1 //===- LoopStrengthReduce.cpp - Strength Reduce IVs in Loops --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This transformation analyzes and transforms the induction variables (and
11 // computations derived from them) into forms suitable for efficient execution
14 // This pass performs a strength reduction on array references inside loops that
15 // 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.
20 // 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:
24 // %i = phi [ 0, %entry ], [ %i.next, %latch ]
26 // %i.next = add %i, 1
27 // %c = icmp eq %i.next, %n
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.
36 // TODO: More sophistication in the way Formulae are generated and filtered.
38 // TODO: Handle multiple loops at a time.
40 // TODO: Should the addressing mode BaseGV be changed to a ConstantExpr instead
43 // TODO: When truncation is free, truncate ICmp users' operands to make it a
44 // smaller encoding (on x86 at least).
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"
54 //===----------------------------------------------------------------------===//
56 #include "llvm/Transforms/Scalar.h"
57 #include "llvm/ADT/DenseSet.h"
58 #include "llvm/ADT/Hashing.h"
59 #include "llvm/ADT/STLExtras.h"
60 #include "llvm/ADT/SetVector.h"
61 #include "llvm/ADT/SmallBitVector.h"
62 #include "llvm/Analysis/IVUsers.h"
63 #include "llvm/Analysis/LoopPass.h"
64 #include "llvm/Analysis/ScalarEvolutionExpander.h"
65 #include "llvm/Analysis/TargetTransformInfo.h"
66 #include "llvm/IR/Constants.h"
67 #include "llvm/IR/DerivedTypes.h"
68 #include "llvm/IR/Dominators.h"
69 #include "llvm/IR/Instructions.h"
70 #include "llvm/IR/IntrinsicInst.h"
71 #include "llvm/IR/Module.h"
72 #include "llvm/IR/ValueHandle.h"
73 #include "llvm/Support/CommandLine.h"
74 #include "llvm/Support/Debug.h"
75 #include "llvm/Support/raw_ostream.h"
76 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
77 #include "llvm/Transforms/Utils/Local.h"
81 #define DEBUG_TYPE "loop-reduce"
83 /// MaxIVUsers is an arbitrary threshold that provides an early opportunitiy for
84 /// bail out. This threshold is far beyond the number of users that LSR can
85 /// conceivably solve, so it should not affect generated code, but catches the
86 /// worst cases before LSR burns too much compile time and stack space.
87 static const unsigned MaxIVUsers = 200;
89 // Temporary flag to cleanup congruent phis after LSR phi expansion.
90 // It's currently disabled until we can determine whether it's truly useful or
91 // not. The flag should be removed after the v3.0 release.
92 // This is now needed for ivchains.
93 static cl::opt<bool> EnablePhiElim(
94 "enable-lsr-phielim", cl::Hidden, cl::init(true),
95 cl::desc("Enable LSR phi elimination"));
98 // Stress test IV chain generation.
99 static cl::opt<bool> StressIVChain(
100 "stress-ivchain", cl::Hidden, cl::init(false),
101 cl::desc("Stress test LSR IV chains"));
103 static bool StressIVChain = false;
108 /// RegSortData - This class holds data which is used to order reuse candidates.
111 /// UsedByIndices - This represents the set of LSRUse indices which reference
112 /// a particular register.
113 SmallBitVector UsedByIndices;
115 void print(raw_ostream &OS) const;
121 void RegSortData::print(raw_ostream &OS) const {
122 OS << "[NumUses=" << UsedByIndices.count() << ']';
125 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
126 void RegSortData::dump() const {
127 print(errs()); errs() << '\n';
133 /// RegUseTracker - Map register candidates to information about how they are
135 class RegUseTracker {
136 typedef DenseMap<const SCEV *, RegSortData> RegUsesTy;
138 RegUsesTy RegUsesMap;
139 SmallVector<const SCEV *, 16> RegSequence;
142 void CountRegister(const SCEV *Reg, size_t LUIdx);
143 void DropRegister(const SCEV *Reg, size_t LUIdx);
144 void SwapAndDropUse(size_t LUIdx, size_t LastLUIdx);
146 bool isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const;
148 const SmallBitVector &getUsedByIndices(const SCEV *Reg) const;
152 typedef SmallVectorImpl<const SCEV *>::iterator iterator;
153 typedef SmallVectorImpl<const SCEV *>::const_iterator const_iterator;
154 iterator begin() { return RegSequence.begin(); }
155 iterator end() { return RegSequence.end(); }
156 const_iterator begin() const { return RegSequence.begin(); }
157 const_iterator end() const { return RegSequence.end(); }
163 RegUseTracker::CountRegister(const SCEV *Reg, size_t LUIdx) {
164 std::pair<RegUsesTy::iterator, bool> Pair =
165 RegUsesMap.insert(std::make_pair(Reg, RegSortData()));
166 RegSortData &RSD = Pair.first->second;
168 RegSequence.push_back(Reg);
169 RSD.UsedByIndices.resize(std::max(RSD.UsedByIndices.size(), LUIdx + 1));
170 RSD.UsedByIndices.set(LUIdx);
174 RegUseTracker::DropRegister(const SCEV *Reg, size_t LUIdx) {
175 RegUsesTy::iterator It = RegUsesMap.find(Reg);
176 assert(It != RegUsesMap.end());
177 RegSortData &RSD = It->second;
178 assert(RSD.UsedByIndices.size() > LUIdx);
179 RSD.UsedByIndices.reset(LUIdx);
183 RegUseTracker::SwapAndDropUse(size_t LUIdx, size_t LastLUIdx) {
184 assert(LUIdx <= LastLUIdx);
186 // Update RegUses. The data structure is not optimized for this purpose;
187 // we must iterate through it and update each of the bit vectors.
188 for (auto &Pair : RegUsesMap) {
189 SmallBitVector &UsedByIndices = Pair.second.UsedByIndices;
190 if (LUIdx < UsedByIndices.size())
191 UsedByIndices[LUIdx] =
192 LastLUIdx < UsedByIndices.size() ? UsedByIndices[LastLUIdx] : 0;
193 UsedByIndices.resize(std::min(UsedByIndices.size(), LastLUIdx));
198 RegUseTracker::isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const {
199 RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
200 if (I == RegUsesMap.end())
202 const SmallBitVector &UsedByIndices = I->second.UsedByIndices;
203 int i = UsedByIndices.find_first();
204 if (i == -1) return false;
205 if ((size_t)i != LUIdx) return true;
206 return UsedByIndices.find_next(i) != -1;
209 const SmallBitVector &RegUseTracker::getUsedByIndices(const SCEV *Reg) const {
210 RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
211 assert(I != RegUsesMap.end() && "Unknown register!");
212 return I->second.UsedByIndices;
215 void RegUseTracker::clear() {
222 /// Formula - This class holds information that describes a formula for
223 /// computing satisfying a use. It may include broken-out immediates and scaled
226 /// Global base address used for complex addressing.
229 /// Base offset for complex addressing.
232 /// Whether any complex addressing has a base register.
235 /// The scale of any complex addressing.
238 /// BaseRegs - The list of "base" registers for this use. When this is
239 /// non-empty. The canonical representation of a formula is
240 /// 1. BaseRegs.size > 1 implies ScaledReg != NULL and
241 /// 2. ScaledReg != NULL implies Scale != 1 || !BaseRegs.empty().
242 /// #1 enforces that the scaled register is always used when at least two
243 /// registers are needed by the formula: e.g., reg1 + reg2 is reg1 + 1 * reg2.
244 /// #2 enforces that 1 * reg is reg.
245 /// This invariant can be temporarly broken while building a formula.
246 /// However, every formula inserted into the LSRInstance must be in canonical
248 SmallVector<const SCEV *, 4> BaseRegs;
250 /// ScaledReg - The 'scaled' register for this use. This should be non-null
251 /// when Scale is not zero.
252 const SCEV *ScaledReg;
254 /// UnfoldedOffset - An additional constant offset which added near the
255 /// use. This requires a temporary register, but the offset itself can
256 /// live in an add immediate field rather than a register.
257 int64_t UnfoldedOffset;
260 : BaseGV(nullptr), BaseOffset(0), HasBaseReg(false), Scale(0),
261 ScaledReg(nullptr), UnfoldedOffset(0) {}
263 void InitialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE);
265 bool isCanonical() const;
271 size_t getNumRegs() const;
272 Type *getType() const;
274 void DeleteBaseReg(const SCEV *&S);
276 bool referencesReg(const SCEV *S) const;
277 bool hasRegsUsedByUsesOtherThan(size_t LUIdx,
278 const RegUseTracker &RegUses) const;
280 void print(raw_ostream &OS) const;
286 /// DoInitialMatch - Recursion helper for InitialMatch.
287 static void DoInitialMatch(const SCEV *S, Loop *L,
288 SmallVectorImpl<const SCEV *> &Good,
289 SmallVectorImpl<const SCEV *> &Bad,
290 ScalarEvolution &SE) {
291 // Collect expressions which properly dominate the loop header.
292 if (SE.properlyDominates(S, L->getHeader())) {
297 // Look at add operands.
298 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
299 for (const SCEV *S : Add->operands())
300 DoInitialMatch(S, L, Good, Bad, SE);
304 // Look at addrec operands.
305 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
306 if (!AR->getStart()->isZero()) {
307 DoInitialMatch(AR->getStart(), L, Good, Bad, SE);
308 DoInitialMatch(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0),
309 AR->getStepRecurrence(SE),
310 // FIXME: AR->getNoWrapFlags()
311 AR->getLoop(), SCEV::FlagAnyWrap),
316 // Handle a multiplication by -1 (negation) if it didn't fold.
317 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S))
318 if (Mul->getOperand(0)->isAllOnesValue()) {
319 SmallVector<const SCEV *, 4> Ops(Mul->op_begin()+1, Mul->op_end());
320 const SCEV *NewMul = SE.getMulExpr(Ops);
322 SmallVector<const SCEV *, 4> MyGood;
323 SmallVector<const SCEV *, 4> MyBad;
324 DoInitialMatch(NewMul, L, MyGood, MyBad, SE);
325 const SCEV *NegOne = SE.getSCEV(ConstantInt::getAllOnesValue(
326 SE.getEffectiveSCEVType(NewMul->getType())));
327 for (SmallVectorImpl<const SCEV *>::const_iterator I = MyGood.begin(),
328 E = MyGood.end(); I != E; ++I)
329 Good.push_back(SE.getMulExpr(NegOne, *I));
330 for (SmallVectorImpl<const SCEV *>::const_iterator I = MyBad.begin(),
331 E = MyBad.end(); I != E; ++I)
332 Bad.push_back(SE.getMulExpr(NegOne, *I));
336 // Ok, we can't do anything interesting. Just stuff the whole thing into a
337 // register and hope for the best.
341 /// InitialMatch - Incorporate loop-variant parts of S into this Formula,
342 /// attempting to keep all loop-invariant and loop-computable values in a
343 /// single base register.
344 void Formula::InitialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE) {
345 SmallVector<const SCEV *, 4> Good;
346 SmallVector<const SCEV *, 4> Bad;
347 DoInitialMatch(S, L, Good, Bad, SE);
349 const SCEV *Sum = SE.getAddExpr(Good);
351 BaseRegs.push_back(Sum);
355 const SCEV *Sum = SE.getAddExpr(Bad);
357 BaseRegs.push_back(Sum);
363 /// \brief Check whether or not this formula statisfies the canonical
365 /// \see Formula::BaseRegs.
366 bool Formula::isCanonical() const {
368 return Scale != 1 || !BaseRegs.empty();
369 return BaseRegs.size() <= 1;
372 /// \brief Helper method to morph a formula into its canonical representation.
373 /// \see Formula::BaseRegs.
374 /// Every formula having more than one base register, must use the ScaledReg
375 /// field. Otherwise, we would have to do special cases everywhere in LSR
376 /// to treat reg1 + reg2 + ... the same way as reg1 + 1*reg2 + ...
377 /// On the other hand, 1*reg should be canonicalized into reg.
378 void Formula::Canonicalize() {
381 // So far we did not need this case. This is easy to implement but it is
382 // useless to maintain dead code. Beside it could hurt compile time.
383 assert(!BaseRegs.empty() && "1*reg => reg, should not be needed.");
384 // Keep the invariant sum in BaseRegs and one of the variant sum in ScaledReg.
385 ScaledReg = BaseRegs.back();
388 size_t BaseRegsSize = BaseRegs.size();
390 // If ScaledReg is an invariant, try to find a variant expression.
391 while (Try < BaseRegsSize && !isa<SCEVAddRecExpr>(ScaledReg))
392 std::swap(ScaledReg, BaseRegs[Try++]);
395 /// \brief Get rid of the scale in the formula.
396 /// In other words, this method morphes reg1 + 1*reg2 into reg1 + reg2.
397 /// \return true if it was possible to get rid of the scale, false otherwise.
398 /// \note After this operation the formula may not be in the canonical form.
399 bool Formula::Unscale() {
403 BaseRegs.push_back(ScaledReg);
408 /// getNumRegs - Return the total number of register operands used by this
409 /// formula. This does not include register uses implied by non-constant
411 size_t Formula::getNumRegs() const {
412 return !!ScaledReg + BaseRegs.size();
415 /// getType - Return the type of this formula, if it has one, or null
416 /// otherwise. This type is meaningless except for the bit size.
417 Type *Formula::getType() const {
418 return !BaseRegs.empty() ? BaseRegs.front()->getType() :
419 ScaledReg ? ScaledReg->getType() :
420 BaseGV ? BaseGV->getType() :
424 /// DeleteBaseReg - Delete the given base reg from the BaseRegs list.
425 void Formula::DeleteBaseReg(const SCEV *&S) {
426 if (&S != &BaseRegs.back())
427 std::swap(S, BaseRegs.back());
431 /// referencesReg - Test if this formula references the given register.
432 bool Formula::referencesReg(const SCEV *S) const {
433 return S == ScaledReg ||
434 std::find(BaseRegs.begin(), BaseRegs.end(), S) != BaseRegs.end();
437 /// hasRegsUsedByUsesOtherThan - Test whether this formula uses registers
438 /// which are used by uses other than the use with the given index.
439 bool Formula::hasRegsUsedByUsesOtherThan(size_t LUIdx,
440 const RegUseTracker &RegUses) const {
442 if (RegUses.isRegUsedByUsesOtherThan(ScaledReg, LUIdx))
444 for (SmallVectorImpl<const SCEV *>::const_iterator I = BaseRegs.begin(),
445 E = BaseRegs.end(); I != E; ++I)
446 if (RegUses.isRegUsedByUsesOtherThan(*I, LUIdx))
451 void Formula::print(raw_ostream &OS) const {
454 if (!First) OS << " + "; else First = false;
455 BaseGV->printAsOperand(OS, /*PrintType=*/false);
457 if (BaseOffset != 0) {
458 if (!First) OS << " + "; else First = false;
461 for (SmallVectorImpl<const SCEV *>::const_iterator I = BaseRegs.begin(),
462 E = BaseRegs.end(); I != E; ++I) {
463 if (!First) OS << " + "; else First = false;
464 OS << "reg(" << **I << ')';
466 if (HasBaseReg && BaseRegs.empty()) {
467 if (!First) OS << " + "; else First = false;
468 OS << "**error: HasBaseReg**";
469 } else if (!HasBaseReg && !BaseRegs.empty()) {
470 if (!First) OS << " + "; else First = false;
471 OS << "**error: !HasBaseReg**";
474 if (!First) OS << " + "; else First = false;
475 OS << Scale << "*reg(";
482 if (UnfoldedOffset != 0) {
483 if (!First) OS << " + ";
484 OS << "imm(" << UnfoldedOffset << ')';
488 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
489 void Formula::dump() const {
490 print(errs()); errs() << '\n';
494 /// isAddRecSExtable - Return true if the given addrec can be sign-extended
495 /// without changing its value.
496 static bool isAddRecSExtable(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
498 IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(AR->getType()) + 1);
499 return isa<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
502 /// isAddSExtable - Return true if the given add can be sign-extended
503 /// without changing its value.
504 static bool isAddSExtable(const SCEVAddExpr *A, ScalarEvolution &SE) {
506 IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(A->getType()) + 1);
507 return isa<SCEVAddExpr>(SE.getSignExtendExpr(A, WideTy));
510 /// isMulSExtable - Return true if the given mul can be sign-extended
511 /// without changing its value.
512 static bool isMulSExtable(const SCEVMulExpr *M, ScalarEvolution &SE) {
514 IntegerType::get(SE.getContext(),
515 SE.getTypeSizeInBits(M->getType()) * M->getNumOperands());
516 return isa<SCEVMulExpr>(SE.getSignExtendExpr(M, WideTy));
519 /// getExactSDiv - Return an expression for LHS /s RHS, if it can be determined
520 /// and if the remainder is known to be zero, or null otherwise. If
521 /// IgnoreSignificantBits is true, expressions like (X * Y) /s Y are simplified
522 /// to Y, ignoring that the multiplication may overflow, which is useful when
523 /// the result will be used in a context where the most significant bits are
525 static const SCEV *getExactSDiv(const SCEV *LHS, const SCEV *RHS,
527 bool IgnoreSignificantBits = false) {
528 // Handle the trivial case, which works for any SCEV type.
530 return SE.getConstant(LHS->getType(), 1);
532 // Handle a few RHS special cases.
533 const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS);
535 const APInt &RA = RC->getValue()->getValue();
536 // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do
538 if (RA.isAllOnesValue())
539 return SE.getMulExpr(LHS, RC);
540 // Handle x /s 1 as x.
545 // Check for a division of a constant by a constant.
546 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(LHS)) {
549 const APInt &LA = C->getValue()->getValue();
550 const APInt &RA = RC->getValue()->getValue();
551 if (LA.srem(RA) != 0)
553 return SE.getConstant(LA.sdiv(RA));
556 // Distribute the sdiv over addrec operands, if the addrec doesn't overflow.
557 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) {
558 if (IgnoreSignificantBits || isAddRecSExtable(AR, SE)) {
559 const SCEV *Step = getExactSDiv(AR->getStepRecurrence(SE), RHS, SE,
560 IgnoreSignificantBits);
561 if (!Step) return nullptr;
562 const SCEV *Start = getExactSDiv(AR->getStart(), RHS, SE,
563 IgnoreSignificantBits);
564 if (!Start) return nullptr;
565 // FlagNW is independent of the start value, step direction, and is
566 // preserved with smaller magnitude steps.
567 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
568 return SE.getAddRecExpr(Start, Step, AR->getLoop(), SCEV::FlagAnyWrap);
573 // Distribute the sdiv over add operands, if the add doesn't overflow.
574 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(LHS)) {
575 if (IgnoreSignificantBits || isAddSExtable(Add, SE)) {
576 SmallVector<const SCEV *, 8> Ops;
577 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
579 const SCEV *Op = getExactSDiv(*I, RHS, SE,
580 IgnoreSignificantBits);
581 if (!Op) return nullptr;
584 return SE.getAddExpr(Ops);
589 // Check for a multiply operand that we can pull RHS out of.
590 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS)) {
591 if (IgnoreSignificantBits || isMulSExtable(Mul, SE)) {
592 SmallVector<const SCEV *, 4> Ops;
594 for (SCEVMulExpr::op_iterator I = Mul->op_begin(), E = Mul->op_end();
598 if (const SCEV *Q = getExactSDiv(S, RHS, SE,
599 IgnoreSignificantBits)) {
605 return Found ? SE.getMulExpr(Ops) : nullptr;
610 // Otherwise we don't know.
614 /// ExtractImmediate - If S involves the addition of a constant integer value,
615 /// return that integer value, and mutate S to point to a new SCEV with that
617 static int64_t ExtractImmediate(const SCEV *&S, ScalarEvolution &SE) {
618 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
619 if (C->getValue()->getValue().getMinSignedBits() <= 64) {
620 S = SE.getConstant(C->getType(), 0);
621 return C->getValue()->getSExtValue();
623 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
624 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
625 int64_t Result = ExtractImmediate(NewOps.front(), SE);
627 S = SE.getAddExpr(NewOps);
629 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
630 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
631 int64_t Result = ExtractImmediate(NewOps.front(), SE);
633 S = SE.getAddRecExpr(NewOps, AR->getLoop(),
634 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
641 /// ExtractSymbol - If S involves the addition of a GlobalValue address,
642 /// return that symbol, and mutate S to point to a new SCEV with that
644 static GlobalValue *ExtractSymbol(const SCEV *&S, ScalarEvolution &SE) {
645 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
646 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) {
647 S = SE.getConstant(GV->getType(), 0);
650 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
651 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
652 GlobalValue *Result = ExtractSymbol(NewOps.back(), SE);
654 S = SE.getAddExpr(NewOps);
656 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
657 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
658 GlobalValue *Result = ExtractSymbol(NewOps.front(), SE);
660 S = SE.getAddRecExpr(NewOps, AR->getLoop(),
661 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
668 /// isAddressUse - Returns true if the specified instruction is using the
669 /// specified value as an address.
670 static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
671 bool isAddress = isa<LoadInst>(Inst);
672 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
673 if (SI->getOperand(1) == OperandVal)
675 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
676 // Addressing modes can also be folded into prefetches and a variety
678 switch (II->getIntrinsicID()) {
680 case Intrinsic::prefetch:
681 case Intrinsic::x86_sse_storeu_ps:
682 case Intrinsic::x86_sse2_storeu_pd:
683 case Intrinsic::x86_sse2_storeu_dq:
684 case Intrinsic::x86_sse2_storel_dq:
685 if (II->getArgOperand(0) == OperandVal)
693 /// getAccessType - Return the type of the memory being accessed.
694 static Type *getAccessType(const Instruction *Inst) {
695 Type *AccessTy = Inst->getType();
696 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst))
697 AccessTy = SI->getOperand(0)->getType();
698 else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
699 // Addressing modes can also be folded into prefetches and a variety
701 switch (II->getIntrinsicID()) {
703 case Intrinsic::x86_sse_storeu_ps:
704 case Intrinsic::x86_sse2_storeu_pd:
705 case Intrinsic::x86_sse2_storeu_dq:
706 case Intrinsic::x86_sse2_storel_dq:
707 AccessTy = II->getArgOperand(0)->getType();
712 // All pointers have the same requirements, so canonicalize them to an
713 // arbitrary pointer type to minimize variation.
714 if (PointerType *PTy = dyn_cast<PointerType>(AccessTy))
715 AccessTy = PointerType::get(IntegerType::get(PTy->getContext(), 1),
716 PTy->getAddressSpace());
721 /// isExistingPhi - Return true if this AddRec is already a phi in its loop.
722 static bool isExistingPhi(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
723 for (BasicBlock::iterator I = AR->getLoop()->getHeader()->begin();
724 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
725 if (SE.isSCEVable(PN->getType()) &&
726 (SE.getEffectiveSCEVType(PN->getType()) ==
727 SE.getEffectiveSCEVType(AR->getType())) &&
728 SE.getSCEV(PN) == AR)
734 /// Check if expanding this expression is likely to incur significant cost. This
735 /// is tricky because SCEV doesn't track which expressions are actually computed
736 /// by the current IR.
738 /// We currently allow expansion of IV increments that involve adds,
739 /// multiplication by constants, and AddRecs from existing phis.
741 /// TODO: Allow UDivExpr if we can find an existing IV increment that is an
742 /// obvious multiple of the UDivExpr.
743 static bool isHighCostExpansion(const SCEV *S,
744 SmallPtrSetImpl<const SCEV*> &Processed,
745 ScalarEvolution &SE) {
746 // Zero/One operand expressions
747 switch (S->getSCEVType()) {
752 return isHighCostExpansion(cast<SCEVTruncateExpr>(S)->getOperand(),
755 return isHighCostExpansion(cast<SCEVZeroExtendExpr>(S)->getOperand(),
758 return isHighCostExpansion(cast<SCEVSignExtendExpr>(S)->getOperand(),
762 if (!Processed.insert(S).second)
765 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
766 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
768 if (isHighCostExpansion(*I, Processed, SE))
774 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
775 if (Mul->getNumOperands() == 2) {
776 // Multiplication by a constant is ok
777 if (isa<SCEVConstant>(Mul->getOperand(0)))
778 return isHighCostExpansion(Mul->getOperand(1), Processed, SE);
780 // If we have the value of one operand, check if an existing
781 // multiplication already generates this expression.
782 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Mul->getOperand(1))) {
783 Value *UVal = U->getValue();
784 for (User *UR : UVal->users()) {
785 // If U is a constant, it may be used by a ConstantExpr.
786 Instruction *UI = dyn_cast<Instruction>(UR);
787 if (UI && UI->getOpcode() == Instruction::Mul &&
788 SE.isSCEVable(UI->getType())) {
789 return SE.getSCEV(UI) == Mul;
796 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
797 if (isExistingPhi(AR, SE))
801 // Fow now, consider any other type of expression (div/mul/min/max) high cost.
805 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
806 /// specified set are trivially dead, delete them and see if this makes any of
807 /// their operands subsequently dead.
809 DeleteTriviallyDeadInstructions(SmallVectorImpl<WeakVH> &DeadInsts) {
810 bool Changed = false;
812 while (!DeadInsts.empty()) {
813 Value *V = DeadInsts.pop_back_val();
814 Instruction *I = dyn_cast_or_null<Instruction>(V);
816 if (!I || !isInstructionTriviallyDead(I))
819 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
820 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
823 DeadInsts.push_back(U);
826 I->eraseFromParent();
837 /// \brief Check if the addressing mode defined by \p F is completely
838 /// folded in \p LU at isel time.
839 /// This includes address-mode folding and special icmp tricks.
840 /// This function returns true if \p LU can accommodate what \p F
841 /// defines and up to 1 base + 1 scaled + offset.
842 /// In other words, if \p F has several base registers, this function may
843 /// still return true. Therefore, users still need to account for
844 /// additional base registers and/or unfolded offsets to derive an
845 /// accurate cost model.
846 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
847 const LSRUse &LU, const Formula &F);
848 // Get the cost of the scaling factor used in F for LU.
849 static unsigned getScalingFactorCost(const TargetTransformInfo &TTI,
850 const LSRUse &LU, const Formula &F);
854 /// Cost - This class is used to measure and compare candidate formulae.
856 /// TODO: Some of these could be merged. Also, a lexical ordering
857 /// isn't always optimal.
861 unsigned NumBaseAdds;
868 : NumRegs(0), AddRecCost(0), NumIVMuls(0), NumBaseAdds(0), ImmCost(0),
869 SetupCost(0), ScaleCost(0) {}
871 bool operator<(const Cost &Other) const;
876 // Once any of the metrics loses, they must all remain losers.
878 return ((NumRegs | AddRecCost | NumIVMuls | NumBaseAdds
879 | ImmCost | SetupCost | ScaleCost) != ~0u)
880 || ((NumRegs & AddRecCost & NumIVMuls & NumBaseAdds
881 & ImmCost & SetupCost & ScaleCost) == ~0u);
886 assert(isValid() && "invalid cost");
887 return NumRegs == ~0u;
890 void RateFormula(const TargetTransformInfo &TTI,
892 SmallPtrSetImpl<const SCEV *> &Regs,
893 const DenseSet<const SCEV *> &VisitedRegs,
895 const SmallVectorImpl<int64_t> &Offsets,
896 ScalarEvolution &SE, DominatorTree &DT,
898 SmallPtrSetImpl<const SCEV *> *LoserRegs = nullptr);
900 void print(raw_ostream &OS) const;
904 void RateRegister(const SCEV *Reg,
905 SmallPtrSetImpl<const SCEV *> &Regs,
907 ScalarEvolution &SE, DominatorTree &DT);
908 void RatePrimaryRegister(const SCEV *Reg,
909 SmallPtrSetImpl<const SCEV *> &Regs,
911 ScalarEvolution &SE, DominatorTree &DT,
912 SmallPtrSetImpl<const SCEV *> *LoserRegs);
917 /// RateRegister - Tally up interesting quantities from the given register.
918 void Cost::RateRegister(const SCEV *Reg,
919 SmallPtrSetImpl<const SCEV *> &Regs,
921 ScalarEvolution &SE, DominatorTree &DT) {
922 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Reg)) {
923 // If this is an addrec for another loop, don't second-guess its addrec phi
924 // nodes. LSR isn't currently smart enough to reason about more than one
925 // loop at a time. LSR has already run on inner loops, will not run on outer
926 // loops, and cannot be expected to change sibling loops.
927 if (AR->getLoop() != L) {
928 // If the AddRec exists, consider it's register free and leave it alone.
929 if (isExistingPhi(AR, SE))
932 // Otherwise, do not consider this formula at all.
936 AddRecCost += 1; /// TODO: This should be a function of the stride.
938 // Add the step value register, if it needs one.
939 // TODO: The non-affine case isn't precisely modeled here.
940 if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1))) {
941 if (!Regs.count(AR->getOperand(1))) {
942 RateRegister(AR->getOperand(1), Regs, L, SE, DT);
950 // Rough heuristic; favor registers which don't require extra setup
951 // instructions in the preheader.
952 if (!isa<SCEVUnknown>(Reg) &&
953 !isa<SCEVConstant>(Reg) &&
954 !(isa<SCEVAddRecExpr>(Reg) &&
955 (isa<SCEVUnknown>(cast<SCEVAddRecExpr>(Reg)->getStart()) ||
956 isa<SCEVConstant>(cast<SCEVAddRecExpr>(Reg)->getStart()))))
959 NumIVMuls += isa<SCEVMulExpr>(Reg) &&
960 SE.hasComputableLoopEvolution(Reg, L);
963 /// RatePrimaryRegister - Record this register in the set. If we haven't seen it
964 /// before, rate it. Optional LoserRegs provides a way to declare any formula
965 /// that refers to one of those regs an instant loser.
966 void Cost::RatePrimaryRegister(const SCEV *Reg,
967 SmallPtrSetImpl<const SCEV *> &Regs,
969 ScalarEvolution &SE, DominatorTree &DT,
970 SmallPtrSetImpl<const SCEV *> *LoserRegs) {
971 if (LoserRegs && LoserRegs->count(Reg)) {
975 if (Regs.insert(Reg).second) {
976 RateRegister(Reg, Regs, L, SE, DT);
977 if (LoserRegs && isLoser())
978 LoserRegs->insert(Reg);
982 void Cost::RateFormula(const TargetTransformInfo &TTI,
984 SmallPtrSetImpl<const SCEV *> &Regs,
985 const DenseSet<const SCEV *> &VisitedRegs,
987 const SmallVectorImpl<int64_t> &Offsets,
988 ScalarEvolution &SE, DominatorTree &DT,
990 SmallPtrSetImpl<const SCEV *> *LoserRegs) {
991 assert(F.isCanonical() && "Cost is accurate only for canonical formula");
992 // Tally up the registers.
993 if (const SCEV *ScaledReg = F.ScaledReg) {
994 if (VisitedRegs.count(ScaledReg)) {
998 RatePrimaryRegister(ScaledReg, Regs, L, SE, DT, LoserRegs);
1002 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
1003 E = F.BaseRegs.end(); I != E; ++I) {
1004 const SCEV *BaseReg = *I;
1005 if (VisitedRegs.count(BaseReg)) {
1009 RatePrimaryRegister(BaseReg, Regs, L, SE, DT, LoserRegs);
1014 // Determine how many (unfolded) adds we'll need inside the loop.
1015 size_t NumBaseParts = F.getNumRegs();
1016 if (NumBaseParts > 1)
1017 // Do not count the base and a possible second register if the target
1018 // allows to fold 2 registers.
1020 NumBaseParts - (1 + (F.Scale && isAMCompletelyFolded(TTI, LU, F)));
1021 NumBaseAdds += (F.UnfoldedOffset != 0);
1023 // Accumulate non-free scaling amounts.
1024 ScaleCost += getScalingFactorCost(TTI, LU, F);
1026 // Tally up the non-zero immediates.
1027 for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
1028 E = Offsets.end(); I != E; ++I) {
1029 int64_t Offset = (uint64_t)*I + F.BaseOffset;
1031 ImmCost += 64; // Handle symbolic values conservatively.
1032 // TODO: This should probably be the pointer size.
1033 else if (Offset != 0)
1034 ImmCost += APInt(64, Offset, true).getMinSignedBits();
1036 assert(isValid() && "invalid cost");
1039 /// Lose - Set this cost to a losing value.
1050 /// operator< - Choose the lower cost.
1051 bool Cost::operator<(const Cost &Other) const {
1052 return std::tie(NumRegs, AddRecCost, NumIVMuls, NumBaseAdds, ScaleCost,
1053 ImmCost, SetupCost) <
1054 std::tie(Other.NumRegs, Other.AddRecCost, Other.NumIVMuls,
1055 Other.NumBaseAdds, Other.ScaleCost, Other.ImmCost,
1059 void Cost::print(raw_ostream &OS) const {
1060 OS << NumRegs << " reg" << (NumRegs == 1 ? "" : "s");
1061 if (AddRecCost != 0)
1062 OS << ", with addrec cost " << AddRecCost;
1064 OS << ", plus " << NumIVMuls << " IV mul" << (NumIVMuls == 1 ? "" : "s");
1065 if (NumBaseAdds != 0)
1066 OS << ", plus " << NumBaseAdds << " base add"
1067 << (NumBaseAdds == 1 ? "" : "s");
1069 OS << ", plus " << ScaleCost << " scale cost";
1071 OS << ", plus " << ImmCost << " imm cost";
1073 OS << ", plus " << SetupCost << " setup cost";
1076 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1077 void Cost::dump() const {
1078 print(errs()); errs() << '\n';
1084 /// LSRFixup - An operand value in an instruction which is to be replaced
1085 /// with some equivalent, possibly strength-reduced, replacement.
1087 /// UserInst - The instruction which will be updated.
1088 Instruction *UserInst;
1090 /// OperandValToReplace - The operand of the instruction which will
1091 /// be replaced. The operand may be used more than once; every instance
1092 /// will be replaced.
1093 Value *OperandValToReplace;
1095 /// PostIncLoops - If this user is to use the post-incremented value of an
1096 /// induction variable, this variable is non-null and holds the loop
1097 /// associated with the induction variable.
1098 PostIncLoopSet PostIncLoops;
1100 /// LUIdx - The index of the LSRUse describing the expression which
1101 /// this fixup needs, minus an offset (below).
1104 /// Offset - A constant offset to be added to the LSRUse expression.
1105 /// This allows multiple fixups to share the same LSRUse with different
1106 /// offsets, for example in an unrolled loop.
1109 bool isUseFullyOutsideLoop(const Loop *L) const;
1113 void print(raw_ostream &OS) const;
1119 LSRFixup::LSRFixup()
1120 : UserInst(nullptr), OperandValToReplace(nullptr), LUIdx(~size_t(0)),
1123 /// isUseFullyOutsideLoop - Test whether this fixup always uses its
1124 /// value outside of the given loop.
1125 bool LSRFixup::isUseFullyOutsideLoop(const Loop *L) const {
1126 // PHI nodes use their value in their incoming blocks.
1127 if (const PHINode *PN = dyn_cast<PHINode>(UserInst)) {
1128 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1129 if (PN->getIncomingValue(i) == OperandValToReplace &&
1130 L->contains(PN->getIncomingBlock(i)))
1135 return !L->contains(UserInst);
1138 void LSRFixup::print(raw_ostream &OS) const {
1140 // Store is common and interesting enough to be worth special-casing.
1141 if (StoreInst *Store = dyn_cast<StoreInst>(UserInst)) {
1143 Store->getOperand(0)->printAsOperand(OS, /*PrintType=*/false);
1144 } else if (UserInst->getType()->isVoidTy())
1145 OS << UserInst->getOpcodeName();
1147 UserInst->printAsOperand(OS, /*PrintType=*/false);
1149 OS << ", OperandValToReplace=";
1150 OperandValToReplace->printAsOperand(OS, /*PrintType=*/false);
1152 for (PostIncLoopSet::const_iterator I = PostIncLoops.begin(),
1153 E = PostIncLoops.end(); I != E; ++I) {
1154 OS << ", PostIncLoop=";
1155 (*I)->getHeader()->printAsOperand(OS, /*PrintType=*/false);
1158 if (LUIdx != ~size_t(0))
1159 OS << ", LUIdx=" << LUIdx;
1162 OS << ", Offset=" << Offset;
1165 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1166 void LSRFixup::dump() const {
1167 print(errs()); errs() << '\n';
1173 /// UniquifierDenseMapInfo - A DenseMapInfo implementation for holding
1174 /// DenseMaps and DenseSets of sorted SmallVectors of const SCEV*.
1175 struct UniquifierDenseMapInfo {
1176 static SmallVector<const SCEV *, 4> getEmptyKey() {
1177 SmallVector<const SCEV *, 4> V;
1178 V.push_back(reinterpret_cast<const SCEV *>(-1));
1182 static SmallVector<const SCEV *, 4> getTombstoneKey() {
1183 SmallVector<const SCEV *, 4> V;
1184 V.push_back(reinterpret_cast<const SCEV *>(-2));
1188 static unsigned getHashValue(const SmallVector<const SCEV *, 4> &V) {
1189 return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
1192 static bool isEqual(const SmallVector<const SCEV *, 4> &LHS,
1193 const SmallVector<const SCEV *, 4> &RHS) {
1198 /// LSRUse - This class holds the state that LSR keeps for each use in
1199 /// IVUsers, as well as uses invented by LSR itself. It includes information
1200 /// about what kinds of things can be folded into the user, information about
1201 /// the user itself, and information about how the use may be satisfied.
1202 /// TODO: Represent multiple users of the same expression in common?
1204 DenseSet<SmallVector<const SCEV *, 4>, UniquifierDenseMapInfo> Uniquifier;
1207 /// KindType - An enum for a kind of use, indicating what types of
1208 /// scaled and immediate operands it might support.
1210 Basic, ///< A normal use, with no folding.
1211 Special, ///< A special case of basic, allowing -1 scales.
1212 Address, ///< An address use; folding according to TargetLowering
1213 ICmpZero ///< An equality icmp with both operands folded into one.
1214 // TODO: Add a generic icmp too?
1217 typedef PointerIntPair<const SCEV *, 2, KindType> SCEVUseKindPair;
1222 SmallVector<int64_t, 8> Offsets;
1226 /// AllFixupsOutsideLoop - This records whether all of the fixups using this
1227 /// LSRUse are outside of the loop, in which case some special-case heuristics
1229 bool AllFixupsOutsideLoop;
1231 /// RigidFormula is set to true to guarantee that this use will be associated
1232 /// with a single formula--the one that initially matched. Some SCEV
1233 /// expressions cannot be expanded. This allows LSR to consider the registers
1234 /// used by those expressions without the need to expand them later after
1235 /// changing the formula.
1238 /// WidestFixupType - This records the widest use type for any fixup using
1239 /// this LSRUse. FindUseWithSimilarFormula can't consider uses with different
1240 /// max fixup widths to be equivalent, because the narrower one may be relying
1241 /// on the implicit truncation to truncate away bogus bits.
1242 Type *WidestFixupType;
1244 /// Formulae - A list of ways to build a value that can satisfy this user.
1245 /// After the list is populated, one of these is selected heuristically and
1246 /// used to formulate a replacement for OperandValToReplace in UserInst.
1247 SmallVector<Formula, 12> Formulae;
1249 /// Regs - The set of register candidates used by all formulae in this LSRUse.
1250 SmallPtrSet<const SCEV *, 4> Regs;
1252 LSRUse(KindType K, Type *T) : Kind(K), AccessTy(T),
1253 MinOffset(INT64_MAX),
1254 MaxOffset(INT64_MIN),
1255 AllFixupsOutsideLoop(true),
1256 RigidFormula(false),
1257 WidestFixupType(nullptr) {}
1259 bool HasFormulaWithSameRegs(const Formula &F) const;
1260 bool InsertFormula(const Formula &F);
1261 void DeleteFormula(Formula &F);
1262 void RecomputeRegs(size_t LUIdx, RegUseTracker &Reguses);
1264 void print(raw_ostream &OS) const;
1270 /// HasFormula - Test whether this use as a formula which has the same
1271 /// registers as the given formula.
1272 bool LSRUse::HasFormulaWithSameRegs(const Formula &F) const {
1273 SmallVector<const SCEV *, 4> Key = F.BaseRegs;
1274 if (F.ScaledReg) Key.push_back(F.ScaledReg);
1275 // Unstable sort by host order ok, because this is only used for uniquifying.
1276 std::sort(Key.begin(), Key.end());
1277 return Uniquifier.count(Key);
1280 /// InsertFormula - If the given formula has not yet been inserted, add it to
1281 /// the list, and return true. Return false otherwise.
1282 /// The formula must be in canonical form.
1283 bool LSRUse::InsertFormula(const Formula &F) {
1284 assert(F.isCanonical() && "Invalid canonical representation");
1286 if (!Formulae.empty() && RigidFormula)
1289 SmallVector<const SCEV *, 4> Key = F.BaseRegs;
1290 if (F.ScaledReg) Key.push_back(F.ScaledReg);
1291 // Unstable sort by host order ok, because this is only used for uniquifying.
1292 std::sort(Key.begin(), Key.end());
1294 if (!Uniquifier.insert(Key).second)
1297 // Using a register to hold the value of 0 is not profitable.
1298 assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&
1299 "Zero allocated in a scaled register!");
1301 for (SmallVectorImpl<const SCEV *>::const_iterator I =
1302 F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I)
1303 assert(!(*I)->isZero() && "Zero allocated in a base register!");
1306 // Add the formula to the list.
1307 Formulae.push_back(F);
1309 // Record registers now being used by this use.
1310 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
1312 Regs.insert(F.ScaledReg);
1317 /// DeleteFormula - Remove the given formula from this use's list.
1318 void LSRUse::DeleteFormula(Formula &F) {
1319 if (&F != &Formulae.back())
1320 std::swap(F, Formulae.back());
1321 Formulae.pop_back();
1324 /// RecomputeRegs - Recompute the Regs field, and update RegUses.
1325 void LSRUse::RecomputeRegs(size_t LUIdx, RegUseTracker &RegUses) {
1326 // Now that we've filtered out some formulae, recompute the Regs set.
1327 SmallPtrSet<const SCEV *, 4> OldRegs = std::move(Regs);
1329 for (const Formula &F : Formulae) {
1330 if (F.ScaledReg) Regs.insert(F.ScaledReg);
1331 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
1334 // Update the RegTracker.
1335 for (const SCEV *S : OldRegs)
1337 RegUses.DropRegister(S, LUIdx);
1340 void LSRUse::print(raw_ostream &OS) const {
1341 OS << "LSR Use: Kind=";
1343 case Basic: OS << "Basic"; break;
1344 case Special: OS << "Special"; break;
1345 case ICmpZero: OS << "ICmpZero"; break;
1347 OS << "Address of ";
1348 if (AccessTy->isPointerTy())
1349 OS << "pointer"; // the full pointer type could be really verbose
1354 OS << ", Offsets={";
1355 for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
1356 E = Offsets.end(); I != E; ++I) {
1358 if (std::next(I) != E)
1363 if (AllFixupsOutsideLoop)
1364 OS << ", all-fixups-outside-loop";
1366 if (WidestFixupType)
1367 OS << ", widest fixup type: " << *WidestFixupType;
1370 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1371 void LSRUse::dump() const {
1372 print(errs()); errs() << '\n';
1376 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1377 LSRUse::KindType Kind, Type *AccessTy,
1378 GlobalValue *BaseGV, int64_t BaseOffset,
1379 bool HasBaseReg, int64_t Scale) {
1381 case LSRUse::Address:
1382 return TTI.isLegalAddressingMode(AccessTy, BaseGV, BaseOffset, HasBaseReg, Scale);
1384 case LSRUse::ICmpZero:
1385 // There's not even a target hook for querying whether it would be legal to
1386 // fold a GV into an ICmp.
1390 // ICmp only has two operands; don't allow more than two non-trivial parts.
1391 if (Scale != 0 && HasBaseReg && BaseOffset != 0)
1394 // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by
1395 // putting the scaled register in the other operand of the icmp.
1396 if (Scale != 0 && Scale != -1)
1399 // If we have low-level target information, ask the target if it can fold an
1400 // integer immediate on an icmp.
1401 if (BaseOffset != 0) {
1403 // ICmpZero BaseReg + BaseOffset => ICmp BaseReg, -BaseOffset
1404 // ICmpZero -1*ScaleReg + BaseOffset => ICmp ScaleReg, BaseOffset
1405 // Offs is the ICmp immediate.
1407 // The cast does the right thing with INT64_MIN.
1408 BaseOffset = -(uint64_t)BaseOffset;
1409 return TTI.isLegalICmpImmediate(BaseOffset);
1412 // ICmpZero BaseReg + -1*ScaleReg => ICmp BaseReg, ScaleReg
1416 // Only handle single-register values.
1417 return !BaseGV && Scale == 0 && BaseOffset == 0;
1419 case LSRUse::Special:
1420 // Special case Basic to handle -1 scales.
1421 return !BaseGV && (Scale == 0 || Scale == -1) && BaseOffset == 0;
1424 llvm_unreachable("Invalid LSRUse Kind!");
1427 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1428 int64_t MinOffset, int64_t MaxOffset,
1429 LSRUse::KindType Kind, Type *AccessTy,
1430 GlobalValue *BaseGV, int64_t BaseOffset,
1431 bool HasBaseReg, int64_t Scale) {
1432 // Check for overflow.
1433 if (((int64_t)((uint64_t)BaseOffset + MinOffset) > BaseOffset) !=
1436 MinOffset = (uint64_t)BaseOffset + MinOffset;
1437 if (((int64_t)((uint64_t)BaseOffset + MaxOffset) > BaseOffset) !=
1440 MaxOffset = (uint64_t)BaseOffset + MaxOffset;
1442 return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MinOffset,
1443 HasBaseReg, Scale) &&
1444 isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MaxOffset,
1448 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1449 int64_t MinOffset, int64_t MaxOffset,
1450 LSRUse::KindType Kind, Type *AccessTy,
1452 // For the purpose of isAMCompletelyFolded either having a canonical formula
1453 // or a scale not equal to zero is correct.
1454 // Problems may arise from non canonical formulae having a scale == 0.
1455 // Strictly speaking it would best to just rely on canonical formulae.
1456 // However, when we generate the scaled formulae, we first check that the
1457 // scaling factor is profitable before computing the actual ScaledReg for
1458 // compile time sake.
1459 assert((F.isCanonical() || F.Scale != 0));
1460 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy,
1461 F.BaseGV, F.BaseOffset, F.HasBaseReg, F.Scale);
1464 /// isLegalUse - Test whether we know how to expand the current formula.
1465 static bool isLegalUse(const TargetTransformInfo &TTI, int64_t MinOffset,
1466 int64_t MaxOffset, LSRUse::KindType Kind, Type *AccessTy,
1467 GlobalValue *BaseGV, int64_t BaseOffset, bool HasBaseReg,
1469 // We know how to expand completely foldable formulae.
1470 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV,
1471 BaseOffset, HasBaseReg, Scale) ||
1472 // Or formulae that use a base register produced by a sum of base
1475 isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy,
1476 BaseGV, BaseOffset, true, 0));
1479 static bool isLegalUse(const TargetTransformInfo &TTI, int64_t MinOffset,
1480 int64_t MaxOffset, LSRUse::KindType Kind, Type *AccessTy,
1482 return isLegalUse(TTI, MinOffset, MaxOffset, Kind, AccessTy, F.BaseGV,
1483 F.BaseOffset, F.HasBaseReg, F.Scale);
1486 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1487 const LSRUse &LU, const Formula &F) {
1488 return isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind,
1489 LU.AccessTy, F.BaseGV, F.BaseOffset, F.HasBaseReg,
1493 static unsigned getScalingFactorCost(const TargetTransformInfo &TTI,
1494 const LSRUse &LU, const Formula &F) {
1498 // If the use is not completely folded in that instruction, we will have to
1499 // pay an extra cost only for scale != 1.
1500 if (!isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind,
1502 return F.Scale != 1;
1505 case LSRUse::Address: {
1506 // Check the scaling factor cost with both the min and max offsets.
1507 int ScaleCostMinOffset =
1508 TTI.getScalingFactorCost(LU.AccessTy, F.BaseGV,
1509 F.BaseOffset + LU.MinOffset,
1510 F.HasBaseReg, F.Scale);
1511 int ScaleCostMaxOffset =
1512 TTI.getScalingFactorCost(LU.AccessTy, F.BaseGV,
1513 F.BaseOffset + LU.MaxOffset,
1514 F.HasBaseReg, F.Scale);
1516 assert(ScaleCostMinOffset >= 0 && ScaleCostMaxOffset >= 0 &&
1517 "Legal addressing mode has an illegal cost!");
1518 return std::max(ScaleCostMinOffset, ScaleCostMaxOffset);
1520 case LSRUse::ICmpZero:
1522 case LSRUse::Special:
1523 // The use is completely folded, i.e., everything is folded into the
1528 llvm_unreachable("Invalid LSRUse Kind!");
1531 static bool isAlwaysFoldable(const TargetTransformInfo &TTI,
1532 LSRUse::KindType Kind, Type *AccessTy,
1533 GlobalValue *BaseGV, int64_t BaseOffset,
1535 // Fast-path: zero is always foldable.
1536 if (BaseOffset == 0 && !BaseGV) return true;
1538 // Conservatively, create an address with an immediate and a
1539 // base and a scale.
1540 int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1542 // Canonicalize a scale of 1 to a base register if the formula doesn't
1543 // already have a base register.
1544 if (!HasBaseReg && Scale == 1) {
1549 return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, BaseOffset,
1553 static bool isAlwaysFoldable(const TargetTransformInfo &TTI,
1554 ScalarEvolution &SE, int64_t MinOffset,
1555 int64_t MaxOffset, LSRUse::KindType Kind,
1556 Type *AccessTy, const SCEV *S, bool HasBaseReg) {
1557 // Fast-path: zero is always foldable.
1558 if (S->isZero()) return true;
1560 // Conservatively, create an address with an immediate and a
1561 // base and a scale.
1562 int64_t BaseOffset = ExtractImmediate(S, SE);
1563 GlobalValue *BaseGV = ExtractSymbol(S, SE);
1565 // If there's anything else involved, it's not foldable.
1566 if (!S->isZero()) return false;
1568 // Fast-path: zero is always foldable.
1569 if (BaseOffset == 0 && !BaseGV) return true;
1571 // Conservatively, create an address with an immediate and a
1572 // base and a scale.
1573 int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1575 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV,
1576 BaseOffset, HasBaseReg, Scale);
1581 /// IVInc - An individual increment in a Chain of IV increments.
1582 /// Relate an IV user to an expression that computes the IV it uses from the IV
1583 /// used by the previous link in the Chain.
1585 /// For the head of a chain, IncExpr holds the absolute SCEV expression for the
1586 /// original IVOperand. The head of the chain's IVOperand is only valid during
1587 /// chain collection, before LSR replaces IV users. During chain generation,
1588 /// IncExpr can be used to find the new IVOperand that computes the same
1591 Instruction *UserInst;
1593 const SCEV *IncExpr;
1595 IVInc(Instruction *U, Value *O, const SCEV *E):
1596 UserInst(U), IVOperand(O), IncExpr(E) {}
1599 // IVChain - The list of IV increments in program order.
1600 // We typically add the head of a chain without finding subsequent links.
1602 SmallVector<IVInc,1> Incs;
1603 const SCEV *ExprBase;
1605 IVChain() : ExprBase(nullptr) {}
1607 IVChain(const IVInc &Head, const SCEV *Base)
1608 : Incs(1, Head), ExprBase(Base) {}
1610 typedef SmallVectorImpl<IVInc>::const_iterator const_iterator;
1612 // begin - return the first increment in the chain.
1613 const_iterator begin() const {
1614 assert(!Incs.empty());
1615 return std::next(Incs.begin());
1617 const_iterator end() const {
1621 // hasIncs - Returns true if this chain contains any increments.
1622 bool hasIncs() const { return Incs.size() >= 2; }
1624 // add - Add an IVInc to the end of this chain.
1625 void add(const IVInc &X) { Incs.push_back(X); }
1627 // tailUserInst - Returns the last UserInst in the chain.
1628 Instruction *tailUserInst() const { return Incs.back().UserInst; }
1630 // isProfitableIncrement - Returns true if IncExpr can be profitably added to
1632 bool isProfitableIncrement(const SCEV *OperExpr,
1633 const SCEV *IncExpr,
1637 /// ChainUsers - Helper for CollectChains to track multiple IV increment uses.
1638 /// Distinguish between FarUsers that definitely cross IV increments and
1639 /// NearUsers that may be used between IV increments.
1641 SmallPtrSet<Instruction*, 4> FarUsers;
1642 SmallPtrSet<Instruction*, 4> NearUsers;
1645 /// LSRInstance - This class holds state for the main loop strength reduction
1649 ScalarEvolution &SE;
1652 const TargetTransformInfo &TTI;
1656 /// IVIncInsertPos - This is the insert position that the current loop's
1657 /// induction variable increment should be placed. In simple loops, this is
1658 /// the latch block's terminator. But in more complicated cases, this is a
1659 /// position which will dominate all the in-loop post-increment users.
1660 Instruction *IVIncInsertPos;
1662 /// Factors - Interesting factors between use strides.
1663 SmallSetVector<int64_t, 8> Factors;
1665 /// Types - Interesting use types, to facilitate truncation reuse.
1666 SmallSetVector<Type *, 4> Types;
1668 /// Fixups - The list of operands which are to be replaced.
1669 SmallVector<LSRFixup, 16> Fixups;
1671 /// Uses - The list of interesting uses.
1672 SmallVector<LSRUse, 16> Uses;
1674 /// RegUses - Track which uses use which register candidates.
1675 RegUseTracker RegUses;
1677 // Limit the number of chains to avoid quadratic behavior. We don't expect to
1678 // have more than a few IV increment chains in a loop. Missing a Chain falls
1679 // back to normal LSR behavior for those uses.
1680 static const unsigned MaxChains = 8;
1682 /// IVChainVec - IV users can form a chain of IV increments.
1683 SmallVector<IVChain, MaxChains> IVChainVec;
1685 /// IVIncSet - IV users that belong to profitable IVChains.
1686 SmallPtrSet<Use*, MaxChains> IVIncSet;
1688 void OptimizeShadowIV();
1689 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse);
1690 ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse);
1691 void OptimizeLoopTermCond();
1693 void ChainInstruction(Instruction *UserInst, Instruction *IVOper,
1694 SmallVectorImpl<ChainUsers> &ChainUsersVec);
1695 void FinalizeChain(IVChain &Chain);
1696 void CollectChains();
1697 void GenerateIVChain(const IVChain &Chain, SCEVExpander &Rewriter,
1698 SmallVectorImpl<WeakVH> &DeadInsts);
1700 void CollectInterestingTypesAndFactors();
1701 void CollectFixupsAndInitialFormulae();
1703 LSRFixup &getNewFixup() {
1704 Fixups.push_back(LSRFixup());
1705 return Fixups.back();
1708 // Support for sharing of LSRUses between LSRFixups.
1709 typedef DenseMap<LSRUse::SCEVUseKindPair, size_t> UseMapTy;
1712 bool reconcileNewOffset(LSRUse &LU, int64_t NewOffset, bool HasBaseReg,
1713 LSRUse::KindType Kind, Type *AccessTy);
1715 std::pair<size_t, int64_t> getUse(const SCEV *&Expr,
1716 LSRUse::KindType Kind,
1719 void DeleteUse(LSRUse &LU, size_t LUIdx);
1721 LSRUse *FindUseWithSimilarFormula(const Formula &F, const LSRUse &OrigLU);
1723 void InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
1724 void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
1725 void CountRegisters(const Formula &F, size_t LUIdx);
1726 bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F);
1728 void CollectLoopInvariantFixupsAndFormulae();
1730 void GenerateReassociations(LSRUse &LU, unsigned LUIdx, Formula Base,
1731 unsigned Depth = 0);
1733 void GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx,
1734 const Formula &Base, unsigned Depth,
1735 size_t Idx, bool IsScaledReg = false);
1736 void GenerateCombinations(LSRUse &LU, unsigned LUIdx, Formula Base);
1737 void GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx,
1738 const Formula &Base, size_t Idx,
1739 bool IsScaledReg = false);
1740 void GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1741 void GenerateConstantOffsetsImpl(LSRUse &LU, unsigned LUIdx,
1742 const Formula &Base,
1743 const SmallVectorImpl<int64_t> &Worklist,
1744 size_t Idx, bool IsScaledReg = false);
1745 void GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1746 void GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1747 void GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1748 void GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base);
1749 void GenerateCrossUseConstantOffsets();
1750 void GenerateAllReuseFormulae();
1752 void FilterOutUndesirableDedicatedRegisters();
1754 size_t EstimateSearchSpaceComplexity() const;
1755 void NarrowSearchSpaceByDetectingSupersets();
1756 void NarrowSearchSpaceByCollapsingUnrolledCode();
1757 void NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
1758 void NarrowSearchSpaceByPickingWinnerRegs();
1759 void NarrowSearchSpaceUsingHeuristics();
1761 void SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
1763 SmallVectorImpl<const Formula *> &Workspace,
1764 const Cost &CurCost,
1765 const SmallPtrSet<const SCEV *, 16> &CurRegs,
1766 DenseSet<const SCEV *> &VisitedRegs) const;
1767 void Solve(SmallVectorImpl<const Formula *> &Solution) const;
1769 BasicBlock::iterator
1770 HoistInsertPosition(BasicBlock::iterator IP,
1771 const SmallVectorImpl<Instruction *> &Inputs) const;
1772 BasicBlock::iterator
1773 AdjustInsertPositionForExpand(BasicBlock::iterator IP,
1776 SCEVExpander &Rewriter) const;
1778 Value *Expand(const LSRFixup &LF,
1780 BasicBlock::iterator IP,
1781 SCEVExpander &Rewriter,
1782 SmallVectorImpl<WeakVH> &DeadInsts) const;
1783 void RewriteForPHI(PHINode *PN, const LSRFixup &LF,
1785 SCEVExpander &Rewriter,
1786 SmallVectorImpl<WeakVH> &DeadInsts,
1788 void Rewrite(const LSRFixup &LF,
1790 SCEVExpander &Rewriter,
1791 SmallVectorImpl<WeakVH> &DeadInsts,
1793 void ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
1797 LSRInstance(Loop *L, Pass *P);
1799 bool getChanged() const { return Changed; }
1801 void print_factors_and_types(raw_ostream &OS) const;
1802 void print_fixups(raw_ostream &OS) const;
1803 void print_uses(raw_ostream &OS) const;
1804 void print(raw_ostream &OS) const;
1810 /// OptimizeShadowIV - If IV is used in a int-to-float cast
1811 /// inside the loop then try to eliminate the cast operation.
1812 void LSRInstance::OptimizeShadowIV() {
1813 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
1814 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1817 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end();
1818 UI != E; /* empty */) {
1819 IVUsers::const_iterator CandidateUI = UI;
1821 Instruction *ShadowUse = CandidateUI->getUser();
1822 Type *DestTy = nullptr;
1823 bool IsSigned = false;
1825 /* If shadow use is a int->float cast then insert a second IV
1826 to eliminate this cast.
1828 for (unsigned i = 0; i < n; ++i)
1834 for (unsigned i = 0; i < n; ++i, ++d)
1837 if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser())) {
1839 DestTy = UCast->getDestTy();
1841 else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser())) {
1843 DestTy = SCast->getDestTy();
1845 if (!DestTy) continue;
1847 // If target does not support DestTy natively then do not apply
1848 // this transformation.
1849 if (!TTI.isTypeLegal(DestTy)) continue;
1851 PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
1853 if (PH->getNumIncomingValues() != 2) continue;
1855 Type *SrcTy = PH->getType();
1856 int Mantissa = DestTy->getFPMantissaWidth();
1857 if (Mantissa == -1) continue;
1858 if ((int)SE.getTypeSizeInBits(SrcTy) > Mantissa)
1861 unsigned Entry, Latch;
1862 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
1870 ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
1871 if (!Init) continue;
1872 Constant *NewInit = ConstantFP::get(DestTy, IsSigned ?
1873 (double)Init->getSExtValue() :
1874 (double)Init->getZExtValue());
1876 BinaryOperator *Incr =
1877 dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
1878 if (!Incr) continue;
1879 if (Incr->getOpcode() != Instruction::Add
1880 && Incr->getOpcode() != Instruction::Sub)
1883 /* Initialize new IV, double d = 0.0 in above example. */
1884 ConstantInt *C = nullptr;
1885 if (Incr->getOperand(0) == PH)
1886 C = dyn_cast<ConstantInt>(Incr->getOperand(1));
1887 else if (Incr->getOperand(1) == PH)
1888 C = dyn_cast<ConstantInt>(Incr->getOperand(0));
1894 // Ignore negative constants, as the code below doesn't handle them
1895 // correctly. TODO: Remove this restriction.
1896 if (!C->getValue().isStrictlyPositive()) continue;
1898 /* Add new PHINode. */
1899 PHINode *NewPH = PHINode::Create(DestTy, 2, "IV.S.", PH);
1901 /* create new increment. '++d' in above example. */
1902 Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue());
1903 BinaryOperator *NewIncr =
1904 BinaryOperator::Create(Incr->getOpcode() == Instruction::Add ?
1905 Instruction::FAdd : Instruction::FSub,
1906 NewPH, CFP, "IV.S.next.", Incr);
1908 NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
1909 NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
1911 /* Remove cast operation */
1912 ShadowUse->replaceAllUsesWith(NewPH);
1913 ShadowUse->eraseFromParent();
1919 /// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
1920 /// set the IV user and stride information and return true, otherwise return
1922 bool LSRInstance::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse) {
1923 for (IVUsers::iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
1924 if (UI->getUser() == Cond) {
1925 // NOTE: we could handle setcc instructions with multiple uses here, but
1926 // InstCombine does it as well for simple uses, it's not clear that it
1927 // occurs enough in real life to handle.
1934 /// OptimizeMax - Rewrite the loop's terminating condition if it uses
1935 /// a max computation.
1937 /// This is a narrow solution to a specific, but acute, problem. For loops
1943 /// } while (++i < n);
1945 /// the trip count isn't just 'n', because 'n' might not be positive. And
1946 /// unfortunately this can come up even for loops where the user didn't use
1947 /// a C do-while loop. For example, seemingly well-behaved top-test loops
1948 /// will commonly be lowered like this:
1954 /// } while (++i < n);
1957 /// and then it's possible for subsequent optimization to obscure the if
1958 /// test in such a way that indvars can't find it.
1960 /// When indvars can't find the if test in loops like this, it creates a
1961 /// max expression, which allows it to give the loop a canonical
1962 /// induction variable:
1965 /// max = n < 1 ? 1 : n;
1968 /// } while (++i != max);
1970 /// Canonical induction variables are necessary because the loop passes
1971 /// are designed around them. The most obvious example of this is the
1972 /// LoopInfo analysis, which doesn't remember trip count values. It
1973 /// expects to be able to rediscover the trip count each time it is
1974 /// needed, and it does this using a simple analysis that only succeeds if
1975 /// the loop has a canonical induction variable.
1977 /// However, when it comes time to generate code, the maximum operation
1978 /// can be quite costly, especially if it's inside of an outer loop.
1980 /// This function solves this problem by detecting this type of loop and
1981 /// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
1982 /// the instructions for the maximum computation.
1984 ICmpInst *LSRInstance::OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse) {
1985 // Check that the loop matches the pattern we're looking for.
1986 if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
1987 Cond->getPredicate() != CmpInst::ICMP_NE)
1990 SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
1991 if (!Sel || !Sel->hasOneUse()) return Cond;
1993 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
1994 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1996 const SCEV *One = SE.getConstant(BackedgeTakenCount->getType(), 1);
1998 // Add one to the backedge-taken count to get the trip count.
1999 const SCEV *IterationCount = SE.getAddExpr(One, BackedgeTakenCount);
2000 if (IterationCount != SE.getSCEV(Sel)) return Cond;
2002 // Check for a max calculation that matches the pattern. There's no check
2003 // for ICMP_ULE here because the comparison would be with zero, which
2004 // isn't interesting.
2005 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
2006 const SCEVNAryExpr *Max = nullptr;
2007 if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(BackedgeTakenCount)) {
2008 Pred = ICmpInst::ICMP_SLE;
2010 } else if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(IterationCount)) {
2011 Pred = ICmpInst::ICMP_SLT;
2013 } else if (const SCEVUMaxExpr *U = dyn_cast<SCEVUMaxExpr>(IterationCount)) {
2014 Pred = ICmpInst::ICMP_ULT;
2021 // To handle a max with more than two operands, this optimization would
2022 // require additional checking and setup.
2023 if (Max->getNumOperands() != 2)
2026 const SCEV *MaxLHS = Max->getOperand(0);
2027 const SCEV *MaxRHS = Max->getOperand(1);
2029 // ScalarEvolution canonicalizes constants to the left. For < and >, look
2030 // for a comparison with 1. For <= and >=, a comparison with zero.
2032 (ICmpInst::isTrueWhenEqual(Pred) ? !MaxLHS->isZero() : (MaxLHS != One)))
2035 // Check the relevant induction variable for conformance to
2037 const SCEV *IV = SE.getSCEV(Cond->getOperand(0));
2038 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
2039 if (!AR || !AR->isAffine() ||
2040 AR->getStart() != One ||
2041 AR->getStepRecurrence(SE) != One)
2044 assert(AR->getLoop() == L &&
2045 "Loop condition operand is an addrec in a different loop!");
2047 // Check the right operand of the select, and remember it, as it will
2048 // be used in the new comparison instruction.
2049 Value *NewRHS = nullptr;
2050 if (ICmpInst::isTrueWhenEqual(Pred)) {
2051 // Look for n+1, and grab n.
2052 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(1)))
2053 if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1)))
2054 if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS)
2055 NewRHS = BO->getOperand(0);
2056 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(2)))
2057 if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1)))
2058 if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS)
2059 NewRHS = BO->getOperand(0);
2062 } else if (SE.getSCEV(Sel->getOperand(1)) == MaxRHS)
2063 NewRHS = Sel->getOperand(1);
2064 else if (SE.getSCEV(Sel->getOperand(2)) == MaxRHS)
2065 NewRHS = Sel->getOperand(2);
2066 else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(MaxRHS))
2067 NewRHS = SU->getValue();
2069 // Max doesn't match expected pattern.
2072 // Determine the new comparison opcode. It may be signed or unsigned,
2073 // and the original comparison may be either equality or inequality.
2074 if (Cond->getPredicate() == CmpInst::ICMP_EQ)
2075 Pred = CmpInst::getInversePredicate(Pred);
2077 // Ok, everything looks ok to change the condition into an SLT or SGE and
2078 // delete the max calculation.
2080 new ICmpInst(Cond, Pred, Cond->getOperand(0), NewRHS, "scmp");
2082 // Delete the max calculation instructions.
2083 Cond->replaceAllUsesWith(NewCond);
2084 CondUse->setUser(NewCond);
2085 Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
2086 Cond->eraseFromParent();
2087 Sel->eraseFromParent();
2088 if (Cmp->use_empty())
2089 Cmp->eraseFromParent();
2093 /// OptimizeLoopTermCond - Change loop terminating condition to use the
2094 /// postinc iv when possible.
2096 LSRInstance::OptimizeLoopTermCond() {
2097 SmallPtrSet<Instruction *, 4> PostIncs;
2099 BasicBlock *LatchBlock = L->getLoopLatch();
2100 SmallVector<BasicBlock*, 8> ExitingBlocks;
2101 L->getExitingBlocks(ExitingBlocks);
2103 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
2104 BasicBlock *ExitingBlock = ExitingBlocks[i];
2106 // Get the terminating condition for the loop if possible. If we
2107 // can, we want to change it to use a post-incremented version of its
2108 // induction variable, to allow coalescing the live ranges for the IV into
2109 // one register value.
2111 BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2114 // FIXME: Overly conservative, termination condition could be an 'or' etc..
2115 if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
2118 // Search IVUsesByStride to find Cond's IVUse if there is one.
2119 IVStrideUse *CondUse = nullptr;
2120 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
2121 if (!FindIVUserForCond(Cond, CondUse))
2124 // If the trip count is computed in terms of a max (due to ScalarEvolution
2125 // being unable to find a sufficient guard, for example), change the loop
2126 // comparison to use SLT or ULT instead of NE.
2127 // One consequence of doing this now is that it disrupts the count-down
2128 // optimization. That's not always a bad thing though, because in such
2129 // cases it may still be worthwhile to avoid a max.
2130 Cond = OptimizeMax(Cond, CondUse);
2132 // If this exiting block dominates the latch block, it may also use
2133 // the post-inc value if it won't be shared with other uses.
2134 // Check for dominance.
2135 if (!DT.dominates(ExitingBlock, LatchBlock))
2138 // Conservatively avoid trying to use the post-inc value in non-latch
2139 // exits if there may be pre-inc users in intervening blocks.
2140 if (LatchBlock != ExitingBlock)
2141 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
2142 // Test if the use is reachable from the exiting block. This dominator
2143 // query is a conservative approximation of reachability.
2144 if (&*UI != CondUse &&
2145 !DT.properlyDominates(UI->getUser()->getParent(), ExitingBlock)) {
2146 // Conservatively assume there may be reuse if the quotient of their
2147 // strides could be a legal scale.
2148 const SCEV *A = IU.getStride(*CondUse, L);
2149 const SCEV *B = IU.getStride(*UI, L);
2150 if (!A || !B) continue;
2151 if (SE.getTypeSizeInBits(A->getType()) !=
2152 SE.getTypeSizeInBits(B->getType())) {
2153 if (SE.getTypeSizeInBits(A->getType()) >
2154 SE.getTypeSizeInBits(B->getType()))
2155 B = SE.getSignExtendExpr(B, A->getType());
2157 A = SE.getSignExtendExpr(A, B->getType());
2159 if (const SCEVConstant *D =
2160 dyn_cast_or_null<SCEVConstant>(getExactSDiv(B, A, SE))) {
2161 const ConstantInt *C = D->getValue();
2162 // Stride of one or negative one can have reuse with non-addresses.
2163 if (C->isOne() || C->isAllOnesValue())
2164 goto decline_post_inc;
2165 // Avoid weird situations.
2166 if (C->getValue().getMinSignedBits() >= 64 ||
2167 C->getValue().isMinSignedValue())
2168 goto decline_post_inc;
2169 // Check for possible scaled-address reuse.
2170 Type *AccessTy = getAccessType(UI->getUser());
2171 int64_t Scale = C->getSExtValue();
2172 if (TTI.isLegalAddressingMode(AccessTy, /*BaseGV=*/ nullptr,
2174 /*HasBaseReg=*/ false, Scale))
2175 goto decline_post_inc;
2177 if (TTI.isLegalAddressingMode(AccessTy, /*BaseGV=*/ nullptr,
2179 /*HasBaseReg=*/ false, Scale))
2180 goto decline_post_inc;
2184 DEBUG(dbgs() << " Change loop exiting icmp to use postinc iv: "
2187 // It's possible for the setcc instruction to be anywhere in the loop, and
2188 // possible for it to have multiple users. If it is not immediately before
2189 // the exiting block branch, move it.
2190 if (&*++BasicBlock::iterator(Cond) != TermBr) {
2191 if (Cond->hasOneUse()) {
2192 Cond->moveBefore(TermBr);
2194 // Clone the terminating condition and insert into the loopend.
2195 ICmpInst *OldCond = Cond;
2196 Cond = cast<ICmpInst>(Cond->clone());
2197 Cond->setName(L->getHeader()->getName() + ".termcond");
2198 ExitingBlock->getInstList().insert(TermBr, Cond);
2200 // Clone the IVUse, as the old use still exists!
2201 CondUse = &IU.AddUser(Cond, CondUse->getOperandValToReplace());
2202 TermBr->replaceUsesOfWith(OldCond, Cond);
2206 // If we get to here, we know that we can transform the setcc instruction to
2207 // use the post-incremented version of the IV, allowing us to coalesce the
2208 // live ranges for the IV correctly.
2209 CondUse->transformToPostInc(L);
2212 PostIncs.insert(Cond);
2216 // Determine an insertion point for the loop induction variable increment. It
2217 // must dominate all the post-inc comparisons we just set up, and it must
2218 // dominate the loop latch edge.
2219 IVIncInsertPos = L->getLoopLatch()->getTerminator();
2220 for (Instruction *Inst : PostIncs) {
2222 DT.findNearestCommonDominator(IVIncInsertPos->getParent(),
2224 if (BB == Inst->getParent())
2225 IVIncInsertPos = Inst;
2226 else if (BB != IVIncInsertPos->getParent())
2227 IVIncInsertPos = BB->getTerminator();
2231 /// reconcileNewOffset - Determine if the given use can accommodate a fixup
2232 /// at the given offset and other details. If so, update the use and
2235 LSRInstance::reconcileNewOffset(LSRUse &LU, int64_t NewOffset, bool HasBaseReg,
2236 LSRUse::KindType Kind, Type *AccessTy) {
2237 int64_t NewMinOffset = LU.MinOffset;
2238 int64_t NewMaxOffset = LU.MaxOffset;
2239 Type *NewAccessTy = AccessTy;
2241 // Check for a mismatched kind. It's tempting to collapse mismatched kinds to
2242 // something conservative, however this can pessimize in the case that one of
2243 // the uses will have all its uses outside the loop, for example.
2244 if (LU.Kind != Kind)
2247 // Check for a mismatched access type, and fall back conservatively as needed.
2248 // TODO: Be less conservative when the type is similar and can use the same
2249 // addressing modes.
2250 if (Kind == LSRUse::Address && AccessTy != LU.AccessTy)
2251 NewAccessTy = Type::getVoidTy(AccessTy->getContext());
2253 // Conservatively assume HasBaseReg is true for now.
2254 if (NewOffset < LU.MinOffset) {
2255 if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr,
2256 LU.MaxOffset - NewOffset, HasBaseReg))
2258 NewMinOffset = NewOffset;
2259 } else if (NewOffset > LU.MaxOffset) {
2260 if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr,
2261 NewOffset - LU.MinOffset, HasBaseReg))
2263 NewMaxOffset = NewOffset;
2267 LU.MinOffset = NewMinOffset;
2268 LU.MaxOffset = NewMaxOffset;
2269 LU.AccessTy = NewAccessTy;
2270 if (NewOffset != LU.Offsets.back())
2271 LU.Offsets.push_back(NewOffset);
2275 /// getUse - Return an LSRUse index and an offset value for a fixup which
2276 /// needs the given expression, with the given kind and optional access type.
2277 /// Either reuse an existing use or create a new one, as needed.
2278 std::pair<size_t, int64_t>
2279 LSRInstance::getUse(const SCEV *&Expr,
2280 LSRUse::KindType Kind, Type *AccessTy) {
2281 const SCEV *Copy = Expr;
2282 int64_t Offset = ExtractImmediate(Expr, SE);
2284 // Basic uses can't accept any offset, for example.
2285 if (!isAlwaysFoldable(TTI, Kind, AccessTy, /*BaseGV=*/ nullptr,
2286 Offset, /*HasBaseReg=*/ true)) {
2291 std::pair<UseMapTy::iterator, bool> P =
2292 UseMap.insert(std::make_pair(LSRUse::SCEVUseKindPair(Expr, Kind), 0));
2294 // A use already existed with this base.
2295 size_t LUIdx = P.first->second;
2296 LSRUse &LU = Uses[LUIdx];
2297 if (reconcileNewOffset(LU, Offset, /*HasBaseReg=*/true, Kind, AccessTy))
2299 return std::make_pair(LUIdx, Offset);
2302 // Create a new use.
2303 size_t LUIdx = Uses.size();
2304 P.first->second = LUIdx;
2305 Uses.push_back(LSRUse(Kind, AccessTy));
2306 LSRUse &LU = Uses[LUIdx];
2308 // We don't need to track redundant offsets, but we don't need to go out
2309 // of our way here to avoid them.
2310 if (LU.Offsets.empty() || Offset != LU.Offsets.back())
2311 LU.Offsets.push_back(Offset);
2313 LU.MinOffset = Offset;
2314 LU.MaxOffset = Offset;
2315 return std::make_pair(LUIdx, Offset);
2318 /// DeleteUse - Delete the given use from the Uses list.
2319 void LSRInstance::DeleteUse(LSRUse &LU, size_t LUIdx) {
2320 if (&LU != &Uses.back())
2321 std::swap(LU, Uses.back());
2325 RegUses.SwapAndDropUse(LUIdx, Uses.size());
2328 /// FindUseWithFormula - Look for a use distinct from OrigLU which is has
2329 /// a formula that has the same registers as the given formula.
2331 LSRInstance::FindUseWithSimilarFormula(const Formula &OrigF,
2332 const LSRUse &OrigLU) {
2333 // Search all uses for the formula. This could be more clever.
2334 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2335 LSRUse &LU = Uses[LUIdx];
2336 // Check whether this use is close enough to OrigLU, to see whether it's
2337 // worthwhile looking through its formulae.
2338 // Ignore ICmpZero uses because they may contain formulae generated by
2339 // GenerateICmpZeroScales, in which case adding fixup offsets may
2341 if (&LU != &OrigLU &&
2342 LU.Kind != LSRUse::ICmpZero &&
2343 LU.Kind == OrigLU.Kind && OrigLU.AccessTy == LU.AccessTy &&
2344 LU.WidestFixupType == OrigLU.WidestFixupType &&
2345 LU.HasFormulaWithSameRegs(OrigF)) {
2346 // Scan through this use's formulae.
2347 for (SmallVectorImpl<Formula>::const_iterator I = LU.Formulae.begin(),
2348 E = LU.Formulae.end(); I != E; ++I) {
2349 const Formula &F = *I;
2350 // Check to see if this formula has the same registers and symbols
2352 if (F.BaseRegs == OrigF.BaseRegs &&
2353 F.ScaledReg == OrigF.ScaledReg &&
2354 F.BaseGV == OrigF.BaseGV &&
2355 F.Scale == OrigF.Scale &&
2356 F.UnfoldedOffset == OrigF.UnfoldedOffset) {
2357 if (F.BaseOffset == 0)
2359 // This is the formula where all the registers and symbols matched;
2360 // there aren't going to be any others. Since we declined it, we
2361 // can skip the rest of the formulae and proceed to the next LSRUse.
2368 // Nothing looked good.
2372 void LSRInstance::CollectInterestingTypesAndFactors() {
2373 SmallSetVector<const SCEV *, 4> Strides;
2375 // Collect interesting types and strides.
2376 SmallVector<const SCEV *, 4> Worklist;
2377 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
2378 const SCEV *Expr = IU.getExpr(*UI);
2380 // Collect interesting types.
2381 Types.insert(SE.getEffectiveSCEVType(Expr->getType()));
2383 // Add strides for mentioned loops.
2384 Worklist.push_back(Expr);
2386 const SCEV *S = Worklist.pop_back_val();
2387 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
2388 if (AR->getLoop() == L)
2389 Strides.insert(AR->getStepRecurrence(SE));
2390 Worklist.push_back(AR->getStart());
2391 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2392 Worklist.append(Add->op_begin(), Add->op_end());
2394 } while (!Worklist.empty());
2397 // Compute interesting factors from the set of interesting strides.
2398 for (SmallSetVector<const SCEV *, 4>::const_iterator
2399 I = Strides.begin(), E = Strides.end(); I != E; ++I)
2400 for (SmallSetVector<const SCEV *, 4>::const_iterator NewStrideIter =
2401 std::next(I); NewStrideIter != E; ++NewStrideIter) {
2402 const SCEV *OldStride = *I;
2403 const SCEV *NewStride = *NewStrideIter;
2405 if (SE.getTypeSizeInBits(OldStride->getType()) !=
2406 SE.getTypeSizeInBits(NewStride->getType())) {
2407 if (SE.getTypeSizeInBits(OldStride->getType()) >
2408 SE.getTypeSizeInBits(NewStride->getType()))
2409 NewStride = SE.getSignExtendExpr(NewStride, OldStride->getType());
2411 OldStride = SE.getSignExtendExpr(OldStride, NewStride->getType());
2413 if (const SCEVConstant *Factor =
2414 dyn_cast_or_null<SCEVConstant>(getExactSDiv(NewStride, OldStride,
2416 if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
2417 Factors.insert(Factor->getValue()->getValue().getSExtValue());
2418 } else if (const SCEVConstant *Factor =
2419 dyn_cast_or_null<SCEVConstant>(getExactSDiv(OldStride,
2422 if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
2423 Factors.insert(Factor->getValue()->getValue().getSExtValue());
2427 // If all uses use the same type, don't bother looking for truncation-based
2429 if (Types.size() == 1)
2432 DEBUG(print_factors_and_types(dbgs()));
2435 /// findIVOperand - Helper for CollectChains that finds an IV operand (computed
2436 /// by an AddRec in this loop) within [OI,OE) or returns OE. If IVUsers mapped
2437 /// Instructions to IVStrideUses, we could partially skip this.
2438 static User::op_iterator
2439 findIVOperand(User::op_iterator OI, User::op_iterator OE,
2440 Loop *L, ScalarEvolution &SE) {
2441 for(; OI != OE; ++OI) {
2442 if (Instruction *Oper = dyn_cast<Instruction>(*OI)) {
2443 if (!SE.isSCEVable(Oper->getType()))
2446 if (const SCEVAddRecExpr *AR =
2447 dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Oper))) {
2448 if (AR->getLoop() == L)
2456 /// getWideOperand - IVChain logic must consistenctly peek base TruncInst
2457 /// operands, so wrap it in a convenient helper.
2458 static Value *getWideOperand(Value *Oper) {
2459 if (TruncInst *Trunc = dyn_cast<TruncInst>(Oper))
2460 return Trunc->getOperand(0);
2464 /// isCompatibleIVType - Return true if we allow an IV chain to include both
2466 static bool isCompatibleIVType(Value *LVal, Value *RVal) {
2467 Type *LType = LVal->getType();
2468 Type *RType = RVal->getType();
2469 return (LType == RType) || (LType->isPointerTy() && RType->isPointerTy());
2472 /// getExprBase - Return an approximation of this SCEV expression's "base", or
2473 /// NULL for any constant. Returning the expression itself is
2474 /// conservative. Returning a deeper subexpression is more precise and valid as
2475 /// long as it isn't less complex than another subexpression. For expressions
2476 /// involving multiple unscaled values, we need to return the pointer-type
2477 /// SCEVUnknown. This avoids forming chains across objects, such as:
2478 /// PrevOper==a[i], IVOper==b[i], IVInc==b-a.
2480 /// Since SCEVUnknown is the rightmost type, and pointers are the rightmost
2481 /// SCEVUnknown, we simply return the rightmost SCEV operand.
2482 static const SCEV *getExprBase(const SCEV *S) {
2483 switch (S->getSCEVType()) {
2484 default: // uncluding scUnknown.
2489 return getExprBase(cast<SCEVTruncateExpr>(S)->getOperand());
2491 return getExprBase(cast<SCEVZeroExtendExpr>(S)->getOperand());
2493 return getExprBase(cast<SCEVSignExtendExpr>(S)->getOperand());
2495 // Skip over scaled operands (scMulExpr) to follow add operands as long as
2496 // there's nothing more complex.
2497 // FIXME: not sure if we want to recognize negation.
2498 const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
2499 for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(Add->op_end()),
2500 E(Add->op_begin()); I != E; ++I) {
2501 const SCEV *SubExpr = *I;
2502 if (SubExpr->getSCEVType() == scAddExpr)
2503 return getExprBase(SubExpr);
2505 if (SubExpr->getSCEVType() != scMulExpr)
2508 return S; // all operands are scaled, be conservative.
2511 return getExprBase(cast<SCEVAddRecExpr>(S)->getStart());
2515 /// Return true if the chain increment is profitable to expand into a loop
2516 /// invariant value, which may require its own register. A profitable chain
2517 /// increment will be an offset relative to the same base. We allow such offsets
2518 /// to potentially be used as chain increment as long as it's not obviously
2519 /// expensive to expand using real instructions.
2520 bool IVChain::isProfitableIncrement(const SCEV *OperExpr,
2521 const SCEV *IncExpr,
2522 ScalarEvolution &SE) {
2523 // Aggressively form chains when -stress-ivchain.
2527 // Do not replace a constant offset from IV head with a nonconstant IV
2529 if (!isa<SCEVConstant>(IncExpr)) {
2530 const SCEV *HeadExpr = SE.getSCEV(getWideOperand(Incs[0].IVOperand));
2531 if (isa<SCEVConstant>(SE.getMinusSCEV(OperExpr, HeadExpr)))
2535 SmallPtrSet<const SCEV*, 8> Processed;
2536 return !isHighCostExpansion(IncExpr, Processed, SE);
2539 /// Return true if the number of registers needed for the chain is estimated to
2540 /// be less than the number required for the individual IV users. First prohibit
2541 /// any IV users that keep the IV live across increments (the Users set should
2542 /// be empty). Next count the number and type of increments in the chain.
2544 /// Chaining IVs can lead to considerable code bloat if ISEL doesn't
2545 /// effectively use postinc addressing modes. Only consider it profitable it the
2546 /// increments can be computed in fewer registers when chained.
2548 /// TODO: Consider IVInc free if it's already used in another chains.
2550 isProfitableChain(IVChain &Chain, SmallPtrSetImpl<Instruction*> &Users,
2551 ScalarEvolution &SE, const TargetTransformInfo &TTI) {
2555 if (!Chain.hasIncs())
2558 if (!Users.empty()) {
2559 DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " users:\n";
2560 for (Instruction *Inst : Users) {
2561 dbgs() << " " << *Inst << "\n";
2565 assert(!Chain.Incs.empty() && "empty IV chains are not allowed");
2567 // The chain itself may require a register, so intialize cost to 1.
2570 // A complete chain likely eliminates the need for keeping the original IV in
2571 // a register. LSR does not currently know how to form a complete chain unless
2572 // the header phi already exists.
2573 if (isa<PHINode>(Chain.tailUserInst())
2574 && SE.getSCEV(Chain.tailUserInst()) == Chain.Incs[0].IncExpr) {
2577 const SCEV *LastIncExpr = nullptr;
2578 unsigned NumConstIncrements = 0;
2579 unsigned NumVarIncrements = 0;
2580 unsigned NumReusedIncrements = 0;
2581 for (IVChain::const_iterator I = Chain.begin(), E = Chain.end();
2584 if (I->IncExpr->isZero())
2587 // Incrementing by zero or some constant is neutral. We assume constants can
2588 // be folded into an addressing mode or an add's immediate operand.
2589 if (isa<SCEVConstant>(I->IncExpr)) {
2590 ++NumConstIncrements;
2594 if (I->IncExpr == LastIncExpr)
2595 ++NumReusedIncrements;
2599 LastIncExpr = I->IncExpr;
2601 // An IV chain with a single increment is handled by LSR's postinc
2602 // uses. However, a chain with multiple increments requires keeping the IV's
2603 // value live longer than it needs to be if chained.
2604 if (NumConstIncrements > 1)
2607 // Materializing increment expressions in the preheader that didn't exist in
2608 // the original code may cost a register. For example, sign-extended array
2609 // indices can produce ridiculous increments like this:
2610 // IV + ((sext i32 (2 * %s) to i64) + (-1 * (sext i32 %s to i64)))
2611 cost += NumVarIncrements;
2613 // Reusing variable increments likely saves a register to hold the multiple of
2615 cost -= NumReusedIncrements;
2617 DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " Cost: " << cost
2623 /// ChainInstruction - Add this IV user to an existing chain or make it the head
2625 void LSRInstance::ChainInstruction(Instruction *UserInst, Instruction *IVOper,
2626 SmallVectorImpl<ChainUsers> &ChainUsersVec) {
2627 // When IVs are used as types of varying widths, they are generally converted
2628 // to a wider type with some uses remaining narrow under a (free) trunc.
2629 Value *const NextIV = getWideOperand(IVOper);
2630 const SCEV *const OperExpr = SE.getSCEV(NextIV);
2631 const SCEV *const OperExprBase = getExprBase(OperExpr);
2633 // Visit all existing chains. Check if its IVOper can be computed as a
2634 // profitable loop invariant increment from the last link in the Chain.
2635 unsigned ChainIdx = 0, NChains = IVChainVec.size();
2636 const SCEV *LastIncExpr = nullptr;
2637 for (; ChainIdx < NChains; ++ChainIdx) {
2638 IVChain &Chain = IVChainVec[ChainIdx];
2640 // Prune the solution space aggressively by checking that both IV operands
2641 // are expressions that operate on the same unscaled SCEVUnknown. This
2642 // "base" will be canceled by the subsequent getMinusSCEV call. Checking
2643 // first avoids creating extra SCEV expressions.
2644 if (!StressIVChain && Chain.ExprBase != OperExprBase)
2647 Value *PrevIV = getWideOperand(Chain.Incs.back().IVOperand);
2648 if (!isCompatibleIVType(PrevIV, NextIV))
2651 // A phi node terminates a chain.
2652 if (isa<PHINode>(UserInst) && isa<PHINode>(Chain.tailUserInst()))
2655 // The increment must be loop-invariant so it can be kept in a register.
2656 const SCEV *PrevExpr = SE.getSCEV(PrevIV);
2657 const SCEV *IncExpr = SE.getMinusSCEV(OperExpr, PrevExpr);
2658 if (!SE.isLoopInvariant(IncExpr, L))
2661 if (Chain.isProfitableIncrement(OperExpr, IncExpr, SE)) {
2662 LastIncExpr = IncExpr;
2666 // If we haven't found a chain, create a new one, unless we hit the max. Don't
2667 // bother for phi nodes, because they must be last in the chain.
2668 if (ChainIdx == NChains) {
2669 if (isa<PHINode>(UserInst))
2671 if (NChains >= MaxChains && !StressIVChain) {
2672 DEBUG(dbgs() << "IV Chain Limit\n");
2675 LastIncExpr = OperExpr;
2676 // IVUsers may have skipped over sign/zero extensions. We don't currently
2677 // attempt to form chains involving extensions unless they can be hoisted
2678 // into this loop's AddRec.
2679 if (!isa<SCEVAddRecExpr>(LastIncExpr))
2682 IVChainVec.push_back(IVChain(IVInc(UserInst, IVOper, LastIncExpr),
2684 ChainUsersVec.resize(NChains);
2685 DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Head: (" << *UserInst
2686 << ") IV=" << *LastIncExpr << "\n");
2688 DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Inc: (" << *UserInst
2689 << ") IV+" << *LastIncExpr << "\n");
2690 // Add this IV user to the end of the chain.
2691 IVChainVec[ChainIdx].add(IVInc(UserInst, IVOper, LastIncExpr));
2693 IVChain &Chain = IVChainVec[ChainIdx];
2695 SmallPtrSet<Instruction*,4> &NearUsers = ChainUsersVec[ChainIdx].NearUsers;
2696 // This chain's NearUsers become FarUsers.
2697 if (!LastIncExpr->isZero()) {
2698 ChainUsersVec[ChainIdx].FarUsers.insert(NearUsers.begin(),
2703 // All other uses of IVOperand become near uses of the chain.
2704 // We currently ignore intermediate values within SCEV expressions, assuming
2705 // they will eventually be used be the current chain, or can be computed
2706 // from one of the chain increments. To be more precise we could
2707 // transitively follow its user and only add leaf IV users to the set.
2708 for (User *U : IVOper->users()) {
2709 Instruction *OtherUse = dyn_cast<Instruction>(U);
2712 // Uses in the chain will no longer be uses if the chain is formed.
2713 // Include the head of the chain in this iteration (not Chain.begin()).
2714 IVChain::const_iterator IncIter = Chain.Incs.begin();
2715 IVChain::const_iterator IncEnd = Chain.Incs.end();
2716 for( ; IncIter != IncEnd; ++IncIter) {
2717 if (IncIter->UserInst == OtherUse)
2720 if (IncIter != IncEnd)
2723 if (SE.isSCEVable(OtherUse->getType())
2724 && !isa<SCEVUnknown>(SE.getSCEV(OtherUse))
2725 && IU.isIVUserOrOperand(OtherUse)) {
2728 NearUsers.insert(OtherUse);
2731 // Since this user is part of the chain, it's no longer considered a use
2733 ChainUsersVec[ChainIdx].FarUsers.erase(UserInst);
2736 /// CollectChains - Populate the vector of Chains.
2738 /// This decreases ILP at the architecture level. Targets with ample registers,
2739 /// multiple memory ports, and no register renaming probably don't want
2740 /// this. However, such targets should probably disable LSR altogether.
2742 /// The job of LSR is to make a reasonable choice of induction variables across
2743 /// the loop. Subsequent passes can easily "unchain" computation exposing more
2744 /// ILP *within the loop* if the target wants it.
2746 /// Finding the best IV chain is potentially a scheduling problem. Since LSR
2747 /// will not reorder memory operations, it will recognize this as a chain, but
2748 /// will generate redundant IV increments. Ideally this would be corrected later
2749 /// by a smart scheduler:
2755 /// TODO: Walk the entire domtree within this loop, not just the path to the
2756 /// loop latch. This will discover chains on side paths, but requires
2757 /// maintaining multiple copies of the Chains state.
2758 void LSRInstance::CollectChains() {
2759 DEBUG(dbgs() << "Collecting IV Chains.\n");
2760 SmallVector<ChainUsers, 8> ChainUsersVec;
2762 SmallVector<BasicBlock *,8> LatchPath;
2763 BasicBlock *LoopHeader = L->getHeader();
2764 for (DomTreeNode *Rung = DT.getNode(L->getLoopLatch());
2765 Rung->getBlock() != LoopHeader; Rung = Rung->getIDom()) {
2766 LatchPath.push_back(Rung->getBlock());
2768 LatchPath.push_back(LoopHeader);
2770 // Walk the instruction stream from the loop header to the loop latch.
2771 for (SmallVectorImpl<BasicBlock *>::reverse_iterator
2772 BBIter = LatchPath.rbegin(), BBEnd = LatchPath.rend();
2773 BBIter != BBEnd; ++BBIter) {
2774 for (BasicBlock::iterator I = (*BBIter)->begin(), E = (*BBIter)->end();
2776 // Skip instructions that weren't seen by IVUsers analysis.
2777 if (isa<PHINode>(I) || !IU.isIVUserOrOperand(I))
2780 // Ignore users that are part of a SCEV expression. This way we only
2781 // consider leaf IV Users. This effectively rediscovers a portion of
2782 // IVUsers analysis but in program order this time.
2783 if (SE.isSCEVable(I->getType()) && !isa<SCEVUnknown>(SE.getSCEV(I)))
2786 // Remove this instruction from any NearUsers set it may be in.
2787 for (unsigned ChainIdx = 0, NChains = IVChainVec.size();
2788 ChainIdx < NChains; ++ChainIdx) {
2789 ChainUsersVec[ChainIdx].NearUsers.erase(I);
2791 // Search for operands that can be chained.
2792 SmallPtrSet<Instruction*, 4> UniqueOperands;
2793 User::op_iterator IVOpEnd = I->op_end();
2794 User::op_iterator IVOpIter = findIVOperand(I->op_begin(), IVOpEnd, L, SE);
2795 while (IVOpIter != IVOpEnd) {
2796 Instruction *IVOpInst = cast<Instruction>(*IVOpIter);
2797 if (UniqueOperands.insert(IVOpInst).second)
2798 ChainInstruction(I, IVOpInst, ChainUsersVec);
2799 IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);
2801 } // Continue walking down the instructions.
2802 } // Continue walking down the domtree.
2803 // Visit phi backedges to determine if the chain can generate the IV postinc.
2804 for (BasicBlock::iterator I = L->getHeader()->begin();
2805 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
2806 if (!SE.isSCEVable(PN->getType()))
2810 dyn_cast<Instruction>(PN->getIncomingValueForBlock(L->getLoopLatch()));
2812 ChainInstruction(PN, IncV, ChainUsersVec);
2814 // Remove any unprofitable chains.
2815 unsigned ChainIdx = 0;
2816 for (unsigned UsersIdx = 0, NChains = IVChainVec.size();
2817 UsersIdx < NChains; ++UsersIdx) {
2818 if (!isProfitableChain(IVChainVec[UsersIdx],
2819 ChainUsersVec[UsersIdx].FarUsers, SE, TTI))
2821 // Preserve the chain at UsesIdx.
2822 if (ChainIdx != UsersIdx)
2823 IVChainVec[ChainIdx] = IVChainVec[UsersIdx];
2824 FinalizeChain(IVChainVec[ChainIdx]);
2827 IVChainVec.resize(ChainIdx);
2830 void LSRInstance::FinalizeChain(IVChain &Chain) {
2831 assert(!Chain.Incs.empty() && "empty IV chains are not allowed");
2832 DEBUG(dbgs() << "Final Chain: " << *Chain.Incs[0].UserInst << "\n");
2834 for (IVChain::const_iterator I = Chain.begin(), E = Chain.end();
2836 DEBUG(dbgs() << " Inc: " << *I->UserInst << "\n");
2837 User::op_iterator UseI =
2838 std::find(I->UserInst->op_begin(), I->UserInst->op_end(), I->IVOperand);
2839 assert(UseI != I->UserInst->op_end() && "cannot find IV operand");
2840 IVIncSet.insert(UseI);
2844 /// Return true if the IVInc can be folded into an addressing mode.
2845 static bool canFoldIVIncExpr(const SCEV *IncExpr, Instruction *UserInst,
2846 Value *Operand, const TargetTransformInfo &TTI) {
2847 const SCEVConstant *IncConst = dyn_cast<SCEVConstant>(IncExpr);
2848 if (!IncConst || !isAddressUse(UserInst, Operand))
2851 if (IncConst->getValue()->getValue().getMinSignedBits() > 64)
2854 int64_t IncOffset = IncConst->getValue()->getSExtValue();
2855 if (!isAlwaysFoldable(TTI, LSRUse::Address,
2856 getAccessType(UserInst), /*BaseGV=*/ nullptr,
2857 IncOffset, /*HaseBaseReg=*/ false))
2863 /// GenerateIVChains - Generate an add or subtract for each IVInc in a chain to
2864 /// materialize the IV user's operand from the previous IV user's operand.
2865 void LSRInstance::GenerateIVChain(const IVChain &Chain, SCEVExpander &Rewriter,
2866 SmallVectorImpl<WeakVH> &DeadInsts) {
2867 // Find the new IVOperand for the head of the chain. It may have been replaced
2869 const IVInc &Head = Chain.Incs[0];
2870 User::op_iterator IVOpEnd = Head.UserInst->op_end();
2871 // findIVOperand returns IVOpEnd if it can no longer find a valid IV user.
2872 User::op_iterator IVOpIter = findIVOperand(Head.UserInst->op_begin(),
2874 Value *IVSrc = nullptr;
2875 while (IVOpIter != IVOpEnd) {
2876 IVSrc = getWideOperand(*IVOpIter);
2878 // If this operand computes the expression that the chain needs, we may use
2879 // it. (Check this after setting IVSrc which is used below.)
2881 // Note that if Head.IncExpr is wider than IVSrc, then this phi is too
2882 // narrow for the chain, so we can no longer use it. We do allow using a
2883 // wider phi, assuming the LSR checked for free truncation. In that case we
2884 // should already have a truncate on this operand such that
2885 // getSCEV(IVSrc) == IncExpr.
2886 if (SE.getSCEV(*IVOpIter) == Head.IncExpr
2887 || SE.getSCEV(IVSrc) == Head.IncExpr) {
2890 IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);
2892 if (IVOpIter == IVOpEnd) {
2893 // Gracefully give up on this chain.
2894 DEBUG(dbgs() << "Concealed chain head: " << *Head.UserInst << "\n");
2898 DEBUG(dbgs() << "Generate chain at: " << *IVSrc << "\n");
2899 Type *IVTy = IVSrc->getType();
2900 Type *IntTy = SE.getEffectiveSCEVType(IVTy);
2901 const SCEV *LeftOverExpr = nullptr;
2902 for (IVChain::const_iterator IncI = Chain.begin(),
2903 IncE = Chain.end(); IncI != IncE; ++IncI) {
2905 Instruction *InsertPt = IncI->UserInst;
2906 if (isa<PHINode>(InsertPt))
2907 InsertPt = L->getLoopLatch()->getTerminator();
2909 // IVOper will replace the current IV User's operand. IVSrc is the IV
2910 // value currently held in a register.
2911 Value *IVOper = IVSrc;
2912 if (!IncI->IncExpr->isZero()) {
2913 // IncExpr was the result of subtraction of two narrow values, so must
2915 const SCEV *IncExpr = SE.getNoopOrSignExtend(IncI->IncExpr, IntTy);
2916 LeftOverExpr = LeftOverExpr ?
2917 SE.getAddExpr(LeftOverExpr, IncExpr) : IncExpr;
2919 if (LeftOverExpr && !LeftOverExpr->isZero()) {
2920 // Expand the IV increment.
2921 Rewriter.clearPostInc();
2922 Value *IncV = Rewriter.expandCodeFor(LeftOverExpr, IntTy, InsertPt);
2923 const SCEV *IVOperExpr = SE.getAddExpr(SE.getUnknown(IVSrc),
2924 SE.getUnknown(IncV));
2925 IVOper = Rewriter.expandCodeFor(IVOperExpr, IVTy, InsertPt);
2927 // If an IV increment can't be folded, use it as the next IV value.
2928 if (!canFoldIVIncExpr(LeftOverExpr, IncI->UserInst, IncI->IVOperand,
2930 assert(IVTy == IVOper->getType() && "inconsistent IV increment type");
2932 LeftOverExpr = nullptr;
2935 Type *OperTy = IncI->IVOperand->getType();
2936 if (IVTy != OperTy) {
2937 assert(SE.getTypeSizeInBits(IVTy) >= SE.getTypeSizeInBits(OperTy) &&
2938 "cannot extend a chained IV");
2939 IRBuilder<> Builder(InsertPt);
2940 IVOper = Builder.CreateTruncOrBitCast(IVOper, OperTy, "lsr.chain");
2942 IncI->UserInst->replaceUsesOfWith(IncI->IVOperand, IVOper);
2943 DeadInsts.push_back(IncI->IVOperand);
2945 // If LSR created a new, wider phi, we may also replace its postinc. We only
2946 // do this if we also found a wide value for the head of the chain.
2947 if (isa<PHINode>(Chain.tailUserInst())) {
2948 for (BasicBlock::iterator I = L->getHeader()->begin();
2949 PHINode *Phi = dyn_cast<PHINode>(I); ++I) {
2950 if (!isCompatibleIVType(Phi, IVSrc))
2952 Instruction *PostIncV = dyn_cast<Instruction>(
2953 Phi->getIncomingValueForBlock(L->getLoopLatch()));
2954 if (!PostIncV || (SE.getSCEV(PostIncV) != SE.getSCEV(IVSrc)))
2956 Value *IVOper = IVSrc;
2957 Type *PostIncTy = PostIncV->getType();
2958 if (IVTy != PostIncTy) {
2959 assert(PostIncTy->isPointerTy() && "mixing int/ptr IV types");
2960 IRBuilder<> Builder(L->getLoopLatch()->getTerminator());
2961 Builder.SetCurrentDebugLocation(PostIncV->getDebugLoc());
2962 IVOper = Builder.CreatePointerCast(IVSrc, PostIncTy, "lsr.chain");
2964 Phi->replaceUsesOfWith(PostIncV, IVOper);
2965 DeadInsts.push_back(PostIncV);
2970 void LSRInstance::CollectFixupsAndInitialFormulae() {
2971 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
2972 Instruction *UserInst = UI->getUser();
2973 // Skip IV users that are part of profitable IV Chains.
2974 User::op_iterator UseI = std::find(UserInst->op_begin(), UserInst->op_end(),
2975 UI->getOperandValToReplace());
2976 assert(UseI != UserInst->op_end() && "cannot find IV operand");
2977 if (IVIncSet.count(UseI))
2981 LSRFixup &LF = getNewFixup();
2982 LF.UserInst = UserInst;
2983 LF.OperandValToReplace = UI->getOperandValToReplace();
2984 LF.PostIncLoops = UI->getPostIncLoops();
2986 LSRUse::KindType Kind = LSRUse::Basic;
2987 Type *AccessTy = nullptr;
2988 if (isAddressUse(LF.UserInst, LF.OperandValToReplace)) {
2989 Kind = LSRUse::Address;
2990 AccessTy = getAccessType(LF.UserInst);
2993 const SCEV *S = IU.getExpr(*UI);
2995 // Equality (== and !=) ICmps are special. We can rewrite (i == N) as
2996 // (N - i == 0), and this allows (N - i) to be the expression that we work
2997 // with rather than just N or i, so we can consider the register
2998 // requirements for both N and i at the same time. Limiting this code to
2999 // equality icmps is not a problem because all interesting loops use
3000 // equality icmps, thanks to IndVarSimplify.
3001 if (ICmpInst *CI = dyn_cast<ICmpInst>(LF.UserInst))
3002 if (CI->isEquality()) {
3003 // Swap the operands if needed to put the OperandValToReplace on the
3004 // left, for consistency.
3005 Value *NV = CI->getOperand(1);
3006 if (NV == LF.OperandValToReplace) {
3007 CI->setOperand(1, CI->getOperand(0));
3008 CI->setOperand(0, NV);
3009 NV = CI->getOperand(1);
3013 // x == y --> x - y == 0
3014 const SCEV *N = SE.getSCEV(NV);
3015 if (SE.isLoopInvariant(N, L) && isSafeToExpand(N, SE)) {
3016 // S is normalized, so normalize N before folding it into S
3017 // to keep the result normalized.
3018 N = TransformForPostIncUse(Normalize, N, CI, nullptr,
3019 LF.PostIncLoops, SE, DT);
3020 Kind = LSRUse::ICmpZero;
3021 S = SE.getMinusSCEV(N, S);
3024 // -1 and the negations of all interesting strides (except the negation
3025 // of -1) are now also interesting.
3026 for (size_t i = 0, e = Factors.size(); i != e; ++i)
3027 if (Factors[i] != -1)
3028 Factors.insert(-(uint64_t)Factors[i]);
3032 // Set up the initial formula for this use.
3033 std::pair<size_t, int64_t> P = getUse(S, Kind, AccessTy);
3035 LF.Offset = P.second;
3036 LSRUse &LU = Uses[LF.LUIdx];
3037 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
3038 if (!LU.WidestFixupType ||
3039 SE.getTypeSizeInBits(LU.WidestFixupType) <
3040 SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
3041 LU.WidestFixupType = LF.OperandValToReplace->getType();
3043 // If this is the first use of this LSRUse, give it a formula.
3044 if (LU.Formulae.empty()) {
3045 InsertInitialFormula(S, LU, LF.LUIdx);
3046 CountRegisters(LU.Formulae.back(), LF.LUIdx);
3050 DEBUG(print_fixups(dbgs()));
3053 /// InsertInitialFormula - Insert a formula for the given expression into
3054 /// the given use, separating out loop-variant portions from loop-invariant
3055 /// and loop-computable portions.
3057 LSRInstance::InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx) {
3058 // Mark uses whose expressions cannot be expanded.
3059 if (!isSafeToExpand(S, SE))
3060 LU.RigidFormula = true;
3063 F.InitialMatch(S, L, SE);
3064 bool Inserted = InsertFormula(LU, LUIdx, F);
3065 assert(Inserted && "Initial formula already exists!"); (void)Inserted;
3068 /// InsertSupplementalFormula - Insert a simple single-register formula for
3069 /// the given expression into the given use.
3071 LSRInstance::InsertSupplementalFormula(const SCEV *S,
3072 LSRUse &LU, size_t LUIdx) {
3074 F.BaseRegs.push_back(S);
3075 F.HasBaseReg = true;
3076 bool Inserted = InsertFormula(LU, LUIdx, F);
3077 assert(Inserted && "Supplemental formula already exists!"); (void)Inserted;
3080 /// CountRegisters - Note which registers are used by the given formula,
3081 /// updating RegUses.
3082 void LSRInstance::CountRegisters(const Formula &F, size_t LUIdx) {
3084 RegUses.CountRegister(F.ScaledReg, LUIdx);
3085 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
3086 E = F.BaseRegs.end(); I != E; ++I)
3087 RegUses.CountRegister(*I, LUIdx);
3090 /// InsertFormula - If the given formula has not yet been inserted, add it to
3091 /// the list, and return true. Return false otherwise.
3092 bool LSRInstance::InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F) {
3093 // Do not insert formula that we will not be able to expand.
3094 assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F) &&
3095 "Formula is illegal");
3096 if (!LU.InsertFormula(F))
3099 CountRegisters(F, LUIdx);
3103 /// CollectLoopInvariantFixupsAndFormulae - Check for other uses of
3104 /// loop-invariant values which we're tracking. These other uses will pin these
3105 /// values in registers, making them less profitable for elimination.
3106 /// TODO: This currently misses non-constant addrec step registers.
3107 /// TODO: Should this give more weight to users inside the loop?
3109 LSRInstance::CollectLoopInvariantFixupsAndFormulae() {
3110 SmallVector<const SCEV *, 8> Worklist(RegUses.begin(), RegUses.end());
3111 SmallPtrSet<const SCEV *, 32> Visited;
3113 while (!Worklist.empty()) {
3114 const SCEV *S = Worklist.pop_back_val();
3116 // Don't process the same SCEV twice
3117 if (!Visited.insert(S).second)
3120 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S))
3121 Worklist.append(N->op_begin(), N->op_end());
3122 else if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
3123 Worklist.push_back(C->getOperand());
3124 else if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
3125 Worklist.push_back(D->getLHS());
3126 Worklist.push_back(D->getRHS());
3127 } else if (const SCEVUnknown *US = dyn_cast<SCEVUnknown>(S)) {
3128 const Value *V = US->getValue();
3129 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
3130 // Look for instructions defined outside the loop.
3131 if (L->contains(Inst)) continue;
3132 } else if (isa<UndefValue>(V))
3133 // Undef doesn't have a live range, so it doesn't matter.
3135 for (const Use &U : V->uses()) {
3136 const Instruction *UserInst = dyn_cast<Instruction>(U.getUser());
3137 // Ignore non-instructions.
3140 // Ignore instructions in other functions (as can happen with
3142 if (UserInst->getParent()->getParent() != L->getHeader()->getParent())
3144 // Ignore instructions not dominated by the loop.
3145 const BasicBlock *UseBB = !isa<PHINode>(UserInst) ?
3146 UserInst->getParent() :
3147 cast<PHINode>(UserInst)->getIncomingBlock(
3148 PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
3149 if (!DT.dominates(L->getHeader(), UseBB))
3151 // Ignore uses which are part of other SCEV expressions, to avoid
3152 // analyzing them multiple times.
3153 if (SE.isSCEVable(UserInst->getType())) {
3154 const SCEV *UserS = SE.getSCEV(const_cast<Instruction *>(UserInst));
3155 // If the user is a no-op, look through to its uses.
3156 if (!isa<SCEVUnknown>(UserS))
3160 SE.getUnknown(const_cast<Instruction *>(UserInst)));
3164 // Ignore icmp instructions which are already being analyzed.
3165 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) {
3166 unsigned OtherIdx = !U.getOperandNo();
3167 Value *OtherOp = const_cast<Value *>(ICI->getOperand(OtherIdx));
3168 if (SE.hasComputableLoopEvolution(SE.getSCEV(OtherOp), L))
3172 LSRFixup &LF = getNewFixup();
3173 LF.UserInst = const_cast<Instruction *>(UserInst);
3174 LF.OperandValToReplace = U;
3175 std::pair<size_t, int64_t> P = getUse(S, LSRUse::Basic, nullptr);
3177 LF.Offset = P.second;
3178 LSRUse &LU = Uses[LF.LUIdx];
3179 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
3180 if (!LU.WidestFixupType ||
3181 SE.getTypeSizeInBits(LU.WidestFixupType) <
3182 SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
3183 LU.WidestFixupType = LF.OperandValToReplace->getType();
3184 InsertSupplementalFormula(US, LU, LF.LUIdx);
3185 CountRegisters(LU.Formulae.back(), Uses.size() - 1);
3192 /// CollectSubexprs - Split S into subexpressions which can be pulled out into
3193 /// separate registers. If C is non-null, multiply each subexpression by C.
3195 /// Return remainder expression after factoring the subexpressions captured by
3196 /// Ops. If Ops is complete, return NULL.
3197 static const SCEV *CollectSubexprs(const SCEV *S, const SCEVConstant *C,
3198 SmallVectorImpl<const SCEV *> &Ops,
3200 ScalarEvolution &SE,
3201 unsigned Depth = 0) {
3202 // Arbitrarily cap recursion to protect compile time.
3206 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3207 // Break out add operands.
3208 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
3210 const SCEV *Remainder = CollectSubexprs(*I, C, Ops, L, SE, Depth+1);
3212 Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder);
3215 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
3216 // Split a non-zero base out of an addrec.
3217 if (AR->getStart()->isZero())
3220 const SCEV *Remainder = CollectSubexprs(AR->getStart(),
3221 C, Ops, L, SE, Depth+1);
3222 // Split the non-zero AddRec unless it is part of a nested recurrence that
3223 // does not pertain to this loop.
3224 if (Remainder && (AR->getLoop() == L || !isa<SCEVAddRecExpr>(Remainder))) {
3225 Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder);
3226 Remainder = nullptr;
3228 if (Remainder != AR->getStart()) {
3230 Remainder = SE.getConstant(AR->getType(), 0);
3231 return SE.getAddRecExpr(Remainder,
3232 AR->getStepRecurrence(SE),
3234 //FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
3237 } else if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3238 // Break (C * (a + b + c)) into C*a + C*b + C*c.
3239 if (Mul->getNumOperands() != 2)
3241 if (const SCEVConstant *Op0 =
3242 dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3243 C = C ? cast<SCEVConstant>(SE.getMulExpr(C, Op0)) : Op0;
3244 const SCEV *Remainder =
3245 CollectSubexprs(Mul->getOperand(1), C, Ops, L, SE, Depth+1);
3247 Ops.push_back(SE.getMulExpr(C, Remainder));
3254 /// \brief Helper function for LSRInstance::GenerateReassociations.
3255 void LSRInstance::GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx,
3256 const Formula &Base,
3257 unsigned Depth, size_t Idx,
3259 const SCEV *BaseReg = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
3260 SmallVector<const SCEV *, 8> AddOps;
3261 const SCEV *Remainder = CollectSubexprs(BaseReg, nullptr, AddOps, L, SE);
3263 AddOps.push_back(Remainder);
3265 if (AddOps.size() == 1)
3268 for (SmallVectorImpl<const SCEV *>::const_iterator J = AddOps.begin(),
3272 // Loop-variant "unknown" values are uninteresting; we won't be able to
3273 // do anything meaningful with them.
3274 if (isa<SCEVUnknown>(*J) && !SE.isLoopInvariant(*J, L))
3277 // Don't pull a constant into a register if the constant could be folded
3278 // into an immediate field.
3279 if (isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind,
3280 LU.AccessTy, *J, Base.getNumRegs() > 1))
3283 // Collect all operands except *J.
3284 SmallVector<const SCEV *, 8> InnerAddOps(
3285 ((const SmallVector<const SCEV *, 8> &)AddOps).begin(), J);
3286 InnerAddOps.append(std::next(J),
3287 ((const SmallVector<const SCEV *, 8> &)AddOps).end());
3289 // Don't leave just a constant behind in a register if the constant could
3290 // be folded into an immediate field.
3291 if (InnerAddOps.size() == 1 &&
3292 isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind,
3293 LU.AccessTy, InnerAddOps[0], Base.getNumRegs() > 1))
3296 const SCEV *InnerSum = SE.getAddExpr(InnerAddOps);
3297 if (InnerSum->isZero())
3301 // Add the remaining pieces of the add back into the new formula.
3302 const SCEVConstant *InnerSumSC = dyn_cast<SCEVConstant>(InnerSum);
3303 if (InnerSumSC && SE.getTypeSizeInBits(InnerSumSC->getType()) <= 64 &&
3304 TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset +
3305 InnerSumSC->getValue()->getZExtValue())) {
3307 (uint64_t)F.UnfoldedOffset + InnerSumSC->getValue()->getZExtValue();
3309 F.ScaledReg = nullptr;
3311 F.BaseRegs.erase(F.BaseRegs.begin() + Idx);
3312 } else if (IsScaledReg)
3313 F.ScaledReg = InnerSum;
3315 F.BaseRegs[Idx] = InnerSum;
3317 // Add J as its own register, or an unfolded immediate.
3318 const SCEVConstant *SC = dyn_cast<SCEVConstant>(*J);
3319 if (SC && SE.getTypeSizeInBits(SC->getType()) <= 64 &&
3320 TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset +
3321 SC->getValue()->getZExtValue()))
3323 (uint64_t)F.UnfoldedOffset + SC->getValue()->getZExtValue();
3325 F.BaseRegs.push_back(*J);
3326 // We may have changed the number of register in base regs, adjust the
3327 // formula accordingly.
3330 if (InsertFormula(LU, LUIdx, F))
3331 // If that formula hadn't been seen before, recurse to find more like
3333 GenerateReassociations(LU, LUIdx, LU.Formulae.back(), Depth + 1);
3337 /// GenerateReassociations - Split out subexpressions from adds and the bases of
3339 void LSRInstance::GenerateReassociations(LSRUse &LU, unsigned LUIdx,
3340 Formula Base, unsigned Depth) {
3341 assert(Base.isCanonical() && "Input must be in the canonical form");
3342 // Arbitrarily cap recursion to protect compile time.
3346 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3347 GenerateReassociationsImpl(LU, LUIdx, Base, Depth, i);
3349 if (Base.Scale == 1)
3350 GenerateReassociationsImpl(LU, LUIdx, Base, Depth,
3351 /* Idx */ -1, /* IsScaledReg */ true);
3354 /// GenerateCombinations - Generate a formula consisting of all of the
3355 /// loop-dominating registers added into a single register.
3356 void LSRInstance::GenerateCombinations(LSRUse &LU, unsigned LUIdx,
3358 // This method is only interesting on a plurality of registers.
3359 if (Base.BaseRegs.size() + (Base.Scale == 1) <= 1)
3362 // Flatten the representation, i.e., reg1 + 1*reg2 => reg1 + reg2, before
3363 // processing the formula.
3367 SmallVector<const SCEV *, 4> Ops;
3368 for (SmallVectorImpl<const SCEV *>::const_iterator
3369 I = Base.BaseRegs.begin(), E = Base.BaseRegs.end(); I != E; ++I) {
3370 const SCEV *BaseReg = *I;
3371 if (SE.properlyDominates(BaseReg, L->getHeader()) &&
3372 !SE.hasComputableLoopEvolution(BaseReg, L))
3373 Ops.push_back(BaseReg);
3375 F.BaseRegs.push_back(BaseReg);
3377 if (Ops.size() > 1) {
3378 const SCEV *Sum = SE.getAddExpr(Ops);
3379 // TODO: If Sum is zero, it probably means ScalarEvolution missed an
3380 // opportunity to fold something. For now, just ignore such cases
3381 // rather than proceed with zero in a register.
3382 if (!Sum->isZero()) {
3383 F.BaseRegs.push_back(Sum);
3385 (void)InsertFormula(LU, LUIdx, F);
3390 /// \brief Helper function for LSRInstance::GenerateSymbolicOffsets.
3391 void LSRInstance::GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx,
3392 const Formula &Base, size_t Idx,
3394 const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
3395 GlobalValue *GV = ExtractSymbol(G, SE);
3396 if (G->isZero() || !GV)
3400 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F))
3405 F.BaseRegs[Idx] = G;
3406 (void)InsertFormula(LU, LUIdx, F);
3409 /// GenerateSymbolicOffsets - Generate reuse formulae using symbolic offsets.
3410 void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx,
3412 // We can't add a symbolic offset if the address already contains one.
3413 if (Base.BaseGV) return;
3415 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3416 GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, i);
3417 if (Base.Scale == 1)
3418 GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, /* Idx */ -1,
3419 /* IsScaledReg */ true);
3422 /// \brief Helper function for LSRInstance::GenerateConstantOffsets.
3423 void LSRInstance::GenerateConstantOffsetsImpl(
3424 LSRUse &LU, unsigned LUIdx, const Formula &Base,
3425 const SmallVectorImpl<int64_t> &Worklist, size_t Idx, bool IsScaledReg) {
3426 const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
3427 for (SmallVectorImpl<int64_t>::const_iterator I = Worklist.begin(),
3431 F.BaseOffset = (uint64_t)Base.BaseOffset - *I;
3432 if (isLegalUse(TTI, LU.MinOffset - *I, LU.MaxOffset - *I, LU.Kind,
3434 // Add the offset to the base register.
3435 const SCEV *NewG = SE.getAddExpr(SE.getConstant(G->getType(), *I), G);
3436 // If it cancelled out, drop the base register, otherwise update it.
3437 if (NewG->isZero()) {
3440 F.ScaledReg = nullptr;
3442 F.DeleteBaseReg(F.BaseRegs[Idx]);
3444 } else if (IsScaledReg)
3447 F.BaseRegs[Idx] = NewG;
3449 (void)InsertFormula(LU, LUIdx, F);
3453 int64_t Imm = ExtractImmediate(G, SE);
3454 if (G->isZero() || Imm == 0)
3457 F.BaseOffset = (uint64_t)F.BaseOffset + Imm;
3458 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F))
3463 F.BaseRegs[Idx] = G;
3464 (void)InsertFormula(LU, LUIdx, F);
3467 /// GenerateConstantOffsets - Generate reuse formulae using symbolic offsets.
3468 void LSRInstance::GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx,
3470 // TODO: For now, just add the min and max offset, because it usually isn't
3471 // worthwhile looking at everything inbetween.
3472 SmallVector<int64_t, 2> Worklist;
3473 Worklist.push_back(LU.MinOffset);
3474 if (LU.MaxOffset != LU.MinOffset)
3475 Worklist.push_back(LU.MaxOffset);
3477 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3478 GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, i);
3479 if (Base.Scale == 1)
3480 GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, /* Idx */ -1,
3481 /* IsScaledReg */ true);
3484 /// GenerateICmpZeroScales - For ICmpZero, check to see if we can scale up
3485 /// the comparison. For example, x == y -> x*c == y*c.
3486 void LSRInstance::GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx,
3488 if (LU.Kind != LSRUse::ICmpZero) return;
3490 // Determine the integer type for the base formula.
3491 Type *IntTy = Base.getType();
3493 if (SE.getTypeSizeInBits(IntTy) > 64) return;
3495 // Don't do this if there is more than one offset.
3496 if (LU.MinOffset != LU.MaxOffset) return;
3498 assert(!Base.BaseGV && "ICmpZero use is not legal!");
3500 // Check each interesting stride.
3501 for (SmallSetVector<int64_t, 8>::const_iterator
3502 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
3503 int64_t Factor = *I;
3505 // Check that the multiplication doesn't overflow.
3506 if (Base.BaseOffset == INT64_MIN && Factor == -1)
3508 int64_t NewBaseOffset = (uint64_t)Base.BaseOffset * Factor;
3509 if (NewBaseOffset / Factor != Base.BaseOffset)
3511 // If the offset will be truncated at this use, check that it is in bounds.
3512 if (!IntTy->isPointerTy() &&
3513 !ConstantInt::isValueValidForType(IntTy, NewBaseOffset))
3516 // Check that multiplying with the use offset doesn't overflow.
3517 int64_t Offset = LU.MinOffset;
3518 if (Offset == INT64_MIN && Factor == -1)
3520 Offset = (uint64_t)Offset * Factor;
3521 if (Offset / Factor != LU.MinOffset)
3523 // If the offset will be truncated at this use, check that it is in bounds.
3524 if (!IntTy->isPointerTy() &&
3525 !ConstantInt::isValueValidForType(IntTy, Offset))
3529 F.BaseOffset = NewBaseOffset;
3531 // Check that this scale is legal.
3532 if (!isLegalUse(TTI, Offset, Offset, LU.Kind, LU.AccessTy, F))
3535 // Compensate for the use having MinOffset built into it.
3536 F.BaseOffset = (uint64_t)F.BaseOffset + Offset - LU.MinOffset;
3538 const SCEV *FactorS = SE.getConstant(IntTy, Factor);
3540 // Check that multiplying with each base register doesn't overflow.
3541 for (size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) {
3542 F.BaseRegs[i] = SE.getMulExpr(F.BaseRegs[i], FactorS);
3543 if (getExactSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i])
3547 // Check that multiplying with the scaled register doesn't overflow.
3549 F.ScaledReg = SE.getMulExpr(F.ScaledReg, FactorS);
3550 if (getExactSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg)
3554 // Check that multiplying with the unfolded offset doesn't overflow.
3555 if (F.UnfoldedOffset != 0) {
3556 if (F.UnfoldedOffset == INT64_MIN && Factor == -1)
3558 F.UnfoldedOffset = (uint64_t)F.UnfoldedOffset * Factor;
3559 if (F.UnfoldedOffset / Factor != Base.UnfoldedOffset)
3561 // If the offset will be truncated, check that it is in bounds.
3562 if (!IntTy->isPointerTy() &&
3563 !ConstantInt::isValueValidForType(IntTy, F.UnfoldedOffset))
3567 // If we make it here and it's legal, add it.
3568 (void)InsertFormula(LU, LUIdx, F);
3573 /// GenerateScales - Generate stride factor reuse formulae by making use of
3574 /// scaled-offset address modes, for example.
3575 void LSRInstance::GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base) {
3576 // Determine the integer type for the base formula.
3577 Type *IntTy = Base.getType();
3580 // If this Formula already has a scaled register, we can't add another one.
3581 // Try to unscale the formula to generate a better scale.
3582 if (Base.Scale != 0 && !Base.Unscale())
3585 assert(Base.Scale == 0 && "Unscale did not did its job!");
3587 // Check each interesting stride.
3588 for (SmallSetVector<int64_t, 8>::const_iterator
3589 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
3590 int64_t Factor = *I;
3592 Base.Scale = Factor;
3593 Base.HasBaseReg = Base.BaseRegs.size() > 1;
3594 // Check whether this scale is going to be legal.
3595 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
3597 // As a special-case, handle special out-of-loop Basic users specially.
3598 // TODO: Reconsider this special case.
3599 if (LU.Kind == LSRUse::Basic &&
3600 isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LSRUse::Special,
3601 LU.AccessTy, Base) &&
3602 LU.AllFixupsOutsideLoop)
3603 LU.Kind = LSRUse::Special;
3607 // For an ICmpZero, negating a solitary base register won't lead to
3609 if (LU.Kind == LSRUse::ICmpZero &&
3610 !Base.HasBaseReg && Base.BaseOffset == 0 && !Base.BaseGV)
3612 // For each addrec base reg, apply the scale, if possible.
3613 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3614 if (const SCEVAddRecExpr *AR =
3615 dyn_cast<SCEVAddRecExpr>(Base.BaseRegs[i])) {
3616 const SCEV *FactorS = SE.getConstant(IntTy, Factor);
3617 if (FactorS->isZero())
3619 // Divide out the factor, ignoring high bits, since we'll be
3620 // scaling the value back up in the end.
3621 if (const SCEV *Quotient = getExactSDiv(AR, FactorS, SE, true)) {
3622 // TODO: This could be optimized to avoid all the copying.
3624 F.ScaledReg = Quotient;
3625 F.DeleteBaseReg(F.BaseRegs[i]);
3626 // The canonical representation of 1*reg is reg, which is already in
3627 // Base. In that case, do not try to insert the formula, it will be
3629 if (F.Scale == 1 && F.BaseRegs.empty())
3631 (void)InsertFormula(LU, LUIdx, F);
3637 /// GenerateTruncates - Generate reuse formulae from different IV types.
3638 void LSRInstance::GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base) {
3639 // Don't bother truncating symbolic values.
3640 if (Base.BaseGV) return;
3642 // Determine the integer type for the base formula.
3643 Type *DstTy = Base.getType();
3645 DstTy = SE.getEffectiveSCEVType(DstTy);
3647 for (SmallSetVector<Type *, 4>::const_iterator
3648 I = Types.begin(), E = Types.end(); I != E; ++I) {
3650 if (SrcTy != DstTy && TTI.isTruncateFree(SrcTy, DstTy)) {
3653 if (F.ScaledReg) F.ScaledReg = SE.getAnyExtendExpr(F.ScaledReg, *I);
3654 for (SmallVectorImpl<const SCEV *>::iterator J = F.BaseRegs.begin(),
3655 JE = F.BaseRegs.end(); J != JE; ++J)
3656 *J = SE.getAnyExtendExpr(*J, SrcTy);
3658 // TODO: This assumes we've done basic processing on all uses and
3659 // have an idea what the register usage is.
3660 if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses))
3663 (void)InsertFormula(LU, LUIdx, F);
3670 /// WorkItem - Helper class for GenerateCrossUseConstantOffsets. It's used to
3671 /// defer modifications so that the search phase doesn't have to worry about
3672 /// the data structures moving underneath it.
3676 const SCEV *OrigReg;
3678 WorkItem(size_t LI, int64_t I, const SCEV *R)
3679 : LUIdx(LI), Imm(I), OrigReg(R) {}
3681 void print(raw_ostream &OS) const;
3687 void WorkItem::print(raw_ostream &OS) const {
3688 OS << "in formulae referencing " << *OrigReg << " in use " << LUIdx
3689 << " , add offset " << Imm;
3692 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3693 void WorkItem::dump() const {
3694 print(errs()); errs() << '\n';
3698 /// GenerateCrossUseConstantOffsets - Look for registers which are a constant
3699 /// distance apart and try to form reuse opportunities between them.
3700 void LSRInstance::GenerateCrossUseConstantOffsets() {
3701 // Group the registers by their value without any added constant offset.
3702 typedef std::map<int64_t, const SCEV *> ImmMapTy;
3703 typedef DenseMap<const SCEV *, ImmMapTy> RegMapTy;
3705 DenseMap<const SCEV *, SmallBitVector> UsedByIndicesMap;
3706 SmallVector<const SCEV *, 8> Sequence;
3707 for (RegUseTracker::const_iterator I = RegUses.begin(), E = RegUses.end();
3709 const SCEV *Reg = *I;
3710 int64_t Imm = ExtractImmediate(Reg, SE);
3711 std::pair<RegMapTy::iterator, bool> Pair =
3712 Map.insert(std::make_pair(Reg, ImmMapTy()));
3714 Sequence.push_back(Reg);
3715 Pair.first->second.insert(std::make_pair(Imm, *I));
3716 UsedByIndicesMap[Reg] |= RegUses.getUsedByIndices(*I);
3719 // Now examine each set of registers with the same base value. Build up
3720 // a list of work to do and do the work in a separate step so that we're
3721 // not adding formulae and register counts while we're searching.
3722 SmallVector<WorkItem, 32> WorkItems;
3723 SmallSet<std::pair<size_t, int64_t>, 32> UniqueItems;
3724 for (SmallVectorImpl<const SCEV *>::const_iterator I = Sequence.begin(),
3725 E = Sequence.end(); I != E; ++I) {
3726 const SCEV *Reg = *I;
3727 const ImmMapTy &Imms = Map.find(Reg)->second;
3729 // It's not worthwhile looking for reuse if there's only one offset.
3730 if (Imms.size() == 1)
3733 DEBUG(dbgs() << "Generating cross-use offsets for " << *Reg << ':';
3734 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
3736 dbgs() << ' ' << J->first;
3739 // Examine each offset.
3740 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
3742 const SCEV *OrigReg = J->second;
3744 int64_t JImm = J->first;
3745 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg);
3747 if (!isa<SCEVConstant>(OrigReg) &&
3748 UsedByIndicesMap[Reg].count() == 1) {
3749 DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg << '\n');
3753 // Conservatively examine offsets between this orig reg a few selected
3755 ImmMapTy::const_iterator OtherImms[] = {
3756 Imms.begin(), std::prev(Imms.end()),
3757 Imms.lower_bound((Imms.begin()->first + std::prev(Imms.end())->first) /
3760 for (size_t i = 0, e = array_lengthof(OtherImms); i != e; ++i) {
3761 ImmMapTy::const_iterator M = OtherImms[i];
3762 if (M == J || M == JE) continue;
3764 // Compute the difference between the two.
3765 int64_t Imm = (uint64_t)JImm - M->first;
3766 for (int LUIdx = UsedByIndices.find_first(); LUIdx != -1;
3767 LUIdx = UsedByIndices.find_next(LUIdx))
3768 // Make a memo of this use, offset, and register tuple.
3769 if (UniqueItems.insert(std::make_pair(LUIdx, Imm)).second)
3770 WorkItems.push_back(WorkItem(LUIdx, Imm, OrigReg));
3777 UsedByIndicesMap.clear();
3778 UniqueItems.clear();
3780 // Now iterate through the worklist and add new formulae.
3781 for (SmallVectorImpl<WorkItem>::const_iterator I = WorkItems.begin(),
3782 E = WorkItems.end(); I != E; ++I) {
3783 const WorkItem &WI = *I;
3784 size_t LUIdx = WI.LUIdx;
3785 LSRUse &LU = Uses[LUIdx];
3786 int64_t Imm = WI.Imm;
3787 const SCEV *OrigReg = WI.OrigReg;
3789 Type *IntTy = SE.getEffectiveSCEVType(OrigReg->getType());
3790 const SCEV *NegImmS = SE.getSCEV(ConstantInt::get(IntTy, -(uint64_t)Imm));
3791 unsigned BitWidth = SE.getTypeSizeInBits(IntTy);
3793 // TODO: Use a more targeted data structure.
3794 for (size_t L = 0, LE = LU.Formulae.size(); L != LE; ++L) {
3795 Formula F = LU.Formulae[L];
3796 // FIXME: The code for the scaled and unscaled registers looks
3797 // very similar but slightly different. Investigate if they
3798 // could be merged. That way, we would not have to unscale the
3801 // Use the immediate in the scaled register.
3802 if (F.ScaledReg == OrigReg) {
3803 int64_t Offset = (uint64_t)F.BaseOffset + Imm * (uint64_t)F.Scale;
3804 // Don't create 50 + reg(-50).
3805 if (F.referencesReg(SE.getSCEV(
3806 ConstantInt::get(IntTy, -(uint64_t)Offset))))
3809 NewF.BaseOffset = Offset;
3810 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
3813 NewF.ScaledReg = SE.getAddExpr(NegImmS, NewF.ScaledReg);
3815 // If the new scale is a constant in a register, and adding the constant
3816 // value to the immediate would produce a value closer to zero than the
3817 // immediate itself, then the formula isn't worthwhile.
3818 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewF.ScaledReg))
3819 if (C->getValue()->isNegative() !=
3820 (NewF.BaseOffset < 0) &&
3821 (C->getValue()->getValue().abs() * APInt(BitWidth, F.Scale))
3822 .ule(std::abs(NewF.BaseOffset)))
3826 NewF.Canonicalize();
3827 (void)InsertFormula(LU, LUIdx, NewF);
3829 // Use the immediate in a base register.
3830 for (size_t N = 0, NE = F.BaseRegs.size(); N != NE; ++N) {
3831 const SCEV *BaseReg = F.BaseRegs[N];
3832 if (BaseReg != OrigReg)
3835 NewF.BaseOffset = (uint64_t)NewF.BaseOffset + Imm;
3836 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset,
3837 LU.Kind, LU.AccessTy, NewF)) {
3838 if (!TTI.isLegalAddImmediate((uint64_t)NewF.UnfoldedOffset + Imm))
3841 NewF.UnfoldedOffset = (uint64_t)NewF.UnfoldedOffset + Imm;
3843 NewF.BaseRegs[N] = SE.getAddExpr(NegImmS, BaseReg);
3845 // If the new formula has a constant in a register, and adding the
3846 // constant value to the immediate would produce a value closer to
3847 // zero than the immediate itself, then the formula isn't worthwhile.
3848 for (const SCEV *NewReg : NewF.BaseRegs)
3849 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewReg))
3850 if ((C->getValue()->getValue() + NewF.BaseOffset).abs().slt(
3851 std::abs(NewF.BaseOffset)) &&
3852 (C->getValue()->getValue() +
3853 NewF.BaseOffset).countTrailingZeros() >=
3854 countTrailingZeros<uint64_t>(NewF.BaseOffset))
3858 NewF.Canonicalize();
3859 (void)InsertFormula(LU, LUIdx, NewF);
3868 /// GenerateAllReuseFormulae - Generate formulae for each use.
3870 LSRInstance::GenerateAllReuseFormulae() {
3871 // This is split into multiple loops so that hasRegsUsedByUsesOtherThan
3872 // queries are more precise.
3873 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3874 LSRUse &LU = Uses[LUIdx];
3875 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3876 GenerateReassociations(LU, LUIdx, LU.Formulae[i]);
3877 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3878 GenerateCombinations(LU, LUIdx, LU.Formulae[i]);
3880 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3881 LSRUse &LU = Uses[LUIdx];
3882 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3883 GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]);
3884 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3885 GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]);
3886 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3887 GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]);
3888 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3889 GenerateScales(LU, LUIdx, LU.Formulae[i]);
3891 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3892 LSRUse &LU = Uses[LUIdx];
3893 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3894 GenerateTruncates(LU, LUIdx, LU.Formulae[i]);
3897 GenerateCrossUseConstantOffsets();
3899 DEBUG(dbgs() << "\n"
3900 "After generating reuse formulae:\n";
3901 print_uses(dbgs()));
3904 /// If there are multiple formulae with the same set of registers used
3905 /// by other uses, pick the best one and delete the others.
3906 void LSRInstance::FilterOutUndesirableDedicatedRegisters() {
3907 DenseSet<const SCEV *> VisitedRegs;
3908 SmallPtrSet<const SCEV *, 16> Regs;
3909 SmallPtrSet<const SCEV *, 16> LoserRegs;
3911 bool ChangedFormulae = false;
3914 // Collect the best formula for each unique set of shared registers. This
3915 // is reset for each use.
3916 typedef DenseMap<SmallVector<const SCEV *, 4>, size_t, UniquifierDenseMapInfo>
3918 BestFormulaeTy BestFormulae;
3920 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3921 LSRUse &LU = Uses[LUIdx];
3922 DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs()); dbgs() << '\n');
3925 for (size_t FIdx = 0, NumForms = LU.Formulae.size();
3926 FIdx != NumForms; ++FIdx) {
3927 Formula &F = LU.Formulae[FIdx];
3929 // Some formulas are instant losers. For example, they may depend on
3930 // nonexistent AddRecs from other loops. These need to be filtered
3931 // immediately, otherwise heuristics could choose them over others leading
3932 // to an unsatisfactory solution. Passing LoserRegs into RateFormula here
3933 // avoids the need to recompute this information across formulae using the
3934 // same bad AddRec. Passing LoserRegs is also essential unless we remove
3935 // the corresponding bad register from the Regs set.
3938 CostF.RateFormula(TTI, F, Regs, VisitedRegs, L, LU.Offsets, SE, DT, LU,
3940 if (CostF.isLoser()) {
3941 // During initial formula generation, undesirable formulae are generated
3942 // by uses within other loops that have some non-trivial address mode or
3943 // use the postinc form of the IV. LSR needs to provide these formulae
3944 // as the basis of rediscovering the desired formula that uses an AddRec
3945 // corresponding to the existing phi. Once all formulae have been
3946 // generated, these initial losers may be pruned.
3947 DEBUG(dbgs() << " Filtering loser "; F.print(dbgs());
3951 SmallVector<const SCEV *, 4> Key;
3952 for (const SCEV *Reg : F.BaseRegs) {
3953 if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx))
3957 RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx))
3958 Key.push_back(F.ScaledReg);
3959 // Unstable sort by host order ok, because this is only used for
3961 std::sort(Key.begin(), Key.end());
3963 std::pair<BestFormulaeTy::const_iterator, bool> P =
3964 BestFormulae.insert(std::make_pair(Key, FIdx));
3968 Formula &Best = LU.Formulae[P.first->second];
3972 CostBest.RateFormula(TTI, Best, Regs, VisitedRegs, L, LU.Offsets, SE,
3974 if (CostF < CostBest)
3976 DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs());
3978 " in favor of formula "; Best.print(dbgs());
3982 ChangedFormulae = true;
3984 LU.DeleteFormula(F);
3990 // Now that we've filtered out some formulae, recompute the Regs set.
3992 LU.RecomputeRegs(LUIdx, RegUses);
3994 // Reset this to prepare for the next use.
3995 BestFormulae.clear();
3998 DEBUG(if (ChangedFormulae) {
4000 "After filtering out undesirable candidates:\n";
4005 // This is a rough guess that seems to work fairly well.
4006 static const size_t ComplexityLimit = UINT16_MAX;
4008 /// EstimateSearchSpaceComplexity - Estimate the worst-case number of
4009 /// solutions the solver might have to consider. It almost never considers
4010 /// this many solutions because it prune the search space, but the pruning
4011 /// isn't always sufficient.
4012 size_t LSRInstance::EstimateSearchSpaceComplexity() const {
4014 for (const LSRUse &LU : Uses) {
4015 size_t FSize = LU.Formulae.size();
4016 if (FSize >= ComplexityLimit) {
4017 Power = ComplexityLimit;
4021 if (Power >= ComplexityLimit)
4027 /// NarrowSearchSpaceByDetectingSupersets - When one formula uses a superset
4028 /// of the registers of another formula, it won't help reduce register
4029 /// pressure (though it may not necessarily hurt register pressure); remove
4030 /// it to simplify the system.
4031 void LSRInstance::NarrowSearchSpaceByDetectingSupersets() {
4032 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
4033 DEBUG(dbgs() << "The search space is too complex.\n");
4035 DEBUG(dbgs() << "Narrowing the search space by eliminating formulae "
4036 "which use a superset of registers used by other "
4039 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4040 LSRUse &LU = Uses[LUIdx];
4042 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
4043 Formula &F = LU.Formulae[i];
4044 // Look for a formula with a constant or GV in a register. If the use
4045 // also has a formula with that same value in an immediate field,
4046 // delete the one that uses a register.
4047 for (SmallVectorImpl<const SCEV *>::const_iterator
4048 I = F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I) {
4049 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*I)) {
4051 NewF.BaseOffset += C->getValue()->getSExtValue();
4052 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
4053 (I - F.BaseRegs.begin()));
4054 if (LU.HasFormulaWithSameRegs(NewF)) {
4055 DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
4056 LU.DeleteFormula(F);
4062 } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(*I)) {
4063 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue()))
4067 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
4068 (I - F.BaseRegs.begin()));
4069 if (LU.HasFormulaWithSameRegs(NewF)) {
4070 DEBUG(dbgs() << " Deleting "; F.print(dbgs());
4072 LU.DeleteFormula(F);
4083 LU.RecomputeRegs(LUIdx, RegUses);
4086 DEBUG(dbgs() << "After pre-selection:\n";
4087 print_uses(dbgs()));
4091 /// NarrowSearchSpaceByCollapsingUnrolledCode - When there are many registers
4092 /// for expressions like A, A+1, A+2, etc., allocate a single register for
4094 void LSRInstance::NarrowSearchSpaceByCollapsingUnrolledCode() {
4095 if (EstimateSearchSpaceComplexity() < ComplexityLimit)
4098 DEBUG(dbgs() << "The search space is too complex.\n"
4099 "Narrowing the search space by assuming that uses separated "
4100 "by a constant offset will use the same registers.\n");
4102 // This is especially useful for unrolled loops.
4104 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4105 LSRUse &LU = Uses[LUIdx];
4106 for (const Formula &F : LU.Formulae) {
4107 if (F.BaseOffset == 0 || (F.Scale != 0 && F.Scale != 1))
4110 LSRUse *LUThatHas = FindUseWithSimilarFormula(F, LU);
4114 if (!reconcileNewOffset(*LUThatHas, F.BaseOffset, /*HasBaseReg=*/ false,
4115 LU.Kind, LU.AccessTy))
4118 DEBUG(dbgs() << " Deleting use "; LU.print(dbgs()); dbgs() << '\n');
4120 LUThatHas->AllFixupsOutsideLoop &= LU.AllFixupsOutsideLoop;
4122 // Update the relocs to reference the new use.
4123 for (LSRFixup &Fixup : Fixups) {
4124 if (Fixup.LUIdx == LUIdx) {
4125 Fixup.LUIdx = LUThatHas - &Uses.front();
4126 Fixup.Offset += F.BaseOffset;
4127 // Add the new offset to LUThatHas' offset list.
4128 if (LUThatHas->Offsets.back() != Fixup.Offset) {
4129 LUThatHas->Offsets.push_back(Fixup.Offset);
4130 if (Fixup.Offset > LUThatHas->MaxOffset)
4131 LUThatHas->MaxOffset = Fixup.Offset;
4132 if (Fixup.Offset < LUThatHas->MinOffset)
4133 LUThatHas->MinOffset = Fixup.Offset;
4135 DEBUG(dbgs() << "New fixup has offset " << Fixup.Offset << '\n');
4137 if (Fixup.LUIdx == NumUses-1)
4138 Fixup.LUIdx = LUIdx;
4141 // Delete formulae from the new use which are no longer legal.
4143 for (size_t i = 0, e = LUThatHas->Formulae.size(); i != e; ++i) {
4144 Formula &F = LUThatHas->Formulae[i];
4145 if (!isLegalUse(TTI, LUThatHas->MinOffset, LUThatHas->MaxOffset,
4146 LUThatHas->Kind, LUThatHas->AccessTy, F)) {
4147 DEBUG(dbgs() << " Deleting "; F.print(dbgs());
4149 LUThatHas->DeleteFormula(F);
4157 LUThatHas->RecomputeRegs(LUThatHas - &Uses.front(), RegUses);
4159 // Delete the old use.
4160 DeleteUse(LU, LUIdx);
4167 DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
4170 /// NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters - Call
4171 /// FilterOutUndesirableDedicatedRegisters again, if necessary, now that
4172 /// we've done more filtering, as it may be able to find more formulae to
4174 void LSRInstance::NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters(){
4175 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
4176 DEBUG(dbgs() << "The search space is too complex.\n");
4178 DEBUG(dbgs() << "Narrowing the search space by re-filtering out "
4179 "undesirable dedicated registers.\n");
4181 FilterOutUndesirableDedicatedRegisters();
4183 DEBUG(dbgs() << "After pre-selection:\n";
4184 print_uses(dbgs()));
4188 /// NarrowSearchSpaceByPickingWinnerRegs - Pick a register which seems likely
4189 /// to be profitable, and then in any use which has any reference to that
4190 /// register, delete all formulae which do not reference that register.
4191 void LSRInstance::NarrowSearchSpaceByPickingWinnerRegs() {
4192 // With all other options exhausted, loop until the system is simple
4193 // enough to handle.
4194 SmallPtrSet<const SCEV *, 4> Taken;
4195 while (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
4196 // Ok, we have too many of formulae on our hands to conveniently handle.
4197 // Use a rough heuristic to thin out the list.
4198 DEBUG(dbgs() << "The search space is too complex.\n");
4200 // Pick the register which is used by the most LSRUses, which is likely
4201 // to be a good reuse register candidate.
4202 const SCEV *Best = nullptr;
4203 unsigned BestNum = 0;
4204 for (const SCEV *Reg : RegUses) {
4205 if (Taken.count(Reg))
4210 unsigned Count = RegUses.getUsedByIndices(Reg).count();
4211 if (Count > BestNum) {
4218 DEBUG(dbgs() << "Narrowing the search space by assuming " << *Best
4219 << " will yield profitable reuse.\n");
4222 // In any use with formulae which references this register, delete formulae
4223 // which don't reference it.
4224 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4225 LSRUse &LU = Uses[LUIdx];
4226 if (!LU.Regs.count(Best)) continue;
4229 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
4230 Formula &F = LU.Formulae[i];
4231 if (!F.referencesReg(Best)) {
4232 DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
4233 LU.DeleteFormula(F);
4237 assert(e != 0 && "Use has no formulae left! Is Regs inconsistent?");
4243 LU.RecomputeRegs(LUIdx, RegUses);
4246 DEBUG(dbgs() << "After pre-selection:\n";
4247 print_uses(dbgs()));
4251 /// NarrowSearchSpaceUsingHeuristics - If there are an extraordinary number of
4252 /// formulae to choose from, use some rough heuristics to prune down the number
4253 /// of formulae. This keeps the main solver from taking an extraordinary amount
4254 /// of time in some worst-case scenarios.
4255 void LSRInstance::NarrowSearchSpaceUsingHeuristics() {
4256 NarrowSearchSpaceByDetectingSupersets();
4257 NarrowSearchSpaceByCollapsingUnrolledCode();
4258 NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
4259 NarrowSearchSpaceByPickingWinnerRegs();
4262 /// SolveRecurse - This is the recursive solver.
4263 void LSRInstance::SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
4265 SmallVectorImpl<const Formula *> &Workspace,
4266 const Cost &CurCost,
4267 const SmallPtrSet<const SCEV *, 16> &CurRegs,
4268 DenseSet<const SCEV *> &VisitedRegs) const {
4271 // - use more aggressive filtering
4272 // - sort the formula so that the most profitable solutions are found first
4273 // - sort the uses too
4275 // - don't compute a cost, and then compare. compare while computing a cost
4277 // - track register sets with SmallBitVector
4279 const LSRUse &LU = Uses[Workspace.size()];
4281 // If this use references any register that's already a part of the
4282 // in-progress solution, consider it a requirement that a formula must
4283 // reference that register in order to be considered. This prunes out
4284 // unprofitable searching.
4285 SmallSetVector<const SCEV *, 4> ReqRegs;
4286 for (const SCEV *S : CurRegs)
4287 if (LU.Regs.count(S))
4290 SmallPtrSet<const SCEV *, 16> NewRegs;
4292 for (const Formula &F : LU.Formulae) {
4293 // Ignore formulae which may not be ideal in terms of register reuse of
4294 // ReqRegs. The formula should use all required registers before
4295 // introducing new ones.
4296 int NumReqRegsToFind = std::min(F.getNumRegs(), ReqRegs.size());
4297 for (const SCEV *Reg : ReqRegs) {
4298 if ((F.ScaledReg && F.ScaledReg == Reg) ||
4299 std::find(F.BaseRegs.begin(), F.BaseRegs.end(), Reg) !=
4302 if (NumReqRegsToFind == 0)
4306 if (NumReqRegsToFind != 0) {
4307 // If none of the formulae satisfied the required registers, then we could
4308 // clear ReqRegs and try again. Currently, we simply give up in this case.
4312 // Evaluate the cost of the current formula. If it's already worse than
4313 // the current best, prune the search at that point.
4316 NewCost.RateFormula(TTI, F, NewRegs, VisitedRegs, L, LU.Offsets, SE, DT,
4318 if (NewCost < SolutionCost) {
4319 Workspace.push_back(&F);
4320 if (Workspace.size() != Uses.size()) {
4321 SolveRecurse(Solution, SolutionCost, Workspace, NewCost,
4322 NewRegs, VisitedRegs);
4323 if (F.getNumRegs() == 1 && Workspace.size() == 1)
4324 VisitedRegs.insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]);
4326 DEBUG(dbgs() << "New best at "; NewCost.print(dbgs());
4327 dbgs() << ".\n Regs:";
4328 for (const SCEV *S : NewRegs)
4329 dbgs() << ' ' << *S;
4332 SolutionCost = NewCost;
4333 Solution = Workspace;
4335 Workspace.pop_back();
4340 /// Solve - Choose one formula from each use. Return the results in the given
4341 /// Solution vector.
4342 void LSRInstance::Solve(SmallVectorImpl<const Formula *> &Solution) const {
4343 SmallVector<const Formula *, 8> Workspace;
4345 SolutionCost.Lose();
4347 SmallPtrSet<const SCEV *, 16> CurRegs;
4348 DenseSet<const SCEV *> VisitedRegs;
4349 Workspace.reserve(Uses.size());
4351 // SolveRecurse does all the work.
4352 SolveRecurse(Solution, SolutionCost, Workspace, CurCost,
4353 CurRegs, VisitedRegs);
4354 if (Solution.empty()) {
4355 DEBUG(dbgs() << "\nNo Satisfactory Solution\n");
4359 // Ok, we've now made all our decisions.
4360 DEBUG(dbgs() << "\n"
4361 "The chosen solution requires "; SolutionCost.print(dbgs());
4363 for (size_t i = 0, e = Uses.size(); i != e; ++i) {
4365 Uses[i].print(dbgs());
4368 Solution[i]->print(dbgs());
4372 assert(Solution.size() == Uses.size() && "Malformed solution!");
4375 /// HoistInsertPosition - Helper for AdjustInsertPositionForExpand. Climb up
4376 /// the dominator tree far as we can go while still being dominated by the
4377 /// input positions. This helps canonicalize the insert position, which
4378 /// encourages sharing.
4379 BasicBlock::iterator
4380 LSRInstance::HoistInsertPosition(BasicBlock::iterator IP,
4381 const SmallVectorImpl<Instruction *> &Inputs)
4384 const Loop *IPLoop = LI.getLoopFor(IP->getParent());
4385 unsigned IPLoopDepth = IPLoop ? IPLoop->getLoopDepth() : 0;
4388 for (DomTreeNode *Rung = DT.getNode(IP->getParent()); ; ) {
4389 if (!Rung) return IP;
4390 Rung = Rung->getIDom();
4391 if (!Rung) return IP;
4392 IDom = Rung->getBlock();
4394 // Don't climb into a loop though.
4395 const Loop *IDomLoop = LI.getLoopFor(IDom);
4396 unsigned IDomDepth = IDomLoop ? IDomLoop->getLoopDepth() : 0;
4397 if (IDomDepth <= IPLoopDepth &&
4398 (IDomDepth != IPLoopDepth || IDomLoop == IPLoop))
4402 bool AllDominate = true;
4403 Instruction *BetterPos = nullptr;
4404 Instruction *Tentative = IDom->getTerminator();
4405 for (Instruction *Inst : Inputs) {
4406 if (Inst == Tentative || !DT.dominates(Inst, Tentative)) {
4407 AllDominate = false;
4410 // Attempt to find an insert position in the middle of the block,
4411 // instead of at the end, so that it can be used for other expansions.
4412 if (IDom == Inst->getParent() &&
4413 (!BetterPos || !DT.dominates(Inst, BetterPos)))
4414 BetterPos = std::next(BasicBlock::iterator(Inst));
4427 /// AdjustInsertPositionForExpand - Determine an input position which will be
4428 /// dominated by the operands and which will dominate the result.
4429 BasicBlock::iterator
4430 LSRInstance::AdjustInsertPositionForExpand(BasicBlock::iterator LowestIP,
4433 SCEVExpander &Rewriter) const {
4434 // Collect some instructions which must be dominated by the
4435 // expanding replacement. These must be dominated by any operands that
4436 // will be required in the expansion.
4437 SmallVector<Instruction *, 4> Inputs;
4438 if (Instruction *I = dyn_cast<Instruction>(LF.OperandValToReplace))
4439 Inputs.push_back(I);
4440 if (LU.Kind == LSRUse::ICmpZero)
4441 if (Instruction *I =
4442 dyn_cast<Instruction>(cast<ICmpInst>(LF.UserInst)->getOperand(1)))
4443 Inputs.push_back(I);
4444 if (LF.PostIncLoops.count(L)) {
4445 if (LF.isUseFullyOutsideLoop(L))
4446 Inputs.push_back(L->getLoopLatch()->getTerminator());
4448 Inputs.push_back(IVIncInsertPos);
4450 // The expansion must also be dominated by the increment positions of any
4451 // loops it for which it is using post-inc mode.
4452 for (const Loop *PIL : LF.PostIncLoops) {
4453 if (PIL == L) continue;
4455 // Be dominated by the loop exit.
4456 SmallVector<BasicBlock *, 4> ExitingBlocks;
4457 PIL->getExitingBlocks(ExitingBlocks);
4458 if (!ExitingBlocks.empty()) {
4459 BasicBlock *BB = ExitingBlocks[0];
4460 for (unsigned i = 1, e = ExitingBlocks.size(); i != e; ++i)
4461 BB = DT.findNearestCommonDominator(BB, ExitingBlocks[i]);
4462 Inputs.push_back(BB->getTerminator());
4466 assert(!isa<PHINode>(LowestIP) && !isa<LandingPadInst>(LowestIP)
4467 && !isa<DbgInfoIntrinsic>(LowestIP) &&
4468 "Insertion point must be a normal instruction");
4470 // Then, climb up the immediate dominator tree as far as we can go while
4471 // still being dominated by the input positions.
4472 BasicBlock::iterator IP = HoistInsertPosition(LowestIP, Inputs);
4474 // Don't insert instructions before PHI nodes.
4475 while (isa<PHINode>(IP)) ++IP;
4477 // Ignore landingpad instructions.
4478 while (isa<LandingPadInst>(IP)) ++IP;
4480 // Ignore debug intrinsics.
4481 while (isa<DbgInfoIntrinsic>(IP)) ++IP;
4483 // Set IP below instructions recently inserted by SCEVExpander. This keeps the
4484 // IP consistent across expansions and allows the previously inserted
4485 // instructions to be reused by subsequent expansion.
4486 while (Rewriter.isInsertedInstruction(IP) && IP != LowestIP) ++IP;
4491 /// Expand - Emit instructions for the leading candidate expression for this
4492 /// LSRUse (this is called "expanding").
4493 Value *LSRInstance::Expand(const LSRFixup &LF,
4495 BasicBlock::iterator IP,
4496 SCEVExpander &Rewriter,
4497 SmallVectorImpl<WeakVH> &DeadInsts) const {
4498 const LSRUse &LU = Uses[LF.LUIdx];
4499 if (LU.RigidFormula)
4500 return LF.OperandValToReplace;
4502 // Determine an input position which will be dominated by the operands and
4503 // which will dominate the result.
4504 IP = AdjustInsertPositionForExpand(IP, LF, LU, Rewriter);
4506 // Inform the Rewriter if we have a post-increment use, so that it can
4507 // perform an advantageous expansion.
4508 Rewriter.setPostInc(LF.PostIncLoops);
4510 // This is the type that the user actually needs.
4511 Type *OpTy = LF.OperandValToReplace->getType();
4512 // This will be the type that we'll initially expand to.
4513 Type *Ty = F.getType();
4515 // No type known; just expand directly to the ultimate type.
4517 else if (SE.getEffectiveSCEVType(Ty) == SE.getEffectiveSCEVType(OpTy))
4518 // Expand directly to the ultimate type if it's the right size.
4520 // This is the type to do integer arithmetic in.
4521 Type *IntTy = SE.getEffectiveSCEVType(Ty);
4523 // Build up a list of operands to add together to form the full base.
4524 SmallVector<const SCEV *, 8> Ops;
4526 // Expand the BaseRegs portion.
4527 for (const SCEV *Reg : F.BaseRegs) {
4528 assert(!Reg->isZero() && "Zero allocated in a base register!");
4530 // If we're expanding for a post-inc user, make the post-inc adjustment.
4531 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
4532 Reg = TransformForPostIncUse(Denormalize, Reg,
4533 LF.UserInst, LF.OperandValToReplace,
4536 Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, nullptr, IP)));
4539 // Expand the ScaledReg portion.
4540 Value *ICmpScaledV = nullptr;
4542 const SCEV *ScaledS = F.ScaledReg;
4544 // If we're expanding for a post-inc user, make the post-inc adjustment.
4545 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
4546 ScaledS = TransformForPostIncUse(Denormalize, ScaledS,
4547 LF.UserInst, LF.OperandValToReplace,
4550 if (LU.Kind == LSRUse::ICmpZero) {
4551 // Expand ScaleReg as if it was part of the base regs.
4554 SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr, IP)));
4556 // An interesting way of "folding" with an icmp is to use a negated
4557 // scale, which we'll implement by inserting it into the other operand
4559 assert(F.Scale == -1 &&
4560 "The only scale supported by ICmpZero uses is -1!");
4561 ICmpScaledV = Rewriter.expandCodeFor(ScaledS, nullptr, IP);
4564 // Otherwise just expand the scaled register and an explicit scale,
4565 // which is expected to be matched as part of the address.
4567 // Flush the operand list to suppress SCEVExpander hoisting address modes.
4568 // Unless the addressing mode will not be folded.
4569 if (!Ops.empty() && LU.Kind == LSRUse::Address &&
4570 isAMCompletelyFolded(TTI, LU, F)) {
4571 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
4573 Ops.push_back(SE.getUnknown(FullV));
4575 ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr, IP));
4578 SE.getMulExpr(ScaledS, SE.getConstant(ScaledS->getType(), F.Scale));
4579 Ops.push_back(ScaledS);
4583 // Expand the GV portion.
4585 // Flush the operand list to suppress SCEVExpander hoisting.
4587 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
4589 Ops.push_back(SE.getUnknown(FullV));
4591 Ops.push_back(SE.getUnknown(F.BaseGV));
4594 // Flush the operand list to suppress SCEVExpander hoisting of both folded and
4595 // unfolded offsets. LSR assumes they both live next to their uses.
4597 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
4599 Ops.push_back(SE.getUnknown(FullV));
4602 // Expand the immediate portion.
4603 int64_t Offset = (uint64_t)F.BaseOffset + LF.Offset;
4605 if (LU.Kind == LSRUse::ICmpZero) {
4606 // The other interesting way of "folding" with an ICmpZero is to use a
4607 // negated immediate.
4609 ICmpScaledV = ConstantInt::get(IntTy, -(uint64_t)Offset);
4611 Ops.push_back(SE.getUnknown(ICmpScaledV));
4612 ICmpScaledV = ConstantInt::get(IntTy, Offset);
4615 // Just add the immediate values. These again are expected to be matched
4616 // as part of the address.
4617 Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy, Offset)));
4621 // Expand the unfolded offset portion.
4622 int64_t UnfoldedOffset = F.UnfoldedOffset;
4623 if (UnfoldedOffset != 0) {
4624 // Just add the immediate values.
4625 Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy,
4629 // Emit instructions summing all the operands.
4630 const SCEV *FullS = Ops.empty() ?
4631 SE.getConstant(IntTy, 0) :
4633 Value *FullV = Rewriter.expandCodeFor(FullS, Ty, IP);
4635 // We're done expanding now, so reset the rewriter.
4636 Rewriter.clearPostInc();
4638 // An ICmpZero Formula represents an ICmp which we're handling as a
4639 // comparison against zero. Now that we've expanded an expression for that
4640 // form, update the ICmp's other operand.
4641 if (LU.Kind == LSRUse::ICmpZero) {
4642 ICmpInst *CI = cast<ICmpInst>(LF.UserInst);
4643 DeadInsts.push_back(CI->getOperand(1));
4644 assert(!F.BaseGV && "ICmp does not support folding a global value and "
4645 "a scale at the same time!");
4646 if (F.Scale == -1) {
4647 if (ICmpScaledV->getType() != OpTy) {
4649 CastInst::Create(CastInst::getCastOpcode(ICmpScaledV, false,
4651 ICmpScaledV, OpTy, "tmp", CI);
4654 CI->setOperand(1, ICmpScaledV);
4656 // A scale of 1 means that the scale has been expanded as part of the
4658 assert((F.Scale == 0 || F.Scale == 1) &&
4659 "ICmp does not support folding a global value and "
4660 "a scale at the same time!");
4661 Constant *C = ConstantInt::getSigned(SE.getEffectiveSCEVType(OpTy),
4663 if (C->getType() != OpTy)
4664 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4668 CI->setOperand(1, C);
4675 /// RewriteForPHI - Helper for Rewrite. PHI nodes are special because the use
4676 /// of their operands effectively happens in their predecessor blocks, so the
4677 /// expression may need to be expanded in multiple places.
4678 void LSRInstance::RewriteForPHI(PHINode *PN,
4681 SCEVExpander &Rewriter,
4682 SmallVectorImpl<WeakVH> &DeadInsts,
4684 DenseMap<BasicBlock *, Value *> Inserted;
4685 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4686 if (PN->getIncomingValue(i) == LF.OperandValToReplace) {
4687 BasicBlock *BB = PN->getIncomingBlock(i);
4689 // If this is a critical edge, split the edge so that we do not insert
4690 // the code on all predecessor/successor paths. We do this unless this
4691 // is the canonical backedge for this loop, which complicates post-inc
4693 if (e != 1 && BB->getTerminator()->getNumSuccessors() > 1 &&
4694 !isa<IndirectBrInst>(BB->getTerminator())) {
4695 BasicBlock *Parent = PN->getParent();
4696 Loop *PNLoop = LI.getLoopFor(Parent);
4697 if (!PNLoop || Parent != PNLoop->getHeader()) {
4698 // Split the critical edge.
4699 BasicBlock *NewBB = nullptr;
4700 if (!Parent->isLandingPad()) {
4701 NewBB = SplitCriticalEdge(BB, Parent,
4702 CriticalEdgeSplittingOptions(&DT, &LI)
4703 .setMergeIdenticalEdges()
4704 .setDontDeleteUselessPHIs());
4706 SmallVector<BasicBlock*, 2> NewBBs;
4707 SplitLandingPadPredecessors(Parent, BB, "", "", NewBBs,
4708 /*AliasAnalysis*/ nullptr, &DT, &LI);
4711 // If NewBB==NULL, then SplitCriticalEdge refused to split because all
4712 // phi predecessors are identical. The simple thing to do is skip
4713 // splitting in this case rather than complicate the API.
4715 // If PN is outside of the loop and BB is in the loop, we want to
4716 // move the block to be immediately before the PHI block, not
4717 // immediately after BB.
4718 if (L->contains(BB) && !L->contains(PN))
4719 NewBB->moveBefore(PN->getParent());
4721 // Splitting the edge can reduce the number of PHI entries we have.
4722 e = PN->getNumIncomingValues();
4724 i = PN->getBasicBlockIndex(BB);
4729 std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> Pair =
4730 Inserted.insert(std::make_pair(BB, static_cast<Value *>(nullptr)));
4732 PN->setIncomingValue(i, Pair.first->second);
4734 Value *FullV = Expand(LF, F, BB->getTerminator(), Rewriter, DeadInsts);
4736 // If this is reuse-by-noop-cast, insert the noop cast.
4737 Type *OpTy = LF.OperandValToReplace->getType();
4738 if (FullV->getType() != OpTy)
4740 CastInst::Create(CastInst::getCastOpcode(FullV, false,
4742 FullV, LF.OperandValToReplace->getType(),
4743 "tmp", BB->getTerminator());
4745 PN->setIncomingValue(i, FullV);
4746 Pair.first->second = FullV;
4751 /// Rewrite - Emit instructions for the leading candidate expression for this
4752 /// LSRUse (this is called "expanding"), and update the UserInst to reference
4753 /// the newly expanded value.
4754 void LSRInstance::Rewrite(const LSRFixup &LF,
4756 SCEVExpander &Rewriter,
4757 SmallVectorImpl<WeakVH> &DeadInsts,
4759 // First, find an insertion point that dominates UserInst. For PHI nodes,
4760 // find the nearest block which dominates all the relevant uses.
4761 if (PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) {
4762 RewriteForPHI(PN, LF, F, Rewriter, DeadInsts, P);
4764 Value *FullV = Expand(LF, F, LF.UserInst, Rewriter, DeadInsts);
4766 // If this is reuse-by-noop-cast, insert the noop cast.
4767 Type *OpTy = LF.OperandValToReplace->getType();
4768 if (FullV->getType() != OpTy) {
4770 CastInst::Create(CastInst::getCastOpcode(FullV, false, OpTy, false),
4771 FullV, OpTy, "tmp", LF.UserInst);
4775 // Update the user. ICmpZero is handled specially here (for now) because
4776 // Expand may have updated one of the operands of the icmp already, and
4777 // its new value may happen to be equal to LF.OperandValToReplace, in
4778 // which case doing replaceUsesOfWith leads to replacing both operands
4779 // with the same value. TODO: Reorganize this.
4780 if (Uses[LF.LUIdx].Kind == LSRUse::ICmpZero)
4781 LF.UserInst->setOperand(0, FullV);
4783 LF.UserInst->replaceUsesOfWith(LF.OperandValToReplace, FullV);
4786 DeadInsts.push_back(LF.OperandValToReplace);
4789 /// ImplementSolution - Rewrite all the fixup locations with new values,
4790 /// following the chosen solution.
4792 LSRInstance::ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
4794 // Keep track of instructions we may have made dead, so that
4795 // we can remove them after we are done working.
4796 SmallVector<WeakVH, 16> DeadInsts;
4798 SCEVExpander Rewriter(SE, L->getHeader()->getModule()->getDataLayout(),
4801 Rewriter.setDebugType(DEBUG_TYPE);
4803 Rewriter.disableCanonicalMode();
4804 Rewriter.enableLSRMode();
4805 Rewriter.setIVIncInsertPos(L, IVIncInsertPos);
4807 // Mark phi nodes that terminate chains so the expander tries to reuse them.
4808 for (const IVChain &Chain : IVChainVec) {
4809 if (PHINode *PN = dyn_cast<PHINode>(Chain.tailUserInst()))
4810 Rewriter.setChainedPhi(PN);
4813 // Expand the new value definitions and update the users.
4814 for (const LSRFixup &Fixup : Fixups) {
4815 Rewrite(Fixup, *Solution[Fixup.LUIdx], Rewriter, DeadInsts, P);
4820 for (const IVChain &Chain : IVChainVec) {
4821 GenerateIVChain(Chain, Rewriter, DeadInsts);
4824 // Clean up after ourselves. This must be done before deleting any
4828 Changed |= DeleteTriviallyDeadInstructions(DeadInsts);
4831 LSRInstance::LSRInstance(Loop *L, Pass *P)
4832 : IU(P->getAnalysis<IVUsers>()), SE(P->getAnalysis<ScalarEvolution>()),
4833 DT(P->getAnalysis<DominatorTreeWrapperPass>().getDomTree()),
4834 LI(P->getAnalysis<LoopInfoWrapperPass>().getLoopInfo()),
4835 TTI(P->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
4836 *L->getHeader()->getParent())),
4837 L(L), Changed(false), IVIncInsertPos(nullptr) {
4838 // If LoopSimplify form is not available, stay out of trouble.
4839 if (!L->isLoopSimplifyForm())
4842 // If there's no interesting work to be done, bail early.
4843 if (IU.empty()) return;
4845 // If there's too much analysis to be done, bail early. We won't be able to
4846 // model the problem anyway.
4847 unsigned NumUsers = 0;
4848 for (const IVStrideUse &U : IU) {
4849 if (++NumUsers > MaxIVUsers) {
4851 DEBUG(dbgs() << "LSR skipping loop, too many IV Users in " << U << "\n");
4857 // All dominating loops must have preheaders, or SCEVExpander may not be able
4858 // to materialize an AddRecExpr whose Start is an outer AddRecExpr.
4860 // IVUsers analysis should only create users that are dominated by simple loop
4861 // headers. Since this loop should dominate all of its users, its user list
4862 // should be empty if this loop itself is not within a simple loop nest.
4863 for (DomTreeNode *Rung = DT.getNode(L->getLoopPreheader());
4864 Rung; Rung = Rung->getIDom()) {
4865 BasicBlock *BB = Rung->getBlock();
4866 const Loop *DomLoop = LI.getLoopFor(BB);
4867 if (DomLoop && DomLoop->getHeader() == BB) {
4868 assert(DomLoop->getLoopPreheader() && "LSR needs a simplified loop nest");
4873 DEBUG(dbgs() << "\nLSR on loop ";
4874 L->getHeader()->printAsOperand(dbgs(), /*PrintType=*/false);
4877 // First, perform some low-level loop optimizations.
4879 OptimizeLoopTermCond();
4881 // If loop preparation eliminates all interesting IV users, bail.
4882 if (IU.empty()) return;
4884 // Skip nested loops until we can model them better with formulae.
4886 DEBUG(dbgs() << "LSR skipping outer loop " << *L << "\n");
4890 // Start collecting data and preparing for the solver.
4892 CollectInterestingTypesAndFactors();
4893 CollectFixupsAndInitialFormulae();
4894 CollectLoopInvariantFixupsAndFormulae();
4896 assert(!Uses.empty() && "IVUsers reported at least one use");
4897 DEBUG(dbgs() << "LSR found " << Uses.size() << " uses:\n";
4898 print_uses(dbgs()));
4900 // Now use the reuse data to generate a bunch of interesting ways
4901 // to formulate the values needed for the uses.
4902 GenerateAllReuseFormulae();
4904 FilterOutUndesirableDedicatedRegisters();
4905 NarrowSearchSpaceUsingHeuristics();
4907 SmallVector<const Formula *, 8> Solution;
4910 // Release memory that is no longer needed.
4915 if (Solution.empty())
4919 // Formulae should be legal.
4920 for (const LSRUse &LU : Uses) {
4921 for (const Formula &F : LU.Formulae)
4922 assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
4923 F) && "Illegal formula generated!");
4927 // Now that we've decided what we want, make it so.
4928 ImplementSolution(Solution, P);
4931 void LSRInstance::print_factors_and_types(raw_ostream &OS) const {
4932 if (Factors.empty() && Types.empty()) return;
4934 OS << "LSR has identified the following interesting factors and types: ";
4937 for (int64_t Factor : Factors) {
4938 if (!First) OS << ", ";
4940 OS << '*' << Factor;
4943 for (Type *Ty : Types) {
4944 if (!First) OS << ", ";
4946 OS << '(' << *Ty << ')';
4951 void LSRInstance::print_fixups(raw_ostream &OS) const {
4952 OS << "LSR is examining the following fixup sites:\n";
4953 for (const LSRFixup &LF : Fixups) {
4960 void LSRInstance::print_uses(raw_ostream &OS) const {
4961 OS << "LSR is examining the following uses:\n";
4962 for (const LSRUse &LU : Uses) {
4966 for (const Formula &F : LU.Formulae) {
4974 void LSRInstance::print(raw_ostream &OS) const {
4975 print_factors_and_types(OS);
4980 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4981 void LSRInstance::dump() const {
4982 print(errs()); errs() << '\n';
4988 class LoopStrengthReduce : public LoopPass {
4990 static char ID; // Pass ID, replacement for typeid
4991 LoopStrengthReduce();
4994 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
4995 void getAnalysisUsage(AnalysisUsage &AU) const override;
5000 char LoopStrengthReduce::ID = 0;
5001 INITIALIZE_PASS_BEGIN(LoopStrengthReduce, "loop-reduce",
5002 "Loop Strength Reduction", false, false)
5003 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
5004 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
5005 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
5006 INITIALIZE_PASS_DEPENDENCY(IVUsers)
5007 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
5008 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5009 INITIALIZE_PASS_END(LoopStrengthReduce, "loop-reduce",
5010 "Loop Strength Reduction", false, false)
5013 Pass *llvm::createLoopStrengthReducePass() {
5014 return new LoopStrengthReduce();
5017 LoopStrengthReduce::LoopStrengthReduce() : LoopPass(ID) {
5018 initializeLoopStrengthReducePass(*PassRegistry::getPassRegistry());
5021 void LoopStrengthReduce::getAnalysisUsage(AnalysisUsage &AU) const {
5022 // We split critical edges, so we change the CFG. However, we do update
5023 // many analyses if they are around.
5024 AU.addPreservedID(LoopSimplifyID);
5026 AU.addRequired<LoopInfoWrapperPass>();
5027 AU.addPreserved<LoopInfoWrapperPass>();
5028 AU.addRequiredID(LoopSimplifyID);
5029 AU.addRequired<DominatorTreeWrapperPass>();
5030 AU.addPreserved<DominatorTreeWrapperPass>();
5031 AU.addRequired<ScalarEvolution>();
5032 AU.addPreserved<ScalarEvolution>();
5033 // Requiring LoopSimplify a second time here prevents IVUsers from running
5034 // twice, since LoopSimplify was invalidated by running ScalarEvolution.
5035 AU.addRequiredID(LoopSimplifyID);
5036 AU.addRequired<IVUsers>();
5037 AU.addPreserved<IVUsers>();
5038 AU.addRequired<TargetTransformInfoWrapperPass>();
5041 bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager & /*LPM*/) {
5042 if (skipOptnoneFunction(L))
5045 bool Changed = false;
5047 // Run the main LSR transformation.
5048 Changed |= LSRInstance(L, this).getChanged();
5050 // Remove any extra phis created by processing inner loops.
5051 Changed |= DeleteDeadPHIs(L->getHeader());
5052 if (EnablePhiElim && L->isLoopSimplifyForm()) {
5053 SmallVector<WeakVH, 16> DeadInsts;
5054 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
5055 SCEVExpander Rewriter(getAnalysis<ScalarEvolution>(), DL, "lsr");
5057 Rewriter.setDebugType(DEBUG_TYPE);
5059 unsigned numFolded = Rewriter.replaceCongruentIVs(
5060 L, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(), DeadInsts,
5061 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
5062 *L->getHeader()->getParent()));
5065 DeleteTriviallyDeadInstructions(DeadInsts);
5066 DeleteDeadPHIs(L->getHeader());