blob: 547fd25d58a469eeb3606bb884d369fd50e49e0b [file] [log] [blame]
Nate Begemaneaa13852004-10-18 21:08:22 +00001//===- LoopStrengthReduce.cpp - Strength Reduce GEPs in Loops -------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Nate Begemaneaa13852004-10-18 21:08:22 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by Nate Begeman and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
Nate Begemaneaa13852004-10-18 21:08:22 +00008//===----------------------------------------------------------------------===//
9//
10// This pass performs a strength reduction on array references inside loops that
11// have as one or more of their components the loop induction variable. This is
12// accomplished by creating a new Value to hold the initial value of the array
13// access for the first iteration, and then creating a new GEP instruction in
14// the loop to increment the value by the appropriate amount.
15//
Nate Begemaneaa13852004-10-18 21:08:22 +000016//===----------------------------------------------------------------------===//
17
Chris Lattnerbe3e5212005-08-03 23:30:08 +000018#define DEBUG_TYPE "loop-reduce"
Nate Begemaneaa13852004-10-18 21:08:22 +000019#include "llvm/Transforms/Scalar.h"
20#include "llvm/Constants.h"
21#include "llvm/Instructions.h"
22#include "llvm/Type.h"
Jeff Cohen2f3c9b72005-03-04 04:04:26 +000023#include "llvm/DerivedTypes.h"
Nate Begemaneaa13852004-10-18 21:08:22 +000024#include "llvm/Analysis/Dominators.h"
25#include "llvm/Analysis/LoopInfo.h"
Nate Begeman16997482005-07-30 00:15:07 +000026#include "llvm/Analysis/ScalarEvolutionExpander.h"
Nate Begemaneaa13852004-10-18 21:08:22 +000027#include "llvm/Support/CFG.h"
Nate Begeman16997482005-07-30 00:15:07 +000028#include "llvm/Support/GetElementPtrTypeIterator.h"
Nate Begemaneaa13852004-10-18 21:08:22 +000029#include "llvm/Transforms/Utils/Local.h"
Jeff Cohen2f3c9b72005-03-04 04:04:26 +000030#include "llvm/Target/TargetData.h"
Nate Begemaneaa13852004-10-18 21:08:22 +000031#include "llvm/ADT/Statistic.h"
Nate Begeman16997482005-07-30 00:15:07 +000032#include "llvm/Support/Debug.h"
Jeff Cohencfb1d422005-07-30 18:22:27 +000033#include <algorithm>
Nate Begemaneaa13852004-10-18 21:08:22 +000034#include <set>
35using namespace llvm;
36
37namespace {
38 Statistic<> NumReduced ("loop-reduce", "Number of GEPs strength reduced");
Chris Lattner26d91f12005-08-04 22:34:05 +000039 Statistic<> NumInserted("loop-reduce", "Number of PHIs inserted");
Nate Begemaneaa13852004-10-18 21:08:22 +000040
Chris Lattnerec3fb632005-08-03 22:21:05 +000041 /// IVStrideUse - Keep track of one use of a strided induction variable, where
42 /// the stride is stored externally. The Offset member keeps track of the
43 /// offset from the IV, User is the actual user of the operand, and 'Operand'
44 /// is the operand # of the User that is the use.
45 struct IVStrideUse {
46 SCEVHandle Offset;
47 Instruction *User;
48 Value *OperandValToReplace;
Chris Lattner010de252005-08-08 05:28:22 +000049
50 // isUseOfPostIncrementedValue - True if this should use the
51 // post-incremented version of this IV, not the preincremented version.
52 // This can only be set in special cases, such as the terminating setcc
53 // instruction for a loop.
54 bool isUseOfPostIncrementedValue;
Chris Lattnerec3fb632005-08-03 22:21:05 +000055
56 IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
Chris Lattner010de252005-08-08 05:28:22 +000057 : Offset(Offs), User(U), OperandValToReplace(O),
58 isUseOfPostIncrementedValue(false) {}
Chris Lattnerec3fb632005-08-03 22:21:05 +000059 };
60
61 /// IVUsersOfOneStride - This structure keeps track of all instructions that
62 /// have an operand that is based on the trip count multiplied by some stride.
63 /// The stride for all of these users is common and kept external to this
64 /// structure.
65 struct IVUsersOfOneStride {
Nate Begeman16997482005-07-30 00:15:07 +000066 /// Users - Keep track of all of the users of this stride as well as the
Chris Lattnerec3fb632005-08-03 22:21:05 +000067 /// initial value and the operand that uses the IV.
68 std::vector<IVStrideUse> Users;
69
70 void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
71 Users.push_back(IVStrideUse(Offset, User, Operand));
Nate Begeman16997482005-07-30 00:15:07 +000072 }
73 };
74
75
Nate Begemaneaa13852004-10-18 21:08:22 +000076 class LoopStrengthReduce : public FunctionPass {
77 LoopInfo *LI;
78 DominatorSet *DS;
Nate Begeman16997482005-07-30 00:15:07 +000079 ScalarEvolution *SE;
80 const TargetData *TD;
81 const Type *UIntPtrTy;
Nate Begemaneaa13852004-10-18 21:08:22 +000082 bool Changed;
Chris Lattner7e608bb2005-08-02 02:52:02 +000083
84 /// MaxTargetAMSize - This is the maximum power-of-two scale value that the
85 /// target can handle for free with its addressing modes.
Jeff Cohen2f3c9b72005-03-04 04:04:26 +000086 unsigned MaxTargetAMSize;
Nate Begeman16997482005-07-30 00:15:07 +000087
88 /// IVUsesByStride - Keep track of all uses of induction variables that we
89 /// are interested in. The key of the map is the stride of the access.
Chris Lattnerec3fb632005-08-03 22:21:05 +000090 std::map<Value*, IVUsersOfOneStride> IVUsesByStride;
Nate Begeman16997482005-07-30 00:15:07 +000091
Chris Lattner49f72e62005-08-04 01:19:13 +000092 /// CastedValues - As we need to cast values to uintptr_t, this keeps track
93 /// of the casted version of each value. This is accessed by
94 /// getCastedVersionOf.
95 std::map<Value*, Value*> CastedPointers;
Nate Begeman16997482005-07-30 00:15:07 +000096
97 /// DeadInsts - Keep track of instructions we may have made dead, so that
98 /// we can remove them after we are done working.
99 std::set<Instruction*> DeadInsts;
Nate Begemaneaa13852004-10-18 21:08:22 +0000100 public:
Jeff Cohen2f3c9b72005-03-04 04:04:26 +0000101 LoopStrengthReduce(unsigned MTAMS = 1)
102 : MaxTargetAMSize(MTAMS) {
103 }
104
Nate Begemaneaa13852004-10-18 21:08:22 +0000105 virtual bool runOnFunction(Function &) {
106 LI = &getAnalysis<LoopInfo>();
107 DS = &getAnalysis<DominatorSet>();
Nate Begeman16997482005-07-30 00:15:07 +0000108 SE = &getAnalysis<ScalarEvolution>();
109 TD = &getAnalysis<TargetData>();
110 UIntPtrTy = TD->getIntPtrType();
Nate Begemaneaa13852004-10-18 21:08:22 +0000111 Changed = false;
112
113 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
114 runOnLoop(*I);
Chris Lattner49f72e62005-08-04 01:19:13 +0000115
Nate Begemaneaa13852004-10-18 21:08:22 +0000116 return Changed;
117 }
118
119 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
120 AU.setPreservesCFG();
Jeff Cohenf465db62005-02-27 19:37:07 +0000121 AU.addRequiredID(LoopSimplifyID);
Nate Begemaneaa13852004-10-18 21:08:22 +0000122 AU.addRequired<LoopInfo>();
123 AU.addRequired<DominatorSet>();
Jeff Cohen2f3c9b72005-03-04 04:04:26 +0000124 AU.addRequired<TargetData>();
Nate Begeman16997482005-07-30 00:15:07 +0000125 AU.addRequired<ScalarEvolution>();
Nate Begemaneaa13852004-10-18 21:08:22 +0000126 }
Chris Lattner49f72e62005-08-04 01:19:13 +0000127
128 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
129 ///
130 Value *getCastedVersionOf(Value *V);
131private:
Nate Begemaneaa13852004-10-18 21:08:22 +0000132 void runOnLoop(Loop *L);
Chris Lattner3416e5f2005-08-04 17:40:30 +0000133 bool AddUsersIfInteresting(Instruction *I, Loop *L,
134 std::set<Instruction*> &Processed);
135 SCEVHandle GetExpressionSCEV(Instruction *E, Loop *L);
136
Chris Lattner010de252005-08-08 05:28:22 +0000137 void OptimizeIndvars(Loop *L);
Nate Begeman16997482005-07-30 00:15:07 +0000138
Chris Lattnerec3fb632005-08-03 22:21:05 +0000139 void StrengthReduceStridedIVUsers(Value *Stride, IVUsersOfOneStride &Uses,
140 Loop *L, bool isOnlyStride);
Nate Begemaneaa13852004-10-18 21:08:22 +0000141 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
142 };
Misha Brukmanfd939082005-04-21 23:48:37 +0000143 RegisterOpt<LoopStrengthReduce> X("loop-reduce",
Nate Begemaneaa13852004-10-18 21:08:22 +0000144 "Strength Reduce GEP Uses of Ind. Vars");
145}
146
Jeff Cohen2f3c9b72005-03-04 04:04:26 +0000147FunctionPass *llvm::createLoopStrengthReducePass(unsigned MaxTargetAMSize) {
148 return new LoopStrengthReduce(MaxTargetAMSize);
Nate Begemaneaa13852004-10-18 21:08:22 +0000149}
150
Chris Lattner49f72e62005-08-04 01:19:13 +0000151/// getCastedVersionOf - Return the specified value casted to uintptr_t.
152///
153Value *LoopStrengthReduce::getCastedVersionOf(Value *V) {
154 if (V->getType() == UIntPtrTy) return V;
155 if (Constant *CB = dyn_cast<Constant>(V))
156 return ConstantExpr::getCast(CB, UIntPtrTy);
157
158 Value *&New = CastedPointers[V];
159 if (New) return New;
160
161 BasicBlock::iterator InsertPt;
162 if (Argument *Arg = dyn_cast<Argument>(V)) {
163 // Insert into the entry of the function, after any allocas.
164 InsertPt = Arg->getParent()->begin()->begin();
165 while (isa<AllocaInst>(InsertPt)) ++InsertPt;
166 } else {
167 if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
168 InsertPt = II->getNormalDest()->begin();
169 } else {
170 InsertPt = cast<Instruction>(V);
171 ++InsertPt;
172 }
173
174 // Do not insert casts into the middle of PHI node blocks.
175 while (isa<PHINode>(InsertPt)) ++InsertPt;
176 }
Chris Lattner7db543f2005-08-04 19:08:16 +0000177
178 New = new CastInst(V, UIntPtrTy, V->getName(), InsertPt);
179 DeadInsts.insert(cast<Instruction>(New));
180 return New;
Chris Lattner49f72e62005-08-04 01:19:13 +0000181}
182
183
Nate Begemaneaa13852004-10-18 21:08:22 +0000184/// DeleteTriviallyDeadInstructions - If any of the instructions is the
185/// specified set are trivially dead, delete them and see if this makes any of
186/// their operands subsequently dead.
187void LoopStrengthReduce::
188DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
189 while (!Insts.empty()) {
190 Instruction *I = *Insts.begin();
191 Insts.erase(Insts.begin());
192 if (isInstructionTriviallyDead(I)) {
Jeff Cohen0456e4a2005-03-01 03:46:11 +0000193 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
194 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
195 Insts.insert(U);
Chris Lattner52d83e62005-08-03 21:36:09 +0000196 SE->deleteInstructionFromRecords(I);
197 I->eraseFromParent();
Nate Begemaneaa13852004-10-18 21:08:22 +0000198 Changed = true;
199 }
200 }
201}
202
Jeff Cohenf465db62005-02-27 19:37:07 +0000203
Chris Lattner3416e5f2005-08-04 17:40:30 +0000204/// GetExpressionSCEV - Compute and return the SCEV for the specified
205/// instruction.
206SCEVHandle LoopStrengthReduce::GetExpressionSCEV(Instruction *Exp, Loop *L) {
Chris Lattner87265ab2005-08-09 23:39:36 +0000207 // Scalar Evolutions doesn't know how to compute SCEV's for GEP instructions.
208 // If this is a GEP that SE doesn't know about, compute it now and insert it.
209 // If this is not a GEP, or if we have already done this computation, just let
210 // SE figure it out.
Chris Lattner3416e5f2005-08-04 17:40:30 +0000211 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
Chris Lattner87265ab2005-08-09 23:39:36 +0000212 if (!GEP || SE->hasSCEV(GEP))
Chris Lattner3416e5f2005-08-04 17:40:30 +0000213 return SE->getSCEV(Exp);
214
Nate Begeman16997482005-07-30 00:15:07 +0000215 // Analyze all of the subscripts of this getelementptr instruction, looking
216 // for uses that are determined by the trip count of L. First, skip all
217 // operands the are not dependent on the IV.
218
219 // Build up the base expression. Insert an LLVM cast of the pointer to
220 // uintptr_t first.
Chris Lattner3416e5f2005-08-04 17:40:30 +0000221 SCEVHandle GEPVal = SCEVUnknown::get(getCastedVersionOf(GEP->getOperand(0)));
Nate Begeman16997482005-07-30 00:15:07 +0000222
223 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattner3416e5f2005-08-04 17:40:30 +0000224
225 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
Nate Begeman16997482005-07-30 00:15:07 +0000226 // If this is a use of a recurrence that we can analyze, and it comes before
227 // Op does in the GEP operand list, we will handle this when we process this
228 // operand.
229 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
230 const StructLayout *SL = TD->getStructLayout(STy);
231 unsigned Idx = cast<ConstantUInt>(GEP->getOperand(i))->getValue();
232 uint64_t Offset = SL->MemberOffsets[Idx];
Chris Lattner3416e5f2005-08-04 17:40:30 +0000233 GEPVal = SCEVAddExpr::get(GEPVal,
234 SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy));
Nate Begeman16997482005-07-30 00:15:07 +0000235 } else {
Chris Lattner7db543f2005-08-04 19:08:16 +0000236 Value *OpVal = getCastedVersionOf(GEP->getOperand(i));
237 SCEVHandle Idx = SE->getSCEV(OpVal);
238
Chris Lattner3416e5f2005-08-04 17:40:30 +0000239 uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
240 if (TypeSize != 1)
241 Idx = SCEVMulExpr::get(Idx,
242 SCEVConstant::get(ConstantUInt::get(UIntPtrTy,
243 TypeSize)));
244 GEPVal = SCEVAddExpr::get(GEPVal, Idx);
Nate Begeman16997482005-07-30 00:15:07 +0000245 }
246 }
247
Chris Lattner87265ab2005-08-09 23:39:36 +0000248 SE->setSCEV(GEP, GEPVal);
Chris Lattner3416e5f2005-08-04 17:40:30 +0000249 return GEPVal;
Nate Begeman16997482005-07-30 00:15:07 +0000250}
251
Chris Lattner7db543f2005-08-04 19:08:16 +0000252/// getSCEVStartAndStride - Compute the start and stride of this expression,
253/// returning false if the expression is not a start/stride pair, or true if it
254/// is. The stride must be a loop invariant expression, but the start may be
255/// a mix of loop invariant and loop variant expressions.
256static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
257 SCEVHandle &Start, Value *&Stride) {
258 SCEVHandle TheAddRec = Start; // Initialize to zero.
259
260 // If the outer level is an AddExpr, the operands are all start values except
261 // for a nested AddRecExpr.
262 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
263 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
264 if (SCEVAddRecExpr *AddRec =
265 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
266 if (AddRec->getLoop() == L)
267 TheAddRec = SCEVAddExpr::get(AddRec, TheAddRec);
268 else
269 return false; // Nested IV of some sort?
270 } else {
271 Start = SCEVAddExpr::get(Start, AE->getOperand(i));
272 }
273
274 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SH)) {
275 TheAddRec = SH;
276 } else {
277 return false; // not analyzable.
278 }
279
280 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
281 if (!AddRec || AddRec->getLoop() != L) return false;
282
283 // FIXME: Generalize to non-affine IV's.
284 if (!AddRec->isAffine()) return false;
285
286 Start = SCEVAddExpr::get(Start, AddRec->getOperand(0));
287
288 // FIXME: generalize to IV's with more complex strides (must emit stride
289 // expression outside of loop!)
290 if (!isa<SCEVConstant>(AddRec->getOperand(1)))
291 return false;
292
293 SCEVConstant *StrideC = cast<SCEVConstant>(AddRec->getOperand(1));
294 Stride = StrideC->getValue();
295
296 assert(Stride->getType()->isUnsigned() &&
297 "Constants should be canonicalized to unsigned!");
298 return true;
299}
300
Nate Begeman16997482005-07-30 00:15:07 +0000301/// AddUsersIfInteresting - Inspect the specified instruction. If it is a
302/// reducible SCEV, recursively add its users to the IVUsesByStride set and
303/// return true. Otherwise, return false.
Chris Lattner3416e5f2005-08-04 17:40:30 +0000304bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
305 std::set<Instruction*> &Processed) {
Nate Begemanf84d5ab2005-07-30 00:21:31 +0000306 if (I->getType() == Type::VoidTy) return false;
Chris Lattner3416e5f2005-08-04 17:40:30 +0000307 if (!Processed.insert(I).second)
308 return true; // Instruction already handled.
309
Chris Lattner7db543f2005-08-04 19:08:16 +0000310 // Get the symbolic expression for this instruction.
Chris Lattner3416e5f2005-08-04 17:40:30 +0000311 SCEVHandle ISE = GetExpressionSCEV(I, L);
Chris Lattner7db543f2005-08-04 19:08:16 +0000312 if (isa<SCEVCouldNotCompute>(ISE)) return false;
Chris Lattner3416e5f2005-08-04 17:40:30 +0000313
Chris Lattner7db543f2005-08-04 19:08:16 +0000314 // Get the start and stride for this expression.
315 SCEVHandle Start = SCEVUnknown::getIntegerSCEV(0, ISE->getType());
316 Value *Stride = 0;
317 if (!getSCEVStartAndStride(ISE, L, Start, Stride))
318 return false; // Non-reducible symbolic expression, bail out.
319
Nate Begeman16997482005-07-30 00:15:07 +0000320 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){
321 Instruction *User = cast<Instruction>(*UI);
322
323 // Do not infinitely recurse on PHI nodes.
324 if (isa<PHINode>(User) && User->getParent() == L->getHeader())
325 continue;
326
327 // If this is an instruction defined in a nested loop, or outside this loop,
Chris Lattnerf9186592005-08-04 00:14:11 +0000328 // don't recurse into it.
Chris Lattner7db543f2005-08-04 19:08:16 +0000329 bool AddUserToIVUsers = false;
Chris Lattnerf9186592005-08-04 00:14:11 +0000330 if (LI->getLoopFor(User->getParent()) != L) {
331 DEBUG(std::cerr << "FOUND USER in nested loop: " << *User
332 << " OF SCEV: " << *ISE << "\n");
Chris Lattner7db543f2005-08-04 19:08:16 +0000333 AddUserToIVUsers = true;
Chris Lattner3416e5f2005-08-04 17:40:30 +0000334 } else if (!AddUsersIfInteresting(User, L, Processed)) {
Chris Lattnera4479ad2005-08-04 00:40:47 +0000335 DEBUG(std::cerr << "FOUND USER: " << *User
336 << " OF SCEV: " << *ISE << "\n");
Chris Lattner7db543f2005-08-04 19:08:16 +0000337 AddUserToIVUsers = true;
338 }
Nate Begeman16997482005-07-30 00:15:07 +0000339
Chris Lattner7db543f2005-08-04 19:08:16 +0000340 if (AddUserToIVUsers) {
Chris Lattnera4479ad2005-08-04 00:40:47 +0000341 // Okay, we found a user that we cannot reduce. Analyze the instruction
342 // and decide what to do with it.
Chris Lattner7db543f2005-08-04 19:08:16 +0000343 IVUsesByStride[Stride].addUser(Start, User, I);
Nate Begeman16997482005-07-30 00:15:07 +0000344 }
345 }
346 return true;
347}
348
349namespace {
350 /// BasedUser - For a particular base value, keep information about how we've
351 /// partitioned the expression so far.
352 struct BasedUser {
Chris Lattnera553b0c2005-08-08 22:56:21 +0000353 /// Base - The Base value for the PHI node that needs to be inserted for
354 /// this use. As the use is processed, information gets moved from this
355 /// field to the Imm field (below). BasedUser values are sorted by this
356 /// field.
357 SCEVHandle Base;
358
Nate Begeman16997482005-07-30 00:15:07 +0000359 /// Inst - The instruction using the induction variable.
360 Instruction *Inst;
361
Chris Lattnerec3fb632005-08-03 22:21:05 +0000362 /// OperandValToReplace - The operand value of Inst to replace with the
363 /// EmittedBase.
364 Value *OperandValToReplace;
Nate Begeman16997482005-07-30 00:15:07 +0000365
366 /// Imm - The immediate value that should be added to the base immediately
367 /// before Inst, because it will be folded into the imm field of the
368 /// instruction.
369 SCEVHandle Imm;
370
371 /// EmittedBase - The actual value* to use for the base value of this
372 /// operation. This is null if we should just use zero so far.
373 Value *EmittedBase;
374
Chris Lattner010de252005-08-08 05:28:22 +0000375 // isUseOfPostIncrementedValue - True if this should use the
376 // post-incremented version of this IV, not the preincremented version.
377 // This can only be set in special cases, such as the terminating setcc
378 // instruction for a loop.
379 bool isUseOfPostIncrementedValue;
Chris Lattnera553b0c2005-08-08 22:56:21 +0000380
381 BasedUser(IVStrideUse &IVSU)
382 : Base(IVSU.Offset), Inst(IVSU.User),
383 OperandValToReplace(IVSU.OperandValToReplace),
384 Imm(SCEVUnknown::getIntegerSCEV(0, Base->getType())), EmittedBase(0),
385 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
Nate Begeman16997482005-07-30 00:15:07 +0000386
Chris Lattner2114b272005-08-04 20:03:32 +0000387 // Once we rewrite the code to insert the new IVs we want, update the
388 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
389 // to it.
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000390 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
391 SCEVExpander &Rewriter);
Nate Begeman16997482005-07-30 00:15:07 +0000392
Chris Lattnera553b0c2005-08-08 22:56:21 +0000393 // Sort by the Base field.
394 bool operator<(const BasedUser &BU) const { return Base < BU.Base; }
Nate Begeman16997482005-07-30 00:15:07 +0000395
396 void dump() const;
397 };
398}
399
400void BasedUser::dump() const {
Chris Lattnera553b0c2005-08-08 22:56:21 +0000401 std::cerr << " Base=" << *Base;
Nate Begeman16997482005-07-30 00:15:07 +0000402 std::cerr << " Imm=" << *Imm;
403 if (EmittedBase)
404 std::cerr << " EB=" << *EmittedBase;
405
406 std::cerr << " Inst: " << *Inst;
407}
408
Chris Lattner2114b272005-08-04 20:03:32 +0000409// Once we rewrite the code to insert the new IVs we want, update the
410// operands of Inst to use the new expression 'NewBase', with 'Imm' added
411// to it.
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000412void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattner2114b272005-08-04 20:03:32 +0000413 SCEVExpander &Rewriter) {
414 if (!isa<PHINode>(Inst)) {
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000415 SCEVHandle NewValSCEV = SCEVAddExpr::get(NewBase, Imm);
Chris Lattner2114b272005-08-04 20:03:32 +0000416 Value *NewVal = Rewriter.expandCodeFor(NewValSCEV, Inst,
417 OperandValToReplace->getType());
418
419 // Replace the use of the operand Value with the new Phi we just created.
420 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
421 DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst);
422 return;
423 }
424
425 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
Chris Lattnerc41e3452005-08-10 00:35:32 +0000426 // expression into each operand block that uses it. Note that PHI nodes can
427 // have multiple entries for the same predecessor. We use a map to make sure
428 // that a PHI node only has a single Value* for each predecessor (which also
429 // prevents us from inserting duplicate code in some blocks).
430 std::map<BasicBlock*, Value*> InsertedCode;
Chris Lattner2114b272005-08-04 20:03:32 +0000431 PHINode *PN = cast<PHINode>(Inst);
432 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
433 if (PN->getIncomingValue(i) == OperandValToReplace) {
434 // FIXME: this should split any critical edges.
435
Chris Lattnerc41e3452005-08-10 00:35:32 +0000436 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
437 if (!Code) {
438 // Insert the code into the end of the predecessor block.
439 BasicBlock::iterator InsertPt =PN->getIncomingBlock(i)->getTerminator();
Chris Lattner2114b272005-08-04 20:03:32 +0000440
Chris Lattnerc41e3452005-08-10 00:35:32 +0000441 SCEVHandle NewValSCEV = SCEVAddExpr::get(NewBase, Imm);
442 Code = Rewriter.expandCodeFor(NewValSCEV, InsertPt,
443 OperandValToReplace->getType());
444 }
Chris Lattner2114b272005-08-04 20:03:32 +0000445
446 // Replace the use of the operand Value with the new Phi we just created.
Chris Lattnerc41e3452005-08-10 00:35:32 +0000447 PN->setIncomingValue(i, Code);
Chris Lattner2114b272005-08-04 20:03:32 +0000448 Rewriter.clear();
449 }
450 }
451 DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst);
452}
453
454
Nate Begeman16997482005-07-30 00:15:07 +0000455/// isTargetConstant - Return true if the following can be referenced by the
456/// immediate field of a target instruction.
457static bool isTargetConstant(const SCEVHandle &V) {
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000458
Nate Begeman16997482005-07-30 00:15:07 +0000459 // FIXME: Look at the target to decide if &GV is a legal constant immediate.
Chris Lattner3821e472005-08-08 06:25:50 +0000460 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
461 // PPC allows a sign-extended 16-bit immediate field.
462 if ((int64_t)SC->getValue()->getRawValue() > -(1 << 16) &&
463 (int64_t)SC->getValue()->getRawValue() < (1 << 16)-1)
464 return true;
465 return false;
466 }
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000467
Nate Begeman16997482005-07-30 00:15:07 +0000468 return false; // ENABLE this for x86
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000469
Nate Begeman16997482005-07-30 00:15:07 +0000470 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
471 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
472 if (CE->getOpcode() == Instruction::Cast)
473 if (isa<GlobalValue>(CE->getOperand(0)))
474 // FIXME: should check to see that the dest is uintptr_t!
475 return true;
476 return false;
477}
478
Chris Lattner44b807e2005-08-08 22:32:34 +0000479/// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
480/// loop varying to the Imm operand.
481static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
482 Loop *L) {
483 if (Val->isLoopInvariant(L)) return; // Nothing to do.
484
485 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
486 std::vector<SCEVHandle> NewOps;
487 NewOps.reserve(SAE->getNumOperands());
488
489 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
490 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
491 // If this is a loop-variant expression, it must stay in the immediate
492 // field of the expression.
493 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
494 } else {
495 NewOps.push_back(SAE->getOperand(i));
496 }
497
498 if (NewOps.empty())
499 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
500 else
501 Val = SCEVAddExpr::get(NewOps);
502 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
503 // Try to pull immediates out of the start value of nested addrec's.
504 SCEVHandle Start = SARE->getStart();
505 MoveLoopVariantsToImediateField(Start, Imm, L);
506
507 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
508 Ops[0] = Start;
509 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
510 } else {
511 // Otherwise, all of Val is variant, move the whole thing over.
512 Imm = SCEVAddExpr::get(Imm, Val);
513 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
514 }
515}
516
517
Chris Lattner26d91f12005-08-04 22:34:05 +0000518/// MoveImmediateValues - Look at Val, and pull out any additions of constants
Nate Begeman16997482005-07-30 00:15:07 +0000519/// that can fit into the immediate field of instructions in the target.
Chris Lattner26d91f12005-08-04 22:34:05 +0000520/// Accumulate these immediate values into the Imm value.
521static void MoveImmediateValues(SCEVHandle &Val, SCEVHandle &Imm,
522 bool isAddress, Loop *L) {
Chris Lattner7a658392005-08-03 23:44:42 +0000523 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
Chris Lattner26d91f12005-08-04 22:34:05 +0000524 std::vector<SCEVHandle> NewOps;
525 NewOps.reserve(SAE->getNumOperands());
526
527 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
Chris Lattner7db543f2005-08-04 19:08:16 +0000528 if (isAddress && isTargetConstant(SAE->getOperand(i))) {
529 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
530 } else if (!SAE->getOperand(i)->isLoopInvariant(L)) {
531 // If this is a loop-variant expression, it must stay in the immediate
532 // field of the expression.
533 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
Chris Lattner26d91f12005-08-04 22:34:05 +0000534 } else {
535 NewOps.push_back(SAE->getOperand(i));
Nate Begeman16997482005-07-30 00:15:07 +0000536 }
Chris Lattner26d91f12005-08-04 22:34:05 +0000537
538 if (NewOps.empty())
539 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
540 else
541 Val = SCEVAddExpr::get(NewOps);
542 return;
Chris Lattner7a658392005-08-03 23:44:42 +0000543 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
544 // Try to pull immediates out of the start value of nested addrec's.
Chris Lattner26d91f12005-08-04 22:34:05 +0000545 SCEVHandle Start = SARE->getStart();
546 MoveImmediateValues(Start, Imm, isAddress, L);
547
548 if (Start != SARE->getStart()) {
549 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
550 Ops[0] = Start;
551 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
552 }
553 return;
Nate Begeman16997482005-07-30 00:15:07 +0000554 }
555
Chris Lattner26d91f12005-08-04 22:34:05 +0000556 // Loop-variant expressions must stay in the immediate field of the
557 // expression.
558 if ((isAddress && isTargetConstant(Val)) ||
559 !Val->isLoopInvariant(L)) {
560 Imm = SCEVAddExpr::get(Imm, Val);
561 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
562 return;
Chris Lattner7a2ca562005-08-04 19:26:19 +0000563 }
Chris Lattner26d91f12005-08-04 22:34:05 +0000564
565 // Otherwise, no immediates to move.
Nate Begeman16997482005-07-30 00:15:07 +0000566}
567
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000568/// RemoveCommonExpressionsFromUseBases - Look through all of the uses in Bases,
569/// removing any common subexpressions from it. Anything truly common is
570/// removed, accumulated, and returned. This looks for things like (a+b+c) and
571/// (a+c+d) -> (a+c). The common expression is *removed* from the Bases.
572static SCEVHandle
573RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses) {
574 unsigned NumUses = Uses.size();
575
576 // Only one use? Use its base, regardless of what it is!
577 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Uses[0].Base->getType());
578 SCEVHandle Result = Zero;
579 if (NumUses == 1) {
580 std::swap(Result, Uses[0].Base);
581 return Result;
582 }
583
584 // To find common subexpressions, count how many of Uses use each expression.
585 // If any subexpressions are used Uses.size() times, they are common.
586 std::map<SCEVHandle, unsigned> SubExpressionUseCounts;
587
588 for (unsigned i = 0; i != NumUses; ++i)
589 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Uses[i].Base)) {
590 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
591 SubExpressionUseCounts[AE->getOperand(j)]++;
592 } else {
593 // If the base is zero (which is common), return zero now, there are no
594 // CSEs we can find.
595 if (Uses[i].Base == Zero) return Result;
596 SubExpressionUseCounts[Uses[i].Base]++;
597 }
598
599 // Now that we know how many times each is used, build Result.
600 for (std::map<SCEVHandle, unsigned>::iterator I =
601 SubExpressionUseCounts.begin(), E = SubExpressionUseCounts.end();
602 I != E; )
603 if (I->second == NumUses) { // Found CSE!
604 Result = SCEVAddExpr::get(Result, I->first);
605 ++I;
606 } else {
607 // Remove non-cse's from SubExpressionUseCounts.
608 SubExpressionUseCounts.erase(I++);
609 }
610
611 // If we found no CSE's, return now.
612 if (Result == Zero) return Result;
613
614 // Otherwise, remove all of the CSE's we found from each of the base values.
615 for (unsigned i = 0; i != NumUses; ++i)
616 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Uses[i].Base)) {
617 std::vector<SCEVHandle> NewOps;
618
619 // Remove all of the values that are now in SubExpressionUseCounts.
620 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
621 if (!SubExpressionUseCounts.count(AE->getOperand(j)))
622 NewOps.push_back(AE->getOperand(j));
Chris Lattnerb965ee52005-08-09 01:13:47 +0000623 if (NewOps.size() == 0)
624 Uses[i].Base = Zero;
625 else
626 Uses[i].Base = SCEVAddExpr::get(NewOps);
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000627 } else {
628 // If the base is zero (which is common), return zero now, there are no
629 // CSEs we can find.
630 assert(Uses[i].Base == Result);
631 Uses[i].Base = Zero;
632 }
633
634 return Result;
635}
636
637
Nate Begeman16997482005-07-30 00:15:07 +0000638/// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
639/// stride of IV. All of the users may have different starting values, and this
640/// may not be the only stride (we know it is if isOnlyStride is true).
641void LoopStrengthReduce::StrengthReduceStridedIVUsers(Value *Stride,
Chris Lattnerec3fb632005-08-03 22:21:05 +0000642 IVUsersOfOneStride &Uses,
643 Loop *L,
Nate Begeman16997482005-07-30 00:15:07 +0000644 bool isOnlyStride) {
645 // Transform our list of users and offsets to a bit more complex table. In
Chris Lattnera553b0c2005-08-08 22:56:21 +0000646 // this new vector, each 'BasedUser' contains 'Base' the base of the
647 // strided accessas well as the old information from Uses. We progressively
648 // move information from the Base field to the Imm field, until we eventually
649 // have the full access expression to rewrite the use.
650 std::vector<BasedUser> UsersToProcess;
Nate Begeman16997482005-07-30 00:15:07 +0000651 UsersToProcess.reserve(Uses.Users.size());
Chris Lattnera553b0c2005-08-08 22:56:21 +0000652 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
653 UsersToProcess.push_back(Uses.Users[i]);
654
655 // Move any loop invariant operands from the offset field to the immediate
656 // field of the use, so that we don't try to use something before it is
657 // computed.
658 MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
659 UsersToProcess.back().Imm, L);
660 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
Chris Lattner26d91f12005-08-04 22:34:05 +0000661 "Base value is not loop invariant!");
Nate Begeman16997482005-07-30 00:15:07 +0000662 }
Chris Lattner44b807e2005-08-08 22:32:34 +0000663
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000664 // We now have a whole bunch of uses of like-strided induction variables, but
665 // they might all have different bases. We want to emit one PHI node for this
666 // stride which we fold as many common expressions (between the IVs) into as
667 // possible. Start by identifying the common expressions in the base values
668 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
669 // "A+B"), emit it to the preheader, then remove the expression from the
670 // UsersToProcess base values.
671 SCEVHandle CommonExprs = RemoveCommonExpressionsFromUseBases(UsersToProcess);
672
Chris Lattner44b807e2005-08-08 22:32:34 +0000673 // Next, figure out what we can represent in the immediate fields of
674 // instructions. If we can represent anything there, move it to the imm
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000675 // fields of the BasedUsers. We do this so that it increases the commonality
676 // of the remaining uses.
Chris Lattner44b807e2005-08-08 22:32:34 +0000677 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
678 // Addressing modes can be folded into loads and stores. Be careful that
679 // the store is through the expression, not of the expression though.
Chris Lattnera553b0c2005-08-08 22:56:21 +0000680 bool isAddress = isa<LoadInst>(UsersToProcess[i].Inst);
681 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
682 if (SI->getOperand(1) == UsersToProcess[i].OperandValToReplace)
Chris Lattner44b807e2005-08-08 22:32:34 +0000683 isAddress = true;
684
Chris Lattnera553b0c2005-08-08 22:56:21 +0000685 MoveImmediateValues(UsersToProcess[i].Base, UsersToProcess[i].Imm,
Chris Lattner44b807e2005-08-08 22:32:34 +0000686 isAddress, L);
687 }
688
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000689 // Now that we know what we need to do, insert the PHI node itself.
690 //
691 DEBUG(std::cerr << "INSERTING IV of STRIDE " << *Stride << " and BASE "
692 << *CommonExprs << " :\n");
693
694 SCEVExpander Rewriter(*SE, *LI);
695 SCEVExpander PreheaderRewriter(*SE, *LI);
Chris Lattner44b807e2005-08-08 22:32:34 +0000696
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000697 BasicBlock *Preheader = L->getLoopPreheader();
698 Instruction *PreInsertPt = Preheader->getTerminator();
699 Instruction *PhiInsertBefore = L->getHeader()->begin();
Chris Lattner44b807e2005-08-08 22:32:34 +0000700
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000701 assert(isa<PHINode>(PhiInsertBefore) &&
702 "How could this loop have IV's without any phis?");
703 PHINode *SomeLoopPHI = cast<PHINode>(PhiInsertBefore);
704 assert(SomeLoopPHI->getNumIncomingValues() == 2 &&
705 "This loop isn't canonicalized right");
706 BasicBlock *LatchBlock =
Chris Lattner87265ab2005-08-09 23:39:36 +0000707 SomeLoopPHI->getIncomingBlock(SomeLoopPHI->getIncomingBlock(0) == Preheader);
Chris Lattnerbe3e5212005-08-03 23:30:08 +0000708
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000709 // Create a new Phi for this base, and stick it in the loop header.
710 const Type *ReplacedTy = CommonExprs->getType();
711 PHINode *NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
712 ++NumInserted;
713
714 // Emit the initial base value into the loop preheader, and add it to the
715 // Phi node.
716 Value *PHIBaseV = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt,
717 ReplacedTy);
718 NewPHI->addIncoming(PHIBaseV, Preheader);
719
720 // Emit the increment of the base value before the terminator of the loop
721 // latch block, and add it to the Phi node.
722 SCEVHandle IncExp = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
723 SCEVUnknown::get(Stride));
724
725 Value *IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator(),
726 ReplacedTy);
727 IncV->setName(NewPHI->getName()+".inc");
728 NewPHI->addIncoming(IncV, LatchBlock);
729
Chris Lattner2351aba2005-08-03 22:51:21 +0000730 // Sort by the base value, so that all IVs with identical bases are next to
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000731 // each other.
Chris Lattner2351aba2005-08-03 22:51:21 +0000732 std::sort(UsersToProcess.begin(), UsersToProcess.end());
Nate Begeman16997482005-07-30 00:15:07 +0000733 while (!UsersToProcess.empty()) {
Chris Lattnera553b0c2005-08-08 22:56:21 +0000734 SCEVHandle Base = UsersToProcess.front().Base;
Chris Lattnerbe3e5212005-08-03 23:30:08 +0000735
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000736 DEBUG(std::cerr << " INSERTING code for BASE = " << *Base << ":\n");
Chris Lattnerbe3e5212005-08-03 23:30:08 +0000737
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000738 // Emit the code for Base into the preheader.
Chris Lattner5272f3c2005-08-08 05:47:49 +0000739 Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt,
740 ReplacedTy);
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000741
742 // If BaseV is a constant other than 0, make sure that it gets inserted into
743 // the preheader, instead of being forward substituted into the uses. We do
744 // this by forcing a noop cast to be inserted into the preheader in this
745 // case.
746 if (Constant *C = dyn_cast<Constant>(BaseV))
747 if (!C->isNullValue()) {
748 // We want this constant emitted into the preheader!
749 BaseV = new CastInst(BaseV, BaseV->getType(), "preheaderinsert",
750 PreInsertPt);
751 }
752
Nate Begeman16997482005-07-30 00:15:07 +0000753 // Emit the code to add the immediate offset to the Phi value, just before
Chris Lattner2351aba2005-08-03 22:51:21 +0000754 // the instructions that we identified as using this stride and base.
Chris Lattnera553b0c2005-08-08 22:56:21 +0000755 while (!UsersToProcess.empty() && UsersToProcess.front().Base == Base) {
756 BasedUser &User = UsersToProcess.front();
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000757
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000758 // If this instruction wants to use the post-incremented value, move it
759 // after the post-inc and use its value instead of the PHI.
760 Value *RewriteOp = NewPHI;
761 if (User.isUseOfPostIncrementedValue) {
762 RewriteOp = IncV;
763 User.Inst->moveBefore(LatchBlock->getTerminator());
764 }
765 SCEVHandle RewriteExpr = SCEVUnknown::get(RewriteOp);
766
Chris Lattner2351aba2005-08-03 22:51:21 +0000767 // Clear the SCEVExpander's expression map so that we are guaranteed
768 // to have the code emitted where we expect it.
769 Rewriter.clear();
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000770
Chris Lattner2114b272005-08-04 20:03:32 +0000771 // Now that we know what we need to do, insert code before User for the
772 // immediate and any loop-variant expressions.
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000773 if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isNullValue())
774 // Add BaseV to the PHI value if needed.
775 RewriteExpr = SCEVAddExpr::get(RewriteExpr, SCEVUnknown::get(BaseV));
776
777 User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter);
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000778
Chris Lattner2351aba2005-08-03 22:51:21 +0000779 // Mark old value we replaced as possibly dead, so that it is elminated
780 // if we just replaced the last use of that value.
Chris Lattner2114b272005-08-04 20:03:32 +0000781 DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
Nate Begeman16997482005-07-30 00:15:07 +0000782
Chris Lattner2351aba2005-08-03 22:51:21 +0000783 UsersToProcess.erase(UsersToProcess.begin());
784 ++NumReduced;
785 }
Nate Begeman16997482005-07-30 00:15:07 +0000786 // TODO: Next, find out which base index is the most common, pull it out.
787 }
788
789 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
790 // different starting values, into different PHIs.
Nate Begeman16997482005-07-30 00:15:07 +0000791}
792
Chris Lattner010de252005-08-08 05:28:22 +0000793// OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
794// uses in the loop, look to see if we can eliminate some, in favor of using
795// common indvars for the different uses.
796void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
797 // TODO: implement optzns here.
798
799
800
801
802 // Finally, get the terminating condition for the loop if possible. If we
803 // can, we want to change it to use a post-incremented version of its
804 // induction variable, to allow coallescing the live ranges for the IV into
805 // one register value.
806 PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
807 BasicBlock *Preheader = L->getLoopPreheader();
808 BasicBlock *LatchBlock =
809 SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
810 BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
811 if (!TermBr || TermBr->isUnconditional() ||
812 !isa<SetCondInst>(TermBr->getCondition()))
813 return;
814 SetCondInst *Cond = cast<SetCondInst>(TermBr->getCondition());
815
816 // Search IVUsesByStride to find Cond's IVUse if there is one.
817 IVStrideUse *CondUse = 0;
818 Value *CondStride = 0;
819
820 for (std::map<Value*, IVUsersOfOneStride>::iterator I =IVUsesByStride.begin(),
821 E = IVUsesByStride.end(); I != E && !CondUse; ++I)
822 for (std::vector<IVStrideUse>::iterator UI = I->second.Users.begin(),
823 E = I->second.Users.end(); UI != E; ++UI)
824 if (UI->User == Cond) {
825 CondUse = &*UI;
826 CondStride = I->first;
827 // NOTE: we could handle setcc instructions with multiple uses here, but
828 // InstCombine does it as well for simple uses, it's not clear that it
829 // occurs enough in real life to handle.
830 break;
831 }
832 if (!CondUse) return; // setcc doesn't use the IV.
833
834 // setcc stride is complex, don't mess with users.
835 if (!isa<ConstantInt>(CondStride)) return;
836
837 // It's possible for the setcc instruction to be anywhere in the loop, and
838 // possible for it to have multiple users. If it is not immediately before
839 // the latch block branch, move it.
840 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
841 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
842 Cond->moveBefore(TermBr);
843 } else {
844 // Otherwise, clone the terminating condition and insert into the loopend.
845 Cond = cast<SetCondInst>(Cond->clone());
846 Cond->setName(L->getHeader()->getName() + ".termcond");
847 LatchBlock->getInstList().insert(TermBr, Cond);
848
849 // Clone the IVUse, as the old use still exists!
850 IVUsesByStride[CondStride].addUser(CondUse->Offset, Cond,
851 CondUse->OperandValToReplace);
852 CondUse = &IVUsesByStride[CondStride].Users.back();
853 }
854 }
855
856 // If we get to here, we know that we can transform the setcc instruction to
857 // use the post-incremented version of the IV, allowing us to coallesce the
858 // live ranges for the IV correctly.
859 CondUse->Offset = SCEV::getMinusSCEV(CondUse->Offset,
860 SCEVUnknown::get(CondStride));
861 CondUse->isUseOfPostIncrementedValue = true;
862}
Nate Begeman16997482005-07-30 00:15:07 +0000863
Nate Begemaneaa13852004-10-18 21:08:22 +0000864void LoopStrengthReduce::runOnLoop(Loop *L) {
865 // First step, transform all loops nesting inside of this loop.
866 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
867 runOnLoop(*I);
868
Nate Begeman16997482005-07-30 00:15:07 +0000869 // Next, find all uses of induction variables in this loop, and catagorize
870 // them by stride. Start by finding all of the PHI nodes in the header for
871 // this loop. If they are induction variables, inspect their uses.
Chris Lattner3416e5f2005-08-04 17:40:30 +0000872 std::set<Instruction*> Processed; // Don't reprocess instructions.
Nate Begeman16997482005-07-30 00:15:07 +0000873 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
Chris Lattner3416e5f2005-08-04 17:40:30 +0000874 AddUsersIfInteresting(I, L, Processed);
Nate Begemaneaa13852004-10-18 21:08:22 +0000875
Nate Begeman16997482005-07-30 00:15:07 +0000876 // If we have nothing to do, return.
Chris Lattner010de252005-08-08 05:28:22 +0000877 if (IVUsesByStride.empty()) return;
878
879 // Optimize induction variables. Some indvar uses can be transformed to use
880 // strides that will be needed for other purposes. A common example of this
881 // is the exit test for the loop, which can often be rewritten to use the
882 // computation of some other indvar to decide when to terminate the loop.
883 OptimizeIndvars(L);
884
Misha Brukmanfd939082005-04-21 23:48:37 +0000885
Nate Begeman16997482005-07-30 00:15:07 +0000886 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
887 // doing computation in byte values, promote to 32-bit values if safe.
888
889 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
890 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
891 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
892 // to be careful that IV's are all the same type. Only works for intptr_t
893 // indvars.
894
895 // If we only have one stride, we can more aggressively eliminate some things.
896 bool HasOneStride = IVUsesByStride.size() == 1;
897
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000898 // Note: this processes each stride/type pair individually. All users passed
899 // into StrengthReduceStridedIVUsers have the same type AND stride.
Chris Lattnerec3fb632005-08-03 22:21:05 +0000900 for (std::map<Value*, IVUsersOfOneStride>::iterator SI
901 = IVUsesByStride.begin(), E = IVUsesByStride.end(); SI != E; ++SI)
Nate Begeman16997482005-07-30 00:15:07 +0000902 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
Nate Begemaneaa13852004-10-18 21:08:22 +0000903
904 // Clean up after ourselves
905 if (!DeadInsts.empty()) {
906 DeleteTriviallyDeadInstructions(DeadInsts);
907
Nate Begeman16997482005-07-30 00:15:07 +0000908 BasicBlock::iterator I = L->getHeader()->begin();
909 PHINode *PN;
Chris Lattnere9100c62005-08-02 02:44:31 +0000910 while ((PN = dyn_cast<PHINode>(I))) {
Chris Lattner1060e092005-08-02 00:41:11 +0000911 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
912
Chris Lattner87265ab2005-08-09 23:39:36 +0000913 // At this point, we know that we have killed one or more GEP
914 // instructions. It is worth checking to see if the cann indvar is also
915 // dead, so that we can remove it as well. The requirements for the cann
916 // indvar to be considered dead are:
Nate Begeman16997482005-07-30 00:15:07 +0000917 // 1. the cann indvar has one use
918 // 2. the use is an add instruction
919 // 3. the add has one use
920 // 4. the add is used by the cann indvar
921 // If all four cases above are true, then we can remove both the add and
922 // the cann indvar.
923 // FIXME: this needs to eliminate an induction variable even if it's being
924 // compared against some value to decide loop termination.
925 if (PN->hasOneUse()) {
926 BinaryOperator *BO = dyn_cast<BinaryOperator>(*(PN->use_begin()));
Chris Lattner7e608bb2005-08-02 02:52:02 +0000927 if (BO && BO->hasOneUse()) {
928 if (PN == *(BO->use_begin())) {
929 DeadInsts.insert(BO);
930 // Break the cycle, then delete the PHI.
931 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattner52d83e62005-08-03 21:36:09 +0000932 SE->deleteInstructionFromRecords(PN);
Chris Lattner7e608bb2005-08-02 02:52:02 +0000933 PN->eraseFromParent();
Nate Begemaneaa13852004-10-18 21:08:22 +0000934 }
Chris Lattner7e608bb2005-08-02 02:52:02 +0000935 }
Nate Begeman16997482005-07-30 00:15:07 +0000936 }
Nate Begemaneaa13852004-10-18 21:08:22 +0000937 }
Nate Begeman16997482005-07-30 00:15:07 +0000938 DeleteTriviallyDeadInstructions(DeadInsts);
Nate Begemaneaa13852004-10-18 21:08:22 +0000939 }
Nate Begeman16997482005-07-30 00:15:07 +0000940
Chris Lattner9a59fbb2005-08-05 01:30:11 +0000941 CastedPointers.clear();
Nate Begeman16997482005-07-30 00:15:07 +0000942 IVUsesByStride.clear();
943 return;
Nate Begemaneaa13852004-10-18 21:08:22 +0000944}