blob: 557f34bc14e27712509916f52be76d1207f15d98 [file] [log] [blame]
Dan Gohman01c2ee72009-04-16 03:18:22 +00001//===- LoopStrengthReduce.cpp - Strength Reduce IVs in Loops --------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass performs a strength reduction on array references inside loops that
Dan Gohman01c2ee72009-04-16 03:18:22 +000011// have as one or more of their components the loop induction variable.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "loop-reduce"
16#include "llvm/Transforms/Scalar.h"
17#include "llvm/Constants.h"
18#include "llvm/Instructions.h"
19#include "llvm/IntrinsicInst.h"
20#include "llvm/Type.h"
21#include "llvm/DerivedTypes.h"
22#include "llvm/Analysis/Dominators.h"
Dan Gohman28055122009-05-12 02:17:14 +000023#include "llvm/Analysis/IVUsers.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000024#include "llvm/Analysis/LoopInfo.h"
25#include "llvm/Analysis/LoopPass.h"
26#include "llvm/Analysis/ScalarEvolutionExpander.h"
Evan Chengf2704c02009-02-21 02:06:47 +000027#include "llvm/Transforms/Utils/AddrModeMatcher.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000028#include "llvm/Transforms/Utils/BasicBlockUtils.h"
29#include "llvm/Transforms/Utils/Local.h"
Evan Cheng635b8f82007-10-26 23:08:19 +000030#include "llvm/ADT/SmallPtrSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000031#include "llvm/ADT/Statistic.h"
Evan Chengf2704c02009-02-21 02:06:47 +000032#include "llvm/Support/CFG.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000033#include "llvm/Support/Debug.h"
34#include "llvm/Support/Compiler.h"
Dan Gohman7cb042d2009-02-20 04:17:46 +000035#include "llvm/Support/CommandLine.h"
Dan Gohman93efe962009-05-02 18:29:22 +000036#include "llvm/Support/ValueHandle.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000037#include "llvm/Target/TargetLowering.h"
38#include <algorithm>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000039using namespace llvm;
40
Dan Gohman14de9b72009-04-16 16:46:01 +000041STATISTIC(NumReduced , "Number of IV uses strength reduced");
Evan Cheng335d87d2007-10-25 09:11:16 +000042STATISTIC(NumInserted, "Number of PHIs inserted");
43STATISTIC(NumVariable, "Number of PHIs with variable strides");
Devang Patelc1fc0fc2008-08-27 17:50:18 +000044STATISTIC(NumEliminated, "Number of strides eliminated");
45STATISTIC(NumShadow, "Number of Shadow IVs optimized");
Evan Chengf2704c02009-02-21 02:06:47 +000046STATISTIC(NumImmSunk, "Number of common expr immediates sunk into uses");
Evan Cheng56cfcd72009-05-11 22:33:01 +000047STATISTIC(NumLoopCond, "Number of loop terminating conds optimized");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000048
Dan Gohman7cb042d2009-02-20 04:17:46 +000049static cl::opt<bool> EnableFullLSRMode("enable-full-lsr",
50 cl::init(false),
51 cl::Hidden);
52
Dan Gohmanf17a25c2007-07-18 16:29:46 +000053namespace {
54
55 struct BasedUser;
56
Dan Gohmanf17a25c2007-07-18 16:29:46 +000057 /// IVInfo - This structure keeps track of one IV expression inserted during
58 /// StrengthReduceStridedIVUsers. It contains the stride, the common base, as
59 /// well as the PHI node and increment value created for rewrite.
60 struct VISIBILITY_HIDDEN IVExpr {
61 SCEVHandle Stride;
62 SCEVHandle Base;
63 PHINode *PHI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000064
Dan Gohman8b90e742009-03-09 22:04:01 +000065 IVExpr(const SCEVHandle &stride, const SCEVHandle &base, PHINode *phi)
66 : Stride(stride), Base(base), PHI(phi) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000067 };
68
69 /// IVsOfOneStride - This structure keeps track of all IV expression inserted
70 /// during StrengthReduceStridedIVUsers for a particular stride of the IV.
71 struct VISIBILITY_HIDDEN IVsOfOneStride {
72 std::vector<IVExpr> IVs;
73
Dan Gohman8b90e742009-03-09 22:04:01 +000074 void addIV(const SCEVHandle &Stride, const SCEVHandle &Base, PHINode *PHI) {
75 IVs.push_back(IVExpr(Stride, Base, PHI));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000076 }
77 };
78
79 class VISIBILITY_HIDDEN LoopStrengthReduce : public LoopPass {
Dan Gohman28055122009-05-12 02:17:14 +000080 IVUsers *IU;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000081 LoopInfo *LI;
82 DominatorTree *DT;
83 ScalarEvolution *SE;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000084 bool Changed;
85
Dan Gohmanf17a25c2007-07-18 16:29:46 +000086 /// IVsByStride - Keep track of all IVs that have been inserted for a
87 /// particular stride.
88 std::map<SCEVHandle, IVsOfOneStride> IVsByStride;
89
Evan Cheng56cfcd72009-05-11 22:33:01 +000090 /// StrideNoReuse - Keep track of all the strides whose ivs cannot be
91 /// reused (nor should they be rewritten to reuse other strides).
92 SmallSet<SCEVHandle, 4> StrideNoReuse;
93
Dan Gohmanf17a25c2007-07-18 16:29:46 +000094 /// DeadInsts - Keep track of instructions we may have made dead, so that
95 /// we can remove them after we are done working.
Dan Gohman28055122009-05-12 02:17:14 +000096 SmallVector<WeakVH, 16> DeadInsts;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000097
98 /// TLI - Keep a pointer of a TargetLowering to consult for determining
99 /// transformation profitability.
100 const TargetLowering *TLI;
101
102 public:
103 static char ID; // Pass ID, replacement for typeid
Dan Gohman34c280e2007-08-01 15:32:29 +0000104 explicit LoopStrengthReduce(const TargetLowering *tli = NULL) :
Dan Gohman26f8c272008-09-04 17:05:41 +0000105 LoopPass(&ID), TLI(tli) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000106 }
107
108 bool runOnLoop(Loop *L, LPPassManager &LPM);
109
110 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
111 // We split critical edges, so we change the CFG. However, we do update
112 // many analyses if they are around.
113 AU.addPreservedID(LoopSimplifyID);
114 AU.addPreserved<LoopInfo>();
115 AU.addPreserved<DominanceFrontier>();
116 AU.addPreserved<DominatorTree>();
117
118 AU.addRequiredID(LoopSimplifyID);
119 AU.addRequired<LoopInfo>();
120 AU.addRequired<DominatorTree>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000121 AU.addRequired<ScalarEvolution>();
Devang Patele4a78772008-08-26 17:57:54 +0000122 AU.addPreserved<ScalarEvolution>();
Dan Gohman28055122009-05-12 02:17:14 +0000123 AU.addRequired<IVUsers>();
124 AU.addPreserved<IVUsers>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000125 }
Dan Gohman01c2ee72009-04-16 03:18:22 +0000126
Dan Gohman63fcfae2009-05-01 16:56:32 +0000127 private:
Evan Cheng335d87d2007-10-25 09:11:16 +0000128 ICmpInst *ChangeCompareStride(Loop *L, ICmpInst *Cond,
129 IVStrideUse* &CondUse,
130 const SCEVHandle* &CondStride);
Evan Cheng5316a262009-05-09 01:08:24 +0000131
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000132 void OptimizeIndvars(Loop *L);
Dale Johannesen0b31ad52009-05-11 17:15:42 +0000133 void OptimizeLoopCountIV(Loop *L);
Evan Cheng5316a262009-05-09 01:08:24 +0000134 void OptimizeLoopTermCond(Loop *L);
135
Devang Patele4a78772008-08-26 17:57:54 +0000136 /// OptimizeShadowIV - If IV is used in a int-to-float cast
137 /// inside the loop then try to eliminate the cast opeation.
138 void OptimizeShadowIV(Loop *L);
139
Dan Gohman156bf982008-09-15 21:22:06 +0000140 /// OptimizeSMax - Rewrite the loop's terminating condition
141 /// if it uses an smax computation.
142 ICmpInst *OptimizeSMax(Loop *L, ICmpInst *Cond,
143 IVStrideUse* &CondUse);
144
Devang Patel7983eaa2008-08-13 20:31:11 +0000145 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse,
Devang Patele4a78772008-08-26 17:57:54 +0000146 const SCEVHandle *&CondStride);
Evan Cheng5385ab72007-10-25 22:45:20 +0000147 bool RequiresTypeConversion(const Type *Ty, const Type *NewTy);
Dale Johannesen671a23c2009-01-14 02:35:31 +0000148 SCEVHandle CheckForIVReuse(bool, bool, bool, const SCEVHandle&,
Dan Gohman5766ac72007-10-22 20:40:42 +0000149 IVExpr&, const Type*,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000150 const std::vector<BasedUser>& UsersToProcess);
Evan Cheng56cfcd72009-05-11 22:33:01 +0000151 bool ValidScale(bool, int64_t,
152 const std::vector<BasedUser>& UsersToProcess);
Dan Gohman28055122009-05-12 02:17:14 +0000153 bool ValidOffset(bool, int64_t, int64_t,
154 const std::vector<BasedUser>& UsersToProcess);
Evan Cheng5385ab72007-10-25 22:45:20 +0000155 SCEVHandle CollectIVUsers(const SCEVHandle &Stride,
156 IVUsersOfOneStride &Uses,
157 Loop *L,
158 bool &AllUsesAreAddresses,
Dale Johannesen7b7b3d42008-12-16 22:16:28 +0000159 bool &AllUsesAreOutsideLoop,
Evan Cheng5385ab72007-10-25 22:45:20 +0000160 std::vector<BasedUser> &UsersToProcess);
Dan Gohman7cb042d2009-02-20 04:17:46 +0000161 bool ShouldUseFullStrengthReductionMode(
162 const std::vector<BasedUser> &UsersToProcess,
163 const Loop *L,
164 bool AllUsesAreAddresses,
165 SCEVHandle Stride);
166 void PrepareToStrengthReduceFully(
167 std::vector<BasedUser> &UsersToProcess,
168 SCEVHandle Stride,
169 SCEVHandle CommonExprs,
170 const Loop *L,
171 SCEVExpander &PreheaderRewriter);
172 void PrepareToStrengthReduceFromSmallerStride(
173 std::vector<BasedUser> &UsersToProcess,
174 Value *CommonBaseV,
175 const IVExpr &ReuseIV,
176 Instruction *PreInsertPt);
177 void PrepareToStrengthReduceWithNewPhi(
178 std::vector<BasedUser> &UsersToProcess,
179 SCEVHandle Stride,
180 SCEVHandle CommonExprs,
181 Value *CommonBaseV,
Evan Cheng56cfcd72009-05-11 22:33:01 +0000182 Instruction *IVIncInsertPt,
Dan Gohman7cb042d2009-02-20 04:17:46 +0000183 const Loop *L,
184 SCEVExpander &PreheaderRewriter);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000185 void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
186 IVUsersOfOneStride &Uses,
Dan Gohman8f4faa02009-03-09 20:41:15 +0000187 Loop *L);
Chris Lattner3b39baa2008-12-01 06:14:28 +0000188 void DeleteTriviallyDeadInstructions();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000189 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000190}
191
Dan Gohman089efff2008-05-13 00:00:25 +0000192char LoopStrengthReduce::ID = 0;
193static RegisterPass<LoopStrengthReduce>
194X("loop-reduce", "Loop Strength Reduction");
195
Daniel Dunbar163555a2008-10-22 23:32:42 +0000196Pass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000197 return new LoopStrengthReduce(TLI);
198}
199
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000200/// DeleteTriviallyDeadInstructions - If any of the instructions is the
201/// specified set are trivially dead, delete them and see if this makes any of
202/// their operands subsequently dead.
Chris Lattner3b39baa2008-12-01 06:14:28 +0000203void LoopStrengthReduce::DeleteTriviallyDeadInstructions() {
Chris Lattner18088ad2008-12-01 06:27:41 +0000204 if (DeadInsts.empty()) return;
205
Chris Lattner3b39baa2008-12-01 06:14:28 +0000206 while (!DeadInsts.empty()) {
Dan Gohman28055122009-05-12 02:17:14 +0000207 Instruction *I = dyn_cast_or_null<Instruction>(DeadInsts.back());
Chris Lattner3b39baa2008-12-01 06:14:28 +0000208 DeadInsts.pop_back();
Chris Lattner18088ad2008-12-01 06:27:41 +0000209
210 if (I == 0 || !isInstructionTriviallyDead(I))
Chris Lattner2757a1d2008-12-01 06:11:32 +0000211 continue;
212
Chris Lattner18088ad2008-12-01 06:27:41 +0000213 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI) {
214 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
215 *OI = 0;
Chris Lattner2757a1d2008-12-01 06:11:32 +0000216 if (U->use_empty())
Chris Lattner18088ad2008-12-01 06:27:41 +0000217 DeadInsts.push_back(U);
Bill Wendlinge7e59722008-11-29 03:43:04 +0000218 }
219 }
Chris Lattner2757a1d2008-12-01 06:11:32 +0000220
221 I->eraseFromParent();
222 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000223 }
224}
225
Dale Johannesen671a23c2009-01-14 02:35:31 +0000226/// containsAddRecFromDifferentLoop - Determine whether expression S involves a
227/// subexpression that is an AddRec from a loop other than L. An outer loop
228/// of L is OK, but not an inner loop nor a disjoint loop.
229static bool containsAddRecFromDifferentLoop(SCEVHandle S, Loop *L) {
230 // This is very common, put it first.
231 if (isa<SCEVConstant>(S))
232 return false;
Dan Gohman9a769972009-04-18 17:56:28 +0000233 if (const SCEVCommutativeExpr *AE = dyn_cast<SCEVCommutativeExpr>(S)) {
Dale Johannesen671a23c2009-01-14 02:35:31 +0000234 for (unsigned int i=0; i< AE->getNumOperands(); i++)
235 if (containsAddRecFromDifferentLoop(AE->getOperand(i), L))
236 return true;
237 return false;
238 }
Dan Gohman9a769972009-04-18 17:56:28 +0000239 if (const SCEVAddRecExpr *AE = dyn_cast<SCEVAddRecExpr>(S)) {
Dale Johannesen671a23c2009-01-14 02:35:31 +0000240 if (const Loop *newLoop = AE->getLoop()) {
241 if (newLoop == L)
242 return false;
243 // if newLoop is an outer loop of L, this is OK.
244 if (!LoopInfoBase<BasicBlock>::isNotAlreadyContainedIn(L, newLoop))
245 return false;
246 }
247 return true;
248 }
Dan Gohman9a769972009-04-18 17:56:28 +0000249 if (const SCEVUDivExpr *DE = dyn_cast<SCEVUDivExpr>(S))
Dale Johannesen671a23c2009-01-14 02:35:31 +0000250 return containsAddRecFromDifferentLoop(DE->getLHS(), L) ||
251 containsAddRecFromDifferentLoop(DE->getRHS(), L);
252#if 0
253 // SCEVSDivExpr has been backed out temporarily, but will be back; we'll
254 // need this when it is.
Dan Gohman9a769972009-04-18 17:56:28 +0000255 if (const SCEVSDivExpr *DE = dyn_cast<SCEVSDivExpr>(S))
Dale Johannesen671a23c2009-01-14 02:35:31 +0000256 return containsAddRecFromDifferentLoop(DE->getLHS(), L) ||
257 containsAddRecFromDifferentLoop(DE->getRHS(), L);
258#endif
Dan Gohman2a381532009-04-21 01:25:57 +0000259 if (const SCEVCastExpr *CE = dyn_cast<SCEVCastExpr>(S))
260 return containsAddRecFromDifferentLoop(CE->getOperand(), L);
Dale Johannesen671a23c2009-01-14 02:35:31 +0000261 return false;
262}
263
Dan Gohmanb3b3c552009-02-18 00:08:39 +0000264/// isAddressUse - Returns true if the specified instruction is using the
Dale Johannesen64660e92008-12-05 21:47:27 +0000265/// specified value as an address.
266static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
267 bool isAddress = isa<LoadInst>(Inst);
268 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
269 if (SI->getOperand(1) == OperandVal)
270 isAddress = true;
271 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
272 // Addressing modes can also be folded into prefetches and a variety
273 // of intrinsics.
274 switch (II->getIntrinsicID()) {
275 default: break;
276 case Intrinsic::prefetch:
277 case Intrinsic::x86_sse2_loadu_dq:
278 case Intrinsic::x86_sse2_loadu_pd:
279 case Intrinsic::x86_sse_loadu_ps:
280 case Intrinsic::x86_sse_storeu_ps:
281 case Intrinsic::x86_sse2_storeu_pd:
282 case Intrinsic::x86_sse2_storeu_dq:
283 case Intrinsic::x86_sse2_storel_dq:
284 if (II->getOperand(1) == OperandVal)
285 isAddress = true;
286 break;
287 }
288 }
289 return isAddress;
290}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000291
Dan Gohmanc0cefca2009-03-09 21:01:17 +0000292/// getAccessType - Return the type of the memory being accessed.
293static const Type *getAccessType(const Instruction *Inst) {
Dan Gohmanb55ee6b2009-05-18 16:45:28 +0000294 const Type *AccessTy = Inst->getType();
Dan Gohmanc0cefca2009-03-09 21:01:17 +0000295 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst))
Dan Gohmanb55ee6b2009-05-18 16:45:28 +0000296 AccessTy = SI->getOperand(0)->getType();
Dan Gohmanc0cefca2009-03-09 21:01:17 +0000297 else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
298 // Addressing modes can also be folded into prefetches and a variety
299 // of intrinsics.
300 switch (II->getIntrinsicID()) {
301 default: break;
302 case Intrinsic::x86_sse_storeu_ps:
303 case Intrinsic::x86_sse2_storeu_pd:
304 case Intrinsic::x86_sse2_storeu_dq:
305 case Intrinsic::x86_sse2_storel_dq:
Dan Gohmanb55ee6b2009-05-18 16:45:28 +0000306 AccessTy = II->getOperand(1)->getType();
Dan Gohmanc0cefca2009-03-09 21:01:17 +0000307 break;
308 }
309 }
Dan Gohmanb55ee6b2009-05-18 16:45:28 +0000310 return AccessTy;
Dan Gohmanc0cefca2009-03-09 21:01:17 +0000311}
312
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000313namespace {
314 /// BasedUser - For a particular base value, keep information about how we've
315 /// partitioned the expression so far.
316 struct BasedUser {
Dan Gohman89f85052007-10-22 18:31:58 +0000317 /// SE - The current ScalarEvolution object.
318 ScalarEvolution *SE;
319
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000320 /// Base - The Base value for the PHI node that needs to be inserted for
321 /// this use. As the use is processed, information gets moved from this
322 /// field to the Imm field (below). BasedUser values are sorted by this
323 /// field.
324 SCEVHandle Base;
325
326 /// Inst - The instruction using the induction variable.
327 Instruction *Inst;
328
329 /// OperandValToReplace - The operand value of Inst to replace with the
330 /// EmittedBase.
331 Value *OperandValToReplace;
332
Dan Gohman28055122009-05-12 02:17:14 +0000333 /// isSigned - The stride (and thus also the Base) of this use may be in
334 /// a narrower type than the use itself (OperandValToReplace->getType()).
335 /// When this is the case, the isSigned field indicates whether the
336 /// IV expression should be signed-extended instead of zero-extended to
337 /// fit the type of the use.
338 bool isSigned;
339
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000340 /// Imm - The immediate value that should be added to the base immediately
341 /// before Inst, because it will be folded into the imm field of the
Dan Gohman8709c272009-02-20 20:29:04 +0000342 /// instruction. This is also sometimes used for loop-variant values that
343 /// must be added inside the loop.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000344 SCEVHandle Imm;
345
Dan Gohman7cb042d2009-02-20 04:17:46 +0000346 /// Phi - The induction variable that performs the striding that
347 /// should be used for this user.
Dan Gohman8b90e742009-03-09 22:04:01 +0000348 PHINode *Phi;
Dan Gohman7cb042d2009-02-20 04:17:46 +0000349
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000350 // isUseOfPostIncrementedValue - True if this should use the
351 // post-incremented version of this IV, not the preincremented version.
352 // This can only be set in special cases, such as the terminating setcc
353 // instruction for a loop and uses outside the loop that are dominated by
354 // the loop.
355 bool isUseOfPostIncrementedValue;
356
Dan Gohman89f85052007-10-22 18:31:58 +0000357 BasedUser(IVStrideUse &IVSU, ScalarEvolution *se)
Dan Gohman28055122009-05-12 02:17:14 +0000358 : SE(se), Base(IVSU.getOffset()), Inst(IVSU.getUser()),
359 OperandValToReplace(IVSU.getOperandValToReplace()),
360 isSigned(IVSU.isSigned()),
Dale Johannesenc71d8672008-12-03 22:43:56 +0000361 Imm(SE->getIntegerSCEV(0, Base->getType())),
Dan Gohman28055122009-05-12 02:17:14 +0000362 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue()) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000363
364 // Once we rewrite the code to insert the new IVs we want, update the
365 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
366 // to it.
367 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Dan Gohmana78c8752008-05-15 23:26:57 +0000368 Instruction *InsertPt,
Evan Chengf7ef8852007-10-30 23:45:15 +0000369 SCEVExpander &Rewriter, Loop *L, Pass *P,
Dan Gohmand0c01232009-05-19 02:15:55 +0000370 LoopInfo &LI,
Dan Gohman28055122009-05-12 02:17:14 +0000371 SmallVectorImpl<WeakVH> &DeadInsts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000372
373 Value *InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
Dan Gohman01c2ee72009-04-16 03:18:22 +0000374 const Type *Ty,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000375 SCEVExpander &Rewriter,
Dan Gohmand0c01232009-05-19 02:15:55 +0000376 Instruction *IP, Loop *L,
377 LoopInfo &LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000378 void dump() const;
379 };
380}
381
382void BasedUser::dump() const {
383 cerr << " Base=" << *Base;
384 cerr << " Imm=" << *Imm;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000385 cerr << " Inst: " << *Inst;
386}
387
388Value *BasedUser::InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
Dan Gohman01c2ee72009-04-16 03:18:22 +0000389 const Type *Ty,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000390 SCEVExpander &Rewriter,
Dan Gohmand0c01232009-05-19 02:15:55 +0000391 Instruction *IP, Loop *L,
392 LoopInfo &LI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000393 // Figure out where we *really* want to insert this code. In particular, if
394 // the user is inside of a loop that is nested inside of L, we really don't
395 // want to insert this expression before the user, we'd rather pull it out as
396 // many loops as possible.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000397 Instruction *BaseInsertPt = IP;
398
399 // Figure out the most-nested loop that IP is in.
400 Loop *InsertLoop = LI.getLoopFor(IP->getParent());
401
402 // If InsertLoop is not L, and InsertLoop is nested inside of L, figure out
403 // the preheader of the outer-most loop where NewBase is not loop invariant.
Dale Johannesenad1d7d02008-12-02 18:40:09 +0000404 if (L->contains(IP->getParent()))
405 while (InsertLoop && NewBase->isLoopInvariant(InsertLoop)) {
406 BaseInsertPt = InsertLoop->getLoopPreheader()->getTerminator();
407 InsertLoop = InsertLoop->getParentLoop();
408 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000409
Dan Gohmand0c01232009-05-19 02:15:55 +0000410 Value *Base = Rewriter.expandCodeFor(NewBase, 0, BaseInsertPt);
Dan Gohman28055122009-05-12 02:17:14 +0000411
412 SCEVHandle NewValSCEV = SE->getUnknown(Base);
Dan Gohman62d4cb02009-02-19 19:23:27 +0000413
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000414 // If there is no immediate value, skip the next part.
Dan Gohman28055122009-05-12 02:17:14 +0000415 if (!Imm->isZero()) {
416 // If we are inserting the base and imm values in the same block, make sure
417 // to adjust the IP position if insertion reused a result.
418 if (IP == BaseInsertPt)
419 IP = Rewriter.getInsertionPoint();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000420
Dan Gohman28055122009-05-12 02:17:14 +0000421 // Always emit the immediate (if non-zero) into the same block as the user.
422 NewValSCEV = SE->getAddExpr(NewValSCEV, Imm);
423 }
424
425 if (isSigned)
426 NewValSCEV = SE->getTruncateOrSignExtend(NewValSCEV, Ty);
427 else
428 NewValSCEV = SE->getTruncateOrZeroExtend(NewValSCEV, Ty);
429
Dan Gohman01c2ee72009-04-16 03:18:22 +0000430 return Rewriter.expandCodeFor(NewValSCEV, Ty, IP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000431}
432
433
434// Once we rewrite the code to insert the new IVs we want, update the
435// operands of Inst to use the new expression 'NewBase', with 'Imm' added
Dan Gohmana78c8752008-05-15 23:26:57 +0000436// to it. NewBasePt is the last instruction which contributes to the
437// value of NewBase in the case that it's a diffferent instruction from
438// the PHI that NewBase is computed from, or null otherwise.
439//
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000440void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Dan Gohmana78c8752008-05-15 23:26:57 +0000441 Instruction *NewBasePt,
Evan Chengf7ef8852007-10-30 23:45:15 +0000442 SCEVExpander &Rewriter, Loop *L, Pass *P,
Dan Gohmand0c01232009-05-19 02:15:55 +0000443 LoopInfo &LI,
Dan Gohman28055122009-05-12 02:17:14 +0000444 SmallVectorImpl<WeakVH> &DeadInsts) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000445 if (!isa<PHINode>(Inst)) {
446 // By default, insert code at the user instruction.
447 BasicBlock::iterator InsertPt = Inst;
448
449 // However, if the Operand is itself an instruction, the (potentially
450 // complex) inserted code may be shared by many users. Because of this, we
451 // want to emit code for the computation of the operand right before its old
452 // computation. This is usually safe, because we obviously used to use the
453 // computation when it was computed in its current block. However, in some
454 // cases (e.g. use of a post-incremented induction variable) the NewBase
455 // value will be pinned to live somewhere after the original computation.
456 // In this case, we have to back off.
Chris Lattnerdb4a4f42008-12-02 04:52:26 +0000457 //
458 // If this is a use outside the loop (which means after, since it is based
459 // on a loop indvar) we use the post-incremented value, so that we don't
460 // artificially make the preinc value live out the bottom of the loop.
Dale Johannesen20299b42008-12-01 22:00:01 +0000461 if (!isUseOfPostIncrementedValue && L->contains(Inst->getParent())) {
Dan Gohman50b570a2008-05-20 03:01:48 +0000462 if (NewBasePt && isa<PHINode>(OperandValToReplace)) {
Dan Gohmana78c8752008-05-15 23:26:57 +0000463 InsertPt = NewBasePt;
464 ++InsertPt;
Gabor Greif5e42ba12008-06-11 21:38:51 +0000465 } else if (Instruction *OpInst
466 = dyn_cast<Instruction>(OperandValToReplace)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000467 InsertPt = OpInst;
468 while (isa<PHINode>(InsertPt)) ++InsertPt;
469 }
470 }
Dan Gohman01c2ee72009-04-16 03:18:22 +0000471 Value *NewVal = InsertCodeForBaseAtPosition(NewBase,
472 OperandValToReplace->getType(),
Dan Gohmand0c01232009-05-19 02:15:55 +0000473 Rewriter, InsertPt, L, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000474 // Replace the use of the operand Value with the new Phi we just created.
475 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
Dan Gohman62d4cb02009-02-19 19:23:27 +0000476
Dan Gohman62d4cb02009-02-19 19:23:27 +0000477 DOUT << " Replacing with ";
Dan Gohman7e467912009-02-19 19:32:06 +0000478 DEBUG(WriteAsOperand(*DOUT, NewVal, /*PrintType=*/false));
Dan Gohman62d4cb02009-02-19 19:23:27 +0000479 DOUT << ", which has value " << *NewBase << " plus IMM " << *Imm << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000480 return;
481 }
Dan Gohman62d4cb02009-02-19 19:23:27 +0000482
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000483 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
484 // expression into each operand block that uses it. Note that PHI nodes can
485 // have multiple entries for the same predecessor. We use a map to make sure
486 // that a PHI node only has a single Value* for each predecessor (which also
487 // prevents us from inserting duplicate code in some blocks).
Evan Chengd7ea7002007-10-30 22:27:26 +0000488 DenseMap<BasicBlock*, Value*> InsertedCode;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000489 PHINode *PN = cast<PHINode>(Inst);
490 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
491 if (PN->getIncomingValue(i) == OperandValToReplace) {
Dale Johannesen671a23c2009-01-14 02:35:31 +0000492 // If the original expression is outside the loop, put the replacement
493 // code in the same place as the original expression,
494 // which need not be an immediate predecessor of this PHI. This way we
495 // need only one copy of it even if it is referenced multiple times in
496 // the PHI. We don't do this when the original expression is inside the
Dale Johannesendb25a832009-02-09 22:14:15 +0000497 // loop because multiple copies sometimes do useful sinking of code in
498 // that case(?).
Dale Johannesen671a23c2009-01-14 02:35:31 +0000499 Instruction *OldLoc = dyn_cast<Instruction>(OperandValToReplace);
500 if (L->contains(OldLoc->getParent())) {
Dale Johannesendb25a832009-02-09 22:14:15 +0000501 // If this is a critical edge, split the edge so that we do not insert
502 // the code on all predecessor/successor paths. We do this unless this
503 // is the canonical backedge for this loop, as this can make some
504 // inserted code be in an illegal position.
Dale Johannesen671a23c2009-01-14 02:35:31 +0000505 BasicBlock *PHIPred = PN->getIncomingBlock(i);
506 if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
507 (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
Dale Johannesen9bc52e12008-12-23 23:21:35 +0000508
Dale Johannesen671a23c2009-01-14 02:35:31 +0000509 // First step, split the critical edge.
510 SplitCriticalEdge(PHIPred, PN->getParent(), P, false);
511
512 // Next step: move the basic block. In particular, if the PHI node
513 // is outside of the loop, and PredTI is in the loop, we want to
514 // move the block to be immediately before the PHI block, not
515 // immediately after PredTI.
516 if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
517 BasicBlock *NewBB = PN->getIncomingBlock(i);
518 NewBB->moveBefore(PN->getParent());
519 }
520
521 // Splitting the edge can reduce the number of PHI entries we have.
522 e = PN->getNumIncomingValues();
523 }
524 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000525 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
526 if (!Code) {
527 // Insert the code into the end of the predecessor block.
Dale Johannesen671a23c2009-01-14 02:35:31 +0000528 Instruction *InsertPt = (L->contains(OldLoc->getParent())) ?
529 PN->getIncomingBlock(i)->getTerminator() :
530 OldLoc->getParent()->getTerminator();
Dan Gohman01c2ee72009-04-16 03:18:22 +0000531 Code = InsertCodeForBaseAtPosition(NewBase, PN->getType(),
Dan Gohmand0c01232009-05-19 02:15:55 +0000532 Rewriter, InsertPt, L, LI);
Dan Gohman62d4cb02009-02-19 19:23:27 +0000533
Dan Gohman62d4cb02009-02-19 19:23:27 +0000534 DOUT << " Changing PHI use to ";
Dan Gohman7e467912009-02-19 19:32:06 +0000535 DEBUG(WriteAsOperand(*DOUT, Code, /*PrintType=*/false));
Dan Gohman62d4cb02009-02-19 19:23:27 +0000536 DOUT << ", which has value " << *NewBase << " plus IMM " << *Imm << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000537 }
Dan Gohman62d4cb02009-02-19 19:23:27 +0000538
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000539 // Replace the use of the operand Value with the new Phi we just created.
540 PN->setIncomingValue(i, Code);
541 Rewriter.clear();
542 }
543 }
Evan Chengf7ef8852007-10-30 23:45:15 +0000544
545 // PHI node might have become a constant value after SplitCriticalEdge.
Chris Lattner18088ad2008-12-01 06:27:41 +0000546 DeadInsts.push_back(Inst);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000547}
548
549
Dale Johannesen64660e92008-12-05 21:47:27 +0000550/// fitsInAddressMode - Return true if V can be subsumed within an addressing
551/// mode, and does not need to be put in a register first.
Dan Gohmanb55ee6b2009-05-18 16:45:28 +0000552static bool fitsInAddressMode(const SCEVHandle &V, const Type *AccessTy,
Dale Johannesen64660e92008-12-05 21:47:27 +0000553 const TargetLowering *TLI, bool HasBaseReg) {
Dan Gohman9a769972009-04-18 17:56:28 +0000554 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000555 int64_t VC = SC->getValue()->getSExtValue();
556 if (TLI) {
557 TargetLowering::AddrMode AM;
558 AM.BaseOffs = VC;
Dale Johannesen64660e92008-12-05 21:47:27 +0000559 AM.HasBaseReg = HasBaseReg;
Dan Gohmanb55ee6b2009-05-18 16:45:28 +0000560 return TLI->isLegalAddressingMode(AM, AccessTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000561 } else {
562 // Defaults to PPC. PPC allows a sign-extended 16-bit immediate field.
563 return (VC > -(1 << 16) && VC < (1 << 16)-1);
564 }
565 }
566
Dan Gohman9a769972009-04-18 17:56:28 +0000567 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
Dan Gohman01c2ee72009-04-16 03:18:22 +0000568 if (GlobalValue *GV = dyn_cast<GlobalValue>(SU->getValue())) {
Dan Gohmanfd4a4962009-05-01 16:29:14 +0000569 if (TLI) {
570 TargetLowering::AddrMode AM;
571 AM.BaseGV = GV;
572 AM.HasBaseReg = HasBaseReg;
Dan Gohmanb55ee6b2009-05-18 16:45:28 +0000573 return TLI->isLegalAddressingMode(AM, AccessTy);
Dan Gohmanfd4a4962009-05-01 16:29:14 +0000574 } else {
575 // Default: assume global addresses are not legal.
576 }
Dan Gohman01c2ee72009-04-16 03:18:22 +0000577 }
578
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000579 return false;
580}
581
Dale Johannesen48e16f92008-12-03 20:56:12 +0000582/// MoveLoopVariantsToImmediateField - Move any subexpressions from Val that are
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000583/// loop varying to the Imm operand.
Dale Johannesen48e16f92008-12-03 20:56:12 +0000584static void MoveLoopVariantsToImmediateField(SCEVHandle &Val, SCEVHandle &Imm,
Evan Cheng56cfcd72009-05-11 22:33:01 +0000585 Loop *L, ScalarEvolution *SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000586 if (Val->isLoopInvariant(L)) return; // Nothing to do.
587
Dan Gohman9a769972009-04-18 17:56:28 +0000588 if (const SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000589 std::vector<SCEVHandle> NewOps;
590 NewOps.reserve(SAE->getNumOperands());
591
592 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
593 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
594 // If this is a loop-variant expression, it must stay in the immediate
595 // field of the expression.
Dan Gohman89f85052007-10-22 18:31:58 +0000596 Imm = SE->getAddExpr(Imm, SAE->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000597 } else {
598 NewOps.push_back(SAE->getOperand(i));
599 }
600
601 if (NewOps.empty())
Dan Gohman89f85052007-10-22 18:31:58 +0000602 Val = SE->getIntegerSCEV(0, Val->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000603 else
Dan Gohman89f85052007-10-22 18:31:58 +0000604 Val = SE->getAddExpr(NewOps);
Dan Gohman9a769972009-04-18 17:56:28 +0000605 } else if (const SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000606 // Try to pull immediates out of the start value of nested addrec's.
607 SCEVHandle Start = SARE->getStart();
Dale Johannesen48e16f92008-12-03 20:56:12 +0000608 MoveLoopVariantsToImmediateField(Start, Imm, L, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000609
610 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
611 Ops[0] = Start;
Dan Gohman89f85052007-10-22 18:31:58 +0000612 Val = SE->getAddRecExpr(Ops, SARE->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000613 } else {
614 // Otherwise, all of Val is variant, move the whole thing over.
Dan Gohman89f85052007-10-22 18:31:58 +0000615 Imm = SE->getAddExpr(Imm, Val);
616 Val = SE->getIntegerSCEV(0, Val->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000617 }
618}
619
620
621/// MoveImmediateValues - Look at Val, and pull out any additions of constants
622/// that can fit into the immediate field of instructions in the target.
623/// Accumulate these immediate values into the Imm value.
624static void MoveImmediateValues(const TargetLowering *TLI,
Dan Gohmanb55ee6b2009-05-18 16:45:28 +0000625 const Type *AccessTy,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000626 SCEVHandle &Val, SCEVHandle &Imm,
Dan Gohman89f85052007-10-22 18:31:58 +0000627 bool isAddress, Loop *L,
628 ScalarEvolution *SE) {
Dan Gohman9a769972009-04-18 17:56:28 +0000629 if (const SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000630 std::vector<SCEVHandle> NewOps;
631 NewOps.reserve(SAE->getNumOperands());
632
633 for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
634 SCEVHandle NewOp = SAE->getOperand(i);
Dan Gohmanb55ee6b2009-05-18 16:45:28 +0000635 MoveImmediateValues(TLI, AccessTy, NewOp, Imm, isAddress, L, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000636
637 if (!NewOp->isLoopInvariant(L)) {
638 // If this is a loop-variant expression, it must stay in the immediate
639 // field of the expression.
Dan Gohman89f85052007-10-22 18:31:58 +0000640 Imm = SE->getAddExpr(Imm, NewOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000641 } else {
642 NewOps.push_back(NewOp);
643 }
644 }
645
646 if (NewOps.empty())
Dan Gohman89f85052007-10-22 18:31:58 +0000647 Val = SE->getIntegerSCEV(0, Val->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000648 else
Dan Gohman89f85052007-10-22 18:31:58 +0000649 Val = SE->getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000650 return;
Dan Gohman9a769972009-04-18 17:56:28 +0000651 } else if (const SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000652 // Try to pull immediates out of the start value of nested addrec's.
653 SCEVHandle Start = SARE->getStart();
Dan Gohmanb55ee6b2009-05-18 16:45:28 +0000654 MoveImmediateValues(TLI, AccessTy, Start, Imm, isAddress, L, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000655
656 if (Start != SARE->getStart()) {
657 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
658 Ops[0] = Start;
Dan Gohman89f85052007-10-22 18:31:58 +0000659 Val = SE->getAddRecExpr(Ops, SARE->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000660 }
661 return;
Dan Gohman9a769972009-04-18 17:56:28 +0000662 } else if (const SCEVMulExpr *SME = dyn_cast<SCEVMulExpr>(Val)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000663 // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
Dan Gohmanb55ee6b2009-05-18 16:45:28 +0000664 if (isAddress &&
665 fitsInAddressMode(SME->getOperand(0), AccessTy, TLI, false) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000666 SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
667
Dan Gohman89f85052007-10-22 18:31:58 +0000668 SCEVHandle SubImm = SE->getIntegerSCEV(0, Val->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000669 SCEVHandle NewOp = SME->getOperand(1);
Dan Gohmanb55ee6b2009-05-18 16:45:28 +0000670 MoveImmediateValues(TLI, AccessTy, NewOp, SubImm, isAddress, L, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000671
672 // If we extracted something out of the subexpressions, see if we can
673 // simplify this!
674 if (NewOp != SME->getOperand(1)) {
675 // Scale SubImm up by "8". If the result is a target constant, we are
676 // good.
Dan Gohman89f85052007-10-22 18:31:58 +0000677 SubImm = SE->getMulExpr(SubImm, SME->getOperand(0));
Dan Gohmanb55ee6b2009-05-18 16:45:28 +0000678 if (fitsInAddressMode(SubImm, AccessTy, TLI, false)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000679 // Accumulate the immediate.
Dan Gohman89f85052007-10-22 18:31:58 +0000680 Imm = SE->getAddExpr(Imm, SubImm);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000681
682 // Update what is left of 'Val'.
Dan Gohman89f85052007-10-22 18:31:58 +0000683 Val = SE->getMulExpr(SME->getOperand(0), NewOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000684 return;
685 }
686 }
687 }
688 }
689
690 // Loop-variant expressions must stay in the immediate field of the
691 // expression.
Dan Gohmanb55ee6b2009-05-18 16:45:28 +0000692 if ((isAddress && fitsInAddressMode(Val, AccessTy, TLI, false)) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000693 !Val->isLoopInvariant(L)) {
Dan Gohman89f85052007-10-22 18:31:58 +0000694 Imm = SE->getAddExpr(Imm, Val);
695 Val = SE->getIntegerSCEV(0, Val->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000696 return;
697 }
698
699 // Otherwise, no immediates to move.
700}
701
Evan Chengf2704c02009-02-21 02:06:47 +0000702static void MoveImmediateValues(const TargetLowering *TLI,
703 Instruction *User,
704 SCEVHandle &Val, SCEVHandle &Imm,
705 bool isAddress, Loop *L,
706 ScalarEvolution *SE) {
Dan Gohmanb55ee6b2009-05-18 16:45:28 +0000707 const Type *AccessTy = getAccessType(User);
708 MoveImmediateValues(TLI, AccessTy, Val, Imm, isAddress, L, SE);
Evan Chengf2704c02009-02-21 02:06:47 +0000709}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000710
711/// SeparateSubExprs - Decompose Expr into all of the subexpressions that are
712/// added together. This is used to reassociate common addition subexprs
713/// together for maximal sharing when rewriting bases.
714static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
Dan Gohman89f85052007-10-22 18:31:58 +0000715 SCEVHandle Expr,
716 ScalarEvolution *SE) {
Dan Gohman9a769972009-04-18 17:56:28 +0000717 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000718 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
Dan Gohman89f85052007-10-22 18:31:58 +0000719 SeparateSubExprs(SubExprs, AE->getOperand(j), SE);
Dan Gohman9a769972009-04-18 17:56:28 +0000720 } else if (const SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
Dan Gohman89f85052007-10-22 18:31:58 +0000721 SCEVHandle Zero = SE->getIntegerSCEV(0, Expr->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000722 if (SARE->getOperand(0) == Zero) {
723 SubExprs.push_back(Expr);
724 } else {
725 // Compute the addrec with zero as its base.
726 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
727 Ops[0] = Zero; // Start with zero base.
Dan Gohman89f85052007-10-22 18:31:58 +0000728 SubExprs.push_back(SE->getAddRecExpr(Ops, SARE->getLoop()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000729
730
Dan Gohman89f85052007-10-22 18:31:58 +0000731 SeparateSubExprs(SubExprs, SARE->getOperand(0), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000732 }
Dan Gohman7b560c42008-06-18 16:23:07 +0000733 } else if (!Expr->isZero()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000734 // Do not add zero.
735 SubExprs.push_back(Expr);
736 }
737}
738
Dale Johannesen64660e92008-12-05 21:47:27 +0000739// This is logically local to the following function, but C++ says we have
740// to make it file scope.
741struct SubExprUseData { unsigned Count; bool notAllUsesAreFree; };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000742
Dale Johannesen64660e92008-12-05 21:47:27 +0000743/// RemoveCommonExpressionsFromUseBases - Look through all of the Bases of all
744/// the Uses, removing any common subexpressions, except that if all such
745/// subexpressions can be folded into an addressing mode for all uses inside
746/// the loop (this case is referred to as "free" in comments herein) we do
747/// not remove anything. This looks for things like (a+b+c) and
Chris Lattnerdb4a4f42008-12-02 04:52:26 +0000748/// (a+c+d) and computes the common (a+c) subexpression. The common expression
749/// is *removed* from the Bases and returned.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000750static SCEVHandle
Dan Gohman89f85052007-10-22 18:31:58 +0000751RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses,
Dale Johannesen64660e92008-12-05 21:47:27 +0000752 ScalarEvolution *SE, Loop *L,
753 const TargetLowering *TLI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000754 unsigned NumUses = Uses.size();
755
Chris Lattnerdb4a4f42008-12-02 04:52:26 +0000756 // Only one use? This is a very common case, so we handle it specially and
757 // cheaply.
Dan Gohman89f85052007-10-22 18:31:58 +0000758 SCEVHandle Zero = SE->getIntegerSCEV(0, Uses[0].Base->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000759 SCEVHandle Result = Zero;
Dale Johannesen64660e92008-12-05 21:47:27 +0000760 SCEVHandle FreeResult = Zero;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000761 if (NumUses == 1) {
Chris Lattnerdb4a4f42008-12-02 04:52:26 +0000762 // If the use is inside the loop, use its base, regardless of what it is:
763 // it is clearly shared across all the IV's. If the use is outside the loop
764 // (which means after it) we don't want to factor anything *into* the loop,
765 // so just use 0 as the base.
Dale Johannesen20299b42008-12-01 22:00:01 +0000766 if (L->contains(Uses[0].Inst->getParent()))
767 std::swap(Result, Uses[0].Base);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000768 return Result;
769 }
770
771 // To find common subexpressions, count how many of Uses use each expression.
772 // If any subexpressions are used Uses.size() times, they are common.
Dale Johannesen64660e92008-12-05 21:47:27 +0000773 // Also track whether all uses of each expression can be moved into an
774 // an addressing mode "for free"; such expressions are left within the loop.
775 // struct SubExprUseData { unsigned Count; bool notAllUsesAreFree; };
776 std::map<SCEVHandle, SubExprUseData> SubExpressionUseData;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000777
778 // UniqueSubExprs - Keep track of all of the subexpressions we see in the
779 // order we see them.
780 std::vector<SCEVHandle> UniqueSubExprs;
781
782 std::vector<SCEVHandle> SubExprs;
Chris Lattnerdb4a4f42008-12-02 04:52:26 +0000783 unsigned NumUsesInsideLoop = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000784 for (unsigned i = 0; i != NumUses; ++i) {
Chris Lattnerdb4a4f42008-12-02 04:52:26 +0000785 // If the user is outside the loop, just ignore it for base computation.
786 // Since the user is outside the loop, it must be *after* the loop (if it
787 // were before, it could not be based on the loop IV). We don't want users
788 // after the loop to affect base computation of values *inside* the loop,
789 // because we can always add their offsets to the result IV after the loop
790 // is done, ensuring we get good code inside the loop.
Dale Johannesen20299b42008-12-01 22:00:01 +0000791 if (!L->contains(Uses[i].Inst->getParent()))
792 continue;
793 NumUsesInsideLoop++;
794
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000795 // If the base is zero (which is common), return zero now, there are no
796 // CSEs we can find.
797 if (Uses[i].Base == Zero) return Zero;
798
Dale Johannesen64660e92008-12-05 21:47:27 +0000799 // If this use is as an address we may be able to put CSEs in the addressing
800 // mode rather than hoisting them.
801 bool isAddrUse = isAddressUse(Uses[i].Inst, Uses[i].OperandValToReplace);
Dan Gohmanb55ee6b2009-05-18 16:45:28 +0000802 // We may need the AccessTy below, but only when isAddrUse, so compute it
Dale Johannesen64660e92008-12-05 21:47:27 +0000803 // only in that case.
Dan Gohmanb55ee6b2009-05-18 16:45:28 +0000804 const Type *AccessTy = 0;
Dan Gohmanc0cefca2009-03-09 21:01:17 +0000805 if (isAddrUse)
Dan Gohmanb55ee6b2009-05-18 16:45:28 +0000806 AccessTy = getAccessType(Uses[i].Inst);
Dale Johannesen64660e92008-12-05 21:47:27 +0000807
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000808 // Split the expression into subexprs.
Dan Gohman89f85052007-10-22 18:31:58 +0000809 SeparateSubExprs(SubExprs, Uses[i].Base, SE);
Dale Johannesen64660e92008-12-05 21:47:27 +0000810 // Add one to SubExpressionUseData.Count for each subexpr present, and
811 // if the subexpr is not a valid immediate within an addressing mode use,
812 // set SubExpressionUseData.notAllUsesAreFree. We definitely want to
813 // hoist these out of the loop (if they are common to all uses).
814 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j) {
815 if (++SubExpressionUseData[SubExprs[j]].Count == 1)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000816 UniqueSubExprs.push_back(SubExprs[j]);
Dan Gohmanb55ee6b2009-05-18 16:45:28 +0000817 if (!isAddrUse || !fitsInAddressMode(SubExprs[j], AccessTy, TLI, false))
Dale Johannesen64660e92008-12-05 21:47:27 +0000818 SubExpressionUseData[SubExprs[j]].notAllUsesAreFree = true;
819 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000820 SubExprs.clear();
821 }
822
823 // Now that we know how many times each is used, build Result. Iterate over
824 // UniqueSubexprs so that we have a stable ordering.
825 for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
Dale Johannesen64660e92008-12-05 21:47:27 +0000826 std::map<SCEVHandle, SubExprUseData>::iterator I =
827 SubExpressionUseData.find(UniqueSubExprs[i]);
828 assert(I != SubExpressionUseData.end() && "Entry not found?");
829 if (I->second.Count == NumUsesInsideLoop) { // Found CSE!
830 if (I->second.notAllUsesAreFree)
831 Result = SE->getAddExpr(Result, I->first);
832 else
833 FreeResult = SE->getAddExpr(FreeResult, I->first);
834 } else
835 // Remove non-cse's from SubExpressionUseData.
836 SubExpressionUseData.erase(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000837 }
Dale Johannesen64660e92008-12-05 21:47:27 +0000838
839 if (FreeResult != Zero) {
840 // We have some subexpressions that can be subsumed into addressing
841 // modes in every use inside the loop. However, it's possible that
842 // there are so many of them that the combined FreeResult cannot
843 // be subsumed, or that the target cannot handle both a FreeResult
844 // and a Result in the same instruction (for example because it would
845 // require too many registers). Check this.
846 for (unsigned i=0; i<NumUses; ++i) {
847 if (!L->contains(Uses[i].Inst->getParent()))
848 continue;
849 // We know this is an addressing mode use; if there are any uses that
850 // are not, FreeResult would be Zero.
Dan Gohmanb55ee6b2009-05-18 16:45:28 +0000851 const Type *AccessTy = getAccessType(Uses[i].Inst);
852 if (!fitsInAddressMode(FreeResult, AccessTy, TLI, Result!=Zero)) {
Dale Johannesen64660e92008-12-05 21:47:27 +0000853 // FIXME: could split up FreeResult into pieces here, some hoisted
Dale Johannesen7b7b3d42008-12-16 22:16:28 +0000854 // and some not. There is no obvious advantage to this.
Dale Johannesen64660e92008-12-05 21:47:27 +0000855 Result = SE->getAddExpr(Result, FreeResult);
856 FreeResult = Zero;
857 break;
858 }
859 }
860 }
861
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000862 // If we found no CSE's, return now.
863 if (Result == Zero) return Result;
864
Dale Johannesen64660e92008-12-05 21:47:27 +0000865 // If we still have a FreeResult, remove its subexpressions from
866 // SubExpressionUseData. This means they will remain in the use Bases.
867 if (FreeResult != Zero) {
868 SeparateSubExprs(SubExprs, FreeResult, SE);
869 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j) {
870 std::map<SCEVHandle, SubExprUseData>::iterator I =
871 SubExpressionUseData.find(SubExprs[j]);
872 SubExpressionUseData.erase(I);
873 }
874 SubExprs.clear();
875 }
876
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000877 // Otherwise, remove all of the CSE's we found from each of the base values.
878 for (unsigned i = 0; i != NumUses; ++i) {
Dale Johannesen60dd8e12008-12-02 21:17:11 +0000879 // Uses outside the loop don't necessarily include the common base, but
880 // the final IV value coming into those uses does. Instead of trying to
881 // remove the pieces of the common base, which might not be there,
882 // subtract off the base to compensate for this.
883 if (!L->contains(Uses[i].Inst->getParent())) {
884 Uses[i].Base = SE->getMinusSCEV(Uses[i].Base, Result);
Dale Johannesen20299b42008-12-01 22:00:01 +0000885 continue;
Dale Johannesen60dd8e12008-12-02 21:17:11 +0000886 }
Dale Johannesen20299b42008-12-01 22:00:01 +0000887
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000888 // Split the expression into subexprs.
Dan Gohman89f85052007-10-22 18:31:58 +0000889 SeparateSubExprs(SubExprs, Uses[i].Base, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000890
891 // Remove any common subexpressions.
892 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
Dale Johannesen64660e92008-12-05 21:47:27 +0000893 if (SubExpressionUseData.count(SubExprs[j])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000894 SubExprs.erase(SubExprs.begin()+j);
895 --j; --e;
896 }
897
Chris Lattnerdb4a4f42008-12-02 04:52:26 +0000898 // Finally, add the non-shared expressions together.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000899 if (SubExprs.empty())
900 Uses[i].Base = Zero;
901 else
Dan Gohman89f85052007-10-22 18:31:58 +0000902 Uses[i].Base = SE->getAddExpr(SubExprs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000903 SubExprs.clear();
904 }
905
906 return Result;
907}
908
Evan Cheng56cfcd72009-05-11 22:33:01 +0000909/// ValidScale - Check whether the given Scale is valid for all loads and
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000910/// stores in UsersToProcess.
911///
Evan Cheng56cfcd72009-05-11 22:33:01 +0000912bool LoopStrengthReduce::ValidScale(bool HasBaseReg, int64_t Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000913 const std::vector<BasedUser>& UsersToProcess) {
Evan Chengb1ed4cd2007-12-19 23:33:23 +0000914 if (!TLI)
915 return true;
916
Evan Cheng56cfcd72009-05-11 22:33:01 +0000917 for (unsigned i = 0, e = UsersToProcess.size(); i!=e; ++i) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000918 // If this is a load or other access, pass the type of the access in.
919 const Type *AccessTy = Type::VoidTy;
Dan Gohmanc0cefca2009-03-09 21:01:17 +0000920 if (isAddressUse(UsersToProcess[i].Inst,
921 UsersToProcess[i].OperandValToReplace))
922 AccessTy = getAccessType(UsersToProcess[i].Inst);
Evan Chengce9bbb32008-03-19 22:02:26 +0000923 else if (isa<PHINode>(UsersToProcess[i].Inst))
924 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000925
926 TargetLowering::AddrMode AM;
Dan Gohman9a769972009-04-18 17:56:28 +0000927 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(UsersToProcess[i].Imm))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000928 AM.BaseOffs = SC->getValue()->getSExtValue();
Dan Gohman7b560c42008-06-18 16:23:07 +0000929 AM.HasBaseReg = HasBaseReg || !UsersToProcess[i].Base->isZero();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000930 AM.Scale = Scale;
931
932 // If load[imm+r*scale] is illegal, bail out.
Evan Chengb1ed4cd2007-12-19 23:33:23 +0000933 if (!TLI->isLegalAddressingMode(AM, AccessTy))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000934 return false;
935 }
936 return true;
937}
938
Dan Gohman28055122009-05-12 02:17:14 +0000939/// ValidOffset - Check whether the given Offset is valid for all loads and
940/// stores in UsersToProcess.
941///
942bool LoopStrengthReduce::ValidOffset(bool HasBaseReg,
943 int64_t Offset,
944 int64_t Scale,
945 const std::vector<BasedUser>& UsersToProcess) {
946 if (!TLI)
947 return true;
948
949 for (unsigned i=0, e = UsersToProcess.size(); i!=e; ++i) {
950 // If this is a load or other access, pass the type of the access in.
951 const Type *AccessTy = Type::VoidTy;
952 if (isAddressUse(UsersToProcess[i].Inst,
953 UsersToProcess[i].OperandValToReplace))
954 AccessTy = getAccessType(UsersToProcess[i].Inst);
955 else if (isa<PHINode>(UsersToProcess[i].Inst))
956 continue;
957
958 TargetLowering::AddrMode AM;
959 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(UsersToProcess[i].Imm))
960 AM.BaseOffs = SC->getValue()->getSExtValue();
961 AM.BaseOffs = (uint64_t)AM.BaseOffs + (uint64_t)Offset;
962 AM.HasBaseReg = HasBaseReg || !UsersToProcess[i].Base->isZero();
963 AM.Scale = Scale;
964
965 // If load[imm+r*scale] is illegal, bail out.
966 if (!TLI->isLegalAddressingMode(AM, AccessTy))
967 return false;
968 }
969 return true;
970}
971
Dale Johannesendb25a832009-02-09 22:14:15 +0000972/// RequiresTypeConversion - Returns true if converting Ty1 to Ty2 is not
Evan Cheng5385ab72007-10-25 22:45:20 +0000973/// a nop.
Evan Cheng27a820a2007-10-26 01:56:11 +0000974bool LoopStrengthReduce::RequiresTypeConversion(const Type *Ty1,
975 const Type *Ty2) {
976 if (Ty1 == Ty2)
Evan Cheng5385ab72007-10-25 22:45:20 +0000977 return false;
Dan Gohman3b790732009-05-01 17:07:43 +0000978 Ty1 = SE->getEffectiveSCEVType(Ty1);
979 Ty2 = SE->getEffectiveSCEVType(Ty2);
980 if (Ty1 == Ty2)
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000981 return false;
Dale Johannesendb25a832009-02-09 22:14:15 +0000982 if (Ty1->canLosslesslyBitCastTo(Ty2))
983 return false;
Evan Cheng27a820a2007-10-26 01:56:11 +0000984 if (TLI && TLI->isTruncateFree(Ty1, Ty2))
985 return false;
Dale Johannesendb25a832009-02-09 22:14:15 +0000986 return true;
Evan Cheng5385ab72007-10-25 22:45:20 +0000987}
988
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000989/// CheckForIVReuse - Returns the multiple if the stride is the multiple
990/// of a previous stride and it is a legal value for the target addressing
Dan Gohman5766ac72007-10-22 20:40:42 +0000991/// mode scale component and optional base reg. This allows the users of
992/// this stride to be rewritten as prev iv * factor. It returns 0 if no
Dale Johannesen7b7b3d42008-12-16 22:16:28 +0000993/// reuse is possible. Factors can be negative on same targets, e.g. ARM.
Dale Johannesen671a23c2009-01-14 02:35:31 +0000994///
995/// If all uses are outside the loop, we don't require that all multiplies
996/// be folded into the addressing mode, nor even that the factor be constant;
997/// a multiply (executed once) outside the loop is better than another IV
998/// within. Well, usually.
999SCEVHandle LoopStrengthReduce::CheckForIVReuse(bool HasBaseReg,
Evan Cheng27a820a2007-10-26 01:56:11 +00001000 bool AllUsesAreAddresses,
Dale Johannesen7b7b3d42008-12-16 22:16:28 +00001001 bool AllUsesAreOutsideLoop,
Dan Gohman5766ac72007-10-22 20:40:42 +00001002 const SCEVHandle &Stride,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001003 IVExpr &IV, const Type *Ty,
1004 const std::vector<BasedUser>& UsersToProcess) {
Evan Cheng56cfcd72009-05-11 22:33:01 +00001005 if (StrideNoReuse.count(Stride))
1006 return SE->getIntegerSCEV(0, Stride->getType());
1007
Dan Gohman9a769972009-04-18 17:56:28 +00001008 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001009 int64_t SInt = SC->getValue()->getSExtValue();
Dan Gohman28055122009-05-12 02:17:14 +00001010 for (unsigned NewStride = 0, e = IU->StrideOrder.size();
1011 NewStride != e; ++NewStride) {
Dale Johannesend92fe9f2007-11-17 02:48:01 +00001012 std::map<SCEVHandle, IVsOfOneStride>::iterator SI =
Dan Gohman28055122009-05-12 02:17:14 +00001013 IVsByStride.find(IU->StrideOrder[NewStride]);
Evan Cheng56cfcd72009-05-11 22:33:01 +00001014 if (SI == IVsByStride.end() || !isa<SCEVConstant>(SI->first) ||
1015 StrideNoReuse.count(SI->first))
Dale Johannesend92fe9f2007-11-17 02:48:01 +00001016 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001017 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
Evan Cheng27a820a2007-10-26 01:56:11 +00001018 if (SI->first != Stride &&
Dale Johannesen8634ce32009-05-13 00:24:22 +00001019 (unsigned(abs64(SInt)) < SSInt || (SInt % SSInt) != 0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001020 continue;
1021 int64_t Scale = SInt / SSInt;
1022 // Check that this stride is valid for all the types used for loads and
1023 // stores; if it can be used for some and not others, we might as well use
1024 // the original stride everywhere, since we have to create the IV for it
Dan Gohman55113942007-10-29 19:23:53 +00001025 // anyway. If the scale is 1, then we don't need to worry about folding
1026 // multiplications.
1027 if (Scale == 1 ||
1028 (AllUsesAreAddresses &&
Dan Gohman28055122009-05-12 02:17:14 +00001029 ValidScale(HasBaseReg, Scale, UsersToProcess))) {
1030 // Prefer to reuse an IV with a base of zero.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001031 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1032 IE = SI->second.IVs.end(); II != IE; ++II)
Dan Gohman28055122009-05-12 02:17:14 +00001033 // Only reuse previous IV if it would not require a type conversion
1034 // and if the base difference can be folded.
Dan Gohman7b560c42008-06-18 16:23:07 +00001035 if (II->Base->isZero() &&
Evan Cheng27a820a2007-10-26 01:56:11 +00001036 !RequiresTypeConversion(II->Base->getType(), Ty)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001037 IV = *II;
Dale Johannesen671a23c2009-01-14 02:35:31 +00001038 return SE->getIntegerSCEV(Scale, Stride->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001039 }
Dan Gohman28055122009-05-12 02:17:14 +00001040 // Otherwise, settle for an IV with a foldable base.
1041 if (AllUsesAreAddresses)
1042 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1043 IE = SI->second.IVs.end(); II != IE; ++II)
1044 // Only reuse previous IV if it would not require a type conversion
1045 // and if the base difference can be folded.
1046 if (SE->getEffectiveSCEVType(II->Base->getType()) ==
1047 SE->getEffectiveSCEVType(Ty) &&
1048 isa<SCEVConstant>(II->Base)) {
1049 int64_t Base =
1050 cast<SCEVConstant>(II->Base)->getValue()->getSExtValue();
1051 if (Base > INT32_MIN && Base <= INT32_MAX &&
1052 ValidOffset(HasBaseReg, -Base * Scale,
1053 Scale, UsersToProcess)) {
1054 IV = *II;
1055 return SE->getIntegerSCEV(Scale, Stride->getType());
1056 }
1057 }
1058 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001059 }
Dale Johannesen671a23c2009-01-14 02:35:31 +00001060 } else if (AllUsesAreOutsideLoop) {
1061 // Accept nonconstant strides here; it is really really right to substitute
1062 // an existing IV if we can.
Dan Gohman28055122009-05-12 02:17:14 +00001063 for (unsigned NewStride = 0, e = IU->StrideOrder.size();
1064 NewStride != e; ++NewStride) {
Dale Johannesen671a23c2009-01-14 02:35:31 +00001065 std::map<SCEVHandle, IVsOfOneStride>::iterator SI =
Dan Gohman28055122009-05-12 02:17:14 +00001066 IVsByStride.find(IU->StrideOrder[NewStride]);
Dale Johannesen671a23c2009-01-14 02:35:31 +00001067 if (SI == IVsByStride.end() || !isa<SCEVConstant>(SI->first))
1068 continue;
1069 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
1070 if (SI->first != Stride && SSInt != 1)
1071 continue;
1072 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1073 IE = SI->second.IVs.end(); II != IE; ++II)
1074 // Accept nonzero base here.
1075 // Only reuse previous IV if it would not require a type conversion.
1076 if (!RequiresTypeConversion(II->Base->getType(), Ty)) {
1077 IV = *II;
1078 return Stride;
1079 }
1080 }
1081 // Special case, old IV is -1*x and this one is x. Can treat this one as
1082 // -1*old.
Dan Gohman28055122009-05-12 02:17:14 +00001083 for (unsigned NewStride = 0, e = IU->StrideOrder.size();
1084 NewStride != e; ++NewStride) {
Dale Johannesen671a23c2009-01-14 02:35:31 +00001085 std::map<SCEVHandle, IVsOfOneStride>::iterator SI =
Dan Gohman28055122009-05-12 02:17:14 +00001086 IVsByStride.find(IU->StrideOrder[NewStride]);
Dale Johannesen671a23c2009-01-14 02:35:31 +00001087 if (SI == IVsByStride.end())
1088 continue;
Dan Gohman9a769972009-04-18 17:56:28 +00001089 if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(SI->first))
1090 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(ME->getOperand(0)))
Dale Johannesen671a23c2009-01-14 02:35:31 +00001091 if (Stride == ME->getOperand(1) &&
1092 SC->getValue()->getSExtValue() == -1LL)
1093 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1094 IE = SI->second.IVs.end(); II != IE; ++II)
1095 // Accept nonzero base here.
1096 // Only reuse previous IV if it would not require type conversion.
1097 if (!RequiresTypeConversion(II->Base->getType(), Ty)) {
1098 IV = *II;
1099 return SE->getIntegerSCEV(-1LL, Stride->getType());
1100 }
1101 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001102 }
Dale Johannesen671a23c2009-01-14 02:35:31 +00001103 return SE->getIntegerSCEV(0, Stride->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001104}
1105
1106/// PartitionByIsUseOfPostIncrementedValue - Simple boolean predicate that
1107/// returns true if Val's isUseOfPostIncrementedValue is true.
1108static bool PartitionByIsUseOfPostIncrementedValue(const BasedUser &Val) {
1109 return Val.isUseOfPostIncrementedValue;
1110}
1111
Dan Gohman5de363f2008-04-14 18:26:16 +00001112/// isNonConstantNegative - Return true if the specified scev is negated, but
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001113/// not a constant.
1114static bool isNonConstantNegative(const SCEVHandle &Expr) {
Dan Gohman9a769972009-04-18 17:56:28 +00001115 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Expr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001116 if (!Mul) return false;
1117
1118 // If there is a constant factor, it will be first.
Dan Gohman9a769972009-04-18 17:56:28 +00001119 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001120 if (!SC) return false;
1121
1122 // Return true if the value is negative, this matches things like (-42 * V).
1123 return SC->getValue()->getValue().isNegative();
1124}
1125
Evan Cheng5385ab72007-10-25 22:45:20 +00001126// CollectIVUsers - Transform our list of users and offsets to a bit more
Dan Gohmanb607e402008-06-23 22:11:52 +00001127// complex table. In this new vector, each 'BasedUser' contains 'Base', the base
1128// of the strided accesses, as well as the old information from Uses. We
Evan Cheng5385ab72007-10-25 22:45:20 +00001129// progressively move information from the Base field to the Imm field, until
1130// we eventually have the full access expression to rewrite the use.
1131SCEVHandle LoopStrengthReduce::CollectIVUsers(const SCEVHandle &Stride,
1132 IVUsersOfOneStride &Uses,
1133 Loop *L,
1134 bool &AllUsesAreAddresses,
Dale Johannesen7b7b3d42008-12-16 22:16:28 +00001135 bool &AllUsesAreOutsideLoop,
Evan Cheng5385ab72007-10-25 22:45:20 +00001136 std::vector<BasedUser> &UsersToProcess) {
Dan Gohman28055122009-05-12 02:17:14 +00001137 // FIXME: Generalize to non-affine IV's.
1138 if (!Stride->isLoopInvariant(L))
1139 return SE->getIntegerSCEV(0, Stride->getType());
1140
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001141 UsersToProcess.reserve(Uses.Users.size());
Dan Gohman28055122009-05-12 02:17:14 +00001142 for (ilist<IVStrideUse>::iterator I = Uses.Users.begin(),
1143 E = Uses.Users.end(); I != E; ++I) {
1144 UsersToProcess.push_back(BasedUser(*I, SE));
1145
Dale Johannesend128e672008-12-03 19:25:46 +00001146 // Move any loop variant operands from the offset field to the immediate
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001147 // field of the use, so that we don't try to use something before it is
1148 // computed.
Dale Johannesen48e16f92008-12-03 20:56:12 +00001149 MoveLoopVariantsToImmediateField(UsersToProcess.back().Base,
Evan Cheng56cfcd72009-05-11 22:33:01 +00001150 UsersToProcess.back().Imm, L, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001151 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
1152 "Base value is not loop invariant!");
1153 }
1154
1155 // We now have a whole bunch of uses of like-strided induction variables, but
1156 // they might all have different bases. We want to emit one PHI node for this
1157 // stride which we fold as many common expressions (between the IVs) into as
1158 // possible. Start by identifying the common expressions in the base values
1159 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
1160 // "A+B"), emit it to the preheader, then remove the expression from the
1161 // UsersToProcess base values.
1162 SCEVHandle CommonExprs =
Dale Johannesen64660e92008-12-05 21:47:27 +00001163 RemoveCommonExpressionsFromUseBases(UsersToProcess, SE, L, TLI);
Dan Gohman5766ac72007-10-22 20:40:42 +00001164
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001165 // Next, figure out what we can represent in the immediate fields of
1166 // instructions. If we can represent anything there, move it to the imm
1167 // fields of the BasedUsers. We do this so that it increases the commonality
1168 // of the remaining uses.
Evan Cheng82366ed2007-12-20 02:20:53 +00001169 unsigned NumPHI = 0;
Evan Chengf0353b12009-02-20 22:16:49 +00001170 bool HasAddress = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001171 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1172 // If the user is not in the current loop, this means it is using the exit
1173 // value of the IV. Do not put anything in the base, make sure it's all in
1174 // the immediate field to allow as much factoring as possible.
1175 if (!L->contains(UsersToProcess[i].Inst->getParent())) {
Dan Gohman89f85052007-10-22 18:31:58 +00001176 UsersToProcess[i].Imm = SE->getAddExpr(UsersToProcess[i].Imm,
1177 UsersToProcess[i].Base);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001178 UsersToProcess[i].Base =
Dan Gohman89f85052007-10-22 18:31:58 +00001179 SE->getIntegerSCEV(0, UsersToProcess[i].Base->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001180 } else {
Evan Chengf2704c02009-02-21 02:06:47 +00001181 // Not all uses are outside the loop.
1182 AllUsesAreOutsideLoop = false;
1183
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001184 // Addressing modes can be folded into loads and stores. Be careful that
1185 // the store is through the expression, not of the expression though.
Evan Cheng82366ed2007-12-20 02:20:53 +00001186 bool isPHI = false;
Evan Chengb1ed4cd2007-12-19 23:33:23 +00001187 bool isAddress = isAddressUse(UsersToProcess[i].Inst,
1188 UsersToProcess[i].OperandValToReplace);
1189 if (isa<PHINode>(UsersToProcess[i].Inst)) {
Evan Cheng82366ed2007-12-20 02:20:53 +00001190 isPHI = true;
1191 ++NumPHI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001192 }
Dan Gohman5766ac72007-10-22 20:40:42 +00001193
Evan Chengf0353b12009-02-20 22:16:49 +00001194 if (isAddress)
1195 HasAddress = true;
Dale Johannesen7b7b3d42008-12-16 22:16:28 +00001196
Dan Gohman5766ac72007-10-22 20:40:42 +00001197 // If this use isn't an address, then not all uses are addresses.
Evan Chengce9bbb32008-03-19 22:02:26 +00001198 if (!isAddress && !isPHI)
Dan Gohman5766ac72007-10-22 20:40:42 +00001199 AllUsesAreAddresses = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001200
1201 MoveImmediateValues(TLI, UsersToProcess[i].Inst, UsersToProcess[i].Base,
Dan Gohman89f85052007-10-22 18:31:58 +00001202 UsersToProcess[i].Imm, isAddress, L, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001203 }
1204 }
1205
Evan Chengf2704c02009-02-21 02:06:47 +00001206 // If one of the use is a PHI node and all other uses are addresses, still
Evan Cheng82366ed2007-12-20 02:20:53 +00001207 // allow iv reuse. Essentially we are trading one constant multiplication
1208 // for one fewer iv.
1209 if (NumPHI > 1)
1210 AllUsesAreAddresses = false;
Evan Chengf2704c02009-02-21 02:06:47 +00001211
Evan Chengf0353b12009-02-20 22:16:49 +00001212 // There are no in-loop address uses.
1213 if (AllUsesAreAddresses && (!HasAddress && !AllUsesAreOutsideLoop))
1214 AllUsesAreAddresses = false;
1215
Evan Cheng5385ab72007-10-25 22:45:20 +00001216 return CommonExprs;
1217}
1218
Dan Gohman7cb042d2009-02-20 04:17:46 +00001219/// ShouldUseFullStrengthReductionMode - Test whether full strength-reduction
1220/// is valid and profitable for the given set of users of a stride. In
1221/// full strength-reduction mode, all addresses at the current stride are
1222/// strength-reduced all the way down to pointer arithmetic.
1223///
1224bool LoopStrengthReduce::ShouldUseFullStrengthReductionMode(
1225 const std::vector<BasedUser> &UsersToProcess,
1226 const Loop *L,
1227 bool AllUsesAreAddresses,
1228 SCEVHandle Stride) {
1229 if (!EnableFullLSRMode)
1230 return false;
1231
1232 // The heuristics below aim to avoid increasing register pressure, but
1233 // fully strength-reducing all the addresses increases the number of
1234 // add instructions, so don't do this when optimizing for size.
1235 // TODO: If the loop is large, the savings due to simpler addresses
1236 // may oughtweight the costs of the extra increment instructions.
1237 if (L->getHeader()->getParent()->hasFnAttr(Attribute::OptimizeForSize))
1238 return false;
1239
1240 // TODO: For now, don't do full strength reduction if there could
1241 // potentially be greater-stride multiples of the current stride
1242 // which could reuse the current stride IV.
Dan Gohman28055122009-05-12 02:17:14 +00001243 if (IU->StrideOrder.back() != Stride)
Dan Gohman7cb042d2009-02-20 04:17:46 +00001244 return false;
1245
1246 // Iterate through the uses to find conditions that automatically rule out
1247 // full-lsr mode.
1248 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001249 const SCEV *Base = UsersToProcess[i].Base;
1250 const SCEV *Imm = UsersToProcess[i].Imm;
Dan Gohman7cb042d2009-02-20 04:17:46 +00001251 // If any users have a loop-variant component, they can't be fully
1252 // strength-reduced.
1253 if (Imm && !Imm->isLoopInvariant(L))
1254 return false;
1255 // If there are to users with the same base and the difference between
1256 // the two Imm values can't be folded into the address, full
1257 // strength reduction would increase register pressure.
1258 do {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001259 const SCEV *CurImm = UsersToProcess[i].Imm;
Dan Gohman6c59b152009-02-22 16:40:52 +00001260 if ((CurImm || Imm) && CurImm != Imm) {
Dan Gohman7cb042d2009-02-20 04:17:46 +00001261 if (!CurImm) CurImm = SE->getIntegerSCEV(0, Stride->getType());
1262 if (!Imm) Imm = SE->getIntegerSCEV(0, Stride->getType());
1263 const Instruction *Inst = UsersToProcess[i].Inst;
Dan Gohmanb55ee6b2009-05-18 16:45:28 +00001264 const Type *AccessTy = getAccessType(Inst);
Dan Gohman7cb042d2009-02-20 04:17:46 +00001265 SCEVHandle Diff = SE->getMinusSCEV(UsersToProcess[i].Imm, Imm);
1266 if (!Diff->isZero() &&
1267 (!AllUsesAreAddresses ||
Dan Gohmanb55ee6b2009-05-18 16:45:28 +00001268 !fitsInAddressMode(Diff, AccessTy, TLI, /*HasBaseReg=*/true)))
Dan Gohman7cb042d2009-02-20 04:17:46 +00001269 return false;
1270 }
1271 } while (++i != e && Base == UsersToProcess[i].Base);
1272 }
1273
1274 // If there's exactly one user in this stride, fully strength-reducing it
1275 // won't increase register pressure. If it's starting from a non-zero base,
1276 // it'll be simpler this way.
1277 if (UsersToProcess.size() == 1 && !UsersToProcess[0].Base->isZero())
1278 return true;
1279
1280 // Otherwise, if there are any users in this stride that don't require
1281 // a register for their base, full strength-reduction will increase
1282 // register pressure.
1283 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
Dan Gohman11ff5152009-02-20 21:05:23 +00001284 if (UsersToProcess[i].Base->isZero())
Dan Gohman7cb042d2009-02-20 04:17:46 +00001285 return false;
1286
1287 // Otherwise, go for it.
1288 return true;
1289}
1290
1291/// InsertAffinePhi Create and insert a PHI node for an induction variable
1292/// with the specified start and step values in the specified loop.
1293///
1294/// If NegateStride is true, the stride should be negated by using a
1295/// subtract instead of an add.
1296///
Dan Gohman8b90e742009-03-09 22:04:01 +00001297/// Return the created phi node.
Dan Gohman7cb042d2009-02-20 04:17:46 +00001298///
1299static PHINode *InsertAffinePhi(SCEVHandle Start, SCEVHandle Step,
Evan Cheng56cfcd72009-05-11 22:33:01 +00001300 Instruction *IVIncInsertPt,
Dan Gohman7cb042d2009-02-20 04:17:46 +00001301 const Loop *L,
Dan Gohman8b90e742009-03-09 22:04:01 +00001302 SCEVExpander &Rewriter) {
Dan Gohman7cb042d2009-02-20 04:17:46 +00001303 assert(Start->isLoopInvariant(L) && "New PHI start is not loop invariant!");
1304 assert(Step->isLoopInvariant(L) && "New PHI stride is not loop invariant!");
1305
1306 BasicBlock *Header = L->getHeader();
1307 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohman8dad0012009-03-09 21:14:16 +00001308 BasicBlock *LatchBlock = L->getLoopLatch();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001309 const Type *Ty = Start->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001310 Ty = Rewriter.SE.getEffectiveSCEVType(Ty);
Dan Gohman7cb042d2009-02-20 04:17:46 +00001311
Dan Gohman01c2ee72009-04-16 03:18:22 +00001312 PHINode *PN = PHINode::Create(Ty, "lsr.iv", Header->begin());
1313 PN->addIncoming(Rewriter.expandCodeFor(Start, Ty, Preheader->getTerminator()),
Dan Gohman7cb042d2009-02-20 04:17:46 +00001314 Preheader);
1315
Dan Gohman7cb042d2009-02-20 04:17:46 +00001316 // If the stride is negative, insert a sub instead of an add for the
1317 // increment.
1318 bool isNegative = isNonConstantNegative(Step);
1319 SCEVHandle IncAmount = Step;
1320 if (isNegative)
1321 IncAmount = Rewriter.SE.getNegativeSCEV(Step);
1322
1323 // Insert an add instruction right before the terminator corresponding
Evan Cheng56cfcd72009-05-11 22:33:01 +00001324 // to the back-edge or just before the only use. The location is determined
1325 // by the caller and passed in as IVIncInsertPt.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001326 Value *StepV = Rewriter.expandCodeFor(IncAmount, Ty,
1327 Preheader->getTerminator());
Dan Gohman8b90e742009-03-09 22:04:01 +00001328 Instruction *IncV;
Dan Gohman7cb042d2009-02-20 04:17:46 +00001329 if (isNegative) {
1330 IncV = BinaryOperator::CreateSub(PN, StepV, "lsr.iv.next",
Evan Cheng56cfcd72009-05-11 22:33:01 +00001331 IVIncInsertPt);
Dan Gohman7cb042d2009-02-20 04:17:46 +00001332 } else {
1333 IncV = BinaryOperator::CreateAdd(PN, StepV, "lsr.iv.next",
Evan Cheng56cfcd72009-05-11 22:33:01 +00001334 IVIncInsertPt);
Dan Gohman7cb042d2009-02-20 04:17:46 +00001335 }
1336 if (!isa<ConstantInt>(StepV)) ++NumVariable;
1337
Dan Gohman8dad0012009-03-09 21:14:16 +00001338 PN->addIncoming(IncV, LatchBlock);
Dan Gohman7cb042d2009-02-20 04:17:46 +00001339
1340 ++NumInserted;
1341 return PN;
1342}
1343
1344static void SortUsersToProcess(std::vector<BasedUser> &UsersToProcess) {
1345 // We want to emit code for users inside the loop first. To do this, we
1346 // rearrange BasedUser so that the entries at the end have
1347 // isUseOfPostIncrementedValue = false, because we pop off the end of the
1348 // vector (so we handle them first).
1349 std::partition(UsersToProcess.begin(), UsersToProcess.end(),
1350 PartitionByIsUseOfPostIncrementedValue);
1351
1352 // Sort this by base, so that things with the same base are handled
1353 // together. By partitioning first and stable-sorting later, we are
1354 // guaranteed that within each base we will pop off users from within the
1355 // loop before users outside of the loop with a particular base.
1356 //
1357 // We would like to use stable_sort here, but we can't. The problem is that
1358 // SCEVHandle's don't have a deterministic ordering w.r.t to each other, so
1359 // we don't have anything to do a '<' comparison on. Because we think the
1360 // number of uses is small, do a horrible bubble sort which just relies on
1361 // ==.
1362 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1363 // Get a base value.
1364 SCEVHandle Base = UsersToProcess[i].Base;
1365
1366 // Compact everything with this base to be consecutive with this one.
1367 for (unsigned j = i+1; j != e; ++j) {
1368 if (UsersToProcess[j].Base == Base) {
1369 std::swap(UsersToProcess[i+1], UsersToProcess[j]);
1370 ++i;
1371 }
1372 }
1373 }
1374}
1375
Dan Gohman36203772009-02-20 21:06:57 +00001376/// PrepareToStrengthReduceFully - Prepare to fully strength-reduce
1377/// UsersToProcess, meaning lowering addresses all the way down to direct
1378/// pointer arithmetic.
Dan Gohman7cb042d2009-02-20 04:17:46 +00001379///
1380void
1381LoopStrengthReduce::PrepareToStrengthReduceFully(
1382 std::vector<BasedUser> &UsersToProcess,
1383 SCEVHandle Stride,
1384 SCEVHandle CommonExprs,
1385 const Loop *L,
1386 SCEVExpander &PreheaderRewriter) {
1387 DOUT << " Fully reducing all users\n";
1388
1389 // Rewrite the UsersToProcess records, creating a separate PHI for each
1390 // unique Base value.
Evan Cheng56cfcd72009-05-11 22:33:01 +00001391 Instruction *IVIncInsertPt = L->getLoopLatch()->getTerminator();
Dan Gohman7cb042d2009-02-20 04:17:46 +00001392 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ) {
1393 // TODO: The uses are grouped by base, but not sorted. We arbitrarily
1394 // pick the first Imm value here to start with, and adjust it for the
1395 // other uses.
1396 SCEVHandle Imm = UsersToProcess[i].Imm;
1397 SCEVHandle Base = UsersToProcess[i].Base;
1398 SCEVHandle Start = SE->getAddExpr(CommonExprs, Base, Imm);
Evan Cheng56cfcd72009-05-11 22:33:01 +00001399 PHINode *Phi = InsertAffinePhi(Start, Stride, IVIncInsertPt, L,
Dan Gohman8b90e742009-03-09 22:04:01 +00001400 PreheaderRewriter);
Dan Gohman7cb042d2009-02-20 04:17:46 +00001401 // Loop over all the users with the same base.
1402 do {
1403 UsersToProcess[i].Base = SE->getIntegerSCEV(0, Stride->getType());
1404 UsersToProcess[i].Imm = SE->getMinusSCEV(UsersToProcess[i].Imm, Imm);
1405 UsersToProcess[i].Phi = Phi;
Dan Gohman7cb042d2009-02-20 04:17:46 +00001406 assert(UsersToProcess[i].Imm->isLoopInvariant(L) &&
1407 "ShouldUseFullStrengthReductionMode should reject this!");
1408 } while (++i != e && Base == UsersToProcess[i].Base);
1409 }
1410}
1411
Evan Cheng56cfcd72009-05-11 22:33:01 +00001412/// FindIVIncInsertPt - Return the location to insert the increment instruction.
1413/// If the only use if a use of postinc value, (must be the loop termination
1414/// condition), then insert it just before the use.
1415static Instruction *FindIVIncInsertPt(std::vector<BasedUser> &UsersToProcess,
1416 const Loop *L) {
1417 if (UsersToProcess.size() == 1 &&
1418 UsersToProcess[0].isUseOfPostIncrementedValue &&
1419 L->contains(UsersToProcess[0].Inst->getParent()))
1420 return UsersToProcess[0].Inst;
1421 return L->getLoopLatch()->getTerminator();
1422}
1423
Dan Gohman7cb042d2009-02-20 04:17:46 +00001424/// PrepareToStrengthReduceWithNewPhi - Insert a new induction variable for the
1425/// given users to share.
1426///
1427void
1428LoopStrengthReduce::PrepareToStrengthReduceWithNewPhi(
1429 std::vector<BasedUser> &UsersToProcess,
1430 SCEVHandle Stride,
1431 SCEVHandle CommonExprs,
1432 Value *CommonBaseV,
Evan Cheng56cfcd72009-05-11 22:33:01 +00001433 Instruction *IVIncInsertPt,
Dan Gohman7cb042d2009-02-20 04:17:46 +00001434 const Loop *L,
1435 SCEVExpander &PreheaderRewriter) {
1436 DOUT << " Inserting new PHI:\n";
1437
Dan Gohman7cb042d2009-02-20 04:17:46 +00001438 PHINode *Phi = InsertAffinePhi(SE->getUnknown(CommonBaseV),
Evan Cheng56cfcd72009-05-11 22:33:01 +00001439 Stride, IVIncInsertPt, L,
Dan Gohman8b90e742009-03-09 22:04:01 +00001440 PreheaderRewriter);
Dan Gohman7cb042d2009-02-20 04:17:46 +00001441
1442 // Remember this in case a later stride is multiple of this.
Dan Gohman8b90e742009-03-09 22:04:01 +00001443 IVsByStride[Stride].addIV(Stride, CommonExprs, Phi);
Dan Gohman7cb042d2009-02-20 04:17:46 +00001444
1445 // All the users will share this new IV.
Dan Gohman8b90e742009-03-09 22:04:01 +00001446 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
Dan Gohman7cb042d2009-02-20 04:17:46 +00001447 UsersToProcess[i].Phi = Phi;
Dan Gohman7cb042d2009-02-20 04:17:46 +00001448
1449 DOUT << " IV=";
1450 DEBUG(WriteAsOperand(*DOUT, Phi, /*PrintType=*/false));
Dan Gohman7cb042d2009-02-20 04:17:46 +00001451 DOUT << "\n";
1452}
1453
Evan Cheng56cfcd72009-05-11 22:33:01 +00001454/// PrepareToStrengthReduceFromSmallerStride - Prepare for the given users to
1455/// reuse an induction variable with a stride that is a factor of the current
Dan Gohman7cb042d2009-02-20 04:17:46 +00001456/// induction variable.
1457///
1458void
1459LoopStrengthReduce::PrepareToStrengthReduceFromSmallerStride(
1460 std::vector<BasedUser> &UsersToProcess,
1461 Value *CommonBaseV,
1462 const IVExpr &ReuseIV,
1463 Instruction *PreInsertPt) {
1464 DOUT << " Rewriting in terms of existing IV of STRIDE " << *ReuseIV.Stride
1465 << " and BASE " << *ReuseIV.Base << "\n";
1466
1467 // All the users will share the reused IV.
Dan Gohman8b90e742009-03-09 22:04:01 +00001468 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
Dan Gohman7cb042d2009-02-20 04:17:46 +00001469 UsersToProcess[i].Phi = ReuseIV.PHI;
Dan Gohman7cb042d2009-02-20 04:17:46 +00001470
1471 Constant *C = dyn_cast<Constant>(CommonBaseV);
1472 if (C &&
1473 (!C->isNullValue() &&
1474 !fitsInAddressMode(SE->getUnknown(CommonBaseV), CommonBaseV->getType(),
1475 TLI, false)))
1476 // We want the common base emitted into the preheader! This is just
1477 // using cast as a copy so BitCast (no-op cast) is appropriate
1478 CommonBaseV = new BitCastInst(CommonBaseV, CommonBaseV->getType(),
1479 "commonbase", PreInsertPt);
1480}
1481
Evan Chengf2704c02009-02-21 02:06:47 +00001482static bool IsImmFoldedIntoAddrMode(GlobalValue *GV, int64_t Offset,
Dan Gohmanea6eae72009-03-09 21:04:19 +00001483 const Type *AccessTy,
Evan Chengf2704c02009-02-21 02:06:47 +00001484 std::vector<BasedUser> &UsersToProcess,
1485 const TargetLowering *TLI) {
1486 SmallVector<Instruction*, 16> AddrModeInsts;
1487 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1488 if (UsersToProcess[i].isUseOfPostIncrementedValue)
1489 continue;
1490 ExtAddrMode AddrMode =
1491 AddressingModeMatcher::Match(UsersToProcess[i].OperandValToReplace,
Dan Gohmanea6eae72009-03-09 21:04:19 +00001492 AccessTy, UsersToProcess[i].Inst,
Evan Chengf2704c02009-02-21 02:06:47 +00001493 AddrModeInsts, *TLI);
1494 if (GV && GV != AddrMode.BaseGV)
1495 return false;
1496 if (Offset && !AddrMode.BaseOffs)
1497 // FIXME: How to accurate check it's immediate offset is folded.
1498 return false;
1499 AddrModeInsts.clear();
1500 }
1501 return true;
1502}
1503
Evan Cheng5385ab72007-10-25 22:45:20 +00001504/// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
1505/// stride of IV. All of the users may have different starting values, and this
Dan Gohman8f4faa02009-03-09 20:41:15 +00001506/// may not be the only stride.
Evan Cheng5385ab72007-10-25 22:45:20 +00001507void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
1508 IVUsersOfOneStride &Uses,
Dan Gohman8f4faa02009-03-09 20:41:15 +00001509 Loop *L) {
Evan Cheng5385ab72007-10-25 22:45:20 +00001510 // If all the users are moved to another stride, then there is nothing to do.
Dan Gohman301f4052008-01-29 13:02:09 +00001511 if (Uses.Users.empty())
Evan Cheng5385ab72007-10-25 22:45:20 +00001512 return;
1513
1514 // Keep track if every use in UsersToProcess is an address. If they all are,
1515 // we may be able to rewrite the entire collection of them in terms of a
1516 // smaller-stride IV.
1517 bool AllUsesAreAddresses = true;
1518
Dale Johannesen7b7b3d42008-12-16 22:16:28 +00001519 // Keep track if every use of a single stride is outside the loop. If so,
1520 // we want to be more aggressive about reusing a smaller-stride IV; a
1521 // multiply outside the loop is better than another IV inside. Well, usually.
1522 bool AllUsesAreOutsideLoop = true;
1523
Evan Cheng5385ab72007-10-25 22:45:20 +00001524 // Transform our list of users and offsets to a bit more complex table. In
1525 // this new vector, each 'BasedUser' contains 'Base' the base of the
1526 // strided accessas well as the old information from Uses. We progressively
1527 // move information from the Base field to the Imm field, until we eventually
1528 // have the full access expression to rewrite the use.
1529 std::vector<BasedUser> UsersToProcess;
1530 SCEVHandle CommonExprs = CollectIVUsers(Stride, Uses, L, AllUsesAreAddresses,
Dale Johannesen7b7b3d42008-12-16 22:16:28 +00001531 AllUsesAreOutsideLoop,
Evan Cheng5385ab72007-10-25 22:45:20 +00001532 UsersToProcess);
1533
Dan Gohman7cb042d2009-02-20 04:17:46 +00001534 // Sort the UsersToProcess array so that users with common bases are
1535 // next to each other.
1536 SortUsersToProcess(UsersToProcess);
1537
Evan Cheng5385ab72007-10-25 22:45:20 +00001538 // If we managed to find some expressions in common, we'll need to carry
1539 // their value in a register and add it in for each use. This will take up
1540 // a register operand, which potentially restricts what stride values are
1541 // valid.
Dan Gohman7b560c42008-06-18 16:23:07 +00001542 bool HaveCommonExprs = !CommonExprs->isZero();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001543 const Type *ReplacedTy = CommonExprs->getType();
Dan Gohman7cb042d2009-02-20 04:17:46 +00001544
Evan Chengf2704c02009-02-21 02:06:47 +00001545 // If all uses are addresses, consider sinking the immediate part of the
1546 // common expression back into uses if they can fit in the immediate fields.
Evan Cheng80947032009-02-22 07:31:19 +00001547 if (TLI && HaveCommonExprs && AllUsesAreAddresses) {
Evan Chengf2704c02009-02-21 02:06:47 +00001548 SCEVHandle NewCommon = CommonExprs;
1549 SCEVHandle Imm = SE->getIntegerSCEV(0, ReplacedTy);
Dan Gohmanc2458b72009-03-09 21:22:12 +00001550 MoveImmediateValues(TLI, Type::VoidTy, NewCommon, Imm, true, L, SE);
Evan Chengf2704c02009-02-21 02:06:47 +00001551 if (!Imm->isZero()) {
1552 bool DoSink = true;
1553
1554 // If the immediate part of the common expression is a GV, check if it's
1555 // possible to fold it into the target addressing mode.
1556 GlobalValue *GV = 0;
Dan Gohman9a769972009-04-18 17:56:28 +00001557 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(Imm))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001558 GV = dyn_cast<GlobalValue>(SU->getValue());
Evan Chengf2704c02009-02-21 02:06:47 +00001559 int64_t Offset = 0;
Dan Gohman9a769972009-04-18 17:56:28 +00001560 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Imm))
Evan Chengf2704c02009-02-21 02:06:47 +00001561 Offset = SC->getValue()->getSExtValue();
1562 if (GV || Offset)
Dan Gohmanea6eae72009-03-09 21:04:19 +00001563 // Pass VoidTy as the AccessTy to be conservative, because
1564 // there could be multiple access types among all the uses.
1565 DoSink = IsImmFoldedIntoAddrMode(GV, Offset, Type::VoidTy,
Evan Chengf2704c02009-02-21 02:06:47 +00001566 UsersToProcess, TLI);
1567
1568 if (DoSink) {
1569 DOUT << " Sinking " << *Imm << " back down into uses\n";
1570 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1571 UsersToProcess[i].Imm = SE->getAddExpr(UsersToProcess[i].Imm, Imm);
1572 CommonExprs = NewCommon;
1573 HaveCommonExprs = !CommonExprs->isZero();
1574 ++NumImmSunk;
1575 }
1576 }
1577 }
1578
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001579 // Now that we know what we need to do, insert the PHI node itself.
1580 //
Dan Gohman62d4cb02009-02-19 19:23:27 +00001581 DOUT << "LSR: Examining IVs of TYPE " << *ReplacedTy << " of STRIDE "
1582 << *Stride << ":\n"
1583 << " Common base: " << *CommonExprs << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001584
Dan Gohmand0c01232009-05-19 02:15:55 +00001585 SCEVExpander Rewriter(*SE);
1586 SCEVExpander PreheaderRewriter(*SE);
Dan Gohman7cb042d2009-02-20 04:17:46 +00001587
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001588 BasicBlock *Preheader = L->getLoopPreheader();
1589 Instruction *PreInsertPt = Preheader->getTerminator();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001590 BasicBlock *LatchBlock = L->getLoopLatch();
Evan Cheng56cfcd72009-05-11 22:33:01 +00001591 Instruction *IVIncInsertPt = LatchBlock->getTerminator();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001592
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001593 Value *CommonBaseV = Constant::getNullValue(ReplacedTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001594
Dan Gohman7cb042d2009-02-20 04:17:46 +00001595 SCEVHandle RewriteFactor = SE->getIntegerSCEV(0, ReplacedTy);
1596 IVExpr ReuseIV(SE->getIntegerSCEV(0, Type::Int32Ty),
1597 SE->getIntegerSCEV(0, Type::Int32Ty),
Dan Gohman8b90e742009-03-09 22:04:01 +00001598 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001599
Dan Gohman7cb042d2009-02-20 04:17:46 +00001600 /// Choose a strength-reduction strategy and prepare for it by creating
1601 /// the necessary PHIs and adjusting the bookkeeping.
1602 if (ShouldUseFullStrengthReductionMode(UsersToProcess, L,
1603 AllUsesAreAddresses, Stride)) {
1604 PrepareToStrengthReduceFully(UsersToProcess, Stride, CommonExprs, L,
1605 PreheaderRewriter);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001606 } else {
Dan Gohman7cb042d2009-02-20 04:17:46 +00001607 // Emit the initial base value into the loop preheader.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001608 CommonBaseV = PreheaderRewriter.expandCodeFor(CommonExprs, ReplacedTy,
1609 PreInsertPt);
Dan Gohman62d4cb02009-02-19 19:23:27 +00001610
Dale Johannesen0b31ad52009-05-11 17:15:42 +00001611 // If all uses are addresses, check if it is possible to reuse an IV. The
1612 // new IV must have a stride that is a multiple of the old stride; the
1613 // multiple must be a number that can be encoded in the scale field of the
1614 // target addressing mode; and we must have a valid instruction after this
1615 // substitution, including the immediate field, if any.
Dan Gohman7cb042d2009-02-20 04:17:46 +00001616 RewriteFactor = CheckForIVReuse(HaveCommonExprs, AllUsesAreAddresses,
1617 AllUsesAreOutsideLoop,
Dan Gohmand5069b02009-03-09 21:19:58 +00001618 Stride, ReuseIV, ReplacedTy,
Dan Gohman7cb042d2009-02-20 04:17:46 +00001619 UsersToProcess);
Evan Cheng56cfcd72009-05-11 22:33:01 +00001620 if (!RewriteFactor->isZero())
Dan Gohman7cb042d2009-02-20 04:17:46 +00001621 PrepareToStrengthReduceFromSmallerStride(UsersToProcess, CommonBaseV,
1622 ReuseIV, PreInsertPt);
Evan Cheng56cfcd72009-05-11 22:33:01 +00001623 else {
1624 IVIncInsertPt = FindIVIncInsertPt(UsersToProcess, L);
1625 PrepareToStrengthReduceWithNewPhi(UsersToProcess, Stride, CommonExprs,
1626 CommonBaseV, IVIncInsertPt,
1627 L, PreheaderRewriter);
1628 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001629 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001630
Dan Gohman7cb042d2009-02-20 04:17:46 +00001631 // Process all the users now, replacing their strided uses with
1632 // strength-reduced forms. This outer loop handles all bases, the inner
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001633 // loop handles all users of a particular base.
1634 while (!UsersToProcess.empty()) {
1635 SCEVHandle Base = UsersToProcess.back().Base;
Dan Gohman62d4cb02009-02-19 19:23:27 +00001636 Instruction *Inst = UsersToProcess.back().Inst;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001637
1638 // Emit the code for Base into the preheader.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001639 Value *BaseV = 0;
1640 if (!Base->isZero()) {
Dan Gohmand0c01232009-05-19 02:15:55 +00001641 BaseV = PreheaderRewriter.expandCodeFor(Base, 0, PreInsertPt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001642
Dan Gohman01c2ee72009-04-16 03:18:22 +00001643 DOUT << " INSERTING code for BASE = " << *Base << ":";
1644 if (BaseV->hasName())
1645 DOUT << " Result value name = %" << BaseV->getNameStr();
1646 DOUT << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001647
Dan Gohman01c2ee72009-04-16 03:18:22 +00001648 // If BaseV is a non-zero constant, make sure that it gets inserted into
1649 // the preheader, instead of being forward substituted into the uses. We
1650 // do this by forcing a BitCast (noop cast) to be inserted into the
1651 // preheader in this case.
1652 if (!fitsInAddressMode(Base, getAccessType(Inst), TLI, false)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001653 // We want this constant emitted into the preheader! This is just
1654 // using cast as a copy so BitCast (no-op cast) is appropriate
1655 BaseV = new BitCastInst(BaseV, BaseV->getType(), "preheaderinsert",
Dan Gohman5de363f2008-04-14 18:26:16 +00001656 PreInsertPt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001657 }
1658 }
1659
1660 // Emit the code to add the immediate offset to the Phi value, just before
1661 // the instructions that we identified as using this stride and base.
1662 do {
1663 // FIXME: Use emitted users to emit other users.
1664 BasedUser &User = UsersToProcess.back();
1665
Evan Cheng56cfcd72009-05-11 22:33:01 +00001666 DOUT << " Examining ";
1667 if (User.isUseOfPostIncrementedValue)
1668 DOUT << "postinc";
1669 else
1670 DOUT << "preinc";
1671 DOUT << " use ";
Dan Gohman7e467912009-02-19 19:32:06 +00001672 DEBUG(WriteAsOperand(*DOUT, UsersToProcess.back().OperandValToReplace,
1673 /*PrintType=*/false));
Dale Johannesen37beff22009-04-29 22:57:20 +00001674 DOUT << " in Inst: " << *(User.Inst);
Dan Gohman62d4cb02009-02-19 19:23:27 +00001675
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001676 // If this instruction wants to use the post-incremented value, move it
1677 // after the post-inc and use its value instead of the PHI.
Dan Gohman7cb042d2009-02-20 04:17:46 +00001678 Value *RewriteOp = User.Phi;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001679 if (User.isUseOfPostIncrementedValue) {
Dan Gohman8b90e742009-03-09 22:04:01 +00001680 RewriteOp = User.Phi->getIncomingValueForBlock(LatchBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001681 // If this user is in the loop, make sure it is the last thing in the
Evan Cheng56cfcd72009-05-11 22:33:01 +00001682 // loop to ensure it is dominated by the increment. In case it's the
1683 // only use of the iv, the increment instruction is already before the
1684 // use.
1685 if (L->contains(User.Inst->getParent()) && User.Inst != IVIncInsertPt)
1686 User.Inst->moveBefore(IVIncInsertPt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001687 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001688
Dan Gohman89f85052007-10-22 18:31:58 +00001689 SCEVHandle RewriteExpr = SE->getUnknown(RewriteOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001690
Dan Gohman28055122009-05-12 02:17:14 +00001691 if (SE->getEffectiveSCEVType(RewriteOp->getType()) !=
1692 SE->getEffectiveSCEVType(ReplacedTy)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001693 assert(SE->getTypeSizeInBits(RewriteOp->getType()) >
1694 SE->getTypeSizeInBits(ReplacedTy) &&
Dan Gohman56b14e32009-04-16 15:47:35 +00001695 "Unexpected widening cast!");
1696 RewriteExpr = SE->getTruncateExpr(RewriteExpr, ReplacedTy);
1697 }
1698
Dale Johannesen7b7b3d42008-12-16 22:16:28 +00001699 // If we had to insert new instructions for RewriteOp, we have to
Dan Gohmana78c8752008-05-15 23:26:57 +00001700 // consider that they may not have been able to end up immediately
1701 // next to RewriteOp, because non-PHI instructions may never precede
1702 // PHI instructions in a block. In this case, remember where the last
Dan Gohman50b570a2008-05-20 03:01:48 +00001703 // instruction was inserted so that if we're replacing a different
1704 // PHI node, we can use the later point to expand the final
1705 // RewriteExpr.
Dan Gohmana78c8752008-05-15 23:26:57 +00001706 Instruction *NewBasePt = dyn_cast<Instruction>(RewriteOp);
Dan Gohman7cb042d2009-02-20 04:17:46 +00001707 if (RewriteOp == User.Phi) NewBasePt = 0;
Dan Gohmana78c8752008-05-15 23:26:57 +00001708
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001709 // Clear the SCEVExpander's expression map so that we are guaranteed
1710 // to have the code emitted where we expect it.
1711 Rewriter.clear();
1712
1713 // If we are reusing the iv, then it must be multiplied by a constant
Dale Johannesendb25a832009-02-09 22:14:15 +00001714 // factor to take advantage of the addressing mode scale component.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001715 if (!RewriteFactor->isZero()) {
Dale Johannesen671a23c2009-01-14 02:35:31 +00001716 // If we're reusing an IV with a nonzero base (currently this happens
1717 // only when all reuses are outside the loop) subtract that base here.
1718 // The base has been used to initialize the PHI node but we don't want
1719 // it here.
Dale Johannesendb25a832009-02-09 22:14:15 +00001720 if (!ReuseIV.Base->isZero()) {
1721 SCEVHandle typedBase = ReuseIV.Base;
Dan Gohman28055122009-05-12 02:17:14 +00001722 if (SE->getEffectiveSCEVType(RewriteExpr->getType()) !=
1723 SE->getEffectiveSCEVType(ReuseIV.Base->getType())) {
Dale Johannesendb25a832009-02-09 22:14:15 +00001724 // It's possible the original IV is a larger type than the new IV,
1725 // in which case we have to truncate the Base. We checked in
1726 // RequiresTypeConversion that this is valid.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001727 assert(SE->getTypeSizeInBits(RewriteExpr->getType()) <
1728 SE->getTypeSizeInBits(ReuseIV.Base->getType()) &&
Dan Gohman4c0ff852009-04-16 22:35:57 +00001729 "Unexpected lengthening conversion!");
Dale Johannesendb25a832009-02-09 22:14:15 +00001730 typedBase = SE->getTruncateExpr(ReuseIV.Base,
1731 RewriteExpr->getType());
1732 }
1733 RewriteExpr = SE->getMinusSCEV(RewriteExpr, typedBase);
1734 }
Dale Johannesen671a23c2009-01-14 02:35:31 +00001735
1736 // Multiply old variable, with base removed, by new scale factor.
1737 RewriteExpr = SE->getMulExpr(RewriteFactor,
Evan Chengd7ea7002007-10-30 22:27:26 +00001738 RewriteExpr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001739
1740 // The common base is emitted in the loop preheader. But since we
1741 // are reusing an IV, it has not been used to initialize the PHI node.
1742 // Add it to the expression used to rewrite the uses.
Dale Johannesen671a23c2009-01-14 02:35:31 +00001743 // When this use is outside the loop, we earlier subtracted the
1744 // common base, and are adding it back here. Use the same expression
1745 // as before, rather than CommonBaseV, so DAGCombiner will zap it.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001746 if (!CommonExprs->isZero()) {
Dale Johannesen671a23c2009-01-14 02:35:31 +00001747 if (L->contains(User.Inst->getParent()))
1748 RewriteExpr = SE->getAddExpr(RewriteExpr,
Dale Johannesen7b7b3d42008-12-16 22:16:28 +00001749 SE->getUnknown(CommonBaseV));
Dale Johannesen671a23c2009-01-14 02:35:31 +00001750 else
1751 RewriteExpr = SE->getAddExpr(RewriteExpr, CommonExprs);
1752 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001753 }
1754
1755 // Now that we know what we need to do, insert code before User for the
1756 // immediate and any loop-variant expressions.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001757 if (BaseV)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001758 // Add BaseV to the PHI value if needed.
Dan Gohman89f85052007-10-22 18:31:58 +00001759 RewriteExpr = SE->getAddExpr(RewriteExpr, SE->getUnknown(BaseV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001760
Dan Gohmana78c8752008-05-15 23:26:57 +00001761 User.RewriteInstructionToUseNewBase(RewriteExpr, NewBasePt,
Dan Gohmand0c01232009-05-19 02:15:55 +00001762 Rewriter, L, this, *LI,
Evan Chengf7ef8852007-10-30 23:45:15 +00001763 DeadInsts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001764
Chris Lattner3b39baa2008-12-01 06:14:28 +00001765 // Mark old value we replaced as possibly dead, so that it is eliminated
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001766 // if we just replaced the last use of that value.
Dan Gohman28055122009-05-12 02:17:14 +00001767 DeadInsts.push_back(User.OperandValToReplace);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001768
1769 UsersToProcess.pop_back();
1770 ++NumReduced;
1771
1772 // If there are any more users to process with the same base, process them
1773 // now. We sorted by base above, so we just have to check the last elt.
1774 } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
1775 // TODO: Next, find out which base index is the most common, pull it out.
1776 }
1777
1778 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1779 // different starting values, into different PHIs.
1780}
1781
Devang Patel7983eaa2008-08-13 20:31:11 +00001782/// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001783/// set the IV user and stride information and return true, otherwise return
1784/// false.
Devang Patel7983eaa2008-08-13 20:31:11 +00001785bool LoopStrengthReduce::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001786 const SCEVHandle *&CondStride) {
Dan Gohman28055122009-05-12 02:17:14 +00001787 for (unsigned Stride = 0, e = IU->StrideOrder.size();
1788 Stride != e && !CondUse; ++Stride) {
1789 std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
1790 IU->IVUsesByStride.find(IU->StrideOrder[Stride]);
1791 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
1792
1793 for (ilist<IVStrideUse>::iterator UI = SI->second->Users.begin(),
1794 E = SI->second->Users.end(); UI != E; ++UI)
1795 if (UI->getUser() == Cond) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001796 // NOTE: we could handle setcc instructions with multiple uses here, but
1797 // InstCombine does it as well for simple uses, it's not clear that it
1798 // occurs enough in real life to handle.
Dan Gohman28055122009-05-12 02:17:14 +00001799 CondUse = UI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001800 CondStride = &SI->first;
1801 return true;
1802 }
1803 }
1804 return false;
1805}
1806
Evan Cheng335d87d2007-10-25 09:11:16 +00001807namespace {
1808 // Constant strides come first which in turns are sorted by their absolute
1809 // values. If absolute values are the same, then positive strides comes first.
1810 // e.g.
1811 // 4, -1, X, 1, 2 ==> 1, -1, 2, 4, X
1812 struct StrideCompare {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001813 const ScalarEvolution *SE;
1814 explicit StrideCompare(const ScalarEvolution *se) : SE(se) {}
Dan Gohman01c2ee72009-04-16 03:18:22 +00001815
Evan Cheng335d87d2007-10-25 09:11:16 +00001816 bool operator()(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Dan Gohman9a769972009-04-18 17:56:28 +00001817 const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS);
1818 const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
Evan Cheng335d87d2007-10-25 09:11:16 +00001819 if (LHSC && RHSC) {
1820 int64_t LV = LHSC->getValue()->getSExtValue();
1821 int64_t RV = RHSC->getValue()->getSExtValue();
1822 uint64_t ALV = (LV < 0) ? -LV : LV;
1823 uint64_t ARV = (RV < 0) ? -RV : RV;
Dan Gohman6deff6c2009-02-13 00:26:43 +00001824 if (ALV == ARV) {
1825 if (LV != RV)
1826 return LV > RV;
1827 } else {
Evan Cheng335d87d2007-10-25 09:11:16 +00001828 return ALV < ARV;
Dan Gohman6deff6c2009-02-13 00:26:43 +00001829 }
1830
1831 // If it's the same value but different type, sort by bit width so
1832 // that we emit larger induction variables before smaller
1833 // ones, letting the smaller be re-written in terms of larger ones.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001834 return SE->getTypeSizeInBits(RHS->getType()) <
1835 SE->getTypeSizeInBits(LHS->getType());
Evan Cheng335d87d2007-10-25 09:11:16 +00001836 }
Dan Gohman6deff6c2009-02-13 00:26:43 +00001837 return LHSC && !RHSC;
Evan Cheng335d87d2007-10-25 09:11:16 +00001838 }
1839 };
1840}
1841
1842/// ChangeCompareStride - If a loop termination compare instruction is the
1843/// only use of its stride, and the compaison is against a constant value,
1844/// try eliminate the stride by moving the compare instruction to another
1845/// stride and change its constant operand accordingly. e.g.
1846///
1847/// loop:
1848/// ...
1849/// v1 = v1 + 3
1850/// v2 = v2 + 1
1851/// if (v2 < 10) goto loop
1852/// =>
1853/// loop:
1854/// ...
1855/// v1 = v1 + 3
1856/// if (v1 < 30) goto loop
1857ICmpInst *LoopStrengthReduce::ChangeCompareStride(Loop *L, ICmpInst *Cond,
Evan Chengf7ef8852007-10-30 23:45:15 +00001858 IVStrideUse* &CondUse,
Evan Cheng335d87d2007-10-25 09:11:16 +00001859 const SCEVHandle* &CondStride) {
Dan Gohman28055122009-05-12 02:17:14 +00001860 // If there's only one stride in the loop, there's nothing to do here.
1861 if (IU->StrideOrder.size() < 2)
Evan Cheng335d87d2007-10-25 09:11:16 +00001862 return Cond;
Dan Gohman28055122009-05-12 02:17:14 +00001863 // If there are other users of the condition's stride, don't bother
1864 // trying to change the condition because the stride will still
1865 // remain.
1866 std::map<SCEVHandle, IVUsersOfOneStride *>::iterator I =
1867 IU->IVUsesByStride.find(*CondStride);
1868 if (I == IU->IVUsesByStride.end() ||
1869 I->second->Users.size() != 1)
1870 return Cond;
1871 // Only handle constant strides for now.
Evan Cheng335d87d2007-10-25 09:11:16 +00001872 const SCEVConstant *SC = dyn_cast<SCEVConstant>(*CondStride);
1873 if (!SC) return Cond;
Evan Cheng335d87d2007-10-25 09:11:16 +00001874
1875 ICmpInst::Predicate Predicate = Cond->getPredicate();
Evan Cheng335d87d2007-10-25 09:11:16 +00001876 int64_t CmpSSInt = SC->getValue()->getSExtValue();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001877 unsigned BitWidth = SE->getTypeSizeInBits((*CondStride)->getType());
Evan Cheng635b8f82007-10-26 23:08:19 +00001878 uint64_t SignBit = 1ULL << (BitWidth-1);
Dan Gohmanc0cdd9272009-02-24 01:58:00 +00001879 const Type *CmpTy = Cond->getOperand(0)->getType();
Evan Cheng635b8f82007-10-26 23:08:19 +00001880 const Type *NewCmpTy = NULL;
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001881 unsigned TyBits = SE->getTypeSizeInBits(CmpTy);
Evan Cheng0ae1de62007-10-29 22:07:18 +00001882 unsigned NewTyBits = 0;
Evan Cheng335d87d2007-10-25 09:11:16 +00001883 SCEVHandle *NewStride = NULL;
Dan Gohman7e4f8042009-02-20 21:27:23 +00001884 Value *NewCmpLHS = NULL;
1885 Value *NewCmpRHS = NULL;
Evan Cheng335d87d2007-10-25 09:11:16 +00001886 int64_t Scale = 1;
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001887 SCEVHandle NewOffset = SE->getIntegerSCEV(0, CmpTy);
Evan Cheng335d87d2007-10-25 09:11:16 +00001888
Dan Gohmanc0cdd9272009-02-24 01:58:00 +00001889 if (ConstantInt *C = dyn_cast<ConstantInt>(Cond->getOperand(1))) {
1890 int64_t CmpVal = C->getValue().getSExtValue();
Evan Cheng635b8f82007-10-26 23:08:19 +00001891
Dan Gohmanc0cdd9272009-02-24 01:58:00 +00001892 // Check stride constant and the comparision constant signs to detect
1893 // overflow.
1894 if ((CmpVal & SignBit) != (CmpSSInt & SignBit))
1895 return Cond;
Evan Cheng635b8f82007-10-26 23:08:19 +00001896
Dan Gohmanc0cdd9272009-02-24 01:58:00 +00001897 // Look for a suitable stride / iv as replacement.
Dan Gohman28055122009-05-12 02:17:14 +00001898 for (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
1899 std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
1900 IU->IVUsesByStride.find(IU->StrideOrder[i]);
Dan Gohmanc0cdd9272009-02-24 01:58:00 +00001901 if (!isa<SCEVConstant>(SI->first))
Dan Gohman7e4f8042009-02-20 21:27:23 +00001902 continue;
Dan Gohmanc0cdd9272009-02-24 01:58:00 +00001903 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
Dan Gohman77304eb2009-04-27 20:35:32 +00001904 if (SSInt == CmpSSInt ||
Dale Johannesen8634ce32009-05-13 00:24:22 +00001905 abs64(SSInt) < abs64(CmpSSInt) ||
Dan Gohman77304eb2009-04-27 20:35:32 +00001906 (SSInt % CmpSSInt) != 0)
Dan Gohmanc0cdd9272009-02-24 01:58:00 +00001907 continue;
1908
1909 Scale = SSInt / CmpSSInt;
1910 int64_t NewCmpVal = CmpVal * Scale;
David Greenebc0460f2009-05-06 17:39:26 +00001911 APInt Mul = APInt(BitWidth*2, CmpVal, true);
1912 Mul = Mul * APInt(BitWidth*2, Scale, true);
Dan Gohmanc0cdd9272009-02-24 01:58:00 +00001913 // Check for overflow.
Evan Chengec1552d2009-05-06 18:00:56 +00001914 if (!Mul.isSignedIntN(BitWidth))
Dan Gohmanc0cdd9272009-02-24 01:58:00 +00001915 continue;
Dan Gohman28055122009-05-12 02:17:14 +00001916 // Check for overflow in the stride's type too.
1917 if (!Mul.isSignedIntN(SE->getTypeSizeInBits(SI->first->getType())))
1918 continue;
Dan Gohmanc0cdd9272009-02-24 01:58:00 +00001919
1920 // Watch out for overflow.
1921 if (ICmpInst::isSignedPredicate(Predicate) &&
1922 (CmpVal & SignBit) != (NewCmpVal & SignBit))
1923 continue;
1924
1925 if (NewCmpVal == CmpVal)
1926 continue;
1927 // Pick the best iv to use trying to avoid a cast.
1928 NewCmpLHS = NULL;
Dan Gohman28055122009-05-12 02:17:14 +00001929 for (ilist<IVStrideUse>::iterator UI = SI->second->Users.begin(),
1930 E = SI->second->Users.end(); UI != E; ++UI) {
1931 Value *Op = UI->getOperandValToReplace();
1932
1933 // If the IVStrideUse implies a cast, check for an actual cast which
1934 // can be used to find the original IV expression.
1935 if (SE->getEffectiveSCEVType(Op->getType()) !=
1936 SE->getEffectiveSCEVType(SI->first->getType())) {
1937 CastInst *CI = dyn_cast<CastInst>(Op);
1938 // If it's not a simple cast, it's complicated.
1939 if (!CI)
1940 continue;
1941 // If it's a cast from a type other than the stride type,
1942 // it's complicated.
1943 if (CI->getOperand(0)->getType() != SI->first->getType())
1944 continue;
1945 // Ok, we found the IV expression in the stride's type.
1946 Op = CI->getOperand(0);
1947 }
1948
1949 NewCmpLHS = Op;
Dan Gohmanc0cdd9272009-02-24 01:58:00 +00001950 if (NewCmpLHS->getType() == CmpTy)
1951 break;
1952 }
1953 if (!NewCmpLHS)
1954 continue;
1955
1956 NewCmpTy = NewCmpLHS->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001957 NewTyBits = SE->getTypeSizeInBits(NewCmpTy);
1958 const Type *NewCmpIntTy = IntegerType::get(NewTyBits);
Dan Gohmanc0cdd9272009-02-24 01:58:00 +00001959 if (RequiresTypeConversion(NewCmpTy, CmpTy)) {
1960 // Check if it is possible to rewrite it using
1961 // an iv / stride of a smaller integer type.
Dan Gohman3f375ec2009-04-16 16:49:48 +00001962 unsigned Bits = NewTyBits;
1963 if (ICmpInst::isSignedPredicate(Predicate))
1964 --Bits;
1965 uint64_t Mask = (1ULL << Bits) - 1;
1966 if (((uint64_t)NewCmpVal & Mask) != (uint64_t)NewCmpVal)
Dan Gohmanc0cdd9272009-02-24 01:58:00 +00001967 continue;
1968 }
1969
1970 // Don't rewrite if use offset is non-constant and the new type is
1971 // of a different type.
1972 // FIXME: too conservative?
Dan Gohman28055122009-05-12 02:17:14 +00001973 if (NewTyBits != TyBits && !isa<SCEVConstant>(CondUse->getOffset()))
Dan Gohmanc0cdd9272009-02-24 01:58:00 +00001974 continue;
1975
1976 bool AllUsesAreAddresses = true;
1977 bool AllUsesAreOutsideLoop = true;
1978 std::vector<BasedUser> UsersToProcess;
Dan Gohman28055122009-05-12 02:17:14 +00001979 SCEVHandle CommonExprs = CollectIVUsers(SI->first, *SI->second, L,
Dan Gohmanc0cdd9272009-02-24 01:58:00 +00001980 AllUsesAreAddresses,
1981 AllUsesAreOutsideLoop,
1982 UsersToProcess);
1983 // Avoid rewriting the compare instruction with an iv of new stride
1984 // if it's likely the new stride uses will be rewritten using the
1985 // stride of the compare instruction.
1986 if (AllUsesAreAddresses &&
Evan Cheng56cfcd72009-05-11 22:33:01 +00001987 ValidScale(!CommonExprs->isZero(), Scale, UsersToProcess))
Dan Gohmanc0cdd9272009-02-24 01:58:00 +00001988 continue;
1989
1990 // If scale is negative, use swapped predicate unless it's testing
1991 // for equality.
1992 if (Scale < 0 && !Cond->isEquality())
1993 Predicate = ICmpInst::getSwappedPredicate(Predicate);
1994
Dan Gohman28055122009-05-12 02:17:14 +00001995 NewStride = &IU->StrideOrder[i];
Dan Gohmanc0cdd9272009-02-24 01:58:00 +00001996 if (!isa<PointerType>(NewCmpTy))
1997 NewCmpRHS = ConstantInt::get(NewCmpTy, NewCmpVal);
1998 else {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001999 ConstantInt *CI = ConstantInt::get(NewCmpIntTy, NewCmpVal);
Dan Gohman8ff112a2009-04-16 15:48:38 +00002000 NewCmpRHS = ConstantExpr::getIntToPtr(CI, NewCmpTy);
Dan Gohmanc0cdd9272009-02-24 01:58:00 +00002001 }
2002 NewOffset = TyBits == NewTyBits
Dan Gohman28055122009-05-12 02:17:14 +00002003 ? SE->getMulExpr(CondUse->getOffset(),
Dan Gohmanc0cdd9272009-02-24 01:58:00 +00002004 SE->getConstant(ConstantInt::get(CmpTy, Scale)))
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002005 : SE->getConstant(ConstantInt::get(NewCmpIntTy,
Dan Gohman28055122009-05-12 02:17:14 +00002006 cast<SCEVConstant>(CondUse->getOffset())->getValue()
2007 ->getSExtValue()*Scale));
Dan Gohmanc0cdd9272009-02-24 01:58:00 +00002008 break;
Dan Gohman7e4f8042009-02-20 21:27:23 +00002009 }
Evan Cheng335d87d2007-10-25 09:11:16 +00002010 }
2011
Dan Gohmancb387ac2008-06-16 22:34:15 +00002012 // Forgo this transformation if it the increment happens to be
2013 // unfortunately positioned after the condition, and the condition
2014 // has multiple uses which prevent it from being moved immediately
2015 // before the branch. See
2016 // test/Transforms/LoopStrengthReduce/change-compare-stride-trickiness-*.ll
2017 // for an example of this situation.
Devang Patelb6ccbce2008-08-13 02:05:14 +00002018 if (!Cond->hasOneUse()) {
Dan Gohmancb387ac2008-06-16 22:34:15 +00002019 for (BasicBlock::iterator I = Cond, E = Cond->getParent()->end();
2020 I != E; ++I)
Dan Gohman7e4f8042009-02-20 21:27:23 +00002021 if (I == NewCmpLHS)
Dan Gohmancb387ac2008-06-16 22:34:15 +00002022 return Cond;
Devang Patelb6ccbce2008-08-13 02:05:14 +00002023 }
Dan Gohmancb387ac2008-06-16 22:34:15 +00002024
Dan Gohman7e4f8042009-02-20 21:27:23 +00002025 if (NewCmpRHS) {
Evan Cheng335d87d2007-10-25 09:11:16 +00002026 // Create a new compare instruction using new stride / iv.
2027 ICmpInst *OldCond = Cond;
Evan Cheng635b8f82007-10-26 23:08:19 +00002028 // Insert new compare instruction.
Dan Gohman7e4f8042009-02-20 21:27:23 +00002029 Cond = new ICmpInst(Predicate, NewCmpLHS, NewCmpRHS,
Dan Gohman87bc2f12008-06-13 21:43:41 +00002030 L->getHeader()->getName() + ".termcond",
2031 OldCond);
Evan Cheng635b8f82007-10-26 23:08:19 +00002032
2033 // Remove the old compare instruction. The old indvar is probably dead too.
Dan Gohman28055122009-05-12 02:17:14 +00002034 DeadInsts.push_back(CondUse->getOperandValToReplace());
Dan Gohman3dfab2b2008-05-21 00:54:12 +00002035 OldCond->replaceAllUsesWith(Cond);
Evan Cheng335d87d2007-10-25 09:11:16 +00002036 OldCond->eraseFromParent();
Evan Cheng635b8f82007-10-26 23:08:19 +00002037
Dan Gohman28055122009-05-12 02:17:14 +00002038 IU->IVUsesByStride[*NewStride]->addUser(NewOffset, Cond, NewCmpLHS, false);
2039 CondUse = &IU->IVUsesByStride[*NewStride]->Users.back();
Evan Cheng335d87d2007-10-25 09:11:16 +00002040 CondStride = NewStride;
2041 ++NumEliminated;
Dan Gohman93efe962009-05-02 18:29:22 +00002042 Changed = true;
Evan Cheng335d87d2007-10-25 09:11:16 +00002043 }
2044
2045 return Cond;
2046}
2047
Dan Gohman156bf982008-09-15 21:22:06 +00002048/// OptimizeSMax - Rewrite the loop's terminating condition if it uses
2049/// an smax computation.
2050///
2051/// This is a narrow solution to a specific, but acute, problem. For loops
2052/// like this:
2053///
2054/// i = 0;
2055/// do {
2056/// p[i] = 0.0;
2057/// } while (++i < n);
2058///
2059/// where the comparison is signed, the trip count isn't just 'n', because
2060/// 'n' could be negative. And unfortunately this can come up even for loops
2061/// where the user didn't use a C do-while loop. For example, seemingly
2062/// well-behaved top-test loops will commonly be lowered like this:
2063//
2064/// if (n > 0) {
2065/// i = 0;
2066/// do {
2067/// p[i] = 0.0;
2068/// } while (++i < n);
2069/// }
2070///
2071/// and then it's possible for subsequent optimization to obscure the if
2072/// test in such a way that indvars can't find it.
2073///
2074/// When indvars can't find the if test in loops like this, it creates a
2075/// signed-max expression, which allows it to give the loop a canonical
2076/// induction variable:
2077///
2078/// i = 0;
2079/// smax = n < 1 ? 1 : n;
2080/// do {
2081/// p[i] = 0.0;
2082/// } while (++i != smax);
2083///
2084/// Canonical induction variables are necessary because the loop passes
2085/// are designed around them. The most obvious example of this is the
2086/// LoopInfo analysis, which doesn't remember trip count values. It
2087/// expects to be able to rediscover the trip count each time it is
2088/// needed, and it does this using a simple analyis that only succeeds if
2089/// the loop has a canonical induction variable.
2090///
2091/// However, when it comes time to generate code, the maximum operation
2092/// can be quite costly, especially if it's inside of an outer loop.
2093///
2094/// This function solves this problem by detecting this type of loop and
2095/// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
2096/// the instructions for the maximum computation.
2097///
2098ICmpInst *LoopStrengthReduce::OptimizeSMax(Loop *L, ICmpInst *Cond,
2099 IVStrideUse* &CondUse) {
2100 // Check that the loop matches the pattern we're looking for.
2101 if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
2102 Cond->getPredicate() != CmpInst::ICMP_NE)
2103 return Cond;
2104
2105 SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
2106 if (!Sel || !Sel->hasOneUse()) return Cond;
2107
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002108 SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2109 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
Dan Gohman156bf982008-09-15 21:22:06 +00002110 return Cond;
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002111 SCEVHandle One = SE->getIntegerSCEV(1, BackedgeTakenCount->getType());
Dan Gohman156bf982008-09-15 21:22:06 +00002112
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002113 // Add one to the backedge-taken count to get the trip count.
2114 SCEVHandle IterationCount = SE->getAddExpr(BackedgeTakenCount, One);
Dan Gohman156bf982008-09-15 21:22:06 +00002115
2116 // Check for a max calculation that matches the pattern.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002117 const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(IterationCount);
Dan Gohman156bf982008-09-15 21:22:06 +00002118 if (!SMax || SMax != SE->getSCEV(Sel)) return Cond;
2119
2120 SCEVHandle SMaxLHS = SMax->getOperand(0);
2121 SCEVHandle SMaxRHS = SMax->getOperand(1);
2122 if (!SMaxLHS || SMaxLHS != One) return Cond;
2123
2124 // Check the relevant induction variable for conformance to
2125 // the pattern.
2126 SCEVHandle IV = SE->getSCEV(Cond->getOperand(0));
Dan Gohman9a769972009-04-18 17:56:28 +00002127 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
Dan Gohman156bf982008-09-15 21:22:06 +00002128 if (!AR || !AR->isAffine() ||
2129 AR->getStart() != One ||
2130 AR->getStepRecurrence(*SE) != One)
2131 return Cond;
2132
Dan Gohman35fdc222009-03-04 20:49:01 +00002133 assert(AR->getLoop() == L &&
2134 "Loop condition operand is an addrec in a different loop!");
2135
Dan Gohman156bf982008-09-15 21:22:06 +00002136 // Check the right operand of the select, and remember it, as it will
2137 // be used in the new comparison instruction.
2138 Value *NewRHS = 0;
2139 if (SE->getSCEV(Sel->getOperand(1)) == SMaxRHS)
2140 NewRHS = Sel->getOperand(1);
2141 else if (SE->getSCEV(Sel->getOperand(2)) == SMaxRHS)
2142 NewRHS = Sel->getOperand(2);
2143 if (!NewRHS) return Cond;
2144
2145 // Ok, everything looks ok to change the condition into an SLT or SGE and
2146 // delete the max calculation.
2147 ICmpInst *NewCond =
2148 new ICmpInst(Cond->getPredicate() == CmpInst::ICMP_NE ?
2149 CmpInst::ICMP_SLT :
2150 CmpInst::ICMP_SGE,
2151 Cond->getOperand(0), NewRHS, "scmp", Cond);
2152
2153 // Delete the max calculation instructions.
2154 Cond->replaceAllUsesWith(NewCond);
Dan Gohman28055122009-05-12 02:17:14 +00002155 CondUse->setUser(NewCond);
Dan Gohman156bf982008-09-15 21:22:06 +00002156 Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
Dan Gohman28055122009-05-12 02:17:14 +00002157 Cond->eraseFromParent();
Dan Gohmana9a6f172008-10-01 02:02:03 +00002158 Sel->eraseFromParent();
Dan Gohmanbff6b582009-05-04 22:30:44 +00002159 if (Cmp->use_empty())
Dan Gohmana9a6f172008-10-01 02:02:03 +00002160 Cmp->eraseFromParent();
Dan Gohman156bf982008-09-15 21:22:06 +00002161 return NewCond;
2162}
2163
Devang Patele4a78772008-08-26 17:57:54 +00002164/// OptimizeShadowIV - If IV is used in a int-to-float cast
2165/// inside the loop then try to eliminate the cast opeation.
2166void LoopStrengthReduce::OptimizeShadowIV(Loop *L) {
2167
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002168 SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2169 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
Devang Patele4a78772008-08-26 17:57:54 +00002170 return;
2171
Dan Gohman28055122009-05-12 02:17:14 +00002172 for (unsigned Stride = 0, e = IU->StrideOrder.size(); Stride != e;
Devang Patele4a78772008-08-26 17:57:54 +00002173 ++Stride) {
Dan Gohman28055122009-05-12 02:17:14 +00002174 std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
2175 IU->IVUsesByStride.find(IU->StrideOrder[Stride]);
2176 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
Devang Patele4a78772008-08-26 17:57:54 +00002177 if (!isa<SCEVConstant>(SI->first))
2178 continue;
2179
Dan Gohman28055122009-05-12 02:17:14 +00002180 for (ilist<IVStrideUse>::iterator UI = SI->second->Users.begin(),
2181 E = SI->second->Users.end(); UI != E; /* empty */) {
2182 ilist<IVStrideUse>::iterator CandidateUI = UI;
Devang Patelc1fc0fc2008-08-27 17:50:18 +00002183 ++UI;
Dan Gohman28055122009-05-12 02:17:14 +00002184 Instruction *ShadowUse = CandidateUI->getUser();
Devang Patele4a78772008-08-26 17:57:54 +00002185 const Type *DestTy = NULL;
2186
2187 /* If shadow use is a int->float cast then insert a second IV
Devang Patelc1fc0fc2008-08-27 17:50:18 +00002188 to eliminate this cast.
Devang Patele4a78772008-08-26 17:57:54 +00002189
2190 for (unsigned i = 0; i < n; ++i)
2191 foo((double)i);
2192
Devang Patelc1fc0fc2008-08-27 17:50:18 +00002193 is transformed into
Devang Patele4a78772008-08-26 17:57:54 +00002194
2195 double d = 0.0;
2196 for (unsigned i = 0; i < n; ++i, ++d)
2197 foo(d);
2198 */
Dan Gohman28055122009-05-12 02:17:14 +00002199 if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser()))
Devang Patele4a78772008-08-26 17:57:54 +00002200 DestTy = UCast->getDestTy();
Dan Gohman28055122009-05-12 02:17:14 +00002201 else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser()))
Devang Patele4a78772008-08-26 17:57:54 +00002202 DestTy = SCast->getDestTy();
Devang Patel704c5252008-08-27 20:55:23 +00002203 if (!DestTy) continue;
2204
2205 if (TLI) {
Evan Cheng56cfcd72009-05-11 22:33:01 +00002206 // If target does not support DestTy natively then do not apply
2207 // this transformation.
Devang Patel704c5252008-08-27 20:55:23 +00002208 MVT DVT = TLI->getValueType(DestTy);
2209 if (!TLI->isTypeLegal(DVT)) continue;
2210 }
2211
Devang Patele4a78772008-08-26 17:57:54 +00002212 PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
2213 if (!PH) continue;
2214 if (PH->getNumIncomingValues() != 2) continue;
2215
2216 const Type *SrcTy = PH->getType();
2217 int Mantissa = DestTy->getFPMantissaWidth();
2218 if (Mantissa == -1) continue;
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002219 if ((int)SE->getTypeSizeInBits(SrcTy) > Mantissa)
Devang Patele4a78772008-08-26 17:57:54 +00002220 continue;
2221
2222 unsigned Entry, Latch;
2223 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
2224 Entry = 0;
2225 Latch = 1;
2226 } else {
2227 Entry = 1;
2228 Latch = 0;
2229 }
2230
2231 ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
2232 if (!Init) continue;
2233 ConstantFP *NewInit = ConstantFP::get(DestTy, Init->getZExtValue());
2234
2235 BinaryOperator *Incr =
2236 dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
2237 if (!Incr) continue;
2238 if (Incr->getOpcode() != Instruction::Add
2239 && Incr->getOpcode() != Instruction::Sub)
2240 continue;
2241
2242 /* Initialize new IV, double d = 0.0 in above example. */
2243 ConstantInt *C = NULL;
2244 if (Incr->getOperand(0) == PH)
2245 C = dyn_cast<ConstantInt>(Incr->getOperand(1));
2246 else if (Incr->getOperand(1) == PH)
2247 C = dyn_cast<ConstantInt>(Incr->getOperand(0));
2248 else
2249 continue;
2250
2251 if (!C) continue;
2252
2253 /* Add new PHINode. */
2254 PHINode *NewPH = PHINode::Create(DestTy, "IV.S.", PH);
2255
Devang Patelc1fc0fc2008-08-27 17:50:18 +00002256 /* create new increment. '++d' in above example. */
Devang Patele4a78772008-08-26 17:57:54 +00002257 ConstantFP *CFP = ConstantFP::get(DestTy, C->getZExtValue());
2258 BinaryOperator *NewIncr =
2259 BinaryOperator::Create(Incr->getOpcode(),
2260 NewPH, CFP, "IV.S.next.", Incr);
2261
2262 NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
2263 NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
2264
2265 /* Remove cast operation */
Devang Patele4a78772008-08-26 17:57:54 +00002266 ShadowUse->replaceAllUsesWith(NewPH);
2267 ShadowUse->eraseFromParent();
Devang Patele4a78772008-08-26 17:57:54 +00002268 NumShadow++;
2269 break;
2270 }
2271 }
2272}
2273
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002274// OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
2275// uses in the loop, look to see if we can eliminate some, in favor of using
2276// common indvars for the different uses.
2277void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
2278 // TODO: implement optzns here.
2279
Devang Patele4a78772008-08-26 17:57:54 +00002280 OptimizeShadowIV(L);
Evan Cheng5316a262009-05-09 01:08:24 +00002281}
2282
2283/// OptimizeLoopTermCond - Change loop terminating condition to use the
2284/// postinc iv when possible.
2285void LoopStrengthReduce::OptimizeLoopTermCond(Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002286 // Finally, get the terminating condition for the loop if possible. If we
2287 // can, we want to change it to use a post-incremented version of its
2288 // induction variable, to allow coalescing the live ranges for the IV into
2289 // one register value.
Evan Cheng56cfcd72009-05-11 22:33:01 +00002290 BasicBlock *LatchBlock = L->getLoopLatch();
2291 BasicBlock *ExitBlock = L->getExitingBlock();
2292 if (!ExitBlock)
2293 // Multiple exits, just look at the exit in the latch block if there is one.
2294 ExitBlock = LatchBlock;
2295 BranchInst *TermBr = dyn_cast<BranchInst>(ExitBlock->getTerminator());
2296 if (!TermBr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002297 return;
Evan Cheng56cfcd72009-05-11 22:33:01 +00002298 if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
2299 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002300
2301 // Search IVUsesByStride to find Cond's IVUse if there is one.
2302 IVStrideUse *CondUse = 0;
2303 const SCEVHandle *CondStride = 0;
Evan Cheng56cfcd72009-05-11 22:33:01 +00002304 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
Devang Patel7983eaa2008-08-13 20:31:11 +00002305 if (!FindIVUserForCond(Cond, CondUse, CondStride))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002306 return; // setcc doesn't use the IV.
Evan Cheng335d87d2007-10-25 09:11:16 +00002307
Evan Cheng56cfcd72009-05-11 22:33:01 +00002308 if (ExitBlock != LatchBlock) {
2309 if (!Cond->hasOneUse())
2310 // See below, we don't want the condition to be cloned.
2311 return;
2312
2313 // If exiting block is the latch block, we know it's safe and profitable to
2314 // transform the icmp to use post-inc iv. Otherwise do so only if it would
2315 // not reuse another iv and its iv would be reused by other uses. We are
2316 // optimizing for the case where the icmp is the only use of the iv.
Dan Gohman28055122009-05-12 02:17:14 +00002317 IVUsersOfOneStride &StrideUses = *IU->IVUsesByStride[*CondStride];
2318 for (ilist<IVStrideUse>::iterator I = StrideUses.Users.begin(),
2319 E = StrideUses.Users.end(); I != E; ++I) {
2320 if (I->getUser() == Cond)
Evan Cheng56cfcd72009-05-11 22:33:01 +00002321 continue;
Dan Gohman28055122009-05-12 02:17:14 +00002322 if (!I->isUseOfPostIncrementedValue())
Evan Cheng56cfcd72009-05-11 22:33:01 +00002323 return;
2324 }
2325
2326 // FIXME: This is expensive, and worse still ChangeCompareStride does a
2327 // similar check. Can we perform all the icmp related transformations after
2328 // StrengthReduceStridedIVUsers?
2329 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(*CondStride)) {
2330 int64_t SInt = SC->getValue()->getSExtValue();
Dan Gohman28055122009-05-12 02:17:14 +00002331 for (unsigned NewStride = 0, ee = IU->StrideOrder.size(); NewStride != ee;
Evan Cheng56cfcd72009-05-11 22:33:01 +00002332 ++NewStride) {
Dan Gohman28055122009-05-12 02:17:14 +00002333 std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
2334 IU->IVUsesByStride.find(IU->StrideOrder[NewStride]);
Evan Cheng56cfcd72009-05-11 22:33:01 +00002335 if (!isa<SCEVConstant>(SI->first) || SI->first == *CondStride)
2336 continue;
2337 int64_t SSInt =
2338 cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
2339 if (SSInt == SInt)
2340 return; // This can definitely be reused.
Dale Johannesen8634ce32009-05-13 00:24:22 +00002341 if (unsigned(abs64(SSInt)) < SInt || (SSInt % SInt) != 0)
Evan Cheng56cfcd72009-05-11 22:33:01 +00002342 continue;
2343 int64_t Scale = SSInt / SInt;
2344 bool AllUsesAreAddresses = true;
2345 bool AllUsesAreOutsideLoop = true;
2346 std::vector<BasedUser> UsersToProcess;
Dan Gohman28055122009-05-12 02:17:14 +00002347 SCEVHandle CommonExprs = CollectIVUsers(SI->first, *SI->second, L,
Evan Cheng56cfcd72009-05-11 22:33:01 +00002348 AllUsesAreAddresses,
2349 AllUsesAreOutsideLoop,
2350 UsersToProcess);
2351 // Avoid rewriting the compare instruction with an iv of new stride
2352 // if it's likely the new stride uses will be rewritten using the
2353 // stride of the compare instruction.
2354 if (AllUsesAreAddresses &&
2355 ValidScale(!CommonExprs->isZero(), Scale, UsersToProcess))
2356 return;
2357 }
2358 }
2359
2360 StrideNoReuse.insert(*CondStride);
2361 }
2362
Dan Gohman156bf982008-09-15 21:22:06 +00002363 // If the trip count is computed in terms of an smax (due to ScalarEvolution
2364 // being unable to find a sufficient guard, for example), change the loop
2365 // comparison to use SLT instead of NE.
2366 Cond = OptimizeSMax(L, Cond, CondUse);
2367
Evan Cheng335d87d2007-10-25 09:11:16 +00002368 // If possible, change stride and operands of the compare instruction to
2369 // eliminate one stride.
Evan Cheng56cfcd72009-05-11 22:33:01 +00002370 if (ExitBlock == LatchBlock)
2371 Cond = ChangeCompareStride(L, Cond, CondUse, CondStride);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002372
2373 // It's possible for the setcc instruction to be anywhere in the loop, and
2374 // possible for it to have multiple users. If it is not immediately before
2375 // the latch block branch, move it.
2376 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
2377 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
2378 Cond->moveBefore(TermBr);
2379 } else {
2380 // Otherwise, clone the terminating condition and insert into the loopend.
2381 Cond = cast<ICmpInst>(Cond->clone());
2382 Cond->setName(L->getHeader()->getName() + ".termcond");
2383 LatchBlock->getInstList().insert(TermBr, Cond);
2384
2385 // Clone the IVUse, as the old use still exists!
Dan Gohman28055122009-05-12 02:17:14 +00002386 IU->IVUsesByStride[*CondStride]->addUser(CondUse->getOffset(), Cond,
2387 CondUse->getOperandValToReplace(),
2388 false);
2389 CondUse = &IU->IVUsesByStride[*CondStride]->Users.back();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002390 }
2391 }
2392
2393 // If we get to here, we know that we can transform the setcc instruction to
2394 // use the post-incremented version of the IV, allowing us to coalesce the
2395 // live ranges for the IV correctly.
Dan Gohman28055122009-05-12 02:17:14 +00002396 CondUse->setOffset(SE->getMinusSCEV(CondUse->getOffset(), *CondStride));
2397 CondUse->setIsUseOfPostIncrementedValue(true);
Evan Cheng5af5ad52008-07-07 19:51:32 +00002398 Changed = true;
Evan Cheng56cfcd72009-05-11 22:33:01 +00002399
2400 ++NumLoopCond;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002401}
2402
Dale Johannesen0b31ad52009-05-11 17:15:42 +00002403// OptimizeLoopCountIV - If, after all sharing of IVs, the IV used for deciding
2404// when to exit the loop is used only for that purpose, try to rearrange things
2405// so it counts down to a test against zero.
2406void LoopStrengthReduce::OptimizeLoopCountIV(Loop *L) {
2407
2408 // If the number of times the loop is executed isn't computable, give up.
2409 SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2410 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2411 return;
2412
2413 // Get the terminating condition for the loop if possible (this isn't
2414 // necessarily in the latch, or a block that's a predecessor of the header).
2415 SmallVector<BasicBlock*, 8> ExitBlocks;
2416 L->getExitBlocks(ExitBlocks);
2417 if (ExitBlocks.size() != 1) return;
2418
2419 // Okay, there is one exit block. Try to find the condition that causes the
2420 // loop to be exited.
2421 BasicBlock *ExitBlock = ExitBlocks[0];
2422
2423 BasicBlock *ExitingBlock = 0;
2424 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
2425 PI != E; ++PI)
2426 if (L->contains(*PI)) {
2427 if (ExitingBlock == 0)
2428 ExitingBlock = *PI;
2429 else
2430 return; // More than one block exiting!
2431 }
2432 assert(ExitingBlock && "No exits from loop, something is broken!");
2433
2434 // Okay, we've computed the exiting block. See what condition causes us to
2435 // exit.
2436 //
2437 // FIXME: we should be able to handle switch instructions (with a single exit)
2438 BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2439 if (TermBr == 0) return;
2440 assert(TermBr->isConditional() && "If unconditional, it can't be in loop!");
2441 if (!isa<ICmpInst>(TermBr->getCondition()))
2442 return;
2443 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
2444
2445 // Handle only tests for equality for the moment, and only stride 1.
2446 if (Cond->getPredicate() != CmpInst::ICMP_EQ)
2447 return;
2448 SCEVHandle IV = SE->getSCEV(Cond->getOperand(0));
2449 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
2450 SCEVHandle One = SE->getIntegerSCEV(1, BackedgeTakenCount->getType());
2451 if (!AR || !AR->isAffine() || AR->getStepRecurrence(*SE) != One)
2452 return;
2453
2454 // Make sure the IV is only used for counting. Value may be preinc or
2455 // postinc; 2 uses in either case.
2456 if (!Cond->getOperand(0)->hasNUses(2))
2457 return;
2458 PHINode *phi = dyn_cast<PHINode>(Cond->getOperand(0));
2459 Instruction *incr;
2460 if (phi && phi->getParent()==L->getHeader()) {
2461 // value tested is preinc. Find the increment.
2462 // A CmpInst is not a BinaryOperator; we depend on this.
2463 Instruction::use_iterator UI = phi->use_begin();
2464 incr = dyn_cast<BinaryOperator>(UI);
2465 if (!incr)
2466 incr = dyn_cast<BinaryOperator>(++UI);
2467 // 1 use for postinc value, the phi. Unnecessarily conservative?
2468 if (!incr || !incr->hasOneUse() || incr->getOpcode()!=Instruction::Add)
2469 return;
2470 } else {
2471 // Value tested is postinc. Find the phi node.
2472 incr = dyn_cast<BinaryOperator>(Cond->getOperand(0));
2473 if (!incr || incr->getOpcode()!=Instruction::Add)
2474 return;
2475
2476 Instruction::use_iterator UI = Cond->getOperand(0)->use_begin();
2477 phi = dyn_cast<PHINode>(UI);
2478 if (!phi)
2479 phi = dyn_cast<PHINode>(++UI);
2480 // 1 use for preinc value, the increment.
2481 if (!phi || phi->getParent()!=L->getHeader() || !phi->hasOneUse())
2482 return;
2483 }
2484
2485 // Replace the increment with a decrement.
2486 BinaryOperator *decr =
2487 BinaryOperator::Create(Instruction::Sub, incr->getOperand(0),
2488 incr->getOperand(1), "tmp", incr);
2489 incr->replaceAllUsesWith(decr);
2490 incr->eraseFromParent();
2491
2492 // Substitute endval-startval for the original startval, and 0 for the
2493 // original endval. Since we're only testing for equality this is OK even
2494 // if the computation wraps around.
2495 BasicBlock *Preheader = L->getLoopPreheader();
2496 Instruction *PreInsertPt = Preheader->getTerminator();
2497 int inBlock = L->contains(phi->getIncomingBlock(0)) ? 1 : 0;
2498 Value *startVal = phi->getIncomingValue(inBlock);
2499 Value *endVal = Cond->getOperand(1);
2500 // FIXME check for case where both are constant
2501 ConstantInt* Zero = ConstantInt::get(Cond->getOperand(1)->getType(), 0);
2502 BinaryOperator *NewStartVal =
2503 BinaryOperator::Create(Instruction::Sub, endVal, startVal,
2504 "tmp", PreInsertPt);
2505 phi->setIncomingValue(inBlock, NewStartVal);
2506 Cond->setOperand(1, Zero);
2507
2508 Changed = true;
2509}
2510
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002511bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager &LPM) {
2512
Dan Gohman28055122009-05-12 02:17:14 +00002513 IU = &getAnalysis<IVUsers>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002514 LI = &getAnalysis<LoopInfo>();
2515 DT = &getAnalysis<DominatorTree>();
2516 SE = &getAnalysis<ScalarEvolution>();
Dan Gohman5fc2bf42008-07-14 17:55:01 +00002517 Changed = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002518
Dan Gohman28055122009-05-12 02:17:14 +00002519 if (!IU->IVUsesByStride.empty()) {
Dan Gohmande3b98c2009-03-09 20:34:59 +00002520#ifndef NDEBUG
2521 DOUT << "\nLSR on \"" << L->getHeader()->getParent()->getNameStart()
2522 << "\" ";
2523 DEBUG(L->dump());
2524#endif
2525
Dan Gohman7152cbc2009-03-09 20:46:50 +00002526 // Sort the StrideOrder so we process larger strides first.
Dan Gohman28055122009-05-12 02:17:14 +00002527 std::stable_sort(IU->StrideOrder.begin(), IU->StrideOrder.end(),
2528 StrideCompare(SE));
Dan Gohman7152cbc2009-03-09 20:46:50 +00002529
Evan Cheng5af5ad52008-07-07 19:51:32 +00002530 // Optimize induction variables. Some indvar uses can be transformed to use
2531 // strides that will be needed for other purposes. A common example of this
2532 // is the exit test for the loop, which can often be rewritten to use the
2533 // computation of some other indvar to decide when to terminate the loop.
2534 OptimizeIndvars(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002535
Evan Cheng56cfcd72009-05-11 22:33:01 +00002536 // Change loop terminating condition to use the postinc iv when possible
2537 // and optimize loop terminating compare. FIXME: Move this after
2538 // StrengthReduceStridedIVUsers?
2539 OptimizeLoopTermCond(L);
2540
Dan Gohmanc0baecf2009-05-05 23:02:38 +00002541 // FIXME: We can shrink overlarge IV's here. e.g. if the code has
Dan Gohmanfd81b492009-05-05 22:59:55 +00002542 // computation in i64 values and the target doesn't support i64, demote
2543 // the computation to 32-bit if safe.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002544
Evan Cheng5af5ad52008-07-07 19:51:32 +00002545 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
2546 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should
2547 // be codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC.
2548 // Need to be careful that IV's are all the same type. Only works for
2549 // intptr_t indvars.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002550
Evan Cheng5af5ad52008-07-07 19:51:32 +00002551 // IVsByStride keeps IVs for one particular loop.
2552 assert(IVsByStride.empty() && "Stale entries in IVsByStride?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002553
Evan Cheng5af5ad52008-07-07 19:51:32 +00002554 // Note: this processes each stride/type pair individually. All users
2555 // passed into StrengthReduceStridedIVUsers have the same type AND stride.
2556 // Also, note that we iterate over IVUsesByStride indirectly by using
2557 // StrideOrder. This extra layer of indirection makes the ordering of
2558 // strides deterministic - not dependent on map order.
Dan Gohman28055122009-05-12 02:17:14 +00002559 for (unsigned Stride = 0, e = IU->StrideOrder.size();
2560 Stride != e; ++Stride) {
2561 std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
2562 IU->IVUsesByStride.find(IU->StrideOrder[Stride]);
2563 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
2564 // FIXME: Generalize to non-affine IV's.
2565 if (!SI->first->isLoopInvariant(L))
2566 continue;
2567 StrengthReduceStridedIVUsers(SI->first, *SI->second, L);
Evan Cheng5af5ad52008-07-07 19:51:32 +00002568 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002569 }
2570
Dale Johannesen0b31ad52009-05-11 17:15:42 +00002571 // After all sharing is done, see if we can adjust the loop to test against
2572 // zero instead of counting up to a maximum. This is usually faster.
2573 OptimizeLoopCountIV(L);
2574
Dan Gohman3dfab2b2008-05-21 00:54:12 +00002575 // We're done analyzing this loop; release all the state we built up for it.
Dan Gohman3dfab2b2008-05-21 00:54:12 +00002576 IVsByStride.clear();
Evan Cheng56cfcd72009-05-11 22:33:01 +00002577 StrideNoReuse.clear();
Dan Gohman3dfab2b2008-05-21 00:54:12 +00002578
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002579 // Clean up after ourselves
Dan Gohman93efe962009-05-02 18:29:22 +00002580 if (!DeadInsts.empty())
Chris Lattner3b39baa2008-12-01 06:14:28 +00002581 DeleteTriviallyDeadInstructions();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002582
Dan Gohman93efe962009-05-02 18:29:22 +00002583 // At this point, it is worth checking to see if any recurrence PHIs are also
Dan Gohmanbff6b582009-05-04 22:30:44 +00002584 // dead, so that we can remove them as well.
2585 DeleteDeadPHIs(L->getHeader());
Dan Gohman93efe962009-05-02 18:29:22 +00002586
Evan Cheng5af5ad52008-07-07 19:51:32 +00002587 return Changed;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002588}