blob: 27d0e5c667da9c6ceeef4c0a1a8d3c075e8af889 [file] [log] [blame]
Nate Begemanb18121e2004-10-18 21:08:22 +00001//===- LoopStrengthReduce.cpp - Strength Reduce GEPs in Loops -------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Nate Begemanb18121e2004-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 Brukmanb1c93172005-04-21 23:48:37 +00007//
Nate Begemanb18121e2004-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 Begemanb18121e2004-10-18 21:08:22 +000016//===----------------------------------------------------------------------===//
17
18#include "llvm/Transforms/Scalar.h"
19#include "llvm/Constants.h"
20#include "llvm/Instructions.h"
21#include "llvm/Type.h"
Jeff Cohena2c59b72005-03-04 04:04:26 +000022#include "llvm/DerivedTypes.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000023#include "llvm/Analysis/Dominators.h"
24#include "llvm/Analysis/LoopInfo.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000025#include "llvm/Analysis/ScalarEvolutionExpander.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000026#include "llvm/Support/CFG.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000027#include "llvm/Support/GetElementPtrTypeIterator.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000028#include "llvm/Transforms/Utils/Local.h"
Jeff Cohena2c59b72005-03-04 04:04:26 +000029#include "llvm/Target/TargetData.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000030#include "llvm/ADT/Statistic.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000031#include "llvm/Support/Debug.h"
Jeff Cohenc5009912005-07-30 18:22:27 +000032#include <algorithm>
Nate Begemanb18121e2004-10-18 21:08:22 +000033#include <set>
34using namespace llvm;
35
36namespace {
37 Statistic<> NumReduced ("loop-reduce", "Number of GEPs strength reduced");
38
Chris Lattnerd3874fa2005-03-06 21:58:22 +000039 class GEPCache {
Jeff Cohenbe37fa02005-03-05 22:40:34 +000040 public:
41 GEPCache() : CachedPHINode(0), Map() {}
42
Chris Lattnerd3874fa2005-03-06 21:58:22 +000043 GEPCache *get(Value *v) {
Jeff Cohenbe37fa02005-03-05 22:40:34 +000044 std::map<Value *, GEPCache>::iterator I = Map.find(v);
45 if (I == Map.end())
46 I = Map.insert(std::pair<Value *, GEPCache>(v, GEPCache())).first;
Chris Lattnerd3874fa2005-03-06 21:58:22 +000047 return &I->second;
Jeff Cohenbe37fa02005-03-05 22:40:34 +000048 }
49
50 PHINode *CachedPHINode;
51 std::map<Value *, GEPCache> Map;
52 };
Chris Lattner430d0022005-08-03 22:21:05 +000053
54 /// IVStrideUse - Keep track of one use of a strided induction variable, where
55 /// the stride is stored externally. The Offset member keeps track of the
56 /// offset from the IV, User is the actual user of the operand, and 'Operand'
57 /// is the operand # of the User that is the use.
58 struct IVStrideUse {
59 SCEVHandle Offset;
60 Instruction *User;
61 Value *OperandValToReplace;
62
63 IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
64 : Offset(Offs), User(U), OperandValToReplace(O) {}
65 };
66
67 /// IVUsersOfOneStride - This structure keeps track of all instructions that
68 /// have an operand that is based on the trip count multiplied by some stride.
69 /// The stride for all of these users is common and kept external to this
70 /// structure.
71 struct IVUsersOfOneStride {
Nate Begemane68bcd12005-07-30 00:15:07 +000072 /// Users - Keep track of all of the users of this stride as well as the
Chris Lattner430d0022005-08-03 22:21:05 +000073 /// initial value and the operand that uses the IV.
74 std::vector<IVStrideUse> Users;
75
76 void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
77 Users.push_back(IVStrideUse(Offset, User, Operand));
Nate Begemane68bcd12005-07-30 00:15:07 +000078 }
79 };
80
81
Nate Begemanb18121e2004-10-18 21:08:22 +000082 class LoopStrengthReduce : public FunctionPass {
83 LoopInfo *LI;
84 DominatorSet *DS;
Nate Begemane68bcd12005-07-30 00:15:07 +000085 ScalarEvolution *SE;
86 const TargetData *TD;
87 const Type *UIntPtrTy;
Nate Begemanb18121e2004-10-18 21:08:22 +000088 bool Changed;
Chris Lattner75a44e12005-08-02 02:52:02 +000089
90 /// MaxTargetAMSize - This is the maximum power-of-two scale value that the
91 /// target can handle for free with its addressing modes.
Jeff Cohena2c59b72005-03-04 04:04:26 +000092 unsigned MaxTargetAMSize;
Nate Begemane68bcd12005-07-30 00:15:07 +000093
94 /// IVUsesByStride - Keep track of all uses of induction variables that we
95 /// are interested in. The key of the map is the stride of the access.
Chris Lattner430d0022005-08-03 22:21:05 +000096 std::map<Value*, IVUsersOfOneStride> IVUsesByStride;
Nate Begemane68bcd12005-07-30 00:15:07 +000097
98 /// CastedBasePointers - As we need to lower getelementptr instructions, we
99 /// cast the pointer input to uintptr_t. This keeps track of the casted
100 /// values for the pointers we have processed so far.
101 std::map<Value*, Value*> CastedBasePointers;
102
103 /// DeadInsts - Keep track of instructions we may have made dead, so that
104 /// we can remove them after we are done working.
105 std::set<Instruction*> DeadInsts;
Nate Begemanb18121e2004-10-18 21:08:22 +0000106 public:
Jeff Cohena2c59b72005-03-04 04:04:26 +0000107 LoopStrengthReduce(unsigned MTAMS = 1)
108 : MaxTargetAMSize(MTAMS) {
109 }
110
Nate Begemanb18121e2004-10-18 21:08:22 +0000111 virtual bool runOnFunction(Function &) {
112 LI = &getAnalysis<LoopInfo>();
113 DS = &getAnalysis<DominatorSet>();
Nate Begemane68bcd12005-07-30 00:15:07 +0000114 SE = &getAnalysis<ScalarEvolution>();
115 TD = &getAnalysis<TargetData>();
116 UIntPtrTy = TD->getIntPtrType();
Nate Begemanb18121e2004-10-18 21:08:22 +0000117 Changed = false;
118
119 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
120 runOnLoop(*I);
121 return Changed;
122 }
123
124 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
125 AU.setPreservesCFG();
Jeff Cohen39751c32005-02-27 19:37:07 +0000126 AU.addRequiredID(LoopSimplifyID);
Nate Begemanb18121e2004-10-18 21:08:22 +0000127 AU.addRequired<LoopInfo>();
128 AU.addRequired<DominatorSet>();
Jeff Cohena2c59b72005-03-04 04:04:26 +0000129 AU.addRequired<TargetData>();
Nate Begemane68bcd12005-07-30 00:15:07 +0000130 AU.addRequired<ScalarEvolution>();
Nate Begemanb18121e2004-10-18 21:08:22 +0000131 }
132 private:
133 void runOnLoop(Loop *L);
Nate Begemane68bcd12005-07-30 00:15:07 +0000134 bool AddUsersIfInteresting(Instruction *I, Loop *L);
135 void AnalyzeGetElementPtrUsers(GetElementPtrInst *GEP, Instruction *I,
136 Loop *L);
137
Chris Lattner430d0022005-08-03 22:21:05 +0000138 void StrengthReduceStridedIVUsers(Value *Stride, IVUsersOfOneStride &Uses,
139 Loop *L, bool isOnlyStride);
Nate Begemane68bcd12005-07-30 00:15:07 +0000140
Nate Begemanb18121e2004-10-18 21:08:22 +0000141 void strengthReduceGEP(GetElementPtrInst *GEPI, Loop *L,
Jeff Cohenbe37fa02005-03-05 22:40:34 +0000142 GEPCache* GEPCache,
Nate Begemanb18121e2004-10-18 21:08:22 +0000143 Instruction *InsertBefore,
144 std::set<Instruction*> &DeadInsts);
145 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
146 };
Misha Brukmanb1c93172005-04-21 23:48:37 +0000147 RegisterOpt<LoopStrengthReduce> X("loop-reduce",
Nate Begemanb18121e2004-10-18 21:08:22 +0000148 "Strength Reduce GEP Uses of Ind. Vars");
149}
150
Jeff Cohena2c59b72005-03-04 04:04:26 +0000151FunctionPass *llvm::createLoopStrengthReducePass(unsigned MaxTargetAMSize) {
152 return new LoopStrengthReduce(MaxTargetAMSize);
Nate Begemanb18121e2004-10-18 21:08:22 +0000153}
154
155/// DeleteTriviallyDeadInstructions - If any of the instructions is the
156/// specified set are trivially dead, delete them and see if this makes any of
157/// their operands subsequently dead.
158void LoopStrengthReduce::
159DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
160 while (!Insts.empty()) {
161 Instruction *I = *Insts.begin();
162 Insts.erase(Insts.begin());
163 if (isInstructionTriviallyDead(I)) {
Jeff Cohen8ea6f9e2005-03-01 03:46:11 +0000164 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
165 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
166 Insts.insert(U);
Chris Lattner84e9baa2005-08-03 21:36:09 +0000167 SE->deleteInstructionFromRecords(I);
168 I->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +0000169 Changed = true;
170 }
171 }
172}
173
Jeff Cohen39751c32005-02-27 19:37:07 +0000174
Nate Begemane68bcd12005-07-30 00:15:07 +0000175/// CanReduceSCEV - Return true if we can strength reduce this scalar evolution
176/// in the specified loop.
177static bool CanReduceSCEV(const SCEVHandle &SH, Loop *L) {
178 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SH);
179 if (!AddRec || AddRec->getLoop() != L) return false;
Jeff Cohena2c59b72005-03-04 04:04:26 +0000180
Nate Begemane68bcd12005-07-30 00:15:07 +0000181 // FIXME: Generalize to non-affine IV's.
182 if (!AddRec->isAffine()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000183
Nate Begemane68bcd12005-07-30 00:15:07 +0000184 // FIXME: generalize to IV's with more complex strides (must emit stride
185 // expression outside of loop!)
186 if (isa<SCEVConstant>(AddRec->getOperand(1)))
187 return true;
Jeff Cohena2c59b72005-03-04 04:04:26 +0000188
Nate Begemane68bcd12005-07-30 00:15:07 +0000189 // We handle steps by unsigned values, because we know we won't have to insert
190 // a cast for them.
191 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(AddRec->getOperand(1)))
192 if (SU->getValue()->getType()->isUnsigned())
193 return true;
Jeff Cohen546fd592005-07-30 18:33:25 +0000194
Nate Begemane68bcd12005-07-30 00:15:07 +0000195 // Otherwise, no, we can't handle it yet.
196 return false;
Nate Begemanb18121e2004-10-18 21:08:22 +0000197}
198
Nate Begemane68bcd12005-07-30 00:15:07 +0000199
200/// GetAdjustedIndex - Adjust the specified GEP sequential type index to match
201/// the size of the pointer type, and scale it by the type size.
202static SCEVHandle GetAdjustedIndex(const SCEVHandle &Idx, uint64_t TySize,
203 const Type *UIntPtrTy) {
204 SCEVHandle Result = Idx;
205 if (Result->getType()->getUnsignedVersion() != UIntPtrTy) {
206 if (UIntPtrTy->getPrimitiveSize() < Result->getType()->getPrimitiveSize())
207 Result = SCEVTruncateExpr::get(Result, UIntPtrTy);
208 else
209 Result = SCEVZeroExtendExpr::get(Result, UIntPtrTy);
210 }
211
212 // This index is scaled by the type size being indexed.
213 if (TySize != 1)
Jeff Cohen546fd592005-07-30 18:33:25 +0000214 Result = SCEVMulExpr::get(Result,
Nate Begemane68bcd12005-07-30 00:15:07 +0000215 SCEVConstant::get(ConstantUInt::get(UIntPtrTy,
216 TySize)));
217 return Result;
218}
219
220/// AnalyzeGetElementPtrUsers - Analyze all of the users of the specified
221/// getelementptr instruction, adding them to the IVUsesByStride table. Note
222/// that we only want to analyze a getelementptr instruction once, and it can
223/// have multiple operands that are uses of the indvar (e.g. A[i][i]). Because
224/// of this, we only process a GEP instruction if its first recurrent operand is
225/// "op", otherwise we will either have already processed it or we will sometime
226/// later.
227void LoopStrengthReduce::AnalyzeGetElementPtrUsers(GetElementPtrInst *GEP,
228 Instruction *Op, Loop *L) {
229 // Analyze all of the subscripts of this getelementptr instruction, looking
230 // for uses that are determined by the trip count of L. First, skip all
231 // operands the are not dependent on the IV.
232
233 // Build up the base expression. Insert an LLVM cast of the pointer to
234 // uintptr_t first.
235 Value *BasePtr;
236 if (Constant *CB = dyn_cast<Constant>(GEP->getOperand(0)))
237 BasePtr = ConstantExpr::getCast(CB, UIntPtrTy);
Jeff Cohen546fd592005-07-30 18:33:25 +0000238 else {
Nate Begemane68bcd12005-07-30 00:15:07 +0000239 Value *&BP = CastedBasePointers[GEP->getOperand(0)];
240 if (BP == 0) {
241 BasicBlock::iterator InsertPt;
242 if (isa<Argument>(GEP->getOperand(0))) {
243 InsertPt = GEP->getParent()->getParent()->begin()->begin();
244 } else {
245 InsertPt = cast<Instruction>(GEP->getOperand(0));
246 if (InvokeInst *II = dyn_cast<InvokeInst>(GEP->getOperand(0)))
247 InsertPt = II->getNormalDest()->begin();
248 else
249 ++InsertPt;
250 }
Chris Lattner351b8912005-08-02 03:31:14 +0000251
252 // Do not insert casts into the middle of PHI node blocks.
253 while (isa<PHINode>(InsertPt)) ++InsertPt;
254
Nate Begemane68bcd12005-07-30 00:15:07 +0000255 BP = new CastInst(GEP->getOperand(0), UIntPtrTy,
256 GEP->getOperand(0)->getName(), InsertPt);
257 }
258 BasePtr = BP;
259 }
260
261 SCEVHandle Base = SCEVUnknown::get(BasePtr);
262
263 gep_type_iterator GTI = gep_type_begin(GEP);
264 unsigned i = 1;
265 for (; GEP->getOperand(i) != Op; ++i, ++GTI) {
266 // If this is a use of a recurrence that we can analyze, and it comes before
267 // Op does in the GEP operand list, we will handle this when we process this
268 // operand.
269 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
270 const StructLayout *SL = TD->getStructLayout(STy);
271 unsigned Idx = cast<ConstantUInt>(GEP->getOperand(i))->getValue();
272 uint64_t Offset = SL->MemberOffsets[Idx];
273 Base = SCEVAddExpr::get(Base, SCEVUnknown::getIntegerSCEV(Offset,
274 UIntPtrTy));
275 } else {
276 SCEVHandle Idx = SE->getSCEV(GEP->getOperand(i));
Chris Lattner9ef12942005-08-02 01:32:29 +0000277
278 // If this operand is reducible, and it's not the one we are looking at
279 // currently, do not process the GEP at this time.
Nate Begemane68bcd12005-07-30 00:15:07 +0000280 if (CanReduceSCEV(Idx, L))
281 return;
282 Base = SCEVAddExpr::get(Base, GetAdjustedIndex(Idx,
283 TD->getTypeSize(GTI.getIndexedType()), UIntPtrTy));
284 }
285 }
286
287 // Get the index, convert it to intptr_t.
288 SCEVHandle GEPIndexExpr =
289 GetAdjustedIndex(SE->getSCEV(Op), TD->getTypeSize(GTI.getIndexedType()),
290 UIntPtrTy);
291
292 // Process all remaining subscripts in the GEP instruction.
293 for (++i, ++GTI; i != GEP->getNumOperands(); ++i, ++GTI)
294 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
295 const StructLayout *SL = TD->getStructLayout(STy);
296 unsigned Idx = cast<ConstantUInt>(GEP->getOperand(i))->getValue();
297 uint64_t Offset = SL->MemberOffsets[Idx];
298 Base = SCEVAddExpr::get(Base, SCEVUnknown::getIntegerSCEV(Offset,
299 UIntPtrTy));
300 } else {
301 SCEVHandle Idx = SE->getSCEV(GEP->getOperand(i));
302 if (CanReduceSCEV(Idx, L)) { // Another IV subscript
303 GEPIndexExpr = SCEVAddExpr::get(GEPIndexExpr,
304 GetAdjustedIndex(Idx, TD->getTypeSize(GTI.getIndexedType()),
305 UIntPtrTy));
306 assert(CanReduceSCEV(GEPIndexExpr, L) &&
307 "Cannot reduce the sum of two reducible SCEV's??");
308 } else {
309 Base = SCEVAddExpr::get(Base, GetAdjustedIndex(Idx,
310 TD->getTypeSize(GTI.getIndexedType()), UIntPtrTy));
311 }
312 }
313
314 assert(CanReduceSCEV(GEPIndexExpr, L) && "Non reducible idx??");
315
Chris Lattner9ef12942005-08-02 01:32:29 +0000316 // FIXME: If the base is not loop invariant, we currently cannot emit this.
317 if (!Base->isLoopInvariant(L)) {
318 DEBUG(std::cerr << "IGNORING GEP due to non-invaiant base: "
319 << *Base << "\n");
320 return;
321 }
322
Nate Begemane68bcd12005-07-30 00:15:07 +0000323 Base = SCEVAddExpr::get(Base, cast<SCEVAddRecExpr>(GEPIndexExpr)->getStart());
324 SCEVHandle Stride = cast<SCEVAddRecExpr>(GEPIndexExpr)->getOperand(1);
325
326 DEBUG(std::cerr << "GEP BASE : " << *Base << "\n");
327 DEBUG(std::cerr << "GEP STRIDE: " << *Stride << "\n");
328
329 Value *Step = 0; // Step of ISE.
330 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride))
331 /// Always get the step value as an unsigned value.
332 Step = ConstantExpr::getCast(SC->getValue(),
333 SC->getValue()->getType()->getUnsignedVersion());
334 else
335 Step = cast<SCEVUnknown>(Stride)->getValue();
336 assert(Step->getType()->isUnsigned() && "Bad step value!");
337
338
339 // Now that we know the base and stride contributed by the GEP instruction,
340 // process all users.
341 for (Value::use_iterator UI = GEP->use_begin(), E = GEP->use_end();
342 UI != E; ++UI) {
343 Instruction *User = cast<Instruction>(*UI);
344
345 // Do not infinitely recurse on PHI nodes.
346 if (isa<PHINode>(User) && User->getParent() == L->getHeader())
347 continue;
348
349 // If this is an instruction defined in a nested loop, or outside this loop,
350 // don't mess with it.
351 if (LI->getLoopFor(User->getParent()) != L)
352 continue;
353
354 DEBUG(std::cerr << "FOUND USER: " << *User
355 << " OF STRIDE: " << *Step << " BASE = " << *Base << "\n");
356
Nate Begemane68bcd12005-07-30 00:15:07 +0000357 // Okay, we found a user that we cannot reduce. Analyze the instruction
358 // and decide what to do with it.
359 IVUsesByStride[Step].addUser(Base, User, GEP);
360 }
361}
362
363/// AddUsersIfInteresting - Inspect the specified instruction. If it is a
364/// reducible SCEV, recursively add its users to the IVUsesByStride set and
365/// return true. Otherwise, return false.
366bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L) {
Nate Begeman17a0e2af2005-07-30 00:21:31 +0000367 if (I->getType() == Type::VoidTy) return false;
Nate Begemane68bcd12005-07-30 00:15:07 +0000368 SCEVHandle ISE = SE->getSCEV(I);
369 if (!CanReduceSCEV(ISE, L)) return false;
370
371 SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(ISE);
372 SCEVHandle Start = AR->getStart();
373
374 // Get the step value, canonicalizing to an unsigned integer type so that
375 // lookups in the map will match.
376 Value *Step = 0; // Step of ISE.
377 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(AR->getOperand(1)))
378 /// Always get the step value as an unsigned value.
379 Step = ConstantExpr::getCast(SC->getValue(),
380 SC->getValue()->getType()->getUnsignedVersion());
381 else
382 Step = cast<SCEVUnknown>(AR->getOperand(1))->getValue();
383 assert(Step->getType()->isUnsigned() && "Bad step value!");
384
385 std::set<GetElementPtrInst*> AnalyzedGEPs;
Jeff Cohen546fd592005-07-30 18:33:25 +0000386
Nate Begemane68bcd12005-07-30 00:15:07 +0000387 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){
388 Instruction *User = cast<Instruction>(*UI);
389
390 // Do not infinitely recurse on PHI nodes.
391 if (isa<PHINode>(User) && User->getParent() == L->getHeader())
392 continue;
393
394 // If this is an instruction defined in a nested loop, or outside this loop,
395 // don't mess with it.
396 if (LI->getLoopFor(User->getParent()) != L)
397 continue;
398
Jeff Cohen546fd592005-07-30 18:33:25 +0000399 // Next, see if this user is analyzable itself!
Nate Begemane68bcd12005-07-30 00:15:07 +0000400 if (!AddUsersIfInteresting(User, L)) {
401 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
402 // If this is a getelementptr instruction, figure out what linear
403 // expression of induction variable is actually being used.
Jeff Cohen546fd592005-07-30 18:33:25 +0000404 //
Nate Begemane68bcd12005-07-30 00:15:07 +0000405 if (AnalyzedGEPs.insert(GEP).second) // Not already analyzed?
406 AnalyzeGetElementPtrUsers(GEP, I, L);
407 } else {
408 DEBUG(std::cerr << "FOUND USER: " << *User
409 << " OF SCEV: " << *ISE << "\n");
410
411 // Okay, we found a user that we cannot reduce. Analyze the instruction
412 // and decide what to do with it.
413 IVUsesByStride[Step].addUser(Start, User, I);
414 }
415 }
416 }
417 return true;
418}
419
420namespace {
421 /// BasedUser - For a particular base value, keep information about how we've
422 /// partitioned the expression so far.
423 struct BasedUser {
424 /// Inst - The instruction using the induction variable.
425 Instruction *Inst;
426
Chris Lattner430d0022005-08-03 22:21:05 +0000427 /// OperandValToReplace - The operand value of Inst to replace with the
428 /// EmittedBase.
429 Value *OperandValToReplace;
Nate Begemane68bcd12005-07-30 00:15:07 +0000430
431 /// Imm - The immediate value that should be added to the base immediately
432 /// before Inst, because it will be folded into the imm field of the
433 /// instruction.
434 SCEVHandle Imm;
435
436 /// EmittedBase - The actual value* to use for the base value of this
437 /// operation. This is null if we should just use zero so far.
438 Value *EmittedBase;
439
Chris Lattner430d0022005-08-03 22:21:05 +0000440 BasedUser(Instruction *I, Value *Op, const SCEVHandle &IMM)
441 : Inst(I), OperandValToReplace(Op), Imm(IMM), EmittedBase(0) {}
Nate Begemane68bcd12005-07-30 00:15:07 +0000442
443
444 // No need to compare these.
445 bool operator<(const BasedUser &BU) const { return 0; }
446
447 void dump() const;
448 };
449}
450
451void BasedUser::dump() const {
452 std::cerr << " Imm=" << *Imm;
453 if (EmittedBase)
454 std::cerr << " EB=" << *EmittedBase;
455
456 std::cerr << " Inst: " << *Inst;
457}
458
459/// isTargetConstant - Return true if the following can be referenced by the
460/// immediate field of a target instruction.
461static bool isTargetConstant(const SCEVHandle &V) {
Jeff Cohen546fd592005-07-30 18:33:25 +0000462
Nate Begemane68bcd12005-07-30 00:15:07 +0000463 // FIXME: Look at the target to decide if &GV is a legal constant immediate.
464 if (isa<SCEVConstant>(V)) return true;
Jeff Cohen546fd592005-07-30 18:33:25 +0000465
Nate Begemane68bcd12005-07-30 00:15:07 +0000466 return false; // ENABLE this for x86
Jeff Cohen546fd592005-07-30 18:33:25 +0000467
Nate Begemane68bcd12005-07-30 00:15:07 +0000468 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
469 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
470 if (CE->getOpcode() == Instruction::Cast)
471 if (isa<GlobalValue>(CE->getOperand(0)))
472 // FIXME: should check to see that the dest is uintptr_t!
473 return true;
474 return false;
475}
476
477/// GetImmediateValues - Look at Val, and pull out any additions of constants
478/// that can fit into the immediate field of instructions in the target.
479static SCEVHandle GetImmediateValues(SCEVHandle Val, bool isAddress) {
480 if (!isAddress)
481 return SCEVUnknown::getIntegerSCEV(0, Val->getType());
482 if (isTargetConstant(Val))
483 return Val;
484
485 SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val);
486 if (SAE) {
487 unsigned i = 0;
488 for (; i != SAE->getNumOperands(); ++i)
489 if (isTargetConstant(SAE->getOperand(i))) {
490 SCEVHandle ImmVal = SAE->getOperand(i);
Jeff Cohen546fd592005-07-30 18:33:25 +0000491
Nate Begemane68bcd12005-07-30 00:15:07 +0000492 // If there are any other immediates that we can handle here, pull them
493 // out too.
494 for (++i; i != SAE->getNumOperands(); ++i)
495 if (isTargetConstant(SAE->getOperand(i)))
496 ImmVal = SCEVAddExpr::get(ImmVal, SAE->getOperand(i));
497 return ImmVal;
498 }
499 }
500
501 return SCEVUnknown::getIntegerSCEV(0, Val->getType());
502}
503
504/// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
505/// stride of IV. All of the users may have different starting values, and this
506/// may not be the only stride (we know it is if isOnlyStride is true).
507void LoopStrengthReduce::StrengthReduceStridedIVUsers(Value *Stride,
Chris Lattner430d0022005-08-03 22:21:05 +0000508 IVUsersOfOneStride &Uses,
509 Loop *L,
Nate Begemane68bcd12005-07-30 00:15:07 +0000510 bool isOnlyStride) {
511 // Transform our list of users and offsets to a bit more complex table. In
512 // this new vector, the first entry for each element is the base of the
513 // strided access, and the second is the BasedUser object for the use. We
514 // progressively move information from the first to the second entry, until we
515 // eventually emit the object.
516 std::vector<std::pair<SCEVHandle, BasedUser> > UsersToProcess;
517 UsersToProcess.reserve(Uses.Users.size());
Jeff Cohen546fd592005-07-30 18:33:25 +0000518
519 SCEVHandle ZeroBase = SCEVUnknown::getIntegerSCEV(0,
Chris Lattner430d0022005-08-03 22:21:05 +0000520 Uses.Users[0].Offset->getType());
Nate Begemane68bcd12005-07-30 00:15:07 +0000521
522 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i)
Chris Lattner430d0022005-08-03 22:21:05 +0000523 UsersToProcess.push_back(std::make_pair(Uses.Users[i].Offset,
524 BasedUser(Uses.Users[i].User,
525 Uses.Users[i].OperandValToReplace,
Nate Begemane68bcd12005-07-30 00:15:07 +0000526 ZeroBase)));
527
528 // First pass, figure out what we can represent in the immediate fields of
529 // instructions. If we can represent anything there, move it to the imm
530 // fields of the BasedUsers.
531 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
532 bool isAddress = isa<LoadInst>(UsersToProcess[i].second.Inst) ||
533 isa<StoreInst>(UsersToProcess[i].second.Inst);
Jeff Cohen546fd592005-07-30 18:33:25 +0000534 UsersToProcess[i].second.Imm = GetImmediateValues(UsersToProcess[i].first,
Nate Begemane68bcd12005-07-30 00:15:07 +0000535 isAddress);
536 UsersToProcess[i].first = SCEV::getMinusSCEV(UsersToProcess[i].first,
537 UsersToProcess[i].second.Imm);
538
539 DEBUG(std::cerr << "BASE: " << *UsersToProcess[i].first);
540 DEBUG(UsersToProcess[i].second.dump());
541 }
542
543 SCEVExpander Rewriter(*SE, *LI);
544 BasicBlock *Preheader = L->getLoopPreheader();
545 Instruction *PreInsertPt = Preheader->getTerminator();
546 Instruction *PhiInsertBefore = L->getHeader()->begin();
547
Jeff Cohen546fd592005-07-30 18:33:25 +0000548 assert(isa<PHINode>(PhiInsertBefore) &&
Nate Begemane68bcd12005-07-30 00:15:07 +0000549 "How could this loop have IV's without any phis?");
550 PHINode *SomeLoopPHI = cast<PHINode>(PhiInsertBefore);
551 assert(SomeLoopPHI->getNumIncomingValues() == 2 &&
552 "This loop isn't canonicalized right");
553 BasicBlock *LatchBlock =
554 SomeLoopPHI->getIncomingBlock(SomeLoopPHI->getIncomingBlock(0) == Preheader);
Jeff Cohen546fd592005-07-30 18:33:25 +0000555
Nate Begemane68bcd12005-07-30 00:15:07 +0000556 // FIXME: This loop needs increasing levels of intelligence.
Chris Lattnerdb23c742005-08-03 22:51:21 +0000557 // STAGE 0: just emit everything as its own base.
Nate Begemane68bcd12005-07-30 00:15:07 +0000558 // STAGE 1: factor out common vars from bases, and try and push resulting
Chris Lattnerdb23c742005-08-03 22:51:21 +0000559 // constants into Imm field. <-- We are here
Nate Begemane68bcd12005-07-30 00:15:07 +0000560 // STAGE 2: factor out large constants to try and make more constants
561 // acceptable for target loads and stores.
Nate Begemane68bcd12005-07-30 00:15:07 +0000562
Chris Lattnerdb23c742005-08-03 22:51:21 +0000563 // Sort by the base value, so that all IVs with identical bases are next to
564 // each other.
565 std::sort(UsersToProcess.begin(), UsersToProcess.end());
Nate Begemane68bcd12005-07-30 00:15:07 +0000566 while (!UsersToProcess.empty()) {
Chris Lattnerdb23c742005-08-03 22:51:21 +0000567 SCEVHandle Base = UsersToProcess.front().first;
568
Nate Begemane68bcd12005-07-30 00:15:07 +0000569 // Create a new Phi for this base, and stick it in the loop header.
Chris Lattnerdb23c742005-08-03 22:51:21 +0000570 const Type *ReplacedTy = Base->getType();
571 PHINode *NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
Nate Begemane68bcd12005-07-30 00:15:07 +0000572
Jeff Cohen546fd592005-07-30 18:33:25 +0000573 // Emit the initial base value into the loop preheader, and add it to the
Nate Begemane68bcd12005-07-30 00:15:07 +0000574 // Phi node.
Chris Lattnerdb23c742005-08-03 22:51:21 +0000575 Value *BaseV = Rewriter.expandCodeFor(Base, PreInsertPt, ReplacedTy);
Nate Begemane68bcd12005-07-30 00:15:07 +0000576 NewPHI->addIncoming(BaseV, Preheader);
577
578 // Emit the increment of the base value before the terminator of the loop
579 // latch block, and add it to the Phi node.
580 SCEVHandle Inc = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
581 SCEVUnknown::get(Stride));
582
583 Value *IncV = Rewriter.expandCodeFor(Inc, LatchBlock->getTerminator(),
584 ReplacedTy);
585 IncV->setName(NewPHI->getName()+".inc");
586 NewPHI->addIncoming(IncV, LatchBlock);
587
588 // Emit the code to add the immediate offset to the Phi value, just before
Chris Lattnerdb23c742005-08-03 22:51:21 +0000589 // the instructions that we identified as using this stride and base.
590 while (!UsersToProcess.empty() && UsersToProcess.front().first == Base) {
591 BasedUser &User = UsersToProcess.front().second;
Jeff Cohen546fd592005-07-30 18:33:25 +0000592
Chris Lattnerdb23c742005-08-03 22:51:21 +0000593 // Clear the SCEVExpander's expression map so that we are guaranteed
594 // to have the code emitted where we expect it.
595 Rewriter.clear();
596 SCEVHandle NewValSCEV = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
597 User.Imm);
598 Value *Replaced = UsersToProcess.front().second.OperandValToReplace;
599 Value *newVal = Rewriter.expandCodeFor(NewValSCEV, User.Inst,
600 Replaced->getType());
Jeff Cohen546fd592005-07-30 18:33:25 +0000601
Chris Lattnerdb23c742005-08-03 22:51:21 +0000602 // Replace the use of the operand Value with the new Phi we just created.
603 DEBUG(std::cerr << "REPLACING: " << *Replaced << "IN: " <<
604 *User.Inst << "WITH: "<< *newVal << '\n');
605 User.Inst->replaceUsesOfWith(Replaced, newVal);
Jeff Cohen546fd592005-07-30 18:33:25 +0000606
Chris Lattnerdb23c742005-08-03 22:51:21 +0000607 // Mark old value we replaced as possibly dead, so that it is elminated
608 // if we just replaced the last use of that value.
609 DeadInsts.insert(cast<Instruction>(Replaced));
Nate Begemane68bcd12005-07-30 00:15:07 +0000610
Chris Lattnerdb23c742005-08-03 22:51:21 +0000611 UsersToProcess.erase(UsersToProcess.begin());
612 ++NumReduced;
613 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000614 // TODO: Next, find out which base index is the most common, pull it out.
615 }
616
617 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
618 // different starting values, into different PHIs.
Jeff Cohen546fd592005-07-30 18:33:25 +0000619
Nate Begemane68bcd12005-07-30 00:15:07 +0000620 // BEFORE writing this, it's probably useful to handle GEP's.
621
622 // NOTE: pull all constants together, for REG+IMM addressing, include &GV in
623 // 'IMM' if the target supports it.
624}
625
626
Nate Begemanb18121e2004-10-18 21:08:22 +0000627void LoopStrengthReduce::runOnLoop(Loop *L) {
628 // First step, transform all loops nesting inside of this loop.
629 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
630 runOnLoop(*I);
631
Nate Begemane68bcd12005-07-30 00:15:07 +0000632 // Next, find all uses of induction variables in this loop, and catagorize
633 // them by stride. Start by finding all of the PHI nodes in the header for
634 // this loop. If they are induction variables, inspect their uses.
635 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
636 AddUsersIfInteresting(I, L);
Nate Begemanb18121e2004-10-18 21:08:22 +0000637
Nate Begemane68bcd12005-07-30 00:15:07 +0000638 // If we have nothing to do, return.
639 //if (IVUsesByStride.empty()) return;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000640
Nate Begemane68bcd12005-07-30 00:15:07 +0000641 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
642 // doing computation in byte values, promote to 32-bit values if safe.
643
644 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
645 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
646 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
647 // to be careful that IV's are all the same type. Only works for intptr_t
648 // indvars.
649
650 // If we only have one stride, we can more aggressively eliminate some things.
651 bool HasOneStride = IVUsesByStride.size() == 1;
652
Chris Lattner430d0022005-08-03 22:21:05 +0000653 for (std::map<Value*, IVUsersOfOneStride>::iterator SI
654 = IVUsesByStride.begin(), E = IVUsesByStride.end(); SI != E; ++SI)
Nate Begemane68bcd12005-07-30 00:15:07 +0000655 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
Nate Begemanb18121e2004-10-18 21:08:22 +0000656
657 // Clean up after ourselves
658 if (!DeadInsts.empty()) {
659 DeleteTriviallyDeadInstructions(DeadInsts);
660
Nate Begemane68bcd12005-07-30 00:15:07 +0000661 BasicBlock::iterator I = L->getHeader()->begin();
662 PHINode *PN;
Chris Lattnerdcce49e2005-08-02 02:44:31 +0000663 while ((PN = dyn_cast<PHINode>(I))) {
Chris Lattner564900e2005-08-02 00:41:11 +0000664 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
665
Nate Begemane68bcd12005-07-30 00:15:07 +0000666 // At this point, we know that we have killed one or more GEP instructions.
667 // It is worth checking to see if the cann indvar is also dead, so that we
668 // can remove it as well. The requirements for the cann indvar to be
669 // considered dead are:
670 // 1. the cann indvar has one use
671 // 2. the use is an add instruction
672 // 3. the add has one use
673 // 4. the add is used by the cann indvar
674 // If all four cases above are true, then we can remove both the add and
675 // the cann indvar.
676 // FIXME: this needs to eliminate an induction variable even if it's being
677 // compared against some value to decide loop termination.
678 if (PN->hasOneUse()) {
679 BinaryOperator *BO = dyn_cast<BinaryOperator>(*(PN->use_begin()));
Chris Lattner75a44e12005-08-02 02:52:02 +0000680 if (BO && BO->hasOneUse()) {
681 if (PN == *(BO->use_begin())) {
682 DeadInsts.insert(BO);
683 // Break the cycle, then delete the PHI.
684 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattner84e9baa2005-08-03 21:36:09 +0000685 SE->deleteInstructionFromRecords(PN);
Chris Lattner75a44e12005-08-02 02:52:02 +0000686 PN->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +0000687 }
Chris Lattner75a44e12005-08-02 02:52:02 +0000688 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000689 }
Nate Begemanb18121e2004-10-18 21:08:22 +0000690 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000691 DeleteTriviallyDeadInstructions(DeadInsts);
Nate Begemanb18121e2004-10-18 21:08:22 +0000692 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000693
694 IVUsesByStride.clear();
Chris Lattnerdcce49e2005-08-02 02:44:31 +0000695 CastedBasePointers.clear();
Nate Begemane68bcd12005-07-30 00:15:07 +0000696 return;
Nate Begemanb18121e2004-10-18 21:08:22 +0000697}