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 (const SCEV *S : MyGood)
328 Good.push_back(SE.getMulExpr(NegOne, S));
329 for (const SCEV *S : MyBad)
330 Bad.push_back(SE.getMulExpr(NegOne, S));
334 // Ok, we can't do anything interesting. Just stuff the whole thing into a
335 // register and hope for the best.
339 /// InitialMatch - Incorporate loop-variant parts of S into this Formula,
340 /// attempting to keep all loop-invariant and loop-computable values in a
341 /// single base register.
342 void Formula::InitialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE) {
343 SmallVector<const SCEV *, 4> Good;
344 SmallVector<const SCEV *, 4> Bad;
345 DoInitialMatch(S, L, Good, Bad, SE);
347 const SCEV *Sum = SE.getAddExpr(Good);
349 BaseRegs.push_back(Sum);
353 const SCEV *Sum = SE.getAddExpr(Bad);
355 BaseRegs.push_back(Sum);
361 /// \brief Check whether or not this formula statisfies the canonical
363 /// \see Formula::BaseRegs.
364 bool Formula::isCanonical() const {
366 return Scale != 1 || !BaseRegs.empty();
367 return BaseRegs.size() <= 1;
370 /// \brief Helper method to morph a formula into its canonical representation.
371 /// \see Formula::BaseRegs.
372 /// Every formula having more than one base register, must use the ScaledReg
373 /// field. Otherwise, we would have to do special cases everywhere in LSR
374 /// to treat reg1 + reg2 + ... the same way as reg1 + 1*reg2 + ...
375 /// On the other hand, 1*reg should be canonicalized into reg.
376 void Formula::Canonicalize() {
379 // So far we did not need this case. This is easy to implement but it is
380 // useless to maintain dead code. Beside it could hurt compile time.
381 assert(!BaseRegs.empty() && "1*reg => reg, should not be needed.");
382 // Keep the invariant sum in BaseRegs and one of the variant sum in ScaledReg.
383 ScaledReg = BaseRegs.back();
386 size_t BaseRegsSize = BaseRegs.size();
388 // If ScaledReg is an invariant, try to find a variant expression.
389 while (Try < BaseRegsSize && !isa<SCEVAddRecExpr>(ScaledReg))
390 std::swap(ScaledReg, BaseRegs[Try++]);
393 /// \brief Get rid of the scale in the formula.
394 /// In other words, this method morphes reg1 + 1*reg2 into reg1 + reg2.
395 /// \return true if it was possible to get rid of the scale, false otherwise.
396 /// \note After this operation the formula may not be in the canonical form.
397 bool Formula::Unscale() {
401 BaseRegs.push_back(ScaledReg);
406 /// getNumRegs - Return the total number of register operands used by this
407 /// formula. This does not include register uses implied by non-constant
409 size_t Formula::getNumRegs() const {
410 return !!ScaledReg + BaseRegs.size();
413 /// getType - Return the type of this formula, if it has one, or null
414 /// otherwise. This type is meaningless except for the bit size.
415 Type *Formula::getType() const {
416 return !BaseRegs.empty() ? BaseRegs.front()->getType() :
417 ScaledReg ? ScaledReg->getType() :
418 BaseGV ? BaseGV->getType() :
422 /// DeleteBaseReg - Delete the given base reg from the BaseRegs list.
423 void Formula::DeleteBaseReg(const SCEV *&S) {
424 if (&S != &BaseRegs.back())
425 std::swap(S, BaseRegs.back());
429 /// referencesReg - Test if this formula references the given register.
430 bool Formula::referencesReg(const SCEV *S) const {
431 return S == ScaledReg ||
432 std::find(BaseRegs.begin(), BaseRegs.end(), S) != BaseRegs.end();
435 /// hasRegsUsedByUsesOtherThan - Test whether this formula uses registers
436 /// which are used by uses other than the use with the given index.
437 bool Formula::hasRegsUsedByUsesOtherThan(size_t LUIdx,
438 const RegUseTracker &RegUses) const {
440 if (RegUses.isRegUsedByUsesOtherThan(ScaledReg, LUIdx))
442 for (const SCEV *BaseReg : BaseRegs)
443 if (RegUses.isRegUsedByUsesOtherThan(BaseReg, LUIdx))
448 void Formula::print(raw_ostream &OS) const {
451 if (!First) OS << " + "; else First = false;
452 BaseGV->printAsOperand(OS, /*PrintType=*/false);
454 if (BaseOffset != 0) {
455 if (!First) OS << " + "; else First = false;
458 for (const SCEV *BaseReg : BaseRegs) {
459 if (!First) OS << " + "; else First = false;
460 OS << "reg(" << *BaseReg << ')';
462 if (HasBaseReg && BaseRegs.empty()) {
463 if (!First) OS << " + "; else First = false;
464 OS << "**error: HasBaseReg**";
465 } else if (!HasBaseReg && !BaseRegs.empty()) {
466 if (!First) OS << " + "; else First = false;
467 OS << "**error: !HasBaseReg**";
470 if (!First) OS << " + "; else First = false;
471 OS << Scale << "*reg(";
478 if (UnfoldedOffset != 0) {
479 if (!First) OS << " + ";
480 OS << "imm(" << UnfoldedOffset << ')';
484 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
485 void Formula::dump() const {
486 print(errs()); errs() << '\n';
490 /// isAddRecSExtable - Return true if the given addrec can be sign-extended
491 /// without changing its value.
492 static bool isAddRecSExtable(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
494 IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(AR->getType()) + 1);
495 return isa<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
498 /// isAddSExtable - Return true if the given add can be sign-extended
499 /// without changing its value.
500 static bool isAddSExtable(const SCEVAddExpr *A, ScalarEvolution &SE) {
502 IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(A->getType()) + 1);
503 return isa<SCEVAddExpr>(SE.getSignExtendExpr(A, WideTy));
506 /// isMulSExtable - Return true if the given mul can be sign-extended
507 /// without changing its value.
508 static bool isMulSExtable(const SCEVMulExpr *M, ScalarEvolution &SE) {
510 IntegerType::get(SE.getContext(),
511 SE.getTypeSizeInBits(M->getType()) * M->getNumOperands());
512 return isa<SCEVMulExpr>(SE.getSignExtendExpr(M, WideTy));
515 /// getExactSDiv - Return an expression for LHS /s RHS, if it can be determined
516 /// and if the remainder is known to be zero, or null otherwise. If
517 /// IgnoreSignificantBits is true, expressions like (X * Y) /s Y are simplified
518 /// to Y, ignoring that the multiplication may overflow, which is useful when
519 /// the result will be used in a context where the most significant bits are
521 static const SCEV *getExactSDiv(const SCEV *LHS, const SCEV *RHS,
523 bool IgnoreSignificantBits = false) {
524 // Handle the trivial case, which works for any SCEV type.
526 return SE.getConstant(LHS->getType(), 1);
528 // Handle a few RHS special cases.
529 const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS);
531 const APInt &RA = RC->getValue()->getValue();
532 // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do
534 if (RA.isAllOnesValue())
535 return SE.getMulExpr(LHS, RC);
536 // Handle x /s 1 as x.
541 // Check for a division of a constant by a constant.
542 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(LHS)) {
545 const APInt &LA = C->getValue()->getValue();
546 const APInt &RA = RC->getValue()->getValue();
547 if (LA.srem(RA) != 0)
549 return SE.getConstant(LA.sdiv(RA));
552 // Distribute the sdiv over addrec operands, if the addrec doesn't overflow.
553 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) {
554 if (IgnoreSignificantBits || isAddRecSExtable(AR, SE)) {
555 const SCEV *Step = getExactSDiv(AR->getStepRecurrence(SE), RHS, SE,
556 IgnoreSignificantBits);
557 if (!Step) return nullptr;
558 const SCEV *Start = getExactSDiv(AR->getStart(), RHS, SE,
559 IgnoreSignificantBits);
560 if (!Start) return nullptr;
561 // FlagNW is independent of the start value, step direction, and is
562 // preserved with smaller magnitude steps.
563 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
564 return SE.getAddRecExpr(Start, Step, AR->getLoop(), SCEV::FlagAnyWrap);
569 // Distribute the sdiv over add operands, if the add doesn't overflow.
570 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(LHS)) {
571 if (IgnoreSignificantBits || isAddSExtable(Add, SE)) {
572 SmallVector<const SCEV *, 8> Ops;
573 for (const SCEV *S : Add->operands()) {
574 const SCEV *Op = getExactSDiv(S, RHS, SE, IgnoreSignificantBits);
575 if (!Op) return nullptr;
578 return SE.getAddExpr(Ops);
583 // Check for a multiply operand that we can pull RHS out of.
584 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS)) {
585 if (IgnoreSignificantBits || isMulSExtable(Mul, SE)) {
586 SmallVector<const SCEV *, 4> Ops;
588 for (const SCEV *S : Mul->operands()) {
590 if (const SCEV *Q = getExactSDiv(S, RHS, SE,
591 IgnoreSignificantBits)) {
597 return Found ? SE.getMulExpr(Ops) : nullptr;
602 // Otherwise we don't know.
606 /// ExtractImmediate - If S involves the addition of a constant integer value,
607 /// return that integer value, and mutate S to point to a new SCEV with that
609 static int64_t ExtractImmediate(const SCEV *&S, ScalarEvolution &SE) {
610 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
611 if (C->getValue()->getValue().getMinSignedBits() <= 64) {
612 S = SE.getConstant(C->getType(), 0);
613 return C->getValue()->getSExtValue();
615 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
616 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
617 int64_t Result = ExtractImmediate(NewOps.front(), SE);
619 S = SE.getAddExpr(NewOps);
621 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
622 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
623 int64_t Result = ExtractImmediate(NewOps.front(), SE);
625 S = SE.getAddRecExpr(NewOps, AR->getLoop(),
626 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
633 /// ExtractSymbol - If S involves the addition of a GlobalValue address,
634 /// return that symbol, and mutate S to point to a new SCEV with that
636 static GlobalValue *ExtractSymbol(const SCEV *&S, ScalarEvolution &SE) {
637 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
638 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) {
639 S = SE.getConstant(GV->getType(), 0);
642 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
643 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
644 GlobalValue *Result = ExtractSymbol(NewOps.back(), SE);
646 S = SE.getAddExpr(NewOps);
648 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
649 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
650 GlobalValue *Result = ExtractSymbol(NewOps.front(), SE);
652 S = SE.getAddRecExpr(NewOps, AR->getLoop(),
653 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
660 /// isAddressUse - Returns true if the specified instruction is using the
661 /// specified value as an address.
662 static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
663 bool isAddress = isa<LoadInst>(Inst);
664 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
665 if (SI->getOperand(1) == OperandVal)
667 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
668 // Addressing modes can also be folded into prefetches and a variety
670 switch (II->getIntrinsicID()) {
672 case Intrinsic::prefetch:
673 case Intrinsic::x86_sse_storeu_ps:
674 case Intrinsic::x86_sse2_storeu_pd:
675 case Intrinsic::x86_sse2_storeu_dq:
676 case Intrinsic::x86_sse2_storel_dq:
677 if (II->getArgOperand(0) == OperandVal)
685 /// getAccessType - Return the type of the memory being accessed.
686 static Type *getAccessType(const Instruction *Inst) {
687 Type *AccessTy = Inst->getType();
688 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst))
689 AccessTy = SI->getOperand(0)->getType();
690 else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
691 // Addressing modes can also be folded into prefetches and a variety
693 switch (II->getIntrinsicID()) {
695 case Intrinsic::x86_sse_storeu_ps:
696 case Intrinsic::x86_sse2_storeu_pd:
697 case Intrinsic::x86_sse2_storeu_dq:
698 case Intrinsic::x86_sse2_storel_dq:
699 AccessTy = II->getArgOperand(0)->getType();
704 // All pointers have the same requirements, so canonicalize them to an
705 // arbitrary pointer type to minimize variation.
706 if (PointerType *PTy = dyn_cast<PointerType>(AccessTy))
707 AccessTy = PointerType::get(IntegerType::get(PTy->getContext(), 1),
708 PTy->getAddressSpace());
713 /// isExistingPhi - Return true if this AddRec is already a phi in its loop.
714 static bool isExistingPhi(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
715 for (BasicBlock::iterator I = AR->getLoop()->getHeader()->begin();
716 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
717 if (SE.isSCEVable(PN->getType()) &&
718 (SE.getEffectiveSCEVType(PN->getType()) ==
719 SE.getEffectiveSCEVType(AR->getType())) &&
720 SE.getSCEV(PN) == AR)
726 /// Check if expanding this expression is likely to incur significant cost. This
727 /// is tricky because SCEV doesn't track which expressions are actually computed
728 /// by the current IR.
730 /// We currently allow expansion of IV increments that involve adds,
731 /// multiplication by constants, and AddRecs from existing phis.
733 /// TODO: Allow UDivExpr if we can find an existing IV increment that is an
734 /// obvious multiple of the UDivExpr.
735 static bool isHighCostExpansion(const SCEV *S,
736 SmallPtrSetImpl<const SCEV*> &Processed,
737 ScalarEvolution &SE) {
738 // Zero/One operand expressions
739 switch (S->getSCEVType()) {
744 return isHighCostExpansion(cast<SCEVTruncateExpr>(S)->getOperand(),
747 return isHighCostExpansion(cast<SCEVZeroExtendExpr>(S)->getOperand(),
750 return isHighCostExpansion(cast<SCEVSignExtendExpr>(S)->getOperand(),
754 if (!Processed.insert(S).second)
757 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
758 for (const SCEV *S : Add->operands()) {
759 if (isHighCostExpansion(S, Processed, SE))
765 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
766 if (Mul->getNumOperands() == 2) {
767 // Multiplication by a constant is ok
768 if (isa<SCEVConstant>(Mul->getOperand(0)))
769 return isHighCostExpansion(Mul->getOperand(1), Processed, SE);
771 // If we have the value of one operand, check if an existing
772 // multiplication already generates this expression.
773 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Mul->getOperand(1))) {
774 Value *UVal = U->getValue();
775 for (User *UR : UVal->users()) {
776 // If U is a constant, it may be used by a ConstantExpr.
777 Instruction *UI = dyn_cast<Instruction>(UR);
778 if (UI && UI->getOpcode() == Instruction::Mul &&
779 SE.isSCEVable(UI->getType())) {
780 return SE.getSCEV(UI) == Mul;
787 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
788 if (isExistingPhi(AR, SE))
792 // Fow now, consider any other type of expression (div/mul/min/max) high cost.
796 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
797 /// specified set are trivially dead, delete them and see if this makes any of
798 /// their operands subsequently dead.
800 DeleteTriviallyDeadInstructions(SmallVectorImpl<WeakVH> &DeadInsts) {
801 bool Changed = false;
803 while (!DeadInsts.empty()) {
804 Value *V = DeadInsts.pop_back_val();
805 Instruction *I = dyn_cast_or_null<Instruction>(V);
807 if (!I || !isInstructionTriviallyDead(I))
810 for (Use &O : I->operands())
811 if (Instruction *U = dyn_cast<Instruction>(O)) {
814 DeadInsts.emplace_back(U);
817 I->eraseFromParent();
828 /// \brief Check if the addressing mode defined by \p F is completely
829 /// folded in \p LU at isel time.
830 /// This includes address-mode folding and special icmp tricks.
831 /// This function returns true if \p LU can accommodate what \p F
832 /// defines and up to 1 base + 1 scaled + offset.
833 /// In other words, if \p F has several base registers, this function may
834 /// still return true. Therefore, users still need to account for
835 /// additional base registers and/or unfolded offsets to derive an
836 /// accurate cost model.
837 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
838 const LSRUse &LU, const Formula &F);
839 // Get the cost of the scaling factor used in F for LU.
840 static unsigned getScalingFactorCost(const TargetTransformInfo &TTI,
841 const LSRUse &LU, const Formula &F);
845 /// Cost - This class is used to measure and compare candidate formulae.
847 /// TODO: Some of these could be merged. Also, a lexical ordering
848 /// isn't always optimal.
852 unsigned NumBaseAdds;
859 : NumRegs(0), AddRecCost(0), NumIVMuls(0), NumBaseAdds(0), ImmCost(0),
860 SetupCost(0), ScaleCost(0) {}
862 bool operator<(const Cost &Other) const;
867 // Once any of the metrics loses, they must all remain losers.
869 return ((NumRegs | AddRecCost | NumIVMuls | NumBaseAdds
870 | ImmCost | SetupCost | ScaleCost) != ~0u)
871 || ((NumRegs & AddRecCost & NumIVMuls & NumBaseAdds
872 & ImmCost & SetupCost & ScaleCost) == ~0u);
877 assert(isValid() && "invalid cost");
878 return NumRegs == ~0u;
881 void RateFormula(const TargetTransformInfo &TTI,
883 SmallPtrSetImpl<const SCEV *> &Regs,
884 const DenseSet<const SCEV *> &VisitedRegs,
886 const SmallVectorImpl<int64_t> &Offsets,
887 ScalarEvolution &SE, DominatorTree &DT,
889 SmallPtrSetImpl<const SCEV *> *LoserRegs = nullptr);
891 void print(raw_ostream &OS) const;
895 void RateRegister(const SCEV *Reg,
896 SmallPtrSetImpl<const SCEV *> &Regs,
898 ScalarEvolution &SE, DominatorTree &DT);
899 void RatePrimaryRegister(const SCEV *Reg,
900 SmallPtrSetImpl<const SCEV *> &Regs,
902 ScalarEvolution &SE, DominatorTree &DT,
903 SmallPtrSetImpl<const SCEV *> *LoserRegs);
908 /// RateRegister - Tally up interesting quantities from the given register.
909 void Cost::RateRegister(const SCEV *Reg,
910 SmallPtrSetImpl<const SCEV *> &Regs,
912 ScalarEvolution &SE, DominatorTree &DT) {
913 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Reg)) {
914 // If this is an addrec for another loop, don't second-guess its addrec phi
915 // nodes. LSR isn't currently smart enough to reason about more than one
916 // loop at a time. LSR has already run on inner loops, will not run on outer
917 // loops, and cannot be expected to change sibling loops.
918 if (AR->getLoop() != L) {
919 // If the AddRec exists, consider it's register free and leave it alone.
920 if (isExistingPhi(AR, SE))
923 // Otherwise, do not consider this formula at all.
927 AddRecCost += 1; /// TODO: This should be a function of the stride.
929 // Add the step value register, if it needs one.
930 // TODO: The non-affine case isn't precisely modeled here.
931 if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1))) {
932 if (!Regs.count(AR->getOperand(1))) {
933 RateRegister(AR->getOperand(1), Regs, L, SE, DT);
941 // Rough heuristic; favor registers which don't require extra setup
942 // instructions in the preheader.
943 if (!isa<SCEVUnknown>(Reg) &&
944 !isa<SCEVConstant>(Reg) &&
945 !(isa<SCEVAddRecExpr>(Reg) &&
946 (isa<SCEVUnknown>(cast<SCEVAddRecExpr>(Reg)->getStart()) ||
947 isa<SCEVConstant>(cast<SCEVAddRecExpr>(Reg)->getStart()))))
950 NumIVMuls += isa<SCEVMulExpr>(Reg) &&
951 SE.hasComputableLoopEvolution(Reg, L);
954 /// RatePrimaryRegister - Record this register in the set. If we haven't seen it
955 /// before, rate it. Optional LoserRegs provides a way to declare any formula
956 /// that refers to one of those regs an instant loser.
957 void Cost::RatePrimaryRegister(const SCEV *Reg,
958 SmallPtrSetImpl<const SCEV *> &Regs,
960 ScalarEvolution &SE, DominatorTree &DT,
961 SmallPtrSetImpl<const SCEV *> *LoserRegs) {
962 if (LoserRegs && LoserRegs->count(Reg)) {
966 if (Regs.insert(Reg).second) {
967 RateRegister(Reg, Regs, L, SE, DT);
968 if (LoserRegs && isLoser())
969 LoserRegs->insert(Reg);
973 void Cost::RateFormula(const TargetTransformInfo &TTI,
975 SmallPtrSetImpl<const SCEV *> &Regs,
976 const DenseSet<const SCEV *> &VisitedRegs,
978 const SmallVectorImpl<int64_t> &Offsets,
979 ScalarEvolution &SE, DominatorTree &DT,
981 SmallPtrSetImpl<const SCEV *> *LoserRegs) {
982 assert(F.isCanonical() && "Cost is accurate only for canonical formula");
983 // Tally up the registers.
984 if (const SCEV *ScaledReg = F.ScaledReg) {
985 if (VisitedRegs.count(ScaledReg)) {
989 RatePrimaryRegister(ScaledReg, Regs, L, SE, DT, LoserRegs);
993 for (const SCEV *BaseReg : F.BaseRegs) {
994 if (VisitedRegs.count(BaseReg)) {
998 RatePrimaryRegister(BaseReg, Regs, L, SE, DT, LoserRegs);
1003 // Determine how many (unfolded) adds we'll need inside the loop.
1004 size_t NumBaseParts = F.getNumRegs();
1005 if (NumBaseParts > 1)
1006 // Do not count the base and a possible second register if the target
1007 // allows to fold 2 registers.
1009 NumBaseParts - (1 + (F.Scale && isAMCompletelyFolded(TTI, LU, F)));
1010 NumBaseAdds += (F.UnfoldedOffset != 0);
1012 // Accumulate non-free scaling amounts.
1013 ScaleCost += getScalingFactorCost(TTI, LU, F);
1015 // Tally up the non-zero immediates.
1016 for (int64_t O : Offsets) {
1017 int64_t Offset = (uint64_t)O + F.BaseOffset;
1019 ImmCost += 64; // Handle symbolic values conservatively.
1020 // TODO: This should probably be the pointer size.
1021 else if (Offset != 0)
1022 ImmCost += APInt(64, Offset, true).getMinSignedBits();
1024 assert(isValid() && "invalid cost");
1027 /// Lose - Set this cost to a losing value.
1038 /// operator< - Choose the lower cost.
1039 bool Cost::operator<(const Cost &Other) const {
1040 return std::tie(NumRegs, AddRecCost, NumIVMuls, NumBaseAdds, ScaleCost,
1041 ImmCost, SetupCost) <
1042 std::tie(Other.NumRegs, Other.AddRecCost, Other.NumIVMuls,
1043 Other.NumBaseAdds, Other.ScaleCost, Other.ImmCost,
1047 void Cost::print(raw_ostream &OS) const {
1048 OS << NumRegs << " reg" << (NumRegs == 1 ? "" : "s");
1049 if (AddRecCost != 0)
1050 OS << ", with addrec cost " << AddRecCost;
1052 OS << ", plus " << NumIVMuls << " IV mul" << (NumIVMuls == 1 ? "" : "s");
1053 if (NumBaseAdds != 0)
1054 OS << ", plus " << NumBaseAdds << " base add"
1055 << (NumBaseAdds == 1 ? "" : "s");
1057 OS << ", plus " << ScaleCost << " scale cost";
1059 OS << ", plus " << ImmCost << " imm cost";
1061 OS << ", plus " << SetupCost << " setup cost";
1064 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1065 void Cost::dump() const {
1066 print(errs()); errs() << '\n';
1072 /// LSRFixup - An operand value in an instruction which is to be replaced
1073 /// with some equivalent, possibly strength-reduced, replacement.
1075 /// UserInst - The instruction which will be updated.
1076 Instruction *UserInst;
1078 /// OperandValToReplace - The operand of the instruction which will
1079 /// be replaced. The operand may be used more than once; every instance
1080 /// will be replaced.
1081 Value *OperandValToReplace;
1083 /// PostIncLoops - If this user is to use the post-incremented value of an
1084 /// induction variable, this variable is non-null and holds the loop
1085 /// associated with the induction variable.
1086 PostIncLoopSet PostIncLoops;
1088 /// LUIdx - The index of the LSRUse describing the expression which
1089 /// this fixup needs, minus an offset (below).
1092 /// Offset - A constant offset to be added to the LSRUse expression.
1093 /// This allows multiple fixups to share the same LSRUse with different
1094 /// offsets, for example in an unrolled loop.
1097 bool isUseFullyOutsideLoop(const Loop *L) const;
1101 void print(raw_ostream &OS) const;
1107 LSRFixup::LSRFixup()
1108 : UserInst(nullptr), OperandValToReplace(nullptr), LUIdx(~size_t(0)),
1111 /// isUseFullyOutsideLoop - Test whether this fixup always uses its
1112 /// value outside of the given loop.
1113 bool LSRFixup::isUseFullyOutsideLoop(const Loop *L) const {
1114 // PHI nodes use their value in their incoming blocks.
1115 if (const PHINode *PN = dyn_cast<PHINode>(UserInst)) {
1116 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1117 if (PN->getIncomingValue(i) == OperandValToReplace &&
1118 L->contains(PN->getIncomingBlock(i)))
1123 return !L->contains(UserInst);
1126 void LSRFixup::print(raw_ostream &OS) const {
1128 // Store is common and interesting enough to be worth special-casing.
1129 if (StoreInst *Store = dyn_cast<StoreInst>(UserInst)) {
1131 Store->getOperand(0)->printAsOperand(OS, /*PrintType=*/false);
1132 } else if (UserInst->getType()->isVoidTy())
1133 OS << UserInst->getOpcodeName();
1135 UserInst->printAsOperand(OS, /*PrintType=*/false);
1137 OS << ", OperandValToReplace=";
1138 OperandValToReplace->printAsOperand(OS, /*PrintType=*/false);
1140 for (const Loop *PIL : PostIncLoops) {
1141 OS << ", PostIncLoop=";
1142 PIL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
1145 if (LUIdx != ~size_t(0))
1146 OS << ", LUIdx=" << LUIdx;
1149 OS << ", Offset=" << Offset;
1152 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1153 void LSRFixup::dump() const {
1154 print(errs()); errs() << '\n';
1160 /// UniquifierDenseMapInfo - A DenseMapInfo implementation for holding
1161 /// DenseMaps and DenseSets of sorted SmallVectors of const SCEV*.
1162 struct UniquifierDenseMapInfo {
1163 static SmallVector<const SCEV *, 4> getEmptyKey() {
1164 SmallVector<const SCEV *, 4> V;
1165 V.push_back(reinterpret_cast<const SCEV *>(-1));
1169 static SmallVector<const SCEV *, 4> getTombstoneKey() {
1170 SmallVector<const SCEV *, 4> V;
1171 V.push_back(reinterpret_cast<const SCEV *>(-2));
1175 static unsigned getHashValue(const SmallVector<const SCEV *, 4> &V) {
1176 return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
1179 static bool isEqual(const SmallVector<const SCEV *, 4> &LHS,
1180 const SmallVector<const SCEV *, 4> &RHS) {
1185 /// LSRUse - This class holds the state that LSR keeps for each use in
1186 /// IVUsers, as well as uses invented by LSR itself. It includes information
1187 /// about what kinds of things can be folded into the user, information about
1188 /// the user itself, and information about how the use may be satisfied.
1189 /// TODO: Represent multiple users of the same expression in common?
1191 DenseSet<SmallVector<const SCEV *, 4>, UniquifierDenseMapInfo> Uniquifier;
1194 /// KindType - An enum for a kind of use, indicating what types of
1195 /// scaled and immediate operands it might support.
1197 Basic, ///< A normal use, with no folding.
1198 Special, ///< A special case of basic, allowing -1 scales.
1199 Address, ///< An address use; folding according to TargetLowering
1200 ICmpZero ///< An equality icmp with both operands folded into one.
1201 // TODO: Add a generic icmp too?
1204 typedef PointerIntPair<const SCEV *, 2, KindType> SCEVUseKindPair;
1209 SmallVector<int64_t, 8> Offsets;
1213 /// AllFixupsOutsideLoop - This records whether all of the fixups using this
1214 /// LSRUse are outside of the loop, in which case some special-case heuristics
1216 bool AllFixupsOutsideLoop;
1218 /// RigidFormula is set to true to guarantee that this use will be associated
1219 /// with a single formula--the one that initially matched. Some SCEV
1220 /// expressions cannot be expanded. This allows LSR to consider the registers
1221 /// used by those expressions without the need to expand them later after
1222 /// changing the formula.
1225 /// WidestFixupType - This records the widest use type for any fixup using
1226 /// this LSRUse. FindUseWithSimilarFormula can't consider uses with different
1227 /// max fixup widths to be equivalent, because the narrower one may be relying
1228 /// on the implicit truncation to truncate away bogus bits.
1229 Type *WidestFixupType;
1231 /// Formulae - A list of ways to build a value that can satisfy this user.
1232 /// After the list is populated, one of these is selected heuristically and
1233 /// used to formulate a replacement for OperandValToReplace in UserInst.
1234 SmallVector<Formula, 12> Formulae;
1236 /// Regs - The set of register candidates used by all formulae in this LSRUse.
1237 SmallPtrSet<const SCEV *, 4> Regs;
1239 LSRUse(KindType K, Type *T) : Kind(K), AccessTy(T),
1240 MinOffset(INT64_MAX),
1241 MaxOffset(INT64_MIN),
1242 AllFixupsOutsideLoop(true),
1243 RigidFormula(false),
1244 WidestFixupType(nullptr) {}
1246 bool HasFormulaWithSameRegs(const Formula &F) const;
1247 bool InsertFormula(const Formula &F);
1248 void DeleteFormula(Formula &F);
1249 void RecomputeRegs(size_t LUIdx, RegUseTracker &Reguses);
1251 void print(raw_ostream &OS) const;
1257 /// HasFormula - Test whether this use as a formula which has the same
1258 /// registers as the given formula.
1259 bool LSRUse::HasFormulaWithSameRegs(const Formula &F) const {
1260 SmallVector<const SCEV *, 4> Key = F.BaseRegs;
1261 if (F.ScaledReg) Key.push_back(F.ScaledReg);
1262 // Unstable sort by host order ok, because this is only used for uniquifying.
1263 std::sort(Key.begin(), Key.end());
1264 return Uniquifier.count(Key);
1267 /// InsertFormula - If the given formula has not yet been inserted, add it to
1268 /// the list, and return true. Return false otherwise.
1269 /// The formula must be in canonical form.
1270 bool LSRUse::InsertFormula(const Formula &F) {
1271 assert(F.isCanonical() && "Invalid canonical representation");
1273 if (!Formulae.empty() && RigidFormula)
1276 SmallVector<const SCEV *, 4> Key = F.BaseRegs;
1277 if (F.ScaledReg) Key.push_back(F.ScaledReg);
1278 // Unstable sort by host order ok, because this is only used for uniquifying.
1279 std::sort(Key.begin(), Key.end());
1281 if (!Uniquifier.insert(Key).second)
1284 // Using a register to hold the value of 0 is not profitable.
1285 assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&
1286 "Zero allocated in a scaled register!");
1288 for (const SCEV *BaseReg : F.BaseRegs)
1289 assert(!BaseReg->isZero() && "Zero allocated in a base register!");
1292 // Add the formula to the list.
1293 Formulae.push_back(F);
1295 // Record registers now being used by this use.
1296 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
1298 Regs.insert(F.ScaledReg);
1303 /// DeleteFormula - Remove the given formula from this use's list.
1304 void LSRUse::DeleteFormula(Formula &F) {
1305 if (&F != &Formulae.back())
1306 std::swap(F, Formulae.back());
1307 Formulae.pop_back();
1310 /// RecomputeRegs - Recompute the Regs field, and update RegUses.
1311 void LSRUse::RecomputeRegs(size_t LUIdx, RegUseTracker &RegUses) {
1312 // Now that we've filtered out some formulae, recompute the Regs set.
1313 SmallPtrSet<const SCEV *, 4> OldRegs = std::move(Regs);
1315 for (const Formula &F : Formulae) {
1316 if (F.ScaledReg) Regs.insert(F.ScaledReg);
1317 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
1320 // Update the RegTracker.
1321 for (const SCEV *S : OldRegs)
1323 RegUses.DropRegister(S, LUIdx);
1326 void LSRUse::print(raw_ostream &OS) const {
1327 OS << "LSR Use: Kind=";
1329 case Basic: OS << "Basic"; break;
1330 case Special: OS << "Special"; break;
1331 case ICmpZero: OS << "ICmpZero"; break;
1333 OS << "Address of ";
1334 if (AccessTy->isPointerTy())
1335 OS << "pointer"; // the full pointer type could be really verbose
1340 OS << ", Offsets={";
1341 bool NeedComma = false;
1342 for (int64_t O : Offsets) {
1343 if (NeedComma) OS << ',';
1349 if (AllFixupsOutsideLoop)
1350 OS << ", all-fixups-outside-loop";
1352 if (WidestFixupType)
1353 OS << ", widest fixup type: " << *WidestFixupType;
1356 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1357 void LSRUse::dump() const {
1358 print(errs()); errs() << '\n';
1362 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1363 LSRUse::KindType Kind, Type *AccessTy,
1364 GlobalValue *BaseGV, int64_t BaseOffset,
1365 bool HasBaseReg, int64_t Scale) {
1367 case LSRUse::Address:
1368 return TTI.isLegalAddressingMode(AccessTy, BaseGV, BaseOffset, HasBaseReg, Scale);
1370 case LSRUse::ICmpZero:
1371 // There's not even a target hook for querying whether it would be legal to
1372 // fold a GV into an ICmp.
1376 // ICmp only has two operands; don't allow more than two non-trivial parts.
1377 if (Scale != 0 && HasBaseReg && BaseOffset != 0)
1380 // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by
1381 // putting the scaled register in the other operand of the icmp.
1382 if (Scale != 0 && Scale != -1)
1385 // If we have low-level target information, ask the target if it can fold an
1386 // integer immediate on an icmp.
1387 if (BaseOffset != 0) {
1389 // ICmpZero BaseReg + BaseOffset => ICmp BaseReg, -BaseOffset
1390 // ICmpZero -1*ScaleReg + BaseOffset => ICmp ScaleReg, BaseOffset
1391 // Offs is the ICmp immediate.
1393 // The cast does the right thing with INT64_MIN.
1394 BaseOffset = -(uint64_t)BaseOffset;
1395 return TTI.isLegalICmpImmediate(BaseOffset);
1398 // ICmpZero BaseReg + -1*ScaleReg => ICmp BaseReg, ScaleReg
1402 // Only handle single-register values.
1403 return !BaseGV && Scale == 0 && BaseOffset == 0;
1405 case LSRUse::Special:
1406 // Special case Basic to handle -1 scales.
1407 return !BaseGV && (Scale == 0 || Scale == -1) && BaseOffset == 0;
1410 llvm_unreachable("Invalid LSRUse Kind!");
1413 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1414 int64_t MinOffset, int64_t MaxOffset,
1415 LSRUse::KindType Kind, Type *AccessTy,
1416 GlobalValue *BaseGV, int64_t BaseOffset,
1417 bool HasBaseReg, int64_t Scale) {
1418 // Check for overflow.
1419 if (((int64_t)((uint64_t)BaseOffset + MinOffset) > BaseOffset) !=
1422 MinOffset = (uint64_t)BaseOffset + MinOffset;
1423 if (((int64_t)((uint64_t)BaseOffset + MaxOffset) > BaseOffset) !=
1426 MaxOffset = (uint64_t)BaseOffset + MaxOffset;
1428 return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MinOffset,
1429 HasBaseReg, Scale) &&
1430 isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MaxOffset,
1434 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1435 int64_t MinOffset, int64_t MaxOffset,
1436 LSRUse::KindType Kind, Type *AccessTy,
1438 // For the purpose of isAMCompletelyFolded either having a canonical formula
1439 // or a scale not equal to zero is correct.
1440 // Problems may arise from non canonical formulae having a scale == 0.
1441 // Strictly speaking it would best to just rely on canonical formulae.
1442 // However, when we generate the scaled formulae, we first check that the
1443 // scaling factor is profitable before computing the actual ScaledReg for
1444 // compile time sake.
1445 assert((F.isCanonical() || F.Scale != 0));
1446 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy,
1447 F.BaseGV, F.BaseOffset, F.HasBaseReg, F.Scale);
1450 /// isLegalUse - Test whether we know how to expand the current formula.
1451 static bool isLegalUse(const TargetTransformInfo &TTI, int64_t MinOffset,
1452 int64_t MaxOffset, LSRUse::KindType Kind, Type *AccessTy,
1453 GlobalValue *BaseGV, int64_t BaseOffset, bool HasBaseReg,
1455 // We know how to expand completely foldable formulae.
1456 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV,
1457 BaseOffset, HasBaseReg, Scale) ||
1458 // Or formulae that use a base register produced by a sum of base
1461 isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy,
1462 BaseGV, BaseOffset, true, 0));
1465 static bool isLegalUse(const TargetTransformInfo &TTI, int64_t MinOffset,
1466 int64_t MaxOffset, LSRUse::KindType Kind, Type *AccessTy,
1468 return isLegalUse(TTI, MinOffset, MaxOffset, Kind, AccessTy, F.BaseGV,
1469 F.BaseOffset, F.HasBaseReg, F.Scale);
1472 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1473 const LSRUse &LU, const Formula &F) {
1474 return isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind,
1475 LU.AccessTy, F.BaseGV, F.BaseOffset, F.HasBaseReg,
1479 static unsigned getScalingFactorCost(const TargetTransformInfo &TTI,
1480 const LSRUse &LU, const Formula &F) {
1484 // If the use is not completely folded in that instruction, we will have to
1485 // pay an extra cost only for scale != 1.
1486 if (!isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind,
1488 return F.Scale != 1;
1491 case LSRUse::Address: {
1492 // Check the scaling factor cost with both the min and max offsets.
1493 int ScaleCostMinOffset =
1494 TTI.getScalingFactorCost(LU.AccessTy, F.BaseGV,
1495 F.BaseOffset + LU.MinOffset,
1496 F.HasBaseReg, F.Scale);
1497 int ScaleCostMaxOffset =
1498 TTI.getScalingFactorCost(LU.AccessTy, F.BaseGV,
1499 F.BaseOffset + LU.MaxOffset,
1500 F.HasBaseReg, F.Scale);
1502 assert(ScaleCostMinOffset >= 0 && ScaleCostMaxOffset >= 0 &&
1503 "Legal addressing mode has an illegal cost!");
1504 return std::max(ScaleCostMinOffset, ScaleCostMaxOffset);
1506 case LSRUse::ICmpZero:
1508 case LSRUse::Special:
1509 // The use is completely folded, i.e., everything is folded into the
1514 llvm_unreachable("Invalid LSRUse Kind!");
1517 static bool isAlwaysFoldable(const TargetTransformInfo &TTI,
1518 LSRUse::KindType Kind, Type *AccessTy,
1519 GlobalValue *BaseGV, int64_t BaseOffset,
1521 // Fast-path: zero is always foldable.
1522 if (BaseOffset == 0 && !BaseGV) return true;
1524 // Conservatively, create an address with an immediate and a
1525 // base and a scale.
1526 int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1528 // Canonicalize a scale of 1 to a base register if the formula doesn't
1529 // already have a base register.
1530 if (!HasBaseReg && Scale == 1) {
1535 return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, BaseOffset,
1539 static bool isAlwaysFoldable(const TargetTransformInfo &TTI,
1540 ScalarEvolution &SE, int64_t MinOffset,
1541 int64_t MaxOffset, LSRUse::KindType Kind,
1542 Type *AccessTy, const SCEV *S, bool HasBaseReg) {
1543 // Fast-path: zero is always foldable.
1544 if (S->isZero()) return true;
1546 // Conservatively, create an address with an immediate and a
1547 // base and a scale.
1548 int64_t BaseOffset = ExtractImmediate(S, SE);
1549 GlobalValue *BaseGV = ExtractSymbol(S, SE);
1551 // If there's anything else involved, it's not foldable.
1552 if (!S->isZero()) return false;
1554 // Fast-path: zero is always foldable.
1555 if (BaseOffset == 0 && !BaseGV) return true;
1557 // Conservatively, create an address with an immediate and a
1558 // base and a scale.
1559 int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1561 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV,
1562 BaseOffset, HasBaseReg, Scale);
1567 /// IVInc - An individual increment in a Chain of IV increments.
1568 /// Relate an IV user to an expression that computes the IV it uses from the IV
1569 /// used by the previous link in the Chain.
1571 /// For the head of a chain, IncExpr holds the absolute SCEV expression for the
1572 /// original IVOperand. The head of the chain's IVOperand is only valid during
1573 /// chain collection, before LSR replaces IV users. During chain generation,
1574 /// IncExpr can be used to find the new IVOperand that computes the same
1577 Instruction *UserInst;
1579 const SCEV *IncExpr;
1581 IVInc(Instruction *U, Value *O, const SCEV *E):
1582 UserInst(U), IVOperand(O), IncExpr(E) {}
1585 // IVChain - The list of IV increments in program order.
1586 // We typically add the head of a chain without finding subsequent links.
1588 SmallVector<IVInc,1> Incs;
1589 const SCEV *ExprBase;
1591 IVChain() : ExprBase(nullptr) {}
1593 IVChain(const IVInc &Head, const SCEV *Base)
1594 : Incs(1, Head), ExprBase(Base) {}
1596 typedef SmallVectorImpl<IVInc>::const_iterator const_iterator;
1598 // begin - return the first increment in the chain.
1599 const_iterator begin() const {
1600 assert(!Incs.empty());
1601 return std::next(Incs.begin());
1603 const_iterator end() const {
1607 // hasIncs - Returns true if this chain contains any increments.
1608 bool hasIncs() const { return Incs.size() >= 2; }
1610 // add - Add an IVInc to the end of this chain.
1611 void add(const IVInc &X) { Incs.push_back(X); }
1613 // tailUserInst - Returns the last UserInst in the chain.
1614 Instruction *tailUserInst() const { return Incs.back().UserInst; }
1616 // isProfitableIncrement - Returns true if IncExpr can be profitably added to
1618 bool isProfitableIncrement(const SCEV *OperExpr,
1619 const SCEV *IncExpr,
1623 /// ChainUsers - Helper for CollectChains to track multiple IV increment uses.
1624 /// Distinguish between FarUsers that definitely cross IV increments and
1625 /// NearUsers that may be used between IV increments.
1627 SmallPtrSet<Instruction*, 4> FarUsers;
1628 SmallPtrSet<Instruction*, 4> NearUsers;
1631 /// LSRInstance - This class holds state for the main loop strength reduction
1635 ScalarEvolution &SE;
1638 const TargetTransformInfo &TTI;
1642 /// IVIncInsertPos - This is the insert position that the current loop's
1643 /// induction variable increment should be placed. In simple loops, this is
1644 /// the latch block's terminator. But in more complicated cases, this is a
1645 /// position which will dominate all the in-loop post-increment users.
1646 Instruction *IVIncInsertPos;
1648 /// Factors - Interesting factors between use strides.
1649 SmallSetVector<int64_t, 8> Factors;
1651 /// Types - Interesting use types, to facilitate truncation reuse.
1652 SmallSetVector<Type *, 4> Types;
1654 /// Fixups - The list of operands which are to be replaced.
1655 SmallVector<LSRFixup, 16> Fixups;
1657 /// Uses - The list of interesting uses.
1658 SmallVector<LSRUse, 16> Uses;
1660 /// RegUses - Track which uses use which register candidates.
1661 RegUseTracker RegUses;
1663 // Limit the number of chains to avoid quadratic behavior. We don't expect to
1664 // have more than a few IV increment chains in a loop. Missing a Chain falls
1665 // back to normal LSR behavior for those uses.
1666 static const unsigned MaxChains = 8;
1668 /// IVChainVec - IV users can form a chain of IV increments.
1669 SmallVector<IVChain, MaxChains> IVChainVec;
1671 /// IVIncSet - IV users that belong to profitable IVChains.
1672 SmallPtrSet<Use*, MaxChains> IVIncSet;
1674 void OptimizeShadowIV();
1675 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse);
1676 ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse);
1677 void OptimizeLoopTermCond();
1679 void ChainInstruction(Instruction *UserInst, Instruction *IVOper,
1680 SmallVectorImpl<ChainUsers> &ChainUsersVec);
1681 void FinalizeChain(IVChain &Chain);
1682 void CollectChains();
1683 void GenerateIVChain(const IVChain &Chain, SCEVExpander &Rewriter,
1684 SmallVectorImpl<WeakVH> &DeadInsts);
1686 void CollectInterestingTypesAndFactors();
1687 void CollectFixupsAndInitialFormulae();
1689 LSRFixup &getNewFixup() {
1690 Fixups.push_back(LSRFixup());
1691 return Fixups.back();
1694 // Support for sharing of LSRUses between LSRFixups.
1695 typedef DenseMap<LSRUse::SCEVUseKindPair, size_t> UseMapTy;
1698 bool reconcileNewOffset(LSRUse &LU, int64_t NewOffset, bool HasBaseReg,
1699 LSRUse::KindType Kind, Type *AccessTy);
1701 std::pair<size_t, int64_t> getUse(const SCEV *&Expr,
1702 LSRUse::KindType Kind,
1705 void DeleteUse(LSRUse &LU, size_t LUIdx);
1707 LSRUse *FindUseWithSimilarFormula(const Formula &F, const LSRUse &OrigLU);
1709 void InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
1710 void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
1711 void CountRegisters(const Formula &F, size_t LUIdx);
1712 bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F);
1714 void CollectLoopInvariantFixupsAndFormulae();
1716 void GenerateReassociations(LSRUse &LU, unsigned LUIdx, Formula Base,
1717 unsigned Depth = 0);
1719 void GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx,
1720 const Formula &Base, unsigned Depth,
1721 size_t Idx, bool IsScaledReg = false);
1722 void GenerateCombinations(LSRUse &LU, unsigned LUIdx, Formula Base);
1723 void GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx,
1724 const Formula &Base, size_t Idx,
1725 bool IsScaledReg = false);
1726 void GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1727 void GenerateConstantOffsetsImpl(LSRUse &LU, unsigned LUIdx,
1728 const Formula &Base,
1729 const SmallVectorImpl<int64_t> &Worklist,
1730 size_t Idx, bool IsScaledReg = false);
1731 void GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1732 void GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1733 void GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1734 void GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base);
1735 void GenerateCrossUseConstantOffsets();
1736 void GenerateAllReuseFormulae();
1738 void FilterOutUndesirableDedicatedRegisters();
1740 size_t EstimateSearchSpaceComplexity() const;
1741 void NarrowSearchSpaceByDetectingSupersets();
1742 void NarrowSearchSpaceByCollapsingUnrolledCode();
1743 void NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
1744 void NarrowSearchSpaceByPickingWinnerRegs();
1745 void NarrowSearchSpaceUsingHeuristics();
1747 void SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
1749 SmallVectorImpl<const Formula *> &Workspace,
1750 const Cost &CurCost,
1751 const SmallPtrSet<const SCEV *, 16> &CurRegs,
1752 DenseSet<const SCEV *> &VisitedRegs) const;
1753 void Solve(SmallVectorImpl<const Formula *> &Solution) const;
1755 BasicBlock::iterator
1756 HoistInsertPosition(BasicBlock::iterator IP,
1757 const SmallVectorImpl<Instruction *> &Inputs) const;
1758 BasicBlock::iterator
1759 AdjustInsertPositionForExpand(BasicBlock::iterator IP,
1762 SCEVExpander &Rewriter) const;
1764 Value *Expand(const LSRFixup &LF,
1766 BasicBlock::iterator IP,
1767 SCEVExpander &Rewriter,
1768 SmallVectorImpl<WeakVH> &DeadInsts) const;
1769 void RewriteForPHI(PHINode *PN, const LSRFixup &LF,
1771 SCEVExpander &Rewriter,
1772 SmallVectorImpl<WeakVH> &DeadInsts,
1774 void Rewrite(const LSRFixup &LF,
1776 SCEVExpander &Rewriter,
1777 SmallVectorImpl<WeakVH> &DeadInsts,
1779 void ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
1783 LSRInstance(Loop *L, Pass *P);
1785 bool getChanged() const { return Changed; }
1787 void print_factors_and_types(raw_ostream &OS) const;
1788 void print_fixups(raw_ostream &OS) const;
1789 void print_uses(raw_ostream &OS) const;
1790 void print(raw_ostream &OS) const;
1796 /// OptimizeShadowIV - If IV is used in a int-to-float cast
1797 /// inside the loop then try to eliminate the cast operation.
1798 void LSRInstance::OptimizeShadowIV() {
1799 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
1800 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1803 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end();
1804 UI != E; /* empty */) {
1805 IVUsers::const_iterator CandidateUI = UI;
1807 Instruction *ShadowUse = CandidateUI->getUser();
1808 Type *DestTy = nullptr;
1809 bool IsSigned = false;
1811 /* If shadow use is a int->float cast then insert a second IV
1812 to eliminate this cast.
1814 for (unsigned i = 0; i < n; ++i)
1820 for (unsigned i = 0; i < n; ++i, ++d)
1823 if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser())) {
1825 DestTy = UCast->getDestTy();
1827 else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser())) {
1829 DestTy = SCast->getDestTy();
1831 if (!DestTy) continue;
1833 // If target does not support DestTy natively then do not apply
1834 // this transformation.
1835 if (!TTI.isTypeLegal(DestTy)) continue;
1837 PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
1839 if (PH->getNumIncomingValues() != 2) continue;
1841 Type *SrcTy = PH->getType();
1842 int Mantissa = DestTy->getFPMantissaWidth();
1843 if (Mantissa == -1) continue;
1844 if ((int)SE.getTypeSizeInBits(SrcTy) > Mantissa)
1847 unsigned Entry, Latch;
1848 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
1856 ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
1857 if (!Init) continue;
1858 Constant *NewInit = ConstantFP::get(DestTy, IsSigned ?
1859 (double)Init->getSExtValue() :
1860 (double)Init->getZExtValue());
1862 BinaryOperator *Incr =
1863 dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
1864 if (!Incr) continue;
1865 if (Incr->getOpcode() != Instruction::Add
1866 && Incr->getOpcode() != Instruction::Sub)
1869 /* Initialize new IV, double d = 0.0 in above example. */
1870 ConstantInt *C = nullptr;
1871 if (Incr->getOperand(0) == PH)
1872 C = dyn_cast<ConstantInt>(Incr->getOperand(1));
1873 else if (Incr->getOperand(1) == PH)
1874 C = dyn_cast<ConstantInt>(Incr->getOperand(0));
1880 // Ignore negative constants, as the code below doesn't handle them
1881 // correctly. TODO: Remove this restriction.
1882 if (!C->getValue().isStrictlyPositive()) continue;
1884 /* Add new PHINode. */
1885 PHINode *NewPH = PHINode::Create(DestTy, 2, "IV.S.", PH);
1887 /* create new increment. '++d' in above example. */
1888 Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue());
1889 BinaryOperator *NewIncr =
1890 BinaryOperator::Create(Incr->getOpcode() == Instruction::Add ?
1891 Instruction::FAdd : Instruction::FSub,
1892 NewPH, CFP, "IV.S.next.", Incr);
1894 NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
1895 NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
1897 /* Remove cast operation */
1898 ShadowUse->replaceAllUsesWith(NewPH);
1899 ShadowUse->eraseFromParent();
1905 /// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
1906 /// set the IV user and stride information and return true, otherwise return
1908 bool LSRInstance::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse) {
1909 for (IVStrideUse &U : IU)
1910 if (U.getUser() == Cond) {
1911 // NOTE: we could handle setcc instructions with multiple uses here, but
1912 // InstCombine does it as well for simple uses, it's not clear that it
1913 // occurs enough in real life to handle.
1920 /// OptimizeMax - Rewrite the loop's terminating condition if it uses
1921 /// a max computation.
1923 /// This is a narrow solution to a specific, but acute, problem. For loops
1929 /// } while (++i < n);
1931 /// the trip count isn't just 'n', because 'n' might not be positive. And
1932 /// unfortunately this can come up even for loops where the user didn't use
1933 /// a C do-while loop. For example, seemingly well-behaved top-test loops
1934 /// will commonly be lowered like this:
1940 /// } while (++i < n);
1943 /// and then it's possible for subsequent optimization to obscure the if
1944 /// test in such a way that indvars can't find it.
1946 /// When indvars can't find the if test in loops like this, it creates a
1947 /// max expression, which allows it to give the loop a canonical
1948 /// induction variable:
1951 /// max = n < 1 ? 1 : n;
1954 /// } while (++i != max);
1956 /// Canonical induction variables are necessary because the loop passes
1957 /// are designed around them. The most obvious example of this is the
1958 /// LoopInfo analysis, which doesn't remember trip count values. It
1959 /// expects to be able to rediscover the trip count each time it is
1960 /// needed, and it does this using a simple analysis that only succeeds if
1961 /// the loop has a canonical induction variable.
1963 /// However, when it comes time to generate code, the maximum operation
1964 /// can be quite costly, especially if it's inside of an outer loop.
1966 /// This function solves this problem by detecting this type of loop and
1967 /// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
1968 /// the instructions for the maximum computation.
1970 ICmpInst *LSRInstance::OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse) {
1971 // Check that the loop matches the pattern we're looking for.
1972 if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
1973 Cond->getPredicate() != CmpInst::ICMP_NE)
1976 SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
1977 if (!Sel || !Sel->hasOneUse()) return Cond;
1979 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
1980 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1982 const SCEV *One = SE.getConstant(BackedgeTakenCount->getType(), 1);
1984 // Add one to the backedge-taken count to get the trip count.
1985 const SCEV *IterationCount = SE.getAddExpr(One, BackedgeTakenCount);
1986 if (IterationCount != SE.getSCEV(Sel)) return Cond;
1988 // Check for a max calculation that matches the pattern. There's no check
1989 // for ICMP_ULE here because the comparison would be with zero, which
1990 // isn't interesting.
1991 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1992 const SCEVNAryExpr *Max = nullptr;
1993 if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(BackedgeTakenCount)) {
1994 Pred = ICmpInst::ICMP_SLE;
1996 } else if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(IterationCount)) {
1997 Pred = ICmpInst::ICMP_SLT;
1999 } else if (const SCEVUMaxExpr *U = dyn_cast<SCEVUMaxExpr>(IterationCount)) {
2000 Pred = ICmpInst::ICMP_ULT;
2007 // To handle a max with more than two operands, this optimization would
2008 // require additional checking and setup.
2009 if (Max->getNumOperands() != 2)
2012 const SCEV *MaxLHS = Max->getOperand(0);
2013 const SCEV *MaxRHS = Max->getOperand(1);
2015 // ScalarEvolution canonicalizes constants to the left. For < and >, look
2016 // for a comparison with 1. For <= and >=, a comparison with zero.
2018 (ICmpInst::isTrueWhenEqual(Pred) ? !MaxLHS->isZero() : (MaxLHS != One)))
2021 // Check the relevant induction variable for conformance to
2023 const SCEV *IV = SE.getSCEV(Cond->getOperand(0));
2024 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
2025 if (!AR || !AR->isAffine() ||
2026 AR->getStart() != One ||
2027 AR->getStepRecurrence(SE) != One)
2030 assert(AR->getLoop() == L &&
2031 "Loop condition operand is an addrec in a different loop!");
2033 // Check the right operand of the select, and remember it, as it will
2034 // be used in the new comparison instruction.
2035 Value *NewRHS = nullptr;
2036 if (ICmpInst::isTrueWhenEqual(Pred)) {
2037 // Look for n+1, and grab n.
2038 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(1)))
2039 if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1)))
2040 if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS)
2041 NewRHS = BO->getOperand(0);
2042 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(2)))
2043 if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1)))
2044 if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS)
2045 NewRHS = BO->getOperand(0);
2048 } else if (SE.getSCEV(Sel->getOperand(1)) == MaxRHS)
2049 NewRHS = Sel->getOperand(1);
2050 else if (SE.getSCEV(Sel->getOperand(2)) == MaxRHS)
2051 NewRHS = Sel->getOperand(2);
2052 else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(MaxRHS))
2053 NewRHS = SU->getValue();
2055 // Max doesn't match expected pattern.
2058 // Determine the new comparison opcode. It may be signed or unsigned,
2059 // and the original comparison may be either equality or inequality.
2060 if (Cond->getPredicate() == CmpInst::ICMP_EQ)
2061 Pred = CmpInst::getInversePredicate(Pred);
2063 // Ok, everything looks ok to change the condition into an SLT or SGE and
2064 // delete the max calculation.
2066 new ICmpInst(Cond, Pred, Cond->getOperand(0), NewRHS, "scmp");
2068 // Delete the max calculation instructions.
2069 Cond->replaceAllUsesWith(NewCond);
2070 CondUse->setUser(NewCond);
2071 Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
2072 Cond->eraseFromParent();
2073 Sel->eraseFromParent();
2074 if (Cmp->use_empty())
2075 Cmp->eraseFromParent();
2079 /// OptimizeLoopTermCond - Change loop terminating condition to use the
2080 /// postinc iv when possible.
2082 LSRInstance::OptimizeLoopTermCond() {
2083 SmallPtrSet<Instruction *, 4> PostIncs;
2085 BasicBlock *LatchBlock = L->getLoopLatch();
2086 SmallVector<BasicBlock*, 8> ExitingBlocks;
2087 L->getExitingBlocks(ExitingBlocks);
2089 for (BasicBlock *ExitingBlock : ExitingBlocks) {
2091 // Get the terminating condition for the loop if possible. If we
2092 // can, we want to change it to use a post-incremented version of its
2093 // induction variable, to allow coalescing the live ranges for the IV into
2094 // one register value.
2096 BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2099 // FIXME: Overly conservative, termination condition could be an 'or' etc..
2100 if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
2103 // Search IVUsesByStride to find Cond's IVUse if there is one.
2104 IVStrideUse *CondUse = nullptr;
2105 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
2106 if (!FindIVUserForCond(Cond, CondUse))
2109 // If the trip count is computed in terms of a max (due to ScalarEvolution
2110 // being unable to find a sufficient guard, for example), change the loop
2111 // comparison to use SLT or ULT instead of NE.
2112 // One consequence of doing this now is that it disrupts the count-down
2113 // optimization. That's not always a bad thing though, because in such
2114 // cases it may still be worthwhile to avoid a max.
2115 Cond = OptimizeMax(Cond, CondUse);
2117 // If this exiting block dominates the latch block, it may also use
2118 // the post-inc value if it won't be shared with other uses.
2119 // Check for dominance.
2120 if (!DT.dominates(ExitingBlock, LatchBlock))
2123 // Conservatively avoid trying to use the post-inc value in non-latch
2124 // exits if there may be pre-inc users in intervening blocks.
2125 if (LatchBlock != ExitingBlock)
2126 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
2127 // Test if the use is reachable from the exiting block. This dominator
2128 // query is a conservative approximation of reachability.
2129 if (&*UI != CondUse &&
2130 !DT.properlyDominates(UI->getUser()->getParent(), ExitingBlock)) {
2131 // Conservatively assume there may be reuse if the quotient of their
2132 // strides could be a legal scale.
2133 const SCEV *A = IU.getStride(*CondUse, L);
2134 const SCEV *B = IU.getStride(*UI, L);
2135 if (!A || !B) continue;
2136 if (SE.getTypeSizeInBits(A->getType()) !=
2137 SE.getTypeSizeInBits(B->getType())) {
2138 if (SE.getTypeSizeInBits(A->getType()) >
2139 SE.getTypeSizeInBits(B->getType()))
2140 B = SE.getSignExtendExpr(B, A->getType());
2142 A = SE.getSignExtendExpr(A, B->getType());
2144 if (const SCEVConstant *D =
2145 dyn_cast_or_null<SCEVConstant>(getExactSDiv(B, A, SE))) {
2146 const ConstantInt *C = D->getValue();
2147 // Stride of one or negative one can have reuse with non-addresses.
2148 if (C->isOne() || C->isAllOnesValue())
2149 goto decline_post_inc;
2150 // Avoid weird situations.
2151 if (C->getValue().getMinSignedBits() >= 64 ||
2152 C->getValue().isMinSignedValue())
2153 goto decline_post_inc;
2154 // Check for possible scaled-address reuse.
2155 Type *AccessTy = getAccessType(UI->getUser());
2156 int64_t Scale = C->getSExtValue();
2157 if (TTI.isLegalAddressingMode(AccessTy, /*BaseGV=*/ nullptr,
2159 /*HasBaseReg=*/ false, Scale))
2160 goto decline_post_inc;
2162 if (TTI.isLegalAddressingMode(AccessTy, /*BaseGV=*/ nullptr,
2164 /*HasBaseReg=*/ false, Scale))
2165 goto decline_post_inc;
2169 DEBUG(dbgs() << " Change loop exiting icmp to use postinc iv: "
2172 // It's possible for the setcc instruction to be anywhere in the loop, and
2173 // possible for it to have multiple users. If it is not immediately before
2174 // the exiting block branch, move it.
2175 if (&*++BasicBlock::iterator(Cond) != TermBr) {
2176 if (Cond->hasOneUse()) {
2177 Cond->moveBefore(TermBr);
2179 // Clone the terminating condition and insert into the loopend.
2180 ICmpInst *OldCond = Cond;
2181 Cond = cast<ICmpInst>(Cond->clone());
2182 Cond->setName(L->getHeader()->getName() + ".termcond");
2183 ExitingBlock->getInstList().insert(TermBr, Cond);
2185 // Clone the IVUse, as the old use still exists!
2186 CondUse = &IU.AddUser(Cond, CondUse->getOperandValToReplace());
2187 TermBr->replaceUsesOfWith(OldCond, Cond);
2191 // If we get to here, we know that we can transform the setcc instruction to
2192 // use the post-incremented version of the IV, allowing us to coalesce the
2193 // live ranges for the IV correctly.
2194 CondUse->transformToPostInc(L);
2197 PostIncs.insert(Cond);
2201 // Determine an insertion point for the loop induction variable increment. It
2202 // must dominate all the post-inc comparisons we just set up, and it must
2203 // dominate the loop latch edge.
2204 IVIncInsertPos = L->getLoopLatch()->getTerminator();
2205 for (Instruction *Inst : PostIncs) {
2207 DT.findNearestCommonDominator(IVIncInsertPos->getParent(),
2209 if (BB == Inst->getParent())
2210 IVIncInsertPos = Inst;
2211 else if (BB != IVIncInsertPos->getParent())
2212 IVIncInsertPos = BB->getTerminator();
2216 /// reconcileNewOffset - Determine if the given use can accommodate a fixup
2217 /// at the given offset and other details. If so, update the use and
2220 LSRInstance::reconcileNewOffset(LSRUse &LU, int64_t NewOffset, bool HasBaseReg,
2221 LSRUse::KindType Kind, Type *AccessTy) {
2222 int64_t NewMinOffset = LU.MinOffset;
2223 int64_t NewMaxOffset = LU.MaxOffset;
2224 Type *NewAccessTy = AccessTy;
2226 // Check for a mismatched kind. It's tempting to collapse mismatched kinds to
2227 // something conservative, however this can pessimize in the case that one of
2228 // the uses will have all its uses outside the loop, for example.
2229 if (LU.Kind != Kind)
2232 // Check for a mismatched access type, and fall back conservatively as needed.
2233 // TODO: Be less conservative when the type is similar and can use the same
2234 // addressing modes.
2235 if (Kind == LSRUse::Address && AccessTy != LU.AccessTy)
2236 NewAccessTy = Type::getVoidTy(AccessTy->getContext());
2238 // Conservatively assume HasBaseReg is true for now.
2239 if (NewOffset < LU.MinOffset) {
2240 if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr,
2241 LU.MaxOffset - NewOffset, HasBaseReg))
2243 NewMinOffset = NewOffset;
2244 } else if (NewOffset > LU.MaxOffset) {
2245 if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr,
2246 NewOffset - LU.MinOffset, HasBaseReg))
2248 NewMaxOffset = NewOffset;
2252 LU.MinOffset = NewMinOffset;
2253 LU.MaxOffset = NewMaxOffset;
2254 LU.AccessTy = NewAccessTy;
2255 if (NewOffset != LU.Offsets.back())
2256 LU.Offsets.push_back(NewOffset);
2260 /// getUse - Return an LSRUse index and an offset value for a fixup which
2261 /// needs the given expression, with the given kind and optional access type.
2262 /// Either reuse an existing use or create a new one, as needed.
2263 std::pair<size_t, int64_t>
2264 LSRInstance::getUse(const SCEV *&Expr,
2265 LSRUse::KindType Kind, Type *AccessTy) {
2266 const SCEV *Copy = Expr;
2267 int64_t Offset = ExtractImmediate(Expr, SE);
2269 // Basic uses can't accept any offset, for example.
2270 if (!isAlwaysFoldable(TTI, Kind, AccessTy, /*BaseGV=*/ nullptr,
2271 Offset, /*HasBaseReg=*/ true)) {
2276 std::pair<UseMapTy::iterator, bool> P =
2277 UseMap.insert(std::make_pair(LSRUse::SCEVUseKindPair(Expr, Kind), 0));
2279 // A use already existed with this base.
2280 size_t LUIdx = P.first->second;
2281 LSRUse &LU = Uses[LUIdx];
2282 if (reconcileNewOffset(LU, Offset, /*HasBaseReg=*/true, Kind, AccessTy))
2284 return std::make_pair(LUIdx, Offset);
2287 // Create a new use.
2288 size_t LUIdx = Uses.size();
2289 P.first->second = LUIdx;
2290 Uses.push_back(LSRUse(Kind, AccessTy));
2291 LSRUse &LU = Uses[LUIdx];
2293 // We don't need to track redundant offsets, but we don't need to go out
2294 // of our way here to avoid them.
2295 if (LU.Offsets.empty() || Offset != LU.Offsets.back())
2296 LU.Offsets.push_back(Offset);
2298 LU.MinOffset = Offset;
2299 LU.MaxOffset = Offset;
2300 return std::make_pair(LUIdx, Offset);
2303 /// DeleteUse - Delete the given use from the Uses list.
2304 void LSRInstance::DeleteUse(LSRUse &LU, size_t LUIdx) {
2305 if (&LU != &Uses.back())
2306 std::swap(LU, Uses.back());
2310 RegUses.SwapAndDropUse(LUIdx, Uses.size());
2313 /// FindUseWithFormula - Look for a use distinct from OrigLU which is has
2314 /// a formula that has the same registers as the given formula.
2316 LSRInstance::FindUseWithSimilarFormula(const Formula &OrigF,
2317 const LSRUse &OrigLU) {
2318 // Search all uses for the formula. This could be more clever.
2319 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2320 LSRUse &LU = Uses[LUIdx];
2321 // Check whether this use is close enough to OrigLU, to see whether it's
2322 // worthwhile looking through its formulae.
2323 // Ignore ICmpZero uses because they may contain formulae generated by
2324 // GenerateICmpZeroScales, in which case adding fixup offsets may
2326 if (&LU != &OrigLU &&
2327 LU.Kind != LSRUse::ICmpZero &&
2328 LU.Kind == OrigLU.Kind && OrigLU.AccessTy == LU.AccessTy &&
2329 LU.WidestFixupType == OrigLU.WidestFixupType &&
2330 LU.HasFormulaWithSameRegs(OrigF)) {
2331 // Scan through this use's formulae.
2332 for (const Formula &F : LU.Formulae) {
2333 // Check to see if this formula has the same registers and symbols
2335 if (F.BaseRegs == OrigF.BaseRegs &&
2336 F.ScaledReg == OrigF.ScaledReg &&
2337 F.BaseGV == OrigF.BaseGV &&
2338 F.Scale == OrigF.Scale &&
2339 F.UnfoldedOffset == OrigF.UnfoldedOffset) {
2340 if (F.BaseOffset == 0)
2342 // This is the formula where all the registers and symbols matched;
2343 // there aren't going to be any others. Since we declined it, we
2344 // can skip the rest of the formulae and proceed to the next LSRUse.
2351 // Nothing looked good.
2355 void LSRInstance::CollectInterestingTypesAndFactors() {
2356 SmallSetVector<const SCEV *, 4> Strides;
2358 // Collect interesting types and strides.
2359 SmallVector<const SCEV *, 4> Worklist;
2360 for (const IVStrideUse &U : IU) {
2361 const SCEV *Expr = IU.getExpr(U);
2363 // Collect interesting types.
2364 Types.insert(SE.getEffectiveSCEVType(Expr->getType()));
2366 // Add strides for mentioned loops.
2367 Worklist.push_back(Expr);
2369 const SCEV *S = Worklist.pop_back_val();
2370 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
2371 if (AR->getLoop() == L)
2372 Strides.insert(AR->getStepRecurrence(SE));
2373 Worklist.push_back(AR->getStart());
2374 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2375 Worklist.append(Add->op_begin(), Add->op_end());
2377 } while (!Worklist.empty());
2380 // Compute interesting factors from the set of interesting strides.
2381 for (SmallSetVector<const SCEV *, 4>::const_iterator
2382 I = Strides.begin(), E = Strides.end(); I != E; ++I)
2383 for (SmallSetVector<const SCEV *, 4>::const_iterator NewStrideIter =
2384 std::next(I); NewStrideIter != E; ++NewStrideIter) {
2385 const SCEV *OldStride = *I;
2386 const SCEV *NewStride = *NewStrideIter;
2388 if (SE.getTypeSizeInBits(OldStride->getType()) !=
2389 SE.getTypeSizeInBits(NewStride->getType())) {
2390 if (SE.getTypeSizeInBits(OldStride->getType()) >
2391 SE.getTypeSizeInBits(NewStride->getType()))
2392 NewStride = SE.getSignExtendExpr(NewStride, OldStride->getType());
2394 OldStride = SE.getSignExtendExpr(OldStride, NewStride->getType());
2396 if (const SCEVConstant *Factor =
2397 dyn_cast_or_null<SCEVConstant>(getExactSDiv(NewStride, OldStride,
2399 if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
2400 Factors.insert(Factor->getValue()->getValue().getSExtValue());
2401 } else if (const SCEVConstant *Factor =
2402 dyn_cast_or_null<SCEVConstant>(getExactSDiv(OldStride,
2405 if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
2406 Factors.insert(Factor->getValue()->getValue().getSExtValue());
2410 // If all uses use the same type, don't bother looking for truncation-based
2412 if (Types.size() == 1)
2415 DEBUG(print_factors_and_types(dbgs()));
2418 /// findIVOperand - Helper for CollectChains that finds an IV operand (computed
2419 /// by an AddRec in this loop) within [OI,OE) or returns OE. If IVUsers mapped
2420 /// Instructions to IVStrideUses, we could partially skip this.
2421 static User::op_iterator
2422 findIVOperand(User::op_iterator OI, User::op_iterator OE,
2423 Loop *L, ScalarEvolution &SE) {
2424 for(; OI != OE; ++OI) {
2425 if (Instruction *Oper = dyn_cast<Instruction>(*OI)) {
2426 if (!SE.isSCEVable(Oper->getType()))
2429 if (const SCEVAddRecExpr *AR =
2430 dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Oper))) {
2431 if (AR->getLoop() == L)
2439 /// getWideOperand - IVChain logic must consistenctly peek base TruncInst
2440 /// operands, so wrap it in a convenient helper.
2441 static Value *getWideOperand(Value *Oper) {
2442 if (TruncInst *Trunc = dyn_cast<TruncInst>(Oper))
2443 return Trunc->getOperand(0);
2447 /// isCompatibleIVType - Return true if we allow an IV chain to include both
2449 static bool isCompatibleIVType(Value *LVal, Value *RVal) {
2450 Type *LType = LVal->getType();
2451 Type *RType = RVal->getType();
2452 return (LType == RType) || (LType->isPointerTy() && RType->isPointerTy());
2455 /// getExprBase - Return an approximation of this SCEV expression's "base", or
2456 /// NULL for any constant. Returning the expression itself is
2457 /// conservative. Returning a deeper subexpression is more precise and valid as
2458 /// long as it isn't less complex than another subexpression. For expressions
2459 /// involving multiple unscaled values, we need to return the pointer-type
2460 /// SCEVUnknown. This avoids forming chains across objects, such as:
2461 /// PrevOper==a[i], IVOper==b[i], IVInc==b-a.
2463 /// Since SCEVUnknown is the rightmost type, and pointers are the rightmost
2464 /// SCEVUnknown, we simply return the rightmost SCEV operand.
2465 static const SCEV *getExprBase(const SCEV *S) {
2466 switch (S->getSCEVType()) {
2467 default: // uncluding scUnknown.
2472 return getExprBase(cast<SCEVTruncateExpr>(S)->getOperand());
2474 return getExprBase(cast<SCEVZeroExtendExpr>(S)->getOperand());
2476 return getExprBase(cast<SCEVSignExtendExpr>(S)->getOperand());
2478 // Skip over scaled operands (scMulExpr) to follow add operands as long as
2479 // there's nothing more complex.
2480 // FIXME: not sure if we want to recognize negation.
2481 const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
2482 for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(Add->op_end()),
2483 E(Add->op_begin()); I != E; ++I) {
2484 const SCEV *SubExpr = *I;
2485 if (SubExpr->getSCEVType() == scAddExpr)
2486 return getExprBase(SubExpr);
2488 if (SubExpr->getSCEVType() != scMulExpr)
2491 return S; // all operands are scaled, be conservative.
2494 return getExprBase(cast<SCEVAddRecExpr>(S)->getStart());
2498 /// Return true if the chain increment is profitable to expand into a loop
2499 /// invariant value, which may require its own register. A profitable chain
2500 /// increment will be an offset relative to the same base. We allow such offsets
2501 /// to potentially be used as chain increment as long as it's not obviously
2502 /// expensive to expand using real instructions.
2503 bool IVChain::isProfitableIncrement(const SCEV *OperExpr,
2504 const SCEV *IncExpr,
2505 ScalarEvolution &SE) {
2506 // Aggressively form chains when -stress-ivchain.
2510 // Do not replace a constant offset from IV head with a nonconstant IV
2512 if (!isa<SCEVConstant>(IncExpr)) {
2513 const SCEV *HeadExpr = SE.getSCEV(getWideOperand(Incs[0].IVOperand));
2514 if (isa<SCEVConstant>(SE.getMinusSCEV(OperExpr, HeadExpr)))
2518 SmallPtrSet<const SCEV*, 8> Processed;
2519 return !isHighCostExpansion(IncExpr, Processed, SE);
2522 /// Return true if the number of registers needed for the chain is estimated to
2523 /// be less than the number required for the individual IV users. First prohibit
2524 /// any IV users that keep the IV live across increments (the Users set should
2525 /// be empty). Next count the number and type of increments in the chain.
2527 /// Chaining IVs can lead to considerable code bloat if ISEL doesn't
2528 /// effectively use postinc addressing modes. Only consider it profitable it the
2529 /// increments can be computed in fewer registers when chained.
2531 /// TODO: Consider IVInc free if it's already used in another chains.
2533 isProfitableChain(IVChain &Chain, SmallPtrSetImpl<Instruction*> &Users,
2534 ScalarEvolution &SE, const TargetTransformInfo &TTI) {
2538 if (!Chain.hasIncs())
2541 if (!Users.empty()) {
2542 DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " users:\n";
2543 for (Instruction *Inst : Users) {
2544 dbgs() << " " << *Inst << "\n";
2548 assert(!Chain.Incs.empty() && "empty IV chains are not allowed");
2550 // The chain itself may require a register, so intialize cost to 1.
2553 // A complete chain likely eliminates the need for keeping the original IV in
2554 // a register. LSR does not currently know how to form a complete chain unless
2555 // the header phi already exists.
2556 if (isa<PHINode>(Chain.tailUserInst())
2557 && SE.getSCEV(Chain.tailUserInst()) == Chain.Incs[0].IncExpr) {
2560 const SCEV *LastIncExpr = nullptr;
2561 unsigned NumConstIncrements = 0;
2562 unsigned NumVarIncrements = 0;
2563 unsigned NumReusedIncrements = 0;
2564 for (const IVInc &Inc : Chain) {
2565 if (Inc.IncExpr->isZero())
2568 // Incrementing by zero or some constant is neutral. We assume constants can
2569 // be folded into an addressing mode or an add's immediate operand.
2570 if (isa<SCEVConstant>(Inc.IncExpr)) {
2571 ++NumConstIncrements;
2575 if (Inc.IncExpr == LastIncExpr)
2576 ++NumReusedIncrements;
2580 LastIncExpr = Inc.IncExpr;
2582 // An IV chain with a single increment is handled by LSR's postinc
2583 // uses. However, a chain with multiple increments requires keeping the IV's
2584 // value live longer than it needs to be if chained.
2585 if (NumConstIncrements > 1)
2588 // Materializing increment expressions in the preheader that didn't exist in
2589 // the original code may cost a register. For example, sign-extended array
2590 // indices can produce ridiculous increments like this:
2591 // IV + ((sext i32 (2 * %s) to i64) + (-1 * (sext i32 %s to i64)))
2592 cost += NumVarIncrements;
2594 // Reusing variable increments likely saves a register to hold the multiple of
2596 cost -= NumReusedIncrements;
2598 DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " Cost: " << cost
2604 /// ChainInstruction - Add this IV user to an existing chain or make it the head
2606 void LSRInstance::ChainInstruction(Instruction *UserInst, Instruction *IVOper,
2607 SmallVectorImpl<ChainUsers> &ChainUsersVec) {
2608 // When IVs are used as types of varying widths, they are generally converted
2609 // to a wider type with some uses remaining narrow under a (free) trunc.
2610 Value *const NextIV = getWideOperand(IVOper);
2611 const SCEV *const OperExpr = SE.getSCEV(NextIV);
2612 const SCEV *const OperExprBase = getExprBase(OperExpr);
2614 // Visit all existing chains. Check if its IVOper can be computed as a
2615 // profitable loop invariant increment from the last link in the Chain.
2616 unsigned ChainIdx = 0, NChains = IVChainVec.size();
2617 const SCEV *LastIncExpr = nullptr;
2618 for (; ChainIdx < NChains; ++ChainIdx) {
2619 IVChain &Chain = IVChainVec[ChainIdx];
2621 // Prune the solution space aggressively by checking that both IV operands
2622 // are expressions that operate on the same unscaled SCEVUnknown. This
2623 // "base" will be canceled by the subsequent getMinusSCEV call. Checking
2624 // first avoids creating extra SCEV expressions.
2625 if (!StressIVChain && Chain.ExprBase != OperExprBase)
2628 Value *PrevIV = getWideOperand(Chain.Incs.back().IVOperand);
2629 if (!isCompatibleIVType(PrevIV, NextIV))
2632 // A phi node terminates a chain.
2633 if (isa<PHINode>(UserInst) && isa<PHINode>(Chain.tailUserInst()))
2636 // The increment must be loop-invariant so it can be kept in a register.
2637 const SCEV *PrevExpr = SE.getSCEV(PrevIV);
2638 const SCEV *IncExpr = SE.getMinusSCEV(OperExpr, PrevExpr);
2639 if (!SE.isLoopInvariant(IncExpr, L))
2642 if (Chain.isProfitableIncrement(OperExpr, IncExpr, SE)) {
2643 LastIncExpr = IncExpr;
2647 // If we haven't found a chain, create a new one, unless we hit the max. Don't
2648 // bother for phi nodes, because they must be last in the chain.
2649 if (ChainIdx == NChains) {
2650 if (isa<PHINode>(UserInst))
2652 if (NChains >= MaxChains && !StressIVChain) {
2653 DEBUG(dbgs() << "IV Chain Limit\n");
2656 LastIncExpr = OperExpr;
2657 // IVUsers may have skipped over sign/zero extensions. We don't currently
2658 // attempt to form chains involving extensions unless they can be hoisted
2659 // into this loop's AddRec.
2660 if (!isa<SCEVAddRecExpr>(LastIncExpr))
2663 IVChainVec.push_back(IVChain(IVInc(UserInst, IVOper, LastIncExpr),
2665 ChainUsersVec.resize(NChains);
2666 DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Head: (" << *UserInst
2667 << ") IV=" << *LastIncExpr << "\n");
2669 DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Inc: (" << *UserInst
2670 << ") IV+" << *LastIncExpr << "\n");
2671 // Add this IV user to the end of the chain.
2672 IVChainVec[ChainIdx].add(IVInc(UserInst, IVOper, LastIncExpr));
2674 IVChain &Chain = IVChainVec[ChainIdx];
2676 SmallPtrSet<Instruction*,4> &NearUsers = ChainUsersVec[ChainIdx].NearUsers;
2677 // This chain's NearUsers become FarUsers.
2678 if (!LastIncExpr->isZero()) {
2679 ChainUsersVec[ChainIdx].FarUsers.insert(NearUsers.begin(),
2684 // All other uses of IVOperand become near uses of the chain.
2685 // We currently ignore intermediate values within SCEV expressions, assuming
2686 // they will eventually be used be the current chain, or can be computed
2687 // from one of the chain increments. To be more precise we could
2688 // transitively follow its user and only add leaf IV users to the set.
2689 for (User *U : IVOper->users()) {
2690 Instruction *OtherUse = dyn_cast<Instruction>(U);
2693 // Uses in the chain will no longer be uses if the chain is formed.
2694 // Include the head of the chain in this iteration (not Chain.begin()).
2695 IVChain::const_iterator IncIter = Chain.Incs.begin();
2696 IVChain::const_iterator IncEnd = Chain.Incs.end();
2697 for( ; IncIter != IncEnd; ++IncIter) {
2698 if (IncIter->UserInst == OtherUse)
2701 if (IncIter != IncEnd)
2704 if (SE.isSCEVable(OtherUse->getType())
2705 && !isa<SCEVUnknown>(SE.getSCEV(OtherUse))
2706 && IU.isIVUserOrOperand(OtherUse)) {
2709 NearUsers.insert(OtherUse);
2712 // Since this user is part of the chain, it's no longer considered a use
2714 ChainUsersVec[ChainIdx].FarUsers.erase(UserInst);
2717 /// CollectChains - Populate the vector of Chains.
2719 /// This decreases ILP at the architecture level. Targets with ample registers,
2720 /// multiple memory ports, and no register renaming probably don't want
2721 /// this. However, such targets should probably disable LSR altogether.
2723 /// The job of LSR is to make a reasonable choice of induction variables across
2724 /// the loop. Subsequent passes can easily "unchain" computation exposing more
2725 /// ILP *within the loop* if the target wants it.
2727 /// Finding the best IV chain is potentially a scheduling problem. Since LSR
2728 /// will not reorder memory operations, it will recognize this as a chain, but
2729 /// will generate redundant IV increments. Ideally this would be corrected later
2730 /// by a smart scheduler:
2736 /// TODO: Walk the entire domtree within this loop, not just the path to the
2737 /// loop latch. This will discover chains on side paths, but requires
2738 /// maintaining multiple copies of the Chains state.
2739 void LSRInstance::CollectChains() {
2740 DEBUG(dbgs() << "Collecting IV Chains.\n");
2741 SmallVector<ChainUsers, 8> ChainUsersVec;
2743 SmallVector<BasicBlock *,8> LatchPath;
2744 BasicBlock *LoopHeader = L->getHeader();
2745 for (DomTreeNode *Rung = DT.getNode(L->getLoopLatch());
2746 Rung->getBlock() != LoopHeader; Rung = Rung->getIDom()) {
2747 LatchPath.push_back(Rung->getBlock());
2749 LatchPath.push_back(LoopHeader);
2751 // Walk the instruction stream from the loop header to the loop latch.
2752 for (SmallVectorImpl<BasicBlock *>::reverse_iterator
2753 BBIter = LatchPath.rbegin(), BBEnd = LatchPath.rend();
2754 BBIter != BBEnd; ++BBIter) {
2755 for (BasicBlock::iterator I = (*BBIter)->begin(), E = (*BBIter)->end();
2757 // Skip instructions that weren't seen by IVUsers analysis.
2758 if (isa<PHINode>(I) || !IU.isIVUserOrOperand(I))
2761 // Ignore users that are part of a SCEV expression. This way we only
2762 // consider leaf IV Users. This effectively rediscovers a portion of
2763 // IVUsers analysis but in program order this time.
2764 if (SE.isSCEVable(I->getType()) && !isa<SCEVUnknown>(SE.getSCEV(I)))
2767 // Remove this instruction from any NearUsers set it may be in.
2768 for (unsigned ChainIdx = 0, NChains = IVChainVec.size();
2769 ChainIdx < NChains; ++ChainIdx) {
2770 ChainUsersVec[ChainIdx].NearUsers.erase(I);
2772 // Search for operands that can be chained.
2773 SmallPtrSet<Instruction*, 4> UniqueOperands;
2774 User::op_iterator IVOpEnd = I->op_end();
2775 User::op_iterator IVOpIter = findIVOperand(I->op_begin(), IVOpEnd, L, SE);
2776 while (IVOpIter != IVOpEnd) {
2777 Instruction *IVOpInst = cast<Instruction>(*IVOpIter);
2778 if (UniqueOperands.insert(IVOpInst).second)
2779 ChainInstruction(I, IVOpInst, ChainUsersVec);
2780 IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);
2782 } // Continue walking down the instructions.
2783 } // Continue walking down the domtree.
2784 // Visit phi backedges to determine if the chain can generate the IV postinc.
2785 for (BasicBlock::iterator I = L->getHeader()->begin();
2786 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
2787 if (!SE.isSCEVable(PN->getType()))
2791 dyn_cast<Instruction>(PN->getIncomingValueForBlock(L->getLoopLatch()));
2793 ChainInstruction(PN, IncV, ChainUsersVec);
2795 // Remove any unprofitable chains.
2796 unsigned ChainIdx = 0;
2797 for (unsigned UsersIdx = 0, NChains = IVChainVec.size();
2798 UsersIdx < NChains; ++UsersIdx) {
2799 if (!isProfitableChain(IVChainVec[UsersIdx],
2800 ChainUsersVec[UsersIdx].FarUsers, SE, TTI))
2802 // Preserve the chain at UsesIdx.
2803 if (ChainIdx != UsersIdx)
2804 IVChainVec[ChainIdx] = IVChainVec[UsersIdx];
2805 FinalizeChain(IVChainVec[ChainIdx]);
2808 IVChainVec.resize(ChainIdx);
2811 void LSRInstance::FinalizeChain(IVChain &Chain) {
2812 assert(!Chain.Incs.empty() && "empty IV chains are not allowed");
2813 DEBUG(dbgs() << "Final Chain: " << *Chain.Incs[0].UserInst << "\n");
2815 for (const IVInc &Inc : Chain) {
2816 DEBUG(dbgs() << " Inc: " << Inc.UserInst << "\n");
2817 auto UseI = std::find(Inc.UserInst->op_begin(), Inc.UserInst->op_end(),
2819 assert(UseI != Inc.UserInst->op_end() && "cannot find IV operand");
2820 IVIncSet.insert(UseI);
2824 /// Return true if the IVInc can be folded into an addressing mode.
2825 static bool canFoldIVIncExpr(const SCEV *IncExpr, Instruction *UserInst,
2826 Value *Operand, const TargetTransformInfo &TTI) {
2827 const SCEVConstant *IncConst = dyn_cast<SCEVConstant>(IncExpr);
2828 if (!IncConst || !isAddressUse(UserInst, Operand))
2831 if (IncConst->getValue()->getValue().getMinSignedBits() > 64)
2834 int64_t IncOffset = IncConst->getValue()->getSExtValue();
2835 if (!isAlwaysFoldable(TTI, LSRUse::Address,
2836 getAccessType(UserInst), /*BaseGV=*/ nullptr,
2837 IncOffset, /*HaseBaseReg=*/ false))
2843 /// GenerateIVChains - Generate an add or subtract for each IVInc in a chain to
2844 /// materialize the IV user's operand from the previous IV user's operand.
2845 void LSRInstance::GenerateIVChain(const IVChain &Chain, SCEVExpander &Rewriter,
2846 SmallVectorImpl<WeakVH> &DeadInsts) {
2847 // Find the new IVOperand for the head of the chain. It may have been replaced
2849 const IVInc &Head = Chain.Incs[0];
2850 User::op_iterator IVOpEnd = Head.UserInst->op_end();
2851 // findIVOperand returns IVOpEnd if it can no longer find a valid IV user.
2852 User::op_iterator IVOpIter = findIVOperand(Head.UserInst->op_begin(),
2854 Value *IVSrc = nullptr;
2855 while (IVOpIter != IVOpEnd) {
2856 IVSrc = getWideOperand(*IVOpIter);
2858 // If this operand computes the expression that the chain needs, we may use
2859 // it. (Check this after setting IVSrc which is used below.)
2861 // Note that if Head.IncExpr is wider than IVSrc, then this phi is too
2862 // narrow for the chain, so we can no longer use it. We do allow using a
2863 // wider phi, assuming the LSR checked for free truncation. In that case we
2864 // should already have a truncate on this operand such that
2865 // getSCEV(IVSrc) == IncExpr.
2866 if (SE.getSCEV(*IVOpIter) == Head.IncExpr
2867 || SE.getSCEV(IVSrc) == Head.IncExpr) {
2870 IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);
2872 if (IVOpIter == IVOpEnd) {
2873 // Gracefully give up on this chain.
2874 DEBUG(dbgs() << "Concealed chain head: " << *Head.UserInst << "\n");
2878 DEBUG(dbgs() << "Generate chain at: " << *IVSrc << "\n");
2879 Type *IVTy = IVSrc->getType();
2880 Type *IntTy = SE.getEffectiveSCEVType(IVTy);
2881 const SCEV *LeftOverExpr = nullptr;
2882 for (const IVInc &Inc : Chain) {
2883 Instruction *InsertPt = Inc.UserInst;
2884 if (isa<PHINode>(InsertPt))
2885 InsertPt = L->getLoopLatch()->getTerminator();
2887 // IVOper will replace the current IV User's operand. IVSrc is the IV
2888 // value currently held in a register.
2889 Value *IVOper = IVSrc;
2890 if (!Inc.IncExpr->isZero()) {
2891 // IncExpr was the result of subtraction of two narrow values, so must
2893 const SCEV *IncExpr = SE.getNoopOrSignExtend(Inc.IncExpr, IntTy);
2894 LeftOverExpr = LeftOverExpr ?
2895 SE.getAddExpr(LeftOverExpr, IncExpr) : IncExpr;
2897 if (LeftOverExpr && !LeftOverExpr->isZero()) {
2898 // Expand the IV increment.
2899 Rewriter.clearPostInc();
2900 Value *IncV = Rewriter.expandCodeFor(LeftOverExpr, IntTy, InsertPt);
2901 const SCEV *IVOperExpr = SE.getAddExpr(SE.getUnknown(IVSrc),
2902 SE.getUnknown(IncV));
2903 IVOper = Rewriter.expandCodeFor(IVOperExpr, IVTy, InsertPt);
2905 // If an IV increment can't be folded, use it as the next IV value.
2906 if (!canFoldIVIncExpr(LeftOverExpr, Inc.UserInst, Inc.IVOperand, TTI)) {
2907 assert(IVTy == IVOper->getType() && "inconsistent IV increment type");
2909 LeftOverExpr = nullptr;
2912 Type *OperTy = Inc.IVOperand->getType();
2913 if (IVTy != OperTy) {
2914 assert(SE.getTypeSizeInBits(IVTy) >= SE.getTypeSizeInBits(OperTy) &&
2915 "cannot extend a chained IV");
2916 IRBuilder<> Builder(InsertPt);
2917 IVOper = Builder.CreateTruncOrBitCast(IVOper, OperTy, "lsr.chain");
2919 Inc.UserInst->replaceUsesOfWith(Inc.IVOperand, IVOper);
2920 DeadInsts.emplace_back(Inc.IVOperand);
2922 // If LSR created a new, wider phi, we may also replace its postinc. We only
2923 // do this if we also found a wide value for the head of the chain.
2924 if (isa<PHINode>(Chain.tailUserInst())) {
2925 for (BasicBlock::iterator I = L->getHeader()->begin();
2926 PHINode *Phi = dyn_cast<PHINode>(I); ++I) {
2927 if (!isCompatibleIVType(Phi, IVSrc))
2929 Instruction *PostIncV = dyn_cast<Instruction>(
2930 Phi->getIncomingValueForBlock(L->getLoopLatch()));
2931 if (!PostIncV || (SE.getSCEV(PostIncV) != SE.getSCEV(IVSrc)))
2933 Value *IVOper = IVSrc;
2934 Type *PostIncTy = PostIncV->getType();
2935 if (IVTy != PostIncTy) {
2936 assert(PostIncTy->isPointerTy() && "mixing int/ptr IV types");
2937 IRBuilder<> Builder(L->getLoopLatch()->getTerminator());
2938 Builder.SetCurrentDebugLocation(PostIncV->getDebugLoc());
2939 IVOper = Builder.CreatePointerCast(IVSrc, PostIncTy, "lsr.chain");
2941 Phi->replaceUsesOfWith(PostIncV, IVOper);
2942 DeadInsts.emplace_back(PostIncV);
2947 void LSRInstance::CollectFixupsAndInitialFormulae() {
2948 for (const IVStrideUse &U : IU) {
2949 Instruction *UserInst = U.getUser();
2950 // Skip IV users that are part of profitable IV Chains.
2951 User::op_iterator UseI = std::find(UserInst->op_begin(), UserInst->op_end(),
2952 U.getOperandValToReplace());
2953 assert(UseI != UserInst->op_end() && "cannot find IV operand");
2954 if (IVIncSet.count(UseI))
2958 LSRFixup &LF = getNewFixup();
2959 LF.UserInst = UserInst;
2960 LF.OperandValToReplace = U.getOperandValToReplace();
2961 LF.PostIncLoops = U.getPostIncLoops();
2963 LSRUse::KindType Kind = LSRUse::Basic;
2964 Type *AccessTy = nullptr;
2965 if (isAddressUse(LF.UserInst, LF.OperandValToReplace)) {
2966 Kind = LSRUse::Address;
2967 AccessTy = getAccessType(LF.UserInst);
2970 const SCEV *S = IU.getExpr(U);
2972 // Equality (== and !=) ICmps are special. We can rewrite (i == N) as
2973 // (N - i == 0), and this allows (N - i) to be the expression that we work
2974 // with rather than just N or i, so we can consider the register
2975 // requirements for both N and i at the same time. Limiting this code to
2976 // equality icmps is not a problem because all interesting loops use
2977 // equality icmps, thanks to IndVarSimplify.
2978 if (ICmpInst *CI = dyn_cast<ICmpInst>(LF.UserInst))
2979 if (CI->isEquality()) {
2980 // Swap the operands if needed to put the OperandValToReplace on the
2981 // left, for consistency.
2982 Value *NV = CI->getOperand(1);
2983 if (NV == LF.OperandValToReplace) {
2984 CI->setOperand(1, CI->getOperand(0));
2985 CI->setOperand(0, NV);
2986 NV = CI->getOperand(1);
2990 // x == y --> x - y == 0
2991 const SCEV *N = SE.getSCEV(NV);
2992 if (SE.isLoopInvariant(N, L) && isSafeToExpand(N, SE)) {
2993 // S is normalized, so normalize N before folding it into S
2994 // to keep the result normalized.
2995 N = TransformForPostIncUse(Normalize, N, CI, nullptr,
2996 LF.PostIncLoops, SE, DT);
2997 Kind = LSRUse::ICmpZero;
2998 S = SE.getMinusSCEV(N, S);
3001 // -1 and the negations of all interesting strides (except the negation
3002 // of -1) are now also interesting.
3003 for (size_t i = 0, e = Factors.size(); i != e; ++i)
3004 if (Factors[i] != -1)
3005 Factors.insert(-(uint64_t)Factors[i]);
3009 // Set up the initial formula for this use.
3010 std::pair<size_t, int64_t> P = getUse(S, Kind, AccessTy);
3012 LF.Offset = P.second;
3013 LSRUse &LU = Uses[LF.LUIdx];
3014 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
3015 if (!LU.WidestFixupType ||
3016 SE.getTypeSizeInBits(LU.WidestFixupType) <
3017 SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
3018 LU.WidestFixupType = LF.OperandValToReplace->getType();
3020 // If this is the first use of this LSRUse, give it a formula.
3021 if (LU.Formulae.empty()) {
3022 InsertInitialFormula(S, LU, LF.LUIdx);
3023 CountRegisters(LU.Formulae.back(), LF.LUIdx);
3027 DEBUG(print_fixups(dbgs()));
3030 /// InsertInitialFormula - Insert a formula for the given expression into
3031 /// the given use, separating out loop-variant portions from loop-invariant
3032 /// and loop-computable portions.
3034 LSRInstance::InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx) {
3035 // Mark uses whose expressions cannot be expanded.
3036 if (!isSafeToExpand(S, SE))
3037 LU.RigidFormula = true;
3040 F.InitialMatch(S, L, SE);
3041 bool Inserted = InsertFormula(LU, LUIdx, F);
3042 assert(Inserted && "Initial formula already exists!"); (void)Inserted;
3045 /// InsertSupplementalFormula - Insert a simple single-register formula for
3046 /// the given expression into the given use.
3048 LSRInstance::InsertSupplementalFormula(const SCEV *S,
3049 LSRUse &LU, size_t LUIdx) {
3051 F.BaseRegs.push_back(S);
3052 F.HasBaseReg = true;
3053 bool Inserted = InsertFormula(LU, LUIdx, F);
3054 assert(Inserted && "Supplemental formula already exists!"); (void)Inserted;
3057 /// CountRegisters - Note which registers are used by the given formula,
3058 /// updating RegUses.
3059 void LSRInstance::CountRegisters(const Formula &F, size_t LUIdx) {
3061 RegUses.CountRegister(F.ScaledReg, LUIdx);
3062 for (const SCEV *BaseReg : F.BaseRegs)
3063 RegUses.CountRegister(BaseReg, LUIdx);
3066 /// InsertFormula - If the given formula has not yet been inserted, add it to
3067 /// the list, and return true. Return false otherwise.
3068 bool LSRInstance::InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F) {
3069 // Do not insert formula that we will not be able to expand.
3070 assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F) &&
3071 "Formula is illegal");
3072 if (!LU.InsertFormula(F))
3075 CountRegisters(F, LUIdx);
3079 /// CollectLoopInvariantFixupsAndFormulae - Check for other uses of
3080 /// loop-invariant values which we're tracking. These other uses will pin these
3081 /// values in registers, making them less profitable for elimination.
3082 /// TODO: This currently misses non-constant addrec step registers.
3083 /// TODO: Should this give more weight to users inside the loop?
3085 LSRInstance::CollectLoopInvariantFixupsAndFormulae() {
3086 SmallVector<const SCEV *, 8> Worklist(RegUses.begin(), RegUses.end());
3087 SmallPtrSet<const SCEV *, 32> Visited;
3089 while (!Worklist.empty()) {
3090 const SCEV *S = Worklist.pop_back_val();
3092 // Don't process the same SCEV twice
3093 if (!Visited.insert(S).second)
3096 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S))
3097 Worklist.append(N->op_begin(), N->op_end());
3098 else if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
3099 Worklist.push_back(C->getOperand());
3100 else if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
3101 Worklist.push_back(D->getLHS());
3102 Worklist.push_back(D->getRHS());
3103 } else if (const SCEVUnknown *US = dyn_cast<SCEVUnknown>(S)) {
3104 const Value *V = US->getValue();
3105 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
3106 // Look for instructions defined outside the loop.
3107 if (L->contains(Inst)) continue;
3108 } else if (isa<UndefValue>(V))
3109 // Undef doesn't have a live range, so it doesn't matter.
3111 for (const Use &U : V->uses()) {
3112 const Instruction *UserInst = dyn_cast<Instruction>(U.getUser());
3113 // Ignore non-instructions.
3116 // Ignore instructions in other functions (as can happen with
3118 if (UserInst->getParent()->getParent() != L->getHeader()->getParent())
3120 // Ignore instructions not dominated by the loop.
3121 const BasicBlock *UseBB = !isa<PHINode>(UserInst) ?
3122 UserInst->getParent() :
3123 cast<PHINode>(UserInst)->getIncomingBlock(
3124 PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
3125 if (!DT.dominates(L->getHeader(), UseBB))
3127 // Ignore uses which are part of other SCEV expressions, to avoid
3128 // analyzing them multiple times.
3129 if (SE.isSCEVable(UserInst->getType())) {
3130 const SCEV *UserS = SE.getSCEV(const_cast<Instruction *>(UserInst));
3131 // If the user is a no-op, look through to its uses.
3132 if (!isa<SCEVUnknown>(UserS))
3136 SE.getUnknown(const_cast<Instruction *>(UserInst)));
3140 // Ignore icmp instructions which are already being analyzed.
3141 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) {
3142 unsigned OtherIdx = !U.getOperandNo();
3143 Value *OtherOp = const_cast<Value *>(ICI->getOperand(OtherIdx));
3144 if (SE.hasComputableLoopEvolution(SE.getSCEV(OtherOp), L))
3148 LSRFixup &LF = getNewFixup();
3149 LF.UserInst = const_cast<Instruction *>(UserInst);
3150 LF.OperandValToReplace = U;
3151 std::pair<size_t, int64_t> P = getUse(S, LSRUse::Basic, nullptr);
3153 LF.Offset = P.second;
3154 LSRUse &LU = Uses[LF.LUIdx];
3155 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
3156 if (!LU.WidestFixupType ||
3157 SE.getTypeSizeInBits(LU.WidestFixupType) <
3158 SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
3159 LU.WidestFixupType = LF.OperandValToReplace->getType();
3160 InsertSupplementalFormula(US, LU, LF.LUIdx);
3161 CountRegisters(LU.Formulae.back(), Uses.size() - 1);
3168 /// CollectSubexprs - Split S into subexpressions which can be pulled out into
3169 /// separate registers. If C is non-null, multiply each subexpression by C.
3171 /// Return remainder expression after factoring the subexpressions captured by
3172 /// Ops. If Ops is complete, return NULL.
3173 static const SCEV *CollectSubexprs(const SCEV *S, const SCEVConstant *C,
3174 SmallVectorImpl<const SCEV *> &Ops,
3176 ScalarEvolution &SE,
3177 unsigned Depth = 0) {
3178 // Arbitrarily cap recursion to protect compile time.
3182 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3183 // Break out add operands.
3184 for (const SCEV *S : Add->operands()) {
3185 const SCEV *Remainder = CollectSubexprs(S, C, Ops, L, SE, Depth+1);
3187 Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder);
3190 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
3191 // Split a non-zero base out of an addrec.
3192 if (AR->getStart()->isZero())
3195 const SCEV *Remainder = CollectSubexprs(AR->getStart(),
3196 C, Ops, L, SE, Depth+1);
3197 // Split the non-zero AddRec unless it is part of a nested recurrence that
3198 // does not pertain to this loop.
3199 if (Remainder && (AR->getLoop() == L || !isa<SCEVAddRecExpr>(Remainder))) {
3200 Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder);
3201 Remainder = nullptr;
3203 if (Remainder != AR->getStart()) {
3205 Remainder = SE.getConstant(AR->getType(), 0);
3206 return SE.getAddRecExpr(Remainder,
3207 AR->getStepRecurrence(SE),
3209 //FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
3212 } else if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3213 // Break (C * (a + b + c)) into C*a + C*b + C*c.
3214 if (Mul->getNumOperands() != 2)
3216 if (const SCEVConstant *Op0 =
3217 dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3218 C = C ? cast<SCEVConstant>(SE.getMulExpr(C, Op0)) : Op0;
3219 const SCEV *Remainder =
3220 CollectSubexprs(Mul->getOperand(1), C, Ops, L, SE, Depth+1);
3222 Ops.push_back(SE.getMulExpr(C, Remainder));
3229 /// \brief Helper function for LSRInstance::GenerateReassociations.
3230 void LSRInstance::GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx,
3231 const Formula &Base,
3232 unsigned Depth, size_t Idx,
3234 const SCEV *BaseReg = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
3235 SmallVector<const SCEV *, 8> AddOps;
3236 const SCEV *Remainder = CollectSubexprs(BaseReg, nullptr, AddOps, L, SE);
3238 AddOps.push_back(Remainder);
3240 if (AddOps.size() == 1)
3243 for (SmallVectorImpl<const SCEV *>::const_iterator J = AddOps.begin(),
3247 // Loop-variant "unknown" values are uninteresting; we won't be able to
3248 // do anything meaningful with them.
3249 if (isa<SCEVUnknown>(*J) && !SE.isLoopInvariant(*J, L))
3252 // Don't pull a constant into a register if the constant could be folded
3253 // into an immediate field.
3254 if (isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind,
3255 LU.AccessTy, *J, Base.getNumRegs() > 1))
3258 // Collect all operands except *J.
3259 SmallVector<const SCEV *, 8> InnerAddOps(
3260 ((const SmallVector<const SCEV *, 8> &)AddOps).begin(), J);
3261 InnerAddOps.append(std::next(J),
3262 ((const SmallVector<const SCEV *, 8> &)AddOps).end());
3264 // Don't leave just a constant behind in a register if the constant could
3265 // be folded into an immediate field.
3266 if (InnerAddOps.size() == 1 &&
3267 isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind,
3268 LU.AccessTy, InnerAddOps[0], Base.getNumRegs() > 1))
3271 const SCEV *InnerSum = SE.getAddExpr(InnerAddOps);
3272 if (InnerSum->isZero())
3276 // Add the remaining pieces of the add back into the new formula.
3277 const SCEVConstant *InnerSumSC = dyn_cast<SCEVConstant>(InnerSum);
3278 if (InnerSumSC && SE.getTypeSizeInBits(InnerSumSC->getType()) <= 64 &&
3279 TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset +
3280 InnerSumSC->getValue()->getZExtValue())) {
3282 (uint64_t)F.UnfoldedOffset + InnerSumSC->getValue()->getZExtValue();
3284 F.ScaledReg = nullptr;
3286 F.BaseRegs.erase(F.BaseRegs.begin() + Idx);
3287 } else if (IsScaledReg)
3288 F.ScaledReg = InnerSum;
3290 F.BaseRegs[Idx] = InnerSum;
3292 // Add J as its own register, or an unfolded immediate.
3293 const SCEVConstant *SC = dyn_cast<SCEVConstant>(*J);
3294 if (SC && SE.getTypeSizeInBits(SC->getType()) <= 64 &&
3295 TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset +
3296 SC->getValue()->getZExtValue()))
3298 (uint64_t)F.UnfoldedOffset + SC->getValue()->getZExtValue();
3300 F.BaseRegs.push_back(*J);
3301 // We may have changed the number of register in base regs, adjust the
3302 // formula accordingly.
3305 if (InsertFormula(LU, LUIdx, F))
3306 // If that formula hadn't been seen before, recurse to find more like
3308 GenerateReassociations(LU, LUIdx, LU.Formulae.back(), Depth + 1);
3312 /// GenerateReassociations - Split out subexpressions from adds and the bases of
3314 void LSRInstance::GenerateReassociations(LSRUse &LU, unsigned LUIdx,
3315 Formula Base, unsigned Depth) {
3316 assert(Base.isCanonical() && "Input must be in the canonical form");
3317 // Arbitrarily cap recursion to protect compile time.
3321 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3322 GenerateReassociationsImpl(LU, LUIdx, Base, Depth, i);
3324 if (Base.Scale == 1)
3325 GenerateReassociationsImpl(LU, LUIdx, Base, Depth,
3326 /* Idx */ -1, /* IsScaledReg */ true);
3329 /// GenerateCombinations - Generate a formula consisting of all of the
3330 /// loop-dominating registers added into a single register.
3331 void LSRInstance::GenerateCombinations(LSRUse &LU, unsigned LUIdx,
3333 // This method is only interesting on a plurality of registers.
3334 if (Base.BaseRegs.size() + (Base.Scale == 1) <= 1)
3337 // Flatten the representation, i.e., reg1 + 1*reg2 => reg1 + reg2, before
3338 // processing the formula.
3342 SmallVector<const SCEV *, 4> Ops;
3343 for (const SCEV *BaseReg : Base.BaseRegs) {
3344 if (SE.properlyDominates(BaseReg, L->getHeader()) &&
3345 !SE.hasComputableLoopEvolution(BaseReg, L))
3346 Ops.push_back(BaseReg);
3348 F.BaseRegs.push_back(BaseReg);
3350 if (Ops.size() > 1) {
3351 const SCEV *Sum = SE.getAddExpr(Ops);
3352 // TODO: If Sum is zero, it probably means ScalarEvolution missed an
3353 // opportunity to fold something. For now, just ignore such cases
3354 // rather than proceed with zero in a register.
3355 if (!Sum->isZero()) {
3356 F.BaseRegs.push_back(Sum);
3358 (void)InsertFormula(LU, LUIdx, F);
3363 /// \brief Helper function for LSRInstance::GenerateSymbolicOffsets.
3364 void LSRInstance::GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx,
3365 const Formula &Base, size_t Idx,
3367 const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
3368 GlobalValue *GV = ExtractSymbol(G, SE);
3369 if (G->isZero() || !GV)
3373 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F))
3378 F.BaseRegs[Idx] = G;
3379 (void)InsertFormula(LU, LUIdx, F);
3382 /// GenerateSymbolicOffsets - Generate reuse formulae using symbolic offsets.
3383 void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx,
3385 // We can't add a symbolic offset if the address already contains one.
3386 if (Base.BaseGV) return;
3388 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3389 GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, i);
3390 if (Base.Scale == 1)
3391 GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, /* Idx */ -1,
3392 /* IsScaledReg */ true);
3395 /// \brief Helper function for LSRInstance::GenerateConstantOffsets.
3396 void LSRInstance::GenerateConstantOffsetsImpl(
3397 LSRUse &LU, unsigned LUIdx, const Formula &Base,
3398 const SmallVectorImpl<int64_t> &Worklist, size_t Idx, bool IsScaledReg) {
3399 const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
3400 for (int64_t Offset : Worklist) {
3402 F.BaseOffset = (uint64_t)Base.BaseOffset - Offset;
3403 if (isLegalUse(TTI, LU.MinOffset - Offset, LU.MaxOffset - Offset, LU.Kind,
3405 // Add the offset to the base register.
3406 const SCEV *NewG = SE.getAddExpr(SE.getConstant(G->getType(), Offset), G);
3407 // If it cancelled out, drop the base register, otherwise update it.
3408 if (NewG->isZero()) {
3411 F.ScaledReg = nullptr;
3413 F.DeleteBaseReg(F.BaseRegs[Idx]);
3415 } else if (IsScaledReg)
3418 F.BaseRegs[Idx] = NewG;
3420 (void)InsertFormula(LU, LUIdx, F);
3424 int64_t Imm = ExtractImmediate(G, SE);
3425 if (G->isZero() || Imm == 0)
3428 F.BaseOffset = (uint64_t)F.BaseOffset + Imm;
3429 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F))
3434 F.BaseRegs[Idx] = G;
3435 (void)InsertFormula(LU, LUIdx, F);
3438 /// GenerateConstantOffsets - Generate reuse formulae using symbolic offsets.
3439 void LSRInstance::GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx,
3441 // TODO: For now, just add the min and max offset, because it usually isn't
3442 // worthwhile looking at everything inbetween.
3443 SmallVector<int64_t, 2> Worklist;
3444 Worklist.push_back(LU.MinOffset);
3445 if (LU.MaxOffset != LU.MinOffset)
3446 Worklist.push_back(LU.MaxOffset);
3448 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3449 GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, i);
3450 if (Base.Scale == 1)
3451 GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, /* Idx */ -1,
3452 /* IsScaledReg */ true);
3455 /// GenerateICmpZeroScales - For ICmpZero, check to see if we can scale up
3456 /// the comparison. For example, x == y -> x*c == y*c.
3457 void LSRInstance::GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx,
3459 if (LU.Kind != LSRUse::ICmpZero) return;
3461 // Determine the integer type for the base formula.
3462 Type *IntTy = Base.getType();
3464 if (SE.getTypeSizeInBits(IntTy) > 64) return;
3466 // Don't do this if there is more than one offset.
3467 if (LU.MinOffset != LU.MaxOffset) return;
3469 assert(!Base.BaseGV && "ICmpZero use is not legal!");
3471 // Check each interesting stride.
3472 for (int64_t Factor : Factors) {
3473 // Check that the multiplication doesn't overflow.
3474 if (Base.BaseOffset == INT64_MIN && Factor == -1)
3476 int64_t NewBaseOffset = (uint64_t)Base.BaseOffset * Factor;
3477 if (NewBaseOffset / Factor != Base.BaseOffset)
3479 // If the offset will be truncated at this use, check that it is in bounds.
3480 if (!IntTy->isPointerTy() &&
3481 !ConstantInt::isValueValidForType(IntTy, NewBaseOffset))
3484 // Check that multiplying with the use offset doesn't overflow.
3485 int64_t Offset = LU.MinOffset;
3486 if (Offset == INT64_MIN && Factor == -1)
3488 Offset = (uint64_t)Offset * Factor;
3489 if (Offset / Factor != LU.MinOffset)
3491 // If the offset will be truncated at this use, check that it is in bounds.
3492 if (!IntTy->isPointerTy() &&
3493 !ConstantInt::isValueValidForType(IntTy, Offset))
3497 F.BaseOffset = NewBaseOffset;
3499 // Check that this scale is legal.
3500 if (!isLegalUse(TTI, Offset, Offset, LU.Kind, LU.AccessTy, F))
3503 // Compensate for the use having MinOffset built into it.
3504 F.BaseOffset = (uint64_t)F.BaseOffset + Offset - LU.MinOffset;
3506 const SCEV *FactorS = SE.getConstant(IntTy, Factor);
3508 // Check that multiplying with each base register doesn't overflow.
3509 for (size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) {
3510 F.BaseRegs[i] = SE.getMulExpr(F.BaseRegs[i], FactorS);
3511 if (getExactSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i])
3515 // Check that multiplying with the scaled register doesn't overflow.
3517 F.ScaledReg = SE.getMulExpr(F.ScaledReg, FactorS);
3518 if (getExactSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg)
3522 // Check that multiplying with the unfolded offset doesn't overflow.
3523 if (F.UnfoldedOffset != 0) {
3524 if (F.UnfoldedOffset == INT64_MIN && Factor == -1)
3526 F.UnfoldedOffset = (uint64_t)F.UnfoldedOffset * Factor;
3527 if (F.UnfoldedOffset / Factor != Base.UnfoldedOffset)
3529 // If the offset will be truncated, check that it is in bounds.
3530 if (!IntTy->isPointerTy() &&
3531 !ConstantInt::isValueValidForType(IntTy, F.UnfoldedOffset))
3535 // If we make it here and it's legal, add it.
3536 (void)InsertFormula(LU, LUIdx, F);
3541 /// GenerateScales - Generate stride factor reuse formulae by making use of
3542 /// scaled-offset address modes, for example.
3543 void LSRInstance::GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base) {
3544 // Determine the integer type for the base formula.
3545 Type *IntTy = Base.getType();
3548 // If this Formula already has a scaled register, we can't add another one.
3549 // Try to unscale the formula to generate a better scale.
3550 if (Base.Scale != 0 && !Base.Unscale())
3553 assert(Base.Scale == 0 && "Unscale did not did its job!");
3555 // Check each interesting stride.
3556 for (int64_t Factor : Factors) {
3557 Base.Scale = Factor;
3558 Base.HasBaseReg = Base.BaseRegs.size() > 1;
3559 // Check whether this scale is going to be legal.
3560 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
3562 // As a special-case, handle special out-of-loop Basic users specially.
3563 // TODO: Reconsider this special case.
3564 if (LU.Kind == LSRUse::Basic &&
3565 isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LSRUse::Special,
3566 LU.AccessTy, Base) &&
3567 LU.AllFixupsOutsideLoop)
3568 LU.Kind = LSRUse::Special;
3572 // For an ICmpZero, negating a solitary base register won't lead to
3574 if (LU.Kind == LSRUse::ICmpZero &&
3575 !Base.HasBaseReg && Base.BaseOffset == 0 && !Base.BaseGV)
3577 // For each addrec base reg, apply the scale, if possible.
3578 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3579 if (const SCEVAddRecExpr *AR =
3580 dyn_cast<SCEVAddRecExpr>(Base.BaseRegs[i])) {
3581 const SCEV *FactorS = SE.getConstant(IntTy, Factor);
3582 if (FactorS->isZero())
3584 // Divide out the factor, ignoring high bits, since we'll be
3585 // scaling the value back up in the end.
3586 if (const SCEV *Quotient = getExactSDiv(AR, FactorS, SE, true)) {
3587 // TODO: This could be optimized to avoid all the copying.
3589 F.ScaledReg = Quotient;
3590 F.DeleteBaseReg(F.BaseRegs[i]);
3591 // The canonical representation of 1*reg is reg, which is already in
3592 // Base. In that case, do not try to insert the formula, it will be
3594 if (F.Scale == 1 && F.BaseRegs.empty())
3596 (void)InsertFormula(LU, LUIdx, F);
3602 /// GenerateTruncates - Generate reuse formulae from different IV types.
3603 void LSRInstance::GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base) {
3604 // Don't bother truncating symbolic values.
3605 if (Base.BaseGV) return;
3607 // Determine the integer type for the base formula.
3608 Type *DstTy = Base.getType();
3610 DstTy = SE.getEffectiveSCEVType(DstTy);
3612 for (Type *SrcTy : Types) {
3613 if (SrcTy != DstTy && TTI.isTruncateFree(SrcTy, DstTy)) {
3616 if (F.ScaledReg) F.ScaledReg = SE.getAnyExtendExpr(F.ScaledReg, SrcTy);
3617 for (const SCEV *&BaseReg : F.BaseRegs)
3618 BaseReg = SE.getAnyExtendExpr(BaseReg, SrcTy);
3620 // TODO: This assumes we've done basic processing on all uses and
3621 // have an idea what the register usage is.
3622 if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses))
3625 (void)InsertFormula(LU, LUIdx, F);
3632 /// WorkItem - Helper class for GenerateCrossUseConstantOffsets. It's used to
3633 /// defer modifications so that the search phase doesn't have to worry about
3634 /// the data structures moving underneath it.
3638 const SCEV *OrigReg;
3640 WorkItem(size_t LI, int64_t I, const SCEV *R)
3641 : LUIdx(LI), Imm(I), OrigReg(R) {}
3643 void print(raw_ostream &OS) const;
3649 void WorkItem::print(raw_ostream &OS) const {
3650 OS << "in formulae referencing " << *OrigReg << " in use " << LUIdx
3651 << " , add offset " << Imm;
3654 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3655 void WorkItem::dump() const {
3656 print(errs()); errs() << '\n';
3660 /// GenerateCrossUseConstantOffsets - Look for registers which are a constant
3661 /// distance apart and try to form reuse opportunities between them.
3662 void LSRInstance::GenerateCrossUseConstantOffsets() {
3663 // Group the registers by their value without any added constant offset.
3664 typedef std::map<int64_t, const SCEV *> ImmMapTy;
3665 DenseMap<const SCEV *, ImmMapTy> Map;
3666 DenseMap<const SCEV *, SmallBitVector> UsedByIndicesMap;
3667 SmallVector<const SCEV *, 8> Sequence;
3668 for (const SCEV *Use : RegUses) {
3669 const SCEV *Reg = Use; // Make a copy for ExtractImmediate to modify.
3670 int64_t Imm = ExtractImmediate(Reg, SE);
3671 auto Pair = Map.insert(std::make_pair(Reg, ImmMapTy()));
3673 Sequence.push_back(Reg);
3674 Pair.first->second.insert(std::make_pair(Imm, Use));
3675 UsedByIndicesMap[Reg] |= RegUses.getUsedByIndices(Use);
3678 // Now examine each set of registers with the same base value. Build up
3679 // a list of work to do and do the work in a separate step so that we're
3680 // not adding formulae and register counts while we're searching.
3681 SmallVector<WorkItem, 32> WorkItems;
3682 SmallSet<std::pair<size_t, int64_t>, 32> UniqueItems;
3683 for (const SCEV *Reg : Sequence) {
3684 const ImmMapTy &Imms = Map.find(Reg)->second;
3686 // It's not worthwhile looking for reuse if there's only one offset.
3687 if (Imms.size() == 1)
3690 DEBUG(dbgs() << "Generating cross-use offsets for " << *Reg << ':';
3691 for (const auto &Entry : Imms)
3692 dbgs() << ' ' << Entry.first;
3695 // Examine each offset.
3696 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
3698 const SCEV *OrigReg = J->second;
3700 int64_t JImm = J->first;
3701 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg);
3703 if (!isa<SCEVConstant>(OrigReg) &&
3704 UsedByIndicesMap[Reg].count() == 1) {
3705 DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg << '\n');
3709 // Conservatively examine offsets between this orig reg a few selected
3711 ImmMapTy::const_iterator OtherImms[] = {
3712 Imms.begin(), std::prev(Imms.end()),
3713 Imms.lower_bound((Imms.begin()->first + std::prev(Imms.end())->first) /
3716 for (size_t i = 0, e = array_lengthof(OtherImms); i != e; ++i) {
3717 ImmMapTy::const_iterator M = OtherImms[i];
3718 if (M == J || M == JE) continue;
3720 // Compute the difference between the two.
3721 int64_t Imm = (uint64_t)JImm - M->first;
3722 for (int LUIdx = UsedByIndices.find_first(); LUIdx != -1;
3723 LUIdx = UsedByIndices.find_next(LUIdx))
3724 // Make a memo of this use, offset, and register tuple.
3725 if (UniqueItems.insert(std::make_pair(LUIdx, Imm)).second)
3726 WorkItems.push_back(WorkItem(LUIdx, Imm, OrigReg));
3733 UsedByIndicesMap.clear();
3734 UniqueItems.clear();
3736 // Now iterate through the worklist and add new formulae.
3737 for (const WorkItem &WI : WorkItems) {
3738 size_t LUIdx = WI.LUIdx;
3739 LSRUse &LU = Uses[LUIdx];
3740 int64_t Imm = WI.Imm;
3741 const SCEV *OrigReg = WI.OrigReg;
3743 Type *IntTy = SE.getEffectiveSCEVType(OrigReg->getType());
3744 const SCEV *NegImmS = SE.getSCEV(ConstantInt::get(IntTy, -(uint64_t)Imm));
3745 unsigned BitWidth = SE.getTypeSizeInBits(IntTy);
3747 // TODO: Use a more targeted data structure.
3748 for (size_t L = 0, LE = LU.Formulae.size(); L != LE; ++L) {
3749 Formula F = LU.Formulae[L];
3750 // FIXME: The code for the scaled and unscaled registers looks
3751 // very similar but slightly different. Investigate if they
3752 // could be merged. That way, we would not have to unscale the
3755 // Use the immediate in the scaled register.
3756 if (F.ScaledReg == OrigReg) {
3757 int64_t Offset = (uint64_t)F.BaseOffset + Imm * (uint64_t)F.Scale;
3758 // Don't create 50 + reg(-50).
3759 if (F.referencesReg(SE.getSCEV(
3760 ConstantInt::get(IntTy, -(uint64_t)Offset))))
3763 NewF.BaseOffset = Offset;
3764 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
3767 NewF.ScaledReg = SE.getAddExpr(NegImmS, NewF.ScaledReg);
3769 // If the new scale is a constant in a register, and adding the constant
3770 // value to the immediate would produce a value closer to zero than the
3771 // immediate itself, then the formula isn't worthwhile.
3772 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewF.ScaledReg))
3773 if (C->getValue()->isNegative() !=
3774 (NewF.BaseOffset < 0) &&
3775 (C->getValue()->getValue().abs() * APInt(BitWidth, F.Scale))
3776 .ule(std::abs(NewF.BaseOffset)))
3780 NewF.Canonicalize();
3781 (void)InsertFormula(LU, LUIdx, NewF);
3783 // Use the immediate in a base register.
3784 for (size_t N = 0, NE = F.BaseRegs.size(); N != NE; ++N) {
3785 const SCEV *BaseReg = F.BaseRegs[N];
3786 if (BaseReg != OrigReg)
3789 NewF.BaseOffset = (uint64_t)NewF.BaseOffset + Imm;
3790 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset,
3791 LU.Kind, LU.AccessTy, NewF)) {
3792 if (!TTI.isLegalAddImmediate((uint64_t)NewF.UnfoldedOffset + Imm))
3795 NewF.UnfoldedOffset = (uint64_t)NewF.UnfoldedOffset + Imm;
3797 NewF.BaseRegs[N] = SE.getAddExpr(NegImmS, BaseReg);
3799 // If the new formula has a constant in a register, and adding the
3800 // constant value to the immediate would produce a value closer to
3801 // zero than the immediate itself, then the formula isn't worthwhile.
3802 for (const SCEV *NewReg : NewF.BaseRegs)
3803 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewReg))
3804 if ((C->getValue()->getValue() + NewF.BaseOffset).abs().slt(
3805 std::abs(NewF.BaseOffset)) &&
3806 (C->getValue()->getValue() +
3807 NewF.BaseOffset).countTrailingZeros() >=
3808 countTrailingZeros<uint64_t>(NewF.BaseOffset))
3812 NewF.Canonicalize();
3813 (void)InsertFormula(LU, LUIdx, NewF);
3822 /// GenerateAllReuseFormulae - Generate formulae for each use.
3824 LSRInstance::GenerateAllReuseFormulae() {
3825 // This is split into multiple loops so that hasRegsUsedByUsesOtherThan
3826 // queries are more precise.
3827 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3828 LSRUse &LU = Uses[LUIdx];
3829 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3830 GenerateReassociations(LU, LUIdx, LU.Formulae[i]);
3831 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3832 GenerateCombinations(LU, LUIdx, LU.Formulae[i]);
3834 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3835 LSRUse &LU = Uses[LUIdx];
3836 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3837 GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]);
3838 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3839 GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]);
3840 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3841 GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]);
3842 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3843 GenerateScales(LU, LUIdx, LU.Formulae[i]);
3845 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3846 LSRUse &LU = Uses[LUIdx];
3847 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3848 GenerateTruncates(LU, LUIdx, LU.Formulae[i]);
3851 GenerateCrossUseConstantOffsets();
3853 DEBUG(dbgs() << "\n"
3854 "After generating reuse formulae:\n";
3855 print_uses(dbgs()));
3858 /// If there are multiple formulae with the same set of registers used
3859 /// by other uses, pick the best one and delete the others.
3860 void LSRInstance::FilterOutUndesirableDedicatedRegisters() {
3861 DenseSet<const SCEV *> VisitedRegs;
3862 SmallPtrSet<const SCEV *, 16> Regs;
3863 SmallPtrSet<const SCEV *, 16> LoserRegs;
3865 bool ChangedFormulae = false;
3868 // Collect the best formula for each unique set of shared registers. This
3869 // is reset for each use.
3870 typedef DenseMap<SmallVector<const SCEV *, 4>, size_t, UniquifierDenseMapInfo>
3872 BestFormulaeTy BestFormulae;
3874 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3875 LSRUse &LU = Uses[LUIdx];
3876 DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs()); dbgs() << '\n');
3879 for (size_t FIdx = 0, NumForms = LU.Formulae.size();
3880 FIdx != NumForms; ++FIdx) {
3881 Formula &F = LU.Formulae[FIdx];
3883 // Some formulas are instant losers. For example, they may depend on
3884 // nonexistent AddRecs from other loops. These need to be filtered
3885 // immediately, otherwise heuristics could choose them over others leading
3886 // to an unsatisfactory solution. Passing LoserRegs into RateFormula here
3887 // avoids the need to recompute this information across formulae using the
3888 // same bad AddRec. Passing LoserRegs is also essential unless we remove
3889 // the corresponding bad register from the Regs set.
3892 CostF.RateFormula(TTI, F, Regs, VisitedRegs, L, LU.Offsets, SE, DT, LU,
3894 if (CostF.isLoser()) {
3895 // During initial formula generation, undesirable formulae are generated
3896 // by uses within other loops that have some non-trivial address mode or
3897 // use the postinc form of the IV. LSR needs to provide these formulae
3898 // as the basis of rediscovering the desired formula that uses an AddRec
3899 // corresponding to the existing phi. Once all formulae have been
3900 // generated, these initial losers may be pruned.
3901 DEBUG(dbgs() << " Filtering loser "; F.print(dbgs());
3905 SmallVector<const SCEV *, 4> Key;
3906 for (const SCEV *Reg : F.BaseRegs) {
3907 if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx))
3911 RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx))
3912 Key.push_back(F.ScaledReg);
3913 // Unstable sort by host order ok, because this is only used for
3915 std::sort(Key.begin(), Key.end());
3917 std::pair<BestFormulaeTy::const_iterator, bool> P =
3918 BestFormulae.insert(std::make_pair(Key, FIdx));
3922 Formula &Best = LU.Formulae[P.first->second];
3926 CostBest.RateFormula(TTI, Best, Regs, VisitedRegs, L, LU.Offsets, SE,
3928 if (CostF < CostBest)
3930 DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs());
3932 " in favor of formula "; Best.print(dbgs());
3936 ChangedFormulae = true;
3938 LU.DeleteFormula(F);
3944 // Now that we've filtered out some formulae, recompute the Regs set.
3946 LU.RecomputeRegs(LUIdx, RegUses);
3948 // Reset this to prepare for the next use.
3949 BestFormulae.clear();
3952 DEBUG(if (ChangedFormulae) {
3954 "After filtering out undesirable candidates:\n";
3959 // This is a rough guess that seems to work fairly well.
3960 static const size_t ComplexityLimit = UINT16_MAX;
3962 /// EstimateSearchSpaceComplexity - Estimate the worst-case number of
3963 /// solutions the solver might have to consider. It almost never considers
3964 /// this many solutions because it prune the search space, but the pruning
3965 /// isn't always sufficient.
3966 size_t LSRInstance::EstimateSearchSpaceComplexity() const {
3968 for (const LSRUse &LU : Uses) {
3969 size_t FSize = LU.Formulae.size();
3970 if (FSize >= ComplexityLimit) {
3971 Power = ComplexityLimit;
3975 if (Power >= ComplexityLimit)
3981 /// NarrowSearchSpaceByDetectingSupersets - When one formula uses a superset
3982 /// of the registers of another formula, it won't help reduce register
3983 /// pressure (though it may not necessarily hurt register pressure); remove
3984 /// it to simplify the system.
3985 void LSRInstance::NarrowSearchSpaceByDetectingSupersets() {
3986 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
3987 DEBUG(dbgs() << "The search space is too complex.\n");
3989 DEBUG(dbgs() << "Narrowing the search space by eliminating formulae "
3990 "which use a superset of registers used by other "
3993 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3994 LSRUse &LU = Uses[LUIdx];
3996 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
3997 Formula &F = LU.Formulae[i];
3998 // Look for a formula with a constant or GV in a register. If the use
3999 // also has a formula with that same value in an immediate field,
4000 // delete the one that uses a register.
4001 for (SmallVectorImpl<const SCEV *>::const_iterator
4002 I = F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I) {
4003 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*I)) {
4005 NewF.BaseOffset += C->getValue()->getSExtValue();
4006 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
4007 (I - F.BaseRegs.begin()));
4008 if (LU.HasFormulaWithSameRegs(NewF)) {
4009 DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
4010 LU.DeleteFormula(F);
4016 } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(*I)) {
4017 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue()))
4021 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
4022 (I - F.BaseRegs.begin()));
4023 if (LU.HasFormulaWithSameRegs(NewF)) {
4024 DEBUG(dbgs() << " Deleting "; F.print(dbgs());
4026 LU.DeleteFormula(F);
4037 LU.RecomputeRegs(LUIdx, RegUses);
4040 DEBUG(dbgs() << "After pre-selection:\n";
4041 print_uses(dbgs()));
4045 /// NarrowSearchSpaceByCollapsingUnrolledCode - When there are many registers
4046 /// for expressions like A, A+1, A+2, etc., allocate a single register for
4048 void LSRInstance::NarrowSearchSpaceByCollapsingUnrolledCode() {
4049 if (EstimateSearchSpaceComplexity() < ComplexityLimit)
4052 DEBUG(dbgs() << "The search space is too complex.\n"
4053 "Narrowing the search space by assuming that uses separated "
4054 "by a constant offset will use the same registers.\n");
4056 // This is especially useful for unrolled loops.
4058 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4059 LSRUse &LU = Uses[LUIdx];
4060 for (const Formula &F : LU.Formulae) {
4061 if (F.BaseOffset == 0 || (F.Scale != 0 && F.Scale != 1))
4064 LSRUse *LUThatHas = FindUseWithSimilarFormula(F, LU);
4068 if (!reconcileNewOffset(*LUThatHas, F.BaseOffset, /*HasBaseReg=*/ false,
4069 LU.Kind, LU.AccessTy))
4072 DEBUG(dbgs() << " Deleting use "; LU.print(dbgs()); dbgs() << '\n');
4074 LUThatHas->AllFixupsOutsideLoop &= LU.AllFixupsOutsideLoop;
4076 // Update the relocs to reference the new use.
4077 for (LSRFixup &Fixup : Fixups) {
4078 if (Fixup.LUIdx == LUIdx) {
4079 Fixup.LUIdx = LUThatHas - &Uses.front();
4080 Fixup.Offset += F.BaseOffset;
4081 // Add the new offset to LUThatHas' offset list.
4082 if (LUThatHas->Offsets.back() != Fixup.Offset) {
4083 LUThatHas->Offsets.push_back(Fixup.Offset);
4084 if (Fixup.Offset > LUThatHas->MaxOffset)
4085 LUThatHas->MaxOffset = Fixup.Offset;
4086 if (Fixup.Offset < LUThatHas->MinOffset)
4087 LUThatHas->MinOffset = Fixup.Offset;
4089 DEBUG(dbgs() << "New fixup has offset " << Fixup.Offset << '\n');
4091 if (Fixup.LUIdx == NumUses-1)
4092 Fixup.LUIdx = LUIdx;
4095 // Delete formulae from the new use which are no longer legal.
4097 for (size_t i = 0, e = LUThatHas->Formulae.size(); i != e; ++i) {
4098 Formula &F = LUThatHas->Formulae[i];
4099 if (!isLegalUse(TTI, LUThatHas->MinOffset, LUThatHas->MaxOffset,
4100 LUThatHas->Kind, LUThatHas->AccessTy, F)) {
4101 DEBUG(dbgs() << " Deleting "; F.print(dbgs());
4103 LUThatHas->DeleteFormula(F);
4111 LUThatHas->RecomputeRegs(LUThatHas - &Uses.front(), RegUses);
4113 // Delete the old use.
4114 DeleteUse(LU, LUIdx);
4121 DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
4124 /// NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters - Call
4125 /// FilterOutUndesirableDedicatedRegisters again, if necessary, now that
4126 /// we've done more filtering, as it may be able to find more formulae to
4128 void LSRInstance::NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters(){
4129 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
4130 DEBUG(dbgs() << "The search space is too complex.\n");
4132 DEBUG(dbgs() << "Narrowing the search space by re-filtering out "
4133 "undesirable dedicated registers.\n");
4135 FilterOutUndesirableDedicatedRegisters();
4137 DEBUG(dbgs() << "After pre-selection:\n";
4138 print_uses(dbgs()));
4142 /// NarrowSearchSpaceByPickingWinnerRegs - Pick a register which seems likely
4143 /// to be profitable, and then in any use which has any reference to that
4144 /// register, delete all formulae which do not reference that register.
4145 void LSRInstance::NarrowSearchSpaceByPickingWinnerRegs() {
4146 // With all other options exhausted, loop until the system is simple
4147 // enough to handle.
4148 SmallPtrSet<const SCEV *, 4> Taken;
4149 while (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
4150 // Ok, we have too many of formulae on our hands to conveniently handle.
4151 // Use a rough heuristic to thin out the list.
4152 DEBUG(dbgs() << "The search space is too complex.\n");
4154 // Pick the register which is used by the most LSRUses, which is likely
4155 // to be a good reuse register candidate.
4156 const SCEV *Best = nullptr;
4157 unsigned BestNum = 0;
4158 for (const SCEV *Reg : RegUses) {
4159 if (Taken.count(Reg))
4164 unsigned Count = RegUses.getUsedByIndices(Reg).count();
4165 if (Count > BestNum) {
4172 DEBUG(dbgs() << "Narrowing the search space by assuming " << *Best
4173 << " will yield profitable reuse.\n");
4176 // In any use with formulae which references this register, delete formulae
4177 // which don't reference it.
4178 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4179 LSRUse &LU = Uses[LUIdx];
4180 if (!LU.Regs.count(Best)) continue;
4183 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
4184 Formula &F = LU.Formulae[i];
4185 if (!F.referencesReg(Best)) {
4186 DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
4187 LU.DeleteFormula(F);
4191 assert(e != 0 && "Use has no formulae left! Is Regs inconsistent?");
4197 LU.RecomputeRegs(LUIdx, RegUses);
4200 DEBUG(dbgs() << "After pre-selection:\n";
4201 print_uses(dbgs()));
4205 /// NarrowSearchSpaceUsingHeuristics - If there are an extraordinary number of
4206 /// formulae to choose from, use some rough heuristics to prune down the number
4207 /// of formulae. This keeps the main solver from taking an extraordinary amount
4208 /// of time in some worst-case scenarios.
4209 void LSRInstance::NarrowSearchSpaceUsingHeuristics() {
4210 NarrowSearchSpaceByDetectingSupersets();
4211 NarrowSearchSpaceByCollapsingUnrolledCode();
4212 NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
4213 NarrowSearchSpaceByPickingWinnerRegs();
4216 /// SolveRecurse - This is the recursive solver.
4217 void LSRInstance::SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
4219 SmallVectorImpl<const Formula *> &Workspace,
4220 const Cost &CurCost,
4221 const SmallPtrSet<const SCEV *, 16> &CurRegs,
4222 DenseSet<const SCEV *> &VisitedRegs) const {
4225 // - use more aggressive filtering
4226 // - sort the formula so that the most profitable solutions are found first
4227 // - sort the uses too
4229 // - don't compute a cost, and then compare. compare while computing a cost
4231 // - track register sets with SmallBitVector
4233 const LSRUse &LU = Uses[Workspace.size()];
4235 // If this use references any register that's already a part of the
4236 // in-progress solution, consider it a requirement that a formula must
4237 // reference that register in order to be considered. This prunes out
4238 // unprofitable searching.
4239 SmallSetVector<const SCEV *, 4> ReqRegs;
4240 for (const SCEV *S : CurRegs)
4241 if (LU.Regs.count(S))
4244 SmallPtrSet<const SCEV *, 16> NewRegs;
4246 for (const Formula &F : LU.Formulae) {
4247 // Ignore formulae which may not be ideal in terms of register reuse of
4248 // ReqRegs. The formula should use all required registers before
4249 // introducing new ones.
4250 int NumReqRegsToFind = std::min(F.getNumRegs(), ReqRegs.size());
4251 for (const SCEV *Reg : ReqRegs) {
4252 if ((F.ScaledReg && F.ScaledReg == Reg) ||
4253 std::find(F.BaseRegs.begin(), F.BaseRegs.end(), Reg) !=
4256 if (NumReqRegsToFind == 0)
4260 if (NumReqRegsToFind != 0) {
4261 // If none of the formulae satisfied the required registers, then we could
4262 // clear ReqRegs and try again. Currently, we simply give up in this case.
4266 // Evaluate the cost of the current formula. If it's already worse than
4267 // the current best, prune the search at that point.
4270 NewCost.RateFormula(TTI, F, NewRegs, VisitedRegs, L, LU.Offsets, SE, DT,
4272 if (NewCost < SolutionCost) {
4273 Workspace.push_back(&F);
4274 if (Workspace.size() != Uses.size()) {
4275 SolveRecurse(Solution, SolutionCost, Workspace, NewCost,
4276 NewRegs, VisitedRegs);
4277 if (F.getNumRegs() == 1 && Workspace.size() == 1)
4278 VisitedRegs.insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]);
4280 DEBUG(dbgs() << "New best at "; NewCost.print(dbgs());
4281 dbgs() << ".\n Regs:";
4282 for (const SCEV *S : NewRegs)
4283 dbgs() << ' ' << *S;
4286 SolutionCost = NewCost;
4287 Solution = Workspace;
4289 Workspace.pop_back();
4294 /// Solve - Choose one formula from each use. Return the results in the given
4295 /// Solution vector.
4296 void LSRInstance::Solve(SmallVectorImpl<const Formula *> &Solution) const {
4297 SmallVector<const Formula *, 8> Workspace;
4299 SolutionCost.Lose();
4301 SmallPtrSet<const SCEV *, 16> CurRegs;
4302 DenseSet<const SCEV *> VisitedRegs;
4303 Workspace.reserve(Uses.size());
4305 // SolveRecurse does all the work.
4306 SolveRecurse(Solution, SolutionCost, Workspace, CurCost,
4307 CurRegs, VisitedRegs);
4308 if (Solution.empty()) {
4309 DEBUG(dbgs() << "\nNo Satisfactory Solution\n");
4313 // Ok, we've now made all our decisions.
4314 DEBUG(dbgs() << "\n"
4315 "The chosen solution requires "; SolutionCost.print(dbgs());
4317 for (size_t i = 0, e = Uses.size(); i != e; ++i) {
4319 Uses[i].print(dbgs());
4322 Solution[i]->print(dbgs());
4326 assert(Solution.size() == Uses.size() && "Malformed solution!");
4329 /// HoistInsertPosition - Helper for AdjustInsertPositionForExpand. Climb up
4330 /// the dominator tree far as we can go while still being dominated by the
4331 /// input positions. This helps canonicalize the insert position, which
4332 /// encourages sharing.
4333 BasicBlock::iterator
4334 LSRInstance::HoistInsertPosition(BasicBlock::iterator IP,
4335 const SmallVectorImpl<Instruction *> &Inputs)
4338 const Loop *IPLoop = LI.getLoopFor(IP->getParent());
4339 unsigned IPLoopDepth = IPLoop ? IPLoop->getLoopDepth() : 0;
4342 for (DomTreeNode *Rung = DT.getNode(IP->getParent()); ; ) {
4343 if (!Rung) return IP;
4344 Rung = Rung->getIDom();
4345 if (!Rung) return IP;
4346 IDom = Rung->getBlock();
4348 // Don't climb into a loop though.
4349 const Loop *IDomLoop = LI.getLoopFor(IDom);
4350 unsigned IDomDepth = IDomLoop ? IDomLoop->getLoopDepth() : 0;
4351 if (IDomDepth <= IPLoopDepth &&
4352 (IDomDepth != IPLoopDepth || IDomLoop == IPLoop))
4356 bool AllDominate = true;
4357 Instruction *BetterPos = nullptr;
4358 Instruction *Tentative = IDom->getTerminator();
4359 for (Instruction *Inst : Inputs) {
4360 if (Inst == Tentative || !DT.dominates(Inst, Tentative)) {
4361 AllDominate = false;
4364 // Attempt to find an insert position in the middle of the block,
4365 // instead of at the end, so that it can be used for other expansions.
4366 if (IDom == Inst->getParent() &&
4367 (!BetterPos || !DT.dominates(Inst, BetterPos)))
4368 BetterPos = std::next(BasicBlock::iterator(Inst));
4381 /// AdjustInsertPositionForExpand - Determine an input position which will be
4382 /// dominated by the operands and which will dominate the result.
4383 BasicBlock::iterator
4384 LSRInstance::AdjustInsertPositionForExpand(BasicBlock::iterator LowestIP,
4387 SCEVExpander &Rewriter) const {
4388 // Collect some instructions which must be dominated by the
4389 // expanding replacement. These must be dominated by any operands that
4390 // will be required in the expansion.
4391 SmallVector<Instruction *, 4> Inputs;
4392 if (Instruction *I = dyn_cast<Instruction>(LF.OperandValToReplace))
4393 Inputs.push_back(I);
4394 if (LU.Kind == LSRUse::ICmpZero)
4395 if (Instruction *I =
4396 dyn_cast<Instruction>(cast<ICmpInst>(LF.UserInst)->getOperand(1)))
4397 Inputs.push_back(I);
4398 if (LF.PostIncLoops.count(L)) {
4399 if (LF.isUseFullyOutsideLoop(L))
4400 Inputs.push_back(L->getLoopLatch()->getTerminator());
4402 Inputs.push_back(IVIncInsertPos);
4404 // The expansion must also be dominated by the increment positions of any
4405 // loops it for which it is using post-inc mode.
4406 for (const Loop *PIL : LF.PostIncLoops) {
4407 if (PIL == L) continue;
4409 // Be dominated by the loop exit.
4410 SmallVector<BasicBlock *, 4> ExitingBlocks;
4411 PIL->getExitingBlocks(ExitingBlocks);
4412 if (!ExitingBlocks.empty()) {
4413 BasicBlock *BB = ExitingBlocks[0];
4414 for (unsigned i = 1, e = ExitingBlocks.size(); i != e; ++i)
4415 BB = DT.findNearestCommonDominator(BB, ExitingBlocks[i]);
4416 Inputs.push_back(BB->getTerminator());
4420 assert(!isa<PHINode>(LowestIP) && !isa<LandingPadInst>(LowestIP)
4421 && !isa<DbgInfoIntrinsic>(LowestIP) &&
4422 "Insertion point must be a normal instruction");
4424 // Then, climb up the immediate dominator tree as far as we can go while
4425 // still being dominated by the input positions.
4426 BasicBlock::iterator IP = HoistInsertPosition(LowestIP, Inputs);
4428 // Don't insert instructions before PHI nodes.
4429 while (isa<PHINode>(IP)) ++IP;
4431 // Ignore landingpad instructions.
4432 while (isa<LandingPadInst>(IP)) ++IP;
4434 // Ignore debug intrinsics.
4435 while (isa<DbgInfoIntrinsic>(IP)) ++IP;
4437 // Set IP below instructions recently inserted by SCEVExpander. This keeps the
4438 // IP consistent across expansions and allows the previously inserted
4439 // instructions to be reused by subsequent expansion.
4440 while (Rewriter.isInsertedInstruction(IP) && IP != LowestIP) ++IP;
4445 /// Expand - Emit instructions for the leading candidate expression for this
4446 /// LSRUse (this is called "expanding").
4447 Value *LSRInstance::Expand(const LSRFixup &LF,
4449 BasicBlock::iterator IP,
4450 SCEVExpander &Rewriter,
4451 SmallVectorImpl<WeakVH> &DeadInsts) const {
4452 const LSRUse &LU = Uses[LF.LUIdx];
4453 if (LU.RigidFormula)
4454 return LF.OperandValToReplace;
4456 // Determine an input position which will be dominated by the operands and
4457 // which will dominate the result.
4458 IP = AdjustInsertPositionForExpand(IP, LF, LU, Rewriter);
4460 // Inform the Rewriter if we have a post-increment use, so that it can
4461 // perform an advantageous expansion.
4462 Rewriter.setPostInc(LF.PostIncLoops);
4464 // This is the type that the user actually needs.
4465 Type *OpTy = LF.OperandValToReplace->getType();
4466 // This will be the type that we'll initially expand to.
4467 Type *Ty = F.getType();
4469 // No type known; just expand directly to the ultimate type.
4471 else if (SE.getEffectiveSCEVType(Ty) == SE.getEffectiveSCEVType(OpTy))
4472 // Expand directly to the ultimate type if it's the right size.
4474 // This is the type to do integer arithmetic in.
4475 Type *IntTy = SE.getEffectiveSCEVType(Ty);
4477 // Build up a list of operands to add together to form the full base.
4478 SmallVector<const SCEV *, 8> Ops;
4480 // Expand the BaseRegs portion.
4481 for (const SCEV *Reg : F.BaseRegs) {
4482 assert(!Reg->isZero() && "Zero allocated in a base register!");
4484 // If we're expanding for a post-inc user, make the post-inc adjustment.
4485 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
4486 Reg = TransformForPostIncUse(Denormalize, Reg,
4487 LF.UserInst, LF.OperandValToReplace,
4490 Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, nullptr, IP)));
4493 // Expand the ScaledReg portion.
4494 Value *ICmpScaledV = nullptr;
4496 const SCEV *ScaledS = F.ScaledReg;
4498 // If we're expanding for a post-inc user, make the post-inc adjustment.
4499 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
4500 ScaledS = TransformForPostIncUse(Denormalize, ScaledS,
4501 LF.UserInst, LF.OperandValToReplace,
4504 if (LU.Kind == LSRUse::ICmpZero) {
4505 // Expand ScaleReg as if it was part of the base regs.
4508 SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr, IP)));
4510 // An interesting way of "folding" with an icmp is to use a negated
4511 // scale, which we'll implement by inserting it into the other operand
4513 assert(F.Scale == -1 &&
4514 "The only scale supported by ICmpZero uses is -1!");
4515 ICmpScaledV = Rewriter.expandCodeFor(ScaledS, nullptr, IP);
4518 // Otherwise just expand the scaled register and an explicit scale,
4519 // which is expected to be matched as part of the address.
4521 // Flush the operand list to suppress SCEVExpander hoisting address modes.
4522 // Unless the addressing mode will not be folded.
4523 if (!Ops.empty() && LU.Kind == LSRUse::Address &&
4524 isAMCompletelyFolded(TTI, LU, F)) {
4525 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
4527 Ops.push_back(SE.getUnknown(FullV));
4529 ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr, IP));
4532 SE.getMulExpr(ScaledS, SE.getConstant(ScaledS->getType(), F.Scale));
4533 Ops.push_back(ScaledS);
4537 // Expand the GV portion.
4539 // Flush the operand list to suppress SCEVExpander hoisting.
4541 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
4543 Ops.push_back(SE.getUnknown(FullV));
4545 Ops.push_back(SE.getUnknown(F.BaseGV));
4548 // Flush the operand list to suppress SCEVExpander hoisting of both folded and
4549 // unfolded offsets. LSR assumes they both live next to their uses.
4551 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
4553 Ops.push_back(SE.getUnknown(FullV));
4556 // Expand the immediate portion.
4557 int64_t Offset = (uint64_t)F.BaseOffset + LF.Offset;
4559 if (LU.Kind == LSRUse::ICmpZero) {
4560 // The other interesting way of "folding" with an ICmpZero is to use a
4561 // negated immediate.
4563 ICmpScaledV = ConstantInt::get(IntTy, -(uint64_t)Offset);
4565 Ops.push_back(SE.getUnknown(ICmpScaledV));
4566 ICmpScaledV = ConstantInt::get(IntTy, Offset);
4569 // Just add the immediate values. These again are expected to be matched
4570 // as part of the address.
4571 Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy, Offset)));
4575 // Expand the unfolded offset portion.
4576 int64_t UnfoldedOffset = F.UnfoldedOffset;
4577 if (UnfoldedOffset != 0) {
4578 // Just add the immediate values.
4579 Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy,
4583 // Emit instructions summing all the operands.
4584 const SCEV *FullS = Ops.empty() ?
4585 SE.getConstant(IntTy, 0) :
4587 Value *FullV = Rewriter.expandCodeFor(FullS, Ty, IP);
4589 // We're done expanding now, so reset the rewriter.
4590 Rewriter.clearPostInc();
4592 // An ICmpZero Formula represents an ICmp which we're handling as a
4593 // comparison against zero. Now that we've expanded an expression for that
4594 // form, update the ICmp's other operand.
4595 if (LU.Kind == LSRUse::ICmpZero) {
4596 ICmpInst *CI = cast<ICmpInst>(LF.UserInst);
4597 DeadInsts.emplace_back(CI->getOperand(1));
4598 assert(!F.BaseGV && "ICmp does not support folding a global value and "
4599 "a scale at the same time!");
4600 if (F.Scale == -1) {
4601 if (ICmpScaledV->getType() != OpTy) {
4603 CastInst::Create(CastInst::getCastOpcode(ICmpScaledV, false,
4605 ICmpScaledV, OpTy, "tmp", CI);
4608 CI->setOperand(1, ICmpScaledV);
4610 // A scale of 1 means that the scale has been expanded as part of the
4612 assert((F.Scale == 0 || F.Scale == 1) &&
4613 "ICmp does not support folding a global value and "
4614 "a scale at the same time!");
4615 Constant *C = ConstantInt::getSigned(SE.getEffectiveSCEVType(OpTy),
4617 if (C->getType() != OpTy)
4618 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4622 CI->setOperand(1, C);
4629 /// RewriteForPHI - Helper for Rewrite. PHI nodes are special because the use
4630 /// of their operands effectively happens in their predecessor blocks, so the
4631 /// expression may need to be expanded in multiple places.
4632 void LSRInstance::RewriteForPHI(PHINode *PN,
4635 SCEVExpander &Rewriter,
4636 SmallVectorImpl<WeakVH> &DeadInsts,
4638 DenseMap<BasicBlock *, Value *> Inserted;
4639 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4640 if (PN->getIncomingValue(i) == LF.OperandValToReplace) {
4641 BasicBlock *BB = PN->getIncomingBlock(i);
4643 // If this is a critical edge, split the edge so that we do not insert
4644 // the code on all predecessor/successor paths. We do this unless this
4645 // is the canonical backedge for this loop, which complicates post-inc
4647 if (e != 1 && BB->getTerminator()->getNumSuccessors() > 1 &&
4648 !isa<IndirectBrInst>(BB->getTerminator())) {
4649 BasicBlock *Parent = PN->getParent();
4650 Loop *PNLoop = LI.getLoopFor(Parent);
4651 if (!PNLoop || Parent != PNLoop->getHeader()) {
4652 // Split the critical edge.
4653 BasicBlock *NewBB = nullptr;
4654 if (!Parent->isLandingPad()) {
4655 NewBB = SplitCriticalEdge(BB, Parent,
4656 CriticalEdgeSplittingOptions(&DT, &LI)
4657 .setMergeIdenticalEdges()
4658 .setDontDeleteUselessPHIs());
4660 SmallVector<BasicBlock*, 2> NewBBs;
4661 SplitLandingPadPredecessors(Parent, BB, "", "", NewBBs,
4662 /*AliasAnalysis*/ nullptr, &DT, &LI);
4665 // If NewBB==NULL, then SplitCriticalEdge refused to split because all
4666 // phi predecessors are identical. The simple thing to do is skip
4667 // splitting in this case rather than complicate the API.
4669 // If PN is outside of the loop and BB is in the loop, we want to
4670 // move the block to be immediately before the PHI block, not
4671 // immediately after BB.
4672 if (L->contains(BB) && !L->contains(PN))
4673 NewBB->moveBefore(PN->getParent());
4675 // Splitting the edge can reduce the number of PHI entries we have.
4676 e = PN->getNumIncomingValues();
4678 i = PN->getBasicBlockIndex(BB);
4683 std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> Pair =
4684 Inserted.insert(std::make_pair(BB, static_cast<Value *>(nullptr)));
4686 PN->setIncomingValue(i, Pair.first->second);
4688 Value *FullV = Expand(LF, F, BB->getTerminator(), Rewriter, DeadInsts);
4690 // If this is reuse-by-noop-cast, insert the noop cast.
4691 Type *OpTy = LF.OperandValToReplace->getType();
4692 if (FullV->getType() != OpTy)
4694 CastInst::Create(CastInst::getCastOpcode(FullV, false,
4696 FullV, LF.OperandValToReplace->getType(),
4697 "tmp", BB->getTerminator());
4699 PN->setIncomingValue(i, FullV);
4700 Pair.first->second = FullV;
4705 /// Rewrite - Emit instructions for the leading candidate expression for this
4706 /// LSRUse (this is called "expanding"), and update the UserInst to reference
4707 /// the newly expanded value.
4708 void LSRInstance::Rewrite(const LSRFixup &LF,
4710 SCEVExpander &Rewriter,
4711 SmallVectorImpl<WeakVH> &DeadInsts,
4713 // First, find an insertion point that dominates UserInst. For PHI nodes,
4714 // find the nearest block which dominates all the relevant uses.
4715 if (PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) {
4716 RewriteForPHI(PN, LF, F, Rewriter, DeadInsts, P);
4718 Value *FullV = Expand(LF, F, LF.UserInst, Rewriter, DeadInsts);
4720 // If this is reuse-by-noop-cast, insert the noop cast.
4721 Type *OpTy = LF.OperandValToReplace->getType();
4722 if (FullV->getType() != OpTy) {
4724 CastInst::Create(CastInst::getCastOpcode(FullV, false, OpTy, false),
4725 FullV, OpTy, "tmp", LF.UserInst);
4729 // Update the user. ICmpZero is handled specially here (for now) because
4730 // Expand may have updated one of the operands of the icmp already, and
4731 // its new value may happen to be equal to LF.OperandValToReplace, in
4732 // which case doing replaceUsesOfWith leads to replacing both operands
4733 // with the same value. TODO: Reorganize this.
4734 if (Uses[LF.LUIdx].Kind == LSRUse::ICmpZero)
4735 LF.UserInst->setOperand(0, FullV);
4737 LF.UserInst->replaceUsesOfWith(LF.OperandValToReplace, FullV);
4740 DeadInsts.emplace_back(LF.OperandValToReplace);
4743 /// ImplementSolution - Rewrite all the fixup locations with new values,
4744 /// following the chosen solution.
4746 LSRInstance::ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
4748 // Keep track of instructions we may have made dead, so that
4749 // we can remove them after we are done working.
4750 SmallVector<WeakVH, 16> DeadInsts;
4752 SCEVExpander Rewriter(SE, L->getHeader()->getModule()->getDataLayout(),
4755 Rewriter.setDebugType(DEBUG_TYPE);
4757 Rewriter.disableCanonicalMode();
4758 Rewriter.enableLSRMode();
4759 Rewriter.setIVIncInsertPos(L, IVIncInsertPos);
4761 // Mark phi nodes that terminate chains so the expander tries to reuse them.
4762 for (const IVChain &Chain : IVChainVec) {
4763 if (PHINode *PN = dyn_cast<PHINode>(Chain.tailUserInst()))
4764 Rewriter.setChainedPhi(PN);
4767 // Expand the new value definitions and update the users.
4768 for (const LSRFixup &Fixup : Fixups) {
4769 Rewrite(Fixup, *Solution[Fixup.LUIdx], Rewriter, DeadInsts, P);
4774 for (const IVChain &Chain : IVChainVec) {
4775 GenerateIVChain(Chain, Rewriter, DeadInsts);
4778 // Clean up after ourselves. This must be done before deleting any
4782 Changed |= DeleteTriviallyDeadInstructions(DeadInsts);
4785 LSRInstance::LSRInstance(Loop *L, Pass *P)
4786 : IU(P->getAnalysis<IVUsers>()), SE(P->getAnalysis<ScalarEvolution>()),
4787 DT(P->getAnalysis<DominatorTreeWrapperPass>().getDomTree()),
4788 LI(P->getAnalysis<LoopInfoWrapperPass>().getLoopInfo()),
4789 TTI(P->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
4790 *L->getHeader()->getParent())),
4791 L(L), Changed(false), IVIncInsertPos(nullptr) {
4792 // If LoopSimplify form is not available, stay out of trouble.
4793 if (!L->isLoopSimplifyForm())
4796 // If there's no interesting work to be done, bail early.
4797 if (IU.empty()) return;
4799 // If there's too much analysis to be done, bail early. We won't be able to
4800 // model the problem anyway.
4801 unsigned NumUsers = 0;
4802 for (const IVStrideUse &U : IU) {
4803 if (++NumUsers > MaxIVUsers) {
4805 DEBUG(dbgs() << "LSR skipping loop, too many IV Users in " << U << "\n");
4811 // All dominating loops must have preheaders, or SCEVExpander may not be able
4812 // to materialize an AddRecExpr whose Start is an outer AddRecExpr.
4814 // IVUsers analysis should only create users that are dominated by simple loop
4815 // headers. Since this loop should dominate all of its users, its user list
4816 // should be empty if this loop itself is not within a simple loop nest.
4817 for (DomTreeNode *Rung = DT.getNode(L->getLoopPreheader());
4818 Rung; Rung = Rung->getIDom()) {
4819 BasicBlock *BB = Rung->getBlock();
4820 const Loop *DomLoop = LI.getLoopFor(BB);
4821 if (DomLoop && DomLoop->getHeader() == BB) {
4822 assert(DomLoop->getLoopPreheader() && "LSR needs a simplified loop nest");
4827 DEBUG(dbgs() << "\nLSR on loop ";
4828 L->getHeader()->printAsOperand(dbgs(), /*PrintType=*/false);
4831 // First, perform some low-level loop optimizations.
4833 OptimizeLoopTermCond();
4835 // If loop preparation eliminates all interesting IV users, bail.
4836 if (IU.empty()) return;
4838 // Skip nested loops until we can model them better with formulae.
4840 DEBUG(dbgs() << "LSR skipping outer loop " << *L << "\n");
4844 // Start collecting data and preparing for the solver.
4846 CollectInterestingTypesAndFactors();
4847 CollectFixupsAndInitialFormulae();
4848 CollectLoopInvariantFixupsAndFormulae();
4850 assert(!Uses.empty() && "IVUsers reported at least one use");
4851 DEBUG(dbgs() << "LSR found " << Uses.size() << " uses:\n";
4852 print_uses(dbgs()));
4854 // Now use the reuse data to generate a bunch of interesting ways
4855 // to formulate the values needed for the uses.
4856 GenerateAllReuseFormulae();
4858 FilterOutUndesirableDedicatedRegisters();
4859 NarrowSearchSpaceUsingHeuristics();
4861 SmallVector<const Formula *, 8> Solution;
4864 // Release memory that is no longer needed.
4869 if (Solution.empty())
4873 // Formulae should be legal.
4874 for (const LSRUse &LU : Uses) {
4875 for (const Formula &F : LU.Formulae)
4876 assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
4877 F) && "Illegal formula generated!");
4881 // Now that we've decided what we want, make it so.
4882 ImplementSolution(Solution, P);
4885 void LSRInstance::print_factors_and_types(raw_ostream &OS) const {
4886 if (Factors.empty() && Types.empty()) return;
4888 OS << "LSR has identified the following interesting factors and types: ";
4891 for (int64_t Factor : Factors) {
4892 if (!First) OS << ", ";
4894 OS << '*' << Factor;
4897 for (Type *Ty : Types) {
4898 if (!First) OS << ", ";
4900 OS << '(' << *Ty << ')';
4905 void LSRInstance::print_fixups(raw_ostream &OS) const {
4906 OS << "LSR is examining the following fixup sites:\n";
4907 for (const LSRFixup &LF : Fixups) {
4914 void LSRInstance::print_uses(raw_ostream &OS) const {
4915 OS << "LSR is examining the following uses:\n";
4916 for (const LSRUse &LU : Uses) {
4920 for (const Formula &F : LU.Formulae) {
4928 void LSRInstance::print(raw_ostream &OS) const {
4929 print_factors_and_types(OS);
4934 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4935 void LSRInstance::dump() const {
4936 print(errs()); errs() << '\n';
4942 class LoopStrengthReduce : public LoopPass {
4944 static char ID; // Pass ID, replacement for typeid
4945 LoopStrengthReduce();
4948 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
4949 void getAnalysisUsage(AnalysisUsage &AU) const override;
4954 char LoopStrengthReduce::ID = 0;
4955 INITIALIZE_PASS_BEGIN(LoopStrengthReduce, "loop-reduce",
4956 "Loop Strength Reduction", false, false)
4957 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
4958 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
4959 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
4960 INITIALIZE_PASS_DEPENDENCY(IVUsers)
4961 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
4962 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
4963 INITIALIZE_PASS_END(LoopStrengthReduce, "loop-reduce",
4964 "Loop Strength Reduction", false, false)
4967 Pass *llvm::createLoopStrengthReducePass() {
4968 return new LoopStrengthReduce();
4971 LoopStrengthReduce::LoopStrengthReduce() : LoopPass(ID) {
4972 initializeLoopStrengthReducePass(*PassRegistry::getPassRegistry());
4975 void LoopStrengthReduce::getAnalysisUsage(AnalysisUsage &AU) const {
4976 // We split critical edges, so we change the CFG. However, we do update
4977 // many analyses if they are around.
4978 AU.addPreservedID(LoopSimplifyID);
4980 AU.addRequired<LoopInfoWrapperPass>();
4981 AU.addPreserved<LoopInfoWrapperPass>();
4982 AU.addRequiredID(LoopSimplifyID);
4983 AU.addRequired<DominatorTreeWrapperPass>();
4984 AU.addPreserved<DominatorTreeWrapperPass>();
4985 AU.addRequired<ScalarEvolution>();
4986 AU.addPreserved<ScalarEvolution>();
4987 // Requiring LoopSimplify a second time here prevents IVUsers from running
4988 // twice, since LoopSimplify was invalidated by running ScalarEvolution.
4989 AU.addRequiredID(LoopSimplifyID);
4990 AU.addRequired<IVUsers>();
4991 AU.addPreserved<IVUsers>();
4992 AU.addRequired<TargetTransformInfoWrapperPass>();
4995 bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager & /*LPM*/) {
4996 if (skipOptnoneFunction(L))
4999 bool Changed = false;
5001 // Run the main LSR transformation.
5002 Changed |= LSRInstance(L, this).getChanged();
5004 // Remove any extra phis created by processing inner loops.
5005 Changed |= DeleteDeadPHIs(L->getHeader());
5006 if (EnablePhiElim && L->isLoopSimplifyForm()) {
5007 SmallVector<WeakVH, 16> DeadInsts;
5008 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
5009 SCEVExpander Rewriter(getAnalysis<ScalarEvolution>(), DL, "lsr");
5011 Rewriter.setDebugType(DEBUG_TYPE);
5013 unsigned numFolded = Rewriter.replaceCongruentIVs(
5014 L, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(), DeadInsts,
5015 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
5016 *L->getHeader()->getParent()));
5019 DeleteTriviallyDeadInstructions(DeadInsts);
5020 DeleteDeadPHIs(L->getHeader());