blob: bf0484c292c004ec60483e368d5c4cae9ff603de [file] [log] [blame]
Nate Begemaneaa13852004-10-18 21:08:22 +00001//===- LoopStrengthReduce.cpp - Strength Reduce GEPs in Loops -------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Nate Begemaneaa13852004-10-18 21:08:22 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by Nate Begeman and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
Nate Begemaneaa13852004-10-18 21:08:22 +00008//===----------------------------------------------------------------------===//
9//
10// This pass performs a strength reduction on array references inside loops that
11// have as one or more of their components the loop induction variable. This is
12// accomplished by creating a new Value to hold the initial value of the array
13// access for the first iteration, and then creating a new GEP instruction in
14// the loop to increment the value by the appropriate amount.
15//
Nate Begemaneaa13852004-10-18 21:08:22 +000016//===----------------------------------------------------------------------===//
17
Chris Lattnerbe3e5212005-08-03 23:30:08 +000018#define DEBUG_TYPE "loop-reduce"
Nate Begemaneaa13852004-10-18 21:08:22 +000019#include "llvm/Transforms/Scalar.h"
20#include "llvm/Constants.h"
21#include "llvm/Instructions.h"
22#include "llvm/Type.h"
Jeff Cohen2f3c9b72005-03-04 04:04:26 +000023#include "llvm/DerivedTypes.h"
Nate Begemaneaa13852004-10-18 21:08:22 +000024#include "llvm/Analysis/Dominators.h"
25#include "llvm/Analysis/LoopInfo.h"
Devang Patel0f54dcb2007-03-06 21:14:09 +000026#include "llvm/Analysis/LoopPass.h"
Nate Begeman16997482005-07-30 00:15:07 +000027#include "llvm/Analysis/ScalarEvolutionExpander.h"
Nate Begemaneaa13852004-10-18 21:08:22 +000028#include "llvm/Support/CFG.h"
Nate Begeman16997482005-07-30 00:15:07 +000029#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnere0391be2005-08-12 22:06:11 +000030#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Nate Begemaneaa13852004-10-18 21:08:22 +000031#include "llvm/Transforms/Utils/Local.h"
Jeff Cohen2f3c9b72005-03-04 04:04:26 +000032#include "llvm/Target/TargetData.h"
Nate Begemaneaa13852004-10-18 21:08:22 +000033#include "llvm/ADT/Statistic.h"
Nate Begeman16997482005-07-30 00:15:07 +000034#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000035#include "llvm/Support/Compiler.h"
Evan Chengd277f2c2006-03-13 23:14:23 +000036#include "llvm/Target/TargetLowering.h"
Jeff Cohencfb1d422005-07-30 18:22:27 +000037#include <algorithm>
Nate Begemaneaa13852004-10-18 21:08:22 +000038#include <set>
39using namespace llvm;
40
Chris Lattner0e5f4992006-12-19 21:40:18 +000041STATISTIC(NumReduced , "Number of GEPs strength reduced");
42STATISTIC(NumInserted, "Number of PHIs inserted");
43STATISTIC(NumVariable, "Number of PHIs with variable strides");
Nate Begemaneaa13852004-10-18 21:08:22 +000044
Chris Lattner0e5f4992006-12-19 21:40:18 +000045namespace {
Dale Johannesendc42f482007-03-20 00:47:50 +000046
Jeff Cohenc01a5302007-03-20 20:43:18 +000047 struct BasedUser;
Dale Johannesendc42f482007-03-20 00:47:50 +000048
Chris Lattnerec3fb632005-08-03 22:21:05 +000049 /// IVStrideUse - Keep track of one use of a strided induction variable, where
50 /// the stride is stored externally. The Offset member keeps track of the
51 /// offset from the IV, User is the actual user of the operand, and 'Operand'
52 /// is the operand # of the User that is the use.
Reid Spencer9133fe22007-02-05 23:32:05 +000053 struct VISIBILITY_HIDDEN IVStrideUse {
Chris Lattnerec3fb632005-08-03 22:21:05 +000054 SCEVHandle Offset;
55 Instruction *User;
56 Value *OperandValToReplace;
Chris Lattner010de252005-08-08 05:28:22 +000057
58 // isUseOfPostIncrementedValue - True if this should use the
59 // post-incremented version of this IV, not the preincremented version.
60 // This can only be set in special cases, such as the terminating setcc
Chris Lattnerc6bae652005-09-12 06:04:47 +000061 // instruction for a loop or uses dominated by the loop.
Chris Lattner010de252005-08-08 05:28:22 +000062 bool isUseOfPostIncrementedValue;
Chris Lattnerec3fb632005-08-03 22:21:05 +000063
64 IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
Chris Lattner010de252005-08-08 05:28:22 +000065 : Offset(Offs), User(U), OperandValToReplace(O),
66 isUseOfPostIncrementedValue(false) {}
Chris Lattnerec3fb632005-08-03 22:21:05 +000067 };
68
69 /// IVUsersOfOneStride - This structure keeps track of all instructions that
70 /// have an operand that is based on the trip count multiplied by some stride.
71 /// The stride for all of these users is common and kept external to this
72 /// structure.
Reid Spencer9133fe22007-02-05 23:32:05 +000073 struct VISIBILITY_HIDDEN IVUsersOfOneStride {
Nate Begeman16997482005-07-30 00:15:07 +000074 /// Users - Keep track of all of the users of this stride as well as the
Chris Lattnerec3fb632005-08-03 22:21:05 +000075 /// initial value and the operand that uses the IV.
76 std::vector<IVStrideUse> Users;
77
78 void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
79 Users.push_back(IVStrideUse(Offset, User, Operand));
Nate Begeman16997482005-07-30 00:15:07 +000080 }
81 };
82
Evan Chengd1d6b5c2006-03-16 21:53:05 +000083 /// IVInfo - This structure keeps track of one IV expression inserted during
Evan Cheng21495772006-03-18 08:03:12 +000084 /// StrengthReduceStridedIVUsers. It contains the stride, the common base, as
85 /// well as the PHI node and increment value created for rewrite.
Reid Spencer9133fe22007-02-05 23:32:05 +000086 struct VISIBILITY_HIDDEN IVExpr {
Evan Cheng21495772006-03-18 08:03:12 +000087 SCEVHandle Stride;
Evan Chengd1d6b5c2006-03-16 21:53:05 +000088 SCEVHandle Base;
89 PHINode *PHI;
90 Value *IncV;
91
Evan Cheng21495772006-03-18 08:03:12 +000092 IVExpr()
Reid Spencerc5b206b2006-12-31 05:48:39 +000093 : Stride(SCEVUnknown::getIntegerSCEV(0, Type::Int32Ty)),
94 Base (SCEVUnknown::getIntegerSCEV(0, Type::Int32Ty)) {}
Evan Cheng21495772006-03-18 08:03:12 +000095 IVExpr(const SCEVHandle &stride, const SCEVHandle &base, PHINode *phi,
96 Value *incv)
97 : Stride(stride), Base(base), PHI(phi), IncV(incv) {}
Evan Chengd1d6b5c2006-03-16 21:53:05 +000098 };
99
100 /// IVsOfOneStride - This structure keeps track of all IV expression inserted
101 /// during StrengthReduceStridedIVUsers for a particular stride of the IV.
Reid Spencer9133fe22007-02-05 23:32:05 +0000102 struct VISIBILITY_HIDDEN IVsOfOneStride {
Evan Chengd1d6b5c2006-03-16 21:53:05 +0000103 std::vector<IVExpr> IVs;
104
Evan Cheng21495772006-03-18 08:03:12 +0000105 void addIV(const SCEVHandle &Stride, const SCEVHandle &Base, PHINode *PHI,
106 Value *IncV) {
107 IVs.push_back(IVExpr(Stride, Base, PHI, IncV));
Evan Chengd1d6b5c2006-03-16 21:53:05 +0000108 }
109 };
Nate Begeman16997482005-07-30 00:15:07 +0000110
Devang Patel0f54dcb2007-03-06 21:14:09 +0000111 class VISIBILITY_HIDDEN LoopStrengthReduce : public LoopPass {
Nate Begemaneaa13852004-10-18 21:08:22 +0000112 LoopInfo *LI;
Chris Lattner88cac3d2006-01-11 05:10:20 +0000113 ETForest *EF;
Nate Begeman16997482005-07-30 00:15:07 +0000114 ScalarEvolution *SE;
115 const TargetData *TD;
116 const Type *UIntPtrTy;
Nate Begemaneaa13852004-10-18 21:08:22 +0000117 bool Changed;
Chris Lattner7e608bb2005-08-02 02:52:02 +0000118
Nate Begeman16997482005-07-30 00:15:07 +0000119 /// IVUsesByStride - Keep track of all uses of induction variables that we
120 /// are interested in. The key of the map is the stride of the access.
Chris Lattner50fad702005-08-10 00:45:21 +0000121 std::map<SCEVHandle, IVUsersOfOneStride> IVUsesByStride;
Nate Begeman16997482005-07-30 00:15:07 +0000122
Evan Chengd1d6b5c2006-03-16 21:53:05 +0000123 /// IVsByStride - Keep track of all IVs that have been inserted for a
124 /// particular stride.
125 std::map<SCEVHandle, IVsOfOneStride> IVsByStride;
126
Chris Lattner7305ae22005-10-09 06:20:55 +0000127 /// StrideOrder - An ordering of the keys in IVUsesByStride that is stable:
128 /// We use this to iterate over the IVUsesByStride collection without being
129 /// dependent on random ordering of pointers in the process.
130 std::vector<SCEVHandle> StrideOrder;
131
Chris Lattner49f72e62005-08-04 01:19:13 +0000132 /// CastedValues - As we need to cast values to uintptr_t, this keeps track
133 /// of the casted version of each value. This is accessed by
134 /// getCastedVersionOf.
135 std::map<Value*, Value*> CastedPointers;
Nate Begeman16997482005-07-30 00:15:07 +0000136
137 /// DeadInsts - Keep track of instructions we may have made dead, so that
138 /// we can remove them after we are done working.
139 std::set<Instruction*> DeadInsts;
Evan Chengd277f2c2006-03-13 23:14:23 +0000140
141 /// TLI - Keep a pointer of a TargetLowering to consult for determining
142 /// transformation profitability.
143 const TargetLowering *TLI;
144
Nate Begemaneaa13852004-10-18 21:08:22 +0000145 public:
Devang Patel19974732007-05-03 01:11:54 +0000146 static char ID; // Pass ID, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +0000147 LoopStrengthReduce(const TargetLowering *tli = NULL) :
148 LoopPass((intptr_t)&ID), TLI(tli) {
Jeff Cohen2f3c9b72005-03-04 04:04:26 +0000149 }
150
Devang Patel0f54dcb2007-03-06 21:14:09 +0000151 bool runOnLoop(Loop *L, LPPassManager &LPM);
Nate Begemaneaa13852004-10-18 21:08:22 +0000152
153 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattneraa96ae72005-08-17 06:35:16 +0000154 // We split critical edges, so we change the CFG. However, we do update
155 // many analyses if they are around.
156 AU.addPreservedID(LoopSimplifyID);
157 AU.addPreserved<LoopInfo>();
Chris Lattner88cac3d2006-01-11 05:10:20 +0000158 AU.addPreserved<ETForest>();
Chris Lattneraa96ae72005-08-17 06:35:16 +0000159 AU.addPreserved<DominanceFrontier>();
160 AU.addPreserved<DominatorTree>();
161
Jeff Cohenf465db62005-02-27 19:37:07 +0000162 AU.addRequiredID(LoopSimplifyID);
Nate Begemaneaa13852004-10-18 21:08:22 +0000163 AU.addRequired<LoopInfo>();
Chris Lattner88cac3d2006-01-11 05:10:20 +0000164 AU.addRequired<ETForest>();
Jeff Cohen2f3c9b72005-03-04 04:04:26 +0000165 AU.addRequired<TargetData>();
Nate Begeman16997482005-07-30 00:15:07 +0000166 AU.addRequired<ScalarEvolution>();
Nate Begemaneaa13852004-10-18 21:08:22 +0000167 }
Chris Lattner49f72e62005-08-04 01:19:13 +0000168
169 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
170 ///
Reid Spencer3ba68b92006-12-13 08:06:42 +0000171 Value *getCastedVersionOf(Instruction::CastOps opcode, Value *V);
Chris Lattner49f72e62005-08-04 01:19:13 +0000172private:
Chris Lattner3416e5f2005-08-04 17:40:30 +0000173 bool AddUsersIfInteresting(Instruction *I, Loop *L,
174 std::set<Instruction*> &Processed);
175 SCEVHandle GetExpressionSCEV(Instruction *E, Loop *L);
176
Chris Lattner010de252005-08-08 05:28:22 +0000177 void OptimizeIndvars(Loop *L);
Chris Lattneraed01d12007-04-03 05:11:24 +0000178 bool FindIVForUser(ICmpInst *Cond, IVStrideUse *&CondUse,
179 const SCEVHandle *&CondStride);
Nate Begeman16997482005-07-30 00:15:07 +0000180
Dale Johannesendc42f482007-03-20 00:47:50 +0000181 unsigned CheckForIVReuse(const SCEVHandle&, IVExpr&, const Type*,
182 const std::vector<BasedUser>& UsersToProcess);
183
184 bool ValidStride(int64_t, const std::vector<BasedUser>& UsersToProcess);
Evan Chengeb8f9e22006-03-17 19:52:23 +0000185
Chris Lattner50fad702005-08-10 00:45:21 +0000186 void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
187 IVUsersOfOneStride &Uses,
Chris Lattnerec3fb632005-08-03 22:21:05 +0000188 Loop *L, bool isOnlyStride);
Nate Begemaneaa13852004-10-18 21:08:22 +0000189 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
190 };
Devang Patel19974732007-05-03 01:11:54 +0000191 char LoopStrengthReduce::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +0000192 RegisterPass<LoopStrengthReduce> X("loop-reduce", "Loop Strength Reduction");
Nate Begemaneaa13852004-10-18 21:08:22 +0000193}
194
Devang Patel0f54dcb2007-03-06 21:14:09 +0000195LoopPass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
Evan Chengd1d6b5c2006-03-16 21:53:05 +0000196 return new LoopStrengthReduce(TLI);
Nate Begemaneaa13852004-10-18 21:08:22 +0000197}
198
Reid Spencer4da49122006-12-12 05:05:00 +0000199/// getCastedVersionOf - Return the specified value casted to uintptr_t. This
200/// assumes that the Value* V is of integer or pointer type only.
Chris Lattner49f72e62005-08-04 01:19:13 +0000201///
Reid Spencer3ba68b92006-12-13 08:06:42 +0000202Value *LoopStrengthReduce::getCastedVersionOf(Instruction::CastOps opcode,
203 Value *V) {
Chris Lattner49f72e62005-08-04 01:19:13 +0000204 if (V->getType() == UIntPtrTy) return V;
205 if (Constant *CB = dyn_cast<Constant>(V))
Reid Spencer3ba68b92006-12-13 08:06:42 +0000206 return ConstantExpr::getCast(opcode, CB, UIntPtrTy);
Chris Lattner49f72e62005-08-04 01:19:13 +0000207
208 Value *&New = CastedPointers[V];
209 if (New) return New;
210
Reid Spencer3ba68b92006-12-13 08:06:42 +0000211 New = SCEVExpander::InsertCastOfTo(opcode, V, UIntPtrTy);
Chris Lattner7db543f2005-08-04 19:08:16 +0000212 DeadInsts.insert(cast<Instruction>(New));
213 return New;
Chris Lattner49f72e62005-08-04 01:19:13 +0000214}
215
216
Nate Begemaneaa13852004-10-18 21:08:22 +0000217/// DeleteTriviallyDeadInstructions - If any of the instructions is the
218/// specified set are trivially dead, delete them and see if this makes any of
219/// their operands subsequently dead.
220void LoopStrengthReduce::
221DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
222 while (!Insts.empty()) {
223 Instruction *I = *Insts.begin();
224 Insts.erase(Insts.begin());
225 if (isInstructionTriviallyDead(I)) {
Jeff Cohen0456e4a2005-03-01 03:46:11 +0000226 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
227 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
228 Insts.insert(U);
Chris Lattner52d83e62005-08-03 21:36:09 +0000229 SE->deleteInstructionFromRecords(I);
230 I->eraseFromParent();
Nate Begemaneaa13852004-10-18 21:08:22 +0000231 Changed = true;
232 }
233 }
234}
235
Jeff Cohenf465db62005-02-27 19:37:07 +0000236
Chris Lattner3416e5f2005-08-04 17:40:30 +0000237/// GetExpressionSCEV - Compute and return the SCEV for the specified
238/// instruction.
239SCEVHandle LoopStrengthReduce::GetExpressionSCEV(Instruction *Exp, Loop *L) {
Dale Johannesenda91f492007-03-26 03:01:27 +0000240 // Pointer to pointer bitcast instructions return the same value as their
241 // operand.
242 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Exp)) {
243 if (SE->hasSCEV(BCI) || !isa<Instruction>(BCI->getOperand(0)))
244 return SE->getSCEV(BCI);
245 SCEVHandle R = GetExpressionSCEV(cast<Instruction>(BCI->getOperand(0)), L);
246 SE->setSCEV(BCI, R);
247 return R;
248 }
249
Chris Lattner87265ab2005-08-09 23:39:36 +0000250 // Scalar Evolutions doesn't know how to compute SCEV's for GEP instructions.
251 // If this is a GEP that SE doesn't know about, compute it now and insert it.
252 // If this is not a GEP, or if we have already done this computation, just let
253 // SE figure it out.
Chris Lattner3416e5f2005-08-04 17:40:30 +0000254 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
Chris Lattner87265ab2005-08-09 23:39:36 +0000255 if (!GEP || SE->hasSCEV(GEP))
Chris Lattner3416e5f2005-08-04 17:40:30 +0000256 return SE->getSCEV(Exp);
257
Nate Begeman16997482005-07-30 00:15:07 +0000258 // Analyze all of the subscripts of this getelementptr instruction, looking
259 // for uses that are determined by the trip count of L. First, skip all
260 // operands the are not dependent on the IV.
261
262 // Build up the base expression. Insert an LLVM cast of the pointer to
263 // uintptr_t first.
Reid Spencer3ba68b92006-12-13 08:06:42 +0000264 SCEVHandle GEPVal = SCEVUnknown::get(
265 getCastedVersionOf(Instruction::PtrToInt, GEP->getOperand(0)));
Nate Begeman16997482005-07-30 00:15:07 +0000266
267 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattner3416e5f2005-08-04 17:40:30 +0000268
269 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
Nate Begeman16997482005-07-30 00:15:07 +0000270 // If this is a use of a recurrence that we can analyze, and it comes before
271 // Op does in the GEP operand list, we will handle this when we process this
272 // operand.
273 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
274 const StructLayout *SL = TD->getStructLayout(STy);
Reid Spencerb83eb642006-10-20 07:07:24 +0000275 unsigned Idx = cast<ConstantInt>(GEP->getOperand(i))->getZExtValue();
Chris Lattnerb1919e22007-02-10 19:55:17 +0000276 uint64_t Offset = SL->getElementOffset(Idx);
Chris Lattner3416e5f2005-08-04 17:40:30 +0000277 GEPVal = SCEVAddExpr::get(GEPVal,
278 SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy));
Nate Begeman16997482005-07-30 00:15:07 +0000279 } else {
Reid Spencer3ba68b92006-12-13 08:06:42 +0000280 unsigned GEPOpiBits =
281 GEP->getOperand(i)->getType()->getPrimitiveSizeInBits();
282 unsigned IntPtrBits = UIntPtrTy->getPrimitiveSizeInBits();
283 Instruction::CastOps opcode = (GEPOpiBits < IntPtrBits ?
284 Instruction::SExt : (GEPOpiBits > IntPtrBits ? Instruction::Trunc :
285 Instruction::BitCast));
286 Value *OpVal = getCastedVersionOf(opcode, GEP->getOperand(i));
Chris Lattner7db543f2005-08-04 19:08:16 +0000287 SCEVHandle Idx = SE->getSCEV(OpVal);
288
Chris Lattner3416e5f2005-08-04 17:40:30 +0000289 uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
290 if (TypeSize != 1)
291 Idx = SCEVMulExpr::get(Idx,
Reid Spencerb83eb642006-10-20 07:07:24 +0000292 SCEVConstant::get(ConstantInt::get(UIntPtrTy,
Chris Lattner3416e5f2005-08-04 17:40:30 +0000293 TypeSize)));
294 GEPVal = SCEVAddExpr::get(GEPVal, Idx);
Nate Begeman16997482005-07-30 00:15:07 +0000295 }
296 }
297
Chris Lattner87265ab2005-08-09 23:39:36 +0000298 SE->setSCEV(GEP, GEPVal);
Chris Lattner3416e5f2005-08-04 17:40:30 +0000299 return GEPVal;
Nate Begeman16997482005-07-30 00:15:07 +0000300}
301
Chris Lattner7db543f2005-08-04 19:08:16 +0000302/// getSCEVStartAndStride - Compute the start and stride of this expression,
303/// returning false if the expression is not a start/stride pair, or true if it
304/// is. The stride must be a loop invariant expression, but the start may be
305/// a mix of loop invariant and loop variant expressions.
306static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
Chris Lattner50fad702005-08-10 00:45:21 +0000307 SCEVHandle &Start, SCEVHandle &Stride) {
Chris Lattner7db543f2005-08-04 19:08:16 +0000308 SCEVHandle TheAddRec = Start; // Initialize to zero.
309
310 // If the outer level is an AddExpr, the operands are all start values except
311 // for a nested AddRecExpr.
312 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
313 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
314 if (SCEVAddRecExpr *AddRec =
315 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
316 if (AddRec->getLoop() == L)
317 TheAddRec = SCEVAddExpr::get(AddRec, TheAddRec);
318 else
319 return false; // Nested IV of some sort?
320 } else {
321 Start = SCEVAddExpr::get(Start, AE->getOperand(i));
322 }
323
Reid Spencer3ed469c2006-11-02 20:25:50 +0000324 } else if (isa<SCEVAddRecExpr>(SH)) {
Chris Lattner7db543f2005-08-04 19:08:16 +0000325 TheAddRec = SH;
326 } else {
327 return false; // not analyzable.
328 }
329
330 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
331 if (!AddRec || AddRec->getLoop() != L) return false;
332
333 // FIXME: Generalize to non-affine IV's.
334 if (!AddRec->isAffine()) return false;
335
336 Start = SCEVAddExpr::get(Start, AddRec->getOperand(0));
337
Chris Lattner7db543f2005-08-04 19:08:16 +0000338 if (!isa<SCEVConstant>(AddRec->getOperand(1)))
Bill Wendlingb7427032006-11-26 09:46:52 +0000339 DOUT << "[" << L->getHeader()->getName()
340 << "] Variable stride: " << *AddRec << "\n";
Chris Lattner7db543f2005-08-04 19:08:16 +0000341
Chris Lattner50fad702005-08-10 00:45:21 +0000342 Stride = AddRec->getOperand(1);
Chris Lattner7db543f2005-08-04 19:08:16 +0000343 return true;
344}
345
Chris Lattner0ae33eb2005-10-03 01:04:44 +0000346/// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
347/// and now we need to decide whether the user should use the preinc or post-inc
348/// value. If this user should use the post-inc version of the IV, return true.
349///
350/// Choosing wrong here can break dominance properties (if we choose to use the
351/// post-inc value when we cannot) or it can end up adding extra live-ranges to
352/// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
353/// should use the post-inc value).
354static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
Chris Lattner88cac3d2006-01-11 05:10:20 +0000355 Loop *L, ETForest *EF, Pass *P) {
Chris Lattner0ae33eb2005-10-03 01:04:44 +0000356 // If the user is in the loop, use the preinc value.
357 if (L->contains(User->getParent())) return false;
358
Chris Lattner5e8ca662005-10-03 02:50:05 +0000359 BasicBlock *LatchBlock = L->getLoopLatch();
360
361 // Ok, the user is outside of the loop. If it is dominated by the latch
362 // block, use the post-inc value.
Chris Lattner88cac3d2006-01-11 05:10:20 +0000363 if (EF->dominates(LatchBlock, User->getParent()))
Chris Lattner5e8ca662005-10-03 02:50:05 +0000364 return true;
365
366 // There is one case we have to be careful of: PHI nodes. These little guys
367 // can live in blocks that do not dominate the latch block, but (since their
368 // uses occur in the predecessor block, not the block the PHI lives in) should
369 // still use the post-inc value. Check for this case now.
370 PHINode *PN = dyn_cast<PHINode>(User);
371 if (!PN) return false; // not a phi, not dominated by latch block.
372
373 // Look at all of the uses of IV by the PHI node. If any use corresponds to
374 // a block that is not dominated by the latch block, give up and use the
375 // preincremented value.
376 unsigned NumUses = 0;
377 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
378 if (PN->getIncomingValue(i) == IV) {
379 ++NumUses;
Chris Lattner88cac3d2006-01-11 05:10:20 +0000380 if (!EF->dominates(LatchBlock, PN->getIncomingBlock(i)))
Chris Lattner5e8ca662005-10-03 02:50:05 +0000381 return false;
382 }
383
384 // Okay, all uses of IV by PN are in predecessor blocks that really are
385 // dominated by the latch block. Split the critical edges and use the
386 // post-incremented value.
387 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
388 if (PN->getIncomingValue(i) == IV) {
Chris Lattner0997fad2006-10-28 06:45:33 +0000389 SplitCriticalEdge(PN->getIncomingBlock(i), PN->getParent(), P,
390 true);
Chris Lattner1b9c8e72006-10-28 00:59:20 +0000391 // Splitting the critical edge can reduce the number of entries in this
392 // PHI.
393 e = PN->getNumIncomingValues();
Chris Lattner5e8ca662005-10-03 02:50:05 +0000394 if (--NumUses == 0) break;
395 }
396
397 return true;
Chris Lattner0ae33eb2005-10-03 01:04:44 +0000398}
399
400
401
Nate Begeman16997482005-07-30 00:15:07 +0000402/// AddUsersIfInteresting - Inspect the specified instruction. If it is a
403/// reducible SCEV, recursively add its users to the IVUsesByStride set and
404/// return true. Otherwise, return false.
Chris Lattner3416e5f2005-08-04 17:40:30 +0000405bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
406 std::set<Instruction*> &Processed) {
Chris Lattner42a75512007-01-15 02:27:26 +0000407 if (!I->getType()->isInteger() && !isa<PointerType>(I->getType()))
Chris Lattner63ad7962005-10-21 05:45:41 +0000408 return false; // Void and FP expressions cannot be reduced.
Chris Lattner3416e5f2005-08-04 17:40:30 +0000409 if (!Processed.insert(I).second)
410 return true; // Instruction already handled.
411
Chris Lattner7db543f2005-08-04 19:08:16 +0000412 // Get the symbolic expression for this instruction.
Chris Lattner3416e5f2005-08-04 17:40:30 +0000413 SCEVHandle ISE = GetExpressionSCEV(I, L);
Chris Lattner7db543f2005-08-04 19:08:16 +0000414 if (isa<SCEVCouldNotCompute>(ISE)) return false;
Chris Lattner3416e5f2005-08-04 17:40:30 +0000415
Chris Lattner7db543f2005-08-04 19:08:16 +0000416 // Get the start and stride for this expression.
417 SCEVHandle Start = SCEVUnknown::getIntegerSCEV(0, ISE->getType());
Chris Lattner50fad702005-08-10 00:45:21 +0000418 SCEVHandle Stride = Start;
Chris Lattner7db543f2005-08-04 19:08:16 +0000419 if (!getSCEVStartAndStride(ISE, L, Start, Stride))
420 return false; // Non-reducible symbolic expression, bail out.
Devang Patel4fe26582007-03-09 21:19:53 +0000421
Devang Patel2a5fa182007-04-23 22:42:03 +0000422 std::vector<Instruction *> IUsers;
423 // Collect all I uses now because IVUseShouldUsePostIncValue may
424 // invalidate use_iterator.
425 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
426 IUsers.push_back(cast<Instruction>(*UI));
Nate Begeman16997482005-07-30 00:15:07 +0000427
Devang Patel2a5fa182007-04-23 22:42:03 +0000428 for (unsigned iused_index = 0, iused_size = IUsers.size();
429 iused_index != iused_size; ++iused_index) {
430
431 Instruction *User = IUsers[iused_index];
Devang Patel4fe26582007-03-09 21:19:53 +0000432
Nate Begeman16997482005-07-30 00:15:07 +0000433 // Do not infinitely recurse on PHI nodes.
Chris Lattner396b2ba2005-09-13 02:09:55 +0000434 if (isa<PHINode>(User) && Processed.count(User))
Nate Begeman16997482005-07-30 00:15:07 +0000435 continue;
436
437 // If this is an instruction defined in a nested loop, or outside this loop,
Chris Lattnerf9186592005-08-04 00:14:11 +0000438 // don't recurse into it.
Chris Lattner7db543f2005-08-04 19:08:16 +0000439 bool AddUserToIVUsers = false;
Chris Lattnerf9186592005-08-04 00:14:11 +0000440 if (LI->getLoopFor(User->getParent()) != L) {
Bill Wendlingb7427032006-11-26 09:46:52 +0000441 DOUT << "FOUND USER in other loop: " << *User
442 << " OF SCEV: " << *ISE << "\n";
Chris Lattner7db543f2005-08-04 19:08:16 +0000443 AddUserToIVUsers = true;
Chris Lattner3416e5f2005-08-04 17:40:30 +0000444 } else if (!AddUsersIfInteresting(User, L, Processed)) {
Bill Wendlingb7427032006-11-26 09:46:52 +0000445 DOUT << "FOUND USER: " << *User
446 << " OF SCEV: " << *ISE << "\n";
Chris Lattner7db543f2005-08-04 19:08:16 +0000447 AddUserToIVUsers = true;
448 }
Nate Begeman16997482005-07-30 00:15:07 +0000449
Chris Lattner7db543f2005-08-04 19:08:16 +0000450 if (AddUserToIVUsers) {
Chris Lattner7305ae22005-10-09 06:20:55 +0000451 IVUsersOfOneStride &StrideUses = IVUsesByStride[Stride];
452 if (StrideUses.Users.empty()) // First occurance of this stride?
453 StrideOrder.push_back(Stride);
454
Chris Lattnera4479ad2005-08-04 00:40:47 +0000455 // Okay, we found a user that we cannot reduce. Analyze the instruction
Chris Lattnerc6bae652005-09-12 06:04:47 +0000456 // and decide what to do with it. If we are a use inside of the loop, use
457 // the value before incrementation, otherwise use it after incrementation.
Chris Lattner88cac3d2006-01-11 05:10:20 +0000458 if (IVUseShouldUsePostIncValue(User, I, L, EF, this)) {
Chris Lattnerc6bae652005-09-12 06:04:47 +0000459 // The value used will be incremented by the stride more than we are
460 // expecting, so subtract this off.
461 SCEVHandle NewStart = SCEV::getMinusSCEV(Start, Stride);
Chris Lattner7305ae22005-10-09 06:20:55 +0000462 StrideUses.addUser(NewStart, User, I);
463 StrideUses.Users.back().isUseOfPostIncrementedValue = true;
Bill Wendlingb7427032006-11-26 09:46:52 +0000464 DOUT << " USING POSTINC SCEV, START=" << *NewStart<< "\n";
Chris Lattner0ae33eb2005-10-03 01:04:44 +0000465 } else {
Chris Lattner7305ae22005-10-09 06:20:55 +0000466 StrideUses.addUser(Start, User, I);
Chris Lattnerc6bae652005-09-12 06:04:47 +0000467 }
Nate Begeman16997482005-07-30 00:15:07 +0000468 }
469 }
470 return true;
471}
472
473namespace {
474 /// BasedUser - For a particular base value, keep information about how we've
475 /// partitioned the expression so far.
476 struct BasedUser {
Chris Lattnera553b0c2005-08-08 22:56:21 +0000477 /// Base - The Base value for the PHI node that needs to be inserted for
478 /// this use. As the use is processed, information gets moved from this
479 /// field to the Imm field (below). BasedUser values are sorted by this
480 /// field.
481 SCEVHandle Base;
482
Nate Begeman16997482005-07-30 00:15:07 +0000483 /// Inst - The instruction using the induction variable.
484 Instruction *Inst;
485
Chris Lattnerec3fb632005-08-03 22:21:05 +0000486 /// OperandValToReplace - The operand value of Inst to replace with the
487 /// EmittedBase.
488 Value *OperandValToReplace;
Nate Begeman16997482005-07-30 00:15:07 +0000489
490 /// Imm - The immediate value that should be added to the base immediately
491 /// before Inst, because it will be folded into the imm field of the
492 /// instruction.
493 SCEVHandle Imm;
494
495 /// EmittedBase - The actual value* to use for the base value of this
496 /// operation. This is null if we should just use zero so far.
497 Value *EmittedBase;
498
Chris Lattner010de252005-08-08 05:28:22 +0000499 // isUseOfPostIncrementedValue - True if this should use the
500 // post-incremented version of this IV, not the preincremented version.
501 // This can only be set in special cases, such as the terminating setcc
Chris Lattnerc6bae652005-09-12 06:04:47 +0000502 // instruction for a loop and uses outside the loop that are dominated by
503 // the loop.
Chris Lattner010de252005-08-08 05:28:22 +0000504 bool isUseOfPostIncrementedValue;
Chris Lattnera553b0c2005-08-08 22:56:21 +0000505
506 BasedUser(IVStrideUse &IVSU)
507 : Base(IVSU.Offset), Inst(IVSU.User),
508 OperandValToReplace(IVSU.OperandValToReplace),
509 Imm(SCEVUnknown::getIntegerSCEV(0, Base->getType())), EmittedBase(0),
510 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
Nate Begeman16997482005-07-30 00:15:07 +0000511
Chris Lattner2114b272005-08-04 20:03:32 +0000512 // Once we rewrite the code to insert the new IVs we want, update the
513 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
514 // to it.
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000515 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattnerc60fb082005-08-12 22:22:17 +0000516 SCEVExpander &Rewriter, Loop *L,
517 Pass *P);
Chris Lattner221fc3c2006-02-04 07:36:50 +0000518
519 Value *InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
520 SCEVExpander &Rewriter,
521 Instruction *IP, Loop *L);
Nate Begeman16997482005-07-30 00:15:07 +0000522 void dump() const;
523 };
524}
525
526void BasedUser::dump() const {
Bill Wendlinge8156192006-12-07 01:30:32 +0000527 cerr << " Base=" << *Base;
528 cerr << " Imm=" << *Imm;
Nate Begeman16997482005-07-30 00:15:07 +0000529 if (EmittedBase)
Bill Wendlinge8156192006-12-07 01:30:32 +0000530 cerr << " EB=" << *EmittedBase;
Nate Begeman16997482005-07-30 00:15:07 +0000531
Bill Wendlinge8156192006-12-07 01:30:32 +0000532 cerr << " Inst: " << *Inst;
Nate Begeman16997482005-07-30 00:15:07 +0000533}
534
Chris Lattner221fc3c2006-02-04 07:36:50 +0000535Value *BasedUser::InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
536 SCEVExpander &Rewriter,
537 Instruction *IP, Loop *L) {
538 // Figure out where we *really* want to insert this code. In particular, if
539 // the user is inside of a loop that is nested inside of L, we really don't
540 // want to insert this expression before the user, we'd rather pull it out as
541 // many loops as possible.
542 LoopInfo &LI = Rewriter.getLoopInfo();
543 Instruction *BaseInsertPt = IP;
544
545 // Figure out the most-nested loop that IP is in.
546 Loop *InsertLoop = LI.getLoopFor(IP->getParent());
547
548 // If InsertLoop is not L, and InsertLoop is nested inside of L, figure out
549 // the preheader of the outer-most loop where NewBase is not loop invariant.
550 while (InsertLoop && NewBase->isLoopInvariant(InsertLoop)) {
551 BaseInsertPt = InsertLoop->getLoopPreheader()->getTerminator();
552 InsertLoop = InsertLoop->getParentLoop();
553 }
554
555 // If there is no immediate value, skip the next part.
556 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Imm))
Reid Spencerbee0f662007-03-02 23:51:25 +0000557 if (SC->getValue()->isZero())
Chris Lattner221fc3c2006-02-04 07:36:50 +0000558 return Rewriter.expandCodeFor(NewBase, BaseInsertPt,
559 OperandValToReplace->getType());
560
561 Value *Base = Rewriter.expandCodeFor(NewBase, BaseInsertPt);
562
563 // Always emit the immediate (if non-zero) into the same block as the user.
564 SCEVHandle NewValSCEV = SCEVAddExpr::get(SCEVUnknown::get(Base), Imm);
565 return Rewriter.expandCodeFor(NewValSCEV, IP,
566 OperandValToReplace->getType());
567}
568
569
Chris Lattner2114b272005-08-04 20:03:32 +0000570// Once we rewrite the code to insert the new IVs we want, update the
571// operands of Inst to use the new expression 'NewBase', with 'Imm' added
572// to it.
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000573void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattnere0391be2005-08-12 22:06:11 +0000574 SCEVExpander &Rewriter,
Chris Lattnerc60fb082005-08-12 22:22:17 +0000575 Loop *L, Pass *P) {
Chris Lattner2114b272005-08-04 20:03:32 +0000576 if (!isa<PHINode>(Inst)) {
Chris Lattnerc5494af2007-04-13 20:42:26 +0000577 // By default, insert code at the user instruction.
578 BasicBlock::iterator InsertPt = Inst;
579
580 // However, if the Operand is itself an instruction, the (potentially
581 // complex) inserted code may be shared by many users. Because of this, we
582 // want to emit code for the computation of the operand right before its old
583 // computation. This is usually safe, because we obviously used to use the
584 // computation when it was computed in its current block. However, in some
585 // cases (e.g. use of a post-incremented induction variable) the NewBase
586 // value will be pinned to live somewhere after the original computation.
587 // In this case, we have to back off.
588 if (!isUseOfPostIncrementedValue) {
589 if (Instruction *OpInst = dyn_cast<Instruction>(OperandValToReplace)) {
590 InsertPt = OpInst;
591 while (isa<PHINode>(InsertPt)) ++InsertPt;
592 }
593 }
594
595 Value *NewVal = InsertCodeForBaseAtPosition(NewBase, Rewriter, InsertPt, L);
Chris Lattner2114b272005-08-04 20:03:32 +0000596 // Replace the use of the operand Value with the new Phi we just created.
597 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
Bill Wendlingb7427032006-11-26 09:46:52 +0000598 DOUT << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst;
Chris Lattner2114b272005-08-04 20:03:32 +0000599 return;
600 }
601
602 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
Chris Lattnerc41e3452005-08-10 00:35:32 +0000603 // expression into each operand block that uses it. Note that PHI nodes can
604 // have multiple entries for the same predecessor. We use a map to make sure
605 // that a PHI node only has a single Value* for each predecessor (which also
606 // prevents us from inserting duplicate code in some blocks).
607 std::map<BasicBlock*, Value*> InsertedCode;
Chris Lattner2114b272005-08-04 20:03:32 +0000608 PHINode *PN = cast<PHINode>(Inst);
609 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
610 if (PN->getIncomingValue(i) == OperandValToReplace) {
Chris Lattnere0391be2005-08-12 22:06:11 +0000611 // If this is a critical edge, split the edge so that we do not insert the
Chris Lattner396b2ba2005-09-13 02:09:55 +0000612 // code on all predecessor/successor paths. We do this unless this is the
613 // canonical backedge for this loop, as this can make some inserted code
614 // be in an illegal position.
Chris Lattner37edbf02005-10-03 00:31:52 +0000615 BasicBlock *PHIPred = PN->getIncomingBlock(i);
616 if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
617 (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
Chris Lattner37edbf02005-10-03 00:31:52 +0000618
Chris Lattneraa96ae72005-08-17 06:35:16 +0000619 // First step, split the critical edge.
Chris Lattner0997fad2006-10-28 06:45:33 +0000620 SplitCriticalEdge(PHIPred, PN->getParent(), P, true);
Chris Lattnerc60fb082005-08-12 22:22:17 +0000621
Chris Lattneraa96ae72005-08-17 06:35:16 +0000622 // Next step: move the basic block. In particular, if the PHI node
623 // is outside of the loop, and PredTI is in the loop, we want to
624 // move the block to be immediately before the PHI block, not
625 // immediately after PredTI.
Chris Lattner37edbf02005-10-03 00:31:52 +0000626 if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
Chris Lattneraa96ae72005-08-17 06:35:16 +0000627 BasicBlock *NewBB = PN->getIncomingBlock(i);
628 NewBB->moveBefore(PN->getParent());
Chris Lattnere0391be2005-08-12 22:06:11 +0000629 }
Chris Lattner1b9c8e72006-10-28 00:59:20 +0000630
631 // Splitting the edge can reduce the number of PHI entries we have.
632 e = PN->getNumIncomingValues();
Chris Lattnere0391be2005-08-12 22:06:11 +0000633 }
Chris Lattner2114b272005-08-04 20:03:32 +0000634
Chris Lattnerc41e3452005-08-10 00:35:32 +0000635 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
636 if (!Code) {
637 // Insert the code into the end of the predecessor block.
Chris Lattner221fc3c2006-02-04 07:36:50 +0000638 Instruction *InsertPt = PN->getIncomingBlock(i)->getTerminator();
639 Code = InsertCodeForBaseAtPosition(NewBase, Rewriter, InsertPt, L);
Chris Lattnerc41e3452005-08-10 00:35:32 +0000640 }
Chris Lattner2114b272005-08-04 20:03:32 +0000641
642 // Replace the use of the operand Value with the new Phi we just created.
Chris Lattnerc41e3452005-08-10 00:35:32 +0000643 PN->setIncomingValue(i, Code);
Chris Lattner2114b272005-08-04 20:03:32 +0000644 Rewriter.clear();
645 }
646 }
Bill Wendlingb7427032006-11-26 09:46:52 +0000647 DOUT << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst;
Chris Lattner2114b272005-08-04 20:03:32 +0000648}
649
650
Nate Begeman16997482005-07-30 00:15:07 +0000651/// isTargetConstant - Return true if the following can be referenced by the
652/// immediate field of a target instruction.
Evan Cheng1d958162007-03-13 20:34:37 +0000653static bool isTargetConstant(const SCEVHandle &V, const Type *UseTy,
654 const TargetLowering *TLI) {
Chris Lattner3821e472005-08-08 06:25:50 +0000655 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
Evan Cheng5eef2d22007-03-12 23:27:37 +0000656 int64_t VC = SC->getValue()->getSExtValue();
Chris Lattner579633c2007-04-09 22:20:14 +0000657 if (TLI) {
658 TargetLowering::AddrMode AM;
659 AM.BaseOffs = VC;
660 return TLI->isLegalAddressingMode(AM, UseTy);
661 } else {
Evan Chengd277f2c2006-03-13 23:14:23 +0000662 // Defaults to PPC. PPC allows a sign-extended 16-bit immediate field.
Evan Cheng5eef2d22007-03-12 23:27:37 +0000663 return (VC > -(1 << 16) && VC < (1 << 16)-1);
Chris Lattner579633c2007-04-09 22:20:14 +0000664 }
Chris Lattner3821e472005-08-08 06:25:50 +0000665 }
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000666
Nate Begeman16997482005-07-30 00:15:07 +0000667 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
668 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
Chris Lattner579633c2007-04-09 22:20:14 +0000669 if (TLI && CE->getOpcode() == Instruction::PtrToInt) {
Evan Chengd277f2c2006-03-13 23:14:23 +0000670 Constant *Op0 = CE->getOperand(0);
Chris Lattner579633c2007-04-09 22:20:14 +0000671 if (GlobalValue *GV = dyn_cast<GlobalValue>(Op0)) {
672 TargetLowering::AddrMode AM;
673 AM.BaseGV = GV;
674 return TLI->isLegalAddressingMode(AM, UseTy);
675 }
Evan Chengd277f2c2006-03-13 23:14:23 +0000676 }
Nate Begeman16997482005-07-30 00:15:07 +0000677 return false;
678}
679
Chris Lattner44b807e2005-08-08 22:32:34 +0000680/// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
681/// loop varying to the Imm operand.
682static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
683 Loop *L) {
684 if (Val->isLoopInvariant(L)) return; // Nothing to do.
685
686 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
687 std::vector<SCEVHandle> NewOps;
688 NewOps.reserve(SAE->getNumOperands());
689
690 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
691 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
692 // If this is a loop-variant expression, it must stay in the immediate
693 // field of the expression.
694 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
695 } else {
696 NewOps.push_back(SAE->getOperand(i));
697 }
698
699 if (NewOps.empty())
700 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
701 else
702 Val = SCEVAddExpr::get(NewOps);
703 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
704 // Try to pull immediates out of the start value of nested addrec's.
705 SCEVHandle Start = SARE->getStart();
706 MoveLoopVariantsToImediateField(Start, Imm, L);
707
708 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
709 Ops[0] = Start;
710 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
711 } else {
712 // Otherwise, all of Val is variant, move the whole thing over.
713 Imm = SCEVAddExpr::get(Imm, Val);
714 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
715 }
716}
717
718
Chris Lattner26d91f12005-08-04 22:34:05 +0000719/// MoveImmediateValues - Look at Val, and pull out any additions of constants
Nate Begeman16997482005-07-30 00:15:07 +0000720/// that can fit into the immediate field of instructions in the target.
Chris Lattner26d91f12005-08-04 22:34:05 +0000721/// Accumulate these immediate values into the Imm value.
Evan Chengd277f2c2006-03-13 23:14:23 +0000722static void MoveImmediateValues(const TargetLowering *TLI,
Evan Cheng1d958162007-03-13 20:34:37 +0000723 Instruction *User,
Evan Chengd277f2c2006-03-13 23:14:23 +0000724 SCEVHandle &Val, SCEVHandle &Imm,
Chris Lattner26d91f12005-08-04 22:34:05 +0000725 bool isAddress, Loop *L) {
Evan Cheng1d958162007-03-13 20:34:37 +0000726 const Type *UseTy = User->getType();
727 if (StoreInst *SI = dyn_cast<StoreInst>(User))
728 UseTy = SI->getOperand(0)->getType();
729
Chris Lattner7a658392005-08-03 23:44:42 +0000730 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
Chris Lattner26d91f12005-08-04 22:34:05 +0000731 std::vector<SCEVHandle> NewOps;
732 NewOps.reserve(SAE->getNumOperands());
733
Chris Lattner221fc3c2006-02-04 07:36:50 +0000734 for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
735 SCEVHandle NewOp = SAE->getOperand(i);
Evan Cheng1d958162007-03-13 20:34:37 +0000736 MoveImmediateValues(TLI, User, NewOp, Imm, isAddress, L);
Chris Lattner221fc3c2006-02-04 07:36:50 +0000737
738 if (!NewOp->isLoopInvariant(L)) {
Chris Lattner7db543f2005-08-04 19:08:16 +0000739 // If this is a loop-variant expression, it must stay in the immediate
740 // field of the expression.
Chris Lattner221fc3c2006-02-04 07:36:50 +0000741 Imm = SCEVAddExpr::get(Imm, NewOp);
Chris Lattner26d91f12005-08-04 22:34:05 +0000742 } else {
Chris Lattner221fc3c2006-02-04 07:36:50 +0000743 NewOps.push_back(NewOp);
Nate Begeman16997482005-07-30 00:15:07 +0000744 }
Chris Lattner221fc3c2006-02-04 07:36:50 +0000745 }
Chris Lattner26d91f12005-08-04 22:34:05 +0000746
747 if (NewOps.empty())
748 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
749 else
750 Val = SCEVAddExpr::get(NewOps);
751 return;
Chris Lattner7a658392005-08-03 23:44:42 +0000752 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
753 // Try to pull immediates out of the start value of nested addrec's.
Chris Lattner26d91f12005-08-04 22:34:05 +0000754 SCEVHandle Start = SARE->getStart();
Evan Cheng1d958162007-03-13 20:34:37 +0000755 MoveImmediateValues(TLI, User, Start, Imm, isAddress, L);
Chris Lattner26d91f12005-08-04 22:34:05 +0000756
757 if (Start != SARE->getStart()) {
758 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
759 Ops[0] = Start;
760 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
761 }
762 return;
Chris Lattner221fc3c2006-02-04 07:36:50 +0000763 } else if (SCEVMulExpr *SME = dyn_cast<SCEVMulExpr>(Val)) {
764 // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
Evan Cheng1d958162007-03-13 20:34:37 +0000765 if (isAddress && isTargetConstant(SME->getOperand(0), UseTy, TLI) &&
Chris Lattner221fc3c2006-02-04 07:36:50 +0000766 SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
767
768 SCEVHandle SubImm = SCEVUnknown::getIntegerSCEV(0, Val->getType());
769 SCEVHandle NewOp = SME->getOperand(1);
Evan Cheng1d958162007-03-13 20:34:37 +0000770 MoveImmediateValues(TLI, User, NewOp, SubImm, isAddress, L);
Chris Lattner221fc3c2006-02-04 07:36:50 +0000771
772 // If we extracted something out of the subexpressions, see if we can
773 // simplify this!
774 if (NewOp != SME->getOperand(1)) {
775 // Scale SubImm up by "8". If the result is a target constant, we are
776 // good.
777 SubImm = SCEVMulExpr::get(SubImm, SME->getOperand(0));
Evan Cheng1d958162007-03-13 20:34:37 +0000778 if (isTargetConstant(SubImm, UseTy, TLI)) {
Chris Lattner221fc3c2006-02-04 07:36:50 +0000779 // Accumulate the immediate.
780 Imm = SCEVAddExpr::get(Imm, SubImm);
781
782 // Update what is left of 'Val'.
783 Val = SCEVMulExpr::get(SME->getOperand(0), NewOp);
784 return;
785 }
786 }
787 }
Nate Begeman16997482005-07-30 00:15:07 +0000788 }
789
Chris Lattner26d91f12005-08-04 22:34:05 +0000790 // Loop-variant expressions must stay in the immediate field of the
791 // expression.
Evan Cheng1d958162007-03-13 20:34:37 +0000792 if ((isAddress && isTargetConstant(Val, UseTy, TLI)) ||
Chris Lattner26d91f12005-08-04 22:34:05 +0000793 !Val->isLoopInvariant(L)) {
794 Imm = SCEVAddExpr::get(Imm, Val);
795 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
796 return;
Chris Lattner7a2ca562005-08-04 19:26:19 +0000797 }
Chris Lattner26d91f12005-08-04 22:34:05 +0000798
799 // Otherwise, no immediates to move.
Nate Begeman16997482005-07-30 00:15:07 +0000800}
801
Chris Lattner934520a2005-08-13 07:27:18 +0000802
Chris Lattner7e79b382006-08-03 06:34:50 +0000803/// SeparateSubExprs - Decompose Expr into all of the subexpressions that are
804/// added together. This is used to reassociate common addition subexprs
805/// together for maximal sharing when rewriting bases.
Chris Lattner934520a2005-08-13 07:27:18 +0000806static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
807 SCEVHandle Expr) {
808 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
809 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
810 SeparateSubExprs(SubExprs, AE->getOperand(j));
811 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
812 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Expr->getType());
813 if (SARE->getOperand(0) == Zero) {
814 SubExprs.push_back(Expr);
815 } else {
816 // Compute the addrec with zero as its base.
817 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
818 Ops[0] = Zero; // Start with zero base.
819 SubExprs.push_back(SCEVAddRecExpr::get(Ops, SARE->getLoop()));
820
821
822 SeparateSubExprs(SubExprs, SARE->getOperand(0));
823 }
824 } else if (!isa<SCEVConstant>(Expr) ||
Reid Spencerbee0f662007-03-02 23:51:25 +0000825 !cast<SCEVConstant>(Expr)->getValue()->isZero()) {
Chris Lattner934520a2005-08-13 07:27:18 +0000826 // Do not add zero.
827 SubExprs.push_back(Expr);
828 }
829}
830
831
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000832/// RemoveCommonExpressionsFromUseBases - Look through all of the uses in Bases,
833/// removing any common subexpressions from it. Anything truly common is
834/// removed, accumulated, and returned. This looks for things like (a+b+c) and
835/// (a+c+d) -> (a+c). The common expression is *removed* from the Bases.
836static SCEVHandle
837RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses) {
838 unsigned NumUses = Uses.size();
839
840 // Only one use? Use its base, regardless of what it is!
841 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Uses[0].Base->getType());
842 SCEVHandle Result = Zero;
843 if (NumUses == 1) {
844 std::swap(Result, Uses[0].Base);
845 return Result;
846 }
847
848 // To find common subexpressions, count how many of Uses use each expression.
849 // If any subexpressions are used Uses.size() times, they are common.
850 std::map<SCEVHandle, unsigned> SubExpressionUseCounts;
851
Chris Lattnerd6155e92005-10-11 18:41:04 +0000852 // UniqueSubExprs - Keep track of all of the subexpressions we see in the
853 // order we see them.
854 std::vector<SCEVHandle> UniqueSubExprs;
855
Chris Lattner934520a2005-08-13 07:27:18 +0000856 std::vector<SCEVHandle> SubExprs;
857 for (unsigned i = 0; i != NumUses; ++i) {
858 // If the base is zero (which is common), return zero now, there are no
859 // CSEs we can find.
860 if (Uses[i].Base == Zero) return Zero;
861
862 // Split the expression into subexprs.
863 SeparateSubExprs(SubExprs, Uses[i].Base);
864 // Add one to SubExpressionUseCounts for each subexpr present.
865 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
Chris Lattnerd6155e92005-10-11 18:41:04 +0000866 if (++SubExpressionUseCounts[SubExprs[j]] == 1)
867 UniqueSubExprs.push_back(SubExprs[j]);
Chris Lattner934520a2005-08-13 07:27:18 +0000868 SubExprs.clear();
869 }
870
Chris Lattnerd6155e92005-10-11 18:41:04 +0000871 // Now that we know how many times each is used, build Result. Iterate over
872 // UniqueSubexprs so that we have a stable ordering.
873 for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
874 std::map<SCEVHandle, unsigned>::iterator I =
875 SubExpressionUseCounts.find(UniqueSubExprs[i]);
876 assert(I != SubExpressionUseCounts.end() && "Entry not found?");
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000877 if (I->second == NumUses) { // Found CSE!
878 Result = SCEVAddExpr::get(Result, I->first);
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000879 } else {
880 // Remove non-cse's from SubExpressionUseCounts.
Chris Lattnerd6155e92005-10-11 18:41:04 +0000881 SubExpressionUseCounts.erase(I);
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000882 }
Chris Lattnerd6155e92005-10-11 18:41:04 +0000883 }
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000884
885 // If we found no CSE's, return now.
886 if (Result == Zero) return Result;
887
888 // Otherwise, remove all of the CSE's we found from each of the base values.
Chris Lattner934520a2005-08-13 07:27:18 +0000889 for (unsigned i = 0; i != NumUses; ++i) {
890 // Split the expression into subexprs.
891 SeparateSubExprs(SubExprs, Uses[i].Base);
892
893 // Remove any common subexpressions.
894 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
895 if (SubExpressionUseCounts.count(SubExprs[j])) {
896 SubExprs.erase(SubExprs.begin()+j);
897 --j; --e;
898 }
899
900 // Finally, the non-shared expressions together.
901 if (SubExprs.empty())
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000902 Uses[i].Base = Zero;
Chris Lattner934520a2005-08-13 07:27:18 +0000903 else
904 Uses[i].Base = SCEVAddExpr::get(SubExprs);
Chris Lattner27e51422005-08-13 07:42:01 +0000905 SubExprs.clear();
Chris Lattner934520a2005-08-13 07:27:18 +0000906 }
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000907
908 return Result;
909}
910
Evan Chengd1d6b5c2006-03-16 21:53:05 +0000911/// isZero - returns true if the scalar evolution expression is zero.
912///
913static bool isZero(SCEVHandle &V) {
914 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V))
Reid Spencerbee0f662007-03-02 23:51:25 +0000915 return SC->getValue()->isZero();
Evan Chengd1d6b5c2006-03-16 21:53:05 +0000916 return false;
917}
918
Dale Johannesendc42f482007-03-20 00:47:50 +0000919/// ValidStride - Check whether the given Scale is valid for all loads and
Chris Lattner579633c2007-04-09 22:20:14 +0000920/// stores in UsersToProcess.
Dale Johannesendc42f482007-03-20 00:47:50 +0000921///
922bool LoopStrengthReduce::ValidStride(int64_t Scale,
923 const std::vector<BasedUser>& UsersToProcess) {
Dale Johannesen8e59e162007-03-20 21:54:54 +0000924 for (unsigned i=0, e = UsersToProcess.size(); i!=e; ++i) {
Chris Lattner1ebd89e2007-04-02 06:34:44 +0000925 // If this is a load or other access, pass the type of the access in.
926 const Type *AccessTy = Type::VoidTy;
927 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
928 AccessTy = SI->getOperand(0)->getType();
929 else if (LoadInst *LI = dyn_cast<LoadInst>(UsersToProcess[i].Inst))
930 AccessTy = LI->getType();
931
Chris Lattner579633c2007-04-09 22:20:14 +0000932 TargetLowering::AddrMode AM;
933 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(UsersToProcess[i].Imm))
934 AM.BaseOffs = SC->getValue()->getSExtValue();
935 AM.Scale = Scale;
936
937 // If load[imm+r*scale] is illegal, bail out.
938 if (!TLI->isLegalAddressingMode(AM, AccessTy))
Dale Johannesendc42f482007-03-20 00:47:50 +0000939 return false;
Dale Johannesen8e59e162007-03-20 21:54:54 +0000940 }
Dale Johannesendc42f482007-03-20 00:47:50 +0000941 return true;
942}
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000943
Evan Chengeb8f9e22006-03-17 19:52:23 +0000944/// CheckForIVReuse - Returns the multiple if the stride is the multiple
945/// of a previous stride and it is a legal value for the target addressing
946/// mode scale component. This allows the users of this stride to be rewritten
Evan Cheng21495772006-03-18 08:03:12 +0000947/// as prev iv * factor. It returns 0 if no reuse is possible.
Dale Johannesendc42f482007-03-20 00:47:50 +0000948unsigned LoopStrengthReduce::CheckForIVReuse(const SCEVHandle &Stride,
949 IVExpr &IV, const Type *Ty,
950 const std::vector<BasedUser>& UsersToProcess) {
Evan Cheng21495772006-03-18 08:03:12 +0000951 if (!TLI) return 0;
Evan Chengeb8f9e22006-03-17 19:52:23 +0000952
953 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride)) {
Reid Spencer502db932007-03-02 23:37:53 +0000954 int64_t SInt = SC->getValue()->getSExtValue();
955 if (SInt == 1) return 0;
Evan Chengeb8f9e22006-03-17 19:52:23 +0000956
Evan Cheng5eef2d22007-03-12 23:27:37 +0000957 for (std::map<SCEVHandle, IVsOfOneStride>::iterator SI= IVsByStride.begin(),
958 SE = IVsByStride.end(); SI != SE; ++SI) {
959 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
Chris Lattner1d312902007-04-02 22:51:58 +0000960 if (SInt != -SSInt &&
961 (unsigned(abs(SInt)) < SSInt || (SInt % SSInt) != 0))
Evan Chengeb8f9e22006-03-17 19:52:23 +0000962 continue;
Evan Cheng5eef2d22007-03-12 23:27:37 +0000963 int64_t Scale = SInt / SSInt;
Dale Johannesendc42f482007-03-20 00:47:50 +0000964 // Check that this stride is valid for all the types used for loads and
965 // stores; if it can be used for some and not others, we might as well use
966 // the original stride everywhere, since we have to create the IV for it
967 // anyway.
968 if (ValidStride(Scale, UsersToProcess))
Evan Cheng5eef2d22007-03-12 23:27:37 +0000969 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
970 IE = SI->second.IVs.end(); II != IE; ++II)
971 // FIXME: Only handle base == 0 for now.
972 // Only reuse previous IV if it would not require a type conversion.
973 if (isZero(II->Base) && II->Base->getType() == Ty) {
974 IV = *II;
975 return Scale;
976 }
Evan Chengeb8f9e22006-03-17 19:52:23 +0000977 }
978 }
Evan Cheng21495772006-03-18 08:03:12 +0000979 return 0;
Evan Chengeb8f9e22006-03-17 19:52:23 +0000980}
981
Chris Lattner7e79b382006-08-03 06:34:50 +0000982/// PartitionByIsUseOfPostIncrementedValue - Simple boolean predicate that
983/// returns true if Val's isUseOfPostIncrementedValue is true.
984static bool PartitionByIsUseOfPostIncrementedValue(const BasedUser &Val) {
985 return Val.isUseOfPostIncrementedValue;
986}
Evan Chengeb8f9e22006-03-17 19:52:23 +0000987
Nate Begeman16997482005-07-30 00:15:07 +0000988/// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
989/// stride of IV. All of the users may have different starting values, and this
990/// may not be the only stride (we know it is if isOnlyStride is true).
Chris Lattner50fad702005-08-10 00:45:21 +0000991void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
Chris Lattnerec3fb632005-08-03 22:21:05 +0000992 IVUsersOfOneStride &Uses,
993 Loop *L,
Nate Begeman16997482005-07-30 00:15:07 +0000994 bool isOnlyStride) {
995 // Transform our list of users and offsets to a bit more complex table. In
Chris Lattnera553b0c2005-08-08 22:56:21 +0000996 // this new vector, each 'BasedUser' contains 'Base' the base of the
997 // strided accessas well as the old information from Uses. We progressively
998 // move information from the Base field to the Imm field, until we eventually
999 // have the full access expression to rewrite the use.
1000 std::vector<BasedUser> UsersToProcess;
Nate Begeman16997482005-07-30 00:15:07 +00001001 UsersToProcess.reserve(Uses.Users.size());
Chris Lattnera553b0c2005-08-08 22:56:21 +00001002 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
1003 UsersToProcess.push_back(Uses.Users[i]);
1004
1005 // Move any loop invariant operands from the offset field to the immediate
1006 // field of the use, so that we don't try to use something before it is
1007 // computed.
1008 MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
1009 UsersToProcess.back().Imm, L);
1010 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
Chris Lattner26d91f12005-08-04 22:34:05 +00001011 "Base value is not loop invariant!");
Nate Begeman16997482005-07-30 00:15:07 +00001012 }
Evan Chengeb8f9e22006-03-17 19:52:23 +00001013
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001014 // We now have a whole bunch of uses of like-strided induction variables, but
1015 // they might all have different bases. We want to emit one PHI node for this
1016 // stride which we fold as many common expressions (between the IVs) into as
1017 // possible. Start by identifying the common expressions in the base values
1018 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
1019 // "A+B"), emit it to the preheader, then remove the expression from the
1020 // UsersToProcess base values.
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001021 SCEVHandle CommonExprs =
1022 RemoveCommonExpressionsFromUseBases(UsersToProcess);
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001023
Chris Lattner44b807e2005-08-08 22:32:34 +00001024 // Next, figure out what we can represent in the immediate fields of
1025 // instructions. If we can represent anything there, move it to the imm
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001026 // fields of the BasedUsers. We do this so that it increases the commonality
1027 // of the remaining uses.
Chris Lattner44b807e2005-08-08 22:32:34 +00001028 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
Chris Lattner80b32b32005-08-16 00:38:11 +00001029 // If the user is not in the current loop, this means it is using the exit
1030 // value of the IV. Do not put anything in the base, make sure it's all in
1031 // the immediate field to allow as much factoring as possible.
1032 if (!L->contains(UsersToProcess[i].Inst->getParent())) {
Chris Lattner8385e512005-08-17 21:22:41 +00001033 UsersToProcess[i].Imm = SCEVAddExpr::get(UsersToProcess[i].Imm,
1034 UsersToProcess[i].Base);
1035 UsersToProcess[i].Base =
1036 SCEVUnknown::getIntegerSCEV(0, UsersToProcess[i].Base->getType());
Chris Lattner80b32b32005-08-16 00:38:11 +00001037 } else {
1038
1039 // Addressing modes can be folded into loads and stores. Be careful that
1040 // the store is through the expression, not of the expression though.
1041 bool isAddress = isa<LoadInst>(UsersToProcess[i].Inst);
1042 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
1043 if (SI->getOperand(1) == UsersToProcess[i].OperandValToReplace)
1044 isAddress = true;
1045
Evan Cheng1d958162007-03-13 20:34:37 +00001046 MoveImmediateValues(TLI, UsersToProcess[i].Inst, UsersToProcess[i].Base,
1047 UsersToProcess[i].Imm, isAddress, L);
Chris Lattner80b32b32005-08-16 00:38:11 +00001048 }
Chris Lattner44b807e2005-08-08 22:32:34 +00001049 }
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001050
Dale Johannesen8e59e162007-03-20 21:54:54 +00001051 // Check if it is possible to reuse a IV with stride that is factor of this
1052 // stride. And the multiple is a number that can be encoded in the scale
1053 // field of the target addressing mode. And we will have a valid
1054 // instruction after this substition, including the immediate field, if any.
1055 PHINode *NewPHI = NULL;
1056 Value *IncV = NULL;
1057 IVExpr ReuseIV;
1058 unsigned RewriteFactor = CheckForIVReuse(Stride, ReuseIV,
1059 CommonExprs->getType(),
1060 UsersToProcess);
1061 if (RewriteFactor != 0) {
1062 DOUT << "BASED ON IV of STRIDE " << *ReuseIV.Stride
1063 << " and BASE " << *ReuseIV.Base << " :\n";
1064 NewPHI = ReuseIV.PHI;
1065 IncV = ReuseIV.IncV;
1066 }
1067
Chris Lattnerfe355552007-04-01 22:21:39 +00001068 const Type *ReplacedTy = CommonExprs->getType();
1069
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001070 // Now that we know what we need to do, insert the PHI node itself.
1071 //
Chris Lattnerfe355552007-04-01 22:21:39 +00001072 DOUT << "INSERTING IV of TYPE " << *ReplacedTy << " of STRIDE "
1073 << *Stride << " and BASE " << *CommonExprs << " :\n";
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001074
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001075 SCEVExpander Rewriter(*SE, *LI);
1076 SCEVExpander PreheaderRewriter(*SE, *LI);
Chris Lattner44b807e2005-08-08 22:32:34 +00001077
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001078 BasicBlock *Preheader = L->getLoopPreheader();
1079 Instruction *PreInsertPt = Preheader->getTerminator();
1080 Instruction *PhiInsertBefore = L->getHeader()->begin();
Chris Lattner44b807e2005-08-08 22:32:34 +00001081
Chris Lattner12b50412005-09-12 17:11:27 +00001082 BasicBlock *LatchBlock = L->getLoopLatch();
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001083
Evan Chengeb8f9e22006-03-17 19:52:23 +00001084
1085 // Emit the initial base value into the loop preheader.
1086 Value *CommonBaseV
1087 = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt,
1088 ReplacedTy);
1089
Evan Cheng21495772006-03-18 08:03:12 +00001090 if (RewriteFactor == 0) {
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001091 // Create a new Phi for this base, and stick it in the loop header.
1092 NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
1093 ++NumInserted;
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001094
Evan Chengeb8f9e22006-03-17 19:52:23 +00001095 // Add common base to the new Phi node.
1096 NewPHI->addIncoming(CommonBaseV, Preheader);
1097
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001098 // Insert the stride into the preheader.
1099 Value *StrideV = PreheaderRewriter.expandCodeFor(Stride, PreInsertPt,
1100 ReplacedTy);
1101 if (!isa<ConstantInt>(StrideV)) ++NumVariable;
Chris Lattner50fad702005-08-10 00:45:21 +00001102
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001103 // Emit the increment of the base value before the terminator of the loop
1104 // latch block, and add it to the Phi node.
1105 SCEVHandle IncExp = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
1106 SCEVUnknown::get(StrideV));
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001107
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001108 IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator(),
1109 ReplacedTy);
1110 IncV->setName(NewPHI->getName()+".inc");
1111 NewPHI->addIncoming(IncV, LatchBlock);
1112
Evan Chengeb8f9e22006-03-17 19:52:23 +00001113 // Remember this in case a later stride is multiple of this.
Evan Cheng21495772006-03-18 08:03:12 +00001114 IVsByStride[Stride].addIV(Stride, CommonExprs, NewPHI, IncV);
Evan Chengeb8f9e22006-03-17 19:52:23 +00001115 } else {
1116 Constant *C = dyn_cast<Constant>(CommonBaseV);
1117 if (!C ||
1118 (!C->isNullValue() &&
Evan Cheng1d958162007-03-13 20:34:37 +00001119 !isTargetConstant(SCEVUnknown::get(CommonBaseV), ReplacedTy, TLI)))
Reid Spencer3da59db2006-11-27 01:05:10 +00001120 // We want the common base emitted into the preheader! This is just
1121 // using cast as a copy so BitCast (no-op cast) is appropriate
1122 CommonBaseV = new BitCastInst(CommonBaseV, CommonBaseV->getType(),
1123 "commonbase", PreInsertPt);
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001124 }
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001125
Chris Lattner7e79b382006-08-03 06:34:50 +00001126 // We want to emit code for users inside the loop first. To do this, we
1127 // rearrange BasedUser so that the entries at the end have
1128 // isUseOfPostIncrementedValue = false, because we pop off the end of the
1129 // vector (so we handle them first).
1130 std::partition(UsersToProcess.begin(), UsersToProcess.end(),
1131 PartitionByIsUseOfPostIncrementedValue);
1132
1133 // Sort this by base, so that things with the same base are handled
1134 // together. By partitioning first and stable-sorting later, we are
1135 // guaranteed that within each base we will pop off users from within the
1136 // loop before users outside of the loop with a particular base.
1137 //
1138 // We would like to use stable_sort here, but we can't. The problem is that
1139 // SCEVHandle's don't have a deterministic ordering w.r.t to each other, so
1140 // we don't have anything to do a '<' comparison on. Because we think the
1141 // number of uses is small, do a horrible bubble sort which just relies on
1142 // ==.
1143 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1144 // Get a base value.
1145 SCEVHandle Base = UsersToProcess[i].Base;
1146
1147 // Compact everything with this base to be consequetive with this one.
1148 for (unsigned j = i+1; j != e; ++j) {
1149 if (UsersToProcess[j].Base == Base) {
1150 std::swap(UsersToProcess[i+1], UsersToProcess[j]);
1151 ++i;
1152 }
1153 }
1154 }
1155
1156 // Process all the users now. This outer loop handles all bases, the inner
1157 // loop handles all users of a particular base.
Nate Begeman16997482005-07-30 00:15:07 +00001158 while (!UsersToProcess.empty()) {
Chris Lattner7b445c52005-10-11 18:30:57 +00001159 SCEVHandle Base = UsersToProcess.back().Base;
Chris Lattnerbe3e5212005-08-03 23:30:08 +00001160
Bill Wendlingb7427032006-11-26 09:46:52 +00001161 DOUT << " INSERTING code for BASE = " << *Base << ":\n";
Chris Lattnerbe3e5212005-08-03 23:30:08 +00001162
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001163 // Emit the code for Base into the preheader.
Chris Lattner5272f3c2005-08-08 05:47:49 +00001164 Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt,
1165 ReplacedTy);
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001166
1167 // If BaseV is a constant other than 0, make sure that it gets inserted into
1168 // the preheader, instead of being forward substituted into the uses. We do
Reid Spencer3da59db2006-11-27 01:05:10 +00001169 // this by forcing a BitCast (noop cast) to be inserted into the preheader
1170 // in this case.
Chris Lattner7e79b382006-08-03 06:34:50 +00001171 if (Constant *C = dyn_cast<Constant>(BaseV)) {
Evan Cheng1d958162007-03-13 20:34:37 +00001172 if (!C->isNullValue() && !isTargetConstant(Base, ReplacedTy, TLI)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001173 // We want this constant emitted into the preheader! This is just
1174 // using cast as a copy so BitCast (no-op cast) is appropriate
1175 BaseV = new BitCastInst(BaseV, BaseV->getType(), "preheaderinsert",
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001176 PreInsertPt);
1177 }
Chris Lattner7e79b382006-08-03 06:34:50 +00001178 }
1179
Nate Begeman16997482005-07-30 00:15:07 +00001180 // Emit the code to add the immediate offset to the Phi value, just before
Chris Lattner2351aba2005-08-03 22:51:21 +00001181 // the instructions that we identified as using this stride and base.
Chris Lattner7b445c52005-10-11 18:30:57 +00001182 do {
Chris Lattner7e79b382006-08-03 06:34:50 +00001183 // FIXME: Use emitted users to emit other users.
Chris Lattner7b445c52005-10-11 18:30:57 +00001184 BasedUser &User = UsersToProcess.back();
Jeff Cohend29b6aa2005-07-30 18:33:25 +00001185
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001186 // If this instruction wants to use the post-incremented value, move it
1187 // after the post-inc and use its value instead of the PHI.
1188 Value *RewriteOp = NewPHI;
1189 if (User.isUseOfPostIncrementedValue) {
1190 RewriteOp = IncV;
Chris Lattnerc6bae652005-09-12 06:04:47 +00001191
1192 // If this user is in the loop, make sure it is the last thing in the
1193 // loop to ensure it is dominated by the increment.
1194 if (L->contains(User.Inst->getParent()))
1195 User.Inst->moveBefore(LatchBlock->getTerminator());
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001196 }
Reid Spencer3ba68b92006-12-13 08:06:42 +00001197 if (RewriteOp->getType() != ReplacedTy) {
1198 Instruction::CastOps opcode = Instruction::Trunc;
1199 if (ReplacedTy->getPrimitiveSizeInBits() ==
1200 RewriteOp->getType()->getPrimitiveSizeInBits())
1201 opcode = Instruction::BitCast;
1202 RewriteOp = SCEVExpander::InsertCastOfTo(opcode, RewriteOp, ReplacedTy);
1203 }
Evan Cheng86c75d32006-06-09 00:12:42 +00001204
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001205 SCEVHandle RewriteExpr = SCEVUnknown::get(RewriteOp);
1206
Chris Lattner2351aba2005-08-03 22:51:21 +00001207 // Clear the SCEVExpander's expression map so that we are guaranteed
1208 // to have the code emitted where we expect it.
1209 Rewriter.clear();
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001210
1211 // If we are reusing the iv, then it must be multiplied by a constant
1212 // factor take advantage of addressing mode scale component.
Evan Cheng21495772006-03-18 08:03:12 +00001213 if (RewriteFactor != 0) {
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001214 RewriteExpr =
1215 SCEVMulExpr::get(SCEVUnknown::getIntegerSCEV(RewriteFactor,
Evan Chengeb8f9e22006-03-17 19:52:23 +00001216 RewriteExpr->getType()),
1217 RewriteExpr);
1218
1219 // The common base is emitted in the loop preheader. But since we
1220 // are reusing an IV, it has not been used to initialize the PHI node.
1221 // Add it to the expression used to rewrite the uses.
1222 if (!isa<ConstantInt>(CommonBaseV) ||
Reid Spencerbee0f662007-03-02 23:51:25 +00001223 !cast<ConstantInt>(CommonBaseV)->isZero())
Evan Chengeb8f9e22006-03-17 19:52:23 +00001224 RewriteExpr = SCEVAddExpr::get(RewriteExpr,
1225 SCEVUnknown::get(CommonBaseV));
1226 }
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001227
Chris Lattner2114b272005-08-04 20:03:32 +00001228 // Now that we know what we need to do, insert code before User for the
1229 // immediate and any loop-variant expressions.
Reid Spencerbee0f662007-03-02 23:51:25 +00001230 if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isZero())
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001231 // Add BaseV to the PHI value if needed.
1232 RewriteExpr = SCEVAddExpr::get(RewriteExpr, SCEVUnknown::get(BaseV));
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001233
Chris Lattnerc60fb082005-08-12 22:22:17 +00001234 User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter, L, this);
Jeff Cohend29b6aa2005-07-30 18:33:25 +00001235
Chris Lattner2351aba2005-08-03 22:51:21 +00001236 // Mark old value we replaced as possibly dead, so that it is elminated
1237 // if we just replaced the last use of that value.
Chris Lattner2114b272005-08-04 20:03:32 +00001238 DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
Nate Begeman16997482005-07-30 00:15:07 +00001239
Chris Lattner7b445c52005-10-11 18:30:57 +00001240 UsersToProcess.pop_back();
Chris Lattner2351aba2005-08-03 22:51:21 +00001241 ++NumReduced;
Chris Lattner7b445c52005-10-11 18:30:57 +00001242
Chris Lattner7e79b382006-08-03 06:34:50 +00001243 // If there are any more users to process with the same base, process them
1244 // now. We sorted by base above, so we just have to check the last elt.
Chris Lattner7b445c52005-10-11 18:30:57 +00001245 } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
Nate Begeman16997482005-07-30 00:15:07 +00001246 // TODO: Next, find out which base index is the most common, pull it out.
1247 }
1248
1249 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1250 // different starting values, into different PHIs.
Nate Begeman16997482005-07-30 00:15:07 +00001251}
1252
Chris Lattneraed01d12007-04-03 05:11:24 +00001253/// FindIVForUser - If Cond has an operand that is an expression of an IV,
1254/// set the IV user and stride information and return true, otherwise return
1255/// false.
1256bool LoopStrengthReduce::FindIVForUser(ICmpInst *Cond, IVStrideUse *&CondUse,
1257 const SCEVHandle *&CondStride) {
1258 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e && !CondUse;
1259 ++Stride) {
1260 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1261 IVUsesByStride.find(StrideOrder[Stride]);
1262 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1263
1264 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
1265 E = SI->second.Users.end(); UI != E; ++UI)
1266 if (UI->User == Cond) {
1267 // NOTE: we could handle setcc instructions with multiple uses here, but
1268 // InstCombine does it as well for simple uses, it's not clear that it
1269 // occurs enough in real life to handle.
1270 CondUse = &*UI;
1271 CondStride = &SI->first;
1272 return true;
1273 }
1274 }
1275 return false;
1276}
1277
Chris Lattner010de252005-08-08 05:28:22 +00001278// OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
1279// uses in the loop, look to see if we can eliminate some, in favor of using
1280// common indvars for the different uses.
1281void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
1282 // TODO: implement optzns here.
1283
Chris Lattner010de252005-08-08 05:28:22 +00001284 // Finally, get the terminating condition for the loop if possible. If we
1285 // can, we want to change it to use a post-incremented version of its
Chris Lattner98d98112006-03-24 07:14:34 +00001286 // induction variable, to allow coalescing the live ranges for the IV into
Chris Lattner010de252005-08-08 05:28:22 +00001287 // one register value.
1288 PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
1289 BasicBlock *Preheader = L->getLoopPreheader();
1290 BasicBlock *LatchBlock =
1291 SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
1292 BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001293 if (!TermBr || TermBr->isUnconditional() ||
1294 !isa<ICmpInst>(TermBr->getCondition()))
Chris Lattner010de252005-08-08 05:28:22 +00001295 return;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001296 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
Chris Lattner010de252005-08-08 05:28:22 +00001297
1298 // Search IVUsesByStride to find Cond's IVUse if there is one.
1299 IVStrideUse *CondUse = 0;
Chris Lattner50fad702005-08-10 00:45:21 +00001300 const SCEVHandle *CondStride = 0;
Chris Lattner010de252005-08-08 05:28:22 +00001301
Chris Lattneraed01d12007-04-03 05:11:24 +00001302 if (!FindIVForUser(Cond, CondUse, CondStride))
1303 return; // setcc doesn't use the IV.
1304
Chris Lattner010de252005-08-08 05:28:22 +00001305
Chris Lattner010de252005-08-08 05:28:22 +00001306 // It's possible for the setcc instruction to be anywhere in the loop, and
1307 // possible for it to have multiple users. If it is not immediately before
1308 // the latch block branch, move it.
1309 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
1310 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
1311 Cond->moveBefore(TermBr);
1312 } else {
1313 // Otherwise, clone the terminating condition and insert into the loopend.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001314 Cond = cast<ICmpInst>(Cond->clone());
Chris Lattner010de252005-08-08 05:28:22 +00001315 Cond->setName(L->getHeader()->getName() + ".termcond");
1316 LatchBlock->getInstList().insert(TermBr, Cond);
1317
1318 // Clone the IVUse, as the old use still exists!
Chris Lattner50fad702005-08-10 00:45:21 +00001319 IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
Chris Lattner010de252005-08-08 05:28:22 +00001320 CondUse->OperandValToReplace);
Chris Lattner50fad702005-08-10 00:45:21 +00001321 CondUse = &IVUsesByStride[*CondStride].Users.back();
Chris Lattner010de252005-08-08 05:28:22 +00001322 }
1323 }
1324
1325 // If we get to here, we know that we can transform the setcc instruction to
Chris Lattner98d98112006-03-24 07:14:34 +00001326 // use the post-incremented version of the IV, allowing us to coalesce the
Chris Lattner010de252005-08-08 05:28:22 +00001327 // live ranges for the IV correctly.
Chris Lattner50fad702005-08-10 00:45:21 +00001328 CondUse->Offset = SCEV::getMinusSCEV(CondUse->Offset, *CondStride);
Chris Lattner010de252005-08-08 05:28:22 +00001329 CondUse->isUseOfPostIncrementedValue = true;
1330}
Nate Begeman16997482005-07-30 00:15:07 +00001331
Evan Cheng4496a502006-03-18 00:44:49 +00001332namespace {
1333 // Constant strides come first which in turns are sorted by their absolute
1334 // values. If absolute values are the same, then positive strides comes first.
1335 // e.g.
1336 // 4, -1, X, 1, 2 ==> 1, -1, 2, 4, X
1337 struct StrideCompare {
1338 bool operator()(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1339 SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS);
1340 SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
1341 if (LHSC && RHSC) {
Reid Spencer513d0f22007-03-02 00:31:39 +00001342 int64_t LV = LHSC->getValue()->getSExtValue();
1343 int64_t RV = RHSC->getValue()->getSExtValue();
1344 uint64_t ALV = (LV < 0) ? -LV : LV;
1345 uint64_t ARV = (RV < 0) ? -RV : RV;
Evan Cheng4496a502006-03-18 00:44:49 +00001346 if (ALV == ARV)
Reid Spencer513d0f22007-03-02 00:31:39 +00001347 return LV > RV;
Evan Cheng4496a502006-03-18 00:44:49 +00001348 else
Reid Spencer513d0f22007-03-02 00:31:39 +00001349 return ALV < ARV;
Chris Lattner035c6a22006-03-22 17:27:24 +00001350 }
1351 return (LHSC && !RHSC);
Evan Cheng4496a502006-03-18 00:44:49 +00001352 }
1353 };
1354}
1355
Devang Patel0f54dcb2007-03-06 21:14:09 +00001356bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager &LPM) {
Nate Begemaneaa13852004-10-18 21:08:22 +00001357
Devang Patel0f54dcb2007-03-06 21:14:09 +00001358 LI = &getAnalysis<LoopInfo>();
1359 EF = &getAnalysis<ETForest>();
1360 SE = &getAnalysis<ScalarEvolution>();
1361 TD = &getAnalysis<TargetData>();
1362 UIntPtrTy = TD->getIntPtrType();
1363
1364 // Find all uses of induction variables in this loop, and catagorize
Nate Begeman16997482005-07-30 00:15:07 +00001365 // them by stride. Start by finding all of the PHI nodes in the header for
1366 // this loop. If they are induction variables, inspect their uses.
Chris Lattner3416e5f2005-08-04 17:40:30 +00001367 std::set<Instruction*> Processed; // Don't reprocess instructions.
Nate Begeman16997482005-07-30 00:15:07 +00001368 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
Chris Lattner3416e5f2005-08-04 17:40:30 +00001369 AddUsersIfInteresting(I, L, Processed);
Nate Begemaneaa13852004-10-18 21:08:22 +00001370
Nate Begeman16997482005-07-30 00:15:07 +00001371 // If we have nothing to do, return.
Devang Patel0f54dcb2007-03-06 21:14:09 +00001372 if (IVUsesByStride.empty()) return false;
Chris Lattner010de252005-08-08 05:28:22 +00001373
1374 // Optimize induction variables. Some indvar uses can be transformed to use
1375 // strides that will be needed for other purposes. A common example of this
1376 // is the exit test for the loop, which can often be rewritten to use the
1377 // computation of some other indvar to decide when to terminate the loop.
1378 OptimizeIndvars(L);
1379
Misha Brukmanfd939082005-04-21 23:48:37 +00001380
Nate Begeman16997482005-07-30 00:15:07 +00001381 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
1382 // doing computation in byte values, promote to 32-bit values if safe.
1383
1384 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
1385 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
1386 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
1387 // to be careful that IV's are all the same type. Only works for intptr_t
1388 // indvars.
1389
1390 // If we only have one stride, we can more aggressively eliminate some things.
1391 bool HasOneStride = IVUsesByStride.size() == 1;
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001392
1393#ifndef NDEBUG
Bill Wendlingb7427032006-11-26 09:46:52 +00001394 DOUT << "\nLSR on ";
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001395 DEBUG(L->dump());
1396#endif
1397
1398 // IVsByStride keeps IVs for one particular loop.
1399 IVsByStride.clear();
1400
Evan Cheng4496a502006-03-18 00:44:49 +00001401 // Sort the StrideOrder so we process larger strides first.
1402 std::stable_sort(StrideOrder.begin(), StrideOrder.end(), StrideCompare());
1403
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001404 // Note: this processes each stride/type pair individually. All users passed
Chris Lattner7305ae22005-10-09 06:20:55 +00001405 // into StrengthReduceStridedIVUsers have the same type AND stride. Also,
1406 // node that we iterate over IVUsesByStride indirectly by using StrideOrder.
1407 // This extra layer of indirection makes the ordering of strides deterministic
1408 // - not dependent on map order.
1409 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
1410 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1411 IVUsesByStride.find(StrideOrder[Stride]);
1412 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
Nate Begeman16997482005-07-30 00:15:07 +00001413 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
Chris Lattner7305ae22005-10-09 06:20:55 +00001414 }
Nate Begemaneaa13852004-10-18 21:08:22 +00001415
1416 // Clean up after ourselves
1417 if (!DeadInsts.empty()) {
1418 DeleteTriviallyDeadInstructions(DeadInsts);
1419
Nate Begeman16997482005-07-30 00:15:07 +00001420 BasicBlock::iterator I = L->getHeader()->begin();
1421 PHINode *PN;
Chris Lattnere9100c62005-08-02 02:44:31 +00001422 while ((PN = dyn_cast<PHINode>(I))) {
Chris Lattner1060e092005-08-02 00:41:11 +00001423 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
1424
Chris Lattner87265ab2005-08-09 23:39:36 +00001425 // At this point, we know that we have killed one or more GEP
1426 // instructions. It is worth checking to see if the cann indvar is also
1427 // dead, so that we can remove it as well. The requirements for the cann
1428 // indvar to be considered dead are:
Nate Begeman16997482005-07-30 00:15:07 +00001429 // 1. the cann indvar has one use
1430 // 2. the use is an add instruction
1431 // 3. the add has one use
1432 // 4. the add is used by the cann indvar
1433 // If all four cases above are true, then we can remove both the add and
1434 // the cann indvar.
1435 // FIXME: this needs to eliminate an induction variable even if it's being
1436 // compared against some value to decide loop termination.
1437 if (PN->hasOneUse()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001438 Instruction *BO = dyn_cast<Instruction>(*PN->use_begin());
1439 if (BO && (isa<BinaryOperator>(BO) || isa<CmpInst>(BO))) {
1440 if (BO->hasOneUse() && PN == *(BO->use_begin())) {
Chris Lattner7e608bb2005-08-02 02:52:02 +00001441 DeadInsts.insert(BO);
1442 // Break the cycle, then delete the PHI.
1443 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattner52d83e62005-08-03 21:36:09 +00001444 SE->deleteInstructionFromRecords(PN);
Chris Lattner7e608bb2005-08-02 02:52:02 +00001445 PN->eraseFromParent();
Nate Begemaneaa13852004-10-18 21:08:22 +00001446 }
Chris Lattner7e608bb2005-08-02 02:52:02 +00001447 }
Nate Begeman16997482005-07-30 00:15:07 +00001448 }
Nate Begemaneaa13852004-10-18 21:08:22 +00001449 }
Nate Begeman16997482005-07-30 00:15:07 +00001450 DeleteTriviallyDeadInstructions(DeadInsts);
Nate Begemaneaa13852004-10-18 21:08:22 +00001451 }
Nate Begeman16997482005-07-30 00:15:07 +00001452
Chris Lattner9a59fbb2005-08-05 01:30:11 +00001453 CastedPointers.clear();
Nate Begeman16997482005-07-30 00:15:07 +00001454 IVUsesByStride.clear();
Chris Lattner7305ae22005-10-09 06:20:55 +00001455 StrideOrder.clear();
Devang Patel0f54dcb2007-03-06 21:14:09 +00001456 return false;
Nate Begemaneaa13852004-10-18 21:08:22 +00001457}