blob: 4975614e50b9887a855413edf01b7d1228d457d3 [file] [log] [blame]
Nate Begemanb18121e2004-10-18 21:08:22 +00001//===- LoopStrengthReduce.cpp - Strength Reduce GEPs in Loops -------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Nate Begemanb18121e2004-10-18 21:08:22 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by Nate Begeman and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
Nate Begemanb18121e2004-10-18 21:08:22 +00008//===----------------------------------------------------------------------===//
9//
10// This pass performs a strength reduction on array references inside loops that
11// have as one or more of their components the loop induction variable. This is
12// accomplished by creating a new Value to hold the initial value of the array
13// access for the first iteration, and then creating a new GEP instruction in
14// the loop to increment the value by the appropriate amount.
15//
Nate Begemanb18121e2004-10-18 21:08:22 +000016//===----------------------------------------------------------------------===//
17
Chris Lattnerbb78c972005-08-03 23:30:08 +000018#define DEBUG_TYPE "loop-reduce"
Nate Begemanb18121e2004-10-18 21:08:22 +000019#include "llvm/Transforms/Scalar.h"
20#include "llvm/Constants.h"
21#include "llvm/Instructions.h"
22#include "llvm/Type.h"
Jeff Cohena2c59b72005-03-04 04:04:26 +000023#include "llvm/DerivedTypes.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000024#include "llvm/Analysis/Dominators.h"
25#include "llvm/Analysis/LoopInfo.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000026#include "llvm/Analysis/ScalarEvolutionExpander.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000027#include "llvm/Support/CFG.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000028#include "llvm/Support/GetElementPtrTypeIterator.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000029#include "llvm/Transforms/Utils/Local.h"
Jeff Cohena2c59b72005-03-04 04:04:26 +000030#include "llvm/Target/TargetData.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000031#include "llvm/ADT/Statistic.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000032#include "llvm/Support/Debug.h"
Jeff Cohenc5009912005-07-30 18:22:27 +000033#include <algorithm>
Nate Begemanb18121e2004-10-18 21:08:22 +000034#include <set>
35using namespace llvm;
36
37namespace {
38 Statistic<> NumReduced ("loop-reduce", "Number of GEPs strength reduced");
Chris Lattner45f8b6e2005-08-04 22:34:05 +000039 Statistic<> NumInserted("loop-reduce", "Number of PHIs inserted");
Nate Begemanb18121e2004-10-18 21:08:22 +000040
Chris Lattner430d0022005-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 Lattner9bfa6f82005-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 Lattner430d0022005-08-03 22:21:05 +000055
56 IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
Chris Lattner9bfa6f82005-08-08 05:28:22 +000057 : Offset(Offs), User(U), OperandValToReplace(O),
58 isUseOfPostIncrementedValue(false) {}
Chris Lattner430d0022005-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 Begemane68bcd12005-07-30 00:15:07 +000066 /// Users - Keep track of all of the users of this stride as well as the
Chris Lattner430d0022005-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 Begemane68bcd12005-07-30 00:15:07 +000072 }
73 };
74
75
Nate Begemanb18121e2004-10-18 21:08:22 +000076 class LoopStrengthReduce : public FunctionPass {
77 LoopInfo *LI;
78 DominatorSet *DS;
Nate Begemane68bcd12005-07-30 00:15:07 +000079 ScalarEvolution *SE;
80 const TargetData *TD;
81 const Type *UIntPtrTy;
Nate Begemanb18121e2004-10-18 21:08:22 +000082 bool Changed;
Chris Lattner75a44e12005-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 Cohena2c59b72005-03-04 04:04:26 +000086 unsigned MaxTargetAMSize;
Nate Begemane68bcd12005-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 Lattner430d0022005-08-03 22:21:05 +000090 std::map<Value*, IVUsersOfOneStride> IVUsesByStride;
Nate Begemane68bcd12005-07-30 00:15:07 +000091
Chris Lattner6f286b72005-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 Begemane68bcd12005-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 Begemanb18121e2004-10-18 21:08:22 +0000100 public:
Jeff Cohena2c59b72005-03-04 04:04:26 +0000101 LoopStrengthReduce(unsigned MTAMS = 1)
102 : MaxTargetAMSize(MTAMS) {
103 }
104
Nate Begemanb18121e2004-10-18 21:08:22 +0000105 virtual bool runOnFunction(Function &) {
106 LI = &getAnalysis<LoopInfo>();
107 DS = &getAnalysis<DominatorSet>();
Nate Begemane68bcd12005-07-30 00:15:07 +0000108 SE = &getAnalysis<ScalarEvolution>();
109 TD = &getAnalysis<TargetData>();
110 UIntPtrTy = TD->getIntPtrType();
Nate Begemanb18121e2004-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 Lattner6f286b72005-08-04 01:19:13 +0000115
Nate Begemanb18121e2004-10-18 21:08:22 +0000116 return Changed;
117 }
118
119 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
120 AU.setPreservesCFG();
Jeff Cohen39751c32005-02-27 19:37:07 +0000121 AU.addRequiredID(LoopSimplifyID);
Nate Begemanb18121e2004-10-18 21:08:22 +0000122 AU.addRequired<LoopInfo>();
123 AU.addRequired<DominatorSet>();
Jeff Cohena2c59b72005-03-04 04:04:26 +0000124 AU.addRequired<TargetData>();
Nate Begemane68bcd12005-07-30 00:15:07 +0000125 AU.addRequired<ScalarEvolution>();
Nate Begemanb18121e2004-10-18 21:08:22 +0000126 }
Chris Lattner6f286b72005-08-04 01:19:13 +0000127
128 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
129 ///
130 Value *getCastedVersionOf(Value *V);
131private:
Nate Begemanb18121e2004-10-18 21:08:22 +0000132 void runOnLoop(Loop *L);
Chris Lattnereaf24722005-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 Lattner9bfa6f82005-08-08 05:28:22 +0000137 void OptimizeIndvars(Loop *L);
Nate Begemane68bcd12005-07-30 00:15:07 +0000138
Chris Lattner430d0022005-08-03 22:21:05 +0000139 void StrengthReduceStridedIVUsers(Value *Stride, IVUsersOfOneStride &Uses,
140 Loop *L, bool isOnlyStride);
Nate Begemanb18121e2004-10-18 21:08:22 +0000141 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
142 };
Misha Brukmanb1c93172005-04-21 23:48:37 +0000143 RegisterOpt<LoopStrengthReduce> X("loop-reduce",
Nate Begemanb18121e2004-10-18 21:08:22 +0000144 "Strength Reduce GEP Uses of Ind. Vars");
145}
146
Jeff Cohena2c59b72005-03-04 04:04:26 +0000147FunctionPass *llvm::createLoopStrengthReducePass(unsigned MaxTargetAMSize) {
148 return new LoopStrengthReduce(MaxTargetAMSize);
Nate Begemanb18121e2004-10-18 21:08:22 +0000149}
150
Chris Lattner6f286b72005-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 Lattneracc42c42005-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 Lattner6f286b72005-08-04 01:19:13 +0000181}
182
183
Nate Begemanb18121e2004-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 Cohen8ea6f9e2005-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 Lattner84e9baa2005-08-03 21:36:09 +0000196 SE->deleteInstructionFromRecords(I);
197 I->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +0000198 Changed = true;
199 }
200 }
201}
202
Jeff Cohen39751c32005-02-27 19:37:07 +0000203
Chris Lattnereaf24722005-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 Lattnerc6c4d992005-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 Lattnereaf24722005-08-04 17:40:30 +0000211 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000212 if (!GEP || SE->hasSCEV(GEP))
Chris Lattnereaf24722005-08-04 17:40:30 +0000213 return SE->getSCEV(Exp);
214
Nate Begemane68bcd12005-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 Lattnereaf24722005-08-04 17:40:30 +0000221 SCEVHandle GEPVal = SCEVUnknown::get(getCastedVersionOf(GEP->getOperand(0)));
Nate Begemane68bcd12005-07-30 00:15:07 +0000222
223 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnereaf24722005-08-04 17:40:30 +0000224
225 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
Nate Begemane68bcd12005-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 Lattnereaf24722005-08-04 17:40:30 +0000233 GEPVal = SCEVAddExpr::get(GEPVal,
234 SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy));
Nate Begemane68bcd12005-07-30 00:15:07 +0000235 } else {
Chris Lattneracc42c42005-08-04 19:08:16 +0000236 Value *OpVal = getCastedVersionOf(GEP->getOperand(i));
237 SCEVHandle Idx = SE->getSCEV(OpVal);
238
Chris Lattnereaf24722005-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 Begemane68bcd12005-07-30 00:15:07 +0000245 }
246 }
247
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000248 SE->setSCEV(GEP, GEPVal);
Chris Lattnereaf24722005-08-04 17:40:30 +0000249 return GEPVal;
Nate Begemane68bcd12005-07-30 00:15:07 +0000250}
251
Chris Lattneracc42c42005-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 Begemane68bcd12005-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 Lattnereaf24722005-08-04 17:40:30 +0000304bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
305 std::set<Instruction*> &Processed) {
Nate Begeman17a0e2af2005-07-30 00:21:31 +0000306 if (I->getType() == Type::VoidTy) return false;
Chris Lattnereaf24722005-08-04 17:40:30 +0000307 if (!Processed.insert(I).second)
308 return true; // Instruction already handled.
309
Chris Lattneracc42c42005-08-04 19:08:16 +0000310 // Get the symbolic expression for this instruction.
Chris Lattnereaf24722005-08-04 17:40:30 +0000311 SCEVHandle ISE = GetExpressionSCEV(I, L);
Chris Lattneracc42c42005-08-04 19:08:16 +0000312 if (isa<SCEVCouldNotCompute>(ISE)) return false;
Chris Lattnereaf24722005-08-04 17:40:30 +0000313
Chris Lattneracc42c42005-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 Begemane68bcd12005-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 Lattnera0102fb2005-08-04 00:14:11 +0000328 // don't recurse into it.
Chris Lattneracc42c42005-08-04 19:08:16 +0000329 bool AddUserToIVUsers = false;
Chris Lattnera0102fb2005-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 Lattneracc42c42005-08-04 19:08:16 +0000333 AddUserToIVUsers = true;
Chris Lattnereaf24722005-08-04 17:40:30 +0000334 } else if (!AddUsersIfInteresting(User, L, Processed)) {
Chris Lattner65107492005-08-04 00:40:47 +0000335 DEBUG(std::cerr << "FOUND USER: " << *User
336 << " OF SCEV: " << *ISE << "\n");
Chris Lattneracc42c42005-08-04 19:08:16 +0000337 AddUserToIVUsers = true;
338 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000339
Chris Lattneracc42c42005-08-04 19:08:16 +0000340 if (AddUserToIVUsers) {
Chris Lattner65107492005-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 Lattneracc42c42005-08-04 19:08:16 +0000343 IVUsesByStride[Stride].addUser(Start, User, I);
Nate Begemane68bcd12005-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 Lattner37c24cc2005-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 Begemane68bcd12005-07-30 00:15:07 +0000359 /// Inst - The instruction using the induction variable.
360 Instruction *Inst;
361
Chris Lattner430d0022005-08-03 22:21:05 +0000362 /// OperandValToReplace - The operand value of Inst to replace with the
363 /// EmittedBase.
364 Value *OperandValToReplace;
Nate Begemane68bcd12005-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 Lattner9bfa6f82005-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 Lattner37c24cc2005-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 Begemane68bcd12005-07-30 00:15:07 +0000386
Chris Lattnera6d7c352005-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 Lattnera091ff12005-08-09 00:18:09 +0000390 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
391 SCEVExpander &Rewriter);
Nate Begemane68bcd12005-07-30 00:15:07 +0000392
Chris Lattner37c24cc2005-08-08 22:56:21 +0000393 // Sort by the Base field.
394 bool operator<(const BasedUser &BU) const { return Base < BU.Base; }
Nate Begemane68bcd12005-07-30 00:15:07 +0000395
396 void dump() const;
397 };
398}
399
400void BasedUser::dump() const {
Chris Lattner37c24cc2005-08-08 22:56:21 +0000401 std::cerr << " Base=" << *Base;
Nate Begemane68bcd12005-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 Lattnera6d7c352005-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 Lattnera091ff12005-08-09 00:18:09 +0000412void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattnera6d7c352005-08-04 20:03:32 +0000413 SCEVExpander &Rewriter) {
414 if (!isa<PHINode>(Inst)) {
Chris Lattnera091ff12005-08-09 00:18:09 +0000415 SCEVHandle NewValSCEV = SCEVAddExpr::get(NewBase, Imm);
Chris Lattnera6d7c352005-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
426 // expression into each operand block that uses it.
427 PHINode *PN = cast<PHINode>(Inst);
428 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
429 if (PN->getIncomingValue(i) == OperandValToReplace) {
430 // FIXME: this should split any critical edges.
431
432 // Insert the code into the end of the predecessor block.
433 BasicBlock::iterator InsertPt = PN->getIncomingBlock(i)->getTerminator();
434
Chris Lattnera091ff12005-08-09 00:18:09 +0000435 SCEVHandle NewValSCEV = SCEVAddExpr::get(NewBase, Imm);
Chris Lattnera6d7c352005-08-04 20:03:32 +0000436 Value *NewVal = Rewriter.expandCodeFor(NewValSCEV, InsertPt,
437 OperandValToReplace->getType());
438
439 // Replace the use of the operand Value with the new Phi we just created.
440 PN->setIncomingValue(i, NewVal);
441 Rewriter.clear();
442 }
443 }
444 DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst);
445}
446
447
Nate Begemane68bcd12005-07-30 00:15:07 +0000448/// isTargetConstant - Return true if the following can be referenced by the
449/// immediate field of a target instruction.
450static bool isTargetConstant(const SCEVHandle &V) {
Jeff Cohen546fd592005-07-30 18:33:25 +0000451
Nate Begemane68bcd12005-07-30 00:15:07 +0000452 // FIXME: Look at the target to decide if &GV is a legal constant immediate.
Chris Lattner14203e82005-08-08 06:25:50 +0000453 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
454 // PPC allows a sign-extended 16-bit immediate field.
455 if ((int64_t)SC->getValue()->getRawValue() > -(1 << 16) &&
456 (int64_t)SC->getValue()->getRawValue() < (1 << 16)-1)
457 return true;
458 return false;
459 }
Jeff Cohen546fd592005-07-30 18:33:25 +0000460
Nate Begemane68bcd12005-07-30 00:15:07 +0000461 return false; // ENABLE this for x86
Jeff Cohen546fd592005-07-30 18:33:25 +0000462
Nate Begemane68bcd12005-07-30 00:15:07 +0000463 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
464 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
465 if (CE->getOpcode() == Instruction::Cast)
466 if (isa<GlobalValue>(CE->getOperand(0)))
467 // FIXME: should check to see that the dest is uintptr_t!
468 return true;
469 return false;
470}
471
Chris Lattner37ed8952005-08-08 22:32:34 +0000472/// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
473/// loop varying to the Imm operand.
474static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
475 Loop *L) {
476 if (Val->isLoopInvariant(L)) return; // Nothing to do.
477
478 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
479 std::vector<SCEVHandle> NewOps;
480 NewOps.reserve(SAE->getNumOperands());
481
482 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
483 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
484 // If this is a loop-variant expression, it must stay in the immediate
485 // field of the expression.
486 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
487 } else {
488 NewOps.push_back(SAE->getOperand(i));
489 }
490
491 if (NewOps.empty())
492 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
493 else
494 Val = SCEVAddExpr::get(NewOps);
495 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
496 // Try to pull immediates out of the start value of nested addrec's.
497 SCEVHandle Start = SARE->getStart();
498 MoveLoopVariantsToImediateField(Start, Imm, L);
499
500 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
501 Ops[0] = Start;
502 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
503 } else {
504 // Otherwise, all of Val is variant, move the whole thing over.
505 Imm = SCEVAddExpr::get(Imm, Val);
506 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
507 }
508}
509
510
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000511/// MoveImmediateValues - Look at Val, and pull out any additions of constants
Nate Begemane68bcd12005-07-30 00:15:07 +0000512/// that can fit into the immediate field of instructions in the target.
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000513/// Accumulate these immediate values into the Imm value.
514static void MoveImmediateValues(SCEVHandle &Val, SCEVHandle &Imm,
515 bool isAddress, Loop *L) {
Chris Lattnerfc624702005-08-03 23:44:42 +0000516 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000517 std::vector<SCEVHandle> NewOps;
518 NewOps.reserve(SAE->getNumOperands());
519
520 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
Chris Lattneracc42c42005-08-04 19:08:16 +0000521 if (isAddress && isTargetConstant(SAE->getOperand(i))) {
522 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
523 } else if (!SAE->getOperand(i)->isLoopInvariant(L)) {
524 // If this is a loop-variant expression, it must stay in the immediate
525 // field of the expression.
526 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000527 } else {
528 NewOps.push_back(SAE->getOperand(i));
Nate Begemane68bcd12005-07-30 00:15:07 +0000529 }
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000530
531 if (NewOps.empty())
532 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
533 else
534 Val = SCEVAddExpr::get(NewOps);
535 return;
Chris Lattnerfc624702005-08-03 23:44:42 +0000536 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
537 // Try to pull immediates out of the start value of nested addrec's.
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000538 SCEVHandle Start = SARE->getStart();
539 MoveImmediateValues(Start, Imm, isAddress, L);
540
541 if (Start != SARE->getStart()) {
542 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
543 Ops[0] = Start;
544 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
545 }
546 return;
Nate Begemane68bcd12005-07-30 00:15:07 +0000547 }
548
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000549 // Loop-variant expressions must stay in the immediate field of the
550 // expression.
551 if ((isAddress && isTargetConstant(Val)) ||
552 !Val->isLoopInvariant(L)) {
553 Imm = SCEVAddExpr::get(Imm, Val);
554 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
555 return;
Chris Lattner0f7c0fa2005-08-04 19:26:19 +0000556 }
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000557
558 // Otherwise, no immediates to move.
Nate Begemane68bcd12005-07-30 00:15:07 +0000559}
560
Chris Lattnera091ff12005-08-09 00:18:09 +0000561/// RemoveCommonExpressionsFromUseBases - Look through all of the uses in Bases,
562/// removing any common subexpressions from it. Anything truly common is
563/// removed, accumulated, and returned. This looks for things like (a+b+c) and
564/// (a+c+d) -> (a+c). The common expression is *removed* from the Bases.
565static SCEVHandle
566RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses) {
567 unsigned NumUses = Uses.size();
568
569 // Only one use? Use its base, regardless of what it is!
570 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Uses[0].Base->getType());
571 SCEVHandle Result = Zero;
572 if (NumUses == 1) {
573 std::swap(Result, Uses[0].Base);
574 return Result;
575 }
576
577 // To find common subexpressions, count how many of Uses use each expression.
578 // If any subexpressions are used Uses.size() times, they are common.
579 std::map<SCEVHandle, unsigned> SubExpressionUseCounts;
580
581 for (unsigned i = 0; i != NumUses; ++i)
582 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Uses[i].Base)) {
583 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
584 SubExpressionUseCounts[AE->getOperand(j)]++;
585 } else {
586 // If the base is zero (which is common), return zero now, there are no
587 // CSEs we can find.
588 if (Uses[i].Base == Zero) return Result;
589 SubExpressionUseCounts[Uses[i].Base]++;
590 }
591
592 // Now that we know how many times each is used, build Result.
593 for (std::map<SCEVHandle, unsigned>::iterator I =
594 SubExpressionUseCounts.begin(), E = SubExpressionUseCounts.end();
595 I != E; )
596 if (I->second == NumUses) { // Found CSE!
597 Result = SCEVAddExpr::get(Result, I->first);
598 ++I;
599 } else {
600 // Remove non-cse's from SubExpressionUseCounts.
601 SubExpressionUseCounts.erase(I++);
602 }
603
604 // If we found no CSE's, return now.
605 if (Result == Zero) return Result;
606
607 // Otherwise, remove all of the CSE's we found from each of the base values.
608 for (unsigned i = 0; i != NumUses; ++i)
609 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Uses[i].Base)) {
610 std::vector<SCEVHandle> NewOps;
611
612 // Remove all of the values that are now in SubExpressionUseCounts.
613 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
614 if (!SubExpressionUseCounts.count(AE->getOperand(j)))
615 NewOps.push_back(AE->getOperand(j));
Chris Lattner02742712005-08-09 01:13:47 +0000616 if (NewOps.size() == 0)
617 Uses[i].Base = Zero;
618 else
619 Uses[i].Base = SCEVAddExpr::get(NewOps);
Chris Lattnera091ff12005-08-09 00:18:09 +0000620 } else {
621 // If the base is zero (which is common), return zero now, there are no
622 // CSEs we can find.
623 assert(Uses[i].Base == Result);
624 Uses[i].Base = Zero;
625 }
626
627 return Result;
628}
629
630
Nate Begemane68bcd12005-07-30 00:15:07 +0000631/// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
632/// stride of IV. All of the users may have different starting values, and this
633/// may not be the only stride (we know it is if isOnlyStride is true).
634void LoopStrengthReduce::StrengthReduceStridedIVUsers(Value *Stride,
Chris Lattner430d0022005-08-03 22:21:05 +0000635 IVUsersOfOneStride &Uses,
636 Loop *L,
Nate Begemane68bcd12005-07-30 00:15:07 +0000637 bool isOnlyStride) {
638 // Transform our list of users and offsets to a bit more complex table. In
Chris Lattner37c24cc2005-08-08 22:56:21 +0000639 // this new vector, each 'BasedUser' contains 'Base' the base of the
640 // strided accessas well as the old information from Uses. We progressively
641 // move information from the Base field to the Imm field, until we eventually
642 // have the full access expression to rewrite the use.
643 std::vector<BasedUser> UsersToProcess;
Nate Begemane68bcd12005-07-30 00:15:07 +0000644 UsersToProcess.reserve(Uses.Users.size());
Chris Lattner37c24cc2005-08-08 22:56:21 +0000645 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
646 UsersToProcess.push_back(Uses.Users[i]);
647
648 // Move any loop invariant operands from the offset field to the immediate
649 // field of the use, so that we don't try to use something before it is
650 // computed.
651 MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
652 UsersToProcess.back().Imm, L);
653 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000654 "Base value is not loop invariant!");
Nate Begemane68bcd12005-07-30 00:15:07 +0000655 }
Chris Lattner37ed8952005-08-08 22:32:34 +0000656
Chris Lattnera091ff12005-08-09 00:18:09 +0000657 // We now have a whole bunch of uses of like-strided induction variables, but
658 // they might all have different bases. We want to emit one PHI node for this
659 // stride which we fold as many common expressions (between the IVs) into as
660 // possible. Start by identifying the common expressions in the base values
661 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
662 // "A+B"), emit it to the preheader, then remove the expression from the
663 // UsersToProcess base values.
664 SCEVHandle CommonExprs = RemoveCommonExpressionsFromUseBases(UsersToProcess);
665
Chris Lattner37ed8952005-08-08 22:32:34 +0000666 // Next, figure out what we can represent in the immediate fields of
667 // instructions. If we can represent anything there, move it to the imm
Chris Lattnera091ff12005-08-09 00:18:09 +0000668 // fields of the BasedUsers. We do this so that it increases the commonality
669 // of the remaining uses.
Chris Lattner37ed8952005-08-08 22:32:34 +0000670 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
671 // Addressing modes can be folded into loads and stores. Be careful that
672 // the store is through the expression, not of the expression though.
Chris Lattner37c24cc2005-08-08 22:56:21 +0000673 bool isAddress = isa<LoadInst>(UsersToProcess[i].Inst);
674 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
675 if (SI->getOperand(1) == UsersToProcess[i].OperandValToReplace)
Chris Lattner37ed8952005-08-08 22:32:34 +0000676 isAddress = true;
677
Chris Lattner37c24cc2005-08-08 22:56:21 +0000678 MoveImmediateValues(UsersToProcess[i].Base, UsersToProcess[i].Imm,
Chris Lattner37ed8952005-08-08 22:32:34 +0000679 isAddress, L);
680 }
681
Chris Lattnera091ff12005-08-09 00:18:09 +0000682 // Now that we know what we need to do, insert the PHI node itself.
683 //
684 DEBUG(std::cerr << "INSERTING IV of STRIDE " << *Stride << " and BASE "
685 << *CommonExprs << " :\n");
686
687 SCEVExpander Rewriter(*SE, *LI);
688 SCEVExpander PreheaderRewriter(*SE, *LI);
Chris Lattner37ed8952005-08-08 22:32:34 +0000689
Chris Lattnera091ff12005-08-09 00:18:09 +0000690 BasicBlock *Preheader = L->getLoopPreheader();
691 Instruction *PreInsertPt = Preheader->getTerminator();
692 Instruction *PhiInsertBefore = L->getHeader()->begin();
Chris Lattner37ed8952005-08-08 22:32:34 +0000693
Chris Lattnera091ff12005-08-09 00:18:09 +0000694 assert(isa<PHINode>(PhiInsertBefore) &&
695 "How could this loop have IV's without any phis?");
696 PHINode *SomeLoopPHI = cast<PHINode>(PhiInsertBefore);
697 assert(SomeLoopPHI->getNumIncomingValues() == 2 &&
698 "This loop isn't canonicalized right");
699 BasicBlock *LatchBlock =
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000700 SomeLoopPHI->getIncomingBlock(SomeLoopPHI->getIncomingBlock(0) == Preheader);
Chris Lattnerbb78c972005-08-03 23:30:08 +0000701
Chris Lattnera091ff12005-08-09 00:18:09 +0000702 // Create a new Phi for this base, and stick it in the loop header.
703 const Type *ReplacedTy = CommonExprs->getType();
704 PHINode *NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
705 ++NumInserted;
706
707 // Emit the initial base value into the loop preheader, and add it to the
708 // Phi node.
709 Value *PHIBaseV = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt,
710 ReplacedTy);
711 NewPHI->addIncoming(PHIBaseV, Preheader);
712
713 // Emit the increment of the base value before the terminator of the loop
714 // latch block, and add it to the Phi node.
715 SCEVHandle IncExp = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
716 SCEVUnknown::get(Stride));
717
718 Value *IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator(),
719 ReplacedTy);
720 IncV->setName(NewPHI->getName()+".inc");
721 NewPHI->addIncoming(IncV, LatchBlock);
722
Chris Lattnerdb23c742005-08-03 22:51:21 +0000723 // Sort by the base value, so that all IVs with identical bases are next to
Chris Lattnera091ff12005-08-09 00:18:09 +0000724 // each other.
Chris Lattnerdb23c742005-08-03 22:51:21 +0000725 std::sort(UsersToProcess.begin(), UsersToProcess.end());
Nate Begemane68bcd12005-07-30 00:15:07 +0000726 while (!UsersToProcess.empty()) {
Chris Lattner37c24cc2005-08-08 22:56:21 +0000727 SCEVHandle Base = UsersToProcess.front().Base;
Chris Lattnerbb78c972005-08-03 23:30:08 +0000728
Chris Lattnera091ff12005-08-09 00:18:09 +0000729 DEBUG(std::cerr << " INSERTING code for BASE = " << *Base << ":\n");
Chris Lattnerbb78c972005-08-03 23:30:08 +0000730
Chris Lattnera091ff12005-08-09 00:18:09 +0000731 // Emit the code for Base into the preheader.
Chris Lattnerc70bbc02005-08-08 05:47:49 +0000732 Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt,
733 ReplacedTy);
Chris Lattnera091ff12005-08-09 00:18:09 +0000734
735 // If BaseV is a constant other than 0, make sure that it gets inserted into
736 // the preheader, instead of being forward substituted into the uses. We do
737 // this by forcing a noop cast to be inserted into the preheader in this
738 // case.
739 if (Constant *C = dyn_cast<Constant>(BaseV))
740 if (!C->isNullValue()) {
741 // We want this constant emitted into the preheader!
742 BaseV = new CastInst(BaseV, BaseV->getType(), "preheaderinsert",
743 PreInsertPt);
744 }
745
Nate Begemane68bcd12005-07-30 00:15:07 +0000746 // Emit the code to add the immediate offset to the Phi value, just before
Chris Lattnerdb23c742005-08-03 22:51:21 +0000747 // the instructions that we identified as using this stride and base.
Chris Lattner37c24cc2005-08-08 22:56:21 +0000748 while (!UsersToProcess.empty() && UsersToProcess.front().Base == Base) {
749 BasedUser &User = UsersToProcess.front();
Jeff Cohen546fd592005-07-30 18:33:25 +0000750
Chris Lattnera091ff12005-08-09 00:18:09 +0000751 // If this instruction wants to use the post-incremented value, move it
752 // after the post-inc and use its value instead of the PHI.
753 Value *RewriteOp = NewPHI;
754 if (User.isUseOfPostIncrementedValue) {
755 RewriteOp = IncV;
756 User.Inst->moveBefore(LatchBlock->getTerminator());
757 }
758 SCEVHandle RewriteExpr = SCEVUnknown::get(RewriteOp);
759
Chris Lattnerdb23c742005-08-03 22:51:21 +0000760 // Clear the SCEVExpander's expression map so that we are guaranteed
761 // to have the code emitted where we expect it.
762 Rewriter.clear();
Chris Lattnera091ff12005-08-09 00:18:09 +0000763
Chris Lattnera6d7c352005-08-04 20:03:32 +0000764 // Now that we know what we need to do, insert code before User for the
765 // immediate and any loop-variant expressions.
Chris Lattnera091ff12005-08-09 00:18:09 +0000766 if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isNullValue())
767 // Add BaseV to the PHI value if needed.
768 RewriteExpr = SCEVAddExpr::get(RewriteExpr, SCEVUnknown::get(BaseV));
769
770 User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter);
Jeff Cohen546fd592005-07-30 18:33:25 +0000771
Chris Lattnerdb23c742005-08-03 22:51:21 +0000772 // Mark old value we replaced as possibly dead, so that it is elminated
773 // if we just replaced the last use of that value.
Chris Lattnera6d7c352005-08-04 20:03:32 +0000774 DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
Nate Begemane68bcd12005-07-30 00:15:07 +0000775
Chris Lattnerdb23c742005-08-03 22:51:21 +0000776 UsersToProcess.erase(UsersToProcess.begin());
777 ++NumReduced;
778 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000779 // TODO: Next, find out which base index is the most common, pull it out.
780 }
781
782 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
783 // different starting values, into different PHIs.
Nate Begemane68bcd12005-07-30 00:15:07 +0000784}
785
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000786// OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
787// uses in the loop, look to see if we can eliminate some, in favor of using
788// common indvars for the different uses.
789void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
790 // TODO: implement optzns here.
791
792
793
794
795 // Finally, get the terminating condition for the loop if possible. If we
796 // can, we want to change it to use a post-incremented version of its
797 // induction variable, to allow coallescing the live ranges for the IV into
798 // one register value.
799 PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
800 BasicBlock *Preheader = L->getLoopPreheader();
801 BasicBlock *LatchBlock =
802 SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
803 BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
804 if (!TermBr || TermBr->isUnconditional() ||
805 !isa<SetCondInst>(TermBr->getCondition()))
806 return;
807 SetCondInst *Cond = cast<SetCondInst>(TermBr->getCondition());
808
809 // Search IVUsesByStride to find Cond's IVUse if there is one.
810 IVStrideUse *CondUse = 0;
811 Value *CondStride = 0;
812
813 for (std::map<Value*, IVUsersOfOneStride>::iterator I =IVUsesByStride.begin(),
814 E = IVUsesByStride.end(); I != E && !CondUse; ++I)
815 for (std::vector<IVStrideUse>::iterator UI = I->second.Users.begin(),
816 E = I->second.Users.end(); UI != E; ++UI)
817 if (UI->User == Cond) {
818 CondUse = &*UI;
819 CondStride = I->first;
820 // NOTE: we could handle setcc instructions with multiple uses here, but
821 // InstCombine does it as well for simple uses, it's not clear that it
822 // occurs enough in real life to handle.
823 break;
824 }
825 if (!CondUse) return; // setcc doesn't use the IV.
826
827 // setcc stride is complex, don't mess with users.
828 if (!isa<ConstantInt>(CondStride)) return;
829
830 // It's possible for the setcc instruction to be anywhere in the loop, and
831 // possible for it to have multiple users. If it is not immediately before
832 // the latch block branch, move it.
833 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
834 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
835 Cond->moveBefore(TermBr);
836 } else {
837 // Otherwise, clone the terminating condition and insert into the loopend.
838 Cond = cast<SetCondInst>(Cond->clone());
839 Cond->setName(L->getHeader()->getName() + ".termcond");
840 LatchBlock->getInstList().insert(TermBr, Cond);
841
842 // Clone the IVUse, as the old use still exists!
843 IVUsesByStride[CondStride].addUser(CondUse->Offset, Cond,
844 CondUse->OperandValToReplace);
845 CondUse = &IVUsesByStride[CondStride].Users.back();
846 }
847 }
848
849 // If we get to here, we know that we can transform the setcc instruction to
850 // use the post-incremented version of the IV, allowing us to coallesce the
851 // live ranges for the IV correctly.
852 CondUse->Offset = SCEV::getMinusSCEV(CondUse->Offset,
853 SCEVUnknown::get(CondStride));
854 CondUse->isUseOfPostIncrementedValue = true;
855}
Nate Begemane68bcd12005-07-30 00:15:07 +0000856
Nate Begemanb18121e2004-10-18 21:08:22 +0000857void LoopStrengthReduce::runOnLoop(Loop *L) {
858 // First step, transform all loops nesting inside of this loop.
859 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
860 runOnLoop(*I);
861
Nate Begemane68bcd12005-07-30 00:15:07 +0000862 // Next, find all uses of induction variables in this loop, and catagorize
863 // them by stride. Start by finding all of the PHI nodes in the header for
864 // this loop. If they are induction variables, inspect their uses.
Chris Lattnereaf24722005-08-04 17:40:30 +0000865 std::set<Instruction*> Processed; // Don't reprocess instructions.
Nate Begemane68bcd12005-07-30 00:15:07 +0000866 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
Chris Lattnereaf24722005-08-04 17:40:30 +0000867 AddUsersIfInteresting(I, L, Processed);
Nate Begemanb18121e2004-10-18 21:08:22 +0000868
Nate Begemane68bcd12005-07-30 00:15:07 +0000869 // If we have nothing to do, return.
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000870 if (IVUsesByStride.empty()) return;
871
872 // Optimize induction variables. Some indvar uses can be transformed to use
873 // strides that will be needed for other purposes. A common example of this
874 // is the exit test for the loop, which can often be rewritten to use the
875 // computation of some other indvar to decide when to terminate the loop.
876 OptimizeIndvars(L);
877
Misha Brukmanb1c93172005-04-21 23:48:37 +0000878
Nate Begemane68bcd12005-07-30 00:15:07 +0000879 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
880 // doing computation in byte values, promote to 32-bit values if safe.
881
882 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
883 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
884 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
885 // to be careful that IV's are all the same type. Only works for intptr_t
886 // indvars.
887
888 // If we only have one stride, we can more aggressively eliminate some things.
889 bool HasOneStride = IVUsesByStride.size() == 1;
890
Chris Lattnera091ff12005-08-09 00:18:09 +0000891 // Note: this processes each stride/type pair individually. All users passed
892 // into StrengthReduceStridedIVUsers have the same type AND stride.
Chris Lattner430d0022005-08-03 22:21:05 +0000893 for (std::map<Value*, IVUsersOfOneStride>::iterator SI
894 = IVUsesByStride.begin(), E = IVUsesByStride.end(); SI != E; ++SI)
Nate Begemane68bcd12005-07-30 00:15:07 +0000895 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
Nate Begemanb18121e2004-10-18 21:08:22 +0000896
897 // Clean up after ourselves
898 if (!DeadInsts.empty()) {
899 DeleteTriviallyDeadInstructions(DeadInsts);
900
Nate Begemane68bcd12005-07-30 00:15:07 +0000901 BasicBlock::iterator I = L->getHeader()->begin();
902 PHINode *PN;
Chris Lattnerdcce49e2005-08-02 02:44:31 +0000903 while ((PN = dyn_cast<PHINode>(I))) {
Chris Lattner564900e2005-08-02 00:41:11 +0000904 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
905
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000906 // At this point, we know that we have killed one or more GEP
907 // instructions. It is worth checking to see if the cann indvar is also
908 // dead, so that we can remove it as well. The requirements for the cann
909 // indvar to be considered dead are:
Nate Begemane68bcd12005-07-30 00:15:07 +0000910 // 1. the cann indvar has one use
911 // 2. the use is an add instruction
912 // 3. the add has one use
913 // 4. the add is used by the cann indvar
914 // If all four cases above are true, then we can remove both the add and
915 // the cann indvar.
916 // FIXME: this needs to eliminate an induction variable even if it's being
917 // compared against some value to decide loop termination.
918 if (PN->hasOneUse()) {
919 BinaryOperator *BO = dyn_cast<BinaryOperator>(*(PN->use_begin()));
Chris Lattner75a44e12005-08-02 02:52:02 +0000920 if (BO && BO->hasOneUse()) {
921 if (PN == *(BO->use_begin())) {
922 DeadInsts.insert(BO);
923 // Break the cycle, then delete the PHI.
924 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattner84e9baa2005-08-03 21:36:09 +0000925 SE->deleteInstructionFromRecords(PN);
Chris Lattner75a44e12005-08-02 02:52:02 +0000926 PN->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +0000927 }
Chris Lattner75a44e12005-08-02 02:52:02 +0000928 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000929 }
Nate Begemanb18121e2004-10-18 21:08:22 +0000930 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000931 DeleteTriviallyDeadInstructions(DeadInsts);
Nate Begemanb18121e2004-10-18 21:08:22 +0000932 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000933
Chris Lattner11e7a5e2005-08-05 01:30:11 +0000934 CastedPointers.clear();
Nate Begemane68bcd12005-07-30 00:15:07 +0000935 IVUsesByStride.clear();
936 return;
Nate Begemanb18121e2004-10-18 21:08:22 +0000937}