blob: c75e549309fa19bece29f31b2b97a38178c96212 [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//
Dan Gohmancec8f9d2009-05-19 20:37:36 +000010// This transformation analyzes and transforms the induction variables (and
11// computations derived from them) into forms suitable for efficient execution
12// on the target.
13//
Nate Begemaneaa13852004-10-18 21:08:22 +000014// This pass performs a strength reduction on array references inside loops that
Dan Gohmancec8f9d2009-05-19 20:37:36 +000015// have as one or more of their components the loop induction variable, it
16// rewrites expressions to take advantage of scaled-index addressing modes
17// available on the target, and it performs a variety of other optimizations
18// related to loop induction variables.
Nate Begemaneaa13852004-10-18 21:08:22 +000019//
Dan Gohman572645c2010-02-12 10:34:29 +000020// Terminology note: this code has a lot of handling for "post-increment" or
21// "post-inc" users. This is not talking about post-increment addressing modes;
22// it is instead talking about code like this:
23//
24// %i = phi [ 0, %entry ], [ %i.next, %latch ]
25// ...
26// %i.next = add %i, 1
27// %c = icmp eq %i.next, %n
28//
29// The SCEV for %i is {0,+,1}<%L>. The SCEV for %i.next is {1,+,1}<%L>, however
30// it's useful to think about these as the same register, with some uses using
31// the value of the register before the add and some using // it after. In this
32// example, the icmp is a post-increment user, since it uses %i.next, which is
33// the value of the induction variable after the increment. The other common
34// case of post-increment users is users outside the loop.
35//
36// TODO: More sophistication in the way Formulae are generated and filtered.
37//
38// TODO: Handle multiple loops at a time.
39//
40// TODO: Should TargetLowering::AddrMode::BaseGV be changed to a ConstantExpr
41// instead of a GlobalValue?
42//
43// TODO: When truncation is free, truncate ICmp users' operands to make it a
44// smaller encoding (on x86 at least).
45//
46// TODO: When a negated register is used by an add (such as in a list of
47// multiple base registers, or as the increment expression in an addrec),
48// we may not actually need both reg and (-1 * reg) in registers; the
49// negation can be implemented by using a sub instead of an add. The
50// lack of support for taking this into consideration when making
51// register pressure decisions is partly worked around by the "Special"
52// use kind.
53//
Nate Begemaneaa13852004-10-18 21:08:22 +000054//===----------------------------------------------------------------------===//
55
Chris Lattnerbe3e5212005-08-03 23:30:08 +000056#define DEBUG_TYPE "loop-reduce"
Nate Begemaneaa13852004-10-18 21:08:22 +000057#include "llvm/Transforms/Scalar.h"
58#include "llvm/Constants.h"
59#include "llvm/Instructions.h"
Dan Gohmane5b01be2007-05-04 14:59:09 +000060#include "llvm/IntrinsicInst.h"
Jeff Cohen2f3c9b72005-03-04 04:04:26 +000061#include "llvm/DerivedTypes.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000062#include "llvm/Analysis/IVUsers.h"
Dan Gohman572645c2010-02-12 10:34:29 +000063#include "llvm/Analysis/Dominators.h"
Devang Patel0f54dcb2007-03-06 21:14:09 +000064#include "llvm/Analysis/LoopPass.h"
Nate Begeman16997482005-07-30 00:15:07 +000065#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chris Lattner9fc5cdf2011-01-02 22:09:33 +000066#include "llvm/Assembly/Writer.h"
Chris Lattnere0391be2005-08-12 22:06:11 +000067#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Nate Begemaneaa13852004-10-18 21:08:22 +000068#include "llvm/Transforms/Utils/Local.h"
Dan Gohman572645c2010-02-12 10:34:29 +000069#include "llvm/ADT/SmallBitVector.h"
70#include "llvm/ADT/SetVector.h"
71#include "llvm/ADT/DenseSet.h"
Nate Begeman16997482005-07-30 00:15:07 +000072#include "llvm/Support/Debug.h"
Andrew Trick80ef1b22011-09-27 00:44:14 +000073#include "llvm/Support/CommandLine.h"
Dan Gohmanafc36a92009-05-02 18:29:22 +000074#include "llvm/Support/ValueHandle.h"
Daniel Dunbar460f6562009-07-26 09:48:23 +000075#include "llvm/Support/raw_ostream.h"
Evan Chengd277f2c2006-03-13 23:14:23 +000076#include "llvm/Target/TargetLowering.h"
Jeff Cohencfb1d422005-07-30 18:22:27 +000077#include <algorithm>
Nate Begemaneaa13852004-10-18 21:08:22 +000078using namespace llvm;
79
Benjamin Kramer0861f572011-11-26 23:01:57 +000080static cl::opt<bool> EnableNested(
Andrew Trick0c01bc32011-09-29 01:33:38 +000081 "enable-lsr-nested", cl::Hidden, cl::desc("Enable LSR on nested loops"));
82
Benjamin Kramer0861f572011-11-26 23:01:57 +000083static cl::opt<bool> EnableRetry(
84 "enable-lsr-retry", cl::Hidden, cl::desc("Enable LSR retry"));
Andrew Tricka02bfce2011-10-11 02:30:45 +000085
86// Temporary flag to cleanup congruent phis after LSR phi expansion.
87// It's currently disabled until we can determine whether it's truly useful or
88// not. The flag should be removed after the v3.0 release.
Andrew Trick24f670f2012-01-07 07:08:17 +000089// This is now needed for ivchains.
Benjamin Kramer0861f572011-11-26 23:01:57 +000090static cl::opt<bool> EnablePhiElim(
Andrew Trick24f670f2012-01-07 07:08:17 +000091 "enable-lsr-phielim", cl::Hidden, cl::init(true),
92 cl::desc("Enable LSR phi elimination"));
Andrew Trick80ef1b22011-09-27 00:44:14 +000093
Dan Gohman572645c2010-02-12 10:34:29 +000094namespace {
Nate Begemaneaa13852004-10-18 21:08:22 +000095
Dan Gohman572645c2010-02-12 10:34:29 +000096/// RegSortData - This class holds data which is used to order reuse candidates.
97class RegSortData {
98public:
99 /// UsedByIndices - This represents the set of LSRUse indices which reference
100 /// a particular register.
101 SmallBitVector UsedByIndices;
102
103 RegSortData() {}
104
105 void print(raw_ostream &OS) const;
106 void dump() const;
107};
108
109}
110
111void RegSortData::print(raw_ostream &OS) const {
112 OS << "[NumUses=" << UsedByIndices.count() << ']';
113}
114
115void RegSortData::dump() const {
116 print(errs()); errs() << '\n';
117}
Dan Gohmanc17e0cf2009-02-20 04:17:46 +0000118
Chris Lattner0e5f4992006-12-19 21:40:18 +0000119namespace {
Dale Johannesendc42f482007-03-20 00:47:50 +0000120
Dan Gohman572645c2010-02-12 10:34:29 +0000121/// RegUseTracker - Map register candidates to information about how they are
122/// used.
123class RegUseTracker {
124 typedef DenseMap<const SCEV *, RegSortData> RegUsesTy;
Dale Johannesendc42f482007-03-20 00:47:50 +0000125
Dan Gohman90bb3552010-05-18 22:33:00 +0000126 RegUsesTy RegUsesMap;
Dan Gohman572645c2010-02-12 10:34:29 +0000127 SmallVector<const SCEV *, 16> RegSequence;
Evan Chengd1d6b5c2006-03-16 21:53:05 +0000128
Dan Gohman572645c2010-02-12 10:34:29 +0000129public:
130 void CountRegister(const SCEV *Reg, size_t LUIdx);
Dan Gohmanb2df4332010-05-18 23:42:37 +0000131 void DropRegister(const SCEV *Reg, size_t LUIdx);
Dan Gohmanc6897702010-10-07 23:33:43 +0000132 void SwapAndDropUse(size_t LUIdx, size_t LastLUIdx);
Dan Gohmana10756e2010-01-21 02:09:26 +0000133
Dan Gohman572645c2010-02-12 10:34:29 +0000134 bool isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const;
Dan Gohmana10756e2010-01-21 02:09:26 +0000135
Dan Gohman572645c2010-02-12 10:34:29 +0000136 const SmallBitVector &getUsedByIndices(const SCEV *Reg) const;
Dan Gohmana10756e2010-01-21 02:09:26 +0000137
Dan Gohman572645c2010-02-12 10:34:29 +0000138 void clear();
Dan Gohmana10756e2010-01-21 02:09:26 +0000139
Dan Gohman572645c2010-02-12 10:34:29 +0000140 typedef SmallVectorImpl<const SCEV *>::iterator iterator;
141 typedef SmallVectorImpl<const SCEV *>::const_iterator const_iterator;
142 iterator begin() { return RegSequence.begin(); }
143 iterator end() { return RegSequence.end(); }
144 const_iterator begin() const { return RegSequence.begin(); }
145 const_iterator end() const { return RegSequence.end(); }
146};
Dan Gohmana10756e2010-01-21 02:09:26 +0000147
Dan Gohmana10756e2010-01-21 02:09:26 +0000148}
149
Dan Gohman572645c2010-02-12 10:34:29 +0000150void
151RegUseTracker::CountRegister(const SCEV *Reg, size_t LUIdx) {
152 std::pair<RegUsesTy::iterator, bool> Pair =
Dan Gohman90bb3552010-05-18 22:33:00 +0000153 RegUsesMap.insert(std::make_pair(Reg, RegSortData()));
Dan Gohman572645c2010-02-12 10:34:29 +0000154 RegSortData &RSD = Pair.first->second;
155 if (Pair.second)
156 RegSequence.push_back(Reg);
157 RSD.UsedByIndices.resize(std::max(RSD.UsedByIndices.size(), LUIdx + 1));
158 RSD.UsedByIndices.set(LUIdx);
Dan Gohmana10756e2010-01-21 02:09:26 +0000159}
160
Dan Gohmanb2df4332010-05-18 23:42:37 +0000161void
162RegUseTracker::DropRegister(const SCEV *Reg, size_t LUIdx) {
163 RegUsesTy::iterator It = RegUsesMap.find(Reg);
164 assert(It != RegUsesMap.end());
165 RegSortData &RSD = It->second;
166 assert(RSD.UsedByIndices.size() > LUIdx);
167 RSD.UsedByIndices.reset(LUIdx);
168}
169
Dan Gohmana2086b32010-05-19 23:43:12 +0000170void
Dan Gohmanc6897702010-10-07 23:33:43 +0000171RegUseTracker::SwapAndDropUse(size_t LUIdx, size_t LastLUIdx) {
172 assert(LUIdx <= LastLUIdx);
173
174 // Update RegUses. The data structure is not optimized for this purpose;
175 // we must iterate through it and update each of the bit vectors.
Dan Gohmana2086b32010-05-19 23:43:12 +0000176 for (RegUsesTy::iterator I = RegUsesMap.begin(), E = RegUsesMap.end();
Dan Gohmanc6897702010-10-07 23:33:43 +0000177 I != E; ++I) {
178 SmallBitVector &UsedByIndices = I->second.UsedByIndices;
179 if (LUIdx < UsedByIndices.size())
180 UsedByIndices[LUIdx] =
181 LastLUIdx < UsedByIndices.size() ? UsedByIndices[LastLUIdx] : 0;
182 UsedByIndices.resize(std::min(UsedByIndices.size(), LastLUIdx));
183 }
Dan Gohmana2086b32010-05-19 23:43:12 +0000184}
185
Dan Gohman572645c2010-02-12 10:34:29 +0000186bool
187RegUseTracker::isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const {
Dan Gohman46fd7a62010-08-29 15:18:49 +0000188 RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
189 if (I == RegUsesMap.end())
190 return false;
191 const SmallBitVector &UsedByIndices = I->second.UsedByIndices;
Dan Gohman572645c2010-02-12 10:34:29 +0000192 int i = UsedByIndices.find_first();
193 if (i == -1) return false;
194 if ((size_t)i != LUIdx) return true;
195 return UsedByIndices.find_next(i) != -1;
196}
Dan Gohmana10756e2010-01-21 02:09:26 +0000197
Dan Gohman572645c2010-02-12 10:34:29 +0000198const SmallBitVector &RegUseTracker::getUsedByIndices(const SCEV *Reg) const {
Dan Gohman90bb3552010-05-18 22:33:00 +0000199 RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
200 assert(I != RegUsesMap.end() && "Unknown register!");
Dan Gohman572645c2010-02-12 10:34:29 +0000201 return I->second.UsedByIndices;
202}
Dan Gohmana10756e2010-01-21 02:09:26 +0000203
Dan Gohman572645c2010-02-12 10:34:29 +0000204void RegUseTracker::clear() {
Dan Gohman90bb3552010-05-18 22:33:00 +0000205 RegUsesMap.clear();
Dan Gohman572645c2010-02-12 10:34:29 +0000206 RegSequence.clear();
207}
Dan Gohmana10756e2010-01-21 02:09:26 +0000208
Dan Gohman572645c2010-02-12 10:34:29 +0000209namespace {
210
211/// Formula - This class holds information that describes a formula for
212/// computing satisfying a use. It may include broken-out immediates and scaled
213/// registers.
214struct Formula {
215 /// AM - This is used to represent complex addressing, as well as other kinds
216 /// of interesting uses.
217 TargetLowering::AddrMode AM;
218
219 /// BaseRegs - The list of "base" registers for this use. When this is
220 /// non-empty, AM.HasBaseReg should be set to true.
221 SmallVector<const SCEV *, 2> BaseRegs;
222
223 /// ScaledReg - The 'scaled' register for this use. This should be non-null
224 /// when AM.Scale is not zero.
225 const SCEV *ScaledReg;
226
Dan Gohmancca82142011-05-03 00:46:49 +0000227 /// UnfoldedOffset - An additional constant offset which added near the
228 /// use. This requires a temporary register, but the offset itself can
229 /// live in an add immediate field rather than a register.
230 int64_t UnfoldedOffset;
231
232 Formula() : ScaledReg(0), UnfoldedOffset(0) {}
Dan Gohman572645c2010-02-12 10:34:29 +0000233
Dan Gohmandc0e8fb2010-11-17 21:41:58 +0000234 void InitialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE);
Dan Gohman572645c2010-02-12 10:34:29 +0000235
236 unsigned getNumRegs() const;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000237 Type *getType() const;
Dan Gohman572645c2010-02-12 10:34:29 +0000238
Dan Gohman5ce6d052010-05-20 15:17:54 +0000239 void DeleteBaseReg(const SCEV *&S);
240
Dan Gohman572645c2010-02-12 10:34:29 +0000241 bool referencesReg(const SCEV *S) const;
242 bool hasRegsUsedByUsesOtherThan(size_t LUIdx,
243 const RegUseTracker &RegUses) const;
244
245 void print(raw_ostream &OS) const;
246 void dump() const;
247};
248
249}
250
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000251/// DoInitialMatch - Recursion helper for InitialMatch.
Dan Gohman572645c2010-02-12 10:34:29 +0000252static void DoInitialMatch(const SCEV *S, Loop *L,
253 SmallVectorImpl<const SCEV *> &Good,
254 SmallVectorImpl<const SCEV *> &Bad,
Dan Gohmandc0e8fb2010-11-17 21:41:58 +0000255 ScalarEvolution &SE) {
Dan Gohman572645c2010-02-12 10:34:29 +0000256 // Collect expressions which properly dominate the loop header.
Dan Gohmandc0e8fb2010-11-17 21:41:58 +0000257 if (SE.properlyDominates(S, L->getHeader())) {
Dan Gohman572645c2010-02-12 10:34:29 +0000258 Good.push_back(S);
259 return;
Dan Gohmana10756e2010-01-21 02:09:26 +0000260 }
Dan Gohman572645c2010-02-12 10:34:29 +0000261
262 // Look at add operands.
263 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
264 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
265 I != E; ++I)
Dan Gohmandc0e8fb2010-11-17 21:41:58 +0000266 DoInitialMatch(*I, L, Good, Bad, SE);
Dan Gohman572645c2010-02-12 10:34:29 +0000267 return;
268 }
269
270 // Look at addrec operands.
271 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
272 if (!AR->getStart()->isZero()) {
Dan Gohmandc0e8fb2010-11-17 21:41:58 +0000273 DoInitialMatch(AR->getStart(), L, Good, Bad, SE);
Dan Gohmandeff6212010-05-03 22:09:21 +0000274 DoInitialMatch(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0),
Dan Gohman572645c2010-02-12 10:34:29 +0000275 AR->getStepRecurrence(SE),
Andrew Trick3228cc22011-03-14 16:50:06 +0000276 // FIXME: AR->getNoWrapFlags()
277 AR->getLoop(), SCEV::FlagAnyWrap),
Dan Gohmandc0e8fb2010-11-17 21:41:58 +0000278 L, Good, Bad, SE);
Dan Gohman572645c2010-02-12 10:34:29 +0000279 return;
280 }
281
282 // Handle a multiplication by -1 (negation) if it didn't fold.
283 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S))
284 if (Mul->getOperand(0)->isAllOnesValue()) {
285 SmallVector<const SCEV *, 4> Ops(Mul->op_begin()+1, Mul->op_end());
286 const SCEV *NewMul = SE.getMulExpr(Ops);
287
288 SmallVector<const SCEV *, 4> MyGood;
289 SmallVector<const SCEV *, 4> MyBad;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +0000290 DoInitialMatch(NewMul, L, MyGood, MyBad, SE);
Dan Gohman572645c2010-02-12 10:34:29 +0000291 const SCEV *NegOne = SE.getSCEV(ConstantInt::getAllOnesValue(
292 SE.getEffectiveSCEVType(NewMul->getType())));
293 for (SmallVectorImpl<const SCEV *>::const_iterator I = MyGood.begin(),
294 E = MyGood.end(); I != E; ++I)
295 Good.push_back(SE.getMulExpr(NegOne, *I));
296 for (SmallVectorImpl<const SCEV *>::const_iterator I = MyBad.begin(),
297 E = MyBad.end(); I != E; ++I)
298 Bad.push_back(SE.getMulExpr(NegOne, *I));
299 return;
300 }
301
302 // Ok, we can't do anything interesting. Just stuff the whole thing into a
303 // register and hope for the best.
304 Bad.push_back(S);
305}
306
307/// InitialMatch - Incorporate loop-variant parts of S into this Formula,
308/// attempting to keep all loop-invariant and loop-computable values in a
309/// single base register.
Dan Gohmandc0e8fb2010-11-17 21:41:58 +0000310void Formula::InitialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE) {
Dan Gohman572645c2010-02-12 10:34:29 +0000311 SmallVector<const SCEV *, 4> Good;
312 SmallVector<const SCEV *, 4> Bad;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +0000313 DoInitialMatch(S, L, Good, Bad, SE);
Dan Gohman572645c2010-02-12 10:34:29 +0000314 if (!Good.empty()) {
Dan Gohmane60bb152010-04-08 23:36:27 +0000315 const SCEV *Sum = SE.getAddExpr(Good);
316 if (!Sum->isZero())
317 BaseRegs.push_back(Sum);
Dan Gohman572645c2010-02-12 10:34:29 +0000318 AM.HasBaseReg = true;
319 }
320 if (!Bad.empty()) {
Dan Gohmane60bb152010-04-08 23:36:27 +0000321 const SCEV *Sum = SE.getAddExpr(Bad);
322 if (!Sum->isZero())
323 BaseRegs.push_back(Sum);
Dan Gohman572645c2010-02-12 10:34:29 +0000324 AM.HasBaseReg = true;
325 }
326}
327
328/// getNumRegs - Return the total number of register operands used by this
329/// formula. This does not include register uses implied by non-constant
330/// addrec strides.
331unsigned Formula::getNumRegs() const {
332 return !!ScaledReg + BaseRegs.size();
333}
334
335/// getType - Return the type of this formula, if it has one, or null
336/// otherwise. This type is meaningless except for the bit size.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000337Type *Formula::getType() const {
Dan Gohman572645c2010-02-12 10:34:29 +0000338 return !BaseRegs.empty() ? BaseRegs.front()->getType() :
339 ScaledReg ? ScaledReg->getType() :
340 AM.BaseGV ? AM.BaseGV->getType() :
341 0;
342}
343
Dan Gohman5ce6d052010-05-20 15:17:54 +0000344/// DeleteBaseReg - Delete the given base reg from the BaseRegs list.
345void Formula::DeleteBaseReg(const SCEV *&S) {
346 if (&S != &BaseRegs.back())
347 std::swap(S, BaseRegs.back());
348 BaseRegs.pop_back();
349}
350
Dan Gohman572645c2010-02-12 10:34:29 +0000351/// referencesReg - Test if this formula references the given register.
352bool Formula::referencesReg(const SCEV *S) const {
353 return S == ScaledReg ||
354 std::find(BaseRegs.begin(), BaseRegs.end(), S) != BaseRegs.end();
355}
356
357/// hasRegsUsedByUsesOtherThan - Test whether this formula uses registers
358/// which are used by uses other than the use with the given index.
359bool Formula::hasRegsUsedByUsesOtherThan(size_t LUIdx,
360 const RegUseTracker &RegUses) const {
361 if (ScaledReg)
362 if (RegUses.isRegUsedByUsesOtherThan(ScaledReg, LUIdx))
363 return true;
364 for (SmallVectorImpl<const SCEV *>::const_iterator I = BaseRegs.begin(),
365 E = BaseRegs.end(); I != E; ++I)
366 if (RegUses.isRegUsedByUsesOtherThan(*I, LUIdx))
367 return true;
368 return false;
369}
370
371void Formula::print(raw_ostream &OS) const {
372 bool First = true;
373 if (AM.BaseGV) {
374 if (!First) OS << " + "; else First = false;
375 WriteAsOperand(OS, AM.BaseGV, /*PrintType=*/false);
376 }
377 if (AM.BaseOffs != 0) {
378 if (!First) OS << " + "; else First = false;
379 OS << AM.BaseOffs;
380 }
381 for (SmallVectorImpl<const SCEV *>::const_iterator I = BaseRegs.begin(),
382 E = BaseRegs.end(); I != E; ++I) {
383 if (!First) OS << " + "; else First = false;
384 OS << "reg(" << **I << ')';
385 }
Dan Gohmanc4cfbaf2010-05-18 22:35:55 +0000386 if (AM.HasBaseReg && BaseRegs.empty()) {
387 if (!First) OS << " + "; else First = false;
388 OS << "**error: HasBaseReg**";
389 } else if (!AM.HasBaseReg && !BaseRegs.empty()) {
390 if (!First) OS << " + "; else First = false;
391 OS << "**error: !HasBaseReg**";
392 }
Dan Gohman572645c2010-02-12 10:34:29 +0000393 if (AM.Scale != 0) {
394 if (!First) OS << " + "; else First = false;
395 OS << AM.Scale << "*reg(";
396 if (ScaledReg)
397 OS << *ScaledReg;
398 else
399 OS << "<unknown>";
400 OS << ')';
401 }
Dan Gohmancca82142011-05-03 00:46:49 +0000402 if (UnfoldedOffset != 0) {
403 if (!First) OS << " + "; else First = false;
404 OS << "imm(" << UnfoldedOffset << ')';
405 }
Dan Gohman572645c2010-02-12 10:34:29 +0000406}
407
408void Formula::dump() const {
409 print(errs()); errs() << '\n';
410}
411
Dan Gohmanaae01f12010-02-19 19:32:49 +0000412/// isAddRecSExtable - Return true if the given addrec can be sign-extended
413/// without changing its value.
414static bool isAddRecSExtable(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000415 Type *WideTy =
Dan Gohmanea507f52010-05-20 19:44:23 +0000416 IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(AR->getType()) + 1);
Dan Gohmanaae01f12010-02-19 19:32:49 +0000417 return isa<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
418}
419
420/// isAddSExtable - Return true if the given add can be sign-extended
421/// without changing its value.
422static bool isAddSExtable(const SCEVAddExpr *A, ScalarEvolution &SE) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000423 Type *WideTy =
Dan Gohmanea507f52010-05-20 19:44:23 +0000424 IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(A->getType()) + 1);
Dan Gohmanaae01f12010-02-19 19:32:49 +0000425 return isa<SCEVAddExpr>(SE.getSignExtendExpr(A, WideTy));
426}
427
Dan Gohman473e6352010-06-24 16:45:11 +0000428/// isMulSExtable - Return true if the given mul can be sign-extended
Dan Gohmanaae01f12010-02-19 19:32:49 +0000429/// without changing its value.
Dan Gohman473e6352010-06-24 16:45:11 +0000430static bool isMulSExtable(const SCEVMulExpr *M, ScalarEvolution &SE) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000431 Type *WideTy =
Dan Gohman473e6352010-06-24 16:45:11 +0000432 IntegerType::get(SE.getContext(),
433 SE.getTypeSizeInBits(M->getType()) * M->getNumOperands());
434 return isa<SCEVMulExpr>(SE.getSignExtendExpr(M, WideTy));
Dan Gohmanaae01f12010-02-19 19:32:49 +0000435}
436
Dan Gohmanf09b7122010-02-19 19:35:48 +0000437/// getExactSDiv - Return an expression for LHS /s RHS, if it can be determined
438/// and if the remainder is known to be zero, or null otherwise. If
439/// IgnoreSignificantBits is true, expressions like (X * Y) /s Y are simplified
440/// to Y, ignoring that the multiplication may overflow, which is useful when
441/// the result will be used in a context where the most significant bits are
442/// ignored.
443static const SCEV *getExactSDiv(const SCEV *LHS, const SCEV *RHS,
444 ScalarEvolution &SE,
445 bool IgnoreSignificantBits = false) {
Dan Gohman572645c2010-02-12 10:34:29 +0000446 // Handle the trivial case, which works for any SCEV type.
447 if (LHS == RHS)
Dan Gohmandeff6212010-05-03 22:09:21 +0000448 return SE.getConstant(LHS->getType(), 1);
Dan Gohman572645c2010-02-12 10:34:29 +0000449
Dan Gohmand42819a2010-06-24 16:51:25 +0000450 // Handle a few RHS special cases.
451 const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS);
452 if (RC) {
453 const APInt &RA = RC->getValue()->getValue();
454 // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do
455 // some folding.
456 if (RA.isAllOnesValue())
457 return SE.getMulExpr(LHS, RC);
458 // Handle x /s 1 as x.
459 if (RA == 1)
460 return LHS;
461 }
Dan Gohman572645c2010-02-12 10:34:29 +0000462
463 // Check for a division of a constant by a constant.
464 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(LHS)) {
Dan Gohman572645c2010-02-12 10:34:29 +0000465 if (!RC)
466 return 0;
Dan Gohmand42819a2010-06-24 16:51:25 +0000467 const APInt &LA = C->getValue()->getValue();
468 const APInt &RA = RC->getValue()->getValue();
469 if (LA.srem(RA) != 0)
Dan Gohman572645c2010-02-12 10:34:29 +0000470 return 0;
Dan Gohmand42819a2010-06-24 16:51:25 +0000471 return SE.getConstant(LA.sdiv(RA));
Dan Gohman572645c2010-02-12 10:34:29 +0000472 }
473
Dan Gohmanaae01f12010-02-19 19:32:49 +0000474 // Distribute the sdiv over addrec operands, if the addrec doesn't overflow.
Dan Gohman572645c2010-02-12 10:34:29 +0000475 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohmanaae01f12010-02-19 19:32:49 +0000476 if (IgnoreSignificantBits || isAddRecSExtable(AR, SE)) {
Dan Gohmanf09b7122010-02-19 19:35:48 +0000477 const SCEV *Step = getExactSDiv(AR->getStepRecurrence(SE), RHS, SE,
478 IgnoreSignificantBits);
Dan Gohmanaae01f12010-02-19 19:32:49 +0000479 if (!Step) return 0;
Dan Gohman694a15e2010-08-19 01:02:31 +0000480 const SCEV *Start = getExactSDiv(AR->getStart(), RHS, SE,
481 IgnoreSignificantBits);
482 if (!Start) return 0;
Andrew Trick3228cc22011-03-14 16:50:06 +0000483 // FlagNW is independent of the start value, step direction, and is
484 // preserved with smaller magnitude steps.
485 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
486 return SE.getAddRecExpr(Start, Step, AR->getLoop(), SCEV::FlagAnyWrap);
Dan Gohmanaae01f12010-02-19 19:32:49 +0000487 }
Dan Gohman2ea09e02010-06-24 16:57:52 +0000488 return 0;
Dan Gohman572645c2010-02-12 10:34:29 +0000489 }
490
Dan Gohmanaae01f12010-02-19 19:32:49 +0000491 // Distribute the sdiv over add operands, if the add doesn't overflow.
Dan Gohman572645c2010-02-12 10:34:29 +0000492 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(LHS)) {
Dan Gohmanaae01f12010-02-19 19:32:49 +0000493 if (IgnoreSignificantBits || isAddSExtable(Add, SE)) {
494 SmallVector<const SCEV *, 8> Ops;
495 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
496 I != E; ++I) {
Dan Gohmanf09b7122010-02-19 19:35:48 +0000497 const SCEV *Op = getExactSDiv(*I, RHS, SE,
498 IgnoreSignificantBits);
Dan Gohmanaae01f12010-02-19 19:32:49 +0000499 if (!Op) return 0;
500 Ops.push_back(Op);
501 }
502 return SE.getAddExpr(Ops);
Dan Gohman572645c2010-02-12 10:34:29 +0000503 }
Dan Gohman2ea09e02010-06-24 16:57:52 +0000504 return 0;
Dan Gohman572645c2010-02-12 10:34:29 +0000505 }
506
507 // Check for a multiply operand that we can pull RHS out of.
Dan Gohman2ea09e02010-06-24 16:57:52 +0000508 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS)) {
Dan Gohmanaae01f12010-02-19 19:32:49 +0000509 if (IgnoreSignificantBits || isMulSExtable(Mul, SE)) {
Dan Gohman572645c2010-02-12 10:34:29 +0000510 SmallVector<const SCEV *, 4> Ops;
511 bool Found = false;
512 for (SCEVMulExpr::op_iterator I = Mul->op_begin(), E = Mul->op_end();
513 I != E; ++I) {
Dan Gohman47667442010-05-20 16:23:28 +0000514 const SCEV *S = *I;
Dan Gohman572645c2010-02-12 10:34:29 +0000515 if (!Found)
Dan Gohman47667442010-05-20 16:23:28 +0000516 if (const SCEV *Q = getExactSDiv(S, RHS, SE,
Dan Gohmanf09b7122010-02-19 19:35:48 +0000517 IgnoreSignificantBits)) {
Dan Gohman47667442010-05-20 16:23:28 +0000518 S = Q;
Dan Gohman572645c2010-02-12 10:34:29 +0000519 Found = true;
Dan Gohman572645c2010-02-12 10:34:29 +0000520 }
Dan Gohman47667442010-05-20 16:23:28 +0000521 Ops.push_back(S);
Dan Gohman572645c2010-02-12 10:34:29 +0000522 }
523 return Found ? SE.getMulExpr(Ops) : 0;
524 }
Dan Gohman2ea09e02010-06-24 16:57:52 +0000525 return 0;
526 }
Dan Gohman572645c2010-02-12 10:34:29 +0000527
528 // Otherwise we don't know.
529 return 0;
530}
531
532/// ExtractImmediate - If S involves the addition of a constant integer value,
533/// return that integer value, and mutate S to point to a new SCEV with that
534/// value excluded.
535static int64_t ExtractImmediate(const SCEV *&S, ScalarEvolution &SE) {
536 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
537 if (C->getValue()->getValue().getMinSignedBits() <= 64) {
Dan Gohmandeff6212010-05-03 22:09:21 +0000538 S = SE.getConstant(C->getType(), 0);
Dan Gohman572645c2010-02-12 10:34:29 +0000539 return C->getValue()->getSExtValue();
540 }
541 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
542 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
543 int64_t Result = ExtractImmediate(NewOps.front(), SE);
Dan Gohmane62d5882010-08-13 21:17:19 +0000544 if (Result != 0)
545 S = SE.getAddExpr(NewOps);
Dan Gohman572645c2010-02-12 10:34:29 +0000546 return Result;
547 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
548 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
549 int64_t Result = ExtractImmediate(NewOps.front(), SE);
Dan Gohmane62d5882010-08-13 21:17:19 +0000550 if (Result != 0)
Andrew Trick3228cc22011-03-14 16:50:06 +0000551 S = SE.getAddRecExpr(NewOps, AR->getLoop(),
552 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
553 SCEV::FlagAnyWrap);
Dan Gohman572645c2010-02-12 10:34:29 +0000554 return Result;
555 }
556 return 0;
557}
558
559/// ExtractSymbol - If S involves the addition of a GlobalValue address,
560/// return that symbol, and mutate S to point to a new SCEV with that
561/// value excluded.
562static GlobalValue *ExtractSymbol(const SCEV *&S, ScalarEvolution &SE) {
563 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
564 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) {
Dan Gohmandeff6212010-05-03 22:09:21 +0000565 S = SE.getConstant(GV->getType(), 0);
Dan Gohman572645c2010-02-12 10:34:29 +0000566 return GV;
567 }
568 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
569 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
570 GlobalValue *Result = ExtractSymbol(NewOps.back(), SE);
Dan Gohmane62d5882010-08-13 21:17:19 +0000571 if (Result)
572 S = SE.getAddExpr(NewOps);
Dan Gohman572645c2010-02-12 10:34:29 +0000573 return Result;
574 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
575 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
576 GlobalValue *Result = ExtractSymbol(NewOps.front(), SE);
Dan Gohmane62d5882010-08-13 21:17:19 +0000577 if (Result)
Andrew Trick3228cc22011-03-14 16:50:06 +0000578 S = SE.getAddRecExpr(NewOps, AR->getLoop(),
579 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
580 SCEV::FlagAnyWrap);
Dan Gohman572645c2010-02-12 10:34:29 +0000581 return Result;
582 }
583 return 0;
Nate Begemaneaa13852004-10-18 21:08:22 +0000584}
585
Dan Gohmanf284ce22009-02-18 00:08:39 +0000586/// isAddressUse - Returns true if the specified instruction is using the
Dale Johannesen203af582008-12-05 21:47:27 +0000587/// specified value as an address.
588static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
589 bool isAddress = isa<LoadInst>(Inst);
590 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
591 if (SI->getOperand(1) == OperandVal)
592 isAddress = true;
593 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
594 // Addressing modes can also be folded into prefetches and a variety
595 // of intrinsics.
596 switch (II->getIntrinsicID()) {
597 default: break;
598 case Intrinsic::prefetch:
Dale Johannesen203af582008-12-05 21:47:27 +0000599 case Intrinsic::x86_sse_storeu_ps:
600 case Intrinsic::x86_sse2_storeu_pd:
601 case Intrinsic::x86_sse2_storeu_dq:
602 case Intrinsic::x86_sse2_storel_dq:
Gabor Greifad72e732010-06-30 09:15:28 +0000603 if (II->getArgOperand(0) == OperandVal)
Dale Johannesen203af582008-12-05 21:47:27 +0000604 isAddress = true;
605 break;
606 }
607 }
608 return isAddress;
609}
Chris Lattner0ae33eb2005-10-03 01:04:44 +0000610
Dan Gohman21e77222009-03-09 21:01:17 +0000611/// getAccessType - Return the type of the memory being accessed.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000612static Type *getAccessType(const Instruction *Inst) {
613 Type *AccessTy = Inst->getType();
Dan Gohman21e77222009-03-09 21:01:17 +0000614 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst))
Dan Gohmana537bf82009-05-18 16:45:28 +0000615 AccessTy = SI->getOperand(0)->getType();
Dan Gohman21e77222009-03-09 21:01:17 +0000616 else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
617 // Addressing modes can also be folded into prefetches and a variety
618 // of intrinsics.
619 switch (II->getIntrinsicID()) {
620 default: break;
621 case Intrinsic::x86_sse_storeu_ps:
622 case Intrinsic::x86_sse2_storeu_pd:
623 case Intrinsic::x86_sse2_storeu_dq:
624 case Intrinsic::x86_sse2_storel_dq:
Gabor Greifad72e732010-06-30 09:15:28 +0000625 AccessTy = II->getArgOperand(0)->getType();
Dan Gohman21e77222009-03-09 21:01:17 +0000626 break;
627 }
628 }
Dan Gohman572645c2010-02-12 10:34:29 +0000629
630 // All pointers have the same requirements, so canonicalize them to an
631 // arbitrary pointer type to minimize variation.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000632 if (PointerType *PTy = dyn_cast<PointerType>(AccessTy))
Dan Gohman572645c2010-02-12 10:34:29 +0000633 AccessTy = PointerType::get(IntegerType::get(PTy->getContext(), 1),
634 PTy->getAddressSpace());
635
Dan Gohmana537bf82009-05-18 16:45:28 +0000636 return AccessTy;
Dan Gohman21e77222009-03-09 21:01:17 +0000637}
638
Andrew Trick8a5d7922011-12-06 03:13:31 +0000639/// isExistingPhi - Return true if this AddRec is already a phi in its loop.
640static bool isExistingPhi(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
641 for (BasicBlock::iterator I = AR->getLoop()->getHeader()->begin();
642 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
643 if (SE.isSCEVable(PN->getType()) &&
644 (SE.getEffectiveSCEVType(PN->getType()) ==
645 SE.getEffectiveSCEVType(AR->getType())) &&
646 SE.getSCEV(PN) == AR)
647 return true;
648 }
649 return false;
650}
651
Dan Gohman572645c2010-02-12 10:34:29 +0000652/// DeleteTriviallyDeadInstructions - If any of the instructions is the
653/// specified set are trivially dead, delete them and see if this makes any of
654/// their operands subsequently dead.
655static bool
656DeleteTriviallyDeadInstructions(SmallVectorImpl<WeakVH> &DeadInsts) {
657 bool Changed = false;
658
659 while (!DeadInsts.empty()) {
Gabor Greiff097b592010-09-18 11:55:34 +0000660 Instruction *I = dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val());
Dan Gohman572645c2010-02-12 10:34:29 +0000661
662 if (I == 0 || !isInstructionTriviallyDead(I))
663 continue;
664
665 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
666 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
667 *OI = 0;
668 if (U->use_empty())
669 DeadInsts.push_back(U);
670 }
671
672 I->eraseFromParent();
673 Changed = true;
674 }
675
676 return Changed;
677}
678
Dan Gohman7979b722010-01-22 00:46:49 +0000679namespace {
Jim Grosbach56a1f802009-11-17 17:53:56 +0000680
Dan Gohman572645c2010-02-12 10:34:29 +0000681/// Cost - This class is used to measure and compare candidate formulae.
682class Cost {
683 /// TODO: Some of these could be merged. Also, a lexical ordering
684 /// isn't always optimal.
685 unsigned NumRegs;
686 unsigned AddRecCost;
687 unsigned NumIVMuls;
688 unsigned NumBaseAdds;
689 unsigned ImmCost;
690 unsigned SetupCost;
Nate Begeman16997482005-07-30 00:15:07 +0000691
Dan Gohman572645c2010-02-12 10:34:29 +0000692public:
693 Cost()
694 : NumRegs(0), AddRecCost(0), NumIVMuls(0), NumBaseAdds(0), ImmCost(0),
695 SetupCost(0) {}
Jim Grosbach56a1f802009-11-17 17:53:56 +0000696
Dan Gohman572645c2010-02-12 10:34:29 +0000697 bool operator<(const Cost &Other) const;
Dan Gohman7979b722010-01-22 00:46:49 +0000698
Dan Gohman572645c2010-02-12 10:34:29 +0000699 void Loose();
Dan Gohman7979b722010-01-22 00:46:49 +0000700
Andrew Trick7d11bd82011-09-26 23:11:04 +0000701#ifndef NDEBUG
702 // Once any of the metrics loses, they must all remain losers.
703 bool isValid() {
704 return ((NumRegs | AddRecCost | NumIVMuls | NumBaseAdds
705 | ImmCost | SetupCost) != ~0u)
706 || ((NumRegs & AddRecCost & NumIVMuls & NumBaseAdds
707 & ImmCost & SetupCost) == ~0u);
708 }
709#endif
710
711 bool isLoser() {
712 assert(isValid() && "invalid cost");
713 return NumRegs == ~0u;
714 }
715
Dan Gohman572645c2010-02-12 10:34:29 +0000716 void RateFormula(const Formula &F,
717 SmallPtrSet<const SCEV *, 16> &Regs,
718 const DenseSet<const SCEV *> &VisitedRegs,
719 const Loop *L,
720 const SmallVectorImpl<int64_t> &Offsets,
Andrew Trick8a5d7922011-12-06 03:13:31 +0000721 ScalarEvolution &SE, DominatorTree &DT,
722 SmallPtrSet<const SCEV *, 16> *LoserRegs = 0);
Dan Gohman7979b722010-01-22 00:46:49 +0000723
Dan Gohman572645c2010-02-12 10:34:29 +0000724 void print(raw_ostream &OS) const;
725 void dump() const;
Dan Gohman7979b722010-01-22 00:46:49 +0000726
Dan Gohman572645c2010-02-12 10:34:29 +0000727private:
728 void RateRegister(const SCEV *Reg,
729 SmallPtrSet<const SCEV *, 16> &Regs,
730 const Loop *L,
731 ScalarEvolution &SE, DominatorTree &DT);
Dan Gohman9214b822010-02-13 02:06:02 +0000732 void RatePrimaryRegister(const SCEV *Reg,
733 SmallPtrSet<const SCEV *, 16> &Regs,
734 const Loop *L,
Andrew Trick8a5d7922011-12-06 03:13:31 +0000735 ScalarEvolution &SE, DominatorTree &DT,
736 SmallPtrSet<const SCEV *, 16> *LoserRegs);
Dan Gohman572645c2010-02-12 10:34:29 +0000737};
738
739}
740
741/// RateRegister - Tally up interesting quantities from the given register.
742void Cost::RateRegister(const SCEV *Reg,
743 SmallPtrSet<const SCEV *, 16> &Regs,
744 const Loop *L,
745 ScalarEvolution &SE, DominatorTree &DT) {
Dan Gohman9214b822010-02-13 02:06:02 +0000746 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Reg)) {
747 if (AR->getLoop() == L)
748 AddRecCost += 1; /// TODO: This should be a function of the stride.
Dan Gohman572645c2010-02-12 10:34:29 +0000749
Andrew Trick0c01bc32011-09-29 01:33:38 +0000750 // If this is an addrec for another loop, don't second-guess its addrec phi
751 // nodes. LSR isn't currently smart enough to reason about more than one
752 // loop at a time. LSR has either already run on inner loops, will not run
753 // on other loops, and cannot be expected to change sibling loops. If the
754 // AddRec exists, consider it's register free and leave it alone. Otherwise,
755 // do not consider this formula at all.
Andrew Trick0c01bc32011-09-29 01:33:38 +0000756 else if (!EnableNested || L->contains(AR->getLoop()) ||
Dan Gohman9214b822010-02-13 02:06:02 +0000757 (!AR->getLoop()->contains(L) &&
758 DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))) {
Andrew Trick8a5d7922011-12-06 03:13:31 +0000759 if (isExistingPhi(AR, SE))
760 return;
761
762 // For !EnableNested, never rewrite IVs in other loops.
Andrew Trick0c01bc32011-09-29 01:33:38 +0000763 if (!EnableNested) {
764 Loose();
765 return;
766 }
Dan Gohman9214b822010-02-13 02:06:02 +0000767 // If this isn't one of the addrecs that the loop already has, it
768 // would require a costly new phi and add. TODO: This isn't
769 // precisely modeled right now.
770 ++NumBaseAdds;
Andrew Trick7d11bd82011-09-26 23:11:04 +0000771 if (!Regs.count(AR->getStart())) {
Dan Gohman572645c2010-02-12 10:34:29 +0000772 RateRegister(AR->getStart(), Regs, L, SE, DT);
Andrew Trick7d11bd82011-09-26 23:11:04 +0000773 if (isLoser())
774 return;
775 }
Dan Gohman572645c2010-02-12 10:34:29 +0000776 }
Dan Gohman572645c2010-02-12 10:34:29 +0000777
Dan Gohman9214b822010-02-13 02:06:02 +0000778 // Add the step value register, if it needs one.
779 // TODO: The non-affine case isn't precisely modeled here.
Andrew Trick25b689e2011-09-26 23:35:25 +0000780 if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1))) {
781 if (!Regs.count(AR->getOperand(1))) {
Dan Gohman9214b822010-02-13 02:06:02 +0000782 RateRegister(AR->getOperand(1), Regs, L, SE, DT);
Andrew Trick25b689e2011-09-26 23:35:25 +0000783 if (isLoser())
784 return;
785 }
786 }
Dan Gohman572645c2010-02-12 10:34:29 +0000787 }
Dan Gohman9214b822010-02-13 02:06:02 +0000788 ++NumRegs;
789
790 // Rough heuristic; favor registers which don't require extra setup
791 // instructions in the preheader.
792 if (!isa<SCEVUnknown>(Reg) &&
793 !isa<SCEVConstant>(Reg) &&
794 !(isa<SCEVAddRecExpr>(Reg) &&
795 (isa<SCEVUnknown>(cast<SCEVAddRecExpr>(Reg)->getStart()) ||
796 isa<SCEVConstant>(cast<SCEVAddRecExpr>(Reg)->getStart()))))
797 ++SetupCost;
Dan Gohman23c3fde2010-10-07 23:41:58 +0000798
799 NumIVMuls += isa<SCEVMulExpr>(Reg) &&
Dan Gohman17ead4f2010-11-17 21:23:15 +0000800 SE.hasComputableLoopEvolution(Reg, L);
Dan Gohman9214b822010-02-13 02:06:02 +0000801}
802
803/// RatePrimaryRegister - Record this register in the set. If we haven't seen it
Andrew Trick8a5d7922011-12-06 03:13:31 +0000804/// before, rate it. Optional LoserRegs provides a way to declare any formula
805/// that refers to one of those regs an instant loser.
Dan Gohman9214b822010-02-13 02:06:02 +0000806void Cost::RatePrimaryRegister(const SCEV *Reg,
Dan Gohman7fca2292010-02-16 19:42:34 +0000807 SmallPtrSet<const SCEV *, 16> &Regs,
808 const Loop *L,
Andrew Trick8a5d7922011-12-06 03:13:31 +0000809 ScalarEvolution &SE, DominatorTree &DT,
810 SmallPtrSet<const SCEV *, 16> *LoserRegs) {
811 if (LoserRegs && LoserRegs->count(Reg)) {
812 Loose();
813 return;
814 }
815 if (Regs.insert(Reg)) {
Dan Gohman9214b822010-02-13 02:06:02 +0000816 RateRegister(Reg, Regs, L, SE, DT);
Andrew Trick8a5d7922011-12-06 03:13:31 +0000817 if (isLoser())
818 LoserRegs->insert(Reg);
819 }
Dan Gohman572645c2010-02-12 10:34:29 +0000820}
821
822void Cost::RateFormula(const Formula &F,
823 SmallPtrSet<const SCEV *, 16> &Regs,
824 const DenseSet<const SCEV *> &VisitedRegs,
825 const Loop *L,
826 const SmallVectorImpl<int64_t> &Offsets,
Andrew Trick8a5d7922011-12-06 03:13:31 +0000827 ScalarEvolution &SE, DominatorTree &DT,
828 SmallPtrSet<const SCEV *, 16> *LoserRegs) {
Dan Gohman572645c2010-02-12 10:34:29 +0000829 // Tally up the registers.
830 if (const SCEV *ScaledReg = F.ScaledReg) {
831 if (VisitedRegs.count(ScaledReg)) {
832 Loose();
833 return;
834 }
Andrew Trick8a5d7922011-12-06 03:13:31 +0000835 RatePrimaryRegister(ScaledReg, Regs, L, SE, DT, LoserRegs);
Andrew Trick7d11bd82011-09-26 23:11:04 +0000836 if (isLoser())
837 return;
Dan Gohman572645c2010-02-12 10:34:29 +0000838 }
839 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
840 E = F.BaseRegs.end(); I != E; ++I) {
841 const SCEV *BaseReg = *I;
842 if (VisitedRegs.count(BaseReg)) {
843 Loose();
844 return;
845 }
Andrew Trick8a5d7922011-12-06 03:13:31 +0000846 RatePrimaryRegister(BaseReg, Regs, L, SE, DT, LoserRegs);
Andrew Trick7d11bd82011-09-26 23:11:04 +0000847 if (isLoser())
848 return;
Dan Gohman572645c2010-02-12 10:34:29 +0000849 }
850
Dan Gohmancca82142011-05-03 00:46:49 +0000851 // Determine how many (unfolded) adds we'll need inside the loop.
852 size_t NumBaseParts = F.BaseRegs.size() + (F.UnfoldedOffset != 0);
853 if (NumBaseParts > 1)
854 NumBaseAdds += NumBaseParts - 1;
Dan Gohman572645c2010-02-12 10:34:29 +0000855
856 // Tally up the non-zero immediates.
857 for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
858 E = Offsets.end(); I != E; ++I) {
859 int64_t Offset = (uint64_t)*I + F.AM.BaseOffs;
860 if (F.AM.BaseGV)
861 ImmCost += 64; // Handle symbolic values conservatively.
862 // TODO: This should probably be the pointer size.
863 else if (Offset != 0)
864 ImmCost += APInt(64, Offset, true).getMinSignedBits();
865 }
Andrew Trick7d11bd82011-09-26 23:11:04 +0000866 assert(isValid() && "invalid cost");
Dan Gohman572645c2010-02-12 10:34:29 +0000867}
868
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000869/// Loose - Set this cost to a losing value.
Dan Gohman572645c2010-02-12 10:34:29 +0000870void Cost::Loose() {
871 NumRegs = ~0u;
872 AddRecCost = ~0u;
873 NumIVMuls = ~0u;
874 NumBaseAdds = ~0u;
875 ImmCost = ~0u;
876 SetupCost = ~0u;
877}
878
879/// operator< - Choose the lower cost.
880bool Cost::operator<(const Cost &Other) const {
881 if (NumRegs != Other.NumRegs)
882 return NumRegs < Other.NumRegs;
883 if (AddRecCost != Other.AddRecCost)
884 return AddRecCost < Other.AddRecCost;
885 if (NumIVMuls != Other.NumIVMuls)
886 return NumIVMuls < Other.NumIVMuls;
887 if (NumBaseAdds != Other.NumBaseAdds)
888 return NumBaseAdds < Other.NumBaseAdds;
889 if (ImmCost != Other.ImmCost)
890 return ImmCost < Other.ImmCost;
891 if (SetupCost != Other.SetupCost)
892 return SetupCost < Other.SetupCost;
893 return false;
894}
895
896void Cost::print(raw_ostream &OS) const {
897 OS << NumRegs << " reg" << (NumRegs == 1 ? "" : "s");
898 if (AddRecCost != 0)
899 OS << ", with addrec cost " << AddRecCost;
900 if (NumIVMuls != 0)
901 OS << ", plus " << NumIVMuls << " IV mul" << (NumIVMuls == 1 ? "" : "s");
902 if (NumBaseAdds != 0)
903 OS << ", plus " << NumBaseAdds << " base add"
904 << (NumBaseAdds == 1 ? "" : "s");
905 if (ImmCost != 0)
906 OS << ", plus " << ImmCost << " imm cost";
907 if (SetupCost != 0)
908 OS << ", plus " << SetupCost << " setup cost";
909}
910
911void Cost::dump() const {
912 print(errs()); errs() << '\n';
913}
914
915namespace {
916
917/// LSRFixup - An operand value in an instruction which is to be replaced
918/// with some equivalent, possibly strength-reduced, replacement.
919struct LSRFixup {
920 /// UserInst - The instruction which will be updated.
921 Instruction *UserInst;
922
923 /// OperandValToReplace - The operand of the instruction which will
924 /// be replaced. The operand may be used more than once; every instance
925 /// will be replaced.
926 Value *OperandValToReplace;
927
Dan Gohman448db1c2010-04-07 22:27:08 +0000928 /// PostIncLoops - If this user is to use the post-incremented value of an
Dan Gohman572645c2010-02-12 10:34:29 +0000929 /// induction variable, this variable is non-null and holds the loop
930 /// associated with the induction variable.
Dan Gohman448db1c2010-04-07 22:27:08 +0000931 PostIncLoopSet PostIncLoops;
Dan Gohman572645c2010-02-12 10:34:29 +0000932
933 /// LUIdx - The index of the LSRUse describing the expression which
934 /// this fixup needs, minus an offset (below).
935 size_t LUIdx;
936
937 /// Offset - A constant offset to be added to the LSRUse expression.
938 /// This allows multiple fixups to share the same LSRUse with different
939 /// offsets, for example in an unrolled loop.
940 int64_t Offset;
941
Dan Gohman448db1c2010-04-07 22:27:08 +0000942 bool isUseFullyOutsideLoop(const Loop *L) const;
943
Dan Gohman572645c2010-02-12 10:34:29 +0000944 LSRFixup();
945
946 void print(raw_ostream &OS) const;
947 void dump() const;
948};
949
950}
951
952LSRFixup::LSRFixup()
Dan Gohmanea507f52010-05-20 19:44:23 +0000953 : UserInst(0), OperandValToReplace(0), LUIdx(~size_t(0)), Offset(0) {}
Dan Gohman572645c2010-02-12 10:34:29 +0000954
Dan Gohman448db1c2010-04-07 22:27:08 +0000955/// isUseFullyOutsideLoop - Test whether this fixup always uses its
956/// value outside of the given loop.
957bool LSRFixup::isUseFullyOutsideLoop(const Loop *L) const {
958 // PHI nodes use their value in their incoming blocks.
959 if (const PHINode *PN = dyn_cast<PHINode>(UserInst)) {
960 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
961 if (PN->getIncomingValue(i) == OperandValToReplace &&
962 L->contains(PN->getIncomingBlock(i)))
963 return false;
964 return true;
965 }
966
967 return !L->contains(UserInst);
968}
969
Dan Gohman572645c2010-02-12 10:34:29 +0000970void LSRFixup::print(raw_ostream &OS) const {
971 OS << "UserInst=";
972 // Store is common and interesting enough to be worth special-casing.
973 if (StoreInst *Store = dyn_cast<StoreInst>(UserInst)) {
974 OS << "store ";
975 WriteAsOperand(OS, Store->getOperand(0), /*PrintType=*/false);
976 } else if (UserInst->getType()->isVoidTy())
977 OS << UserInst->getOpcodeName();
978 else
979 WriteAsOperand(OS, UserInst, /*PrintType=*/false);
980
981 OS << ", OperandValToReplace=";
982 WriteAsOperand(OS, OperandValToReplace, /*PrintType=*/false);
983
Dan Gohman448db1c2010-04-07 22:27:08 +0000984 for (PostIncLoopSet::const_iterator I = PostIncLoops.begin(),
985 E = PostIncLoops.end(); I != E; ++I) {
Dan Gohman572645c2010-02-12 10:34:29 +0000986 OS << ", PostIncLoop=";
Dan Gohman448db1c2010-04-07 22:27:08 +0000987 WriteAsOperand(OS, (*I)->getHeader(), /*PrintType=*/false);
Dan Gohman572645c2010-02-12 10:34:29 +0000988 }
989
990 if (LUIdx != ~size_t(0))
991 OS << ", LUIdx=" << LUIdx;
992
993 if (Offset != 0)
994 OS << ", Offset=" << Offset;
995}
996
997void LSRFixup::dump() const {
998 print(errs()); errs() << '\n';
999}
1000
1001namespace {
1002
1003/// UniquifierDenseMapInfo - A DenseMapInfo implementation for holding
1004/// DenseMaps and DenseSets of sorted SmallVectors of const SCEV*.
1005struct UniquifierDenseMapInfo {
1006 static SmallVector<const SCEV *, 2> getEmptyKey() {
1007 SmallVector<const SCEV *, 2> V;
1008 V.push_back(reinterpret_cast<const SCEV *>(-1));
1009 return V;
1010 }
1011
1012 static SmallVector<const SCEV *, 2> getTombstoneKey() {
1013 SmallVector<const SCEV *, 2> V;
1014 V.push_back(reinterpret_cast<const SCEV *>(-2));
1015 return V;
1016 }
1017
1018 static unsigned getHashValue(const SmallVector<const SCEV *, 2> &V) {
1019 unsigned Result = 0;
1020 for (SmallVectorImpl<const SCEV *>::const_iterator I = V.begin(),
1021 E = V.end(); I != E; ++I)
1022 Result ^= DenseMapInfo<const SCEV *>::getHashValue(*I);
1023 return Result;
1024 }
1025
1026 static bool isEqual(const SmallVector<const SCEV *, 2> &LHS,
1027 const SmallVector<const SCEV *, 2> &RHS) {
1028 return LHS == RHS;
1029 }
1030};
1031
1032/// LSRUse - This class holds the state that LSR keeps for each use in
1033/// IVUsers, as well as uses invented by LSR itself. It includes information
1034/// about what kinds of things can be folded into the user, information about
1035/// the user itself, and information about how the use may be satisfied.
1036/// TODO: Represent multiple users of the same expression in common?
1037class LSRUse {
1038 DenseSet<SmallVector<const SCEV *, 2>, UniquifierDenseMapInfo> Uniquifier;
1039
1040public:
1041 /// KindType - An enum for a kind of use, indicating what types of
1042 /// scaled and immediate operands it might support.
1043 enum KindType {
1044 Basic, ///< A normal use, with no folding.
1045 Special, ///< A special case of basic, allowing -1 scales.
1046 Address, ///< An address use; folding according to TargetLowering
1047 ICmpZero ///< An equality icmp with both operands folded into one.
1048 // TODO: Add a generic icmp too?
Dan Gohman7979b722010-01-22 00:46:49 +00001049 };
Dan Gohman572645c2010-02-12 10:34:29 +00001050
1051 KindType Kind;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001052 Type *AccessTy;
Dan Gohman572645c2010-02-12 10:34:29 +00001053
1054 SmallVector<int64_t, 8> Offsets;
1055 int64_t MinOffset;
1056 int64_t MaxOffset;
1057
1058 /// AllFixupsOutsideLoop - This records whether all of the fixups using this
1059 /// LSRUse are outside of the loop, in which case some special-case heuristics
1060 /// may be used.
1061 bool AllFixupsOutsideLoop;
1062
Dan Gohmana9db1292010-07-15 20:24:58 +00001063 /// WidestFixupType - This records the widest use type for any fixup using
1064 /// this LSRUse. FindUseWithSimilarFormula can't consider uses with different
1065 /// max fixup widths to be equivalent, because the narrower one may be relying
1066 /// on the implicit truncation to truncate away bogus bits.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001067 Type *WidestFixupType;
Dan Gohmana9db1292010-07-15 20:24:58 +00001068
Dan Gohman572645c2010-02-12 10:34:29 +00001069 /// Formulae - A list of ways to build a value that can satisfy this user.
1070 /// After the list is populated, one of these is selected heuristically and
1071 /// used to formulate a replacement for OperandValToReplace in UserInst.
1072 SmallVector<Formula, 12> Formulae;
1073
1074 /// Regs - The set of register candidates used by all formulae in this LSRUse.
1075 SmallPtrSet<const SCEV *, 4> Regs;
1076
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001077 LSRUse(KindType K, Type *T) : Kind(K), AccessTy(T),
Dan Gohman572645c2010-02-12 10:34:29 +00001078 MinOffset(INT64_MAX),
1079 MaxOffset(INT64_MIN),
Dan Gohmana9db1292010-07-15 20:24:58 +00001080 AllFixupsOutsideLoop(true),
1081 WidestFixupType(0) {}
Dan Gohman572645c2010-02-12 10:34:29 +00001082
Dan Gohmana2086b32010-05-19 23:43:12 +00001083 bool HasFormulaWithSameRegs(const Formula &F) const;
Dan Gohman454d26d2010-02-22 04:11:59 +00001084 bool InsertFormula(const Formula &F);
Dan Gohmand69d6282010-05-18 22:39:15 +00001085 void DeleteFormula(Formula &F);
Dan Gohmanb2df4332010-05-18 23:42:37 +00001086 void RecomputeRegs(size_t LUIdx, RegUseTracker &Reguses);
Dan Gohman572645c2010-02-12 10:34:29 +00001087
Dan Gohman572645c2010-02-12 10:34:29 +00001088 void print(raw_ostream &OS) const;
1089 void dump() const;
1090};
1091
Dan Gohmanb6211712010-06-19 21:21:39 +00001092}
1093
Dan Gohmana2086b32010-05-19 23:43:12 +00001094/// HasFormula - Test whether this use as a formula which has the same
1095/// registers as the given formula.
1096bool LSRUse::HasFormulaWithSameRegs(const Formula &F) const {
1097 SmallVector<const SCEV *, 2> Key = F.BaseRegs;
1098 if (F.ScaledReg) Key.push_back(F.ScaledReg);
1099 // Unstable sort by host order ok, because this is only used for uniquifying.
1100 std::sort(Key.begin(), Key.end());
1101 return Uniquifier.count(Key);
1102}
1103
Dan Gohman572645c2010-02-12 10:34:29 +00001104/// InsertFormula - If the given formula has not yet been inserted, add it to
1105/// the list, and return true. Return false otherwise.
Dan Gohman454d26d2010-02-22 04:11:59 +00001106bool LSRUse::InsertFormula(const Formula &F) {
Dan Gohman572645c2010-02-12 10:34:29 +00001107 SmallVector<const SCEV *, 2> Key = F.BaseRegs;
1108 if (F.ScaledReg) Key.push_back(F.ScaledReg);
1109 // Unstable sort by host order ok, because this is only used for uniquifying.
1110 std::sort(Key.begin(), Key.end());
1111
1112 if (!Uniquifier.insert(Key).second)
1113 return false;
1114
1115 // Using a register to hold the value of 0 is not profitable.
1116 assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&
1117 "Zero allocated in a scaled register!");
1118#ifndef NDEBUG
1119 for (SmallVectorImpl<const SCEV *>::const_iterator I =
1120 F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I)
1121 assert(!(*I)->isZero() && "Zero allocated in a base register!");
1122#endif
1123
1124 // Add the formula to the list.
1125 Formulae.push_back(F);
1126
1127 // Record registers now being used by this use.
Dan Gohman572645c2010-02-12 10:34:29 +00001128 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
1129
1130 return true;
Dan Gohman7979b722010-01-22 00:46:49 +00001131}
1132
Dan Gohmand69d6282010-05-18 22:39:15 +00001133/// DeleteFormula - Remove the given formula from this use's list.
1134void LSRUse::DeleteFormula(Formula &F) {
Dan Gohman5ce6d052010-05-20 15:17:54 +00001135 if (&F != &Formulae.back())
1136 std::swap(F, Formulae.back());
Dan Gohmand69d6282010-05-18 22:39:15 +00001137 Formulae.pop_back();
1138}
1139
Dan Gohmanb2df4332010-05-18 23:42:37 +00001140/// RecomputeRegs - Recompute the Regs field, and update RegUses.
1141void LSRUse::RecomputeRegs(size_t LUIdx, RegUseTracker &RegUses) {
1142 // Now that we've filtered out some formulae, recompute the Regs set.
1143 SmallPtrSet<const SCEV *, 4> OldRegs = Regs;
1144 Regs.clear();
Dan Gohman402d4352010-05-20 20:33:18 +00001145 for (SmallVectorImpl<Formula>::const_iterator I = Formulae.begin(),
1146 E = Formulae.end(); I != E; ++I) {
1147 const Formula &F = *I;
Dan Gohmanb2df4332010-05-18 23:42:37 +00001148 if (F.ScaledReg) Regs.insert(F.ScaledReg);
1149 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
1150 }
1151
1152 // Update the RegTracker.
1153 for (SmallPtrSet<const SCEV *, 4>::iterator I = OldRegs.begin(),
1154 E = OldRegs.end(); I != E; ++I)
1155 if (!Regs.count(*I))
1156 RegUses.DropRegister(*I, LUIdx);
1157}
1158
Dan Gohman572645c2010-02-12 10:34:29 +00001159void LSRUse::print(raw_ostream &OS) const {
1160 OS << "LSR Use: Kind=";
1161 switch (Kind) {
1162 case Basic: OS << "Basic"; break;
1163 case Special: OS << "Special"; break;
1164 case ICmpZero: OS << "ICmpZero"; break;
1165 case Address:
1166 OS << "Address of ";
Duncan Sands1df98592010-02-16 11:11:14 +00001167 if (AccessTy->isPointerTy())
Dan Gohman572645c2010-02-12 10:34:29 +00001168 OS << "pointer"; // the full pointer type could be really verbose
1169 else
1170 OS << *AccessTy;
Evan Chengcdf43b12007-10-25 09:11:16 +00001171 }
1172
Dan Gohman572645c2010-02-12 10:34:29 +00001173 OS << ", Offsets={";
1174 for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
1175 E = Offsets.end(); I != E; ++I) {
1176 OS << *I;
Oscar Fuentesee56c422010-08-02 06:00:15 +00001177 if (llvm::next(I) != E)
Dan Gohman572645c2010-02-12 10:34:29 +00001178 OS << ',';
Dan Gohman7979b722010-01-22 00:46:49 +00001179 }
Dan Gohman572645c2010-02-12 10:34:29 +00001180 OS << '}';
Dan Gohman7979b722010-01-22 00:46:49 +00001181
Dan Gohman572645c2010-02-12 10:34:29 +00001182 if (AllFixupsOutsideLoop)
1183 OS << ", all-fixups-outside-loop";
Dan Gohmana9db1292010-07-15 20:24:58 +00001184
1185 if (WidestFixupType)
1186 OS << ", widest fixup type: " << *WidestFixupType;
Dan Gohman7979b722010-01-22 00:46:49 +00001187}
1188
Dan Gohman572645c2010-02-12 10:34:29 +00001189void LSRUse::dump() const {
1190 print(errs()); errs() << '\n';
1191}
Dan Gohman7979b722010-01-22 00:46:49 +00001192
Dan Gohman572645c2010-02-12 10:34:29 +00001193/// isLegalUse - Test whether the use described by AM is "legal", meaning it can
1194/// be completely folded into the user instruction at isel time. This includes
1195/// address-mode folding and special icmp tricks.
1196static bool isLegalUse(const TargetLowering::AddrMode &AM,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001197 LSRUse::KindType Kind, Type *AccessTy,
Dan Gohman572645c2010-02-12 10:34:29 +00001198 const TargetLowering *TLI) {
1199 switch (Kind) {
1200 case LSRUse::Address:
1201 // If we have low-level target information, ask the target if it can
1202 // completely fold this address.
1203 if (TLI) return TLI->isLegalAddressingMode(AM, AccessTy);
1204
1205 // Otherwise, just guess that reg+reg addressing is legal.
1206 return !AM.BaseGV && AM.BaseOffs == 0 && AM.Scale <= 1;
1207
1208 case LSRUse::ICmpZero:
1209 // There's not even a target hook for querying whether it would be legal to
1210 // fold a GV into an ICmp.
1211 if (AM.BaseGV)
1212 return false;
1213
1214 // ICmp only has two operands; don't allow more than two non-trivial parts.
1215 if (AM.Scale != 0 && AM.HasBaseReg && AM.BaseOffs != 0)
1216 return false;
1217
1218 // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by
1219 // putting the scaled register in the other operand of the icmp.
1220 if (AM.Scale != 0 && AM.Scale != -1)
1221 return false;
1222
1223 // If we have low-level target information, ask the target if it can fold an
1224 // integer immediate on an icmp.
1225 if (AM.BaseOffs != 0) {
Eli Friedmandae36ba2011-10-13 23:48:33 +00001226 if (TLI) return TLI->isLegalICmpImmediate(-(uint64_t)AM.BaseOffs);
Dan Gohman572645c2010-02-12 10:34:29 +00001227 return false;
Dan Gohman7979b722010-01-22 00:46:49 +00001228 }
Dan Gohman572645c2010-02-12 10:34:29 +00001229
1230 return true;
1231
1232 case LSRUse::Basic:
1233 // Only handle single-register values.
1234 return !AM.BaseGV && AM.Scale == 0 && AM.BaseOffs == 0;
1235
1236 case LSRUse::Special:
1237 // Only handle -1 scales, or no scale.
1238 return AM.Scale == 0 || AM.Scale == -1;
Dan Gohman7979b722010-01-22 00:46:49 +00001239 }
1240
Dan Gohman7979b722010-01-22 00:46:49 +00001241 return false;
1242}
1243
Dan Gohman572645c2010-02-12 10:34:29 +00001244static bool isLegalUse(TargetLowering::AddrMode AM,
1245 int64_t MinOffset, int64_t MaxOffset,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001246 LSRUse::KindType Kind, Type *AccessTy,
Dan Gohman572645c2010-02-12 10:34:29 +00001247 const TargetLowering *TLI) {
1248 // Check for overflow.
1249 if (((int64_t)((uint64_t)AM.BaseOffs + MinOffset) > AM.BaseOffs) !=
1250 (MinOffset > 0))
1251 return false;
1252 AM.BaseOffs = (uint64_t)AM.BaseOffs + MinOffset;
1253 if (isLegalUse(AM, Kind, AccessTy, TLI)) {
1254 AM.BaseOffs = (uint64_t)AM.BaseOffs - MinOffset;
1255 // Check for overflow.
1256 if (((int64_t)((uint64_t)AM.BaseOffs + MaxOffset) > AM.BaseOffs) !=
1257 (MaxOffset > 0))
1258 return false;
1259 AM.BaseOffs = (uint64_t)AM.BaseOffs + MaxOffset;
1260 return isLegalUse(AM, Kind, AccessTy, TLI);
Dan Gohman7979b722010-01-22 00:46:49 +00001261 }
Dan Gohman572645c2010-02-12 10:34:29 +00001262 return false;
Dan Gohman7979b722010-01-22 00:46:49 +00001263}
1264
Dan Gohman572645c2010-02-12 10:34:29 +00001265static bool isAlwaysFoldable(int64_t BaseOffs,
1266 GlobalValue *BaseGV,
1267 bool HasBaseReg,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001268 LSRUse::KindType Kind, Type *AccessTy,
Dan Gohman454d26d2010-02-22 04:11:59 +00001269 const TargetLowering *TLI) {
Dan Gohman572645c2010-02-12 10:34:29 +00001270 // Fast-path: zero is always foldable.
1271 if (BaseOffs == 0 && !BaseGV) return true;
Dan Gohman7979b722010-01-22 00:46:49 +00001272
Dan Gohman572645c2010-02-12 10:34:29 +00001273 // Conservatively, create an address with an immediate and a
1274 // base and a scale.
1275 TargetLowering::AddrMode AM;
1276 AM.BaseOffs = BaseOffs;
1277 AM.BaseGV = BaseGV;
1278 AM.HasBaseReg = HasBaseReg;
1279 AM.Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
Dan Gohman7979b722010-01-22 00:46:49 +00001280
Dan Gohmana2086b32010-05-19 23:43:12 +00001281 // Canonicalize a scale of 1 to a base register if the formula doesn't
1282 // already have a base register.
1283 if (!AM.HasBaseReg && AM.Scale == 1) {
1284 AM.Scale = 0;
1285 AM.HasBaseReg = true;
1286 }
1287
Dan Gohman572645c2010-02-12 10:34:29 +00001288 return isLegalUse(AM, Kind, AccessTy, TLI);
Dan Gohman7979b722010-01-22 00:46:49 +00001289}
1290
Dan Gohman572645c2010-02-12 10:34:29 +00001291static bool isAlwaysFoldable(const SCEV *S,
1292 int64_t MinOffset, int64_t MaxOffset,
1293 bool HasBaseReg,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001294 LSRUse::KindType Kind, Type *AccessTy,
Dan Gohman572645c2010-02-12 10:34:29 +00001295 const TargetLowering *TLI,
1296 ScalarEvolution &SE) {
1297 // Fast-path: zero is always foldable.
1298 if (S->isZero()) return true;
1299
1300 // Conservatively, create an address with an immediate and a
1301 // base and a scale.
1302 int64_t BaseOffs = ExtractImmediate(S, SE);
1303 GlobalValue *BaseGV = ExtractSymbol(S, SE);
1304
1305 // If there's anything else involved, it's not foldable.
1306 if (!S->isZero()) return false;
1307
1308 // Fast-path: zero is always foldable.
1309 if (BaseOffs == 0 && !BaseGV) return true;
1310
1311 // Conservatively, create an address with an immediate and a
1312 // base and a scale.
1313 TargetLowering::AddrMode AM;
1314 AM.BaseOffs = BaseOffs;
1315 AM.BaseGV = BaseGV;
1316 AM.HasBaseReg = HasBaseReg;
1317 AM.Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1318
1319 return isLegalUse(AM, MinOffset, MaxOffset, Kind, AccessTy, TLI);
Dan Gohman7979b722010-01-22 00:46:49 +00001320}
1321
Dan Gohmanb6211712010-06-19 21:21:39 +00001322namespace {
1323
Dan Gohman1e3121c2010-06-19 21:29:59 +00001324/// UseMapDenseMapInfo - A DenseMapInfo implementation for holding
1325/// DenseMaps and DenseSets of pairs of const SCEV* and LSRUse::Kind.
1326struct UseMapDenseMapInfo {
1327 static std::pair<const SCEV *, LSRUse::KindType> getEmptyKey() {
1328 return std::make_pair(reinterpret_cast<const SCEV *>(-1), LSRUse::Basic);
1329 }
1330
1331 static std::pair<const SCEV *, LSRUse::KindType> getTombstoneKey() {
1332 return std::make_pair(reinterpret_cast<const SCEV *>(-2), LSRUse::Basic);
1333 }
1334
1335 static unsigned
1336 getHashValue(const std::pair<const SCEV *, LSRUse::KindType> &V) {
1337 unsigned Result = DenseMapInfo<const SCEV *>::getHashValue(V.first);
1338 Result ^= DenseMapInfo<unsigned>::getHashValue(unsigned(V.second));
1339 return Result;
1340 }
1341
1342 static bool isEqual(const std::pair<const SCEV *, LSRUse::KindType> &LHS,
1343 const std::pair<const SCEV *, LSRUse::KindType> &RHS) {
1344 return LHS == RHS;
1345 }
1346};
1347
Andrew Trick6c7d0ae2012-01-09 19:50:34 +00001348/// IVInc - An individual increment in a Chain of IV increments.
1349/// Relate an IV user to an expression that computes the IV it uses from the IV
1350/// used by the previous link in the Chain.
1351///
1352/// For the head of a chain, IncExpr holds the absolute SCEV expression for the
1353/// original IVOperand. The head of the chain's IVOperand is only valid during
1354/// chain collection, before LSR replaces IV users. During chain generation,
1355/// IncExpr can be used to find the new IVOperand that computes the same
1356/// expression.
1357struct IVInc {
1358 Instruction *UserInst;
1359 Value* IVOperand;
1360 const SCEV *IncExpr;
1361
1362 IVInc(Instruction *U, Value *O, const SCEV *E):
1363 UserInst(U), IVOperand(O), IncExpr(E) {}
1364};
1365
1366// IVChain - The list of IV increments in program order.
1367// We typically add the head of a chain without finding subsequent links.
1368typedef SmallVector<IVInc,1> IVChain;
1369
1370/// ChainUsers - Helper for CollectChains to track multiple IV increment uses.
1371/// Distinguish between FarUsers that definitely cross IV increments and
1372/// NearUsers that may be used between IV increments.
1373struct ChainUsers {
1374 SmallPtrSet<Instruction*, 4> FarUsers;
1375 SmallPtrSet<Instruction*, 4> NearUsers;
1376};
1377
Dan Gohman572645c2010-02-12 10:34:29 +00001378/// LSRInstance - This class holds state for the main loop strength reduction
1379/// logic.
1380class LSRInstance {
1381 IVUsers &IU;
1382 ScalarEvolution &SE;
1383 DominatorTree &DT;
Dan Gohmane5f76872010-04-09 22:07:05 +00001384 LoopInfo &LI;
Dan Gohman572645c2010-02-12 10:34:29 +00001385 const TargetLowering *const TLI;
1386 Loop *const L;
1387 bool Changed;
1388
1389 /// IVIncInsertPos - This is the insert position that the current loop's
1390 /// induction variable increment should be placed. In simple loops, this is
1391 /// the latch block's terminator. But in more complicated cases, this is a
1392 /// position which will dominate all the in-loop post-increment users.
1393 Instruction *IVIncInsertPos;
1394
1395 /// Factors - Interesting factors between use strides.
1396 SmallSetVector<int64_t, 8> Factors;
1397
1398 /// Types - Interesting use types, to facilitate truncation reuse.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001399 SmallSetVector<Type *, 4> Types;
Dan Gohman572645c2010-02-12 10:34:29 +00001400
1401 /// Fixups - The list of operands which are to be replaced.
1402 SmallVector<LSRFixup, 16> Fixups;
1403
1404 /// Uses - The list of interesting uses.
1405 SmallVector<LSRUse, 16> Uses;
1406
1407 /// RegUses - Track which uses use which register candidates.
1408 RegUseTracker RegUses;
1409
Andrew Trick6c7d0ae2012-01-09 19:50:34 +00001410 // Limit the number of chains to avoid quadratic behavior. We don't expect to
1411 // have more than a few IV increment chains in a loop. Missing a Chain falls
1412 // back to normal LSR behavior for those uses.
1413 static const unsigned MaxChains = 8;
1414
1415 /// IVChainVec - IV users can form a chain of IV increments.
1416 SmallVector<IVChain, MaxChains> IVChainVec;
1417
Dan Gohman572645c2010-02-12 10:34:29 +00001418 void OptimizeShadowIV();
1419 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse);
1420 ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse);
Dan Gohmanc6519f92010-05-20 20:05:31 +00001421 void OptimizeLoopTermCond();
Dan Gohman572645c2010-02-12 10:34:29 +00001422
Andrew Trick6c7d0ae2012-01-09 19:50:34 +00001423 void ChainInstruction(Instruction *UserInst, Instruction *IVOper,
1424 SmallVectorImpl<ChainUsers> &ChainUsersVec);
1425 void CollectChains();
1426
Dan Gohman572645c2010-02-12 10:34:29 +00001427 void CollectInterestingTypesAndFactors();
1428 void CollectFixupsAndInitialFormulae();
1429
1430 LSRFixup &getNewFixup() {
1431 Fixups.push_back(LSRFixup());
1432 return Fixups.back();
1433 }
1434
1435 // Support for sharing of LSRUses between LSRFixups.
Dan Gohman1e3121c2010-06-19 21:29:59 +00001436 typedef DenseMap<std::pair<const SCEV *, LSRUse::KindType>,
1437 size_t,
1438 UseMapDenseMapInfo> UseMapTy;
Dan Gohman572645c2010-02-12 10:34:29 +00001439 UseMapTy UseMap;
1440
Dan Gohman191bd642010-09-01 01:45:53 +00001441 bool reconcileNewOffset(LSRUse &LU, int64_t NewOffset, bool HasBaseReg,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001442 LSRUse::KindType Kind, Type *AccessTy);
Dan Gohman572645c2010-02-12 10:34:29 +00001443
1444 std::pair<size_t, int64_t> getUse(const SCEV *&Expr,
1445 LSRUse::KindType Kind,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001446 Type *AccessTy);
Dan Gohman572645c2010-02-12 10:34:29 +00001447
Dan Gohmanc6897702010-10-07 23:33:43 +00001448 void DeleteUse(LSRUse &LU, size_t LUIdx);
Dan Gohman5ce6d052010-05-20 15:17:54 +00001449
Dan Gohman191bd642010-09-01 01:45:53 +00001450 LSRUse *FindUseWithSimilarFormula(const Formula &F, const LSRUse &OrigLU);
Dan Gohmana2086b32010-05-19 23:43:12 +00001451
Dan Gohman454d26d2010-02-22 04:11:59 +00001452 void InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
Dan Gohman572645c2010-02-12 10:34:29 +00001453 void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
1454 void CountRegisters(const Formula &F, size_t LUIdx);
1455 bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F);
1456
1457 void CollectLoopInvariantFixupsAndFormulae();
1458
1459 void GenerateReassociations(LSRUse &LU, unsigned LUIdx, Formula Base,
1460 unsigned Depth = 0);
1461 void GenerateCombinations(LSRUse &LU, unsigned LUIdx, Formula Base);
1462 void GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1463 void GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1464 void GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1465 void GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1466 void GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base);
1467 void GenerateCrossUseConstantOffsets();
1468 void GenerateAllReuseFormulae();
1469
1470 void FilterOutUndesirableDedicatedRegisters();
Dan Gohmand079c302010-05-18 22:51:59 +00001471
1472 size_t EstimateSearchSpaceComplexity() const;
Dan Gohman4aa5c2e2010-08-29 16:09:42 +00001473 void NarrowSearchSpaceByDetectingSupersets();
1474 void NarrowSearchSpaceByCollapsingUnrolledCode();
Dan Gohman4f7e18d2010-08-29 16:39:22 +00001475 void NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
Dan Gohman4aa5c2e2010-08-29 16:09:42 +00001476 void NarrowSearchSpaceByPickingWinnerRegs();
Dan Gohman572645c2010-02-12 10:34:29 +00001477 void NarrowSearchSpaceUsingHeuristics();
1478
1479 void SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
1480 Cost &SolutionCost,
1481 SmallVectorImpl<const Formula *> &Workspace,
1482 const Cost &CurCost,
1483 const SmallPtrSet<const SCEV *, 16> &CurRegs,
1484 DenseSet<const SCEV *> &VisitedRegs) const;
1485 void Solve(SmallVectorImpl<const Formula *> &Solution) const;
1486
Dan Gohmane5f76872010-04-09 22:07:05 +00001487 BasicBlock::iterator
1488 HoistInsertPosition(BasicBlock::iterator IP,
1489 const SmallVectorImpl<Instruction *> &Inputs) const;
1490 BasicBlock::iterator AdjustInsertPositionForExpand(BasicBlock::iterator IP,
1491 const LSRFixup &LF,
1492 const LSRUse &LU) const;
Dan Gohmand96eae82010-04-09 02:00:38 +00001493
Dan Gohman572645c2010-02-12 10:34:29 +00001494 Value *Expand(const LSRFixup &LF,
1495 const Formula &F,
Dan Gohman454d26d2010-02-22 04:11:59 +00001496 BasicBlock::iterator IP,
Dan Gohman572645c2010-02-12 10:34:29 +00001497 SCEVExpander &Rewriter,
Dan Gohman454d26d2010-02-22 04:11:59 +00001498 SmallVectorImpl<WeakVH> &DeadInsts) const;
Dan Gohman3a02cbc2010-02-16 20:25:07 +00001499 void RewriteForPHI(PHINode *PN, const LSRFixup &LF,
1500 const Formula &F,
Dan Gohman3a02cbc2010-02-16 20:25:07 +00001501 SCEVExpander &Rewriter,
1502 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman3a02cbc2010-02-16 20:25:07 +00001503 Pass *P) const;
Dan Gohman572645c2010-02-12 10:34:29 +00001504 void Rewrite(const LSRFixup &LF,
1505 const Formula &F,
Dan Gohman572645c2010-02-12 10:34:29 +00001506 SCEVExpander &Rewriter,
1507 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman572645c2010-02-12 10:34:29 +00001508 Pass *P) const;
1509 void ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
1510 Pass *P);
1511
Andrew Trickd56ef8d2011-12-13 00:55:33 +00001512public:
Dan Gohman572645c2010-02-12 10:34:29 +00001513 LSRInstance(const TargetLowering *tli, Loop *l, Pass *P);
1514
1515 bool getChanged() const { return Changed; }
1516
1517 void print_factors_and_types(raw_ostream &OS) const;
1518 void print_fixups(raw_ostream &OS) const;
1519 void print_uses(raw_ostream &OS) const;
1520 void print(raw_ostream &OS) const;
1521 void dump() const;
1522};
1523
1524}
1525
1526/// OptimizeShadowIV - If IV is used in a int-to-float cast
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001527/// inside the loop then try to eliminate the cast operation.
Dan Gohman572645c2010-02-12 10:34:29 +00001528void LSRInstance::OptimizeShadowIV() {
1529 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
1530 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1531 return;
1532
1533 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end();
1534 UI != E; /* empty */) {
1535 IVUsers::const_iterator CandidateUI = UI;
1536 ++UI;
1537 Instruction *ShadowUse = CandidateUI->getUser();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001538 Type *DestTy = NULL;
Andrew Trickc2c988e2011-07-21 01:05:01 +00001539 bool IsSigned = false;
Dan Gohman572645c2010-02-12 10:34:29 +00001540
1541 /* If shadow use is a int->float cast then insert a second IV
1542 to eliminate this cast.
1543
1544 for (unsigned i = 0; i < n; ++i)
1545 foo((double)i);
1546
1547 is transformed into
1548
1549 double d = 0.0;
1550 for (unsigned i = 0; i < n; ++i, ++d)
1551 foo(d);
1552 */
Andrew Trickc2c988e2011-07-21 01:05:01 +00001553 if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser())) {
1554 IsSigned = false;
Dan Gohman572645c2010-02-12 10:34:29 +00001555 DestTy = UCast->getDestTy();
Andrew Trickc2c988e2011-07-21 01:05:01 +00001556 }
1557 else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser())) {
1558 IsSigned = true;
Dan Gohman572645c2010-02-12 10:34:29 +00001559 DestTy = SCast->getDestTy();
Andrew Trickc2c988e2011-07-21 01:05:01 +00001560 }
Dan Gohman572645c2010-02-12 10:34:29 +00001561 if (!DestTy) continue;
1562
1563 if (TLI) {
1564 // If target does not support DestTy natively then do not apply
1565 // this transformation.
1566 EVT DVT = TLI->getValueType(DestTy);
1567 if (!TLI->isTypeLegal(DVT)) continue;
1568 }
1569
1570 PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
1571 if (!PH) continue;
1572 if (PH->getNumIncomingValues() != 2) continue;
1573
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001574 Type *SrcTy = PH->getType();
Dan Gohman572645c2010-02-12 10:34:29 +00001575 int Mantissa = DestTy->getFPMantissaWidth();
1576 if (Mantissa == -1) continue;
1577 if ((int)SE.getTypeSizeInBits(SrcTy) > Mantissa)
1578 continue;
1579
1580 unsigned Entry, Latch;
1581 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
1582 Entry = 0;
1583 Latch = 1;
Dan Gohman7979b722010-01-22 00:46:49 +00001584 } else {
Dan Gohman572645c2010-02-12 10:34:29 +00001585 Entry = 1;
1586 Latch = 0;
Dan Gohman7979b722010-01-22 00:46:49 +00001587 }
Dan Gohman7979b722010-01-22 00:46:49 +00001588
Dan Gohman572645c2010-02-12 10:34:29 +00001589 ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
1590 if (!Init) continue;
Andrew Trickc2c988e2011-07-21 01:05:01 +00001591 Constant *NewInit = ConstantFP::get(DestTy, IsSigned ?
Andrew Trickc205a092011-07-21 01:45:54 +00001592 (double)Init->getSExtValue() :
1593 (double)Init->getZExtValue());
Dan Gohman7979b722010-01-22 00:46:49 +00001594
Dan Gohman572645c2010-02-12 10:34:29 +00001595 BinaryOperator *Incr =
1596 dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
1597 if (!Incr) continue;
1598 if (Incr->getOpcode() != Instruction::Add
1599 && Incr->getOpcode() != Instruction::Sub)
Dan Gohman7979b722010-01-22 00:46:49 +00001600 continue;
Dan Gohman7979b722010-01-22 00:46:49 +00001601
Dan Gohman572645c2010-02-12 10:34:29 +00001602 /* Initialize new IV, double d = 0.0 in above example. */
1603 ConstantInt *C = NULL;
1604 if (Incr->getOperand(0) == PH)
1605 C = dyn_cast<ConstantInt>(Incr->getOperand(1));
1606 else if (Incr->getOperand(1) == PH)
1607 C = dyn_cast<ConstantInt>(Incr->getOperand(0));
Dan Gohman7979b722010-01-22 00:46:49 +00001608 else
Dan Gohman7979b722010-01-22 00:46:49 +00001609 continue;
1610
Dan Gohman572645c2010-02-12 10:34:29 +00001611 if (!C) continue;
Dan Gohman7979b722010-01-22 00:46:49 +00001612
Dan Gohman572645c2010-02-12 10:34:29 +00001613 // Ignore negative constants, as the code below doesn't handle them
1614 // correctly. TODO: Remove this restriction.
1615 if (!C->getValue().isStrictlyPositive()) continue;
Dan Gohman7979b722010-01-22 00:46:49 +00001616
Dan Gohman572645c2010-02-12 10:34:29 +00001617 /* Add new PHINode. */
Jay Foad3ecfc862011-03-30 11:28:46 +00001618 PHINode *NewPH = PHINode::Create(DestTy, 2, "IV.S.", PH);
Dan Gohman7979b722010-01-22 00:46:49 +00001619
Dan Gohman572645c2010-02-12 10:34:29 +00001620 /* create new increment. '++d' in above example. */
1621 Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue());
1622 BinaryOperator *NewIncr =
1623 BinaryOperator::Create(Incr->getOpcode() == Instruction::Add ?
1624 Instruction::FAdd : Instruction::FSub,
1625 NewPH, CFP, "IV.S.next.", Incr);
Dan Gohman7979b722010-01-22 00:46:49 +00001626
Dan Gohman572645c2010-02-12 10:34:29 +00001627 NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
1628 NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
Dan Gohman7979b722010-01-22 00:46:49 +00001629
Dan Gohman572645c2010-02-12 10:34:29 +00001630 /* Remove cast operation */
1631 ShadowUse->replaceAllUsesWith(NewPH);
1632 ShadowUse->eraseFromParent();
Dan Gohmanc6519f92010-05-20 20:05:31 +00001633 Changed = true;
Dan Gohman572645c2010-02-12 10:34:29 +00001634 break;
Dan Gohman7979b722010-01-22 00:46:49 +00001635 }
1636}
1637
1638/// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
1639/// set the IV user and stride information and return true, otherwise return
1640/// false.
Dan Gohmanea507f52010-05-20 19:44:23 +00001641bool LSRInstance::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse) {
Dan Gohman572645c2010-02-12 10:34:29 +00001642 for (IVUsers::iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
1643 if (UI->getUser() == Cond) {
1644 // NOTE: we could handle setcc instructions with multiple uses here, but
1645 // InstCombine does it as well for simple uses, it's not clear that it
1646 // occurs enough in real life to handle.
1647 CondUse = UI;
1648 return true;
1649 }
Dan Gohman7979b722010-01-22 00:46:49 +00001650 return false;
Evan Chengcdf43b12007-10-25 09:11:16 +00001651}
1652
Dan Gohman7979b722010-01-22 00:46:49 +00001653/// OptimizeMax - Rewrite the loop's terminating condition if it uses
1654/// a max computation.
1655///
1656/// This is a narrow solution to a specific, but acute, problem. For loops
1657/// like this:
1658///
1659/// i = 0;
1660/// do {
1661/// p[i] = 0.0;
1662/// } while (++i < n);
1663///
1664/// the trip count isn't just 'n', because 'n' might not be positive. And
1665/// unfortunately this can come up even for loops where the user didn't use
1666/// a C do-while loop. For example, seemingly well-behaved top-test loops
1667/// will commonly be lowered like this:
1668//
1669/// if (n > 0) {
1670/// i = 0;
1671/// do {
1672/// p[i] = 0.0;
1673/// } while (++i < n);
1674/// }
1675///
1676/// and then it's possible for subsequent optimization to obscure the if
1677/// test in such a way that indvars can't find it.
1678///
1679/// When indvars can't find the if test in loops like this, it creates a
1680/// max expression, which allows it to give the loop a canonical
1681/// induction variable:
1682///
1683/// i = 0;
1684/// max = n < 1 ? 1 : n;
1685/// do {
1686/// p[i] = 0.0;
1687/// } while (++i != max);
1688///
1689/// Canonical induction variables are necessary because the loop passes
1690/// are designed around them. The most obvious example of this is the
1691/// LoopInfo analysis, which doesn't remember trip count values. It
1692/// expects to be able to rediscover the trip count each time it is
Dan Gohman572645c2010-02-12 10:34:29 +00001693/// needed, and it does this using a simple analysis that only succeeds if
Dan Gohman7979b722010-01-22 00:46:49 +00001694/// the loop has a canonical induction variable.
1695///
1696/// However, when it comes time to generate code, the maximum operation
1697/// can be quite costly, especially if it's inside of an outer loop.
1698///
1699/// This function solves this problem by detecting this type of loop and
1700/// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
1701/// the instructions for the maximum computation.
1702///
Dan Gohman572645c2010-02-12 10:34:29 +00001703ICmpInst *LSRInstance::OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse) {
Dan Gohman7979b722010-01-22 00:46:49 +00001704 // Check that the loop matches the pattern we're looking for.
1705 if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
1706 Cond->getPredicate() != CmpInst::ICMP_NE)
1707 return Cond;
Dan Gohmana10756e2010-01-21 02:09:26 +00001708
Dan Gohman7979b722010-01-22 00:46:49 +00001709 SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
1710 if (!Sel || !Sel->hasOneUse()) return Cond;
Dan Gohmana10756e2010-01-21 02:09:26 +00001711
Dan Gohman572645c2010-02-12 10:34:29 +00001712 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
Dan Gohman7979b722010-01-22 00:46:49 +00001713 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1714 return Cond;
Dan Gohmandeff6212010-05-03 22:09:21 +00001715 const SCEV *One = SE.getConstant(BackedgeTakenCount->getType(), 1);
Dan Gohmana10756e2010-01-21 02:09:26 +00001716
Dan Gohman7979b722010-01-22 00:46:49 +00001717 // Add one to the backedge-taken count to get the trip count.
Dan Gohman4065f602010-08-16 15:39:27 +00001718 const SCEV *IterationCount = SE.getAddExpr(One, BackedgeTakenCount);
Dan Gohman1d367982010-04-24 03:13:44 +00001719 if (IterationCount != SE.getSCEV(Sel)) return Cond;
Dan Gohman7979b722010-01-22 00:46:49 +00001720
Dan Gohman1d367982010-04-24 03:13:44 +00001721 // Check for a max calculation that matches the pattern. There's no check
1722 // for ICMP_ULE here because the comparison would be with zero, which
1723 // isn't interesting.
1724 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1725 const SCEVNAryExpr *Max = 0;
1726 if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(BackedgeTakenCount)) {
1727 Pred = ICmpInst::ICMP_SLE;
1728 Max = S;
1729 } else if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(IterationCount)) {
1730 Pred = ICmpInst::ICMP_SLT;
1731 Max = S;
1732 } else if (const SCEVUMaxExpr *U = dyn_cast<SCEVUMaxExpr>(IterationCount)) {
1733 Pred = ICmpInst::ICMP_ULT;
1734 Max = U;
1735 } else {
1736 // No match; bail.
Dan Gohman7979b722010-01-22 00:46:49 +00001737 return Cond;
Dan Gohman1d367982010-04-24 03:13:44 +00001738 }
Dan Gohman7979b722010-01-22 00:46:49 +00001739
1740 // To handle a max with more than two operands, this optimization would
1741 // require additional checking and setup.
1742 if (Max->getNumOperands() != 2)
1743 return Cond;
1744
1745 const SCEV *MaxLHS = Max->getOperand(0);
1746 const SCEV *MaxRHS = Max->getOperand(1);
Dan Gohman1d367982010-04-24 03:13:44 +00001747
1748 // ScalarEvolution canonicalizes constants to the left. For < and >, look
1749 // for a comparison with 1. For <= and >=, a comparison with zero.
1750 if (!MaxLHS ||
1751 (ICmpInst::isTrueWhenEqual(Pred) ? !MaxLHS->isZero() : (MaxLHS != One)))
1752 return Cond;
1753
Dan Gohman7979b722010-01-22 00:46:49 +00001754 // Check the relevant induction variable for conformance to
1755 // the pattern.
Dan Gohman572645c2010-02-12 10:34:29 +00001756 const SCEV *IV = SE.getSCEV(Cond->getOperand(0));
Dan Gohman7979b722010-01-22 00:46:49 +00001757 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
1758 if (!AR || !AR->isAffine() ||
1759 AR->getStart() != One ||
Dan Gohman572645c2010-02-12 10:34:29 +00001760 AR->getStepRecurrence(SE) != One)
Dan Gohman7979b722010-01-22 00:46:49 +00001761 return Cond;
1762
1763 assert(AR->getLoop() == L &&
1764 "Loop condition operand is an addrec in a different loop!");
1765
1766 // Check the right operand of the select, and remember it, as it will
1767 // be used in the new comparison instruction.
1768 Value *NewRHS = 0;
Dan Gohman1d367982010-04-24 03:13:44 +00001769 if (ICmpInst::isTrueWhenEqual(Pred)) {
1770 // Look for n+1, and grab n.
1771 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(1)))
1772 if (isa<ConstantInt>(BO->getOperand(1)) &&
1773 cast<ConstantInt>(BO->getOperand(1))->isOne() &&
1774 SE.getSCEV(BO->getOperand(0)) == MaxRHS)
1775 NewRHS = BO->getOperand(0);
1776 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(2)))
1777 if (isa<ConstantInt>(BO->getOperand(1)) &&
1778 cast<ConstantInt>(BO->getOperand(1))->isOne() &&
1779 SE.getSCEV(BO->getOperand(0)) == MaxRHS)
1780 NewRHS = BO->getOperand(0);
1781 if (!NewRHS)
1782 return Cond;
1783 } else if (SE.getSCEV(Sel->getOperand(1)) == MaxRHS)
Dan Gohman7979b722010-01-22 00:46:49 +00001784 NewRHS = Sel->getOperand(1);
Dan Gohman572645c2010-02-12 10:34:29 +00001785 else if (SE.getSCEV(Sel->getOperand(2)) == MaxRHS)
Dan Gohman7979b722010-01-22 00:46:49 +00001786 NewRHS = Sel->getOperand(2);
Dan Gohmancaf71ab2010-06-22 23:07:13 +00001787 else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(MaxRHS))
1788 NewRHS = SU->getValue();
Dan Gohman1d367982010-04-24 03:13:44 +00001789 else
Dan Gohmancaf71ab2010-06-22 23:07:13 +00001790 // Max doesn't match expected pattern.
1791 return Cond;
Dan Gohman7979b722010-01-22 00:46:49 +00001792
1793 // Determine the new comparison opcode. It may be signed or unsigned,
1794 // and the original comparison may be either equality or inequality.
Dan Gohman7979b722010-01-22 00:46:49 +00001795 if (Cond->getPredicate() == CmpInst::ICMP_EQ)
1796 Pred = CmpInst::getInversePredicate(Pred);
1797
1798 // Ok, everything looks ok to change the condition into an SLT or SGE and
1799 // delete the max calculation.
1800 ICmpInst *NewCond =
1801 new ICmpInst(Cond, Pred, Cond->getOperand(0), NewRHS, "scmp");
1802
1803 // Delete the max calculation instructions.
1804 Cond->replaceAllUsesWith(NewCond);
1805 CondUse->setUser(NewCond);
1806 Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
1807 Cond->eraseFromParent();
1808 Sel->eraseFromParent();
1809 if (Cmp->use_empty())
1810 Cmp->eraseFromParent();
1811 return NewCond;
Dan Gohmanad7321f2008-09-15 21:22:06 +00001812}
1813
Jim Grosbach56a1f802009-11-17 17:53:56 +00001814/// OptimizeLoopTermCond - Change loop terminating condition to use the
Evan Cheng586f69a2009-11-12 07:35:05 +00001815/// postinc iv when possible.
Dan Gohmanc6519f92010-05-20 20:05:31 +00001816void
Dan Gohman572645c2010-02-12 10:34:29 +00001817LSRInstance::OptimizeLoopTermCond() {
1818 SmallPtrSet<Instruction *, 4> PostIncs;
1819
Evan Cheng586f69a2009-11-12 07:35:05 +00001820 BasicBlock *LatchBlock = L->getLoopLatch();
Evan Cheng076e0852009-11-17 18:10:11 +00001821 SmallVector<BasicBlock*, 8> ExitingBlocks;
1822 L->getExitingBlocks(ExitingBlocks);
Jim Grosbach56a1f802009-11-17 17:53:56 +00001823
Evan Cheng076e0852009-11-17 18:10:11 +00001824 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
1825 BasicBlock *ExitingBlock = ExitingBlocks[i];
Evan Cheng586f69a2009-11-12 07:35:05 +00001826
Dan Gohman572645c2010-02-12 10:34:29 +00001827 // Get the terminating condition for the loop if possible. If we
Evan Cheng076e0852009-11-17 18:10:11 +00001828 // can, we want to change it to use a post-incremented version of its
1829 // induction variable, to allow coalescing the live ranges for the IV into
1830 // one register value.
Evan Cheng586f69a2009-11-12 07:35:05 +00001831
Evan Cheng076e0852009-11-17 18:10:11 +00001832 BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1833 if (!TermBr)
1834 continue;
1835 // FIXME: Overly conservative, termination condition could be an 'or' etc..
1836 if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
1837 continue;
Evan Cheng586f69a2009-11-12 07:35:05 +00001838
Evan Cheng076e0852009-11-17 18:10:11 +00001839 // Search IVUsesByStride to find Cond's IVUse if there is one.
1840 IVStrideUse *CondUse = 0;
Evan Cheng076e0852009-11-17 18:10:11 +00001841 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
Dan Gohman572645c2010-02-12 10:34:29 +00001842 if (!FindIVUserForCond(Cond, CondUse))
Evan Cheng076e0852009-11-17 18:10:11 +00001843 continue;
1844
Evan Cheng076e0852009-11-17 18:10:11 +00001845 // If the trip count is computed in terms of a max (due to ScalarEvolution
1846 // being unable to find a sufficient guard, for example), change the loop
1847 // comparison to use SLT or ULT instead of NE.
Dan Gohman572645c2010-02-12 10:34:29 +00001848 // One consequence of doing this now is that it disrupts the count-down
1849 // optimization. That's not always a bad thing though, because in such
1850 // cases it may still be worthwhile to avoid a max.
1851 Cond = OptimizeMax(Cond, CondUse);
Evan Cheng076e0852009-11-17 18:10:11 +00001852
Dan Gohman572645c2010-02-12 10:34:29 +00001853 // If this exiting block dominates the latch block, it may also use
1854 // the post-inc value if it won't be shared with other uses.
1855 // Check for dominance.
1856 if (!DT.dominates(ExitingBlock, LatchBlock))
Dan Gohman7979b722010-01-22 00:46:49 +00001857 continue;
Evan Cheng076e0852009-11-17 18:10:11 +00001858
Dan Gohman572645c2010-02-12 10:34:29 +00001859 // Conservatively avoid trying to use the post-inc value in non-latch
1860 // exits if there may be pre-inc users in intervening blocks.
Dan Gohman590bfe82010-02-14 03:21:49 +00001861 if (LatchBlock != ExitingBlock)
Dan Gohman572645c2010-02-12 10:34:29 +00001862 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
1863 // Test if the use is reachable from the exiting block. This dominator
1864 // query is a conservative approximation of reachability.
1865 if (&*UI != CondUse &&
1866 !DT.properlyDominates(UI->getUser()->getParent(), ExitingBlock)) {
1867 // Conservatively assume there may be reuse if the quotient of their
1868 // strides could be a legal scale.
Dan Gohmanc0564542010-04-19 21:48:58 +00001869 const SCEV *A = IU.getStride(*CondUse, L);
1870 const SCEV *B = IU.getStride(*UI, L);
Dan Gohman448db1c2010-04-07 22:27:08 +00001871 if (!A || !B) continue;
Dan Gohman572645c2010-02-12 10:34:29 +00001872 if (SE.getTypeSizeInBits(A->getType()) !=
1873 SE.getTypeSizeInBits(B->getType())) {
1874 if (SE.getTypeSizeInBits(A->getType()) >
1875 SE.getTypeSizeInBits(B->getType()))
1876 B = SE.getSignExtendExpr(B, A->getType());
1877 else
1878 A = SE.getSignExtendExpr(A, B->getType());
1879 }
1880 if (const SCEVConstant *D =
Dan Gohmanf09b7122010-02-19 19:35:48 +00001881 dyn_cast_or_null<SCEVConstant>(getExactSDiv(B, A, SE))) {
Dan Gohman9f383eb2010-05-20 22:25:20 +00001882 const ConstantInt *C = D->getValue();
Dan Gohman572645c2010-02-12 10:34:29 +00001883 // Stride of one or negative one can have reuse with non-addresses.
Dan Gohman9f383eb2010-05-20 22:25:20 +00001884 if (C->isOne() || C->isAllOnesValue())
Dan Gohman572645c2010-02-12 10:34:29 +00001885 goto decline_post_inc;
1886 // Avoid weird situations.
Dan Gohman9f383eb2010-05-20 22:25:20 +00001887 if (C->getValue().getMinSignedBits() >= 64 ||
1888 C->getValue().isMinSignedValue())
Dan Gohman572645c2010-02-12 10:34:29 +00001889 goto decline_post_inc;
Dan Gohman590bfe82010-02-14 03:21:49 +00001890 // Without TLI, assume that any stride might be valid, and so any
1891 // use might be shared.
1892 if (!TLI)
1893 goto decline_post_inc;
Dan Gohman572645c2010-02-12 10:34:29 +00001894 // Check for possible scaled-address reuse.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001895 Type *AccessTy = getAccessType(UI->getUser());
Dan Gohman572645c2010-02-12 10:34:29 +00001896 TargetLowering::AddrMode AM;
Dan Gohman9f383eb2010-05-20 22:25:20 +00001897 AM.Scale = C->getSExtValue();
Dan Gohman2763dfd2010-02-14 02:45:21 +00001898 if (TLI->isLegalAddressingMode(AM, AccessTy))
Dan Gohman572645c2010-02-12 10:34:29 +00001899 goto decline_post_inc;
1900 AM.Scale = -AM.Scale;
Dan Gohman2763dfd2010-02-14 02:45:21 +00001901 if (TLI->isLegalAddressingMode(AM, AccessTy))
Dan Gohman572645c2010-02-12 10:34:29 +00001902 goto decline_post_inc;
1903 }
1904 }
1905
David Greene63c94632009-12-23 22:58:38 +00001906 DEBUG(dbgs() << " Change loop exiting icmp to use postinc iv: "
Dan Gohman572645c2010-02-12 10:34:29 +00001907 << *Cond << '\n');
Evan Cheng076e0852009-11-17 18:10:11 +00001908
1909 // It's possible for the setcc instruction to be anywhere in the loop, and
1910 // possible for it to have multiple users. If it is not immediately before
1911 // the exiting block branch, move it.
Dan Gohman572645c2010-02-12 10:34:29 +00001912 if (&*++BasicBlock::iterator(Cond) != TermBr) {
1913 if (Cond->hasOneUse()) {
Evan Cheng076e0852009-11-17 18:10:11 +00001914 Cond->moveBefore(TermBr);
1915 } else {
Dan Gohman572645c2010-02-12 10:34:29 +00001916 // Clone the terminating condition and insert into the loopend.
1917 ICmpInst *OldCond = Cond;
Evan Cheng076e0852009-11-17 18:10:11 +00001918 Cond = cast<ICmpInst>(Cond->clone());
1919 Cond->setName(L->getHeader()->getName() + ".termcond");
1920 ExitingBlock->getInstList().insert(TermBr, Cond);
1921
1922 // Clone the IVUse, as the old use still exists!
Andrew Trick4417e532011-06-21 15:43:52 +00001923 CondUse = &IU.AddUser(Cond, CondUse->getOperandValToReplace());
Dan Gohman572645c2010-02-12 10:34:29 +00001924 TermBr->replaceUsesOfWith(OldCond, Cond);
Evan Cheng076e0852009-11-17 18:10:11 +00001925 }
Evan Cheng586f69a2009-11-12 07:35:05 +00001926 }
1927
Evan Cheng076e0852009-11-17 18:10:11 +00001928 // If we get to here, we know that we can transform the setcc instruction to
1929 // use the post-incremented version of the IV, allowing us to coalesce the
1930 // live ranges for the IV correctly.
Dan Gohman448db1c2010-04-07 22:27:08 +00001931 CondUse->transformToPostInc(L);
Evan Cheng076e0852009-11-17 18:10:11 +00001932 Changed = true;
1933
Dan Gohman572645c2010-02-12 10:34:29 +00001934 PostIncs.insert(Cond);
1935 decline_post_inc:;
Dan Gohmana10756e2010-01-21 02:09:26 +00001936 }
Dan Gohman572645c2010-02-12 10:34:29 +00001937
1938 // Determine an insertion point for the loop induction variable increment. It
1939 // must dominate all the post-inc comparisons we just set up, and it must
1940 // dominate the loop latch edge.
1941 IVIncInsertPos = L->getLoopLatch()->getTerminator();
1942 for (SmallPtrSet<Instruction *, 4>::const_iterator I = PostIncs.begin(),
1943 E = PostIncs.end(); I != E; ++I) {
1944 BasicBlock *BB =
1945 DT.findNearestCommonDominator(IVIncInsertPos->getParent(),
1946 (*I)->getParent());
1947 if (BB == (*I)->getParent())
1948 IVIncInsertPos = *I;
1949 else if (BB != IVIncInsertPos->getParent())
1950 IVIncInsertPos = BB->getTerminator();
1951 }
Dan Gohmana10756e2010-01-21 02:09:26 +00001952}
1953
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001954/// reconcileNewOffset - Determine if the given use can accommodate a fixup
Dan Gohman76c315a2010-05-20 20:52:00 +00001955/// at the given offset and other details. If so, update the use and
1956/// return true.
Dan Gohman572645c2010-02-12 10:34:29 +00001957bool
Dan Gohman191bd642010-09-01 01:45:53 +00001958LSRInstance::reconcileNewOffset(LSRUse &LU, int64_t NewOffset, bool HasBaseReg,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001959 LSRUse::KindType Kind, Type *AccessTy) {
Dan Gohman191bd642010-09-01 01:45:53 +00001960 int64_t NewMinOffset = LU.MinOffset;
1961 int64_t NewMaxOffset = LU.MaxOffset;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001962 Type *NewAccessTy = AccessTy;
Dan Gohman7979b722010-01-22 00:46:49 +00001963
Dan Gohman572645c2010-02-12 10:34:29 +00001964 // Check for a mismatched kind. It's tempting to collapse mismatched kinds to
1965 // something conservative, however this can pessimize in the case that one of
1966 // the uses will have all its uses outside the loop, for example.
1967 if (LU.Kind != Kind)
Dan Gohman7979b722010-01-22 00:46:49 +00001968 return false;
Dan Gohman572645c2010-02-12 10:34:29 +00001969 // Conservatively assume HasBaseReg is true for now.
Dan Gohman191bd642010-09-01 01:45:53 +00001970 if (NewOffset < LU.MinOffset) {
1971 if (!isAlwaysFoldable(LU.MaxOffset - NewOffset, 0, HasBaseReg,
Dan Gohman454d26d2010-02-22 04:11:59 +00001972 Kind, AccessTy, TLI))
Dan Gohman7979b722010-01-22 00:46:49 +00001973 return false;
Dan Gohman191bd642010-09-01 01:45:53 +00001974 NewMinOffset = NewOffset;
1975 } else if (NewOffset > LU.MaxOffset) {
1976 if (!isAlwaysFoldable(NewOffset - LU.MinOffset, 0, HasBaseReg,
Dan Gohman454d26d2010-02-22 04:11:59 +00001977 Kind, AccessTy, TLI))
Dan Gohman7979b722010-01-22 00:46:49 +00001978 return false;
Dan Gohman191bd642010-09-01 01:45:53 +00001979 NewMaxOffset = NewOffset;
Dan Gohmana10756e2010-01-21 02:09:26 +00001980 }
Dan Gohman572645c2010-02-12 10:34:29 +00001981 // Check for a mismatched access type, and fall back conservatively as needed.
Dan Gohman74e5ef02010-06-19 21:30:18 +00001982 // TODO: Be less conservative when the type is similar and can use the same
1983 // addressing modes.
Dan Gohman572645c2010-02-12 10:34:29 +00001984 if (Kind == LSRUse::Address && AccessTy != LU.AccessTy)
Dan Gohman191bd642010-09-01 01:45:53 +00001985 NewAccessTy = Type::getVoidTy(AccessTy->getContext());
Dan Gohmana10756e2010-01-21 02:09:26 +00001986
Dan Gohman572645c2010-02-12 10:34:29 +00001987 // Update the use.
Dan Gohman191bd642010-09-01 01:45:53 +00001988 LU.MinOffset = NewMinOffset;
1989 LU.MaxOffset = NewMaxOffset;
1990 LU.AccessTy = NewAccessTy;
1991 if (NewOffset != LU.Offsets.back())
1992 LU.Offsets.push_back(NewOffset);
Dan Gohman8b0ade32010-01-21 22:42:49 +00001993 return true;
1994}
1995
Dan Gohman572645c2010-02-12 10:34:29 +00001996/// getUse - Return an LSRUse index and an offset value for a fixup which
1997/// needs the given expression, with the given kind and optional access type.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001998/// Either reuse an existing use or create a new one, as needed.
Dan Gohman572645c2010-02-12 10:34:29 +00001999std::pair<size_t, int64_t>
2000LSRInstance::getUse(const SCEV *&Expr,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002001 LSRUse::KindType Kind, Type *AccessTy) {
Dan Gohman572645c2010-02-12 10:34:29 +00002002 const SCEV *Copy = Expr;
2003 int64_t Offset = ExtractImmediate(Expr, SE);
Evan Cheng586f69a2009-11-12 07:35:05 +00002004
Dan Gohman572645c2010-02-12 10:34:29 +00002005 // Basic uses can't accept any offset, for example.
Dan Gohman454d26d2010-02-22 04:11:59 +00002006 if (!isAlwaysFoldable(Offset, 0, /*HasBaseReg=*/true, Kind, AccessTy, TLI)) {
Dan Gohman572645c2010-02-12 10:34:29 +00002007 Expr = Copy;
2008 Offset = 0;
2009 }
2010
2011 std::pair<UseMapTy::iterator, bool> P =
Dan Gohman1e3121c2010-06-19 21:29:59 +00002012 UseMap.insert(std::make_pair(std::make_pair(Expr, Kind), 0));
Dan Gohman572645c2010-02-12 10:34:29 +00002013 if (!P.second) {
2014 // A use already existed with this base.
2015 size_t LUIdx = P.first->second;
2016 LSRUse &LU = Uses[LUIdx];
Dan Gohman191bd642010-09-01 01:45:53 +00002017 if (reconcileNewOffset(LU, Offset, /*HasBaseReg=*/true, Kind, AccessTy))
Dan Gohman572645c2010-02-12 10:34:29 +00002018 // Reuse this use.
2019 return std::make_pair(LUIdx, Offset);
2020 }
2021
2022 // Create a new use.
2023 size_t LUIdx = Uses.size();
2024 P.first->second = LUIdx;
2025 Uses.push_back(LSRUse(Kind, AccessTy));
2026 LSRUse &LU = Uses[LUIdx];
2027
Dan Gohman191bd642010-09-01 01:45:53 +00002028 // We don't need to track redundant offsets, but we don't need to go out
2029 // of our way here to avoid them.
2030 if (LU.Offsets.empty() || Offset != LU.Offsets.back())
2031 LU.Offsets.push_back(Offset);
2032
Dan Gohman572645c2010-02-12 10:34:29 +00002033 LU.MinOffset = Offset;
2034 LU.MaxOffset = Offset;
2035 return std::make_pair(LUIdx, Offset);
2036}
2037
Dan Gohman5ce6d052010-05-20 15:17:54 +00002038/// DeleteUse - Delete the given use from the Uses list.
Dan Gohmanc6897702010-10-07 23:33:43 +00002039void LSRInstance::DeleteUse(LSRUse &LU, size_t LUIdx) {
Dan Gohman191bd642010-09-01 01:45:53 +00002040 if (&LU != &Uses.back())
Dan Gohman5ce6d052010-05-20 15:17:54 +00002041 std::swap(LU, Uses.back());
2042 Uses.pop_back();
Dan Gohmanc6897702010-10-07 23:33:43 +00002043
2044 // Update RegUses.
2045 RegUses.SwapAndDropUse(LUIdx, Uses.size());
Dan Gohman5ce6d052010-05-20 15:17:54 +00002046}
2047
Dan Gohmana2086b32010-05-19 23:43:12 +00002048/// FindUseWithFormula - Look for a use distinct from OrigLU which is has
2049/// a formula that has the same registers as the given formula.
2050LSRUse *
2051LSRInstance::FindUseWithSimilarFormula(const Formula &OrigF,
Dan Gohman191bd642010-09-01 01:45:53 +00002052 const LSRUse &OrigLU) {
2053 // Search all uses for the formula. This could be more clever.
Dan Gohmana2086b32010-05-19 23:43:12 +00002054 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2055 LSRUse &LU = Uses[LUIdx];
Dan Gohman6a832712010-08-29 15:27:08 +00002056 // Check whether this use is close enough to OrigLU, to see whether it's
2057 // worthwhile looking through its formulae.
2058 // Ignore ICmpZero uses because they may contain formulae generated by
2059 // GenerateICmpZeroScales, in which case adding fixup offsets may
2060 // be invalid.
Dan Gohmana2086b32010-05-19 23:43:12 +00002061 if (&LU != &OrigLU &&
2062 LU.Kind != LSRUse::ICmpZero &&
2063 LU.Kind == OrigLU.Kind && OrigLU.AccessTy == LU.AccessTy &&
Dan Gohmana9db1292010-07-15 20:24:58 +00002064 LU.WidestFixupType == OrigLU.WidestFixupType &&
Dan Gohmana2086b32010-05-19 23:43:12 +00002065 LU.HasFormulaWithSameRegs(OrigF)) {
Dan Gohman6a832712010-08-29 15:27:08 +00002066 // Scan through this use's formulae.
Dan Gohman402d4352010-05-20 20:33:18 +00002067 for (SmallVectorImpl<Formula>::const_iterator I = LU.Formulae.begin(),
2068 E = LU.Formulae.end(); I != E; ++I) {
2069 const Formula &F = *I;
Dan Gohman6a832712010-08-29 15:27:08 +00002070 // Check to see if this formula has the same registers and symbols
2071 // as OrigF.
Dan Gohmana2086b32010-05-19 23:43:12 +00002072 if (F.BaseRegs == OrigF.BaseRegs &&
2073 F.ScaledReg == OrigF.ScaledReg &&
2074 F.AM.BaseGV == OrigF.AM.BaseGV &&
Dan Gohmancca82142011-05-03 00:46:49 +00002075 F.AM.Scale == OrigF.AM.Scale &&
2076 F.UnfoldedOffset == OrigF.UnfoldedOffset) {
Dan Gohman191bd642010-09-01 01:45:53 +00002077 if (F.AM.BaseOffs == 0)
Dan Gohmana2086b32010-05-19 23:43:12 +00002078 return &LU;
Dan Gohman6a832712010-08-29 15:27:08 +00002079 // This is the formula where all the registers and symbols matched;
2080 // there aren't going to be any others. Since we declined it, we
2081 // can skip the rest of the formulae and procede to the next LSRUse.
Dan Gohmana2086b32010-05-19 23:43:12 +00002082 break;
2083 }
2084 }
2085 }
2086 }
2087
Dan Gohman6a832712010-08-29 15:27:08 +00002088 // Nothing looked good.
Dan Gohmana2086b32010-05-19 23:43:12 +00002089 return 0;
2090}
2091
Dan Gohman572645c2010-02-12 10:34:29 +00002092void LSRInstance::CollectInterestingTypesAndFactors() {
2093 SmallSetVector<const SCEV *, 4> Strides;
2094
Dan Gohman1b7bf182010-02-19 00:05:23 +00002095 // Collect interesting types and strides.
Dan Gohman448db1c2010-04-07 22:27:08 +00002096 SmallVector<const SCEV *, 4> Worklist;
Dan Gohman572645c2010-02-12 10:34:29 +00002097 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
Dan Gohmanc0564542010-04-19 21:48:58 +00002098 const SCEV *Expr = IU.getExpr(*UI);
Dan Gohman572645c2010-02-12 10:34:29 +00002099
2100 // Collect interesting types.
Dan Gohman448db1c2010-04-07 22:27:08 +00002101 Types.insert(SE.getEffectiveSCEVType(Expr->getType()));
Dan Gohman572645c2010-02-12 10:34:29 +00002102
Dan Gohman448db1c2010-04-07 22:27:08 +00002103 // Add strides for mentioned loops.
2104 Worklist.push_back(Expr);
2105 do {
2106 const SCEV *S = Worklist.pop_back_val();
2107 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
Andrew Trickfa1948a2011-12-10 00:25:00 +00002108 if (EnableNested || AR->getLoop() == L)
2109 Strides.insert(AR->getStepRecurrence(SE));
Dan Gohman448db1c2010-04-07 22:27:08 +00002110 Worklist.push_back(AR->getStart());
2111 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
Dan Gohman403a8cd2010-06-21 19:47:52 +00002112 Worklist.append(Add->op_begin(), Add->op_end());
Dan Gohman448db1c2010-04-07 22:27:08 +00002113 }
2114 } while (!Worklist.empty());
Dan Gohman1b7bf182010-02-19 00:05:23 +00002115 }
2116
2117 // Compute interesting factors from the set of interesting strides.
2118 for (SmallSetVector<const SCEV *, 4>::const_iterator
2119 I = Strides.begin(), E = Strides.end(); I != E; ++I)
Dan Gohman572645c2010-02-12 10:34:29 +00002120 for (SmallSetVector<const SCEV *, 4>::const_iterator NewStrideIter =
Oscar Fuentesee56c422010-08-02 06:00:15 +00002121 llvm::next(I); NewStrideIter != E; ++NewStrideIter) {
Dan Gohman1b7bf182010-02-19 00:05:23 +00002122 const SCEV *OldStride = *I;
Dan Gohman572645c2010-02-12 10:34:29 +00002123 const SCEV *NewStride = *NewStrideIter;
Dan Gohman572645c2010-02-12 10:34:29 +00002124
2125 if (SE.getTypeSizeInBits(OldStride->getType()) !=
2126 SE.getTypeSizeInBits(NewStride->getType())) {
2127 if (SE.getTypeSizeInBits(OldStride->getType()) >
2128 SE.getTypeSizeInBits(NewStride->getType()))
2129 NewStride = SE.getSignExtendExpr(NewStride, OldStride->getType());
2130 else
2131 OldStride = SE.getSignExtendExpr(OldStride, NewStride->getType());
2132 }
2133 if (const SCEVConstant *Factor =
Dan Gohmanf09b7122010-02-19 19:35:48 +00002134 dyn_cast_or_null<SCEVConstant>(getExactSDiv(NewStride, OldStride,
2135 SE, true))) {
Dan Gohman572645c2010-02-12 10:34:29 +00002136 if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
2137 Factors.insert(Factor->getValue()->getValue().getSExtValue());
2138 } else if (const SCEVConstant *Factor =
Dan Gohman454d26d2010-02-22 04:11:59 +00002139 dyn_cast_or_null<SCEVConstant>(getExactSDiv(OldStride,
2140 NewStride,
Dan Gohmanf09b7122010-02-19 19:35:48 +00002141 SE, true))) {
Dan Gohman572645c2010-02-12 10:34:29 +00002142 if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
2143 Factors.insert(Factor->getValue()->getValue().getSExtValue());
2144 }
2145 }
Dan Gohman572645c2010-02-12 10:34:29 +00002146
2147 // If all uses use the same type, don't bother looking for truncation-based
2148 // reuse.
2149 if (Types.size() == 1)
2150 Types.clear();
2151
2152 DEBUG(print_factors_and_types(dbgs()));
2153}
2154
Andrew Trick6c7d0ae2012-01-09 19:50:34 +00002155/// findIVOperand - Helper for CollectChains that finds an IV operand (computed
2156/// by an AddRec in this loop) within [OI,OE) or returns OE. If IVUsers mapped
2157/// Instructions to IVStrideUses, we could partially skip this.
2158static User::op_iterator
2159findIVOperand(User::op_iterator OI, User::op_iterator OE,
2160 Loop *L, ScalarEvolution &SE) {
2161 for(; OI != OE; ++OI) {
2162 if (Instruction *Oper = dyn_cast<Instruction>(*OI)) {
2163 if (!SE.isSCEVable(Oper->getType()))
2164 continue;
2165
2166 if (const SCEVAddRecExpr *AR =
2167 dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Oper))) {
2168 if (AR->getLoop() == L)
2169 break;
2170 }
2171 }
2172 }
2173 return OI;
2174}
2175
2176/// getWideOperand - IVChain logic must consistenctly peek base TruncInst
2177/// operands, so wrap it in a convenient helper.
2178static Value *getWideOperand(Value *Oper) {
2179 if (TruncInst *Trunc = dyn_cast<TruncInst>(Oper))
2180 return Trunc->getOperand(0);
2181 return Oper;
2182}
2183
2184/// isCompatibleIVType - Return true if we allow an IV chain to include both
2185/// types.
2186static bool isCompatibleIVType(Value *LVal, Value *RVal) {
2187 Type *LType = LVal->getType();
2188 Type *RType = RVal->getType();
2189 return (LType == RType) || (LType->isPointerTy() && RType->isPointerTy());
2190}
2191
2192/// ChainInstruction - Add this IV user to an existing chain or make it the head
2193/// of a new chain.
2194void LSRInstance::ChainInstruction(Instruction *UserInst, Instruction *IVOper,
2195 SmallVectorImpl<ChainUsers> &ChainUsersVec) {
2196 // When IVs are used as types of varying widths, they are generally converted
2197 // to a wider type with some uses remaining narrow under a (free) trunc.
2198 Value *NextIV = getWideOperand(IVOper);
2199
2200 // Visit all existing chains. Check if its IVOper can be computed as a
2201 // profitable loop invariant increment from the last link in the Chain.
2202 unsigned ChainIdx = 0, NChains = IVChainVec.size();
2203 const SCEV *LastIncExpr = 0;
2204 for (; ChainIdx < NChains; ++ChainIdx) {
2205 Value *PrevIV = getWideOperand(IVChainVec[ChainIdx].back().IVOperand);
2206 if (!isCompatibleIVType(PrevIV, NextIV))
2207 continue;
2208
2209 // A phi nodes terminates a chain.
2210 if (isa<PHINode>(UserInst)
2211 && isa<PHINode>(IVChainVec[ChainIdx].back().UserInst))
2212 continue;
2213
2214 const SCEV *IncExpr = SE.getMinusSCEV(SE.getSCEV(NextIV),
2215 SE.getSCEV(PrevIV));
2216 if (SE.isLoopInvariant(IncExpr, L)) {
2217 LastIncExpr = IncExpr;
2218 break;
2219 }
2220 }
2221 // If we haven't found a chain, create a new one, unless we hit the max. Don't
2222 // bother for phi nodes, because they must be last in the chain.
2223 if (ChainIdx == NChains) {
2224 if (isa<PHINode>(UserInst))
2225 return;
2226 if (NChains >= MaxChains) {
2227 DEBUG(dbgs() << "IV Chain Limit\n");
2228 return;
2229 }
2230 ++NChains;
2231 IVChainVec.resize(NChains);
2232 ChainUsersVec.resize(NChains);
2233 LastIncExpr = SE.getSCEV(NextIV);
2234 assert(isa<SCEVAddRecExpr>(LastIncExpr) && "expect recurrence at IV user");
2235 DEBUG(dbgs() << "IV Head: (" << *UserInst << ") IV=" << *LastIncExpr
2236 << "\n");
2237 }
2238 else
2239 DEBUG(dbgs() << "IV Inc: (" << *UserInst << ") IV+" << *LastIncExpr
2240 << "\n");
2241
2242 // Add this IV user to the end of the chain.
2243 IVChainVec[ChainIdx].push_back(IVInc(UserInst, IVOper, LastIncExpr));
2244
2245 SmallPtrSet<Instruction*,4> &NearUsers = ChainUsersVec[ChainIdx].NearUsers;
2246 // This chain's NearUsers become FarUsers.
2247 if (!LastIncExpr->isZero()) {
2248 ChainUsersVec[ChainIdx].FarUsers.insert(NearUsers.begin(),
2249 NearUsers.end());
2250 NearUsers.clear();
2251 }
2252
2253 // All other uses of IVOperand become near uses of the chain.
2254 // We currently ignore intermediate values within SCEV expressions, assuming
2255 // they will eventually be used be the current chain, or can be computed
2256 // from one of the chain increments. To be more precise we could
2257 // transitively follow its user and only add leaf IV users to the set.
2258 for (Value::use_iterator UseIter = IVOper->use_begin(),
2259 UseEnd = IVOper->use_end(); UseIter != UseEnd; ++UseIter) {
2260 Instruction *OtherUse = dyn_cast<Instruction>(*UseIter);
2261 if (SE.isSCEVable(OtherUse->getType())
2262 && !isa<SCEVUnknown>(SE.getSCEV(OtherUse))
2263 && IU.isIVUserOrOperand(OtherUse)) {
2264 continue;
2265 }
2266 if (OtherUse && OtherUse != UserInst)
2267 NearUsers.insert(OtherUse);
2268 }
2269
2270 // Since this user is part of the chain, it's no longer considered a use
2271 // of the chain.
2272 ChainUsersVec[ChainIdx].FarUsers.erase(UserInst);
2273}
2274
2275/// CollectChains - Populate the vector of Chains.
2276///
2277/// This decreases ILP at the architecture level. Targets with ample registers,
2278/// multiple memory ports, and no register renaming probably don't want
2279/// this. However, such targets should probably disable LSR altogether.
2280///
2281/// The job of LSR is to make a reasonable choice of induction variables across
2282/// the loop. Subsequent passes can easily "unchain" computation exposing more
2283/// ILP *within the loop* if the target wants it.
2284///
2285/// Finding the best IV chain is potentially a scheduling problem. Since LSR
2286/// will not reorder memory operations, it will recognize this as a chain, but
2287/// will generate redundant IV increments. Ideally this would be corrected later
2288/// by a smart scheduler:
2289/// = A[i]
2290/// = A[i+x]
2291/// A[i] =
2292/// A[i+x] =
2293///
2294/// TODO: Walk the entire domtree within this loop, not just the path to the
2295/// loop latch. This will discover chains on side paths, but requires
2296/// maintaining multiple copies of the Chains state.
2297void LSRInstance::CollectChains() {
2298 SmallVector<ChainUsers, 8> ChainUsersVec;
2299
2300 SmallVector<BasicBlock *,8> LatchPath;
2301 BasicBlock *LoopHeader = L->getHeader();
2302 for (DomTreeNode *Rung = DT.getNode(L->getLoopLatch());
2303 Rung->getBlock() != LoopHeader; Rung = Rung->getIDom()) {
2304 LatchPath.push_back(Rung->getBlock());
2305 }
2306 LatchPath.push_back(LoopHeader);
2307
2308 // Walk the instruction stream from the loop header to the loop latch.
2309 for (SmallVectorImpl<BasicBlock *>::reverse_iterator
2310 BBIter = LatchPath.rbegin(), BBEnd = LatchPath.rend();
2311 BBIter != BBEnd; ++BBIter) {
2312 for (BasicBlock::iterator I = (*BBIter)->begin(), E = (*BBIter)->end();
2313 I != E; ++I) {
2314 // Skip instructions that weren't seen by IVUsers analysis.
2315 if (isa<PHINode>(I) || !IU.isIVUserOrOperand(I))
2316 continue;
2317
2318 // Ignore users that are part of a SCEV expression. This way we only
2319 // consider leaf IV Users. This effectively rediscovers a portion of
2320 // IVUsers analysis but in program order this time.
2321 if (SE.isSCEVable(I->getType()) && !isa<SCEVUnknown>(SE.getSCEV(I)))
2322 continue;
2323
2324 // Remove this instruction from any NearUsers set it may be in.
2325 for (unsigned ChainIdx = 0, NChains = IVChainVec.size();
2326 ChainIdx < NChains; ++ChainIdx) {
2327 ChainUsersVec[ChainIdx].NearUsers.erase(I);
2328 }
2329 // Search for operands that can be chained.
2330 SmallPtrSet<Instruction*, 4> UniqueOperands;
2331 User::op_iterator IVOpEnd = I->op_end();
2332 User::op_iterator IVOpIter = findIVOperand(I->op_begin(), IVOpEnd, L, SE);
2333 while (IVOpIter != IVOpEnd) {
2334 Instruction *IVOpInst = cast<Instruction>(*IVOpIter);
2335 if (UniqueOperands.insert(IVOpInst))
2336 ChainInstruction(I, IVOpInst, ChainUsersVec);
2337 IVOpIter = findIVOperand(llvm::next(IVOpIter), IVOpEnd, L, SE);
2338 }
2339 } // Continue walking down the instructions.
2340 } // Continue walking down the domtree.
2341 // Visit phi backedges to determine if the chain can generate the IV postinc.
2342 for (BasicBlock::iterator I = L->getHeader()->begin();
2343 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
2344 if (!SE.isSCEVable(PN->getType()))
2345 continue;
2346
2347 Instruction *IncV =
2348 dyn_cast<Instruction>(PN->getIncomingValueForBlock(L->getLoopLatch()));
2349 if (IncV)
2350 ChainInstruction(PN, IncV, ChainUsersVec);
2351 }
2352}
2353
Dan Gohman572645c2010-02-12 10:34:29 +00002354void LSRInstance::CollectFixupsAndInitialFormulae() {
2355 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
2356 // Record the uses.
2357 LSRFixup &LF = getNewFixup();
2358 LF.UserInst = UI->getUser();
2359 LF.OperandValToReplace = UI->getOperandValToReplace();
Dan Gohman448db1c2010-04-07 22:27:08 +00002360 LF.PostIncLoops = UI->getPostIncLoops();
Dan Gohman572645c2010-02-12 10:34:29 +00002361
2362 LSRUse::KindType Kind = LSRUse::Basic;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002363 Type *AccessTy = 0;
Dan Gohman572645c2010-02-12 10:34:29 +00002364 if (isAddressUse(LF.UserInst, LF.OperandValToReplace)) {
2365 Kind = LSRUse::Address;
2366 AccessTy = getAccessType(LF.UserInst);
2367 }
2368
Dan Gohmanc0564542010-04-19 21:48:58 +00002369 const SCEV *S = IU.getExpr(*UI);
Dan Gohman572645c2010-02-12 10:34:29 +00002370
2371 // Equality (== and !=) ICmps are special. We can rewrite (i == N) as
2372 // (N - i == 0), and this allows (N - i) to be the expression that we work
2373 // with rather than just N or i, so we can consider the register
2374 // requirements for both N and i at the same time. Limiting this code to
2375 // equality icmps is not a problem because all interesting loops use
2376 // equality icmps, thanks to IndVarSimplify.
2377 if (ICmpInst *CI = dyn_cast<ICmpInst>(LF.UserInst))
2378 if (CI->isEquality()) {
2379 // Swap the operands if needed to put the OperandValToReplace on the
2380 // left, for consistency.
2381 Value *NV = CI->getOperand(1);
2382 if (NV == LF.OperandValToReplace) {
2383 CI->setOperand(1, CI->getOperand(0));
2384 CI->setOperand(0, NV);
Dan Gohmanf182b232010-05-20 19:26:52 +00002385 NV = CI->getOperand(1);
Dan Gohman9da1bf42010-05-20 19:16:03 +00002386 Changed = true;
Dan Gohman572645c2010-02-12 10:34:29 +00002387 }
2388
2389 // x == y --> x - y == 0
2390 const SCEV *N = SE.getSCEV(NV);
Dan Gohman17ead4f2010-11-17 21:23:15 +00002391 if (SE.isLoopInvariant(N, L)) {
Dan Gohman673968a2011-05-18 21:02:18 +00002392 // S is normalized, so normalize N before folding it into S
2393 // to keep the result normalized.
2394 N = TransformForPostIncUse(Normalize, N, CI, 0,
2395 LF.PostIncLoops, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +00002396 Kind = LSRUse::ICmpZero;
2397 S = SE.getMinusSCEV(N, S);
2398 }
2399
2400 // -1 and the negations of all interesting strides (except the negation
2401 // of -1) are now also interesting.
2402 for (size_t i = 0, e = Factors.size(); i != e; ++i)
2403 if (Factors[i] != -1)
2404 Factors.insert(-(uint64_t)Factors[i]);
2405 Factors.insert(-1);
2406 }
2407
2408 // Set up the initial formula for this use.
2409 std::pair<size_t, int64_t> P = getUse(S, Kind, AccessTy);
2410 LF.LUIdx = P.first;
2411 LF.Offset = P.second;
2412 LSRUse &LU = Uses[LF.LUIdx];
Dan Gohman448db1c2010-04-07 22:27:08 +00002413 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
Dan Gohmana9db1292010-07-15 20:24:58 +00002414 if (!LU.WidestFixupType ||
2415 SE.getTypeSizeInBits(LU.WidestFixupType) <
2416 SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
2417 LU.WidestFixupType = LF.OperandValToReplace->getType();
Dan Gohman572645c2010-02-12 10:34:29 +00002418
2419 // If this is the first use of this LSRUse, give it a formula.
2420 if (LU.Formulae.empty()) {
Dan Gohman454d26d2010-02-22 04:11:59 +00002421 InsertInitialFormula(S, LU, LF.LUIdx);
Dan Gohman572645c2010-02-12 10:34:29 +00002422 CountRegisters(LU.Formulae.back(), LF.LUIdx);
2423 }
2424 }
2425
2426 DEBUG(print_fixups(dbgs()));
2427}
2428
Dan Gohman76c315a2010-05-20 20:52:00 +00002429/// InsertInitialFormula - Insert a formula for the given expression into
2430/// the given use, separating out loop-variant portions from loop-invariant
2431/// and loop-computable portions.
Dan Gohman572645c2010-02-12 10:34:29 +00002432void
Dan Gohman454d26d2010-02-22 04:11:59 +00002433LSRInstance::InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx) {
Dan Gohman572645c2010-02-12 10:34:29 +00002434 Formula F;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00002435 F.InitialMatch(S, L, SE);
Dan Gohman572645c2010-02-12 10:34:29 +00002436 bool Inserted = InsertFormula(LU, LUIdx, F);
2437 assert(Inserted && "Initial formula already exists!"); (void)Inserted;
2438}
2439
Dan Gohman76c315a2010-05-20 20:52:00 +00002440/// InsertSupplementalFormula - Insert a simple single-register formula for
2441/// the given expression into the given use.
Dan Gohman572645c2010-02-12 10:34:29 +00002442void
2443LSRInstance::InsertSupplementalFormula(const SCEV *S,
2444 LSRUse &LU, size_t LUIdx) {
2445 Formula F;
2446 F.BaseRegs.push_back(S);
2447 F.AM.HasBaseReg = true;
2448 bool Inserted = InsertFormula(LU, LUIdx, F);
2449 assert(Inserted && "Supplemental formula already exists!"); (void)Inserted;
2450}
2451
2452/// CountRegisters - Note which registers are used by the given formula,
2453/// updating RegUses.
2454void LSRInstance::CountRegisters(const Formula &F, size_t LUIdx) {
2455 if (F.ScaledReg)
2456 RegUses.CountRegister(F.ScaledReg, LUIdx);
2457 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
2458 E = F.BaseRegs.end(); I != E; ++I)
2459 RegUses.CountRegister(*I, LUIdx);
2460}
2461
2462/// InsertFormula - If the given formula has not yet been inserted, add it to
2463/// the list, and return true. Return false otherwise.
2464bool LSRInstance::InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F) {
Dan Gohman454d26d2010-02-22 04:11:59 +00002465 if (!LU.InsertFormula(F))
Dan Gohman572645c2010-02-12 10:34:29 +00002466 return false;
2467
2468 CountRegisters(F, LUIdx);
2469 return true;
2470}
2471
2472/// CollectLoopInvariantFixupsAndFormulae - Check for other uses of
2473/// loop-invariant values which we're tracking. These other uses will pin these
2474/// values in registers, making them less profitable for elimination.
2475/// TODO: This currently misses non-constant addrec step registers.
2476/// TODO: Should this give more weight to users inside the loop?
2477void
2478LSRInstance::CollectLoopInvariantFixupsAndFormulae() {
2479 SmallVector<const SCEV *, 8> Worklist(RegUses.begin(), RegUses.end());
2480 SmallPtrSet<const SCEV *, 8> Inserted;
2481
2482 while (!Worklist.empty()) {
2483 const SCEV *S = Worklist.pop_back_val();
2484
2485 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S))
Dan Gohman403a8cd2010-06-21 19:47:52 +00002486 Worklist.append(N->op_begin(), N->op_end());
Dan Gohman572645c2010-02-12 10:34:29 +00002487 else if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
2488 Worklist.push_back(C->getOperand());
2489 else if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
2490 Worklist.push_back(D->getLHS());
2491 Worklist.push_back(D->getRHS());
2492 } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2493 if (!Inserted.insert(U)) continue;
2494 const Value *V = U->getValue();
Dan Gohmana15ec5d2010-06-04 23:16:05 +00002495 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
2496 // Look for instructions defined outside the loop.
Dan Gohman572645c2010-02-12 10:34:29 +00002497 if (L->contains(Inst)) continue;
Dan Gohmana15ec5d2010-06-04 23:16:05 +00002498 } else if (isa<UndefValue>(V))
2499 // Undef doesn't have a live range, so it doesn't matter.
2500 continue;
Gabor Greif60ad7812010-03-25 23:06:16 +00002501 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
Dan Gohman572645c2010-02-12 10:34:29 +00002502 UI != UE; ++UI) {
2503 const Instruction *UserInst = dyn_cast<Instruction>(*UI);
2504 // Ignore non-instructions.
2505 if (!UserInst)
Dan Gohman7979b722010-01-22 00:46:49 +00002506 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002507 // Ignore instructions in other functions (as can happen with
2508 // Constants).
2509 if (UserInst->getParent()->getParent() != L->getHeader()->getParent())
Dan Gohman7979b722010-01-22 00:46:49 +00002510 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002511 // Ignore instructions not dominated by the loop.
2512 const BasicBlock *UseBB = !isa<PHINode>(UserInst) ?
2513 UserInst->getParent() :
2514 cast<PHINode>(UserInst)->getIncomingBlock(
2515 PHINode::getIncomingValueNumForOperand(UI.getOperandNo()));
2516 if (!DT.dominates(L->getHeader(), UseBB))
2517 continue;
2518 // Ignore uses which are part of other SCEV expressions, to avoid
2519 // analyzing them multiple times.
Dan Gohman4a2a6832010-04-09 19:12:34 +00002520 if (SE.isSCEVable(UserInst->getType())) {
2521 const SCEV *UserS = SE.getSCEV(const_cast<Instruction *>(UserInst));
2522 // If the user is a no-op, look through to its uses.
2523 if (!isa<SCEVUnknown>(UserS))
2524 continue;
2525 if (UserS == U) {
2526 Worklist.push_back(
2527 SE.getUnknown(const_cast<Instruction *>(UserInst)));
2528 continue;
2529 }
2530 }
Dan Gohman572645c2010-02-12 10:34:29 +00002531 // Ignore icmp instructions which are already being analyzed.
2532 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) {
2533 unsigned OtherIdx = !UI.getOperandNo();
2534 Value *OtherOp = const_cast<Value *>(ICI->getOperand(OtherIdx));
Dan Gohman17ead4f2010-11-17 21:23:15 +00002535 if (SE.hasComputableLoopEvolution(SE.getSCEV(OtherOp), L))
Dan Gohman572645c2010-02-12 10:34:29 +00002536 continue;
2537 }
2538
2539 LSRFixup &LF = getNewFixup();
2540 LF.UserInst = const_cast<Instruction *>(UserInst);
2541 LF.OperandValToReplace = UI.getUse();
2542 std::pair<size_t, int64_t> P = getUse(S, LSRUse::Basic, 0);
2543 LF.LUIdx = P.first;
2544 LF.Offset = P.second;
2545 LSRUse &LU = Uses[LF.LUIdx];
Dan Gohman448db1c2010-04-07 22:27:08 +00002546 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
Dan Gohmana9db1292010-07-15 20:24:58 +00002547 if (!LU.WidestFixupType ||
2548 SE.getTypeSizeInBits(LU.WidestFixupType) <
2549 SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
2550 LU.WidestFixupType = LF.OperandValToReplace->getType();
Dan Gohman572645c2010-02-12 10:34:29 +00002551 InsertSupplementalFormula(U, LU, LF.LUIdx);
2552 CountRegisters(LU.Formulae.back(), Uses.size() - 1);
2553 break;
2554 }
2555 }
2556 }
2557}
2558
2559/// CollectSubexprs - Split S into subexpressions which can be pulled out into
2560/// separate registers. If C is non-null, multiply each subexpression by C.
2561static void CollectSubexprs(const SCEV *S, const SCEVConstant *C,
2562 SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman3e3f15b2010-06-25 22:32:18 +00002563 const Loop *L,
Dan Gohman572645c2010-02-12 10:34:29 +00002564 ScalarEvolution &SE) {
2565 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2566 // Break out add operands.
2567 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
2568 I != E; ++I)
Dan Gohman3e22b7c2010-08-16 15:50:00 +00002569 CollectSubexprs(*I, C, Ops, L, SE);
Dan Gohman572645c2010-02-12 10:34:29 +00002570 return;
2571 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
2572 // Split a non-zero base out of an addrec.
2573 if (!AR->getStart()->isZero()) {
Dan Gohmandeff6212010-05-03 22:09:21 +00002574 CollectSubexprs(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0),
Dan Gohman572645c2010-02-12 10:34:29 +00002575 AR->getStepRecurrence(SE),
Andrew Trick3228cc22011-03-14 16:50:06 +00002576 AR->getLoop(),
2577 //FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
2578 SCEV::FlagAnyWrap),
Dan Gohman3e22b7c2010-08-16 15:50:00 +00002579 C, Ops, L, SE);
2580 CollectSubexprs(AR->getStart(), C, Ops, L, SE);
Dan Gohman572645c2010-02-12 10:34:29 +00002581 return;
2582 }
2583 } else if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2584 // Break (C * (a + b + c)) into C*a + C*b + C*c.
2585 if (Mul->getNumOperands() == 2)
2586 if (const SCEVConstant *Op0 =
2587 dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
2588 CollectSubexprs(Mul->getOperand(1),
2589 C ? cast<SCEVConstant>(SE.getMulExpr(C, Op0)) : Op0,
Dan Gohman3e22b7c2010-08-16 15:50:00 +00002590 Ops, L, SE);
Dan Gohman572645c2010-02-12 10:34:29 +00002591 return;
2592 }
2593 }
2594
Dan Gohman3e22b7c2010-08-16 15:50:00 +00002595 // Otherwise use the value itself, optionally with a scale applied.
2596 Ops.push_back(C ? SE.getMulExpr(C, S) : S);
Dan Gohman572645c2010-02-12 10:34:29 +00002597}
2598
2599/// GenerateReassociations - Split out subexpressions from adds and the bases of
2600/// addrecs.
2601void LSRInstance::GenerateReassociations(LSRUse &LU, unsigned LUIdx,
2602 Formula Base,
2603 unsigned Depth) {
2604 // Arbitrarily cap recursion to protect compile time.
2605 if (Depth >= 3) return;
2606
2607 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2608 const SCEV *BaseReg = Base.BaseRegs[i];
2609
Dan Gohman3e22b7c2010-08-16 15:50:00 +00002610 SmallVector<const SCEV *, 8> AddOps;
2611 CollectSubexprs(BaseReg, 0, AddOps, L, SE);
Dan Gohman3e3f15b2010-06-25 22:32:18 +00002612
Dan Gohman572645c2010-02-12 10:34:29 +00002613 if (AddOps.size() == 1) continue;
2614
2615 for (SmallVectorImpl<const SCEV *>::const_iterator J = AddOps.begin(),
2616 JE = AddOps.end(); J != JE; ++J) {
Dan Gohman3e22b7c2010-08-16 15:50:00 +00002617
2618 // Loop-variant "unknown" values are uninteresting; we won't be able to
2619 // do anything meaningful with them.
Dan Gohman17ead4f2010-11-17 21:23:15 +00002620 if (isa<SCEVUnknown>(*J) && !SE.isLoopInvariant(*J, L))
Dan Gohman3e22b7c2010-08-16 15:50:00 +00002621 continue;
2622
Dan Gohman572645c2010-02-12 10:34:29 +00002623 // Don't pull a constant into a register if the constant could be folded
2624 // into an immediate field.
2625 if (isAlwaysFoldable(*J, LU.MinOffset, LU.MaxOffset,
2626 Base.getNumRegs() > 1,
2627 LU.Kind, LU.AccessTy, TLI, SE))
2628 continue;
2629
2630 // Collect all operands except *J.
Dan Gohman403a8cd2010-06-21 19:47:52 +00002631 SmallVector<const SCEV *, 8> InnerAddOps
Dan Gohman4eaee282010-08-04 17:43:57 +00002632 (((const SmallVector<const SCEV *, 8> &)AddOps).begin(), J);
Dan Gohman403a8cd2010-06-21 19:47:52 +00002633 InnerAddOps.append
Oscar Fuentesee56c422010-08-02 06:00:15 +00002634 (llvm::next(J), ((const SmallVector<const SCEV *, 8> &)AddOps).end());
Dan Gohman572645c2010-02-12 10:34:29 +00002635
2636 // Don't leave just a constant behind in a register if the constant could
2637 // be folded into an immediate field.
2638 if (InnerAddOps.size() == 1 &&
2639 isAlwaysFoldable(InnerAddOps[0], LU.MinOffset, LU.MaxOffset,
2640 Base.getNumRegs() > 1,
2641 LU.Kind, LU.AccessTy, TLI, SE))
2642 continue;
2643
Dan Gohmanfafb8902010-04-23 01:55:05 +00002644 const SCEV *InnerSum = SE.getAddExpr(InnerAddOps);
2645 if (InnerSum->isZero())
2646 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002647 Formula F = Base;
Dan Gohmancca82142011-05-03 00:46:49 +00002648
2649 // Add the remaining pieces of the add back into the new formula.
2650 const SCEVConstant *InnerSumSC = dyn_cast<SCEVConstant>(InnerSum);
2651 if (TLI && InnerSumSC &&
2652 SE.getTypeSizeInBits(InnerSumSC->getType()) <= 64 &&
2653 TLI->isLegalAddImmediate((uint64_t)F.UnfoldedOffset +
2654 InnerSumSC->getValue()->getZExtValue())) {
2655 F.UnfoldedOffset = (uint64_t)F.UnfoldedOffset +
2656 InnerSumSC->getValue()->getZExtValue();
2657 F.BaseRegs.erase(F.BaseRegs.begin() + i);
2658 } else
2659 F.BaseRegs[i] = InnerSum;
2660
2661 // Add J as its own register, or an unfolded immediate.
2662 const SCEVConstant *SC = dyn_cast<SCEVConstant>(*J);
2663 if (TLI && SC && SE.getTypeSizeInBits(SC->getType()) <= 64 &&
2664 TLI->isLegalAddImmediate((uint64_t)F.UnfoldedOffset +
2665 SC->getValue()->getZExtValue()))
2666 F.UnfoldedOffset = (uint64_t)F.UnfoldedOffset +
2667 SC->getValue()->getZExtValue();
2668 else
2669 F.BaseRegs.push_back(*J);
2670
Dan Gohman572645c2010-02-12 10:34:29 +00002671 if (InsertFormula(LU, LUIdx, F))
2672 // If that formula hadn't been seen before, recurse to find more like
2673 // it.
2674 GenerateReassociations(LU, LUIdx, LU.Formulae.back(), Depth+1);
2675 }
2676 }
2677}
2678
2679/// GenerateCombinations - Generate a formula consisting of all of the
2680/// loop-dominating registers added into a single register.
2681void LSRInstance::GenerateCombinations(LSRUse &LU, unsigned LUIdx,
Dan Gohman441a3892010-02-14 18:51:39 +00002682 Formula Base) {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002683 // This method is only interesting on a plurality of registers.
Dan Gohman572645c2010-02-12 10:34:29 +00002684 if (Base.BaseRegs.size() <= 1) return;
2685
2686 Formula F = Base;
2687 F.BaseRegs.clear();
2688 SmallVector<const SCEV *, 4> Ops;
2689 for (SmallVectorImpl<const SCEV *>::const_iterator
2690 I = Base.BaseRegs.begin(), E = Base.BaseRegs.end(); I != E; ++I) {
2691 const SCEV *BaseReg = *I;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00002692 if (SE.properlyDominates(BaseReg, L->getHeader()) &&
Dan Gohman17ead4f2010-11-17 21:23:15 +00002693 !SE.hasComputableLoopEvolution(BaseReg, L))
Dan Gohman572645c2010-02-12 10:34:29 +00002694 Ops.push_back(BaseReg);
2695 else
2696 F.BaseRegs.push_back(BaseReg);
2697 }
2698 if (Ops.size() > 1) {
Dan Gohmance947362010-02-14 18:50:49 +00002699 const SCEV *Sum = SE.getAddExpr(Ops);
2700 // TODO: If Sum is zero, it probably means ScalarEvolution missed an
2701 // opportunity to fold something. For now, just ignore such cases
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002702 // rather than proceed with zero in a register.
Dan Gohmance947362010-02-14 18:50:49 +00002703 if (!Sum->isZero()) {
2704 F.BaseRegs.push_back(Sum);
2705 (void)InsertFormula(LU, LUIdx, F);
2706 }
Dan Gohman572645c2010-02-12 10:34:29 +00002707 }
2708}
2709
2710/// GenerateSymbolicOffsets - Generate reuse formulae using symbolic offsets.
2711void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx,
2712 Formula Base) {
2713 // We can't add a symbolic offset if the address already contains one.
2714 if (Base.AM.BaseGV) return;
2715
2716 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2717 const SCEV *G = Base.BaseRegs[i];
2718 GlobalValue *GV = ExtractSymbol(G, SE);
2719 if (G->isZero() || !GV)
2720 continue;
2721 Formula F = Base;
2722 F.AM.BaseGV = GV;
2723 if (!isLegalUse(F.AM, LU.MinOffset, LU.MaxOffset,
2724 LU.Kind, LU.AccessTy, TLI))
2725 continue;
2726 F.BaseRegs[i] = G;
2727 (void)InsertFormula(LU, LUIdx, F);
2728 }
2729}
2730
2731/// GenerateConstantOffsets - Generate reuse formulae using symbolic offsets.
2732void LSRInstance::GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx,
2733 Formula Base) {
2734 // TODO: For now, just add the min and max offset, because it usually isn't
2735 // worthwhile looking at everything inbetween.
Dan Gohmanc88c1a42010-07-15 15:14:45 +00002736 SmallVector<int64_t, 2> Worklist;
Dan Gohman572645c2010-02-12 10:34:29 +00002737 Worklist.push_back(LU.MinOffset);
2738 if (LU.MaxOffset != LU.MinOffset)
2739 Worklist.push_back(LU.MaxOffset);
2740
2741 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2742 const SCEV *G = Base.BaseRegs[i];
2743
2744 for (SmallVectorImpl<int64_t>::const_iterator I = Worklist.begin(),
2745 E = Worklist.end(); I != E; ++I) {
2746 Formula F = Base;
2747 F.AM.BaseOffs = (uint64_t)Base.AM.BaseOffs - *I;
2748 if (isLegalUse(F.AM, LU.MinOffset - *I, LU.MaxOffset - *I,
2749 LU.Kind, LU.AccessTy, TLI)) {
Dan Gohmanc88c1a42010-07-15 15:14:45 +00002750 // Add the offset to the base register.
Dan Gohman4065f602010-08-16 15:39:27 +00002751 const SCEV *NewG = SE.getAddExpr(SE.getConstant(G->getType(), *I), G);
Dan Gohmanc88c1a42010-07-15 15:14:45 +00002752 // If it cancelled out, drop the base register, otherwise update it.
2753 if (NewG->isZero()) {
2754 std::swap(F.BaseRegs[i], F.BaseRegs.back());
2755 F.BaseRegs.pop_back();
2756 } else
2757 F.BaseRegs[i] = NewG;
Dan Gohman572645c2010-02-12 10:34:29 +00002758
2759 (void)InsertFormula(LU, LUIdx, F);
2760 }
2761 }
2762
2763 int64_t Imm = ExtractImmediate(G, SE);
2764 if (G->isZero() || Imm == 0)
2765 continue;
2766 Formula F = Base;
2767 F.AM.BaseOffs = (uint64_t)F.AM.BaseOffs + Imm;
2768 if (!isLegalUse(F.AM, LU.MinOffset, LU.MaxOffset,
2769 LU.Kind, LU.AccessTy, TLI))
2770 continue;
2771 F.BaseRegs[i] = G;
2772 (void)InsertFormula(LU, LUIdx, F);
2773 }
2774}
2775
2776/// GenerateICmpZeroScales - For ICmpZero, check to see if we can scale up
2777/// the comparison. For example, x == y -> x*c == y*c.
2778void LSRInstance::GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx,
2779 Formula Base) {
2780 if (LU.Kind != LSRUse::ICmpZero) return;
2781
2782 // Determine the integer type for the base formula.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002783 Type *IntTy = Base.getType();
Dan Gohman572645c2010-02-12 10:34:29 +00002784 if (!IntTy) return;
2785 if (SE.getTypeSizeInBits(IntTy) > 64) return;
2786
2787 // Don't do this if there is more than one offset.
2788 if (LU.MinOffset != LU.MaxOffset) return;
2789
2790 assert(!Base.AM.BaseGV && "ICmpZero use is not legal!");
2791
2792 // Check each interesting stride.
2793 for (SmallSetVector<int64_t, 8>::const_iterator
2794 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
2795 int64_t Factor = *I;
Dan Gohman572645c2010-02-12 10:34:29 +00002796
2797 // Check that the multiplication doesn't overflow.
Dan Gohman2ea09e02010-06-24 16:57:52 +00002798 if (Base.AM.BaseOffs == INT64_MIN && Factor == -1)
Dan Gohman968cb932010-02-17 00:41:53 +00002799 continue;
Dan Gohman2ea09e02010-06-24 16:57:52 +00002800 int64_t NewBaseOffs = (uint64_t)Base.AM.BaseOffs * Factor;
2801 if (NewBaseOffs / Factor != Base.AM.BaseOffs)
Dan Gohman572645c2010-02-12 10:34:29 +00002802 continue;
2803
2804 // Check that multiplying with the use offset doesn't overflow.
2805 int64_t Offset = LU.MinOffset;
Dan Gohman968cb932010-02-17 00:41:53 +00002806 if (Offset == INT64_MIN && Factor == -1)
2807 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002808 Offset = (uint64_t)Offset * Factor;
Dan Gohman378c0b32010-02-17 00:42:19 +00002809 if (Offset / Factor != LU.MinOffset)
Dan Gohman572645c2010-02-12 10:34:29 +00002810 continue;
2811
Dan Gohman2ea09e02010-06-24 16:57:52 +00002812 Formula F = Base;
2813 F.AM.BaseOffs = NewBaseOffs;
2814
Dan Gohman572645c2010-02-12 10:34:29 +00002815 // Check that this scale is legal.
2816 if (!isLegalUse(F.AM, Offset, Offset, LU.Kind, LU.AccessTy, TLI))
2817 continue;
2818
2819 // Compensate for the use having MinOffset built into it.
2820 F.AM.BaseOffs = (uint64_t)F.AM.BaseOffs + Offset - LU.MinOffset;
2821
Dan Gohmandeff6212010-05-03 22:09:21 +00002822 const SCEV *FactorS = SE.getConstant(IntTy, Factor);
Dan Gohman572645c2010-02-12 10:34:29 +00002823
2824 // Check that multiplying with each base register doesn't overflow.
2825 for (size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) {
2826 F.BaseRegs[i] = SE.getMulExpr(F.BaseRegs[i], FactorS);
Dan Gohmanf09b7122010-02-19 19:35:48 +00002827 if (getExactSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i])
Dan Gohman572645c2010-02-12 10:34:29 +00002828 goto next;
2829 }
2830
2831 // Check that multiplying with the scaled register doesn't overflow.
2832 if (F.ScaledReg) {
2833 F.ScaledReg = SE.getMulExpr(F.ScaledReg, FactorS);
Dan Gohmanf09b7122010-02-19 19:35:48 +00002834 if (getExactSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg)
Dan Gohman572645c2010-02-12 10:34:29 +00002835 continue;
2836 }
2837
Dan Gohmancca82142011-05-03 00:46:49 +00002838 // Check that multiplying with the unfolded offset doesn't overflow.
2839 if (F.UnfoldedOffset != 0) {
Dan Gohman1b58d452011-05-23 21:07:39 +00002840 if (F.UnfoldedOffset == INT64_MIN && Factor == -1)
2841 continue;
Dan Gohmancca82142011-05-03 00:46:49 +00002842 F.UnfoldedOffset = (uint64_t)F.UnfoldedOffset * Factor;
2843 if (F.UnfoldedOffset / Factor != Base.UnfoldedOffset)
2844 continue;
2845 }
2846
Dan Gohman572645c2010-02-12 10:34:29 +00002847 // If we make it here and it's legal, add it.
2848 (void)InsertFormula(LU, LUIdx, F);
2849 next:;
2850 }
2851}
2852
2853/// GenerateScales - Generate stride factor reuse formulae by making use of
2854/// scaled-offset address modes, for example.
Dan Gohmanea507f52010-05-20 19:44:23 +00002855void LSRInstance::GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base) {
Dan Gohman572645c2010-02-12 10:34:29 +00002856 // Determine the integer type for the base formula.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002857 Type *IntTy = Base.getType();
Dan Gohman572645c2010-02-12 10:34:29 +00002858 if (!IntTy) return;
2859
2860 // If this Formula already has a scaled register, we can't add another one.
2861 if (Base.AM.Scale != 0) return;
2862
2863 // Check each interesting stride.
2864 for (SmallSetVector<int64_t, 8>::const_iterator
2865 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
2866 int64_t Factor = *I;
2867
2868 Base.AM.Scale = Factor;
2869 Base.AM.HasBaseReg = Base.BaseRegs.size() > 1;
2870 // Check whether this scale is going to be legal.
2871 if (!isLegalUse(Base.AM, LU.MinOffset, LU.MaxOffset,
2872 LU.Kind, LU.AccessTy, TLI)) {
2873 // As a special-case, handle special out-of-loop Basic users specially.
2874 // TODO: Reconsider this special case.
2875 if (LU.Kind == LSRUse::Basic &&
2876 isLegalUse(Base.AM, LU.MinOffset, LU.MaxOffset,
2877 LSRUse::Special, LU.AccessTy, TLI) &&
2878 LU.AllFixupsOutsideLoop)
2879 LU.Kind = LSRUse::Special;
2880 else
2881 continue;
2882 }
2883 // For an ICmpZero, negating a solitary base register won't lead to
2884 // new solutions.
2885 if (LU.Kind == LSRUse::ICmpZero &&
2886 !Base.AM.HasBaseReg && Base.AM.BaseOffs == 0 && !Base.AM.BaseGV)
2887 continue;
2888 // For each addrec base reg, apply the scale, if possible.
2889 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
2890 if (const SCEVAddRecExpr *AR =
2891 dyn_cast<SCEVAddRecExpr>(Base.BaseRegs[i])) {
Dan Gohmandeff6212010-05-03 22:09:21 +00002892 const SCEV *FactorS = SE.getConstant(IntTy, Factor);
Dan Gohman572645c2010-02-12 10:34:29 +00002893 if (FactorS->isZero())
2894 continue;
2895 // Divide out the factor, ignoring high bits, since we'll be
2896 // scaling the value back up in the end.
Dan Gohmanf09b7122010-02-19 19:35:48 +00002897 if (const SCEV *Quotient = getExactSDiv(AR, FactorS, SE, true)) {
Dan Gohman572645c2010-02-12 10:34:29 +00002898 // TODO: This could be optimized to avoid all the copying.
2899 Formula F = Base;
2900 F.ScaledReg = Quotient;
Dan Gohman5ce6d052010-05-20 15:17:54 +00002901 F.DeleteBaseReg(F.BaseRegs[i]);
Dan Gohman572645c2010-02-12 10:34:29 +00002902 (void)InsertFormula(LU, LUIdx, F);
2903 }
2904 }
2905 }
2906}
2907
2908/// GenerateTruncates - Generate reuse formulae from different IV types.
Dan Gohmanea507f52010-05-20 19:44:23 +00002909void LSRInstance::GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base) {
Dan Gohman572645c2010-02-12 10:34:29 +00002910 // This requires TargetLowering to tell us which truncates are free.
2911 if (!TLI) return;
2912
2913 // Don't bother truncating symbolic values.
2914 if (Base.AM.BaseGV) return;
2915
2916 // Determine the integer type for the base formula.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002917 Type *DstTy = Base.getType();
Dan Gohman572645c2010-02-12 10:34:29 +00002918 if (!DstTy) return;
2919 DstTy = SE.getEffectiveSCEVType(DstTy);
2920
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002921 for (SmallSetVector<Type *, 4>::const_iterator
Dan Gohman572645c2010-02-12 10:34:29 +00002922 I = Types.begin(), E = Types.end(); I != E; ++I) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002923 Type *SrcTy = *I;
Dan Gohman572645c2010-02-12 10:34:29 +00002924 if (SrcTy != DstTy && TLI->isTruncateFree(SrcTy, DstTy)) {
2925 Formula F = Base;
2926
2927 if (F.ScaledReg) F.ScaledReg = SE.getAnyExtendExpr(F.ScaledReg, *I);
2928 for (SmallVectorImpl<const SCEV *>::iterator J = F.BaseRegs.begin(),
2929 JE = F.BaseRegs.end(); J != JE; ++J)
2930 *J = SE.getAnyExtendExpr(*J, SrcTy);
2931
2932 // TODO: This assumes we've done basic processing on all uses and
2933 // have an idea what the register usage is.
2934 if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses))
2935 continue;
2936
2937 (void)InsertFormula(LU, LUIdx, F);
2938 }
2939 }
2940}
2941
2942namespace {
2943
Dan Gohman6020d852010-02-14 18:51:20 +00002944/// WorkItem - Helper class for GenerateCrossUseConstantOffsets. It's used to
Dan Gohman572645c2010-02-12 10:34:29 +00002945/// defer modifications so that the search phase doesn't have to worry about
2946/// the data structures moving underneath it.
2947struct WorkItem {
2948 size_t LUIdx;
2949 int64_t Imm;
2950 const SCEV *OrigReg;
2951
2952 WorkItem(size_t LI, int64_t I, const SCEV *R)
2953 : LUIdx(LI), Imm(I), OrigReg(R) {}
2954
2955 void print(raw_ostream &OS) const;
2956 void dump() const;
2957};
2958
2959}
2960
2961void WorkItem::print(raw_ostream &OS) const {
2962 OS << "in formulae referencing " << *OrigReg << " in use " << LUIdx
2963 << " , add offset " << Imm;
2964}
2965
2966void WorkItem::dump() const {
2967 print(errs()); errs() << '\n';
2968}
2969
2970/// GenerateCrossUseConstantOffsets - Look for registers which are a constant
2971/// distance apart and try to form reuse opportunities between them.
2972void LSRInstance::GenerateCrossUseConstantOffsets() {
2973 // Group the registers by their value without any added constant offset.
2974 typedef std::map<int64_t, const SCEV *> ImmMapTy;
2975 typedef DenseMap<const SCEV *, ImmMapTy> RegMapTy;
2976 RegMapTy Map;
2977 DenseMap<const SCEV *, SmallBitVector> UsedByIndicesMap;
2978 SmallVector<const SCEV *, 8> Sequence;
2979 for (RegUseTracker::const_iterator I = RegUses.begin(), E = RegUses.end();
2980 I != E; ++I) {
2981 const SCEV *Reg = *I;
2982 int64_t Imm = ExtractImmediate(Reg, SE);
2983 std::pair<RegMapTy::iterator, bool> Pair =
2984 Map.insert(std::make_pair(Reg, ImmMapTy()));
2985 if (Pair.second)
2986 Sequence.push_back(Reg);
2987 Pair.first->second.insert(std::make_pair(Imm, *I));
2988 UsedByIndicesMap[Reg] |= RegUses.getUsedByIndices(*I);
2989 }
2990
2991 // Now examine each set of registers with the same base value. Build up
2992 // a list of work to do and do the work in a separate step so that we're
2993 // not adding formulae and register counts while we're searching.
Dan Gohman191bd642010-09-01 01:45:53 +00002994 SmallVector<WorkItem, 32> WorkItems;
2995 SmallSet<std::pair<size_t, int64_t>, 32> UniqueItems;
Dan Gohman572645c2010-02-12 10:34:29 +00002996 for (SmallVectorImpl<const SCEV *>::const_iterator I = Sequence.begin(),
2997 E = Sequence.end(); I != E; ++I) {
2998 const SCEV *Reg = *I;
2999 const ImmMapTy &Imms = Map.find(Reg)->second;
3000
Dan Gohmancd045c02010-02-12 19:20:37 +00003001 // It's not worthwhile looking for reuse if there's only one offset.
3002 if (Imms.size() == 1)
3003 continue;
3004
Dan Gohman572645c2010-02-12 10:34:29 +00003005 DEBUG(dbgs() << "Generating cross-use offsets for " << *Reg << ':';
3006 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
3007 J != JE; ++J)
3008 dbgs() << ' ' << J->first;
3009 dbgs() << '\n');
3010
3011 // Examine each offset.
3012 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
3013 J != JE; ++J) {
3014 const SCEV *OrigReg = J->second;
3015
3016 int64_t JImm = J->first;
3017 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg);
3018
3019 if (!isa<SCEVConstant>(OrigReg) &&
3020 UsedByIndicesMap[Reg].count() == 1) {
3021 DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg << '\n');
3022 continue;
3023 }
3024
3025 // Conservatively examine offsets between this orig reg a few selected
3026 // other orig regs.
3027 ImmMapTy::const_iterator OtherImms[] = {
3028 Imms.begin(), prior(Imms.end()),
Dan Gohmancca82142011-05-03 00:46:49 +00003029 Imms.lower_bound((Imms.begin()->first + prior(Imms.end())->first) / 2)
Dan Gohman572645c2010-02-12 10:34:29 +00003030 };
3031 for (size_t i = 0, e = array_lengthof(OtherImms); i != e; ++i) {
3032 ImmMapTy::const_iterator M = OtherImms[i];
Dan Gohmancd045c02010-02-12 19:20:37 +00003033 if (M == J || M == JE) continue;
Dan Gohman572645c2010-02-12 10:34:29 +00003034
3035 // Compute the difference between the two.
3036 int64_t Imm = (uint64_t)JImm - M->first;
3037 for (int LUIdx = UsedByIndices.find_first(); LUIdx != -1;
Dan Gohman191bd642010-09-01 01:45:53 +00003038 LUIdx = UsedByIndices.find_next(LUIdx))
Dan Gohman572645c2010-02-12 10:34:29 +00003039 // Make a memo of this use, offset, and register tuple.
Dan Gohman191bd642010-09-01 01:45:53 +00003040 if (UniqueItems.insert(std::make_pair(LUIdx, Imm)))
3041 WorkItems.push_back(WorkItem(LUIdx, Imm, OrigReg));
Evan Cheng586f69a2009-11-12 07:35:05 +00003042 }
3043 }
3044 }
3045
Dan Gohman572645c2010-02-12 10:34:29 +00003046 Map.clear();
3047 Sequence.clear();
3048 UsedByIndicesMap.clear();
Dan Gohman191bd642010-09-01 01:45:53 +00003049 UniqueItems.clear();
Dan Gohman572645c2010-02-12 10:34:29 +00003050
3051 // Now iterate through the worklist and add new formulae.
3052 for (SmallVectorImpl<WorkItem>::const_iterator I = WorkItems.begin(),
3053 E = WorkItems.end(); I != E; ++I) {
3054 const WorkItem &WI = *I;
3055 size_t LUIdx = WI.LUIdx;
3056 LSRUse &LU = Uses[LUIdx];
3057 int64_t Imm = WI.Imm;
3058 const SCEV *OrigReg = WI.OrigReg;
3059
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003060 Type *IntTy = SE.getEffectiveSCEVType(OrigReg->getType());
Dan Gohman572645c2010-02-12 10:34:29 +00003061 const SCEV *NegImmS = SE.getSCEV(ConstantInt::get(IntTy, -(uint64_t)Imm));
3062 unsigned BitWidth = SE.getTypeSizeInBits(IntTy);
3063
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003064 // TODO: Use a more targeted data structure.
Dan Gohman572645c2010-02-12 10:34:29 +00003065 for (size_t L = 0, LE = LU.Formulae.size(); L != LE; ++L) {
Dan Gohman9f383eb2010-05-20 22:25:20 +00003066 const Formula &F = LU.Formulae[L];
Dan Gohman572645c2010-02-12 10:34:29 +00003067 // Use the immediate in the scaled register.
3068 if (F.ScaledReg == OrigReg) {
3069 int64_t Offs = (uint64_t)F.AM.BaseOffs +
3070 Imm * (uint64_t)F.AM.Scale;
3071 // Don't create 50 + reg(-50).
3072 if (F.referencesReg(SE.getSCEV(
3073 ConstantInt::get(IntTy, -(uint64_t)Offs))))
3074 continue;
3075 Formula NewF = F;
3076 NewF.AM.BaseOffs = Offs;
3077 if (!isLegalUse(NewF.AM, LU.MinOffset, LU.MaxOffset,
3078 LU.Kind, LU.AccessTy, TLI))
3079 continue;
3080 NewF.ScaledReg = SE.getAddExpr(NegImmS, NewF.ScaledReg);
3081
3082 // If the new scale is a constant in a register, and adding the constant
3083 // value to the immediate would produce a value closer to zero than the
3084 // immediate itself, then the formula isn't worthwhile.
3085 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewF.ScaledReg))
Chris Lattnerc73b24d2011-07-15 06:08:15 +00003086 if (C->getValue()->isNegative() !=
Dan Gohman572645c2010-02-12 10:34:29 +00003087 (NewF.AM.BaseOffs < 0) &&
3088 (C->getValue()->getValue().abs() * APInt(BitWidth, F.AM.Scale))
Dan Gohmane0567812010-04-08 23:03:40 +00003089 .ule(abs64(NewF.AM.BaseOffs)))
Dan Gohman572645c2010-02-12 10:34:29 +00003090 continue;
3091
3092 // OK, looks good.
3093 (void)InsertFormula(LU, LUIdx, NewF);
3094 } else {
3095 // Use the immediate in a base register.
3096 for (size_t N = 0, NE = F.BaseRegs.size(); N != NE; ++N) {
3097 const SCEV *BaseReg = F.BaseRegs[N];
3098 if (BaseReg != OrigReg)
3099 continue;
3100 Formula NewF = F;
3101 NewF.AM.BaseOffs = (uint64_t)NewF.AM.BaseOffs + Imm;
3102 if (!isLegalUse(NewF.AM, LU.MinOffset, LU.MaxOffset,
Dan Gohmancca82142011-05-03 00:46:49 +00003103 LU.Kind, LU.AccessTy, TLI)) {
3104 if (!TLI ||
3105 !TLI->isLegalAddImmediate((uint64_t)NewF.UnfoldedOffset + Imm))
3106 continue;
3107 NewF = F;
3108 NewF.UnfoldedOffset = (uint64_t)NewF.UnfoldedOffset + Imm;
3109 }
Dan Gohman572645c2010-02-12 10:34:29 +00003110 NewF.BaseRegs[N] = SE.getAddExpr(NegImmS, BaseReg);
3111
3112 // If the new formula has a constant in a register, and adding the
3113 // constant value to the immediate would produce a value closer to
3114 // zero than the immediate itself, then the formula isn't worthwhile.
3115 for (SmallVectorImpl<const SCEV *>::const_iterator
3116 J = NewF.BaseRegs.begin(), JE = NewF.BaseRegs.end();
3117 J != JE; ++J)
3118 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*J))
Dan Gohman360026f2010-05-18 23:48:08 +00003119 if ((C->getValue()->getValue() + NewF.AM.BaseOffs).abs().slt(
3120 abs64(NewF.AM.BaseOffs)) &&
3121 (C->getValue()->getValue() +
3122 NewF.AM.BaseOffs).countTrailingZeros() >=
3123 CountTrailingZeros_64(NewF.AM.BaseOffs))
Dan Gohman572645c2010-02-12 10:34:29 +00003124 goto skip_formula;
3125
3126 // Ok, looks good.
3127 (void)InsertFormula(LU, LUIdx, NewF);
3128 break;
3129 skip_formula:;
3130 }
3131 }
3132 }
3133 }
Dale Johannesenc1acc3f2009-05-11 17:15:42 +00003134}
3135
Dan Gohman572645c2010-02-12 10:34:29 +00003136/// GenerateAllReuseFormulae - Generate formulae for each use.
3137void
3138LSRInstance::GenerateAllReuseFormulae() {
Dan Gohmanc2385a02010-02-16 01:42:53 +00003139 // This is split into multiple loops so that hasRegsUsedByUsesOtherThan
Dan Gohman572645c2010-02-12 10:34:29 +00003140 // queries are more precise.
3141 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3142 LSRUse &LU = Uses[LUIdx];
3143 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3144 GenerateReassociations(LU, LUIdx, LU.Formulae[i]);
3145 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3146 GenerateCombinations(LU, LUIdx, LU.Formulae[i]);
3147 }
3148 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3149 LSRUse &LU = Uses[LUIdx];
3150 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3151 GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]);
3152 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3153 GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]);
3154 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3155 GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]);
3156 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3157 GenerateScales(LU, LUIdx, LU.Formulae[i]);
Dan Gohmanc2385a02010-02-16 01:42:53 +00003158 }
3159 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3160 LSRUse &LU = Uses[LUIdx];
Dan Gohman572645c2010-02-12 10:34:29 +00003161 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3162 GenerateTruncates(LU, LUIdx, LU.Formulae[i]);
3163 }
3164
3165 GenerateCrossUseConstantOffsets();
Dan Gohman3902f9f2010-08-29 15:21:38 +00003166
3167 DEBUG(dbgs() << "\n"
3168 "After generating reuse formulae:\n";
3169 print_uses(dbgs()));
Dan Gohman572645c2010-02-12 10:34:29 +00003170}
3171
Dan Gohmanf63d70f2010-10-07 23:43:09 +00003172/// If there are multiple formulae with the same set of registers used
Dan Gohman572645c2010-02-12 10:34:29 +00003173/// by other uses, pick the best one and delete the others.
3174void LSRInstance::FilterOutUndesirableDedicatedRegisters() {
Dan Gohmanfc7744b2010-10-07 23:52:18 +00003175 DenseSet<const SCEV *> VisitedRegs;
3176 SmallPtrSet<const SCEV *, 16> Regs;
Andrew Trick8a5d7922011-12-06 03:13:31 +00003177 SmallPtrSet<const SCEV *, 16> LoserRegs;
Dan Gohman572645c2010-02-12 10:34:29 +00003178#ifndef NDEBUG
Dan Gohmanc6519f92010-05-20 20:05:31 +00003179 bool ChangedFormulae = false;
Dan Gohman572645c2010-02-12 10:34:29 +00003180#endif
3181
3182 // Collect the best formula for each unique set of shared registers. This
3183 // is reset for each use.
3184 typedef DenseMap<SmallVector<const SCEV *, 2>, size_t, UniquifierDenseMapInfo>
3185 BestFormulaeTy;
3186 BestFormulaeTy BestFormulae;
3187
3188 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3189 LSRUse &LU = Uses[LUIdx];
Dan Gohmanea507f52010-05-20 19:44:23 +00003190 DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs()); dbgs() << '\n');
Dan Gohman572645c2010-02-12 10:34:29 +00003191
Dan Gohmanb2df4332010-05-18 23:42:37 +00003192 bool Any = false;
Dan Gohman572645c2010-02-12 10:34:29 +00003193 for (size_t FIdx = 0, NumForms = LU.Formulae.size();
3194 FIdx != NumForms; ++FIdx) {
3195 Formula &F = LU.Formulae[FIdx];
3196
Andrew Trick8a5d7922011-12-06 03:13:31 +00003197 // Some formulas are instant losers. For example, they may depend on
3198 // nonexistent AddRecs from other loops. These need to be filtered
3199 // immediately, otherwise heuristics could choose them over others leading
3200 // to an unsatisfactory solution. Passing LoserRegs into RateFormula here
3201 // avoids the need to recompute this information across formulae using the
3202 // same bad AddRec. Passing LoserRegs is also essential unless we remove
3203 // the corresponding bad register from the Regs set.
3204 Cost CostF;
3205 Regs.clear();
3206 CostF.RateFormula(F, Regs, VisitedRegs, L, LU.Offsets, SE, DT,
3207 &LoserRegs);
3208 if (CostF.isLoser()) {
3209 // During initial formula generation, undesirable formulae are generated
3210 // by uses within other loops that have some non-trivial address mode or
3211 // use the postinc form of the IV. LSR needs to provide these formulae
3212 // as the basis of rediscovering the desired formula that uses an AddRec
3213 // corresponding to the existing phi. Once all formulae have been
3214 // generated, these initial losers may be pruned.
3215 DEBUG(dbgs() << " Filtering loser "; F.print(dbgs());
3216 dbgs() << "\n");
Dan Gohman572645c2010-02-12 10:34:29 +00003217 }
Andrew Trick8a5d7922011-12-06 03:13:31 +00003218 else {
3219 SmallVector<const SCEV *, 2> Key;
3220 for (SmallVectorImpl<const SCEV *>::const_iterator J = F.BaseRegs.begin(),
3221 JE = F.BaseRegs.end(); J != JE; ++J) {
3222 const SCEV *Reg = *J;
3223 if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx))
3224 Key.push_back(Reg);
3225 }
3226 if (F.ScaledReg &&
3227 RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx))
3228 Key.push_back(F.ScaledReg);
3229 // Unstable sort by host order ok, because this is only used for
3230 // uniquifying.
3231 std::sort(Key.begin(), Key.end());
Dan Gohman572645c2010-02-12 10:34:29 +00003232
Andrew Trick8a5d7922011-12-06 03:13:31 +00003233 std::pair<BestFormulaeTy::const_iterator, bool> P =
3234 BestFormulae.insert(std::make_pair(Key, FIdx));
3235 if (P.second)
3236 continue;
3237
Dan Gohman572645c2010-02-12 10:34:29 +00003238 Formula &Best = LU.Formulae[P.first->second];
Dan Gohmanfc7744b2010-10-07 23:52:18 +00003239
Dan Gohmanfc7744b2010-10-07 23:52:18 +00003240 Cost CostBest;
Dan Gohmanfc7744b2010-10-07 23:52:18 +00003241 Regs.clear();
Andrew Trick8a5d7922011-12-06 03:13:31 +00003242 CostBest.RateFormula(Best, Regs, VisitedRegs, L, LU.Offsets, SE, DT);
Dan Gohmanfc7744b2010-10-07 23:52:18 +00003243 if (CostF < CostBest)
Dan Gohman572645c2010-02-12 10:34:29 +00003244 std::swap(F, Best);
Dan Gohman6458ff92010-05-18 22:37:37 +00003245 DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs());
Dan Gohman572645c2010-02-12 10:34:29 +00003246 dbgs() << "\n"
Dan Gohman6458ff92010-05-18 22:37:37 +00003247 " in favor of formula "; Best.print(dbgs());
Dan Gohman572645c2010-02-12 10:34:29 +00003248 dbgs() << '\n');
Dan Gohman572645c2010-02-12 10:34:29 +00003249 }
Andrew Trick8a5d7922011-12-06 03:13:31 +00003250#ifndef NDEBUG
3251 ChangedFormulae = true;
3252#endif
3253 LU.DeleteFormula(F);
3254 --FIdx;
3255 --NumForms;
3256 Any = true;
Dan Gohman59dc6032010-05-07 23:36:59 +00003257 }
3258
Dan Gohman57aaa0b2010-05-18 23:55:57 +00003259 // Now that we've filtered out some formulae, recompute the Regs set.
Dan Gohmanb2df4332010-05-18 23:42:37 +00003260 if (Any)
3261 LU.RecomputeRegs(LUIdx, RegUses);
Dan Gohman59dc6032010-05-07 23:36:59 +00003262
3263 // Reset this to prepare for the next use.
Dan Gohman572645c2010-02-12 10:34:29 +00003264 BestFormulae.clear();
3265 }
3266
Dan Gohmanc6519f92010-05-20 20:05:31 +00003267 DEBUG(if (ChangedFormulae) {
Dan Gohman9214b822010-02-13 02:06:02 +00003268 dbgs() << "\n"
3269 "After filtering out undesirable candidates:\n";
Dan Gohman572645c2010-02-12 10:34:29 +00003270 print_uses(dbgs());
3271 });
3272}
3273
Dan Gohmand079c302010-05-18 22:51:59 +00003274// This is a rough guess that seems to work fairly well.
3275static const size_t ComplexityLimit = UINT16_MAX;
3276
3277/// EstimateSearchSpaceComplexity - Estimate the worst-case number of
3278/// solutions the solver might have to consider. It almost never considers
3279/// this many solutions because it prune the search space, but the pruning
3280/// isn't always sufficient.
3281size_t LSRInstance::EstimateSearchSpaceComplexity() const {
Dan Gohman0d6715a2010-10-07 23:37:58 +00003282 size_t Power = 1;
Dan Gohmand079c302010-05-18 22:51:59 +00003283 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
3284 E = Uses.end(); I != E; ++I) {
3285 size_t FSize = I->Formulae.size();
3286 if (FSize >= ComplexityLimit) {
3287 Power = ComplexityLimit;
3288 break;
3289 }
3290 Power *= FSize;
3291 if (Power >= ComplexityLimit)
3292 break;
3293 }
3294 return Power;
3295}
3296
Dan Gohman4aa5c2e2010-08-29 16:09:42 +00003297/// NarrowSearchSpaceByDetectingSupersets - When one formula uses a superset
3298/// of the registers of another formula, it won't help reduce register
3299/// pressure (though it may not necessarily hurt register pressure); remove
3300/// it to simplify the system.
3301void LSRInstance::NarrowSearchSpaceByDetectingSupersets() {
Dan Gohmana2086b32010-05-19 23:43:12 +00003302 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
3303 DEBUG(dbgs() << "The search space is too complex.\n");
3304
3305 DEBUG(dbgs() << "Narrowing the search space by eliminating formulae "
3306 "which use a superset of registers used by other "
3307 "formulae.\n");
3308
3309 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3310 LSRUse &LU = Uses[LUIdx];
3311 bool Any = false;
3312 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
3313 Formula &F = LU.Formulae[i];
Dan Gohmanf7ff37d2010-05-20 20:00:41 +00003314 // Look for a formula with a constant or GV in a register. If the use
3315 // also has a formula with that same value in an immediate field,
3316 // delete the one that uses a register.
Dan Gohmana2086b32010-05-19 23:43:12 +00003317 for (SmallVectorImpl<const SCEV *>::const_iterator
3318 I = F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I) {
3319 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*I)) {
3320 Formula NewF = F;
3321 NewF.AM.BaseOffs += C->getValue()->getSExtValue();
3322 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
3323 (I - F.BaseRegs.begin()));
3324 if (LU.HasFormulaWithSameRegs(NewF)) {
3325 DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
3326 LU.DeleteFormula(F);
3327 --i;
3328 --e;
3329 Any = true;
3330 break;
3331 }
3332 } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(*I)) {
3333 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue()))
3334 if (!F.AM.BaseGV) {
3335 Formula NewF = F;
3336 NewF.AM.BaseGV = GV;
3337 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
3338 (I - F.BaseRegs.begin()));
3339 if (LU.HasFormulaWithSameRegs(NewF)) {
3340 DEBUG(dbgs() << " Deleting "; F.print(dbgs());
3341 dbgs() << '\n');
3342 LU.DeleteFormula(F);
3343 --i;
3344 --e;
3345 Any = true;
3346 break;
3347 }
3348 }
3349 }
3350 }
3351 }
3352 if (Any)
3353 LU.RecomputeRegs(LUIdx, RegUses);
3354 }
3355
3356 DEBUG(dbgs() << "After pre-selection:\n";
3357 print_uses(dbgs()));
3358 }
Dan Gohman4aa5c2e2010-08-29 16:09:42 +00003359}
Dan Gohmana2086b32010-05-19 23:43:12 +00003360
Dan Gohman4aa5c2e2010-08-29 16:09:42 +00003361/// NarrowSearchSpaceByCollapsingUnrolledCode - When there are many registers
3362/// for expressions like A, A+1, A+2, etc., allocate a single register for
3363/// them.
3364void LSRInstance::NarrowSearchSpaceByCollapsingUnrolledCode() {
Dan Gohmana2086b32010-05-19 23:43:12 +00003365 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
3366 DEBUG(dbgs() << "The search space is too complex.\n");
3367
3368 DEBUG(dbgs() << "Narrowing the search space by assuming that uses "
3369 "separated by a constant offset will use the same "
3370 "registers.\n");
3371
Dan Gohmanf7ff37d2010-05-20 20:00:41 +00003372 // This is especially useful for unrolled loops.
3373
Dan Gohmana2086b32010-05-19 23:43:12 +00003374 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3375 LSRUse &LU = Uses[LUIdx];
Dan Gohman402d4352010-05-20 20:33:18 +00003376 for (SmallVectorImpl<Formula>::const_iterator I = LU.Formulae.begin(),
3377 E = LU.Formulae.end(); I != E; ++I) {
3378 const Formula &F = *I;
Dan Gohmana2086b32010-05-19 23:43:12 +00003379 if (F.AM.BaseOffs != 0 && F.AM.Scale == 0) {
Dan Gohman191bd642010-09-01 01:45:53 +00003380 if (LSRUse *LUThatHas = FindUseWithSimilarFormula(F, LU)) {
3381 if (reconcileNewOffset(*LUThatHas, F.AM.BaseOffs,
Dan Gohmana2086b32010-05-19 23:43:12 +00003382 /*HasBaseReg=*/false,
3383 LU.Kind, LU.AccessTy)) {
3384 DEBUG(dbgs() << " Deleting use "; LU.print(dbgs());
3385 dbgs() << '\n');
3386
3387 LUThatHas->AllFixupsOutsideLoop &= LU.AllFixupsOutsideLoop;
3388
Dan Gohman191bd642010-09-01 01:45:53 +00003389 // Update the relocs to reference the new use.
3390 for (SmallVectorImpl<LSRFixup>::iterator I = Fixups.begin(),
3391 E = Fixups.end(); I != E; ++I) {
3392 LSRFixup &Fixup = *I;
3393 if (Fixup.LUIdx == LUIdx) {
3394 Fixup.LUIdx = LUThatHas - &Uses.front();
3395 Fixup.Offset += F.AM.BaseOffs;
Dan Gohmandd3db0e2010-10-07 23:36:45 +00003396 // Add the new offset to LUThatHas' offset list.
3397 if (LUThatHas->Offsets.back() != Fixup.Offset) {
3398 LUThatHas->Offsets.push_back(Fixup.Offset);
3399 if (Fixup.Offset > LUThatHas->MaxOffset)
3400 LUThatHas->MaxOffset = Fixup.Offset;
3401 if (Fixup.Offset < LUThatHas->MinOffset)
3402 LUThatHas->MinOffset = Fixup.Offset;
3403 }
Dan Gohman191bd642010-09-01 01:45:53 +00003404 DEBUG(dbgs() << "New fixup has offset "
3405 << Fixup.Offset << '\n');
3406 }
3407 if (Fixup.LUIdx == NumUses-1)
3408 Fixup.LUIdx = LUIdx;
3409 }
3410
Dan Gohmanc2921ea2010-10-08 19:33:26 +00003411 // Delete formulae from the new use which are no longer legal.
3412 bool Any = false;
3413 for (size_t i = 0, e = LUThatHas->Formulae.size(); i != e; ++i) {
3414 Formula &F = LUThatHas->Formulae[i];
3415 if (!isLegalUse(F.AM,
3416 LUThatHas->MinOffset, LUThatHas->MaxOffset,
3417 LUThatHas->Kind, LUThatHas->AccessTy, TLI)) {
3418 DEBUG(dbgs() << " Deleting "; F.print(dbgs());
3419 dbgs() << '\n');
3420 LUThatHas->DeleteFormula(F);
3421 --i;
3422 --e;
3423 Any = true;
3424 }
3425 }
3426 if (Any)
3427 LUThatHas->RecomputeRegs(LUThatHas - &Uses.front(), RegUses);
3428
Dan Gohmana2086b32010-05-19 23:43:12 +00003429 // Delete the old use.
Dan Gohmanc6897702010-10-07 23:33:43 +00003430 DeleteUse(LU, LUIdx);
Dan Gohmana2086b32010-05-19 23:43:12 +00003431 --LUIdx;
3432 --NumUses;
3433 break;
3434 }
3435 }
3436 }
3437 }
3438 }
3439
3440 DEBUG(dbgs() << "After pre-selection:\n";
3441 print_uses(dbgs()));
3442 }
Dan Gohman4aa5c2e2010-08-29 16:09:42 +00003443}
Dan Gohmana2086b32010-05-19 23:43:12 +00003444
Andrew Trick3228cc22011-03-14 16:50:06 +00003445/// NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters - Call
Dan Gohman4f7e18d2010-08-29 16:39:22 +00003446/// FilterOutUndesirableDedicatedRegisters again, if necessary, now that
3447/// we've done more filtering, as it may be able to find more formulae to
3448/// eliminate.
3449void LSRInstance::NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters(){
3450 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
3451 DEBUG(dbgs() << "The search space is too complex.\n");
3452
3453 DEBUG(dbgs() << "Narrowing the search space by re-filtering out "
3454 "undesirable dedicated registers.\n");
3455
3456 FilterOutUndesirableDedicatedRegisters();
3457
3458 DEBUG(dbgs() << "After pre-selection:\n";
3459 print_uses(dbgs()));
3460 }
3461}
3462
Dan Gohman4aa5c2e2010-08-29 16:09:42 +00003463/// NarrowSearchSpaceByPickingWinnerRegs - Pick a register which seems likely
3464/// to be profitable, and then in any use which has any reference to that
3465/// register, delete all formulae which do not reference that register.
3466void LSRInstance::NarrowSearchSpaceByPickingWinnerRegs() {
Dan Gohman76c315a2010-05-20 20:52:00 +00003467 // With all other options exhausted, loop until the system is simple
3468 // enough to handle.
Dan Gohman572645c2010-02-12 10:34:29 +00003469 SmallPtrSet<const SCEV *, 4> Taken;
Dan Gohmand079c302010-05-18 22:51:59 +00003470 while (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
Dan Gohman572645c2010-02-12 10:34:29 +00003471 // Ok, we have too many of formulae on our hands to conveniently handle.
3472 // Use a rough heuristic to thin out the list.
Dan Gohman0da751b2010-05-18 22:41:32 +00003473 DEBUG(dbgs() << "The search space is too complex.\n");
Dan Gohman572645c2010-02-12 10:34:29 +00003474
3475 // Pick the register which is used by the most LSRUses, which is likely
3476 // to be a good reuse register candidate.
3477 const SCEV *Best = 0;
3478 unsigned BestNum = 0;
3479 for (RegUseTracker::const_iterator I = RegUses.begin(), E = RegUses.end();
3480 I != E; ++I) {
3481 const SCEV *Reg = *I;
3482 if (Taken.count(Reg))
3483 continue;
3484 if (!Best)
3485 Best = Reg;
3486 else {
3487 unsigned Count = RegUses.getUsedByIndices(Reg).count();
3488 if (Count > BestNum) {
3489 Best = Reg;
3490 BestNum = Count;
3491 }
3492 }
3493 }
3494
3495 DEBUG(dbgs() << "Narrowing the search space by assuming " << *Best
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003496 << " will yield profitable reuse.\n");
Dan Gohman572645c2010-02-12 10:34:29 +00003497 Taken.insert(Best);
3498
3499 // In any use with formulae which references this register, delete formulae
3500 // which don't reference it.
Dan Gohmanb2df4332010-05-18 23:42:37 +00003501 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3502 LSRUse &LU = Uses[LUIdx];
Dan Gohman572645c2010-02-12 10:34:29 +00003503 if (!LU.Regs.count(Best)) continue;
3504
Dan Gohmanb2df4332010-05-18 23:42:37 +00003505 bool Any = false;
Dan Gohman572645c2010-02-12 10:34:29 +00003506 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
3507 Formula &F = LU.Formulae[i];
3508 if (!F.referencesReg(Best)) {
3509 DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
Dan Gohmand69d6282010-05-18 22:39:15 +00003510 LU.DeleteFormula(F);
Dan Gohman572645c2010-02-12 10:34:29 +00003511 --e;
3512 --i;
Dan Gohmanb2df4332010-05-18 23:42:37 +00003513 Any = true;
Dan Gohman59dc6032010-05-07 23:36:59 +00003514 assert(e != 0 && "Use has no formulae left! Is Regs inconsistent?");
Dan Gohman572645c2010-02-12 10:34:29 +00003515 continue;
3516 }
Dan Gohman572645c2010-02-12 10:34:29 +00003517 }
Dan Gohmanb2df4332010-05-18 23:42:37 +00003518
3519 if (Any)
3520 LU.RecomputeRegs(LUIdx, RegUses);
Dan Gohman572645c2010-02-12 10:34:29 +00003521 }
3522
3523 DEBUG(dbgs() << "After pre-selection:\n";
3524 print_uses(dbgs()));
3525 }
3526}
3527
Dan Gohman4aa5c2e2010-08-29 16:09:42 +00003528/// NarrowSearchSpaceUsingHeuristics - If there are an extraordinary number of
3529/// formulae to choose from, use some rough heuristics to prune down the number
3530/// of formulae. This keeps the main solver from taking an extraordinary amount
3531/// of time in some worst-case scenarios.
3532void LSRInstance::NarrowSearchSpaceUsingHeuristics() {
3533 NarrowSearchSpaceByDetectingSupersets();
3534 NarrowSearchSpaceByCollapsingUnrolledCode();
Dan Gohman4f7e18d2010-08-29 16:39:22 +00003535 NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
Dan Gohman4aa5c2e2010-08-29 16:09:42 +00003536 NarrowSearchSpaceByPickingWinnerRegs();
3537}
3538
Dan Gohman572645c2010-02-12 10:34:29 +00003539/// SolveRecurse - This is the recursive solver.
3540void LSRInstance::SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
3541 Cost &SolutionCost,
3542 SmallVectorImpl<const Formula *> &Workspace,
3543 const Cost &CurCost,
3544 const SmallPtrSet<const SCEV *, 16> &CurRegs,
3545 DenseSet<const SCEV *> &VisitedRegs) const {
3546 // Some ideas:
3547 // - prune more:
3548 // - use more aggressive filtering
3549 // - sort the formula so that the most profitable solutions are found first
3550 // - sort the uses too
3551 // - search faster:
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003552 // - don't compute a cost, and then compare. compare while computing a cost
Dan Gohman572645c2010-02-12 10:34:29 +00003553 // and bail early.
3554 // - track register sets with SmallBitVector
3555
3556 const LSRUse &LU = Uses[Workspace.size()];
3557
3558 // If this use references any register that's already a part of the
3559 // in-progress solution, consider it a requirement that a formula must
3560 // reference that register in order to be considered. This prunes out
3561 // unprofitable searching.
3562 SmallSetVector<const SCEV *, 4> ReqRegs;
3563 for (SmallPtrSet<const SCEV *, 16>::const_iterator I = CurRegs.begin(),
3564 E = CurRegs.end(); I != E; ++I)
Dan Gohman9214b822010-02-13 02:06:02 +00003565 if (LU.Regs.count(*I))
Dan Gohman572645c2010-02-12 10:34:29 +00003566 ReqRegs.insert(*I);
Dan Gohman572645c2010-02-12 10:34:29 +00003567
Dan Gohman9214b822010-02-13 02:06:02 +00003568 bool AnySatisfiedReqRegs = false;
Dan Gohman572645c2010-02-12 10:34:29 +00003569 SmallPtrSet<const SCEV *, 16> NewRegs;
3570 Cost NewCost;
Dan Gohman9214b822010-02-13 02:06:02 +00003571retry:
Dan Gohman572645c2010-02-12 10:34:29 +00003572 for (SmallVectorImpl<Formula>::const_iterator I = LU.Formulae.begin(),
3573 E = LU.Formulae.end(); I != E; ++I) {
3574 const Formula &F = *I;
3575
3576 // Ignore formulae which do not use any of the required registers.
3577 for (SmallSetVector<const SCEV *, 4>::const_iterator J = ReqRegs.begin(),
3578 JE = ReqRegs.end(); J != JE; ++J) {
3579 const SCEV *Reg = *J;
3580 if ((!F.ScaledReg || F.ScaledReg != Reg) &&
3581 std::find(F.BaseRegs.begin(), F.BaseRegs.end(), Reg) ==
3582 F.BaseRegs.end())
3583 goto skip;
3584 }
Dan Gohman9214b822010-02-13 02:06:02 +00003585 AnySatisfiedReqRegs = true;
Dan Gohman572645c2010-02-12 10:34:29 +00003586
3587 // Evaluate the cost of the current formula. If it's already worse than
3588 // the current best, prune the search at that point.
3589 NewCost = CurCost;
3590 NewRegs = CurRegs;
3591 NewCost.RateFormula(F, NewRegs, VisitedRegs, L, LU.Offsets, SE, DT);
3592 if (NewCost < SolutionCost) {
3593 Workspace.push_back(&F);
3594 if (Workspace.size() != Uses.size()) {
3595 SolveRecurse(Solution, SolutionCost, Workspace, NewCost,
3596 NewRegs, VisitedRegs);
3597 if (F.getNumRegs() == 1 && Workspace.size() == 1)
3598 VisitedRegs.insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]);
3599 } else {
3600 DEBUG(dbgs() << "New best at "; NewCost.print(dbgs());
Andrew Trick8bf295b2012-01-09 18:58:16 +00003601 dbgs() << ".\n Regs:";
Dan Gohman572645c2010-02-12 10:34:29 +00003602 for (SmallPtrSet<const SCEV *, 16>::const_iterator
3603 I = NewRegs.begin(), E = NewRegs.end(); I != E; ++I)
3604 dbgs() << ' ' << **I;
3605 dbgs() << '\n');
3606
3607 SolutionCost = NewCost;
3608 Solution = Workspace;
3609 }
3610 Workspace.pop_back();
3611 }
3612 skip:;
3613 }
Dan Gohman9214b822010-02-13 02:06:02 +00003614
Andrew Trick80ef1b22011-09-27 00:44:14 +00003615 if (!EnableRetry && !AnySatisfiedReqRegs)
3616 return;
3617
Dan Gohman9214b822010-02-13 02:06:02 +00003618 // If none of the formulae had all of the required registers, relax the
3619 // constraint so that we don't exclude all formulae.
3620 if (!AnySatisfiedReqRegs) {
Dan Gohman59dc6032010-05-07 23:36:59 +00003621 assert(!ReqRegs.empty() && "Solver failed even without required registers");
Dan Gohman9214b822010-02-13 02:06:02 +00003622 ReqRegs.clear();
3623 goto retry;
3624 }
Dan Gohman572645c2010-02-12 10:34:29 +00003625}
3626
Dan Gohman76c315a2010-05-20 20:52:00 +00003627/// Solve - Choose one formula from each use. Return the results in the given
3628/// Solution vector.
Dan Gohman572645c2010-02-12 10:34:29 +00003629void LSRInstance::Solve(SmallVectorImpl<const Formula *> &Solution) const {
3630 SmallVector<const Formula *, 8> Workspace;
3631 Cost SolutionCost;
3632 SolutionCost.Loose();
3633 Cost CurCost;
3634 SmallPtrSet<const SCEV *, 16> CurRegs;
3635 DenseSet<const SCEV *> VisitedRegs;
3636 Workspace.reserve(Uses.size());
3637
Dan Gohmanf7ff37d2010-05-20 20:00:41 +00003638 // SolveRecurse does all the work.
Dan Gohman572645c2010-02-12 10:34:29 +00003639 SolveRecurse(Solution, SolutionCost, Workspace, CurCost,
3640 CurRegs, VisitedRegs);
Andrew Trick80ef1b22011-09-27 00:44:14 +00003641 if (Solution.empty()) {
3642 DEBUG(dbgs() << "\nNo Satisfactory Solution\n");
3643 return;
3644 }
Dan Gohman572645c2010-02-12 10:34:29 +00003645
3646 // Ok, we've now made all our decisions.
3647 DEBUG(dbgs() << "\n"
3648 "The chosen solution requires "; SolutionCost.print(dbgs());
3649 dbgs() << ":\n";
3650 for (size_t i = 0, e = Uses.size(); i != e; ++i) {
3651 dbgs() << " ";
3652 Uses[i].print(dbgs());
3653 dbgs() << "\n"
3654 " ";
3655 Solution[i]->print(dbgs());
3656 dbgs() << '\n';
3657 });
Dan Gohmana5528782010-05-20 20:59:23 +00003658
3659 assert(Solution.size() == Uses.size() && "Malformed solution!");
Dan Gohman572645c2010-02-12 10:34:29 +00003660}
3661
Dan Gohmane5f76872010-04-09 22:07:05 +00003662/// HoistInsertPosition - Helper for AdjustInsertPositionForExpand. Climb up
3663/// the dominator tree far as we can go while still being dominated by the
3664/// input positions. This helps canonicalize the insert position, which
3665/// encourages sharing.
3666BasicBlock::iterator
3667LSRInstance::HoistInsertPosition(BasicBlock::iterator IP,
3668 const SmallVectorImpl<Instruction *> &Inputs)
3669 const {
3670 for (;;) {
3671 const Loop *IPLoop = LI.getLoopFor(IP->getParent());
3672 unsigned IPLoopDepth = IPLoop ? IPLoop->getLoopDepth() : 0;
3673
3674 BasicBlock *IDom;
Dan Gohmand974a0e2010-05-20 20:00:25 +00003675 for (DomTreeNode *Rung = DT.getNode(IP->getParent()); ; ) {
Dan Gohman0fe46d92010-05-20 22:46:54 +00003676 if (!Rung) return IP;
Dan Gohmand974a0e2010-05-20 20:00:25 +00003677 Rung = Rung->getIDom();
3678 if (!Rung) return IP;
3679 IDom = Rung->getBlock();
Dan Gohmane5f76872010-04-09 22:07:05 +00003680
3681 // Don't climb into a loop though.
3682 const Loop *IDomLoop = LI.getLoopFor(IDom);
3683 unsigned IDomDepth = IDomLoop ? IDomLoop->getLoopDepth() : 0;
3684 if (IDomDepth <= IPLoopDepth &&
3685 (IDomDepth != IPLoopDepth || IDomLoop == IPLoop))
3686 break;
3687 }
3688
3689 bool AllDominate = true;
3690 Instruction *BetterPos = 0;
3691 Instruction *Tentative = IDom->getTerminator();
3692 for (SmallVectorImpl<Instruction *>::const_iterator I = Inputs.begin(),
3693 E = Inputs.end(); I != E; ++I) {
3694 Instruction *Inst = *I;
3695 if (Inst == Tentative || !DT.dominates(Inst, Tentative)) {
3696 AllDominate = false;
3697 break;
3698 }
3699 // Attempt to find an insert position in the middle of the block,
3700 // instead of at the end, so that it can be used for other expansions.
3701 if (IDom == Inst->getParent() &&
3702 (!BetterPos || DT.dominates(BetterPos, Inst)))
Douglas Gregor7d9663c2010-05-11 06:17:44 +00003703 BetterPos = llvm::next(BasicBlock::iterator(Inst));
Dan Gohmane5f76872010-04-09 22:07:05 +00003704 }
3705 if (!AllDominate)
3706 break;
3707 if (BetterPos)
3708 IP = BetterPos;
3709 else
3710 IP = Tentative;
3711 }
3712
3713 return IP;
3714}
3715
3716/// AdjustInsertPositionForExpand - Determine an input position which will be
Dan Gohmand96eae82010-04-09 02:00:38 +00003717/// dominated by the operands and which will dominate the result.
3718BasicBlock::iterator
Dan Gohmane5f76872010-04-09 22:07:05 +00003719LSRInstance::AdjustInsertPositionForExpand(BasicBlock::iterator IP,
3720 const LSRFixup &LF,
3721 const LSRUse &LU) const {
Dan Gohmand96eae82010-04-09 02:00:38 +00003722 // Collect some instructions which must be dominated by the
Dan Gohman448db1c2010-04-07 22:27:08 +00003723 // expanding replacement. These must be dominated by any operands that
Dan Gohman572645c2010-02-12 10:34:29 +00003724 // will be required in the expansion.
3725 SmallVector<Instruction *, 4> Inputs;
3726 if (Instruction *I = dyn_cast<Instruction>(LF.OperandValToReplace))
3727 Inputs.push_back(I);
3728 if (LU.Kind == LSRUse::ICmpZero)
3729 if (Instruction *I =
3730 dyn_cast<Instruction>(cast<ICmpInst>(LF.UserInst)->getOperand(1)))
3731 Inputs.push_back(I);
Dan Gohman448db1c2010-04-07 22:27:08 +00003732 if (LF.PostIncLoops.count(L)) {
3733 if (LF.isUseFullyOutsideLoop(L))
Dan Gohman069d6f32010-03-02 01:59:21 +00003734 Inputs.push_back(L->getLoopLatch()->getTerminator());
3735 else
3736 Inputs.push_back(IVIncInsertPos);
3737 }
Dan Gohman701a4ae2010-04-08 05:57:57 +00003738 // The expansion must also be dominated by the increment positions of any
3739 // loops it for which it is using post-inc mode.
3740 for (PostIncLoopSet::const_iterator I = LF.PostIncLoops.begin(),
3741 E = LF.PostIncLoops.end(); I != E; ++I) {
3742 const Loop *PIL = *I;
3743 if (PIL == L) continue;
3744
Dan Gohmane5f76872010-04-09 22:07:05 +00003745 // Be dominated by the loop exit.
Dan Gohman701a4ae2010-04-08 05:57:57 +00003746 SmallVector<BasicBlock *, 4> ExitingBlocks;
3747 PIL->getExitingBlocks(ExitingBlocks);
3748 if (!ExitingBlocks.empty()) {
3749 BasicBlock *BB = ExitingBlocks[0];
3750 for (unsigned i = 1, e = ExitingBlocks.size(); i != e; ++i)
3751 BB = DT.findNearestCommonDominator(BB, ExitingBlocks[i]);
3752 Inputs.push_back(BB->getTerminator());
3753 }
3754 }
Dan Gohman572645c2010-02-12 10:34:29 +00003755
3756 // Then, climb up the immediate dominator tree as far as we can go while
3757 // still being dominated by the input positions.
Dan Gohmane5f76872010-04-09 22:07:05 +00003758 IP = HoistInsertPosition(IP, Inputs);
Dan Gohmand96eae82010-04-09 02:00:38 +00003759
3760 // Don't insert instructions before PHI nodes.
Dan Gohman572645c2010-02-12 10:34:29 +00003761 while (isa<PHINode>(IP)) ++IP;
Dan Gohmand96eae82010-04-09 02:00:38 +00003762
Bill Wendlinga4c86ab2011-08-24 21:06:46 +00003763 // Ignore landingpad instructions.
3764 while (isa<LandingPadInst>(IP)) ++IP;
3765
Dan Gohmand96eae82010-04-09 02:00:38 +00003766 // Ignore debug intrinsics.
Dan Gohman449f31c2010-03-26 00:33:27 +00003767 while (isa<DbgInfoIntrinsic>(IP)) ++IP;
Dan Gohman572645c2010-02-12 10:34:29 +00003768
Dan Gohmand96eae82010-04-09 02:00:38 +00003769 return IP;
3770}
3771
Dan Gohman76c315a2010-05-20 20:52:00 +00003772/// Expand - Emit instructions for the leading candidate expression for this
3773/// LSRUse (this is called "expanding").
Dan Gohmand96eae82010-04-09 02:00:38 +00003774Value *LSRInstance::Expand(const LSRFixup &LF,
3775 const Formula &F,
3776 BasicBlock::iterator IP,
3777 SCEVExpander &Rewriter,
3778 SmallVectorImpl<WeakVH> &DeadInsts) const {
3779 const LSRUse &LU = Uses[LF.LUIdx];
3780
3781 // Determine an input position which will be dominated by the operands and
3782 // which will dominate the result.
Dan Gohmane5f76872010-04-09 22:07:05 +00003783 IP = AdjustInsertPositionForExpand(IP, LF, LU);
Dan Gohmand96eae82010-04-09 02:00:38 +00003784
Dan Gohman572645c2010-02-12 10:34:29 +00003785 // Inform the Rewriter if we have a post-increment use, so that it can
3786 // perform an advantageous expansion.
Dan Gohman448db1c2010-04-07 22:27:08 +00003787 Rewriter.setPostInc(LF.PostIncLoops);
Dan Gohman572645c2010-02-12 10:34:29 +00003788
3789 // This is the type that the user actually needs.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003790 Type *OpTy = LF.OperandValToReplace->getType();
Dan Gohman572645c2010-02-12 10:34:29 +00003791 // This will be the type that we'll initially expand to.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003792 Type *Ty = F.getType();
Dan Gohman572645c2010-02-12 10:34:29 +00003793 if (!Ty)
3794 // No type known; just expand directly to the ultimate type.
3795 Ty = OpTy;
3796 else if (SE.getEffectiveSCEVType(Ty) == SE.getEffectiveSCEVType(OpTy))
3797 // Expand directly to the ultimate type if it's the right size.
3798 Ty = OpTy;
3799 // This is the type to do integer arithmetic in.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003800 Type *IntTy = SE.getEffectiveSCEVType(Ty);
Dan Gohman572645c2010-02-12 10:34:29 +00003801
3802 // Build up a list of operands to add together to form the full base.
3803 SmallVector<const SCEV *, 8> Ops;
3804
3805 // Expand the BaseRegs portion.
3806 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
3807 E = F.BaseRegs.end(); I != E; ++I) {
3808 const SCEV *Reg = *I;
3809 assert(!Reg->isZero() && "Zero allocated in a base register!");
3810
Dan Gohman448db1c2010-04-07 22:27:08 +00003811 // If we're expanding for a post-inc user, make the post-inc adjustment.
3812 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
3813 Reg = TransformForPostIncUse(Denormalize, Reg,
3814 LF.UserInst, LF.OperandValToReplace,
3815 Loops, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +00003816
3817 Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, 0, IP)));
3818 }
3819
Dan Gohman087bd1e2010-03-03 05:29:13 +00003820 // Flush the operand list to suppress SCEVExpander hoisting.
3821 if (!Ops.empty()) {
3822 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
3823 Ops.clear();
3824 Ops.push_back(SE.getUnknown(FullV));
3825 }
3826
Dan Gohman572645c2010-02-12 10:34:29 +00003827 // Expand the ScaledReg portion.
3828 Value *ICmpScaledV = 0;
3829 if (F.AM.Scale != 0) {
3830 const SCEV *ScaledS = F.ScaledReg;
3831
Dan Gohman448db1c2010-04-07 22:27:08 +00003832 // If we're expanding for a post-inc user, make the post-inc adjustment.
3833 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
3834 ScaledS = TransformForPostIncUse(Denormalize, ScaledS,
3835 LF.UserInst, LF.OperandValToReplace,
3836 Loops, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +00003837
3838 if (LU.Kind == LSRUse::ICmpZero) {
3839 // An interesting way of "folding" with an icmp is to use a negated
3840 // scale, which we'll implement by inserting it into the other operand
3841 // of the icmp.
3842 assert(F.AM.Scale == -1 &&
3843 "The only scale supported by ICmpZero uses is -1!");
3844 ICmpScaledV = Rewriter.expandCodeFor(ScaledS, 0, IP);
3845 } else {
3846 // Otherwise just expand the scaled register and an explicit scale,
3847 // which is expected to be matched as part of the address.
3848 ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, 0, IP));
3849 ScaledS = SE.getMulExpr(ScaledS,
Dan Gohmandeff6212010-05-03 22:09:21 +00003850 SE.getConstant(ScaledS->getType(), F.AM.Scale));
Dan Gohman572645c2010-02-12 10:34:29 +00003851 Ops.push_back(ScaledS);
Dan Gohman087bd1e2010-03-03 05:29:13 +00003852
3853 // Flush the operand list to suppress SCEVExpander hoisting.
3854 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
3855 Ops.clear();
3856 Ops.push_back(SE.getUnknown(FullV));
Dan Gohman572645c2010-02-12 10:34:29 +00003857 }
3858 }
3859
Dan Gohman087bd1e2010-03-03 05:29:13 +00003860 // Expand the GV portion.
3861 if (F.AM.BaseGV) {
3862 Ops.push_back(SE.getUnknown(F.AM.BaseGV));
3863
3864 // Flush the operand list to suppress SCEVExpander hoisting.
3865 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
3866 Ops.clear();
3867 Ops.push_back(SE.getUnknown(FullV));
3868 }
3869
3870 // Expand the immediate portion.
Dan Gohman572645c2010-02-12 10:34:29 +00003871 int64_t Offset = (uint64_t)F.AM.BaseOffs + LF.Offset;
3872 if (Offset != 0) {
3873 if (LU.Kind == LSRUse::ICmpZero) {
3874 // The other interesting way of "folding" with an ICmpZero is to use a
3875 // negated immediate.
3876 if (!ICmpScaledV)
Eli Friedmandae36ba2011-10-13 23:48:33 +00003877 ICmpScaledV = ConstantInt::get(IntTy, -(uint64_t)Offset);
Dan Gohman572645c2010-02-12 10:34:29 +00003878 else {
3879 Ops.push_back(SE.getUnknown(ICmpScaledV));
3880 ICmpScaledV = ConstantInt::get(IntTy, Offset);
3881 }
3882 } else {
3883 // Just add the immediate values. These again are expected to be matched
3884 // as part of the address.
Dan Gohman087bd1e2010-03-03 05:29:13 +00003885 Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy, Offset)));
Dan Gohman572645c2010-02-12 10:34:29 +00003886 }
3887 }
3888
Dan Gohmancca82142011-05-03 00:46:49 +00003889 // Expand the unfolded offset portion.
3890 int64_t UnfoldedOffset = F.UnfoldedOffset;
3891 if (UnfoldedOffset != 0) {
3892 // Just add the immediate values.
3893 Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy,
3894 UnfoldedOffset)));
3895 }
3896
Dan Gohman572645c2010-02-12 10:34:29 +00003897 // Emit instructions summing all the operands.
3898 const SCEV *FullS = Ops.empty() ?
Dan Gohmandeff6212010-05-03 22:09:21 +00003899 SE.getConstant(IntTy, 0) :
Dan Gohman572645c2010-02-12 10:34:29 +00003900 SE.getAddExpr(Ops);
3901 Value *FullV = Rewriter.expandCodeFor(FullS, Ty, IP);
3902
3903 // We're done expanding now, so reset the rewriter.
Dan Gohman448db1c2010-04-07 22:27:08 +00003904 Rewriter.clearPostInc();
Dan Gohman572645c2010-02-12 10:34:29 +00003905
3906 // An ICmpZero Formula represents an ICmp which we're handling as a
3907 // comparison against zero. Now that we've expanded an expression for that
3908 // form, update the ICmp's other operand.
3909 if (LU.Kind == LSRUse::ICmpZero) {
3910 ICmpInst *CI = cast<ICmpInst>(LF.UserInst);
3911 DeadInsts.push_back(CI->getOperand(1));
3912 assert(!F.AM.BaseGV && "ICmp does not support folding a global value and "
3913 "a scale at the same time!");
3914 if (F.AM.Scale == -1) {
3915 if (ICmpScaledV->getType() != OpTy) {
3916 Instruction *Cast =
3917 CastInst::Create(CastInst::getCastOpcode(ICmpScaledV, false,
3918 OpTy, false),
3919 ICmpScaledV, OpTy, "tmp", CI);
3920 ICmpScaledV = Cast;
3921 }
3922 CI->setOperand(1, ICmpScaledV);
3923 } else {
3924 assert(F.AM.Scale == 0 &&
3925 "ICmp does not support folding a global value and "
3926 "a scale at the same time!");
3927 Constant *C = ConstantInt::getSigned(SE.getEffectiveSCEVType(OpTy),
3928 -(uint64_t)Offset);
3929 if (C->getType() != OpTy)
3930 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3931 OpTy, false),
3932 C, OpTy);
3933
3934 CI->setOperand(1, C);
3935 }
3936 }
3937
3938 return FullV;
3939}
3940
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003941/// RewriteForPHI - Helper for Rewrite. PHI nodes are special because the use
3942/// of their operands effectively happens in their predecessor blocks, so the
3943/// expression may need to be expanded in multiple places.
3944void LSRInstance::RewriteForPHI(PHINode *PN,
3945 const LSRFixup &LF,
3946 const Formula &F,
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003947 SCEVExpander &Rewriter,
3948 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003949 Pass *P) const {
3950 DenseMap<BasicBlock *, Value *> Inserted;
3951 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
3952 if (PN->getIncomingValue(i) == LF.OperandValToReplace) {
3953 BasicBlock *BB = PN->getIncomingBlock(i);
3954
3955 // If this is a critical edge, split the edge so that we do not insert
3956 // the code on all predecessor/successor paths. We do this unless this
3957 // is the canonical backedge for this loop, which complicates post-inc
3958 // users.
3959 if (e != 1 && BB->getTerminator()->getNumSuccessors() > 1 &&
Dan Gohman3ef98382011-02-08 00:55:13 +00003960 !isa<IndirectBrInst>(BB->getTerminator())) {
Bill Wendling89d44112011-08-25 01:08:34 +00003961 BasicBlock *Parent = PN->getParent();
3962 Loop *PNLoop = LI.getLoopFor(Parent);
3963 if (!PNLoop || Parent != PNLoop->getHeader()) {
Dan Gohman3ef98382011-02-08 00:55:13 +00003964 // Split the critical edge.
Bill Wendling8b6af8a2011-08-25 05:55:40 +00003965 BasicBlock *NewBB = 0;
3966 if (!Parent->isLandingPad()) {
Andrew Trickf143b792011-10-04 03:50:44 +00003967 NewBB = SplitCriticalEdge(BB, Parent, P,
3968 /*MergeIdenticalEdges=*/true,
3969 /*DontDeleteUselessPhis=*/true);
Bill Wendling8b6af8a2011-08-25 05:55:40 +00003970 } else {
3971 SmallVector<BasicBlock*, 2> NewBBs;
3972 SplitLandingPadPredecessors(Parent, BB, "", "", P, NewBBs);
3973 NewBB = NewBBs[0];
3974 }
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003975
Dan Gohman3ef98382011-02-08 00:55:13 +00003976 // If PN is outside of the loop and BB is in the loop, we want to
3977 // move the block to be immediately before the PHI block, not
3978 // immediately after BB.
3979 if (L->contains(BB) && !L->contains(PN))
3980 NewBB->moveBefore(PN->getParent());
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003981
Dan Gohman3ef98382011-02-08 00:55:13 +00003982 // Splitting the edge can reduce the number of PHI entries we have.
3983 e = PN->getNumIncomingValues();
3984 BB = NewBB;
3985 i = PN->getBasicBlockIndex(BB);
3986 }
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003987 }
3988
3989 std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> Pair =
3990 Inserted.insert(std::make_pair(BB, static_cast<Value *>(0)));
3991 if (!Pair.second)
3992 PN->setIncomingValue(i, Pair.first->second);
3993 else {
Dan Gohman454d26d2010-02-22 04:11:59 +00003994 Value *FullV = Expand(LF, F, BB->getTerminator(), Rewriter, DeadInsts);
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003995
3996 // If this is reuse-by-noop-cast, insert the noop cast.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003997 Type *OpTy = LF.OperandValToReplace->getType();
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003998 if (FullV->getType() != OpTy)
3999 FullV =
4000 CastInst::Create(CastInst::getCastOpcode(FullV, false,
4001 OpTy, false),
4002 FullV, LF.OperandValToReplace->getType(),
4003 "tmp", BB->getTerminator());
4004
4005 PN->setIncomingValue(i, FullV);
4006 Pair.first->second = FullV;
4007 }
4008 }
4009}
4010
Dan Gohman572645c2010-02-12 10:34:29 +00004011/// Rewrite - Emit instructions for the leading candidate expression for this
4012/// LSRUse (this is called "expanding"), and update the UserInst to reference
4013/// the newly expanded value.
4014void LSRInstance::Rewrite(const LSRFixup &LF,
4015 const Formula &F,
Dan Gohman572645c2010-02-12 10:34:29 +00004016 SCEVExpander &Rewriter,
4017 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman572645c2010-02-12 10:34:29 +00004018 Pass *P) const {
Dan Gohman572645c2010-02-12 10:34:29 +00004019 // First, find an insertion point that dominates UserInst. For PHI nodes,
4020 // find the nearest block which dominates all the relevant uses.
4021 if (PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) {
Dan Gohman454d26d2010-02-22 04:11:59 +00004022 RewriteForPHI(PN, LF, F, Rewriter, DeadInsts, P);
Dan Gohman572645c2010-02-12 10:34:29 +00004023 } else {
Dan Gohman454d26d2010-02-22 04:11:59 +00004024 Value *FullV = Expand(LF, F, LF.UserInst, Rewriter, DeadInsts);
Dan Gohman572645c2010-02-12 10:34:29 +00004025
4026 // If this is reuse-by-noop-cast, insert the noop cast.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00004027 Type *OpTy = LF.OperandValToReplace->getType();
Dan Gohman572645c2010-02-12 10:34:29 +00004028 if (FullV->getType() != OpTy) {
4029 Instruction *Cast =
4030 CastInst::Create(CastInst::getCastOpcode(FullV, false, OpTy, false),
4031 FullV, OpTy, "tmp", LF.UserInst);
4032 FullV = Cast;
4033 }
4034
4035 // Update the user. ICmpZero is handled specially here (for now) because
4036 // Expand may have updated one of the operands of the icmp already, and
4037 // its new value may happen to be equal to LF.OperandValToReplace, in
4038 // which case doing replaceUsesOfWith leads to replacing both operands
4039 // with the same value. TODO: Reorganize this.
4040 if (Uses[LF.LUIdx].Kind == LSRUse::ICmpZero)
4041 LF.UserInst->setOperand(0, FullV);
4042 else
4043 LF.UserInst->replaceUsesOfWith(LF.OperandValToReplace, FullV);
4044 }
4045
4046 DeadInsts.push_back(LF.OperandValToReplace);
4047}
4048
Dan Gohman76c315a2010-05-20 20:52:00 +00004049/// ImplementSolution - Rewrite all the fixup locations with new values,
4050/// following the chosen solution.
Dan Gohman572645c2010-02-12 10:34:29 +00004051void
4052LSRInstance::ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
4053 Pass *P) {
4054 // Keep track of instructions we may have made dead, so that
4055 // we can remove them after we are done working.
4056 SmallVector<WeakVH, 16> DeadInsts;
4057
Andrew Trick5e7645b2011-06-28 05:07:32 +00004058 SCEVExpander Rewriter(SE, "lsr");
Andrew Trick8bf295b2012-01-09 18:58:16 +00004059#ifndef NDEBUG
4060 Rewriter.setDebugType(DEBUG_TYPE);
4061#endif
Dan Gohman572645c2010-02-12 10:34:29 +00004062 Rewriter.disableCanonicalMode();
Andrew Trickc5701912011-10-07 23:46:21 +00004063 Rewriter.enableLSRMode();
Dan Gohman572645c2010-02-12 10:34:29 +00004064 Rewriter.setIVIncInsertPos(L, IVIncInsertPos);
4065
4066 // Expand the new value definitions and update the users.
Dan Gohman402d4352010-05-20 20:33:18 +00004067 for (SmallVectorImpl<LSRFixup>::const_iterator I = Fixups.begin(),
4068 E = Fixups.end(); I != E; ++I) {
4069 const LSRFixup &Fixup = *I;
Dan Gohman572645c2010-02-12 10:34:29 +00004070
Dan Gohman402d4352010-05-20 20:33:18 +00004071 Rewrite(Fixup, *Solution[Fixup.LUIdx], Rewriter, DeadInsts, P);
Dan Gohman572645c2010-02-12 10:34:29 +00004072
4073 Changed = true;
4074 }
4075
4076 // Clean up after ourselves. This must be done before deleting any
4077 // instructions.
4078 Rewriter.clear();
4079
4080 Changed |= DeleteTriviallyDeadInstructions(DeadInsts);
4081}
4082
4083LSRInstance::LSRInstance(const TargetLowering *tli, Loop *l, Pass *P)
4084 : IU(P->getAnalysis<IVUsers>()),
4085 SE(P->getAnalysis<ScalarEvolution>()),
4086 DT(P->getAnalysis<DominatorTree>()),
Dan Gohmane5f76872010-04-09 22:07:05 +00004087 LI(P->getAnalysis<LoopInfo>()),
Dan Gohman572645c2010-02-12 10:34:29 +00004088 TLI(tli), L(l), Changed(false), IVIncInsertPos(0) {
Devang Patel0f54dcb2007-03-06 21:14:09 +00004089
Dan Gohman03e896b2009-11-05 21:11:53 +00004090 // If LoopSimplify form is not available, stay out of trouble.
Andrew Trickacdb4aa2012-01-07 03:16:50 +00004091 if (!L->isLoopSimplifyForm())
4092 return;
Dan Gohman03e896b2009-11-05 21:11:53 +00004093
Andrew Trickacdb4aa2012-01-07 03:16:50 +00004094 // All outer loops must have preheaders, or SCEVExpander may not be able to
4095 // materialize an AddRecExpr whose Start is an outer AddRecExpr.
4096 for (const Loop *OuterLoop = L; (OuterLoop = OuterLoop->getParentLoop());) {
4097 if (!OuterLoop->getLoopPreheader())
4098 return;
4099 }
Dan Gohman572645c2010-02-12 10:34:29 +00004100 // If there's no interesting work to be done, bail early.
4101 if (IU.empty()) return;
Dan Gohman80b0f8c2009-03-09 20:34:59 +00004102
Dan Gohman572645c2010-02-12 10:34:29 +00004103 DEBUG(dbgs() << "\nLSR on loop ";
4104 WriteAsOperand(dbgs(), L->getHeader(), /*PrintType=*/false);
4105 dbgs() << ":\n");
Dan Gohmanf7912df2009-03-09 20:46:50 +00004106
Dan Gohman402d4352010-05-20 20:33:18 +00004107 // First, perform some low-level loop optimizations.
Dan Gohman572645c2010-02-12 10:34:29 +00004108 OptimizeShadowIV();
Dan Gohmanc6519f92010-05-20 20:05:31 +00004109 OptimizeLoopTermCond();
Evan Cheng5792f512009-05-11 22:33:01 +00004110
Andrew Trick37eb38d2011-07-21 00:40:04 +00004111 // If loop preparation eliminates all interesting IV users, bail.
4112 if (IU.empty()) return;
4113
Andrew Trick5219f862011-09-29 01:53:08 +00004114 // Skip nested loops until we can model them better with formulae.
Andrew Trick0c01bc32011-09-29 01:33:38 +00004115 if (!EnableNested && !L->empty()) {
4116 DEBUG(dbgs() << "LSR skipping outer loop " << *L << "\n");
Andrew Trick5219f862011-09-29 01:53:08 +00004117 return;
Andrew Trick0c01bc32011-09-29 01:33:38 +00004118 }
4119
Dan Gohman402d4352010-05-20 20:33:18 +00004120 // Start collecting data and preparing for the solver.
Andrew Trick6c7d0ae2012-01-09 19:50:34 +00004121 CollectChains();
Dan Gohman572645c2010-02-12 10:34:29 +00004122 CollectInterestingTypesAndFactors();
4123 CollectFixupsAndInitialFormulae();
4124 CollectLoopInvariantFixupsAndFormulae();
Chris Lattner010de252005-08-08 05:28:22 +00004125
Dan Gohman572645c2010-02-12 10:34:29 +00004126 DEBUG(dbgs() << "LSR found " << Uses.size() << " uses:\n";
4127 print_uses(dbgs()));
Misha Brukmanfd939082005-04-21 23:48:37 +00004128
Dan Gohman572645c2010-02-12 10:34:29 +00004129 // Now use the reuse data to generate a bunch of interesting ways
4130 // to formulate the values needed for the uses.
4131 GenerateAllReuseFormulae();
Evan Chengd1d6b5c2006-03-16 21:53:05 +00004132
Dan Gohman572645c2010-02-12 10:34:29 +00004133 FilterOutUndesirableDedicatedRegisters();
4134 NarrowSearchSpaceUsingHeuristics();
Dan Gohman6bec5bb2009-12-18 00:06:20 +00004135
Dan Gohman572645c2010-02-12 10:34:29 +00004136 SmallVector<const Formula *, 8> Solution;
4137 Solve(Solution);
Dan Gohman6bec5bb2009-12-18 00:06:20 +00004138
Dan Gohman572645c2010-02-12 10:34:29 +00004139 // Release memory that is no longer needed.
4140 Factors.clear();
4141 Types.clear();
4142 RegUses.clear();
4143
Andrew Trick80ef1b22011-09-27 00:44:14 +00004144 if (Solution.empty())
4145 return;
4146
Dan Gohman572645c2010-02-12 10:34:29 +00004147#ifndef NDEBUG
4148 // Formulae should be legal.
4149 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
4150 E = Uses.end(); I != E; ++I) {
4151 const LSRUse &LU = *I;
4152 for (SmallVectorImpl<Formula>::const_iterator J = LU.Formulae.begin(),
4153 JE = LU.Formulae.end(); J != JE; ++J)
4154 assert(isLegalUse(J->AM, LU.MinOffset, LU.MaxOffset,
4155 LU.Kind, LU.AccessTy, TLI) &&
4156 "Illegal formula generated!");
4157 };
4158#endif
4159
4160 // Now that we've decided what we want, make it so.
4161 ImplementSolution(Solution, P);
4162}
4163
4164void LSRInstance::print_factors_and_types(raw_ostream &OS) const {
4165 if (Factors.empty() && Types.empty()) return;
4166
4167 OS << "LSR has identified the following interesting factors and types: ";
4168 bool First = true;
4169
4170 for (SmallSetVector<int64_t, 8>::const_iterator
4171 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
4172 if (!First) OS << ", ";
4173 First = false;
4174 OS << '*' << *I;
Evan Cheng81ebdcf2009-11-10 21:14:05 +00004175 }
Dale Johannesenc1acc3f2009-05-11 17:15:42 +00004176
Chris Lattnerdb125cf2011-07-18 04:54:35 +00004177 for (SmallSetVector<Type *, 4>::const_iterator
Dan Gohman572645c2010-02-12 10:34:29 +00004178 I = Types.begin(), E = Types.end(); I != E; ++I) {
4179 if (!First) OS << ", ";
4180 First = false;
4181 OS << '(' << **I << ')';
4182 }
4183 OS << '\n';
4184}
4185
4186void LSRInstance::print_fixups(raw_ostream &OS) const {
4187 OS << "LSR is examining the following fixup sites:\n";
4188 for (SmallVectorImpl<LSRFixup>::const_iterator I = Fixups.begin(),
4189 E = Fixups.end(); I != E; ++I) {
Dan Gohman572645c2010-02-12 10:34:29 +00004190 dbgs() << " ";
Dan Gohman9f383eb2010-05-20 22:25:20 +00004191 I->print(OS);
Dan Gohman572645c2010-02-12 10:34:29 +00004192 OS << '\n';
4193 }
4194}
4195
4196void LSRInstance::print_uses(raw_ostream &OS) const {
4197 OS << "LSR is examining the following uses:\n";
4198 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
4199 E = Uses.end(); I != E; ++I) {
4200 const LSRUse &LU = *I;
4201 dbgs() << " ";
4202 LU.print(OS);
4203 OS << '\n';
4204 for (SmallVectorImpl<Formula>::const_iterator J = LU.Formulae.begin(),
4205 JE = LU.Formulae.end(); J != JE; ++J) {
4206 OS << " ";
4207 J->print(OS);
4208 OS << '\n';
4209 }
4210 }
4211}
4212
4213void LSRInstance::print(raw_ostream &OS) const {
4214 print_factors_and_types(OS);
4215 print_fixups(OS);
4216 print_uses(OS);
4217}
4218
4219void LSRInstance::dump() const {
4220 print(errs()); errs() << '\n';
4221}
4222
4223namespace {
4224
4225class LoopStrengthReduce : public LoopPass {
4226 /// TLI - Keep a pointer of a TargetLowering to consult for determining
4227 /// transformation profitability.
4228 const TargetLowering *const TLI;
4229
4230public:
4231 static char ID; // Pass ID, replacement for typeid
4232 explicit LoopStrengthReduce(const TargetLowering *tli = 0);
4233
4234private:
4235 bool runOnLoop(Loop *L, LPPassManager &LPM);
4236 void getAnalysisUsage(AnalysisUsage &AU) const;
4237};
4238
4239}
4240
4241char LoopStrengthReduce::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +00004242INITIALIZE_PASS_BEGIN(LoopStrengthReduce, "loop-reduce",
Owen Andersonce665bd2010-10-07 22:25:06 +00004243 "Loop Strength Reduction", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +00004244INITIALIZE_PASS_DEPENDENCY(DominatorTree)
4245INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
4246INITIALIZE_PASS_DEPENDENCY(IVUsers)
Owen Anderson205942a2010-10-19 20:08:44 +00004247INITIALIZE_PASS_DEPENDENCY(LoopInfo)
4248INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Owen Anderson2ab36d32010-10-12 19:48:12 +00004249INITIALIZE_PASS_END(LoopStrengthReduce, "loop-reduce",
4250 "Loop Strength Reduction", false, false)
4251
Dan Gohman572645c2010-02-12 10:34:29 +00004252
4253Pass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
4254 return new LoopStrengthReduce(TLI);
4255}
4256
4257LoopStrengthReduce::LoopStrengthReduce(const TargetLowering *tli)
Owen Anderson081c34b2010-10-19 17:21:58 +00004258 : LoopPass(ID), TLI(tli) {
4259 initializeLoopStrengthReducePass(*PassRegistry::getPassRegistry());
4260 }
Dan Gohman572645c2010-02-12 10:34:29 +00004261
4262void LoopStrengthReduce::getAnalysisUsage(AnalysisUsage &AU) const {
4263 // We split critical edges, so we change the CFG. However, we do update
4264 // many analyses if they are around.
Eric Christopher6793c492011-02-10 01:48:24 +00004265 AU.addPreservedID(LoopSimplifyID);
Dan Gohman572645c2010-02-12 10:34:29 +00004266
Eric Christopher6793c492011-02-10 01:48:24 +00004267 AU.addRequired<LoopInfo>();
4268 AU.addPreserved<LoopInfo>();
4269 AU.addRequiredID(LoopSimplifyID);
Dan Gohman572645c2010-02-12 10:34:29 +00004270 AU.addRequired<DominatorTree>();
4271 AU.addPreserved<DominatorTree>();
4272 AU.addRequired<ScalarEvolution>();
4273 AU.addPreserved<ScalarEvolution>();
Cameron Zwarich2c2b9332011-02-10 23:53:14 +00004274 // Requiring LoopSimplify a second time here prevents IVUsers from running
4275 // twice, since LoopSimplify was invalidated by running ScalarEvolution.
4276 AU.addRequiredID(LoopSimplifyID);
Dan Gohman572645c2010-02-12 10:34:29 +00004277 AU.addRequired<IVUsers>();
4278 AU.addPreserved<IVUsers>();
4279}
4280
4281bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager & /*LPM*/) {
4282 bool Changed = false;
4283
4284 // Run the main LSR transformation.
4285 Changed |= LSRInstance(TLI, L, this).getChanged();
4286
Andrew Trickf231a6d2012-01-07 01:36:44 +00004287 // Remove any extra phis created by processing inner loops.
Dan Gohman9fff2182010-01-05 16:31:45 +00004288 Changed |= DeleteDeadPHIs(L->getHeader());
Andrew Trickf231a6d2012-01-07 01:36:44 +00004289 if (EnablePhiElim) {
4290 SmallVector<WeakVH, 16> DeadInsts;
4291 SCEVExpander Rewriter(getAnalysis<ScalarEvolution>(), "lsr");
4292#ifndef NDEBUG
4293 Rewriter.setDebugType(DEBUG_TYPE);
4294#endif
4295 unsigned numFolded = Rewriter.
4296 replaceCongruentIVs(L, &getAnalysis<DominatorTree>(), DeadInsts, TLI);
4297 if (numFolded) {
4298 Changed = true;
4299 DeleteTriviallyDeadInstructions(DeadInsts);
4300 DeleteDeadPHIs(L->getHeader());
4301 }
4302 }
Evan Cheng1ce75dc2008-07-07 19:51:32 +00004303 return Changed;
Nate Begemaneaa13852004-10-18 21:08:22 +00004304}