blob: ed12d8683d2926197ae4fe5738ce480d9c846c4d [file] [log] [blame]
Dan Gohman2d1be872009-04-16 03:18:22 +00001//===- LoopStrengthReduce.cpp - Strength Reduce IVs in Loops --------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Nate Begemaneaa13852004-10-18 21:08:22 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
Nate Begemaneaa13852004-10-18 21:08:22 +00008//===----------------------------------------------------------------------===//
9//
10// This pass performs a strength reduction on array references inside loops that
Dan Gohman2d1be872009-04-16 03:18:22 +000011// have as one or more of their components the loop induction variable.
Nate Begemaneaa13852004-10-18 21:08:22 +000012//
Nate Begemaneaa13852004-10-18 21:08:22 +000013//===----------------------------------------------------------------------===//
14
Chris Lattnerbe3e5212005-08-03 23:30:08 +000015#define DEBUG_TYPE "loop-reduce"
Nate Begemaneaa13852004-10-18 21:08:22 +000016#include "llvm/Transforms/Scalar.h"
17#include "llvm/Constants.h"
18#include "llvm/Instructions.h"
Dan Gohmane5b01be2007-05-04 14:59:09 +000019#include "llvm/IntrinsicInst.h"
Nate Begemaneaa13852004-10-18 21:08:22 +000020#include "llvm/Type.h"
Jeff Cohen2f3c9b72005-03-04 04:04:26 +000021#include "llvm/DerivedTypes.h"
Nate Begemaneaa13852004-10-18 21:08:22 +000022#include "llvm/Analysis/Dominators.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000023#include "llvm/Analysis/IVUsers.h"
Nate Begemaneaa13852004-10-18 21:08:22 +000024#include "llvm/Analysis/LoopInfo.h"
Devang Patel0f54dcb2007-03-06 21:14:09 +000025#include "llvm/Analysis/LoopPass.h"
Nate Begeman16997482005-07-30 00:15:07 +000026#include "llvm/Analysis/ScalarEvolutionExpander.h"
Evan Chengd9fb7122009-02-21 02:06:47 +000027#include "llvm/Transforms/Utils/AddrModeMatcher.h"
Chris Lattnere0391be2005-08-12 22:06:11 +000028#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Nate Begemaneaa13852004-10-18 21:08:22 +000029#include "llvm/Transforms/Utils/Local.h"
Evan Cheng168a66b2007-10-26 23:08:19 +000030#include "llvm/ADT/SmallPtrSet.h"
Nate Begemaneaa13852004-10-18 21:08:22 +000031#include "llvm/ADT/Statistic.h"
Evan Chengd9fb7122009-02-21 02:06:47 +000032#include "llvm/Support/CFG.h"
Nate Begeman16997482005-07-30 00:15:07 +000033#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000034#include "llvm/Support/Compiler.h"
Dan Gohmanc17e0cf2009-02-20 04:17:46 +000035#include "llvm/Support/CommandLine.h"
Dan Gohmanafc36a92009-05-02 18:29:22 +000036#include "llvm/Support/ValueHandle.h"
Evan Chengd277f2c2006-03-13 23:14:23 +000037#include "llvm/Target/TargetLowering.h"
Jeff Cohencfb1d422005-07-30 18:22:27 +000038#include <algorithm>
Nate Begemaneaa13852004-10-18 21:08:22 +000039using namespace llvm;
40
Dan Gohman13317bc2009-04-16 16:46:01 +000041STATISTIC(NumReduced , "Number of IV uses strength reduced");
Evan Chengcdf43b12007-10-25 09:11:16 +000042STATISTIC(NumInserted, "Number of PHIs inserted");
43STATISTIC(NumVariable, "Number of PHIs with variable strides");
Devang Patel54153272008-08-27 17:50:18 +000044STATISTIC(NumEliminated, "Number of strides eliminated");
45STATISTIC(NumShadow, "Number of Shadow IVs optimized");
Evan Chengd9fb7122009-02-21 02:06:47 +000046STATISTIC(NumImmSunk, "Number of common expr immediates sunk into uses");
Evan Cheng5792f512009-05-11 22:33:01 +000047STATISTIC(NumLoopCond, "Number of loop terminating conds optimized");
Nate Begemaneaa13852004-10-18 21:08:22 +000048
Dan Gohmanc17e0cf2009-02-20 04:17:46 +000049static cl::opt<bool> EnableFullLSRMode("enable-full-lsr",
50 cl::init(false),
51 cl::Hidden);
52
Chris Lattner0e5f4992006-12-19 21:40:18 +000053namespace {
Dale Johannesendc42f482007-03-20 00:47:50 +000054
Jeff Cohenc01a5302007-03-20 20:43:18 +000055 struct BasedUser;
Dale Johannesendc42f482007-03-20 00:47:50 +000056
Evan Chengd1d6b5c2006-03-16 21:53:05 +000057 /// IVInfo - This structure keeps track of one IV expression inserted during
Evan Cheng21495772006-03-18 08:03:12 +000058 /// StrengthReduceStridedIVUsers. It contains the stride, the common base, as
59 /// well as the PHI node and increment value created for rewrite.
Reid Spencer9133fe22007-02-05 23:32:05 +000060 struct VISIBILITY_HIDDEN IVExpr {
Evan Cheng21495772006-03-18 08:03:12 +000061 SCEVHandle Stride;
Evan Chengd1d6b5c2006-03-16 21:53:05 +000062 SCEVHandle Base;
63 PHINode *PHI;
Evan Chengd1d6b5c2006-03-16 21:53:05 +000064
Dan Gohman9d100862009-03-09 22:04:01 +000065 IVExpr(const SCEVHandle &stride, const SCEVHandle &base, PHINode *phi)
66 : Stride(stride), Base(base), PHI(phi) {}
Evan Chengd1d6b5c2006-03-16 21:53:05 +000067 };
68
69 /// IVsOfOneStride - This structure keeps track of all IV expression inserted
70 /// during StrengthReduceStridedIVUsers for a particular stride of the IV.
Reid Spencer9133fe22007-02-05 23:32:05 +000071 struct VISIBILITY_HIDDEN IVsOfOneStride {
Evan Chengd1d6b5c2006-03-16 21:53:05 +000072 std::vector<IVExpr> IVs;
73
Dan Gohman9d100862009-03-09 22:04:01 +000074 void addIV(const SCEVHandle &Stride, const SCEVHandle &Base, PHINode *PHI) {
75 IVs.push_back(IVExpr(Stride, Base, PHI));
Evan Chengd1d6b5c2006-03-16 21:53:05 +000076 }
77 };
Nate Begeman16997482005-07-30 00:15:07 +000078
Devang Patel0f54dcb2007-03-06 21:14:09 +000079 class VISIBILITY_HIDDEN LoopStrengthReduce : public LoopPass {
Dan Gohman81db61a2009-05-12 02:17:14 +000080 IVUsers *IU;
Nate Begemaneaa13852004-10-18 21:08:22 +000081 LoopInfo *LI;
Devang Patelb7d9dfc2007-06-07 21:42:15 +000082 DominatorTree *DT;
Nate Begeman16997482005-07-30 00:15:07 +000083 ScalarEvolution *SE;
Nate Begemaneaa13852004-10-18 21:08:22 +000084 bool Changed;
Chris Lattner7e608bb2005-08-02 02:52:02 +000085
Evan Chengd1d6b5c2006-03-16 21:53:05 +000086 /// IVsByStride - Keep track of all IVs that have been inserted for a
87 /// particular stride.
88 std::map<SCEVHandle, IVsOfOneStride> IVsByStride;
89
Evan Cheng5792f512009-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
Nate Begeman16997482005-07-30 00:15:07 +000094 /// DeadInsts - Keep track of instructions we may have made dead, so that
95 /// we can remove them after we are done working.
Dan Gohman81db61a2009-05-12 02:17:14 +000096 SmallVector<WeakVH, 16> DeadInsts;
Evan Chengd277f2c2006-03-13 23:14:23 +000097
98 /// TLI - Keep a pointer of a TargetLowering to consult for determining
99 /// transformation profitability.
100 const TargetLowering *TLI;
101
Nate Begemaneaa13852004-10-18 21:08:22 +0000102 public:
Devang Patel19974732007-05-03 01:11:54 +0000103 static char ID; // Pass ID, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +0000104 explicit LoopStrengthReduce(const TargetLowering *tli = NULL) :
Dan Gohmanae73dc12008-09-04 17:05:41 +0000105 LoopPass(&ID), TLI(tli) {
Jeff Cohen2f3c9b72005-03-04 04:04:26 +0000106 }
107
Devang Patel0f54dcb2007-03-06 21:14:09 +0000108 bool runOnLoop(Loop *L, LPPassManager &LPM);
Nate Begemaneaa13852004-10-18 21:08:22 +0000109
110 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattneraa96ae72005-08-17 06:35:16 +0000111 // 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>();
Chris Lattneraa96ae72005-08-17 06:35:16 +0000115 AU.addPreserved<DominanceFrontier>();
116 AU.addPreserved<DominatorTree>();
117
Jeff Cohenf465db62005-02-27 19:37:07 +0000118 AU.addRequiredID(LoopSimplifyID);
Nate Begemaneaa13852004-10-18 21:08:22 +0000119 AU.addRequired<LoopInfo>();
Devang Patelb7d9dfc2007-06-07 21:42:15 +0000120 AU.addRequired<DominatorTree>();
Nate Begeman16997482005-07-30 00:15:07 +0000121 AU.addRequired<ScalarEvolution>();
Devang Patela0b39092008-08-26 17:57:54 +0000122 AU.addPreserved<ScalarEvolution>();
Dan Gohman81db61a2009-05-12 02:17:14 +0000123 AU.addRequired<IVUsers>();
124 AU.addPreserved<IVUsers>();
Nate Begemaneaa13852004-10-18 21:08:22 +0000125 }
Dan Gohman2d1be872009-04-16 03:18:22 +0000126
Dan Gohman3d81e312009-05-01 16:56:32 +0000127 private:
Evan Chengcdf43b12007-10-25 09:11:16 +0000128 ICmpInst *ChangeCompareStride(Loop *L, ICmpInst *Cond,
129 IVStrideUse* &CondUse,
130 const SCEVHandle* &CondStride);
Evan Cheng2d850522009-05-09 01:08:24 +0000131
Chris Lattner010de252005-08-08 05:28:22 +0000132 void OptimizeIndvars(Loop *L);
Dale Johannesenc1acc3f2009-05-11 17:15:42 +0000133 void OptimizeLoopCountIV(Loop *L);
Evan Cheng2d850522009-05-09 01:08:24 +0000134 void OptimizeLoopTermCond(Loop *L);
135
Devang Patela0b39092008-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 Gohmanad7321f2008-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 Patelc677de22008-08-13 20:31:11 +0000145 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse,
Devang Patela0b39092008-08-26 17:57:54 +0000146 const SCEVHandle *&CondStride);
Evan Cheng5f8ebaa2007-10-25 22:45:20 +0000147 bool RequiresTypeConversion(const Type *Ty, const Type *NewTy);
Dale Johannesen2f46bb82009-01-14 02:35:31 +0000148 SCEVHandle CheckForIVReuse(bool, bool, bool, const SCEVHandle&,
Dan Gohman02e4fa72007-10-22 20:40:42 +0000149 IVExpr&, const Type*,
Dale Johannesendc42f482007-03-20 00:47:50 +0000150 const std::vector<BasedUser>& UsersToProcess);
Evan Cheng5792f512009-05-11 22:33:01 +0000151 bool ValidScale(bool, int64_t,
152 const std::vector<BasedUser>& UsersToProcess);
Dan Gohman81db61a2009-05-12 02:17:14 +0000153 bool ValidOffset(bool, int64_t, int64_t,
154 const std::vector<BasedUser>& UsersToProcess);
Evan Cheng5f8ebaa2007-10-25 22:45:20 +0000155 SCEVHandle CollectIVUsers(const SCEVHandle &Stride,
156 IVUsersOfOneStride &Uses,
157 Loop *L,
158 bool &AllUsesAreAddresses,
Dale Johannesenb0390622008-12-16 22:16:28 +0000159 bool &AllUsesAreOutsideLoop,
Evan Cheng5f8ebaa2007-10-25 22:45:20 +0000160 std::vector<BasedUser> &UsersToProcess);
Dan Gohmanc17e0cf2009-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 Cheng5792f512009-05-11 22:33:01 +0000182 Instruction *IVIncInsertPt,
Dan Gohmanc17e0cf2009-02-20 04:17:46 +0000183 const Loop *L,
184 SCEVExpander &PreheaderRewriter);
Chris Lattner50fad702005-08-10 00:45:21 +0000185 void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
186 IVUsersOfOneStride &Uses,
Dan Gohman9f4ac312009-03-09 20:41:15 +0000187 Loop *L);
Chris Lattnera68d4ca2008-12-01 06:14:28 +0000188 void DeleteTriviallyDeadInstructions();
Nate Begemaneaa13852004-10-18 21:08:22 +0000189 };
Nate Begemaneaa13852004-10-18 21:08:22 +0000190}
191
Dan Gohman844731a2008-05-13 00:00:25 +0000192char LoopStrengthReduce::ID = 0;
193static RegisterPass<LoopStrengthReduce>
194X("loop-reduce", "Loop Strength Reduction");
195
Daniel Dunbar394f0442008-10-22 23:32:42 +0000196Pass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
Evan Chengd1d6b5c2006-03-16 21:53:05 +0000197 return new LoopStrengthReduce(TLI);
Nate Begemaneaa13852004-10-18 21:08:22 +0000198}
199
200/// 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 Lattnera68d4ca2008-12-01 06:14:28 +0000203void LoopStrengthReduce::DeleteTriviallyDeadInstructions() {
Chris Lattner09fb7da2008-12-01 06:27:41 +0000204 if (DeadInsts.empty()) return;
205
Chris Lattnera68d4ca2008-12-01 06:14:28 +0000206 while (!DeadInsts.empty()) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000207 Instruction *I = dyn_cast_or_null<Instruction>(DeadInsts.back());
Chris Lattnera68d4ca2008-12-01 06:14:28 +0000208 DeadInsts.pop_back();
Chris Lattner09fb7da2008-12-01 06:27:41 +0000209
210 if (I == 0 || !isInstructionTriviallyDead(I))
Chris Lattnerbfcee362008-12-01 06:11:32 +0000211 continue;
212
Chris Lattner09fb7da2008-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 Lattnerbfcee362008-12-01 06:11:32 +0000216 if (U->use_empty())
Chris Lattner09fb7da2008-12-01 06:27:41 +0000217 DeadInsts.push_back(U);
Bill Wendling411052b2008-11-29 03:43:04 +0000218 }
219 }
Chris Lattnerbfcee362008-12-01 06:11:32 +0000220
221 I->eraseFromParent();
222 Changed = true;
Nate Begemaneaa13852004-10-18 21:08:22 +0000223 }
224}
225
Dale Johannesen2f46bb82009-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 Gohman890f92b2009-04-18 17:56:28 +0000233 if (const SCEVCommutativeExpr *AE = dyn_cast<SCEVCommutativeExpr>(S)) {
Dale Johannesen2f46bb82009-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 Gohman890f92b2009-04-18 17:56:28 +0000239 if (const SCEVAddRecExpr *AE = dyn_cast<SCEVAddRecExpr>(S)) {
Dale Johannesen2f46bb82009-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 Gohman890f92b2009-04-18 17:56:28 +0000249 if (const SCEVUDivExpr *DE = dyn_cast<SCEVUDivExpr>(S))
Dale Johannesen2f46bb82009-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 Gohman890f92b2009-04-18 17:56:28 +0000255 if (const SCEVSDivExpr *DE = dyn_cast<SCEVSDivExpr>(S))
Dale Johannesen2f46bb82009-01-14 02:35:31 +0000256 return containsAddRecFromDifferentLoop(DE->getLHS(), L) ||
257 containsAddRecFromDifferentLoop(DE->getRHS(), L);
258#endif
Dan Gohman84923602009-04-21 01:25:57 +0000259 if (const SCEVCastExpr *CE = dyn_cast<SCEVCastExpr>(S))
260 return containsAddRecFromDifferentLoop(CE->getOperand(), L);
Dale Johannesen2f46bb82009-01-14 02:35:31 +0000261 return false;
262}
263
Dan Gohmanf284ce22009-02-18 00:08:39 +0000264/// isAddressUse - Returns true if the specified instruction is using the
Dale Johannesen203af582008-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}
Chris Lattner0ae33eb2005-10-03 01:04:44 +0000291
Dan Gohman21e77222009-03-09 21:01:17 +0000292/// getAccessType - Return the type of the memory being accessed.
293static const Type *getAccessType(const Instruction *Inst) {
294 const Type *UseTy = Inst->getType();
295 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst))
296 UseTy = SI->getOperand(0)->getType();
297 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:
306 UseTy = II->getOperand(1)->getType();
307 break;
308 }
309 }
310 return UseTy;
311}
312
Nate Begeman16997482005-07-30 00:15:07 +0000313namespace {
314 /// BasedUser - For a particular base value, keep information about how we've
315 /// partitioned the expression so far.
316 struct BasedUser {
Dan Gohman246b2562007-10-22 18:31:58 +0000317 /// SE - The current ScalarEvolution object.
318 ScalarEvolution *SE;
319
Chris Lattnera553b0c2005-08-08 22:56:21 +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
Nate Begeman16997482005-07-30 00:15:07 +0000326 /// Inst - The instruction using the induction variable.
327 Instruction *Inst;
328
Chris Lattnerec3fb632005-08-03 22:21:05 +0000329 /// OperandValToReplace - The operand value of Inst to replace with the
330 /// EmittedBase.
331 Value *OperandValToReplace;
Nate Begeman16997482005-07-30 00:15:07 +0000332
Dan Gohman81db61a2009-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
Nate Begeman16997482005-07-30 00:15:07 +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 Gohman33e3a362009-02-20 20:29:04 +0000342 /// instruction. This is also sometimes used for loop-variant values that
343 /// must be added inside the loop.
Nate Begeman16997482005-07-30 00:15:07 +0000344 SCEVHandle Imm;
345
Dan Gohmanc17e0cf2009-02-20 04:17:46 +0000346 /// Phi - The induction variable that performs the striding that
347 /// should be used for this user.
Dan Gohman9d100862009-03-09 22:04:01 +0000348 PHINode *Phi;
Dan Gohmanc17e0cf2009-02-20 04:17:46 +0000349
Chris Lattner010de252005-08-08 05:28:22 +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
Chris Lattnerc6bae652005-09-12 06:04:47 +0000353 // instruction for a loop and uses outside the loop that are dominated by
354 // the loop.
Chris Lattner010de252005-08-08 05:28:22 +0000355 bool isUseOfPostIncrementedValue;
Chris Lattnera553b0c2005-08-08 22:56:21 +0000356
Dan Gohman246b2562007-10-22 18:31:58 +0000357 BasedUser(IVStrideUse &IVSU, ScalarEvolution *se)
Dan Gohman81db61a2009-05-12 02:17:14 +0000358 : SE(se), Base(IVSU.getOffset()), Inst(IVSU.getUser()),
359 OperandValToReplace(IVSU.getOperandValToReplace()),
360 isSigned(IVSU.isSigned()),
Dale Johannesen308f24d2008-12-03 22:43:56 +0000361 Imm(SE->getIntegerSCEV(0, Base->getType())),
Dan Gohman81db61a2009-05-12 02:17:14 +0000362 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue()) {}
Nate Begeman16997482005-07-30 00:15:07 +0000363
Chris Lattner2114b272005-08-04 20:03:32 +0000364 // 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.
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000367 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Dan Gohmanf20d70d2008-05-15 23:26:57 +0000368 Instruction *InsertPt,
Evan Cheng0e0014d2007-10-30 23:45:15 +0000369 SCEVExpander &Rewriter, Loop *L, Pass *P,
Dan Gohman81db61a2009-05-12 02:17:14 +0000370 SmallVectorImpl<WeakVH> &DeadInsts);
Chris Lattner221fc3c2006-02-04 07:36:50 +0000371
372 Value *InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
Dan Gohman2d1be872009-04-16 03:18:22 +0000373 const Type *Ty,
Chris Lattner221fc3c2006-02-04 07:36:50 +0000374 SCEVExpander &Rewriter,
375 Instruction *IP, Loop *L);
Nate Begeman16997482005-07-30 00:15:07 +0000376 void dump() const;
377 };
378}
379
380void BasedUser::dump() const {
Bill Wendlinge8156192006-12-07 01:30:32 +0000381 cerr << " Base=" << *Base;
382 cerr << " Imm=" << *Imm;
Bill Wendlinge8156192006-12-07 01:30:32 +0000383 cerr << " Inst: " << *Inst;
Nate Begeman16997482005-07-30 00:15:07 +0000384}
385
Chris Lattner221fc3c2006-02-04 07:36:50 +0000386Value *BasedUser::InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
Dan Gohman2d1be872009-04-16 03:18:22 +0000387 const Type *Ty,
Chris Lattner221fc3c2006-02-04 07:36:50 +0000388 SCEVExpander &Rewriter,
389 Instruction *IP, Loop *L) {
390 // Figure out where we *really* want to insert this code. In particular, if
391 // the user is inside of a loop that is nested inside of L, we really don't
392 // want to insert this expression before the user, we'd rather pull it out as
393 // many loops as possible.
394 LoopInfo &LI = Rewriter.getLoopInfo();
395 Instruction *BaseInsertPt = IP;
396
397 // Figure out the most-nested loop that IP is in.
398 Loop *InsertLoop = LI.getLoopFor(IP->getParent());
399
400 // If InsertLoop is not L, and InsertLoop is nested inside of L, figure out
401 // the preheader of the outer-most loop where NewBase is not loop invariant.
Dale Johanneseneccdd082008-12-02 18:40:09 +0000402 if (L->contains(IP->getParent()))
403 while (InsertLoop && NewBase->isLoopInvariant(InsertLoop)) {
404 BaseInsertPt = InsertLoop->getLoopPreheader()->getTerminator();
405 InsertLoop = InsertLoop->getParentLoop();
406 }
Chris Lattner221fc3c2006-02-04 07:36:50 +0000407
Dan Gohman81db61a2009-05-12 02:17:14 +0000408 Value *Base = Rewriter.expandCodeFor(NewBase, NewBase->getType(),
409 BaseInsertPt);
410
411 SCEVHandle NewValSCEV = SE->getUnknown(Base);
Dan Gohman2f09f512009-02-19 19:23:27 +0000412
Chris Lattner221fc3c2006-02-04 07:36:50 +0000413 // If there is no immediate value, skip the next part.
Dan Gohman81db61a2009-05-12 02:17:14 +0000414 if (!Imm->isZero()) {
415 // If we are inserting the base and imm values in the same block, make sure
416 // to adjust the IP position if insertion reused a result.
417 if (IP == BaseInsertPt)
418 IP = Rewriter.getInsertionPoint();
Chris Lattnerb47f6122007-06-06 01:23:55 +0000419
Dan Gohman81db61a2009-05-12 02:17:14 +0000420 // Always emit the immediate (if non-zero) into the same block as the user.
421 NewValSCEV = SE->getAddExpr(NewValSCEV, Imm);
422 }
423
424 if (isSigned)
425 NewValSCEV = SE->getTruncateOrSignExtend(NewValSCEV, Ty);
426 else
427 NewValSCEV = SE->getTruncateOrZeroExtend(NewValSCEV, Ty);
428
Dan Gohman2d1be872009-04-16 03:18:22 +0000429 return Rewriter.expandCodeFor(NewValSCEV, Ty, IP);
Chris Lattner221fc3c2006-02-04 07:36:50 +0000430}
431
432
Chris Lattner2114b272005-08-04 20:03:32 +0000433// Once we rewrite the code to insert the new IVs we want, update the
434// operands of Inst to use the new expression 'NewBase', with 'Imm' added
Dan Gohmanf20d70d2008-05-15 23:26:57 +0000435// to it. NewBasePt is the last instruction which contributes to the
436// value of NewBase in the case that it's a diffferent instruction from
437// the PHI that NewBase is computed from, or null otherwise.
438//
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000439void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Dan Gohmanf20d70d2008-05-15 23:26:57 +0000440 Instruction *NewBasePt,
Evan Cheng0e0014d2007-10-30 23:45:15 +0000441 SCEVExpander &Rewriter, Loop *L, Pass *P,
Dan Gohman81db61a2009-05-12 02:17:14 +0000442 SmallVectorImpl<WeakVH> &DeadInsts) {
Chris Lattner2114b272005-08-04 20:03:32 +0000443 if (!isa<PHINode>(Inst)) {
Chris Lattnerc5494af2007-04-13 20:42:26 +0000444 // By default, insert code at the user instruction.
445 BasicBlock::iterator InsertPt = Inst;
446
447 // However, if the Operand is itself an instruction, the (potentially
448 // complex) inserted code may be shared by many users. Because of this, we
449 // want to emit code for the computation of the operand right before its old
450 // computation. This is usually safe, because we obviously used to use the
451 // computation when it was computed in its current block. However, in some
452 // cases (e.g. use of a post-incremented induction variable) the NewBase
453 // value will be pinned to live somewhere after the original computation.
454 // In this case, we have to back off.
Chris Lattnerf8828eb2008-12-02 04:52:26 +0000455 //
456 // If this is a use outside the loop (which means after, since it is based
457 // on a loop indvar) we use the post-incremented value, so that we don't
458 // artificially make the preinc value live out the bottom of the loop.
Dale Johannesen589bf082008-12-01 22:00:01 +0000459 if (!isUseOfPostIncrementedValue && L->contains(Inst->getParent())) {
Dan Gohmanca756ae2008-05-20 03:01:48 +0000460 if (NewBasePt && isa<PHINode>(OperandValToReplace)) {
Dan Gohmanf20d70d2008-05-15 23:26:57 +0000461 InsertPt = NewBasePt;
462 ++InsertPt;
Gabor Greif6725cb52008-06-11 21:38:51 +0000463 } else if (Instruction *OpInst
464 = dyn_cast<Instruction>(OperandValToReplace)) {
Chris Lattnerc5494af2007-04-13 20:42:26 +0000465 InsertPt = OpInst;
466 while (isa<PHINode>(InsertPt)) ++InsertPt;
467 }
468 }
Dan Gohman2d1be872009-04-16 03:18:22 +0000469 Value *NewVal = InsertCodeForBaseAtPosition(NewBase,
470 OperandValToReplace->getType(),
471 Rewriter, InsertPt, L);
Chris Lattner2114b272005-08-04 20:03:32 +0000472 // Replace the use of the operand Value with the new Phi we just created.
473 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
Dan Gohman2f09f512009-02-19 19:23:27 +0000474
Dan Gohman2f09f512009-02-19 19:23:27 +0000475 DOUT << " Replacing with ";
Dan Gohman4a359ea2009-02-19 19:32:06 +0000476 DEBUG(WriteAsOperand(*DOUT, NewVal, /*PrintType=*/false));
Dan Gohman2f09f512009-02-19 19:23:27 +0000477 DOUT << ", which has value " << *NewBase << " plus IMM " << *Imm << "\n";
Chris Lattner2114b272005-08-04 20:03:32 +0000478 return;
479 }
Dan Gohman2f09f512009-02-19 19:23:27 +0000480
Chris Lattner2114b272005-08-04 20:03:32 +0000481 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
Chris Lattnerc41e3452005-08-10 00:35:32 +0000482 // expression into each operand block that uses it. Note that PHI nodes can
483 // have multiple entries for the same predecessor. We use a map to make sure
484 // that a PHI node only has a single Value* for each predecessor (which also
485 // prevents us from inserting duplicate code in some blocks).
Evan Cheng83927722007-10-30 22:27:26 +0000486 DenseMap<BasicBlock*, Value*> InsertedCode;
Chris Lattner2114b272005-08-04 20:03:32 +0000487 PHINode *PN = cast<PHINode>(Inst);
488 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
489 if (PN->getIncomingValue(i) == OperandValToReplace) {
Dale Johannesen2f46bb82009-01-14 02:35:31 +0000490 // If the original expression is outside the loop, put the replacement
491 // code in the same place as the original expression,
492 // which need not be an immediate predecessor of this PHI. This way we
493 // need only one copy of it even if it is referenced multiple times in
494 // the PHI. We don't do this when the original expression is inside the
Dale Johannesen1de17d52009-02-09 22:14:15 +0000495 // loop because multiple copies sometimes do useful sinking of code in
496 // that case(?).
Dale Johannesen2f46bb82009-01-14 02:35:31 +0000497 Instruction *OldLoc = dyn_cast<Instruction>(OperandValToReplace);
498 if (L->contains(OldLoc->getParent())) {
Dale Johannesen1de17d52009-02-09 22:14:15 +0000499 // If this is a critical edge, split the edge so that we do not insert
500 // the code on all predecessor/successor paths. We do this unless this
501 // is the canonical backedge for this loop, as this can make some
502 // inserted code be in an illegal position.
Dale Johannesen2f46bb82009-01-14 02:35:31 +0000503 BasicBlock *PHIPred = PN->getIncomingBlock(i);
504 if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
505 (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
Dale Johannesenf6727b02008-12-23 23:21:35 +0000506
Dale Johannesen2f46bb82009-01-14 02:35:31 +0000507 // First step, split the critical edge.
508 SplitCriticalEdge(PHIPred, PN->getParent(), P, false);
509
510 // Next step: move the basic block. In particular, if the PHI node
511 // is outside of the loop, and PredTI is in the loop, we want to
512 // move the block to be immediately before the PHI block, not
513 // immediately after PredTI.
514 if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
515 BasicBlock *NewBB = PN->getIncomingBlock(i);
516 NewBB->moveBefore(PN->getParent());
517 }
518
519 // Splitting the edge can reduce the number of PHI entries we have.
520 e = PN->getNumIncomingValues();
521 }
522 }
Chris Lattnerc41e3452005-08-10 00:35:32 +0000523 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
524 if (!Code) {
525 // Insert the code into the end of the predecessor block.
Dale Johannesen2f46bb82009-01-14 02:35:31 +0000526 Instruction *InsertPt = (L->contains(OldLoc->getParent())) ?
527 PN->getIncomingBlock(i)->getTerminator() :
528 OldLoc->getParent()->getTerminator();
Dan Gohman2d1be872009-04-16 03:18:22 +0000529 Code = InsertCodeForBaseAtPosition(NewBase, PN->getType(),
530 Rewriter, InsertPt, L);
Dan Gohman2f09f512009-02-19 19:23:27 +0000531
Dan Gohman2f09f512009-02-19 19:23:27 +0000532 DOUT << " Changing PHI use to ";
Dan Gohman4a359ea2009-02-19 19:32:06 +0000533 DEBUG(WriteAsOperand(*DOUT, Code, /*PrintType=*/false));
Dan Gohman2f09f512009-02-19 19:23:27 +0000534 DOUT << ", which has value " << *NewBase << " plus IMM " << *Imm << "\n";
Chris Lattnerc41e3452005-08-10 00:35:32 +0000535 }
Dan Gohman2f09f512009-02-19 19:23:27 +0000536
Chris Lattner2114b272005-08-04 20:03:32 +0000537 // Replace the use of the operand Value with the new Phi we just created.
Chris Lattnerc41e3452005-08-10 00:35:32 +0000538 PN->setIncomingValue(i, Code);
Chris Lattner2114b272005-08-04 20:03:32 +0000539 Rewriter.clear();
540 }
541 }
Evan Cheng0e0014d2007-10-30 23:45:15 +0000542
543 // PHI node might have become a constant value after SplitCriticalEdge.
Chris Lattner09fb7da2008-12-01 06:27:41 +0000544 DeadInsts.push_back(Inst);
Chris Lattner2114b272005-08-04 20:03:32 +0000545}
546
547
Dale Johannesen203af582008-12-05 21:47:27 +0000548/// fitsInAddressMode - Return true if V can be subsumed within an addressing
549/// mode, and does not need to be put in a register first.
550static bool fitsInAddressMode(const SCEVHandle &V, const Type *UseTy,
551 const TargetLowering *TLI, bool HasBaseReg) {
Dan Gohman890f92b2009-04-18 17:56:28 +0000552 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
Evan Cheng5eef2d22007-03-12 23:27:37 +0000553 int64_t VC = SC->getValue()->getSExtValue();
Chris Lattner579633c2007-04-09 22:20:14 +0000554 if (TLI) {
555 TargetLowering::AddrMode AM;
556 AM.BaseOffs = VC;
Dale Johannesen203af582008-12-05 21:47:27 +0000557 AM.HasBaseReg = HasBaseReg;
Chris Lattner579633c2007-04-09 22:20:14 +0000558 return TLI->isLegalAddressingMode(AM, UseTy);
559 } else {
Evan Chengd277f2c2006-03-13 23:14:23 +0000560 // Defaults to PPC. PPC allows a sign-extended 16-bit immediate field.
Evan Cheng5eef2d22007-03-12 23:27:37 +0000561 return (VC > -(1 << 16) && VC < (1 << 16)-1);
Chris Lattner579633c2007-04-09 22:20:14 +0000562 }
Chris Lattner3821e472005-08-08 06:25:50 +0000563 }
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000564
Dan Gohman890f92b2009-04-18 17:56:28 +0000565 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
Dan Gohman2d1be872009-04-16 03:18:22 +0000566 if (GlobalValue *GV = dyn_cast<GlobalValue>(SU->getValue())) {
Dan Gohmancc2ad052009-05-01 16:29:14 +0000567 if (TLI) {
568 TargetLowering::AddrMode AM;
569 AM.BaseGV = GV;
570 AM.HasBaseReg = HasBaseReg;
571 return TLI->isLegalAddressingMode(AM, UseTy);
572 } else {
573 // Default: assume global addresses are not legal.
574 }
Dan Gohman2d1be872009-04-16 03:18:22 +0000575 }
576
Nate Begeman16997482005-07-30 00:15:07 +0000577 return false;
578}
579
Dale Johannesen544e0d02008-12-03 20:56:12 +0000580/// MoveLoopVariantsToImmediateField - Move any subexpressions from Val that are
Chris Lattner44b807e2005-08-08 22:32:34 +0000581/// loop varying to the Imm operand.
Dale Johannesen544e0d02008-12-03 20:56:12 +0000582static void MoveLoopVariantsToImmediateField(SCEVHandle &Val, SCEVHandle &Imm,
Evan Cheng5792f512009-05-11 22:33:01 +0000583 Loop *L, ScalarEvolution *SE) {
Chris Lattner44b807e2005-08-08 22:32:34 +0000584 if (Val->isLoopInvariant(L)) return; // Nothing to do.
585
Dan Gohman890f92b2009-04-18 17:56:28 +0000586 if (const SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
Chris Lattner44b807e2005-08-08 22:32:34 +0000587 std::vector<SCEVHandle> NewOps;
588 NewOps.reserve(SAE->getNumOperands());
589
590 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
591 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
592 // If this is a loop-variant expression, it must stay in the immediate
593 // field of the expression.
Dan Gohman246b2562007-10-22 18:31:58 +0000594 Imm = SE->getAddExpr(Imm, SAE->getOperand(i));
Chris Lattner44b807e2005-08-08 22:32:34 +0000595 } else {
596 NewOps.push_back(SAE->getOperand(i));
597 }
598
599 if (NewOps.empty())
Dan Gohman246b2562007-10-22 18:31:58 +0000600 Val = SE->getIntegerSCEV(0, Val->getType());
Chris Lattner44b807e2005-08-08 22:32:34 +0000601 else
Dan Gohman246b2562007-10-22 18:31:58 +0000602 Val = SE->getAddExpr(NewOps);
Dan Gohman890f92b2009-04-18 17:56:28 +0000603 } else if (const SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
Chris Lattner44b807e2005-08-08 22:32:34 +0000604 // Try to pull immediates out of the start value of nested addrec's.
605 SCEVHandle Start = SARE->getStart();
Dale Johannesen544e0d02008-12-03 20:56:12 +0000606 MoveLoopVariantsToImmediateField(Start, Imm, L, SE);
Chris Lattner44b807e2005-08-08 22:32:34 +0000607
608 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
609 Ops[0] = Start;
Dan Gohman246b2562007-10-22 18:31:58 +0000610 Val = SE->getAddRecExpr(Ops, SARE->getLoop());
Chris Lattner44b807e2005-08-08 22:32:34 +0000611 } else {
612 // Otherwise, all of Val is variant, move the whole thing over.
Dan Gohman246b2562007-10-22 18:31:58 +0000613 Imm = SE->getAddExpr(Imm, Val);
614 Val = SE->getIntegerSCEV(0, Val->getType());
Chris Lattner44b807e2005-08-08 22:32:34 +0000615 }
616}
617
618
Chris Lattner26d91f12005-08-04 22:34:05 +0000619/// MoveImmediateValues - Look at Val, and pull out any additions of constants
Nate Begeman16997482005-07-30 00:15:07 +0000620/// that can fit into the immediate field of instructions in the target.
Chris Lattner26d91f12005-08-04 22:34:05 +0000621/// Accumulate these immediate values into the Imm value.
Evan Chengd277f2c2006-03-13 23:14:23 +0000622static void MoveImmediateValues(const TargetLowering *TLI,
Evan Chengd9fb7122009-02-21 02:06:47 +0000623 const Type *UseTy,
Evan Chengd277f2c2006-03-13 23:14:23 +0000624 SCEVHandle &Val, SCEVHandle &Imm,
Dan Gohman246b2562007-10-22 18:31:58 +0000625 bool isAddress, Loop *L,
626 ScalarEvolution *SE) {
Dan Gohman890f92b2009-04-18 17:56:28 +0000627 if (const SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
Chris Lattner26d91f12005-08-04 22:34:05 +0000628 std::vector<SCEVHandle> NewOps;
629 NewOps.reserve(SAE->getNumOperands());
630
Chris Lattner221fc3c2006-02-04 07:36:50 +0000631 for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
632 SCEVHandle NewOp = SAE->getOperand(i);
Evan Chengd9fb7122009-02-21 02:06:47 +0000633 MoveImmediateValues(TLI, UseTy, NewOp, Imm, isAddress, L, SE);
Chris Lattner221fc3c2006-02-04 07:36:50 +0000634
635 if (!NewOp->isLoopInvariant(L)) {
Chris Lattner7db543f2005-08-04 19:08:16 +0000636 // If this is a loop-variant expression, it must stay in the immediate
637 // field of the expression.
Dan Gohman246b2562007-10-22 18:31:58 +0000638 Imm = SE->getAddExpr(Imm, NewOp);
Chris Lattner26d91f12005-08-04 22:34:05 +0000639 } else {
Chris Lattner221fc3c2006-02-04 07:36:50 +0000640 NewOps.push_back(NewOp);
Nate Begeman16997482005-07-30 00:15:07 +0000641 }
Chris Lattner221fc3c2006-02-04 07:36:50 +0000642 }
Chris Lattner26d91f12005-08-04 22:34:05 +0000643
644 if (NewOps.empty())
Dan Gohman246b2562007-10-22 18:31:58 +0000645 Val = SE->getIntegerSCEV(0, Val->getType());
Chris Lattner26d91f12005-08-04 22:34:05 +0000646 else
Dan Gohman246b2562007-10-22 18:31:58 +0000647 Val = SE->getAddExpr(NewOps);
Chris Lattner26d91f12005-08-04 22:34:05 +0000648 return;
Dan Gohman890f92b2009-04-18 17:56:28 +0000649 } else if (const SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
Chris Lattner7a658392005-08-03 23:44:42 +0000650 // Try to pull immediates out of the start value of nested addrec's.
Chris Lattner26d91f12005-08-04 22:34:05 +0000651 SCEVHandle Start = SARE->getStart();
Evan Chengd9fb7122009-02-21 02:06:47 +0000652 MoveImmediateValues(TLI, UseTy, Start, Imm, isAddress, L, SE);
Chris Lattner26d91f12005-08-04 22:34:05 +0000653
654 if (Start != SARE->getStart()) {
655 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
656 Ops[0] = Start;
Dan Gohman246b2562007-10-22 18:31:58 +0000657 Val = SE->getAddRecExpr(Ops, SARE->getLoop());
Chris Lattner26d91f12005-08-04 22:34:05 +0000658 }
659 return;
Dan Gohman890f92b2009-04-18 17:56:28 +0000660 } else if (const SCEVMulExpr *SME = dyn_cast<SCEVMulExpr>(Val)) {
Chris Lattner221fc3c2006-02-04 07:36:50 +0000661 // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
Dale Johannesen203af582008-12-05 21:47:27 +0000662 if (isAddress && fitsInAddressMode(SME->getOperand(0), UseTy, TLI, false) &&
Chris Lattner221fc3c2006-02-04 07:36:50 +0000663 SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
664
Dan Gohman246b2562007-10-22 18:31:58 +0000665 SCEVHandle SubImm = SE->getIntegerSCEV(0, Val->getType());
Chris Lattner221fc3c2006-02-04 07:36:50 +0000666 SCEVHandle NewOp = SME->getOperand(1);
Evan Chengd9fb7122009-02-21 02:06:47 +0000667 MoveImmediateValues(TLI, UseTy, NewOp, SubImm, isAddress, L, SE);
Chris Lattner221fc3c2006-02-04 07:36:50 +0000668
669 // If we extracted something out of the subexpressions, see if we can
670 // simplify this!
671 if (NewOp != SME->getOperand(1)) {
672 // Scale SubImm up by "8". If the result is a target constant, we are
673 // good.
Dan Gohman246b2562007-10-22 18:31:58 +0000674 SubImm = SE->getMulExpr(SubImm, SME->getOperand(0));
Dale Johannesen203af582008-12-05 21:47:27 +0000675 if (fitsInAddressMode(SubImm, UseTy, TLI, false)) {
Chris Lattner221fc3c2006-02-04 07:36:50 +0000676 // Accumulate the immediate.
Dan Gohman246b2562007-10-22 18:31:58 +0000677 Imm = SE->getAddExpr(Imm, SubImm);
Chris Lattner221fc3c2006-02-04 07:36:50 +0000678
679 // Update what is left of 'Val'.
Dan Gohman246b2562007-10-22 18:31:58 +0000680 Val = SE->getMulExpr(SME->getOperand(0), NewOp);
Chris Lattner221fc3c2006-02-04 07:36:50 +0000681 return;
682 }
683 }
684 }
Nate Begeman16997482005-07-30 00:15:07 +0000685 }
686
Chris Lattner26d91f12005-08-04 22:34:05 +0000687 // Loop-variant expressions must stay in the immediate field of the
688 // expression.
Dale Johannesen203af582008-12-05 21:47:27 +0000689 if ((isAddress && fitsInAddressMode(Val, UseTy, TLI, false)) ||
Chris Lattner26d91f12005-08-04 22:34:05 +0000690 !Val->isLoopInvariant(L)) {
Dan Gohman246b2562007-10-22 18:31:58 +0000691 Imm = SE->getAddExpr(Imm, Val);
692 Val = SE->getIntegerSCEV(0, Val->getType());
Chris Lattner26d91f12005-08-04 22:34:05 +0000693 return;
Chris Lattner7a2ca562005-08-04 19:26:19 +0000694 }
Chris Lattner26d91f12005-08-04 22:34:05 +0000695
696 // Otherwise, no immediates to move.
Nate Begeman16997482005-07-30 00:15:07 +0000697}
698
Evan Chengd9fb7122009-02-21 02:06:47 +0000699static void MoveImmediateValues(const TargetLowering *TLI,
700 Instruction *User,
701 SCEVHandle &Val, SCEVHandle &Imm,
702 bool isAddress, Loop *L,
703 ScalarEvolution *SE) {
Dan Gohman21e77222009-03-09 21:01:17 +0000704 const Type *UseTy = getAccessType(User);
Evan Chengd9fb7122009-02-21 02:06:47 +0000705 MoveImmediateValues(TLI, UseTy, Val, Imm, isAddress, L, SE);
706}
Chris Lattner934520a2005-08-13 07:27:18 +0000707
Chris Lattner7e79b382006-08-03 06:34:50 +0000708/// SeparateSubExprs - Decompose Expr into all of the subexpressions that are
709/// added together. This is used to reassociate common addition subexprs
710/// together for maximal sharing when rewriting bases.
Chris Lattner934520a2005-08-13 07:27:18 +0000711static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
Dan Gohman246b2562007-10-22 18:31:58 +0000712 SCEVHandle Expr,
713 ScalarEvolution *SE) {
Dan Gohman890f92b2009-04-18 17:56:28 +0000714 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
Chris Lattner934520a2005-08-13 07:27:18 +0000715 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
Dan Gohman246b2562007-10-22 18:31:58 +0000716 SeparateSubExprs(SubExprs, AE->getOperand(j), SE);
Dan Gohman890f92b2009-04-18 17:56:28 +0000717 } else if (const SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
Dan Gohman246b2562007-10-22 18:31:58 +0000718 SCEVHandle Zero = SE->getIntegerSCEV(0, Expr->getType());
Chris Lattner934520a2005-08-13 07:27:18 +0000719 if (SARE->getOperand(0) == Zero) {
720 SubExprs.push_back(Expr);
721 } else {
722 // Compute the addrec with zero as its base.
723 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
724 Ops[0] = Zero; // Start with zero base.
Dan Gohman246b2562007-10-22 18:31:58 +0000725 SubExprs.push_back(SE->getAddRecExpr(Ops, SARE->getLoop()));
Chris Lattner934520a2005-08-13 07:27:18 +0000726
727
Dan Gohman246b2562007-10-22 18:31:58 +0000728 SeparateSubExprs(SubExprs, SARE->getOperand(0), SE);
Chris Lattner934520a2005-08-13 07:27:18 +0000729 }
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000730 } else if (!Expr->isZero()) {
Chris Lattner934520a2005-08-13 07:27:18 +0000731 // Do not add zero.
732 SubExprs.push_back(Expr);
733 }
734}
735
Dale Johannesen203af582008-12-05 21:47:27 +0000736// This is logically local to the following function, but C++ says we have
737// to make it file scope.
738struct SubExprUseData { unsigned Count; bool notAllUsesAreFree; };
Chris Lattner934520a2005-08-13 07:27:18 +0000739
Dale Johannesen203af582008-12-05 21:47:27 +0000740/// RemoveCommonExpressionsFromUseBases - Look through all of the Bases of all
741/// the Uses, removing any common subexpressions, except that if all such
742/// subexpressions can be folded into an addressing mode for all uses inside
743/// the loop (this case is referred to as "free" in comments herein) we do
744/// not remove anything. This looks for things like (a+b+c) and
Chris Lattnerf8828eb2008-12-02 04:52:26 +0000745/// (a+c+d) and computes the common (a+c) subexpression. The common expression
746/// is *removed* from the Bases and returned.
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000747static SCEVHandle
Dan Gohman246b2562007-10-22 18:31:58 +0000748RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses,
Dale Johannesen203af582008-12-05 21:47:27 +0000749 ScalarEvolution *SE, Loop *L,
750 const TargetLowering *TLI) {
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000751 unsigned NumUses = Uses.size();
752
Chris Lattnerf8828eb2008-12-02 04:52:26 +0000753 // Only one use? This is a very common case, so we handle it specially and
754 // cheaply.
Dan Gohman246b2562007-10-22 18:31:58 +0000755 SCEVHandle Zero = SE->getIntegerSCEV(0, Uses[0].Base->getType());
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000756 SCEVHandle Result = Zero;
Dale Johannesen203af582008-12-05 21:47:27 +0000757 SCEVHandle FreeResult = Zero;
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000758 if (NumUses == 1) {
Chris Lattnerf8828eb2008-12-02 04:52:26 +0000759 // If the use is inside the loop, use its base, regardless of what it is:
760 // it is clearly shared across all the IV's. If the use is outside the loop
761 // (which means after it) we don't want to factor anything *into* the loop,
762 // so just use 0 as the base.
Dale Johannesen589bf082008-12-01 22:00:01 +0000763 if (L->contains(Uses[0].Inst->getParent()))
764 std::swap(Result, Uses[0].Base);
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000765 return Result;
766 }
767
768 // To find common subexpressions, count how many of Uses use each expression.
769 // If any subexpressions are used Uses.size() times, they are common.
Dale Johannesen203af582008-12-05 21:47:27 +0000770 // Also track whether all uses of each expression can be moved into an
771 // an addressing mode "for free"; such expressions are left within the loop.
772 // struct SubExprUseData { unsigned Count; bool notAllUsesAreFree; };
773 std::map<SCEVHandle, SubExprUseData> SubExpressionUseData;
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000774
Chris Lattnerd6155e92005-10-11 18:41:04 +0000775 // UniqueSubExprs - Keep track of all of the subexpressions we see in the
776 // order we see them.
777 std::vector<SCEVHandle> UniqueSubExprs;
778
Chris Lattner934520a2005-08-13 07:27:18 +0000779 std::vector<SCEVHandle> SubExprs;
Chris Lattnerf8828eb2008-12-02 04:52:26 +0000780 unsigned NumUsesInsideLoop = 0;
Chris Lattner934520a2005-08-13 07:27:18 +0000781 for (unsigned i = 0; i != NumUses; ++i) {
Chris Lattnerf8828eb2008-12-02 04:52:26 +0000782 // If the user is outside the loop, just ignore it for base computation.
783 // Since the user is outside the loop, it must be *after* the loop (if it
784 // were before, it could not be based on the loop IV). We don't want users
785 // after the loop to affect base computation of values *inside* the loop,
786 // because we can always add their offsets to the result IV after the loop
787 // is done, ensuring we get good code inside the loop.
Dale Johannesen589bf082008-12-01 22:00:01 +0000788 if (!L->contains(Uses[i].Inst->getParent()))
789 continue;
790 NumUsesInsideLoop++;
791
Chris Lattner934520a2005-08-13 07:27:18 +0000792 // If the base is zero (which is common), return zero now, there are no
793 // CSEs we can find.
794 if (Uses[i].Base == Zero) return Zero;
795
Dale Johannesen203af582008-12-05 21:47:27 +0000796 // If this use is as an address we may be able to put CSEs in the addressing
797 // mode rather than hoisting them.
798 bool isAddrUse = isAddressUse(Uses[i].Inst, Uses[i].OperandValToReplace);
799 // We may need the UseTy below, but only when isAddrUse, so compute it
800 // only in that case.
801 const Type *UseTy = 0;
Dan Gohman21e77222009-03-09 21:01:17 +0000802 if (isAddrUse)
803 UseTy = getAccessType(Uses[i].Inst);
Dale Johannesen203af582008-12-05 21:47:27 +0000804
Chris Lattner934520a2005-08-13 07:27:18 +0000805 // Split the expression into subexprs.
Dan Gohman246b2562007-10-22 18:31:58 +0000806 SeparateSubExprs(SubExprs, Uses[i].Base, SE);
Dale Johannesen203af582008-12-05 21:47:27 +0000807 // Add one to SubExpressionUseData.Count for each subexpr present, and
808 // if the subexpr is not a valid immediate within an addressing mode use,
809 // set SubExpressionUseData.notAllUsesAreFree. We definitely want to
810 // hoist these out of the loop (if they are common to all uses).
811 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j) {
812 if (++SubExpressionUseData[SubExprs[j]].Count == 1)
Chris Lattnerd6155e92005-10-11 18:41:04 +0000813 UniqueSubExprs.push_back(SubExprs[j]);
Dale Johannesen203af582008-12-05 21:47:27 +0000814 if (!isAddrUse || !fitsInAddressMode(SubExprs[j], UseTy, TLI, false))
815 SubExpressionUseData[SubExprs[j]].notAllUsesAreFree = true;
816 }
Chris Lattner934520a2005-08-13 07:27:18 +0000817 SubExprs.clear();
818 }
819
Chris Lattnerd6155e92005-10-11 18:41:04 +0000820 // Now that we know how many times each is used, build Result. Iterate over
821 // UniqueSubexprs so that we have a stable ordering.
822 for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
Dale Johannesen203af582008-12-05 21:47:27 +0000823 std::map<SCEVHandle, SubExprUseData>::iterator I =
824 SubExpressionUseData.find(UniqueSubExprs[i]);
825 assert(I != SubExpressionUseData.end() && "Entry not found?");
826 if (I->second.Count == NumUsesInsideLoop) { // Found CSE!
827 if (I->second.notAllUsesAreFree)
828 Result = SE->getAddExpr(Result, I->first);
829 else
830 FreeResult = SE->getAddExpr(FreeResult, I->first);
831 } else
832 // Remove non-cse's from SubExpressionUseData.
833 SubExpressionUseData.erase(I);
Chris Lattnerd6155e92005-10-11 18:41:04 +0000834 }
Dale Johannesen203af582008-12-05 21:47:27 +0000835
836 if (FreeResult != Zero) {
837 // We have some subexpressions that can be subsumed into addressing
838 // modes in every use inside the loop. However, it's possible that
839 // there are so many of them that the combined FreeResult cannot
840 // be subsumed, or that the target cannot handle both a FreeResult
841 // and a Result in the same instruction (for example because it would
842 // require too many registers). Check this.
843 for (unsigned i=0; i<NumUses; ++i) {
844 if (!L->contains(Uses[i].Inst->getParent()))
845 continue;
846 // We know this is an addressing mode use; if there are any uses that
847 // are not, FreeResult would be Zero.
Dan Gohman21e77222009-03-09 21:01:17 +0000848 const Type *UseTy = getAccessType(Uses[i].Inst);
Dale Johannesen203af582008-12-05 21:47:27 +0000849 if (!fitsInAddressMode(FreeResult, UseTy, TLI, Result!=Zero)) {
850 // FIXME: could split up FreeResult into pieces here, some hoisted
Dale Johannesenb0390622008-12-16 22:16:28 +0000851 // and some not. There is no obvious advantage to this.
Dale Johannesen203af582008-12-05 21:47:27 +0000852 Result = SE->getAddExpr(Result, FreeResult);
853 FreeResult = Zero;
854 break;
855 }
856 }
857 }
858
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000859 // If we found no CSE's, return now.
860 if (Result == Zero) return Result;
861
Dale Johannesen203af582008-12-05 21:47:27 +0000862 // If we still have a FreeResult, remove its subexpressions from
863 // SubExpressionUseData. This means they will remain in the use Bases.
864 if (FreeResult != Zero) {
865 SeparateSubExprs(SubExprs, FreeResult, SE);
866 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j) {
867 std::map<SCEVHandle, SubExprUseData>::iterator I =
868 SubExpressionUseData.find(SubExprs[j]);
869 SubExpressionUseData.erase(I);
870 }
871 SubExprs.clear();
872 }
873
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000874 // Otherwise, remove all of the CSE's we found from each of the base values.
Chris Lattner934520a2005-08-13 07:27:18 +0000875 for (unsigned i = 0; i != NumUses; ++i) {
Dale Johannesenfb10cd42008-12-02 21:17:11 +0000876 // Uses outside the loop don't necessarily include the common base, but
877 // the final IV value coming into those uses does. Instead of trying to
878 // remove the pieces of the common base, which might not be there,
879 // subtract off the base to compensate for this.
880 if (!L->contains(Uses[i].Inst->getParent())) {
881 Uses[i].Base = SE->getMinusSCEV(Uses[i].Base, Result);
Dale Johannesen589bf082008-12-01 22:00:01 +0000882 continue;
Dale Johannesenfb10cd42008-12-02 21:17:11 +0000883 }
Dale Johannesen589bf082008-12-01 22:00:01 +0000884
Chris Lattner934520a2005-08-13 07:27:18 +0000885 // Split the expression into subexprs.
Dan Gohman246b2562007-10-22 18:31:58 +0000886 SeparateSubExprs(SubExprs, Uses[i].Base, SE);
Chris Lattner934520a2005-08-13 07:27:18 +0000887
888 // Remove any common subexpressions.
889 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
Dale Johannesen203af582008-12-05 21:47:27 +0000890 if (SubExpressionUseData.count(SubExprs[j])) {
Chris Lattner934520a2005-08-13 07:27:18 +0000891 SubExprs.erase(SubExprs.begin()+j);
892 --j; --e;
893 }
894
Chris Lattnerf8828eb2008-12-02 04:52:26 +0000895 // Finally, add the non-shared expressions together.
Chris Lattner934520a2005-08-13 07:27:18 +0000896 if (SubExprs.empty())
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000897 Uses[i].Base = Zero;
Chris Lattner934520a2005-08-13 07:27:18 +0000898 else
Dan Gohman246b2562007-10-22 18:31:58 +0000899 Uses[i].Base = SE->getAddExpr(SubExprs);
Chris Lattner27e51422005-08-13 07:42:01 +0000900 SubExprs.clear();
Chris Lattner934520a2005-08-13 07:27:18 +0000901 }
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000902
903 return Result;
904}
905
Evan Cheng5792f512009-05-11 22:33:01 +0000906/// ValidScale - Check whether the given Scale is valid for all loads and
Chris Lattner579633c2007-04-09 22:20:14 +0000907/// stores in UsersToProcess.
Dale Johannesendc42f482007-03-20 00:47:50 +0000908///
Evan Cheng5792f512009-05-11 22:33:01 +0000909bool LoopStrengthReduce::ValidScale(bool HasBaseReg, int64_t Scale,
Dale Johannesendc42f482007-03-20 00:47:50 +0000910 const std::vector<BasedUser>& UsersToProcess) {
Evan Chengd6b62a52007-12-19 23:33:23 +0000911 if (!TLI)
912 return true;
913
Evan Cheng5792f512009-05-11 22:33:01 +0000914 for (unsigned i = 0, e = UsersToProcess.size(); i!=e; ++i) {
Chris Lattner1ebd89e2007-04-02 06:34:44 +0000915 // If this is a load or other access, pass the type of the access in.
916 const Type *AccessTy = Type::VoidTy;
Dan Gohman21e77222009-03-09 21:01:17 +0000917 if (isAddressUse(UsersToProcess[i].Inst,
918 UsersToProcess[i].OperandValToReplace))
919 AccessTy = getAccessType(UsersToProcess[i].Inst);
Evan Cheng55e641b2008-03-19 22:02:26 +0000920 else if (isa<PHINode>(UsersToProcess[i].Inst))
921 continue;
Chris Lattner1ebd89e2007-04-02 06:34:44 +0000922
Chris Lattner579633c2007-04-09 22:20:14 +0000923 TargetLowering::AddrMode AM;
Dan Gohman890f92b2009-04-18 17:56:28 +0000924 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(UsersToProcess[i].Imm))
Chris Lattner579633c2007-04-09 22:20:14 +0000925 AM.BaseOffs = SC->getValue()->getSExtValue();
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000926 AM.HasBaseReg = HasBaseReg || !UsersToProcess[i].Base->isZero();
Chris Lattner579633c2007-04-09 22:20:14 +0000927 AM.Scale = Scale;
928
929 // If load[imm+r*scale] is illegal, bail out.
Evan Chengd6b62a52007-12-19 23:33:23 +0000930 if (!TLI->isLegalAddressingMode(AM, AccessTy))
Dale Johannesendc42f482007-03-20 00:47:50 +0000931 return false;
Dale Johannesen8e59e162007-03-20 21:54:54 +0000932 }
Dale Johannesendc42f482007-03-20 00:47:50 +0000933 return true;
934}
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000935
Dan Gohman81db61a2009-05-12 02:17:14 +0000936/// ValidOffset - Check whether the given Offset is valid for all loads and
937/// stores in UsersToProcess.
938///
939bool LoopStrengthReduce::ValidOffset(bool HasBaseReg,
940 int64_t Offset,
941 int64_t Scale,
942 const std::vector<BasedUser>& UsersToProcess) {
943 if (!TLI)
944 return true;
945
946 for (unsigned i=0, e = UsersToProcess.size(); i!=e; ++i) {
947 // If this is a load or other access, pass the type of the access in.
948 const Type *AccessTy = Type::VoidTy;
949 if (isAddressUse(UsersToProcess[i].Inst,
950 UsersToProcess[i].OperandValToReplace))
951 AccessTy = getAccessType(UsersToProcess[i].Inst);
952 else if (isa<PHINode>(UsersToProcess[i].Inst))
953 continue;
954
955 TargetLowering::AddrMode AM;
956 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(UsersToProcess[i].Imm))
957 AM.BaseOffs = SC->getValue()->getSExtValue();
958 AM.BaseOffs = (uint64_t)AM.BaseOffs + (uint64_t)Offset;
959 AM.HasBaseReg = HasBaseReg || !UsersToProcess[i].Base->isZero();
960 AM.Scale = Scale;
961
962 // If load[imm+r*scale] is illegal, bail out.
963 if (!TLI->isLegalAddressingMode(AM, AccessTy))
964 return false;
965 }
966 return true;
967}
968
Dale Johannesen1de17d52009-02-09 22:14:15 +0000969/// RequiresTypeConversion - Returns true if converting Ty1 to Ty2 is not
Evan Cheng5f8ebaa2007-10-25 22:45:20 +0000970/// a nop.
Evan Cheng2bd122c2007-10-26 01:56:11 +0000971bool LoopStrengthReduce::RequiresTypeConversion(const Type *Ty1,
972 const Type *Ty2) {
973 if (Ty1 == Ty2)
Evan Cheng5f8ebaa2007-10-25 22:45:20 +0000974 return false;
Dan Gohman9f2d6712009-05-01 17:07:43 +0000975 Ty1 = SE->getEffectiveSCEVType(Ty1);
976 Ty2 = SE->getEffectiveSCEVType(Ty2);
977 if (Ty1 == Ty2)
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000978 return false;
Dale Johannesen1de17d52009-02-09 22:14:15 +0000979 if (Ty1->canLosslesslyBitCastTo(Ty2))
980 return false;
Evan Cheng2bd122c2007-10-26 01:56:11 +0000981 if (TLI && TLI->isTruncateFree(Ty1, Ty2))
982 return false;
Dale Johannesen1de17d52009-02-09 22:14:15 +0000983 return true;
Evan Cheng5f8ebaa2007-10-25 22:45:20 +0000984}
985
Evan Chengeb8f9e22006-03-17 19:52:23 +0000986/// CheckForIVReuse - Returns the multiple if the stride is the multiple
987/// of a previous stride and it is a legal value for the target addressing
Dan Gohman02e4fa72007-10-22 20:40:42 +0000988/// mode scale component and optional base reg. This allows the users of
989/// this stride to be rewritten as prev iv * factor. It returns 0 if no
Dale Johannesenb0390622008-12-16 22:16:28 +0000990/// reuse is possible. Factors can be negative on same targets, e.g. ARM.
Dale Johannesen2f46bb82009-01-14 02:35:31 +0000991///
992/// If all uses are outside the loop, we don't require that all multiplies
993/// be folded into the addressing mode, nor even that the factor be constant;
994/// a multiply (executed once) outside the loop is better than another IV
995/// within. Well, usually.
996SCEVHandle LoopStrengthReduce::CheckForIVReuse(bool HasBaseReg,
Evan Cheng2bd122c2007-10-26 01:56:11 +0000997 bool AllUsesAreAddresses,
Dale Johannesenb0390622008-12-16 22:16:28 +0000998 bool AllUsesAreOutsideLoop,
Dan Gohman02e4fa72007-10-22 20:40:42 +0000999 const SCEVHandle &Stride,
Dale Johannesendc42f482007-03-20 00:47:50 +00001000 IVExpr &IV, const Type *Ty,
1001 const std::vector<BasedUser>& UsersToProcess) {
Evan Cheng5792f512009-05-11 22:33:01 +00001002 if (StrideNoReuse.count(Stride))
1003 return SE->getIntegerSCEV(0, Stride->getType());
1004
Dan Gohman890f92b2009-04-18 17:56:28 +00001005 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride)) {
Reid Spencer502db932007-03-02 23:37:53 +00001006 int64_t SInt = SC->getValue()->getSExtValue();
Dan Gohman81db61a2009-05-12 02:17:14 +00001007 for (unsigned NewStride = 0, e = IU->StrideOrder.size();
1008 NewStride != e; ++NewStride) {
Dale Johannesenb51b4b52007-11-17 02:48:01 +00001009 std::map<SCEVHandle, IVsOfOneStride>::iterator SI =
Dan Gohman81db61a2009-05-12 02:17:14 +00001010 IVsByStride.find(IU->StrideOrder[NewStride]);
Evan Cheng5792f512009-05-11 22:33:01 +00001011 if (SI == IVsByStride.end() || !isa<SCEVConstant>(SI->first) ||
1012 StrideNoReuse.count(SI->first))
Dale Johannesenb51b4b52007-11-17 02:48:01 +00001013 continue;
Evan Cheng5eef2d22007-03-12 23:27:37 +00001014 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
Evan Cheng2bd122c2007-10-26 01:56:11 +00001015 if (SI->first != Stride &&
Dale Johannesen7b9486a2009-05-13 00:24:22 +00001016 (unsigned(abs64(SInt)) < SSInt || (SInt % SSInt) != 0))
Evan Chengeb8f9e22006-03-17 19:52:23 +00001017 continue;
Evan Cheng5eef2d22007-03-12 23:27:37 +00001018 int64_t Scale = SInt / SSInt;
Dale Johannesendc42f482007-03-20 00:47:50 +00001019 // Check that this stride is valid for all the types used for loads and
1020 // stores; if it can be used for some and not others, we might as well use
1021 // the original stride everywhere, since we have to create the IV for it
Dan Gohmanaa343312007-10-29 19:23:53 +00001022 // anyway. If the scale is 1, then we don't need to worry about folding
1023 // multiplications.
1024 if (Scale == 1 ||
1025 (AllUsesAreAddresses &&
Dan Gohman81db61a2009-05-12 02:17:14 +00001026 ValidScale(HasBaseReg, Scale, UsersToProcess))) {
1027 // Prefer to reuse an IV with a base of zero.
Evan Cheng5eef2d22007-03-12 23:27:37 +00001028 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1029 IE = SI->second.IVs.end(); II != IE; ++II)
Dan Gohman81db61a2009-05-12 02:17:14 +00001030 // Only reuse previous IV if it would not require a type conversion
1031 // and if the base difference can be folded.
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001032 if (II->Base->isZero() &&
Evan Cheng2bd122c2007-10-26 01:56:11 +00001033 !RequiresTypeConversion(II->Base->getType(), Ty)) {
Evan Cheng5eef2d22007-03-12 23:27:37 +00001034 IV = *II;
Dale Johannesen2f46bb82009-01-14 02:35:31 +00001035 return SE->getIntegerSCEV(Scale, Stride->getType());
Evan Cheng5eef2d22007-03-12 23:27:37 +00001036 }
Dan Gohman81db61a2009-05-12 02:17:14 +00001037 // Otherwise, settle for an IV with a foldable base.
1038 if (AllUsesAreAddresses)
1039 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1040 IE = SI->second.IVs.end(); II != IE; ++II)
1041 // Only reuse previous IV if it would not require a type conversion
1042 // and if the base difference can be folded.
1043 if (SE->getEffectiveSCEVType(II->Base->getType()) ==
1044 SE->getEffectiveSCEVType(Ty) &&
1045 isa<SCEVConstant>(II->Base)) {
1046 int64_t Base =
1047 cast<SCEVConstant>(II->Base)->getValue()->getSExtValue();
1048 if (Base > INT32_MIN && Base <= INT32_MAX &&
1049 ValidOffset(HasBaseReg, -Base * Scale,
1050 Scale, UsersToProcess)) {
1051 IV = *II;
1052 return SE->getIntegerSCEV(Scale, Stride->getType());
1053 }
1054 }
1055 }
Evan Chengeb8f9e22006-03-17 19:52:23 +00001056 }
Dale Johannesen2f46bb82009-01-14 02:35:31 +00001057 } else if (AllUsesAreOutsideLoop) {
1058 // Accept nonconstant strides here; it is really really right to substitute
1059 // an existing IV if we can.
Dan Gohman81db61a2009-05-12 02:17:14 +00001060 for (unsigned NewStride = 0, e = IU->StrideOrder.size();
1061 NewStride != e; ++NewStride) {
Dale Johannesen2f46bb82009-01-14 02:35:31 +00001062 std::map<SCEVHandle, IVsOfOneStride>::iterator SI =
Dan Gohman81db61a2009-05-12 02:17:14 +00001063 IVsByStride.find(IU->StrideOrder[NewStride]);
Dale Johannesen2f46bb82009-01-14 02:35:31 +00001064 if (SI == IVsByStride.end() || !isa<SCEVConstant>(SI->first))
1065 continue;
1066 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
1067 if (SI->first != Stride && SSInt != 1)
1068 continue;
1069 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1070 IE = SI->second.IVs.end(); II != IE; ++II)
1071 // Accept nonzero base here.
1072 // Only reuse previous IV if it would not require a type conversion.
1073 if (!RequiresTypeConversion(II->Base->getType(), Ty)) {
1074 IV = *II;
1075 return Stride;
1076 }
1077 }
1078 // Special case, old IV is -1*x and this one is x. Can treat this one as
1079 // -1*old.
Dan Gohman81db61a2009-05-12 02:17:14 +00001080 for (unsigned NewStride = 0, e = IU->StrideOrder.size();
1081 NewStride != e; ++NewStride) {
Dale Johannesen2f46bb82009-01-14 02:35:31 +00001082 std::map<SCEVHandle, IVsOfOneStride>::iterator SI =
Dan Gohman81db61a2009-05-12 02:17:14 +00001083 IVsByStride.find(IU->StrideOrder[NewStride]);
Dale Johannesen2f46bb82009-01-14 02:35:31 +00001084 if (SI == IVsByStride.end())
1085 continue;
Dan Gohman890f92b2009-04-18 17:56:28 +00001086 if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(SI->first))
1087 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(ME->getOperand(0)))
Dale Johannesen2f46bb82009-01-14 02:35:31 +00001088 if (Stride == ME->getOperand(1) &&
1089 SC->getValue()->getSExtValue() == -1LL)
1090 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1091 IE = SI->second.IVs.end(); II != IE; ++II)
1092 // Accept nonzero base here.
1093 // Only reuse previous IV if it would not require type conversion.
1094 if (!RequiresTypeConversion(II->Base->getType(), Ty)) {
1095 IV = *II;
1096 return SE->getIntegerSCEV(-1LL, Stride->getType());
1097 }
1098 }
Evan Chengeb8f9e22006-03-17 19:52:23 +00001099 }
Dale Johannesen2f46bb82009-01-14 02:35:31 +00001100 return SE->getIntegerSCEV(0, Stride->getType());
Evan Chengeb8f9e22006-03-17 19:52:23 +00001101}
1102
Chris Lattner7e79b382006-08-03 06:34:50 +00001103/// PartitionByIsUseOfPostIncrementedValue - Simple boolean predicate that
1104/// returns true if Val's isUseOfPostIncrementedValue is true.
1105static bool PartitionByIsUseOfPostIncrementedValue(const BasedUser &Val) {
1106 return Val.isUseOfPostIncrementedValue;
1107}
Evan Chengeb8f9e22006-03-17 19:52:23 +00001108
Dan Gohman4a9a3e52008-04-14 18:26:16 +00001109/// isNonConstantNegative - Return true if the specified scev is negated, but
Chris Lattnerfb3e1192007-05-19 01:22:21 +00001110/// not a constant.
1111static bool isNonConstantNegative(const SCEVHandle &Expr) {
Dan Gohman890f92b2009-04-18 17:56:28 +00001112 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Expr);
Chris Lattnerfb3e1192007-05-19 01:22:21 +00001113 if (!Mul) return false;
1114
1115 // If there is a constant factor, it will be first.
Dan Gohman890f92b2009-04-18 17:56:28 +00001116 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
Chris Lattnerfb3e1192007-05-19 01:22:21 +00001117 if (!SC) return false;
1118
1119 // Return true if the value is negative, this matches things like (-42 * V).
1120 return SC->getValue()->getValue().isNegative();
1121}
1122
Evan Cheng5f8ebaa2007-10-25 22:45:20 +00001123// CollectIVUsers - Transform our list of users and offsets to a bit more
Dan Gohman73b43b92008-06-23 22:11:52 +00001124// complex table. In this new vector, each 'BasedUser' contains 'Base', the base
1125// of the strided accesses, as well as the old information from Uses. We
Evan Cheng5f8ebaa2007-10-25 22:45:20 +00001126// progressively move information from the Base field to the Imm field, until
1127// we eventually have the full access expression to rewrite the use.
1128SCEVHandle LoopStrengthReduce::CollectIVUsers(const SCEVHandle &Stride,
1129 IVUsersOfOneStride &Uses,
1130 Loop *L,
1131 bool &AllUsesAreAddresses,
Dale Johannesenb0390622008-12-16 22:16:28 +00001132 bool &AllUsesAreOutsideLoop,
Evan Cheng5f8ebaa2007-10-25 22:45:20 +00001133 std::vector<BasedUser> &UsersToProcess) {
Dan Gohman81db61a2009-05-12 02:17:14 +00001134 // FIXME: Generalize to non-affine IV's.
1135 if (!Stride->isLoopInvariant(L))
1136 return SE->getIntegerSCEV(0, Stride->getType());
1137
Nate Begeman16997482005-07-30 00:15:07 +00001138 UsersToProcess.reserve(Uses.Users.size());
Dan Gohman81db61a2009-05-12 02:17:14 +00001139 for (ilist<IVStrideUse>::iterator I = Uses.Users.begin(),
1140 E = Uses.Users.end(); I != E; ++I) {
1141 UsersToProcess.push_back(BasedUser(*I, SE));
1142
Dale Johannesen67c79892008-12-03 19:25:46 +00001143 // Move any loop variant operands from the offset field to the immediate
Chris Lattnera553b0c2005-08-08 22:56:21 +00001144 // field of the use, so that we don't try to use something before it is
1145 // computed.
Dale Johannesen544e0d02008-12-03 20:56:12 +00001146 MoveLoopVariantsToImmediateField(UsersToProcess.back().Base,
Evan Cheng5792f512009-05-11 22:33:01 +00001147 UsersToProcess.back().Imm, L, SE);
Chris Lattnera553b0c2005-08-08 22:56:21 +00001148 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
Chris Lattner26d91f12005-08-04 22:34:05 +00001149 "Base value is not loop invariant!");
Nate Begeman16997482005-07-30 00:15:07 +00001150 }
Evan Chengeb8f9e22006-03-17 19:52:23 +00001151
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001152 // We now have a whole bunch of uses of like-strided induction variables, but
1153 // they might all have different bases. We want to emit one PHI node for this
1154 // stride which we fold as many common expressions (between the IVs) into as
1155 // possible. Start by identifying the common expressions in the base values
1156 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
1157 // "A+B"), emit it to the preheader, then remove the expression from the
1158 // UsersToProcess base values.
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001159 SCEVHandle CommonExprs =
Dale Johannesen203af582008-12-05 21:47:27 +00001160 RemoveCommonExpressionsFromUseBases(UsersToProcess, SE, L, TLI);
Dan Gohman02e4fa72007-10-22 20:40:42 +00001161
Chris Lattner44b807e2005-08-08 22:32:34 +00001162 // Next, figure out what we can represent in the immediate fields of
1163 // instructions. If we can represent anything there, move it to the imm
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001164 // fields of the BasedUsers. We do this so that it increases the commonality
1165 // of the remaining uses.
Evan Cheng32e4c7c2007-12-20 02:20:53 +00001166 unsigned NumPHI = 0;
Evan Chengd33cec12009-02-20 22:16:49 +00001167 bool HasAddress = false;
Chris Lattner44b807e2005-08-08 22:32:34 +00001168 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
Chris Lattner80b32b32005-08-16 00:38:11 +00001169 // If the user is not in the current loop, this means it is using the exit
1170 // value of the IV. Do not put anything in the base, make sure it's all in
1171 // the immediate field to allow as much factoring as possible.
1172 if (!L->contains(UsersToProcess[i].Inst->getParent())) {
Dan Gohman246b2562007-10-22 18:31:58 +00001173 UsersToProcess[i].Imm = SE->getAddExpr(UsersToProcess[i].Imm,
1174 UsersToProcess[i].Base);
Chris Lattner8385e512005-08-17 21:22:41 +00001175 UsersToProcess[i].Base =
Dan Gohman246b2562007-10-22 18:31:58 +00001176 SE->getIntegerSCEV(0, UsersToProcess[i].Base->getType());
Chris Lattner80b32b32005-08-16 00:38:11 +00001177 } else {
Evan Chengd9fb7122009-02-21 02:06:47 +00001178 // Not all uses are outside the loop.
1179 AllUsesAreOutsideLoop = false;
1180
Chris Lattner80b32b32005-08-16 00:38:11 +00001181 // Addressing modes can be folded into loads and stores. Be careful that
1182 // the store is through the expression, not of the expression though.
Evan Cheng32e4c7c2007-12-20 02:20:53 +00001183 bool isPHI = false;
Evan Chengd6b62a52007-12-19 23:33:23 +00001184 bool isAddress = isAddressUse(UsersToProcess[i].Inst,
1185 UsersToProcess[i].OperandValToReplace);
1186 if (isa<PHINode>(UsersToProcess[i].Inst)) {
Evan Cheng32e4c7c2007-12-20 02:20:53 +00001187 isPHI = true;
1188 ++NumPHI;
Dan Gohman2acc7602007-05-03 23:20:33 +00001189 }
Dan Gohman02e4fa72007-10-22 20:40:42 +00001190
Evan Chengd33cec12009-02-20 22:16:49 +00001191 if (isAddress)
1192 HasAddress = true;
Dale Johannesenb0390622008-12-16 22:16:28 +00001193
Dan Gohman02e4fa72007-10-22 20:40:42 +00001194 // If this use isn't an address, then not all uses are addresses.
Evan Cheng55e641b2008-03-19 22:02:26 +00001195 if (!isAddress && !isPHI)
Dan Gohman02e4fa72007-10-22 20:40:42 +00001196 AllUsesAreAddresses = false;
Chris Lattner80b32b32005-08-16 00:38:11 +00001197
Evan Cheng1d958162007-03-13 20:34:37 +00001198 MoveImmediateValues(TLI, UsersToProcess[i].Inst, UsersToProcess[i].Base,
Dan Gohman246b2562007-10-22 18:31:58 +00001199 UsersToProcess[i].Imm, isAddress, L, SE);
Chris Lattner80b32b32005-08-16 00:38:11 +00001200 }
Chris Lattner44b807e2005-08-08 22:32:34 +00001201 }
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001202
Evan Chengd9fb7122009-02-21 02:06:47 +00001203 // If one of the use is a PHI node and all other uses are addresses, still
Evan Cheng32e4c7c2007-12-20 02:20:53 +00001204 // allow iv reuse. Essentially we are trading one constant multiplication
1205 // for one fewer iv.
1206 if (NumPHI > 1)
1207 AllUsesAreAddresses = false;
Evan Chengd9fb7122009-02-21 02:06:47 +00001208
Evan Chengd33cec12009-02-20 22:16:49 +00001209 // There are no in-loop address uses.
1210 if (AllUsesAreAddresses && (!HasAddress && !AllUsesAreOutsideLoop))
1211 AllUsesAreAddresses = false;
1212
Evan Cheng5f8ebaa2007-10-25 22:45:20 +00001213 return CommonExprs;
1214}
1215
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001216/// ShouldUseFullStrengthReductionMode - Test whether full strength-reduction
1217/// is valid and profitable for the given set of users of a stride. In
1218/// full strength-reduction mode, all addresses at the current stride are
1219/// strength-reduced all the way down to pointer arithmetic.
1220///
1221bool LoopStrengthReduce::ShouldUseFullStrengthReductionMode(
1222 const std::vector<BasedUser> &UsersToProcess,
1223 const Loop *L,
1224 bool AllUsesAreAddresses,
1225 SCEVHandle Stride) {
1226 if (!EnableFullLSRMode)
1227 return false;
1228
1229 // The heuristics below aim to avoid increasing register pressure, but
1230 // fully strength-reducing all the addresses increases the number of
1231 // add instructions, so don't do this when optimizing for size.
1232 // TODO: If the loop is large, the savings due to simpler addresses
1233 // may oughtweight the costs of the extra increment instructions.
1234 if (L->getHeader()->getParent()->hasFnAttr(Attribute::OptimizeForSize))
1235 return false;
1236
1237 // TODO: For now, don't do full strength reduction if there could
1238 // potentially be greater-stride multiples of the current stride
1239 // which could reuse the current stride IV.
Dan Gohman81db61a2009-05-12 02:17:14 +00001240 if (IU->StrideOrder.back() != Stride)
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001241 return false;
1242
1243 // Iterate through the uses to find conditions that automatically rule out
1244 // full-lsr mode.
1245 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ) {
Dan Gohman622ed672009-05-04 22:02:23 +00001246 const SCEV *Base = UsersToProcess[i].Base;
1247 const SCEV *Imm = UsersToProcess[i].Imm;
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001248 // If any users have a loop-variant component, they can't be fully
1249 // strength-reduced.
1250 if (Imm && !Imm->isLoopInvariant(L))
1251 return false;
1252 // If there are to users with the same base and the difference between
1253 // the two Imm values can't be folded into the address, full
1254 // strength reduction would increase register pressure.
1255 do {
Dan Gohman622ed672009-05-04 22:02:23 +00001256 const SCEV *CurImm = UsersToProcess[i].Imm;
Dan Gohmana04af432009-02-22 16:40:52 +00001257 if ((CurImm || Imm) && CurImm != Imm) {
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001258 if (!CurImm) CurImm = SE->getIntegerSCEV(0, Stride->getType());
1259 if (!Imm) Imm = SE->getIntegerSCEV(0, Stride->getType());
1260 const Instruction *Inst = UsersToProcess[i].Inst;
Dan Gohman21e77222009-03-09 21:01:17 +00001261 const Type *UseTy = getAccessType(Inst);
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001262 SCEVHandle Diff = SE->getMinusSCEV(UsersToProcess[i].Imm, Imm);
1263 if (!Diff->isZero() &&
1264 (!AllUsesAreAddresses ||
1265 !fitsInAddressMode(Diff, UseTy, TLI, /*HasBaseReg=*/true)))
1266 return false;
1267 }
1268 } while (++i != e && Base == UsersToProcess[i].Base);
1269 }
1270
1271 // If there's exactly one user in this stride, fully strength-reducing it
1272 // won't increase register pressure. If it's starting from a non-zero base,
1273 // it'll be simpler this way.
1274 if (UsersToProcess.size() == 1 && !UsersToProcess[0].Base->isZero())
1275 return true;
1276
1277 // Otherwise, if there are any users in this stride that don't require
1278 // a register for their base, full strength-reduction will increase
1279 // register pressure.
1280 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
Dan Gohmanf0baa6e2009-02-20 21:05:23 +00001281 if (UsersToProcess[i].Base->isZero())
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001282 return false;
1283
1284 // Otherwise, go for it.
1285 return true;
1286}
1287
1288/// InsertAffinePhi Create and insert a PHI node for an induction variable
1289/// with the specified start and step values in the specified loop.
1290///
1291/// If NegateStride is true, the stride should be negated by using a
1292/// subtract instead of an add.
1293///
Dan Gohman9d100862009-03-09 22:04:01 +00001294/// Return the created phi node.
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001295///
1296static PHINode *InsertAffinePhi(SCEVHandle Start, SCEVHandle Step,
Evan Cheng5792f512009-05-11 22:33:01 +00001297 Instruction *IVIncInsertPt,
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001298 const Loop *L,
Dan Gohman9d100862009-03-09 22:04:01 +00001299 SCEVExpander &Rewriter) {
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001300 assert(Start->isLoopInvariant(L) && "New PHI start is not loop invariant!");
1301 assert(Step->isLoopInvariant(L) && "New PHI stride is not loop invariant!");
1302
1303 BasicBlock *Header = L->getHeader();
1304 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohman0daeed22009-03-09 21:14:16 +00001305 BasicBlock *LatchBlock = L->getLoopLatch();
Dan Gohman2d1be872009-04-16 03:18:22 +00001306 const Type *Ty = Start->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001307 Ty = Rewriter.SE.getEffectiveSCEVType(Ty);
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001308
Dan Gohman2d1be872009-04-16 03:18:22 +00001309 PHINode *PN = PHINode::Create(Ty, "lsr.iv", Header->begin());
1310 PN->addIncoming(Rewriter.expandCodeFor(Start, Ty, Preheader->getTerminator()),
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001311 Preheader);
1312
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001313 // If the stride is negative, insert a sub instead of an add for the
1314 // increment.
1315 bool isNegative = isNonConstantNegative(Step);
1316 SCEVHandle IncAmount = Step;
1317 if (isNegative)
1318 IncAmount = Rewriter.SE.getNegativeSCEV(Step);
1319
1320 // Insert an add instruction right before the terminator corresponding
Evan Cheng5792f512009-05-11 22:33:01 +00001321 // to the back-edge or just before the only use. The location is determined
1322 // by the caller and passed in as IVIncInsertPt.
Dan Gohman2d1be872009-04-16 03:18:22 +00001323 Value *StepV = Rewriter.expandCodeFor(IncAmount, Ty,
1324 Preheader->getTerminator());
Dan Gohman9d100862009-03-09 22:04:01 +00001325 Instruction *IncV;
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001326 if (isNegative) {
1327 IncV = BinaryOperator::CreateSub(PN, StepV, "lsr.iv.next",
Evan Cheng5792f512009-05-11 22:33:01 +00001328 IVIncInsertPt);
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001329 } else {
1330 IncV = BinaryOperator::CreateAdd(PN, StepV, "lsr.iv.next",
Evan Cheng5792f512009-05-11 22:33:01 +00001331 IVIncInsertPt);
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001332 }
1333 if (!isa<ConstantInt>(StepV)) ++NumVariable;
1334
Dan Gohman0daeed22009-03-09 21:14:16 +00001335 PN->addIncoming(IncV, LatchBlock);
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001336
1337 ++NumInserted;
1338 return PN;
1339}
1340
1341static void SortUsersToProcess(std::vector<BasedUser> &UsersToProcess) {
1342 // We want to emit code for users inside the loop first. To do this, we
1343 // rearrange BasedUser so that the entries at the end have
1344 // isUseOfPostIncrementedValue = false, because we pop off the end of the
1345 // vector (so we handle them first).
1346 std::partition(UsersToProcess.begin(), UsersToProcess.end(),
1347 PartitionByIsUseOfPostIncrementedValue);
1348
1349 // Sort this by base, so that things with the same base are handled
1350 // together. By partitioning first and stable-sorting later, we are
1351 // guaranteed that within each base we will pop off users from within the
1352 // loop before users outside of the loop with a particular base.
1353 //
1354 // We would like to use stable_sort here, but we can't. The problem is that
1355 // SCEVHandle's don't have a deterministic ordering w.r.t to each other, so
1356 // we don't have anything to do a '<' comparison on. Because we think the
1357 // number of uses is small, do a horrible bubble sort which just relies on
1358 // ==.
1359 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1360 // Get a base value.
1361 SCEVHandle Base = UsersToProcess[i].Base;
1362
1363 // Compact everything with this base to be consecutive with this one.
1364 for (unsigned j = i+1; j != e; ++j) {
1365 if (UsersToProcess[j].Base == Base) {
1366 std::swap(UsersToProcess[i+1], UsersToProcess[j]);
1367 ++i;
1368 }
1369 }
1370 }
1371}
1372
Dan Gohman6b38e292009-02-20 21:06:57 +00001373/// PrepareToStrengthReduceFully - Prepare to fully strength-reduce
1374/// UsersToProcess, meaning lowering addresses all the way down to direct
1375/// pointer arithmetic.
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001376///
1377void
1378LoopStrengthReduce::PrepareToStrengthReduceFully(
1379 std::vector<BasedUser> &UsersToProcess,
1380 SCEVHandle Stride,
1381 SCEVHandle CommonExprs,
1382 const Loop *L,
1383 SCEVExpander &PreheaderRewriter) {
1384 DOUT << " Fully reducing all users\n";
1385
1386 // Rewrite the UsersToProcess records, creating a separate PHI for each
1387 // unique Base value.
Evan Cheng5792f512009-05-11 22:33:01 +00001388 Instruction *IVIncInsertPt = L->getLoopLatch()->getTerminator();
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001389 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ) {
1390 // TODO: The uses are grouped by base, but not sorted. We arbitrarily
1391 // pick the first Imm value here to start with, and adjust it for the
1392 // other uses.
1393 SCEVHandle Imm = UsersToProcess[i].Imm;
1394 SCEVHandle Base = UsersToProcess[i].Base;
1395 SCEVHandle Start = SE->getAddExpr(CommonExprs, Base, Imm);
Evan Cheng5792f512009-05-11 22:33:01 +00001396 PHINode *Phi = InsertAffinePhi(Start, Stride, IVIncInsertPt, L,
Dan Gohman9d100862009-03-09 22:04:01 +00001397 PreheaderRewriter);
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001398 // Loop over all the users with the same base.
1399 do {
1400 UsersToProcess[i].Base = SE->getIntegerSCEV(0, Stride->getType());
1401 UsersToProcess[i].Imm = SE->getMinusSCEV(UsersToProcess[i].Imm, Imm);
1402 UsersToProcess[i].Phi = Phi;
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001403 assert(UsersToProcess[i].Imm->isLoopInvariant(L) &&
1404 "ShouldUseFullStrengthReductionMode should reject this!");
1405 } while (++i != e && Base == UsersToProcess[i].Base);
1406 }
1407}
1408
Evan Cheng5792f512009-05-11 22:33:01 +00001409/// FindIVIncInsertPt - Return the location to insert the increment instruction.
1410/// If the only use if a use of postinc value, (must be the loop termination
1411/// condition), then insert it just before the use.
1412static Instruction *FindIVIncInsertPt(std::vector<BasedUser> &UsersToProcess,
1413 const Loop *L) {
1414 if (UsersToProcess.size() == 1 &&
1415 UsersToProcess[0].isUseOfPostIncrementedValue &&
1416 L->contains(UsersToProcess[0].Inst->getParent()))
1417 return UsersToProcess[0].Inst;
1418 return L->getLoopLatch()->getTerminator();
1419}
1420
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001421/// PrepareToStrengthReduceWithNewPhi - Insert a new induction variable for the
1422/// given users to share.
1423///
1424void
1425LoopStrengthReduce::PrepareToStrengthReduceWithNewPhi(
1426 std::vector<BasedUser> &UsersToProcess,
1427 SCEVHandle Stride,
1428 SCEVHandle CommonExprs,
1429 Value *CommonBaseV,
Evan Cheng5792f512009-05-11 22:33:01 +00001430 Instruction *IVIncInsertPt,
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001431 const Loop *L,
1432 SCEVExpander &PreheaderRewriter) {
1433 DOUT << " Inserting new PHI:\n";
1434
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001435 PHINode *Phi = InsertAffinePhi(SE->getUnknown(CommonBaseV),
Evan Cheng5792f512009-05-11 22:33:01 +00001436 Stride, IVIncInsertPt, L,
Dan Gohman9d100862009-03-09 22:04:01 +00001437 PreheaderRewriter);
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001438
1439 // Remember this in case a later stride is multiple of this.
Dan Gohman9d100862009-03-09 22:04:01 +00001440 IVsByStride[Stride].addIV(Stride, CommonExprs, Phi);
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001441
1442 // All the users will share this new IV.
Dan Gohman9d100862009-03-09 22:04:01 +00001443 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001444 UsersToProcess[i].Phi = Phi;
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001445
1446 DOUT << " IV=";
1447 DEBUG(WriteAsOperand(*DOUT, Phi, /*PrintType=*/false));
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001448 DOUT << "\n";
1449}
1450
Evan Cheng5792f512009-05-11 22:33:01 +00001451/// PrepareToStrengthReduceFromSmallerStride - Prepare for the given users to
1452/// reuse an induction variable with a stride that is a factor of the current
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001453/// induction variable.
1454///
1455void
1456LoopStrengthReduce::PrepareToStrengthReduceFromSmallerStride(
1457 std::vector<BasedUser> &UsersToProcess,
1458 Value *CommonBaseV,
1459 const IVExpr &ReuseIV,
1460 Instruction *PreInsertPt) {
1461 DOUT << " Rewriting in terms of existing IV of STRIDE " << *ReuseIV.Stride
1462 << " and BASE " << *ReuseIV.Base << "\n";
1463
1464 // All the users will share the reused IV.
Dan Gohman9d100862009-03-09 22:04:01 +00001465 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001466 UsersToProcess[i].Phi = ReuseIV.PHI;
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001467
1468 Constant *C = dyn_cast<Constant>(CommonBaseV);
1469 if (C &&
1470 (!C->isNullValue() &&
1471 !fitsInAddressMode(SE->getUnknown(CommonBaseV), CommonBaseV->getType(),
1472 TLI, false)))
1473 // We want the common base emitted into the preheader! This is just
1474 // using cast as a copy so BitCast (no-op cast) is appropriate
1475 CommonBaseV = new BitCastInst(CommonBaseV, CommonBaseV->getType(),
1476 "commonbase", PreInsertPt);
1477}
1478
Evan Chengd9fb7122009-02-21 02:06:47 +00001479static bool IsImmFoldedIntoAddrMode(GlobalValue *GV, int64_t Offset,
Dan Gohman53f2ae22009-03-09 21:04:19 +00001480 const Type *AccessTy,
Evan Chengd9fb7122009-02-21 02:06:47 +00001481 std::vector<BasedUser> &UsersToProcess,
1482 const TargetLowering *TLI) {
1483 SmallVector<Instruction*, 16> AddrModeInsts;
1484 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1485 if (UsersToProcess[i].isUseOfPostIncrementedValue)
1486 continue;
1487 ExtAddrMode AddrMode =
1488 AddressingModeMatcher::Match(UsersToProcess[i].OperandValToReplace,
Dan Gohman53f2ae22009-03-09 21:04:19 +00001489 AccessTy, UsersToProcess[i].Inst,
Evan Chengd9fb7122009-02-21 02:06:47 +00001490 AddrModeInsts, *TLI);
1491 if (GV && GV != AddrMode.BaseGV)
1492 return false;
1493 if (Offset && !AddrMode.BaseOffs)
1494 // FIXME: How to accurate check it's immediate offset is folded.
1495 return false;
1496 AddrModeInsts.clear();
1497 }
1498 return true;
1499}
1500
Evan Cheng5f8ebaa2007-10-25 22:45:20 +00001501/// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
1502/// stride of IV. All of the users may have different starting values, and this
Dan Gohman9f4ac312009-03-09 20:41:15 +00001503/// may not be the only stride.
Evan Cheng5f8ebaa2007-10-25 22:45:20 +00001504void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
1505 IVUsersOfOneStride &Uses,
Dan Gohman9f4ac312009-03-09 20:41:15 +00001506 Loop *L) {
Evan Cheng5f8ebaa2007-10-25 22:45:20 +00001507 // If all the users are moved to another stride, then there is nothing to do.
Dan Gohman30359592008-01-29 13:02:09 +00001508 if (Uses.Users.empty())
Evan Cheng5f8ebaa2007-10-25 22:45:20 +00001509 return;
1510
1511 // Keep track if every use in UsersToProcess is an address. If they all are,
1512 // we may be able to rewrite the entire collection of them in terms of a
1513 // smaller-stride IV.
1514 bool AllUsesAreAddresses = true;
1515
Dale Johannesenb0390622008-12-16 22:16:28 +00001516 // Keep track if every use of a single stride is outside the loop. If so,
1517 // we want to be more aggressive about reusing a smaller-stride IV; a
1518 // multiply outside the loop is better than another IV inside. Well, usually.
1519 bool AllUsesAreOutsideLoop = true;
1520
Evan Cheng5f8ebaa2007-10-25 22:45:20 +00001521 // Transform our list of users and offsets to a bit more complex table. In
1522 // this new vector, each 'BasedUser' contains 'Base' the base of the
1523 // strided accessas well as the old information from Uses. We progressively
1524 // move information from the Base field to the Imm field, until we eventually
1525 // have the full access expression to rewrite the use.
1526 std::vector<BasedUser> UsersToProcess;
1527 SCEVHandle CommonExprs = CollectIVUsers(Stride, Uses, L, AllUsesAreAddresses,
Dale Johannesenb0390622008-12-16 22:16:28 +00001528 AllUsesAreOutsideLoop,
Evan Cheng5f8ebaa2007-10-25 22:45:20 +00001529 UsersToProcess);
1530
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001531 // Sort the UsersToProcess array so that users with common bases are
1532 // next to each other.
1533 SortUsersToProcess(UsersToProcess);
1534
Evan Cheng5f8ebaa2007-10-25 22:45:20 +00001535 // If we managed to find some expressions in common, we'll need to carry
1536 // their value in a register and add it in for each use. This will take up
1537 // a register operand, which potentially restricts what stride values are
1538 // valid.
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001539 bool HaveCommonExprs = !CommonExprs->isZero();
Chris Lattnerfe355552007-04-01 22:21:39 +00001540 const Type *ReplacedTy = CommonExprs->getType();
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001541
Evan Chengd9fb7122009-02-21 02:06:47 +00001542 // If all uses are addresses, consider sinking the immediate part of the
1543 // common expression back into uses if they can fit in the immediate fields.
Evan Cheng3cd389d2009-02-22 07:31:19 +00001544 if (TLI && HaveCommonExprs && AllUsesAreAddresses) {
Evan Chengd9fb7122009-02-21 02:06:47 +00001545 SCEVHandle NewCommon = CommonExprs;
1546 SCEVHandle Imm = SE->getIntegerSCEV(0, ReplacedTy);
Dan Gohman3cfe6a42009-03-09 21:22:12 +00001547 MoveImmediateValues(TLI, Type::VoidTy, NewCommon, Imm, true, L, SE);
Evan Chengd9fb7122009-02-21 02:06:47 +00001548 if (!Imm->isZero()) {
1549 bool DoSink = true;
1550
1551 // If the immediate part of the common expression is a GV, check if it's
1552 // possible to fold it into the target addressing mode.
1553 GlobalValue *GV = 0;
Dan Gohman890f92b2009-04-18 17:56:28 +00001554 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(Imm))
Dan Gohman2d1be872009-04-16 03:18:22 +00001555 GV = dyn_cast<GlobalValue>(SU->getValue());
Evan Chengd9fb7122009-02-21 02:06:47 +00001556 int64_t Offset = 0;
Dan Gohman890f92b2009-04-18 17:56:28 +00001557 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Imm))
Evan Chengd9fb7122009-02-21 02:06:47 +00001558 Offset = SC->getValue()->getSExtValue();
1559 if (GV || Offset)
Dan Gohman53f2ae22009-03-09 21:04:19 +00001560 // Pass VoidTy as the AccessTy to be conservative, because
1561 // there could be multiple access types among all the uses.
1562 DoSink = IsImmFoldedIntoAddrMode(GV, Offset, Type::VoidTy,
Evan Chengd9fb7122009-02-21 02:06:47 +00001563 UsersToProcess, TLI);
1564
1565 if (DoSink) {
1566 DOUT << " Sinking " << *Imm << " back down into uses\n";
1567 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1568 UsersToProcess[i].Imm = SE->getAddExpr(UsersToProcess[i].Imm, Imm);
1569 CommonExprs = NewCommon;
1570 HaveCommonExprs = !CommonExprs->isZero();
1571 ++NumImmSunk;
1572 }
1573 }
1574 }
1575
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001576 // Now that we know what we need to do, insert the PHI node itself.
1577 //
Dan Gohman2f09f512009-02-19 19:23:27 +00001578 DOUT << "LSR: Examining IVs of TYPE " << *ReplacedTy << " of STRIDE "
1579 << *Stride << ":\n"
1580 << " Common base: " << *CommonExprs << "\n";
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001581
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001582 SCEVExpander Rewriter(*SE, *LI);
1583 SCEVExpander PreheaderRewriter(*SE, *LI);
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001584
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001585 BasicBlock *Preheader = L->getLoopPreheader();
1586 Instruction *PreInsertPt = Preheader->getTerminator();
Chris Lattner12b50412005-09-12 17:11:27 +00001587 BasicBlock *LatchBlock = L->getLoopLatch();
Evan Cheng5792f512009-05-11 22:33:01 +00001588 Instruction *IVIncInsertPt = LatchBlock->getTerminator();
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001589
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001590 Value *CommonBaseV = Constant::getNullValue(ReplacedTy);
Evan Chengeb8f9e22006-03-17 19:52:23 +00001591
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001592 SCEVHandle RewriteFactor = SE->getIntegerSCEV(0, ReplacedTy);
1593 IVExpr ReuseIV(SE->getIntegerSCEV(0, Type::Int32Ty),
1594 SE->getIntegerSCEV(0, Type::Int32Ty),
Dan Gohman9d100862009-03-09 22:04:01 +00001595 0);
Evan Chengeb8f9e22006-03-17 19:52:23 +00001596
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001597 /// Choose a strength-reduction strategy and prepare for it by creating
1598 /// the necessary PHIs and adjusting the bookkeeping.
1599 if (ShouldUseFullStrengthReductionMode(UsersToProcess, L,
1600 AllUsesAreAddresses, Stride)) {
1601 PrepareToStrengthReduceFully(UsersToProcess, Stride, CommonExprs, L,
1602 PreheaderRewriter);
Evan Chengeb8f9e22006-03-17 19:52:23 +00001603 } else {
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001604 // Emit the initial base value into the loop preheader.
Dan Gohman2d1be872009-04-16 03:18:22 +00001605 CommonBaseV = PreheaderRewriter.expandCodeFor(CommonExprs, ReplacedTy,
1606 PreInsertPt);
Dan Gohman2f09f512009-02-19 19:23:27 +00001607
Dale Johannesenc1acc3f2009-05-11 17:15:42 +00001608 // If all uses are addresses, check if it is possible to reuse an IV. The
1609 // new IV must have a stride that is a multiple of the old stride; the
1610 // multiple must be a number that can be encoded in the scale field of the
1611 // target addressing mode; and we must have a valid instruction after this
1612 // substitution, including the immediate field, if any.
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001613 RewriteFactor = CheckForIVReuse(HaveCommonExprs, AllUsesAreAddresses,
1614 AllUsesAreOutsideLoop,
Dan Gohmanbb5b49c2009-03-09 21:19:58 +00001615 Stride, ReuseIV, ReplacedTy,
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001616 UsersToProcess);
Evan Cheng5792f512009-05-11 22:33:01 +00001617 if (!RewriteFactor->isZero())
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001618 PrepareToStrengthReduceFromSmallerStride(UsersToProcess, CommonBaseV,
1619 ReuseIV, PreInsertPt);
Evan Cheng5792f512009-05-11 22:33:01 +00001620 else {
1621 IVIncInsertPt = FindIVIncInsertPt(UsersToProcess, L);
1622 PrepareToStrengthReduceWithNewPhi(UsersToProcess, Stride, CommonExprs,
1623 CommonBaseV, IVIncInsertPt,
1624 L, PreheaderRewriter);
1625 }
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001626 }
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001627
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001628 // Process all the users now, replacing their strided uses with
1629 // strength-reduced forms. This outer loop handles all bases, the inner
Chris Lattner7e79b382006-08-03 06:34:50 +00001630 // loop handles all users of a particular base.
Nate Begeman16997482005-07-30 00:15:07 +00001631 while (!UsersToProcess.empty()) {
Chris Lattner7b445c52005-10-11 18:30:57 +00001632 SCEVHandle Base = UsersToProcess.back().Base;
Dan Gohman2f09f512009-02-19 19:23:27 +00001633 Instruction *Inst = UsersToProcess.back().Inst;
Chris Lattnerbe3e5212005-08-03 23:30:08 +00001634
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001635 // Emit the code for Base into the preheader.
Dan Gohman2d1be872009-04-16 03:18:22 +00001636 Value *BaseV = 0;
1637 if (!Base->isZero()) {
1638 BaseV = PreheaderRewriter.expandCodeFor(Base, Base->getType(),
1639 PreInsertPt);
Chris Lattner7d8ed8a2007-05-11 22:40:34 +00001640
Dan Gohman2d1be872009-04-16 03:18:22 +00001641 DOUT << " INSERTING code for BASE = " << *Base << ":";
1642 if (BaseV->hasName())
1643 DOUT << " Result value name = %" << BaseV->getNameStr();
1644 DOUT << "\n";
Chris Lattner7d8ed8a2007-05-11 22:40:34 +00001645
Dan Gohman2d1be872009-04-16 03:18:22 +00001646 // If BaseV is a non-zero constant, make sure that it gets inserted into
1647 // the preheader, instead of being forward substituted into the uses. We
1648 // do this by forcing a BitCast (noop cast) to be inserted into the
1649 // preheader in this case.
1650 if (!fitsInAddressMode(Base, getAccessType(Inst), TLI, false)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001651 // We want this constant emitted into the preheader! This is just
1652 // using cast as a copy so BitCast (no-op cast) is appropriate
1653 BaseV = new BitCastInst(BaseV, BaseV->getType(), "preheaderinsert",
Dan Gohman4a9a3e52008-04-14 18:26:16 +00001654 PreInsertPt);
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001655 }
Chris Lattner7e79b382006-08-03 06:34:50 +00001656 }
1657
Nate Begeman16997482005-07-30 00:15:07 +00001658 // Emit the code to add the immediate offset to the Phi value, just before
Chris Lattner2351aba2005-08-03 22:51:21 +00001659 // the instructions that we identified as using this stride and base.
Chris Lattner7b445c52005-10-11 18:30:57 +00001660 do {
Chris Lattner7e79b382006-08-03 06:34:50 +00001661 // FIXME: Use emitted users to emit other users.
Chris Lattner7b445c52005-10-11 18:30:57 +00001662 BasedUser &User = UsersToProcess.back();
Jeff Cohend29b6aa2005-07-30 18:33:25 +00001663
Evan Cheng5792f512009-05-11 22:33:01 +00001664 DOUT << " Examining ";
1665 if (User.isUseOfPostIncrementedValue)
1666 DOUT << "postinc";
1667 else
1668 DOUT << "preinc";
1669 DOUT << " use ";
Dan Gohman4a359ea2009-02-19 19:32:06 +00001670 DEBUG(WriteAsOperand(*DOUT, UsersToProcess.back().OperandValToReplace,
1671 /*PrintType=*/false));
Dale Johannesen22523ad2009-04-29 22:57:20 +00001672 DOUT << " in Inst: " << *(User.Inst);
Dan Gohman2f09f512009-02-19 19:23:27 +00001673
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001674 // If this instruction wants to use the post-incremented value, move it
1675 // after the post-inc and use its value instead of the PHI.
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001676 Value *RewriteOp = User.Phi;
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001677 if (User.isUseOfPostIncrementedValue) {
Dan Gohman9d100862009-03-09 22:04:01 +00001678 RewriteOp = User.Phi->getIncomingValueForBlock(LatchBlock);
Chris Lattnerc6bae652005-09-12 06:04:47 +00001679 // If this user is in the loop, make sure it is the last thing in the
Evan Cheng5792f512009-05-11 22:33:01 +00001680 // loop to ensure it is dominated by the increment. In case it's the
1681 // only use of the iv, the increment instruction is already before the
1682 // use.
1683 if (L->contains(User.Inst->getParent()) && User.Inst != IVIncInsertPt)
1684 User.Inst->moveBefore(IVIncInsertPt);
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001685 }
Evan Cheng86c75d32006-06-09 00:12:42 +00001686
Dan Gohman246b2562007-10-22 18:31:58 +00001687 SCEVHandle RewriteExpr = SE->getUnknown(RewriteOp);
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001688
Dan Gohman81db61a2009-05-12 02:17:14 +00001689 if (SE->getEffectiveSCEVType(RewriteOp->getType()) !=
1690 SE->getEffectiveSCEVType(ReplacedTy)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001691 assert(SE->getTypeSizeInBits(RewriteOp->getType()) >
1692 SE->getTypeSizeInBits(ReplacedTy) &&
Dan Gohmane616bf32009-04-16 15:47:35 +00001693 "Unexpected widening cast!");
1694 RewriteExpr = SE->getTruncateExpr(RewriteExpr, ReplacedTy);
1695 }
1696
Dale Johannesenb0390622008-12-16 22:16:28 +00001697 // If we had to insert new instructions for RewriteOp, we have to
Dan Gohmanf20d70d2008-05-15 23:26:57 +00001698 // consider that they may not have been able to end up immediately
1699 // next to RewriteOp, because non-PHI instructions may never precede
1700 // PHI instructions in a block. In this case, remember where the last
Dan Gohmanca756ae2008-05-20 03:01:48 +00001701 // instruction was inserted so that if we're replacing a different
1702 // PHI node, we can use the later point to expand the final
1703 // RewriteExpr.
Dan Gohmanf20d70d2008-05-15 23:26:57 +00001704 Instruction *NewBasePt = dyn_cast<Instruction>(RewriteOp);
Dan Gohmanc17e0cf2009-02-20 04:17:46 +00001705 if (RewriteOp == User.Phi) NewBasePt = 0;
Dan Gohmanf20d70d2008-05-15 23:26:57 +00001706
Chris Lattner2351aba2005-08-03 22:51:21 +00001707 // Clear the SCEVExpander's expression map so that we are guaranteed
1708 // to have the code emitted where we expect it.
1709 Rewriter.clear();
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001710
1711 // If we are reusing the iv, then it must be multiplied by a constant
Dale Johannesen1de17d52009-02-09 22:14:15 +00001712 // factor to take advantage of the addressing mode scale component.
Dan Gohman2d1be872009-04-16 03:18:22 +00001713 if (!RewriteFactor->isZero()) {
Dale Johannesen2f46bb82009-01-14 02:35:31 +00001714 // If we're reusing an IV with a nonzero base (currently this happens
1715 // only when all reuses are outside the loop) subtract that base here.
1716 // The base has been used to initialize the PHI node but we don't want
1717 // it here.
Dale Johannesen1de17d52009-02-09 22:14:15 +00001718 if (!ReuseIV.Base->isZero()) {
1719 SCEVHandle typedBase = ReuseIV.Base;
Dan Gohman81db61a2009-05-12 02:17:14 +00001720 if (SE->getEffectiveSCEVType(RewriteExpr->getType()) !=
1721 SE->getEffectiveSCEVType(ReuseIV.Base->getType())) {
Dale Johannesen1de17d52009-02-09 22:14:15 +00001722 // It's possible the original IV is a larger type than the new IV,
1723 // in which case we have to truncate the Base. We checked in
1724 // RequiresTypeConversion that this is valid.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001725 assert(SE->getTypeSizeInBits(RewriteExpr->getType()) <
1726 SE->getTypeSizeInBits(ReuseIV.Base->getType()) &&
Dan Gohman84fc33e2009-04-16 22:35:57 +00001727 "Unexpected lengthening conversion!");
Dale Johannesen1de17d52009-02-09 22:14:15 +00001728 typedBase = SE->getTruncateExpr(ReuseIV.Base,
1729 RewriteExpr->getType());
1730 }
1731 RewriteExpr = SE->getMinusSCEV(RewriteExpr, typedBase);
1732 }
Dale Johannesen2f46bb82009-01-14 02:35:31 +00001733
1734 // Multiply old variable, with base removed, by new scale factor.
1735 RewriteExpr = SE->getMulExpr(RewriteFactor,
Evan Cheng83927722007-10-30 22:27:26 +00001736 RewriteExpr);
Evan Chengeb8f9e22006-03-17 19:52:23 +00001737
1738 // The common base is emitted in the loop preheader. But since we
1739 // are reusing an IV, it has not been used to initialize the PHI node.
1740 // Add it to the expression used to rewrite the uses.
Dale Johannesen2f46bb82009-01-14 02:35:31 +00001741 // When this use is outside the loop, we earlier subtracted the
1742 // common base, and are adding it back here. Use the same expression
1743 // as before, rather than CommonBaseV, so DAGCombiner will zap it.
Dan Gohman2d1be872009-04-16 03:18:22 +00001744 if (!CommonExprs->isZero()) {
Dale Johannesen2f46bb82009-01-14 02:35:31 +00001745 if (L->contains(User.Inst->getParent()))
1746 RewriteExpr = SE->getAddExpr(RewriteExpr,
Dale Johannesenb0390622008-12-16 22:16:28 +00001747 SE->getUnknown(CommonBaseV));
Dale Johannesen2f46bb82009-01-14 02:35:31 +00001748 else
1749 RewriteExpr = SE->getAddExpr(RewriteExpr, CommonExprs);
1750 }
Evan Chengeb8f9e22006-03-17 19:52:23 +00001751 }
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001752
Chris Lattner2114b272005-08-04 20:03:32 +00001753 // Now that we know what we need to do, insert code before User for the
1754 // immediate and any loop-variant expressions.
Dan Gohman2d1be872009-04-16 03:18:22 +00001755 if (BaseV)
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001756 // Add BaseV to the PHI value if needed.
Dan Gohman246b2562007-10-22 18:31:58 +00001757 RewriteExpr = SE->getAddExpr(RewriteExpr, SE->getUnknown(BaseV));
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001758
Dan Gohmanf20d70d2008-05-15 23:26:57 +00001759 User.RewriteInstructionToUseNewBase(RewriteExpr, NewBasePt,
1760 Rewriter, L, this,
Evan Cheng0e0014d2007-10-30 23:45:15 +00001761 DeadInsts);
Jeff Cohend29b6aa2005-07-30 18:33:25 +00001762
Chris Lattnera68d4ca2008-12-01 06:14:28 +00001763 // Mark old value we replaced as possibly dead, so that it is eliminated
Chris Lattner2351aba2005-08-03 22:51:21 +00001764 // if we just replaced the last use of that value.
Dan Gohman81db61a2009-05-12 02:17:14 +00001765 DeadInsts.push_back(User.OperandValToReplace);
Nate Begeman16997482005-07-30 00:15:07 +00001766
Chris Lattner7b445c52005-10-11 18:30:57 +00001767 UsersToProcess.pop_back();
Chris Lattner2351aba2005-08-03 22:51:21 +00001768 ++NumReduced;
Chris Lattner7b445c52005-10-11 18:30:57 +00001769
Chris Lattner7e79b382006-08-03 06:34:50 +00001770 // If there are any more users to process with the same base, process them
1771 // now. We sorted by base above, so we just have to check the last elt.
Chris Lattner7b445c52005-10-11 18:30:57 +00001772 } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
Nate Begeman16997482005-07-30 00:15:07 +00001773 // TODO: Next, find out which base index is the most common, pull it out.
1774 }
1775
1776 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1777 // different starting values, into different PHIs.
Nate Begeman16997482005-07-30 00:15:07 +00001778}
1779
Devang Patelc677de22008-08-13 20:31:11 +00001780/// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
Chris Lattneraed01d12007-04-03 05:11:24 +00001781/// set the IV user and stride information and return true, otherwise return
1782/// false.
Devang Patelc677de22008-08-13 20:31:11 +00001783bool LoopStrengthReduce::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse,
Chris Lattneraed01d12007-04-03 05:11:24 +00001784 const SCEVHandle *&CondStride) {
Dan Gohman81db61a2009-05-12 02:17:14 +00001785 for (unsigned Stride = 0, e = IU->StrideOrder.size();
1786 Stride != e && !CondUse; ++Stride) {
1787 std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
1788 IU->IVUsesByStride.find(IU->StrideOrder[Stride]);
1789 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
1790
1791 for (ilist<IVStrideUse>::iterator UI = SI->second->Users.begin(),
1792 E = SI->second->Users.end(); UI != E; ++UI)
1793 if (UI->getUser() == Cond) {
Chris Lattneraed01d12007-04-03 05:11:24 +00001794 // NOTE: we could handle setcc instructions with multiple uses here, but
1795 // InstCombine does it as well for simple uses, it's not clear that it
1796 // occurs enough in real life to handle.
Dan Gohman81db61a2009-05-12 02:17:14 +00001797 CondUse = UI;
Chris Lattneraed01d12007-04-03 05:11:24 +00001798 CondStride = &SI->first;
1799 return true;
1800 }
1801 }
1802 return false;
1803}
1804
Evan Chengcdf43b12007-10-25 09:11:16 +00001805namespace {
1806 // Constant strides come first which in turns are sorted by their absolute
1807 // values. If absolute values are the same, then positive strides comes first.
1808 // e.g.
1809 // 4, -1, X, 1, 2 ==> 1, -1, 2, 4, X
1810 struct StrideCompare {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001811 const ScalarEvolution *SE;
1812 explicit StrideCompare(const ScalarEvolution *se) : SE(se) {}
Dan Gohman2d1be872009-04-16 03:18:22 +00001813
Evan Chengcdf43b12007-10-25 09:11:16 +00001814 bool operator()(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Dan Gohman890f92b2009-04-18 17:56:28 +00001815 const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS);
1816 const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
Evan Chengcdf43b12007-10-25 09:11:16 +00001817 if (LHSC && RHSC) {
1818 int64_t LV = LHSC->getValue()->getSExtValue();
1819 int64_t RV = RHSC->getValue()->getSExtValue();
1820 uint64_t ALV = (LV < 0) ? -LV : LV;
1821 uint64_t ARV = (RV < 0) ? -RV : RV;
Dan Gohmanbc511722009-02-13 00:26:43 +00001822 if (ALV == ARV) {
1823 if (LV != RV)
1824 return LV > RV;
1825 } else {
Evan Chengcdf43b12007-10-25 09:11:16 +00001826 return ALV < ARV;
Dan Gohmanbc511722009-02-13 00:26:43 +00001827 }
1828
1829 // If it's the same value but different type, sort by bit width so
1830 // that we emit larger induction variables before smaller
1831 // ones, letting the smaller be re-written in terms of larger ones.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001832 return SE->getTypeSizeInBits(RHS->getType()) <
1833 SE->getTypeSizeInBits(LHS->getType());
Evan Chengcdf43b12007-10-25 09:11:16 +00001834 }
Dan Gohmanbc511722009-02-13 00:26:43 +00001835 return LHSC && !RHSC;
Evan Chengcdf43b12007-10-25 09:11:16 +00001836 }
1837 };
1838}
1839
1840/// ChangeCompareStride - If a loop termination compare instruction is the
1841/// only use of its stride, and the compaison is against a constant value,
1842/// try eliminate the stride by moving the compare instruction to another
1843/// stride and change its constant operand accordingly. e.g.
1844///
1845/// loop:
1846/// ...
1847/// v1 = v1 + 3
1848/// v2 = v2 + 1
1849/// if (v2 < 10) goto loop
1850/// =>
1851/// loop:
1852/// ...
1853/// v1 = v1 + 3
1854/// if (v1 < 30) goto loop
1855ICmpInst *LoopStrengthReduce::ChangeCompareStride(Loop *L, ICmpInst *Cond,
Evan Cheng0e0014d2007-10-30 23:45:15 +00001856 IVStrideUse* &CondUse,
Evan Chengcdf43b12007-10-25 09:11:16 +00001857 const SCEVHandle* &CondStride) {
Dan Gohman81db61a2009-05-12 02:17:14 +00001858 // If there's only one stride in the loop, there's nothing to do here.
1859 if (IU->StrideOrder.size() < 2)
Evan Chengcdf43b12007-10-25 09:11:16 +00001860 return Cond;
Dan Gohman81db61a2009-05-12 02:17:14 +00001861 // If there are other users of the condition's stride, don't bother
1862 // trying to change the condition because the stride will still
1863 // remain.
1864 std::map<SCEVHandle, IVUsersOfOneStride *>::iterator I =
1865 IU->IVUsesByStride.find(*CondStride);
1866 if (I == IU->IVUsesByStride.end() ||
1867 I->second->Users.size() != 1)
1868 return Cond;
1869 // Only handle constant strides for now.
Evan Chengcdf43b12007-10-25 09:11:16 +00001870 const SCEVConstant *SC = dyn_cast<SCEVConstant>(*CondStride);
1871 if (!SC) return Cond;
Evan Chengcdf43b12007-10-25 09:11:16 +00001872
1873 ICmpInst::Predicate Predicate = Cond->getPredicate();
Evan Chengcdf43b12007-10-25 09:11:16 +00001874 int64_t CmpSSInt = SC->getValue()->getSExtValue();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001875 unsigned BitWidth = SE->getTypeSizeInBits((*CondStride)->getType());
Evan Cheng168a66b2007-10-26 23:08:19 +00001876 uint64_t SignBit = 1ULL << (BitWidth-1);
Dan Gohmanc34fea32009-02-24 01:58:00 +00001877 const Type *CmpTy = Cond->getOperand(0)->getType();
Evan Cheng168a66b2007-10-26 23:08:19 +00001878 const Type *NewCmpTy = NULL;
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001879 unsigned TyBits = SE->getTypeSizeInBits(CmpTy);
Evan Chengaf62c092007-10-29 22:07:18 +00001880 unsigned NewTyBits = 0;
Evan Chengcdf43b12007-10-25 09:11:16 +00001881 SCEVHandle *NewStride = NULL;
Dan Gohmanff518c82009-02-20 21:27:23 +00001882 Value *NewCmpLHS = NULL;
1883 Value *NewCmpRHS = NULL;
Evan Chengcdf43b12007-10-25 09:11:16 +00001884 int64_t Scale = 1;
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001885 SCEVHandle NewOffset = SE->getIntegerSCEV(0, CmpTy);
Evan Chengcdf43b12007-10-25 09:11:16 +00001886
Dan Gohmanc34fea32009-02-24 01:58:00 +00001887 if (ConstantInt *C = dyn_cast<ConstantInt>(Cond->getOperand(1))) {
1888 int64_t CmpVal = C->getValue().getSExtValue();
Evan Cheng168a66b2007-10-26 23:08:19 +00001889
Dan Gohmanc34fea32009-02-24 01:58:00 +00001890 // Check stride constant and the comparision constant signs to detect
1891 // overflow.
1892 if ((CmpVal & SignBit) != (CmpSSInt & SignBit))
1893 return Cond;
Evan Cheng168a66b2007-10-26 23:08:19 +00001894
Dan Gohmanc34fea32009-02-24 01:58:00 +00001895 // Look for a suitable stride / iv as replacement.
Dan Gohman81db61a2009-05-12 02:17:14 +00001896 for (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
1897 std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
1898 IU->IVUsesByStride.find(IU->StrideOrder[i]);
Dan Gohmanc34fea32009-02-24 01:58:00 +00001899 if (!isa<SCEVConstant>(SI->first))
Dan Gohmanff518c82009-02-20 21:27:23 +00001900 continue;
Dan Gohmanc34fea32009-02-24 01:58:00 +00001901 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
Dan Gohmanc7749b72009-04-27 20:35:32 +00001902 if (SSInt == CmpSSInt ||
Dale Johannesen7b9486a2009-05-13 00:24:22 +00001903 abs64(SSInt) < abs64(CmpSSInt) ||
Dan Gohmanc7749b72009-04-27 20:35:32 +00001904 (SSInt % CmpSSInt) != 0)
Dan Gohmanc34fea32009-02-24 01:58:00 +00001905 continue;
1906
1907 Scale = SSInt / CmpSSInt;
1908 int64_t NewCmpVal = CmpVal * Scale;
David Greenee19c8402009-05-06 17:39:26 +00001909 APInt Mul = APInt(BitWidth*2, CmpVal, true);
1910 Mul = Mul * APInt(BitWidth*2, Scale, true);
Dan Gohmanc34fea32009-02-24 01:58:00 +00001911 // Check for overflow.
Evan Chengee08da82009-05-06 18:00:56 +00001912 if (!Mul.isSignedIntN(BitWidth))
Dan Gohmanc34fea32009-02-24 01:58:00 +00001913 continue;
Dan Gohman81db61a2009-05-12 02:17:14 +00001914 // Check for overflow in the stride's type too.
1915 if (!Mul.isSignedIntN(SE->getTypeSizeInBits(SI->first->getType())))
1916 continue;
Dan Gohmanc34fea32009-02-24 01:58:00 +00001917
1918 // Watch out for overflow.
1919 if (ICmpInst::isSignedPredicate(Predicate) &&
1920 (CmpVal & SignBit) != (NewCmpVal & SignBit))
1921 continue;
1922
1923 if (NewCmpVal == CmpVal)
1924 continue;
1925 // Pick the best iv to use trying to avoid a cast.
1926 NewCmpLHS = NULL;
Dan Gohman81db61a2009-05-12 02:17:14 +00001927 for (ilist<IVStrideUse>::iterator UI = SI->second->Users.begin(),
1928 E = SI->second->Users.end(); UI != E; ++UI) {
1929 Value *Op = UI->getOperandValToReplace();
1930
1931 // If the IVStrideUse implies a cast, check for an actual cast which
1932 // can be used to find the original IV expression.
1933 if (SE->getEffectiveSCEVType(Op->getType()) !=
1934 SE->getEffectiveSCEVType(SI->first->getType())) {
1935 CastInst *CI = dyn_cast<CastInst>(Op);
1936 // If it's not a simple cast, it's complicated.
1937 if (!CI)
1938 continue;
1939 // If it's a cast from a type other than the stride type,
1940 // it's complicated.
1941 if (CI->getOperand(0)->getType() != SI->first->getType())
1942 continue;
1943 // Ok, we found the IV expression in the stride's type.
1944 Op = CI->getOperand(0);
1945 }
1946
1947 NewCmpLHS = Op;
Dan Gohmanc34fea32009-02-24 01:58:00 +00001948 if (NewCmpLHS->getType() == CmpTy)
1949 break;
1950 }
1951 if (!NewCmpLHS)
1952 continue;
1953
1954 NewCmpTy = NewCmpLHS->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001955 NewTyBits = SE->getTypeSizeInBits(NewCmpTy);
1956 const Type *NewCmpIntTy = IntegerType::get(NewTyBits);
Dan Gohmanc34fea32009-02-24 01:58:00 +00001957 if (RequiresTypeConversion(NewCmpTy, CmpTy)) {
1958 // Check if it is possible to rewrite it using
1959 // an iv / stride of a smaller integer type.
Dan Gohman65e05b62009-04-16 16:49:48 +00001960 unsigned Bits = NewTyBits;
1961 if (ICmpInst::isSignedPredicate(Predicate))
1962 --Bits;
1963 uint64_t Mask = (1ULL << Bits) - 1;
1964 if (((uint64_t)NewCmpVal & Mask) != (uint64_t)NewCmpVal)
Dan Gohmanc34fea32009-02-24 01:58:00 +00001965 continue;
1966 }
1967
1968 // Don't rewrite if use offset is non-constant and the new type is
1969 // of a different type.
1970 // FIXME: too conservative?
Dan Gohman81db61a2009-05-12 02:17:14 +00001971 if (NewTyBits != TyBits && !isa<SCEVConstant>(CondUse->getOffset()))
Dan Gohmanc34fea32009-02-24 01:58:00 +00001972 continue;
1973
1974 bool AllUsesAreAddresses = true;
1975 bool AllUsesAreOutsideLoop = true;
1976 std::vector<BasedUser> UsersToProcess;
Dan Gohman81db61a2009-05-12 02:17:14 +00001977 SCEVHandle CommonExprs = CollectIVUsers(SI->first, *SI->second, L,
Dan Gohmanc34fea32009-02-24 01:58:00 +00001978 AllUsesAreAddresses,
1979 AllUsesAreOutsideLoop,
1980 UsersToProcess);
1981 // Avoid rewriting the compare instruction with an iv of new stride
1982 // if it's likely the new stride uses will be rewritten using the
1983 // stride of the compare instruction.
1984 if (AllUsesAreAddresses &&
Evan Cheng5792f512009-05-11 22:33:01 +00001985 ValidScale(!CommonExprs->isZero(), Scale, UsersToProcess))
Dan Gohmanc34fea32009-02-24 01:58:00 +00001986 continue;
1987
1988 // If scale is negative, use swapped predicate unless it's testing
1989 // for equality.
1990 if (Scale < 0 && !Cond->isEquality())
1991 Predicate = ICmpInst::getSwappedPredicate(Predicate);
1992
Dan Gohman81db61a2009-05-12 02:17:14 +00001993 NewStride = &IU->StrideOrder[i];
Dan Gohmanc34fea32009-02-24 01:58:00 +00001994 if (!isa<PointerType>(NewCmpTy))
1995 NewCmpRHS = ConstantInt::get(NewCmpTy, NewCmpVal);
1996 else {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001997 ConstantInt *CI = ConstantInt::get(NewCmpIntTy, NewCmpVal);
Dan Gohman798d3922009-04-16 15:48:38 +00001998 NewCmpRHS = ConstantExpr::getIntToPtr(CI, NewCmpTy);
Dan Gohmanc34fea32009-02-24 01:58:00 +00001999 }
2000 NewOffset = TyBits == NewTyBits
Dan Gohman81db61a2009-05-12 02:17:14 +00002001 ? SE->getMulExpr(CondUse->getOffset(),
Dan Gohmanc34fea32009-02-24 01:58:00 +00002002 SE->getConstant(ConstantInt::get(CmpTy, Scale)))
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002003 : SE->getConstant(ConstantInt::get(NewCmpIntTy,
Dan Gohman81db61a2009-05-12 02:17:14 +00002004 cast<SCEVConstant>(CondUse->getOffset())->getValue()
2005 ->getSExtValue()*Scale));
Dan Gohmanc34fea32009-02-24 01:58:00 +00002006 break;
Dan Gohmanff518c82009-02-20 21:27:23 +00002007 }
Evan Chengcdf43b12007-10-25 09:11:16 +00002008 }
2009
Dan Gohman9b93dd12008-06-16 22:34:15 +00002010 // Forgo this transformation if it the increment happens to be
2011 // unfortunately positioned after the condition, and the condition
2012 // has multiple uses which prevent it from being moved immediately
2013 // before the branch. See
2014 // test/Transforms/LoopStrengthReduce/change-compare-stride-trickiness-*.ll
2015 // for an example of this situation.
Devang Pateld16aba22008-08-13 02:05:14 +00002016 if (!Cond->hasOneUse()) {
Dan Gohman9b93dd12008-06-16 22:34:15 +00002017 for (BasicBlock::iterator I = Cond, E = Cond->getParent()->end();
2018 I != E; ++I)
Dan Gohmanff518c82009-02-20 21:27:23 +00002019 if (I == NewCmpLHS)
Dan Gohman9b93dd12008-06-16 22:34:15 +00002020 return Cond;
Devang Pateld16aba22008-08-13 02:05:14 +00002021 }
Dan Gohman9b93dd12008-06-16 22:34:15 +00002022
Dan Gohmanff518c82009-02-20 21:27:23 +00002023 if (NewCmpRHS) {
Evan Chengcdf43b12007-10-25 09:11:16 +00002024 // Create a new compare instruction using new stride / iv.
2025 ICmpInst *OldCond = Cond;
Evan Cheng168a66b2007-10-26 23:08:19 +00002026 // Insert new compare instruction.
Dan Gohmanff518c82009-02-20 21:27:23 +00002027 Cond = new ICmpInst(Predicate, NewCmpLHS, NewCmpRHS,
Dan Gohmane562b172008-06-13 21:43:41 +00002028 L->getHeader()->getName() + ".termcond",
2029 OldCond);
Evan Cheng168a66b2007-10-26 23:08:19 +00002030
2031 // Remove the old compare instruction. The old indvar is probably dead too.
Dan Gohman81db61a2009-05-12 02:17:14 +00002032 DeadInsts.push_back(CondUse->getOperandValToReplace());
Dan Gohman010ee2d2008-05-21 00:54:12 +00002033 OldCond->replaceAllUsesWith(Cond);
Evan Chengcdf43b12007-10-25 09:11:16 +00002034 OldCond->eraseFromParent();
Evan Cheng168a66b2007-10-26 23:08:19 +00002035
Dan Gohman81db61a2009-05-12 02:17:14 +00002036 IU->IVUsesByStride[*NewStride]->addUser(NewOffset, Cond, NewCmpLHS, false);
2037 CondUse = &IU->IVUsesByStride[*NewStride]->Users.back();
Evan Chengcdf43b12007-10-25 09:11:16 +00002038 CondStride = NewStride;
2039 ++NumEliminated;
Dan Gohmanafc36a92009-05-02 18:29:22 +00002040 Changed = true;
Evan Chengcdf43b12007-10-25 09:11:16 +00002041 }
2042
2043 return Cond;
2044}
2045
Dan Gohmanad7321f2008-09-15 21:22:06 +00002046/// OptimizeSMax - Rewrite the loop's terminating condition if it uses
2047/// an smax computation.
2048///
2049/// This is a narrow solution to a specific, but acute, problem. For loops
2050/// like this:
2051///
2052/// i = 0;
2053/// do {
2054/// p[i] = 0.0;
2055/// } while (++i < n);
2056///
2057/// where the comparison is signed, the trip count isn't just 'n', because
2058/// 'n' could be negative. And unfortunately this can come up even for loops
2059/// where the user didn't use a C do-while loop. For example, seemingly
2060/// well-behaved top-test loops will commonly be lowered like this:
2061//
2062/// if (n > 0) {
2063/// i = 0;
2064/// do {
2065/// p[i] = 0.0;
2066/// } while (++i < n);
2067/// }
2068///
2069/// and then it's possible for subsequent optimization to obscure the if
2070/// test in such a way that indvars can't find it.
2071///
2072/// When indvars can't find the if test in loops like this, it creates a
2073/// signed-max expression, which allows it to give the loop a canonical
2074/// induction variable:
2075///
2076/// i = 0;
2077/// smax = n < 1 ? 1 : n;
2078/// do {
2079/// p[i] = 0.0;
2080/// } while (++i != smax);
2081///
2082/// Canonical induction variables are necessary because the loop passes
2083/// are designed around them. The most obvious example of this is the
2084/// LoopInfo analysis, which doesn't remember trip count values. It
2085/// expects to be able to rediscover the trip count each time it is
2086/// needed, and it does this using a simple analyis that only succeeds if
2087/// the loop has a canonical induction variable.
2088///
2089/// However, when it comes time to generate code, the maximum operation
2090/// can be quite costly, especially if it's inside of an outer loop.
2091///
2092/// This function solves this problem by detecting this type of loop and
2093/// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
2094/// the instructions for the maximum computation.
2095///
2096ICmpInst *LoopStrengthReduce::OptimizeSMax(Loop *L, ICmpInst *Cond,
2097 IVStrideUse* &CondUse) {
2098 // Check that the loop matches the pattern we're looking for.
2099 if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
2100 Cond->getPredicate() != CmpInst::ICMP_NE)
2101 return Cond;
2102
2103 SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
2104 if (!Sel || !Sel->hasOneUse()) return Cond;
2105
Dan Gohman46bdfb02009-02-24 18:55:53 +00002106 SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2107 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
Dan Gohmanad7321f2008-09-15 21:22:06 +00002108 return Cond;
Dan Gohman46bdfb02009-02-24 18:55:53 +00002109 SCEVHandle One = SE->getIntegerSCEV(1, BackedgeTakenCount->getType());
Dan Gohmanad7321f2008-09-15 21:22:06 +00002110
Dan Gohman46bdfb02009-02-24 18:55:53 +00002111 // Add one to the backedge-taken count to get the trip count.
2112 SCEVHandle IterationCount = SE->getAddExpr(BackedgeTakenCount, One);
Dan Gohmanad7321f2008-09-15 21:22:06 +00002113
2114 // Check for a max calculation that matches the pattern.
Dan Gohman35738ac2009-05-04 22:30:44 +00002115 const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(IterationCount);
Dan Gohmanad7321f2008-09-15 21:22:06 +00002116 if (!SMax || SMax != SE->getSCEV(Sel)) return Cond;
2117
2118 SCEVHandle SMaxLHS = SMax->getOperand(0);
2119 SCEVHandle SMaxRHS = SMax->getOperand(1);
2120 if (!SMaxLHS || SMaxLHS != One) return Cond;
2121
2122 // Check the relevant induction variable for conformance to
2123 // the pattern.
2124 SCEVHandle IV = SE->getSCEV(Cond->getOperand(0));
Dan Gohman890f92b2009-04-18 17:56:28 +00002125 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
Dan Gohmanad7321f2008-09-15 21:22:06 +00002126 if (!AR || !AR->isAffine() ||
2127 AR->getStart() != One ||
2128 AR->getStepRecurrence(*SE) != One)
2129 return Cond;
2130
Dan Gohmanbc10b8c2009-03-04 20:49:01 +00002131 assert(AR->getLoop() == L &&
2132 "Loop condition operand is an addrec in a different loop!");
2133
Dan Gohmanad7321f2008-09-15 21:22:06 +00002134 // Check the right operand of the select, and remember it, as it will
2135 // be used in the new comparison instruction.
2136 Value *NewRHS = 0;
2137 if (SE->getSCEV(Sel->getOperand(1)) == SMaxRHS)
2138 NewRHS = Sel->getOperand(1);
2139 else if (SE->getSCEV(Sel->getOperand(2)) == SMaxRHS)
2140 NewRHS = Sel->getOperand(2);
2141 if (!NewRHS) return Cond;
2142
2143 // Ok, everything looks ok to change the condition into an SLT or SGE and
2144 // delete the max calculation.
2145 ICmpInst *NewCond =
2146 new ICmpInst(Cond->getPredicate() == CmpInst::ICMP_NE ?
2147 CmpInst::ICMP_SLT :
2148 CmpInst::ICMP_SGE,
2149 Cond->getOperand(0), NewRHS, "scmp", Cond);
2150
2151 // Delete the max calculation instructions.
2152 Cond->replaceAllUsesWith(NewCond);
Dan Gohman81db61a2009-05-12 02:17:14 +00002153 CondUse->setUser(NewCond);
Dan Gohmanad7321f2008-09-15 21:22:06 +00002154 Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
Dan Gohman81db61a2009-05-12 02:17:14 +00002155 Cond->eraseFromParent();
Dan Gohman586b7b72008-10-01 02:02:03 +00002156 Sel->eraseFromParent();
Dan Gohman35738ac2009-05-04 22:30:44 +00002157 if (Cmp->use_empty())
Dan Gohman586b7b72008-10-01 02:02:03 +00002158 Cmp->eraseFromParent();
Dan Gohmanad7321f2008-09-15 21:22:06 +00002159 return NewCond;
2160}
2161
Devang Patela0b39092008-08-26 17:57:54 +00002162/// OptimizeShadowIV - If IV is used in a int-to-float cast
2163/// inside the loop then try to eliminate the cast opeation.
2164void LoopStrengthReduce::OptimizeShadowIV(Loop *L) {
2165
Dan Gohman46bdfb02009-02-24 18:55:53 +00002166 SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2167 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
Devang Patela0b39092008-08-26 17:57:54 +00002168 return;
2169
Dan Gohman81db61a2009-05-12 02:17:14 +00002170 for (unsigned Stride = 0, e = IU->StrideOrder.size(); Stride != e;
Devang Patela0b39092008-08-26 17:57:54 +00002171 ++Stride) {
Dan Gohman81db61a2009-05-12 02:17:14 +00002172 std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
2173 IU->IVUsesByStride.find(IU->StrideOrder[Stride]);
2174 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
Devang Patela0b39092008-08-26 17:57:54 +00002175 if (!isa<SCEVConstant>(SI->first))
2176 continue;
2177
Dan Gohman81db61a2009-05-12 02:17:14 +00002178 for (ilist<IVStrideUse>::iterator UI = SI->second->Users.begin(),
2179 E = SI->second->Users.end(); UI != E; /* empty */) {
2180 ilist<IVStrideUse>::iterator CandidateUI = UI;
Devang Patel54153272008-08-27 17:50:18 +00002181 ++UI;
Dan Gohman81db61a2009-05-12 02:17:14 +00002182 Instruction *ShadowUse = CandidateUI->getUser();
Devang Patela0b39092008-08-26 17:57:54 +00002183 const Type *DestTy = NULL;
2184
2185 /* If shadow use is a int->float cast then insert a second IV
Devang Patel54153272008-08-27 17:50:18 +00002186 to eliminate this cast.
Devang Patela0b39092008-08-26 17:57:54 +00002187
2188 for (unsigned i = 0; i < n; ++i)
2189 foo((double)i);
2190
Devang Patel54153272008-08-27 17:50:18 +00002191 is transformed into
Devang Patela0b39092008-08-26 17:57:54 +00002192
2193 double d = 0.0;
2194 for (unsigned i = 0; i < n; ++i, ++d)
2195 foo(d);
2196 */
Dan Gohman81db61a2009-05-12 02:17:14 +00002197 if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser()))
Devang Patela0b39092008-08-26 17:57:54 +00002198 DestTy = UCast->getDestTy();
Dan Gohman81db61a2009-05-12 02:17:14 +00002199 else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser()))
Devang Patela0b39092008-08-26 17:57:54 +00002200 DestTy = SCast->getDestTy();
Devang Patel18bb2782008-08-27 20:55:23 +00002201 if (!DestTy) continue;
2202
2203 if (TLI) {
Evan Cheng5792f512009-05-11 22:33:01 +00002204 // If target does not support DestTy natively then do not apply
2205 // this transformation.
Devang Patel18bb2782008-08-27 20:55:23 +00002206 MVT DVT = TLI->getValueType(DestTy);
2207 if (!TLI->isTypeLegal(DVT)) continue;
2208 }
2209
Devang Patela0b39092008-08-26 17:57:54 +00002210 PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
2211 if (!PH) continue;
2212 if (PH->getNumIncomingValues() != 2) continue;
2213
2214 const Type *SrcTy = PH->getType();
2215 int Mantissa = DestTy->getFPMantissaWidth();
2216 if (Mantissa == -1) continue;
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002217 if ((int)SE->getTypeSizeInBits(SrcTy) > Mantissa)
Devang Patela0b39092008-08-26 17:57:54 +00002218 continue;
2219
2220 unsigned Entry, Latch;
2221 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
2222 Entry = 0;
2223 Latch = 1;
2224 } else {
2225 Entry = 1;
2226 Latch = 0;
2227 }
2228
2229 ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
2230 if (!Init) continue;
2231 ConstantFP *NewInit = ConstantFP::get(DestTy, Init->getZExtValue());
2232
2233 BinaryOperator *Incr =
2234 dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
2235 if (!Incr) continue;
2236 if (Incr->getOpcode() != Instruction::Add
2237 && Incr->getOpcode() != Instruction::Sub)
2238 continue;
2239
2240 /* Initialize new IV, double d = 0.0 in above example. */
2241 ConstantInt *C = NULL;
2242 if (Incr->getOperand(0) == PH)
2243 C = dyn_cast<ConstantInt>(Incr->getOperand(1));
2244 else if (Incr->getOperand(1) == PH)
2245 C = dyn_cast<ConstantInt>(Incr->getOperand(0));
2246 else
2247 continue;
2248
2249 if (!C) continue;
2250
2251 /* Add new PHINode. */
2252 PHINode *NewPH = PHINode::Create(DestTy, "IV.S.", PH);
2253
Devang Patel54153272008-08-27 17:50:18 +00002254 /* create new increment. '++d' in above example. */
Devang Patela0b39092008-08-26 17:57:54 +00002255 ConstantFP *CFP = ConstantFP::get(DestTy, C->getZExtValue());
2256 BinaryOperator *NewIncr =
2257 BinaryOperator::Create(Incr->getOpcode(),
2258 NewPH, CFP, "IV.S.next.", Incr);
2259
2260 NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
2261 NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
2262
2263 /* Remove cast operation */
Devang Patela0b39092008-08-26 17:57:54 +00002264 ShadowUse->replaceAllUsesWith(NewPH);
2265 ShadowUse->eraseFromParent();
Devang Patela0b39092008-08-26 17:57:54 +00002266 NumShadow++;
2267 break;
2268 }
2269 }
2270}
2271
Chris Lattner010de252005-08-08 05:28:22 +00002272// OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
2273// uses in the loop, look to see if we can eliminate some, in favor of using
2274// common indvars for the different uses.
2275void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
2276 // TODO: implement optzns here.
2277
Devang Patela0b39092008-08-26 17:57:54 +00002278 OptimizeShadowIV(L);
Evan Cheng2d850522009-05-09 01:08:24 +00002279}
2280
2281/// OptimizeLoopTermCond - Change loop terminating condition to use the
2282/// postinc iv when possible.
2283void LoopStrengthReduce::OptimizeLoopTermCond(Loop *L) {
Chris Lattner010de252005-08-08 05:28:22 +00002284 // Finally, get the terminating condition for the loop if possible. If we
2285 // can, we want to change it to use a post-incremented version of its
Chris Lattner98d98112006-03-24 07:14:34 +00002286 // induction variable, to allow coalescing the live ranges for the IV into
Chris Lattner010de252005-08-08 05:28:22 +00002287 // one register value.
Evan Cheng5792f512009-05-11 22:33:01 +00002288 BasicBlock *LatchBlock = L->getLoopLatch();
2289 BasicBlock *ExitBlock = L->getExitingBlock();
2290 if (!ExitBlock)
2291 // Multiple exits, just look at the exit in the latch block if there is one.
2292 ExitBlock = LatchBlock;
2293 BranchInst *TermBr = dyn_cast<BranchInst>(ExitBlock->getTerminator());
2294 if (!TermBr)
Chris Lattner010de252005-08-08 05:28:22 +00002295 return;
Evan Cheng5792f512009-05-11 22:33:01 +00002296 if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
2297 return;
Chris Lattner010de252005-08-08 05:28:22 +00002298
2299 // Search IVUsesByStride to find Cond's IVUse if there is one.
2300 IVStrideUse *CondUse = 0;
Chris Lattner50fad702005-08-10 00:45:21 +00002301 const SCEVHandle *CondStride = 0;
Evan Cheng5792f512009-05-11 22:33:01 +00002302 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
Devang Patelc677de22008-08-13 20:31:11 +00002303 if (!FindIVUserForCond(Cond, CondUse, CondStride))
Chris Lattneraed01d12007-04-03 05:11:24 +00002304 return; // setcc doesn't use the IV.
Evan Chengcdf43b12007-10-25 09:11:16 +00002305
Evan Cheng5792f512009-05-11 22:33:01 +00002306 if (ExitBlock != LatchBlock) {
2307 if (!Cond->hasOneUse())
2308 // See below, we don't want the condition to be cloned.
2309 return;
2310
2311 // If exiting block is the latch block, we know it's safe and profitable to
2312 // transform the icmp to use post-inc iv. Otherwise do so only if it would
2313 // not reuse another iv and its iv would be reused by other uses. We are
2314 // optimizing for the case where the icmp is the only use of the iv.
Dan Gohman81db61a2009-05-12 02:17:14 +00002315 IVUsersOfOneStride &StrideUses = *IU->IVUsesByStride[*CondStride];
2316 for (ilist<IVStrideUse>::iterator I = StrideUses.Users.begin(),
2317 E = StrideUses.Users.end(); I != E; ++I) {
2318 if (I->getUser() == Cond)
Evan Cheng5792f512009-05-11 22:33:01 +00002319 continue;
Dan Gohman81db61a2009-05-12 02:17:14 +00002320 if (!I->isUseOfPostIncrementedValue())
Evan Cheng5792f512009-05-11 22:33:01 +00002321 return;
2322 }
2323
2324 // FIXME: This is expensive, and worse still ChangeCompareStride does a
2325 // similar check. Can we perform all the icmp related transformations after
2326 // StrengthReduceStridedIVUsers?
2327 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(*CondStride)) {
2328 int64_t SInt = SC->getValue()->getSExtValue();
Dan Gohman81db61a2009-05-12 02:17:14 +00002329 for (unsigned NewStride = 0, ee = IU->StrideOrder.size(); NewStride != ee;
Evan Cheng5792f512009-05-11 22:33:01 +00002330 ++NewStride) {
Dan Gohman81db61a2009-05-12 02:17:14 +00002331 std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
2332 IU->IVUsesByStride.find(IU->StrideOrder[NewStride]);
Evan Cheng5792f512009-05-11 22:33:01 +00002333 if (!isa<SCEVConstant>(SI->first) || SI->first == *CondStride)
2334 continue;
2335 int64_t SSInt =
2336 cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
2337 if (SSInt == SInt)
2338 return; // This can definitely be reused.
Dale Johannesen7b9486a2009-05-13 00:24:22 +00002339 if (unsigned(abs64(SSInt)) < SInt || (SSInt % SInt) != 0)
Evan Cheng5792f512009-05-11 22:33:01 +00002340 continue;
2341 int64_t Scale = SSInt / SInt;
2342 bool AllUsesAreAddresses = true;
2343 bool AllUsesAreOutsideLoop = true;
2344 std::vector<BasedUser> UsersToProcess;
Dan Gohman81db61a2009-05-12 02:17:14 +00002345 SCEVHandle CommonExprs = CollectIVUsers(SI->first, *SI->second, L,
Evan Cheng5792f512009-05-11 22:33:01 +00002346 AllUsesAreAddresses,
2347 AllUsesAreOutsideLoop,
2348 UsersToProcess);
2349 // Avoid rewriting the compare instruction with an iv of new stride
2350 // if it's likely the new stride uses will be rewritten using the
2351 // stride of the compare instruction.
2352 if (AllUsesAreAddresses &&
2353 ValidScale(!CommonExprs->isZero(), Scale, UsersToProcess))
2354 return;
2355 }
2356 }
2357
2358 StrideNoReuse.insert(*CondStride);
2359 }
2360
Dan Gohmanad7321f2008-09-15 21:22:06 +00002361 // If the trip count is computed in terms of an smax (due to ScalarEvolution
2362 // being unable to find a sufficient guard, for example), change the loop
2363 // comparison to use SLT instead of NE.
2364 Cond = OptimizeSMax(L, Cond, CondUse);
2365
Evan Chengcdf43b12007-10-25 09:11:16 +00002366 // If possible, change stride and operands of the compare instruction to
2367 // eliminate one stride.
Evan Cheng5792f512009-05-11 22:33:01 +00002368 if (ExitBlock == LatchBlock)
2369 Cond = ChangeCompareStride(L, Cond, CondUse, CondStride);
Chris Lattner010de252005-08-08 05:28:22 +00002370
Chris Lattner010de252005-08-08 05:28:22 +00002371 // It's possible for the setcc instruction to be anywhere in the loop, and
2372 // possible for it to have multiple users. If it is not immediately before
2373 // the latch block branch, move it.
2374 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
2375 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
2376 Cond->moveBefore(TermBr);
2377 } else {
2378 // Otherwise, clone the terminating condition and insert into the loopend.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002379 Cond = cast<ICmpInst>(Cond->clone());
Chris Lattner010de252005-08-08 05:28:22 +00002380 Cond->setName(L->getHeader()->getName() + ".termcond");
2381 LatchBlock->getInstList().insert(TermBr, Cond);
2382
2383 // Clone the IVUse, as the old use still exists!
Dan Gohman81db61a2009-05-12 02:17:14 +00002384 IU->IVUsesByStride[*CondStride]->addUser(CondUse->getOffset(), Cond,
2385 CondUse->getOperandValToReplace(),
2386 false);
2387 CondUse = &IU->IVUsesByStride[*CondStride]->Users.back();
Chris Lattner010de252005-08-08 05:28:22 +00002388 }
2389 }
2390
2391 // If we get to here, we know that we can transform the setcc instruction to
Chris Lattner98d98112006-03-24 07:14:34 +00002392 // use the post-incremented version of the IV, allowing us to coalesce the
Chris Lattner010de252005-08-08 05:28:22 +00002393 // live ranges for the IV correctly.
Dan Gohman81db61a2009-05-12 02:17:14 +00002394 CondUse->setOffset(SE->getMinusSCEV(CondUse->getOffset(), *CondStride));
2395 CondUse->setIsUseOfPostIncrementedValue(true);
Evan Cheng1ce75dc2008-07-07 19:51:32 +00002396 Changed = true;
Evan Cheng5792f512009-05-11 22:33:01 +00002397
2398 ++NumLoopCond;
Chris Lattner010de252005-08-08 05:28:22 +00002399}
Nate Begeman16997482005-07-30 00:15:07 +00002400
Dale Johannesenc1acc3f2009-05-11 17:15:42 +00002401// OptimizeLoopCountIV - If, after all sharing of IVs, the IV used for deciding
2402// when to exit the loop is used only for that purpose, try to rearrange things
2403// so it counts down to a test against zero.
2404void LoopStrengthReduce::OptimizeLoopCountIV(Loop *L) {
2405
2406 // If the number of times the loop is executed isn't computable, give up.
2407 SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2408 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2409 return;
2410
2411 // Get the terminating condition for the loop if possible (this isn't
2412 // necessarily in the latch, or a block that's a predecessor of the header).
2413 SmallVector<BasicBlock*, 8> ExitBlocks;
2414 L->getExitBlocks(ExitBlocks);
2415 if (ExitBlocks.size() != 1) return;
2416
2417 // Okay, there is one exit block. Try to find the condition that causes the
2418 // loop to be exited.
2419 BasicBlock *ExitBlock = ExitBlocks[0];
2420
2421 BasicBlock *ExitingBlock = 0;
2422 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
2423 PI != E; ++PI)
2424 if (L->contains(*PI)) {
2425 if (ExitingBlock == 0)
2426 ExitingBlock = *PI;
2427 else
2428 return; // More than one block exiting!
2429 }
2430 assert(ExitingBlock && "No exits from loop, something is broken!");
2431
2432 // Okay, we've computed the exiting block. See what condition causes us to
2433 // exit.
2434 //
2435 // FIXME: we should be able to handle switch instructions (with a single exit)
2436 BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2437 if (TermBr == 0) return;
2438 assert(TermBr->isConditional() && "If unconditional, it can't be in loop!");
2439 if (!isa<ICmpInst>(TermBr->getCondition()))
2440 return;
2441 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
2442
2443 // Handle only tests for equality for the moment, and only stride 1.
2444 if (Cond->getPredicate() != CmpInst::ICMP_EQ)
2445 return;
2446 SCEVHandle IV = SE->getSCEV(Cond->getOperand(0));
2447 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
2448 SCEVHandle One = SE->getIntegerSCEV(1, BackedgeTakenCount->getType());
2449 if (!AR || !AR->isAffine() || AR->getStepRecurrence(*SE) != One)
2450 return;
2451
2452 // Make sure the IV is only used for counting. Value may be preinc or
2453 // postinc; 2 uses in either case.
2454 if (!Cond->getOperand(0)->hasNUses(2))
2455 return;
2456 PHINode *phi = dyn_cast<PHINode>(Cond->getOperand(0));
2457 Instruction *incr;
2458 if (phi && phi->getParent()==L->getHeader()) {
2459 // value tested is preinc. Find the increment.
2460 // A CmpInst is not a BinaryOperator; we depend on this.
2461 Instruction::use_iterator UI = phi->use_begin();
2462 incr = dyn_cast<BinaryOperator>(UI);
2463 if (!incr)
2464 incr = dyn_cast<BinaryOperator>(++UI);
2465 // 1 use for postinc value, the phi. Unnecessarily conservative?
2466 if (!incr || !incr->hasOneUse() || incr->getOpcode()!=Instruction::Add)
2467 return;
2468 } else {
2469 // Value tested is postinc. Find the phi node.
2470 incr = dyn_cast<BinaryOperator>(Cond->getOperand(0));
2471 if (!incr || incr->getOpcode()!=Instruction::Add)
2472 return;
2473
2474 Instruction::use_iterator UI = Cond->getOperand(0)->use_begin();
2475 phi = dyn_cast<PHINode>(UI);
2476 if (!phi)
2477 phi = dyn_cast<PHINode>(++UI);
2478 // 1 use for preinc value, the increment.
2479 if (!phi || phi->getParent()!=L->getHeader() || !phi->hasOneUse())
2480 return;
2481 }
2482
2483 // Replace the increment with a decrement.
2484 BinaryOperator *decr =
2485 BinaryOperator::Create(Instruction::Sub, incr->getOperand(0),
2486 incr->getOperand(1), "tmp", incr);
2487 incr->replaceAllUsesWith(decr);
2488 incr->eraseFromParent();
2489
2490 // Substitute endval-startval for the original startval, and 0 for the
2491 // original endval. Since we're only testing for equality this is OK even
2492 // if the computation wraps around.
2493 BasicBlock *Preheader = L->getLoopPreheader();
2494 Instruction *PreInsertPt = Preheader->getTerminator();
2495 int inBlock = L->contains(phi->getIncomingBlock(0)) ? 1 : 0;
2496 Value *startVal = phi->getIncomingValue(inBlock);
2497 Value *endVal = Cond->getOperand(1);
2498 // FIXME check for case where both are constant
2499 ConstantInt* Zero = ConstantInt::get(Cond->getOperand(1)->getType(), 0);
2500 BinaryOperator *NewStartVal =
2501 BinaryOperator::Create(Instruction::Sub, endVal, startVal,
2502 "tmp", PreInsertPt);
2503 phi->setIncomingValue(inBlock, NewStartVal);
2504 Cond->setOperand(1, Zero);
2505
2506 Changed = true;
2507}
2508
Devang Patel0f54dcb2007-03-06 21:14:09 +00002509bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager &LPM) {
Nate Begemaneaa13852004-10-18 21:08:22 +00002510
Dan Gohman81db61a2009-05-12 02:17:14 +00002511 IU = &getAnalysis<IVUsers>();
Devang Patel0f54dcb2007-03-06 21:14:09 +00002512 LI = &getAnalysis<LoopInfo>();
Devang Patelb7d9dfc2007-06-07 21:42:15 +00002513 DT = &getAnalysis<DominatorTree>();
Devang Patel0f54dcb2007-03-06 21:14:09 +00002514 SE = &getAnalysis<ScalarEvolution>();
Dan Gohman3fea6432008-07-14 17:55:01 +00002515 Changed = false;
Devang Patel0f54dcb2007-03-06 21:14:09 +00002516
Dan Gohman81db61a2009-05-12 02:17:14 +00002517 if (!IU->IVUsesByStride.empty()) {
Dan Gohman80b0f8c2009-03-09 20:34:59 +00002518#ifndef NDEBUG
2519 DOUT << "\nLSR on \"" << L->getHeader()->getParent()->getNameStart()
2520 << "\" ";
2521 DEBUG(L->dump());
2522#endif
2523
Dan Gohmanf7912df2009-03-09 20:46:50 +00002524 // Sort the StrideOrder so we process larger strides first.
Dan Gohman81db61a2009-05-12 02:17:14 +00002525 std::stable_sort(IU->StrideOrder.begin(), IU->StrideOrder.end(),
2526 StrideCompare(SE));
Dan Gohmanf7912df2009-03-09 20:46:50 +00002527
Evan Cheng1ce75dc2008-07-07 19:51:32 +00002528 // Optimize induction variables. Some indvar uses can be transformed to use
2529 // strides that will be needed for other purposes. A common example of this
2530 // is the exit test for the loop, which can often be rewritten to use the
2531 // computation of some other indvar to decide when to terminate the loop.
2532 OptimizeIndvars(L);
Chris Lattner010de252005-08-08 05:28:22 +00002533
Evan Cheng5792f512009-05-11 22:33:01 +00002534 // Change loop terminating condition to use the postinc iv when possible
2535 // and optimize loop terminating compare. FIXME: Move this after
2536 // StrengthReduceStridedIVUsers?
2537 OptimizeLoopTermCond(L);
2538
Dan Gohmance174f82009-05-05 23:02:38 +00002539 // FIXME: We can shrink overlarge IV's here. e.g. if the code has
Dan Gohman4221ae82009-05-05 22:59:55 +00002540 // computation in i64 values and the target doesn't support i64, demote
2541 // the computation to 32-bit if safe.
Chris Lattner010de252005-08-08 05:28:22 +00002542
Evan Cheng1ce75dc2008-07-07 19:51:32 +00002543 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
2544 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should
2545 // be codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC.
2546 // Need to be careful that IV's are all the same type. Only works for
2547 // intptr_t indvars.
Misha Brukmanfd939082005-04-21 23:48:37 +00002548
Evan Cheng1ce75dc2008-07-07 19:51:32 +00002549 // IVsByStride keeps IVs for one particular loop.
2550 assert(IVsByStride.empty() && "Stale entries in IVsByStride?");
Evan Chengd1d6b5c2006-03-16 21:53:05 +00002551
Evan Cheng1ce75dc2008-07-07 19:51:32 +00002552 // Note: this processes each stride/type pair individually. All users
2553 // passed into StrengthReduceStridedIVUsers have the same type AND stride.
2554 // Also, note that we iterate over IVUsesByStride indirectly by using
2555 // StrideOrder. This extra layer of indirection makes the ordering of
2556 // strides deterministic - not dependent on map order.
Dan Gohman81db61a2009-05-12 02:17:14 +00002557 for (unsigned Stride = 0, e = IU->StrideOrder.size();
2558 Stride != e; ++Stride) {
2559 std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
2560 IU->IVUsesByStride.find(IU->StrideOrder[Stride]);
2561 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
2562 // FIXME: Generalize to non-affine IV's.
2563 if (!SI->first->isLoopInvariant(L))
2564 continue;
2565 StrengthReduceStridedIVUsers(SI->first, *SI->second, L);
Evan Cheng1ce75dc2008-07-07 19:51:32 +00002566 }
Chris Lattner7305ae22005-10-09 06:20:55 +00002567 }
Nate Begemaneaa13852004-10-18 21:08:22 +00002568
Dale Johannesenc1acc3f2009-05-11 17:15:42 +00002569 // After all sharing is done, see if we can adjust the loop to test against
2570 // zero instead of counting up to a maximum. This is usually faster.
2571 OptimizeLoopCountIV(L);
2572
Dan Gohman010ee2d2008-05-21 00:54:12 +00002573 // We're done analyzing this loop; release all the state we built up for it.
Dan Gohman010ee2d2008-05-21 00:54:12 +00002574 IVsByStride.clear();
Evan Cheng5792f512009-05-11 22:33:01 +00002575 StrideNoReuse.clear();
Dan Gohman010ee2d2008-05-21 00:54:12 +00002576
Nate Begemaneaa13852004-10-18 21:08:22 +00002577 // Clean up after ourselves
Dan Gohmanafc36a92009-05-02 18:29:22 +00002578 if (!DeadInsts.empty())
Chris Lattnera68d4ca2008-12-01 06:14:28 +00002579 DeleteTriviallyDeadInstructions();
Nate Begemaneaa13852004-10-18 21:08:22 +00002580
Dan Gohmanafc36a92009-05-02 18:29:22 +00002581 // At this point, it is worth checking to see if any recurrence PHIs are also
Dan Gohman35738ac2009-05-04 22:30:44 +00002582 // dead, so that we can remove them as well.
2583 DeleteDeadPHIs(L->getHeader());
Dan Gohmanafc36a92009-05-02 18:29:22 +00002584
Evan Cheng1ce75dc2008-07-07 19:51:32 +00002585 return Changed;
Nate Begemaneaa13852004-10-18 21:08:22 +00002586}