blob: ddce7511042416f3f8ae905cdad1735387aefd6d [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
Chris Lattnerbb78c972005-08-03 23:30:08 +000018#define DEBUG_TYPE "loop-reduce"
Nate Begemanb18121e2004-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 Cohena2c59b72005-03-04 04:04:26 +000023#include "llvm/DerivedTypes.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000024#include "llvm/Analysis/Dominators.h"
25#include "llvm/Analysis/LoopInfo.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000026#include "llvm/Analysis/ScalarEvolutionExpander.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000027#include "llvm/Support/CFG.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000028#include "llvm/Support/GetElementPtrTypeIterator.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000029#include "llvm/Transforms/Utils/Local.h"
Jeff Cohena2c59b72005-03-04 04:04:26 +000030#include "llvm/Target/TargetData.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000031#include "llvm/ADT/Statistic.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000032#include "llvm/Support/Debug.h"
Jeff Cohenc5009912005-07-30 18:22:27 +000033#include <algorithm>
Nate Begemanb18121e2004-10-18 21:08:22 +000034#include <set>
35using namespace llvm;
36
37namespace {
38 Statistic<> NumReduced ("loop-reduce", "Number of GEPs strength reduced");
39
Chris Lattnerd3874fa2005-03-06 21:58:22 +000040 class GEPCache {
Jeff Cohenbe37fa02005-03-05 22:40:34 +000041 public:
42 GEPCache() : CachedPHINode(0), Map() {}
43
Chris Lattnerd3874fa2005-03-06 21:58:22 +000044 GEPCache *get(Value *v) {
Jeff Cohenbe37fa02005-03-05 22:40:34 +000045 std::map<Value *, GEPCache>::iterator I = Map.find(v);
46 if (I == Map.end())
47 I = Map.insert(std::pair<Value *, GEPCache>(v, GEPCache())).first;
Chris Lattnerd3874fa2005-03-06 21:58:22 +000048 return &I->second;
Jeff Cohenbe37fa02005-03-05 22:40:34 +000049 }
50
51 PHINode *CachedPHINode;
52 std::map<Value *, GEPCache> Map;
53 };
Chris Lattner430d0022005-08-03 22:21:05 +000054
55 /// IVStrideUse - Keep track of one use of a strided induction variable, where
56 /// the stride is stored externally. The Offset member keeps track of the
57 /// offset from the IV, User is the actual user of the operand, and 'Operand'
58 /// is the operand # of the User that is the use.
59 struct IVStrideUse {
60 SCEVHandle Offset;
61 Instruction *User;
62 Value *OperandValToReplace;
63
64 IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
65 : Offset(Offs), User(U), OperandValToReplace(O) {}
66 };
67
68 /// IVUsersOfOneStride - This structure keeps track of all instructions that
69 /// have an operand that is based on the trip count multiplied by some stride.
70 /// The stride for all of these users is common and kept external to this
71 /// structure.
72 struct IVUsersOfOneStride {
Nate Begemane68bcd12005-07-30 00:15:07 +000073 /// Users - Keep track of all of the users of this stride as well as the
Chris Lattner430d0022005-08-03 22:21:05 +000074 /// initial value and the operand that uses the IV.
75 std::vector<IVStrideUse> Users;
76
77 void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
78 Users.push_back(IVStrideUse(Offset, User, Operand));
Nate Begemane68bcd12005-07-30 00:15:07 +000079 }
80 };
81
82
Nate Begemanb18121e2004-10-18 21:08:22 +000083 class LoopStrengthReduce : public FunctionPass {
84 LoopInfo *LI;
85 DominatorSet *DS;
Nate Begemane68bcd12005-07-30 00:15:07 +000086 ScalarEvolution *SE;
87 const TargetData *TD;
88 const Type *UIntPtrTy;
Nate Begemanb18121e2004-10-18 21:08:22 +000089 bool Changed;
Chris Lattner75a44e12005-08-02 02:52:02 +000090
91 /// MaxTargetAMSize - This is the maximum power-of-two scale value that the
92 /// target can handle for free with its addressing modes.
Jeff Cohena2c59b72005-03-04 04:04:26 +000093 unsigned MaxTargetAMSize;
Nate Begemane68bcd12005-07-30 00:15:07 +000094
95 /// IVUsesByStride - Keep track of all uses of induction variables that we
96 /// are interested in. The key of the map is the stride of the access.
Chris Lattner430d0022005-08-03 22:21:05 +000097 std::map<Value*, IVUsersOfOneStride> IVUsesByStride;
Nate Begemane68bcd12005-07-30 00:15:07 +000098
99 /// CastedBasePointers - As we need to lower getelementptr instructions, we
100 /// cast the pointer input to uintptr_t. This keeps track of the casted
101 /// values for the pointers we have processed so far.
102 std::map<Value*, Value*> CastedBasePointers;
103
104 /// DeadInsts - Keep track of instructions we may have made dead, so that
105 /// we can remove them after we are done working.
106 std::set<Instruction*> DeadInsts;
Nate Begemanb18121e2004-10-18 21:08:22 +0000107 public:
Jeff Cohena2c59b72005-03-04 04:04:26 +0000108 LoopStrengthReduce(unsigned MTAMS = 1)
109 : MaxTargetAMSize(MTAMS) {
110 }
111
Nate Begemanb18121e2004-10-18 21:08:22 +0000112 virtual bool runOnFunction(Function &) {
113 LI = &getAnalysis<LoopInfo>();
114 DS = &getAnalysis<DominatorSet>();
Nate Begemane68bcd12005-07-30 00:15:07 +0000115 SE = &getAnalysis<ScalarEvolution>();
116 TD = &getAnalysis<TargetData>();
117 UIntPtrTy = TD->getIntPtrType();
Nate Begemanb18121e2004-10-18 21:08:22 +0000118 Changed = false;
119
120 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
121 runOnLoop(*I);
122 return Changed;
123 }
124
125 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
126 AU.setPreservesCFG();
Jeff Cohen39751c32005-02-27 19:37:07 +0000127 AU.addRequiredID(LoopSimplifyID);
Nate Begemanb18121e2004-10-18 21:08:22 +0000128 AU.addRequired<LoopInfo>();
129 AU.addRequired<DominatorSet>();
Jeff Cohena2c59b72005-03-04 04:04:26 +0000130 AU.addRequired<TargetData>();
Nate Begemane68bcd12005-07-30 00:15:07 +0000131 AU.addRequired<ScalarEvolution>();
Nate Begemanb18121e2004-10-18 21:08:22 +0000132 }
133 private:
134 void runOnLoop(Loop *L);
Nate Begemane68bcd12005-07-30 00:15:07 +0000135 bool AddUsersIfInteresting(Instruction *I, Loop *L);
136 void AnalyzeGetElementPtrUsers(GetElementPtrInst *GEP, Instruction *I,
137 Loop *L);
138
Chris Lattner430d0022005-08-03 22:21:05 +0000139 void StrengthReduceStridedIVUsers(Value *Stride, IVUsersOfOneStride &Uses,
140 Loop *L, bool isOnlyStride);
Nate Begemane68bcd12005-07-30 00:15:07 +0000141
Nate Begemanb18121e2004-10-18 21:08:22 +0000142 void strengthReduceGEP(GetElementPtrInst *GEPI, Loop *L,
Jeff Cohenbe37fa02005-03-05 22:40:34 +0000143 GEPCache* GEPCache,
Nate Begemanb18121e2004-10-18 21:08:22 +0000144 Instruction *InsertBefore,
145 std::set<Instruction*> &DeadInsts);
146 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
147 };
Misha Brukmanb1c93172005-04-21 23:48:37 +0000148 RegisterOpt<LoopStrengthReduce> X("loop-reduce",
Nate Begemanb18121e2004-10-18 21:08:22 +0000149 "Strength Reduce GEP Uses of Ind. Vars");
150}
151
Jeff Cohena2c59b72005-03-04 04:04:26 +0000152FunctionPass *llvm::createLoopStrengthReducePass(unsigned MaxTargetAMSize) {
153 return new LoopStrengthReduce(MaxTargetAMSize);
Nate Begemanb18121e2004-10-18 21:08:22 +0000154}
155
156/// DeleteTriviallyDeadInstructions - If any of the instructions is the
157/// specified set are trivially dead, delete them and see if this makes any of
158/// their operands subsequently dead.
159void LoopStrengthReduce::
160DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
161 while (!Insts.empty()) {
162 Instruction *I = *Insts.begin();
163 Insts.erase(Insts.begin());
164 if (isInstructionTriviallyDead(I)) {
Jeff Cohen8ea6f9e2005-03-01 03:46:11 +0000165 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
166 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
167 Insts.insert(U);
Chris Lattner84e9baa2005-08-03 21:36:09 +0000168 SE->deleteInstructionFromRecords(I);
169 I->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +0000170 Changed = true;
171 }
172 }
173}
174
Jeff Cohen39751c32005-02-27 19:37:07 +0000175
Nate Begemane68bcd12005-07-30 00:15:07 +0000176/// CanReduceSCEV - Return true if we can strength reduce this scalar evolution
177/// in the specified loop.
178static bool CanReduceSCEV(const SCEVHandle &SH, Loop *L) {
179 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SH);
180 if (!AddRec || AddRec->getLoop() != L) return false;
Jeff Cohena2c59b72005-03-04 04:04:26 +0000181
Nate Begemane68bcd12005-07-30 00:15:07 +0000182 // FIXME: Generalize to non-affine IV's.
183 if (!AddRec->isAffine()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000184
Nate Begemane68bcd12005-07-30 00:15:07 +0000185 // FIXME: generalize to IV's with more complex strides (must emit stride
186 // expression outside of loop!)
187 if (isa<SCEVConstant>(AddRec->getOperand(1)))
188 return true;
Jeff Cohena2c59b72005-03-04 04:04:26 +0000189
Nate Begemane68bcd12005-07-30 00:15:07 +0000190 // We handle steps by unsigned values, because we know we won't have to insert
191 // a cast for them.
192 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(AddRec->getOperand(1)))
193 if (SU->getValue()->getType()->isUnsigned())
194 return true;
Jeff Cohen546fd592005-07-30 18:33:25 +0000195
Nate Begemane68bcd12005-07-30 00:15:07 +0000196 // Otherwise, no, we can't handle it yet.
197 return false;
Nate Begemanb18121e2004-10-18 21:08:22 +0000198}
199
Nate Begemane68bcd12005-07-30 00:15:07 +0000200
201/// GetAdjustedIndex - Adjust the specified GEP sequential type index to match
202/// the size of the pointer type, and scale it by the type size.
203static SCEVHandle GetAdjustedIndex(const SCEVHandle &Idx, uint64_t TySize,
204 const Type *UIntPtrTy) {
205 SCEVHandle Result = Idx;
206 if (Result->getType()->getUnsignedVersion() != UIntPtrTy) {
207 if (UIntPtrTy->getPrimitiveSize() < Result->getType()->getPrimitiveSize())
208 Result = SCEVTruncateExpr::get(Result, UIntPtrTy);
209 else
210 Result = SCEVZeroExtendExpr::get(Result, UIntPtrTy);
211 }
212
213 // This index is scaled by the type size being indexed.
214 if (TySize != 1)
Jeff Cohen546fd592005-07-30 18:33:25 +0000215 Result = SCEVMulExpr::get(Result,
Nate Begemane68bcd12005-07-30 00:15:07 +0000216 SCEVConstant::get(ConstantUInt::get(UIntPtrTy,
217 TySize)));
218 return Result;
219}
220
221/// AnalyzeGetElementPtrUsers - Analyze all of the users of the specified
222/// getelementptr instruction, adding them to the IVUsesByStride table. Note
223/// that we only want to analyze a getelementptr instruction once, and it can
224/// have multiple operands that are uses of the indvar (e.g. A[i][i]). Because
225/// of this, we only process a GEP instruction if its first recurrent operand is
226/// "op", otherwise we will either have already processed it or we will sometime
227/// later.
228void LoopStrengthReduce::AnalyzeGetElementPtrUsers(GetElementPtrInst *GEP,
229 Instruction *Op, Loop *L) {
230 // Analyze all of the subscripts of this getelementptr instruction, looking
231 // for uses that are determined by the trip count of L. First, skip all
232 // operands the are not dependent on the IV.
233
234 // Build up the base expression. Insert an LLVM cast of the pointer to
235 // uintptr_t first.
236 Value *BasePtr;
237 if (Constant *CB = dyn_cast<Constant>(GEP->getOperand(0)))
238 BasePtr = ConstantExpr::getCast(CB, UIntPtrTy);
Jeff Cohen546fd592005-07-30 18:33:25 +0000239 else {
Nate Begemane68bcd12005-07-30 00:15:07 +0000240 Value *&BP = CastedBasePointers[GEP->getOperand(0)];
241 if (BP == 0) {
242 BasicBlock::iterator InsertPt;
243 if (isa<Argument>(GEP->getOperand(0))) {
244 InsertPt = GEP->getParent()->getParent()->begin()->begin();
245 } else {
246 InsertPt = cast<Instruction>(GEP->getOperand(0));
247 if (InvokeInst *II = dyn_cast<InvokeInst>(GEP->getOperand(0)))
248 InsertPt = II->getNormalDest()->begin();
249 else
250 ++InsertPt;
251 }
Chris Lattner351b8912005-08-02 03:31:14 +0000252
253 // Do not insert casts into the middle of PHI node blocks.
254 while (isa<PHINode>(InsertPt)) ++InsertPt;
255
Nate Begemane68bcd12005-07-30 00:15:07 +0000256 BP = new CastInst(GEP->getOperand(0), UIntPtrTy,
257 GEP->getOperand(0)->getName(), InsertPt);
258 }
259 BasePtr = BP;
260 }
261
262 SCEVHandle Base = SCEVUnknown::get(BasePtr);
263
264 gep_type_iterator GTI = gep_type_begin(GEP);
265 unsigned i = 1;
266 for (; GEP->getOperand(i) != Op; ++i, ++GTI) {
267 // If this is a use of a recurrence that we can analyze, and it comes before
268 // Op does in the GEP operand list, we will handle this when we process this
269 // operand.
270 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
271 const StructLayout *SL = TD->getStructLayout(STy);
272 unsigned Idx = cast<ConstantUInt>(GEP->getOperand(i))->getValue();
273 uint64_t Offset = SL->MemberOffsets[Idx];
274 Base = SCEVAddExpr::get(Base, SCEVUnknown::getIntegerSCEV(Offset,
275 UIntPtrTy));
276 } else {
277 SCEVHandle Idx = SE->getSCEV(GEP->getOperand(i));
Chris Lattner9ef12942005-08-02 01:32:29 +0000278
279 // If this operand is reducible, and it's not the one we are looking at
280 // currently, do not process the GEP at this time.
Nate Begemane68bcd12005-07-30 00:15:07 +0000281 if (CanReduceSCEV(Idx, L))
282 return;
283 Base = SCEVAddExpr::get(Base, GetAdjustedIndex(Idx,
284 TD->getTypeSize(GTI.getIndexedType()), UIntPtrTy));
285 }
286 }
287
288 // Get the index, convert it to intptr_t.
289 SCEVHandle GEPIndexExpr =
290 GetAdjustedIndex(SE->getSCEV(Op), TD->getTypeSize(GTI.getIndexedType()),
291 UIntPtrTy);
292
293 // Process all remaining subscripts in the GEP instruction.
294 for (++i, ++GTI; i != GEP->getNumOperands(); ++i, ++GTI)
295 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
296 const StructLayout *SL = TD->getStructLayout(STy);
297 unsigned Idx = cast<ConstantUInt>(GEP->getOperand(i))->getValue();
298 uint64_t Offset = SL->MemberOffsets[Idx];
299 Base = SCEVAddExpr::get(Base, SCEVUnknown::getIntegerSCEV(Offset,
300 UIntPtrTy));
301 } else {
302 SCEVHandle Idx = SE->getSCEV(GEP->getOperand(i));
303 if (CanReduceSCEV(Idx, L)) { // Another IV subscript
304 GEPIndexExpr = SCEVAddExpr::get(GEPIndexExpr,
305 GetAdjustedIndex(Idx, TD->getTypeSize(GTI.getIndexedType()),
306 UIntPtrTy));
307 assert(CanReduceSCEV(GEPIndexExpr, L) &&
308 "Cannot reduce the sum of two reducible SCEV's??");
309 } else {
310 Base = SCEVAddExpr::get(Base, GetAdjustedIndex(Idx,
311 TD->getTypeSize(GTI.getIndexedType()), UIntPtrTy));
312 }
313 }
314
315 assert(CanReduceSCEV(GEPIndexExpr, L) && "Non reducible idx??");
316
Chris Lattner9ef12942005-08-02 01:32:29 +0000317 // FIXME: If the base is not loop invariant, we currently cannot emit this.
318 if (!Base->isLoopInvariant(L)) {
319 DEBUG(std::cerr << "IGNORING GEP due to non-invaiant base: "
320 << *Base << "\n");
321 return;
322 }
323
Nate Begemane68bcd12005-07-30 00:15:07 +0000324 Base = SCEVAddExpr::get(Base, cast<SCEVAddRecExpr>(GEPIndexExpr)->getStart());
325 SCEVHandle Stride = cast<SCEVAddRecExpr>(GEPIndexExpr)->getOperand(1);
326
327 DEBUG(std::cerr << "GEP BASE : " << *Base << "\n");
328 DEBUG(std::cerr << "GEP STRIDE: " << *Stride << "\n");
329
330 Value *Step = 0; // Step of ISE.
331 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride))
332 /// Always get the step value as an unsigned value.
333 Step = ConstantExpr::getCast(SC->getValue(),
334 SC->getValue()->getType()->getUnsignedVersion());
335 else
336 Step = cast<SCEVUnknown>(Stride)->getValue();
337 assert(Step->getType()->isUnsigned() && "Bad step value!");
338
339
340 // Now that we know the base and stride contributed by the GEP instruction,
341 // process all users.
342 for (Value::use_iterator UI = GEP->use_begin(), E = GEP->use_end();
343 UI != E; ++UI) {
344 Instruction *User = cast<Instruction>(*UI);
345
346 // Do not infinitely recurse on PHI nodes.
347 if (isa<PHINode>(User) && User->getParent() == L->getHeader())
348 continue;
349
350 // If this is an instruction defined in a nested loop, or outside this loop,
351 // don't mess with it.
352 if (LI->getLoopFor(User->getParent()) != L)
353 continue;
354
355 DEBUG(std::cerr << "FOUND USER: " << *User
356 << " OF STRIDE: " << *Step << " BASE = " << *Base << "\n");
357
Nate Begemane68bcd12005-07-30 00:15:07 +0000358 // Okay, we found a user that we cannot reduce. Analyze the instruction
359 // and decide what to do with it.
360 IVUsesByStride[Step].addUser(Base, User, GEP);
361 }
362}
363
364/// AddUsersIfInteresting - Inspect the specified instruction. If it is a
365/// reducible SCEV, recursively add its users to the IVUsesByStride set and
366/// return true. Otherwise, return false.
367bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L) {
Nate Begeman17a0e2af2005-07-30 00:21:31 +0000368 if (I->getType() == Type::VoidTy) return false;
Nate Begemane68bcd12005-07-30 00:15:07 +0000369 SCEVHandle ISE = SE->getSCEV(I);
370 if (!CanReduceSCEV(ISE, L)) return false;
371
372 SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(ISE);
373 SCEVHandle Start = AR->getStart();
374
375 // Get the step value, canonicalizing to an unsigned integer type so that
376 // lookups in the map will match.
377 Value *Step = 0; // Step of ISE.
378 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(AR->getOperand(1)))
379 /// Always get the step value as an unsigned value.
380 Step = ConstantExpr::getCast(SC->getValue(),
381 SC->getValue()->getType()->getUnsignedVersion());
382 else
383 Step = cast<SCEVUnknown>(AR->getOperand(1))->getValue();
384 assert(Step->getType()->isUnsigned() && "Bad step value!");
385
386 std::set<GetElementPtrInst*> AnalyzedGEPs;
Jeff Cohen546fd592005-07-30 18:33:25 +0000387
Nate Begemane68bcd12005-07-30 00:15:07 +0000388 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){
389 Instruction *User = cast<Instruction>(*UI);
390
391 // Do not infinitely recurse on PHI nodes.
392 if (isa<PHINode>(User) && User->getParent() == L->getHeader())
393 continue;
394
395 // If this is an instruction defined in a nested loop, or outside this loop,
396 // don't mess with it.
397 if (LI->getLoopFor(User->getParent()) != L)
398 continue;
399
Jeff Cohen546fd592005-07-30 18:33:25 +0000400 // Next, see if this user is analyzable itself!
Nate Begemane68bcd12005-07-30 00:15:07 +0000401 if (!AddUsersIfInteresting(User, L)) {
402 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
403 // If this is a getelementptr instruction, figure out what linear
404 // expression of induction variable is actually being used.
Jeff Cohen546fd592005-07-30 18:33:25 +0000405 //
Nate Begemane68bcd12005-07-30 00:15:07 +0000406 if (AnalyzedGEPs.insert(GEP).second) // Not already analyzed?
407 AnalyzeGetElementPtrUsers(GEP, I, L);
408 } else {
409 DEBUG(std::cerr << "FOUND USER: " << *User
410 << " OF SCEV: " << *ISE << "\n");
411
412 // Okay, we found a user that we cannot reduce. Analyze the instruction
413 // and decide what to do with it.
414 IVUsesByStride[Step].addUser(Start, User, I);
415 }
416 }
417 }
418 return true;
419}
420
421namespace {
422 /// BasedUser - For a particular base value, keep information about how we've
423 /// partitioned the expression so far.
424 struct BasedUser {
425 /// Inst - The instruction using the induction variable.
426 Instruction *Inst;
427
Chris Lattner430d0022005-08-03 22:21:05 +0000428 /// OperandValToReplace - The operand value of Inst to replace with the
429 /// EmittedBase.
430 Value *OperandValToReplace;
Nate Begemane68bcd12005-07-30 00:15:07 +0000431
432 /// Imm - The immediate value that should be added to the base immediately
433 /// before Inst, because it will be folded into the imm field of the
434 /// instruction.
435 SCEVHandle Imm;
436
437 /// EmittedBase - The actual value* to use for the base value of this
438 /// operation. This is null if we should just use zero so far.
439 Value *EmittedBase;
440
Chris Lattner430d0022005-08-03 22:21:05 +0000441 BasedUser(Instruction *I, Value *Op, const SCEVHandle &IMM)
442 : Inst(I), OperandValToReplace(Op), Imm(IMM), EmittedBase(0) {}
Nate Begemane68bcd12005-07-30 00:15:07 +0000443
444
445 // No need to compare these.
446 bool operator<(const BasedUser &BU) const { return 0; }
447
448 void dump() const;
449 };
450}
451
452void BasedUser::dump() const {
453 std::cerr << " Imm=" << *Imm;
454 if (EmittedBase)
455 std::cerr << " EB=" << *EmittedBase;
456
457 std::cerr << " Inst: " << *Inst;
458}
459
460/// isTargetConstant - Return true if the following can be referenced by the
461/// immediate field of a target instruction.
462static bool isTargetConstant(const SCEVHandle &V) {
Jeff Cohen546fd592005-07-30 18:33:25 +0000463
Nate Begemane68bcd12005-07-30 00:15:07 +0000464 // FIXME: Look at the target to decide if &GV is a legal constant immediate.
465 if (isa<SCEVConstant>(V)) return true;
Jeff Cohen546fd592005-07-30 18:33:25 +0000466
Nate Begemane68bcd12005-07-30 00:15:07 +0000467 return false; // ENABLE this for x86
Jeff Cohen546fd592005-07-30 18:33:25 +0000468
Nate Begemane68bcd12005-07-30 00:15:07 +0000469 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
470 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
471 if (CE->getOpcode() == Instruction::Cast)
472 if (isa<GlobalValue>(CE->getOperand(0)))
473 // FIXME: should check to see that the dest is uintptr_t!
474 return true;
475 return false;
476}
477
478/// GetImmediateValues - Look at Val, and pull out any additions of constants
479/// that can fit into the immediate field of instructions in the target.
480static SCEVHandle GetImmediateValues(SCEVHandle Val, bool isAddress) {
481 if (!isAddress)
482 return SCEVUnknown::getIntegerSCEV(0, Val->getType());
483 if (isTargetConstant(Val))
484 return Val;
485
486 SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val);
487 if (SAE) {
488 unsigned i = 0;
489 for (; i != SAE->getNumOperands(); ++i)
490 if (isTargetConstant(SAE->getOperand(i))) {
491 SCEVHandle ImmVal = SAE->getOperand(i);
Jeff Cohen546fd592005-07-30 18:33:25 +0000492
Nate Begemane68bcd12005-07-30 00:15:07 +0000493 // If there are any other immediates that we can handle here, pull them
494 // out too.
495 for (++i; i != SAE->getNumOperands(); ++i)
496 if (isTargetConstant(SAE->getOperand(i)))
497 ImmVal = SCEVAddExpr::get(ImmVal, SAE->getOperand(i));
498 return ImmVal;
499 }
500 }
501
502 return SCEVUnknown::getIntegerSCEV(0, Val->getType());
503}
504
505/// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
506/// stride of IV. All of the users may have different starting values, and this
507/// may not be the only stride (we know it is if isOnlyStride is true).
508void LoopStrengthReduce::StrengthReduceStridedIVUsers(Value *Stride,
Chris Lattner430d0022005-08-03 22:21:05 +0000509 IVUsersOfOneStride &Uses,
510 Loop *L,
Nate Begemane68bcd12005-07-30 00:15:07 +0000511 bool isOnlyStride) {
512 // Transform our list of users and offsets to a bit more complex table. In
513 // this new vector, the first entry for each element is the base of the
514 // strided access, and the second is the BasedUser object for the use. We
515 // progressively move information from the first to the second entry, until we
516 // eventually emit the object.
517 std::vector<std::pair<SCEVHandle, BasedUser> > UsersToProcess;
518 UsersToProcess.reserve(Uses.Users.size());
Jeff Cohen546fd592005-07-30 18:33:25 +0000519
520 SCEVHandle ZeroBase = SCEVUnknown::getIntegerSCEV(0,
Chris Lattner430d0022005-08-03 22:21:05 +0000521 Uses.Users[0].Offset->getType());
Nate Begemane68bcd12005-07-30 00:15:07 +0000522
523 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i)
Chris Lattner430d0022005-08-03 22:21:05 +0000524 UsersToProcess.push_back(std::make_pair(Uses.Users[i].Offset,
525 BasedUser(Uses.Users[i].User,
526 Uses.Users[i].OperandValToReplace,
Nate Begemane68bcd12005-07-30 00:15:07 +0000527 ZeroBase)));
528
529 // First pass, figure out what we can represent in the immediate fields of
530 // instructions. If we can represent anything there, move it to the imm
531 // fields of the BasedUsers.
532 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
533 bool isAddress = isa<LoadInst>(UsersToProcess[i].second.Inst) ||
534 isa<StoreInst>(UsersToProcess[i].second.Inst);
Jeff Cohen546fd592005-07-30 18:33:25 +0000535 UsersToProcess[i].second.Imm = GetImmediateValues(UsersToProcess[i].first,
Nate Begemane68bcd12005-07-30 00:15:07 +0000536 isAddress);
537 UsersToProcess[i].first = SCEV::getMinusSCEV(UsersToProcess[i].first,
538 UsersToProcess[i].second.Imm);
539
540 DEBUG(std::cerr << "BASE: " << *UsersToProcess[i].first);
541 DEBUG(UsersToProcess[i].second.dump());
542 }
543
544 SCEVExpander Rewriter(*SE, *LI);
545 BasicBlock *Preheader = L->getLoopPreheader();
546 Instruction *PreInsertPt = Preheader->getTerminator();
547 Instruction *PhiInsertBefore = L->getHeader()->begin();
548
Jeff Cohen546fd592005-07-30 18:33:25 +0000549 assert(isa<PHINode>(PhiInsertBefore) &&
Nate Begemane68bcd12005-07-30 00:15:07 +0000550 "How could this loop have IV's without any phis?");
551 PHINode *SomeLoopPHI = cast<PHINode>(PhiInsertBefore);
552 assert(SomeLoopPHI->getNumIncomingValues() == 2 &&
553 "This loop isn't canonicalized right");
554 BasicBlock *LatchBlock =
555 SomeLoopPHI->getIncomingBlock(SomeLoopPHI->getIncomingBlock(0) == Preheader);
Jeff Cohen546fd592005-07-30 18:33:25 +0000556
Chris Lattnerbb78c972005-08-03 23:30:08 +0000557 DEBUG(std::cerr << "INSERTING IVs of STRIDE " << *Stride << ":\n");
558
Nate Begemane68bcd12005-07-30 00:15:07 +0000559 // FIXME: This loop needs increasing levels of intelligence.
Chris Lattnerdb23c742005-08-03 22:51:21 +0000560 // STAGE 0: just emit everything as its own base.
Nate Begemane68bcd12005-07-30 00:15:07 +0000561 // STAGE 1: factor out common vars from bases, and try and push resulting
Chris Lattnerdb23c742005-08-03 22:51:21 +0000562 // constants into Imm field. <-- We are here
Nate Begemane68bcd12005-07-30 00:15:07 +0000563 // STAGE 2: factor out large constants to try and make more constants
564 // acceptable for target loads and stores.
Nate Begemane68bcd12005-07-30 00:15:07 +0000565
Chris Lattnerdb23c742005-08-03 22:51:21 +0000566 // Sort by the base value, so that all IVs with identical bases are next to
567 // each other.
568 std::sort(UsersToProcess.begin(), UsersToProcess.end());
Nate Begemane68bcd12005-07-30 00:15:07 +0000569 while (!UsersToProcess.empty()) {
Chris Lattnerdb23c742005-08-03 22:51:21 +0000570 SCEVHandle Base = UsersToProcess.front().first;
Chris Lattnerbb78c972005-08-03 23:30:08 +0000571
572 DEBUG(std::cerr << " INSERTING PHI with BASE = " << *Base << ":\n");
573
Nate Begemane68bcd12005-07-30 00:15:07 +0000574 // Create a new Phi for this base, and stick it in the loop header.
Chris Lattnerdb23c742005-08-03 22:51:21 +0000575 const Type *ReplacedTy = Base->getType();
576 PHINode *NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
Nate Begemane68bcd12005-07-30 00:15:07 +0000577
Jeff Cohen546fd592005-07-30 18:33:25 +0000578 // Emit the initial base value into the loop preheader, and add it to the
Nate Begemane68bcd12005-07-30 00:15:07 +0000579 // Phi node.
Chris Lattnerdb23c742005-08-03 22:51:21 +0000580 Value *BaseV = Rewriter.expandCodeFor(Base, PreInsertPt, ReplacedTy);
Nate Begemane68bcd12005-07-30 00:15:07 +0000581 NewPHI->addIncoming(BaseV, Preheader);
582
583 // Emit the increment of the base value before the terminator of the loop
584 // latch block, and add it to the Phi node.
585 SCEVHandle Inc = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
586 SCEVUnknown::get(Stride));
587
588 Value *IncV = Rewriter.expandCodeFor(Inc, LatchBlock->getTerminator(),
589 ReplacedTy);
590 IncV->setName(NewPHI->getName()+".inc");
591 NewPHI->addIncoming(IncV, LatchBlock);
592
593 // Emit the code to add the immediate offset to the Phi value, just before
Chris Lattnerdb23c742005-08-03 22:51:21 +0000594 // the instructions that we identified as using this stride and base.
595 while (!UsersToProcess.empty() && UsersToProcess.front().first == Base) {
596 BasedUser &User = UsersToProcess.front().second;
Jeff Cohen546fd592005-07-30 18:33:25 +0000597
Chris Lattnerdb23c742005-08-03 22:51:21 +0000598 // Clear the SCEVExpander's expression map so that we are guaranteed
599 // to have the code emitted where we expect it.
600 Rewriter.clear();
601 SCEVHandle NewValSCEV = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
602 User.Imm);
Chris Lattnerbb78c972005-08-03 23:30:08 +0000603 Value *Replaced = User.OperandValToReplace;
Chris Lattnerdb23c742005-08-03 22:51:21 +0000604 Value *newVal = Rewriter.expandCodeFor(NewValSCEV, User.Inst,
605 Replaced->getType());
Jeff Cohen546fd592005-07-30 18:33:25 +0000606
Chris Lattnerdb23c742005-08-03 22:51:21 +0000607 // Replace the use of the operand Value with the new Phi we just created.
Chris Lattnerdb23c742005-08-03 22:51:21 +0000608 User.Inst->replaceUsesOfWith(Replaced, newVal);
Chris Lattnerbb78c972005-08-03 23:30:08 +0000609 DEBUG(std::cerr << " CHANGED: IMM =" << *User.Imm << " Inst = "
610 << *User.Inst);
Jeff Cohen546fd592005-07-30 18:33:25 +0000611
Chris Lattnerdb23c742005-08-03 22:51:21 +0000612 // Mark old value we replaced as possibly dead, so that it is elminated
613 // if we just replaced the last use of that value.
614 DeadInsts.insert(cast<Instruction>(Replaced));
Nate Begemane68bcd12005-07-30 00:15:07 +0000615
Chris Lattnerdb23c742005-08-03 22:51:21 +0000616 UsersToProcess.erase(UsersToProcess.begin());
617 ++NumReduced;
618 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000619 // TODO: Next, find out which base index is the most common, pull it out.
620 }
621
622 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
623 // different starting values, into different PHIs.
Jeff Cohen546fd592005-07-30 18:33:25 +0000624
Nate Begemane68bcd12005-07-30 00:15:07 +0000625 // BEFORE writing this, it's probably useful to handle GEP's.
626
627 // NOTE: pull all constants together, for REG+IMM addressing, include &GV in
628 // 'IMM' if the target supports it.
629}
630
631
Nate Begemanb18121e2004-10-18 21:08:22 +0000632void LoopStrengthReduce::runOnLoop(Loop *L) {
633 // First step, transform all loops nesting inside of this loop.
634 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
635 runOnLoop(*I);
636
Nate Begemane68bcd12005-07-30 00:15:07 +0000637 // Next, find all uses of induction variables in this loop, and catagorize
638 // them by stride. Start by finding all of the PHI nodes in the header for
639 // this loop. If they are induction variables, inspect their uses.
640 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
641 AddUsersIfInteresting(I, L);
Nate Begemanb18121e2004-10-18 21:08:22 +0000642
Nate Begemane68bcd12005-07-30 00:15:07 +0000643 // If we have nothing to do, return.
644 //if (IVUsesByStride.empty()) return;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000645
Nate Begemane68bcd12005-07-30 00:15:07 +0000646 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
647 // doing computation in byte values, promote to 32-bit values if safe.
648
649 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
650 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
651 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
652 // to be careful that IV's are all the same type. Only works for intptr_t
653 // indvars.
654
655 // If we only have one stride, we can more aggressively eliminate some things.
656 bool HasOneStride = IVUsesByStride.size() == 1;
657
Chris Lattner430d0022005-08-03 22:21:05 +0000658 for (std::map<Value*, IVUsersOfOneStride>::iterator SI
659 = IVUsesByStride.begin(), E = IVUsesByStride.end(); SI != E; ++SI)
Nate Begemane68bcd12005-07-30 00:15:07 +0000660 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
Nate Begemanb18121e2004-10-18 21:08:22 +0000661
662 // Clean up after ourselves
663 if (!DeadInsts.empty()) {
664 DeleteTriviallyDeadInstructions(DeadInsts);
665
Nate Begemane68bcd12005-07-30 00:15:07 +0000666 BasicBlock::iterator I = L->getHeader()->begin();
667 PHINode *PN;
Chris Lattnerdcce49e2005-08-02 02:44:31 +0000668 while ((PN = dyn_cast<PHINode>(I))) {
Chris Lattner564900e2005-08-02 00:41:11 +0000669 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
670
Nate Begemane68bcd12005-07-30 00:15:07 +0000671 // At this point, we know that we have killed one or more GEP instructions.
672 // It is worth checking to see if the cann indvar is also dead, so that we
673 // can remove it as well. The requirements for the cann indvar to be
674 // considered dead are:
675 // 1. the cann indvar has one use
676 // 2. the use is an add instruction
677 // 3. the add has one use
678 // 4. the add is used by the cann indvar
679 // If all four cases above are true, then we can remove both the add and
680 // the cann indvar.
681 // FIXME: this needs to eliminate an induction variable even if it's being
682 // compared against some value to decide loop termination.
683 if (PN->hasOneUse()) {
684 BinaryOperator *BO = dyn_cast<BinaryOperator>(*(PN->use_begin()));
Chris Lattner75a44e12005-08-02 02:52:02 +0000685 if (BO && BO->hasOneUse()) {
686 if (PN == *(BO->use_begin())) {
687 DeadInsts.insert(BO);
688 // Break the cycle, then delete the PHI.
689 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattner84e9baa2005-08-03 21:36:09 +0000690 SE->deleteInstructionFromRecords(PN);
Chris Lattner75a44e12005-08-02 02:52:02 +0000691 PN->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +0000692 }
Chris Lattner75a44e12005-08-02 02:52:02 +0000693 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000694 }
Nate Begemanb18121e2004-10-18 21:08:22 +0000695 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000696 DeleteTriviallyDeadInstructions(DeadInsts);
Nate Begemanb18121e2004-10-18 21:08:22 +0000697 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000698
699 IVUsesByStride.clear();
Chris Lattnerdcce49e2005-08-02 02:44:31 +0000700 CastedBasePointers.clear();
Nate Begemane68bcd12005-07-30 00:15:07 +0000701 return;
Nate Begemanb18121e2004-10-18 21:08:22 +0000702}