blob: 0eac92e44167478f37d547416ef0f8d6f259dad2 [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 Gohman572645c2010-02-12 10:34:29 +0000367/// getSDiv - Return an expression for LHS /s RHS, if it can be determined,
368/// or null otherwise. If IgnoreSignificantBits is true, expressions like
369/// (X * Y) /s Y are simplified to Y, ignoring that the multiplication may
370/// overflow, which is useful when the result will be used in a context where
371/// the most significant bits are ignored.
372static const SCEV *getSDiv(const SCEV *LHS, const SCEV *RHS,
373 ScalarEvolution &SE,
374 bool IgnoreSignificantBits = false) {
375 // Handle the trivial case, which works for any SCEV type.
376 if (LHS == RHS)
377 return SE.getIntegerSCEV(1, LHS->getType());
378
379 // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do some
380 // folding.
381 if (RHS->isAllOnesValue())
382 return SE.getMulExpr(LHS, RHS);
383
384 // Check for a division of a constant by a constant.
385 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(LHS)) {
386 const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS);
387 if (!RC)
388 return 0;
389 if (C->getValue()->getValue().srem(RC->getValue()->getValue()) != 0)
390 return 0;
391 return SE.getConstant(C->getValue()->getValue()
392 .sdiv(RC->getValue()->getValue()));
393 }
394
Dan Gohmanaae01f12010-02-19 19:32:49 +0000395 // Distribute the sdiv over addrec operands, if the addrec doesn't overflow.
Dan Gohman572645c2010-02-12 10:34:29 +0000396 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohmanaae01f12010-02-19 19:32:49 +0000397 if (IgnoreSignificantBits || isAddRecSExtable(AR, SE)) {
398 const SCEV *Start = getSDiv(AR->getStart(), RHS, SE,
399 IgnoreSignificantBits);
400 if (!Start) return 0;
401 const SCEV *Step = getSDiv(AR->getStepRecurrence(SE), RHS, SE,
402 IgnoreSignificantBits);
403 if (!Step) return 0;
404 return SE.getAddRecExpr(Start, Step, AR->getLoop());
405 }
Dan Gohman572645c2010-02-12 10:34:29 +0000406 }
407
Dan Gohmanaae01f12010-02-19 19:32:49 +0000408 // Distribute the sdiv over add operands, if the add doesn't overflow.
Dan Gohman572645c2010-02-12 10:34:29 +0000409 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(LHS)) {
Dan Gohmanaae01f12010-02-19 19:32:49 +0000410 if (IgnoreSignificantBits || isAddSExtable(Add, SE)) {
411 SmallVector<const SCEV *, 8> Ops;
412 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
413 I != E; ++I) {
414 const SCEV *Op = getSDiv(*I, RHS, SE,
415 IgnoreSignificantBits);
416 if (!Op) return 0;
417 Ops.push_back(Op);
418 }
419 return SE.getAddExpr(Ops);
Dan Gohman572645c2010-02-12 10:34:29 +0000420 }
Dan Gohman572645c2010-02-12 10:34:29 +0000421 }
422
423 // Check for a multiply operand that we can pull RHS out of.
424 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS))
Dan Gohmanaae01f12010-02-19 19:32:49 +0000425 if (IgnoreSignificantBits || isMulSExtable(Mul, SE)) {
Dan Gohman572645c2010-02-12 10:34:29 +0000426 SmallVector<const SCEV *, 4> Ops;
427 bool Found = false;
428 for (SCEVMulExpr::op_iterator I = Mul->op_begin(), E = Mul->op_end();
429 I != E; ++I) {
430 if (!Found)
431 if (const SCEV *Q = getSDiv(*I, RHS, SE, IgnoreSignificantBits)) {
432 Ops.push_back(Q);
433 Found = true;
434 continue;
435 }
436 Ops.push_back(*I);
437 }
438 return Found ? SE.getMulExpr(Ops) : 0;
439 }
440
441 // Otherwise we don't know.
442 return 0;
443}
444
445/// ExtractImmediate - If S involves the addition of a constant integer value,
446/// return that integer value, and mutate S to point to a new SCEV with that
447/// value excluded.
448static int64_t ExtractImmediate(const SCEV *&S, ScalarEvolution &SE) {
449 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
450 if (C->getValue()->getValue().getMinSignedBits() <= 64) {
451 S = SE.getIntegerSCEV(0, C->getType());
452 return C->getValue()->getSExtValue();
453 }
454 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
455 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
456 int64_t Result = ExtractImmediate(NewOps.front(), SE);
457 S = SE.getAddExpr(NewOps);
458 return Result;
459 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
460 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
461 int64_t Result = ExtractImmediate(NewOps.front(), SE);
462 S = SE.getAddRecExpr(NewOps, AR->getLoop());
463 return Result;
464 }
465 return 0;
466}
467
468/// ExtractSymbol - If S involves the addition of a GlobalValue address,
469/// return that symbol, and mutate S to point to a new SCEV with that
470/// value excluded.
471static GlobalValue *ExtractSymbol(const SCEV *&S, ScalarEvolution &SE) {
472 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
473 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) {
474 S = SE.getIntegerSCEV(0, GV->getType());
475 return GV;
476 }
477 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
478 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
479 GlobalValue *Result = ExtractSymbol(NewOps.back(), SE);
480 S = SE.getAddExpr(NewOps);
481 return Result;
482 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
483 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
484 GlobalValue *Result = ExtractSymbol(NewOps.front(), SE);
485 S = SE.getAddRecExpr(NewOps, AR->getLoop());
486 return Result;
487 }
488 return 0;
Nate Begemaneaa13852004-10-18 21:08:22 +0000489}
490
Dan Gohmanf284ce22009-02-18 00:08:39 +0000491/// isAddressUse - Returns true if the specified instruction is using the
Dale Johannesen203af582008-12-05 21:47:27 +0000492/// specified value as an address.
493static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
494 bool isAddress = isa<LoadInst>(Inst);
495 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
496 if (SI->getOperand(1) == OperandVal)
497 isAddress = true;
498 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
499 // Addressing modes can also be folded into prefetches and a variety
500 // of intrinsics.
501 switch (II->getIntrinsicID()) {
502 default: break;
503 case Intrinsic::prefetch:
504 case Intrinsic::x86_sse2_loadu_dq:
505 case Intrinsic::x86_sse2_loadu_pd:
506 case Intrinsic::x86_sse_loadu_ps:
507 case Intrinsic::x86_sse_storeu_ps:
508 case Intrinsic::x86_sse2_storeu_pd:
509 case Intrinsic::x86_sse2_storeu_dq:
510 case Intrinsic::x86_sse2_storel_dq:
511 if (II->getOperand(1) == OperandVal)
512 isAddress = true;
513 break;
514 }
515 }
516 return isAddress;
517}
Chris Lattner0ae33eb2005-10-03 01:04:44 +0000518
Dan Gohman21e77222009-03-09 21:01:17 +0000519/// getAccessType - Return the type of the memory being accessed.
520static const Type *getAccessType(const Instruction *Inst) {
Dan Gohmana537bf82009-05-18 16:45:28 +0000521 const Type *AccessTy = Inst->getType();
Dan Gohman21e77222009-03-09 21:01:17 +0000522 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst))
Dan Gohmana537bf82009-05-18 16:45:28 +0000523 AccessTy = SI->getOperand(0)->getType();
Dan Gohman21e77222009-03-09 21:01:17 +0000524 else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
525 // Addressing modes can also be folded into prefetches and a variety
526 // of intrinsics.
527 switch (II->getIntrinsicID()) {
528 default: break;
529 case Intrinsic::x86_sse_storeu_ps:
530 case Intrinsic::x86_sse2_storeu_pd:
531 case Intrinsic::x86_sse2_storeu_dq:
532 case Intrinsic::x86_sse2_storel_dq:
Dan Gohmana537bf82009-05-18 16:45:28 +0000533 AccessTy = II->getOperand(1)->getType();
Dan Gohman21e77222009-03-09 21:01:17 +0000534 break;
535 }
536 }
Dan Gohman572645c2010-02-12 10:34:29 +0000537
538 // All pointers have the same requirements, so canonicalize them to an
539 // arbitrary pointer type to minimize variation.
540 if (const PointerType *PTy = dyn_cast<PointerType>(AccessTy))
541 AccessTy = PointerType::get(IntegerType::get(PTy->getContext(), 1),
542 PTy->getAddressSpace());
543
Dan Gohmana537bf82009-05-18 16:45:28 +0000544 return AccessTy;
Dan Gohman21e77222009-03-09 21:01:17 +0000545}
546
Dan Gohman572645c2010-02-12 10:34:29 +0000547/// DeleteTriviallyDeadInstructions - If any of the instructions is the
548/// specified set are trivially dead, delete them and see if this makes any of
549/// their operands subsequently dead.
550static bool
551DeleteTriviallyDeadInstructions(SmallVectorImpl<WeakVH> &DeadInsts) {
552 bool Changed = false;
553
554 while (!DeadInsts.empty()) {
555 Instruction *I = dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val());
556
557 if (I == 0 || !isInstructionTriviallyDead(I))
558 continue;
559
560 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
561 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
562 *OI = 0;
563 if (U->use_empty())
564 DeadInsts.push_back(U);
565 }
566
567 I->eraseFromParent();
568 Changed = true;
569 }
570
571 return Changed;
572}
573
Dan Gohman7979b722010-01-22 00:46:49 +0000574namespace {
Jim Grosbach56a1f802009-11-17 17:53:56 +0000575
Dan Gohman572645c2010-02-12 10:34:29 +0000576/// Cost - This class is used to measure and compare candidate formulae.
577class Cost {
578 /// TODO: Some of these could be merged. Also, a lexical ordering
579 /// isn't always optimal.
580 unsigned NumRegs;
581 unsigned AddRecCost;
582 unsigned NumIVMuls;
583 unsigned NumBaseAdds;
584 unsigned ImmCost;
585 unsigned SetupCost;
Nate Begeman16997482005-07-30 00:15:07 +0000586
Dan Gohman572645c2010-02-12 10:34:29 +0000587public:
588 Cost()
589 : NumRegs(0), AddRecCost(0), NumIVMuls(0), NumBaseAdds(0), ImmCost(0),
590 SetupCost(0) {}
Jim Grosbach56a1f802009-11-17 17:53:56 +0000591
Dan Gohman572645c2010-02-12 10:34:29 +0000592 unsigned getNumRegs() const { return NumRegs; }
Dan Gohman7979b722010-01-22 00:46:49 +0000593
Dan Gohman572645c2010-02-12 10:34:29 +0000594 bool operator<(const Cost &Other) const;
Dan Gohman7979b722010-01-22 00:46:49 +0000595
Dan Gohman572645c2010-02-12 10:34:29 +0000596 void Loose();
Dan Gohman7979b722010-01-22 00:46:49 +0000597
Dan Gohman572645c2010-02-12 10:34:29 +0000598 void RateFormula(const Formula &F,
599 SmallPtrSet<const SCEV *, 16> &Regs,
600 const DenseSet<const SCEV *> &VisitedRegs,
601 const Loop *L,
602 const SmallVectorImpl<int64_t> &Offsets,
603 ScalarEvolution &SE, DominatorTree &DT);
Dan Gohman7979b722010-01-22 00:46:49 +0000604
Dan Gohman572645c2010-02-12 10:34:29 +0000605 void print(raw_ostream &OS) const;
606 void dump() const;
Dan Gohman7979b722010-01-22 00:46:49 +0000607
Dan Gohman572645c2010-02-12 10:34:29 +0000608private:
609 void RateRegister(const SCEV *Reg,
610 SmallPtrSet<const SCEV *, 16> &Regs,
611 const Loop *L,
612 ScalarEvolution &SE, DominatorTree &DT);
Dan Gohman9214b822010-02-13 02:06:02 +0000613 void RatePrimaryRegister(const SCEV *Reg,
614 SmallPtrSet<const SCEV *, 16> &Regs,
615 const Loop *L,
616 ScalarEvolution &SE, DominatorTree &DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000617};
618
619}
620
621/// RateRegister - Tally up interesting quantities from the given register.
622void Cost::RateRegister(const SCEV *Reg,
623 SmallPtrSet<const SCEV *, 16> &Regs,
624 const Loop *L,
625 ScalarEvolution &SE, DominatorTree &DT) {
Dan Gohman9214b822010-02-13 02:06:02 +0000626 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Reg)) {
627 if (AR->getLoop() == L)
628 AddRecCost += 1; /// TODO: This should be a function of the stride.
Dan Gohman572645c2010-02-12 10:34:29 +0000629
Dan Gohman9214b822010-02-13 02:06:02 +0000630 // If this is an addrec for a loop that's already been visited by LSR,
631 // don't second-guess its addrec phi nodes. LSR isn't currently smart
632 // enough to reason about more than one loop at a time. Consider these
633 // registers free and leave them alone.
634 else if (L->contains(AR->getLoop()) ||
635 (!AR->getLoop()->contains(L) &&
636 DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))) {
637 for (BasicBlock::iterator I = AR->getLoop()->getHeader()->begin();
638 PHINode *PN = dyn_cast<PHINode>(I); ++I)
639 if (SE.isSCEVable(PN->getType()) &&
640 (SE.getEffectiveSCEVType(PN->getType()) ==
641 SE.getEffectiveSCEVType(AR->getType())) &&
642 SE.getSCEV(PN) == AR)
643 return;
Dan Gohman572645c2010-02-12 10:34:29 +0000644
Dan Gohman9214b822010-02-13 02:06:02 +0000645 // If this isn't one of the addrecs that the loop already has, it
646 // would require a costly new phi and add. TODO: This isn't
647 // precisely modeled right now.
648 ++NumBaseAdds;
649 if (!Regs.count(AR->getStart()))
Dan Gohman572645c2010-02-12 10:34:29 +0000650 RateRegister(AR->getStart(), Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000651 }
Dan Gohman572645c2010-02-12 10:34:29 +0000652
Dan Gohman9214b822010-02-13 02:06:02 +0000653 // Add the step value register, if it needs one.
654 // TODO: The non-affine case isn't precisely modeled here.
655 if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1)))
656 if (!Regs.count(AR->getStart()))
657 RateRegister(AR->getOperand(1), Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000658 }
Dan Gohman9214b822010-02-13 02:06:02 +0000659 ++NumRegs;
660
661 // Rough heuristic; favor registers which don't require extra setup
662 // instructions in the preheader.
663 if (!isa<SCEVUnknown>(Reg) &&
664 !isa<SCEVConstant>(Reg) &&
665 !(isa<SCEVAddRecExpr>(Reg) &&
666 (isa<SCEVUnknown>(cast<SCEVAddRecExpr>(Reg)->getStart()) ||
667 isa<SCEVConstant>(cast<SCEVAddRecExpr>(Reg)->getStart()))))
668 ++SetupCost;
669}
670
671/// RatePrimaryRegister - Record this register in the set. If we haven't seen it
672/// before, rate it.
673void Cost::RatePrimaryRegister(const SCEV *Reg,
Dan Gohman7fca2292010-02-16 19:42:34 +0000674 SmallPtrSet<const SCEV *, 16> &Regs,
675 const Loop *L,
676 ScalarEvolution &SE, DominatorTree &DT) {
Dan Gohman9214b822010-02-13 02:06:02 +0000677 if (Regs.insert(Reg))
678 RateRegister(Reg, Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000679}
680
681void Cost::RateFormula(const Formula &F,
682 SmallPtrSet<const SCEV *, 16> &Regs,
683 const DenseSet<const SCEV *> &VisitedRegs,
684 const Loop *L,
685 const SmallVectorImpl<int64_t> &Offsets,
686 ScalarEvolution &SE, DominatorTree &DT) {
687 // Tally up the registers.
688 if (const SCEV *ScaledReg = F.ScaledReg) {
689 if (VisitedRegs.count(ScaledReg)) {
690 Loose();
691 return;
692 }
Dan Gohman9214b822010-02-13 02:06:02 +0000693 RatePrimaryRegister(ScaledReg, Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000694 }
695 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
696 E = F.BaseRegs.end(); I != E; ++I) {
697 const SCEV *BaseReg = *I;
698 if (VisitedRegs.count(BaseReg)) {
699 Loose();
700 return;
701 }
Dan Gohman9214b822010-02-13 02:06:02 +0000702 RatePrimaryRegister(BaseReg, Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000703
704 NumIVMuls += isa<SCEVMulExpr>(BaseReg) &&
705 BaseReg->hasComputableLoopEvolution(L);
706 }
707
708 if (F.BaseRegs.size() > 1)
709 NumBaseAdds += F.BaseRegs.size() - 1;
710
711 // Tally up the non-zero immediates.
712 for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
713 E = Offsets.end(); I != E; ++I) {
714 int64_t Offset = (uint64_t)*I + F.AM.BaseOffs;
715 if (F.AM.BaseGV)
716 ImmCost += 64; // Handle symbolic values conservatively.
717 // TODO: This should probably be the pointer size.
718 else if (Offset != 0)
719 ImmCost += APInt(64, Offset, true).getMinSignedBits();
720 }
721}
722
723/// Loose - Set this cost to a loosing value.
724void Cost::Loose() {
725 NumRegs = ~0u;
726 AddRecCost = ~0u;
727 NumIVMuls = ~0u;
728 NumBaseAdds = ~0u;
729 ImmCost = ~0u;
730 SetupCost = ~0u;
731}
732
733/// operator< - Choose the lower cost.
734bool Cost::operator<(const Cost &Other) const {
735 if (NumRegs != Other.NumRegs)
736 return NumRegs < Other.NumRegs;
737 if (AddRecCost != Other.AddRecCost)
738 return AddRecCost < Other.AddRecCost;
739 if (NumIVMuls != Other.NumIVMuls)
740 return NumIVMuls < Other.NumIVMuls;
741 if (NumBaseAdds != Other.NumBaseAdds)
742 return NumBaseAdds < Other.NumBaseAdds;
743 if (ImmCost != Other.ImmCost)
744 return ImmCost < Other.ImmCost;
745 if (SetupCost != Other.SetupCost)
746 return SetupCost < Other.SetupCost;
747 return false;
748}
749
750void Cost::print(raw_ostream &OS) const {
751 OS << NumRegs << " reg" << (NumRegs == 1 ? "" : "s");
752 if (AddRecCost != 0)
753 OS << ", with addrec cost " << AddRecCost;
754 if (NumIVMuls != 0)
755 OS << ", plus " << NumIVMuls << " IV mul" << (NumIVMuls == 1 ? "" : "s");
756 if (NumBaseAdds != 0)
757 OS << ", plus " << NumBaseAdds << " base add"
758 << (NumBaseAdds == 1 ? "" : "s");
759 if (ImmCost != 0)
760 OS << ", plus " << ImmCost << " imm cost";
761 if (SetupCost != 0)
762 OS << ", plus " << SetupCost << " setup cost";
763}
764
765void Cost::dump() const {
766 print(errs()); errs() << '\n';
767}
768
769namespace {
770
771/// LSRFixup - An operand value in an instruction which is to be replaced
772/// with some equivalent, possibly strength-reduced, replacement.
773struct LSRFixup {
774 /// UserInst - The instruction which will be updated.
775 Instruction *UserInst;
776
777 /// OperandValToReplace - The operand of the instruction which will
778 /// be replaced. The operand may be used more than once; every instance
779 /// will be replaced.
780 Value *OperandValToReplace;
781
782 /// PostIncLoop - If this user is to use the post-incremented value of an
783 /// induction variable, this variable is non-null and holds the loop
784 /// associated with the induction variable.
785 const Loop *PostIncLoop;
786
787 /// LUIdx - The index of the LSRUse describing the expression which
788 /// this fixup needs, minus an offset (below).
789 size_t LUIdx;
790
791 /// Offset - A constant offset to be added to the LSRUse expression.
792 /// This allows multiple fixups to share the same LSRUse with different
793 /// offsets, for example in an unrolled loop.
794 int64_t Offset;
795
796 LSRFixup();
797
798 void print(raw_ostream &OS) const;
799 void dump() const;
800};
801
802}
803
804LSRFixup::LSRFixup()
805 : UserInst(0), OperandValToReplace(0), PostIncLoop(0),
806 LUIdx(~size_t(0)), Offset(0) {}
807
808void LSRFixup::print(raw_ostream &OS) const {
809 OS << "UserInst=";
810 // Store is common and interesting enough to be worth special-casing.
811 if (StoreInst *Store = dyn_cast<StoreInst>(UserInst)) {
812 OS << "store ";
813 WriteAsOperand(OS, Store->getOperand(0), /*PrintType=*/false);
814 } else if (UserInst->getType()->isVoidTy())
815 OS << UserInst->getOpcodeName();
816 else
817 WriteAsOperand(OS, UserInst, /*PrintType=*/false);
818
819 OS << ", OperandValToReplace=";
820 WriteAsOperand(OS, OperandValToReplace, /*PrintType=*/false);
821
822 if (PostIncLoop) {
823 OS << ", PostIncLoop=";
824 WriteAsOperand(OS, PostIncLoop->getHeader(), /*PrintType=*/false);
825 }
826
827 if (LUIdx != ~size_t(0))
828 OS << ", LUIdx=" << LUIdx;
829
830 if (Offset != 0)
831 OS << ", Offset=" << Offset;
832}
833
834void LSRFixup::dump() const {
835 print(errs()); errs() << '\n';
836}
837
838namespace {
839
840/// UniquifierDenseMapInfo - A DenseMapInfo implementation for holding
841/// DenseMaps and DenseSets of sorted SmallVectors of const SCEV*.
842struct UniquifierDenseMapInfo {
843 static SmallVector<const SCEV *, 2> getEmptyKey() {
844 SmallVector<const SCEV *, 2> V;
845 V.push_back(reinterpret_cast<const SCEV *>(-1));
846 return V;
847 }
848
849 static SmallVector<const SCEV *, 2> getTombstoneKey() {
850 SmallVector<const SCEV *, 2> V;
851 V.push_back(reinterpret_cast<const SCEV *>(-2));
852 return V;
853 }
854
855 static unsigned getHashValue(const SmallVector<const SCEV *, 2> &V) {
856 unsigned Result = 0;
857 for (SmallVectorImpl<const SCEV *>::const_iterator I = V.begin(),
858 E = V.end(); I != E; ++I)
859 Result ^= DenseMapInfo<const SCEV *>::getHashValue(*I);
860 return Result;
861 }
862
863 static bool isEqual(const SmallVector<const SCEV *, 2> &LHS,
864 const SmallVector<const SCEV *, 2> &RHS) {
865 return LHS == RHS;
866 }
867};
868
869/// LSRUse - This class holds the state that LSR keeps for each use in
870/// IVUsers, as well as uses invented by LSR itself. It includes information
871/// about what kinds of things can be folded into the user, information about
872/// the user itself, and information about how the use may be satisfied.
873/// TODO: Represent multiple users of the same expression in common?
874class LSRUse {
875 DenseSet<SmallVector<const SCEV *, 2>, UniquifierDenseMapInfo> Uniquifier;
876
877public:
878 /// KindType - An enum for a kind of use, indicating what types of
879 /// scaled and immediate operands it might support.
880 enum KindType {
881 Basic, ///< A normal use, with no folding.
882 Special, ///< A special case of basic, allowing -1 scales.
883 Address, ///< An address use; folding according to TargetLowering
884 ICmpZero ///< An equality icmp with both operands folded into one.
885 // TODO: Add a generic icmp too?
Dan Gohman7979b722010-01-22 00:46:49 +0000886 };
Dan Gohman572645c2010-02-12 10:34:29 +0000887
888 KindType Kind;
889 const Type *AccessTy;
890
891 SmallVector<int64_t, 8> Offsets;
892 int64_t MinOffset;
893 int64_t MaxOffset;
894
895 /// AllFixupsOutsideLoop - This records whether all of the fixups using this
896 /// LSRUse are outside of the loop, in which case some special-case heuristics
897 /// may be used.
898 bool AllFixupsOutsideLoop;
899
900 /// Formulae - A list of ways to build a value that can satisfy this user.
901 /// After the list is populated, one of these is selected heuristically and
902 /// used to formulate a replacement for OperandValToReplace in UserInst.
903 SmallVector<Formula, 12> Formulae;
904
905 /// Regs - The set of register candidates used by all formulae in this LSRUse.
906 SmallPtrSet<const SCEV *, 4> Regs;
907
908 LSRUse(KindType K, const Type *T) : Kind(K), AccessTy(T),
909 MinOffset(INT64_MAX),
910 MaxOffset(INT64_MIN),
911 AllFixupsOutsideLoop(true) {}
912
913 bool InsertFormula(size_t LUIdx, const Formula &F);
914
915 void check() const;
916
917 void print(raw_ostream &OS) const;
918 void dump() const;
919};
920
921/// InsertFormula - If the given formula has not yet been inserted, add it to
922/// the list, and return true. Return false otherwise.
923bool LSRUse::InsertFormula(size_t LUIdx, const Formula &F) {
924 SmallVector<const SCEV *, 2> Key = F.BaseRegs;
925 if (F.ScaledReg) Key.push_back(F.ScaledReg);
926 // Unstable sort by host order ok, because this is only used for uniquifying.
927 std::sort(Key.begin(), Key.end());
928
929 if (!Uniquifier.insert(Key).second)
930 return false;
931
932 // Using a register to hold the value of 0 is not profitable.
933 assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&
934 "Zero allocated in a scaled register!");
935#ifndef NDEBUG
936 for (SmallVectorImpl<const SCEV *>::const_iterator I =
937 F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I)
938 assert(!(*I)->isZero() && "Zero allocated in a base register!");
939#endif
940
941 // Add the formula to the list.
942 Formulae.push_back(F);
943
944 // Record registers now being used by this use.
945 if (F.ScaledReg) Regs.insert(F.ScaledReg);
946 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
947
948 return true;
Dan Gohman7979b722010-01-22 00:46:49 +0000949}
950
Dan Gohman572645c2010-02-12 10:34:29 +0000951void LSRUse::print(raw_ostream &OS) const {
952 OS << "LSR Use: Kind=";
953 switch (Kind) {
954 case Basic: OS << "Basic"; break;
955 case Special: OS << "Special"; break;
956 case ICmpZero: OS << "ICmpZero"; break;
957 case Address:
958 OS << "Address of ";
Duncan Sands1df98592010-02-16 11:11:14 +0000959 if (AccessTy->isPointerTy())
Dan Gohman572645c2010-02-12 10:34:29 +0000960 OS << "pointer"; // the full pointer type could be really verbose
961 else
962 OS << *AccessTy;
Evan Chengcdf43b12007-10-25 09:11:16 +0000963 }
964
Dan Gohman572645c2010-02-12 10:34:29 +0000965 OS << ", Offsets={";
966 for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
967 E = Offsets.end(); I != E; ++I) {
968 OS << *I;
969 if (next(I) != E)
970 OS << ',';
Dan Gohman7979b722010-01-22 00:46:49 +0000971 }
Dan Gohman572645c2010-02-12 10:34:29 +0000972 OS << '}';
Dan Gohman7979b722010-01-22 00:46:49 +0000973
Dan Gohman572645c2010-02-12 10:34:29 +0000974 if (AllFixupsOutsideLoop)
975 OS << ", all-fixups-outside-loop";
Dan Gohman7979b722010-01-22 00:46:49 +0000976}
977
Dan Gohman572645c2010-02-12 10:34:29 +0000978void LSRUse::dump() const {
979 print(errs()); errs() << '\n';
980}
Dan Gohman7979b722010-01-22 00:46:49 +0000981
Dan Gohman572645c2010-02-12 10:34:29 +0000982/// isLegalUse - Test whether the use described by AM is "legal", meaning it can
983/// be completely folded into the user instruction at isel time. This includes
984/// address-mode folding and special icmp tricks.
985static bool isLegalUse(const TargetLowering::AddrMode &AM,
986 LSRUse::KindType Kind, const Type *AccessTy,
987 const TargetLowering *TLI) {
988 switch (Kind) {
989 case LSRUse::Address:
990 // If we have low-level target information, ask the target if it can
991 // completely fold this address.
992 if (TLI) return TLI->isLegalAddressingMode(AM, AccessTy);
993
994 // Otherwise, just guess that reg+reg addressing is legal.
995 return !AM.BaseGV && AM.BaseOffs == 0 && AM.Scale <= 1;
996
997 case LSRUse::ICmpZero:
998 // There's not even a target hook for querying whether it would be legal to
999 // fold a GV into an ICmp.
1000 if (AM.BaseGV)
1001 return false;
1002
1003 // ICmp only has two operands; don't allow more than two non-trivial parts.
1004 if (AM.Scale != 0 && AM.HasBaseReg && AM.BaseOffs != 0)
1005 return false;
1006
1007 // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by
1008 // putting the scaled register in the other operand of the icmp.
1009 if (AM.Scale != 0 && AM.Scale != -1)
1010 return false;
1011
1012 // If we have low-level target information, ask the target if it can fold an
1013 // integer immediate on an icmp.
1014 if (AM.BaseOffs != 0) {
1015 if (TLI) return TLI->isLegalICmpImmediate(-AM.BaseOffs);
1016 return false;
Dan Gohman7979b722010-01-22 00:46:49 +00001017 }
Dan Gohman572645c2010-02-12 10:34:29 +00001018
1019 return true;
1020
1021 case LSRUse::Basic:
1022 // Only handle single-register values.
1023 return !AM.BaseGV && AM.Scale == 0 && AM.BaseOffs == 0;
1024
1025 case LSRUse::Special:
1026 // Only handle -1 scales, or no scale.
1027 return AM.Scale == 0 || AM.Scale == -1;
Dan Gohman7979b722010-01-22 00:46:49 +00001028 }
1029
Dan Gohman7979b722010-01-22 00:46:49 +00001030 return false;
1031}
1032
Dan Gohman572645c2010-02-12 10:34:29 +00001033static bool isLegalUse(TargetLowering::AddrMode AM,
1034 int64_t MinOffset, int64_t MaxOffset,
1035 LSRUse::KindType Kind, const Type *AccessTy,
1036 const TargetLowering *TLI) {
1037 // Check for overflow.
1038 if (((int64_t)((uint64_t)AM.BaseOffs + MinOffset) > AM.BaseOffs) !=
1039 (MinOffset > 0))
1040 return false;
1041 AM.BaseOffs = (uint64_t)AM.BaseOffs + MinOffset;
1042 if (isLegalUse(AM, Kind, AccessTy, TLI)) {
1043 AM.BaseOffs = (uint64_t)AM.BaseOffs - MinOffset;
1044 // Check for overflow.
1045 if (((int64_t)((uint64_t)AM.BaseOffs + MaxOffset) > AM.BaseOffs) !=
1046 (MaxOffset > 0))
1047 return false;
1048 AM.BaseOffs = (uint64_t)AM.BaseOffs + MaxOffset;
1049 return isLegalUse(AM, Kind, AccessTy, TLI);
Dan Gohman7979b722010-01-22 00:46:49 +00001050 }
Dan Gohman572645c2010-02-12 10:34:29 +00001051 return false;
Dan Gohman7979b722010-01-22 00:46:49 +00001052}
1053
Dan Gohman572645c2010-02-12 10:34:29 +00001054static bool isAlwaysFoldable(int64_t BaseOffs,
1055 GlobalValue *BaseGV,
1056 bool HasBaseReg,
1057 LSRUse::KindType Kind, const Type *AccessTy,
1058 const TargetLowering *TLI,
1059 ScalarEvolution &SE) {
1060 // Fast-path: zero is always foldable.
1061 if (BaseOffs == 0 && !BaseGV) return true;
Dan Gohman7979b722010-01-22 00:46:49 +00001062
Dan Gohman572645c2010-02-12 10:34:29 +00001063 // Conservatively, create an address with an immediate and a
1064 // base and a scale.
1065 TargetLowering::AddrMode AM;
1066 AM.BaseOffs = BaseOffs;
1067 AM.BaseGV = BaseGV;
1068 AM.HasBaseReg = HasBaseReg;
1069 AM.Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
Dan Gohman7979b722010-01-22 00:46:49 +00001070
Dan Gohman572645c2010-02-12 10:34:29 +00001071 return isLegalUse(AM, Kind, AccessTy, TLI);
Dan Gohman7979b722010-01-22 00:46:49 +00001072}
1073
Dan Gohman572645c2010-02-12 10:34:29 +00001074static bool isAlwaysFoldable(const SCEV *S,
1075 int64_t MinOffset, int64_t MaxOffset,
1076 bool HasBaseReg,
1077 LSRUse::KindType Kind, const Type *AccessTy,
1078 const TargetLowering *TLI,
1079 ScalarEvolution &SE) {
1080 // Fast-path: zero is always foldable.
1081 if (S->isZero()) return true;
1082
1083 // Conservatively, create an address with an immediate and a
1084 // base and a scale.
1085 int64_t BaseOffs = ExtractImmediate(S, SE);
1086 GlobalValue *BaseGV = ExtractSymbol(S, SE);
1087
1088 // If there's anything else involved, it's not foldable.
1089 if (!S->isZero()) return false;
1090
1091 // Fast-path: zero is always foldable.
1092 if (BaseOffs == 0 && !BaseGV) return true;
1093
1094 // Conservatively, create an address with an immediate and a
1095 // base and a scale.
1096 TargetLowering::AddrMode AM;
1097 AM.BaseOffs = BaseOffs;
1098 AM.BaseGV = BaseGV;
1099 AM.HasBaseReg = HasBaseReg;
1100 AM.Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1101
1102 return isLegalUse(AM, MinOffset, MaxOffset, Kind, AccessTy, TLI);
Dan Gohman7979b722010-01-22 00:46:49 +00001103}
1104
Dan Gohman572645c2010-02-12 10:34:29 +00001105/// FormulaSorter - This class implements an ordering for formulae which sorts
1106/// the by their standalone cost.
1107class FormulaSorter {
1108 /// These two sets are kept empty, so that we compute standalone costs.
1109 DenseSet<const SCEV *> VisitedRegs;
1110 SmallPtrSet<const SCEV *, 16> Regs;
1111 Loop *L;
1112 LSRUse *LU;
1113 ScalarEvolution &SE;
1114 DominatorTree &DT;
1115
1116public:
1117 FormulaSorter(Loop *l, LSRUse &lu, ScalarEvolution &se, DominatorTree &dt)
1118 : L(l), LU(&lu), SE(se), DT(dt) {}
1119
1120 bool operator()(const Formula &A, const Formula &B) {
1121 Cost CostA;
1122 CostA.RateFormula(A, Regs, VisitedRegs, L, LU->Offsets, SE, DT);
1123 Regs.clear();
1124 Cost CostB;
1125 CostB.RateFormula(B, Regs, VisitedRegs, L, LU->Offsets, SE, DT);
1126 Regs.clear();
1127 return CostA < CostB;
1128 }
1129};
1130
1131/// LSRInstance - This class holds state for the main loop strength reduction
1132/// logic.
1133class LSRInstance {
1134 IVUsers &IU;
1135 ScalarEvolution &SE;
1136 DominatorTree &DT;
1137 const TargetLowering *const TLI;
1138 Loop *const L;
1139 bool Changed;
1140
1141 /// IVIncInsertPos - This is the insert position that the current loop's
1142 /// induction variable increment should be placed. In simple loops, this is
1143 /// the latch block's terminator. But in more complicated cases, this is a
1144 /// position which will dominate all the in-loop post-increment users.
1145 Instruction *IVIncInsertPos;
1146
1147 /// Factors - Interesting factors between use strides.
1148 SmallSetVector<int64_t, 8> Factors;
1149
1150 /// Types - Interesting use types, to facilitate truncation reuse.
1151 SmallSetVector<const Type *, 4> Types;
1152
1153 /// Fixups - The list of operands which are to be replaced.
1154 SmallVector<LSRFixup, 16> Fixups;
1155
1156 /// Uses - The list of interesting uses.
1157 SmallVector<LSRUse, 16> Uses;
1158
1159 /// RegUses - Track which uses use which register candidates.
1160 RegUseTracker RegUses;
1161
1162 void OptimizeShadowIV();
1163 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse);
1164 ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse);
1165 bool OptimizeLoopTermCond();
1166
1167 void CollectInterestingTypesAndFactors();
1168 void CollectFixupsAndInitialFormulae();
1169
1170 LSRFixup &getNewFixup() {
1171 Fixups.push_back(LSRFixup());
1172 return Fixups.back();
1173 }
1174
1175 // Support for sharing of LSRUses between LSRFixups.
1176 typedef DenseMap<const SCEV *, size_t> UseMapTy;
1177 UseMapTy UseMap;
1178
1179 bool reconcileNewOffset(LSRUse &LU, int64_t NewOffset,
1180 LSRUse::KindType Kind, const Type *AccessTy);
1181
1182 std::pair<size_t, int64_t> getUse(const SCEV *&Expr,
1183 LSRUse::KindType Kind,
1184 const Type *AccessTy);
1185
1186public:
1187 void InsertInitialFormula(const SCEV *S, Loop *L, LSRUse &LU, size_t LUIdx);
1188 void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
1189 void CountRegisters(const Formula &F, size_t LUIdx);
1190 bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F);
1191
1192 void CollectLoopInvariantFixupsAndFormulae();
1193
1194 void GenerateReassociations(LSRUse &LU, unsigned LUIdx, Formula Base,
1195 unsigned Depth = 0);
1196 void GenerateCombinations(LSRUse &LU, unsigned LUIdx, Formula Base);
1197 void GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1198 void GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1199 void GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1200 void GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1201 void GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base);
1202 void GenerateCrossUseConstantOffsets();
1203 void GenerateAllReuseFormulae();
1204
1205 void FilterOutUndesirableDedicatedRegisters();
1206 void NarrowSearchSpaceUsingHeuristics();
1207
1208 void SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
1209 Cost &SolutionCost,
1210 SmallVectorImpl<const Formula *> &Workspace,
1211 const Cost &CurCost,
1212 const SmallPtrSet<const SCEV *, 16> &CurRegs,
1213 DenseSet<const SCEV *> &VisitedRegs) const;
1214 void Solve(SmallVectorImpl<const Formula *> &Solution) const;
1215
1216 Value *Expand(const LSRFixup &LF,
1217 const Formula &F,
1218 BasicBlock::iterator IP, Loop *L, Instruction *IVIncInsertPos,
1219 SCEVExpander &Rewriter,
1220 SmallVectorImpl<WeakVH> &DeadInsts,
1221 ScalarEvolution &SE, DominatorTree &DT) const;
Dan Gohman3a02cbc2010-02-16 20:25:07 +00001222 void RewriteForPHI(PHINode *PN, const LSRFixup &LF,
1223 const Formula &F,
1224 Loop *L, Instruction *IVIncInsertPos,
1225 SCEVExpander &Rewriter,
1226 SmallVectorImpl<WeakVH> &DeadInsts,
1227 ScalarEvolution &SE, DominatorTree &DT,
1228 Pass *P) const;
Dan Gohman572645c2010-02-12 10:34:29 +00001229 void Rewrite(const LSRFixup &LF,
1230 const Formula &F,
1231 Loop *L, Instruction *IVIncInsertPos,
1232 SCEVExpander &Rewriter,
1233 SmallVectorImpl<WeakVH> &DeadInsts,
1234 ScalarEvolution &SE, DominatorTree &DT,
1235 Pass *P) const;
1236 void ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
1237 Pass *P);
1238
1239 LSRInstance(const TargetLowering *tli, Loop *l, Pass *P);
1240
1241 bool getChanged() const { return Changed; }
1242
1243 void print_factors_and_types(raw_ostream &OS) const;
1244 void print_fixups(raw_ostream &OS) const;
1245 void print_uses(raw_ostream &OS) const;
1246 void print(raw_ostream &OS) const;
1247 void dump() const;
1248};
1249
1250}
1251
1252/// OptimizeShadowIV - If IV is used in a int-to-float cast
1253/// inside the loop then try to eliminate the cast opeation.
1254void LSRInstance::OptimizeShadowIV() {
1255 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
1256 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1257 return;
1258
1259 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end();
1260 UI != E; /* empty */) {
1261 IVUsers::const_iterator CandidateUI = UI;
1262 ++UI;
1263 Instruction *ShadowUse = CandidateUI->getUser();
1264 const Type *DestTy = NULL;
1265
1266 /* If shadow use is a int->float cast then insert a second IV
1267 to eliminate this cast.
1268
1269 for (unsigned i = 0; i < n; ++i)
1270 foo((double)i);
1271
1272 is transformed into
1273
1274 double d = 0.0;
1275 for (unsigned i = 0; i < n; ++i, ++d)
1276 foo(d);
1277 */
1278 if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser()))
1279 DestTy = UCast->getDestTy();
1280 else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser()))
1281 DestTy = SCast->getDestTy();
1282 if (!DestTy) continue;
1283
1284 if (TLI) {
1285 // If target does not support DestTy natively then do not apply
1286 // this transformation.
1287 EVT DVT = TLI->getValueType(DestTy);
1288 if (!TLI->isTypeLegal(DVT)) continue;
1289 }
1290
1291 PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
1292 if (!PH) continue;
1293 if (PH->getNumIncomingValues() != 2) continue;
1294
1295 const Type *SrcTy = PH->getType();
1296 int Mantissa = DestTy->getFPMantissaWidth();
1297 if (Mantissa == -1) continue;
1298 if ((int)SE.getTypeSizeInBits(SrcTy) > Mantissa)
1299 continue;
1300
1301 unsigned Entry, Latch;
1302 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
1303 Entry = 0;
1304 Latch = 1;
Dan Gohman7979b722010-01-22 00:46:49 +00001305 } else {
Dan Gohman572645c2010-02-12 10:34:29 +00001306 Entry = 1;
1307 Latch = 0;
Dan Gohman7979b722010-01-22 00:46:49 +00001308 }
Dan Gohman7979b722010-01-22 00:46:49 +00001309
Dan Gohman572645c2010-02-12 10:34:29 +00001310 ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
1311 if (!Init) continue;
1312 Constant *NewInit = ConstantFP::get(DestTy, Init->getZExtValue());
Dan Gohman7979b722010-01-22 00:46:49 +00001313
Dan Gohman572645c2010-02-12 10:34:29 +00001314 BinaryOperator *Incr =
1315 dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
1316 if (!Incr) continue;
1317 if (Incr->getOpcode() != Instruction::Add
1318 && Incr->getOpcode() != Instruction::Sub)
Dan Gohman7979b722010-01-22 00:46:49 +00001319 continue;
Dan Gohman7979b722010-01-22 00:46:49 +00001320
Dan Gohman572645c2010-02-12 10:34:29 +00001321 /* Initialize new IV, double d = 0.0 in above example. */
1322 ConstantInt *C = NULL;
1323 if (Incr->getOperand(0) == PH)
1324 C = dyn_cast<ConstantInt>(Incr->getOperand(1));
1325 else if (Incr->getOperand(1) == PH)
1326 C = dyn_cast<ConstantInt>(Incr->getOperand(0));
Dan Gohman7979b722010-01-22 00:46:49 +00001327 else
Dan Gohman7979b722010-01-22 00:46:49 +00001328 continue;
1329
Dan Gohman572645c2010-02-12 10:34:29 +00001330 if (!C) continue;
Dan Gohman7979b722010-01-22 00:46:49 +00001331
Dan Gohman572645c2010-02-12 10:34:29 +00001332 // Ignore negative constants, as the code below doesn't handle them
1333 // correctly. TODO: Remove this restriction.
1334 if (!C->getValue().isStrictlyPositive()) continue;
Dan Gohman7979b722010-01-22 00:46:49 +00001335
Dan Gohman572645c2010-02-12 10:34:29 +00001336 /* Add new PHINode. */
1337 PHINode *NewPH = PHINode::Create(DestTy, "IV.S.", PH);
Dan Gohman7979b722010-01-22 00:46:49 +00001338
Dan Gohman572645c2010-02-12 10:34:29 +00001339 /* create new increment. '++d' in above example. */
1340 Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue());
1341 BinaryOperator *NewIncr =
1342 BinaryOperator::Create(Incr->getOpcode() == Instruction::Add ?
1343 Instruction::FAdd : Instruction::FSub,
1344 NewPH, CFP, "IV.S.next.", Incr);
Dan Gohman7979b722010-01-22 00:46:49 +00001345
Dan Gohman572645c2010-02-12 10:34:29 +00001346 NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
1347 NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
Dan Gohman7979b722010-01-22 00:46:49 +00001348
Dan Gohman572645c2010-02-12 10:34:29 +00001349 /* Remove cast operation */
1350 ShadowUse->replaceAllUsesWith(NewPH);
1351 ShadowUse->eraseFromParent();
1352 break;
Dan Gohman7979b722010-01-22 00:46:49 +00001353 }
1354}
1355
1356/// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
1357/// set the IV user and stride information and return true, otherwise return
1358/// false.
Dan Gohman572645c2010-02-12 10:34:29 +00001359bool LSRInstance::FindIVUserForCond(ICmpInst *Cond,
1360 IVStrideUse *&CondUse) {
1361 for (IVUsers::iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
1362 if (UI->getUser() == Cond) {
1363 // NOTE: we could handle setcc instructions with multiple uses here, but
1364 // InstCombine does it as well for simple uses, it's not clear that it
1365 // occurs enough in real life to handle.
1366 CondUse = UI;
1367 return true;
1368 }
Dan Gohman7979b722010-01-22 00:46:49 +00001369 return false;
Evan Chengcdf43b12007-10-25 09:11:16 +00001370}
1371
Dan Gohman7979b722010-01-22 00:46:49 +00001372/// OptimizeMax - Rewrite the loop's terminating condition if it uses
1373/// a max computation.
1374///
1375/// This is a narrow solution to a specific, but acute, problem. For loops
1376/// like this:
1377///
1378/// i = 0;
1379/// do {
1380/// p[i] = 0.0;
1381/// } while (++i < n);
1382///
1383/// the trip count isn't just 'n', because 'n' might not be positive. And
1384/// unfortunately this can come up even for loops where the user didn't use
1385/// a C do-while loop. For example, seemingly well-behaved top-test loops
1386/// will commonly be lowered like this:
1387//
1388/// if (n > 0) {
1389/// i = 0;
1390/// do {
1391/// p[i] = 0.0;
1392/// } while (++i < n);
1393/// }
1394///
1395/// and then it's possible for subsequent optimization to obscure the if
1396/// test in such a way that indvars can't find it.
1397///
1398/// When indvars can't find the if test in loops like this, it creates a
1399/// max expression, which allows it to give the loop a canonical
1400/// induction variable:
1401///
1402/// i = 0;
1403/// max = n < 1 ? 1 : n;
1404/// do {
1405/// p[i] = 0.0;
1406/// } while (++i != max);
1407///
1408/// Canonical induction variables are necessary because the loop passes
1409/// are designed around them. The most obvious example of this is the
1410/// LoopInfo analysis, which doesn't remember trip count values. It
1411/// expects to be able to rediscover the trip count each time it is
Dan Gohman572645c2010-02-12 10:34:29 +00001412/// needed, and it does this using a simple analysis that only succeeds if
Dan Gohman7979b722010-01-22 00:46:49 +00001413/// the loop has a canonical induction variable.
1414///
1415/// However, when it comes time to generate code, the maximum operation
1416/// can be quite costly, especially if it's inside of an outer loop.
1417///
1418/// This function solves this problem by detecting this type of loop and
1419/// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
1420/// the instructions for the maximum computation.
1421///
Dan Gohman572645c2010-02-12 10:34:29 +00001422ICmpInst *LSRInstance::OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse) {
Dan Gohman7979b722010-01-22 00:46:49 +00001423 // Check that the loop matches the pattern we're looking for.
1424 if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
1425 Cond->getPredicate() != CmpInst::ICMP_NE)
1426 return Cond;
Dan Gohmana10756e2010-01-21 02:09:26 +00001427
Dan Gohman7979b722010-01-22 00:46:49 +00001428 SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
1429 if (!Sel || !Sel->hasOneUse()) return Cond;
Dan Gohmana10756e2010-01-21 02:09:26 +00001430
Dan Gohman572645c2010-02-12 10:34:29 +00001431 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
Dan Gohman7979b722010-01-22 00:46:49 +00001432 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1433 return Cond;
Dan Gohman572645c2010-02-12 10:34:29 +00001434 const SCEV *One = SE.getIntegerSCEV(1, BackedgeTakenCount->getType());
Dan Gohmana10756e2010-01-21 02:09:26 +00001435
Dan Gohman7979b722010-01-22 00:46:49 +00001436 // Add one to the backedge-taken count to get the trip count.
Dan Gohman572645c2010-02-12 10:34:29 +00001437 const SCEV *IterationCount = SE.getAddExpr(BackedgeTakenCount, One);
Dan Gohman7979b722010-01-22 00:46:49 +00001438
1439 // Check for a max calculation that matches the pattern.
1440 if (!isa<SCEVSMaxExpr>(IterationCount) && !isa<SCEVUMaxExpr>(IterationCount))
1441 return Cond;
1442 const SCEVNAryExpr *Max = cast<SCEVNAryExpr>(IterationCount);
Dan Gohman572645c2010-02-12 10:34:29 +00001443 if (Max != SE.getSCEV(Sel)) return Cond;
Dan Gohman7979b722010-01-22 00:46:49 +00001444
1445 // To handle a max with more than two operands, this optimization would
1446 // require additional checking and setup.
1447 if (Max->getNumOperands() != 2)
1448 return Cond;
1449
1450 const SCEV *MaxLHS = Max->getOperand(0);
1451 const SCEV *MaxRHS = Max->getOperand(1);
1452 if (!MaxLHS || MaxLHS != One) return Cond;
Dan Gohman7979b722010-01-22 00:46:49 +00001453 // Check the relevant induction variable for conformance to
1454 // the pattern.
Dan Gohman572645c2010-02-12 10:34:29 +00001455 const SCEV *IV = SE.getSCEV(Cond->getOperand(0));
Dan Gohman7979b722010-01-22 00:46:49 +00001456 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
1457 if (!AR || !AR->isAffine() ||
1458 AR->getStart() != One ||
Dan Gohman572645c2010-02-12 10:34:29 +00001459 AR->getStepRecurrence(SE) != One)
Dan Gohman7979b722010-01-22 00:46:49 +00001460 return Cond;
1461
1462 assert(AR->getLoop() == L &&
1463 "Loop condition operand is an addrec in a different loop!");
1464
1465 // Check the right operand of the select, and remember it, as it will
1466 // be used in the new comparison instruction.
1467 Value *NewRHS = 0;
Dan Gohman572645c2010-02-12 10:34:29 +00001468 if (SE.getSCEV(Sel->getOperand(1)) == MaxRHS)
Dan Gohman7979b722010-01-22 00:46:49 +00001469 NewRHS = Sel->getOperand(1);
Dan Gohman572645c2010-02-12 10:34:29 +00001470 else if (SE.getSCEV(Sel->getOperand(2)) == MaxRHS)
Dan Gohman7979b722010-01-22 00:46:49 +00001471 NewRHS = Sel->getOperand(2);
1472 if (!NewRHS) return Cond;
1473
1474 // Determine the new comparison opcode. It may be signed or unsigned,
1475 // and the original comparison may be either equality or inequality.
1476 CmpInst::Predicate Pred =
1477 isa<SCEVSMaxExpr>(Max) ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;
1478 if (Cond->getPredicate() == CmpInst::ICMP_EQ)
1479 Pred = CmpInst::getInversePredicate(Pred);
1480
1481 // Ok, everything looks ok to change the condition into an SLT or SGE and
1482 // delete the max calculation.
1483 ICmpInst *NewCond =
1484 new ICmpInst(Cond, Pred, Cond->getOperand(0), NewRHS, "scmp");
1485
1486 // Delete the max calculation instructions.
1487 Cond->replaceAllUsesWith(NewCond);
1488 CondUse->setUser(NewCond);
1489 Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
1490 Cond->eraseFromParent();
1491 Sel->eraseFromParent();
1492 if (Cmp->use_empty())
1493 Cmp->eraseFromParent();
1494 return NewCond;
Dan Gohmanad7321f2008-09-15 21:22:06 +00001495}
1496
Jim Grosbach56a1f802009-11-17 17:53:56 +00001497/// OptimizeLoopTermCond - Change loop terminating condition to use the
Evan Cheng586f69a2009-11-12 07:35:05 +00001498/// postinc iv when possible.
Dan Gohman572645c2010-02-12 10:34:29 +00001499bool
1500LSRInstance::OptimizeLoopTermCond() {
1501 SmallPtrSet<Instruction *, 4> PostIncs;
1502
Evan Cheng586f69a2009-11-12 07:35:05 +00001503 BasicBlock *LatchBlock = L->getLoopLatch();
Evan Cheng076e0852009-11-17 18:10:11 +00001504 SmallVector<BasicBlock*, 8> ExitingBlocks;
1505 L->getExitingBlocks(ExitingBlocks);
Jim Grosbach56a1f802009-11-17 17:53:56 +00001506
Evan Cheng076e0852009-11-17 18:10:11 +00001507 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
1508 BasicBlock *ExitingBlock = ExitingBlocks[i];
Evan Cheng586f69a2009-11-12 07:35:05 +00001509
Dan Gohman572645c2010-02-12 10:34:29 +00001510 // Get the terminating condition for the loop if possible. If we
Evan Cheng076e0852009-11-17 18:10:11 +00001511 // can, we want to change it to use a post-incremented version of its
1512 // induction variable, to allow coalescing the live ranges for the IV into
1513 // one register value.
Evan Cheng586f69a2009-11-12 07:35:05 +00001514
Evan Cheng076e0852009-11-17 18:10:11 +00001515 BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1516 if (!TermBr)
1517 continue;
1518 // FIXME: Overly conservative, termination condition could be an 'or' etc..
1519 if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
1520 continue;
Evan Cheng586f69a2009-11-12 07:35:05 +00001521
Evan Cheng076e0852009-11-17 18:10:11 +00001522 // Search IVUsesByStride to find Cond's IVUse if there is one.
1523 IVStrideUse *CondUse = 0;
Evan Cheng076e0852009-11-17 18:10:11 +00001524 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
Dan Gohman572645c2010-02-12 10:34:29 +00001525 if (!FindIVUserForCond(Cond, CondUse))
Evan Cheng076e0852009-11-17 18:10:11 +00001526 continue;
1527
Evan Cheng076e0852009-11-17 18:10:11 +00001528 // If the trip count is computed in terms of a max (due to ScalarEvolution
1529 // being unable to find a sufficient guard, for example), change the loop
1530 // comparison to use SLT or ULT instead of NE.
Dan Gohman572645c2010-02-12 10:34:29 +00001531 // One consequence of doing this now is that it disrupts the count-down
1532 // optimization. That's not always a bad thing though, because in such
1533 // cases it may still be worthwhile to avoid a max.
1534 Cond = OptimizeMax(Cond, CondUse);
Evan Cheng076e0852009-11-17 18:10:11 +00001535
Dan Gohman572645c2010-02-12 10:34:29 +00001536 // If this exiting block dominates the latch block, it may also use
1537 // the post-inc value if it won't be shared with other uses.
1538 // Check for dominance.
1539 if (!DT.dominates(ExitingBlock, LatchBlock))
Dan Gohman7979b722010-01-22 00:46:49 +00001540 continue;
Evan Cheng076e0852009-11-17 18:10:11 +00001541
Dan Gohman572645c2010-02-12 10:34:29 +00001542 // Conservatively avoid trying to use the post-inc value in non-latch
1543 // exits if there may be pre-inc users in intervening blocks.
Dan Gohman590bfe82010-02-14 03:21:49 +00001544 if (LatchBlock != ExitingBlock)
Dan Gohman572645c2010-02-12 10:34:29 +00001545 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
1546 // Test if the use is reachable from the exiting block. This dominator
1547 // query is a conservative approximation of reachability.
1548 if (&*UI != CondUse &&
1549 !DT.properlyDominates(UI->getUser()->getParent(), ExitingBlock)) {
1550 // Conservatively assume there may be reuse if the quotient of their
1551 // strides could be a legal scale.
1552 const SCEV *A = CondUse->getStride();
1553 const SCEV *B = UI->getStride();
1554 if (SE.getTypeSizeInBits(A->getType()) !=
1555 SE.getTypeSizeInBits(B->getType())) {
1556 if (SE.getTypeSizeInBits(A->getType()) >
1557 SE.getTypeSizeInBits(B->getType()))
1558 B = SE.getSignExtendExpr(B, A->getType());
1559 else
1560 A = SE.getSignExtendExpr(A, B->getType());
1561 }
1562 if (const SCEVConstant *D =
1563 dyn_cast_or_null<SCEVConstant>(getSDiv(B, A, SE))) {
1564 // Stride of one or negative one can have reuse with non-addresses.
1565 if (D->getValue()->isOne() ||
1566 D->getValue()->isAllOnesValue())
1567 goto decline_post_inc;
1568 // Avoid weird situations.
1569 if (D->getValue()->getValue().getMinSignedBits() >= 64 ||
1570 D->getValue()->getValue().isMinSignedValue())
1571 goto decline_post_inc;
Dan Gohman590bfe82010-02-14 03:21:49 +00001572 // Without TLI, assume that any stride might be valid, and so any
1573 // use might be shared.
1574 if (!TLI)
1575 goto decline_post_inc;
Dan Gohman572645c2010-02-12 10:34:29 +00001576 // Check for possible scaled-address reuse.
1577 const Type *AccessTy = getAccessType(UI->getUser());
1578 TargetLowering::AddrMode AM;
1579 AM.Scale = D->getValue()->getSExtValue();
Dan Gohman2763dfd2010-02-14 02:45:21 +00001580 if (TLI->isLegalAddressingMode(AM, AccessTy))
Dan Gohman572645c2010-02-12 10:34:29 +00001581 goto decline_post_inc;
1582 AM.Scale = -AM.Scale;
Dan Gohman2763dfd2010-02-14 02:45:21 +00001583 if (TLI->isLegalAddressingMode(AM, AccessTy))
Dan Gohman572645c2010-02-12 10:34:29 +00001584 goto decline_post_inc;
1585 }
1586 }
1587
David Greene63c94632009-12-23 22:58:38 +00001588 DEBUG(dbgs() << " Change loop exiting icmp to use postinc iv: "
Dan Gohman572645c2010-02-12 10:34:29 +00001589 << *Cond << '\n');
Evan Cheng076e0852009-11-17 18:10:11 +00001590
1591 // It's possible for the setcc instruction to be anywhere in the loop, and
1592 // possible for it to have multiple users. If it is not immediately before
1593 // the exiting block branch, move it.
Dan Gohman572645c2010-02-12 10:34:29 +00001594 if (&*++BasicBlock::iterator(Cond) != TermBr) {
1595 if (Cond->hasOneUse()) {
Evan Cheng076e0852009-11-17 18:10:11 +00001596 Cond->moveBefore(TermBr);
1597 } else {
Dan Gohman572645c2010-02-12 10:34:29 +00001598 // Clone the terminating condition and insert into the loopend.
1599 ICmpInst *OldCond = Cond;
Evan Cheng076e0852009-11-17 18:10:11 +00001600 Cond = cast<ICmpInst>(Cond->clone());
1601 Cond->setName(L->getHeader()->getName() + ".termcond");
1602 ExitingBlock->getInstList().insert(TermBr, Cond);
1603
1604 // Clone the IVUse, as the old use still exists!
Dan Gohman572645c2010-02-12 10:34:29 +00001605 CondUse = &IU.AddUser(CondUse->getStride(), CondUse->getOffset(),
1606 Cond, CondUse->getOperandValToReplace());
1607 TermBr->replaceUsesOfWith(OldCond, Cond);
Evan Cheng076e0852009-11-17 18:10:11 +00001608 }
Evan Cheng586f69a2009-11-12 07:35:05 +00001609 }
1610
Evan Cheng076e0852009-11-17 18:10:11 +00001611 // If we get to here, we know that we can transform the setcc instruction to
1612 // use the post-incremented version of the IV, allowing us to coalesce the
1613 // live ranges for the IV correctly.
Dan Gohman572645c2010-02-12 10:34:29 +00001614 CondUse->setOffset(SE.getMinusSCEV(CondUse->getOffset(),
1615 CondUse->getStride()));
Evan Cheng076e0852009-11-17 18:10:11 +00001616 CondUse->setIsUseOfPostIncrementedValue(true);
1617 Changed = true;
1618
Dan Gohman572645c2010-02-12 10:34:29 +00001619 PostIncs.insert(Cond);
1620 decline_post_inc:;
Dan Gohmana10756e2010-01-21 02:09:26 +00001621 }
Dan Gohman572645c2010-02-12 10:34:29 +00001622
1623 // Determine an insertion point for the loop induction variable increment. It
1624 // must dominate all the post-inc comparisons we just set up, and it must
1625 // dominate the loop latch edge.
1626 IVIncInsertPos = L->getLoopLatch()->getTerminator();
1627 for (SmallPtrSet<Instruction *, 4>::const_iterator I = PostIncs.begin(),
1628 E = PostIncs.end(); I != E; ++I) {
1629 BasicBlock *BB =
1630 DT.findNearestCommonDominator(IVIncInsertPos->getParent(),
1631 (*I)->getParent());
1632 if (BB == (*I)->getParent())
1633 IVIncInsertPos = *I;
1634 else if (BB != IVIncInsertPos->getParent())
1635 IVIncInsertPos = BB->getTerminator();
1636 }
1637
1638 return Changed;
Dan Gohmana10756e2010-01-21 02:09:26 +00001639}
1640
Dan Gohman572645c2010-02-12 10:34:29 +00001641bool
1642LSRInstance::reconcileNewOffset(LSRUse &LU, int64_t NewOffset,
1643 LSRUse::KindType Kind, const Type *AccessTy) {
1644 int64_t NewMinOffset = LU.MinOffset;
1645 int64_t NewMaxOffset = LU.MaxOffset;
1646 const Type *NewAccessTy = AccessTy;
Dan Gohman7979b722010-01-22 00:46:49 +00001647
Dan Gohman572645c2010-02-12 10:34:29 +00001648 // Check for a mismatched kind. It's tempting to collapse mismatched kinds to
1649 // something conservative, however this can pessimize in the case that one of
1650 // the uses will have all its uses outside the loop, for example.
1651 if (LU.Kind != Kind)
Dan Gohman7979b722010-01-22 00:46:49 +00001652 return false;
Dan Gohman572645c2010-02-12 10:34:29 +00001653 // Conservatively assume HasBaseReg is true for now.
1654 if (NewOffset < LU.MinOffset) {
1655 if (!isAlwaysFoldable(LU.MaxOffset - NewOffset, 0, /*HasBaseReg=*/true,
1656 Kind, AccessTy, TLI, SE))
Dan Gohman7979b722010-01-22 00:46:49 +00001657 return false;
Dan Gohman572645c2010-02-12 10:34:29 +00001658 NewMinOffset = NewOffset;
1659 } else if (NewOffset > LU.MaxOffset) {
1660 if (!isAlwaysFoldable(NewOffset - LU.MinOffset, 0, /*HasBaseReg=*/true,
1661 Kind, AccessTy, TLI, SE))
Dan Gohman7979b722010-01-22 00:46:49 +00001662 return false;
Dan Gohman572645c2010-02-12 10:34:29 +00001663 NewMaxOffset = NewOffset;
Dan Gohmana10756e2010-01-21 02:09:26 +00001664 }
Dan Gohman572645c2010-02-12 10:34:29 +00001665 // Check for a mismatched access type, and fall back conservatively as needed.
1666 if (Kind == LSRUse::Address && AccessTy != LU.AccessTy)
1667 NewAccessTy = Type::getVoidTy(AccessTy->getContext());
Dan Gohmana10756e2010-01-21 02:09:26 +00001668
Dan Gohman572645c2010-02-12 10:34:29 +00001669 // Update the use.
1670 LU.MinOffset = NewMinOffset;
1671 LU.MaxOffset = NewMaxOffset;
1672 LU.AccessTy = NewAccessTy;
1673 if (NewOffset != LU.Offsets.back())
1674 LU.Offsets.push_back(NewOffset);
Dan Gohman8b0ade32010-01-21 22:42:49 +00001675 return true;
1676}
1677
Dan Gohman572645c2010-02-12 10:34:29 +00001678/// getUse - Return an LSRUse index and an offset value for a fixup which
1679/// needs the given expression, with the given kind and optional access type.
1680/// Either reuse an exisitng use or create a new one, as needed.
1681std::pair<size_t, int64_t>
1682LSRInstance::getUse(const SCEV *&Expr,
1683 LSRUse::KindType Kind, const Type *AccessTy) {
1684 const SCEV *Copy = Expr;
1685 int64_t Offset = ExtractImmediate(Expr, SE);
Evan Cheng586f69a2009-11-12 07:35:05 +00001686
Dan Gohman572645c2010-02-12 10:34:29 +00001687 // Basic uses can't accept any offset, for example.
1688 if (!isAlwaysFoldable(Offset, 0, /*HasBaseReg=*/true,
1689 Kind, AccessTy, TLI, SE)) {
1690 Expr = Copy;
1691 Offset = 0;
1692 }
1693
1694 std::pair<UseMapTy::iterator, bool> P =
1695 UseMap.insert(std::make_pair(Expr, 0));
1696 if (!P.second) {
1697 // A use already existed with this base.
1698 size_t LUIdx = P.first->second;
1699 LSRUse &LU = Uses[LUIdx];
1700 if (reconcileNewOffset(LU, Offset, Kind, AccessTy))
1701 // Reuse this use.
1702 return std::make_pair(LUIdx, Offset);
1703 }
1704
1705 // Create a new use.
1706 size_t LUIdx = Uses.size();
1707 P.first->second = LUIdx;
1708 Uses.push_back(LSRUse(Kind, AccessTy));
1709 LSRUse &LU = Uses[LUIdx];
1710
1711 // We don't need to track redundant offsets, but we don't need to go out
1712 // of our way here to avoid them.
1713 if (LU.Offsets.empty() || Offset != LU.Offsets.back())
1714 LU.Offsets.push_back(Offset);
1715
1716 LU.MinOffset = Offset;
1717 LU.MaxOffset = Offset;
1718 return std::make_pair(LUIdx, Offset);
1719}
1720
1721void LSRInstance::CollectInterestingTypesAndFactors() {
1722 SmallSetVector<const SCEV *, 4> Strides;
1723
Dan Gohman1b7bf182010-02-19 00:05:23 +00001724 // Collect interesting types and strides.
Dan Gohman572645c2010-02-12 10:34:29 +00001725 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
1726 const SCEV *Stride = UI->getStride();
1727
1728 // Collect interesting types.
1729 Types.insert(SE.getEffectiveSCEVType(Stride->getType()));
1730
Dan Gohman1b7bf182010-02-19 00:05:23 +00001731 // Add the stride for this loop.
1732 Strides.insert(Stride);
1733
1734 // Add strides for other mentioned loops.
1735 for (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(UI->getOffset());
1736 AR; AR = dyn_cast<SCEVAddRecExpr>(AR->getStart()))
1737 Strides.insert(AR->getStepRecurrence(SE));
1738 }
1739
1740 // Compute interesting factors from the set of interesting strides.
1741 for (SmallSetVector<const SCEV *, 4>::const_iterator
1742 I = Strides.begin(), E = Strides.end(); I != E; ++I)
Dan Gohman572645c2010-02-12 10:34:29 +00001743 for (SmallSetVector<const SCEV *, 4>::const_iterator NewStrideIter =
Dan Gohman1b7bf182010-02-19 00:05:23 +00001744 next(I); NewStrideIter != E; ++NewStrideIter) {
1745 const SCEV *OldStride = *I;
Dan Gohman572645c2010-02-12 10:34:29 +00001746 const SCEV *NewStride = *NewStrideIter;
Dan Gohman572645c2010-02-12 10:34:29 +00001747
1748 if (SE.getTypeSizeInBits(OldStride->getType()) !=
1749 SE.getTypeSizeInBits(NewStride->getType())) {
1750 if (SE.getTypeSizeInBits(OldStride->getType()) >
1751 SE.getTypeSizeInBits(NewStride->getType()))
1752 NewStride = SE.getSignExtendExpr(NewStride, OldStride->getType());
1753 else
1754 OldStride = SE.getSignExtendExpr(OldStride, NewStride->getType());
1755 }
1756 if (const SCEVConstant *Factor =
1757 dyn_cast_or_null<SCEVConstant>(getSDiv(NewStride, OldStride,
1758 SE, true))) {
1759 if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
1760 Factors.insert(Factor->getValue()->getValue().getSExtValue());
1761 } else if (const SCEVConstant *Factor =
1762 dyn_cast_or_null<SCEVConstant>(getSDiv(OldStride, NewStride,
1763 SE, true))) {
1764 if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
1765 Factors.insert(Factor->getValue()->getValue().getSExtValue());
1766 }
1767 }
Dan Gohman572645c2010-02-12 10:34:29 +00001768
1769 // If all uses use the same type, don't bother looking for truncation-based
1770 // reuse.
1771 if (Types.size() == 1)
1772 Types.clear();
1773
1774 DEBUG(print_factors_and_types(dbgs()));
1775}
1776
1777void LSRInstance::CollectFixupsAndInitialFormulae() {
1778 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
1779 // Record the uses.
1780 LSRFixup &LF = getNewFixup();
1781 LF.UserInst = UI->getUser();
1782 LF.OperandValToReplace = UI->getOperandValToReplace();
1783 if (UI->isUseOfPostIncrementedValue())
1784 LF.PostIncLoop = L;
1785
1786 LSRUse::KindType Kind = LSRUse::Basic;
1787 const Type *AccessTy = 0;
1788 if (isAddressUse(LF.UserInst, LF.OperandValToReplace)) {
1789 Kind = LSRUse::Address;
1790 AccessTy = getAccessType(LF.UserInst);
1791 }
1792
1793 const SCEV *S = IU.getCanonicalExpr(*UI);
1794
1795 // Equality (== and !=) ICmps are special. We can rewrite (i == N) as
1796 // (N - i == 0), and this allows (N - i) to be the expression that we work
1797 // with rather than just N or i, so we can consider the register
1798 // requirements for both N and i at the same time. Limiting this code to
1799 // equality icmps is not a problem because all interesting loops use
1800 // equality icmps, thanks to IndVarSimplify.
1801 if (ICmpInst *CI = dyn_cast<ICmpInst>(LF.UserInst))
1802 if (CI->isEquality()) {
1803 // Swap the operands if needed to put the OperandValToReplace on the
1804 // left, for consistency.
1805 Value *NV = CI->getOperand(1);
1806 if (NV == LF.OperandValToReplace) {
1807 CI->setOperand(1, CI->getOperand(0));
1808 CI->setOperand(0, NV);
1809 }
1810
1811 // x == y --> x - y == 0
1812 const SCEV *N = SE.getSCEV(NV);
1813 if (N->isLoopInvariant(L)) {
1814 Kind = LSRUse::ICmpZero;
1815 S = SE.getMinusSCEV(N, S);
1816 }
1817
1818 // -1 and the negations of all interesting strides (except the negation
1819 // of -1) are now also interesting.
1820 for (size_t i = 0, e = Factors.size(); i != e; ++i)
1821 if (Factors[i] != -1)
1822 Factors.insert(-(uint64_t)Factors[i]);
1823 Factors.insert(-1);
1824 }
1825
1826 // Set up the initial formula for this use.
1827 std::pair<size_t, int64_t> P = getUse(S, Kind, AccessTy);
1828 LF.LUIdx = P.first;
1829 LF.Offset = P.second;
1830 LSRUse &LU = Uses[LF.LUIdx];
1831 LU.AllFixupsOutsideLoop &= !L->contains(LF.UserInst);
1832
1833 // If this is the first use of this LSRUse, give it a formula.
1834 if (LU.Formulae.empty()) {
1835 InsertInitialFormula(S, L, LU, LF.LUIdx);
1836 CountRegisters(LU.Formulae.back(), LF.LUIdx);
1837 }
1838 }
1839
1840 DEBUG(print_fixups(dbgs()));
1841}
1842
1843void
1844LSRInstance::InsertInitialFormula(const SCEV *S, Loop *L,
1845 LSRUse &LU, size_t LUIdx) {
1846 Formula F;
1847 F.InitialMatch(S, L, SE, DT);
1848 bool Inserted = InsertFormula(LU, LUIdx, F);
1849 assert(Inserted && "Initial formula already exists!"); (void)Inserted;
1850}
1851
1852void
1853LSRInstance::InsertSupplementalFormula(const SCEV *S,
1854 LSRUse &LU, size_t LUIdx) {
1855 Formula F;
1856 F.BaseRegs.push_back(S);
1857 F.AM.HasBaseReg = true;
1858 bool Inserted = InsertFormula(LU, LUIdx, F);
1859 assert(Inserted && "Supplemental formula already exists!"); (void)Inserted;
1860}
1861
1862/// CountRegisters - Note which registers are used by the given formula,
1863/// updating RegUses.
1864void LSRInstance::CountRegisters(const Formula &F, size_t LUIdx) {
1865 if (F.ScaledReg)
1866 RegUses.CountRegister(F.ScaledReg, LUIdx);
1867 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
1868 E = F.BaseRegs.end(); I != E; ++I)
1869 RegUses.CountRegister(*I, LUIdx);
1870}
1871
1872/// InsertFormula - If the given formula has not yet been inserted, add it to
1873/// the list, and return true. Return false otherwise.
1874bool LSRInstance::InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F) {
1875 if (!LU.InsertFormula(LUIdx, F))
1876 return false;
1877
1878 CountRegisters(F, LUIdx);
1879 return true;
1880}
1881
1882/// CollectLoopInvariantFixupsAndFormulae - Check for other uses of
1883/// loop-invariant values which we're tracking. These other uses will pin these
1884/// values in registers, making them less profitable for elimination.
1885/// TODO: This currently misses non-constant addrec step registers.
1886/// TODO: Should this give more weight to users inside the loop?
1887void
1888LSRInstance::CollectLoopInvariantFixupsAndFormulae() {
1889 SmallVector<const SCEV *, 8> Worklist(RegUses.begin(), RegUses.end());
1890 SmallPtrSet<const SCEV *, 8> Inserted;
1891
1892 while (!Worklist.empty()) {
1893 const SCEV *S = Worklist.pop_back_val();
1894
1895 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S))
1896 Worklist.insert(Worklist.end(), N->op_begin(), N->op_end());
1897 else if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
1898 Worklist.push_back(C->getOperand());
1899 else if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
1900 Worklist.push_back(D->getLHS());
1901 Worklist.push_back(D->getRHS());
1902 } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
1903 if (!Inserted.insert(U)) continue;
1904 const Value *V = U->getValue();
1905 if (const Instruction *Inst = dyn_cast<Instruction>(V))
1906 if (L->contains(Inst)) continue;
1907 for (Value::use_const_iterator UI = V->use_begin(), UE = V->use_end();
1908 UI != UE; ++UI) {
1909 const Instruction *UserInst = dyn_cast<Instruction>(*UI);
1910 // Ignore non-instructions.
1911 if (!UserInst)
Dan Gohman7979b722010-01-22 00:46:49 +00001912 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00001913 // Ignore instructions in other functions (as can happen with
1914 // Constants).
1915 if (UserInst->getParent()->getParent() != L->getHeader()->getParent())
Dan Gohman7979b722010-01-22 00:46:49 +00001916 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00001917 // Ignore instructions not dominated by the loop.
1918 const BasicBlock *UseBB = !isa<PHINode>(UserInst) ?
1919 UserInst->getParent() :
1920 cast<PHINode>(UserInst)->getIncomingBlock(
1921 PHINode::getIncomingValueNumForOperand(UI.getOperandNo()));
1922 if (!DT.dominates(L->getHeader(), UseBB))
1923 continue;
1924 // Ignore uses which are part of other SCEV expressions, to avoid
1925 // analyzing them multiple times.
1926 if (SE.isSCEVable(UserInst->getType()) &&
1927 !isa<SCEVUnknown>(SE.getSCEV(const_cast<Instruction *>(UserInst))))
1928 continue;
1929 // Ignore icmp instructions which are already being analyzed.
1930 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) {
1931 unsigned OtherIdx = !UI.getOperandNo();
1932 Value *OtherOp = const_cast<Value *>(ICI->getOperand(OtherIdx));
1933 if (SE.getSCEV(OtherOp)->hasComputableLoopEvolution(L))
1934 continue;
1935 }
1936
1937 LSRFixup &LF = getNewFixup();
1938 LF.UserInst = const_cast<Instruction *>(UserInst);
1939 LF.OperandValToReplace = UI.getUse();
1940 std::pair<size_t, int64_t> P = getUse(S, LSRUse::Basic, 0);
1941 LF.LUIdx = P.first;
1942 LF.Offset = P.second;
1943 LSRUse &LU = Uses[LF.LUIdx];
1944 LU.AllFixupsOutsideLoop &= L->contains(LF.UserInst);
1945 InsertSupplementalFormula(U, LU, LF.LUIdx);
1946 CountRegisters(LU.Formulae.back(), Uses.size() - 1);
1947 break;
1948 }
1949 }
1950 }
1951}
1952
1953/// CollectSubexprs - Split S into subexpressions which can be pulled out into
1954/// separate registers. If C is non-null, multiply each subexpression by C.
1955static void CollectSubexprs(const SCEV *S, const SCEVConstant *C,
1956 SmallVectorImpl<const SCEV *> &Ops,
1957 ScalarEvolution &SE) {
1958 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
1959 // Break out add operands.
1960 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1961 I != E; ++I)
1962 CollectSubexprs(*I, C, Ops, SE);
1963 return;
1964 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
1965 // Split a non-zero base out of an addrec.
1966 if (!AR->getStart()->isZero()) {
Dan Gohman572645c2010-02-12 10:34:29 +00001967 CollectSubexprs(SE.getAddRecExpr(SE.getIntegerSCEV(0, AR->getType()),
1968 AR->getStepRecurrence(SE),
1969 AR->getLoop()), C, Ops, SE);
Dan Gohman68d6da12010-02-12 19:35:25 +00001970 CollectSubexprs(AR->getStart(), C, Ops, SE);
Dan Gohman572645c2010-02-12 10:34:29 +00001971 return;
1972 }
1973 } else if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
1974 // Break (C * (a + b + c)) into C*a + C*b + C*c.
1975 if (Mul->getNumOperands() == 2)
1976 if (const SCEVConstant *Op0 =
1977 dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
1978 CollectSubexprs(Mul->getOperand(1),
1979 C ? cast<SCEVConstant>(SE.getMulExpr(C, Op0)) : Op0,
1980 Ops, SE);
1981 return;
1982 }
1983 }
1984
1985 // Otherwise use the value itself.
1986 Ops.push_back(C ? SE.getMulExpr(C, S) : S);
1987}
1988
1989/// GenerateReassociations - Split out subexpressions from adds and the bases of
1990/// addrecs.
1991void LSRInstance::GenerateReassociations(LSRUse &LU, unsigned LUIdx,
1992 Formula Base,
1993 unsigned Depth) {
1994 // Arbitrarily cap recursion to protect compile time.
1995 if (Depth >= 3) return;
1996
1997 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
1998 const SCEV *BaseReg = Base.BaseRegs[i];
1999
2000 SmallVector<const SCEV *, 8> AddOps;
2001 CollectSubexprs(BaseReg, 0, AddOps, SE);
2002 if (AddOps.size() == 1) continue;
2003
2004 for (SmallVectorImpl<const SCEV *>::const_iterator J = AddOps.begin(),
2005 JE = AddOps.end(); J != JE; ++J) {
2006 // Don't pull a constant into a register if the constant could be folded
2007 // into an immediate field.
2008 if (isAlwaysFoldable(*J, LU.MinOffset, LU.MaxOffset,
2009 Base.getNumRegs() > 1,
2010 LU.Kind, LU.AccessTy, TLI, SE))
2011 continue;
2012
2013 // Collect all operands except *J.
2014 SmallVector<const SCEV *, 8> InnerAddOps;
2015 for (SmallVectorImpl<const SCEV *>::const_iterator K = AddOps.begin(),
2016 KE = AddOps.end(); K != KE; ++K)
2017 if (K != J)
2018 InnerAddOps.push_back(*K);
2019
2020 // Don't leave just a constant behind in a register if the constant could
2021 // be folded into an immediate field.
2022 if (InnerAddOps.size() == 1 &&
2023 isAlwaysFoldable(InnerAddOps[0], LU.MinOffset, LU.MaxOffset,
2024 Base.getNumRegs() > 1,
2025 LU.Kind, LU.AccessTy, TLI, SE))
2026 continue;
2027
2028 Formula F = Base;
2029 F.BaseRegs[i] = SE.getAddExpr(InnerAddOps);
2030 F.BaseRegs.push_back(*J);
2031 if (InsertFormula(LU, LUIdx, F))
2032 // If that formula hadn't been seen before, recurse to find more like
2033 // it.
2034 GenerateReassociations(LU, LUIdx, LU.Formulae.back(), Depth+1);
2035 }
2036 }
2037}
2038
2039/// GenerateCombinations - Generate a formula consisting of all of the
2040/// loop-dominating registers added into a single register.
2041void LSRInstance::GenerateCombinations(LSRUse &LU, unsigned LUIdx,
Dan Gohman441a3892010-02-14 18:51:39 +00002042 Formula Base) {
Dan Gohman572645c2010-02-12 10:34:29 +00002043 // This method is only intersting on a plurality of registers.
2044 if (Base.BaseRegs.size() <= 1) return;
2045
2046 Formula F = Base;
2047 F.BaseRegs.clear();
2048 SmallVector<const SCEV *, 4> Ops;
2049 for (SmallVectorImpl<const SCEV *>::const_iterator
2050 I = Base.BaseRegs.begin(), E = Base.BaseRegs.end(); I != E; ++I) {
2051 const SCEV *BaseReg = *I;
2052 if (BaseReg->properlyDominates(L->getHeader(), &DT) &&
2053 !BaseReg->hasComputableLoopEvolution(L))
2054 Ops.push_back(BaseReg);
2055 else
2056 F.BaseRegs.push_back(BaseReg);
2057 }
2058 if (Ops.size() > 1) {
Dan Gohmance947362010-02-14 18:50:49 +00002059 const SCEV *Sum = SE.getAddExpr(Ops);
2060 // TODO: If Sum is zero, it probably means ScalarEvolution missed an
2061 // opportunity to fold something. For now, just ignore such cases
2062 // rather than procede with zero in a register.
2063 if (!Sum->isZero()) {
2064 F.BaseRegs.push_back(Sum);
2065 (void)InsertFormula(LU, LUIdx, F);
2066 }
Dan Gohman572645c2010-02-12 10:34:29 +00002067 }
2068}
2069
2070/// GenerateSymbolicOffsets - Generate reuse formulae using symbolic offsets.
2071void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx,
2072 Formula Base) {
2073 // We can't add a symbolic offset if the address already contains one.
2074 if (Base.AM.BaseGV) return;
2075
2076 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2077 const SCEV *G = Base.BaseRegs[i];
2078 GlobalValue *GV = ExtractSymbol(G, SE);
2079 if (G->isZero() || !GV)
2080 continue;
2081 Formula F = Base;
2082 F.AM.BaseGV = GV;
2083 if (!isLegalUse(F.AM, LU.MinOffset, LU.MaxOffset,
2084 LU.Kind, LU.AccessTy, TLI))
2085 continue;
2086 F.BaseRegs[i] = G;
2087 (void)InsertFormula(LU, LUIdx, F);
2088 }
2089}
2090
2091/// GenerateConstantOffsets - Generate reuse formulae using symbolic offsets.
2092void LSRInstance::GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx,
2093 Formula Base) {
2094 // TODO: For now, just add the min and max offset, because it usually isn't
2095 // worthwhile looking at everything inbetween.
2096 SmallVector<int64_t, 4> Worklist;
2097 Worklist.push_back(LU.MinOffset);
2098 if (LU.MaxOffset != LU.MinOffset)
2099 Worklist.push_back(LU.MaxOffset);
2100
2101 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2102 const SCEV *G = Base.BaseRegs[i];
2103
2104 for (SmallVectorImpl<int64_t>::const_iterator I = Worklist.begin(),
2105 E = Worklist.end(); I != E; ++I) {
2106 Formula F = Base;
2107 F.AM.BaseOffs = (uint64_t)Base.AM.BaseOffs - *I;
2108 if (isLegalUse(F.AM, LU.MinOffset - *I, LU.MaxOffset - *I,
2109 LU.Kind, LU.AccessTy, TLI)) {
2110 F.BaseRegs[i] = SE.getAddExpr(G, SE.getIntegerSCEV(*I, G->getType()));
2111
2112 (void)InsertFormula(LU, LUIdx, F);
2113 }
2114 }
2115
2116 int64_t Imm = ExtractImmediate(G, SE);
2117 if (G->isZero() || Imm == 0)
2118 continue;
2119 Formula F = Base;
2120 F.AM.BaseOffs = (uint64_t)F.AM.BaseOffs + Imm;
2121 if (!isLegalUse(F.AM, LU.MinOffset, LU.MaxOffset,
2122 LU.Kind, LU.AccessTy, TLI))
2123 continue;
2124 F.BaseRegs[i] = G;
2125 (void)InsertFormula(LU, LUIdx, F);
2126 }
2127}
2128
2129/// GenerateICmpZeroScales - For ICmpZero, check to see if we can scale up
2130/// the comparison. For example, x == y -> x*c == y*c.
2131void LSRInstance::GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx,
2132 Formula Base) {
2133 if (LU.Kind != LSRUse::ICmpZero) return;
2134
2135 // Determine the integer type for the base formula.
2136 const Type *IntTy = Base.getType();
2137 if (!IntTy) return;
2138 if (SE.getTypeSizeInBits(IntTy) > 64) return;
2139
2140 // Don't do this if there is more than one offset.
2141 if (LU.MinOffset != LU.MaxOffset) return;
2142
2143 assert(!Base.AM.BaseGV && "ICmpZero use is not legal!");
2144
2145 // Check each interesting stride.
2146 for (SmallSetVector<int64_t, 8>::const_iterator
2147 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
2148 int64_t Factor = *I;
2149 Formula F = Base;
2150
2151 // Check that the multiplication doesn't overflow.
Dan Gohman968cb932010-02-17 00:41:53 +00002152 if (F.AM.BaseOffs == INT64_MIN && Factor == -1)
2153 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002154 F.AM.BaseOffs = (uint64_t)Base.AM.BaseOffs * Factor;
Dan Gohman378c0b32010-02-17 00:42:19 +00002155 if (F.AM.BaseOffs / Factor != Base.AM.BaseOffs)
Dan Gohman572645c2010-02-12 10:34:29 +00002156 continue;
2157
2158 // Check that multiplying with the use offset doesn't overflow.
2159 int64_t Offset = LU.MinOffset;
Dan Gohman968cb932010-02-17 00:41:53 +00002160 if (Offset == INT64_MIN && Factor == -1)
2161 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002162 Offset = (uint64_t)Offset * Factor;
Dan Gohman378c0b32010-02-17 00:42:19 +00002163 if (Offset / Factor != LU.MinOffset)
Dan Gohman572645c2010-02-12 10:34:29 +00002164 continue;
2165
2166 // Check that this scale is legal.
2167 if (!isLegalUse(F.AM, Offset, Offset, LU.Kind, LU.AccessTy, TLI))
2168 continue;
2169
2170 // Compensate for the use having MinOffset built into it.
2171 F.AM.BaseOffs = (uint64_t)F.AM.BaseOffs + Offset - LU.MinOffset;
2172
2173 const SCEV *FactorS = SE.getIntegerSCEV(Factor, IntTy);
2174
2175 // Check that multiplying with each base register doesn't overflow.
2176 for (size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) {
2177 F.BaseRegs[i] = SE.getMulExpr(F.BaseRegs[i], FactorS);
2178 if (getSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i])
2179 goto next;
2180 }
2181
2182 // Check that multiplying with the scaled register doesn't overflow.
2183 if (F.ScaledReg) {
2184 F.ScaledReg = SE.getMulExpr(F.ScaledReg, FactorS);
2185 if (getSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg)
2186 continue;
2187 }
2188
2189 // If we make it here and it's legal, add it.
2190 (void)InsertFormula(LU, LUIdx, F);
2191 next:;
2192 }
2193}
2194
2195/// GenerateScales - Generate stride factor reuse formulae by making use of
2196/// scaled-offset address modes, for example.
2197void LSRInstance::GenerateScales(LSRUse &LU, unsigned LUIdx,
2198 Formula Base) {
2199 // Determine the integer type for the base formula.
2200 const Type *IntTy = Base.getType();
2201 if (!IntTy) return;
2202
2203 // If this Formula already has a scaled register, we can't add another one.
2204 if (Base.AM.Scale != 0) return;
2205
2206 // Check each interesting stride.
2207 for (SmallSetVector<int64_t, 8>::const_iterator
2208 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
2209 int64_t Factor = *I;
2210
2211 Base.AM.Scale = Factor;
2212 Base.AM.HasBaseReg = Base.BaseRegs.size() > 1;
2213 // Check whether this scale is going to be legal.
2214 if (!isLegalUse(Base.AM, LU.MinOffset, LU.MaxOffset,
2215 LU.Kind, LU.AccessTy, TLI)) {
2216 // As a special-case, handle special out-of-loop Basic users specially.
2217 // TODO: Reconsider this special case.
2218 if (LU.Kind == LSRUse::Basic &&
2219 isLegalUse(Base.AM, LU.MinOffset, LU.MaxOffset,
2220 LSRUse::Special, LU.AccessTy, TLI) &&
2221 LU.AllFixupsOutsideLoop)
2222 LU.Kind = LSRUse::Special;
2223 else
2224 continue;
2225 }
2226 // For an ICmpZero, negating a solitary base register won't lead to
2227 // new solutions.
2228 if (LU.Kind == LSRUse::ICmpZero &&
2229 !Base.AM.HasBaseReg && Base.AM.BaseOffs == 0 && !Base.AM.BaseGV)
2230 continue;
2231 // For each addrec base reg, apply the scale, if possible.
2232 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
2233 if (const SCEVAddRecExpr *AR =
2234 dyn_cast<SCEVAddRecExpr>(Base.BaseRegs[i])) {
2235 const SCEV *FactorS = SE.getIntegerSCEV(Factor, IntTy);
2236 if (FactorS->isZero())
2237 continue;
2238 // Divide out the factor, ignoring high bits, since we'll be
2239 // scaling the value back up in the end.
2240 if (const SCEV *Quotient = getSDiv(AR, FactorS, SE, true)) {
2241 // TODO: This could be optimized to avoid all the copying.
2242 Formula F = Base;
2243 F.ScaledReg = Quotient;
2244 std::swap(F.BaseRegs[i], F.BaseRegs.back());
2245 F.BaseRegs.pop_back();
2246 (void)InsertFormula(LU, LUIdx, F);
2247 }
2248 }
2249 }
2250}
2251
2252/// GenerateTruncates - Generate reuse formulae from different IV types.
2253void LSRInstance::GenerateTruncates(LSRUse &LU, unsigned LUIdx,
2254 Formula Base) {
2255 // This requires TargetLowering to tell us which truncates are free.
2256 if (!TLI) return;
2257
2258 // Don't bother truncating symbolic values.
2259 if (Base.AM.BaseGV) return;
2260
2261 // Determine the integer type for the base formula.
2262 const Type *DstTy = Base.getType();
2263 if (!DstTy) return;
2264 DstTy = SE.getEffectiveSCEVType(DstTy);
2265
2266 for (SmallSetVector<const Type *, 4>::const_iterator
2267 I = Types.begin(), E = Types.end(); I != E; ++I) {
2268 const Type *SrcTy = *I;
2269 if (SrcTy != DstTy && TLI->isTruncateFree(SrcTy, DstTy)) {
2270 Formula F = Base;
2271
2272 if (F.ScaledReg) F.ScaledReg = SE.getAnyExtendExpr(F.ScaledReg, *I);
2273 for (SmallVectorImpl<const SCEV *>::iterator J = F.BaseRegs.begin(),
2274 JE = F.BaseRegs.end(); J != JE; ++J)
2275 *J = SE.getAnyExtendExpr(*J, SrcTy);
2276
2277 // TODO: This assumes we've done basic processing on all uses and
2278 // have an idea what the register usage is.
2279 if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses))
2280 continue;
2281
2282 (void)InsertFormula(LU, LUIdx, F);
2283 }
2284 }
2285}
2286
2287namespace {
2288
Dan Gohman6020d852010-02-14 18:51:20 +00002289/// WorkItem - Helper class for GenerateCrossUseConstantOffsets. It's used to
Dan Gohman572645c2010-02-12 10:34:29 +00002290/// defer modifications so that the search phase doesn't have to worry about
2291/// the data structures moving underneath it.
2292struct WorkItem {
2293 size_t LUIdx;
2294 int64_t Imm;
2295 const SCEV *OrigReg;
2296
2297 WorkItem(size_t LI, int64_t I, const SCEV *R)
2298 : LUIdx(LI), Imm(I), OrigReg(R) {}
2299
2300 void print(raw_ostream &OS) const;
2301 void dump() const;
2302};
2303
2304}
2305
2306void WorkItem::print(raw_ostream &OS) const {
2307 OS << "in formulae referencing " << *OrigReg << " in use " << LUIdx
2308 << " , add offset " << Imm;
2309}
2310
2311void WorkItem::dump() const {
2312 print(errs()); errs() << '\n';
2313}
2314
2315/// GenerateCrossUseConstantOffsets - Look for registers which are a constant
2316/// distance apart and try to form reuse opportunities between them.
2317void LSRInstance::GenerateCrossUseConstantOffsets() {
2318 // Group the registers by their value without any added constant offset.
2319 typedef std::map<int64_t, const SCEV *> ImmMapTy;
2320 typedef DenseMap<const SCEV *, ImmMapTy> RegMapTy;
2321 RegMapTy Map;
2322 DenseMap<const SCEV *, SmallBitVector> UsedByIndicesMap;
2323 SmallVector<const SCEV *, 8> Sequence;
2324 for (RegUseTracker::const_iterator I = RegUses.begin(), E = RegUses.end();
2325 I != E; ++I) {
2326 const SCEV *Reg = *I;
2327 int64_t Imm = ExtractImmediate(Reg, SE);
2328 std::pair<RegMapTy::iterator, bool> Pair =
2329 Map.insert(std::make_pair(Reg, ImmMapTy()));
2330 if (Pair.second)
2331 Sequence.push_back(Reg);
2332 Pair.first->second.insert(std::make_pair(Imm, *I));
2333 UsedByIndicesMap[Reg] |= RegUses.getUsedByIndices(*I);
2334 }
2335
2336 // Now examine each set of registers with the same base value. Build up
2337 // a list of work to do and do the work in a separate step so that we're
2338 // not adding formulae and register counts while we're searching.
2339 SmallVector<WorkItem, 32> WorkItems;
2340 SmallSet<std::pair<size_t, int64_t>, 32> UniqueItems;
2341 for (SmallVectorImpl<const SCEV *>::const_iterator I = Sequence.begin(),
2342 E = Sequence.end(); I != E; ++I) {
2343 const SCEV *Reg = *I;
2344 const ImmMapTy &Imms = Map.find(Reg)->second;
2345
Dan Gohmancd045c02010-02-12 19:20:37 +00002346 // It's not worthwhile looking for reuse if there's only one offset.
2347 if (Imms.size() == 1)
2348 continue;
2349
Dan Gohman572645c2010-02-12 10:34:29 +00002350 DEBUG(dbgs() << "Generating cross-use offsets for " << *Reg << ':';
2351 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
2352 J != JE; ++J)
2353 dbgs() << ' ' << J->first;
2354 dbgs() << '\n');
2355
2356 // Examine each offset.
2357 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
2358 J != JE; ++J) {
2359 const SCEV *OrigReg = J->second;
2360
2361 int64_t JImm = J->first;
2362 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg);
2363
2364 if (!isa<SCEVConstant>(OrigReg) &&
2365 UsedByIndicesMap[Reg].count() == 1) {
2366 DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg << '\n');
2367 continue;
2368 }
2369
2370 // Conservatively examine offsets between this orig reg a few selected
2371 // other orig regs.
2372 ImmMapTy::const_iterator OtherImms[] = {
2373 Imms.begin(), prior(Imms.end()),
2374 Imms.upper_bound((Imms.begin()->first + prior(Imms.end())->first) / 2)
2375 };
2376 for (size_t i = 0, e = array_lengthof(OtherImms); i != e; ++i) {
2377 ImmMapTy::const_iterator M = OtherImms[i];
Dan Gohmancd045c02010-02-12 19:20:37 +00002378 if (M == J || M == JE) continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002379
2380 // Compute the difference between the two.
2381 int64_t Imm = (uint64_t)JImm - M->first;
2382 for (int LUIdx = UsedByIndices.find_first(); LUIdx != -1;
2383 LUIdx = UsedByIndices.find_next(LUIdx))
2384 // Make a memo of this use, offset, and register tuple.
2385 if (UniqueItems.insert(std::make_pair(LUIdx, Imm)))
2386 WorkItems.push_back(WorkItem(LUIdx, Imm, OrigReg));
Evan Cheng586f69a2009-11-12 07:35:05 +00002387 }
2388 }
2389 }
2390
Dan Gohman572645c2010-02-12 10:34:29 +00002391 Map.clear();
2392 Sequence.clear();
2393 UsedByIndicesMap.clear();
2394 UniqueItems.clear();
2395
2396 // Now iterate through the worklist and add new formulae.
2397 for (SmallVectorImpl<WorkItem>::const_iterator I = WorkItems.begin(),
2398 E = WorkItems.end(); I != E; ++I) {
2399 const WorkItem &WI = *I;
2400 size_t LUIdx = WI.LUIdx;
2401 LSRUse &LU = Uses[LUIdx];
2402 int64_t Imm = WI.Imm;
2403 const SCEV *OrigReg = WI.OrigReg;
2404
2405 const Type *IntTy = SE.getEffectiveSCEVType(OrigReg->getType());
2406 const SCEV *NegImmS = SE.getSCEV(ConstantInt::get(IntTy, -(uint64_t)Imm));
2407 unsigned BitWidth = SE.getTypeSizeInBits(IntTy);
2408
2409 // TODO: Use a more targetted data structure.
2410 for (size_t L = 0, LE = LU.Formulae.size(); L != LE; ++L) {
2411 Formula F = LU.Formulae[L];
2412 // Use the immediate in the scaled register.
2413 if (F.ScaledReg == OrigReg) {
2414 int64_t Offs = (uint64_t)F.AM.BaseOffs +
2415 Imm * (uint64_t)F.AM.Scale;
2416 // Don't create 50 + reg(-50).
2417 if (F.referencesReg(SE.getSCEV(
2418 ConstantInt::get(IntTy, -(uint64_t)Offs))))
2419 continue;
2420 Formula NewF = F;
2421 NewF.AM.BaseOffs = Offs;
2422 if (!isLegalUse(NewF.AM, LU.MinOffset, LU.MaxOffset,
2423 LU.Kind, LU.AccessTy, TLI))
2424 continue;
2425 NewF.ScaledReg = SE.getAddExpr(NegImmS, NewF.ScaledReg);
2426
2427 // If the new scale is a constant in a register, and adding the constant
2428 // value to the immediate would produce a value closer to zero than the
2429 // immediate itself, then the formula isn't worthwhile.
2430 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewF.ScaledReg))
2431 if (C->getValue()->getValue().isNegative() !=
2432 (NewF.AM.BaseOffs < 0) &&
2433 (C->getValue()->getValue().abs() * APInt(BitWidth, F.AM.Scale))
2434 .ule(APInt(BitWidth, NewF.AM.BaseOffs).abs()))
2435 continue;
2436
2437 // OK, looks good.
2438 (void)InsertFormula(LU, LUIdx, NewF);
2439 } else {
2440 // Use the immediate in a base register.
2441 for (size_t N = 0, NE = F.BaseRegs.size(); N != NE; ++N) {
2442 const SCEV *BaseReg = F.BaseRegs[N];
2443 if (BaseReg != OrigReg)
2444 continue;
2445 Formula NewF = F;
2446 NewF.AM.BaseOffs = (uint64_t)NewF.AM.BaseOffs + Imm;
2447 if (!isLegalUse(NewF.AM, LU.MinOffset, LU.MaxOffset,
2448 LU.Kind, LU.AccessTy, TLI))
2449 continue;
2450 NewF.BaseRegs[N] = SE.getAddExpr(NegImmS, BaseReg);
2451
2452 // If the new formula has a constant in a register, and adding the
2453 // constant value to the immediate would produce a value closer to
2454 // zero than the immediate itself, then the formula isn't worthwhile.
2455 for (SmallVectorImpl<const SCEV *>::const_iterator
2456 J = NewF.BaseRegs.begin(), JE = NewF.BaseRegs.end();
2457 J != JE; ++J)
2458 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*J))
2459 if (C->getValue()->getValue().isNegative() !=
2460 (NewF.AM.BaseOffs < 0) &&
2461 C->getValue()->getValue().abs()
2462 .ule(APInt(BitWidth, NewF.AM.BaseOffs).abs()))
2463 goto skip_formula;
2464
2465 // Ok, looks good.
2466 (void)InsertFormula(LU, LUIdx, NewF);
2467 break;
2468 skip_formula:;
2469 }
2470 }
2471 }
2472 }
Dale Johannesenc1acc3f2009-05-11 17:15:42 +00002473}
2474
Dan Gohman572645c2010-02-12 10:34:29 +00002475/// GenerateAllReuseFormulae - Generate formulae for each use.
2476void
2477LSRInstance::GenerateAllReuseFormulae() {
Dan Gohmanc2385a02010-02-16 01:42:53 +00002478 // This is split into multiple loops so that hasRegsUsedByUsesOtherThan
Dan Gohman572645c2010-02-12 10:34:29 +00002479 // queries are more precise.
2480 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2481 LSRUse &LU = Uses[LUIdx];
2482 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2483 GenerateReassociations(LU, LUIdx, LU.Formulae[i]);
2484 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2485 GenerateCombinations(LU, LUIdx, LU.Formulae[i]);
2486 }
2487 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2488 LSRUse &LU = Uses[LUIdx];
2489 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2490 GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]);
2491 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2492 GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]);
2493 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2494 GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]);
2495 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2496 GenerateScales(LU, LUIdx, LU.Formulae[i]);
Dan Gohmanc2385a02010-02-16 01:42:53 +00002497 }
2498 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2499 LSRUse &LU = Uses[LUIdx];
Dan Gohman572645c2010-02-12 10:34:29 +00002500 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2501 GenerateTruncates(LU, LUIdx, LU.Formulae[i]);
2502 }
2503
2504 GenerateCrossUseConstantOffsets();
2505}
2506
2507/// If their are multiple formulae with the same set of registers used
2508/// by other uses, pick the best one and delete the others.
2509void LSRInstance::FilterOutUndesirableDedicatedRegisters() {
2510#ifndef NDEBUG
2511 bool Changed = false;
2512#endif
2513
2514 // Collect the best formula for each unique set of shared registers. This
2515 // is reset for each use.
2516 typedef DenseMap<SmallVector<const SCEV *, 2>, size_t, UniquifierDenseMapInfo>
2517 BestFormulaeTy;
2518 BestFormulaeTy BestFormulae;
2519
2520 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2521 LSRUse &LU = Uses[LUIdx];
2522 FormulaSorter Sorter(L, LU, SE, DT);
2523
2524 // Clear out the set of used regs; it will be recomputed.
2525 LU.Regs.clear();
2526
2527 for (size_t FIdx = 0, NumForms = LU.Formulae.size();
2528 FIdx != NumForms; ++FIdx) {
2529 Formula &F = LU.Formulae[FIdx];
2530
2531 SmallVector<const SCEV *, 2> Key;
2532 for (SmallVectorImpl<const SCEV *>::const_iterator J = F.BaseRegs.begin(),
2533 JE = F.BaseRegs.end(); J != JE; ++J) {
2534 const SCEV *Reg = *J;
2535 if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx))
2536 Key.push_back(Reg);
2537 }
2538 if (F.ScaledReg &&
2539 RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx))
2540 Key.push_back(F.ScaledReg);
2541 // Unstable sort by host order ok, because this is only used for
2542 // uniquifying.
2543 std::sort(Key.begin(), Key.end());
2544
2545 std::pair<BestFormulaeTy::const_iterator, bool> P =
2546 BestFormulae.insert(std::make_pair(Key, FIdx));
2547 if (!P.second) {
2548 Formula &Best = LU.Formulae[P.first->second];
2549 if (Sorter.operator()(F, Best))
2550 std::swap(F, Best);
2551 DEBUG(dbgs() << "Filtering out "; F.print(dbgs());
2552 dbgs() << "\n"
2553 " in favor of "; Best.print(dbgs());
2554 dbgs() << '\n');
2555#ifndef NDEBUG
2556 Changed = true;
2557#endif
2558 std::swap(F, LU.Formulae.back());
2559 LU.Formulae.pop_back();
2560 --FIdx;
2561 --NumForms;
2562 continue;
2563 }
2564 if (F.ScaledReg) LU.Regs.insert(F.ScaledReg);
2565 LU.Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
2566 }
2567 BestFormulae.clear();
2568 }
2569
2570 DEBUG(if (Changed) {
Dan Gohman9214b822010-02-13 02:06:02 +00002571 dbgs() << "\n"
2572 "After filtering out undesirable candidates:\n";
Dan Gohman572645c2010-02-12 10:34:29 +00002573 print_uses(dbgs());
2574 });
2575}
2576
2577/// NarrowSearchSpaceUsingHeuristics - If there are an extrordinary number of
2578/// formulae to choose from, use some rough heuristics to prune down the number
2579/// of formulae. This keeps the main solver from taking an extrordinary amount
2580/// of time in some worst-case scenarios.
2581void LSRInstance::NarrowSearchSpaceUsingHeuristics() {
2582 // This is a rough guess that seems to work fairly well.
2583 const size_t Limit = UINT16_MAX;
2584
2585 SmallPtrSet<const SCEV *, 4> Taken;
2586 for (;;) {
2587 // Estimate the worst-case number of solutions we might consider. We almost
2588 // never consider this many solutions because we prune the search space,
2589 // but the pruning isn't always sufficient.
2590 uint32_t Power = 1;
2591 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
2592 E = Uses.end(); I != E; ++I) {
2593 size_t FSize = I->Formulae.size();
2594 if (FSize >= Limit) {
2595 Power = Limit;
2596 break;
2597 }
2598 Power *= FSize;
2599 if (Power >= Limit)
2600 break;
2601 }
2602 if (Power < Limit)
2603 break;
2604
2605 // Ok, we have too many of formulae on our hands to conveniently handle.
2606 // Use a rough heuristic to thin out the list.
2607
2608 // Pick the register which is used by the most LSRUses, which is likely
2609 // to be a good reuse register candidate.
2610 const SCEV *Best = 0;
2611 unsigned BestNum = 0;
2612 for (RegUseTracker::const_iterator I = RegUses.begin(), E = RegUses.end();
2613 I != E; ++I) {
2614 const SCEV *Reg = *I;
2615 if (Taken.count(Reg))
2616 continue;
2617 if (!Best)
2618 Best = Reg;
2619 else {
2620 unsigned Count = RegUses.getUsedByIndices(Reg).count();
2621 if (Count > BestNum) {
2622 Best = Reg;
2623 BestNum = Count;
2624 }
2625 }
2626 }
2627
2628 DEBUG(dbgs() << "Narrowing the search space by assuming " << *Best
2629 << " will yeild profitable reuse.\n");
2630 Taken.insert(Best);
2631
2632 // In any use with formulae which references this register, delete formulae
2633 // which don't reference it.
2634 for (SmallVectorImpl<LSRUse>::iterator I = Uses.begin(),
2635 E = Uses.end(); I != E; ++I) {
2636 LSRUse &LU = *I;
2637 if (!LU.Regs.count(Best)) continue;
2638
2639 // Clear out the set of used regs; it will be recomputed.
2640 LU.Regs.clear();
2641
2642 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
2643 Formula &F = LU.Formulae[i];
2644 if (!F.referencesReg(Best)) {
2645 DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
2646 std::swap(LU.Formulae.back(), F);
2647 LU.Formulae.pop_back();
2648 --e;
2649 --i;
2650 continue;
2651 }
2652
2653 if (F.ScaledReg) LU.Regs.insert(F.ScaledReg);
2654 LU.Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
2655 }
2656 }
2657
2658 DEBUG(dbgs() << "After pre-selection:\n";
2659 print_uses(dbgs()));
2660 }
2661}
2662
2663/// SolveRecurse - This is the recursive solver.
2664void LSRInstance::SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
2665 Cost &SolutionCost,
2666 SmallVectorImpl<const Formula *> &Workspace,
2667 const Cost &CurCost,
2668 const SmallPtrSet<const SCEV *, 16> &CurRegs,
2669 DenseSet<const SCEV *> &VisitedRegs) const {
2670 // Some ideas:
2671 // - prune more:
2672 // - use more aggressive filtering
2673 // - sort the formula so that the most profitable solutions are found first
2674 // - sort the uses too
2675 // - search faster:
2676 // - dont compute a cost, and then compare. compare while computing a cost
2677 // and bail early.
2678 // - track register sets with SmallBitVector
2679
2680 const LSRUse &LU = Uses[Workspace.size()];
2681
2682 // If this use references any register that's already a part of the
2683 // in-progress solution, consider it a requirement that a formula must
2684 // reference that register in order to be considered. This prunes out
2685 // unprofitable searching.
2686 SmallSetVector<const SCEV *, 4> ReqRegs;
2687 for (SmallPtrSet<const SCEV *, 16>::const_iterator I = CurRegs.begin(),
2688 E = CurRegs.end(); I != E; ++I)
Dan Gohman9214b822010-02-13 02:06:02 +00002689 if (LU.Regs.count(*I))
Dan Gohman572645c2010-02-12 10:34:29 +00002690 ReqRegs.insert(*I);
Dan Gohman572645c2010-02-12 10:34:29 +00002691
Dan Gohman9214b822010-02-13 02:06:02 +00002692 bool AnySatisfiedReqRegs = false;
Dan Gohman572645c2010-02-12 10:34:29 +00002693 SmallPtrSet<const SCEV *, 16> NewRegs;
2694 Cost NewCost;
Dan Gohman9214b822010-02-13 02:06:02 +00002695retry:
Dan Gohman572645c2010-02-12 10:34:29 +00002696 for (SmallVectorImpl<Formula>::const_iterator I = LU.Formulae.begin(),
2697 E = LU.Formulae.end(); I != E; ++I) {
2698 const Formula &F = *I;
2699
2700 // Ignore formulae which do not use any of the required registers.
2701 for (SmallSetVector<const SCEV *, 4>::const_iterator J = ReqRegs.begin(),
2702 JE = ReqRegs.end(); J != JE; ++J) {
2703 const SCEV *Reg = *J;
2704 if ((!F.ScaledReg || F.ScaledReg != Reg) &&
2705 std::find(F.BaseRegs.begin(), F.BaseRegs.end(), Reg) ==
2706 F.BaseRegs.end())
2707 goto skip;
2708 }
Dan Gohman9214b822010-02-13 02:06:02 +00002709 AnySatisfiedReqRegs = true;
Dan Gohman572645c2010-02-12 10:34:29 +00002710
2711 // Evaluate the cost of the current formula. If it's already worse than
2712 // the current best, prune the search at that point.
2713 NewCost = CurCost;
2714 NewRegs = CurRegs;
2715 NewCost.RateFormula(F, NewRegs, VisitedRegs, L, LU.Offsets, SE, DT);
2716 if (NewCost < SolutionCost) {
2717 Workspace.push_back(&F);
2718 if (Workspace.size() != Uses.size()) {
2719 SolveRecurse(Solution, SolutionCost, Workspace, NewCost,
2720 NewRegs, VisitedRegs);
2721 if (F.getNumRegs() == 1 && Workspace.size() == 1)
2722 VisitedRegs.insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]);
2723 } else {
2724 DEBUG(dbgs() << "New best at "; NewCost.print(dbgs());
2725 dbgs() << ". Regs:";
2726 for (SmallPtrSet<const SCEV *, 16>::const_iterator
2727 I = NewRegs.begin(), E = NewRegs.end(); I != E; ++I)
2728 dbgs() << ' ' << **I;
2729 dbgs() << '\n');
2730
2731 SolutionCost = NewCost;
2732 Solution = Workspace;
2733 }
2734 Workspace.pop_back();
2735 }
2736 skip:;
2737 }
Dan Gohman9214b822010-02-13 02:06:02 +00002738
2739 // If none of the formulae had all of the required registers, relax the
2740 // constraint so that we don't exclude all formulae.
2741 if (!AnySatisfiedReqRegs) {
2742 ReqRegs.clear();
2743 goto retry;
2744 }
Dan Gohman572645c2010-02-12 10:34:29 +00002745}
2746
2747void LSRInstance::Solve(SmallVectorImpl<const Formula *> &Solution) const {
2748 SmallVector<const Formula *, 8> Workspace;
2749 Cost SolutionCost;
2750 SolutionCost.Loose();
2751 Cost CurCost;
2752 SmallPtrSet<const SCEV *, 16> CurRegs;
2753 DenseSet<const SCEV *> VisitedRegs;
2754 Workspace.reserve(Uses.size());
2755
2756 SolveRecurse(Solution, SolutionCost, Workspace, CurCost,
2757 CurRegs, VisitedRegs);
2758
2759 // Ok, we've now made all our decisions.
2760 DEBUG(dbgs() << "\n"
2761 "The chosen solution requires "; SolutionCost.print(dbgs());
2762 dbgs() << ":\n";
2763 for (size_t i = 0, e = Uses.size(); i != e; ++i) {
2764 dbgs() << " ";
2765 Uses[i].print(dbgs());
2766 dbgs() << "\n"
2767 " ";
2768 Solution[i]->print(dbgs());
2769 dbgs() << '\n';
2770 });
2771}
2772
2773/// getImmediateDominator - A handy utility for the specific DominatorTree
2774/// query that we need here.
2775///
2776static BasicBlock *getImmediateDominator(BasicBlock *BB, DominatorTree &DT) {
2777 DomTreeNode *Node = DT.getNode(BB);
2778 if (!Node) return 0;
2779 Node = Node->getIDom();
2780 if (!Node) return 0;
2781 return Node->getBlock();
2782}
2783
2784Value *LSRInstance::Expand(const LSRFixup &LF,
2785 const Formula &F,
2786 BasicBlock::iterator IP,
2787 Loop *L, Instruction *IVIncInsertPos,
2788 SCEVExpander &Rewriter,
2789 SmallVectorImpl<WeakVH> &DeadInsts,
2790 ScalarEvolution &SE, DominatorTree &DT) const {
2791 const LSRUse &LU = Uses[LF.LUIdx];
2792
2793 // Then, collect some instructions which we will remain dominated by when
2794 // expanding the replacement. These must be dominated by any operands that
2795 // will be required in the expansion.
2796 SmallVector<Instruction *, 4> Inputs;
2797 if (Instruction *I = dyn_cast<Instruction>(LF.OperandValToReplace))
2798 Inputs.push_back(I);
2799 if (LU.Kind == LSRUse::ICmpZero)
2800 if (Instruction *I =
2801 dyn_cast<Instruction>(cast<ICmpInst>(LF.UserInst)->getOperand(1)))
2802 Inputs.push_back(I);
2803 if (LF.PostIncLoop && !L->contains(LF.UserInst))
2804 Inputs.push_back(L->getLoopLatch()->getTerminator());
2805
2806 // Then, climb up the immediate dominator tree as far as we can go while
2807 // still being dominated by the input positions.
2808 for (;;) {
2809 bool AllDominate = true;
2810 Instruction *BetterPos = 0;
2811 BasicBlock *IDom = getImmediateDominator(IP->getParent(), DT);
2812 if (!IDom) break;
2813 Instruction *Tentative = IDom->getTerminator();
2814 for (SmallVectorImpl<Instruction *>::const_iterator I = Inputs.begin(),
2815 E = Inputs.end(); I != E; ++I) {
2816 Instruction *Inst = *I;
2817 if (Inst == Tentative || !DT.dominates(Inst, Tentative)) {
2818 AllDominate = false;
2819 break;
2820 }
2821 if (IDom == Inst->getParent() &&
2822 (!BetterPos || DT.dominates(BetterPos, Inst)))
2823 BetterPos = next(BasicBlock::iterator(Inst));
2824 }
2825 if (!AllDominate)
2826 break;
2827 if (BetterPos)
2828 IP = BetterPos;
2829 else
2830 IP = Tentative;
2831 }
2832 while (isa<PHINode>(IP)) ++IP;
2833
2834 // Inform the Rewriter if we have a post-increment use, so that it can
2835 // perform an advantageous expansion.
2836 Rewriter.setPostInc(LF.PostIncLoop);
2837
2838 // This is the type that the user actually needs.
2839 const Type *OpTy = LF.OperandValToReplace->getType();
2840 // This will be the type that we'll initially expand to.
2841 const Type *Ty = F.getType();
2842 if (!Ty)
2843 // No type known; just expand directly to the ultimate type.
2844 Ty = OpTy;
2845 else if (SE.getEffectiveSCEVType(Ty) == SE.getEffectiveSCEVType(OpTy))
2846 // Expand directly to the ultimate type if it's the right size.
2847 Ty = OpTy;
2848 // This is the type to do integer arithmetic in.
2849 const Type *IntTy = SE.getEffectiveSCEVType(Ty);
2850
2851 // Build up a list of operands to add together to form the full base.
2852 SmallVector<const SCEV *, 8> Ops;
2853
2854 // Expand the BaseRegs portion.
2855 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
2856 E = F.BaseRegs.end(); I != E; ++I) {
2857 const SCEV *Reg = *I;
2858 assert(!Reg->isZero() && "Zero allocated in a base register!");
2859
2860 // If we're expanding for a post-inc user for the add-rec's loop, make the
2861 // post-inc adjustment.
2862 const SCEV *Start = Reg;
2863 while (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Start)) {
2864 if (AR->getLoop() == LF.PostIncLoop) {
2865 Reg = SE.getAddExpr(Reg, AR->getStepRecurrence(SE));
2866 // If the user is inside the loop, insert the code after the increment
2867 // so that it is dominated by its operand.
2868 if (L->contains(LF.UserInst))
2869 IP = IVIncInsertPos;
2870 break;
2871 }
2872 Start = AR->getStart();
2873 }
2874
2875 Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, 0, IP)));
2876 }
2877
2878 // Expand the ScaledReg portion.
2879 Value *ICmpScaledV = 0;
2880 if (F.AM.Scale != 0) {
2881 const SCEV *ScaledS = F.ScaledReg;
2882
2883 // If we're expanding for a post-inc user for the add-rec's loop, make the
2884 // post-inc adjustment.
2885 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ScaledS))
2886 if (AR->getLoop() == LF.PostIncLoop)
2887 ScaledS = SE.getAddExpr(ScaledS, AR->getStepRecurrence(SE));
2888
2889 if (LU.Kind == LSRUse::ICmpZero) {
2890 // An interesting way of "folding" with an icmp is to use a negated
2891 // scale, which we'll implement by inserting it into the other operand
2892 // of the icmp.
2893 assert(F.AM.Scale == -1 &&
2894 "The only scale supported by ICmpZero uses is -1!");
2895 ICmpScaledV = Rewriter.expandCodeFor(ScaledS, 0, IP);
2896 } else {
2897 // Otherwise just expand the scaled register and an explicit scale,
2898 // which is expected to be matched as part of the address.
2899 ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, 0, IP));
2900 ScaledS = SE.getMulExpr(ScaledS,
2901 SE.getIntegerSCEV(F.AM.Scale,
2902 ScaledS->getType()));
2903 Ops.push_back(ScaledS);
2904 }
2905 }
2906
2907 // Expand the immediate portions.
2908 if (F.AM.BaseGV)
2909 Ops.push_back(SE.getSCEV(F.AM.BaseGV));
2910 int64_t Offset = (uint64_t)F.AM.BaseOffs + LF.Offset;
2911 if (Offset != 0) {
2912 if (LU.Kind == LSRUse::ICmpZero) {
2913 // The other interesting way of "folding" with an ICmpZero is to use a
2914 // negated immediate.
2915 if (!ICmpScaledV)
2916 ICmpScaledV = ConstantInt::get(IntTy, -Offset);
2917 else {
2918 Ops.push_back(SE.getUnknown(ICmpScaledV));
2919 ICmpScaledV = ConstantInt::get(IntTy, Offset);
2920 }
2921 } else {
2922 // Just add the immediate values. These again are expected to be matched
2923 // as part of the address.
2924 Ops.push_back(SE.getIntegerSCEV(Offset, IntTy));
2925 }
2926 }
2927
2928 // Emit instructions summing all the operands.
2929 const SCEV *FullS = Ops.empty() ?
2930 SE.getIntegerSCEV(0, IntTy) :
2931 SE.getAddExpr(Ops);
2932 Value *FullV = Rewriter.expandCodeFor(FullS, Ty, IP);
2933
2934 // We're done expanding now, so reset the rewriter.
2935 Rewriter.setPostInc(0);
2936
2937 // An ICmpZero Formula represents an ICmp which we're handling as a
2938 // comparison against zero. Now that we've expanded an expression for that
2939 // form, update the ICmp's other operand.
2940 if (LU.Kind == LSRUse::ICmpZero) {
2941 ICmpInst *CI = cast<ICmpInst>(LF.UserInst);
2942 DeadInsts.push_back(CI->getOperand(1));
2943 assert(!F.AM.BaseGV && "ICmp does not support folding a global value and "
2944 "a scale at the same time!");
2945 if (F.AM.Scale == -1) {
2946 if (ICmpScaledV->getType() != OpTy) {
2947 Instruction *Cast =
2948 CastInst::Create(CastInst::getCastOpcode(ICmpScaledV, false,
2949 OpTy, false),
2950 ICmpScaledV, OpTy, "tmp", CI);
2951 ICmpScaledV = Cast;
2952 }
2953 CI->setOperand(1, ICmpScaledV);
2954 } else {
2955 assert(F.AM.Scale == 0 &&
2956 "ICmp does not support folding a global value and "
2957 "a scale at the same time!");
2958 Constant *C = ConstantInt::getSigned(SE.getEffectiveSCEVType(OpTy),
2959 -(uint64_t)Offset);
2960 if (C->getType() != OpTy)
2961 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2962 OpTy, false),
2963 C, OpTy);
2964
2965 CI->setOperand(1, C);
2966 }
2967 }
2968
2969 return FullV;
2970}
2971
Dan Gohman3a02cbc2010-02-16 20:25:07 +00002972/// RewriteForPHI - Helper for Rewrite. PHI nodes are special because the use
2973/// of their operands effectively happens in their predecessor blocks, so the
2974/// expression may need to be expanded in multiple places.
2975void LSRInstance::RewriteForPHI(PHINode *PN,
2976 const LSRFixup &LF,
2977 const Formula &F,
2978 Loop *L, Instruction *IVIncInsertPos,
2979 SCEVExpander &Rewriter,
2980 SmallVectorImpl<WeakVH> &DeadInsts,
2981 ScalarEvolution &SE, DominatorTree &DT,
2982 Pass *P) const {
2983 DenseMap<BasicBlock *, Value *> Inserted;
2984 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2985 if (PN->getIncomingValue(i) == LF.OperandValToReplace) {
2986 BasicBlock *BB = PN->getIncomingBlock(i);
2987
2988 // If this is a critical edge, split the edge so that we do not insert
2989 // the code on all predecessor/successor paths. We do this unless this
2990 // is the canonical backedge for this loop, which complicates post-inc
2991 // users.
2992 if (e != 1 && BB->getTerminator()->getNumSuccessors() > 1 &&
2993 !isa<IndirectBrInst>(BB->getTerminator()) &&
2994 (PN->getParent() != L->getHeader() || !L->contains(BB))) {
2995 // Split the critical edge.
2996 BasicBlock *NewBB = SplitCriticalEdge(BB, PN->getParent(), P);
2997
2998 // If PN is outside of the loop and BB is in the loop, we want to
2999 // move the block to be immediately before the PHI block, not
3000 // immediately after BB.
3001 if (L->contains(BB) && !L->contains(PN))
3002 NewBB->moveBefore(PN->getParent());
3003
3004 // Splitting the edge can reduce the number of PHI entries we have.
3005 e = PN->getNumIncomingValues();
3006 BB = NewBB;
3007 i = PN->getBasicBlockIndex(BB);
3008 }
3009
3010 std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> Pair =
3011 Inserted.insert(std::make_pair(BB, static_cast<Value *>(0)));
3012 if (!Pair.second)
3013 PN->setIncomingValue(i, Pair.first->second);
3014 else {
3015 Value *FullV = Expand(LF, F, BB->getTerminator(), L, IVIncInsertPos,
3016 Rewriter, DeadInsts, SE, DT);
3017
3018 // If this is reuse-by-noop-cast, insert the noop cast.
3019 const Type *OpTy = LF.OperandValToReplace->getType();
3020 if (FullV->getType() != OpTy)
3021 FullV =
3022 CastInst::Create(CastInst::getCastOpcode(FullV, false,
3023 OpTy, false),
3024 FullV, LF.OperandValToReplace->getType(),
3025 "tmp", BB->getTerminator());
3026
3027 PN->setIncomingValue(i, FullV);
3028 Pair.first->second = FullV;
3029 }
3030 }
3031}
3032
Dan Gohman572645c2010-02-12 10:34:29 +00003033/// Rewrite - Emit instructions for the leading candidate expression for this
3034/// LSRUse (this is called "expanding"), and update the UserInst to reference
3035/// the newly expanded value.
3036void LSRInstance::Rewrite(const LSRFixup &LF,
3037 const Formula &F,
3038 Loop *L, Instruction *IVIncInsertPos,
3039 SCEVExpander &Rewriter,
3040 SmallVectorImpl<WeakVH> &DeadInsts,
3041 ScalarEvolution &SE, DominatorTree &DT,
3042 Pass *P) const {
Dan Gohman572645c2010-02-12 10:34:29 +00003043 // First, find an insertion point that dominates UserInst. For PHI nodes,
3044 // find the nearest block which dominates all the relevant uses.
3045 if (PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) {
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003046 RewriteForPHI(PN, LF, F, L, IVIncInsertPos, Rewriter, DeadInsts, SE, DT, P);
Dan Gohman572645c2010-02-12 10:34:29 +00003047 } else {
3048 Value *FullV = Expand(LF, F, LF.UserInst, L, IVIncInsertPos,
3049 Rewriter, DeadInsts, SE, DT);
3050
3051 // If this is reuse-by-noop-cast, insert the noop cast.
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003052 const Type *OpTy = LF.OperandValToReplace->getType();
Dan Gohman572645c2010-02-12 10:34:29 +00003053 if (FullV->getType() != OpTy) {
3054 Instruction *Cast =
3055 CastInst::Create(CastInst::getCastOpcode(FullV, false, OpTy, false),
3056 FullV, OpTy, "tmp", LF.UserInst);
3057 FullV = Cast;
3058 }
3059
3060 // Update the user. ICmpZero is handled specially here (for now) because
3061 // Expand may have updated one of the operands of the icmp already, and
3062 // its new value may happen to be equal to LF.OperandValToReplace, in
3063 // which case doing replaceUsesOfWith leads to replacing both operands
3064 // with the same value. TODO: Reorganize this.
3065 if (Uses[LF.LUIdx].Kind == LSRUse::ICmpZero)
3066 LF.UserInst->setOperand(0, FullV);
3067 else
3068 LF.UserInst->replaceUsesOfWith(LF.OperandValToReplace, FullV);
3069 }
3070
3071 DeadInsts.push_back(LF.OperandValToReplace);
3072}
3073
3074void
3075LSRInstance::ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
3076 Pass *P) {
3077 // Keep track of instructions we may have made dead, so that
3078 // we can remove them after we are done working.
3079 SmallVector<WeakVH, 16> DeadInsts;
3080
3081 SCEVExpander Rewriter(SE);
3082 Rewriter.disableCanonicalMode();
3083 Rewriter.setIVIncInsertPos(L, IVIncInsertPos);
3084
3085 // Expand the new value definitions and update the users.
3086 for (size_t i = 0, e = Fixups.size(); i != e; ++i) {
3087 size_t LUIdx = Fixups[i].LUIdx;
3088
3089 Rewrite(Fixups[i], *Solution[LUIdx], L, IVIncInsertPos, Rewriter,
3090 DeadInsts, SE, DT, P);
3091
3092 Changed = true;
3093 }
3094
3095 // Clean up after ourselves. This must be done before deleting any
3096 // instructions.
3097 Rewriter.clear();
3098
3099 Changed |= DeleteTriviallyDeadInstructions(DeadInsts);
3100}
3101
3102LSRInstance::LSRInstance(const TargetLowering *tli, Loop *l, Pass *P)
3103 : IU(P->getAnalysis<IVUsers>()),
3104 SE(P->getAnalysis<ScalarEvolution>()),
3105 DT(P->getAnalysis<DominatorTree>()),
3106 TLI(tli), L(l), Changed(false), IVIncInsertPos(0) {
Devang Patel0f54dcb2007-03-06 21:14:09 +00003107
Dan Gohman03e896b2009-11-05 21:11:53 +00003108 // If LoopSimplify form is not available, stay out of trouble.
Dan Gohman572645c2010-02-12 10:34:29 +00003109 if (!L->isLoopSimplifyForm()) return;
Dan Gohman03e896b2009-11-05 21:11:53 +00003110
Dan Gohman572645c2010-02-12 10:34:29 +00003111 // If there's no interesting work to be done, bail early.
3112 if (IU.empty()) return;
Dan Gohman80b0f8c2009-03-09 20:34:59 +00003113
Dan Gohman572645c2010-02-12 10:34:29 +00003114 DEBUG(dbgs() << "\nLSR on loop ";
3115 WriteAsOperand(dbgs(), L->getHeader(), /*PrintType=*/false);
3116 dbgs() << ":\n");
Dan Gohmanf7912df2009-03-09 20:46:50 +00003117
Dan Gohman572645c2010-02-12 10:34:29 +00003118 /// OptimizeShadowIV - If IV is used in a int-to-float cast
3119 /// inside the loop then try to eliminate the cast opeation.
3120 OptimizeShadowIV();
Chris Lattner010de252005-08-08 05:28:22 +00003121
Dan Gohman572645c2010-02-12 10:34:29 +00003122 // Change loop terminating condition to use the postinc iv when possible.
3123 Changed |= OptimizeLoopTermCond();
Evan Cheng5792f512009-05-11 22:33:01 +00003124
Dan Gohman572645c2010-02-12 10:34:29 +00003125 CollectInterestingTypesAndFactors();
3126 CollectFixupsAndInitialFormulae();
3127 CollectLoopInvariantFixupsAndFormulae();
Chris Lattner010de252005-08-08 05:28:22 +00003128
Dan Gohman572645c2010-02-12 10:34:29 +00003129 DEBUG(dbgs() << "LSR found " << Uses.size() << " uses:\n";
3130 print_uses(dbgs()));
Misha Brukmanfd939082005-04-21 23:48:37 +00003131
Dan Gohman572645c2010-02-12 10:34:29 +00003132 // Now use the reuse data to generate a bunch of interesting ways
3133 // to formulate the values needed for the uses.
3134 GenerateAllReuseFormulae();
Evan Chengd1d6b5c2006-03-16 21:53:05 +00003135
Dan Gohman572645c2010-02-12 10:34:29 +00003136 DEBUG(dbgs() << "\n"
3137 "After generating reuse formulae:\n";
3138 print_uses(dbgs()));
Nate Begemaneaa13852004-10-18 21:08:22 +00003139
Dan Gohman572645c2010-02-12 10:34:29 +00003140 FilterOutUndesirableDedicatedRegisters();
3141 NarrowSearchSpaceUsingHeuristics();
Dan Gohman6bec5bb2009-12-18 00:06:20 +00003142
Dan Gohman572645c2010-02-12 10:34:29 +00003143 SmallVector<const Formula *, 8> Solution;
3144 Solve(Solution);
3145 assert(Solution.size() == Uses.size() && "Malformed solution!");
Dan Gohman6bec5bb2009-12-18 00:06:20 +00003146
Dan Gohman572645c2010-02-12 10:34:29 +00003147 // Release memory that is no longer needed.
3148 Factors.clear();
3149 Types.clear();
3150 RegUses.clear();
3151
3152#ifndef NDEBUG
3153 // Formulae should be legal.
3154 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
3155 E = Uses.end(); I != E; ++I) {
3156 const LSRUse &LU = *I;
3157 for (SmallVectorImpl<Formula>::const_iterator J = LU.Formulae.begin(),
3158 JE = LU.Formulae.end(); J != JE; ++J)
3159 assert(isLegalUse(J->AM, LU.MinOffset, LU.MaxOffset,
3160 LU.Kind, LU.AccessTy, TLI) &&
3161 "Illegal formula generated!");
3162 };
3163#endif
3164
3165 // Now that we've decided what we want, make it so.
3166 ImplementSolution(Solution, P);
3167}
3168
3169void LSRInstance::print_factors_and_types(raw_ostream &OS) const {
3170 if (Factors.empty() && Types.empty()) return;
3171
3172 OS << "LSR has identified the following interesting factors and types: ";
3173 bool First = true;
3174
3175 for (SmallSetVector<int64_t, 8>::const_iterator
3176 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
3177 if (!First) OS << ", ";
3178 First = false;
3179 OS << '*' << *I;
Evan Cheng81ebdcf2009-11-10 21:14:05 +00003180 }
Dale Johannesenc1acc3f2009-05-11 17:15:42 +00003181
Dan Gohman572645c2010-02-12 10:34:29 +00003182 for (SmallSetVector<const Type *, 4>::const_iterator
3183 I = Types.begin(), E = Types.end(); I != E; ++I) {
3184 if (!First) OS << ", ";
3185 First = false;
3186 OS << '(' << **I << ')';
3187 }
3188 OS << '\n';
3189}
3190
3191void LSRInstance::print_fixups(raw_ostream &OS) const {
3192 OS << "LSR is examining the following fixup sites:\n";
3193 for (SmallVectorImpl<LSRFixup>::const_iterator I = Fixups.begin(),
3194 E = Fixups.end(); I != E; ++I) {
3195 const LSRFixup &LF = *I;
3196 dbgs() << " ";
3197 LF.print(OS);
3198 OS << '\n';
3199 }
3200}
3201
3202void LSRInstance::print_uses(raw_ostream &OS) const {
3203 OS << "LSR is examining the following uses:\n";
3204 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
3205 E = Uses.end(); I != E; ++I) {
3206 const LSRUse &LU = *I;
3207 dbgs() << " ";
3208 LU.print(OS);
3209 OS << '\n';
3210 for (SmallVectorImpl<Formula>::const_iterator J = LU.Formulae.begin(),
3211 JE = LU.Formulae.end(); J != JE; ++J) {
3212 OS << " ";
3213 J->print(OS);
3214 OS << '\n';
3215 }
3216 }
3217}
3218
3219void LSRInstance::print(raw_ostream &OS) const {
3220 print_factors_and_types(OS);
3221 print_fixups(OS);
3222 print_uses(OS);
3223}
3224
3225void LSRInstance::dump() const {
3226 print(errs()); errs() << '\n';
3227}
3228
3229namespace {
3230
3231class LoopStrengthReduce : public LoopPass {
3232 /// TLI - Keep a pointer of a TargetLowering to consult for determining
3233 /// transformation profitability.
3234 const TargetLowering *const TLI;
3235
3236public:
3237 static char ID; // Pass ID, replacement for typeid
3238 explicit LoopStrengthReduce(const TargetLowering *tli = 0);
3239
3240private:
3241 bool runOnLoop(Loop *L, LPPassManager &LPM);
3242 void getAnalysisUsage(AnalysisUsage &AU) const;
3243};
3244
3245}
3246
3247char LoopStrengthReduce::ID = 0;
3248static RegisterPass<LoopStrengthReduce>
3249X("loop-reduce", "Loop Strength Reduction");
3250
3251Pass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
3252 return new LoopStrengthReduce(TLI);
3253}
3254
3255LoopStrengthReduce::LoopStrengthReduce(const TargetLowering *tli)
3256 : LoopPass(&ID), TLI(tli) {}
3257
3258void LoopStrengthReduce::getAnalysisUsage(AnalysisUsage &AU) const {
3259 // We split critical edges, so we change the CFG. However, we do update
3260 // many analyses if they are around.
3261 AU.addPreservedID(LoopSimplifyID);
3262 AU.addPreserved<LoopInfo>();
3263 AU.addPreserved("domfrontier");
3264
3265 AU.addRequiredID(LoopSimplifyID);
3266 AU.addRequired<DominatorTree>();
3267 AU.addPreserved<DominatorTree>();
3268 AU.addRequired<ScalarEvolution>();
3269 AU.addPreserved<ScalarEvolution>();
3270 AU.addRequired<IVUsers>();
3271 AU.addPreserved<IVUsers>();
3272}
3273
3274bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager & /*LPM*/) {
3275 bool Changed = false;
3276
3277 // Run the main LSR transformation.
3278 Changed |= LSRInstance(TLI, L, this).getChanged();
3279
Dan Gohmanafc36a92009-05-02 18:29:22 +00003280 // At this point, it is worth checking to see if any recurrence PHIs are also
Dan Gohman35738ac2009-05-04 22:30:44 +00003281 // dead, so that we can remove them as well.
Dan Gohman9fff2182010-01-05 16:31:45 +00003282 Changed |= DeleteDeadPHIs(L->getHeader());
Dan Gohmanafc36a92009-05-02 18:29:22 +00003283
Evan Cheng1ce75dc2008-07-07 19:51:32 +00003284 return Changed;
Nate Begemaneaa13852004-10-18 21:08:22 +00003285}