blob: 45a79d7f037fd8e2015a831120934185f6ec760c [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"
Jeff Cohenc5009912005-07-30 18:22:27 +000034#include <algorithm>
Chris Lattnerc597b8a2006-01-22 23:32:06 +000035#include <iostream>
Nate Begemanb18121e2004-10-18 21:08:22 +000036#include <set>
37using namespace llvm;
38
39namespace {
40 Statistic<> NumReduced ("loop-reduce", "Number of GEPs strength reduced");
Chris Lattner45f8b6e2005-08-04 22:34:05 +000041 Statistic<> NumInserted("loop-reduce", "Number of PHIs inserted");
Chris Lattneredff91a2005-08-10 00:45:21 +000042 Statistic<> NumVariable("loop-reduce","Number of PHIs with variable strides");
Nate Begemanb18121e2004-10-18 21:08:22 +000043
Chris Lattner430d0022005-08-03 22:21:05 +000044 /// IVStrideUse - Keep track of one use of a strided induction variable, where
45 /// the stride is stored externally. The Offset member keeps track of the
46 /// offset from the IV, User is the actual user of the operand, and 'Operand'
47 /// is the operand # of the User that is the use.
48 struct IVStrideUse {
49 SCEVHandle Offset;
50 Instruction *User;
51 Value *OperandValToReplace;
Chris Lattner9bfa6f82005-08-08 05:28:22 +000052
53 // isUseOfPostIncrementedValue - True if this should use the
54 // post-incremented version of this IV, not the preincremented version.
55 // This can only be set in special cases, such as the terminating setcc
Chris Lattnera6764832005-09-12 06:04:47 +000056 // instruction for a loop or uses dominated by the loop.
Chris Lattner9bfa6f82005-08-08 05:28:22 +000057 bool isUseOfPostIncrementedValue;
Chris Lattner430d0022005-08-03 22:21:05 +000058
59 IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
Chris Lattner9bfa6f82005-08-08 05:28:22 +000060 : Offset(Offs), User(U), OperandValToReplace(O),
61 isUseOfPostIncrementedValue(false) {}
Chris Lattner430d0022005-08-03 22:21:05 +000062 };
63
64 /// IVUsersOfOneStride - This structure keeps track of all instructions that
65 /// have an operand that is based on the trip count multiplied by some stride.
66 /// The stride for all of these users is common and kept external to this
67 /// structure.
68 struct IVUsersOfOneStride {
Nate Begemane68bcd12005-07-30 00:15:07 +000069 /// Users - Keep track of all of the users of this stride as well as the
Chris Lattner430d0022005-08-03 22:21:05 +000070 /// initial value and the operand that uses the IV.
71 std::vector<IVStrideUse> Users;
72
73 void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
74 Users.push_back(IVStrideUse(Offset, User, Operand));
Nate Begemane68bcd12005-07-30 00:15:07 +000075 }
76 };
77
78
Nate Begemanb18121e2004-10-18 21:08:22 +000079 class LoopStrengthReduce : public FunctionPass {
80 LoopInfo *LI;
Chris Lattnercb367102006-01-11 05:10:20 +000081 ETForest *EF;
Nate Begemane68bcd12005-07-30 00:15:07 +000082 ScalarEvolution *SE;
83 const TargetData *TD;
84 const Type *UIntPtrTy;
Nate Begemanb18121e2004-10-18 21:08:22 +000085 bool Changed;
Chris Lattner75a44e12005-08-02 02:52:02 +000086
87 /// MaxTargetAMSize - This is the maximum power-of-two scale value that the
88 /// target can handle for free with its addressing modes.
Jeff Cohena2c59b72005-03-04 04:04:26 +000089 unsigned MaxTargetAMSize;
Nate Begemane68bcd12005-07-30 00:15:07 +000090
91 /// IVUsesByStride - Keep track of all uses of induction variables that we
92 /// are interested in. The key of the map is the stride of the access.
Chris Lattneredff91a2005-08-10 00:45:21 +000093 std::map<SCEVHandle, IVUsersOfOneStride> IVUsesByStride;
Nate Begemane68bcd12005-07-30 00:15:07 +000094
Chris Lattner4ea0a3e2005-10-09 06:20:55 +000095 /// StrideOrder - An ordering of the keys in IVUsesByStride that is stable:
96 /// We use this to iterate over the IVUsesByStride collection without being
97 /// dependent on random ordering of pointers in the process.
98 std::vector<SCEVHandle> StrideOrder;
99
Chris Lattner6f286b72005-08-04 01:19:13 +0000100 /// CastedValues - As we need to cast values to uintptr_t, this keeps track
101 /// of the casted version of each value. This is accessed by
102 /// getCastedVersionOf.
103 std::map<Value*, Value*> CastedPointers;
Nate Begemane68bcd12005-07-30 00:15:07 +0000104
105 /// DeadInsts - Keep track of instructions we may have made dead, so that
106 /// we can remove them after we are done working.
107 std::set<Instruction*> DeadInsts;
Nate Begemanb18121e2004-10-18 21:08:22 +0000108 public:
Jeff Cohena2c59b72005-03-04 04:04:26 +0000109 LoopStrengthReduce(unsigned MTAMS = 1)
110 : MaxTargetAMSize(MTAMS) {
111 }
112
Nate Begemanb18121e2004-10-18 21:08:22 +0000113 virtual bool runOnFunction(Function &) {
114 LI = &getAnalysis<LoopInfo>();
Chris Lattnercb367102006-01-11 05:10:20 +0000115 EF = &getAnalysis<ETForest>();
Nate Begemane68bcd12005-07-30 00:15:07 +0000116 SE = &getAnalysis<ScalarEvolution>();
117 TD = &getAnalysis<TargetData>();
118 UIntPtrTy = TD->getIntPtrType();
Nate Begemanb18121e2004-10-18 21:08:22 +0000119 Changed = false;
120
121 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
122 runOnLoop(*I);
Chris Lattner6f286b72005-08-04 01:19:13 +0000123
Nate Begemanb18121e2004-10-18 21:08:22 +0000124 return Changed;
125 }
126
127 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000128 // We split critical edges, so we change the CFG. However, we do update
129 // many analyses if they are around.
130 AU.addPreservedID(LoopSimplifyID);
131 AU.addPreserved<LoopInfo>();
132 AU.addPreserved<DominatorSet>();
Chris Lattnercb367102006-01-11 05:10:20 +0000133 AU.addPreserved<ETForest>();
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000134 AU.addPreserved<ImmediateDominators>();
135 AU.addPreserved<DominanceFrontier>();
136 AU.addPreserved<DominatorTree>();
137
Jeff Cohen39751c32005-02-27 19:37:07 +0000138 AU.addRequiredID(LoopSimplifyID);
Nate Begemanb18121e2004-10-18 21:08:22 +0000139 AU.addRequired<LoopInfo>();
Chris Lattnercb367102006-01-11 05:10:20 +0000140 AU.addRequired<ETForest>();
Jeff Cohena2c59b72005-03-04 04:04:26 +0000141 AU.addRequired<TargetData>();
Nate Begemane68bcd12005-07-30 00:15:07 +0000142 AU.addRequired<ScalarEvolution>();
Nate Begemanb18121e2004-10-18 21:08:22 +0000143 }
Chris Lattner6f286b72005-08-04 01:19:13 +0000144
145 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
146 ///
147 Value *getCastedVersionOf(Value *V);
148private:
Nate Begemanb18121e2004-10-18 21:08:22 +0000149 void runOnLoop(Loop *L);
Chris Lattnereaf24722005-08-04 17:40:30 +0000150 bool AddUsersIfInteresting(Instruction *I, Loop *L,
151 std::set<Instruction*> &Processed);
152 SCEVHandle GetExpressionSCEV(Instruction *E, Loop *L);
153
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000154 void OptimizeIndvars(Loop *L);
Nate Begemane68bcd12005-07-30 00:15:07 +0000155
Chris Lattneredff91a2005-08-10 00:45:21 +0000156 void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
157 IVUsersOfOneStride &Uses,
Chris Lattner430d0022005-08-03 22:21:05 +0000158 Loop *L, bool isOnlyStride);
Nate Begemanb18121e2004-10-18 21:08:22 +0000159 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
160 };
Misha Brukmanb1c93172005-04-21 23:48:37 +0000161 RegisterOpt<LoopStrengthReduce> X("loop-reduce",
Chris Lattner92233d22005-09-27 21:10:32 +0000162 "Loop Strength Reduction");
Nate Begemanb18121e2004-10-18 21:08:22 +0000163}
164
Jeff Cohena2c59b72005-03-04 04:04:26 +0000165FunctionPass *llvm::createLoopStrengthReducePass(unsigned MaxTargetAMSize) {
166 return new LoopStrengthReduce(MaxTargetAMSize);
Nate Begemanb18121e2004-10-18 21:08:22 +0000167}
168
Chris Lattner6f286b72005-08-04 01:19:13 +0000169/// getCastedVersionOf - Return the specified value casted to uintptr_t.
170///
171Value *LoopStrengthReduce::getCastedVersionOf(Value *V) {
172 if (V->getType() == UIntPtrTy) return V;
173 if (Constant *CB = dyn_cast<Constant>(V))
174 return ConstantExpr::getCast(CB, UIntPtrTy);
175
176 Value *&New = CastedPointers[V];
177 if (New) return New;
178
Chris Lattnerd30c4992006-02-04 09:52:43 +0000179 New = SCEVExpander::InsertCastOfTo(V, UIntPtrTy);
Chris Lattneracc42c42005-08-04 19:08:16 +0000180 DeadInsts.insert(cast<Instruction>(New));
181 return New;
Chris Lattner6f286b72005-08-04 01:19:13 +0000182}
183
184
Nate Begemanb18121e2004-10-18 21:08:22 +0000185/// DeleteTriviallyDeadInstructions - If any of the instructions is the
186/// specified set are trivially dead, delete them and see if this makes any of
187/// their operands subsequently dead.
188void LoopStrengthReduce::
189DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
190 while (!Insts.empty()) {
191 Instruction *I = *Insts.begin();
192 Insts.erase(Insts.begin());
193 if (isInstructionTriviallyDead(I)) {
Jeff Cohen8ea6f9e2005-03-01 03:46:11 +0000194 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
195 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
196 Insts.insert(U);
Chris Lattner84e9baa2005-08-03 21:36:09 +0000197 SE->deleteInstructionFromRecords(I);
198 I->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +0000199 Changed = true;
200 }
201 }
202}
203
Jeff Cohen39751c32005-02-27 19:37:07 +0000204
Chris Lattnereaf24722005-08-04 17:40:30 +0000205/// GetExpressionSCEV - Compute and return the SCEV for the specified
206/// instruction.
207SCEVHandle LoopStrengthReduce::GetExpressionSCEV(Instruction *Exp, Loop *L) {
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000208 // Scalar Evolutions doesn't know how to compute SCEV's for GEP instructions.
209 // If this is a GEP that SE doesn't know about, compute it now and insert it.
210 // If this is not a GEP, or if we have already done this computation, just let
211 // SE figure it out.
Chris Lattnereaf24722005-08-04 17:40:30 +0000212 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000213 if (!GEP || SE->hasSCEV(GEP))
Chris Lattnereaf24722005-08-04 17:40:30 +0000214 return SE->getSCEV(Exp);
215
Nate Begemane68bcd12005-07-30 00:15:07 +0000216 // Analyze all of the subscripts of this getelementptr instruction, looking
217 // for uses that are determined by the trip count of L. First, skip all
218 // operands the are not dependent on the IV.
219
220 // Build up the base expression. Insert an LLVM cast of the pointer to
221 // uintptr_t first.
Chris Lattnereaf24722005-08-04 17:40:30 +0000222 SCEVHandle GEPVal = SCEVUnknown::get(getCastedVersionOf(GEP->getOperand(0)));
Nate Begemane68bcd12005-07-30 00:15:07 +0000223
224 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnereaf24722005-08-04 17:40:30 +0000225
226 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
Nate Begemane68bcd12005-07-30 00:15:07 +0000227 // If this is a use of a recurrence that we can analyze, and it comes before
228 // Op does in the GEP operand list, we will handle this when we process this
229 // operand.
230 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
231 const StructLayout *SL = TD->getStructLayout(STy);
232 unsigned Idx = cast<ConstantUInt>(GEP->getOperand(i))->getValue();
233 uint64_t Offset = SL->MemberOffsets[Idx];
Chris Lattnereaf24722005-08-04 17:40:30 +0000234 GEPVal = SCEVAddExpr::get(GEPVal,
235 SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy));
Nate Begemane68bcd12005-07-30 00:15:07 +0000236 } else {
Chris Lattneracc42c42005-08-04 19:08:16 +0000237 Value *OpVal = getCastedVersionOf(GEP->getOperand(i));
238 SCEVHandle Idx = SE->getSCEV(OpVal);
239
Chris Lattnereaf24722005-08-04 17:40:30 +0000240 uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
241 if (TypeSize != 1)
242 Idx = SCEVMulExpr::get(Idx,
243 SCEVConstant::get(ConstantUInt::get(UIntPtrTy,
244 TypeSize)));
245 GEPVal = SCEVAddExpr::get(GEPVal, Idx);
Nate Begemane68bcd12005-07-30 00:15:07 +0000246 }
247 }
248
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000249 SE->setSCEV(GEP, GEPVal);
Chris Lattnereaf24722005-08-04 17:40:30 +0000250 return GEPVal;
Nate Begemane68bcd12005-07-30 00:15:07 +0000251}
252
Chris Lattneracc42c42005-08-04 19:08:16 +0000253/// getSCEVStartAndStride - Compute the start and stride of this expression,
254/// returning false if the expression is not a start/stride pair, or true if it
255/// is. The stride must be a loop invariant expression, but the start may be
256/// a mix of loop invariant and loop variant expressions.
257static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
Chris Lattneredff91a2005-08-10 00:45:21 +0000258 SCEVHandle &Start, SCEVHandle &Stride) {
Chris Lattneracc42c42005-08-04 19:08:16 +0000259 SCEVHandle TheAddRec = Start; // Initialize to zero.
260
261 // If the outer level is an AddExpr, the operands are all start values except
262 // for a nested AddRecExpr.
263 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
264 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
265 if (SCEVAddRecExpr *AddRec =
266 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
267 if (AddRec->getLoop() == L)
268 TheAddRec = SCEVAddExpr::get(AddRec, TheAddRec);
269 else
270 return false; // Nested IV of some sort?
271 } else {
272 Start = SCEVAddExpr::get(Start, AE->getOperand(i));
273 }
274
275 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SH)) {
276 TheAddRec = SH;
277 } else {
278 return false; // not analyzable.
279 }
280
281 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
282 if (!AddRec || AddRec->getLoop() != L) return false;
283
284 // FIXME: Generalize to non-affine IV's.
285 if (!AddRec->isAffine()) return false;
286
287 Start = SCEVAddExpr::get(Start, AddRec->getOperand(0));
288
Chris Lattneracc42c42005-08-04 19:08:16 +0000289 if (!isa<SCEVConstant>(AddRec->getOperand(1)))
Chris Lattneredff91a2005-08-10 00:45:21 +0000290 DEBUG(std::cerr << "[" << L->getHeader()->getName()
291 << "] Variable stride: " << *AddRec << "\n");
Chris Lattneracc42c42005-08-04 19:08:16 +0000292
Chris Lattneredff91a2005-08-10 00:45:21 +0000293 Stride = AddRec->getOperand(1);
294 // Check that all constant strides are the unsigned type, we don't want to
295 // have two IV's one of signed stride 4 and one of unsigned stride 4 to not be
296 // merged.
297 assert((!isa<SCEVConstant>(Stride) || Stride->getType()->isUnsigned()) &&
Chris Lattneracc42c42005-08-04 19:08:16 +0000298 "Constants should be canonicalized to unsigned!");
Chris Lattneredff91a2005-08-10 00:45:21 +0000299
Chris Lattneracc42c42005-08-04 19:08:16 +0000300 return true;
301}
302
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000303/// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
304/// and now we need to decide whether the user should use the preinc or post-inc
305/// value. If this user should use the post-inc version of the IV, return true.
306///
307/// Choosing wrong here can break dominance properties (if we choose to use the
308/// post-inc value when we cannot) or it can end up adding extra live-ranges to
309/// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
310/// should use the post-inc value).
311static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
Chris Lattnercb367102006-01-11 05:10:20 +0000312 Loop *L, ETForest *EF, Pass *P) {
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000313 // If the user is in the loop, use the preinc value.
314 if (L->contains(User->getParent())) return false;
315
Chris Lattnerf07a5872005-10-03 02:50:05 +0000316 BasicBlock *LatchBlock = L->getLoopLatch();
317
318 // Ok, the user is outside of the loop. If it is dominated by the latch
319 // block, use the post-inc value.
Chris Lattnercb367102006-01-11 05:10:20 +0000320 if (EF->dominates(LatchBlock, User->getParent()))
Chris Lattnerf07a5872005-10-03 02:50:05 +0000321 return true;
322
323 // There is one case we have to be careful of: PHI nodes. These little guys
324 // can live in blocks that do not dominate the latch block, but (since their
325 // uses occur in the predecessor block, not the block the PHI lives in) should
326 // still use the post-inc value. Check for this case now.
327 PHINode *PN = dyn_cast<PHINode>(User);
328 if (!PN) return false; // not a phi, not dominated by latch block.
329
330 // Look at all of the uses of IV by the PHI node. If any use corresponds to
331 // a block that is not dominated by the latch block, give up and use the
332 // preincremented value.
333 unsigned NumUses = 0;
334 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
335 if (PN->getIncomingValue(i) == IV) {
336 ++NumUses;
Chris Lattnercb367102006-01-11 05:10:20 +0000337 if (!EF->dominates(LatchBlock, PN->getIncomingBlock(i)))
Chris Lattnerf07a5872005-10-03 02:50:05 +0000338 return false;
339 }
340
341 // Okay, all uses of IV by PN are in predecessor blocks that really are
342 // dominated by the latch block. Split the critical edges and use the
343 // post-incremented value.
344 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
345 if (PN->getIncomingValue(i) == IV) {
346 SplitCriticalEdge(PN->getIncomingBlock(i), PN->getParent(), P);
347 if (--NumUses == 0) break;
348 }
349
350 return true;
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000351}
352
353
354
Nate Begemane68bcd12005-07-30 00:15:07 +0000355/// AddUsersIfInteresting - Inspect the specified instruction. If it is a
356/// reducible SCEV, recursively add its users to the IVUsesByStride set and
357/// return true. Otherwise, return false.
Chris Lattnereaf24722005-08-04 17:40:30 +0000358bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
359 std::set<Instruction*> &Processed) {
Chris Lattner5df0e362005-10-21 05:45:41 +0000360 if (!I->getType()->isInteger() && !isa<PointerType>(I->getType()))
361 return false; // Void and FP expressions cannot be reduced.
Chris Lattnereaf24722005-08-04 17:40:30 +0000362 if (!Processed.insert(I).second)
363 return true; // Instruction already handled.
364
Chris Lattneracc42c42005-08-04 19:08:16 +0000365 // Get the symbolic expression for this instruction.
Chris Lattnereaf24722005-08-04 17:40:30 +0000366 SCEVHandle ISE = GetExpressionSCEV(I, L);
Chris Lattneracc42c42005-08-04 19:08:16 +0000367 if (isa<SCEVCouldNotCompute>(ISE)) return false;
Chris Lattnereaf24722005-08-04 17:40:30 +0000368
Chris Lattneracc42c42005-08-04 19:08:16 +0000369 // Get the start and stride for this expression.
370 SCEVHandle Start = SCEVUnknown::getIntegerSCEV(0, ISE->getType());
Chris Lattneredff91a2005-08-10 00:45:21 +0000371 SCEVHandle Stride = Start;
Chris Lattneracc42c42005-08-04 19:08:16 +0000372 if (!getSCEVStartAndStride(ISE, L, Start, Stride))
373 return false; // Non-reducible symbolic expression, bail out.
374
Nate Begemane68bcd12005-07-30 00:15:07 +0000375 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){
376 Instruction *User = cast<Instruction>(*UI);
377
378 // Do not infinitely recurse on PHI nodes.
Chris Lattnerfd018c82005-09-13 02:09:55 +0000379 if (isa<PHINode>(User) && Processed.count(User))
Nate Begemane68bcd12005-07-30 00:15:07 +0000380 continue;
381
382 // If this is an instruction defined in a nested loop, or outside this loop,
Chris Lattnera0102fb2005-08-04 00:14:11 +0000383 // don't recurse into it.
Chris Lattneracc42c42005-08-04 19:08:16 +0000384 bool AddUserToIVUsers = false;
Chris Lattnera0102fb2005-08-04 00:14:11 +0000385 if (LI->getLoopFor(User->getParent()) != L) {
Chris Lattnerfd018c82005-09-13 02:09:55 +0000386 DEBUG(std::cerr << "FOUND USER in other loop: " << *User
Chris Lattnera0102fb2005-08-04 00:14:11 +0000387 << " OF SCEV: " << *ISE << "\n");
Chris Lattneracc42c42005-08-04 19:08:16 +0000388 AddUserToIVUsers = true;
Chris Lattnereaf24722005-08-04 17:40:30 +0000389 } else if (!AddUsersIfInteresting(User, L, Processed)) {
Chris Lattner65107492005-08-04 00:40:47 +0000390 DEBUG(std::cerr << "FOUND USER: " << *User
391 << " OF SCEV: " << *ISE << "\n");
Chris Lattneracc42c42005-08-04 19:08:16 +0000392 AddUserToIVUsers = true;
393 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000394
Chris Lattneracc42c42005-08-04 19:08:16 +0000395 if (AddUserToIVUsers) {
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000396 IVUsersOfOneStride &StrideUses = IVUsesByStride[Stride];
397 if (StrideUses.Users.empty()) // First occurance of this stride?
398 StrideOrder.push_back(Stride);
399
Chris Lattner65107492005-08-04 00:40:47 +0000400 // Okay, we found a user that we cannot reduce. Analyze the instruction
Chris Lattnera6764832005-09-12 06:04:47 +0000401 // and decide what to do with it. If we are a use inside of the loop, use
402 // the value before incrementation, otherwise use it after incrementation.
Chris Lattnercb367102006-01-11 05:10:20 +0000403 if (IVUseShouldUsePostIncValue(User, I, L, EF, this)) {
Chris Lattnera6764832005-09-12 06:04:47 +0000404 // The value used will be incremented by the stride more than we are
405 // expecting, so subtract this off.
406 SCEVHandle NewStart = SCEV::getMinusSCEV(Start, Stride);
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000407 StrideUses.addUser(NewStart, User, I);
408 StrideUses.Users.back().isUseOfPostIncrementedValue = true;
Chris Lattnerf07a5872005-10-03 02:50:05 +0000409 DEBUG(std::cerr << " USING POSTINC SCEV, START=" << *NewStart<< "\n");
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000410 } else {
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000411 StrideUses.addUser(Start, User, I);
Chris Lattnera6764832005-09-12 06:04:47 +0000412 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000413 }
414 }
415 return true;
416}
417
418namespace {
419 /// BasedUser - For a particular base value, keep information about how we've
420 /// partitioned the expression so far.
421 struct BasedUser {
Chris Lattner37c24cc2005-08-08 22:56:21 +0000422 /// Base - The Base value for the PHI node that needs to be inserted for
423 /// this use. As the use is processed, information gets moved from this
424 /// field to the Imm field (below). BasedUser values are sorted by this
425 /// field.
426 SCEVHandle Base;
427
Nate Begemane68bcd12005-07-30 00:15:07 +0000428 /// Inst - The instruction using the induction variable.
429 Instruction *Inst;
430
Chris Lattner430d0022005-08-03 22:21:05 +0000431 /// OperandValToReplace - The operand value of Inst to replace with the
432 /// EmittedBase.
433 Value *OperandValToReplace;
Nate Begemane68bcd12005-07-30 00:15:07 +0000434
435 /// Imm - The immediate value that should be added to the base immediately
436 /// before Inst, because it will be folded into the imm field of the
437 /// instruction.
438 SCEVHandle Imm;
439
440 /// EmittedBase - The actual value* to use for the base value of this
441 /// operation. This is null if we should just use zero so far.
442 Value *EmittedBase;
443
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000444 // isUseOfPostIncrementedValue - True if this should use the
445 // post-incremented version of this IV, not the preincremented version.
446 // This can only be set in special cases, such as the terminating setcc
Chris Lattnera6764832005-09-12 06:04:47 +0000447 // instruction for a loop and uses outside the loop that are dominated by
448 // the loop.
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000449 bool isUseOfPostIncrementedValue;
Chris Lattner37c24cc2005-08-08 22:56:21 +0000450
451 BasedUser(IVStrideUse &IVSU)
452 : Base(IVSU.Offset), Inst(IVSU.User),
453 OperandValToReplace(IVSU.OperandValToReplace),
454 Imm(SCEVUnknown::getIntegerSCEV(0, Base->getType())), EmittedBase(0),
455 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
Nate Begemane68bcd12005-07-30 00:15:07 +0000456
Chris Lattnera6d7c352005-08-04 20:03:32 +0000457 // Once we rewrite the code to insert the new IVs we want, update the
458 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
459 // to it.
Chris Lattnera091ff12005-08-09 00:18:09 +0000460 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattner8447b492005-08-12 22:22:17 +0000461 SCEVExpander &Rewriter, Loop *L,
462 Pass *P);
Chris Lattner2959f002006-02-04 07:36:50 +0000463
464 Value *InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
465 SCEVExpander &Rewriter,
466 Instruction *IP, Loop *L);
Nate Begemane68bcd12005-07-30 00:15:07 +0000467 void dump() const;
468 };
469}
470
471void BasedUser::dump() const {
Chris Lattner37c24cc2005-08-08 22:56:21 +0000472 std::cerr << " Base=" << *Base;
Nate Begemane68bcd12005-07-30 00:15:07 +0000473 std::cerr << " Imm=" << *Imm;
474 if (EmittedBase)
475 std::cerr << " EB=" << *EmittedBase;
476
477 std::cerr << " Inst: " << *Inst;
478}
479
Chris Lattner2959f002006-02-04 07:36:50 +0000480Value *BasedUser::InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
481 SCEVExpander &Rewriter,
482 Instruction *IP, Loop *L) {
483 // Figure out where we *really* want to insert this code. In particular, if
484 // the user is inside of a loop that is nested inside of L, we really don't
485 // want to insert this expression before the user, we'd rather pull it out as
486 // many loops as possible.
487 LoopInfo &LI = Rewriter.getLoopInfo();
488 Instruction *BaseInsertPt = IP;
489
490 // Figure out the most-nested loop that IP is in.
491 Loop *InsertLoop = LI.getLoopFor(IP->getParent());
492
493 // If InsertLoop is not L, and InsertLoop is nested inside of L, figure out
494 // the preheader of the outer-most loop where NewBase is not loop invariant.
495 while (InsertLoop && NewBase->isLoopInvariant(InsertLoop)) {
496 BaseInsertPt = InsertLoop->getLoopPreheader()->getTerminator();
497 InsertLoop = InsertLoop->getParentLoop();
498 }
499
500 // If there is no immediate value, skip the next part.
501 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Imm))
502 if (SC->getValue()->isNullValue())
503 return Rewriter.expandCodeFor(NewBase, BaseInsertPt,
504 OperandValToReplace->getType());
505
506 Value *Base = Rewriter.expandCodeFor(NewBase, BaseInsertPt);
507
508 // Always emit the immediate (if non-zero) into the same block as the user.
509 SCEVHandle NewValSCEV = SCEVAddExpr::get(SCEVUnknown::get(Base), Imm);
510 return Rewriter.expandCodeFor(NewValSCEV, IP,
511 OperandValToReplace->getType());
512}
513
514
Chris Lattnera6d7c352005-08-04 20:03:32 +0000515// Once we rewrite the code to insert the new IVs we want, update the
516// operands of Inst to use the new expression 'NewBase', with 'Imm' added
517// to it.
Chris Lattnera091ff12005-08-09 00:18:09 +0000518void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattner4fec86d2005-08-12 22:06:11 +0000519 SCEVExpander &Rewriter,
Chris Lattner8447b492005-08-12 22:22:17 +0000520 Loop *L, Pass *P) {
Chris Lattnera6d7c352005-08-04 20:03:32 +0000521 if (!isa<PHINode>(Inst)) {
Chris Lattner2959f002006-02-04 07:36:50 +0000522 Value *NewVal = InsertCodeForBaseAtPosition(NewBase, Rewriter, Inst, L);
Chris Lattnera6d7c352005-08-04 20:03:32 +0000523 // Replace the use of the operand Value with the new Phi we just created.
524 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
525 DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst);
526 return;
527 }
528
529 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000530 // expression into each operand block that uses it. Note that PHI nodes can
531 // have multiple entries for the same predecessor. We use a map to make sure
532 // that a PHI node only has a single Value* for each predecessor (which also
533 // prevents us from inserting duplicate code in some blocks).
534 std::map<BasicBlock*, Value*> InsertedCode;
Chris Lattnera6d7c352005-08-04 20:03:32 +0000535 PHINode *PN = cast<PHINode>(Inst);
536 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
537 if (PN->getIncomingValue(i) == OperandValToReplace) {
Chris Lattner4fec86d2005-08-12 22:06:11 +0000538 // If this is a critical edge, split the edge so that we do not insert the
Chris Lattnerfd018c82005-09-13 02:09:55 +0000539 // code on all predecessor/successor paths. We do this unless this is the
540 // canonical backedge for this loop, as this can make some inserted code
541 // be in an illegal position.
Chris Lattner8fcce172005-10-03 00:31:52 +0000542 BasicBlock *PHIPred = PN->getIncomingBlock(i);
543 if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
544 (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
Chris Lattner8fcce172005-10-03 00:31:52 +0000545
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000546 // First step, split the critical edge.
Chris Lattner8fcce172005-10-03 00:31:52 +0000547 SplitCriticalEdge(PHIPred, PN->getParent(), P);
Chris Lattner8447b492005-08-12 22:22:17 +0000548
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000549 // Next step: move the basic block. In particular, if the PHI node
550 // is outside of the loop, and PredTI is in the loop, we want to
551 // move the block to be immediately before the PHI block, not
552 // immediately after PredTI.
Chris Lattner8fcce172005-10-03 00:31:52 +0000553 if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000554 BasicBlock *NewBB = PN->getIncomingBlock(i);
555 NewBB->moveBefore(PN->getParent());
Chris Lattner4fec86d2005-08-12 22:06:11 +0000556 }
557 }
Chris Lattnera6d7c352005-08-04 20:03:32 +0000558
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000559 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
560 if (!Code) {
561 // Insert the code into the end of the predecessor block.
Chris Lattner2959f002006-02-04 07:36:50 +0000562 Instruction *InsertPt = PN->getIncomingBlock(i)->getTerminator();
563 Code = InsertCodeForBaseAtPosition(NewBase, Rewriter, InsertPt, L);
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000564 }
Chris Lattnera6d7c352005-08-04 20:03:32 +0000565
566 // Replace the use of the operand Value with the new Phi we just created.
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000567 PN->setIncomingValue(i, Code);
Chris Lattnera6d7c352005-08-04 20:03:32 +0000568 Rewriter.clear();
569 }
570 }
571 DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst);
572}
573
574
Nate Begemane68bcd12005-07-30 00:15:07 +0000575/// isTargetConstant - Return true if the following can be referenced by the
576/// immediate field of a target instruction.
577static bool isTargetConstant(const SCEVHandle &V) {
Jeff Cohen546fd592005-07-30 18:33:25 +0000578
Nate Begemane68bcd12005-07-30 00:15:07 +0000579 // FIXME: Look at the target to decide if &GV is a legal constant immediate.
Chris Lattner14203e82005-08-08 06:25:50 +0000580 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
581 // PPC allows a sign-extended 16-bit immediate field.
Chris Lattner07720072005-12-05 18:23:57 +0000582 int64_t V = SC->getValue()->getSExtValue();
583 if (V > -(1 << 16) && V < (1 << 16)-1)
584 return true;
Chris Lattner14203e82005-08-08 06:25:50 +0000585 return false;
586 }
Jeff Cohen546fd592005-07-30 18:33:25 +0000587
Nate Begemane68bcd12005-07-30 00:15:07 +0000588 return false; // ENABLE this for x86
Jeff Cohen546fd592005-07-30 18:33:25 +0000589
Nate Begemane68bcd12005-07-30 00:15:07 +0000590 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
591 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
592 if (CE->getOpcode() == Instruction::Cast)
593 if (isa<GlobalValue>(CE->getOperand(0)))
594 // FIXME: should check to see that the dest is uintptr_t!
595 return true;
596 return false;
597}
598
Chris Lattner37ed8952005-08-08 22:32:34 +0000599/// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
600/// loop varying to the Imm operand.
601static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
602 Loop *L) {
603 if (Val->isLoopInvariant(L)) return; // Nothing to do.
604
605 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
606 std::vector<SCEVHandle> NewOps;
607 NewOps.reserve(SAE->getNumOperands());
608
609 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
610 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
611 // If this is a loop-variant expression, it must stay in the immediate
612 // field of the expression.
613 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
614 } else {
615 NewOps.push_back(SAE->getOperand(i));
616 }
617
618 if (NewOps.empty())
619 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
620 else
621 Val = SCEVAddExpr::get(NewOps);
622 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
623 // Try to pull immediates out of the start value of nested addrec's.
624 SCEVHandle Start = SARE->getStart();
625 MoveLoopVariantsToImediateField(Start, Imm, L);
626
627 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
628 Ops[0] = Start;
629 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
630 } else {
631 // Otherwise, all of Val is variant, move the whole thing over.
632 Imm = SCEVAddExpr::get(Imm, Val);
633 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
634 }
635}
636
637
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000638/// MoveImmediateValues - Look at Val, and pull out any additions of constants
Nate Begemane68bcd12005-07-30 00:15:07 +0000639/// that can fit into the immediate field of instructions in the target.
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000640/// Accumulate these immediate values into the Imm value.
641static void MoveImmediateValues(SCEVHandle &Val, SCEVHandle &Imm,
642 bool isAddress, Loop *L) {
Chris Lattnerfc624702005-08-03 23:44:42 +0000643 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000644 std::vector<SCEVHandle> NewOps;
645 NewOps.reserve(SAE->getNumOperands());
646
Chris Lattner2959f002006-02-04 07:36:50 +0000647 for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
648 SCEVHandle NewOp = SAE->getOperand(i);
649 MoveImmediateValues(NewOp, Imm, isAddress, L);
650
651 if (!NewOp->isLoopInvariant(L)) {
Chris Lattneracc42c42005-08-04 19:08:16 +0000652 // If this is a loop-variant expression, it must stay in the immediate
653 // field of the expression.
Chris Lattner2959f002006-02-04 07:36:50 +0000654 Imm = SCEVAddExpr::get(Imm, NewOp);
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000655 } else {
Chris Lattner2959f002006-02-04 07:36:50 +0000656 NewOps.push_back(NewOp);
Nate Begemane68bcd12005-07-30 00:15:07 +0000657 }
Chris Lattner2959f002006-02-04 07:36:50 +0000658 }
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000659
660 if (NewOps.empty())
661 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
662 else
663 Val = SCEVAddExpr::get(NewOps);
664 return;
Chris Lattnerfc624702005-08-03 23:44:42 +0000665 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
666 // Try to pull immediates out of the start value of nested addrec's.
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000667 SCEVHandle Start = SARE->getStart();
668 MoveImmediateValues(Start, Imm, isAddress, L);
669
670 if (Start != SARE->getStart()) {
671 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
672 Ops[0] = Start;
673 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
674 }
675 return;
Chris Lattner2959f002006-02-04 07:36:50 +0000676 } else if (SCEVMulExpr *SME = dyn_cast<SCEVMulExpr>(Val)) {
677 // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
678 if (isAddress && isTargetConstant(SME->getOperand(0)) &&
679 SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
680
681 SCEVHandle SubImm = SCEVUnknown::getIntegerSCEV(0, Val->getType());
682 SCEVHandle NewOp = SME->getOperand(1);
683 MoveImmediateValues(NewOp, SubImm, isAddress, L);
684
685 // If we extracted something out of the subexpressions, see if we can
686 // simplify this!
687 if (NewOp != SME->getOperand(1)) {
688 // Scale SubImm up by "8". If the result is a target constant, we are
689 // good.
690 SubImm = SCEVMulExpr::get(SubImm, SME->getOperand(0));
691 if (isTargetConstant(SubImm)) {
692 // Accumulate the immediate.
693 Imm = SCEVAddExpr::get(Imm, SubImm);
694
695 // Update what is left of 'Val'.
696 Val = SCEVMulExpr::get(SME->getOperand(0), NewOp);
697 return;
698 }
699 }
700 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000701 }
702
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000703 // Loop-variant expressions must stay in the immediate field of the
704 // expression.
705 if ((isAddress && isTargetConstant(Val)) ||
706 !Val->isLoopInvariant(L)) {
707 Imm = SCEVAddExpr::get(Imm, Val);
708 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
709 return;
Chris Lattner0f7c0fa2005-08-04 19:26:19 +0000710 }
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000711
712 // Otherwise, no immediates to move.
Nate Begemane68bcd12005-07-30 00:15:07 +0000713}
714
Chris Lattner5949d492005-08-13 07:27:18 +0000715
716/// IncrementAddExprUses - Decompose the specified expression into its added
717/// subexpressions, and increment SubExpressionUseCounts for each of these
718/// decomposed parts.
719static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
720 SCEVHandle Expr) {
721 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
722 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
723 SeparateSubExprs(SubExprs, AE->getOperand(j));
724 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
725 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Expr->getType());
726 if (SARE->getOperand(0) == Zero) {
727 SubExprs.push_back(Expr);
728 } else {
729 // Compute the addrec with zero as its base.
730 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
731 Ops[0] = Zero; // Start with zero base.
732 SubExprs.push_back(SCEVAddRecExpr::get(Ops, SARE->getLoop()));
733
734
735 SeparateSubExprs(SubExprs, SARE->getOperand(0));
736 }
737 } else if (!isa<SCEVConstant>(Expr) ||
738 !cast<SCEVConstant>(Expr)->getValue()->isNullValue()) {
739 // Do not add zero.
740 SubExprs.push_back(Expr);
741 }
742}
743
744
Chris Lattnera091ff12005-08-09 00:18:09 +0000745/// RemoveCommonExpressionsFromUseBases - Look through all of the uses in Bases,
746/// removing any common subexpressions from it. Anything truly common is
747/// removed, accumulated, and returned. This looks for things like (a+b+c) and
748/// (a+c+d) -> (a+c). The common expression is *removed* from the Bases.
749static SCEVHandle
750RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses) {
751 unsigned NumUses = Uses.size();
752
753 // Only one use? Use its base, regardless of what it is!
754 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Uses[0].Base->getType());
755 SCEVHandle Result = Zero;
756 if (NumUses == 1) {
757 std::swap(Result, Uses[0].Base);
758 return Result;
759 }
760
761 // To find common subexpressions, count how many of Uses use each expression.
762 // If any subexpressions are used Uses.size() times, they are common.
763 std::map<SCEVHandle, unsigned> SubExpressionUseCounts;
764
Chris Lattner192cd182005-10-11 18:41:04 +0000765 // UniqueSubExprs - Keep track of all of the subexpressions we see in the
766 // order we see them.
767 std::vector<SCEVHandle> UniqueSubExprs;
768
Chris Lattner5949d492005-08-13 07:27:18 +0000769 std::vector<SCEVHandle> SubExprs;
770 for (unsigned i = 0; i != NumUses; ++i) {
771 // If the base is zero (which is common), return zero now, there are no
772 // CSEs we can find.
773 if (Uses[i].Base == Zero) return Zero;
774
775 // Split the expression into subexprs.
776 SeparateSubExprs(SubExprs, Uses[i].Base);
777 // Add one to SubExpressionUseCounts for each subexpr present.
778 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
Chris Lattner192cd182005-10-11 18:41:04 +0000779 if (++SubExpressionUseCounts[SubExprs[j]] == 1)
780 UniqueSubExprs.push_back(SubExprs[j]);
Chris Lattner5949d492005-08-13 07:27:18 +0000781 SubExprs.clear();
782 }
783
Chris Lattner192cd182005-10-11 18:41:04 +0000784 // Now that we know how many times each is used, build Result. Iterate over
785 // UniqueSubexprs so that we have a stable ordering.
786 for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
787 std::map<SCEVHandle, unsigned>::iterator I =
788 SubExpressionUseCounts.find(UniqueSubExprs[i]);
789 assert(I != SubExpressionUseCounts.end() && "Entry not found?");
Chris Lattnera091ff12005-08-09 00:18:09 +0000790 if (I->second == NumUses) { // Found CSE!
791 Result = SCEVAddExpr::get(Result, I->first);
Chris Lattnera091ff12005-08-09 00:18:09 +0000792 } else {
793 // Remove non-cse's from SubExpressionUseCounts.
Chris Lattner192cd182005-10-11 18:41:04 +0000794 SubExpressionUseCounts.erase(I);
Chris Lattnera091ff12005-08-09 00:18:09 +0000795 }
Chris Lattner192cd182005-10-11 18:41:04 +0000796 }
Chris Lattnera091ff12005-08-09 00:18:09 +0000797
798 // If we found no CSE's, return now.
799 if (Result == Zero) return Result;
800
801 // Otherwise, remove all of the CSE's we found from each of the base values.
Chris Lattner5949d492005-08-13 07:27:18 +0000802 for (unsigned i = 0; i != NumUses; ++i) {
803 // Split the expression into subexprs.
804 SeparateSubExprs(SubExprs, Uses[i].Base);
805
806 // Remove any common subexpressions.
807 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
808 if (SubExpressionUseCounts.count(SubExprs[j])) {
809 SubExprs.erase(SubExprs.begin()+j);
810 --j; --e;
811 }
812
813 // Finally, the non-shared expressions together.
814 if (SubExprs.empty())
Chris Lattnera091ff12005-08-09 00:18:09 +0000815 Uses[i].Base = Zero;
Chris Lattner5949d492005-08-13 07:27:18 +0000816 else
817 Uses[i].Base = SCEVAddExpr::get(SubExprs);
Chris Lattner47d3ec32005-08-13 07:42:01 +0000818 SubExprs.clear();
Chris Lattner5949d492005-08-13 07:27:18 +0000819 }
Chris Lattnera091ff12005-08-09 00:18:09 +0000820
821 return Result;
822}
823
824
Nate Begemane68bcd12005-07-30 00:15:07 +0000825/// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
826/// stride of IV. All of the users may have different starting values, and this
827/// may not be the only stride (we know it is if isOnlyStride is true).
Chris Lattneredff91a2005-08-10 00:45:21 +0000828void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
Chris Lattner430d0022005-08-03 22:21:05 +0000829 IVUsersOfOneStride &Uses,
830 Loop *L,
Nate Begemane68bcd12005-07-30 00:15:07 +0000831 bool isOnlyStride) {
832 // Transform our list of users and offsets to a bit more complex table. In
Chris Lattner37c24cc2005-08-08 22:56:21 +0000833 // this new vector, each 'BasedUser' contains 'Base' the base of the
834 // strided accessas well as the old information from Uses. We progressively
835 // move information from the Base field to the Imm field, until we eventually
836 // have the full access expression to rewrite the use.
837 std::vector<BasedUser> UsersToProcess;
Nate Begemane68bcd12005-07-30 00:15:07 +0000838 UsersToProcess.reserve(Uses.Users.size());
Chris Lattner37c24cc2005-08-08 22:56:21 +0000839 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
840 UsersToProcess.push_back(Uses.Users[i]);
841
842 // Move any loop invariant operands from the offset field to the immediate
843 // field of the use, so that we don't try to use something before it is
844 // computed.
845 MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
846 UsersToProcess.back().Imm, L);
847 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000848 "Base value is not loop invariant!");
Nate Begemane68bcd12005-07-30 00:15:07 +0000849 }
Chris Lattner37ed8952005-08-08 22:32:34 +0000850
Chris Lattnera091ff12005-08-09 00:18:09 +0000851 // We now have a whole bunch of uses of like-strided induction variables, but
852 // they might all have different bases. We want to emit one PHI node for this
853 // stride which we fold as many common expressions (between the IVs) into as
854 // possible. Start by identifying the common expressions in the base values
855 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
856 // "A+B"), emit it to the preheader, then remove the expression from the
857 // UsersToProcess base values.
858 SCEVHandle CommonExprs = RemoveCommonExpressionsFromUseBases(UsersToProcess);
859
Chris Lattner37ed8952005-08-08 22:32:34 +0000860 // Next, figure out what we can represent in the immediate fields of
861 // instructions. If we can represent anything there, move it to the imm
Chris Lattnera091ff12005-08-09 00:18:09 +0000862 // fields of the BasedUsers. We do this so that it increases the commonality
863 // of the remaining uses.
Chris Lattner37ed8952005-08-08 22:32:34 +0000864 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
Chris Lattner5cf983e2005-08-16 00:38:11 +0000865 // If the user is not in the current loop, this means it is using the exit
866 // value of the IV. Do not put anything in the base, make sure it's all in
867 // the immediate field to allow as much factoring as possible.
868 if (!L->contains(UsersToProcess[i].Inst->getParent())) {
Chris Lattnerea7dfd52005-08-17 21:22:41 +0000869 UsersToProcess[i].Imm = SCEVAddExpr::get(UsersToProcess[i].Imm,
870 UsersToProcess[i].Base);
871 UsersToProcess[i].Base =
872 SCEVUnknown::getIntegerSCEV(0, UsersToProcess[i].Base->getType());
Chris Lattner5cf983e2005-08-16 00:38:11 +0000873 } else {
874
875 // Addressing modes can be folded into loads and stores. Be careful that
876 // the store is through the expression, not of the expression though.
877 bool isAddress = isa<LoadInst>(UsersToProcess[i].Inst);
878 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
879 if (SI->getOperand(1) == UsersToProcess[i].OperandValToReplace)
880 isAddress = true;
881
882 MoveImmediateValues(UsersToProcess[i].Base, UsersToProcess[i].Imm,
883 isAddress, L);
884 }
Chris Lattner37ed8952005-08-08 22:32:34 +0000885 }
886
Chris Lattnera091ff12005-08-09 00:18:09 +0000887 // Now that we know what we need to do, insert the PHI node itself.
888 //
889 DEBUG(std::cerr << "INSERTING IV of STRIDE " << *Stride << " and BASE "
890 << *CommonExprs << " :\n");
891
892 SCEVExpander Rewriter(*SE, *LI);
893 SCEVExpander PreheaderRewriter(*SE, *LI);
Chris Lattner37ed8952005-08-08 22:32:34 +0000894
Chris Lattnera091ff12005-08-09 00:18:09 +0000895 BasicBlock *Preheader = L->getLoopPreheader();
896 Instruction *PreInsertPt = Preheader->getTerminator();
897 Instruction *PhiInsertBefore = L->getHeader()->begin();
Chris Lattner37ed8952005-08-08 22:32:34 +0000898
Chris Lattner8048b852005-09-12 17:11:27 +0000899 BasicBlock *LatchBlock = L->getLoopLatch();
Chris Lattnerbb78c972005-08-03 23:30:08 +0000900
Chris Lattnera091ff12005-08-09 00:18:09 +0000901 // Create a new Phi for this base, and stick it in the loop header.
902 const Type *ReplacedTy = CommonExprs->getType();
903 PHINode *NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
904 ++NumInserted;
905
Chris Lattneredff91a2005-08-10 00:45:21 +0000906 // Insert the stride into the preheader.
907 Value *StrideV = PreheaderRewriter.expandCodeFor(Stride, PreInsertPt,
908 ReplacedTy);
909 if (!isa<ConstantInt>(StrideV)) ++NumVariable;
910
911
Chris Lattnera091ff12005-08-09 00:18:09 +0000912 // Emit the initial base value into the loop preheader, and add it to the
913 // Phi node.
914 Value *PHIBaseV = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt,
915 ReplacedTy);
916 NewPHI->addIncoming(PHIBaseV, Preheader);
917
918 // Emit the increment of the base value before the terminator of the loop
919 // latch block, and add it to the Phi node.
920 SCEVHandle IncExp = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
Chris Lattneredff91a2005-08-10 00:45:21 +0000921 SCEVUnknown::get(StrideV));
Chris Lattnera091ff12005-08-09 00:18:09 +0000922
923 Value *IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator(),
924 ReplacedTy);
925 IncV->setName(NewPHI->getName()+".inc");
926 NewPHI->addIncoming(IncV, LatchBlock);
927
Chris Lattnerdb23c742005-08-03 22:51:21 +0000928 // Sort by the base value, so that all IVs with identical bases are next to
Chris Lattnera091ff12005-08-09 00:18:09 +0000929 // each other.
Nate Begemane68bcd12005-07-30 00:15:07 +0000930 while (!UsersToProcess.empty()) {
Chris Lattner5c9d63d2005-10-11 18:30:57 +0000931 SCEVHandle Base = UsersToProcess.back().Base;
Chris Lattnerbb78c972005-08-03 23:30:08 +0000932
Chris Lattnera091ff12005-08-09 00:18:09 +0000933 DEBUG(std::cerr << " INSERTING code for BASE = " << *Base << ":\n");
Chris Lattnerbb78c972005-08-03 23:30:08 +0000934
Chris Lattnera091ff12005-08-09 00:18:09 +0000935 // Emit the code for Base into the preheader.
Chris Lattnerc70bbc02005-08-08 05:47:49 +0000936 Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt,
937 ReplacedTy);
Chris Lattnera091ff12005-08-09 00:18:09 +0000938
939 // If BaseV is a constant other than 0, make sure that it gets inserted into
940 // the preheader, instead of being forward substituted into the uses. We do
941 // this by forcing a noop cast to be inserted into the preheader in this
942 // case.
943 if (Constant *C = dyn_cast<Constant>(BaseV))
Chris Lattner530fe6a2005-09-10 01:18:45 +0000944 if (!C->isNullValue() && !isTargetConstant(Base)) {
Chris Lattnera091ff12005-08-09 00:18:09 +0000945 // We want this constant emitted into the preheader!
946 BaseV = new CastInst(BaseV, BaseV->getType(), "preheaderinsert",
947 PreInsertPt);
948 }
949
Nate Begemane68bcd12005-07-30 00:15:07 +0000950 // Emit the code to add the immediate offset to the Phi value, just before
Chris Lattnerdb23c742005-08-03 22:51:21 +0000951 // the instructions that we identified as using this stride and base.
Chris Lattner5c9d63d2005-10-11 18:30:57 +0000952 unsigned ScanPos = 0;
953 do {
954 BasedUser &User = UsersToProcess.back();
Jeff Cohen546fd592005-07-30 18:33:25 +0000955
Chris Lattnera091ff12005-08-09 00:18:09 +0000956 // If this instruction wants to use the post-incremented value, move it
957 // after the post-inc and use its value instead of the PHI.
958 Value *RewriteOp = NewPHI;
959 if (User.isUseOfPostIncrementedValue) {
960 RewriteOp = IncV;
Chris Lattnera6764832005-09-12 06:04:47 +0000961
962 // If this user is in the loop, make sure it is the last thing in the
963 // loop to ensure it is dominated by the increment.
964 if (L->contains(User.Inst->getParent()))
965 User.Inst->moveBefore(LatchBlock->getTerminator());
Chris Lattnera091ff12005-08-09 00:18:09 +0000966 }
967 SCEVHandle RewriteExpr = SCEVUnknown::get(RewriteOp);
968
Chris Lattnerdb23c742005-08-03 22:51:21 +0000969 // Clear the SCEVExpander's expression map so that we are guaranteed
970 // to have the code emitted where we expect it.
971 Rewriter.clear();
Chris Lattnera091ff12005-08-09 00:18:09 +0000972
Chris Lattnera6d7c352005-08-04 20:03:32 +0000973 // Now that we know what we need to do, insert code before User for the
974 // immediate and any loop-variant expressions.
Chris Lattnera091ff12005-08-09 00:18:09 +0000975 if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isNullValue())
976 // Add BaseV to the PHI value if needed.
977 RewriteExpr = SCEVAddExpr::get(RewriteExpr, SCEVUnknown::get(BaseV));
978
Chris Lattner8447b492005-08-12 22:22:17 +0000979 User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter, L, this);
Jeff Cohen546fd592005-07-30 18:33:25 +0000980
Chris Lattnerdb23c742005-08-03 22:51:21 +0000981 // Mark old value we replaced as possibly dead, so that it is elminated
982 // if we just replaced the last use of that value.
Chris Lattnera6d7c352005-08-04 20:03:32 +0000983 DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
Nate Begemane68bcd12005-07-30 00:15:07 +0000984
Chris Lattner5c9d63d2005-10-11 18:30:57 +0000985 UsersToProcess.pop_back();
Chris Lattnerdb23c742005-08-03 22:51:21 +0000986 ++NumReduced;
Chris Lattner5c9d63d2005-10-11 18:30:57 +0000987
988 // If there are any more users to process with the same base, move one of
989 // them to the end of the list so that we will process it.
990 if (!UsersToProcess.empty()) {
991 for (unsigned e = UsersToProcess.size(); ScanPos != e; ++ScanPos)
992 if (UsersToProcess[ScanPos].Base == Base) {
993 std::swap(UsersToProcess[ScanPos], UsersToProcess.back());
994 break;
995 }
996 }
997 } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
Nate Begemane68bcd12005-07-30 00:15:07 +0000998 // TODO: Next, find out which base index is the most common, pull it out.
999 }
1000
1001 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1002 // different starting values, into different PHIs.
Nate Begemane68bcd12005-07-30 00:15:07 +00001003}
1004
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001005// OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
1006// uses in the loop, look to see if we can eliminate some, in favor of using
1007// common indvars for the different uses.
1008void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
1009 // TODO: implement optzns here.
1010
1011
1012
1013
1014 // Finally, get the terminating condition for the loop if possible. If we
1015 // can, we want to change it to use a post-incremented version of its
1016 // induction variable, to allow coallescing the live ranges for the IV into
1017 // one register value.
1018 PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
1019 BasicBlock *Preheader = L->getLoopPreheader();
1020 BasicBlock *LatchBlock =
1021 SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
1022 BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
1023 if (!TermBr || TermBr->isUnconditional() ||
1024 !isa<SetCondInst>(TermBr->getCondition()))
1025 return;
1026 SetCondInst *Cond = cast<SetCondInst>(TermBr->getCondition());
1027
1028 // Search IVUsesByStride to find Cond's IVUse if there is one.
1029 IVStrideUse *CondUse = 0;
Chris Lattneredff91a2005-08-10 00:45:21 +00001030 const SCEVHandle *CondStride = 0;
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001031
Chris Lattnerb7a38942005-10-11 18:17:57 +00001032 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e && !CondUse;
1033 ++Stride) {
1034 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1035 IVUsesByStride.find(StrideOrder[Stride]);
1036 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1037
1038 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
1039 E = SI->second.Users.end(); UI != E; ++UI)
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001040 if (UI->User == Cond) {
1041 CondUse = &*UI;
Chris Lattnerb7a38942005-10-11 18:17:57 +00001042 CondStride = &SI->first;
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001043 // NOTE: we could handle setcc instructions with multiple uses here, but
1044 // InstCombine does it as well for simple uses, it's not clear that it
1045 // occurs enough in real life to handle.
1046 break;
1047 }
Chris Lattnerb7a38942005-10-11 18:17:57 +00001048 }
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001049 if (!CondUse) return; // setcc doesn't use the IV.
1050
1051 // setcc stride is complex, don't mess with users.
Chris Lattneredff91a2005-08-10 00:45:21 +00001052 // FIXME: Evaluate whether this is a good idea or not.
1053 if (!isa<SCEVConstant>(*CondStride)) return;
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001054
1055 // It's possible for the setcc instruction to be anywhere in the loop, and
1056 // possible for it to have multiple users. If it is not immediately before
1057 // the latch block branch, move it.
1058 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
1059 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
1060 Cond->moveBefore(TermBr);
1061 } else {
1062 // Otherwise, clone the terminating condition and insert into the loopend.
1063 Cond = cast<SetCondInst>(Cond->clone());
1064 Cond->setName(L->getHeader()->getName() + ".termcond");
1065 LatchBlock->getInstList().insert(TermBr, Cond);
1066
1067 // Clone the IVUse, as the old use still exists!
Chris Lattneredff91a2005-08-10 00:45:21 +00001068 IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001069 CondUse->OperandValToReplace);
Chris Lattneredff91a2005-08-10 00:45:21 +00001070 CondUse = &IVUsesByStride[*CondStride].Users.back();
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001071 }
1072 }
1073
1074 // If we get to here, we know that we can transform the setcc instruction to
1075 // use the post-incremented version of the IV, allowing us to coallesce the
1076 // live ranges for the IV correctly.
Chris Lattneredff91a2005-08-10 00:45:21 +00001077 CondUse->Offset = SCEV::getMinusSCEV(CondUse->Offset, *CondStride);
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001078 CondUse->isUseOfPostIncrementedValue = true;
1079}
Nate Begemane68bcd12005-07-30 00:15:07 +00001080
Nate Begemanb18121e2004-10-18 21:08:22 +00001081void LoopStrengthReduce::runOnLoop(Loop *L) {
1082 // First step, transform all loops nesting inside of this loop.
1083 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
1084 runOnLoop(*I);
1085
Nate Begemane68bcd12005-07-30 00:15:07 +00001086 // Next, find all uses of induction variables in this loop, and catagorize
1087 // them by stride. Start by finding all of the PHI nodes in the header for
1088 // this loop. If they are induction variables, inspect their uses.
Chris Lattnereaf24722005-08-04 17:40:30 +00001089 std::set<Instruction*> Processed; // Don't reprocess instructions.
Nate Begemane68bcd12005-07-30 00:15:07 +00001090 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
Chris Lattnereaf24722005-08-04 17:40:30 +00001091 AddUsersIfInteresting(I, L, Processed);
Nate Begemanb18121e2004-10-18 21:08:22 +00001092
Nate Begemane68bcd12005-07-30 00:15:07 +00001093 // If we have nothing to do, return.
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001094 if (IVUsesByStride.empty()) return;
1095
1096 // Optimize induction variables. Some indvar uses can be transformed to use
1097 // strides that will be needed for other purposes. A common example of this
1098 // is the exit test for the loop, which can often be rewritten to use the
1099 // computation of some other indvar to decide when to terminate the loop.
1100 OptimizeIndvars(L);
1101
Misha Brukmanb1c93172005-04-21 23:48:37 +00001102
Nate Begemane68bcd12005-07-30 00:15:07 +00001103 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
1104 // doing computation in byte values, promote to 32-bit values if safe.
1105
1106 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
1107 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
1108 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
1109 // to be careful that IV's are all the same type. Only works for intptr_t
1110 // indvars.
1111
1112 // If we only have one stride, we can more aggressively eliminate some things.
1113 bool HasOneStride = IVUsesByStride.size() == 1;
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001114
Chris Lattnera091ff12005-08-09 00:18:09 +00001115 // Note: this processes each stride/type pair individually. All users passed
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001116 // into StrengthReduceStridedIVUsers have the same type AND stride. Also,
1117 // node that we iterate over IVUsesByStride indirectly by using StrideOrder.
1118 // This extra layer of indirection makes the ordering of strides deterministic
1119 // - not dependent on map order.
1120 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
1121 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1122 IVUsesByStride.find(StrideOrder[Stride]);
1123 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
Nate Begemane68bcd12005-07-30 00:15:07 +00001124 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001125 }
Nate Begemanb18121e2004-10-18 21:08:22 +00001126
1127 // Clean up after ourselves
1128 if (!DeadInsts.empty()) {
1129 DeleteTriviallyDeadInstructions(DeadInsts);
1130
Nate Begemane68bcd12005-07-30 00:15:07 +00001131 BasicBlock::iterator I = L->getHeader()->begin();
1132 PHINode *PN;
Chris Lattnerdcce49e2005-08-02 02:44:31 +00001133 while ((PN = dyn_cast<PHINode>(I))) {
Chris Lattner564900e2005-08-02 00:41:11 +00001134 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
1135
Chris Lattnerc6c4d992005-08-09 23:39:36 +00001136 // At this point, we know that we have killed one or more GEP
1137 // instructions. It is worth checking to see if the cann indvar is also
1138 // dead, so that we can remove it as well. The requirements for the cann
1139 // indvar to be considered dead are:
Nate Begemane68bcd12005-07-30 00:15:07 +00001140 // 1. the cann indvar has one use
1141 // 2. the use is an add instruction
1142 // 3. the add has one use
1143 // 4. the add is used by the cann indvar
1144 // If all four cases above are true, then we can remove both the add and
1145 // the cann indvar.
1146 // FIXME: this needs to eliminate an induction variable even if it's being
1147 // compared against some value to decide loop termination.
1148 if (PN->hasOneUse()) {
1149 BinaryOperator *BO = dyn_cast<BinaryOperator>(*(PN->use_begin()));
Chris Lattner75a44e12005-08-02 02:52:02 +00001150 if (BO && BO->hasOneUse()) {
1151 if (PN == *(BO->use_begin())) {
1152 DeadInsts.insert(BO);
1153 // Break the cycle, then delete the PHI.
1154 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattner84e9baa2005-08-03 21:36:09 +00001155 SE->deleteInstructionFromRecords(PN);
Chris Lattner75a44e12005-08-02 02:52:02 +00001156 PN->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +00001157 }
Chris Lattner75a44e12005-08-02 02:52:02 +00001158 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001159 }
Nate Begemanb18121e2004-10-18 21:08:22 +00001160 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001161 DeleteTriviallyDeadInstructions(DeadInsts);
Nate Begemanb18121e2004-10-18 21:08:22 +00001162 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001163
Chris Lattner11e7a5e2005-08-05 01:30:11 +00001164 CastedPointers.clear();
Nate Begemane68bcd12005-07-30 00:15:07 +00001165 IVUsesByStride.clear();
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001166 StrideOrder.clear();
Nate Begemane68bcd12005-07-30 00:15:07 +00001167 return;
Nate Begemanb18121e2004-10-18 21:08:22 +00001168}