blob: e97921237fcecb1bd5d76006e829160efbfb4203 [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
Chris Lattner79a42ac2006-12-19 21:40:18 +000040STATISTIC(NumReduced , "Number of GEPs strength reduced");
41STATISTIC(NumInserted, "Number of PHIs inserted");
42STATISTIC(NumVariable, "Number of PHIs with variable strides");
Nate Begemanb18121e2004-10-18 21:08:22 +000043
Chris Lattner79a42ac2006-12-19 21:40:18 +000044namespace {
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.
Reid Spencer557ab152007-02-05 23:32:05 +000049 struct VISIBILITY_HIDDEN IVStrideUse {
Chris Lattner430d0022005-08-03 22:21:05 +000050 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.
Reid Spencer557ab152007-02-05 23:32:05 +000069 struct VISIBILITY_HIDDEN 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.
Reid Spencer557ab152007-02-05 23:32:05 +000082 struct VISIBILITY_HIDDEN 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()
Reid Spencerc635f472006-12-31 05:48:39 +000089 : Stride(SCEVUnknown::getIntegerSCEV(0, Type::Int32Ty)),
90 Base (SCEVUnknown::getIntegerSCEV(0, Type::Int32Ty)) {}
Evan Chengc28282b2006-03-18 08:03:12 +000091 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.
Reid Spencer557ab152007-02-05 23:32:05 +000098 struct VISIBILITY_HIDDEN IVsOfOneStride {
Evan Cheng3df447d2006-03-16 21:53:05 +000099 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 ///
Reid Spencerdf1f19a2006-12-13 08:06:42 +0000180 Value *getCastedVersionOf(Instruction::CastOps opcode, Value *V);
Chris Lattner6f286b72005-08-04 01:19:13 +0000181private:
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///
Reid Spencerdf1f19a2006-12-13 08:06:42 +0000206Value *LoopStrengthReduce::getCastedVersionOf(Instruction::CastOps opcode,
207 Value *V) {
Chris Lattner6f286b72005-08-04 01:19:13 +0000208 if (V->getType() == UIntPtrTy) return V;
209 if (Constant *CB = dyn_cast<Constant>(V))
Reid Spencerdf1f19a2006-12-13 08:06:42 +0000210 return ConstantExpr::getCast(opcode, CB, UIntPtrTy);
Chris Lattner6f286b72005-08-04 01:19:13 +0000211
212 Value *&New = CastedPointers[V];
213 if (New) return New;
214
Reid Spencerdf1f19a2006-12-13 08:06:42 +0000215 New = SCEVExpander::InsertCastOfTo(opcode, V, UIntPtrTy);
Chris Lattneracc42c42005-08-04 19:08:16 +0000216 DeadInsts.insert(cast<Instruction>(New));
217 return New;
Chris Lattner6f286b72005-08-04 01:19:13 +0000218}
219
220
Nate Begemanb18121e2004-10-18 21:08:22 +0000221/// DeleteTriviallyDeadInstructions - If any of the instructions is the
222/// specified set are trivially dead, delete them and see if this makes any of
223/// their operands subsequently dead.
224void LoopStrengthReduce::
225DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
226 while (!Insts.empty()) {
227 Instruction *I = *Insts.begin();
228 Insts.erase(Insts.begin());
229 if (isInstructionTriviallyDead(I)) {
Jeff Cohen8ea6f9e2005-03-01 03:46:11 +0000230 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
231 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
232 Insts.insert(U);
Chris Lattner84e9baa2005-08-03 21:36:09 +0000233 SE->deleteInstructionFromRecords(I);
234 I->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +0000235 Changed = true;
236 }
237 }
238}
239
Jeff Cohen39751c32005-02-27 19:37:07 +0000240
Chris Lattnereaf24722005-08-04 17:40:30 +0000241/// GetExpressionSCEV - Compute and return the SCEV for the specified
242/// instruction.
243SCEVHandle LoopStrengthReduce::GetExpressionSCEV(Instruction *Exp, Loop *L) {
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000244 // Scalar Evolutions doesn't know how to compute SCEV's for GEP instructions.
245 // If this is a GEP that SE doesn't know about, compute it now and insert it.
246 // If this is not a GEP, or if we have already done this computation, just let
247 // SE figure it out.
Chris Lattnereaf24722005-08-04 17:40:30 +0000248 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000249 if (!GEP || SE->hasSCEV(GEP))
Chris Lattnereaf24722005-08-04 17:40:30 +0000250 return SE->getSCEV(Exp);
251
Nate Begemane68bcd12005-07-30 00:15:07 +0000252 // Analyze all of the subscripts of this getelementptr instruction, looking
253 // for uses that are determined by the trip count of L. First, skip all
254 // operands the are not dependent on the IV.
255
256 // Build up the base expression. Insert an LLVM cast of the pointer to
257 // uintptr_t first.
Reid Spencerdf1f19a2006-12-13 08:06:42 +0000258 SCEVHandle GEPVal = SCEVUnknown::get(
259 getCastedVersionOf(Instruction::PtrToInt, GEP->getOperand(0)));
Nate Begemane68bcd12005-07-30 00:15:07 +0000260
261 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnereaf24722005-08-04 17:40:30 +0000262
263 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
Nate Begemane68bcd12005-07-30 00:15:07 +0000264 // If this is a use of a recurrence that we can analyze, and it comes before
265 // Op does in the GEP operand list, we will handle this when we process this
266 // operand.
267 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
268 const StructLayout *SL = TD->getStructLayout(STy);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000269 unsigned Idx = cast<ConstantInt>(GEP->getOperand(i))->getZExtValue();
Chris Lattnerc473d8e2007-02-10 19:55:17 +0000270 uint64_t Offset = SL->getElementOffset(Idx);
Chris Lattnereaf24722005-08-04 17:40:30 +0000271 GEPVal = SCEVAddExpr::get(GEPVal,
272 SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy));
Nate Begemane68bcd12005-07-30 00:15:07 +0000273 } else {
Reid Spencerdf1f19a2006-12-13 08:06:42 +0000274 unsigned GEPOpiBits =
275 GEP->getOperand(i)->getType()->getPrimitiveSizeInBits();
276 unsigned IntPtrBits = UIntPtrTy->getPrimitiveSizeInBits();
277 Instruction::CastOps opcode = (GEPOpiBits < IntPtrBits ?
278 Instruction::SExt : (GEPOpiBits > IntPtrBits ? Instruction::Trunc :
279 Instruction::BitCast));
280 Value *OpVal = getCastedVersionOf(opcode, GEP->getOperand(i));
Chris Lattneracc42c42005-08-04 19:08:16 +0000281 SCEVHandle Idx = SE->getSCEV(OpVal);
282
Chris Lattnereaf24722005-08-04 17:40:30 +0000283 uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
284 if (TypeSize != 1)
285 Idx = SCEVMulExpr::get(Idx,
Reid Spencere0fc4df2006-10-20 07:07:24 +0000286 SCEVConstant::get(ConstantInt::get(UIntPtrTy,
Chris Lattnereaf24722005-08-04 17:40:30 +0000287 TypeSize)));
288 GEPVal = SCEVAddExpr::get(GEPVal, Idx);
Nate Begemane68bcd12005-07-30 00:15:07 +0000289 }
290 }
291
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000292 SE->setSCEV(GEP, GEPVal);
Chris Lattnereaf24722005-08-04 17:40:30 +0000293 return GEPVal;
Nate Begemane68bcd12005-07-30 00:15:07 +0000294}
295
Chris Lattneracc42c42005-08-04 19:08:16 +0000296/// getSCEVStartAndStride - Compute the start and stride of this expression,
297/// returning false if the expression is not a start/stride pair, or true if it
298/// is. The stride must be a loop invariant expression, but the start may be
299/// a mix of loop invariant and loop variant expressions.
300static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
Chris Lattneredff91a2005-08-10 00:45:21 +0000301 SCEVHandle &Start, SCEVHandle &Stride) {
Chris Lattneracc42c42005-08-04 19:08:16 +0000302 SCEVHandle TheAddRec = Start; // Initialize to zero.
303
304 // If the outer level is an AddExpr, the operands are all start values except
305 // for a nested AddRecExpr.
306 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
307 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
308 if (SCEVAddRecExpr *AddRec =
309 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
310 if (AddRec->getLoop() == L)
311 TheAddRec = SCEVAddExpr::get(AddRec, TheAddRec);
312 else
313 return false; // Nested IV of some sort?
314 } else {
315 Start = SCEVAddExpr::get(Start, AE->getOperand(i));
316 }
317
Reid Spencerde46e482006-11-02 20:25:50 +0000318 } else if (isa<SCEVAddRecExpr>(SH)) {
Chris Lattneracc42c42005-08-04 19:08:16 +0000319 TheAddRec = SH;
320 } else {
321 return false; // not analyzable.
322 }
323
324 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
325 if (!AddRec || AddRec->getLoop() != L) return false;
326
327 // FIXME: Generalize to non-affine IV's.
328 if (!AddRec->isAffine()) return false;
329
330 Start = SCEVAddExpr::get(Start, AddRec->getOperand(0));
331
Chris Lattneracc42c42005-08-04 19:08:16 +0000332 if (!isa<SCEVConstant>(AddRec->getOperand(1)))
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000333 DOUT << "[" << L->getHeader()->getName()
334 << "] Variable stride: " << *AddRec << "\n";
Chris Lattneracc42c42005-08-04 19:08:16 +0000335
Chris Lattneredff91a2005-08-10 00:45:21 +0000336 Stride = AddRec->getOperand(1);
Chris Lattneracc42c42005-08-04 19:08:16 +0000337 return true;
338}
339
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000340/// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
341/// and now we need to decide whether the user should use the preinc or post-inc
342/// value. If this user should use the post-inc version of the IV, return true.
343///
344/// Choosing wrong here can break dominance properties (if we choose to use the
345/// post-inc value when we cannot) or it can end up adding extra live-ranges to
346/// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
347/// should use the post-inc value).
348static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
Chris Lattnercb367102006-01-11 05:10:20 +0000349 Loop *L, ETForest *EF, Pass *P) {
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000350 // If the user is in the loop, use the preinc value.
351 if (L->contains(User->getParent())) return false;
352
Chris Lattnerf07a5872005-10-03 02:50:05 +0000353 BasicBlock *LatchBlock = L->getLoopLatch();
354
355 // Ok, the user is outside of the loop. If it is dominated by the latch
356 // block, use the post-inc value.
Chris Lattnercb367102006-01-11 05:10:20 +0000357 if (EF->dominates(LatchBlock, User->getParent()))
Chris Lattnerf07a5872005-10-03 02:50:05 +0000358 return true;
359
360 // There is one case we have to be careful of: PHI nodes. These little guys
361 // can live in blocks that do not dominate the latch block, but (since their
362 // uses occur in the predecessor block, not the block the PHI lives in) should
363 // still use the post-inc value. Check for this case now.
364 PHINode *PN = dyn_cast<PHINode>(User);
365 if (!PN) return false; // not a phi, not dominated by latch block.
366
367 // Look at all of the uses of IV by the PHI node. If any use corresponds to
368 // a block that is not dominated by the latch block, give up and use the
369 // preincremented value.
370 unsigned NumUses = 0;
371 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
372 if (PN->getIncomingValue(i) == IV) {
373 ++NumUses;
Chris Lattnercb367102006-01-11 05:10:20 +0000374 if (!EF->dominates(LatchBlock, PN->getIncomingBlock(i)))
Chris Lattnerf07a5872005-10-03 02:50:05 +0000375 return false;
376 }
377
378 // Okay, all uses of IV by PN are in predecessor blocks that really are
379 // dominated by the latch block. Split the critical edges and use the
380 // post-incremented value.
381 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
382 if (PN->getIncomingValue(i) == IV) {
Chris Lattnera6eb7e02006-10-28 06:45:33 +0000383 SplitCriticalEdge(PN->getIncomingBlock(i), PN->getParent(), P,
384 true);
Chris Lattner5191c652006-10-28 00:59:20 +0000385 // Splitting the critical edge can reduce the number of entries in this
386 // PHI.
387 e = PN->getNumIncomingValues();
Chris Lattnerf07a5872005-10-03 02:50:05 +0000388 if (--NumUses == 0) break;
389 }
390
391 return true;
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000392}
393
394
395
Nate Begemane68bcd12005-07-30 00:15:07 +0000396/// AddUsersIfInteresting - Inspect the specified instruction. If it is a
397/// reducible SCEV, recursively add its users to the IVUsesByStride set and
398/// return true. Otherwise, return false.
Chris Lattnereaf24722005-08-04 17:40:30 +0000399bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
400 std::set<Instruction*> &Processed) {
Chris Lattner03c49532007-01-15 02:27:26 +0000401 if (!I->getType()->isInteger() && !isa<PointerType>(I->getType()))
Chris Lattner5df0e362005-10-21 05:45:41 +0000402 return false; // Void and FP expressions cannot be reduced.
Chris Lattnereaf24722005-08-04 17:40:30 +0000403 if (!Processed.insert(I).second)
404 return true; // Instruction already handled.
405
Chris Lattneracc42c42005-08-04 19:08:16 +0000406 // Get the symbolic expression for this instruction.
Chris Lattnereaf24722005-08-04 17:40:30 +0000407 SCEVHandle ISE = GetExpressionSCEV(I, L);
Chris Lattneracc42c42005-08-04 19:08:16 +0000408 if (isa<SCEVCouldNotCompute>(ISE)) return false;
Chris Lattnereaf24722005-08-04 17:40:30 +0000409
Chris Lattneracc42c42005-08-04 19:08:16 +0000410 // Get the start and stride for this expression.
411 SCEVHandle Start = SCEVUnknown::getIntegerSCEV(0, ISE->getType());
Chris Lattneredff91a2005-08-10 00:45:21 +0000412 SCEVHandle Stride = Start;
Chris Lattneracc42c42005-08-04 19:08:16 +0000413 if (!getSCEVStartAndStride(ISE, L, Start, Stride))
414 return false; // Non-reducible symbolic expression, bail out.
415
Nate Begemane68bcd12005-07-30 00:15:07 +0000416 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){
417 Instruction *User = cast<Instruction>(*UI);
418
419 // Do not infinitely recurse on PHI nodes.
Chris Lattnerfd018c82005-09-13 02:09:55 +0000420 if (isa<PHINode>(User) && Processed.count(User))
Nate Begemane68bcd12005-07-30 00:15:07 +0000421 continue;
422
423 // If this is an instruction defined in a nested loop, or outside this loop,
Chris Lattnera0102fb2005-08-04 00:14:11 +0000424 // don't recurse into it.
Chris Lattneracc42c42005-08-04 19:08:16 +0000425 bool AddUserToIVUsers = false;
Chris Lattnera0102fb2005-08-04 00:14:11 +0000426 if (LI->getLoopFor(User->getParent()) != L) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000427 DOUT << "FOUND USER in other loop: " << *User
428 << " OF SCEV: " << *ISE << "\n";
Chris Lattneracc42c42005-08-04 19:08:16 +0000429 AddUserToIVUsers = true;
Chris Lattnereaf24722005-08-04 17:40:30 +0000430 } else if (!AddUsersIfInteresting(User, L, Processed)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000431 DOUT << "FOUND USER: " << *User
432 << " OF SCEV: " << *ISE << "\n";
Chris Lattneracc42c42005-08-04 19:08:16 +0000433 AddUserToIVUsers = true;
434 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000435
Chris Lattneracc42c42005-08-04 19:08:16 +0000436 if (AddUserToIVUsers) {
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000437 IVUsersOfOneStride &StrideUses = IVUsesByStride[Stride];
438 if (StrideUses.Users.empty()) // First occurance of this stride?
439 StrideOrder.push_back(Stride);
440
Chris Lattner65107492005-08-04 00:40:47 +0000441 // Okay, we found a user that we cannot reduce. Analyze the instruction
Chris Lattnera6764832005-09-12 06:04:47 +0000442 // and decide what to do with it. If we are a use inside of the loop, use
443 // the value before incrementation, otherwise use it after incrementation.
Chris Lattnercb367102006-01-11 05:10:20 +0000444 if (IVUseShouldUsePostIncValue(User, I, L, EF, this)) {
Chris Lattnera6764832005-09-12 06:04:47 +0000445 // The value used will be incremented by the stride more than we are
446 // expecting, so subtract this off.
447 SCEVHandle NewStart = SCEV::getMinusSCEV(Start, Stride);
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000448 StrideUses.addUser(NewStart, User, I);
449 StrideUses.Users.back().isUseOfPostIncrementedValue = true;
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000450 DOUT << " USING POSTINC SCEV, START=" << *NewStart<< "\n";
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000451 } else {
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000452 StrideUses.addUser(Start, User, I);
Chris Lattnera6764832005-09-12 06:04:47 +0000453 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000454 }
455 }
456 return true;
457}
458
459namespace {
460 /// BasedUser - For a particular base value, keep information about how we've
461 /// partitioned the expression so far.
462 struct BasedUser {
Chris Lattner37c24cc2005-08-08 22:56:21 +0000463 /// Base - The Base value for the PHI node that needs to be inserted for
464 /// this use. As the use is processed, information gets moved from this
465 /// field to the Imm field (below). BasedUser values are sorted by this
466 /// field.
467 SCEVHandle Base;
468
Nate Begemane68bcd12005-07-30 00:15:07 +0000469 /// Inst - The instruction using the induction variable.
470 Instruction *Inst;
471
Chris Lattner430d0022005-08-03 22:21:05 +0000472 /// OperandValToReplace - The operand value of Inst to replace with the
473 /// EmittedBase.
474 Value *OperandValToReplace;
Nate Begemane68bcd12005-07-30 00:15:07 +0000475
476 /// Imm - The immediate value that should be added to the base immediately
477 /// before Inst, because it will be folded into the imm field of the
478 /// instruction.
479 SCEVHandle Imm;
480
481 /// EmittedBase - The actual value* to use for the base value of this
482 /// operation. This is null if we should just use zero so far.
483 Value *EmittedBase;
484
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000485 // isUseOfPostIncrementedValue - True if this should use the
486 // post-incremented version of this IV, not the preincremented version.
487 // This can only be set in special cases, such as the terminating setcc
Chris Lattnera6764832005-09-12 06:04:47 +0000488 // instruction for a loop and uses outside the loop that are dominated by
489 // the loop.
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000490 bool isUseOfPostIncrementedValue;
Chris Lattner37c24cc2005-08-08 22:56:21 +0000491
492 BasedUser(IVStrideUse &IVSU)
493 : Base(IVSU.Offset), Inst(IVSU.User),
494 OperandValToReplace(IVSU.OperandValToReplace),
495 Imm(SCEVUnknown::getIntegerSCEV(0, Base->getType())), EmittedBase(0),
496 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
Nate Begemane68bcd12005-07-30 00:15:07 +0000497
Chris Lattnera6d7c352005-08-04 20:03:32 +0000498 // Once we rewrite the code to insert the new IVs we want, update the
499 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
500 // to it.
Chris Lattnera091ff12005-08-09 00:18:09 +0000501 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattner8447b492005-08-12 22:22:17 +0000502 SCEVExpander &Rewriter, Loop *L,
503 Pass *P);
Chris Lattner2959f002006-02-04 07:36:50 +0000504
505 Value *InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
506 SCEVExpander &Rewriter,
507 Instruction *IP, Loop *L);
Nate Begemane68bcd12005-07-30 00:15:07 +0000508 void dump() const;
509 };
510}
511
512void BasedUser::dump() const {
Bill Wendlingf3baad32006-12-07 01:30:32 +0000513 cerr << " Base=" << *Base;
514 cerr << " Imm=" << *Imm;
Nate Begemane68bcd12005-07-30 00:15:07 +0000515 if (EmittedBase)
Bill Wendlingf3baad32006-12-07 01:30:32 +0000516 cerr << " EB=" << *EmittedBase;
Nate Begemane68bcd12005-07-30 00:15:07 +0000517
Bill Wendlingf3baad32006-12-07 01:30:32 +0000518 cerr << " Inst: " << *Inst;
Nate Begemane68bcd12005-07-30 00:15:07 +0000519}
520
Chris Lattner2959f002006-02-04 07:36:50 +0000521Value *BasedUser::InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
522 SCEVExpander &Rewriter,
523 Instruction *IP, Loop *L) {
524 // Figure out where we *really* want to insert this code. In particular, if
525 // the user is inside of a loop that is nested inside of L, we really don't
526 // want to insert this expression before the user, we'd rather pull it out as
527 // many loops as possible.
528 LoopInfo &LI = Rewriter.getLoopInfo();
529 Instruction *BaseInsertPt = IP;
530
531 // Figure out the most-nested loop that IP is in.
532 Loop *InsertLoop = LI.getLoopFor(IP->getParent());
533
534 // If InsertLoop is not L, and InsertLoop is nested inside of L, figure out
535 // the preheader of the outer-most loop where NewBase is not loop invariant.
536 while (InsertLoop && NewBase->isLoopInvariant(InsertLoop)) {
537 BaseInsertPt = InsertLoop->getLoopPreheader()->getTerminator();
538 InsertLoop = InsertLoop->getParentLoop();
539 }
540
541 // If there is no immediate value, skip the next part.
542 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Imm))
543 if (SC->getValue()->isNullValue())
544 return Rewriter.expandCodeFor(NewBase, BaseInsertPt,
545 OperandValToReplace->getType());
546
547 Value *Base = Rewriter.expandCodeFor(NewBase, BaseInsertPt);
548
549 // Always emit the immediate (if non-zero) into the same block as the user.
550 SCEVHandle NewValSCEV = SCEVAddExpr::get(SCEVUnknown::get(Base), Imm);
551 return Rewriter.expandCodeFor(NewValSCEV, IP,
552 OperandValToReplace->getType());
553}
554
555
Chris Lattnera6d7c352005-08-04 20:03:32 +0000556// Once we rewrite the code to insert the new IVs we want, update the
557// operands of Inst to use the new expression 'NewBase', with 'Imm' added
558// to it.
Chris Lattnera091ff12005-08-09 00:18:09 +0000559void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattner4fec86d2005-08-12 22:06:11 +0000560 SCEVExpander &Rewriter,
Chris Lattner8447b492005-08-12 22:22:17 +0000561 Loop *L, Pass *P) {
Chris Lattnera6d7c352005-08-04 20:03:32 +0000562 if (!isa<PHINode>(Inst)) {
Chris Lattner2959f002006-02-04 07:36:50 +0000563 Value *NewVal = InsertCodeForBaseAtPosition(NewBase, Rewriter, Inst, L);
Chris Lattnera6d7c352005-08-04 20:03:32 +0000564 // Replace the use of the operand Value with the new Phi we just created.
565 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000566 DOUT << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst;
Chris Lattnera6d7c352005-08-04 20:03:32 +0000567 return;
568 }
569
570 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000571 // expression into each operand block that uses it. Note that PHI nodes can
572 // have multiple entries for the same predecessor. We use a map to make sure
573 // that a PHI node only has a single Value* for each predecessor (which also
574 // prevents us from inserting duplicate code in some blocks).
575 std::map<BasicBlock*, Value*> InsertedCode;
Chris Lattnera6d7c352005-08-04 20:03:32 +0000576 PHINode *PN = cast<PHINode>(Inst);
577 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
578 if (PN->getIncomingValue(i) == OperandValToReplace) {
Chris Lattner4fec86d2005-08-12 22:06:11 +0000579 // If this is a critical edge, split the edge so that we do not insert the
Chris Lattnerfd018c82005-09-13 02:09:55 +0000580 // code on all predecessor/successor paths. We do this unless this is the
581 // canonical backedge for this loop, as this can make some inserted code
582 // be in an illegal position.
Chris Lattner8fcce172005-10-03 00:31:52 +0000583 BasicBlock *PHIPred = PN->getIncomingBlock(i);
584 if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
585 (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
Chris Lattner8fcce172005-10-03 00:31:52 +0000586
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000587 // First step, split the critical edge.
Chris Lattnera6eb7e02006-10-28 06:45:33 +0000588 SplitCriticalEdge(PHIPred, PN->getParent(), P, true);
Chris Lattner8447b492005-08-12 22:22:17 +0000589
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000590 // Next step: move the basic block. In particular, if the PHI node
591 // is outside of the loop, and PredTI is in the loop, we want to
592 // move the block to be immediately before the PHI block, not
593 // immediately after PredTI.
Chris Lattner8fcce172005-10-03 00:31:52 +0000594 if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000595 BasicBlock *NewBB = PN->getIncomingBlock(i);
596 NewBB->moveBefore(PN->getParent());
Chris Lattner4fec86d2005-08-12 22:06:11 +0000597 }
Chris Lattner5191c652006-10-28 00:59:20 +0000598
599 // Splitting the edge can reduce the number of PHI entries we have.
600 e = PN->getNumIncomingValues();
Chris Lattner4fec86d2005-08-12 22:06:11 +0000601 }
Chris Lattnera6d7c352005-08-04 20:03:32 +0000602
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000603 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
604 if (!Code) {
605 // Insert the code into the end of the predecessor block.
Chris Lattner2959f002006-02-04 07:36:50 +0000606 Instruction *InsertPt = PN->getIncomingBlock(i)->getTerminator();
607 Code = InsertCodeForBaseAtPosition(NewBase, Rewriter, InsertPt, L);
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000608 }
Chris Lattnera6d7c352005-08-04 20:03:32 +0000609
610 // Replace the use of the operand Value with the new Phi we just created.
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000611 PN->setIncomingValue(i, Code);
Chris Lattnera6d7c352005-08-04 20:03:32 +0000612 Rewriter.clear();
613 }
614 }
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000615 DOUT << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst;
Chris Lattnera6d7c352005-08-04 20:03:32 +0000616}
617
618
Nate Begemane68bcd12005-07-30 00:15:07 +0000619/// isTargetConstant - Return true if the following can be referenced by the
620/// immediate field of a target instruction.
Evan Chengc567c4e2006-03-13 23:14:23 +0000621static bool isTargetConstant(const SCEVHandle &V, const TargetLowering *TLI) {
Chris Lattner14203e82005-08-08 06:25:50 +0000622 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
Chris Lattner07720072005-12-05 18:23:57 +0000623 int64_t V = SC->getValue()->getSExtValue();
Evan Chengc567c4e2006-03-13 23:14:23 +0000624 if (TLI)
625 return TLI->isLegalAddressImmediate(V);
626 else
627 // Defaults to PPC. PPC allows a sign-extended 16-bit immediate field.
628 return (V > -(1 << 16) && V < (1 << 16)-1);
Chris Lattner14203e82005-08-08 06:25:50 +0000629 }
Jeff Cohen546fd592005-07-30 18:33:25 +0000630
Nate Begemane68bcd12005-07-30 00:15:07 +0000631 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
632 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000633 if (CE->getOpcode() == Instruction::PtrToInt) {
Evan Chengc567c4e2006-03-13 23:14:23 +0000634 Constant *Op0 = CE->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000635 if (isa<GlobalValue>(Op0) && TLI &&
Evan Chengc567c4e2006-03-13 23:14:23 +0000636 TLI->isLegalAddressImmediate(cast<GlobalValue>(Op0)))
Nate Begemane68bcd12005-07-30 00:15:07 +0000637 return true;
Evan Chengc567c4e2006-03-13 23:14:23 +0000638 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000639 return false;
640}
641
Chris Lattner37ed8952005-08-08 22:32:34 +0000642/// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
643/// loop varying to the Imm operand.
644static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
645 Loop *L) {
646 if (Val->isLoopInvariant(L)) return; // Nothing to do.
647
648 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
649 std::vector<SCEVHandle> NewOps;
650 NewOps.reserve(SAE->getNumOperands());
651
652 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
653 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
654 // If this is a loop-variant expression, it must stay in the immediate
655 // field of the expression.
656 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
657 } else {
658 NewOps.push_back(SAE->getOperand(i));
659 }
660
661 if (NewOps.empty())
662 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
663 else
664 Val = SCEVAddExpr::get(NewOps);
665 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
666 // Try to pull immediates out of the start value of nested addrec's.
667 SCEVHandle Start = SARE->getStart();
668 MoveLoopVariantsToImediateField(Start, Imm, L);
669
670 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
671 Ops[0] = Start;
672 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
673 } else {
674 // Otherwise, all of Val is variant, move the whole thing over.
675 Imm = SCEVAddExpr::get(Imm, Val);
676 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
677 }
678}
679
680
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000681/// MoveImmediateValues - Look at Val, and pull out any additions of constants
Nate Begemane68bcd12005-07-30 00:15:07 +0000682/// that can fit into the immediate field of instructions in the target.
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000683/// Accumulate these immediate values into the Imm value.
Evan Chengc567c4e2006-03-13 23:14:23 +0000684static void MoveImmediateValues(const TargetLowering *TLI,
685 SCEVHandle &Val, SCEVHandle &Imm,
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000686 bool isAddress, Loop *L) {
Chris Lattnerfc624702005-08-03 23:44:42 +0000687 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000688 std::vector<SCEVHandle> NewOps;
689 NewOps.reserve(SAE->getNumOperands());
690
Chris Lattner2959f002006-02-04 07:36:50 +0000691 for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
692 SCEVHandle NewOp = SAE->getOperand(i);
Evan Chengc567c4e2006-03-13 23:14:23 +0000693 MoveImmediateValues(TLI, NewOp, Imm, isAddress, L);
Chris Lattner2959f002006-02-04 07:36:50 +0000694
695 if (!NewOp->isLoopInvariant(L)) {
Chris Lattneracc42c42005-08-04 19:08:16 +0000696 // If this is a loop-variant expression, it must stay in the immediate
697 // field of the expression.
Chris Lattner2959f002006-02-04 07:36:50 +0000698 Imm = SCEVAddExpr::get(Imm, NewOp);
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000699 } else {
Chris Lattner2959f002006-02-04 07:36:50 +0000700 NewOps.push_back(NewOp);
Nate Begemane68bcd12005-07-30 00:15:07 +0000701 }
Chris Lattner2959f002006-02-04 07:36:50 +0000702 }
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000703
704 if (NewOps.empty())
705 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
706 else
707 Val = SCEVAddExpr::get(NewOps);
708 return;
Chris Lattnerfc624702005-08-03 23:44:42 +0000709 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
710 // Try to pull immediates out of the start value of nested addrec's.
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000711 SCEVHandle Start = SARE->getStart();
Evan Chengc567c4e2006-03-13 23:14:23 +0000712 MoveImmediateValues(TLI, Start, Imm, isAddress, L);
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000713
714 if (Start != SARE->getStart()) {
715 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
716 Ops[0] = Start;
717 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
718 }
719 return;
Chris Lattner2959f002006-02-04 07:36:50 +0000720 } else if (SCEVMulExpr *SME = dyn_cast<SCEVMulExpr>(Val)) {
721 // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
Evan Chengc567c4e2006-03-13 23:14:23 +0000722 if (isAddress && isTargetConstant(SME->getOperand(0), TLI) &&
Chris Lattner2959f002006-02-04 07:36:50 +0000723 SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
724
725 SCEVHandle SubImm = SCEVUnknown::getIntegerSCEV(0, Val->getType());
726 SCEVHandle NewOp = SME->getOperand(1);
Evan Chengc567c4e2006-03-13 23:14:23 +0000727 MoveImmediateValues(TLI, NewOp, SubImm, isAddress, L);
Chris Lattner2959f002006-02-04 07:36:50 +0000728
729 // If we extracted something out of the subexpressions, see if we can
730 // simplify this!
731 if (NewOp != SME->getOperand(1)) {
732 // Scale SubImm up by "8". If the result is a target constant, we are
733 // good.
734 SubImm = SCEVMulExpr::get(SubImm, SME->getOperand(0));
Evan Chengc567c4e2006-03-13 23:14:23 +0000735 if (isTargetConstant(SubImm, TLI)) {
Chris Lattner2959f002006-02-04 07:36:50 +0000736 // Accumulate the immediate.
737 Imm = SCEVAddExpr::get(Imm, SubImm);
738
739 // Update what is left of 'Val'.
740 Val = SCEVMulExpr::get(SME->getOperand(0), NewOp);
741 return;
742 }
743 }
744 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000745 }
746
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000747 // Loop-variant expressions must stay in the immediate field of the
748 // expression.
Evan Chengc567c4e2006-03-13 23:14:23 +0000749 if ((isAddress && isTargetConstant(Val, TLI)) ||
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000750 !Val->isLoopInvariant(L)) {
751 Imm = SCEVAddExpr::get(Imm, Val);
752 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
753 return;
Chris Lattner0f7c0fa2005-08-04 19:26:19 +0000754 }
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000755
756 // Otherwise, no immediates to move.
Nate Begemane68bcd12005-07-30 00:15:07 +0000757}
758
Chris Lattner5949d492005-08-13 07:27:18 +0000759
Chris Lattner3ff62012006-08-03 06:34:50 +0000760/// SeparateSubExprs - Decompose Expr into all of the subexpressions that are
761/// added together. This is used to reassociate common addition subexprs
762/// together for maximal sharing when rewriting bases.
Chris Lattner5949d492005-08-13 07:27:18 +0000763static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
764 SCEVHandle Expr) {
765 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
766 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
767 SeparateSubExprs(SubExprs, AE->getOperand(j));
768 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
769 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Expr->getType());
770 if (SARE->getOperand(0) == Zero) {
771 SubExprs.push_back(Expr);
772 } else {
773 // Compute the addrec with zero as its base.
774 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
775 Ops[0] = Zero; // Start with zero base.
776 SubExprs.push_back(SCEVAddRecExpr::get(Ops, SARE->getLoop()));
777
778
779 SeparateSubExprs(SubExprs, SARE->getOperand(0));
780 }
781 } else if (!isa<SCEVConstant>(Expr) ||
782 !cast<SCEVConstant>(Expr)->getValue()->isNullValue()) {
783 // Do not add zero.
784 SubExprs.push_back(Expr);
785 }
786}
787
788
Chris Lattnera091ff12005-08-09 00:18:09 +0000789/// RemoveCommonExpressionsFromUseBases - Look through all of the uses in Bases,
790/// removing any common subexpressions from it. Anything truly common is
791/// removed, accumulated, and returned. This looks for things like (a+b+c) and
792/// (a+c+d) -> (a+c). The common expression is *removed* from the Bases.
793static SCEVHandle
794RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses) {
795 unsigned NumUses = Uses.size();
796
797 // Only one use? Use its base, regardless of what it is!
798 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Uses[0].Base->getType());
799 SCEVHandle Result = Zero;
800 if (NumUses == 1) {
801 std::swap(Result, Uses[0].Base);
802 return Result;
803 }
804
805 // To find common subexpressions, count how many of Uses use each expression.
806 // If any subexpressions are used Uses.size() times, they are common.
807 std::map<SCEVHandle, unsigned> SubExpressionUseCounts;
808
Chris Lattner192cd182005-10-11 18:41:04 +0000809 // UniqueSubExprs - Keep track of all of the subexpressions we see in the
810 // order we see them.
811 std::vector<SCEVHandle> UniqueSubExprs;
812
Chris Lattner5949d492005-08-13 07:27:18 +0000813 std::vector<SCEVHandle> SubExprs;
814 for (unsigned i = 0; i != NumUses; ++i) {
815 // If the base is zero (which is common), return zero now, there are no
816 // CSEs we can find.
817 if (Uses[i].Base == Zero) return Zero;
818
819 // Split the expression into subexprs.
820 SeparateSubExprs(SubExprs, Uses[i].Base);
821 // Add one to SubExpressionUseCounts for each subexpr present.
822 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
Chris Lattner192cd182005-10-11 18:41:04 +0000823 if (++SubExpressionUseCounts[SubExprs[j]] == 1)
824 UniqueSubExprs.push_back(SubExprs[j]);
Chris Lattner5949d492005-08-13 07:27:18 +0000825 SubExprs.clear();
826 }
827
Chris Lattner192cd182005-10-11 18:41:04 +0000828 // Now that we know how many times each is used, build Result. Iterate over
829 // UniqueSubexprs so that we have a stable ordering.
830 for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
831 std::map<SCEVHandle, unsigned>::iterator I =
832 SubExpressionUseCounts.find(UniqueSubExprs[i]);
833 assert(I != SubExpressionUseCounts.end() && "Entry not found?");
Chris Lattnera091ff12005-08-09 00:18:09 +0000834 if (I->second == NumUses) { // Found CSE!
835 Result = SCEVAddExpr::get(Result, I->first);
Chris Lattnera091ff12005-08-09 00:18:09 +0000836 } else {
837 // Remove non-cse's from SubExpressionUseCounts.
Chris Lattner192cd182005-10-11 18:41:04 +0000838 SubExpressionUseCounts.erase(I);
Chris Lattnera091ff12005-08-09 00:18:09 +0000839 }
Chris Lattner192cd182005-10-11 18:41:04 +0000840 }
Chris Lattnera091ff12005-08-09 00:18:09 +0000841
842 // If we found no CSE's, return now.
843 if (Result == Zero) return Result;
844
845 // Otherwise, remove all of the CSE's we found from each of the base values.
Chris Lattner5949d492005-08-13 07:27:18 +0000846 for (unsigned i = 0; i != NumUses; ++i) {
847 // Split the expression into subexprs.
848 SeparateSubExprs(SubExprs, Uses[i].Base);
849
850 // Remove any common subexpressions.
851 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
852 if (SubExpressionUseCounts.count(SubExprs[j])) {
853 SubExprs.erase(SubExprs.begin()+j);
854 --j; --e;
855 }
856
857 // Finally, the non-shared expressions together.
858 if (SubExprs.empty())
Chris Lattnera091ff12005-08-09 00:18:09 +0000859 Uses[i].Base = Zero;
Chris Lattner5949d492005-08-13 07:27:18 +0000860 else
861 Uses[i].Base = SCEVAddExpr::get(SubExprs);
Chris Lattner47d3ec32005-08-13 07:42:01 +0000862 SubExprs.clear();
Chris Lattner5949d492005-08-13 07:27:18 +0000863 }
Chris Lattnera091ff12005-08-09 00:18:09 +0000864
865 return Result;
866}
867
Evan Cheng3df447d2006-03-16 21:53:05 +0000868/// isZero - returns true if the scalar evolution expression is zero.
869///
870static bool isZero(SCEVHandle &V) {
871 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V))
Reid Spencere0fc4df2006-10-20 07:07:24 +0000872 return SC->getValue()->getZExtValue() == 0;
Evan Cheng3df447d2006-03-16 21:53:05 +0000873 return false;
874}
875
Chris Lattnera091ff12005-08-09 00:18:09 +0000876
Evan Cheng45206982006-03-17 19:52:23 +0000877/// CheckForIVReuse - Returns the multiple if the stride is the multiple
878/// of a previous stride and it is a legal value for the target addressing
879/// mode scale component. This allows the users of this stride to be rewritten
Evan Chengc28282b2006-03-18 08:03:12 +0000880/// as prev iv * factor. It returns 0 if no reuse is possible.
Evan Cheng45206982006-03-17 19:52:23 +0000881unsigned LoopStrengthReduce::CheckForIVReuse(const SCEVHandle &Stride,
Evan Chenge9c68f52006-07-18 19:07:58 +0000882 IVExpr &IV, const Type *Ty) {
Evan Chengc28282b2006-03-18 08:03:12 +0000883 if (!TLI) return 0;
Evan Cheng45206982006-03-17 19:52:23 +0000884
885 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride)) {
Evan Chengc28282b2006-03-18 08:03:12 +0000886 int64_t SInt = SC->getValue()->getSExtValue();
887 if (SInt == 1) return 0;
Evan Cheng45206982006-03-17 19:52:23 +0000888
889 for (TargetLowering::legal_am_scale_iterator
890 I = TLI->legal_am_scale_begin(), E = TLI->legal_am_scale_end();
891 I != E; ++I) {
892 unsigned Scale = *I;
Reid Spencer13a1a7a2006-04-12 19:28:15 +0000893 if (unsigned(abs(SInt)) < Scale || (SInt % Scale) != 0)
Evan Cheng45206982006-03-17 19:52:23 +0000894 continue;
895 std::map<SCEVHandle, IVsOfOneStride>::iterator SI =
Reid Spencerbf96e022007-01-08 16:17:51 +0000896 IVsByStride.find(SCEVUnknown::getIntegerSCEV(SInt/Scale, UIntPtrTy));
Evan Cheng45206982006-03-17 19:52:23 +0000897 if (SI == IVsByStride.end())
898 continue;
899 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
900 IE = SI->second.IVs.end(); II != IE; ++II)
901 // FIXME: Only handle base == 0 for now.
Evan Chenge9c68f52006-07-18 19:07:58 +0000902 // Only reuse previous IV if it would not require a type conversion.
Chris Lattner3fe98ae2007-01-06 01:37:35 +0000903 if (isZero(II->Base) && II->Base->getType() == Ty) {
Evan Cheng45206982006-03-17 19:52:23 +0000904 IV = *II;
905 return Scale;
906 }
907 }
908 }
909
Evan Chengc28282b2006-03-18 08:03:12 +0000910 return 0;
Evan Cheng45206982006-03-17 19:52:23 +0000911}
912
Chris Lattner3ff62012006-08-03 06:34:50 +0000913/// PartitionByIsUseOfPostIncrementedValue - Simple boolean predicate that
914/// returns true if Val's isUseOfPostIncrementedValue is true.
915static bool PartitionByIsUseOfPostIncrementedValue(const BasedUser &Val) {
916 return Val.isUseOfPostIncrementedValue;
917}
Evan Cheng45206982006-03-17 19:52:23 +0000918
Nate Begemane68bcd12005-07-30 00:15:07 +0000919/// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
920/// stride of IV. All of the users may have different starting values, and this
921/// may not be the only stride (we know it is if isOnlyStride is true).
Chris Lattneredff91a2005-08-10 00:45:21 +0000922void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
Chris Lattner430d0022005-08-03 22:21:05 +0000923 IVUsersOfOneStride &Uses,
924 Loop *L,
Nate Begemane68bcd12005-07-30 00:15:07 +0000925 bool isOnlyStride) {
926 // Transform our list of users and offsets to a bit more complex table. In
Chris Lattner37c24cc2005-08-08 22:56:21 +0000927 // this new vector, each 'BasedUser' contains 'Base' the base of the
928 // strided accessas well as the old information from Uses. We progressively
929 // move information from the Base field to the Imm field, until we eventually
930 // have the full access expression to rewrite the use.
931 std::vector<BasedUser> UsersToProcess;
Nate Begemane68bcd12005-07-30 00:15:07 +0000932 UsersToProcess.reserve(Uses.Users.size());
Chris Lattner37c24cc2005-08-08 22:56:21 +0000933 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
934 UsersToProcess.push_back(Uses.Users[i]);
935
936 // Move any loop invariant operands from the offset field to the immediate
937 // field of the use, so that we don't try to use something before it is
938 // computed.
939 MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
940 UsersToProcess.back().Imm, L);
941 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000942 "Base value is not loop invariant!");
Nate Begemane68bcd12005-07-30 00:15:07 +0000943 }
Evan Cheng45206982006-03-17 19:52:23 +0000944
Chris Lattnera091ff12005-08-09 00:18:09 +0000945 // We now have a whole bunch of uses of like-strided induction variables, but
946 // they might all have different bases. We want to emit one PHI node for this
947 // stride which we fold as many common expressions (between the IVs) into as
948 // possible. Start by identifying the common expressions in the base values
949 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
950 // "A+B"), emit it to the preheader, then remove the expression from the
951 // UsersToProcess base values.
Evan Cheng3df447d2006-03-16 21:53:05 +0000952 SCEVHandle CommonExprs =
953 RemoveCommonExpressionsFromUseBases(UsersToProcess);
Chris Lattnera091ff12005-08-09 00:18:09 +0000954
Evan Chenge9c68f52006-07-18 19:07:58 +0000955 // Check if it is possible to reuse a IV with stride that is factor of this
956 // stride. And the multiple is a number that can be encoded in the scale
957 // field of the target addressing mode.
958 PHINode *NewPHI = NULL;
959 Value *IncV = NULL;
960 IVExpr ReuseIV;
961 unsigned RewriteFactor = CheckForIVReuse(Stride, ReuseIV,
962 CommonExprs->getType());
963 if (RewriteFactor != 0) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000964 DOUT << "BASED ON IV of STRIDE " << *ReuseIV.Stride
965 << " and BASE " << *ReuseIV.Base << " :\n";
Evan Chenge9c68f52006-07-18 19:07:58 +0000966 NewPHI = ReuseIV.PHI;
967 IncV = ReuseIV.IncV;
968 }
969
Chris Lattner37ed8952005-08-08 22:32:34 +0000970 // Next, figure out what we can represent in the immediate fields of
971 // instructions. If we can represent anything there, move it to the imm
Chris Lattnera091ff12005-08-09 00:18:09 +0000972 // fields of the BasedUsers. We do this so that it increases the commonality
973 // of the remaining uses.
Chris Lattner37ed8952005-08-08 22:32:34 +0000974 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
Chris Lattner5cf983e2005-08-16 00:38:11 +0000975 // If the user is not in the current loop, this means it is using the exit
976 // value of the IV. Do not put anything in the base, make sure it's all in
977 // the immediate field to allow as much factoring as possible.
978 if (!L->contains(UsersToProcess[i].Inst->getParent())) {
Chris Lattnerea7dfd52005-08-17 21:22:41 +0000979 UsersToProcess[i].Imm = SCEVAddExpr::get(UsersToProcess[i].Imm,
980 UsersToProcess[i].Base);
981 UsersToProcess[i].Base =
982 SCEVUnknown::getIntegerSCEV(0, UsersToProcess[i].Base->getType());
Chris Lattner5cf983e2005-08-16 00:38:11 +0000983 } else {
984
985 // Addressing modes can be folded into loads and stores. Be careful that
986 // the store is through the expression, not of the expression though.
987 bool isAddress = isa<LoadInst>(UsersToProcess[i].Inst);
988 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
989 if (SI->getOperand(1) == UsersToProcess[i].OperandValToReplace)
990 isAddress = true;
991
Evan Chengc567c4e2006-03-13 23:14:23 +0000992 MoveImmediateValues(TLI, UsersToProcess[i].Base, UsersToProcess[i].Imm,
Chris Lattner5cf983e2005-08-16 00:38:11 +0000993 isAddress, L);
994 }
Chris Lattner37ed8952005-08-08 22:32:34 +0000995 }
Evan Cheng3df447d2006-03-16 21:53:05 +0000996
Chris Lattnera091ff12005-08-09 00:18:09 +0000997 // Now that we know what we need to do, insert the PHI node itself.
998 //
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000999 DOUT << "INSERTING IV of STRIDE " << *Stride << " and BASE "
1000 << *CommonExprs << " :\n";
Evan Cheng3df447d2006-03-16 21:53:05 +00001001
Chris Lattnera091ff12005-08-09 00:18:09 +00001002 SCEVExpander Rewriter(*SE, *LI);
1003 SCEVExpander PreheaderRewriter(*SE, *LI);
Chris Lattner37ed8952005-08-08 22:32:34 +00001004
Chris Lattnera091ff12005-08-09 00:18:09 +00001005 BasicBlock *Preheader = L->getLoopPreheader();
1006 Instruction *PreInsertPt = Preheader->getTerminator();
1007 Instruction *PhiInsertBefore = L->getHeader()->begin();
Chris Lattner37ed8952005-08-08 22:32:34 +00001008
Chris Lattner8048b852005-09-12 17:11:27 +00001009 BasicBlock *LatchBlock = L->getLoopLatch();
Evan Cheng3df447d2006-03-16 21:53:05 +00001010
Chris Lattnera091ff12005-08-09 00:18:09 +00001011 const Type *ReplacedTy = CommonExprs->getType();
Evan Cheng45206982006-03-17 19:52:23 +00001012
1013 // Emit the initial base value into the loop preheader.
1014 Value *CommonBaseV
1015 = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt,
1016 ReplacedTy);
1017
Evan Chengc28282b2006-03-18 08:03:12 +00001018 if (RewriteFactor == 0) {
Evan Cheng3df447d2006-03-16 21:53:05 +00001019 // Create a new Phi for this base, and stick it in the loop header.
1020 NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
1021 ++NumInserted;
Chris Lattnera091ff12005-08-09 00:18:09 +00001022
Evan Cheng45206982006-03-17 19:52:23 +00001023 // Add common base to the new Phi node.
1024 NewPHI->addIncoming(CommonBaseV, Preheader);
1025
Evan Cheng3df447d2006-03-16 21:53:05 +00001026 // Insert the stride into the preheader.
1027 Value *StrideV = PreheaderRewriter.expandCodeFor(Stride, PreInsertPt,
1028 ReplacedTy);
1029 if (!isa<ConstantInt>(StrideV)) ++NumVariable;
Chris Lattneredff91a2005-08-10 00:45:21 +00001030
Evan Cheng3df447d2006-03-16 21:53:05 +00001031 // Emit the increment of the base value before the terminator of the loop
1032 // latch block, and add it to the Phi node.
1033 SCEVHandle IncExp = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
1034 SCEVUnknown::get(StrideV));
Chris Lattnera091ff12005-08-09 00:18:09 +00001035
Evan Cheng3df447d2006-03-16 21:53:05 +00001036 IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator(),
1037 ReplacedTy);
1038 IncV->setName(NewPHI->getName()+".inc");
1039 NewPHI->addIncoming(IncV, LatchBlock);
1040
Evan Cheng45206982006-03-17 19:52:23 +00001041 // Remember this in case a later stride is multiple of this.
Evan Chengc28282b2006-03-18 08:03:12 +00001042 IVsByStride[Stride].addIV(Stride, CommonExprs, NewPHI, IncV);
Evan Cheng45206982006-03-17 19:52:23 +00001043 } else {
1044 Constant *C = dyn_cast<Constant>(CommonBaseV);
1045 if (!C ||
1046 (!C->isNullValue() &&
1047 !isTargetConstant(SCEVUnknown::get(CommonBaseV), TLI)))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001048 // We want the common base emitted into the preheader! This is just
1049 // using cast as a copy so BitCast (no-op cast) is appropriate
1050 CommonBaseV = new BitCastInst(CommonBaseV, CommonBaseV->getType(),
1051 "commonbase", PreInsertPt);
Evan Cheng3df447d2006-03-16 21:53:05 +00001052 }
Chris Lattnera091ff12005-08-09 00:18:09 +00001053
Chris Lattner3ff62012006-08-03 06:34:50 +00001054 // We want to emit code for users inside the loop first. To do this, we
1055 // rearrange BasedUser so that the entries at the end have
1056 // isUseOfPostIncrementedValue = false, because we pop off the end of the
1057 // vector (so we handle them first).
1058 std::partition(UsersToProcess.begin(), UsersToProcess.end(),
1059 PartitionByIsUseOfPostIncrementedValue);
1060
1061 // Sort this by base, so that things with the same base are handled
1062 // together. By partitioning first and stable-sorting later, we are
1063 // guaranteed that within each base we will pop off users from within the
1064 // loop before users outside of the loop with a particular base.
1065 //
1066 // We would like to use stable_sort here, but we can't. The problem is that
1067 // SCEVHandle's don't have a deterministic ordering w.r.t to each other, so
1068 // we don't have anything to do a '<' comparison on. Because we think the
1069 // number of uses is small, do a horrible bubble sort which just relies on
1070 // ==.
1071 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1072 // Get a base value.
1073 SCEVHandle Base = UsersToProcess[i].Base;
1074
1075 // Compact everything with this base to be consequetive with this one.
1076 for (unsigned j = i+1; j != e; ++j) {
1077 if (UsersToProcess[j].Base == Base) {
1078 std::swap(UsersToProcess[i+1], UsersToProcess[j]);
1079 ++i;
1080 }
1081 }
1082 }
1083
1084 // Process all the users now. This outer loop handles all bases, the inner
1085 // loop handles all users of a particular base.
Nate Begemane68bcd12005-07-30 00:15:07 +00001086 while (!UsersToProcess.empty()) {
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001087 SCEVHandle Base = UsersToProcess.back().Base;
Chris Lattnerbb78c972005-08-03 23:30:08 +00001088
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001089 DOUT << " INSERTING code for BASE = " << *Base << ":\n";
Chris Lattnerbb78c972005-08-03 23:30:08 +00001090
Chris Lattnera091ff12005-08-09 00:18:09 +00001091 // Emit the code for Base into the preheader.
Chris Lattnerc70bbc02005-08-08 05:47:49 +00001092 Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt,
1093 ReplacedTy);
Chris Lattnera091ff12005-08-09 00:18:09 +00001094
1095 // If BaseV is a constant other than 0, make sure that it gets inserted into
1096 // the preheader, instead of being forward substituted into the uses. We do
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001097 // this by forcing a BitCast (noop cast) to be inserted into the preheader
1098 // in this case.
Chris Lattner3ff62012006-08-03 06:34:50 +00001099 if (Constant *C = dyn_cast<Constant>(BaseV)) {
Evan Chengc567c4e2006-03-13 23:14:23 +00001100 if (!C->isNullValue() && !isTargetConstant(Base, TLI)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001101 // We want this constant emitted into the preheader! This is just
1102 // using cast as a copy so BitCast (no-op cast) is appropriate
1103 BaseV = new BitCastInst(BaseV, BaseV->getType(), "preheaderinsert",
Chris Lattnera091ff12005-08-09 00:18:09 +00001104 PreInsertPt);
1105 }
Chris Lattner3ff62012006-08-03 06:34:50 +00001106 }
1107
Nate Begemane68bcd12005-07-30 00:15:07 +00001108 // Emit the code to add the immediate offset to the Phi value, just before
Chris Lattnerdb23c742005-08-03 22:51:21 +00001109 // the instructions that we identified as using this stride and base.
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001110 do {
Chris Lattner3ff62012006-08-03 06:34:50 +00001111 // FIXME: Use emitted users to emit other users.
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001112 BasedUser &User = UsersToProcess.back();
Jeff Cohen546fd592005-07-30 18:33:25 +00001113
Chris Lattnera091ff12005-08-09 00:18:09 +00001114 // If this instruction wants to use the post-incremented value, move it
1115 // after the post-inc and use its value instead of the PHI.
1116 Value *RewriteOp = NewPHI;
1117 if (User.isUseOfPostIncrementedValue) {
1118 RewriteOp = IncV;
Chris Lattnera6764832005-09-12 06:04:47 +00001119
1120 // If this user is in the loop, make sure it is the last thing in the
1121 // loop to ensure it is dominated by the increment.
1122 if (L->contains(User.Inst->getParent()))
1123 User.Inst->moveBefore(LatchBlock->getTerminator());
Chris Lattnera091ff12005-08-09 00:18:09 +00001124 }
Reid Spencerdf1f19a2006-12-13 08:06:42 +00001125 if (RewriteOp->getType() != ReplacedTy) {
1126 Instruction::CastOps opcode = Instruction::Trunc;
1127 if (ReplacedTy->getPrimitiveSizeInBits() ==
1128 RewriteOp->getType()->getPrimitiveSizeInBits())
1129 opcode = Instruction::BitCast;
1130 RewriteOp = SCEVExpander::InsertCastOfTo(opcode, RewriteOp, ReplacedTy);
1131 }
Evan Cheng398f7022006-06-09 00:12:42 +00001132
Chris Lattnera091ff12005-08-09 00:18:09 +00001133 SCEVHandle RewriteExpr = SCEVUnknown::get(RewriteOp);
1134
Chris Lattnerdb23c742005-08-03 22:51:21 +00001135 // Clear the SCEVExpander's expression map so that we are guaranteed
1136 // to have the code emitted where we expect it.
1137 Rewriter.clear();
Evan Cheng3df447d2006-03-16 21:53:05 +00001138
1139 // If we are reusing the iv, then it must be multiplied by a constant
1140 // factor take advantage of addressing mode scale component.
Evan Chengc28282b2006-03-18 08:03:12 +00001141 if (RewriteFactor != 0) {
Evan Cheng3df447d2006-03-16 21:53:05 +00001142 RewriteExpr =
1143 SCEVMulExpr::get(SCEVUnknown::getIntegerSCEV(RewriteFactor,
Evan Cheng45206982006-03-17 19:52:23 +00001144 RewriteExpr->getType()),
1145 RewriteExpr);
1146
1147 // The common base is emitted in the loop preheader. But since we
1148 // are reusing an IV, it has not been used to initialize the PHI node.
1149 // Add it to the expression used to rewrite the uses.
1150 if (!isa<ConstantInt>(CommonBaseV) ||
1151 !cast<ConstantInt>(CommonBaseV)->isNullValue())
1152 RewriteExpr = SCEVAddExpr::get(RewriteExpr,
1153 SCEVUnknown::get(CommonBaseV));
1154 }
Evan Cheng3df447d2006-03-16 21:53:05 +00001155
Chris Lattnera6d7c352005-08-04 20:03:32 +00001156 // Now that we know what we need to do, insert code before User for the
1157 // immediate and any loop-variant expressions.
Chris Lattnera091ff12005-08-09 00:18:09 +00001158 if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isNullValue())
1159 // Add BaseV to the PHI value if needed.
1160 RewriteExpr = SCEVAddExpr::get(RewriteExpr, SCEVUnknown::get(BaseV));
Evan Cheng3df447d2006-03-16 21:53:05 +00001161
Chris Lattner8447b492005-08-12 22:22:17 +00001162 User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter, L, this);
Jeff Cohen546fd592005-07-30 18:33:25 +00001163
Chris Lattnerdb23c742005-08-03 22:51:21 +00001164 // Mark old value we replaced as possibly dead, so that it is elminated
1165 // if we just replaced the last use of that value.
Chris Lattnera6d7c352005-08-04 20:03:32 +00001166 DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
Nate Begemane68bcd12005-07-30 00:15:07 +00001167
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001168 UsersToProcess.pop_back();
Chris Lattnerdb23c742005-08-03 22:51:21 +00001169 ++NumReduced;
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001170
Chris Lattner3ff62012006-08-03 06:34:50 +00001171 // If there are any more users to process with the same base, process them
1172 // now. We sorted by base above, so we just have to check the last elt.
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001173 } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
Nate Begemane68bcd12005-07-30 00:15:07 +00001174 // TODO: Next, find out which base index is the most common, pull it out.
1175 }
1176
1177 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1178 // different starting values, into different PHIs.
Nate Begemane68bcd12005-07-30 00:15:07 +00001179}
1180
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001181// OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
1182// uses in the loop, look to see if we can eliminate some, in favor of using
1183// common indvars for the different uses.
1184void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
1185 // TODO: implement optzns here.
1186
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001187 // Finally, get the terminating condition for the loop if possible. If we
1188 // can, we want to change it to use a post-incremented version of its
Chris Lattnerf365f5f2006-03-24 07:14:34 +00001189 // induction variable, to allow coalescing the live ranges for the IV into
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001190 // one register value.
1191 PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
1192 BasicBlock *Preheader = L->getLoopPreheader();
1193 BasicBlock *LatchBlock =
1194 SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
1195 BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00001196 if (!TermBr || TermBr->isUnconditional() ||
1197 !isa<ICmpInst>(TermBr->getCondition()))
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001198 return;
Reid Spencer266e42b2006-12-23 06:05:41 +00001199 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001200
1201 // Search IVUsesByStride to find Cond's IVUse if there is one.
1202 IVStrideUse *CondUse = 0;
Chris Lattneredff91a2005-08-10 00:45:21 +00001203 const SCEVHandle *CondStride = 0;
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001204
Chris Lattnerb7a38942005-10-11 18:17:57 +00001205 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e && !CondUse;
1206 ++Stride) {
1207 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1208 IVUsesByStride.find(StrideOrder[Stride]);
1209 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1210
1211 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
1212 E = SI->second.Users.end(); UI != E; ++UI)
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001213 if (UI->User == Cond) {
1214 CondUse = &*UI;
Chris Lattnerb7a38942005-10-11 18:17:57 +00001215 CondStride = &SI->first;
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001216 // NOTE: we could handle setcc instructions with multiple uses here, but
1217 // InstCombine does it as well for simple uses, it's not clear that it
1218 // occurs enough in real life to handle.
1219 break;
1220 }
Chris Lattnerb7a38942005-10-11 18:17:57 +00001221 }
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001222 if (!CondUse) return; // setcc doesn't use the IV.
1223
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001224 // It's possible for the setcc instruction to be anywhere in the loop, and
1225 // possible for it to have multiple users. If it is not immediately before
1226 // the latch block branch, move it.
1227 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
1228 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
1229 Cond->moveBefore(TermBr);
1230 } else {
1231 // Otherwise, clone the terminating condition and insert into the loopend.
Reid Spencer266e42b2006-12-23 06:05:41 +00001232 Cond = cast<ICmpInst>(Cond->clone());
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001233 Cond->setName(L->getHeader()->getName() + ".termcond");
1234 LatchBlock->getInstList().insert(TermBr, Cond);
1235
1236 // Clone the IVUse, as the old use still exists!
Chris Lattneredff91a2005-08-10 00:45:21 +00001237 IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001238 CondUse->OperandValToReplace);
Chris Lattneredff91a2005-08-10 00:45:21 +00001239 CondUse = &IVUsesByStride[*CondStride].Users.back();
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001240 }
1241 }
1242
1243 // If we get to here, we know that we can transform the setcc instruction to
Chris Lattnerf365f5f2006-03-24 07:14:34 +00001244 // use the post-incremented version of the IV, allowing us to coalesce the
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001245 // live ranges for the IV correctly.
Chris Lattneredff91a2005-08-10 00:45:21 +00001246 CondUse->Offset = SCEV::getMinusSCEV(CondUse->Offset, *CondStride);
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001247 CondUse->isUseOfPostIncrementedValue = true;
1248}
Nate Begemane68bcd12005-07-30 00:15:07 +00001249
Evan Chengf09f0eb2006-03-18 00:44:49 +00001250namespace {
1251 // Constant strides come first which in turns are sorted by their absolute
1252 // values. If absolute values are the same, then positive strides comes first.
1253 // e.g.
1254 // 4, -1, X, 1, 2 ==> 1, -1, 2, 4, X
1255 struct StrideCompare {
1256 bool operator()(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1257 SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS);
1258 SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
1259 if (LHSC && RHSC) {
1260 int64_t LV = LHSC->getValue()->getSExtValue();
1261 int64_t RV = RHSC->getValue()->getSExtValue();
1262 uint64_t ALV = (LV < 0) ? -LV : LV;
1263 uint64_t ARV = (RV < 0) ? -RV : RV;
1264 if (ALV == ARV)
1265 return LV > RV;
1266 else
1267 return ALV < ARV;
Chris Lattner7d80b4f2006-03-22 17:27:24 +00001268 }
1269 return (LHSC && !RHSC);
Evan Chengf09f0eb2006-03-18 00:44:49 +00001270 }
1271 };
1272}
1273
Nate Begemanb18121e2004-10-18 21:08:22 +00001274void LoopStrengthReduce::runOnLoop(Loop *L) {
1275 // First step, transform all loops nesting inside of this loop.
1276 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
1277 runOnLoop(*I);
1278
Nate Begemane68bcd12005-07-30 00:15:07 +00001279 // Next, find all uses of induction variables in this loop, and catagorize
1280 // them by stride. Start by finding all of the PHI nodes in the header for
1281 // this loop. If they are induction variables, inspect their uses.
Chris Lattnereaf24722005-08-04 17:40:30 +00001282 std::set<Instruction*> Processed; // Don't reprocess instructions.
Nate Begemane68bcd12005-07-30 00:15:07 +00001283 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
Chris Lattnereaf24722005-08-04 17:40:30 +00001284 AddUsersIfInteresting(I, L, Processed);
Nate Begemanb18121e2004-10-18 21:08:22 +00001285
Nate Begemane68bcd12005-07-30 00:15:07 +00001286 // If we have nothing to do, return.
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001287 if (IVUsesByStride.empty()) return;
1288
1289 // Optimize induction variables. Some indvar uses can be transformed to use
1290 // strides that will be needed for other purposes. A common example of this
1291 // is the exit test for the loop, which can often be rewritten to use the
1292 // computation of some other indvar to decide when to terminate the loop.
1293 OptimizeIndvars(L);
1294
Misha Brukmanb1c93172005-04-21 23:48:37 +00001295
Nate Begemane68bcd12005-07-30 00:15:07 +00001296 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
1297 // doing computation in byte values, promote to 32-bit values if safe.
1298
1299 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
1300 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
1301 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
1302 // to be careful that IV's are all the same type. Only works for intptr_t
1303 // indvars.
1304
1305 // If we only have one stride, we can more aggressively eliminate some things.
1306 bool HasOneStride = IVUsesByStride.size() == 1;
Evan Cheng3df447d2006-03-16 21:53:05 +00001307
1308#ifndef NDEBUG
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001309 DOUT << "\nLSR on ";
Evan Cheng3df447d2006-03-16 21:53:05 +00001310 DEBUG(L->dump());
1311#endif
1312
1313 // IVsByStride keeps IVs for one particular loop.
1314 IVsByStride.clear();
1315
Evan Chengf09f0eb2006-03-18 00:44:49 +00001316 // Sort the StrideOrder so we process larger strides first.
1317 std::stable_sort(StrideOrder.begin(), StrideOrder.end(), StrideCompare());
1318
Chris Lattnera091ff12005-08-09 00:18:09 +00001319 // Note: this processes each stride/type pair individually. All users passed
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001320 // into StrengthReduceStridedIVUsers have the same type AND stride. Also,
1321 // node that we iterate over IVUsesByStride indirectly by using StrideOrder.
1322 // This extra layer of indirection makes the ordering of strides deterministic
1323 // - not dependent on map order.
1324 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
1325 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1326 IVUsesByStride.find(StrideOrder[Stride]);
1327 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
Nate Begemane68bcd12005-07-30 00:15:07 +00001328 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001329 }
Nate Begemanb18121e2004-10-18 21:08:22 +00001330
1331 // Clean up after ourselves
1332 if (!DeadInsts.empty()) {
1333 DeleteTriviallyDeadInstructions(DeadInsts);
1334
Nate Begemane68bcd12005-07-30 00:15:07 +00001335 BasicBlock::iterator I = L->getHeader()->begin();
1336 PHINode *PN;
Chris Lattnerdcce49e2005-08-02 02:44:31 +00001337 while ((PN = dyn_cast<PHINode>(I))) {
Chris Lattner564900e2005-08-02 00:41:11 +00001338 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
1339
Chris Lattnerc6c4d992005-08-09 23:39:36 +00001340 // At this point, we know that we have killed one or more GEP
1341 // instructions. It is worth checking to see if the cann indvar is also
1342 // dead, so that we can remove it as well. The requirements for the cann
1343 // indvar to be considered dead are:
Nate Begemane68bcd12005-07-30 00:15:07 +00001344 // 1. the cann indvar has one use
1345 // 2. the use is an add instruction
1346 // 3. the add has one use
1347 // 4. the add is used by the cann indvar
1348 // If all four cases above are true, then we can remove both the add and
1349 // the cann indvar.
1350 // FIXME: this needs to eliminate an induction variable even if it's being
1351 // compared against some value to decide loop termination.
1352 if (PN->hasOneUse()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001353 Instruction *BO = dyn_cast<Instruction>(*PN->use_begin());
1354 if (BO && (isa<BinaryOperator>(BO) || isa<CmpInst>(BO))) {
1355 if (BO->hasOneUse() && PN == *(BO->use_begin())) {
Chris Lattner75a44e12005-08-02 02:52:02 +00001356 DeadInsts.insert(BO);
1357 // Break the cycle, then delete the PHI.
1358 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattner84e9baa2005-08-03 21:36:09 +00001359 SE->deleteInstructionFromRecords(PN);
Chris Lattner75a44e12005-08-02 02:52:02 +00001360 PN->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +00001361 }
Chris Lattner75a44e12005-08-02 02:52:02 +00001362 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001363 }
Nate Begemanb18121e2004-10-18 21:08:22 +00001364 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001365 DeleteTriviallyDeadInstructions(DeadInsts);
Nate Begemanb18121e2004-10-18 21:08:22 +00001366 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001367
Chris Lattner11e7a5e2005-08-05 01:30:11 +00001368 CastedPointers.clear();
Nate Begemane68bcd12005-07-30 00:15:07 +00001369 IVUsesByStride.clear();
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001370 StrideOrder.clear();
Nate Begemane68bcd12005-07-30 00:15:07 +00001371 return;
Nate Begemanb18121e2004-10-18 21:08:22 +00001372}