blob: 6c72c3cb9fba44de49169083f6d4756297ec4a6f [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 Lattnere0391be2005-08-12 22:06:11 +000066#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Nate Begemaneaa13852004-10-18 21:08:22 +000067#include "llvm/Transforms/Utils/Local.h"
Dan Gohman572645c2010-02-12 10:34:29 +000068#include "llvm/ADT/SmallBitVector.h"
69#include "llvm/ADT/SetVector.h"
70#include "llvm/ADT/DenseSet.h"
Nate Begeman16997482005-07-30 00:15:07 +000071#include "llvm/Support/Debug.h"
Dan Gohmanafc36a92009-05-02 18:29:22 +000072#include "llvm/Support/ValueHandle.h"
Daniel Dunbar460f6562009-07-26 09:48:23 +000073#include "llvm/Support/raw_ostream.h"
Evan Chengd277f2c2006-03-13 23:14:23 +000074#include "llvm/Target/TargetLowering.h"
Jeff Cohencfb1d422005-07-30 18:22:27 +000075#include <algorithm>
Nate Begemaneaa13852004-10-18 21:08:22 +000076using namespace llvm;
77
Dan Gohman572645c2010-02-12 10:34:29 +000078namespace {
Nate Begemaneaa13852004-10-18 21:08:22 +000079
Dan Gohman572645c2010-02-12 10:34:29 +000080/// RegSortData - This class holds data which is used to order reuse candidates.
81class RegSortData {
82public:
83 /// UsedByIndices - This represents the set of LSRUse indices which reference
84 /// a particular register.
85 SmallBitVector UsedByIndices;
86
87 RegSortData() {}
88
89 void print(raw_ostream &OS) const;
90 void dump() const;
91};
92
93}
94
95void RegSortData::print(raw_ostream &OS) const {
96 OS << "[NumUses=" << UsedByIndices.count() << ']';
97}
98
99void RegSortData::dump() const {
100 print(errs()); errs() << '\n';
101}
Dan Gohmanc17e0cf2009-02-20 04:17:46 +0000102
Chris Lattner0e5f4992006-12-19 21:40:18 +0000103namespace {
Dale Johannesendc42f482007-03-20 00:47:50 +0000104
Dan Gohman572645c2010-02-12 10:34:29 +0000105/// RegUseTracker - Map register candidates to information about how they are
106/// used.
107class RegUseTracker {
108 typedef DenseMap<const SCEV *, RegSortData> RegUsesTy;
Dale Johannesendc42f482007-03-20 00:47:50 +0000109
Dan Gohman90bb3552010-05-18 22:33:00 +0000110 RegUsesTy RegUsesMap;
Dan Gohman572645c2010-02-12 10:34:29 +0000111 SmallVector<const SCEV *, 16> RegSequence;
Evan Chengd1d6b5c2006-03-16 21:53:05 +0000112
Dan Gohman572645c2010-02-12 10:34:29 +0000113public:
114 void CountRegister(const SCEV *Reg, size_t LUIdx);
Dan Gohmanb2df4332010-05-18 23:42:37 +0000115 void DropRegister(const SCEV *Reg, size_t LUIdx);
Dan Gohmanc6897702010-10-07 23:33:43 +0000116 void SwapAndDropUse(size_t LUIdx, size_t LastLUIdx);
Dan Gohmana10756e2010-01-21 02:09:26 +0000117
Dan Gohman572645c2010-02-12 10:34:29 +0000118 bool isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const;
Dan Gohmana10756e2010-01-21 02:09:26 +0000119
Dan Gohman572645c2010-02-12 10:34:29 +0000120 const SmallBitVector &getUsedByIndices(const SCEV *Reg) const;
Dan Gohmana10756e2010-01-21 02:09:26 +0000121
Dan Gohman572645c2010-02-12 10:34:29 +0000122 void clear();
Dan Gohmana10756e2010-01-21 02:09:26 +0000123
Dan Gohman572645c2010-02-12 10:34:29 +0000124 typedef SmallVectorImpl<const SCEV *>::iterator iterator;
125 typedef SmallVectorImpl<const SCEV *>::const_iterator const_iterator;
126 iterator begin() { return RegSequence.begin(); }
127 iterator end() { return RegSequence.end(); }
128 const_iterator begin() const { return RegSequence.begin(); }
129 const_iterator end() const { return RegSequence.end(); }
130};
Dan Gohmana10756e2010-01-21 02:09:26 +0000131
Dan Gohmana10756e2010-01-21 02:09:26 +0000132}
133
Dan Gohman572645c2010-02-12 10:34:29 +0000134void
135RegUseTracker::CountRegister(const SCEV *Reg, size_t LUIdx) {
136 std::pair<RegUsesTy::iterator, bool> Pair =
Dan Gohman90bb3552010-05-18 22:33:00 +0000137 RegUsesMap.insert(std::make_pair(Reg, RegSortData()));
Dan Gohman572645c2010-02-12 10:34:29 +0000138 RegSortData &RSD = Pair.first->second;
139 if (Pair.second)
140 RegSequence.push_back(Reg);
141 RSD.UsedByIndices.resize(std::max(RSD.UsedByIndices.size(), LUIdx + 1));
142 RSD.UsedByIndices.set(LUIdx);
Dan Gohmana10756e2010-01-21 02:09:26 +0000143}
144
Dan Gohmanb2df4332010-05-18 23:42:37 +0000145void
146RegUseTracker::DropRegister(const SCEV *Reg, size_t LUIdx) {
147 RegUsesTy::iterator It = RegUsesMap.find(Reg);
148 assert(It != RegUsesMap.end());
149 RegSortData &RSD = It->second;
150 assert(RSD.UsedByIndices.size() > LUIdx);
151 RSD.UsedByIndices.reset(LUIdx);
152}
153
Dan Gohmana2086b32010-05-19 23:43:12 +0000154void
Dan Gohmanc6897702010-10-07 23:33:43 +0000155RegUseTracker::SwapAndDropUse(size_t LUIdx, size_t LastLUIdx) {
156 assert(LUIdx <= LastLUIdx);
157
158 // Update RegUses. The data structure is not optimized for this purpose;
159 // we must iterate through it and update each of the bit vectors.
Dan Gohmana2086b32010-05-19 23:43:12 +0000160 for (RegUsesTy::iterator I = RegUsesMap.begin(), E = RegUsesMap.end();
Dan Gohmanc6897702010-10-07 23:33:43 +0000161 I != E; ++I) {
162 SmallBitVector &UsedByIndices = I->second.UsedByIndices;
163 if (LUIdx < UsedByIndices.size())
164 UsedByIndices[LUIdx] =
165 LastLUIdx < UsedByIndices.size() ? UsedByIndices[LastLUIdx] : 0;
166 UsedByIndices.resize(std::min(UsedByIndices.size(), LastLUIdx));
167 }
Dan Gohmana2086b32010-05-19 23:43:12 +0000168}
169
Dan Gohman572645c2010-02-12 10:34:29 +0000170bool
171RegUseTracker::isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const {
Dan Gohman46fd7a62010-08-29 15:18:49 +0000172 RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
173 if (I == RegUsesMap.end())
174 return false;
175 const SmallBitVector &UsedByIndices = I->second.UsedByIndices;
Dan Gohman572645c2010-02-12 10:34:29 +0000176 int i = UsedByIndices.find_first();
177 if (i == -1) return false;
178 if ((size_t)i != LUIdx) return true;
179 return UsedByIndices.find_next(i) != -1;
180}
Dan Gohmana10756e2010-01-21 02:09:26 +0000181
Dan Gohman572645c2010-02-12 10:34:29 +0000182const SmallBitVector &RegUseTracker::getUsedByIndices(const SCEV *Reg) const {
Dan Gohman90bb3552010-05-18 22:33:00 +0000183 RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
184 assert(I != RegUsesMap.end() && "Unknown register!");
Dan Gohman572645c2010-02-12 10:34:29 +0000185 return I->second.UsedByIndices;
186}
Dan Gohmana10756e2010-01-21 02:09:26 +0000187
Dan Gohman572645c2010-02-12 10:34:29 +0000188void RegUseTracker::clear() {
Dan Gohman90bb3552010-05-18 22:33:00 +0000189 RegUsesMap.clear();
Dan Gohman572645c2010-02-12 10:34:29 +0000190 RegSequence.clear();
191}
Dan Gohmana10756e2010-01-21 02:09:26 +0000192
Dan Gohman572645c2010-02-12 10:34:29 +0000193namespace {
194
195/// Formula - This class holds information that describes a formula for
196/// computing satisfying a use. It may include broken-out immediates and scaled
197/// registers.
198struct Formula {
199 /// AM - This is used to represent complex addressing, as well as other kinds
200 /// of interesting uses.
201 TargetLowering::AddrMode AM;
202
203 /// BaseRegs - The list of "base" registers for this use. When this is
204 /// non-empty, AM.HasBaseReg should be set to true.
205 SmallVector<const SCEV *, 2> BaseRegs;
206
207 /// ScaledReg - The 'scaled' register for this use. This should be non-null
208 /// when AM.Scale is not zero.
209 const SCEV *ScaledReg;
210
211 Formula() : ScaledReg(0) {}
212
Dan Gohmandc0e8fb2010-11-17 21:41:58 +0000213 void InitialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE);
Dan Gohman572645c2010-02-12 10:34:29 +0000214
215 unsigned getNumRegs() const;
216 const Type *getType() const;
217
Dan Gohman5ce6d052010-05-20 15:17:54 +0000218 void DeleteBaseReg(const SCEV *&S);
219
Dan Gohman572645c2010-02-12 10:34:29 +0000220 bool referencesReg(const SCEV *S) const;
221 bool hasRegsUsedByUsesOtherThan(size_t LUIdx,
222 const RegUseTracker &RegUses) const;
223
224 void print(raw_ostream &OS) const;
225 void dump() const;
226};
227
228}
229
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000230/// DoInitialMatch - Recursion helper for InitialMatch.
Dan Gohman572645c2010-02-12 10:34:29 +0000231static void DoInitialMatch(const SCEV *S, Loop *L,
232 SmallVectorImpl<const SCEV *> &Good,
233 SmallVectorImpl<const SCEV *> &Bad,
Dan Gohmandc0e8fb2010-11-17 21:41:58 +0000234 ScalarEvolution &SE) {
Dan Gohman572645c2010-02-12 10:34:29 +0000235 // Collect expressions which properly dominate the loop header.
Dan Gohmandc0e8fb2010-11-17 21:41:58 +0000236 if (SE.properlyDominates(S, L->getHeader())) {
Dan Gohman572645c2010-02-12 10:34:29 +0000237 Good.push_back(S);
238 return;
Dan Gohmana10756e2010-01-21 02:09:26 +0000239 }
Dan Gohman572645c2010-02-12 10:34:29 +0000240
241 // Look at add operands.
242 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
243 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
244 I != E; ++I)
Dan Gohmandc0e8fb2010-11-17 21:41:58 +0000245 DoInitialMatch(*I, L, Good, Bad, SE);
Dan Gohman572645c2010-02-12 10:34:29 +0000246 return;
247 }
248
249 // Look at addrec operands.
250 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
251 if (!AR->getStart()->isZero()) {
Dan Gohmandc0e8fb2010-11-17 21:41:58 +0000252 DoInitialMatch(AR->getStart(), L, Good, Bad, SE);
Dan Gohmandeff6212010-05-03 22:09:21 +0000253 DoInitialMatch(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0),
Dan Gohman572645c2010-02-12 10:34:29 +0000254 AR->getStepRecurrence(SE),
255 AR->getLoop()),
Dan Gohmandc0e8fb2010-11-17 21:41:58 +0000256 L, Good, Bad, SE);
Dan Gohman572645c2010-02-12 10:34:29 +0000257 return;
258 }
259
260 // Handle a multiplication by -1 (negation) if it didn't fold.
261 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S))
262 if (Mul->getOperand(0)->isAllOnesValue()) {
263 SmallVector<const SCEV *, 4> Ops(Mul->op_begin()+1, Mul->op_end());
264 const SCEV *NewMul = SE.getMulExpr(Ops);
265
266 SmallVector<const SCEV *, 4> MyGood;
267 SmallVector<const SCEV *, 4> MyBad;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +0000268 DoInitialMatch(NewMul, L, MyGood, MyBad, SE);
Dan Gohman572645c2010-02-12 10:34:29 +0000269 const SCEV *NegOne = SE.getSCEV(ConstantInt::getAllOnesValue(
270 SE.getEffectiveSCEVType(NewMul->getType())));
271 for (SmallVectorImpl<const SCEV *>::const_iterator I = MyGood.begin(),
272 E = MyGood.end(); I != E; ++I)
273 Good.push_back(SE.getMulExpr(NegOne, *I));
274 for (SmallVectorImpl<const SCEV *>::const_iterator I = MyBad.begin(),
275 E = MyBad.end(); I != E; ++I)
276 Bad.push_back(SE.getMulExpr(NegOne, *I));
277 return;
278 }
279
280 // Ok, we can't do anything interesting. Just stuff the whole thing into a
281 // register and hope for the best.
282 Bad.push_back(S);
283}
284
285/// InitialMatch - Incorporate loop-variant parts of S into this Formula,
286/// attempting to keep all loop-invariant and loop-computable values in a
287/// single base register.
Dan Gohmandc0e8fb2010-11-17 21:41:58 +0000288void Formula::InitialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE) {
Dan Gohman572645c2010-02-12 10:34:29 +0000289 SmallVector<const SCEV *, 4> Good;
290 SmallVector<const SCEV *, 4> Bad;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +0000291 DoInitialMatch(S, L, Good, Bad, SE);
Dan Gohman572645c2010-02-12 10:34:29 +0000292 if (!Good.empty()) {
Dan Gohmane60bb152010-04-08 23:36:27 +0000293 const SCEV *Sum = SE.getAddExpr(Good);
294 if (!Sum->isZero())
295 BaseRegs.push_back(Sum);
Dan Gohman572645c2010-02-12 10:34:29 +0000296 AM.HasBaseReg = true;
297 }
298 if (!Bad.empty()) {
Dan Gohmane60bb152010-04-08 23:36:27 +0000299 const SCEV *Sum = SE.getAddExpr(Bad);
300 if (!Sum->isZero())
301 BaseRegs.push_back(Sum);
Dan Gohman572645c2010-02-12 10:34:29 +0000302 AM.HasBaseReg = true;
303 }
304}
305
306/// getNumRegs - Return the total number of register operands used by this
307/// formula. This does not include register uses implied by non-constant
308/// addrec strides.
309unsigned Formula::getNumRegs() const {
310 return !!ScaledReg + BaseRegs.size();
311}
312
313/// getType - Return the type of this formula, if it has one, or null
314/// otherwise. This type is meaningless except for the bit size.
315const Type *Formula::getType() const {
316 return !BaseRegs.empty() ? BaseRegs.front()->getType() :
317 ScaledReg ? ScaledReg->getType() :
318 AM.BaseGV ? AM.BaseGV->getType() :
319 0;
320}
321
Dan Gohman5ce6d052010-05-20 15:17:54 +0000322/// DeleteBaseReg - Delete the given base reg from the BaseRegs list.
323void Formula::DeleteBaseReg(const SCEV *&S) {
324 if (&S != &BaseRegs.back())
325 std::swap(S, BaseRegs.back());
326 BaseRegs.pop_back();
327}
328
Dan Gohman572645c2010-02-12 10:34:29 +0000329/// referencesReg - Test if this formula references the given register.
330bool Formula::referencesReg(const SCEV *S) const {
331 return S == ScaledReg ||
332 std::find(BaseRegs.begin(), BaseRegs.end(), S) != BaseRegs.end();
333}
334
335/// hasRegsUsedByUsesOtherThan - Test whether this formula uses registers
336/// which are used by uses other than the use with the given index.
337bool Formula::hasRegsUsedByUsesOtherThan(size_t LUIdx,
338 const RegUseTracker &RegUses) const {
339 if (ScaledReg)
340 if (RegUses.isRegUsedByUsesOtherThan(ScaledReg, LUIdx))
341 return true;
342 for (SmallVectorImpl<const SCEV *>::const_iterator I = BaseRegs.begin(),
343 E = BaseRegs.end(); I != E; ++I)
344 if (RegUses.isRegUsedByUsesOtherThan(*I, LUIdx))
345 return true;
346 return false;
347}
348
349void Formula::print(raw_ostream &OS) const {
350 bool First = true;
351 if (AM.BaseGV) {
352 if (!First) OS << " + "; else First = false;
353 WriteAsOperand(OS, AM.BaseGV, /*PrintType=*/false);
354 }
355 if (AM.BaseOffs != 0) {
356 if (!First) OS << " + "; else First = false;
357 OS << AM.BaseOffs;
358 }
359 for (SmallVectorImpl<const SCEV *>::const_iterator I = BaseRegs.begin(),
360 E = BaseRegs.end(); I != E; ++I) {
361 if (!First) OS << " + "; else First = false;
362 OS << "reg(" << **I << ')';
363 }
Dan Gohmanc4cfbaf2010-05-18 22:35:55 +0000364 if (AM.HasBaseReg && BaseRegs.empty()) {
365 if (!First) OS << " + "; else First = false;
366 OS << "**error: HasBaseReg**";
367 } else if (!AM.HasBaseReg && !BaseRegs.empty()) {
368 if (!First) OS << " + "; else First = false;
369 OS << "**error: !HasBaseReg**";
370 }
Dan Gohman572645c2010-02-12 10:34:29 +0000371 if (AM.Scale != 0) {
372 if (!First) OS << " + "; else First = false;
373 OS << AM.Scale << "*reg(";
374 if (ScaledReg)
375 OS << *ScaledReg;
376 else
377 OS << "<unknown>";
378 OS << ')';
379 }
380}
381
382void Formula::dump() const {
383 print(errs()); errs() << '\n';
384}
385
Dan Gohmanaae01f12010-02-19 19:32:49 +0000386/// isAddRecSExtable - Return true if the given addrec can be sign-extended
387/// without changing its value.
388static bool isAddRecSExtable(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
389 const Type *WideTy =
Dan Gohmanea507f52010-05-20 19:44:23 +0000390 IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(AR->getType()) + 1);
Dan Gohmanaae01f12010-02-19 19:32:49 +0000391 return isa<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
392}
393
394/// isAddSExtable - Return true if the given add can be sign-extended
395/// without changing its value.
396static bool isAddSExtable(const SCEVAddExpr *A, ScalarEvolution &SE) {
397 const Type *WideTy =
Dan Gohmanea507f52010-05-20 19:44:23 +0000398 IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(A->getType()) + 1);
Dan Gohmanaae01f12010-02-19 19:32:49 +0000399 return isa<SCEVAddExpr>(SE.getSignExtendExpr(A, WideTy));
400}
401
Dan Gohman473e6352010-06-24 16:45:11 +0000402/// isMulSExtable - Return true if the given mul can be sign-extended
Dan Gohmanaae01f12010-02-19 19:32:49 +0000403/// without changing its value.
Dan Gohman473e6352010-06-24 16:45:11 +0000404static bool isMulSExtable(const SCEVMulExpr *M, ScalarEvolution &SE) {
Dan Gohmanaae01f12010-02-19 19:32:49 +0000405 const Type *WideTy =
Dan Gohman473e6352010-06-24 16:45:11 +0000406 IntegerType::get(SE.getContext(),
407 SE.getTypeSizeInBits(M->getType()) * M->getNumOperands());
408 return isa<SCEVMulExpr>(SE.getSignExtendExpr(M, WideTy));
Dan Gohmanaae01f12010-02-19 19:32:49 +0000409}
410
Dan Gohmanf09b7122010-02-19 19:35:48 +0000411/// getExactSDiv - Return an expression for LHS /s RHS, if it can be determined
412/// and if the remainder is known to be zero, or null otherwise. If
413/// IgnoreSignificantBits is true, expressions like (X * Y) /s Y are simplified
414/// to Y, ignoring that the multiplication may overflow, which is useful when
415/// the result will be used in a context where the most significant bits are
416/// ignored.
417static const SCEV *getExactSDiv(const SCEV *LHS, const SCEV *RHS,
418 ScalarEvolution &SE,
419 bool IgnoreSignificantBits = false) {
Dan Gohman572645c2010-02-12 10:34:29 +0000420 // Handle the trivial case, which works for any SCEV type.
421 if (LHS == RHS)
Dan Gohmandeff6212010-05-03 22:09:21 +0000422 return SE.getConstant(LHS->getType(), 1);
Dan Gohman572645c2010-02-12 10:34:29 +0000423
Dan Gohmand42819a2010-06-24 16:51:25 +0000424 // Handle a few RHS special cases.
425 const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS);
426 if (RC) {
427 const APInt &RA = RC->getValue()->getValue();
428 // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do
429 // some folding.
430 if (RA.isAllOnesValue())
431 return SE.getMulExpr(LHS, RC);
432 // Handle x /s 1 as x.
433 if (RA == 1)
434 return LHS;
435 }
Dan Gohman572645c2010-02-12 10:34:29 +0000436
437 // Check for a division of a constant by a constant.
438 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(LHS)) {
Dan Gohman572645c2010-02-12 10:34:29 +0000439 if (!RC)
440 return 0;
Dan Gohmand42819a2010-06-24 16:51:25 +0000441 const APInt &LA = C->getValue()->getValue();
442 const APInt &RA = RC->getValue()->getValue();
443 if (LA.srem(RA) != 0)
Dan Gohman572645c2010-02-12 10:34:29 +0000444 return 0;
Dan Gohmand42819a2010-06-24 16:51:25 +0000445 return SE.getConstant(LA.sdiv(RA));
Dan Gohman572645c2010-02-12 10:34:29 +0000446 }
447
Dan Gohmanaae01f12010-02-19 19:32:49 +0000448 // Distribute the sdiv over addrec operands, if the addrec doesn't overflow.
Dan Gohman572645c2010-02-12 10:34:29 +0000449 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohmanaae01f12010-02-19 19:32:49 +0000450 if (IgnoreSignificantBits || isAddRecSExtable(AR, SE)) {
Dan Gohmanf09b7122010-02-19 19:35:48 +0000451 const SCEV *Step = getExactSDiv(AR->getStepRecurrence(SE), RHS, SE,
452 IgnoreSignificantBits);
Dan Gohmanaae01f12010-02-19 19:32:49 +0000453 if (!Step) return 0;
Dan Gohman694a15e2010-08-19 01:02:31 +0000454 const SCEV *Start = getExactSDiv(AR->getStart(), RHS, SE,
455 IgnoreSignificantBits);
456 if (!Start) return 0;
Dan Gohmanaae01f12010-02-19 19:32:49 +0000457 return SE.getAddRecExpr(Start, Step, AR->getLoop());
458 }
Dan Gohman2ea09e02010-06-24 16:57:52 +0000459 return 0;
Dan Gohman572645c2010-02-12 10:34:29 +0000460 }
461
Dan Gohmanaae01f12010-02-19 19:32:49 +0000462 // Distribute the sdiv over add operands, if the add doesn't overflow.
Dan Gohman572645c2010-02-12 10:34:29 +0000463 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(LHS)) {
Dan Gohmanaae01f12010-02-19 19:32:49 +0000464 if (IgnoreSignificantBits || isAddSExtable(Add, SE)) {
465 SmallVector<const SCEV *, 8> Ops;
466 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
467 I != E; ++I) {
Dan Gohmanf09b7122010-02-19 19:35:48 +0000468 const SCEV *Op = getExactSDiv(*I, RHS, SE,
469 IgnoreSignificantBits);
Dan Gohmanaae01f12010-02-19 19:32:49 +0000470 if (!Op) return 0;
471 Ops.push_back(Op);
472 }
473 return SE.getAddExpr(Ops);
Dan Gohman572645c2010-02-12 10:34:29 +0000474 }
Dan Gohman2ea09e02010-06-24 16:57:52 +0000475 return 0;
Dan Gohman572645c2010-02-12 10:34:29 +0000476 }
477
478 // Check for a multiply operand that we can pull RHS out of.
Dan Gohman2ea09e02010-06-24 16:57:52 +0000479 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS)) {
Dan Gohmanaae01f12010-02-19 19:32:49 +0000480 if (IgnoreSignificantBits || isMulSExtable(Mul, SE)) {
Dan Gohman572645c2010-02-12 10:34:29 +0000481 SmallVector<const SCEV *, 4> Ops;
482 bool Found = false;
483 for (SCEVMulExpr::op_iterator I = Mul->op_begin(), E = Mul->op_end();
484 I != E; ++I) {
Dan Gohman47667442010-05-20 16:23:28 +0000485 const SCEV *S = *I;
Dan Gohman572645c2010-02-12 10:34:29 +0000486 if (!Found)
Dan Gohman47667442010-05-20 16:23:28 +0000487 if (const SCEV *Q = getExactSDiv(S, RHS, SE,
Dan Gohmanf09b7122010-02-19 19:35:48 +0000488 IgnoreSignificantBits)) {
Dan Gohman47667442010-05-20 16:23:28 +0000489 S = Q;
Dan Gohman572645c2010-02-12 10:34:29 +0000490 Found = true;
Dan Gohman572645c2010-02-12 10:34:29 +0000491 }
Dan Gohman47667442010-05-20 16:23:28 +0000492 Ops.push_back(S);
Dan Gohman572645c2010-02-12 10:34:29 +0000493 }
494 return Found ? SE.getMulExpr(Ops) : 0;
495 }
Dan Gohman2ea09e02010-06-24 16:57:52 +0000496 return 0;
497 }
Dan Gohman572645c2010-02-12 10:34:29 +0000498
499 // Otherwise we don't know.
500 return 0;
501}
502
503/// ExtractImmediate - If S involves the addition of a constant integer value,
504/// return that integer value, and mutate S to point to a new SCEV with that
505/// value excluded.
506static int64_t ExtractImmediate(const SCEV *&S, ScalarEvolution &SE) {
507 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
508 if (C->getValue()->getValue().getMinSignedBits() <= 64) {
Dan Gohmandeff6212010-05-03 22:09:21 +0000509 S = SE.getConstant(C->getType(), 0);
Dan Gohman572645c2010-02-12 10:34:29 +0000510 return C->getValue()->getSExtValue();
511 }
512 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
513 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
514 int64_t Result = ExtractImmediate(NewOps.front(), SE);
Dan Gohmane62d5882010-08-13 21:17:19 +0000515 if (Result != 0)
516 S = SE.getAddExpr(NewOps);
Dan Gohman572645c2010-02-12 10:34:29 +0000517 return Result;
518 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
519 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
520 int64_t Result = ExtractImmediate(NewOps.front(), SE);
Dan Gohmane62d5882010-08-13 21:17:19 +0000521 if (Result != 0)
522 S = SE.getAddRecExpr(NewOps, AR->getLoop());
Dan Gohman572645c2010-02-12 10:34:29 +0000523 return Result;
524 }
525 return 0;
526}
527
528/// ExtractSymbol - If S involves the addition of a GlobalValue address,
529/// return that symbol, and mutate S to point to a new SCEV with that
530/// value excluded.
531static GlobalValue *ExtractSymbol(const SCEV *&S, ScalarEvolution &SE) {
532 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
533 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) {
Dan Gohmandeff6212010-05-03 22:09:21 +0000534 S = SE.getConstant(GV->getType(), 0);
Dan Gohman572645c2010-02-12 10:34:29 +0000535 return GV;
536 }
537 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
538 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
539 GlobalValue *Result = ExtractSymbol(NewOps.back(), SE);
Dan Gohmane62d5882010-08-13 21:17:19 +0000540 if (Result)
541 S = SE.getAddExpr(NewOps);
Dan Gohman572645c2010-02-12 10:34:29 +0000542 return Result;
543 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
544 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
545 GlobalValue *Result = ExtractSymbol(NewOps.front(), SE);
Dan Gohmane62d5882010-08-13 21:17:19 +0000546 if (Result)
547 S = SE.getAddRecExpr(NewOps, AR->getLoop());
Dan Gohman572645c2010-02-12 10:34:29 +0000548 return Result;
549 }
550 return 0;
Nate Begemaneaa13852004-10-18 21:08:22 +0000551}
552
Dan Gohmanf284ce22009-02-18 00:08:39 +0000553/// isAddressUse - Returns true if the specified instruction is using the
Dale Johannesen203af582008-12-05 21:47:27 +0000554/// specified value as an address.
555static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
556 bool isAddress = isa<LoadInst>(Inst);
557 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
558 if (SI->getOperand(1) == OperandVal)
559 isAddress = true;
560 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
561 // Addressing modes can also be folded into prefetches and a variety
562 // of intrinsics.
563 switch (II->getIntrinsicID()) {
564 default: break;
565 case Intrinsic::prefetch:
566 case Intrinsic::x86_sse2_loadu_dq:
567 case Intrinsic::x86_sse2_loadu_pd:
568 case Intrinsic::x86_sse_loadu_ps:
569 case Intrinsic::x86_sse_storeu_ps:
570 case Intrinsic::x86_sse2_storeu_pd:
571 case Intrinsic::x86_sse2_storeu_dq:
572 case Intrinsic::x86_sse2_storel_dq:
Gabor Greifad72e732010-06-30 09:15:28 +0000573 if (II->getArgOperand(0) == OperandVal)
Dale Johannesen203af582008-12-05 21:47:27 +0000574 isAddress = true;
575 break;
576 }
577 }
578 return isAddress;
579}
Chris Lattner0ae33eb2005-10-03 01:04:44 +0000580
Dan Gohman21e77222009-03-09 21:01:17 +0000581/// getAccessType - Return the type of the memory being accessed.
582static const Type *getAccessType(const Instruction *Inst) {
Dan Gohmana537bf82009-05-18 16:45:28 +0000583 const Type *AccessTy = Inst->getType();
Dan Gohman21e77222009-03-09 21:01:17 +0000584 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst))
Dan Gohmana537bf82009-05-18 16:45:28 +0000585 AccessTy = SI->getOperand(0)->getType();
Dan Gohman21e77222009-03-09 21:01:17 +0000586 else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
587 // Addressing modes can also be folded into prefetches and a variety
588 // of intrinsics.
589 switch (II->getIntrinsicID()) {
590 default: break;
591 case Intrinsic::x86_sse_storeu_ps:
592 case Intrinsic::x86_sse2_storeu_pd:
593 case Intrinsic::x86_sse2_storeu_dq:
594 case Intrinsic::x86_sse2_storel_dq:
Gabor Greifad72e732010-06-30 09:15:28 +0000595 AccessTy = II->getArgOperand(0)->getType();
Dan Gohman21e77222009-03-09 21:01:17 +0000596 break;
597 }
598 }
Dan Gohman572645c2010-02-12 10:34:29 +0000599
600 // All pointers have the same requirements, so canonicalize them to an
601 // arbitrary pointer type to minimize variation.
602 if (const PointerType *PTy = dyn_cast<PointerType>(AccessTy))
603 AccessTy = PointerType::get(IntegerType::get(PTy->getContext(), 1),
604 PTy->getAddressSpace());
605
Dan Gohmana537bf82009-05-18 16:45:28 +0000606 return AccessTy;
Dan Gohman21e77222009-03-09 21:01:17 +0000607}
608
Dan Gohman572645c2010-02-12 10:34:29 +0000609/// DeleteTriviallyDeadInstructions - If any of the instructions is the
610/// specified set are trivially dead, delete them and see if this makes any of
611/// their operands subsequently dead.
612static bool
613DeleteTriviallyDeadInstructions(SmallVectorImpl<WeakVH> &DeadInsts) {
614 bool Changed = false;
615
616 while (!DeadInsts.empty()) {
Gabor Greiff097b592010-09-18 11:55:34 +0000617 Instruction *I = dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val());
Dan Gohman572645c2010-02-12 10:34:29 +0000618
619 if (I == 0 || !isInstructionTriviallyDead(I))
620 continue;
621
622 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
623 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
624 *OI = 0;
625 if (U->use_empty())
626 DeadInsts.push_back(U);
627 }
628
629 I->eraseFromParent();
630 Changed = true;
631 }
632
633 return Changed;
634}
635
Dan Gohman7979b722010-01-22 00:46:49 +0000636namespace {
Jim Grosbach56a1f802009-11-17 17:53:56 +0000637
Dan Gohman572645c2010-02-12 10:34:29 +0000638/// Cost - This class is used to measure and compare candidate formulae.
639class Cost {
640 /// TODO: Some of these could be merged. Also, a lexical ordering
641 /// isn't always optimal.
642 unsigned NumRegs;
643 unsigned AddRecCost;
644 unsigned NumIVMuls;
645 unsigned NumBaseAdds;
646 unsigned ImmCost;
647 unsigned SetupCost;
Nate Begeman16997482005-07-30 00:15:07 +0000648
Dan Gohman572645c2010-02-12 10:34:29 +0000649public:
650 Cost()
651 : NumRegs(0), AddRecCost(0), NumIVMuls(0), NumBaseAdds(0), ImmCost(0),
652 SetupCost(0) {}
Jim Grosbach56a1f802009-11-17 17:53:56 +0000653
Dan Gohman572645c2010-02-12 10:34:29 +0000654 bool operator<(const Cost &Other) const;
Dan Gohman7979b722010-01-22 00:46:49 +0000655
Dan Gohman572645c2010-02-12 10:34:29 +0000656 void Loose();
Dan Gohman7979b722010-01-22 00:46:49 +0000657
Dan Gohman572645c2010-02-12 10:34:29 +0000658 void RateFormula(const Formula &F,
659 SmallPtrSet<const SCEV *, 16> &Regs,
660 const DenseSet<const SCEV *> &VisitedRegs,
661 const Loop *L,
662 const SmallVectorImpl<int64_t> &Offsets,
663 ScalarEvolution &SE, DominatorTree &DT);
Dan Gohman7979b722010-01-22 00:46:49 +0000664
Dan Gohman572645c2010-02-12 10:34:29 +0000665 void print(raw_ostream &OS) const;
666 void dump() const;
Dan Gohman7979b722010-01-22 00:46:49 +0000667
Dan Gohman572645c2010-02-12 10:34:29 +0000668private:
669 void RateRegister(const SCEV *Reg,
670 SmallPtrSet<const SCEV *, 16> &Regs,
671 const Loop *L,
672 ScalarEvolution &SE, DominatorTree &DT);
Dan Gohman9214b822010-02-13 02:06:02 +0000673 void RatePrimaryRegister(const SCEV *Reg,
674 SmallPtrSet<const SCEV *, 16> &Regs,
675 const Loop *L,
676 ScalarEvolution &SE, DominatorTree &DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000677};
678
679}
680
681/// RateRegister - Tally up interesting quantities from the given register.
682void Cost::RateRegister(const SCEV *Reg,
683 SmallPtrSet<const SCEV *, 16> &Regs,
684 const Loop *L,
685 ScalarEvolution &SE, DominatorTree &DT) {
Dan Gohman9214b822010-02-13 02:06:02 +0000686 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Reg)) {
687 if (AR->getLoop() == L)
688 AddRecCost += 1; /// TODO: This should be a function of the stride.
Dan Gohman572645c2010-02-12 10:34:29 +0000689
Dan Gohman9214b822010-02-13 02:06:02 +0000690 // If this is an addrec for a loop that's already been visited by LSR,
691 // don't second-guess its addrec phi nodes. LSR isn't currently smart
692 // enough to reason about more than one loop at a time. Consider these
693 // registers free and leave them alone.
694 else if (L->contains(AR->getLoop()) ||
695 (!AR->getLoop()->contains(L) &&
696 DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))) {
697 for (BasicBlock::iterator I = AR->getLoop()->getHeader()->begin();
698 PHINode *PN = dyn_cast<PHINode>(I); ++I)
699 if (SE.isSCEVable(PN->getType()) &&
700 (SE.getEffectiveSCEVType(PN->getType()) ==
701 SE.getEffectiveSCEVType(AR->getType())) &&
702 SE.getSCEV(PN) == AR)
703 return;
Dan Gohman572645c2010-02-12 10:34:29 +0000704
Dan Gohman9214b822010-02-13 02:06:02 +0000705 // If this isn't one of the addrecs that the loop already has, it
706 // would require a costly new phi and add. TODO: This isn't
707 // precisely modeled right now.
708 ++NumBaseAdds;
709 if (!Regs.count(AR->getStart()))
Dan Gohman572645c2010-02-12 10:34:29 +0000710 RateRegister(AR->getStart(), Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000711 }
Dan Gohman572645c2010-02-12 10:34:29 +0000712
Dan Gohman9214b822010-02-13 02:06:02 +0000713 // Add the step value register, if it needs one.
714 // TODO: The non-affine case isn't precisely modeled here.
715 if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1)))
716 if (!Regs.count(AR->getStart()))
717 RateRegister(AR->getOperand(1), Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000718 }
Dan Gohman9214b822010-02-13 02:06:02 +0000719 ++NumRegs;
720
721 // Rough heuristic; favor registers which don't require extra setup
722 // instructions in the preheader.
723 if (!isa<SCEVUnknown>(Reg) &&
724 !isa<SCEVConstant>(Reg) &&
725 !(isa<SCEVAddRecExpr>(Reg) &&
726 (isa<SCEVUnknown>(cast<SCEVAddRecExpr>(Reg)->getStart()) ||
727 isa<SCEVConstant>(cast<SCEVAddRecExpr>(Reg)->getStart()))))
728 ++SetupCost;
Dan Gohman23c3fde2010-10-07 23:41:58 +0000729
730 NumIVMuls += isa<SCEVMulExpr>(Reg) &&
Dan Gohman17ead4f2010-11-17 21:23:15 +0000731 SE.hasComputableLoopEvolution(Reg, L);
Dan Gohman9214b822010-02-13 02:06:02 +0000732}
733
734/// RatePrimaryRegister - Record this register in the set. If we haven't seen it
735/// before, rate it.
736void Cost::RatePrimaryRegister(const SCEV *Reg,
Dan Gohman7fca2292010-02-16 19:42:34 +0000737 SmallPtrSet<const SCEV *, 16> &Regs,
738 const Loop *L,
739 ScalarEvolution &SE, DominatorTree &DT) {
Dan Gohman9214b822010-02-13 02:06:02 +0000740 if (Regs.insert(Reg))
741 RateRegister(Reg, Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000742}
743
744void Cost::RateFormula(const Formula &F,
745 SmallPtrSet<const SCEV *, 16> &Regs,
746 const DenseSet<const SCEV *> &VisitedRegs,
747 const Loop *L,
748 const SmallVectorImpl<int64_t> &Offsets,
749 ScalarEvolution &SE, DominatorTree &DT) {
750 // Tally up the registers.
751 if (const SCEV *ScaledReg = F.ScaledReg) {
752 if (VisitedRegs.count(ScaledReg)) {
753 Loose();
754 return;
755 }
Dan Gohman9214b822010-02-13 02:06:02 +0000756 RatePrimaryRegister(ScaledReg, Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000757 }
758 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
759 E = F.BaseRegs.end(); I != E; ++I) {
760 const SCEV *BaseReg = *I;
761 if (VisitedRegs.count(BaseReg)) {
762 Loose();
763 return;
764 }
Dan Gohman9214b822010-02-13 02:06:02 +0000765 RatePrimaryRegister(BaseReg, Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000766 }
767
768 if (F.BaseRegs.size() > 1)
769 NumBaseAdds += F.BaseRegs.size() - 1;
770
771 // Tally up the non-zero immediates.
772 for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
773 E = Offsets.end(); I != E; ++I) {
774 int64_t Offset = (uint64_t)*I + F.AM.BaseOffs;
775 if (F.AM.BaseGV)
776 ImmCost += 64; // Handle symbolic values conservatively.
777 // TODO: This should probably be the pointer size.
778 else if (Offset != 0)
779 ImmCost += APInt(64, Offset, true).getMinSignedBits();
780 }
781}
782
783/// Loose - Set this cost to a loosing value.
784void Cost::Loose() {
785 NumRegs = ~0u;
786 AddRecCost = ~0u;
787 NumIVMuls = ~0u;
788 NumBaseAdds = ~0u;
789 ImmCost = ~0u;
790 SetupCost = ~0u;
791}
792
793/// operator< - Choose the lower cost.
794bool Cost::operator<(const Cost &Other) const {
795 if (NumRegs != Other.NumRegs)
796 return NumRegs < Other.NumRegs;
797 if (AddRecCost != Other.AddRecCost)
798 return AddRecCost < Other.AddRecCost;
799 if (NumIVMuls != Other.NumIVMuls)
800 return NumIVMuls < Other.NumIVMuls;
801 if (NumBaseAdds != Other.NumBaseAdds)
802 return NumBaseAdds < Other.NumBaseAdds;
803 if (ImmCost != Other.ImmCost)
804 return ImmCost < Other.ImmCost;
805 if (SetupCost != Other.SetupCost)
806 return SetupCost < Other.SetupCost;
807 return false;
808}
809
810void Cost::print(raw_ostream &OS) const {
811 OS << NumRegs << " reg" << (NumRegs == 1 ? "" : "s");
812 if (AddRecCost != 0)
813 OS << ", with addrec cost " << AddRecCost;
814 if (NumIVMuls != 0)
815 OS << ", plus " << NumIVMuls << " IV mul" << (NumIVMuls == 1 ? "" : "s");
816 if (NumBaseAdds != 0)
817 OS << ", plus " << NumBaseAdds << " base add"
818 << (NumBaseAdds == 1 ? "" : "s");
819 if (ImmCost != 0)
820 OS << ", plus " << ImmCost << " imm cost";
821 if (SetupCost != 0)
822 OS << ", plus " << SetupCost << " setup cost";
823}
824
825void Cost::dump() const {
826 print(errs()); errs() << '\n';
827}
828
829namespace {
830
831/// LSRFixup - An operand value in an instruction which is to be replaced
832/// with some equivalent, possibly strength-reduced, replacement.
833struct LSRFixup {
834 /// UserInst - The instruction which will be updated.
835 Instruction *UserInst;
836
837 /// OperandValToReplace - The operand of the instruction which will
838 /// be replaced. The operand may be used more than once; every instance
839 /// will be replaced.
840 Value *OperandValToReplace;
841
Dan Gohman448db1c2010-04-07 22:27:08 +0000842 /// PostIncLoops - If this user is to use the post-incremented value of an
Dan Gohman572645c2010-02-12 10:34:29 +0000843 /// induction variable, this variable is non-null and holds the loop
844 /// associated with the induction variable.
Dan Gohman448db1c2010-04-07 22:27:08 +0000845 PostIncLoopSet PostIncLoops;
Dan Gohman572645c2010-02-12 10:34:29 +0000846
847 /// LUIdx - The index of the LSRUse describing the expression which
848 /// this fixup needs, minus an offset (below).
849 size_t LUIdx;
850
851 /// Offset - A constant offset to be added to the LSRUse expression.
852 /// This allows multiple fixups to share the same LSRUse with different
853 /// offsets, for example in an unrolled loop.
854 int64_t Offset;
855
Dan Gohman448db1c2010-04-07 22:27:08 +0000856 bool isUseFullyOutsideLoop(const Loop *L) const;
857
Dan Gohman572645c2010-02-12 10:34:29 +0000858 LSRFixup();
859
860 void print(raw_ostream &OS) const;
861 void dump() const;
862};
863
864}
865
866LSRFixup::LSRFixup()
Dan Gohmanea507f52010-05-20 19:44:23 +0000867 : UserInst(0), OperandValToReplace(0), LUIdx(~size_t(0)), Offset(0) {}
Dan Gohman572645c2010-02-12 10:34:29 +0000868
Dan Gohman448db1c2010-04-07 22:27:08 +0000869/// isUseFullyOutsideLoop - Test whether this fixup always uses its
870/// value outside of the given loop.
871bool LSRFixup::isUseFullyOutsideLoop(const Loop *L) const {
872 // PHI nodes use their value in their incoming blocks.
873 if (const PHINode *PN = dyn_cast<PHINode>(UserInst)) {
874 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
875 if (PN->getIncomingValue(i) == OperandValToReplace &&
876 L->contains(PN->getIncomingBlock(i)))
877 return false;
878 return true;
879 }
880
881 return !L->contains(UserInst);
882}
883
Dan Gohman572645c2010-02-12 10:34:29 +0000884void LSRFixup::print(raw_ostream &OS) const {
885 OS << "UserInst=";
886 // Store is common and interesting enough to be worth special-casing.
887 if (StoreInst *Store = dyn_cast<StoreInst>(UserInst)) {
888 OS << "store ";
889 WriteAsOperand(OS, Store->getOperand(0), /*PrintType=*/false);
890 } else if (UserInst->getType()->isVoidTy())
891 OS << UserInst->getOpcodeName();
892 else
893 WriteAsOperand(OS, UserInst, /*PrintType=*/false);
894
895 OS << ", OperandValToReplace=";
896 WriteAsOperand(OS, OperandValToReplace, /*PrintType=*/false);
897
Dan Gohman448db1c2010-04-07 22:27:08 +0000898 for (PostIncLoopSet::const_iterator I = PostIncLoops.begin(),
899 E = PostIncLoops.end(); I != E; ++I) {
Dan Gohman572645c2010-02-12 10:34:29 +0000900 OS << ", PostIncLoop=";
Dan Gohman448db1c2010-04-07 22:27:08 +0000901 WriteAsOperand(OS, (*I)->getHeader(), /*PrintType=*/false);
Dan Gohman572645c2010-02-12 10:34:29 +0000902 }
903
904 if (LUIdx != ~size_t(0))
905 OS << ", LUIdx=" << LUIdx;
906
907 if (Offset != 0)
908 OS << ", Offset=" << Offset;
909}
910
911void LSRFixup::dump() const {
912 print(errs()); errs() << '\n';
913}
914
915namespace {
916
917/// UniquifierDenseMapInfo - A DenseMapInfo implementation for holding
918/// DenseMaps and DenseSets of sorted SmallVectors of const SCEV*.
919struct UniquifierDenseMapInfo {
920 static SmallVector<const SCEV *, 2> getEmptyKey() {
921 SmallVector<const SCEV *, 2> V;
922 V.push_back(reinterpret_cast<const SCEV *>(-1));
923 return V;
924 }
925
926 static SmallVector<const SCEV *, 2> getTombstoneKey() {
927 SmallVector<const SCEV *, 2> V;
928 V.push_back(reinterpret_cast<const SCEV *>(-2));
929 return V;
930 }
931
932 static unsigned getHashValue(const SmallVector<const SCEV *, 2> &V) {
933 unsigned Result = 0;
934 for (SmallVectorImpl<const SCEV *>::const_iterator I = V.begin(),
935 E = V.end(); I != E; ++I)
936 Result ^= DenseMapInfo<const SCEV *>::getHashValue(*I);
937 return Result;
938 }
939
940 static bool isEqual(const SmallVector<const SCEV *, 2> &LHS,
941 const SmallVector<const SCEV *, 2> &RHS) {
942 return LHS == RHS;
943 }
944};
945
946/// LSRUse - This class holds the state that LSR keeps for each use in
947/// IVUsers, as well as uses invented by LSR itself. It includes information
948/// about what kinds of things can be folded into the user, information about
949/// the user itself, and information about how the use may be satisfied.
950/// TODO: Represent multiple users of the same expression in common?
951class LSRUse {
952 DenseSet<SmallVector<const SCEV *, 2>, UniquifierDenseMapInfo> Uniquifier;
953
954public:
955 /// KindType - An enum for a kind of use, indicating what types of
956 /// scaled and immediate operands it might support.
957 enum KindType {
958 Basic, ///< A normal use, with no folding.
959 Special, ///< A special case of basic, allowing -1 scales.
960 Address, ///< An address use; folding according to TargetLowering
961 ICmpZero ///< An equality icmp with both operands folded into one.
962 // TODO: Add a generic icmp too?
Dan Gohman7979b722010-01-22 00:46:49 +0000963 };
Dan Gohman572645c2010-02-12 10:34:29 +0000964
965 KindType Kind;
966 const Type *AccessTy;
967
968 SmallVector<int64_t, 8> Offsets;
969 int64_t MinOffset;
970 int64_t MaxOffset;
971
972 /// AllFixupsOutsideLoop - This records whether all of the fixups using this
973 /// LSRUse are outside of the loop, in which case some special-case heuristics
974 /// may be used.
975 bool AllFixupsOutsideLoop;
976
Dan Gohmana9db1292010-07-15 20:24:58 +0000977 /// WidestFixupType - This records the widest use type for any fixup using
978 /// this LSRUse. FindUseWithSimilarFormula can't consider uses with different
979 /// max fixup widths to be equivalent, because the narrower one may be relying
980 /// on the implicit truncation to truncate away bogus bits.
981 const Type *WidestFixupType;
982
Dan Gohman572645c2010-02-12 10:34:29 +0000983 /// Formulae - A list of ways to build a value that can satisfy this user.
984 /// After the list is populated, one of these is selected heuristically and
985 /// used to formulate a replacement for OperandValToReplace in UserInst.
986 SmallVector<Formula, 12> Formulae;
987
988 /// Regs - The set of register candidates used by all formulae in this LSRUse.
989 SmallPtrSet<const SCEV *, 4> Regs;
990
991 LSRUse(KindType K, const Type *T) : Kind(K), AccessTy(T),
992 MinOffset(INT64_MAX),
993 MaxOffset(INT64_MIN),
Dan Gohmana9db1292010-07-15 20:24:58 +0000994 AllFixupsOutsideLoop(true),
995 WidestFixupType(0) {}
Dan Gohman572645c2010-02-12 10:34:29 +0000996
Dan Gohmana2086b32010-05-19 23:43:12 +0000997 bool HasFormulaWithSameRegs(const Formula &F) const;
Dan Gohman454d26d2010-02-22 04:11:59 +0000998 bool InsertFormula(const Formula &F);
Dan Gohmand69d6282010-05-18 22:39:15 +0000999 void DeleteFormula(Formula &F);
Dan Gohmanb2df4332010-05-18 23:42:37 +00001000 void RecomputeRegs(size_t LUIdx, RegUseTracker &Reguses);
Dan Gohman572645c2010-02-12 10:34:29 +00001001
Dan Gohman572645c2010-02-12 10:34:29 +00001002 void print(raw_ostream &OS) const;
1003 void dump() const;
1004};
1005
Dan Gohmanb6211712010-06-19 21:21:39 +00001006}
1007
Dan Gohmana2086b32010-05-19 23:43:12 +00001008/// HasFormula - Test whether this use as a formula which has the same
1009/// registers as the given formula.
1010bool LSRUse::HasFormulaWithSameRegs(const Formula &F) const {
1011 SmallVector<const SCEV *, 2> Key = F.BaseRegs;
1012 if (F.ScaledReg) Key.push_back(F.ScaledReg);
1013 // Unstable sort by host order ok, because this is only used for uniquifying.
1014 std::sort(Key.begin(), Key.end());
1015 return Uniquifier.count(Key);
1016}
1017
Dan Gohman572645c2010-02-12 10:34:29 +00001018/// InsertFormula - If the given formula has not yet been inserted, add it to
1019/// the list, and return true. Return false otherwise.
Dan Gohman454d26d2010-02-22 04:11:59 +00001020bool LSRUse::InsertFormula(const Formula &F) {
Dan Gohman572645c2010-02-12 10:34:29 +00001021 SmallVector<const SCEV *, 2> Key = F.BaseRegs;
1022 if (F.ScaledReg) Key.push_back(F.ScaledReg);
1023 // Unstable sort by host order ok, because this is only used for uniquifying.
1024 std::sort(Key.begin(), Key.end());
1025
1026 if (!Uniquifier.insert(Key).second)
1027 return false;
1028
1029 // Using a register to hold the value of 0 is not profitable.
1030 assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&
1031 "Zero allocated in a scaled register!");
1032#ifndef NDEBUG
1033 for (SmallVectorImpl<const SCEV *>::const_iterator I =
1034 F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I)
1035 assert(!(*I)->isZero() && "Zero allocated in a base register!");
1036#endif
1037
1038 // Add the formula to the list.
1039 Formulae.push_back(F);
1040
1041 // Record registers now being used by this use.
1042 if (F.ScaledReg) Regs.insert(F.ScaledReg);
1043 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
1044
1045 return true;
Dan Gohman7979b722010-01-22 00:46:49 +00001046}
1047
Dan Gohmand69d6282010-05-18 22:39:15 +00001048/// DeleteFormula - Remove the given formula from this use's list.
1049void LSRUse::DeleteFormula(Formula &F) {
Dan Gohman5ce6d052010-05-20 15:17:54 +00001050 if (&F != &Formulae.back())
1051 std::swap(F, Formulae.back());
Dan Gohmand69d6282010-05-18 22:39:15 +00001052 Formulae.pop_back();
Dan Gohmana2086b32010-05-19 23:43:12 +00001053 assert(!Formulae.empty() && "LSRUse has no formulae left!");
Dan Gohmand69d6282010-05-18 22:39:15 +00001054}
1055
Dan Gohmanb2df4332010-05-18 23:42:37 +00001056/// RecomputeRegs - Recompute the Regs field, and update RegUses.
1057void LSRUse::RecomputeRegs(size_t LUIdx, RegUseTracker &RegUses) {
1058 // Now that we've filtered out some formulae, recompute the Regs set.
1059 SmallPtrSet<const SCEV *, 4> OldRegs = Regs;
1060 Regs.clear();
Dan Gohman402d4352010-05-20 20:33:18 +00001061 for (SmallVectorImpl<Formula>::const_iterator I = Formulae.begin(),
1062 E = Formulae.end(); I != E; ++I) {
1063 const Formula &F = *I;
Dan Gohmanb2df4332010-05-18 23:42:37 +00001064 if (F.ScaledReg) Regs.insert(F.ScaledReg);
1065 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
1066 }
1067
1068 // Update the RegTracker.
1069 for (SmallPtrSet<const SCEV *, 4>::iterator I = OldRegs.begin(),
1070 E = OldRegs.end(); I != E; ++I)
1071 if (!Regs.count(*I))
1072 RegUses.DropRegister(*I, LUIdx);
1073}
1074
Dan Gohman572645c2010-02-12 10:34:29 +00001075void LSRUse::print(raw_ostream &OS) const {
1076 OS << "LSR Use: Kind=";
1077 switch (Kind) {
1078 case Basic: OS << "Basic"; break;
1079 case Special: OS << "Special"; break;
1080 case ICmpZero: OS << "ICmpZero"; break;
1081 case Address:
1082 OS << "Address of ";
Duncan Sands1df98592010-02-16 11:11:14 +00001083 if (AccessTy->isPointerTy())
Dan Gohman572645c2010-02-12 10:34:29 +00001084 OS << "pointer"; // the full pointer type could be really verbose
1085 else
1086 OS << *AccessTy;
Evan Chengcdf43b12007-10-25 09:11:16 +00001087 }
1088
Dan Gohman572645c2010-02-12 10:34:29 +00001089 OS << ", Offsets={";
1090 for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
1091 E = Offsets.end(); I != E; ++I) {
1092 OS << *I;
Oscar Fuentesee56c422010-08-02 06:00:15 +00001093 if (llvm::next(I) != E)
Dan Gohman572645c2010-02-12 10:34:29 +00001094 OS << ',';
Dan Gohman7979b722010-01-22 00:46:49 +00001095 }
Dan Gohman572645c2010-02-12 10:34:29 +00001096 OS << '}';
Dan Gohman7979b722010-01-22 00:46:49 +00001097
Dan Gohman572645c2010-02-12 10:34:29 +00001098 if (AllFixupsOutsideLoop)
1099 OS << ", all-fixups-outside-loop";
Dan Gohmana9db1292010-07-15 20:24:58 +00001100
1101 if (WidestFixupType)
1102 OS << ", widest fixup type: " << *WidestFixupType;
Dan Gohman7979b722010-01-22 00:46:49 +00001103}
1104
Dan Gohman572645c2010-02-12 10:34:29 +00001105void LSRUse::dump() const {
1106 print(errs()); errs() << '\n';
1107}
Dan Gohman7979b722010-01-22 00:46:49 +00001108
Dan Gohman572645c2010-02-12 10:34:29 +00001109/// isLegalUse - Test whether the use described by AM is "legal", meaning it can
1110/// be completely folded into the user instruction at isel time. This includes
1111/// address-mode folding and special icmp tricks.
1112static bool isLegalUse(const TargetLowering::AddrMode &AM,
1113 LSRUse::KindType Kind, const Type *AccessTy,
1114 const TargetLowering *TLI) {
1115 switch (Kind) {
1116 case LSRUse::Address:
1117 // If we have low-level target information, ask the target if it can
1118 // completely fold this address.
1119 if (TLI) return TLI->isLegalAddressingMode(AM, AccessTy);
1120
1121 // Otherwise, just guess that reg+reg addressing is legal.
1122 return !AM.BaseGV && AM.BaseOffs == 0 && AM.Scale <= 1;
1123
1124 case LSRUse::ICmpZero:
1125 // There's not even a target hook for querying whether it would be legal to
1126 // fold a GV into an ICmp.
1127 if (AM.BaseGV)
1128 return false;
1129
1130 // ICmp only has two operands; don't allow more than two non-trivial parts.
1131 if (AM.Scale != 0 && AM.HasBaseReg && AM.BaseOffs != 0)
1132 return false;
1133
1134 // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by
1135 // putting the scaled register in the other operand of the icmp.
1136 if (AM.Scale != 0 && AM.Scale != -1)
1137 return false;
1138
1139 // If we have low-level target information, ask the target if it can fold an
1140 // integer immediate on an icmp.
1141 if (AM.BaseOffs != 0) {
1142 if (TLI) return TLI->isLegalICmpImmediate(-AM.BaseOffs);
1143 return false;
Dan Gohman7979b722010-01-22 00:46:49 +00001144 }
Dan Gohman572645c2010-02-12 10:34:29 +00001145
1146 return true;
1147
1148 case LSRUse::Basic:
1149 // Only handle single-register values.
1150 return !AM.BaseGV && AM.Scale == 0 && AM.BaseOffs == 0;
1151
1152 case LSRUse::Special:
1153 // Only handle -1 scales, or no scale.
1154 return AM.Scale == 0 || AM.Scale == -1;
Dan Gohman7979b722010-01-22 00:46:49 +00001155 }
1156
Dan Gohman7979b722010-01-22 00:46:49 +00001157 return false;
1158}
1159
Dan Gohman572645c2010-02-12 10:34:29 +00001160static bool isLegalUse(TargetLowering::AddrMode AM,
1161 int64_t MinOffset, int64_t MaxOffset,
1162 LSRUse::KindType Kind, const Type *AccessTy,
1163 const TargetLowering *TLI) {
1164 // Check for overflow.
1165 if (((int64_t)((uint64_t)AM.BaseOffs + MinOffset) > AM.BaseOffs) !=
1166 (MinOffset > 0))
1167 return false;
1168 AM.BaseOffs = (uint64_t)AM.BaseOffs + MinOffset;
1169 if (isLegalUse(AM, Kind, AccessTy, TLI)) {
1170 AM.BaseOffs = (uint64_t)AM.BaseOffs - MinOffset;
1171 // Check for overflow.
1172 if (((int64_t)((uint64_t)AM.BaseOffs + MaxOffset) > AM.BaseOffs) !=
1173 (MaxOffset > 0))
1174 return false;
1175 AM.BaseOffs = (uint64_t)AM.BaseOffs + MaxOffset;
1176 return isLegalUse(AM, Kind, AccessTy, TLI);
Dan Gohman7979b722010-01-22 00:46:49 +00001177 }
Dan Gohman572645c2010-02-12 10:34:29 +00001178 return false;
Dan Gohman7979b722010-01-22 00:46:49 +00001179}
1180
Dan Gohman572645c2010-02-12 10:34:29 +00001181static bool isAlwaysFoldable(int64_t BaseOffs,
1182 GlobalValue *BaseGV,
1183 bool HasBaseReg,
1184 LSRUse::KindType Kind, const Type *AccessTy,
Dan Gohman454d26d2010-02-22 04:11:59 +00001185 const TargetLowering *TLI) {
Dan Gohman572645c2010-02-12 10:34:29 +00001186 // Fast-path: zero is always foldable.
1187 if (BaseOffs == 0 && !BaseGV) return true;
Dan Gohman7979b722010-01-22 00:46:49 +00001188
Dan Gohman572645c2010-02-12 10:34:29 +00001189 // Conservatively, create an address with an immediate and a
1190 // base and a scale.
1191 TargetLowering::AddrMode AM;
1192 AM.BaseOffs = BaseOffs;
1193 AM.BaseGV = BaseGV;
1194 AM.HasBaseReg = HasBaseReg;
1195 AM.Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
Dan Gohman7979b722010-01-22 00:46:49 +00001196
Dan Gohmana2086b32010-05-19 23:43:12 +00001197 // Canonicalize a scale of 1 to a base register if the formula doesn't
1198 // already have a base register.
1199 if (!AM.HasBaseReg && AM.Scale == 1) {
1200 AM.Scale = 0;
1201 AM.HasBaseReg = true;
1202 }
1203
Dan Gohman572645c2010-02-12 10:34:29 +00001204 return isLegalUse(AM, Kind, AccessTy, TLI);
Dan Gohman7979b722010-01-22 00:46:49 +00001205}
1206
Dan Gohman572645c2010-02-12 10:34:29 +00001207static bool isAlwaysFoldable(const SCEV *S,
1208 int64_t MinOffset, int64_t MaxOffset,
1209 bool HasBaseReg,
1210 LSRUse::KindType Kind, const Type *AccessTy,
1211 const TargetLowering *TLI,
1212 ScalarEvolution &SE) {
1213 // Fast-path: zero is always foldable.
1214 if (S->isZero()) return true;
1215
1216 // Conservatively, create an address with an immediate and a
1217 // base and a scale.
1218 int64_t BaseOffs = ExtractImmediate(S, SE);
1219 GlobalValue *BaseGV = ExtractSymbol(S, SE);
1220
1221 // If there's anything else involved, it's not foldable.
1222 if (!S->isZero()) return false;
1223
1224 // Fast-path: zero is always foldable.
1225 if (BaseOffs == 0 && !BaseGV) return true;
1226
1227 // Conservatively, create an address with an immediate and a
1228 // base and a scale.
1229 TargetLowering::AddrMode AM;
1230 AM.BaseOffs = BaseOffs;
1231 AM.BaseGV = BaseGV;
1232 AM.HasBaseReg = HasBaseReg;
1233 AM.Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1234
1235 return isLegalUse(AM, MinOffset, MaxOffset, Kind, AccessTy, TLI);
Dan Gohman7979b722010-01-22 00:46:49 +00001236}
1237
Dan Gohmanb6211712010-06-19 21:21:39 +00001238namespace {
1239
Dan Gohman1e3121c2010-06-19 21:29:59 +00001240/// UseMapDenseMapInfo - A DenseMapInfo implementation for holding
1241/// DenseMaps and DenseSets of pairs of const SCEV* and LSRUse::Kind.
1242struct UseMapDenseMapInfo {
1243 static std::pair<const SCEV *, LSRUse::KindType> getEmptyKey() {
1244 return std::make_pair(reinterpret_cast<const SCEV *>(-1), LSRUse::Basic);
1245 }
1246
1247 static std::pair<const SCEV *, LSRUse::KindType> getTombstoneKey() {
1248 return std::make_pair(reinterpret_cast<const SCEV *>(-2), LSRUse::Basic);
1249 }
1250
1251 static unsigned
1252 getHashValue(const std::pair<const SCEV *, LSRUse::KindType> &V) {
1253 unsigned Result = DenseMapInfo<const SCEV *>::getHashValue(V.first);
1254 Result ^= DenseMapInfo<unsigned>::getHashValue(unsigned(V.second));
1255 return Result;
1256 }
1257
1258 static bool isEqual(const std::pair<const SCEV *, LSRUse::KindType> &LHS,
1259 const std::pair<const SCEV *, LSRUse::KindType> &RHS) {
1260 return LHS == RHS;
1261 }
1262};
1263
Dan Gohman572645c2010-02-12 10:34:29 +00001264/// LSRInstance - This class holds state for the main loop strength reduction
1265/// logic.
1266class LSRInstance {
1267 IVUsers &IU;
1268 ScalarEvolution &SE;
1269 DominatorTree &DT;
Dan Gohmane5f76872010-04-09 22:07:05 +00001270 LoopInfo &LI;
Dan Gohman572645c2010-02-12 10:34:29 +00001271 const TargetLowering *const TLI;
1272 Loop *const L;
1273 bool Changed;
1274
1275 /// IVIncInsertPos - This is the insert position that the current loop's
1276 /// induction variable increment should be placed. In simple loops, this is
1277 /// the latch block's terminator. But in more complicated cases, this is a
1278 /// position which will dominate all the in-loop post-increment users.
1279 Instruction *IVIncInsertPos;
1280
1281 /// Factors - Interesting factors between use strides.
1282 SmallSetVector<int64_t, 8> Factors;
1283
1284 /// Types - Interesting use types, to facilitate truncation reuse.
1285 SmallSetVector<const Type *, 4> Types;
1286
1287 /// Fixups - The list of operands which are to be replaced.
1288 SmallVector<LSRFixup, 16> Fixups;
1289
1290 /// Uses - The list of interesting uses.
1291 SmallVector<LSRUse, 16> Uses;
1292
1293 /// RegUses - Track which uses use which register candidates.
1294 RegUseTracker RegUses;
1295
1296 void OptimizeShadowIV();
1297 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse);
1298 ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse);
Dan Gohmanc6519f92010-05-20 20:05:31 +00001299 void OptimizeLoopTermCond();
Dan Gohman572645c2010-02-12 10:34:29 +00001300
1301 void CollectInterestingTypesAndFactors();
1302 void CollectFixupsAndInitialFormulae();
1303
1304 LSRFixup &getNewFixup() {
1305 Fixups.push_back(LSRFixup());
1306 return Fixups.back();
1307 }
1308
1309 // Support for sharing of LSRUses between LSRFixups.
Dan Gohman1e3121c2010-06-19 21:29:59 +00001310 typedef DenseMap<std::pair<const SCEV *, LSRUse::KindType>,
1311 size_t,
1312 UseMapDenseMapInfo> UseMapTy;
Dan Gohman572645c2010-02-12 10:34:29 +00001313 UseMapTy UseMap;
1314
Dan Gohman191bd642010-09-01 01:45:53 +00001315 bool reconcileNewOffset(LSRUse &LU, int64_t NewOffset, bool HasBaseReg,
Dan Gohman572645c2010-02-12 10:34:29 +00001316 LSRUse::KindType Kind, const Type *AccessTy);
1317
1318 std::pair<size_t, int64_t> getUse(const SCEV *&Expr,
1319 LSRUse::KindType Kind,
1320 const Type *AccessTy);
1321
Dan Gohmanc6897702010-10-07 23:33:43 +00001322 void DeleteUse(LSRUse &LU, size_t LUIdx);
Dan Gohman5ce6d052010-05-20 15:17:54 +00001323
Dan Gohman191bd642010-09-01 01:45:53 +00001324 LSRUse *FindUseWithSimilarFormula(const Formula &F, const LSRUse &OrigLU);
Dan Gohmana2086b32010-05-19 23:43:12 +00001325
Dan Gohman572645c2010-02-12 10:34:29 +00001326public:
Dan Gohman454d26d2010-02-22 04:11:59 +00001327 void InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
Dan Gohman572645c2010-02-12 10:34:29 +00001328 void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
1329 void CountRegisters(const Formula &F, size_t LUIdx);
1330 bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F);
1331
1332 void CollectLoopInvariantFixupsAndFormulae();
1333
1334 void GenerateReassociations(LSRUse &LU, unsigned LUIdx, Formula Base,
1335 unsigned Depth = 0);
1336 void GenerateCombinations(LSRUse &LU, unsigned LUIdx, Formula Base);
1337 void GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1338 void GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1339 void GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1340 void GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1341 void GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base);
1342 void GenerateCrossUseConstantOffsets();
1343 void GenerateAllReuseFormulae();
1344
1345 void FilterOutUndesirableDedicatedRegisters();
Dan Gohmand079c302010-05-18 22:51:59 +00001346
1347 size_t EstimateSearchSpaceComplexity() const;
Dan Gohman4aa5c2e2010-08-29 16:09:42 +00001348 void NarrowSearchSpaceByDetectingSupersets();
1349 void NarrowSearchSpaceByCollapsingUnrolledCode();
Dan Gohman4f7e18d2010-08-29 16:39:22 +00001350 void NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
Dan Gohman4aa5c2e2010-08-29 16:09:42 +00001351 void NarrowSearchSpaceByPickingWinnerRegs();
Dan Gohman572645c2010-02-12 10:34:29 +00001352 void NarrowSearchSpaceUsingHeuristics();
1353
1354 void SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
1355 Cost &SolutionCost,
1356 SmallVectorImpl<const Formula *> &Workspace,
1357 const Cost &CurCost,
1358 const SmallPtrSet<const SCEV *, 16> &CurRegs,
1359 DenseSet<const SCEV *> &VisitedRegs) const;
1360 void Solve(SmallVectorImpl<const Formula *> &Solution) const;
1361
Dan Gohmane5f76872010-04-09 22:07:05 +00001362 BasicBlock::iterator
1363 HoistInsertPosition(BasicBlock::iterator IP,
1364 const SmallVectorImpl<Instruction *> &Inputs) const;
1365 BasicBlock::iterator AdjustInsertPositionForExpand(BasicBlock::iterator IP,
1366 const LSRFixup &LF,
1367 const LSRUse &LU) const;
Dan Gohmand96eae82010-04-09 02:00:38 +00001368
Dan Gohman572645c2010-02-12 10:34:29 +00001369 Value *Expand(const LSRFixup &LF,
1370 const Formula &F,
Dan Gohman454d26d2010-02-22 04:11:59 +00001371 BasicBlock::iterator IP,
Dan Gohman572645c2010-02-12 10:34:29 +00001372 SCEVExpander &Rewriter,
Dan Gohman454d26d2010-02-22 04:11:59 +00001373 SmallVectorImpl<WeakVH> &DeadInsts) const;
Dan Gohman3a02cbc2010-02-16 20:25:07 +00001374 void RewriteForPHI(PHINode *PN, const LSRFixup &LF,
1375 const Formula &F,
Dan Gohman3a02cbc2010-02-16 20:25:07 +00001376 SCEVExpander &Rewriter,
1377 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman3a02cbc2010-02-16 20:25:07 +00001378 Pass *P) const;
Dan Gohman572645c2010-02-12 10:34:29 +00001379 void Rewrite(const LSRFixup &LF,
1380 const Formula &F,
Dan Gohman572645c2010-02-12 10:34:29 +00001381 SCEVExpander &Rewriter,
1382 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman572645c2010-02-12 10:34:29 +00001383 Pass *P) const;
1384 void ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
1385 Pass *P);
1386
1387 LSRInstance(const TargetLowering *tli, Loop *l, Pass *P);
1388
1389 bool getChanged() const { return Changed; }
1390
1391 void print_factors_and_types(raw_ostream &OS) const;
1392 void print_fixups(raw_ostream &OS) const;
1393 void print_uses(raw_ostream &OS) const;
1394 void print(raw_ostream &OS) const;
1395 void dump() const;
1396};
1397
1398}
1399
1400/// OptimizeShadowIV - If IV is used in a int-to-float cast
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001401/// inside the loop then try to eliminate the cast operation.
Dan Gohman572645c2010-02-12 10:34:29 +00001402void LSRInstance::OptimizeShadowIV() {
1403 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
1404 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1405 return;
1406
1407 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end();
1408 UI != E; /* empty */) {
1409 IVUsers::const_iterator CandidateUI = UI;
1410 ++UI;
1411 Instruction *ShadowUse = CandidateUI->getUser();
1412 const Type *DestTy = NULL;
1413
1414 /* If shadow use is a int->float cast then insert a second IV
1415 to eliminate this cast.
1416
1417 for (unsigned i = 0; i < n; ++i)
1418 foo((double)i);
1419
1420 is transformed into
1421
1422 double d = 0.0;
1423 for (unsigned i = 0; i < n; ++i, ++d)
1424 foo(d);
1425 */
1426 if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser()))
1427 DestTy = UCast->getDestTy();
1428 else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser()))
1429 DestTy = SCast->getDestTy();
1430 if (!DestTy) continue;
1431
1432 if (TLI) {
1433 // If target does not support DestTy natively then do not apply
1434 // this transformation.
1435 EVT DVT = TLI->getValueType(DestTy);
1436 if (!TLI->isTypeLegal(DVT)) continue;
1437 }
1438
1439 PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
1440 if (!PH) continue;
1441 if (PH->getNumIncomingValues() != 2) continue;
1442
1443 const Type *SrcTy = PH->getType();
1444 int Mantissa = DestTy->getFPMantissaWidth();
1445 if (Mantissa == -1) continue;
1446 if ((int)SE.getTypeSizeInBits(SrcTy) > Mantissa)
1447 continue;
1448
1449 unsigned Entry, Latch;
1450 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
1451 Entry = 0;
1452 Latch = 1;
Dan Gohman7979b722010-01-22 00:46:49 +00001453 } else {
Dan Gohman572645c2010-02-12 10:34:29 +00001454 Entry = 1;
1455 Latch = 0;
Dan Gohman7979b722010-01-22 00:46:49 +00001456 }
Dan Gohman7979b722010-01-22 00:46:49 +00001457
Dan Gohman572645c2010-02-12 10:34:29 +00001458 ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
1459 if (!Init) continue;
1460 Constant *NewInit = ConstantFP::get(DestTy, Init->getZExtValue());
Dan Gohman7979b722010-01-22 00:46:49 +00001461
Dan Gohman572645c2010-02-12 10:34:29 +00001462 BinaryOperator *Incr =
1463 dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
1464 if (!Incr) continue;
1465 if (Incr->getOpcode() != Instruction::Add
1466 && Incr->getOpcode() != Instruction::Sub)
Dan Gohman7979b722010-01-22 00:46:49 +00001467 continue;
Dan Gohman7979b722010-01-22 00:46:49 +00001468
Dan Gohman572645c2010-02-12 10:34:29 +00001469 /* Initialize new IV, double d = 0.0 in above example. */
1470 ConstantInt *C = NULL;
1471 if (Incr->getOperand(0) == PH)
1472 C = dyn_cast<ConstantInt>(Incr->getOperand(1));
1473 else if (Incr->getOperand(1) == PH)
1474 C = dyn_cast<ConstantInt>(Incr->getOperand(0));
Dan Gohman7979b722010-01-22 00:46:49 +00001475 else
Dan Gohman7979b722010-01-22 00:46:49 +00001476 continue;
1477
Dan Gohman572645c2010-02-12 10:34:29 +00001478 if (!C) continue;
Dan Gohman7979b722010-01-22 00:46:49 +00001479
Dan Gohman572645c2010-02-12 10:34:29 +00001480 // Ignore negative constants, as the code below doesn't handle them
1481 // correctly. TODO: Remove this restriction.
1482 if (!C->getValue().isStrictlyPositive()) continue;
Dan Gohman7979b722010-01-22 00:46:49 +00001483
Dan Gohman572645c2010-02-12 10:34:29 +00001484 /* Add new PHINode. */
1485 PHINode *NewPH = PHINode::Create(DestTy, "IV.S.", PH);
Dan Gohman7979b722010-01-22 00:46:49 +00001486
Dan Gohman572645c2010-02-12 10:34:29 +00001487 /* create new increment. '++d' in above example. */
1488 Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue());
1489 BinaryOperator *NewIncr =
1490 BinaryOperator::Create(Incr->getOpcode() == Instruction::Add ?
1491 Instruction::FAdd : Instruction::FSub,
1492 NewPH, CFP, "IV.S.next.", Incr);
Dan Gohman7979b722010-01-22 00:46:49 +00001493
Dan Gohman572645c2010-02-12 10:34:29 +00001494 NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
1495 NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
Dan Gohman7979b722010-01-22 00:46:49 +00001496
Dan Gohman572645c2010-02-12 10:34:29 +00001497 /* Remove cast operation */
1498 ShadowUse->replaceAllUsesWith(NewPH);
1499 ShadowUse->eraseFromParent();
Dan Gohmanc6519f92010-05-20 20:05:31 +00001500 Changed = true;
Dan Gohman572645c2010-02-12 10:34:29 +00001501 break;
Dan Gohman7979b722010-01-22 00:46:49 +00001502 }
1503}
1504
1505/// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
1506/// set the IV user and stride information and return true, otherwise return
1507/// false.
Dan Gohmanea507f52010-05-20 19:44:23 +00001508bool LSRInstance::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse) {
Dan Gohman572645c2010-02-12 10:34:29 +00001509 for (IVUsers::iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
1510 if (UI->getUser() == Cond) {
1511 // NOTE: we could handle setcc instructions with multiple uses here, but
1512 // InstCombine does it as well for simple uses, it's not clear that it
1513 // occurs enough in real life to handle.
1514 CondUse = UI;
1515 return true;
1516 }
Dan Gohman7979b722010-01-22 00:46:49 +00001517 return false;
Evan Chengcdf43b12007-10-25 09:11:16 +00001518}
1519
Dan Gohman7979b722010-01-22 00:46:49 +00001520/// OptimizeMax - Rewrite the loop's terminating condition if it uses
1521/// a max computation.
1522///
1523/// This is a narrow solution to a specific, but acute, problem. For loops
1524/// like this:
1525///
1526/// i = 0;
1527/// do {
1528/// p[i] = 0.0;
1529/// } while (++i < n);
1530///
1531/// the trip count isn't just 'n', because 'n' might not be positive. And
1532/// unfortunately this can come up even for loops where the user didn't use
1533/// a C do-while loop. For example, seemingly well-behaved top-test loops
1534/// will commonly be lowered like this:
1535//
1536/// if (n > 0) {
1537/// i = 0;
1538/// do {
1539/// p[i] = 0.0;
1540/// } while (++i < n);
1541/// }
1542///
1543/// and then it's possible for subsequent optimization to obscure the if
1544/// test in such a way that indvars can't find it.
1545///
1546/// When indvars can't find the if test in loops like this, it creates a
1547/// max expression, which allows it to give the loop a canonical
1548/// induction variable:
1549///
1550/// i = 0;
1551/// max = n < 1 ? 1 : n;
1552/// do {
1553/// p[i] = 0.0;
1554/// } while (++i != max);
1555///
1556/// Canonical induction variables are necessary because the loop passes
1557/// are designed around them. The most obvious example of this is the
1558/// LoopInfo analysis, which doesn't remember trip count values. It
1559/// expects to be able to rediscover the trip count each time it is
Dan Gohman572645c2010-02-12 10:34:29 +00001560/// needed, and it does this using a simple analysis that only succeeds if
Dan Gohman7979b722010-01-22 00:46:49 +00001561/// the loop has a canonical induction variable.
1562///
1563/// However, when it comes time to generate code, the maximum operation
1564/// can be quite costly, especially if it's inside of an outer loop.
1565///
1566/// This function solves this problem by detecting this type of loop and
1567/// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
1568/// the instructions for the maximum computation.
1569///
Dan Gohman572645c2010-02-12 10:34:29 +00001570ICmpInst *LSRInstance::OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse) {
Dan Gohman7979b722010-01-22 00:46:49 +00001571 // Check that the loop matches the pattern we're looking for.
1572 if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
1573 Cond->getPredicate() != CmpInst::ICMP_NE)
1574 return Cond;
Dan Gohmana10756e2010-01-21 02:09:26 +00001575
Dan Gohman7979b722010-01-22 00:46:49 +00001576 SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
1577 if (!Sel || !Sel->hasOneUse()) return Cond;
Dan Gohmana10756e2010-01-21 02:09:26 +00001578
Dan Gohman572645c2010-02-12 10:34:29 +00001579 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
Dan Gohman7979b722010-01-22 00:46:49 +00001580 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1581 return Cond;
Dan Gohmandeff6212010-05-03 22:09:21 +00001582 const SCEV *One = SE.getConstant(BackedgeTakenCount->getType(), 1);
Dan Gohmana10756e2010-01-21 02:09:26 +00001583
Dan Gohman7979b722010-01-22 00:46:49 +00001584 // Add one to the backedge-taken count to get the trip count.
Dan Gohman4065f602010-08-16 15:39:27 +00001585 const SCEV *IterationCount = SE.getAddExpr(One, BackedgeTakenCount);
Dan Gohman1d367982010-04-24 03:13:44 +00001586 if (IterationCount != SE.getSCEV(Sel)) return Cond;
Dan Gohman7979b722010-01-22 00:46:49 +00001587
Dan Gohman1d367982010-04-24 03:13:44 +00001588 // Check for a max calculation that matches the pattern. There's no check
1589 // for ICMP_ULE here because the comparison would be with zero, which
1590 // isn't interesting.
1591 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1592 const SCEVNAryExpr *Max = 0;
1593 if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(BackedgeTakenCount)) {
1594 Pred = ICmpInst::ICMP_SLE;
1595 Max = S;
1596 } else if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(IterationCount)) {
1597 Pred = ICmpInst::ICMP_SLT;
1598 Max = S;
1599 } else if (const SCEVUMaxExpr *U = dyn_cast<SCEVUMaxExpr>(IterationCount)) {
1600 Pred = ICmpInst::ICMP_ULT;
1601 Max = U;
1602 } else {
1603 // No match; bail.
Dan Gohman7979b722010-01-22 00:46:49 +00001604 return Cond;
Dan Gohman1d367982010-04-24 03:13:44 +00001605 }
Dan Gohman7979b722010-01-22 00:46:49 +00001606
1607 // To handle a max with more than two operands, this optimization would
1608 // require additional checking and setup.
1609 if (Max->getNumOperands() != 2)
1610 return Cond;
1611
1612 const SCEV *MaxLHS = Max->getOperand(0);
1613 const SCEV *MaxRHS = Max->getOperand(1);
Dan Gohman1d367982010-04-24 03:13:44 +00001614
1615 // ScalarEvolution canonicalizes constants to the left. For < and >, look
1616 // for a comparison with 1. For <= and >=, a comparison with zero.
1617 if (!MaxLHS ||
1618 (ICmpInst::isTrueWhenEqual(Pred) ? !MaxLHS->isZero() : (MaxLHS != One)))
1619 return Cond;
1620
Dan Gohman7979b722010-01-22 00:46:49 +00001621 // Check the relevant induction variable for conformance to
1622 // the pattern.
Dan Gohman572645c2010-02-12 10:34:29 +00001623 const SCEV *IV = SE.getSCEV(Cond->getOperand(0));
Dan Gohman7979b722010-01-22 00:46:49 +00001624 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
1625 if (!AR || !AR->isAffine() ||
1626 AR->getStart() != One ||
Dan Gohman572645c2010-02-12 10:34:29 +00001627 AR->getStepRecurrence(SE) != One)
Dan Gohman7979b722010-01-22 00:46:49 +00001628 return Cond;
1629
1630 assert(AR->getLoop() == L &&
1631 "Loop condition operand is an addrec in a different loop!");
1632
1633 // Check the right operand of the select, and remember it, as it will
1634 // be used in the new comparison instruction.
1635 Value *NewRHS = 0;
Dan Gohman1d367982010-04-24 03:13:44 +00001636 if (ICmpInst::isTrueWhenEqual(Pred)) {
1637 // Look for n+1, and grab n.
1638 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(1)))
1639 if (isa<ConstantInt>(BO->getOperand(1)) &&
1640 cast<ConstantInt>(BO->getOperand(1))->isOne() &&
1641 SE.getSCEV(BO->getOperand(0)) == MaxRHS)
1642 NewRHS = BO->getOperand(0);
1643 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(2)))
1644 if (isa<ConstantInt>(BO->getOperand(1)) &&
1645 cast<ConstantInt>(BO->getOperand(1))->isOne() &&
1646 SE.getSCEV(BO->getOperand(0)) == MaxRHS)
1647 NewRHS = BO->getOperand(0);
1648 if (!NewRHS)
1649 return Cond;
1650 } else if (SE.getSCEV(Sel->getOperand(1)) == MaxRHS)
Dan Gohman7979b722010-01-22 00:46:49 +00001651 NewRHS = Sel->getOperand(1);
Dan Gohman572645c2010-02-12 10:34:29 +00001652 else if (SE.getSCEV(Sel->getOperand(2)) == MaxRHS)
Dan Gohman7979b722010-01-22 00:46:49 +00001653 NewRHS = Sel->getOperand(2);
Dan Gohmancaf71ab2010-06-22 23:07:13 +00001654 else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(MaxRHS))
1655 NewRHS = SU->getValue();
Dan Gohman1d367982010-04-24 03:13:44 +00001656 else
Dan Gohmancaf71ab2010-06-22 23:07:13 +00001657 // Max doesn't match expected pattern.
1658 return Cond;
Dan Gohman7979b722010-01-22 00:46:49 +00001659
1660 // Determine the new comparison opcode. It may be signed or unsigned,
1661 // and the original comparison may be either equality or inequality.
Dan Gohman7979b722010-01-22 00:46:49 +00001662 if (Cond->getPredicate() == CmpInst::ICMP_EQ)
1663 Pred = CmpInst::getInversePredicate(Pred);
1664
1665 // Ok, everything looks ok to change the condition into an SLT or SGE and
1666 // delete the max calculation.
1667 ICmpInst *NewCond =
1668 new ICmpInst(Cond, Pred, Cond->getOperand(0), NewRHS, "scmp");
1669
1670 // Delete the max calculation instructions.
1671 Cond->replaceAllUsesWith(NewCond);
1672 CondUse->setUser(NewCond);
1673 Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
1674 Cond->eraseFromParent();
1675 Sel->eraseFromParent();
1676 if (Cmp->use_empty())
1677 Cmp->eraseFromParent();
1678 return NewCond;
Dan Gohmanad7321f2008-09-15 21:22:06 +00001679}
1680
Jim Grosbach56a1f802009-11-17 17:53:56 +00001681/// OptimizeLoopTermCond - Change loop terminating condition to use the
Evan Cheng586f69a2009-11-12 07:35:05 +00001682/// postinc iv when possible.
Dan Gohmanc6519f92010-05-20 20:05:31 +00001683void
Dan Gohman572645c2010-02-12 10:34:29 +00001684LSRInstance::OptimizeLoopTermCond() {
1685 SmallPtrSet<Instruction *, 4> PostIncs;
1686
Evan Cheng586f69a2009-11-12 07:35:05 +00001687 BasicBlock *LatchBlock = L->getLoopLatch();
Evan Cheng076e0852009-11-17 18:10:11 +00001688 SmallVector<BasicBlock*, 8> ExitingBlocks;
1689 L->getExitingBlocks(ExitingBlocks);
Jim Grosbach56a1f802009-11-17 17:53:56 +00001690
Evan Cheng076e0852009-11-17 18:10:11 +00001691 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
1692 BasicBlock *ExitingBlock = ExitingBlocks[i];
Evan Cheng586f69a2009-11-12 07:35:05 +00001693
Dan Gohman572645c2010-02-12 10:34:29 +00001694 // Get the terminating condition for the loop if possible. If we
Evan Cheng076e0852009-11-17 18:10:11 +00001695 // can, we want to change it to use a post-incremented version of its
1696 // induction variable, to allow coalescing the live ranges for the IV into
1697 // one register value.
Evan Cheng586f69a2009-11-12 07:35:05 +00001698
Evan Cheng076e0852009-11-17 18:10:11 +00001699 BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1700 if (!TermBr)
1701 continue;
1702 // FIXME: Overly conservative, termination condition could be an 'or' etc..
1703 if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
1704 continue;
Evan Cheng586f69a2009-11-12 07:35:05 +00001705
Evan Cheng076e0852009-11-17 18:10:11 +00001706 // Search IVUsesByStride to find Cond's IVUse if there is one.
1707 IVStrideUse *CondUse = 0;
Evan Cheng076e0852009-11-17 18:10:11 +00001708 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
Dan Gohman572645c2010-02-12 10:34:29 +00001709 if (!FindIVUserForCond(Cond, CondUse))
Evan Cheng076e0852009-11-17 18:10:11 +00001710 continue;
1711
Evan Cheng076e0852009-11-17 18:10:11 +00001712 // If the trip count is computed in terms of a max (due to ScalarEvolution
1713 // being unable to find a sufficient guard, for example), change the loop
1714 // comparison to use SLT or ULT instead of NE.
Dan Gohman572645c2010-02-12 10:34:29 +00001715 // One consequence of doing this now is that it disrupts the count-down
1716 // optimization. That's not always a bad thing though, because in such
1717 // cases it may still be worthwhile to avoid a max.
1718 Cond = OptimizeMax(Cond, CondUse);
Evan Cheng076e0852009-11-17 18:10:11 +00001719
Dan Gohman572645c2010-02-12 10:34:29 +00001720 // If this exiting block dominates the latch block, it may also use
1721 // the post-inc value if it won't be shared with other uses.
1722 // Check for dominance.
1723 if (!DT.dominates(ExitingBlock, LatchBlock))
Dan Gohman7979b722010-01-22 00:46:49 +00001724 continue;
Evan Cheng076e0852009-11-17 18:10:11 +00001725
Dan Gohman572645c2010-02-12 10:34:29 +00001726 // Conservatively avoid trying to use the post-inc value in non-latch
1727 // exits if there may be pre-inc users in intervening blocks.
Dan Gohman590bfe82010-02-14 03:21:49 +00001728 if (LatchBlock != ExitingBlock)
Dan Gohman572645c2010-02-12 10:34:29 +00001729 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
1730 // Test if the use is reachable from the exiting block. This dominator
1731 // query is a conservative approximation of reachability.
1732 if (&*UI != CondUse &&
1733 !DT.properlyDominates(UI->getUser()->getParent(), ExitingBlock)) {
1734 // Conservatively assume there may be reuse if the quotient of their
1735 // strides could be a legal scale.
Dan Gohmanc0564542010-04-19 21:48:58 +00001736 const SCEV *A = IU.getStride(*CondUse, L);
1737 const SCEV *B = IU.getStride(*UI, L);
Dan Gohman448db1c2010-04-07 22:27:08 +00001738 if (!A || !B) continue;
Dan Gohman572645c2010-02-12 10:34:29 +00001739 if (SE.getTypeSizeInBits(A->getType()) !=
1740 SE.getTypeSizeInBits(B->getType())) {
1741 if (SE.getTypeSizeInBits(A->getType()) >
1742 SE.getTypeSizeInBits(B->getType()))
1743 B = SE.getSignExtendExpr(B, A->getType());
1744 else
1745 A = SE.getSignExtendExpr(A, B->getType());
1746 }
1747 if (const SCEVConstant *D =
Dan Gohmanf09b7122010-02-19 19:35:48 +00001748 dyn_cast_or_null<SCEVConstant>(getExactSDiv(B, A, SE))) {
Dan Gohman9f383eb2010-05-20 22:25:20 +00001749 const ConstantInt *C = D->getValue();
Dan Gohman572645c2010-02-12 10:34:29 +00001750 // Stride of one or negative one can have reuse with non-addresses.
Dan Gohman9f383eb2010-05-20 22:25:20 +00001751 if (C->isOne() || C->isAllOnesValue())
Dan Gohman572645c2010-02-12 10:34:29 +00001752 goto decline_post_inc;
1753 // Avoid weird situations.
Dan Gohman9f383eb2010-05-20 22:25:20 +00001754 if (C->getValue().getMinSignedBits() >= 64 ||
1755 C->getValue().isMinSignedValue())
Dan Gohman572645c2010-02-12 10:34:29 +00001756 goto decline_post_inc;
Dan Gohman590bfe82010-02-14 03:21:49 +00001757 // Without TLI, assume that any stride might be valid, and so any
1758 // use might be shared.
1759 if (!TLI)
1760 goto decline_post_inc;
Dan Gohman572645c2010-02-12 10:34:29 +00001761 // Check for possible scaled-address reuse.
1762 const Type *AccessTy = getAccessType(UI->getUser());
1763 TargetLowering::AddrMode AM;
Dan Gohman9f383eb2010-05-20 22:25:20 +00001764 AM.Scale = C->getSExtValue();
Dan Gohman2763dfd2010-02-14 02:45:21 +00001765 if (TLI->isLegalAddressingMode(AM, AccessTy))
Dan Gohman572645c2010-02-12 10:34:29 +00001766 goto decline_post_inc;
1767 AM.Scale = -AM.Scale;
Dan Gohman2763dfd2010-02-14 02:45:21 +00001768 if (TLI->isLegalAddressingMode(AM, AccessTy))
Dan Gohman572645c2010-02-12 10:34:29 +00001769 goto decline_post_inc;
1770 }
1771 }
1772
David Greene63c94632009-12-23 22:58:38 +00001773 DEBUG(dbgs() << " Change loop exiting icmp to use postinc iv: "
Dan Gohman572645c2010-02-12 10:34:29 +00001774 << *Cond << '\n');
Evan Cheng076e0852009-11-17 18:10:11 +00001775
1776 // It's possible for the setcc instruction to be anywhere in the loop, and
1777 // possible for it to have multiple users. If it is not immediately before
1778 // the exiting block branch, move it.
Dan Gohman572645c2010-02-12 10:34:29 +00001779 if (&*++BasicBlock::iterator(Cond) != TermBr) {
1780 if (Cond->hasOneUse()) {
Evan Cheng076e0852009-11-17 18:10:11 +00001781 Cond->moveBefore(TermBr);
1782 } else {
Dan Gohman572645c2010-02-12 10:34:29 +00001783 // Clone the terminating condition and insert into the loopend.
1784 ICmpInst *OldCond = Cond;
Evan Cheng076e0852009-11-17 18:10:11 +00001785 Cond = cast<ICmpInst>(Cond->clone());
1786 Cond->setName(L->getHeader()->getName() + ".termcond");
1787 ExitingBlock->getInstList().insert(TermBr, Cond);
1788
1789 // Clone the IVUse, as the old use still exists!
Dan Gohmanc0564542010-04-19 21:48:58 +00001790 CondUse = &IU.AddUser(Cond, CondUse->getOperandValToReplace());
Dan Gohman572645c2010-02-12 10:34:29 +00001791 TermBr->replaceUsesOfWith(OldCond, Cond);
Evan Cheng076e0852009-11-17 18:10:11 +00001792 }
Evan Cheng586f69a2009-11-12 07:35:05 +00001793 }
1794
Evan Cheng076e0852009-11-17 18:10:11 +00001795 // If we get to here, we know that we can transform the setcc instruction to
1796 // use the post-incremented version of the IV, allowing us to coalesce the
1797 // live ranges for the IV correctly.
Dan Gohman448db1c2010-04-07 22:27:08 +00001798 CondUse->transformToPostInc(L);
Evan Cheng076e0852009-11-17 18:10:11 +00001799 Changed = true;
1800
Dan Gohman572645c2010-02-12 10:34:29 +00001801 PostIncs.insert(Cond);
1802 decline_post_inc:;
Dan Gohmana10756e2010-01-21 02:09:26 +00001803 }
Dan Gohman572645c2010-02-12 10:34:29 +00001804
1805 // Determine an insertion point for the loop induction variable increment. It
1806 // must dominate all the post-inc comparisons we just set up, and it must
1807 // dominate the loop latch edge.
1808 IVIncInsertPos = L->getLoopLatch()->getTerminator();
1809 for (SmallPtrSet<Instruction *, 4>::const_iterator I = PostIncs.begin(),
1810 E = PostIncs.end(); I != E; ++I) {
1811 BasicBlock *BB =
1812 DT.findNearestCommonDominator(IVIncInsertPos->getParent(),
1813 (*I)->getParent());
1814 if (BB == (*I)->getParent())
1815 IVIncInsertPos = *I;
1816 else if (BB != IVIncInsertPos->getParent())
1817 IVIncInsertPos = BB->getTerminator();
1818 }
Dan Gohmana10756e2010-01-21 02:09:26 +00001819}
1820
Dan Gohman76c315a2010-05-20 20:52:00 +00001821/// reconcileNewOffset - Determine if the given use can accomodate a fixup
1822/// at the given offset and other details. If so, update the use and
1823/// return true.
Dan Gohman572645c2010-02-12 10:34:29 +00001824bool
Dan Gohman191bd642010-09-01 01:45:53 +00001825LSRInstance::reconcileNewOffset(LSRUse &LU, int64_t NewOffset, bool HasBaseReg,
Dan Gohman572645c2010-02-12 10:34:29 +00001826 LSRUse::KindType Kind, const Type *AccessTy) {
Dan Gohman191bd642010-09-01 01:45:53 +00001827 int64_t NewMinOffset = LU.MinOffset;
1828 int64_t NewMaxOffset = LU.MaxOffset;
1829 const Type *NewAccessTy = AccessTy;
Dan Gohman7979b722010-01-22 00:46:49 +00001830
Dan Gohman572645c2010-02-12 10:34:29 +00001831 // Check for a mismatched kind. It's tempting to collapse mismatched kinds to
1832 // something conservative, however this can pessimize in the case that one of
1833 // the uses will have all its uses outside the loop, for example.
1834 if (LU.Kind != Kind)
Dan Gohman7979b722010-01-22 00:46:49 +00001835 return false;
Dan Gohman572645c2010-02-12 10:34:29 +00001836 // Conservatively assume HasBaseReg is true for now.
Dan Gohman191bd642010-09-01 01:45:53 +00001837 if (NewOffset < LU.MinOffset) {
1838 if (!isAlwaysFoldable(LU.MaxOffset - NewOffset, 0, HasBaseReg,
Dan Gohman454d26d2010-02-22 04:11:59 +00001839 Kind, AccessTy, TLI))
Dan Gohman7979b722010-01-22 00:46:49 +00001840 return false;
Dan Gohman191bd642010-09-01 01:45:53 +00001841 NewMinOffset = NewOffset;
1842 } else if (NewOffset > LU.MaxOffset) {
1843 if (!isAlwaysFoldable(NewOffset - LU.MinOffset, 0, HasBaseReg,
Dan Gohman454d26d2010-02-22 04:11:59 +00001844 Kind, AccessTy, TLI))
Dan Gohman7979b722010-01-22 00:46:49 +00001845 return false;
Dan Gohman191bd642010-09-01 01:45:53 +00001846 NewMaxOffset = NewOffset;
Dan Gohmana10756e2010-01-21 02:09:26 +00001847 }
Dan Gohman572645c2010-02-12 10:34:29 +00001848 // Check for a mismatched access type, and fall back conservatively as needed.
Dan Gohman74e5ef02010-06-19 21:30:18 +00001849 // TODO: Be less conservative when the type is similar and can use the same
1850 // addressing modes.
Dan Gohman572645c2010-02-12 10:34:29 +00001851 if (Kind == LSRUse::Address && AccessTy != LU.AccessTy)
Dan Gohman191bd642010-09-01 01:45:53 +00001852 NewAccessTy = Type::getVoidTy(AccessTy->getContext());
Dan Gohmana10756e2010-01-21 02:09:26 +00001853
Dan Gohman572645c2010-02-12 10:34:29 +00001854 // Update the use.
Dan Gohman191bd642010-09-01 01:45:53 +00001855 LU.MinOffset = NewMinOffset;
1856 LU.MaxOffset = NewMaxOffset;
1857 LU.AccessTy = NewAccessTy;
1858 if (NewOffset != LU.Offsets.back())
1859 LU.Offsets.push_back(NewOffset);
Dan Gohman8b0ade32010-01-21 22:42:49 +00001860 return true;
1861}
1862
Dan Gohman572645c2010-02-12 10:34:29 +00001863/// getUse - Return an LSRUse index and an offset value for a fixup which
1864/// needs the given expression, with the given kind and optional access type.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001865/// Either reuse an existing use or create a new one, as needed.
Dan Gohman572645c2010-02-12 10:34:29 +00001866std::pair<size_t, int64_t>
1867LSRInstance::getUse(const SCEV *&Expr,
1868 LSRUse::KindType Kind, const Type *AccessTy) {
1869 const SCEV *Copy = Expr;
1870 int64_t Offset = ExtractImmediate(Expr, SE);
Evan Cheng586f69a2009-11-12 07:35:05 +00001871
Dan Gohman572645c2010-02-12 10:34:29 +00001872 // Basic uses can't accept any offset, for example.
Dan Gohman454d26d2010-02-22 04:11:59 +00001873 if (!isAlwaysFoldable(Offset, 0, /*HasBaseReg=*/true, Kind, AccessTy, TLI)) {
Dan Gohman572645c2010-02-12 10:34:29 +00001874 Expr = Copy;
1875 Offset = 0;
1876 }
1877
1878 std::pair<UseMapTy::iterator, bool> P =
Dan Gohman1e3121c2010-06-19 21:29:59 +00001879 UseMap.insert(std::make_pair(std::make_pair(Expr, Kind), 0));
Dan Gohman572645c2010-02-12 10:34:29 +00001880 if (!P.second) {
1881 // A use already existed with this base.
1882 size_t LUIdx = P.first->second;
1883 LSRUse &LU = Uses[LUIdx];
Dan Gohman191bd642010-09-01 01:45:53 +00001884 if (reconcileNewOffset(LU, Offset, /*HasBaseReg=*/true, Kind, AccessTy))
Dan Gohman572645c2010-02-12 10:34:29 +00001885 // Reuse this use.
1886 return std::make_pair(LUIdx, Offset);
1887 }
1888
1889 // Create a new use.
1890 size_t LUIdx = Uses.size();
1891 P.first->second = LUIdx;
1892 Uses.push_back(LSRUse(Kind, AccessTy));
1893 LSRUse &LU = Uses[LUIdx];
1894
Dan Gohman191bd642010-09-01 01:45:53 +00001895 // We don't need to track redundant offsets, but we don't need to go out
1896 // of our way here to avoid them.
1897 if (LU.Offsets.empty() || Offset != LU.Offsets.back())
1898 LU.Offsets.push_back(Offset);
1899
Dan Gohman572645c2010-02-12 10:34:29 +00001900 LU.MinOffset = Offset;
1901 LU.MaxOffset = Offset;
1902 return std::make_pair(LUIdx, Offset);
1903}
1904
Dan Gohman5ce6d052010-05-20 15:17:54 +00001905/// DeleteUse - Delete the given use from the Uses list.
Dan Gohmanc6897702010-10-07 23:33:43 +00001906void LSRInstance::DeleteUse(LSRUse &LU, size_t LUIdx) {
Dan Gohman191bd642010-09-01 01:45:53 +00001907 if (&LU != &Uses.back())
Dan Gohman5ce6d052010-05-20 15:17:54 +00001908 std::swap(LU, Uses.back());
1909 Uses.pop_back();
Dan Gohmanc6897702010-10-07 23:33:43 +00001910
1911 // Update RegUses.
1912 RegUses.SwapAndDropUse(LUIdx, Uses.size());
Dan Gohman5ce6d052010-05-20 15:17:54 +00001913}
1914
Dan Gohmana2086b32010-05-19 23:43:12 +00001915/// FindUseWithFormula - Look for a use distinct from OrigLU which is has
1916/// a formula that has the same registers as the given formula.
1917LSRUse *
1918LSRInstance::FindUseWithSimilarFormula(const Formula &OrigF,
Dan Gohman191bd642010-09-01 01:45:53 +00001919 const LSRUse &OrigLU) {
1920 // Search all uses for the formula. This could be more clever.
Dan Gohmana2086b32010-05-19 23:43:12 +00001921 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
1922 LSRUse &LU = Uses[LUIdx];
Dan Gohman6a832712010-08-29 15:27:08 +00001923 // Check whether this use is close enough to OrigLU, to see whether it's
1924 // worthwhile looking through its formulae.
1925 // Ignore ICmpZero uses because they may contain formulae generated by
1926 // GenerateICmpZeroScales, in which case adding fixup offsets may
1927 // be invalid.
Dan Gohmana2086b32010-05-19 23:43:12 +00001928 if (&LU != &OrigLU &&
1929 LU.Kind != LSRUse::ICmpZero &&
1930 LU.Kind == OrigLU.Kind && OrigLU.AccessTy == LU.AccessTy &&
Dan Gohmana9db1292010-07-15 20:24:58 +00001931 LU.WidestFixupType == OrigLU.WidestFixupType &&
Dan Gohmana2086b32010-05-19 23:43:12 +00001932 LU.HasFormulaWithSameRegs(OrigF)) {
Dan Gohman6a832712010-08-29 15:27:08 +00001933 // Scan through this use's formulae.
Dan Gohman402d4352010-05-20 20:33:18 +00001934 for (SmallVectorImpl<Formula>::const_iterator I = LU.Formulae.begin(),
1935 E = LU.Formulae.end(); I != E; ++I) {
1936 const Formula &F = *I;
Dan Gohman6a832712010-08-29 15:27:08 +00001937 // Check to see if this formula has the same registers and symbols
1938 // as OrigF.
Dan Gohmana2086b32010-05-19 23:43:12 +00001939 if (F.BaseRegs == OrigF.BaseRegs &&
1940 F.ScaledReg == OrigF.ScaledReg &&
1941 F.AM.BaseGV == OrigF.AM.BaseGV &&
Dan Gohmane39a47c2010-08-29 15:30:29 +00001942 F.AM.Scale == OrigF.AM.Scale) {
Dan Gohman191bd642010-09-01 01:45:53 +00001943 if (F.AM.BaseOffs == 0)
Dan Gohmana2086b32010-05-19 23:43:12 +00001944 return &LU;
Dan Gohman6a832712010-08-29 15:27:08 +00001945 // This is the formula where all the registers and symbols matched;
1946 // there aren't going to be any others. Since we declined it, we
1947 // can skip the rest of the formulae and procede to the next LSRUse.
Dan Gohmana2086b32010-05-19 23:43:12 +00001948 break;
1949 }
1950 }
1951 }
1952 }
1953
Dan Gohman6a832712010-08-29 15:27:08 +00001954 // Nothing looked good.
Dan Gohmana2086b32010-05-19 23:43:12 +00001955 return 0;
1956}
1957
Dan Gohman572645c2010-02-12 10:34:29 +00001958void LSRInstance::CollectInterestingTypesAndFactors() {
1959 SmallSetVector<const SCEV *, 4> Strides;
1960
Dan Gohman1b7bf182010-02-19 00:05:23 +00001961 // Collect interesting types and strides.
Dan Gohman448db1c2010-04-07 22:27:08 +00001962 SmallVector<const SCEV *, 4> Worklist;
Dan Gohman572645c2010-02-12 10:34:29 +00001963 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
Dan Gohmanc0564542010-04-19 21:48:58 +00001964 const SCEV *Expr = IU.getExpr(*UI);
Dan Gohman572645c2010-02-12 10:34:29 +00001965
1966 // Collect interesting types.
Dan Gohman448db1c2010-04-07 22:27:08 +00001967 Types.insert(SE.getEffectiveSCEVType(Expr->getType()));
Dan Gohman572645c2010-02-12 10:34:29 +00001968
Dan Gohman448db1c2010-04-07 22:27:08 +00001969 // Add strides for mentioned loops.
1970 Worklist.push_back(Expr);
1971 do {
1972 const SCEV *S = Worklist.pop_back_val();
1973 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
1974 Strides.insert(AR->getStepRecurrence(SE));
1975 Worklist.push_back(AR->getStart());
1976 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
Dan Gohman403a8cd2010-06-21 19:47:52 +00001977 Worklist.append(Add->op_begin(), Add->op_end());
Dan Gohman448db1c2010-04-07 22:27:08 +00001978 }
1979 } while (!Worklist.empty());
Dan Gohman1b7bf182010-02-19 00:05:23 +00001980 }
1981
1982 // Compute interesting factors from the set of interesting strides.
1983 for (SmallSetVector<const SCEV *, 4>::const_iterator
1984 I = Strides.begin(), E = Strides.end(); I != E; ++I)
Dan Gohman572645c2010-02-12 10:34:29 +00001985 for (SmallSetVector<const SCEV *, 4>::const_iterator NewStrideIter =
Oscar Fuentesee56c422010-08-02 06:00:15 +00001986 llvm::next(I); NewStrideIter != E; ++NewStrideIter) {
Dan Gohman1b7bf182010-02-19 00:05:23 +00001987 const SCEV *OldStride = *I;
Dan Gohman572645c2010-02-12 10:34:29 +00001988 const SCEV *NewStride = *NewStrideIter;
Dan Gohman572645c2010-02-12 10:34:29 +00001989
1990 if (SE.getTypeSizeInBits(OldStride->getType()) !=
1991 SE.getTypeSizeInBits(NewStride->getType())) {
1992 if (SE.getTypeSizeInBits(OldStride->getType()) >
1993 SE.getTypeSizeInBits(NewStride->getType()))
1994 NewStride = SE.getSignExtendExpr(NewStride, OldStride->getType());
1995 else
1996 OldStride = SE.getSignExtendExpr(OldStride, NewStride->getType());
1997 }
1998 if (const SCEVConstant *Factor =
Dan Gohmanf09b7122010-02-19 19:35:48 +00001999 dyn_cast_or_null<SCEVConstant>(getExactSDiv(NewStride, OldStride,
2000 SE, true))) {
Dan Gohman572645c2010-02-12 10:34:29 +00002001 if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
2002 Factors.insert(Factor->getValue()->getValue().getSExtValue());
2003 } else if (const SCEVConstant *Factor =
Dan Gohman454d26d2010-02-22 04:11:59 +00002004 dyn_cast_or_null<SCEVConstant>(getExactSDiv(OldStride,
2005 NewStride,
Dan Gohmanf09b7122010-02-19 19:35:48 +00002006 SE, true))) {
Dan Gohman572645c2010-02-12 10:34:29 +00002007 if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
2008 Factors.insert(Factor->getValue()->getValue().getSExtValue());
2009 }
2010 }
Dan Gohman572645c2010-02-12 10:34:29 +00002011
2012 // If all uses use the same type, don't bother looking for truncation-based
2013 // reuse.
2014 if (Types.size() == 1)
2015 Types.clear();
2016
2017 DEBUG(print_factors_and_types(dbgs()));
2018}
2019
2020void LSRInstance::CollectFixupsAndInitialFormulae() {
2021 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
2022 // Record the uses.
2023 LSRFixup &LF = getNewFixup();
2024 LF.UserInst = UI->getUser();
2025 LF.OperandValToReplace = UI->getOperandValToReplace();
Dan Gohman448db1c2010-04-07 22:27:08 +00002026 LF.PostIncLoops = UI->getPostIncLoops();
Dan Gohman572645c2010-02-12 10:34:29 +00002027
2028 LSRUse::KindType Kind = LSRUse::Basic;
2029 const Type *AccessTy = 0;
2030 if (isAddressUse(LF.UserInst, LF.OperandValToReplace)) {
2031 Kind = LSRUse::Address;
2032 AccessTy = getAccessType(LF.UserInst);
2033 }
2034
Dan Gohmanc0564542010-04-19 21:48:58 +00002035 const SCEV *S = IU.getExpr(*UI);
Dan Gohman572645c2010-02-12 10:34:29 +00002036
2037 // Equality (== and !=) ICmps are special. We can rewrite (i == N) as
2038 // (N - i == 0), and this allows (N - i) to be the expression that we work
2039 // with rather than just N or i, so we can consider the register
2040 // requirements for both N and i at the same time. Limiting this code to
2041 // equality icmps is not a problem because all interesting loops use
2042 // equality icmps, thanks to IndVarSimplify.
2043 if (ICmpInst *CI = dyn_cast<ICmpInst>(LF.UserInst))
2044 if (CI->isEquality()) {
2045 // Swap the operands if needed to put the OperandValToReplace on the
2046 // left, for consistency.
2047 Value *NV = CI->getOperand(1);
2048 if (NV == LF.OperandValToReplace) {
2049 CI->setOperand(1, CI->getOperand(0));
2050 CI->setOperand(0, NV);
Dan Gohmanf182b232010-05-20 19:26:52 +00002051 NV = CI->getOperand(1);
Dan Gohman9da1bf42010-05-20 19:16:03 +00002052 Changed = true;
Dan Gohman572645c2010-02-12 10:34:29 +00002053 }
2054
2055 // x == y --> x - y == 0
2056 const SCEV *N = SE.getSCEV(NV);
Dan Gohman17ead4f2010-11-17 21:23:15 +00002057 if (SE.isLoopInvariant(N, L)) {
Dan Gohman572645c2010-02-12 10:34:29 +00002058 Kind = LSRUse::ICmpZero;
2059 S = SE.getMinusSCEV(N, S);
2060 }
2061
2062 // -1 and the negations of all interesting strides (except the negation
2063 // of -1) are now also interesting.
2064 for (size_t i = 0, e = Factors.size(); i != e; ++i)
2065 if (Factors[i] != -1)
2066 Factors.insert(-(uint64_t)Factors[i]);
2067 Factors.insert(-1);
2068 }
2069
2070 // Set up the initial formula for this use.
2071 std::pair<size_t, int64_t> P = getUse(S, Kind, AccessTy);
2072 LF.LUIdx = P.first;
2073 LF.Offset = P.second;
2074 LSRUse &LU = Uses[LF.LUIdx];
Dan Gohman448db1c2010-04-07 22:27:08 +00002075 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
Dan Gohmana9db1292010-07-15 20:24:58 +00002076 if (!LU.WidestFixupType ||
2077 SE.getTypeSizeInBits(LU.WidestFixupType) <
2078 SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
2079 LU.WidestFixupType = LF.OperandValToReplace->getType();
Dan Gohman572645c2010-02-12 10:34:29 +00002080
2081 // If this is the first use of this LSRUse, give it a formula.
2082 if (LU.Formulae.empty()) {
Dan Gohman454d26d2010-02-22 04:11:59 +00002083 InsertInitialFormula(S, LU, LF.LUIdx);
Dan Gohman572645c2010-02-12 10:34:29 +00002084 CountRegisters(LU.Formulae.back(), LF.LUIdx);
2085 }
2086 }
2087
2088 DEBUG(print_fixups(dbgs()));
2089}
2090
Dan Gohman76c315a2010-05-20 20:52:00 +00002091/// InsertInitialFormula - Insert a formula for the given expression into
2092/// the given use, separating out loop-variant portions from loop-invariant
2093/// and loop-computable portions.
Dan Gohman572645c2010-02-12 10:34:29 +00002094void
Dan Gohman454d26d2010-02-22 04:11:59 +00002095LSRInstance::InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx) {
Dan Gohman572645c2010-02-12 10:34:29 +00002096 Formula F;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00002097 F.InitialMatch(S, L, SE);
Dan Gohman572645c2010-02-12 10:34:29 +00002098 bool Inserted = InsertFormula(LU, LUIdx, F);
2099 assert(Inserted && "Initial formula already exists!"); (void)Inserted;
2100}
2101
Dan Gohman76c315a2010-05-20 20:52:00 +00002102/// InsertSupplementalFormula - Insert a simple single-register formula for
2103/// the given expression into the given use.
Dan Gohman572645c2010-02-12 10:34:29 +00002104void
2105LSRInstance::InsertSupplementalFormula(const SCEV *S,
2106 LSRUse &LU, size_t LUIdx) {
2107 Formula F;
2108 F.BaseRegs.push_back(S);
2109 F.AM.HasBaseReg = true;
2110 bool Inserted = InsertFormula(LU, LUIdx, F);
2111 assert(Inserted && "Supplemental formula already exists!"); (void)Inserted;
2112}
2113
2114/// CountRegisters - Note which registers are used by the given formula,
2115/// updating RegUses.
2116void LSRInstance::CountRegisters(const Formula &F, size_t LUIdx) {
2117 if (F.ScaledReg)
2118 RegUses.CountRegister(F.ScaledReg, LUIdx);
2119 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
2120 E = F.BaseRegs.end(); I != E; ++I)
2121 RegUses.CountRegister(*I, LUIdx);
2122}
2123
2124/// InsertFormula - If the given formula has not yet been inserted, add it to
2125/// the list, and return true. Return false otherwise.
2126bool LSRInstance::InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F) {
Dan Gohman454d26d2010-02-22 04:11:59 +00002127 if (!LU.InsertFormula(F))
Dan Gohman572645c2010-02-12 10:34:29 +00002128 return false;
2129
2130 CountRegisters(F, LUIdx);
2131 return true;
2132}
2133
2134/// CollectLoopInvariantFixupsAndFormulae - Check for other uses of
2135/// loop-invariant values which we're tracking. These other uses will pin these
2136/// values in registers, making them less profitable for elimination.
2137/// TODO: This currently misses non-constant addrec step registers.
2138/// TODO: Should this give more weight to users inside the loop?
2139void
2140LSRInstance::CollectLoopInvariantFixupsAndFormulae() {
2141 SmallVector<const SCEV *, 8> Worklist(RegUses.begin(), RegUses.end());
2142 SmallPtrSet<const SCEV *, 8> Inserted;
2143
2144 while (!Worklist.empty()) {
2145 const SCEV *S = Worklist.pop_back_val();
2146
2147 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S))
Dan Gohman403a8cd2010-06-21 19:47:52 +00002148 Worklist.append(N->op_begin(), N->op_end());
Dan Gohman572645c2010-02-12 10:34:29 +00002149 else if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
2150 Worklist.push_back(C->getOperand());
2151 else if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
2152 Worklist.push_back(D->getLHS());
2153 Worklist.push_back(D->getRHS());
2154 } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2155 if (!Inserted.insert(U)) continue;
2156 const Value *V = U->getValue();
Dan Gohmana15ec5d2010-06-04 23:16:05 +00002157 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
2158 // Look for instructions defined outside the loop.
Dan Gohman572645c2010-02-12 10:34:29 +00002159 if (L->contains(Inst)) continue;
Dan Gohmana15ec5d2010-06-04 23:16:05 +00002160 } else if (isa<UndefValue>(V))
2161 // Undef doesn't have a live range, so it doesn't matter.
2162 continue;
Gabor Greif60ad7812010-03-25 23:06:16 +00002163 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
Dan Gohman572645c2010-02-12 10:34:29 +00002164 UI != UE; ++UI) {
2165 const Instruction *UserInst = dyn_cast<Instruction>(*UI);
2166 // Ignore non-instructions.
2167 if (!UserInst)
Dan Gohman7979b722010-01-22 00:46:49 +00002168 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002169 // Ignore instructions in other functions (as can happen with
2170 // Constants).
2171 if (UserInst->getParent()->getParent() != L->getHeader()->getParent())
Dan Gohman7979b722010-01-22 00:46:49 +00002172 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002173 // Ignore instructions not dominated by the loop.
2174 const BasicBlock *UseBB = !isa<PHINode>(UserInst) ?
2175 UserInst->getParent() :
2176 cast<PHINode>(UserInst)->getIncomingBlock(
2177 PHINode::getIncomingValueNumForOperand(UI.getOperandNo()));
2178 if (!DT.dominates(L->getHeader(), UseBB))
2179 continue;
2180 // Ignore uses which are part of other SCEV expressions, to avoid
2181 // analyzing them multiple times.
Dan Gohman4a2a6832010-04-09 19:12:34 +00002182 if (SE.isSCEVable(UserInst->getType())) {
2183 const SCEV *UserS = SE.getSCEV(const_cast<Instruction *>(UserInst));
2184 // If the user is a no-op, look through to its uses.
2185 if (!isa<SCEVUnknown>(UserS))
2186 continue;
2187 if (UserS == U) {
2188 Worklist.push_back(
2189 SE.getUnknown(const_cast<Instruction *>(UserInst)));
2190 continue;
2191 }
2192 }
Dan Gohman572645c2010-02-12 10:34:29 +00002193 // Ignore icmp instructions which are already being analyzed.
2194 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) {
2195 unsigned OtherIdx = !UI.getOperandNo();
2196 Value *OtherOp = const_cast<Value *>(ICI->getOperand(OtherIdx));
Dan Gohman17ead4f2010-11-17 21:23:15 +00002197 if (SE.hasComputableLoopEvolution(SE.getSCEV(OtherOp), L))
Dan Gohman572645c2010-02-12 10:34:29 +00002198 continue;
2199 }
2200
2201 LSRFixup &LF = getNewFixup();
2202 LF.UserInst = const_cast<Instruction *>(UserInst);
2203 LF.OperandValToReplace = UI.getUse();
2204 std::pair<size_t, int64_t> P = getUse(S, LSRUse::Basic, 0);
2205 LF.LUIdx = P.first;
2206 LF.Offset = P.second;
2207 LSRUse &LU = Uses[LF.LUIdx];
Dan Gohman448db1c2010-04-07 22:27:08 +00002208 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
Dan Gohmana9db1292010-07-15 20:24:58 +00002209 if (!LU.WidestFixupType ||
2210 SE.getTypeSizeInBits(LU.WidestFixupType) <
2211 SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
2212 LU.WidestFixupType = LF.OperandValToReplace->getType();
Dan Gohman572645c2010-02-12 10:34:29 +00002213 InsertSupplementalFormula(U, LU, LF.LUIdx);
2214 CountRegisters(LU.Formulae.back(), Uses.size() - 1);
2215 break;
2216 }
2217 }
2218 }
2219}
2220
2221/// CollectSubexprs - Split S into subexpressions which can be pulled out into
2222/// separate registers. If C is non-null, multiply each subexpression by C.
2223static void CollectSubexprs(const SCEV *S, const SCEVConstant *C,
2224 SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman3e3f15b2010-06-25 22:32:18 +00002225 const Loop *L,
Dan Gohman572645c2010-02-12 10:34:29 +00002226 ScalarEvolution &SE) {
2227 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2228 // Break out add operands.
2229 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
2230 I != E; ++I)
Dan Gohman3e22b7c2010-08-16 15:50:00 +00002231 CollectSubexprs(*I, C, Ops, L, SE);
Dan Gohman572645c2010-02-12 10:34:29 +00002232 return;
2233 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
2234 // Split a non-zero base out of an addrec.
2235 if (!AR->getStart()->isZero()) {
Dan Gohmandeff6212010-05-03 22:09:21 +00002236 CollectSubexprs(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0),
Dan Gohman572645c2010-02-12 10:34:29 +00002237 AR->getStepRecurrence(SE),
Dan Gohman3e3f15b2010-06-25 22:32:18 +00002238 AR->getLoop()),
Dan Gohman3e22b7c2010-08-16 15:50:00 +00002239 C, Ops, L, SE);
2240 CollectSubexprs(AR->getStart(), C, Ops, L, SE);
Dan Gohman572645c2010-02-12 10:34:29 +00002241 return;
2242 }
2243 } else if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2244 // Break (C * (a + b + c)) into C*a + C*b + C*c.
2245 if (Mul->getNumOperands() == 2)
2246 if (const SCEVConstant *Op0 =
2247 dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
2248 CollectSubexprs(Mul->getOperand(1),
2249 C ? cast<SCEVConstant>(SE.getMulExpr(C, Op0)) : Op0,
Dan Gohman3e22b7c2010-08-16 15:50:00 +00002250 Ops, L, SE);
Dan Gohman572645c2010-02-12 10:34:29 +00002251 return;
2252 }
2253 }
2254
Dan Gohman3e22b7c2010-08-16 15:50:00 +00002255 // Otherwise use the value itself, optionally with a scale applied.
2256 Ops.push_back(C ? SE.getMulExpr(C, S) : S);
Dan Gohman572645c2010-02-12 10:34:29 +00002257}
2258
2259/// GenerateReassociations - Split out subexpressions from adds and the bases of
2260/// addrecs.
2261void LSRInstance::GenerateReassociations(LSRUse &LU, unsigned LUIdx,
2262 Formula Base,
2263 unsigned Depth) {
2264 // Arbitrarily cap recursion to protect compile time.
2265 if (Depth >= 3) return;
2266
2267 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2268 const SCEV *BaseReg = Base.BaseRegs[i];
2269
Dan Gohman3e22b7c2010-08-16 15:50:00 +00002270 SmallVector<const SCEV *, 8> AddOps;
2271 CollectSubexprs(BaseReg, 0, AddOps, L, SE);
Dan Gohman3e3f15b2010-06-25 22:32:18 +00002272
Dan Gohman572645c2010-02-12 10:34:29 +00002273 if (AddOps.size() == 1) continue;
2274
2275 for (SmallVectorImpl<const SCEV *>::const_iterator J = AddOps.begin(),
2276 JE = AddOps.end(); J != JE; ++J) {
Dan Gohman3e22b7c2010-08-16 15:50:00 +00002277
2278 // Loop-variant "unknown" values are uninteresting; we won't be able to
2279 // do anything meaningful with them.
Dan Gohman17ead4f2010-11-17 21:23:15 +00002280 if (isa<SCEVUnknown>(*J) && !SE.isLoopInvariant(*J, L))
Dan Gohman3e22b7c2010-08-16 15:50:00 +00002281 continue;
2282
Dan Gohman572645c2010-02-12 10:34:29 +00002283 // Don't pull a constant into a register if the constant could be folded
2284 // into an immediate field.
2285 if (isAlwaysFoldable(*J, LU.MinOffset, LU.MaxOffset,
2286 Base.getNumRegs() > 1,
2287 LU.Kind, LU.AccessTy, TLI, SE))
2288 continue;
2289
2290 // Collect all operands except *J.
Dan Gohman403a8cd2010-06-21 19:47:52 +00002291 SmallVector<const SCEV *, 8> InnerAddOps
Dan Gohman4eaee282010-08-04 17:43:57 +00002292 (((const SmallVector<const SCEV *, 8> &)AddOps).begin(), J);
Dan Gohman403a8cd2010-06-21 19:47:52 +00002293 InnerAddOps.append
Oscar Fuentesee56c422010-08-02 06:00:15 +00002294 (llvm::next(J), ((const SmallVector<const SCEV *, 8> &)AddOps).end());
Dan Gohman572645c2010-02-12 10:34:29 +00002295
2296 // Don't leave just a constant behind in a register if the constant could
2297 // be folded into an immediate field.
2298 if (InnerAddOps.size() == 1 &&
2299 isAlwaysFoldable(InnerAddOps[0], LU.MinOffset, LU.MaxOffset,
2300 Base.getNumRegs() > 1,
2301 LU.Kind, LU.AccessTy, TLI, SE))
2302 continue;
2303
Dan Gohmanfafb8902010-04-23 01:55:05 +00002304 const SCEV *InnerSum = SE.getAddExpr(InnerAddOps);
2305 if (InnerSum->isZero())
2306 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002307 Formula F = Base;
Dan Gohmanfafb8902010-04-23 01:55:05 +00002308 F.BaseRegs[i] = InnerSum;
Dan Gohman572645c2010-02-12 10:34:29 +00002309 F.BaseRegs.push_back(*J);
2310 if (InsertFormula(LU, LUIdx, F))
2311 // If that formula hadn't been seen before, recurse to find more like
2312 // it.
2313 GenerateReassociations(LU, LUIdx, LU.Formulae.back(), Depth+1);
2314 }
2315 }
2316}
2317
2318/// GenerateCombinations - Generate a formula consisting of all of the
2319/// loop-dominating registers added into a single register.
2320void LSRInstance::GenerateCombinations(LSRUse &LU, unsigned LUIdx,
Dan Gohman441a3892010-02-14 18:51:39 +00002321 Formula Base) {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002322 // This method is only interesting on a plurality of registers.
Dan Gohman572645c2010-02-12 10:34:29 +00002323 if (Base.BaseRegs.size() <= 1) return;
2324
2325 Formula F = Base;
2326 F.BaseRegs.clear();
2327 SmallVector<const SCEV *, 4> Ops;
2328 for (SmallVectorImpl<const SCEV *>::const_iterator
2329 I = Base.BaseRegs.begin(), E = Base.BaseRegs.end(); I != E; ++I) {
2330 const SCEV *BaseReg = *I;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00002331 if (SE.properlyDominates(BaseReg, L->getHeader()) &&
Dan Gohman17ead4f2010-11-17 21:23:15 +00002332 !SE.hasComputableLoopEvolution(BaseReg, L))
Dan Gohman572645c2010-02-12 10:34:29 +00002333 Ops.push_back(BaseReg);
2334 else
2335 F.BaseRegs.push_back(BaseReg);
2336 }
2337 if (Ops.size() > 1) {
Dan Gohmance947362010-02-14 18:50:49 +00002338 const SCEV *Sum = SE.getAddExpr(Ops);
2339 // TODO: If Sum is zero, it probably means ScalarEvolution missed an
2340 // opportunity to fold something. For now, just ignore such cases
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002341 // rather than proceed with zero in a register.
Dan Gohmance947362010-02-14 18:50:49 +00002342 if (!Sum->isZero()) {
2343 F.BaseRegs.push_back(Sum);
2344 (void)InsertFormula(LU, LUIdx, F);
2345 }
Dan Gohman572645c2010-02-12 10:34:29 +00002346 }
2347}
2348
2349/// GenerateSymbolicOffsets - Generate reuse formulae using symbolic offsets.
2350void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx,
2351 Formula Base) {
2352 // We can't add a symbolic offset if the address already contains one.
2353 if (Base.AM.BaseGV) return;
2354
2355 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2356 const SCEV *G = Base.BaseRegs[i];
2357 GlobalValue *GV = ExtractSymbol(G, SE);
2358 if (G->isZero() || !GV)
2359 continue;
2360 Formula F = Base;
2361 F.AM.BaseGV = GV;
2362 if (!isLegalUse(F.AM, LU.MinOffset, LU.MaxOffset,
2363 LU.Kind, LU.AccessTy, TLI))
2364 continue;
2365 F.BaseRegs[i] = G;
2366 (void)InsertFormula(LU, LUIdx, F);
2367 }
2368}
2369
2370/// GenerateConstantOffsets - Generate reuse formulae using symbolic offsets.
2371void LSRInstance::GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx,
2372 Formula Base) {
2373 // TODO: For now, just add the min and max offset, because it usually isn't
2374 // worthwhile looking at everything inbetween.
Dan Gohmanc88c1a42010-07-15 15:14:45 +00002375 SmallVector<int64_t, 2> Worklist;
Dan Gohman572645c2010-02-12 10:34:29 +00002376 Worklist.push_back(LU.MinOffset);
2377 if (LU.MaxOffset != LU.MinOffset)
2378 Worklist.push_back(LU.MaxOffset);
2379
2380 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2381 const SCEV *G = Base.BaseRegs[i];
2382
2383 for (SmallVectorImpl<int64_t>::const_iterator I = Worklist.begin(),
2384 E = Worklist.end(); I != E; ++I) {
2385 Formula F = Base;
2386 F.AM.BaseOffs = (uint64_t)Base.AM.BaseOffs - *I;
2387 if (isLegalUse(F.AM, LU.MinOffset - *I, LU.MaxOffset - *I,
2388 LU.Kind, LU.AccessTy, TLI)) {
Dan Gohmanc88c1a42010-07-15 15:14:45 +00002389 // Add the offset to the base register.
Dan Gohman4065f602010-08-16 15:39:27 +00002390 const SCEV *NewG = SE.getAddExpr(SE.getConstant(G->getType(), *I), G);
Dan Gohmanc88c1a42010-07-15 15:14:45 +00002391 // If it cancelled out, drop the base register, otherwise update it.
2392 if (NewG->isZero()) {
2393 std::swap(F.BaseRegs[i], F.BaseRegs.back());
2394 F.BaseRegs.pop_back();
2395 } else
2396 F.BaseRegs[i] = NewG;
Dan Gohman572645c2010-02-12 10:34:29 +00002397
2398 (void)InsertFormula(LU, LUIdx, F);
2399 }
2400 }
2401
2402 int64_t Imm = ExtractImmediate(G, SE);
2403 if (G->isZero() || Imm == 0)
2404 continue;
2405 Formula F = Base;
2406 F.AM.BaseOffs = (uint64_t)F.AM.BaseOffs + Imm;
2407 if (!isLegalUse(F.AM, LU.MinOffset, LU.MaxOffset,
2408 LU.Kind, LU.AccessTy, TLI))
2409 continue;
2410 F.BaseRegs[i] = G;
2411 (void)InsertFormula(LU, LUIdx, F);
2412 }
2413}
2414
2415/// GenerateICmpZeroScales - For ICmpZero, check to see if we can scale up
2416/// the comparison. For example, x == y -> x*c == y*c.
2417void LSRInstance::GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx,
2418 Formula Base) {
2419 if (LU.Kind != LSRUse::ICmpZero) return;
2420
2421 // Determine the integer type for the base formula.
2422 const Type *IntTy = Base.getType();
2423 if (!IntTy) return;
2424 if (SE.getTypeSizeInBits(IntTy) > 64) return;
2425
2426 // Don't do this if there is more than one offset.
2427 if (LU.MinOffset != LU.MaxOffset) return;
2428
2429 assert(!Base.AM.BaseGV && "ICmpZero use is not legal!");
2430
2431 // Check each interesting stride.
2432 for (SmallSetVector<int64_t, 8>::const_iterator
2433 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
2434 int64_t Factor = *I;
Dan Gohman572645c2010-02-12 10:34:29 +00002435
2436 // Check that the multiplication doesn't overflow.
Dan Gohman2ea09e02010-06-24 16:57:52 +00002437 if (Base.AM.BaseOffs == INT64_MIN && Factor == -1)
Dan Gohman968cb932010-02-17 00:41:53 +00002438 continue;
Dan Gohman2ea09e02010-06-24 16:57:52 +00002439 int64_t NewBaseOffs = (uint64_t)Base.AM.BaseOffs * Factor;
2440 if (NewBaseOffs / Factor != Base.AM.BaseOffs)
Dan Gohman572645c2010-02-12 10:34:29 +00002441 continue;
2442
2443 // Check that multiplying with the use offset doesn't overflow.
2444 int64_t Offset = LU.MinOffset;
Dan Gohman968cb932010-02-17 00:41:53 +00002445 if (Offset == INT64_MIN && Factor == -1)
2446 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002447 Offset = (uint64_t)Offset * Factor;
Dan Gohman378c0b32010-02-17 00:42:19 +00002448 if (Offset / Factor != LU.MinOffset)
Dan Gohman572645c2010-02-12 10:34:29 +00002449 continue;
2450
Dan Gohman2ea09e02010-06-24 16:57:52 +00002451 Formula F = Base;
2452 F.AM.BaseOffs = NewBaseOffs;
2453
Dan Gohman572645c2010-02-12 10:34:29 +00002454 // Check that this scale is legal.
2455 if (!isLegalUse(F.AM, Offset, Offset, LU.Kind, LU.AccessTy, TLI))
2456 continue;
2457
2458 // Compensate for the use having MinOffset built into it.
2459 F.AM.BaseOffs = (uint64_t)F.AM.BaseOffs + Offset - LU.MinOffset;
2460
Dan Gohmandeff6212010-05-03 22:09:21 +00002461 const SCEV *FactorS = SE.getConstant(IntTy, Factor);
Dan Gohman572645c2010-02-12 10:34:29 +00002462
2463 // Check that multiplying with each base register doesn't overflow.
2464 for (size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) {
2465 F.BaseRegs[i] = SE.getMulExpr(F.BaseRegs[i], FactorS);
Dan Gohmanf09b7122010-02-19 19:35:48 +00002466 if (getExactSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i])
Dan Gohman572645c2010-02-12 10:34:29 +00002467 goto next;
2468 }
2469
2470 // Check that multiplying with the scaled register doesn't overflow.
2471 if (F.ScaledReg) {
2472 F.ScaledReg = SE.getMulExpr(F.ScaledReg, FactorS);
Dan Gohmanf09b7122010-02-19 19:35:48 +00002473 if (getExactSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg)
Dan Gohman572645c2010-02-12 10:34:29 +00002474 continue;
2475 }
2476
2477 // If we make it here and it's legal, add it.
2478 (void)InsertFormula(LU, LUIdx, F);
2479 next:;
2480 }
2481}
2482
2483/// GenerateScales - Generate stride factor reuse formulae by making use of
2484/// scaled-offset address modes, for example.
Dan Gohmanea507f52010-05-20 19:44:23 +00002485void LSRInstance::GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base) {
Dan Gohman572645c2010-02-12 10:34:29 +00002486 // Determine the integer type for the base formula.
2487 const Type *IntTy = Base.getType();
2488 if (!IntTy) return;
2489
2490 // If this Formula already has a scaled register, we can't add another one.
2491 if (Base.AM.Scale != 0) return;
2492
2493 // Check each interesting stride.
2494 for (SmallSetVector<int64_t, 8>::const_iterator
2495 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
2496 int64_t Factor = *I;
2497
2498 Base.AM.Scale = Factor;
2499 Base.AM.HasBaseReg = Base.BaseRegs.size() > 1;
2500 // Check whether this scale is going to be legal.
2501 if (!isLegalUse(Base.AM, LU.MinOffset, LU.MaxOffset,
2502 LU.Kind, LU.AccessTy, TLI)) {
2503 // As a special-case, handle special out-of-loop Basic users specially.
2504 // TODO: Reconsider this special case.
2505 if (LU.Kind == LSRUse::Basic &&
2506 isLegalUse(Base.AM, LU.MinOffset, LU.MaxOffset,
2507 LSRUse::Special, LU.AccessTy, TLI) &&
2508 LU.AllFixupsOutsideLoop)
2509 LU.Kind = LSRUse::Special;
2510 else
2511 continue;
2512 }
2513 // For an ICmpZero, negating a solitary base register won't lead to
2514 // new solutions.
2515 if (LU.Kind == LSRUse::ICmpZero &&
2516 !Base.AM.HasBaseReg && Base.AM.BaseOffs == 0 && !Base.AM.BaseGV)
2517 continue;
2518 // For each addrec base reg, apply the scale, if possible.
2519 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
2520 if (const SCEVAddRecExpr *AR =
2521 dyn_cast<SCEVAddRecExpr>(Base.BaseRegs[i])) {
Dan Gohmandeff6212010-05-03 22:09:21 +00002522 const SCEV *FactorS = SE.getConstant(IntTy, Factor);
Dan Gohman572645c2010-02-12 10:34:29 +00002523 if (FactorS->isZero())
2524 continue;
2525 // Divide out the factor, ignoring high bits, since we'll be
2526 // scaling the value back up in the end.
Dan Gohmanf09b7122010-02-19 19:35:48 +00002527 if (const SCEV *Quotient = getExactSDiv(AR, FactorS, SE, true)) {
Dan Gohman572645c2010-02-12 10:34:29 +00002528 // TODO: This could be optimized to avoid all the copying.
2529 Formula F = Base;
2530 F.ScaledReg = Quotient;
Dan Gohman5ce6d052010-05-20 15:17:54 +00002531 F.DeleteBaseReg(F.BaseRegs[i]);
Dan Gohman572645c2010-02-12 10:34:29 +00002532 (void)InsertFormula(LU, LUIdx, F);
2533 }
2534 }
2535 }
2536}
2537
2538/// GenerateTruncates - Generate reuse formulae from different IV types.
Dan Gohmanea507f52010-05-20 19:44:23 +00002539void LSRInstance::GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base) {
Dan Gohman572645c2010-02-12 10:34:29 +00002540 // This requires TargetLowering to tell us which truncates are free.
2541 if (!TLI) return;
2542
2543 // Don't bother truncating symbolic values.
2544 if (Base.AM.BaseGV) return;
2545
2546 // Determine the integer type for the base formula.
2547 const Type *DstTy = Base.getType();
2548 if (!DstTy) return;
2549 DstTy = SE.getEffectiveSCEVType(DstTy);
2550
2551 for (SmallSetVector<const Type *, 4>::const_iterator
2552 I = Types.begin(), E = Types.end(); I != E; ++I) {
2553 const Type *SrcTy = *I;
2554 if (SrcTy != DstTy && TLI->isTruncateFree(SrcTy, DstTy)) {
2555 Formula F = Base;
2556
2557 if (F.ScaledReg) F.ScaledReg = SE.getAnyExtendExpr(F.ScaledReg, *I);
2558 for (SmallVectorImpl<const SCEV *>::iterator J = F.BaseRegs.begin(),
2559 JE = F.BaseRegs.end(); J != JE; ++J)
2560 *J = SE.getAnyExtendExpr(*J, SrcTy);
2561
2562 // TODO: This assumes we've done basic processing on all uses and
2563 // have an idea what the register usage is.
2564 if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses))
2565 continue;
2566
2567 (void)InsertFormula(LU, LUIdx, F);
2568 }
2569 }
2570}
2571
2572namespace {
2573
Dan Gohman6020d852010-02-14 18:51:20 +00002574/// WorkItem - Helper class for GenerateCrossUseConstantOffsets. It's used to
Dan Gohman572645c2010-02-12 10:34:29 +00002575/// defer modifications so that the search phase doesn't have to worry about
2576/// the data structures moving underneath it.
2577struct WorkItem {
2578 size_t LUIdx;
2579 int64_t Imm;
2580 const SCEV *OrigReg;
2581
2582 WorkItem(size_t LI, int64_t I, const SCEV *R)
2583 : LUIdx(LI), Imm(I), OrigReg(R) {}
2584
2585 void print(raw_ostream &OS) const;
2586 void dump() const;
2587};
2588
2589}
2590
2591void WorkItem::print(raw_ostream &OS) const {
2592 OS << "in formulae referencing " << *OrigReg << " in use " << LUIdx
2593 << " , add offset " << Imm;
2594}
2595
2596void WorkItem::dump() const {
2597 print(errs()); errs() << '\n';
2598}
2599
2600/// GenerateCrossUseConstantOffsets - Look for registers which are a constant
2601/// distance apart and try to form reuse opportunities between them.
2602void LSRInstance::GenerateCrossUseConstantOffsets() {
2603 // Group the registers by their value without any added constant offset.
2604 typedef std::map<int64_t, const SCEV *> ImmMapTy;
2605 typedef DenseMap<const SCEV *, ImmMapTy> RegMapTy;
2606 RegMapTy Map;
2607 DenseMap<const SCEV *, SmallBitVector> UsedByIndicesMap;
2608 SmallVector<const SCEV *, 8> Sequence;
2609 for (RegUseTracker::const_iterator I = RegUses.begin(), E = RegUses.end();
2610 I != E; ++I) {
2611 const SCEV *Reg = *I;
2612 int64_t Imm = ExtractImmediate(Reg, SE);
2613 std::pair<RegMapTy::iterator, bool> Pair =
2614 Map.insert(std::make_pair(Reg, ImmMapTy()));
2615 if (Pair.second)
2616 Sequence.push_back(Reg);
2617 Pair.first->second.insert(std::make_pair(Imm, *I));
2618 UsedByIndicesMap[Reg] |= RegUses.getUsedByIndices(*I);
2619 }
2620
2621 // Now examine each set of registers with the same base value. Build up
2622 // a list of work to do and do the work in a separate step so that we're
2623 // not adding formulae and register counts while we're searching.
Dan Gohman191bd642010-09-01 01:45:53 +00002624 SmallVector<WorkItem, 32> WorkItems;
2625 SmallSet<std::pair<size_t, int64_t>, 32> UniqueItems;
Dan Gohman572645c2010-02-12 10:34:29 +00002626 for (SmallVectorImpl<const SCEV *>::const_iterator I = Sequence.begin(),
2627 E = Sequence.end(); I != E; ++I) {
2628 const SCEV *Reg = *I;
2629 const ImmMapTy &Imms = Map.find(Reg)->second;
2630
Dan Gohmancd045c02010-02-12 19:20:37 +00002631 // It's not worthwhile looking for reuse if there's only one offset.
2632 if (Imms.size() == 1)
2633 continue;
2634
Dan Gohman572645c2010-02-12 10:34:29 +00002635 DEBUG(dbgs() << "Generating cross-use offsets for " << *Reg << ':';
2636 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
2637 J != JE; ++J)
2638 dbgs() << ' ' << J->first;
2639 dbgs() << '\n');
2640
2641 // Examine each offset.
2642 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
2643 J != JE; ++J) {
2644 const SCEV *OrigReg = J->second;
2645
2646 int64_t JImm = J->first;
2647 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg);
2648
2649 if (!isa<SCEVConstant>(OrigReg) &&
2650 UsedByIndicesMap[Reg].count() == 1) {
2651 DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg << '\n');
2652 continue;
2653 }
2654
2655 // Conservatively examine offsets between this orig reg a few selected
2656 // other orig regs.
2657 ImmMapTy::const_iterator OtherImms[] = {
2658 Imms.begin(), prior(Imms.end()),
2659 Imms.upper_bound((Imms.begin()->first + prior(Imms.end())->first) / 2)
2660 };
2661 for (size_t i = 0, e = array_lengthof(OtherImms); i != e; ++i) {
2662 ImmMapTy::const_iterator M = OtherImms[i];
Dan Gohmancd045c02010-02-12 19:20:37 +00002663 if (M == J || M == JE) continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002664
2665 // Compute the difference between the two.
2666 int64_t Imm = (uint64_t)JImm - M->first;
2667 for (int LUIdx = UsedByIndices.find_first(); LUIdx != -1;
Dan Gohman191bd642010-09-01 01:45:53 +00002668 LUIdx = UsedByIndices.find_next(LUIdx))
Dan Gohman572645c2010-02-12 10:34:29 +00002669 // Make a memo of this use, offset, and register tuple.
Dan Gohman191bd642010-09-01 01:45:53 +00002670 if (UniqueItems.insert(std::make_pair(LUIdx, Imm)))
2671 WorkItems.push_back(WorkItem(LUIdx, Imm, OrigReg));
Evan Cheng586f69a2009-11-12 07:35:05 +00002672 }
2673 }
2674 }
2675
Dan Gohman572645c2010-02-12 10:34:29 +00002676 Map.clear();
2677 Sequence.clear();
2678 UsedByIndicesMap.clear();
Dan Gohman191bd642010-09-01 01:45:53 +00002679 UniqueItems.clear();
Dan Gohman572645c2010-02-12 10:34:29 +00002680
2681 // Now iterate through the worklist and add new formulae.
2682 for (SmallVectorImpl<WorkItem>::const_iterator I = WorkItems.begin(),
2683 E = WorkItems.end(); I != E; ++I) {
2684 const WorkItem &WI = *I;
2685 size_t LUIdx = WI.LUIdx;
2686 LSRUse &LU = Uses[LUIdx];
2687 int64_t Imm = WI.Imm;
2688 const SCEV *OrigReg = WI.OrigReg;
2689
2690 const Type *IntTy = SE.getEffectiveSCEVType(OrigReg->getType());
2691 const SCEV *NegImmS = SE.getSCEV(ConstantInt::get(IntTy, -(uint64_t)Imm));
2692 unsigned BitWidth = SE.getTypeSizeInBits(IntTy);
2693
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002694 // TODO: Use a more targeted data structure.
Dan Gohman572645c2010-02-12 10:34:29 +00002695 for (size_t L = 0, LE = LU.Formulae.size(); L != LE; ++L) {
Dan Gohman9f383eb2010-05-20 22:25:20 +00002696 const Formula &F = LU.Formulae[L];
Dan Gohman572645c2010-02-12 10:34:29 +00002697 // Use the immediate in the scaled register.
2698 if (F.ScaledReg == OrigReg) {
2699 int64_t Offs = (uint64_t)F.AM.BaseOffs +
2700 Imm * (uint64_t)F.AM.Scale;
2701 // Don't create 50 + reg(-50).
2702 if (F.referencesReg(SE.getSCEV(
2703 ConstantInt::get(IntTy, -(uint64_t)Offs))))
2704 continue;
2705 Formula NewF = F;
2706 NewF.AM.BaseOffs = Offs;
2707 if (!isLegalUse(NewF.AM, LU.MinOffset, LU.MaxOffset,
2708 LU.Kind, LU.AccessTy, TLI))
2709 continue;
2710 NewF.ScaledReg = SE.getAddExpr(NegImmS, NewF.ScaledReg);
2711
2712 // If the new scale is a constant in a register, and adding the constant
2713 // value to the immediate would produce a value closer to zero than the
2714 // immediate itself, then the formula isn't worthwhile.
2715 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewF.ScaledReg))
2716 if (C->getValue()->getValue().isNegative() !=
2717 (NewF.AM.BaseOffs < 0) &&
2718 (C->getValue()->getValue().abs() * APInt(BitWidth, F.AM.Scale))
Dan Gohmane0567812010-04-08 23:03:40 +00002719 .ule(abs64(NewF.AM.BaseOffs)))
Dan Gohman572645c2010-02-12 10:34:29 +00002720 continue;
2721
2722 // OK, looks good.
2723 (void)InsertFormula(LU, LUIdx, NewF);
2724 } else {
2725 // Use the immediate in a base register.
2726 for (size_t N = 0, NE = F.BaseRegs.size(); N != NE; ++N) {
2727 const SCEV *BaseReg = F.BaseRegs[N];
2728 if (BaseReg != OrigReg)
2729 continue;
2730 Formula NewF = F;
2731 NewF.AM.BaseOffs = (uint64_t)NewF.AM.BaseOffs + Imm;
2732 if (!isLegalUse(NewF.AM, LU.MinOffset, LU.MaxOffset,
2733 LU.Kind, LU.AccessTy, TLI))
2734 continue;
2735 NewF.BaseRegs[N] = SE.getAddExpr(NegImmS, BaseReg);
2736
2737 // If the new formula has a constant in a register, and adding the
2738 // constant value to the immediate would produce a value closer to
2739 // zero than the immediate itself, then the formula isn't worthwhile.
2740 for (SmallVectorImpl<const SCEV *>::const_iterator
2741 J = NewF.BaseRegs.begin(), JE = NewF.BaseRegs.end();
2742 J != JE; ++J)
2743 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*J))
Dan Gohman360026f2010-05-18 23:48:08 +00002744 if ((C->getValue()->getValue() + NewF.AM.BaseOffs).abs().slt(
2745 abs64(NewF.AM.BaseOffs)) &&
2746 (C->getValue()->getValue() +
2747 NewF.AM.BaseOffs).countTrailingZeros() >=
2748 CountTrailingZeros_64(NewF.AM.BaseOffs))
Dan Gohman572645c2010-02-12 10:34:29 +00002749 goto skip_formula;
2750
2751 // Ok, looks good.
2752 (void)InsertFormula(LU, LUIdx, NewF);
2753 break;
2754 skip_formula:;
2755 }
2756 }
2757 }
2758 }
Dale Johannesenc1acc3f2009-05-11 17:15:42 +00002759}
2760
Dan Gohman572645c2010-02-12 10:34:29 +00002761/// GenerateAllReuseFormulae - Generate formulae for each use.
2762void
2763LSRInstance::GenerateAllReuseFormulae() {
Dan Gohmanc2385a02010-02-16 01:42:53 +00002764 // This is split into multiple loops so that hasRegsUsedByUsesOtherThan
Dan Gohman572645c2010-02-12 10:34:29 +00002765 // queries are more precise.
2766 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2767 LSRUse &LU = Uses[LUIdx];
2768 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2769 GenerateReassociations(LU, LUIdx, LU.Formulae[i]);
2770 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2771 GenerateCombinations(LU, LUIdx, LU.Formulae[i]);
2772 }
2773 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2774 LSRUse &LU = Uses[LUIdx];
2775 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2776 GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]);
2777 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2778 GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]);
2779 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2780 GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]);
2781 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2782 GenerateScales(LU, LUIdx, LU.Formulae[i]);
Dan Gohmanc2385a02010-02-16 01:42:53 +00002783 }
2784 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2785 LSRUse &LU = Uses[LUIdx];
Dan Gohman572645c2010-02-12 10:34:29 +00002786 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2787 GenerateTruncates(LU, LUIdx, LU.Formulae[i]);
2788 }
2789
2790 GenerateCrossUseConstantOffsets();
Dan Gohman3902f9f2010-08-29 15:21:38 +00002791
2792 DEBUG(dbgs() << "\n"
2793 "After generating reuse formulae:\n";
2794 print_uses(dbgs()));
Dan Gohman572645c2010-02-12 10:34:29 +00002795}
2796
Dan Gohmanf63d70f2010-10-07 23:43:09 +00002797/// If there are multiple formulae with the same set of registers used
Dan Gohman572645c2010-02-12 10:34:29 +00002798/// by other uses, pick the best one and delete the others.
2799void LSRInstance::FilterOutUndesirableDedicatedRegisters() {
Dan Gohmanfc7744b2010-10-07 23:52:18 +00002800 DenseSet<const SCEV *> VisitedRegs;
2801 SmallPtrSet<const SCEV *, 16> Regs;
Dan Gohman572645c2010-02-12 10:34:29 +00002802#ifndef NDEBUG
Dan Gohmanc6519f92010-05-20 20:05:31 +00002803 bool ChangedFormulae = false;
Dan Gohman572645c2010-02-12 10:34:29 +00002804#endif
2805
2806 // Collect the best formula for each unique set of shared registers. This
2807 // is reset for each use.
2808 typedef DenseMap<SmallVector<const SCEV *, 2>, size_t, UniquifierDenseMapInfo>
2809 BestFormulaeTy;
2810 BestFormulaeTy BestFormulae;
2811
2812 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2813 LSRUse &LU = Uses[LUIdx];
Dan Gohmanea507f52010-05-20 19:44:23 +00002814 DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs()); dbgs() << '\n');
Dan Gohman572645c2010-02-12 10:34:29 +00002815
Dan Gohmanb2df4332010-05-18 23:42:37 +00002816 bool Any = false;
Dan Gohman572645c2010-02-12 10:34:29 +00002817 for (size_t FIdx = 0, NumForms = LU.Formulae.size();
2818 FIdx != NumForms; ++FIdx) {
2819 Formula &F = LU.Formulae[FIdx];
2820
2821 SmallVector<const SCEV *, 2> Key;
2822 for (SmallVectorImpl<const SCEV *>::const_iterator J = F.BaseRegs.begin(),
2823 JE = F.BaseRegs.end(); J != JE; ++J) {
2824 const SCEV *Reg = *J;
2825 if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx))
2826 Key.push_back(Reg);
2827 }
2828 if (F.ScaledReg &&
2829 RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx))
2830 Key.push_back(F.ScaledReg);
2831 // Unstable sort by host order ok, because this is only used for
2832 // uniquifying.
2833 std::sort(Key.begin(), Key.end());
2834
2835 std::pair<BestFormulaeTy::const_iterator, bool> P =
2836 BestFormulae.insert(std::make_pair(Key, FIdx));
2837 if (!P.second) {
2838 Formula &Best = LU.Formulae[P.first->second];
Dan Gohmanfc7744b2010-10-07 23:52:18 +00002839
2840 Cost CostF;
2841 CostF.RateFormula(F, Regs, VisitedRegs, L, LU.Offsets, SE, DT);
2842 Regs.clear();
2843 Cost CostBest;
2844 CostBest.RateFormula(Best, Regs, VisitedRegs, L, LU.Offsets, SE, DT);
2845 Regs.clear();
2846 if (CostF < CostBest)
Dan Gohman572645c2010-02-12 10:34:29 +00002847 std::swap(F, Best);
Dan Gohman6458ff92010-05-18 22:37:37 +00002848 DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs());
Dan Gohman572645c2010-02-12 10:34:29 +00002849 dbgs() << "\n"
Dan Gohman6458ff92010-05-18 22:37:37 +00002850 " in favor of formula "; Best.print(dbgs());
Dan Gohman572645c2010-02-12 10:34:29 +00002851 dbgs() << '\n');
2852#ifndef NDEBUG
Dan Gohmanc6519f92010-05-20 20:05:31 +00002853 ChangedFormulae = true;
Dan Gohman572645c2010-02-12 10:34:29 +00002854#endif
Dan Gohmand69d6282010-05-18 22:39:15 +00002855 LU.DeleteFormula(F);
Dan Gohman572645c2010-02-12 10:34:29 +00002856 --FIdx;
2857 --NumForms;
Dan Gohmanb2df4332010-05-18 23:42:37 +00002858 Any = true;
Dan Gohman572645c2010-02-12 10:34:29 +00002859 continue;
2860 }
Dan Gohman59dc6032010-05-07 23:36:59 +00002861 }
2862
Dan Gohman57aaa0b2010-05-18 23:55:57 +00002863 // Now that we've filtered out some formulae, recompute the Regs set.
Dan Gohmanb2df4332010-05-18 23:42:37 +00002864 if (Any)
2865 LU.RecomputeRegs(LUIdx, RegUses);
Dan Gohman59dc6032010-05-07 23:36:59 +00002866
2867 // Reset this to prepare for the next use.
Dan Gohman572645c2010-02-12 10:34:29 +00002868 BestFormulae.clear();
2869 }
2870
Dan Gohmanc6519f92010-05-20 20:05:31 +00002871 DEBUG(if (ChangedFormulae) {
Dan Gohman9214b822010-02-13 02:06:02 +00002872 dbgs() << "\n"
2873 "After filtering out undesirable candidates:\n";
Dan Gohman572645c2010-02-12 10:34:29 +00002874 print_uses(dbgs());
2875 });
2876}
2877
Dan Gohmand079c302010-05-18 22:51:59 +00002878// This is a rough guess that seems to work fairly well.
2879static const size_t ComplexityLimit = UINT16_MAX;
2880
2881/// EstimateSearchSpaceComplexity - Estimate the worst-case number of
2882/// solutions the solver might have to consider. It almost never considers
2883/// this many solutions because it prune the search space, but the pruning
2884/// isn't always sufficient.
2885size_t LSRInstance::EstimateSearchSpaceComplexity() const {
Dan Gohman0d6715a2010-10-07 23:37:58 +00002886 size_t Power = 1;
Dan Gohmand079c302010-05-18 22:51:59 +00002887 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
2888 E = Uses.end(); I != E; ++I) {
2889 size_t FSize = I->Formulae.size();
2890 if (FSize >= ComplexityLimit) {
2891 Power = ComplexityLimit;
2892 break;
2893 }
2894 Power *= FSize;
2895 if (Power >= ComplexityLimit)
2896 break;
2897 }
2898 return Power;
2899}
2900
Dan Gohman4aa5c2e2010-08-29 16:09:42 +00002901/// NarrowSearchSpaceByDetectingSupersets - When one formula uses a superset
2902/// of the registers of another formula, it won't help reduce register
2903/// pressure (though it may not necessarily hurt register pressure); remove
2904/// it to simplify the system.
2905void LSRInstance::NarrowSearchSpaceByDetectingSupersets() {
Dan Gohmana2086b32010-05-19 23:43:12 +00002906 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
2907 DEBUG(dbgs() << "The search space is too complex.\n");
2908
2909 DEBUG(dbgs() << "Narrowing the search space by eliminating formulae "
2910 "which use a superset of registers used by other "
2911 "formulae.\n");
2912
2913 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2914 LSRUse &LU = Uses[LUIdx];
2915 bool Any = false;
2916 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
2917 Formula &F = LU.Formulae[i];
Dan Gohmanf7ff37d2010-05-20 20:00:41 +00002918 // Look for a formula with a constant or GV in a register. If the use
2919 // also has a formula with that same value in an immediate field,
2920 // delete the one that uses a register.
Dan Gohmana2086b32010-05-19 23:43:12 +00002921 for (SmallVectorImpl<const SCEV *>::const_iterator
2922 I = F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I) {
2923 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*I)) {
2924 Formula NewF = F;
2925 NewF.AM.BaseOffs += C->getValue()->getSExtValue();
2926 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
2927 (I - F.BaseRegs.begin()));
2928 if (LU.HasFormulaWithSameRegs(NewF)) {
2929 DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
2930 LU.DeleteFormula(F);
2931 --i;
2932 --e;
2933 Any = true;
2934 break;
2935 }
2936 } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(*I)) {
2937 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue()))
2938 if (!F.AM.BaseGV) {
2939 Formula NewF = F;
2940 NewF.AM.BaseGV = GV;
2941 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
2942 (I - F.BaseRegs.begin()));
2943 if (LU.HasFormulaWithSameRegs(NewF)) {
2944 DEBUG(dbgs() << " Deleting "; F.print(dbgs());
2945 dbgs() << '\n');
2946 LU.DeleteFormula(F);
2947 --i;
2948 --e;
2949 Any = true;
2950 break;
2951 }
2952 }
2953 }
2954 }
2955 }
2956 if (Any)
2957 LU.RecomputeRegs(LUIdx, RegUses);
2958 }
2959
2960 DEBUG(dbgs() << "After pre-selection:\n";
2961 print_uses(dbgs()));
2962 }
Dan Gohman4aa5c2e2010-08-29 16:09:42 +00002963}
Dan Gohmana2086b32010-05-19 23:43:12 +00002964
Dan Gohman4aa5c2e2010-08-29 16:09:42 +00002965/// NarrowSearchSpaceByCollapsingUnrolledCode - When there are many registers
2966/// for expressions like A, A+1, A+2, etc., allocate a single register for
2967/// them.
2968void LSRInstance::NarrowSearchSpaceByCollapsingUnrolledCode() {
Dan Gohmana2086b32010-05-19 23:43:12 +00002969 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
2970 DEBUG(dbgs() << "The search space is too complex.\n");
2971
2972 DEBUG(dbgs() << "Narrowing the search space by assuming that uses "
2973 "separated by a constant offset will use the same "
2974 "registers.\n");
2975
Dan Gohmanf7ff37d2010-05-20 20:00:41 +00002976 // This is especially useful for unrolled loops.
2977
Dan Gohmana2086b32010-05-19 23:43:12 +00002978 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2979 LSRUse &LU = Uses[LUIdx];
Dan Gohman402d4352010-05-20 20:33:18 +00002980 for (SmallVectorImpl<Formula>::const_iterator I = LU.Formulae.begin(),
2981 E = LU.Formulae.end(); I != E; ++I) {
2982 const Formula &F = *I;
Dan Gohmana2086b32010-05-19 23:43:12 +00002983 if (F.AM.BaseOffs != 0 && F.AM.Scale == 0) {
Dan Gohman191bd642010-09-01 01:45:53 +00002984 if (LSRUse *LUThatHas = FindUseWithSimilarFormula(F, LU)) {
2985 if (reconcileNewOffset(*LUThatHas, F.AM.BaseOffs,
Dan Gohmana2086b32010-05-19 23:43:12 +00002986 /*HasBaseReg=*/false,
2987 LU.Kind, LU.AccessTy)) {
2988 DEBUG(dbgs() << " Deleting use "; LU.print(dbgs());
2989 dbgs() << '\n');
2990
2991 LUThatHas->AllFixupsOutsideLoop &= LU.AllFixupsOutsideLoop;
2992
Dan Gohman191bd642010-09-01 01:45:53 +00002993 // Update the relocs to reference the new use.
2994 for (SmallVectorImpl<LSRFixup>::iterator I = Fixups.begin(),
2995 E = Fixups.end(); I != E; ++I) {
2996 LSRFixup &Fixup = *I;
2997 if (Fixup.LUIdx == LUIdx) {
2998 Fixup.LUIdx = LUThatHas - &Uses.front();
2999 Fixup.Offset += F.AM.BaseOffs;
Dan Gohmandd3db0e2010-10-07 23:36:45 +00003000 // Add the new offset to LUThatHas' offset list.
3001 if (LUThatHas->Offsets.back() != Fixup.Offset) {
3002 LUThatHas->Offsets.push_back(Fixup.Offset);
3003 if (Fixup.Offset > LUThatHas->MaxOffset)
3004 LUThatHas->MaxOffset = Fixup.Offset;
3005 if (Fixup.Offset < LUThatHas->MinOffset)
3006 LUThatHas->MinOffset = Fixup.Offset;
3007 }
Dan Gohman191bd642010-09-01 01:45:53 +00003008 DEBUG(dbgs() << "New fixup has offset "
3009 << Fixup.Offset << '\n');
3010 }
3011 if (Fixup.LUIdx == NumUses-1)
3012 Fixup.LUIdx = LUIdx;
3013 }
3014
Dan Gohmanc2921ea2010-10-08 19:33:26 +00003015 // Delete formulae from the new use which are no longer legal.
3016 bool Any = false;
3017 for (size_t i = 0, e = LUThatHas->Formulae.size(); i != e; ++i) {
3018 Formula &F = LUThatHas->Formulae[i];
3019 if (!isLegalUse(F.AM,
3020 LUThatHas->MinOffset, LUThatHas->MaxOffset,
3021 LUThatHas->Kind, LUThatHas->AccessTy, TLI)) {
3022 DEBUG(dbgs() << " Deleting "; F.print(dbgs());
3023 dbgs() << '\n');
3024 LUThatHas->DeleteFormula(F);
3025 --i;
3026 --e;
3027 Any = true;
3028 }
3029 }
3030 if (Any)
3031 LUThatHas->RecomputeRegs(LUThatHas - &Uses.front(), RegUses);
3032
Dan Gohmana2086b32010-05-19 23:43:12 +00003033 // Delete the old use.
Dan Gohmanc6897702010-10-07 23:33:43 +00003034 DeleteUse(LU, LUIdx);
Dan Gohmana2086b32010-05-19 23:43:12 +00003035 --LUIdx;
3036 --NumUses;
3037 break;
3038 }
3039 }
3040 }
3041 }
3042 }
3043
3044 DEBUG(dbgs() << "After pre-selection:\n";
3045 print_uses(dbgs()));
3046 }
Dan Gohman4aa5c2e2010-08-29 16:09:42 +00003047}
Dan Gohmana2086b32010-05-19 23:43:12 +00003048
Dan Gohman4f7e18d2010-08-29 16:39:22 +00003049/// NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters - Call
3050/// FilterOutUndesirableDedicatedRegisters again, if necessary, now that
3051/// we've done more filtering, as it may be able to find more formulae to
3052/// eliminate.
3053void LSRInstance::NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters(){
3054 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
3055 DEBUG(dbgs() << "The search space is too complex.\n");
3056
3057 DEBUG(dbgs() << "Narrowing the search space by re-filtering out "
3058 "undesirable dedicated registers.\n");
3059
3060 FilterOutUndesirableDedicatedRegisters();
3061
3062 DEBUG(dbgs() << "After pre-selection:\n";
3063 print_uses(dbgs()));
3064 }
3065}
3066
Dan Gohman4aa5c2e2010-08-29 16:09:42 +00003067/// NarrowSearchSpaceByPickingWinnerRegs - Pick a register which seems likely
3068/// to be profitable, and then in any use which has any reference to that
3069/// register, delete all formulae which do not reference that register.
3070void LSRInstance::NarrowSearchSpaceByPickingWinnerRegs() {
Dan Gohman76c315a2010-05-20 20:52:00 +00003071 // With all other options exhausted, loop until the system is simple
3072 // enough to handle.
Dan Gohman572645c2010-02-12 10:34:29 +00003073 SmallPtrSet<const SCEV *, 4> Taken;
Dan Gohmand079c302010-05-18 22:51:59 +00003074 while (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
Dan Gohman572645c2010-02-12 10:34:29 +00003075 // Ok, we have too many of formulae on our hands to conveniently handle.
3076 // Use a rough heuristic to thin out the list.
Dan Gohman0da751b2010-05-18 22:41:32 +00003077 DEBUG(dbgs() << "The search space is too complex.\n");
Dan Gohman572645c2010-02-12 10:34:29 +00003078
3079 // Pick the register which is used by the most LSRUses, which is likely
3080 // to be a good reuse register candidate.
3081 const SCEV *Best = 0;
3082 unsigned BestNum = 0;
3083 for (RegUseTracker::const_iterator I = RegUses.begin(), E = RegUses.end();
3084 I != E; ++I) {
3085 const SCEV *Reg = *I;
3086 if (Taken.count(Reg))
3087 continue;
3088 if (!Best)
3089 Best = Reg;
3090 else {
3091 unsigned Count = RegUses.getUsedByIndices(Reg).count();
3092 if (Count > BestNum) {
3093 Best = Reg;
3094 BestNum = Count;
3095 }
3096 }
3097 }
3098
3099 DEBUG(dbgs() << "Narrowing the search space by assuming " << *Best
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003100 << " will yield profitable reuse.\n");
Dan Gohman572645c2010-02-12 10:34:29 +00003101 Taken.insert(Best);
3102
3103 // In any use with formulae which references this register, delete formulae
3104 // which don't reference it.
Dan Gohmanb2df4332010-05-18 23:42:37 +00003105 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3106 LSRUse &LU = Uses[LUIdx];
Dan Gohman572645c2010-02-12 10:34:29 +00003107 if (!LU.Regs.count(Best)) continue;
3108
Dan Gohmanb2df4332010-05-18 23:42:37 +00003109 bool Any = false;
Dan Gohman572645c2010-02-12 10:34:29 +00003110 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
3111 Formula &F = LU.Formulae[i];
3112 if (!F.referencesReg(Best)) {
3113 DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
Dan Gohmand69d6282010-05-18 22:39:15 +00003114 LU.DeleteFormula(F);
Dan Gohman572645c2010-02-12 10:34:29 +00003115 --e;
3116 --i;
Dan Gohmanb2df4332010-05-18 23:42:37 +00003117 Any = true;
Dan Gohman59dc6032010-05-07 23:36:59 +00003118 assert(e != 0 && "Use has no formulae left! Is Regs inconsistent?");
Dan Gohman572645c2010-02-12 10:34:29 +00003119 continue;
3120 }
Dan Gohman572645c2010-02-12 10:34:29 +00003121 }
Dan Gohmanb2df4332010-05-18 23:42:37 +00003122
3123 if (Any)
3124 LU.RecomputeRegs(LUIdx, RegUses);
Dan Gohman572645c2010-02-12 10:34:29 +00003125 }
3126
3127 DEBUG(dbgs() << "After pre-selection:\n";
3128 print_uses(dbgs()));
3129 }
3130}
3131
Dan Gohman4aa5c2e2010-08-29 16:09:42 +00003132/// NarrowSearchSpaceUsingHeuristics - If there are an extraordinary number of
3133/// formulae to choose from, use some rough heuristics to prune down the number
3134/// of formulae. This keeps the main solver from taking an extraordinary amount
3135/// of time in some worst-case scenarios.
3136void LSRInstance::NarrowSearchSpaceUsingHeuristics() {
3137 NarrowSearchSpaceByDetectingSupersets();
3138 NarrowSearchSpaceByCollapsingUnrolledCode();
Dan Gohman4f7e18d2010-08-29 16:39:22 +00003139 NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
Dan Gohman4aa5c2e2010-08-29 16:09:42 +00003140 NarrowSearchSpaceByPickingWinnerRegs();
3141}
3142
Dan Gohman572645c2010-02-12 10:34:29 +00003143/// SolveRecurse - This is the recursive solver.
3144void LSRInstance::SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
3145 Cost &SolutionCost,
3146 SmallVectorImpl<const Formula *> &Workspace,
3147 const Cost &CurCost,
3148 const SmallPtrSet<const SCEV *, 16> &CurRegs,
3149 DenseSet<const SCEV *> &VisitedRegs) const {
3150 // Some ideas:
3151 // - prune more:
3152 // - use more aggressive filtering
3153 // - sort the formula so that the most profitable solutions are found first
3154 // - sort the uses too
3155 // - search faster:
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003156 // - don't compute a cost, and then compare. compare while computing a cost
Dan Gohman572645c2010-02-12 10:34:29 +00003157 // and bail early.
3158 // - track register sets with SmallBitVector
3159
3160 const LSRUse &LU = Uses[Workspace.size()];
3161
3162 // If this use references any register that's already a part of the
3163 // in-progress solution, consider it a requirement that a formula must
3164 // reference that register in order to be considered. This prunes out
3165 // unprofitable searching.
3166 SmallSetVector<const SCEV *, 4> ReqRegs;
3167 for (SmallPtrSet<const SCEV *, 16>::const_iterator I = CurRegs.begin(),
3168 E = CurRegs.end(); I != E; ++I)
Dan Gohman9214b822010-02-13 02:06:02 +00003169 if (LU.Regs.count(*I))
Dan Gohman572645c2010-02-12 10:34:29 +00003170 ReqRegs.insert(*I);
Dan Gohman572645c2010-02-12 10:34:29 +00003171
Dan Gohman9214b822010-02-13 02:06:02 +00003172 bool AnySatisfiedReqRegs = false;
Dan Gohman572645c2010-02-12 10:34:29 +00003173 SmallPtrSet<const SCEV *, 16> NewRegs;
3174 Cost NewCost;
Dan Gohman9214b822010-02-13 02:06:02 +00003175retry:
Dan Gohman572645c2010-02-12 10:34:29 +00003176 for (SmallVectorImpl<Formula>::const_iterator I = LU.Formulae.begin(),
3177 E = LU.Formulae.end(); I != E; ++I) {
3178 const Formula &F = *I;
3179
3180 // Ignore formulae which do not use any of the required registers.
3181 for (SmallSetVector<const SCEV *, 4>::const_iterator J = ReqRegs.begin(),
3182 JE = ReqRegs.end(); J != JE; ++J) {
3183 const SCEV *Reg = *J;
3184 if ((!F.ScaledReg || F.ScaledReg != Reg) &&
3185 std::find(F.BaseRegs.begin(), F.BaseRegs.end(), Reg) ==
3186 F.BaseRegs.end())
3187 goto skip;
3188 }
Dan Gohman9214b822010-02-13 02:06:02 +00003189 AnySatisfiedReqRegs = true;
Dan Gohman572645c2010-02-12 10:34:29 +00003190
3191 // Evaluate the cost of the current formula. If it's already worse than
3192 // the current best, prune the search at that point.
3193 NewCost = CurCost;
3194 NewRegs = CurRegs;
3195 NewCost.RateFormula(F, NewRegs, VisitedRegs, L, LU.Offsets, SE, DT);
3196 if (NewCost < SolutionCost) {
3197 Workspace.push_back(&F);
3198 if (Workspace.size() != Uses.size()) {
3199 SolveRecurse(Solution, SolutionCost, Workspace, NewCost,
3200 NewRegs, VisitedRegs);
3201 if (F.getNumRegs() == 1 && Workspace.size() == 1)
3202 VisitedRegs.insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]);
3203 } else {
3204 DEBUG(dbgs() << "New best at "; NewCost.print(dbgs());
3205 dbgs() << ". Regs:";
3206 for (SmallPtrSet<const SCEV *, 16>::const_iterator
3207 I = NewRegs.begin(), E = NewRegs.end(); I != E; ++I)
3208 dbgs() << ' ' << **I;
3209 dbgs() << '\n');
3210
3211 SolutionCost = NewCost;
3212 Solution = Workspace;
3213 }
3214 Workspace.pop_back();
3215 }
3216 skip:;
3217 }
Dan Gohman9214b822010-02-13 02:06:02 +00003218
3219 // If none of the formulae had all of the required registers, relax the
3220 // constraint so that we don't exclude all formulae.
3221 if (!AnySatisfiedReqRegs) {
Dan Gohman59dc6032010-05-07 23:36:59 +00003222 assert(!ReqRegs.empty() && "Solver failed even without required registers");
Dan Gohman9214b822010-02-13 02:06:02 +00003223 ReqRegs.clear();
3224 goto retry;
3225 }
Dan Gohman572645c2010-02-12 10:34:29 +00003226}
3227
Dan Gohman76c315a2010-05-20 20:52:00 +00003228/// Solve - Choose one formula from each use. Return the results in the given
3229/// Solution vector.
Dan Gohman572645c2010-02-12 10:34:29 +00003230void LSRInstance::Solve(SmallVectorImpl<const Formula *> &Solution) const {
3231 SmallVector<const Formula *, 8> Workspace;
3232 Cost SolutionCost;
3233 SolutionCost.Loose();
3234 Cost CurCost;
3235 SmallPtrSet<const SCEV *, 16> CurRegs;
3236 DenseSet<const SCEV *> VisitedRegs;
3237 Workspace.reserve(Uses.size());
3238
Dan Gohmanf7ff37d2010-05-20 20:00:41 +00003239 // SolveRecurse does all the work.
Dan Gohman572645c2010-02-12 10:34:29 +00003240 SolveRecurse(Solution, SolutionCost, Workspace, CurCost,
3241 CurRegs, VisitedRegs);
3242
3243 // Ok, we've now made all our decisions.
3244 DEBUG(dbgs() << "\n"
3245 "The chosen solution requires "; SolutionCost.print(dbgs());
3246 dbgs() << ":\n";
3247 for (size_t i = 0, e = Uses.size(); i != e; ++i) {
3248 dbgs() << " ";
3249 Uses[i].print(dbgs());
3250 dbgs() << "\n"
3251 " ";
3252 Solution[i]->print(dbgs());
3253 dbgs() << '\n';
3254 });
Dan Gohmana5528782010-05-20 20:59:23 +00003255
3256 assert(Solution.size() == Uses.size() && "Malformed solution!");
Dan Gohman572645c2010-02-12 10:34:29 +00003257}
3258
Dan Gohmane5f76872010-04-09 22:07:05 +00003259/// HoistInsertPosition - Helper for AdjustInsertPositionForExpand. Climb up
3260/// the dominator tree far as we can go while still being dominated by the
3261/// input positions. This helps canonicalize the insert position, which
3262/// encourages sharing.
3263BasicBlock::iterator
3264LSRInstance::HoistInsertPosition(BasicBlock::iterator IP,
3265 const SmallVectorImpl<Instruction *> &Inputs)
3266 const {
3267 for (;;) {
3268 const Loop *IPLoop = LI.getLoopFor(IP->getParent());
3269 unsigned IPLoopDepth = IPLoop ? IPLoop->getLoopDepth() : 0;
3270
3271 BasicBlock *IDom;
Dan Gohmand974a0e2010-05-20 20:00:25 +00003272 for (DomTreeNode *Rung = DT.getNode(IP->getParent()); ; ) {
Dan Gohman0fe46d92010-05-20 22:46:54 +00003273 if (!Rung) return IP;
Dan Gohmand974a0e2010-05-20 20:00:25 +00003274 Rung = Rung->getIDom();
3275 if (!Rung) return IP;
3276 IDom = Rung->getBlock();
Dan Gohmane5f76872010-04-09 22:07:05 +00003277
3278 // Don't climb into a loop though.
3279 const Loop *IDomLoop = LI.getLoopFor(IDom);
3280 unsigned IDomDepth = IDomLoop ? IDomLoop->getLoopDepth() : 0;
3281 if (IDomDepth <= IPLoopDepth &&
3282 (IDomDepth != IPLoopDepth || IDomLoop == IPLoop))
3283 break;
3284 }
3285
3286 bool AllDominate = true;
3287 Instruction *BetterPos = 0;
3288 Instruction *Tentative = IDom->getTerminator();
3289 for (SmallVectorImpl<Instruction *>::const_iterator I = Inputs.begin(),
3290 E = Inputs.end(); I != E; ++I) {
3291 Instruction *Inst = *I;
3292 if (Inst == Tentative || !DT.dominates(Inst, Tentative)) {
3293 AllDominate = false;
3294 break;
3295 }
3296 // Attempt to find an insert position in the middle of the block,
3297 // instead of at the end, so that it can be used for other expansions.
3298 if (IDom == Inst->getParent() &&
3299 (!BetterPos || DT.dominates(BetterPos, Inst)))
Douglas Gregor7d9663c2010-05-11 06:17:44 +00003300 BetterPos = llvm::next(BasicBlock::iterator(Inst));
Dan Gohmane5f76872010-04-09 22:07:05 +00003301 }
3302 if (!AllDominate)
3303 break;
3304 if (BetterPos)
3305 IP = BetterPos;
3306 else
3307 IP = Tentative;
3308 }
3309
3310 return IP;
3311}
3312
3313/// AdjustInsertPositionForExpand - Determine an input position which will be
Dan Gohmand96eae82010-04-09 02:00:38 +00003314/// dominated by the operands and which will dominate the result.
3315BasicBlock::iterator
Dan Gohmane5f76872010-04-09 22:07:05 +00003316LSRInstance::AdjustInsertPositionForExpand(BasicBlock::iterator IP,
3317 const LSRFixup &LF,
3318 const LSRUse &LU) const {
Dan Gohmand96eae82010-04-09 02:00:38 +00003319 // Collect some instructions which must be dominated by the
Dan Gohman448db1c2010-04-07 22:27:08 +00003320 // expanding replacement. These must be dominated by any operands that
Dan Gohman572645c2010-02-12 10:34:29 +00003321 // will be required in the expansion.
3322 SmallVector<Instruction *, 4> Inputs;
3323 if (Instruction *I = dyn_cast<Instruction>(LF.OperandValToReplace))
3324 Inputs.push_back(I);
3325 if (LU.Kind == LSRUse::ICmpZero)
3326 if (Instruction *I =
3327 dyn_cast<Instruction>(cast<ICmpInst>(LF.UserInst)->getOperand(1)))
3328 Inputs.push_back(I);
Dan Gohman448db1c2010-04-07 22:27:08 +00003329 if (LF.PostIncLoops.count(L)) {
3330 if (LF.isUseFullyOutsideLoop(L))
Dan Gohman069d6f32010-03-02 01:59:21 +00003331 Inputs.push_back(L->getLoopLatch()->getTerminator());
3332 else
3333 Inputs.push_back(IVIncInsertPos);
3334 }
Dan Gohman701a4ae2010-04-08 05:57:57 +00003335 // The expansion must also be dominated by the increment positions of any
3336 // loops it for which it is using post-inc mode.
3337 for (PostIncLoopSet::const_iterator I = LF.PostIncLoops.begin(),
3338 E = LF.PostIncLoops.end(); I != E; ++I) {
3339 const Loop *PIL = *I;
3340 if (PIL == L) continue;
3341
Dan Gohmane5f76872010-04-09 22:07:05 +00003342 // Be dominated by the loop exit.
Dan Gohman701a4ae2010-04-08 05:57:57 +00003343 SmallVector<BasicBlock *, 4> ExitingBlocks;
3344 PIL->getExitingBlocks(ExitingBlocks);
3345 if (!ExitingBlocks.empty()) {
3346 BasicBlock *BB = ExitingBlocks[0];
3347 for (unsigned i = 1, e = ExitingBlocks.size(); i != e; ++i)
3348 BB = DT.findNearestCommonDominator(BB, ExitingBlocks[i]);
3349 Inputs.push_back(BB->getTerminator());
3350 }
3351 }
Dan Gohman572645c2010-02-12 10:34:29 +00003352
3353 // Then, climb up the immediate dominator tree as far as we can go while
3354 // still being dominated by the input positions.
Dan Gohmane5f76872010-04-09 22:07:05 +00003355 IP = HoistInsertPosition(IP, Inputs);
Dan Gohmand96eae82010-04-09 02:00:38 +00003356
3357 // Don't insert instructions before PHI nodes.
Dan Gohman572645c2010-02-12 10:34:29 +00003358 while (isa<PHINode>(IP)) ++IP;
Dan Gohmand96eae82010-04-09 02:00:38 +00003359
3360 // Ignore debug intrinsics.
Dan Gohman449f31c2010-03-26 00:33:27 +00003361 while (isa<DbgInfoIntrinsic>(IP)) ++IP;
Dan Gohman572645c2010-02-12 10:34:29 +00003362
Dan Gohmand96eae82010-04-09 02:00:38 +00003363 return IP;
3364}
3365
Dan Gohman76c315a2010-05-20 20:52:00 +00003366/// Expand - Emit instructions for the leading candidate expression for this
3367/// LSRUse (this is called "expanding").
Dan Gohmand96eae82010-04-09 02:00:38 +00003368Value *LSRInstance::Expand(const LSRFixup &LF,
3369 const Formula &F,
3370 BasicBlock::iterator IP,
3371 SCEVExpander &Rewriter,
3372 SmallVectorImpl<WeakVH> &DeadInsts) const {
3373 const LSRUse &LU = Uses[LF.LUIdx];
3374
3375 // Determine an input position which will be dominated by the operands and
3376 // which will dominate the result.
Dan Gohmane5f76872010-04-09 22:07:05 +00003377 IP = AdjustInsertPositionForExpand(IP, LF, LU);
Dan Gohmand96eae82010-04-09 02:00:38 +00003378
Dan Gohman572645c2010-02-12 10:34:29 +00003379 // Inform the Rewriter if we have a post-increment use, so that it can
3380 // perform an advantageous expansion.
Dan Gohman448db1c2010-04-07 22:27:08 +00003381 Rewriter.setPostInc(LF.PostIncLoops);
Dan Gohman572645c2010-02-12 10:34:29 +00003382
3383 // This is the type that the user actually needs.
3384 const Type *OpTy = LF.OperandValToReplace->getType();
3385 // This will be the type that we'll initially expand to.
3386 const Type *Ty = F.getType();
3387 if (!Ty)
3388 // No type known; just expand directly to the ultimate type.
3389 Ty = OpTy;
3390 else if (SE.getEffectiveSCEVType(Ty) == SE.getEffectiveSCEVType(OpTy))
3391 // Expand directly to the ultimate type if it's the right size.
3392 Ty = OpTy;
3393 // This is the type to do integer arithmetic in.
3394 const Type *IntTy = SE.getEffectiveSCEVType(Ty);
3395
3396 // Build up a list of operands to add together to form the full base.
3397 SmallVector<const SCEV *, 8> Ops;
3398
3399 // Expand the BaseRegs portion.
3400 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
3401 E = F.BaseRegs.end(); I != E; ++I) {
3402 const SCEV *Reg = *I;
3403 assert(!Reg->isZero() && "Zero allocated in a base register!");
3404
Dan Gohman448db1c2010-04-07 22:27:08 +00003405 // If we're expanding for a post-inc user, make the post-inc adjustment.
3406 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
3407 Reg = TransformForPostIncUse(Denormalize, Reg,
3408 LF.UserInst, LF.OperandValToReplace,
3409 Loops, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +00003410
3411 Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, 0, IP)));
3412 }
3413
Dan Gohman087bd1e2010-03-03 05:29:13 +00003414 // Flush the operand list to suppress SCEVExpander hoisting.
3415 if (!Ops.empty()) {
3416 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
3417 Ops.clear();
3418 Ops.push_back(SE.getUnknown(FullV));
3419 }
3420
Dan Gohman572645c2010-02-12 10:34:29 +00003421 // Expand the ScaledReg portion.
3422 Value *ICmpScaledV = 0;
3423 if (F.AM.Scale != 0) {
3424 const SCEV *ScaledS = F.ScaledReg;
3425
Dan Gohman448db1c2010-04-07 22:27:08 +00003426 // If we're expanding for a post-inc user, make the post-inc adjustment.
3427 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
3428 ScaledS = TransformForPostIncUse(Denormalize, ScaledS,
3429 LF.UserInst, LF.OperandValToReplace,
3430 Loops, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +00003431
3432 if (LU.Kind == LSRUse::ICmpZero) {
3433 // An interesting way of "folding" with an icmp is to use a negated
3434 // scale, which we'll implement by inserting it into the other operand
3435 // of the icmp.
3436 assert(F.AM.Scale == -1 &&
3437 "The only scale supported by ICmpZero uses is -1!");
3438 ICmpScaledV = Rewriter.expandCodeFor(ScaledS, 0, IP);
3439 } else {
3440 // Otherwise just expand the scaled register and an explicit scale,
3441 // which is expected to be matched as part of the address.
3442 ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, 0, IP));
3443 ScaledS = SE.getMulExpr(ScaledS,
Dan Gohmandeff6212010-05-03 22:09:21 +00003444 SE.getConstant(ScaledS->getType(), F.AM.Scale));
Dan Gohman572645c2010-02-12 10:34:29 +00003445 Ops.push_back(ScaledS);
Dan Gohman087bd1e2010-03-03 05:29:13 +00003446
3447 // Flush the operand list to suppress SCEVExpander hoisting.
3448 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
3449 Ops.clear();
3450 Ops.push_back(SE.getUnknown(FullV));
Dan Gohman572645c2010-02-12 10:34:29 +00003451 }
3452 }
3453
Dan Gohman087bd1e2010-03-03 05:29:13 +00003454 // Expand the GV portion.
3455 if (F.AM.BaseGV) {
3456 Ops.push_back(SE.getUnknown(F.AM.BaseGV));
3457
3458 // Flush the operand list to suppress SCEVExpander hoisting.
3459 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
3460 Ops.clear();
3461 Ops.push_back(SE.getUnknown(FullV));
3462 }
3463
3464 // Expand the immediate portion.
Dan Gohman572645c2010-02-12 10:34:29 +00003465 int64_t Offset = (uint64_t)F.AM.BaseOffs + LF.Offset;
3466 if (Offset != 0) {
3467 if (LU.Kind == LSRUse::ICmpZero) {
3468 // The other interesting way of "folding" with an ICmpZero is to use a
3469 // negated immediate.
3470 if (!ICmpScaledV)
3471 ICmpScaledV = ConstantInt::get(IntTy, -Offset);
3472 else {
3473 Ops.push_back(SE.getUnknown(ICmpScaledV));
3474 ICmpScaledV = ConstantInt::get(IntTy, Offset);
3475 }
3476 } else {
3477 // Just add the immediate values. These again are expected to be matched
3478 // as part of the address.
Dan Gohman087bd1e2010-03-03 05:29:13 +00003479 Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy, Offset)));
Dan Gohman572645c2010-02-12 10:34:29 +00003480 }
3481 }
3482
3483 // Emit instructions summing all the operands.
3484 const SCEV *FullS = Ops.empty() ?
Dan Gohmandeff6212010-05-03 22:09:21 +00003485 SE.getConstant(IntTy, 0) :
Dan Gohman572645c2010-02-12 10:34:29 +00003486 SE.getAddExpr(Ops);
3487 Value *FullV = Rewriter.expandCodeFor(FullS, Ty, IP);
3488
3489 // We're done expanding now, so reset the rewriter.
Dan Gohman448db1c2010-04-07 22:27:08 +00003490 Rewriter.clearPostInc();
Dan Gohman572645c2010-02-12 10:34:29 +00003491
3492 // An ICmpZero Formula represents an ICmp which we're handling as a
3493 // comparison against zero. Now that we've expanded an expression for that
3494 // form, update the ICmp's other operand.
3495 if (LU.Kind == LSRUse::ICmpZero) {
3496 ICmpInst *CI = cast<ICmpInst>(LF.UserInst);
3497 DeadInsts.push_back(CI->getOperand(1));
3498 assert(!F.AM.BaseGV && "ICmp does not support folding a global value and "
3499 "a scale at the same time!");
3500 if (F.AM.Scale == -1) {
3501 if (ICmpScaledV->getType() != OpTy) {
3502 Instruction *Cast =
3503 CastInst::Create(CastInst::getCastOpcode(ICmpScaledV, false,
3504 OpTy, false),
3505 ICmpScaledV, OpTy, "tmp", CI);
3506 ICmpScaledV = Cast;
3507 }
3508 CI->setOperand(1, ICmpScaledV);
3509 } else {
3510 assert(F.AM.Scale == 0 &&
3511 "ICmp does not support folding a global value and "
3512 "a scale at the same time!");
3513 Constant *C = ConstantInt::getSigned(SE.getEffectiveSCEVType(OpTy),
3514 -(uint64_t)Offset);
3515 if (C->getType() != OpTy)
3516 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3517 OpTy, false),
3518 C, OpTy);
3519
3520 CI->setOperand(1, C);
3521 }
3522 }
3523
3524 return FullV;
3525}
3526
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003527/// RewriteForPHI - Helper for Rewrite. PHI nodes are special because the use
3528/// of their operands effectively happens in their predecessor blocks, so the
3529/// expression may need to be expanded in multiple places.
3530void LSRInstance::RewriteForPHI(PHINode *PN,
3531 const LSRFixup &LF,
3532 const Formula &F,
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003533 SCEVExpander &Rewriter,
3534 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003535 Pass *P) const {
3536 DenseMap<BasicBlock *, Value *> Inserted;
3537 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
3538 if (PN->getIncomingValue(i) == LF.OperandValToReplace) {
3539 BasicBlock *BB = PN->getIncomingBlock(i);
3540
3541 // If this is a critical edge, split the edge so that we do not insert
3542 // the code on all predecessor/successor paths. We do this unless this
3543 // is the canonical backedge for this loop, which complicates post-inc
3544 // users.
3545 if (e != 1 && BB->getTerminator()->getNumSuccessors() > 1 &&
3546 !isa<IndirectBrInst>(BB->getTerminator()) &&
3547 (PN->getParent() != L->getHeader() || !L->contains(BB))) {
3548 // Split the critical edge.
3549 BasicBlock *NewBB = SplitCriticalEdge(BB, PN->getParent(), P);
3550
3551 // If PN is outside of the loop and BB is in the loop, we want to
3552 // move the block to be immediately before the PHI block, not
3553 // immediately after BB.
3554 if (L->contains(BB) && !L->contains(PN))
3555 NewBB->moveBefore(PN->getParent());
3556
3557 // Splitting the edge can reduce the number of PHI entries we have.
3558 e = PN->getNumIncomingValues();
3559 BB = NewBB;
3560 i = PN->getBasicBlockIndex(BB);
3561 }
3562
3563 std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> Pair =
3564 Inserted.insert(std::make_pair(BB, static_cast<Value *>(0)));
3565 if (!Pair.second)
3566 PN->setIncomingValue(i, Pair.first->second);
3567 else {
Dan Gohman454d26d2010-02-22 04:11:59 +00003568 Value *FullV = Expand(LF, F, BB->getTerminator(), Rewriter, DeadInsts);
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003569
3570 // If this is reuse-by-noop-cast, insert the noop cast.
3571 const Type *OpTy = LF.OperandValToReplace->getType();
3572 if (FullV->getType() != OpTy)
3573 FullV =
3574 CastInst::Create(CastInst::getCastOpcode(FullV, false,
3575 OpTy, false),
3576 FullV, LF.OperandValToReplace->getType(),
3577 "tmp", BB->getTerminator());
3578
3579 PN->setIncomingValue(i, FullV);
3580 Pair.first->second = FullV;
3581 }
3582 }
3583}
3584
Dan Gohman572645c2010-02-12 10:34:29 +00003585/// Rewrite - Emit instructions for the leading candidate expression for this
3586/// LSRUse (this is called "expanding"), and update the UserInst to reference
3587/// the newly expanded value.
3588void LSRInstance::Rewrite(const LSRFixup &LF,
3589 const Formula &F,
Dan Gohman572645c2010-02-12 10:34:29 +00003590 SCEVExpander &Rewriter,
3591 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman572645c2010-02-12 10:34:29 +00003592 Pass *P) const {
Dan Gohman572645c2010-02-12 10:34:29 +00003593 // First, find an insertion point that dominates UserInst. For PHI nodes,
3594 // find the nearest block which dominates all the relevant uses.
3595 if (PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) {
Dan Gohman454d26d2010-02-22 04:11:59 +00003596 RewriteForPHI(PN, LF, F, Rewriter, DeadInsts, P);
Dan Gohman572645c2010-02-12 10:34:29 +00003597 } else {
Dan Gohman454d26d2010-02-22 04:11:59 +00003598 Value *FullV = Expand(LF, F, LF.UserInst, Rewriter, DeadInsts);
Dan Gohman572645c2010-02-12 10:34:29 +00003599
3600 // If this is reuse-by-noop-cast, insert the noop cast.
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003601 const Type *OpTy = LF.OperandValToReplace->getType();
Dan Gohman572645c2010-02-12 10:34:29 +00003602 if (FullV->getType() != OpTy) {
3603 Instruction *Cast =
3604 CastInst::Create(CastInst::getCastOpcode(FullV, false, OpTy, false),
3605 FullV, OpTy, "tmp", LF.UserInst);
3606 FullV = Cast;
3607 }
3608
3609 // Update the user. ICmpZero is handled specially here (for now) because
3610 // Expand may have updated one of the operands of the icmp already, and
3611 // its new value may happen to be equal to LF.OperandValToReplace, in
3612 // which case doing replaceUsesOfWith leads to replacing both operands
3613 // with the same value. TODO: Reorganize this.
3614 if (Uses[LF.LUIdx].Kind == LSRUse::ICmpZero)
3615 LF.UserInst->setOperand(0, FullV);
3616 else
3617 LF.UserInst->replaceUsesOfWith(LF.OperandValToReplace, FullV);
3618 }
3619
3620 DeadInsts.push_back(LF.OperandValToReplace);
3621}
3622
Dan Gohman76c315a2010-05-20 20:52:00 +00003623/// ImplementSolution - Rewrite all the fixup locations with new values,
3624/// following the chosen solution.
Dan Gohman572645c2010-02-12 10:34:29 +00003625void
3626LSRInstance::ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
3627 Pass *P) {
3628 // Keep track of instructions we may have made dead, so that
3629 // we can remove them after we are done working.
3630 SmallVector<WeakVH, 16> DeadInsts;
3631
3632 SCEVExpander Rewriter(SE);
3633 Rewriter.disableCanonicalMode();
3634 Rewriter.setIVIncInsertPos(L, IVIncInsertPos);
3635
3636 // Expand the new value definitions and update the users.
Dan Gohman402d4352010-05-20 20:33:18 +00003637 for (SmallVectorImpl<LSRFixup>::const_iterator I = Fixups.begin(),
3638 E = Fixups.end(); I != E; ++I) {
3639 const LSRFixup &Fixup = *I;
Dan Gohman572645c2010-02-12 10:34:29 +00003640
Dan Gohman402d4352010-05-20 20:33:18 +00003641 Rewrite(Fixup, *Solution[Fixup.LUIdx], Rewriter, DeadInsts, P);
Dan Gohman572645c2010-02-12 10:34:29 +00003642
3643 Changed = true;
3644 }
3645
3646 // Clean up after ourselves. This must be done before deleting any
3647 // instructions.
3648 Rewriter.clear();
3649
3650 Changed |= DeleteTriviallyDeadInstructions(DeadInsts);
3651}
3652
3653LSRInstance::LSRInstance(const TargetLowering *tli, Loop *l, Pass *P)
3654 : IU(P->getAnalysis<IVUsers>()),
3655 SE(P->getAnalysis<ScalarEvolution>()),
3656 DT(P->getAnalysis<DominatorTree>()),
Dan Gohmane5f76872010-04-09 22:07:05 +00003657 LI(P->getAnalysis<LoopInfo>()),
Dan Gohman572645c2010-02-12 10:34:29 +00003658 TLI(tli), L(l), Changed(false), IVIncInsertPos(0) {
Devang Patel0f54dcb2007-03-06 21:14:09 +00003659
Dan Gohman03e896b2009-11-05 21:11:53 +00003660 // If LoopSimplify form is not available, stay out of trouble.
Dan Gohman572645c2010-02-12 10:34:29 +00003661 if (!L->isLoopSimplifyForm()) return;
Dan Gohman03e896b2009-11-05 21:11:53 +00003662
Dan Gohman572645c2010-02-12 10:34:29 +00003663 // If there's no interesting work to be done, bail early.
3664 if (IU.empty()) return;
Dan Gohman80b0f8c2009-03-09 20:34:59 +00003665
Dan Gohman572645c2010-02-12 10:34:29 +00003666 DEBUG(dbgs() << "\nLSR on loop ";
3667 WriteAsOperand(dbgs(), L->getHeader(), /*PrintType=*/false);
3668 dbgs() << ":\n");
Dan Gohmanf7912df2009-03-09 20:46:50 +00003669
Dan Gohman402d4352010-05-20 20:33:18 +00003670 // First, perform some low-level loop optimizations.
Dan Gohman572645c2010-02-12 10:34:29 +00003671 OptimizeShadowIV();
Dan Gohmanc6519f92010-05-20 20:05:31 +00003672 OptimizeLoopTermCond();
Evan Cheng5792f512009-05-11 22:33:01 +00003673
Dan Gohman402d4352010-05-20 20:33:18 +00003674 // Start collecting data and preparing for the solver.
Dan Gohman572645c2010-02-12 10:34:29 +00003675 CollectInterestingTypesAndFactors();
3676 CollectFixupsAndInitialFormulae();
3677 CollectLoopInvariantFixupsAndFormulae();
Chris Lattner010de252005-08-08 05:28:22 +00003678
Dan Gohman572645c2010-02-12 10:34:29 +00003679 DEBUG(dbgs() << "LSR found " << Uses.size() << " uses:\n";
3680 print_uses(dbgs()));
Misha Brukmanfd939082005-04-21 23:48:37 +00003681
Dan Gohman572645c2010-02-12 10:34:29 +00003682 // Now use the reuse data to generate a bunch of interesting ways
3683 // to formulate the values needed for the uses.
3684 GenerateAllReuseFormulae();
Evan Chengd1d6b5c2006-03-16 21:53:05 +00003685
Dan Gohman572645c2010-02-12 10:34:29 +00003686 FilterOutUndesirableDedicatedRegisters();
3687 NarrowSearchSpaceUsingHeuristics();
Dan Gohman6bec5bb2009-12-18 00:06:20 +00003688
Dan Gohman572645c2010-02-12 10:34:29 +00003689 SmallVector<const Formula *, 8> Solution;
3690 Solve(Solution);
Dan Gohman6bec5bb2009-12-18 00:06:20 +00003691
Dan Gohman572645c2010-02-12 10:34:29 +00003692 // Release memory that is no longer needed.
3693 Factors.clear();
3694 Types.clear();
3695 RegUses.clear();
3696
3697#ifndef NDEBUG
3698 // Formulae should be legal.
3699 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
3700 E = Uses.end(); I != E; ++I) {
3701 const LSRUse &LU = *I;
3702 for (SmallVectorImpl<Formula>::const_iterator J = LU.Formulae.begin(),
3703 JE = LU.Formulae.end(); J != JE; ++J)
3704 assert(isLegalUse(J->AM, LU.MinOffset, LU.MaxOffset,
3705 LU.Kind, LU.AccessTy, TLI) &&
3706 "Illegal formula generated!");
3707 };
3708#endif
3709
3710 // Now that we've decided what we want, make it so.
3711 ImplementSolution(Solution, P);
3712}
3713
3714void LSRInstance::print_factors_and_types(raw_ostream &OS) const {
3715 if (Factors.empty() && Types.empty()) return;
3716
3717 OS << "LSR has identified the following interesting factors and types: ";
3718 bool First = true;
3719
3720 for (SmallSetVector<int64_t, 8>::const_iterator
3721 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
3722 if (!First) OS << ", ";
3723 First = false;
3724 OS << '*' << *I;
Evan Cheng81ebdcf2009-11-10 21:14:05 +00003725 }
Dale Johannesenc1acc3f2009-05-11 17:15:42 +00003726
Dan Gohman572645c2010-02-12 10:34:29 +00003727 for (SmallSetVector<const Type *, 4>::const_iterator
3728 I = Types.begin(), E = Types.end(); I != E; ++I) {
3729 if (!First) OS << ", ";
3730 First = false;
3731 OS << '(' << **I << ')';
3732 }
3733 OS << '\n';
3734}
3735
3736void LSRInstance::print_fixups(raw_ostream &OS) const {
3737 OS << "LSR is examining the following fixup sites:\n";
3738 for (SmallVectorImpl<LSRFixup>::const_iterator I = Fixups.begin(),
3739 E = Fixups.end(); I != E; ++I) {
Dan Gohman572645c2010-02-12 10:34:29 +00003740 dbgs() << " ";
Dan Gohman9f383eb2010-05-20 22:25:20 +00003741 I->print(OS);
Dan Gohman572645c2010-02-12 10:34:29 +00003742 OS << '\n';
3743 }
3744}
3745
3746void LSRInstance::print_uses(raw_ostream &OS) const {
3747 OS << "LSR is examining the following uses:\n";
3748 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
3749 E = Uses.end(); I != E; ++I) {
3750 const LSRUse &LU = *I;
3751 dbgs() << " ";
3752 LU.print(OS);
3753 OS << '\n';
3754 for (SmallVectorImpl<Formula>::const_iterator J = LU.Formulae.begin(),
3755 JE = LU.Formulae.end(); J != JE; ++J) {
3756 OS << " ";
3757 J->print(OS);
3758 OS << '\n';
3759 }
3760 }
3761}
3762
3763void LSRInstance::print(raw_ostream &OS) const {
3764 print_factors_and_types(OS);
3765 print_fixups(OS);
3766 print_uses(OS);
3767}
3768
3769void LSRInstance::dump() const {
3770 print(errs()); errs() << '\n';
3771}
3772
3773namespace {
3774
3775class LoopStrengthReduce : public LoopPass {
3776 /// TLI - Keep a pointer of a TargetLowering to consult for determining
3777 /// transformation profitability.
3778 const TargetLowering *const TLI;
3779
3780public:
3781 static char ID; // Pass ID, replacement for typeid
3782 explicit LoopStrengthReduce(const TargetLowering *tli = 0);
3783
3784private:
3785 bool runOnLoop(Loop *L, LPPassManager &LPM);
3786 void getAnalysisUsage(AnalysisUsage &AU) const;
3787};
3788
3789}
3790
3791char LoopStrengthReduce::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +00003792INITIALIZE_PASS_BEGIN(LoopStrengthReduce, "loop-reduce",
Owen Andersonce665bd2010-10-07 22:25:06 +00003793 "Loop Strength Reduction", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +00003794INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3795INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3796INITIALIZE_PASS_DEPENDENCY(IVUsers)
Owen Anderson205942a2010-10-19 20:08:44 +00003797INITIALIZE_PASS_DEPENDENCY(LoopInfo)
3798INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Owen Anderson2ab36d32010-10-12 19:48:12 +00003799INITIALIZE_PASS_END(LoopStrengthReduce, "loop-reduce",
3800 "Loop Strength Reduction", false, false)
3801
Dan Gohman572645c2010-02-12 10:34:29 +00003802
3803Pass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
3804 return new LoopStrengthReduce(TLI);
3805}
3806
3807LoopStrengthReduce::LoopStrengthReduce(const TargetLowering *tli)
Owen Anderson081c34b2010-10-19 17:21:58 +00003808 : LoopPass(ID), TLI(tli) {
3809 initializeLoopStrengthReducePass(*PassRegistry::getPassRegistry());
3810 }
Dan Gohman572645c2010-02-12 10:34:29 +00003811
3812void LoopStrengthReduce::getAnalysisUsage(AnalysisUsage &AU) const {
3813 // We split critical edges, so we change the CFG. However, we do update
3814 // many analyses if they are around.
3815 AU.addPreservedID(LoopSimplifyID);
Dan Gohman572645c2010-02-12 10:34:29 +00003816 AU.addPreserved("domfrontier");
3817
Dan Gohmane5f76872010-04-09 22:07:05 +00003818 AU.addRequired<LoopInfo>();
3819 AU.addPreserved<LoopInfo>();
Dan Gohman572645c2010-02-12 10:34:29 +00003820 AU.addRequiredID(LoopSimplifyID);
3821 AU.addRequired<DominatorTree>();
3822 AU.addPreserved<DominatorTree>();
3823 AU.addRequired<ScalarEvolution>();
3824 AU.addPreserved<ScalarEvolution>();
3825 AU.addRequired<IVUsers>();
3826 AU.addPreserved<IVUsers>();
3827}
3828
3829bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager & /*LPM*/) {
3830 bool Changed = false;
3831
3832 // Run the main LSR transformation.
3833 Changed |= LSRInstance(TLI, L, this).getChanged();
3834
Dan Gohmanafc36a92009-05-02 18:29:22 +00003835 // At this point, it is worth checking to see if any recurrence PHIs are also
Dan Gohman35738ac2009-05-04 22:30:44 +00003836 // dead, so that we can remove them as well.
Dan Gohman9fff2182010-01-05 16:31:45 +00003837 Changed |= DeleteDeadPHIs(L->getHeader());
Dan Gohmanafc36a92009-05-02 18:29:22 +00003838
Evan Cheng1ce75dc2008-07-07 19:51:32 +00003839 return Changed;
Nate Begemaneaa13852004-10-18 21:08:22 +00003840}