blob: f8b208e47517960a8360d6493dffc37a8ced05cd [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"
Chris Lattnere0391be2005-08-12 22:06:11 +000029#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Nate Begemaneaa13852004-10-18 21:08:22 +000030#include "llvm/Transforms/Utils/Local.h"
Jeff Cohen2f3c9b72005-03-04 04:04:26 +000031#include "llvm/Target/TargetData.h"
Nate Begemaneaa13852004-10-18 21:08:22 +000032#include "llvm/ADT/Statistic.h"
Nate Begeman16997482005-07-30 00:15:07 +000033#include "llvm/Support/Debug.h"
Jeff Cohencfb1d422005-07-30 18:22:27 +000034#include <algorithm>
Nate Begemaneaa13852004-10-18 21:08:22 +000035#include <set>
36using namespace llvm;
37
38namespace {
39 Statistic<> NumReduced ("loop-reduce", "Number of GEPs strength reduced");
Chris Lattner26d91f12005-08-04 22:34:05 +000040 Statistic<> NumInserted("loop-reduce", "Number of PHIs inserted");
Chris Lattner50fad702005-08-10 00:45:21 +000041 Statistic<> NumVariable("loop-reduce","Number of PHIs with variable strides");
Nate Begemaneaa13852004-10-18 21:08:22 +000042
Chris Lattnerec3fb632005-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 Lattner010de252005-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 Lattnerec3fb632005-08-03 22:21:05 +000057
58 IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
Chris Lattner010de252005-08-08 05:28:22 +000059 : Offset(Offs), User(U), OperandValToReplace(O),
60 isUseOfPostIncrementedValue(false) {}
Chris Lattnerec3fb632005-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 Begeman16997482005-07-30 00:15:07 +000068 /// Users - Keep track of all of the users of this stride as well as the
Chris Lattnerec3fb632005-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 Begeman16997482005-07-30 00:15:07 +000074 }
75 };
76
77
Nate Begemaneaa13852004-10-18 21:08:22 +000078 class LoopStrengthReduce : public FunctionPass {
79 LoopInfo *LI;
80 DominatorSet *DS;
Nate Begeman16997482005-07-30 00:15:07 +000081 ScalarEvolution *SE;
82 const TargetData *TD;
83 const Type *UIntPtrTy;
Nate Begemaneaa13852004-10-18 21:08:22 +000084 bool Changed;
Chris Lattner7e608bb2005-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 Cohen2f3c9b72005-03-04 04:04:26 +000088 unsigned MaxTargetAMSize;
Nate Begeman16997482005-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 Lattner50fad702005-08-10 00:45:21 +000092 std::map<SCEVHandle, IVUsersOfOneStride> IVUsesByStride;
Nate Begeman16997482005-07-30 00:15:07 +000093
Chris Lattner49f72e62005-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 Begeman16997482005-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 Begemaneaa13852004-10-18 21:08:22 +0000102 public:
Jeff Cohen2f3c9b72005-03-04 04:04:26 +0000103 LoopStrengthReduce(unsigned MTAMS = 1)
104 : MaxTargetAMSize(MTAMS) {
105 }
106
Nate Begemaneaa13852004-10-18 21:08:22 +0000107 virtual bool runOnFunction(Function &) {
108 LI = &getAnalysis<LoopInfo>();
109 DS = &getAnalysis<DominatorSet>();
Nate Begeman16997482005-07-30 00:15:07 +0000110 SE = &getAnalysis<ScalarEvolution>();
111 TD = &getAnalysis<TargetData>();
112 UIntPtrTy = TD->getIntPtrType();
Nate Begemaneaa13852004-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 Lattner49f72e62005-08-04 01:19:13 +0000117
Nate Begemaneaa13852004-10-18 21:08:22 +0000118 return Changed;
119 }
120
121 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattneraa96ae72005-08-17 06:35:16 +0000122 // We split critical edges, so we change the CFG. However, we do update
123 // many analyses if they are around.
124 AU.addPreservedID(LoopSimplifyID);
125 AU.addPreserved<LoopInfo>();
126 AU.addPreserved<DominatorSet>();
127 AU.addPreserved<ImmediateDominators>();
128 AU.addPreserved<DominanceFrontier>();
129 AU.addPreserved<DominatorTree>();
130
Jeff Cohenf465db62005-02-27 19:37:07 +0000131 AU.addRequiredID(LoopSimplifyID);
Nate Begemaneaa13852004-10-18 21:08:22 +0000132 AU.addRequired<LoopInfo>();
133 AU.addRequired<DominatorSet>();
Jeff Cohen2f3c9b72005-03-04 04:04:26 +0000134 AU.addRequired<TargetData>();
Nate Begeman16997482005-07-30 00:15:07 +0000135 AU.addRequired<ScalarEvolution>();
Nate Begemaneaa13852004-10-18 21:08:22 +0000136 }
Chris Lattner49f72e62005-08-04 01:19:13 +0000137
138 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
139 ///
140 Value *getCastedVersionOf(Value *V);
141private:
Nate Begemaneaa13852004-10-18 21:08:22 +0000142 void runOnLoop(Loop *L);
Chris Lattner3416e5f2005-08-04 17:40:30 +0000143 bool AddUsersIfInteresting(Instruction *I, Loop *L,
144 std::set<Instruction*> &Processed);
145 SCEVHandle GetExpressionSCEV(Instruction *E, Loop *L);
146
Chris Lattner010de252005-08-08 05:28:22 +0000147 void OptimizeIndvars(Loop *L);
Nate Begeman16997482005-07-30 00:15:07 +0000148
Chris Lattner50fad702005-08-10 00:45:21 +0000149 void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
150 IVUsersOfOneStride &Uses,
Chris Lattnerec3fb632005-08-03 22:21:05 +0000151 Loop *L, bool isOnlyStride);
Nate Begemaneaa13852004-10-18 21:08:22 +0000152 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
153 };
Misha Brukmanfd939082005-04-21 23:48:37 +0000154 RegisterOpt<LoopStrengthReduce> X("loop-reduce",
Nate Begemaneaa13852004-10-18 21:08:22 +0000155 "Strength Reduce GEP Uses of Ind. Vars");
156}
157
Jeff Cohen2f3c9b72005-03-04 04:04:26 +0000158FunctionPass *llvm::createLoopStrengthReducePass(unsigned MaxTargetAMSize) {
159 return new LoopStrengthReduce(MaxTargetAMSize);
Nate Begemaneaa13852004-10-18 21:08:22 +0000160}
161
Chris Lattner49f72e62005-08-04 01:19:13 +0000162/// getCastedVersionOf - Return the specified value casted to uintptr_t.
163///
164Value *LoopStrengthReduce::getCastedVersionOf(Value *V) {
165 if (V->getType() == UIntPtrTy) return V;
166 if (Constant *CB = dyn_cast<Constant>(V))
167 return ConstantExpr::getCast(CB, UIntPtrTy);
168
169 Value *&New = CastedPointers[V];
170 if (New) return New;
171
172 BasicBlock::iterator InsertPt;
173 if (Argument *Arg = dyn_cast<Argument>(V)) {
174 // Insert into the entry of the function, after any allocas.
175 InsertPt = Arg->getParent()->begin()->begin();
176 while (isa<AllocaInst>(InsertPt)) ++InsertPt;
177 } else {
178 if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
179 InsertPt = II->getNormalDest()->begin();
180 } else {
181 InsertPt = cast<Instruction>(V);
182 ++InsertPt;
183 }
184
185 // Do not insert casts into the middle of PHI node blocks.
186 while (isa<PHINode>(InsertPt)) ++InsertPt;
187 }
Chris Lattner7db543f2005-08-04 19:08:16 +0000188
189 New = new CastInst(V, UIntPtrTy, V->getName(), InsertPt);
190 DeadInsts.insert(cast<Instruction>(New));
191 return New;
Chris Lattner49f72e62005-08-04 01:19:13 +0000192}
193
194
Nate Begemaneaa13852004-10-18 21:08:22 +0000195/// DeleteTriviallyDeadInstructions - If any of the instructions is the
196/// specified set are trivially dead, delete them and see if this makes any of
197/// their operands subsequently dead.
198void LoopStrengthReduce::
199DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
200 while (!Insts.empty()) {
201 Instruction *I = *Insts.begin();
202 Insts.erase(Insts.begin());
203 if (isInstructionTriviallyDead(I)) {
Jeff Cohen0456e4a2005-03-01 03:46:11 +0000204 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
205 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
206 Insts.insert(U);
Chris Lattner52d83e62005-08-03 21:36:09 +0000207 SE->deleteInstructionFromRecords(I);
208 I->eraseFromParent();
Nate Begemaneaa13852004-10-18 21:08:22 +0000209 Changed = true;
210 }
211 }
212}
213
Jeff Cohenf465db62005-02-27 19:37:07 +0000214
Chris Lattner3416e5f2005-08-04 17:40:30 +0000215/// GetExpressionSCEV - Compute and return the SCEV for the specified
216/// instruction.
217SCEVHandle LoopStrengthReduce::GetExpressionSCEV(Instruction *Exp, Loop *L) {
Chris Lattner87265ab2005-08-09 23:39:36 +0000218 // Scalar Evolutions doesn't know how to compute SCEV's for GEP instructions.
219 // If this is a GEP that SE doesn't know about, compute it now and insert it.
220 // If this is not a GEP, or if we have already done this computation, just let
221 // SE figure it out.
Chris Lattner3416e5f2005-08-04 17:40:30 +0000222 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
Chris Lattner87265ab2005-08-09 23:39:36 +0000223 if (!GEP || SE->hasSCEV(GEP))
Chris Lattner3416e5f2005-08-04 17:40:30 +0000224 return SE->getSCEV(Exp);
225
Nate Begeman16997482005-07-30 00:15:07 +0000226 // Analyze all of the subscripts of this getelementptr instruction, looking
227 // for uses that are determined by the trip count of L. First, skip all
228 // operands the are not dependent on the IV.
229
230 // Build up the base expression. Insert an LLVM cast of the pointer to
231 // uintptr_t first.
Chris Lattner3416e5f2005-08-04 17:40:30 +0000232 SCEVHandle GEPVal = SCEVUnknown::get(getCastedVersionOf(GEP->getOperand(0)));
Nate Begeman16997482005-07-30 00:15:07 +0000233
234 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattner3416e5f2005-08-04 17:40:30 +0000235
236 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
Nate Begeman16997482005-07-30 00:15:07 +0000237 // If this is a use of a recurrence that we can analyze, and it comes before
238 // Op does in the GEP operand list, we will handle this when we process this
239 // operand.
240 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
241 const StructLayout *SL = TD->getStructLayout(STy);
242 unsigned Idx = cast<ConstantUInt>(GEP->getOperand(i))->getValue();
243 uint64_t Offset = SL->MemberOffsets[Idx];
Chris Lattner3416e5f2005-08-04 17:40:30 +0000244 GEPVal = SCEVAddExpr::get(GEPVal,
245 SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy));
Nate Begeman16997482005-07-30 00:15:07 +0000246 } else {
Chris Lattner7db543f2005-08-04 19:08:16 +0000247 Value *OpVal = getCastedVersionOf(GEP->getOperand(i));
248 SCEVHandle Idx = SE->getSCEV(OpVal);
249
Chris Lattner3416e5f2005-08-04 17:40:30 +0000250 uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
251 if (TypeSize != 1)
252 Idx = SCEVMulExpr::get(Idx,
253 SCEVConstant::get(ConstantUInt::get(UIntPtrTy,
254 TypeSize)));
255 GEPVal = SCEVAddExpr::get(GEPVal, Idx);
Nate Begeman16997482005-07-30 00:15:07 +0000256 }
257 }
258
Chris Lattner87265ab2005-08-09 23:39:36 +0000259 SE->setSCEV(GEP, GEPVal);
Chris Lattner3416e5f2005-08-04 17:40:30 +0000260 return GEPVal;
Nate Begeman16997482005-07-30 00:15:07 +0000261}
262
Chris Lattner7db543f2005-08-04 19:08:16 +0000263/// getSCEVStartAndStride - Compute the start and stride of this expression,
264/// returning false if the expression is not a start/stride pair, or true if it
265/// is. The stride must be a loop invariant expression, but the start may be
266/// a mix of loop invariant and loop variant expressions.
267static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
Chris Lattner50fad702005-08-10 00:45:21 +0000268 SCEVHandle &Start, SCEVHandle &Stride) {
Chris Lattner7db543f2005-08-04 19:08:16 +0000269 SCEVHandle TheAddRec = Start; // Initialize to zero.
270
271 // If the outer level is an AddExpr, the operands are all start values except
272 // for a nested AddRecExpr.
273 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
274 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
275 if (SCEVAddRecExpr *AddRec =
276 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
277 if (AddRec->getLoop() == L)
278 TheAddRec = SCEVAddExpr::get(AddRec, TheAddRec);
279 else
280 return false; // Nested IV of some sort?
281 } else {
282 Start = SCEVAddExpr::get(Start, AE->getOperand(i));
283 }
284
285 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SH)) {
286 TheAddRec = SH;
287 } else {
288 return false; // not analyzable.
289 }
290
291 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
292 if (!AddRec || AddRec->getLoop() != L) return false;
293
294 // FIXME: Generalize to non-affine IV's.
295 if (!AddRec->isAffine()) return false;
296
297 Start = SCEVAddExpr::get(Start, AddRec->getOperand(0));
298
Chris Lattner7db543f2005-08-04 19:08:16 +0000299 if (!isa<SCEVConstant>(AddRec->getOperand(1)))
Chris Lattner50fad702005-08-10 00:45:21 +0000300 DEBUG(std::cerr << "[" << L->getHeader()->getName()
301 << "] Variable stride: " << *AddRec << "\n");
Chris Lattner7db543f2005-08-04 19:08:16 +0000302
Chris Lattner50fad702005-08-10 00:45:21 +0000303 Stride = AddRec->getOperand(1);
304 // Check that all constant strides are the unsigned type, we don't want to
305 // have two IV's one of signed stride 4 and one of unsigned stride 4 to not be
306 // merged.
307 assert((!isa<SCEVConstant>(Stride) || Stride->getType()->isUnsigned()) &&
Chris Lattner7db543f2005-08-04 19:08:16 +0000308 "Constants should be canonicalized to unsigned!");
Chris Lattner50fad702005-08-10 00:45:21 +0000309
Chris Lattner7db543f2005-08-04 19:08:16 +0000310 return true;
311}
312
Nate Begeman16997482005-07-30 00:15:07 +0000313/// AddUsersIfInteresting - Inspect the specified instruction. If it is a
314/// reducible SCEV, recursively add its users to the IVUsesByStride set and
315/// return true. Otherwise, return false.
Chris Lattner3416e5f2005-08-04 17:40:30 +0000316bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
317 std::set<Instruction*> &Processed) {
Nate Begemanf84d5ab2005-07-30 00:21:31 +0000318 if (I->getType() == Type::VoidTy) return false;
Chris Lattner3416e5f2005-08-04 17:40:30 +0000319 if (!Processed.insert(I).second)
320 return true; // Instruction already handled.
321
Chris Lattner7db543f2005-08-04 19:08:16 +0000322 // Get the symbolic expression for this instruction.
Chris Lattner3416e5f2005-08-04 17:40:30 +0000323 SCEVHandle ISE = GetExpressionSCEV(I, L);
Chris Lattner7db543f2005-08-04 19:08:16 +0000324 if (isa<SCEVCouldNotCompute>(ISE)) return false;
Chris Lattner3416e5f2005-08-04 17:40:30 +0000325
Chris Lattner7db543f2005-08-04 19:08:16 +0000326 // Get the start and stride for this expression.
327 SCEVHandle Start = SCEVUnknown::getIntegerSCEV(0, ISE->getType());
Chris Lattner50fad702005-08-10 00:45:21 +0000328 SCEVHandle Stride = Start;
Chris Lattner7db543f2005-08-04 19:08:16 +0000329 if (!getSCEVStartAndStride(ISE, L, Start, Stride))
330 return false; // Non-reducible symbolic expression, bail out.
331
Nate Begeman16997482005-07-30 00:15:07 +0000332 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){
333 Instruction *User = cast<Instruction>(*UI);
334
335 // Do not infinitely recurse on PHI nodes.
336 if (isa<PHINode>(User) && User->getParent() == L->getHeader())
337 continue;
338
339 // If this is an instruction defined in a nested loop, or outside this loop,
Chris Lattnerf9186592005-08-04 00:14:11 +0000340 // don't recurse into it.
Chris Lattner7db543f2005-08-04 19:08:16 +0000341 bool AddUserToIVUsers = false;
Chris Lattnerf9186592005-08-04 00:14:11 +0000342 if (LI->getLoopFor(User->getParent()) != L) {
343 DEBUG(std::cerr << "FOUND USER in nested loop: " << *User
344 << " OF SCEV: " << *ISE << "\n");
Chris Lattner7db543f2005-08-04 19:08:16 +0000345 AddUserToIVUsers = true;
Chris Lattner3416e5f2005-08-04 17:40:30 +0000346 } else if (!AddUsersIfInteresting(User, L, Processed)) {
Chris Lattnera4479ad2005-08-04 00:40:47 +0000347 DEBUG(std::cerr << "FOUND USER: " << *User
348 << " OF SCEV: " << *ISE << "\n");
Chris Lattner7db543f2005-08-04 19:08:16 +0000349 AddUserToIVUsers = true;
350 }
Nate Begeman16997482005-07-30 00:15:07 +0000351
Chris Lattner7db543f2005-08-04 19:08:16 +0000352 if (AddUserToIVUsers) {
Chris Lattnera4479ad2005-08-04 00:40:47 +0000353 // Okay, we found a user that we cannot reduce. Analyze the instruction
354 // and decide what to do with it.
Chris Lattner7db543f2005-08-04 19:08:16 +0000355 IVUsesByStride[Stride].addUser(Start, User, I);
Nate Begeman16997482005-07-30 00:15:07 +0000356 }
357 }
358 return true;
359}
360
361namespace {
362 /// BasedUser - For a particular base value, keep information about how we've
363 /// partitioned the expression so far.
364 struct BasedUser {
Chris Lattnera553b0c2005-08-08 22:56:21 +0000365 /// Base - The Base value for the PHI node that needs to be inserted for
366 /// this use. As the use is processed, information gets moved from this
367 /// field to the Imm field (below). BasedUser values are sorted by this
368 /// field.
369 SCEVHandle Base;
370
Nate Begeman16997482005-07-30 00:15:07 +0000371 /// Inst - The instruction using the induction variable.
372 Instruction *Inst;
373
Chris Lattnerec3fb632005-08-03 22:21:05 +0000374 /// OperandValToReplace - The operand value of Inst to replace with the
375 /// EmittedBase.
376 Value *OperandValToReplace;
Nate Begeman16997482005-07-30 00:15:07 +0000377
378 /// Imm - The immediate value that should be added to the base immediately
379 /// before Inst, because it will be folded into the imm field of the
380 /// instruction.
381 SCEVHandle Imm;
382
383 /// EmittedBase - The actual value* to use for the base value of this
384 /// operation. This is null if we should just use zero so far.
385 Value *EmittedBase;
386
Chris Lattner010de252005-08-08 05:28:22 +0000387 // isUseOfPostIncrementedValue - True if this should use the
388 // post-incremented version of this IV, not the preincremented version.
389 // This can only be set in special cases, such as the terminating setcc
390 // instruction for a loop.
391 bool isUseOfPostIncrementedValue;
Chris Lattnera553b0c2005-08-08 22:56:21 +0000392
393 BasedUser(IVStrideUse &IVSU)
394 : Base(IVSU.Offset), Inst(IVSU.User),
395 OperandValToReplace(IVSU.OperandValToReplace),
396 Imm(SCEVUnknown::getIntegerSCEV(0, Base->getType())), EmittedBase(0),
397 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
Nate Begeman16997482005-07-30 00:15:07 +0000398
Chris Lattner2114b272005-08-04 20:03:32 +0000399 // Once we rewrite the code to insert the new IVs we want, update the
400 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
401 // to it.
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000402 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattnerc60fb082005-08-12 22:22:17 +0000403 SCEVExpander &Rewriter, Loop *L,
404 Pass *P);
Nate Begeman16997482005-07-30 00:15:07 +0000405
Chris Lattnera553b0c2005-08-08 22:56:21 +0000406 // Sort by the Base field.
407 bool operator<(const BasedUser &BU) const { return Base < BU.Base; }
Nate Begeman16997482005-07-30 00:15:07 +0000408
409 void dump() const;
410 };
411}
412
413void BasedUser::dump() const {
Chris Lattnera553b0c2005-08-08 22:56:21 +0000414 std::cerr << " Base=" << *Base;
Nate Begeman16997482005-07-30 00:15:07 +0000415 std::cerr << " Imm=" << *Imm;
416 if (EmittedBase)
417 std::cerr << " EB=" << *EmittedBase;
418
419 std::cerr << " Inst: " << *Inst;
420}
421
Chris Lattner2114b272005-08-04 20:03:32 +0000422// Once we rewrite the code to insert the new IVs we want, update the
423// operands of Inst to use the new expression 'NewBase', with 'Imm' added
424// to it.
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000425void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattnere0391be2005-08-12 22:06:11 +0000426 SCEVExpander &Rewriter,
Chris Lattnerc60fb082005-08-12 22:22:17 +0000427 Loop *L, Pass *P) {
Chris Lattner2114b272005-08-04 20:03:32 +0000428 if (!isa<PHINode>(Inst)) {
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000429 SCEVHandle NewValSCEV = SCEVAddExpr::get(NewBase, Imm);
Chris Lattner2114b272005-08-04 20:03:32 +0000430 Value *NewVal = Rewriter.expandCodeFor(NewValSCEV, Inst,
431 OperandValToReplace->getType());
Chris Lattner2114b272005-08-04 20:03:32 +0000432 // Replace the use of the operand Value with the new Phi we just created.
433 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
434 DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst);
435 return;
436 }
437
438 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
Chris Lattnerc41e3452005-08-10 00:35:32 +0000439 // expression into each operand block that uses it. Note that PHI nodes can
440 // have multiple entries for the same predecessor. We use a map to make sure
441 // that a PHI node only has a single Value* for each predecessor (which also
442 // prevents us from inserting duplicate code in some blocks).
443 std::map<BasicBlock*, Value*> InsertedCode;
Chris Lattner2114b272005-08-04 20:03:32 +0000444 PHINode *PN = cast<PHINode>(Inst);
445 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
446 if (PN->getIncomingValue(i) == OperandValToReplace) {
Chris Lattnere0391be2005-08-12 22:06:11 +0000447 // If this is a critical edge, split the edge so that we do not insert the
448 // code on all predecessor/successor paths.
449 if (e != 1 &&
450 PN->getIncomingBlock(i)->getTerminator()->getNumSuccessors() > 1) {
Chris Lattneraa96ae72005-08-17 06:35:16 +0000451
452 // First step, split the critical edge.
453 SplitCriticalEdge(PN->getIncomingBlock(i), PN->getParent(), P);
Chris Lattnerc60fb082005-08-12 22:22:17 +0000454
Chris Lattneraa96ae72005-08-17 06:35:16 +0000455 // Next step: move the basic block. In particular, if the PHI node
456 // is outside of the loop, and PredTI is in the loop, we want to
457 // move the block to be immediately before the PHI block, not
458 // immediately after PredTI.
459 if (L->contains(PN->getIncomingBlock(i)) &&
460 !L->contains(PN->getParent())) {
461 BasicBlock *NewBB = PN->getIncomingBlock(i);
462 NewBB->moveBefore(PN->getParent());
Chris Lattnere0391be2005-08-12 22:06:11 +0000463 }
Chris Lattneraa96ae72005-08-17 06:35:16 +0000464 break;
Chris Lattnere0391be2005-08-12 22:06:11 +0000465 }
Chris Lattner2114b272005-08-04 20:03:32 +0000466
Chris Lattnerc41e3452005-08-10 00:35:32 +0000467 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
468 if (!Code) {
469 // Insert the code into the end of the predecessor block.
470 BasicBlock::iterator InsertPt =PN->getIncomingBlock(i)->getTerminator();
Chris Lattner2114b272005-08-04 20:03:32 +0000471
Chris Lattnerc41e3452005-08-10 00:35:32 +0000472 SCEVHandle NewValSCEV = SCEVAddExpr::get(NewBase, Imm);
473 Code = Rewriter.expandCodeFor(NewValSCEV, InsertPt,
474 OperandValToReplace->getType());
475 }
Chris Lattner2114b272005-08-04 20:03:32 +0000476
477 // Replace the use of the operand Value with the new Phi we just created.
Chris Lattnerc41e3452005-08-10 00:35:32 +0000478 PN->setIncomingValue(i, Code);
Chris Lattner2114b272005-08-04 20:03:32 +0000479 Rewriter.clear();
480 }
481 }
482 DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst);
483}
484
485
Nate Begeman16997482005-07-30 00:15:07 +0000486/// isTargetConstant - Return true if the following can be referenced by the
487/// immediate field of a target instruction.
488static bool isTargetConstant(const SCEVHandle &V) {
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000489
Nate Begeman16997482005-07-30 00:15:07 +0000490 // FIXME: Look at the target to decide if &GV is a legal constant immediate.
Chris Lattner3821e472005-08-08 06:25:50 +0000491 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
492 // PPC allows a sign-extended 16-bit immediate field.
493 if ((int64_t)SC->getValue()->getRawValue() > -(1 << 16) &&
494 (int64_t)SC->getValue()->getRawValue() < (1 << 16)-1)
495 return true;
496 return false;
497 }
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000498
Nate Begeman16997482005-07-30 00:15:07 +0000499 return false; // ENABLE this for x86
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000500
Nate Begeman16997482005-07-30 00:15:07 +0000501 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
502 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
503 if (CE->getOpcode() == Instruction::Cast)
504 if (isa<GlobalValue>(CE->getOperand(0)))
505 // FIXME: should check to see that the dest is uintptr_t!
506 return true;
507 return false;
508}
509
Chris Lattner44b807e2005-08-08 22:32:34 +0000510/// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
511/// loop varying to the Imm operand.
512static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
513 Loop *L) {
514 if (Val->isLoopInvariant(L)) return; // Nothing to do.
515
516 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
517 std::vector<SCEVHandle> NewOps;
518 NewOps.reserve(SAE->getNumOperands());
519
520 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
521 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
522 // If this is a loop-variant expression, it must stay in the immediate
523 // field of the expression.
524 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
525 } else {
526 NewOps.push_back(SAE->getOperand(i));
527 }
528
529 if (NewOps.empty())
530 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
531 else
532 Val = SCEVAddExpr::get(NewOps);
533 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
534 // Try to pull immediates out of the start value of nested addrec's.
535 SCEVHandle Start = SARE->getStart();
536 MoveLoopVariantsToImediateField(Start, Imm, L);
537
538 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
539 Ops[0] = Start;
540 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
541 } else {
542 // Otherwise, all of Val is variant, move the whole thing over.
543 Imm = SCEVAddExpr::get(Imm, Val);
544 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
545 }
546}
547
548
Chris Lattner26d91f12005-08-04 22:34:05 +0000549/// MoveImmediateValues - Look at Val, and pull out any additions of constants
Nate Begeman16997482005-07-30 00:15:07 +0000550/// that can fit into the immediate field of instructions in the target.
Chris Lattner26d91f12005-08-04 22:34:05 +0000551/// Accumulate these immediate values into the Imm value.
552static void MoveImmediateValues(SCEVHandle &Val, SCEVHandle &Imm,
553 bool isAddress, Loop *L) {
Chris Lattner7a658392005-08-03 23:44:42 +0000554 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
Chris Lattner26d91f12005-08-04 22:34:05 +0000555 std::vector<SCEVHandle> NewOps;
556 NewOps.reserve(SAE->getNumOperands());
557
558 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
Chris Lattner7db543f2005-08-04 19:08:16 +0000559 if (isAddress && isTargetConstant(SAE->getOperand(i))) {
560 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
561 } else if (!SAE->getOperand(i)->isLoopInvariant(L)) {
562 // If this is a loop-variant expression, it must stay in the immediate
563 // field of the expression.
564 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
Chris Lattner26d91f12005-08-04 22:34:05 +0000565 } else {
566 NewOps.push_back(SAE->getOperand(i));
Nate Begeman16997482005-07-30 00:15:07 +0000567 }
Chris Lattner26d91f12005-08-04 22:34:05 +0000568
569 if (NewOps.empty())
570 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
571 else
572 Val = SCEVAddExpr::get(NewOps);
573 return;
Chris Lattner7a658392005-08-03 23:44:42 +0000574 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
575 // Try to pull immediates out of the start value of nested addrec's.
Chris Lattner26d91f12005-08-04 22:34:05 +0000576 SCEVHandle Start = SARE->getStart();
577 MoveImmediateValues(Start, Imm, isAddress, L);
578
579 if (Start != SARE->getStart()) {
580 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
581 Ops[0] = Start;
582 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
583 }
584 return;
Nate Begeman16997482005-07-30 00:15:07 +0000585 }
586
Chris Lattner26d91f12005-08-04 22:34:05 +0000587 // Loop-variant expressions must stay in the immediate field of the
588 // expression.
589 if ((isAddress && isTargetConstant(Val)) ||
590 !Val->isLoopInvariant(L)) {
591 Imm = SCEVAddExpr::get(Imm, Val);
592 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
593 return;
Chris Lattner7a2ca562005-08-04 19:26:19 +0000594 }
Chris Lattner26d91f12005-08-04 22:34:05 +0000595
596 // Otherwise, no immediates to move.
Nate Begeman16997482005-07-30 00:15:07 +0000597}
598
Chris Lattner934520a2005-08-13 07:27:18 +0000599
600/// IncrementAddExprUses - Decompose the specified expression into its added
601/// subexpressions, and increment SubExpressionUseCounts for each of these
602/// decomposed parts.
603static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
604 SCEVHandle Expr) {
605 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
606 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
607 SeparateSubExprs(SubExprs, AE->getOperand(j));
608 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
609 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Expr->getType());
610 if (SARE->getOperand(0) == Zero) {
611 SubExprs.push_back(Expr);
612 } else {
613 // Compute the addrec with zero as its base.
614 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
615 Ops[0] = Zero; // Start with zero base.
616 SubExprs.push_back(SCEVAddRecExpr::get(Ops, SARE->getLoop()));
617
618
619 SeparateSubExprs(SubExprs, SARE->getOperand(0));
620 }
621 } else if (!isa<SCEVConstant>(Expr) ||
622 !cast<SCEVConstant>(Expr)->getValue()->isNullValue()) {
623 // Do not add zero.
624 SubExprs.push_back(Expr);
625 }
626}
627
628
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000629/// RemoveCommonExpressionsFromUseBases - Look through all of the uses in Bases,
630/// removing any common subexpressions from it. Anything truly common is
631/// removed, accumulated, and returned. This looks for things like (a+b+c) and
632/// (a+c+d) -> (a+c). The common expression is *removed* from the Bases.
633static SCEVHandle
634RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses) {
635 unsigned NumUses = Uses.size();
636
637 // Only one use? Use its base, regardless of what it is!
638 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Uses[0].Base->getType());
639 SCEVHandle Result = Zero;
640 if (NumUses == 1) {
641 std::swap(Result, Uses[0].Base);
642 return Result;
643 }
644
645 // To find common subexpressions, count how many of Uses use each expression.
646 // If any subexpressions are used Uses.size() times, they are common.
647 std::map<SCEVHandle, unsigned> SubExpressionUseCounts;
648
Chris Lattner934520a2005-08-13 07:27:18 +0000649 std::vector<SCEVHandle> SubExprs;
650 for (unsigned i = 0; i != NumUses; ++i) {
651 // If the base is zero (which is common), return zero now, there are no
652 // CSEs we can find.
653 if (Uses[i].Base == Zero) return Zero;
654
655 // Split the expression into subexprs.
656 SeparateSubExprs(SubExprs, Uses[i].Base);
657 // Add one to SubExpressionUseCounts for each subexpr present.
658 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
659 SubExpressionUseCounts[SubExprs[j]]++;
660 SubExprs.clear();
661 }
662
663
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000664 // Now that we know how many times each is used, build Result.
665 for (std::map<SCEVHandle, unsigned>::iterator I =
666 SubExpressionUseCounts.begin(), E = SubExpressionUseCounts.end();
667 I != E; )
668 if (I->second == NumUses) { // Found CSE!
669 Result = SCEVAddExpr::get(Result, I->first);
670 ++I;
671 } else {
672 // Remove non-cse's from SubExpressionUseCounts.
673 SubExpressionUseCounts.erase(I++);
674 }
675
676 // If we found no CSE's, return now.
677 if (Result == Zero) return Result;
678
679 // Otherwise, remove all of the CSE's we found from each of the base values.
Chris Lattner934520a2005-08-13 07:27:18 +0000680 for (unsigned i = 0; i != NumUses; ++i) {
681 // Split the expression into subexprs.
682 SeparateSubExprs(SubExprs, Uses[i].Base);
683
684 // Remove any common subexpressions.
685 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
686 if (SubExpressionUseCounts.count(SubExprs[j])) {
687 SubExprs.erase(SubExprs.begin()+j);
688 --j; --e;
689 }
690
691 // Finally, the non-shared expressions together.
692 if (SubExprs.empty())
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000693 Uses[i].Base = Zero;
Chris Lattner934520a2005-08-13 07:27:18 +0000694 else
695 Uses[i].Base = SCEVAddExpr::get(SubExprs);
Chris Lattner27e51422005-08-13 07:42:01 +0000696 SubExprs.clear();
Chris Lattner934520a2005-08-13 07:27:18 +0000697 }
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000698
699 return Result;
700}
701
702
Nate Begeman16997482005-07-30 00:15:07 +0000703/// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
704/// stride of IV. All of the users may have different starting values, and this
705/// may not be the only stride (we know it is if isOnlyStride is true).
Chris Lattner50fad702005-08-10 00:45:21 +0000706void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
Chris Lattnerec3fb632005-08-03 22:21:05 +0000707 IVUsersOfOneStride &Uses,
708 Loop *L,
Nate Begeman16997482005-07-30 00:15:07 +0000709 bool isOnlyStride) {
710 // Transform our list of users and offsets to a bit more complex table. In
Chris Lattnera553b0c2005-08-08 22:56:21 +0000711 // this new vector, each 'BasedUser' contains 'Base' the base of the
712 // strided accessas well as the old information from Uses. We progressively
713 // move information from the Base field to the Imm field, until we eventually
714 // have the full access expression to rewrite the use.
715 std::vector<BasedUser> UsersToProcess;
Nate Begeman16997482005-07-30 00:15:07 +0000716 UsersToProcess.reserve(Uses.Users.size());
Chris Lattnera553b0c2005-08-08 22:56:21 +0000717 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
718 UsersToProcess.push_back(Uses.Users[i]);
719
720 // Move any loop invariant operands from the offset field to the immediate
721 // field of the use, so that we don't try to use something before it is
722 // computed.
723 MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
724 UsersToProcess.back().Imm, L);
725 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
Chris Lattner26d91f12005-08-04 22:34:05 +0000726 "Base value is not loop invariant!");
Nate Begeman16997482005-07-30 00:15:07 +0000727 }
Chris Lattner44b807e2005-08-08 22:32:34 +0000728
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000729 // We now have a whole bunch of uses of like-strided induction variables, but
730 // they might all have different bases. We want to emit one PHI node for this
731 // stride which we fold as many common expressions (between the IVs) into as
732 // possible. Start by identifying the common expressions in the base values
733 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
734 // "A+B"), emit it to the preheader, then remove the expression from the
735 // UsersToProcess base values.
736 SCEVHandle CommonExprs = RemoveCommonExpressionsFromUseBases(UsersToProcess);
737
Chris Lattner44b807e2005-08-08 22:32:34 +0000738 // Next, figure out what we can represent in the immediate fields of
739 // instructions. If we can represent anything there, move it to the imm
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000740 // fields of the BasedUsers. We do this so that it increases the commonality
741 // of the remaining uses.
Chris Lattner44b807e2005-08-08 22:32:34 +0000742 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
Chris Lattner80b32b32005-08-16 00:38:11 +0000743 // If the user is not in the current loop, this means it is using the exit
744 // value of the IV. Do not put anything in the base, make sure it's all in
745 // the immediate field to allow as much factoring as possible.
746 if (!L->contains(UsersToProcess[i].Inst->getParent())) {
Chris Lattner8385e512005-08-17 21:22:41 +0000747 UsersToProcess[i].Imm = SCEVAddExpr::get(UsersToProcess[i].Imm,
748 UsersToProcess[i].Base);
749 UsersToProcess[i].Base =
750 SCEVUnknown::getIntegerSCEV(0, UsersToProcess[i].Base->getType());
Chris Lattner80b32b32005-08-16 00:38:11 +0000751 } else {
752
753 // Addressing modes can be folded into loads and stores. Be careful that
754 // the store is through the expression, not of the expression though.
755 bool isAddress = isa<LoadInst>(UsersToProcess[i].Inst);
756 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
757 if (SI->getOperand(1) == UsersToProcess[i].OperandValToReplace)
758 isAddress = true;
759
760 MoveImmediateValues(UsersToProcess[i].Base, UsersToProcess[i].Imm,
761 isAddress, L);
762 }
Chris Lattner44b807e2005-08-08 22:32:34 +0000763 }
764
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000765 // Now that we know what we need to do, insert the PHI node itself.
766 //
767 DEBUG(std::cerr << "INSERTING IV of STRIDE " << *Stride << " and BASE "
768 << *CommonExprs << " :\n");
769
770 SCEVExpander Rewriter(*SE, *LI);
771 SCEVExpander PreheaderRewriter(*SE, *LI);
Chris Lattner44b807e2005-08-08 22:32:34 +0000772
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000773 BasicBlock *Preheader = L->getLoopPreheader();
774 Instruction *PreInsertPt = Preheader->getTerminator();
775 Instruction *PhiInsertBefore = L->getHeader()->begin();
Chris Lattner44b807e2005-08-08 22:32:34 +0000776
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000777 assert(isa<PHINode>(PhiInsertBefore) &&
778 "How could this loop have IV's without any phis?");
779 PHINode *SomeLoopPHI = cast<PHINode>(PhiInsertBefore);
780 assert(SomeLoopPHI->getNumIncomingValues() == 2 &&
781 "This loop isn't canonicalized right");
782 BasicBlock *LatchBlock =
Chris Lattner87265ab2005-08-09 23:39:36 +0000783 SomeLoopPHI->getIncomingBlock(SomeLoopPHI->getIncomingBlock(0) == Preheader);
Chris Lattnerbe3e5212005-08-03 23:30:08 +0000784
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000785 // Create a new Phi for this base, and stick it in the loop header.
786 const Type *ReplacedTy = CommonExprs->getType();
787 PHINode *NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
788 ++NumInserted;
789
Chris Lattner50fad702005-08-10 00:45:21 +0000790 // Insert the stride into the preheader.
791 Value *StrideV = PreheaderRewriter.expandCodeFor(Stride, PreInsertPt,
792 ReplacedTy);
793 if (!isa<ConstantInt>(StrideV)) ++NumVariable;
794
795
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000796 // Emit the initial base value into the loop preheader, and add it to the
797 // Phi node.
798 Value *PHIBaseV = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt,
799 ReplacedTy);
800 NewPHI->addIncoming(PHIBaseV, Preheader);
801
802 // Emit the increment of the base value before the terminator of the loop
803 // latch block, and add it to the Phi node.
804 SCEVHandle IncExp = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
Chris Lattner50fad702005-08-10 00:45:21 +0000805 SCEVUnknown::get(StrideV));
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000806
807 Value *IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator(),
808 ReplacedTy);
809 IncV->setName(NewPHI->getName()+".inc");
810 NewPHI->addIncoming(IncV, LatchBlock);
811
Chris Lattner2351aba2005-08-03 22:51:21 +0000812 // Sort by the base value, so that all IVs with identical bases are next to
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000813 // each other.
Chris Lattner2351aba2005-08-03 22:51:21 +0000814 std::sort(UsersToProcess.begin(), UsersToProcess.end());
Nate Begeman16997482005-07-30 00:15:07 +0000815 while (!UsersToProcess.empty()) {
Chris Lattnera553b0c2005-08-08 22:56:21 +0000816 SCEVHandle Base = UsersToProcess.front().Base;
Chris Lattnerbe3e5212005-08-03 23:30:08 +0000817
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000818 DEBUG(std::cerr << " INSERTING code for BASE = " << *Base << ":\n");
Chris Lattnerbe3e5212005-08-03 23:30:08 +0000819
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000820 // Emit the code for Base into the preheader.
Chris Lattner5272f3c2005-08-08 05:47:49 +0000821 Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt,
822 ReplacedTy);
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000823
824 // If BaseV is a constant other than 0, make sure that it gets inserted into
825 // the preheader, instead of being forward substituted into the uses. We do
826 // this by forcing a noop cast to be inserted into the preheader in this
827 // case.
828 if (Constant *C = dyn_cast<Constant>(BaseV))
Chris Lattner7259df32005-09-10 01:18:45 +0000829 if (!C->isNullValue() && !isTargetConstant(Base)) {
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000830 // We want this constant emitted into the preheader!
831 BaseV = new CastInst(BaseV, BaseV->getType(), "preheaderinsert",
832 PreInsertPt);
833 }
834
Nate Begeman16997482005-07-30 00:15:07 +0000835 // Emit the code to add the immediate offset to the Phi value, just before
Chris Lattner2351aba2005-08-03 22:51:21 +0000836 // the instructions that we identified as using this stride and base.
Chris Lattnera553b0c2005-08-08 22:56:21 +0000837 while (!UsersToProcess.empty() && UsersToProcess.front().Base == Base) {
838 BasedUser &User = UsersToProcess.front();
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000839
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000840 // If this instruction wants to use the post-incremented value, move it
841 // after the post-inc and use its value instead of the PHI.
842 Value *RewriteOp = NewPHI;
843 if (User.isUseOfPostIncrementedValue) {
844 RewriteOp = IncV;
845 User.Inst->moveBefore(LatchBlock->getTerminator());
846 }
847 SCEVHandle RewriteExpr = SCEVUnknown::get(RewriteOp);
848
Chris Lattner2351aba2005-08-03 22:51:21 +0000849 // Clear the SCEVExpander's expression map so that we are guaranteed
850 // to have the code emitted where we expect it.
851 Rewriter.clear();
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000852
Chris Lattner2114b272005-08-04 20:03:32 +0000853 // Now that we know what we need to do, insert code before User for the
854 // immediate and any loop-variant expressions.
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000855 if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isNullValue())
856 // Add BaseV to the PHI value if needed.
857 RewriteExpr = SCEVAddExpr::get(RewriteExpr, SCEVUnknown::get(BaseV));
858
Chris Lattnerc60fb082005-08-12 22:22:17 +0000859 User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter, L, this);
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000860
Chris Lattner2351aba2005-08-03 22:51:21 +0000861 // Mark old value we replaced as possibly dead, so that it is elminated
862 // if we just replaced the last use of that value.
Chris Lattner2114b272005-08-04 20:03:32 +0000863 DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
Nate Begeman16997482005-07-30 00:15:07 +0000864
Chris Lattner2351aba2005-08-03 22:51:21 +0000865 UsersToProcess.erase(UsersToProcess.begin());
866 ++NumReduced;
867 }
Nate Begeman16997482005-07-30 00:15:07 +0000868 // TODO: Next, find out which base index is the most common, pull it out.
869 }
870
871 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
872 // different starting values, into different PHIs.
Nate Begeman16997482005-07-30 00:15:07 +0000873}
874
Chris Lattner010de252005-08-08 05:28:22 +0000875// OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
876// uses in the loop, look to see if we can eliminate some, in favor of using
877// common indvars for the different uses.
878void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
879 // TODO: implement optzns here.
880
881
882
883
884 // Finally, get the terminating condition for the loop if possible. If we
885 // can, we want to change it to use a post-incremented version of its
886 // induction variable, to allow coallescing the live ranges for the IV into
887 // one register value.
888 PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
889 BasicBlock *Preheader = L->getLoopPreheader();
890 BasicBlock *LatchBlock =
891 SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
892 BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
893 if (!TermBr || TermBr->isUnconditional() ||
894 !isa<SetCondInst>(TermBr->getCondition()))
895 return;
896 SetCondInst *Cond = cast<SetCondInst>(TermBr->getCondition());
897
898 // Search IVUsesByStride to find Cond's IVUse if there is one.
899 IVStrideUse *CondUse = 0;
Chris Lattner50fad702005-08-10 00:45:21 +0000900 const SCEVHandle *CondStride = 0;
Chris Lattner010de252005-08-08 05:28:22 +0000901
Chris Lattner50fad702005-08-10 00:45:21 +0000902 for (std::map<SCEVHandle, IVUsersOfOneStride>::iterator
903 I = IVUsesByStride.begin(), E = IVUsesByStride.end();
904 I != E && !CondUse; ++I)
Chris Lattner010de252005-08-08 05:28:22 +0000905 for (std::vector<IVStrideUse>::iterator UI = I->second.Users.begin(),
906 E = I->second.Users.end(); UI != E; ++UI)
907 if (UI->User == Cond) {
908 CondUse = &*UI;
Chris Lattner50fad702005-08-10 00:45:21 +0000909 CondStride = &I->first;
Chris Lattner010de252005-08-08 05:28:22 +0000910 // NOTE: we could handle setcc instructions with multiple uses here, but
911 // InstCombine does it as well for simple uses, it's not clear that it
912 // occurs enough in real life to handle.
913 break;
914 }
915 if (!CondUse) return; // setcc doesn't use the IV.
916
917 // setcc stride is complex, don't mess with users.
Chris Lattner50fad702005-08-10 00:45:21 +0000918 // FIXME: Evaluate whether this is a good idea or not.
919 if (!isa<SCEVConstant>(*CondStride)) return;
Chris Lattner010de252005-08-08 05:28:22 +0000920
921 // It's possible for the setcc instruction to be anywhere in the loop, and
922 // possible for it to have multiple users. If it is not immediately before
923 // the latch block branch, move it.
924 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
925 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
926 Cond->moveBefore(TermBr);
927 } else {
928 // Otherwise, clone the terminating condition and insert into the loopend.
929 Cond = cast<SetCondInst>(Cond->clone());
930 Cond->setName(L->getHeader()->getName() + ".termcond");
931 LatchBlock->getInstList().insert(TermBr, Cond);
932
933 // Clone the IVUse, as the old use still exists!
Chris Lattner50fad702005-08-10 00:45:21 +0000934 IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
Chris Lattner010de252005-08-08 05:28:22 +0000935 CondUse->OperandValToReplace);
Chris Lattner50fad702005-08-10 00:45:21 +0000936 CondUse = &IVUsesByStride[*CondStride].Users.back();
Chris Lattner010de252005-08-08 05:28:22 +0000937 }
938 }
939
940 // If we get to here, we know that we can transform the setcc instruction to
941 // use the post-incremented version of the IV, allowing us to coallesce the
942 // live ranges for the IV correctly.
Chris Lattner50fad702005-08-10 00:45:21 +0000943 CondUse->Offset = SCEV::getMinusSCEV(CondUse->Offset, *CondStride);
Chris Lattner010de252005-08-08 05:28:22 +0000944 CondUse->isUseOfPostIncrementedValue = true;
945}
Nate Begeman16997482005-07-30 00:15:07 +0000946
Nate Begemaneaa13852004-10-18 21:08:22 +0000947void LoopStrengthReduce::runOnLoop(Loop *L) {
948 // First step, transform all loops nesting inside of this loop.
949 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
950 runOnLoop(*I);
951
Nate Begeman16997482005-07-30 00:15:07 +0000952 // Next, find all uses of induction variables in this loop, and catagorize
953 // them by stride. Start by finding all of the PHI nodes in the header for
954 // this loop. If they are induction variables, inspect their uses.
Chris Lattner3416e5f2005-08-04 17:40:30 +0000955 std::set<Instruction*> Processed; // Don't reprocess instructions.
Nate Begeman16997482005-07-30 00:15:07 +0000956 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
Chris Lattner3416e5f2005-08-04 17:40:30 +0000957 AddUsersIfInteresting(I, L, Processed);
Nate Begemaneaa13852004-10-18 21:08:22 +0000958
Nate Begeman16997482005-07-30 00:15:07 +0000959 // If we have nothing to do, return.
Chris Lattner010de252005-08-08 05:28:22 +0000960 if (IVUsesByStride.empty()) return;
961
962 // Optimize induction variables. Some indvar uses can be transformed to use
963 // strides that will be needed for other purposes. A common example of this
964 // is the exit test for the loop, which can often be rewritten to use the
965 // computation of some other indvar to decide when to terminate the loop.
966 OptimizeIndvars(L);
967
Misha Brukmanfd939082005-04-21 23:48:37 +0000968
Nate Begeman16997482005-07-30 00:15:07 +0000969 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
970 // doing computation in byte values, promote to 32-bit values if safe.
971
972 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
973 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
974 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
975 // to be careful that IV's are all the same type. Only works for intptr_t
976 // indvars.
977
978 // If we only have one stride, we can more aggressively eliminate some things.
979 bool HasOneStride = IVUsesByStride.size() == 1;
980
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000981 // Note: this processes each stride/type pair individually. All users passed
982 // into StrengthReduceStridedIVUsers have the same type AND stride.
Chris Lattner50fad702005-08-10 00:45:21 +0000983 for (std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI
Chris Lattnerec3fb632005-08-03 22:21:05 +0000984 = IVUsesByStride.begin(), E = IVUsesByStride.end(); SI != E; ++SI)
Nate Begeman16997482005-07-30 00:15:07 +0000985 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
Nate Begemaneaa13852004-10-18 21:08:22 +0000986
987 // Clean up after ourselves
988 if (!DeadInsts.empty()) {
989 DeleteTriviallyDeadInstructions(DeadInsts);
990
Nate Begeman16997482005-07-30 00:15:07 +0000991 BasicBlock::iterator I = L->getHeader()->begin();
992 PHINode *PN;
Chris Lattnere9100c62005-08-02 02:44:31 +0000993 while ((PN = dyn_cast<PHINode>(I))) {
Chris Lattner1060e092005-08-02 00:41:11 +0000994 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
995
Chris Lattner87265ab2005-08-09 23:39:36 +0000996 // At this point, we know that we have killed one or more GEP
997 // instructions. It is worth checking to see if the cann indvar is also
998 // dead, so that we can remove it as well. The requirements for the cann
999 // indvar to be considered dead are:
Nate Begeman16997482005-07-30 00:15:07 +00001000 // 1. the cann indvar has one use
1001 // 2. the use is an add instruction
1002 // 3. the add has one use
1003 // 4. the add is used by the cann indvar
1004 // If all four cases above are true, then we can remove both the add and
1005 // the cann indvar.
1006 // FIXME: this needs to eliminate an induction variable even if it's being
1007 // compared against some value to decide loop termination.
1008 if (PN->hasOneUse()) {
1009 BinaryOperator *BO = dyn_cast<BinaryOperator>(*(PN->use_begin()));
Chris Lattner7e608bb2005-08-02 02:52:02 +00001010 if (BO && BO->hasOneUse()) {
1011 if (PN == *(BO->use_begin())) {
1012 DeadInsts.insert(BO);
1013 // Break the cycle, then delete the PHI.
1014 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattner52d83e62005-08-03 21:36:09 +00001015 SE->deleteInstructionFromRecords(PN);
Chris Lattner7e608bb2005-08-02 02:52:02 +00001016 PN->eraseFromParent();
Nate Begemaneaa13852004-10-18 21:08:22 +00001017 }
Chris Lattner7e608bb2005-08-02 02:52:02 +00001018 }
Nate Begeman16997482005-07-30 00:15:07 +00001019 }
Nate Begemaneaa13852004-10-18 21:08:22 +00001020 }
Nate Begeman16997482005-07-30 00:15:07 +00001021 DeleteTriviallyDeadInstructions(DeadInsts);
Nate Begemaneaa13852004-10-18 21:08:22 +00001022 }
Nate Begeman16997482005-07-30 00:15:07 +00001023
Chris Lattner9a59fbb2005-08-05 01:30:11 +00001024 CastedPointers.clear();
Nate Begeman16997482005-07-30 00:15:07 +00001025 IVUsesByStride.clear();
1026 return;
Nate Begemaneaa13852004-10-18 21:08:22 +00001027}