blob: a542ca02a2187cb2fea496987c160d0a7b25f2e4 [file] [log] [blame]
Dan Gohman2d1be872009-04-16 03:18:22 +00001//===- LoopStrengthReduce.cpp - Strength Reduce IVs in Loops --------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Nate Begemaneaa13852004-10-18 21:08:22 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
Nate Begemaneaa13852004-10-18 21:08:22 +00008//===----------------------------------------------------------------------===//
9//
10// This pass performs a strength reduction on array references inside loops that
Dan Gohman2d1be872009-04-16 03:18:22 +000011// have as one or more of their components the loop induction variable.
Nate Begemaneaa13852004-10-18 21:08:22 +000012//
Nate Begemaneaa13852004-10-18 21:08:22 +000013//===----------------------------------------------------------------------===//
14
Chris Lattnerbe3e5212005-08-03 23:30:08 +000015#define DEBUG_TYPE "loop-reduce"
Nate Begemaneaa13852004-10-18 21:08:22 +000016#include "llvm/Transforms/Scalar.h"
17#include "llvm/Constants.h"
18#include "llvm/Instructions.h"
Dan Gohmane5b01be2007-05-04 14:59:09 +000019#include "llvm/IntrinsicInst.h"
Nate Begemaneaa13852004-10-18 21:08:22 +000020#include "llvm/Type.h"
Jeff Cohen2f3c9b72005-03-04 04:04:26 +000021#include "llvm/DerivedTypes.h"
Nate Begemaneaa13852004-10-18 21:08:22 +000022#include "llvm/Analysis/Dominators.h"
23#include "llvm/Analysis/LoopInfo.h"
Devang Patel0f54dcb2007-03-06 21:14:09 +000024#include "llvm/Analysis/LoopPass.h"
Nate Begeman16997482005-07-30 00:15:07 +000025#include "llvm/Analysis/ScalarEvolutionExpander.h"
Evan Chengd9fb7122009-02-21 02:06:47 +000026#include "llvm/Transforms/Utils/AddrModeMatcher.h"
Chris Lattnere0391be2005-08-12 22:06:11 +000027#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Nate Begemaneaa13852004-10-18 21:08:22 +000028#include "llvm/Transforms/Utils/Local.h"
Jeff Cohen2f3c9b72005-03-04 04:04:26 +000029#include "llvm/Target/TargetData.h"
Evan Cheng168a66b2007-10-26 23:08:19 +000030#include "llvm/ADT/SmallPtrSet.h"
Nate Begemaneaa13852004-10-18 21:08:22 +000031#include "llvm/ADT/Statistic.h"
Evan Chengd9fb7122009-02-21 02:06:47 +000032#include "llvm/Support/CFG.h"
Nate Begeman16997482005-07-30 00:15:07 +000033#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000034#include "llvm/Support/Compiler.h"
Dan Gohmanc17e0cf2009-02-20 04:17:46 +000035#include "llvm/Support/CommandLine.h"
Evan Chengd9fb7122009-02-21 02:06:47 +000036#include "llvm/Support/GetElementPtrTypeIterator.h"
Evan Chengd277f2c2006-03-13 23:14:23 +000037#include "llvm/Target/TargetLowering.h"
Jeff Cohencfb1d422005-07-30 18:22:27 +000038#include <algorithm>
Nate Begemaneaa13852004-10-18 21:08:22 +000039using namespace llvm;
40
Evan Chengcdf43b12007-10-25 09:11:16 +000041STATISTIC(NumReduced , "Number of GEPs strength reduced");
42STATISTIC(NumInserted, "Number of PHIs inserted");
43STATISTIC(NumVariable, "Number of PHIs with variable strides");
Devang Patel54153272008-08-27 17:50:18 +000044STATISTIC(NumEliminated, "Number of strides eliminated");
45STATISTIC(NumShadow, "Number of Shadow IVs optimized");
Evan Chengd9fb7122009-02-21 02:06:47 +000046STATISTIC(NumImmSunk, "Number of common expr immediates sunk into uses");
Nate Begemaneaa13852004-10-18 21:08:22 +000047
Dan Gohmanc17e0cf2009-02-20 04:17:46 +000048static cl::opt<bool> EnableFullLSRMode("enable-full-lsr",
49 cl::init(false),
50 cl::Hidden);
51
Chris Lattner0e5f4992006-12-19 21:40:18 +000052namespace {
Dale Johannesendc42f482007-03-20 00:47:50 +000053
Jeff Cohenc01a5302007-03-20 20:43:18 +000054 struct BasedUser;
Dale Johannesendc42f482007-03-20 00:47:50 +000055
Chris Lattnerec3fb632005-08-03 22:21:05 +000056 /// IVStrideUse - Keep track of one use of a strided induction variable, where
57 /// the stride is stored externally. The Offset member keeps track of the
Dan Gohman9330c3a2007-10-29 19:32:39 +000058 /// offset from the IV, User is the actual user of the operand, and
59 /// 'OperandValToReplace' is the operand of the User that is the use.
Reid Spencer9133fe22007-02-05 23:32:05 +000060 struct VISIBILITY_HIDDEN IVStrideUse {
Chris Lattnerec3fb632005-08-03 22:21:05 +000061 SCEVHandle Offset;
62 Instruction *User;
63 Value *OperandValToReplace;
Chris Lattner010de252005-08-08 05:28:22 +000064
65 // isUseOfPostIncrementedValue - True if this should use the
66 // post-incremented version of this IV, not the preincremented version.
67 // This can only be set in special cases, such as the terminating setcc
Chris Lattnerc6bae652005-09-12 06:04:47 +000068 // instruction for a loop or uses dominated by the loop.
Chris Lattner010de252005-08-08 05:28:22 +000069 bool isUseOfPostIncrementedValue;
Chris Lattnerec3fb632005-08-03 22:21:05 +000070
71 IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
Chris Lattner010de252005-08-08 05:28:22 +000072 : Offset(Offs), User(U), OperandValToReplace(O),
73 isUseOfPostIncrementedValue(false) {}
Chris Lattnerec3fb632005-08-03 22:21:05 +000074 };
75
76 /// IVUsersOfOneStride - This structure keeps track of all instructions that
77 /// have an operand that is based on the trip count multiplied by some stride.
78 /// The stride for all of these users is common and kept external to this
79 /// structure.
Reid Spencer9133fe22007-02-05 23:32:05 +000080 struct VISIBILITY_HIDDEN IVUsersOfOneStride {
Nate Begeman16997482005-07-30 00:15:07 +000081 /// Users - Keep track of all of the users of this stride as well as the
Chris Lattnerec3fb632005-08-03 22:21:05 +000082 /// initial value and the operand that uses the IV.
83 std::vector<IVStrideUse> Users;
84
85 void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
86 Users.push_back(IVStrideUse(Offset, User, Operand));
Nate Begeman16997482005-07-30 00:15:07 +000087 }
88 };
89
Evan Chengd1d6b5c2006-03-16 21:53:05 +000090 /// IVInfo - This structure keeps track of one IV expression inserted during
Evan Cheng21495772006-03-18 08:03:12 +000091 /// StrengthReduceStridedIVUsers. It contains the stride, the common base, as
92 /// well as the PHI node and increment value created for rewrite.
Reid Spencer9133fe22007-02-05 23:32:05 +000093 struct VISIBILITY_HIDDEN IVExpr {
Evan Cheng21495772006-03-18 08:03:12 +000094 SCEVHandle Stride;
Evan Chengd1d6b5c2006-03-16 21:53:05 +000095 SCEVHandle Base;
96 PHINode *PHI;
Evan Chengd1d6b5c2006-03-16 21:53:05 +000097
Dan Gohman9d100862009-03-09 22:04:01 +000098 IVExpr(const SCEVHandle &stride, const SCEVHandle &base, PHINode *phi)
99 : Stride(stride), Base(base), PHI(phi) {}
Evan Chengd1d6b5c2006-03-16 21:53:05 +0000100 };
101
102 /// IVsOfOneStride - This structure keeps track of all IV expression inserted
103 /// during StrengthReduceStridedIVUsers for a particular stride of the IV.
Reid Spencer9133fe22007-02-05 23:32:05 +0000104 struct VISIBILITY_HIDDEN IVsOfOneStride {
Evan Chengd1d6b5c2006-03-16 21:53:05 +0000105 std::vector<IVExpr> IVs;
106
Dan Gohman9d100862009-03-09 22:04:01 +0000107 void addIV(const SCEVHandle &Stride, const SCEVHandle &Base, PHINode *PHI) {
108 IVs.push_back(IVExpr(Stride, Base, PHI));
Evan Chengd1d6b5c2006-03-16 21:53:05 +0000109 }
110 };
Nate Begeman16997482005-07-30 00:15:07 +0000111
Devang Patel0f54dcb2007-03-06 21:14:09 +0000112 class VISIBILITY_HIDDEN LoopStrengthReduce : public LoopPass {
Nate Begemaneaa13852004-10-18 21:08:22 +0000113 LoopInfo *LI;
Devang Patelb7d9dfc2007-06-07 21:42:15 +0000114 DominatorTree *DT;
Nate Begeman16997482005-07-30 00:15:07 +0000115 ScalarEvolution *SE;
116 const TargetData *TD;
117 const Type *UIntPtrTy;
Nate Begemaneaa13852004-10-18 21:08:22 +0000118 bool Changed;
Chris Lattner7e608bb2005-08-02 02:52:02 +0000119
Nate Begeman16997482005-07-30 00:15:07 +0000120 /// IVUsesByStride - Keep track of all uses of induction variables that we
121 /// are interested in. The key of the map is the stride of the access.
Chris Lattner50fad702005-08-10 00:45:21 +0000122 std::map<SCEVHandle, IVUsersOfOneStride> IVUsesByStride;
Nate Begeman16997482005-07-30 00:15:07 +0000123
Evan Chengd1d6b5c2006-03-16 21:53:05 +0000124 /// IVsByStride - Keep track of all IVs that have been inserted for a
125 /// particular stride.
126 std::map<SCEVHandle, IVsOfOneStride> IVsByStride;
127
Chris Lattner7305ae22005-10-09 06:20:55 +0000128 /// StrideOrder - An ordering of the keys in IVUsesByStride that is stable:
129 /// We use this to iterate over the IVUsesByStride collection without being
130 /// dependent on random ordering of pointers in the process.
Evan Cheng83927722007-10-30 22:27:26 +0000131 SmallVector<SCEVHandle, 16> StrideOrder;
Chris Lattner7305ae22005-10-09 06:20:55 +0000132
Nate Begeman16997482005-07-30 00:15:07 +0000133 /// DeadInsts - Keep track of instructions we may have made dead, so that
134 /// we can remove them after we are done working.
Chris Lattner09fb7da2008-12-01 06:27:41 +0000135 SmallVector<Instruction*, 16> DeadInsts;
Evan Chengd277f2c2006-03-13 23:14:23 +0000136
137 /// TLI - Keep a pointer of a TargetLowering to consult for determining
138 /// transformation profitability.
139 const TargetLowering *TLI;
140
Nate Begemaneaa13852004-10-18 21:08:22 +0000141 public:
Devang Patel19974732007-05-03 01:11:54 +0000142 static char ID; // Pass ID, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +0000143 explicit LoopStrengthReduce(const TargetLowering *tli = NULL) :
Dan Gohmanae73dc12008-09-04 17:05:41 +0000144 LoopPass(&ID), TLI(tli) {
Jeff Cohen2f3c9b72005-03-04 04:04:26 +0000145 }
146
Devang Patel0f54dcb2007-03-06 21:14:09 +0000147 bool runOnLoop(Loop *L, LPPassManager &LPM);
Nate Begemaneaa13852004-10-18 21:08:22 +0000148
149 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattneraa96ae72005-08-17 06:35:16 +0000150 // We split critical edges, so we change the CFG. However, we do update
151 // many analyses if they are around.
152 AU.addPreservedID(LoopSimplifyID);
153 AU.addPreserved<LoopInfo>();
Chris Lattneraa96ae72005-08-17 06:35:16 +0000154 AU.addPreserved<DominanceFrontier>();
155 AU.addPreserved<DominatorTree>();
156
Jeff Cohenf465db62005-02-27 19:37:07 +0000157 AU.addRequiredID(LoopSimplifyID);
Nate Begemaneaa13852004-10-18 21:08:22 +0000158 AU.addRequired<LoopInfo>();
Devang Patelb7d9dfc2007-06-07 21:42:15 +0000159 AU.addRequired<DominatorTree>();
Jeff Cohen2f3c9b72005-03-04 04:04:26 +0000160 AU.addRequired<TargetData>();
Nate Begeman16997482005-07-30 00:15:07 +0000161 AU.addRequired<ScalarEvolution>();
Devang Patela0b39092008-08-26 17:57:54 +0000162 AU.addPreserved<ScalarEvolution>();
Nate Begemaneaa13852004-10-18 21:08:22 +0000163 }
Dan Gohman2d1be872009-04-16 03:18:22 +0000164
Chris Lattner49f72e62005-08-04 01:19:13 +0000165private:
Chris Lattner3416e5f2005-08-04 17:40:30 +0000166 bool AddUsersIfInteresting(Instruction *I, Loop *L,
Evan Cheng168a66b2007-10-26 23:08:19 +0000167 SmallPtrSet<Instruction*,16> &Processed);
Evan Chengcdf43b12007-10-25 09:11:16 +0000168 ICmpInst *ChangeCompareStride(Loop *L, ICmpInst *Cond,
169 IVStrideUse* &CondUse,
170 const SCEVHandle* &CondStride);
Chris Lattner010de252005-08-08 05:28:22 +0000171 void OptimizeIndvars(Loop *L);
Devang Patela0b39092008-08-26 17:57:54 +0000172
173 /// OptimizeShadowIV - If IV is used in a int-to-float cast
174 /// inside the loop then try to eliminate the cast opeation.
175 void OptimizeShadowIV(Loop *L);
176
Dan Gohmanad7321f2008-09-15 21:22:06 +0000177 /// OptimizeSMax - Rewrite the loop's terminating condition
178 /// if it uses an smax computation.
179 ICmpInst *OptimizeSMax(Loop *L, ICmpInst *Cond,
180 IVStrideUse* &CondUse);
181
Devang Patelc677de22008-08-13 20:31:11 +0000182 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse,
Devang Patela0b39092008-08-26 17:57:54 +0000183 const SCEVHandle *&CondStride);
Evan Cheng5f8ebaa2007-10-25 22:45:20 +0000184 bool RequiresTypeConversion(const Type *Ty, const Type *NewTy);
Dale Johannesen2f46bb82009-01-14 02:35:31 +0000185 SCEVHandle CheckForIVReuse(bool, bool, bool, const SCEVHandle&,
Dan Gohman02e4fa72007-10-22 20:40:42 +0000186 IVExpr&, const Type*,
Dale Johannesendc42f482007-03-20 00:47:50 +0000187 const std::vector<BasedUser>& UsersToProcess);
Dan Gohman02e4fa72007-10-22 20:40:42 +0000188 bool ValidStride(bool, int64_t,
189 const std::vector<BasedUser>& UsersToProcess);
Evan Cheng5f8ebaa2007-10-25 22:45:20 +0000190 SCEVHandle CollectIVUsers(const SCEVHandle &Stride,
191 IVUsersOfOneStride &Uses,
192 Loop *L,
193 bool &AllUsesAreAddresses,
Dale Johannesenb0390622008-12-16 22:16:28 +0000194 bool &AllUsesAreOutsideLoop,
Evan Cheng5f8ebaa2007-10-25 22:45:20 +0000195 std::vector<BasedUser> &UsersToProcess);
Dan Gohmanc17e0cf2009-02-20 04:17:46 +0000196 bool ShouldUseFullStrengthReductionMode(
197 const std::vector<BasedUser> &UsersToProcess,
198 const Loop *L,
199 bool AllUsesAreAddresses,
200 SCEVHandle Stride);
201 void PrepareToStrengthReduceFully(
202 std::vector<BasedUser> &UsersToProcess,
203 SCEVHandle Stride,
204 SCEVHandle CommonExprs,
205 const Loop *L,
206 SCEVExpander &PreheaderRewriter);
207 void PrepareToStrengthReduceFromSmallerStride(
208 std::vector<BasedUser> &UsersToProcess,
209 Value *CommonBaseV,
210 const IVExpr &ReuseIV,
211 Instruction *PreInsertPt);
212 void PrepareToStrengthReduceWithNewPhi(
213 std::vector<BasedUser> &UsersToProcess,
214 SCEVHandle Stride,
215 SCEVHandle CommonExprs,
216 Value *CommonBaseV,
217 const Loop *L,
218 SCEVExpander &PreheaderRewriter);
Chris Lattner50fad702005-08-10 00:45:21 +0000219 void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
220 IVUsersOfOneStride &Uses,
Dan Gohman9f4ac312009-03-09 20:41:15 +0000221 Loop *L);
Chris Lattnera68d4ca2008-12-01 06:14:28 +0000222 void DeleteTriviallyDeadInstructions();
Nate Begemaneaa13852004-10-18 21:08:22 +0000223 };
Nate Begemaneaa13852004-10-18 21:08:22 +0000224}
225
Dan Gohman844731a2008-05-13 00:00:25 +0000226char LoopStrengthReduce::ID = 0;
227static RegisterPass<LoopStrengthReduce>
228X("loop-reduce", "Loop Strength Reduction");
229
Daniel Dunbar394f0442008-10-22 23:32:42 +0000230Pass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
Evan Chengd1d6b5c2006-03-16 21:53:05 +0000231 return new LoopStrengthReduce(TLI);
Nate Begemaneaa13852004-10-18 21:08:22 +0000232}
233
234/// DeleteTriviallyDeadInstructions - If any of the instructions is the
235/// specified set are trivially dead, delete them and see if this makes any of
236/// their operands subsequently dead.
Chris Lattnera68d4ca2008-12-01 06:14:28 +0000237void LoopStrengthReduce::DeleteTriviallyDeadInstructions() {
Chris Lattner09fb7da2008-12-01 06:27:41 +0000238 if (DeadInsts.empty()) return;
239
240 // Sort the deadinsts list so that we can trivially eliminate duplicates as we
241 // go. The code below never adds a non-dead instruction to the worklist, but
242 // callers may not be so careful.
Chris Lattner99d00152008-12-01 06:49:59 +0000243 array_pod_sort(DeadInsts.begin(), DeadInsts.end());
Chris Lattner09fb7da2008-12-01 06:27:41 +0000244
245 // Drop duplicate instructions and those with uses.
246 for (unsigned i = 0, e = DeadInsts.size()-1; i < e; ++i) {
247 Instruction *I = DeadInsts[i];
248 if (!I->use_empty()) DeadInsts[i] = 0;
Chris Lattner46a879e2008-12-09 04:47:21 +0000249 while (i != e && DeadInsts[i+1] == I)
Chris Lattner09fb7da2008-12-01 06:27:41 +0000250 DeadInsts[++i] = 0;
251 }
252
Chris Lattnera68d4ca2008-12-01 06:14:28 +0000253 while (!DeadInsts.empty()) {
254 Instruction *I = DeadInsts.back();
255 DeadInsts.pop_back();
Chris Lattner09fb7da2008-12-01 06:27:41 +0000256
257 if (I == 0 || !isInstructionTriviallyDead(I))
Chris Lattnerbfcee362008-12-01 06:11:32 +0000258 continue;
259
260 SE->deleteValueFromRecords(I);
261
Chris Lattner09fb7da2008-12-01 06:27:41 +0000262 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI) {
263 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
264 *OI = 0;
Chris Lattnerbfcee362008-12-01 06:11:32 +0000265 if (U->use_empty())
Chris Lattner09fb7da2008-12-01 06:27:41 +0000266 DeadInsts.push_back(U);
Bill Wendling411052b2008-11-29 03:43:04 +0000267 }
268 }
Chris Lattnerbfcee362008-12-01 06:11:32 +0000269
270 I->eraseFromParent();
271 Changed = true;
Nate Begemaneaa13852004-10-18 21:08:22 +0000272 }
273}
274
Dale Johannesen2f46bb82009-01-14 02:35:31 +0000275/// containsAddRecFromDifferentLoop - Determine whether expression S involves a
276/// subexpression that is an AddRec from a loop other than L. An outer loop
277/// of L is OK, but not an inner loop nor a disjoint loop.
278static bool containsAddRecFromDifferentLoop(SCEVHandle S, Loop *L) {
279 // This is very common, put it first.
280 if (isa<SCEVConstant>(S))
281 return false;
282 if (SCEVCommutativeExpr *AE = dyn_cast<SCEVCommutativeExpr>(S)) {
283 for (unsigned int i=0; i< AE->getNumOperands(); i++)
284 if (containsAddRecFromDifferentLoop(AE->getOperand(i), L))
285 return true;
286 return false;
287 }
288 if (SCEVAddRecExpr *AE = dyn_cast<SCEVAddRecExpr>(S)) {
289 if (const Loop *newLoop = AE->getLoop()) {
290 if (newLoop == L)
291 return false;
292 // if newLoop is an outer loop of L, this is OK.
293 if (!LoopInfoBase<BasicBlock>::isNotAlreadyContainedIn(L, newLoop))
294 return false;
295 }
296 return true;
297 }
298 if (SCEVUDivExpr *DE = dyn_cast<SCEVUDivExpr>(S))
299 return containsAddRecFromDifferentLoop(DE->getLHS(), L) ||
300 containsAddRecFromDifferentLoop(DE->getRHS(), L);
301#if 0
302 // SCEVSDivExpr has been backed out temporarily, but will be back; we'll
303 // need this when it is.
304 if (SCEVSDivExpr *DE = dyn_cast<SCEVSDivExpr>(S))
305 return containsAddRecFromDifferentLoop(DE->getLHS(), L) ||
306 containsAddRecFromDifferentLoop(DE->getRHS(), L);
307#endif
308 if (SCEVTruncateExpr *TE = dyn_cast<SCEVTruncateExpr>(S))
309 return containsAddRecFromDifferentLoop(TE->getOperand(), L);
310 if (SCEVZeroExtendExpr *ZE = dyn_cast<SCEVZeroExtendExpr>(S))
311 return containsAddRecFromDifferentLoop(ZE->getOperand(), L);
312 if (SCEVSignExtendExpr *SE = dyn_cast<SCEVSignExtendExpr>(S))
313 return containsAddRecFromDifferentLoop(SE->getOperand(), L);
314 return false;
315}
316
Chris Lattner7db543f2005-08-04 19:08:16 +0000317/// getSCEVStartAndStride - Compute the start and stride of this expression,
318/// returning false if the expression is not a start/stride pair, or true if it
319/// is. The stride must be a loop invariant expression, but the start may be
Dale Johannesen2f46bb82009-01-14 02:35:31 +0000320/// a mix of loop invariant and loop variant expressions. The start cannot,
321/// however, contain an AddRec from a different loop, unless that loop is an
322/// outer loop of the current loop.
Chris Lattner7db543f2005-08-04 19:08:16 +0000323static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
Dan Gohman246b2562007-10-22 18:31:58 +0000324 SCEVHandle &Start, SCEVHandle &Stride,
Evan Cheng8f40afe2009-02-15 06:06:15 +0000325 ScalarEvolution *SE, DominatorTree *DT) {
Chris Lattner7db543f2005-08-04 19:08:16 +0000326 SCEVHandle TheAddRec = Start; // Initialize to zero.
327
328 // If the outer level is an AddExpr, the operands are all start values except
329 // for a nested AddRecExpr.
330 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
331 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
332 if (SCEVAddRecExpr *AddRec =
333 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
334 if (AddRec->getLoop() == L)
Dan Gohman246b2562007-10-22 18:31:58 +0000335 TheAddRec = SE->getAddExpr(AddRec, TheAddRec);
Chris Lattner7db543f2005-08-04 19:08:16 +0000336 else
337 return false; // Nested IV of some sort?
338 } else {
Dan Gohman246b2562007-10-22 18:31:58 +0000339 Start = SE->getAddExpr(Start, AE->getOperand(i));
Chris Lattner7db543f2005-08-04 19:08:16 +0000340 }
341
Reid Spencer3ed469c2006-11-02 20:25:50 +0000342 } else if (isa<SCEVAddRecExpr>(SH)) {
Chris Lattner7db543f2005-08-04 19:08:16 +0000343 TheAddRec = SH;
344 } else {
345 return false; // not analyzable.
346 }
347
348 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
349 if (!AddRec || AddRec->getLoop() != L) return false;
350
351 // FIXME: Generalize to non-affine IV's.
352 if (!AddRec->isAffine()) return false;
353
Dale Johannesen2f46bb82009-01-14 02:35:31 +0000354 // If Start contains an SCEVAddRecExpr from a different loop, other than an
Dale Johannesen1de17d52009-02-09 22:14:15 +0000355 // outer loop of the current loop, reject it. SCEV has no concept of
Dan Gohmanfd033992009-03-04 20:50:23 +0000356 // operating on more than one loop at a time so don't confuse it with such
357 // expressions.
Dan Gohman9194e8b2009-02-13 03:58:31 +0000358 if (containsAddRecFromDifferentLoop(AddRec->getOperand(0), L))
Dale Johannesen2f46bb82009-01-14 02:35:31 +0000359 return false;
360
Dan Gohman246b2562007-10-22 18:31:58 +0000361 Start = SE->getAddExpr(Start, AddRec->getOperand(0));
Chris Lattner7db543f2005-08-04 19:08:16 +0000362
Evan Cheng8f40afe2009-02-15 06:06:15 +0000363 if (!isa<SCEVConstant>(AddRec->getOperand(1))) {
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000364 // If stride is an instruction, make sure it dominates the loop preheader.
Evan Cheng8f40afe2009-02-15 06:06:15 +0000365 // Otherwise we could end up with a use before def situation.
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000366 BasicBlock *Preheader = L->getLoopPreheader();
367 if (!AddRec->getOperand(1)->dominates(Preheader, DT))
368 return false;
Evan Cheng8f40afe2009-02-15 06:06:15 +0000369
Bill Wendlingb7427032006-11-26 09:46:52 +0000370 DOUT << "[" << L->getHeader()->getName()
371 << "] Variable stride: " << *AddRec << "\n";
Evan Cheng8f40afe2009-02-15 06:06:15 +0000372 }
Chris Lattner7db543f2005-08-04 19:08:16 +0000373
Chris Lattner50fad702005-08-10 00:45:21 +0000374 Stride = AddRec->getOperand(1);
Chris Lattner7db543f2005-08-04 19:08:16 +0000375 return true;
376}
377
Chris Lattner0ae33eb2005-10-03 01:04:44 +0000378/// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
379/// and now we need to decide whether the user should use the preinc or post-inc
380/// value. If this user should use the post-inc version of the IV, return true.
381///
382/// Choosing wrong here can break dominance properties (if we choose to use the
383/// post-inc value when we cannot) or it can end up adding extra live-ranges to
384/// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
385/// should use the post-inc value).
386static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
Evan Cheng0e0014d2007-10-30 23:45:15 +0000387 Loop *L, DominatorTree *DT, Pass *P,
Chris Lattner09fb7da2008-12-01 06:27:41 +0000388 SmallVectorImpl<Instruction*> &DeadInsts){
Chris Lattner0ae33eb2005-10-03 01:04:44 +0000389 // If the user is in the loop, use the preinc value.
390 if (L->contains(User->getParent())) return false;
391
Chris Lattner5e8ca662005-10-03 02:50:05 +0000392 BasicBlock *LatchBlock = L->getLoopLatch();
393
394 // Ok, the user is outside of the loop. If it is dominated by the latch
395 // block, use the post-inc value.
Devang Patelb7d9dfc2007-06-07 21:42:15 +0000396 if (DT->dominates(LatchBlock, User->getParent()))
Chris Lattner5e8ca662005-10-03 02:50:05 +0000397 return true;
398
399 // There is one case we have to be careful of: PHI nodes. These little guys
400 // can live in blocks that do not dominate the latch block, but (since their
401 // uses occur in the predecessor block, not the block the PHI lives in) should
402 // still use the post-inc value. Check for this case now.
403 PHINode *PN = dyn_cast<PHINode>(User);
404 if (!PN) return false; // not a phi, not dominated by latch block.
405
406 // Look at all of the uses of IV by the PHI node. If any use corresponds to
407 // a block that is not dominated by the latch block, give up and use the
408 // preincremented value.
409 unsigned NumUses = 0;
410 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
411 if (PN->getIncomingValue(i) == IV) {
412 ++NumUses;
Devang Patelb7d9dfc2007-06-07 21:42:15 +0000413 if (!DT->dominates(LatchBlock, PN->getIncomingBlock(i)))
Chris Lattner5e8ca662005-10-03 02:50:05 +0000414 return false;
415 }
416
417 // Okay, all uses of IV by PN are in predecessor blocks that really are
418 // dominated by the latch block. Split the critical edges and use the
419 // post-incremented value.
420 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
421 if (PN->getIncomingValue(i) == IV) {
Evan Cheng83927722007-10-30 22:27:26 +0000422 SplitCriticalEdge(PN->getIncomingBlock(i), PN->getParent(), P, false);
Chris Lattner1b9c8e72006-10-28 00:59:20 +0000423 // Splitting the critical edge can reduce the number of entries in this
424 // PHI.
425 e = PN->getNumIncomingValues();
Chris Lattner5e8ca662005-10-03 02:50:05 +0000426 if (--NumUses == 0) break;
427 }
Evan Cheng0e0014d2007-10-30 23:45:15 +0000428
429 // PHI node might have become a constant value after SplitCriticalEdge.
Chris Lattner09fb7da2008-12-01 06:27:41 +0000430 DeadInsts.push_back(User);
Chris Lattner5e8ca662005-10-03 02:50:05 +0000431
432 return true;
Chris Lattner0ae33eb2005-10-03 01:04:44 +0000433}
434
Dan Gohmanf284ce22009-02-18 00:08:39 +0000435/// isAddressUse - Returns true if the specified instruction is using the
Dale Johannesen203af582008-12-05 21:47:27 +0000436/// specified value as an address.
437static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
438 bool isAddress = isa<LoadInst>(Inst);
439 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
440 if (SI->getOperand(1) == OperandVal)
441 isAddress = true;
442 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
443 // Addressing modes can also be folded into prefetches and a variety
444 // of intrinsics.
445 switch (II->getIntrinsicID()) {
446 default: break;
447 case Intrinsic::prefetch:
448 case Intrinsic::x86_sse2_loadu_dq:
449 case Intrinsic::x86_sse2_loadu_pd:
450 case Intrinsic::x86_sse_loadu_ps:
451 case Intrinsic::x86_sse_storeu_ps:
452 case Intrinsic::x86_sse2_storeu_pd:
453 case Intrinsic::x86_sse2_storeu_dq:
454 case Intrinsic::x86_sse2_storel_dq:
455 if (II->getOperand(1) == OperandVal)
456 isAddress = true;
457 break;
458 }
459 }
460 return isAddress;
461}
Chris Lattner0ae33eb2005-10-03 01:04:44 +0000462
Dan Gohman21e77222009-03-09 21:01:17 +0000463/// getAccessType - Return the type of the memory being accessed.
464static const Type *getAccessType(const Instruction *Inst) {
465 const Type *UseTy = Inst->getType();
466 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst))
467 UseTy = SI->getOperand(0)->getType();
468 else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
469 // Addressing modes can also be folded into prefetches and a variety
470 // of intrinsics.
471 switch (II->getIntrinsicID()) {
472 default: break;
473 case Intrinsic::x86_sse_storeu_ps:
474 case Intrinsic::x86_sse2_storeu_pd:
475 case Intrinsic::x86_sse2_storeu_dq:
476 case Intrinsic::x86_sse2_storel_dq:
477 UseTy = II->getOperand(1)->getType();
478 break;
479 }
480 }
481 return UseTy;
482}
483
Nate Begeman16997482005-07-30 00:15:07 +0000484/// AddUsersIfInteresting - Inspect the specified instruction. If it is a
485/// reducible SCEV, recursively add its users to the IVUsesByStride set and
486/// return true. Otherwise, return false.
Chris Lattner3416e5f2005-08-04 17:40:30 +0000487bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
Evan Cheng168a66b2007-10-26 23:08:19 +0000488 SmallPtrSet<Instruction*,16> &Processed) {
Chris Lattner42a75512007-01-15 02:27:26 +0000489 if (!I->getType()->isInteger() && !isa<PointerType>(I->getType()))
Dan Gohman4a9a3e52008-04-14 18:26:16 +0000490 return false; // Void and FP expressions cannot be reduced.
Chris Lattnerb7e64ac2009-03-17 23:58:30 +0000491
492 // LSR is not APInt clean, do not touch integers bigger than 64-bits.
493 if (I->getType()->isInteger() &&
494 I->getType()->getPrimitiveSizeInBits() > 64)
495 return false;
496
Evan Cheng168a66b2007-10-26 23:08:19 +0000497 if (!Processed.insert(I))
Chris Lattner3416e5f2005-08-04 17:40:30 +0000498 return true; // Instruction already handled.
499
Chris Lattner7db543f2005-08-04 19:08:16 +0000500 // Get the symbolic expression for this instruction.
Dan Gohman2d1be872009-04-16 03:18:22 +0000501 SCEVHandle ISE = SE->getSCEV(I);
Chris Lattner7db543f2005-08-04 19:08:16 +0000502 if (isa<SCEVCouldNotCompute>(ISE)) return false;
Chris Lattner3416e5f2005-08-04 17:40:30 +0000503
Chris Lattner7db543f2005-08-04 19:08:16 +0000504 // Get the start and stride for this expression.
Dan Gohman246b2562007-10-22 18:31:58 +0000505 SCEVHandle Start = SE->getIntegerSCEV(0, ISE->getType());
Chris Lattner50fad702005-08-10 00:45:21 +0000506 SCEVHandle Stride = Start;
Evan Cheng8f40afe2009-02-15 06:06:15 +0000507 if (!getSCEVStartAndStride(ISE, L, Start, Stride, SE, DT))
Chris Lattner7db543f2005-08-04 19:08:16 +0000508 return false; // Non-reducible symbolic expression, bail out.
Devang Patel4fe26582007-03-09 21:19:53 +0000509
Devang Patel2a5fa182007-04-23 22:42:03 +0000510 std::vector<Instruction *> IUsers;
511 // Collect all I uses now because IVUseShouldUsePostIncValue may
512 // invalidate use_iterator.
513 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
514 IUsers.push_back(cast<Instruction>(*UI));
Nate Begeman16997482005-07-30 00:15:07 +0000515
Devang Patel2a5fa182007-04-23 22:42:03 +0000516 for (unsigned iused_index = 0, iused_size = IUsers.size();
517 iused_index != iused_size; ++iused_index) {
518
519 Instruction *User = IUsers[iused_index];
Devang Patel4fe26582007-03-09 21:19:53 +0000520
Nate Begeman16997482005-07-30 00:15:07 +0000521 // Do not infinitely recurse on PHI nodes.
Chris Lattner396b2ba2005-09-13 02:09:55 +0000522 if (isa<PHINode>(User) && Processed.count(User))
Nate Begeman16997482005-07-30 00:15:07 +0000523 continue;
524
Dale Johannesen2f46bb82009-01-14 02:35:31 +0000525 // Descend recursively, but not into PHI nodes outside the current loop.
526 // It's important to see the entire expression outside the loop to get
527 // choices that depend on addressing mode use right, although we won't
528 // consider references ouside the loop in all cases.
529 // If User is already in Processed, we don't want to recurse into it again,
530 // but do want to record a second reference in the same instruction.
Chris Lattner7db543f2005-08-04 19:08:16 +0000531 bool AddUserToIVUsers = false;
Chris Lattnerf9186592005-08-04 00:14:11 +0000532 if (LI->getLoopFor(User->getParent()) != L) {
Dale Johannesen2f46bb82009-01-14 02:35:31 +0000533 if (isa<PHINode>(User) || Processed.count(User) ||
534 !AddUsersIfInteresting(User, L, Processed)) {
535 DOUT << "FOUND USER in other loop: " << *User
536 << " OF SCEV: " << *ISE << "\n";
537 AddUserToIVUsers = true;
538 }
539 } else if (Processed.count(User) ||
540 !AddUsersIfInteresting(User, L, Processed)) {
Bill Wendlingb7427032006-11-26 09:46:52 +0000541 DOUT << "FOUND USER: " << *User
542 << " OF SCEV: " << *ISE << "\n";
Chris Lattner7db543f2005-08-04 19:08:16 +0000543 AddUserToIVUsers = true;
544 }
Nate Begeman16997482005-07-30 00:15:07 +0000545
Chris Lattner7db543f2005-08-04 19:08:16 +0000546 if (AddUserToIVUsers) {
Chris Lattner7305ae22005-10-09 06:20:55 +0000547 IVUsersOfOneStride &StrideUses = IVUsesByStride[Stride];
Dale Johannesenb0390622008-12-16 22:16:28 +0000548 if (StrideUses.Users.empty()) // First occurrence of this stride?
Chris Lattner7305ae22005-10-09 06:20:55 +0000549 StrideOrder.push_back(Stride);
550
Chris Lattnera4479ad2005-08-04 00:40:47 +0000551 // Okay, we found a user that we cannot reduce. Analyze the instruction
Chris Lattnerc6bae652005-09-12 06:04:47 +0000552 // and decide what to do with it. If we are a use inside of the loop, use
553 // the value before incrementation, otherwise use it after incrementation.
Evan Cheng0e0014d2007-10-30 23:45:15 +0000554 if (IVUseShouldUsePostIncValue(User, I, L, DT, this, DeadInsts)) {
Chris Lattnerc6bae652005-09-12 06:04:47 +0000555 // The value used will be incremented by the stride more than we are
556 // expecting, so subtract this off.
Dan Gohman246b2562007-10-22 18:31:58 +0000557 SCEVHandle NewStart = SE->getMinusSCEV(Start, Stride);
Chris Lattner7305ae22005-10-09 06:20:55 +0000558 StrideUses.addUser(NewStart, User, I);
559 StrideUses.Users.back().isUseOfPostIncrementedValue = true;
Bill Wendlingb7427032006-11-26 09:46:52 +0000560 DOUT << " USING POSTINC SCEV, START=" << *NewStart<< "\n";
Chris Lattner0ae33eb2005-10-03 01:04:44 +0000561 } else {
Chris Lattner7305ae22005-10-09 06:20:55 +0000562 StrideUses.addUser(Start, User, I);
Chris Lattnerc6bae652005-09-12 06:04:47 +0000563 }
Nate Begeman16997482005-07-30 00:15:07 +0000564 }
565 }
566 return true;
567}
568
569namespace {
570 /// BasedUser - For a particular base value, keep information about how we've
571 /// partitioned the expression so far.
572 struct BasedUser {
Dan Gohman246b2562007-10-22 18:31:58 +0000573 /// SE - The current ScalarEvolution object.
574 ScalarEvolution *SE;
575
Chris Lattnera553b0c2005-08-08 22:56:21 +0000576 /// Base - The Base value for the PHI node that needs to be inserted for
577 /// this use. As the use is processed, information gets moved from this
578 /// field to the Imm field (below). BasedUser values are sorted by this
579 /// field.
580 SCEVHandle Base;
581
Nate Begeman16997482005-07-30 00:15:07 +0000582 /// Inst - The instruction using the induction variable.
583 Instruction *Inst;
584
Chris Lattnerec3fb632005-08-03 22:21:05 +0000585 /// OperandValToReplace - The operand value of Inst to replace with the
586 /// EmittedBase.
587 Value *OperandValToReplace;
Nate Begeman16997482005-07-30 00:15:07 +0000588
589 /// Imm - The immediate value that should be added to the base immediately
590 /// before Inst, because it will be folded into the imm field of the
Dan Gohman33e3a362009-02-20 20:29:04 +0000591 /// instruction. This is also sometimes used for loop-variant values that
592 /// must be added inside the loop.
Nate Begeman16997482005-07-30 00:15:07 +0000593 SCEVHandle Imm;
594
Dan Gohmanc17e0cf2009-02-20 04:17:46 +0000595 /// Phi - The induction variable that performs the striding that
596 /// should be used for this user.
Dan Gohman9d100862009-03-09 22:04:01 +0000597 PHINode *Phi;
Dan Gohmanc17e0cf2009-02-20 04:17:46 +0000598
Chris Lattner010de252005-08-08 05:28:22 +0000599 // isUseOfPostIncrementedValue - True if this should use the
600 // post-incremented version of this IV, not the preincremented version.
601 // This can only be set in special cases, such as the terminating setcc
Chris Lattnerc6bae652005-09-12 06:04:47 +0000602 // instruction for a loop and uses outside the loop that are dominated by
603 // the loop.
Chris Lattner010de252005-08-08 05:28:22 +0000604 bool isUseOfPostIncrementedValue;
Chris Lattnera553b0c2005-08-08 22:56:21 +0000605
Dan Gohman246b2562007-10-22 18:31:58 +0000606 BasedUser(IVStrideUse &IVSU, ScalarEvolution *se)
607 : SE(se), Base(IVSU.Offset), Inst(IVSU.User),
Chris Lattnera553b0c2005-08-08 22:56:21 +0000608 OperandValToReplace(IVSU.OperandValToReplace),
Dale Johannesen308f24d2008-12-03 22:43:56 +0000609 Imm(SE->getIntegerSCEV(0, Base->getType())),
Chris Lattnera553b0c2005-08-08 22:56:21 +0000610 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
Nate Begeman16997482005-07-30 00:15:07 +0000611
Chris Lattner2114b272005-08-04 20:03:32 +0000612 // Once we rewrite the code to insert the new IVs we want, update the
613 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
614 // to it.
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000615 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Dan Gohmanf20d70d2008-05-15 23:26:57 +0000616 Instruction *InsertPt,
Evan Cheng0e0014d2007-10-30 23:45:15 +0000617 SCEVExpander &Rewriter, Loop *L, Pass *P,
Chris Lattner09fb7da2008-12-01 06:27:41 +0000618 SmallVectorImpl<Instruction*> &DeadInsts);
Chris Lattner221fc3c2006-02-04 07:36:50 +0000619
620 Value *InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
Dan Gohman2d1be872009-04-16 03:18:22 +0000621 const Type *Ty,
Chris Lattner221fc3c2006-02-04 07:36:50 +0000622 SCEVExpander &Rewriter,
623 Instruction *IP, Loop *L);
Nate Begeman16997482005-07-30 00:15:07 +0000624 void dump() const;
625 };
626}
627
628void BasedUser::dump() const {
Bill Wendlinge8156192006-12-07 01:30:32 +0000629 cerr << " Base=" << *Base;
630 cerr << " Imm=" << *Imm;
Bill Wendlinge8156192006-12-07 01:30:32 +0000631 cerr << " Inst: " << *Inst;
Nate Begeman16997482005-07-30 00:15:07 +0000632}
633
Chris Lattner221fc3c2006-02-04 07:36:50 +0000634Value *BasedUser::InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
Dan Gohman2d1be872009-04-16 03:18:22 +0000635 const Type *Ty,
Chris Lattner221fc3c2006-02-04 07:36:50 +0000636 SCEVExpander &Rewriter,
637 Instruction *IP, Loop *L) {
638 // Figure out where we *really* want to insert this code. In particular, if
639 // the user is inside of a loop that is nested inside of L, we really don't
640 // want to insert this expression before the user, we'd rather pull it out as
641 // many loops as possible.
642 LoopInfo &LI = Rewriter.getLoopInfo();
643 Instruction *BaseInsertPt = IP;
644
645 // Figure out the most-nested loop that IP is in.
646 Loop *InsertLoop = LI.getLoopFor(IP->getParent());
647
648 // If InsertLoop is not L, and InsertLoop is nested inside of L, figure out
649 // the preheader of the outer-most loop where NewBase is not loop invariant.
Dale Johanneseneccdd082008-12-02 18:40:09 +0000650 if (L->contains(IP->getParent()))
651 while (InsertLoop && NewBase->isLoopInvariant(InsertLoop)) {
652 BaseInsertPt = InsertLoop->getLoopPreheader()->getTerminator();
653 InsertLoop = InsertLoop->getParentLoop();
654 }
Chris Lattner221fc3c2006-02-04 07:36:50 +0000655
Dan Gohman2d1be872009-04-16 03:18:22 +0000656 Value *Base = Rewriter.expandCodeFor(NewBase, Ty, BaseInsertPt);
Dan Gohman2f09f512009-02-19 19:23:27 +0000657
Chris Lattner221fc3c2006-02-04 07:36:50 +0000658 // If there is no immediate value, skip the next part.
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000659 if (Imm->isZero())
Dan Gohman2f09f512009-02-19 19:23:27 +0000660 return Base;
Chris Lattnerb47f6122007-06-06 01:23:55 +0000661
662 // If we are inserting the base and imm values in the same block, make sure to
663 // adjust the IP position if insertion reused a result.
664 if (IP == BaseInsertPt)
665 IP = Rewriter.getInsertionPoint();
Chris Lattner221fc3c2006-02-04 07:36:50 +0000666
667 // Always emit the immediate (if non-zero) into the same block as the user.
Dan Gohman246b2562007-10-22 18:31:58 +0000668 SCEVHandle NewValSCEV = SE->getAddExpr(SE->getUnknown(Base), Imm);
Dan Gohman2d1be872009-04-16 03:18:22 +0000669 return Rewriter.expandCodeFor(NewValSCEV, Ty, IP);
Chris Lattner221fc3c2006-02-04 07:36:50 +0000670}
671
672
Chris Lattner2114b272005-08-04 20:03:32 +0000673// Once we rewrite the code to insert the new IVs we want, update the
674// operands of Inst to use the new expression 'NewBase', with 'Imm' added
Dan Gohmanf20d70d2008-05-15 23:26:57 +0000675// to it. NewBasePt is the last instruction which contributes to the
676// value of NewBase in the case that it's a diffferent instruction from
677// the PHI that NewBase is computed from, or null otherwise.
678//
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000679void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Dan Gohmanf20d70d2008-05-15 23:26:57 +0000680 Instruction *NewBasePt,
Evan Cheng0e0014d2007-10-30 23:45:15 +0000681 SCEVExpander &Rewriter, Loop *L, Pass *P,
Chris Lattner09fb7da2008-12-01 06:27:41 +0000682 SmallVectorImpl<Instruction*> &DeadInsts){
Chris Lattner2114b272005-08-04 20:03:32 +0000683 if (!isa<PHINode>(Inst)) {
Chris Lattnerc5494af2007-04-13 20:42:26 +0000684 // By default, insert code at the user instruction.
685 BasicBlock::iterator InsertPt = Inst;
686
687 // However, if the Operand is itself an instruction, the (potentially
688 // complex) inserted code may be shared by many users. Because of this, we
689 // want to emit code for the computation of the operand right before its old
690 // computation. This is usually safe, because we obviously used to use the
691 // computation when it was computed in its current block. However, in some
692 // cases (e.g. use of a post-incremented induction variable) the NewBase
693 // value will be pinned to live somewhere after the original computation.
694 // In this case, we have to back off.
Chris Lattnerf8828eb2008-12-02 04:52:26 +0000695 //
696 // If this is a use outside the loop (which means after, since it is based
697 // on a loop indvar) we use the post-incremented value, so that we don't
698 // artificially make the preinc value live out the bottom of the loop.
Dale Johannesen589bf082008-12-01 22:00:01 +0000699 if (!isUseOfPostIncrementedValue && L->contains(Inst->getParent())) {
Dan Gohmanca756ae2008-05-20 03:01:48 +0000700 if (NewBasePt && isa<PHINode>(OperandValToReplace)) {
Dan Gohmanf20d70d2008-05-15 23:26:57 +0000701 InsertPt = NewBasePt;
702 ++InsertPt;
Gabor Greif6725cb52008-06-11 21:38:51 +0000703 } else if (Instruction *OpInst
704 = dyn_cast<Instruction>(OperandValToReplace)) {
Chris Lattnerc5494af2007-04-13 20:42:26 +0000705 InsertPt = OpInst;
706 while (isa<PHINode>(InsertPt)) ++InsertPt;
707 }
708 }
Dan Gohman2d1be872009-04-16 03:18:22 +0000709 Value *NewVal = InsertCodeForBaseAtPosition(NewBase,
710 OperandValToReplace->getType(),
711 Rewriter, InsertPt, L);
Chris Lattner2114b272005-08-04 20:03:32 +0000712 // Replace the use of the operand Value with the new Phi we just created.
713 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
Dan Gohman2f09f512009-02-19 19:23:27 +0000714
Dan Gohman2f09f512009-02-19 19:23:27 +0000715 DOUT << " Replacing with ";
Dan Gohman4a359ea2009-02-19 19:32:06 +0000716 DEBUG(WriteAsOperand(*DOUT, NewVal, /*PrintType=*/false));
Dan Gohman2f09f512009-02-19 19:23:27 +0000717 DOUT << ", which has value " << *NewBase << " plus IMM " << *Imm << "\n";
Chris Lattner2114b272005-08-04 20:03:32 +0000718 return;
719 }
Dan Gohman2f09f512009-02-19 19:23:27 +0000720
Chris Lattner2114b272005-08-04 20:03:32 +0000721 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
Chris Lattnerc41e3452005-08-10 00:35:32 +0000722 // expression into each operand block that uses it. Note that PHI nodes can
723 // have multiple entries for the same predecessor. We use a map to make sure
724 // that a PHI node only has a single Value* for each predecessor (which also
725 // prevents us from inserting duplicate code in some blocks).
Evan Cheng83927722007-10-30 22:27:26 +0000726 DenseMap<BasicBlock*, Value*> InsertedCode;
Chris Lattner2114b272005-08-04 20:03:32 +0000727 PHINode *PN = cast<PHINode>(Inst);
728 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
729 if (PN->getIncomingValue(i) == OperandValToReplace) {
Dale Johannesen2f46bb82009-01-14 02:35:31 +0000730 // If the original expression is outside the loop, put the replacement
731 // code in the same place as the original expression,
732 // which need not be an immediate predecessor of this PHI. This way we
733 // need only one copy of it even if it is referenced multiple times in
734 // the PHI. We don't do this when the original expression is inside the
Dale Johannesen1de17d52009-02-09 22:14:15 +0000735 // loop because multiple copies sometimes do useful sinking of code in
736 // that case(?).
Dale Johannesen2f46bb82009-01-14 02:35:31 +0000737 Instruction *OldLoc = dyn_cast<Instruction>(OperandValToReplace);
738 if (L->contains(OldLoc->getParent())) {
Dale Johannesen1de17d52009-02-09 22:14:15 +0000739 // If this is a critical edge, split the edge so that we do not insert
740 // the code on all predecessor/successor paths. We do this unless this
741 // is the canonical backedge for this loop, as this can make some
742 // inserted code be in an illegal position.
Dale Johannesen2f46bb82009-01-14 02:35:31 +0000743 BasicBlock *PHIPred = PN->getIncomingBlock(i);
744 if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
745 (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
Dale Johannesenf6727b02008-12-23 23:21:35 +0000746
Dale Johannesen2f46bb82009-01-14 02:35:31 +0000747 // First step, split the critical edge.
748 SplitCriticalEdge(PHIPred, PN->getParent(), P, false);
749
750 // Next step: move the basic block. In particular, if the PHI node
751 // is outside of the loop, and PredTI is in the loop, we want to
752 // move the block to be immediately before the PHI block, not
753 // immediately after PredTI.
754 if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
755 BasicBlock *NewBB = PN->getIncomingBlock(i);
756 NewBB->moveBefore(PN->getParent());
757 }
758
759 // Splitting the edge can reduce the number of PHI entries we have.
760 e = PN->getNumIncomingValues();
761 }
762 }
Chris Lattnerc41e3452005-08-10 00:35:32 +0000763 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
764 if (!Code) {
765 // Insert the code into the end of the predecessor block.
Dale Johannesen2f46bb82009-01-14 02:35:31 +0000766 Instruction *InsertPt = (L->contains(OldLoc->getParent())) ?
767 PN->getIncomingBlock(i)->getTerminator() :
768 OldLoc->getParent()->getTerminator();
Dan Gohman2d1be872009-04-16 03:18:22 +0000769 Code = InsertCodeForBaseAtPosition(NewBase, PN->getType(),
770 Rewriter, InsertPt, L);
Dan Gohman2f09f512009-02-19 19:23:27 +0000771
Dan Gohman2f09f512009-02-19 19:23:27 +0000772 DOUT << " Changing PHI use to ";
Dan Gohman4a359ea2009-02-19 19:32:06 +0000773 DEBUG(WriteAsOperand(*DOUT, Code, /*PrintType=*/false));
Dan Gohman2f09f512009-02-19 19:23:27 +0000774 DOUT << ", which has value " << *NewBase << " plus IMM " << *Imm << "\n";
Chris Lattnerc41e3452005-08-10 00:35:32 +0000775 }
Dan Gohman2f09f512009-02-19 19:23:27 +0000776
Chris Lattner2114b272005-08-04 20:03:32 +0000777 // Replace the use of the operand Value with the new Phi we just created.
Chris Lattnerc41e3452005-08-10 00:35:32 +0000778 PN->setIncomingValue(i, Code);
Chris Lattner2114b272005-08-04 20:03:32 +0000779 Rewriter.clear();
780 }
781 }
Evan Cheng0e0014d2007-10-30 23:45:15 +0000782
783 // PHI node might have become a constant value after SplitCriticalEdge.
Chris Lattner09fb7da2008-12-01 06:27:41 +0000784 DeadInsts.push_back(Inst);
Chris Lattner2114b272005-08-04 20:03:32 +0000785}
786
787
Dale Johannesen203af582008-12-05 21:47:27 +0000788/// fitsInAddressMode - Return true if V can be subsumed within an addressing
789/// mode, and does not need to be put in a register first.
790static bool fitsInAddressMode(const SCEVHandle &V, const Type *UseTy,
791 const TargetLowering *TLI, bool HasBaseReg) {
Chris Lattner3821e472005-08-08 06:25:50 +0000792 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
Evan Cheng5eef2d22007-03-12 23:27:37 +0000793 int64_t VC = SC->getValue()->getSExtValue();
Chris Lattner579633c2007-04-09 22:20:14 +0000794 if (TLI) {
795 TargetLowering::AddrMode AM;
796 AM.BaseOffs = VC;
Dale Johannesen203af582008-12-05 21:47:27 +0000797 AM.HasBaseReg = HasBaseReg;
Chris Lattner579633c2007-04-09 22:20:14 +0000798 return TLI->isLegalAddressingMode(AM, UseTy);
799 } else {
Evan Chengd277f2c2006-03-13 23:14:23 +0000800 // Defaults to PPC. PPC allows a sign-extended 16-bit immediate field.
Evan Cheng5eef2d22007-03-12 23:27:37 +0000801 return (VC > -(1 << 16) && VC < (1 << 16)-1);
Chris Lattner579633c2007-04-09 22:20:14 +0000802 }
Chris Lattner3821e472005-08-08 06:25:50 +0000803 }
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000804
Nate Begeman16997482005-07-30 00:15:07 +0000805 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
Dan Gohman2d1be872009-04-16 03:18:22 +0000806 if (GlobalValue *GV = dyn_cast<GlobalValue>(SU->getValue())) {
807 TargetLowering::AddrMode AM;
808 AM.BaseGV = GV;
809 AM.HasBaseReg = HasBaseReg;
810 return TLI->isLegalAddressingMode(AM, UseTy);
811 }
812
Nate Begeman16997482005-07-30 00:15:07 +0000813 return false;
814}
815
Dale Johannesen544e0d02008-12-03 20:56:12 +0000816/// MoveLoopVariantsToImmediateField - Move any subexpressions from Val that are
Chris Lattner44b807e2005-08-08 22:32:34 +0000817/// loop varying to the Imm operand.
Dale Johannesen544e0d02008-12-03 20:56:12 +0000818static void MoveLoopVariantsToImmediateField(SCEVHandle &Val, SCEVHandle &Imm,
Dan Gohman246b2562007-10-22 18:31:58 +0000819 Loop *L, ScalarEvolution *SE) {
Chris Lattner44b807e2005-08-08 22:32:34 +0000820 if (Val->isLoopInvariant(L)) return; // Nothing to do.
821
822 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
823 std::vector<SCEVHandle> NewOps;
824 NewOps.reserve(SAE->getNumOperands());
825
826 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
827 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
828 // If this is a loop-variant expression, it must stay in the immediate
829 // field of the expression.
Dan Gohman246b2562007-10-22 18:31:58 +0000830 Imm = SE->getAddExpr(Imm, SAE->getOperand(i));
Chris Lattner44b807e2005-08-08 22:32:34 +0000831 } else {
832 NewOps.push_back(SAE->getOperand(i));
833 }
834
835 if (NewOps.empty())
Dan Gohman246b2562007-10-22 18:31:58 +0000836 Val = SE->getIntegerSCEV(0, Val->getType());
Chris Lattner44b807e2005-08-08 22:32:34 +0000837 else
Dan Gohman246b2562007-10-22 18:31:58 +0000838 Val = SE->getAddExpr(NewOps);
Chris Lattner44b807e2005-08-08 22:32:34 +0000839 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
840 // Try to pull immediates out of the start value of nested addrec's.
841 SCEVHandle Start = SARE->getStart();
Dale Johannesen544e0d02008-12-03 20:56:12 +0000842 MoveLoopVariantsToImmediateField(Start, Imm, L, SE);
Chris Lattner44b807e2005-08-08 22:32:34 +0000843
844 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
845 Ops[0] = Start;
Dan Gohman246b2562007-10-22 18:31:58 +0000846 Val = SE->getAddRecExpr(Ops, SARE->getLoop());
Chris Lattner44b807e2005-08-08 22:32:34 +0000847 } else {
848 // Otherwise, all of Val is variant, move the whole thing over.
Dan Gohman246b2562007-10-22 18:31:58 +0000849 Imm = SE->getAddExpr(Imm, Val);
850 Val = SE->getIntegerSCEV(0, Val->getType());
Chris Lattner44b807e2005-08-08 22:32:34 +0000851 }
852}
853
854
Chris Lattner26d91f12005-08-04 22:34:05 +0000855/// MoveImmediateValues - Look at Val, and pull out any additions of constants
Nate Begeman16997482005-07-30 00:15:07 +0000856/// that can fit into the immediate field of instructions in the target.
Chris Lattner26d91f12005-08-04 22:34:05 +0000857/// Accumulate these immediate values into the Imm value.
Evan Chengd277f2c2006-03-13 23:14:23 +0000858static void MoveImmediateValues(const TargetLowering *TLI,
Evan Chengd9fb7122009-02-21 02:06:47 +0000859 const Type *UseTy,
Evan Chengd277f2c2006-03-13 23:14:23 +0000860 SCEVHandle &Val, SCEVHandle &Imm,
Dan Gohman246b2562007-10-22 18:31:58 +0000861 bool isAddress, Loop *L,
862 ScalarEvolution *SE) {
Chris Lattner7a658392005-08-03 23:44:42 +0000863 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
Chris Lattner26d91f12005-08-04 22:34:05 +0000864 std::vector<SCEVHandle> NewOps;
865 NewOps.reserve(SAE->getNumOperands());
866
Chris Lattner221fc3c2006-02-04 07:36:50 +0000867 for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
868 SCEVHandle NewOp = SAE->getOperand(i);
Evan Chengd9fb7122009-02-21 02:06:47 +0000869 MoveImmediateValues(TLI, UseTy, NewOp, Imm, isAddress, L, SE);
Chris Lattner221fc3c2006-02-04 07:36:50 +0000870
871 if (!NewOp->isLoopInvariant(L)) {
Chris Lattner7db543f2005-08-04 19:08:16 +0000872 // If this is a loop-variant expression, it must stay in the immediate
873 // field of the expression.
Dan Gohman246b2562007-10-22 18:31:58 +0000874 Imm = SE->getAddExpr(Imm, NewOp);
Chris Lattner26d91f12005-08-04 22:34:05 +0000875 } else {
Chris Lattner221fc3c2006-02-04 07:36:50 +0000876 NewOps.push_back(NewOp);
Nate Begeman16997482005-07-30 00:15:07 +0000877 }
Chris Lattner221fc3c2006-02-04 07:36:50 +0000878 }
Chris Lattner26d91f12005-08-04 22:34:05 +0000879
880 if (NewOps.empty())
Dan Gohman246b2562007-10-22 18:31:58 +0000881 Val = SE->getIntegerSCEV(0, Val->getType());
Chris Lattner26d91f12005-08-04 22:34:05 +0000882 else
Dan Gohman246b2562007-10-22 18:31:58 +0000883 Val = SE->getAddExpr(NewOps);
Chris Lattner26d91f12005-08-04 22:34:05 +0000884 return;
Chris Lattner7a658392005-08-03 23:44:42 +0000885 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
886 // Try to pull immediates out of the start value of nested addrec's.
Chris Lattner26d91f12005-08-04 22:34:05 +0000887 SCEVHandle Start = SARE->getStart();
Evan Chengd9fb7122009-02-21 02:06:47 +0000888 MoveImmediateValues(TLI, UseTy, Start, Imm, isAddress, L, SE);
Chris Lattner26d91f12005-08-04 22:34:05 +0000889
890 if (Start != SARE->getStart()) {
891 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
892 Ops[0] = Start;
Dan Gohman246b2562007-10-22 18:31:58 +0000893 Val = SE->getAddRecExpr(Ops, SARE->getLoop());
Chris Lattner26d91f12005-08-04 22:34:05 +0000894 }
895 return;
Chris Lattner221fc3c2006-02-04 07:36:50 +0000896 } else if (SCEVMulExpr *SME = dyn_cast<SCEVMulExpr>(Val)) {
897 // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
Dale Johannesen203af582008-12-05 21:47:27 +0000898 if (isAddress && fitsInAddressMode(SME->getOperand(0), UseTy, TLI, false) &&
Chris Lattner221fc3c2006-02-04 07:36:50 +0000899 SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
900
Dan Gohman246b2562007-10-22 18:31:58 +0000901 SCEVHandle SubImm = SE->getIntegerSCEV(0, Val->getType());
Chris Lattner221fc3c2006-02-04 07:36:50 +0000902 SCEVHandle NewOp = SME->getOperand(1);
Evan Chengd9fb7122009-02-21 02:06:47 +0000903 MoveImmediateValues(TLI, UseTy, NewOp, SubImm, isAddress, L, SE);
Chris Lattner221fc3c2006-02-04 07:36:50 +0000904
905 // If we extracted something out of the subexpressions, see if we can
906 // simplify this!
907 if (NewOp != SME->getOperand(1)) {
908 // Scale SubImm up by "8". If the result is a target constant, we are
909 // good.
Dan Gohman246b2562007-10-22 18:31:58 +0000910 SubImm = SE->getMulExpr(SubImm, SME->getOperand(0));
Dale Johannesen203af582008-12-05 21:47:27 +0000911 if (fitsInAddressMode(SubImm, UseTy, TLI, false)) {
Chris Lattner221fc3c2006-02-04 07:36:50 +0000912 // Accumulate the immediate.
Dan Gohman246b2562007-10-22 18:31:58 +0000913 Imm = SE->getAddExpr(Imm, SubImm);
Chris Lattner221fc3c2006-02-04 07:36:50 +0000914
915 // Update what is left of 'Val'.
Dan Gohman246b2562007-10-22 18:31:58 +0000916 Val = SE->getMulExpr(SME->getOperand(0), NewOp);
Chris Lattner221fc3c2006-02-04 07:36:50 +0000917 return;
918 }
919 }
920 }
Nate Begeman16997482005-07-30 00:15:07 +0000921 }
922
Chris Lattner26d91f12005-08-04 22:34:05 +0000923 // Loop-variant expressions must stay in the immediate field of the
924 // expression.
Dale Johannesen203af582008-12-05 21:47:27 +0000925 if ((isAddress && fitsInAddressMode(Val, UseTy, TLI, false)) ||
Chris Lattner26d91f12005-08-04 22:34:05 +0000926 !Val->isLoopInvariant(L)) {
Dan Gohman246b2562007-10-22 18:31:58 +0000927 Imm = SE->getAddExpr(Imm, Val);
928 Val = SE->getIntegerSCEV(0, Val->getType());
Chris Lattner26d91f12005-08-04 22:34:05 +0000929 return;
Chris Lattner7a2ca562005-08-04 19:26:19 +0000930 }
Chris Lattner26d91f12005-08-04 22:34:05 +0000931
932 // Otherwise, no immediates to move.
Nate Begeman16997482005-07-30 00:15:07 +0000933}
934
Evan Chengd9fb7122009-02-21 02:06:47 +0000935static void MoveImmediateValues(const TargetLowering *TLI,
936 Instruction *User,
937 SCEVHandle &Val, SCEVHandle &Imm,
938 bool isAddress, Loop *L,
939 ScalarEvolution *SE) {
Dan Gohman21e77222009-03-09 21:01:17 +0000940 const Type *UseTy = getAccessType(User);
Evan Chengd9fb7122009-02-21 02:06:47 +0000941 MoveImmediateValues(TLI, UseTy, Val, Imm, isAddress, L, SE);
942}
Chris Lattner934520a2005-08-13 07:27:18 +0000943
Chris Lattner7e79b382006-08-03 06:34:50 +0000944/// SeparateSubExprs - Decompose Expr into all of the subexpressions that are
945/// added together. This is used to reassociate common addition subexprs
946/// together for maximal sharing when rewriting bases.
Chris Lattner934520a2005-08-13 07:27:18 +0000947static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
Dan Gohman246b2562007-10-22 18:31:58 +0000948 SCEVHandle Expr,
949 ScalarEvolution *SE) {
Chris Lattner934520a2005-08-13 07:27:18 +0000950 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
951 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
Dan Gohman246b2562007-10-22 18:31:58 +0000952 SeparateSubExprs(SubExprs, AE->getOperand(j), SE);
Chris Lattner934520a2005-08-13 07:27:18 +0000953 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
Dan Gohman246b2562007-10-22 18:31:58 +0000954 SCEVHandle Zero = SE->getIntegerSCEV(0, Expr->getType());
Chris Lattner934520a2005-08-13 07:27:18 +0000955 if (SARE->getOperand(0) == Zero) {
956 SubExprs.push_back(Expr);
957 } else {
958 // Compute the addrec with zero as its base.
959 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
960 Ops[0] = Zero; // Start with zero base.
Dan Gohman246b2562007-10-22 18:31:58 +0000961 SubExprs.push_back(SE->getAddRecExpr(Ops, SARE->getLoop()));
Chris Lattner934520a2005-08-13 07:27:18 +0000962
963
Dan Gohman246b2562007-10-22 18:31:58 +0000964 SeparateSubExprs(SubExprs, SARE->getOperand(0), SE);
Chris Lattner934520a2005-08-13 07:27:18 +0000965 }
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000966 } else if (!Expr->isZero()) {
Chris Lattner934520a2005-08-13 07:27:18 +0000967 // Do not add zero.
968 SubExprs.push_back(Expr);
969 }
970}
971
Dale Johannesen203af582008-12-05 21:47:27 +0000972// This is logically local to the following function, but C++ says we have
973// to make it file scope.
974struct SubExprUseData { unsigned Count; bool notAllUsesAreFree; };
Chris Lattner934520a2005-08-13 07:27:18 +0000975
Dale Johannesen203af582008-12-05 21:47:27 +0000976/// RemoveCommonExpressionsFromUseBases - Look through all of the Bases of all
977/// the Uses, removing any common subexpressions, except that if all such
978/// subexpressions can be folded into an addressing mode for all uses inside
979/// the loop (this case is referred to as "free" in comments herein) we do
980/// not remove anything. This looks for things like (a+b+c) and
Chris Lattnerf8828eb2008-12-02 04:52:26 +0000981/// (a+c+d) and computes the common (a+c) subexpression. The common expression
982/// is *removed* from the Bases and returned.
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000983static SCEVHandle
Dan Gohman246b2562007-10-22 18:31:58 +0000984RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses,
Dale Johannesen203af582008-12-05 21:47:27 +0000985 ScalarEvolution *SE, Loop *L,
986 const TargetLowering *TLI) {
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000987 unsigned NumUses = Uses.size();
988
Chris Lattnerf8828eb2008-12-02 04:52:26 +0000989 // Only one use? This is a very common case, so we handle it specially and
990 // cheaply.
Dan Gohman246b2562007-10-22 18:31:58 +0000991 SCEVHandle Zero = SE->getIntegerSCEV(0, Uses[0].Base->getType());
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000992 SCEVHandle Result = Zero;
Dale Johannesen203af582008-12-05 21:47:27 +0000993 SCEVHandle FreeResult = Zero;
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000994 if (NumUses == 1) {
Chris Lattnerf8828eb2008-12-02 04:52:26 +0000995 // If the use is inside the loop, use its base, regardless of what it is:
996 // it is clearly shared across all the IV's. If the use is outside the loop
997 // (which means after it) we don't want to factor anything *into* the loop,
998 // so just use 0 as the base.
Dale Johannesen589bf082008-12-01 22:00:01 +0000999 if (L->contains(Uses[0].Inst->getParent()))
1000 std::swap(Result, Uses[0].Base);
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001001 return Result;
1002 }
1003
1004 // To find common subexpressions, count how many of Uses use each expression.
1005 // If any subexpressions are used Uses.size() times, they are common.
Dale Johannesen203af582008-12-05 21:47:27 +00001006 // Also track whether all uses of each expression can be moved into an
1007 // an addressing mode "for free"; such expressions are left within the loop.
1008 // struct SubExprUseData { unsigned Count; bool notAllUsesAreFree; };
1009 std::map<SCEVHandle, SubExprUseData> SubExpressionUseData;
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001010
Chris Lattnerd6155e92005-10-11 18:41:04 +00001011 // UniqueSubExprs - Keep track of all of the subexpressions we see in the
1012 // order we see them.
1013 std::vector<SCEVHandle> UniqueSubExprs;
1014
Chris Lattner934520a2005-08-13 07:27:18 +00001015 std::vector<SCEVHandle> SubExprs;
Chris Lattnerf8828eb2008-12-02 04:52:26 +00001016 unsigned NumUsesInsideLoop = 0;
Chris Lattner934520a2005-08-13 07:27:18 +00001017 for (unsigned i = 0; i != NumUses; ++i) {
Chris Lattnerf8828eb2008-12-02 04:52:26 +00001018 // If the user is outside the loop, just ignore it for base computation.
1019 // Since the user is outside the loop, it must be *after* the loop (if it
1020 // were before, it could not be based on the loop IV). We don't want users
1021 // after the loop to affect base computation of values *inside* the loop,
1022 // because we can always add their offsets to the result IV after the loop
1023 // is done, ensuring we get good code inside the loop.
Dale Johannesen589bf082008-12-01 22:00:01 +00001024 if (!L->contains(Uses[i].Inst->getParent()))
1025 continue;
1026 NumUsesInsideLoop++;
1027
Chris Lattner934520a2005-08-13 07:27:18 +00001028 // If the base is zero (which is common), return zero now, there are no
1029 // CSEs we can find.
1030 if (Uses[i].Base == Zero) return Zero;
1031
Dale Johannesen203af582008-12-05 21:47:27 +00001032 // If this use is as an address we may be able to put CSEs in the addressing
1033 // mode rather than hoisting them.
1034 bool isAddrUse = isAddressUse(Uses[i].Inst, Uses[i].OperandValToReplace);
1035 // We may need the UseTy below, but only when isAddrUse, so compute it
1036 // only in that case.
1037 const Type *UseTy = 0;
Dan Gohman21e77222009-03-09 21:01:17 +00001038 if (isAddrUse)
1039 UseTy = getAccessType(Uses[i].Inst);
Dale Johannesen203af582008-12-05 21:47:27 +00001040
Chris Lattner934520a2005-08-13 07:27:18 +00001041 // Split the expression into subexprs.
Dan Gohman246b2562007-10-22 18:31:58 +00001042 SeparateSubExprs(SubExprs, Uses[i].Base, SE);
Dale Johannesen203af582008-12-05 21:47:27 +00001043 // Add one to SubExpressionUseData.Count for each subexpr present, and
1044 // if the subexpr is not a valid immediate within an addressing mode use,
1045 // set SubExpressionUseData.notAllUsesAreFree. We definitely want to
1046 // hoist these out of the loop (if they are common to all uses).
1047 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j) {
1048 if (++SubExpressionUseData[SubExprs[j]].Count == 1)
Chris Lattnerd6155e92005-10-11 18:41:04 +00001049 UniqueSubExprs.push_back(SubExprs[j]);
Dale Johannesen203af582008-12-05 21:47:27 +00001050 if (!isAddrUse || !fitsInAddressMode(SubExprs[j], UseTy, TLI, false))
1051 SubExpressionUseData[SubExprs[j]].notAllUsesAreFree = true;
1052 }
Chris Lattner934520a2005-08-13 07:27:18 +00001053 SubExprs.clear();
1054 }
1055
Chris Lattnerd6155e92005-10-11 18:41:04 +00001056 // Now that we know how many times each is used, build Result. Iterate over
1057 // UniqueSubexprs so that we have a stable ordering.
1058 for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
Dale Johannesen203af582008-12-05 21:47:27 +00001059 std::map<SCEVHandle, SubExprUseData>::iterator I =
1060 SubExpressionUseData.find(UniqueSubExprs[i]);
1061 assert(I != SubExpressionUseData.end() && "Entry not found?");
1062 if (I->second.Count == NumUsesInsideLoop) { // Found CSE!
1063 if (I->second.notAllUsesAreFree)
1064 Result = SE->getAddExpr(Result, I->first);
1065 else
1066 FreeResult = SE->getAddExpr(FreeResult, I->first);
1067 } else
1068 // Remove non-cse's from SubExpressionUseData.
1069 SubExpressionUseData.erase(I);
Chris Lattnerd6155e92005-10-11 18:41:04 +00001070 }
Dale Johannesen203af582008-12-05 21:47:27 +00001071
1072 if (FreeResult != Zero) {
1073 // We have some subexpressions that can be subsumed into addressing
1074 // modes in every use inside the loop. However, it's possible that
1075 // there are so many of them that the combined FreeResult cannot
1076 // be subsumed, or that the target cannot handle both a FreeResult
1077 // and a Result in the same instruction (for example because it would
1078 // require too many registers). Check this.
1079 for (unsigned i=0; i<NumUses; ++i) {
1080 if (!L->contains(Uses[i].Inst->getParent()))
1081 continue;
1082 // We know this is an addressing mode use; if there are any uses that
1083 // are not, FreeResult would be Zero.
Dan Gohman21e77222009-03-09 21:01:17 +00001084 const Type *UseTy = getAccessType(Uses[i].Inst);
Dale Johannesen203af582008-12-05 21:47:27 +00001085 if (!fitsInAddressMode(FreeResult, UseTy, TLI, Result!=Zero)) {
1086 // FIXME: could split up FreeResult into pieces here, some hoisted
Dale Johannesenb0390622008-12-16 22:16:28 +00001087 // and some not. There is no obvious advantage to this.
Dale Johannesen203af582008-12-05 21:47:27 +00001088 Result = SE->getAddExpr(Result, FreeResult);
1089 FreeResult = Zero;
1090 break;
1091 }
1092 }
1093 }
1094
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001095 // If we found no CSE's, return now.
1096 if (Result == Zero) return Result;
1097
Dale Johannesen203af582008-12-05 21:47:27 +00001098 // If we still have a FreeResult, remove its subexpressions from
1099 // SubExpressionUseData. This means they will remain in the use Bases.
1100 if (FreeResult != Zero) {
1101 SeparateSubExprs(SubExprs, FreeResult, SE);
1102 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j) {
1103 std::map<SCEVHandle, SubExprUseData>::iterator I =
1104 SubExpressionUseData.find(SubExprs[j]);
1105 SubExpressionUseData.erase(I);
1106 }
1107 SubExprs.clear();
1108 }
1109
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001110 // Otherwise, remove all of the CSE's we found from each of the base values.
Chris Lattner934520a2005-08-13 07:27:18 +00001111 for (unsigned i = 0; i != NumUses; ++i) {
Dale Johannesenfb10cd42008-12-02 21:17:11 +00001112 // Uses outside the loop don't necessarily include the common base, but
1113 // the final IV value coming into those uses does. Instead of trying to
1114 // remove the pieces of the common base, which might not be there,
1115 // subtract off the base to compensate for this.
1116 if (!L->contains(Uses[i].Inst->getParent())) {
1117 Uses[i].Base = SE->getMinusSCEV(Uses[i].Base, Result);
Dale Johannesen589bf082008-12-01 22:00:01 +00001118 continue;
Dale Johannesenfb10cd42008-12-02 21:17:11 +00001119 }
Dale Johannesen589bf082008-12-01 22:00:01 +00001120
Chris Lattner934520a2005-08-13 07:27:18 +00001121 // Split the expression into subexprs.
Dan Gohman246b2562007-10-22 18:31:58 +00001122 SeparateSubExprs(SubExprs, Uses[i].Base, SE);
Chris Lattner934520a2005-08-13 07:27:18 +00001123
1124 // Remove any common subexpressions.
1125 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
Dale Johannesen203af582008-12-05 21:47:27 +00001126 if (SubExpressionUseData.count(SubExprs[j])) {
Chris Lattner934520a2005-08-13 07:27:18 +00001127 SubExprs.erase(SubExprs.begin()+j);
1128 --j; --e;
1129 }
1130
Chris Lattnerf8828eb2008-12-02 04:52:26 +00001131 // Finally, add the non-shared expressions together.
Chris Lattner934520a2005-08-13 07:27:18 +00001132 if (SubExprs.empty())
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001133 Uses[i].Base = Zero;
Chris Lattner934520a2005-08-13 07:27:18 +00001134 else
Dan Gohman246b2562007-10-22 18:31:58 +00001135 Uses[i].Base = SE->getAddExpr(SubExprs);
Chris Lattner27e51422005-08-13 07:42:01 +00001136 SubExprs.clear();
Chris Lattner934520a2005-08-13 07:27:18 +00001137 }
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001138
1139 return Result;
1140}
1141
Dale Johannesendc42f482007-03-20 00:47:50 +00001142/// ValidStride - Check whether the given Scale is valid for all loads and
Chris Lattner579633c2007-04-09 22:20:14 +00001143/// stores in UsersToProcess.
Dale Johannesendc42f482007-03-20 00:47:50 +00001144///
Dan Gohman02e4fa72007-10-22 20:40:42 +00001145bool LoopStrengthReduce::ValidStride(bool HasBaseReg,
1146 int64_t Scale,
Dale Johannesendc42f482007-03-20 00:47:50 +00001147 const std::vector<BasedUser>& UsersToProcess) {
Evan Chengd6b62a52007-12-19 23:33:23 +00001148 if (!TLI)
1149 return true;
1150
Dale Johannesen8e59e162007-03-20 21:54:54 +00001151 for (unsigned i=0, e = UsersToProcess.size(); i!=e; ++i) {
Chris Lattner1ebd89e2007-04-02 06:34:44 +00001152 // If this is a load or other access, pass the type of the access in.
1153 const Type *AccessTy = Type::VoidTy;
Dan Gohman21e77222009-03-09 21:01:17 +00001154 if (isAddressUse(UsersToProcess[i].Inst,
1155 UsersToProcess[i].OperandValToReplace))
1156 AccessTy = getAccessType(UsersToProcess[i].Inst);
Evan Cheng55e641b2008-03-19 22:02:26 +00001157 else if (isa<PHINode>(UsersToProcess[i].Inst))
1158 continue;
Chris Lattner1ebd89e2007-04-02 06:34:44 +00001159
Chris Lattner579633c2007-04-09 22:20:14 +00001160 TargetLowering::AddrMode AM;
1161 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(UsersToProcess[i].Imm))
1162 AM.BaseOffs = SC->getValue()->getSExtValue();
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001163 AM.HasBaseReg = HasBaseReg || !UsersToProcess[i].Base->isZero();
Chris Lattner579633c2007-04-09 22:20:14 +00001164 AM.Scale = Scale;
1165
1166 // If load[imm+r*scale] is illegal, bail out.
Evan Chengd6b62a52007-12-19 23:33:23 +00001167 if (!TLI->isLegalAddressingMode(AM, AccessTy))
Dale Johannesendc42f482007-03-20 00:47:50 +00001168 return false;
Dale Johannesen8e59e162007-03-20 21:54:54 +00001169 }
Dale Johannesendc42f482007-03-20 00:47:50 +00001170 return true;
1171}
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001172
Dale Johannesen1de17d52009-02-09 22:14:15 +00001173/// RequiresTypeConversion - Returns true if converting Ty1 to Ty2 is not
Evan Cheng5f8ebaa2007-10-25 22:45:20 +00001174/// a nop.
Evan Cheng2bd122c2007-10-26 01:56:11 +00001175bool LoopStrengthReduce::RequiresTypeConversion(const Type *Ty1,
1176 const Type *Ty2) {
1177 if (Ty1 == Ty2)
Evan Cheng5f8ebaa2007-10-25 22:45:20 +00001178 return false;
Dale Johannesen1de17d52009-02-09 22:14:15 +00001179 if (Ty1->canLosslesslyBitCastTo(Ty2))
1180 return false;
Evan Cheng2bd122c2007-10-26 01:56:11 +00001181 if (TLI && TLI->isTruncateFree(Ty1, Ty2))
1182 return false;
Dale Johannesen1de17d52009-02-09 22:14:15 +00001183 if (isa<PointerType>(Ty2) && Ty1->canLosslesslyBitCastTo(UIntPtrTy))
1184 return false;
1185 if (isa<PointerType>(Ty1) && Ty2->canLosslesslyBitCastTo(UIntPtrTy))
1186 return false;
1187 return true;
Evan Cheng5f8ebaa2007-10-25 22:45:20 +00001188}
1189
Evan Chengeb8f9e22006-03-17 19:52:23 +00001190/// CheckForIVReuse - Returns the multiple if the stride is the multiple
1191/// of a previous stride and it is a legal value for the target addressing
Dan Gohman02e4fa72007-10-22 20:40:42 +00001192/// mode scale component and optional base reg. This allows the users of
1193/// this stride to be rewritten as prev iv * factor. It returns 0 if no
Dale Johannesenb0390622008-12-16 22:16:28 +00001194/// reuse is possible. Factors can be negative on same targets, e.g. ARM.
Dale Johannesen2f46bb82009-01-14 02:35:31 +00001195///
1196/// If all uses are outside the loop, we don't require that all multiplies
1197/// be folded into the addressing mode, nor even that the factor be constant;
1198/// a multiply (executed once) outside the loop is better than another IV
1199/// within. Well, usually.
1200SCEVHandle LoopStrengthReduce::CheckForIVReuse(bool HasBaseReg,
Evan Cheng2bd122c2007-10-26 01:56:11 +00001201 bool AllUsesAreAddresses,
Dale Johannesenb0390622008-12-16 22:16:28 +00001202 bool AllUsesAreOutsideLoop,
Dan Gohman02e4fa72007-10-22 20:40:42 +00001203 const SCEVHandle &Stride,
Dale Johannesendc42f482007-03-20 00:47:50 +00001204 IVExpr &IV, const Type *Ty,
1205 const std::vector<BasedUser>& UsersToProcess) {
Evan Chengeb8f9e22006-03-17 19:52:23 +00001206 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride)) {
Reid Spencer502db932007-03-02 23:37:53 +00001207 int64_t SInt = SC->getValue()->getSExtValue();
Dale Johannesenb51b4b52007-11-17 02:48:01 +00001208 for (unsigned NewStride = 0, e = StrideOrder.size(); NewStride != e;
1209 ++NewStride) {
1210 std::map<SCEVHandle, IVsOfOneStride>::iterator SI =
1211 IVsByStride.find(StrideOrder[NewStride]);
Dale Johannesen2f46bb82009-01-14 02:35:31 +00001212 if (SI == IVsByStride.end() || !isa<SCEVConstant>(SI->first))
Dale Johannesenb51b4b52007-11-17 02:48:01 +00001213 continue;
Evan Cheng5eef2d22007-03-12 23:27:37 +00001214 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
Evan Cheng2bd122c2007-10-26 01:56:11 +00001215 if (SI->first != Stride &&
Chris Lattner1d312902007-04-02 22:51:58 +00001216 (unsigned(abs(SInt)) < SSInt || (SInt % SSInt) != 0))
Evan Chengeb8f9e22006-03-17 19:52:23 +00001217 continue;
Evan Cheng5eef2d22007-03-12 23:27:37 +00001218 int64_t Scale = SInt / SSInt;
Dale Johannesendc42f482007-03-20 00:47:50 +00001219 // Check that this stride is valid for all the types used for loads and
1220 // stores; if it can be used for some and not others, we might as well use
1221 // the original stride everywhere, since we have to create the IV for it
Dan Gohmanaa343312007-10-29 19:23:53 +00001222 // anyway. If the scale is 1, then we don't need to worry about folding
1223 // multiplications.
1224 if (Scale == 1 ||
1225 (AllUsesAreAddresses &&
1226 ValidStride(HasBaseReg, Scale, UsersToProcess)))
Evan Cheng5eef2d22007-03-12 23:27:37 +00001227 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1228 IE = SI->second.IVs.end(); II != IE; ++II)
1229 // FIXME: Only handle base == 0 for now.
1230 // Only reuse previous IV if it would not require a type conversion.
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001231 if (II->Base->isZero() &&
Evan Cheng2bd122c2007-10-26 01:56:11 +00001232 !RequiresTypeConversion(II->Base->getType(), Ty)) {
Evan Cheng5eef2d22007-03-12 23:27:37 +00001233 IV = *II;
Dale Johannesen2f46bb82009-01-14 02:35:31 +00001234 return SE->getIntegerSCEV(Scale, Stride->getType());
Evan Cheng5eef2d22007-03-12 23:27:37 +00001235 }
Evan Chengeb8f9e22006-03-17 19:52:23 +00001236 }
Dale Johannesen2f46bb82009-01-14 02:35:31 +00001237 } else if (AllUsesAreOutsideLoop) {
1238 // Accept nonconstant strides here; it is really really right to substitute
1239 // an existing IV if we can.
1240 for (unsigned NewStride = 0, e = StrideOrder.size(); NewStride != e;
1241 ++NewStride) {
1242 std::map<SCEVHandle, IVsOfOneStride>::iterator SI =
1243 IVsByStride.find(StrideOrder[NewStride]);
1244 if (SI == IVsByStride.end() || !isa<SCEVConstant>(SI->first))
1245 continue;
1246 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
1247 if (SI->first != Stride && SSInt != 1)
1248 continue;
1249 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1250 IE = SI->second.IVs.end(); II != IE; ++II)
1251 // Accept nonzero base here.
1252 // Only reuse previous IV if it would not require a type conversion.
1253 if (!RequiresTypeConversion(II->Base->getType(), Ty)) {
1254 IV = *II;
1255 return Stride;
1256 }
1257 }
1258 // Special case, old IV is -1*x and this one is x. Can treat this one as
1259 // -1*old.
1260 for (unsigned NewStride = 0, e = StrideOrder.size(); NewStride != e;
1261 ++NewStride) {
1262 std::map<SCEVHandle, IVsOfOneStride>::iterator SI =
1263 IVsByStride.find(StrideOrder[NewStride]);
1264 if (SI == IVsByStride.end())
1265 continue;
1266 if (SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(SI->first))
1267 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(ME->getOperand(0)))
1268 if (Stride == ME->getOperand(1) &&
1269 SC->getValue()->getSExtValue() == -1LL)
1270 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1271 IE = SI->second.IVs.end(); II != IE; ++II)
1272 // Accept nonzero base here.
1273 // Only reuse previous IV if it would not require type conversion.
1274 if (!RequiresTypeConversion(II->Base->getType(), Ty)) {
1275 IV = *II;
1276 return SE->getIntegerSCEV(-1LL, Stride->getType());
1277 }
1278 }
Evan Chengeb8f9e22006-03-17 19:52:23 +00001279 }
Dale Johannesen2f46bb82009-01-14 02:35:31 +00001280 return SE->getIntegerSCEV(0, Stride->getType());
Evan Chengeb8f9e22006-03-17 19:52:23 +00001281}
1282
Chris Lattner7e79b382006-08-03 06:34:50 +00001283/// PartitionByIsUseOfPostIncrementedValue - Simple boolean predicate that
1284/// returns true if Val's isUseOfPostIncrementedValue is true.
1285static bool PartitionByIsUseOfPostIncrementedValue(const BasedUser &Val) {
1286 return Val.isUseOfPostIncrementedValue;
1287}
Evan Chengeb8f9e22006-03-17 19:52:23 +00001288
Dan Gohman4a9a3e52008-04-14 18:26:16 +00001289/// isNonConstantNegative - Return true if the specified scev is negated, but
Chris Lattnerfb3e1192007-05-19 01:22:21 +00001290/// not a constant.
1291static bool isNonConstantNegative(const SCEVHandle &Expr) {
1292 SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Expr);
1293 if (!Mul) return false;
1294
1295 // If there is a constant factor, it will be first.
1296 SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
1297 if (!SC) return false;
1298
1299 // Return true if the value is negative, this matches things like (-42 * V).
1300 return SC->getValue()->getValue().isNegative();
1301}
1302
Evan Cheng5f8ebaa2007-10-25 22:45:20 +00001303// CollectIVUsers - Transform our list of users and offsets to a bit more
Dan Gohman73b43b92008-06-23 22:11:52 +00001304// complex table. In this new vector, each 'BasedUser' contains 'Base', the base
1305// of the strided accesses, as well as the old information from Uses. We
Evan Cheng5f8ebaa2007-10-25 22:45:20 +00001306// progressively move information from the Base field to the Imm field, until
1307// we eventually have the full access expression to rewrite the use.
1308SCEVHandle LoopStrengthReduce::CollectIVUsers(const SCEVHandle &Stride,
1309 IVUsersOfOneStride &Uses,
1310 Loop *L,
1311 bool &AllUsesAreAddresses,
Dale Johannesenb0390622008-12-16 22:16:28 +00001312 bool &AllUsesAreOutsideLoop,
Evan Cheng5f8ebaa2007-10-25 22:45:20 +00001313 std::vector<BasedUser> &UsersToProcess) {
Nate Begeman16997482005-07-30 00:15:07 +00001314 UsersToProcess.reserve(Uses.Users.size());
Chris Lattnera553b0c2005-08-08 22:56:21 +00001315 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +00001316 UsersToProcess.push_back(BasedUser(Uses.Users[i], SE));
Chris Lattnera553b0c2005-08-08 22:56:21 +00001317
Dale Johannesen67c79892008-12-03 19:25:46 +00001318 // Move any loop variant operands from the offset field to the immediate
Chris Lattnera553b0c2005-08-08 22:56:21 +00001319 // field of the use, so that we don't try to use something before it is
1320 // computed.
Dale Johannesen544e0d02008-12-03 20:56:12 +00001321 MoveLoopVariantsToImmediateField(UsersToProcess.back().Base,
Dan Gohman246b2562007-10-22 18:31:58 +00001322 UsersToProcess.back().Imm, L, SE);
Chris Lattnera553b0c2005-08-08 22:56:21 +00001323 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
Chris Lattner26d91f12005-08-04 22:34:05 +00001324 "Base value is not loop invariant!");
Nate Begeman16997482005-07-30 00:15:07 +00001325 }
Evan Chengeb8f9e22006-03-17 19:52:23 +00001326
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001327 // We now have a whole bunch of uses of like-strided induction variables, but
1328 // they might all have different bases. We want to emit one PHI node for this
1329 // stride which we fold as many common expressions (between the IVs) into as
1330 // possible. Start by identifying the common expressions in the base values
1331 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
1332 // "A+B"), emit it to the preheader, then remove the expression from the
1333 // UsersToProcess base values.
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001334 SCEVHandle CommonExprs =
Dale Johannesen203af582008-12-05 21:47:27 +00001335 RemoveCommonExpressionsFromUseBases(UsersToProcess, SE, L, TLI);
Dan Gohman02e4fa72007-10-22 20:40:42 +00001336
Chris Lattner44b807e2005-08-08 22:32:34 +00001337 // Next, figure out what we can represent in the immediate fields of
1338 // instructions. If we can represent anything there, move it to the imm
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001339 // fields of the BasedUsers. We do this so that it increases the commonality
1340 // of the remaining uses.
Evan Cheng32e4c7c2007-12-20 02:20:53 +00001341 unsigned NumPHI = 0;
Evan Chengd33cec12009-02-20 22:16:49 +00001342 bool HasAddress = false;
Chris Lattner44b807e2005-08-08 22:32:34 +00001343 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
Chris Lattner80b32b32005-08-16 00:38:11 +00001344 // If the user is not in the current loop, this means it is using the exit
1345 // value of the IV. Do not put anything in the base, make sure it's all in
1346 // the immediate field to allow as much factoring as possible.
1347 if (!L->contains(UsersToProcess[i].Inst->getParent())) {
Dan Gohman246b2562007-10-22 18:31:58 +00001348 UsersToProcess[i].Imm = SE->getAddExpr(UsersToProcess[i].Imm,
1349 UsersToProcess[i].Base);
Chris Lattner8385e512005-08-17 21:22:41 +00001350 UsersToProcess[i].Base =
Dan Gohman246b2562007-10-22 18:31:58 +00001351 SE->getIntegerSCEV(0, UsersToProcess[i].Base->getType());
Chris Lattner80b32b32005-08-16 00:38:11 +00001352 } else {
Evan Chengd9fb7122009-02-21 02:06:47 +00001353 // Not all uses are outside the loop.
1354 AllUsesAreOutsideLoop = false;
1355
Chris Lattner80b32b32005-08-16 00:38:11 +00001356 // Addressing modes can be folded into loads and stores. Be careful that
1357 // the store is through the expression, not of the expression though.
Evan Cheng32e4c7c2007-12-20 02:20:53 +00001358 bool isPHI = false;
Evan Chengd6b62a52007-12-19 23:33:23 +00001359 bool isAddress = isAddressUse(UsersToProcess[i].Inst,
1360 UsersToProcess[i].OperandValToReplace);
1361 if (isa<PHINode>(UsersToProcess[i].Inst)) {
Evan Cheng32e4c7c2007-12-20 02:20:53 +00001362 isPHI = true;
1363 ++NumPHI;
Dan Gohman2acc7602007-05-03 23:20:33 +00001364 }
Dan Gohman02e4fa72007-10-22 20:40:42 +00001365
Evan Chengd33cec12009-02-20 22:16:49 +00001366 if (isAddress)
1367 HasAddress = true;
Dale Johannesenb0390622008-12-16 22:16:28 +00001368
Dan Gohman02e4fa72007-10-22 20:40:42 +00001369 // If this use isn't an address, then not all uses are addresses.
Evan Cheng55e641b2008-03-19 22:02:26 +00001370 if (!isAddress && !isPHI)
Dan Gohman02e4fa72007-10-22 20:40:42 +00001371 AllUsesAreAddresses = false;
Chris Lattner80b32b32005-08-16 00:38:11 +00001372
Evan Cheng1d958162007-03-13 20:34:37 +00001373 MoveImmediateValues(TLI, UsersToProcess[i].Inst, UsersToProcess[i].Base,
Dan Gohman246b2562007-10-22 18:31:58 +00001374 UsersToProcess[i].Imm, isAddress, L, SE);
Chris Lattner80b32b32005-08-16 00:38:11 +00001375 }
Chris Lattner44b807e2005-08-08 22:32:34 +00001376 }
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001377
Evan Chengd9fb7122009-02-21 02:06:47 +00001378 // If one of the use is a PHI node and all other uses are addresses, still
Evan Cheng32e4c7c2007-12-20 02:20:53 +00001379 // allow iv reuse. Essentially we are trading one constant multiplication
1380 // for one fewer iv.
1381 if (NumPHI > 1)
1382 AllUsesAreAddresses = false;
Evan Chengd9fb7122009-02-21 02:06:47 +00001383
Evan Chengd33cec12009-02-20 22:16:49 +00001384 // There are no in-loop address uses.
1385 if (AllUsesAreAddresses && (!HasAddress && !AllUsesAreOutsideLoop))
1386 AllUsesAreAddresses = false;
1387
Evan Cheng5f8ebaa2007-10-25 22:45:20 +00001388 return CommonExprs;
1389}
1390
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001391/// ShouldUseFullStrengthReductionMode - Test whether full strength-reduction
1392/// is valid and profitable for the given set of users of a stride. In
1393/// full strength-reduction mode, all addresses at the current stride are
1394/// strength-reduced all the way down to pointer arithmetic.
1395///
1396bool LoopStrengthReduce::ShouldUseFullStrengthReductionMode(
1397 const std::vector<BasedUser> &UsersToProcess,
1398 const Loop *L,
1399 bool AllUsesAreAddresses,
1400 SCEVHandle Stride) {
1401 if (!EnableFullLSRMode)
1402 return false;
1403
1404 // The heuristics below aim to avoid increasing register pressure, but
1405 // fully strength-reducing all the addresses increases the number of
1406 // add instructions, so don't do this when optimizing for size.
1407 // TODO: If the loop is large, the savings due to simpler addresses
1408 // may oughtweight the costs of the extra increment instructions.
1409 if (L->getHeader()->getParent()->hasFnAttr(Attribute::OptimizeForSize))
1410 return false;
1411
1412 // TODO: For now, don't do full strength reduction if there could
1413 // potentially be greater-stride multiples of the current stride
1414 // which could reuse the current stride IV.
1415 if (StrideOrder.back() != Stride)
1416 return false;
1417
1418 // Iterate through the uses to find conditions that automatically rule out
1419 // full-lsr mode.
1420 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ) {
1421 SCEV *Base = UsersToProcess[i].Base;
1422 SCEV *Imm = UsersToProcess[i].Imm;
1423 // If any users have a loop-variant component, they can't be fully
1424 // strength-reduced.
1425 if (Imm && !Imm->isLoopInvariant(L))
1426 return false;
1427 // If there are to users with the same base and the difference between
1428 // the two Imm values can't be folded into the address, full
1429 // strength reduction would increase register pressure.
1430 do {
1431 SCEV *CurImm = UsersToProcess[i].Imm;
Dan Gohmana04af432009-02-22 16:40:52 +00001432 if ((CurImm || Imm) && CurImm != Imm) {
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001433 if (!CurImm) CurImm = SE->getIntegerSCEV(0, Stride->getType());
1434 if (!Imm) Imm = SE->getIntegerSCEV(0, Stride->getType());
1435 const Instruction *Inst = UsersToProcess[i].Inst;
Dan Gohman21e77222009-03-09 21:01:17 +00001436 const Type *UseTy = getAccessType(Inst);
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001437 SCEVHandle Diff = SE->getMinusSCEV(UsersToProcess[i].Imm, Imm);
1438 if (!Diff->isZero() &&
1439 (!AllUsesAreAddresses ||
1440 !fitsInAddressMode(Diff, UseTy, TLI, /*HasBaseReg=*/true)))
1441 return false;
1442 }
1443 } while (++i != e && Base == UsersToProcess[i].Base);
1444 }
1445
1446 // If there's exactly one user in this stride, fully strength-reducing it
1447 // won't increase register pressure. If it's starting from a non-zero base,
1448 // it'll be simpler this way.
1449 if (UsersToProcess.size() == 1 && !UsersToProcess[0].Base->isZero())
1450 return true;
1451
1452 // Otherwise, if there are any users in this stride that don't require
1453 // a register for their base, full strength-reduction will increase
1454 // register pressure.
1455 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
Dan Gohmanf0baa6e2009-02-20 21:05:23 +00001456 if (UsersToProcess[i].Base->isZero())
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001457 return false;
1458
1459 // Otherwise, go for it.
1460 return true;
1461}
1462
1463/// InsertAffinePhi Create and insert a PHI node for an induction variable
1464/// with the specified start and step values in the specified loop.
1465///
1466/// If NegateStride is true, the stride should be negated by using a
1467/// subtract instead of an add.
1468///
Dan Gohman9d100862009-03-09 22:04:01 +00001469/// Return the created phi node.
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001470///
1471static PHINode *InsertAffinePhi(SCEVHandle Start, SCEVHandle Step,
1472 const Loop *L,
Dan Gohman2d1be872009-04-16 03:18:22 +00001473 const TargetData *TD,
Dan Gohman9d100862009-03-09 22:04:01 +00001474 SCEVExpander &Rewriter) {
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001475 assert(Start->isLoopInvariant(L) && "New PHI start is not loop invariant!");
1476 assert(Step->isLoopInvariant(L) && "New PHI stride is not loop invariant!");
1477
1478 BasicBlock *Header = L->getHeader();
1479 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohman0daeed22009-03-09 21:14:16 +00001480 BasicBlock *LatchBlock = L->getLoopLatch();
Dan Gohman2d1be872009-04-16 03:18:22 +00001481 const Type *Ty = Start->getType();
1482 if (isa<PointerType>(Ty)) Ty = TD->getIntPtrType();
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001483
Dan Gohman2d1be872009-04-16 03:18:22 +00001484 PHINode *PN = PHINode::Create(Ty, "lsr.iv", Header->begin());
1485 PN->addIncoming(Rewriter.expandCodeFor(Start, Ty, Preheader->getTerminator()),
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001486 Preheader);
1487
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001488 // If the stride is negative, insert a sub instead of an add for the
1489 // increment.
1490 bool isNegative = isNonConstantNegative(Step);
1491 SCEVHandle IncAmount = Step;
1492 if (isNegative)
1493 IncAmount = Rewriter.SE.getNegativeSCEV(Step);
1494
1495 // Insert an add instruction right before the terminator corresponding
1496 // to the back-edge.
Dan Gohman2d1be872009-04-16 03:18:22 +00001497 Value *StepV = Rewriter.expandCodeFor(IncAmount, Ty,
1498 Preheader->getTerminator());
Dan Gohman9d100862009-03-09 22:04:01 +00001499 Instruction *IncV;
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001500 if (isNegative) {
1501 IncV = BinaryOperator::CreateSub(PN, StepV, "lsr.iv.next",
Dan Gohman0daeed22009-03-09 21:14:16 +00001502 LatchBlock->getTerminator());
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001503 } else {
1504 IncV = BinaryOperator::CreateAdd(PN, StepV, "lsr.iv.next",
Dan Gohman0daeed22009-03-09 21:14:16 +00001505 LatchBlock->getTerminator());
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001506 }
1507 if (!isa<ConstantInt>(StepV)) ++NumVariable;
1508
Dan Gohman0daeed22009-03-09 21:14:16 +00001509 PN->addIncoming(IncV, LatchBlock);
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001510
1511 ++NumInserted;
1512 return PN;
1513}
1514
1515static void SortUsersToProcess(std::vector<BasedUser> &UsersToProcess) {
1516 // We want to emit code for users inside the loop first. To do this, we
1517 // rearrange BasedUser so that the entries at the end have
1518 // isUseOfPostIncrementedValue = false, because we pop off the end of the
1519 // vector (so we handle them first).
1520 std::partition(UsersToProcess.begin(), UsersToProcess.end(),
1521 PartitionByIsUseOfPostIncrementedValue);
1522
1523 // Sort this by base, so that things with the same base are handled
1524 // together. By partitioning first and stable-sorting later, we are
1525 // guaranteed that within each base we will pop off users from within the
1526 // loop before users outside of the loop with a particular base.
1527 //
1528 // We would like to use stable_sort here, but we can't. The problem is that
1529 // SCEVHandle's don't have a deterministic ordering w.r.t to each other, so
1530 // we don't have anything to do a '<' comparison on. Because we think the
1531 // number of uses is small, do a horrible bubble sort which just relies on
1532 // ==.
1533 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1534 // Get a base value.
1535 SCEVHandle Base = UsersToProcess[i].Base;
1536
1537 // Compact everything with this base to be consecutive with this one.
1538 for (unsigned j = i+1; j != e; ++j) {
1539 if (UsersToProcess[j].Base == Base) {
1540 std::swap(UsersToProcess[i+1], UsersToProcess[j]);
1541 ++i;
1542 }
1543 }
1544 }
1545}
1546
Dan Gohman6b38e292009-02-20 21:06:57 +00001547/// PrepareToStrengthReduceFully - Prepare to fully strength-reduce
1548/// UsersToProcess, meaning lowering addresses all the way down to direct
1549/// pointer arithmetic.
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001550///
1551void
1552LoopStrengthReduce::PrepareToStrengthReduceFully(
1553 std::vector<BasedUser> &UsersToProcess,
1554 SCEVHandle Stride,
1555 SCEVHandle CommonExprs,
1556 const Loop *L,
1557 SCEVExpander &PreheaderRewriter) {
1558 DOUT << " Fully reducing all users\n";
1559
1560 // Rewrite the UsersToProcess records, creating a separate PHI for each
1561 // unique Base value.
1562 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ) {
1563 // TODO: The uses are grouped by base, but not sorted. We arbitrarily
1564 // pick the first Imm value here to start with, and adjust it for the
1565 // other uses.
1566 SCEVHandle Imm = UsersToProcess[i].Imm;
1567 SCEVHandle Base = UsersToProcess[i].Base;
1568 SCEVHandle Start = SE->getAddExpr(CommonExprs, Base, Imm);
Dan Gohman2d1be872009-04-16 03:18:22 +00001569 PHINode *Phi = InsertAffinePhi(Start, Stride, L, TD,
Dan Gohman9d100862009-03-09 22:04:01 +00001570 PreheaderRewriter);
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001571 // Loop over all the users with the same base.
1572 do {
1573 UsersToProcess[i].Base = SE->getIntegerSCEV(0, Stride->getType());
1574 UsersToProcess[i].Imm = SE->getMinusSCEV(UsersToProcess[i].Imm, Imm);
1575 UsersToProcess[i].Phi = Phi;
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001576 assert(UsersToProcess[i].Imm->isLoopInvariant(L) &&
1577 "ShouldUseFullStrengthReductionMode should reject this!");
1578 } while (++i != e && Base == UsersToProcess[i].Base);
1579 }
1580}
1581
1582/// PrepareToStrengthReduceWithNewPhi - Insert a new induction variable for the
1583/// given users to share.
1584///
1585void
1586LoopStrengthReduce::PrepareToStrengthReduceWithNewPhi(
1587 std::vector<BasedUser> &UsersToProcess,
1588 SCEVHandle Stride,
1589 SCEVHandle CommonExprs,
1590 Value *CommonBaseV,
1591 const Loop *L,
1592 SCEVExpander &PreheaderRewriter) {
1593 DOUT << " Inserting new PHI:\n";
1594
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001595 PHINode *Phi = InsertAffinePhi(SE->getUnknown(CommonBaseV),
Dan Gohman2d1be872009-04-16 03:18:22 +00001596 Stride, L, TD,
Dan Gohman9d100862009-03-09 22:04:01 +00001597 PreheaderRewriter);
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001598
1599 // Remember this in case a later stride is multiple of this.
Dan Gohman9d100862009-03-09 22:04:01 +00001600 IVsByStride[Stride].addIV(Stride, CommonExprs, Phi);
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001601
1602 // All the users will share this new IV.
Dan Gohman9d100862009-03-09 22:04:01 +00001603 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001604 UsersToProcess[i].Phi = Phi;
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001605
1606 DOUT << " IV=";
1607 DEBUG(WriteAsOperand(*DOUT, Phi, /*PrintType=*/false));
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001608 DOUT << "\n";
1609}
1610
1611/// PrepareToStrengthReduceWithNewPhi - Prepare for the given users to reuse
1612/// an induction variable with a stride that is a factor of the current
1613/// induction variable.
1614///
1615void
1616LoopStrengthReduce::PrepareToStrengthReduceFromSmallerStride(
1617 std::vector<BasedUser> &UsersToProcess,
1618 Value *CommonBaseV,
1619 const IVExpr &ReuseIV,
1620 Instruction *PreInsertPt) {
1621 DOUT << " Rewriting in terms of existing IV of STRIDE " << *ReuseIV.Stride
1622 << " and BASE " << *ReuseIV.Base << "\n";
1623
1624 // All the users will share the reused IV.
Dan Gohman9d100862009-03-09 22:04:01 +00001625 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001626 UsersToProcess[i].Phi = ReuseIV.PHI;
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001627
1628 Constant *C = dyn_cast<Constant>(CommonBaseV);
1629 if (C &&
1630 (!C->isNullValue() &&
1631 !fitsInAddressMode(SE->getUnknown(CommonBaseV), CommonBaseV->getType(),
1632 TLI, false)))
1633 // We want the common base emitted into the preheader! This is just
1634 // using cast as a copy so BitCast (no-op cast) is appropriate
1635 CommonBaseV = new BitCastInst(CommonBaseV, CommonBaseV->getType(),
1636 "commonbase", PreInsertPt);
1637}
1638
Evan Chengd9fb7122009-02-21 02:06:47 +00001639static bool IsImmFoldedIntoAddrMode(GlobalValue *GV, int64_t Offset,
Dan Gohman53f2ae22009-03-09 21:04:19 +00001640 const Type *AccessTy,
Evan Chengd9fb7122009-02-21 02:06:47 +00001641 std::vector<BasedUser> &UsersToProcess,
1642 const TargetLowering *TLI) {
1643 SmallVector<Instruction*, 16> AddrModeInsts;
1644 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1645 if (UsersToProcess[i].isUseOfPostIncrementedValue)
1646 continue;
1647 ExtAddrMode AddrMode =
1648 AddressingModeMatcher::Match(UsersToProcess[i].OperandValToReplace,
Dan Gohman53f2ae22009-03-09 21:04:19 +00001649 AccessTy, UsersToProcess[i].Inst,
Evan Chengd9fb7122009-02-21 02:06:47 +00001650 AddrModeInsts, *TLI);
1651 if (GV && GV != AddrMode.BaseGV)
1652 return false;
1653 if (Offset && !AddrMode.BaseOffs)
1654 // FIXME: How to accurate check it's immediate offset is folded.
1655 return false;
1656 AddrModeInsts.clear();
1657 }
1658 return true;
1659}
1660
Evan Cheng5f8ebaa2007-10-25 22:45:20 +00001661/// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
1662/// stride of IV. All of the users may have different starting values, and this
Dan Gohman9f4ac312009-03-09 20:41:15 +00001663/// may not be the only stride.
Evan Cheng5f8ebaa2007-10-25 22:45:20 +00001664void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
1665 IVUsersOfOneStride &Uses,
Dan Gohman9f4ac312009-03-09 20:41:15 +00001666 Loop *L) {
Evan Cheng5f8ebaa2007-10-25 22:45:20 +00001667 // If all the users are moved to another stride, then there is nothing to do.
Dan Gohman30359592008-01-29 13:02:09 +00001668 if (Uses.Users.empty())
Evan Cheng5f8ebaa2007-10-25 22:45:20 +00001669 return;
1670
1671 // Keep track if every use in UsersToProcess is an address. If they all are,
1672 // we may be able to rewrite the entire collection of them in terms of a
1673 // smaller-stride IV.
1674 bool AllUsesAreAddresses = true;
1675
Dale Johannesenb0390622008-12-16 22:16:28 +00001676 // Keep track if every use of a single stride is outside the loop. If so,
1677 // we want to be more aggressive about reusing a smaller-stride IV; a
1678 // multiply outside the loop is better than another IV inside. Well, usually.
1679 bool AllUsesAreOutsideLoop = true;
1680
Evan Cheng5f8ebaa2007-10-25 22:45:20 +00001681 // Transform our list of users and offsets to a bit more complex table. In
1682 // this new vector, each 'BasedUser' contains 'Base' the base of the
1683 // strided accessas well as the old information from Uses. We progressively
1684 // move information from the Base field to the Imm field, until we eventually
1685 // have the full access expression to rewrite the use.
1686 std::vector<BasedUser> UsersToProcess;
1687 SCEVHandle CommonExprs = CollectIVUsers(Stride, Uses, L, AllUsesAreAddresses,
Dale Johannesenb0390622008-12-16 22:16:28 +00001688 AllUsesAreOutsideLoop,
Evan Cheng5f8ebaa2007-10-25 22:45:20 +00001689 UsersToProcess);
1690
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001691 // Sort the UsersToProcess array so that users with common bases are
1692 // next to each other.
1693 SortUsersToProcess(UsersToProcess);
1694
Evan Cheng5f8ebaa2007-10-25 22:45:20 +00001695 // If we managed to find some expressions in common, we'll need to carry
1696 // their value in a register and add it in for each use. This will take up
1697 // a register operand, which potentially restricts what stride values are
1698 // valid.
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001699 bool HaveCommonExprs = !CommonExprs->isZero();
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001700
Chris Lattnerfe355552007-04-01 22:21:39 +00001701 const Type *ReplacedTy = CommonExprs->getType();
Dan Gohman2d1be872009-04-16 03:18:22 +00001702 if (isa<PointerType>(ReplacedTy)) ReplacedTy = TD->getIntPtrType();
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001703
Evan Chengd9fb7122009-02-21 02:06:47 +00001704 // If all uses are addresses, consider sinking the immediate part of the
1705 // common expression back into uses if they can fit in the immediate fields.
Evan Cheng3cd389d2009-02-22 07:31:19 +00001706 if (TLI && HaveCommonExprs && AllUsesAreAddresses) {
Evan Chengd9fb7122009-02-21 02:06:47 +00001707 SCEVHandle NewCommon = CommonExprs;
1708 SCEVHandle Imm = SE->getIntegerSCEV(0, ReplacedTy);
Dan Gohman3cfe6a42009-03-09 21:22:12 +00001709 MoveImmediateValues(TLI, Type::VoidTy, NewCommon, Imm, true, L, SE);
Evan Chengd9fb7122009-02-21 02:06:47 +00001710 if (!Imm->isZero()) {
1711 bool DoSink = true;
1712
1713 // If the immediate part of the common expression is a GV, check if it's
1714 // possible to fold it into the target addressing mode.
1715 GlobalValue *GV = 0;
Dan Gohman2d1be872009-04-16 03:18:22 +00001716 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(Imm))
1717 GV = dyn_cast<GlobalValue>(SU->getValue());
Evan Chengd9fb7122009-02-21 02:06:47 +00001718 int64_t Offset = 0;
1719 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Imm))
1720 Offset = SC->getValue()->getSExtValue();
1721 if (GV || Offset)
Dan Gohman53f2ae22009-03-09 21:04:19 +00001722 // Pass VoidTy as the AccessTy to be conservative, because
1723 // there could be multiple access types among all the uses.
1724 DoSink = IsImmFoldedIntoAddrMode(GV, Offset, Type::VoidTy,
Evan Chengd9fb7122009-02-21 02:06:47 +00001725 UsersToProcess, TLI);
1726
1727 if (DoSink) {
1728 DOUT << " Sinking " << *Imm << " back down into uses\n";
1729 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1730 UsersToProcess[i].Imm = SE->getAddExpr(UsersToProcess[i].Imm, Imm);
1731 CommonExprs = NewCommon;
1732 HaveCommonExprs = !CommonExprs->isZero();
1733 ++NumImmSunk;
1734 }
1735 }
1736 }
1737
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001738 // Now that we know what we need to do, insert the PHI node itself.
1739 //
Dan Gohman2f09f512009-02-19 19:23:27 +00001740 DOUT << "LSR: Examining IVs of TYPE " << *ReplacedTy << " of STRIDE "
1741 << *Stride << ":\n"
1742 << " Common base: " << *CommonExprs << "\n";
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001743
Dan Gohman2d1be872009-04-16 03:18:22 +00001744 SCEVExpander Rewriter(*SE, *LI, *TD);
1745 SCEVExpander PreheaderRewriter(*SE, *LI, *TD);
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001746
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001747 BasicBlock *Preheader = L->getLoopPreheader();
1748 Instruction *PreInsertPt = Preheader->getTerminator();
Chris Lattner12b50412005-09-12 17:11:27 +00001749 BasicBlock *LatchBlock = L->getLoopLatch();
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001750
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001751 Value *CommonBaseV = ConstantInt::get(ReplacedTy, 0);
Evan Chengeb8f9e22006-03-17 19:52:23 +00001752
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001753 SCEVHandle RewriteFactor = SE->getIntegerSCEV(0, ReplacedTy);
1754 IVExpr ReuseIV(SE->getIntegerSCEV(0, Type::Int32Ty),
1755 SE->getIntegerSCEV(0, Type::Int32Ty),
Dan Gohman9d100862009-03-09 22:04:01 +00001756 0);
Evan Chengeb8f9e22006-03-17 19:52:23 +00001757
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001758 /// Choose a strength-reduction strategy and prepare for it by creating
1759 /// the necessary PHIs and adjusting the bookkeeping.
1760 if (ShouldUseFullStrengthReductionMode(UsersToProcess, L,
1761 AllUsesAreAddresses, Stride)) {
1762 PrepareToStrengthReduceFully(UsersToProcess, Stride, CommonExprs, L,
1763 PreheaderRewriter);
Evan Chengeb8f9e22006-03-17 19:52:23 +00001764 } else {
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001765 // Emit the initial base value into the loop preheader.
Dan Gohman2d1be872009-04-16 03:18:22 +00001766 CommonBaseV = PreheaderRewriter.expandCodeFor(CommonExprs, ReplacedTy,
1767 PreInsertPt);
Dan Gohman2f09f512009-02-19 19:23:27 +00001768
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001769 // If all uses are addresses, check if it is possible to reuse an IV with a
1770 // stride that is a factor of this stride. And that the multiple is a number
1771 // that can be encoded in the scale field of the target addressing mode. And
Dan Gohman6b38e292009-02-20 21:06:57 +00001772 // that we will have a valid instruction after this substition, including
1773 // the immediate field, if any.
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001774 RewriteFactor = CheckForIVReuse(HaveCommonExprs, AllUsesAreAddresses,
1775 AllUsesAreOutsideLoop,
Dan Gohmanbb5b49c2009-03-09 21:19:58 +00001776 Stride, ReuseIV, ReplacedTy,
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001777 UsersToProcess);
1778 if (isa<SCEVConstant>(RewriteFactor) &&
1779 cast<SCEVConstant>(RewriteFactor)->isZero())
1780 PrepareToStrengthReduceWithNewPhi(UsersToProcess, Stride, CommonExprs,
1781 CommonBaseV, L, PreheaderRewriter);
1782 else
1783 PrepareToStrengthReduceFromSmallerStride(UsersToProcess, CommonBaseV,
1784 ReuseIV, PreInsertPt);
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001785 }
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001786
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001787 // Process all the users now, replacing their strided uses with
1788 // strength-reduced forms. This outer loop handles all bases, the inner
Chris Lattner7e79b382006-08-03 06:34:50 +00001789 // loop handles all users of a particular base.
Nate Begeman16997482005-07-30 00:15:07 +00001790 while (!UsersToProcess.empty()) {
Chris Lattner7b445c52005-10-11 18:30:57 +00001791 SCEVHandle Base = UsersToProcess.back().Base;
Dan Gohman2f09f512009-02-19 19:23:27 +00001792 Instruction *Inst = UsersToProcess.back().Inst;
Chris Lattnerbe3e5212005-08-03 23:30:08 +00001793
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001794 // Emit the code for Base into the preheader.
Dan Gohman2d1be872009-04-16 03:18:22 +00001795 Value *BaseV = 0;
1796 if (!Base->isZero()) {
1797 BaseV = PreheaderRewriter.expandCodeFor(Base, Base->getType(),
1798 PreInsertPt);
Chris Lattner7d8ed8a2007-05-11 22:40:34 +00001799
Dan Gohman2d1be872009-04-16 03:18:22 +00001800 DOUT << " INSERTING code for BASE = " << *Base << ":";
1801 if (BaseV->hasName())
1802 DOUT << " Result value name = %" << BaseV->getNameStr();
1803 DOUT << "\n";
Chris Lattner7d8ed8a2007-05-11 22:40:34 +00001804
Dan Gohman2d1be872009-04-16 03:18:22 +00001805 // If BaseV is a non-zero constant, make sure that it gets inserted into
1806 // the preheader, instead of being forward substituted into the uses. We
1807 // do this by forcing a BitCast (noop cast) to be inserted into the
1808 // preheader in this case.
1809 if (!fitsInAddressMode(Base, getAccessType(Inst), TLI, false)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001810 // We want this constant emitted into the preheader! This is just
1811 // using cast as a copy so BitCast (no-op cast) is appropriate
1812 BaseV = new BitCastInst(BaseV, BaseV->getType(), "preheaderinsert",
Dan Gohman4a9a3e52008-04-14 18:26:16 +00001813 PreInsertPt);
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001814 }
Chris Lattner7e79b382006-08-03 06:34:50 +00001815 }
1816
Nate Begeman16997482005-07-30 00:15:07 +00001817 // Emit the code to add the immediate offset to the Phi value, just before
Chris Lattner2351aba2005-08-03 22:51:21 +00001818 // the instructions that we identified as using this stride and base.
Chris Lattner7b445c52005-10-11 18:30:57 +00001819 do {
Chris Lattner7e79b382006-08-03 06:34:50 +00001820 // FIXME: Use emitted users to emit other users.
Chris Lattner7b445c52005-10-11 18:30:57 +00001821 BasedUser &User = UsersToProcess.back();
Jeff Cohend29b6aa2005-07-30 18:33:25 +00001822
Dan Gohman2f09f512009-02-19 19:23:27 +00001823 DOUT << " Examining use ";
Dan Gohman4a359ea2009-02-19 19:32:06 +00001824 DEBUG(WriteAsOperand(*DOUT, UsersToProcess.back().OperandValToReplace,
1825 /*PrintType=*/false));
Dan Gohman2f09f512009-02-19 19:23:27 +00001826 DOUT << " in Inst: " << *Inst;
Dan Gohman2f09f512009-02-19 19:23:27 +00001827
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001828 // If this instruction wants to use the post-incremented value, move it
1829 // after the post-inc and use its value instead of the PHI.
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001830 Value *RewriteOp = User.Phi;
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001831 if (User.isUseOfPostIncrementedValue) {
Dan Gohman9d100862009-03-09 22:04:01 +00001832 RewriteOp = User.Phi->getIncomingValueForBlock(LatchBlock);
Chris Lattnerc6bae652005-09-12 06:04:47 +00001833
1834 // If this user is in the loop, make sure it is the last thing in the
1835 // loop to ensure it is dominated by the increment.
1836 if (L->contains(User.Inst->getParent()))
1837 User.Inst->moveBefore(LatchBlock->getTerminator());
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001838 }
Reid Spencer3ba68b92006-12-13 08:06:42 +00001839 if (RewriteOp->getType() != ReplacedTy) {
Dan Gohman2d1be872009-04-16 03:18:22 +00001840 Instruction::CastOps opcode =
1841 CastInst::getCastOpcode(RewriteOp, false, ReplacedTy, false);
1842 assert(opcode != Instruction::SExt &&
1843 opcode != Instruction::ZExt &&
1844 "Unexpected widening cast!");
Reid Spencer3ba68b92006-12-13 08:06:42 +00001845 RewriteOp = SCEVExpander::InsertCastOfTo(opcode, RewriteOp, ReplacedTy);
1846 }
Evan Cheng86c75d32006-06-09 00:12:42 +00001847
Dan Gohman246b2562007-10-22 18:31:58 +00001848 SCEVHandle RewriteExpr = SE->getUnknown(RewriteOp);
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001849
Dale Johannesenb0390622008-12-16 22:16:28 +00001850 // If we had to insert new instructions for RewriteOp, we have to
Dan Gohmanf20d70d2008-05-15 23:26:57 +00001851 // consider that they may not have been able to end up immediately
1852 // next to RewriteOp, because non-PHI instructions may never precede
1853 // PHI instructions in a block. In this case, remember where the last
Dan Gohmanca756ae2008-05-20 03:01:48 +00001854 // instruction was inserted so that if we're replacing a different
1855 // PHI node, we can use the later point to expand the final
1856 // RewriteExpr.
Dan Gohmanf20d70d2008-05-15 23:26:57 +00001857 Instruction *NewBasePt = dyn_cast<Instruction>(RewriteOp);
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001858 if (RewriteOp == User.Phi) NewBasePt = 0;
Dan Gohmanf20d70d2008-05-15 23:26:57 +00001859
Chris Lattner2351aba2005-08-03 22:51:21 +00001860 // Clear the SCEVExpander's expression map so that we are guaranteed
1861 // to have the code emitted where we expect it.
1862 Rewriter.clear();
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001863
1864 // If we are reusing the iv, then it must be multiplied by a constant
Dale Johannesen1de17d52009-02-09 22:14:15 +00001865 // factor to take advantage of the addressing mode scale component.
Dan Gohman2d1be872009-04-16 03:18:22 +00001866 if (!RewriteFactor->isZero()) {
Dale Johannesen2f46bb82009-01-14 02:35:31 +00001867 // If we're reusing an IV with a nonzero base (currently this happens
1868 // only when all reuses are outside the loop) subtract that base here.
1869 // The base has been used to initialize the PHI node but we don't want
1870 // it here.
Dale Johannesen1de17d52009-02-09 22:14:15 +00001871 if (!ReuseIV.Base->isZero()) {
1872 SCEVHandle typedBase = ReuseIV.Base;
1873 if (RewriteExpr->getType()->getPrimitiveSizeInBits() !=
1874 ReuseIV.Base->getType()->getPrimitiveSizeInBits()) {
1875 // It's possible the original IV is a larger type than the new IV,
1876 // in which case we have to truncate the Base. We checked in
1877 // RequiresTypeConversion that this is valid.
1878 assert (RewriteExpr->getType()->getPrimitiveSizeInBits() <
1879 ReuseIV.Base->getType()->getPrimitiveSizeInBits() &&
1880 "Unexpected lengthening conversion!");
1881 typedBase = SE->getTruncateExpr(ReuseIV.Base,
1882 RewriteExpr->getType());
1883 }
1884 RewriteExpr = SE->getMinusSCEV(RewriteExpr, typedBase);
1885 }
Dale Johannesen2f46bb82009-01-14 02:35:31 +00001886
1887 // Multiply old variable, with base removed, by new scale factor.
1888 RewriteExpr = SE->getMulExpr(RewriteFactor,
Evan Cheng83927722007-10-30 22:27:26 +00001889 RewriteExpr);
Evan Chengeb8f9e22006-03-17 19:52:23 +00001890
1891 // The common base is emitted in the loop preheader. But since we
1892 // are reusing an IV, it has not been used to initialize the PHI node.
1893 // Add it to the expression used to rewrite the uses.
Dale Johannesen2f46bb82009-01-14 02:35:31 +00001894 // When this use is outside the loop, we earlier subtracted the
1895 // common base, and are adding it back here. Use the same expression
1896 // as before, rather than CommonBaseV, so DAGCombiner will zap it.
Dan Gohman2d1be872009-04-16 03:18:22 +00001897 if (!CommonExprs->isZero()) {
Dale Johannesen2f46bb82009-01-14 02:35:31 +00001898 if (L->contains(User.Inst->getParent()))
1899 RewriteExpr = SE->getAddExpr(RewriteExpr,
Dale Johannesenb0390622008-12-16 22:16:28 +00001900 SE->getUnknown(CommonBaseV));
Dale Johannesen2f46bb82009-01-14 02:35:31 +00001901 else
1902 RewriteExpr = SE->getAddExpr(RewriteExpr, CommonExprs);
1903 }
Evan Chengeb8f9e22006-03-17 19:52:23 +00001904 }
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001905
Chris Lattner2114b272005-08-04 20:03:32 +00001906 // Now that we know what we need to do, insert code before User for the
1907 // immediate and any loop-variant expressions.
Dan Gohman2d1be872009-04-16 03:18:22 +00001908 if (BaseV)
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001909 // Add BaseV to the PHI value if needed.
Dan Gohman246b2562007-10-22 18:31:58 +00001910 RewriteExpr = SE->getAddExpr(RewriteExpr, SE->getUnknown(BaseV));
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001911
Dan Gohmanf20d70d2008-05-15 23:26:57 +00001912 User.RewriteInstructionToUseNewBase(RewriteExpr, NewBasePt,
1913 Rewriter, L, this,
Evan Cheng0e0014d2007-10-30 23:45:15 +00001914 DeadInsts);
Jeff Cohend29b6aa2005-07-30 18:33:25 +00001915
Chris Lattnera68d4ca2008-12-01 06:14:28 +00001916 // Mark old value we replaced as possibly dead, so that it is eliminated
Chris Lattner2351aba2005-08-03 22:51:21 +00001917 // if we just replaced the last use of that value.
Chris Lattner09fb7da2008-12-01 06:27:41 +00001918 DeadInsts.push_back(cast<Instruction>(User.OperandValToReplace));
Nate Begeman16997482005-07-30 00:15:07 +00001919
Chris Lattner7b445c52005-10-11 18:30:57 +00001920 UsersToProcess.pop_back();
Chris Lattner2351aba2005-08-03 22:51:21 +00001921 ++NumReduced;
Chris Lattner7b445c52005-10-11 18:30:57 +00001922
Chris Lattner7e79b382006-08-03 06:34:50 +00001923 // If there are any more users to process with the same base, process them
1924 // now. We sorted by base above, so we just have to check the last elt.
Chris Lattner7b445c52005-10-11 18:30:57 +00001925 } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
Nate Begeman16997482005-07-30 00:15:07 +00001926 // TODO: Next, find out which base index is the most common, pull it out.
1927 }
1928
1929 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1930 // different starting values, into different PHIs.
Nate Begeman16997482005-07-30 00:15:07 +00001931}
1932
Devang Patelc677de22008-08-13 20:31:11 +00001933/// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
Chris Lattneraed01d12007-04-03 05:11:24 +00001934/// set the IV user and stride information and return true, otherwise return
1935/// false.
Devang Patelc677de22008-08-13 20:31:11 +00001936bool LoopStrengthReduce::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse,
Chris Lattneraed01d12007-04-03 05:11:24 +00001937 const SCEVHandle *&CondStride) {
1938 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e && !CondUse;
1939 ++Stride) {
1940 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1941 IVUsesByStride.find(StrideOrder[Stride]);
1942 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1943
1944 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
1945 E = SI->second.Users.end(); UI != E; ++UI)
1946 if (UI->User == Cond) {
1947 // NOTE: we could handle setcc instructions with multiple uses here, but
1948 // InstCombine does it as well for simple uses, it's not clear that it
1949 // occurs enough in real life to handle.
1950 CondUse = &*UI;
1951 CondStride = &SI->first;
1952 return true;
1953 }
1954 }
1955 return false;
1956}
1957
Evan Chengcdf43b12007-10-25 09:11:16 +00001958namespace {
1959 // Constant strides come first which in turns are sorted by their absolute
1960 // values. If absolute values are the same, then positive strides comes first.
1961 // e.g.
1962 // 4, -1, X, 1, 2 ==> 1, -1, 2, 4, X
1963 struct StrideCompare {
Dan Gohman2d1be872009-04-16 03:18:22 +00001964 const TargetData *TD;
1965 explicit StrideCompare(const TargetData *td) : TD(td) {}
1966
Evan Chengcdf43b12007-10-25 09:11:16 +00001967 bool operator()(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1968 SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS);
1969 SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
1970 if (LHSC && RHSC) {
1971 int64_t LV = LHSC->getValue()->getSExtValue();
1972 int64_t RV = RHSC->getValue()->getSExtValue();
1973 uint64_t ALV = (LV < 0) ? -LV : LV;
1974 uint64_t ARV = (RV < 0) ? -RV : RV;
Dan Gohmanbc511722009-02-13 00:26:43 +00001975 if (ALV == ARV) {
1976 if (LV != RV)
1977 return LV > RV;
1978 } else {
Evan Chengcdf43b12007-10-25 09:11:16 +00001979 return ALV < ARV;
Dan Gohmanbc511722009-02-13 00:26:43 +00001980 }
1981
1982 // If it's the same value but different type, sort by bit width so
1983 // that we emit larger induction variables before smaller
1984 // ones, letting the smaller be re-written in terms of larger ones.
Dan Gohman2d1be872009-04-16 03:18:22 +00001985 return TD->getTypeSizeInBits(RHS->getType()) <
1986 TD->getTypeSizeInBits(LHS->getType());
Evan Chengcdf43b12007-10-25 09:11:16 +00001987 }
Dan Gohmanbc511722009-02-13 00:26:43 +00001988 return LHSC && !RHSC;
Evan Chengcdf43b12007-10-25 09:11:16 +00001989 }
1990 };
1991}
1992
1993/// ChangeCompareStride - If a loop termination compare instruction is the
1994/// only use of its stride, and the compaison is against a constant value,
1995/// try eliminate the stride by moving the compare instruction to another
1996/// stride and change its constant operand accordingly. e.g.
1997///
1998/// loop:
1999/// ...
2000/// v1 = v1 + 3
2001/// v2 = v2 + 1
2002/// if (v2 < 10) goto loop
2003/// =>
2004/// loop:
2005/// ...
2006/// v1 = v1 + 3
2007/// if (v1 < 30) goto loop
2008ICmpInst *LoopStrengthReduce::ChangeCompareStride(Loop *L, ICmpInst *Cond,
Evan Cheng0e0014d2007-10-30 23:45:15 +00002009 IVStrideUse* &CondUse,
Evan Chengcdf43b12007-10-25 09:11:16 +00002010 const SCEVHandle* &CondStride) {
2011 if (StrideOrder.size() < 2 ||
2012 IVUsesByStride[*CondStride].Users.size() != 1)
2013 return Cond;
Evan Chengcdf43b12007-10-25 09:11:16 +00002014 const SCEVConstant *SC = dyn_cast<SCEVConstant>(*CondStride);
2015 if (!SC) return Cond;
Evan Chengcdf43b12007-10-25 09:11:16 +00002016
2017 ICmpInst::Predicate Predicate = Cond->getPredicate();
Evan Chengcdf43b12007-10-25 09:11:16 +00002018 int64_t CmpSSInt = SC->getValue()->getSExtValue();
Dan Gohman2d1be872009-04-16 03:18:22 +00002019 unsigned BitWidth = TD->getTypeSizeInBits((*CondStride)->getType());
Evan Cheng168a66b2007-10-26 23:08:19 +00002020 uint64_t SignBit = 1ULL << (BitWidth-1);
Dan Gohmanc34fea32009-02-24 01:58:00 +00002021 const Type *CmpTy = Cond->getOperand(0)->getType();
Evan Cheng168a66b2007-10-26 23:08:19 +00002022 const Type *NewCmpTy = NULL;
Dan Gohman2d1be872009-04-16 03:18:22 +00002023 unsigned TyBits = TD->getTypeSizeInBits(CmpTy);
Evan Chengaf62c092007-10-29 22:07:18 +00002024 unsigned NewTyBits = 0;
Evan Chengcdf43b12007-10-25 09:11:16 +00002025 SCEVHandle *NewStride = NULL;
Dan Gohmanff518c82009-02-20 21:27:23 +00002026 Value *NewCmpLHS = NULL;
2027 Value *NewCmpRHS = NULL;
Evan Chengcdf43b12007-10-25 09:11:16 +00002028 int64_t Scale = 1;
Dan Gohmanc34fea32009-02-24 01:58:00 +00002029 SCEVHandle NewOffset = SE->getIntegerSCEV(0, UIntPtrTy);
Evan Chengcdf43b12007-10-25 09:11:16 +00002030
Dan Gohmanc34fea32009-02-24 01:58:00 +00002031 if (ConstantInt *C = dyn_cast<ConstantInt>(Cond->getOperand(1))) {
2032 int64_t CmpVal = C->getValue().getSExtValue();
Evan Cheng168a66b2007-10-26 23:08:19 +00002033
Dan Gohmanc34fea32009-02-24 01:58:00 +00002034 // Check stride constant and the comparision constant signs to detect
2035 // overflow.
2036 if ((CmpVal & SignBit) != (CmpSSInt & SignBit))
2037 return Cond;
Evan Cheng168a66b2007-10-26 23:08:19 +00002038
Dan Gohmanc34fea32009-02-24 01:58:00 +00002039 // Look for a suitable stride / iv as replacement.
2040 for (unsigned i = 0, e = StrideOrder.size(); i != e; ++i) {
2041 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
2042 IVUsesByStride.find(StrideOrder[i]);
2043 if (!isa<SCEVConstant>(SI->first))
Dan Gohmanff518c82009-02-20 21:27:23 +00002044 continue;
Dan Gohmanc34fea32009-02-24 01:58:00 +00002045 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
2046 if (abs(SSInt) <= abs(CmpSSInt) || (SSInt % CmpSSInt) != 0)
2047 continue;
2048
2049 Scale = SSInt / CmpSSInt;
2050 int64_t NewCmpVal = CmpVal * Scale;
2051 APInt Mul = APInt(BitWidth, NewCmpVal);
2052 // Check for overflow.
2053 if (Mul.getSExtValue() != NewCmpVal)
2054 continue;
2055
2056 // Watch out for overflow.
2057 if (ICmpInst::isSignedPredicate(Predicate) &&
2058 (CmpVal & SignBit) != (NewCmpVal & SignBit))
2059 continue;
2060
2061 if (NewCmpVal == CmpVal)
2062 continue;
2063 // Pick the best iv to use trying to avoid a cast.
2064 NewCmpLHS = NULL;
2065 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
2066 E = SI->second.Users.end(); UI != E; ++UI) {
2067 NewCmpLHS = UI->OperandValToReplace;
2068 if (NewCmpLHS->getType() == CmpTy)
2069 break;
2070 }
2071 if (!NewCmpLHS)
2072 continue;
2073
2074 NewCmpTy = NewCmpLHS->getType();
Dan Gohman2d1be872009-04-16 03:18:22 +00002075 NewTyBits = TD->getTypeSizeInBits(NewCmpTy);
Dan Gohmanc34fea32009-02-24 01:58:00 +00002076 if (RequiresTypeConversion(NewCmpTy, CmpTy)) {
2077 // Check if it is possible to rewrite it using
2078 // an iv / stride of a smaller integer type.
2079 bool TruncOk = false;
2080 if (NewCmpTy->isInteger()) {
2081 unsigned Bits = NewTyBits;
2082 if (ICmpInst::isSignedPredicate(Predicate))
2083 --Bits;
2084 uint64_t Mask = (1ULL << Bits) - 1;
2085 if (((uint64_t)NewCmpVal & Mask) == (uint64_t)NewCmpVal)
2086 TruncOk = true;
2087 }
2088 if (!TruncOk)
2089 continue;
2090 }
2091
2092 // Don't rewrite if use offset is non-constant and the new type is
2093 // of a different type.
2094 // FIXME: too conservative?
2095 if (NewTyBits != TyBits && !isa<SCEVConstant>(CondUse->Offset))
2096 continue;
2097
2098 bool AllUsesAreAddresses = true;
2099 bool AllUsesAreOutsideLoop = true;
2100 std::vector<BasedUser> UsersToProcess;
2101 SCEVHandle CommonExprs = CollectIVUsers(SI->first, SI->second, L,
2102 AllUsesAreAddresses,
2103 AllUsesAreOutsideLoop,
2104 UsersToProcess);
2105 // Avoid rewriting the compare instruction with an iv of new stride
2106 // if it's likely the new stride uses will be rewritten using the
2107 // stride of the compare instruction.
2108 if (AllUsesAreAddresses &&
2109 ValidStride(!CommonExprs->isZero(), Scale, UsersToProcess))
2110 continue;
2111
2112 // If scale is negative, use swapped predicate unless it's testing
2113 // for equality.
2114 if (Scale < 0 && !Cond->isEquality())
2115 Predicate = ICmpInst::getSwappedPredicate(Predicate);
2116
2117 NewStride = &StrideOrder[i];
2118 if (!isa<PointerType>(NewCmpTy))
2119 NewCmpRHS = ConstantInt::get(NewCmpTy, NewCmpVal);
2120 else {
2121 NewCmpRHS = ConstantInt::get(UIntPtrTy, NewCmpVal);
2122 NewCmpRHS = SCEVExpander::InsertCastOfTo(Instruction::IntToPtr,
2123 NewCmpRHS, NewCmpTy);
2124 }
2125 NewOffset = TyBits == NewTyBits
2126 ? SE->getMulExpr(CondUse->Offset,
2127 SE->getConstant(ConstantInt::get(CmpTy, Scale)))
2128 : SE->getConstant(ConstantInt::get(NewCmpTy,
2129 cast<SCEVConstant>(CondUse->Offset)->getValue()->getSExtValue()*Scale));
2130 break;
Dan Gohmanff518c82009-02-20 21:27:23 +00002131 }
Evan Chengcdf43b12007-10-25 09:11:16 +00002132 }
2133
Dan Gohman9b93dd12008-06-16 22:34:15 +00002134 // Forgo this transformation if it the increment happens to be
2135 // unfortunately positioned after the condition, and the condition
2136 // has multiple uses which prevent it from being moved immediately
2137 // before the branch. See
2138 // test/Transforms/LoopStrengthReduce/change-compare-stride-trickiness-*.ll
2139 // for an example of this situation.
Devang Pateld16aba22008-08-13 02:05:14 +00002140 if (!Cond->hasOneUse()) {
Dan Gohman9b93dd12008-06-16 22:34:15 +00002141 for (BasicBlock::iterator I = Cond, E = Cond->getParent()->end();
2142 I != E; ++I)
Dan Gohmanff518c82009-02-20 21:27:23 +00002143 if (I == NewCmpLHS)
Dan Gohman9b93dd12008-06-16 22:34:15 +00002144 return Cond;
Devang Pateld16aba22008-08-13 02:05:14 +00002145 }
Dan Gohman9b93dd12008-06-16 22:34:15 +00002146
Dan Gohmanff518c82009-02-20 21:27:23 +00002147 if (NewCmpRHS) {
Evan Chengcdf43b12007-10-25 09:11:16 +00002148 // Create a new compare instruction using new stride / iv.
2149 ICmpInst *OldCond = Cond;
Evan Cheng168a66b2007-10-26 23:08:19 +00002150 // Insert new compare instruction.
Dan Gohmanff518c82009-02-20 21:27:23 +00002151 Cond = new ICmpInst(Predicate, NewCmpLHS, NewCmpRHS,
Dan Gohmane562b172008-06-13 21:43:41 +00002152 L->getHeader()->getName() + ".termcond",
2153 OldCond);
Evan Cheng168a66b2007-10-26 23:08:19 +00002154
2155 // Remove the old compare instruction. The old indvar is probably dead too.
Chris Lattner09fb7da2008-12-01 06:27:41 +00002156 DeadInsts.push_back(cast<Instruction>(CondUse->OperandValToReplace));
Evan Cheng168a66b2007-10-26 23:08:19 +00002157 SE->deleteValueFromRecords(OldCond);
Dan Gohman010ee2d2008-05-21 00:54:12 +00002158 OldCond->replaceAllUsesWith(Cond);
Evan Chengcdf43b12007-10-25 09:11:16 +00002159 OldCond->eraseFromParent();
Evan Cheng168a66b2007-10-26 23:08:19 +00002160
Evan Chengcdf43b12007-10-25 09:11:16 +00002161 IVUsesByStride[*CondStride].Users.pop_back();
Dan Gohmanff518c82009-02-20 21:27:23 +00002162 IVUsesByStride[*NewStride].addUser(NewOffset, Cond, NewCmpLHS);
Evan Chengcdf43b12007-10-25 09:11:16 +00002163 CondUse = &IVUsesByStride[*NewStride].Users.back();
2164 CondStride = NewStride;
2165 ++NumEliminated;
2166 }
2167
2168 return Cond;
2169}
2170
Dan Gohmanad7321f2008-09-15 21:22:06 +00002171/// OptimizeSMax - Rewrite the loop's terminating condition if it uses
2172/// an smax computation.
2173///
2174/// This is a narrow solution to a specific, but acute, problem. For loops
2175/// like this:
2176///
2177/// i = 0;
2178/// do {
2179/// p[i] = 0.0;
2180/// } while (++i < n);
2181///
2182/// where the comparison is signed, the trip count isn't just 'n', because
2183/// 'n' could be negative. And unfortunately this can come up even for loops
2184/// where the user didn't use a C do-while loop. For example, seemingly
2185/// well-behaved top-test loops will commonly be lowered like this:
2186//
2187/// if (n > 0) {
2188/// i = 0;
2189/// do {
2190/// p[i] = 0.0;
2191/// } while (++i < n);
2192/// }
2193///
2194/// and then it's possible for subsequent optimization to obscure the if
2195/// test in such a way that indvars can't find it.
2196///
2197/// When indvars can't find the if test in loops like this, it creates a
2198/// signed-max expression, which allows it to give the loop a canonical
2199/// induction variable:
2200///
2201/// i = 0;
2202/// smax = n < 1 ? 1 : n;
2203/// do {
2204/// p[i] = 0.0;
2205/// } while (++i != smax);
2206///
2207/// Canonical induction variables are necessary because the loop passes
2208/// are designed around them. The most obvious example of this is the
2209/// LoopInfo analysis, which doesn't remember trip count values. It
2210/// expects to be able to rediscover the trip count each time it is
2211/// needed, and it does this using a simple analyis that only succeeds if
2212/// the loop has a canonical induction variable.
2213///
2214/// However, when it comes time to generate code, the maximum operation
2215/// can be quite costly, especially if it's inside of an outer loop.
2216///
2217/// This function solves this problem by detecting this type of loop and
2218/// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
2219/// the instructions for the maximum computation.
2220///
2221ICmpInst *LoopStrengthReduce::OptimizeSMax(Loop *L, ICmpInst *Cond,
2222 IVStrideUse* &CondUse) {
2223 // Check that the loop matches the pattern we're looking for.
2224 if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
2225 Cond->getPredicate() != CmpInst::ICMP_NE)
2226 return Cond;
2227
2228 SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
2229 if (!Sel || !Sel->hasOneUse()) return Cond;
2230
Dan Gohman46bdfb02009-02-24 18:55:53 +00002231 SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2232 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
Dan Gohmanad7321f2008-09-15 21:22:06 +00002233 return Cond;
Dan Gohman46bdfb02009-02-24 18:55:53 +00002234 SCEVHandle One = SE->getIntegerSCEV(1, BackedgeTakenCount->getType());
Dan Gohmanad7321f2008-09-15 21:22:06 +00002235
Dan Gohman46bdfb02009-02-24 18:55:53 +00002236 // Add one to the backedge-taken count to get the trip count.
2237 SCEVHandle IterationCount = SE->getAddExpr(BackedgeTakenCount, One);
Dan Gohmanad7321f2008-09-15 21:22:06 +00002238
2239 // Check for a max calculation that matches the pattern.
2240 SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(IterationCount);
2241 if (!SMax || SMax != SE->getSCEV(Sel)) return Cond;
2242
2243 SCEVHandle SMaxLHS = SMax->getOperand(0);
2244 SCEVHandle SMaxRHS = SMax->getOperand(1);
2245 if (!SMaxLHS || SMaxLHS != One) return Cond;
2246
2247 // Check the relevant induction variable for conformance to
2248 // the pattern.
2249 SCEVHandle IV = SE->getSCEV(Cond->getOperand(0));
2250 SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
2251 if (!AR || !AR->isAffine() ||
2252 AR->getStart() != One ||
2253 AR->getStepRecurrence(*SE) != One)
2254 return Cond;
2255
Dan Gohmanbc10b8c2009-03-04 20:49:01 +00002256 assert(AR->getLoop() == L &&
2257 "Loop condition operand is an addrec in a different loop!");
2258
Dan Gohmanad7321f2008-09-15 21:22:06 +00002259 // Check the right operand of the select, and remember it, as it will
2260 // be used in the new comparison instruction.
2261 Value *NewRHS = 0;
2262 if (SE->getSCEV(Sel->getOperand(1)) == SMaxRHS)
2263 NewRHS = Sel->getOperand(1);
2264 else if (SE->getSCEV(Sel->getOperand(2)) == SMaxRHS)
2265 NewRHS = Sel->getOperand(2);
2266 if (!NewRHS) return Cond;
2267
2268 // Ok, everything looks ok to change the condition into an SLT or SGE and
2269 // delete the max calculation.
2270 ICmpInst *NewCond =
2271 new ICmpInst(Cond->getPredicate() == CmpInst::ICMP_NE ?
2272 CmpInst::ICMP_SLT :
2273 CmpInst::ICMP_SGE,
2274 Cond->getOperand(0), NewRHS, "scmp", Cond);
2275
2276 // Delete the max calculation instructions.
Dan Gohman586b7b72008-10-01 02:02:03 +00002277 SE->deleteValueFromRecords(Cond);
Dan Gohmanad7321f2008-09-15 21:22:06 +00002278 Cond->replaceAllUsesWith(NewCond);
2279 Cond->eraseFromParent();
Dan Gohmanad7321f2008-09-15 21:22:06 +00002280 Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
Dan Gohmanad7321f2008-09-15 21:22:06 +00002281 SE->deleteValueFromRecords(Sel);
Dan Gohman586b7b72008-10-01 02:02:03 +00002282 Sel->eraseFromParent();
Dan Gohmanad7321f2008-09-15 21:22:06 +00002283 if (Cmp->use_empty()) {
Dan Gohmanad7321f2008-09-15 21:22:06 +00002284 SE->deleteValueFromRecords(Cmp);
Dan Gohman586b7b72008-10-01 02:02:03 +00002285 Cmp->eraseFromParent();
Dan Gohmanad7321f2008-09-15 21:22:06 +00002286 }
2287 CondUse->User = NewCond;
2288 return NewCond;
2289}
2290
Devang Patela0b39092008-08-26 17:57:54 +00002291/// OptimizeShadowIV - If IV is used in a int-to-float cast
2292/// inside the loop then try to eliminate the cast opeation.
2293void LoopStrengthReduce::OptimizeShadowIV(Loop *L) {
2294
Dan Gohman46bdfb02009-02-24 18:55:53 +00002295 SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2296 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
Devang Patela0b39092008-08-26 17:57:54 +00002297 return;
2298
2299 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e;
2300 ++Stride) {
2301 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
2302 IVUsesByStride.find(StrideOrder[Stride]);
2303 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
2304 if (!isa<SCEVConstant>(SI->first))
2305 continue;
2306
2307 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
2308 E = SI->second.Users.end(); UI != E; /* empty */) {
2309 std::vector<IVStrideUse>::iterator CandidateUI = UI;
Devang Patel54153272008-08-27 17:50:18 +00002310 ++UI;
Devang Patela0b39092008-08-26 17:57:54 +00002311 Instruction *ShadowUse = CandidateUI->User;
2312 const Type *DestTy = NULL;
2313
2314 /* If shadow use is a int->float cast then insert a second IV
Devang Patel54153272008-08-27 17:50:18 +00002315 to eliminate this cast.
Devang Patela0b39092008-08-26 17:57:54 +00002316
2317 for (unsigned i = 0; i < n; ++i)
2318 foo((double)i);
2319
Devang Patel54153272008-08-27 17:50:18 +00002320 is transformed into
Devang Patela0b39092008-08-26 17:57:54 +00002321
2322 double d = 0.0;
2323 for (unsigned i = 0; i < n; ++i, ++d)
2324 foo(d);
2325 */
Devang Patel54153272008-08-27 17:50:18 +00002326 if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->User))
Devang Patela0b39092008-08-26 17:57:54 +00002327 DestTy = UCast->getDestTy();
Devang Patel54153272008-08-27 17:50:18 +00002328 else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->User))
Devang Patela0b39092008-08-26 17:57:54 +00002329 DestTy = SCast->getDestTy();
Devang Patel18bb2782008-08-27 20:55:23 +00002330 if (!DestTy) continue;
2331
2332 if (TLI) {
2333 /* If target does not support DestTy natively then do not apply
2334 this transformation. */
2335 MVT DVT = TLI->getValueType(DestTy);
2336 if (!TLI->isTypeLegal(DVT)) continue;
2337 }
2338
Devang Patela0b39092008-08-26 17:57:54 +00002339 PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
2340 if (!PH) continue;
2341 if (PH->getNumIncomingValues() != 2) continue;
2342
2343 const Type *SrcTy = PH->getType();
2344 int Mantissa = DestTy->getFPMantissaWidth();
2345 if (Mantissa == -1) continue;
2346 if ((int)TD->getTypeSizeInBits(SrcTy) > Mantissa)
2347 continue;
2348
2349 unsigned Entry, Latch;
2350 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
2351 Entry = 0;
2352 Latch = 1;
2353 } else {
2354 Entry = 1;
2355 Latch = 0;
2356 }
2357
2358 ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
2359 if (!Init) continue;
2360 ConstantFP *NewInit = ConstantFP::get(DestTy, Init->getZExtValue());
2361
2362 BinaryOperator *Incr =
2363 dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
2364 if (!Incr) continue;
2365 if (Incr->getOpcode() != Instruction::Add
2366 && Incr->getOpcode() != Instruction::Sub)
2367 continue;
2368
2369 /* Initialize new IV, double d = 0.0 in above example. */
2370 ConstantInt *C = NULL;
2371 if (Incr->getOperand(0) == PH)
2372 C = dyn_cast<ConstantInt>(Incr->getOperand(1));
2373 else if (Incr->getOperand(1) == PH)
2374 C = dyn_cast<ConstantInt>(Incr->getOperand(0));
2375 else
2376 continue;
2377
2378 if (!C) continue;
2379
2380 /* Add new PHINode. */
2381 PHINode *NewPH = PHINode::Create(DestTy, "IV.S.", PH);
2382
Devang Patel54153272008-08-27 17:50:18 +00002383 /* create new increment. '++d' in above example. */
Devang Patela0b39092008-08-26 17:57:54 +00002384 ConstantFP *CFP = ConstantFP::get(DestTy, C->getZExtValue());
2385 BinaryOperator *NewIncr =
2386 BinaryOperator::Create(Incr->getOpcode(),
2387 NewPH, CFP, "IV.S.next.", Incr);
2388
2389 NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
2390 NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
2391
2392 /* Remove cast operation */
2393 SE->deleteValueFromRecords(ShadowUse);
2394 ShadowUse->replaceAllUsesWith(NewPH);
2395 ShadowUse->eraseFromParent();
2396 SI->second.Users.erase(CandidateUI);
2397 NumShadow++;
2398 break;
2399 }
2400 }
2401}
2402
Chris Lattner010de252005-08-08 05:28:22 +00002403// OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
2404// uses in the loop, look to see if we can eliminate some, in favor of using
2405// common indvars for the different uses.
2406void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
2407 // TODO: implement optzns here.
2408
Devang Patela0b39092008-08-26 17:57:54 +00002409 OptimizeShadowIV(L);
2410
Chris Lattner010de252005-08-08 05:28:22 +00002411 // Finally, get the terminating condition for the loop if possible. If we
2412 // can, we want to change it to use a post-incremented version of its
Chris Lattner98d98112006-03-24 07:14:34 +00002413 // induction variable, to allow coalescing the live ranges for the IV into
Chris Lattner010de252005-08-08 05:28:22 +00002414 // one register value.
2415 PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
2416 BasicBlock *Preheader = L->getLoopPreheader();
2417 BasicBlock *LatchBlock =
2418 SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
2419 BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002420 if (!TermBr || TermBr->isUnconditional() ||
2421 !isa<ICmpInst>(TermBr->getCondition()))
Chris Lattner010de252005-08-08 05:28:22 +00002422 return;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002423 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
Chris Lattner010de252005-08-08 05:28:22 +00002424
2425 // Search IVUsesByStride to find Cond's IVUse if there is one.
2426 IVStrideUse *CondUse = 0;
Chris Lattner50fad702005-08-10 00:45:21 +00002427 const SCEVHandle *CondStride = 0;
Chris Lattner010de252005-08-08 05:28:22 +00002428
Devang Patelc677de22008-08-13 20:31:11 +00002429 if (!FindIVUserForCond(Cond, CondUse, CondStride))
Chris Lattneraed01d12007-04-03 05:11:24 +00002430 return; // setcc doesn't use the IV.
Evan Chengcdf43b12007-10-25 09:11:16 +00002431
Dan Gohmanad7321f2008-09-15 21:22:06 +00002432 // If the trip count is computed in terms of an smax (due to ScalarEvolution
2433 // being unable to find a sufficient guard, for example), change the loop
2434 // comparison to use SLT instead of NE.
2435 Cond = OptimizeSMax(L, Cond, CondUse);
2436
Evan Chengcdf43b12007-10-25 09:11:16 +00002437 // If possible, change stride and operands of the compare instruction to
2438 // eliminate one stride.
2439 Cond = ChangeCompareStride(L, Cond, CondUse, CondStride);
Chris Lattner010de252005-08-08 05:28:22 +00002440
Chris Lattner010de252005-08-08 05:28:22 +00002441 // It's possible for the setcc instruction to be anywhere in the loop, and
2442 // possible for it to have multiple users. If it is not immediately before
2443 // the latch block branch, move it.
2444 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
2445 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
2446 Cond->moveBefore(TermBr);
2447 } else {
2448 // Otherwise, clone the terminating condition and insert into the loopend.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002449 Cond = cast<ICmpInst>(Cond->clone());
Chris Lattner010de252005-08-08 05:28:22 +00002450 Cond->setName(L->getHeader()->getName() + ".termcond");
2451 LatchBlock->getInstList().insert(TermBr, Cond);
2452
2453 // Clone the IVUse, as the old use still exists!
Chris Lattner50fad702005-08-10 00:45:21 +00002454 IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
Chris Lattner010de252005-08-08 05:28:22 +00002455 CondUse->OperandValToReplace);
Chris Lattner50fad702005-08-10 00:45:21 +00002456 CondUse = &IVUsesByStride[*CondStride].Users.back();
Chris Lattner010de252005-08-08 05:28:22 +00002457 }
2458 }
2459
2460 // If we get to here, we know that we can transform the setcc instruction to
Chris Lattner98d98112006-03-24 07:14:34 +00002461 // use the post-incremented version of the IV, allowing us to coalesce the
Chris Lattner010de252005-08-08 05:28:22 +00002462 // live ranges for the IV correctly.
Dan Gohman246b2562007-10-22 18:31:58 +00002463 CondUse->Offset = SE->getMinusSCEV(CondUse->Offset, *CondStride);
Chris Lattner010de252005-08-08 05:28:22 +00002464 CondUse->isUseOfPostIncrementedValue = true;
Evan Cheng1ce75dc2008-07-07 19:51:32 +00002465 Changed = true;
Chris Lattner010de252005-08-08 05:28:22 +00002466}
Nate Begeman16997482005-07-30 00:15:07 +00002467
Devang Patel0f54dcb2007-03-06 21:14:09 +00002468bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager &LPM) {
Nate Begemaneaa13852004-10-18 21:08:22 +00002469
Devang Patel0f54dcb2007-03-06 21:14:09 +00002470 LI = &getAnalysis<LoopInfo>();
Devang Patelb7d9dfc2007-06-07 21:42:15 +00002471 DT = &getAnalysis<DominatorTree>();
Devang Patel0f54dcb2007-03-06 21:14:09 +00002472 SE = &getAnalysis<ScalarEvolution>();
2473 TD = &getAnalysis<TargetData>();
2474 UIntPtrTy = TD->getIntPtrType();
Dan Gohman3fea6432008-07-14 17:55:01 +00002475 Changed = false;
Devang Patel0f54dcb2007-03-06 21:14:09 +00002476
Dale Johannesenb0390622008-12-16 22:16:28 +00002477 // Find all uses of induction variables in this loop, and categorize
Nate Begeman16997482005-07-30 00:15:07 +00002478 // them by stride. Start by finding all of the PHI nodes in the header for
2479 // this loop. If they are induction variables, inspect their uses.
Evan Cheng168a66b2007-10-26 23:08:19 +00002480 SmallPtrSet<Instruction*,16> Processed; // Don't reprocess instructions.
Nate Begeman16997482005-07-30 00:15:07 +00002481 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
Chris Lattner3416e5f2005-08-04 17:40:30 +00002482 AddUsersIfInteresting(I, L, Processed);
Nate Begemaneaa13852004-10-18 21:08:22 +00002483
Evan Cheng1ce75dc2008-07-07 19:51:32 +00002484 if (!IVUsesByStride.empty()) {
Dan Gohman80b0f8c2009-03-09 20:34:59 +00002485#ifndef NDEBUG
2486 DOUT << "\nLSR on \"" << L->getHeader()->getParent()->getNameStart()
2487 << "\" ";
2488 DEBUG(L->dump());
2489#endif
2490
Dan Gohmanf7912df2009-03-09 20:46:50 +00002491 // Sort the StrideOrder so we process larger strides first.
Dan Gohman2d1be872009-04-16 03:18:22 +00002492 std::stable_sort(StrideOrder.begin(), StrideOrder.end(), StrideCompare(TD));
Dan Gohmanf7912df2009-03-09 20:46:50 +00002493
Evan Cheng1ce75dc2008-07-07 19:51:32 +00002494 // Optimize induction variables. Some indvar uses can be transformed to use
2495 // strides that will be needed for other purposes. A common example of this
2496 // is the exit test for the loop, which can often be rewritten to use the
2497 // computation of some other indvar to decide when to terminate the loop.
2498 OptimizeIndvars(L);
Chris Lattner010de252005-08-08 05:28:22 +00002499
Evan Cheng1ce75dc2008-07-07 19:51:32 +00002500 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
2501 // doing computation in byte values, promote to 32-bit values if safe.
Chris Lattner010de252005-08-08 05:28:22 +00002502
Evan Cheng1ce75dc2008-07-07 19:51:32 +00002503 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
2504 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should
2505 // be codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC.
2506 // Need to be careful that IV's are all the same type. Only works for
2507 // intptr_t indvars.
Misha Brukmanfd939082005-04-21 23:48:37 +00002508
Evan Cheng1ce75dc2008-07-07 19:51:32 +00002509 // IVsByStride keeps IVs for one particular loop.
2510 assert(IVsByStride.empty() && "Stale entries in IVsByStride?");
Evan Chengd1d6b5c2006-03-16 21:53:05 +00002511
Evan Cheng1ce75dc2008-07-07 19:51:32 +00002512 // Note: this processes each stride/type pair individually. All users
2513 // passed into StrengthReduceStridedIVUsers have the same type AND stride.
2514 // Also, note that we iterate over IVUsesByStride indirectly by using
2515 // StrideOrder. This extra layer of indirection makes the ordering of
2516 // strides deterministic - not dependent on map order.
2517 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
2518 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
2519 IVUsesByStride.find(StrideOrder[Stride]);
2520 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
Dan Gohman9f4ac312009-03-09 20:41:15 +00002521 StrengthReduceStridedIVUsers(SI->first, SI->second, L);
Evan Cheng1ce75dc2008-07-07 19:51:32 +00002522 }
Chris Lattner7305ae22005-10-09 06:20:55 +00002523 }
Nate Begemaneaa13852004-10-18 21:08:22 +00002524
Dan Gohman010ee2d2008-05-21 00:54:12 +00002525 // We're done analyzing this loop; release all the state we built up for it.
Dan Gohman010ee2d2008-05-21 00:54:12 +00002526 IVUsesByStride.clear();
2527 IVsByStride.clear();
2528 StrideOrder.clear();
2529
Nate Begemaneaa13852004-10-18 21:08:22 +00002530 // Clean up after ourselves
2531 if (!DeadInsts.empty()) {
Chris Lattnera68d4ca2008-12-01 06:14:28 +00002532 DeleteTriviallyDeadInstructions();
Nate Begemaneaa13852004-10-18 21:08:22 +00002533
Nate Begeman16997482005-07-30 00:15:07 +00002534 BasicBlock::iterator I = L->getHeader()->begin();
Dan Gohmancbfe5bb2008-06-22 20:44:02 +00002535 while (PHINode *PN = dyn_cast<PHINode>(I++)) {
2536 // At this point, we know that we have killed one or more IV users.
Chris Lattnerbfcee362008-12-01 06:11:32 +00002537 // It is worth checking to see if the cannonical indvar is also
Dan Gohmancbfe5bb2008-06-22 20:44:02 +00002538 // dead, so that we can remove it as well.
2539 //
2540 // We can remove a PHI if it is on a cycle in the def-use graph
2541 // where each node in the cycle has degree one, i.e. only one use,
2542 // and is an instruction with no side effects.
2543 //
Nate Begeman16997482005-07-30 00:15:07 +00002544 // FIXME: this needs to eliminate an induction variable even if it's being
2545 // compared against some value to decide loop termination.
Chris Lattnera0d44862008-11-27 23:00:20 +00002546 if (!PN->hasOneUse())
2547 continue;
2548
2549 SmallPtrSet<PHINode *, 4> PHIs;
2550 for (Instruction *J = dyn_cast<Instruction>(*PN->use_begin());
2551 J && J->hasOneUse() && !J->mayWriteToMemory();
2552 J = dyn_cast<Instruction>(*J->use_begin())) {
2553 // If we find the original PHI, we've discovered a cycle.
2554 if (J == PN) {
2555 // Break the cycle and mark the PHI for deletion.
2556 SE->deleteValueFromRecords(PN);
2557 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattner09fb7da2008-12-01 06:27:41 +00002558 DeadInsts.push_back(PN);
Chris Lattnera0d44862008-11-27 23:00:20 +00002559 Changed = true;
2560 break;
Chris Lattner7e608bb2005-08-02 02:52:02 +00002561 }
Chris Lattnera0d44862008-11-27 23:00:20 +00002562 // If we find a PHI more than once, we're on a cycle that
2563 // won't prove fruitful.
2564 if (isa<PHINode>(J) && !PHIs.insert(cast<PHINode>(J)))
2565 break;
Nate Begeman16997482005-07-30 00:15:07 +00002566 }
Nate Begemaneaa13852004-10-18 21:08:22 +00002567 }
Chris Lattnera68d4ca2008-12-01 06:14:28 +00002568 DeleteTriviallyDeadInstructions();
Nate Begemaneaa13852004-10-18 21:08:22 +00002569 }
Evan Cheng1ce75dc2008-07-07 19:51:32 +00002570 return Changed;
Nate Begemaneaa13852004-10-18 21:08:22 +00002571}