blob: 49d0c58a644d409ab3eb95f85994a2d9d0f17e78 [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
179 BasicBlock::iterator InsertPt;
180 if (Argument *Arg = dyn_cast<Argument>(V)) {
181 // Insert into the entry of the function, after any allocas.
182 InsertPt = Arg->getParent()->begin()->begin();
183 while (isa<AllocaInst>(InsertPt)) ++InsertPt;
184 } else {
185 if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
186 InsertPt = II->getNormalDest()->begin();
187 } else {
188 InsertPt = cast<Instruction>(V);
189 ++InsertPt;
190 }
191
192 // Do not insert casts into the middle of PHI node blocks.
193 while (isa<PHINode>(InsertPt)) ++InsertPt;
194 }
Chris Lattneracc42c42005-08-04 19:08:16 +0000195
196 New = new CastInst(V, UIntPtrTy, V->getName(), InsertPt);
197 DeadInsts.insert(cast<Instruction>(New));
198 return New;
Chris Lattner6f286b72005-08-04 01:19:13 +0000199}
200
201
Nate Begemanb18121e2004-10-18 21:08:22 +0000202/// DeleteTriviallyDeadInstructions - If any of the instructions is the
203/// specified set are trivially dead, delete them and see if this makes any of
204/// their operands subsequently dead.
205void LoopStrengthReduce::
206DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
207 while (!Insts.empty()) {
208 Instruction *I = *Insts.begin();
209 Insts.erase(Insts.begin());
210 if (isInstructionTriviallyDead(I)) {
Jeff Cohen8ea6f9e2005-03-01 03:46:11 +0000211 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
212 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
213 Insts.insert(U);
Chris Lattner84e9baa2005-08-03 21:36:09 +0000214 SE->deleteInstructionFromRecords(I);
215 I->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +0000216 Changed = true;
217 }
218 }
219}
220
Jeff Cohen39751c32005-02-27 19:37:07 +0000221
Chris Lattnereaf24722005-08-04 17:40:30 +0000222/// GetExpressionSCEV - Compute and return the SCEV for the specified
223/// instruction.
224SCEVHandle LoopStrengthReduce::GetExpressionSCEV(Instruction *Exp, Loop *L) {
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000225 // Scalar Evolutions doesn't know how to compute SCEV's for GEP instructions.
226 // If this is a GEP that SE doesn't know about, compute it now and insert it.
227 // If this is not a GEP, or if we have already done this computation, just let
228 // SE figure it out.
Chris Lattnereaf24722005-08-04 17:40:30 +0000229 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000230 if (!GEP || SE->hasSCEV(GEP))
Chris Lattnereaf24722005-08-04 17:40:30 +0000231 return SE->getSCEV(Exp);
232
Nate Begemane68bcd12005-07-30 00:15:07 +0000233 // Analyze all of the subscripts of this getelementptr instruction, looking
234 // for uses that are determined by the trip count of L. First, skip all
235 // operands the are not dependent on the IV.
236
237 // Build up the base expression. Insert an LLVM cast of the pointer to
238 // uintptr_t first.
Chris Lattnereaf24722005-08-04 17:40:30 +0000239 SCEVHandle GEPVal = SCEVUnknown::get(getCastedVersionOf(GEP->getOperand(0)));
Nate Begemane68bcd12005-07-30 00:15:07 +0000240
241 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnereaf24722005-08-04 17:40:30 +0000242
243 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
Nate Begemane68bcd12005-07-30 00:15:07 +0000244 // If this is a use of a recurrence that we can analyze, and it comes before
245 // Op does in the GEP operand list, we will handle this when we process this
246 // operand.
247 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
248 const StructLayout *SL = TD->getStructLayout(STy);
249 unsigned Idx = cast<ConstantUInt>(GEP->getOperand(i))->getValue();
250 uint64_t Offset = SL->MemberOffsets[Idx];
Chris Lattnereaf24722005-08-04 17:40:30 +0000251 GEPVal = SCEVAddExpr::get(GEPVal,
252 SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy));
Nate Begemane68bcd12005-07-30 00:15:07 +0000253 } else {
Chris Lattneracc42c42005-08-04 19:08:16 +0000254 Value *OpVal = getCastedVersionOf(GEP->getOperand(i));
255 SCEVHandle Idx = SE->getSCEV(OpVal);
256
Chris Lattnereaf24722005-08-04 17:40:30 +0000257 uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
258 if (TypeSize != 1)
259 Idx = SCEVMulExpr::get(Idx,
260 SCEVConstant::get(ConstantUInt::get(UIntPtrTy,
261 TypeSize)));
262 GEPVal = SCEVAddExpr::get(GEPVal, Idx);
Nate Begemane68bcd12005-07-30 00:15:07 +0000263 }
264 }
265
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000266 SE->setSCEV(GEP, GEPVal);
Chris Lattnereaf24722005-08-04 17:40:30 +0000267 return GEPVal;
Nate Begemane68bcd12005-07-30 00:15:07 +0000268}
269
Chris Lattneracc42c42005-08-04 19:08:16 +0000270/// getSCEVStartAndStride - Compute the start and stride of this expression,
271/// returning false if the expression is not a start/stride pair, or true if it
272/// is. The stride must be a loop invariant expression, but the start may be
273/// a mix of loop invariant and loop variant expressions.
274static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
Chris Lattneredff91a2005-08-10 00:45:21 +0000275 SCEVHandle &Start, SCEVHandle &Stride) {
Chris Lattneracc42c42005-08-04 19:08:16 +0000276 SCEVHandle TheAddRec = Start; // Initialize to zero.
277
278 // If the outer level is an AddExpr, the operands are all start values except
279 // for a nested AddRecExpr.
280 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
281 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
282 if (SCEVAddRecExpr *AddRec =
283 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
284 if (AddRec->getLoop() == L)
285 TheAddRec = SCEVAddExpr::get(AddRec, TheAddRec);
286 else
287 return false; // Nested IV of some sort?
288 } else {
289 Start = SCEVAddExpr::get(Start, AE->getOperand(i));
290 }
291
292 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SH)) {
293 TheAddRec = SH;
294 } else {
295 return false; // not analyzable.
296 }
297
298 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
299 if (!AddRec || AddRec->getLoop() != L) return false;
300
301 // FIXME: Generalize to non-affine IV's.
302 if (!AddRec->isAffine()) return false;
303
304 Start = SCEVAddExpr::get(Start, AddRec->getOperand(0));
305
Chris Lattneracc42c42005-08-04 19:08:16 +0000306 if (!isa<SCEVConstant>(AddRec->getOperand(1)))
Chris Lattneredff91a2005-08-10 00:45:21 +0000307 DEBUG(std::cerr << "[" << L->getHeader()->getName()
308 << "] Variable stride: " << *AddRec << "\n");
Chris Lattneracc42c42005-08-04 19:08:16 +0000309
Chris Lattneredff91a2005-08-10 00:45:21 +0000310 Stride = AddRec->getOperand(1);
311 // Check that all constant strides are the unsigned type, we don't want to
312 // have two IV's one of signed stride 4 and one of unsigned stride 4 to not be
313 // merged.
314 assert((!isa<SCEVConstant>(Stride) || Stride->getType()->isUnsigned()) &&
Chris Lattneracc42c42005-08-04 19:08:16 +0000315 "Constants should be canonicalized to unsigned!");
Chris Lattneredff91a2005-08-10 00:45:21 +0000316
Chris Lattneracc42c42005-08-04 19:08:16 +0000317 return true;
318}
319
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000320/// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
321/// and now we need to decide whether the user should use the preinc or post-inc
322/// value. If this user should use the post-inc version of the IV, return true.
323///
324/// Choosing wrong here can break dominance properties (if we choose to use the
325/// post-inc value when we cannot) or it can end up adding extra live-ranges to
326/// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
327/// should use the post-inc value).
328static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
Chris Lattnercb367102006-01-11 05:10:20 +0000329 Loop *L, ETForest *EF, Pass *P) {
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000330 // If the user is in the loop, use the preinc value.
331 if (L->contains(User->getParent())) return false;
332
Chris Lattnerf07a5872005-10-03 02:50:05 +0000333 BasicBlock *LatchBlock = L->getLoopLatch();
334
335 // Ok, the user is outside of the loop. If it is dominated by the latch
336 // block, use the post-inc value.
Chris Lattnercb367102006-01-11 05:10:20 +0000337 if (EF->dominates(LatchBlock, User->getParent()))
Chris Lattnerf07a5872005-10-03 02:50:05 +0000338 return true;
339
340 // There is one case we have to be careful of: PHI nodes. These little guys
341 // can live in blocks that do not dominate the latch block, but (since their
342 // uses occur in the predecessor block, not the block the PHI lives in) should
343 // still use the post-inc value. Check for this case now.
344 PHINode *PN = dyn_cast<PHINode>(User);
345 if (!PN) return false; // not a phi, not dominated by latch block.
346
347 // Look at all of the uses of IV by the PHI node. If any use corresponds to
348 // a block that is not dominated by the latch block, give up and use the
349 // preincremented value.
350 unsigned NumUses = 0;
351 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
352 if (PN->getIncomingValue(i) == IV) {
353 ++NumUses;
Chris Lattnercb367102006-01-11 05:10:20 +0000354 if (!EF->dominates(LatchBlock, PN->getIncomingBlock(i)))
Chris Lattnerf07a5872005-10-03 02:50:05 +0000355 return false;
356 }
357
358 // Okay, all uses of IV by PN are in predecessor blocks that really are
359 // dominated by the latch block. Split the critical edges and use the
360 // post-incremented value.
361 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
362 if (PN->getIncomingValue(i) == IV) {
363 SplitCriticalEdge(PN->getIncomingBlock(i), PN->getParent(), P);
364 if (--NumUses == 0) break;
365 }
366
367 return true;
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000368}
369
370
371
Nate Begemane68bcd12005-07-30 00:15:07 +0000372/// AddUsersIfInteresting - Inspect the specified instruction. If it is a
373/// reducible SCEV, recursively add its users to the IVUsesByStride set and
374/// return true. Otherwise, return false.
Chris Lattnereaf24722005-08-04 17:40:30 +0000375bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
376 std::set<Instruction*> &Processed) {
Chris Lattner5df0e362005-10-21 05:45:41 +0000377 if (!I->getType()->isInteger() && !isa<PointerType>(I->getType()))
378 return false; // Void and FP expressions cannot be reduced.
Chris Lattnereaf24722005-08-04 17:40:30 +0000379 if (!Processed.insert(I).second)
380 return true; // Instruction already handled.
381
Chris Lattneracc42c42005-08-04 19:08:16 +0000382 // Get the symbolic expression for this instruction.
Chris Lattnereaf24722005-08-04 17:40:30 +0000383 SCEVHandle ISE = GetExpressionSCEV(I, L);
Chris Lattneracc42c42005-08-04 19:08:16 +0000384 if (isa<SCEVCouldNotCompute>(ISE)) return false;
Chris Lattnereaf24722005-08-04 17:40:30 +0000385
Chris Lattneracc42c42005-08-04 19:08:16 +0000386 // Get the start and stride for this expression.
387 SCEVHandle Start = SCEVUnknown::getIntegerSCEV(0, ISE->getType());
Chris Lattneredff91a2005-08-10 00:45:21 +0000388 SCEVHandle Stride = Start;
Chris Lattneracc42c42005-08-04 19:08:16 +0000389 if (!getSCEVStartAndStride(ISE, L, Start, Stride))
390 return false; // Non-reducible symbolic expression, bail out.
391
Nate Begemane68bcd12005-07-30 00:15:07 +0000392 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){
393 Instruction *User = cast<Instruction>(*UI);
394
395 // Do not infinitely recurse on PHI nodes.
Chris Lattnerfd018c82005-09-13 02:09:55 +0000396 if (isa<PHINode>(User) && Processed.count(User))
Nate Begemane68bcd12005-07-30 00:15:07 +0000397 continue;
398
399 // If this is an instruction defined in a nested loop, or outside this loop,
Chris Lattnera0102fb2005-08-04 00:14:11 +0000400 // don't recurse into it.
Chris Lattneracc42c42005-08-04 19:08:16 +0000401 bool AddUserToIVUsers = false;
Chris Lattnera0102fb2005-08-04 00:14:11 +0000402 if (LI->getLoopFor(User->getParent()) != L) {
Chris Lattnerfd018c82005-09-13 02:09:55 +0000403 DEBUG(std::cerr << "FOUND USER in other loop: " << *User
Chris Lattnera0102fb2005-08-04 00:14:11 +0000404 << " OF SCEV: " << *ISE << "\n");
Chris Lattneracc42c42005-08-04 19:08:16 +0000405 AddUserToIVUsers = true;
Chris Lattnereaf24722005-08-04 17:40:30 +0000406 } else if (!AddUsersIfInteresting(User, L, Processed)) {
Chris Lattner65107492005-08-04 00:40:47 +0000407 DEBUG(std::cerr << "FOUND USER: " << *User
408 << " OF SCEV: " << *ISE << "\n");
Chris Lattneracc42c42005-08-04 19:08:16 +0000409 AddUserToIVUsers = true;
410 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000411
Chris Lattneracc42c42005-08-04 19:08:16 +0000412 if (AddUserToIVUsers) {
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000413 IVUsersOfOneStride &StrideUses = IVUsesByStride[Stride];
414 if (StrideUses.Users.empty()) // First occurance of this stride?
415 StrideOrder.push_back(Stride);
416
Chris Lattner65107492005-08-04 00:40:47 +0000417 // Okay, we found a user that we cannot reduce. Analyze the instruction
Chris Lattnera6764832005-09-12 06:04:47 +0000418 // and decide what to do with it. If we are a use inside of the loop, use
419 // the value before incrementation, otherwise use it after incrementation.
Chris Lattnercb367102006-01-11 05:10:20 +0000420 if (IVUseShouldUsePostIncValue(User, I, L, EF, this)) {
Chris Lattnera6764832005-09-12 06:04:47 +0000421 // The value used will be incremented by the stride more than we are
422 // expecting, so subtract this off.
423 SCEVHandle NewStart = SCEV::getMinusSCEV(Start, Stride);
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000424 StrideUses.addUser(NewStart, User, I);
425 StrideUses.Users.back().isUseOfPostIncrementedValue = true;
Chris Lattnerf07a5872005-10-03 02:50:05 +0000426 DEBUG(std::cerr << " USING POSTINC SCEV, START=" << *NewStart<< "\n");
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000427 } else {
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000428 StrideUses.addUser(Start, User, I);
Chris Lattnera6764832005-09-12 06:04:47 +0000429 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000430 }
431 }
432 return true;
433}
434
435namespace {
436 /// BasedUser - For a particular base value, keep information about how we've
437 /// partitioned the expression so far.
438 struct BasedUser {
Chris Lattner37c24cc2005-08-08 22:56:21 +0000439 /// Base - The Base value for the PHI node that needs to be inserted for
440 /// this use. As the use is processed, information gets moved from this
441 /// field to the Imm field (below). BasedUser values are sorted by this
442 /// field.
443 SCEVHandle Base;
444
Nate Begemane68bcd12005-07-30 00:15:07 +0000445 /// Inst - The instruction using the induction variable.
446 Instruction *Inst;
447
Chris Lattner430d0022005-08-03 22:21:05 +0000448 /// OperandValToReplace - The operand value of Inst to replace with the
449 /// EmittedBase.
450 Value *OperandValToReplace;
Nate Begemane68bcd12005-07-30 00:15:07 +0000451
452 /// Imm - The immediate value that should be added to the base immediately
453 /// before Inst, because it will be folded into the imm field of the
454 /// instruction.
455 SCEVHandle Imm;
456
457 /// EmittedBase - The actual value* to use for the base value of this
458 /// operation. This is null if we should just use zero so far.
459 Value *EmittedBase;
460
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000461 // isUseOfPostIncrementedValue - True if this should use the
462 // post-incremented version of this IV, not the preincremented version.
463 // This can only be set in special cases, such as the terminating setcc
Chris Lattnera6764832005-09-12 06:04:47 +0000464 // instruction for a loop and uses outside the loop that are dominated by
465 // the loop.
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000466 bool isUseOfPostIncrementedValue;
Chris Lattner37c24cc2005-08-08 22:56:21 +0000467
468 BasedUser(IVStrideUse &IVSU)
469 : Base(IVSU.Offset), Inst(IVSU.User),
470 OperandValToReplace(IVSU.OperandValToReplace),
471 Imm(SCEVUnknown::getIntegerSCEV(0, Base->getType())), EmittedBase(0),
472 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
Nate Begemane68bcd12005-07-30 00:15:07 +0000473
Chris Lattnera6d7c352005-08-04 20:03:32 +0000474 // Once we rewrite the code to insert the new IVs we want, update the
475 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
476 // to it.
Chris Lattnera091ff12005-08-09 00:18:09 +0000477 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattner8447b492005-08-12 22:22:17 +0000478 SCEVExpander &Rewriter, Loop *L,
479 Pass *P);
Chris Lattner2959f002006-02-04 07:36:50 +0000480
481 Value *InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
482 SCEVExpander &Rewriter,
483 Instruction *IP, Loop *L);
Nate Begemane68bcd12005-07-30 00:15:07 +0000484 void dump() const;
485 };
486}
487
488void BasedUser::dump() const {
Chris Lattner37c24cc2005-08-08 22:56:21 +0000489 std::cerr << " Base=" << *Base;
Nate Begemane68bcd12005-07-30 00:15:07 +0000490 std::cerr << " Imm=" << *Imm;
491 if (EmittedBase)
492 std::cerr << " EB=" << *EmittedBase;
493
494 std::cerr << " Inst: " << *Inst;
495}
496
Chris Lattner2959f002006-02-04 07:36:50 +0000497Value *BasedUser::InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
498 SCEVExpander &Rewriter,
499 Instruction *IP, Loop *L) {
500 // Figure out where we *really* want to insert this code. In particular, if
501 // the user is inside of a loop that is nested inside of L, we really don't
502 // want to insert this expression before the user, we'd rather pull it out as
503 // many loops as possible.
504 LoopInfo &LI = Rewriter.getLoopInfo();
505 Instruction *BaseInsertPt = IP;
506
507 // Figure out the most-nested loop that IP is in.
508 Loop *InsertLoop = LI.getLoopFor(IP->getParent());
509
510 // If InsertLoop is not L, and InsertLoop is nested inside of L, figure out
511 // the preheader of the outer-most loop where NewBase is not loop invariant.
512 while (InsertLoop && NewBase->isLoopInvariant(InsertLoop)) {
513 BaseInsertPt = InsertLoop->getLoopPreheader()->getTerminator();
514 InsertLoop = InsertLoop->getParentLoop();
515 }
516
517 // If there is no immediate value, skip the next part.
518 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Imm))
519 if (SC->getValue()->isNullValue())
520 return Rewriter.expandCodeFor(NewBase, BaseInsertPt,
521 OperandValToReplace->getType());
522
523 Value *Base = Rewriter.expandCodeFor(NewBase, BaseInsertPt);
524
525 // Always emit the immediate (if non-zero) into the same block as the user.
526 SCEVHandle NewValSCEV = SCEVAddExpr::get(SCEVUnknown::get(Base), Imm);
527 return Rewriter.expandCodeFor(NewValSCEV, IP,
528 OperandValToReplace->getType());
529}
530
531
Chris Lattnera6d7c352005-08-04 20:03:32 +0000532// Once we rewrite the code to insert the new IVs we want, update the
533// operands of Inst to use the new expression 'NewBase', with 'Imm' added
534// to it.
Chris Lattnera091ff12005-08-09 00:18:09 +0000535void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattner4fec86d2005-08-12 22:06:11 +0000536 SCEVExpander &Rewriter,
Chris Lattner8447b492005-08-12 22:22:17 +0000537 Loop *L, Pass *P) {
Chris Lattnera6d7c352005-08-04 20:03:32 +0000538 if (!isa<PHINode>(Inst)) {
Chris Lattner2959f002006-02-04 07:36:50 +0000539 Value *NewVal = InsertCodeForBaseAtPosition(NewBase, Rewriter, Inst, L);
Chris Lattnera6d7c352005-08-04 20:03:32 +0000540 // Replace the use of the operand Value with the new Phi we just created.
541 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
542 DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst);
543 return;
544 }
545
546 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000547 // expression into each operand block that uses it. Note that PHI nodes can
548 // have multiple entries for the same predecessor. We use a map to make sure
549 // that a PHI node only has a single Value* for each predecessor (which also
550 // prevents us from inserting duplicate code in some blocks).
551 std::map<BasicBlock*, Value*> InsertedCode;
Chris Lattnera6d7c352005-08-04 20:03:32 +0000552 PHINode *PN = cast<PHINode>(Inst);
553 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
554 if (PN->getIncomingValue(i) == OperandValToReplace) {
Chris Lattner4fec86d2005-08-12 22:06:11 +0000555 // If this is a critical edge, split the edge so that we do not insert the
Chris Lattnerfd018c82005-09-13 02:09:55 +0000556 // code on all predecessor/successor paths. We do this unless this is the
557 // canonical backedge for this loop, as this can make some inserted code
558 // be in an illegal position.
Chris Lattner8fcce172005-10-03 00:31:52 +0000559 BasicBlock *PHIPred = PN->getIncomingBlock(i);
560 if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
561 (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
Chris Lattner8fcce172005-10-03 00:31:52 +0000562
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000563 // First step, split the critical edge.
Chris Lattner8fcce172005-10-03 00:31:52 +0000564 SplitCriticalEdge(PHIPred, PN->getParent(), P);
Chris Lattner8447b492005-08-12 22:22:17 +0000565
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000566 // Next step: move the basic block. In particular, if the PHI node
567 // is outside of the loop, and PredTI is in the loop, we want to
568 // move the block to be immediately before the PHI block, not
569 // immediately after PredTI.
Chris Lattner8fcce172005-10-03 00:31:52 +0000570 if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000571 BasicBlock *NewBB = PN->getIncomingBlock(i);
572 NewBB->moveBefore(PN->getParent());
Chris Lattner4fec86d2005-08-12 22:06:11 +0000573 }
574 }
Chris Lattnera6d7c352005-08-04 20:03:32 +0000575
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000576 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
577 if (!Code) {
578 // Insert the code into the end of the predecessor block.
Chris Lattner2959f002006-02-04 07:36:50 +0000579 Instruction *InsertPt = PN->getIncomingBlock(i)->getTerminator();
580 Code = InsertCodeForBaseAtPosition(NewBase, Rewriter, InsertPt, L);
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000581 }
Chris Lattnera6d7c352005-08-04 20:03:32 +0000582
583 // Replace the use of the operand Value with the new Phi we just created.
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000584 PN->setIncomingValue(i, Code);
Chris Lattnera6d7c352005-08-04 20:03:32 +0000585 Rewriter.clear();
586 }
587 }
588 DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst);
589}
590
591
Nate Begemane68bcd12005-07-30 00:15:07 +0000592/// isTargetConstant - Return true if the following can be referenced by the
593/// immediate field of a target instruction.
594static bool isTargetConstant(const SCEVHandle &V) {
Jeff Cohen546fd592005-07-30 18:33:25 +0000595
Nate Begemane68bcd12005-07-30 00:15:07 +0000596 // FIXME: Look at the target to decide if &GV is a legal constant immediate.
Chris Lattner14203e82005-08-08 06:25:50 +0000597 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
598 // PPC allows a sign-extended 16-bit immediate field.
Chris Lattner07720072005-12-05 18:23:57 +0000599 int64_t V = SC->getValue()->getSExtValue();
600 if (V > -(1 << 16) && V < (1 << 16)-1)
601 return true;
Chris Lattner14203e82005-08-08 06:25:50 +0000602 return false;
603 }
Jeff Cohen546fd592005-07-30 18:33:25 +0000604
Nate Begemane68bcd12005-07-30 00:15:07 +0000605 return false; // ENABLE this for x86
Jeff Cohen546fd592005-07-30 18:33:25 +0000606
Nate Begemane68bcd12005-07-30 00:15:07 +0000607 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
608 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
609 if (CE->getOpcode() == Instruction::Cast)
610 if (isa<GlobalValue>(CE->getOperand(0)))
611 // FIXME: should check to see that the dest is uintptr_t!
612 return true;
613 return false;
614}
615
Chris Lattner37ed8952005-08-08 22:32:34 +0000616/// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
617/// loop varying to the Imm operand.
618static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
619 Loop *L) {
620 if (Val->isLoopInvariant(L)) return; // Nothing to do.
621
622 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
623 std::vector<SCEVHandle> NewOps;
624 NewOps.reserve(SAE->getNumOperands());
625
626 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
627 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
628 // If this is a loop-variant expression, it must stay in the immediate
629 // field of the expression.
630 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
631 } else {
632 NewOps.push_back(SAE->getOperand(i));
633 }
634
635 if (NewOps.empty())
636 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
637 else
638 Val = SCEVAddExpr::get(NewOps);
639 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
640 // Try to pull immediates out of the start value of nested addrec's.
641 SCEVHandle Start = SARE->getStart();
642 MoveLoopVariantsToImediateField(Start, Imm, L);
643
644 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
645 Ops[0] = Start;
646 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
647 } else {
648 // Otherwise, all of Val is variant, move the whole thing over.
649 Imm = SCEVAddExpr::get(Imm, Val);
650 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
651 }
652}
653
654
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000655/// MoveImmediateValues - Look at Val, and pull out any additions of constants
Nate Begemane68bcd12005-07-30 00:15:07 +0000656/// that can fit into the immediate field of instructions in the target.
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000657/// Accumulate these immediate values into the Imm value.
658static void MoveImmediateValues(SCEVHandle &Val, SCEVHandle &Imm,
659 bool isAddress, Loop *L) {
Chris Lattnerfc624702005-08-03 23:44:42 +0000660 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000661 std::vector<SCEVHandle> NewOps;
662 NewOps.reserve(SAE->getNumOperands());
663
Chris Lattner2959f002006-02-04 07:36:50 +0000664 for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
665 SCEVHandle NewOp = SAE->getOperand(i);
666 MoveImmediateValues(NewOp, Imm, isAddress, L);
667
668 if (!NewOp->isLoopInvariant(L)) {
Chris Lattneracc42c42005-08-04 19:08:16 +0000669 // If this is a loop-variant expression, it must stay in the immediate
670 // field of the expression.
Chris Lattner2959f002006-02-04 07:36:50 +0000671 Imm = SCEVAddExpr::get(Imm, NewOp);
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000672 } else {
Chris Lattner2959f002006-02-04 07:36:50 +0000673 NewOps.push_back(NewOp);
Nate Begemane68bcd12005-07-30 00:15:07 +0000674 }
Chris Lattner2959f002006-02-04 07:36:50 +0000675 }
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000676
677 if (NewOps.empty())
678 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
679 else
680 Val = SCEVAddExpr::get(NewOps);
681 return;
Chris Lattnerfc624702005-08-03 23:44:42 +0000682 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
683 // Try to pull immediates out of the start value of nested addrec's.
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000684 SCEVHandle Start = SARE->getStart();
685 MoveImmediateValues(Start, Imm, isAddress, L);
686
687 if (Start != SARE->getStart()) {
688 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
689 Ops[0] = Start;
690 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
691 }
692 return;
Chris Lattner2959f002006-02-04 07:36:50 +0000693 } else if (SCEVMulExpr *SME = dyn_cast<SCEVMulExpr>(Val)) {
694 // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
695 if (isAddress && isTargetConstant(SME->getOperand(0)) &&
696 SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
697
698 SCEVHandle SubImm = SCEVUnknown::getIntegerSCEV(0, Val->getType());
699 SCEVHandle NewOp = SME->getOperand(1);
700 MoveImmediateValues(NewOp, SubImm, isAddress, L);
701
702 // If we extracted something out of the subexpressions, see if we can
703 // simplify this!
704 if (NewOp != SME->getOperand(1)) {
705 // Scale SubImm up by "8". If the result is a target constant, we are
706 // good.
707 SubImm = SCEVMulExpr::get(SubImm, SME->getOperand(0));
708 if (isTargetConstant(SubImm)) {
709 // Accumulate the immediate.
710 Imm = SCEVAddExpr::get(Imm, SubImm);
711
712 // Update what is left of 'Val'.
713 Val = SCEVMulExpr::get(SME->getOperand(0), NewOp);
714 return;
715 }
716 }
717 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000718 }
719
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000720 // Loop-variant expressions must stay in the immediate field of the
721 // expression.
722 if ((isAddress && isTargetConstant(Val)) ||
723 !Val->isLoopInvariant(L)) {
724 Imm = SCEVAddExpr::get(Imm, Val);
725 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
726 return;
Chris Lattner0f7c0fa2005-08-04 19:26:19 +0000727 }
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000728
729 // Otherwise, no immediates to move.
Nate Begemane68bcd12005-07-30 00:15:07 +0000730}
731
Chris Lattner5949d492005-08-13 07:27:18 +0000732
733/// IncrementAddExprUses - Decompose the specified expression into its added
734/// subexpressions, and increment SubExpressionUseCounts for each of these
735/// decomposed parts.
736static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
737 SCEVHandle Expr) {
738 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
739 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
740 SeparateSubExprs(SubExprs, AE->getOperand(j));
741 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
742 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Expr->getType());
743 if (SARE->getOperand(0) == Zero) {
744 SubExprs.push_back(Expr);
745 } else {
746 // Compute the addrec with zero as its base.
747 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
748 Ops[0] = Zero; // Start with zero base.
749 SubExprs.push_back(SCEVAddRecExpr::get(Ops, SARE->getLoop()));
750
751
752 SeparateSubExprs(SubExprs, SARE->getOperand(0));
753 }
754 } else if (!isa<SCEVConstant>(Expr) ||
755 !cast<SCEVConstant>(Expr)->getValue()->isNullValue()) {
756 // Do not add zero.
757 SubExprs.push_back(Expr);
758 }
759}
760
761
Chris Lattnera091ff12005-08-09 00:18:09 +0000762/// RemoveCommonExpressionsFromUseBases - Look through all of the uses in Bases,
763/// removing any common subexpressions from it. Anything truly common is
764/// removed, accumulated, and returned. This looks for things like (a+b+c) and
765/// (a+c+d) -> (a+c). The common expression is *removed* from the Bases.
766static SCEVHandle
767RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses) {
768 unsigned NumUses = Uses.size();
769
770 // Only one use? Use its base, regardless of what it is!
771 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Uses[0].Base->getType());
772 SCEVHandle Result = Zero;
773 if (NumUses == 1) {
774 std::swap(Result, Uses[0].Base);
775 return Result;
776 }
777
778 // To find common subexpressions, count how many of Uses use each expression.
779 // If any subexpressions are used Uses.size() times, they are common.
780 std::map<SCEVHandle, unsigned> SubExpressionUseCounts;
781
Chris Lattner192cd182005-10-11 18:41:04 +0000782 // UniqueSubExprs - Keep track of all of the subexpressions we see in the
783 // order we see them.
784 std::vector<SCEVHandle> UniqueSubExprs;
785
Chris Lattner5949d492005-08-13 07:27:18 +0000786 std::vector<SCEVHandle> SubExprs;
787 for (unsigned i = 0; i != NumUses; ++i) {
788 // If the base is zero (which is common), return zero now, there are no
789 // CSEs we can find.
790 if (Uses[i].Base == Zero) return Zero;
791
792 // Split the expression into subexprs.
793 SeparateSubExprs(SubExprs, Uses[i].Base);
794 // Add one to SubExpressionUseCounts for each subexpr present.
795 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
Chris Lattner192cd182005-10-11 18:41:04 +0000796 if (++SubExpressionUseCounts[SubExprs[j]] == 1)
797 UniqueSubExprs.push_back(SubExprs[j]);
Chris Lattner5949d492005-08-13 07:27:18 +0000798 SubExprs.clear();
799 }
800
Chris Lattner192cd182005-10-11 18:41:04 +0000801 // Now that we know how many times each is used, build Result. Iterate over
802 // UniqueSubexprs so that we have a stable ordering.
803 for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
804 std::map<SCEVHandle, unsigned>::iterator I =
805 SubExpressionUseCounts.find(UniqueSubExprs[i]);
806 assert(I != SubExpressionUseCounts.end() && "Entry not found?");
Chris Lattnera091ff12005-08-09 00:18:09 +0000807 if (I->second == NumUses) { // Found CSE!
808 Result = SCEVAddExpr::get(Result, I->first);
Chris Lattnera091ff12005-08-09 00:18:09 +0000809 } else {
810 // Remove non-cse's from SubExpressionUseCounts.
Chris Lattner192cd182005-10-11 18:41:04 +0000811 SubExpressionUseCounts.erase(I);
Chris Lattnera091ff12005-08-09 00:18:09 +0000812 }
Chris Lattner192cd182005-10-11 18:41:04 +0000813 }
Chris Lattnera091ff12005-08-09 00:18:09 +0000814
815 // If we found no CSE's, return now.
816 if (Result == Zero) return Result;
817
818 // Otherwise, remove all of the CSE's we found from each of the base values.
Chris Lattner5949d492005-08-13 07:27:18 +0000819 for (unsigned i = 0; i != NumUses; ++i) {
820 // Split the expression into subexprs.
821 SeparateSubExprs(SubExprs, Uses[i].Base);
822
823 // Remove any common subexpressions.
824 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
825 if (SubExpressionUseCounts.count(SubExprs[j])) {
826 SubExprs.erase(SubExprs.begin()+j);
827 --j; --e;
828 }
829
830 // Finally, the non-shared expressions together.
831 if (SubExprs.empty())
Chris Lattnera091ff12005-08-09 00:18:09 +0000832 Uses[i].Base = Zero;
Chris Lattner5949d492005-08-13 07:27:18 +0000833 else
834 Uses[i].Base = SCEVAddExpr::get(SubExprs);
Chris Lattner47d3ec32005-08-13 07:42:01 +0000835 SubExprs.clear();
Chris Lattner5949d492005-08-13 07:27:18 +0000836 }
Chris Lattnera091ff12005-08-09 00:18:09 +0000837
838 return Result;
839}
840
841
Nate Begemane68bcd12005-07-30 00:15:07 +0000842/// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
843/// stride of IV. All of the users may have different starting values, and this
844/// may not be the only stride (we know it is if isOnlyStride is true).
Chris Lattneredff91a2005-08-10 00:45:21 +0000845void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
Chris Lattner430d0022005-08-03 22:21:05 +0000846 IVUsersOfOneStride &Uses,
847 Loop *L,
Nate Begemane68bcd12005-07-30 00:15:07 +0000848 bool isOnlyStride) {
849 // Transform our list of users and offsets to a bit more complex table. In
Chris Lattner37c24cc2005-08-08 22:56:21 +0000850 // this new vector, each 'BasedUser' contains 'Base' the base of the
851 // strided accessas well as the old information from Uses. We progressively
852 // move information from the Base field to the Imm field, until we eventually
853 // have the full access expression to rewrite the use.
854 std::vector<BasedUser> UsersToProcess;
Nate Begemane68bcd12005-07-30 00:15:07 +0000855 UsersToProcess.reserve(Uses.Users.size());
Chris Lattner37c24cc2005-08-08 22:56:21 +0000856 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
857 UsersToProcess.push_back(Uses.Users[i]);
858
859 // Move any loop invariant operands from the offset field to the immediate
860 // field of the use, so that we don't try to use something before it is
861 // computed.
862 MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
863 UsersToProcess.back().Imm, L);
864 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000865 "Base value is not loop invariant!");
Nate Begemane68bcd12005-07-30 00:15:07 +0000866 }
Chris Lattner37ed8952005-08-08 22:32:34 +0000867
Chris Lattnera091ff12005-08-09 00:18:09 +0000868 // We now have a whole bunch of uses of like-strided induction variables, but
869 // they might all have different bases. We want to emit one PHI node for this
870 // stride which we fold as many common expressions (between the IVs) into as
871 // possible. Start by identifying the common expressions in the base values
872 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
873 // "A+B"), emit it to the preheader, then remove the expression from the
874 // UsersToProcess base values.
875 SCEVHandle CommonExprs = RemoveCommonExpressionsFromUseBases(UsersToProcess);
876
Chris Lattner37ed8952005-08-08 22:32:34 +0000877 // Next, figure out what we can represent in the immediate fields of
878 // instructions. If we can represent anything there, move it to the imm
Chris Lattnera091ff12005-08-09 00:18:09 +0000879 // fields of the BasedUsers. We do this so that it increases the commonality
880 // of the remaining uses.
Chris Lattner37ed8952005-08-08 22:32:34 +0000881 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
Chris Lattner5cf983e2005-08-16 00:38:11 +0000882 // If the user is not in the current loop, this means it is using the exit
883 // value of the IV. Do not put anything in the base, make sure it's all in
884 // the immediate field to allow as much factoring as possible.
885 if (!L->contains(UsersToProcess[i].Inst->getParent())) {
Chris Lattnerea7dfd52005-08-17 21:22:41 +0000886 UsersToProcess[i].Imm = SCEVAddExpr::get(UsersToProcess[i].Imm,
887 UsersToProcess[i].Base);
888 UsersToProcess[i].Base =
889 SCEVUnknown::getIntegerSCEV(0, UsersToProcess[i].Base->getType());
Chris Lattner5cf983e2005-08-16 00:38:11 +0000890 } else {
891
892 // Addressing modes can be folded into loads and stores. Be careful that
893 // the store is through the expression, not of the expression though.
894 bool isAddress = isa<LoadInst>(UsersToProcess[i].Inst);
895 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
896 if (SI->getOperand(1) == UsersToProcess[i].OperandValToReplace)
897 isAddress = true;
898
899 MoveImmediateValues(UsersToProcess[i].Base, UsersToProcess[i].Imm,
900 isAddress, L);
901 }
Chris Lattner37ed8952005-08-08 22:32:34 +0000902 }
903
Chris Lattnera091ff12005-08-09 00:18:09 +0000904 // Now that we know what we need to do, insert the PHI node itself.
905 //
906 DEBUG(std::cerr << "INSERTING IV of STRIDE " << *Stride << " and BASE "
907 << *CommonExprs << " :\n");
908
909 SCEVExpander Rewriter(*SE, *LI);
910 SCEVExpander PreheaderRewriter(*SE, *LI);
Chris Lattner37ed8952005-08-08 22:32:34 +0000911
Chris Lattnera091ff12005-08-09 00:18:09 +0000912 BasicBlock *Preheader = L->getLoopPreheader();
913 Instruction *PreInsertPt = Preheader->getTerminator();
914 Instruction *PhiInsertBefore = L->getHeader()->begin();
Chris Lattner37ed8952005-08-08 22:32:34 +0000915
Chris Lattner8048b852005-09-12 17:11:27 +0000916 BasicBlock *LatchBlock = L->getLoopLatch();
Chris Lattnerbb78c972005-08-03 23:30:08 +0000917
Chris Lattnera091ff12005-08-09 00:18:09 +0000918 // Create a new Phi for this base, and stick it in the loop header.
919 const Type *ReplacedTy = CommonExprs->getType();
920 PHINode *NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
921 ++NumInserted;
922
Chris Lattneredff91a2005-08-10 00:45:21 +0000923 // Insert the stride into the preheader.
924 Value *StrideV = PreheaderRewriter.expandCodeFor(Stride, PreInsertPt,
925 ReplacedTy);
926 if (!isa<ConstantInt>(StrideV)) ++NumVariable;
927
928
Chris Lattnera091ff12005-08-09 00:18:09 +0000929 // Emit the initial base value into the loop preheader, and add it to the
930 // Phi node.
931 Value *PHIBaseV = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt,
932 ReplacedTy);
933 NewPHI->addIncoming(PHIBaseV, Preheader);
934
935 // Emit the increment of the base value before the terminator of the loop
936 // latch block, and add it to the Phi node.
937 SCEVHandle IncExp = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
Chris Lattneredff91a2005-08-10 00:45:21 +0000938 SCEVUnknown::get(StrideV));
Chris Lattnera091ff12005-08-09 00:18:09 +0000939
940 Value *IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator(),
941 ReplacedTy);
942 IncV->setName(NewPHI->getName()+".inc");
943 NewPHI->addIncoming(IncV, LatchBlock);
944
Chris Lattnerdb23c742005-08-03 22:51:21 +0000945 // Sort by the base value, so that all IVs with identical bases are next to
Chris Lattnera091ff12005-08-09 00:18:09 +0000946 // each other.
Nate Begemane68bcd12005-07-30 00:15:07 +0000947 while (!UsersToProcess.empty()) {
Chris Lattner5c9d63d2005-10-11 18:30:57 +0000948 SCEVHandle Base = UsersToProcess.back().Base;
Chris Lattnerbb78c972005-08-03 23:30:08 +0000949
Chris Lattnera091ff12005-08-09 00:18:09 +0000950 DEBUG(std::cerr << " INSERTING code for BASE = " << *Base << ":\n");
Chris Lattnerbb78c972005-08-03 23:30:08 +0000951
Chris Lattnera091ff12005-08-09 00:18:09 +0000952 // Emit the code for Base into the preheader.
Chris Lattnerc70bbc02005-08-08 05:47:49 +0000953 Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt,
954 ReplacedTy);
Chris Lattnera091ff12005-08-09 00:18:09 +0000955
956 // If BaseV is a constant other than 0, make sure that it gets inserted into
957 // the preheader, instead of being forward substituted into the uses. We do
958 // this by forcing a noop cast to be inserted into the preheader in this
959 // case.
960 if (Constant *C = dyn_cast<Constant>(BaseV))
Chris Lattner530fe6a2005-09-10 01:18:45 +0000961 if (!C->isNullValue() && !isTargetConstant(Base)) {
Chris Lattnera091ff12005-08-09 00:18:09 +0000962 // We want this constant emitted into the preheader!
963 BaseV = new CastInst(BaseV, BaseV->getType(), "preheaderinsert",
964 PreInsertPt);
965 }
966
Nate Begemane68bcd12005-07-30 00:15:07 +0000967 // Emit the code to add the immediate offset to the Phi value, just before
Chris Lattnerdb23c742005-08-03 22:51:21 +0000968 // the instructions that we identified as using this stride and base.
Chris Lattner5c9d63d2005-10-11 18:30:57 +0000969 unsigned ScanPos = 0;
970 do {
971 BasedUser &User = UsersToProcess.back();
Jeff Cohen546fd592005-07-30 18:33:25 +0000972
Chris Lattnera091ff12005-08-09 00:18:09 +0000973 // If this instruction wants to use the post-incremented value, move it
974 // after the post-inc and use its value instead of the PHI.
975 Value *RewriteOp = NewPHI;
976 if (User.isUseOfPostIncrementedValue) {
977 RewriteOp = IncV;
Chris Lattnera6764832005-09-12 06:04:47 +0000978
979 // If this user is in the loop, make sure it is the last thing in the
980 // loop to ensure it is dominated by the increment.
981 if (L->contains(User.Inst->getParent()))
982 User.Inst->moveBefore(LatchBlock->getTerminator());
Chris Lattnera091ff12005-08-09 00:18:09 +0000983 }
984 SCEVHandle RewriteExpr = SCEVUnknown::get(RewriteOp);
985
Chris Lattnerdb23c742005-08-03 22:51:21 +0000986 // Clear the SCEVExpander's expression map so that we are guaranteed
987 // to have the code emitted where we expect it.
988 Rewriter.clear();
Chris Lattnera091ff12005-08-09 00:18:09 +0000989
Chris Lattnera6d7c352005-08-04 20:03:32 +0000990 // Now that we know what we need to do, insert code before User for the
991 // immediate and any loop-variant expressions.
Chris Lattnera091ff12005-08-09 00:18:09 +0000992 if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isNullValue())
993 // Add BaseV to the PHI value if needed.
994 RewriteExpr = SCEVAddExpr::get(RewriteExpr, SCEVUnknown::get(BaseV));
995
Chris Lattner8447b492005-08-12 22:22:17 +0000996 User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter, L, this);
Jeff Cohen546fd592005-07-30 18:33:25 +0000997
Chris Lattnerdb23c742005-08-03 22:51:21 +0000998 // Mark old value we replaced as possibly dead, so that it is elminated
999 // if we just replaced the last use of that value.
Chris Lattnera6d7c352005-08-04 20:03:32 +00001000 DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
Nate Begemane68bcd12005-07-30 00:15:07 +00001001
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001002 UsersToProcess.pop_back();
Chris Lattnerdb23c742005-08-03 22:51:21 +00001003 ++NumReduced;
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001004
1005 // If there are any more users to process with the same base, move one of
1006 // them to the end of the list so that we will process it.
1007 if (!UsersToProcess.empty()) {
1008 for (unsigned e = UsersToProcess.size(); ScanPos != e; ++ScanPos)
1009 if (UsersToProcess[ScanPos].Base == Base) {
1010 std::swap(UsersToProcess[ScanPos], UsersToProcess.back());
1011 break;
1012 }
1013 }
1014 } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
Nate Begemane68bcd12005-07-30 00:15:07 +00001015 // TODO: Next, find out which base index is the most common, pull it out.
1016 }
1017
1018 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1019 // different starting values, into different PHIs.
Nate Begemane68bcd12005-07-30 00:15:07 +00001020}
1021
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001022// OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
1023// uses in the loop, look to see if we can eliminate some, in favor of using
1024// common indvars for the different uses.
1025void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
1026 // TODO: implement optzns here.
1027
1028
1029
1030
1031 // Finally, get the terminating condition for the loop if possible. If we
1032 // can, we want to change it to use a post-incremented version of its
1033 // induction variable, to allow coallescing the live ranges for the IV into
1034 // one register value.
1035 PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
1036 BasicBlock *Preheader = L->getLoopPreheader();
1037 BasicBlock *LatchBlock =
1038 SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
1039 BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
1040 if (!TermBr || TermBr->isUnconditional() ||
1041 !isa<SetCondInst>(TermBr->getCondition()))
1042 return;
1043 SetCondInst *Cond = cast<SetCondInst>(TermBr->getCondition());
1044
1045 // Search IVUsesByStride to find Cond's IVUse if there is one.
1046 IVStrideUse *CondUse = 0;
Chris Lattneredff91a2005-08-10 00:45:21 +00001047 const SCEVHandle *CondStride = 0;
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001048
Chris Lattnerb7a38942005-10-11 18:17:57 +00001049 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e && !CondUse;
1050 ++Stride) {
1051 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1052 IVUsesByStride.find(StrideOrder[Stride]);
1053 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1054
1055 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
1056 E = SI->second.Users.end(); UI != E; ++UI)
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001057 if (UI->User == Cond) {
1058 CondUse = &*UI;
Chris Lattnerb7a38942005-10-11 18:17:57 +00001059 CondStride = &SI->first;
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001060 // NOTE: we could handle setcc instructions with multiple uses here, but
1061 // InstCombine does it as well for simple uses, it's not clear that it
1062 // occurs enough in real life to handle.
1063 break;
1064 }
Chris Lattnerb7a38942005-10-11 18:17:57 +00001065 }
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001066 if (!CondUse) return; // setcc doesn't use the IV.
1067
1068 // setcc stride is complex, don't mess with users.
Chris Lattneredff91a2005-08-10 00:45:21 +00001069 // FIXME: Evaluate whether this is a good idea or not.
1070 if (!isa<SCEVConstant>(*CondStride)) return;
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001071
1072 // It's possible for the setcc instruction to be anywhere in the loop, and
1073 // possible for it to have multiple users. If it is not immediately before
1074 // the latch block branch, move it.
1075 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
1076 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
1077 Cond->moveBefore(TermBr);
1078 } else {
1079 // Otherwise, clone the terminating condition and insert into the loopend.
1080 Cond = cast<SetCondInst>(Cond->clone());
1081 Cond->setName(L->getHeader()->getName() + ".termcond");
1082 LatchBlock->getInstList().insert(TermBr, Cond);
1083
1084 // Clone the IVUse, as the old use still exists!
Chris Lattneredff91a2005-08-10 00:45:21 +00001085 IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001086 CondUse->OperandValToReplace);
Chris Lattneredff91a2005-08-10 00:45:21 +00001087 CondUse = &IVUsesByStride[*CondStride].Users.back();
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001088 }
1089 }
1090
1091 // If we get to here, we know that we can transform the setcc instruction to
1092 // use the post-incremented version of the IV, allowing us to coallesce the
1093 // live ranges for the IV correctly.
Chris Lattneredff91a2005-08-10 00:45:21 +00001094 CondUse->Offset = SCEV::getMinusSCEV(CondUse->Offset, *CondStride);
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001095 CondUse->isUseOfPostIncrementedValue = true;
1096}
Nate Begemane68bcd12005-07-30 00:15:07 +00001097
Nate Begemanb18121e2004-10-18 21:08:22 +00001098void LoopStrengthReduce::runOnLoop(Loop *L) {
1099 // First step, transform all loops nesting inside of this loop.
1100 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
1101 runOnLoop(*I);
1102
Nate Begemane68bcd12005-07-30 00:15:07 +00001103 // Next, find all uses of induction variables in this loop, and catagorize
1104 // them by stride. Start by finding all of the PHI nodes in the header for
1105 // this loop. If they are induction variables, inspect their uses.
Chris Lattnereaf24722005-08-04 17:40:30 +00001106 std::set<Instruction*> Processed; // Don't reprocess instructions.
Nate Begemane68bcd12005-07-30 00:15:07 +00001107 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
Chris Lattnereaf24722005-08-04 17:40:30 +00001108 AddUsersIfInteresting(I, L, Processed);
Nate Begemanb18121e2004-10-18 21:08:22 +00001109
Nate Begemane68bcd12005-07-30 00:15:07 +00001110 // If we have nothing to do, return.
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001111 if (IVUsesByStride.empty()) return;
1112
1113 // Optimize induction variables. Some indvar uses can be transformed to use
1114 // strides that will be needed for other purposes. A common example of this
1115 // is the exit test for the loop, which can often be rewritten to use the
1116 // computation of some other indvar to decide when to terminate the loop.
1117 OptimizeIndvars(L);
1118
Misha Brukmanb1c93172005-04-21 23:48:37 +00001119
Nate Begemane68bcd12005-07-30 00:15:07 +00001120 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
1121 // doing computation in byte values, promote to 32-bit values if safe.
1122
1123 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
1124 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
1125 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
1126 // to be careful that IV's are all the same type. Only works for intptr_t
1127 // indvars.
1128
1129 // If we only have one stride, we can more aggressively eliminate some things.
1130 bool HasOneStride = IVUsesByStride.size() == 1;
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001131
Chris Lattnera091ff12005-08-09 00:18:09 +00001132 // Note: this processes each stride/type pair individually. All users passed
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001133 // into StrengthReduceStridedIVUsers have the same type AND stride. Also,
1134 // node that we iterate over IVUsesByStride indirectly by using StrideOrder.
1135 // This extra layer of indirection makes the ordering of strides deterministic
1136 // - not dependent on map order.
1137 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
1138 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1139 IVUsesByStride.find(StrideOrder[Stride]);
1140 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
Nate Begemane68bcd12005-07-30 00:15:07 +00001141 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001142 }
Nate Begemanb18121e2004-10-18 21:08:22 +00001143
1144 // Clean up after ourselves
1145 if (!DeadInsts.empty()) {
1146 DeleteTriviallyDeadInstructions(DeadInsts);
1147
Nate Begemane68bcd12005-07-30 00:15:07 +00001148 BasicBlock::iterator I = L->getHeader()->begin();
1149 PHINode *PN;
Chris Lattnerdcce49e2005-08-02 02:44:31 +00001150 while ((PN = dyn_cast<PHINode>(I))) {
Chris Lattner564900e2005-08-02 00:41:11 +00001151 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
1152
Chris Lattnerc6c4d992005-08-09 23:39:36 +00001153 // At this point, we know that we have killed one or more GEP
1154 // instructions. It is worth checking to see if the cann indvar is also
1155 // dead, so that we can remove it as well. The requirements for the cann
1156 // indvar to be considered dead are:
Nate Begemane68bcd12005-07-30 00:15:07 +00001157 // 1. the cann indvar has one use
1158 // 2. the use is an add instruction
1159 // 3. the add has one use
1160 // 4. the add is used by the cann indvar
1161 // If all four cases above are true, then we can remove both the add and
1162 // the cann indvar.
1163 // FIXME: this needs to eliminate an induction variable even if it's being
1164 // compared against some value to decide loop termination.
1165 if (PN->hasOneUse()) {
1166 BinaryOperator *BO = dyn_cast<BinaryOperator>(*(PN->use_begin()));
Chris Lattner75a44e12005-08-02 02:52:02 +00001167 if (BO && BO->hasOneUse()) {
1168 if (PN == *(BO->use_begin())) {
1169 DeadInsts.insert(BO);
1170 // Break the cycle, then delete the PHI.
1171 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattner84e9baa2005-08-03 21:36:09 +00001172 SE->deleteInstructionFromRecords(PN);
Chris Lattner75a44e12005-08-02 02:52:02 +00001173 PN->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +00001174 }
Chris Lattner75a44e12005-08-02 02:52:02 +00001175 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001176 }
Nate Begemanb18121e2004-10-18 21:08:22 +00001177 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001178 DeleteTriviallyDeadInstructions(DeadInsts);
Nate Begemanb18121e2004-10-18 21:08:22 +00001179 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001180
Chris Lattner11e7a5e2005-08-05 01:30:11 +00001181 CastedPointers.clear();
Nate Begemane68bcd12005-07-30 00:15:07 +00001182 IVUsesByStride.clear();
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001183 StrideOrder.clear();
Nate Begemane68bcd12005-07-30 00:15:07 +00001184 return;
Nate Begemanb18121e2004-10-18 21:08:22 +00001185}