1 //===- LoopStrengthReduce.cpp - Strength Reduce IVs in Loops --------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This transformation analyzes and transforms the induction variables (and
10 // computations derived from them) into forms suitable for efficient execution
13 // This pass performs a strength reduction on array references inside loops that
14 // have as one or more of their components the loop induction variable, it
15 // rewrites expressions to take advantage of scaled-index addressing modes
16 // available on the target, and it performs a variety of other optimizations
17 // related to loop induction variables.
19 // Terminology note: this code has a lot of handling for "post-increment" or
20 // "post-inc" users. This is not talking about post-increment addressing modes;
21 // it is instead talking about code like this:
23 // %i = phi [ 0, %entry ], [ %i.next, %latch ]
25 // %i.next = add %i, 1
26 // %c = icmp eq %i.next, %n
28 // The SCEV for %i is {0,+,1}<%L>. The SCEV for %i.next is {1,+,1}<%L>, however
29 // it's useful to think about these as the same register, with some uses using
30 // the value of the register before the add and some using it after. In this
31 // example, the icmp is a post-increment user, since it uses %i.next, which is
32 // the value of the induction variable after the increment. The other common
33 // case of post-increment users is users outside the loop.
35 // TODO: More sophistication in the way Formulae are generated and filtered.
37 // TODO: Handle multiple loops at a time.
39 // TODO: Should the addressing mode BaseGV be changed to a ConstantExpr instead
42 // TODO: When truncation is free, truncate ICmp users' operands to make it a
43 // smaller encoding (on x86 at least).
45 // TODO: When a negated register is used by an add (such as in a list of
46 // multiple base registers, or as the increment expression in an addrec),
47 // we may not actually need both reg and (-1 * reg) in registers; the
48 // negation can be implemented by using a sub instead of an add. The
49 // lack of support for taking this into consideration when making
50 // register pressure decisions is partly worked around by the "Special"
53 //===----------------------------------------------------------------------===//
55 #include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
56 #include "llvm/ADT/APInt.h"
57 #include "llvm/ADT/DenseMap.h"
58 #include "llvm/ADT/DenseSet.h"
59 #include "llvm/ADT/Hashing.h"
60 #include "llvm/ADT/PointerIntPair.h"
61 #include "llvm/ADT/STLExtras.h"
62 #include "llvm/ADT/SetVector.h"
63 #include "llvm/ADT/SmallBitVector.h"
64 #include "llvm/ADT/SmallPtrSet.h"
65 #include "llvm/ADT/SmallSet.h"
66 #include "llvm/ADT/SmallVector.h"
67 #include "llvm/ADT/iterator_range.h"
68 #include "llvm/Analysis/AssumptionCache.h"
69 #include "llvm/Analysis/IVUsers.h"
70 #include "llvm/Analysis/LoopAnalysisManager.h"
71 #include "llvm/Analysis/LoopInfo.h"
72 #include "llvm/Analysis/LoopPass.h"
73 #include "llvm/Analysis/MemorySSA.h"
74 #include "llvm/Analysis/MemorySSAUpdater.h"
75 #include "llvm/Analysis/ScalarEvolution.h"
76 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
77 #include "llvm/Analysis/ScalarEvolutionNormalization.h"
78 #include "llvm/Analysis/TargetLibraryInfo.h"
79 #include "llvm/Analysis/TargetTransformInfo.h"
80 #include "llvm/Analysis/ValueTracking.h"
81 #include "llvm/Config/llvm-config.h"
82 #include "llvm/IR/BasicBlock.h"
83 #include "llvm/IR/Constant.h"
84 #include "llvm/IR/Constants.h"
85 #include "llvm/IR/DebugInfoMetadata.h"
86 #include "llvm/IR/DerivedTypes.h"
87 #include "llvm/IR/Dominators.h"
88 #include "llvm/IR/GlobalValue.h"
89 #include "llvm/IR/IRBuilder.h"
90 #include "llvm/IR/InstrTypes.h"
91 #include "llvm/IR/Instruction.h"
92 #include "llvm/IR/Instructions.h"
93 #include "llvm/IR/IntrinsicInst.h"
94 #include "llvm/IR/Intrinsics.h"
95 #include "llvm/IR/Module.h"
96 #include "llvm/IR/OperandTraits.h"
97 #include "llvm/IR/Operator.h"
98 #include "llvm/IR/PassManager.h"
99 #include "llvm/IR/Type.h"
100 #include "llvm/IR/Use.h"
101 #include "llvm/IR/User.h"
102 #include "llvm/IR/Value.h"
103 #include "llvm/IR/ValueHandle.h"
104 #include "llvm/InitializePasses.h"
105 #include "llvm/Pass.h"
106 #include "llvm/Support/Casting.h"
107 #include "llvm/Support/CommandLine.h"
108 #include "llvm/Support/Compiler.h"
109 #include "llvm/Support/Debug.h"
110 #include "llvm/Support/ErrorHandling.h"
111 #include "llvm/Support/MathExtras.h"
112 #include "llvm/Support/raw_ostream.h"
113 #include "llvm/Transforms/Scalar.h"
114 #include "llvm/Transforms/Utils.h"
115 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
116 #include "llvm/Transforms/Utils/Local.h"
117 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
129 using namespace llvm
;
131 #define DEBUG_TYPE "loop-reduce"
133 /// MaxIVUsers is an arbitrary threshold that provides an early opportunity for
134 /// bail out. This threshold is far beyond the number of users that LSR can
135 /// conceivably solve, so it should not affect generated code, but catches the
136 /// worst cases before LSR burns too much compile time and stack space.
137 static const unsigned MaxIVUsers
= 200;
139 // Temporary flag to cleanup congruent phis after LSR phi expansion.
140 // It's currently disabled until we can determine whether it's truly useful or
141 // not. The flag should be removed after the v3.0 release.
142 // This is now needed for ivchains.
143 static cl::opt
<bool> EnablePhiElim(
144 "enable-lsr-phielim", cl::Hidden
, cl::init(true),
145 cl::desc("Enable LSR phi elimination"));
147 // The flag adds instruction count to solutions cost comparision.
148 static cl::opt
<bool> InsnsCost(
149 "lsr-insns-cost", cl::Hidden
, cl::init(true),
150 cl::desc("Add instruction count to a LSR cost model"));
152 // Flag to choose how to narrow complex lsr solution
153 static cl::opt
<bool> LSRExpNarrow(
154 "lsr-exp-narrow", cl::Hidden
, cl::init(false),
155 cl::desc("Narrow LSR complex solution using"
156 " expectation of registers number"));
158 // Flag to narrow search space by filtering non-optimal formulae with
159 // the same ScaledReg and Scale.
160 static cl::opt
<bool> FilterSameScaledReg(
161 "lsr-filter-same-scaled-reg", cl::Hidden
, cl::init(true),
162 cl::desc("Narrow LSR search space by filtering non-optimal formulae"
163 " with the same ScaledReg and Scale"));
165 static cl::opt
<TTI::AddressingModeKind
> PreferredAddresingMode(
166 "lsr-preferred-addressing-mode", cl::Hidden
, cl::init(TTI::AMK_None
),
167 cl::desc("A flag that overrides the target's preferred addressing mode."),
168 cl::values(clEnumValN(TTI::AMK_None
,
170 "Don't prefer any addressing mode"),
171 clEnumValN(TTI::AMK_PreIndexed
,
173 "Prefer pre-indexed addressing mode"),
174 clEnumValN(TTI::AMK_PostIndexed
,
176 "Prefer post-indexed addressing mode")));
178 static cl::opt
<unsigned> ComplexityLimit(
179 "lsr-complexity-limit", cl::Hidden
,
180 cl::init(std::numeric_limits
<uint16_t>::max()),
181 cl::desc("LSR search space complexity limit"));
183 static cl::opt
<unsigned> SetupCostDepthLimit(
184 "lsr-setupcost-depth-limit", cl::Hidden
, cl::init(7),
185 cl::desc("The limit on recursion depth for LSRs setup cost"));
188 // Stress test IV chain generation.
189 static cl::opt
<bool> StressIVChain(
190 "stress-ivchain", cl::Hidden
, cl::init(false),
191 cl::desc("Stress test LSR IV chains"));
193 static bool StressIVChain
= false;
199 /// Used in situations where the accessed memory type is unknown.
200 static const unsigned UnknownAddressSpace
=
201 std::numeric_limits
<unsigned>::max();
203 Type
*MemTy
= nullptr;
204 unsigned AddrSpace
= UnknownAddressSpace
;
206 MemAccessTy() = default;
207 MemAccessTy(Type
*Ty
, unsigned AS
) : MemTy(Ty
), AddrSpace(AS
) {}
209 bool operator==(MemAccessTy Other
) const {
210 return MemTy
== Other
.MemTy
&& AddrSpace
== Other
.AddrSpace
;
213 bool operator!=(MemAccessTy Other
) const { return !(*this == Other
); }
215 static MemAccessTy
getUnknown(LLVMContext
&Ctx
,
216 unsigned AS
= UnknownAddressSpace
) {
217 return MemAccessTy(Type::getVoidTy(Ctx
), AS
);
220 Type
*getType() { return MemTy
; }
223 /// This class holds data which is used to order reuse candidates.
226 /// This represents the set of LSRUse indices which reference
227 /// a particular register.
228 SmallBitVector UsedByIndices
;
230 void print(raw_ostream
&OS
) const;
234 } // end anonymous namespace
236 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
237 void RegSortData::print(raw_ostream
&OS
) const {
238 OS
<< "[NumUses=" << UsedByIndices
.count() << ']';
241 LLVM_DUMP_METHOD
void RegSortData::dump() const {
242 print(errs()); errs() << '\n';
248 /// Map register candidates to information about how they are used.
249 class RegUseTracker
{
250 using RegUsesTy
= DenseMap
<const SCEV
*, RegSortData
>;
252 RegUsesTy RegUsesMap
;
253 SmallVector
<const SCEV
*, 16> RegSequence
;
256 void countRegister(const SCEV
*Reg
, size_t LUIdx
);
257 void dropRegister(const SCEV
*Reg
, size_t LUIdx
);
258 void swapAndDropUse(size_t LUIdx
, size_t LastLUIdx
);
260 bool isRegUsedByUsesOtherThan(const SCEV
*Reg
, size_t LUIdx
) const;
262 const SmallBitVector
&getUsedByIndices(const SCEV
*Reg
) const;
266 using iterator
= SmallVectorImpl
<const SCEV
*>::iterator
;
267 using const_iterator
= SmallVectorImpl
<const SCEV
*>::const_iterator
;
269 iterator
begin() { return RegSequence
.begin(); }
270 iterator
end() { return RegSequence
.end(); }
271 const_iterator
begin() const { return RegSequence
.begin(); }
272 const_iterator
end() const { return RegSequence
.end(); }
275 } // end anonymous namespace
278 RegUseTracker::countRegister(const SCEV
*Reg
, size_t LUIdx
) {
279 std::pair
<RegUsesTy::iterator
, bool> Pair
=
280 RegUsesMap
.insert(std::make_pair(Reg
, RegSortData()));
281 RegSortData
&RSD
= Pair
.first
->second
;
283 RegSequence
.push_back(Reg
);
284 RSD
.UsedByIndices
.resize(std::max(RSD
.UsedByIndices
.size(), LUIdx
+ 1));
285 RSD
.UsedByIndices
.set(LUIdx
);
289 RegUseTracker::dropRegister(const SCEV
*Reg
, size_t LUIdx
) {
290 RegUsesTy::iterator It
= RegUsesMap
.find(Reg
);
291 assert(It
!= RegUsesMap
.end());
292 RegSortData
&RSD
= It
->second
;
293 assert(RSD
.UsedByIndices
.size() > LUIdx
);
294 RSD
.UsedByIndices
.reset(LUIdx
);
298 RegUseTracker::swapAndDropUse(size_t LUIdx
, size_t LastLUIdx
) {
299 assert(LUIdx
<= LastLUIdx
);
301 // Update RegUses. The data structure is not optimized for this purpose;
302 // we must iterate through it and update each of the bit vectors.
303 for (auto &Pair
: RegUsesMap
) {
304 SmallBitVector
&UsedByIndices
= Pair
.second
.UsedByIndices
;
305 if (LUIdx
< UsedByIndices
.size())
306 UsedByIndices
[LUIdx
] =
307 LastLUIdx
< UsedByIndices
.size() ? UsedByIndices
[LastLUIdx
] : false;
308 UsedByIndices
.resize(std::min(UsedByIndices
.size(), LastLUIdx
));
313 RegUseTracker::isRegUsedByUsesOtherThan(const SCEV
*Reg
, size_t LUIdx
) const {
314 RegUsesTy::const_iterator I
= RegUsesMap
.find(Reg
);
315 if (I
== RegUsesMap
.end())
317 const SmallBitVector
&UsedByIndices
= I
->second
.UsedByIndices
;
318 int i
= UsedByIndices
.find_first();
319 if (i
== -1) return false;
320 if ((size_t)i
!= LUIdx
) return true;
321 return UsedByIndices
.find_next(i
) != -1;
324 const SmallBitVector
&RegUseTracker::getUsedByIndices(const SCEV
*Reg
) const {
325 RegUsesTy::const_iterator I
= RegUsesMap
.find(Reg
);
326 assert(I
!= RegUsesMap
.end() && "Unknown register!");
327 return I
->second
.UsedByIndices
;
330 void RegUseTracker::clear() {
337 /// This class holds information that describes a formula for computing
338 /// satisfying a use. It may include broken-out immediates and scaled registers.
340 /// Global base address used for complex addressing.
341 GlobalValue
*BaseGV
= nullptr;
343 /// Base offset for complex addressing.
344 int64_t BaseOffset
= 0;
346 /// Whether any complex addressing has a base register.
347 bool HasBaseReg
= false;
349 /// The scale of any complex addressing.
352 /// The list of "base" registers for this use. When this is non-empty. The
353 /// canonical representation of a formula is
354 /// 1. BaseRegs.size > 1 implies ScaledReg != NULL and
355 /// 2. ScaledReg != NULL implies Scale != 1 || !BaseRegs.empty().
356 /// 3. The reg containing recurrent expr related with currect loop in the
357 /// formula should be put in the ScaledReg.
358 /// #1 enforces that the scaled register is always used when at least two
359 /// registers are needed by the formula: e.g., reg1 + reg2 is reg1 + 1 * reg2.
360 /// #2 enforces that 1 * reg is reg.
361 /// #3 ensures invariant regs with respect to current loop can be combined
362 /// together in LSR codegen.
363 /// This invariant can be temporarily broken while building a formula.
364 /// However, every formula inserted into the LSRInstance must be in canonical
366 SmallVector
<const SCEV
*, 4> BaseRegs
;
368 /// The 'scaled' register for this use. This should be non-null when Scale is
370 const SCEV
*ScaledReg
= nullptr;
372 /// An additional constant offset which added near the use. This requires a
373 /// temporary register, but the offset itself can live in an add immediate
374 /// field rather than a register.
375 int64_t UnfoldedOffset
= 0;
379 void initialMatch(const SCEV
*S
, Loop
*L
, ScalarEvolution
&SE
);
381 bool isCanonical(const Loop
&L
) const;
383 void canonicalize(const Loop
&L
);
387 bool hasZeroEnd() const;
389 size_t getNumRegs() const;
390 Type
*getType() const;
392 void deleteBaseReg(const SCEV
*&S
);
394 bool referencesReg(const SCEV
*S
) const;
395 bool hasRegsUsedByUsesOtherThan(size_t LUIdx
,
396 const RegUseTracker
&RegUses
) const;
398 void print(raw_ostream
&OS
) const;
402 } // end anonymous namespace
404 /// Recursion helper for initialMatch.
405 static void DoInitialMatch(const SCEV
*S
, Loop
*L
,
406 SmallVectorImpl
<const SCEV
*> &Good
,
407 SmallVectorImpl
<const SCEV
*> &Bad
,
408 ScalarEvolution
&SE
) {
409 // Collect expressions which properly dominate the loop header.
410 if (SE
.properlyDominates(S
, L
->getHeader())) {
415 // Look at add operands.
416 if (const SCEVAddExpr
*Add
= dyn_cast
<SCEVAddExpr
>(S
)) {
417 for (const SCEV
*S
: Add
->operands())
418 DoInitialMatch(S
, L
, Good
, Bad
, SE
);
422 // Look at addrec operands.
423 if (const SCEVAddRecExpr
*AR
= dyn_cast
<SCEVAddRecExpr
>(S
))
424 if (!AR
->getStart()->isZero() && AR
->isAffine()) {
425 DoInitialMatch(AR
->getStart(), L
, Good
, Bad
, SE
);
426 DoInitialMatch(SE
.getAddRecExpr(SE
.getConstant(AR
->getType(), 0),
427 AR
->getStepRecurrence(SE
),
428 // FIXME: AR->getNoWrapFlags()
429 AR
->getLoop(), SCEV::FlagAnyWrap
),
434 // Handle a multiplication by -1 (negation) if it didn't fold.
435 if (const SCEVMulExpr
*Mul
= dyn_cast
<SCEVMulExpr
>(S
))
436 if (Mul
->getOperand(0)->isAllOnesValue()) {
437 SmallVector
<const SCEV
*, 4> Ops(drop_begin(Mul
->operands()));
438 const SCEV
*NewMul
= SE
.getMulExpr(Ops
);
440 SmallVector
<const SCEV
*, 4> MyGood
;
441 SmallVector
<const SCEV
*, 4> MyBad
;
442 DoInitialMatch(NewMul
, L
, MyGood
, MyBad
, SE
);
443 const SCEV
*NegOne
= SE
.getSCEV(ConstantInt::getAllOnesValue(
444 SE
.getEffectiveSCEVType(NewMul
->getType())));
445 for (const SCEV
*S
: MyGood
)
446 Good
.push_back(SE
.getMulExpr(NegOne
, S
));
447 for (const SCEV
*S
: MyBad
)
448 Bad
.push_back(SE
.getMulExpr(NegOne
, S
));
452 // Ok, we can't do anything interesting. Just stuff the whole thing into a
453 // register and hope for the best.
457 /// Incorporate loop-variant parts of S into this Formula, attempting to keep
458 /// all loop-invariant and loop-computable values in a single base register.
459 void Formula::initialMatch(const SCEV
*S
, Loop
*L
, ScalarEvolution
&SE
) {
460 SmallVector
<const SCEV
*, 4> Good
;
461 SmallVector
<const SCEV
*, 4> Bad
;
462 DoInitialMatch(S
, L
, Good
, Bad
, SE
);
464 const SCEV
*Sum
= SE
.getAddExpr(Good
);
466 BaseRegs
.push_back(Sum
);
470 const SCEV
*Sum
= SE
.getAddExpr(Bad
);
472 BaseRegs
.push_back(Sum
);
478 /// Check whether or not this formula satisfies the canonical
480 /// \see Formula::BaseRegs.
481 bool Formula::isCanonical(const Loop
&L
) const {
483 return BaseRegs
.size() <= 1;
488 if (Scale
== 1 && BaseRegs
.empty())
491 const SCEVAddRecExpr
*SAR
= dyn_cast
<const SCEVAddRecExpr
>(ScaledReg
);
492 if (SAR
&& SAR
->getLoop() == &L
)
495 // If ScaledReg is not a recurrent expr, or it is but its loop is not current
496 // loop, meanwhile BaseRegs contains a recurrent expr reg related with current
497 // loop, we want to swap the reg in BaseRegs with ScaledReg.
498 auto I
= find_if(BaseRegs
, [&](const SCEV
*S
) {
499 return isa
<const SCEVAddRecExpr
>(S
) &&
500 (cast
<SCEVAddRecExpr
>(S
)->getLoop() == &L
);
502 return I
== BaseRegs
.end();
505 /// Helper method to morph a formula into its canonical representation.
506 /// \see Formula::BaseRegs.
507 /// Every formula having more than one base register, must use the ScaledReg
508 /// field. Otherwise, we would have to do special cases everywhere in LSR
509 /// to treat reg1 + reg2 + ... the same way as reg1 + 1*reg2 + ...
510 /// On the other hand, 1*reg should be canonicalized into reg.
511 void Formula::canonicalize(const Loop
&L
) {
515 if (BaseRegs
.empty()) {
516 // No base reg? Use scale reg with scale = 1 as such.
517 assert(ScaledReg
&& "Expected 1*reg => reg");
518 assert(Scale
== 1 && "Expected 1*reg => reg");
519 BaseRegs
.push_back(ScaledReg
);
525 // Keep the invariant sum in BaseRegs and one of the variant sum in ScaledReg.
527 ScaledReg
= BaseRegs
.pop_back_val();
531 // If ScaledReg is an invariant with respect to L, find the reg from
532 // BaseRegs containing the recurrent expr related with Loop L. Swap the
533 // reg with ScaledReg.
534 const SCEVAddRecExpr
*SAR
= dyn_cast
<const SCEVAddRecExpr
>(ScaledReg
);
535 if (!SAR
|| SAR
->getLoop() != &L
) {
536 auto I
= find_if(BaseRegs
, [&](const SCEV
*S
) {
537 return isa
<const SCEVAddRecExpr
>(S
) &&
538 (cast
<SCEVAddRecExpr
>(S
)->getLoop() == &L
);
540 if (I
!= BaseRegs
.end())
541 std::swap(ScaledReg
, *I
);
543 assert(isCanonical(L
) && "Failed to canonicalize?");
546 /// Get rid of the scale in the formula.
547 /// In other words, this method morphes reg1 + 1*reg2 into reg1 + reg2.
548 /// \return true if it was possible to get rid of the scale, false otherwise.
549 /// \note After this operation the formula may not be in the canonical form.
550 bool Formula::unscale() {
554 BaseRegs
.push_back(ScaledReg
);
559 bool Formula::hasZeroEnd() const {
560 if (UnfoldedOffset
|| BaseOffset
)
562 if (BaseRegs
.size() != 1 || ScaledReg
)
567 /// Return the total number of register operands used by this formula. This does
568 /// not include register uses implied by non-constant addrec strides.
569 size_t Formula::getNumRegs() const {
570 return !!ScaledReg
+ BaseRegs
.size();
573 /// Return the type of this formula, if it has one, or null otherwise. This type
574 /// is meaningless except for the bit size.
575 Type
*Formula::getType() const {
576 return !BaseRegs
.empty() ? BaseRegs
.front()->getType() :
577 ScaledReg
? ScaledReg
->getType() :
578 BaseGV
? BaseGV
->getType() :
582 /// Delete the given base reg from the BaseRegs list.
583 void Formula::deleteBaseReg(const SCEV
*&S
) {
584 if (&S
!= &BaseRegs
.back())
585 std::swap(S
, BaseRegs
.back());
589 /// Test if this formula references the given register.
590 bool Formula::referencesReg(const SCEV
*S
) const {
591 return S
== ScaledReg
|| is_contained(BaseRegs
, S
);
594 /// Test whether this formula uses registers which are used by uses other than
595 /// the use with the given index.
596 bool Formula::hasRegsUsedByUsesOtherThan(size_t LUIdx
,
597 const RegUseTracker
&RegUses
) const {
599 if (RegUses
.isRegUsedByUsesOtherThan(ScaledReg
, LUIdx
))
601 for (const SCEV
*BaseReg
: BaseRegs
)
602 if (RegUses
.isRegUsedByUsesOtherThan(BaseReg
, LUIdx
))
607 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
608 void Formula::print(raw_ostream
&OS
) const {
611 if (!First
) OS
<< " + "; else First
= false;
612 BaseGV
->printAsOperand(OS
, /*PrintType=*/false);
614 if (BaseOffset
!= 0) {
615 if (!First
) OS
<< " + "; else First
= false;
618 for (const SCEV
*BaseReg
: BaseRegs
) {
619 if (!First
) OS
<< " + "; else First
= false;
620 OS
<< "reg(" << *BaseReg
<< ')';
622 if (HasBaseReg
&& BaseRegs
.empty()) {
623 if (!First
) OS
<< " + "; else First
= false;
624 OS
<< "**error: HasBaseReg**";
625 } else if (!HasBaseReg
&& !BaseRegs
.empty()) {
626 if (!First
) OS
<< " + "; else First
= false;
627 OS
<< "**error: !HasBaseReg**";
630 if (!First
) OS
<< " + "; else First
= false;
631 OS
<< Scale
<< "*reg(";
638 if (UnfoldedOffset
!= 0) {
639 if (!First
) OS
<< " + ";
640 OS
<< "imm(" << UnfoldedOffset
<< ')';
644 LLVM_DUMP_METHOD
void Formula::dump() const {
645 print(errs()); errs() << '\n';
649 /// Return true if the given addrec can be sign-extended without changing its
651 static bool isAddRecSExtable(const SCEVAddRecExpr
*AR
, ScalarEvolution
&SE
) {
653 IntegerType::get(SE
.getContext(), SE
.getTypeSizeInBits(AR
->getType()) + 1);
654 return isa
<SCEVAddRecExpr
>(SE
.getSignExtendExpr(AR
, WideTy
));
657 /// Return true if the given add can be sign-extended without changing its
659 static bool isAddSExtable(const SCEVAddExpr
*A
, ScalarEvolution
&SE
) {
661 IntegerType::get(SE
.getContext(), SE
.getTypeSizeInBits(A
->getType()) + 1);
662 return isa
<SCEVAddExpr
>(SE
.getSignExtendExpr(A
, WideTy
));
665 /// Return true if the given mul can be sign-extended without changing its
667 static bool isMulSExtable(const SCEVMulExpr
*M
, ScalarEvolution
&SE
) {
669 IntegerType::get(SE
.getContext(),
670 SE
.getTypeSizeInBits(M
->getType()) * M
->getNumOperands());
671 return isa
<SCEVMulExpr
>(SE
.getSignExtendExpr(M
, WideTy
));
674 /// Return an expression for LHS /s RHS, if it can be determined and if the
675 /// remainder is known to be zero, or null otherwise. If IgnoreSignificantBits
676 /// is true, expressions like (X * Y) /s Y are simplified to X, ignoring that
677 /// the multiplication may overflow, which is useful when the result will be
678 /// used in a context where the most significant bits are ignored.
679 static const SCEV
*getExactSDiv(const SCEV
*LHS
, const SCEV
*RHS
,
681 bool IgnoreSignificantBits
= false) {
682 // Handle the trivial case, which works for any SCEV type.
684 return SE
.getConstant(LHS
->getType(), 1);
686 // Handle a few RHS special cases.
687 const SCEVConstant
*RC
= dyn_cast
<SCEVConstant
>(RHS
);
689 const APInt
&RA
= RC
->getAPInt();
690 // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do
692 if (RA
.isAllOnesValue()) {
693 if (LHS
->getType()->isPointerTy())
695 return SE
.getMulExpr(LHS
, RC
);
697 // Handle x /s 1 as x.
702 // Check for a division of a constant by a constant.
703 if (const SCEVConstant
*C
= dyn_cast
<SCEVConstant
>(LHS
)) {
706 const APInt
&LA
= C
->getAPInt();
707 const APInt
&RA
= RC
->getAPInt();
708 if (LA
.srem(RA
) != 0)
710 return SE
.getConstant(LA
.sdiv(RA
));
713 // Distribute the sdiv over addrec operands, if the addrec doesn't overflow.
714 if (const SCEVAddRecExpr
*AR
= dyn_cast
<SCEVAddRecExpr
>(LHS
)) {
715 if ((IgnoreSignificantBits
|| isAddRecSExtable(AR
, SE
)) && AR
->isAffine()) {
716 const SCEV
*Step
= getExactSDiv(AR
->getStepRecurrence(SE
), RHS
, SE
,
717 IgnoreSignificantBits
);
718 if (!Step
) return nullptr;
719 const SCEV
*Start
= getExactSDiv(AR
->getStart(), RHS
, SE
,
720 IgnoreSignificantBits
);
721 if (!Start
) return nullptr;
722 // FlagNW is independent of the start value, step direction, and is
723 // preserved with smaller magnitude steps.
724 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
725 return SE
.getAddRecExpr(Start
, Step
, AR
->getLoop(), SCEV::FlagAnyWrap
);
730 // Distribute the sdiv over add operands, if the add doesn't overflow.
731 if (const SCEVAddExpr
*Add
= dyn_cast
<SCEVAddExpr
>(LHS
)) {
732 if (IgnoreSignificantBits
|| isAddSExtable(Add
, SE
)) {
733 SmallVector
<const SCEV
*, 8> Ops
;
734 for (const SCEV
*S
: Add
->operands()) {
735 const SCEV
*Op
= getExactSDiv(S
, RHS
, SE
, IgnoreSignificantBits
);
736 if (!Op
) return nullptr;
739 return SE
.getAddExpr(Ops
);
744 // Check for a multiply operand that we can pull RHS out of.
745 if (const SCEVMulExpr
*Mul
= dyn_cast
<SCEVMulExpr
>(LHS
)) {
746 if (IgnoreSignificantBits
|| isMulSExtable(Mul
, SE
)) {
747 // Handle special case C1*X*Y /s C2*X*Y.
748 if (const SCEVMulExpr
*MulRHS
= dyn_cast
<SCEVMulExpr
>(RHS
)) {
749 if (IgnoreSignificantBits
|| isMulSExtable(MulRHS
, SE
)) {
750 const SCEVConstant
*LC
= dyn_cast
<SCEVConstant
>(Mul
->getOperand(0));
751 const SCEVConstant
*RC
=
752 dyn_cast
<SCEVConstant
>(MulRHS
->getOperand(0));
754 SmallVector
<const SCEV
*, 4> LOps(drop_begin(Mul
->operands()));
755 SmallVector
<const SCEV
*, 4> ROps(drop_begin(MulRHS
->operands()));
757 return getExactSDiv(LC
, RC
, SE
, IgnoreSignificantBits
);
762 SmallVector
<const SCEV
*, 4> Ops
;
764 for (const SCEV
*S
: Mul
->operands()) {
766 if (const SCEV
*Q
= getExactSDiv(S
, RHS
, SE
,
767 IgnoreSignificantBits
)) {
773 return Found
? SE
.getMulExpr(Ops
) : nullptr;
778 // Otherwise we don't know.
782 /// If S involves the addition of a constant integer value, return that integer
783 /// value, and mutate S to point to a new SCEV with that value excluded.
784 static int64_t ExtractImmediate(const SCEV
*&S
, ScalarEvolution
&SE
) {
785 if (const SCEVConstant
*C
= dyn_cast
<SCEVConstant
>(S
)) {
786 if (C
->getAPInt().getMinSignedBits() <= 64) {
787 S
= SE
.getConstant(C
->getType(), 0);
788 return C
->getValue()->getSExtValue();
790 } else if (const SCEVAddExpr
*Add
= dyn_cast
<SCEVAddExpr
>(S
)) {
791 SmallVector
<const SCEV
*, 8> NewOps(Add
->operands());
792 int64_t Result
= ExtractImmediate(NewOps
.front(), SE
);
794 S
= SE
.getAddExpr(NewOps
);
796 } else if (const SCEVAddRecExpr
*AR
= dyn_cast
<SCEVAddRecExpr
>(S
)) {
797 SmallVector
<const SCEV
*, 8> NewOps(AR
->operands());
798 int64_t Result
= ExtractImmediate(NewOps
.front(), SE
);
800 S
= SE
.getAddRecExpr(NewOps
, AR
->getLoop(),
801 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
808 /// If S involves the addition of a GlobalValue address, return that symbol, and
809 /// mutate S to point to a new SCEV with that value excluded.
810 static GlobalValue
*ExtractSymbol(const SCEV
*&S
, ScalarEvolution
&SE
) {
811 if (const SCEVUnknown
*U
= dyn_cast
<SCEVUnknown
>(S
)) {
812 if (GlobalValue
*GV
= dyn_cast
<GlobalValue
>(U
->getValue())) {
813 S
= SE
.getConstant(GV
->getType(), 0);
816 } else if (const SCEVAddExpr
*Add
= dyn_cast
<SCEVAddExpr
>(S
)) {
817 SmallVector
<const SCEV
*, 8> NewOps(Add
->operands());
818 GlobalValue
*Result
= ExtractSymbol(NewOps
.back(), SE
);
820 S
= SE
.getAddExpr(NewOps
);
822 } else if (const SCEVAddRecExpr
*AR
= dyn_cast
<SCEVAddRecExpr
>(S
)) {
823 SmallVector
<const SCEV
*, 8> NewOps(AR
->operands());
824 GlobalValue
*Result
= ExtractSymbol(NewOps
.front(), SE
);
826 S
= SE
.getAddRecExpr(NewOps
, AR
->getLoop(),
827 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
834 /// Returns true if the specified instruction is using the specified value as an
836 static bool isAddressUse(const TargetTransformInfo
&TTI
,
837 Instruction
*Inst
, Value
*OperandVal
) {
838 bool isAddress
= isa
<LoadInst
>(Inst
);
839 if (StoreInst
*SI
= dyn_cast
<StoreInst
>(Inst
)) {
840 if (SI
->getPointerOperand() == OperandVal
)
842 } else if (IntrinsicInst
*II
= dyn_cast
<IntrinsicInst
>(Inst
)) {
843 // Addressing modes can also be folded into prefetches and a variety
845 switch (II
->getIntrinsicID()) {
846 case Intrinsic::memset
:
847 case Intrinsic::prefetch
:
848 case Intrinsic::masked_load
:
849 if (II
->getArgOperand(0) == OperandVal
)
852 case Intrinsic::masked_store
:
853 if (II
->getArgOperand(1) == OperandVal
)
856 case Intrinsic::memmove
:
857 case Intrinsic::memcpy
:
858 if (II
->getArgOperand(0) == OperandVal
||
859 II
->getArgOperand(1) == OperandVal
)
863 MemIntrinsicInfo IntrInfo
;
864 if (TTI
.getTgtMemIntrinsic(II
, IntrInfo
)) {
865 if (IntrInfo
.PtrVal
== OperandVal
)
870 } else if (AtomicRMWInst
*RMW
= dyn_cast
<AtomicRMWInst
>(Inst
)) {
871 if (RMW
->getPointerOperand() == OperandVal
)
873 } else if (AtomicCmpXchgInst
*CmpX
= dyn_cast
<AtomicCmpXchgInst
>(Inst
)) {
874 if (CmpX
->getPointerOperand() == OperandVal
)
880 /// Return the type of the memory being accessed.
881 static MemAccessTy
getAccessType(const TargetTransformInfo
&TTI
,
882 Instruction
*Inst
, Value
*OperandVal
) {
883 MemAccessTy
AccessTy(Inst
->getType(), MemAccessTy::UnknownAddressSpace
);
884 if (const StoreInst
*SI
= dyn_cast
<StoreInst
>(Inst
)) {
885 AccessTy
.MemTy
= SI
->getOperand(0)->getType();
886 AccessTy
.AddrSpace
= SI
->getPointerAddressSpace();
887 } else if (const LoadInst
*LI
= dyn_cast
<LoadInst
>(Inst
)) {
888 AccessTy
.AddrSpace
= LI
->getPointerAddressSpace();
889 } else if (const AtomicRMWInst
*RMW
= dyn_cast
<AtomicRMWInst
>(Inst
)) {
890 AccessTy
.AddrSpace
= RMW
->getPointerAddressSpace();
891 } else if (const AtomicCmpXchgInst
*CmpX
= dyn_cast
<AtomicCmpXchgInst
>(Inst
)) {
892 AccessTy
.AddrSpace
= CmpX
->getPointerAddressSpace();
893 } else if (IntrinsicInst
*II
= dyn_cast
<IntrinsicInst
>(Inst
)) {
894 switch (II
->getIntrinsicID()) {
895 case Intrinsic::prefetch
:
896 case Intrinsic::memset
:
897 AccessTy
.AddrSpace
= II
->getArgOperand(0)->getType()->getPointerAddressSpace();
898 AccessTy
.MemTy
= OperandVal
->getType();
900 case Intrinsic::memmove
:
901 case Intrinsic::memcpy
:
902 AccessTy
.AddrSpace
= OperandVal
->getType()->getPointerAddressSpace();
903 AccessTy
.MemTy
= OperandVal
->getType();
905 case Intrinsic::masked_load
:
907 II
->getArgOperand(0)->getType()->getPointerAddressSpace();
909 case Intrinsic::masked_store
:
910 AccessTy
.MemTy
= II
->getOperand(0)->getType();
912 II
->getArgOperand(1)->getType()->getPointerAddressSpace();
915 MemIntrinsicInfo IntrInfo
;
916 if (TTI
.getTgtMemIntrinsic(II
, IntrInfo
) && IntrInfo
.PtrVal
) {
918 = IntrInfo
.PtrVal
->getType()->getPointerAddressSpace();
926 // All pointers have the same requirements, so canonicalize them to an
927 // arbitrary pointer type to minimize variation.
928 if (PointerType
*PTy
= dyn_cast
<PointerType
>(AccessTy
.MemTy
))
929 AccessTy
.MemTy
= PointerType::get(IntegerType::get(PTy
->getContext(), 1),
930 PTy
->getAddressSpace());
935 /// Return true if this AddRec is already a phi in its loop.
936 static bool isExistingPhi(const SCEVAddRecExpr
*AR
, ScalarEvolution
&SE
) {
937 for (PHINode
&PN
: AR
->getLoop()->getHeader()->phis()) {
938 if (SE
.isSCEVable(PN
.getType()) &&
939 (SE
.getEffectiveSCEVType(PN
.getType()) ==
940 SE
.getEffectiveSCEVType(AR
->getType())) &&
941 SE
.getSCEV(&PN
) == AR
)
947 /// Check if expanding this expression is likely to incur significant cost. This
948 /// is tricky because SCEV doesn't track which expressions are actually computed
949 /// by the current IR.
951 /// We currently allow expansion of IV increments that involve adds,
952 /// multiplication by constants, and AddRecs from existing phis.
954 /// TODO: Allow UDivExpr if we can find an existing IV increment that is an
955 /// obvious multiple of the UDivExpr.
956 static bool isHighCostExpansion(const SCEV
*S
,
957 SmallPtrSetImpl
<const SCEV
*> &Processed
,
958 ScalarEvolution
&SE
) {
959 // Zero/One operand expressions
960 switch (S
->getSCEVType()) {
965 return isHighCostExpansion(cast
<SCEVTruncateExpr
>(S
)->getOperand(),
968 return isHighCostExpansion(cast
<SCEVZeroExtendExpr
>(S
)->getOperand(),
971 return isHighCostExpansion(cast
<SCEVSignExtendExpr
>(S
)->getOperand(),
977 if (!Processed
.insert(S
).second
)
980 if (const SCEVAddExpr
*Add
= dyn_cast
<SCEVAddExpr
>(S
)) {
981 for (const SCEV
*S
: Add
->operands()) {
982 if (isHighCostExpansion(S
, Processed
, SE
))
988 if (const SCEVMulExpr
*Mul
= dyn_cast
<SCEVMulExpr
>(S
)) {
989 if (Mul
->getNumOperands() == 2) {
990 // Multiplication by a constant is ok
991 if (isa
<SCEVConstant
>(Mul
->getOperand(0)))
992 return isHighCostExpansion(Mul
->getOperand(1), Processed
, SE
);
994 // If we have the value of one operand, check if an existing
995 // multiplication already generates this expression.
996 if (const SCEVUnknown
*U
= dyn_cast
<SCEVUnknown
>(Mul
->getOperand(1))) {
997 Value
*UVal
= U
->getValue();
998 for (User
*UR
: UVal
->users()) {
999 // If U is a constant, it may be used by a ConstantExpr.
1000 Instruction
*UI
= dyn_cast
<Instruction
>(UR
);
1001 if (UI
&& UI
->getOpcode() == Instruction::Mul
&&
1002 SE
.isSCEVable(UI
->getType())) {
1003 return SE
.getSCEV(UI
) == Mul
;
1010 if (const SCEVAddRecExpr
*AR
= dyn_cast
<SCEVAddRecExpr
>(S
)) {
1011 if (isExistingPhi(AR
, SE
))
1015 // Fow now, consider any other type of expression (div/mul/min/max) high cost.
1023 } // end anonymous namespace
1025 /// Check if the addressing mode defined by \p F is completely
1026 /// folded in \p LU at isel time.
1027 /// This includes address-mode folding and special icmp tricks.
1028 /// This function returns true if \p LU can accommodate what \p F
1029 /// defines and up to 1 base + 1 scaled + offset.
1030 /// In other words, if \p F has several base registers, this function may
1031 /// still return true. Therefore, users still need to account for
1032 /// additional base registers and/or unfolded offsets to derive an
1033 /// accurate cost model.
1034 static bool isAMCompletelyFolded(const TargetTransformInfo
&TTI
,
1035 const LSRUse
&LU
, const Formula
&F
);
1037 // Get the cost of the scaling factor used in F for LU.
1038 static InstructionCost
getScalingFactorCost(const TargetTransformInfo
&TTI
,
1039 const LSRUse
&LU
, const Formula
&F
,
1044 /// This class is used to measure and compare candidate formulae.
1046 const Loop
*L
= nullptr;
1047 ScalarEvolution
*SE
= nullptr;
1048 const TargetTransformInfo
*TTI
= nullptr;
1049 TargetTransformInfo::LSRCost C
;
1050 TTI::AddressingModeKind AMK
= TTI::AMK_None
;
1054 Cost(const Loop
*L
, ScalarEvolution
&SE
, const TargetTransformInfo
&TTI
,
1055 TTI::AddressingModeKind AMK
) :
1056 L(L
), SE(&SE
), TTI(&TTI
), AMK(AMK
) {
1067 bool isLess(Cost
&Other
);
1072 // Once any of the metrics loses, they must all remain losers.
1074 return ((C
.Insns
| C
.NumRegs
| C
.AddRecCost
| C
.NumIVMuls
| C
.NumBaseAdds
1075 | C
.ImmCost
| C
.SetupCost
| C
.ScaleCost
) != ~0u)
1076 || ((C
.Insns
& C
.NumRegs
& C
.AddRecCost
& C
.NumIVMuls
& C
.NumBaseAdds
1077 & C
.ImmCost
& C
.SetupCost
& C
.ScaleCost
) == ~0u);
1082 assert(isValid() && "invalid cost");
1083 return C
.NumRegs
== ~0u;
1086 void RateFormula(const Formula
&F
,
1087 SmallPtrSetImpl
<const SCEV
*> &Regs
,
1088 const DenseSet
<const SCEV
*> &VisitedRegs
,
1090 SmallPtrSetImpl
<const SCEV
*> *LoserRegs
= nullptr);
1092 void print(raw_ostream
&OS
) const;
1096 void RateRegister(const Formula
&F
, const SCEV
*Reg
,
1097 SmallPtrSetImpl
<const SCEV
*> &Regs
);
1098 void RatePrimaryRegister(const Formula
&F
, const SCEV
*Reg
,
1099 SmallPtrSetImpl
<const SCEV
*> &Regs
,
1100 SmallPtrSetImpl
<const SCEV
*> *LoserRegs
);
1103 /// An operand value in an instruction which is to be replaced with some
1104 /// equivalent, possibly strength-reduced, replacement.
1106 /// The instruction which will be updated.
1107 Instruction
*UserInst
= nullptr;
1109 /// The operand of the instruction which will be replaced. The operand may be
1110 /// used more than once; every instance will be replaced.
1111 Value
*OperandValToReplace
= nullptr;
1113 /// If this user is to use the post-incremented value of an induction
1114 /// variable, this set is non-empty and holds the loops associated with the
1115 /// induction variable.
1116 PostIncLoopSet PostIncLoops
;
1118 /// A constant offset to be added to the LSRUse expression. This allows
1119 /// multiple fixups to share the same LSRUse with different offsets, for
1120 /// example in an unrolled loop.
1123 LSRFixup() = default;
1125 bool isUseFullyOutsideLoop(const Loop
*L
) const;
1127 void print(raw_ostream
&OS
) const;
1131 /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of sorted
1132 /// SmallVectors of const SCEV*.
1133 struct UniquifierDenseMapInfo
{
1134 static SmallVector
<const SCEV
*, 4> getEmptyKey() {
1135 SmallVector
<const SCEV
*, 4> V
;
1136 V
.push_back(reinterpret_cast<const SCEV
*>(-1));
1140 static SmallVector
<const SCEV
*, 4> getTombstoneKey() {
1141 SmallVector
<const SCEV
*, 4> V
;
1142 V
.push_back(reinterpret_cast<const SCEV
*>(-2));
1146 static unsigned getHashValue(const SmallVector
<const SCEV
*, 4> &V
) {
1147 return static_cast<unsigned>(hash_combine_range(V
.begin(), V
.end()));
1150 static bool isEqual(const SmallVector
<const SCEV
*, 4> &LHS
,
1151 const SmallVector
<const SCEV
*, 4> &RHS
) {
1156 /// This class holds the state that LSR keeps for each use in IVUsers, as well
1157 /// as uses invented by LSR itself. It includes information about what kinds of
1158 /// things can be folded into the user, information about the user itself, and
1159 /// information about how the use may be satisfied. TODO: Represent multiple
1160 /// users of the same expression in common?
1162 DenseSet
<SmallVector
<const SCEV
*, 4>, UniquifierDenseMapInfo
> Uniquifier
;
1165 /// An enum for a kind of use, indicating what types of scaled and immediate
1166 /// operands it might support.
1168 Basic
, ///< A normal use, with no folding.
1169 Special
, ///< A special case of basic, allowing -1 scales.
1170 Address
, ///< An address use; folding according to TargetLowering
1171 ICmpZero
///< An equality icmp with both operands folded into one.
1172 // TODO: Add a generic icmp too?
1175 using SCEVUseKindPair
= PointerIntPair
<const SCEV
*, 2, KindType
>;
1178 MemAccessTy AccessTy
;
1180 /// The list of operands which are to be replaced.
1181 SmallVector
<LSRFixup
, 8> Fixups
;
1183 /// Keep track of the min and max offsets of the fixups.
1184 int64_t MinOffset
= std::numeric_limits
<int64_t>::max();
1185 int64_t MaxOffset
= std::numeric_limits
<int64_t>::min();
1187 /// This records whether all of the fixups using this LSRUse are outside of
1188 /// the loop, in which case some special-case heuristics may be used.
1189 bool AllFixupsOutsideLoop
= true;
1191 /// RigidFormula is set to true to guarantee that this use will be associated
1192 /// with a single formula--the one that initially matched. Some SCEV
1193 /// expressions cannot be expanded. This allows LSR to consider the registers
1194 /// used by those expressions without the need to expand them later after
1195 /// changing the formula.
1196 bool RigidFormula
= false;
1198 /// This records the widest use type for any fixup using this
1199 /// LSRUse. FindUseWithSimilarFormula can't consider uses with different max
1200 /// fixup widths to be equivalent, because the narrower one may be relying on
1201 /// the implicit truncation to truncate away bogus bits.
1202 Type
*WidestFixupType
= nullptr;
1204 /// A list of ways to build a value that can satisfy this user. After the
1205 /// list is populated, one of these is selected heuristically and used to
1206 /// formulate a replacement for OperandValToReplace in UserInst.
1207 SmallVector
<Formula
, 12> Formulae
;
1209 /// The set of register candidates used by all formulae in this LSRUse.
1210 SmallPtrSet
<const SCEV
*, 4> Regs
;
1212 LSRUse(KindType K
, MemAccessTy AT
) : Kind(K
), AccessTy(AT
) {}
1214 LSRFixup
&getNewFixup() {
1215 Fixups
.push_back(LSRFixup());
1216 return Fixups
.back();
1219 void pushFixup(LSRFixup
&f
) {
1220 Fixups
.push_back(f
);
1221 if (f
.Offset
> MaxOffset
)
1222 MaxOffset
= f
.Offset
;
1223 if (f
.Offset
< MinOffset
)
1224 MinOffset
= f
.Offset
;
1227 bool HasFormulaWithSameRegs(const Formula
&F
) const;
1228 float getNotSelectedProbability(const SCEV
*Reg
) const;
1229 bool InsertFormula(const Formula
&F
, const Loop
&L
);
1230 void DeleteFormula(Formula
&F
);
1231 void RecomputeRegs(size_t LUIdx
, RegUseTracker
&Reguses
);
1233 void print(raw_ostream
&OS
) const;
1237 } // end anonymous namespace
1239 static bool isAMCompletelyFolded(const TargetTransformInfo
&TTI
,
1240 LSRUse::KindType Kind
, MemAccessTy AccessTy
,
1241 GlobalValue
*BaseGV
, int64_t BaseOffset
,
1242 bool HasBaseReg
, int64_t Scale
,
1243 Instruction
*Fixup
= nullptr);
1245 static unsigned getSetupCost(const SCEV
*Reg
, unsigned Depth
) {
1246 if (isa
<SCEVUnknown
>(Reg
) || isa
<SCEVConstant
>(Reg
))
1250 if (const auto *S
= dyn_cast
<SCEVAddRecExpr
>(Reg
))
1251 return getSetupCost(S
->getStart(), Depth
- 1);
1252 if (auto S
= dyn_cast
<SCEVIntegralCastExpr
>(Reg
))
1253 return getSetupCost(S
->getOperand(), Depth
- 1);
1254 if (auto S
= dyn_cast
<SCEVNAryExpr
>(Reg
))
1255 return std::accumulate(S
->op_begin(), S
->op_end(), 0,
1256 [&](unsigned i
, const SCEV
*Reg
) {
1257 return i
+ getSetupCost(Reg
, Depth
- 1);
1259 if (auto S
= dyn_cast
<SCEVUDivExpr
>(Reg
))
1260 return getSetupCost(S
->getLHS(), Depth
- 1) +
1261 getSetupCost(S
->getRHS(), Depth
- 1);
1265 /// Tally up interesting quantities from the given register.
1266 void Cost::RateRegister(const Formula
&F
, const SCEV
*Reg
,
1267 SmallPtrSetImpl
<const SCEV
*> &Regs
) {
1268 if (const SCEVAddRecExpr
*AR
= dyn_cast
<SCEVAddRecExpr
>(Reg
)) {
1269 // If this is an addrec for another loop, it should be an invariant
1270 // with respect to L since L is the innermost loop (at least
1271 // for now LSR only handles innermost loops).
1272 if (AR
->getLoop() != L
) {
1273 // If the AddRec exists, consider it's register free and leave it alone.
1274 if (isExistingPhi(AR
, *SE
) && AMK
!= TTI::AMK_PostIndexed
)
1277 // It is bad to allow LSR for current loop to add induction variables
1278 // for its sibling loops.
1279 if (!AR
->getLoop()->contains(L
)) {
1284 // Otherwise, it will be an invariant with respect to Loop L.
1289 unsigned LoopCost
= 1;
1290 if (TTI
->isIndexedLoadLegal(TTI
->MIM_PostInc
, AR
->getType()) ||
1291 TTI
->isIndexedStoreLegal(TTI
->MIM_PostInc
, AR
->getType())) {
1293 // If the step size matches the base offset, we could use pre-indexed
1295 if (AMK
== TTI::AMK_PreIndexed
) {
1296 if (auto *Step
= dyn_cast
<SCEVConstant
>(AR
->getStepRecurrence(*SE
)))
1297 if (Step
->getAPInt() == F
.BaseOffset
)
1299 } else if (AMK
== TTI::AMK_PostIndexed
) {
1300 const SCEV
*LoopStep
= AR
->getStepRecurrence(*SE
);
1301 if (isa
<SCEVConstant
>(LoopStep
)) {
1302 const SCEV
*LoopStart
= AR
->getStart();
1303 if (!isa
<SCEVConstant
>(LoopStart
) &&
1304 SE
->isLoopInvariant(LoopStart
, L
))
1309 C
.AddRecCost
+= LoopCost
;
1311 // Add the step value register, if it needs one.
1312 // TODO: The non-affine case isn't precisely modeled here.
1313 if (!AR
->isAffine() || !isa
<SCEVConstant
>(AR
->getOperand(1))) {
1314 if (!Regs
.count(AR
->getOperand(1))) {
1315 RateRegister(F
, AR
->getOperand(1), Regs
);
1323 // Rough heuristic; favor registers which don't require extra setup
1324 // instructions in the preheader.
1325 C
.SetupCost
+= getSetupCost(Reg
, SetupCostDepthLimit
);
1326 // Ensure we don't, even with the recusion limit, produce invalid costs.
1327 C
.SetupCost
= std::min
<unsigned>(C
.SetupCost
, 1 << 16);
1329 C
.NumIVMuls
+= isa
<SCEVMulExpr
>(Reg
) &&
1330 SE
->hasComputableLoopEvolution(Reg
, L
);
1333 /// Record this register in the set. If we haven't seen it before, rate
1334 /// it. Optional LoserRegs provides a way to declare any formula that refers to
1335 /// one of those regs an instant loser.
1336 void Cost::RatePrimaryRegister(const Formula
&F
, const SCEV
*Reg
,
1337 SmallPtrSetImpl
<const SCEV
*> &Regs
,
1338 SmallPtrSetImpl
<const SCEV
*> *LoserRegs
) {
1339 if (LoserRegs
&& LoserRegs
->count(Reg
)) {
1343 if (Regs
.insert(Reg
).second
) {
1344 RateRegister(F
, Reg
, Regs
);
1345 if (LoserRegs
&& isLoser())
1346 LoserRegs
->insert(Reg
);
1350 void Cost::RateFormula(const Formula
&F
,
1351 SmallPtrSetImpl
<const SCEV
*> &Regs
,
1352 const DenseSet
<const SCEV
*> &VisitedRegs
,
1354 SmallPtrSetImpl
<const SCEV
*> *LoserRegs
) {
1355 assert(F
.isCanonical(*L
) && "Cost is accurate only for canonical formula");
1356 // Tally up the registers.
1357 unsigned PrevAddRecCost
= C
.AddRecCost
;
1358 unsigned PrevNumRegs
= C
.NumRegs
;
1359 unsigned PrevNumBaseAdds
= C
.NumBaseAdds
;
1360 if (const SCEV
*ScaledReg
= F
.ScaledReg
) {
1361 if (VisitedRegs
.count(ScaledReg
)) {
1365 RatePrimaryRegister(F
, ScaledReg
, Regs
, LoserRegs
);
1369 for (const SCEV
*BaseReg
: F
.BaseRegs
) {
1370 if (VisitedRegs
.count(BaseReg
)) {
1374 RatePrimaryRegister(F
, BaseReg
, Regs
, LoserRegs
);
1379 // Determine how many (unfolded) adds we'll need inside the loop.
1380 size_t NumBaseParts
= F
.getNumRegs();
1381 if (NumBaseParts
> 1)
1382 // Do not count the base and a possible second register if the target
1383 // allows to fold 2 registers.
1385 NumBaseParts
- (1 + (F
.Scale
&& isAMCompletelyFolded(*TTI
, LU
, F
)));
1386 C
.NumBaseAdds
+= (F
.UnfoldedOffset
!= 0);
1388 // Accumulate non-free scaling amounts.
1389 C
.ScaleCost
+= *getScalingFactorCost(*TTI
, LU
, F
, *L
).getValue();
1391 // Tally up the non-zero immediates.
1392 for (const LSRFixup
&Fixup
: LU
.Fixups
) {
1393 int64_t O
= Fixup
.Offset
;
1394 int64_t Offset
= (uint64_t)O
+ F
.BaseOffset
;
1396 C
.ImmCost
+= 64; // Handle symbolic values conservatively.
1397 // TODO: This should probably be the pointer size.
1398 else if (Offset
!= 0)
1399 C
.ImmCost
+= APInt(64, Offset
, true).getMinSignedBits();
1401 // Check with target if this offset with this instruction is
1402 // specifically not supported.
1403 if (LU
.Kind
== LSRUse::Address
&& Offset
!= 0 &&
1404 !isAMCompletelyFolded(*TTI
, LSRUse::Address
, LU
.AccessTy
, F
.BaseGV
,
1405 Offset
, F
.HasBaseReg
, F
.Scale
, Fixup
.UserInst
))
1409 // If we don't count instruction cost exit here.
1411 assert(isValid() && "invalid cost");
1415 // Treat every new register that exceeds TTI.getNumberOfRegisters() - 1 as
1416 // additional instruction (at least fill).
1417 // TODO: Need distinguish register class?
1418 unsigned TTIRegNum
= TTI
->getNumberOfRegisters(
1419 TTI
->getRegisterClassForType(false, F
.getType())) - 1;
1420 if (C
.NumRegs
> TTIRegNum
) {
1421 // Cost already exceeded TTIRegNum, then only newly added register can add
1422 // new instructions.
1423 if (PrevNumRegs
> TTIRegNum
)
1424 C
.Insns
+= (C
.NumRegs
- PrevNumRegs
);
1426 C
.Insns
+= (C
.NumRegs
- TTIRegNum
);
1429 // If ICmpZero formula ends with not 0, it could not be replaced by
1430 // just add or sub. We'll need to compare final result of AddRec.
1431 // That means we'll need an additional instruction. But if the target can
1432 // macro-fuse a compare with a branch, don't count this extra instruction.
1433 // For -10 + {0, +, 1}:
1439 if (LU
.Kind
== LSRUse::ICmpZero
&& !F
.hasZeroEnd() &&
1440 !TTI
->canMacroFuseCmp())
1442 // Each new AddRec adds 1 instruction to calculation.
1443 C
.Insns
+= (C
.AddRecCost
- PrevAddRecCost
);
1445 // BaseAdds adds instructions for unfolded registers.
1446 if (LU
.Kind
!= LSRUse::ICmpZero
)
1447 C
.Insns
+= C
.NumBaseAdds
- PrevNumBaseAdds
;
1448 assert(isValid() && "invalid cost");
1451 /// Set this cost to a losing value.
1453 C
.Insns
= std::numeric_limits
<unsigned>::max();
1454 C
.NumRegs
= std::numeric_limits
<unsigned>::max();
1455 C
.AddRecCost
= std::numeric_limits
<unsigned>::max();
1456 C
.NumIVMuls
= std::numeric_limits
<unsigned>::max();
1457 C
.NumBaseAdds
= std::numeric_limits
<unsigned>::max();
1458 C
.ImmCost
= std::numeric_limits
<unsigned>::max();
1459 C
.SetupCost
= std::numeric_limits
<unsigned>::max();
1460 C
.ScaleCost
= std::numeric_limits
<unsigned>::max();
1463 /// Choose the lower cost.
1464 bool Cost::isLess(Cost
&Other
) {
1465 if (InsnsCost
.getNumOccurrences() > 0 && InsnsCost
&&
1466 C
.Insns
!= Other
.C
.Insns
)
1467 return C
.Insns
< Other
.C
.Insns
;
1468 return TTI
->isLSRCostLess(C
, Other
.C
);
1471 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1472 void Cost::print(raw_ostream
&OS
) const {
1474 OS
<< C
.Insns
<< " instruction" << (C
.Insns
== 1 ? " " : "s ");
1475 OS
<< C
.NumRegs
<< " reg" << (C
.NumRegs
== 1 ? "" : "s");
1476 if (C
.AddRecCost
!= 0)
1477 OS
<< ", with addrec cost " << C
.AddRecCost
;
1478 if (C
.NumIVMuls
!= 0)
1479 OS
<< ", plus " << C
.NumIVMuls
<< " IV mul"
1480 << (C
.NumIVMuls
== 1 ? "" : "s");
1481 if (C
.NumBaseAdds
!= 0)
1482 OS
<< ", plus " << C
.NumBaseAdds
<< " base add"
1483 << (C
.NumBaseAdds
== 1 ? "" : "s");
1484 if (C
.ScaleCost
!= 0)
1485 OS
<< ", plus " << C
.ScaleCost
<< " scale cost";
1487 OS
<< ", plus " << C
.ImmCost
<< " imm cost";
1488 if (C
.SetupCost
!= 0)
1489 OS
<< ", plus " << C
.SetupCost
<< " setup cost";
1492 LLVM_DUMP_METHOD
void Cost::dump() const {
1493 print(errs()); errs() << '\n';
1497 /// Test whether this fixup always uses its value outside of the given loop.
1498 bool LSRFixup::isUseFullyOutsideLoop(const Loop
*L
) const {
1499 // PHI nodes use their value in their incoming blocks.
1500 if (const PHINode
*PN
= dyn_cast
<PHINode
>(UserInst
)) {
1501 for (unsigned i
= 0, e
= PN
->getNumIncomingValues(); i
!= e
; ++i
)
1502 if (PN
->getIncomingValue(i
) == OperandValToReplace
&&
1503 L
->contains(PN
->getIncomingBlock(i
)))
1508 return !L
->contains(UserInst
);
1511 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1512 void LSRFixup::print(raw_ostream
&OS
) const {
1514 // Store is common and interesting enough to be worth special-casing.
1515 if (StoreInst
*Store
= dyn_cast
<StoreInst
>(UserInst
)) {
1517 Store
->getOperand(0)->printAsOperand(OS
, /*PrintType=*/false);
1518 } else if (UserInst
->getType()->isVoidTy())
1519 OS
<< UserInst
->getOpcodeName();
1521 UserInst
->printAsOperand(OS
, /*PrintType=*/false);
1523 OS
<< ", OperandValToReplace=";
1524 OperandValToReplace
->printAsOperand(OS
, /*PrintType=*/false);
1526 for (const Loop
*PIL
: PostIncLoops
) {
1527 OS
<< ", PostIncLoop=";
1528 PIL
->getHeader()->printAsOperand(OS
, /*PrintType=*/false);
1532 OS
<< ", Offset=" << Offset
;
1535 LLVM_DUMP_METHOD
void LSRFixup::dump() const {
1536 print(errs()); errs() << '\n';
1540 /// Test whether this use as a formula which has the same registers as the given
1542 bool LSRUse::HasFormulaWithSameRegs(const Formula
&F
) const {
1543 SmallVector
<const SCEV
*, 4> Key
= F
.BaseRegs
;
1544 if (F
.ScaledReg
) Key
.push_back(F
.ScaledReg
);
1545 // Unstable sort by host order ok, because this is only used for uniquifying.
1547 return Uniquifier
.count(Key
);
1550 /// The function returns a probability of selecting formula without Reg.
1551 float LSRUse::getNotSelectedProbability(const SCEV
*Reg
) const {
1553 for (const Formula
&F
: Formulae
)
1554 if (F
.referencesReg(Reg
))
1556 return ((float)(Formulae
.size() - FNum
)) / Formulae
.size();
1559 /// If the given formula has not yet been inserted, add it to the list, and
1560 /// return true. Return false otherwise. The formula must be in canonical form.
1561 bool LSRUse::InsertFormula(const Formula
&F
, const Loop
&L
) {
1562 assert(F
.isCanonical(L
) && "Invalid canonical representation");
1564 if (!Formulae
.empty() && RigidFormula
)
1567 SmallVector
<const SCEV
*, 4> Key
= F
.BaseRegs
;
1568 if (F
.ScaledReg
) Key
.push_back(F
.ScaledReg
);
1569 // Unstable sort by host order ok, because this is only used for uniquifying.
1572 if (!Uniquifier
.insert(Key
).second
)
1575 // Using a register to hold the value of 0 is not profitable.
1576 assert((!F
.ScaledReg
|| !F
.ScaledReg
->isZero()) &&
1577 "Zero allocated in a scaled register!");
1579 for (const SCEV
*BaseReg
: F
.BaseRegs
)
1580 assert(!BaseReg
->isZero() && "Zero allocated in a base register!");
1583 // Add the formula to the list.
1584 Formulae
.push_back(F
);
1586 // Record registers now being used by this use.
1587 Regs
.insert(F
.BaseRegs
.begin(), F
.BaseRegs
.end());
1589 Regs
.insert(F
.ScaledReg
);
1594 /// Remove the given formula from this use's list.
1595 void LSRUse::DeleteFormula(Formula
&F
) {
1596 if (&F
!= &Formulae
.back())
1597 std::swap(F
, Formulae
.back());
1598 Formulae
.pop_back();
1601 /// Recompute the Regs field, and update RegUses.
1602 void LSRUse::RecomputeRegs(size_t LUIdx
, RegUseTracker
&RegUses
) {
1603 // Now that we've filtered out some formulae, recompute the Regs set.
1604 SmallPtrSet
<const SCEV
*, 4> OldRegs
= std::move(Regs
);
1606 for (const Formula
&F
: Formulae
) {
1607 if (F
.ScaledReg
) Regs
.insert(F
.ScaledReg
);
1608 Regs
.insert(F
.BaseRegs
.begin(), F
.BaseRegs
.end());
1611 // Update the RegTracker.
1612 for (const SCEV
*S
: OldRegs
)
1614 RegUses
.dropRegister(S
, LUIdx
);
1617 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1618 void LSRUse::print(raw_ostream
&OS
) const {
1619 OS
<< "LSR Use: Kind=";
1621 case Basic
: OS
<< "Basic"; break;
1622 case Special
: OS
<< "Special"; break;
1623 case ICmpZero
: OS
<< "ICmpZero"; break;
1625 OS
<< "Address of ";
1626 if (AccessTy
.MemTy
->isPointerTy())
1627 OS
<< "pointer"; // the full pointer type could be really verbose
1629 OS
<< *AccessTy
.MemTy
;
1632 OS
<< " in addrspace(" << AccessTy
.AddrSpace
<< ')';
1635 OS
<< ", Offsets={";
1636 bool NeedComma
= false;
1637 for (const LSRFixup
&Fixup
: Fixups
) {
1638 if (NeedComma
) OS
<< ',';
1644 if (AllFixupsOutsideLoop
)
1645 OS
<< ", all-fixups-outside-loop";
1647 if (WidestFixupType
)
1648 OS
<< ", widest fixup type: " << *WidestFixupType
;
1651 LLVM_DUMP_METHOD
void LSRUse::dump() const {
1652 print(errs()); errs() << '\n';
1656 static bool isAMCompletelyFolded(const TargetTransformInfo
&TTI
,
1657 LSRUse::KindType Kind
, MemAccessTy AccessTy
,
1658 GlobalValue
*BaseGV
, int64_t BaseOffset
,
1659 bool HasBaseReg
, int64_t Scale
,
1660 Instruction
*Fixup
/*= nullptr*/) {
1662 case LSRUse::Address
:
1663 return TTI
.isLegalAddressingMode(AccessTy
.MemTy
, BaseGV
, BaseOffset
,
1664 HasBaseReg
, Scale
, AccessTy
.AddrSpace
, Fixup
);
1666 case LSRUse::ICmpZero
:
1667 // There's not even a target hook for querying whether it would be legal to
1668 // fold a GV into an ICmp.
1672 // ICmp only has two operands; don't allow more than two non-trivial parts.
1673 if (Scale
!= 0 && HasBaseReg
&& BaseOffset
!= 0)
1676 // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by
1677 // putting the scaled register in the other operand of the icmp.
1678 if (Scale
!= 0 && Scale
!= -1)
1681 // If we have low-level target information, ask the target if it can fold an
1682 // integer immediate on an icmp.
1683 if (BaseOffset
!= 0) {
1685 // ICmpZero BaseReg + BaseOffset => ICmp BaseReg, -BaseOffset
1686 // ICmpZero -1*ScaleReg + BaseOffset => ICmp ScaleReg, BaseOffset
1687 // Offs is the ICmp immediate.
1689 // The cast does the right thing with
1690 // std::numeric_limits<int64_t>::min().
1691 BaseOffset
= -(uint64_t)BaseOffset
;
1692 return TTI
.isLegalICmpImmediate(BaseOffset
);
1695 // ICmpZero BaseReg + -1*ScaleReg => ICmp BaseReg, ScaleReg
1699 // Only handle single-register values.
1700 return !BaseGV
&& Scale
== 0 && BaseOffset
== 0;
1702 case LSRUse::Special
:
1703 // Special case Basic to handle -1 scales.
1704 return !BaseGV
&& (Scale
== 0 || Scale
== -1) && BaseOffset
== 0;
1707 llvm_unreachable("Invalid LSRUse Kind!");
1710 static bool isAMCompletelyFolded(const TargetTransformInfo
&TTI
,
1711 int64_t MinOffset
, int64_t MaxOffset
,
1712 LSRUse::KindType Kind
, MemAccessTy AccessTy
,
1713 GlobalValue
*BaseGV
, int64_t BaseOffset
,
1714 bool HasBaseReg
, int64_t Scale
) {
1715 // Check for overflow.
1716 if (((int64_t)((uint64_t)BaseOffset
+ MinOffset
) > BaseOffset
) !=
1719 MinOffset
= (uint64_t)BaseOffset
+ MinOffset
;
1720 if (((int64_t)((uint64_t)BaseOffset
+ MaxOffset
) > BaseOffset
) !=
1723 MaxOffset
= (uint64_t)BaseOffset
+ MaxOffset
;
1725 return isAMCompletelyFolded(TTI
, Kind
, AccessTy
, BaseGV
, MinOffset
,
1726 HasBaseReg
, Scale
) &&
1727 isAMCompletelyFolded(TTI
, Kind
, AccessTy
, BaseGV
, MaxOffset
,
1731 static bool isAMCompletelyFolded(const TargetTransformInfo
&TTI
,
1732 int64_t MinOffset
, int64_t MaxOffset
,
1733 LSRUse::KindType Kind
, MemAccessTy AccessTy
,
1734 const Formula
&F
, const Loop
&L
) {
1735 // For the purpose of isAMCompletelyFolded either having a canonical formula
1736 // or a scale not equal to zero is correct.
1737 // Problems may arise from non canonical formulae having a scale == 0.
1738 // Strictly speaking it would best to just rely on canonical formulae.
1739 // However, when we generate the scaled formulae, we first check that the
1740 // scaling factor is profitable before computing the actual ScaledReg for
1741 // compile time sake.
1742 assert((F
.isCanonical(L
) || F
.Scale
!= 0));
1743 return isAMCompletelyFolded(TTI
, MinOffset
, MaxOffset
, Kind
, AccessTy
,
1744 F
.BaseGV
, F
.BaseOffset
, F
.HasBaseReg
, F
.Scale
);
1747 /// Test whether we know how to expand the current formula.
1748 static bool isLegalUse(const TargetTransformInfo
&TTI
, int64_t MinOffset
,
1749 int64_t MaxOffset
, LSRUse::KindType Kind
,
1750 MemAccessTy AccessTy
, GlobalValue
*BaseGV
,
1751 int64_t BaseOffset
, bool HasBaseReg
, int64_t Scale
) {
1752 // We know how to expand completely foldable formulae.
1753 return isAMCompletelyFolded(TTI
, MinOffset
, MaxOffset
, Kind
, AccessTy
, BaseGV
,
1754 BaseOffset
, HasBaseReg
, Scale
) ||
1755 // Or formulae that use a base register produced by a sum of base
1758 isAMCompletelyFolded(TTI
, MinOffset
, MaxOffset
, Kind
, AccessTy
,
1759 BaseGV
, BaseOffset
, true, 0));
1762 static bool isLegalUse(const TargetTransformInfo
&TTI
, int64_t MinOffset
,
1763 int64_t MaxOffset
, LSRUse::KindType Kind
,
1764 MemAccessTy AccessTy
, const Formula
&F
) {
1765 return isLegalUse(TTI
, MinOffset
, MaxOffset
, Kind
, AccessTy
, F
.BaseGV
,
1766 F
.BaseOffset
, F
.HasBaseReg
, F
.Scale
);
1769 static bool isAMCompletelyFolded(const TargetTransformInfo
&TTI
,
1770 const LSRUse
&LU
, const Formula
&F
) {
1771 // Target may want to look at the user instructions.
1772 if (LU
.Kind
== LSRUse::Address
&& TTI
.LSRWithInstrQueries()) {
1773 for (const LSRFixup
&Fixup
: LU
.Fixups
)
1774 if (!isAMCompletelyFolded(TTI
, LSRUse::Address
, LU
.AccessTy
, F
.BaseGV
,
1775 (F
.BaseOffset
+ Fixup
.Offset
), F
.HasBaseReg
,
1776 F
.Scale
, Fixup
.UserInst
))
1781 return isAMCompletelyFolded(TTI
, LU
.MinOffset
, LU
.MaxOffset
, LU
.Kind
,
1782 LU
.AccessTy
, F
.BaseGV
, F
.BaseOffset
, F
.HasBaseReg
,
1786 static InstructionCost
getScalingFactorCost(const TargetTransformInfo
&TTI
,
1787 const LSRUse
&LU
, const Formula
&F
,
1792 // If the use is not completely folded in that instruction, we will have to
1793 // pay an extra cost only for scale != 1.
1794 if (!isAMCompletelyFolded(TTI
, LU
.MinOffset
, LU
.MaxOffset
, LU
.Kind
,
1796 return F
.Scale
!= 1;
1799 case LSRUse::Address
: {
1800 // Check the scaling factor cost with both the min and max offsets.
1801 InstructionCost ScaleCostMinOffset
= TTI
.getScalingFactorCost(
1802 LU
.AccessTy
.MemTy
, F
.BaseGV
, F
.BaseOffset
+ LU
.MinOffset
, F
.HasBaseReg
,
1803 F
.Scale
, LU
.AccessTy
.AddrSpace
);
1804 InstructionCost ScaleCostMaxOffset
= TTI
.getScalingFactorCost(
1805 LU
.AccessTy
.MemTy
, F
.BaseGV
, F
.BaseOffset
+ LU
.MaxOffset
, F
.HasBaseReg
,
1806 F
.Scale
, LU
.AccessTy
.AddrSpace
);
1808 assert(ScaleCostMinOffset
.isValid() && ScaleCostMaxOffset
.isValid() &&
1809 "Legal addressing mode has an illegal cost!");
1810 return std::max(ScaleCostMinOffset
, ScaleCostMaxOffset
);
1812 case LSRUse::ICmpZero
:
1814 case LSRUse::Special
:
1815 // The use is completely folded, i.e., everything is folded into the
1820 llvm_unreachable("Invalid LSRUse Kind!");
1823 static bool isAlwaysFoldable(const TargetTransformInfo
&TTI
,
1824 LSRUse::KindType Kind
, MemAccessTy AccessTy
,
1825 GlobalValue
*BaseGV
, int64_t BaseOffset
,
1827 // Fast-path: zero is always foldable.
1828 if (BaseOffset
== 0 && !BaseGV
) return true;
1830 // Conservatively, create an address with an immediate and a
1831 // base and a scale.
1832 int64_t Scale
= Kind
== LSRUse::ICmpZero
? -1 : 1;
1834 // Canonicalize a scale of 1 to a base register if the formula doesn't
1835 // already have a base register.
1836 if (!HasBaseReg
&& Scale
== 1) {
1841 return isAMCompletelyFolded(TTI
, Kind
, AccessTy
, BaseGV
, BaseOffset
,
1845 static bool isAlwaysFoldable(const TargetTransformInfo
&TTI
,
1846 ScalarEvolution
&SE
, int64_t MinOffset
,
1847 int64_t MaxOffset
, LSRUse::KindType Kind
,
1848 MemAccessTy AccessTy
, const SCEV
*S
,
1850 // Fast-path: zero is always foldable.
1851 if (S
->isZero()) return true;
1853 // Conservatively, create an address with an immediate and a
1854 // base and a scale.
1855 int64_t BaseOffset
= ExtractImmediate(S
, SE
);
1856 GlobalValue
*BaseGV
= ExtractSymbol(S
, SE
);
1858 // If there's anything else involved, it's not foldable.
1859 if (!S
->isZero()) return false;
1861 // Fast-path: zero is always foldable.
1862 if (BaseOffset
== 0 && !BaseGV
) return true;
1864 // Conservatively, create an address with an immediate and a
1865 // base and a scale.
1866 int64_t Scale
= Kind
== LSRUse::ICmpZero
? -1 : 1;
1868 return isAMCompletelyFolded(TTI
, MinOffset
, MaxOffset
, Kind
, AccessTy
, BaseGV
,
1869 BaseOffset
, HasBaseReg
, Scale
);
1874 /// An individual increment in a Chain of IV increments. Relate an IV user to
1875 /// an expression that computes the IV it uses from the IV used by the previous
1876 /// link in the Chain.
1878 /// For the head of a chain, IncExpr holds the absolute SCEV expression for the
1879 /// original IVOperand. The head of the chain's IVOperand is only valid during
1880 /// chain collection, before LSR replaces IV users. During chain generation,
1881 /// IncExpr can be used to find the new IVOperand that computes the same
1884 Instruction
*UserInst
;
1886 const SCEV
*IncExpr
;
1888 IVInc(Instruction
*U
, Value
*O
, const SCEV
*E
)
1889 : UserInst(U
), IVOperand(O
), IncExpr(E
) {}
1892 // The list of IV increments in program order. We typically add the head of a
1893 // chain without finding subsequent links.
1895 SmallVector
<IVInc
, 1> Incs
;
1896 const SCEV
*ExprBase
= nullptr;
1898 IVChain() = default;
1899 IVChain(const IVInc
&Head
, const SCEV
*Base
)
1900 : Incs(1, Head
), ExprBase(Base
) {}
1902 using const_iterator
= SmallVectorImpl
<IVInc
>::const_iterator
;
1904 // Return the first increment in the chain.
1905 const_iterator
begin() const {
1906 assert(!Incs
.empty());
1907 return std::next(Incs
.begin());
1909 const_iterator
end() const {
1913 // Returns true if this chain contains any increments.
1914 bool hasIncs() const { return Incs
.size() >= 2; }
1916 // Add an IVInc to the end of this chain.
1917 void add(const IVInc
&X
) { Incs
.push_back(X
); }
1919 // Returns the last UserInst in the chain.
1920 Instruction
*tailUserInst() const { return Incs
.back().UserInst
; }
1922 // Returns true if IncExpr can be profitably added to this chain.
1923 bool isProfitableIncrement(const SCEV
*OperExpr
,
1924 const SCEV
*IncExpr
,
1928 /// Helper for CollectChains to track multiple IV increment uses. Distinguish
1929 /// between FarUsers that definitely cross IV increments and NearUsers that may
1930 /// be used between IV increments.
1932 SmallPtrSet
<Instruction
*, 4> FarUsers
;
1933 SmallPtrSet
<Instruction
*, 4> NearUsers
;
1936 /// This class holds state for the main loop strength reduction logic.
1939 ScalarEvolution
&SE
;
1942 AssumptionCache
&AC
;
1943 TargetLibraryInfo
&TLI
;
1944 const TargetTransformInfo
&TTI
;
1946 MemorySSAUpdater
*MSSAU
;
1947 TTI::AddressingModeKind AMK
;
1948 bool Changed
= false;
1950 /// This is the insert position that the current loop's induction variable
1951 /// increment should be placed. In simple loops, this is the latch block's
1952 /// terminator. But in more complicated cases, this is a position which will
1953 /// dominate all the in-loop post-increment users.
1954 Instruction
*IVIncInsertPos
= nullptr;
1956 /// Interesting factors between use strides.
1958 /// We explicitly use a SetVector which contains a SmallSet, instead of the
1959 /// default, a SmallDenseSet, because we need to use the full range of
1960 /// int64_ts, and there's currently no good way of doing that with
1962 SetVector
<int64_t, SmallVector
<int64_t, 8>, SmallSet
<int64_t, 8>> Factors
;
1964 /// Interesting use types, to facilitate truncation reuse.
1965 SmallSetVector
<Type
*, 4> Types
;
1967 /// The list of interesting uses.
1968 mutable SmallVector
<LSRUse
, 16> Uses
;
1970 /// Track which uses use which register candidates.
1971 RegUseTracker RegUses
;
1973 // Limit the number of chains to avoid quadratic behavior. We don't expect to
1974 // have more than a few IV increment chains in a loop. Missing a Chain falls
1975 // back to normal LSR behavior for those uses.
1976 static const unsigned MaxChains
= 8;
1978 /// IV users can form a chain of IV increments.
1979 SmallVector
<IVChain
, MaxChains
> IVChainVec
;
1981 /// IV users that belong to profitable IVChains.
1982 SmallPtrSet
<Use
*, MaxChains
> IVIncSet
;
1984 /// Induction variables that were generated and inserted by the SCEV Expander.
1985 SmallVector
<llvm::WeakVH
, 2> ScalarEvolutionIVs
;
1987 void OptimizeShadowIV();
1988 bool FindIVUserForCond(ICmpInst
*Cond
, IVStrideUse
*&CondUse
);
1989 ICmpInst
*OptimizeMax(ICmpInst
*Cond
, IVStrideUse
* &CondUse
);
1990 void OptimizeLoopTermCond();
1992 void ChainInstruction(Instruction
*UserInst
, Instruction
*IVOper
,
1993 SmallVectorImpl
<ChainUsers
> &ChainUsersVec
);
1994 void FinalizeChain(IVChain
&Chain
);
1995 void CollectChains();
1996 void GenerateIVChain(const IVChain
&Chain
, SCEVExpander
&Rewriter
,
1997 SmallVectorImpl
<WeakTrackingVH
> &DeadInsts
);
1999 void CollectInterestingTypesAndFactors();
2000 void CollectFixupsAndInitialFormulae();
2002 // Support for sharing of LSRUses between LSRFixups.
2003 using UseMapTy
= DenseMap
<LSRUse::SCEVUseKindPair
, size_t>;
2006 bool reconcileNewOffset(LSRUse
&LU
, int64_t NewOffset
, bool HasBaseReg
,
2007 LSRUse::KindType Kind
, MemAccessTy AccessTy
);
2009 std::pair
<size_t, int64_t> getUse(const SCEV
*&Expr
, LSRUse::KindType Kind
,
2010 MemAccessTy AccessTy
);
2012 void DeleteUse(LSRUse
&LU
, size_t LUIdx
);
2014 LSRUse
*FindUseWithSimilarFormula(const Formula
&F
, const LSRUse
&OrigLU
);
2016 void InsertInitialFormula(const SCEV
*S
, LSRUse
&LU
, size_t LUIdx
);
2017 void InsertSupplementalFormula(const SCEV
*S
, LSRUse
&LU
, size_t LUIdx
);
2018 void CountRegisters(const Formula
&F
, size_t LUIdx
);
2019 bool InsertFormula(LSRUse
&LU
, unsigned LUIdx
, const Formula
&F
);
2021 void CollectLoopInvariantFixupsAndFormulae();
2023 void GenerateReassociations(LSRUse
&LU
, unsigned LUIdx
, Formula Base
,
2024 unsigned Depth
= 0);
2026 void GenerateReassociationsImpl(LSRUse
&LU
, unsigned LUIdx
,
2027 const Formula
&Base
, unsigned Depth
,
2028 size_t Idx
, bool IsScaledReg
= false);
2029 void GenerateCombinations(LSRUse
&LU
, unsigned LUIdx
, Formula Base
);
2030 void GenerateSymbolicOffsetsImpl(LSRUse
&LU
, unsigned LUIdx
,
2031 const Formula
&Base
, size_t Idx
,
2032 bool IsScaledReg
= false);
2033 void GenerateSymbolicOffsets(LSRUse
&LU
, unsigned LUIdx
, Formula Base
);
2034 void GenerateConstantOffsetsImpl(LSRUse
&LU
, unsigned LUIdx
,
2035 const Formula
&Base
,
2036 const SmallVectorImpl
<int64_t> &Worklist
,
2037 size_t Idx
, bool IsScaledReg
= false);
2038 void GenerateConstantOffsets(LSRUse
&LU
, unsigned LUIdx
, Formula Base
);
2039 void GenerateICmpZeroScales(LSRUse
&LU
, unsigned LUIdx
, Formula Base
);
2040 void GenerateScales(LSRUse
&LU
, unsigned LUIdx
, Formula Base
);
2041 void GenerateTruncates(LSRUse
&LU
, unsigned LUIdx
, Formula Base
);
2042 void GenerateCrossUseConstantOffsets();
2043 void GenerateAllReuseFormulae();
2045 void FilterOutUndesirableDedicatedRegisters();
2047 size_t EstimateSearchSpaceComplexity() const;
2048 void NarrowSearchSpaceByDetectingSupersets();
2049 void NarrowSearchSpaceByCollapsingUnrolledCode();
2050 void NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
2051 void NarrowSearchSpaceByFilterFormulaWithSameScaledReg();
2052 void NarrowSearchSpaceByFilterPostInc();
2053 void NarrowSearchSpaceByDeletingCostlyFormulas();
2054 void NarrowSearchSpaceByPickingWinnerRegs();
2055 void NarrowSearchSpaceUsingHeuristics();
2057 void SolveRecurse(SmallVectorImpl
<const Formula
*> &Solution
,
2059 SmallVectorImpl
<const Formula
*> &Workspace
,
2060 const Cost
&CurCost
,
2061 const SmallPtrSet
<const SCEV
*, 16> &CurRegs
,
2062 DenseSet
<const SCEV
*> &VisitedRegs
) const;
2063 void Solve(SmallVectorImpl
<const Formula
*> &Solution
) const;
2065 BasicBlock::iterator
2066 HoistInsertPosition(BasicBlock::iterator IP
,
2067 const SmallVectorImpl
<Instruction
*> &Inputs
) const;
2068 BasicBlock::iterator
2069 AdjustInsertPositionForExpand(BasicBlock::iterator IP
,
2072 SCEVExpander
&Rewriter
) const;
2074 Value
*Expand(const LSRUse
&LU
, const LSRFixup
&LF
, const Formula
&F
,
2075 BasicBlock::iterator IP
, SCEVExpander
&Rewriter
,
2076 SmallVectorImpl
<WeakTrackingVH
> &DeadInsts
) const;
2077 void RewriteForPHI(PHINode
*PN
, const LSRUse
&LU
, const LSRFixup
&LF
,
2078 const Formula
&F
, SCEVExpander
&Rewriter
,
2079 SmallVectorImpl
<WeakTrackingVH
> &DeadInsts
) const;
2080 void Rewrite(const LSRUse
&LU
, const LSRFixup
&LF
, const Formula
&F
,
2081 SCEVExpander
&Rewriter
,
2082 SmallVectorImpl
<WeakTrackingVH
> &DeadInsts
) const;
2083 void ImplementSolution(const SmallVectorImpl
<const Formula
*> &Solution
);
2086 LSRInstance(Loop
*L
, IVUsers
&IU
, ScalarEvolution
&SE
, DominatorTree
&DT
,
2087 LoopInfo
&LI
, const TargetTransformInfo
&TTI
, AssumptionCache
&AC
,
2088 TargetLibraryInfo
&TLI
, MemorySSAUpdater
*MSSAU
);
2090 bool getChanged() const { return Changed
; }
2091 const SmallVectorImpl
<WeakVH
> &getScalarEvolutionIVs() const {
2092 return ScalarEvolutionIVs
;
2095 void print_factors_and_types(raw_ostream
&OS
) const;
2096 void print_fixups(raw_ostream
&OS
) const;
2097 void print_uses(raw_ostream
&OS
) const;
2098 void print(raw_ostream
&OS
) const;
2102 } // end anonymous namespace
2104 /// If IV is used in a int-to-float cast inside the loop then try to eliminate
2105 /// the cast operation.
2106 void LSRInstance::OptimizeShadowIV() {
2107 const SCEV
*BackedgeTakenCount
= SE
.getBackedgeTakenCount(L
);
2108 if (isa
<SCEVCouldNotCompute
>(BackedgeTakenCount
))
2111 for (IVUsers::const_iterator UI
= IU
.begin(), E
= IU
.end();
2112 UI
!= E
; /* empty */) {
2113 IVUsers::const_iterator CandidateUI
= UI
;
2115 Instruction
*ShadowUse
= CandidateUI
->getUser();
2116 Type
*DestTy
= nullptr;
2117 bool IsSigned
= false;
2119 /* If shadow use is a int->float cast then insert a second IV
2120 to eliminate this cast.
2122 for (unsigned i = 0; i < n; ++i)
2128 for (unsigned i = 0; i < n; ++i, ++d)
2131 if (UIToFPInst
*UCast
= dyn_cast
<UIToFPInst
>(CandidateUI
->getUser())) {
2133 DestTy
= UCast
->getDestTy();
2135 else if (SIToFPInst
*SCast
= dyn_cast
<SIToFPInst
>(CandidateUI
->getUser())) {
2137 DestTy
= SCast
->getDestTy();
2139 if (!DestTy
) continue;
2141 // If target does not support DestTy natively then do not apply
2142 // this transformation.
2143 if (!TTI
.isTypeLegal(DestTy
)) continue;
2145 PHINode
*PH
= dyn_cast
<PHINode
>(ShadowUse
->getOperand(0));
2147 if (PH
->getNumIncomingValues() != 2) continue;
2149 // If the calculation in integers overflows, the result in FP type will
2150 // differ. So we only can do this transformation if we are guaranteed to not
2151 // deal with overflowing values
2152 const SCEVAddRecExpr
*AR
= dyn_cast
<SCEVAddRecExpr
>(SE
.getSCEV(PH
));
2154 if (IsSigned
&& !AR
->hasNoSignedWrap()) continue;
2155 if (!IsSigned
&& !AR
->hasNoUnsignedWrap()) continue;
2157 Type
*SrcTy
= PH
->getType();
2158 int Mantissa
= DestTy
->getFPMantissaWidth();
2159 if (Mantissa
== -1) continue;
2160 if ((int)SE
.getTypeSizeInBits(SrcTy
) > Mantissa
)
2163 unsigned Entry
, Latch
;
2164 if (PH
->getIncomingBlock(0) == L
->getLoopPreheader()) {
2172 ConstantInt
*Init
= dyn_cast
<ConstantInt
>(PH
->getIncomingValue(Entry
));
2173 if (!Init
) continue;
2174 Constant
*NewInit
= ConstantFP::get(DestTy
, IsSigned
?
2175 (double)Init
->getSExtValue() :
2176 (double)Init
->getZExtValue());
2178 BinaryOperator
*Incr
=
2179 dyn_cast
<BinaryOperator
>(PH
->getIncomingValue(Latch
));
2180 if (!Incr
) continue;
2181 if (Incr
->getOpcode() != Instruction::Add
2182 && Incr
->getOpcode() != Instruction::Sub
)
2185 /* Initialize new IV, double d = 0.0 in above example. */
2186 ConstantInt
*C
= nullptr;
2187 if (Incr
->getOperand(0) == PH
)
2188 C
= dyn_cast
<ConstantInt
>(Incr
->getOperand(1));
2189 else if (Incr
->getOperand(1) == PH
)
2190 C
= dyn_cast
<ConstantInt
>(Incr
->getOperand(0));
2196 // Ignore negative constants, as the code below doesn't handle them
2197 // correctly. TODO: Remove this restriction.
2198 if (!C
->getValue().isStrictlyPositive()) continue;
2200 /* Add new PHINode. */
2201 PHINode
*NewPH
= PHINode::Create(DestTy
, 2, "IV.S.", PH
);
2203 /* create new increment. '++d' in above example. */
2204 Constant
*CFP
= ConstantFP::get(DestTy
, C
->getZExtValue());
2205 BinaryOperator
*NewIncr
=
2206 BinaryOperator::Create(Incr
->getOpcode() == Instruction::Add
?
2207 Instruction::FAdd
: Instruction::FSub
,
2208 NewPH
, CFP
, "IV.S.next.", Incr
);
2210 NewPH
->addIncoming(NewInit
, PH
->getIncomingBlock(Entry
));
2211 NewPH
->addIncoming(NewIncr
, PH
->getIncomingBlock(Latch
));
2213 /* Remove cast operation */
2214 ShadowUse
->replaceAllUsesWith(NewPH
);
2215 ShadowUse
->eraseFromParent();
2221 /// If Cond has an operand that is an expression of an IV, set the IV user and
2222 /// stride information and return true, otherwise return false.
2223 bool LSRInstance::FindIVUserForCond(ICmpInst
*Cond
, IVStrideUse
*&CondUse
) {
2224 for (IVStrideUse
&U
: IU
)
2225 if (U
.getUser() == Cond
) {
2226 // NOTE: we could handle setcc instructions with multiple uses here, but
2227 // InstCombine does it as well for simple uses, it's not clear that it
2228 // occurs enough in real life to handle.
2235 /// Rewrite the loop's terminating condition if it uses a max computation.
2237 /// This is a narrow solution to a specific, but acute, problem. For loops
2243 /// } while (++i < n);
2245 /// the trip count isn't just 'n', because 'n' might not be positive. And
2246 /// unfortunately this can come up even for loops where the user didn't use
2247 /// a C do-while loop. For example, seemingly well-behaved top-test loops
2248 /// will commonly be lowered like this:
2254 /// } while (++i < n);
2257 /// and then it's possible for subsequent optimization to obscure the if
2258 /// test in such a way that indvars can't find it.
2260 /// When indvars can't find the if test in loops like this, it creates a
2261 /// max expression, which allows it to give the loop a canonical
2262 /// induction variable:
2265 /// max = n < 1 ? 1 : n;
2268 /// } while (++i != max);
2270 /// Canonical induction variables are necessary because the loop passes
2271 /// are designed around them. The most obvious example of this is the
2272 /// LoopInfo analysis, which doesn't remember trip count values. It
2273 /// expects to be able to rediscover the trip count each time it is
2274 /// needed, and it does this using a simple analysis that only succeeds if
2275 /// the loop has a canonical induction variable.
2277 /// However, when it comes time to generate code, the maximum operation
2278 /// can be quite costly, especially if it's inside of an outer loop.
2280 /// This function solves this problem by detecting this type of loop and
2281 /// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
2282 /// the instructions for the maximum computation.
2283 ICmpInst
*LSRInstance::OptimizeMax(ICmpInst
*Cond
, IVStrideUse
* &CondUse
) {
2284 // Check that the loop matches the pattern we're looking for.
2285 if (Cond
->getPredicate() != CmpInst::ICMP_EQ
&&
2286 Cond
->getPredicate() != CmpInst::ICMP_NE
)
2289 SelectInst
*Sel
= dyn_cast
<SelectInst
>(Cond
->getOperand(1));
2290 if (!Sel
|| !Sel
->hasOneUse()) return Cond
;
2292 const SCEV
*BackedgeTakenCount
= SE
.getBackedgeTakenCount(L
);
2293 if (isa
<SCEVCouldNotCompute
>(BackedgeTakenCount
))
2295 const SCEV
*One
= SE
.getConstant(BackedgeTakenCount
->getType(), 1);
2297 // Add one to the backedge-taken count to get the trip count.
2298 const SCEV
*IterationCount
= SE
.getAddExpr(One
, BackedgeTakenCount
);
2299 if (IterationCount
!= SE
.getSCEV(Sel
)) return Cond
;
2301 // Check for a max calculation that matches the pattern. There's no check
2302 // for ICMP_ULE here because the comparison would be with zero, which
2303 // isn't interesting.
2304 CmpInst::Predicate Pred
= ICmpInst::BAD_ICMP_PREDICATE
;
2305 const SCEVNAryExpr
*Max
= nullptr;
2306 if (const SCEVSMaxExpr
*S
= dyn_cast
<SCEVSMaxExpr
>(BackedgeTakenCount
)) {
2307 Pred
= ICmpInst::ICMP_SLE
;
2309 } else if (const SCEVSMaxExpr
*S
= dyn_cast
<SCEVSMaxExpr
>(IterationCount
)) {
2310 Pred
= ICmpInst::ICMP_SLT
;
2312 } else if (const SCEVUMaxExpr
*U
= dyn_cast
<SCEVUMaxExpr
>(IterationCount
)) {
2313 Pred
= ICmpInst::ICMP_ULT
;
2320 // To handle a max with more than two operands, this optimization would
2321 // require additional checking and setup.
2322 if (Max
->getNumOperands() != 2)
2325 const SCEV
*MaxLHS
= Max
->getOperand(0);
2326 const SCEV
*MaxRHS
= Max
->getOperand(1);
2328 // ScalarEvolution canonicalizes constants to the left. For < and >, look
2329 // for a comparison with 1. For <= and >=, a comparison with zero.
2331 (ICmpInst::isTrueWhenEqual(Pred
) ? !MaxLHS
->isZero() : (MaxLHS
!= One
)))
2334 // Check the relevant induction variable for conformance to
2336 const SCEV
*IV
= SE
.getSCEV(Cond
->getOperand(0));
2337 const SCEVAddRecExpr
*AR
= dyn_cast
<SCEVAddRecExpr
>(IV
);
2338 if (!AR
|| !AR
->isAffine() ||
2339 AR
->getStart() != One
||
2340 AR
->getStepRecurrence(SE
) != One
)
2343 assert(AR
->getLoop() == L
&&
2344 "Loop condition operand is an addrec in a different loop!");
2346 // Check the right operand of the select, and remember it, as it will
2347 // be used in the new comparison instruction.
2348 Value
*NewRHS
= nullptr;
2349 if (ICmpInst::isTrueWhenEqual(Pred
)) {
2350 // Look for n+1, and grab n.
2351 if (AddOperator
*BO
= dyn_cast
<AddOperator
>(Sel
->getOperand(1)))
2352 if (ConstantInt
*BO1
= dyn_cast
<ConstantInt
>(BO
->getOperand(1)))
2353 if (BO1
->isOne() && SE
.getSCEV(BO
->getOperand(0)) == MaxRHS
)
2354 NewRHS
= BO
->getOperand(0);
2355 if (AddOperator
*BO
= dyn_cast
<AddOperator
>(Sel
->getOperand(2)))
2356 if (ConstantInt
*BO1
= dyn_cast
<ConstantInt
>(BO
->getOperand(1)))
2357 if (BO1
->isOne() && SE
.getSCEV(BO
->getOperand(0)) == MaxRHS
)
2358 NewRHS
= BO
->getOperand(0);
2361 } else if (SE
.getSCEV(Sel
->getOperand(1)) == MaxRHS
)
2362 NewRHS
= Sel
->getOperand(1);
2363 else if (SE
.getSCEV(Sel
->getOperand(2)) == MaxRHS
)
2364 NewRHS
= Sel
->getOperand(2);
2365 else if (const SCEVUnknown
*SU
= dyn_cast
<SCEVUnknown
>(MaxRHS
))
2366 NewRHS
= SU
->getValue();
2368 // Max doesn't match expected pattern.
2371 // Determine the new comparison opcode. It may be signed or unsigned,
2372 // and the original comparison may be either equality or inequality.
2373 if (Cond
->getPredicate() == CmpInst::ICMP_EQ
)
2374 Pred
= CmpInst::getInversePredicate(Pred
);
2376 // Ok, everything looks ok to change the condition into an SLT or SGE and
2377 // delete the max calculation.
2379 new ICmpInst(Cond
, Pred
, Cond
->getOperand(0), NewRHS
, "scmp");
2381 // Delete the max calculation instructions.
2382 NewCond
->setDebugLoc(Cond
->getDebugLoc());
2383 Cond
->replaceAllUsesWith(NewCond
);
2384 CondUse
->setUser(NewCond
);
2385 Instruction
*Cmp
= cast
<Instruction
>(Sel
->getOperand(0));
2386 Cond
->eraseFromParent();
2387 Sel
->eraseFromParent();
2388 if (Cmp
->use_empty())
2389 Cmp
->eraseFromParent();
2393 /// Change loop terminating condition to use the postinc iv when possible.
2395 LSRInstance::OptimizeLoopTermCond() {
2396 SmallPtrSet
<Instruction
*, 4> PostIncs
;
2398 // We need a different set of heuristics for rotated and non-rotated loops.
2399 // If a loop is rotated then the latch is also the backedge, so inserting
2400 // post-inc expressions just before the latch is ideal. To reduce live ranges
2401 // it also makes sense to rewrite terminating conditions to use post-inc
2404 // If the loop is not rotated then the latch is not a backedge; the latch
2405 // check is done in the loop head. Adding post-inc expressions before the
2406 // latch will cause overlapping live-ranges of pre-inc and post-inc expressions
2407 // in the loop body. In this case we do *not* want to use post-inc expressions
2408 // in the latch check, and we want to insert post-inc expressions before
2410 BasicBlock
*LatchBlock
= L
->getLoopLatch();
2411 SmallVector
<BasicBlock
*, 8> ExitingBlocks
;
2412 L
->getExitingBlocks(ExitingBlocks
);
2413 if (llvm::all_of(ExitingBlocks
, [&LatchBlock
](const BasicBlock
*BB
) {
2414 return LatchBlock
!= BB
;
2416 // The backedge doesn't exit the loop; treat this as a head-tested loop.
2417 IVIncInsertPos
= LatchBlock
->getTerminator();
2421 // Otherwise treat this as a rotated loop.
2422 for (BasicBlock
*ExitingBlock
: ExitingBlocks
) {
2423 // Get the terminating condition for the loop if possible. If we
2424 // can, we want to change it to use a post-incremented version of its
2425 // induction variable, to allow coalescing the live ranges for the IV into
2426 // one register value.
2428 BranchInst
*TermBr
= dyn_cast
<BranchInst
>(ExitingBlock
->getTerminator());
2431 // FIXME: Overly conservative, termination condition could be an 'or' etc..
2432 if (TermBr
->isUnconditional() || !isa
<ICmpInst
>(TermBr
->getCondition()))
2435 // Search IVUsesByStride to find Cond's IVUse if there is one.
2436 IVStrideUse
*CondUse
= nullptr;
2437 ICmpInst
*Cond
= cast
<ICmpInst
>(TermBr
->getCondition());
2438 if (!FindIVUserForCond(Cond
, CondUse
))
2441 // If the trip count is computed in terms of a max (due to ScalarEvolution
2442 // being unable to find a sufficient guard, for example), change the loop
2443 // comparison to use SLT or ULT instead of NE.
2444 // One consequence of doing this now is that it disrupts the count-down
2445 // optimization. That's not always a bad thing though, because in such
2446 // cases it may still be worthwhile to avoid a max.
2447 Cond
= OptimizeMax(Cond
, CondUse
);
2449 // If this exiting block dominates the latch block, it may also use
2450 // the post-inc value if it won't be shared with other uses.
2451 // Check for dominance.
2452 if (!DT
.dominates(ExitingBlock
, LatchBlock
))
2455 // Conservatively avoid trying to use the post-inc value in non-latch
2456 // exits if there may be pre-inc users in intervening blocks.
2457 if (LatchBlock
!= ExitingBlock
)
2458 for (IVUsers::const_iterator UI
= IU
.begin(), E
= IU
.end(); UI
!= E
; ++UI
)
2459 // Test if the use is reachable from the exiting block. This dominator
2460 // query is a conservative approximation of reachability.
2461 if (&*UI
!= CondUse
&&
2462 !DT
.properlyDominates(UI
->getUser()->getParent(), ExitingBlock
)) {
2463 // Conservatively assume there may be reuse if the quotient of their
2464 // strides could be a legal scale.
2465 const SCEV
*A
= IU
.getStride(*CondUse
, L
);
2466 const SCEV
*B
= IU
.getStride(*UI
, L
);
2467 if (!A
|| !B
) continue;
2468 if (SE
.getTypeSizeInBits(A
->getType()) !=
2469 SE
.getTypeSizeInBits(B
->getType())) {
2470 if (SE
.getTypeSizeInBits(A
->getType()) >
2471 SE
.getTypeSizeInBits(B
->getType()))
2472 B
= SE
.getSignExtendExpr(B
, A
->getType());
2474 A
= SE
.getSignExtendExpr(A
, B
->getType());
2476 if (const SCEVConstant
*D
=
2477 dyn_cast_or_null
<SCEVConstant
>(getExactSDiv(B
, A
, SE
))) {
2478 const ConstantInt
*C
= D
->getValue();
2479 // Stride of one or negative one can have reuse with non-addresses.
2480 if (C
->isOne() || C
->isMinusOne())
2481 goto decline_post_inc
;
2482 // Avoid weird situations.
2483 if (C
->getValue().getMinSignedBits() >= 64 ||
2484 C
->getValue().isMinSignedValue())
2485 goto decline_post_inc
;
2486 // Check for possible scaled-address reuse.
2487 if (isAddressUse(TTI
, UI
->getUser(), UI
->getOperandValToReplace())) {
2488 MemAccessTy AccessTy
= getAccessType(
2489 TTI
, UI
->getUser(), UI
->getOperandValToReplace());
2490 int64_t Scale
= C
->getSExtValue();
2491 if (TTI
.isLegalAddressingMode(AccessTy
.MemTy
, /*BaseGV=*/nullptr,
2493 /*HasBaseReg=*/false, Scale
,
2494 AccessTy
.AddrSpace
))
2495 goto decline_post_inc
;
2497 if (TTI
.isLegalAddressingMode(AccessTy
.MemTy
, /*BaseGV=*/nullptr,
2499 /*HasBaseReg=*/false, Scale
,
2500 AccessTy
.AddrSpace
))
2501 goto decline_post_inc
;
2506 LLVM_DEBUG(dbgs() << " Change loop exiting icmp to use postinc iv: "
2509 // It's possible for the setcc instruction to be anywhere in the loop, and
2510 // possible for it to have multiple users. If it is not immediately before
2511 // the exiting block branch, move it.
2512 if (Cond
->getNextNonDebugInstruction() != TermBr
) {
2513 if (Cond
->hasOneUse()) {
2514 Cond
->moveBefore(TermBr
);
2516 // Clone the terminating condition and insert into the loopend.
2517 ICmpInst
*OldCond
= Cond
;
2518 Cond
= cast
<ICmpInst
>(Cond
->clone());
2519 Cond
->setName(L
->getHeader()->getName() + ".termcond");
2520 ExitingBlock
->getInstList().insert(TermBr
->getIterator(), Cond
);
2522 // Clone the IVUse, as the old use still exists!
2523 CondUse
= &IU
.AddUser(Cond
, CondUse
->getOperandValToReplace());
2524 TermBr
->replaceUsesOfWith(OldCond
, Cond
);
2528 // If we get to here, we know that we can transform the setcc instruction to
2529 // use the post-incremented version of the IV, allowing us to coalesce the
2530 // live ranges for the IV correctly.
2531 CondUse
->transformToPostInc(L
);
2534 PostIncs
.insert(Cond
);
2538 // Determine an insertion point for the loop induction variable increment. It
2539 // must dominate all the post-inc comparisons we just set up, and it must
2540 // dominate the loop latch edge.
2541 IVIncInsertPos
= L
->getLoopLatch()->getTerminator();
2542 for (Instruction
*Inst
: PostIncs
) {
2544 DT
.findNearestCommonDominator(IVIncInsertPos
->getParent(),
2546 if (BB
== Inst
->getParent())
2547 IVIncInsertPos
= Inst
;
2548 else if (BB
!= IVIncInsertPos
->getParent())
2549 IVIncInsertPos
= BB
->getTerminator();
2553 /// Determine if the given use can accommodate a fixup at the given offset and
2554 /// other details. If so, update the use and return true.
2555 bool LSRInstance::reconcileNewOffset(LSRUse
&LU
, int64_t NewOffset
,
2556 bool HasBaseReg
, LSRUse::KindType Kind
,
2557 MemAccessTy AccessTy
) {
2558 int64_t NewMinOffset
= LU
.MinOffset
;
2559 int64_t NewMaxOffset
= LU
.MaxOffset
;
2560 MemAccessTy NewAccessTy
= AccessTy
;
2562 // Check for a mismatched kind. It's tempting to collapse mismatched kinds to
2563 // something conservative, however this can pessimize in the case that one of
2564 // the uses will have all its uses outside the loop, for example.
2565 if (LU
.Kind
!= Kind
)
2568 // Check for a mismatched access type, and fall back conservatively as needed.
2569 // TODO: Be less conservative when the type is similar and can use the same
2570 // addressing modes.
2571 if (Kind
== LSRUse::Address
) {
2572 if (AccessTy
.MemTy
!= LU
.AccessTy
.MemTy
) {
2573 NewAccessTy
= MemAccessTy::getUnknown(AccessTy
.MemTy
->getContext(),
2574 AccessTy
.AddrSpace
);
2578 // Conservatively assume HasBaseReg is true for now.
2579 if (NewOffset
< LU
.MinOffset
) {
2580 if (!isAlwaysFoldable(TTI
, Kind
, NewAccessTy
, /*BaseGV=*/nullptr,
2581 LU
.MaxOffset
- NewOffset
, HasBaseReg
))
2583 NewMinOffset
= NewOffset
;
2584 } else if (NewOffset
> LU
.MaxOffset
) {
2585 if (!isAlwaysFoldable(TTI
, Kind
, NewAccessTy
, /*BaseGV=*/nullptr,
2586 NewOffset
- LU
.MinOffset
, HasBaseReg
))
2588 NewMaxOffset
= NewOffset
;
2592 LU
.MinOffset
= NewMinOffset
;
2593 LU
.MaxOffset
= NewMaxOffset
;
2594 LU
.AccessTy
= NewAccessTy
;
2598 /// Return an LSRUse index and an offset value for a fixup which needs the given
2599 /// expression, with the given kind and optional access type. Either reuse an
2600 /// existing use or create a new one, as needed.
2601 std::pair
<size_t, int64_t> LSRInstance::getUse(const SCEV
*&Expr
,
2602 LSRUse::KindType Kind
,
2603 MemAccessTy AccessTy
) {
2604 const SCEV
*Copy
= Expr
;
2605 int64_t Offset
= ExtractImmediate(Expr
, SE
);
2607 // Basic uses can't accept any offset, for example.
2608 if (!isAlwaysFoldable(TTI
, Kind
, AccessTy
, /*BaseGV=*/ nullptr,
2609 Offset
, /*HasBaseReg=*/ true)) {
2614 std::pair
<UseMapTy::iterator
, bool> P
=
2615 UseMap
.insert(std::make_pair(LSRUse::SCEVUseKindPair(Expr
, Kind
), 0));
2617 // A use already existed with this base.
2618 size_t LUIdx
= P
.first
->second
;
2619 LSRUse
&LU
= Uses
[LUIdx
];
2620 if (reconcileNewOffset(LU
, Offset
, /*HasBaseReg=*/true, Kind
, AccessTy
))
2622 return std::make_pair(LUIdx
, Offset
);
2625 // Create a new use.
2626 size_t LUIdx
= Uses
.size();
2627 P
.first
->second
= LUIdx
;
2628 Uses
.push_back(LSRUse(Kind
, AccessTy
));
2629 LSRUse
&LU
= Uses
[LUIdx
];
2631 LU
.MinOffset
= Offset
;
2632 LU
.MaxOffset
= Offset
;
2633 return std::make_pair(LUIdx
, Offset
);
2636 /// Delete the given use from the Uses list.
2637 void LSRInstance::DeleteUse(LSRUse
&LU
, size_t LUIdx
) {
2638 if (&LU
!= &Uses
.back())
2639 std::swap(LU
, Uses
.back());
2643 RegUses
.swapAndDropUse(LUIdx
, Uses
.size());
2646 /// Look for a use distinct from OrigLU which is has a formula that has the same
2647 /// registers as the given formula.
2649 LSRInstance::FindUseWithSimilarFormula(const Formula
&OrigF
,
2650 const LSRUse
&OrigLU
) {
2651 // Search all uses for the formula. This could be more clever.
2652 for (size_t LUIdx
= 0, NumUses
= Uses
.size(); LUIdx
!= NumUses
; ++LUIdx
) {
2653 LSRUse
&LU
= Uses
[LUIdx
];
2654 // Check whether this use is close enough to OrigLU, to see whether it's
2655 // worthwhile looking through its formulae.
2656 // Ignore ICmpZero uses because they may contain formulae generated by
2657 // GenerateICmpZeroScales, in which case adding fixup offsets may
2659 if (&LU
!= &OrigLU
&&
2660 LU
.Kind
!= LSRUse::ICmpZero
&&
2661 LU
.Kind
== OrigLU
.Kind
&& OrigLU
.AccessTy
== LU
.AccessTy
&&
2662 LU
.WidestFixupType
== OrigLU
.WidestFixupType
&&
2663 LU
.HasFormulaWithSameRegs(OrigF
)) {
2664 // Scan through this use's formulae.
2665 for (const Formula
&F
: LU
.Formulae
) {
2666 // Check to see if this formula has the same registers and symbols
2668 if (F
.BaseRegs
== OrigF
.BaseRegs
&&
2669 F
.ScaledReg
== OrigF
.ScaledReg
&&
2670 F
.BaseGV
== OrigF
.BaseGV
&&
2671 F
.Scale
== OrigF
.Scale
&&
2672 F
.UnfoldedOffset
== OrigF
.UnfoldedOffset
) {
2673 if (F
.BaseOffset
== 0)
2675 // This is the formula where all the registers and symbols matched;
2676 // there aren't going to be any others. Since we declined it, we
2677 // can skip the rest of the formulae and proceed to the next LSRUse.
2684 // Nothing looked good.
2688 void LSRInstance::CollectInterestingTypesAndFactors() {
2689 SmallSetVector
<const SCEV
*, 4> Strides
;
2691 // Collect interesting types and strides.
2692 SmallVector
<const SCEV
*, 4> Worklist
;
2693 for (const IVStrideUse
&U
: IU
) {
2694 const SCEV
*Expr
= IU
.getExpr(U
);
2696 // Collect interesting types.
2697 Types
.insert(SE
.getEffectiveSCEVType(Expr
->getType()));
2699 // Add strides for mentioned loops.
2700 Worklist
.push_back(Expr
);
2702 const SCEV
*S
= Worklist
.pop_back_val();
2703 if (const SCEVAddRecExpr
*AR
= dyn_cast
<SCEVAddRecExpr
>(S
)) {
2704 if (AR
->getLoop() == L
)
2705 Strides
.insert(AR
->getStepRecurrence(SE
));
2706 Worklist
.push_back(AR
->getStart());
2707 } else if (const SCEVAddExpr
*Add
= dyn_cast
<SCEVAddExpr
>(S
)) {
2708 Worklist
.append(Add
->op_begin(), Add
->op_end());
2710 } while (!Worklist
.empty());
2713 // Compute interesting factors from the set of interesting strides.
2714 for (SmallSetVector
<const SCEV
*, 4>::const_iterator
2715 I
= Strides
.begin(), E
= Strides
.end(); I
!= E
; ++I
)
2716 for (SmallSetVector
<const SCEV
*, 4>::const_iterator NewStrideIter
=
2717 std::next(I
); NewStrideIter
!= E
; ++NewStrideIter
) {
2718 const SCEV
*OldStride
= *I
;
2719 const SCEV
*NewStride
= *NewStrideIter
;
2721 if (SE
.getTypeSizeInBits(OldStride
->getType()) !=
2722 SE
.getTypeSizeInBits(NewStride
->getType())) {
2723 if (SE
.getTypeSizeInBits(OldStride
->getType()) >
2724 SE
.getTypeSizeInBits(NewStride
->getType()))
2725 NewStride
= SE
.getSignExtendExpr(NewStride
, OldStride
->getType());
2727 OldStride
= SE
.getSignExtendExpr(OldStride
, NewStride
->getType());
2729 if (const SCEVConstant
*Factor
=
2730 dyn_cast_or_null
<SCEVConstant
>(getExactSDiv(NewStride
, OldStride
,
2732 if (Factor
->getAPInt().getMinSignedBits() <= 64 && !Factor
->isZero())
2733 Factors
.insert(Factor
->getAPInt().getSExtValue());
2734 } else if (const SCEVConstant
*Factor
=
2735 dyn_cast_or_null
<SCEVConstant
>(getExactSDiv(OldStride
,
2738 if (Factor
->getAPInt().getMinSignedBits() <= 64 && !Factor
->isZero())
2739 Factors
.insert(Factor
->getAPInt().getSExtValue());
2743 // If all uses use the same type, don't bother looking for truncation-based
2745 if (Types
.size() == 1)
2748 LLVM_DEBUG(print_factors_and_types(dbgs()));
2751 /// Helper for CollectChains that finds an IV operand (computed by an AddRec in
2752 /// this loop) within [OI,OE) or returns OE. If IVUsers mapped Instructions to
2753 /// IVStrideUses, we could partially skip this.
2754 static User::op_iterator
2755 findIVOperand(User::op_iterator OI
, User::op_iterator OE
,
2756 Loop
*L
, ScalarEvolution
&SE
) {
2757 for(; OI
!= OE
; ++OI
) {
2758 if (Instruction
*Oper
= dyn_cast
<Instruction
>(*OI
)) {
2759 if (!SE
.isSCEVable(Oper
->getType()))
2762 if (const SCEVAddRecExpr
*AR
=
2763 dyn_cast
<SCEVAddRecExpr
>(SE
.getSCEV(Oper
))) {
2764 if (AR
->getLoop() == L
)
2772 /// IVChain logic must consistently peek base TruncInst operands, so wrap it in
2773 /// a convenient helper.
2774 static Value
*getWideOperand(Value
*Oper
) {
2775 if (TruncInst
*Trunc
= dyn_cast
<TruncInst
>(Oper
))
2776 return Trunc
->getOperand(0);
2780 /// Return true if we allow an IV chain to include both types.
2781 static bool isCompatibleIVType(Value
*LVal
, Value
*RVal
) {
2782 Type
*LType
= LVal
->getType();
2783 Type
*RType
= RVal
->getType();
2784 return (LType
== RType
) || (LType
->isPointerTy() && RType
->isPointerTy() &&
2785 // Different address spaces means (possibly)
2786 // different types of the pointer implementation,
2787 // e.g. i16 vs i32 so disallow that.
2788 (LType
->getPointerAddressSpace() ==
2789 RType
->getPointerAddressSpace()));
2792 /// Return an approximation of this SCEV expression's "base", or NULL for any
2793 /// constant. Returning the expression itself is conservative. Returning a
2794 /// deeper subexpression is more precise and valid as long as it isn't less
2795 /// complex than another subexpression. For expressions involving multiple
2796 /// unscaled values, we need to return the pointer-type SCEVUnknown. This avoids
2797 /// forming chains across objects, such as: PrevOper==a[i], IVOper==b[i],
2800 /// Since SCEVUnknown is the rightmost type, and pointers are the rightmost
2801 /// SCEVUnknown, we simply return the rightmost SCEV operand.
2802 static const SCEV
*getExprBase(const SCEV
*S
) {
2803 switch (S
->getSCEVType()) {
2804 default: // uncluding scUnknown.
2809 return getExprBase(cast
<SCEVTruncateExpr
>(S
)->getOperand());
2811 return getExprBase(cast
<SCEVZeroExtendExpr
>(S
)->getOperand());
2813 return getExprBase(cast
<SCEVSignExtendExpr
>(S
)->getOperand());
2815 // Skip over scaled operands (scMulExpr) to follow add operands as long as
2816 // there's nothing more complex.
2817 // FIXME: not sure if we want to recognize negation.
2818 const SCEVAddExpr
*Add
= cast
<SCEVAddExpr
>(S
);
2819 for (std::reverse_iterator
<SCEVAddExpr::op_iterator
> I(Add
->op_end()),
2820 E(Add
->op_begin()); I
!= E
; ++I
) {
2821 const SCEV
*SubExpr
= *I
;
2822 if (SubExpr
->getSCEVType() == scAddExpr
)
2823 return getExprBase(SubExpr
);
2825 if (SubExpr
->getSCEVType() != scMulExpr
)
2828 return S
; // all operands are scaled, be conservative.
2831 return getExprBase(cast
<SCEVAddRecExpr
>(S
)->getStart());
2833 llvm_unreachable("Unknown SCEV kind!");
2836 /// Return true if the chain increment is profitable to expand into a loop
2837 /// invariant value, which may require its own register. A profitable chain
2838 /// increment will be an offset relative to the same base. We allow such offsets
2839 /// to potentially be used as chain increment as long as it's not obviously
2840 /// expensive to expand using real instructions.
2841 bool IVChain::isProfitableIncrement(const SCEV
*OperExpr
,
2842 const SCEV
*IncExpr
,
2843 ScalarEvolution
&SE
) {
2844 // Aggressively form chains when -stress-ivchain.
2848 // Do not replace a constant offset from IV head with a nonconstant IV
2850 if (!isa
<SCEVConstant
>(IncExpr
)) {
2851 const SCEV
*HeadExpr
= SE
.getSCEV(getWideOperand(Incs
[0].IVOperand
));
2852 if (isa
<SCEVConstant
>(SE
.getMinusSCEV(OperExpr
, HeadExpr
)))
2856 SmallPtrSet
<const SCEV
*, 8> Processed
;
2857 return !isHighCostExpansion(IncExpr
, Processed
, SE
);
2860 /// Return true if the number of registers needed for the chain is estimated to
2861 /// be less than the number required for the individual IV users. First prohibit
2862 /// any IV users that keep the IV live across increments (the Users set should
2863 /// be empty). Next count the number and type of increments in the chain.
2865 /// Chaining IVs can lead to considerable code bloat if ISEL doesn't
2866 /// effectively use postinc addressing modes. Only consider it profitable it the
2867 /// increments can be computed in fewer registers when chained.
2869 /// TODO: Consider IVInc free if it's already used in another chains.
2870 static bool isProfitableChain(IVChain
&Chain
,
2871 SmallPtrSetImpl
<Instruction
*> &Users
,
2872 ScalarEvolution
&SE
,
2873 const TargetTransformInfo
&TTI
) {
2877 if (!Chain
.hasIncs())
2880 if (!Users
.empty()) {
2881 LLVM_DEBUG(dbgs() << "Chain: " << *Chain
.Incs
[0].UserInst
<< " users:\n";
2882 for (Instruction
*Inst
2883 : Users
) { dbgs() << " " << *Inst
<< "\n"; });
2886 assert(!Chain
.Incs
.empty() && "empty IV chains are not allowed");
2888 // The chain itself may require a register, so intialize cost to 1.
2891 // A complete chain likely eliminates the need for keeping the original IV in
2892 // a register. LSR does not currently know how to form a complete chain unless
2893 // the header phi already exists.
2894 if (isa
<PHINode
>(Chain
.tailUserInst())
2895 && SE
.getSCEV(Chain
.tailUserInst()) == Chain
.Incs
[0].IncExpr
) {
2898 const SCEV
*LastIncExpr
= nullptr;
2899 unsigned NumConstIncrements
= 0;
2900 unsigned NumVarIncrements
= 0;
2901 unsigned NumReusedIncrements
= 0;
2903 if (TTI
.isProfitableLSRChainElement(Chain
.Incs
[0].UserInst
))
2906 for (const IVInc
&Inc
: Chain
) {
2907 if (TTI
.isProfitableLSRChainElement(Inc
.UserInst
))
2909 if (Inc
.IncExpr
->isZero())
2912 // Incrementing by zero or some constant is neutral. We assume constants can
2913 // be folded into an addressing mode or an add's immediate operand.
2914 if (isa
<SCEVConstant
>(Inc
.IncExpr
)) {
2915 ++NumConstIncrements
;
2919 if (Inc
.IncExpr
== LastIncExpr
)
2920 ++NumReusedIncrements
;
2924 LastIncExpr
= Inc
.IncExpr
;
2926 // An IV chain with a single increment is handled by LSR's postinc
2927 // uses. However, a chain with multiple increments requires keeping the IV's
2928 // value live longer than it needs to be if chained.
2929 if (NumConstIncrements
> 1)
2932 // Materializing increment expressions in the preheader that didn't exist in
2933 // the original code may cost a register. For example, sign-extended array
2934 // indices can produce ridiculous increments like this:
2935 // IV + ((sext i32 (2 * %s) to i64) + (-1 * (sext i32 %s to i64)))
2936 cost
+= NumVarIncrements
;
2938 // Reusing variable increments likely saves a register to hold the multiple of
2940 cost
-= NumReusedIncrements
;
2942 LLVM_DEBUG(dbgs() << "Chain: " << *Chain
.Incs
[0].UserInst
<< " Cost: " << cost
2948 /// Add this IV user to an existing chain or make it the head of a new chain.
2949 void LSRInstance::ChainInstruction(Instruction
*UserInst
, Instruction
*IVOper
,
2950 SmallVectorImpl
<ChainUsers
> &ChainUsersVec
) {
2951 // When IVs are used as types of varying widths, they are generally converted
2952 // to a wider type with some uses remaining narrow under a (free) trunc.
2953 Value
*const NextIV
= getWideOperand(IVOper
);
2954 const SCEV
*const OperExpr
= SE
.getSCEV(NextIV
);
2955 const SCEV
*const OperExprBase
= getExprBase(OperExpr
);
2957 // Visit all existing chains. Check if its IVOper can be computed as a
2958 // profitable loop invariant increment from the last link in the Chain.
2959 unsigned ChainIdx
= 0, NChains
= IVChainVec
.size();
2960 const SCEV
*LastIncExpr
= nullptr;
2961 for (; ChainIdx
< NChains
; ++ChainIdx
) {
2962 IVChain
&Chain
= IVChainVec
[ChainIdx
];
2964 // Prune the solution space aggressively by checking that both IV operands
2965 // are expressions that operate on the same unscaled SCEVUnknown. This
2966 // "base" will be canceled by the subsequent getMinusSCEV call. Checking
2967 // first avoids creating extra SCEV expressions.
2968 if (!StressIVChain
&& Chain
.ExprBase
!= OperExprBase
)
2971 Value
*PrevIV
= getWideOperand(Chain
.Incs
.back().IVOperand
);
2972 if (!isCompatibleIVType(PrevIV
, NextIV
))
2975 // A phi node terminates a chain.
2976 if (isa
<PHINode
>(UserInst
) && isa
<PHINode
>(Chain
.tailUserInst()))
2979 // The increment must be loop-invariant so it can be kept in a register.
2980 const SCEV
*PrevExpr
= SE
.getSCEV(PrevIV
);
2981 const SCEV
*IncExpr
= SE
.getMinusSCEV(OperExpr
, PrevExpr
);
2982 if (isa
<SCEVCouldNotCompute
>(IncExpr
) || !SE
.isLoopInvariant(IncExpr
, L
))
2985 if (Chain
.isProfitableIncrement(OperExpr
, IncExpr
, SE
)) {
2986 LastIncExpr
= IncExpr
;
2990 // If we haven't found a chain, create a new one, unless we hit the max. Don't
2991 // bother for phi nodes, because they must be last in the chain.
2992 if (ChainIdx
== NChains
) {
2993 if (isa
<PHINode
>(UserInst
))
2995 if (NChains
>= MaxChains
&& !StressIVChain
) {
2996 LLVM_DEBUG(dbgs() << "IV Chain Limit\n");
2999 LastIncExpr
= OperExpr
;
3000 // IVUsers may have skipped over sign/zero extensions. We don't currently
3001 // attempt to form chains involving extensions unless they can be hoisted
3002 // into this loop's AddRec.
3003 if (!isa
<SCEVAddRecExpr
>(LastIncExpr
))
3006 IVChainVec
.push_back(IVChain(IVInc(UserInst
, IVOper
, LastIncExpr
),
3008 ChainUsersVec
.resize(NChains
);
3009 LLVM_DEBUG(dbgs() << "IV Chain#" << ChainIdx
<< " Head: (" << *UserInst
3010 << ") IV=" << *LastIncExpr
<< "\n");
3012 LLVM_DEBUG(dbgs() << "IV Chain#" << ChainIdx
<< " Inc: (" << *UserInst
3013 << ") IV+" << *LastIncExpr
<< "\n");
3014 // Add this IV user to the end of the chain.
3015 IVChainVec
[ChainIdx
].add(IVInc(UserInst
, IVOper
, LastIncExpr
));
3017 IVChain
&Chain
= IVChainVec
[ChainIdx
];
3019 SmallPtrSet
<Instruction
*,4> &NearUsers
= ChainUsersVec
[ChainIdx
].NearUsers
;
3020 // This chain's NearUsers become FarUsers.
3021 if (!LastIncExpr
->isZero()) {
3022 ChainUsersVec
[ChainIdx
].FarUsers
.insert(NearUsers
.begin(),
3027 // All other uses of IVOperand become near uses of the chain.
3028 // We currently ignore intermediate values within SCEV expressions, assuming
3029 // they will eventually be used be the current chain, or can be computed
3030 // from one of the chain increments. To be more precise we could
3031 // transitively follow its user and only add leaf IV users to the set.
3032 for (User
*U
: IVOper
->users()) {
3033 Instruction
*OtherUse
= dyn_cast
<Instruction
>(U
);
3036 // Uses in the chain will no longer be uses if the chain is formed.
3037 // Include the head of the chain in this iteration (not Chain.begin()).
3038 IVChain::const_iterator IncIter
= Chain
.Incs
.begin();
3039 IVChain::const_iterator IncEnd
= Chain
.Incs
.end();
3040 for( ; IncIter
!= IncEnd
; ++IncIter
) {
3041 if (IncIter
->UserInst
== OtherUse
)
3044 if (IncIter
!= IncEnd
)
3047 if (SE
.isSCEVable(OtherUse
->getType())
3048 && !isa
<SCEVUnknown
>(SE
.getSCEV(OtherUse
))
3049 && IU
.isIVUserOrOperand(OtherUse
)) {
3052 NearUsers
.insert(OtherUse
);
3055 // Since this user is part of the chain, it's no longer considered a use
3057 ChainUsersVec
[ChainIdx
].FarUsers
.erase(UserInst
);
3060 /// Populate the vector of Chains.
3062 /// This decreases ILP at the architecture level. Targets with ample registers,
3063 /// multiple memory ports, and no register renaming probably don't want
3064 /// this. However, such targets should probably disable LSR altogether.
3066 /// The job of LSR is to make a reasonable choice of induction variables across
3067 /// the loop. Subsequent passes can easily "unchain" computation exposing more
3068 /// ILP *within the loop* if the target wants it.
3070 /// Finding the best IV chain is potentially a scheduling problem. Since LSR
3071 /// will not reorder memory operations, it will recognize this as a chain, but
3072 /// will generate redundant IV increments. Ideally this would be corrected later
3073 /// by a smart scheduler:
3079 /// TODO: Walk the entire domtree within this loop, not just the path to the
3080 /// loop latch. This will discover chains on side paths, but requires
3081 /// maintaining multiple copies of the Chains state.
3082 void LSRInstance::CollectChains() {
3083 LLVM_DEBUG(dbgs() << "Collecting IV Chains.\n");
3084 SmallVector
<ChainUsers
, 8> ChainUsersVec
;
3086 SmallVector
<BasicBlock
*,8> LatchPath
;
3087 BasicBlock
*LoopHeader
= L
->getHeader();
3088 for (DomTreeNode
*Rung
= DT
.getNode(L
->getLoopLatch());
3089 Rung
->getBlock() != LoopHeader
; Rung
= Rung
->getIDom()) {
3090 LatchPath
.push_back(Rung
->getBlock());
3092 LatchPath
.push_back(LoopHeader
);
3094 // Walk the instruction stream from the loop header to the loop latch.
3095 for (BasicBlock
*BB
: reverse(LatchPath
)) {
3096 for (Instruction
&I
: *BB
) {
3097 // Skip instructions that weren't seen by IVUsers analysis.
3098 if (isa
<PHINode
>(I
) || !IU
.isIVUserOrOperand(&I
))
3101 // Ignore users that are part of a SCEV expression. This way we only
3102 // consider leaf IV Users. This effectively rediscovers a portion of
3103 // IVUsers analysis but in program order this time.
3104 if (SE
.isSCEVable(I
.getType()) && !isa
<SCEVUnknown
>(SE
.getSCEV(&I
)))
3107 // Remove this instruction from any NearUsers set it may be in.
3108 for (unsigned ChainIdx
= 0, NChains
= IVChainVec
.size();
3109 ChainIdx
< NChains
; ++ChainIdx
) {
3110 ChainUsersVec
[ChainIdx
].NearUsers
.erase(&I
);
3112 // Search for operands that can be chained.
3113 SmallPtrSet
<Instruction
*, 4> UniqueOperands
;
3114 User::op_iterator IVOpEnd
= I
.op_end();
3115 User::op_iterator IVOpIter
= findIVOperand(I
.op_begin(), IVOpEnd
, L
, SE
);
3116 while (IVOpIter
!= IVOpEnd
) {
3117 Instruction
*IVOpInst
= cast
<Instruction
>(*IVOpIter
);
3118 if (UniqueOperands
.insert(IVOpInst
).second
)
3119 ChainInstruction(&I
, IVOpInst
, ChainUsersVec
);
3120 IVOpIter
= findIVOperand(std::next(IVOpIter
), IVOpEnd
, L
, SE
);
3122 } // Continue walking down the instructions.
3123 } // Continue walking down the domtree.
3124 // Visit phi backedges to determine if the chain can generate the IV postinc.
3125 for (PHINode
&PN
: L
->getHeader()->phis()) {
3126 if (!SE
.isSCEVable(PN
.getType()))
3130 dyn_cast
<Instruction
>(PN
.getIncomingValueForBlock(L
->getLoopLatch()));
3132 ChainInstruction(&PN
, IncV
, ChainUsersVec
);
3134 // Remove any unprofitable chains.
3135 unsigned ChainIdx
= 0;
3136 for (unsigned UsersIdx
= 0, NChains
= IVChainVec
.size();
3137 UsersIdx
< NChains
; ++UsersIdx
) {
3138 if (!isProfitableChain(IVChainVec
[UsersIdx
],
3139 ChainUsersVec
[UsersIdx
].FarUsers
, SE
, TTI
))
3141 // Preserve the chain at UsesIdx.
3142 if (ChainIdx
!= UsersIdx
)
3143 IVChainVec
[ChainIdx
] = IVChainVec
[UsersIdx
];
3144 FinalizeChain(IVChainVec
[ChainIdx
]);
3147 IVChainVec
.resize(ChainIdx
);
3150 void LSRInstance::FinalizeChain(IVChain
&Chain
) {
3151 assert(!Chain
.Incs
.empty() && "empty IV chains are not allowed");
3152 LLVM_DEBUG(dbgs() << "Final Chain: " << *Chain
.Incs
[0].UserInst
<< "\n");
3154 for (const IVInc
&Inc
: Chain
) {
3155 LLVM_DEBUG(dbgs() << " Inc: " << *Inc
.UserInst
<< "\n");
3156 auto UseI
= find(Inc
.UserInst
->operands(), Inc
.IVOperand
);
3157 assert(UseI
!= Inc
.UserInst
->op_end() && "cannot find IV operand");
3158 IVIncSet
.insert(UseI
);
3162 /// Return true if the IVInc can be folded into an addressing mode.
3163 static bool canFoldIVIncExpr(const SCEV
*IncExpr
, Instruction
*UserInst
,
3164 Value
*Operand
, const TargetTransformInfo
&TTI
) {
3165 const SCEVConstant
*IncConst
= dyn_cast
<SCEVConstant
>(IncExpr
);
3166 if (!IncConst
|| !isAddressUse(TTI
, UserInst
, Operand
))
3169 if (IncConst
->getAPInt().getMinSignedBits() > 64)
3172 MemAccessTy AccessTy
= getAccessType(TTI
, UserInst
, Operand
);
3173 int64_t IncOffset
= IncConst
->getValue()->getSExtValue();
3174 if (!isAlwaysFoldable(TTI
, LSRUse::Address
, AccessTy
, /*BaseGV=*/nullptr,
3175 IncOffset
, /*HasBaseReg=*/false))
3181 /// Generate an add or subtract for each IVInc in a chain to materialize the IV
3182 /// user's operand from the previous IV user's operand.
3183 void LSRInstance::GenerateIVChain(const IVChain
&Chain
, SCEVExpander
&Rewriter
,
3184 SmallVectorImpl
<WeakTrackingVH
> &DeadInsts
) {
3185 // Find the new IVOperand for the head of the chain. It may have been replaced
3187 const IVInc
&Head
= Chain
.Incs
[0];
3188 User::op_iterator IVOpEnd
= Head
.UserInst
->op_end();
3189 // findIVOperand returns IVOpEnd if it can no longer find a valid IV user.
3190 User::op_iterator IVOpIter
= findIVOperand(Head
.UserInst
->op_begin(),
3192 Value
*IVSrc
= nullptr;
3193 while (IVOpIter
!= IVOpEnd
) {
3194 IVSrc
= getWideOperand(*IVOpIter
);
3196 // If this operand computes the expression that the chain needs, we may use
3197 // it. (Check this after setting IVSrc which is used below.)
3199 // Note that if Head.IncExpr is wider than IVSrc, then this phi is too
3200 // narrow for the chain, so we can no longer use it. We do allow using a
3201 // wider phi, assuming the LSR checked for free truncation. In that case we
3202 // should already have a truncate on this operand such that
3203 // getSCEV(IVSrc) == IncExpr.
3204 if (SE
.getSCEV(*IVOpIter
) == Head
.IncExpr
3205 || SE
.getSCEV(IVSrc
) == Head
.IncExpr
) {
3208 IVOpIter
= findIVOperand(std::next(IVOpIter
), IVOpEnd
, L
, SE
);
3210 if (IVOpIter
== IVOpEnd
) {
3211 // Gracefully give up on this chain.
3212 LLVM_DEBUG(dbgs() << "Concealed chain head: " << *Head
.UserInst
<< "\n");
3215 assert(IVSrc
&& "Failed to find IV chain source");
3217 LLVM_DEBUG(dbgs() << "Generate chain at: " << *IVSrc
<< "\n");
3218 Type
*IVTy
= IVSrc
->getType();
3219 Type
*IntTy
= SE
.getEffectiveSCEVType(IVTy
);
3220 const SCEV
*LeftOverExpr
= nullptr;
3221 for (const IVInc
&Inc
: Chain
) {
3222 Instruction
*InsertPt
= Inc
.UserInst
;
3223 if (isa
<PHINode
>(InsertPt
))
3224 InsertPt
= L
->getLoopLatch()->getTerminator();
3226 // IVOper will replace the current IV User's operand. IVSrc is the IV
3227 // value currently held in a register.
3228 Value
*IVOper
= IVSrc
;
3229 if (!Inc
.IncExpr
->isZero()) {
3230 // IncExpr was the result of subtraction of two narrow values, so must
3232 const SCEV
*IncExpr
= SE
.getNoopOrSignExtend(Inc
.IncExpr
, IntTy
);
3233 LeftOverExpr
= LeftOverExpr
?
3234 SE
.getAddExpr(LeftOverExpr
, IncExpr
) : IncExpr
;
3236 if (LeftOverExpr
&& !LeftOverExpr
->isZero()) {
3237 // Expand the IV increment.
3238 Rewriter
.clearPostInc();
3239 Value
*IncV
= Rewriter
.expandCodeFor(LeftOverExpr
, IntTy
, InsertPt
);
3240 const SCEV
*IVOperExpr
= SE
.getAddExpr(SE
.getUnknown(IVSrc
),
3241 SE
.getUnknown(IncV
));
3242 IVOper
= Rewriter
.expandCodeFor(IVOperExpr
, IVTy
, InsertPt
);
3244 // If an IV increment can't be folded, use it as the next IV value.
3245 if (!canFoldIVIncExpr(LeftOverExpr
, Inc
.UserInst
, Inc
.IVOperand
, TTI
)) {
3246 assert(IVTy
== IVOper
->getType() && "inconsistent IV increment type");
3248 LeftOverExpr
= nullptr;
3251 Type
*OperTy
= Inc
.IVOperand
->getType();
3252 if (IVTy
!= OperTy
) {
3253 assert(SE
.getTypeSizeInBits(IVTy
) >= SE
.getTypeSizeInBits(OperTy
) &&
3254 "cannot extend a chained IV");
3255 IRBuilder
<> Builder(InsertPt
);
3256 IVOper
= Builder
.CreateTruncOrBitCast(IVOper
, OperTy
, "lsr.chain");
3258 Inc
.UserInst
->replaceUsesOfWith(Inc
.IVOperand
, IVOper
);
3259 if (auto *OperandIsInstr
= dyn_cast
<Instruction
>(Inc
.IVOperand
))
3260 DeadInsts
.emplace_back(OperandIsInstr
);
3262 // If LSR created a new, wider phi, we may also replace its postinc. We only
3263 // do this if we also found a wide value for the head of the chain.
3264 if (isa
<PHINode
>(Chain
.tailUserInst())) {
3265 for (PHINode
&Phi
: L
->getHeader()->phis()) {
3266 if (!isCompatibleIVType(&Phi
, IVSrc
))
3268 Instruction
*PostIncV
= dyn_cast
<Instruction
>(
3269 Phi
.getIncomingValueForBlock(L
->getLoopLatch()));
3270 if (!PostIncV
|| (SE
.getSCEV(PostIncV
) != SE
.getSCEV(IVSrc
)))
3272 Value
*IVOper
= IVSrc
;
3273 Type
*PostIncTy
= PostIncV
->getType();
3274 if (IVTy
!= PostIncTy
) {
3275 assert(PostIncTy
->isPointerTy() && "mixing int/ptr IV types");
3276 IRBuilder
<> Builder(L
->getLoopLatch()->getTerminator());
3277 Builder
.SetCurrentDebugLocation(PostIncV
->getDebugLoc());
3278 IVOper
= Builder
.CreatePointerCast(IVSrc
, PostIncTy
, "lsr.chain");
3280 Phi
.replaceUsesOfWith(PostIncV
, IVOper
);
3281 DeadInsts
.emplace_back(PostIncV
);
3286 void LSRInstance::CollectFixupsAndInitialFormulae() {
3287 BranchInst
*ExitBranch
= nullptr;
3288 bool SaveCmp
= TTI
.canSaveCmp(L
, &ExitBranch
, &SE
, &LI
, &DT
, &AC
, &TLI
);
3290 for (const IVStrideUse
&U
: IU
) {
3291 Instruction
*UserInst
= U
.getUser();
3292 // Skip IV users that are part of profitable IV Chains.
3293 User::op_iterator UseI
=
3294 find(UserInst
->operands(), U
.getOperandValToReplace());
3295 assert(UseI
!= UserInst
->op_end() && "cannot find IV operand");
3296 if (IVIncSet
.count(UseI
)) {
3297 LLVM_DEBUG(dbgs() << "Use is in profitable chain: " << **UseI
<< '\n');
3301 LSRUse::KindType Kind
= LSRUse::Basic
;
3302 MemAccessTy AccessTy
;
3303 if (isAddressUse(TTI
, UserInst
, U
.getOperandValToReplace())) {
3304 Kind
= LSRUse::Address
;
3305 AccessTy
= getAccessType(TTI
, UserInst
, U
.getOperandValToReplace());
3308 const SCEV
*S
= IU
.getExpr(U
);
3309 PostIncLoopSet TmpPostIncLoops
= U
.getPostIncLoops();
3311 // Equality (== and !=) ICmps are special. We can rewrite (i == N) as
3312 // (N - i == 0), and this allows (N - i) to be the expression that we work
3313 // with rather than just N or i, so we can consider the register
3314 // requirements for both N and i at the same time. Limiting this code to
3315 // equality icmps is not a problem because all interesting loops use
3316 // equality icmps, thanks to IndVarSimplify.
3317 if (ICmpInst
*CI
= dyn_cast
<ICmpInst
>(UserInst
)) {
3318 // If CI can be saved in some target, like replaced inside hardware loop
3319 // in PowerPC, no need to generate initial formulae for it.
3320 if (SaveCmp
&& CI
== dyn_cast
<ICmpInst
>(ExitBranch
->getCondition()))
3322 if (CI
->isEquality()) {
3323 // Swap the operands if needed to put the OperandValToReplace on the
3324 // left, for consistency.
3325 Value
*NV
= CI
->getOperand(1);
3326 if (NV
== U
.getOperandValToReplace()) {
3327 CI
->setOperand(1, CI
->getOperand(0));
3328 CI
->setOperand(0, NV
);
3329 NV
= CI
->getOperand(1);
3333 // x == y --> x - y == 0
3334 const SCEV
*N
= SE
.getSCEV(NV
);
3335 if (SE
.isLoopInvariant(N
, L
) && isSafeToExpand(N
, SE
) &&
3336 (!NV
->getType()->isPointerTy() ||
3337 SE
.getPointerBase(N
) == SE
.getPointerBase(S
))) {
3338 // S is normalized, so normalize N before folding it into S
3339 // to keep the result normalized.
3340 N
= normalizeForPostIncUse(N
, TmpPostIncLoops
, SE
);
3341 Kind
= LSRUse::ICmpZero
;
3342 S
= SE
.getMinusSCEV(N
, S
);
3345 // -1 and the negations of all interesting strides (except the negation
3346 // of -1) are now also interesting.
3347 for (size_t i
= 0, e
= Factors
.size(); i
!= e
; ++i
)
3348 if (Factors
[i
] != -1)
3349 Factors
.insert(-(uint64_t)Factors
[i
]);
3354 // Get or create an LSRUse.
3355 std::pair
<size_t, int64_t> P
= getUse(S
, Kind
, AccessTy
);
3356 size_t LUIdx
= P
.first
;
3357 int64_t Offset
= P
.second
;
3358 LSRUse
&LU
= Uses
[LUIdx
];
3360 // Record the fixup.
3361 LSRFixup
&LF
= LU
.getNewFixup();
3362 LF
.UserInst
= UserInst
;
3363 LF
.OperandValToReplace
= U
.getOperandValToReplace();
3364 LF
.PostIncLoops
= TmpPostIncLoops
;
3366 LU
.AllFixupsOutsideLoop
&= LF
.isUseFullyOutsideLoop(L
);
3368 if (!LU
.WidestFixupType
||
3369 SE
.getTypeSizeInBits(LU
.WidestFixupType
) <
3370 SE
.getTypeSizeInBits(LF
.OperandValToReplace
->getType()))
3371 LU
.WidestFixupType
= LF
.OperandValToReplace
->getType();
3373 // If this is the first use of this LSRUse, give it a formula.
3374 if (LU
.Formulae
.empty()) {
3375 InsertInitialFormula(S
, LU
, LUIdx
);
3376 CountRegisters(LU
.Formulae
.back(), LUIdx
);
3380 LLVM_DEBUG(print_fixups(dbgs()));
3383 /// Insert a formula for the given expression into the given use, separating out
3384 /// loop-variant portions from loop-invariant and loop-computable portions.
3386 LSRInstance::InsertInitialFormula(const SCEV
*S
, LSRUse
&LU
, size_t LUIdx
) {
3387 // Mark uses whose expressions cannot be expanded.
3388 if (!isSafeToExpand(S
, SE
))
3389 LU
.RigidFormula
= true;
3392 F
.initialMatch(S
, L
, SE
);
3393 bool Inserted
= InsertFormula(LU
, LUIdx
, F
);
3394 assert(Inserted
&& "Initial formula already exists!"); (void)Inserted
;
3397 /// Insert a simple single-register formula for the given expression into the
3400 LSRInstance::InsertSupplementalFormula(const SCEV
*S
,
3401 LSRUse
&LU
, size_t LUIdx
) {
3403 F
.BaseRegs
.push_back(S
);
3404 F
.HasBaseReg
= true;
3405 bool Inserted
= InsertFormula(LU
, LUIdx
, F
);
3406 assert(Inserted
&& "Supplemental formula already exists!"); (void)Inserted
;
3409 /// Note which registers are used by the given formula, updating RegUses.
3410 void LSRInstance::CountRegisters(const Formula
&F
, size_t LUIdx
) {
3412 RegUses
.countRegister(F
.ScaledReg
, LUIdx
);
3413 for (const SCEV
*BaseReg
: F
.BaseRegs
)
3414 RegUses
.countRegister(BaseReg
, LUIdx
);
3417 /// If the given formula has not yet been inserted, add it to the list, and
3418 /// return true. Return false otherwise.
3419 bool LSRInstance::InsertFormula(LSRUse
&LU
, unsigned LUIdx
, const Formula
&F
) {
3420 // Do not insert formula that we will not be able to expand.
3421 assert(isLegalUse(TTI
, LU
.MinOffset
, LU
.MaxOffset
, LU
.Kind
, LU
.AccessTy
, F
) &&
3422 "Formula is illegal");
3424 if (!LU
.InsertFormula(F
, *L
))
3427 CountRegisters(F
, LUIdx
);
3431 /// Check for other uses of loop-invariant values which we're tracking. These
3432 /// other uses will pin these values in registers, making them less profitable
3433 /// for elimination.
3434 /// TODO: This currently misses non-constant addrec step registers.
3435 /// TODO: Should this give more weight to users inside the loop?
3437 LSRInstance::CollectLoopInvariantFixupsAndFormulae() {
3438 SmallVector
<const SCEV
*, 8> Worklist(RegUses
.begin(), RegUses
.end());
3439 SmallPtrSet
<const SCEV
*, 32> Visited
;
3441 while (!Worklist
.empty()) {
3442 const SCEV
*S
= Worklist
.pop_back_val();
3444 // Don't process the same SCEV twice
3445 if (!Visited
.insert(S
).second
)
3448 if (const SCEVNAryExpr
*N
= dyn_cast
<SCEVNAryExpr
>(S
))
3449 Worklist
.append(N
->op_begin(), N
->op_end());
3450 else if (const SCEVIntegralCastExpr
*C
= dyn_cast
<SCEVIntegralCastExpr
>(S
))
3451 Worklist
.push_back(C
->getOperand());
3452 else if (const SCEVUDivExpr
*D
= dyn_cast
<SCEVUDivExpr
>(S
)) {
3453 Worklist
.push_back(D
->getLHS());
3454 Worklist
.push_back(D
->getRHS());
3455 } else if (const SCEVUnknown
*US
= dyn_cast
<SCEVUnknown
>(S
)) {
3456 const Value
*V
= US
->getValue();
3457 if (const Instruction
*Inst
= dyn_cast
<Instruction
>(V
)) {
3458 // Look for instructions defined outside the loop.
3459 if (L
->contains(Inst
)) continue;
3460 } else if (isa
<UndefValue
>(V
))
3461 // Undef doesn't have a live range, so it doesn't matter.
3463 for (const Use
&U
: V
->uses()) {
3464 const Instruction
*UserInst
= dyn_cast
<Instruction
>(U
.getUser());
3465 // Ignore non-instructions.
3468 // Don't bother if the instruction is an EHPad.
3469 if (UserInst
->isEHPad())
3471 // Ignore instructions in other functions (as can happen with
3473 if (UserInst
->getParent()->getParent() != L
->getHeader()->getParent())
3475 // Ignore instructions not dominated by the loop.
3476 const BasicBlock
*UseBB
= !isa
<PHINode
>(UserInst
) ?
3477 UserInst
->getParent() :
3478 cast
<PHINode
>(UserInst
)->getIncomingBlock(
3479 PHINode::getIncomingValueNumForOperand(U
.getOperandNo()));
3480 if (!DT
.dominates(L
->getHeader(), UseBB
))
3482 // Don't bother if the instruction is in a BB which ends in an EHPad.
3483 if (UseBB
->getTerminator()->isEHPad())
3485 // Don't bother rewriting PHIs in catchswitch blocks.
3486 if (isa
<CatchSwitchInst
>(UserInst
->getParent()->getTerminator()))
3488 // Ignore uses which are part of other SCEV expressions, to avoid
3489 // analyzing them multiple times.
3490 if (SE
.isSCEVable(UserInst
->getType())) {
3491 const SCEV
*UserS
= SE
.getSCEV(const_cast<Instruction
*>(UserInst
));
3492 // If the user is a no-op, look through to its uses.
3493 if (!isa
<SCEVUnknown
>(UserS
))
3497 SE
.getUnknown(const_cast<Instruction
*>(UserInst
)));
3501 // Ignore icmp instructions which are already being analyzed.
3502 if (const ICmpInst
*ICI
= dyn_cast
<ICmpInst
>(UserInst
)) {
3503 unsigned OtherIdx
= !U
.getOperandNo();
3504 Value
*OtherOp
= const_cast<Value
*>(ICI
->getOperand(OtherIdx
));
3505 if (SE
.hasComputableLoopEvolution(SE
.getSCEV(OtherOp
), L
))
3509 std::pair
<size_t, int64_t> P
= getUse(
3510 S
, LSRUse::Basic
, MemAccessTy());
3511 size_t LUIdx
= P
.first
;
3512 int64_t Offset
= P
.second
;
3513 LSRUse
&LU
= Uses
[LUIdx
];
3514 LSRFixup
&LF
= LU
.getNewFixup();
3515 LF
.UserInst
= const_cast<Instruction
*>(UserInst
);
3516 LF
.OperandValToReplace
= U
;
3518 LU
.AllFixupsOutsideLoop
&= LF
.isUseFullyOutsideLoop(L
);
3519 if (!LU
.WidestFixupType
||
3520 SE
.getTypeSizeInBits(LU
.WidestFixupType
) <
3521 SE
.getTypeSizeInBits(LF
.OperandValToReplace
->getType()))
3522 LU
.WidestFixupType
= LF
.OperandValToReplace
->getType();
3523 InsertSupplementalFormula(US
, LU
, LUIdx
);
3524 CountRegisters(LU
.Formulae
.back(), Uses
.size() - 1);
3531 /// Split S into subexpressions which can be pulled out into separate
3532 /// registers. If C is non-null, multiply each subexpression by C.
3534 /// Return remainder expression after factoring the subexpressions captured by
3535 /// Ops. If Ops is complete, return NULL.
3536 static const SCEV
*CollectSubexprs(const SCEV
*S
, const SCEVConstant
*C
,
3537 SmallVectorImpl
<const SCEV
*> &Ops
,
3539 ScalarEvolution
&SE
,
3540 unsigned Depth
= 0) {
3541 // Arbitrarily cap recursion to protect compile time.
3545 if (const SCEVAddExpr
*Add
= dyn_cast
<SCEVAddExpr
>(S
)) {
3546 // Break out add operands.
3547 for (const SCEV
*S
: Add
->operands()) {
3548 const SCEV
*Remainder
= CollectSubexprs(S
, C
, Ops
, L
, SE
, Depth
+1);
3550 Ops
.push_back(C
? SE
.getMulExpr(C
, Remainder
) : Remainder
);
3553 } else if (const SCEVAddRecExpr
*AR
= dyn_cast
<SCEVAddRecExpr
>(S
)) {
3554 // Split a non-zero base out of an addrec.
3555 if (AR
->getStart()->isZero() || !AR
->isAffine())
3558 const SCEV
*Remainder
= CollectSubexprs(AR
->getStart(),
3559 C
, Ops
, L
, SE
, Depth
+1);
3560 // Split the non-zero AddRec unless it is part of a nested recurrence that
3561 // does not pertain to this loop.
3562 if (Remainder
&& (AR
->getLoop() == L
|| !isa
<SCEVAddRecExpr
>(Remainder
))) {
3563 Ops
.push_back(C
? SE
.getMulExpr(C
, Remainder
) : Remainder
);
3564 Remainder
= nullptr;
3566 if (Remainder
!= AR
->getStart()) {
3568 Remainder
= SE
.getConstant(AR
->getType(), 0);
3569 return SE
.getAddRecExpr(Remainder
,
3570 AR
->getStepRecurrence(SE
),
3572 //FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
3575 } else if (const SCEVMulExpr
*Mul
= dyn_cast
<SCEVMulExpr
>(S
)) {
3576 // Break (C * (a + b + c)) into C*a + C*b + C*c.
3577 if (Mul
->getNumOperands() != 2)
3579 if (const SCEVConstant
*Op0
=
3580 dyn_cast
<SCEVConstant
>(Mul
->getOperand(0))) {
3581 C
= C
? cast
<SCEVConstant
>(SE
.getMulExpr(C
, Op0
)) : Op0
;
3582 const SCEV
*Remainder
=
3583 CollectSubexprs(Mul
->getOperand(1), C
, Ops
, L
, SE
, Depth
+1);
3585 Ops
.push_back(SE
.getMulExpr(C
, Remainder
));
3592 /// Return true if the SCEV represents a value that may end up as a
3593 /// post-increment operation.
3594 static bool mayUsePostIncMode(const TargetTransformInfo
&TTI
,
3595 LSRUse
&LU
, const SCEV
*S
, const Loop
*L
,
3596 ScalarEvolution
&SE
) {
3597 if (LU
.Kind
!= LSRUse::Address
||
3598 !LU
.AccessTy
.getType()->isIntOrIntVectorTy())
3600 const SCEVAddRecExpr
*AR
= dyn_cast
<SCEVAddRecExpr
>(S
);
3603 const SCEV
*LoopStep
= AR
->getStepRecurrence(SE
);
3604 if (!isa
<SCEVConstant
>(LoopStep
))
3606 // Check if a post-indexed load/store can be used.
3607 if (TTI
.isIndexedLoadLegal(TTI
.MIM_PostInc
, AR
->getType()) ||
3608 TTI
.isIndexedStoreLegal(TTI
.MIM_PostInc
, AR
->getType())) {
3609 const SCEV
*LoopStart
= AR
->getStart();
3610 if (!isa
<SCEVConstant
>(LoopStart
) && SE
.isLoopInvariant(LoopStart
, L
))
3616 /// Helper function for LSRInstance::GenerateReassociations.
3617 void LSRInstance::GenerateReassociationsImpl(LSRUse
&LU
, unsigned LUIdx
,
3618 const Formula
&Base
,
3619 unsigned Depth
, size_t Idx
,
3621 const SCEV
*BaseReg
= IsScaledReg
? Base
.ScaledReg
: Base
.BaseRegs
[Idx
];
3622 // Don't generate reassociations for the base register of a value that
3623 // may generate a post-increment operator. The reason is that the
3624 // reassociations cause extra base+register formula to be created,
3625 // and possibly chosen, but the post-increment is more efficient.
3626 if (AMK
== TTI::AMK_PostIndexed
&& mayUsePostIncMode(TTI
, LU
, BaseReg
, L
, SE
))
3628 SmallVector
<const SCEV
*, 8> AddOps
;
3629 const SCEV
*Remainder
= CollectSubexprs(BaseReg
, nullptr, AddOps
, L
, SE
);
3631 AddOps
.push_back(Remainder
);
3633 if (AddOps
.size() == 1)
3636 for (SmallVectorImpl
<const SCEV
*>::const_iterator J
= AddOps
.begin(),
3639 // Loop-variant "unknown" values are uninteresting; we won't be able to
3640 // do anything meaningful with them.
3641 if (isa
<SCEVUnknown
>(*J
) && !SE
.isLoopInvariant(*J
, L
))
3644 // Don't pull a constant into a register if the constant could be folded
3645 // into an immediate field.
3646 if (isAlwaysFoldable(TTI
, SE
, LU
.MinOffset
, LU
.MaxOffset
, LU
.Kind
,
3647 LU
.AccessTy
, *J
, Base
.getNumRegs() > 1))
3650 // Collect all operands except *J.
3651 SmallVector
<const SCEV
*, 8> InnerAddOps(
3652 ((const SmallVector
<const SCEV
*, 8> &)AddOps
).begin(), J
);
3653 InnerAddOps
.append(std::next(J
),
3654 ((const SmallVector
<const SCEV
*, 8> &)AddOps
).end());
3656 // Don't leave just a constant behind in a register if the constant could
3657 // be folded into an immediate field.
3658 if (InnerAddOps
.size() == 1 &&
3659 isAlwaysFoldable(TTI
, SE
, LU
.MinOffset
, LU
.MaxOffset
, LU
.Kind
,
3660 LU
.AccessTy
, InnerAddOps
[0], Base
.getNumRegs() > 1))
3663 const SCEV
*InnerSum
= SE
.getAddExpr(InnerAddOps
);
3664 if (InnerSum
->isZero())
3668 // Add the remaining pieces of the add back into the new formula.
3669 const SCEVConstant
*InnerSumSC
= dyn_cast
<SCEVConstant
>(InnerSum
);
3670 if (InnerSumSC
&& SE
.getTypeSizeInBits(InnerSumSC
->getType()) <= 64 &&
3671 TTI
.isLegalAddImmediate((uint64_t)F
.UnfoldedOffset
+
3672 InnerSumSC
->getValue()->getZExtValue())) {
3674 (uint64_t)F
.UnfoldedOffset
+ InnerSumSC
->getValue()->getZExtValue();
3676 F
.ScaledReg
= nullptr;
3678 F
.BaseRegs
.erase(F
.BaseRegs
.begin() + Idx
);
3679 } else if (IsScaledReg
)
3680 F
.ScaledReg
= InnerSum
;
3682 F
.BaseRegs
[Idx
] = InnerSum
;
3684 // Add J as its own register, or an unfolded immediate.
3685 const SCEVConstant
*SC
= dyn_cast
<SCEVConstant
>(*J
);
3686 if (SC
&& SE
.getTypeSizeInBits(SC
->getType()) <= 64 &&
3687 TTI
.isLegalAddImmediate((uint64_t)F
.UnfoldedOffset
+
3688 SC
->getValue()->getZExtValue()))
3690 (uint64_t)F
.UnfoldedOffset
+ SC
->getValue()->getZExtValue();
3692 F
.BaseRegs
.push_back(*J
);
3693 // We may have changed the number of register in base regs, adjust the
3694 // formula accordingly.
3697 if (InsertFormula(LU
, LUIdx
, F
))
3698 // If that formula hadn't been seen before, recurse to find more like
3700 // Add check on Log16(AddOps.size()) - same as Log2_32(AddOps.size()) >> 2)
3701 // Because just Depth is not enough to bound compile time.
3702 // This means that every time AddOps.size() is greater 16^x we will add
3704 GenerateReassociations(LU
, LUIdx
, LU
.Formulae
.back(),
3705 Depth
+ 1 + (Log2_32(AddOps
.size()) >> 2));
3709 /// Split out subexpressions from adds and the bases of addrecs.
3710 void LSRInstance::GenerateReassociations(LSRUse
&LU
, unsigned LUIdx
,
3711 Formula Base
, unsigned Depth
) {
3712 assert(Base
.isCanonical(*L
) && "Input must be in the canonical form");
3713 // Arbitrarily cap recursion to protect compile time.
3717 for (size_t i
= 0, e
= Base
.BaseRegs
.size(); i
!= e
; ++i
)
3718 GenerateReassociationsImpl(LU
, LUIdx
, Base
, Depth
, i
);
3720 if (Base
.Scale
== 1)
3721 GenerateReassociationsImpl(LU
, LUIdx
, Base
, Depth
,
3722 /* Idx */ -1, /* IsScaledReg */ true);
3725 /// Generate a formula consisting of all of the loop-dominating registers added
3726 /// into a single register.
3727 void LSRInstance::GenerateCombinations(LSRUse
&LU
, unsigned LUIdx
,
3729 // This method is only interesting on a plurality of registers.
3730 if (Base
.BaseRegs
.size() + (Base
.Scale
== 1) +
3731 (Base
.UnfoldedOffset
!= 0) <= 1)
3734 // Flatten the representation, i.e., reg1 + 1*reg2 => reg1 + reg2, before
3735 // processing the formula.
3737 SmallVector
<const SCEV
*, 4> Ops
;
3738 Formula NewBase
= Base
;
3739 NewBase
.BaseRegs
.clear();
3740 Type
*CombinedIntegerType
= nullptr;
3741 for (const SCEV
*BaseReg
: Base
.BaseRegs
) {
3742 if (SE
.properlyDominates(BaseReg
, L
->getHeader()) &&
3743 !SE
.hasComputableLoopEvolution(BaseReg
, L
)) {
3744 if (!CombinedIntegerType
)
3745 CombinedIntegerType
= SE
.getEffectiveSCEVType(BaseReg
->getType());
3746 Ops
.push_back(BaseReg
);
3749 NewBase
.BaseRegs
.push_back(BaseReg
);
3752 // If no register is relevant, we're done.
3753 if (Ops
.size() == 0)
3756 // Utility function for generating the required variants of the combined
3758 auto GenerateFormula
= [&](const SCEV
*Sum
) {
3759 Formula F
= NewBase
;
3761 // TODO: If Sum is zero, it probably means ScalarEvolution missed an
3762 // opportunity to fold something. For now, just ignore such cases
3763 // rather than proceed with zero in a register.
3767 F
.BaseRegs
.push_back(Sum
);
3769 (void)InsertFormula(LU
, LUIdx
, F
);
3772 // If we collected at least two registers, generate a formula combining them.
3773 if (Ops
.size() > 1) {
3774 SmallVector
<const SCEV
*, 4> OpsCopy(Ops
); // Don't let SE modify Ops.
3775 GenerateFormula(SE
.getAddExpr(OpsCopy
));
3778 // If we have an unfolded offset, generate a formula combining it with the
3779 // registers collected.
3780 if (NewBase
.UnfoldedOffset
) {
3781 assert(CombinedIntegerType
&& "Missing a type for the unfolded offset");
3782 Ops
.push_back(SE
.getConstant(CombinedIntegerType
, NewBase
.UnfoldedOffset
,
3784 NewBase
.UnfoldedOffset
= 0;
3785 GenerateFormula(SE
.getAddExpr(Ops
));
3789 /// Helper function for LSRInstance::GenerateSymbolicOffsets.
3790 void LSRInstance::GenerateSymbolicOffsetsImpl(LSRUse
&LU
, unsigned LUIdx
,
3791 const Formula
&Base
, size_t Idx
,
3793 const SCEV
*G
= IsScaledReg
? Base
.ScaledReg
: Base
.BaseRegs
[Idx
];
3794 GlobalValue
*GV
= ExtractSymbol(G
, SE
);
3795 if (G
->isZero() || !GV
)
3799 if (!isLegalUse(TTI
, LU
.MinOffset
, LU
.MaxOffset
, LU
.Kind
, LU
.AccessTy
, F
))
3804 F
.BaseRegs
[Idx
] = G
;
3805 (void)InsertFormula(LU
, LUIdx
, F
);
3808 /// Generate reuse formulae using symbolic offsets.
3809 void LSRInstance::GenerateSymbolicOffsets(LSRUse
&LU
, unsigned LUIdx
,
3811 // We can't add a symbolic offset if the address already contains one.
3812 if (Base
.BaseGV
) return;
3814 for (size_t i
= 0, e
= Base
.BaseRegs
.size(); i
!= e
; ++i
)
3815 GenerateSymbolicOffsetsImpl(LU
, LUIdx
, Base
, i
);
3816 if (Base
.Scale
== 1)
3817 GenerateSymbolicOffsetsImpl(LU
, LUIdx
, Base
, /* Idx */ -1,
3818 /* IsScaledReg */ true);
3821 /// Helper function for LSRInstance::GenerateConstantOffsets.
3822 void LSRInstance::GenerateConstantOffsetsImpl(
3823 LSRUse
&LU
, unsigned LUIdx
, const Formula
&Base
,
3824 const SmallVectorImpl
<int64_t> &Worklist
, size_t Idx
, bool IsScaledReg
) {
3826 auto GenerateOffset
= [&](const SCEV
*G
, int64_t Offset
) {
3828 F
.BaseOffset
= (uint64_t)Base
.BaseOffset
- Offset
;
3830 if (isLegalUse(TTI
, LU
.MinOffset
, LU
.MaxOffset
, LU
.Kind
, LU
.AccessTy
, F
)) {
3831 // Add the offset to the base register.
3832 const SCEV
*NewG
= SE
.getAddExpr(SE
.getConstant(G
->getType(), Offset
), G
);
3833 // If it cancelled out, drop the base register, otherwise update it.
3834 if (NewG
->isZero()) {
3837 F
.ScaledReg
= nullptr;
3839 F
.deleteBaseReg(F
.BaseRegs
[Idx
]);
3841 } else if (IsScaledReg
)
3844 F
.BaseRegs
[Idx
] = NewG
;
3846 (void)InsertFormula(LU
, LUIdx
, F
);
3850 const SCEV
*G
= IsScaledReg
? Base
.ScaledReg
: Base
.BaseRegs
[Idx
];
3852 // With constant offsets and constant steps, we can generate pre-inc
3853 // accesses by having the offset equal the step. So, for access #0 with a
3854 // step of 8, we generate a G - 8 base which would require the first access
3855 // to be ((G - 8) + 8),+,8. The pre-indexed access then updates the pointer
3856 // for itself and hopefully becomes the base for other accesses. This means
3857 // means that a single pre-indexed access can be generated to become the new
3858 // base pointer for each iteration of the loop, resulting in no extra add/sub
3859 // instructions for pointer updating.
3860 if (AMK
== TTI::AMK_PreIndexed
&& LU
.Kind
== LSRUse::Address
) {
3861 if (auto *GAR
= dyn_cast
<SCEVAddRecExpr
>(G
)) {
3863 dyn_cast
<SCEVConstant
>(GAR
->getStepRecurrence(SE
))) {
3864 const APInt
&StepInt
= StepRec
->getAPInt();
3865 int64_t Step
= StepInt
.isNegative() ?
3866 StepInt
.getSExtValue() : StepInt
.getZExtValue();
3868 for (int64_t Offset
: Worklist
) {
3870 GenerateOffset(G
, Offset
);
3875 for (int64_t Offset
: Worklist
)
3876 GenerateOffset(G
, Offset
);
3878 int64_t Imm
= ExtractImmediate(G
, SE
);
3879 if (G
->isZero() || Imm
== 0)
3882 F
.BaseOffset
= (uint64_t)F
.BaseOffset
+ Imm
;
3883 if (!isLegalUse(TTI
, LU
.MinOffset
, LU
.MaxOffset
, LU
.Kind
, LU
.AccessTy
, F
))
3888 F
.BaseRegs
[Idx
] = G
;
3889 // We may generate non canonical Formula if G is a recurrent expr reg
3890 // related with current loop while F.ScaledReg is not.
3893 (void)InsertFormula(LU
, LUIdx
, F
);
3896 /// GenerateConstantOffsets - Generate reuse formulae using symbolic offsets.
3897 void LSRInstance::GenerateConstantOffsets(LSRUse
&LU
, unsigned LUIdx
,
3899 // TODO: For now, just add the min and max offset, because it usually isn't
3900 // worthwhile looking at everything inbetween.
3901 SmallVector
<int64_t, 2> Worklist
;
3902 Worklist
.push_back(LU
.MinOffset
);
3903 if (LU
.MaxOffset
!= LU
.MinOffset
)
3904 Worklist
.push_back(LU
.MaxOffset
);
3906 for (size_t i
= 0, e
= Base
.BaseRegs
.size(); i
!= e
; ++i
)
3907 GenerateConstantOffsetsImpl(LU
, LUIdx
, Base
, Worklist
, i
);
3908 if (Base
.Scale
== 1)
3909 GenerateConstantOffsetsImpl(LU
, LUIdx
, Base
, Worklist
, /* Idx */ -1,
3910 /* IsScaledReg */ true);
3913 /// For ICmpZero, check to see if we can scale up the comparison. For example, x
3914 /// == y -> x*c == y*c.
3915 void LSRInstance::GenerateICmpZeroScales(LSRUse
&LU
, unsigned LUIdx
,
3917 if (LU
.Kind
!= LSRUse::ICmpZero
) return;
3919 // Determine the integer type for the base formula.
3920 Type
*IntTy
= Base
.getType();
3922 if (SE
.getTypeSizeInBits(IntTy
) > 64) return;
3924 // Don't do this if there is more than one offset.
3925 if (LU
.MinOffset
!= LU
.MaxOffset
) return;
3927 // Check if transformation is valid. It is illegal to multiply pointer.
3928 if (Base
.ScaledReg
&& Base
.ScaledReg
->getType()->isPointerTy())
3930 for (const SCEV
*BaseReg
: Base
.BaseRegs
)
3931 if (BaseReg
->getType()->isPointerTy())
3933 assert(!Base
.BaseGV
&& "ICmpZero use is not legal!");
3935 // Check each interesting stride.
3936 for (int64_t Factor
: Factors
) {
3937 // Check that the multiplication doesn't overflow.
3938 if (Base
.BaseOffset
== std::numeric_limits
<int64_t>::min() && Factor
== -1)
3940 int64_t NewBaseOffset
= (uint64_t)Base
.BaseOffset
* Factor
;
3941 assert(Factor
!= 0 && "Zero factor not expected!");
3942 if (NewBaseOffset
/ Factor
!= Base
.BaseOffset
)
3944 // If the offset will be truncated at this use, check that it is in bounds.
3945 if (!IntTy
->isPointerTy() &&
3946 !ConstantInt::isValueValidForType(IntTy
, NewBaseOffset
))
3949 // Check that multiplying with the use offset doesn't overflow.
3950 int64_t Offset
= LU
.MinOffset
;
3951 if (Offset
== std::numeric_limits
<int64_t>::min() && Factor
== -1)
3953 Offset
= (uint64_t)Offset
* Factor
;
3954 if (Offset
/ Factor
!= LU
.MinOffset
)
3956 // If the offset will be truncated at this use, check that it is in bounds.
3957 if (!IntTy
->isPointerTy() &&
3958 !ConstantInt::isValueValidForType(IntTy
, Offset
))
3962 F
.BaseOffset
= NewBaseOffset
;
3964 // Check that this scale is legal.
3965 if (!isLegalUse(TTI
, Offset
, Offset
, LU
.Kind
, LU
.AccessTy
, F
))
3968 // Compensate for the use having MinOffset built into it.
3969 F
.BaseOffset
= (uint64_t)F
.BaseOffset
+ Offset
- LU
.MinOffset
;
3971 const SCEV
*FactorS
= SE
.getConstant(IntTy
, Factor
);
3973 // Check that multiplying with each base register doesn't overflow.
3974 for (size_t i
= 0, e
= F
.BaseRegs
.size(); i
!= e
; ++i
) {
3975 F
.BaseRegs
[i
] = SE
.getMulExpr(F
.BaseRegs
[i
], FactorS
);
3976 if (getExactSDiv(F
.BaseRegs
[i
], FactorS
, SE
) != Base
.BaseRegs
[i
])
3980 // Check that multiplying with the scaled register doesn't overflow.
3982 F
.ScaledReg
= SE
.getMulExpr(F
.ScaledReg
, FactorS
);
3983 if (getExactSDiv(F
.ScaledReg
, FactorS
, SE
) != Base
.ScaledReg
)
3987 // Check that multiplying with the unfolded offset doesn't overflow.
3988 if (F
.UnfoldedOffset
!= 0) {
3989 if (F
.UnfoldedOffset
== std::numeric_limits
<int64_t>::min() &&
3992 F
.UnfoldedOffset
= (uint64_t)F
.UnfoldedOffset
* Factor
;
3993 if (F
.UnfoldedOffset
/ Factor
!= Base
.UnfoldedOffset
)
3995 // If the offset will be truncated, check that it is in bounds.
3996 if (!IntTy
->isPointerTy() &&
3997 !ConstantInt::isValueValidForType(IntTy
, F
.UnfoldedOffset
))
4001 // If we make it here and it's legal, add it.
4002 (void)InsertFormula(LU
, LUIdx
, F
);
4007 /// Generate stride factor reuse formulae by making use of scaled-offset address
4008 /// modes, for example.
4009 void LSRInstance::GenerateScales(LSRUse
&LU
, unsigned LUIdx
, Formula Base
) {
4010 // Determine the integer type for the base formula.
4011 Type
*IntTy
= Base
.getType();
4014 // If this Formula already has a scaled register, we can't add another one.
4015 // Try to unscale the formula to generate a better scale.
4016 if (Base
.Scale
!= 0 && !Base
.unscale())
4019 assert(Base
.Scale
== 0 && "unscale did not did its job!");
4021 // Check each interesting stride.
4022 for (int64_t Factor
: Factors
) {
4023 Base
.Scale
= Factor
;
4024 Base
.HasBaseReg
= Base
.BaseRegs
.size() > 1;
4025 // Check whether this scale is going to be legal.
4026 if (!isLegalUse(TTI
, LU
.MinOffset
, LU
.MaxOffset
, LU
.Kind
, LU
.AccessTy
,
4028 // As a special-case, handle special out-of-loop Basic users specially.
4029 // TODO: Reconsider this special case.
4030 if (LU
.Kind
== LSRUse::Basic
&&
4031 isLegalUse(TTI
, LU
.MinOffset
, LU
.MaxOffset
, LSRUse::Special
,
4032 LU
.AccessTy
, Base
) &&
4033 LU
.AllFixupsOutsideLoop
)
4034 LU
.Kind
= LSRUse::Special
;
4038 // For an ICmpZero, negating a solitary base register won't lead to
4040 if (LU
.Kind
== LSRUse::ICmpZero
&&
4041 !Base
.HasBaseReg
&& Base
.BaseOffset
== 0 && !Base
.BaseGV
)
4043 // For each addrec base reg, if its loop is current loop, apply the scale.
4044 for (size_t i
= 0, e
= Base
.BaseRegs
.size(); i
!= e
; ++i
) {
4045 const SCEVAddRecExpr
*AR
= dyn_cast
<SCEVAddRecExpr
>(Base
.BaseRegs
[i
]);
4046 if (AR
&& (AR
->getLoop() == L
|| LU
.AllFixupsOutsideLoop
)) {
4047 const SCEV
*FactorS
= SE
.getConstant(IntTy
, Factor
);
4048 if (FactorS
->isZero())
4050 // Divide out the factor, ignoring high bits, since we'll be
4051 // scaling the value back up in the end.
4052 if (const SCEV
*Quotient
= getExactSDiv(AR
, FactorS
, SE
, true)) {
4053 // TODO: This could be optimized to avoid all the copying.
4055 F
.ScaledReg
= Quotient
;
4056 F
.deleteBaseReg(F
.BaseRegs
[i
]);
4057 // The canonical representation of 1*reg is reg, which is already in
4058 // Base. In that case, do not try to insert the formula, it will be
4060 if (F
.Scale
== 1 && (F
.BaseRegs
.empty() ||
4061 (AR
->getLoop() != L
&& LU
.AllFixupsOutsideLoop
)))
4063 // If AllFixupsOutsideLoop is true and F.Scale is 1, we may generate
4064 // non canonical Formula with ScaledReg's loop not being L.
4065 if (F
.Scale
== 1 && LU
.AllFixupsOutsideLoop
)
4067 (void)InsertFormula(LU
, LUIdx
, F
);
4074 /// Generate reuse formulae from different IV types.
4075 void LSRInstance::GenerateTruncates(LSRUse
&LU
, unsigned LUIdx
, Formula Base
) {
4076 // Don't bother truncating symbolic values.
4077 if (Base
.BaseGV
) return;
4079 // Determine the integer type for the base formula.
4080 Type
*DstTy
= Base
.getType();
4082 if (DstTy
->isPointerTy())
4085 // It is invalid to extend a pointer type so exit early if ScaledReg or
4086 // any of the BaseRegs are pointers.
4087 if (Base
.ScaledReg
&& Base
.ScaledReg
->getType()->isPointerTy())
4089 if (any_of(Base
.BaseRegs
,
4090 [](const SCEV
*S
) { return S
->getType()->isPointerTy(); }))
4093 for (Type
*SrcTy
: Types
) {
4094 if (SrcTy
!= DstTy
&& TTI
.isTruncateFree(SrcTy
, DstTy
)) {
4097 // Sometimes SCEV is able to prove zero during ext transform. It may
4098 // happen if SCEV did not do all possible transforms while creating the
4099 // initial node (maybe due to depth limitations), but it can do them while
4102 const SCEV
*NewScaledReg
= SE
.getAnyExtendExpr(F
.ScaledReg
, SrcTy
);
4103 if (NewScaledReg
->isZero())
4105 F
.ScaledReg
= NewScaledReg
;
4107 bool HasZeroBaseReg
= false;
4108 for (const SCEV
*&BaseReg
: F
.BaseRegs
) {
4109 const SCEV
*NewBaseReg
= SE
.getAnyExtendExpr(BaseReg
, SrcTy
);
4110 if (NewBaseReg
->isZero()) {
4111 HasZeroBaseReg
= true;
4114 BaseReg
= NewBaseReg
;
4119 // TODO: This assumes we've done basic processing on all uses and
4120 // have an idea what the register usage is.
4121 if (!F
.hasRegsUsedByUsesOtherThan(LUIdx
, RegUses
))
4125 (void)InsertFormula(LU
, LUIdx
, F
);
4132 /// Helper class for GenerateCrossUseConstantOffsets. It's used to defer
4133 /// modifications so that the search phase doesn't have to worry about the data
4134 /// structures moving underneath it.
4138 const SCEV
*OrigReg
;
4140 WorkItem(size_t LI
, int64_t I
, const SCEV
*R
)
4141 : LUIdx(LI
), Imm(I
), OrigReg(R
) {}
4143 void print(raw_ostream
&OS
) const;
4147 } // end anonymous namespace
4149 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4150 void WorkItem::print(raw_ostream
&OS
) const {
4151 OS
<< "in formulae referencing " << *OrigReg
<< " in use " << LUIdx
4152 << " , add offset " << Imm
;
4155 LLVM_DUMP_METHOD
void WorkItem::dump() const {
4156 print(errs()); errs() << '\n';
4160 /// Look for registers which are a constant distance apart and try to form reuse
4161 /// opportunities between them.
4162 void LSRInstance::GenerateCrossUseConstantOffsets() {
4163 // Group the registers by their value without any added constant offset.
4164 using ImmMapTy
= std::map
<int64_t, const SCEV
*>;
4166 DenseMap
<const SCEV
*, ImmMapTy
> Map
;
4167 DenseMap
<const SCEV
*, SmallBitVector
> UsedByIndicesMap
;
4168 SmallVector
<const SCEV
*, 8> Sequence
;
4169 for (const SCEV
*Use
: RegUses
) {
4170 const SCEV
*Reg
= Use
; // Make a copy for ExtractImmediate to modify.
4171 int64_t Imm
= ExtractImmediate(Reg
, SE
);
4172 auto Pair
= Map
.insert(std::make_pair(Reg
, ImmMapTy()));
4174 Sequence
.push_back(Reg
);
4175 Pair
.first
->second
.insert(std::make_pair(Imm
, Use
));
4176 UsedByIndicesMap
[Reg
] |= RegUses
.getUsedByIndices(Use
);
4179 // Now examine each set of registers with the same base value. Build up
4180 // a list of work to do and do the work in a separate step so that we're
4181 // not adding formulae and register counts while we're searching.
4182 SmallVector
<WorkItem
, 32> WorkItems
;
4183 SmallSet
<std::pair
<size_t, int64_t>, 32> UniqueItems
;
4184 for (const SCEV
*Reg
: Sequence
) {
4185 const ImmMapTy
&Imms
= Map
.find(Reg
)->second
;
4187 // It's not worthwhile looking for reuse if there's only one offset.
4188 if (Imms
.size() == 1)
4191 LLVM_DEBUG(dbgs() << "Generating cross-use offsets for " << *Reg
<< ':';
4192 for (const auto &Entry
4194 << ' ' << Entry
.first
;
4197 // Examine each offset.
4198 for (ImmMapTy::const_iterator J
= Imms
.begin(), JE
= Imms
.end();
4200 const SCEV
*OrigReg
= J
->second
;
4202 int64_t JImm
= J
->first
;
4203 const SmallBitVector
&UsedByIndices
= RegUses
.getUsedByIndices(OrigReg
);
4205 if (!isa
<SCEVConstant
>(OrigReg
) &&
4206 UsedByIndicesMap
[Reg
].count() == 1) {
4207 LLVM_DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg
4212 // Conservatively examine offsets between this orig reg a few selected
4214 int64_t First
= Imms
.begin()->first
;
4215 int64_t Last
= std::prev(Imms
.end())->first
;
4216 // Compute (First + Last) / 2 without overflow using the fact that
4217 // First + Last = 2 * (First + Last) + (First ^ Last).
4218 int64_t Avg
= (First
& Last
) + ((First
^ Last
) >> 1);
4219 // If the result is negative and First is odd and Last even (or vice versa),
4220 // we rounded towards -inf. Add 1 in that case, to round towards 0.
4221 Avg
= Avg
+ ((First
^ Last
) & ((uint64_t)Avg
>> 63));
4222 ImmMapTy::const_iterator OtherImms
[] = {
4223 Imms
.begin(), std::prev(Imms
.end()),
4224 Imms
.lower_bound(Avg
)};
4225 for (size_t i
= 0, e
= array_lengthof(OtherImms
); i
!= e
; ++i
) {
4226 ImmMapTy::const_iterator M
= OtherImms
[i
];
4227 if (M
== J
|| M
== JE
) continue;
4229 // Compute the difference between the two.
4230 int64_t Imm
= (uint64_t)JImm
- M
->first
;
4231 for (unsigned LUIdx
: UsedByIndices
.set_bits())
4232 // Make a memo of this use, offset, and register tuple.
4233 if (UniqueItems
.insert(std::make_pair(LUIdx
, Imm
)).second
)
4234 WorkItems
.push_back(WorkItem(LUIdx
, Imm
, OrigReg
));
4241 UsedByIndicesMap
.clear();
4242 UniqueItems
.clear();
4244 // Now iterate through the worklist and add new formulae.
4245 for (const WorkItem
&WI
: WorkItems
) {
4246 size_t LUIdx
= WI
.LUIdx
;
4247 LSRUse
&LU
= Uses
[LUIdx
];
4248 int64_t Imm
= WI
.Imm
;
4249 const SCEV
*OrigReg
= WI
.OrigReg
;
4251 Type
*IntTy
= SE
.getEffectiveSCEVType(OrigReg
->getType());
4252 const SCEV
*NegImmS
= SE
.getSCEV(ConstantInt::get(IntTy
, -(uint64_t)Imm
));
4253 unsigned BitWidth
= SE
.getTypeSizeInBits(IntTy
);
4255 // TODO: Use a more targeted data structure.
4256 for (size_t L
= 0, LE
= LU
.Formulae
.size(); L
!= LE
; ++L
) {
4257 Formula F
= LU
.Formulae
[L
];
4258 // FIXME: The code for the scaled and unscaled registers looks
4259 // very similar but slightly different. Investigate if they
4260 // could be merged. That way, we would not have to unscale the
4263 // Use the immediate in the scaled register.
4264 if (F
.ScaledReg
== OrigReg
) {
4265 int64_t Offset
= (uint64_t)F
.BaseOffset
+ Imm
* (uint64_t)F
.Scale
;
4266 // Don't create 50 + reg(-50).
4267 if (F
.referencesReg(SE
.getSCEV(
4268 ConstantInt::get(IntTy
, -(uint64_t)Offset
))))
4271 NewF
.BaseOffset
= Offset
;
4272 if (!isLegalUse(TTI
, LU
.MinOffset
, LU
.MaxOffset
, LU
.Kind
, LU
.AccessTy
,
4275 NewF
.ScaledReg
= SE
.getAddExpr(NegImmS
, NewF
.ScaledReg
);
4277 // If the new scale is a constant in a register, and adding the constant
4278 // value to the immediate would produce a value closer to zero than the
4279 // immediate itself, then the formula isn't worthwhile.
4280 if (const SCEVConstant
*C
= dyn_cast
<SCEVConstant
>(NewF
.ScaledReg
))
4281 if (C
->getValue()->isNegative() != (NewF
.BaseOffset
< 0) &&
4282 (C
->getAPInt().abs() * APInt(BitWidth
, F
.Scale
))
4283 .ule(std::abs(NewF
.BaseOffset
)))
4287 NewF
.canonicalize(*this->L
);
4288 (void)InsertFormula(LU
, LUIdx
, NewF
);
4290 // Use the immediate in a base register.
4291 for (size_t N
= 0, NE
= F
.BaseRegs
.size(); N
!= NE
; ++N
) {
4292 const SCEV
*BaseReg
= F
.BaseRegs
[N
];
4293 if (BaseReg
!= OrigReg
)
4296 NewF
.BaseOffset
= (uint64_t)NewF
.BaseOffset
+ Imm
;
4297 if (!isLegalUse(TTI
, LU
.MinOffset
, LU
.MaxOffset
,
4298 LU
.Kind
, LU
.AccessTy
, NewF
)) {
4299 if (AMK
== TTI::AMK_PostIndexed
&&
4300 mayUsePostIncMode(TTI
, LU
, OrigReg
, this->L
, SE
))
4302 if (!TTI
.isLegalAddImmediate((uint64_t)NewF
.UnfoldedOffset
+ Imm
))
4305 NewF
.UnfoldedOffset
= (uint64_t)NewF
.UnfoldedOffset
+ Imm
;
4307 NewF
.BaseRegs
[N
] = SE
.getAddExpr(NegImmS
, BaseReg
);
4309 // If the new formula has a constant in a register, and adding the
4310 // constant value to the immediate would produce a value closer to
4311 // zero than the immediate itself, then the formula isn't worthwhile.
4312 for (const SCEV
*NewReg
: NewF
.BaseRegs
)
4313 if (const SCEVConstant
*C
= dyn_cast
<SCEVConstant
>(NewReg
))
4314 if ((C
->getAPInt() + NewF
.BaseOffset
)
4316 .slt(std::abs(NewF
.BaseOffset
)) &&
4317 (C
->getAPInt() + NewF
.BaseOffset
).countTrailingZeros() >=
4318 countTrailingZeros
<uint64_t>(NewF
.BaseOffset
))
4322 NewF
.canonicalize(*this->L
);
4323 (void)InsertFormula(LU
, LUIdx
, NewF
);
4332 /// Generate formulae for each use.
4334 LSRInstance::GenerateAllReuseFormulae() {
4335 // This is split into multiple loops so that hasRegsUsedByUsesOtherThan
4336 // queries are more precise.
4337 for (size_t LUIdx
= 0, NumUses
= Uses
.size(); LUIdx
!= NumUses
; ++LUIdx
) {
4338 LSRUse
&LU
= Uses
[LUIdx
];
4339 for (size_t i
= 0, f
= LU
.Formulae
.size(); i
!= f
; ++i
)
4340 GenerateReassociations(LU
, LUIdx
, LU
.Formulae
[i
]);
4341 for (size_t i
= 0, f
= LU
.Formulae
.size(); i
!= f
; ++i
)
4342 GenerateCombinations(LU
, LUIdx
, LU
.Formulae
[i
]);
4344 for (size_t LUIdx
= 0, NumUses
= Uses
.size(); LUIdx
!= NumUses
; ++LUIdx
) {
4345 LSRUse
&LU
= Uses
[LUIdx
];
4346 for (size_t i
= 0, f
= LU
.Formulae
.size(); i
!= f
; ++i
)
4347 GenerateSymbolicOffsets(LU
, LUIdx
, LU
.Formulae
[i
]);
4348 for (size_t i
= 0, f
= LU
.Formulae
.size(); i
!= f
; ++i
)
4349 GenerateConstantOffsets(LU
, LUIdx
, LU
.Formulae
[i
]);
4350 for (size_t i
= 0, f
= LU
.Formulae
.size(); i
!= f
; ++i
)
4351 GenerateICmpZeroScales(LU
, LUIdx
, LU
.Formulae
[i
]);
4352 for (size_t i
= 0, f
= LU
.Formulae
.size(); i
!= f
; ++i
)
4353 GenerateScales(LU
, LUIdx
, LU
.Formulae
[i
]);
4355 for (size_t LUIdx
= 0, NumUses
= Uses
.size(); LUIdx
!= NumUses
; ++LUIdx
) {
4356 LSRUse
&LU
= Uses
[LUIdx
];
4357 for (size_t i
= 0, f
= LU
.Formulae
.size(); i
!= f
; ++i
)
4358 GenerateTruncates(LU
, LUIdx
, LU
.Formulae
[i
]);
4361 GenerateCrossUseConstantOffsets();
4363 LLVM_DEBUG(dbgs() << "\n"
4364 "After generating reuse formulae:\n";
4365 print_uses(dbgs()));
4368 /// If there are multiple formulae with the same set of registers used
4369 /// by other uses, pick the best one and delete the others.
4370 void LSRInstance::FilterOutUndesirableDedicatedRegisters() {
4371 DenseSet
<const SCEV
*> VisitedRegs
;
4372 SmallPtrSet
<const SCEV
*, 16> Regs
;
4373 SmallPtrSet
<const SCEV
*, 16> LoserRegs
;
4375 bool ChangedFormulae
= false;
4378 // Collect the best formula for each unique set of shared registers. This
4379 // is reset for each use.
4380 using BestFormulaeTy
=
4381 DenseMap
<SmallVector
<const SCEV
*, 4>, size_t, UniquifierDenseMapInfo
>;
4383 BestFormulaeTy BestFormulae
;
4385 for (size_t LUIdx
= 0, NumUses
= Uses
.size(); LUIdx
!= NumUses
; ++LUIdx
) {
4386 LSRUse
&LU
= Uses
[LUIdx
];
4387 LLVM_DEBUG(dbgs() << "Filtering for use "; LU
.print(dbgs());
4391 for (size_t FIdx
= 0, NumForms
= LU
.Formulae
.size();
4392 FIdx
!= NumForms
; ++FIdx
) {
4393 Formula
&F
= LU
.Formulae
[FIdx
];
4395 // Some formulas are instant losers. For example, they may depend on
4396 // nonexistent AddRecs from other loops. These need to be filtered
4397 // immediately, otherwise heuristics could choose them over others leading
4398 // to an unsatisfactory solution. Passing LoserRegs into RateFormula here
4399 // avoids the need to recompute this information across formulae using the
4400 // same bad AddRec. Passing LoserRegs is also essential unless we remove
4401 // the corresponding bad register from the Regs set.
4402 Cost
CostF(L
, SE
, TTI
, AMK
);
4404 CostF
.RateFormula(F
, Regs
, VisitedRegs
, LU
, &LoserRegs
);
4405 if (CostF
.isLoser()) {
4406 // During initial formula generation, undesirable formulae are generated
4407 // by uses within other loops that have some non-trivial address mode or
4408 // use the postinc form of the IV. LSR needs to provide these formulae
4409 // as the basis of rediscovering the desired formula that uses an AddRec
4410 // corresponding to the existing phi. Once all formulae have been
4411 // generated, these initial losers may be pruned.
4412 LLVM_DEBUG(dbgs() << " Filtering loser "; F
.print(dbgs());
4416 SmallVector
<const SCEV
*, 4> Key
;
4417 for (const SCEV
*Reg
: F
.BaseRegs
) {
4418 if (RegUses
.isRegUsedByUsesOtherThan(Reg
, LUIdx
))
4422 RegUses
.isRegUsedByUsesOtherThan(F
.ScaledReg
, LUIdx
))
4423 Key
.push_back(F
.ScaledReg
);
4424 // Unstable sort by host order ok, because this is only used for
4428 std::pair
<BestFormulaeTy::const_iterator
, bool> P
=
4429 BestFormulae
.insert(std::make_pair(Key
, FIdx
));
4433 Formula
&Best
= LU
.Formulae
[P
.first
->second
];
4435 Cost
CostBest(L
, SE
, TTI
, AMK
);
4437 CostBest
.RateFormula(Best
, Regs
, VisitedRegs
, LU
);
4438 if (CostF
.isLess(CostBest
))
4440 LLVM_DEBUG(dbgs() << " Filtering out formula "; F
.print(dbgs());
4442 " in favor of formula ";
4443 Best
.print(dbgs()); dbgs() << '\n');
4446 ChangedFormulae
= true;
4448 LU
.DeleteFormula(F
);
4454 // Now that we've filtered out some formulae, recompute the Regs set.
4456 LU
.RecomputeRegs(LUIdx
, RegUses
);
4458 // Reset this to prepare for the next use.
4459 BestFormulae
.clear();
4462 LLVM_DEBUG(if (ChangedFormulae
) {
4464 "After filtering out undesirable candidates:\n";
4469 /// Estimate the worst-case number of solutions the solver might have to
4470 /// consider. It almost never considers this many solutions because it prune the
4471 /// search space, but the pruning isn't always sufficient.
4472 size_t LSRInstance::EstimateSearchSpaceComplexity() const {
4474 for (const LSRUse
&LU
: Uses
) {
4475 size_t FSize
= LU
.Formulae
.size();
4476 if (FSize
>= ComplexityLimit
) {
4477 Power
= ComplexityLimit
;
4481 if (Power
>= ComplexityLimit
)
4487 /// When one formula uses a superset of the registers of another formula, it
4488 /// won't help reduce register pressure (though it may not necessarily hurt
4489 /// register pressure); remove it to simplify the system.
4490 void LSRInstance::NarrowSearchSpaceByDetectingSupersets() {
4491 if (EstimateSearchSpaceComplexity() >= ComplexityLimit
) {
4492 LLVM_DEBUG(dbgs() << "The search space is too complex.\n");
4494 LLVM_DEBUG(dbgs() << "Narrowing the search space by eliminating formulae "
4495 "which use a superset of registers used by other "
4498 for (size_t LUIdx
= 0, NumUses
= Uses
.size(); LUIdx
!= NumUses
; ++LUIdx
) {
4499 LSRUse
&LU
= Uses
[LUIdx
];
4501 for (size_t i
= 0, e
= LU
.Formulae
.size(); i
!= e
; ++i
) {
4502 Formula
&F
= LU
.Formulae
[i
];
4503 // Look for a formula with a constant or GV in a register. If the use
4504 // also has a formula with that same value in an immediate field,
4505 // delete the one that uses a register.
4506 for (SmallVectorImpl
<const SCEV
*>::const_iterator
4507 I
= F
.BaseRegs
.begin(), E
= F
.BaseRegs
.end(); I
!= E
; ++I
) {
4508 if (const SCEVConstant
*C
= dyn_cast
<SCEVConstant
>(*I
)) {
4510 //FIXME: Formulas should store bitwidth to do wrapping properly.
4512 NewF
.BaseOffset
+= (uint64_t)C
->getValue()->getSExtValue();
4513 NewF
.BaseRegs
.erase(NewF
.BaseRegs
.begin() +
4514 (I
- F
.BaseRegs
.begin()));
4515 if (LU
.HasFormulaWithSameRegs(NewF
)) {
4516 LLVM_DEBUG(dbgs() << " Deleting "; F
.print(dbgs());
4518 LU
.DeleteFormula(F
);
4524 } else if (const SCEVUnknown
*U
= dyn_cast
<SCEVUnknown
>(*I
)) {
4525 if (GlobalValue
*GV
= dyn_cast
<GlobalValue
>(U
->getValue()))
4529 NewF
.BaseRegs
.erase(NewF
.BaseRegs
.begin() +
4530 (I
- F
.BaseRegs
.begin()));
4531 if (LU
.HasFormulaWithSameRegs(NewF
)) {
4532 LLVM_DEBUG(dbgs() << " Deleting "; F
.print(dbgs());
4534 LU
.DeleteFormula(F
);
4545 LU
.RecomputeRegs(LUIdx
, RegUses
);
4548 LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
4552 /// When there are many registers for expressions like A, A+1, A+2, etc.,
4553 /// allocate a single register for them.
4554 void LSRInstance::NarrowSearchSpaceByCollapsingUnrolledCode() {
4555 if (EstimateSearchSpaceComplexity() < ComplexityLimit
)
4559 dbgs() << "The search space is too complex.\n"
4560 "Narrowing the search space by assuming that uses separated "
4561 "by a constant offset will use the same registers.\n");
4563 // This is especially useful for unrolled loops.
4565 for (size_t LUIdx
= 0, NumUses
= Uses
.size(); LUIdx
!= NumUses
; ++LUIdx
) {
4566 LSRUse
&LU
= Uses
[LUIdx
];
4567 for (const Formula
&F
: LU
.Formulae
) {
4568 if (F
.BaseOffset
== 0 || (F
.Scale
!= 0 && F
.Scale
!= 1))
4571 LSRUse
*LUThatHas
= FindUseWithSimilarFormula(F
, LU
);
4575 if (!reconcileNewOffset(*LUThatHas
, F
.BaseOffset
, /*HasBaseReg=*/ false,
4576 LU
.Kind
, LU
.AccessTy
))
4579 LLVM_DEBUG(dbgs() << " Deleting use "; LU
.print(dbgs()); dbgs() << '\n');
4581 LUThatHas
->AllFixupsOutsideLoop
&= LU
.AllFixupsOutsideLoop
;
4583 // Transfer the fixups of LU to LUThatHas.
4584 for (LSRFixup
&Fixup
: LU
.Fixups
) {
4585 Fixup
.Offset
+= F
.BaseOffset
;
4586 LUThatHas
->pushFixup(Fixup
);
4587 LLVM_DEBUG(dbgs() << "New fixup has offset " << Fixup
.Offset
<< '\n');
4590 // Delete formulae from the new use which are no longer legal.
4592 for (size_t i
= 0, e
= LUThatHas
->Formulae
.size(); i
!= e
; ++i
) {
4593 Formula
&F
= LUThatHas
->Formulae
[i
];
4594 if (!isLegalUse(TTI
, LUThatHas
->MinOffset
, LUThatHas
->MaxOffset
,
4595 LUThatHas
->Kind
, LUThatHas
->AccessTy
, F
)) {
4596 LLVM_DEBUG(dbgs() << " Deleting "; F
.print(dbgs()); dbgs() << '\n');
4597 LUThatHas
->DeleteFormula(F
);
4605 LUThatHas
->RecomputeRegs(LUThatHas
- &Uses
.front(), RegUses
);
4607 // Delete the old use.
4608 DeleteUse(LU
, LUIdx
);
4615 LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
4618 /// Call FilterOutUndesirableDedicatedRegisters again, if necessary, now that
4619 /// we've done more filtering, as it may be able to find more formulae to
4621 void LSRInstance::NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters(){
4622 if (EstimateSearchSpaceComplexity() >= ComplexityLimit
) {
4623 LLVM_DEBUG(dbgs() << "The search space is too complex.\n");
4625 LLVM_DEBUG(dbgs() << "Narrowing the search space by re-filtering out "
4626 "undesirable dedicated registers.\n");
4628 FilterOutUndesirableDedicatedRegisters();
4630 LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
4634 /// If a LSRUse has multiple formulae with the same ScaledReg and Scale.
4635 /// Pick the best one and delete the others.
4636 /// This narrowing heuristic is to keep as many formulae with different
4637 /// Scale and ScaledReg pair as possible while narrowing the search space.
4638 /// The benefit is that it is more likely to find out a better solution
4639 /// from a formulae set with more Scale and ScaledReg variations than
4640 /// a formulae set with the same Scale and ScaledReg. The picking winner
4641 /// reg heuristic will often keep the formulae with the same Scale and
4642 /// ScaledReg and filter others, and we want to avoid that if possible.
4643 void LSRInstance::NarrowSearchSpaceByFilterFormulaWithSameScaledReg() {
4644 if (EstimateSearchSpaceComplexity() < ComplexityLimit
)
4648 dbgs() << "The search space is too complex.\n"
4649 "Narrowing the search space by choosing the best Formula "
4650 "from the Formulae with the same Scale and ScaledReg.\n");
4652 // Map the "Scale * ScaledReg" pair to the best formula of current LSRUse.
4653 using BestFormulaeTy
= DenseMap
<std::pair
<const SCEV
*, int64_t>, size_t>;
4655 BestFormulaeTy BestFormulae
;
4657 bool ChangedFormulae
= false;
4659 DenseSet
<const SCEV
*> VisitedRegs
;
4660 SmallPtrSet
<const SCEV
*, 16> Regs
;
4662 for (size_t LUIdx
= 0, NumUses
= Uses
.size(); LUIdx
!= NumUses
; ++LUIdx
) {
4663 LSRUse
&LU
= Uses
[LUIdx
];
4664 LLVM_DEBUG(dbgs() << "Filtering for use "; LU
.print(dbgs());
4667 // Return true if Formula FA is better than Formula FB.
4668 auto IsBetterThan
= [&](Formula
&FA
, Formula
&FB
) {
4669 // First we will try to choose the Formula with fewer new registers.
4670 // For a register used by current Formula, the more the register is
4671 // shared among LSRUses, the less we increase the register number
4672 // counter of the formula.
4673 size_t FARegNum
= 0;
4674 for (const SCEV
*Reg
: FA
.BaseRegs
) {
4675 const SmallBitVector
&UsedByIndices
= RegUses
.getUsedByIndices(Reg
);
4676 FARegNum
+= (NumUses
- UsedByIndices
.count() + 1);
4678 size_t FBRegNum
= 0;
4679 for (const SCEV
*Reg
: FB
.BaseRegs
) {
4680 const SmallBitVector
&UsedByIndices
= RegUses
.getUsedByIndices(Reg
);
4681 FBRegNum
+= (NumUses
- UsedByIndices
.count() + 1);
4683 if (FARegNum
!= FBRegNum
)
4684 return FARegNum
< FBRegNum
;
4686 // If the new register numbers are the same, choose the Formula with
4688 Cost
CostFA(L
, SE
, TTI
, AMK
);
4689 Cost
CostFB(L
, SE
, TTI
, AMK
);
4691 CostFA
.RateFormula(FA
, Regs
, VisitedRegs
, LU
);
4693 CostFB
.RateFormula(FB
, Regs
, VisitedRegs
, LU
);
4694 return CostFA
.isLess(CostFB
);
4698 for (size_t FIdx
= 0, NumForms
= LU
.Formulae
.size(); FIdx
!= NumForms
;
4700 Formula
&F
= LU
.Formulae
[FIdx
];
4703 auto P
= BestFormulae
.insert({{F
.ScaledReg
, F
.Scale
}, FIdx
});
4707 Formula
&Best
= LU
.Formulae
[P
.first
->second
];
4708 if (IsBetterThan(F
, Best
))
4710 LLVM_DEBUG(dbgs() << " Filtering out formula "; F
.print(dbgs());
4712 " in favor of formula ";
4713 Best
.print(dbgs()); dbgs() << '\n');
4715 ChangedFormulae
= true;
4717 LU
.DeleteFormula(F
);
4723 LU
.RecomputeRegs(LUIdx
, RegUses
);
4725 // Reset this to prepare for the next use.
4726 BestFormulae
.clear();
4729 LLVM_DEBUG(if (ChangedFormulae
) {
4731 "After filtering out undesirable candidates:\n";
4736 /// If we are over the complexity limit, filter out any post-inc prefering
4737 /// variables to only post-inc values.
4738 void LSRInstance::NarrowSearchSpaceByFilterPostInc() {
4739 if (AMK
!= TTI::AMK_PostIndexed
)
4741 if (EstimateSearchSpaceComplexity() < ComplexityLimit
)
4744 LLVM_DEBUG(dbgs() << "The search space is too complex.\n"
4745 "Narrowing the search space by choosing the lowest "
4746 "register Formula for PostInc Uses.\n");
4748 for (size_t LUIdx
= 0, NumUses
= Uses
.size(); LUIdx
!= NumUses
; ++LUIdx
) {
4749 LSRUse
&LU
= Uses
[LUIdx
];
4751 if (LU
.Kind
!= LSRUse::Address
)
4753 if (!TTI
.isIndexedLoadLegal(TTI
.MIM_PostInc
, LU
.AccessTy
.getType()) &&
4754 !TTI
.isIndexedStoreLegal(TTI
.MIM_PostInc
, LU
.AccessTy
.getType()))
4757 size_t MinRegs
= std::numeric_limits
<size_t>::max();
4758 for (const Formula
&F
: LU
.Formulae
)
4759 MinRegs
= std::min(F
.getNumRegs(), MinRegs
);
4762 for (size_t FIdx
= 0, NumForms
= LU
.Formulae
.size(); FIdx
!= NumForms
;
4764 Formula
&F
= LU
.Formulae
[FIdx
];
4765 if (F
.getNumRegs() > MinRegs
) {
4766 LLVM_DEBUG(dbgs() << " Filtering out formula "; F
.print(dbgs());
4768 LU
.DeleteFormula(F
);
4775 LU
.RecomputeRegs(LUIdx
, RegUses
);
4777 if (EstimateSearchSpaceComplexity() < ComplexityLimit
)
4781 LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
4784 /// The function delete formulas with high registers number expectation.
4785 /// Assuming we don't know the value of each formula (already delete
4786 /// all inefficient), generate probability of not selecting for each
4790 /// reg(a) + reg({0,+,1})
4791 /// reg(a) + reg({-1,+,1}) + 1
4794 /// reg(b) + reg({0,+,1})
4795 /// reg(b) + reg({-1,+,1}) + 1
4798 /// reg(c) + reg(b) + reg({0,+,1})
4799 /// reg(c) + reg({b,+,1})
4801 /// Probability of not selecting
4803 /// reg(a) (1/3) * 1 * 1
4804 /// reg(b) 1 * (1/3) * (1/2)
4805 /// reg({0,+,1}) (2/3) * (2/3) * (1/2)
4806 /// reg({-1,+,1}) (2/3) * (2/3) * 1
4807 /// reg({a,+,1}) (2/3) * 1 * 1
4808 /// reg({b,+,1}) 1 * (2/3) * (2/3)
4809 /// reg(c) 1 * 1 * 0
4811 /// Now count registers number mathematical expectation for each formula:
4812 /// Note that for each use we exclude probability if not selecting for the use.
4813 /// For example for Use1 probability for reg(a) would be just 1 * 1 (excluding
4814 /// probabilty 1/3 of not selecting for Use1).
4816 /// reg(a) + reg({0,+,1}) 1 + 1/3 -- to be deleted
4817 /// reg(a) + reg({-1,+,1}) + 1 1 + 4/9 -- to be deleted
4820 /// reg(b) + reg({0,+,1}) 1/2 + 1/3 -- to be deleted
4821 /// reg(b) + reg({-1,+,1}) + 1 1/2 + 2/3 -- to be deleted
4822 /// reg({b,+,1}) 2/3
4824 /// reg(c) + reg(b) + reg({0,+,1}) 1 + 1/3 + 4/9 -- to be deleted
4825 /// reg(c) + reg({b,+,1}) 1 + 2/3
4826 void LSRInstance::NarrowSearchSpaceByDeletingCostlyFormulas() {
4827 if (EstimateSearchSpaceComplexity() < ComplexityLimit
)
4829 // Ok, we have too many of formulae on our hands to conveniently handle.
4830 // Use a rough heuristic to thin out the list.
4832 // Set of Regs wich will be 100% used in final solution.
4833 // Used in each formula of a solution (in example above this is reg(c)).
4834 // We can skip them in calculations.
4835 SmallPtrSet
<const SCEV
*, 4> UniqRegs
;
4836 LLVM_DEBUG(dbgs() << "The search space is too complex.\n");
4838 // Map each register to probability of not selecting
4839 DenseMap
<const SCEV
*, float> RegNumMap
;
4840 for (const SCEV
*Reg
: RegUses
) {
4841 if (UniqRegs
.count(Reg
))
4844 for (const LSRUse
&LU
: Uses
) {
4845 if (!LU
.Regs
.count(Reg
))
4847 float P
= LU
.getNotSelectedProbability(Reg
);
4851 UniqRegs
.insert(Reg
);
4853 RegNumMap
.insert(std::make_pair(Reg
, PNotSel
));
4857 dbgs() << "Narrowing the search space by deleting costly formulas\n");
4859 // Delete formulas where registers number expectation is high.
4860 for (size_t LUIdx
= 0, NumUses
= Uses
.size(); LUIdx
!= NumUses
; ++LUIdx
) {
4861 LSRUse
&LU
= Uses
[LUIdx
];
4862 // If nothing to delete - continue.
4863 if (LU
.Formulae
.size() < 2)
4865 // This is temporary solution to test performance. Float should be
4866 // replaced with round independent type (based on integers) to avoid
4867 // different results for different target builds.
4868 float FMinRegNum
= LU
.Formulae
[0].getNumRegs();
4869 float FMinARegNum
= LU
.Formulae
[0].getNumRegs();
4871 for (size_t i
= 0, e
= LU
.Formulae
.size(); i
!= e
; ++i
) {
4872 Formula
&F
= LU
.Formulae
[i
];
4875 for (const SCEV
*BaseReg
: F
.BaseRegs
) {
4876 if (UniqRegs
.count(BaseReg
))
4878 FRegNum
+= RegNumMap
[BaseReg
] / LU
.getNotSelectedProbability(BaseReg
);
4879 if (isa
<SCEVAddRecExpr
>(BaseReg
))
4881 RegNumMap
[BaseReg
] / LU
.getNotSelectedProbability(BaseReg
);
4883 if (const SCEV
*ScaledReg
= F
.ScaledReg
) {
4884 if (!UniqRegs
.count(ScaledReg
)) {
4886 RegNumMap
[ScaledReg
] / LU
.getNotSelectedProbability(ScaledReg
);
4887 if (isa
<SCEVAddRecExpr
>(ScaledReg
))
4889 RegNumMap
[ScaledReg
] / LU
.getNotSelectedProbability(ScaledReg
);
4892 if (FMinRegNum
> FRegNum
||
4893 (FMinRegNum
== FRegNum
&& FMinARegNum
> FARegNum
)) {
4894 FMinRegNum
= FRegNum
;
4895 FMinARegNum
= FARegNum
;
4899 LLVM_DEBUG(dbgs() << " The formula "; LU
.Formulae
[MinIdx
].print(dbgs());
4900 dbgs() << " with min reg num " << FMinRegNum
<< '\n');
4902 std::swap(LU
.Formulae
[MinIdx
], LU
.Formulae
[0]);
4903 while (LU
.Formulae
.size() != 1) {
4904 LLVM_DEBUG(dbgs() << " Deleting "; LU
.Formulae
.back().print(dbgs());
4906 LU
.Formulae
.pop_back();
4908 LU
.RecomputeRegs(LUIdx
, RegUses
);
4909 assert(LU
.Formulae
.size() == 1 && "Should be exactly 1 min regs formula");
4910 Formula
&F
= LU
.Formulae
[0];
4911 LLVM_DEBUG(dbgs() << " Leaving only "; F
.print(dbgs()); dbgs() << '\n');
4912 // When we choose the formula, the regs become unique.
4913 UniqRegs
.insert(F
.BaseRegs
.begin(), F
.BaseRegs
.end());
4915 UniqRegs
.insert(F
.ScaledReg
);
4917 LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
4920 /// Pick a register which seems likely to be profitable, and then in any use
4921 /// which has any reference to that register, delete all formulae which do not
4922 /// reference that register.
4923 void LSRInstance::NarrowSearchSpaceByPickingWinnerRegs() {
4924 // With all other options exhausted, loop until the system is simple
4925 // enough to handle.
4926 SmallPtrSet
<const SCEV
*, 4> Taken
;
4927 while (EstimateSearchSpaceComplexity() >= ComplexityLimit
) {
4928 // Ok, we have too many of formulae on our hands to conveniently handle.
4929 // Use a rough heuristic to thin out the list.
4930 LLVM_DEBUG(dbgs() << "The search space is too complex.\n");
4932 // Pick the register which is used by the most LSRUses, which is likely
4933 // to be a good reuse register candidate.
4934 const SCEV
*Best
= nullptr;
4935 unsigned BestNum
= 0;
4936 for (const SCEV
*Reg
: RegUses
) {
4937 if (Taken
.count(Reg
))
4941 BestNum
= RegUses
.getUsedByIndices(Reg
).count();
4943 unsigned Count
= RegUses
.getUsedByIndices(Reg
).count();
4944 if (Count
> BestNum
) {
4950 assert(Best
&& "Failed to find best LSRUse candidate");
4952 LLVM_DEBUG(dbgs() << "Narrowing the search space by assuming " << *Best
4953 << " will yield profitable reuse.\n");
4956 // In any use with formulae which references this register, delete formulae
4957 // which don't reference it.
4958 for (size_t LUIdx
= 0, NumUses
= Uses
.size(); LUIdx
!= NumUses
; ++LUIdx
) {
4959 LSRUse
&LU
= Uses
[LUIdx
];
4960 if (!LU
.Regs
.count(Best
)) continue;
4963 for (size_t i
= 0, e
= LU
.Formulae
.size(); i
!= e
; ++i
) {
4964 Formula
&F
= LU
.Formulae
[i
];
4965 if (!F
.referencesReg(Best
)) {
4966 LLVM_DEBUG(dbgs() << " Deleting "; F
.print(dbgs()); dbgs() << '\n');
4967 LU
.DeleteFormula(F
);
4971 assert(e
!= 0 && "Use has no formulae left! Is Regs inconsistent?");
4977 LU
.RecomputeRegs(LUIdx
, RegUses
);
4980 LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
4984 /// If there are an extraordinary number of formulae to choose from, use some
4985 /// rough heuristics to prune down the number of formulae. This keeps the main
4986 /// solver from taking an extraordinary amount of time in some worst-case
4988 void LSRInstance::NarrowSearchSpaceUsingHeuristics() {
4989 NarrowSearchSpaceByDetectingSupersets();
4990 NarrowSearchSpaceByCollapsingUnrolledCode();
4991 NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
4992 if (FilterSameScaledReg
)
4993 NarrowSearchSpaceByFilterFormulaWithSameScaledReg();
4994 NarrowSearchSpaceByFilterPostInc();
4996 NarrowSearchSpaceByDeletingCostlyFormulas();
4998 NarrowSearchSpaceByPickingWinnerRegs();
5001 /// This is the recursive solver.
5002 void LSRInstance::SolveRecurse(SmallVectorImpl
<const Formula
*> &Solution
,
5004 SmallVectorImpl
<const Formula
*> &Workspace
,
5005 const Cost
&CurCost
,
5006 const SmallPtrSet
<const SCEV
*, 16> &CurRegs
,
5007 DenseSet
<const SCEV
*> &VisitedRegs
) const {
5010 // - use more aggressive filtering
5011 // - sort the formula so that the most profitable solutions are found first
5012 // - sort the uses too
5014 // - don't compute a cost, and then compare. compare while computing a cost
5016 // - track register sets with SmallBitVector
5018 const LSRUse
&LU
= Uses
[Workspace
.size()];
5020 // If this use references any register that's already a part of the
5021 // in-progress solution, consider it a requirement that a formula must
5022 // reference that register in order to be considered. This prunes out
5023 // unprofitable searching.
5024 SmallSetVector
<const SCEV
*, 4> ReqRegs
;
5025 for (const SCEV
*S
: CurRegs
)
5026 if (LU
.Regs
.count(S
))
5029 SmallPtrSet
<const SCEV
*, 16> NewRegs
;
5030 Cost
NewCost(L
, SE
, TTI
, AMK
);
5031 for (const Formula
&F
: LU
.Formulae
) {
5032 // Ignore formulae which may not be ideal in terms of register reuse of
5033 // ReqRegs. The formula should use all required registers before
5034 // introducing new ones.
5035 // This can sometimes (notably when trying to favour postinc) lead to
5036 // sub-optimial decisions. There it is best left to the cost modelling to
5038 if (AMK
!= TTI::AMK_PostIndexed
|| LU
.Kind
!= LSRUse::Address
) {
5039 int NumReqRegsToFind
= std::min(F
.getNumRegs(), ReqRegs
.size());
5040 for (const SCEV
*Reg
: ReqRegs
) {
5041 if ((F
.ScaledReg
&& F
.ScaledReg
== Reg
) ||
5042 is_contained(F
.BaseRegs
, Reg
)) {
5044 if (NumReqRegsToFind
== 0)
5048 if (NumReqRegsToFind
!= 0) {
5049 // If none of the formulae satisfied the required registers, then we could
5050 // clear ReqRegs and try again. Currently, we simply give up in this case.
5055 // Evaluate the cost of the current formula. If it's already worse than
5056 // the current best, prune the search at that point.
5059 NewCost
.RateFormula(F
, NewRegs
, VisitedRegs
, LU
);
5060 if (NewCost
.isLess(SolutionCost
)) {
5061 Workspace
.push_back(&F
);
5062 if (Workspace
.size() != Uses
.size()) {
5063 SolveRecurse(Solution
, SolutionCost
, Workspace
, NewCost
,
5064 NewRegs
, VisitedRegs
);
5065 if (F
.getNumRegs() == 1 && Workspace
.size() == 1)
5066 VisitedRegs
.insert(F
.ScaledReg
? F
.ScaledReg
: F
.BaseRegs
[0]);
5068 LLVM_DEBUG(dbgs() << "New best at "; NewCost
.print(dbgs());
5069 dbgs() << ".\nRegs:\n";
5070 for (const SCEV
*S
: NewRegs
) dbgs()
5071 << "- " << *S
<< "\n";
5074 SolutionCost
= NewCost
;
5075 Solution
= Workspace
;
5077 Workspace
.pop_back();
5082 /// Choose one formula from each use. Return the results in the given Solution
5084 void LSRInstance::Solve(SmallVectorImpl
<const Formula
*> &Solution
) const {
5085 SmallVector
<const Formula
*, 8> Workspace
;
5086 Cost
SolutionCost(L
, SE
, TTI
, AMK
);
5087 SolutionCost
.Lose();
5088 Cost
CurCost(L
, SE
, TTI
, AMK
);
5089 SmallPtrSet
<const SCEV
*, 16> CurRegs
;
5090 DenseSet
<const SCEV
*> VisitedRegs
;
5091 Workspace
.reserve(Uses
.size());
5093 // SolveRecurse does all the work.
5094 SolveRecurse(Solution
, SolutionCost
, Workspace
, CurCost
,
5095 CurRegs
, VisitedRegs
);
5096 if (Solution
.empty()) {
5097 LLVM_DEBUG(dbgs() << "\nNo Satisfactory Solution\n");
5101 // Ok, we've now made all our decisions.
5102 LLVM_DEBUG(dbgs() << "\n"
5103 "The chosen solution requires ";
5104 SolutionCost
.print(dbgs()); dbgs() << ":\n";
5105 for (size_t i
= 0, e
= Uses
.size(); i
!= e
; ++i
) {
5107 Uses
[i
].print(dbgs());
5110 Solution
[i
]->print(dbgs());
5114 assert(Solution
.size() == Uses
.size() && "Malformed solution!");
5117 /// Helper for AdjustInsertPositionForExpand. Climb up the dominator tree far as
5118 /// we can go while still being dominated by the input positions. This helps
5119 /// canonicalize the insert position, which encourages sharing.
5120 BasicBlock::iterator
5121 LSRInstance::HoistInsertPosition(BasicBlock::iterator IP
,
5122 const SmallVectorImpl
<Instruction
*> &Inputs
)
5124 Instruction
*Tentative
= &*IP
;
5126 bool AllDominate
= true;
5127 Instruction
*BetterPos
= nullptr;
5128 // Don't bother attempting to insert before a catchswitch, their basic block
5129 // cannot have other non-PHI instructions.
5130 if (isa
<CatchSwitchInst
>(Tentative
))
5133 for (Instruction
*Inst
: Inputs
) {
5134 if (Inst
== Tentative
|| !DT
.dominates(Inst
, Tentative
)) {
5135 AllDominate
= false;
5138 // Attempt to find an insert position in the middle of the block,
5139 // instead of at the end, so that it can be used for other expansions.
5140 if (Tentative
->getParent() == Inst
->getParent() &&
5141 (!BetterPos
|| !DT
.dominates(Inst
, BetterPos
)))
5142 BetterPos
= &*std::next(BasicBlock::iterator(Inst
));
5147 IP
= BetterPos
->getIterator();
5149 IP
= Tentative
->getIterator();
5151 const Loop
*IPLoop
= LI
.getLoopFor(IP
->getParent());
5152 unsigned IPLoopDepth
= IPLoop
? IPLoop
->getLoopDepth() : 0;
5155 for (DomTreeNode
*Rung
= DT
.getNode(IP
->getParent()); ; ) {
5156 if (!Rung
) return IP
;
5157 Rung
= Rung
->getIDom();
5158 if (!Rung
) return IP
;
5159 IDom
= Rung
->getBlock();
5161 // Don't climb into a loop though.
5162 const Loop
*IDomLoop
= LI
.getLoopFor(IDom
);
5163 unsigned IDomDepth
= IDomLoop
? IDomLoop
->getLoopDepth() : 0;
5164 if (IDomDepth
<= IPLoopDepth
&&
5165 (IDomDepth
!= IPLoopDepth
|| IDomLoop
== IPLoop
))
5169 Tentative
= IDom
->getTerminator();
5175 /// Determine an input position which will be dominated by the operands and
5176 /// which will dominate the result.
5177 BasicBlock::iterator
5178 LSRInstance::AdjustInsertPositionForExpand(BasicBlock::iterator LowestIP
,
5181 SCEVExpander
&Rewriter
) const {
5182 // Collect some instructions which must be dominated by the
5183 // expanding replacement. These must be dominated by any operands that
5184 // will be required in the expansion.
5185 SmallVector
<Instruction
*, 4> Inputs
;
5186 if (Instruction
*I
= dyn_cast
<Instruction
>(LF
.OperandValToReplace
))
5187 Inputs
.push_back(I
);
5188 if (LU
.Kind
== LSRUse::ICmpZero
)
5189 if (Instruction
*I
=
5190 dyn_cast
<Instruction
>(cast
<ICmpInst
>(LF
.UserInst
)->getOperand(1)))
5191 Inputs
.push_back(I
);
5192 if (LF
.PostIncLoops
.count(L
)) {
5193 if (LF
.isUseFullyOutsideLoop(L
))
5194 Inputs
.push_back(L
->getLoopLatch()->getTerminator());
5196 Inputs
.push_back(IVIncInsertPos
);
5198 // The expansion must also be dominated by the increment positions of any
5199 // loops it for which it is using post-inc mode.
5200 for (const Loop
*PIL
: LF
.PostIncLoops
) {
5201 if (PIL
== L
) continue;
5203 // Be dominated by the loop exit.
5204 SmallVector
<BasicBlock
*, 4> ExitingBlocks
;
5205 PIL
->getExitingBlocks(ExitingBlocks
);
5206 if (!ExitingBlocks
.empty()) {
5207 BasicBlock
*BB
= ExitingBlocks
[0];
5208 for (unsigned i
= 1, e
= ExitingBlocks
.size(); i
!= e
; ++i
)
5209 BB
= DT
.findNearestCommonDominator(BB
, ExitingBlocks
[i
]);
5210 Inputs
.push_back(BB
->getTerminator());
5214 assert(!isa
<PHINode
>(LowestIP
) && !LowestIP
->isEHPad()
5215 && !isa
<DbgInfoIntrinsic
>(LowestIP
) &&
5216 "Insertion point must be a normal instruction");
5218 // Then, climb up the immediate dominator tree as far as we can go while
5219 // still being dominated by the input positions.
5220 BasicBlock::iterator IP
= HoistInsertPosition(LowestIP
, Inputs
);
5222 // Don't insert instructions before PHI nodes.
5223 while (isa
<PHINode
>(IP
)) ++IP
;
5225 // Ignore landingpad instructions.
5226 while (IP
->isEHPad()) ++IP
;
5228 // Ignore debug intrinsics.
5229 while (isa
<DbgInfoIntrinsic
>(IP
)) ++IP
;
5231 // Set IP below instructions recently inserted by SCEVExpander. This keeps the
5232 // IP consistent across expansions and allows the previously inserted
5233 // instructions to be reused by subsequent expansion.
5234 while (Rewriter
.isInsertedInstruction(&*IP
) && IP
!= LowestIP
)
5240 /// Emit instructions for the leading candidate expression for this LSRUse (this
5241 /// is called "expanding").
5242 Value
*LSRInstance::Expand(const LSRUse
&LU
, const LSRFixup
&LF
,
5243 const Formula
&F
, BasicBlock::iterator IP
,
5244 SCEVExpander
&Rewriter
,
5245 SmallVectorImpl
<WeakTrackingVH
> &DeadInsts
) const {
5246 if (LU
.RigidFormula
)
5247 return LF
.OperandValToReplace
;
5249 // Determine an input position which will be dominated by the operands and
5250 // which will dominate the result.
5251 IP
= AdjustInsertPositionForExpand(IP
, LF
, LU
, Rewriter
);
5252 Rewriter
.setInsertPoint(&*IP
);
5254 // Inform the Rewriter if we have a post-increment use, so that it can
5255 // perform an advantageous expansion.
5256 Rewriter
.setPostInc(LF
.PostIncLoops
);
5258 // This is the type that the user actually needs.
5259 Type
*OpTy
= LF
.OperandValToReplace
->getType();
5260 // This will be the type that we'll initially expand to.
5261 Type
*Ty
= F
.getType();
5263 // No type known; just expand directly to the ultimate type.
5265 else if (SE
.getEffectiveSCEVType(Ty
) == SE
.getEffectiveSCEVType(OpTy
))
5266 // Expand directly to the ultimate type if it's the right size.
5268 // This is the type to do integer arithmetic in.
5269 Type
*IntTy
= SE
.getEffectiveSCEVType(Ty
);
5271 // Build up a list of operands to add together to form the full base.
5272 SmallVector
<const SCEV
*, 8> Ops
;
5274 // Expand the BaseRegs portion.
5275 for (const SCEV
*Reg
: F
.BaseRegs
) {
5276 assert(!Reg
->isZero() && "Zero allocated in a base register!");
5278 // If we're expanding for a post-inc user, make the post-inc adjustment.
5279 Reg
= denormalizeForPostIncUse(Reg
, LF
.PostIncLoops
, SE
);
5280 Ops
.push_back(SE
.getUnknown(Rewriter
.expandCodeFor(Reg
, nullptr)));
5283 // Expand the ScaledReg portion.
5284 Value
*ICmpScaledV
= nullptr;
5286 const SCEV
*ScaledS
= F
.ScaledReg
;
5288 // If we're expanding for a post-inc user, make the post-inc adjustment.
5289 PostIncLoopSet
&Loops
= const_cast<PostIncLoopSet
&>(LF
.PostIncLoops
);
5290 ScaledS
= denormalizeForPostIncUse(ScaledS
, Loops
, SE
);
5292 if (LU
.Kind
== LSRUse::ICmpZero
) {
5293 // Expand ScaleReg as if it was part of the base regs.
5296 SE
.getUnknown(Rewriter
.expandCodeFor(ScaledS
, nullptr)));
5298 // An interesting way of "folding" with an icmp is to use a negated
5299 // scale, which we'll implement by inserting it into the other operand
5301 assert(F
.Scale
== -1 &&
5302 "The only scale supported by ICmpZero uses is -1!");
5303 ICmpScaledV
= Rewriter
.expandCodeFor(ScaledS
, nullptr);
5306 // Otherwise just expand the scaled register and an explicit scale,
5307 // which is expected to be matched as part of the address.
5309 // Flush the operand list to suppress SCEVExpander hoisting address modes.
5310 // Unless the addressing mode will not be folded.
5311 if (!Ops
.empty() && LU
.Kind
== LSRUse::Address
&&
5312 isAMCompletelyFolded(TTI
, LU
, F
)) {
5313 Value
*FullV
= Rewriter
.expandCodeFor(SE
.getAddExpr(Ops
), nullptr);
5315 Ops
.push_back(SE
.getUnknown(FullV
));
5317 ScaledS
= SE
.getUnknown(Rewriter
.expandCodeFor(ScaledS
, nullptr));
5320 SE
.getMulExpr(ScaledS
, SE
.getConstant(ScaledS
->getType(), F
.Scale
));
5321 Ops
.push_back(ScaledS
);
5325 // Expand the GV portion.
5327 // Flush the operand list to suppress SCEVExpander hoisting.
5329 Value
*FullV
= Rewriter
.expandCodeFor(SE
.getAddExpr(Ops
), IntTy
);
5331 Ops
.push_back(SE
.getUnknown(FullV
));
5333 Ops
.push_back(SE
.getUnknown(F
.BaseGV
));
5336 // Flush the operand list to suppress SCEVExpander hoisting of both folded and
5337 // unfolded offsets. LSR assumes they both live next to their uses.
5339 Value
*FullV
= Rewriter
.expandCodeFor(SE
.getAddExpr(Ops
), Ty
);
5341 Ops
.push_back(SE
.getUnknown(FullV
));
5344 // Expand the immediate portion.
5345 int64_t Offset
= (uint64_t)F
.BaseOffset
+ LF
.Offset
;
5347 if (LU
.Kind
== LSRUse::ICmpZero
) {
5348 // The other interesting way of "folding" with an ICmpZero is to use a
5349 // negated immediate.
5351 ICmpScaledV
= ConstantInt::get(IntTy
, -(uint64_t)Offset
);
5353 Ops
.push_back(SE
.getUnknown(ICmpScaledV
));
5354 ICmpScaledV
= ConstantInt::get(IntTy
, Offset
);
5357 // Just add the immediate values. These again are expected to be matched
5358 // as part of the address.
5359 Ops
.push_back(SE
.getUnknown(ConstantInt::getSigned(IntTy
, Offset
)));
5363 // Expand the unfolded offset portion.
5364 int64_t UnfoldedOffset
= F
.UnfoldedOffset
;
5365 if (UnfoldedOffset
!= 0) {
5366 // Just add the immediate values.
5367 Ops
.push_back(SE
.getUnknown(ConstantInt::getSigned(IntTy
,
5371 // Emit instructions summing all the operands.
5372 const SCEV
*FullS
= Ops
.empty() ?
5373 SE
.getConstant(IntTy
, 0) :
5375 Value
*FullV
= Rewriter
.expandCodeFor(FullS
, Ty
);
5377 // We're done expanding now, so reset the rewriter.
5378 Rewriter
.clearPostInc();
5380 // An ICmpZero Formula represents an ICmp which we're handling as a
5381 // comparison against zero. Now that we've expanded an expression for that
5382 // form, update the ICmp's other operand.
5383 if (LU
.Kind
== LSRUse::ICmpZero
) {
5384 ICmpInst
*CI
= cast
<ICmpInst
>(LF
.UserInst
);
5385 if (auto *OperandIsInstr
= dyn_cast
<Instruction
>(CI
->getOperand(1)))
5386 DeadInsts
.emplace_back(OperandIsInstr
);
5387 assert(!F
.BaseGV
&& "ICmp does not support folding a global value and "
5388 "a scale at the same time!");
5389 if (F
.Scale
== -1) {
5390 if (ICmpScaledV
->getType() != OpTy
) {
5392 CastInst::Create(CastInst::getCastOpcode(ICmpScaledV
, false,
5394 ICmpScaledV
, OpTy
, "tmp", CI
);
5397 CI
->setOperand(1, ICmpScaledV
);
5399 // A scale of 1 means that the scale has been expanded as part of the
5401 assert((F
.Scale
== 0 || F
.Scale
== 1) &&
5402 "ICmp does not support folding a global value and "
5403 "a scale at the same time!");
5404 Constant
*C
= ConstantInt::getSigned(SE
.getEffectiveSCEVType(OpTy
),
5406 if (C
->getType() != OpTy
)
5407 C
= ConstantExpr::getCast(CastInst::getCastOpcode(C
, false,
5411 CI
->setOperand(1, C
);
5418 /// Helper for Rewrite. PHI nodes are special because the use of their operands
5419 /// effectively happens in their predecessor blocks, so the expression may need
5420 /// to be expanded in multiple places.
5421 void LSRInstance::RewriteForPHI(
5422 PHINode
*PN
, const LSRUse
&LU
, const LSRFixup
&LF
, const Formula
&F
,
5423 SCEVExpander
&Rewriter
, SmallVectorImpl
<WeakTrackingVH
> &DeadInsts
) const {
5424 DenseMap
<BasicBlock
*, Value
*> Inserted
;
5425 for (unsigned i
= 0, e
= PN
->getNumIncomingValues(); i
!= e
; ++i
)
5426 if (PN
->getIncomingValue(i
) == LF
.OperandValToReplace
) {
5427 bool needUpdateFixups
= false;
5428 BasicBlock
*BB
= PN
->getIncomingBlock(i
);
5430 // If this is a critical edge, split the edge so that we do not insert
5431 // the code on all predecessor/successor paths. We do this unless this
5432 // is the canonical backedge for this loop, which complicates post-inc
5434 if (e
!= 1 && BB
->getTerminator()->getNumSuccessors() > 1 &&
5435 !isa
<IndirectBrInst
>(BB
->getTerminator()) &&
5436 !isa
<CatchSwitchInst
>(BB
->getTerminator())) {
5437 BasicBlock
*Parent
= PN
->getParent();
5438 Loop
*PNLoop
= LI
.getLoopFor(Parent
);
5439 if (!PNLoop
|| Parent
!= PNLoop
->getHeader()) {
5440 // Split the critical edge.
5441 BasicBlock
*NewBB
= nullptr;
5442 if (!Parent
->isLandingPad()) {
5444 SplitCriticalEdge(BB
, Parent
,
5445 CriticalEdgeSplittingOptions(&DT
, &LI
, MSSAU
)
5446 .setMergeIdenticalEdges()
5447 .setKeepOneInputPHIs());
5449 SmallVector
<BasicBlock
*, 2> NewBBs
;
5450 SplitLandingPadPredecessors(Parent
, BB
, "", "", NewBBs
, &DT
, &LI
);
5453 // If NewBB==NULL, then SplitCriticalEdge refused to split because all
5454 // phi predecessors are identical. The simple thing to do is skip
5455 // splitting in this case rather than complicate the API.
5457 // If PN is outside of the loop and BB is in the loop, we want to
5458 // move the block to be immediately before the PHI block, not
5459 // immediately after BB.
5460 if (L
->contains(BB
) && !L
->contains(PN
))
5461 NewBB
->moveBefore(PN
->getParent());
5463 // Splitting the edge can reduce the number of PHI entries we have.
5464 e
= PN
->getNumIncomingValues();
5466 i
= PN
->getBasicBlockIndex(BB
);
5468 needUpdateFixups
= true;
5473 std::pair
<DenseMap
<BasicBlock
*, Value
*>::iterator
, bool> Pair
=
5474 Inserted
.insert(std::make_pair(BB
, static_cast<Value
*>(nullptr)));
5476 PN
->setIncomingValue(i
, Pair
.first
->second
);
5478 Value
*FullV
= Expand(LU
, LF
, F
, BB
->getTerminator()->getIterator(),
5479 Rewriter
, DeadInsts
);
5481 // If this is reuse-by-noop-cast, insert the noop cast.
5482 Type
*OpTy
= LF
.OperandValToReplace
->getType();
5483 if (FullV
->getType() != OpTy
)
5485 CastInst::Create(CastInst::getCastOpcode(FullV
, false,
5487 FullV
, LF
.OperandValToReplace
->getType(),
5488 "tmp", BB
->getTerminator());
5490 PN
->setIncomingValue(i
, FullV
);
5491 Pair
.first
->second
= FullV
;
5494 // If LSR splits critical edge and phi node has other pending
5495 // fixup operands, we need to update those pending fixups. Otherwise
5496 // formulae will not be implemented completely and some instructions
5497 // will not be eliminated.
5498 if (needUpdateFixups
) {
5499 for (size_t LUIdx
= 0, NumUses
= Uses
.size(); LUIdx
!= NumUses
; ++LUIdx
)
5500 for (LSRFixup
&Fixup
: Uses
[LUIdx
].Fixups
)
5501 // If fixup is supposed to rewrite some operand in the phi
5502 // that was just updated, it may be already moved to
5503 // another phi node. Such fixup requires update.
5504 if (Fixup
.UserInst
== PN
) {
5505 // Check if the operand we try to replace still exists in the
5507 bool foundInOriginalPHI
= false;
5508 for (const auto &val
: PN
->incoming_values())
5509 if (val
== Fixup
.OperandValToReplace
) {
5510 foundInOriginalPHI
= true;
5514 // If fixup operand found in original PHI - nothing to do.
5515 if (foundInOriginalPHI
)
5518 // Otherwise it might be moved to another PHI and requires update.
5519 // If fixup operand not found in any of the incoming blocks that
5520 // means we have already rewritten it - nothing to do.
5521 for (const auto &Block
: PN
->blocks())
5522 for (BasicBlock::iterator I
= Block
->begin(); isa
<PHINode
>(I
);
5524 PHINode
*NewPN
= cast
<PHINode
>(I
);
5525 for (const auto &val
: NewPN
->incoming_values())
5526 if (val
== Fixup
.OperandValToReplace
)
5527 Fixup
.UserInst
= NewPN
;
5534 /// Emit instructions for the leading candidate expression for this LSRUse (this
5535 /// is called "expanding"), and update the UserInst to reference the newly
5537 void LSRInstance::Rewrite(const LSRUse
&LU
, const LSRFixup
&LF
,
5538 const Formula
&F
, SCEVExpander
&Rewriter
,
5539 SmallVectorImpl
<WeakTrackingVH
> &DeadInsts
) const {
5540 // First, find an insertion point that dominates UserInst. For PHI nodes,
5541 // find the nearest block which dominates all the relevant uses.
5542 if (PHINode
*PN
= dyn_cast
<PHINode
>(LF
.UserInst
)) {
5543 RewriteForPHI(PN
, LU
, LF
, F
, Rewriter
, DeadInsts
);
5546 Expand(LU
, LF
, F
, LF
.UserInst
->getIterator(), Rewriter
, DeadInsts
);
5548 // If this is reuse-by-noop-cast, insert the noop cast.
5549 Type
*OpTy
= LF
.OperandValToReplace
->getType();
5550 if (FullV
->getType() != OpTy
) {
5552 CastInst::Create(CastInst::getCastOpcode(FullV
, false, OpTy
, false),
5553 FullV
, OpTy
, "tmp", LF
.UserInst
);
5557 // Update the user. ICmpZero is handled specially here (for now) because
5558 // Expand may have updated one of the operands of the icmp already, and
5559 // its new value may happen to be equal to LF.OperandValToReplace, in
5560 // which case doing replaceUsesOfWith leads to replacing both operands
5561 // with the same value. TODO: Reorganize this.
5562 if (LU
.Kind
== LSRUse::ICmpZero
)
5563 LF
.UserInst
->setOperand(0, FullV
);
5565 LF
.UserInst
->replaceUsesOfWith(LF
.OperandValToReplace
, FullV
);
5568 if (auto *OperandIsInstr
= dyn_cast
<Instruction
>(LF
.OperandValToReplace
))
5569 DeadInsts
.emplace_back(OperandIsInstr
);
5572 /// Rewrite all the fixup locations with new values, following the chosen
5574 void LSRInstance::ImplementSolution(
5575 const SmallVectorImpl
<const Formula
*> &Solution
) {
5576 // Keep track of instructions we may have made dead, so that
5577 // we can remove them after we are done working.
5578 SmallVector
<WeakTrackingVH
, 16> DeadInsts
;
5580 SCEVExpander
Rewriter(SE
, L
->getHeader()->getModule()->getDataLayout(), "lsr",
5583 Rewriter
.setDebugType(DEBUG_TYPE
);
5585 Rewriter
.disableCanonicalMode();
5586 Rewriter
.enableLSRMode();
5587 Rewriter
.setIVIncInsertPos(L
, IVIncInsertPos
);
5589 // Mark phi nodes that terminate chains so the expander tries to reuse them.
5590 for (const IVChain
&Chain
: IVChainVec
) {
5591 if (PHINode
*PN
= dyn_cast
<PHINode
>(Chain
.tailUserInst()))
5592 Rewriter
.setChainedPhi(PN
);
5595 // Expand the new value definitions and update the users.
5596 for (size_t LUIdx
= 0, NumUses
= Uses
.size(); LUIdx
!= NumUses
; ++LUIdx
)
5597 for (const LSRFixup
&Fixup
: Uses
[LUIdx
].Fixups
) {
5598 Rewrite(Uses
[LUIdx
], Fixup
, *Solution
[LUIdx
], Rewriter
, DeadInsts
);
5602 for (const IVChain
&Chain
: IVChainVec
) {
5603 GenerateIVChain(Chain
, Rewriter
, DeadInsts
);
5607 for (const WeakVH
&IV
: Rewriter
.getInsertedIVs())
5608 if (IV
&& dyn_cast
<Instruction
>(&*IV
)->getParent())
5609 ScalarEvolutionIVs
.push_back(IV
);
5611 // Clean up after ourselves. This must be done before deleting any
5615 Changed
|= RecursivelyDeleteTriviallyDeadInstructionsPermissive(DeadInsts
,
5618 // In our cost analysis above, we assume that each addrec consumes exactly
5619 // one register, and arrange to have increments inserted just before the
5620 // latch to maximimize the chance this is true. However, if we reused
5621 // existing IVs, we now need to move the increments to match our
5622 // expectations. Otherwise, our cost modeling results in us having a
5623 // chosen a non-optimal result for the actual schedule. (And yes, this
5624 // scheduling decision does impact later codegen.)
5625 for (PHINode
&PN
: L
->getHeader()->phis()) {
5626 BinaryOperator
*BO
= nullptr;
5627 Value
*Start
= nullptr, *Step
= nullptr;
5628 if (!matchSimpleRecurrence(&PN
, BO
, Start
, Step
))
5631 switch (BO
->getOpcode()) {
5632 case Instruction::Sub
:
5633 if (BO
->getOperand(0) != &PN
)
5634 // sub is non-commutative - match handling elsewhere in LSR
5637 case Instruction::Add
:
5643 if (!isa
<Constant
>(Step
))
5644 // If not a constant step, might increase register pressure
5645 // (We assume constants have been canonicalized to RHS)
5648 if (BO
->getParent() == IVIncInsertPos
->getParent())
5649 // Only bother moving across blocks. Isel can handle block local case.
5652 // Can we legally schedule inc at the desired point?
5653 if (!llvm::all_of(BO
->uses(),
5654 [&](Use
&U
) {return DT
.dominates(IVIncInsertPos
, U
);}))
5656 BO
->moveBefore(IVIncInsertPos
);
5663 LSRInstance::LSRInstance(Loop
*L
, IVUsers
&IU
, ScalarEvolution
&SE
,
5664 DominatorTree
&DT
, LoopInfo
&LI
,
5665 const TargetTransformInfo
&TTI
, AssumptionCache
&AC
,
5666 TargetLibraryInfo
&TLI
, MemorySSAUpdater
*MSSAU
)
5667 : IU(IU
), SE(SE
), DT(DT
), LI(LI
), AC(AC
), TLI(TLI
), TTI(TTI
), L(L
),
5668 MSSAU(MSSAU
), AMK(PreferredAddresingMode
.getNumOccurrences() > 0 ?
5669 PreferredAddresingMode
: TTI
.getPreferredAddressingMode(L
, &SE
)) {
5670 // If LoopSimplify form is not available, stay out of trouble.
5671 if (!L
->isLoopSimplifyForm())
5674 // If there's no interesting work to be done, bail early.
5675 if (IU
.empty()) return;
5677 // If there's too much analysis to be done, bail early. We won't be able to
5678 // model the problem anyway.
5679 unsigned NumUsers
= 0;
5680 for (const IVStrideUse
&U
: IU
) {
5681 if (++NumUsers
> MaxIVUsers
) {
5683 LLVM_DEBUG(dbgs() << "LSR skipping loop, too many IV Users in " << U
5687 // Bail out if we have a PHI on an EHPad that gets a value from a
5688 // CatchSwitchInst. Because the CatchSwitchInst cannot be split, there is
5689 // no good place to stick any instructions.
5690 if (auto *PN
= dyn_cast
<PHINode
>(U
.getUser())) {
5691 auto *FirstNonPHI
= PN
->getParent()->getFirstNonPHI();
5692 if (isa
<FuncletPadInst
>(FirstNonPHI
) ||
5693 isa
<CatchSwitchInst
>(FirstNonPHI
))
5694 for (BasicBlock
*PredBB
: PN
->blocks())
5695 if (isa
<CatchSwitchInst
>(PredBB
->getFirstNonPHI()))
5701 // All dominating loops must have preheaders, or SCEVExpander may not be able
5702 // to materialize an AddRecExpr whose Start is an outer AddRecExpr.
5704 // IVUsers analysis should only create users that are dominated by simple loop
5705 // headers. Since this loop should dominate all of its users, its user list
5706 // should be empty if this loop itself is not within a simple loop nest.
5707 for (DomTreeNode
*Rung
= DT
.getNode(L
->getLoopPreheader());
5708 Rung
; Rung
= Rung
->getIDom()) {
5709 BasicBlock
*BB
= Rung
->getBlock();
5710 const Loop
*DomLoop
= LI
.getLoopFor(BB
);
5711 if (DomLoop
&& DomLoop
->getHeader() == BB
) {
5712 assert(DomLoop
->getLoopPreheader() && "LSR needs a simplified loop nest");
5717 LLVM_DEBUG(dbgs() << "\nLSR on loop ";
5718 L
->getHeader()->printAsOperand(dbgs(), /*PrintType=*/false);
5721 // First, perform some low-level loop optimizations.
5723 OptimizeLoopTermCond();
5725 // If loop preparation eliminates all interesting IV users, bail.
5726 if (IU
.empty()) return;
5728 // Skip nested loops until we can model them better with formulae.
5729 if (!L
->isInnermost()) {
5730 LLVM_DEBUG(dbgs() << "LSR skipping outer loop " << *L
<< "\n");
5734 // Start collecting data and preparing for the solver.
5735 // If number of registers is not the major cost, we cannot benefit from the
5736 // current profitable chain optimization which is based on number of
5738 // FIXME: add profitable chain optimization for other kinds major cost, for
5739 // example number of instructions.
5740 if (TTI
.isNumRegsMajorCostOfLSR() || StressIVChain
)
5742 CollectInterestingTypesAndFactors();
5743 CollectFixupsAndInitialFormulae();
5744 CollectLoopInvariantFixupsAndFormulae();
5749 LLVM_DEBUG(dbgs() << "LSR found " << Uses
.size() << " uses:\n";
5750 print_uses(dbgs()));
5752 // Now use the reuse data to generate a bunch of interesting ways
5753 // to formulate the values needed for the uses.
5754 GenerateAllReuseFormulae();
5756 FilterOutUndesirableDedicatedRegisters();
5757 NarrowSearchSpaceUsingHeuristics();
5759 SmallVector
<const Formula
*, 8> Solution
;
5762 // Release memory that is no longer needed.
5767 if (Solution
.empty())
5771 // Formulae should be legal.
5772 for (const LSRUse
&LU
: Uses
) {
5773 for (const Formula
&F
: LU
.Formulae
)
5774 assert(isLegalUse(TTI
, LU
.MinOffset
, LU
.MaxOffset
, LU
.Kind
, LU
.AccessTy
,
5775 F
) && "Illegal formula generated!");
5779 // Now that we've decided what we want, make it so.
5780 ImplementSolution(Solution
);
5783 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5784 void LSRInstance::print_factors_and_types(raw_ostream
&OS
) const {
5785 if (Factors
.empty() && Types
.empty()) return;
5787 OS
<< "LSR has identified the following interesting factors and types: ";
5790 for (int64_t Factor
: Factors
) {
5791 if (!First
) OS
<< ", ";
5793 OS
<< '*' << Factor
;
5796 for (Type
*Ty
: Types
) {
5797 if (!First
) OS
<< ", ";
5799 OS
<< '(' << *Ty
<< ')';
5804 void LSRInstance::print_fixups(raw_ostream
&OS
) const {
5805 OS
<< "LSR is examining the following fixup sites:\n";
5806 for (const LSRUse
&LU
: Uses
)
5807 for (const LSRFixup
&LF
: LU
.Fixups
) {
5814 void LSRInstance::print_uses(raw_ostream
&OS
) const {
5815 OS
<< "LSR is examining the following uses:\n";
5816 for (const LSRUse
&LU
: Uses
) {
5820 for (const Formula
&F
: LU
.Formulae
) {
5828 void LSRInstance::print(raw_ostream
&OS
) const {
5829 print_factors_and_types(OS
);
5834 LLVM_DUMP_METHOD
void LSRInstance::dump() const {
5835 print(errs()); errs() << '\n';
5841 class LoopStrengthReduce
: public LoopPass
{
5843 static char ID
; // Pass ID, replacement for typeid
5845 LoopStrengthReduce();
5848 bool runOnLoop(Loop
*L
, LPPassManager
&LPM
) override
;
5849 void getAnalysisUsage(AnalysisUsage
&AU
) const override
;
5852 } // end anonymous namespace
5854 LoopStrengthReduce::LoopStrengthReduce() : LoopPass(ID
) {
5855 initializeLoopStrengthReducePass(*PassRegistry::getPassRegistry());
5858 void LoopStrengthReduce::getAnalysisUsage(AnalysisUsage
&AU
) const {
5859 // We split critical edges, so we change the CFG. However, we do update
5860 // many analyses if they are around.
5861 AU
.addPreservedID(LoopSimplifyID
);
5863 AU
.addRequired
<LoopInfoWrapperPass
>();
5864 AU
.addPreserved
<LoopInfoWrapperPass
>();
5865 AU
.addRequiredID(LoopSimplifyID
);
5866 AU
.addRequired
<DominatorTreeWrapperPass
>();
5867 AU
.addPreserved
<DominatorTreeWrapperPass
>();
5868 AU
.addRequired
<ScalarEvolutionWrapperPass
>();
5869 AU
.addPreserved
<ScalarEvolutionWrapperPass
>();
5870 AU
.addRequired
<AssumptionCacheTracker
>();
5871 AU
.addRequired
<TargetLibraryInfoWrapperPass
>();
5872 // Requiring LoopSimplify a second time here prevents IVUsers from running
5873 // twice, since LoopSimplify was invalidated by running ScalarEvolution.
5874 AU
.addRequiredID(LoopSimplifyID
);
5875 AU
.addRequired
<IVUsersWrapperPass
>();
5876 AU
.addPreserved
<IVUsersWrapperPass
>();
5877 AU
.addRequired
<TargetTransformInfoWrapperPass
>();
5878 AU
.addPreserved
<MemorySSAWrapperPass
>();
5881 struct SCEVDbgValueBuilder
{
5882 SCEVDbgValueBuilder() = default;
5883 SCEVDbgValueBuilder(const SCEVDbgValueBuilder
&Base
) {
5884 Values
= Base
.Values
;
5888 /// The DIExpression as we translate the SCEV.
5889 SmallVector
<uint64_t, 6> Expr
;
5890 /// The location ops of the DIExpression.
5891 SmallVector
<llvm::ValueAsMetadata
*, 2> Values
;
5893 void pushOperator(uint64_t Op
) { Expr
.push_back(Op
); }
5894 void pushUInt(uint64_t Operand
) { Expr
.push_back(Operand
); }
5896 /// Add a DW_OP_LLVM_arg to the expression, followed by the index of the value
5897 /// in the set of values referenced by the expression.
5898 void pushValue(llvm::Value
*V
) {
5899 Expr
.push_back(llvm::dwarf::DW_OP_LLVM_arg
);
5901 std::find(Values
.begin(), Values
.end(), llvm::ValueAsMetadata::get(V
));
5902 unsigned ArgIndex
= 0;
5903 if (It
!= Values
.end()) {
5904 ArgIndex
= std::distance(Values
.begin(), It
);
5906 ArgIndex
= Values
.size();
5907 Values
.push_back(llvm::ValueAsMetadata::get(V
));
5909 Expr
.push_back(ArgIndex
);
5912 void pushValue(const SCEVUnknown
*U
) {
5913 llvm::Value
*V
= cast
<SCEVUnknown
>(U
)->getValue();
5917 bool pushConst(const SCEVConstant
*C
) {
5918 if (C
->getAPInt().getMinSignedBits() > 64)
5920 Expr
.push_back(llvm::dwarf::DW_OP_consts
);
5921 Expr
.push_back(C
->getAPInt().getSExtValue());
5925 /// Several SCEV types are sequences of the same arithmetic operator applied
5926 /// to constants and values that may be extended or truncated.
5927 bool pushArithmeticExpr(const llvm::SCEVCommutativeExpr
*CommExpr
,
5929 assert((isa
<llvm::SCEVAddExpr
>(CommExpr
) || isa
<SCEVMulExpr
>(CommExpr
)) &&
5930 "Expected arithmetic SCEV type");
5931 bool Success
= true;
5932 unsigned EmitOperator
= 0;
5933 for (auto &Op
: CommExpr
->operands()) {
5934 Success
&= pushSCEV(Op
);
5936 if (EmitOperator
>= 1)
5937 pushOperator(DwarfOp
);
5943 // TODO: Identify and omit noop casts.
5944 bool pushCast(const llvm::SCEVCastExpr
*C
, bool IsSigned
) {
5945 const llvm::SCEV
*Inner
= C
->getOperand(0);
5946 const llvm::Type
*Type
= C
->getType();
5947 uint64_t ToWidth
= Type
->getIntegerBitWidth();
5948 bool Success
= pushSCEV(Inner
);
5949 uint64_t CastOps
[] = {dwarf::DW_OP_LLVM_convert
, ToWidth
,
5950 IsSigned
? llvm::dwarf::DW_ATE_signed
5951 : llvm::dwarf::DW_ATE_unsigned
};
5952 for (const auto &Op
: CastOps
)
5957 // TODO: MinMax - although these haven't been encountered in the test suite.
5958 bool pushSCEV(const llvm::SCEV
*S
) {
5959 bool Success
= true;
5960 if (const SCEVConstant
*StartInt
= dyn_cast
<SCEVConstant
>(S
)) {
5961 Success
&= pushConst(StartInt
);
5963 } else if (const SCEVUnknown
*U
= dyn_cast
<SCEVUnknown
>(S
)) {
5966 pushValue(U
->getValue());
5968 } else if (const SCEVMulExpr
*MulRec
= dyn_cast
<SCEVMulExpr
>(S
)) {
5969 Success
&= pushArithmeticExpr(MulRec
, llvm::dwarf::DW_OP_mul
);
5971 } else if (const SCEVUDivExpr
*UDiv
= dyn_cast
<SCEVUDivExpr
>(S
)) {
5972 Success
&= pushSCEV(UDiv
->getLHS());
5973 Success
&= pushSCEV(UDiv
->getRHS());
5974 pushOperator(llvm::dwarf::DW_OP_div
);
5976 } else if (const SCEVCastExpr
*Cast
= dyn_cast
<SCEVCastExpr
>(S
)) {
5977 // Assert if a new and unknown SCEVCastEXpr type is encountered.
5978 assert((isa
<SCEVZeroExtendExpr
>(Cast
) || isa
<SCEVTruncateExpr
>(Cast
) ||
5979 isa
<SCEVPtrToIntExpr
>(Cast
) || isa
<SCEVSignExtendExpr
>(Cast
)) &&
5980 "Unexpected cast type in SCEV.");
5981 Success
&= pushCast(Cast
, (isa
<SCEVSignExtendExpr
>(Cast
)));
5983 } else if (const SCEVAddExpr
*AddExpr
= dyn_cast
<SCEVAddExpr
>(S
)) {
5984 Success
&= pushArithmeticExpr(AddExpr
, llvm::dwarf::DW_OP_plus
);
5986 } else if (isa
<SCEVAddRecExpr
>(S
)) {
5987 // Nested SCEVAddRecExpr are generated by nested loops and are currently
5997 void setFinalExpression(llvm::DbgValueInst
&DI
, const DIExpression
*OldExpr
) {
5998 // Re-state assumption that this dbg.value is not variadic. Any remaining
5999 // opcodes in its expression operate on a single value already on the
6000 // expression stack. Prepend our operations, which will re-compute and
6001 // place that value on the expression stack.
6002 assert(!DI
.hasArgList());
6004 DIExpression::prependOpcodes(OldExpr
, Expr
, /*StackValue*/ true);
6005 DI
.setExpression(NewExpr
);
6007 auto ValArrayRef
= llvm::ArrayRef
<llvm::ValueAsMetadata
*>(Values
);
6008 DI
.setRawLocation(llvm::DIArgList::get(DI
.getContext(), ValArrayRef
));
6011 /// If a DVI can be emitted without a DIArgList, omit DW_OP_llvm_arg and the
6012 /// location op index 0.
6013 void setShortFinalExpression(llvm::DbgValueInst
&DI
,
6014 const DIExpression
*OldExpr
) {
6015 assert((Expr
[0] == llvm::dwarf::DW_OP_LLVM_arg
&& Expr
[1] == 0) &&
6016 "Expected DW_OP_llvm_arg and 0.");
6017 DI
.replaceVariableLocationOp(
6018 0u, llvm::MetadataAsValue::get(DI
.getContext(), Values
[0]));
6020 // See setFinalExpression: prepend our opcodes on the start of any old
6021 // expression opcodes.
6022 assert(!DI
.hasArgList());
6023 llvm::SmallVector
<uint64_t, 6> FinalExpr(Expr
.begin() + 2, Expr
.end());
6025 DIExpression::prependOpcodes(OldExpr
, FinalExpr
, /*StackValue*/ true);
6026 DI
.setExpression(NewExpr
);
6029 /// Once the IV and variable SCEV translation is complete, write it to the
6031 void applyExprToDbgValue(llvm::DbgValueInst
&DI
,
6032 const DIExpression
*OldExpr
) {
6033 assert(!Expr
.empty() && "Unexpected empty expression.");
6034 // Emit a simpler form if only a single location is referenced.
6035 if (Values
.size() == 1 && Expr
[0] == llvm::dwarf::DW_OP_LLVM_arg
&&
6037 setShortFinalExpression(DI
, OldExpr
);
6039 setFinalExpression(DI
, OldExpr
);
6043 /// Return true if the combination of arithmetic operator and underlying
6044 /// SCEV constant value is an identity function.
6045 bool isIdentityFunction(uint64_t Op
, const SCEV
*S
) {
6046 if (const SCEVConstant
*C
= dyn_cast
<SCEVConstant
>(S
)) {
6047 if (C
->getAPInt().getMinSignedBits() > 64)
6049 int64_t I
= C
->getAPInt().getSExtValue();
6051 case llvm::dwarf::DW_OP_plus
:
6052 case llvm::dwarf::DW_OP_minus
:
6054 case llvm::dwarf::DW_OP_mul
:
6055 case llvm::dwarf::DW_OP_div
:
6062 /// Convert a SCEV of a value to a DIExpression that is pushed onto the
6063 /// builder's expression stack. The stack should already contain an
6064 /// expression for the iteration count, so that it can be multiplied by
6065 /// the stride and added to the start.
6066 /// Components of the expression are omitted if they are an identity function.
6067 /// Chain (non-affine) SCEVs are not supported.
6068 bool SCEVToValueExpr(const llvm::SCEVAddRecExpr
&SAR
, ScalarEvolution
&SE
) {
6069 assert(SAR
.isAffine() && "Expected affine SCEV");
6070 // TODO: Is this check needed?
6071 if (isa
<SCEVAddRecExpr
>(SAR
.getStart()))
6074 const SCEV
*Start
= SAR
.getStart();
6075 const SCEV
*Stride
= SAR
.getStepRecurrence(SE
);
6077 // Skip pushing arithmetic noops.
6078 if (!isIdentityFunction(llvm::dwarf::DW_OP_mul
, Stride
)) {
6079 if (!pushSCEV(Stride
))
6081 pushOperator(llvm::dwarf::DW_OP_mul
);
6083 if (!isIdentityFunction(llvm::dwarf::DW_OP_plus
, Start
)) {
6084 if (!pushSCEV(Start
))
6086 pushOperator(llvm::dwarf::DW_OP_plus
);
6091 /// Convert a SCEV of a value to a DIExpression that is pushed onto the
6092 /// builder's expression stack. The stack should already contain an
6093 /// expression for the iteration count, so that it can be multiplied by
6094 /// the stride and added to the start.
6095 /// Components of the expression are omitted if they are an identity function.
6096 bool SCEVToIterCountExpr(const llvm::SCEVAddRecExpr
&SAR
,
6097 ScalarEvolution
&SE
) {
6098 assert(SAR
.isAffine() && "Expected affine SCEV");
6099 if (isa
<SCEVAddRecExpr
>(SAR
.getStart())) {
6100 LLVM_DEBUG(dbgs() << "scev-salvage: IV SCEV. Unsupported nested AddRec: "
6104 const SCEV
*Start
= SAR
.getStart();
6105 const SCEV
*Stride
= SAR
.getStepRecurrence(SE
);
6107 // Skip pushing arithmetic noops.
6108 if (!isIdentityFunction(llvm::dwarf::DW_OP_minus
, Start
)) {
6109 if (!pushSCEV(Start
))
6111 pushOperator(llvm::dwarf::DW_OP_minus
);
6113 if (!isIdentityFunction(llvm::dwarf::DW_OP_div
, Stride
)) {
6114 if (!pushSCEV(Stride
))
6116 pushOperator(llvm::dwarf::DW_OP_div
);
6122 struct DVIRecoveryRec
{
6125 Metadata
*LocationOp
;
6126 const llvm::SCEV
*SCEV
;
6129 static bool RewriteDVIUsingIterCount(DVIRecoveryRec CachedDVI
,
6130 const SCEVDbgValueBuilder
&IterationCount
,
6131 ScalarEvolution
&SE
) {
6132 // LSR may add locations to previously single location-op DVIs which
6133 // are currently not supported.
6134 if (CachedDVI
.DVI
->getNumVariableLocationOps() != 1)
6137 // SCEVs for SSA values are most frquently of the form
6138 // {start,+,stride}, but sometimes they are ({start,+,stride} + %a + ..).
6139 // This is because %a is a PHI node that is not the IV. However, these
6140 // SCEVs have not been observed to result in debuginfo-lossy optimisations,
6141 // so its not expected this point will be reached.
6142 if (!isa
<SCEVAddRecExpr
>(CachedDVI
.SCEV
))
6145 LLVM_DEBUG(dbgs() << "scev-salvage: Value to salvage SCEV: "
6146 << *CachedDVI
.SCEV
<< '\n');
6148 const auto *Rec
= cast
<SCEVAddRecExpr
>(CachedDVI
.SCEV
);
6149 if (!Rec
->isAffine())
6152 // Initialise a new builder with the iteration count expression. In
6153 // combination with the value's SCEV this enables recovery.
6154 SCEVDbgValueBuilder
RecoverValue(IterationCount
);
6155 if (!RecoverValue
.SCEVToValueExpr(*Rec
, SE
))
6158 LLVM_DEBUG(dbgs() << "scev-salvage: Updating: " << *CachedDVI
.DVI
<< '\n');
6159 RecoverValue
.applyExprToDbgValue(*CachedDVI
.DVI
, CachedDVI
.Expr
);
6160 LLVM_DEBUG(dbgs() << "scev-salvage: to: " << *CachedDVI
.DVI
<< '\n');
6165 DbgRewriteSalvageableDVIs(llvm::Loop
*L
, ScalarEvolution
&SE
,
6166 llvm::PHINode
*LSRInductionVar
,
6167 SmallVector
<DVIRecoveryRec
, 2> &DVIToUpdate
) {
6168 if (DVIToUpdate
.empty())
6171 const llvm::SCEV
*SCEVInductionVar
= SE
.getSCEV(LSRInductionVar
);
6172 assert(SCEVInductionVar
&&
6173 "Anticipated a SCEV for the post-LSR induction variable");
6175 bool Changed
= false;
6176 if (const SCEVAddRecExpr
*IVAddRec
=
6177 dyn_cast
<SCEVAddRecExpr
>(SCEVInductionVar
)) {
6178 if (!IVAddRec
->isAffine())
6181 SCEVDbgValueBuilder IterCountExpr
;
6182 IterCountExpr
.pushValue(LSRInductionVar
);
6183 if (!IterCountExpr
.SCEVToIterCountExpr(*IVAddRec
, SE
))
6186 LLVM_DEBUG(dbgs() << "scev-salvage: IV SCEV: " << *SCEVInductionVar
6189 // Needn't salvage if the location op hasn't been undef'd by LSR.
6190 for (auto &DVIRec
: DVIToUpdate
) {
6191 if (!DVIRec
.DVI
->isUndef())
6194 // Some DVIs that were single location-op when cached are now multi-op,
6195 // due to LSR optimisations. However, multi-op salvaging is not yet
6196 // supported by SCEV salvaging. But, we can attempt a salvage by restoring
6197 // the pre-LSR single-op expression.
6198 if (DVIRec
.DVI
->hasArgList()) {
6199 if (!DVIRec
.DVI
->getVariableLocationOp(0))
6201 llvm::Type
*Ty
= DVIRec
.DVI
->getVariableLocationOp(0)->getType();
6202 DVIRec
.DVI
->setRawLocation(
6203 llvm::ValueAsMetadata::get(UndefValue::get(Ty
)));
6204 DVIRec
.DVI
->setExpression(DVIRec
.Expr
);
6207 Changed
|= RewriteDVIUsingIterCount(DVIRec
, IterCountExpr
, SE
);
6213 /// Identify and cache salvageable DVI locations and expressions along with the
6214 /// corresponding SCEV(s). Also ensure that the DVI is not deleted before
6216 DbgGatherSalvagableDVI(Loop
*L
, ScalarEvolution
&SE
,
6217 SmallVector
<DVIRecoveryRec
, 2> &SalvageableDVISCEVs
,
6218 SmallSet
<AssertingVH
<DbgValueInst
>, 2> &DVIHandles
) {
6219 for (auto &B
: L
->getBlocks()) {
6220 for (auto &I
: *B
) {
6221 auto DVI
= dyn_cast
<DbgValueInst
>(&I
);
6228 if (DVI
->hasArgList())
6231 if (!DVI
->getVariableLocationOp(0) ||
6232 !SE
.isSCEVable(DVI
->getVariableLocationOp(0)->getType()))
6235 SalvageableDVISCEVs
.push_back(
6236 {DVI
, DVI
->getExpression(), DVI
->getRawLocation(),
6237 SE
.getSCEV(DVI
->getVariableLocationOp(0))});
6238 DVIHandles
.insert(DVI
);
6243 /// Ideally pick the PHI IV inserted by ScalarEvolutionExpander. As a fallback
6244 /// any PHi from the loop header is usable, but may have less chance of
6245 /// surviving subsequent transforms.
6246 static llvm::PHINode
*GetInductionVariable(const Loop
&L
, ScalarEvolution
&SE
,
6247 const LSRInstance
&LSR
) {
6248 // For now, just pick the first IV generated and inserted. Ideally pick an IV
6249 // that is unlikely to be optimised away by subsequent transforms.
6250 for (const WeakVH
&IV
: LSR
.getScalarEvolutionIVs()) {
6254 assert(isa
<PHINode
>(&*IV
) && "Expected PhI node.");
6255 if (SE
.isSCEVable((*IV
).getType())) {
6256 PHINode
*Phi
= dyn_cast
<PHINode
>(&*IV
);
6257 LLVM_DEBUG(dbgs() << "scev-salvage: IV : " << *IV
6258 << "with SCEV: " << *SE
.getSCEV(Phi
) << "\n");
6263 for (PHINode
&Phi
: L
.getHeader()->phis()) {
6264 if (!SE
.isSCEVable(Phi
.getType()))
6267 const llvm::SCEV
*PhiSCEV
= SE
.getSCEV(&Phi
);
6268 if (const llvm::SCEVAddRecExpr
*Rec
= dyn_cast
<SCEVAddRecExpr
>(PhiSCEV
))
6269 if (!Rec
->isAffine())
6272 LLVM_DEBUG(dbgs() << "scev-salvage: Selected IV from loop header: " << Phi
6273 << " with SCEV: " << *PhiSCEV
<< "\n");
6279 static bool ReduceLoopStrength(Loop
*L
, IVUsers
&IU
, ScalarEvolution
&SE
,
6280 DominatorTree
&DT
, LoopInfo
&LI
,
6281 const TargetTransformInfo
&TTI
,
6282 AssumptionCache
&AC
, TargetLibraryInfo
&TLI
,
6285 // Debug preservation - before we start removing anything identify which DVI
6286 // meet the salvageable criteria and store their DIExpression and SCEVs.
6287 SmallVector
<DVIRecoveryRec
, 2> SalvageableDVI
;
6288 SmallSet
<AssertingVH
<DbgValueInst
>, 2> DVIHandles
;
6289 DbgGatherSalvagableDVI(L
, SE
, SalvageableDVI
, DVIHandles
);
6291 bool Changed
= false;
6292 std::unique_ptr
<MemorySSAUpdater
> MSSAU
;
6294 MSSAU
= std::make_unique
<MemorySSAUpdater
>(MSSA
);
6296 // Run the main LSR transformation.
6297 const LSRInstance
&Reducer
=
6298 LSRInstance(L
, IU
, SE
, DT
, LI
, TTI
, AC
, TLI
, MSSAU
.get());
6299 Changed
|= Reducer
.getChanged();
6301 // Remove any extra phis created by processing inner loops.
6302 Changed
|= DeleteDeadPHIs(L
->getHeader(), &TLI
, MSSAU
.get());
6303 if (EnablePhiElim
&& L
->isLoopSimplifyForm()) {
6304 SmallVector
<WeakTrackingVH
, 16> DeadInsts
;
6305 const DataLayout
&DL
= L
->getHeader()->getModule()->getDataLayout();
6306 SCEVExpander
Rewriter(SE
, DL
, "lsr", false);
6308 Rewriter
.setDebugType(DEBUG_TYPE
);
6310 unsigned numFolded
= Rewriter
.replaceCongruentIVs(L
, &DT
, DeadInsts
, &TTI
);
6313 RecursivelyDeleteTriviallyDeadInstructionsPermissive(DeadInsts
, &TLI
,
6315 DeleteDeadPHIs(L
->getHeader(), &TLI
, MSSAU
.get());
6319 if (SalvageableDVI
.empty())
6322 // Obtain relevant IVs and attempt to rewrite the salvageable DVIs with
6323 // expressions composed using the derived iteration count.
6324 // TODO: Allow for multiple IV references for nested AddRecSCEVs
6325 for (auto &L
: LI
) {
6326 if (llvm::PHINode
*IV
= GetInductionVariable(*L
, SE
, Reducer
))
6327 DbgRewriteSalvageableDVIs(L
, SE
, IV
, SalvageableDVI
);
6329 LLVM_DEBUG(dbgs() << "scev-salvage: SCEV salvaging not possible. An IV "
6330 "could not be identified.\n");
6338 bool LoopStrengthReduce::runOnLoop(Loop
*L
, LPPassManager
& /*LPM*/) {
6342 auto &IU
= getAnalysis
<IVUsersWrapperPass
>().getIU();
6343 auto &SE
= getAnalysis
<ScalarEvolutionWrapperPass
>().getSE();
6344 auto &DT
= getAnalysis
<DominatorTreeWrapperPass
>().getDomTree();
6345 auto &LI
= getAnalysis
<LoopInfoWrapperPass
>().getLoopInfo();
6346 const auto &TTI
= getAnalysis
<TargetTransformInfoWrapperPass
>().getTTI(
6347 *L
->getHeader()->getParent());
6348 auto &AC
= getAnalysis
<AssumptionCacheTracker
>().getAssumptionCache(
6349 *L
->getHeader()->getParent());
6350 auto &TLI
= getAnalysis
<TargetLibraryInfoWrapperPass
>().getTLI(
6351 *L
->getHeader()->getParent());
6352 auto *MSSAAnalysis
= getAnalysisIfAvailable
<MemorySSAWrapperPass
>();
6353 MemorySSA
*MSSA
= nullptr;
6355 MSSA
= &MSSAAnalysis
->getMSSA();
6356 return ReduceLoopStrength(L
, IU
, SE
, DT
, LI
, TTI
, AC
, TLI
, MSSA
);
6359 PreservedAnalyses
LoopStrengthReducePass::run(Loop
&L
, LoopAnalysisManager
&AM
,
6360 LoopStandardAnalysisResults
&AR
,
6362 if (!ReduceLoopStrength(&L
, AM
.getResult
<IVUsersAnalysis
>(L
, AR
), AR
.SE
,
6363 AR
.DT
, AR
.LI
, AR
.TTI
, AR
.AC
, AR
.TLI
, AR
.MSSA
))
6364 return PreservedAnalyses::all();
6366 auto PA
= getLoopPassPreservedAnalyses();
6368 PA
.preserve
<MemorySSAAnalysis
>();
6372 char LoopStrengthReduce::ID
= 0;
6374 INITIALIZE_PASS_BEGIN(LoopStrengthReduce
, "loop-reduce",
6375 "Loop Strength Reduction", false, false)
6376 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass
)
6377 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass
)
6378 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass
)
6379 INITIALIZE_PASS_DEPENDENCY(IVUsersWrapperPass
)
6380 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass
)
6381 INITIALIZE_PASS_DEPENDENCY(LoopSimplify
)
6382 INITIALIZE_PASS_END(LoopStrengthReduce
, "loop-reduce",
6383 "Loop Strength Reduction", false, false)
6385 Pass
*llvm::createLoopStrengthReducePass() { return new LoopStrengthReduce(); }