blob: c132aaef927e4e90fb2cb3f716e943f29965cdef [file] [log] [blame]
Nate Begemanb18121e2004-10-18 21:08:22 +00001//===- LoopStrengthReduce.cpp - Strength Reduce GEPs in Loops -------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Nate Begemanb18121e2004-10-18 21:08:22 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by Nate Begeman and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
Nate Begemanb18121e2004-10-18 21:08:22 +00008//===----------------------------------------------------------------------===//
9//
10// This pass performs a strength reduction on array references inside loops that
11// have as one or more of their components the loop induction variable. This is
12// accomplished by creating a new Value to hold the initial value of the array
13// access for the first iteration, and then creating a new GEP instruction in
14// the loop to increment the value by the appropriate amount.
15//
Nate Begemanb18121e2004-10-18 21:08:22 +000016//===----------------------------------------------------------------------===//
17
Chris Lattnerbb78c972005-08-03 23:30:08 +000018#define DEBUG_TYPE "loop-reduce"
Nate Begemanb18121e2004-10-18 21:08:22 +000019#include "llvm/Transforms/Scalar.h"
20#include "llvm/Constants.h"
21#include "llvm/Instructions.h"
22#include "llvm/Type.h"
Jeff Cohena2c59b72005-03-04 04:04:26 +000023#include "llvm/DerivedTypes.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000024#include "llvm/Analysis/Dominators.h"
25#include "llvm/Analysis/LoopInfo.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000026#include "llvm/Analysis/ScalarEvolutionExpander.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000027#include "llvm/Support/CFG.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000028#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner4fec86d2005-08-12 22:06:11 +000029#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000030#include "llvm/Transforms/Utils/Local.h"
Jeff Cohena2c59b72005-03-04 04:04:26 +000031#include "llvm/Target/TargetData.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000032#include "llvm/ADT/Statistic.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000033#include "llvm/Support/Debug.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000034#include "llvm/Support/Compiler.h"
Evan Chengc567c4e2006-03-13 23:14:23 +000035#include "llvm/Target/TargetLowering.h"
Jeff Cohenc5009912005-07-30 18:22:27 +000036#include <algorithm>
Nate Begemanb18121e2004-10-18 21:08:22 +000037#include <set>
38using namespace llvm;
39
40namespace {
Chris Lattner700b8732006-12-06 17:46:33 +000041 Statistic NumReduced ("loop-reduce", "Number of GEPs strength reduced");
42 Statistic NumInserted("loop-reduce", "Number of PHIs inserted");
43 Statistic NumVariable("loop-reduce","Number of PHIs with variable strides");
Nate Begemanb18121e2004-10-18 21:08:22 +000044
Chris Lattner430d0022005-08-03 22:21:05 +000045 /// IVStrideUse - Keep track of one use of a strided induction variable, where
46 /// the stride is stored externally. The Offset member keeps track of the
47 /// offset from the IV, User is the actual user of the operand, and 'Operand'
48 /// is the operand # of the User that is the use.
49 struct IVStrideUse {
50 SCEVHandle Offset;
51 Instruction *User;
52 Value *OperandValToReplace;
Chris Lattner9bfa6f82005-08-08 05:28:22 +000053
54 // isUseOfPostIncrementedValue - True if this should use the
55 // post-incremented version of this IV, not the preincremented version.
56 // This can only be set in special cases, such as the terminating setcc
Chris Lattnera6764832005-09-12 06:04:47 +000057 // instruction for a loop or uses dominated by the loop.
Chris Lattner9bfa6f82005-08-08 05:28:22 +000058 bool isUseOfPostIncrementedValue;
Chris Lattner430d0022005-08-03 22:21:05 +000059
60 IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
Chris Lattner9bfa6f82005-08-08 05:28:22 +000061 : Offset(Offs), User(U), OperandValToReplace(O),
62 isUseOfPostIncrementedValue(false) {}
Chris Lattner430d0022005-08-03 22:21:05 +000063 };
64
65 /// IVUsersOfOneStride - This structure keeps track of all instructions that
66 /// have an operand that is based on the trip count multiplied by some stride.
67 /// The stride for all of these users is common and kept external to this
68 /// structure.
69 struct IVUsersOfOneStride {
Nate Begemane68bcd12005-07-30 00:15:07 +000070 /// Users - Keep track of all of the users of this stride as well as the
Chris Lattner430d0022005-08-03 22:21:05 +000071 /// initial value and the operand that uses the IV.
72 std::vector<IVStrideUse> Users;
73
74 void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
75 Users.push_back(IVStrideUse(Offset, User, Operand));
Nate Begemane68bcd12005-07-30 00:15:07 +000076 }
77 };
78
Evan Cheng3df447d2006-03-16 21:53:05 +000079 /// IVInfo - This structure keeps track of one IV expression inserted during
Evan Chengc28282b2006-03-18 08:03:12 +000080 /// StrengthReduceStridedIVUsers. It contains the stride, the common base, as
81 /// well as the PHI node and increment value created for rewrite.
Evan Cheng3df447d2006-03-16 21:53:05 +000082 struct IVExpr {
Evan Chengc28282b2006-03-18 08:03:12 +000083 SCEVHandle Stride;
Evan Cheng3df447d2006-03-16 21:53:05 +000084 SCEVHandle Base;
85 PHINode *PHI;
86 Value *IncV;
87
Evan Chengc28282b2006-03-18 08:03:12 +000088 IVExpr()
89 : Stride(SCEVUnknown::getIntegerSCEV(0, Type::UIntTy)),
90 Base (SCEVUnknown::getIntegerSCEV(0, Type::UIntTy)) {}
91 IVExpr(const SCEVHandle &stride, const SCEVHandle &base, PHINode *phi,
92 Value *incv)
93 : Stride(stride), Base(base), PHI(phi), IncV(incv) {}
Evan Cheng3df447d2006-03-16 21:53:05 +000094 };
95
96 /// IVsOfOneStride - This structure keeps track of all IV expression inserted
97 /// during StrengthReduceStridedIVUsers for a particular stride of the IV.
98 struct IVsOfOneStride {
99 std::vector<IVExpr> IVs;
100
Evan Chengc28282b2006-03-18 08:03:12 +0000101 void addIV(const SCEVHandle &Stride, const SCEVHandle &Base, PHINode *PHI,
102 Value *IncV) {
103 IVs.push_back(IVExpr(Stride, Base, PHI, IncV));
Evan Cheng3df447d2006-03-16 21:53:05 +0000104 }
105 };
Nate Begemane68bcd12005-07-30 00:15:07 +0000106
Chris Lattner996795b2006-06-28 23:17:24 +0000107 class VISIBILITY_HIDDEN LoopStrengthReduce : public FunctionPass {
Nate Begemanb18121e2004-10-18 21:08:22 +0000108 LoopInfo *LI;
Chris Lattnercb367102006-01-11 05:10:20 +0000109 ETForest *EF;
Nate Begemane68bcd12005-07-30 00:15:07 +0000110 ScalarEvolution *SE;
111 const TargetData *TD;
112 const Type *UIntPtrTy;
Nate Begemanb18121e2004-10-18 21:08:22 +0000113 bool Changed;
Chris Lattner75a44e12005-08-02 02:52:02 +0000114
Nate Begemane68bcd12005-07-30 00:15:07 +0000115 /// IVUsesByStride - Keep track of all uses of induction variables that we
116 /// are interested in. The key of the map is the stride of the access.
Chris Lattneredff91a2005-08-10 00:45:21 +0000117 std::map<SCEVHandle, IVUsersOfOneStride> IVUsesByStride;
Nate Begemane68bcd12005-07-30 00:15:07 +0000118
Evan Cheng3df447d2006-03-16 21:53:05 +0000119 /// IVsByStride - Keep track of all IVs that have been inserted for a
120 /// particular stride.
121 std::map<SCEVHandle, IVsOfOneStride> IVsByStride;
122
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000123 /// StrideOrder - An ordering of the keys in IVUsesByStride that is stable:
124 /// We use this to iterate over the IVUsesByStride collection without being
125 /// dependent on random ordering of pointers in the process.
126 std::vector<SCEVHandle> StrideOrder;
127
Chris Lattner6f286b72005-08-04 01:19:13 +0000128 /// CastedValues - As we need to cast values to uintptr_t, this keeps track
129 /// of the casted version of each value. This is accessed by
130 /// getCastedVersionOf.
131 std::map<Value*, Value*> CastedPointers;
Nate Begemane68bcd12005-07-30 00:15:07 +0000132
133 /// DeadInsts - Keep track of instructions we may have made dead, so that
134 /// we can remove them after we are done working.
135 std::set<Instruction*> DeadInsts;
Evan Chengc567c4e2006-03-13 23:14:23 +0000136
137 /// TLI - Keep a pointer of a TargetLowering to consult for determining
138 /// transformation profitability.
139 const TargetLowering *TLI;
140
Nate Begemanb18121e2004-10-18 21:08:22 +0000141 public:
Evan Cheng3df447d2006-03-16 21:53:05 +0000142 LoopStrengthReduce(const TargetLowering *tli = NULL)
143 : TLI(tli) {
Jeff Cohena2c59b72005-03-04 04:04:26 +0000144 }
145
Nate Begemanb18121e2004-10-18 21:08:22 +0000146 virtual bool runOnFunction(Function &) {
147 LI = &getAnalysis<LoopInfo>();
Chris Lattnercb367102006-01-11 05:10:20 +0000148 EF = &getAnalysis<ETForest>();
Nate Begemane68bcd12005-07-30 00:15:07 +0000149 SE = &getAnalysis<ScalarEvolution>();
150 TD = &getAnalysis<TargetData>();
151 UIntPtrTy = TD->getIntPtrType();
Nate Begemanb18121e2004-10-18 21:08:22 +0000152 Changed = false;
153
154 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
155 runOnLoop(*I);
Chris Lattner6f286b72005-08-04 01:19:13 +0000156
Nate Begemanb18121e2004-10-18 21:08:22 +0000157 return Changed;
158 }
159
160 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000161 // We split critical edges, so we change the CFG. However, we do update
162 // many analyses if they are around.
163 AU.addPreservedID(LoopSimplifyID);
164 AU.addPreserved<LoopInfo>();
165 AU.addPreserved<DominatorSet>();
Chris Lattnercb367102006-01-11 05:10:20 +0000166 AU.addPreserved<ETForest>();
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000167 AU.addPreserved<ImmediateDominators>();
168 AU.addPreserved<DominanceFrontier>();
169 AU.addPreserved<DominatorTree>();
170
Jeff Cohen39751c32005-02-27 19:37:07 +0000171 AU.addRequiredID(LoopSimplifyID);
Nate Begemanb18121e2004-10-18 21:08:22 +0000172 AU.addRequired<LoopInfo>();
Chris Lattnercb367102006-01-11 05:10:20 +0000173 AU.addRequired<ETForest>();
Jeff Cohena2c59b72005-03-04 04:04:26 +0000174 AU.addRequired<TargetData>();
Nate Begemane68bcd12005-07-30 00:15:07 +0000175 AU.addRequired<ScalarEvolution>();
Nate Begemanb18121e2004-10-18 21:08:22 +0000176 }
Chris Lattner6f286b72005-08-04 01:19:13 +0000177
178 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
179 ///
180 Value *getCastedVersionOf(Value *V);
181private:
Nate Begemanb18121e2004-10-18 21:08:22 +0000182 void runOnLoop(Loop *L);
Chris Lattnereaf24722005-08-04 17:40:30 +0000183 bool AddUsersIfInteresting(Instruction *I, Loop *L,
184 std::set<Instruction*> &Processed);
185 SCEVHandle GetExpressionSCEV(Instruction *E, Loop *L);
186
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000187 void OptimizeIndvars(Loop *L);
Nate Begemane68bcd12005-07-30 00:15:07 +0000188
Evan Chenge9c68f52006-07-18 19:07:58 +0000189 unsigned CheckForIVReuse(const SCEVHandle&, IVExpr&, const Type*);
Evan Cheng45206982006-03-17 19:52:23 +0000190
Chris Lattneredff91a2005-08-10 00:45:21 +0000191 void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
192 IVUsersOfOneStride &Uses,
Chris Lattner430d0022005-08-03 22:21:05 +0000193 Loop *L, bool isOnlyStride);
Nate Begemanb18121e2004-10-18 21:08:22 +0000194 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
195 };
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000196 RegisterPass<LoopStrengthReduce> X("loop-reduce", "Loop Strength Reduction");
Nate Begemanb18121e2004-10-18 21:08:22 +0000197}
198
Evan Cheng3df447d2006-03-16 21:53:05 +0000199FunctionPass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
200 return new LoopStrengthReduce(TLI);
Nate Begemanb18121e2004-10-18 21:08:22 +0000201}
202
Reid Spencerb341b082006-12-12 05:05:00 +0000203/// getCastedVersionOf - Return the specified value casted to uintptr_t. This
204/// assumes that the Value* V is of integer or pointer type only.
Chris Lattner6f286b72005-08-04 01:19:13 +0000205///
206Value *LoopStrengthReduce::getCastedVersionOf(Value *V) {
207 if (V->getType() == UIntPtrTy) return V;
208 if (Constant *CB = dyn_cast<Constant>(V))
Reid Spencerb341b082006-12-12 05:05:00 +0000209 if (CB->getType()->isInteger())
210 return ConstantExpr::getIntegerCast(CB, UIntPtrTy,
211 CB->getType()->isSigned());
212 else
213 return ConstantExpr::getPtrToInt(CB, UIntPtrTy);
Chris Lattner6f286b72005-08-04 01:19:13 +0000214
215 Value *&New = CastedPointers[V];
216 if (New) return New;
217
Chris Lattnerd30c4992006-02-04 09:52:43 +0000218 New = SCEVExpander::InsertCastOfTo(V, UIntPtrTy);
Chris Lattneracc42c42005-08-04 19:08:16 +0000219 DeadInsts.insert(cast<Instruction>(New));
220 return New;
Chris Lattner6f286b72005-08-04 01:19:13 +0000221}
222
223
Nate Begemanb18121e2004-10-18 21:08:22 +0000224/// DeleteTriviallyDeadInstructions - If any of the instructions is the
225/// specified set are trivially dead, delete them and see if this makes any of
226/// their operands subsequently dead.
227void LoopStrengthReduce::
228DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
229 while (!Insts.empty()) {
230 Instruction *I = *Insts.begin();
231 Insts.erase(Insts.begin());
232 if (isInstructionTriviallyDead(I)) {
Jeff Cohen8ea6f9e2005-03-01 03:46:11 +0000233 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
234 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
235 Insts.insert(U);
Chris Lattner84e9baa2005-08-03 21:36:09 +0000236 SE->deleteInstructionFromRecords(I);
237 I->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +0000238 Changed = true;
239 }
240 }
241}
242
Jeff Cohen39751c32005-02-27 19:37:07 +0000243
Chris Lattnereaf24722005-08-04 17:40:30 +0000244/// GetExpressionSCEV - Compute and return the SCEV for the specified
245/// instruction.
246SCEVHandle LoopStrengthReduce::GetExpressionSCEV(Instruction *Exp, Loop *L) {
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000247 // Scalar Evolutions doesn't know how to compute SCEV's for GEP instructions.
248 // If this is a GEP that SE doesn't know about, compute it now and insert it.
249 // If this is not a GEP, or if we have already done this computation, just let
250 // SE figure it out.
Chris Lattnereaf24722005-08-04 17:40:30 +0000251 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000252 if (!GEP || SE->hasSCEV(GEP))
Chris Lattnereaf24722005-08-04 17:40:30 +0000253 return SE->getSCEV(Exp);
254
Nate Begemane68bcd12005-07-30 00:15:07 +0000255 // Analyze all of the subscripts of this getelementptr instruction, looking
256 // for uses that are determined by the trip count of L. First, skip all
257 // operands the are not dependent on the IV.
258
259 // Build up the base expression. Insert an LLVM cast of the pointer to
260 // uintptr_t first.
Chris Lattnereaf24722005-08-04 17:40:30 +0000261 SCEVHandle GEPVal = SCEVUnknown::get(getCastedVersionOf(GEP->getOperand(0)));
Nate Begemane68bcd12005-07-30 00:15:07 +0000262
263 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnereaf24722005-08-04 17:40:30 +0000264
265 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
Nate Begemane68bcd12005-07-30 00:15:07 +0000266 // If this is a use of a recurrence that we can analyze, and it comes before
267 // Op does in the GEP operand list, we will handle this when we process this
268 // operand.
269 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
270 const StructLayout *SL = TD->getStructLayout(STy);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000271 unsigned Idx = cast<ConstantInt>(GEP->getOperand(i))->getZExtValue();
Nate Begemane68bcd12005-07-30 00:15:07 +0000272 uint64_t Offset = SL->MemberOffsets[Idx];
Chris Lattnereaf24722005-08-04 17:40:30 +0000273 GEPVal = SCEVAddExpr::get(GEPVal,
274 SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy));
Nate Begemane68bcd12005-07-30 00:15:07 +0000275 } else {
Chris Lattneracc42c42005-08-04 19:08:16 +0000276 Value *OpVal = getCastedVersionOf(GEP->getOperand(i));
277 SCEVHandle Idx = SE->getSCEV(OpVal);
278
Chris Lattnereaf24722005-08-04 17:40:30 +0000279 uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
280 if (TypeSize != 1)
281 Idx = SCEVMulExpr::get(Idx,
Reid Spencere0fc4df2006-10-20 07:07:24 +0000282 SCEVConstant::get(ConstantInt::get(UIntPtrTy,
Chris Lattnereaf24722005-08-04 17:40:30 +0000283 TypeSize)));
284 GEPVal = SCEVAddExpr::get(GEPVal, Idx);
Nate Begemane68bcd12005-07-30 00:15:07 +0000285 }
286 }
287
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000288 SE->setSCEV(GEP, GEPVal);
Chris Lattnereaf24722005-08-04 17:40:30 +0000289 return GEPVal;
Nate Begemane68bcd12005-07-30 00:15:07 +0000290}
291
Chris Lattneracc42c42005-08-04 19:08:16 +0000292/// getSCEVStartAndStride - Compute the start and stride of this expression,
293/// returning false if the expression is not a start/stride pair, or true if it
294/// is. The stride must be a loop invariant expression, but the start may be
295/// a mix of loop invariant and loop variant expressions.
296static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
Chris Lattneredff91a2005-08-10 00:45:21 +0000297 SCEVHandle &Start, SCEVHandle &Stride) {
Chris Lattneracc42c42005-08-04 19:08:16 +0000298 SCEVHandle TheAddRec = Start; // Initialize to zero.
299
300 // If the outer level is an AddExpr, the operands are all start values except
301 // for a nested AddRecExpr.
302 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
303 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
304 if (SCEVAddRecExpr *AddRec =
305 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
306 if (AddRec->getLoop() == L)
307 TheAddRec = SCEVAddExpr::get(AddRec, TheAddRec);
308 else
309 return false; // Nested IV of some sort?
310 } else {
311 Start = SCEVAddExpr::get(Start, AE->getOperand(i));
312 }
313
Reid Spencerde46e482006-11-02 20:25:50 +0000314 } else if (isa<SCEVAddRecExpr>(SH)) {
Chris Lattneracc42c42005-08-04 19:08:16 +0000315 TheAddRec = SH;
316 } else {
317 return false; // not analyzable.
318 }
319
320 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
321 if (!AddRec || AddRec->getLoop() != L) return false;
322
323 // FIXME: Generalize to non-affine IV's.
324 if (!AddRec->isAffine()) return false;
325
326 Start = SCEVAddExpr::get(Start, AddRec->getOperand(0));
327
Chris Lattneracc42c42005-08-04 19:08:16 +0000328 if (!isa<SCEVConstant>(AddRec->getOperand(1)))
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000329 DOUT << "[" << L->getHeader()->getName()
330 << "] Variable stride: " << *AddRec << "\n";
Chris Lattneracc42c42005-08-04 19:08:16 +0000331
Chris Lattneredff91a2005-08-10 00:45:21 +0000332 Stride = AddRec->getOperand(1);
333 // Check that all constant strides are the unsigned type, we don't want to
334 // have two IV's one of signed stride 4 and one of unsigned stride 4 to not be
335 // merged.
336 assert((!isa<SCEVConstant>(Stride) || Stride->getType()->isUnsigned()) &&
Chris Lattneracc42c42005-08-04 19:08:16 +0000337 "Constants should be canonicalized to unsigned!");
Chris Lattneredff91a2005-08-10 00:45:21 +0000338
Chris Lattneracc42c42005-08-04 19:08:16 +0000339 return true;
340}
341
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000342/// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
343/// and now we need to decide whether the user should use the preinc or post-inc
344/// value. If this user should use the post-inc version of the IV, return true.
345///
346/// Choosing wrong here can break dominance properties (if we choose to use the
347/// post-inc value when we cannot) or it can end up adding extra live-ranges to
348/// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
349/// should use the post-inc value).
350static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
Chris Lattnercb367102006-01-11 05:10:20 +0000351 Loop *L, ETForest *EF, Pass *P) {
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000352 // If the user is in the loop, use the preinc value.
353 if (L->contains(User->getParent())) return false;
354
Chris Lattnerf07a5872005-10-03 02:50:05 +0000355 BasicBlock *LatchBlock = L->getLoopLatch();
356
357 // Ok, the user is outside of the loop. If it is dominated by the latch
358 // block, use the post-inc value.
Chris Lattnercb367102006-01-11 05:10:20 +0000359 if (EF->dominates(LatchBlock, User->getParent()))
Chris Lattnerf07a5872005-10-03 02:50:05 +0000360 return true;
361
362 // There is one case we have to be careful of: PHI nodes. These little guys
363 // can live in blocks that do not dominate the latch block, but (since their
364 // uses occur in the predecessor block, not the block the PHI lives in) should
365 // still use the post-inc value. Check for this case now.
366 PHINode *PN = dyn_cast<PHINode>(User);
367 if (!PN) return false; // not a phi, not dominated by latch block.
368
369 // Look at all of the uses of IV by the PHI node. If any use corresponds to
370 // a block that is not dominated by the latch block, give up and use the
371 // preincremented value.
372 unsigned NumUses = 0;
373 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
374 if (PN->getIncomingValue(i) == IV) {
375 ++NumUses;
Chris Lattnercb367102006-01-11 05:10:20 +0000376 if (!EF->dominates(LatchBlock, PN->getIncomingBlock(i)))
Chris Lattnerf07a5872005-10-03 02:50:05 +0000377 return false;
378 }
379
380 // Okay, all uses of IV by PN are in predecessor blocks that really are
381 // dominated by the latch block. Split the critical edges and use the
382 // post-incremented value.
383 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
384 if (PN->getIncomingValue(i) == IV) {
Chris Lattnera6eb7e02006-10-28 06:45:33 +0000385 SplitCriticalEdge(PN->getIncomingBlock(i), PN->getParent(), P,
386 true);
Chris Lattner5191c652006-10-28 00:59:20 +0000387 // Splitting the critical edge can reduce the number of entries in this
388 // PHI.
389 e = PN->getNumIncomingValues();
Chris Lattnerf07a5872005-10-03 02:50:05 +0000390 if (--NumUses == 0) break;
391 }
392
393 return true;
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000394}
395
396
397
Nate Begemane68bcd12005-07-30 00:15:07 +0000398/// AddUsersIfInteresting - Inspect the specified instruction. If it is a
399/// reducible SCEV, recursively add its users to the IVUsesByStride set and
400/// return true. Otherwise, return false.
Chris Lattnereaf24722005-08-04 17:40:30 +0000401bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
402 std::set<Instruction*> &Processed) {
Chris Lattner5df0e362005-10-21 05:45:41 +0000403 if (!I->getType()->isInteger() && !isa<PointerType>(I->getType()))
404 return false; // Void and FP expressions cannot be reduced.
Chris Lattnereaf24722005-08-04 17:40:30 +0000405 if (!Processed.insert(I).second)
406 return true; // Instruction already handled.
407
Chris Lattneracc42c42005-08-04 19:08:16 +0000408 // Get the symbolic expression for this instruction.
Chris Lattnereaf24722005-08-04 17:40:30 +0000409 SCEVHandle ISE = GetExpressionSCEV(I, L);
Chris Lattneracc42c42005-08-04 19:08:16 +0000410 if (isa<SCEVCouldNotCompute>(ISE)) return false;
Chris Lattnereaf24722005-08-04 17:40:30 +0000411
Chris Lattneracc42c42005-08-04 19:08:16 +0000412 // Get the start and stride for this expression.
413 SCEVHandle Start = SCEVUnknown::getIntegerSCEV(0, ISE->getType());
Chris Lattneredff91a2005-08-10 00:45:21 +0000414 SCEVHandle Stride = Start;
Chris Lattneracc42c42005-08-04 19:08:16 +0000415 if (!getSCEVStartAndStride(ISE, L, Start, Stride))
416 return false; // Non-reducible symbolic expression, bail out.
417
Nate Begemane68bcd12005-07-30 00:15:07 +0000418 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){
419 Instruction *User = cast<Instruction>(*UI);
420
421 // Do not infinitely recurse on PHI nodes.
Chris Lattnerfd018c82005-09-13 02:09:55 +0000422 if (isa<PHINode>(User) && Processed.count(User))
Nate Begemane68bcd12005-07-30 00:15:07 +0000423 continue;
424
425 // If this is an instruction defined in a nested loop, or outside this loop,
Chris Lattnera0102fb2005-08-04 00:14:11 +0000426 // don't recurse into it.
Chris Lattneracc42c42005-08-04 19:08:16 +0000427 bool AddUserToIVUsers = false;
Chris Lattnera0102fb2005-08-04 00:14:11 +0000428 if (LI->getLoopFor(User->getParent()) != L) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000429 DOUT << "FOUND USER in other loop: " << *User
430 << " OF SCEV: " << *ISE << "\n";
Chris Lattneracc42c42005-08-04 19:08:16 +0000431 AddUserToIVUsers = true;
Chris Lattnereaf24722005-08-04 17:40:30 +0000432 } else if (!AddUsersIfInteresting(User, L, Processed)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000433 DOUT << "FOUND USER: " << *User
434 << " OF SCEV: " << *ISE << "\n";
Chris Lattneracc42c42005-08-04 19:08:16 +0000435 AddUserToIVUsers = true;
436 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000437
Chris Lattneracc42c42005-08-04 19:08:16 +0000438 if (AddUserToIVUsers) {
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000439 IVUsersOfOneStride &StrideUses = IVUsesByStride[Stride];
440 if (StrideUses.Users.empty()) // First occurance of this stride?
441 StrideOrder.push_back(Stride);
442
Chris Lattner65107492005-08-04 00:40:47 +0000443 // Okay, we found a user that we cannot reduce. Analyze the instruction
Chris Lattnera6764832005-09-12 06:04:47 +0000444 // and decide what to do with it. If we are a use inside of the loop, use
445 // the value before incrementation, otherwise use it after incrementation.
Chris Lattnercb367102006-01-11 05:10:20 +0000446 if (IVUseShouldUsePostIncValue(User, I, L, EF, this)) {
Chris Lattnera6764832005-09-12 06:04:47 +0000447 // The value used will be incremented by the stride more than we are
448 // expecting, so subtract this off.
449 SCEVHandle NewStart = SCEV::getMinusSCEV(Start, Stride);
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000450 StrideUses.addUser(NewStart, User, I);
451 StrideUses.Users.back().isUseOfPostIncrementedValue = true;
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000452 DOUT << " USING POSTINC SCEV, START=" << *NewStart<< "\n";
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000453 } else {
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000454 StrideUses.addUser(Start, User, I);
Chris Lattnera6764832005-09-12 06:04:47 +0000455 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000456 }
457 }
458 return true;
459}
460
461namespace {
462 /// BasedUser - For a particular base value, keep information about how we've
463 /// partitioned the expression so far.
464 struct BasedUser {
Chris Lattner37c24cc2005-08-08 22:56:21 +0000465 /// Base - The Base value for the PHI node that needs to be inserted for
466 /// this use. As the use is processed, information gets moved from this
467 /// field to the Imm field (below). BasedUser values are sorted by this
468 /// field.
469 SCEVHandle Base;
470
Nate Begemane68bcd12005-07-30 00:15:07 +0000471 /// Inst - The instruction using the induction variable.
472 Instruction *Inst;
473
Chris Lattner430d0022005-08-03 22:21:05 +0000474 /// OperandValToReplace - The operand value of Inst to replace with the
475 /// EmittedBase.
476 Value *OperandValToReplace;
Nate Begemane68bcd12005-07-30 00:15:07 +0000477
478 /// Imm - The immediate value that should be added to the base immediately
479 /// before Inst, because it will be folded into the imm field of the
480 /// instruction.
481 SCEVHandle Imm;
482
483 /// EmittedBase - The actual value* to use for the base value of this
484 /// operation. This is null if we should just use zero so far.
485 Value *EmittedBase;
486
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000487 // isUseOfPostIncrementedValue - True if this should use the
488 // post-incremented version of this IV, not the preincremented version.
489 // This can only be set in special cases, such as the terminating setcc
Chris Lattnera6764832005-09-12 06:04:47 +0000490 // instruction for a loop and uses outside the loop that are dominated by
491 // the loop.
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000492 bool isUseOfPostIncrementedValue;
Chris Lattner37c24cc2005-08-08 22:56:21 +0000493
494 BasedUser(IVStrideUse &IVSU)
495 : Base(IVSU.Offset), Inst(IVSU.User),
496 OperandValToReplace(IVSU.OperandValToReplace),
497 Imm(SCEVUnknown::getIntegerSCEV(0, Base->getType())), EmittedBase(0),
498 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
Nate Begemane68bcd12005-07-30 00:15:07 +0000499
Chris Lattnera6d7c352005-08-04 20:03:32 +0000500 // Once we rewrite the code to insert the new IVs we want, update the
501 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
502 // to it.
Chris Lattnera091ff12005-08-09 00:18:09 +0000503 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattner8447b492005-08-12 22:22:17 +0000504 SCEVExpander &Rewriter, Loop *L,
505 Pass *P);
Chris Lattner2959f002006-02-04 07:36:50 +0000506
507 Value *InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
508 SCEVExpander &Rewriter,
509 Instruction *IP, Loop *L);
Nate Begemane68bcd12005-07-30 00:15:07 +0000510 void dump() const;
511 };
512}
513
514void BasedUser::dump() const {
Bill Wendlingf3baad32006-12-07 01:30:32 +0000515 cerr << " Base=" << *Base;
516 cerr << " Imm=" << *Imm;
Nate Begemane68bcd12005-07-30 00:15:07 +0000517 if (EmittedBase)
Bill Wendlingf3baad32006-12-07 01:30:32 +0000518 cerr << " EB=" << *EmittedBase;
Nate Begemane68bcd12005-07-30 00:15:07 +0000519
Bill Wendlingf3baad32006-12-07 01:30:32 +0000520 cerr << " Inst: " << *Inst;
Nate Begemane68bcd12005-07-30 00:15:07 +0000521}
522
Chris Lattner2959f002006-02-04 07:36:50 +0000523Value *BasedUser::InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
524 SCEVExpander &Rewriter,
525 Instruction *IP, Loop *L) {
526 // Figure out where we *really* want to insert this code. In particular, if
527 // the user is inside of a loop that is nested inside of L, we really don't
528 // want to insert this expression before the user, we'd rather pull it out as
529 // many loops as possible.
530 LoopInfo &LI = Rewriter.getLoopInfo();
531 Instruction *BaseInsertPt = IP;
532
533 // Figure out the most-nested loop that IP is in.
534 Loop *InsertLoop = LI.getLoopFor(IP->getParent());
535
536 // If InsertLoop is not L, and InsertLoop is nested inside of L, figure out
537 // the preheader of the outer-most loop where NewBase is not loop invariant.
538 while (InsertLoop && NewBase->isLoopInvariant(InsertLoop)) {
539 BaseInsertPt = InsertLoop->getLoopPreheader()->getTerminator();
540 InsertLoop = InsertLoop->getParentLoop();
541 }
542
543 // If there is no immediate value, skip the next part.
544 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Imm))
545 if (SC->getValue()->isNullValue())
546 return Rewriter.expandCodeFor(NewBase, BaseInsertPt,
547 OperandValToReplace->getType());
548
549 Value *Base = Rewriter.expandCodeFor(NewBase, BaseInsertPt);
550
551 // Always emit the immediate (if non-zero) into the same block as the user.
552 SCEVHandle NewValSCEV = SCEVAddExpr::get(SCEVUnknown::get(Base), Imm);
553 return Rewriter.expandCodeFor(NewValSCEV, IP,
554 OperandValToReplace->getType());
555}
556
557
Chris Lattnera6d7c352005-08-04 20:03:32 +0000558// Once we rewrite the code to insert the new IVs we want, update the
559// operands of Inst to use the new expression 'NewBase', with 'Imm' added
560// to it.
Chris Lattnera091ff12005-08-09 00:18:09 +0000561void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattner4fec86d2005-08-12 22:06:11 +0000562 SCEVExpander &Rewriter,
Chris Lattner8447b492005-08-12 22:22:17 +0000563 Loop *L, Pass *P) {
Chris Lattnera6d7c352005-08-04 20:03:32 +0000564 if (!isa<PHINode>(Inst)) {
Chris Lattner2959f002006-02-04 07:36:50 +0000565 Value *NewVal = InsertCodeForBaseAtPosition(NewBase, Rewriter, Inst, L);
Chris Lattnera6d7c352005-08-04 20:03:32 +0000566 // Replace the use of the operand Value with the new Phi we just created.
567 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000568 DOUT << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst;
Chris Lattnera6d7c352005-08-04 20:03:32 +0000569 return;
570 }
571
572 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000573 // expression into each operand block that uses it. Note that PHI nodes can
574 // have multiple entries for the same predecessor. We use a map to make sure
575 // that a PHI node only has a single Value* for each predecessor (which also
576 // prevents us from inserting duplicate code in some blocks).
577 std::map<BasicBlock*, Value*> InsertedCode;
Chris Lattnera6d7c352005-08-04 20:03:32 +0000578 PHINode *PN = cast<PHINode>(Inst);
579 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
580 if (PN->getIncomingValue(i) == OperandValToReplace) {
Chris Lattner4fec86d2005-08-12 22:06:11 +0000581 // If this is a critical edge, split the edge so that we do not insert the
Chris Lattnerfd018c82005-09-13 02:09:55 +0000582 // code on all predecessor/successor paths. We do this unless this is the
583 // canonical backedge for this loop, as this can make some inserted code
584 // be in an illegal position.
Chris Lattner8fcce172005-10-03 00:31:52 +0000585 BasicBlock *PHIPred = PN->getIncomingBlock(i);
586 if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
587 (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
Chris Lattner8fcce172005-10-03 00:31:52 +0000588
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000589 // First step, split the critical edge.
Chris Lattnera6eb7e02006-10-28 06:45:33 +0000590 SplitCriticalEdge(PHIPred, PN->getParent(), P, true);
Chris Lattner8447b492005-08-12 22:22:17 +0000591
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000592 // Next step: move the basic block. In particular, if the PHI node
593 // is outside of the loop, and PredTI is in the loop, we want to
594 // move the block to be immediately before the PHI block, not
595 // immediately after PredTI.
Chris Lattner8fcce172005-10-03 00:31:52 +0000596 if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000597 BasicBlock *NewBB = PN->getIncomingBlock(i);
598 NewBB->moveBefore(PN->getParent());
Chris Lattner4fec86d2005-08-12 22:06:11 +0000599 }
Chris Lattner5191c652006-10-28 00:59:20 +0000600
601 // Splitting the edge can reduce the number of PHI entries we have.
602 e = PN->getNumIncomingValues();
Chris Lattner4fec86d2005-08-12 22:06:11 +0000603 }
Chris Lattnera6d7c352005-08-04 20:03:32 +0000604
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000605 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
606 if (!Code) {
607 // Insert the code into the end of the predecessor block.
Chris Lattner2959f002006-02-04 07:36:50 +0000608 Instruction *InsertPt = PN->getIncomingBlock(i)->getTerminator();
609 Code = InsertCodeForBaseAtPosition(NewBase, Rewriter, InsertPt, L);
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000610 }
Chris Lattnera6d7c352005-08-04 20:03:32 +0000611
612 // Replace the use of the operand Value with the new Phi we just created.
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000613 PN->setIncomingValue(i, Code);
Chris Lattnera6d7c352005-08-04 20:03:32 +0000614 Rewriter.clear();
615 }
616 }
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000617 DOUT << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst;
Chris Lattnera6d7c352005-08-04 20:03:32 +0000618}
619
620
Nate Begemane68bcd12005-07-30 00:15:07 +0000621/// isTargetConstant - Return true if the following can be referenced by the
622/// immediate field of a target instruction.
Evan Chengc567c4e2006-03-13 23:14:23 +0000623static bool isTargetConstant(const SCEVHandle &V, const TargetLowering *TLI) {
Chris Lattner14203e82005-08-08 06:25:50 +0000624 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
Chris Lattner07720072005-12-05 18:23:57 +0000625 int64_t V = SC->getValue()->getSExtValue();
Evan Chengc567c4e2006-03-13 23:14:23 +0000626 if (TLI)
627 return TLI->isLegalAddressImmediate(V);
628 else
629 // Defaults to PPC. PPC allows a sign-extended 16-bit immediate field.
630 return (V > -(1 << 16) && V < (1 << 16)-1);
Chris Lattner14203e82005-08-08 06:25:50 +0000631 }
Jeff Cohen546fd592005-07-30 18:33:25 +0000632
Nate Begemane68bcd12005-07-30 00:15:07 +0000633 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
634 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000635 if (CE->getOpcode() == Instruction::PtrToInt) {
Evan Chengc567c4e2006-03-13 23:14:23 +0000636 Constant *Op0 = CE->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000637 if (isa<GlobalValue>(Op0) && TLI &&
Evan Chengc567c4e2006-03-13 23:14:23 +0000638 TLI->isLegalAddressImmediate(cast<GlobalValue>(Op0)))
Nate Begemane68bcd12005-07-30 00:15:07 +0000639 return true;
Evan Chengc567c4e2006-03-13 23:14:23 +0000640 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000641 return false;
642}
643
Chris Lattner37ed8952005-08-08 22:32:34 +0000644/// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
645/// loop varying to the Imm operand.
646static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
647 Loop *L) {
648 if (Val->isLoopInvariant(L)) return; // Nothing to do.
649
650 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
651 std::vector<SCEVHandle> NewOps;
652 NewOps.reserve(SAE->getNumOperands());
653
654 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
655 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
656 // If this is a loop-variant expression, it must stay in the immediate
657 // field of the expression.
658 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
659 } else {
660 NewOps.push_back(SAE->getOperand(i));
661 }
662
663 if (NewOps.empty())
664 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
665 else
666 Val = SCEVAddExpr::get(NewOps);
667 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
668 // Try to pull immediates out of the start value of nested addrec's.
669 SCEVHandle Start = SARE->getStart();
670 MoveLoopVariantsToImediateField(Start, Imm, L);
671
672 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
673 Ops[0] = Start;
674 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
675 } else {
676 // Otherwise, all of Val is variant, move the whole thing over.
677 Imm = SCEVAddExpr::get(Imm, Val);
678 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
679 }
680}
681
682
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000683/// MoveImmediateValues - Look at Val, and pull out any additions of constants
Nate Begemane68bcd12005-07-30 00:15:07 +0000684/// that can fit into the immediate field of instructions in the target.
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000685/// Accumulate these immediate values into the Imm value.
Evan Chengc567c4e2006-03-13 23:14:23 +0000686static void MoveImmediateValues(const TargetLowering *TLI,
687 SCEVHandle &Val, SCEVHandle &Imm,
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000688 bool isAddress, Loop *L) {
Chris Lattnerfc624702005-08-03 23:44:42 +0000689 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000690 std::vector<SCEVHandle> NewOps;
691 NewOps.reserve(SAE->getNumOperands());
692
Chris Lattner2959f002006-02-04 07:36:50 +0000693 for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
694 SCEVHandle NewOp = SAE->getOperand(i);
Evan Chengc567c4e2006-03-13 23:14:23 +0000695 MoveImmediateValues(TLI, NewOp, Imm, isAddress, L);
Chris Lattner2959f002006-02-04 07:36:50 +0000696
697 if (!NewOp->isLoopInvariant(L)) {
Chris Lattneracc42c42005-08-04 19:08:16 +0000698 // If this is a loop-variant expression, it must stay in the immediate
699 // field of the expression.
Chris Lattner2959f002006-02-04 07:36:50 +0000700 Imm = SCEVAddExpr::get(Imm, NewOp);
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000701 } else {
Chris Lattner2959f002006-02-04 07:36:50 +0000702 NewOps.push_back(NewOp);
Nate Begemane68bcd12005-07-30 00:15:07 +0000703 }
Chris Lattner2959f002006-02-04 07:36:50 +0000704 }
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000705
706 if (NewOps.empty())
707 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
708 else
709 Val = SCEVAddExpr::get(NewOps);
710 return;
Chris Lattnerfc624702005-08-03 23:44:42 +0000711 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
712 // Try to pull immediates out of the start value of nested addrec's.
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000713 SCEVHandle Start = SARE->getStart();
Evan Chengc567c4e2006-03-13 23:14:23 +0000714 MoveImmediateValues(TLI, Start, Imm, isAddress, L);
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000715
716 if (Start != SARE->getStart()) {
717 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
718 Ops[0] = Start;
719 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
720 }
721 return;
Chris Lattner2959f002006-02-04 07:36:50 +0000722 } else if (SCEVMulExpr *SME = dyn_cast<SCEVMulExpr>(Val)) {
723 // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
Evan Chengc567c4e2006-03-13 23:14:23 +0000724 if (isAddress && isTargetConstant(SME->getOperand(0), TLI) &&
Chris Lattner2959f002006-02-04 07:36:50 +0000725 SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
726
727 SCEVHandle SubImm = SCEVUnknown::getIntegerSCEV(0, Val->getType());
728 SCEVHandle NewOp = SME->getOperand(1);
Evan Chengc567c4e2006-03-13 23:14:23 +0000729 MoveImmediateValues(TLI, NewOp, SubImm, isAddress, L);
Chris Lattner2959f002006-02-04 07:36:50 +0000730
731 // If we extracted something out of the subexpressions, see if we can
732 // simplify this!
733 if (NewOp != SME->getOperand(1)) {
734 // Scale SubImm up by "8". If the result is a target constant, we are
735 // good.
736 SubImm = SCEVMulExpr::get(SubImm, SME->getOperand(0));
Evan Chengc567c4e2006-03-13 23:14:23 +0000737 if (isTargetConstant(SubImm, TLI)) {
Chris Lattner2959f002006-02-04 07:36:50 +0000738 // Accumulate the immediate.
739 Imm = SCEVAddExpr::get(Imm, SubImm);
740
741 // Update what is left of 'Val'.
742 Val = SCEVMulExpr::get(SME->getOperand(0), NewOp);
743 return;
744 }
745 }
746 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000747 }
748
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000749 // Loop-variant expressions must stay in the immediate field of the
750 // expression.
Evan Chengc567c4e2006-03-13 23:14:23 +0000751 if ((isAddress && isTargetConstant(Val, TLI)) ||
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000752 !Val->isLoopInvariant(L)) {
753 Imm = SCEVAddExpr::get(Imm, Val);
754 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
755 return;
Chris Lattner0f7c0fa2005-08-04 19:26:19 +0000756 }
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000757
758 // Otherwise, no immediates to move.
Nate Begemane68bcd12005-07-30 00:15:07 +0000759}
760
Chris Lattner5949d492005-08-13 07:27:18 +0000761
Chris Lattner3ff62012006-08-03 06:34:50 +0000762/// SeparateSubExprs - Decompose Expr into all of the subexpressions that are
763/// added together. This is used to reassociate common addition subexprs
764/// together for maximal sharing when rewriting bases.
Chris Lattner5949d492005-08-13 07:27:18 +0000765static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
766 SCEVHandle Expr) {
767 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
768 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
769 SeparateSubExprs(SubExprs, AE->getOperand(j));
770 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
771 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Expr->getType());
772 if (SARE->getOperand(0) == Zero) {
773 SubExprs.push_back(Expr);
774 } else {
775 // Compute the addrec with zero as its base.
776 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
777 Ops[0] = Zero; // Start with zero base.
778 SubExprs.push_back(SCEVAddRecExpr::get(Ops, SARE->getLoop()));
779
780
781 SeparateSubExprs(SubExprs, SARE->getOperand(0));
782 }
783 } else if (!isa<SCEVConstant>(Expr) ||
784 !cast<SCEVConstant>(Expr)->getValue()->isNullValue()) {
785 // Do not add zero.
786 SubExprs.push_back(Expr);
787 }
788}
789
790
Chris Lattnera091ff12005-08-09 00:18:09 +0000791/// RemoveCommonExpressionsFromUseBases - Look through all of the uses in Bases,
792/// removing any common subexpressions from it. Anything truly common is
793/// removed, accumulated, and returned. This looks for things like (a+b+c) and
794/// (a+c+d) -> (a+c). The common expression is *removed* from the Bases.
795static SCEVHandle
796RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses) {
797 unsigned NumUses = Uses.size();
798
799 // Only one use? Use its base, regardless of what it is!
800 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Uses[0].Base->getType());
801 SCEVHandle Result = Zero;
802 if (NumUses == 1) {
803 std::swap(Result, Uses[0].Base);
804 return Result;
805 }
806
807 // To find common subexpressions, count how many of Uses use each expression.
808 // If any subexpressions are used Uses.size() times, they are common.
809 std::map<SCEVHandle, unsigned> SubExpressionUseCounts;
810
Chris Lattner192cd182005-10-11 18:41:04 +0000811 // UniqueSubExprs - Keep track of all of the subexpressions we see in the
812 // order we see them.
813 std::vector<SCEVHandle> UniqueSubExprs;
814
Chris Lattner5949d492005-08-13 07:27:18 +0000815 std::vector<SCEVHandle> SubExprs;
816 for (unsigned i = 0; i != NumUses; ++i) {
817 // If the base is zero (which is common), return zero now, there are no
818 // CSEs we can find.
819 if (Uses[i].Base == Zero) return Zero;
820
821 // Split the expression into subexprs.
822 SeparateSubExprs(SubExprs, Uses[i].Base);
823 // Add one to SubExpressionUseCounts for each subexpr present.
824 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
Chris Lattner192cd182005-10-11 18:41:04 +0000825 if (++SubExpressionUseCounts[SubExprs[j]] == 1)
826 UniqueSubExprs.push_back(SubExprs[j]);
Chris Lattner5949d492005-08-13 07:27:18 +0000827 SubExprs.clear();
828 }
829
Chris Lattner192cd182005-10-11 18:41:04 +0000830 // Now that we know how many times each is used, build Result. Iterate over
831 // UniqueSubexprs so that we have a stable ordering.
832 for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
833 std::map<SCEVHandle, unsigned>::iterator I =
834 SubExpressionUseCounts.find(UniqueSubExprs[i]);
835 assert(I != SubExpressionUseCounts.end() && "Entry not found?");
Chris Lattnera091ff12005-08-09 00:18:09 +0000836 if (I->second == NumUses) { // Found CSE!
837 Result = SCEVAddExpr::get(Result, I->first);
Chris Lattnera091ff12005-08-09 00:18:09 +0000838 } else {
839 // Remove non-cse's from SubExpressionUseCounts.
Chris Lattner192cd182005-10-11 18:41:04 +0000840 SubExpressionUseCounts.erase(I);
Chris Lattnera091ff12005-08-09 00:18:09 +0000841 }
Chris Lattner192cd182005-10-11 18:41:04 +0000842 }
Chris Lattnera091ff12005-08-09 00:18:09 +0000843
844 // If we found no CSE's, return now.
845 if (Result == Zero) return Result;
846
847 // Otherwise, remove all of the CSE's we found from each of the base values.
Chris Lattner5949d492005-08-13 07:27:18 +0000848 for (unsigned i = 0; i != NumUses; ++i) {
849 // Split the expression into subexprs.
850 SeparateSubExprs(SubExprs, Uses[i].Base);
851
852 // Remove any common subexpressions.
853 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
854 if (SubExpressionUseCounts.count(SubExprs[j])) {
855 SubExprs.erase(SubExprs.begin()+j);
856 --j; --e;
857 }
858
859 // Finally, the non-shared expressions together.
860 if (SubExprs.empty())
Chris Lattnera091ff12005-08-09 00:18:09 +0000861 Uses[i].Base = Zero;
Chris Lattner5949d492005-08-13 07:27:18 +0000862 else
863 Uses[i].Base = SCEVAddExpr::get(SubExprs);
Chris Lattner47d3ec32005-08-13 07:42:01 +0000864 SubExprs.clear();
Chris Lattner5949d492005-08-13 07:27:18 +0000865 }
Chris Lattnera091ff12005-08-09 00:18:09 +0000866
867 return Result;
868}
869
Evan Cheng3df447d2006-03-16 21:53:05 +0000870/// isZero - returns true if the scalar evolution expression is zero.
871///
872static bool isZero(SCEVHandle &V) {
873 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V))
Reid Spencere0fc4df2006-10-20 07:07:24 +0000874 return SC->getValue()->getZExtValue() == 0;
Evan Cheng3df447d2006-03-16 21:53:05 +0000875 return false;
876}
877
Chris Lattnera091ff12005-08-09 00:18:09 +0000878
Evan Cheng45206982006-03-17 19:52:23 +0000879/// CheckForIVReuse - Returns the multiple if the stride is the multiple
880/// of a previous stride and it is a legal value for the target addressing
881/// mode scale component. This allows the users of this stride to be rewritten
Evan Chengc28282b2006-03-18 08:03:12 +0000882/// as prev iv * factor. It returns 0 if no reuse is possible.
Evan Cheng45206982006-03-17 19:52:23 +0000883unsigned LoopStrengthReduce::CheckForIVReuse(const SCEVHandle &Stride,
Evan Chenge9c68f52006-07-18 19:07:58 +0000884 IVExpr &IV, const Type *Ty) {
Evan Chengc28282b2006-03-18 08:03:12 +0000885 if (!TLI) return 0;
Evan Cheng45206982006-03-17 19:52:23 +0000886
887 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride)) {
Evan Chengc28282b2006-03-18 08:03:12 +0000888 int64_t SInt = SC->getValue()->getSExtValue();
889 if (SInt == 1) return 0;
Evan Cheng45206982006-03-17 19:52:23 +0000890
891 for (TargetLowering::legal_am_scale_iterator
892 I = TLI->legal_am_scale_begin(), E = TLI->legal_am_scale_end();
893 I != E; ++I) {
894 unsigned Scale = *I;
Reid Spencer13a1a7a2006-04-12 19:28:15 +0000895 if (unsigned(abs(SInt)) < Scale || (SInt % Scale) != 0)
Evan Cheng45206982006-03-17 19:52:23 +0000896 continue;
897 std::map<SCEVHandle, IVsOfOneStride>::iterator SI =
898 IVsByStride.find(SCEVUnknown::getIntegerSCEV(SInt/Scale, Type::UIntTy));
899 if (SI == IVsByStride.end())
900 continue;
901 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
902 IE = SI->second.IVs.end(); II != IE; ++II)
903 // FIXME: Only handle base == 0 for now.
Evan Chenge9c68f52006-07-18 19:07:58 +0000904 // Only reuse previous IV if it would not require a type conversion.
905 if (isZero(II->Base) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000906 II->Base->getType()->canLosslesslyBitCastTo(Ty)) {
Evan Cheng45206982006-03-17 19:52:23 +0000907 IV = *II;
908 return Scale;
909 }
910 }
911 }
912
Evan Chengc28282b2006-03-18 08:03:12 +0000913 return 0;
Evan Cheng45206982006-03-17 19:52:23 +0000914}
915
Chris Lattner3ff62012006-08-03 06:34:50 +0000916/// PartitionByIsUseOfPostIncrementedValue - Simple boolean predicate that
917/// returns true if Val's isUseOfPostIncrementedValue is true.
918static bool PartitionByIsUseOfPostIncrementedValue(const BasedUser &Val) {
919 return Val.isUseOfPostIncrementedValue;
920}
Evan Cheng45206982006-03-17 19:52:23 +0000921
Nate Begemane68bcd12005-07-30 00:15:07 +0000922/// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
923/// stride of IV. All of the users may have different starting values, and this
924/// may not be the only stride (we know it is if isOnlyStride is true).
Chris Lattneredff91a2005-08-10 00:45:21 +0000925void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
Chris Lattner430d0022005-08-03 22:21:05 +0000926 IVUsersOfOneStride &Uses,
927 Loop *L,
Nate Begemane68bcd12005-07-30 00:15:07 +0000928 bool isOnlyStride) {
929 // Transform our list of users and offsets to a bit more complex table. In
Chris Lattner37c24cc2005-08-08 22:56:21 +0000930 // this new vector, each 'BasedUser' contains 'Base' the base of the
931 // strided accessas well as the old information from Uses. We progressively
932 // move information from the Base field to the Imm field, until we eventually
933 // have the full access expression to rewrite the use.
934 std::vector<BasedUser> UsersToProcess;
Nate Begemane68bcd12005-07-30 00:15:07 +0000935 UsersToProcess.reserve(Uses.Users.size());
Chris Lattner37c24cc2005-08-08 22:56:21 +0000936 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
937 UsersToProcess.push_back(Uses.Users[i]);
938
939 // Move any loop invariant operands from the offset field to the immediate
940 // field of the use, so that we don't try to use something before it is
941 // computed.
942 MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
943 UsersToProcess.back().Imm, L);
944 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000945 "Base value is not loop invariant!");
Nate Begemane68bcd12005-07-30 00:15:07 +0000946 }
Evan Cheng45206982006-03-17 19:52:23 +0000947
Chris Lattnera091ff12005-08-09 00:18:09 +0000948 // We now have a whole bunch of uses of like-strided induction variables, but
949 // they might all have different bases. We want to emit one PHI node for this
950 // stride which we fold as many common expressions (between the IVs) into as
951 // possible. Start by identifying the common expressions in the base values
952 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
953 // "A+B"), emit it to the preheader, then remove the expression from the
954 // UsersToProcess base values.
Evan Cheng3df447d2006-03-16 21:53:05 +0000955 SCEVHandle CommonExprs =
956 RemoveCommonExpressionsFromUseBases(UsersToProcess);
Chris Lattnera091ff12005-08-09 00:18:09 +0000957
Evan Chenge9c68f52006-07-18 19:07:58 +0000958 // Check if it is possible to reuse a IV with stride that is factor of this
959 // stride. And the multiple is a number that can be encoded in the scale
960 // field of the target addressing mode.
961 PHINode *NewPHI = NULL;
962 Value *IncV = NULL;
963 IVExpr ReuseIV;
964 unsigned RewriteFactor = CheckForIVReuse(Stride, ReuseIV,
965 CommonExprs->getType());
966 if (RewriteFactor != 0) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000967 DOUT << "BASED ON IV of STRIDE " << *ReuseIV.Stride
968 << " and BASE " << *ReuseIV.Base << " :\n";
Evan Chenge9c68f52006-07-18 19:07:58 +0000969 NewPHI = ReuseIV.PHI;
970 IncV = ReuseIV.IncV;
971 }
972
Chris Lattner37ed8952005-08-08 22:32:34 +0000973 // Next, figure out what we can represent in the immediate fields of
974 // instructions. If we can represent anything there, move it to the imm
Chris Lattnera091ff12005-08-09 00:18:09 +0000975 // fields of the BasedUsers. We do this so that it increases the commonality
976 // of the remaining uses.
Chris Lattner37ed8952005-08-08 22:32:34 +0000977 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
Chris Lattner5cf983e2005-08-16 00:38:11 +0000978 // If the user is not in the current loop, this means it is using the exit
979 // value of the IV. Do not put anything in the base, make sure it's all in
980 // the immediate field to allow as much factoring as possible.
981 if (!L->contains(UsersToProcess[i].Inst->getParent())) {
Chris Lattnerea7dfd52005-08-17 21:22:41 +0000982 UsersToProcess[i].Imm = SCEVAddExpr::get(UsersToProcess[i].Imm,
983 UsersToProcess[i].Base);
984 UsersToProcess[i].Base =
985 SCEVUnknown::getIntegerSCEV(0, UsersToProcess[i].Base->getType());
Chris Lattner5cf983e2005-08-16 00:38:11 +0000986 } else {
987
988 // Addressing modes can be folded into loads and stores. Be careful that
989 // the store is through the expression, not of the expression though.
990 bool isAddress = isa<LoadInst>(UsersToProcess[i].Inst);
991 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
992 if (SI->getOperand(1) == UsersToProcess[i].OperandValToReplace)
993 isAddress = true;
994
Evan Chengc567c4e2006-03-13 23:14:23 +0000995 MoveImmediateValues(TLI, UsersToProcess[i].Base, UsersToProcess[i].Imm,
Chris Lattner5cf983e2005-08-16 00:38:11 +0000996 isAddress, L);
997 }
Chris Lattner37ed8952005-08-08 22:32:34 +0000998 }
Evan Cheng3df447d2006-03-16 21:53:05 +0000999
Chris Lattnera091ff12005-08-09 00:18:09 +00001000 // Now that we know what we need to do, insert the PHI node itself.
1001 //
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001002 DOUT << "INSERTING IV of STRIDE " << *Stride << " and BASE "
1003 << *CommonExprs << " :\n";
Evan Cheng3df447d2006-03-16 21:53:05 +00001004
Chris Lattnera091ff12005-08-09 00:18:09 +00001005 SCEVExpander Rewriter(*SE, *LI);
1006 SCEVExpander PreheaderRewriter(*SE, *LI);
Chris Lattner37ed8952005-08-08 22:32:34 +00001007
Chris Lattnera091ff12005-08-09 00:18:09 +00001008 BasicBlock *Preheader = L->getLoopPreheader();
1009 Instruction *PreInsertPt = Preheader->getTerminator();
1010 Instruction *PhiInsertBefore = L->getHeader()->begin();
Chris Lattner37ed8952005-08-08 22:32:34 +00001011
Chris Lattner8048b852005-09-12 17:11:27 +00001012 BasicBlock *LatchBlock = L->getLoopLatch();
Evan Cheng3df447d2006-03-16 21:53:05 +00001013
Chris Lattnera091ff12005-08-09 00:18:09 +00001014 const Type *ReplacedTy = CommonExprs->getType();
Evan Cheng45206982006-03-17 19:52:23 +00001015
1016 // Emit the initial base value into the loop preheader.
1017 Value *CommonBaseV
1018 = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt,
1019 ReplacedTy);
1020
Evan Chengc28282b2006-03-18 08:03:12 +00001021 if (RewriteFactor == 0) {
Evan Cheng3df447d2006-03-16 21:53:05 +00001022 // Create a new Phi for this base, and stick it in the loop header.
1023 NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
1024 ++NumInserted;
Chris Lattnera091ff12005-08-09 00:18:09 +00001025
Evan Cheng45206982006-03-17 19:52:23 +00001026 // Add common base to the new Phi node.
1027 NewPHI->addIncoming(CommonBaseV, Preheader);
1028
Evan Cheng3df447d2006-03-16 21:53:05 +00001029 // Insert the stride into the preheader.
1030 Value *StrideV = PreheaderRewriter.expandCodeFor(Stride, PreInsertPt,
1031 ReplacedTy);
1032 if (!isa<ConstantInt>(StrideV)) ++NumVariable;
Chris Lattneredff91a2005-08-10 00:45:21 +00001033
Evan Cheng3df447d2006-03-16 21:53:05 +00001034 // Emit the increment of the base value before the terminator of the loop
1035 // latch block, and add it to the Phi node.
1036 SCEVHandle IncExp = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
1037 SCEVUnknown::get(StrideV));
Chris Lattnera091ff12005-08-09 00:18:09 +00001038
Evan Cheng3df447d2006-03-16 21:53:05 +00001039 IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator(),
1040 ReplacedTy);
1041 IncV->setName(NewPHI->getName()+".inc");
1042 NewPHI->addIncoming(IncV, LatchBlock);
1043
Evan Cheng45206982006-03-17 19:52:23 +00001044 // Remember this in case a later stride is multiple of this.
Evan Chengc28282b2006-03-18 08:03:12 +00001045 IVsByStride[Stride].addIV(Stride, CommonExprs, NewPHI, IncV);
Evan Cheng45206982006-03-17 19:52:23 +00001046 } else {
1047 Constant *C = dyn_cast<Constant>(CommonBaseV);
1048 if (!C ||
1049 (!C->isNullValue() &&
1050 !isTargetConstant(SCEVUnknown::get(CommonBaseV), TLI)))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001051 // We want the common base emitted into the preheader! This is just
1052 // using cast as a copy so BitCast (no-op cast) is appropriate
1053 CommonBaseV = new BitCastInst(CommonBaseV, CommonBaseV->getType(),
1054 "commonbase", PreInsertPt);
Evan Cheng3df447d2006-03-16 21:53:05 +00001055 }
Chris Lattnera091ff12005-08-09 00:18:09 +00001056
Chris Lattner3ff62012006-08-03 06:34:50 +00001057 // We want to emit code for users inside the loop first. To do this, we
1058 // rearrange BasedUser so that the entries at the end have
1059 // isUseOfPostIncrementedValue = false, because we pop off the end of the
1060 // vector (so we handle them first).
1061 std::partition(UsersToProcess.begin(), UsersToProcess.end(),
1062 PartitionByIsUseOfPostIncrementedValue);
1063
1064 // Sort this by base, so that things with the same base are handled
1065 // together. By partitioning first and stable-sorting later, we are
1066 // guaranteed that within each base we will pop off users from within the
1067 // loop before users outside of the loop with a particular base.
1068 //
1069 // We would like to use stable_sort here, but we can't. The problem is that
1070 // SCEVHandle's don't have a deterministic ordering w.r.t to each other, so
1071 // we don't have anything to do a '<' comparison on. Because we think the
1072 // number of uses is small, do a horrible bubble sort which just relies on
1073 // ==.
1074 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1075 // Get a base value.
1076 SCEVHandle Base = UsersToProcess[i].Base;
1077
1078 // Compact everything with this base to be consequetive with this one.
1079 for (unsigned j = i+1; j != e; ++j) {
1080 if (UsersToProcess[j].Base == Base) {
1081 std::swap(UsersToProcess[i+1], UsersToProcess[j]);
1082 ++i;
1083 }
1084 }
1085 }
1086
1087 // Process all the users now. This outer loop handles all bases, the inner
1088 // loop handles all users of a particular base.
Nate Begemane68bcd12005-07-30 00:15:07 +00001089 while (!UsersToProcess.empty()) {
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001090 SCEVHandle Base = UsersToProcess.back().Base;
Chris Lattnerbb78c972005-08-03 23:30:08 +00001091
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001092 DOUT << " INSERTING code for BASE = " << *Base << ":\n";
Chris Lattnerbb78c972005-08-03 23:30:08 +00001093
Chris Lattnera091ff12005-08-09 00:18:09 +00001094 // Emit the code for Base into the preheader.
Chris Lattnerc70bbc02005-08-08 05:47:49 +00001095 Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt,
1096 ReplacedTy);
Chris Lattnera091ff12005-08-09 00:18:09 +00001097
1098 // If BaseV is a constant other than 0, make sure that it gets inserted into
1099 // the preheader, instead of being forward substituted into the uses. We do
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001100 // this by forcing a BitCast (noop cast) to be inserted into the preheader
1101 // in this case.
Chris Lattner3ff62012006-08-03 06:34:50 +00001102 if (Constant *C = dyn_cast<Constant>(BaseV)) {
Evan Chengc567c4e2006-03-13 23:14:23 +00001103 if (!C->isNullValue() && !isTargetConstant(Base, TLI)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001104 // We want this constant emitted into the preheader! This is just
1105 // using cast as a copy so BitCast (no-op cast) is appropriate
1106 BaseV = new BitCastInst(BaseV, BaseV->getType(), "preheaderinsert",
Chris Lattnera091ff12005-08-09 00:18:09 +00001107 PreInsertPt);
1108 }
Chris Lattner3ff62012006-08-03 06:34:50 +00001109 }
1110
Nate Begemane68bcd12005-07-30 00:15:07 +00001111 // Emit the code to add the immediate offset to the Phi value, just before
Chris Lattnerdb23c742005-08-03 22:51:21 +00001112 // the instructions that we identified as using this stride and base.
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001113 do {
Chris Lattner3ff62012006-08-03 06:34:50 +00001114 // FIXME: Use emitted users to emit other users.
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001115 BasedUser &User = UsersToProcess.back();
Jeff Cohen546fd592005-07-30 18:33:25 +00001116
Chris Lattnera091ff12005-08-09 00:18:09 +00001117 // If this instruction wants to use the post-incremented value, move it
1118 // after the post-inc and use its value instead of the PHI.
1119 Value *RewriteOp = NewPHI;
1120 if (User.isUseOfPostIncrementedValue) {
1121 RewriteOp = IncV;
Chris Lattnera6764832005-09-12 06:04:47 +00001122
1123 // If this user is in the loop, make sure it is the last thing in the
1124 // loop to ensure it is dominated by the increment.
1125 if (L->contains(User.Inst->getParent()))
1126 User.Inst->moveBefore(LatchBlock->getTerminator());
Chris Lattnera091ff12005-08-09 00:18:09 +00001127 }
Evan Cheng398f7022006-06-09 00:12:42 +00001128 if (RewriteOp->getType() != ReplacedTy)
1129 RewriteOp = SCEVExpander::InsertCastOfTo(RewriteOp, ReplacedTy);
1130
Chris Lattnera091ff12005-08-09 00:18:09 +00001131 SCEVHandle RewriteExpr = SCEVUnknown::get(RewriteOp);
1132
Chris Lattnerdb23c742005-08-03 22:51:21 +00001133 // Clear the SCEVExpander's expression map so that we are guaranteed
1134 // to have the code emitted where we expect it.
1135 Rewriter.clear();
Evan Cheng3df447d2006-03-16 21:53:05 +00001136
1137 // If we are reusing the iv, then it must be multiplied by a constant
1138 // factor take advantage of addressing mode scale component.
Evan Chengc28282b2006-03-18 08:03:12 +00001139 if (RewriteFactor != 0) {
Evan Cheng3df447d2006-03-16 21:53:05 +00001140 RewriteExpr =
1141 SCEVMulExpr::get(SCEVUnknown::getIntegerSCEV(RewriteFactor,
Evan Cheng45206982006-03-17 19:52:23 +00001142 RewriteExpr->getType()),
1143 RewriteExpr);
1144
1145 // The common base is emitted in the loop preheader. But since we
1146 // are reusing an IV, it has not been used to initialize the PHI node.
1147 // Add it to the expression used to rewrite the uses.
1148 if (!isa<ConstantInt>(CommonBaseV) ||
1149 !cast<ConstantInt>(CommonBaseV)->isNullValue())
1150 RewriteExpr = SCEVAddExpr::get(RewriteExpr,
1151 SCEVUnknown::get(CommonBaseV));
1152 }
Evan Cheng3df447d2006-03-16 21:53:05 +00001153
Chris Lattnera6d7c352005-08-04 20:03:32 +00001154 // Now that we know what we need to do, insert code before User for the
1155 // immediate and any loop-variant expressions.
Chris Lattnera091ff12005-08-09 00:18:09 +00001156 if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isNullValue())
1157 // Add BaseV to the PHI value if needed.
1158 RewriteExpr = SCEVAddExpr::get(RewriteExpr, SCEVUnknown::get(BaseV));
Evan Cheng3df447d2006-03-16 21:53:05 +00001159
Chris Lattner8447b492005-08-12 22:22:17 +00001160 User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter, L, this);
Jeff Cohen546fd592005-07-30 18:33:25 +00001161
Chris Lattnerdb23c742005-08-03 22:51:21 +00001162 // Mark old value we replaced as possibly dead, so that it is elminated
1163 // if we just replaced the last use of that value.
Chris Lattnera6d7c352005-08-04 20:03:32 +00001164 DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
Nate Begemane68bcd12005-07-30 00:15:07 +00001165
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001166 UsersToProcess.pop_back();
Chris Lattnerdb23c742005-08-03 22:51:21 +00001167 ++NumReduced;
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001168
Chris Lattner3ff62012006-08-03 06:34:50 +00001169 // If there are any more users to process with the same base, process them
1170 // now. We sorted by base above, so we just have to check the last elt.
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001171 } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
Nate Begemane68bcd12005-07-30 00:15:07 +00001172 // TODO: Next, find out which base index is the most common, pull it out.
1173 }
1174
1175 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1176 // different starting values, into different PHIs.
Nate Begemane68bcd12005-07-30 00:15:07 +00001177}
1178
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001179// OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
1180// uses in the loop, look to see if we can eliminate some, in favor of using
1181// common indvars for the different uses.
1182void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
1183 // TODO: implement optzns here.
1184
1185
1186
1187
1188 // Finally, get the terminating condition for the loop if possible. If we
1189 // can, we want to change it to use a post-incremented version of its
Chris Lattnerf365f5f2006-03-24 07:14:34 +00001190 // induction variable, to allow coalescing the live ranges for the IV into
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001191 // one register value.
1192 PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
1193 BasicBlock *Preheader = L->getLoopPreheader();
1194 BasicBlock *LatchBlock =
1195 SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
1196 BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
1197 if (!TermBr || TermBr->isUnconditional() ||
1198 !isa<SetCondInst>(TermBr->getCondition()))
1199 return;
1200 SetCondInst *Cond = cast<SetCondInst>(TermBr->getCondition());
1201
1202 // Search IVUsesByStride to find Cond's IVUse if there is one.
1203 IVStrideUse *CondUse = 0;
Chris Lattneredff91a2005-08-10 00:45:21 +00001204 const SCEVHandle *CondStride = 0;
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001205
Chris Lattnerb7a38942005-10-11 18:17:57 +00001206 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e && !CondUse;
1207 ++Stride) {
1208 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1209 IVUsesByStride.find(StrideOrder[Stride]);
1210 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1211
1212 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
1213 E = SI->second.Users.end(); UI != E; ++UI)
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001214 if (UI->User == Cond) {
1215 CondUse = &*UI;
Chris Lattnerb7a38942005-10-11 18:17:57 +00001216 CondStride = &SI->first;
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001217 // NOTE: we could handle setcc instructions with multiple uses here, but
1218 // InstCombine does it as well for simple uses, it's not clear that it
1219 // occurs enough in real life to handle.
1220 break;
1221 }
Chris Lattnerb7a38942005-10-11 18:17:57 +00001222 }
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001223 if (!CondUse) return; // setcc doesn't use the IV.
1224
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001225 // It's possible for the setcc instruction to be anywhere in the loop, and
1226 // possible for it to have multiple users. If it is not immediately before
1227 // the latch block branch, move it.
1228 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
1229 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
1230 Cond->moveBefore(TermBr);
1231 } else {
1232 // Otherwise, clone the terminating condition and insert into the loopend.
1233 Cond = cast<SetCondInst>(Cond->clone());
1234 Cond->setName(L->getHeader()->getName() + ".termcond");
1235 LatchBlock->getInstList().insert(TermBr, Cond);
1236
1237 // Clone the IVUse, as the old use still exists!
Chris Lattneredff91a2005-08-10 00:45:21 +00001238 IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001239 CondUse->OperandValToReplace);
Chris Lattneredff91a2005-08-10 00:45:21 +00001240 CondUse = &IVUsesByStride[*CondStride].Users.back();
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001241 }
1242 }
1243
1244 // If we get to here, we know that we can transform the setcc instruction to
Chris Lattnerf365f5f2006-03-24 07:14:34 +00001245 // use the post-incremented version of the IV, allowing us to coalesce the
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001246 // live ranges for the IV correctly.
Chris Lattneredff91a2005-08-10 00:45:21 +00001247 CondUse->Offset = SCEV::getMinusSCEV(CondUse->Offset, *CondStride);
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001248 CondUse->isUseOfPostIncrementedValue = true;
1249}
Nate Begemane68bcd12005-07-30 00:15:07 +00001250
Evan Chengf09f0eb2006-03-18 00:44:49 +00001251namespace {
1252 // Constant strides come first which in turns are sorted by their absolute
1253 // values. If absolute values are the same, then positive strides comes first.
1254 // e.g.
1255 // 4, -1, X, 1, 2 ==> 1, -1, 2, 4, X
1256 struct StrideCompare {
1257 bool operator()(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1258 SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS);
1259 SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
1260 if (LHSC && RHSC) {
1261 int64_t LV = LHSC->getValue()->getSExtValue();
1262 int64_t RV = RHSC->getValue()->getSExtValue();
1263 uint64_t ALV = (LV < 0) ? -LV : LV;
1264 uint64_t ARV = (RV < 0) ? -RV : RV;
1265 if (ALV == ARV)
1266 return LV > RV;
1267 else
1268 return ALV < ARV;
Chris Lattner7d80b4f2006-03-22 17:27:24 +00001269 }
1270 return (LHSC && !RHSC);
Evan Chengf09f0eb2006-03-18 00:44:49 +00001271 }
1272 };
1273}
1274
Nate Begemanb18121e2004-10-18 21:08:22 +00001275void LoopStrengthReduce::runOnLoop(Loop *L) {
1276 // First step, transform all loops nesting inside of this loop.
1277 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
1278 runOnLoop(*I);
1279
Nate Begemane68bcd12005-07-30 00:15:07 +00001280 // Next, find all uses of induction variables in this loop, and catagorize
1281 // them by stride. Start by finding all of the PHI nodes in the header for
1282 // this loop. If they are induction variables, inspect their uses.
Chris Lattnereaf24722005-08-04 17:40:30 +00001283 std::set<Instruction*> Processed; // Don't reprocess instructions.
Nate Begemane68bcd12005-07-30 00:15:07 +00001284 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
Chris Lattnereaf24722005-08-04 17:40:30 +00001285 AddUsersIfInteresting(I, L, Processed);
Nate Begemanb18121e2004-10-18 21:08:22 +00001286
Nate Begemane68bcd12005-07-30 00:15:07 +00001287 // If we have nothing to do, return.
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001288 if (IVUsesByStride.empty()) return;
1289
1290 // Optimize induction variables. Some indvar uses can be transformed to use
1291 // strides that will be needed for other purposes. A common example of this
1292 // is the exit test for the loop, which can often be rewritten to use the
1293 // computation of some other indvar to decide when to terminate the loop.
1294 OptimizeIndvars(L);
1295
Misha Brukmanb1c93172005-04-21 23:48:37 +00001296
Nate Begemane68bcd12005-07-30 00:15:07 +00001297 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
1298 // doing computation in byte values, promote to 32-bit values if safe.
1299
1300 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
1301 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
1302 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
1303 // to be careful that IV's are all the same type. Only works for intptr_t
1304 // indvars.
1305
1306 // If we only have one stride, we can more aggressively eliminate some things.
1307 bool HasOneStride = IVUsesByStride.size() == 1;
Evan Cheng3df447d2006-03-16 21:53:05 +00001308
1309#ifndef NDEBUG
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001310 DOUT << "\nLSR on ";
Evan Cheng3df447d2006-03-16 21:53:05 +00001311 DEBUG(L->dump());
1312#endif
1313
1314 // IVsByStride keeps IVs for one particular loop.
1315 IVsByStride.clear();
1316
Evan Chengf09f0eb2006-03-18 00:44:49 +00001317 // Sort the StrideOrder so we process larger strides first.
1318 std::stable_sort(StrideOrder.begin(), StrideOrder.end(), StrideCompare());
1319
Chris Lattnera091ff12005-08-09 00:18:09 +00001320 // Note: this processes each stride/type pair individually. All users passed
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001321 // into StrengthReduceStridedIVUsers have the same type AND stride. Also,
1322 // node that we iterate over IVUsesByStride indirectly by using StrideOrder.
1323 // This extra layer of indirection makes the ordering of strides deterministic
1324 // - not dependent on map order.
1325 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
1326 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1327 IVUsesByStride.find(StrideOrder[Stride]);
1328 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
Nate Begemane68bcd12005-07-30 00:15:07 +00001329 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001330 }
Nate Begemanb18121e2004-10-18 21:08:22 +00001331
1332 // Clean up after ourselves
1333 if (!DeadInsts.empty()) {
1334 DeleteTriviallyDeadInstructions(DeadInsts);
1335
Nate Begemane68bcd12005-07-30 00:15:07 +00001336 BasicBlock::iterator I = L->getHeader()->begin();
1337 PHINode *PN;
Chris Lattnerdcce49e2005-08-02 02:44:31 +00001338 while ((PN = dyn_cast<PHINode>(I))) {
Chris Lattner564900e2005-08-02 00:41:11 +00001339 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
1340
Chris Lattnerc6c4d992005-08-09 23:39:36 +00001341 // At this point, we know that we have killed one or more GEP
1342 // instructions. It is worth checking to see if the cann indvar is also
1343 // dead, so that we can remove it as well. The requirements for the cann
1344 // indvar to be considered dead are:
Nate Begemane68bcd12005-07-30 00:15:07 +00001345 // 1. the cann indvar has one use
1346 // 2. the use is an add instruction
1347 // 3. the add has one use
1348 // 4. the add is used by the cann indvar
1349 // If all four cases above are true, then we can remove both the add and
1350 // the cann indvar.
1351 // FIXME: this needs to eliminate an induction variable even if it's being
1352 // compared against some value to decide loop termination.
1353 if (PN->hasOneUse()) {
1354 BinaryOperator *BO = dyn_cast<BinaryOperator>(*(PN->use_begin()));
Chris Lattner75a44e12005-08-02 02:52:02 +00001355 if (BO && BO->hasOneUse()) {
1356 if (PN == *(BO->use_begin())) {
1357 DeadInsts.insert(BO);
1358 // Break the cycle, then delete the PHI.
1359 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattner84e9baa2005-08-03 21:36:09 +00001360 SE->deleteInstructionFromRecords(PN);
Chris Lattner75a44e12005-08-02 02:52:02 +00001361 PN->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +00001362 }
Chris Lattner75a44e12005-08-02 02:52:02 +00001363 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001364 }
Nate Begemanb18121e2004-10-18 21:08:22 +00001365 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001366 DeleteTriviallyDeadInstructions(DeadInsts);
Nate Begemanb18121e2004-10-18 21:08:22 +00001367 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001368
Chris Lattner11e7a5e2005-08-05 01:30:11 +00001369 CastedPointers.clear();
Nate Begemane68bcd12005-07-30 00:15:07 +00001370 IVUsesByStride.clear();
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001371 StrideOrder.clear();
Nate Begemane68bcd12005-07-30 00:15:07 +00001372 return;
Nate Begemanb18121e2004-10-18 21:08:22 +00001373}