blob: a4bc0170edb34f44318850fd1941ae1ceb1bfc36 [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 Gohman572645c2010-02-12 10:34:29 +0000110 RegUsesTy RegUses;
111 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 Gohmana10756e2010-01-21 02:09:26 +0000115
Dan Gohman572645c2010-02-12 10:34:29 +0000116 bool isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const;
Dan Gohmana10756e2010-01-21 02:09:26 +0000117
Dan Gohman572645c2010-02-12 10:34:29 +0000118 const SmallBitVector &getUsedByIndices(const SCEV *Reg) const;
Dan Gohmana10756e2010-01-21 02:09:26 +0000119
Dan Gohman572645c2010-02-12 10:34:29 +0000120 void clear();
Dan Gohmana10756e2010-01-21 02:09:26 +0000121
Dan Gohman572645c2010-02-12 10:34:29 +0000122 typedef SmallVectorImpl<const SCEV *>::iterator iterator;
123 typedef SmallVectorImpl<const SCEV *>::const_iterator const_iterator;
124 iterator begin() { return RegSequence.begin(); }
125 iterator end() { return RegSequence.end(); }
126 const_iterator begin() const { return RegSequence.begin(); }
127 const_iterator end() const { return RegSequence.end(); }
128};
Dan Gohmana10756e2010-01-21 02:09:26 +0000129
Dan Gohmana10756e2010-01-21 02:09:26 +0000130}
131
Dan Gohman572645c2010-02-12 10:34:29 +0000132void
133RegUseTracker::CountRegister(const SCEV *Reg, size_t LUIdx) {
134 std::pair<RegUsesTy::iterator, bool> Pair =
135 RegUses.insert(std::make_pair(Reg, RegSortData()));
136 RegSortData &RSD = Pair.first->second;
137 if (Pair.second)
138 RegSequence.push_back(Reg);
139 RSD.UsedByIndices.resize(std::max(RSD.UsedByIndices.size(), LUIdx + 1));
140 RSD.UsedByIndices.set(LUIdx);
Dan Gohmana10756e2010-01-21 02:09:26 +0000141}
142
Dan Gohman572645c2010-02-12 10:34:29 +0000143bool
144RegUseTracker::isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const {
145 if (!RegUses.count(Reg)) return false;
146 const SmallBitVector &UsedByIndices =
147 RegUses.find(Reg)->second.UsedByIndices;
148 int i = UsedByIndices.find_first();
149 if (i == -1) return false;
150 if ((size_t)i != LUIdx) return true;
151 return UsedByIndices.find_next(i) != -1;
152}
Dan Gohmana10756e2010-01-21 02:09:26 +0000153
Dan Gohman572645c2010-02-12 10:34:29 +0000154const SmallBitVector &RegUseTracker::getUsedByIndices(const SCEV *Reg) const {
155 RegUsesTy::const_iterator I = RegUses.find(Reg);
156 assert(I != RegUses.end() && "Unknown register!");
157 return I->second.UsedByIndices;
158}
Dan Gohmana10756e2010-01-21 02:09:26 +0000159
Dan Gohman572645c2010-02-12 10:34:29 +0000160void RegUseTracker::clear() {
161 RegUses.clear();
162 RegSequence.clear();
163}
Dan Gohmana10756e2010-01-21 02:09:26 +0000164
Dan Gohman572645c2010-02-12 10:34:29 +0000165namespace {
166
167/// Formula - This class holds information that describes a formula for
168/// computing satisfying a use. It may include broken-out immediates and scaled
169/// registers.
170struct Formula {
171 /// AM - This is used to represent complex addressing, as well as other kinds
172 /// of interesting uses.
173 TargetLowering::AddrMode AM;
174
175 /// BaseRegs - The list of "base" registers for this use. When this is
176 /// non-empty, AM.HasBaseReg should be set to true.
177 SmallVector<const SCEV *, 2> BaseRegs;
178
179 /// ScaledReg - The 'scaled' register for this use. This should be non-null
180 /// when AM.Scale is not zero.
181 const SCEV *ScaledReg;
182
183 Formula() : ScaledReg(0) {}
184
185 void InitialMatch(const SCEV *S, Loop *L,
186 ScalarEvolution &SE, DominatorTree &DT);
187
188 unsigned getNumRegs() const;
189 const Type *getType() const;
190
191 bool referencesReg(const SCEV *S) const;
192 bool hasRegsUsedByUsesOtherThan(size_t LUIdx,
193 const RegUseTracker &RegUses) const;
194
195 void print(raw_ostream &OS) const;
196 void dump() const;
197};
198
199}
200
201/// DoInitialMatch - Recurrsion helper for InitialMatch.
202static void DoInitialMatch(const SCEV *S, Loop *L,
203 SmallVectorImpl<const SCEV *> &Good,
204 SmallVectorImpl<const SCEV *> &Bad,
205 ScalarEvolution &SE, DominatorTree &DT) {
206 // Collect expressions which properly dominate the loop header.
207 if (S->properlyDominates(L->getHeader(), &DT)) {
208 Good.push_back(S);
209 return;
Dan Gohmana10756e2010-01-21 02:09:26 +0000210 }
Dan Gohman572645c2010-02-12 10:34:29 +0000211
212 // Look at add operands.
213 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
214 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
215 I != E; ++I)
216 DoInitialMatch(*I, L, Good, Bad, SE, DT);
217 return;
218 }
219
220 // Look at addrec operands.
221 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
222 if (!AR->getStart()->isZero()) {
223 DoInitialMatch(AR->getStart(), L, Good, Bad, SE, DT);
224 DoInitialMatch(SE.getAddRecExpr(SE.getIntegerSCEV(0, AR->getType()),
225 AR->getStepRecurrence(SE),
226 AR->getLoop()),
227 L, Good, Bad, SE, DT);
228 return;
229 }
230
231 // Handle a multiplication by -1 (negation) if it didn't fold.
232 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S))
233 if (Mul->getOperand(0)->isAllOnesValue()) {
234 SmallVector<const SCEV *, 4> Ops(Mul->op_begin()+1, Mul->op_end());
235 const SCEV *NewMul = SE.getMulExpr(Ops);
236
237 SmallVector<const SCEV *, 4> MyGood;
238 SmallVector<const SCEV *, 4> MyBad;
239 DoInitialMatch(NewMul, L, MyGood, MyBad, SE, DT);
240 const SCEV *NegOne = SE.getSCEV(ConstantInt::getAllOnesValue(
241 SE.getEffectiveSCEVType(NewMul->getType())));
242 for (SmallVectorImpl<const SCEV *>::const_iterator I = MyGood.begin(),
243 E = MyGood.end(); I != E; ++I)
244 Good.push_back(SE.getMulExpr(NegOne, *I));
245 for (SmallVectorImpl<const SCEV *>::const_iterator I = MyBad.begin(),
246 E = MyBad.end(); I != E; ++I)
247 Bad.push_back(SE.getMulExpr(NegOne, *I));
248 return;
249 }
250
251 // Ok, we can't do anything interesting. Just stuff the whole thing into a
252 // register and hope for the best.
253 Bad.push_back(S);
254}
255
256/// InitialMatch - Incorporate loop-variant parts of S into this Formula,
257/// attempting to keep all loop-invariant and loop-computable values in a
258/// single base register.
259void Formula::InitialMatch(const SCEV *S, Loop *L,
260 ScalarEvolution &SE, DominatorTree &DT) {
261 SmallVector<const SCEV *, 4> Good;
262 SmallVector<const SCEV *, 4> Bad;
263 DoInitialMatch(S, L, Good, Bad, SE, DT);
264 if (!Good.empty()) {
265 BaseRegs.push_back(SE.getAddExpr(Good));
266 AM.HasBaseReg = true;
267 }
268 if (!Bad.empty()) {
269 BaseRegs.push_back(SE.getAddExpr(Bad));
270 AM.HasBaseReg = true;
271 }
272}
273
274/// getNumRegs - Return the total number of register operands used by this
275/// formula. This does not include register uses implied by non-constant
276/// addrec strides.
277unsigned Formula::getNumRegs() const {
278 return !!ScaledReg + BaseRegs.size();
279}
280
281/// getType - Return the type of this formula, if it has one, or null
282/// otherwise. This type is meaningless except for the bit size.
283const Type *Formula::getType() const {
284 return !BaseRegs.empty() ? BaseRegs.front()->getType() :
285 ScaledReg ? ScaledReg->getType() :
286 AM.BaseGV ? AM.BaseGV->getType() :
287 0;
288}
289
290/// referencesReg - Test if this formula references the given register.
291bool Formula::referencesReg(const SCEV *S) const {
292 return S == ScaledReg ||
293 std::find(BaseRegs.begin(), BaseRegs.end(), S) != BaseRegs.end();
294}
295
296/// hasRegsUsedByUsesOtherThan - Test whether this formula uses registers
297/// which are used by uses other than the use with the given index.
298bool Formula::hasRegsUsedByUsesOtherThan(size_t LUIdx,
299 const RegUseTracker &RegUses) const {
300 if (ScaledReg)
301 if (RegUses.isRegUsedByUsesOtherThan(ScaledReg, LUIdx))
302 return true;
303 for (SmallVectorImpl<const SCEV *>::const_iterator I = BaseRegs.begin(),
304 E = BaseRegs.end(); I != E; ++I)
305 if (RegUses.isRegUsedByUsesOtherThan(*I, LUIdx))
306 return true;
307 return false;
308}
309
310void Formula::print(raw_ostream &OS) const {
311 bool First = true;
312 if (AM.BaseGV) {
313 if (!First) OS << " + "; else First = false;
314 WriteAsOperand(OS, AM.BaseGV, /*PrintType=*/false);
315 }
316 if (AM.BaseOffs != 0) {
317 if (!First) OS << " + "; else First = false;
318 OS << AM.BaseOffs;
319 }
320 for (SmallVectorImpl<const SCEV *>::const_iterator I = BaseRegs.begin(),
321 E = BaseRegs.end(); I != E; ++I) {
322 if (!First) OS << " + "; else First = false;
323 OS << "reg(" << **I << ')';
324 }
325 if (AM.Scale != 0) {
326 if (!First) OS << " + "; else First = false;
327 OS << AM.Scale << "*reg(";
328 if (ScaledReg)
329 OS << *ScaledReg;
330 else
331 OS << "<unknown>";
332 OS << ')';
333 }
334}
335
336void Formula::dump() const {
337 print(errs()); errs() << '\n';
338}
339
Dan Gohmanaae01f12010-02-19 19:32:49 +0000340/// isAddRecSExtable - Return true if the given addrec can be sign-extended
341/// without changing its value.
342static bool isAddRecSExtable(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
343 const Type *WideTy =
344 IntegerType::get(SE.getContext(),
345 SE.getTypeSizeInBits(AR->getType()) + 1);
346 return isa<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
347}
348
349/// isAddSExtable - Return true if the given add can be sign-extended
350/// without changing its value.
351static bool isAddSExtable(const SCEVAddExpr *A, ScalarEvolution &SE) {
352 const Type *WideTy =
353 IntegerType::get(SE.getContext(),
354 SE.getTypeSizeInBits(A->getType()) + 1);
355 return isa<SCEVAddExpr>(SE.getSignExtendExpr(A, WideTy));
356}
357
358/// isMulSExtable - Return true if the given add can be sign-extended
359/// without changing its value.
360static bool isMulSExtable(const SCEVMulExpr *A, ScalarEvolution &SE) {
361 const Type *WideTy =
362 IntegerType::get(SE.getContext(),
363 SE.getTypeSizeInBits(A->getType()) + 1);
364 return isa<SCEVMulExpr>(SE.getSignExtendExpr(A, WideTy));
365}
366
Dan Gohmanf09b7122010-02-19 19:35:48 +0000367/// getExactSDiv - Return an expression for LHS /s RHS, if it can be determined
368/// and if the remainder is known to be zero, or null otherwise. If
369/// IgnoreSignificantBits is true, expressions like (X * Y) /s Y are simplified
370/// to Y, ignoring that the multiplication may overflow, which is useful when
371/// the result will be used in a context where the most significant bits are
372/// ignored.
373static const SCEV *getExactSDiv(const SCEV *LHS, const SCEV *RHS,
374 ScalarEvolution &SE,
375 bool IgnoreSignificantBits = false) {
Dan Gohman572645c2010-02-12 10:34:29 +0000376 // Handle the trivial case, which works for any SCEV type.
377 if (LHS == RHS)
378 return SE.getIntegerSCEV(1, LHS->getType());
379
380 // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do some
381 // folding.
382 if (RHS->isAllOnesValue())
383 return SE.getMulExpr(LHS, RHS);
384
385 // Check for a division of a constant by a constant.
386 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(LHS)) {
387 const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS);
388 if (!RC)
389 return 0;
390 if (C->getValue()->getValue().srem(RC->getValue()->getValue()) != 0)
391 return 0;
392 return SE.getConstant(C->getValue()->getValue()
393 .sdiv(RC->getValue()->getValue()));
394 }
395
Dan Gohmanaae01f12010-02-19 19:32:49 +0000396 // Distribute the sdiv over addrec operands, if the addrec doesn't overflow.
Dan Gohman572645c2010-02-12 10:34:29 +0000397 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohmanaae01f12010-02-19 19:32:49 +0000398 if (IgnoreSignificantBits || isAddRecSExtable(AR, SE)) {
Dan Gohmanf09b7122010-02-19 19:35:48 +0000399 const SCEV *Start = getExactSDiv(AR->getStart(), RHS, SE,
400 IgnoreSignificantBits);
Dan Gohmanaae01f12010-02-19 19:32:49 +0000401 if (!Start) return 0;
Dan Gohmanf09b7122010-02-19 19:35:48 +0000402 const SCEV *Step = getExactSDiv(AR->getStepRecurrence(SE), RHS, SE,
403 IgnoreSignificantBits);
Dan Gohmanaae01f12010-02-19 19:32:49 +0000404 if (!Step) return 0;
405 return SE.getAddRecExpr(Start, Step, AR->getLoop());
406 }
Dan Gohman572645c2010-02-12 10:34:29 +0000407 }
408
Dan Gohmanaae01f12010-02-19 19:32:49 +0000409 // Distribute the sdiv over add operands, if the add doesn't overflow.
Dan Gohman572645c2010-02-12 10:34:29 +0000410 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(LHS)) {
Dan Gohmanaae01f12010-02-19 19:32:49 +0000411 if (IgnoreSignificantBits || isAddSExtable(Add, SE)) {
412 SmallVector<const SCEV *, 8> Ops;
413 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
414 I != E; ++I) {
Dan Gohmanf09b7122010-02-19 19:35:48 +0000415 const SCEV *Op = getExactSDiv(*I, RHS, SE,
416 IgnoreSignificantBits);
Dan Gohmanaae01f12010-02-19 19:32:49 +0000417 if (!Op) return 0;
418 Ops.push_back(Op);
419 }
420 return SE.getAddExpr(Ops);
Dan Gohman572645c2010-02-12 10:34:29 +0000421 }
Dan Gohman572645c2010-02-12 10:34:29 +0000422 }
423
424 // Check for a multiply operand that we can pull RHS out of.
425 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS))
Dan Gohmanaae01f12010-02-19 19:32:49 +0000426 if (IgnoreSignificantBits || isMulSExtable(Mul, SE)) {
Dan Gohman572645c2010-02-12 10:34:29 +0000427 SmallVector<const SCEV *, 4> Ops;
428 bool Found = false;
429 for (SCEVMulExpr::op_iterator I = Mul->op_begin(), E = Mul->op_end();
430 I != E; ++I) {
431 if (!Found)
Dan Gohmanf09b7122010-02-19 19:35:48 +0000432 if (const SCEV *Q = getExactSDiv(*I, RHS, SE,
433 IgnoreSignificantBits)) {
Dan Gohman572645c2010-02-12 10:34:29 +0000434 Ops.push_back(Q);
435 Found = true;
436 continue;
437 }
438 Ops.push_back(*I);
439 }
440 return Found ? SE.getMulExpr(Ops) : 0;
441 }
442
443 // Otherwise we don't know.
444 return 0;
445}
446
447/// ExtractImmediate - If S involves the addition of a constant integer value,
448/// return that integer value, and mutate S to point to a new SCEV with that
449/// value excluded.
450static int64_t ExtractImmediate(const SCEV *&S, ScalarEvolution &SE) {
451 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
452 if (C->getValue()->getValue().getMinSignedBits() <= 64) {
453 S = SE.getIntegerSCEV(0, C->getType());
454 return C->getValue()->getSExtValue();
455 }
456 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
457 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
458 int64_t Result = ExtractImmediate(NewOps.front(), SE);
459 S = SE.getAddExpr(NewOps);
460 return Result;
461 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
462 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
463 int64_t Result = ExtractImmediate(NewOps.front(), SE);
464 S = SE.getAddRecExpr(NewOps, AR->getLoop());
465 return Result;
466 }
467 return 0;
468}
469
470/// ExtractSymbol - If S involves the addition of a GlobalValue address,
471/// return that symbol, and mutate S to point to a new SCEV with that
472/// value excluded.
473static GlobalValue *ExtractSymbol(const SCEV *&S, ScalarEvolution &SE) {
474 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
475 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) {
476 S = SE.getIntegerSCEV(0, GV->getType());
477 return GV;
478 }
479 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
480 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
481 GlobalValue *Result = ExtractSymbol(NewOps.back(), SE);
482 S = SE.getAddExpr(NewOps);
483 return Result;
484 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
485 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
486 GlobalValue *Result = ExtractSymbol(NewOps.front(), SE);
487 S = SE.getAddRecExpr(NewOps, AR->getLoop());
488 return Result;
489 }
490 return 0;
Nate Begemaneaa13852004-10-18 21:08:22 +0000491}
492
Dan Gohmanf284ce22009-02-18 00:08:39 +0000493/// isAddressUse - Returns true if the specified instruction is using the
Dale Johannesen203af582008-12-05 21:47:27 +0000494/// specified value as an address.
495static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
496 bool isAddress = isa<LoadInst>(Inst);
497 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
498 if (SI->getOperand(1) == OperandVal)
499 isAddress = true;
500 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
501 // Addressing modes can also be folded into prefetches and a variety
502 // of intrinsics.
503 switch (II->getIntrinsicID()) {
504 default: break;
505 case Intrinsic::prefetch:
506 case Intrinsic::x86_sse2_loadu_dq:
507 case Intrinsic::x86_sse2_loadu_pd:
508 case Intrinsic::x86_sse_loadu_ps:
509 case Intrinsic::x86_sse_storeu_ps:
510 case Intrinsic::x86_sse2_storeu_pd:
511 case Intrinsic::x86_sse2_storeu_dq:
512 case Intrinsic::x86_sse2_storel_dq:
513 if (II->getOperand(1) == OperandVal)
514 isAddress = true;
515 break;
516 }
517 }
518 return isAddress;
519}
Chris Lattner0ae33eb2005-10-03 01:04:44 +0000520
Dan Gohman21e77222009-03-09 21:01:17 +0000521/// getAccessType - Return the type of the memory being accessed.
522static const Type *getAccessType(const Instruction *Inst) {
Dan Gohmana537bf82009-05-18 16:45:28 +0000523 const Type *AccessTy = Inst->getType();
Dan Gohman21e77222009-03-09 21:01:17 +0000524 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst))
Dan Gohmana537bf82009-05-18 16:45:28 +0000525 AccessTy = SI->getOperand(0)->getType();
Dan Gohman21e77222009-03-09 21:01:17 +0000526 else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
527 // Addressing modes can also be folded into prefetches and a variety
528 // of intrinsics.
529 switch (II->getIntrinsicID()) {
530 default: break;
531 case Intrinsic::x86_sse_storeu_ps:
532 case Intrinsic::x86_sse2_storeu_pd:
533 case Intrinsic::x86_sse2_storeu_dq:
534 case Intrinsic::x86_sse2_storel_dq:
Dan Gohmana537bf82009-05-18 16:45:28 +0000535 AccessTy = II->getOperand(1)->getType();
Dan Gohman21e77222009-03-09 21:01:17 +0000536 break;
537 }
538 }
Dan Gohman572645c2010-02-12 10:34:29 +0000539
540 // All pointers have the same requirements, so canonicalize them to an
541 // arbitrary pointer type to minimize variation.
542 if (const PointerType *PTy = dyn_cast<PointerType>(AccessTy))
543 AccessTy = PointerType::get(IntegerType::get(PTy->getContext(), 1),
544 PTy->getAddressSpace());
545
Dan Gohmana537bf82009-05-18 16:45:28 +0000546 return AccessTy;
Dan Gohman21e77222009-03-09 21:01:17 +0000547}
548
Dan Gohman572645c2010-02-12 10:34:29 +0000549/// DeleteTriviallyDeadInstructions - If any of the instructions is the
550/// specified set are trivially dead, delete them and see if this makes any of
551/// their operands subsequently dead.
552static bool
553DeleteTriviallyDeadInstructions(SmallVectorImpl<WeakVH> &DeadInsts) {
554 bool Changed = false;
555
556 while (!DeadInsts.empty()) {
557 Instruction *I = dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val());
558
559 if (I == 0 || !isInstructionTriviallyDead(I))
560 continue;
561
562 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
563 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
564 *OI = 0;
565 if (U->use_empty())
566 DeadInsts.push_back(U);
567 }
568
569 I->eraseFromParent();
570 Changed = true;
571 }
572
573 return Changed;
574}
575
Dan Gohman7979b722010-01-22 00:46:49 +0000576namespace {
Jim Grosbach56a1f802009-11-17 17:53:56 +0000577
Dan Gohman572645c2010-02-12 10:34:29 +0000578/// Cost - This class is used to measure and compare candidate formulae.
579class Cost {
580 /// TODO: Some of these could be merged. Also, a lexical ordering
581 /// isn't always optimal.
582 unsigned NumRegs;
583 unsigned AddRecCost;
584 unsigned NumIVMuls;
585 unsigned NumBaseAdds;
586 unsigned ImmCost;
587 unsigned SetupCost;
Nate Begeman16997482005-07-30 00:15:07 +0000588
Dan Gohman572645c2010-02-12 10:34:29 +0000589public:
590 Cost()
591 : NumRegs(0), AddRecCost(0), NumIVMuls(0), NumBaseAdds(0), ImmCost(0),
592 SetupCost(0) {}
Jim Grosbach56a1f802009-11-17 17:53:56 +0000593
Dan Gohman572645c2010-02-12 10:34:29 +0000594 unsigned getNumRegs() const { return NumRegs; }
Dan Gohman7979b722010-01-22 00:46:49 +0000595
Dan Gohman572645c2010-02-12 10:34:29 +0000596 bool operator<(const Cost &Other) const;
Dan Gohman7979b722010-01-22 00:46:49 +0000597
Dan Gohman572645c2010-02-12 10:34:29 +0000598 void Loose();
Dan Gohman7979b722010-01-22 00:46:49 +0000599
Dan Gohman572645c2010-02-12 10:34:29 +0000600 void RateFormula(const Formula &F,
601 SmallPtrSet<const SCEV *, 16> &Regs,
602 const DenseSet<const SCEV *> &VisitedRegs,
603 const Loop *L,
604 const SmallVectorImpl<int64_t> &Offsets,
605 ScalarEvolution &SE, DominatorTree &DT);
Dan Gohman7979b722010-01-22 00:46:49 +0000606
Dan Gohman572645c2010-02-12 10:34:29 +0000607 void print(raw_ostream &OS) const;
608 void dump() const;
Dan Gohman7979b722010-01-22 00:46:49 +0000609
Dan Gohman572645c2010-02-12 10:34:29 +0000610private:
611 void RateRegister(const SCEV *Reg,
612 SmallPtrSet<const SCEV *, 16> &Regs,
613 const Loop *L,
614 ScalarEvolution &SE, DominatorTree &DT);
Dan Gohman9214b822010-02-13 02:06:02 +0000615 void RatePrimaryRegister(const SCEV *Reg,
616 SmallPtrSet<const SCEV *, 16> &Regs,
617 const Loop *L,
618 ScalarEvolution &SE, DominatorTree &DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000619};
620
621}
622
623/// RateRegister - Tally up interesting quantities from the given register.
624void Cost::RateRegister(const SCEV *Reg,
625 SmallPtrSet<const SCEV *, 16> &Regs,
626 const Loop *L,
627 ScalarEvolution &SE, DominatorTree &DT) {
Dan Gohman9214b822010-02-13 02:06:02 +0000628 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Reg)) {
629 if (AR->getLoop() == L)
630 AddRecCost += 1; /// TODO: This should be a function of the stride.
Dan Gohman572645c2010-02-12 10:34:29 +0000631
Dan Gohman9214b822010-02-13 02:06:02 +0000632 // If this is an addrec for a loop that's already been visited by LSR,
633 // don't second-guess its addrec phi nodes. LSR isn't currently smart
634 // enough to reason about more than one loop at a time. Consider these
635 // registers free and leave them alone.
636 else if (L->contains(AR->getLoop()) ||
637 (!AR->getLoop()->contains(L) &&
638 DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))) {
639 for (BasicBlock::iterator I = AR->getLoop()->getHeader()->begin();
640 PHINode *PN = dyn_cast<PHINode>(I); ++I)
641 if (SE.isSCEVable(PN->getType()) &&
642 (SE.getEffectiveSCEVType(PN->getType()) ==
643 SE.getEffectiveSCEVType(AR->getType())) &&
644 SE.getSCEV(PN) == AR)
645 return;
Dan Gohman572645c2010-02-12 10:34:29 +0000646
Dan Gohman9214b822010-02-13 02:06:02 +0000647 // If this isn't one of the addrecs that the loop already has, it
648 // would require a costly new phi and add. TODO: This isn't
649 // precisely modeled right now.
650 ++NumBaseAdds;
651 if (!Regs.count(AR->getStart()))
Dan Gohman572645c2010-02-12 10:34:29 +0000652 RateRegister(AR->getStart(), Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000653 }
Dan Gohman572645c2010-02-12 10:34:29 +0000654
Dan Gohman9214b822010-02-13 02:06:02 +0000655 // Add the step value register, if it needs one.
656 // TODO: The non-affine case isn't precisely modeled here.
657 if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1)))
658 if (!Regs.count(AR->getStart()))
659 RateRegister(AR->getOperand(1), Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000660 }
Dan Gohman9214b822010-02-13 02:06:02 +0000661 ++NumRegs;
662
663 // Rough heuristic; favor registers which don't require extra setup
664 // instructions in the preheader.
665 if (!isa<SCEVUnknown>(Reg) &&
666 !isa<SCEVConstant>(Reg) &&
667 !(isa<SCEVAddRecExpr>(Reg) &&
668 (isa<SCEVUnknown>(cast<SCEVAddRecExpr>(Reg)->getStart()) ||
669 isa<SCEVConstant>(cast<SCEVAddRecExpr>(Reg)->getStart()))))
670 ++SetupCost;
671}
672
673/// RatePrimaryRegister - Record this register in the set. If we haven't seen it
674/// before, rate it.
675void Cost::RatePrimaryRegister(const SCEV *Reg,
Dan Gohman7fca2292010-02-16 19:42:34 +0000676 SmallPtrSet<const SCEV *, 16> &Regs,
677 const Loop *L,
678 ScalarEvolution &SE, DominatorTree &DT) {
Dan Gohman9214b822010-02-13 02:06:02 +0000679 if (Regs.insert(Reg))
680 RateRegister(Reg, Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000681}
682
683void Cost::RateFormula(const Formula &F,
684 SmallPtrSet<const SCEV *, 16> &Regs,
685 const DenseSet<const SCEV *> &VisitedRegs,
686 const Loop *L,
687 const SmallVectorImpl<int64_t> &Offsets,
688 ScalarEvolution &SE, DominatorTree &DT) {
689 // Tally up the registers.
690 if (const SCEV *ScaledReg = F.ScaledReg) {
691 if (VisitedRegs.count(ScaledReg)) {
692 Loose();
693 return;
694 }
Dan Gohman9214b822010-02-13 02:06:02 +0000695 RatePrimaryRegister(ScaledReg, Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000696 }
697 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
698 E = F.BaseRegs.end(); I != E; ++I) {
699 const SCEV *BaseReg = *I;
700 if (VisitedRegs.count(BaseReg)) {
701 Loose();
702 return;
703 }
Dan Gohman9214b822010-02-13 02:06:02 +0000704 RatePrimaryRegister(BaseReg, Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000705
706 NumIVMuls += isa<SCEVMulExpr>(BaseReg) &&
707 BaseReg->hasComputableLoopEvolution(L);
708 }
709
710 if (F.BaseRegs.size() > 1)
711 NumBaseAdds += F.BaseRegs.size() - 1;
712
713 // Tally up the non-zero immediates.
714 for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
715 E = Offsets.end(); I != E; ++I) {
716 int64_t Offset = (uint64_t)*I + F.AM.BaseOffs;
717 if (F.AM.BaseGV)
718 ImmCost += 64; // Handle symbolic values conservatively.
719 // TODO: This should probably be the pointer size.
720 else if (Offset != 0)
721 ImmCost += APInt(64, Offset, true).getMinSignedBits();
722 }
723}
724
725/// Loose - Set this cost to a loosing value.
726void Cost::Loose() {
727 NumRegs = ~0u;
728 AddRecCost = ~0u;
729 NumIVMuls = ~0u;
730 NumBaseAdds = ~0u;
731 ImmCost = ~0u;
732 SetupCost = ~0u;
733}
734
735/// operator< - Choose the lower cost.
736bool Cost::operator<(const Cost &Other) const {
737 if (NumRegs != Other.NumRegs)
738 return NumRegs < Other.NumRegs;
739 if (AddRecCost != Other.AddRecCost)
740 return AddRecCost < Other.AddRecCost;
741 if (NumIVMuls != Other.NumIVMuls)
742 return NumIVMuls < Other.NumIVMuls;
743 if (NumBaseAdds != Other.NumBaseAdds)
744 return NumBaseAdds < Other.NumBaseAdds;
745 if (ImmCost != Other.ImmCost)
746 return ImmCost < Other.ImmCost;
747 if (SetupCost != Other.SetupCost)
748 return SetupCost < Other.SetupCost;
749 return false;
750}
751
752void Cost::print(raw_ostream &OS) const {
753 OS << NumRegs << " reg" << (NumRegs == 1 ? "" : "s");
754 if (AddRecCost != 0)
755 OS << ", with addrec cost " << AddRecCost;
756 if (NumIVMuls != 0)
757 OS << ", plus " << NumIVMuls << " IV mul" << (NumIVMuls == 1 ? "" : "s");
758 if (NumBaseAdds != 0)
759 OS << ", plus " << NumBaseAdds << " base add"
760 << (NumBaseAdds == 1 ? "" : "s");
761 if (ImmCost != 0)
762 OS << ", plus " << ImmCost << " imm cost";
763 if (SetupCost != 0)
764 OS << ", plus " << SetupCost << " setup cost";
765}
766
767void Cost::dump() const {
768 print(errs()); errs() << '\n';
769}
770
771namespace {
772
773/// LSRFixup - An operand value in an instruction which is to be replaced
774/// with some equivalent, possibly strength-reduced, replacement.
775struct LSRFixup {
776 /// UserInst - The instruction which will be updated.
777 Instruction *UserInst;
778
779 /// OperandValToReplace - The operand of the instruction which will
780 /// be replaced. The operand may be used more than once; every instance
781 /// will be replaced.
782 Value *OperandValToReplace;
783
784 /// PostIncLoop - If this user is to use the post-incremented value of an
785 /// induction variable, this variable is non-null and holds the loop
786 /// associated with the induction variable.
787 const Loop *PostIncLoop;
788
789 /// LUIdx - The index of the LSRUse describing the expression which
790 /// this fixup needs, minus an offset (below).
791 size_t LUIdx;
792
793 /// Offset - A constant offset to be added to the LSRUse expression.
794 /// This allows multiple fixups to share the same LSRUse with different
795 /// offsets, for example in an unrolled loop.
796 int64_t Offset;
797
798 LSRFixup();
799
800 void print(raw_ostream &OS) const;
801 void dump() const;
802};
803
804}
805
806LSRFixup::LSRFixup()
807 : UserInst(0), OperandValToReplace(0), PostIncLoop(0),
808 LUIdx(~size_t(0)), Offset(0) {}
809
810void LSRFixup::print(raw_ostream &OS) const {
811 OS << "UserInst=";
812 // Store is common and interesting enough to be worth special-casing.
813 if (StoreInst *Store = dyn_cast<StoreInst>(UserInst)) {
814 OS << "store ";
815 WriteAsOperand(OS, Store->getOperand(0), /*PrintType=*/false);
816 } else if (UserInst->getType()->isVoidTy())
817 OS << UserInst->getOpcodeName();
818 else
819 WriteAsOperand(OS, UserInst, /*PrintType=*/false);
820
821 OS << ", OperandValToReplace=";
822 WriteAsOperand(OS, OperandValToReplace, /*PrintType=*/false);
823
824 if (PostIncLoop) {
825 OS << ", PostIncLoop=";
826 WriteAsOperand(OS, PostIncLoop->getHeader(), /*PrintType=*/false);
827 }
828
829 if (LUIdx != ~size_t(0))
830 OS << ", LUIdx=" << LUIdx;
831
832 if (Offset != 0)
833 OS << ", Offset=" << Offset;
834}
835
836void LSRFixup::dump() const {
837 print(errs()); errs() << '\n';
838}
839
840namespace {
841
842/// UniquifierDenseMapInfo - A DenseMapInfo implementation for holding
843/// DenseMaps and DenseSets of sorted SmallVectors of const SCEV*.
844struct UniquifierDenseMapInfo {
845 static SmallVector<const SCEV *, 2> getEmptyKey() {
846 SmallVector<const SCEV *, 2> V;
847 V.push_back(reinterpret_cast<const SCEV *>(-1));
848 return V;
849 }
850
851 static SmallVector<const SCEV *, 2> getTombstoneKey() {
852 SmallVector<const SCEV *, 2> V;
853 V.push_back(reinterpret_cast<const SCEV *>(-2));
854 return V;
855 }
856
857 static unsigned getHashValue(const SmallVector<const SCEV *, 2> &V) {
858 unsigned Result = 0;
859 for (SmallVectorImpl<const SCEV *>::const_iterator I = V.begin(),
860 E = V.end(); I != E; ++I)
861 Result ^= DenseMapInfo<const SCEV *>::getHashValue(*I);
862 return Result;
863 }
864
865 static bool isEqual(const SmallVector<const SCEV *, 2> &LHS,
866 const SmallVector<const SCEV *, 2> &RHS) {
867 return LHS == RHS;
868 }
869};
870
871/// LSRUse - This class holds the state that LSR keeps for each use in
872/// IVUsers, as well as uses invented by LSR itself. It includes information
873/// about what kinds of things can be folded into the user, information about
874/// the user itself, and information about how the use may be satisfied.
875/// TODO: Represent multiple users of the same expression in common?
876class LSRUse {
877 DenseSet<SmallVector<const SCEV *, 2>, UniquifierDenseMapInfo> Uniquifier;
878
879public:
880 /// KindType - An enum for a kind of use, indicating what types of
881 /// scaled and immediate operands it might support.
882 enum KindType {
883 Basic, ///< A normal use, with no folding.
884 Special, ///< A special case of basic, allowing -1 scales.
885 Address, ///< An address use; folding according to TargetLowering
886 ICmpZero ///< An equality icmp with both operands folded into one.
887 // TODO: Add a generic icmp too?
Dan Gohman7979b722010-01-22 00:46:49 +0000888 };
Dan Gohman572645c2010-02-12 10:34:29 +0000889
890 KindType Kind;
891 const Type *AccessTy;
892
893 SmallVector<int64_t, 8> Offsets;
894 int64_t MinOffset;
895 int64_t MaxOffset;
896
897 /// AllFixupsOutsideLoop - This records whether all of the fixups using this
898 /// LSRUse are outside of the loop, in which case some special-case heuristics
899 /// may be used.
900 bool AllFixupsOutsideLoop;
901
902 /// Formulae - A list of ways to build a value that can satisfy this user.
903 /// After the list is populated, one of these is selected heuristically and
904 /// used to formulate a replacement for OperandValToReplace in UserInst.
905 SmallVector<Formula, 12> Formulae;
906
907 /// Regs - The set of register candidates used by all formulae in this LSRUse.
908 SmallPtrSet<const SCEV *, 4> Regs;
909
910 LSRUse(KindType K, const Type *T) : Kind(K), AccessTy(T),
911 MinOffset(INT64_MAX),
912 MaxOffset(INT64_MIN),
913 AllFixupsOutsideLoop(true) {}
914
915 bool InsertFormula(size_t LUIdx, const Formula &F);
916
917 void check() const;
918
919 void print(raw_ostream &OS) const;
920 void dump() const;
921};
922
923/// InsertFormula - If the given formula has not yet been inserted, add it to
924/// the list, and return true. Return false otherwise.
925bool LSRUse::InsertFormula(size_t LUIdx, const Formula &F) {
926 SmallVector<const SCEV *, 2> Key = F.BaseRegs;
927 if (F.ScaledReg) Key.push_back(F.ScaledReg);
928 // Unstable sort by host order ok, because this is only used for uniquifying.
929 std::sort(Key.begin(), Key.end());
930
931 if (!Uniquifier.insert(Key).second)
932 return false;
933
934 // Using a register to hold the value of 0 is not profitable.
935 assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&
936 "Zero allocated in a scaled register!");
937#ifndef NDEBUG
938 for (SmallVectorImpl<const SCEV *>::const_iterator I =
939 F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I)
940 assert(!(*I)->isZero() && "Zero allocated in a base register!");
941#endif
942
943 // Add the formula to the list.
944 Formulae.push_back(F);
945
946 // Record registers now being used by this use.
947 if (F.ScaledReg) Regs.insert(F.ScaledReg);
948 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
949
950 return true;
Dan Gohman7979b722010-01-22 00:46:49 +0000951}
952
Dan Gohman572645c2010-02-12 10:34:29 +0000953void LSRUse::print(raw_ostream &OS) const {
954 OS << "LSR Use: Kind=";
955 switch (Kind) {
956 case Basic: OS << "Basic"; break;
957 case Special: OS << "Special"; break;
958 case ICmpZero: OS << "ICmpZero"; break;
959 case Address:
960 OS << "Address of ";
Duncan Sands1df98592010-02-16 11:11:14 +0000961 if (AccessTy->isPointerTy())
Dan Gohman572645c2010-02-12 10:34:29 +0000962 OS << "pointer"; // the full pointer type could be really verbose
963 else
964 OS << *AccessTy;
Evan Chengcdf43b12007-10-25 09:11:16 +0000965 }
966
Dan Gohman572645c2010-02-12 10:34:29 +0000967 OS << ", Offsets={";
968 for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
969 E = Offsets.end(); I != E; ++I) {
970 OS << *I;
971 if (next(I) != E)
972 OS << ',';
Dan Gohman7979b722010-01-22 00:46:49 +0000973 }
Dan Gohman572645c2010-02-12 10:34:29 +0000974 OS << '}';
Dan Gohman7979b722010-01-22 00:46:49 +0000975
Dan Gohman572645c2010-02-12 10:34:29 +0000976 if (AllFixupsOutsideLoop)
977 OS << ", all-fixups-outside-loop";
Dan Gohman7979b722010-01-22 00:46:49 +0000978}
979
Dan Gohman572645c2010-02-12 10:34:29 +0000980void LSRUse::dump() const {
981 print(errs()); errs() << '\n';
982}
Dan Gohman7979b722010-01-22 00:46:49 +0000983
Dan Gohman572645c2010-02-12 10:34:29 +0000984/// isLegalUse - Test whether the use described by AM is "legal", meaning it can
985/// be completely folded into the user instruction at isel time. This includes
986/// address-mode folding and special icmp tricks.
987static bool isLegalUse(const TargetLowering::AddrMode &AM,
988 LSRUse::KindType Kind, const Type *AccessTy,
989 const TargetLowering *TLI) {
990 switch (Kind) {
991 case LSRUse::Address:
992 // If we have low-level target information, ask the target if it can
993 // completely fold this address.
994 if (TLI) return TLI->isLegalAddressingMode(AM, AccessTy);
995
996 // Otherwise, just guess that reg+reg addressing is legal.
997 return !AM.BaseGV && AM.BaseOffs == 0 && AM.Scale <= 1;
998
999 case LSRUse::ICmpZero:
1000 // There's not even a target hook for querying whether it would be legal to
1001 // fold a GV into an ICmp.
1002 if (AM.BaseGV)
1003 return false;
1004
1005 // ICmp only has two operands; don't allow more than two non-trivial parts.
1006 if (AM.Scale != 0 && AM.HasBaseReg && AM.BaseOffs != 0)
1007 return false;
1008
1009 // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by
1010 // putting the scaled register in the other operand of the icmp.
1011 if (AM.Scale != 0 && AM.Scale != -1)
1012 return false;
1013
1014 // If we have low-level target information, ask the target if it can fold an
1015 // integer immediate on an icmp.
1016 if (AM.BaseOffs != 0) {
1017 if (TLI) return TLI->isLegalICmpImmediate(-AM.BaseOffs);
1018 return false;
Dan Gohman7979b722010-01-22 00:46:49 +00001019 }
Dan Gohman572645c2010-02-12 10:34:29 +00001020
1021 return true;
1022
1023 case LSRUse::Basic:
1024 // Only handle single-register values.
1025 return !AM.BaseGV && AM.Scale == 0 && AM.BaseOffs == 0;
1026
1027 case LSRUse::Special:
1028 // Only handle -1 scales, or no scale.
1029 return AM.Scale == 0 || AM.Scale == -1;
Dan Gohman7979b722010-01-22 00:46:49 +00001030 }
1031
Dan Gohman7979b722010-01-22 00:46:49 +00001032 return false;
1033}
1034
Dan Gohman572645c2010-02-12 10:34:29 +00001035static bool isLegalUse(TargetLowering::AddrMode AM,
1036 int64_t MinOffset, int64_t MaxOffset,
1037 LSRUse::KindType Kind, const Type *AccessTy,
1038 const TargetLowering *TLI) {
1039 // Check for overflow.
1040 if (((int64_t)((uint64_t)AM.BaseOffs + MinOffset) > AM.BaseOffs) !=
1041 (MinOffset > 0))
1042 return false;
1043 AM.BaseOffs = (uint64_t)AM.BaseOffs + MinOffset;
1044 if (isLegalUse(AM, Kind, AccessTy, TLI)) {
1045 AM.BaseOffs = (uint64_t)AM.BaseOffs - MinOffset;
1046 // Check for overflow.
1047 if (((int64_t)((uint64_t)AM.BaseOffs + MaxOffset) > AM.BaseOffs) !=
1048 (MaxOffset > 0))
1049 return false;
1050 AM.BaseOffs = (uint64_t)AM.BaseOffs + MaxOffset;
1051 return isLegalUse(AM, Kind, AccessTy, TLI);
Dan Gohman7979b722010-01-22 00:46:49 +00001052 }
Dan Gohman572645c2010-02-12 10:34:29 +00001053 return false;
Dan Gohman7979b722010-01-22 00:46:49 +00001054}
1055
Dan Gohman572645c2010-02-12 10:34:29 +00001056static bool isAlwaysFoldable(int64_t BaseOffs,
1057 GlobalValue *BaseGV,
1058 bool HasBaseReg,
1059 LSRUse::KindType Kind, const Type *AccessTy,
1060 const TargetLowering *TLI,
1061 ScalarEvolution &SE) {
1062 // Fast-path: zero is always foldable.
1063 if (BaseOffs == 0 && !BaseGV) return true;
Dan Gohman7979b722010-01-22 00:46:49 +00001064
Dan Gohman572645c2010-02-12 10:34:29 +00001065 // Conservatively, create an address with an immediate and a
1066 // base and a scale.
1067 TargetLowering::AddrMode AM;
1068 AM.BaseOffs = BaseOffs;
1069 AM.BaseGV = BaseGV;
1070 AM.HasBaseReg = HasBaseReg;
1071 AM.Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
Dan Gohman7979b722010-01-22 00:46:49 +00001072
Dan Gohman572645c2010-02-12 10:34:29 +00001073 return isLegalUse(AM, Kind, AccessTy, TLI);
Dan Gohman7979b722010-01-22 00:46:49 +00001074}
1075
Dan Gohman572645c2010-02-12 10:34:29 +00001076static bool isAlwaysFoldable(const SCEV *S,
1077 int64_t MinOffset, int64_t MaxOffset,
1078 bool HasBaseReg,
1079 LSRUse::KindType Kind, const Type *AccessTy,
1080 const TargetLowering *TLI,
1081 ScalarEvolution &SE) {
1082 // Fast-path: zero is always foldable.
1083 if (S->isZero()) return true;
1084
1085 // Conservatively, create an address with an immediate and a
1086 // base and a scale.
1087 int64_t BaseOffs = ExtractImmediate(S, SE);
1088 GlobalValue *BaseGV = ExtractSymbol(S, SE);
1089
1090 // If there's anything else involved, it's not foldable.
1091 if (!S->isZero()) return false;
1092
1093 // Fast-path: zero is always foldable.
1094 if (BaseOffs == 0 && !BaseGV) return true;
1095
1096 // Conservatively, create an address with an immediate and a
1097 // base and a scale.
1098 TargetLowering::AddrMode AM;
1099 AM.BaseOffs = BaseOffs;
1100 AM.BaseGV = BaseGV;
1101 AM.HasBaseReg = HasBaseReg;
1102 AM.Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1103
1104 return isLegalUse(AM, MinOffset, MaxOffset, Kind, AccessTy, TLI);
Dan Gohman7979b722010-01-22 00:46:49 +00001105}
1106
Dan Gohman572645c2010-02-12 10:34:29 +00001107/// FormulaSorter - This class implements an ordering for formulae which sorts
1108/// the by their standalone cost.
1109class FormulaSorter {
1110 /// These two sets are kept empty, so that we compute standalone costs.
1111 DenseSet<const SCEV *> VisitedRegs;
1112 SmallPtrSet<const SCEV *, 16> Regs;
1113 Loop *L;
1114 LSRUse *LU;
1115 ScalarEvolution &SE;
1116 DominatorTree &DT;
1117
1118public:
1119 FormulaSorter(Loop *l, LSRUse &lu, ScalarEvolution &se, DominatorTree &dt)
1120 : L(l), LU(&lu), SE(se), DT(dt) {}
1121
1122 bool operator()(const Formula &A, const Formula &B) {
1123 Cost CostA;
1124 CostA.RateFormula(A, Regs, VisitedRegs, L, LU->Offsets, SE, DT);
1125 Regs.clear();
1126 Cost CostB;
1127 CostB.RateFormula(B, Regs, VisitedRegs, L, LU->Offsets, SE, DT);
1128 Regs.clear();
1129 return CostA < CostB;
1130 }
1131};
1132
1133/// LSRInstance - This class holds state for the main loop strength reduction
1134/// logic.
1135class LSRInstance {
1136 IVUsers &IU;
1137 ScalarEvolution &SE;
1138 DominatorTree &DT;
1139 const TargetLowering *const TLI;
1140 Loop *const L;
1141 bool Changed;
1142
1143 /// IVIncInsertPos - This is the insert position that the current loop's
1144 /// induction variable increment should be placed. In simple loops, this is
1145 /// the latch block's terminator. But in more complicated cases, this is a
1146 /// position which will dominate all the in-loop post-increment users.
1147 Instruction *IVIncInsertPos;
1148
1149 /// Factors - Interesting factors between use strides.
1150 SmallSetVector<int64_t, 8> Factors;
1151
1152 /// Types - Interesting use types, to facilitate truncation reuse.
1153 SmallSetVector<const Type *, 4> Types;
1154
1155 /// Fixups - The list of operands which are to be replaced.
1156 SmallVector<LSRFixup, 16> Fixups;
1157
1158 /// Uses - The list of interesting uses.
1159 SmallVector<LSRUse, 16> Uses;
1160
1161 /// RegUses - Track which uses use which register candidates.
1162 RegUseTracker RegUses;
1163
1164 void OptimizeShadowIV();
1165 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse);
1166 ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse);
1167 bool OptimizeLoopTermCond();
1168
1169 void CollectInterestingTypesAndFactors();
1170 void CollectFixupsAndInitialFormulae();
1171
1172 LSRFixup &getNewFixup() {
1173 Fixups.push_back(LSRFixup());
1174 return Fixups.back();
1175 }
1176
1177 // Support for sharing of LSRUses between LSRFixups.
1178 typedef DenseMap<const SCEV *, size_t> UseMapTy;
1179 UseMapTy UseMap;
1180
1181 bool reconcileNewOffset(LSRUse &LU, int64_t NewOffset,
1182 LSRUse::KindType Kind, const Type *AccessTy);
1183
1184 std::pair<size_t, int64_t> getUse(const SCEV *&Expr,
1185 LSRUse::KindType Kind,
1186 const Type *AccessTy);
1187
1188public:
1189 void InsertInitialFormula(const SCEV *S, Loop *L, LSRUse &LU, size_t LUIdx);
1190 void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
1191 void CountRegisters(const Formula &F, size_t LUIdx);
1192 bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F);
1193
1194 void CollectLoopInvariantFixupsAndFormulae();
1195
1196 void GenerateReassociations(LSRUse &LU, unsigned LUIdx, Formula Base,
1197 unsigned Depth = 0);
1198 void GenerateCombinations(LSRUse &LU, unsigned LUIdx, Formula Base);
1199 void GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1200 void GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1201 void GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1202 void GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1203 void GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base);
1204 void GenerateCrossUseConstantOffsets();
1205 void GenerateAllReuseFormulae();
1206
1207 void FilterOutUndesirableDedicatedRegisters();
1208 void NarrowSearchSpaceUsingHeuristics();
1209
1210 void SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
1211 Cost &SolutionCost,
1212 SmallVectorImpl<const Formula *> &Workspace,
1213 const Cost &CurCost,
1214 const SmallPtrSet<const SCEV *, 16> &CurRegs,
1215 DenseSet<const SCEV *> &VisitedRegs) const;
1216 void Solve(SmallVectorImpl<const Formula *> &Solution) const;
1217
1218 Value *Expand(const LSRFixup &LF,
1219 const Formula &F,
1220 BasicBlock::iterator IP, Loop *L, Instruction *IVIncInsertPos,
1221 SCEVExpander &Rewriter,
1222 SmallVectorImpl<WeakVH> &DeadInsts,
1223 ScalarEvolution &SE, DominatorTree &DT) const;
Dan Gohman3a02cbc2010-02-16 20:25:07 +00001224 void RewriteForPHI(PHINode *PN, const LSRFixup &LF,
1225 const Formula &F,
1226 Loop *L, Instruction *IVIncInsertPos,
1227 SCEVExpander &Rewriter,
1228 SmallVectorImpl<WeakVH> &DeadInsts,
1229 ScalarEvolution &SE, DominatorTree &DT,
1230 Pass *P) const;
Dan Gohman572645c2010-02-12 10:34:29 +00001231 void Rewrite(const LSRFixup &LF,
1232 const Formula &F,
1233 Loop *L, Instruction *IVIncInsertPos,
1234 SCEVExpander &Rewriter,
1235 SmallVectorImpl<WeakVH> &DeadInsts,
1236 ScalarEvolution &SE, DominatorTree &DT,
1237 Pass *P) const;
1238 void ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
1239 Pass *P);
1240
1241 LSRInstance(const TargetLowering *tli, Loop *l, Pass *P);
1242
1243 bool getChanged() const { return Changed; }
1244
1245 void print_factors_and_types(raw_ostream &OS) const;
1246 void print_fixups(raw_ostream &OS) const;
1247 void print_uses(raw_ostream &OS) const;
1248 void print(raw_ostream &OS) const;
1249 void dump() const;
1250};
1251
1252}
1253
1254/// OptimizeShadowIV - If IV is used in a int-to-float cast
1255/// inside the loop then try to eliminate the cast opeation.
1256void LSRInstance::OptimizeShadowIV() {
1257 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
1258 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1259 return;
1260
1261 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end();
1262 UI != E; /* empty */) {
1263 IVUsers::const_iterator CandidateUI = UI;
1264 ++UI;
1265 Instruction *ShadowUse = CandidateUI->getUser();
1266 const Type *DestTy = NULL;
1267
1268 /* If shadow use is a int->float cast then insert a second IV
1269 to eliminate this cast.
1270
1271 for (unsigned i = 0; i < n; ++i)
1272 foo((double)i);
1273
1274 is transformed into
1275
1276 double d = 0.0;
1277 for (unsigned i = 0; i < n; ++i, ++d)
1278 foo(d);
1279 */
1280 if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser()))
1281 DestTy = UCast->getDestTy();
1282 else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser()))
1283 DestTy = SCast->getDestTy();
1284 if (!DestTy) continue;
1285
1286 if (TLI) {
1287 // If target does not support DestTy natively then do not apply
1288 // this transformation.
1289 EVT DVT = TLI->getValueType(DestTy);
1290 if (!TLI->isTypeLegal(DVT)) continue;
1291 }
1292
1293 PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
1294 if (!PH) continue;
1295 if (PH->getNumIncomingValues() != 2) continue;
1296
1297 const Type *SrcTy = PH->getType();
1298 int Mantissa = DestTy->getFPMantissaWidth();
1299 if (Mantissa == -1) continue;
1300 if ((int)SE.getTypeSizeInBits(SrcTy) > Mantissa)
1301 continue;
1302
1303 unsigned Entry, Latch;
1304 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
1305 Entry = 0;
1306 Latch = 1;
Dan Gohman7979b722010-01-22 00:46:49 +00001307 } else {
Dan Gohman572645c2010-02-12 10:34:29 +00001308 Entry = 1;
1309 Latch = 0;
Dan Gohman7979b722010-01-22 00:46:49 +00001310 }
Dan Gohman7979b722010-01-22 00:46:49 +00001311
Dan Gohman572645c2010-02-12 10:34:29 +00001312 ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
1313 if (!Init) continue;
1314 Constant *NewInit = ConstantFP::get(DestTy, Init->getZExtValue());
Dan Gohman7979b722010-01-22 00:46:49 +00001315
Dan Gohman572645c2010-02-12 10:34:29 +00001316 BinaryOperator *Incr =
1317 dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
1318 if (!Incr) continue;
1319 if (Incr->getOpcode() != Instruction::Add
1320 && Incr->getOpcode() != Instruction::Sub)
Dan Gohman7979b722010-01-22 00:46:49 +00001321 continue;
Dan Gohman7979b722010-01-22 00:46:49 +00001322
Dan Gohman572645c2010-02-12 10:34:29 +00001323 /* Initialize new IV, double d = 0.0 in above example. */
1324 ConstantInt *C = NULL;
1325 if (Incr->getOperand(0) == PH)
1326 C = dyn_cast<ConstantInt>(Incr->getOperand(1));
1327 else if (Incr->getOperand(1) == PH)
1328 C = dyn_cast<ConstantInt>(Incr->getOperand(0));
Dan Gohman7979b722010-01-22 00:46:49 +00001329 else
Dan Gohman7979b722010-01-22 00:46:49 +00001330 continue;
1331
Dan Gohman572645c2010-02-12 10:34:29 +00001332 if (!C) continue;
Dan Gohman7979b722010-01-22 00:46:49 +00001333
Dan Gohman572645c2010-02-12 10:34:29 +00001334 // Ignore negative constants, as the code below doesn't handle them
1335 // correctly. TODO: Remove this restriction.
1336 if (!C->getValue().isStrictlyPositive()) continue;
Dan Gohman7979b722010-01-22 00:46:49 +00001337
Dan Gohman572645c2010-02-12 10:34:29 +00001338 /* Add new PHINode. */
1339 PHINode *NewPH = PHINode::Create(DestTy, "IV.S.", PH);
Dan Gohman7979b722010-01-22 00:46:49 +00001340
Dan Gohman572645c2010-02-12 10:34:29 +00001341 /* create new increment. '++d' in above example. */
1342 Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue());
1343 BinaryOperator *NewIncr =
1344 BinaryOperator::Create(Incr->getOpcode() == Instruction::Add ?
1345 Instruction::FAdd : Instruction::FSub,
1346 NewPH, CFP, "IV.S.next.", Incr);
Dan Gohman7979b722010-01-22 00:46:49 +00001347
Dan Gohman572645c2010-02-12 10:34:29 +00001348 NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
1349 NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
Dan Gohman7979b722010-01-22 00:46:49 +00001350
Dan Gohman572645c2010-02-12 10:34:29 +00001351 /* Remove cast operation */
1352 ShadowUse->replaceAllUsesWith(NewPH);
1353 ShadowUse->eraseFromParent();
1354 break;
Dan Gohman7979b722010-01-22 00:46:49 +00001355 }
1356}
1357
1358/// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
1359/// set the IV user and stride information and return true, otherwise return
1360/// false.
Dan Gohman572645c2010-02-12 10:34:29 +00001361bool LSRInstance::FindIVUserForCond(ICmpInst *Cond,
1362 IVStrideUse *&CondUse) {
1363 for (IVUsers::iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
1364 if (UI->getUser() == Cond) {
1365 // NOTE: we could handle setcc instructions with multiple uses here, but
1366 // InstCombine does it as well for simple uses, it's not clear that it
1367 // occurs enough in real life to handle.
1368 CondUse = UI;
1369 return true;
1370 }
Dan Gohman7979b722010-01-22 00:46:49 +00001371 return false;
Evan Chengcdf43b12007-10-25 09:11:16 +00001372}
1373
Dan Gohman7979b722010-01-22 00:46:49 +00001374/// OptimizeMax - Rewrite the loop's terminating condition if it uses
1375/// a max computation.
1376///
1377/// This is a narrow solution to a specific, but acute, problem. For loops
1378/// like this:
1379///
1380/// i = 0;
1381/// do {
1382/// p[i] = 0.0;
1383/// } while (++i < n);
1384///
1385/// the trip count isn't just 'n', because 'n' might not be positive. And
1386/// unfortunately this can come up even for loops where the user didn't use
1387/// a C do-while loop. For example, seemingly well-behaved top-test loops
1388/// will commonly be lowered like this:
1389//
1390/// if (n > 0) {
1391/// i = 0;
1392/// do {
1393/// p[i] = 0.0;
1394/// } while (++i < n);
1395/// }
1396///
1397/// and then it's possible for subsequent optimization to obscure the if
1398/// test in such a way that indvars can't find it.
1399///
1400/// When indvars can't find the if test in loops like this, it creates a
1401/// max expression, which allows it to give the loop a canonical
1402/// induction variable:
1403///
1404/// i = 0;
1405/// max = n < 1 ? 1 : n;
1406/// do {
1407/// p[i] = 0.0;
1408/// } while (++i != max);
1409///
1410/// Canonical induction variables are necessary because the loop passes
1411/// are designed around them. The most obvious example of this is the
1412/// LoopInfo analysis, which doesn't remember trip count values. It
1413/// expects to be able to rediscover the trip count each time it is
Dan Gohman572645c2010-02-12 10:34:29 +00001414/// needed, and it does this using a simple analysis that only succeeds if
Dan Gohman7979b722010-01-22 00:46:49 +00001415/// the loop has a canonical induction variable.
1416///
1417/// However, when it comes time to generate code, the maximum operation
1418/// can be quite costly, especially if it's inside of an outer loop.
1419///
1420/// This function solves this problem by detecting this type of loop and
1421/// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
1422/// the instructions for the maximum computation.
1423///
Dan Gohman572645c2010-02-12 10:34:29 +00001424ICmpInst *LSRInstance::OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse) {
Dan Gohman7979b722010-01-22 00:46:49 +00001425 // Check that the loop matches the pattern we're looking for.
1426 if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
1427 Cond->getPredicate() != CmpInst::ICMP_NE)
1428 return Cond;
Dan Gohmana10756e2010-01-21 02:09:26 +00001429
Dan Gohman7979b722010-01-22 00:46:49 +00001430 SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
1431 if (!Sel || !Sel->hasOneUse()) return Cond;
Dan Gohmana10756e2010-01-21 02:09:26 +00001432
Dan Gohman572645c2010-02-12 10:34:29 +00001433 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
Dan Gohman7979b722010-01-22 00:46:49 +00001434 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1435 return Cond;
Dan Gohman572645c2010-02-12 10:34:29 +00001436 const SCEV *One = SE.getIntegerSCEV(1, BackedgeTakenCount->getType());
Dan Gohmana10756e2010-01-21 02:09:26 +00001437
Dan Gohman7979b722010-01-22 00:46:49 +00001438 // Add one to the backedge-taken count to get the trip count.
Dan Gohman572645c2010-02-12 10:34:29 +00001439 const SCEV *IterationCount = SE.getAddExpr(BackedgeTakenCount, One);
Dan Gohman7979b722010-01-22 00:46:49 +00001440
1441 // Check for a max calculation that matches the pattern.
1442 if (!isa<SCEVSMaxExpr>(IterationCount) && !isa<SCEVUMaxExpr>(IterationCount))
1443 return Cond;
1444 const SCEVNAryExpr *Max = cast<SCEVNAryExpr>(IterationCount);
Dan Gohman572645c2010-02-12 10:34:29 +00001445 if (Max != SE.getSCEV(Sel)) return Cond;
Dan Gohman7979b722010-01-22 00:46:49 +00001446
1447 // To handle a max with more than two operands, this optimization would
1448 // require additional checking and setup.
1449 if (Max->getNumOperands() != 2)
1450 return Cond;
1451
1452 const SCEV *MaxLHS = Max->getOperand(0);
1453 const SCEV *MaxRHS = Max->getOperand(1);
1454 if (!MaxLHS || MaxLHS != One) return Cond;
Dan Gohman7979b722010-01-22 00:46:49 +00001455 // Check the relevant induction variable for conformance to
1456 // the pattern.
Dan Gohman572645c2010-02-12 10:34:29 +00001457 const SCEV *IV = SE.getSCEV(Cond->getOperand(0));
Dan Gohman7979b722010-01-22 00:46:49 +00001458 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
1459 if (!AR || !AR->isAffine() ||
1460 AR->getStart() != One ||
Dan Gohman572645c2010-02-12 10:34:29 +00001461 AR->getStepRecurrence(SE) != One)
Dan Gohman7979b722010-01-22 00:46:49 +00001462 return Cond;
1463
1464 assert(AR->getLoop() == L &&
1465 "Loop condition operand is an addrec in a different loop!");
1466
1467 // Check the right operand of the select, and remember it, as it will
1468 // be used in the new comparison instruction.
1469 Value *NewRHS = 0;
Dan Gohman572645c2010-02-12 10:34:29 +00001470 if (SE.getSCEV(Sel->getOperand(1)) == MaxRHS)
Dan Gohman7979b722010-01-22 00:46:49 +00001471 NewRHS = Sel->getOperand(1);
Dan Gohman572645c2010-02-12 10:34:29 +00001472 else if (SE.getSCEV(Sel->getOperand(2)) == MaxRHS)
Dan Gohman7979b722010-01-22 00:46:49 +00001473 NewRHS = Sel->getOperand(2);
1474 if (!NewRHS) return Cond;
1475
1476 // Determine the new comparison opcode. It may be signed or unsigned,
1477 // and the original comparison may be either equality or inequality.
1478 CmpInst::Predicate Pred =
1479 isa<SCEVSMaxExpr>(Max) ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;
1480 if (Cond->getPredicate() == CmpInst::ICMP_EQ)
1481 Pred = CmpInst::getInversePredicate(Pred);
1482
1483 // Ok, everything looks ok to change the condition into an SLT or SGE and
1484 // delete the max calculation.
1485 ICmpInst *NewCond =
1486 new ICmpInst(Cond, Pred, Cond->getOperand(0), NewRHS, "scmp");
1487
1488 // Delete the max calculation instructions.
1489 Cond->replaceAllUsesWith(NewCond);
1490 CondUse->setUser(NewCond);
1491 Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
1492 Cond->eraseFromParent();
1493 Sel->eraseFromParent();
1494 if (Cmp->use_empty())
1495 Cmp->eraseFromParent();
1496 return NewCond;
Dan Gohmanad7321f2008-09-15 21:22:06 +00001497}
1498
Jim Grosbach56a1f802009-11-17 17:53:56 +00001499/// OptimizeLoopTermCond - Change loop terminating condition to use the
Evan Cheng586f69a2009-11-12 07:35:05 +00001500/// postinc iv when possible.
Dan Gohman572645c2010-02-12 10:34:29 +00001501bool
1502LSRInstance::OptimizeLoopTermCond() {
1503 SmallPtrSet<Instruction *, 4> PostIncs;
1504
Evan Cheng586f69a2009-11-12 07:35:05 +00001505 BasicBlock *LatchBlock = L->getLoopLatch();
Evan Cheng076e0852009-11-17 18:10:11 +00001506 SmallVector<BasicBlock*, 8> ExitingBlocks;
1507 L->getExitingBlocks(ExitingBlocks);
Jim Grosbach56a1f802009-11-17 17:53:56 +00001508
Evan Cheng076e0852009-11-17 18:10:11 +00001509 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
1510 BasicBlock *ExitingBlock = ExitingBlocks[i];
Evan Cheng586f69a2009-11-12 07:35:05 +00001511
Dan Gohman572645c2010-02-12 10:34:29 +00001512 // Get the terminating condition for the loop if possible. If we
Evan Cheng076e0852009-11-17 18:10:11 +00001513 // can, we want to change it to use a post-incremented version of its
1514 // induction variable, to allow coalescing the live ranges for the IV into
1515 // one register value.
Evan Cheng586f69a2009-11-12 07:35:05 +00001516
Evan Cheng076e0852009-11-17 18:10:11 +00001517 BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1518 if (!TermBr)
1519 continue;
1520 // FIXME: Overly conservative, termination condition could be an 'or' etc..
1521 if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
1522 continue;
Evan Cheng586f69a2009-11-12 07:35:05 +00001523
Evan Cheng076e0852009-11-17 18:10:11 +00001524 // Search IVUsesByStride to find Cond's IVUse if there is one.
1525 IVStrideUse *CondUse = 0;
Evan Cheng076e0852009-11-17 18:10:11 +00001526 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
Dan Gohman572645c2010-02-12 10:34:29 +00001527 if (!FindIVUserForCond(Cond, CondUse))
Evan Cheng076e0852009-11-17 18:10:11 +00001528 continue;
1529
Evan Cheng076e0852009-11-17 18:10:11 +00001530 // If the trip count is computed in terms of a max (due to ScalarEvolution
1531 // being unable to find a sufficient guard, for example), change the loop
1532 // comparison to use SLT or ULT instead of NE.
Dan Gohman572645c2010-02-12 10:34:29 +00001533 // One consequence of doing this now is that it disrupts the count-down
1534 // optimization. That's not always a bad thing though, because in such
1535 // cases it may still be worthwhile to avoid a max.
1536 Cond = OptimizeMax(Cond, CondUse);
Evan Cheng076e0852009-11-17 18:10:11 +00001537
Dan Gohman572645c2010-02-12 10:34:29 +00001538 // If this exiting block dominates the latch block, it may also use
1539 // the post-inc value if it won't be shared with other uses.
1540 // Check for dominance.
1541 if (!DT.dominates(ExitingBlock, LatchBlock))
Dan Gohman7979b722010-01-22 00:46:49 +00001542 continue;
Evan Cheng076e0852009-11-17 18:10:11 +00001543
Dan Gohman572645c2010-02-12 10:34:29 +00001544 // Conservatively avoid trying to use the post-inc value in non-latch
1545 // exits if there may be pre-inc users in intervening blocks.
Dan Gohman590bfe82010-02-14 03:21:49 +00001546 if (LatchBlock != ExitingBlock)
Dan Gohman572645c2010-02-12 10:34:29 +00001547 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
1548 // Test if the use is reachable from the exiting block. This dominator
1549 // query is a conservative approximation of reachability.
1550 if (&*UI != CondUse &&
1551 !DT.properlyDominates(UI->getUser()->getParent(), ExitingBlock)) {
1552 // Conservatively assume there may be reuse if the quotient of their
1553 // strides could be a legal scale.
1554 const SCEV *A = CondUse->getStride();
1555 const SCEV *B = UI->getStride();
1556 if (SE.getTypeSizeInBits(A->getType()) !=
1557 SE.getTypeSizeInBits(B->getType())) {
1558 if (SE.getTypeSizeInBits(A->getType()) >
1559 SE.getTypeSizeInBits(B->getType()))
1560 B = SE.getSignExtendExpr(B, A->getType());
1561 else
1562 A = SE.getSignExtendExpr(A, B->getType());
1563 }
1564 if (const SCEVConstant *D =
Dan Gohmanf09b7122010-02-19 19:35:48 +00001565 dyn_cast_or_null<SCEVConstant>(getExactSDiv(B, A, SE))) {
Dan Gohman572645c2010-02-12 10:34:29 +00001566 // Stride of one or negative one can have reuse with non-addresses.
1567 if (D->getValue()->isOne() ||
1568 D->getValue()->isAllOnesValue())
1569 goto decline_post_inc;
1570 // Avoid weird situations.
1571 if (D->getValue()->getValue().getMinSignedBits() >= 64 ||
1572 D->getValue()->getValue().isMinSignedValue())
1573 goto decline_post_inc;
Dan Gohman590bfe82010-02-14 03:21:49 +00001574 // Without TLI, assume that any stride might be valid, and so any
1575 // use might be shared.
1576 if (!TLI)
1577 goto decline_post_inc;
Dan Gohman572645c2010-02-12 10:34:29 +00001578 // Check for possible scaled-address reuse.
1579 const Type *AccessTy = getAccessType(UI->getUser());
1580 TargetLowering::AddrMode AM;
1581 AM.Scale = D->getValue()->getSExtValue();
Dan Gohman2763dfd2010-02-14 02:45:21 +00001582 if (TLI->isLegalAddressingMode(AM, AccessTy))
Dan Gohman572645c2010-02-12 10:34:29 +00001583 goto decline_post_inc;
1584 AM.Scale = -AM.Scale;
Dan Gohman2763dfd2010-02-14 02:45:21 +00001585 if (TLI->isLegalAddressingMode(AM, AccessTy))
Dan Gohman572645c2010-02-12 10:34:29 +00001586 goto decline_post_inc;
1587 }
1588 }
1589
David Greene63c94632009-12-23 22:58:38 +00001590 DEBUG(dbgs() << " Change loop exiting icmp to use postinc iv: "
Dan Gohman572645c2010-02-12 10:34:29 +00001591 << *Cond << '\n');
Evan Cheng076e0852009-11-17 18:10:11 +00001592
1593 // It's possible for the setcc instruction to be anywhere in the loop, and
1594 // possible for it to have multiple users. If it is not immediately before
1595 // the exiting block branch, move it.
Dan Gohman572645c2010-02-12 10:34:29 +00001596 if (&*++BasicBlock::iterator(Cond) != TermBr) {
1597 if (Cond->hasOneUse()) {
Evan Cheng076e0852009-11-17 18:10:11 +00001598 Cond->moveBefore(TermBr);
1599 } else {
Dan Gohman572645c2010-02-12 10:34:29 +00001600 // Clone the terminating condition and insert into the loopend.
1601 ICmpInst *OldCond = Cond;
Evan Cheng076e0852009-11-17 18:10:11 +00001602 Cond = cast<ICmpInst>(Cond->clone());
1603 Cond->setName(L->getHeader()->getName() + ".termcond");
1604 ExitingBlock->getInstList().insert(TermBr, Cond);
1605
1606 // Clone the IVUse, as the old use still exists!
Dan Gohman572645c2010-02-12 10:34:29 +00001607 CondUse = &IU.AddUser(CondUse->getStride(), CondUse->getOffset(),
1608 Cond, CondUse->getOperandValToReplace());
1609 TermBr->replaceUsesOfWith(OldCond, Cond);
Evan Cheng076e0852009-11-17 18:10:11 +00001610 }
Evan Cheng586f69a2009-11-12 07:35:05 +00001611 }
1612
Evan Cheng076e0852009-11-17 18:10:11 +00001613 // If we get to here, we know that we can transform the setcc instruction to
1614 // use the post-incremented version of the IV, allowing us to coalesce the
1615 // live ranges for the IV correctly.
Dan Gohman572645c2010-02-12 10:34:29 +00001616 CondUse->setOffset(SE.getMinusSCEV(CondUse->getOffset(),
1617 CondUse->getStride()));
Evan Cheng076e0852009-11-17 18:10:11 +00001618 CondUse->setIsUseOfPostIncrementedValue(true);
1619 Changed = true;
1620
Dan Gohman572645c2010-02-12 10:34:29 +00001621 PostIncs.insert(Cond);
1622 decline_post_inc:;
Dan Gohmana10756e2010-01-21 02:09:26 +00001623 }
Dan Gohman572645c2010-02-12 10:34:29 +00001624
1625 // Determine an insertion point for the loop induction variable increment. It
1626 // must dominate all the post-inc comparisons we just set up, and it must
1627 // dominate the loop latch edge.
1628 IVIncInsertPos = L->getLoopLatch()->getTerminator();
1629 for (SmallPtrSet<Instruction *, 4>::const_iterator I = PostIncs.begin(),
1630 E = PostIncs.end(); I != E; ++I) {
1631 BasicBlock *BB =
1632 DT.findNearestCommonDominator(IVIncInsertPos->getParent(),
1633 (*I)->getParent());
1634 if (BB == (*I)->getParent())
1635 IVIncInsertPos = *I;
1636 else if (BB != IVIncInsertPos->getParent())
1637 IVIncInsertPos = BB->getTerminator();
1638 }
1639
1640 return Changed;
Dan Gohmana10756e2010-01-21 02:09:26 +00001641}
1642
Dan Gohman572645c2010-02-12 10:34:29 +00001643bool
1644LSRInstance::reconcileNewOffset(LSRUse &LU, int64_t NewOffset,
1645 LSRUse::KindType Kind, const Type *AccessTy) {
1646 int64_t NewMinOffset = LU.MinOffset;
1647 int64_t NewMaxOffset = LU.MaxOffset;
1648 const Type *NewAccessTy = AccessTy;
Dan Gohman7979b722010-01-22 00:46:49 +00001649
Dan Gohman572645c2010-02-12 10:34:29 +00001650 // Check for a mismatched kind. It's tempting to collapse mismatched kinds to
1651 // something conservative, however this can pessimize in the case that one of
1652 // the uses will have all its uses outside the loop, for example.
1653 if (LU.Kind != Kind)
Dan Gohman7979b722010-01-22 00:46:49 +00001654 return false;
Dan Gohman572645c2010-02-12 10:34:29 +00001655 // Conservatively assume HasBaseReg is true for now.
1656 if (NewOffset < LU.MinOffset) {
1657 if (!isAlwaysFoldable(LU.MaxOffset - NewOffset, 0, /*HasBaseReg=*/true,
1658 Kind, AccessTy, TLI, SE))
Dan Gohman7979b722010-01-22 00:46:49 +00001659 return false;
Dan Gohman572645c2010-02-12 10:34:29 +00001660 NewMinOffset = NewOffset;
1661 } else if (NewOffset > LU.MaxOffset) {
1662 if (!isAlwaysFoldable(NewOffset - LU.MinOffset, 0, /*HasBaseReg=*/true,
1663 Kind, AccessTy, TLI, SE))
Dan Gohman7979b722010-01-22 00:46:49 +00001664 return false;
Dan Gohman572645c2010-02-12 10:34:29 +00001665 NewMaxOffset = NewOffset;
Dan Gohmana10756e2010-01-21 02:09:26 +00001666 }
Dan Gohman572645c2010-02-12 10:34:29 +00001667 // Check for a mismatched access type, and fall back conservatively as needed.
1668 if (Kind == LSRUse::Address && AccessTy != LU.AccessTy)
1669 NewAccessTy = Type::getVoidTy(AccessTy->getContext());
Dan Gohmana10756e2010-01-21 02:09:26 +00001670
Dan Gohman572645c2010-02-12 10:34:29 +00001671 // Update the use.
1672 LU.MinOffset = NewMinOffset;
1673 LU.MaxOffset = NewMaxOffset;
1674 LU.AccessTy = NewAccessTy;
1675 if (NewOffset != LU.Offsets.back())
1676 LU.Offsets.push_back(NewOffset);
Dan Gohman8b0ade32010-01-21 22:42:49 +00001677 return true;
1678}
1679
Dan Gohman572645c2010-02-12 10:34:29 +00001680/// getUse - Return an LSRUse index and an offset value for a fixup which
1681/// needs the given expression, with the given kind and optional access type.
1682/// Either reuse an exisitng use or create a new one, as needed.
1683std::pair<size_t, int64_t>
1684LSRInstance::getUse(const SCEV *&Expr,
1685 LSRUse::KindType Kind, const Type *AccessTy) {
1686 const SCEV *Copy = Expr;
1687 int64_t Offset = ExtractImmediate(Expr, SE);
Evan Cheng586f69a2009-11-12 07:35:05 +00001688
Dan Gohman572645c2010-02-12 10:34:29 +00001689 // Basic uses can't accept any offset, for example.
1690 if (!isAlwaysFoldable(Offset, 0, /*HasBaseReg=*/true,
1691 Kind, AccessTy, TLI, SE)) {
1692 Expr = Copy;
1693 Offset = 0;
1694 }
1695
1696 std::pair<UseMapTy::iterator, bool> P =
1697 UseMap.insert(std::make_pair(Expr, 0));
1698 if (!P.second) {
1699 // A use already existed with this base.
1700 size_t LUIdx = P.first->second;
1701 LSRUse &LU = Uses[LUIdx];
1702 if (reconcileNewOffset(LU, Offset, Kind, AccessTy))
1703 // Reuse this use.
1704 return std::make_pair(LUIdx, Offset);
1705 }
1706
1707 // Create a new use.
1708 size_t LUIdx = Uses.size();
1709 P.first->second = LUIdx;
1710 Uses.push_back(LSRUse(Kind, AccessTy));
1711 LSRUse &LU = Uses[LUIdx];
1712
1713 // We don't need to track redundant offsets, but we don't need to go out
1714 // of our way here to avoid them.
1715 if (LU.Offsets.empty() || Offset != LU.Offsets.back())
1716 LU.Offsets.push_back(Offset);
1717
1718 LU.MinOffset = Offset;
1719 LU.MaxOffset = Offset;
1720 return std::make_pair(LUIdx, Offset);
1721}
1722
1723void LSRInstance::CollectInterestingTypesAndFactors() {
1724 SmallSetVector<const SCEV *, 4> Strides;
1725
Dan Gohman1b7bf182010-02-19 00:05:23 +00001726 // Collect interesting types and strides.
Dan Gohman572645c2010-02-12 10:34:29 +00001727 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
1728 const SCEV *Stride = UI->getStride();
1729
1730 // Collect interesting types.
1731 Types.insert(SE.getEffectiveSCEVType(Stride->getType()));
1732
Dan Gohman1b7bf182010-02-19 00:05:23 +00001733 // Add the stride for this loop.
1734 Strides.insert(Stride);
1735
1736 // Add strides for other mentioned loops.
1737 for (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(UI->getOffset());
1738 AR; AR = dyn_cast<SCEVAddRecExpr>(AR->getStart()))
1739 Strides.insert(AR->getStepRecurrence(SE));
1740 }
1741
1742 // Compute interesting factors from the set of interesting strides.
1743 for (SmallSetVector<const SCEV *, 4>::const_iterator
1744 I = Strides.begin(), E = Strides.end(); I != E; ++I)
Dan Gohman572645c2010-02-12 10:34:29 +00001745 for (SmallSetVector<const SCEV *, 4>::const_iterator NewStrideIter =
Dan Gohman1b7bf182010-02-19 00:05:23 +00001746 next(I); NewStrideIter != E; ++NewStrideIter) {
1747 const SCEV *OldStride = *I;
Dan Gohman572645c2010-02-12 10:34:29 +00001748 const SCEV *NewStride = *NewStrideIter;
Dan Gohman572645c2010-02-12 10:34:29 +00001749
1750 if (SE.getTypeSizeInBits(OldStride->getType()) !=
1751 SE.getTypeSizeInBits(NewStride->getType())) {
1752 if (SE.getTypeSizeInBits(OldStride->getType()) >
1753 SE.getTypeSizeInBits(NewStride->getType()))
1754 NewStride = SE.getSignExtendExpr(NewStride, OldStride->getType());
1755 else
1756 OldStride = SE.getSignExtendExpr(OldStride, NewStride->getType());
1757 }
1758 if (const SCEVConstant *Factor =
Dan Gohmanf09b7122010-02-19 19:35:48 +00001759 dyn_cast_or_null<SCEVConstant>(getExactSDiv(NewStride, OldStride,
1760 SE, true))) {
Dan Gohman572645c2010-02-12 10:34:29 +00001761 if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
1762 Factors.insert(Factor->getValue()->getValue().getSExtValue());
1763 } else if (const SCEVConstant *Factor =
Dan Gohmanf09b7122010-02-19 19:35:48 +00001764 dyn_cast_or_null<SCEVConstant>(getExactSDiv(OldStride, NewStride,
1765 SE, true))) {
Dan Gohman572645c2010-02-12 10:34:29 +00001766 if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
1767 Factors.insert(Factor->getValue()->getValue().getSExtValue());
1768 }
1769 }
Dan Gohman572645c2010-02-12 10:34:29 +00001770
1771 // If all uses use the same type, don't bother looking for truncation-based
1772 // reuse.
1773 if (Types.size() == 1)
1774 Types.clear();
1775
1776 DEBUG(print_factors_and_types(dbgs()));
1777}
1778
1779void LSRInstance::CollectFixupsAndInitialFormulae() {
1780 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
1781 // Record the uses.
1782 LSRFixup &LF = getNewFixup();
1783 LF.UserInst = UI->getUser();
1784 LF.OperandValToReplace = UI->getOperandValToReplace();
1785 if (UI->isUseOfPostIncrementedValue())
1786 LF.PostIncLoop = L;
1787
1788 LSRUse::KindType Kind = LSRUse::Basic;
1789 const Type *AccessTy = 0;
1790 if (isAddressUse(LF.UserInst, LF.OperandValToReplace)) {
1791 Kind = LSRUse::Address;
1792 AccessTy = getAccessType(LF.UserInst);
1793 }
1794
1795 const SCEV *S = IU.getCanonicalExpr(*UI);
1796
1797 // Equality (== and !=) ICmps are special. We can rewrite (i == N) as
1798 // (N - i == 0), and this allows (N - i) to be the expression that we work
1799 // with rather than just N or i, so we can consider the register
1800 // requirements for both N and i at the same time. Limiting this code to
1801 // equality icmps is not a problem because all interesting loops use
1802 // equality icmps, thanks to IndVarSimplify.
1803 if (ICmpInst *CI = dyn_cast<ICmpInst>(LF.UserInst))
1804 if (CI->isEquality()) {
1805 // Swap the operands if needed to put the OperandValToReplace on the
1806 // left, for consistency.
1807 Value *NV = CI->getOperand(1);
1808 if (NV == LF.OperandValToReplace) {
1809 CI->setOperand(1, CI->getOperand(0));
1810 CI->setOperand(0, NV);
1811 }
1812
1813 // x == y --> x - y == 0
1814 const SCEV *N = SE.getSCEV(NV);
1815 if (N->isLoopInvariant(L)) {
1816 Kind = LSRUse::ICmpZero;
1817 S = SE.getMinusSCEV(N, S);
1818 }
1819
1820 // -1 and the negations of all interesting strides (except the negation
1821 // of -1) are now also interesting.
1822 for (size_t i = 0, e = Factors.size(); i != e; ++i)
1823 if (Factors[i] != -1)
1824 Factors.insert(-(uint64_t)Factors[i]);
1825 Factors.insert(-1);
1826 }
1827
1828 // Set up the initial formula for this use.
1829 std::pair<size_t, int64_t> P = getUse(S, Kind, AccessTy);
1830 LF.LUIdx = P.first;
1831 LF.Offset = P.second;
1832 LSRUse &LU = Uses[LF.LUIdx];
1833 LU.AllFixupsOutsideLoop &= !L->contains(LF.UserInst);
1834
1835 // If this is the first use of this LSRUse, give it a formula.
1836 if (LU.Formulae.empty()) {
1837 InsertInitialFormula(S, L, LU, LF.LUIdx);
1838 CountRegisters(LU.Formulae.back(), LF.LUIdx);
1839 }
1840 }
1841
1842 DEBUG(print_fixups(dbgs()));
1843}
1844
1845void
1846LSRInstance::InsertInitialFormula(const SCEV *S, Loop *L,
1847 LSRUse &LU, size_t LUIdx) {
1848 Formula F;
1849 F.InitialMatch(S, L, SE, DT);
1850 bool Inserted = InsertFormula(LU, LUIdx, F);
1851 assert(Inserted && "Initial formula already exists!"); (void)Inserted;
1852}
1853
1854void
1855LSRInstance::InsertSupplementalFormula(const SCEV *S,
1856 LSRUse &LU, size_t LUIdx) {
1857 Formula F;
1858 F.BaseRegs.push_back(S);
1859 F.AM.HasBaseReg = true;
1860 bool Inserted = InsertFormula(LU, LUIdx, F);
1861 assert(Inserted && "Supplemental formula already exists!"); (void)Inserted;
1862}
1863
1864/// CountRegisters - Note which registers are used by the given formula,
1865/// updating RegUses.
1866void LSRInstance::CountRegisters(const Formula &F, size_t LUIdx) {
1867 if (F.ScaledReg)
1868 RegUses.CountRegister(F.ScaledReg, LUIdx);
1869 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
1870 E = F.BaseRegs.end(); I != E; ++I)
1871 RegUses.CountRegister(*I, LUIdx);
1872}
1873
1874/// InsertFormula - If the given formula has not yet been inserted, add it to
1875/// the list, and return true. Return false otherwise.
1876bool LSRInstance::InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F) {
1877 if (!LU.InsertFormula(LUIdx, F))
1878 return false;
1879
1880 CountRegisters(F, LUIdx);
1881 return true;
1882}
1883
1884/// CollectLoopInvariantFixupsAndFormulae - Check for other uses of
1885/// loop-invariant values which we're tracking. These other uses will pin these
1886/// values in registers, making them less profitable for elimination.
1887/// TODO: This currently misses non-constant addrec step registers.
1888/// TODO: Should this give more weight to users inside the loop?
1889void
1890LSRInstance::CollectLoopInvariantFixupsAndFormulae() {
1891 SmallVector<const SCEV *, 8> Worklist(RegUses.begin(), RegUses.end());
1892 SmallPtrSet<const SCEV *, 8> Inserted;
1893
1894 while (!Worklist.empty()) {
1895 const SCEV *S = Worklist.pop_back_val();
1896
1897 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S))
1898 Worklist.insert(Worklist.end(), N->op_begin(), N->op_end());
1899 else if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
1900 Worklist.push_back(C->getOperand());
1901 else if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
1902 Worklist.push_back(D->getLHS());
1903 Worklist.push_back(D->getRHS());
1904 } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
1905 if (!Inserted.insert(U)) continue;
1906 const Value *V = U->getValue();
1907 if (const Instruction *Inst = dyn_cast<Instruction>(V))
1908 if (L->contains(Inst)) continue;
1909 for (Value::use_const_iterator UI = V->use_begin(), UE = V->use_end();
1910 UI != UE; ++UI) {
1911 const Instruction *UserInst = dyn_cast<Instruction>(*UI);
1912 // Ignore non-instructions.
1913 if (!UserInst)
Dan Gohman7979b722010-01-22 00:46:49 +00001914 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00001915 // Ignore instructions in other functions (as can happen with
1916 // Constants).
1917 if (UserInst->getParent()->getParent() != L->getHeader()->getParent())
Dan Gohman7979b722010-01-22 00:46:49 +00001918 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00001919 // Ignore instructions not dominated by the loop.
1920 const BasicBlock *UseBB = !isa<PHINode>(UserInst) ?
1921 UserInst->getParent() :
1922 cast<PHINode>(UserInst)->getIncomingBlock(
1923 PHINode::getIncomingValueNumForOperand(UI.getOperandNo()));
1924 if (!DT.dominates(L->getHeader(), UseBB))
1925 continue;
1926 // Ignore uses which are part of other SCEV expressions, to avoid
1927 // analyzing them multiple times.
1928 if (SE.isSCEVable(UserInst->getType()) &&
1929 !isa<SCEVUnknown>(SE.getSCEV(const_cast<Instruction *>(UserInst))))
1930 continue;
1931 // Ignore icmp instructions which are already being analyzed.
1932 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) {
1933 unsigned OtherIdx = !UI.getOperandNo();
1934 Value *OtherOp = const_cast<Value *>(ICI->getOperand(OtherIdx));
1935 if (SE.getSCEV(OtherOp)->hasComputableLoopEvolution(L))
1936 continue;
1937 }
1938
1939 LSRFixup &LF = getNewFixup();
1940 LF.UserInst = const_cast<Instruction *>(UserInst);
1941 LF.OperandValToReplace = UI.getUse();
1942 std::pair<size_t, int64_t> P = getUse(S, LSRUse::Basic, 0);
1943 LF.LUIdx = P.first;
1944 LF.Offset = P.second;
1945 LSRUse &LU = Uses[LF.LUIdx];
1946 LU.AllFixupsOutsideLoop &= L->contains(LF.UserInst);
1947 InsertSupplementalFormula(U, LU, LF.LUIdx);
1948 CountRegisters(LU.Formulae.back(), Uses.size() - 1);
1949 break;
1950 }
1951 }
1952 }
1953}
1954
1955/// CollectSubexprs - Split S into subexpressions which can be pulled out into
1956/// separate registers. If C is non-null, multiply each subexpression by C.
1957static void CollectSubexprs(const SCEV *S, const SCEVConstant *C,
1958 SmallVectorImpl<const SCEV *> &Ops,
1959 ScalarEvolution &SE) {
1960 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
1961 // Break out add operands.
1962 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1963 I != E; ++I)
1964 CollectSubexprs(*I, C, Ops, SE);
1965 return;
1966 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
1967 // Split a non-zero base out of an addrec.
1968 if (!AR->getStart()->isZero()) {
Dan Gohman572645c2010-02-12 10:34:29 +00001969 CollectSubexprs(SE.getAddRecExpr(SE.getIntegerSCEV(0, AR->getType()),
1970 AR->getStepRecurrence(SE),
1971 AR->getLoop()), C, Ops, SE);
Dan Gohman68d6da12010-02-12 19:35:25 +00001972 CollectSubexprs(AR->getStart(), C, Ops, SE);
Dan Gohman572645c2010-02-12 10:34:29 +00001973 return;
1974 }
1975 } else if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
1976 // Break (C * (a + b + c)) into C*a + C*b + C*c.
1977 if (Mul->getNumOperands() == 2)
1978 if (const SCEVConstant *Op0 =
1979 dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
1980 CollectSubexprs(Mul->getOperand(1),
1981 C ? cast<SCEVConstant>(SE.getMulExpr(C, Op0)) : Op0,
1982 Ops, SE);
1983 return;
1984 }
1985 }
1986
1987 // Otherwise use the value itself.
1988 Ops.push_back(C ? SE.getMulExpr(C, S) : S);
1989}
1990
1991/// GenerateReassociations - Split out subexpressions from adds and the bases of
1992/// addrecs.
1993void LSRInstance::GenerateReassociations(LSRUse &LU, unsigned LUIdx,
1994 Formula Base,
1995 unsigned Depth) {
1996 // Arbitrarily cap recursion to protect compile time.
1997 if (Depth >= 3) return;
1998
1999 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2000 const SCEV *BaseReg = Base.BaseRegs[i];
2001
2002 SmallVector<const SCEV *, 8> AddOps;
2003 CollectSubexprs(BaseReg, 0, AddOps, SE);
2004 if (AddOps.size() == 1) continue;
2005
2006 for (SmallVectorImpl<const SCEV *>::const_iterator J = AddOps.begin(),
2007 JE = AddOps.end(); J != JE; ++J) {
2008 // Don't pull a constant into a register if the constant could be folded
2009 // into an immediate field.
2010 if (isAlwaysFoldable(*J, LU.MinOffset, LU.MaxOffset,
2011 Base.getNumRegs() > 1,
2012 LU.Kind, LU.AccessTy, TLI, SE))
2013 continue;
2014
2015 // Collect all operands except *J.
2016 SmallVector<const SCEV *, 8> InnerAddOps;
2017 for (SmallVectorImpl<const SCEV *>::const_iterator K = AddOps.begin(),
2018 KE = AddOps.end(); K != KE; ++K)
2019 if (K != J)
2020 InnerAddOps.push_back(*K);
2021
2022 // Don't leave just a constant behind in a register if the constant could
2023 // be folded into an immediate field.
2024 if (InnerAddOps.size() == 1 &&
2025 isAlwaysFoldable(InnerAddOps[0], LU.MinOffset, LU.MaxOffset,
2026 Base.getNumRegs() > 1,
2027 LU.Kind, LU.AccessTy, TLI, SE))
2028 continue;
2029
2030 Formula F = Base;
2031 F.BaseRegs[i] = SE.getAddExpr(InnerAddOps);
2032 F.BaseRegs.push_back(*J);
2033 if (InsertFormula(LU, LUIdx, F))
2034 // If that formula hadn't been seen before, recurse to find more like
2035 // it.
2036 GenerateReassociations(LU, LUIdx, LU.Formulae.back(), Depth+1);
2037 }
2038 }
2039}
2040
2041/// GenerateCombinations - Generate a formula consisting of all of the
2042/// loop-dominating registers added into a single register.
2043void LSRInstance::GenerateCombinations(LSRUse &LU, unsigned LUIdx,
Dan Gohman441a3892010-02-14 18:51:39 +00002044 Formula Base) {
Dan Gohman572645c2010-02-12 10:34:29 +00002045 // This method is only intersting on a plurality of registers.
2046 if (Base.BaseRegs.size() <= 1) return;
2047
2048 Formula F = Base;
2049 F.BaseRegs.clear();
2050 SmallVector<const SCEV *, 4> Ops;
2051 for (SmallVectorImpl<const SCEV *>::const_iterator
2052 I = Base.BaseRegs.begin(), E = Base.BaseRegs.end(); I != E; ++I) {
2053 const SCEV *BaseReg = *I;
2054 if (BaseReg->properlyDominates(L->getHeader(), &DT) &&
2055 !BaseReg->hasComputableLoopEvolution(L))
2056 Ops.push_back(BaseReg);
2057 else
2058 F.BaseRegs.push_back(BaseReg);
2059 }
2060 if (Ops.size() > 1) {
Dan Gohmance947362010-02-14 18:50:49 +00002061 const SCEV *Sum = SE.getAddExpr(Ops);
2062 // TODO: If Sum is zero, it probably means ScalarEvolution missed an
2063 // opportunity to fold something. For now, just ignore such cases
2064 // rather than procede with zero in a register.
2065 if (!Sum->isZero()) {
2066 F.BaseRegs.push_back(Sum);
2067 (void)InsertFormula(LU, LUIdx, F);
2068 }
Dan Gohman572645c2010-02-12 10:34:29 +00002069 }
2070}
2071
2072/// GenerateSymbolicOffsets - Generate reuse formulae using symbolic offsets.
2073void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx,
2074 Formula Base) {
2075 // We can't add a symbolic offset if the address already contains one.
2076 if (Base.AM.BaseGV) return;
2077
2078 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2079 const SCEV *G = Base.BaseRegs[i];
2080 GlobalValue *GV = ExtractSymbol(G, SE);
2081 if (G->isZero() || !GV)
2082 continue;
2083 Formula F = Base;
2084 F.AM.BaseGV = GV;
2085 if (!isLegalUse(F.AM, LU.MinOffset, LU.MaxOffset,
2086 LU.Kind, LU.AccessTy, TLI))
2087 continue;
2088 F.BaseRegs[i] = G;
2089 (void)InsertFormula(LU, LUIdx, F);
2090 }
2091}
2092
2093/// GenerateConstantOffsets - Generate reuse formulae using symbolic offsets.
2094void LSRInstance::GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx,
2095 Formula Base) {
2096 // TODO: For now, just add the min and max offset, because it usually isn't
2097 // worthwhile looking at everything inbetween.
2098 SmallVector<int64_t, 4> Worklist;
2099 Worklist.push_back(LU.MinOffset);
2100 if (LU.MaxOffset != LU.MinOffset)
2101 Worklist.push_back(LU.MaxOffset);
2102
2103 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2104 const SCEV *G = Base.BaseRegs[i];
2105
2106 for (SmallVectorImpl<int64_t>::const_iterator I = Worklist.begin(),
2107 E = Worklist.end(); I != E; ++I) {
2108 Formula F = Base;
2109 F.AM.BaseOffs = (uint64_t)Base.AM.BaseOffs - *I;
2110 if (isLegalUse(F.AM, LU.MinOffset - *I, LU.MaxOffset - *I,
2111 LU.Kind, LU.AccessTy, TLI)) {
2112 F.BaseRegs[i] = SE.getAddExpr(G, SE.getIntegerSCEV(*I, G->getType()));
2113
2114 (void)InsertFormula(LU, LUIdx, F);
2115 }
2116 }
2117
2118 int64_t Imm = ExtractImmediate(G, SE);
2119 if (G->isZero() || Imm == 0)
2120 continue;
2121 Formula F = Base;
2122 F.AM.BaseOffs = (uint64_t)F.AM.BaseOffs + Imm;
2123 if (!isLegalUse(F.AM, LU.MinOffset, LU.MaxOffset,
2124 LU.Kind, LU.AccessTy, TLI))
2125 continue;
2126 F.BaseRegs[i] = G;
2127 (void)InsertFormula(LU, LUIdx, F);
2128 }
2129}
2130
2131/// GenerateICmpZeroScales - For ICmpZero, check to see if we can scale up
2132/// the comparison. For example, x == y -> x*c == y*c.
2133void LSRInstance::GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx,
2134 Formula Base) {
2135 if (LU.Kind != LSRUse::ICmpZero) return;
2136
2137 // Determine the integer type for the base formula.
2138 const Type *IntTy = Base.getType();
2139 if (!IntTy) return;
2140 if (SE.getTypeSizeInBits(IntTy) > 64) return;
2141
2142 // Don't do this if there is more than one offset.
2143 if (LU.MinOffset != LU.MaxOffset) return;
2144
2145 assert(!Base.AM.BaseGV && "ICmpZero use is not legal!");
2146
2147 // Check each interesting stride.
2148 for (SmallSetVector<int64_t, 8>::const_iterator
2149 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
2150 int64_t Factor = *I;
2151 Formula F = Base;
2152
2153 // Check that the multiplication doesn't overflow.
Dan Gohman968cb932010-02-17 00:41:53 +00002154 if (F.AM.BaseOffs == INT64_MIN && Factor == -1)
2155 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002156 F.AM.BaseOffs = (uint64_t)Base.AM.BaseOffs * Factor;
Dan Gohman378c0b32010-02-17 00:42:19 +00002157 if (F.AM.BaseOffs / Factor != Base.AM.BaseOffs)
Dan Gohman572645c2010-02-12 10:34:29 +00002158 continue;
2159
2160 // Check that multiplying with the use offset doesn't overflow.
2161 int64_t Offset = LU.MinOffset;
Dan Gohman968cb932010-02-17 00:41:53 +00002162 if (Offset == INT64_MIN && Factor == -1)
2163 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002164 Offset = (uint64_t)Offset * Factor;
Dan Gohman378c0b32010-02-17 00:42:19 +00002165 if (Offset / Factor != LU.MinOffset)
Dan Gohman572645c2010-02-12 10:34:29 +00002166 continue;
2167
2168 // Check that this scale is legal.
2169 if (!isLegalUse(F.AM, Offset, Offset, LU.Kind, LU.AccessTy, TLI))
2170 continue;
2171
2172 // Compensate for the use having MinOffset built into it.
2173 F.AM.BaseOffs = (uint64_t)F.AM.BaseOffs + Offset - LU.MinOffset;
2174
2175 const SCEV *FactorS = SE.getIntegerSCEV(Factor, IntTy);
2176
2177 // Check that multiplying with each base register doesn't overflow.
2178 for (size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) {
2179 F.BaseRegs[i] = SE.getMulExpr(F.BaseRegs[i], FactorS);
Dan Gohmanf09b7122010-02-19 19:35:48 +00002180 if (getExactSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i])
Dan Gohman572645c2010-02-12 10:34:29 +00002181 goto next;
2182 }
2183
2184 // Check that multiplying with the scaled register doesn't overflow.
2185 if (F.ScaledReg) {
2186 F.ScaledReg = SE.getMulExpr(F.ScaledReg, FactorS);
Dan Gohmanf09b7122010-02-19 19:35:48 +00002187 if (getExactSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg)
Dan Gohman572645c2010-02-12 10:34:29 +00002188 continue;
2189 }
2190
2191 // If we make it here and it's legal, add it.
2192 (void)InsertFormula(LU, LUIdx, F);
2193 next:;
2194 }
2195}
2196
2197/// GenerateScales - Generate stride factor reuse formulae by making use of
2198/// scaled-offset address modes, for example.
2199void LSRInstance::GenerateScales(LSRUse &LU, unsigned LUIdx,
2200 Formula Base) {
2201 // Determine the integer type for the base formula.
2202 const Type *IntTy = Base.getType();
2203 if (!IntTy) return;
2204
2205 // If this Formula already has a scaled register, we can't add another one.
2206 if (Base.AM.Scale != 0) return;
2207
2208 // Check each interesting stride.
2209 for (SmallSetVector<int64_t, 8>::const_iterator
2210 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
2211 int64_t Factor = *I;
2212
2213 Base.AM.Scale = Factor;
2214 Base.AM.HasBaseReg = Base.BaseRegs.size() > 1;
2215 // Check whether this scale is going to be legal.
2216 if (!isLegalUse(Base.AM, LU.MinOffset, LU.MaxOffset,
2217 LU.Kind, LU.AccessTy, TLI)) {
2218 // As a special-case, handle special out-of-loop Basic users specially.
2219 // TODO: Reconsider this special case.
2220 if (LU.Kind == LSRUse::Basic &&
2221 isLegalUse(Base.AM, LU.MinOffset, LU.MaxOffset,
2222 LSRUse::Special, LU.AccessTy, TLI) &&
2223 LU.AllFixupsOutsideLoop)
2224 LU.Kind = LSRUse::Special;
2225 else
2226 continue;
2227 }
2228 // For an ICmpZero, negating a solitary base register won't lead to
2229 // new solutions.
2230 if (LU.Kind == LSRUse::ICmpZero &&
2231 !Base.AM.HasBaseReg && Base.AM.BaseOffs == 0 && !Base.AM.BaseGV)
2232 continue;
2233 // For each addrec base reg, apply the scale, if possible.
2234 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
2235 if (const SCEVAddRecExpr *AR =
2236 dyn_cast<SCEVAddRecExpr>(Base.BaseRegs[i])) {
2237 const SCEV *FactorS = SE.getIntegerSCEV(Factor, IntTy);
2238 if (FactorS->isZero())
2239 continue;
2240 // Divide out the factor, ignoring high bits, since we'll be
2241 // scaling the value back up in the end.
Dan Gohmanf09b7122010-02-19 19:35:48 +00002242 if (const SCEV *Quotient = getExactSDiv(AR, FactorS, SE, true)) {
Dan Gohman572645c2010-02-12 10:34:29 +00002243 // TODO: This could be optimized to avoid all the copying.
2244 Formula F = Base;
2245 F.ScaledReg = Quotient;
2246 std::swap(F.BaseRegs[i], F.BaseRegs.back());
2247 F.BaseRegs.pop_back();
2248 (void)InsertFormula(LU, LUIdx, F);
2249 }
2250 }
2251 }
2252}
2253
2254/// GenerateTruncates - Generate reuse formulae from different IV types.
2255void LSRInstance::GenerateTruncates(LSRUse &LU, unsigned LUIdx,
2256 Formula Base) {
2257 // This requires TargetLowering to tell us which truncates are free.
2258 if (!TLI) return;
2259
2260 // Don't bother truncating symbolic values.
2261 if (Base.AM.BaseGV) return;
2262
2263 // Determine the integer type for the base formula.
2264 const Type *DstTy = Base.getType();
2265 if (!DstTy) return;
2266 DstTy = SE.getEffectiveSCEVType(DstTy);
2267
2268 for (SmallSetVector<const Type *, 4>::const_iterator
2269 I = Types.begin(), E = Types.end(); I != E; ++I) {
2270 const Type *SrcTy = *I;
2271 if (SrcTy != DstTy && TLI->isTruncateFree(SrcTy, DstTy)) {
2272 Formula F = Base;
2273
2274 if (F.ScaledReg) F.ScaledReg = SE.getAnyExtendExpr(F.ScaledReg, *I);
2275 for (SmallVectorImpl<const SCEV *>::iterator J = F.BaseRegs.begin(),
2276 JE = F.BaseRegs.end(); J != JE; ++J)
2277 *J = SE.getAnyExtendExpr(*J, SrcTy);
2278
2279 // TODO: This assumes we've done basic processing on all uses and
2280 // have an idea what the register usage is.
2281 if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses))
2282 continue;
2283
2284 (void)InsertFormula(LU, LUIdx, F);
2285 }
2286 }
2287}
2288
2289namespace {
2290
Dan Gohman6020d852010-02-14 18:51:20 +00002291/// WorkItem - Helper class for GenerateCrossUseConstantOffsets. It's used to
Dan Gohman572645c2010-02-12 10:34:29 +00002292/// defer modifications so that the search phase doesn't have to worry about
2293/// the data structures moving underneath it.
2294struct WorkItem {
2295 size_t LUIdx;
2296 int64_t Imm;
2297 const SCEV *OrigReg;
2298
2299 WorkItem(size_t LI, int64_t I, const SCEV *R)
2300 : LUIdx(LI), Imm(I), OrigReg(R) {}
2301
2302 void print(raw_ostream &OS) const;
2303 void dump() const;
2304};
2305
2306}
2307
2308void WorkItem::print(raw_ostream &OS) const {
2309 OS << "in formulae referencing " << *OrigReg << " in use " << LUIdx
2310 << " , add offset " << Imm;
2311}
2312
2313void WorkItem::dump() const {
2314 print(errs()); errs() << '\n';
2315}
2316
2317/// GenerateCrossUseConstantOffsets - Look for registers which are a constant
2318/// distance apart and try to form reuse opportunities between them.
2319void LSRInstance::GenerateCrossUseConstantOffsets() {
2320 // Group the registers by their value without any added constant offset.
2321 typedef std::map<int64_t, const SCEV *> ImmMapTy;
2322 typedef DenseMap<const SCEV *, ImmMapTy> RegMapTy;
2323 RegMapTy Map;
2324 DenseMap<const SCEV *, SmallBitVector> UsedByIndicesMap;
2325 SmallVector<const SCEV *, 8> Sequence;
2326 for (RegUseTracker::const_iterator I = RegUses.begin(), E = RegUses.end();
2327 I != E; ++I) {
2328 const SCEV *Reg = *I;
2329 int64_t Imm = ExtractImmediate(Reg, SE);
2330 std::pair<RegMapTy::iterator, bool> Pair =
2331 Map.insert(std::make_pair(Reg, ImmMapTy()));
2332 if (Pair.second)
2333 Sequence.push_back(Reg);
2334 Pair.first->second.insert(std::make_pair(Imm, *I));
2335 UsedByIndicesMap[Reg] |= RegUses.getUsedByIndices(*I);
2336 }
2337
2338 // Now examine each set of registers with the same base value. Build up
2339 // a list of work to do and do the work in a separate step so that we're
2340 // not adding formulae and register counts while we're searching.
2341 SmallVector<WorkItem, 32> WorkItems;
2342 SmallSet<std::pair<size_t, int64_t>, 32> UniqueItems;
2343 for (SmallVectorImpl<const SCEV *>::const_iterator I = Sequence.begin(),
2344 E = Sequence.end(); I != E; ++I) {
2345 const SCEV *Reg = *I;
2346 const ImmMapTy &Imms = Map.find(Reg)->second;
2347
Dan Gohmancd045c02010-02-12 19:20:37 +00002348 // It's not worthwhile looking for reuse if there's only one offset.
2349 if (Imms.size() == 1)
2350 continue;
2351
Dan Gohman572645c2010-02-12 10:34:29 +00002352 DEBUG(dbgs() << "Generating cross-use offsets for " << *Reg << ':';
2353 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
2354 J != JE; ++J)
2355 dbgs() << ' ' << J->first;
2356 dbgs() << '\n');
2357
2358 // Examine each offset.
2359 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
2360 J != JE; ++J) {
2361 const SCEV *OrigReg = J->second;
2362
2363 int64_t JImm = J->first;
2364 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg);
2365
2366 if (!isa<SCEVConstant>(OrigReg) &&
2367 UsedByIndicesMap[Reg].count() == 1) {
2368 DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg << '\n');
2369 continue;
2370 }
2371
2372 // Conservatively examine offsets between this orig reg a few selected
2373 // other orig regs.
2374 ImmMapTy::const_iterator OtherImms[] = {
2375 Imms.begin(), prior(Imms.end()),
2376 Imms.upper_bound((Imms.begin()->first + prior(Imms.end())->first) / 2)
2377 };
2378 for (size_t i = 0, e = array_lengthof(OtherImms); i != e; ++i) {
2379 ImmMapTy::const_iterator M = OtherImms[i];
Dan Gohmancd045c02010-02-12 19:20:37 +00002380 if (M == J || M == JE) continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002381
2382 // Compute the difference between the two.
2383 int64_t Imm = (uint64_t)JImm - M->first;
2384 for (int LUIdx = UsedByIndices.find_first(); LUIdx != -1;
2385 LUIdx = UsedByIndices.find_next(LUIdx))
2386 // Make a memo of this use, offset, and register tuple.
2387 if (UniqueItems.insert(std::make_pair(LUIdx, Imm)))
2388 WorkItems.push_back(WorkItem(LUIdx, Imm, OrigReg));
Evan Cheng586f69a2009-11-12 07:35:05 +00002389 }
2390 }
2391 }
2392
Dan Gohman572645c2010-02-12 10:34:29 +00002393 Map.clear();
2394 Sequence.clear();
2395 UsedByIndicesMap.clear();
2396 UniqueItems.clear();
2397
2398 // Now iterate through the worklist and add new formulae.
2399 for (SmallVectorImpl<WorkItem>::const_iterator I = WorkItems.begin(),
2400 E = WorkItems.end(); I != E; ++I) {
2401 const WorkItem &WI = *I;
2402 size_t LUIdx = WI.LUIdx;
2403 LSRUse &LU = Uses[LUIdx];
2404 int64_t Imm = WI.Imm;
2405 const SCEV *OrigReg = WI.OrigReg;
2406
2407 const Type *IntTy = SE.getEffectiveSCEVType(OrigReg->getType());
2408 const SCEV *NegImmS = SE.getSCEV(ConstantInt::get(IntTy, -(uint64_t)Imm));
2409 unsigned BitWidth = SE.getTypeSizeInBits(IntTy);
2410
2411 // TODO: Use a more targetted data structure.
2412 for (size_t L = 0, LE = LU.Formulae.size(); L != LE; ++L) {
2413 Formula F = LU.Formulae[L];
2414 // Use the immediate in the scaled register.
2415 if (F.ScaledReg == OrigReg) {
2416 int64_t Offs = (uint64_t)F.AM.BaseOffs +
2417 Imm * (uint64_t)F.AM.Scale;
2418 // Don't create 50 + reg(-50).
2419 if (F.referencesReg(SE.getSCEV(
2420 ConstantInt::get(IntTy, -(uint64_t)Offs))))
2421 continue;
2422 Formula NewF = F;
2423 NewF.AM.BaseOffs = Offs;
2424 if (!isLegalUse(NewF.AM, LU.MinOffset, LU.MaxOffset,
2425 LU.Kind, LU.AccessTy, TLI))
2426 continue;
2427 NewF.ScaledReg = SE.getAddExpr(NegImmS, NewF.ScaledReg);
2428
2429 // If the new scale is a constant in a register, and adding the constant
2430 // value to the immediate would produce a value closer to zero than the
2431 // immediate itself, then the formula isn't worthwhile.
2432 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewF.ScaledReg))
2433 if (C->getValue()->getValue().isNegative() !=
2434 (NewF.AM.BaseOffs < 0) &&
2435 (C->getValue()->getValue().abs() * APInt(BitWidth, F.AM.Scale))
2436 .ule(APInt(BitWidth, NewF.AM.BaseOffs).abs()))
2437 continue;
2438
2439 // OK, looks good.
2440 (void)InsertFormula(LU, LUIdx, NewF);
2441 } else {
2442 // Use the immediate in a base register.
2443 for (size_t N = 0, NE = F.BaseRegs.size(); N != NE; ++N) {
2444 const SCEV *BaseReg = F.BaseRegs[N];
2445 if (BaseReg != OrigReg)
2446 continue;
2447 Formula NewF = F;
2448 NewF.AM.BaseOffs = (uint64_t)NewF.AM.BaseOffs + Imm;
2449 if (!isLegalUse(NewF.AM, LU.MinOffset, LU.MaxOffset,
2450 LU.Kind, LU.AccessTy, TLI))
2451 continue;
2452 NewF.BaseRegs[N] = SE.getAddExpr(NegImmS, BaseReg);
2453
2454 // If the new formula has a constant in a register, and adding the
2455 // constant value to the immediate would produce a value closer to
2456 // zero than the immediate itself, then the formula isn't worthwhile.
2457 for (SmallVectorImpl<const SCEV *>::const_iterator
2458 J = NewF.BaseRegs.begin(), JE = NewF.BaseRegs.end();
2459 J != JE; ++J)
2460 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*J))
2461 if (C->getValue()->getValue().isNegative() !=
2462 (NewF.AM.BaseOffs < 0) &&
2463 C->getValue()->getValue().abs()
2464 .ule(APInt(BitWidth, NewF.AM.BaseOffs).abs()))
2465 goto skip_formula;
2466
2467 // Ok, looks good.
2468 (void)InsertFormula(LU, LUIdx, NewF);
2469 break;
2470 skip_formula:;
2471 }
2472 }
2473 }
2474 }
Dale Johannesenc1acc3f2009-05-11 17:15:42 +00002475}
2476
Dan Gohman572645c2010-02-12 10:34:29 +00002477/// GenerateAllReuseFormulae - Generate formulae for each use.
2478void
2479LSRInstance::GenerateAllReuseFormulae() {
Dan Gohmanc2385a02010-02-16 01:42:53 +00002480 // This is split into multiple loops so that hasRegsUsedByUsesOtherThan
Dan Gohman572645c2010-02-12 10:34:29 +00002481 // queries are more precise.
2482 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2483 LSRUse &LU = Uses[LUIdx];
2484 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2485 GenerateReassociations(LU, LUIdx, LU.Formulae[i]);
2486 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2487 GenerateCombinations(LU, LUIdx, LU.Formulae[i]);
2488 }
2489 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2490 LSRUse &LU = Uses[LUIdx];
2491 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2492 GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]);
2493 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2494 GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]);
2495 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2496 GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]);
2497 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2498 GenerateScales(LU, LUIdx, LU.Formulae[i]);
Dan Gohmanc2385a02010-02-16 01:42:53 +00002499 }
2500 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2501 LSRUse &LU = Uses[LUIdx];
Dan Gohman572645c2010-02-12 10:34:29 +00002502 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2503 GenerateTruncates(LU, LUIdx, LU.Formulae[i]);
2504 }
2505
2506 GenerateCrossUseConstantOffsets();
2507}
2508
2509/// If their are multiple formulae with the same set of registers used
2510/// by other uses, pick the best one and delete the others.
2511void LSRInstance::FilterOutUndesirableDedicatedRegisters() {
2512#ifndef NDEBUG
2513 bool Changed = false;
2514#endif
2515
2516 // Collect the best formula for each unique set of shared registers. This
2517 // is reset for each use.
2518 typedef DenseMap<SmallVector<const SCEV *, 2>, size_t, UniquifierDenseMapInfo>
2519 BestFormulaeTy;
2520 BestFormulaeTy BestFormulae;
2521
2522 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2523 LSRUse &LU = Uses[LUIdx];
2524 FormulaSorter Sorter(L, LU, SE, DT);
2525
2526 // Clear out the set of used regs; it will be recomputed.
2527 LU.Regs.clear();
2528
2529 for (size_t FIdx = 0, NumForms = LU.Formulae.size();
2530 FIdx != NumForms; ++FIdx) {
2531 Formula &F = LU.Formulae[FIdx];
2532
2533 SmallVector<const SCEV *, 2> Key;
2534 for (SmallVectorImpl<const SCEV *>::const_iterator J = F.BaseRegs.begin(),
2535 JE = F.BaseRegs.end(); J != JE; ++J) {
2536 const SCEV *Reg = *J;
2537 if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx))
2538 Key.push_back(Reg);
2539 }
2540 if (F.ScaledReg &&
2541 RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx))
2542 Key.push_back(F.ScaledReg);
2543 // Unstable sort by host order ok, because this is only used for
2544 // uniquifying.
2545 std::sort(Key.begin(), Key.end());
2546
2547 std::pair<BestFormulaeTy::const_iterator, bool> P =
2548 BestFormulae.insert(std::make_pair(Key, FIdx));
2549 if (!P.second) {
2550 Formula &Best = LU.Formulae[P.first->second];
2551 if (Sorter.operator()(F, Best))
2552 std::swap(F, Best);
2553 DEBUG(dbgs() << "Filtering out "; F.print(dbgs());
2554 dbgs() << "\n"
2555 " in favor of "; Best.print(dbgs());
2556 dbgs() << '\n');
2557#ifndef NDEBUG
2558 Changed = true;
2559#endif
2560 std::swap(F, LU.Formulae.back());
2561 LU.Formulae.pop_back();
2562 --FIdx;
2563 --NumForms;
2564 continue;
2565 }
2566 if (F.ScaledReg) LU.Regs.insert(F.ScaledReg);
2567 LU.Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
2568 }
2569 BestFormulae.clear();
2570 }
2571
2572 DEBUG(if (Changed) {
Dan Gohman9214b822010-02-13 02:06:02 +00002573 dbgs() << "\n"
2574 "After filtering out undesirable candidates:\n";
Dan Gohman572645c2010-02-12 10:34:29 +00002575 print_uses(dbgs());
2576 });
2577}
2578
2579/// NarrowSearchSpaceUsingHeuristics - If there are an extrordinary number of
2580/// formulae to choose from, use some rough heuristics to prune down the number
2581/// of formulae. This keeps the main solver from taking an extrordinary amount
2582/// of time in some worst-case scenarios.
2583void LSRInstance::NarrowSearchSpaceUsingHeuristics() {
2584 // This is a rough guess that seems to work fairly well.
2585 const size_t Limit = UINT16_MAX;
2586
2587 SmallPtrSet<const SCEV *, 4> Taken;
2588 for (;;) {
2589 // Estimate the worst-case number of solutions we might consider. We almost
2590 // never consider this many solutions because we prune the search space,
2591 // but the pruning isn't always sufficient.
2592 uint32_t Power = 1;
2593 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
2594 E = Uses.end(); I != E; ++I) {
2595 size_t FSize = I->Formulae.size();
2596 if (FSize >= Limit) {
2597 Power = Limit;
2598 break;
2599 }
2600 Power *= FSize;
2601 if (Power >= Limit)
2602 break;
2603 }
2604 if (Power < Limit)
2605 break;
2606
2607 // Ok, we have too many of formulae on our hands to conveniently handle.
2608 // Use a rough heuristic to thin out the list.
2609
2610 // Pick the register which is used by the most LSRUses, which is likely
2611 // to be a good reuse register candidate.
2612 const SCEV *Best = 0;
2613 unsigned BestNum = 0;
2614 for (RegUseTracker::const_iterator I = RegUses.begin(), E = RegUses.end();
2615 I != E; ++I) {
2616 const SCEV *Reg = *I;
2617 if (Taken.count(Reg))
2618 continue;
2619 if (!Best)
2620 Best = Reg;
2621 else {
2622 unsigned Count = RegUses.getUsedByIndices(Reg).count();
2623 if (Count > BestNum) {
2624 Best = Reg;
2625 BestNum = Count;
2626 }
2627 }
2628 }
2629
2630 DEBUG(dbgs() << "Narrowing the search space by assuming " << *Best
2631 << " will yeild profitable reuse.\n");
2632 Taken.insert(Best);
2633
2634 // In any use with formulae which references this register, delete formulae
2635 // which don't reference it.
2636 for (SmallVectorImpl<LSRUse>::iterator I = Uses.begin(),
2637 E = Uses.end(); I != E; ++I) {
2638 LSRUse &LU = *I;
2639 if (!LU.Regs.count(Best)) continue;
2640
2641 // Clear out the set of used regs; it will be recomputed.
2642 LU.Regs.clear();
2643
2644 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
2645 Formula &F = LU.Formulae[i];
2646 if (!F.referencesReg(Best)) {
2647 DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
2648 std::swap(LU.Formulae.back(), F);
2649 LU.Formulae.pop_back();
2650 --e;
2651 --i;
2652 continue;
2653 }
2654
2655 if (F.ScaledReg) LU.Regs.insert(F.ScaledReg);
2656 LU.Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
2657 }
2658 }
2659
2660 DEBUG(dbgs() << "After pre-selection:\n";
2661 print_uses(dbgs()));
2662 }
2663}
2664
2665/// SolveRecurse - This is the recursive solver.
2666void LSRInstance::SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
2667 Cost &SolutionCost,
2668 SmallVectorImpl<const Formula *> &Workspace,
2669 const Cost &CurCost,
2670 const SmallPtrSet<const SCEV *, 16> &CurRegs,
2671 DenseSet<const SCEV *> &VisitedRegs) const {
2672 // Some ideas:
2673 // - prune more:
2674 // - use more aggressive filtering
2675 // - sort the formula so that the most profitable solutions are found first
2676 // - sort the uses too
2677 // - search faster:
2678 // - dont compute a cost, and then compare. compare while computing a cost
2679 // and bail early.
2680 // - track register sets with SmallBitVector
2681
2682 const LSRUse &LU = Uses[Workspace.size()];
2683
2684 // If this use references any register that's already a part of the
2685 // in-progress solution, consider it a requirement that a formula must
2686 // reference that register in order to be considered. This prunes out
2687 // unprofitable searching.
2688 SmallSetVector<const SCEV *, 4> ReqRegs;
2689 for (SmallPtrSet<const SCEV *, 16>::const_iterator I = CurRegs.begin(),
2690 E = CurRegs.end(); I != E; ++I)
Dan Gohman9214b822010-02-13 02:06:02 +00002691 if (LU.Regs.count(*I))
Dan Gohman572645c2010-02-12 10:34:29 +00002692 ReqRegs.insert(*I);
Dan Gohman572645c2010-02-12 10:34:29 +00002693
Dan Gohman9214b822010-02-13 02:06:02 +00002694 bool AnySatisfiedReqRegs = false;
Dan Gohman572645c2010-02-12 10:34:29 +00002695 SmallPtrSet<const SCEV *, 16> NewRegs;
2696 Cost NewCost;
Dan Gohman9214b822010-02-13 02:06:02 +00002697retry:
Dan Gohman572645c2010-02-12 10:34:29 +00002698 for (SmallVectorImpl<Formula>::const_iterator I = LU.Formulae.begin(),
2699 E = LU.Formulae.end(); I != E; ++I) {
2700 const Formula &F = *I;
2701
2702 // Ignore formulae which do not use any of the required registers.
2703 for (SmallSetVector<const SCEV *, 4>::const_iterator J = ReqRegs.begin(),
2704 JE = ReqRegs.end(); J != JE; ++J) {
2705 const SCEV *Reg = *J;
2706 if ((!F.ScaledReg || F.ScaledReg != Reg) &&
2707 std::find(F.BaseRegs.begin(), F.BaseRegs.end(), Reg) ==
2708 F.BaseRegs.end())
2709 goto skip;
2710 }
Dan Gohman9214b822010-02-13 02:06:02 +00002711 AnySatisfiedReqRegs = true;
Dan Gohman572645c2010-02-12 10:34:29 +00002712
2713 // Evaluate the cost of the current formula. If it's already worse than
2714 // the current best, prune the search at that point.
2715 NewCost = CurCost;
2716 NewRegs = CurRegs;
2717 NewCost.RateFormula(F, NewRegs, VisitedRegs, L, LU.Offsets, SE, DT);
2718 if (NewCost < SolutionCost) {
2719 Workspace.push_back(&F);
2720 if (Workspace.size() != Uses.size()) {
2721 SolveRecurse(Solution, SolutionCost, Workspace, NewCost,
2722 NewRegs, VisitedRegs);
2723 if (F.getNumRegs() == 1 && Workspace.size() == 1)
2724 VisitedRegs.insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]);
2725 } else {
2726 DEBUG(dbgs() << "New best at "; NewCost.print(dbgs());
2727 dbgs() << ". Regs:";
2728 for (SmallPtrSet<const SCEV *, 16>::const_iterator
2729 I = NewRegs.begin(), E = NewRegs.end(); I != E; ++I)
2730 dbgs() << ' ' << **I;
2731 dbgs() << '\n');
2732
2733 SolutionCost = NewCost;
2734 Solution = Workspace;
2735 }
2736 Workspace.pop_back();
2737 }
2738 skip:;
2739 }
Dan Gohman9214b822010-02-13 02:06:02 +00002740
2741 // If none of the formulae had all of the required registers, relax the
2742 // constraint so that we don't exclude all formulae.
2743 if (!AnySatisfiedReqRegs) {
2744 ReqRegs.clear();
2745 goto retry;
2746 }
Dan Gohman572645c2010-02-12 10:34:29 +00002747}
2748
2749void LSRInstance::Solve(SmallVectorImpl<const Formula *> &Solution) const {
2750 SmallVector<const Formula *, 8> Workspace;
2751 Cost SolutionCost;
2752 SolutionCost.Loose();
2753 Cost CurCost;
2754 SmallPtrSet<const SCEV *, 16> CurRegs;
2755 DenseSet<const SCEV *> VisitedRegs;
2756 Workspace.reserve(Uses.size());
2757
2758 SolveRecurse(Solution, SolutionCost, Workspace, CurCost,
2759 CurRegs, VisitedRegs);
2760
2761 // Ok, we've now made all our decisions.
2762 DEBUG(dbgs() << "\n"
2763 "The chosen solution requires "; SolutionCost.print(dbgs());
2764 dbgs() << ":\n";
2765 for (size_t i = 0, e = Uses.size(); i != e; ++i) {
2766 dbgs() << " ";
2767 Uses[i].print(dbgs());
2768 dbgs() << "\n"
2769 " ";
2770 Solution[i]->print(dbgs());
2771 dbgs() << '\n';
2772 });
2773}
2774
2775/// getImmediateDominator - A handy utility for the specific DominatorTree
2776/// query that we need here.
2777///
2778static BasicBlock *getImmediateDominator(BasicBlock *BB, DominatorTree &DT) {
2779 DomTreeNode *Node = DT.getNode(BB);
2780 if (!Node) return 0;
2781 Node = Node->getIDom();
2782 if (!Node) return 0;
2783 return Node->getBlock();
2784}
2785
2786Value *LSRInstance::Expand(const LSRFixup &LF,
2787 const Formula &F,
2788 BasicBlock::iterator IP,
2789 Loop *L, Instruction *IVIncInsertPos,
2790 SCEVExpander &Rewriter,
2791 SmallVectorImpl<WeakVH> &DeadInsts,
2792 ScalarEvolution &SE, DominatorTree &DT) const {
2793 const LSRUse &LU = Uses[LF.LUIdx];
2794
2795 // Then, collect some instructions which we will remain dominated by when
2796 // expanding the replacement. These must be dominated by any operands that
2797 // will be required in the expansion.
2798 SmallVector<Instruction *, 4> Inputs;
2799 if (Instruction *I = dyn_cast<Instruction>(LF.OperandValToReplace))
2800 Inputs.push_back(I);
2801 if (LU.Kind == LSRUse::ICmpZero)
2802 if (Instruction *I =
2803 dyn_cast<Instruction>(cast<ICmpInst>(LF.UserInst)->getOperand(1)))
2804 Inputs.push_back(I);
2805 if (LF.PostIncLoop && !L->contains(LF.UserInst))
2806 Inputs.push_back(L->getLoopLatch()->getTerminator());
2807
2808 // Then, climb up the immediate dominator tree as far as we can go while
2809 // still being dominated by the input positions.
2810 for (;;) {
2811 bool AllDominate = true;
2812 Instruction *BetterPos = 0;
2813 BasicBlock *IDom = getImmediateDominator(IP->getParent(), DT);
2814 if (!IDom) break;
2815 Instruction *Tentative = IDom->getTerminator();
2816 for (SmallVectorImpl<Instruction *>::const_iterator I = Inputs.begin(),
2817 E = Inputs.end(); I != E; ++I) {
2818 Instruction *Inst = *I;
2819 if (Inst == Tentative || !DT.dominates(Inst, Tentative)) {
2820 AllDominate = false;
2821 break;
2822 }
2823 if (IDom == Inst->getParent() &&
2824 (!BetterPos || DT.dominates(BetterPos, Inst)))
2825 BetterPos = next(BasicBlock::iterator(Inst));
2826 }
2827 if (!AllDominate)
2828 break;
2829 if (BetterPos)
2830 IP = BetterPos;
2831 else
2832 IP = Tentative;
2833 }
2834 while (isa<PHINode>(IP)) ++IP;
2835
2836 // Inform the Rewriter if we have a post-increment use, so that it can
2837 // perform an advantageous expansion.
2838 Rewriter.setPostInc(LF.PostIncLoop);
2839
2840 // This is the type that the user actually needs.
2841 const Type *OpTy = LF.OperandValToReplace->getType();
2842 // This will be the type that we'll initially expand to.
2843 const Type *Ty = F.getType();
2844 if (!Ty)
2845 // No type known; just expand directly to the ultimate type.
2846 Ty = OpTy;
2847 else if (SE.getEffectiveSCEVType(Ty) == SE.getEffectiveSCEVType(OpTy))
2848 // Expand directly to the ultimate type if it's the right size.
2849 Ty = OpTy;
2850 // This is the type to do integer arithmetic in.
2851 const Type *IntTy = SE.getEffectiveSCEVType(Ty);
2852
2853 // Build up a list of operands to add together to form the full base.
2854 SmallVector<const SCEV *, 8> Ops;
2855
2856 // Expand the BaseRegs portion.
2857 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
2858 E = F.BaseRegs.end(); I != E; ++I) {
2859 const SCEV *Reg = *I;
2860 assert(!Reg->isZero() && "Zero allocated in a base register!");
2861
2862 // If we're expanding for a post-inc user for the add-rec's loop, make the
2863 // post-inc adjustment.
2864 const SCEV *Start = Reg;
2865 while (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Start)) {
2866 if (AR->getLoop() == LF.PostIncLoop) {
2867 Reg = SE.getAddExpr(Reg, AR->getStepRecurrence(SE));
2868 // If the user is inside the loop, insert the code after the increment
Dan Gohman278f9582010-02-22 03:59:54 +00002869 // so that it is dominated by its operand. If the original insert point
2870 // was already dominated by the increment, keep it, because there may
2871 // be loop-variant operands that need to be respected also.
2872 if (L->contains(LF.UserInst) && !DT.dominates(IVIncInsertPos, IP))
Dan Gohman572645c2010-02-12 10:34:29 +00002873 IP = IVIncInsertPos;
2874 break;
2875 }
2876 Start = AR->getStart();
2877 }
2878
2879 Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, 0, IP)));
2880 }
2881
2882 // Expand the ScaledReg portion.
2883 Value *ICmpScaledV = 0;
2884 if (F.AM.Scale != 0) {
2885 const SCEV *ScaledS = F.ScaledReg;
2886
2887 // If we're expanding for a post-inc user for the add-rec's loop, make the
2888 // post-inc adjustment.
2889 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ScaledS))
2890 if (AR->getLoop() == LF.PostIncLoop)
2891 ScaledS = SE.getAddExpr(ScaledS, AR->getStepRecurrence(SE));
2892
2893 if (LU.Kind == LSRUse::ICmpZero) {
2894 // An interesting way of "folding" with an icmp is to use a negated
2895 // scale, which we'll implement by inserting it into the other operand
2896 // of the icmp.
2897 assert(F.AM.Scale == -1 &&
2898 "The only scale supported by ICmpZero uses is -1!");
2899 ICmpScaledV = Rewriter.expandCodeFor(ScaledS, 0, IP);
2900 } else {
2901 // Otherwise just expand the scaled register and an explicit scale,
2902 // which is expected to be matched as part of the address.
2903 ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, 0, IP));
2904 ScaledS = SE.getMulExpr(ScaledS,
2905 SE.getIntegerSCEV(F.AM.Scale,
2906 ScaledS->getType()));
2907 Ops.push_back(ScaledS);
2908 }
2909 }
2910
2911 // Expand the immediate portions.
2912 if (F.AM.BaseGV)
2913 Ops.push_back(SE.getSCEV(F.AM.BaseGV));
2914 int64_t Offset = (uint64_t)F.AM.BaseOffs + LF.Offset;
2915 if (Offset != 0) {
2916 if (LU.Kind == LSRUse::ICmpZero) {
2917 // The other interesting way of "folding" with an ICmpZero is to use a
2918 // negated immediate.
2919 if (!ICmpScaledV)
2920 ICmpScaledV = ConstantInt::get(IntTy, -Offset);
2921 else {
2922 Ops.push_back(SE.getUnknown(ICmpScaledV));
2923 ICmpScaledV = ConstantInt::get(IntTy, Offset);
2924 }
2925 } else {
2926 // Just add the immediate values. These again are expected to be matched
2927 // as part of the address.
2928 Ops.push_back(SE.getIntegerSCEV(Offset, IntTy));
2929 }
2930 }
2931
2932 // Emit instructions summing all the operands.
2933 const SCEV *FullS = Ops.empty() ?
2934 SE.getIntegerSCEV(0, IntTy) :
2935 SE.getAddExpr(Ops);
2936 Value *FullV = Rewriter.expandCodeFor(FullS, Ty, IP);
2937
2938 // We're done expanding now, so reset the rewriter.
2939 Rewriter.setPostInc(0);
2940
2941 // An ICmpZero Formula represents an ICmp which we're handling as a
2942 // comparison against zero. Now that we've expanded an expression for that
2943 // form, update the ICmp's other operand.
2944 if (LU.Kind == LSRUse::ICmpZero) {
2945 ICmpInst *CI = cast<ICmpInst>(LF.UserInst);
2946 DeadInsts.push_back(CI->getOperand(1));
2947 assert(!F.AM.BaseGV && "ICmp does not support folding a global value and "
2948 "a scale at the same time!");
2949 if (F.AM.Scale == -1) {
2950 if (ICmpScaledV->getType() != OpTy) {
2951 Instruction *Cast =
2952 CastInst::Create(CastInst::getCastOpcode(ICmpScaledV, false,
2953 OpTy, false),
2954 ICmpScaledV, OpTy, "tmp", CI);
2955 ICmpScaledV = Cast;
2956 }
2957 CI->setOperand(1, ICmpScaledV);
2958 } else {
2959 assert(F.AM.Scale == 0 &&
2960 "ICmp does not support folding a global value and "
2961 "a scale at the same time!");
2962 Constant *C = ConstantInt::getSigned(SE.getEffectiveSCEVType(OpTy),
2963 -(uint64_t)Offset);
2964 if (C->getType() != OpTy)
2965 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2966 OpTy, false),
2967 C, OpTy);
2968
2969 CI->setOperand(1, C);
2970 }
2971 }
2972
2973 return FullV;
2974}
2975
Dan Gohman3a02cbc2010-02-16 20:25:07 +00002976/// RewriteForPHI - Helper for Rewrite. PHI nodes are special because the use
2977/// of their operands effectively happens in their predecessor blocks, so the
2978/// expression may need to be expanded in multiple places.
2979void LSRInstance::RewriteForPHI(PHINode *PN,
2980 const LSRFixup &LF,
2981 const Formula &F,
2982 Loop *L, Instruction *IVIncInsertPos,
2983 SCEVExpander &Rewriter,
2984 SmallVectorImpl<WeakVH> &DeadInsts,
2985 ScalarEvolution &SE, DominatorTree &DT,
2986 Pass *P) const {
2987 DenseMap<BasicBlock *, Value *> Inserted;
2988 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2989 if (PN->getIncomingValue(i) == LF.OperandValToReplace) {
2990 BasicBlock *BB = PN->getIncomingBlock(i);
2991
2992 // If this is a critical edge, split the edge so that we do not insert
2993 // the code on all predecessor/successor paths. We do this unless this
2994 // is the canonical backedge for this loop, which complicates post-inc
2995 // users.
2996 if (e != 1 && BB->getTerminator()->getNumSuccessors() > 1 &&
2997 !isa<IndirectBrInst>(BB->getTerminator()) &&
2998 (PN->getParent() != L->getHeader() || !L->contains(BB))) {
2999 // Split the critical edge.
3000 BasicBlock *NewBB = SplitCriticalEdge(BB, PN->getParent(), P);
3001
3002 // If PN is outside of the loop and BB is in the loop, we want to
3003 // move the block to be immediately before the PHI block, not
3004 // immediately after BB.
3005 if (L->contains(BB) && !L->contains(PN))
3006 NewBB->moveBefore(PN->getParent());
3007
3008 // Splitting the edge can reduce the number of PHI entries we have.
3009 e = PN->getNumIncomingValues();
3010 BB = NewBB;
3011 i = PN->getBasicBlockIndex(BB);
3012 }
3013
3014 std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> Pair =
3015 Inserted.insert(std::make_pair(BB, static_cast<Value *>(0)));
3016 if (!Pair.second)
3017 PN->setIncomingValue(i, Pair.first->second);
3018 else {
3019 Value *FullV = Expand(LF, F, BB->getTerminator(), L, IVIncInsertPos,
3020 Rewriter, DeadInsts, SE, DT);
3021
3022 // If this is reuse-by-noop-cast, insert the noop cast.
3023 const Type *OpTy = LF.OperandValToReplace->getType();
3024 if (FullV->getType() != OpTy)
3025 FullV =
3026 CastInst::Create(CastInst::getCastOpcode(FullV, false,
3027 OpTy, false),
3028 FullV, LF.OperandValToReplace->getType(),
3029 "tmp", BB->getTerminator());
3030
3031 PN->setIncomingValue(i, FullV);
3032 Pair.first->second = FullV;
3033 }
3034 }
3035}
3036
Dan Gohman572645c2010-02-12 10:34:29 +00003037/// Rewrite - Emit instructions for the leading candidate expression for this
3038/// LSRUse (this is called "expanding"), and update the UserInst to reference
3039/// the newly expanded value.
3040void LSRInstance::Rewrite(const LSRFixup &LF,
3041 const Formula &F,
3042 Loop *L, Instruction *IVIncInsertPos,
3043 SCEVExpander &Rewriter,
3044 SmallVectorImpl<WeakVH> &DeadInsts,
3045 ScalarEvolution &SE, DominatorTree &DT,
3046 Pass *P) const {
Dan Gohman572645c2010-02-12 10:34:29 +00003047 // First, find an insertion point that dominates UserInst. For PHI nodes,
3048 // find the nearest block which dominates all the relevant uses.
3049 if (PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) {
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003050 RewriteForPHI(PN, LF, F, L, IVIncInsertPos, Rewriter, DeadInsts, SE, DT, P);
Dan Gohman572645c2010-02-12 10:34:29 +00003051 } else {
3052 Value *FullV = Expand(LF, F, LF.UserInst, L, IVIncInsertPos,
3053 Rewriter, DeadInsts, SE, DT);
3054
3055 // If this is reuse-by-noop-cast, insert the noop cast.
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003056 const Type *OpTy = LF.OperandValToReplace->getType();
Dan Gohman572645c2010-02-12 10:34:29 +00003057 if (FullV->getType() != OpTy) {
3058 Instruction *Cast =
3059 CastInst::Create(CastInst::getCastOpcode(FullV, false, OpTy, false),
3060 FullV, OpTy, "tmp", LF.UserInst);
3061 FullV = Cast;
3062 }
3063
3064 // Update the user. ICmpZero is handled specially here (for now) because
3065 // Expand may have updated one of the operands of the icmp already, and
3066 // its new value may happen to be equal to LF.OperandValToReplace, in
3067 // which case doing replaceUsesOfWith leads to replacing both operands
3068 // with the same value. TODO: Reorganize this.
3069 if (Uses[LF.LUIdx].Kind == LSRUse::ICmpZero)
3070 LF.UserInst->setOperand(0, FullV);
3071 else
3072 LF.UserInst->replaceUsesOfWith(LF.OperandValToReplace, FullV);
3073 }
3074
3075 DeadInsts.push_back(LF.OperandValToReplace);
3076}
3077
3078void
3079LSRInstance::ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
3080 Pass *P) {
3081 // Keep track of instructions we may have made dead, so that
3082 // we can remove them after we are done working.
3083 SmallVector<WeakVH, 16> DeadInsts;
3084
3085 SCEVExpander Rewriter(SE);
3086 Rewriter.disableCanonicalMode();
3087 Rewriter.setIVIncInsertPos(L, IVIncInsertPos);
3088
3089 // Expand the new value definitions and update the users.
3090 for (size_t i = 0, e = Fixups.size(); i != e; ++i) {
3091 size_t LUIdx = Fixups[i].LUIdx;
3092
3093 Rewrite(Fixups[i], *Solution[LUIdx], L, IVIncInsertPos, Rewriter,
3094 DeadInsts, SE, DT, P);
3095
3096 Changed = true;
3097 }
3098
3099 // Clean up after ourselves. This must be done before deleting any
3100 // instructions.
3101 Rewriter.clear();
3102
3103 Changed |= DeleteTriviallyDeadInstructions(DeadInsts);
3104}
3105
3106LSRInstance::LSRInstance(const TargetLowering *tli, Loop *l, Pass *P)
3107 : IU(P->getAnalysis<IVUsers>()),
3108 SE(P->getAnalysis<ScalarEvolution>()),
3109 DT(P->getAnalysis<DominatorTree>()),
3110 TLI(tli), L(l), Changed(false), IVIncInsertPos(0) {
Devang Patel0f54dcb2007-03-06 21:14:09 +00003111
Dan Gohman03e896b2009-11-05 21:11:53 +00003112 // If LoopSimplify form is not available, stay out of trouble.
Dan Gohman572645c2010-02-12 10:34:29 +00003113 if (!L->isLoopSimplifyForm()) return;
Dan Gohman03e896b2009-11-05 21:11:53 +00003114
Dan Gohman572645c2010-02-12 10:34:29 +00003115 // If there's no interesting work to be done, bail early.
3116 if (IU.empty()) return;
Dan Gohman80b0f8c2009-03-09 20:34:59 +00003117
Dan Gohman572645c2010-02-12 10:34:29 +00003118 DEBUG(dbgs() << "\nLSR on loop ";
3119 WriteAsOperand(dbgs(), L->getHeader(), /*PrintType=*/false);
3120 dbgs() << ":\n");
Dan Gohmanf7912df2009-03-09 20:46:50 +00003121
Dan Gohman572645c2010-02-12 10:34:29 +00003122 /// OptimizeShadowIV - If IV is used in a int-to-float cast
3123 /// inside the loop then try to eliminate the cast opeation.
3124 OptimizeShadowIV();
Chris Lattner010de252005-08-08 05:28:22 +00003125
Dan Gohman572645c2010-02-12 10:34:29 +00003126 // Change loop terminating condition to use the postinc iv when possible.
3127 Changed |= OptimizeLoopTermCond();
Evan Cheng5792f512009-05-11 22:33:01 +00003128
Dan Gohman572645c2010-02-12 10:34:29 +00003129 CollectInterestingTypesAndFactors();
3130 CollectFixupsAndInitialFormulae();
3131 CollectLoopInvariantFixupsAndFormulae();
Chris Lattner010de252005-08-08 05:28:22 +00003132
Dan Gohman572645c2010-02-12 10:34:29 +00003133 DEBUG(dbgs() << "LSR found " << Uses.size() << " uses:\n";
3134 print_uses(dbgs()));
Misha Brukmanfd939082005-04-21 23:48:37 +00003135
Dan Gohman572645c2010-02-12 10:34:29 +00003136 // Now use the reuse data to generate a bunch of interesting ways
3137 // to formulate the values needed for the uses.
3138 GenerateAllReuseFormulae();
Evan Chengd1d6b5c2006-03-16 21:53:05 +00003139
Dan Gohman572645c2010-02-12 10:34:29 +00003140 DEBUG(dbgs() << "\n"
3141 "After generating reuse formulae:\n";
3142 print_uses(dbgs()));
Nate Begemaneaa13852004-10-18 21:08:22 +00003143
Dan Gohman572645c2010-02-12 10:34:29 +00003144 FilterOutUndesirableDedicatedRegisters();
3145 NarrowSearchSpaceUsingHeuristics();
Dan Gohman6bec5bb2009-12-18 00:06:20 +00003146
Dan Gohman572645c2010-02-12 10:34:29 +00003147 SmallVector<const Formula *, 8> Solution;
3148 Solve(Solution);
3149 assert(Solution.size() == Uses.size() && "Malformed solution!");
Dan Gohman6bec5bb2009-12-18 00:06:20 +00003150
Dan Gohman572645c2010-02-12 10:34:29 +00003151 // Release memory that is no longer needed.
3152 Factors.clear();
3153 Types.clear();
3154 RegUses.clear();
3155
3156#ifndef NDEBUG
3157 // Formulae should be legal.
3158 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
3159 E = Uses.end(); I != E; ++I) {
3160 const LSRUse &LU = *I;
3161 for (SmallVectorImpl<Formula>::const_iterator J = LU.Formulae.begin(),
3162 JE = LU.Formulae.end(); J != JE; ++J)
3163 assert(isLegalUse(J->AM, LU.MinOffset, LU.MaxOffset,
3164 LU.Kind, LU.AccessTy, TLI) &&
3165 "Illegal formula generated!");
3166 };
3167#endif
3168
3169 // Now that we've decided what we want, make it so.
3170 ImplementSolution(Solution, P);
3171}
3172
3173void LSRInstance::print_factors_and_types(raw_ostream &OS) const {
3174 if (Factors.empty() && Types.empty()) return;
3175
3176 OS << "LSR has identified the following interesting factors and types: ";
3177 bool First = true;
3178
3179 for (SmallSetVector<int64_t, 8>::const_iterator
3180 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
3181 if (!First) OS << ", ";
3182 First = false;
3183 OS << '*' << *I;
Evan Cheng81ebdcf2009-11-10 21:14:05 +00003184 }
Dale Johannesenc1acc3f2009-05-11 17:15:42 +00003185
Dan Gohman572645c2010-02-12 10:34:29 +00003186 for (SmallSetVector<const Type *, 4>::const_iterator
3187 I = Types.begin(), E = Types.end(); I != E; ++I) {
3188 if (!First) OS << ", ";
3189 First = false;
3190 OS << '(' << **I << ')';
3191 }
3192 OS << '\n';
3193}
3194
3195void LSRInstance::print_fixups(raw_ostream &OS) const {
3196 OS << "LSR is examining the following fixup sites:\n";
3197 for (SmallVectorImpl<LSRFixup>::const_iterator I = Fixups.begin(),
3198 E = Fixups.end(); I != E; ++I) {
3199 const LSRFixup &LF = *I;
3200 dbgs() << " ";
3201 LF.print(OS);
3202 OS << '\n';
3203 }
3204}
3205
3206void LSRInstance::print_uses(raw_ostream &OS) const {
3207 OS << "LSR is examining the following uses:\n";
3208 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
3209 E = Uses.end(); I != E; ++I) {
3210 const LSRUse &LU = *I;
3211 dbgs() << " ";
3212 LU.print(OS);
3213 OS << '\n';
3214 for (SmallVectorImpl<Formula>::const_iterator J = LU.Formulae.begin(),
3215 JE = LU.Formulae.end(); J != JE; ++J) {
3216 OS << " ";
3217 J->print(OS);
3218 OS << '\n';
3219 }
3220 }
3221}
3222
3223void LSRInstance::print(raw_ostream &OS) const {
3224 print_factors_and_types(OS);
3225 print_fixups(OS);
3226 print_uses(OS);
3227}
3228
3229void LSRInstance::dump() const {
3230 print(errs()); errs() << '\n';
3231}
3232
3233namespace {
3234
3235class LoopStrengthReduce : public LoopPass {
3236 /// TLI - Keep a pointer of a TargetLowering to consult for determining
3237 /// transformation profitability.
3238 const TargetLowering *const TLI;
3239
3240public:
3241 static char ID; // Pass ID, replacement for typeid
3242 explicit LoopStrengthReduce(const TargetLowering *tli = 0);
3243
3244private:
3245 bool runOnLoop(Loop *L, LPPassManager &LPM);
3246 void getAnalysisUsage(AnalysisUsage &AU) const;
3247};
3248
3249}
3250
3251char LoopStrengthReduce::ID = 0;
3252static RegisterPass<LoopStrengthReduce>
3253X("loop-reduce", "Loop Strength Reduction");
3254
3255Pass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
3256 return new LoopStrengthReduce(TLI);
3257}
3258
3259LoopStrengthReduce::LoopStrengthReduce(const TargetLowering *tli)
3260 : LoopPass(&ID), TLI(tli) {}
3261
3262void LoopStrengthReduce::getAnalysisUsage(AnalysisUsage &AU) const {
3263 // We split critical edges, so we change the CFG. However, we do update
3264 // many analyses if they are around.
3265 AU.addPreservedID(LoopSimplifyID);
3266 AU.addPreserved<LoopInfo>();
3267 AU.addPreserved("domfrontier");
3268
3269 AU.addRequiredID(LoopSimplifyID);
3270 AU.addRequired<DominatorTree>();
3271 AU.addPreserved<DominatorTree>();
3272 AU.addRequired<ScalarEvolution>();
3273 AU.addPreserved<ScalarEvolution>();
3274 AU.addRequired<IVUsers>();
3275 AU.addPreserved<IVUsers>();
3276}
3277
3278bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager & /*LPM*/) {
3279 bool Changed = false;
3280
3281 // Run the main LSR transformation.
3282 Changed |= LSRInstance(TLI, L, this).getChanged();
3283
Dan Gohmanafc36a92009-05-02 18:29:22 +00003284 // At this point, it is worth checking to see if any recurrence PHIs are also
Dan Gohman35738ac2009-05-04 22:30:44 +00003285 // dead, so that we can remove them as well.
Dan Gohman9fff2182010-01-05 16:31:45 +00003286 Changed |= DeleteDeadPHIs(L->getHeader());
Dan Gohmanafc36a92009-05-02 18:29:22 +00003287
Evan Cheng1ce75dc2008-07-07 19:51:32 +00003288 return Changed;
Nate Begemaneaa13852004-10-18 21:08:22 +00003289}