blob: 73d3f9db8965402347df6678473aff42b38b0a92 [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
340/// getSDiv - Return an expression for LHS /s RHS, if it can be determined,
341/// or null otherwise. If IgnoreSignificantBits is true, expressions like
342/// (X * Y) /s Y are simplified to Y, ignoring that the multiplication may
343/// overflow, which is useful when the result will be used in a context where
344/// the most significant bits are ignored.
345static const SCEV *getSDiv(const SCEV *LHS, const SCEV *RHS,
346 ScalarEvolution &SE,
347 bool IgnoreSignificantBits = false) {
348 // Handle the trivial case, which works for any SCEV type.
349 if (LHS == RHS)
350 return SE.getIntegerSCEV(1, LHS->getType());
351
352 // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do some
353 // folding.
354 if (RHS->isAllOnesValue())
355 return SE.getMulExpr(LHS, RHS);
356
357 // Check for a division of a constant by a constant.
358 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(LHS)) {
359 const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS);
360 if (!RC)
361 return 0;
362 if (C->getValue()->getValue().srem(RC->getValue()->getValue()) != 0)
363 return 0;
364 return SE.getConstant(C->getValue()->getValue()
365 .sdiv(RC->getValue()->getValue()));
366 }
367
368 // Distribute the sdiv over addrec operands.
369 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) {
370 const SCEV *Start = getSDiv(AR->getStart(), RHS, SE,
371 IgnoreSignificantBits);
372 if (!Start) return 0;
373 const SCEV *Step = getSDiv(AR->getStepRecurrence(SE), RHS, SE,
374 IgnoreSignificantBits);
375 if (!Step) return 0;
376 return SE.getAddRecExpr(Start, Step, AR->getLoop());
377 }
378
379 // Distribute the sdiv over add operands.
380 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(LHS)) {
381 SmallVector<const SCEV *, 8> Ops;
382 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
383 I != E; ++I) {
384 const SCEV *Op = getSDiv(*I, RHS, SE,
385 IgnoreSignificantBits);
386 if (!Op) return 0;
387 Ops.push_back(Op);
388 }
389 return SE.getAddExpr(Ops);
390 }
391
392 // Check for a multiply operand that we can pull RHS out of.
393 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS))
394 if (IgnoreSignificantBits || Mul->hasNoSignedWrap()) {
395 SmallVector<const SCEV *, 4> Ops;
396 bool Found = false;
397 for (SCEVMulExpr::op_iterator I = Mul->op_begin(), E = Mul->op_end();
398 I != E; ++I) {
399 if (!Found)
400 if (const SCEV *Q = getSDiv(*I, RHS, SE, IgnoreSignificantBits)) {
401 Ops.push_back(Q);
402 Found = true;
403 continue;
404 }
405 Ops.push_back(*I);
406 }
407 return Found ? SE.getMulExpr(Ops) : 0;
408 }
409
410 // Otherwise we don't know.
411 return 0;
412}
413
414/// ExtractImmediate - If S involves the addition of a constant integer value,
415/// return that integer value, and mutate S to point to a new SCEV with that
416/// value excluded.
417static int64_t ExtractImmediate(const SCEV *&S, ScalarEvolution &SE) {
418 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
419 if (C->getValue()->getValue().getMinSignedBits() <= 64) {
420 S = SE.getIntegerSCEV(0, C->getType());
421 return C->getValue()->getSExtValue();
422 }
423 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
424 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
425 int64_t Result = ExtractImmediate(NewOps.front(), SE);
426 S = SE.getAddExpr(NewOps);
427 return Result;
428 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
429 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
430 int64_t Result = ExtractImmediate(NewOps.front(), SE);
431 S = SE.getAddRecExpr(NewOps, AR->getLoop());
432 return Result;
433 }
434 return 0;
435}
436
437/// ExtractSymbol - If S involves the addition of a GlobalValue address,
438/// return that symbol, and mutate S to point to a new SCEV with that
439/// value excluded.
440static GlobalValue *ExtractSymbol(const SCEV *&S, ScalarEvolution &SE) {
441 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
442 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) {
443 S = SE.getIntegerSCEV(0, GV->getType());
444 return GV;
445 }
446 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
447 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
448 GlobalValue *Result = ExtractSymbol(NewOps.back(), SE);
449 S = SE.getAddExpr(NewOps);
450 return Result;
451 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
452 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
453 GlobalValue *Result = ExtractSymbol(NewOps.front(), SE);
454 S = SE.getAddRecExpr(NewOps, AR->getLoop());
455 return Result;
456 }
457 return 0;
Nate Begemaneaa13852004-10-18 21:08:22 +0000458}
459
Dan Gohmanf284ce22009-02-18 00:08:39 +0000460/// isAddressUse - Returns true if the specified instruction is using the
Dale Johannesen203af582008-12-05 21:47:27 +0000461/// specified value as an address.
462static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
463 bool isAddress = isa<LoadInst>(Inst);
464 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
465 if (SI->getOperand(1) == OperandVal)
466 isAddress = true;
467 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
468 // Addressing modes can also be folded into prefetches and a variety
469 // of intrinsics.
470 switch (II->getIntrinsicID()) {
471 default: break;
472 case Intrinsic::prefetch:
473 case Intrinsic::x86_sse2_loadu_dq:
474 case Intrinsic::x86_sse2_loadu_pd:
475 case Intrinsic::x86_sse_loadu_ps:
476 case Intrinsic::x86_sse_storeu_ps:
477 case Intrinsic::x86_sse2_storeu_pd:
478 case Intrinsic::x86_sse2_storeu_dq:
479 case Intrinsic::x86_sse2_storel_dq:
480 if (II->getOperand(1) == OperandVal)
481 isAddress = true;
482 break;
483 }
484 }
485 return isAddress;
486}
Chris Lattner0ae33eb2005-10-03 01:04:44 +0000487
Dan Gohman21e77222009-03-09 21:01:17 +0000488/// getAccessType - Return the type of the memory being accessed.
489static const Type *getAccessType(const Instruction *Inst) {
Dan Gohmana537bf82009-05-18 16:45:28 +0000490 const Type *AccessTy = Inst->getType();
Dan Gohman21e77222009-03-09 21:01:17 +0000491 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst))
Dan Gohmana537bf82009-05-18 16:45:28 +0000492 AccessTy = SI->getOperand(0)->getType();
Dan Gohman21e77222009-03-09 21:01:17 +0000493 else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
494 // Addressing modes can also be folded into prefetches and a variety
495 // of intrinsics.
496 switch (II->getIntrinsicID()) {
497 default: break;
498 case Intrinsic::x86_sse_storeu_ps:
499 case Intrinsic::x86_sse2_storeu_pd:
500 case Intrinsic::x86_sse2_storeu_dq:
501 case Intrinsic::x86_sse2_storel_dq:
Dan Gohmana537bf82009-05-18 16:45:28 +0000502 AccessTy = II->getOperand(1)->getType();
Dan Gohman21e77222009-03-09 21:01:17 +0000503 break;
504 }
505 }
Dan Gohman572645c2010-02-12 10:34:29 +0000506
507 // All pointers have the same requirements, so canonicalize them to an
508 // arbitrary pointer type to minimize variation.
509 if (const PointerType *PTy = dyn_cast<PointerType>(AccessTy))
510 AccessTy = PointerType::get(IntegerType::get(PTy->getContext(), 1),
511 PTy->getAddressSpace());
512
Dan Gohmana537bf82009-05-18 16:45:28 +0000513 return AccessTy;
Dan Gohman21e77222009-03-09 21:01:17 +0000514}
515
Dan Gohman572645c2010-02-12 10:34:29 +0000516/// DeleteTriviallyDeadInstructions - If any of the instructions is the
517/// specified set are trivially dead, delete them and see if this makes any of
518/// their operands subsequently dead.
519static bool
520DeleteTriviallyDeadInstructions(SmallVectorImpl<WeakVH> &DeadInsts) {
521 bool Changed = false;
522
523 while (!DeadInsts.empty()) {
524 Instruction *I = dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val());
525
526 if (I == 0 || !isInstructionTriviallyDead(I))
527 continue;
528
529 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
530 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
531 *OI = 0;
532 if (U->use_empty())
533 DeadInsts.push_back(U);
534 }
535
536 I->eraseFromParent();
537 Changed = true;
538 }
539
540 return Changed;
541}
542
Dan Gohman7979b722010-01-22 00:46:49 +0000543namespace {
Jim Grosbach56a1f802009-11-17 17:53:56 +0000544
Dan Gohman572645c2010-02-12 10:34:29 +0000545/// Cost - This class is used to measure and compare candidate formulae.
546class Cost {
547 /// TODO: Some of these could be merged. Also, a lexical ordering
548 /// isn't always optimal.
549 unsigned NumRegs;
550 unsigned AddRecCost;
551 unsigned NumIVMuls;
552 unsigned NumBaseAdds;
553 unsigned ImmCost;
554 unsigned SetupCost;
Nate Begeman16997482005-07-30 00:15:07 +0000555
Dan Gohman572645c2010-02-12 10:34:29 +0000556public:
557 Cost()
558 : NumRegs(0), AddRecCost(0), NumIVMuls(0), NumBaseAdds(0), ImmCost(0),
559 SetupCost(0) {}
Jim Grosbach56a1f802009-11-17 17:53:56 +0000560
Dan Gohman572645c2010-02-12 10:34:29 +0000561 unsigned getNumRegs() const { return NumRegs; }
Dan Gohman7979b722010-01-22 00:46:49 +0000562
Dan Gohman572645c2010-02-12 10:34:29 +0000563 bool operator<(const Cost &Other) const;
Dan Gohman7979b722010-01-22 00:46:49 +0000564
Dan Gohman572645c2010-02-12 10:34:29 +0000565 void Loose();
Dan Gohman7979b722010-01-22 00:46:49 +0000566
Dan Gohman572645c2010-02-12 10:34:29 +0000567 void RateFormula(const Formula &F,
568 SmallPtrSet<const SCEV *, 16> &Regs,
569 const DenseSet<const SCEV *> &VisitedRegs,
570 const Loop *L,
571 const SmallVectorImpl<int64_t> &Offsets,
572 ScalarEvolution &SE, DominatorTree &DT);
Dan Gohman7979b722010-01-22 00:46:49 +0000573
Dan Gohman572645c2010-02-12 10:34:29 +0000574 void print(raw_ostream &OS) const;
575 void dump() const;
Dan Gohman7979b722010-01-22 00:46:49 +0000576
Dan Gohman572645c2010-02-12 10:34:29 +0000577private:
578 void RateRegister(const SCEV *Reg,
579 SmallPtrSet<const SCEV *, 16> &Regs,
580 const Loop *L,
581 ScalarEvolution &SE, DominatorTree &DT);
582};
583
584}
585
586/// RateRegister - Tally up interesting quantities from the given register.
587void Cost::RateRegister(const SCEV *Reg,
588 SmallPtrSet<const SCEV *, 16> &Regs,
589 const Loop *L,
590 ScalarEvolution &SE, DominatorTree &DT) {
591 if (Regs.insert(Reg)) {
592 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Reg)) {
593 if (AR->getLoop() == L)
594 AddRecCost += 1; /// TODO: This should be a function of the stride.
595
596 // If this is an addrec for a loop that's already been visited by LSR,
597 // don't second-guess its addrec phi nodes. LSR isn't currently smart
598 // enough to reason about more than one loop at a time. Consider these
599 // registers free and leave them alone.
600 else if (L->contains(AR->getLoop()) ||
601 (!AR->getLoop()->contains(L) &&
602 DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))) {
603 for (BasicBlock::iterator I = AR->getLoop()->getHeader()->begin();
604 PHINode *PN = dyn_cast<PHINode>(I); ++I)
605 if (SE.isSCEVable(PN->getType()) &&
606 (SE.getEffectiveSCEVType(PN->getType()) ==
607 SE.getEffectiveSCEVType(AR->getType())) &&
608 SE.getSCEV(PN) == AR)
609 goto no_cost;
610
611 // If this isn't one of the addrecs that the loop already has, it
612 // would require a costly new phi and add.
613 ++NumBaseAdds;
614 RateRegister(AR->getStart(), Regs, L, SE, DT);
615 }
616
617 // Add the step value register, if it needs one.
618 // TODO: The non-affine case isn't precisely modeled here.
619 if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1)))
620 RateRegister(AR->getOperand(1), Regs, L, SE, DT);
621 }
622 ++NumRegs;
623
624 // Rough heuristic; favor registers which don't require extra setup
625 // instructions in the preheader.
626 if (!isa<SCEVUnknown>(Reg) &&
627 !isa<SCEVConstant>(Reg) &&
628 !(isa<SCEVAddRecExpr>(Reg) &&
629 (isa<SCEVUnknown>(cast<SCEVAddRecExpr>(Reg)->getStart()) ||
630 isa<SCEVConstant>(cast<SCEVAddRecExpr>(Reg)->getStart()))))
631 ++SetupCost;
632 no_cost:;
633 }
634}
635
636void Cost::RateFormula(const Formula &F,
637 SmallPtrSet<const SCEV *, 16> &Regs,
638 const DenseSet<const SCEV *> &VisitedRegs,
639 const Loop *L,
640 const SmallVectorImpl<int64_t> &Offsets,
641 ScalarEvolution &SE, DominatorTree &DT) {
642 // Tally up the registers.
643 if (const SCEV *ScaledReg = F.ScaledReg) {
644 if (VisitedRegs.count(ScaledReg)) {
645 Loose();
646 return;
647 }
648 RateRegister(ScaledReg, Regs, L, SE, DT);
649 }
650 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
651 E = F.BaseRegs.end(); I != E; ++I) {
652 const SCEV *BaseReg = *I;
653 if (VisitedRegs.count(BaseReg)) {
654 Loose();
655 return;
656 }
657 RateRegister(BaseReg, Regs, L, SE, DT);
658
659 NumIVMuls += isa<SCEVMulExpr>(BaseReg) &&
660 BaseReg->hasComputableLoopEvolution(L);
661 }
662
663 if (F.BaseRegs.size() > 1)
664 NumBaseAdds += F.BaseRegs.size() - 1;
665
666 // Tally up the non-zero immediates.
667 for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
668 E = Offsets.end(); I != E; ++I) {
669 int64_t Offset = (uint64_t)*I + F.AM.BaseOffs;
670 if (F.AM.BaseGV)
671 ImmCost += 64; // Handle symbolic values conservatively.
672 // TODO: This should probably be the pointer size.
673 else if (Offset != 0)
674 ImmCost += APInt(64, Offset, true).getMinSignedBits();
675 }
676}
677
678/// Loose - Set this cost to a loosing value.
679void Cost::Loose() {
680 NumRegs = ~0u;
681 AddRecCost = ~0u;
682 NumIVMuls = ~0u;
683 NumBaseAdds = ~0u;
684 ImmCost = ~0u;
685 SetupCost = ~0u;
686}
687
688/// operator< - Choose the lower cost.
689bool Cost::operator<(const Cost &Other) const {
690 if (NumRegs != Other.NumRegs)
691 return NumRegs < Other.NumRegs;
692 if (AddRecCost != Other.AddRecCost)
693 return AddRecCost < Other.AddRecCost;
694 if (NumIVMuls != Other.NumIVMuls)
695 return NumIVMuls < Other.NumIVMuls;
696 if (NumBaseAdds != Other.NumBaseAdds)
697 return NumBaseAdds < Other.NumBaseAdds;
698 if (ImmCost != Other.ImmCost)
699 return ImmCost < Other.ImmCost;
700 if (SetupCost != Other.SetupCost)
701 return SetupCost < Other.SetupCost;
702 return false;
703}
704
705void Cost::print(raw_ostream &OS) const {
706 OS << NumRegs << " reg" << (NumRegs == 1 ? "" : "s");
707 if (AddRecCost != 0)
708 OS << ", with addrec cost " << AddRecCost;
709 if (NumIVMuls != 0)
710 OS << ", plus " << NumIVMuls << " IV mul" << (NumIVMuls == 1 ? "" : "s");
711 if (NumBaseAdds != 0)
712 OS << ", plus " << NumBaseAdds << " base add"
713 << (NumBaseAdds == 1 ? "" : "s");
714 if (ImmCost != 0)
715 OS << ", plus " << ImmCost << " imm cost";
716 if (SetupCost != 0)
717 OS << ", plus " << SetupCost << " setup cost";
718}
719
720void Cost::dump() const {
721 print(errs()); errs() << '\n';
722}
723
724namespace {
725
726/// LSRFixup - An operand value in an instruction which is to be replaced
727/// with some equivalent, possibly strength-reduced, replacement.
728struct LSRFixup {
729 /// UserInst - The instruction which will be updated.
730 Instruction *UserInst;
731
732 /// OperandValToReplace - The operand of the instruction which will
733 /// be replaced. The operand may be used more than once; every instance
734 /// will be replaced.
735 Value *OperandValToReplace;
736
737 /// PostIncLoop - If this user is to use the post-incremented value of an
738 /// induction variable, this variable is non-null and holds the loop
739 /// associated with the induction variable.
740 const Loop *PostIncLoop;
741
742 /// LUIdx - The index of the LSRUse describing the expression which
743 /// this fixup needs, minus an offset (below).
744 size_t LUIdx;
745
746 /// Offset - A constant offset to be added to the LSRUse expression.
747 /// This allows multiple fixups to share the same LSRUse with different
748 /// offsets, for example in an unrolled loop.
749 int64_t Offset;
750
751 LSRFixup();
752
753 void print(raw_ostream &OS) const;
754 void dump() const;
755};
756
757}
758
759LSRFixup::LSRFixup()
760 : UserInst(0), OperandValToReplace(0), PostIncLoop(0),
761 LUIdx(~size_t(0)), Offset(0) {}
762
763void LSRFixup::print(raw_ostream &OS) const {
764 OS << "UserInst=";
765 // Store is common and interesting enough to be worth special-casing.
766 if (StoreInst *Store = dyn_cast<StoreInst>(UserInst)) {
767 OS << "store ";
768 WriteAsOperand(OS, Store->getOperand(0), /*PrintType=*/false);
769 } else if (UserInst->getType()->isVoidTy())
770 OS << UserInst->getOpcodeName();
771 else
772 WriteAsOperand(OS, UserInst, /*PrintType=*/false);
773
774 OS << ", OperandValToReplace=";
775 WriteAsOperand(OS, OperandValToReplace, /*PrintType=*/false);
776
777 if (PostIncLoop) {
778 OS << ", PostIncLoop=";
779 WriteAsOperand(OS, PostIncLoop->getHeader(), /*PrintType=*/false);
780 }
781
782 if (LUIdx != ~size_t(0))
783 OS << ", LUIdx=" << LUIdx;
784
785 if (Offset != 0)
786 OS << ", Offset=" << Offset;
787}
788
789void LSRFixup::dump() const {
790 print(errs()); errs() << '\n';
791}
792
793namespace {
794
795/// UniquifierDenseMapInfo - A DenseMapInfo implementation for holding
796/// DenseMaps and DenseSets of sorted SmallVectors of const SCEV*.
797struct UniquifierDenseMapInfo {
798 static SmallVector<const SCEV *, 2> getEmptyKey() {
799 SmallVector<const SCEV *, 2> V;
800 V.push_back(reinterpret_cast<const SCEV *>(-1));
801 return V;
802 }
803
804 static SmallVector<const SCEV *, 2> getTombstoneKey() {
805 SmallVector<const SCEV *, 2> V;
806 V.push_back(reinterpret_cast<const SCEV *>(-2));
807 return V;
808 }
809
810 static unsigned getHashValue(const SmallVector<const SCEV *, 2> &V) {
811 unsigned Result = 0;
812 for (SmallVectorImpl<const SCEV *>::const_iterator I = V.begin(),
813 E = V.end(); I != E; ++I)
814 Result ^= DenseMapInfo<const SCEV *>::getHashValue(*I);
815 return Result;
816 }
817
818 static bool isEqual(const SmallVector<const SCEV *, 2> &LHS,
819 const SmallVector<const SCEV *, 2> &RHS) {
820 return LHS == RHS;
821 }
822};
823
824/// LSRUse - This class holds the state that LSR keeps for each use in
825/// IVUsers, as well as uses invented by LSR itself. It includes information
826/// about what kinds of things can be folded into the user, information about
827/// the user itself, and information about how the use may be satisfied.
828/// TODO: Represent multiple users of the same expression in common?
829class LSRUse {
830 DenseSet<SmallVector<const SCEV *, 2>, UniquifierDenseMapInfo> Uniquifier;
831
832public:
833 /// KindType - An enum for a kind of use, indicating what types of
834 /// scaled and immediate operands it might support.
835 enum KindType {
836 Basic, ///< A normal use, with no folding.
837 Special, ///< A special case of basic, allowing -1 scales.
838 Address, ///< An address use; folding according to TargetLowering
839 ICmpZero ///< An equality icmp with both operands folded into one.
840 // TODO: Add a generic icmp too?
Dan Gohman7979b722010-01-22 00:46:49 +0000841 };
Dan Gohman572645c2010-02-12 10:34:29 +0000842
843 KindType Kind;
844 const Type *AccessTy;
845
846 SmallVector<int64_t, 8> Offsets;
847 int64_t MinOffset;
848 int64_t MaxOffset;
849
850 /// AllFixupsOutsideLoop - This records whether all of the fixups using this
851 /// LSRUse are outside of the loop, in which case some special-case heuristics
852 /// may be used.
853 bool AllFixupsOutsideLoop;
854
855 /// Formulae - A list of ways to build a value that can satisfy this user.
856 /// After the list is populated, one of these is selected heuristically and
857 /// used to formulate a replacement for OperandValToReplace in UserInst.
858 SmallVector<Formula, 12> Formulae;
859
860 /// Regs - The set of register candidates used by all formulae in this LSRUse.
861 SmallPtrSet<const SCEV *, 4> Regs;
862
863 LSRUse(KindType K, const Type *T) : Kind(K), AccessTy(T),
864 MinOffset(INT64_MAX),
865 MaxOffset(INT64_MIN),
866 AllFixupsOutsideLoop(true) {}
867
868 bool InsertFormula(size_t LUIdx, const Formula &F);
869
870 void check() const;
871
872 void print(raw_ostream &OS) const;
873 void dump() const;
874};
875
876/// InsertFormula - If the given formula has not yet been inserted, add it to
877/// the list, and return true. Return false otherwise.
878bool LSRUse::InsertFormula(size_t LUIdx, const Formula &F) {
879 SmallVector<const SCEV *, 2> Key = F.BaseRegs;
880 if (F.ScaledReg) Key.push_back(F.ScaledReg);
881 // Unstable sort by host order ok, because this is only used for uniquifying.
882 std::sort(Key.begin(), Key.end());
883
884 if (!Uniquifier.insert(Key).second)
885 return false;
886
887 // Using a register to hold the value of 0 is not profitable.
888 assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&
889 "Zero allocated in a scaled register!");
890#ifndef NDEBUG
891 for (SmallVectorImpl<const SCEV *>::const_iterator I =
892 F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I)
893 assert(!(*I)->isZero() && "Zero allocated in a base register!");
894#endif
895
896 // Add the formula to the list.
897 Formulae.push_back(F);
898
899 // Record registers now being used by this use.
900 if (F.ScaledReg) Regs.insert(F.ScaledReg);
901 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
902
903 return true;
Dan Gohman7979b722010-01-22 00:46:49 +0000904}
905
Dan Gohman572645c2010-02-12 10:34:29 +0000906void LSRUse::print(raw_ostream &OS) const {
907 OS << "LSR Use: Kind=";
908 switch (Kind) {
909 case Basic: OS << "Basic"; break;
910 case Special: OS << "Special"; break;
911 case ICmpZero: OS << "ICmpZero"; break;
912 case Address:
913 OS << "Address of ";
914 if (isa<PointerType>(AccessTy))
915 OS << "pointer"; // the full pointer type could be really verbose
916 else
917 OS << *AccessTy;
Evan Chengcdf43b12007-10-25 09:11:16 +0000918 }
919
Dan Gohman572645c2010-02-12 10:34:29 +0000920 OS << ", Offsets={";
921 for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
922 E = Offsets.end(); I != E; ++I) {
923 OS << *I;
924 if (next(I) != E)
925 OS << ',';
Dan Gohman7979b722010-01-22 00:46:49 +0000926 }
Dan Gohman572645c2010-02-12 10:34:29 +0000927 OS << '}';
Dan Gohman7979b722010-01-22 00:46:49 +0000928
Dan Gohman572645c2010-02-12 10:34:29 +0000929 if (AllFixupsOutsideLoop)
930 OS << ", all-fixups-outside-loop";
Dan Gohman7979b722010-01-22 00:46:49 +0000931}
932
Dan Gohman572645c2010-02-12 10:34:29 +0000933void LSRUse::dump() const {
934 print(errs()); errs() << '\n';
935}
Dan Gohman7979b722010-01-22 00:46:49 +0000936
Dan Gohman572645c2010-02-12 10:34:29 +0000937/// isLegalUse - Test whether the use described by AM is "legal", meaning it can
938/// be completely folded into the user instruction at isel time. This includes
939/// address-mode folding and special icmp tricks.
940static bool isLegalUse(const TargetLowering::AddrMode &AM,
941 LSRUse::KindType Kind, const Type *AccessTy,
942 const TargetLowering *TLI) {
943 switch (Kind) {
944 case LSRUse::Address:
945 // If we have low-level target information, ask the target if it can
946 // completely fold this address.
947 if (TLI) return TLI->isLegalAddressingMode(AM, AccessTy);
948
949 // Otherwise, just guess that reg+reg addressing is legal.
950 return !AM.BaseGV && AM.BaseOffs == 0 && AM.Scale <= 1;
951
952 case LSRUse::ICmpZero:
953 // There's not even a target hook for querying whether it would be legal to
954 // fold a GV into an ICmp.
955 if (AM.BaseGV)
956 return false;
957
958 // ICmp only has two operands; don't allow more than two non-trivial parts.
959 if (AM.Scale != 0 && AM.HasBaseReg && AM.BaseOffs != 0)
960 return false;
961
962 // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by
963 // putting the scaled register in the other operand of the icmp.
964 if (AM.Scale != 0 && AM.Scale != -1)
965 return false;
966
967 // If we have low-level target information, ask the target if it can fold an
968 // integer immediate on an icmp.
969 if (AM.BaseOffs != 0) {
970 if (TLI) return TLI->isLegalICmpImmediate(-AM.BaseOffs);
971 return false;
Dan Gohman7979b722010-01-22 00:46:49 +0000972 }
Dan Gohman572645c2010-02-12 10:34:29 +0000973
974 return true;
975
976 case LSRUse::Basic:
977 // Only handle single-register values.
978 return !AM.BaseGV && AM.Scale == 0 && AM.BaseOffs == 0;
979
980 case LSRUse::Special:
981 // Only handle -1 scales, or no scale.
982 return AM.Scale == 0 || AM.Scale == -1;
Dan Gohman7979b722010-01-22 00:46:49 +0000983 }
984
Dan Gohman7979b722010-01-22 00:46:49 +0000985 return false;
986}
987
Dan Gohman572645c2010-02-12 10:34:29 +0000988static bool isLegalUse(TargetLowering::AddrMode AM,
989 int64_t MinOffset, int64_t MaxOffset,
990 LSRUse::KindType Kind, const Type *AccessTy,
991 const TargetLowering *TLI) {
992 // Check for overflow.
993 if (((int64_t)((uint64_t)AM.BaseOffs + MinOffset) > AM.BaseOffs) !=
994 (MinOffset > 0))
995 return false;
996 AM.BaseOffs = (uint64_t)AM.BaseOffs + MinOffset;
997 if (isLegalUse(AM, Kind, AccessTy, TLI)) {
998 AM.BaseOffs = (uint64_t)AM.BaseOffs - MinOffset;
999 // Check for overflow.
1000 if (((int64_t)((uint64_t)AM.BaseOffs + MaxOffset) > AM.BaseOffs) !=
1001 (MaxOffset > 0))
1002 return false;
1003 AM.BaseOffs = (uint64_t)AM.BaseOffs + MaxOffset;
1004 return isLegalUse(AM, Kind, AccessTy, TLI);
Dan Gohman7979b722010-01-22 00:46:49 +00001005 }
Dan Gohman572645c2010-02-12 10:34:29 +00001006 return false;
Dan Gohman7979b722010-01-22 00:46:49 +00001007}
1008
Dan Gohman572645c2010-02-12 10:34:29 +00001009static bool isAlwaysFoldable(int64_t BaseOffs,
1010 GlobalValue *BaseGV,
1011 bool HasBaseReg,
1012 LSRUse::KindType Kind, const Type *AccessTy,
1013 const TargetLowering *TLI,
1014 ScalarEvolution &SE) {
1015 // Fast-path: zero is always foldable.
1016 if (BaseOffs == 0 && !BaseGV) return true;
Dan Gohman7979b722010-01-22 00:46:49 +00001017
Dan Gohman572645c2010-02-12 10:34:29 +00001018 // Conservatively, create an address with an immediate and a
1019 // base and a scale.
1020 TargetLowering::AddrMode AM;
1021 AM.BaseOffs = BaseOffs;
1022 AM.BaseGV = BaseGV;
1023 AM.HasBaseReg = HasBaseReg;
1024 AM.Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
Dan Gohman7979b722010-01-22 00:46:49 +00001025
Dan Gohman572645c2010-02-12 10:34:29 +00001026 return isLegalUse(AM, Kind, AccessTy, TLI);
Dan Gohman7979b722010-01-22 00:46:49 +00001027}
1028
Dan Gohman572645c2010-02-12 10:34:29 +00001029static bool isAlwaysFoldable(const SCEV *S,
1030 int64_t MinOffset, int64_t MaxOffset,
1031 bool HasBaseReg,
1032 LSRUse::KindType Kind, const Type *AccessTy,
1033 const TargetLowering *TLI,
1034 ScalarEvolution &SE) {
1035 // Fast-path: zero is always foldable.
1036 if (S->isZero()) return true;
1037
1038 // Conservatively, create an address with an immediate and a
1039 // base and a scale.
1040 int64_t BaseOffs = ExtractImmediate(S, SE);
1041 GlobalValue *BaseGV = ExtractSymbol(S, SE);
1042
1043 // If there's anything else involved, it's not foldable.
1044 if (!S->isZero()) return false;
1045
1046 // Fast-path: zero is always foldable.
1047 if (BaseOffs == 0 && !BaseGV) return true;
1048
1049 // Conservatively, create an address with an immediate and a
1050 // base and a scale.
1051 TargetLowering::AddrMode AM;
1052 AM.BaseOffs = BaseOffs;
1053 AM.BaseGV = BaseGV;
1054 AM.HasBaseReg = HasBaseReg;
1055 AM.Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1056
1057 return isLegalUse(AM, MinOffset, MaxOffset, Kind, AccessTy, TLI);
Dan Gohman7979b722010-01-22 00:46:49 +00001058}
1059
Dan Gohman572645c2010-02-12 10:34:29 +00001060/// FormulaSorter - This class implements an ordering for formulae which sorts
1061/// the by their standalone cost.
1062class FormulaSorter {
1063 /// These two sets are kept empty, so that we compute standalone costs.
1064 DenseSet<const SCEV *> VisitedRegs;
1065 SmallPtrSet<const SCEV *, 16> Regs;
1066 Loop *L;
1067 LSRUse *LU;
1068 ScalarEvolution &SE;
1069 DominatorTree &DT;
1070
1071public:
1072 FormulaSorter(Loop *l, LSRUse &lu, ScalarEvolution &se, DominatorTree &dt)
1073 : L(l), LU(&lu), SE(se), DT(dt) {}
1074
1075 bool operator()(const Formula &A, const Formula &B) {
1076 Cost CostA;
1077 CostA.RateFormula(A, Regs, VisitedRegs, L, LU->Offsets, SE, DT);
1078 Regs.clear();
1079 Cost CostB;
1080 CostB.RateFormula(B, Regs, VisitedRegs, L, LU->Offsets, SE, DT);
1081 Regs.clear();
1082 return CostA < CostB;
1083 }
1084};
1085
1086/// LSRInstance - This class holds state for the main loop strength reduction
1087/// logic.
1088class LSRInstance {
1089 IVUsers &IU;
1090 ScalarEvolution &SE;
1091 DominatorTree &DT;
1092 const TargetLowering *const TLI;
1093 Loop *const L;
1094 bool Changed;
1095
1096 /// IVIncInsertPos - This is the insert position that the current loop's
1097 /// induction variable increment should be placed. In simple loops, this is
1098 /// the latch block's terminator. But in more complicated cases, this is a
1099 /// position which will dominate all the in-loop post-increment users.
1100 Instruction *IVIncInsertPos;
1101
1102 /// Factors - Interesting factors between use strides.
1103 SmallSetVector<int64_t, 8> Factors;
1104
1105 /// Types - Interesting use types, to facilitate truncation reuse.
1106 SmallSetVector<const Type *, 4> Types;
1107
1108 /// Fixups - The list of operands which are to be replaced.
1109 SmallVector<LSRFixup, 16> Fixups;
1110
1111 /// Uses - The list of interesting uses.
1112 SmallVector<LSRUse, 16> Uses;
1113
1114 /// RegUses - Track which uses use which register candidates.
1115 RegUseTracker RegUses;
1116
1117 void OptimizeShadowIV();
1118 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse);
1119 ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse);
1120 bool OptimizeLoopTermCond();
1121
1122 void CollectInterestingTypesAndFactors();
1123 void CollectFixupsAndInitialFormulae();
1124
1125 LSRFixup &getNewFixup() {
1126 Fixups.push_back(LSRFixup());
1127 return Fixups.back();
1128 }
1129
1130 // Support for sharing of LSRUses between LSRFixups.
1131 typedef DenseMap<const SCEV *, size_t> UseMapTy;
1132 UseMapTy UseMap;
1133
1134 bool reconcileNewOffset(LSRUse &LU, int64_t NewOffset,
1135 LSRUse::KindType Kind, const Type *AccessTy);
1136
1137 std::pair<size_t, int64_t> getUse(const SCEV *&Expr,
1138 LSRUse::KindType Kind,
1139 const Type *AccessTy);
1140
1141public:
1142 void InsertInitialFormula(const SCEV *S, Loop *L, LSRUse &LU, size_t LUIdx);
1143 void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
1144 void CountRegisters(const Formula &F, size_t LUIdx);
1145 bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F);
1146
1147 void CollectLoopInvariantFixupsAndFormulae();
1148
1149 void GenerateReassociations(LSRUse &LU, unsigned LUIdx, Formula Base,
1150 unsigned Depth = 0);
1151 void GenerateCombinations(LSRUse &LU, unsigned LUIdx, Formula Base);
1152 void GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1153 void GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1154 void GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1155 void GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1156 void GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base);
1157 void GenerateCrossUseConstantOffsets();
1158 void GenerateAllReuseFormulae();
1159
1160 void FilterOutUndesirableDedicatedRegisters();
1161 void NarrowSearchSpaceUsingHeuristics();
1162
1163 void SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
1164 Cost &SolutionCost,
1165 SmallVectorImpl<const Formula *> &Workspace,
1166 const Cost &CurCost,
1167 const SmallPtrSet<const SCEV *, 16> &CurRegs,
1168 DenseSet<const SCEV *> &VisitedRegs) const;
1169 void Solve(SmallVectorImpl<const Formula *> &Solution) const;
1170
1171 Value *Expand(const LSRFixup &LF,
1172 const Formula &F,
1173 BasicBlock::iterator IP, Loop *L, Instruction *IVIncInsertPos,
1174 SCEVExpander &Rewriter,
1175 SmallVectorImpl<WeakVH> &DeadInsts,
1176 ScalarEvolution &SE, DominatorTree &DT) const;
1177 void Rewrite(const LSRFixup &LF,
1178 const Formula &F,
1179 Loop *L, Instruction *IVIncInsertPos,
1180 SCEVExpander &Rewriter,
1181 SmallVectorImpl<WeakVH> &DeadInsts,
1182 ScalarEvolution &SE, DominatorTree &DT,
1183 Pass *P) const;
1184 void ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
1185 Pass *P);
1186
1187 LSRInstance(const TargetLowering *tli, Loop *l, Pass *P);
1188
1189 bool getChanged() const { return Changed; }
1190
1191 void print_factors_and_types(raw_ostream &OS) const;
1192 void print_fixups(raw_ostream &OS) const;
1193 void print_uses(raw_ostream &OS) const;
1194 void print(raw_ostream &OS) const;
1195 void dump() const;
1196};
1197
1198}
1199
1200/// OptimizeShadowIV - If IV is used in a int-to-float cast
1201/// inside the loop then try to eliminate the cast opeation.
1202void LSRInstance::OptimizeShadowIV() {
1203 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
1204 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1205 return;
1206
1207 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end();
1208 UI != E; /* empty */) {
1209 IVUsers::const_iterator CandidateUI = UI;
1210 ++UI;
1211 Instruction *ShadowUse = CandidateUI->getUser();
1212 const Type *DestTy = NULL;
1213
1214 /* If shadow use is a int->float cast then insert a second IV
1215 to eliminate this cast.
1216
1217 for (unsigned i = 0; i < n; ++i)
1218 foo((double)i);
1219
1220 is transformed into
1221
1222 double d = 0.0;
1223 for (unsigned i = 0; i < n; ++i, ++d)
1224 foo(d);
1225 */
1226 if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser()))
1227 DestTy = UCast->getDestTy();
1228 else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser()))
1229 DestTy = SCast->getDestTy();
1230 if (!DestTy) continue;
1231
1232 if (TLI) {
1233 // If target does not support DestTy natively then do not apply
1234 // this transformation.
1235 EVT DVT = TLI->getValueType(DestTy);
1236 if (!TLI->isTypeLegal(DVT)) continue;
1237 }
1238
1239 PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
1240 if (!PH) continue;
1241 if (PH->getNumIncomingValues() != 2) continue;
1242
1243 const Type *SrcTy = PH->getType();
1244 int Mantissa = DestTy->getFPMantissaWidth();
1245 if (Mantissa == -1) continue;
1246 if ((int)SE.getTypeSizeInBits(SrcTy) > Mantissa)
1247 continue;
1248
1249 unsigned Entry, Latch;
1250 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
1251 Entry = 0;
1252 Latch = 1;
Dan Gohman7979b722010-01-22 00:46:49 +00001253 } else {
Dan Gohman572645c2010-02-12 10:34:29 +00001254 Entry = 1;
1255 Latch = 0;
Dan Gohman7979b722010-01-22 00:46:49 +00001256 }
Dan Gohman7979b722010-01-22 00:46:49 +00001257
Dan Gohman572645c2010-02-12 10:34:29 +00001258 ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
1259 if (!Init) continue;
1260 Constant *NewInit = ConstantFP::get(DestTy, Init->getZExtValue());
Dan Gohman7979b722010-01-22 00:46:49 +00001261
Dan Gohman572645c2010-02-12 10:34:29 +00001262 BinaryOperator *Incr =
1263 dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
1264 if (!Incr) continue;
1265 if (Incr->getOpcode() != Instruction::Add
1266 && Incr->getOpcode() != Instruction::Sub)
Dan Gohman7979b722010-01-22 00:46:49 +00001267 continue;
Dan Gohman7979b722010-01-22 00:46:49 +00001268
Dan Gohman572645c2010-02-12 10:34:29 +00001269 /* Initialize new IV, double d = 0.0 in above example. */
1270 ConstantInt *C = NULL;
1271 if (Incr->getOperand(0) == PH)
1272 C = dyn_cast<ConstantInt>(Incr->getOperand(1));
1273 else if (Incr->getOperand(1) == PH)
1274 C = dyn_cast<ConstantInt>(Incr->getOperand(0));
Dan Gohman7979b722010-01-22 00:46:49 +00001275 else
Dan Gohman7979b722010-01-22 00:46:49 +00001276 continue;
1277
Dan Gohman572645c2010-02-12 10:34:29 +00001278 if (!C) continue;
Dan Gohman7979b722010-01-22 00:46:49 +00001279
Dan Gohman572645c2010-02-12 10:34:29 +00001280 // Ignore negative constants, as the code below doesn't handle them
1281 // correctly. TODO: Remove this restriction.
1282 if (!C->getValue().isStrictlyPositive()) continue;
Dan Gohman7979b722010-01-22 00:46:49 +00001283
Dan Gohman572645c2010-02-12 10:34:29 +00001284 /* Add new PHINode. */
1285 PHINode *NewPH = PHINode::Create(DestTy, "IV.S.", PH);
Dan Gohman7979b722010-01-22 00:46:49 +00001286
Dan Gohman572645c2010-02-12 10:34:29 +00001287 /* create new increment. '++d' in above example. */
1288 Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue());
1289 BinaryOperator *NewIncr =
1290 BinaryOperator::Create(Incr->getOpcode() == Instruction::Add ?
1291 Instruction::FAdd : Instruction::FSub,
1292 NewPH, CFP, "IV.S.next.", Incr);
Dan Gohman7979b722010-01-22 00:46:49 +00001293
Dan Gohman572645c2010-02-12 10:34:29 +00001294 NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
1295 NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
Dan Gohman7979b722010-01-22 00:46:49 +00001296
Dan Gohman572645c2010-02-12 10:34:29 +00001297 /* Remove cast operation */
1298 ShadowUse->replaceAllUsesWith(NewPH);
1299 ShadowUse->eraseFromParent();
1300 break;
Dan Gohman7979b722010-01-22 00:46:49 +00001301 }
1302}
1303
1304/// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
1305/// set the IV user and stride information and return true, otherwise return
1306/// false.
Dan Gohman572645c2010-02-12 10:34:29 +00001307bool LSRInstance::FindIVUserForCond(ICmpInst *Cond,
1308 IVStrideUse *&CondUse) {
1309 for (IVUsers::iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
1310 if (UI->getUser() == Cond) {
1311 // NOTE: we could handle setcc instructions with multiple uses here, but
1312 // InstCombine does it as well for simple uses, it's not clear that it
1313 // occurs enough in real life to handle.
1314 CondUse = UI;
1315 return true;
1316 }
Dan Gohman7979b722010-01-22 00:46:49 +00001317 return false;
Evan Chengcdf43b12007-10-25 09:11:16 +00001318}
1319
Dan Gohman7979b722010-01-22 00:46:49 +00001320/// OptimizeMax - Rewrite the loop's terminating condition if it uses
1321/// a max computation.
1322///
1323/// This is a narrow solution to a specific, but acute, problem. For loops
1324/// like this:
1325///
1326/// i = 0;
1327/// do {
1328/// p[i] = 0.0;
1329/// } while (++i < n);
1330///
1331/// the trip count isn't just 'n', because 'n' might not be positive. And
1332/// unfortunately this can come up even for loops where the user didn't use
1333/// a C do-while loop. For example, seemingly well-behaved top-test loops
1334/// will commonly be lowered like this:
1335//
1336/// if (n > 0) {
1337/// i = 0;
1338/// do {
1339/// p[i] = 0.0;
1340/// } while (++i < n);
1341/// }
1342///
1343/// and then it's possible for subsequent optimization to obscure the if
1344/// test in such a way that indvars can't find it.
1345///
1346/// When indvars can't find the if test in loops like this, it creates a
1347/// max expression, which allows it to give the loop a canonical
1348/// induction variable:
1349///
1350/// i = 0;
1351/// max = n < 1 ? 1 : n;
1352/// do {
1353/// p[i] = 0.0;
1354/// } while (++i != max);
1355///
1356/// Canonical induction variables are necessary because the loop passes
1357/// are designed around them. The most obvious example of this is the
1358/// LoopInfo analysis, which doesn't remember trip count values. It
1359/// expects to be able to rediscover the trip count each time it is
Dan Gohman572645c2010-02-12 10:34:29 +00001360/// needed, and it does this using a simple analysis that only succeeds if
Dan Gohman7979b722010-01-22 00:46:49 +00001361/// the loop has a canonical induction variable.
1362///
1363/// However, when it comes time to generate code, the maximum operation
1364/// can be quite costly, especially if it's inside of an outer loop.
1365///
1366/// This function solves this problem by detecting this type of loop and
1367/// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
1368/// the instructions for the maximum computation.
1369///
Dan Gohman572645c2010-02-12 10:34:29 +00001370ICmpInst *LSRInstance::OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse) {
Dan Gohman7979b722010-01-22 00:46:49 +00001371 // Check that the loop matches the pattern we're looking for.
1372 if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
1373 Cond->getPredicate() != CmpInst::ICMP_NE)
1374 return Cond;
Dan Gohmana10756e2010-01-21 02:09:26 +00001375
Dan Gohman7979b722010-01-22 00:46:49 +00001376 SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
1377 if (!Sel || !Sel->hasOneUse()) return Cond;
Dan Gohmana10756e2010-01-21 02:09:26 +00001378
Dan Gohman572645c2010-02-12 10:34:29 +00001379 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
Dan Gohman7979b722010-01-22 00:46:49 +00001380 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1381 return Cond;
Dan Gohman572645c2010-02-12 10:34:29 +00001382 const SCEV *One = SE.getIntegerSCEV(1, BackedgeTakenCount->getType());
Dan Gohmana10756e2010-01-21 02:09:26 +00001383
Dan Gohman7979b722010-01-22 00:46:49 +00001384 // Add one to the backedge-taken count to get the trip count.
Dan Gohman572645c2010-02-12 10:34:29 +00001385 const SCEV *IterationCount = SE.getAddExpr(BackedgeTakenCount, One);
Dan Gohman7979b722010-01-22 00:46:49 +00001386
1387 // Check for a max calculation that matches the pattern.
1388 if (!isa<SCEVSMaxExpr>(IterationCount) && !isa<SCEVUMaxExpr>(IterationCount))
1389 return Cond;
1390 const SCEVNAryExpr *Max = cast<SCEVNAryExpr>(IterationCount);
Dan Gohman572645c2010-02-12 10:34:29 +00001391 if (Max != SE.getSCEV(Sel)) return Cond;
Dan Gohman7979b722010-01-22 00:46:49 +00001392
1393 // To handle a max with more than two operands, this optimization would
1394 // require additional checking and setup.
1395 if (Max->getNumOperands() != 2)
1396 return Cond;
1397
1398 const SCEV *MaxLHS = Max->getOperand(0);
1399 const SCEV *MaxRHS = Max->getOperand(1);
1400 if (!MaxLHS || MaxLHS != One) return Cond;
Dan Gohman7979b722010-01-22 00:46:49 +00001401 // Check the relevant induction variable for conformance to
1402 // the pattern.
Dan Gohman572645c2010-02-12 10:34:29 +00001403 const SCEV *IV = SE.getSCEV(Cond->getOperand(0));
Dan Gohman7979b722010-01-22 00:46:49 +00001404 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
1405 if (!AR || !AR->isAffine() ||
1406 AR->getStart() != One ||
Dan Gohman572645c2010-02-12 10:34:29 +00001407 AR->getStepRecurrence(SE) != One)
Dan Gohman7979b722010-01-22 00:46:49 +00001408 return Cond;
1409
1410 assert(AR->getLoop() == L &&
1411 "Loop condition operand is an addrec in a different loop!");
1412
1413 // Check the right operand of the select, and remember it, as it will
1414 // be used in the new comparison instruction.
1415 Value *NewRHS = 0;
Dan Gohman572645c2010-02-12 10:34:29 +00001416 if (SE.getSCEV(Sel->getOperand(1)) == MaxRHS)
Dan Gohman7979b722010-01-22 00:46:49 +00001417 NewRHS = Sel->getOperand(1);
Dan Gohman572645c2010-02-12 10:34:29 +00001418 else if (SE.getSCEV(Sel->getOperand(2)) == MaxRHS)
Dan Gohman7979b722010-01-22 00:46:49 +00001419 NewRHS = Sel->getOperand(2);
1420 if (!NewRHS) return Cond;
1421
1422 // Determine the new comparison opcode. It may be signed or unsigned,
1423 // and the original comparison may be either equality or inequality.
1424 CmpInst::Predicate Pred =
1425 isa<SCEVSMaxExpr>(Max) ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;
1426 if (Cond->getPredicate() == CmpInst::ICMP_EQ)
1427 Pred = CmpInst::getInversePredicate(Pred);
1428
1429 // Ok, everything looks ok to change the condition into an SLT or SGE and
1430 // delete the max calculation.
1431 ICmpInst *NewCond =
1432 new ICmpInst(Cond, Pred, Cond->getOperand(0), NewRHS, "scmp");
1433
1434 // Delete the max calculation instructions.
1435 Cond->replaceAllUsesWith(NewCond);
1436 CondUse->setUser(NewCond);
1437 Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
1438 Cond->eraseFromParent();
1439 Sel->eraseFromParent();
1440 if (Cmp->use_empty())
1441 Cmp->eraseFromParent();
1442 return NewCond;
Dan Gohmanad7321f2008-09-15 21:22:06 +00001443}
1444
Jim Grosbach56a1f802009-11-17 17:53:56 +00001445/// OptimizeLoopTermCond - Change loop terminating condition to use the
Evan Cheng586f69a2009-11-12 07:35:05 +00001446/// postinc iv when possible.
Dan Gohman572645c2010-02-12 10:34:29 +00001447bool
1448LSRInstance::OptimizeLoopTermCond() {
1449 SmallPtrSet<Instruction *, 4> PostIncs;
1450
Evan Cheng586f69a2009-11-12 07:35:05 +00001451 BasicBlock *LatchBlock = L->getLoopLatch();
Evan Cheng076e0852009-11-17 18:10:11 +00001452 SmallVector<BasicBlock*, 8> ExitingBlocks;
1453 L->getExitingBlocks(ExitingBlocks);
Jim Grosbach56a1f802009-11-17 17:53:56 +00001454
Evan Cheng076e0852009-11-17 18:10:11 +00001455 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
1456 BasicBlock *ExitingBlock = ExitingBlocks[i];
Evan Cheng586f69a2009-11-12 07:35:05 +00001457
Dan Gohman572645c2010-02-12 10:34:29 +00001458 // Get the terminating condition for the loop if possible. If we
Evan Cheng076e0852009-11-17 18:10:11 +00001459 // can, we want to change it to use a post-incremented version of its
1460 // induction variable, to allow coalescing the live ranges for the IV into
1461 // one register value.
Evan Cheng586f69a2009-11-12 07:35:05 +00001462
Evan Cheng076e0852009-11-17 18:10:11 +00001463 BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1464 if (!TermBr)
1465 continue;
1466 // FIXME: Overly conservative, termination condition could be an 'or' etc..
1467 if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
1468 continue;
Evan Cheng586f69a2009-11-12 07:35:05 +00001469
Evan Cheng076e0852009-11-17 18:10:11 +00001470 // Search IVUsesByStride to find Cond's IVUse if there is one.
1471 IVStrideUse *CondUse = 0;
Evan Cheng076e0852009-11-17 18:10:11 +00001472 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
Dan Gohman572645c2010-02-12 10:34:29 +00001473 if (!FindIVUserForCond(Cond, CondUse))
Evan Cheng076e0852009-11-17 18:10:11 +00001474 continue;
1475
Evan Cheng076e0852009-11-17 18:10:11 +00001476 // If the trip count is computed in terms of a max (due to ScalarEvolution
1477 // being unable to find a sufficient guard, for example), change the loop
1478 // comparison to use SLT or ULT instead of NE.
Dan Gohman572645c2010-02-12 10:34:29 +00001479 // One consequence of doing this now is that it disrupts the count-down
1480 // optimization. That's not always a bad thing though, because in such
1481 // cases it may still be worthwhile to avoid a max.
1482 Cond = OptimizeMax(Cond, CondUse);
Evan Cheng076e0852009-11-17 18:10:11 +00001483
Dan Gohman572645c2010-02-12 10:34:29 +00001484 // If this exiting block dominates the latch block, it may also use
1485 // the post-inc value if it won't be shared with other uses.
1486 // Check for dominance.
1487 if (!DT.dominates(ExitingBlock, LatchBlock))
Dan Gohman7979b722010-01-22 00:46:49 +00001488 continue;
Evan Cheng076e0852009-11-17 18:10:11 +00001489
Dan Gohman572645c2010-02-12 10:34:29 +00001490 // Conservatively avoid trying to use the post-inc value in non-latch
1491 // exits if there may be pre-inc users in intervening blocks.
1492 if (LatchBlock != ExitingBlock)
1493 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
1494 // Test if the use is reachable from the exiting block. This dominator
1495 // query is a conservative approximation of reachability.
1496 if (&*UI != CondUse &&
1497 !DT.properlyDominates(UI->getUser()->getParent(), ExitingBlock)) {
1498 // Conservatively assume there may be reuse if the quotient of their
1499 // strides could be a legal scale.
1500 const SCEV *A = CondUse->getStride();
1501 const SCEV *B = UI->getStride();
1502 if (SE.getTypeSizeInBits(A->getType()) !=
1503 SE.getTypeSizeInBits(B->getType())) {
1504 if (SE.getTypeSizeInBits(A->getType()) >
1505 SE.getTypeSizeInBits(B->getType()))
1506 B = SE.getSignExtendExpr(B, A->getType());
1507 else
1508 A = SE.getSignExtendExpr(A, B->getType());
1509 }
1510 if (const SCEVConstant *D =
1511 dyn_cast_or_null<SCEVConstant>(getSDiv(B, A, SE))) {
1512 // Stride of one or negative one can have reuse with non-addresses.
1513 if (D->getValue()->isOne() ||
1514 D->getValue()->isAllOnesValue())
1515 goto decline_post_inc;
1516 // Avoid weird situations.
1517 if (D->getValue()->getValue().getMinSignedBits() >= 64 ||
1518 D->getValue()->getValue().isMinSignedValue())
1519 goto decline_post_inc;
1520 // Check for possible scaled-address reuse.
1521 const Type *AccessTy = getAccessType(UI->getUser());
1522 TargetLowering::AddrMode AM;
1523 AM.Scale = D->getValue()->getSExtValue();
1524 if (TLI->isLegalAddressingMode(AM, AccessTy))
1525 goto decline_post_inc;
1526 AM.Scale = -AM.Scale;
1527 if (TLI->isLegalAddressingMode(AM, AccessTy))
1528 goto decline_post_inc;
1529 }
1530 }
1531
David Greene63c94632009-12-23 22:58:38 +00001532 DEBUG(dbgs() << " Change loop exiting icmp to use postinc iv: "
Dan Gohman572645c2010-02-12 10:34:29 +00001533 << *Cond << '\n');
Evan Cheng076e0852009-11-17 18:10:11 +00001534
1535 // It's possible for the setcc instruction to be anywhere in the loop, and
1536 // possible for it to have multiple users. If it is not immediately before
1537 // the exiting block branch, move it.
Dan Gohman572645c2010-02-12 10:34:29 +00001538 if (&*++BasicBlock::iterator(Cond) != TermBr) {
1539 if (Cond->hasOneUse()) {
Evan Cheng076e0852009-11-17 18:10:11 +00001540 Cond->moveBefore(TermBr);
1541 } else {
Dan Gohman572645c2010-02-12 10:34:29 +00001542 // Clone the terminating condition and insert into the loopend.
1543 ICmpInst *OldCond = Cond;
Evan Cheng076e0852009-11-17 18:10:11 +00001544 Cond = cast<ICmpInst>(Cond->clone());
1545 Cond->setName(L->getHeader()->getName() + ".termcond");
1546 ExitingBlock->getInstList().insert(TermBr, Cond);
1547
1548 // Clone the IVUse, as the old use still exists!
Dan Gohman572645c2010-02-12 10:34:29 +00001549 CondUse = &IU.AddUser(CondUse->getStride(), CondUse->getOffset(),
1550 Cond, CondUse->getOperandValToReplace());
1551 TermBr->replaceUsesOfWith(OldCond, Cond);
Evan Cheng076e0852009-11-17 18:10:11 +00001552 }
Evan Cheng586f69a2009-11-12 07:35:05 +00001553 }
1554
Evan Cheng076e0852009-11-17 18:10:11 +00001555 // If we get to here, we know that we can transform the setcc instruction to
1556 // use the post-incremented version of the IV, allowing us to coalesce the
1557 // live ranges for the IV correctly.
Dan Gohman572645c2010-02-12 10:34:29 +00001558 CondUse->setOffset(SE.getMinusSCEV(CondUse->getOffset(),
1559 CondUse->getStride()));
Evan Cheng076e0852009-11-17 18:10:11 +00001560 CondUse->setIsUseOfPostIncrementedValue(true);
1561 Changed = true;
1562
Dan Gohman572645c2010-02-12 10:34:29 +00001563 PostIncs.insert(Cond);
1564 decline_post_inc:;
Dan Gohmana10756e2010-01-21 02:09:26 +00001565 }
Dan Gohman572645c2010-02-12 10:34:29 +00001566
1567 // Determine an insertion point for the loop induction variable increment. It
1568 // must dominate all the post-inc comparisons we just set up, and it must
1569 // dominate the loop latch edge.
1570 IVIncInsertPos = L->getLoopLatch()->getTerminator();
1571 for (SmallPtrSet<Instruction *, 4>::const_iterator I = PostIncs.begin(),
1572 E = PostIncs.end(); I != E; ++I) {
1573 BasicBlock *BB =
1574 DT.findNearestCommonDominator(IVIncInsertPos->getParent(),
1575 (*I)->getParent());
1576 if (BB == (*I)->getParent())
1577 IVIncInsertPos = *I;
1578 else if (BB != IVIncInsertPos->getParent())
1579 IVIncInsertPos = BB->getTerminator();
1580 }
1581
1582 return Changed;
Dan Gohmana10756e2010-01-21 02:09:26 +00001583}
1584
Dan Gohman572645c2010-02-12 10:34:29 +00001585bool
1586LSRInstance::reconcileNewOffset(LSRUse &LU, int64_t NewOffset,
1587 LSRUse::KindType Kind, const Type *AccessTy) {
1588 int64_t NewMinOffset = LU.MinOffset;
1589 int64_t NewMaxOffset = LU.MaxOffset;
1590 const Type *NewAccessTy = AccessTy;
Dan Gohman7979b722010-01-22 00:46:49 +00001591
Dan Gohman572645c2010-02-12 10:34:29 +00001592 // Check for a mismatched kind. It's tempting to collapse mismatched kinds to
1593 // something conservative, however this can pessimize in the case that one of
1594 // the uses will have all its uses outside the loop, for example.
1595 if (LU.Kind != Kind)
Dan Gohman7979b722010-01-22 00:46:49 +00001596 return false;
Dan Gohman572645c2010-02-12 10:34:29 +00001597 // Conservatively assume HasBaseReg is true for now.
1598 if (NewOffset < LU.MinOffset) {
1599 if (!isAlwaysFoldable(LU.MaxOffset - NewOffset, 0, /*HasBaseReg=*/true,
1600 Kind, AccessTy, TLI, SE))
Dan Gohman7979b722010-01-22 00:46:49 +00001601 return false;
Dan Gohman572645c2010-02-12 10:34:29 +00001602 NewMinOffset = NewOffset;
1603 } else if (NewOffset > LU.MaxOffset) {
1604 if (!isAlwaysFoldable(NewOffset - LU.MinOffset, 0, /*HasBaseReg=*/true,
1605 Kind, AccessTy, TLI, SE))
Dan Gohman7979b722010-01-22 00:46:49 +00001606 return false;
Dan Gohman572645c2010-02-12 10:34:29 +00001607 NewMaxOffset = NewOffset;
Dan Gohmana10756e2010-01-21 02:09:26 +00001608 }
Dan Gohman572645c2010-02-12 10:34:29 +00001609 // Check for a mismatched access type, and fall back conservatively as needed.
1610 if (Kind == LSRUse::Address && AccessTy != LU.AccessTy)
1611 NewAccessTy = Type::getVoidTy(AccessTy->getContext());
Dan Gohmana10756e2010-01-21 02:09:26 +00001612
Dan Gohman572645c2010-02-12 10:34:29 +00001613 // Update the use.
1614 LU.MinOffset = NewMinOffset;
1615 LU.MaxOffset = NewMaxOffset;
1616 LU.AccessTy = NewAccessTy;
1617 if (NewOffset != LU.Offsets.back())
1618 LU.Offsets.push_back(NewOffset);
Dan Gohman8b0ade32010-01-21 22:42:49 +00001619 return true;
1620}
1621
Dan Gohman572645c2010-02-12 10:34:29 +00001622/// getUse - Return an LSRUse index and an offset value for a fixup which
1623/// needs the given expression, with the given kind and optional access type.
1624/// Either reuse an exisitng use or create a new one, as needed.
1625std::pair<size_t, int64_t>
1626LSRInstance::getUse(const SCEV *&Expr,
1627 LSRUse::KindType Kind, const Type *AccessTy) {
1628 const SCEV *Copy = Expr;
1629 int64_t Offset = ExtractImmediate(Expr, SE);
Evan Cheng586f69a2009-11-12 07:35:05 +00001630
Dan Gohman572645c2010-02-12 10:34:29 +00001631 // Basic uses can't accept any offset, for example.
1632 if (!isAlwaysFoldable(Offset, 0, /*HasBaseReg=*/true,
1633 Kind, AccessTy, TLI, SE)) {
1634 Expr = Copy;
1635 Offset = 0;
1636 }
1637
1638 std::pair<UseMapTy::iterator, bool> P =
1639 UseMap.insert(std::make_pair(Expr, 0));
1640 if (!P.second) {
1641 // A use already existed with this base.
1642 size_t LUIdx = P.first->second;
1643 LSRUse &LU = Uses[LUIdx];
1644 if (reconcileNewOffset(LU, Offset, Kind, AccessTy))
1645 // Reuse this use.
1646 return std::make_pair(LUIdx, Offset);
1647 }
1648
1649 // Create a new use.
1650 size_t LUIdx = Uses.size();
1651 P.first->second = LUIdx;
1652 Uses.push_back(LSRUse(Kind, AccessTy));
1653 LSRUse &LU = Uses[LUIdx];
1654
1655 // We don't need to track redundant offsets, but we don't need to go out
1656 // of our way here to avoid them.
1657 if (LU.Offsets.empty() || Offset != LU.Offsets.back())
1658 LU.Offsets.push_back(Offset);
1659
1660 LU.MinOffset = Offset;
1661 LU.MaxOffset = Offset;
1662 return std::make_pair(LUIdx, Offset);
1663}
1664
1665void LSRInstance::CollectInterestingTypesAndFactors() {
1666 SmallSetVector<const SCEV *, 4> Strides;
1667
1668 // Collect interesting types and factors.
1669 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
1670 const SCEV *Stride = UI->getStride();
1671
1672 // Collect interesting types.
1673 Types.insert(SE.getEffectiveSCEVType(Stride->getType()));
1674
1675 // Collect interesting factors.
1676 for (SmallSetVector<const SCEV *, 4>::const_iterator NewStrideIter =
1677 Strides.begin(), SEnd = Strides.end(); NewStrideIter != SEnd;
1678 ++NewStrideIter) {
1679 const SCEV *OldStride = Stride;
1680 const SCEV *NewStride = *NewStrideIter;
1681 if (OldStride == NewStride)
1682 continue;
1683
1684 if (SE.getTypeSizeInBits(OldStride->getType()) !=
1685 SE.getTypeSizeInBits(NewStride->getType())) {
1686 if (SE.getTypeSizeInBits(OldStride->getType()) >
1687 SE.getTypeSizeInBits(NewStride->getType()))
1688 NewStride = SE.getSignExtendExpr(NewStride, OldStride->getType());
1689 else
1690 OldStride = SE.getSignExtendExpr(OldStride, NewStride->getType());
1691 }
1692 if (const SCEVConstant *Factor =
1693 dyn_cast_or_null<SCEVConstant>(getSDiv(NewStride, OldStride,
1694 SE, true))) {
1695 if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
1696 Factors.insert(Factor->getValue()->getValue().getSExtValue());
1697 } else if (const SCEVConstant *Factor =
1698 dyn_cast_or_null<SCEVConstant>(getSDiv(OldStride, NewStride,
1699 SE, true))) {
1700 if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
1701 Factors.insert(Factor->getValue()->getValue().getSExtValue());
1702 }
1703 }
1704 Strides.insert(Stride);
1705 }
1706
1707 // If all uses use the same type, don't bother looking for truncation-based
1708 // reuse.
1709 if (Types.size() == 1)
1710 Types.clear();
1711
1712 DEBUG(print_factors_and_types(dbgs()));
1713}
1714
1715void LSRInstance::CollectFixupsAndInitialFormulae() {
1716 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
1717 // Record the uses.
1718 LSRFixup &LF = getNewFixup();
1719 LF.UserInst = UI->getUser();
1720 LF.OperandValToReplace = UI->getOperandValToReplace();
1721 if (UI->isUseOfPostIncrementedValue())
1722 LF.PostIncLoop = L;
1723
1724 LSRUse::KindType Kind = LSRUse::Basic;
1725 const Type *AccessTy = 0;
1726 if (isAddressUse(LF.UserInst, LF.OperandValToReplace)) {
1727 Kind = LSRUse::Address;
1728 AccessTy = getAccessType(LF.UserInst);
1729 }
1730
1731 const SCEV *S = IU.getCanonicalExpr(*UI);
1732
1733 // Equality (== and !=) ICmps are special. We can rewrite (i == N) as
1734 // (N - i == 0), and this allows (N - i) to be the expression that we work
1735 // with rather than just N or i, so we can consider the register
1736 // requirements for both N and i at the same time. Limiting this code to
1737 // equality icmps is not a problem because all interesting loops use
1738 // equality icmps, thanks to IndVarSimplify.
1739 if (ICmpInst *CI = dyn_cast<ICmpInst>(LF.UserInst))
1740 if (CI->isEquality()) {
1741 // Swap the operands if needed to put the OperandValToReplace on the
1742 // left, for consistency.
1743 Value *NV = CI->getOperand(1);
1744 if (NV == LF.OperandValToReplace) {
1745 CI->setOperand(1, CI->getOperand(0));
1746 CI->setOperand(0, NV);
1747 }
1748
1749 // x == y --> x - y == 0
1750 const SCEV *N = SE.getSCEV(NV);
1751 if (N->isLoopInvariant(L)) {
1752 Kind = LSRUse::ICmpZero;
1753 S = SE.getMinusSCEV(N, S);
1754 }
1755
1756 // -1 and the negations of all interesting strides (except the negation
1757 // of -1) are now also interesting.
1758 for (size_t i = 0, e = Factors.size(); i != e; ++i)
1759 if (Factors[i] != -1)
1760 Factors.insert(-(uint64_t)Factors[i]);
1761 Factors.insert(-1);
1762 }
1763
1764 // Set up the initial formula for this use.
1765 std::pair<size_t, int64_t> P = getUse(S, Kind, AccessTy);
1766 LF.LUIdx = P.first;
1767 LF.Offset = P.second;
1768 LSRUse &LU = Uses[LF.LUIdx];
1769 LU.AllFixupsOutsideLoop &= !L->contains(LF.UserInst);
1770
1771 // If this is the first use of this LSRUse, give it a formula.
1772 if (LU.Formulae.empty()) {
1773 InsertInitialFormula(S, L, LU, LF.LUIdx);
1774 CountRegisters(LU.Formulae.back(), LF.LUIdx);
1775 }
1776 }
1777
1778 DEBUG(print_fixups(dbgs()));
1779}
1780
1781void
1782LSRInstance::InsertInitialFormula(const SCEV *S, Loop *L,
1783 LSRUse &LU, size_t LUIdx) {
1784 Formula F;
1785 F.InitialMatch(S, L, SE, DT);
1786 bool Inserted = InsertFormula(LU, LUIdx, F);
1787 assert(Inserted && "Initial formula already exists!"); (void)Inserted;
1788}
1789
1790void
1791LSRInstance::InsertSupplementalFormula(const SCEV *S,
1792 LSRUse &LU, size_t LUIdx) {
1793 Formula F;
1794 F.BaseRegs.push_back(S);
1795 F.AM.HasBaseReg = true;
1796 bool Inserted = InsertFormula(LU, LUIdx, F);
1797 assert(Inserted && "Supplemental formula already exists!"); (void)Inserted;
1798}
1799
1800/// CountRegisters - Note which registers are used by the given formula,
1801/// updating RegUses.
1802void LSRInstance::CountRegisters(const Formula &F, size_t LUIdx) {
1803 if (F.ScaledReg)
1804 RegUses.CountRegister(F.ScaledReg, LUIdx);
1805 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
1806 E = F.BaseRegs.end(); I != E; ++I)
1807 RegUses.CountRegister(*I, LUIdx);
1808}
1809
1810/// InsertFormula - If the given formula has not yet been inserted, add it to
1811/// the list, and return true. Return false otherwise.
1812bool LSRInstance::InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F) {
1813 if (!LU.InsertFormula(LUIdx, F))
1814 return false;
1815
1816 CountRegisters(F, LUIdx);
1817 return true;
1818}
1819
1820/// CollectLoopInvariantFixupsAndFormulae - Check for other uses of
1821/// loop-invariant values which we're tracking. These other uses will pin these
1822/// values in registers, making them less profitable for elimination.
1823/// TODO: This currently misses non-constant addrec step registers.
1824/// TODO: Should this give more weight to users inside the loop?
1825void
1826LSRInstance::CollectLoopInvariantFixupsAndFormulae() {
1827 SmallVector<const SCEV *, 8> Worklist(RegUses.begin(), RegUses.end());
1828 SmallPtrSet<const SCEV *, 8> Inserted;
1829
1830 while (!Worklist.empty()) {
1831 const SCEV *S = Worklist.pop_back_val();
1832
1833 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S))
1834 Worklist.insert(Worklist.end(), N->op_begin(), N->op_end());
1835 else if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
1836 Worklist.push_back(C->getOperand());
1837 else if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
1838 Worklist.push_back(D->getLHS());
1839 Worklist.push_back(D->getRHS());
1840 } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
1841 if (!Inserted.insert(U)) continue;
1842 const Value *V = U->getValue();
1843 if (const Instruction *Inst = dyn_cast<Instruction>(V))
1844 if (L->contains(Inst)) continue;
1845 for (Value::use_const_iterator UI = V->use_begin(), UE = V->use_end();
1846 UI != UE; ++UI) {
1847 const Instruction *UserInst = dyn_cast<Instruction>(*UI);
1848 // Ignore non-instructions.
1849 if (!UserInst)
Dan Gohman7979b722010-01-22 00:46:49 +00001850 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00001851 // Ignore instructions in other functions (as can happen with
1852 // Constants).
1853 if (UserInst->getParent()->getParent() != L->getHeader()->getParent())
Dan Gohman7979b722010-01-22 00:46:49 +00001854 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00001855 // Ignore instructions not dominated by the loop.
1856 const BasicBlock *UseBB = !isa<PHINode>(UserInst) ?
1857 UserInst->getParent() :
1858 cast<PHINode>(UserInst)->getIncomingBlock(
1859 PHINode::getIncomingValueNumForOperand(UI.getOperandNo()));
1860 if (!DT.dominates(L->getHeader(), UseBB))
1861 continue;
1862 // Ignore uses which are part of other SCEV expressions, to avoid
1863 // analyzing them multiple times.
1864 if (SE.isSCEVable(UserInst->getType()) &&
1865 !isa<SCEVUnknown>(SE.getSCEV(const_cast<Instruction *>(UserInst))))
1866 continue;
1867 // Ignore icmp instructions which are already being analyzed.
1868 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) {
1869 unsigned OtherIdx = !UI.getOperandNo();
1870 Value *OtherOp = const_cast<Value *>(ICI->getOperand(OtherIdx));
1871 if (SE.getSCEV(OtherOp)->hasComputableLoopEvolution(L))
1872 continue;
1873 }
1874
1875 LSRFixup &LF = getNewFixup();
1876 LF.UserInst = const_cast<Instruction *>(UserInst);
1877 LF.OperandValToReplace = UI.getUse();
1878 std::pair<size_t, int64_t> P = getUse(S, LSRUse::Basic, 0);
1879 LF.LUIdx = P.first;
1880 LF.Offset = P.second;
1881 LSRUse &LU = Uses[LF.LUIdx];
1882 LU.AllFixupsOutsideLoop &= L->contains(LF.UserInst);
1883 InsertSupplementalFormula(U, LU, LF.LUIdx);
1884 CountRegisters(LU.Formulae.back(), Uses.size() - 1);
1885 break;
1886 }
1887 }
1888 }
1889}
1890
1891/// CollectSubexprs - Split S into subexpressions which can be pulled out into
1892/// separate registers. If C is non-null, multiply each subexpression by C.
1893static void CollectSubexprs(const SCEV *S, const SCEVConstant *C,
1894 SmallVectorImpl<const SCEV *> &Ops,
1895 ScalarEvolution &SE) {
1896 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
1897 // Break out add operands.
1898 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1899 I != E; ++I)
1900 CollectSubexprs(*I, C, Ops, SE);
1901 return;
1902 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
1903 // Split a non-zero base out of an addrec.
1904 if (!AR->getStart()->isZero()) {
Daniel Dunbarae086252010-02-12 17:27:08 +00001905 CollectSubexprs(AR->getStart(), C, Ops, SE);
Dan Gohman572645c2010-02-12 10:34:29 +00001906 CollectSubexprs(SE.getAddRecExpr(SE.getIntegerSCEV(0, AR->getType()),
1907 AR->getStepRecurrence(SE),
1908 AR->getLoop()), C, Ops, SE);
1909 return;
1910 }
1911 } else if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
1912 // Break (C * (a + b + c)) into C*a + C*b + C*c.
1913 if (Mul->getNumOperands() == 2)
1914 if (const SCEVConstant *Op0 =
1915 dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
1916 CollectSubexprs(Mul->getOperand(1),
1917 C ? cast<SCEVConstant>(SE.getMulExpr(C, Op0)) : Op0,
1918 Ops, SE);
1919 return;
1920 }
1921 }
1922
1923 // Otherwise use the value itself.
1924 Ops.push_back(C ? SE.getMulExpr(C, S) : S);
1925}
1926
1927/// GenerateReassociations - Split out subexpressions from adds and the bases of
1928/// addrecs.
1929void LSRInstance::GenerateReassociations(LSRUse &LU, unsigned LUIdx,
1930 Formula Base,
1931 unsigned Depth) {
1932 // Arbitrarily cap recursion to protect compile time.
1933 if (Depth >= 3) return;
1934
1935 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
1936 const SCEV *BaseReg = Base.BaseRegs[i];
1937
1938 SmallVector<const SCEV *, 8> AddOps;
1939 CollectSubexprs(BaseReg, 0, AddOps, SE);
1940 if (AddOps.size() == 1) continue;
1941
1942 for (SmallVectorImpl<const SCEV *>::const_iterator J = AddOps.begin(),
1943 JE = AddOps.end(); J != JE; ++J) {
1944 // Don't pull a constant into a register if the constant could be folded
1945 // into an immediate field.
1946 if (isAlwaysFoldable(*J, LU.MinOffset, LU.MaxOffset,
1947 Base.getNumRegs() > 1,
1948 LU.Kind, LU.AccessTy, TLI, SE))
1949 continue;
1950
1951 // Collect all operands except *J.
1952 SmallVector<const SCEV *, 8> InnerAddOps;
1953 for (SmallVectorImpl<const SCEV *>::const_iterator K = AddOps.begin(),
1954 KE = AddOps.end(); K != KE; ++K)
1955 if (K != J)
1956 InnerAddOps.push_back(*K);
1957
1958 // Don't leave just a constant behind in a register if the constant could
1959 // be folded into an immediate field.
1960 if (InnerAddOps.size() == 1 &&
1961 isAlwaysFoldable(InnerAddOps[0], LU.MinOffset, LU.MaxOffset,
1962 Base.getNumRegs() > 1,
1963 LU.Kind, LU.AccessTy, TLI, SE))
1964 continue;
1965
1966 Formula F = Base;
1967 F.BaseRegs[i] = SE.getAddExpr(InnerAddOps);
1968 F.BaseRegs.push_back(*J);
1969 if (InsertFormula(LU, LUIdx, F))
1970 // If that formula hadn't been seen before, recurse to find more like
1971 // it.
1972 GenerateReassociations(LU, LUIdx, LU.Formulae.back(), Depth+1);
1973 }
1974 }
1975}
1976
1977/// GenerateCombinations - Generate a formula consisting of all of the
1978/// loop-dominating registers added into a single register.
1979void LSRInstance::GenerateCombinations(LSRUse &LU, unsigned LUIdx,
1980 Formula Base) {
1981 // This method is only intersting on a plurality of registers.
1982 if (Base.BaseRegs.size() <= 1) return;
1983
1984 Formula F = Base;
1985 F.BaseRegs.clear();
1986 SmallVector<const SCEV *, 4> Ops;
1987 for (SmallVectorImpl<const SCEV *>::const_iterator
1988 I = Base.BaseRegs.begin(), E = Base.BaseRegs.end(); I != E; ++I) {
1989 const SCEV *BaseReg = *I;
1990 if (BaseReg->properlyDominates(L->getHeader(), &DT) &&
1991 !BaseReg->hasComputableLoopEvolution(L))
1992 Ops.push_back(BaseReg);
1993 else
1994 F.BaseRegs.push_back(BaseReg);
1995 }
1996 if (Ops.size() > 1) {
1997 F.BaseRegs.push_back(SE.getAddExpr(Ops));
1998 (void)InsertFormula(LU, LUIdx, F);
1999 }
2000}
2001
2002/// GenerateSymbolicOffsets - Generate reuse formulae using symbolic offsets.
2003void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx,
2004 Formula Base) {
2005 // We can't add a symbolic offset if the address already contains one.
2006 if (Base.AM.BaseGV) return;
2007
2008 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2009 const SCEV *G = Base.BaseRegs[i];
2010 GlobalValue *GV = ExtractSymbol(G, SE);
2011 if (G->isZero() || !GV)
2012 continue;
2013 Formula F = Base;
2014 F.AM.BaseGV = GV;
2015 if (!isLegalUse(F.AM, LU.MinOffset, LU.MaxOffset,
2016 LU.Kind, LU.AccessTy, TLI))
2017 continue;
2018 F.BaseRegs[i] = G;
2019 (void)InsertFormula(LU, LUIdx, F);
2020 }
2021}
2022
2023/// GenerateConstantOffsets - Generate reuse formulae using symbolic offsets.
2024void LSRInstance::GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx,
2025 Formula Base) {
2026 // TODO: For now, just add the min and max offset, because it usually isn't
2027 // worthwhile looking at everything inbetween.
2028 SmallVector<int64_t, 4> Worklist;
2029 Worklist.push_back(LU.MinOffset);
2030 if (LU.MaxOffset != LU.MinOffset)
2031 Worklist.push_back(LU.MaxOffset);
2032
2033 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2034 const SCEV *G = Base.BaseRegs[i];
2035
2036 for (SmallVectorImpl<int64_t>::const_iterator I = Worklist.begin(),
2037 E = Worklist.end(); I != E; ++I) {
2038 Formula F = Base;
2039 F.AM.BaseOffs = (uint64_t)Base.AM.BaseOffs - *I;
2040 if (isLegalUse(F.AM, LU.MinOffset - *I, LU.MaxOffset - *I,
2041 LU.Kind, LU.AccessTy, TLI)) {
2042 F.BaseRegs[i] = SE.getAddExpr(G, SE.getIntegerSCEV(*I, G->getType()));
2043
2044 (void)InsertFormula(LU, LUIdx, F);
2045 }
2046 }
2047
2048 int64_t Imm = ExtractImmediate(G, SE);
2049 if (G->isZero() || Imm == 0)
2050 continue;
2051 Formula F = Base;
2052 F.AM.BaseOffs = (uint64_t)F.AM.BaseOffs + Imm;
2053 if (!isLegalUse(F.AM, LU.MinOffset, LU.MaxOffset,
2054 LU.Kind, LU.AccessTy, TLI))
2055 continue;
2056 F.BaseRegs[i] = G;
2057 (void)InsertFormula(LU, LUIdx, F);
2058 }
2059}
2060
2061/// GenerateICmpZeroScales - For ICmpZero, check to see if we can scale up
2062/// the comparison. For example, x == y -> x*c == y*c.
2063void LSRInstance::GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx,
2064 Formula Base) {
2065 if (LU.Kind != LSRUse::ICmpZero) return;
2066
2067 // Determine the integer type for the base formula.
2068 const Type *IntTy = Base.getType();
2069 if (!IntTy) return;
2070 if (SE.getTypeSizeInBits(IntTy) > 64) return;
2071
2072 // Don't do this if there is more than one offset.
2073 if (LU.MinOffset != LU.MaxOffset) return;
2074
2075 assert(!Base.AM.BaseGV && "ICmpZero use is not legal!");
2076
2077 // Check each interesting stride.
2078 for (SmallSetVector<int64_t, 8>::const_iterator
2079 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
2080 int64_t Factor = *I;
2081 Formula F = Base;
2082
2083 // Check that the multiplication doesn't overflow.
2084 F.AM.BaseOffs = (uint64_t)Base.AM.BaseOffs * Factor;
2085 if ((int64_t)F.AM.BaseOffs / Factor != Base.AM.BaseOffs)
2086 continue;
2087
2088 // Check that multiplying with the use offset doesn't overflow.
2089 int64_t Offset = LU.MinOffset;
2090 Offset = (uint64_t)Offset * Factor;
2091 if ((int64_t)Offset / Factor != LU.MinOffset)
2092 continue;
2093
2094 // Check that this scale is legal.
2095 if (!isLegalUse(F.AM, Offset, Offset, LU.Kind, LU.AccessTy, TLI))
2096 continue;
2097
2098 // Compensate for the use having MinOffset built into it.
2099 F.AM.BaseOffs = (uint64_t)F.AM.BaseOffs + Offset - LU.MinOffset;
2100
2101 const SCEV *FactorS = SE.getIntegerSCEV(Factor, IntTy);
2102
2103 // Check that multiplying with each base register doesn't overflow.
2104 for (size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) {
2105 F.BaseRegs[i] = SE.getMulExpr(F.BaseRegs[i], FactorS);
2106 if (getSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i])
2107 goto next;
2108 }
2109
2110 // Check that multiplying with the scaled register doesn't overflow.
2111 if (F.ScaledReg) {
2112 F.ScaledReg = SE.getMulExpr(F.ScaledReg, FactorS);
2113 if (getSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg)
2114 continue;
2115 }
2116
2117 // If we make it here and it's legal, add it.
2118 (void)InsertFormula(LU, LUIdx, F);
2119 next:;
2120 }
2121}
2122
2123/// GenerateScales - Generate stride factor reuse formulae by making use of
2124/// scaled-offset address modes, for example.
2125void LSRInstance::GenerateScales(LSRUse &LU, unsigned LUIdx,
2126 Formula Base) {
2127 // Determine the integer type for the base formula.
2128 const Type *IntTy = Base.getType();
2129 if (!IntTy) return;
2130
2131 // If this Formula already has a scaled register, we can't add another one.
2132 if (Base.AM.Scale != 0) return;
2133
2134 // Check each interesting stride.
2135 for (SmallSetVector<int64_t, 8>::const_iterator
2136 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
2137 int64_t Factor = *I;
2138
2139 Base.AM.Scale = Factor;
2140 Base.AM.HasBaseReg = Base.BaseRegs.size() > 1;
2141 // Check whether this scale is going to be legal.
2142 if (!isLegalUse(Base.AM, LU.MinOffset, LU.MaxOffset,
2143 LU.Kind, LU.AccessTy, TLI)) {
2144 // As a special-case, handle special out-of-loop Basic users specially.
2145 // TODO: Reconsider this special case.
2146 if (LU.Kind == LSRUse::Basic &&
2147 isLegalUse(Base.AM, LU.MinOffset, LU.MaxOffset,
2148 LSRUse::Special, LU.AccessTy, TLI) &&
2149 LU.AllFixupsOutsideLoop)
2150 LU.Kind = LSRUse::Special;
2151 else
2152 continue;
2153 }
2154 // For an ICmpZero, negating a solitary base register won't lead to
2155 // new solutions.
2156 if (LU.Kind == LSRUse::ICmpZero &&
2157 !Base.AM.HasBaseReg && Base.AM.BaseOffs == 0 && !Base.AM.BaseGV)
2158 continue;
2159 // For each addrec base reg, apply the scale, if possible.
2160 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
2161 if (const SCEVAddRecExpr *AR =
2162 dyn_cast<SCEVAddRecExpr>(Base.BaseRegs[i])) {
2163 const SCEV *FactorS = SE.getIntegerSCEV(Factor, IntTy);
2164 if (FactorS->isZero())
2165 continue;
2166 // Divide out the factor, ignoring high bits, since we'll be
2167 // scaling the value back up in the end.
2168 if (const SCEV *Quotient = getSDiv(AR, FactorS, SE, true)) {
2169 // TODO: This could be optimized to avoid all the copying.
2170 Formula F = Base;
2171 F.ScaledReg = Quotient;
2172 std::swap(F.BaseRegs[i], F.BaseRegs.back());
2173 F.BaseRegs.pop_back();
2174 (void)InsertFormula(LU, LUIdx, F);
2175 }
2176 }
2177 }
2178}
2179
2180/// GenerateTruncates - Generate reuse formulae from different IV types.
2181void LSRInstance::GenerateTruncates(LSRUse &LU, unsigned LUIdx,
2182 Formula Base) {
2183 // This requires TargetLowering to tell us which truncates are free.
2184 if (!TLI) return;
2185
2186 // Don't bother truncating symbolic values.
2187 if (Base.AM.BaseGV) return;
2188
2189 // Determine the integer type for the base formula.
2190 const Type *DstTy = Base.getType();
2191 if (!DstTy) return;
2192 DstTy = SE.getEffectiveSCEVType(DstTy);
2193
2194 for (SmallSetVector<const Type *, 4>::const_iterator
2195 I = Types.begin(), E = Types.end(); I != E; ++I) {
2196 const Type *SrcTy = *I;
2197 if (SrcTy != DstTy && TLI->isTruncateFree(SrcTy, DstTy)) {
2198 Formula F = Base;
2199
2200 if (F.ScaledReg) F.ScaledReg = SE.getAnyExtendExpr(F.ScaledReg, *I);
2201 for (SmallVectorImpl<const SCEV *>::iterator J = F.BaseRegs.begin(),
2202 JE = F.BaseRegs.end(); J != JE; ++J)
2203 *J = SE.getAnyExtendExpr(*J, SrcTy);
2204
2205 // TODO: This assumes we've done basic processing on all uses and
2206 // have an idea what the register usage is.
2207 if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses))
2208 continue;
2209
2210 (void)InsertFormula(LU, LUIdx, F);
2211 }
2212 }
2213}
2214
2215namespace {
2216
2217/// WorkItem - Helper class for GenerateConstantOffsetReuse. It's used to
2218/// defer modifications so that the search phase doesn't have to worry about
2219/// the data structures moving underneath it.
2220struct WorkItem {
2221 size_t LUIdx;
2222 int64_t Imm;
2223 const SCEV *OrigReg;
2224
2225 WorkItem(size_t LI, int64_t I, const SCEV *R)
2226 : LUIdx(LI), Imm(I), OrigReg(R) {}
2227
2228 void print(raw_ostream &OS) const;
2229 void dump() const;
2230};
2231
2232}
2233
2234void WorkItem::print(raw_ostream &OS) const {
2235 OS << "in formulae referencing " << *OrigReg << " in use " << LUIdx
2236 << " , add offset " << Imm;
2237}
2238
2239void WorkItem::dump() const {
2240 print(errs()); errs() << '\n';
2241}
2242
2243/// GenerateCrossUseConstantOffsets - Look for registers which are a constant
2244/// distance apart and try to form reuse opportunities between them.
2245void LSRInstance::GenerateCrossUseConstantOffsets() {
2246 // Group the registers by their value without any added constant offset.
2247 typedef std::map<int64_t, const SCEV *> ImmMapTy;
2248 typedef DenseMap<const SCEV *, ImmMapTy> RegMapTy;
2249 RegMapTy Map;
2250 DenseMap<const SCEV *, SmallBitVector> UsedByIndicesMap;
2251 SmallVector<const SCEV *, 8> Sequence;
2252 for (RegUseTracker::const_iterator I = RegUses.begin(), E = RegUses.end();
2253 I != E; ++I) {
2254 const SCEV *Reg = *I;
2255 int64_t Imm = ExtractImmediate(Reg, SE);
2256 std::pair<RegMapTy::iterator, bool> Pair =
2257 Map.insert(std::make_pair(Reg, ImmMapTy()));
2258 if (Pair.second)
2259 Sequence.push_back(Reg);
2260 Pair.first->second.insert(std::make_pair(Imm, *I));
2261 UsedByIndicesMap[Reg] |= RegUses.getUsedByIndices(*I);
2262 }
2263
2264 // Now examine each set of registers with the same base value. Build up
2265 // a list of work to do and do the work in a separate step so that we're
2266 // not adding formulae and register counts while we're searching.
2267 SmallVector<WorkItem, 32> WorkItems;
2268 SmallSet<std::pair<size_t, int64_t>, 32> UniqueItems;
2269 for (SmallVectorImpl<const SCEV *>::const_iterator I = Sequence.begin(),
2270 E = Sequence.end(); I != E; ++I) {
2271 const SCEV *Reg = *I;
2272 const ImmMapTy &Imms = Map.find(Reg)->second;
2273
2274 DEBUG(dbgs() << "Generating cross-use offsets for " << *Reg << ':';
2275 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
2276 J != JE; ++J)
2277 dbgs() << ' ' << J->first;
2278 dbgs() << '\n');
2279
2280 // Examine each offset.
2281 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
2282 J != JE; ++J) {
2283 const SCEV *OrigReg = J->second;
2284
2285 int64_t JImm = J->first;
2286 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg);
2287
2288 if (!isa<SCEVConstant>(OrigReg) &&
2289 UsedByIndicesMap[Reg].count() == 1) {
2290 DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg << '\n');
2291 continue;
2292 }
2293
2294 // Conservatively examine offsets between this orig reg a few selected
2295 // other orig regs.
2296 ImmMapTy::const_iterator OtherImms[] = {
2297 Imms.begin(), prior(Imms.end()),
2298 Imms.upper_bound((Imms.begin()->first + prior(Imms.end())->first) / 2)
2299 };
2300 for (size_t i = 0, e = array_lengthof(OtherImms); i != e; ++i) {
2301 ImmMapTy::const_iterator M = OtherImms[i];
2302 if (M == J) continue;
2303
2304 // Compute the difference between the two.
2305 int64_t Imm = (uint64_t)JImm - M->first;
2306 for (int LUIdx = UsedByIndices.find_first(); LUIdx != -1;
2307 LUIdx = UsedByIndices.find_next(LUIdx))
2308 // Make a memo of this use, offset, and register tuple.
2309 if (UniqueItems.insert(std::make_pair(LUIdx, Imm)))
2310 WorkItems.push_back(WorkItem(LUIdx, Imm, OrigReg));
Evan Cheng586f69a2009-11-12 07:35:05 +00002311 }
2312 }
2313 }
2314
Dan Gohman572645c2010-02-12 10:34:29 +00002315 Map.clear();
2316 Sequence.clear();
2317 UsedByIndicesMap.clear();
2318 UniqueItems.clear();
2319
2320 // Now iterate through the worklist and add new formulae.
2321 for (SmallVectorImpl<WorkItem>::const_iterator I = WorkItems.begin(),
2322 E = WorkItems.end(); I != E; ++I) {
2323 const WorkItem &WI = *I;
2324 size_t LUIdx = WI.LUIdx;
2325 LSRUse &LU = Uses[LUIdx];
2326 int64_t Imm = WI.Imm;
2327 const SCEV *OrigReg = WI.OrigReg;
2328
2329 const Type *IntTy = SE.getEffectiveSCEVType(OrigReg->getType());
2330 const SCEV *NegImmS = SE.getSCEV(ConstantInt::get(IntTy, -(uint64_t)Imm));
2331 unsigned BitWidth = SE.getTypeSizeInBits(IntTy);
2332
2333 // TODO: Use a more targetted data structure.
2334 for (size_t L = 0, LE = LU.Formulae.size(); L != LE; ++L) {
2335 Formula F = LU.Formulae[L];
2336 // Use the immediate in the scaled register.
2337 if (F.ScaledReg == OrigReg) {
2338 int64_t Offs = (uint64_t)F.AM.BaseOffs +
2339 Imm * (uint64_t)F.AM.Scale;
2340 // Don't create 50 + reg(-50).
2341 if (F.referencesReg(SE.getSCEV(
2342 ConstantInt::get(IntTy, -(uint64_t)Offs))))
2343 continue;
2344 Formula NewF = F;
2345 NewF.AM.BaseOffs = Offs;
2346 if (!isLegalUse(NewF.AM, LU.MinOffset, LU.MaxOffset,
2347 LU.Kind, LU.AccessTy, TLI))
2348 continue;
2349 NewF.ScaledReg = SE.getAddExpr(NegImmS, NewF.ScaledReg);
2350
2351 // If the new scale is a constant in a register, and adding the constant
2352 // value to the immediate would produce a value closer to zero than the
2353 // immediate itself, then the formula isn't worthwhile.
2354 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewF.ScaledReg))
2355 if (C->getValue()->getValue().isNegative() !=
2356 (NewF.AM.BaseOffs < 0) &&
2357 (C->getValue()->getValue().abs() * APInt(BitWidth, F.AM.Scale))
2358 .ule(APInt(BitWidth, NewF.AM.BaseOffs).abs()))
2359 continue;
2360
2361 // OK, looks good.
2362 (void)InsertFormula(LU, LUIdx, NewF);
2363 } else {
2364 // Use the immediate in a base register.
2365 for (size_t N = 0, NE = F.BaseRegs.size(); N != NE; ++N) {
2366 const SCEV *BaseReg = F.BaseRegs[N];
2367 if (BaseReg != OrigReg)
2368 continue;
2369 Formula NewF = F;
2370 NewF.AM.BaseOffs = (uint64_t)NewF.AM.BaseOffs + Imm;
2371 if (!isLegalUse(NewF.AM, LU.MinOffset, LU.MaxOffset,
2372 LU.Kind, LU.AccessTy, TLI))
2373 continue;
2374 NewF.BaseRegs[N] = SE.getAddExpr(NegImmS, BaseReg);
2375
2376 // If the new formula has a constant in a register, and adding the
2377 // constant value to the immediate would produce a value closer to
2378 // zero than the immediate itself, then the formula isn't worthwhile.
2379 for (SmallVectorImpl<const SCEV *>::const_iterator
2380 J = NewF.BaseRegs.begin(), JE = NewF.BaseRegs.end();
2381 J != JE; ++J)
2382 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*J))
2383 if (C->getValue()->getValue().isNegative() !=
2384 (NewF.AM.BaseOffs < 0) &&
2385 C->getValue()->getValue().abs()
2386 .ule(APInt(BitWidth, NewF.AM.BaseOffs).abs()))
2387 goto skip_formula;
2388
2389 // Ok, looks good.
2390 (void)InsertFormula(LU, LUIdx, NewF);
2391 break;
2392 skip_formula:;
2393 }
2394 }
2395 }
2396 }
Dale Johannesenc1acc3f2009-05-11 17:15:42 +00002397}
2398
Dan Gohman572645c2010-02-12 10:34:29 +00002399/// GenerateAllReuseFormulae - Generate formulae for each use.
2400void
2401LSRInstance::GenerateAllReuseFormulae() {
2402 // This is split into two loops so that hasRegsUsedByUsesOtherThan
2403 // queries are more precise.
2404 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2405 LSRUse &LU = Uses[LUIdx];
2406 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2407 GenerateReassociations(LU, LUIdx, LU.Formulae[i]);
2408 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2409 GenerateCombinations(LU, LUIdx, LU.Formulae[i]);
2410 }
2411 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2412 LSRUse &LU = Uses[LUIdx];
2413 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2414 GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]);
2415 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2416 GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]);
2417 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2418 GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]);
2419 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2420 GenerateScales(LU, LUIdx, LU.Formulae[i]);
2421 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2422 GenerateTruncates(LU, LUIdx, LU.Formulae[i]);
2423 }
2424
2425 GenerateCrossUseConstantOffsets();
2426}
2427
2428/// If their are multiple formulae with the same set of registers used
2429/// by other uses, pick the best one and delete the others.
2430void LSRInstance::FilterOutUndesirableDedicatedRegisters() {
2431#ifndef NDEBUG
2432 bool Changed = false;
2433#endif
2434
2435 // Collect the best formula for each unique set of shared registers. This
2436 // is reset for each use.
2437 typedef DenseMap<SmallVector<const SCEV *, 2>, size_t, UniquifierDenseMapInfo>
2438 BestFormulaeTy;
2439 BestFormulaeTy BestFormulae;
2440
2441 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2442 LSRUse &LU = Uses[LUIdx];
2443 FormulaSorter Sorter(L, LU, SE, DT);
2444
2445 // Clear out the set of used regs; it will be recomputed.
2446 LU.Regs.clear();
2447
2448 for (size_t FIdx = 0, NumForms = LU.Formulae.size();
2449 FIdx != NumForms; ++FIdx) {
2450 Formula &F = LU.Formulae[FIdx];
2451
2452 SmallVector<const SCEV *, 2> Key;
2453 for (SmallVectorImpl<const SCEV *>::const_iterator J = F.BaseRegs.begin(),
2454 JE = F.BaseRegs.end(); J != JE; ++J) {
2455 const SCEV *Reg = *J;
2456 if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx))
2457 Key.push_back(Reg);
2458 }
2459 if (F.ScaledReg &&
2460 RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx))
2461 Key.push_back(F.ScaledReg);
2462 // Unstable sort by host order ok, because this is only used for
2463 // uniquifying.
2464 std::sort(Key.begin(), Key.end());
2465
2466 std::pair<BestFormulaeTy::const_iterator, bool> P =
2467 BestFormulae.insert(std::make_pair(Key, FIdx));
2468 if (!P.second) {
2469 Formula &Best = LU.Formulae[P.first->second];
2470 if (Sorter.operator()(F, Best))
2471 std::swap(F, Best);
2472 DEBUG(dbgs() << "Filtering out "; F.print(dbgs());
2473 dbgs() << "\n"
2474 " in favor of "; Best.print(dbgs());
2475 dbgs() << '\n');
2476#ifndef NDEBUG
2477 Changed = true;
2478#endif
2479 std::swap(F, LU.Formulae.back());
2480 LU.Formulae.pop_back();
2481 --FIdx;
2482 --NumForms;
2483 continue;
2484 }
2485 if (F.ScaledReg) LU.Regs.insert(F.ScaledReg);
2486 LU.Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
2487 }
2488 BestFormulae.clear();
2489 }
2490
2491 DEBUG(if (Changed) {
2492 dbgs() << "After filtering out undesirable candidates:\n";
2493 print_uses(dbgs());
2494 });
2495}
2496
2497/// NarrowSearchSpaceUsingHeuristics - If there are an extrordinary number of
2498/// formulae to choose from, use some rough heuristics to prune down the number
2499/// of formulae. This keeps the main solver from taking an extrordinary amount
2500/// of time in some worst-case scenarios.
2501void LSRInstance::NarrowSearchSpaceUsingHeuristics() {
2502 // This is a rough guess that seems to work fairly well.
2503 const size_t Limit = UINT16_MAX;
2504
2505 SmallPtrSet<const SCEV *, 4> Taken;
2506 for (;;) {
2507 // Estimate the worst-case number of solutions we might consider. We almost
2508 // never consider this many solutions because we prune the search space,
2509 // but the pruning isn't always sufficient.
2510 uint32_t Power = 1;
2511 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
2512 E = Uses.end(); I != E; ++I) {
2513 size_t FSize = I->Formulae.size();
2514 if (FSize >= Limit) {
2515 Power = Limit;
2516 break;
2517 }
2518 Power *= FSize;
2519 if (Power >= Limit)
2520 break;
2521 }
2522 if (Power < Limit)
2523 break;
2524
2525 // Ok, we have too many of formulae on our hands to conveniently handle.
2526 // Use a rough heuristic to thin out the list.
2527
2528 // Pick the register which is used by the most LSRUses, which is likely
2529 // to be a good reuse register candidate.
2530 const SCEV *Best = 0;
2531 unsigned BestNum = 0;
2532 for (RegUseTracker::const_iterator I = RegUses.begin(), E = RegUses.end();
2533 I != E; ++I) {
2534 const SCEV *Reg = *I;
2535 if (Taken.count(Reg))
2536 continue;
2537 if (!Best)
2538 Best = Reg;
2539 else {
2540 unsigned Count = RegUses.getUsedByIndices(Reg).count();
2541 if (Count > BestNum) {
2542 Best = Reg;
2543 BestNum = Count;
2544 }
2545 }
2546 }
2547
2548 DEBUG(dbgs() << "Narrowing the search space by assuming " << *Best
2549 << " will yeild profitable reuse.\n");
2550 Taken.insert(Best);
2551
2552 // In any use with formulae which references this register, delete formulae
2553 // which don't reference it.
2554 for (SmallVectorImpl<LSRUse>::iterator I = Uses.begin(),
2555 E = Uses.end(); I != E; ++I) {
2556 LSRUse &LU = *I;
2557 if (!LU.Regs.count(Best)) continue;
2558
2559 // Clear out the set of used regs; it will be recomputed.
2560 LU.Regs.clear();
2561
2562 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
2563 Formula &F = LU.Formulae[i];
2564 if (!F.referencesReg(Best)) {
2565 DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
2566 std::swap(LU.Formulae.back(), F);
2567 LU.Formulae.pop_back();
2568 --e;
2569 --i;
2570 continue;
2571 }
2572
2573 if (F.ScaledReg) LU.Regs.insert(F.ScaledReg);
2574 LU.Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
2575 }
2576 }
2577
2578 DEBUG(dbgs() << "After pre-selection:\n";
2579 print_uses(dbgs()));
2580 }
2581}
2582
2583/// SolveRecurse - This is the recursive solver.
2584void LSRInstance::SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
2585 Cost &SolutionCost,
2586 SmallVectorImpl<const Formula *> &Workspace,
2587 const Cost &CurCost,
2588 const SmallPtrSet<const SCEV *, 16> &CurRegs,
2589 DenseSet<const SCEV *> &VisitedRegs) const {
2590 // Some ideas:
2591 // - prune more:
2592 // - use more aggressive filtering
2593 // - sort the formula so that the most profitable solutions are found first
2594 // - sort the uses too
2595 // - search faster:
2596 // - dont compute a cost, and then compare. compare while computing a cost
2597 // and bail early.
2598 // - track register sets with SmallBitVector
2599
2600 const LSRUse &LU = Uses[Workspace.size()];
2601
2602 // If this use references any register that's already a part of the
2603 // in-progress solution, consider it a requirement that a formula must
2604 // reference that register in order to be considered. This prunes out
2605 // unprofitable searching.
2606 SmallSetVector<const SCEV *, 4> ReqRegs;
2607 for (SmallPtrSet<const SCEV *, 16>::const_iterator I = CurRegs.begin(),
2608 E = CurRegs.end(); I != E; ++I)
2609 if (LU.Regs.count(*I)) {
2610 ReqRegs.insert(*I);
2611 break;
2612 }
2613
2614 SmallPtrSet<const SCEV *, 16> NewRegs;
2615 Cost NewCost;
2616 for (SmallVectorImpl<Formula>::const_iterator I = LU.Formulae.begin(),
2617 E = LU.Formulae.end(); I != E; ++I) {
2618 const Formula &F = *I;
2619
2620 // Ignore formulae which do not use any of the required registers.
2621 for (SmallSetVector<const SCEV *, 4>::const_iterator J = ReqRegs.begin(),
2622 JE = ReqRegs.end(); J != JE; ++J) {
2623 const SCEV *Reg = *J;
2624 if ((!F.ScaledReg || F.ScaledReg != Reg) &&
2625 std::find(F.BaseRegs.begin(), F.BaseRegs.end(), Reg) ==
2626 F.BaseRegs.end())
2627 goto skip;
2628 }
2629
2630 // Evaluate the cost of the current formula. If it's already worse than
2631 // the current best, prune the search at that point.
2632 NewCost = CurCost;
2633 NewRegs = CurRegs;
2634 NewCost.RateFormula(F, NewRegs, VisitedRegs, L, LU.Offsets, SE, DT);
2635 if (NewCost < SolutionCost) {
2636 Workspace.push_back(&F);
2637 if (Workspace.size() != Uses.size()) {
2638 SolveRecurse(Solution, SolutionCost, Workspace, NewCost,
2639 NewRegs, VisitedRegs);
2640 if (F.getNumRegs() == 1 && Workspace.size() == 1)
2641 VisitedRegs.insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]);
2642 } else {
2643 DEBUG(dbgs() << "New best at "; NewCost.print(dbgs());
2644 dbgs() << ". Regs:";
2645 for (SmallPtrSet<const SCEV *, 16>::const_iterator
2646 I = NewRegs.begin(), E = NewRegs.end(); I != E; ++I)
2647 dbgs() << ' ' << **I;
2648 dbgs() << '\n');
2649
2650 SolutionCost = NewCost;
2651 Solution = Workspace;
2652 }
2653 Workspace.pop_back();
2654 }
2655 skip:;
2656 }
2657}
2658
2659void LSRInstance::Solve(SmallVectorImpl<const Formula *> &Solution) const {
2660 SmallVector<const Formula *, 8> Workspace;
2661 Cost SolutionCost;
2662 SolutionCost.Loose();
2663 Cost CurCost;
2664 SmallPtrSet<const SCEV *, 16> CurRegs;
2665 DenseSet<const SCEV *> VisitedRegs;
2666 Workspace.reserve(Uses.size());
2667
2668 SolveRecurse(Solution, SolutionCost, Workspace, CurCost,
2669 CurRegs, VisitedRegs);
2670
2671 // Ok, we've now made all our decisions.
2672 DEBUG(dbgs() << "\n"
2673 "The chosen solution requires "; SolutionCost.print(dbgs());
2674 dbgs() << ":\n";
2675 for (size_t i = 0, e = Uses.size(); i != e; ++i) {
2676 dbgs() << " ";
2677 Uses[i].print(dbgs());
2678 dbgs() << "\n"
2679 " ";
2680 Solution[i]->print(dbgs());
2681 dbgs() << '\n';
2682 });
2683}
2684
2685/// getImmediateDominator - A handy utility for the specific DominatorTree
2686/// query that we need here.
2687///
2688static BasicBlock *getImmediateDominator(BasicBlock *BB, DominatorTree &DT) {
2689 DomTreeNode *Node = DT.getNode(BB);
2690 if (!Node) return 0;
2691 Node = Node->getIDom();
2692 if (!Node) return 0;
2693 return Node->getBlock();
2694}
2695
2696Value *LSRInstance::Expand(const LSRFixup &LF,
2697 const Formula &F,
2698 BasicBlock::iterator IP,
2699 Loop *L, Instruction *IVIncInsertPos,
2700 SCEVExpander &Rewriter,
2701 SmallVectorImpl<WeakVH> &DeadInsts,
2702 ScalarEvolution &SE, DominatorTree &DT) const {
2703 const LSRUse &LU = Uses[LF.LUIdx];
2704
2705 // Then, collect some instructions which we will remain dominated by when
2706 // expanding the replacement. These must be dominated by any operands that
2707 // will be required in the expansion.
2708 SmallVector<Instruction *, 4> Inputs;
2709 if (Instruction *I = dyn_cast<Instruction>(LF.OperandValToReplace))
2710 Inputs.push_back(I);
2711 if (LU.Kind == LSRUse::ICmpZero)
2712 if (Instruction *I =
2713 dyn_cast<Instruction>(cast<ICmpInst>(LF.UserInst)->getOperand(1)))
2714 Inputs.push_back(I);
2715 if (LF.PostIncLoop && !L->contains(LF.UserInst))
2716 Inputs.push_back(L->getLoopLatch()->getTerminator());
2717
2718 // Then, climb up the immediate dominator tree as far as we can go while
2719 // still being dominated by the input positions.
2720 for (;;) {
2721 bool AllDominate = true;
2722 Instruction *BetterPos = 0;
2723 BasicBlock *IDom = getImmediateDominator(IP->getParent(), DT);
2724 if (!IDom) break;
2725 Instruction *Tentative = IDom->getTerminator();
2726 for (SmallVectorImpl<Instruction *>::const_iterator I = Inputs.begin(),
2727 E = Inputs.end(); I != E; ++I) {
2728 Instruction *Inst = *I;
2729 if (Inst == Tentative || !DT.dominates(Inst, Tentative)) {
2730 AllDominate = false;
2731 break;
2732 }
2733 if (IDom == Inst->getParent() &&
2734 (!BetterPos || DT.dominates(BetterPos, Inst)))
2735 BetterPos = next(BasicBlock::iterator(Inst));
2736 }
2737 if (!AllDominate)
2738 break;
2739 if (BetterPos)
2740 IP = BetterPos;
2741 else
2742 IP = Tentative;
2743 }
2744 while (isa<PHINode>(IP)) ++IP;
2745
2746 // Inform the Rewriter if we have a post-increment use, so that it can
2747 // perform an advantageous expansion.
2748 Rewriter.setPostInc(LF.PostIncLoop);
2749
2750 // This is the type that the user actually needs.
2751 const Type *OpTy = LF.OperandValToReplace->getType();
2752 // This will be the type that we'll initially expand to.
2753 const Type *Ty = F.getType();
2754 if (!Ty)
2755 // No type known; just expand directly to the ultimate type.
2756 Ty = OpTy;
2757 else if (SE.getEffectiveSCEVType(Ty) == SE.getEffectiveSCEVType(OpTy))
2758 // Expand directly to the ultimate type if it's the right size.
2759 Ty = OpTy;
2760 // This is the type to do integer arithmetic in.
2761 const Type *IntTy = SE.getEffectiveSCEVType(Ty);
2762
2763 // Build up a list of operands to add together to form the full base.
2764 SmallVector<const SCEV *, 8> Ops;
2765
2766 // Expand the BaseRegs portion.
2767 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
2768 E = F.BaseRegs.end(); I != E; ++I) {
2769 const SCEV *Reg = *I;
2770 assert(!Reg->isZero() && "Zero allocated in a base register!");
2771
2772 // If we're expanding for a post-inc user for the add-rec's loop, make the
2773 // post-inc adjustment.
2774 const SCEV *Start = Reg;
2775 while (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Start)) {
2776 if (AR->getLoop() == LF.PostIncLoop) {
2777 Reg = SE.getAddExpr(Reg, AR->getStepRecurrence(SE));
2778 // If the user is inside the loop, insert the code after the increment
2779 // so that it is dominated by its operand.
2780 if (L->contains(LF.UserInst))
2781 IP = IVIncInsertPos;
2782 break;
2783 }
2784 Start = AR->getStart();
2785 }
2786
2787 Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, 0, IP)));
2788 }
2789
2790 // Expand the ScaledReg portion.
2791 Value *ICmpScaledV = 0;
2792 if (F.AM.Scale != 0) {
2793 const SCEV *ScaledS = F.ScaledReg;
2794
2795 // If we're expanding for a post-inc user for the add-rec's loop, make the
2796 // post-inc adjustment.
2797 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ScaledS))
2798 if (AR->getLoop() == LF.PostIncLoop)
2799 ScaledS = SE.getAddExpr(ScaledS, AR->getStepRecurrence(SE));
2800
2801 if (LU.Kind == LSRUse::ICmpZero) {
2802 // An interesting way of "folding" with an icmp is to use a negated
2803 // scale, which we'll implement by inserting it into the other operand
2804 // of the icmp.
2805 assert(F.AM.Scale == -1 &&
2806 "The only scale supported by ICmpZero uses is -1!");
2807 ICmpScaledV = Rewriter.expandCodeFor(ScaledS, 0, IP);
2808 } else {
2809 // Otherwise just expand the scaled register and an explicit scale,
2810 // which is expected to be matched as part of the address.
2811 ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, 0, IP));
2812 ScaledS = SE.getMulExpr(ScaledS,
2813 SE.getIntegerSCEV(F.AM.Scale,
2814 ScaledS->getType()));
2815 Ops.push_back(ScaledS);
2816 }
2817 }
2818
2819 // Expand the immediate portions.
2820 if (F.AM.BaseGV)
2821 Ops.push_back(SE.getSCEV(F.AM.BaseGV));
2822 int64_t Offset = (uint64_t)F.AM.BaseOffs + LF.Offset;
2823 if (Offset != 0) {
2824 if (LU.Kind == LSRUse::ICmpZero) {
2825 // The other interesting way of "folding" with an ICmpZero is to use a
2826 // negated immediate.
2827 if (!ICmpScaledV)
2828 ICmpScaledV = ConstantInt::get(IntTy, -Offset);
2829 else {
2830 Ops.push_back(SE.getUnknown(ICmpScaledV));
2831 ICmpScaledV = ConstantInt::get(IntTy, Offset);
2832 }
2833 } else {
2834 // Just add the immediate values. These again are expected to be matched
2835 // as part of the address.
2836 Ops.push_back(SE.getIntegerSCEV(Offset, IntTy));
2837 }
2838 }
2839
2840 // Emit instructions summing all the operands.
2841 const SCEV *FullS = Ops.empty() ?
2842 SE.getIntegerSCEV(0, IntTy) :
2843 SE.getAddExpr(Ops);
2844 Value *FullV = Rewriter.expandCodeFor(FullS, Ty, IP);
2845
2846 // We're done expanding now, so reset the rewriter.
2847 Rewriter.setPostInc(0);
2848
2849 // An ICmpZero Formula represents an ICmp which we're handling as a
2850 // comparison against zero. Now that we've expanded an expression for that
2851 // form, update the ICmp's other operand.
2852 if (LU.Kind == LSRUse::ICmpZero) {
2853 ICmpInst *CI = cast<ICmpInst>(LF.UserInst);
2854 DeadInsts.push_back(CI->getOperand(1));
2855 assert(!F.AM.BaseGV && "ICmp does not support folding a global value and "
2856 "a scale at the same time!");
2857 if (F.AM.Scale == -1) {
2858 if (ICmpScaledV->getType() != OpTy) {
2859 Instruction *Cast =
2860 CastInst::Create(CastInst::getCastOpcode(ICmpScaledV, false,
2861 OpTy, false),
2862 ICmpScaledV, OpTy, "tmp", CI);
2863 ICmpScaledV = Cast;
2864 }
2865 CI->setOperand(1, ICmpScaledV);
2866 } else {
2867 assert(F.AM.Scale == 0 &&
2868 "ICmp does not support folding a global value and "
2869 "a scale at the same time!");
2870 Constant *C = ConstantInt::getSigned(SE.getEffectiveSCEVType(OpTy),
2871 -(uint64_t)Offset);
2872 if (C->getType() != OpTy)
2873 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2874 OpTy, false),
2875 C, OpTy);
2876
2877 CI->setOperand(1, C);
2878 }
2879 }
2880
2881 return FullV;
2882}
2883
2884/// Rewrite - Emit instructions for the leading candidate expression for this
2885/// LSRUse (this is called "expanding"), and update the UserInst to reference
2886/// the newly expanded value.
2887void LSRInstance::Rewrite(const LSRFixup &LF,
2888 const Formula &F,
2889 Loop *L, Instruction *IVIncInsertPos,
2890 SCEVExpander &Rewriter,
2891 SmallVectorImpl<WeakVH> &DeadInsts,
2892 ScalarEvolution &SE, DominatorTree &DT,
2893 Pass *P) const {
2894 const Type *OpTy = LF.OperandValToReplace->getType();
2895
2896 // First, find an insertion point that dominates UserInst. For PHI nodes,
2897 // find the nearest block which dominates all the relevant uses.
2898 if (PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) {
2899 DenseMap<BasicBlock *, Value *> Inserted;
2900 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2901 if (PN->getIncomingValue(i) == LF.OperandValToReplace) {
2902 BasicBlock *BB = PN->getIncomingBlock(i);
2903
2904 // If this is a critical edge, split the edge so that we do not insert
2905 // the code on all predecessor/successor paths. We do this unless this
2906 // is the canonical backedge for this loop, which complicates post-inc
2907 // users.
2908 if (e != 1 && BB->getTerminator()->getNumSuccessors() > 1 &&
2909 !isa<IndirectBrInst>(BB->getTerminator()) &&
2910 (PN->getParent() != L->getHeader() || !L->contains(BB))) {
2911 // Split the critical edge.
2912 BasicBlock *NewBB = SplitCriticalEdge(BB, PN->getParent(), P);
2913
2914 // If PN is outside of the loop and BB is in the loop, we want to
2915 // move the block to be immediately before the PHI block, not
2916 // immediately after BB.
2917 if (L->contains(BB) && !L->contains(PN))
2918 NewBB->moveBefore(PN->getParent());
2919
2920 // Splitting the edge can reduce the number of PHI entries we have.
2921 e = PN->getNumIncomingValues();
2922 BB = NewBB;
2923 i = PN->getBasicBlockIndex(BB);
2924 }
2925
2926 std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> Pair =
2927 Inserted.insert(std::make_pair(BB, static_cast<Value *>(0)));
2928 if (!Pair.second)
2929 PN->setIncomingValue(i, Pair.first->second);
2930 else {
2931 Value *FullV = Expand(LF, F, BB->getTerminator(), L, IVIncInsertPos,
2932 Rewriter, DeadInsts, SE, DT);
2933
2934 // If this is reuse-by-noop-cast, insert the noop cast.
2935 if (FullV->getType() != OpTy)
2936 FullV =
2937 CastInst::Create(CastInst::getCastOpcode(FullV, false,
2938 OpTy, false),
2939 FullV, LF.OperandValToReplace->getType(),
2940 "tmp", BB->getTerminator());
2941
2942 PN->setIncomingValue(i, FullV);
2943 Pair.first->second = FullV;
2944 }
2945 }
2946 } else {
2947 Value *FullV = Expand(LF, F, LF.UserInst, L, IVIncInsertPos,
2948 Rewriter, DeadInsts, SE, DT);
2949
2950 // If this is reuse-by-noop-cast, insert the noop cast.
2951 if (FullV->getType() != OpTy) {
2952 Instruction *Cast =
2953 CastInst::Create(CastInst::getCastOpcode(FullV, false, OpTy, false),
2954 FullV, OpTy, "tmp", LF.UserInst);
2955 FullV = Cast;
2956 }
2957
2958 // Update the user. ICmpZero is handled specially here (for now) because
2959 // Expand may have updated one of the operands of the icmp already, and
2960 // its new value may happen to be equal to LF.OperandValToReplace, in
2961 // which case doing replaceUsesOfWith leads to replacing both operands
2962 // with the same value. TODO: Reorganize this.
2963 if (Uses[LF.LUIdx].Kind == LSRUse::ICmpZero)
2964 LF.UserInst->setOperand(0, FullV);
2965 else
2966 LF.UserInst->replaceUsesOfWith(LF.OperandValToReplace, FullV);
2967 }
2968
2969 DeadInsts.push_back(LF.OperandValToReplace);
2970}
2971
2972void
2973LSRInstance::ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
2974 Pass *P) {
2975 // Keep track of instructions we may have made dead, so that
2976 // we can remove them after we are done working.
2977 SmallVector<WeakVH, 16> DeadInsts;
2978
2979 SCEVExpander Rewriter(SE);
2980 Rewriter.disableCanonicalMode();
2981 Rewriter.setIVIncInsertPos(L, IVIncInsertPos);
2982
2983 // Expand the new value definitions and update the users.
2984 for (size_t i = 0, e = Fixups.size(); i != e; ++i) {
2985 size_t LUIdx = Fixups[i].LUIdx;
2986
2987 Rewrite(Fixups[i], *Solution[LUIdx], L, IVIncInsertPos, Rewriter,
2988 DeadInsts, SE, DT, P);
2989
2990 Changed = true;
2991 }
2992
2993 // Clean up after ourselves. This must be done before deleting any
2994 // instructions.
2995 Rewriter.clear();
2996
2997 Changed |= DeleteTriviallyDeadInstructions(DeadInsts);
2998}
2999
3000LSRInstance::LSRInstance(const TargetLowering *tli, Loop *l, Pass *P)
3001 : IU(P->getAnalysis<IVUsers>()),
3002 SE(P->getAnalysis<ScalarEvolution>()),
3003 DT(P->getAnalysis<DominatorTree>()),
3004 TLI(tli), L(l), Changed(false), IVIncInsertPos(0) {
Devang Patel0f54dcb2007-03-06 21:14:09 +00003005
Dan Gohman03e896b2009-11-05 21:11:53 +00003006 // If LoopSimplify form is not available, stay out of trouble.
Dan Gohman572645c2010-02-12 10:34:29 +00003007 if (!L->isLoopSimplifyForm()) return;
Dan Gohman03e896b2009-11-05 21:11:53 +00003008
Dan Gohman572645c2010-02-12 10:34:29 +00003009 // If there's no interesting work to be done, bail early.
3010 if (IU.empty()) return;
Dan Gohman80b0f8c2009-03-09 20:34:59 +00003011
Dan Gohman572645c2010-02-12 10:34:29 +00003012 DEBUG(dbgs() << "\nLSR on loop ";
3013 WriteAsOperand(dbgs(), L->getHeader(), /*PrintType=*/false);
3014 dbgs() << ":\n");
Dan Gohmanf7912df2009-03-09 20:46:50 +00003015
Dan Gohman572645c2010-02-12 10:34:29 +00003016 /// OptimizeShadowIV - If IV is used in a int-to-float cast
3017 /// inside the loop then try to eliminate the cast opeation.
3018 OptimizeShadowIV();
Chris Lattner010de252005-08-08 05:28:22 +00003019
Dan Gohman572645c2010-02-12 10:34:29 +00003020 // Change loop terminating condition to use the postinc iv when possible.
3021 Changed |= OptimizeLoopTermCond();
Evan Cheng5792f512009-05-11 22:33:01 +00003022
Dan Gohman572645c2010-02-12 10:34:29 +00003023 CollectInterestingTypesAndFactors();
3024 CollectFixupsAndInitialFormulae();
3025 CollectLoopInvariantFixupsAndFormulae();
Chris Lattner010de252005-08-08 05:28:22 +00003026
Dan Gohman572645c2010-02-12 10:34:29 +00003027 DEBUG(dbgs() << "LSR found " << Uses.size() << " uses:\n";
3028 print_uses(dbgs()));
Misha Brukmanfd939082005-04-21 23:48:37 +00003029
Dan Gohman572645c2010-02-12 10:34:29 +00003030 // Now use the reuse data to generate a bunch of interesting ways
3031 // to formulate the values needed for the uses.
3032 GenerateAllReuseFormulae();
Evan Chengd1d6b5c2006-03-16 21:53:05 +00003033
Dan Gohman572645c2010-02-12 10:34:29 +00003034 DEBUG(dbgs() << "\n"
3035 "After generating reuse formulae:\n";
3036 print_uses(dbgs()));
Nate Begemaneaa13852004-10-18 21:08:22 +00003037
Dan Gohman572645c2010-02-12 10:34:29 +00003038 FilterOutUndesirableDedicatedRegisters();
3039 NarrowSearchSpaceUsingHeuristics();
Dan Gohman6bec5bb2009-12-18 00:06:20 +00003040
Dan Gohman572645c2010-02-12 10:34:29 +00003041 SmallVector<const Formula *, 8> Solution;
3042 Solve(Solution);
3043 assert(Solution.size() == Uses.size() && "Malformed solution!");
Dan Gohman6bec5bb2009-12-18 00:06:20 +00003044
Dan Gohman572645c2010-02-12 10:34:29 +00003045 // Release memory that is no longer needed.
3046 Factors.clear();
3047 Types.clear();
3048 RegUses.clear();
3049
3050#ifndef NDEBUG
3051 // Formulae should be legal.
3052 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
3053 E = Uses.end(); I != E; ++I) {
3054 const LSRUse &LU = *I;
3055 for (SmallVectorImpl<Formula>::const_iterator J = LU.Formulae.begin(),
3056 JE = LU.Formulae.end(); J != JE; ++J)
3057 assert(isLegalUse(J->AM, LU.MinOffset, LU.MaxOffset,
3058 LU.Kind, LU.AccessTy, TLI) &&
3059 "Illegal formula generated!");
3060 };
3061#endif
3062
3063 // Now that we've decided what we want, make it so.
3064 ImplementSolution(Solution, P);
3065}
3066
3067void LSRInstance::print_factors_and_types(raw_ostream &OS) const {
3068 if (Factors.empty() && Types.empty()) return;
3069
3070 OS << "LSR has identified the following interesting factors and types: ";
3071 bool First = true;
3072
3073 for (SmallSetVector<int64_t, 8>::const_iterator
3074 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
3075 if (!First) OS << ", ";
3076 First = false;
3077 OS << '*' << *I;
Evan Cheng81ebdcf2009-11-10 21:14:05 +00003078 }
Dale Johannesenc1acc3f2009-05-11 17:15:42 +00003079
Dan Gohman572645c2010-02-12 10:34:29 +00003080 for (SmallSetVector<const Type *, 4>::const_iterator
3081 I = Types.begin(), E = Types.end(); I != E; ++I) {
3082 if (!First) OS << ", ";
3083 First = false;
3084 OS << '(' << **I << ')';
3085 }
3086 OS << '\n';
3087}
3088
3089void LSRInstance::print_fixups(raw_ostream &OS) const {
3090 OS << "LSR is examining the following fixup sites:\n";
3091 for (SmallVectorImpl<LSRFixup>::const_iterator I = Fixups.begin(),
3092 E = Fixups.end(); I != E; ++I) {
3093 const LSRFixup &LF = *I;
3094 dbgs() << " ";
3095 LF.print(OS);
3096 OS << '\n';
3097 }
3098}
3099
3100void LSRInstance::print_uses(raw_ostream &OS) const {
3101 OS << "LSR is examining the following uses:\n";
3102 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
3103 E = Uses.end(); I != E; ++I) {
3104 const LSRUse &LU = *I;
3105 dbgs() << " ";
3106 LU.print(OS);
3107 OS << '\n';
3108 for (SmallVectorImpl<Formula>::const_iterator J = LU.Formulae.begin(),
3109 JE = LU.Formulae.end(); J != JE; ++J) {
3110 OS << " ";
3111 J->print(OS);
3112 OS << '\n';
3113 }
3114 }
3115}
3116
3117void LSRInstance::print(raw_ostream &OS) const {
3118 print_factors_and_types(OS);
3119 print_fixups(OS);
3120 print_uses(OS);
3121}
3122
3123void LSRInstance::dump() const {
3124 print(errs()); errs() << '\n';
3125}
3126
3127namespace {
3128
3129class LoopStrengthReduce : public LoopPass {
3130 /// TLI - Keep a pointer of a TargetLowering to consult for determining
3131 /// transformation profitability.
3132 const TargetLowering *const TLI;
3133
3134public:
3135 static char ID; // Pass ID, replacement for typeid
3136 explicit LoopStrengthReduce(const TargetLowering *tli = 0);
3137
3138private:
3139 bool runOnLoop(Loop *L, LPPassManager &LPM);
3140 void getAnalysisUsage(AnalysisUsage &AU) const;
3141};
3142
3143}
3144
3145char LoopStrengthReduce::ID = 0;
3146static RegisterPass<LoopStrengthReduce>
3147X("loop-reduce", "Loop Strength Reduction");
3148
3149Pass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
3150 return new LoopStrengthReduce(TLI);
3151}
3152
3153LoopStrengthReduce::LoopStrengthReduce(const TargetLowering *tli)
3154 : LoopPass(&ID), TLI(tli) {}
3155
3156void LoopStrengthReduce::getAnalysisUsage(AnalysisUsage &AU) const {
3157 // We split critical edges, so we change the CFG. However, we do update
3158 // many analyses if they are around.
3159 AU.addPreservedID(LoopSimplifyID);
3160 AU.addPreserved<LoopInfo>();
3161 AU.addPreserved("domfrontier");
3162
3163 AU.addRequiredID(LoopSimplifyID);
3164 AU.addRequired<DominatorTree>();
3165 AU.addPreserved<DominatorTree>();
3166 AU.addRequired<ScalarEvolution>();
3167 AU.addPreserved<ScalarEvolution>();
3168 AU.addRequired<IVUsers>();
3169 AU.addPreserved<IVUsers>();
3170}
3171
3172bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager & /*LPM*/) {
3173 bool Changed = false;
3174
3175 // Run the main LSR transformation.
3176 Changed |= LSRInstance(TLI, L, this).getChanged();
3177
Dan Gohmanafc36a92009-05-02 18:29:22 +00003178 // At this point, it is worth checking to see if any recurrence PHIs are also
Dan Gohman35738ac2009-05-04 22:30:44 +00003179 // dead, so that we can remove them as well.
Dan Gohman9fff2182010-01-05 16:31:45 +00003180 Changed |= DeleteDeadPHIs(L->getHeader());
Dan Gohmanafc36a92009-05-02 18:29:22 +00003181
Evan Cheng1ce75dc2008-07-07 19:51:32 +00003182 return Changed;
Nate Begemaneaa13852004-10-18 21:08:22 +00003183}