blob: 75a681d98ec6d75068cfcf749009936f919531bd [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"
Chris Lattner4fec86d2005-08-12 22:06:11 +000029#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000030#include "llvm/Transforms/Utils/Local.h"
Jeff Cohena2c59b72005-03-04 04:04:26 +000031#include "llvm/Target/TargetData.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000032#include "llvm/ADT/Statistic.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000033#include "llvm/Support/Debug.h"
Jeff Cohenc5009912005-07-30 18:22:27 +000034#include <algorithm>
Nate Begemanb18121e2004-10-18 21:08:22 +000035#include <set>
36using namespace llvm;
37
38namespace {
39 Statistic<> NumReduced ("loop-reduce", "Number of GEPs strength reduced");
Chris Lattner45f8b6e2005-08-04 22:34:05 +000040 Statistic<> NumInserted("loop-reduce", "Number of PHIs inserted");
Chris Lattneredff91a2005-08-10 00:45:21 +000041 Statistic<> NumVariable("loop-reduce","Number of PHIs with variable strides");
Nate Begemanb18121e2004-10-18 21:08:22 +000042
Chris Lattner430d0022005-08-03 22:21:05 +000043 /// IVStrideUse - Keep track of one use of a strided induction variable, where
44 /// the stride is stored externally. The Offset member keeps track of the
45 /// offset from the IV, User is the actual user of the operand, and 'Operand'
46 /// is the operand # of the User that is the use.
47 struct IVStrideUse {
48 SCEVHandle Offset;
49 Instruction *User;
50 Value *OperandValToReplace;
Chris Lattner9bfa6f82005-08-08 05:28:22 +000051
52 // isUseOfPostIncrementedValue - True if this should use the
53 // post-incremented version of this IV, not the preincremented version.
54 // This can only be set in special cases, such as the terminating setcc
55 // instruction for a loop.
56 bool isUseOfPostIncrementedValue;
Chris Lattner430d0022005-08-03 22:21:05 +000057
58 IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
Chris Lattner9bfa6f82005-08-08 05:28:22 +000059 : Offset(Offs), User(U), OperandValToReplace(O),
60 isUseOfPostIncrementedValue(false) {}
Chris Lattner430d0022005-08-03 22:21:05 +000061 };
62
63 /// IVUsersOfOneStride - This structure keeps track of all instructions that
64 /// have an operand that is based on the trip count multiplied by some stride.
65 /// The stride for all of these users is common and kept external to this
66 /// structure.
67 struct IVUsersOfOneStride {
Nate Begemane68bcd12005-07-30 00:15:07 +000068 /// Users - Keep track of all of the users of this stride as well as the
Chris Lattner430d0022005-08-03 22:21:05 +000069 /// initial value and the operand that uses the IV.
70 std::vector<IVStrideUse> Users;
71
72 void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
73 Users.push_back(IVStrideUse(Offset, User, Operand));
Nate Begemane68bcd12005-07-30 00:15:07 +000074 }
75 };
76
77
Nate Begemanb18121e2004-10-18 21:08:22 +000078 class LoopStrengthReduce : public FunctionPass {
79 LoopInfo *LI;
80 DominatorSet *DS;
Nate Begemane68bcd12005-07-30 00:15:07 +000081 ScalarEvolution *SE;
82 const TargetData *TD;
83 const Type *UIntPtrTy;
Nate Begemanb18121e2004-10-18 21:08:22 +000084 bool Changed;
Chris Lattner75a44e12005-08-02 02:52:02 +000085
86 /// MaxTargetAMSize - This is the maximum power-of-two scale value that the
87 /// target can handle for free with its addressing modes.
Jeff Cohena2c59b72005-03-04 04:04:26 +000088 unsigned MaxTargetAMSize;
Nate Begemane68bcd12005-07-30 00:15:07 +000089
90 /// IVUsesByStride - Keep track of all uses of induction variables that we
91 /// are interested in. The key of the map is the stride of the access.
Chris Lattneredff91a2005-08-10 00:45:21 +000092 std::map<SCEVHandle, IVUsersOfOneStride> IVUsesByStride;
Nate Begemane68bcd12005-07-30 00:15:07 +000093
Chris Lattner6f286b72005-08-04 01:19:13 +000094 /// CastedValues - As we need to cast values to uintptr_t, this keeps track
95 /// of the casted version of each value. This is accessed by
96 /// getCastedVersionOf.
97 std::map<Value*, Value*> CastedPointers;
Nate Begemane68bcd12005-07-30 00:15:07 +000098
99 /// DeadInsts - Keep track of instructions we may have made dead, so that
100 /// we can remove them after we are done working.
101 std::set<Instruction*> DeadInsts;
Nate Begemanb18121e2004-10-18 21:08:22 +0000102 public:
Jeff Cohena2c59b72005-03-04 04:04:26 +0000103 LoopStrengthReduce(unsigned MTAMS = 1)
104 : MaxTargetAMSize(MTAMS) {
105 }
106
Nate Begemanb18121e2004-10-18 21:08:22 +0000107 virtual bool runOnFunction(Function &) {
108 LI = &getAnalysis<LoopInfo>();
109 DS = &getAnalysis<DominatorSet>();
Nate Begemane68bcd12005-07-30 00:15:07 +0000110 SE = &getAnalysis<ScalarEvolution>();
111 TD = &getAnalysis<TargetData>();
112 UIntPtrTy = TD->getIntPtrType();
Nate Begemanb18121e2004-10-18 21:08:22 +0000113 Changed = false;
114
115 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
116 runOnLoop(*I);
Chris Lattner6f286b72005-08-04 01:19:13 +0000117
Nate Begemanb18121e2004-10-18 21:08:22 +0000118 return Changed;
119 }
120
121 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
122 AU.setPreservesCFG();
Jeff Cohen39751c32005-02-27 19:37:07 +0000123 AU.addRequiredID(LoopSimplifyID);
Nate Begemanb18121e2004-10-18 21:08:22 +0000124 AU.addRequired<LoopInfo>();
125 AU.addRequired<DominatorSet>();
Jeff Cohena2c59b72005-03-04 04:04:26 +0000126 AU.addRequired<TargetData>();
Nate Begemane68bcd12005-07-30 00:15:07 +0000127 AU.addRequired<ScalarEvolution>();
Nate Begemanb18121e2004-10-18 21:08:22 +0000128 }
Chris Lattner6f286b72005-08-04 01:19:13 +0000129
130 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
131 ///
132 Value *getCastedVersionOf(Value *V);
133private:
Nate Begemanb18121e2004-10-18 21:08:22 +0000134 void runOnLoop(Loop *L);
Chris Lattnereaf24722005-08-04 17:40:30 +0000135 bool AddUsersIfInteresting(Instruction *I, Loop *L,
136 std::set<Instruction*> &Processed);
137 SCEVHandle GetExpressionSCEV(Instruction *E, Loop *L);
138
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000139 void OptimizeIndvars(Loop *L);
Nate Begemane68bcd12005-07-30 00:15:07 +0000140
Chris Lattneredff91a2005-08-10 00:45:21 +0000141 void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
142 IVUsersOfOneStride &Uses,
Chris Lattner430d0022005-08-03 22:21:05 +0000143 Loop *L, bool isOnlyStride);
Nate Begemanb18121e2004-10-18 21:08:22 +0000144 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
145 };
Misha Brukmanb1c93172005-04-21 23:48:37 +0000146 RegisterOpt<LoopStrengthReduce> X("loop-reduce",
Nate Begemanb18121e2004-10-18 21:08:22 +0000147 "Strength Reduce GEP Uses of Ind. Vars");
148}
149
Jeff Cohena2c59b72005-03-04 04:04:26 +0000150FunctionPass *llvm::createLoopStrengthReducePass(unsigned MaxTargetAMSize) {
151 return new LoopStrengthReduce(MaxTargetAMSize);
Nate Begemanb18121e2004-10-18 21:08:22 +0000152}
153
Chris Lattner6f286b72005-08-04 01:19:13 +0000154/// getCastedVersionOf - Return the specified value casted to uintptr_t.
155///
156Value *LoopStrengthReduce::getCastedVersionOf(Value *V) {
157 if (V->getType() == UIntPtrTy) return V;
158 if (Constant *CB = dyn_cast<Constant>(V))
159 return ConstantExpr::getCast(CB, UIntPtrTy);
160
161 Value *&New = CastedPointers[V];
162 if (New) return New;
163
164 BasicBlock::iterator InsertPt;
165 if (Argument *Arg = dyn_cast<Argument>(V)) {
166 // Insert into the entry of the function, after any allocas.
167 InsertPt = Arg->getParent()->begin()->begin();
168 while (isa<AllocaInst>(InsertPt)) ++InsertPt;
169 } else {
170 if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
171 InsertPt = II->getNormalDest()->begin();
172 } else {
173 InsertPt = cast<Instruction>(V);
174 ++InsertPt;
175 }
176
177 // Do not insert casts into the middle of PHI node blocks.
178 while (isa<PHINode>(InsertPt)) ++InsertPt;
179 }
Chris Lattneracc42c42005-08-04 19:08:16 +0000180
181 New = new CastInst(V, UIntPtrTy, V->getName(), InsertPt);
182 DeadInsts.insert(cast<Instruction>(New));
183 return New;
Chris Lattner6f286b72005-08-04 01:19:13 +0000184}
185
186
Nate Begemanb18121e2004-10-18 21:08:22 +0000187/// DeleteTriviallyDeadInstructions - If any of the instructions is the
188/// specified set are trivially dead, delete them and see if this makes any of
189/// their operands subsequently dead.
190void LoopStrengthReduce::
191DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
192 while (!Insts.empty()) {
193 Instruction *I = *Insts.begin();
194 Insts.erase(Insts.begin());
195 if (isInstructionTriviallyDead(I)) {
Jeff Cohen8ea6f9e2005-03-01 03:46:11 +0000196 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
197 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
198 Insts.insert(U);
Chris Lattner84e9baa2005-08-03 21:36:09 +0000199 SE->deleteInstructionFromRecords(I);
200 I->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +0000201 Changed = true;
202 }
203 }
204}
205
Jeff Cohen39751c32005-02-27 19:37:07 +0000206
Chris Lattnereaf24722005-08-04 17:40:30 +0000207/// GetExpressionSCEV - Compute and return the SCEV for the specified
208/// instruction.
209SCEVHandle LoopStrengthReduce::GetExpressionSCEV(Instruction *Exp, Loop *L) {
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000210 // Scalar Evolutions doesn't know how to compute SCEV's for GEP instructions.
211 // If this is a GEP that SE doesn't know about, compute it now and insert it.
212 // If this is not a GEP, or if we have already done this computation, just let
213 // SE figure it out.
Chris Lattnereaf24722005-08-04 17:40:30 +0000214 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000215 if (!GEP || SE->hasSCEV(GEP))
Chris Lattnereaf24722005-08-04 17:40:30 +0000216 return SE->getSCEV(Exp);
217
Nate Begemane68bcd12005-07-30 00:15:07 +0000218 // Analyze all of the subscripts of this getelementptr instruction, looking
219 // for uses that are determined by the trip count of L. First, skip all
220 // operands the are not dependent on the IV.
221
222 // Build up the base expression. Insert an LLVM cast of the pointer to
223 // uintptr_t first.
Chris Lattnereaf24722005-08-04 17:40:30 +0000224 SCEVHandle GEPVal = SCEVUnknown::get(getCastedVersionOf(GEP->getOperand(0)));
Nate Begemane68bcd12005-07-30 00:15:07 +0000225
226 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnereaf24722005-08-04 17:40:30 +0000227
228 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
Nate Begemane68bcd12005-07-30 00:15:07 +0000229 // If this is a use of a recurrence that we can analyze, and it comes before
230 // Op does in the GEP operand list, we will handle this when we process this
231 // operand.
232 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
233 const StructLayout *SL = TD->getStructLayout(STy);
234 unsigned Idx = cast<ConstantUInt>(GEP->getOperand(i))->getValue();
235 uint64_t Offset = SL->MemberOffsets[Idx];
Chris Lattnereaf24722005-08-04 17:40:30 +0000236 GEPVal = SCEVAddExpr::get(GEPVal,
237 SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy));
Nate Begemane68bcd12005-07-30 00:15:07 +0000238 } else {
Chris Lattneracc42c42005-08-04 19:08:16 +0000239 Value *OpVal = getCastedVersionOf(GEP->getOperand(i));
240 SCEVHandle Idx = SE->getSCEV(OpVal);
241
Chris Lattnereaf24722005-08-04 17:40:30 +0000242 uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
243 if (TypeSize != 1)
244 Idx = SCEVMulExpr::get(Idx,
245 SCEVConstant::get(ConstantUInt::get(UIntPtrTy,
246 TypeSize)));
247 GEPVal = SCEVAddExpr::get(GEPVal, Idx);
Nate Begemane68bcd12005-07-30 00:15:07 +0000248 }
249 }
250
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000251 SE->setSCEV(GEP, GEPVal);
Chris Lattnereaf24722005-08-04 17:40:30 +0000252 return GEPVal;
Nate Begemane68bcd12005-07-30 00:15:07 +0000253}
254
Chris Lattneracc42c42005-08-04 19:08:16 +0000255/// getSCEVStartAndStride - Compute the start and stride of this expression,
256/// returning false if the expression is not a start/stride pair, or true if it
257/// is. The stride must be a loop invariant expression, but the start may be
258/// a mix of loop invariant and loop variant expressions.
259static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
Chris Lattneredff91a2005-08-10 00:45:21 +0000260 SCEVHandle &Start, SCEVHandle &Stride) {
Chris Lattneracc42c42005-08-04 19:08:16 +0000261 SCEVHandle TheAddRec = Start; // Initialize to zero.
262
263 // If the outer level is an AddExpr, the operands are all start values except
264 // for a nested AddRecExpr.
265 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
266 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
267 if (SCEVAddRecExpr *AddRec =
268 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
269 if (AddRec->getLoop() == L)
270 TheAddRec = SCEVAddExpr::get(AddRec, TheAddRec);
271 else
272 return false; // Nested IV of some sort?
273 } else {
274 Start = SCEVAddExpr::get(Start, AE->getOperand(i));
275 }
276
277 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SH)) {
278 TheAddRec = SH;
279 } else {
280 return false; // not analyzable.
281 }
282
283 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
284 if (!AddRec || AddRec->getLoop() != L) return false;
285
286 // FIXME: Generalize to non-affine IV's.
287 if (!AddRec->isAffine()) return false;
288
289 Start = SCEVAddExpr::get(Start, AddRec->getOperand(0));
290
Chris Lattneracc42c42005-08-04 19:08:16 +0000291 if (!isa<SCEVConstant>(AddRec->getOperand(1)))
Chris Lattneredff91a2005-08-10 00:45:21 +0000292 DEBUG(std::cerr << "[" << L->getHeader()->getName()
293 << "] Variable stride: " << *AddRec << "\n");
Chris Lattneracc42c42005-08-04 19:08:16 +0000294
Chris Lattneredff91a2005-08-10 00:45:21 +0000295 Stride = AddRec->getOperand(1);
296 // Check that all constant strides are the unsigned type, we don't want to
297 // have two IV's one of signed stride 4 and one of unsigned stride 4 to not be
298 // merged.
299 assert((!isa<SCEVConstant>(Stride) || Stride->getType()->isUnsigned()) &&
Chris Lattneracc42c42005-08-04 19:08:16 +0000300 "Constants should be canonicalized to unsigned!");
Chris Lattneredff91a2005-08-10 00:45:21 +0000301
Chris Lattneracc42c42005-08-04 19:08:16 +0000302 return true;
303}
304
Nate Begemane68bcd12005-07-30 00:15:07 +0000305/// AddUsersIfInteresting - Inspect the specified instruction. If it is a
306/// reducible SCEV, recursively add its users to the IVUsesByStride set and
307/// return true. Otherwise, return false.
Chris Lattnereaf24722005-08-04 17:40:30 +0000308bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
309 std::set<Instruction*> &Processed) {
Nate Begeman17a0e2af2005-07-30 00:21:31 +0000310 if (I->getType() == Type::VoidTy) return false;
Chris Lattnereaf24722005-08-04 17:40:30 +0000311 if (!Processed.insert(I).second)
312 return true; // Instruction already handled.
313
Chris Lattneracc42c42005-08-04 19:08:16 +0000314 // Get the symbolic expression for this instruction.
Chris Lattnereaf24722005-08-04 17:40:30 +0000315 SCEVHandle ISE = GetExpressionSCEV(I, L);
Chris Lattneracc42c42005-08-04 19:08:16 +0000316 if (isa<SCEVCouldNotCompute>(ISE)) return false;
Chris Lattnereaf24722005-08-04 17:40:30 +0000317
Chris Lattneracc42c42005-08-04 19:08:16 +0000318 // Get the start and stride for this expression.
319 SCEVHandle Start = SCEVUnknown::getIntegerSCEV(0, ISE->getType());
Chris Lattneredff91a2005-08-10 00:45:21 +0000320 SCEVHandle Stride = Start;
Chris Lattneracc42c42005-08-04 19:08:16 +0000321 if (!getSCEVStartAndStride(ISE, L, Start, Stride))
322 return false; // Non-reducible symbolic expression, bail out.
323
Nate Begemane68bcd12005-07-30 00:15:07 +0000324 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){
325 Instruction *User = cast<Instruction>(*UI);
326
327 // Do not infinitely recurse on PHI nodes.
328 if (isa<PHINode>(User) && User->getParent() == L->getHeader())
329 continue;
330
331 // If this is an instruction defined in a nested loop, or outside this loop,
Chris Lattnera0102fb2005-08-04 00:14:11 +0000332 // don't recurse into it.
Chris Lattneracc42c42005-08-04 19:08:16 +0000333 bool AddUserToIVUsers = false;
Chris Lattnera0102fb2005-08-04 00:14:11 +0000334 if (LI->getLoopFor(User->getParent()) != L) {
335 DEBUG(std::cerr << "FOUND USER in nested loop: " << *User
336 << " OF SCEV: " << *ISE << "\n");
Chris Lattneracc42c42005-08-04 19:08:16 +0000337 AddUserToIVUsers = true;
Chris Lattnereaf24722005-08-04 17:40:30 +0000338 } else if (!AddUsersIfInteresting(User, L, Processed)) {
Chris Lattner65107492005-08-04 00:40:47 +0000339 DEBUG(std::cerr << "FOUND USER: " << *User
340 << " OF SCEV: " << *ISE << "\n");
Chris Lattneracc42c42005-08-04 19:08:16 +0000341 AddUserToIVUsers = true;
342 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000343
Chris Lattneracc42c42005-08-04 19:08:16 +0000344 if (AddUserToIVUsers) {
Chris Lattner65107492005-08-04 00:40:47 +0000345 // Okay, we found a user that we cannot reduce. Analyze the instruction
346 // and decide what to do with it.
Chris Lattneracc42c42005-08-04 19:08:16 +0000347 IVUsesByStride[Stride].addUser(Start, User, I);
Nate Begemane68bcd12005-07-30 00:15:07 +0000348 }
349 }
350 return true;
351}
352
353namespace {
354 /// BasedUser - For a particular base value, keep information about how we've
355 /// partitioned the expression so far.
356 struct BasedUser {
Chris Lattner37c24cc2005-08-08 22:56:21 +0000357 /// Base - The Base value for the PHI node that needs to be inserted for
358 /// this use. As the use is processed, information gets moved from this
359 /// field to the Imm field (below). BasedUser values are sorted by this
360 /// field.
361 SCEVHandle Base;
362
Nate Begemane68bcd12005-07-30 00:15:07 +0000363 /// Inst - The instruction using the induction variable.
364 Instruction *Inst;
365
Chris Lattner430d0022005-08-03 22:21:05 +0000366 /// OperandValToReplace - The operand value of Inst to replace with the
367 /// EmittedBase.
368 Value *OperandValToReplace;
Nate Begemane68bcd12005-07-30 00:15:07 +0000369
370 /// Imm - The immediate value that should be added to the base immediately
371 /// before Inst, because it will be folded into the imm field of the
372 /// instruction.
373 SCEVHandle Imm;
374
375 /// EmittedBase - The actual value* to use for the base value of this
376 /// operation. This is null if we should just use zero so far.
377 Value *EmittedBase;
378
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000379 // isUseOfPostIncrementedValue - True if this should use the
380 // post-incremented version of this IV, not the preincremented version.
381 // This can only be set in special cases, such as the terminating setcc
382 // instruction for a loop.
383 bool isUseOfPostIncrementedValue;
Chris Lattner37c24cc2005-08-08 22:56:21 +0000384
385 BasedUser(IVStrideUse &IVSU)
386 : Base(IVSU.Offset), Inst(IVSU.User),
387 OperandValToReplace(IVSU.OperandValToReplace),
388 Imm(SCEVUnknown::getIntegerSCEV(0, Base->getType())), EmittedBase(0),
389 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
Nate Begemane68bcd12005-07-30 00:15:07 +0000390
Chris Lattnera6d7c352005-08-04 20:03:32 +0000391 // Once we rewrite the code to insert the new IVs we want, update the
392 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
393 // to it.
Chris Lattnera091ff12005-08-09 00:18:09 +0000394 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattner4fec86d2005-08-12 22:06:11 +0000395 SCEVExpander &Rewriter, Pass *P);
Nate Begemane68bcd12005-07-30 00:15:07 +0000396
Chris Lattner37c24cc2005-08-08 22:56:21 +0000397 // Sort by the Base field.
398 bool operator<(const BasedUser &BU) const { return Base < BU.Base; }
Nate Begemane68bcd12005-07-30 00:15:07 +0000399
400 void dump() const;
401 };
402}
403
404void BasedUser::dump() const {
Chris Lattner37c24cc2005-08-08 22:56:21 +0000405 std::cerr << " Base=" << *Base;
Nate Begemane68bcd12005-07-30 00:15:07 +0000406 std::cerr << " Imm=" << *Imm;
407 if (EmittedBase)
408 std::cerr << " EB=" << *EmittedBase;
409
410 std::cerr << " Inst: " << *Inst;
411}
412
Chris Lattnera6d7c352005-08-04 20:03:32 +0000413// Once we rewrite the code to insert the new IVs we want, update the
414// operands of Inst to use the new expression 'NewBase', with 'Imm' added
415// to it.
Chris Lattnera091ff12005-08-09 00:18:09 +0000416void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattner4fec86d2005-08-12 22:06:11 +0000417 SCEVExpander &Rewriter,
418 Pass *P) {
Chris Lattnera6d7c352005-08-04 20:03:32 +0000419 if (!isa<PHINode>(Inst)) {
Chris Lattnera091ff12005-08-09 00:18:09 +0000420 SCEVHandle NewValSCEV = SCEVAddExpr::get(NewBase, Imm);
Chris Lattnera6d7c352005-08-04 20:03:32 +0000421 Value *NewVal = Rewriter.expandCodeFor(NewValSCEV, Inst,
422 OperandValToReplace->getType());
Chris Lattnera6d7c352005-08-04 20:03:32 +0000423 // Replace the use of the operand Value with the new Phi we just created.
424 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
425 DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst);
426 return;
427 }
428
429 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000430 // expression into each operand block that uses it. Note that PHI nodes can
431 // have multiple entries for the same predecessor. We use a map to make sure
432 // that a PHI node only has a single Value* for each predecessor (which also
433 // prevents us from inserting duplicate code in some blocks).
434 std::map<BasicBlock*, Value*> InsertedCode;
Chris Lattnera6d7c352005-08-04 20:03:32 +0000435 PHINode *PN = cast<PHINode>(Inst);
436 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
437 if (PN->getIncomingValue(i) == OperandValToReplace) {
Chris Lattner4fec86d2005-08-12 22:06:11 +0000438 // If this is a critical edge, split the edge so that we do not insert the
439 // code on all predecessor/successor paths.
440 if (e != 1 &&
441 PN->getIncomingBlock(i)->getTerminator()->getNumSuccessors() > 1) {
442 TerminatorInst *PredTI = PN->getIncomingBlock(i)->getTerminator();
443 for (unsigned Succ = 0; ; ++Succ) {
444 assert(Succ != PredTI->getNumSuccessors() &&"Didn't find successor?");
445 if (PredTI->getSuccessor(Succ) == PN->getParent()) {
446 SplitCriticalEdge(PredTI, Succ, P);
447 break;
448 }
449 }
450 }
Chris Lattnera6d7c352005-08-04 20:03:32 +0000451
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000452 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
453 if (!Code) {
454 // Insert the code into the end of the predecessor block.
455 BasicBlock::iterator InsertPt =PN->getIncomingBlock(i)->getTerminator();
Chris Lattnera6d7c352005-08-04 20:03:32 +0000456
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000457 SCEVHandle NewValSCEV = SCEVAddExpr::get(NewBase, Imm);
458 Code = Rewriter.expandCodeFor(NewValSCEV, InsertPt,
459 OperandValToReplace->getType());
460 }
Chris Lattnera6d7c352005-08-04 20:03:32 +0000461
462 // Replace the use of the operand Value with the new Phi we just created.
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000463 PN->setIncomingValue(i, Code);
Chris Lattnera6d7c352005-08-04 20:03:32 +0000464 Rewriter.clear();
465 }
466 }
467 DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst);
468}
469
470
Nate Begemane68bcd12005-07-30 00:15:07 +0000471/// isTargetConstant - Return true if the following can be referenced by the
472/// immediate field of a target instruction.
473static bool isTargetConstant(const SCEVHandle &V) {
Jeff Cohen546fd592005-07-30 18:33:25 +0000474
Nate Begemane68bcd12005-07-30 00:15:07 +0000475 // FIXME: Look at the target to decide if &GV is a legal constant immediate.
Chris Lattner14203e82005-08-08 06:25:50 +0000476 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
477 // PPC allows a sign-extended 16-bit immediate field.
478 if ((int64_t)SC->getValue()->getRawValue() > -(1 << 16) &&
479 (int64_t)SC->getValue()->getRawValue() < (1 << 16)-1)
480 return true;
481 return false;
482 }
Jeff Cohen546fd592005-07-30 18:33:25 +0000483
Nate Begemane68bcd12005-07-30 00:15:07 +0000484 return false; // ENABLE this for x86
Jeff Cohen546fd592005-07-30 18:33:25 +0000485
Nate Begemane68bcd12005-07-30 00:15:07 +0000486 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
487 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
488 if (CE->getOpcode() == Instruction::Cast)
489 if (isa<GlobalValue>(CE->getOperand(0)))
490 // FIXME: should check to see that the dest is uintptr_t!
491 return true;
492 return false;
493}
494
Chris Lattner37ed8952005-08-08 22:32:34 +0000495/// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
496/// loop varying to the Imm operand.
497static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
498 Loop *L) {
499 if (Val->isLoopInvariant(L)) return; // Nothing to do.
500
501 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
502 std::vector<SCEVHandle> NewOps;
503 NewOps.reserve(SAE->getNumOperands());
504
505 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
506 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
507 // If this is a loop-variant expression, it must stay in the immediate
508 // field of the expression.
509 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
510 } else {
511 NewOps.push_back(SAE->getOperand(i));
512 }
513
514 if (NewOps.empty())
515 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
516 else
517 Val = SCEVAddExpr::get(NewOps);
518 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
519 // Try to pull immediates out of the start value of nested addrec's.
520 SCEVHandle Start = SARE->getStart();
521 MoveLoopVariantsToImediateField(Start, Imm, L);
522
523 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
524 Ops[0] = Start;
525 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
526 } else {
527 // Otherwise, all of Val is variant, move the whole thing over.
528 Imm = SCEVAddExpr::get(Imm, Val);
529 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
530 }
531}
532
533
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000534/// MoveImmediateValues - Look at Val, and pull out any additions of constants
Nate Begemane68bcd12005-07-30 00:15:07 +0000535/// that can fit into the immediate field of instructions in the target.
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000536/// Accumulate these immediate values into the Imm value.
537static void MoveImmediateValues(SCEVHandle &Val, SCEVHandle &Imm,
538 bool isAddress, Loop *L) {
Chris Lattnerfc624702005-08-03 23:44:42 +0000539 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000540 std::vector<SCEVHandle> NewOps;
541 NewOps.reserve(SAE->getNumOperands());
542
543 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
Chris Lattneracc42c42005-08-04 19:08:16 +0000544 if (isAddress && isTargetConstant(SAE->getOperand(i))) {
545 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
546 } else if (!SAE->getOperand(i)->isLoopInvariant(L)) {
547 // If this is a loop-variant expression, it must stay in the immediate
548 // field of the expression.
549 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000550 } else {
551 NewOps.push_back(SAE->getOperand(i));
Nate Begemane68bcd12005-07-30 00:15:07 +0000552 }
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000553
554 if (NewOps.empty())
555 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
556 else
557 Val = SCEVAddExpr::get(NewOps);
558 return;
Chris Lattnerfc624702005-08-03 23:44:42 +0000559 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
560 // Try to pull immediates out of the start value of nested addrec's.
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000561 SCEVHandle Start = SARE->getStart();
562 MoveImmediateValues(Start, Imm, isAddress, L);
563
564 if (Start != SARE->getStart()) {
565 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
566 Ops[0] = Start;
567 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
568 }
569 return;
Nate Begemane68bcd12005-07-30 00:15:07 +0000570 }
571
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000572 // Loop-variant expressions must stay in the immediate field of the
573 // expression.
574 if ((isAddress && isTargetConstant(Val)) ||
575 !Val->isLoopInvariant(L)) {
576 Imm = SCEVAddExpr::get(Imm, Val);
577 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
578 return;
Chris Lattner0f7c0fa2005-08-04 19:26:19 +0000579 }
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000580
581 // Otherwise, no immediates to move.
Nate Begemane68bcd12005-07-30 00:15:07 +0000582}
583
Chris Lattnera091ff12005-08-09 00:18:09 +0000584/// RemoveCommonExpressionsFromUseBases - Look through all of the uses in Bases,
585/// removing any common subexpressions from it. Anything truly common is
586/// removed, accumulated, and returned. This looks for things like (a+b+c) and
587/// (a+c+d) -> (a+c). The common expression is *removed* from the Bases.
588static SCEVHandle
589RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses) {
590 unsigned NumUses = Uses.size();
591
592 // Only one use? Use its base, regardless of what it is!
593 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Uses[0].Base->getType());
594 SCEVHandle Result = Zero;
595 if (NumUses == 1) {
596 std::swap(Result, Uses[0].Base);
597 return Result;
598 }
599
600 // To find common subexpressions, count how many of Uses use each expression.
601 // If any subexpressions are used Uses.size() times, they are common.
602 std::map<SCEVHandle, unsigned> SubExpressionUseCounts;
603
604 for (unsigned i = 0; i != NumUses; ++i)
605 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Uses[i].Base)) {
606 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
607 SubExpressionUseCounts[AE->getOperand(j)]++;
608 } else {
609 // If the base is zero (which is common), return zero now, there are no
610 // CSEs we can find.
611 if (Uses[i].Base == Zero) return Result;
612 SubExpressionUseCounts[Uses[i].Base]++;
613 }
614
615 // Now that we know how many times each is used, build Result.
616 for (std::map<SCEVHandle, unsigned>::iterator I =
617 SubExpressionUseCounts.begin(), E = SubExpressionUseCounts.end();
618 I != E; )
619 if (I->second == NumUses) { // Found CSE!
620 Result = SCEVAddExpr::get(Result, I->first);
621 ++I;
622 } else {
623 // Remove non-cse's from SubExpressionUseCounts.
624 SubExpressionUseCounts.erase(I++);
625 }
626
627 // If we found no CSE's, return now.
628 if (Result == Zero) return Result;
629
630 // Otherwise, remove all of the CSE's we found from each of the base values.
631 for (unsigned i = 0; i != NumUses; ++i)
632 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Uses[i].Base)) {
633 std::vector<SCEVHandle> NewOps;
634
635 // Remove all of the values that are now in SubExpressionUseCounts.
636 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
637 if (!SubExpressionUseCounts.count(AE->getOperand(j)))
638 NewOps.push_back(AE->getOperand(j));
Chris Lattner4fec86d2005-08-12 22:06:11 +0000639 if (NewOps.empty())
Chris Lattner02742712005-08-09 01:13:47 +0000640 Uses[i].Base = Zero;
641 else
642 Uses[i].Base = SCEVAddExpr::get(NewOps);
Chris Lattnera091ff12005-08-09 00:18:09 +0000643 } else {
644 // If the base is zero (which is common), return zero now, there are no
645 // CSEs we can find.
646 assert(Uses[i].Base == Result);
647 Uses[i].Base = Zero;
648 }
649
650 return Result;
651}
652
653
Nate Begemane68bcd12005-07-30 00:15:07 +0000654/// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
655/// stride of IV. All of the users may have different starting values, and this
656/// may not be the only stride (we know it is if isOnlyStride is true).
Chris Lattneredff91a2005-08-10 00:45:21 +0000657void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
Chris Lattner430d0022005-08-03 22:21:05 +0000658 IVUsersOfOneStride &Uses,
659 Loop *L,
Nate Begemane68bcd12005-07-30 00:15:07 +0000660 bool isOnlyStride) {
661 // Transform our list of users and offsets to a bit more complex table. In
Chris Lattner37c24cc2005-08-08 22:56:21 +0000662 // this new vector, each 'BasedUser' contains 'Base' the base of the
663 // strided accessas well as the old information from Uses. We progressively
664 // move information from the Base field to the Imm field, until we eventually
665 // have the full access expression to rewrite the use.
666 std::vector<BasedUser> UsersToProcess;
Nate Begemane68bcd12005-07-30 00:15:07 +0000667 UsersToProcess.reserve(Uses.Users.size());
Chris Lattner37c24cc2005-08-08 22:56:21 +0000668 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
669 UsersToProcess.push_back(Uses.Users[i]);
670
671 // Move any loop invariant operands from the offset field to the immediate
672 // field of the use, so that we don't try to use something before it is
673 // computed.
674 MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
675 UsersToProcess.back().Imm, L);
676 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000677 "Base value is not loop invariant!");
Nate Begemane68bcd12005-07-30 00:15:07 +0000678 }
Chris Lattner37ed8952005-08-08 22:32:34 +0000679
Chris Lattnera091ff12005-08-09 00:18:09 +0000680 // We now have a whole bunch of uses of like-strided induction variables, but
681 // they might all have different bases. We want to emit one PHI node for this
682 // stride which we fold as many common expressions (between the IVs) into as
683 // possible. Start by identifying the common expressions in the base values
684 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
685 // "A+B"), emit it to the preheader, then remove the expression from the
686 // UsersToProcess base values.
687 SCEVHandle CommonExprs = RemoveCommonExpressionsFromUseBases(UsersToProcess);
688
Chris Lattner37ed8952005-08-08 22:32:34 +0000689 // Next, figure out what we can represent in the immediate fields of
690 // instructions. If we can represent anything there, move it to the imm
Chris Lattnera091ff12005-08-09 00:18:09 +0000691 // fields of the BasedUsers. We do this so that it increases the commonality
692 // of the remaining uses.
Chris Lattner37ed8952005-08-08 22:32:34 +0000693 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
694 // Addressing modes can be folded into loads and stores. Be careful that
695 // the store is through the expression, not of the expression though.
Chris Lattner37c24cc2005-08-08 22:56:21 +0000696 bool isAddress = isa<LoadInst>(UsersToProcess[i].Inst);
697 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
698 if (SI->getOperand(1) == UsersToProcess[i].OperandValToReplace)
Chris Lattner37ed8952005-08-08 22:32:34 +0000699 isAddress = true;
700
Chris Lattner37c24cc2005-08-08 22:56:21 +0000701 MoveImmediateValues(UsersToProcess[i].Base, UsersToProcess[i].Imm,
Chris Lattner37ed8952005-08-08 22:32:34 +0000702 isAddress, L);
703 }
704
Chris Lattnera091ff12005-08-09 00:18:09 +0000705 // Now that we know what we need to do, insert the PHI node itself.
706 //
707 DEBUG(std::cerr << "INSERTING IV of STRIDE " << *Stride << " and BASE "
708 << *CommonExprs << " :\n");
709
710 SCEVExpander Rewriter(*SE, *LI);
711 SCEVExpander PreheaderRewriter(*SE, *LI);
Chris Lattner37ed8952005-08-08 22:32:34 +0000712
Chris Lattnera091ff12005-08-09 00:18:09 +0000713 BasicBlock *Preheader = L->getLoopPreheader();
714 Instruction *PreInsertPt = Preheader->getTerminator();
715 Instruction *PhiInsertBefore = L->getHeader()->begin();
Chris Lattner37ed8952005-08-08 22:32:34 +0000716
Chris Lattnera091ff12005-08-09 00:18:09 +0000717 assert(isa<PHINode>(PhiInsertBefore) &&
718 "How could this loop have IV's without any phis?");
719 PHINode *SomeLoopPHI = cast<PHINode>(PhiInsertBefore);
720 assert(SomeLoopPHI->getNumIncomingValues() == 2 &&
721 "This loop isn't canonicalized right");
722 BasicBlock *LatchBlock =
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000723 SomeLoopPHI->getIncomingBlock(SomeLoopPHI->getIncomingBlock(0) == Preheader);
Chris Lattnerbb78c972005-08-03 23:30:08 +0000724
Chris Lattnera091ff12005-08-09 00:18:09 +0000725 // Create a new Phi for this base, and stick it in the loop header.
726 const Type *ReplacedTy = CommonExprs->getType();
727 PHINode *NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
728 ++NumInserted;
729
Chris Lattneredff91a2005-08-10 00:45:21 +0000730 // Insert the stride into the preheader.
731 Value *StrideV = PreheaderRewriter.expandCodeFor(Stride, PreInsertPt,
732 ReplacedTy);
733 if (!isa<ConstantInt>(StrideV)) ++NumVariable;
734
735
Chris Lattnera091ff12005-08-09 00:18:09 +0000736 // Emit the initial base value into the loop preheader, and add it to the
737 // Phi node.
738 Value *PHIBaseV = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt,
739 ReplacedTy);
740 NewPHI->addIncoming(PHIBaseV, Preheader);
741
742 // Emit the increment of the base value before the terminator of the loop
743 // latch block, and add it to the Phi node.
744 SCEVHandle IncExp = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
Chris Lattneredff91a2005-08-10 00:45:21 +0000745 SCEVUnknown::get(StrideV));
Chris Lattnera091ff12005-08-09 00:18:09 +0000746
747 Value *IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator(),
748 ReplacedTy);
749 IncV->setName(NewPHI->getName()+".inc");
750 NewPHI->addIncoming(IncV, LatchBlock);
751
Chris Lattnerdb23c742005-08-03 22:51:21 +0000752 // Sort by the base value, so that all IVs with identical bases are next to
Chris Lattnera091ff12005-08-09 00:18:09 +0000753 // each other.
Chris Lattnerdb23c742005-08-03 22:51:21 +0000754 std::sort(UsersToProcess.begin(), UsersToProcess.end());
Nate Begemane68bcd12005-07-30 00:15:07 +0000755 while (!UsersToProcess.empty()) {
Chris Lattner37c24cc2005-08-08 22:56:21 +0000756 SCEVHandle Base = UsersToProcess.front().Base;
Chris Lattnerbb78c972005-08-03 23:30:08 +0000757
Chris Lattnera091ff12005-08-09 00:18:09 +0000758 DEBUG(std::cerr << " INSERTING code for BASE = " << *Base << ":\n");
Chris Lattnerbb78c972005-08-03 23:30:08 +0000759
Chris Lattnera091ff12005-08-09 00:18:09 +0000760 // Emit the code for Base into the preheader.
Chris Lattnerc70bbc02005-08-08 05:47:49 +0000761 Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt,
762 ReplacedTy);
Chris Lattnera091ff12005-08-09 00:18:09 +0000763
764 // If BaseV is a constant other than 0, make sure that it gets inserted into
765 // the preheader, instead of being forward substituted into the uses. We do
766 // this by forcing a noop cast to be inserted into the preheader in this
767 // case.
768 if (Constant *C = dyn_cast<Constant>(BaseV))
769 if (!C->isNullValue()) {
770 // We want this constant emitted into the preheader!
771 BaseV = new CastInst(BaseV, BaseV->getType(), "preheaderinsert",
772 PreInsertPt);
773 }
774
Nate Begemane68bcd12005-07-30 00:15:07 +0000775 // Emit the code to add the immediate offset to the Phi value, just before
Chris Lattnerdb23c742005-08-03 22:51:21 +0000776 // the instructions that we identified as using this stride and base.
Chris Lattner37c24cc2005-08-08 22:56:21 +0000777 while (!UsersToProcess.empty() && UsersToProcess.front().Base == Base) {
778 BasedUser &User = UsersToProcess.front();
Jeff Cohen546fd592005-07-30 18:33:25 +0000779
Chris Lattnera091ff12005-08-09 00:18:09 +0000780 // If this instruction wants to use the post-incremented value, move it
781 // after the post-inc and use its value instead of the PHI.
782 Value *RewriteOp = NewPHI;
783 if (User.isUseOfPostIncrementedValue) {
784 RewriteOp = IncV;
785 User.Inst->moveBefore(LatchBlock->getTerminator());
786 }
787 SCEVHandle RewriteExpr = SCEVUnknown::get(RewriteOp);
788
Chris Lattnerdb23c742005-08-03 22:51:21 +0000789 // Clear the SCEVExpander's expression map so that we are guaranteed
790 // to have the code emitted where we expect it.
791 Rewriter.clear();
Chris Lattnera091ff12005-08-09 00:18:09 +0000792
Chris Lattnera6d7c352005-08-04 20:03:32 +0000793 // Now that we know what we need to do, insert code before User for the
794 // immediate and any loop-variant expressions.
Chris Lattnera091ff12005-08-09 00:18:09 +0000795 if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isNullValue())
796 // Add BaseV to the PHI value if needed.
797 RewriteExpr = SCEVAddExpr::get(RewriteExpr, SCEVUnknown::get(BaseV));
798
Chris Lattner4fec86d2005-08-12 22:06:11 +0000799 User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter, this);
Jeff Cohen546fd592005-07-30 18:33:25 +0000800
Chris Lattnerdb23c742005-08-03 22:51:21 +0000801 // Mark old value we replaced as possibly dead, so that it is elminated
802 // if we just replaced the last use of that value.
Chris Lattnera6d7c352005-08-04 20:03:32 +0000803 DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
Nate Begemane68bcd12005-07-30 00:15:07 +0000804
Chris Lattnerdb23c742005-08-03 22:51:21 +0000805 UsersToProcess.erase(UsersToProcess.begin());
806 ++NumReduced;
807 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000808 // TODO: Next, find out which base index is the most common, pull it out.
809 }
810
811 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
812 // different starting values, into different PHIs.
Nate Begemane68bcd12005-07-30 00:15:07 +0000813}
814
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000815// OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
816// uses in the loop, look to see if we can eliminate some, in favor of using
817// common indvars for the different uses.
818void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
819 // TODO: implement optzns here.
820
821
822
823
824 // Finally, get the terminating condition for the loop if possible. If we
825 // can, we want to change it to use a post-incremented version of its
826 // induction variable, to allow coallescing the live ranges for the IV into
827 // one register value.
828 PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
829 BasicBlock *Preheader = L->getLoopPreheader();
830 BasicBlock *LatchBlock =
831 SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
832 BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
833 if (!TermBr || TermBr->isUnconditional() ||
834 !isa<SetCondInst>(TermBr->getCondition()))
835 return;
836 SetCondInst *Cond = cast<SetCondInst>(TermBr->getCondition());
837
838 // Search IVUsesByStride to find Cond's IVUse if there is one.
839 IVStrideUse *CondUse = 0;
Chris Lattneredff91a2005-08-10 00:45:21 +0000840 const SCEVHandle *CondStride = 0;
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000841
Chris Lattneredff91a2005-08-10 00:45:21 +0000842 for (std::map<SCEVHandle, IVUsersOfOneStride>::iterator
843 I = IVUsesByStride.begin(), E = IVUsesByStride.end();
844 I != E && !CondUse; ++I)
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000845 for (std::vector<IVStrideUse>::iterator UI = I->second.Users.begin(),
846 E = I->second.Users.end(); UI != E; ++UI)
847 if (UI->User == Cond) {
848 CondUse = &*UI;
Chris Lattneredff91a2005-08-10 00:45:21 +0000849 CondStride = &I->first;
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000850 // NOTE: we could handle setcc instructions with multiple uses here, but
851 // InstCombine does it as well for simple uses, it's not clear that it
852 // occurs enough in real life to handle.
853 break;
854 }
855 if (!CondUse) return; // setcc doesn't use the IV.
856
857 // setcc stride is complex, don't mess with users.
Chris Lattneredff91a2005-08-10 00:45:21 +0000858 // FIXME: Evaluate whether this is a good idea or not.
859 if (!isa<SCEVConstant>(*CondStride)) return;
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000860
861 // It's possible for the setcc instruction to be anywhere in the loop, and
862 // possible for it to have multiple users. If it is not immediately before
863 // the latch block branch, move it.
864 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
865 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
866 Cond->moveBefore(TermBr);
867 } else {
868 // Otherwise, clone the terminating condition and insert into the loopend.
869 Cond = cast<SetCondInst>(Cond->clone());
870 Cond->setName(L->getHeader()->getName() + ".termcond");
871 LatchBlock->getInstList().insert(TermBr, Cond);
872
873 // Clone the IVUse, as the old use still exists!
Chris Lattneredff91a2005-08-10 00:45:21 +0000874 IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000875 CondUse->OperandValToReplace);
Chris Lattneredff91a2005-08-10 00:45:21 +0000876 CondUse = &IVUsesByStride[*CondStride].Users.back();
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000877 }
878 }
879
880 // If we get to here, we know that we can transform the setcc instruction to
881 // use the post-incremented version of the IV, allowing us to coallesce the
882 // live ranges for the IV correctly.
Chris Lattneredff91a2005-08-10 00:45:21 +0000883 CondUse->Offset = SCEV::getMinusSCEV(CondUse->Offset, *CondStride);
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000884 CondUse->isUseOfPostIncrementedValue = true;
885}
Nate Begemane68bcd12005-07-30 00:15:07 +0000886
Nate Begemanb18121e2004-10-18 21:08:22 +0000887void LoopStrengthReduce::runOnLoop(Loop *L) {
888 // First step, transform all loops nesting inside of this loop.
889 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
890 runOnLoop(*I);
891
Nate Begemane68bcd12005-07-30 00:15:07 +0000892 // Next, find all uses of induction variables in this loop, and catagorize
893 // them by stride. Start by finding all of the PHI nodes in the header for
894 // this loop. If they are induction variables, inspect their uses.
Chris Lattnereaf24722005-08-04 17:40:30 +0000895 std::set<Instruction*> Processed; // Don't reprocess instructions.
Nate Begemane68bcd12005-07-30 00:15:07 +0000896 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
Chris Lattnereaf24722005-08-04 17:40:30 +0000897 AddUsersIfInteresting(I, L, Processed);
Nate Begemanb18121e2004-10-18 21:08:22 +0000898
Nate Begemane68bcd12005-07-30 00:15:07 +0000899 // If we have nothing to do, return.
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000900 if (IVUsesByStride.empty()) return;
901
902 // Optimize induction variables. Some indvar uses can be transformed to use
903 // strides that will be needed for other purposes. A common example of this
904 // is the exit test for the loop, which can often be rewritten to use the
905 // computation of some other indvar to decide when to terminate the loop.
906 OptimizeIndvars(L);
907
Misha Brukmanb1c93172005-04-21 23:48:37 +0000908
Nate Begemane68bcd12005-07-30 00:15:07 +0000909 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
910 // doing computation in byte values, promote to 32-bit values if safe.
911
912 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
913 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
914 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
915 // to be careful that IV's are all the same type. Only works for intptr_t
916 // indvars.
917
918 // If we only have one stride, we can more aggressively eliminate some things.
919 bool HasOneStride = IVUsesByStride.size() == 1;
920
Chris Lattnera091ff12005-08-09 00:18:09 +0000921 // Note: this processes each stride/type pair individually. All users passed
922 // into StrengthReduceStridedIVUsers have the same type AND stride.
Chris Lattneredff91a2005-08-10 00:45:21 +0000923 for (std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI
Chris Lattner430d0022005-08-03 22:21:05 +0000924 = IVUsesByStride.begin(), E = IVUsesByStride.end(); SI != E; ++SI)
Nate Begemane68bcd12005-07-30 00:15:07 +0000925 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
Nate Begemanb18121e2004-10-18 21:08:22 +0000926
927 // Clean up after ourselves
928 if (!DeadInsts.empty()) {
929 DeleteTriviallyDeadInstructions(DeadInsts);
930
Nate Begemane68bcd12005-07-30 00:15:07 +0000931 BasicBlock::iterator I = L->getHeader()->begin();
932 PHINode *PN;
Chris Lattnerdcce49e2005-08-02 02:44:31 +0000933 while ((PN = dyn_cast<PHINode>(I))) {
Chris Lattner564900e2005-08-02 00:41:11 +0000934 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
935
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000936 // At this point, we know that we have killed one or more GEP
937 // instructions. It is worth checking to see if the cann indvar is also
938 // dead, so that we can remove it as well. The requirements for the cann
939 // indvar to be considered dead are:
Nate Begemane68bcd12005-07-30 00:15:07 +0000940 // 1. the cann indvar has one use
941 // 2. the use is an add instruction
942 // 3. the add has one use
943 // 4. the add is used by the cann indvar
944 // If all four cases above are true, then we can remove both the add and
945 // the cann indvar.
946 // FIXME: this needs to eliminate an induction variable even if it's being
947 // compared against some value to decide loop termination.
948 if (PN->hasOneUse()) {
949 BinaryOperator *BO = dyn_cast<BinaryOperator>(*(PN->use_begin()));
Chris Lattner75a44e12005-08-02 02:52:02 +0000950 if (BO && BO->hasOneUse()) {
951 if (PN == *(BO->use_begin())) {
952 DeadInsts.insert(BO);
953 // Break the cycle, then delete the PHI.
954 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattner84e9baa2005-08-03 21:36:09 +0000955 SE->deleteInstructionFromRecords(PN);
Chris Lattner75a44e12005-08-02 02:52:02 +0000956 PN->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +0000957 }
Chris Lattner75a44e12005-08-02 02:52:02 +0000958 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000959 }
Nate Begemanb18121e2004-10-18 21:08:22 +0000960 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000961 DeleteTriviallyDeadInstructions(DeadInsts);
Nate Begemanb18121e2004-10-18 21:08:22 +0000962 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000963
Chris Lattner11e7a5e2005-08-05 01:30:11 +0000964 CastedPointers.clear();
Nate Begemane68bcd12005-07-30 00:15:07 +0000965 IVUsesByStride.clear();
966 return;
Nate Begemanb18121e2004-10-18 21:08:22 +0000967}