1//===- LoopStrengthReduce.cpp - Strength Reduce IVs in Loops --------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// This transformation analyzes and transforms the induction variables (and
10// computations derived from them) into forms suitable for efficient execution
11// on the target.
12//
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.
18//
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:
22//
23// %i = phi [ 0, %entry ], [ %i.next, %latch ]
24// ...
25// %i.next = add %i, 1
26// %c = icmp eq %i.next, %n
27//
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.
34//
35// TODO: More sophistication in the way Formulae are generated and filtered.
36//
37// TODO: Handle multiple loops at a time.
38//
39// TODO: Should the addressing mode BaseGV be changed to a ConstantExpr instead
40// of a GlobalValue?
41//
42// TODO: When truncation is free, truncate ICmp users' operands to make it a
43// smaller encoding (on x86 at least).
44//
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"
51// use kind.
52//
53//===----------------------------------------------------------------------===//
54
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/PointerIntPair.h"
60#include "llvm/ADT/STLExtras.h"
61#include "llvm/ADT/SetVector.h"
62#include "llvm/ADT/SmallBitVector.h"
63#include "llvm/ADT/SmallPtrSet.h"
64#include "llvm/ADT/SmallSet.h"
65#include "llvm/ADT/SmallVector.h"
66#include "llvm/ADT/Statistic.h"
67#include "llvm/ADT/iterator_range.h"
68#include "llvm/Analysis/AssumptionCache.h"
69#include "llvm/Analysis/DomTreeUpdater.h"
70#include "llvm/Analysis/IVUsers.h"
71#include "llvm/Analysis/LoopAnalysisManager.h"
72#include "llvm/Analysis/LoopInfo.h"
73#include "llvm/Analysis/LoopPass.h"
74#include "llvm/Analysis/MemorySSA.h"
75#include "llvm/Analysis/MemorySSAUpdater.h"
76#include "llvm/Analysis/ScalarEvolution.h"
77#include "llvm/Analysis/ScalarEvolutionExpressions.h"
78#include "llvm/Analysis/ScalarEvolutionNormalization.h"
79#include "llvm/Analysis/ScalarEvolutionPatternMatch.h"
80#include "llvm/Analysis/TargetLibraryInfo.h"
81#include "llvm/Analysis/TargetTransformInfo.h"
82#include "llvm/Analysis/ValueTracking.h"
83#include "llvm/BinaryFormat/Dwarf.h"
84#include "llvm/IR/BasicBlock.h"
85#include "llvm/IR/Constant.h"
86#include "llvm/IR/Constants.h"
87#include "llvm/IR/DebugInfoMetadata.h"
88#include "llvm/IR/DerivedTypes.h"
89#include "llvm/IR/Dominators.h"
90#include "llvm/IR/GlobalValue.h"
91#include "llvm/IR/IRBuilder.h"
92#include "llvm/IR/InstrTypes.h"
93#include "llvm/IR/Instruction.h"
94#include "llvm/IR/Instructions.h"
95#include "llvm/IR/IntrinsicInst.h"
96#include "llvm/IR/Module.h"
97#include "llvm/IR/Operator.h"
98#include "llvm/IR/Type.h"
99#include "llvm/IR/Use.h"
100#include "llvm/IR/User.h"
101#include "llvm/IR/Value.h"
102#include "llvm/IR/ValueHandle.h"
103#include "llvm/InitializePasses.h"
104#include "llvm/Pass.h"
105#include "llvm/Support/Casting.h"
106#include "llvm/Support/CommandLine.h"
107#include "llvm/Support/Compiler.h"
108#include "llvm/Support/Debug.h"
109#include "llvm/Support/ErrorHandling.h"
110#include "llvm/Support/MathExtras.h"
111#include "llvm/Support/raw_ostream.h"
112#include "llvm/Transforms/Scalar.h"
113#include "llvm/Transforms/Utils.h"
114#include "llvm/Transforms/Utils/BasicBlockUtils.h"
115#include "llvm/Transforms/Utils/Local.h"
116#include "llvm/Transforms/Utils/LoopUtils.h"
117#include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
118#include <algorithm>
119#include <cassert>
120#include <cstddef>
121#include <cstdint>
122#include <iterator>
123#include <limits>
124#include <map>
125#include <numeric>
126#include <optional>
127#include <utility>
128
129using namespace llvm;
130using namespace SCEVPatternMatch;
131
132#define DEBUG_TYPE "loop-reduce"
133
134/// MaxIVUsers is an arbitrary threshold that provides an early opportunity for
135/// bail out. This threshold is far beyond the number of users that LSR can
136/// conceivably solve, so it should not affect generated code, but catches the
137/// worst cases before LSR burns too much compile time and stack space.
138static const unsigned MaxIVUsers = 200;
139
140/// Limit the size of expression that SCEV-based salvaging will attempt to
141/// translate into a DIExpression.
142/// Choose a maximum size such that debuginfo is not excessively increased and
143/// the salvaging is not too expensive for the compiler.
144static const unsigned MaxSCEVSalvageExpressionSize = 64;
145
146// Cleanup congruent phis after LSR phi expansion.
147static cl::opt<bool> EnablePhiElim(
148 "enable-lsr-phielim", cl::Hidden, cl::init(Val: true),
149 cl::desc("Enable LSR phi elimination"));
150
151// The flag adds instruction count to solutions cost comparison.
152static cl::opt<bool> InsnsCost(
153 "lsr-insns-cost", cl::Hidden, cl::init(Val: true),
154 cl::desc("Add instruction count to a LSR cost model"));
155
156// Flag to choose how to narrow complex lsr solution
157static cl::opt<bool> LSRExpNarrow(
158 "lsr-exp-narrow", cl::Hidden, cl::init(Val: false),
159 cl::desc("Narrow LSR complex solution using"
160 " expectation of registers number"));
161
162// Flag to narrow search space by filtering non-optimal formulae with
163// the same ScaledReg and Scale.
164static cl::opt<bool> FilterSameScaledReg(
165 "lsr-filter-same-scaled-reg", cl::Hidden, cl::init(Val: true),
166 cl::desc("Narrow LSR search space by filtering non-optimal formulae"
167 " with the same ScaledReg and Scale"));
168
169static cl::opt<TTI::AddressingModeKind> PreferredAddresingMode(
170 "lsr-preferred-addressing-mode", cl::Hidden, cl::init(Val: TTI::AMK_None),
171 cl::desc("A flag that overrides the target's preferred addressing mode."),
172 cl::values(
173 clEnumValN(TTI::AMK_None, "none", "Don't prefer any addressing mode"),
174 clEnumValN(TTI::AMK_PreIndexed, "preindexed",
175 "Prefer pre-indexed addressing mode"),
176 clEnumValN(TTI::AMK_PostIndexed, "postindexed",
177 "Prefer post-indexed addressing mode"),
178 clEnumValN(TTI::AMK_All, "all", "Consider all addressing modes")));
179
180static cl::opt<unsigned> ComplexityLimit(
181 "lsr-complexity-limit", cl::Hidden,
182 cl::init(Val: std::numeric_limits<uint16_t>::max()),
183 cl::desc("LSR search space complexity limit"));
184
185static cl::opt<unsigned> SetupCostDepthLimit(
186 "lsr-setupcost-depth-limit", cl::Hidden, cl::init(Val: 7),
187 cl::desc("The limit on recursion depth for LSRs setup cost"));
188
189static cl::opt<cl::boolOrDefault> AllowDropSolutionIfLessProfitable(
190 "lsr-drop-solution", cl::Hidden,
191 cl::desc("Attempt to drop solution if it is less profitable"));
192
193static cl::opt<bool> EnableVScaleImmediates(
194 "lsr-enable-vscale-immediates", cl::Hidden, cl::init(Val: true),
195 cl::desc("Enable analysis of vscale-relative immediates in LSR"));
196
197static cl::opt<bool> DropScaledForVScale(
198 "lsr-drop-scaled-reg-for-vscale", cl::Hidden, cl::init(Val: true),
199 cl::desc("Avoid using scaled registers with vscale-relative addressing"));
200
201#ifndef NDEBUG
202// Stress test IV chain generation.
203static cl::opt<bool> StressIVChain(
204 "stress-ivchain", cl::Hidden, cl::init(false),
205 cl::desc("Stress test LSR IV chains"));
206#else
207static bool StressIVChain = false;
208#endif
209
210namespace {
211
212struct MemAccessTy {
213 /// Used in situations where the accessed memory type is unknown.
214 static const unsigned UnknownAddressSpace =
215 std::numeric_limits<unsigned>::max();
216
217 Type *MemTy = nullptr;
218 unsigned AddrSpace = UnknownAddressSpace;
219
220 MemAccessTy() = default;
221 MemAccessTy(Type *Ty, unsigned AS) : MemTy(Ty), AddrSpace(AS) {}
222
223 bool operator==(MemAccessTy Other) const {
224 return MemTy == Other.MemTy && AddrSpace == Other.AddrSpace;
225 }
226
227 bool operator!=(MemAccessTy Other) const { return !(*this == Other); }
228
229 static MemAccessTy getUnknown(LLVMContext &Ctx,
230 unsigned AS = UnknownAddressSpace) {
231 return MemAccessTy(Type::getVoidTy(C&: Ctx), AS);
232 }
233
234 Type *getType() { return MemTy; }
235};
236
237/// This class holds data which is used to order reuse candidates.
238class RegSortData {
239public:
240 /// This represents the set of LSRUse indices which reference
241 /// a particular register.
242 SmallBitVector UsedByIndices;
243
244 void print(raw_ostream &OS) const;
245 void dump() const;
246};
247
248// An offset from an address that is either scalable or fixed. Used for
249// per-target optimizations of addressing modes.
250class Immediate : public details::FixedOrScalableQuantity<Immediate, int64_t> {
251 constexpr Immediate(ScalarTy MinVal, bool Scalable)
252 : FixedOrScalableQuantity(MinVal, Scalable) {}
253
254 constexpr Immediate(const FixedOrScalableQuantity<Immediate, int64_t> &V)
255 : FixedOrScalableQuantity(V) {}
256
257public:
258 constexpr Immediate() = delete;
259
260 static constexpr Immediate getFixed(ScalarTy MinVal) {
261 return {MinVal, false};
262 }
263 static constexpr Immediate getScalable(ScalarTy MinVal) {
264 return {MinVal, true};
265 }
266 static constexpr Immediate get(ScalarTy MinVal, bool Scalable) {
267 return {MinVal, Scalable};
268 }
269 static constexpr Immediate getZero() { return {0, false}; }
270 static constexpr Immediate getFixedMin() {
271 return {std::numeric_limits<int64_t>::min(), false};
272 }
273 static constexpr Immediate getFixedMax() {
274 return {std::numeric_limits<int64_t>::max(), false};
275 }
276 static constexpr Immediate getScalableMin() {
277 return {std::numeric_limits<int64_t>::min(), true};
278 }
279 static constexpr Immediate getScalableMax() {
280 return {std::numeric_limits<int64_t>::max(), true};
281 }
282
283 constexpr bool isLessThanZero() const { return Quantity < 0; }
284
285 constexpr bool isGreaterThanZero() const { return Quantity > 0; }
286
287 constexpr bool isCompatibleImmediate(const Immediate &Imm) const {
288 return isZero() || Imm.isZero() || Imm.Scalable == Scalable;
289 }
290
291 constexpr bool isMin() const {
292 return Quantity == std::numeric_limits<ScalarTy>::min();
293 }
294
295 constexpr bool isMax() const {
296 return Quantity == std::numeric_limits<ScalarTy>::max();
297 }
298
299 // Arithmetic 'operators' that cast to unsigned types first.
300 constexpr Immediate addUnsigned(const Immediate &RHS) const {
301 assert(isCompatibleImmediate(RHS) && "Incompatible Immediates");
302 ScalarTy Value = (uint64_t)Quantity + RHS.getKnownMinValue();
303 return {Value, Scalable || RHS.isScalable()};
304 }
305
306 constexpr Immediate subUnsigned(const Immediate &RHS) const {
307 assert(isCompatibleImmediate(RHS) && "Incompatible Immediates");
308 ScalarTy Value = (uint64_t)Quantity - RHS.getKnownMinValue();
309 return {Value, Scalable || RHS.isScalable()};
310 }
311
312 // Scale the quantity by a constant without caring about runtime scalability.
313 constexpr Immediate mulUnsigned(const ScalarTy RHS) const {
314 ScalarTy Value = (uint64_t)Quantity * RHS;
315 return {Value, Scalable};
316 }
317
318 // Helpers for generating SCEVs with vscale terms where needed.
319 const SCEV *getSCEV(ScalarEvolution &SE, Type *Ty) const {
320 const SCEV *S = SE.getConstant(Ty, V: Quantity);
321 if (Scalable)
322 S = SE.getMulExpr(LHS: S, RHS: SE.getVScale(Ty: S->getType()));
323 return S;
324 }
325
326 const SCEV *getNegativeSCEV(ScalarEvolution &SE, Type *Ty) const {
327 const SCEV *NegS = SE.getConstant(Ty, V: -(uint64_t)Quantity);
328 if (Scalable)
329 NegS = SE.getMulExpr(LHS: NegS, RHS: SE.getVScale(Ty: NegS->getType()));
330 return NegS;
331 }
332
333 const SCEV *getUnknownSCEV(ScalarEvolution &SE, Type *Ty) const {
334 // TODO: Avoid implicit trunc?
335 // See https://github.com/llvm/llvm-project/issues/112510.
336 const SCEV *SU = SE.getUnknown(
337 V: ConstantInt::getSigned(Ty, V: Quantity, /*ImplicitTrunc=*/true));
338 if (Scalable)
339 SU = SE.getMulExpr(LHS: SU, RHS: SE.getVScale(Ty: SU->getType()));
340 return SU;
341 }
342};
343
344// This is needed for the Compare type of std::map when Immediate is used
345// as a key. We don't need it to be fully correct against any value of vscale,
346// just to make sure that vscale-related terms in the map are considered against
347// each other rather than being mixed up and potentially missing opportunities.
348struct KeyOrderTargetImmediate {
349 bool operator()(const Immediate &LHS, const Immediate &RHS) const {
350 if (LHS.isScalable() && !RHS.isScalable())
351 return false;
352 if (!LHS.isScalable() && RHS.isScalable())
353 return true;
354 return LHS.getKnownMinValue() < RHS.getKnownMinValue();
355 }
356};
357
358// This would be nicer if we could be generic instead of directly using size_t,
359// but there doesn't seem to be a type trait for is_orderable or
360// is_lessthan_comparable or similar.
361struct KeyOrderSizeTAndImmediate {
362 bool operator()(const std::pair<size_t, Immediate> &LHS,
363 const std::pair<size_t, Immediate> &RHS) const {
364 size_t LSize = LHS.first;
365 size_t RSize = RHS.first;
366 if (LSize != RSize)
367 return LSize < RSize;
368 return KeyOrderTargetImmediate()(LHS.second, RHS.second);
369 }
370};
371} // end anonymous namespace
372
373#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
374void RegSortData::print(raw_ostream &OS) const {
375 OS << "[NumUses=" << UsedByIndices.count() << ']';
376}
377
378LLVM_DUMP_METHOD void RegSortData::dump() const {
379 print(errs()); errs() << '\n';
380}
381#endif
382
383namespace {
384
385/// Map register candidates to information about how they are used.
386class RegUseTracker {
387 using RegUsesTy = DenseMap<const SCEV *, RegSortData>;
388
389 RegUsesTy RegUsesMap;
390 SmallVector<const SCEV *, 16> RegSequence;
391
392public:
393 void countRegister(const SCEV *Reg, size_t LUIdx);
394 void dropRegister(const SCEV *Reg, size_t LUIdx);
395 void swapAndDropUse(size_t LUIdx, size_t LastLUIdx);
396
397 bool isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const;
398
399 const SmallBitVector &getUsedByIndices(const SCEV *Reg) const;
400
401 void clear();
402
403 using iterator = SmallVectorImpl<const SCEV *>::iterator;
404 using const_iterator = SmallVectorImpl<const SCEV *>::const_iterator;
405
406 iterator begin() { return RegSequence.begin(); }
407 iterator end() { return RegSequence.end(); }
408 const_iterator begin() const { return RegSequence.begin(); }
409 const_iterator end() const { return RegSequence.end(); }
410};
411
412} // end anonymous namespace
413
414void
415RegUseTracker::countRegister(const SCEV *Reg, size_t LUIdx) {
416 std::pair<RegUsesTy::iterator, bool> Pair = RegUsesMap.try_emplace(Key: Reg);
417 RegSortData &RSD = Pair.first->second;
418 if (Pair.second)
419 RegSequence.push_back(Elt: Reg);
420 RSD.UsedByIndices.resize(N: std::max(a: RSD.UsedByIndices.size(), b: LUIdx + 1));
421 RSD.UsedByIndices.set(LUIdx);
422}
423
424void
425RegUseTracker::dropRegister(const SCEV *Reg, size_t LUIdx) {
426 RegUsesTy::iterator It = RegUsesMap.find(Val: Reg);
427 assert(It != RegUsesMap.end());
428 RegSortData &RSD = It->second;
429 assert(RSD.UsedByIndices.size() > LUIdx);
430 RSD.UsedByIndices.reset(Idx: LUIdx);
431}
432
433void
434RegUseTracker::swapAndDropUse(size_t LUIdx, size_t LastLUIdx) {
435 assert(LUIdx <= LastLUIdx);
436
437 // Update RegUses. The data structure is not optimized for this purpose;
438 // we must iterate through it and update each of the bit vectors.
439 for (auto &Pair : RegUsesMap) {
440 SmallBitVector &UsedByIndices = Pair.second.UsedByIndices;
441 if (LUIdx < UsedByIndices.size())
442 UsedByIndices[LUIdx] =
443 LastLUIdx < UsedByIndices.size() ? UsedByIndices[LastLUIdx] : false;
444 UsedByIndices.resize(N: std::min(a: UsedByIndices.size(), b: LastLUIdx));
445 }
446}
447
448bool
449RegUseTracker::isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const {
450 RegUsesTy::const_iterator I = RegUsesMap.find(Val: Reg);
451 if (I == RegUsesMap.end())
452 return false;
453 const SmallBitVector &UsedByIndices = I->second.UsedByIndices;
454 int i = UsedByIndices.find_first();
455 if (i == -1) return false;
456 if ((size_t)i != LUIdx) return true;
457 return UsedByIndices.find_next(Prev: i) != -1;
458}
459
460const SmallBitVector &RegUseTracker::getUsedByIndices(const SCEV *Reg) const {
461 RegUsesTy::const_iterator I = RegUsesMap.find(Val: Reg);
462 assert(I != RegUsesMap.end() && "Unknown register!");
463 return I->second.UsedByIndices;
464}
465
466void RegUseTracker::clear() {
467 RegUsesMap.clear();
468 RegSequence.clear();
469}
470
471namespace {
472
473/// This class holds information that describes a formula for computing
474/// satisfying a use. It may include broken-out immediates and scaled registers.
475struct Formula {
476 /// Global base address used for complex addressing.
477 GlobalValue *BaseGV = nullptr;
478
479 /// Base offset for complex addressing.
480 Immediate BaseOffset = Immediate::getZero();
481
482 /// Whether any complex addressing has a base register.
483 bool HasBaseReg = false;
484
485 /// The scale of any complex addressing.
486 int64_t Scale = 0;
487
488 /// The list of "base" registers for this use. When this is non-empty. The
489 /// canonical representation of a formula is
490 /// 1. BaseRegs.size > 1 implies ScaledReg != NULL and
491 /// 2. ScaledReg != NULL implies Scale != 1 || !BaseRegs.empty().
492 /// 3. The reg containing recurrent expr related with currect loop in the
493 /// formula should be put in the ScaledReg.
494 /// #1 enforces that the scaled register is always used when at least two
495 /// registers are needed by the formula: e.g., reg1 + reg2 is reg1 + 1 * reg2.
496 /// #2 enforces that 1 * reg is reg.
497 /// #3 ensures invariant regs with respect to current loop can be combined
498 /// together in LSR codegen.
499 /// This invariant can be temporarily broken while building a formula.
500 /// However, every formula inserted into the LSRInstance must be in canonical
501 /// form.
502 SmallVector<const SCEV *, 4> BaseRegs;
503
504 /// The 'scaled' register for this use. This should be non-null when Scale is
505 /// not zero.
506 const SCEV *ScaledReg = nullptr;
507
508 /// An additional constant offset which added near the use. This requires a
509 /// temporary register, but the offset itself can live in an add immediate
510 /// field rather than a register.
511 Immediate UnfoldedOffset = Immediate::getZero();
512
513 Formula() = default;
514
515 void initialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE);
516
517 bool isCanonical(const Loop &L) const;
518
519 void canonicalize(const Loop &L);
520
521 bool unscale();
522
523 bool hasZeroEnd() const;
524
525 bool countsDownToZero() const;
526
527 size_t getNumRegs() const;
528 Type *getType() const;
529
530 void deleteBaseReg(const SCEV *&S);
531
532 bool referencesReg(const SCEV *S) const;
533 bool hasRegsUsedByUsesOtherThan(size_t LUIdx,
534 const RegUseTracker &RegUses) const;
535
536 void print(raw_ostream &OS) const;
537 void dump() const;
538};
539
540} // end anonymous namespace
541
542/// Recursion helper for initialMatch.
543static void DoInitialMatch(const SCEV *S, Loop *L,
544 SmallVectorImpl<SCEVUse> &Good,
545 SmallVectorImpl<SCEVUse> &Bad, ScalarEvolution &SE) {
546 // Collect expressions which properly dominate the loop header.
547 if (SE.properlyDominates(S, BB: L->getHeader())) {
548 Good.push_back(Elt: S);
549 return;
550 }
551
552 // Look at add operands.
553 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Val: S)) {
554 for (const SCEV *S : Add->operands())
555 DoInitialMatch(S, L, Good, Bad, SE);
556 return;
557 }
558
559 // Look at addrec operands.
560 const SCEV *Start, *Step;
561 const Loop *ARLoop;
562 if (match(S,
563 P: m_scev_AffineAddRec(Op0: m_SCEV(V&: Start), Op1: m_SCEV(V&: Step), L: m_Loop(L&: ARLoop))) &&
564 !Start->isZero()) {
565 DoInitialMatch(S: Start, L, Good, Bad, SE);
566 DoInitialMatch(S: SE.getAddRecExpr(Start: SE.getConstant(Ty: S->getType(), V: 0), Step,
567 // FIXME: AR->getNoWrapFlags()
568 L: ARLoop, Flags: SCEV::FlagAnyWrap),
569 L, Good, Bad, SE);
570 return;
571 }
572
573 // Handle a multiplication by -1 (negation) if it didn't fold.
574 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Val: S))
575 if (Mul->getOperand(i: 0)->isAllOnesValue()) {
576 SmallVector<SCEVUse, 4> Ops(drop_begin(RangeOrContainer: Mul->operands()));
577 const SCEV *NewMul = SE.getMulExpr(Ops);
578
579 SmallVector<SCEVUse, 4> MyGood;
580 SmallVector<SCEVUse, 4> MyBad;
581 DoInitialMatch(S: NewMul, L, Good&: MyGood, Bad&: MyBad, SE);
582 const SCEV *NegOne = SE.getSCEV(V: ConstantInt::getAllOnesValue(
583 Ty: SE.getEffectiveSCEVType(Ty: NewMul->getType())));
584 for (const SCEV *S : MyGood)
585 Good.push_back(Elt: SE.getMulExpr(LHS: NegOne, RHS: S));
586 for (const SCEV *S : MyBad)
587 Bad.push_back(Elt: SE.getMulExpr(LHS: NegOne, RHS: S));
588 return;
589 }
590
591 // Ok, we can't do anything interesting. Just stuff the whole thing into a
592 // register and hope for the best.
593 Bad.push_back(Elt: S);
594}
595
596/// Incorporate loop-variant parts of S into this Formula, attempting to keep
597/// all loop-invariant and loop-computable values in a single base register.
598void Formula::initialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE) {
599 SmallVector<SCEVUse, 4> Good;
600 SmallVector<SCEVUse, 4> Bad;
601 DoInitialMatch(S, L, Good, Bad, SE);
602 if (!Good.empty()) {
603 const SCEV *Sum = SE.getAddExpr(Ops&: Good);
604 if (!Sum->isZero())
605 BaseRegs.push_back(Elt: Sum);
606 HasBaseReg = true;
607 }
608 if (!Bad.empty()) {
609 const SCEV *Sum = SE.getAddExpr(Ops&: Bad);
610 if (!Sum->isZero())
611 BaseRegs.push_back(Elt: Sum);
612 HasBaseReg = true;
613 }
614 canonicalize(L: *L);
615}
616
617static bool containsAddRecDependentOnLoop(const SCEV *S, const Loop &L) {
618 return SCEVExprContains(Root: S, Pred: [&L](const SCEV *S) {
619 return isa<SCEVAddRecExpr>(Val: S) && (cast<SCEVAddRecExpr>(Val: S)->getLoop() == &L);
620 });
621}
622
623/// Check whether or not this formula satisfies the canonical
624/// representation.
625/// \see Formula::BaseRegs.
626bool Formula::isCanonical(const Loop &L) const {
627 assert((Scale == 0 || ScaledReg) &&
628 "ScaledReg must be non-null if Scale is non-zero");
629
630 if (!ScaledReg)
631 return BaseRegs.size() <= 1;
632
633 if (Scale != 1)
634 return true;
635
636 if (Scale == 1 && BaseRegs.empty())
637 return false;
638
639 if (containsAddRecDependentOnLoop(S: ScaledReg, L))
640 return true;
641
642 // If ScaledReg is not a recurrent expr, or it is but its loop is not current
643 // loop, meanwhile BaseRegs contains a recurrent expr reg related with current
644 // loop, we want to swap the reg in BaseRegs with ScaledReg.
645 return none_of(Range: BaseRegs, P: [&L](const SCEV *S) {
646 return containsAddRecDependentOnLoop(S, L);
647 });
648}
649
650/// Helper method to morph a formula into its canonical representation.
651/// \see Formula::BaseRegs.
652/// Every formula having more than one base register, must use the ScaledReg
653/// field. Otherwise, we would have to do special cases everywhere in LSR
654/// to treat reg1 + reg2 + ... the same way as reg1 + 1*reg2 + ...
655/// On the other hand, 1*reg should be canonicalized into reg.
656void Formula::canonicalize(const Loop &L) {
657 if (isCanonical(L))
658 return;
659
660 if (BaseRegs.empty()) {
661 // No base reg? Use scale reg with scale = 1 as such.
662 assert(ScaledReg && "Expected 1*reg => reg");
663 assert(Scale == 1 && "Expected 1*reg => reg");
664 BaseRegs.push_back(Elt: ScaledReg);
665 Scale = 0;
666 ScaledReg = nullptr;
667 return;
668 }
669
670 // Keep the invariant sum in BaseRegs and one of the variant sum in ScaledReg.
671 if (!ScaledReg) {
672 ScaledReg = BaseRegs.pop_back_val();
673 Scale = 1;
674 }
675
676 // If ScaledReg is an invariant with respect to L, find the reg from
677 // BaseRegs containing the recurrent expr related with Loop L. Swap the
678 // reg with ScaledReg.
679 if (!containsAddRecDependentOnLoop(S: ScaledReg, L)) {
680 auto I = find_if(Range&: BaseRegs, P: [&L](const SCEV *S) {
681 return containsAddRecDependentOnLoop(S, L);
682 });
683 if (I != BaseRegs.end())
684 std::swap(a&: ScaledReg, b&: *I);
685 }
686 assert(isCanonical(L) && "Failed to canonicalize?");
687}
688
689/// Get rid of the scale in the formula.
690/// In other words, this method morphes reg1 + 1*reg2 into reg1 + reg2.
691/// \return true if it was possible to get rid of the scale, false otherwise.
692/// \note After this operation the formula may not be in the canonical form.
693bool Formula::unscale() {
694 if (Scale != 1)
695 return false;
696 Scale = 0;
697 BaseRegs.push_back(Elt: ScaledReg);
698 ScaledReg = nullptr;
699 return true;
700}
701
702bool Formula::hasZeroEnd() const {
703 if (UnfoldedOffset || BaseOffset)
704 return false;
705 if (BaseRegs.size() != 1 || ScaledReg)
706 return false;
707 return true;
708}
709
710bool Formula::countsDownToZero() const {
711 if (!hasZeroEnd())
712 return false;
713 assert(BaseRegs.size() == 1 && "hasZeroEnd should mean one BaseReg");
714 const APInt *StepInt;
715 if (!match(S: BaseRegs[0], P: m_scev_AffineAddRec(Op0: m_SCEV(), Op1: m_scev_APInt(C&: StepInt))))
716 return false;
717 return StepInt->isNegative();
718}
719
720/// Return the total number of register operands used by this formula. This does
721/// not include register uses implied by non-constant addrec strides.
722size_t Formula::getNumRegs() const {
723 return !!ScaledReg + BaseRegs.size();
724}
725
726/// Return the type of this formula, if it has one, or null otherwise. This type
727/// is meaningless except for the bit size.
728Type *Formula::getType() const {
729 return !BaseRegs.empty() ? BaseRegs.front()->getType() :
730 ScaledReg ? ScaledReg->getType() :
731 BaseGV ? BaseGV->getType() :
732 nullptr;
733}
734
735/// Delete the given base reg from the BaseRegs list.
736void Formula::deleteBaseReg(const SCEV *&S) {
737 if (&S != &BaseRegs.back())
738 std::swap(a&: S, b&: BaseRegs.back());
739 BaseRegs.pop_back();
740}
741
742/// Test if this formula references the given register.
743bool Formula::referencesReg(const SCEV *S) const {
744 return S == ScaledReg || is_contained(Range: BaseRegs, Element: S);
745}
746
747/// Test whether this formula uses registers which are used by uses other than
748/// the use with the given index.
749bool Formula::hasRegsUsedByUsesOtherThan(size_t LUIdx,
750 const RegUseTracker &RegUses) const {
751 if (ScaledReg)
752 if (RegUses.isRegUsedByUsesOtherThan(Reg: ScaledReg, LUIdx))
753 return true;
754 for (const SCEV *BaseReg : BaseRegs)
755 if (RegUses.isRegUsedByUsesOtherThan(Reg: BaseReg, LUIdx))
756 return true;
757 return false;
758}
759
760#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
761void Formula::print(raw_ostream &OS) const {
762 ListSeparator Plus(" + ");
763 if (BaseGV) {
764 OS << Plus;
765 BaseGV->printAsOperand(OS, /*PrintType=*/false);
766 }
767 if (BaseOffset.isNonZero())
768 OS << Plus << BaseOffset;
769
770 for (const SCEV *BaseReg : BaseRegs)
771 OS << Plus << "reg(" << *BaseReg << ')';
772
773 if (HasBaseReg && BaseRegs.empty())
774 OS << Plus << "**error: HasBaseReg**";
775 else if (!HasBaseReg && !BaseRegs.empty())
776 OS << Plus << "**error: !HasBaseReg**";
777
778 if (Scale != 0) {
779 OS << Plus << Scale << "*reg(";
780 if (ScaledReg)
781 OS << *ScaledReg;
782 else
783 OS << "<unknown>";
784 OS << ')';
785 }
786 if (UnfoldedOffset.isNonZero())
787 OS << Plus << "imm(" << UnfoldedOffset << ')';
788}
789
790LLVM_DUMP_METHOD void Formula::dump() const {
791 print(errs()); errs() << '\n';
792}
793#endif
794
795/// Return true if the given addrec can be sign-extended without changing its
796/// value.
797static bool isAddRecSExtable(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
798 Type *WideTy =
799 IntegerType::get(C&: SE.getContext(), NumBits: SE.getTypeSizeInBits(Ty: AR->getType()) + 1);
800 return isa<SCEVAddRecExpr>(Val: SE.getSignExtendExpr(Op: AR, Ty: WideTy));
801}
802
803/// Return true if the given add can be sign-extended without changing its
804/// value.
805static bool isAddSExtable(const SCEVAddExpr *A, ScalarEvolution &SE) {
806 Type *WideTy =
807 IntegerType::get(C&: SE.getContext(), NumBits: SE.getTypeSizeInBits(Ty: A->getType()) + 1);
808 return isa<SCEVAddExpr>(Val: SE.getSignExtendExpr(Op: A, Ty: WideTy));
809}
810
811/// Return true if the given mul can be sign-extended without changing its
812/// value.
813static bool isMulSExtable(const SCEVMulExpr *M, ScalarEvolution &SE) {
814 Type *WideTy =
815 IntegerType::get(C&: SE.getContext(),
816 NumBits: SE.getTypeSizeInBits(Ty: M->getType()) * M->getNumOperands());
817 return isa<SCEVMulExpr>(Val: SE.getSignExtendExpr(Op: M, Ty: WideTy));
818}
819
820/// Return an expression for LHS /s RHS, if it can be determined and if the
821/// remainder is known to be zero, or null otherwise. If IgnoreSignificantBits
822/// is true, expressions like (X * Y) /s Y are simplified to X, ignoring that
823/// the multiplication may overflow, which is useful when the result will be
824/// used in a context where the most significant bits are ignored.
825static const SCEV *getExactSDiv(const SCEV *LHS, const SCEV *RHS,
826 ScalarEvolution &SE,
827 bool IgnoreSignificantBits = false) {
828 // Handle the trivial case, which works for any SCEV type.
829 if (LHS == RHS)
830 return SE.getConstant(Ty: LHS->getType(), V: 1);
831
832 // Handle a few RHS special cases.
833 const SCEVConstant *RC = dyn_cast<SCEVConstant>(Val: RHS);
834 if (RC) {
835 const APInt &RA = RC->getAPInt();
836 // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do
837 // some folding.
838 if (RA.isAllOnes()) {
839 if (LHS->getType()->isPointerTy())
840 return nullptr;
841 return SE.getMulExpr(LHS, RHS: RC);
842 }
843 // Handle x /s 1 as x.
844 if (RA == 1)
845 return LHS;
846 }
847
848 // Check for a division of a constant by a constant.
849 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Val: LHS)) {
850 if (!RC)
851 return nullptr;
852 const APInt &LA = C->getAPInt();
853 const APInt &RA = RC->getAPInt();
854 if (LA.srem(RHS: RA) != 0)
855 return nullptr;
856 return SE.getConstant(Val: LA.sdiv(RHS: RA));
857 }
858
859 // Distribute the sdiv over addrec operands, if the addrec doesn't overflow.
860 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Val: LHS)) {
861 if ((IgnoreSignificantBits || isAddRecSExtable(AR, SE)) && AR->isAffine()) {
862 const SCEV *Step = getExactSDiv(LHS: AR->getStepRecurrence(SE), RHS, SE,
863 IgnoreSignificantBits);
864 if (!Step) return nullptr;
865 const SCEV *Start = getExactSDiv(LHS: AR->getStart(), RHS, SE,
866 IgnoreSignificantBits);
867 if (!Start) return nullptr;
868 // FlagNW is independent of the start value, step direction, and is
869 // preserved with smaller magnitude steps.
870 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
871 return SE.getAddRecExpr(Start, Step, L: AR->getLoop(), Flags: SCEV::FlagAnyWrap);
872 }
873 return nullptr;
874 }
875
876 // Distribute the sdiv over add operands, if the add doesn't overflow.
877 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Val: LHS)) {
878 if (IgnoreSignificantBits || isAddSExtable(A: Add, SE)) {
879 SmallVector<SCEVUse, 8> Ops;
880 for (const SCEV *S : Add->operands()) {
881 const SCEV *Op = getExactSDiv(LHS: S, RHS, SE, IgnoreSignificantBits);
882 if (!Op) return nullptr;
883 Ops.push_back(Elt: Op);
884 }
885 return SE.getAddExpr(Ops);
886 }
887 return nullptr;
888 }
889
890 // Check for a multiply operand that we can pull RHS out of.
891 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Val: LHS)) {
892 if (IgnoreSignificantBits || isMulSExtable(M: Mul, SE)) {
893 // Handle special case C1*X*Y /s C2*X*Y.
894 if (const SCEVMulExpr *MulRHS = dyn_cast<SCEVMulExpr>(Val: RHS)) {
895 if (IgnoreSignificantBits || isMulSExtable(M: MulRHS, SE)) {
896 const SCEVConstant *LC = dyn_cast<SCEVConstant>(Val: Mul->getOperand(i: 0));
897 const SCEVConstant *RC =
898 dyn_cast<SCEVConstant>(Val: MulRHS->getOperand(i: 0));
899 if (LC && RC) {
900 SmallVector<const SCEV *, 4> LOps(drop_begin(RangeOrContainer: Mul->operands()));
901 SmallVector<const SCEV *, 4> ROps(drop_begin(RangeOrContainer: MulRHS->operands()));
902 if (LOps == ROps)
903 return getExactSDiv(LHS: LC, RHS: RC, SE, IgnoreSignificantBits);
904 }
905 }
906 }
907
908 SmallVector<SCEVUse, 4> Ops;
909 bool Found = false;
910 for (const SCEV *S : Mul->operands()) {
911 if (!Found)
912 if (const SCEV *Q = getExactSDiv(LHS: S, RHS, SE,
913 IgnoreSignificantBits)) {
914 S = Q;
915 Found = true;
916 }
917 Ops.push_back(Elt: S);
918 }
919 return Found ? SE.getMulExpr(Ops) : nullptr;
920 }
921 return nullptr;
922 }
923
924 // Otherwise we don't know.
925 return nullptr;
926}
927
928/// If S involves the addition of a constant integer value, return that integer
929/// value, and mutate S to point to a new SCEV with that value excluded.
930static Immediate ExtractImmediate(SCEVUse &S, ScalarEvolution &SE) {
931 const APInt *C;
932 if (match(U: S, P: m_scev_APInt(C))) {
933 if (C->getSignificantBits() <= 64) {
934 S = SE.getConstant(Ty: S->getType(), V: 0);
935 return Immediate::getFixed(MinVal: C->getSExtValue());
936 }
937 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Val&: S)) {
938 SmallVector<SCEVUse, 8> NewOps(Add->operands());
939 Immediate Result = ExtractImmediate(S&: NewOps.front(), SE);
940 if (Result.isNonZero())
941 S = SE.getAddExpr(Ops&: NewOps);
942 return Result;
943 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Val&: S)) {
944 SmallVector<SCEVUse, 8> NewOps(AR->operands());
945 Immediate Result = ExtractImmediate(S&: NewOps.front(), SE);
946 if (Result.isNonZero())
947 S = SE.getAddRecExpr(Operands&: NewOps, L: AR->getLoop(),
948 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
949 Flags: SCEV::FlagAnyWrap);
950 return Result;
951 } else if (EnableVScaleImmediates &&
952 match(U: S, P: m_scev_Mul(Op0: m_scev_APInt(C), Op1: m_SCEVVScale()))) {
953 S = SE.getConstant(Ty: S->getType(), V: 0);
954 return Immediate::getScalable(MinVal: C->getSExtValue());
955 }
956 return Immediate::getZero();
957}
958
959/// If S involves the addition of a GlobalValue address, return that symbol, and
960/// mutate S to point to a new SCEV with that value excluded.
961static GlobalValue *ExtractSymbol(SCEVUse &S, ScalarEvolution &SE) {
962 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Val&: S)) {
963 if (GlobalValue *GV = dyn_cast<GlobalValue>(Val: U->getValue())) {
964 S = SE.getConstant(Ty: GV->getType(), V: 0);
965 return GV;
966 }
967 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Val&: S)) {
968 SmallVector<SCEVUse, 8> NewOps(Add->operands());
969 GlobalValue *Result = ExtractSymbol(S&: NewOps.back(), SE);
970 if (Result)
971 S = SE.getAddExpr(Ops&: NewOps);
972 return Result;
973 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Val&: S)) {
974 SmallVector<SCEVUse, 8> NewOps(AR->operands());
975 GlobalValue *Result = ExtractSymbol(S&: NewOps.front(), SE);
976 if (Result)
977 S = SE.getAddRecExpr(Operands&: NewOps, L: AR->getLoop(),
978 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
979 Flags: SCEV::FlagAnyWrap);
980 return Result;
981 }
982 return nullptr;
983}
984
985/// Returns true if the specified instruction is using the specified value as an
986/// address.
987static bool isAddressUse(const TargetTransformInfo &TTI,
988 Instruction *Inst, Value *OperandVal) {
989 bool isAddress = isa<LoadInst>(Val: Inst);
990 if (StoreInst *SI = dyn_cast<StoreInst>(Val: Inst)) {
991 if (SI->getPointerOperand() == OperandVal)
992 isAddress = true;
993 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Val: Inst)) {
994 // Addressing modes can also be folded into prefetches and a variety
995 // of intrinsics.
996 switch (II->getIntrinsicID()) {
997 case Intrinsic::memset:
998 case Intrinsic::prefetch:
999 case Intrinsic::masked_load:
1000 if (II->getArgOperand(i: 0) == OperandVal)
1001 isAddress = true;
1002 break;
1003 case Intrinsic::masked_store:
1004 if (II->getArgOperand(i: 1) == OperandVal)
1005 isAddress = true;
1006 break;
1007 case Intrinsic::memmove:
1008 case Intrinsic::memcpy:
1009 if (II->getArgOperand(i: 0) == OperandVal ||
1010 II->getArgOperand(i: 1) == OperandVal)
1011 isAddress = true;
1012 break;
1013 default: {
1014 MemIntrinsicInfo IntrInfo;
1015 if (TTI.getTgtMemIntrinsic(Inst: II, Info&: IntrInfo)) {
1016 if (IntrInfo.PtrVal == OperandVal)
1017 isAddress = true;
1018 }
1019 }
1020 }
1021 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(Val: Inst)) {
1022 if (RMW->getPointerOperand() == OperandVal)
1023 isAddress = true;
1024 } else if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(Val: Inst)) {
1025 if (CmpX->getPointerOperand() == OperandVal)
1026 isAddress = true;
1027 }
1028 return isAddress;
1029}
1030
1031/// Return the type of the memory being accessed.
1032static MemAccessTy getAccessType(const TargetTransformInfo &TTI,
1033 Instruction *Inst, Value *OperandVal) {
1034 MemAccessTy AccessTy = MemAccessTy::getUnknown(Ctx&: Inst->getContext());
1035
1036 // First get the type of memory being accessed.
1037 if (Type *Ty = Inst->getAccessType())
1038 AccessTy.MemTy = Ty;
1039
1040 // Then get the pointer address space.
1041 if (const StoreInst *SI = dyn_cast<StoreInst>(Val: Inst)) {
1042 AccessTy.AddrSpace = SI->getPointerAddressSpace();
1043 } else if (const LoadInst *LI = dyn_cast<LoadInst>(Val: Inst)) {
1044 AccessTy.AddrSpace = LI->getPointerAddressSpace();
1045 } else if (const AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(Val: Inst)) {
1046 AccessTy.AddrSpace = RMW->getPointerAddressSpace();
1047 } else if (const AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(Val: Inst)) {
1048 AccessTy.AddrSpace = CmpX->getPointerAddressSpace();
1049 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Val: Inst)) {
1050 switch (II->getIntrinsicID()) {
1051 case Intrinsic::prefetch:
1052 case Intrinsic::memset:
1053 AccessTy.AddrSpace = II->getArgOperand(i: 0)->getType()->getPointerAddressSpace();
1054 AccessTy.MemTy = OperandVal->getType();
1055 break;
1056 case Intrinsic::memmove:
1057 case Intrinsic::memcpy:
1058 AccessTy.AddrSpace = OperandVal->getType()->getPointerAddressSpace();
1059 AccessTy.MemTy = OperandVal->getType();
1060 break;
1061 case Intrinsic::masked_load:
1062 AccessTy.AddrSpace =
1063 II->getArgOperand(i: 0)->getType()->getPointerAddressSpace();
1064 break;
1065 case Intrinsic::masked_store:
1066 AccessTy.AddrSpace =
1067 II->getArgOperand(i: 1)->getType()->getPointerAddressSpace();
1068 break;
1069 default: {
1070 MemIntrinsicInfo IntrInfo;
1071 if (TTI.getTgtMemIntrinsic(Inst: II, Info&: IntrInfo) && IntrInfo.PtrVal) {
1072 AccessTy.AddrSpace
1073 = IntrInfo.PtrVal->getType()->getPointerAddressSpace();
1074 }
1075
1076 break;
1077 }
1078 }
1079 }
1080
1081 return AccessTy;
1082}
1083
1084/// Return true if this AddRec is already a phi in its loop.
1085static bool isExistingPhi(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
1086 for (PHINode &PN : AR->getLoop()->getHeader()->phis()) {
1087 if (SE.isSCEVable(Ty: PN.getType()) &&
1088 (SE.getEffectiveSCEVType(Ty: PN.getType()) ==
1089 SE.getEffectiveSCEVType(Ty: AR->getType())) &&
1090 SE.getSCEV(V: &PN) == AR)
1091 return true;
1092 }
1093 return false;
1094}
1095
1096/// Check if expanding this expression is likely to incur significant cost. This
1097/// is tricky because SCEV doesn't track which expressions are actually computed
1098/// by the current IR.
1099///
1100/// We currently allow expansion of IV increments that involve adds,
1101/// multiplication by constants, and AddRecs from existing phis.
1102///
1103/// TODO: Allow UDivExpr if we can find an existing IV increment that is an
1104/// obvious multiple of the UDivExpr.
1105static bool isHighCostExpansion(const SCEV *S,
1106 SmallPtrSetImpl<const SCEV*> &Processed,
1107 ScalarEvolution &SE) {
1108 // Zero/One operand expressions
1109 switch (S->getSCEVType()) {
1110 case scUnknown:
1111 case scConstant:
1112 case scVScale:
1113 return false;
1114 case scTruncate:
1115 return isHighCostExpansion(S: cast<SCEVTruncateExpr>(Val: S)->getOperand(),
1116 Processed, SE);
1117 case scZeroExtend:
1118 return isHighCostExpansion(S: cast<SCEVZeroExtendExpr>(Val: S)->getOperand(),
1119 Processed, SE);
1120 case scSignExtend:
1121 return isHighCostExpansion(S: cast<SCEVSignExtendExpr>(Val: S)->getOperand(),
1122 Processed, SE);
1123 default:
1124 break;
1125 }
1126
1127 if (!Processed.insert(Ptr: S).second)
1128 return false;
1129
1130 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Val: S)) {
1131 for (const SCEV *S : Add->operands()) {
1132 if (isHighCostExpansion(S, Processed, SE))
1133 return true;
1134 }
1135 return false;
1136 }
1137
1138 const SCEV *Op0, *Op1;
1139 if (match(S, P: m_scev_Mul(Op0: m_SCEV(V&: Op0), Op1: m_SCEV(V&: Op1)))) {
1140 // Multiplication by a constant is ok
1141 if (isa<SCEVConstant>(Val: Op0))
1142 return isHighCostExpansion(S: Op1, Processed, SE);
1143
1144 // If we have the value of one operand, check if an existing
1145 // multiplication already generates this expression.
1146 if (const auto *U = dyn_cast<SCEVUnknown>(Val: Op1)) {
1147 Value *UVal = U->getValue();
1148 for (User *UR : UVal->users()) {
1149 // If U is a constant, it may be used by a ConstantExpr.
1150 Instruction *UI = dyn_cast<Instruction>(Val: UR);
1151 if (UI && UI->getOpcode() == Instruction::Mul &&
1152 SE.isSCEVable(Ty: UI->getType())) {
1153 return SE.getSCEV(V: UI) == S;
1154 }
1155 }
1156 }
1157 }
1158
1159 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Val: S)) {
1160 if (isExistingPhi(AR, SE))
1161 return false;
1162 }
1163
1164 // Fow now, consider any other type of expression (div/mul/min/max) high cost.
1165 return true;
1166}
1167
1168namespace {
1169
1170class LSRUse;
1171
1172} // end anonymous namespace
1173
1174/// Check if the addressing mode defined by \p F is completely
1175/// folded in \p LU at isel time.
1176/// This includes address-mode folding and special icmp tricks.
1177/// This function returns true if \p LU can accommodate what \p F
1178/// defines and up to 1 base + 1 scaled + offset.
1179/// In other words, if \p F has several base registers, this function may
1180/// still return true. Therefore, users still need to account for
1181/// additional base registers and/or unfolded offsets to derive an
1182/// accurate cost model.
1183static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1184 const LSRUse &LU, const Formula &F);
1185
1186// Get the cost of the scaling factor used in F for LU.
1187static InstructionCost getScalingFactorCost(const TargetTransformInfo &TTI,
1188 const LSRUse &LU, const Formula &F,
1189 const Loop &L);
1190
1191namespace {
1192
1193/// This class is used to measure and compare candidate formulae.
1194class Cost {
1195 const Loop *L = nullptr;
1196 ScalarEvolution *SE = nullptr;
1197 const TargetTransformInfo *TTI = nullptr;
1198 TargetTransformInfo::LSRCost C;
1199 TTI::AddressingModeKind AMK = TTI::AMK_None;
1200
1201public:
1202 Cost() = delete;
1203 Cost(const Loop *L, ScalarEvolution &SE, const TargetTransformInfo &TTI,
1204 TTI::AddressingModeKind AMK) :
1205 L(L), SE(&SE), TTI(&TTI), AMK(AMK) {
1206 C.Insns = 0;
1207 C.NumRegs = 0;
1208 C.AddRecCost = 0;
1209 C.NumIVMuls = 0;
1210 C.NumBaseAdds = 0;
1211 C.ImmCost = 0;
1212 C.SetupCost = 0;
1213 C.ScaleCost = 0;
1214 }
1215
1216 bool isLess(const Cost &Other) const;
1217
1218 void Lose();
1219
1220#ifndef NDEBUG
1221 // Once any of the metrics loses, they must all remain losers.
1222 bool isValid() {
1223 return ((C.Insns | C.NumRegs | C.AddRecCost | C.NumIVMuls | C.NumBaseAdds
1224 | C.ImmCost | C.SetupCost | C.ScaleCost) != ~0u)
1225 || ((C.Insns & C.NumRegs & C.AddRecCost & C.NumIVMuls & C.NumBaseAdds
1226 & C.ImmCost & C.SetupCost & C.ScaleCost) == ~0u);
1227 }
1228#endif
1229
1230 bool isLoser() {
1231 assert(isValid() && "invalid cost");
1232 return C.NumRegs == ~0u;
1233 }
1234
1235 void RateFormula(const Formula &F, SmallPtrSetImpl<const SCEV *> &Regs,
1236 const DenseSet<const SCEV *> &VisitedRegs, const LSRUse &LU,
1237 bool HardwareLoopProfitable,
1238 SmallPtrSetImpl<const SCEV *> *LoserRegs = nullptr);
1239
1240 void print(raw_ostream &OS) const;
1241 void dump() const;
1242
1243private:
1244 void RateRegister(const Formula &F, const SCEV *Reg,
1245 SmallPtrSetImpl<const SCEV *> &Regs, const LSRUse &LU,
1246 bool HardwareLoopProfitable);
1247 void RatePrimaryRegister(const Formula &F, const SCEV *Reg,
1248 SmallPtrSetImpl<const SCEV *> &Regs,
1249 const LSRUse &LU, bool HardwareLoopProfitable,
1250 SmallPtrSetImpl<const SCEV *> *LoserRegs);
1251};
1252
1253/// An operand value in an instruction which is to be replaced with some
1254/// equivalent, possibly strength-reduced, replacement.
1255struct LSRFixup {
1256 /// The instruction which will be updated.
1257 Instruction *UserInst = nullptr;
1258
1259 /// The operand of the instruction which will be replaced. The operand may be
1260 /// used more than once; every instance will be replaced.
1261 Value *OperandValToReplace = nullptr;
1262
1263 /// If this user is to use the post-incremented value of an induction
1264 /// variable, this set is non-empty and holds the loops associated with the
1265 /// induction variable.
1266 PostIncLoopSet PostIncLoops;
1267
1268 /// A constant offset to be added to the LSRUse expression. This allows
1269 /// multiple fixups to share the same LSRUse with different offsets, for
1270 /// example in an unrolled loop.
1271 Immediate Offset = Immediate::getZero();
1272
1273 LSRFixup() = default;
1274
1275 bool isUseFullyOutsideLoop(const Loop *L) const;
1276
1277 void print(raw_ostream &OS) const;
1278 void dump() const;
1279};
1280
1281/// This class holds the state that LSR keeps for each use in IVUsers, as well
1282/// as uses invented by LSR itself. It includes information about what kinds of
1283/// things can be folded into the user, information about the user itself, and
1284/// information about how the use may be satisfied. TODO: Represent multiple
1285/// users of the same expression in common?
1286class LSRUse {
1287 DenseSet<SmallVector<const SCEV *, 4>> Uniquifier;
1288
1289public:
1290 /// An enum for a kind of use, indicating what types of scaled and immediate
1291 /// operands it might support.
1292 enum KindType {
1293 Basic, ///< A normal use, with no folding.
1294 Special, ///< A special case of basic, allowing -1 scales.
1295 Address, ///< An address use; folding according to TargetLowering
1296 ICmpZero ///< An equality icmp with both operands folded into one.
1297 // TODO: Add a generic icmp too?
1298 };
1299
1300 using SCEVUseKindPair = PointerIntPair<const SCEV *, 2, KindType>;
1301
1302 KindType Kind;
1303 MemAccessTy AccessTy;
1304
1305 /// The list of operands which are to be replaced.
1306 SmallVector<LSRFixup, 8> Fixups;
1307
1308 /// Keep track of the min and max offsets of the fixups.
1309 Immediate MinOffset = Immediate::getFixedMax();
1310 Immediate MaxOffset = Immediate::getFixedMin();
1311
1312 /// This records whether all of the fixups using this LSRUse are outside of
1313 /// the loop, in which case some special-case heuristics may be used.
1314 bool AllFixupsOutsideLoop = true;
1315
1316 /// This records whether all of the fixups using this LSRUse are unconditional
1317 /// within the loop, meaning they will be executed on every path to the loop
1318 /// latch. This includes fixups before early exits.
1319 bool AllFixupsUnconditional = true;
1320
1321 /// RigidFormula is set to true to guarantee that this use will be associated
1322 /// with a single formula--the one that initially matched. Some SCEV
1323 /// expressions cannot be expanded. This allows LSR to consider the registers
1324 /// used by those expressions without the need to expand them later after
1325 /// changing the formula.
1326 bool RigidFormula = false;
1327
1328 /// A list of ways to build a value that can satisfy this user. After the
1329 /// list is populated, one of these is selected heuristically and used to
1330 /// formulate a replacement for OperandValToReplace in UserInst.
1331 SmallVector<Formula, 12> Formulae;
1332
1333 /// The set of register candidates used by all formulae in this LSRUse.
1334 SmallPtrSet<const SCEV *, 4> Regs;
1335
1336 LSRUse(KindType K, MemAccessTy AT) : Kind(K), AccessTy(AT) {}
1337
1338 LSRFixup &getNewFixup() {
1339 Fixups.push_back(Elt: LSRFixup());
1340 return Fixups.back();
1341 }
1342
1343 void pushFixup(LSRFixup &f) {
1344 Fixups.push_back(Elt: f);
1345 if (Immediate::isKnownGT(LHS: f.Offset, RHS: MaxOffset))
1346 MaxOffset = f.Offset;
1347 if (Immediate::isKnownLT(LHS: f.Offset, RHS: MinOffset))
1348 MinOffset = f.Offset;
1349 }
1350
1351 bool HasFormulaWithSameRegs(const Formula &F) const;
1352 float getNotSelectedProbability(const SCEV *Reg) const;
1353 bool InsertFormula(const Formula &F, const Loop &L);
1354 void DeleteFormula(Formula &F);
1355 void RecomputeRegs(size_t LUIdx, RegUseTracker &Reguses);
1356
1357 void print(raw_ostream &OS) const;
1358 void dump() const;
1359};
1360
1361} // end anonymous namespace
1362
1363static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1364 LSRUse::KindType Kind, MemAccessTy AccessTy,
1365 GlobalValue *BaseGV, Immediate BaseOffset,
1366 bool HasBaseReg, int64_t Scale,
1367 Instruction *Fixup = nullptr);
1368
1369static unsigned getSetupCost(const SCEV *Reg, unsigned Depth) {
1370 if (isa<SCEVUnknown>(Val: Reg) || isa<SCEVConstant>(Val: Reg))
1371 return 1;
1372 if (Depth == 0)
1373 return 0;
1374 if (const auto *S = dyn_cast<SCEVAddRecExpr>(Val: Reg))
1375 return getSetupCost(Reg: S->getStart(), Depth: Depth - 1);
1376 if (auto S = dyn_cast<SCEVIntegralCastExpr>(Val: Reg))
1377 return getSetupCost(Reg: S->getOperand(), Depth: Depth - 1);
1378 if (auto S = dyn_cast<SCEVNAryExpr>(Val: Reg))
1379 return std::accumulate(first: S->operands().begin(), last: S->operands().end(), init: 0,
1380 binary_op: [&](unsigned i, const SCEV *Reg) {
1381 return i + getSetupCost(Reg, Depth: Depth - 1);
1382 });
1383 if (auto S = dyn_cast<SCEVUDivExpr>(Val: Reg))
1384 return getSetupCost(Reg: S->getLHS(), Depth: Depth - 1) +
1385 getSetupCost(Reg: S->getRHS(), Depth: Depth - 1);
1386 return 0;
1387}
1388
1389/// Tally up interesting quantities from the given register.
1390void Cost::RateRegister(const Formula &F, const SCEV *Reg,
1391 SmallPtrSetImpl<const SCEV *> &Regs, const LSRUse &LU,
1392 bool HardwareLoopProfitable) {
1393 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Val: Reg)) {
1394 // If this is an addrec for another loop, it should be an invariant
1395 // with respect to L since L is the innermost loop (at least
1396 // for now LSR only handles innermost loops).
1397 if (AR->getLoop() != L) {
1398 // If the AddRec exists, consider it's register free and leave it alone.
1399 if (isExistingPhi(AR, SE&: *SE) && !(AMK & TTI::AMK_PostIndexed))
1400 return;
1401
1402 // It is bad to allow LSR for current loop to add induction variables
1403 // for its sibling loops.
1404 if (!AR->getLoop()->contains(L)) {
1405 Lose();
1406 return;
1407 }
1408
1409 // Otherwise, it will be an invariant with respect to Loop L.
1410 ++C.NumRegs;
1411 return;
1412 }
1413
1414 unsigned LoopCost = 1;
1415 if (TTI->isIndexedLoadLegal(Mode: TTI->MIM_PostInc, Ty: AR->getType()) ||
1416 TTI->isIndexedStoreLegal(Mode: TTI->MIM_PostInc, Ty: AR->getType())) {
1417 const SCEV *Start;
1418 const APInt *Step;
1419 if (match(S: AR, P: m_scev_AffineAddRec(Op0: m_SCEV(V&: Start), Op1: m_scev_APInt(C&: Step)))) {
1420 // If the step size matches the base offset, we could use pre-indexed
1421 // addressing.
1422 bool CanPreIndex = (AMK & TTI::AMK_PreIndexed) &&
1423 F.BaseOffset.isFixed() &&
1424 *Step == F.BaseOffset.getFixedValue();
1425 bool CanPostIndex = (AMK & TTI::AMK_PostIndexed) &&
1426 !isa<SCEVConstant>(Val: Start) &&
1427 SE->isLoopInvariant(S: Start, L);
1428 // We can only pre or post index when the load/store is unconditional.
1429 if ((CanPreIndex || CanPostIndex) && LU.AllFixupsUnconditional)
1430 LoopCost = 0;
1431 }
1432 }
1433
1434 // If the loop counts down to zero and we'll be using a hardware loop then
1435 // the addrec will be combined into the hardware loop instruction.
1436 if (LU.Kind == LSRUse::ICmpZero && F.countsDownToZero() &&
1437 HardwareLoopProfitable)
1438 LoopCost = 0;
1439 C.AddRecCost += LoopCost;
1440
1441 // Add the step value register, if it needs one.
1442 // TODO: The non-affine case isn't precisely modeled here.
1443 if (!AR->isAffine() || !isa<SCEVConstant>(Val: AR->getOperand(i: 1))) {
1444 if (!Regs.count(Ptr: AR->getOperand(i: 1))) {
1445 RateRegister(F, Reg: AR->getOperand(i: 1), Regs, LU, HardwareLoopProfitable);
1446 if (isLoser())
1447 return;
1448 }
1449 }
1450 }
1451 ++C.NumRegs;
1452
1453 // Rough heuristic; favor registers which don't require extra setup
1454 // instructions in the preheader.
1455 C.SetupCost += getSetupCost(Reg, Depth: SetupCostDepthLimit);
1456 // Ensure we don't, even with the recusion limit, produce invalid costs.
1457 C.SetupCost = std::min<unsigned>(a: C.SetupCost, b: 1 << 16);
1458
1459 C.NumIVMuls += isa<SCEVMulExpr>(Val: Reg) &&
1460 SE->hasComputableLoopEvolution(S: Reg, L);
1461}
1462
1463/// Record this register in the set. If we haven't seen it before, rate
1464/// it. Optional LoserRegs provides a way to declare any formula that refers to
1465/// one of those regs an instant loser.
1466void Cost::RatePrimaryRegister(const Formula &F, const SCEV *Reg,
1467 SmallPtrSetImpl<const SCEV *> &Regs,
1468 const LSRUse &LU, bool HardwareLoopProfitable,
1469 SmallPtrSetImpl<const SCEV *> *LoserRegs) {
1470 if (LoserRegs && LoserRegs->count(Ptr: Reg)) {
1471 Lose();
1472 return;
1473 }
1474 if (Regs.insert(Ptr: Reg).second) {
1475 RateRegister(F, Reg, Regs, LU, HardwareLoopProfitable);
1476 if (LoserRegs && isLoser())
1477 LoserRegs->insert(Ptr: Reg);
1478 }
1479}
1480
1481void Cost::RateFormula(const Formula &F, SmallPtrSetImpl<const SCEV *> &Regs,
1482 const DenseSet<const SCEV *> &VisitedRegs,
1483 const LSRUse &LU, bool HardwareLoopProfitable,
1484 SmallPtrSetImpl<const SCEV *> *LoserRegs) {
1485 if (isLoser())
1486 return;
1487 assert(F.isCanonical(*L) && "Cost is accurate only for canonical formula");
1488 // Tally up the registers.
1489 unsigned PrevAddRecCost = C.AddRecCost;
1490 unsigned PrevNumRegs = C.NumRegs;
1491 unsigned PrevNumBaseAdds = C.NumBaseAdds;
1492 if (const SCEV *ScaledReg = F.ScaledReg) {
1493 if (VisitedRegs.count(V: ScaledReg)) {
1494 Lose();
1495 return;
1496 }
1497 RatePrimaryRegister(F, Reg: ScaledReg, Regs, LU, HardwareLoopProfitable,
1498 LoserRegs);
1499 if (isLoser())
1500 return;
1501 }
1502 for (const SCEV *BaseReg : F.BaseRegs) {
1503 if (VisitedRegs.count(V: BaseReg)) {
1504 Lose();
1505 return;
1506 }
1507 RatePrimaryRegister(F, Reg: BaseReg, Regs, LU, HardwareLoopProfitable,
1508 LoserRegs);
1509 if (isLoser())
1510 return;
1511 }
1512
1513 // Determine how many (unfolded) adds we'll need inside the loop.
1514 size_t NumBaseParts = F.getNumRegs();
1515 if (NumBaseParts > 1)
1516 // Do not count the base and a possible second register if the target
1517 // allows to fold 2 registers.
1518 C.NumBaseAdds +=
1519 NumBaseParts - (1 + (F.Scale && isAMCompletelyFolded(TTI: *TTI, LU, F)));
1520 C.NumBaseAdds += (F.UnfoldedOffset.isNonZero());
1521
1522 // Accumulate non-free scaling amounts.
1523 C.ScaleCost += getScalingFactorCost(TTI: *TTI, LU, F, L: *L).getValue();
1524
1525 // Tally up the non-zero immediates.
1526 for (const LSRFixup &Fixup : LU.Fixups) {
1527 if (Fixup.Offset.isCompatibleImmediate(Imm: F.BaseOffset)) {
1528 Immediate Offset = Fixup.Offset.addUnsigned(RHS: F.BaseOffset);
1529 if (F.BaseGV)
1530 C.ImmCost += 64; // Handle symbolic values conservatively.
1531 // TODO: This should probably be the pointer size.
1532 else if (Offset.isNonZero())
1533 C.ImmCost +=
1534 APInt(64, Offset.getKnownMinValue(), true).getSignificantBits();
1535
1536 // Check with target if this offset with this instruction is
1537 // specifically not supported.
1538 if (LU.Kind == LSRUse::Address && Offset.isNonZero() &&
1539 !isAMCompletelyFolded(TTI: *TTI, Kind: LSRUse::Address, AccessTy: LU.AccessTy, BaseGV: F.BaseGV,
1540 BaseOffset: Offset, HasBaseReg: F.HasBaseReg, Scale: F.Scale, Fixup: Fixup.UserInst))
1541 C.NumBaseAdds++;
1542 } else {
1543 // Incompatible immediate type, increase cost to avoid using
1544 C.ImmCost += 2048;
1545 }
1546 }
1547
1548 // If we don't count instruction cost exit here.
1549 if (!InsnsCost) {
1550 assert(isValid() && "invalid cost");
1551 return;
1552 }
1553
1554 // Treat every new register that exceeds TTI.getNumberOfRegisters() - 1 as
1555 // additional instruction (at least fill).
1556 // TODO: Need distinguish register class?
1557 unsigned TTIRegNum = TTI->getNumberOfRegisters(
1558 ClassID: TTI->getRegisterClassForType(Vector: false, Ty: F.getType())) - 1;
1559 if (C.NumRegs > TTIRegNum) {
1560 // Cost already exceeded TTIRegNum, then only newly added register can add
1561 // new instructions.
1562 if (PrevNumRegs > TTIRegNum)
1563 C.Insns += (C.NumRegs - PrevNumRegs);
1564 else
1565 C.Insns += (C.NumRegs - TTIRegNum);
1566 }
1567
1568 // If ICmpZero formula ends with not 0, it could not be replaced by
1569 // just add or sub. We'll need to compare final result of AddRec.
1570 // That means we'll need an additional instruction. But if the target can
1571 // macro-fuse a compare with a branch, don't count this extra instruction.
1572 // For -10 + {0, +, 1}:
1573 // i = i + 1;
1574 // cmp i, 10
1575 //
1576 // For {-10, +, 1}:
1577 // i = i + 1;
1578 if (LU.Kind == LSRUse::ICmpZero && !F.hasZeroEnd() &&
1579 !TTI->canMacroFuseCmp())
1580 C.Insns++;
1581 // Each new AddRec adds 1 instruction to calculation.
1582 C.Insns += (C.AddRecCost - PrevAddRecCost);
1583
1584 // BaseAdds adds instructions for unfolded registers.
1585 if (LU.Kind != LSRUse::ICmpZero)
1586 C.Insns += C.NumBaseAdds - PrevNumBaseAdds;
1587 assert(isValid() && "invalid cost");
1588}
1589
1590/// Set this cost to a losing value.
1591void Cost::Lose() {
1592 C.Insns = std::numeric_limits<unsigned>::max();
1593 C.NumRegs = std::numeric_limits<unsigned>::max();
1594 C.AddRecCost = std::numeric_limits<unsigned>::max();
1595 C.NumIVMuls = std::numeric_limits<unsigned>::max();
1596 C.NumBaseAdds = std::numeric_limits<unsigned>::max();
1597 C.ImmCost = std::numeric_limits<unsigned>::max();
1598 C.SetupCost = std::numeric_limits<unsigned>::max();
1599 C.ScaleCost = std::numeric_limits<unsigned>::max();
1600}
1601
1602/// Choose the lower cost.
1603bool Cost::isLess(const Cost &Other) const {
1604 if (InsnsCost.getNumOccurrences() > 0 && InsnsCost &&
1605 C.Insns != Other.C.Insns)
1606 return C.Insns < Other.C.Insns;
1607 return TTI->isLSRCostLess(C1: C, C2: Other.C);
1608}
1609
1610#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1611void Cost::print(raw_ostream &OS) const {
1612 if (InsnsCost)
1613 OS << C.Insns << " instruction" << (C.Insns == 1 ? " " : "s ");
1614 OS << C.NumRegs << " reg" << (C.NumRegs == 1 ? "" : "s");
1615 if (C.AddRecCost != 0)
1616 OS << ", with addrec cost " << C.AddRecCost;
1617 if (C.NumIVMuls != 0)
1618 OS << ", plus " << C.NumIVMuls << " IV mul"
1619 << (C.NumIVMuls == 1 ? "" : "s");
1620 if (C.NumBaseAdds != 0)
1621 OS << ", plus " << C.NumBaseAdds << " base add"
1622 << (C.NumBaseAdds == 1 ? "" : "s");
1623 if (C.ScaleCost != 0)
1624 OS << ", plus " << C.ScaleCost << " scale cost";
1625 if (C.ImmCost != 0)
1626 OS << ", plus " << C.ImmCost << " imm cost";
1627 if (C.SetupCost != 0)
1628 OS << ", plus " << C.SetupCost << " setup cost";
1629}
1630
1631LLVM_DUMP_METHOD void Cost::dump() const {
1632 print(errs()); errs() << '\n';
1633}
1634#endif
1635
1636/// Test whether this fixup always uses its value outside of the given loop.
1637bool LSRFixup::isUseFullyOutsideLoop(const Loop *L) const {
1638 // PHI nodes use their value in their incoming blocks.
1639 if (const PHINode *PN = dyn_cast<PHINode>(Val: UserInst)) {
1640 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1641 if (PN->getIncomingValue(i) == OperandValToReplace &&
1642 L->contains(BB: PN->getIncomingBlock(i)))
1643 return false;
1644 return true;
1645 }
1646
1647 return !L->contains(Inst: UserInst);
1648}
1649
1650#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1651void LSRFixup::print(raw_ostream &OS) const {
1652 OS << "UserInst=";
1653 // Store is common and interesting enough to be worth special-casing.
1654 if (StoreInst *Store = dyn_cast<StoreInst>(UserInst)) {
1655 OS << "store ";
1656 Store->getOperand(0)->printAsOperand(OS, /*PrintType=*/false);
1657 } else if (UserInst->getType()->isVoidTy())
1658 OS << UserInst->getOpcodeName();
1659 else
1660 UserInst->printAsOperand(OS, /*PrintType=*/false);
1661
1662 OS << ", OperandValToReplace=";
1663 OperandValToReplace->printAsOperand(OS, /*PrintType=*/false);
1664
1665 for (const Loop *PIL : PostIncLoops) {
1666 OS << ", PostIncLoop=";
1667 PIL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
1668 }
1669
1670 if (Offset.isNonZero())
1671 OS << ", Offset=" << Offset;
1672}
1673
1674LLVM_DUMP_METHOD void LSRFixup::dump() const {
1675 print(errs()); errs() << '\n';
1676}
1677#endif
1678
1679/// Test whether this use as a formula which has the same registers as the given
1680/// formula.
1681bool LSRUse::HasFormulaWithSameRegs(const Formula &F) const {
1682 SmallVector<const SCEV *, 4> Key = F.BaseRegs;
1683 if (F.ScaledReg) Key.push_back(Elt: F.ScaledReg);
1684 // Unstable sort by host order ok, because this is only used for uniquifying.
1685 llvm::sort(C&: Key);
1686 return Uniquifier.count(V: Key);
1687}
1688
1689/// The function returns a probability of selecting formula without Reg.
1690float LSRUse::getNotSelectedProbability(const SCEV *Reg) const {
1691 unsigned FNum = 0;
1692 for (const Formula &F : Formulae)
1693 if (F.referencesReg(S: Reg))
1694 FNum++;
1695 return ((float)(Formulae.size() - FNum)) / Formulae.size();
1696}
1697
1698/// If the given formula has not yet been inserted, add it to the list, and
1699/// return true. Return false otherwise. The formula must be in canonical form.
1700bool LSRUse::InsertFormula(const Formula &F, const Loop &L) {
1701 assert(F.isCanonical(L) && "Invalid canonical representation");
1702
1703 if (!Formulae.empty() && RigidFormula)
1704 return false;
1705
1706 SmallVector<const SCEV *, 4> Key = F.BaseRegs;
1707 if (F.ScaledReg) Key.push_back(Elt: F.ScaledReg);
1708 // Unstable sort by host order ok, because this is only used for uniquifying.
1709 llvm::sort(C&: Key);
1710
1711 if (!Uniquifier.insert(V: Key).second)
1712 return false;
1713
1714 // Using a register to hold the value of 0 is not profitable.
1715 assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&
1716 "Zero allocated in a scaled register!");
1717#ifndef NDEBUG
1718 for (const SCEV *BaseReg : F.BaseRegs)
1719 assert(!BaseReg->isZero() && "Zero allocated in a base register!");
1720#endif
1721
1722 // Add the formula to the list.
1723 Formulae.push_back(Elt: F);
1724
1725 // Record registers now being used by this use.
1726 Regs.insert_range(R: F.BaseRegs);
1727 if (F.ScaledReg)
1728 Regs.insert(Ptr: F.ScaledReg);
1729
1730 return true;
1731}
1732
1733/// Remove the given formula from this use's list.
1734void LSRUse::DeleteFormula(Formula &F) {
1735 if (&F != &Formulae.back())
1736 std::swap(a&: F, b&: Formulae.back());
1737 Formulae.pop_back();
1738}
1739
1740/// Recompute the Regs field, and update RegUses.
1741void LSRUse::RecomputeRegs(size_t LUIdx, RegUseTracker &RegUses) {
1742 // Now that we've filtered out some formulae, recompute the Regs set.
1743 SmallPtrSet<const SCEV *, 4> OldRegs = std::move(Regs);
1744 Regs.clear();
1745 for (const Formula &F : Formulae) {
1746 if (F.ScaledReg) Regs.insert(Ptr: F.ScaledReg);
1747 Regs.insert_range(R: F.BaseRegs);
1748 }
1749
1750 // Update the RegTracker.
1751 for (const SCEV *S : OldRegs)
1752 if (!Regs.count(Ptr: S))
1753 RegUses.dropRegister(Reg: S, LUIdx);
1754}
1755
1756#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1757void LSRUse::print(raw_ostream &OS) const {
1758 OS << "LSR Use: Kind=";
1759 switch (Kind) {
1760 case Basic: OS << "Basic"; break;
1761 case Special: OS << "Special"; break;
1762 case ICmpZero: OS << "ICmpZero"; break;
1763 case Address:
1764 OS << "Address of ";
1765 if (AccessTy.MemTy->isPointerTy())
1766 OS << "pointer"; // the full pointer type could be really verbose
1767 else {
1768 OS << *AccessTy.MemTy;
1769 }
1770
1771 OS << " in addrspace(" << AccessTy.AddrSpace << ')';
1772 }
1773
1774 OS << ", Offsets={";
1775 bool NeedComma = false;
1776 for (const LSRFixup &Fixup : Fixups) {
1777 if (NeedComma) OS << ',';
1778 OS << Fixup.Offset;
1779 NeedComma = true;
1780 }
1781 OS << '}';
1782
1783 if (AllFixupsOutsideLoop)
1784 OS << ", all-fixups-outside-loop";
1785
1786 if (AllFixupsUnconditional)
1787 OS << ", all-fixups-unconditional";
1788}
1789
1790LLVM_DUMP_METHOD void LSRUse::dump() const {
1791 print(errs()); errs() << '\n';
1792}
1793#endif
1794
1795static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1796 LSRUse::KindType Kind, MemAccessTy AccessTy,
1797 GlobalValue *BaseGV, Immediate BaseOffset,
1798 bool HasBaseReg, int64_t Scale,
1799 Instruction *Fixup /* = nullptr */) {
1800 switch (Kind) {
1801 case LSRUse::Address: {
1802 int64_t FixedOffset =
1803 BaseOffset.isScalable() ? 0 : BaseOffset.getFixedValue();
1804 int64_t ScalableOffset =
1805 BaseOffset.isScalable() ? BaseOffset.getKnownMinValue() : 0;
1806 return TTI.isLegalAddressingMode(Ty: AccessTy.MemTy, BaseGV, BaseOffset: FixedOffset,
1807 HasBaseReg, Scale, AddrSpace: AccessTy.AddrSpace,
1808 I: Fixup, ScalableOffset);
1809 }
1810 case LSRUse::ICmpZero:
1811 // There's not even a target hook for querying whether it would be legal to
1812 // fold a GV into an ICmp.
1813 if (BaseGV)
1814 return false;
1815
1816 // ICmp only has two operands; don't allow more than two non-trivial parts.
1817 if (Scale != 0 && HasBaseReg && BaseOffset.isNonZero())
1818 return false;
1819
1820 // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by
1821 // putting the scaled register in the other operand of the icmp.
1822 if (Scale != 0 && Scale != -1)
1823 return false;
1824
1825 // If we have low-level target information, ask the target if it can fold an
1826 // integer immediate on an icmp.
1827 if (BaseOffset.isNonZero()) {
1828 // We don't have an interface to query whether the target supports
1829 // icmpzero against scalable quantities yet.
1830 if (BaseOffset.isScalable())
1831 return false;
1832
1833 // We have one of:
1834 // ICmpZero BaseReg + BaseOffset => ICmp BaseReg, -BaseOffset
1835 // ICmpZero -1*ScaleReg + BaseOffset => ICmp ScaleReg, BaseOffset
1836 // Offs is the ICmp immediate.
1837 if (Scale == 0)
1838 // The cast does the right thing with
1839 // std::numeric_limits<int64_t>::min().
1840 BaseOffset = BaseOffset.getFixed(MinVal: -(uint64_t)BaseOffset.getFixedValue());
1841 return TTI.isLegalICmpImmediate(Imm: BaseOffset.getFixedValue());
1842 }
1843
1844 // ICmpZero BaseReg + -1*ScaleReg => ICmp BaseReg, ScaleReg
1845 return true;
1846
1847 case LSRUse::Basic:
1848 // Only handle single-register values.
1849 return !BaseGV && Scale == 0 && BaseOffset.isZero();
1850
1851 case LSRUse::Special:
1852 // Special case Basic to handle -1 scales.
1853 return !BaseGV && (Scale == 0 || Scale == -1) && BaseOffset.isZero();
1854 }
1855
1856 llvm_unreachable("Invalid LSRUse Kind!");
1857}
1858
1859static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1860 Immediate MinOffset, Immediate MaxOffset,
1861 LSRUse::KindType Kind, MemAccessTy AccessTy,
1862 GlobalValue *BaseGV, Immediate BaseOffset,
1863 bool HasBaseReg, int64_t Scale) {
1864 if (BaseOffset.isNonZero() &&
1865 (BaseOffset.isScalable() != MinOffset.isScalable() ||
1866 BaseOffset.isScalable() != MaxOffset.isScalable()))
1867 return false;
1868 // Check for overflow.
1869 int64_t Base = BaseOffset.getKnownMinValue();
1870 int64_t Min = MinOffset.getKnownMinValue();
1871 int64_t Max = MaxOffset.getKnownMinValue();
1872 if (((int64_t)((uint64_t)Base + Min) > Base) != (Min > 0))
1873 return false;
1874 MinOffset = Immediate::get(MinVal: (uint64_t)Base + Min, Scalable: MinOffset.isScalable());
1875 if (((int64_t)((uint64_t)Base + Max) > Base) != (Max > 0))
1876 return false;
1877 MaxOffset = Immediate::get(MinVal: (uint64_t)Base + Max, Scalable: MaxOffset.isScalable());
1878
1879 return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, BaseOffset: MinOffset,
1880 HasBaseReg, Scale) &&
1881 isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, BaseOffset: MaxOffset,
1882 HasBaseReg, Scale);
1883}
1884
1885static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1886 Immediate MinOffset, Immediate MaxOffset,
1887 LSRUse::KindType Kind, MemAccessTy AccessTy,
1888 const Formula &F, const Loop &L) {
1889 // For the purpose of isAMCompletelyFolded either having a canonical formula
1890 // or a scale not equal to zero is correct.
1891 // Problems may arise from non canonical formulae having a scale == 0.
1892 // Strictly speaking it would best to just rely on canonical formulae.
1893 // However, when we generate the scaled formulae, we first check that the
1894 // scaling factor is profitable before computing the actual ScaledReg for
1895 // compile time sake.
1896 assert((F.isCanonical(L) || F.Scale != 0));
1897 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy,
1898 BaseGV: F.BaseGV, BaseOffset: F.BaseOffset, HasBaseReg: F.HasBaseReg, Scale: F.Scale);
1899}
1900
1901/// Test whether we know how to expand the current formula.
1902static bool isLegalUse(const TargetTransformInfo &TTI, Immediate MinOffset,
1903 Immediate MaxOffset, LSRUse::KindType Kind,
1904 MemAccessTy AccessTy, GlobalValue *BaseGV,
1905 Immediate BaseOffset, bool HasBaseReg, int64_t Scale) {
1906 // We know how to expand completely foldable formulae.
1907 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV,
1908 BaseOffset, HasBaseReg, Scale) ||
1909 // Or formulae that use a base register produced by a sum of base
1910 // registers.
1911 (Scale == 1 &&
1912 isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy,
1913 BaseGV, BaseOffset, HasBaseReg: true, Scale: 0));
1914}
1915
1916static bool isLegalUse(const TargetTransformInfo &TTI, Immediate MinOffset,
1917 Immediate MaxOffset, LSRUse::KindType Kind,
1918 MemAccessTy AccessTy, const Formula &F) {
1919 return isLegalUse(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV: F.BaseGV,
1920 BaseOffset: F.BaseOffset, HasBaseReg: F.HasBaseReg, Scale: F.Scale);
1921}
1922
1923static bool isLegalAddImmediate(const TargetTransformInfo &TTI,
1924 Immediate Offset) {
1925 if (Offset.isScalable())
1926 return TTI.isLegalAddScalableImmediate(Imm: Offset.getKnownMinValue());
1927
1928 return TTI.isLegalAddImmediate(Imm: Offset.getFixedValue());
1929}
1930
1931static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1932 const LSRUse &LU, const Formula &F) {
1933 // Target may want to look at the user instructions.
1934 if (LU.Kind == LSRUse::Address && TTI.LSRWithInstrQueries()) {
1935 for (const LSRFixup &Fixup : LU.Fixups)
1936 if (!isAMCompletelyFolded(TTI, Kind: LSRUse::Address, AccessTy: LU.AccessTy, BaseGV: F.BaseGV,
1937 BaseOffset: (F.BaseOffset + Fixup.Offset), HasBaseReg: F.HasBaseReg,
1938 Scale: F.Scale, Fixup: Fixup.UserInst))
1939 return false;
1940 return true;
1941 }
1942
1943 return isAMCompletelyFolded(TTI, MinOffset: LU.MinOffset, MaxOffset: LU.MaxOffset, Kind: LU.Kind,
1944 AccessTy: LU.AccessTy, BaseGV: F.BaseGV, BaseOffset: F.BaseOffset, HasBaseReg: F.HasBaseReg,
1945 Scale: F.Scale);
1946}
1947
1948static InstructionCost getScalingFactorCost(const TargetTransformInfo &TTI,
1949 const LSRUse &LU, const Formula &F,
1950 const Loop &L) {
1951 if (!F.Scale)
1952 return 0;
1953
1954 // If the use is not completely folded in that instruction, we will have to
1955 // pay an extra cost only for scale != 1.
1956 if (!isAMCompletelyFolded(TTI, MinOffset: LU.MinOffset, MaxOffset: LU.MaxOffset, Kind: LU.Kind,
1957 AccessTy: LU.AccessTy, F, L))
1958 return F.Scale != 1;
1959
1960 switch (LU.Kind) {
1961 case LSRUse::Address: {
1962 // Check the scaling factor cost with both the min and max offsets.
1963 int64_t ScalableMin = 0, ScalableMax = 0, FixedMin = 0, FixedMax = 0;
1964 if (F.BaseOffset.isScalable()) {
1965 ScalableMin = (F.BaseOffset + LU.MinOffset).getKnownMinValue();
1966 ScalableMax = (F.BaseOffset + LU.MaxOffset).getKnownMinValue();
1967 } else {
1968 FixedMin = (F.BaseOffset + LU.MinOffset).getFixedValue();
1969 FixedMax = (F.BaseOffset + LU.MaxOffset).getFixedValue();
1970 }
1971 InstructionCost ScaleCostMinOffset = TTI.getScalingFactorCost(
1972 Ty: LU.AccessTy.MemTy, BaseGV: F.BaseGV, BaseOffset: StackOffset::get(Fixed: FixedMin, Scalable: ScalableMin),
1973 HasBaseReg: F.HasBaseReg, Scale: F.Scale, AddrSpace: LU.AccessTy.AddrSpace);
1974 InstructionCost ScaleCostMaxOffset = TTI.getScalingFactorCost(
1975 Ty: LU.AccessTy.MemTy, BaseGV: F.BaseGV, BaseOffset: StackOffset::get(Fixed: FixedMax, Scalable: ScalableMax),
1976 HasBaseReg: F.HasBaseReg, Scale: F.Scale, AddrSpace: LU.AccessTy.AddrSpace);
1977
1978 assert(ScaleCostMinOffset.isValid() && ScaleCostMaxOffset.isValid() &&
1979 "Legal addressing mode has an illegal cost!");
1980 return std::max(a: ScaleCostMinOffset, b: ScaleCostMaxOffset);
1981 }
1982 case LSRUse::ICmpZero:
1983 case LSRUse::Basic:
1984 case LSRUse::Special:
1985 // The use is completely folded, i.e., everything is folded into the
1986 // instruction.
1987 return 0;
1988 }
1989
1990 llvm_unreachable("Invalid LSRUse Kind!");
1991}
1992
1993static bool isAlwaysFoldable(const TargetTransformInfo &TTI,
1994 LSRUse::KindType Kind, MemAccessTy AccessTy,
1995 GlobalValue *BaseGV, Immediate BaseOffset,
1996 bool HasBaseReg) {
1997 // Fast-path: zero is always foldable.
1998 if (BaseOffset.isZero() && !BaseGV)
1999 return true;
2000
2001 // Conservatively, create an address with an immediate and a
2002 // base and a scale.
2003 int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
2004
2005 // Canonicalize a scale of 1 to a base register if the formula doesn't
2006 // already have a base register.
2007 if (!HasBaseReg && Scale == 1) {
2008 Scale = 0;
2009 HasBaseReg = true;
2010 }
2011
2012 // FIXME: Try with + without a scale? Maybe based on TTI?
2013 // I think basereg + scaledreg + immediateoffset isn't a good 'conservative'
2014 // default for many architectures, not just AArch64 SVE. More investigation
2015 // needed later to determine if this should be used more widely than just
2016 // on scalable types.
2017 if (HasBaseReg && BaseOffset.isNonZero() && Kind != LSRUse::ICmpZero &&
2018 AccessTy.MemTy && AccessTy.MemTy->isScalableTy() && DropScaledForVScale)
2019 Scale = 0;
2020
2021 return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, BaseOffset,
2022 HasBaseReg, Scale);
2023}
2024
2025static bool isAlwaysFoldable(const TargetTransformInfo &TTI,
2026 ScalarEvolution &SE, Immediate MinOffset,
2027 Immediate MaxOffset, LSRUse::KindType Kind,
2028 MemAccessTy AccessTy, const SCEV *S,
2029 bool HasBaseReg) {
2030 // Fast-path: zero is always foldable.
2031 if (S->isZero()) return true;
2032
2033 // Conservatively, create an address with an immediate and a
2034 // base and a scale.
2035 SCEVUse SCopy = S;
2036 Immediate BaseOffset = ExtractImmediate(S&: SCopy, SE);
2037 GlobalValue *BaseGV = ExtractSymbol(S&: SCopy, SE);
2038
2039 // If there's anything else involved, it's not foldable.
2040 if (!SCopy->isZero())
2041 return false;
2042
2043 // Fast-path: zero is always foldable.
2044 if (BaseOffset.isZero() && !BaseGV)
2045 return true;
2046
2047 if (BaseOffset.isScalable())
2048 return false;
2049
2050 // Conservatively, create an address with an immediate and a
2051 // base and a scale.
2052 int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
2053
2054 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV,
2055 BaseOffset, HasBaseReg, Scale);
2056}
2057
2058namespace {
2059
2060/// An individual increment in a Chain of IV increments. Relate an IV user to
2061/// an expression that computes the IV it uses from the IV used by the previous
2062/// link in the Chain.
2063///
2064/// For the head of a chain, IncExpr holds the absolute SCEV expression for the
2065/// original IVOperand. The head of the chain's IVOperand is only valid during
2066/// chain collection, before LSR replaces IV users. During chain generation,
2067/// IncExpr can be used to find the new IVOperand that computes the same
2068/// expression.
2069struct IVInc {
2070 Instruction *UserInst;
2071 Value* IVOperand;
2072 const SCEV *IncExpr;
2073
2074 IVInc(Instruction *U, Value *O, const SCEV *E)
2075 : UserInst(U), IVOperand(O), IncExpr(E) {}
2076};
2077
2078// The list of IV increments in program order. We typically add the head of a
2079// chain without finding subsequent links.
2080struct IVChain {
2081 SmallVector<IVInc, 1> Incs;
2082 const SCEV *ExprBase = nullptr;
2083
2084 IVChain() = default;
2085 IVChain(const IVInc &Head, const SCEV *Base)
2086 : Incs(1, Head), ExprBase(Base) {}
2087
2088 using const_iterator = SmallVectorImpl<IVInc>::const_iterator;
2089
2090 // Return the first increment in the chain.
2091 const_iterator begin() const {
2092 assert(!Incs.empty());
2093 return std::next(x: Incs.begin());
2094 }
2095 const_iterator end() const {
2096 return Incs.end();
2097 }
2098
2099 // Returns true if this chain contains any increments.
2100 bool hasIncs() const { return Incs.size() >= 2; }
2101
2102 // Add an IVInc to the end of this chain.
2103 void add(const IVInc &X) { Incs.push_back(Elt: X); }
2104
2105 // Returns the last UserInst in the chain.
2106 Instruction *tailUserInst() const { return Incs.back().UserInst; }
2107
2108 // Returns true if IncExpr can be profitably added to this chain.
2109 bool isProfitableIncrement(const SCEV *OperExpr,
2110 const SCEV *IncExpr,
2111 ScalarEvolution&);
2112};
2113
2114/// Helper for CollectChains to track multiple IV increment uses. Distinguish
2115/// between FarUsers that definitely cross IV increments and NearUsers that may
2116/// be used between IV increments.
2117struct ChainUsers {
2118 SmallPtrSet<Instruction*, 4> FarUsers;
2119 SmallPtrSet<Instruction*, 4> NearUsers;
2120};
2121
2122/// This class holds state for the main loop strength reduction logic.
2123class LSRInstance {
2124 IVUsers &IU;
2125 ScalarEvolution &SE;
2126 DominatorTree &DT;
2127 LoopInfo &LI;
2128 AssumptionCache &AC;
2129 TargetLibraryInfo &TLI;
2130 const TargetTransformInfo &TTI;
2131 Loop *const L;
2132 MemorySSAUpdater *MSSAU;
2133 TTI::AddressingModeKind AMK;
2134 mutable SCEVExpander Rewriter;
2135 bool Changed = false;
2136 bool HardwareLoopProfitable = false;
2137
2138 /// This is the insert position that the current loop's induction variable
2139 /// increment should be placed. In simple loops, this is the latch block's
2140 /// terminator. But in more complicated cases, this is a position which will
2141 /// dominate all the in-loop post-increment users.
2142 Instruction *IVIncInsertPos = nullptr;
2143
2144 /// Interesting factors between use strides.
2145 ///
2146 /// We explicitly use a SetVector which contains a SmallSet, instead of the
2147 /// default, a SmallDenseSet, because we need to use the full range of
2148 /// int64_ts, and there's currently no good way of doing that with
2149 /// SmallDenseSet.
2150 SetVector<int64_t, SmallVector<int64_t, 8>, SmallSet<int64_t, 8>> Factors;
2151
2152 /// The cost of the current SCEV, the best solution by LSR will be dropped if
2153 /// the solution is not profitable.
2154 Cost BaselineCost;
2155
2156 /// Interesting use types, to facilitate truncation reuse.
2157 SmallSetVector<Type *, 4> Types;
2158
2159 /// The list of interesting uses.
2160 mutable SmallVector<LSRUse, 16> Uses;
2161
2162 /// Track which uses use which register candidates.
2163 RegUseTracker RegUses;
2164
2165 // Limit the number of chains to avoid quadratic behavior. We don't expect to
2166 // have more than a few IV increment chains in a loop. Missing a Chain falls
2167 // back to normal LSR behavior for those uses.
2168 static const unsigned MaxChains = 8;
2169
2170 /// IV users can form a chain of IV increments.
2171 SmallVector<IVChain, MaxChains> IVChainVec;
2172
2173 /// IV users that belong to profitable IVChains.
2174 SmallPtrSet<Use*, MaxChains> IVIncSet;
2175
2176 /// Induction variables that were generated and inserted by the SCEV Expander.
2177 SmallVector<llvm::WeakVH, 2> ScalarEvolutionIVs;
2178
2179 // Inserting instructions in the loop and using them as PHI's input could
2180 // break LCSSA in case if PHI's parent block is not a loop exit (i.e. the
2181 // corresponding incoming block is not loop exiting). So collect all such
2182 // instructions to form LCSSA for them later.
2183 SmallSetVector<Instruction *, 4> InsertedNonLCSSAInsts;
2184
2185 void OptimizeShadowIV();
2186 bool FindIVUserForCond(Instruction *Cond, IVStrideUse *&CondUse);
2187 Instruction *OptimizeMax(ICmpInst *Cond, IVStrideUse *&CondUse);
2188 void OptimizeLoopTermCond();
2189
2190 void ChainInstruction(Instruction *UserInst, Instruction *IVOper,
2191 SmallVectorImpl<ChainUsers> &ChainUsersVec);
2192 void FinalizeChain(IVChain &Chain);
2193 void CollectChains();
2194 void GenerateIVChain(const IVChain &Chain,
2195 SmallVectorImpl<WeakTrackingVH> &DeadInsts);
2196
2197 void CollectInterestingTypesAndFactors();
2198 void CollectFixupsAndInitialFormulae();
2199
2200 // Support for sharing of LSRUses between LSRFixups.
2201 using UseMapTy = DenseMap<LSRUse::SCEVUseKindPair, size_t>;
2202 UseMapTy UseMap;
2203
2204 bool reconcileNewOffset(LSRUse &LU, Immediate NewOffset, bool HasBaseReg,
2205 LSRUse::KindType Kind, MemAccessTy AccessTy);
2206
2207 std::pair<size_t, Immediate> getUse(const SCEV *&Expr, LSRUse::KindType Kind,
2208 MemAccessTy AccessTy);
2209
2210 void DeleteUse(LSRUse &LU, size_t LUIdx);
2211
2212 LSRUse *FindUseWithSimilarFormula(const Formula &F, const LSRUse &OrigLU);
2213
2214 void InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
2215 void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
2216 void CountRegisters(const Formula &F, size_t LUIdx);
2217 bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F);
2218 bool IsFixupExecutedEachIncrement(const LSRFixup &LF) const;
2219
2220 void CollectLoopInvariantFixupsAndFormulae();
2221
2222 void GenerateReassociations(LSRUse &LU, unsigned LUIdx, Formula Base,
2223 unsigned Depth = 0);
2224
2225 void GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx,
2226 const Formula &Base, unsigned Depth,
2227 size_t Idx, bool IsScaledReg = false);
2228 void GenerateCombinations(LSRUse &LU, unsigned LUIdx, Formula Base);
2229 void GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx,
2230 const Formula &Base, size_t Idx,
2231 bool IsScaledReg = false);
2232 void GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
2233 void GenerateConstantOffsetsImpl(LSRUse &LU, unsigned LUIdx,
2234 const Formula &Base,
2235 const SmallVectorImpl<Immediate> &Worklist,
2236 size_t Idx, bool IsScaledReg = false);
2237 void GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
2238 void GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, Formula Base);
2239 void GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base);
2240 void GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base);
2241 void GenerateCrossUseConstantOffsets();
2242 void GenerateAllReuseFormulae();
2243
2244 void FilterOutUndesirableDedicatedRegisters();
2245
2246 size_t EstimateSearchSpaceComplexity() const;
2247 void NarrowSearchSpaceByDetectingSupersets();
2248 void NarrowSearchSpaceByCollapsingUnrolledCode();
2249 void NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
2250 void NarrowSearchSpaceByFilterFormulaWithSameScaledReg();
2251 void NarrowSearchSpaceByFilterPostInc();
2252 void NarrowSearchSpaceByDeletingCostlyFormulas();
2253 void NarrowSearchSpaceByPickingWinnerRegs();
2254 void NarrowSearchSpaceUsingHeuristics();
2255
2256 void SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
2257 Cost &SolutionCost,
2258 SmallVectorImpl<const Formula *> &Workspace,
2259 const Cost &CurCost,
2260 const SmallPtrSet<const SCEV *, 16> &CurRegs,
2261 DenseSet<const SCEV *> &VisitedRegs) const;
2262 void Solve(SmallVectorImpl<const Formula *> &Solution) const;
2263
2264 BasicBlock::iterator
2265 HoistInsertPosition(BasicBlock::iterator IP,
2266 const SmallVectorImpl<Instruction *> &Inputs) const;
2267 BasicBlock::iterator AdjustInsertPositionForExpand(BasicBlock::iterator IP,
2268 const LSRFixup &LF,
2269 const LSRUse &LU) const;
2270
2271 Value *Expand(const LSRUse &LU, const LSRFixup &LF, const Formula &F,
2272 BasicBlock::iterator IP,
2273 SmallVectorImpl<WeakTrackingVH> &DeadInsts) const;
2274 void RewriteForPHI(PHINode *PN, const LSRUse &LU, const LSRFixup &LF,
2275 const Formula &F,
2276 SmallVectorImpl<WeakTrackingVH> &DeadInsts);
2277 void Rewrite(const LSRUse &LU, const LSRFixup &LF, const Formula &F,
2278 SmallVectorImpl<WeakTrackingVH> &DeadInsts);
2279 void ImplementSolution(const SmallVectorImpl<const Formula *> &Solution);
2280
2281public:
2282 LSRInstance(Loop *L, IVUsers &IU, ScalarEvolution &SE, DominatorTree &DT,
2283 LoopInfo &LI, const TargetTransformInfo &TTI, AssumptionCache &AC,
2284 TargetLibraryInfo &TLI, MemorySSAUpdater *MSSAU);
2285
2286 bool getChanged() const { return Changed; }
2287 const SmallVectorImpl<WeakVH> &getScalarEvolutionIVs() const {
2288 return ScalarEvolutionIVs;
2289 }
2290
2291 void print_factors_and_types(raw_ostream &OS) const;
2292 void print_fixups(raw_ostream &OS) const;
2293 void print_uses(raw_ostream &OS) const;
2294 void print(raw_ostream &OS) const;
2295 void dump() const;
2296};
2297
2298} // end anonymous namespace
2299
2300/// If IV is used in a int-to-float cast inside the loop then try to eliminate
2301/// the cast operation.
2302void LSRInstance::OptimizeShadowIV() {
2303 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
2304 if (isa<SCEVCouldNotCompute>(Val: BackedgeTakenCount))
2305 return;
2306
2307 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end();
2308 UI != E; /* empty */) {
2309 IVUsers::const_iterator CandidateUI = UI;
2310 ++UI;
2311 Instruction *ShadowUse = CandidateUI->getUser();
2312 Type *DestTy = nullptr;
2313 bool IsSigned = false;
2314
2315 /* If shadow use is a int->float cast then insert a second IV
2316 to eliminate this cast.
2317
2318 for (unsigned i = 0; i < n; ++i)
2319 foo((double)i);
2320
2321 is transformed into
2322
2323 double d = 0.0;
2324 for (unsigned i = 0; i < n; ++i, ++d)
2325 foo(d);
2326 */
2327 if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(Val: CandidateUI->getUser())) {
2328 IsSigned = false;
2329 DestTy = UCast->getDestTy();
2330 }
2331 else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(Val: CandidateUI->getUser())) {
2332 IsSigned = true;
2333 DestTy = SCast->getDestTy();
2334 }
2335 if (!DestTy) continue;
2336
2337 // If target does not support DestTy natively then do not apply
2338 // this transformation.
2339 if (!TTI.isTypeLegal(Ty: DestTy)) continue;
2340
2341 PHINode *PH = dyn_cast<PHINode>(Val: ShadowUse->getOperand(i: 0));
2342 if (!PH) continue;
2343 if (PH->getNumIncomingValues() != 2) continue;
2344
2345 // If the calculation in integers overflows, the result in FP type will
2346 // differ. So we only can do this transformation if we are guaranteed to not
2347 // deal with overflowing values
2348 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Val: SE.getSCEV(V: PH));
2349 if (!AR) continue;
2350 if (IsSigned && !AR->hasNoSignedWrap()) continue;
2351 if (!IsSigned && !AR->hasNoUnsignedWrap()) continue;
2352
2353 Type *SrcTy = PH->getType();
2354 int Mantissa = DestTy->getFPMantissaWidth();
2355 if (Mantissa == -1) continue;
2356 if ((int)SE.getTypeSizeInBits(Ty: SrcTy) > Mantissa)
2357 continue;
2358
2359 unsigned Entry, Latch;
2360 if (PH->getIncomingBlock(i: 0) == L->getLoopPreheader()) {
2361 Entry = 0;
2362 Latch = 1;
2363 } else {
2364 Entry = 1;
2365 Latch = 0;
2366 }
2367
2368 ConstantInt *Init = dyn_cast<ConstantInt>(Val: PH->getIncomingValue(i: Entry));
2369 if (!Init) continue;
2370 Constant *NewInit = ConstantFP::get(Ty: DestTy, V: IsSigned ?
2371 (double)Init->getSExtValue() :
2372 (double)Init->getZExtValue());
2373
2374 BinaryOperator *Incr =
2375 dyn_cast<BinaryOperator>(Val: PH->getIncomingValue(i: Latch));
2376 if (!Incr) continue;
2377 if (Incr->getOpcode() != Instruction::Add
2378 && Incr->getOpcode() != Instruction::Sub)
2379 continue;
2380
2381 /* Initialize new IV, double d = 0.0 in above example. */
2382 ConstantInt *C = nullptr;
2383 if (Incr->getOperand(i_nocapture: 0) == PH)
2384 C = dyn_cast<ConstantInt>(Val: Incr->getOperand(i_nocapture: 1));
2385 else if (Incr->getOperand(i_nocapture: 1) == PH)
2386 C = dyn_cast<ConstantInt>(Val: Incr->getOperand(i_nocapture: 0));
2387 else
2388 continue;
2389
2390 if (!C) continue;
2391
2392 // Ignore negative constants, as the code below doesn't handle them
2393 // correctly. TODO: Remove this restriction.
2394 if (!C->getValue().isStrictlyPositive())
2395 continue;
2396
2397 /* Add new PHINode. */
2398 PHINode *NewPH = PHINode::Create(Ty: DestTy, NumReservedValues: 2, NameStr: "IV.S.", InsertBefore: PH->getIterator());
2399 NewPH->setDebugLoc(PH->getDebugLoc());
2400
2401 /* create new increment. '++d' in above example. */
2402 Constant *CFP = ConstantFP::get(Ty: DestTy, V: C->getZExtValue());
2403 BinaryOperator *NewIncr = BinaryOperator::Create(
2404 Op: Incr->getOpcode() == Instruction::Add ? Instruction::FAdd
2405 : Instruction::FSub,
2406 S1: NewPH, S2: CFP, Name: "IV.S.next.", InsertBefore: Incr->getIterator());
2407 NewIncr->setDebugLoc(Incr->getDebugLoc());
2408
2409 NewPH->addIncoming(V: NewInit, BB: PH->getIncomingBlock(i: Entry));
2410 NewPH->addIncoming(V: NewIncr, BB: PH->getIncomingBlock(i: Latch));
2411
2412 /* Remove cast operation */
2413 ShadowUse->replaceAllUsesWith(V: NewPH);
2414 ShadowUse->eraseFromParent();
2415 Changed = true;
2416 break;
2417 }
2418}
2419
2420/// If Cond has an operand that is an expression of an IV, set the IV user and
2421/// stride information and return true, otherwise return false.
2422bool LSRInstance::FindIVUserForCond(Instruction *Cond, IVStrideUse *&CondUse) {
2423 for (IVStrideUse &U : IU)
2424 if (U.getUser() == Cond) {
2425 // NOTE: we could handle setcc instructions with multiple uses here, but
2426 // InstCombine does it as well for simple uses, it's not clear that it
2427 // occurs enough in real life to handle.
2428 CondUse = &U;
2429 return true;
2430 }
2431 return false;
2432}
2433
2434/// Rewrite the loop's terminating condition if it uses a max computation.
2435///
2436/// This is a narrow solution to a specific, but acute, problem. For loops
2437/// like this:
2438///
2439/// i = 0;
2440/// do {
2441/// p[i] = 0.0;
2442/// } while (++i < n);
2443///
2444/// the trip count isn't just 'n', because 'n' might not be positive. And
2445/// unfortunately this can come up even for loops where the user didn't use
2446/// a C do-while loop. For example, seemingly well-behaved top-test loops
2447/// will commonly be lowered like this:
2448///
2449/// if (n > 0) {
2450/// i = 0;
2451/// do {
2452/// p[i] = 0.0;
2453/// } while (++i < n);
2454/// }
2455///
2456/// and then it's possible for subsequent optimization to obscure the if
2457/// test in such a way that indvars can't find it.
2458///
2459/// When indvars can't find the if test in loops like this, it creates a
2460/// max expression, which allows it to give the loop a canonical
2461/// induction variable:
2462///
2463/// i = 0;
2464/// max = n < 1 ? 1 : n;
2465/// do {
2466/// p[i] = 0.0;
2467/// } while (++i != max);
2468///
2469/// Canonical induction variables are necessary because the loop passes
2470/// are designed around them. The most obvious example of this is the
2471/// LoopInfo analysis, which doesn't remember trip count values. It
2472/// expects to be able to rediscover the trip count each time it is
2473/// needed, and it does this using a simple analysis that only succeeds if
2474/// the loop has a canonical induction variable.
2475///
2476/// However, when it comes time to generate code, the maximum operation
2477/// can be quite costly, especially if it's inside of an outer loop.
2478///
2479/// This function solves this problem by detecting this type of loop and
2480/// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
2481/// the instructions for the maximum computation.
2482Instruction *LSRInstance::OptimizeMax(ICmpInst *Cond, IVStrideUse *&CondUse) {
2483 // Check that the loop matches the pattern we're looking for.
2484 if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
2485 Cond->getPredicate() != CmpInst::ICMP_NE)
2486 return Cond;
2487
2488 SelectInst *Sel = dyn_cast<SelectInst>(Val: Cond->getOperand(i_nocapture: 1));
2489 if (!Sel || !Sel->hasOneUse()) return Cond;
2490
2491 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
2492 if (isa<SCEVCouldNotCompute>(Val: BackedgeTakenCount))
2493 return Cond;
2494 const SCEV *One = SE.getConstant(Ty: BackedgeTakenCount->getType(), V: 1);
2495
2496 // Add one to the backedge-taken count to get the trip count.
2497 const SCEV *IterationCount = SE.getAddExpr(LHS: One, RHS: BackedgeTakenCount);
2498 if (IterationCount != SE.getSCEV(V: Sel)) return Cond;
2499
2500 // Check for a max calculation that matches the pattern. There's no check
2501 // for ICMP_ULE here because the comparison would be with zero, which
2502 // isn't interesting.
2503 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
2504 const SCEVNAryExpr *Max = nullptr;
2505 if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(Val: BackedgeTakenCount)) {
2506 Pred = ICmpInst::ICMP_SLE;
2507 Max = S;
2508 } else if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(Val: IterationCount)) {
2509 Pred = ICmpInst::ICMP_SLT;
2510 Max = S;
2511 } else if (const SCEVUMaxExpr *U = dyn_cast<SCEVUMaxExpr>(Val: IterationCount)) {
2512 Pred = ICmpInst::ICMP_ULT;
2513 Max = U;
2514 } else {
2515 // No match; bail.
2516 return Cond;
2517 }
2518
2519 // To handle a max with more than two operands, this optimization would
2520 // require additional checking and setup.
2521 if (Max->getNumOperands() != 2)
2522 return Cond;
2523
2524 const SCEV *MaxLHS = Max->getOperand(i: 0);
2525 const SCEV *MaxRHS = Max->getOperand(i: 1);
2526
2527 // ScalarEvolution canonicalizes constants to the left. For < and >, look
2528 // for a comparison with 1. For <= and >=, a comparison with zero.
2529 if (!MaxLHS ||
2530 (ICmpInst::isTrueWhenEqual(predicate: Pred) ? !MaxLHS->isZero() : (MaxLHS != One)))
2531 return Cond;
2532
2533 // Check the relevant induction variable for conformance to
2534 // the pattern.
2535 const SCEV *IV = SE.getSCEV(V: Cond->getOperand(i_nocapture: 0));
2536 if (!match(S: IV,
2537 P: m_scev_AffineAddRec(Op0: m_scev_SpecificInt(V: 1), Op1: m_scev_SpecificInt(V: 1))))
2538 return Cond;
2539
2540 assert(cast<SCEVAddRecExpr>(IV)->getLoop() == L &&
2541 "Loop condition operand is an addrec in a different loop!");
2542
2543 // Check the right operand of the select, and remember it, as it will
2544 // be used in the new comparison instruction.
2545 Value *NewRHS = nullptr;
2546 if (ICmpInst::isTrueWhenEqual(predicate: Pred)) {
2547 // Look for n+1, and grab n.
2548 if (AddOperator *BO = dyn_cast<AddOperator>(Val: Sel->getOperand(i_nocapture: 1)))
2549 if (ConstantInt *BO1 = dyn_cast<ConstantInt>(Val: BO->getOperand(i_nocapture: 1)))
2550 if (BO1->isOne() && SE.getSCEV(V: BO->getOperand(i_nocapture: 0)) == MaxRHS)
2551 NewRHS = BO->getOperand(i_nocapture: 0);
2552 if (AddOperator *BO = dyn_cast<AddOperator>(Val: Sel->getOperand(i_nocapture: 2)))
2553 if (ConstantInt *BO1 = dyn_cast<ConstantInt>(Val: BO->getOperand(i_nocapture: 1)))
2554 if (BO1->isOne() && SE.getSCEV(V: BO->getOperand(i_nocapture: 0)) == MaxRHS)
2555 NewRHS = BO->getOperand(i_nocapture: 0);
2556 if (!NewRHS)
2557 return Cond;
2558 } else if (SE.getSCEV(V: Sel->getOperand(i_nocapture: 1)) == MaxRHS)
2559 NewRHS = Sel->getOperand(i_nocapture: 1);
2560 else if (SE.getSCEV(V: Sel->getOperand(i_nocapture: 2)) == MaxRHS)
2561 NewRHS = Sel->getOperand(i_nocapture: 2);
2562 else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(Val: MaxRHS))
2563 NewRHS = SU->getValue();
2564 else
2565 // Max doesn't match expected pattern.
2566 return Cond;
2567
2568 // Determine the new comparison opcode. It may be signed or unsigned,
2569 // and the original comparison may be either equality or inequality.
2570 if (Cond->getPredicate() == CmpInst::ICMP_EQ)
2571 Pred = CmpInst::getInversePredicate(pred: Pred);
2572
2573 // Ok, everything looks ok to change the condition into an SLT or SGE and
2574 // delete the max calculation.
2575 ICmpInst *NewCond = new ICmpInst(Cond->getIterator(), Pred,
2576 Cond->getOperand(i_nocapture: 0), NewRHS, "scmp");
2577
2578 // Delete the max calculation instructions.
2579 NewCond->setDebugLoc(Cond->getDebugLoc());
2580 Cond->replaceAllUsesWith(V: NewCond);
2581 CondUse->setUser(NewCond);
2582 Instruction *Cmp = cast<Instruction>(Val: Sel->getOperand(i_nocapture: 0));
2583 Cond->eraseFromParent();
2584 Sel->eraseFromParent();
2585 if (Cmp->use_empty()) {
2586 salvageDebugInfo(I&: *Cmp);
2587 Cmp->eraseFromParent();
2588 }
2589 return NewCond;
2590}
2591
2592/// Change loop terminating condition to use the postinc iv when possible.
2593void
2594LSRInstance::OptimizeLoopTermCond() {
2595 SmallPtrSet<Instruction *, 4> PostIncs;
2596
2597 // We need a different set of heuristics for rotated and non-rotated loops.
2598 // If a loop is rotated then the latch is also the backedge, so inserting
2599 // post-inc expressions just before the latch is ideal. To reduce live ranges
2600 // it also makes sense to rewrite terminating conditions to use post-inc
2601 // expressions.
2602 //
2603 // If the loop is not rotated then the latch is not a backedge; the latch
2604 // check is done in the loop head. Adding post-inc expressions before the
2605 // latch will cause overlapping live-ranges of pre-inc and post-inc expressions
2606 // in the loop body. In this case we do *not* want to use post-inc expressions
2607 // in the latch check, and we want to insert post-inc expressions before
2608 // the backedge.
2609 BasicBlock *LatchBlock = L->getLoopLatch();
2610 SmallVector<BasicBlock*, 8> ExitingBlocks;
2611 L->getExitingBlocks(ExitingBlocks);
2612 if (!llvm::is_contained(Range&: ExitingBlocks, Element: LatchBlock)) {
2613 // The backedge doesn't exit the loop; treat this as a head-tested loop.
2614 IVIncInsertPos = LatchBlock->getTerminator();
2615 return;
2616 }
2617
2618 // Otherwise treat this as a rotated loop.
2619 for (BasicBlock *ExitingBlock : ExitingBlocks) {
2620 // Get the terminating condition for the loop if possible. If we
2621 // can, we want to change it to use a post-incremented version of its
2622 // induction variable, to allow coalescing the live ranges for the IV into
2623 // one register value.
2624
2625 CondBrInst *TermBr = dyn_cast<CondBrInst>(Val: ExitingBlock->getTerminator());
2626 if (!TermBr)
2627 continue;
2628
2629 Instruction *Cond = dyn_cast<Instruction>(Val: TermBr->getCondition());
2630 // If the argument to TermBr is an extractelement, then the source of that
2631 // instruction is what's generated the condition.
2632 auto *Extract = dyn_cast_or_null<ExtractElementInst>(Val: Cond);
2633 if (Extract)
2634 Cond = dyn_cast<Instruction>(Val: Extract->getVectorOperand());
2635 // FIXME: We could do more here, like handling logical operations where one
2636 // side is a cmp that uses an induction variable.
2637 if (!Cond)
2638 continue;
2639
2640 // Search IVUsesByStride to find Cond's IVUse if there is one.
2641 IVStrideUse *CondUse = nullptr;
2642 if (!FindIVUserForCond(Cond, CondUse))
2643 continue;
2644
2645 // If the trip count is computed in terms of a max (due to ScalarEvolution
2646 // being unable to find a sufficient guard, for example), change the loop
2647 // comparison to use SLT or ULT instead of NE.
2648 // One consequence of doing this now is that it disrupts the count-down
2649 // optimization. That's not always a bad thing though, because in such
2650 // cases it may still be worthwhile to avoid a max.
2651 if (auto *Cmp = dyn_cast<ICmpInst>(Val: Cond))
2652 Cond = OptimizeMax(Cond: Cmp, CondUse);
2653
2654 // If this exiting block dominates the latch block, it may also use
2655 // the post-inc value if it won't be shared with other uses.
2656 // Check for dominance.
2657 if (!DT.dominates(A: ExitingBlock, B: LatchBlock))
2658 continue;
2659
2660 // Conservatively avoid trying to use the post-inc value in non-latch
2661 // exits if there may be pre-inc users in intervening blocks.
2662 if (LatchBlock != ExitingBlock)
2663 for (const IVStrideUse &UI : IU)
2664 // Test if the use is reachable from the exiting block. This dominator
2665 // query is a conservative approximation of reachability.
2666 if (&UI != CondUse &&
2667 !DT.properlyDominates(A: UI.getUser()->getParent(), B: ExitingBlock)) {
2668 // Conservatively assume there may be reuse if the quotient of their
2669 // strides could be a legal scale.
2670 const SCEV *A = IU.getStride(IU: *CondUse, L);
2671 const SCEV *B = IU.getStride(IU: UI, L);
2672 if (!A || !B) continue;
2673 if (SE.getTypeSizeInBits(Ty: A->getType()) !=
2674 SE.getTypeSizeInBits(Ty: B->getType())) {
2675 if (SE.getTypeSizeInBits(Ty: A->getType()) >
2676 SE.getTypeSizeInBits(Ty: B->getType()))
2677 B = SE.getSignExtendExpr(Op: B, Ty: A->getType());
2678 else
2679 A = SE.getSignExtendExpr(Op: A, Ty: B->getType());
2680 }
2681 if (const SCEVConstant *D =
2682 dyn_cast_or_null<SCEVConstant>(Val: getExactSDiv(LHS: B, RHS: A, SE))) {
2683 const ConstantInt *C = D->getValue();
2684 // Stride of one or negative one can have reuse with non-addresses.
2685 if (C->isOne() || C->isMinusOne())
2686 goto decline_post_inc;
2687 // Avoid weird situations.
2688 if (C->getValue().getSignificantBits() >= 64 ||
2689 C->getValue().isMinSignedValue())
2690 goto decline_post_inc;
2691 // Check for possible scaled-address reuse.
2692 if (isAddressUse(TTI, Inst: UI.getUser(), OperandVal: UI.getOperandValToReplace())) {
2693 MemAccessTy AccessTy =
2694 getAccessType(TTI, Inst: UI.getUser(), OperandVal: UI.getOperandValToReplace());
2695 int64_t Scale = C->getSExtValue();
2696 if (TTI.isLegalAddressingMode(Ty: AccessTy.MemTy, /*BaseGV=*/nullptr,
2697 /*BaseOffset=*/0,
2698 /*HasBaseReg=*/true, Scale,
2699 AddrSpace: AccessTy.AddrSpace))
2700 goto decline_post_inc;
2701 Scale = -Scale;
2702 if (TTI.isLegalAddressingMode(Ty: AccessTy.MemTy, /*BaseGV=*/nullptr,
2703 /*BaseOffset=*/0,
2704 /*HasBaseReg=*/true, Scale,
2705 AddrSpace: AccessTy.AddrSpace))
2706 goto decline_post_inc;
2707 }
2708 }
2709 }
2710
2711 LLVM_DEBUG(dbgs() << " Change loop exiting icmp to use postinc iv: "
2712 << *Cond << '\n');
2713
2714 // It's possible for the setcc instruction to be anywhere in the loop, and
2715 // possible for it to have multiple users. If it is not immediately before
2716 // the exiting block branch, move it.
2717 if (isa_and_nonnull<CmpInst>(Val: Cond) && Cond->getNextNode() != TermBr &&
2718 !Extract) {
2719 if (Cond->hasOneUse()) {
2720 Cond->moveBefore(InsertPos: TermBr->getIterator());
2721 } else {
2722 // Clone the terminating condition and insert into the loopend.
2723 Instruction *OldCond = Cond;
2724 Cond = Cond->clone();
2725 Cond->setName(L->getHeader()->getName() + ".termcond");
2726 Cond->insertInto(ParentBB: ExitingBlock, It: TermBr->getIterator());
2727
2728 // Clone the IVUse, as the old use still exists!
2729 CondUse = &IU.AddUser(User: Cond, Operand: CondUse->getOperandValToReplace());
2730 TermBr->replaceUsesOfWith(From: OldCond, To: Cond);
2731 }
2732 }
2733
2734 // If we get to here, we know that we can transform the setcc instruction to
2735 // use the post-incremented version of the IV, allowing us to coalesce the
2736 // live ranges for the IV correctly.
2737 CondUse->transformToPostInc(L);
2738 Changed = true;
2739
2740 PostIncs.insert(Ptr: Cond);
2741 decline_post_inc:;
2742 }
2743
2744 // Determine an insertion point for the loop induction variable increment. It
2745 // must dominate all the post-inc comparisons we just set up, and it must
2746 // dominate the loop latch edge.
2747 IVIncInsertPos = L->getLoopLatch()->getTerminator();
2748 for (Instruction *Inst : PostIncs)
2749 IVIncInsertPos = DT.findNearestCommonDominator(I1: IVIncInsertPos, I2: Inst);
2750}
2751
2752/// Determine if the given use can accommodate a fixup at the given offset and
2753/// other details. If so, update the use and return true.
2754bool LSRInstance::reconcileNewOffset(LSRUse &LU, Immediate NewOffset,
2755 bool HasBaseReg, LSRUse::KindType Kind,
2756 MemAccessTy AccessTy) {
2757 Immediate NewMinOffset = LU.MinOffset;
2758 Immediate NewMaxOffset = LU.MaxOffset;
2759 MemAccessTy NewAccessTy = AccessTy;
2760
2761 // Check for a mismatched kind. It's tempting to collapse mismatched kinds to
2762 // something conservative, however this can pessimize in the case that one of
2763 // the uses will have all its uses outside the loop, for example.
2764 if (LU.Kind != Kind)
2765 return false;
2766
2767 // Check for a mismatched access type, and fall back conservatively as needed.
2768 // TODO: Be less conservative when the type is similar and can use the same
2769 // addressing modes.
2770 if (Kind == LSRUse::Address) {
2771 if (AccessTy.MemTy != LU.AccessTy.MemTy) {
2772 NewAccessTy = MemAccessTy::getUnknown(Ctx&: AccessTy.MemTy->getContext(),
2773 AS: AccessTy.AddrSpace);
2774 }
2775 }
2776
2777 // Conservatively assume HasBaseReg is true for now.
2778 if (Immediate::isKnownLT(LHS: NewOffset, RHS: LU.MinOffset)) {
2779 if (!isAlwaysFoldable(TTI, Kind, AccessTy: NewAccessTy, /*BaseGV=*/nullptr,
2780 BaseOffset: LU.MaxOffset - NewOffset, HasBaseReg))
2781 return false;
2782 NewMinOffset = NewOffset;
2783 } else if (Immediate::isKnownGT(LHS: NewOffset, RHS: LU.MaxOffset)) {
2784 if (!isAlwaysFoldable(TTI, Kind, AccessTy: NewAccessTy, /*BaseGV=*/nullptr,
2785 BaseOffset: NewOffset - LU.MinOffset, HasBaseReg))
2786 return false;
2787 NewMaxOffset = NewOffset;
2788 }
2789
2790 // FIXME: We should be able to handle some level of scalable offset support
2791 // for 'void', but in order to get basic support up and running this is
2792 // being left out.
2793 if (NewAccessTy.MemTy && NewAccessTy.MemTy->isVoidTy() &&
2794 (NewMinOffset.isScalable() || NewMaxOffset.isScalable()))
2795 return false;
2796
2797 // Update the use.
2798 LU.MinOffset = NewMinOffset;
2799 LU.MaxOffset = NewMaxOffset;
2800 LU.AccessTy = NewAccessTy;
2801 return true;
2802}
2803
2804/// Return an LSRUse index and an offset value for a fixup which needs the given
2805/// expression, with the given kind and optional access type. Either reuse an
2806/// existing use or create a new one, as needed.
2807std::pair<size_t, Immediate> LSRInstance::getUse(const SCEV *&Expr,
2808 LSRUse::KindType Kind,
2809 MemAccessTy AccessTy) {
2810 const SCEV *Copy = Expr;
2811 SCEVUse ExprUse = Expr;
2812 Immediate Offset = ExtractImmediate(S&: ExprUse, SE);
2813 Expr = ExprUse;
2814
2815 // Basic uses can't accept any offset, for example.
2816 if (!isAlwaysFoldable(TTI, Kind, AccessTy, /*BaseGV=*/ nullptr,
2817 BaseOffset: Offset, /*HasBaseReg=*/ true)) {
2818 Expr = Copy;
2819 Offset = Immediate::getFixed(MinVal: 0);
2820 }
2821
2822 std::pair<UseMapTy::iterator, bool> P =
2823 UseMap.try_emplace(Key: LSRUse::SCEVUseKindPair(Expr, Kind));
2824 if (!P.second) {
2825 // A use already existed with this base.
2826 size_t LUIdx = P.first->second;
2827 LSRUse &LU = Uses[LUIdx];
2828 if (reconcileNewOffset(LU, NewOffset: Offset, /*HasBaseReg=*/true, Kind, AccessTy))
2829 // Reuse this use.
2830 return std::make_pair(x&: LUIdx, y&: Offset);
2831 }
2832
2833 // Create a new use.
2834 size_t LUIdx = Uses.size();
2835 P.first->second = LUIdx;
2836 Uses.push_back(Elt: LSRUse(Kind, AccessTy));
2837 LSRUse &LU = Uses[LUIdx];
2838
2839 LU.MinOffset = Offset;
2840 LU.MaxOffset = Offset;
2841 return std::make_pair(x&: LUIdx, y&: Offset);
2842}
2843
2844/// Delete the given use from the Uses list.
2845void LSRInstance::DeleteUse(LSRUse &LU, size_t LUIdx) {
2846 if (&LU != &Uses.back())
2847 std::swap(a&: LU, b&: Uses.back());
2848 Uses.pop_back();
2849
2850 // Update RegUses.
2851 RegUses.swapAndDropUse(LUIdx, LastLUIdx: Uses.size());
2852}
2853
2854/// Look for a use distinct from OrigLU which is has a formula that has the same
2855/// registers as the given formula.
2856LSRUse *
2857LSRInstance::FindUseWithSimilarFormula(const Formula &OrigF,
2858 const LSRUse &OrigLU) {
2859 // Search all uses for the formula. This could be more clever.
2860 for (LSRUse &LU : Uses) {
2861 // Check whether this use is close enough to OrigLU, to see whether it's
2862 // worthwhile looking through its formulae.
2863 // Ignore ICmpZero uses because they may contain formulae generated by
2864 // GenerateICmpZeroScales, in which case adding fixup offsets may
2865 // be invalid.
2866 if (&LU != &OrigLU && LU.Kind != LSRUse::ICmpZero &&
2867 LU.Kind == OrigLU.Kind && OrigLU.AccessTy == LU.AccessTy &&
2868 LU.HasFormulaWithSameRegs(F: OrigF)) {
2869 // Scan through this use's formulae.
2870 for (const Formula &F : LU.Formulae) {
2871 // Check to see if this formula has the same registers and symbols
2872 // as OrigF.
2873 if (F.BaseRegs == OrigF.BaseRegs &&
2874 F.ScaledReg == OrigF.ScaledReg &&
2875 F.BaseGV == OrigF.BaseGV &&
2876 F.Scale == OrigF.Scale &&
2877 F.UnfoldedOffset == OrigF.UnfoldedOffset) {
2878 if (F.BaseOffset.isZero())
2879 return &LU;
2880 // This is the formula where all the registers and symbols matched;
2881 // there aren't going to be any others. Since we declined it, we
2882 // can skip the rest of the formulae and proceed to the next LSRUse.
2883 break;
2884 }
2885 }
2886 }
2887 }
2888
2889 // Nothing looked good.
2890 return nullptr;
2891}
2892
2893void LSRInstance::CollectInterestingTypesAndFactors() {
2894 SmallSetVector<const SCEV *, 4> Strides;
2895
2896 // Collect interesting types and strides.
2897 SmallVector<const SCEV *, 4> Worklist;
2898 for (const IVStrideUse &U : IU) {
2899 const SCEV *Expr = IU.getExpr(IU: U);
2900 if (!Expr)
2901 continue;
2902
2903 // Collect interesting types.
2904 Types.insert(X: SE.getEffectiveSCEVType(Ty: Expr->getType()));
2905
2906 // Add strides for mentioned loops.
2907 Worklist.push_back(Elt: Expr);
2908 do {
2909 const SCEV *S = Worklist.pop_back_val();
2910 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Val: S)) {
2911 if (AR->getLoop() == L)
2912 Strides.insert(X: AR->getStepRecurrence(SE));
2913 Worklist.push_back(Elt: AR->getStart());
2914 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Val: S)) {
2915 append_range(C&: Worklist, R: Add->operands());
2916 }
2917 } while (!Worklist.empty());
2918 }
2919
2920 // Compute interesting factors from the set of interesting strides.
2921 for (SmallSetVector<const SCEV *, 4>::const_iterator
2922 I = Strides.begin(), E = Strides.end(); I != E; ++I)
2923 for (SmallSetVector<const SCEV *, 4>::const_iterator NewStrideIter =
2924 std::next(x: I); NewStrideIter != E; ++NewStrideIter) {
2925 const SCEV *OldStride = *I;
2926 const SCEV *NewStride = *NewStrideIter;
2927
2928 if (SE.getTypeSizeInBits(Ty: OldStride->getType()) !=
2929 SE.getTypeSizeInBits(Ty: NewStride->getType())) {
2930 if (SE.getTypeSizeInBits(Ty: OldStride->getType()) >
2931 SE.getTypeSizeInBits(Ty: NewStride->getType()))
2932 NewStride = SE.getSignExtendExpr(Op: NewStride, Ty: OldStride->getType());
2933 else
2934 OldStride = SE.getSignExtendExpr(Op: OldStride, Ty: NewStride->getType());
2935 }
2936 if (const SCEVConstant *Factor =
2937 dyn_cast_or_null<SCEVConstant>(Val: getExactSDiv(LHS: NewStride, RHS: OldStride,
2938 SE, IgnoreSignificantBits: true))) {
2939 if (Factor->getAPInt().getSignificantBits() <= 64 && !Factor->isZero())
2940 Factors.insert(X: Factor->getAPInt().getSExtValue());
2941 } else if (const SCEVConstant *Factor =
2942 dyn_cast_or_null<SCEVConstant>(Val: getExactSDiv(LHS: OldStride,
2943 RHS: NewStride,
2944 SE, IgnoreSignificantBits: true))) {
2945 if (Factor->getAPInt().getSignificantBits() <= 64 && !Factor->isZero())
2946 Factors.insert(X: Factor->getAPInt().getSExtValue());
2947 }
2948 }
2949
2950 // If all uses use the same type, don't bother looking for truncation-based
2951 // reuse.
2952 if (Types.size() == 1)
2953 Types.clear();
2954
2955 LLVM_DEBUG(print_factors_and_types(dbgs()));
2956}
2957
2958/// Helper for CollectChains that finds an IV operand (computed by an AddRec in
2959/// this loop) within [OI,OE) or returns OE. If IVUsers mapped Instructions to
2960/// IVStrideUses, we could partially skip this.
2961static User::op_iterator
2962findIVOperand(User::op_iterator OI, User::op_iterator OE,
2963 Loop *L, ScalarEvolution &SE) {
2964 for(; OI != OE; ++OI) {
2965 if (Instruction *Oper = dyn_cast<Instruction>(Val&: *OI)) {
2966 if (!SE.isSCEVable(Ty: Oper->getType()))
2967 continue;
2968
2969 if (const SCEVAddRecExpr *AR =
2970 dyn_cast<SCEVAddRecExpr>(Val: SE.getSCEV(V: Oper))) {
2971 if (AR->getLoop() == L)
2972 break;
2973 }
2974 }
2975 }
2976 return OI;
2977}
2978
2979/// IVChain logic must consistently peek base TruncInst operands, so wrap it in
2980/// a convenient helper.
2981static Value *getWideOperand(Value *Oper) {
2982 if (TruncInst *Trunc = dyn_cast<TruncInst>(Val: Oper))
2983 return Trunc->getOperand(i_nocapture: 0);
2984 return Oper;
2985}
2986
2987/// Return an approximation of this SCEV expression's "base", or NULL for any
2988/// constant. Returning the expression itself is conservative. Returning a
2989/// deeper subexpression is more precise and valid as long as it isn't less
2990/// complex than another subexpression. For expressions involving multiple
2991/// unscaled values, we need to return the pointer-type SCEVUnknown. This avoids
2992/// forming chains across objects, such as: PrevOper==a[i], IVOper==b[i],
2993/// IVInc==b-a.
2994///
2995/// Since SCEVUnknown is the rightmost type, and pointers are the rightmost
2996/// SCEVUnknown, we simply return the rightmost SCEV operand.
2997static const SCEV *getExprBase(const SCEV *S) {
2998 switch (S->getSCEVType()) {
2999 default: // including scUnknown.
3000 return S;
3001 case scConstant:
3002 case scVScale:
3003 return nullptr;
3004 case scTruncate:
3005 return getExprBase(S: cast<SCEVTruncateExpr>(Val: S)->getOperand());
3006 case scZeroExtend:
3007 return getExprBase(S: cast<SCEVZeroExtendExpr>(Val: S)->getOperand());
3008 case scSignExtend:
3009 return getExprBase(S: cast<SCEVSignExtendExpr>(Val: S)->getOperand());
3010 case scAddExpr: {
3011 // Skip over scaled operands (scMulExpr) to follow add operands as long as
3012 // there's nothing more complex.
3013 // FIXME: not sure if we want to recognize negation.
3014 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Val: S);
3015 for (const SCEV *SubExpr : reverse(C: Add->operands())) {
3016 if (SubExpr->getSCEVType() == scAddExpr)
3017 return getExprBase(S: SubExpr);
3018
3019 if (SubExpr->getSCEVType() != scMulExpr)
3020 return SubExpr;
3021 }
3022 return S; // all operands are scaled, be conservative.
3023 }
3024 case scAddRecExpr:
3025 return getExprBase(S: cast<SCEVAddRecExpr>(Val: S)->getStart());
3026 }
3027 llvm_unreachable("Unknown SCEV kind!");
3028}
3029
3030/// Return true if the chain increment is profitable to expand into a loop
3031/// invariant value, which may require its own register. A profitable chain
3032/// increment will be an offset relative to the same base. We allow such offsets
3033/// to potentially be used as chain increment as long as it's not obviously
3034/// expensive to expand using real instructions.
3035bool IVChain::isProfitableIncrement(const SCEV *OperExpr,
3036 const SCEV *IncExpr,
3037 ScalarEvolution &SE) {
3038 // Aggressively form chains when -stress-ivchain.
3039 if (StressIVChain)
3040 return true;
3041
3042 // Do not replace a constant offset from IV head with a nonconstant IV
3043 // increment.
3044 if (!isa<SCEVConstant>(Val: IncExpr)) {
3045 const SCEV *HeadExpr = SE.getSCEV(V: getWideOperand(Oper: Incs[0].IVOperand));
3046 if (isa<SCEVConstant>(Val: SE.getMinusSCEV(LHS: OperExpr, RHS: HeadExpr)))
3047 return false;
3048 }
3049
3050 SmallPtrSet<const SCEV*, 8> Processed;
3051 return !isHighCostExpansion(S: IncExpr, Processed, SE);
3052}
3053
3054/// Return true if the number of registers needed for the chain is estimated to
3055/// be less than the number required for the individual IV users. First prohibit
3056/// any IV users that keep the IV live across increments (the Users set should
3057/// be empty). Next count the number and type of increments in the chain.
3058///
3059/// Chaining IVs can lead to considerable code bloat if ISEL doesn't
3060/// effectively use postinc addressing modes. Only consider it profitable it the
3061/// increments can be computed in fewer registers when chained.
3062///
3063/// TODO: Consider IVInc free if it's already used in another chains.
3064static bool isProfitableChain(IVChain &Chain,
3065 SmallPtrSetImpl<Instruction *> &Users,
3066 ScalarEvolution &SE,
3067 const TargetTransformInfo &TTI) {
3068 if (StressIVChain)
3069 return true;
3070
3071 if (!Chain.hasIncs())
3072 return false;
3073
3074 if (!Users.empty()) {
3075 LLVM_DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " users:\n";
3076 for (Instruction *Inst
3077 : Users) { dbgs() << " " << *Inst << "\n"; });
3078 return false;
3079 }
3080 assert(!Chain.Incs.empty() && "empty IV chains are not allowed");
3081
3082 // The chain itself may require a register, so initialize cost to 1.
3083 int cost = 1;
3084
3085 // A complete chain likely eliminates the need for keeping the original IV in
3086 // a register. LSR does not currently know how to form a complete chain unless
3087 // the header phi already exists.
3088 if (isa<PHINode>(Val: Chain.tailUserInst())
3089 && SE.getSCEV(V: Chain.tailUserInst()) == Chain.Incs[0].IncExpr) {
3090 --cost;
3091 }
3092 const SCEV *LastIncExpr = nullptr;
3093 unsigned NumConstIncrements = 0;
3094 unsigned NumVarIncrements = 0;
3095 unsigned NumReusedIncrements = 0;
3096
3097 if (TTI.isProfitableLSRChainElement(I: Chain.Incs[0].UserInst))
3098 return true;
3099
3100 for (const IVInc &Inc : Chain) {
3101 if (TTI.isProfitableLSRChainElement(I: Inc.UserInst))
3102 return true;
3103 if (Inc.IncExpr->isZero())
3104 continue;
3105
3106 // Incrementing by zero or some constant is neutral. We assume constants can
3107 // be folded into an addressing mode or an add's immediate operand.
3108 if (isa<SCEVConstant>(Val: Inc.IncExpr)) {
3109 ++NumConstIncrements;
3110 continue;
3111 }
3112
3113 if (Inc.IncExpr == LastIncExpr)
3114 ++NumReusedIncrements;
3115 else
3116 ++NumVarIncrements;
3117
3118 LastIncExpr = Inc.IncExpr;
3119 }
3120 // An IV chain with a single increment is handled by LSR's postinc
3121 // uses. However, a chain with multiple increments requires keeping the IV's
3122 // value live longer than it needs to be if chained.
3123 if (NumConstIncrements > 1)
3124 --cost;
3125
3126 // Materializing increment expressions in the preheader that didn't exist in
3127 // the original code may cost a register. For example, sign-extended array
3128 // indices can produce ridiculous increments like this:
3129 // IV + ((sext i32 (2 * %s) to i64) + (-1 * (sext i32 %s to i64)))
3130 cost += NumVarIncrements;
3131
3132 // Reusing variable increments likely saves a register to hold the multiple of
3133 // the stride.
3134 cost -= NumReusedIncrements;
3135
3136 LLVM_DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " Cost: " << cost
3137 << "\n");
3138
3139 return cost < 0;
3140}
3141
3142/// Add this IV user to an existing chain or make it the head of a new chain.
3143void LSRInstance::ChainInstruction(Instruction *UserInst, Instruction *IVOper,
3144 SmallVectorImpl<ChainUsers> &ChainUsersVec) {
3145 // When IVs are used as types of varying widths, they are generally converted
3146 // to a wider type with some uses remaining narrow under a (free) trunc.
3147 Value *const NextIV = getWideOperand(Oper: IVOper);
3148 const SCEV *const OperExpr = SE.getSCEV(V: NextIV);
3149 const SCEV *const OperExprBase = getExprBase(S: OperExpr);
3150
3151 // Visit all existing chains. Check if its IVOper can be computed as a
3152 // profitable loop invariant increment from the last link in the Chain.
3153 unsigned ChainIdx = 0, NChains = IVChainVec.size();
3154 const SCEV *LastIncExpr = nullptr;
3155 for (; ChainIdx < NChains; ++ChainIdx) {
3156 IVChain &Chain = IVChainVec[ChainIdx];
3157
3158 // Prune the solution space aggressively by checking that both IV operands
3159 // are expressions that operate on the same unscaled SCEVUnknown. This
3160 // "base" will be canceled by the subsequent getMinusSCEV call. Checking
3161 // first avoids creating extra SCEV expressions.
3162 if (!StressIVChain && Chain.ExprBase != OperExprBase)
3163 continue;
3164
3165 Value *PrevIV = getWideOperand(Oper: Chain.Incs.back().IVOperand);
3166 if (PrevIV->getType() != NextIV->getType())
3167 continue;
3168
3169 // A phi node terminates a chain.
3170 if (isa<PHINode>(Val: UserInst) && isa<PHINode>(Val: Chain.tailUserInst()))
3171 continue;
3172
3173 // The increment must be loop-invariant so it can be kept in a register.
3174 const SCEV *PrevExpr = SE.getSCEV(V: PrevIV);
3175 const SCEV *IncExpr = SE.getMinusSCEV(LHS: OperExpr, RHS: PrevExpr);
3176 if (isa<SCEVCouldNotCompute>(Val: IncExpr) || !SE.isLoopInvariant(S: IncExpr, L))
3177 continue;
3178
3179 if (Chain.isProfitableIncrement(OperExpr, IncExpr, SE)) {
3180 LastIncExpr = IncExpr;
3181 break;
3182 }
3183 }
3184 // If we haven't found a chain, create a new one, unless we hit the max. Don't
3185 // bother for phi nodes, because they must be last in the chain.
3186 if (ChainIdx == NChains) {
3187 if (isa<PHINode>(Val: UserInst))
3188 return;
3189 if (NChains >= MaxChains && !StressIVChain) {
3190 LLVM_DEBUG(dbgs() << "IV Chain Limit\n");
3191 return;
3192 }
3193 LastIncExpr = OperExpr;
3194 // IVUsers may have skipped over sign/zero extensions. We don't currently
3195 // attempt to form chains involving extensions unless they can be hoisted
3196 // into this loop's AddRec.
3197 if (!isa<SCEVAddRecExpr>(Val: LastIncExpr))
3198 return;
3199 ++NChains;
3200 IVChainVec.push_back(Elt: IVChain(IVInc(UserInst, IVOper, LastIncExpr),
3201 OperExprBase));
3202 ChainUsersVec.resize(N: NChains);
3203 LLVM_DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Head: (" << *UserInst
3204 << ") IV=" << *LastIncExpr << "\n");
3205 } else {
3206 LLVM_DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Inc: (" << *UserInst
3207 << ") IV+" << *LastIncExpr << "\n");
3208 // Add this IV user to the end of the chain.
3209 IVChainVec[ChainIdx].add(X: IVInc(UserInst, IVOper, LastIncExpr));
3210 }
3211 IVChain &Chain = IVChainVec[ChainIdx];
3212
3213 SmallPtrSet<Instruction*,4> &NearUsers = ChainUsersVec[ChainIdx].NearUsers;
3214 // This chain's NearUsers become FarUsers.
3215 if (!LastIncExpr->isZero()) {
3216 ChainUsersVec[ChainIdx].FarUsers.insert_range(R&: NearUsers);
3217 NearUsers.clear();
3218 }
3219
3220 // All other uses of IVOperand become near uses of the chain.
3221 // We currently ignore intermediate values within SCEV expressions, assuming
3222 // they will eventually be used be the current chain, or can be computed
3223 // from one of the chain increments. To be more precise we could
3224 // transitively follow its user and only add leaf IV users to the set.
3225 for (User *U : IVOper->users()) {
3226 Instruction *OtherUse = dyn_cast<Instruction>(Val: U);
3227 if (!OtherUse)
3228 continue;
3229 // Uses in the chain will no longer be uses if the chain is formed.
3230 // Include the head of the chain in this iteration (not Chain.begin()).
3231 IVChain::const_iterator IncIter = Chain.Incs.begin();
3232 IVChain::const_iterator IncEnd = Chain.Incs.end();
3233 for( ; IncIter != IncEnd; ++IncIter) {
3234 if (IncIter->UserInst == OtherUse)
3235 break;
3236 }
3237 if (IncIter != IncEnd)
3238 continue;
3239
3240 if (SE.isSCEVable(Ty: OtherUse->getType())
3241 && !isa<SCEVUnknown>(Val: SE.getSCEV(V: OtherUse))
3242 && IU.isIVUserOrOperand(Inst: OtherUse)) {
3243 continue;
3244 }
3245 NearUsers.insert(Ptr: OtherUse);
3246 }
3247
3248 // Since this user is part of the chain, it's no longer considered a use
3249 // of the chain.
3250 ChainUsersVec[ChainIdx].FarUsers.erase(Ptr: UserInst);
3251}
3252
3253/// Populate the vector of Chains.
3254///
3255/// This decreases ILP at the architecture level. Targets with ample registers,
3256/// multiple memory ports, and no register renaming probably don't want
3257/// this. However, such targets should probably disable LSR altogether.
3258///
3259/// The job of LSR is to make a reasonable choice of induction variables across
3260/// the loop. Subsequent passes can easily "unchain" computation exposing more
3261/// ILP *within the loop* if the target wants it.
3262///
3263/// Finding the best IV chain is potentially a scheduling problem. Since LSR
3264/// will not reorder memory operations, it will recognize this as a chain, but
3265/// will generate redundant IV increments. Ideally this would be corrected later
3266/// by a smart scheduler:
3267/// = A[i]
3268/// = A[i+x]
3269/// A[i] =
3270/// A[i+x] =
3271///
3272/// TODO: Walk the entire domtree within this loop, not just the path to the
3273/// loop latch. This will discover chains on side paths, but requires
3274/// maintaining multiple copies of the Chains state.
3275void LSRInstance::CollectChains() {
3276 LLVM_DEBUG(dbgs() << "Collecting IV Chains.\n");
3277 SmallVector<ChainUsers, 8> ChainUsersVec;
3278
3279 SmallVector<BasicBlock *,8> LatchPath;
3280 BasicBlock *LoopHeader = L->getHeader();
3281 for (DomTreeNode *Rung = DT.getNode(BB: L->getLoopLatch());
3282 Rung->getBlock() != LoopHeader; Rung = Rung->getIDom()) {
3283 LatchPath.push_back(Elt: Rung->getBlock());
3284 }
3285 LatchPath.push_back(Elt: LoopHeader);
3286
3287 // Walk the instruction stream from the loop header to the loop latch.
3288 for (BasicBlock *BB : reverse(C&: LatchPath)) {
3289 for (Instruction &I : *BB) {
3290 // Skip instructions that weren't seen by IVUsers analysis.
3291 if (isa<PHINode>(Val: I) || !IU.isIVUserOrOperand(Inst: &I))
3292 continue;
3293
3294 // Ignore users that are part of a SCEV expression. This way we only
3295 // consider leaf IV Users. This effectively rediscovers a portion of
3296 // IVUsers analysis but in program order this time.
3297 if (SE.isSCEVable(Ty: I.getType()) && !isa<SCEVUnknown>(Val: SE.getSCEV(V: &I)))
3298 continue;
3299
3300 // Remove this instruction from any NearUsers set it may be in.
3301 for (unsigned ChainIdx = 0, NChains = IVChainVec.size();
3302 ChainIdx < NChains; ++ChainIdx) {
3303 ChainUsersVec[ChainIdx].NearUsers.erase(Ptr: &I);
3304 }
3305 // Search for operands that can be chained.
3306 SmallPtrSet<Instruction*, 4> UniqueOperands;
3307 User::op_iterator IVOpEnd = I.op_end();
3308 User::op_iterator IVOpIter = findIVOperand(OI: I.op_begin(), OE: IVOpEnd, L, SE);
3309 while (IVOpIter != IVOpEnd) {
3310 Instruction *IVOpInst = cast<Instruction>(Val&: *IVOpIter);
3311 if (UniqueOperands.insert(Ptr: IVOpInst).second)
3312 ChainInstruction(UserInst: &I, IVOper: IVOpInst, ChainUsersVec);
3313 IVOpIter = findIVOperand(OI: std::next(x: IVOpIter), OE: IVOpEnd, L, SE);
3314 }
3315 } // Continue walking down the instructions.
3316 } // Continue walking down the domtree.
3317 // Visit phi backedges to determine if the chain can generate the IV postinc.
3318 for (PHINode &PN : L->getHeader()->phis()) {
3319 if (!SE.isSCEVable(Ty: PN.getType()))
3320 continue;
3321
3322 Instruction *IncV =
3323 dyn_cast<Instruction>(Val: PN.getIncomingValueForBlock(BB: L->getLoopLatch()));
3324 if (IncV)
3325 ChainInstruction(UserInst: &PN, IVOper: IncV, ChainUsersVec);
3326 }
3327 // Remove any unprofitable chains.
3328 unsigned ChainIdx = 0;
3329 for (unsigned UsersIdx = 0, NChains = IVChainVec.size();
3330 UsersIdx < NChains; ++UsersIdx) {
3331 if (!isProfitableChain(Chain&: IVChainVec[UsersIdx],
3332 Users&: ChainUsersVec[UsersIdx].FarUsers, SE, TTI))
3333 continue;
3334 // Preserve the chain at UsesIdx.
3335 if (ChainIdx != UsersIdx)
3336 IVChainVec[ChainIdx] = IVChainVec[UsersIdx];
3337 FinalizeChain(Chain&: IVChainVec[ChainIdx]);
3338 ++ChainIdx;
3339 }
3340 IVChainVec.resize(N: ChainIdx);
3341}
3342
3343void LSRInstance::FinalizeChain(IVChain &Chain) {
3344 assert(!Chain.Incs.empty() && "empty IV chains are not allowed");
3345 LLVM_DEBUG(dbgs() << "Final Chain: " << *Chain.Incs[0].UserInst << "\n");
3346
3347 for (const IVInc &Inc : Chain) {
3348 LLVM_DEBUG(dbgs() << " Inc: " << *Inc.UserInst << "\n");
3349 auto UseI = find(Range: Inc.UserInst->operands(), Val: Inc.IVOperand);
3350 assert(UseI != Inc.UserInst->op_end() && "cannot find IV operand");
3351 IVIncSet.insert(Ptr: UseI);
3352 }
3353}
3354
3355/// Return true if the IVInc can be folded into an addressing mode.
3356static bool canFoldIVIncExpr(const SCEV *IncExpr, Instruction *UserInst,
3357 Value *Operand, const TargetTransformInfo &TTI) {
3358 const SCEVConstant *IncConst = dyn_cast<SCEVConstant>(Val: IncExpr);
3359 Immediate IncOffset = Immediate::getZero();
3360 if (IncConst) {
3361 if (IncConst && IncConst->getAPInt().getSignificantBits() > 64)
3362 return false;
3363 IncOffset = Immediate::getFixed(MinVal: IncConst->getValue()->getSExtValue());
3364 } else {
3365 // Look for mul(vscale, constant), to detect a scalable offset.
3366 const APInt *C;
3367 if (!match(S: IncExpr, P: m_scev_Mul(Op0: m_scev_APInt(C), Op1: m_SCEVVScale())) ||
3368 C->getSignificantBits() > 64)
3369 return false;
3370 IncOffset = Immediate::getScalable(MinVal: C->getSExtValue());
3371 }
3372
3373 if (!isAddressUse(TTI, Inst: UserInst, OperandVal: Operand))
3374 return false;
3375
3376 MemAccessTy AccessTy = getAccessType(TTI, Inst: UserInst, OperandVal: Operand);
3377 if (!isAlwaysFoldable(TTI, Kind: LSRUse::Address, AccessTy, /*BaseGV=*/nullptr,
3378 BaseOffset: IncOffset, /*HasBaseReg=*/false))
3379 return false;
3380
3381 return true;
3382}
3383
3384/// Generate an add or subtract for each IVInc in a chain to materialize the IV
3385/// user's operand from the previous IV user's operand.
3386void LSRInstance::GenerateIVChain(const IVChain &Chain,
3387 SmallVectorImpl<WeakTrackingVH> &DeadInsts) {
3388 // Find the new IVOperand for the head of the chain. It may have been replaced
3389 // by LSR.
3390 const IVInc &Head = Chain.Incs[0];
3391 User::op_iterator IVOpEnd = Head.UserInst->op_end();
3392 // findIVOperand returns IVOpEnd if it can no longer find a valid IV user.
3393 User::op_iterator IVOpIter = findIVOperand(OI: Head.UserInst->op_begin(),
3394 OE: IVOpEnd, L, SE);
3395 Value *IVSrc = nullptr;
3396 while (IVOpIter != IVOpEnd) {
3397 IVSrc = getWideOperand(Oper: *IVOpIter);
3398
3399 // If this operand computes the expression that the chain needs, we may use
3400 // it. (Check this after setting IVSrc which is used below.)
3401 //
3402 // Note that if Head.IncExpr is wider than IVSrc, then this phi is too
3403 // narrow for the chain, so we can no longer use it. We do allow using a
3404 // wider phi, assuming the LSR checked for free truncation. In that case we
3405 // should already have a truncate on this operand such that
3406 // getSCEV(IVSrc) == IncExpr.
3407 if (SE.getSCEV(V: *IVOpIter) == Head.IncExpr
3408 || SE.getSCEV(V: IVSrc) == Head.IncExpr) {
3409 break;
3410 }
3411 IVOpIter = findIVOperand(OI: std::next(x: IVOpIter), OE: IVOpEnd, L, SE);
3412 }
3413 if (IVOpIter == IVOpEnd) {
3414 // Gracefully give up on this chain.
3415 LLVM_DEBUG(dbgs() << "Concealed chain head: " << *Head.UserInst << "\n");
3416 return;
3417 }
3418 assert(IVSrc && "Failed to find IV chain source");
3419
3420 LLVM_DEBUG(dbgs() << "Generate chain at: " << *IVSrc << "\n");
3421 Type *IVTy = IVSrc->getType();
3422 Type *IntTy = SE.getEffectiveSCEVType(Ty: IVTy);
3423 const SCEV *LeftOverExpr = nullptr;
3424 const SCEV *Accum = SE.getZero(Ty: IntTy);
3425 SmallVector<std::pair<const SCEV *, Value *>> Bases;
3426 Bases.emplace_back(Args&: Accum, Args&: IVSrc);
3427
3428 for (const IVInc &Inc : Chain) {
3429 Instruction *InsertPt = Inc.UserInst;
3430 if (isa<PHINode>(Val: InsertPt))
3431 InsertPt = L->getLoopLatch()->getTerminator();
3432
3433 // IVOper will replace the current IV User's operand. IVSrc is the IV
3434 // value currently held in a register.
3435 Value *IVOper = IVSrc;
3436 if (!Inc.IncExpr->isZero()) {
3437 // IncExpr was the result of subtraction of two narrow values, so must
3438 // be signed.
3439 const SCEV *IncExpr = SE.getNoopOrSignExtend(V: Inc.IncExpr, Ty: IntTy);
3440 Accum = SE.getAddExpr(LHS: Accum, RHS: IncExpr);
3441 LeftOverExpr = LeftOverExpr ?
3442 SE.getAddExpr(LHS: LeftOverExpr, RHS: IncExpr) : IncExpr;
3443 }
3444
3445 // Look through each base to see if any can produce a nice addressing mode.
3446 bool FoundBase = false;
3447 for (auto [MapScev, MapIVOper] : reverse(C&: Bases)) {
3448 const SCEV *Remainder = SE.getMinusSCEV(LHS: Accum, RHS: MapScev);
3449 if (canFoldIVIncExpr(IncExpr: Remainder, UserInst: Inc.UserInst, Operand: Inc.IVOperand, TTI)) {
3450 if (!Remainder->isZero()) {
3451 Rewriter.clearPostInc();
3452 Value *IncV = Rewriter.expandCodeFor(SH: Remainder, Ty: IntTy, I: InsertPt);
3453 const SCEV *IVOperExpr =
3454 SE.getAddExpr(LHS: SE.getUnknown(V: MapIVOper), RHS: SE.getUnknown(V: IncV));
3455 IVOper = Rewriter.expandCodeFor(SH: IVOperExpr, Ty: IVTy, I: InsertPt);
3456 } else {
3457 IVOper = MapIVOper;
3458 }
3459
3460 FoundBase = true;
3461 break;
3462 }
3463 }
3464 if (!FoundBase && LeftOverExpr && !LeftOverExpr->isZero()) {
3465 // Expand the IV increment.
3466 Rewriter.clearPostInc();
3467 Value *IncV = Rewriter.expandCodeFor(SH: LeftOverExpr, Ty: IntTy, I: InsertPt);
3468 const SCEV *IVOperExpr = SE.getAddExpr(LHS: SE.getUnknown(V: IVSrc),
3469 RHS: SE.getUnknown(V: IncV));
3470 IVOper = Rewriter.expandCodeFor(SH: IVOperExpr, Ty: IVTy, I: InsertPt);
3471
3472 // If an IV increment can't be folded, use it as the next IV value.
3473 if (!canFoldIVIncExpr(IncExpr: LeftOverExpr, UserInst: Inc.UserInst, Operand: Inc.IVOperand, TTI)) {
3474 assert(IVTy == IVOper->getType() && "inconsistent IV increment type");
3475 Bases.emplace_back(Args&: Accum, Args&: IVOper);
3476 IVSrc = IVOper;
3477 LeftOverExpr = nullptr;
3478 }
3479 }
3480 Type *OperTy = Inc.IVOperand->getType();
3481 if (IVTy != OperTy) {
3482 assert(SE.getTypeSizeInBits(IVTy) >= SE.getTypeSizeInBits(OperTy) &&
3483 "cannot extend a chained IV");
3484 IRBuilder<> Builder(InsertPt);
3485 IVOper = Builder.CreateTruncOrBitCast(V: IVOper, DestTy: OperTy, Name: "lsr.chain");
3486 }
3487 Inc.UserInst->replaceUsesOfWith(From: Inc.IVOperand, To: IVOper);
3488 if (auto *OperandIsInstr = dyn_cast<Instruction>(Val: Inc.IVOperand))
3489 DeadInsts.emplace_back(Args&: OperandIsInstr);
3490 }
3491 // If LSR created a new, wider phi, we may also replace its postinc. We only
3492 // do this if we also found a wide value for the head of the chain.
3493 if (isa<PHINode>(Val: Chain.tailUserInst())) {
3494 for (PHINode &Phi : L->getHeader()->phis()) {
3495 if (Phi.getType() != IVSrc->getType())
3496 continue;
3497 Instruction *PostIncV = dyn_cast<Instruction>(
3498 Val: Phi.getIncomingValueForBlock(BB: L->getLoopLatch()));
3499 if (!PostIncV || (SE.getSCEV(V: PostIncV) != SE.getSCEV(V: IVSrc)))
3500 continue;
3501 Value *IVOper = IVSrc;
3502 Type *PostIncTy = PostIncV->getType();
3503 if (IVTy != PostIncTy) {
3504 assert(PostIncTy->isPointerTy() && "mixing int/ptr IV types");
3505 IRBuilder<> Builder(L->getLoopLatch()->getTerminator());
3506 Builder.SetCurrentDebugLocation(PostIncV->getDebugLoc());
3507 IVOper = Builder.CreatePointerCast(V: IVSrc, DestTy: PostIncTy, Name: "lsr.chain");
3508 }
3509 Phi.replaceUsesOfWith(From: PostIncV, To: IVOper);
3510 DeadInsts.emplace_back(Args&: PostIncV);
3511 }
3512 }
3513}
3514
3515void LSRInstance::CollectFixupsAndInitialFormulae() {
3516 CondBrInst *ExitBranch = nullptr;
3517 bool SaveCmp = TTI.canSaveCmp(L, BI: &ExitBranch, SE: &SE, LI: &LI, DT: &DT, AC: &AC, LibInfo: &TLI);
3518
3519 // For calculating baseline cost
3520 SmallPtrSet<const SCEV *, 16> Regs;
3521 DenseSet<const SCEV *> VisitedRegs;
3522 DenseSet<size_t> VisitedLSRUse;
3523
3524 for (const IVStrideUse &U : IU) {
3525 Instruction *UserInst = U.getUser();
3526 // Skip IV users that are part of profitable IV Chains.
3527 User::op_iterator UseI =
3528 find(Range: UserInst->operands(), Val: U.getOperandValToReplace());
3529 assert(UseI != UserInst->op_end() && "cannot find IV operand");
3530 if (IVIncSet.count(Ptr: UseI)) {
3531 LLVM_DEBUG(dbgs() << "Use is in profitable chain: " << **UseI << '\n');
3532 continue;
3533 }
3534
3535 LSRUse::KindType Kind = LSRUse::Basic;
3536 MemAccessTy AccessTy;
3537 if (isAddressUse(TTI, Inst: UserInst, OperandVal: U.getOperandValToReplace())) {
3538 Kind = LSRUse::Address;
3539 AccessTy = getAccessType(TTI, Inst: UserInst, OperandVal: U.getOperandValToReplace());
3540 }
3541
3542 const SCEV *S = IU.getExpr(IU: U);
3543 if (!S)
3544 continue;
3545 PostIncLoopSet TmpPostIncLoops = U.getPostIncLoops();
3546
3547 // Equality (== and !=) ICmps are special. We can rewrite (i == N) as
3548 // (N - i == 0), and this allows (N - i) to be the expression that we work
3549 // with rather than just N or i, so we can consider the register
3550 // requirements for both N and i at the same time. Limiting this code to
3551 // equality icmps is not a problem because all interesting loops use
3552 // equality icmps, thanks to IndVarSimplify.
3553 if (ICmpInst *CI = dyn_cast<ICmpInst>(Val: UserInst)) {
3554 // If CI can be saved in some target, like replaced inside hardware loop
3555 // in PowerPC, no need to generate initial formulae for it.
3556 if (SaveCmp && CI == dyn_cast<ICmpInst>(Val: ExitBranch->getCondition()))
3557 continue;
3558 if (CI->isEquality()) {
3559 // Swap the operands if needed to put the OperandValToReplace on the
3560 // left, for consistency.
3561 Value *NV = CI->getOperand(i_nocapture: 1);
3562 if (NV == U.getOperandValToReplace()) {
3563 CI->setOperand(i_nocapture: 1, Val_nocapture: CI->getOperand(i_nocapture: 0));
3564 CI->setOperand(i_nocapture: 0, Val_nocapture: NV);
3565 NV = CI->getOperand(i_nocapture: 1);
3566 Changed = true;
3567 }
3568
3569 // x == y --> x - y == 0
3570 const SCEV *N = SE.getSCEV(V: NV);
3571 if (SE.isLoopInvariant(S: N, L) && Rewriter.isSafeToExpand(S: N) &&
3572 (!NV->getType()->isPointerTy() ||
3573 SE.getPointerBase(V: N) == SE.getPointerBase(V: S))) {
3574 // S is normalized, so normalize N before folding it into S
3575 // to keep the result normalized.
3576 N = normalizeForPostIncUse(S: N, Loops: TmpPostIncLoops, SE);
3577 if (!N)
3578 continue;
3579 Kind = LSRUse::ICmpZero;
3580 S = SE.getMinusSCEV(LHS: N, RHS: S);
3581 } else if (L->isLoopInvariant(V: NV) &&
3582 (!isa<Instruction>(Val: NV) ||
3583 DT.dominates(Def: cast<Instruction>(Val: NV), BB: L->getHeader())) &&
3584 !NV->getType()->isPointerTy()) {
3585 // If we can't generally expand the expression (e.g. it contains
3586 // a divide), but it is already at a loop invariant point before the
3587 // loop, wrap it in an unknown (to prevent the expander from trying
3588 // to re-expand in a potentially unsafe way.) The restriction to
3589 // integer types is required because the unknown hides the base, and
3590 // SCEV can't compute the difference of two unknown pointers.
3591 N = SE.getUnknown(V: NV);
3592 N = normalizeForPostIncUse(S: N, Loops: TmpPostIncLoops, SE);
3593 if (!N)
3594 continue;
3595 Kind = LSRUse::ICmpZero;
3596 S = SE.getMinusSCEV(LHS: N, RHS: S);
3597 assert(!isa<SCEVCouldNotCompute>(S));
3598 }
3599
3600 // -1 and the negations of all interesting strides (except the negation
3601 // of -1) are now also interesting.
3602 for (size_t i = 0, e = Factors.size(); i != e; ++i)
3603 if (Factors[i] != -1)
3604 Factors.insert(X: -(uint64_t)Factors[i]);
3605 Factors.insert(X: -1);
3606 }
3607 }
3608
3609 // Get or create an LSRUse.
3610 std::pair<size_t, Immediate> P = getUse(Expr&: S, Kind, AccessTy);
3611 size_t LUIdx = P.first;
3612 Immediate Offset = P.second;
3613 LSRUse &LU = Uses[LUIdx];
3614
3615 // Record the fixup.
3616 LSRFixup &LF = LU.getNewFixup();
3617 LF.UserInst = UserInst;
3618 LF.OperandValToReplace = U.getOperandValToReplace();
3619 LF.PostIncLoops = TmpPostIncLoops;
3620 LF.Offset = Offset;
3621 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
3622 LU.AllFixupsUnconditional &= IsFixupExecutedEachIncrement(LF);
3623
3624 // Create SCEV as Formula for calculating baseline cost
3625 if (!VisitedLSRUse.count(V: LUIdx) && !LF.isUseFullyOutsideLoop(L)) {
3626 Formula F;
3627 F.initialMatch(S, L, SE);
3628 BaselineCost.RateFormula(F, Regs, VisitedRegs, LU,
3629 HardwareLoopProfitable);
3630 VisitedLSRUse.insert(V: LUIdx);
3631 }
3632
3633 // If this is the first use of this LSRUse, give it a formula.
3634 if (LU.Formulae.empty()) {
3635 InsertInitialFormula(S, LU, LUIdx);
3636 CountRegisters(F: LU.Formulae.back(), LUIdx);
3637 }
3638 }
3639
3640 LLVM_DEBUG(print_fixups(dbgs()));
3641}
3642
3643/// Insert a formula for the given expression into the given use, separating out
3644/// loop-variant portions from loop-invariant and loop-computable portions.
3645void LSRInstance::InsertInitialFormula(const SCEV *S, LSRUse &LU,
3646 size_t LUIdx) {
3647 // Mark uses whose expressions cannot be expanded.
3648 if (!Rewriter.isSafeToExpand(S))
3649 LU.RigidFormula = true;
3650
3651 Formula F;
3652 F.initialMatch(S, L, SE);
3653 bool Inserted = InsertFormula(LU, LUIdx, F);
3654 assert(Inserted && "Initial formula already exists!"); (void)Inserted;
3655}
3656
3657/// Insert a simple single-register formula for the given expression into the
3658/// given use.
3659void
3660LSRInstance::InsertSupplementalFormula(const SCEV *S,
3661 LSRUse &LU, size_t LUIdx) {
3662 Formula F;
3663 F.BaseRegs.push_back(Elt: S);
3664 F.HasBaseReg = true;
3665 bool Inserted = InsertFormula(LU, LUIdx, F);
3666 assert(Inserted && "Supplemental formula already exists!"); (void)Inserted;
3667}
3668
3669/// Note which registers are used by the given formula, updating RegUses.
3670void LSRInstance::CountRegisters(const Formula &F, size_t LUIdx) {
3671 if (F.ScaledReg)
3672 RegUses.countRegister(Reg: F.ScaledReg, LUIdx);
3673 for (const SCEV *BaseReg : F.BaseRegs)
3674 RegUses.countRegister(Reg: BaseReg, LUIdx);
3675}
3676
3677/// If the given formula has not yet been inserted, add it to the list, and
3678/// return true. Return false otherwise.
3679bool LSRInstance::InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F) {
3680 // Do not insert formula that we will not be able to expand.
3681 assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F) &&
3682 "Formula is illegal");
3683
3684 if (!LU.InsertFormula(F, L: *L))
3685 return false;
3686
3687 CountRegisters(F, LUIdx);
3688 return true;
3689}
3690
3691/// Test whether this fixup will be executed each time the corresponding IV
3692/// increment instruction is executed.
3693bool LSRInstance::IsFixupExecutedEachIncrement(const LSRFixup &LF) const {
3694 // If the fixup block dominates the IV increment block then there is no path
3695 // through the loop to the increment that doesn't pass through the fixup.
3696 return DT.dominates(A: LF.UserInst->getParent(), B: IVIncInsertPos->getParent());
3697}
3698
3699/// Check for other uses of loop-invariant values which we're tracking. These
3700/// other uses will pin these values in registers, making them less profitable
3701/// for elimination.
3702/// TODO: This currently misses non-constant addrec step registers.
3703/// TODO: Should this give more weight to users inside the loop?
3704void
3705LSRInstance::CollectLoopInvariantFixupsAndFormulae() {
3706 SmallVector<const SCEV *, 8> Worklist(RegUses.begin(), RegUses.end());
3707 SmallPtrSet<const SCEV *, 32> Visited;
3708
3709 // Don't collect outside uses if we are favoring postinc - the instructions in
3710 // the loop are more important than the ones outside of it.
3711 if (AMK == TTI::AMK_PostIndexed)
3712 return;
3713
3714 while (!Worklist.empty()) {
3715 const SCEV *S = Worklist.pop_back_val();
3716
3717 // Don't process the same SCEV twice
3718 if (!Visited.insert(Ptr: S).second)
3719 continue;
3720
3721 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(Val: S))
3722 append_range(C&: Worklist, R: N->operands());
3723 else if (const SCEVIntegralCastExpr *C = dyn_cast<SCEVIntegralCastExpr>(Val: S))
3724 Worklist.push_back(Elt: C->getOperand());
3725 else if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(Val: S)) {
3726 Worklist.push_back(Elt: D->getLHS());
3727 Worklist.push_back(Elt: D->getRHS());
3728 } else if (const SCEVUnknown *US = dyn_cast<SCEVUnknown>(Val: S)) {
3729 const Value *V = US->getValue();
3730 if (const Instruction *Inst = dyn_cast<Instruction>(Val: V)) {
3731 // Look for instructions defined outside the loop.
3732 if (L->contains(Inst)) continue;
3733 } else if (isa<Constant>(Val: V))
3734 // Constants can be re-materialized.
3735 continue;
3736 for (const Use &U : V->uses()) {
3737 const Instruction *UserInst = dyn_cast<Instruction>(Val: U.getUser());
3738 // Ignore non-instructions.
3739 if (!UserInst)
3740 continue;
3741 // Don't bother if the instruction is an EHPad.
3742 if (UserInst->isEHPad())
3743 continue;
3744 // Ignore instructions in other functions (as can happen with
3745 // Constants).
3746 if (UserInst->getParent()->getParent() != L->getHeader()->getParent())
3747 continue;
3748 // Ignore instructions not dominated by the loop.
3749 const BasicBlock *UseBB = !isa<PHINode>(Val: UserInst) ?
3750 UserInst->getParent() :
3751 cast<PHINode>(Val: UserInst)->getIncomingBlock(
3752 i: PHINode::getIncomingValueNumForOperand(i: U.getOperandNo()));
3753 if (!DT.dominates(A: L->getHeader(), B: UseBB))
3754 continue;
3755 // Don't bother if the instruction is in a BB which ends in an EHPad.
3756 if (UseBB->getTerminator()->isEHPad())
3757 continue;
3758
3759 // Ignore cases in which the currently-examined value could come from
3760 // a basic block terminated with an EHPad. This checks all incoming
3761 // blocks of the phi node since it is possible that the same incoming
3762 // value comes from multiple basic blocks, only some of which may end
3763 // in an EHPad. If any of them do, a subsequent rewrite attempt by this
3764 // pass would try to insert instructions into an EHPad, hitting an
3765 // assertion.
3766 if (isa<PHINode>(Val: UserInst)) {
3767 const auto *PhiNode = cast<PHINode>(Val: UserInst);
3768 bool HasIncompatibleEHPTerminatedBlock = false;
3769 llvm::Value *ExpectedValue = U;
3770 for (unsigned int I = 0; I < PhiNode->getNumIncomingValues(); I++) {
3771 if (PhiNode->getIncomingValue(i: I) == ExpectedValue) {
3772 if (PhiNode->getIncomingBlock(i: I)->getTerminator()->isEHPad()) {
3773 HasIncompatibleEHPTerminatedBlock = true;
3774 break;
3775 }
3776 }
3777 }
3778 if (HasIncompatibleEHPTerminatedBlock) {
3779 continue;
3780 }
3781 }
3782
3783 // Don't bother rewriting PHIs in catchswitch blocks.
3784 if (isa<CatchSwitchInst>(Val: UserInst->getParent()->getTerminator()))
3785 continue;
3786 // Ignore uses which are part of other SCEV expressions, to avoid
3787 // analyzing them multiple times.
3788 if (SE.isSCEVable(Ty: UserInst->getType())) {
3789 const SCEV *UserS = SE.getSCEV(V: const_cast<Instruction *>(UserInst));
3790 // If the user is a no-op, look through to its uses.
3791 if (!isa<SCEVUnknown>(Val: UserS))
3792 continue;
3793 if (UserS == US) {
3794 Worklist.push_back(
3795 Elt: SE.getUnknown(V: const_cast<Instruction *>(UserInst)));
3796 continue;
3797 }
3798 }
3799 // Ignore icmp instructions which are already being analyzed.
3800 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Val: UserInst)) {
3801 unsigned OtherIdx = !U.getOperandNo();
3802 Value *OtherOp = ICI->getOperand(i_nocapture: OtherIdx);
3803 if (SE.hasComputableLoopEvolution(S: SE.getSCEV(V: OtherOp), L))
3804 continue;
3805 }
3806
3807 // Do not consider uses inside lifetime intrinsics. These are not
3808 // actually materialized.
3809 if (UserInst->isLifetimeStartOrEnd())
3810 continue;
3811
3812 std::pair<size_t, Immediate> P =
3813 getUse(Expr&: S, Kind: LSRUse::Basic, AccessTy: MemAccessTy());
3814 size_t LUIdx = P.first;
3815 Immediate Offset = P.second;
3816 LSRUse &LU = Uses[LUIdx];
3817 LSRFixup &LF = LU.getNewFixup();
3818 LF.UserInst = const_cast<Instruction *>(UserInst);
3819 LF.OperandValToReplace = U;
3820 LF.Offset = Offset;
3821 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
3822 LU.AllFixupsUnconditional &= IsFixupExecutedEachIncrement(LF);
3823 InsertSupplementalFormula(S: US, LU, LUIdx);
3824 CountRegisters(F: LU.Formulae.back(), LUIdx: Uses.size() - 1);
3825 break;
3826 }
3827 }
3828 }
3829}
3830
3831/// Split S into subexpressions which can be pulled out into separate
3832/// registers. If C is non-null, multiply each subexpression by C.
3833///
3834/// Return remainder expression after factoring the subexpressions captured by
3835/// Ops. If Ops is complete, return NULL.
3836static const SCEV *CollectSubexprs(const SCEV *S, const SCEVConstant *C,
3837 SmallVectorImpl<const SCEV *> &Ops,
3838 const Loop *L,
3839 ScalarEvolution &SE,
3840 unsigned Depth = 0) {
3841 // Arbitrarily cap recursion to protect compile time.
3842 if (Depth >= 3)
3843 return S;
3844
3845 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Val: S)) {
3846 // Break out add operands.
3847 for (const SCEV *S : Add->operands()) {
3848 const SCEV *Remainder = CollectSubexprs(S, C, Ops, L, SE, Depth: Depth+1);
3849 if (Remainder)
3850 Ops.push_back(Elt: C ? SE.getMulExpr(LHS: C, RHS: Remainder) : Remainder);
3851 }
3852 return nullptr;
3853 }
3854 const SCEV *Start, *Step;
3855 const SCEVConstant *Op0;
3856 const SCEV *Op1;
3857 if (match(S, P: m_scev_AffineAddRec(Op0: m_SCEV(V&: Start), Op1: m_SCEV(V&: Step)))) {
3858 // Split a non-zero base out of an addrec.
3859 if (Start->isZero())
3860 return S;
3861
3862 const SCEV *Remainder = CollectSubexprs(S: Start, C, Ops, L, SE, Depth: Depth + 1);
3863 // Split the non-zero AddRec unless it is part of a nested recurrence that
3864 // does not pertain to this loop.
3865 if (Remainder && (cast<SCEVAddRecExpr>(Val: S)->getLoop() == L ||
3866 !isa<SCEVAddRecExpr>(Val: Remainder))) {
3867 Ops.push_back(Elt: C ? SE.getMulExpr(LHS: C, RHS: Remainder) : Remainder);
3868 Remainder = nullptr;
3869 }
3870 if (Remainder != Start) {
3871 if (!Remainder)
3872 Remainder = SE.getConstant(Ty: S->getType(), V: 0);
3873 return SE.getAddRecExpr(Start: Remainder, Step,
3874 L: cast<SCEVAddRecExpr>(Val: S)->getLoop(),
3875 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
3876 Flags: SCEV::FlagAnyWrap);
3877 }
3878 } else if (match(S, P: m_scev_Mul(Op0: m_SCEVConstant(V&: Op0), Op1: m_SCEV(V&: Op1)))) {
3879 // Break (C * (a + b + c)) into C*a + C*b + C*c.
3880 C = C ? cast<SCEVConstant>(Val: SE.getMulExpr(LHS: C, RHS: Op0)) : Op0;
3881 const SCEV *Remainder = CollectSubexprs(S: Op1, C, Ops, L, SE, Depth: Depth + 1);
3882 if (Remainder)
3883 Ops.push_back(Elt: SE.getMulExpr(LHS: C, RHS: Remainder));
3884 return nullptr;
3885 }
3886 return S;
3887}
3888
3889/// Return true if the SCEV represents a value that may end up as a
3890/// post-increment operation.
3891static bool mayUsePostIncMode(const TargetTransformInfo &TTI,
3892 LSRUse &LU, const SCEV *S, const Loop *L,
3893 ScalarEvolution &SE) {
3894 if (LU.Kind != LSRUse::Address ||
3895 !LU.AccessTy.getType()->isIntOrIntVectorTy())
3896 return false;
3897 const SCEV *Start;
3898 if (!match(S, P: m_scev_AffineAddRec(Op0: m_SCEV(V&: Start), Op1: m_SCEVConstant())))
3899 return false;
3900 // Check if a post-indexed load/store can be used.
3901 if (TTI.isIndexedLoadLegal(Mode: TTI.MIM_PostInc, Ty: S->getType()) ||
3902 TTI.isIndexedStoreLegal(Mode: TTI.MIM_PostInc, Ty: S->getType())) {
3903 if (!isa<SCEVConstant>(Val: Start) && SE.isLoopInvariant(S: Start, L))
3904 return true;
3905 }
3906 return false;
3907}
3908
3909/// Helper function for LSRInstance::GenerateReassociations.
3910void LSRInstance::GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx,
3911 const Formula &Base,
3912 unsigned Depth, size_t Idx,
3913 bool IsScaledReg) {
3914 const SCEV *BaseReg = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
3915 // Don't generate reassociations for the base register of a value that
3916 // may generate a post-increment operator. The reason is that the
3917 // reassociations cause extra base+register formula to be created,
3918 // and possibly chosen, but the post-increment is more efficient.
3919 if (AMK == TTI::AMK_PostIndexed && mayUsePostIncMode(TTI, LU, S: BaseReg, L, SE))
3920 return;
3921 SmallVector<const SCEV *, 8> AddOps;
3922 const SCEV *Remainder = CollectSubexprs(S: BaseReg, C: nullptr, Ops&: AddOps, L, SE);
3923 if (Remainder)
3924 AddOps.push_back(Elt: Remainder);
3925
3926 if (AddOps.size() == 1)
3927 return;
3928
3929 for (SmallVectorImpl<const SCEV *>::const_iterator J = AddOps.begin(),
3930 JE = AddOps.end();
3931 J != JE; ++J) {
3932 // Loop-variant "unknown" values are uninteresting; we won't be able to
3933 // do anything meaningful with them.
3934 if (isa<SCEVUnknown>(Val: *J) && !SE.isLoopInvariant(S: *J, L))
3935 continue;
3936
3937 // Don't pull a constant into a register if the constant could be folded
3938 // into an immediate field.
3939 if (isAlwaysFoldable(TTI, SE, MinOffset: LU.MinOffset, MaxOffset: LU.MaxOffset, Kind: LU.Kind,
3940 AccessTy: LU.AccessTy, S: *J, HasBaseReg: Base.getNumRegs() > 1))
3941 continue;
3942
3943 // Collect all operands except *J.
3944 SmallVector<SCEVUse, 8> InnerAddOps(std::as_const(t&: AddOps).begin(), J);
3945 InnerAddOps.append(in_start: std::next(x: J), in_end: std::as_const(t&: AddOps).end());
3946
3947 // Don't leave just a constant behind in a register if the constant could
3948 // be folded into an immediate field.
3949 if (InnerAddOps.size() == 1 &&
3950 isAlwaysFoldable(TTI, SE, MinOffset: LU.MinOffset, MaxOffset: LU.MaxOffset, Kind: LU.Kind,
3951 AccessTy: LU.AccessTy, S: InnerAddOps[0], HasBaseReg: Base.getNumRegs() > 1))
3952 continue;
3953
3954 const SCEV *InnerSum = SE.getAddExpr(Ops&: InnerAddOps);
3955 if (InnerSum->isZero())
3956 continue;
3957 Formula F = Base;
3958
3959 if (F.UnfoldedOffset.isNonZero() && F.UnfoldedOffset.isScalable())
3960 continue;
3961
3962 // Add the remaining pieces of the add back into the new formula.
3963 const SCEVConstant *InnerSumSC = dyn_cast<SCEVConstant>(Val: InnerSum);
3964 if (InnerSumSC && SE.getTypeSizeInBits(Ty: InnerSumSC->getType()) <= 64 &&
3965 TTI.isLegalAddImmediate(Imm: (uint64_t)F.UnfoldedOffset.getFixedValue() +
3966 InnerSumSC->getValue()->getZExtValue())) {
3967 F.UnfoldedOffset =
3968 Immediate::getFixed(MinVal: (uint64_t)F.UnfoldedOffset.getFixedValue() +
3969 InnerSumSC->getValue()->getZExtValue());
3970 if (IsScaledReg) {
3971 F.ScaledReg = nullptr;
3972 F.Scale = 0;
3973 } else
3974 F.BaseRegs.erase(CI: F.BaseRegs.begin() + Idx);
3975 } else if (IsScaledReg)
3976 F.ScaledReg = InnerSum;
3977 else
3978 F.BaseRegs[Idx] = InnerSum;
3979
3980 // Add J as its own register, or an unfolded immediate.
3981 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Val: *J);
3982 if (SC && SE.getTypeSizeInBits(Ty: SC->getType()) <= 64 &&
3983 TTI.isLegalAddImmediate(Imm: (uint64_t)F.UnfoldedOffset.getFixedValue() +
3984 SC->getValue()->getZExtValue()))
3985 F.UnfoldedOffset =
3986 Immediate::getFixed(MinVal: (uint64_t)F.UnfoldedOffset.getFixedValue() +
3987 SC->getValue()->getZExtValue());
3988 else
3989 F.BaseRegs.push_back(Elt: *J);
3990 // We may have changed the number of register in base regs, adjust the
3991 // formula accordingly.
3992 F.canonicalize(L: *L);
3993
3994 if (InsertFormula(LU, LUIdx, F))
3995 // If that formula hadn't been seen before, recurse to find more like
3996 // it.
3997 // Add check on Log16(AddOps.size()) - same as Log2_32(AddOps.size()) >> 2)
3998 // Because just Depth is not enough to bound compile time.
3999 // This means that every time AddOps.size() is greater 16^x we will add
4000 // x to Depth.
4001 GenerateReassociations(LU, LUIdx, Base: LU.Formulae.back(),
4002 Depth: Depth + 1 + (Log2_32(Value: AddOps.size()) >> 2));
4003 }
4004}
4005
4006/// Split out subexpressions from adds and the bases of addrecs.
4007void LSRInstance::GenerateReassociations(LSRUse &LU, unsigned LUIdx,
4008 Formula Base, unsigned Depth) {
4009 assert(Base.isCanonical(*L) && "Input must be in the canonical form");
4010 // Arbitrarily cap recursion to protect compile time.
4011 if (Depth >= 3)
4012 return;
4013
4014 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
4015 GenerateReassociationsImpl(LU, LUIdx, Base, Depth, Idx: i);
4016
4017 if (Base.Scale == 1)
4018 GenerateReassociationsImpl(LU, LUIdx, Base, Depth,
4019 /* Idx */ -1, /* IsScaledReg */ true);
4020}
4021
4022/// Generate a formula consisting of all of the loop-dominating registers added
4023/// into a single register.
4024void LSRInstance::GenerateCombinations(LSRUse &LU, unsigned LUIdx,
4025 Formula Base) {
4026 // This method is only interesting on a plurality of registers.
4027 if (Base.BaseRegs.size() + (Base.Scale == 1) +
4028 (Base.UnfoldedOffset.isNonZero()) <=
4029 1)
4030 return;
4031
4032 // Flatten the representation, i.e., reg1 + 1*reg2 => reg1 + reg2, before
4033 // processing the formula.
4034 Base.unscale();
4035 SmallVector<SCEVUse, 4> Ops;
4036 Formula NewBase = Base;
4037 NewBase.BaseRegs.clear();
4038 Type *CombinedIntegerType = nullptr;
4039 for (const SCEV *BaseReg : Base.BaseRegs) {
4040 if (SE.properlyDominates(S: BaseReg, BB: L->getHeader()) &&
4041 !SE.hasComputableLoopEvolution(S: BaseReg, L)) {
4042 if (!CombinedIntegerType)
4043 CombinedIntegerType = SE.getEffectiveSCEVType(Ty: BaseReg->getType());
4044 Ops.push_back(Elt: BaseReg);
4045 }
4046 else
4047 NewBase.BaseRegs.push_back(Elt: BaseReg);
4048 }
4049
4050 // If no register is relevant, we're done.
4051 if (Ops.size() == 0)
4052 return;
4053
4054 // Utility function for generating the required variants of the combined
4055 // registers.
4056 auto GenerateFormula = [&](const SCEV *Sum) {
4057 Formula F = NewBase;
4058
4059 // TODO: If Sum is zero, it probably means ScalarEvolution missed an
4060 // opportunity to fold something. For now, just ignore such cases
4061 // rather than proceed with zero in a register.
4062 if (Sum->isZero())
4063 return;
4064
4065 F.BaseRegs.push_back(Elt: Sum);
4066 F.canonicalize(L: *L);
4067 (void)InsertFormula(LU, LUIdx, F);
4068 };
4069
4070 // If we collected at least two registers, generate a formula combining them.
4071 if (Ops.size() > 1) {
4072 SmallVector<SCEVUse, 4> OpsCopy(Ops); // Don't let SE modify Ops.
4073 GenerateFormula(SE.getAddExpr(Ops&: OpsCopy));
4074 }
4075
4076 // If we have an unfolded offset, generate a formula combining it with the
4077 // registers collected.
4078 if (NewBase.UnfoldedOffset.isNonZero() && NewBase.UnfoldedOffset.isFixed()) {
4079 assert(CombinedIntegerType && "Missing a type for the unfolded offset");
4080 Ops.push_back(Elt: SE.getConstant(Ty: CombinedIntegerType,
4081 V: NewBase.UnfoldedOffset.getFixedValue(), isSigned: true));
4082 NewBase.UnfoldedOffset = Immediate::getFixed(MinVal: 0);
4083 GenerateFormula(SE.getAddExpr(Ops));
4084 }
4085}
4086
4087/// Helper function for LSRInstance::GenerateSymbolicOffsets.
4088void LSRInstance::GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx,
4089 const Formula &Base, size_t Idx,
4090 bool IsScaledReg) {
4091 SCEVUse G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
4092 GlobalValue *GV = ExtractSymbol(S&: G, SE);
4093 if (G->isZero() || !GV)
4094 return;
4095 Formula F = Base;
4096 F.BaseGV = GV;
4097 if (!isLegalUse(TTI, MinOffset: LU.MinOffset, MaxOffset: LU.MaxOffset, Kind: LU.Kind, AccessTy: LU.AccessTy, F))
4098 return;
4099 if (IsScaledReg)
4100 F.ScaledReg = G;
4101 else
4102 F.BaseRegs[Idx] = G;
4103 (void)InsertFormula(LU, LUIdx, F);
4104}
4105
4106/// Generate reuse formulae using symbolic offsets.
4107void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx,
4108 Formula Base) {
4109 // We can't add a symbolic offset if the address already contains one.
4110 if (Base.BaseGV) return;
4111
4112 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
4113 GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, Idx: i);
4114 if (Base.Scale == 1)
4115 GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, /* Idx */ -1,
4116 /* IsScaledReg */ true);
4117}
4118
4119/// Helper function for LSRInstance::GenerateConstantOffsets.
4120void LSRInstance::GenerateConstantOffsetsImpl(
4121 LSRUse &LU, unsigned LUIdx, const Formula &Base,
4122 const SmallVectorImpl<Immediate> &Worklist, size_t Idx, bool IsScaledReg) {
4123
4124 auto GenerateOffset = [&](const SCEV *G, Immediate Offset) {
4125 Formula F = Base;
4126 if (!Base.BaseOffset.isCompatibleImmediate(Imm: Offset))
4127 return;
4128 F.BaseOffset = Base.BaseOffset.subUnsigned(RHS: Offset);
4129
4130 if (isLegalUse(TTI, MinOffset: LU.MinOffset, MaxOffset: LU.MaxOffset, Kind: LU.Kind, AccessTy: LU.AccessTy, F)) {
4131 // Add the offset to the base register.
4132 const SCEV *NewOffset = Offset.getSCEV(SE, Ty: G->getType());
4133 const SCEV *NewG = SE.getAddExpr(LHS: NewOffset, RHS: G);
4134 // If it cancelled out, drop the base register, otherwise update it.
4135 if (NewG->isZero()) {
4136 if (IsScaledReg) {
4137 F.Scale = 0;
4138 F.ScaledReg = nullptr;
4139 } else
4140 F.deleteBaseReg(S&: F.BaseRegs[Idx]);
4141 F.canonicalize(L: *L);
4142 } else if (IsScaledReg)
4143 F.ScaledReg = NewG;
4144 else
4145 F.BaseRegs[Idx] = NewG;
4146
4147 (void)InsertFormula(LU, LUIdx, F);
4148 }
4149 };
4150
4151 SCEVUse G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
4152
4153 // With constant offsets and constant steps, we can generate pre-inc
4154 // accesses by having the offset equal the step. So, for access #0 with a
4155 // step of 8, we generate a G - 8 base which would require the first access
4156 // to be ((G - 8) + 8),+,8. The pre-indexed access then updates the pointer
4157 // for itself and hopefully becomes the base for other accesses. This means
4158 // means that a single pre-indexed access can be generated to become the new
4159 // base pointer for each iteration of the loop, resulting in no extra add/sub
4160 // instructions for pointer updating.
4161 if ((AMK & TTI::AMK_PreIndexed) && LU.Kind == LSRUse::Address) {
4162 const APInt *StepInt;
4163 if (match(U: G, P: m_scev_AffineAddRec(Op0: m_SCEV(), Op1: m_scev_APInt(C&: StepInt)))) {
4164 int64_t Step = StepInt->isNegative() ? StepInt->getSExtValue()
4165 : StepInt->getZExtValue();
4166
4167 for (Immediate Offset : Worklist) {
4168 if (Offset.isFixed()) {
4169 Offset = Immediate::getFixed(MinVal: Offset.getFixedValue() - Step);
4170 GenerateOffset(G, Offset);
4171 }
4172 }
4173 }
4174 }
4175 for (Immediate Offset : Worklist)
4176 GenerateOffset(G, Offset);
4177
4178 Immediate Imm = ExtractImmediate(S&: G, SE);
4179 if (G->isZero() || Imm.isZero() ||
4180 !Base.BaseOffset.isCompatibleImmediate(Imm))
4181 return;
4182 Formula F = Base;
4183 F.BaseOffset = F.BaseOffset.addUnsigned(RHS: Imm);
4184 if (!isLegalUse(TTI, MinOffset: LU.MinOffset, MaxOffset: LU.MaxOffset, Kind: LU.Kind, AccessTy: LU.AccessTy, F))
4185 return;
4186 if (IsScaledReg) {
4187 F.ScaledReg = G;
4188 } else {
4189 F.BaseRegs[Idx] = G;
4190 // We may generate non canonical Formula if G is a recurrent expr reg
4191 // related with current loop while F.ScaledReg is not.
4192 F.canonicalize(L: *L);
4193 }
4194 (void)InsertFormula(LU, LUIdx, F);
4195}
4196
4197/// GenerateConstantOffsets - Generate reuse formulae using symbolic offsets.
4198void LSRInstance::GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx,
4199 Formula Base) {
4200 // TODO: For now, just add the min and max offset, because it usually isn't
4201 // worthwhile looking at everything inbetween.
4202 SmallVector<Immediate, 2> Worklist;
4203 Worklist.push_back(Elt: LU.MinOffset);
4204 if (LU.MaxOffset != LU.MinOffset)
4205 Worklist.push_back(Elt: LU.MaxOffset);
4206
4207 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
4208 GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, Idx: i);
4209 if (Base.Scale == 1)
4210 GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, /* Idx */ -1,
4211 /* IsScaledReg */ true);
4212}
4213
4214/// For ICmpZero, check to see if we can scale up the comparison. For example, x
4215/// == y -> x*c == y*c.
4216void LSRInstance::GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx,
4217 Formula Base) {
4218 if (LU.Kind != LSRUse::ICmpZero) return;
4219
4220 // Determine the integer type for the base formula.
4221 Type *IntTy = Base.getType();
4222 if (!IntTy) return;
4223 if (SE.getTypeSizeInBits(Ty: IntTy) > 64) return;
4224
4225 // Don't do this if there is more than one offset.
4226 if (LU.MinOffset != LU.MaxOffset) return;
4227
4228 // Check if transformation is valid. It is illegal to multiply pointer.
4229 if (Base.ScaledReg && Base.ScaledReg->getType()->isPointerTy())
4230 return;
4231 for (const SCEV *BaseReg : Base.BaseRegs)
4232 if (BaseReg->getType()->isPointerTy())
4233 return;
4234 assert(!Base.BaseGV && "ICmpZero use is not legal!");
4235
4236 // Check each interesting stride.
4237 for (int64_t Factor : Factors) {
4238 // Check that Factor can be represented by IntTy
4239 if (!ConstantInt::isValueValidForType(Ty: IntTy, V: Factor))
4240 continue;
4241 // Check that the multiplication doesn't overflow.
4242 if (Base.BaseOffset.isMin() && Factor == -1)
4243 continue;
4244 // Not supporting scalable immediates.
4245 if (Base.BaseOffset.isNonZero() && Base.BaseOffset.isScalable())
4246 continue;
4247 Immediate NewBaseOffset = Base.BaseOffset.mulUnsigned(RHS: Factor);
4248 assert(Factor != 0 && "Zero factor not expected!");
4249 if (NewBaseOffset.getFixedValue() / Factor !=
4250 Base.BaseOffset.getFixedValue())
4251 continue;
4252 // If the offset will be truncated at this use, check that it is in bounds.
4253 if (!IntTy->isPointerTy() &&
4254 !ConstantInt::isValueValidForType(Ty: IntTy, V: NewBaseOffset.getFixedValue()))
4255 continue;
4256
4257 // Check that multiplying with the use offset doesn't overflow.
4258 Immediate Offset = LU.MinOffset;
4259 if (Offset.isMin() && Factor == -1)
4260 continue;
4261 Offset = Offset.mulUnsigned(RHS: Factor);
4262 if (Offset.getFixedValue() / Factor != LU.MinOffset.getFixedValue())
4263 continue;
4264 // If the offset will be truncated at this use, check that it is in bounds.
4265 if (!IntTy->isPointerTy() &&
4266 !ConstantInt::isValueValidForType(Ty: IntTy, V: Offset.getFixedValue()))
4267 continue;
4268
4269 Formula F = Base;
4270 F.BaseOffset = NewBaseOffset;
4271
4272 // Check that this scale is legal.
4273 if (!isLegalUse(TTI, MinOffset: Offset, MaxOffset: Offset, Kind: LU.Kind, AccessTy: LU.AccessTy, F))
4274 continue;
4275
4276 // Compensate for the use having MinOffset built into it.
4277 F.BaseOffset = F.BaseOffset.addUnsigned(RHS: Offset).subUnsigned(RHS: LU.MinOffset);
4278
4279 const SCEV *FactorS = SE.getConstant(Ty: IntTy, V: Factor);
4280
4281 // Check that multiplying with each base register doesn't overflow.
4282 for (size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) {
4283 F.BaseRegs[i] = SE.getMulExpr(LHS: F.BaseRegs[i], RHS: FactorS);
4284 if (getExactSDiv(LHS: F.BaseRegs[i], RHS: FactorS, SE) != Base.BaseRegs[i])
4285 goto next;
4286 }
4287
4288 // Check that multiplying with the scaled register doesn't overflow.
4289 if (F.ScaledReg) {
4290 F.ScaledReg = SE.getMulExpr(LHS: F.ScaledReg, RHS: FactorS);
4291 if (getExactSDiv(LHS: F.ScaledReg, RHS: FactorS, SE) != Base.ScaledReg)
4292 continue;
4293 }
4294
4295 // Check that multiplying with the unfolded offset doesn't overflow.
4296 if (F.UnfoldedOffset.isNonZero()) {
4297 if (F.UnfoldedOffset.isMin() && Factor == -1)
4298 continue;
4299 F.UnfoldedOffset = F.UnfoldedOffset.mulUnsigned(RHS: Factor);
4300 if (F.UnfoldedOffset.getFixedValue() / Factor !=
4301 Base.UnfoldedOffset.getFixedValue())
4302 continue;
4303 // If the offset will be truncated, check that it is in bounds.
4304 if (!IntTy->isPointerTy() && !ConstantInt::isValueValidForType(
4305 Ty: IntTy, V: F.UnfoldedOffset.getFixedValue()))
4306 continue;
4307 }
4308
4309 // If we make it here and it's legal, add it.
4310 (void)InsertFormula(LU, LUIdx, F);
4311 next:;
4312 }
4313}
4314
4315/// Generate stride factor reuse formulae by making use of scaled-offset address
4316/// modes, for example.
4317void LSRInstance::GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base) {
4318 // Determine the integer type for the base formula.
4319 Type *IntTy = Base.getType();
4320 if (!IntTy) return;
4321
4322 // If this Formula already has a scaled register, we can't add another one.
4323 // Try to unscale the formula to generate a better scale.
4324 if (Base.Scale != 0 && !Base.unscale())
4325 return;
4326
4327 assert(Base.Scale == 0 && "unscale did not did its job!");
4328
4329 // Check each interesting stride.
4330 for (int64_t Factor : Factors) {
4331 Base.Scale = Factor;
4332 Base.HasBaseReg = Base.BaseRegs.size() > 1;
4333 // Check whether this scale is going to be legal.
4334 if (!isLegalUse(TTI, MinOffset: LU.MinOffset, MaxOffset: LU.MaxOffset, Kind: LU.Kind, AccessTy: LU.AccessTy,
4335 F: Base)) {
4336 // As a special-case, handle special out-of-loop Basic users specially.
4337 // TODO: Reconsider this special case.
4338 if (LU.Kind == LSRUse::Basic &&
4339 isLegalUse(TTI, MinOffset: LU.MinOffset, MaxOffset: LU.MaxOffset, Kind: LSRUse::Special,
4340 AccessTy: LU.AccessTy, F: Base) &&
4341 LU.AllFixupsOutsideLoop)
4342 LU.Kind = LSRUse::Special;
4343 else
4344 continue;
4345 }
4346 // For an ICmpZero, negating a solitary base register won't lead to
4347 // new solutions.
4348 if (LU.Kind == LSRUse::ICmpZero && !Base.HasBaseReg &&
4349 Base.BaseOffset.isZero() && !Base.BaseGV)
4350 continue;
4351 // For each addrec base reg, if its loop is current loop, apply the scale.
4352 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
4353 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Val: Base.BaseRegs[i]);
4354 if (AR && (AR->getLoop() == L || LU.AllFixupsOutsideLoop)) {
4355 const SCEV *FactorS = SE.getConstant(Ty: IntTy, V: Factor);
4356 if (FactorS->isZero())
4357 continue;
4358 // Divide out the factor, ignoring high bits, since we'll be
4359 // scaling the value back up in the end.
4360 if (const SCEV *Quotient = getExactSDiv(LHS: AR, RHS: FactorS, SE, IgnoreSignificantBits: true))
4361 if (!Quotient->isZero()) {
4362 // TODO: This could be optimized to avoid all the copying.
4363 Formula F = Base;
4364 F.ScaledReg = Quotient;
4365 F.deleteBaseReg(S&: F.BaseRegs[i]);
4366 // The canonical representation of 1*reg is reg, which is already in
4367 // Base. In that case, do not try to insert the formula, it will be
4368 // rejected anyway.
4369 if (F.Scale == 1 && (F.BaseRegs.empty() ||
4370 (AR->getLoop() != L && LU.AllFixupsOutsideLoop)))
4371 continue;
4372 // If AllFixupsOutsideLoop is true and F.Scale is 1, we may generate
4373 // non canonical Formula with ScaledReg's loop not being L.
4374 if (F.Scale == 1 && LU.AllFixupsOutsideLoop)
4375 F.canonicalize(L: *L);
4376 (void)InsertFormula(LU, LUIdx, F);
4377 }
4378 }
4379 }
4380 }
4381}
4382
4383/// Extend/Truncate \p Expr to \p ToTy considering post-inc uses in \p Loops.
4384/// For all PostIncLoopSets in \p Loops, first de-normalize \p Expr, then
4385/// perform the extension/truncate and normalize again, as the normalized form
4386/// can result in folds that are not valid in the post-inc use contexts. The
4387/// expressions for all PostIncLoopSets must match, otherwise return nullptr.
4388static const SCEV *
4389getAnyExtendConsideringPostIncUses(ArrayRef<PostIncLoopSet> Loops,
4390 const SCEV *Expr, Type *ToTy,
4391 ScalarEvolution &SE) {
4392 const SCEV *Result = nullptr;
4393 for (auto &L : Loops) {
4394 auto *DenormExpr = denormalizeForPostIncUse(S: Expr, Loops: L, SE);
4395 const SCEV *NewDenormExpr = SE.getAnyExtendExpr(Op: DenormExpr, Ty: ToTy);
4396 const SCEV *New = normalizeForPostIncUse(S: NewDenormExpr, Loops: L, SE);
4397 if (!New || (Result && New != Result))
4398 return nullptr;
4399 Result = New;
4400 }
4401
4402 assert(Result && "failed to create expression");
4403 return Result;
4404}
4405
4406/// Generate reuse formulae from different IV types.
4407void LSRInstance::GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base) {
4408 // Don't bother truncating symbolic values.
4409 if (Base.BaseGV) return;
4410
4411 // Determine the integer type for the base formula.
4412 Type *DstTy = Base.getType();
4413 if (!DstTy) return;
4414 if (DstTy->isPointerTy())
4415 return;
4416
4417 // It is invalid to extend a pointer type so exit early if ScaledReg or
4418 // any of the BaseRegs are pointers.
4419 if (Base.ScaledReg && Base.ScaledReg->getType()->isPointerTy())
4420 return;
4421 if (any_of(Range&: Base.BaseRegs,
4422 P: [](const SCEV *S) { return S->getType()->isPointerTy(); }))
4423 return;
4424
4425 SmallVector<PostIncLoopSet> Loops;
4426 for (auto &LF : LU.Fixups)
4427 Loops.push_back(Elt: LF.PostIncLoops);
4428
4429 for (Type *SrcTy : Types) {
4430 if (SrcTy != DstTy && TTI.isTruncateFree(Ty1: SrcTy, Ty2: DstTy)) {
4431 Formula F = Base;
4432
4433 // Sometimes SCEV is able to prove zero during ext transform. It may
4434 // happen if SCEV did not do all possible transforms while creating the
4435 // initial node (maybe due to depth limitations), but it can do them while
4436 // taking ext.
4437 if (F.ScaledReg) {
4438 const SCEV *NewScaledReg =
4439 getAnyExtendConsideringPostIncUses(Loops, Expr: F.ScaledReg, ToTy: SrcTy, SE);
4440 if (!NewScaledReg || NewScaledReg->isZero())
4441 continue;
4442 F.ScaledReg = NewScaledReg;
4443 }
4444 bool HasZeroBaseReg = false;
4445 for (const SCEV *&BaseReg : F.BaseRegs) {
4446 const SCEV *NewBaseReg =
4447 getAnyExtendConsideringPostIncUses(Loops, Expr: BaseReg, ToTy: SrcTy, SE);
4448 if (!NewBaseReg || NewBaseReg->isZero()) {
4449 HasZeroBaseReg = true;
4450 break;
4451 }
4452 BaseReg = NewBaseReg;
4453 }
4454 if (HasZeroBaseReg)
4455 continue;
4456
4457 // TODO: This assumes we've done basic processing on all uses and
4458 // have an idea what the register usage is.
4459 if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses))
4460 continue;
4461
4462 F.canonicalize(L: *L);
4463 (void)InsertFormula(LU, LUIdx, F);
4464 }
4465 }
4466}
4467
4468namespace {
4469
4470/// Helper class for GenerateCrossUseConstantOffsets. It's used to defer
4471/// modifications so that the search phase doesn't have to worry about the data
4472/// structures moving underneath it.
4473struct WorkItem {
4474 size_t LUIdx;
4475 Immediate Imm;
4476 const SCEV *OrigReg;
4477
4478 WorkItem(size_t LI, Immediate I, const SCEV *R)
4479 : LUIdx(LI), Imm(I), OrigReg(R) {}
4480
4481 void print(raw_ostream &OS) const;
4482 void dump() const;
4483};
4484
4485} // end anonymous namespace
4486
4487#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4488void WorkItem::print(raw_ostream &OS) const {
4489 OS << "in formulae referencing " << *OrigReg << " in use " << LUIdx
4490 << " , add offset " << Imm;
4491}
4492
4493LLVM_DUMP_METHOD void WorkItem::dump() const {
4494 print(errs()); errs() << '\n';
4495}
4496#endif
4497
4498/// Look for registers which are a constant distance apart and try to form reuse
4499/// opportunities between them.
4500void LSRInstance::GenerateCrossUseConstantOffsets() {
4501 // Group the registers by their value without any added constant offset.
4502 using ImmMapTy = std::map<Immediate, const SCEV *, KeyOrderTargetImmediate>;
4503
4504 DenseMap<const SCEV *, ImmMapTy> Map;
4505 DenseMap<const SCEV *, SmallBitVector> UsedByIndicesMap;
4506 SmallVector<const SCEV *, 8> Sequence;
4507 for (const SCEV *Use : RegUses) {
4508 SCEVUse Reg = Use; // Make a copy for ExtractImmediate to modify.
4509 Immediate Imm = ExtractImmediate(S&: Reg, SE);
4510 auto Pair = Map.try_emplace(Key: Reg);
4511 if (Pair.second)
4512 Sequence.push_back(Elt: Reg);
4513 Pair.first->second.insert(x: std::make_pair(x&: Imm, y&: Use));
4514 UsedByIndicesMap[Reg] |= RegUses.getUsedByIndices(Reg: Use);
4515 }
4516
4517 // Now examine each set of registers with the same base value. Build up
4518 // a list of work to do and do the work in a separate step so that we're
4519 // not adding formulae and register counts while we're searching.
4520 SmallVector<WorkItem, 32> WorkItems;
4521 SmallSet<std::pair<size_t, Immediate>, 32, KeyOrderSizeTAndImmediate>
4522 UniqueItems;
4523 for (const SCEV *Reg : Sequence) {
4524 const ImmMapTy &Imms = Map.find(Val: Reg)->second;
4525
4526 // It's not worthwhile looking for reuse if there's only one offset.
4527 if (Imms.size() == 1)
4528 continue;
4529
4530 LLVM_DEBUG(dbgs() << "Generating cross-use offsets for " << *Reg << ':';
4531 for (const auto &Entry
4532 : Imms) dbgs()
4533 << ' ' << Entry.first;
4534 dbgs() << '\n');
4535
4536 // Examine each offset.
4537 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
4538 J != JE; ++J) {
4539 const SCEV *OrigReg = J->second;
4540
4541 Immediate JImm = J->first;
4542 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(Reg: OrigReg);
4543
4544 if (!isa<SCEVConstant>(Val: OrigReg) &&
4545 UsedByIndicesMap[Reg].count() == 1) {
4546 LLVM_DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg
4547 << '\n');
4548 continue;
4549 }
4550
4551 // Conservatively examine offsets between this orig reg a few selected
4552 // other orig regs.
4553 Immediate First = Imms.begin()->first;
4554 Immediate Last = std::prev(x: Imms.end())->first;
4555 if (!First.isCompatibleImmediate(Imm: Last)) {
4556 LLVM_DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg
4557 << "\n");
4558 continue;
4559 }
4560 // Only scalable if both terms are scalable, or if one is scalable and
4561 // the other is 0.
4562 bool Scalable = First.isScalable() || Last.isScalable();
4563 int64_t FI = First.getKnownMinValue();
4564 int64_t LI = Last.getKnownMinValue();
4565 // Compute (First + Last) / 2 without overflow using the fact that
4566 // First + Last = 2 * (First + Last) + (First ^ Last).
4567 int64_t Avg = (FI & LI) + ((FI ^ LI) >> 1);
4568 // If the result is negative and FI is odd and LI even (or vice versa),
4569 // we rounded towards -inf. Add 1 in that case, to round towards 0.
4570 Avg = Avg + ((FI ^ LI) & ((uint64_t)Avg >> 63));
4571 ImmMapTy::const_iterator OtherImms[] = {
4572 Imms.begin(), std::prev(x: Imms.end()),
4573 Imms.lower_bound(x: Immediate::get(MinVal: Avg, Scalable))};
4574 for (const auto &M : OtherImms) {
4575 if (M == J || M == JE) continue;
4576 if (!JImm.isCompatibleImmediate(Imm: M->first))
4577 continue;
4578
4579 // Compute the difference between the two.
4580 Immediate Imm = JImm.subUnsigned(RHS: M->first);
4581 for (unsigned LUIdx : UsedByIndices.set_bits())
4582 // Make a memo of this use, offset, and register tuple.
4583 if (UniqueItems.insert(V: std::make_pair(x&: LUIdx, y&: Imm)).second)
4584 WorkItems.push_back(Elt: WorkItem(LUIdx, Imm, OrigReg));
4585 }
4586 }
4587 }
4588
4589 Map.clear();
4590 Sequence.clear();
4591 UsedByIndicesMap.clear();
4592 UniqueItems.clear();
4593
4594 // Now iterate through the worklist and add new formulae.
4595 for (const WorkItem &WI : WorkItems) {
4596 size_t LUIdx = WI.LUIdx;
4597 LSRUse &LU = Uses[LUIdx];
4598 Immediate Imm = WI.Imm;
4599 const SCEV *OrigReg = WI.OrigReg;
4600
4601 Type *IntTy = SE.getEffectiveSCEVType(Ty: OrigReg->getType());
4602 const SCEV *NegImmS = Imm.getNegativeSCEV(SE, Ty: IntTy);
4603 unsigned BitWidth = SE.getTypeSizeInBits(Ty: IntTy);
4604
4605 // TODO: Use a more targeted data structure.
4606 for (size_t L = 0, LE = LU.Formulae.size(); L != LE; ++L) {
4607 Formula F = LU.Formulae[L];
4608 // FIXME: The code for the scaled and unscaled registers looks
4609 // very similar but slightly different. Investigate if they
4610 // could be merged. That way, we would not have to unscale the
4611 // Formula.
4612 F.unscale();
4613 // Use the immediate in the scaled register.
4614 if (F.ScaledReg == OrigReg) {
4615 if (!F.BaseOffset.isCompatibleImmediate(Imm))
4616 continue;
4617 Immediate Offset = F.BaseOffset.addUnsigned(RHS: Imm.mulUnsigned(RHS: F.Scale));
4618 // Don't create 50 + reg(-50).
4619 const SCEV *S = Offset.getNegativeSCEV(SE, Ty: IntTy);
4620 if (F.referencesReg(S))
4621 continue;
4622 Formula NewF = F;
4623 NewF.BaseOffset = Offset;
4624 if (!isLegalUse(TTI, MinOffset: LU.MinOffset, MaxOffset: LU.MaxOffset, Kind: LU.Kind, AccessTy: LU.AccessTy,
4625 F: NewF))
4626 continue;
4627 NewF.ScaledReg = SE.getAddExpr(LHS: NegImmS, RHS: NewF.ScaledReg);
4628
4629 // If the new scale is a constant in a register, and adding the constant
4630 // value to the immediate would produce a value closer to zero than the
4631 // immediate itself, then the formula isn't worthwhile.
4632 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Val: NewF.ScaledReg)) {
4633 // FIXME: Do we need to do something for scalable immediates here?
4634 // A scalable SCEV won't be constant, but we might still have
4635 // something in the offset? Bail out for now to be safe.
4636 if (NewF.BaseOffset.isNonZero() && NewF.BaseOffset.isScalable())
4637 continue;
4638 if (C->getValue()->isNegative() !=
4639 (NewF.BaseOffset.isLessThanZero()) &&
4640 (C->getAPInt().abs() * APInt(BitWidth, F.Scale))
4641 .ule(RHS: std::abs(i: NewF.BaseOffset.getFixedValue())))
4642 continue;
4643 }
4644
4645 // OK, looks good.
4646 NewF.canonicalize(L: *this->L);
4647 (void)InsertFormula(LU, LUIdx, F: NewF);
4648 } else {
4649 // Use the immediate in a base register.
4650 for (size_t N = 0, NE = F.BaseRegs.size(); N != NE; ++N) {
4651 const SCEV *BaseReg = F.BaseRegs[N];
4652 if (BaseReg != OrigReg)
4653 continue;
4654 Formula NewF = F;
4655 if (!NewF.BaseOffset.isCompatibleImmediate(Imm) ||
4656 !NewF.UnfoldedOffset.isCompatibleImmediate(Imm) ||
4657 !NewF.BaseOffset.isCompatibleImmediate(Imm: NewF.UnfoldedOffset))
4658 continue;
4659 NewF.BaseOffset = NewF.BaseOffset.addUnsigned(RHS: Imm);
4660 if (!isLegalUse(TTI, MinOffset: LU.MinOffset, MaxOffset: LU.MaxOffset,
4661 Kind: LU.Kind, AccessTy: LU.AccessTy, F: NewF)) {
4662 if (AMK == TTI::AMK_PostIndexed &&
4663 mayUsePostIncMode(TTI, LU, S: OrigReg, L: this->L, SE))
4664 continue;
4665 Immediate NewUnfoldedOffset = NewF.UnfoldedOffset.addUnsigned(RHS: Imm);
4666 if (!isLegalAddImmediate(TTI, Offset: NewUnfoldedOffset))
4667 continue;
4668 NewF = F;
4669 NewF.UnfoldedOffset = NewUnfoldedOffset;
4670 }
4671 NewF.BaseRegs[N] = SE.getAddExpr(LHS: NegImmS, RHS: BaseReg);
4672
4673 // If the new formula has a constant in a register, and adding the
4674 // constant value to the immediate would produce a value closer to
4675 // zero than the immediate itself, then the formula isn't worthwhile.
4676 for (const SCEV *NewReg : NewF.BaseRegs)
4677 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Val: NewReg)) {
4678 if (NewF.BaseOffset.isNonZero() && NewF.BaseOffset.isScalable())
4679 goto skip_formula;
4680 if ((C->getAPInt() + NewF.BaseOffset.getFixedValue())
4681 .abs()
4682 .slt(RHS: std::abs(i: NewF.BaseOffset.getFixedValue())) &&
4683 (C->getAPInt() + NewF.BaseOffset.getFixedValue())
4684 .countr_zero() >=
4685 (unsigned)llvm::countr_zero<uint64_t>(
4686 Val: NewF.BaseOffset.getFixedValue()))
4687 goto skip_formula;
4688 }
4689
4690 // Ok, looks good.
4691 NewF.canonicalize(L: *this->L);
4692 (void)InsertFormula(LU, LUIdx, F: NewF);
4693 break;
4694 skip_formula:;
4695 }
4696 }
4697 }
4698 }
4699}
4700
4701/// Generate formulae for each use.
4702void
4703LSRInstance::GenerateAllReuseFormulae() {
4704 // This is split into multiple loops so that hasRegsUsedByUsesOtherThan
4705 // queries are more precise.
4706 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4707 LSRUse &LU = Uses[LUIdx];
4708 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4709 GenerateReassociations(LU, LUIdx, Base: LU.Formulae[i]);
4710 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4711 GenerateCombinations(LU, LUIdx, Base: LU.Formulae[i]);
4712 }
4713 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4714 LSRUse &LU = Uses[LUIdx];
4715 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4716 GenerateSymbolicOffsets(LU, LUIdx, Base: LU.Formulae[i]);
4717 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4718 GenerateConstantOffsets(LU, LUIdx, Base: LU.Formulae[i]);
4719 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4720 GenerateICmpZeroScales(LU, LUIdx, Base: LU.Formulae[i]);
4721 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4722 GenerateScales(LU, LUIdx, Base: LU.Formulae[i]);
4723 }
4724 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4725 LSRUse &LU = Uses[LUIdx];
4726 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4727 GenerateTruncates(LU, LUIdx, Base: LU.Formulae[i]);
4728 }
4729
4730 GenerateCrossUseConstantOffsets();
4731
4732 LLVM_DEBUG(dbgs() << "\n"
4733 "After generating reuse formulae:\n";
4734 print_uses(dbgs()));
4735}
4736
4737/// If there are multiple formulae with the same set of registers used
4738/// by other uses, pick the best one and delete the others.
4739void LSRInstance::FilterOutUndesirableDedicatedRegisters() {
4740 DenseSet<const SCEV *> VisitedRegs;
4741 SmallPtrSet<const SCEV *, 16> Regs;
4742 SmallPtrSet<const SCEV *, 16> LoserRegs;
4743#ifndef NDEBUG
4744 bool ChangedFormulae = false;
4745#endif
4746
4747 // Collect the best formula for each unique set of shared registers. This
4748 // is reset for each use.
4749 using BestFormulaeTy = DenseMap<SmallVector<const SCEV *, 4>, size_t>;
4750
4751 BestFormulaeTy BestFormulae;
4752
4753 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4754 LSRUse &LU = Uses[LUIdx];
4755 LLVM_DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs());
4756 dbgs() << '\n');
4757
4758 bool Any = false;
4759 for (size_t FIdx = 0, NumForms = LU.Formulae.size();
4760 FIdx != NumForms; ++FIdx) {
4761 Formula &F = LU.Formulae[FIdx];
4762
4763 // Some formulas are instant losers. For example, they may depend on
4764 // nonexistent AddRecs from other loops. These need to be filtered
4765 // immediately, otherwise heuristics could choose them over others leading
4766 // to an unsatisfactory solution. Passing LoserRegs into RateFormula here
4767 // avoids the need to recompute this information across formulae using the
4768 // same bad AddRec. Passing LoserRegs is also essential unless we remove
4769 // the corresponding bad register from the Regs set.
4770 Cost CostF(L, SE, TTI, AMK);
4771 Regs.clear();
4772 CostF.RateFormula(F, Regs, VisitedRegs, LU, HardwareLoopProfitable,
4773 LoserRegs: &LoserRegs);
4774 if (CostF.isLoser()) {
4775 // During initial formula generation, undesirable formulae are generated
4776 // by uses within other loops that have some non-trivial address mode or
4777 // use the postinc form of the IV. LSR needs to provide these formulae
4778 // as the basis of rediscovering the desired formula that uses an AddRec
4779 // corresponding to the existing phi. Once all formulae have been
4780 // generated, these initial losers may be pruned.
4781 LLVM_DEBUG(dbgs() << " Filtering loser "; F.print(dbgs());
4782 dbgs() << "\n");
4783 }
4784 else {
4785 SmallVector<const SCEV *, 4> Key;
4786 for (const SCEV *Reg : F.BaseRegs) {
4787 if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx))
4788 Key.push_back(Elt: Reg);
4789 }
4790 if (F.ScaledReg &&
4791 RegUses.isRegUsedByUsesOtherThan(Reg: F.ScaledReg, LUIdx))
4792 Key.push_back(Elt: F.ScaledReg);
4793 // Unstable sort by host order ok, because this is only used for
4794 // uniquifying.
4795 llvm::sort(C&: Key);
4796
4797 std::pair<BestFormulaeTy::const_iterator, bool> P =
4798 BestFormulae.insert(KV: std::make_pair(x&: Key, y&: FIdx));
4799 if (P.second)
4800 continue;
4801
4802 Formula &Best = LU.Formulae[P.first->second];
4803
4804 Cost CostBest(L, SE, TTI, AMK);
4805 Regs.clear();
4806 CostBest.RateFormula(F: Best, Regs, VisitedRegs, LU,
4807 HardwareLoopProfitable);
4808 if (CostF.isLess(Other: CostBest))
4809 std::swap(a&: F, b&: Best);
4810 LLVM_DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs());
4811 dbgs() << "\n"
4812 " in favor of formula ";
4813 Best.print(dbgs()); dbgs() << '\n');
4814 }
4815#ifndef NDEBUG
4816 ChangedFormulae = true;
4817#endif
4818 LU.DeleteFormula(F);
4819 --FIdx;
4820 --NumForms;
4821 Any = true;
4822 }
4823
4824 // Now that we've filtered out some formulae, recompute the Regs set.
4825 if (Any)
4826 LU.RecomputeRegs(LUIdx, RegUses);
4827
4828 // Reset this to prepare for the next use.
4829 BestFormulae.clear();
4830 }
4831
4832 LLVM_DEBUG(if (ChangedFormulae) {
4833 dbgs() << "\n"
4834 "After filtering out undesirable candidates:\n";
4835 print_uses(dbgs());
4836 });
4837}
4838
4839/// Estimate the worst-case number of solutions the solver might have to
4840/// consider. It almost never considers this many solutions because it prune the
4841/// search space, but the pruning isn't always sufficient.
4842size_t LSRInstance::EstimateSearchSpaceComplexity() const {
4843 size_t Power = 1;
4844 for (const LSRUse &LU : Uses) {
4845 size_t FSize = LU.Formulae.size();
4846 if (FSize >= ComplexityLimit) {
4847 Power = ComplexityLimit;
4848 break;
4849 }
4850 Power *= FSize;
4851 if (Power >= ComplexityLimit)
4852 break;
4853 }
4854 return Power;
4855}
4856
4857/// When one formula uses a superset of the registers of another formula, it
4858/// won't help reduce register pressure (though it may not necessarily hurt
4859/// register pressure); remove it to simplify the system.
4860void LSRInstance::NarrowSearchSpaceByDetectingSupersets() {
4861 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
4862 LLVM_DEBUG(dbgs() << "The search space is too complex.\n");
4863
4864 LLVM_DEBUG(dbgs() << "Narrowing the search space by eliminating formulae "
4865 "which use a superset of registers used by other "
4866 "formulae.\n");
4867
4868 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4869 LSRUse &LU = Uses[LUIdx];
4870 bool Any = false;
4871 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
4872 Formula &F = LU.Formulae[i];
4873 if (F.BaseOffset.isNonZero() && F.BaseOffset.isScalable())
4874 continue;
4875 // Look for a formula with a constant or GV in a register. If the use
4876 // also has a formula with that same value in an immediate field,
4877 // delete the one that uses a register.
4878 for (SmallVectorImpl<const SCEV *>::const_iterator
4879 I = F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I) {
4880 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Val: *I)) {
4881 Formula NewF = F;
4882 //FIXME: Formulas should store bitwidth to do wrapping properly.
4883 // See PR41034.
4884 NewF.BaseOffset =
4885 Immediate::getFixed(MinVal: NewF.BaseOffset.getFixedValue() +
4886 (uint64_t)C->getValue()->getSExtValue());
4887 NewF.BaseRegs.erase(CI: NewF.BaseRegs.begin() +
4888 (I - F.BaseRegs.begin()));
4889 if (LU.HasFormulaWithSameRegs(F: NewF)) {
4890 LLVM_DEBUG(dbgs() << " Deleting "; F.print(dbgs());
4891 dbgs() << '\n');
4892 LU.DeleteFormula(F);
4893 --i;
4894 --e;
4895 Any = true;
4896 break;
4897 }
4898 } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Val: *I)) {
4899 if (GlobalValue *GV = dyn_cast<GlobalValue>(Val: U->getValue()))
4900 if (!F.BaseGV) {
4901 Formula NewF = F;
4902 NewF.BaseGV = GV;
4903 NewF.BaseRegs.erase(CI: NewF.BaseRegs.begin() +
4904 (I - F.BaseRegs.begin()));
4905 if (LU.HasFormulaWithSameRegs(F: NewF)) {
4906 LLVM_DEBUG(dbgs() << " Deleting "; F.print(dbgs());
4907 dbgs() << '\n');
4908 LU.DeleteFormula(F);
4909 --i;
4910 --e;
4911 Any = true;
4912 break;
4913 }
4914 }
4915 }
4916 }
4917 }
4918 if (Any)
4919 LU.RecomputeRegs(LUIdx, RegUses);
4920 }
4921
4922 LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
4923 }
4924}
4925
4926/// When there are many registers for expressions like A, A+1, A+2, etc.,
4927/// allocate a single register for them.
4928void LSRInstance::NarrowSearchSpaceByCollapsingUnrolledCode() {
4929 if (EstimateSearchSpaceComplexity() < ComplexityLimit)
4930 return;
4931
4932 LLVM_DEBUG(
4933 dbgs() << "The search space is too complex.\n"
4934 "Narrowing the search space by assuming that uses separated "
4935 "by a constant offset will use the same registers.\n");
4936
4937 // This is especially useful for unrolled loops.
4938
4939 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4940 LSRUse &LU = Uses[LUIdx];
4941 for (const Formula &F : LU.Formulae) {
4942 if (F.BaseOffset.isZero() || (F.Scale != 0 && F.Scale != 1))
4943 continue;
4944 assert((LU.Kind == LSRUse::Address || LU.Kind == LSRUse::ICmpZero) &&
4945 "Only address and cmp uses expected to have nonzero BaseOffset");
4946
4947 LSRUse *LUThatHas = FindUseWithSimilarFormula(OrigF: F, OrigLU: LU);
4948 if (!LUThatHas)
4949 continue;
4950
4951 if (!reconcileNewOffset(LU&: *LUThatHas, NewOffset: F.BaseOffset, /*HasBaseReg=*/ false,
4952 Kind: LU.Kind, AccessTy: LU.AccessTy))
4953 continue;
4954
4955 LLVM_DEBUG(dbgs() << " Deleting use "; LU.print(dbgs()); dbgs() << '\n');
4956
4957 LUThatHas->AllFixupsOutsideLoop &= LU.AllFixupsOutsideLoop;
4958 LUThatHas->AllFixupsUnconditional &= LU.AllFixupsUnconditional;
4959
4960 // Transfer the fixups of LU to LUThatHas.
4961 for (LSRFixup &Fixup : LU.Fixups) {
4962 Fixup.Offset += F.BaseOffset;
4963 LUThatHas->pushFixup(f&: Fixup);
4964 LLVM_DEBUG(dbgs() << "New fixup has offset " << Fixup.Offset << '\n');
4965 }
4966
4967#ifndef NDEBUG
4968 Type *FixupType = LUThatHas->Fixups[0].OperandValToReplace->getType();
4969 for (LSRFixup &Fixup : LUThatHas->Fixups)
4970 assert(Fixup.OperandValToReplace->getType() == FixupType &&
4971 "Expected all fixups to have the same type");
4972#endif
4973
4974 // Delete formulae from the new use which are no longer legal.
4975 bool Any = false;
4976 for (size_t i = 0, e = LUThatHas->Formulae.size(); i != e; ++i) {
4977 Formula &F = LUThatHas->Formulae[i];
4978 if (!isLegalUse(TTI, MinOffset: LUThatHas->MinOffset, MaxOffset: LUThatHas->MaxOffset,
4979 Kind: LUThatHas->Kind, AccessTy: LUThatHas->AccessTy, F)) {
4980 LLVM_DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
4981 LUThatHas->DeleteFormula(F);
4982 --i;
4983 --e;
4984 Any = true;
4985 }
4986 }
4987
4988 if (Any)
4989 LUThatHas->RecomputeRegs(LUIdx: LUThatHas - &Uses.front(), RegUses);
4990
4991 // Delete the old use.
4992 DeleteUse(LU, LUIdx);
4993 --LUIdx;
4994 --NumUses;
4995 break;
4996 }
4997 }
4998
4999 LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
5000}
5001
5002/// Call FilterOutUndesirableDedicatedRegisters again, if necessary, now that
5003/// we've done more filtering, as it may be able to find more formulae to
5004/// eliminate.
5005void LSRInstance::NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters(){
5006 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
5007 LLVM_DEBUG(dbgs() << "The search space is too complex.\n");
5008
5009 LLVM_DEBUG(dbgs() << "Narrowing the search space by re-filtering out "
5010 "undesirable dedicated registers.\n");
5011
5012 FilterOutUndesirableDedicatedRegisters();
5013
5014 LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
5015 }
5016}
5017
5018/// If a LSRUse has multiple formulae with the same ScaledReg and Scale.
5019/// Pick the best one and delete the others.
5020/// This narrowing heuristic is to keep as many formulae with different
5021/// Scale and ScaledReg pair as possible while narrowing the search space.
5022/// The benefit is that it is more likely to find out a better solution
5023/// from a formulae set with more Scale and ScaledReg variations than
5024/// a formulae set with the same Scale and ScaledReg. The picking winner
5025/// reg heuristic will often keep the formulae with the same Scale and
5026/// ScaledReg and filter others, and we want to avoid that if possible.
5027void LSRInstance::NarrowSearchSpaceByFilterFormulaWithSameScaledReg() {
5028 if (EstimateSearchSpaceComplexity() < ComplexityLimit)
5029 return;
5030
5031 LLVM_DEBUG(
5032 dbgs() << "The search space is too complex.\n"
5033 "Narrowing the search space by choosing the best Formula "
5034 "from the Formulae with the same Scale and ScaledReg.\n");
5035
5036 // Map the "Scale * ScaledReg" pair to the best formula of current LSRUse.
5037 using BestFormulaeTy = DenseMap<std::pair<const SCEV *, int64_t>, size_t>;
5038
5039 BestFormulaeTy BestFormulae;
5040#ifndef NDEBUG
5041 bool ChangedFormulae = false;
5042#endif
5043 DenseSet<const SCEV *> VisitedRegs;
5044 SmallPtrSet<const SCEV *, 16> Regs;
5045
5046 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
5047 LSRUse &LU = Uses[LUIdx];
5048 LLVM_DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs());
5049 dbgs() << '\n');
5050
5051 // Return true if Formula FA is better than Formula FB.
5052 auto IsBetterThan = [&](Formula &FA, Formula &FB) {
5053 // First we will try to choose the Formula with fewer new registers.
5054 // For a register used by current Formula, the more the register is
5055 // shared among LSRUses, the less we increase the register number
5056 // counter of the formula.
5057 size_t FARegNum = 0;
5058 for (const SCEV *Reg : FA.BaseRegs) {
5059 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(Reg);
5060 FARegNum += (NumUses - UsedByIndices.count() + 1);
5061 }
5062 size_t FBRegNum = 0;
5063 for (const SCEV *Reg : FB.BaseRegs) {
5064 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(Reg);
5065 FBRegNum += (NumUses - UsedByIndices.count() + 1);
5066 }
5067 if (FARegNum != FBRegNum)
5068 return FARegNum < FBRegNum;
5069
5070 // If the new register numbers are the same, choose the Formula with
5071 // less Cost.
5072 Cost CostFA(L, SE, TTI, AMK);
5073 Cost CostFB(L, SE, TTI, AMK);
5074 Regs.clear();
5075 CostFA.RateFormula(F: FA, Regs, VisitedRegs, LU, HardwareLoopProfitable);
5076 Regs.clear();
5077 CostFB.RateFormula(F: FB, Regs, VisitedRegs, LU, HardwareLoopProfitable);
5078 return CostFA.isLess(Other: CostFB);
5079 };
5080
5081 bool Any = false;
5082 for (size_t FIdx = 0, NumForms = LU.Formulae.size(); FIdx != NumForms;
5083 ++FIdx) {
5084 Formula &F = LU.Formulae[FIdx];
5085 if (!F.ScaledReg)
5086 continue;
5087 auto P = BestFormulae.insert(KV: {{F.ScaledReg, F.Scale}, FIdx});
5088 if (P.second)
5089 continue;
5090
5091 Formula &Best = LU.Formulae[P.first->second];
5092 if (IsBetterThan(F, Best))
5093 std::swap(a&: F, b&: Best);
5094 LLVM_DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs());
5095 dbgs() << "\n"
5096 " in favor of formula ";
5097 Best.print(dbgs()); dbgs() << '\n');
5098#ifndef NDEBUG
5099 ChangedFormulae = true;
5100#endif
5101 LU.DeleteFormula(F);
5102 --FIdx;
5103 --NumForms;
5104 Any = true;
5105 }
5106 if (Any)
5107 LU.RecomputeRegs(LUIdx, RegUses);
5108
5109 // Reset this to prepare for the next use.
5110 BestFormulae.clear();
5111 }
5112
5113 LLVM_DEBUG(if (ChangedFormulae) {
5114 dbgs() << "\n"
5115 "After filtering out undesirable candidates:\n";
5116 print_uses(dbgs());
5117 });
5118}
5119
5120/// If we are over the complexity limit, filter out any post-inc prefering
5121/// variables to only post-inc values.
5122void LSRInstance::NarrowSearchSpaceByFilterPostInc() {
5123 if (AMK != TTI::AMK_PostIndexed)
5124 return;
5125 if (EstimateSearchSpaceComplexity() < ComplexityLimit)
5126 return;
5127
5128 LLVM_DEBUG(dbgs() << "The search space is too complex.\n"
5129 "Narrowing the search space by choosing the lowest "
5130 "register Formula for PostInc Uses.\n");
5131
5132 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
5133 LSRUse &LU = Uses[LUIdx];
5134
5135 if (LU.Kind != LSRUse::Address)
5136 continue;
5137 if (!TTI.isIndexedLoadLegal(Mode: TTI.MIM_PostInc, Ty: LU.AccessTy.getType()) &&
5138 !TTI.isIndexedStoreLegal(Mode: TTI.MIM_PostInc, Ty: LU.AccessTy.getType()))
5139 continue;
5140
5141 size_t MinRegs = std::numeric_limits<size_t>::max();
5142 for (const Formula &F : LU.Formulae)
5143 MinRegs = std::min(a: F.getNumRegs(), b: MinRegs);
5144
5145 bool Any = false;
5146 for (size_t FIdx = 0, NumForms = LU.Formulae.size(); FIdx != NumForms;
5147 ++FIdx) {
5148 Formula &F = LU.Formulae[FIdx];
5149 if (F.getNumRegs() > MinRegs) {
5150 LLVM_DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs());
5151 dbgs() << "\n");
5152 LU.DeleteFormula(F);
5153 --FIdx;
5154 --NumForms;
5155 Any = true;
5156 }
5157 }
5158 if (Any)
5159 LU.RecomputeRegs(LUIdx, RegUses);
5160
5161 if (EstimateSearchSpaceComplexity() < ComplexityLimit)
5162 break;
5163 }
5164
5165 LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
5166}
5167
5168/// The function delete formulas with high registers number expectation.
5169/// Assuming we don't know the value of each formula (already delete
5170/// all inefficient), generate probability of not selecting for each
5171/// register.
5172/// For example,
5173/// Use1:
5174/// reg(a) + reg({0,+,1})
5175/// reg(a) + reg({-1,+,1}) + 1
5176/// reg({a,+,1})
5177/// Use2:
5178/// reg(b) + reg({0,+,1})
5179/// reg(b) + reg({-1,+,1}) + 1
5180/// reg({b,+,1})
5181/// Use3:
5182/// reg(c) + reg(b) + reg({0,+,1})
5183/// reg(c) + reg({b,+,1})
5184///
5185/// Probability of not selecting
5186/// Use1 Use2 Use3
5187/// reg(a) (1/3) * 1 * 1
5188/// reg(b) 1 * (1/3) * (1/2)
5189/// reg({0,+,1}) (2/3) * (2/3) * (1/2)
5190/// reg({-1,+,1}) (2/3) * (2/3) * 1
5191/// reg({a,+,1}) (2/3) * 1 * 1
5192/// reg({b,+,1}) 1 * (2/3) * (2/3)
5193/// reg(c) 1 * 1 * 0
5194///
5195/// Now count registers number mathematical expectation for each formula:
5196/// Note that for each use we exclude probability if not selecting for the use.
5197/// For example for Use1 probability for reg(a) would be just 1 * 1 (excluding
5198/// probabilty 1/3 of not selecting for Use1).
5199/// Use1:
5200/// reg(a) + reg({0,+,1}) 1 + 1/3 -- to be deleted
5201/// reg(a) + reg({-1,+,1}) + 1 1 + 4/9 -- to be deleted
5202/// reg({a,+,1}) 1
5203/// Use2:
5204/// reg(b) + reg({0,+,1}) 1/2 + 1/3 -- to be deleted
5205/// reg(b) + reg({-1,+,1}) + 1 1/2 + 2/3 -- to be deleted
5206/// reg({b,+,1}) 2/3
5207/// Use3:
5208/// reg(c) + reg(b) + reg({0,+,1}) 1 + 1/3 + 4/9 -- to be deleted
5209/// reg(c) + reg({b,+,1}) 1 + 2/3
5210void LSRInstance::NarrowSearchSpaceByDeletingCostlyFormulas() {
5211 if (EstimateSearchSpaceComplexity() < ComplexityLimit)
5212 return;
5213 // Ok, we have too many of formulae on our hands to conveniently handle.
5214 // Use a rough heuristic to thin out the list.
5215
5216 // Set of Regs wich will be 100% used in final solution.
5217 // Used in each formula of a solution (in example above this is reg(c)).
5218 // We can skip them in calculations.
5219 SmallPtrSet<const SCEV *, 4> UniqRegs;
5220 LLVM_DEBUG(dbgs() << "The search space is too complex.\n");
5221
5222 // Map each register to probability of not selecting
5223 DenseMap <const SCEV *, float> RegNumMap;
5224 for (const SCEV *Reg : RegUses) {
5225 if (UniqRegs.count(Ptr: Reg))
5226 continue;
5227 float PNotSel = 1;
5228 for (const LSRUse &LU : Uses) {
5229 if (!LU.Regs.count(Ptr: Reg))
5230 continue;
5231 float P = LU.getNotSelectedProbability(Reg);
5232 if (P != 0.0)
5233 PNotSel *= P;
5234 else
5235 UniqRegs.insert(Ptr: Reg);
5236 }
5237 RegNumMap.insert(KV: std::make_pair(x&: Reg, y&: PNotSel));
5238 }
5239
5240 LLVM_DEBUG(
5241 dbgs() << "Narrowing the search space by deleting costly formulas\n");
5242
5243 // Delete formulas where registers number expectation is high.
5244 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
5245 LSRUse &LU = Uses[LUIdx];
5246 // If nothing to delete - continue.
5247 if (LU.Formulae.size() < 2)
5248 continue;
5249 // This is temporary solution to test performance. Float should be
5250 // replaced with round independent type (based on integers) to avoid
5251 // different results for different target builds.
5252 float FMinRegNum = LU.Formulae[0].getNumRegs();
5253 float FMinARegNum = LU.Formulae[0].getNumRegs();
5254 size_t MinIdx = 0;
5255 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
5256 Formula &F = LU.Formulae[i];
5257 float FRegNum = 0;
5258 float FARegNum = 0;
5259 for (const SCEV *BaseReg : F.BaseRegs) {
5260 if (UniqRegs.count(Ptr: BaseReg))
5261 continue;
5262 FRegNum += RegNumMap[BaseReg] / LU.getNotSelectedProbability(Reg: BaseReg);
5263 if (isa<SCEVAddRecExpr>(Val: BaseReg))
5264 FARegNum +=
5265 RegNumMap[BaseReg] / LU.getNotSelectedProbability(Reg: BaseReg);
5266 }
5267 if (const SCEV *ScaledReg = F.ScaledReg) {
5268 if (!UniqRegs.count(Ptr: ScaledReg)) {
5269 FRegNum +=
5270 RegNumMap[ScaledReg] / LU.getNotSelectedProbability(Reg: ScaledReg);
5271 if (isa<SCEVAddRecExpr>(Val: ScaledReg))
5272 FARegNum +=
5273 RegNumMap[ScaledReg] / LU.getNotSelectedProbability(Reg: ScaledReg);
5274 }
5275 }
5276 if (FMinRegNum > FRegNum ||
5277 (FMinRegNum == FRegNum && FMinARegNum > FARegNum)) {
5278 FMinRegNum = FRegNum;
5279 FMinARegNum = FARegNum;
5280 MinIdx = i;
5281 }
5282 }
5283 LLVM_DEBUG(dbgs() << " The formula "; LU.Formulae[MinIdx].print(dbgs());
5284 dbgs() << " with min reg num " << FMinRegNum << '\n');
5285 if (MinIdx != 0)
5286 std::swap(a&: LU.Formulae[MinIdx], b&: LU.Formulae[0]);
5287 while (LU.Formulae.size() != 1) {
5288 LLVM_DEBUG(dbgs() << " Deleting "; LU.Formulae.back().print(dbgs());
5289 dbgs() << '\n');
5290 LU.Formulae.pop_back();
5291 }
5292 LU.RecomputeRegs(LUIdx, RegUses);
5293 assert(LU.Formulae.size() == 1 && "Should be exactly 1 min regs formula");
5294 Formula &F = LU.Formulae[0];
5295 LLVM_DEBUG(dbgs() << " Leaving only "; F.print(dbgs()); dbgs() << '\n');
5296 // When we choose the formula, the regs become unique.
5297 UniqRegs.insert_range(R&: F.BaseRegs);
5298 if (F.ScaledReg)
5299 UniqRegs.insert(Ptr: F.ScaledReg);
5300 }
5301 LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
5302}
5303
5304// Check if Best and Reg are SCEVs separated by a constant amount C, and if so
5305// would the addressing offset +C would be legal where the negative offset -C is
5306// not.
5307static bool IsSimplerBaseSCEVForTarget(const TargetTransformInfo &TTI,
5308 ScalarEvolution &SE, const SCEV *Best,
5309 const SCEV *Reg,
5310 MemAccessTy AccessType) {
5311 if (Best->getType() != Reg->getType() ||
5312 (isa<SCEVAddRecExpr>(Val: Best) && isa<SCEVAddRecExpr>(Val: Reg) &&
5313 cast<SCEVAddRecExpr>(Val: Best)->getLoop() !=
5314 cast<SCEVAddRecExpr>(Val: Reg)->getLoop()))
5315 return false;
5316 std::optional<APInt> Diff = SE.computeConstantDifference(LHS: Best, RHS: Reg);
5317 if (!Diff)
5318 return false;
5319
5320 return TTI.isLegalAddressingMode(
5321 Ty: AccessType.MemTy, /*BaseGV=*/nullptr,
5322 /*BaseOffset=*/Diff->getSExtValue(),
5323 /*HasBaseReg=*/true, /*Scale=*/0, AddrSpace: AccessType.AddrSpace) &&
5324 !TTI.isLegalAddressingMode(
5325 Ty: AccessType.MemTy, /*BaseGV=*/nullptr,
5326 /*BaseOffset=*/-Diff->getSExtValue(),
5327 /*HasBaseReg=*/true, /*Scale=*/0, AddrSpace: AccessType.AddrSpace);
5328}
5329
5330/// Pick a register which seems likely to be profitable, and then in any use
5331/// which has any reference to that register, delete all formulae which do not
5332/// reference that register.
5333void LSRInstance::NarrowSearchSpaceByPickingWinnerRegs() {
5334 // With all other options exhausted, loop until the system is simple
5335 // enough to handle.
5336 SmallPtrSet<const SCEV *, 4> Taken;
5337 while (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
5338 // Ok, we have too many of formulae on our hands to conveniently handle.
5339 // Use a rough heuristic to thin out the list.
5340 LLVM_DEBUG(dbgs() << "The search space is too complex.\n");
5341
5342 // Pick the register which is used by the most LSRUses, which is likely
5343 // to be a good reuse register candidate.
5344 const SCEV *Best = nullptr;
5345 unsigned BestNum = 0;
5346 for (const SCEV *Reg : RegUses) {
5347 if (Taken.count(Ptr: Reg))
5348 continue;
5349 if (!Best) {
5350 Best = Reg;
5351 BestNum = RegUses.getUsedByIndices(Reg).count();
5352 } else {
5353 unsigned Count = RegUses.getUsedByIndices(Reg).count();
5354 if (Count > BestNum) {
5355 Best = Reg;
5356 BestNum = Count;
5357 }
5358
5359 // If the scores are the same, but the Reg is simpler for the target
5360 // (for example {x,+,1} as opposed to {x+C,+,1}, where the target can
5361 // handle +C but not -C), opt for the simpler formula.
5362 if (Count == BestNum) {
5363 int LUIdx = RegUses.getUsedByIndices(Reg).find_first();
5364 if (LUIdx >= 0 && Uses[LUIdx].Kind == LSRUse::Address &&
5365 IsSimplerBaseSCEVForTarget(TTI, SE, Best, Reg,
5366 AccessType: Uses[LUIdx].AccessTy)) {
5367 Best = Reg;
5368 BestNum = Count;
5369 }
5370 }
5371 }
5372 }
5373 assert(Best && "Failed to find best LSRUse candidate");
5374
5375 LLVM_DEBUG(dbgs() << "Narrowing the search space by assuming " << *Best
5376 << " will yield profitable reuse.\n");
5377 Taken.insert(Ptr: Best);
5378
5379 // In any use with formulae which references this register, delete formulae
5380 // which don't reference it.
5381 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
5382 LSRUse &LU = Uses[LUIdx];
5383 if (!LU.Regs.count(Ptr: Best)) continue;
5384
5385 bool Any = false;
5386 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
5387 Formula &F = LU.Formulae[i];
5388 if (!F.referencesReg(S: Best)) {
5389 LLVM_DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
5390 LU.DeleteFormula(F);
5391 --e;
5392 --i;
5393 Any = true;
5394 assert(e != 0 && "Use has no formulae left! Is Regs inconsistent?");
5395 continue;
5396 }
5397 }
5398
5399 if (Any)
5400 LU.RecomputeRegs(LUIdx, RegUses);
5401 }
5402
5403 LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
5404 }
5405}
5406
5407/// If there are an extraordinary number of formulae to choose from, use some
5408/// rough heuristics to prune down the number of formulae. This keeps the main
5409/// solver from taking an extraordinary amount of time in some worst-case
5410/// scenarios.
5411void LSRInstance::NarrowSearchSpaceUsingHeuristics() {
5412 NarrowSearchSpaceByDetectingSupersets();
5413 NarrowSearchSpaceByCollapsingUnrolledCode();
5414 NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
5415 if (FilterSameScaledReg)
5416 NarrowSearchSpaceByFilterFormulaWithSameScaledReg();
5417 NarrowSearchSpaceByFilterPostInc();
5418 if (LSRExpNarrow)
5419 NarrowSearchSpaceByDeletingCostlyFormulas();
5420 else
5421 NarrowSearchSpaceByPickingWinnerRegs();
5422}
5423
5424/// This is the recursive solver.
5425void LSRInstance::SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
5426 Cost &SolutionCost,
5427 SmallVectorImpl<const Formula *> &Workspace,
5428 const Cost &CurCost,
5429 const SmallPtrSet<const SCEV *, 16> &CurRegs,
5430 DenseSet<const SCEV *> &VisitedRegs) const {
5431 // Some ideas:
5432 // - prune more:
5433 // - use more aggressive filtering
5434 // - sort the formula so that the most profitable solutions are found first
5435 // - sort the uses too
5436 // - search faster:
5437 // - don't compute a cost, and then compare. compare while computing a cost
5438 // and bail early.
5439 // - track register sets with SmallBitVector
5440
5441 const LSRUse &LU = Uses[Workspace.size()];
5442
5443 // If this use references any register that's already a part of the
5444 // in-progress solution, consider it a requirement that a formula must
5445 // reference that register in order to be considered. This prunes out
5446 // unprofitable searching.
5447 SmallSetVector<const SCEV *, 4> ReqRegs;
5448 for (const SCEV *S : CurRegs)
5449 if (LU.Regs.count(Ptr: S))
5450 ReqRegs.insert(X: S);
5451
5452 SmallPtrSet<const SCEV *, 16> NewRegs;
5453 Cost NewCost(L, SE, TTI, AMK);
5454 for (const Formula &F : LU.Formulae) {
5455 // Ignore formulae which may not be ideal in terms of register reuse of
5456 // ReqRegs. The formula should use all required registers before
5457 // introducing new ones.
5458 // This can sometimes (notably when trying to favour postinc) lead to
5459 // sub-optimial decisions. There it is best left to the cost modelling to
5460 // get correct.
5461 if (!(AMK & TTI::AMK_PostIndexed) || LU.Kind != LSRUse::Address) {
5462 int NumReqRegsToFind = std::min(a: F.getNumRegs(), b: ReqRegs.size());
5463 for (const SCEV *Reg : ReqRegs) {
5464 if ((F.ScaledReg && F.ScaledReg == Reg) ||
5465 is_contained(Range: F.BaseRegs, Element: Reg)) {
5466 --NumReqRegsToFind;
5467 if (NumReqRegsToFind == 0)
5468 break;
5469 }
5470 }
5471 if (NumReqRegsToFind != 0) {
5472 // If none of the formulae satisfied the required registers, then we could
5473 // clear ReqRegs and try again. Currently, we simply give up in this case.
5474 continue;
5475 }
5476 }
5477
5478 // Evaluate the cost of the current formula. If it's already worse than
5479 // the current best, prune the search at that point.
5480 NewCost = CurCost;
5481 NewRegs = CurRegs;
5482 NewCost.RateFormula(F, Regs&: NewRegs, VisitedRegs, LU, HardwareLoopProfitable);
5483 if (NewCost.isLess(Other: SolutionCost)) {
5484 Workspace.push_back(Elt: &F);
5485 if (Workspace.size() != Uses.size()) {
5486 SolveRecurse(Solution, SolutionCost, Workspace, CurCost: NewCost,
5487 CurRegs: NewRegs, VisitedRegs);
5488 if (F.getNumRegs() == 1 && Workspace.size() == 1)
5489 VisitedRegs.insert(V: F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]);
5490 } else {
5491 LLVM_DEBUG(dbgs() << "New best at "; NewCost.print(dbgs());
5492 dbgs() << ".\nRegs:\n";
5493 for (const SCEV *S : NewRegs) dbgs()
5494 << "- " << *S << "\n";
5495 dbgs() << '\n');
5496
5497 SolutionCost = NewCost;
5498 Solution = Workspace;
5499 }
5500 Workspace.pop_back();
5501 }
5502 }
5503}
5504
5505/// Choose one formula from each use. Return the results in the given Solution
5506/// vector.
5507void LSRInstance::Solve(SmallVectorImpl<const Formula *> &Solution) const {
5508 SmallVector<const Formula *, 8> Workspace;
5509 Cost SolutionCost(L, SE, TTI, AMK);
5510 SolutionCost.Lose();
5511 Cost CurCost(L, SE, TTI, AMK);
5512 SmallPtrSet<const SCEV *, 16> CurRegs;
5513 DenseSet<const SCEV *> VisitedRegs;
5514 Workspace.reserve(N: Uses.size());
5515
5516 // SolveRecurse does all the work.
5517 SolveRecurse(Solution, SolutionCost, Workspace, CurCost,
5518 CurRegs, VisitedRegs);
5519 if (Solution.empty()) {
5520 LLVM_DEBUG(dbgs() << "\nNo Satisfactory Solution\n");
5521 return;
5522 }
5523
5524 // Ok, we've now made all our decisions.
5525 LLVM_DEBUG(dbgs() << "\n"
5526 "The chosen solution requires ";
5527 SolutionCost.print(dbgs()); dbgs() << ":\n";
5528 for (size_t i = 0, e = Uses.size(); i != e; ++i) {
5529 dbgs() << " ";
5530 Uses[i].print(dbgs());
5531 dbgs() << "\n"
5532 " ";
5533 Solution[i]->print(dbgs());
5534 dbgs() << '\n';
5535 });
5536
5537 assert(Solution.size() == Uses.size() && "Malformed solution!");
5538
5539 const bool EnableDropUnprofitableSolution = [&] {
5540 switch (AllowDropSolutionIfLessProfitable) {
5541 case cl::BOU_TRUE:
5542 return true;
5543 case cl::BOU_FALSE:
5544 return false;
5545 case cl::BOU_UNSET:
5546 return TTI.shouldDropLSRSolutionIfLessProfitable();
5547 }
5548 llvm_unreachable("Unhandled cl::boolOrDefault enum");
5549 }();
5550
5551 if (BaselineCost.isLess(Other: SolutionCost)) {
5552 if (!EnableDropUnprofitableSolution)
5553 LLVM_DEBUG(
5554 dbgs() << "Baseline is more profitable than chosen solution, "
5555 "add option 'lsr-drop-solution' to drop LSR solution.\n");
5556 else {
5557 LLVM_DEBUG(dbgs() << "Baseline is more profitable than chosen "
5558 "solution, dropping LSR solution.\n";);
5559 Solution.clear();
5560 }
5561 }
5562}
5563
5564/// Helper for AdjustInsertPositionForExpand. Climb up the dominator tree far as
5565/// we can go while still being dominated by the input positions. This helps
5566/// canonicalize the insert position, which encourages sharing.
5567BasicBlock::iterator
5568LSRInstance::HoistInsertPosition(BasicBlock::iterator IP,
5569 const SmallVectorImpl<Instruction *> &Inputs)
5570 const {
5571 Instruction *Tentative = &*IP;
5572 while (true) {
5573 bool AllDominate = true;
5574 Instruction *BetterPos = nullptr;
5575 // Don't bother attempting to insert before a catchswitch, their basic block
5576 // cannot have other non-PHI instructions.
5577 if (isa<CatchSwitchInst>(Val: Tentative))
5578 return IP;
5579
5580 for (Instruction *Inst : Inputs) {
5581 if (Inst == Tentative || !DT.dominates(Def: Inst, User: Tentative)) {
5582 AllDominate = false;
5583 break;
5584 }
5585 // Attempt to find an insert position in the middle of the block,
5586 // instead of at the end, so that it can be used for other expansions.
5587 if (Tentative->getParent() == Inst->getParent() &&
5588 (!BetterPos || !DT.dominates(Def: Inst, User: BetterPos)))
5589 BetterPos = &*std::next(x: BasicBlock::iterator(Inst));
5590 }
5591 if (!AllDominate)
5592 break;
5593 if (BetterPos)
5594 IP = BetterPos->getIterator();
5595 else
5596 IP = Tentative->getIterator();
5597
5598 const Loop *IPLoop = LI.getLoopFor(BB: IP->getParent());
5599 unsigned IPLoopDepth = IPLoop ? IPLoop->getLoopDepth() : 0;
5600
5601 BasicBlock *IDom;
5602 for (DomTreeNode *Rung = DT.getNode(BB: IP->getParent()); ; ) {
5603 if (!Rung) return IP;
5604 Rung = Rung->getIDom();
5605 if (!Rung) return IP;
5606 IDom = Rung->getBlock();
5607
5608 // Don't climb into a loop though.
5609 const Loop *IDomLoop = LI.getLoopFor(BB: IDom);
5610 unsigned IDomDepth = IDomLoop ? IDomLoop->getLoopDepth() : 0;
5611 if (IDomDepth <= IPLoopDepth &&
5612 (IDomDepth != IPLoopDepth || IDomLoop == IPLoop))
5613 break;
5614 }
5615
5616 Tentative = IDom->getTerminator();
5617 }
5618
5619 return IP;
5620}
5621
5622/// Determine an input position which will be dominated by the operands and
5623/// which will dominate the result.
5624BasicBlock::iterator LSRInstance::AdjustInsertPositionForExpand(
5625 BasicBlock::iterator LowestIP, const LSRFixup &LF, const LSRUse &LU) const {
5626 // Collect some instructions which must be dominated by the
5627 // expanding replacement. These must be dominated by any operands that
5628 // will be required in the expansion.
5629 SmallVector<Instruction *, 4> Inputs;
5630 if (Instruction *I = dyn_cast<Instruction>(Val: LF.OperandValToReplace))
5631 Inputs.push_back(Elt: I);
5632 if (LU.Kind == LSRUse::ICmpZero)
5633 if (Instruction *I =
5634 dyn_cast<Instruction>(Val: cast<ICmpInst>(Val: LF.UserInst)->getOperand(i_nocapture: 1)))
5635 Inputs.push_back(Elt: I);
5636 if (LF.PostIncLoops.count(Ptr: L)) {
5637 if (LF.isUseFullyOutsideLoop(L))
5638 Inputs.push_back(Elt: L->getLoopLatch()->getTerminator());
5639 else
5640 Inputs.push_back(Elt: IVIncInsertPos);
5641 }
5642 // The expansion must also be dominated by the increment positions of any
5643 // loops it for which it is using post-inc mode.
5644 for (const Loop *PIL : LF.PostIncLoops) {
5645 if (PIL == L) continue;
5646
5647 // Be dominated by the loop exit.
5648 SmallVector<BasicBlock *, 4> ExitingBlocks;
5649 PIL->getExitingBlocks(ExitingBlocks);
5650 if (!ExitingBlocks.empty()) {
5651 BasicBlock *BB = ExitingBlocks[0];
5652 for (unsigned i = 1, e = ExitingBlocks.size(); i != e; ++i)
5653 BB = DT.findNearestCommonDominator(A: BB, B: ExitingBlocks[i]);
5654 Inputs.push_back(Elt: BB->getTerminator());
5655 }
5656 }
5657
5658 assert(!isa<PHINode>(LowestIP) && !LowestIP->isEHPad() &&
5659 "Insertion point must be a normal instruction");
5660
5661 // Then, climb up the immediate dominator tree as far as we can go while
5662 // still being dominated by the input positions.
5663 BasicBlock::iterator IP = HoistInsertPosition(IP: LowestIP, Inputs);
5664
5665 // Don't insert instructions before PHI nodes.
5666 while (isa<PHINode>(Val: IP)) ++IP;
5667
5668 // Ignore landingpad instructions.
5669 while (IP->isEHPad()) ++IP;
5670
5671 // Set IP below instructions recently inserted by SCEVExpander. This keeps the
5672 // IP consistent across expansions and allows the previously inserted
5673 // instructions to be reused by subsequent expansion.
5674 while (Rewriter.isInsertedInstruction(I: &*IP) && IP != LowestIP)
5675 ++IP;
5676
5677 return IP;
5678}
5679
5680/// Emit instructions for the leading candidate expression for this LSRUse (this
5681/// is called "expanding").
5682Value *LSRInstance::Expand(const LSRUse &LU, const LSRFixup &LF,
5683 const Formula &F, BasicBlock::iterator IP,
5684 SmallVectorImpl<WeakTrackingVH> &DeadInsts) const {
5685 if (LU.RigidFormula)
5686 return LF.OperandValToReplace;
5687
5688 // Determine an input position which will be dominated by the operands and
5689 // which will dominate the result.
5690 IP = AdjustInsertPositionForExpand(LowestIP: IP, LF, LU);
5691 Rewriter.setInsertPoint(&*IP);
5692
5693 // Inform the Rewriter if we have a post-increment use, so that it can
5694 // perform an advantageous expansion.
5695 Rewriter.setPostInc(LF.PostIncLoops);
5696
5697 // This is the type that the user actually needs.
5698 Type *OpTy = LF.OperandValToReplace->getType();
5699 // This will be the type that we'll initially expand to.
5700 Type *Ty = F.getType();
5701 if (!Ty)
5702 // No type known; just expand directly to the ultimate type.
5703 Ty = OpTy;
5704 else if (SE.getEffectiveSCEVType(Ty) == SE.getEffectiveSCEVType(Ty: OpTy))
5705 // Expand directly to the ultimate type if it's the right size.
5706 Ty = OpTy;
5707 // This is the type to do integer arithmetic in.
5708 Type *IntTy = SE.getEffectiveSCEVType(Ty);
5709
5710 // Build up a list of operands to add together to form the full base.
5711 SmallVector<SCEVUse, 8> Ops;
5712
5713 // Expand the BaseRegs portion.
5714 for (const SCEV *Reg : F.BaseRegs) {
5715 assert(!Reg->isZero() && "Zero allocated in a base register!");
5716
5717 // If we're expanding for a post-inc user, make the post-inc adjustment.
5718 Reg = denormalizeForPostIncUse(S: Reg, Loops: LF.PostIncLoops, SE);
5719 Ops.push_back(Elt: SE.getUnknown(V: Rewriter.expandCodeFor(SH: Reg, Ty: nullptr)));
5720 }
5721
5722 // Expand the ScaledReg portion.
5723 Value *ICmpScaledV = nullptr;
5724 if (F.Scale != 0) {
5725 const SCEV *ScaledS = F.ScaledReg;
5726
5727 // If we're expanding for a post-inc user, make the post-inc adjustment.
5728 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
5729 ScaledS = denormalizeForPostIncUse(S: ScaledS, Loops, SE);
5730
5731 if (LU.Kind == LSRUse::ICmpZero) {
5732 // Expand ScaleReg as if it was part of the base regs.
5733 if (F.Scale == 1)
5734 Ops.push_back(
5735 Elt: SE.getUnknown(V: Rewriter.expandCodeFor(SH: ScaledS, Ty: nullptr)));
5736 else {
5737 // An interesting way of "folding" with an icmp is to use a negated
5738 // scale, which we'll implement by inserting it into the other operand
5739 // of the icmp.
5740 assert(F.Scale == -1 &&
5741 "The only scale supported by ICmpZero uses is -1!");
5742 ICmpScaledV = Rewriter.expandCodeFor(SH: ScaledS, Ty: nullptr);
5743 }
5744 } else {
5745 // Otherwise just expand the scaled register and an explicit scale,
5746 // which is expected to be matched as part of the address.
5747
5748 // Flush the operand list to suppress SCEVExpander hoisting address modes.
5749 // Unless the addressing mode will not be folded.
5750 if (!Ops.empty() && LU.Kind == LSRUse::Address &&
5751 isAMCompletelyFolded(TTI, LU, F)) {
5752 Value *FullV = Rewriter.expandCodeFor(SH: SE.getAddExpr(Ops), Ty: nullptr);
5753 Ops.clear();
5754 Ops.push_back(Elt: SE.getUnknown(V: FullV));
5755 }
5756 ScaledS = SE.getUnknown(V: Rewriter.expandCodeFor(SH: ScaledS, Ty: nullptr));
5757 if (F.Scale != 1)
5758 ScaledS =
5759 SE.getMulExpr(LHS: ScaledS, RHS: SE.getConstant(Ty: ScaledS->getType(), V: F.Scale));
5760 Ops.push_back(Elt: ScaledS);
5761 }
5762 }
5763
5764 // Expand the GV portion.
5765 if (F.BaseGV) {
5766 // Flush the operand list to suppress SCEVExpander hoisting.
5767 if (!Ops.empty()) {
5768 Value *FullV = Rewriter.expandCodeFor(SH: SE.getAddExpr(Ops), Ty: IntTy);
5769 Ops.clear();
5770 Ops.push_back(Elt: SE.getUnknown(V: FullV));
5771 }
5772 Ops.push_back(Elt: SE.getUnknown(V: F.BaseGV));
5773 }
5774
5775 // Flush the operand list to suppress SCEVExpander hoisting of both folded and
5776 // unfolded offsets. LSR assumes they both live next to their uses.
5777 if (!Ops.empty()) {
5778 Value *FullV = Rewriter.expandCodeFor(SH: SE.getAddExpr(Ops), Ty);
5779 Ops.clear();
5780 Ops.push_back(Elt: SE.getUnknown(V: FullV));
5781 }
5782
5783 // FIXME: Are we sure we won't get a mismatch here? Is there a way to bail
5784 // out at this point, or should we generate a SCEV adding together mixed
5785 // offsets?
5786 assert(F.BaseOffset.isCompatibleImmediate(LF.Offset) &&
5787 "Expanding mismatched offsets\n");
5788 // Expand the immediate portion.
5789 Immediate Offset = F.BaseOffset.addUnsigned(RHS: LF.Offset);
5790 if (Offset.isNonZero()) {
5791 if (LU.Kind == LSRUse::ICmpZero) {
5792 // The other interesting way of "folding" with an ICmpZero is to use a
5793 // negated immediate.
5794 if (!ICmpScaledV) {
5795 // TODO: Avoid implicit trunc?
5796 // See https://github.com/llvm/llvm-project/issues/112510.
5797 ICmpScaledV = ConstantInt::getSigned(
5798 Ty: IntTy, V: -(uint64_t)Offset.getFixedValue(), /*ImplicitTrunc=*/true);
5799 } else {
5800 Ops.push_back(Elt: SE.getUnknown(V: ICmpScaledV));
5801 ICmpScaledV = ConstantInt::getSigned(Ty: IntTy, V: Offset.getFixedValue(),
5802 /*ImplicitTrunc=*/true);
5803 }
5804 } else {
5805 // Just add the immediate values. These again are expected to be matched
5806 // as part of the address.
5807 Ops.push_back(Elt: Offset.getUnknownSCEV(SE, Ty: IntTy));
5808 }
5809 }
5810
5811 // Expand the unfolded offset portion.
5812 Immediate UnfoldedOffset = F.UnfoldedOffset;
5813 if (UnfoldedOffset.isNonZero()) {
5814 // Just add the immediate values.
5815 Ops.push_back(Elt: UnfoldedOffset.getUnknownSCEV(SE, Ty: IntTy));
5816 }
5817
5818 // Emit instructions summing all the operands.
5819 const SCEV *FullS = Ops.empty() ?
5820 SE.getConstant(Ty: IntTy, V: 0) :
5821 SE.getAddExpr(Ops);
5822 Value *FullV = Rewriter.expandCodeFor(SH: FullS, Ty);
5823
5824 // We're done expanding now, so reset the rewriter.
5825 Rewriter.clearPostInc();
5826
5827 // An ICmpZero Formula represents an ICmp which we're handling as a
5828 // comparison against zero. Now that we've expanded an expression for that
5829 // form, update the ICmp's other operand.
5830 if (LU.Kind == LSRUse::ICmpZero) {
5831 ICmpInst *CI = cast<ICmpInst>(Val: LF.UserInst);
5832 if (auto *OperandIsInstr = dyn_cast<Instruction>(Val: CI->getOperand(i_nocapture: 1)))
5833 DeadInsts.emplace_back(Args&: OperandIsInstr);
5834 assert(!F.BaseGV && "ICmp does not support folding a global value and "
5835 "a scale at the same time!");
5836 if (F.Scale == -1) {
5837 if (ICmpScaledV->getType() != OpTy) {
5838 Instruction *Cast = CastInst::Create(
5839 CastInst::getCastOpcode(Val: ICmpScaledV, SrcIsSigned: false, Ty: OpTy, DstIsSigned: false),
5840 S: ICmpScaledV, Ty: OpTy, Name: "tmp", InsertBefore: CI->getIterator());
5841 ICmpScaledV = Cast;
5842 }
5843 CI->setOperand(i_nocapture: 1, Val_nocapture: ICmpScaledV);
5844 } else {
5845 // A scale of 1 means that the scale has been expanded as part of the
5846 // base regs.
5847 assert((F.Scale == 0 || F.Scale == 1) &&
5848 "ICmp does not support folding a global value and "
5849 "a scale at the same time!");
5850 // TODO: Avoid implicit trunc?
5851 // See https://github.com/llvm/llvm-project/issues/112510.
5852 Constant *C = ConstantInt::getSigned(Ty: SE.getEffectiveSCEVType(Ty: OpTy),
5853 V: -(uint64_t)Offset.getFixedValue(),
5854 /*ImplicitTrunc=*/true);
5855 if (C->getType() != OpTy) {
5856 C = ConstantFoldCastOperand(
5857 Opcode: CastInst::getCastOpcode(Val: C, SrcIsSigned: false, Ty: OpTy, DstIsSigned: false), C, DestTy: OpTy,
5858 DL: CI->getDataLayout());
5859 assert(C && "Cast of ConstantInt should have folded");
5860 }
5861
5862 CI->setOperand(i_nocapture: 1, Val_nocapture: C);
5863 }
5864 }
5865
5866 return FullV;
5867}
5868
5869/// Helper for Rewrite. PHI nodes are special because the use of their operands
5870/// effectively happens in their predecessor blocks, so the expression may need
5871/// to be expanded in multiple places.
5872void LSRInstance::RewriteForPHI(PHINode *PN, const LSRUse &LU,
5873 const LSRFixup &LF, const Formula &F,
5874 SmallVectorImpl<WeakTrackingVH> &DeadInsts) {
5875 DenseMap<BasicBlock *, Value *> Inserted;
5876
5877 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5878 if (PN->getIncomingValue(i) == LF.OperandValToReplace) {
5879 bool needUpdateFixups = false;
5880 BasicBlock *BB = PN->getIncomingBlock(i);
5881
5882 // If this is a critical edge, split the edge so that we do not insert
5883 // the code on all predecessor/successor paths. We do this unless this
5884 // is the canonical backedge for this loop, which complicates post-inc
5885 // users.
5886 if (e != 1 && BB->getTerminator()->getNumSuccessors() > 1 &&
5887 !isa<IndirectBrInst>(Val: BB->getTerminator()) &&
5888 !isa<CatchSwitchInst>(Val: BB->getTerminator())) {
5889 BasicBlock *Parent = PN->getParent();
5890 Loop *PNLoop = LI.getLoopFor(BB: Parent);
5891 if (!PNLoop || Parent != PNLoop->getHeader()) {
5892 // Split the critical edge.
5893 BasicBlock *NewBB = nullptr;
5894 if (!Parent->isLandingPad()) {
5895 NewBB =
5896 SplitCriticalEdge(Src: BB, Dst: Parent,
5897 Options: CriticalEdgeSplittingOptions(&DT, &LI, MSSAU)
5898 .setMergeIdenticalEdges()
5899 .setKeepOneInputPHIs());
5900 } else {
5901 SmallVector<BasicBlock*, 2> NewBBs;
5902 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
5903 SplitLandingPadPredecessors(OrigBB: Parent, Preds: BB, Suffix: "", Suffix2: "", NewBBs, DTU: &DTU, LI: &LI);
5904 NewBB = NewBBs[0];
5905 }
5906 // If NewBB==NULL, then SplitCriticalEdge refused to split because all
5907 // phi predecessors are identical. The simple thing to do is skip
5908 // splitting in this case rather than complicate the API.
5909 if (NewBB) {
5910 // If PN is outside of the loop and BB is in the loop, we want to
5911 // move the block to be immediately before the PHI block, not
5912 // immediately after BB.
5913 if (L->contains(BB) && !L->contains(Inst: PN))
5914 NewBB->moveBefore(MovePos: PN->getParent());
5915
5916 // Splitting the edge can reduce the number of PHI entries we have.
5917 e = PN->getNumIncomingValues();
5918 BB = NewBB;
5919 i = PN->getBasicBlockIndex(BB);
5920
5921 needUpdateFixups = true;
5922 }
5923 }
5924 }
5925
5926 std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> Pair =
5927 Inserted.try_emplace(Key: BB);
5928 if (!Pair.second)
5929 PN->setIncomingValue(i, V: Pair.first->second);
5930 else {
5931 Value *FullV =
5932 Expand(LU, LF, F, IP: BB->getTerminator()->getIterator(), DeadInsts);
5933
5934 // If this is reuse-by-noop-cast, insert the noop cast.
5935 Type *OpTy = LF.OperandValToReplace->getType();
5936 if (FullV->getType() != OpTy)
5937 FullV = CastInst::Create(
5938 CastInst::getCastOpcode(Val: FullV, SrcIsSigned: false, Ty: OpTy, DstIsSigned: false), S: FullV,
5939 Ty: LF.OperandValToReplace->getType(), Name: "tmp",
5940 InsertBefore: BB->getTerminator()->getIterator());
5941
5942 // If the incoming block for this value is not in the loop, it means the
5943 // current PHI is not in a loop exit, so we must create a LCSSA PHI for
5944 // the inserted value.
5945 if (auto *I = dyn_cast<Instruction>(Val: FullV))
5946 if (L->contains(Inst: I) && !L->contains(BB))
5947 InsertedNonLCSSAInsts.insert(X: I);
5948
5949 PN->setIncomingValue(i, V: FullV);
5950 Pair.first->second = FullV;
5951 }
5952
5953 // If LSR splits critical edge and phi node has other pending
5954 // fixup operands, we need to update those pending fixups. Otherwise
5955 // formulae will not be implemented completely and some instructions
5956 // will not be eliminated.
5957 if (needUpdateFixups) {
5958 for (LSRUse &LU : Uses)
5959 for (LSRFixup &Fixup : LU.Fixups)
5960 // If fixup is supposed to rewrite some operand in the phi
5961 // that was just updated, it may be already moved to
5962 // another phi node. Such fixup requires update.
5963 if (Fixup.UserInst == PN) {
5964 // Check if the operand we try to replace still exists in the
5965 // original phi.
5966 bool foundInOriginalPHI = false;
5967 for (const auto &val : PN->incoming_values())
5968 if (val == Fixup.OperandValToReplace) {
5969 foundInOriginalPHI = true;
5970 break;
5971 }
5972
5973 // If fixup operand found in original PHI - nothing to do.
5974 if (foundInOriginalPHI)
5975 continue;
5976
5977 // Otherwise it might be moved to another PHI and requires update.
5978 // If fixup operand not found in any of the incoming blocks that
5979 // means we have already rewritten it - nothing to do.
5980 for (const auto &Block : PN->blocks())
5981 for (BasicBlock::iterator I = Block->begin(); isa<PHINode>(Val: I);
5982 ++I) {
5983 PHINode *NewPN = cast<PHINode>(Val&: I);
5984 for (const auto &val : NewPN->incoming_values())
5985 if (val == Fixup.OperandValToReplace)
5986 Fixup.UserInst = NewPN;
5987 }
5988 }
5989 }
5990 }
5991}
5992
5993/// Emit instructions for the leading candidate expression for this LSRUse (this
5994/// is called "expanding"), and update the UserInst to reference the newly
5995/// expanded value.
5996void LSRInstance::Rewrite(const LSRUse &LU, const LSRFixup &LF,
5997 const Formula &F,
5998 SmallVectorImpl<WeakTrackingVH> &DeadInsts) {
5999 // First, find an insertion point that dominates UserInst. For PHI nodes,
6000 // find the nearest block which dominates all the relevant uses.
6001 if (PHINode *PN = dyn_cast<PHINode>(Val: LF.UserInst)) {
6002 RewriteForPHI(PN, LU, LF, F, DeadInsts);
6003 } else {
6004 Value *FullV = Expand(LU, LF, F, IP: LF.UserInst->getIterator(), DeadInsts);
6005
6006 // If this is reuse-by-noop-cast, insert the noop cast.
6007 Type *OpTy = LF.OperandValToReplace->getType();
6008 if (FullV->getType() != OpTy) {
6009 Instruction *Cast =
6010 CastInst::Create(CastInst::getCastOpcode(Val: FullV, SrcIsSigned: false, Ty: OpTy, DstIsSigned: false),
6011 S: FullV, Ty: OpTy, Name: "tmp", InsertBefore: LF.UserInst->getIterator());
6012 FullV = Cast;
6013 }
6014
6015 // Update the user. ICmpZero is handled specially here (for now) because
6016 // Expand may have updated one of the operands of the icmp already, and
6017 // its new value may happen to be equal to LF.OperandValToReplace, in
6018 // which case doing replaceUsesOfWith leads to replacing both operands
6019 // with the same value. TODO: Reorganize this.
6020 if (LU.Kind == LSRUse::ICmpZero)
6021 LF.UserInst->setOperand(i: 0, Val: FullV);
6022 else
6023 LF.UserInst->replaceUsesOfWith(From: LF.OperandValToReplace, To: FullV);
6024 }
6025
6026 if (auto *OperandIsInstr = dyn_cast<Instruction>(Val: LF.OperandValToReplace))
6027 DeadInsts.emplace_back(Args&: OperandIsInstr);
6028}
6029
6030// Determine where to insert the transformed IV increment instruction for this
6031// fixup. By default this is the default insert position, but if this is a
6032// postincrement opportunity then we try to insert it in the same block as the
6033// fixup user instruction, as this is needed for a postincrement instruction to
6034// be generated.
6035static Instruction *getFixupInsertPos(const TargetTransformInfo &TTI,
6036 const LSRFixup &Fixup, const LSRUse &LU,
6037 Instruction *IVIncInsertPos,
6038 DominatorTree &DT) {
6039 // Only address uses can be postincremented
6040 if (LU.Kind != LSRUse::Address)
6041 return IVIncInsertPos;
6042
6043 // Don't try to postincrement if it's not legal
6044 Instruction *I = Fixup.UserInst;
6045 Type *Ty = I->getType();
6046 if (!(isa<LoadInst>(Val: I) && TTI.isIndexedLoadLegal(Mode: TTI.MIM_PostInc, Ty)) &&
6047 !(isa<StoreInst>(Val: I) && TTI.isIndexedStoreLegal(Mode: TTI.MIM_PostInc, Ty)))
6048 return IVIncInsertPos;
6049
6050 // It's only legal to hoist to the user block if it dominates the default
6051 // insert position.
6052 BasicBlock *HoistBlock = I->getParent();
6053 BasicBlock *IVIncBlock = IVIncInsertPos->getParent();
6054 if (!DT.dominates(Def: I, BB: IVIncBlock))
6055 return IVIncInsertPos;
6056
6057 return HoistBlock->getTerminator();
6058}
6059
6060/// Rewrite all the fixup locations with new values, following the chosen
6061/// solution.
6062void LSRInstance::ImplementSolution(
6063 const SmallVectorImpl<const Formula *> &Solution) {
6064 // Keep track of instructions we may have made dead, so that
6065 // we can remove them after we are done working.
6066 SmallVector<WeakTrackingVH, 16> DeadInsts;
6067
6068 // Mark phi nodes that terminate chains so the expander tries to reuse them.
6069 for (const IVChain &Chain : IVChainVec) {
6070 if (PHINode *PN = dyn_cast<PHINode>(Val: Chain.tailUserInst()))
6071 Rewriter.setChainedPhi(PN);
6072 }
6073
6074 // Expand the new value definitions and update the users.
6075 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx)
6076 for (const LSRFixup &Fixup : Uses[LUIdx].Fixups) {
6077 Instruction *InsertPos =
6078 getFixupInsertPos(TTI, Fixup, LU: Uses[LUIdx], IVIncInsertPos, DT);
6079 Rewriter.setIVIncInsertPos(L, Pos: InsertPos);
6080 Rewrite(LU: Uses[LUIdx], LF: Fixup, F: *Solution[LUIdx], DeadInsts);
6081 Changed = true;
6082 }
6083
6084 auto InsertedInsts = InsertedNonLCSSAInsts.takeVector();
6085 formLCSSAForInstructions(Worklist&: InsertedInsts, DT, LI, SE: &SE);
6086
6087 for (const IVChain &Chain : IVChainVec) {
6088 GenerateIVChain(Chain, DeadInsts);
6089 Changed = true;
6090 }
6091
6092 for (const WeakVH &IV : Rewriter.getInsertedIVs())
6093 if (IV && dyn_cast<Instruction>(Val: &*IV)->getParent())
6094 ScalarEvolutionIVs.push_back(Elt: IV);
6095
6096 // Clean up after ourselves. This must be done before deleting any
6097 // instructions.
6098 Rewriter.clear();
6099
6100 Changed |= RecursivelyDeleteTriviallyDeadInstructionsPermissive(DeadInsts,
6101 TLI: &TLI, MSSAU);
6102
6103 // In our cost analysis above, we assume that each addrec consumes exactly
6104 // one register, and arrange to have increments inserted just before the
6105 // latch to maximimize the chance this is true. However, if we reused
6106 // existing IVs, we now need to move the increments to match our
6107 // expectations. Otherwise, our cost modeling results in us having a
6108 // chosen a non-optimal result for the actual schedule. (And yes, this
6109 // scheduling decision does impact later codegen.)
6110 for (PHINode &PN : L->getHeader()->phis()) {
6111 BinaryOperator *BO = nullptr;
6112 Value *Start = nullptr, *Step = nullptr;
6113 if (!matchSimpleRecurrence(P: &PN, BO, Start, Step))
6114 continue;
6115
6116 switch (BO->getOpcode()) {
6117 case Instruction::Sub:
6118 if (BO->getOperand(i_nocapture: 0) != &PN)
6119 // sub is non-commutative - match handling elsewhere in LSR
6120 continue;
6121 break;
6122 case Instruction::Add:
6123 break;
6124 default:
6125 continue;
6126 };
6127
6128 if (!isa<Constant>(Val: Step))
6129 // If not a constant step, might increase register pressure
6130 // (We assume constants have been canonicalized to RHS)
6131 continue;
6132
6133 if (BO->getParent() == IVIncInsertPos->getParent())
6134 // Only bother moving across blocks. Isel can handle block local case.
6135 continue;
6136
6137 // Can we legally schedule inc at the desired point?
6138 if (!llvm::all_of(Range: BO->uses(),
6139 P: [&](Use &U) {return DT.dominates(Def: IVIncInsertPos, U);}))
6140 continue;
6141 BO->moveBefore(InsertPos: IVIncInsertPos->getIterator());
6142 Changed = true;
6143 }
6144
6145
6146}
6147
6148LSRInstance::LSRInstance(Loop *L, IVUsers &IU, ScalarEvolution &SE,
6149 DominatorTree &DT, LoopInfo &LI,
6150 const TargetTransformInfo &TTI, AssumptionCache &AC,
6151 TargetLibraryInfo &TLI, MemorySSAUpdater *MSSAU)
6152 : IU(IU), SE(SE), DT(DT), LI(LI), AC(AC), TLI(TLI), TTI(TTI), L(L),
6153 MSSAU(MSSAU), AMK(PreferredAddresingMode.getNumOccurrences() > 0
6154 ? PreferredAddresingMode
6155 : TTI.getPreferredAddressingMode(L, SE: &SE)),
6156 Rewriter(SE, "lsr", false), BaselineCost(L, SE, TTI, AMK) {
6157 // If LoopSimplify form is not available, stay out of trouble.
6158 if (!L->isLoopSimplifyForm())
6159 return;
6160
6161 // If there's no interesting work to be done, bail early.
6162 if (IU.empty()) return;
6163
6164 // If there's too much analysis to be done, bail early. We won't be able to
6165 // model the problem anyway.
6166 unsigned NumUsers = 0;
6167 for (const IVStrideUse &U : IU) {
6168 if (++NumUsers > MaxIVUsers) {
6169 (void)U;
6170 LLVM_DEBUG(dbgs() << "LSR skipping loop, too many IV Users in " << U
6171 << "\n");
6172 return;
6173 }
6174 // Bail out if we have a PHI on an EHPad that gets a value from a
6175 // CatchSwitchInst. Because the CatchSwitchInst cannot be split, there is
6176 // no good place to stick any instructions.
6177 if (auto *PN = dyn_cast<PHINode>(Val: U.getUser())) {
6178 auto FirstNonPHI = PN->getParent()->getFirstNonPHIIt();
6179 if (isa<FuncletPadInst>(Val: FirstNonPHI) ||
6180 isa<CatchSwitchInst>(Val: FirstNonPHI))
6181 for (BasicBlock *PredBB : PN->blocks())
6182 if (isa<CatchSwitchInst>(Val: PredBB->getFirstNonPHIIt()))
6183 return;
6184 }
6185 }
6186
6187 LLVM_DEBUG(dbgs() << "\nLSR on loop ";
6188 L->getHeader()->printAsOperand(dbgs(), /*PrintType=*/false);
6189 dbgs() << ":\n");
6190
6191 // Check if we expect this loop to use a hardware loop instruction, which will
6192 // be used when calculating the costs of formulas.
6193 HardwareLoopInfo HWLoopInfo(L);
6194 HardwareLoopProfitable =
6195 TTI.isHardwareLoopProfitable(L, SE, AC, LibInfo: &TLI, HWLoopInfo);
6196
6197 // Configure SCEVExpander already now, so the correct mode is used for
6198 // isSafeToExpand() checks.
6199#if LLVM_ENABLE_ABI_BREAKING_CHECKS
6200 Rewriter.setDebugType(DEBUG_TYPE);
6201#endif
6202 Rewriter.disableCanonicalMode();
6203 Rewriter.enableLSRMode();
6204
6205 // First, perform some low-level loop optimizations.
6206 OptimizeShadowIV();
6207 OptimizeLoopTermCond();
6208
6209 // If loop preparation eliminates all interesting IV users, bail.
6210 if (IU.empty()) return;
6211
6212 // Skip nested loops until we can model them better with formulae.
6213 if (!L->isInnermost()) {
6214 LLVM_DEBUG(dbgs() << "LSR skipping outer loop " << *L << "\n");
6215 return;
6216 }
6217
6218 // Start collecting data and preparing for the solver.
6219 // If number of registers is not the major cost, we cannot benefit from the
6220 // current profitable chain optimization which is based on number of
6221 // registers.
6222 // FIXME: add profitable chain optimization for other kinds major cost, for
6223 // example number of instructions.
6224 if (TTI.isNumRegsMajorCostOfLSR() || StressIVChain)
6225 CollectChains();
6226 CollectInterestingTypesAndFactors();
6227 CollectFixupsAndInitialFormulae();
6228 CollectLoopInvariantFixupsAndFormulae();
6229
6230 if (Uses.empty())
6231 return;
6232
6233 LLVM_DEBUG(dbgs() << "LSR found " << Uses.size() << " uses:\n";
6234 print_uses(dbgs()));
6235 LLVM_DEBUG(dbgs() << "The baseline solution requires ";
6236 BaselineCost.print(dbgs()); dbgs() << "\n");
6237
6238 // Now use the reuse data to generate a bunch of interesting ways
6239 // to formulate the values needed for the uses.
6240 GenerateAllReuseFormulae();
6241
6242 FilterOutUndesirableDedicatedRegisters();
6243 NarrowSearchSpaceUsingHeuristics();
6244
6245 SmallVector<const Formula *, 8> Solution;
6246 Solve(Solution);
6247
6248 // Release memory that is no longer needed.
6249 Factors.clear();
6250 Types.clear();
6251 RegUses.clear();
6252
6253 if (Solution.empty())
6254 return;
6255
6256#ifndef NDEBUG
6257 // Formulae should be legal.
6258 for (const LSRUse &LU : Uses) {
6259 for (const Formula &F : LU.Formulae)
6260 assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
6261 F) && "Illegal formula generated!");
6262 };
6263#endif
6264
6265 // Now that we've decided what we want, make it so.
6266 ImplementSolution(Solution);
6267}
6268
6269#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
6270void LSRInstance::print_factors_and_types(raw_ostream &OS) const {
6271 if (Factors.empty() && Types.empty()) return;
6272
6273 OS << "LSR has identified the following interesting factors and types: ";
6274 ListSeparator LS;
6275
6276 for (int64_t Factor : Factors)
6277 OS << LS << '*' << Factor;
6278
6279 for (Type *Ty : Types)
6280 OS << LS << '(' << *Ty << ')';
6281 OS << '\n';
6282}
6283
6284void LSRInstance::print_fixups(raw_ostream &OS) const {
6285 OS << "LSR is examining the following fixup sites:\n";
6286 for (const LSRUse &LU : Uses)
6287 for (const LSRFixup &LF : LU.Fixups) {
6288 dbgs() << " ";
6289 LF.print(OS);
6290 OS << '\n';
6291 }
6292}
6293
6294void LSRInstance::print_uses(raw_ostream &OS) const {
6295 OS << "LSR is examining the following uses:\n";
6296 for (const LSRUse &LU : Uses) {
6297 dbgs() << " ";
6298 LU.print(OS);
6299 OS << '\n';
6300 for (const Formula &F : LU.Formulae) {
6301 OS << " ";
6302 F.print(OS);
6303 OS << '\n';
6304 }
6305 }
6306}
6307
6308void LSRInstance::print(raw_ostream &OS) const {
6309 print_factors_and_types(OS);
6310 print_fixups(OS);
6311 print_uses(OS);
6312}
6313
6314LLVM_DUMP_METHOD void LSRInstance::dump() const {
6315 print(errs()); errs() << '\n';
6316}
6317#endif
6318
6319namespace {
6320
6321class LoopStrengthReduce : public LoopPass {
6322public:
6323 static char ID; // Pass ID, replacement for typeid
6324
6325 LoopStrengthReduce();
6326
6327private:
6328 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
6329 void getAnalysisUsage(AnalysisUsage &AU) const override;
6330};
6331
6332} // end anonymous namespace
6333
6334LoopStrengthReduce::LoopStrengthReduce() : LoopPass(ID) {
6335 initializeLoopStrengthReducePass(*PassRegistry::getPassRegistry());
6336}
6337
6338void LoopStrengthReduce::getAnalysisUsage(AnalysisUsage &AU) const {
6339 // We split critical edges, so we change the CFG. However, we do update
6340 // many analyses if they are around.
6341 AU.addPreservedID(ID&: LoopSimplifyID);
6342
6343 AU.addRequired<LoopInfoWrapperPass>();
6344 AU.addPreserved<LoopInfoWrapperPass>();
6345 AU.addRequiredID(ID&: LoopSimplifyID);
6346 AU.addRequired<DominatorTreeWrapperPass>();
6347 AU.addPreserved<DominatorTreeWrapperPass>();
6348 AU.addRequired<ScalarEvolutionWrapperPass>();
6349 AU.addPreserved<ScalarEvolutionWrapperPass>();
6350 AU.addRequired<AssumptionCacheTracker>();
6351 AU.addRequired<TargetLibraryInfoWrapperPass>();
6352 // Requiring LoopSimplify a second time here prevents IVUsers from running
6353 // twice, since LoopSimplify was invalidated by running ScalarEvolution.
6354 AU.addRequiredID(ID&: LoopSimplifyID);
6355 AU.addRequired<IVUsersWrapperPass>();
6356 AU.addPreserved<IVUsersWrapperPass>();
6357 AU.addRequired<TargetTransformInfoWrapperPass>();
6358 AU.addPreserved<MemorySSAWrapperPass>();
6359}
6360
6361namespace {
6362
6363/// Enables more convenient iteration over a DWARF expression vector.
6364static iterator_range<llvm::DIExpression::expr_op_iterator>
6365ToDwarfOpIter(SmallVectorImpl<uint64_t> &Expr) {
6366 llvm::DIExpression::expr_op_iterator Begin =
6367 llvm::DIExpression::expr_op_iterator(Expr.begin());
6368 llvm::DIExpression::expr_op_iterator End =
6369 llvm::DIExpression::expr_op_iterator(Expr.end());
6370 return {Begin, End};
6371}
6372
6373struct SCEVDbgValueBuilder {
6374 SCEVDbgValueBuilder() = default;
6375 SCEVDbgValueBuilder(const SCEVDbgValueBuilder &Base) { clone(Base); }
6376
6377 void clone(const SCEVDbgValueBuilder &Base) {
6378 LocationOps = Base.LocationOps;
6379 Expr = Base.Expr;
6380 }
6381
6382 void clear() {
6383 LocationOps.clear();
6384 Expr.clear();
6385 }
6386
6387 /// The DIExpression as we translate the SCEV.
6388 SmallVector<uint64_t, 6> Expr;
6389 /// The location ops of the DIExpression.
6390 SmallVector<Value *, 2> LocationOps;
6391
6392 void pushOperator(uint64_t Op) { Expr.push_back(Elt: Op); }
6393 void pushUInt(uint64_t Operand) { Expr.push_back(Elt: Operand); }
6394
6395 /// Add a DW_OP_LLVM_arg to the expression, followed by the index of the value
6396 /// in the set of values referenced by the expression.
6397 void pushLocation(llvm::Value *V) {
6398 Expr.push_back(Elt: llvm::dwarf::DW_OP_LLVM_arg);
6399 auto *It = llvm::find(Range&: LocationOps, Val: V);
6400 unsigned ArgIndex = 0;
6401 if (It != LocationOps.end()) {
6402 ArgIndex = std::distance(first: LocationOps.begin(), last: It);
6403 } else {
6404 ArgIndex = LocationOps.size();
6405 LocationOps.push_back(Elt: V);
6406 }
6407 Expr.push_back(Elt: ArgIndex);
6408 }
6409
6410 void pushValue(const SCEVUnknown *U) {
6411 llvm::Value *V = cast<SCEVUnknown>(Val: U)->getValue();
6412 pushLocation(V);
6413 }
6414
6415 bool pushConst(const SCEVConstant *C) {
6416 if (C->getAPInt().getSignificantBits() > 64)
6417 return false;
6418 Expr.push_back(Elt: llvm::dwarf::DW_OP_consts);
6419 Expr.push_back(Elt: C->getAPInt().getSExtValue());
6420 return true;
6421 }
6422
6423 // Iterating the expression as DWARF ops is convenient when updating
6424 // DWARF_OP_LLVM_args.
6425 iterator_range<llvm::DIExpression::expr_op_iterator> expr_ops() {
6426 return ToDwarfOpIter(Expr);
6427 }
6428
6429 /// Several SCEV types are sequences of the same arithmetic operator applied
6430 /// to constants and values that may be extended or truncated.
6431 bool pushArithmeticExpr(const llvm::SCEVCommutativeExpr *CommExpr,
6432 uint64_t DwarfOp) {
6433 assert((isa<llvm::SCEVAddExpr>(CommExpr) || isa<SCEVMulExpr>(CommExpr)) &&
6434 "Expected arithmetic SCEV type");
6435 bool Success = true;
6436 unsigned EmitOperator = 0;
6437 for (const auto &Op : CommExpr->operands()) {
6438 Success &= pushSCEV(S: Op);
6439
6440 if (EmitOperator >= 1)
6441 pushOperator(Op: DwarfOp);
6442 ++EmitOperator;
6443 }
6444 return Success;
6445 }
6446
6447 // TODO: Identify and omit noop casts.
6448 bool pushCast(const llvm::SCEVCastExpr *C, bool IsSigned) {
6449 const llvm::SCEV *Inner = C->getOperand(i: 0);
6450 const llvm::Type *Type = C->getType();
6451 uint64_t ToWidth = Type->getIntegerBitWidth();
6452 bool Success = pushSCEV(S: Inner);
6453 uint64_t CastOps[] = {dwarf::DW_OP_LLVM_convert, ToWidth,
6454 IsSigned ? llvm::dwarf::DW_ATE_signed
6455 : llvm::dwarf::DW_ATE_unsigned};
6456 for (const auto &Op : CastOps)
6457 pushOperator(Op);
6458 return Success;
6459 }
6460
6461 // TODO: MinMax - although these haven't been encountered in the test suite.
6462 bool pushSCEV(const llvm::SCEV *S) {
6463 bool Success = true;
6464 if (const SCEVConstant *StartInt = dyn_cast<SCEVConstant>(Val: S)) {
6465 Success &= pushConst(C: StartInt);
6466
6467 } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Val: S)) {
6468 if (!U->getValue())
6469 return false;
6470 pushLocation(V: U->getValue());
6471
6472 } else if (const SCEVMulExpr *MulRec = dyn_cast<SCEVMulExpr>(Val: S)) {
6473 Success &= pushArithmeticExpr(CommExpr: MulRec, DwarfOp: llvm::dwarf::DW_OP_mul);
6474
6475 } else if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(Val: S)) {
6476 Success &= pushSCEV(S: UDiv->getLHS());
6477 Success &= pushSCEV(S: UDiv->getRHS());
6478 pushOperator(Op: llvm::dwarf::DW_OP_div);
6479
6480 } else if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(Val: S)) {
6481 // Assert if a new and unknown SCEVCastEXpr type is encountered.
6482 assert((isa<SCEVZeroExtendExpr>(Cast) || isa<SCEVTruncateExpr>(Cast) ||
6483 isa<SCEVPtrToIntExpr>(Cast) || isa<SCEVPtrToAddrExpr>(Cast) ||
6484 isa<SCEVSignExtendExpr>(Cast)) &&
6485 "Unexpected cast type in SCEV.");
6486 Success &= pushCast(C: Cast, IsSigned: (isa<SCEVSignExtendExpr>(Val: Cast)));
6487
6488 } else if (const SCEVAddExpr *AddExpr = dyn_cast<SCEVAddExpr>(Val: S)) {
6489 Success &= pushArithmeticExpr(CommExpr: AddExpr, DwarfOp: llvm::dwarf::DW_OP_plus);
6490
6491 } else if (isa<SCEVAddRecExpr>(Val: S)) {
6492 // Nested SCEVAddRecExpr are generated by nested loops and are currently
6493 // unsupported.
6494 return false;
6495
6496 } else {
6497 return false;
6498 }
6499 return Success;
6500 }
6501
6502 /// Return true if the combination of arithmetic operator and underlying
6503 /// SCEV constant value is an identity function.
6504 bool isIdentityFunction(uint64_t Op, const SCEV *S) {
6505 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Val: S)) {
6506 if (C->getAPInt().getSignificantBits() > 64)
6507 return false;
6508 int64_t I = C->getAPInt().getSExtValue();
6509 switch (Op) {
6510 case llvm::dwarf::DW_OP_plus:
6511 case llvm::dwarf::DW_OP_minus:
6512 return I == 0;
6513 case llvm::dwarf::DW_OP_mul:
6514 case llvm::dwarf::DW_OP_div:
6515 return I == 1;
6516 }
6517 }
6518 return false;
6519 }
6520
6521 /// Convert a SCEV of a value to a DIExpression that is pushed onto the
6522 /// builder's expression stack. The stack should already contain an
6523 /// expression for the iteration count, so that it can be multiplied by
6524 /// the stride and added to the start.
6525 /// Components of the expression are omitted if they are an identity function.
6526 /// Chain (non-affine) SCEVs are not supported.
6527 bool SCEVToValueExpr(const llvm::SCEVAddRecExpr &SAR, ScalarEvolution &SE) {
6528 assert(SAR.isAffine() && "Expected affine SCEV");
6529 const SCEV *Start = SAR.getStart();
6530 const SCEV *Stride = SAR.getStepRecurrence(SE);
6531
6532 // Skip pushing arithmetic noops.
6533 if (!isIdentityFunction(Op: llvm::dwarf::DW_OP_mul, S: Stride)) {
6534 if (!pushSCEV(S: Stride))
6535 return false;
6536 pushOperator(Op: llvm::dwarf::DW_OP_mul);
6537 }
6538 if (!isIdentityFunction(Op: llvm::dwarf::DW_OP_plus, S: Start)) {
6539 if (!pushSCEV(S: Start))
6540 return false;
6541 pushOperator(Op: llvm::dwarf::DW_OP_plus);
6542 }
6543 return true;
6544 }
6545
6546 /// Create an expression that is an offset from a value (usually the IV).
6547 void createOffsetExpr(int64_t Offset, Value *OffsetValue) {
6548 pushLocation(V: OffsetValue);
6549 DIExpression::appendOffset(Ops&: Expr, Offset);
6550 LLVM_DEBUG(
6551 dbgs() << "scev-salvage: Generated IV offset expression. Offset: "
6552 << std::to_string(Offset) << "\n");
6553 }
6554
6555 /// Combine a translation of the SCEV and the IV to create an expression that
6556 /// recovers a location's value.
6557 /// returns true if an expression was created.
6558 bool createIterCountExpr(const SCEV *S,
6559 const SCEVDbgValueBuilder &IterationCount,
6560 ScalarEvolution &SE) {
6561 // SCEVs for SSA values are most frquently of the form
6562 // {start,+,stride}, but sometimes they are ({start,+,stride} + %a + ..).
6563 // This is because %a is a PHI node that is not the IV. However, these
6564 // SCEVs have not been observed to result in debuginfo-lossy optimisations,
6565 // so its not expected this point will be reached.
6566 if (!isa<SCEVAddRecExpr>(Val: S))
6567 return false;
6568
6569 LLVM_DEBUG(dbgs() << "scev-salvage: Location to salvage SCEV: " << *S
6570 << '\n');
6571
6572 const auto *Rec = cast<SCEVAddRecExpr>(Val: S);
6573 if (!Rec->isAffine())
6574 return false;
6575
6576 if (S->getExpressionSize() > MaxSCEVSalvageExpressionSize)
6577 return false;
6578
6579 // Initialise a new builder with the iteration count expression. In
6580 // combination with the value's SCEV this enables recovery.
6581 clone(Base: IterationCount);
6582 if (!SCEVToValueExpr(SAR: *Rec, SE))
6583 return false;
6584
6585 return true;
6586 }
6587
6588 /// Convert a SCEV of a value to a DIExpression that is pushed onto the
6589 /// builder's expression stack. The stack should already contain an
6590 /// expression for the iteration count, so that it can be multiplied by
6591 /// the stride and added to the start.
6592 /// Components of the expression are omitted if they are an identity function.
6593 bool SCEVToIterCountExpr(const llvm::SCEVAddRecExpr &SAR,
6594 ScalarEvolution &SE) {
6595 assert(SAR.isAffine() && "Expected affine SCEV");
6596 const SCEV *Start = SAR.getStart();
6597 const SCEV *Stride = SAR.getStepRecurrence(SE);
6598
6599 // Skip pushing arithmetic noops.
6600 if (!isIdentityFunction(Op: llvm::dwarf::DW_OP_minus, S: Start)) {
6601 if (!pushSCEV(S: Start))
6602 return false;
6603 pushOperator(Op: llvm::dwarf::DW_OP_minus);
6604 }
6605 if (!isIdentityFunction(Op: llvm::dwarf::DW_OP_div, S: Stride)) {
6606 if (!pushSCEV(S: Stride))
6607 return false;
6608 pushOperator(Op: llvm::dwarf::DW_OP_div);
6609 }
6610 return true;
6611 }
6612
6613 // Append the current expression and locations to a location list and an
6614 // expression list. Modify the DW_OP_LLVM_arg indexes to account for
6615 // the locations already present in the destination list.
6616 void appendToVectors(SmallVectorImpl<uint64_t> &DestExpr,
6617 SmallVectorImpl<Value *> &DestLocations) {
6618 assert(!DestLocations.empty() &&
6619 "Expected the locations vector to contain the IV");
6620 // The DWARF_OP_LLVM_arg arguments of the expression being appended must be
6621 // modified to account for the locations already in the destination vector.
6622 // All builders contain the IV as the first location op.
6623 assert(!LocationOps.empty() &&
6624 "Expected the location ops to contain the IV.");
6625 // DestIndexMap[n] contains the index in DestLocations for the nth
6626 // location in this SCEVDbgValueBuilder.
6627 SmallVector<uint64_t, 2> DestIndexMap;
6628 for (const auto &Op : LocationOps) {
6629 auto It = find(Range&: DestLocations, Val: Op);
6630 if (It != DestLocations.end()) {
6631 // Location already exists in DestLocations, reuse existing ArgIndex.
6632 DestIndexMap.push_back(Elt: std::distance(first: DestLocations.begin(), last: It));
6633 continue;
6634 }
6635 // Location is not in DestLocations, add it.
6636 DestIndexMap.push_back(Elt: DestLocations.size());
6637 DestLocations.push_back(Elt: Op);
6638 }
6639
6640 for (const auto &Op : expr_ops()) {
6641 if (Op.getOp() != dwarf::DW_OP_LLVM_arg) {
6642 Op.appendToVector(V&: DestExpr);
6643 continue;
6644 }
6645
6646 DestExpr.push_back(Elt: dwarf::DW_OP_LLVM_arg);
6647 // `DW_OP_LLVM_arg n` represents the nth LocationOp in this SCEV,
6648 // DestIndexMap[n] contains its new index in DestLocations.
6649 uint64_t NewIndex = DestIndexMap[Op.getArg(I: 0)];
6650 DestExpr.push_back(Elt: NewIndex);
6651 }
6652 }
6653};
6654
6655/// Holds all the required data to salvage a dbg.value using the pre-LSR SCEVs
6656/// and DIExpression.
6657struct DVIRecoveryRec {
6658 DVIRecoveryRec(DbgVariableRecord *DVR)
6659 : DbgRef(DVR), Expr(DVR->getExpression()), HadLocationArgList(false) {}
6660
6661 DbgVariableRecord *DbgRef;
6662 DIExpression *Expr;
6663 bool HadLocationArgList;
6664 SmallVector<WeakVH, 2> LocationOps;
6665 SmallVector<const llvm::SCEV *, 2> SCEVs;
6666 SmallVector<std::unique_ptr<SCEVDbgValueBuilder>, 2> RecoveryExprs;
6667
6668 void clear() {
6669 for (auto &RE : RecoveryExprs)
6670 RE.reset();
6671 RecoveryExprs.clear();
6672 }
6673
6674 ~DVIRecoveryRec() { clear(); }
6675};
6676} // namespace
6677
6678/// Returns the total number of DW_OP_llvm_arg operands in the expression.
6679/// This helps in determining if a DIArglist is necessary or can be omitted from
6680/// the dbg.value.
6681static unsigned numLLVMArgOps(SmallVectorImpl<uint64_t> &Expr) {
6682 auto expr_ops = ToDwarfOpIter(Expr);
6683 unsigned Count = 0;
6684 for (auto Op : expr_ops)
6685 if (Op.getOp() == dwarf::DW_OP_LLVM_arg)
6686 Count++;
6687 return Count;
6688}
6689
6690/// Overwrites DVI with the location and Ops as the DIExpression. This will
6691/// create an invalid expression if Ops has any dwarf::DW_OP_llvm_arg operands,
6692/// because a DIArglist is not created for the first argument of the dbg.value.
6693template <typename T>
6694static void updateDVIWithLocation(T &DbgVal, Value *Location,
6695 SmallVectorImpl<uint64_t> &Ops) {
6696 assert(numLLVMArgOps(Ops) == 0 && "Expected expression that does not "
6697 "contain any DW_OP_llvm_arg operands.");
6698 DbgVal.setRawLocation(ValueAsMetadata::get(V: Location));
6699 DbgVal.setExpression(DIExpression::get(Context&: DbgVal.getContext(), Elements: Ops));
6700 DbgVal.setExpression(DIExpression::get(Context&: DbgVal.getContext(), Elements: Ops));
6701}
6702
6703/// Overwrite DVI with locations placed into a DIArglist.
6704template <typename T>
6705static void updateDVIWithLocations(T &DbgVal,
6706 SmallVectorImpl<Value *> &Locations,
6707 SmallVectorImpl<uint64_t> &Ops) {
6708 assert(numLLVMArgOps(Ops) != 0 &&
6709 "Expected expression that references DIArglist locations using "
6710 "DW_OP_llvm_arg operands.");
6711 SmallVector<ValueAsMetadata *, 3> MetadataLocs;
6712 for (Value *V : Locations)
6713 MetadataLocs.push_back(Elt: ValueAsMetadata::get(V));
6714 auto ValArrayRef = llvm::ArrayRef<llvm::ValueAsMetadata *>(MetadataLocs);
6715 DbgVal.setRawLocation(llvm::DIArgList::get(Context&: DbgVal.getContext(), Args: ValArrayRef));
6716 DbgVal.setExpression(DIExpression::get(Context&: DbgVal.getContext(), Elements: Ops));
6717}
6718
6719/// Write the new expression and new location ops for the dbg.value. If possible
6720/// reduce the szie of the dbg.value by omitting DIArglist. This
6721/// can be omitted if:
6722/// 1. There is only a single location, refenced by a single DW_OP_llvm_arg.
6723/// 2. The DW_OP_LLVM_arg is the first operand in the expression.
6724static void UpdateDbgValue(DVIRecoveryRec &DVIRec,
6725 SmallVectorImpl<Value *> &NewLocationOps,
6726 SmallVectorImpl<uint64_t> &NewExpr) {
6727 DbgVariableRecord *DbgVal = DVIRec.DbgRef;
6728 unsigned NumLLVMArgs = numLLVMArgOps(Expr&: NewExpr);
6729 if (NumLLVMArgs == 0) {
6730 // Location assumed to be on the stack.
6731 updateDVIWithLocation(DbgVal&: *DbgVal, Location: NewLocationOps[0], Ops&: NewExpr);
6732 } else if (NumLLVMArgs == 1 && NewExpr[0] == dwarf::DW_OP_LLVM_arg) {
6733 // There is only a single DW_OP_llvm_arg at the start of the expression,
6734 // so it can be omitted along with DIArglist.
6735 assert(NewExpr[1] == 0 &&
6736 "Lone LLVM_arg in a DIExpression should refer to location-op 0.");
6737 llvm::SmallVector<uint64_t, 6> ShortenedOps(llvm::drop_begin(RangeOrContainer&: NewExpr, N: 2));
6738 updateDVIWithLocation(DbgVal&: *DbgVal, Location: NewLocationOps[0], Ops&: ShortenedOps);
6739 } else {
6740 // Multiple DW_OP_llvm_arg, so DIArgList is strictly necessary.
6741 updateDVIWithLocations(DbgVal&: *DbgVal, Locations&: NewLocationOps, Ops&: NewExpr);
6742 }
6743
6744 // If the DIExpression was previously empty then add the stack terminator.
6745 // Non-empty expressions have only had elements inserted into them and so
6746 // the terminator should already be present e.g. stack_value or fragment.
6747 DIExpression *SalvageExpr = DbgVal->getExpression();
6748 if (!DVIRec.Expr->isComplex() && SalvageExpr->isComplex()) {
6749 SalvageExpr = DIExpression::append(Expr: SalvageExpr, Ops: {dwarf::DW_OP_stack_value});
6750 DbgVal->setExpression(SalvageExpr);
6751 }
6752}
6753
6754/// Cached location ops may be erased during LSR, in which case a poison is
6755/// required when restoring from the cache. The type of that location is no
6756/// longer available, so just use int8. The poison will be replaced by one or
6757/// more locations later when a SCEVDbgValueBuilder selects alternative
6758/// locations to use for the salvage.
6759static Value *getValueOrPoison(WeakVH &VH, LLVMContext &C) {
6760 return (VH) ? VH : PoisonValue::get(T: llvm::Type::getInt8Ty(C));
6761}
6762
6763/// Restore the DVI's pre-LSR arguments. Substitute undef for any erased values.
6764static void restorePreTransformState(DVIRecoveryRec &DVIRec) {
6765 DbgVariableRecord *DbgVal = DVIRec.DbgRef;
6766 LLVM_DEBUG(dbgs() << "scev-salvage: restore dbg.value to pre-LSR state\n"
6767 << "scev-salvage: post-LSR: " << *DbgVal << '\n');
6768 assert(DVIRec.Expr && "Expected an expression");
6769 DbgVal->setExpression(DVIRec.Expr);
6770
6771 // Even a single location-op may be inside a DIArgList and referenced with
6772 // DW_OP_LLVM_arg, which is valid only with a DIArgList.
6773 if (!DVIRec.HadLocationArgList) {
6774 assert(DVIRec.LocationOps.size() == 1 &&
6775 "Unexpected number of location ops.");
6776 // LSR's unsuccessful salvage attempt may have added DIArgList, which in
6777 // this case was not present before, so force the location back to a
6778 // single uncontained Value.
6779 Value *CachedValue =
6780 getValueOrPoison(VH&: DVIRec.LocationOps[0], C&: DbgVal->getContext());
6781 DbgVal->setRawLocation(ValueAsMetadata::get(V: CachedValue));
6782 } else {
6783 SmallVector<ValueAsMetadata *, 3> MetadataLocs;
6784 for (WeakVH VH : DVIRec.LocationOps) {
6785 Value *CachedValue = getValueOrPoison(VH, C&: DbgVal->getContext());
6786 MetadataLocs.push_back(Elt: ValueAsMetadata::get(V: CachedValue));
6787 }
6788 auto ValArrayRef = llvm::ArrayRef<llvm::ValueAsMetadata *>(MetadataLocs);
6789 DbgVal->setRawLocation(
6790 llvm::DIArgList::get(Context&: DbgVal->getContext(), Args: ValArrayRef));
6791 }
6792 LLVM_DEBUG(dbgs() << "scev-salvage: pre-LSR: " << *DbgVal << '\n');
6793}
6794
6795static bool SalvageDVI(llvm::Loop *L, ScalarEvolution &SE,
6796 llvm::PHINode *LSRInductionVar, DVIRecoveryRec &DVIRec,
6797 const SCEV *SCEVInductionVar,
6798 SCEVDbgValueBuilder IterCountExpr) {
6799
6800 if (!DVIRec.DbgRef->isKillLocation())
6801 return false;
6802
6803 // LSR may have caused several changes to the dbg.value in the failed salvage
6804 // attempt. So restore the DIExpression, the location ops and also the
6805 // location ops format, which is always DIArglist for multiple ops, but only
6806 // sometimes for a single op.
6807 restorePreTransformState(DVIRec);
6808
6809 // LocationOpIndexMap[i] will store the post-LSR location index of
6810 // the non-optimised out location at pre-LSR index i.
6811 SmallVector<int64_t, 2> LocationOpIndexMap;
6812 LocationOpIndexMap.assign(NumElts: DVIRec.LocationOps.size(), Elt: -1);
6813 SmallVector<Value *, 2> NewLocationOps;
6814 NewLocationOps.push_back(Elt: LSRInductionVar);
6815
6816 for (unsigned i = 0; i < DVIRec.LocationOps.size(); i++) {
6817 WeakVH VH = DVIRec.LocationOps[i];
6818 // Place the locations not optimised out in the list first, avoiding
6819 // inserts later. The map is used to update the DIExpression's
6820 // DW_OP_LLVM_arg arguments as the expression is updated.
6821 if (VH && !isa<UndefValue>(Val: VH)) {
6822 NewLocationOps.push_back(Elt: VH);
6823 LocationOpIndexMap[i] = NewLocationOps.size() - 1;
6824 LLVM_DEBUG(dbgs() << "scev-salvage: Location index " << i
6825 << " now at index " << LocationOpIndexMap[i] << "\n");
6826 continue;
6827 }
6828
6829 // It's possible that a value referred to in the SCEV may have been
6830 // optimised out by LSR.
6831 if (SE.containsErasedValue(S: DVIRec.SCEVs[i]) ||
6832 SE.containsUndefs(S: DVIRec.SCEVs[i])) {
6833 LLVM_DEBUG(dbgs() << "scev-salvage: SCEV for location at index: " << i
6834 << " refers to a location that is now undef or erased. "
6835 "Salvage abandoned.\n");
6836 return false;
6837 }
6838
6839 LLVM_DEBUG(dbgs() << "scev-salvage: salvaging location at index " << i
6840 << " with SCEV: " << *DVIRec.SCEVs[i] << "\n");
6841
6842 DVIRec.RecoveryExprs[i] = std::make_unique<SCEVDbgValueBuilder>();
6843 SCEVDbgValueBuilder *SalvageExpr = DVIRec.RecoveryExprs[i].get();
6844
6845 // Create an offset-based salvage expression if possible, as it requires
6846 // less DWARF ops than an iteration count-based expression.
6847 if (std::optional<APInt> Offset =
6848 SE.computeConstantDifference(LHS: DVIRec.SCEVs[i], RHS: SCEVInductionVar)) {
6849 if (Offset->getSignificantBits() <= 64)
6850 SalvageExpr->createOffsetExpr(Offset: Offset->getSExtValue(), OffsetValue: LSRInductionVar);
6851 else
6852 return false;
6853 } else if (!SalvageExpr->createIterCountExpr(S: DVIRec.SCEVs[i], IterationCount: IterCountExpr,
6854 SE))
6855 return false;
6856 }
6857
6858 // Merge the DbgValueBuilder generated expressions and the original
6859 // DIExpression, place the result into an new vector.
6860 SmallVector<uint64_t, 3> NewExpr;
6861 if (DVIRec.Expr->getNumElements() == 0) {
6862 assert(DVIRec.RecoveryExprs.size() == 1 &&
6863 "Expected only a single recovery expression for an empty "
6864 "DIExpression.");
6865 assert(DVIRec.RecoveryExprs[0] &&
6866 "Expected a SCEVDbgSalvageBuilder for location 0");
6867 SCEVDbgValueBuilder *B = DVIRec.RecoveryExprs[0].get();
6868 B->appendToVectors(DestExpr&: NewExpr, DestLocations&: NewLocationOps);
6869 }
6870 for (const auto &Op : DVIRec.Expr->expr_ops()) {
6871 // Most Ops needn't be updated.
6872 if (Op.getOp() != dwarf::DW_OP_LLVM_arg) {
6873 Op.appendToVector(V&: NewExpr);
6874 continue;
6875 }
6876
6877 uint64_t LocationArgIndex = Op.getArg(I: 0);
6878 SCEVDbgValueBuilder *DbgBuilder =
6879 DVIRec.RecoveryExprs[LocationArgIndex].get();
6880 // The location doesn't have s SCEVDbgValueBuilder, so LSR did not
6881 // optimise it away. So just translate the argument to the updated
6882 // location index.
6883 if (!DbgBuilder) {
6884 NewExpr.push_back(Elt: dwarf::DW_OP_LLVM_arg);
6885 assert(LocationOpIndexMap[Op.getArg(0)] != -1 &&
6886 "Expected a positive index for the location-op position.");
6887 NewExpr.push_back(Elt: LocationOpIndexMap[Op.getArg(I: 0)]);
6888 continue;
6889 }
6890 // The location has a recovery expression.
6891 DbgBuilder->appendToVectors(DestExpr&: NewExpr, DestLocations&: NewLocationOps);
6892 }
6893
6894 UpdateDbgValue(DVIRec, NewLocationOps, NewExpr);
6895 LLVM_DEBUG(dbgs() << "scev-salvage: Updated DVI: " << *DVIRec.DbgRef << "\n");
6896 return true;
6897}
6898
6899/// Obtain an expression for the iteration count, then attempt to salvage the
6900/// dbg.value intrinsics.
6901static void DbgRewriteSalvageableDVIs(
6902 llvm::Loop *L, ScalarEvolution &SE, llvm::PHINode *LSRInductionVar,
6903 SmallVector<std::unique_ptr<DVIRecoveryRec>, 2> &DVIToUpdate) {
6904 if (DVIToUpdate.empty())
6905 return;
6906
6907 const llvm::SCEV *SCEVInductionVar = SE.getSCEV(V: LSRInductionVar);
6908 assert(SCEVInductionVar &&
6909 "Anticipated a SCEV for the post-LSR induction variable");
6910
6911 if (const SCEVAddRecExpr *IVAddRec =
6912 dyn_cast<SCEVAddRecExpr>(Val: SCEVInductionVar)) {
6913 if (!IVAddRec->isAffine())
6914 return;
6915
6916 // Prevent translation using excessive resources.
6917 if (IVAddRec->getExpressionSize() > MaxSCEVSalvageExpressionSize)
6918 return;
6919
6920 // The iteration count is required to recover location values.
6921 SCEVDbgValueBuilder IterCountExpr;
6922 IterCountExpr.pushLocation(V: LSRInductionVar);
6923 if (!IterCountExpr.SCEVToIterCountExpr(SAR: *IVAddRec, SE))
6924 return;
6925
6926 LLVM_DEBUG(dbgs() << "scev-salvage: IV SCEV: " << *SCEVInductionVar
6927 << '\n');
6928
6929 for (auto &DVIRec : DVIToUpdate) {
6930 SalvageDVI(L, SE, LSRInductionVar, DVIRec&: *DVIRec, SCEVInductionVar,
6931 IterCountExpr);
6932 }
6933 }
6934}
6935
6936/// Identify and cache salvageable DVI locations and expressions along with the
6937/// corresponding SCEV(s). Also ensure that the DVI is not deleted between
6938/// cacheing and salvaging.
6939static void DbgGatherSalvagableDVI(
6940 Loop *L, ScalarEvolution &SE,
6941 SmallVector<std::unique_ptr<DVIRecoveryRec>, 2> &SalvageableDVISCEVs) {
6942 for (const auto &B : L->getBlocks()) {
6943 for (auto &I : *B) {
6944 for (DbgVariableRecord &DbgVal : filterDbgVars(R: I.getDbgRecordRange())) {
6945 if (!DbgVal.isDbgValue() && !DbgVal.isDbgAssign())
6946 continue;
6947
6948 // Ensure that if any location op is undef that the dbg.vlue is not
6949 // cached.
6950 if (DbgVal.isKillLocation())
6951 continue;
6952
6953 // Check that the location op SCEVs are suitable for translation to
6954 // DIExpression.
6955 const auto &HasTranslatableLocationOps =
6956 [&](const DbgVariableRecord &DbgValToTranslate) -> bool {
6957 for (const auto LocOp : DbgValToTranslate.location_ops()) {
6958 if (!LocOp)
6959 return false;
6960
6961 if (!SE.isSCEVable(Ty: LocOp->getType()))
6962 return false;
6963
6964 const SCEV *S = SE.getSCEV(V: LocOp);
6965 if (SE.containsUndefs(S))
6966 return false;
6967 }
6968 return true;
6969 };
6970
6971 if (!HasTranslatableLocationOps(DbgVal))
6972 continue;
6973
6974 std::unique_ptr<DVIRecoveryRec> NewRec =
6975 std::make_unique<DVIRecoveryRec>(args: &DbgVal);
6976 // Each location Op may need a SCEVDbgValueBuilder in order to recover
6977 // it. Pre-allocating a vector will enable quick lookups of the builder
6978 // later during the salvage.
6979 NewRec->RecoveryExprs.resize(N: DbgVal.getNumVariableLocationOps());
6980 for (const auto LocOp : DbgVal.location_ops()) {
6981 NewRec->SCEVs.push_back(Elt: SE.getSCEV(V: LocOp));
6982 NewRec->LocationOps.push_back(Elt: LocOp);
6983 NewRec->HadLocationArgList = DbgVal.hasArgList();
6984 }
6985 SalvageableDVISCEVs.push_back(Elt: std::move(NewRec));
6986 }
6987 }
6988 }
6989}
6990
6991/// Ideally pick the PHI IV inserted by ScalarEvolutionExpander. As a fallback
6992/// any PHi from the loop header is usable, but may have less chance of
6993/// surviving subsequent transforms.
6994static llvm::PHINode *GetInductionVariable(const Loop &L, ScalarEvolution &SE,
6995 const LSRInstance &LSR) {
6996
6997 auto IsSuitableIV = [&](PHINode *P) {
6998 if (!SE.isSCEVable(Ty: P->getType()))
6999 return false;
7000 if (const SCEVAddRecExpr *Rec = dyn_cast<SCEVAddRecExpr>(Val: SE.getSCEV(V: P)))
7001 return Rec->isAffine() && !SE.containsUndefs(S: SE.getSCEV(V: P));
7002 return false;
7003 };
7004
7005 // For now, just pick the first IV that was generated and inserted by
7006 // ScalarEvolution. Ideally pick an IV that is unlikely to be optimised away
7007 // by subsequent transforms.
7008 for (const WeakVH &IV : LSR.getScalarEvolutionIVs()) {
7009 if (!IV)
7010 continue;
7011
7012 // There should only be PHI node IVs.
7013 PHINode *P = cast<PHINode>(Val: &*IV);
7014
7015 if (IsSuitableIV(P))
7016 return P;
7017 }
7018
7019 for (PHINode &P : L.getHeader()->phis()) {
7020 if (IsSuitableIV(&P))
7021 return &P;
7022 }
7023 return nullptr;
7024}
7025
7026static bool ReduceLoopStrength(Loop *L, IVUsers &IU, ScalarEvolution &SE,
7027 DominatorTree &DT, LoopInfo &LI,
7028 const TargetTransformInfo &TTI,
7029 AssumptionCache &AC, TargetLibraryInfo &TLI,
7030 MemorySSA *MSSA) {
7031
7032 // Debug preservation - before we start removing anything identify which DVI
7033 // meet the salvageable criteria and store their DIExpression and SCEVs.
7034 SmallVector<std::unique_ptr<DVIRecoveryRec>, 2> SalvageableDVIRecords;
7035 DbgGatherSalvagableDVI(L, SE, SalvageableDVISCEVs&: SalvageableDVIRecords);
7036
7037 bool Changed = false;
7038 std::unique_ptr<MemorySSAUpdater> MSSAU;
7039 if (MSSA)
7040 MSSAU = std::make_unique<MemorySSAUpdater>(args&: MSSA);
7041
7042 // Run the main LSR transformation.
7043 const LSRInstance &Reducer =
7044 LSRInstance(L, IU, SE, DT, LI, TTI, AC, TLI, MSSAU.get());
7045 Changed |= Reducer.getChanged();
7046
7047 // Remove any extra phis created by processing inner loops.
7048 Changed |= DeleteDeadPHIs(BB: L->getHeader(), TLI: &TLI, MSSAU: MSSAU.get());
7049 if (EnablePhiElim && L->isLoopSimplifyForm()) {
7050 SmallVector<WeakTrackingVH, 16> DeadInsts;
7051 SCEVExpander Rewriter(SE, "lsr", false);
7052#if LLVM_ENABLE_ABI_BREAKING_CHECKS
7053 Rewriter.setDebugType(DEBUG_TYPE);
7054#endif
7055 unsigned numFolded = Rewriter.replaceCongruentIVs(L, DT: &DT, DeadInsts, TTI: &TTI);
7056 Rewriter.clear();
7057 if (numFolded) {
7058 Changed = true;
7059 RecursivelyDeleteTriviallyDeadInstructionsPermissive(DeadInsts, TLI: &TLI,
7060 MSSAU: MSSAU.get());
7061 DeleteDeadPHIs(BB: L->getHeader(), TLI: &TLI, MSSAU: MSSAU.get());
7062 }
7063 }
7064 // LSR may at times remove all uses of an induction variable from a loop.
7065 // The only remaining use is the PHI in the exit block.
7066 // When this is the case, if the exit value of the IV can be calculated using
7067 // SCEV, we can replace the exit block PHI with the final value of the IV and
7068 // skip the updates in each loop iteration.
7069 if (L->isRecursivelyLCSSAForm(DT, LI) && L->getExitBlock()) {
7070 SmallVector<WeakTrackingVH, 16> DeadInsts;
7071 SCEVExpander Rewriter(SE, "lsr", true);
7072 int Rewrites = rewriteLoopExitValues(L, LI: &LI, TLI: &TLI, SE: &SE, TTI: &TTI, Rewriter, DT: &DT,
7073 ReplaceExitValue: UnusedIndVarInLoop, DeadInsts);
7074 Rewriter.clear();
7075 if (Rewrites) {
7076 Changed = true;
7077 RecursivelyDeleteTriviallyDeadInstructionsPermissive(DeadInsts, TLI: &TLI,
7078 MSSAU: MSSAU.get());
7079 DeleteDeadPHIs(BB: L->getHeader(), TLI: &TLI, MSSAU: MSSAU.get());
7080 }
7081 }
7082
7083 if (SalvageableDVIRecords.empty())
7084 return Changed;
7085
7086 // Obtain relevant IVs and attempt to rewrite the salvageable DVIs with
7087 // expressions composed using the derived iteration count.
7088 // TODO: Allow for multiple IV references for nested AddRecSCEVs
7089 for (const auto &L : LI) {
7090 if (llvm::PHINode *IV = GetInductionVariable(L: *L, SE, LSR: Reducer))
7091 DbgRewriteSalvageableDVIs(L, SE, LSRInductionVar: IV, DVIToUpdate&: SalvageableDVIRecords);
7092 else {
7093 LLVM_DEBUG(dbgs() << "scev-salvage: SCEV salvaging not possible. An IV "
7094 "could not be identified.\n");
7095 }
7096 }
7097
7098 for (auto &Rec : SalvageableDVIRecords)
7099 Rec->clear();
7100 SalvageableDVIRecords.clear();
7101 return Changed;
7102}
7103
7104bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager & /*LPM*/) {
7105 if (skipLoop(L))
7106 return false;
7107
7108 auto &IU = getAnalysis<IVUsersWrapperPass>().getIU();
7109 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
7110 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
7111 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
7112 const auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
7113 F: *L->getHeader()->getParent());
7114 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
7115 F&: *L->getHeader()->getParent());
7116 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(
7117 F: *L->getHeader()->getParent());
7118 auto *MSSAAnalysis = getAnalysisIfAvailable<MemorySSAWrapperPass>();
7119 MemorySSA *MSSA = nullptr;
7120 if (MSSAAnalysis)
7121 MSSA = &MSSAAnalysis->getMSSA();
7122 return ReduceLoopStrength(L, IU, SE, DT, LI, TTI, AC, TLI, MSSA);
7123}
7124
7125PreservedAnalyses LoopStrengthReducePass::run(Loop &L, LoopAnalysisManager &AM,
7126 LoopStandardAnalysisResults &AR,
7127 LPMUpdater &) {
7128 if (!ReduceLoopStrength(L: &L, IU&: AM.getResult<IVUsersAnalysis>(IR&: L, ExtraArgs&: AR), SE&: AR.SE,
7129 DT&: AR.DT, LI&: AR.LI, TTI: AR.TTI, AC&: AR.AC, TLI&: AR.TLI, MSSA: AR.MSSA))
7130 return PreservedAnalyses::all();
7131
7132 auto PA = getLoopPassPreservedAnalyses();
7133 if (AR.MSSA)
7134 PA.preserve<MemorySSAAnalysis>();
7135 return PA;
7136}
7137
7138char LoopStrengthReduce::ID = 0;
7139
7140INITIALIZE_PASS_BEGIN(LoopStrengthReduce, "loop-reduce",
7141 "Loop Strength Reduction", false, false)
7142INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
7143INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
7144INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
7145INITIALIZE_PASS_DEPENDENCY(IVUsersWrapperPass)
7146INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
7147INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
7148INITIALIZE_PASS_END(LoopStrengthReduce, "loop-reduce",
7149 "Loop Strength Reduction", false, false)
7150
7151Pass *llvm::createLoopStrengthReducePass() { return new LoopStrengthReduce(); }
7152