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