blob: 7b743e230e839929ef43d694f9fbbc92699d86c3 [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 Lattner430d0022005-08-03 22:21:05 +000040 /// IVStrideUse - Keep track of one use of a strided induction variable, where
41 /// the stride is stored externally. The Offset member keeps track of the
42 /// offset from the IV, User is the actual user of the operand, and 'Operand'
43 /// is the operand # of the User that is the use.
44 struct IVStrideUse {
45 SCEVHandle Offset;
46 Instruction *User;
47 Value *OperandValToReplace;
48
49 IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
50 : Offset(Offs), User(U), OperandValToReplace(O) {}
51 };
52
53 /// IVUsersOfOneStride - This structure keeps track of all instructions that
54 /// have an operand that is based on the trip count multiplied by some stride.
55 /// The stride for all of these users is common and kept external to this
56 /// structure.
57 struct IVUsersOfOneStride {
Nate Begemane68bcd12005-07-30 00:15:07 +000058 /// Users - Keep track of all of the users of this stride as well as the
Chris Lattner430d0022005-08-03 22:21:05 +000059 /// initial value and the operand that uses the IV.
60 std::vector<IVStrideUse> Users;
61
62 void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
63 Users.push_back(IVStrideUse(Offset, User, Operand));
Nate Begemane68bcd12005-07-30 00:15:07 +000064 }
65 };
66
67
Nate Begemanb18121e2004-10-18 21:08:22 +000068 class LoopStrengthReduce : public FunctionPass {
69 LoopInfo *LI;
70 DominatorSet *DS;
Nate Begemane68bcd12005-07-30 00:15:07 +000071 ScalarEvolution *SE;
72 const TargetData *TD;
73 const Type *UIntPtrTy;
Nate Begemanb18121e2004-10-18 21:08:22 +000074 bool Changed;
Chris Lattner75a44e12005-08-02 02:52:02 +000075
76 /// MaxTargetAMSize - This is the maximum power-of-two scale value that the
77 /// target can handle for free with its addressing modes.
Jeff Cohena2c59b72005-03-04 04:04:26 +000078 unsigned MaxTargetAMSize;
Nate Begemane68bcd12005-07-30 00:15:07 +000079
80 /// IVUsesByStride - Keep track of all uses of induction variables that we
81 /// are interested in. The key of the map is the stride of the access.
Chris Lattner430d0022005-08-03 22:21:05 +000082 std::map<Value*, IVUsersOfOneStride> IVUsesByStride;
Nate Begemane68bcd12005-07-30 00:15:07 +000083
Chris Lattner6f286b72005-08-04 01:19:13 +000084 /// CastedValues - As we need to cast values to uintptr_t, this keeps track
85 /// of the casted version of each value. This is accessed by
86 /// getCastedVersionOf.
87 std::map<Value*, Value*> CastedPointers;
Nate Begemane68bcd12005-07-30 00:15:07 +000088
89 /// DeadInsts - Keep track of instructions we may have made dead, so that
90 /// we can remove them after we are done working.
91 std::set<Instruction*> DeadInsts;
Nate Begemanb18121e2004-10-18 21:08:22 +000092 public:
Jeff Cohena2c59b72005-03-04 04:04:26 +000093 LoopStrengthReduce(unsigned MTAMS = 1)
94 : MaxTargetAMSize(MTAMS) {
95 }
96
Nate Begemanb18121e2004-10-18 21:08:22 +000097 virtual bool runOnFunction(Function &) {
98 LI = &getAnalysis<LoopInfo>();
99 DS = &getAnalysis<DominatorSet>();
Nate Begemane68bcd12005-07-30 00:15:07 +0000100 SE = &getAnalysis<ScalarEvolution>();
101 TD = &getAnalysis<TargetData>();
102 UIntPtrTy = TD->getIntPtrType();
Nate Begemanb18121e2004-10-18 21:08:22 +0000103 Changed = false;
104
105 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
106 runOnLoop(*I);
Chris Lattner6f286b72005-08-04 01:19:13 +0000107
108 CastedPointers.clear();
Nate Begemanb18121e2004-10-18 21:08:22 +0000109 return Changed;
110 }
111
112 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
113 AU.setPreservesCFG();
Jeff Cohen39751c32005-02-27 19:37:07 +0000114 AU.addRequiredID(LoopSimplifyID);
Nate Begemanb18121e2004-10-18 21:08:22 +0000115 AU.addRequired<LoopInfo>();
116 AU.addRequired<DominatorSet>();
Jeff Cohena2c59b72005-03-04 04:04:26 +0000117 AU.addRequired<TargetData>();
Nate Begemane68bcd12005-07-30 00:15:07 +0000118 AU.addRequired<ScalarEvolution>();
Nate Begemanb18121e2004-10-18 21:08:22 +0000119 }
Chris Lattner6f286b72005-08-04 01:19:13 +0000120
121 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
122 ///
123 Value *getCastedVersionOf(Value *V);
124private:
Nate Begemanb18121e2004-10-18 21:08:22 +0000125 void runOnLoop(Loop *L);
Chris Lattnereaf24722005-08-04 17:40:30 +0000126 bool AddUsersIfInteresting(Instruction *I, Loop *L,
127 std::set<Instruction*> &Processed);
128 SCEVHandle GetExpressionSCEV(Instruction *E, Loop *L);
129
Nate Begemane68bcd12005-07-30 00:15:07 +0000130
Chris Lattner430d0022005-08-03 22:21:05 +0000131 void StrengthReduceStridedIVUsers(Value *Stride, IVUsersOfOneStride &Uses,
132 Loop *L, bool isOnlyStride);
Nate Begemanb18121e2004-10-18 21:08:22 +0000133 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
134 };
Misha Brukmanb1c93172005-04-21 23:48:37 +0000135 RegisterOpt<LoopStrengthReduce> X("loop-reduce",
Nate Begemanb18121e2004-10-18 21:08:22 +0000136 "Strength Reduce GEP Uses of Ind. Vars");
137}
138
Jeff Cohena2c59b72005-03-04 04:04:26 +0000139FunctionPass *llvm::createLoopStrengthReducePass(unsigned MaxTargetAMSize) {
140 return new LoopStrengthReduce(MaxTargetAMSize);
Nate Begemanb18121e2004-10-18 21:08:22 +0000141}
142
Chris Lattner6f286b72005-08-04 01:19:13 +0000143/// getCastedVersionOf - Return the specified value casted to uintptr_t.
144///
145Value *LoopStrengthReduce::getCastedVersionOf(Value *V) {
146 if (V->getType() == UIntPtrTy) return V;
147 if (Constant *CB = dyn_cast<Constant>(V))
148 return ConstantExpr::getCast(CB, UIntPtrTy);
149
150 Value *&New = CastedPointers[V];
151 if (New) return New;
152
153 BasicBlock::iterator InsertPt;
154 if (Argument *Arg = dyn_cast<Argument>(V)) {
155 // Insert into the entry of the function, after any allocas.
156 InsertPt = Arg->getParent()->begin()->begin();
157 while (isa<AllocaInst>(InsertPt)) ++InsertPt;
158 } else {
159 if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
160 InsertPt = II->getNormalDest()->begin();
161 } else {
162 InsertPt = cast<Instruction>(V);
163 ++InsertPt;
164 }
165
166 // Do not insert casts into the middle of PHI node blocks.
167 while (isa<PHINode>(InsertPt)) ++InsertPt;
168 }
Chris Lattneracc42c42005-08-04 19:08:16 +0000169
170 New = new CastInst(V, UIntPtrTy, V->getName(), InsertPt);
171 DeadInsts.insert(cast<Instruction>(New));
172 return New;
Chris Lattner6f286b72005-08-04 01:19:13 +0000173}
174
175
Nate Begemanb18121e2004-10-18 21:08:22 +0000176/// DeleteTriviallyDeadInstructions - If any of the instructions is the
177/// specified set are trivially dead, delete them and see if this makes any of
178/// their operands subsequently dead.
179void LoopStrengthReduce::
180DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
181 while (!Insts.empty()) {
182 Instruction *I = *Insts.begin();
183 Insts.erase(Insts.begin());
184 if (isInstructionTriviallyDead(I)) {
Jeff Cohen8ea6f9e2005-03-01 03:46:11 +0000185 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
186 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
187 Insts.insert(U);
Chris Lattner84e9baa2005-08-03 21:36:09 +0000188 SE->deleteInstructionFromRecords(I);
189 I->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +0000190 Changed = true;
191 }
192 }
193}
194
Jeff Cohen39751c32005-02-27 19:37:07 +0000195
Chris Lattnereaf24722005-08-04 17:40:30 +0000196/// GetExpressionSCEV - Compute and return the SCEV for the specified
197/// instruction.
198SCEVHandle LoopStrengthReduce::GetExpressionSCEV(Instruction *Exp, Loop *L) {
199 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
200 if (!GEP)
201 return SE->getSCEV(Exp);
202
Nate Begemane68bcd12005-07-30 00:15:07 +0000203 // Analyze all of the subscripts of this getelementptr instruction, looking
204 // for uses that are determined by the trip count of L. First, skip all
205 // operands the are not dependent on the IV.
206
207 // Build up the base expression. Insert an LLVM cast of the pointer to
208 // uintptr_t first.
Chris Lattnereaf24722005-08-04 17:40:30 +0000209 SCEVHandle GEPVal = SCEVUnknown::get(getCastedVersionOf(GEP->getOperand(0)));
Nate Begemane68bcd12005-07-30 00:15:07 +0000210
211 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnereaf24722005-08-04 17:40:30 +0000212
213 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
Nate Begemane68bcd12005-07-30 00:15:07 +0000214 // If this is a use of a recurrence that we can analyze, and it comes before
215 // Op does in the GEP operand list, we will handle this when we process this
216 // operand.
217 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
218 const StructLayout *SL = TD->getStructLayout(STy);
219 unsigned Idx = cast<ConstantUInt>(GEP->getOperand(i))->getValue();
220 uint64_t Offset = SL->MemberOffsets[Idx];
Chris Lattnereaf24722005-08-04 17:40:30 +0000221 GEPVal = SCEVAddExpr::get(GEPVal,
222 SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy));
Nate Begemane68bcd12005-07-30 00:15:07 +0000223 } else {
Chris Lattneracc42c42005-08-04 19:08:16 +0000224 Value *OpVal = getCastedVersionOf(GEP->getOperand(i));
225 SCEVHandle Idx = SE->getSCEV(OpVal);
226
Chris Lattnereaf24722005-08-04 17:40:30 +0000227 uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
228 if (TypeSize != 1)
229 Idx = SCEVMulExpr::get(Idx,
230 SCEVConstant::get(ConstantUInt::get(UIntPtrTy,
231 TypeSize)));
232 GEPVal = SCEVAddExpr::get(GEPVal, Idx);
Nate Begemane68bcd12005-07-30 00:15:07 +0000233 }
234 }
235
Chris Lattnereaf24722005-08-04 17:40:30 +0000236 return GEPVal;
Nate Begemane68bcd12005-07-30 00:15:07 +0000237}
238
Chris Lattneracc42c42005-08-04 19:08:16 +0000239/// getSCEVStartAndStride - Compute the start and stride of this expression,
240/// returning false if the expression is not a start/stride pair, or true if it
241/// is. The stride must be a loop invariant expression, but the start may be
242/// a mix of loop invariant and loop variant expressions.
243static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
244 SCEVHandle &Start, Value *&Stride) {
245 SCEVHandle TheAddRec = Start; // Initialize to zero.
246
247 // If the outer level is an AddExpr, the operands are all start values except
248 // for a nested AddRecExpr.
249 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
250 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
251 if (SCEVAddRecExpr *AddRec =
252 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
253 if (AddRec->getLoop() == L)
254 TheAddRec = SCEVAddExpr::get(AddRec, TheAddRec);
255 else
256 return false; // Nested IV of some sort?
257 } else {
258 Start = SCEVAddExpr::get(Start, AE->getOperand(i));
259 }
260
261 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SH)) {
262 TheAddRec = SH;
263 } else {
264 return false; // not analyzable.
265 }
266
267 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
268 if (!AddRec || AddRec->getLoop() != L) return false;
269
270 // FIXME: Generalize to non-affine IV's.
271 if (!AddRec->isAffine()) return false;
272
273 Start = SCEVAddExpr::get(Start, AddRec->getOperand(0));
274
275 // FIXME: generalize to IV's with more complex strides (must emit stride
276 // expression outside of loop!)
277 if (!isa<SCEVConstant>(AddRec->getOperand(1)))
278 return false;
279
280 SCEVConstant *StrideC = cast<SCEVConstant>(AddRec->getOperand(1));
281 Stride = StrideC->getValue();
282
283 assert(Stride->getType()->isUnsigned() &&
284 "Constants should be canonicalized to unsigned!");
285 return true;
286}
287
Nate Begemane68bcd12005-07-30 00:15:07 +0000288/// AddUsersIfInteresting - Inspect the specified instruction. If it is a
289/// reducible SCEV, recursively add its users to the IVUsesByStride set and
290/// return true. Otherwise, return false.
Chris Lattnereaf24722005-08-04 17:40:30 +0000291bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
292 std::set<Instruction*> &Processed) {
Nate Begeman17a0e2af2005-07-30 00:21:31 +0000293 if (I->getType() == Type::VoidTy) return false;
Chris Lattnereaf24722005-08-04 17:40:30 +0000294 if (!Processed.insert(I).second)
295 return true; // Instruction already handled.
296
Chris Lattneracc42c42005-08-04 19:08:16 +0000297 // Get the symbolic expression for this instruction.
Chris Lattnereaf24722005-08-04 17:40:30 +0000298 SCEVHandle ISE = GetExpressionSCEV(I, L);
Chris Lattneracc42c42005-08-04 19:08:16 +0000299 if (isa<SCEVCouldNotCompute>(ISE)) return false;
Chris Lattnereaf24722005-08-04 17:40:30 +0000300
Chris Lattneracc42c42005-08-04 19:08:16 +0000301 // Get the start and stride for this expression.
302 SCEVHandle Start = SCEVUnknown::getIntegerSCEV(0, ISE->getType());
303 Value *Stride = 0;
304 if (!getSCEVStartAndStride(ISE, L, Start, Stride))
305 return false; // Non-reducible symbolic expression, bail out.
306
Nate Begemane68bcd12005-07-30 00:15:07 +0000307 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){
308 Instruction *User = cast<Instruction>(*UI);
309
310 // Do not infinitely recurse on PHI nodes.
311 if (isa<PHINode>(User) && User->getParent() == L->getHeader())
312 continue;
313
314 // If this is an instruction defined in a nested loop, or outside this loop,
Chris Lattnera0102fb2005-08-04 00:14:11 +0000315 // don't recurse into it.
Chris Lattneracc42c42005-08-04 19:08:16 +0000316 bool AddUserToIVUsers = false;
Chris Lattnera0102fb2005-08-04 00:14:11 +0000317 if (LI->getLoopFor(User->getParent()) != L) {
318 DEBUG(std::cerr << "FOUND USER in nested loop: " << *User
319 << " OF SCEV: " << *ISE << "\n");
Chris Lattneracc42c42005-08-04 19:08:16 +0000320 AddUserToIVUsers = true;
Chris Lattnereaf24722005-08-04 17:40:30 +0000321 } else if (!AddUsersIfInteresting(User, L, Processed)) {
Chris Lattner65107492005-08-04 00:40:47 +0000322 DEBUG(std::cerr << "FOUND USER: " << *User
323 << " OF SCEV: " << *ISE << "\n");
Chris Lattneracc42c42005-08-04 19:08:16 +0000324 AddUserToIVUsers = true;
325 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000326
Chris Lattneracc42c42005-08-04 19:08:16 +0000327 if (AddUserToIVUsers) {
Chris Lattner65107492005-08-04 00:40:47 +0000328 // Okay, we found a user that we cannot reduce. Analyze the instruction
329 // and decide what to do with it.
Chris Lattneracc42c42005-08-04 19:08:16 +0000330 IVUsesByStride[Stride].addUser(Start, User, I);
Nate Begemane68bcd12005-07-30 00:15:07 +0000331 }
332 }
333 return true;
334}
335
336namespace {
337 /// BasedUser - For a particular base value, keep information about how we've
338 /// partitioned the expression so far.
339 struct BasedUser {
340 /// Inst - The instruction using the induction variable.
341 Instruction *Inst;
342
Chris Lattner430d0022005-08-03 22:21:05 +0000343 /// OperandValToReplace - The operand value of Inst to replace with the
344 /// EmittedBase.
345 Value *OperandValToReplace;
Nate Begemane68bcd12005-07-30 00:15:07 +0000346
347 /// Imm - The immediate value that should be added to the base immediately
348 /// before Inst, because it will be folded into the imm field of the
349 /// instruction.
350 SCEVHandle Imm;
351
352 /// EmittedBase - The actual value* to use for the base value of this
353 /// operation. This is null if we should just use zero so far.
354 Value *EmittedBase;
355
Chris Lattner430d0022005-08-03 22:21:05 +0000356 BasedUser(Instruction *I, Value *Op, const SCEVHandle &IMM)
357 : Inst(I), OperandValToReplace(Op), Imm(IMM), EmittedBase(0) {}
Nate Begemane68bcd12005-07-30 00:15:07 +0000358
359
360 // No need to compare these.
361 bool operator<(const BasedUser &BU) const { return 0; }
362
363 void dump() const;
364 };
365}
366
367void BasedUser::dump() const {
368 std::cerr << " Imm=" << *Imm;
369 if (EmittedBase)
370 std::cerr << " EB=" << *EmittedBase;
371
372 std::cerr << " Inst: " << *Inst;
373}
374
375/// isTargetConstant - Return true if the following can be referenced by the
376/// immediate field of a target instruction.
377static bool isTargetConstant(const SCEVHandle &V) {
Jeff Cohen546fd592005-07-30 18:33:25 +0000378
Nate Begemane68bcd12005-07-30 00:15:07 +0000379 // FIXME: Look at the target to decide if &GV is a legal constant immediate.
380 if (isa<SCEVConstant>(V)) return true;
Jeff Cohen546fd592005-07-30 18:33:25 +0000381
Nate Begemane68bcd12005-07-30 00:15:07 +0000382 return false; // ENABLE this for x86
Jeff Cohen546fd592005-07-30 18:33:25 +0000383
Nate Begemane68bcd12005-07-30 00:15:07 +0000384 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
385 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
386 if (CE->getOpcode() == Instruction::Cast)
387 if (isa<GlobalValue>(CE->getOperand(0)))
388 // FIXME: should check to see that the dest is uintptr_t!
389 return true;
390 return false;
391}
392
393/// GetImmediateValues - Look at Val, and pull out any additions of constants
394/// that can fit into the immediate field of instructions in the target.
Chris Lattneracc42c42005-08-04 19:08:16 +0000395static SCEVHandle GetImmediateValues(SCEVHandle Val, bool isAddress, Loop *L) {
396 if (isAddress && isTargetConstant(Val))
Nate Begemane68bcd12005-07-30 00:15:07 +0000397 return Val;
398
Chris Lattnerfc624702005-08-03 23:44:42 +0000399 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
Nate Begemane68bcd12005-07-30 00:15:07 +0000400 unsigned i = 0;
Chris Lattneracc42c42005-08-04 19:08:16 +0000401 SCEVHandle Imm = SCEVUnknown::getIntegerSCEV(0, Val->getType());
Jeff Cohen546fd592005-07-30 18:33:25 +0000402
Chris Lattneracc42c42005-08-04 19:08:16 +0000403 for (; i != SAE->getNumOperands(); ++i)
404 if (isAddress && isTargetConstant(SAE->getOperand(i))) {
405 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
406 } else if (!SAE->getOperand(i)->isLoopInvariant(L)) {
407 // If this is a loop-variant expression, it must stay in the immediate
408 // field of the expression.
409 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
Nate Begemane68bcd12005-07-30 00:15:07 +0000410 }
Chris Lattneracc42c42005-08-04 19:08:16 +0000411
412 return Imm;
Chris Lattnerfc624702005-08-03 23:44:42 +0000413 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
414 // Try to pull immediates out of the start value of nested addrec's.
Chris Lattneracc42c42005-08-04 19:08:16 +0000415 return GetImmediateValues(SARE->getStart(), isAddress, L);
Nate Begemane68bcd12005-07-30 00:15:07 +0000416 }
417
418 return SCEVUnknown::getIntegerSCEV(0, Val->getType());
419}
420
421/// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
422/// stride of IV. All of the users may have different starting values, and this
423/// may not be the only stride (we know it is if isOnlyStride is true).
424void LoopStrengthReduce::StrengthReduceStridedIVUsers(Value *Stride,
Chris Lattner430d0022005-08-03 22:21:05 +0000425 IVUsersOfOneStride &Uses,
426 Loop *L,
Nate Begemane68bcd12005-07-30 00:15:07 +0000427 bool isOnlyStride) {
428 // Transform our list of users and offsets to a bit more complex table. In
429 // this new vector, the first entry for each element is the base of the
430 // strided access, and the second is the BasedUser object for the use. We
431 // progressively move information from the first to the second entry, until we
432 // eventually emit the object.
433 std::vector<std::pair<SCEVHandle, BasedUser> > UsersToProcess;
434 UsersToProcess.reserve(Uses.Users.size());
Jeff Cohen546fd592005-07-30 18:33:25 +0000435
436 SCEVHandle ZeroBase = SCEVUnknown::getIntegerSCEV(0,
Chris Lattner430d0022005-08-03 22:21:05 +0000437 Uses.Users[0].Offset->getType());
Nate Begemane68bcd12005-07-30 00:15:07 +0000438
439 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i)
Chris Lattner430d0022005-08-03 22:21:05 +0000440 UsersToProcess.push_back(std::make_pair(Uses.Users[i].Offset,
441 BasedUser(Uses.Users[i].User,
442 Uses.Users[i].OperandValToReplace,
Nate Begemane68bcd12005-07-30 00:15:07 +0000443 ZeroBase)));
444
445 // First pass, figure out what we can represent in the immediate fields of
446 // instructions. If we can represent anything there, move it to the imm
447 // fields of the BasedUsers.
448 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
Chris Lattneracc42c42005-08-04 19:08:16 +0000449 // Addressing modes can be folded into loads and stores. Be careful that
450 // the store is through the expression, not of the expression though.
451 bool isAddress = isa<LoadInst>(UsersToProcess[i].second.Inst);
452 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].second.Inst))
453 if (SI->getOperand(1) == UsersToProcess[i].second.OperandValToReplace)
454 isAddress = true;
455
456 UsersToProcess[i].second.Imm =
457 GetImmediateValues(UsersToProcess[i].first, isAddress, L);
458
Nate Begemane68bcd12005-07-30 00:15:07 +0000459 UsersToProcess[i].first = SCEV::getMinusSCEV(UsersToProcess[i].first,
460 UsersToProcess[i].second.Imm);
461
462 DEBUG(std::cerr << "BASE: " << *UsersToProcess[i].first);
463 DEBUG(UsersToProcess[i].second.dump());
464 }
465
466 SCEVExpander Rewriter(*SE, *LI);
467 BasicBlock *Preheader = L->getLoopPreheader();
468 Instruction *PreInsertPt = Preheader->getTerminator();
469 Instruction *PhiInsertBefore = L->getHeader()->begin();
470
Jeff Cohen546fd592005-07-30 18:33:25 +0000471 assert(isa<PHINode>(PhiInsertBefore) &&
Nate Begemane68bcd12005-07-30 00:15:07 +0000472 "How could this loop have IV's without any phis?");
473 PHINode *SomeLoopPHI = cast<PHINode>(PhiInsertBefore);
474 assert(SomeLoopPHI->getNumIncomingValues() == 2 &&
475 "This loop isn't canonicalized right");
476 BasicBlock *LatchBlock =
477 SomeLoopPHI->getIncomingBlock(SomeLoopPHI->getIncomingBlock(0) == Preheader);
Jeff Cohen546fd592005-07-30 18:33:25 +0000478
Chris Lattnerbb78c972005-08-03 23:30:08 +0000479 DEBUG(std::cerr << "INSERTING IVs of STRIDE " << *Stride << ":\n");
480
Nate Begemane68bcd12005-07-30 00:15:07 +0000481 // FIXME: This loop needs increasing levels of intelligence.
Chris Lattnerdb23c742005-08-03 22:51:21 +0000482 // STAGE 0: just emit everything as its own base.
Nate Begemane68bcd12005-07-30 00:15:07 +0000483 // STAGE 1: factor out common vars from bases, and try and push resulting
Chris Lattnerdb23c742005-08-03 22:51:21 +0000484 // constants into Imm field. <-- We are here
Nate Begemane68bcd12005-07-30 00:15:07 +0000485 // STAGE 2: factor out large constants to try and make more constants
486 // acceptable for target loads and stores.
Nate Begemane68bcd12005-07-30 00:15:07 +0000487
Chris Lattnerdb23c742005-08-03 22:51:21 +0000488 // Sort by the base value, so that all IVs with identical bases are next to
489 // each other.
490 std::sort(UsersToProcess.begin(), UsersToProcess.end());
Nate Begemane68bcd12005-07-30 00:15:07 +0000491 while (!UsersToProcess.empty()) {
Chris Lattnerdb23c742005-08-03 22:51:21 +0000492 SCEVHandle Base = UsersToProcess.front().first;
Chris Lattnerbb78c972005-08-03 23:30:08 +0000493
494 DEBUG(std::cerr << " INSERTING PHI with BASE = " << *Base << ":\n");
495
Nate Begemane68bcd12005-07-30 00:15:07 +0000496 // Create a new Phi for this base, and stick it in the loop header.
Chris Lattnerdb23c742005-08-03 22:51:21 +0000497 const Type *ReplacedTy = Base->getType();
498 PHINode *NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
Nate Begemane68bcd12005-07-30 00:15:07 +0000499
Jeff Cohen546fd592005-07-30 18:33:25 +0000500 // Emit the initial base value into the loop preheader, and add it to the
Nate Begemane68bcd12005-07-30 00:15:07 +0000501 // Phi node.
Chris Lattnerdb23c742005-08-03 22:51:21 +0000502 Value *BaseV = Rewriter.expandCodeFor(Base, PreInsertPt, ReplacedTy);
Nate Begemane68bcd12005-07-30 00:15:07 +0000503 NewPHI->addIncoming(BaseV, Preheader);
504
505 // Emit the increment of the base value before the terminator of the loop
506 // latch block, and add it to the Phi node.
507 SCEVHandle Inc = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
508 SCEVUnknown::get(Stride));
509
510 Value *IncV = Rewriter.expandCodeFor(Inc, LatchBlock->getTerminator(),
511 ReplacedTy);
512 IncV->setName(NewPHI->getName()+".inc");
513 NewPHI->addIncoming(IncV, LatchBlock);
514
515 // Emit the code to add the immediate offset to the Phi value, just before
Chris Lattnerdb23c742005-08-03 22:51:21 +0000516 // the instructions that we identified as using this stride and base.
517 while (!UsersToProcess.empty() && UsersToProcess.front().first == Base) {
518 BasedUser &User = UsersToProcess.front().second;
Jeff Cohen546fd592005-07-30 18:33:25 +0000519
Chris Lattnerdb23c742005-08-03 22:51:21 +0000520 // Clear the SCEVExpander's expression map so that we are guaranteed
521 // to have the code emitted where we expect it.
522 Rewriter.clear();
523 SCEVHandle NewValSCEV = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
524 User.Imm);
Chris Lattnerbb78c972005-08-03 23:30:08 +0000525 Value *Replaced = User.OperandValToReplace;
Chris Lattnerdb23c742005-08-03 22:51:21 +0000526 Value *newVal = Rewriter.expandCodeFor(NewValSCEV, User.Inst,
527 Replaced->getType());
Jeff Cohen546fd592005-07-30 18:33:25 +0000528
Chris Lattnerdb23c742005-08-03 22:51:21 +0000529 // Replace the use of the operand Value with the new Phi we just created.
Chris Lattnerdb23c742005-08-03 22:51:21 +0000530 User.Inst->replaceUsesOfWith(Replaced, newVal);
Chris Lattnerbb78c972005-08-03 23:30:08 +0000531 DEBUG(std::cerr << " CHANGED: IMM =" << *User.Imm << " Inst = "
532 << *User.Inst);
Jeff Cohen546fd592005-07-30 18:33:25 +0000533
Chris Lattnerdb23c742005-08-03 22:51:21 +0000534 // Mark old value we replaced as possibly dead, so that it is elminated
535 // if we just replaced the last use of that value.
536 DeadInsts.insert(cast<Instruction>(Replaced));
Nate Begemane68bcd12005-07-30 00:15:07 +0000537
Chris Lattnerdb23c742005-08-03 22:51:21 +0000538 UsersToProcess.erase(UsersToProcess.begin());
539 ++NumReduced;
540 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000541 // TODO: Next, find out which base index is the most common, pull it out.
542 }
543
544 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
545 // different starting values, into different PHIs.
Jeff Cohen546fd592005-07-30 18:33:25 +0000546
Nate Begemane68bcd12005-07-30 00:15:07 +0000547 // BEFORE writing this, it's probably useful to handle GEP's.
548
549 // NOTE: pull all constants together, for REG+IMM addressing, include &GV in
550 // 'IMM' if the target supports it.
551}
552
553
Nate Begemanb18121e2004-10-18 21:08:22 +0000554void LoopStrengthReduce::runOnLoop(Loop *L) {
555 // First step, transform all loops nesting inside of this loop.
556 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
557 runOnLoop(*I);
558
Nate Begemane68bcd12005-07-30 00:15:07 +0000559 // Next, find all uses of induction variables in this loop, and catagorize
560 // them by stride. Start by finding all of the PHI nodes in the header for
561 // this loop. If they are induction variables, inspect their uses.
Chris Lattnereaf24722005-08-04 17:40:30 +0000562 std::set<Instruction*> Processed; // Don't reprocess instructions.
Nate Begemane68bcd12005-07-30 00:15:07 +0000563 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
Chris Lattnereaf24722005-08-04 17:40:30 +0000564 AddUsersIfInteresting(I, L, Processed);
Nate Begemanb18121e2004-10-18 21:08:22 +0000565
Nate Begemane68bcd12005-07-30 00:15:07 +0000566 // If we have nothing to do, return.
567 //if (IVUsesByStride.empty()) return;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000568
Nate Begemane68bcd12005-07-30 00:15:07 +0000569 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
570 // doing computation in byte values, promote to 32-bit values if safe.
571
572 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
573 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
574 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
575 // to be careful that IV's are all the same type. Only works for intptr_t
576 // indvars.
577
578 // If we only have one stride, we can more aggressively eliminate some things.
579 bool HasOneStride = IVUsesByStride.size() == 1;
580
Chris Lattner430d0022005-08-03 22:21:05 +0000581 for (std::map<Value*, IVUsersOfOneStride>::iterator SI
582 = IVUsesByStride.begin(), E = IVUsesByStride.end(); SI != E; ++SI)
Nate Begemane68bcd12005-07-30 00:15:07 +0000583 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
Nate Begemanb18121e2004-10-18 21:08:22 +0000584
585 // Clean up after ourselves
586 if (!DeadInsts.empty()) {
587 DeleteTriviallyDeadInstructions(DeadInsts);
588
Nate Begemane68bcd12005-07-30 00:15:07 +0000589 BasicBlock::iterator I = L->getHeader()->begin();
590 PHINode *PN;
Chris Lattnerdcce49e2005-08-02 02:44:31 +0000591 while ((PN = dyn_cast<PHINode>(I))) {
Chris Lattner564900e2005-08-02 00:41:11 +0000592 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
593
Nate Begemane68bcd12005-07-30 00:15:07 +0000594 // At this point, we know that we have killed one or more GEP instructions.
595 // It is worth checking to see if the cann indvar is also dead, so that we
596 // can remove it as well. The requirements for the cann indvar to be
597 // considered dead are:
598 // 1. the cann indvar has one use
599 // 2. the use is an add instruction
600 // 3. the add has one use
601 // 4. the add is used by the cann indvar
602 // If all four cases above are true, then we can remove both the add and
603 // the cann indvar.
604 // FIXME: this needs to eliminate an induction variable even if it's being
605 // compared against some value to decide loop termination.
606 if (PN->hasOneUse()) {
607 BinaryOperator *BO = dyn_cast<BinaryOperator>(*(PN->use_begin()));
Chris Lattner75a44e12005-08-02 02:52:02 +0000608 if (BO && BO->hasOneUse()) {
609 if (PN == *(BO->use_begin())) {
610 DeadInsts.insert(BO);
611 // Break the cycle, then delete the PHI.
612 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattner84e9baa2005-08-03 21:36:09 +0000613 SE->deleteInstructionFromRecords(PN);
Chris Lattner75a44e12005-08-02 02:52:02 +0000614 PN->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +0000615 }
Chris Lattner75a44e12005-08-02 02:52:02 +0000616 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000617 }
Nate Begemanb18121e2004-10-18 21:08:22 +0000618 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000619 DeleteTriviallyDeadInstructions(DeadInsts);
Nate Begemanb18121e2004-10-18 21:08:22 +0000620 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000621
622 IVUsesByStride.clear();
623 return;
Nate Begemanb18121e2004-10-18 21:08:22 +0000624}