blob: 1908693cc29f10b2d4665a6534d5cd1f618dfa90 [file] [log] [blame]
Nate Begemaneaa13852004-10-18 21:08:22 +00001//===- LoopStrengthReduce.cpp - Strength Reduce GEPs in Loops -------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Nate Begemaneaa13852004-10-18 21:08:22 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by Nate Begeman and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
Nate Begemaneaa13852004-10-18 21:08:22 +00008//===----------------------------------------------------------------------===//
9//
10// This pass performs a strength reduction on array references inside loops that
11// have as one or more of their components the loop induction variable. This is
12// accomplished by creating a new Value to hold the initial value of the array
13// access for the first iteration, and then creating a new GEP instruction in
14// the loop to increment the value by the appropriate amount.
15//
Nate Begemaneaa13852004-10-18 21:08:22 +000016//===----------------------------------------------------------------------===//
17
Chris Lattnerbe3e5212005-08-03 23:30:08 +000018#define DEBUG_TYPE "loop-reduce"
Nate Begemaneaa13852004-10-18 21:08:22 +000019#include "llvm/Transforms/Scalar.h"
20#include "llvm/Constants.h"
21#include "llvm/Instructions.h"
22#include "llvm/Type.h"
Jeff Cohen2f3c9b72005-03-04 04:04:26 +000023#include "llvm/DerivedTypes.h"
Nate Begemaneaa13852004-10-18 21:08:22 +000024#include "llvm/Analysis/Dominators.h"
25#include "llvm/Analysis/LoopInfo.h"
Nate Begeman16997482005-07-30 00:15:07 +000026#include "llvm/Analysis/ScalarEvolutionExpander.h"
Nate Begemaneaa13852004-10-18 21:08:22 +000027#include "llvm/Support/CFG.h"
Nate Begeman16997482005-07-30 00:15:07 +000028#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnere0391be2005-08-12 22:06:11 +000029#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Nate Begemaneaa13852004-10-18 21:08:22 +000030#include "llvm/Transforms/Utils/Local.h"
Jeff Cohen2f3c9b72005-03-04 04:04:26 +000031#include "llvm/Target/TargetData.h"
Nate Begemaneaa13852004-10-18 21:08:22 +000032#include "llvm/ADT/Statistic.h"
Nate Begeman16997482005-07-30 00:15:07 +000033#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000034#include "llvm/Support/Compiler.h"
Evan Chengd277f2c2006-03-13 23:14:23 +000035#include "llvm/Target/TargetLowering.h"
Jeff Cohencfb1d422005-07-30 18:22:27 +000036#include <algorithm>
Nate Begemaneaa13852004-10-18 21:08:22 +000037#include <set>
38using namespace llvm;
39
Chris Lattner0e5f4992006-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 Begemaneaa13852004-10-18 21:08:22 +000043
Chris Lattner0e5f4992006-12-19 21:40:18 +000044namespace {
Chris Lattnerec3fb632005-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 Lattner010de252005-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 Lattnerc6bae652005-09-12 06:04:47 +000057 // instruction for a loop or uses dominated by the loop.
Chris Lattner010de252005-08-08 05:28:22 +000058 bool isUseOfPostIncrementedValue;
Chris Lattnerec3fb632005-08-03 22:21:05 +000059
60 IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
Chris Lattner010de252005-08-08 05:28:22 +000061 : Offset(Offs), User(U), OperandValToReplace(O),
62 isUseOfPostIncrementedValue(false) {}
Chris Lattnerec3fb632005-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 Begeman16997482005-07-30 00:15:07 +000070 /// Users - Keep track of all of the users of this stride as well as the
Chris Lattnerec3fb632005-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 Begeman16997482005-07-30 00:15:07 +000076 }
77 };
78
Evan Chengd1d6b5c2006-03-16 21:53:05 +000079 /// IVInfo - This structure keeps track of one IV expression inserted during
Evan Cheng21495772006-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 Chengd1d6b5c2006-03-16 21:53:05 +000082 struct IVExpr {
Evan Cheng21495772006-03-18 08:03:12 +000083 SCEVHandle Stride;
Evan Chengd1d6b5c2006-03-16 21:53:05 +000084 SCEVHandle Base;
85 PHINode *PHI;
86 Value *IncV;
87
Evan Cheng21495772006-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 Chengd1d6b5c2006-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 Cheng21495772006-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 Chengd1d6b5c2006-03-16 21:53:05 +0000104 }
105 };
Nate Begeman16997482005-07-30 00:15:07 +0000106
Chris Lattner95255282006-06-28 23:17:24 +0000107 class VISIBILITY_HIDDEN LoopStrengthReduce : public FunctionPass {
Nate Begemaneaa13852004-10-18 21:08:22 +0000108 LoopInfo *LI;
Chris Lattner88cac3d2006-01-11 05:10:20 +0000109 ETForest *EF;
Nate Begeman16997482005-07-30 00:15:07 +0000110 ScalarEvolution *SE;
111 const TargetData *TD;
112 const Type *UIntPtrTy;
Nate Begemaneaa13852004-10-18 21:08:22 +0000113 bool Changed;
Chris Lattner7e608bb2005-08-02 02:52:02 +0000114
Nate Begeman16997482005-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 Lattner50fad702005-08-10 00:45:21 +0000117 std::map<SCEVHandle, IVUsersOfOneStride> IVUsesByStride;
Nate Begeman16997482005-07-30 00:15:07 +0000118
Evan Chengd1d6b5c2006-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 Lattner7305ae22005-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 Lattner49f72e62005-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 Begeman16997482005-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 Chengd277f2c2006-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 Begemaneaa13852004-10-18 21:08:22 +0000141 public:
Evan Chengd1d6b5c2006-03-16 21:53:05 +0000142 LoopStrengthReduce(const TargetLowering *tli = NULL)
143 : TLI(tli) {
Jeff Cohen2f3c9b72005-03-04 04:04:26 +0000144 }
145
Nate Begemaneaa13852004-10-18 21:08:22 +0000146 virtual bool runOnFunction(Function &) {
147 LI = &getAnalysis<LoopInfo>();
Chris Lattner88cac3d2006-01-11 05:10:20 +0000148 EF = &getAnalysis<ETForest>();
Nate Begeman16997482005-07-30 00:15:07 +0000149 SE = &getAnalysis<ScalarEvolution>();
150 TD = &getAnalysis<TargetData>();
151 UIntPtrTy = TD->getIntPtrType();
Nate Begemaneaa13852004-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 Lattner49f72e62005-08-04 01:19:13 +0000156
Nate Begemaneaa13852004-10-18 21:08:22 +0000157 return Changed;
158 }
159
160 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattneraa96ae72005-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 Lattner88cac3d2006-01-11 05:10:20 +0000166 AU.addPreserved<ETForest>();
Chris Lattneraa96ae72005-08-17 06:35:16 +0000167 AU.addPreserved<ImmediateDominators>();
168 AU.addPreserved<DominanceFrontier>();
169 AU.addPreserved<DominatorTree>();
170
Jeff Cohenf465db62005-02-27 19:37:07 +0000171 AU.addRequiredID(LoopSimplifyID);
Nate Begemaneaa13852004-10-18 21:08:22 +0000172 AU.addRequired<LoopInfo>();
Chris Lattner88cac3d2006-01-11 05:10:20 +0000173 AU.addRequired<ETForest>();
Jeff Cohen2f3c9b72005-03-04 04:04:26 +0000174 AU.addRequired<TargetData>();
Nate Begeman16997482005-07-30 00:15:07 +0000175 AU.addRequired<ScalarEvolution>();
Nate Begemaneaa13852004-10-18 21:08:22 +0000176 }
Chris Lattner49f72e62005-08-04 01:19:13 +0000177
178 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
179 ///
Reid Spencer3ba68b92006-12-13 08:06:42 +0000180 Value *getCastedVersionOf(Instruction::CastOps opcode, Value *V);
Chris Lattner49f72e62005-08-04 01:19:13 +0000181private:
Nate Begemaneaa13852004-10-18 21:08:22 +0000182 void runOnLoop(Loop *L);
Chris Lattner3416e5f2005-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 Lattner010de252005-08-08 05:28:22 +0000187 void OptimizeIndvars(Loop *L);
Nate Begeman16997482005-07-30 00:15:07 +0000188
Evan Cheng31e77312006-07-18 19:07:58 +0000189 unsigned CheckForIVReuse(const SCEVHandle&, IVExpr&, const Type*);
Evan Chengeb8f9e22006-03-17 19:52:23 +0000190
Chris Lattner50fad702005-08-10 00:45:21 +0000191 void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
192 IVUsersOfOneStride &Uses,
Chris Lattnerec3fb632005-08-03 22:21:05 +0000193 Loop *L, bool isOnlyStride);
Nate Begemaneaa13852004-10-18 21:08:22 +0000194 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
195 };
Chris Lattner7f8897f2006-08-27 22:42:52 +0000196 RegisterPass<LoopStrengthReduce> X("loop-reduce", "Loop Strength Reduction");
Nate Begemaneaa13852004-10-18 21:08:22 +0000197}
198
Evan Chengd1d6b5c2006-03-16 21:53:05 +0000199FunctionPass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
200 return new LoopStrengthReduce(TLI);
Nate Begemaneaa13852004-10-18 21:08:22 +0000201}
202
Reid Spencer4da49122006-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 Lattner49f72e62005-08-04 01:19:13 +0000205///
Reid Spencer3ba68b92006-12-13 08:06:42 +0000206Value *LoopStrengthReduce::getCastedVersionOf(Instruction::CastOps opcode,
207 Value *V) {
Chris Lattner49f72e62005-08-04 01:19:13 +0000208 if (V->getType() == UIntPtrTy) return V;
209 if (Constant *CB = dyn_cast<Constant>(V))
Reid Spencer3ba68b92006-12-13 08:06:42 +0000210 return ConstantExpr::getCast(opcode, CB, UIntPtrTy);
Chris Lattner49f72e62005-08-04 01:19:13 +0000211
212 Value *&New = CastedPointers[V];
213 if (New) return New;
214
Reid Spencer3ba68b92006-12-13 08:06:42 +0000215 New = SCEVExpander::InsertCastOfTo(opcode, V, UIntPtrTy);
Chris Lattner7db543f2005-08-04 19:08:16 +0000216 DeadInsts.insert(cast<Instruction>(New));
217 return New;
Chris Lattner49f72e62005-08-04 01:19:13 +0000218}
219
220
Nate Begemaneaa13852004-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 Cohen0456e4a2005-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 Lattner52d83e62005-08-03 21:36:09 +0000233 SE->deleteInstructionFromRecords(I);
234 I->eraseFromParent();
Nate Begemaneaa13852004-10-18 21:08:22 +0000235 Changed = true;
236 }
237 }
238}
239
Jeff Cohenf465db62005-02-27 19:37:07 +0000240
Chris Lattner3416e5f2005-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 Lattner87265ab2005-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 Lattner3416e5f2005-08-04 17:40:30 +0000248 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
Chris Lattner87265ab2005-08-09 23:39:36 +0000249 if (!GEP || SE->hasSCEV(GEP))
Chris Lattner3416e5f2005-08-04 17:40:30 +0000250 return SE->getSCEV(Exp);
251
Nate Begeman16997482005-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 Spencer3ba68b92006-12-13 08:06:42 +0000258 SCEVHandle GEPVal = SCEVUnknown::get(
259 getCastedVersionOf(Instruction::PtrToInt, GEP->getOperand(0)));
Nate Begeman16997482005-07-30 00:15:07 +0000260
261 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattner3416e5f2005-08-04 17:40:30 +0000262
263 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
Nate Begeman16997482005-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 Spencerb83eb642006-10-20 07:07:24 +0000269 unsigned Idx = cast<ConstantInt>(GEP->getOperand(i))->getZExtValue();
Nate Begeman16997482005-07-30 00:15:07 +0000270 uint64_t Offset = SL->MemberOffsets[Idx];
Chris Lattner3416e5f2005-08-04 17:40:30 +0000271 GEPVal = SCEVAddExpr::get(GEPVal,
272 SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy));
Nate Begeman16997482005-07-30 00:15:07 +0000273 } else {
Reid Spencer3ba68b92006-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 Lattner7db543f2005-08-04 19:08:16 +0000281 SCEVHandle Idx = SE->getSCEV(OpVal);
282
Chris Lattner3416e5f2005-08-04 17:40:30 +0000283 uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
284 if (TypeSize != 1)
285 Idx = SCEVMulExpr::get(Idx,
Reid Spencerb83eb642006-10-20 07:07:24 +0000286 SCEVConstant::get(ConstantInt::get(UIntPtrTy,
Chris Lattner3416e5f2005-08-04 17:40:30 +0000287 TypeSize)));
288 GEPVal = SCEVAddExpr::get(GEPVal, Idx);
Nate Begeman16997482005-07-30 00:15:07 +0000289 }
290 }
291
Chris Lattner87265ab2005-08-09 23:39:36 +0000292 SE->setSCEV(GEP, GEPVal);
Chris Lattner3416e5f2005-08-04 17:40:30 +0000293 return GEPVal;
Nate Begeman16997482005-07-30 00:15:07 +0000294}
295
Chris Lattner7db543f2005-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 Lattner50fad702005-08-10 00:45:21 +0000301 SCEVHandle &Start, SCEVHandle &Stride) {
Chris Lattner7db543f2005-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 Spencer3ed469c2006-11-02 20:25:50 +0000318 } else if (isa<SCEVAddRecExpr>(SH)) {
Chris Lattner7db543f2005-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 Lattner7db543f2005-08-04 19:08:16 +0000332 if (!isa<SCEVConstant>(AddRec->getOperand(1)))
Bill Wendlingb7427032006-11-26 09:46:52 +0000333 DOUT << "[" << L->getHeader()->getName()
334 << "] Variable stride: " << *AddRec << "\n";
Chris Lattner7db543f2005-08-04 19:08:16 +0000335
Chris Lattner50fad702005-08-10 00:45:21 +0000336 Stride = AddRec->getOperand(1);
337 // Check that all constant strides are the unsigned type, we don't want to
338 // have two IV's one of signed stride 4 and one of unsigned stride 4 to not be
339 // merged.
340 assert((!isa<SCEVConstant>(Stride) || Stride->getType()->isUnsigned()) &&
Chris Lattner7db543f2005-08-04 19:08:16 +0000341 "Constants should be canonicalized to unsigned!");
Chris Lattner50fad702005-08-10 00:45:21 +0000342
Chris Lattner7db543f2005-08-04 19:08:16 +0000343 return true;
344}
345
Chris Lattner0ae33eb2005-10-03 01:04:44 +0000346/// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
347/// and now we need to decide whether the user should use the preinc or post-inc
348/// value. If this user should use the post-inc version of the IV, return true.
349///
350/// Choosing wrong here can break dominance properties (if we choose to use the
351/// post-inc value when we cannot) or it can end up adding extra live-ranges to
352/// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
353/// should use the post-inc value).
354static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
Chris Lattner88cac3d2006-01-11 05:10:20 +0000355 Loop *L, ETForest *EF, Pass *P) {
Chris Lattner0ae33eb2005-10-03 01:04:44 +0000356 // If the user is in the loop, use the preinc value.
357 if (L->contains(User->getParent())) return false;
358
Chris Lattner5e8ca662005-10-03 02:50:05 +0000359 BasicBlock *LatchBlock = L->getLoopLatch();
360
361 // Ok, the user is outside of the loop. If it is dominated by the latch
362 // block, use the post-inc value.
Chris Lattner88cac3d2006-01-11 05:10:20 +0000363 if (EF->dominates(LatchBlock, User->getParent()))
Chris Lattner5e8ca662005-10-03 02:50:05 +0000364 return true;
365
366 // There is one case we have to be careful of: PHI nodes. These little guys
367 // can live in blocks that do not dominate the latch block, but (since their
368 // uses occur in the predecessor block, not the block the PHI lives in) should
369 // still use the post-inc value. Check for this case now.
370 PHINode *PN = dyn_cast<PHINode>(User);
371 if (!PN) return false; // not a phi, not dominated by latch block.
372
373 // Look at all of the uses of IV by the PHI node. If any use corresponds to
374 // a block that is not dominated by the latch block, give up and use the
375 // preincremented value.
376 unsigned NumUses = 0;
377 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
378 if (PN->getIncomingValue(i) == IV) {
379 ++NumUses;
Chris Lattner88cac3d2006-01-11 05:10:20 +0000380 if (!EF->dominates(LatchBlock, PN->getIncomingBlock(i)))
Chris Lattner5e8ca662005-10-03 02:50:05 +0000381 return false;
382 }
383
384 // Okay, all uses of IV by PN are in predecessor blocks that really are
385 // dominated by the latch block. Split the critical edges and use the
386 // post-incremented value.
387 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
388 if (PN->getIncomingValue(i) == IV) {
Chris Lattner0997fad2006-10-28 06:45:33 +0000389 SplitCriticalEdge(PN->getIncomingBlock(i), PN->getParent(), P,
390 true);
Chris Lattner1b9c8e72006-10-28 00:59:20 +0000391 // Splitting the critical edge can reduce the number of entries in this
392 // PHI.
393 e = PN->getNumIncomingValues();
Chris Lattner5e8ca662005-10-03 02:50:05 +0000394 if (--NumUses == 0) break;
395 }
396
397 return true;
Chris Lattner0ae33eb2005-10-03 01:04:44 +0000398}
399
400
401
Nate Begeman16997482005-07-30 00:15:07 +0000402/// AddUsersIfInteresting - Inspect the specified instruction. If it is a
403/// reducible SCEV, recursively add its users to the IVUsesByStride set and
404/// return true. Otherwise, return false.
Chris Lattner3416e5f2005-08-04 17:40:30 +0000405bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
406 std::set<Instruction*> &Processed) {
Chris Lattner63ad7962005-10-21 05:45:41 +0000407 if (!I->getType()->isInteger() && !isa<PointerType>(I->getType()))
408 return false; // Void and FP expressions cannot be reduced.
Chris Lattner3416e5f2005-08-04 17:40:30 +0000409 if (!Processed.insert(I).second)
410 return true; // Instruction already handled.
411
Chris Lattner7db543f2005-08-04 19:08:16 +0000412 // Get the symbolic expression for this instruction.
Chris Lattner3416e5f2005-08-04 17:40:30 +0000413 SCEVHandle ISE = GetExpressionSCEV(I, L);
Chris Lattner7db543f2005-08-04 19:08:16 +0000414 if (isa<SCEVCouldNotCompute>(ISE)) return false;
Chris Lattner3416e5f2005-08-04 17:40:30 +0000415
Chris Lattner7db543f2005-08-04 19:08:16 +0000416 // Get the start and stride for this expression.
417 SCEVHandle Start = SCEVUnknown::getIntegerSCEV(0, ISE->getType());
Chris Lattner50fad702005-08-10 00:45:21 +0000418 SCEVHandle Stride = Start;
Chris Lattner7db543f2005-08-04 19:08:16 +0000419 if (!getSCEVStartAndStride(ISE, L, Start, Stride))
420 return false; // Non-reducible symbolic expression, bail out.
421
Nate Begeman16997482005-07-30 00:15:07 +0000422 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){
423 Instruction *User = cast<Instruction>(*UI);
424
425 // Do not infinitely recurse on PHI nodes.
Chris Lattner396b2ba2005-09-13 02:09:55 +0000426 if (isa<PHINode>(User) && Processed.count(User))
Nate Begeman16997482005-07-30 00:15:07 +0000427 continue;
428
429 // If this is an instruction defined in a nested loop, or outside this loop,
Chris Lattnerf9186592005-08-04 00:14:11 +0000430 // don't recurse into it.
Chris Lattner7db543f2005-08-04 19:08:16 +0000431 bool AddUserToIVUsers = false;
Chris Lattnerf9186592005-08-04 00:14:11 +0000432 if (LI->getLoopFor(User->getParent()) != L) {
Bill Wendlingb7427032006-11-26 09:46:52 +0000433 DOUT << "FOUND USER in other loop: " << *User
434 << " OF SCEV: " << *ISE << "\n";
Chris Lattner7db543f2005-08-04 19:08:16 +0000435 AddUserToIVUsers = true;
Chris Lattner3416e5f2005-08-04 17:40:30 +0000436 } else if (!AddUsersIfInteresting(User, L, Processed)) {
Bill Wendlingb7427032006-11-26 09:46:52 +0000437 DOUT << "FOUND USER: " << *User
438 << " OF SCEV: " << *ISE << "\n";
Chris Lattner7db543f2005-08-04 19:08:16 +0000439 AddUserToIVUsers = true;
440 }
Nate Begeman16997482005-07-30 00:15:07 +0000441
Chris Lattner7db543f2005-08-04 19:08:16 +0000442 if (AddUserToIVUsers) {
Chris Lattner7305ae22005-10-09 06:20:55 +0000443 IVUsersOfOneStride &StrideUses = IVUsesByStride[Stride];
444 if (StrideUses.Users.empty()) // First occurance of this stride?
445 StrideOrder.push_back(Stride);
446
Chris Lattnera4479ad2005-08-04 00:40:47 +0000447 // Okay, we found a user that we cannot reduce. Analyze the instruction
Chris Lattnerc6bae652005-09-12 06:04:47 +0000448 // and decide what to do with it. If we are a use inside of the loop, use
449 // the value before incrementation, otherwise use it after incrementation.
Chris Lattner88cac3d2006-01-11 05:10:20 +0000450 if (IVUseShouldUsePostIncValue(User, I, L, EF, this)) {
Chris Lattnerc6bae652005-09-12 06:04:47 +0000451 // The value used will be incremented by the stride more than we are
452 // expecting, so subtract this off.
453 SCEVHandle NewStart = SCEV::getMinusSCEV(Start, Stride);
Chris Lattner7305ae22005-10-09 06:20:55 +0000454 StrideUses.addUser(NewStart, User, I);
455 StrideUses.Users.back().isUseOfPostIncrementedValue = true;
Bill Wendlingb7427032006-11-26 09:46:52 +0000456 DOUT << " USING POSTINC SCEV, START=" << *NewStart<< "\n";
Chris Lattner0ae33eb2005-10-03 01:04:44 +0000457 } else {
Chris Lattner7305ae22005-10-09 06:20:55 +0000458 StrideUses.addUser(Start, User, I);
Chris Lattnerc6bae652005-09-12 06:04:47 +0000459 }
Nate Begeman16997482005-07-30 00:15:07 +0000460 }
461 }
462 return true;
463}
464
465namespace {
466 /// BasedUser - For a particular base value, keep information about how we've
467 /// partitioned the expression so far.
468 struct BasedUser {
Chris Lattnera553b0c2005-08-08 22:56:21 +0000469 /// Base - The Base value for the PHI node that needs to be inserted for
470 /// this use. As the use is processed, information gets moved from this
471 /// field to the Imm field (below). BasedUser values are sorted by this
472 /// field.
473 SCEVHandle Base;
474
Nate Begeman16997482005-07-30 00:15:07 +0000475 /// Inst - The instruction using the induction variable.
476 Instruction *Inst;
477
Chris Lattnerec3fb632005-08-03 22:21:05 +0000478 /// OperandValToReplace - The operand value of Inst to replace with the
479 /// EmittedBase.
480 Value *OperandValToReplace;
Nate Begeman16997482005-07-30 00:15:07 +0000481
482 /// Imm - The immediate value that should be added to the base immediately
483 /// before Inst, because it will be folded into the imm field of the
484 /// instruction.
485 SCEVHandle Imm;
486
487 /// EmittedBase - The actual value* to use for the base value of this
488 /// operation. This is null if we should just use zero so far.
489 Value *EmittedBase;
490
Chris Lattner010de252005-08-08 05:28:22 +0000491 // isUseOfPostIncrementedValue - True if this should use the
492 // post-incremented version of this IV, not the preincremented version.
493 // This can only be set in special cases, such as the terminating setcc
Chris Lattnerc6bae652005-09-12 06:04:47 +0000494 // instruction for a loop and uses outside the loop that are dominated by
495 // the loop.
Chris Lattner010de252005-08-08 05:28:22 +0000496 bool isUseOfPostIncrementedValue;
Chris Lattnera553b0c2005-08-08 22:56:21 +0000497
498 BasedUser(IVStrideUse &IVSU)
499 : Base(IVSU.Offset), Inst(IVSU.User),
500 OperandValToReplace(IVSU.OperandValToReplace),
501 Imm(SCEVUnknown::getIntegerSCEV(0, Base->getType())), EmittedBase(0),
502 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
Nate Begeman16997482005-07-30 00:15:07 +0000503
Chris Lattner2114b272005-08-04 20:03:32 +0000504 // Once we rewrite the code to insert the new IVs we want, update the
505 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
506 // to it.
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000507 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattnerc60fb082005-08-12 22:22:17 +0000508 SCEVExpander &Rewriter, Loop *L,
509 Pass *P);
Chris Lattner221fc3c2006-02-04 07:36:50 +0000510
511 Value *InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
512 SCEVExpander &Rewriter,
513 Instruction *IP, Loop *L);
Nate Begeman16997482005-07-30 00:15:07 +0000514 void dump() const;
515 };
516}
517
518void BasedUser::dump() const {
Bill Wendlinge8156192006-12-07 01:30:32 +0000519 cerr << " Base=" << *Base;
520 cerr << " Imm=" << *Imm;
Nate Begeman16997482005-07-30 00:15:07 +0000521 if (EmittedBase)
Bill Wendlinge8156192006-12-07 01:30:32 +0000522 cerr << " EB=" << *EmittedBase;
Nate Begeman16997482005-07-30 00:15:07 +0000523
Bill Wendlinge8156192006-12-07 01:30:32 +0000524 cerr << " Inst: " << *Inst;
Nate Begeman16997482005-07-30 00:15:07 +0000525}
526
Chris Lattner221fc3c2006-02-04 07:36:50 +0000527Value *BasedUser::InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
528 SCEVExpander &Rewriter,
529 Instruction *IP, Loop *L) {
530 // Figure out where we *really* want to insert this code. In particular, if
531 // the user is inside of a loop that is nested inside of L, we really don't
532 // want to insert this expression before the user, we'd rather pull it out as
533 // many loops as possible.
534 LoopInfo &LI = Rewriter.getLoopInfo();
535 Instruction *BaseInsertPt = IP;
536
537 // Figure out the most-nested loop that IP is in.
538 Loop *InsertLoop = LI.getLoopFor(IP->getParent());
539
540 // If InsertLoop is not L, and InsertLoop is nested inside of L, figure out
541 // the preheader of the outer-most loop where NewBase is not loop invariant.
542 while (InsertLoop && NewBase->isLoopInvariant(InsertLoop)) {
543 BaseInsertPt = InsertLoop->getLoopPreheader()->getTerminator();
544 InsertLoop = InsertLoop->getParentLoop();
545 }
546
547 // If there is no immediate value, skip the next part.
548 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Imm))
549 if (SC->getValue()->isNullValue())
550 return Rewriter.expandCodeFor(NewBase, BaseInsertPt,
551 OperandValToReplace->getType());
552
553 Value *Base = Rewriter.expandCodeFor(NewBase, BaseInsertPt);
554
555 // Always emit the immediate (if non-zero) into the same block as the user.
556 SCEVHandle NewValSCEV = SCEVAddExpr::get(SCEVUnknown::get(Base), Imm);
557 return Rewriter.expandCodeFor(NewValSCEV, IP,
558 OperandValToReplace->getType());
559}
560
561
Chris Lattner2114b272005-08-04 20:03:32 +0000562// Once we rewrite the code to insert the new IVs we want, update the
563// operands of Inst to use the new expression 'NewBase', with 'Imm' added
564// to it.
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000565void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattnere0391be2005-08-12 22:06:11 +0000566 SCEVExpander &Rewriter,
Chris Lattnerc60fb082005-08-12 22:22:17 +0000567 Loop *L, Pass *P) {
Chris Lattner2114b272005-08-04 20:03:32 +0000568 if (!isa<PHINode>(Inst)) {
Chris Lattner221fc3c2006-02-04 07:36:50 +0000569 Value *NewVal = InsertCodeForBaseAtPosition(NewBase, Rewriter, Inst, L);
Chris Lattner2114b272005-08-04 20:03:32 +0000570 // Replace the use of the operand Value with the new Phi we just created.
571 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
Bill Wendlingb7427032006-11-26 09:46:52 +0000572 DOUT << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst;
Chris Lattner2114b272005-08-04 20:03:32 +0000573 return;
574 }
575
576 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
Chris Lattnerc41e3452005-08-10 00:35:32 +0000577 // expression into each operand block that uses it. Note that PHI nodes can
578 // have multiple entries for the same predecessor. We use a map to make sure
579 // that a PHI node only has a single Value* for each predecessor (which also
580 // prevents us from inserting duplicate code in some blocks).
581 std::map<BasicBlock*, Value*> InsertedCode;
Chris Lattner2114b272005-08-04 20:03:32 +0000582 PHINode *PN = cast<PHINode>(Inst);
583 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
584 if (PN->getIncomingValue(i) == OperandValToReplace) {
Chris Lattnere0391be2005-08-12 22:06:11 +0000585 // If this is a critical edge, split the edge so that we do not insert the
Chris Lattner396b2ba2005-09-13 02:09:55 +0000586 // code on all predecessor/successor paths. We do this unless this is the
587 // canonical backedge for this loop, as this can make some inserted code
588 // be in an illegal position.
Chris Lattner37edbf02005-10-03 00:31:52 +0000589 BasicBlock *PHIPred = PN->getIncomingBlock(i);
590 if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
591 (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
Chris Lattner37edbf02005-10-03 00:31:52 +0000592
Chris Lattneraa96ae72005-08-17 06:35:16 +0000593 // First step, split the critical edge.
Chris Lattner0997fad2006-10-28 06:45:33 +0000594 SplitCriticalEdge(PHIPred, PN->getParent(), P, true);
Chris Lattnerc60fb082005-08-12 22:22:17 +0000595
Chris Lattneraa96ae72005-08-17 06:35:16 +0000596 // Next step: move the basic block. In particular, if the PHI node
597 // is outside of the loop, and PredTI is in the loop, we want to
598 // move the block to be immediately before the PHI block, not
599 // immediately after PredTI.
Chris Lattner37edbf02005-10-03 00:31:52 +0000600 if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
Chris Lattneraa96ae72005-08-17 06:35:16 +0000601 BasicBlock *NewBB = PN->getIncomingBlock(i);
602 NewBB->moveBefore(PN->getParent());
Chris Lattnere0391be2005-08-12 22:06:11 +0000603 }
Chris Lattner1b9c8e72006-10-28 00:59:20 +0000604
605 // Splitting the edge can reduce the number of PHI entries we have.
606 e = PN->getNumIncomingValues();
Chris Lattnere0391be2005-08-12 22:06:11 +0000607 }
Chris Lattner2114b272005-08-04 20:03:32 +0000608
Chris Lattnerc41e3452005-08-10 00:35:32 +0000609 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
610 if (!Code) {
611 // Insert the code into the end of the predecessor block.
Chris Lattner221fc3c2006-02-04 07:36:50 +0000612 Instruction *InsertPt = PN->getIncomingBlock(i)->getTerminator();
613 Code = InsertCodeForBaseAtPosition(NewBase, Rewriter, InsertPt, L);
Chris Lattnerc41e3452005-08-10 00:35:32 +0000614 }
Chris Lattner2114b272005-08-04 20:03:32 +0000615
616 // Replace the use of the operand Value with the new Phi we just created.
Chris Lattnerc41e3452005-08-10 00:35:32 +0000617 PN->setIncomingValue(i, Code);
Chris Lattner2114b272005-08-04 20:03:32 +0000618 Rewriter.clear();
619 }
620 }
Bill Wendlingb7427032006-11-26 09:46:52 +0000621 DOUT << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst;
Chris Lattner2114b272005-08-04 20:03:32 +0000622}
623
624
Nate Begeman16997482005-07-30 00:15:07 +0000625/// isTargetConstant - Return true if the following can be referenced by the
626/// immediate field of a target instruction.
Evan Chengd277f2c2006-03-13 23:14:23 +0000627static bool isTargetConstant(const SCEVHandle &V, const TargetLowering *TLI) {
Chris Lattner3821e472005-08-08 06:25:50 +0000628 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
Chris Lattnere08dc622005-12-05 18:23:57 +0000629 int64_t V = SC->getValue()->getSExtValue();
Evan Chengd277f2c2006-03-13 23:14:23 +0000630 if (TLI)
631 return TLI->isLegalAddressImmediate(V);
632 else
633 // Defaults to PPC. PPC allows a sign-extended 16-bit immediate field.
634 return (V > -(1 << 16) && V < (1 << 16)-1);
Chris Lattner3821e472005-08-08 06:25:50 +0000635 }
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000636
Nate Begeman16997482005-07-30 00:15:07 +0000637 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
638 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
Reid Spencer3da59db2006-11-27 01:05:10 +0000639 if (CE->getOpcode() == Instruction::PtrToInt) {
Evan Chengd277f2c2006-03-13 23:14:23 +0000640 Constant *Op0 = CE->getOperand(0);
Reid Spencer3da59db2006-11-27 01:05:10 +0000641 if (isa<GlobalValue>(Op0) && TLI &&
Evan Chengd277f2c2006-03-13 23:14:23 +0000642 TLI->isLegalAddressImmediate(cast<GlobalValue>(Op0)))
Nate Begeman16997482005-07-30 00:15:07 +0000643 return true;
Evan Chengd277f2c2006-03-13 23:14:23 +0000644 }
Nate Begeman16997482005-07-30 00:15:07 +0000645 return false;
646}
647
Chris Lattner44b807e2005-08-08 22:32:34 +0000648/// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
649/// loop varying to the Imm operand.
650static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
651 Loop *L) {
652 if (Val->isLoopInvariant(L)) return; // Nothing to do.
653
654 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
655 std::vector<SCEVHandle> NewOps;
656 NewOps.reserve(SAE->getNumOperands());
657
658 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
659 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
660 // If this is a loop-variant expression, it must stay in the immediate
661 // field of the expression.
662 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
663 } else {
664 NewOps.push_back(SAE->getOperand(i));
665 }
666
667 if (NewOps.empty())
668 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
669 else
670 Val = SCEVAddExpr::get(NewOps);
671 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
672 // Try to pull immediates out of the start value of nested addrec's.
673 SCEVHandle Start = SARE->getStart();
674 MoveLoopVariantsToImediateField(Start, Imm, L);
675
676 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
677 Ops[0] = Start;
678 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
679 } else {
680 // Otherwise, all of Val is variant, move the whole thing over.
681 Imm = SCEVAddExpr::get(Imm, Val);
682 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
683 }
684}
685
686
Chris Lattner26d91f12005-08-04 22:34:05 +0000687/// MoveImmediateValues - Look at Val, and pull out any additions of constants
Nate Begeman16997482005-07-30 00:15:07 +0000688/// that can fit into the immediate field of instructions in the target.
Chris Lattner26d91f12005-08-04 22:34:05 +0000689/// Accumulate these immediate values into the Imm value.
Evan Chengd277f2c2006-03-13 23:14:23 +0000690static void MoveImmediateValues(const TargetLowering *TLI,
691 SCEVHandle &Val, SCEVHandle &Imm,
Chris Lattner26d91f12005-08-04 22:34:05 +0000692 bool isAddress, Loop *L) {
Chris Lattner7a658392005-08-03 23:44:42 +0000693 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
Chris Lattner26d91f12005-08-04 22:34:05 +0000694 std::vector<SCEVHandle> NewOps;
695 NewOps.reserve(SAE->getNumOperands());
696
Chris Lattner221fc3c2006-02-04 07:36:50 +0000697 for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
698 SCEVHandle NewOp = SAE->getOperand(i);
Evan Chengd277f2c2006-03-13 23:14:23 +0000699 MoveImmediateValues(TLI, NewOp, Imm, isAddress, L);
Chris Lattner221fc3c2006-02-04 07:36:50 +0000700
701 if (!NewOp->isLoopInvariant(L)) {
Chris Lattner7db543f2005-08-04 19:08:16 +0000702 // If this is a loop-variant expression, it must stay in the immediate
703 // field of the expression.
Chris Lattner221fc3c2006-02-04 07:36:50 +0000704 Imm = SCEVAddExpr::get(Imm, NewOp);
Chris Lattner26d91f12005-08-04 22:34:05 +0000705 } else {
Chris Lattner221fc3c2006-02-04 07:36:50 +0000706 NewOps.push_back(NewOp);
Nate Begeman16997482005-07-30 00:15:07 +0000707 }
Chris Lattner221fc3c2006-02-04 07:36:50 +0000708 }
Chris Lattner26d91f12005-08-04 22:34:05 +0000709
710 if (NewOps.empty())
711 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
712 else
713 Val = SCEVAddExpr::get(NewOps);
714 return;
Chris Lattner7a658392005-08-03 23:44:42 +0000715 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
716 // Try to pull immediates out of the start value of nested addrec's.
Chris Lattner26d91f12005-08-04 22:34:05 +0000717 SCEVHandle Start = SARE->getStart();
Evan Chengd277f2c2006-03-13 23:14:23 +0000718 MoveImmediateValues(TLI, Start, Imm, isAddress, L);
Chris Lattner26d91f12005-08-04 22:34:05 +0000719
720 if (Start != SARE->getStart()) {
721 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
722 Ops[0] = Start;
723 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
724 }
725 return;
Chris Lattner221fc3c2006-02-04 07:36:50 +0000726 } else if (SCEVMulExpr *SME = dyn_cast<SCEVMulExpr>(Val)) {
727 // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
Evan Chengd277f2c2006-03-13 23:14:23 +0000728 if (isAddress && isTargetConstant(SME->getOperand(0), TLI) &&
Chris Lattner221fc3c2006-02-04 07:36:50 +0000729 SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
730
731 SCEVHandle SubImm = SCEVUnknown::getIntegerSCEV(0, Val->getType());
732 SCEVHandle NewOp = SME->getOperand(1);
Evan Chengd277f2c2006-03-13 23:14:23 +0000733 MoveImmediateValues(TLI, NewOp, SubImm, isAddress, L);
Chris Lattner221fc3c2006-02-04 07:36:50 +0000734
735 // If we extracted something out of the subexpressions, see if we can
736 // simplify this!
737 if (NewOp != SME->getOperand(1)) {
738 // Scale SubImm up by "8". If the result is a target constant, we are
739 // good.
740 SubImm = SCEVMulExpr::get(SubImm, SME->getOperand(0));
Evan Chengd277f2c2006-03-13 23:14:23 +0000741 if (isTargetConstant(SubImm, TLI)) {
Chris Lattner221fc3c2006-02-04 07:36:50 +0000742 // Accumulate the immediate.
743 Imm = SCEVAddExpr::get(Imm, SubImm);
744
745 // Update what is left of 'Val'.
746 Val = SCEVMulExpr::get(SME->getOperand(0), NewOp);
747 return;
748 }
749 }
750 }
Nate Begeman16997482005-07-30 00:15:07 +0000751 }
752
Chris Lattner26d91f12005-08-04 22:34:05 +0000753 // Loop-variant expressions must stay in the immediate field of the
754 // expression.
Evan Chengd277f2c2006-03-13 23:14:23 +0000755 if ((isAddress && isTargetConstant(Val, TLI)) ||
Chris Lattner26d91f12005-08-04 22:34:05 +0000756 !Val->isLoopInvariant(L)) {
757 Imm = SCEVAddExpr::get(Imm, Val);
758 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
759 return;
Chris Lattner7a2ca562005-08-04 19:26:19 +0000760 }
Chris Lattner26d91f12005-08-04 22:34:05 +0000761
762 // Otherwise, no immediates to move.
Nate Begeman16997482005-07-30 00:15:07 +0000763}
764
Chris Lattner934520a2005-08-13 07:27:18 +0000765
Chris Lattner7e79b382006-08-03 06:34:50 +0000766/// SeparateSubExprs - Decompose Expr into all of the subexpressions that are
767/// added together. This is used to reassociate common addition subexprs
768/// together for maximal sharing when rewriting bases.
Chris Lattner934520a2005-08-13 07:27:18 +0000769static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
770 SCEVHandle Expr) {
771 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
772 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
773 SeparateSubExprs(SubExprs, AE->getOperand(j));
774 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
775 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Expr->getType());
776 if (SARE->getOperand(0) == Zero) {
777 SubExprs.push_back(Expr);
778 } else {
779 // Compute the addrec with zero as its base.
780 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
781 Ops[0] = Zero; // Start with zero base.
782 SubExprs.push_back(SCEVAddRecExpr::get(Ops, SARE->getLoop()));
783
784
785 SeparateSubExprs(SubExprs, SARE->getOperand(0));
786 }
787 } else if (!isa<SCEVConstant>(Expr) ||
788 !cast<SCEVConstant>(Expr)->getValue()->isNullValue()) {
789 // Do not add zero.
790 SubExprs.push_back(Expr);
791 }
792}
793
794
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000795/// RemoveCommonExpressionsFromUseBases - Look through all of the uses in Bases,
796/// removing any common subexpressions from it. Anything truly common is
797/// removed, accumulated, and returned. This looks for things like (a+b+c) and
798/// (a+c+d) -> (a+c). The common expression is *removed* from the Bases.
799static SCEVHandle
800RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses) {
801 unsigned NumUses = Uses.size();
802
803 // Only one use? Use its base, regardless of what it is!
804 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Uses[0].Base->getType());
805 SCEVHandle Result = Zero;
806 if (NumUses == 1) {
807 std::swap(Result, Uses[0].Base);
808 return Result;
809 }
810
811 // To find common subexpressions, count how many of Uses use each expression.
812 // If any subexpressions are used Uses.size() times, they are common.
813 std::map<SCEVHandle, unsigned> SubExpressionUseCounts;
814
Chris Lattnerd6155e92005-10-11 18:41:04 +0000815 // UniqueSubExprs - Keep track of all of the subexpressions we see in the
816 // order we see them.
817 std::vector<SCEVHandle> UniqueSubExprs;
818
Chris Lattner934520a2005-08-13 07:27:18 +0000819 std::vector<SCEVHandle> SubExprs;
820 for (unsigned i = 0; i != NumUses; ++i) {
821 // If the base is zero (which is common), return zero now, there are no
822 // CSEs we can find.
823 if (Uses[i].Base == Zero) return Zero;
824
825 // Split the expression into subexprs.
826 SeparateSubExprs(SubExprs, Uses[i].Base);
827 // Add one to SubExpressionUseCounts for each subexpr present.
828 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
Chris Lattnerd6155e92005-10-11 18:41:04 +0000829 if (++SubExpressionUseCounts[SubExprs[j]] == 1)
830 UniqueSubExprs.push_back(SubExprs[j]);
Chris Lattner934520a2005-08-13 07:27:18 +0000831 SubExprs.clear();
832 }
833
Chris Lattnerd6155e92005-10-11 18:41:04 +0000834 // Now that we know how many times each is used, build Result. Iterate over
835 // UniqueSubexprs so that we have a stable ordering.
836 for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
837 std::map<SCEVHandle, unsigned>::iterator I =
838 SubExpressionUseCounts.find(UniqueSubExprs[i]);
839 assert(I != SubExpressionUseCounts.end() && "Entry not found?");
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000840 if (I->second == NumUses) { // Found CSE!
841 Result = SCEVAddExpr::get(Result, I->first);
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000842 } else {
843 // Remove non-cse's from SubExpressionUseCounts.
Chris Lattnerd6155e92005-10-11 18:41:04 +0000844 SubExpressionUseCounts.erase(I);
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000845 }
Chris Lattnerd6155e92005-10-11 18:41:04 +0000846 }
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000847
848 // If we found no CSE's, return now.
849 if (Result == Zero) return Result;
850
851 // Otherwise, remove all of the CSE's we found from each of the base values.
Chris Lattner934520a2005-08-13 07:27:18 +0000852 for (unsigned i = 0; i != NumUses; ++i) {
853 // Split the expression into subexprs.
854 SeparateSubExprs(SubExprs, Uses[i].Base);
855
856 // Remove any common subexpressions.
857 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
858 if (SubExpressionUseCounts.count(SubExprs[j])) {
859 SubExprs.erase(SubExprs.begin()+j);
860 --j; --e;
861 }
862
863 // Finally, the non-shared expressions together.
864 if (SubExprs.empty())
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000865 Uses[i].Base = Zero;
Chris Lattner934520a2005-08-13 07:27:18 +0000866 else
867 Uses[i].Base = SCEVAddExpr::get(SubExprs);
Chris Lattner27e51422005-08-13 07:42:01 +0000868 SubExprs.clear();
Chris Lattner934520a2005-08-13 07:27:18 +0000869 }
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000870
871 return Result;
872}
873
Evan Chengd1d6b5c2006-03-16 21:53:05 +0000874/// isZero - returns true if the scalar evolution expression is zero.
875///
876static bool isZero(SCEVHandle &V) {
877 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V))
Reid Spencerb83eb642006-10-20 07:07:24 +0000878 return SC->getValue()->getZExtValue() == 0;
Evan Chengd1d6b5c2006-03-16 21:53:05 +0000879 return false;
880}
881
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000882
Evan Chengeb8f9e22006-03-17 19:52:23 +0000883/// CheckForIVReuse - Returns the multiple if the stride is the multiple
884/// of a previous stride and it is a legal value for the target addressing
885/// mode scale component. This allows the users of this stride to be rewritten
Evan Cheng21495772006-03-18 08:03:12 +0000886/// as prev iv * factor. It returns 0 if no reuse is possible.
Evan Chengeb8f9e22006-03-17 19:52:23 +0000887unsigned LoopStrengthReduce::CheckForIVReuse(const SCEVHandle &Stride,
Evan Cheng31e77312006-07-18 19:07:58 +0000888 IVExpr &IV, const Type *Ty) {
Evan Cheng21495772006-03-18 08:03:12 +0000889 if (!TLI) return 0;
Evan Chengeb8f9e22006-03-17 19:52:23 +0000890
891 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride)) {
Evan Cheng21495772006-03-18 08:03:12 +0000892 int64_t SInt = SC->getValue()->getSExtValue();
893 if (SInt == 1) return 0;
Evan Chengeb8f9e22006-03-17 19:52:23 +0000894
895 for (TargetLowering::legal_am_scale_iterator
896 I = TLI->legal_am_scale_begin(), E = TLI->legal_am_scale_end();
897 I != E; ++I) {
898 unsigned Scale = *I;
Reid Spencerad207262006-04-12 19:28:15 +0000899 if (unsigned(abs(SInt)) < Scale || (SInt % Scale) != 0)
Evan Chengeb8f9e22006-03-17 19:52:23 +0000900 continue;
901 std::map<SCEVHandle, IVsOfOneStride>::iterator SI =
902 IVsByStride.find(SCEVUnknown::getIntegerSCEV(SInt/Scale, Type::UIntTy));
903 if (SI == IVsByStride.end())
904 continue;
905 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
906 IE = SI->second.IVs.end(); II != IE; ++II)
907 // FIXME: Only handle base == 0 for now.
Evan Cheng31e77312006-07-18 19:07:58 +0000908 // Only reuse previous IV if it would not require a type conversion.
909 if (isZero(II->Base) &&
Reid Spencer3da59db2006-11-27 01:05:10 +0000910 II->Base->getType()->canLosslesslyBitCastTo(Ty)) {
Evan Chengeb8f9e22006-03-17 19:52:23 +0000911 IV = *II;
912 return Scale;
913 }
914 }
915 }
916
Evan Cheng21495772006-03-18 08:03:12 +0000917 return 0;
Evan Chengeb8f9e22006-03-17 19:52:23 +0000918}
919
Chris Lattner7e79b382006-08-03 06:34:50 +0000920/// PartitionByIsUseOfPostIncrementedValue - Simple boolean predicate that
921/// returns true if Val's isUseOfPostIncrementedValue is true.
922static bool PartitionByIsUseOfPostIncrementedValue(const BasedUser &Val) {
923 return Val.isUseOfPostIncrementedValue;
924}
Evan Chengeb8f9e22006-03-17 19:52:23 +0000925
Nate Begeman16997482005-07-30 00:15:07 +0000926/// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
927/// stride of IV. All of the users may have different starting values, and this
928/// may not be the only stride (we know it is if isOnlyStride is true).
Chris Lattner50fad702005-08-10 00:45:21 +0000929void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
Chris Lattnerec3fb632005-08-03 22:21:05 +0000930 IVUsersOfOneStride &Uses,
931 Loop *L,
Nate Begeman16997482005-07-30 00:15:07 +0000932 bool isOnlyStride) {
933 // Transform our list of users and offsets to a bit more complex table. In
Chris Lattnera553b0c2005-08-08 22:56:21 +0000934 // this new vector, each 'BasedUser' contains 'Base' the base of the
935 // strided accessas well as the old information from Uses. We progressively
936 // move information from the Base field to the Imm field, until we eventually
937 // have the full access expression to rewrite the use.
938 std::vector<BasedUser> UsersToProcess;
Nate Begeman16997482005-07-30 00:15:07 +0000939 UsersToProcess.reserve(Uses.Users.size());
Chris Lattnera553b0c2005-08-08 22:56:21 +0000940 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
941 UsersToProcess.push_back(Uses.Users[i]);
942
943 // Move any loop invariant operands from the offset field to the immediate
944 // field of the use, so that we don't try to use something before it is
945 // computed.
946 MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
947 UsersToProcess.back().Imm, L);
948 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
Chris Lattner26d91f12005-08-04 22:34:05 +0000949 "Base value is not loop invariant!");
Nate Begeman16997482005-07-30 00:15:07 +0000950 }
Evan Chengeb8f9e22006-03-17 19:52:23 +0000951
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000952 // We now have a whole bunch of uses of like-strided induction variables, but
953 // they might all have different bases. We want to emit one PHI node for this
954 // stride which we fold as many common expressions (between the IVs) into as
955 // possible. Start by identifying the common expressions in the base values
956 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
957 // "A+B"), emit it to the preheader, then remove the expression from the
958 // UsersToProcess base values.
Evan Chengd1d6b5c2006-03-16 21:53:05 +0000959 SCEVHandle CommonExprs =
960 RemoveCommonExpressionsFromUseBases(UsersToProcess);
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000961
Evan Cheng31e77312006-07-18 19:07:58 +0000962 // Check if it is possible to reuse a IV with stride that is factor of this
963 // stride. And the multiple is a number that can be encoded in the scale
964 // field of the target addressing mode.
965 PHINode *NewPHI = NULL;
966 Value *IncV = NULL;
967 IVExpr ReuseIV;
968 unsigned RewriteFactor = CheckForIVReuse(Stride, ReuseIV,
969 CommonExprs->getType());
970 if (RewriteFactor != 0) {
Bill Wendlingb7427032006-11-26 09:46:52 +0000971 DOUT << "BASED ON IV of STRIDE " << *ReuseIV.Stride
972 << " and BASE " << *ReuseIV.Base << " :\n";
Evan Cheng31e77312006-07-18 19:07:58 +0000973 NewPHI = ReuseIV.PHI;
974 IncV = ReuseIV.IncV;
975 }
976
Chris Lattner44b807e2005-08-08 22:32:34 +0000977 // Next, figure out what we can represent in the immediate fields of
978 // instructions. If we can represent anything there, move it to the imm
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000979 // fields of the BasedUsers. We do this so that it increases the commonality
980 // of the remaining uses.
Chris Lattner44b807e2005-08-08 22:32:34 +0000981 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
Chris Lattner80b32b32005-08-16 00:38:11 +0000982 // If the user is not in the current loop, this means it is using the exit
983 // value of the IV. Do not put anything in the base, make sure it's all in
984 // the immediate field to allow as much factoring as possible.
985 if (!L->contains(UsersToProcess[i].Inst->getParent())) {
Chris Lattner8385e512005-08-17 21:22:41 +0000986 UsersToProcess[i].Imm = SCEVAddExpr::get(UsersToProcess[i].Imm,
987 UsersToProcess[i].Base);
988 UsersToProcess[i].Base =
989 SCEVUnknown::getIntegerSCEV(0, UsersToProcess[i].Base->getType());
Chris Lattner80b32b32005-08-16 00:38:11 +0000990 } else {
991
992 // Addressing modes can be folded into loads and stores. Be careful that
993 // the store is through the expression, not of the expression though.
994 bool isAddress = isa<LoadInst>(UsersToProcess[i].Inst);
995 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
996 if (SI->getOperand(1) == UsersToProcess[i].OperandValToReplace)
997 isAddress = true;
998
Evan Chengd277f2c2006-03-13 23:14:23 +0000999 MoveImmediateValues(TLI, UsersToProcess[i].Base, UsersToProcess[i].Imm,
Chris Lattner80b32b32005-08-16 00:38:11 +00001000 isAddress, L);
1001 }
Chris Lattner44b807e2005-08-08 22:32:34 +00001002 }
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001003
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001004 // Now that we know what we need to do, insert the PHI node itself.
1005 //
Bill Wendlingb7427032006-11-26 09:46:52 +00001006 DOUT << "INSERTING IV of STRIDE " << *Stride << " and BASE "
1007 << *CommonExprs << " :\n";
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001008
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001009 SCEVExpander Rewriter(*SE, *LI);
1010 SCEVExpander PreheaderRewriter(*SE, *LI);
Chris Lattner44b807e2005-08-08 22:32:34 +00001011
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001012 BasicBlock *Preheader = L->getLoopPreheader();
1013 Instruction *PreInsertPt = Preheader->getTerminator();
1014 Instruction *PhiInsertBefore = L->getHeader()->begin();
Chris Lattner44b807e2005-08-08 22:32:34 +00001015
Chris Lattner12b50412005-09-12 17:11:27 +00001016 BasicBlock *LatchBlock = L->getLoopLatch();
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001017
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001018 const Type *ReplacedTy = CommonExprs->getType();
Evan Chengeb8f9e22006-03-17 19:52:23 +00001019
1020 // Emit the initial base value into the loop preheader.
1021 Value *CommonBaseV
1022 = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt,
1023 ReplacedTy);
1024
Evan Cheng21495772006-03-18 08:03:12 +00001025 if (RewriteFactor == 0) {
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001026 // Create a new Phi for this base, and stick it in the loop header.
1027 NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
1028 ++NumInserted;
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001029
Evan Chengeb8f9e22006-03-17 19:52:23 +00001030 // Add common base to the new Phi node.
1031 NewPHI->addIncoming(CommonBaseV, Preheader);
1032
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001033 // Insert the stride into the preheader.
1034 Value *StrideV = PreheaderRewriter.expandCodeFor(Stride, PreInsertPt,
1035 ReplacedTy);
1036 if (!isa<ConstantInt>(StrideV)) ++NumVariable;
Chris Lattner50fad702005-08-10 00:45:21 +00001037
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001038 // Emit the increment of the base value before the terminator of the loop
1039 // latch block, and add it to the Phi node.
1040 SCEVHandle IncExp = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
1041 SCEVUnknown::get(StrideV));
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001042
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001043 IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator(),
1044 ReplacedTy);
1045 IncV->setName(NewPHI->getName()+".inc");
1046 NewPHI->addIncoming(IncV, LatchBlock);
1047
Evan Chengeb8f9e22006-03-17 19:52:23 +00001048 // Remember this in case a later stride is multiple of this.
Evan Cheng21495772006-03-18 08:03:12 +00001049 IVsByStride[Stride].addIV(Stride, CommonExprs, NewPHI, IncV);
Evan Chengeb8f9e22006-03-17 19:52:23 +00001050 } else {
1051 Constant *C = dyn_cast<Constant>(CommonBaseV);
1052 if (!C ||
1053 (!C->isNullValue() &&
1054 !isTargetConstant(SCEVUnknown::get(CommonBaseV), TLI)))
Reid Spencer3da59db2006-11-27 01:05:10 +00001055 // We want the common base emitted into the preheader! This is just
1056 // using cast as a copy so BitCast (no-op cast) is appropriate
1057 CommonBaseV = new BitCastInst(CommonBaseV, CommonBaseV->getType(),
1058 "commonbase", PreInsertPt);
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001059 }
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001060
Chris Lattner7e79b382006-08-03 06:34:50 +00001061 // We want to emit code for users inside the loop first. To do this, we
1062 // rearrange BasedUser so that the entries at the end have
1063 // isUseOfPostIncrementedValue = false, because we pop off the end of the
1064 // vector (so we handle them first).
1065 std::partition(UsersToProcess.begin(), UsersToProcess.end(),
1066 PartitionByIsUseOfPostIncrementedValue);
1067
1068 // Sort this by base, so that things with the same base are handled
1069 // together. By partitioning first and stable-sorting later, we are
1070 // guaranteed that within each base we will pop off users from within the
1071 // loop before users outside of the loop with a particular base.
1072 //
1073 // We would like to use stable_sort here, but we can't. The problem is that
1074 // SCEVHandle's don't have a deterministic ordering w.r.t to each other, so
1075 // we don't have anything to do a '<' comparison on. Because we think the
1076 // number of uses is small, do a horrible bubble sort which just relies on
1077 // ==.
1078 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1079 // Get a base value.
1080 SCEVHandle Base = UsersToProcess[i].Base;
1081
1082 // Compact everything with this base to be consequetive with this one.
1083 for (unsigned j = i+1; j != e; ++j) {
1084 if (UsersToProcess[j].Base == Base) {
1085 std::swap(UsersToProcess[i+1], UsersToProcess[j]);
1086 ++i;
1087 }
1088 }
1089 }
1090
1091 // Process all the users now. This outer loop handles all bases, the inner
1092 // loop handles all users of a particular base.
Nate Begeman16997482005-07-30 00:15:07 +00001093 while (!UsersToProcess.empty()) {
Chris Lattner7b445c52005-10-11 18:30:57 +00001094 SCEVHandle Base = UsersToProcess.back().Base;
Chris Lattnerbe3e5212005-08-03 23:30:08 +00001095
Bill Wendlingb7427032006-11-26 09:46:52 +00001096 DOUT << " INSERTING code for BASE = " << *Base << ":\n";
Chris Lattnerbe3e5212005-08-03 23:30:08 +00001097
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001098 // Emit the code for Base into the preheader.
Chris Lattner5272f3c2005-08-08 05:47:49 +00001099 Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt,
1100 ReplacedTy);
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001101
1102 // If BaseV is a constant other than 0, make sure that it gets inserted into
1103 // the preheader, instead of being forward substituted into the uses. We do
Reid Spencer3da59db2006-11-27 01:05:10 +00001104 // this by forcing a BitCast (noop cast) to be inserted into the preheader
1105 // in this case.
Chris Lattner7e79b382006-08-03 06:34:50 +00001106 if (Constant *C = dyn_cast<Constant>(BaseV)) {
Evan Chengd277f2c2006-03-13 23:14:23 +00001107 if (!C->isNullValue() && !isTargetConstant(Base, TLI)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001108 // We want this constant emitted into the preheader! This is just
1109 // using cast as a copy so BitCast (no-op cast) is appropriate
1110 BaseV = new BitCastInst(BaseV, BaseV->getType(), "preheaderinsert",
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001111 PreInsertPt);
1112 }
Chris Lattner7e79b382006-08-03 06:34:50 +00001113 }
1114
Nate Begeman16997482005-07-30 00:15:07 +00001115 // Emit the code to add the immediate offset to the Phi value, just before
Chris Lattner2351aba2005-08-03 22:51:21 +00001116 // the instructions that we identified as using this stride and base.
Chris Lattner7b445c52005-10-11 18:30:57 +00001117 do {
Chris Lattner7e79b382006-08-03 06:34:50 +00001118 // FIXME: Use emitted users to emit other users.
Chris Lattner7b445c52005-10-11 18:30:57 +00001119 BasedUser &User = UsersToProcess.back();
Jeff Cohend29b6aa2005-07-30 18:33:25 +00001120
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001121 // If this instruction wants to use the post-incremented value, move it
1122 // after the post-inc and use its value instead of the PHI.
1123 Value *RewriteOp = NewPHI;
1124 if (User.isUseOfPostIncrementedValue) {
1125 RewriteOp = IncV;
Chris Lattnerc6bae652005-09-12 06:04:47 +00001126
1127 // If this user is in the loop, make sure it is the last thing in the
1128 // loop to ensure it is dominated by the increment.
1129 if (L->contains(User.Inst->getParent()))
1130 User.Inst->moveBefore(LatchBlock->getTerminator());
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001131 }
Reid Spencer3ba68b92006-12-13 08:06:42 +00001132 if (RewriteOp->getType() != ReplacedTy) {
1133 Instruction::CastOps opcode = Instruction::Trunc;
1134 if (ReplacedTy->getPrimitiveSizeInBits() ==
1135 RewriteOp->getType()->getPrimitiveSizeInBits())
1136 opcode = Instruction::BitCast;
1137 RewriteOp = SCEVExpander::InsertCastOfTo(opcode, RewriteOp, ReplacedTy);
1138 }
Evan Cheng86c75d32006-06-09 00:12:42 +00001139
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001140 SCEVHandle RewriteExpr = SCEVUnknown::get(RewriteOp);
1141
Chris Lattner2351aba2005-08-03 22:51:21 +00001142 // Clear the SCEVExpander's expression map so that we are guaranteed
1143 // to have the code emitted where we expect it.
1144 Rewriter.clear();
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001145
1146 // If we are reusing the iv, then it must be multiplied by a constant
1147 // factor take advantage of addressing mode scale component.
Evan Cheng21495772006-03-18 08:03:12 +00001148 if (RewriteFactor != 0) {
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001149 RewriteExpr =
1150 SCEVMulExpr::get(SCEVUnknown::getIntegerSCEV(RewriteFactor,
Evan Chengeb8f9e22006-03-17 19:52:23 +00001151 RewriteExpr->getType()),
1152 RewriteExpr);
1153
1154 // The common base is emitted in the loop preheader. But since we
1155 // are reusing an IV, it has not been used to initialize the PHI node.
1156 // Add it to the expression used to rewrite the uses.
1157 if (!isa<ConstantInt>(CommonBaseV) ||
1158 !cast<ConstantInt>(CommonBaseV)->isNullValue())
1159 RewriteExpr = SCEVAddExpr::get(RewriteExpr,
1160 SCEVUnknown::get(CommonBaseV));
1161 }
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001162
Chris Lattner2114b272005-08-04 20:03:32 +00001163 // Now that we know what we need to do, insert code before User for the
1164 // immediate and any loop-variant expressions.
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001165 if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isNullValue())
1166 // Add BaseV to the PHI value if needed.
1167 RewriteExpr = SCEVAddExpr::get(RewriteExpr, SCEVUnknown::get(BaseV));
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001168
Chris Lattnerc60fb082005-08-12 22:22:17 +00001169 User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter, L, this);
Jeff Cohend29b6aa2005-07-30 18:33:25 +00001170
Chris Lattner2351aba2005-08-03 22:51:21 +00001171 // Mark old value we replaced as possibly dead, so that it is elminated
1172 // if we just replaced the last use of that value.
Chris Lattner2114b272005-08-04 20:03:32 +00001173 DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
Nate Begeman16997482005-07-30 00:15:07 +00001174
Chris Lattner7b445c52005-10-11 18:30:57 +00001175 UsersToProcess.pop_back();
Chris Lattner2351aba2005-08-03 22:51:21 +00001176 ++NumReduced;
Chris Lattner7b445c52005-10-11 18:30:57 +00001177
Chris Lattner7e79b382006-08-03 06:34:50 +00001178 // If there are any more users to process with the same base, process them
1179 // now. We sorted by base above, so we just have to check the last elt.
Chris Lattner7b445c52005-10-11 18:30:57 +00001180 } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
Nate Begeman16997482005-07-30 00:15:07 +00001181 // TODO: Next, find out which base index is the most common, pull it out.
1182 }
1183
1184 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1185 // different starting values, into different PHIs.
Nate Begeman16997482005-07-30 00:15:07 +00001186}
1187
Chris Lattner010de252005-08-08 05:28:22 +00001188// OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
1189// uses in the loop, look to see if we can eliminate some, in favor of using
1190// common indvars for the different uses.
1191void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
1192 // TODO: implement optzns here.
1193
Chris Lattner010de252005-08-08 05:28:22 +00001194 // Finally, get the terminating condition for the loop if possible. If we
1195 // can, we want to change it to use a post-incremented version of its
Chris Lattner98d98112006-03-24 07:14:34 +00001196 // induction variable, to allow coalescing the live ranges for the IV into
Chris Lattner010de252005-08-08 05:28:22 +00001197 // one register value.
1198 PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
1199 BasicBlock *Preheader = L->getLoopPreheader();
1200 BasicBlock *LatchBlock =
1201 SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
1202 BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001203 if (!TermBr || TermBr->isUnconditional() ||
1204 !isa<ICmpInst>(TermBr->getCondition()))
Chris Lattner010de252005-08-08 05:28:22 +00001205 return;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001206 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
Chris Lattner010de252005-08-08 05:28:22 +00001207
1208 // Search IVUsesByStride to find Cond's IVUse if there is one.
1209 IVStrideUse *CondUse = 0;
Chris Lattner50fad702005-08-10 00:45:21 +00001210 const SCEVHandle *CondStride = 0;
Chris Lattner010de252005-08-08 05:28:22 +00001211
Chris Lattnerb4dd1b82005-10-11 18:17:57 +00001212 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e && !CondUse;
1213 ++Stride) {
1214 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1215 IVUsesByStride.find(StrideOrder[Stride]);
1216 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1217
1218 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
1219 E = SI->second.Users.end(); UI != E; ++UI)
Chris Lattner010de252005-08-08 05:28:22 +00001220 if (UI->User == Cond) {
1221 CondUse = &*UI;
Chris Lattnerb4dd1b82005-10-11 18:17:57 +00001222 CondStride = &SI->first;
Chris Lattner010de252005-08-08 05:28:22 +00001223 // NOTE: we could handle setcc instructions with multiple uses here, but
1224 // InstCombine does it as well for simple uses, it's not clear that it
1225 // occurs enough in real life to handle.
1226 break;
1227 }
Chris Lattnerb4dd1b82005-10-11 18:17:57 +00001228 }
Chris Lattner010de252005-08-08 05:28:22 +00001229 if (!CondUse) return; // setcc doesn't use the IV.
1230
Chris Lattner010de252005-08-08 05:28:22 +00001231 // It's possible for the setcc instruction to be anywhere in the loop, and
1232 // possible for it to have multiple users. If it is not immediately before
1233 // the latch block branch, move it.
1234 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
1235 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
1236 Cond->moveBefore(TermBr);
1237 } else {
1238 // Otherwise, clone the terminating condition and insert into the loopend.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001239 Cond = cast<ICmpInst>(Cond->clone());
Chris Lattner010de252005-08-08 05:28:22 +00001240 Cond->setName(L->getHeader()->getName() + ".termcond");
1241 LatchBlock->getInstList().insert(TermBr, Cond);
1242
1243 // Clone the IVUse, as the old use still exists!
Chris Lattner50fad702005-08-10 00:45:21 +00001244 IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
Chris Lattner010de252005-08-08 05:28:22 +00001245 CondUse->OperandValToReplace);
Chris Lattner50fad702005-08-10 00:45:21 +00001246 CondUse = &IVUsesByStride[*CondStride].Users.back();
Chris Lattner010de252005-08-08 05:28:22 +00001247 }
1248 }
1249
1250 // If we get to here, we know that we can transform the setcc instruction to
Chris Lattner98d98112006-03-24 07:14:34 +00001251 // use the post-incremented version of the IV, allowing us to coalesce the
Chris Lattner010de252005-08-08 05:28:22 +00001252 // live ranges for the IV correctly.
Chris Lattner50fad702005-08-10 00:45:21 +00001253 CondUse->Offset = SCEV::getMinusSCEV(CondUse->Offset, *CondStride);
Chris Lattner010de252005-08-08 05:28:22 +00001254 CondUse->isUseOfPostIncrementedValue = true;
1255}
Nate Begeman16997482005-07-30 00:15:07 +00001256
Evan Cheng4496a502006-03-18 00:44:49 +00001257namespace {
1258 // Constant strides come first which in turns are sorted by their absolute
1259 // values. If absolute values are the same, then positive strides comes first.
1260 // e.g.
1261 // 4, -1, X, 1, 2 ==> 1, -1, 2, 4, X
1262 struct StrideCompare {
1263 bool operator()(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1264 SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS);
1265 SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
1266 if (LHSC && RHSC) {
1267 int64_t LV = LHSC->getValue()->getSExtValue();
1268 int64_t RV = RHSC->getValue()->getSExtValue();
1269 uint64_t ALV = (LV < 0) ? -LV : LV;
1270 uint64_t ARV = (RV < 0) ? -RV : RV;
1271 if (ALV == ARV)
1272 return LV > RV;
1273 else
1274 return ALV < ARV;
Chris Lattner035c6a22006-03-22 17:27:24 +00001275 }
1276 return (LHSC && !RHSC);
Evan Cheng4496a502006-03-18 00:44:49 +00001277 }
1278 };
1279}
1280
Nate Begemaneaa13852004-10-18 21:08:22 +00001281void LoopStrengthReduce::runOnLoop(Loop *L) {
1282 // First step, transform all loops nesting inside of this loop.
1283 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
1284 runOnLoop(*I);
1285
Nate Begeman16997482005-07-30 00:15:07 +00001286 // Next, find all uses of induction variables in this loop, and catagorize
1287 // them by stride. Start by finding all of the PHI nodes in the header for
1288 // this loop. If they are induction variables, inspect their uses.
Chris Lattner3416e5f2005-08-04 17:40:30 +00001289 std::set<Instruction*> Processed; // Don't reprocess instructions.
Nate Begeman16997482005-07-30 00:15:07 +00001290 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
Chris Lattner3416e5f2005-08-04 17:40:30 +00001291 AddUsersIfInteresting(I, L, Processed);
Nate Begemaneaa13852004-10-18 21:08:22 +00001292
Nate Begeman16997482005-07-30 00:15:07 +00001293 // If we have nothing to do, return.
Chris Lattner010de252005-08-08 05:28:22 +00001294 if (IVUsesByStride.empty()) return;
1295
1296 // Optimize induction variables. Some indvar uses can be transformed to use
1297 // strides that will be needed for other purposes. A common example of this
1298 // is the exit test for the loop, which can often be rewritten to use the
1299 // computation of some other indvar to decide when to terminate the loop.
1300 OptimizeIndvars(L);
1301
Misha Brukmanfd939082005-04-21 23:48:37 +00001302
Nate Begeman16997482005-07-30 00:15:07 +00001303 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
1304 // doing computation in byte values, promote to 32-bit values if safe.
1305
1306 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
1307 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
1308 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
1309 // to be careful that IV's are all the same type. Only works for intptr_t
1310 // indvars.
1311
1312 // If we only have one stride, we can more aggressively eliminate some things.
1313 bool HasOneStride = IVUsesByStride.size() == 1;
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001314
1315#ifndef NDEBUG
Bill Wendlingb7427032006-11-26 09:46:52 +00001316 DOUT << "\nLSR on ";
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001317 DEBUG(L->dump());
1318#endif
1319
1320 // IVsByStride keeps IVs for one particular loop.
1321 IVsByStride.clear();
1322
Evan Cheng4496a502006-03-18 00:44:49 +00001323 // Sort the StrideOrder so we process larger strides first.
1324 std::stable_sort(StrideOrder.begin(), StrideOrder.end(), StrideCompare());
1325
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001326 // Note: this processes each stride/type pair individually. All users passed
Chris Lattner7305ae22005-10-09 06:20:55 +00001327 // into StrengthReduceStridedIVUsers have the same type AND stride. Also,
1328 // node that we iterate over IVUsesByStride indirectly by using StrideOrder.
1329 // This extra layer of indirection makes the ordering of strides deterministic
1330 // - not dependent on map order.
1331 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
1332 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1333 IVUsesByStride.find(StrideOrder[Stride]);
1334 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
Nate Begeman16997482005-07-30 00:15:07 +00001335 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
Chris Lattner7305ae22005-10-09 06:20:55 +00001336 }
Nate Begemaneaa13852004-10-18 21:08:22 +00001337
1338 // Clean up after ourselves
1339 if (!DeadInsts.empty()) {
1340 DeleteTriviallyDeadInstructions(DeadInsts);
1341
Nate Begeman16997482005-07-30 00:15:07 +00001342 BasicBlock::iterator I = L->getHeader()->begin();
1343 PHINode *PN;
Chris Lattnere9100c62005-08-02 02:44:31 +00001344 while ((PN = dyn_cast<PHINode>(I))) {
Chris Lattner1060e092005-08-02 00:41:11 +00001345 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
1346
Chris Lattner87265ab2005-08-09 23:39:36 +00001347 // At this point, we know that we have killed one or more GEP
1348 // instructions. It is worth checking to see if the cann indvar is also
1349 // dead, so that we can remove it as well. The requirements for the cann
1350 // indvar to be considered dead are:
Nate Begeman16997482005-07-30 00:15:07 +00001351 // 1. the cann indvar has one use
1352 // 2. the use is an add instruction
1353 // 3. the add has one use
1354 // 4. the add is used by the cann indvar
1355 // If all four cases above are true, then we can remove both the add and
1356 // the cann indvar.
1357 // FIXME: this needs to eliminate an induction variable even if it's being
1358 // compared against some value to decide loop termination.
1359 if (PN->hasOneUse()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001360 Instruction *BO = dyn_cast<Instruction>(*PN->use_begin());
1361 if (BO && (isa<BinaryOperator>(BO) || isa<CmpInst>(BO))) {
1362 if (BO->hasOneUse() && PN == *(BO->use_begin())) {
Chris Lattner7e608bb2005-08-02 02:52:02 +00001363 DeadInsts.insert(BO);
1364 // Break the cycle, then delete the PHI.
1365 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattner52d83e62005-08-03 21:36:09 +00001366 SE->deleteInstructionFromRecords(PN);
Chris Lattner7e608bb2005-08-02 02:52:02 +00001367 PN->eraseFromParent();
Nate Begemaneaa13852004-10-18 21:08:22 +00001368 }
Chris Lattner7e608bb2005-08-02 02:52:02 +00001369 }
Nate Begeman16997482005-07-30 00:15:07 +00001370 }
Nate Begemaneaa13852004-10-18 21:08:22 +00001371 }
Nate Begeman16997482005-07-30 00:15:07 +00001372 DeleteTriviallyDeadInstructions(DeadInsts);
Nate Begemaneaa13852004-10-18 21:08:22 +00001373 }
Nate Begeman16997482005-07-30 00:15:07 +00001374
Chris Lattner9a59fbb2005-08-05 01:30:11 +00001375 CastedPointers.clear();
Nate Begeman16997482005-07-30 00:15:07 +00001376 IVUsesByStride.clear();
Chris Lattner7305ae22005-10-09 06:20:55 +00001377 StrideOrder.clear();
Nate Begeman16997482005-07-30 00:15:07 +00001378 return;
Nate Begemaneaa13852004-10-18 21:08:22 +00001379}