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