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