Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp
35266 views
//===- LoopStrengthReduce.cpp - Strength Reduce IVs in Loops --------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This transformation analyzes and transforms the induction variables (and9// computations derived from them) into forms suitable for efficient execution10// on the target.11//12// This pass performs a strength reduction on array references inside loops that13// have as one or more of their components the loop induction variable, it14// rewrites expressions to take advantage of scaled-index addressing modes15// available on the target, and it performs a variety of other optimizations16// related to loop induction variables.17//18// Terminology note: this code has a lot of handling for "post-increment" or19// "post-inc" users. This is not talking about post-increment addressing modes;20// it is instead talking about code like this:21//22// %i = phi [ 0, %entry ], [ %i.next, %latch ]23// ...24// %i.next = add %i, 125// %c = icmp eq %i.next, %n26//27// The SCEV for %i is {0,+,1}<%L>. The SCEV for %i.next is {1,+,1}<%L>, however28// it's useful to think about these as the same register, with some uses using29// the value of the register before the add and some using it after. In this30// example, the icmp is a post-increment user, since it uses %i.next, which is31// the value of the induction variable after the increment. The other common32// case of post-increment users is users outside the loop.33//34// TODO: More sophistication in the way Formulae are generated and filtered.35//36// TODO: Handle multiple loops at a time.37//38// TODO: Should the addressing mode BaseGV be changed to a ConstantExpr instead39// of a GlobalValue?40//41// TODO: When truncation is free, truncate ICmp users' operands to make it a42// smaller encoding (on x86 at least).43//44// TODO: When a negated register is used by an add (such as in a list of45// multiple base registers, or as the increment expression in an addrec),46// we may not actually need both reg and (-1 * reg) in registers; the47// negation can be implemented by using a sub instead of an add. The48// lack of support for taking this into consideration when making49// register pressure decisions is partly worked around by the "Special"50// use kind.51//52//===----------------------------------------------------------------------===//5354#include "llvm/Transforms/Scalar/LoopStrengthReduce.h"55#include "llvm/ADT/APInt.h"56#include "llvm/ADT/DenseMap.h"57#include "llvm/ADT/DenseSet.h"58#include "llvm/ADT/Hashing.h"59#include "llvm/ADT/PointerIntPair.h"60#include "llvm/ADT/STLExtras.h"61#include "llvm/ADT/SetVector.h"62#include "llvm/ADT/SmallBitVector.h"63#include "llvm/ADT/SmallPtrSet.h"64#include "llvm/ADT/SmallSet.h"65#include "llvm/ADT/SmallVector.h"66#include "llvm/ADT/Statistic.h"67#include "llvm/ADT/iterator_range.h"68#include "llvm/Analysis/AssumptionCache.h"69#include "llvm/Analysis/DomTreeUpdater.h"70#include "llvm/Analysis/IVUsers.h"71#include "llvm/Analysis/LoopAnalysisManager.h"72#include "llvm/Analysis/LoopInfo.h"73#include "llvm/Analysis/LoopPass.h"74#include "llvm/Analysis/MemorySSA.h"75#include "llvm/Analysis/MemorySSAUpdater.h"76#include "llvm/Analysis/ScalarEvolution.h"77#include "llvm/Analysis/ScalarEvolutionExpressions.h"78#include "llvm/Analysis/ScalarEvolutionNormalization.h"79#include "llvm/Analysis/TargetLibraryInfo.h"80#include "llvm/Analysis/TargetTransformInfo.h"81#include "llvm/Analysis/ValueTracking.h"82#include "llvm/BinaryFormat/Dwarf.h"83#include "llvm/Config/llvm-config.h"84#include "llvm/IR/BasicBlock.h"85#include "llvm/IR/Constant.h"86#include "llvm/IR/Constants.h"87#include "llvm/IR/DebugInfoMetadata.h"88#include "llvm/IR/DerivedTypes.h"89#include "llvm/IR/Dominators.h"90#include "llvm/IR/GlobalValue.h"91#include "llvm/IR/IRBuilder.h"92#include "llvm/IR/InstrTypes.h"93#include "llvm/IR/Instruction.h"94#include "llvm/IR/Instructions.h"95#include "llvm/IR/IntrinsicInst.h"96#include "llvm/IR/Module.h"97#include "llvm/IR/Operator.h"98#include "llvm/IR/PassManager.h"99#include "llvm/IR/Type.h"100#include "llvm/IR/Use.h"101#include "llvm/IR/User.h"102#include "llvm/IR/Value.h"103#include "llvm/IR/ValueHandle.h"104#include "llvm/InitializePasses.h"105#include "llvm/Pass.h"106#include "llvm/Support/Casting.h"107#include "llvm/Support/CommandLine.h"108#include "llvm/Support/Compiler.h"109#include "llvm/Support/Debug.h"110#include "llvm/Support/ErrorHandling.h"111#include "llvm/Support/MathExtras.h"112#include "llvm/Support/raw_ostream.h"113#include "llvm/Transforms/Scalar.h"114#include "llvm/Transforms/Utils.h"115#include "llvm/Transforms/Utils/BasicBlockUtils.h"116#include "llvm/Transforms/Utils/Local.h"117#include "llvm/Transforms/Utils/LoopUtils.h"118#include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"119#include <algorithm>120#include <cassert>121#include <cstddef>122#include <cstdint>123#include <iterator>124#include <limits>125#include <map>126#include <numeric>127#include <optional>128#include <utility>129130using namespace llvm;131132#define DEBUG_TYPE "loop-reduce"133134/// MaxIVUsers is an arbitrary threshold that provides an early opportunity for135/// bail out. This threshold is far beyond the number of users that LSR can136/// conceivably solve, so it should not affect generated code, but catches the137/// worst cases before LSR burns too much compile time and stack space.138static const unsigned MaxIVUsers = 200;139140/// Limit the size of expression that SCEV-based salvaging will attempt to141/// translate into a DIExpression.142/// Choose a maximum size such that debuginfo is not excessively increased and143/// the salvaging is not too expensive for the compiler.144static const unsigned MaxSCEVSalvageExpressionSize = 64;145146// Cleanup congruent phis after LSR phi expansion.147static cl::opt<bool> EnablePhiElim(148"enable-lsr-phielim", cl::Hidden, cl::init(true),149cl::desc("Enable LSR phi elimination"));150151// The flag adds instruction count to solutions cost comparison.152static cl::opt<bool> InsnsCost(153"lsr-insns-cost", cl::Hidden, cl::init(true),154cl::desc("Add instruction count to a LSR cost model"));155156// Flag to choose how to narrow complex lsr solution157static cl::opt<bool> LSRExpNarrow(158"lsr-exp-narrow", cl::Hidden, cl::init(false),159cl::desc("Narrow LSR complex solution using"160" expectation of registers number"));161162// Flag to narrow search space by filtering non-optimal formulae with163// the same ScaledReg and Scale.164static cl::opt<bool> FilterSameScaledReg(165"lsr-filter-same-scaled-reg", cl::Hidden, cl::init(true),166cl::desc("Narrow LSR search space by filtering non-optimal formulae"167" with the same ScaledReg and Scale"));168169static cl::opt<TTI::AddressingModeKind> PreferredAddresingMode(170"lsr-preferred-addressing-mode", cl::Hidden, cl::init(TTI::AMK_None),171cl::desc("A flag that overrides the target's preferred addressing mode."),172cl::values(clEnumValN(TTI::AMK_None,173"none",174"Don't prefer any addressing mode"),175clEnumValN(TTI::AMK_PreIndexed,176"preindexed",177"Prefer pre-indexed addressing mode"),178clEnumValN(TTI::AMK_PostIndexed,179"postindexed",180"Prefer post-indexed addressing mode")));181182static cl::opt<unsigned> ComplexityLimit(183"lsr-complexity-limit", cl::Hidden,184cl::init(std::numeric_limits<uint16_t>::max()),185cl::desc("LSR search space complexity limit"));186187static cl::opt<unsigned> SetupCostDepthLimit(188"lsr-setupcost-depth-limit", cl::Hidden, cl::init(7),189cl::desc("The limit on recursion depth for LSRs setup cost"));190191static cl::opt<cl::boolOrDefault> AllowTerminatingConditionFoldingAfterLSR(192"lsr-term-fold", cl::Hidden,193cl::desc("Attempt to replace primary IV with other IV."));194195static cl::opt<cl::boolOrDefault> AllowDropSolutionIfLessProfitable(196"lsr-drop-solution", cl::Hidden,197cl::desc("Attempt to drop solution if it is less profitable"));198199static cl::opt<bool> EnableVScaleImmediates(200"lsr-enable-vscale-immediates", cl::Hidden, cl::init(true),201cl::desc("Enable analysis of vscale-relative immediates in LSR"));202203static cl::opt<bool> DropScaledForVScale(204"lsr-drop-scaled-reg-for-vscale", cl::Hidden, cl::init(true),205cl::desc("Avoid using scaled registers with vscale-relative addressing"));206207STATISTIC(NumTermFold,208"Number of terminating condition fold recognized and performed");209210#ifndef NDEBUG211// Stress test IV chain generation.212static cl::opt<bool> StressIVChain(213"stress-ivchain", cl::Hidden, cl::init(false),214cl::desc("Stress test LSR IV chains"));215#else216static bool StressIVChain = false;217#endif218219namespace {220221struct MemAccessTy {222/// Used in situations where the accessed memory type is unknown.223static const unsigned UnknownAddressSpace =224std::numeric_limits<unsigned>::max();225226Type *MemTy = nullptr;227unsigned AddrSpace = UnknownAddressSpace;228229MemAccessTy() = default;230MemAccessTy(Type *Ty, unsigned AS) : MemTy(Ty), AddrSpace(AS) {}231232bool operator==(MemAccessTy Other) const {233return MemTy == Other.MemTy && AddrSpace == Other.AddrSpace;234}235236bool operator!=(MemAccessTy Other) const { return !(*this == Other); }237238static MemAccessTy getUnknown(LLVMContext &Ctx,239unsigned AS = UnknownAddressSpace) {240return MemAccessTy(Type::getVoidTy(Ctx), AS);241}242243Type *getType() { return MemTy; }244};245246/// This class holds data which is used to order reuse candidates.247class RegSortData {248public:249/// This represents the set of LSRUse indices which reference250/// a particular register.251SmallBitVector UsedByIndices;252253void print(raw_ostream &OS) const;254void dump() const;255};256257// An offset from an address that is either scalable or fixed. Used for258// per-target optimizations of addressing modes.259class Immediate : public details::FixedOrScalableQuantity<Immediate, int64_t> {260constexpr Immediate(ScalarTy MinVal, bool Scalable)261: FixedOrScalableQuantity(MinVal, Scalable) {}262263constexpr Immediate(const FixedOrScalableQuantity<Immediate, int64_t> &V)264: FixedOrScalableQuantity(V) {}265266public:267constexpr Immediate() = delete;268269static constexpr Immediate getFixed(ScalarTy MinVal) {270return {MinVal, false};271}272static constexpr Immediate getScalable(ScalarTy MinVal) {273return {MinVal, true};274}275static constexpr Immediate get(ScalarTy MinVal, bool Scalable) {276return {MinVal, Scalable};277}278static constexpr Immediate getZero() { return {0, false}; }279static constexpr Immediate getFixedMin() {280return {std::numeric_limits<int64_t>::min(), false};281}282static constexpr Immediate getFixedMax() {283return {std::numeric_limits<int64_t>::max(), false};284}285static constexpr Immediate getScalableMin() {286return {std::numeric_limits<int64_t>::min(), true};287}288static constexpr Immediate getScalableMax() {289return {std::numeric_limits<int64_t>::max(), true};290}291292constexpr bool isLessThanZero() const { return Quantity < 0; }293294constexpr bool isGreaterThanZero() const { return Quantity > 0; }295296constexpr bool isCompatibleImmediate(const Immediate &Imm) const {297return isZero() || Imm.isZero() || Imm.Scalable == Scalable;298}299300constexpr bool isMin() const {301return Quantity == std::numeric_limits<ScalarTy>::min();302}303304constexpr bool isMax() const {305return Quantity == std::numeric_limits<ScalarTy>::max();306}307308// Arithmetic 'operators' that cast to unsigned types first.309constexpr Immediate addUnsigned(const Immediate &RHS) const {310assert(isCompatibleImmediate(RHS) && "Incompatible Immediates");311ScalarTy Value = (uint64_t)Quantity + RHS.getKnownMinValue();312return {Value, Scalable || RHS.isScalable()};313}314315constexpr Immediate subUnsigned(const Immediate &RHS) const {316assert(isCompatibleImmediate(RHS) && "Incompatible Immediates");317ScalarTy Value = (uint64_t)Quantity - RHS.getKnownMinValue();318return {Value, Scalable || RHS.isScalable()};319}320321// Scale the quantity by a constant without caring about runtime scalability.322constexpr Immediate mulUnsigned(const ScalarTy RHS) const {323ScalarTy Value = (uint64_t)Quantity * RHS;324return {Value, Scalable};325}326327// Helpers for generating SCEVs with vscale terms where needed.328const SCEV *getSCEV(ScalarEvolution &SE, Type *Ty) const {329const SCEV *S = SE.getConstant(Ty, Quantity);330if (Scalable)331S = SE.getMulExpr(S, SE.getVScale(S->getType()));332return S;333}334335const SCEV *getNegativeSCEV(ScalarEvolution &SE, Type *Ty) const {336const SCEV *NegS = SE.getConstant(Ty, -(uint64_t)Quantity);337if (Scalable)338NegS = SE.getMulExpr(NegS, SE.getVScale(NegS->getType()));339return NegS;340}341342const SCEV *getUnknownSCEV(ScalarEvolution &SE, Type *Ty) const {343const SCEV *SU = SE.getUnknown(ConstantInt::getSigned(Ty, Quantity));344if (Scalable)345SU = SE.getMulExpr(SU, SE.getVScale(SU->getType()));346return SU;347}348};349350// This is needed for the Compare type of std::map when Immediate is used351// as a key. We don't need it to be fully correct against any value of vscale,352// just to make sure that vscale-related terms in the map are considered against353// each other rather than being mixed up and potentially missing opportunities.354struct KeyOrderTargetImmediate {355bool operator()(const Immediate &LHS, const Immediate &RHS) const {356if (LHS.isScalable() && !RHS.isScalable())357return false;358if (!LHS.isScalable() && RHS.isScalable())359return true;360return LHS.getKnownMinValue() < RHS.getKnownMinValue();361}362};363364// This would be nicer if we could be generic instead of directly using size_t,365// but there doesn't seem to be a type trait for is_orderable or366// is_lessthan_comparable or similar.367struct KeyOrderSizeTAndImmediate {368bool operator()(const std::pair<size_t, Immediate> &LHS,369const std::pair<size_t, Immediate> &RHS) const {370size_t LSize = LHS.first;371size_t RSize = RHS.first;372if (LSize != RSize)373return LSize < RSize;374return KeyOrderTargetImmediate()(LHS.second, RHS.second);375}376};377} // end anonymous namespace378379#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)380void RegSortData::print(raw_ostream &OS) const {381OS << "[NumUses=" << UsedByIndices.count() << ']';382}383384LLVM_DUMP_METHOD void RegSortData::dump() const {385print(errs()); errs() << '\n';386}387#endif388389namespace {390391/// Map register candidates to information about how they are used.392class RegUseTracker {393using RegUsesTy = DenseMap<const SCEV *, RegSortData>;394395RegUsesTy RegUsesMap;396SmallVector<const SCEV *, 16> RegSequence;397398public:399void countRegister(const SCEV *Reg, size_t LUIdx);400void dropRegister(const SCEV *Reg, size_t LUIdx);401void swapAndDropUse(size_t LUIdx, size_t LastLUIdx);402403bool isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const;404405const SmallBitVector &getUsedByIndices(const SCEV *Reg) const;406407void clear();408409using iterator = SmallVectorImpl<const SCEV *>::iterator;410using const_iterator = SmallVectorImpl<const SCEV *>::const_iterator;411412iterator begin() { return RegSequence.begin(); }413iterator end() { return RegSequence.end(); }414const_iterator begin() const { return RegSequence.begin(); }415const_iterator end() const { return RegSequence.end(); }416};417418} // end anonymous namespace419420void421RegUseTracker::countRegister(const SCEV *Reg, size_t LUIdx) {422std::pair<RegUsesTy::iterator, bool> Pair =423RegUsesMap.insert(std::make_pair(Reg, RegSortData()));424RegSortData &RSD = Pair.first->second;425if (Pair.second)426RegSequence.push_back(Reg);427RSD.UsedByIndices.resize(std::max(RSD.UsedByIndices.size(), LUIdx + 1));428RSD.UsedByIndices.set(LUIdx);429}430431void432RegUseTracker::dropRegister(const SCEV *Reg, size_t LUIdx) {433RegUsesTy::iterator It = RegUsesMap.find(Reg);434assert(It != RegUsesMap.end());435RegSortData &RSD = It->second;436assert(RSD.UsedByIndices.size() > LUIdx);437RSD.UsedByIndices.reset(LUIdx);438}439440void441RegUseTracker::swapAndDropUse(size_t LUIdx, size_t LastLUIdx) {442assert(LUIdx <= LastLUIdx);443444// Update RegUses. The data structure is not optimized for this purpose;445// we must iterate through it and update each of the bit vectors.446for (auto &Pair : RegUsesMap) {447SmallBitVector &UsedByIndices = Pair.second.UsedByIndices;448if (LUIdx < UsedByIndices.size())449UsedByIndices[LUIdx] =450LastLUIdx < UsedByIndices.size() ? UsedByIndices[LastLUIdx] : false;451UsedByIndices.resize(std::min(UsedByIndices.size(), LastLUIdx));452}453}454455bool456RegUseTracker::isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const {457RegUsesTy::const_iterator I = RegUsesMap.find(Reg);458if (I == RegUsesMap.end())459return false;460const SmallBitVector &UsedByIndices = I->second.UsedByIndices;461int i = UsedByIndices.find_first();462if (i == -1) return false;463if ((size_t)i != LUIdx) return true;464return UsedByIndices.find_next(i) != -1;465}466467const SmallBitVector &RegUseTracker::getUsedByIndices(const SCEV *Reg) const {468RegUsesTy::const_iterator I = RegUsesMap.find(Reg);469assert(I != RegUsesMap.end() && "Unknown register!");470return I->second.UsedByIndices;471}472473void RegUseTracker::clear() {474RegUsesMap.clear();475RegSequence.clear();476}477478namespace {479480/// This class holds information that describes a formula for computing481/// satisfying a use. It may include broken-out immediates and scaled registers.482struct Formula {483/// Global base address used for complex addressing.484GlobalValue *BaseGV = nullptr;485486/// Base offset for complex addressing.487Immediate BaseOffset = Immediate::getZero();488489/// Whether any complex addressing has a base register.490bool HasBaseReg = false;491492/// The scale of any complex addressing.493int64_t Scale = 0;494495/// The list of "base" registers for this use. When this is non-empty. The496/// canonical representation of a formula is497/// 1. BaseRegs.size > 1 implies ScaledReg != NULL and498/// 2. ScaledReg != NULL implies Scale != 1 || !BaseRegs.empty().499/// 3. The reg containing recurrent expr related with currect loop in the500/// formula should be put in the ScaledReg.501/// #1 enforces that the scaled register is always used when at least two502/// registers are needed by the formula: e.g., reg1 + reg2 is reg1 + 1 * reg2.503/// #2 enforces that 1 * reg is reg.504/// #3 ensures invariant regs with respect to current loop can be combined505/// together in LSR codegen.506/// This invariant can be temporarily broken while building a formula.507/// However, every formula inserted into the LSRInstance must be in canonical508/// form.509SmallVector<const SCEV *, 4> BaseRegs;510511/// The 'scaled' register for this use. This should be non-null when Scale is512/// not zero.513const SCEV *ScaledReg = nullptr;514515/// An additional constant offset which added near the use. This requires a516/// temporary register, but the offset itself can live in an add immediate517/// field rather than a register.518Immediate UnfoldedOffset = Immediate::getZero();519520Formula() = default;521522void initialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE);523524bool isCanonical(const Loop &L) const;525526void canonicalize(const Loop &L);527528bool unscale();529530bool hasZeroEnd() const;531532size_t getNumRegs() const;533Type *getType() const;534535void deleteBaseReg(const SCEV *&S);536537bool referencesReg(const SCEV *S) const;538bool hasRegsUsedByUsesOtherThan(size_t LUIdx,539const RegUseTracker &RegUses) const;540541void print(raw_ostream &OS) const;542void dump() const;543};544545} // end anonymous namespace546547/// Recursion helper for initialMatch.548static void DoInitialMatch(const SCEV *S, Loop *L,549SmallVectorImpl<const SCEV *> &Good,550SmallVectorImpl<const SCEV *> &Bad,551ScalarEvolution &SE) {552// Collect expressions which properly dominate the loop header.553if (SE.properlyDominates(S, L->getHeader())) {554Good.push_back(S);555return;556}557558// Look at add operands.559if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {560for (const SCEV *S : Add->operands())561DoInitialMatch(S, L, Good, Bad, SE);562return;563}564565// Look at addrec operands.566if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))567if (!AR->getStart()->isZero() && AR->isAffine()) {568DoInitialMatch(AR->getStart(), L, Good, Bad, SE);569DoInitialMatch(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0),570AR->getStepRecurrence(SE),571// FIXME: AR->getNoWrapFlags()572AR->getLoop(), SCEV::FlagAnyWrap),573L, Good, Bad, SE);574return;575}576577// Handle a multiplication by -1 (negation) if it didn't fold.578if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S))579if (Mul->getOperand(0)->isAllOnesValue()) {580SmallVector<const SCEV *, 4> Ops(drop_begin(Mul->operands()));581const SCEV *NewMul = SE.getMulExpr(Ops);582583SmallVector<const SCEV *, 4> MyGood;584SmallVector<const SCEV *, 4> MyBad;585DoInitialMatch(NewMul, L, MyGood, MyBad, SE);586const SCEV *NegOne = SE.getSCEV(ConstantInt::getAllOnesValue(587SE.getEffectiveSCEVType(NewMul->getType())));588for (const SCEV *S : MyGood)589Good.push_back(SE.getMulExpr(NegOne, S));590for (const SCEV *S : MyBad)591Bad.push_back(SE.getMulExpr(NegOne, S));592return;593}594595// Ok, we can't do anything interesting. Just stuff the whole thing into a596// register and hope for the best.597Bad.push_back(S);598}599600/// Incorporate loop-variant parts of S into this Formula, attempting to keep601/// all loop-invariant and loop-computable values in a single base register.602void Formula::initialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE) {603SmallVector<const SCEV *, 4> Good;604SmallVector<const SCEV *, 4> Bad;605DoInitialMatch(S, L, Good, Bad, SE);606if (!Good.empty()) {607const SCEV *Sum = SE.getAddExpr(Good);608if (!Sum->isZero())609BaseRegs.push_back(Sum);610HasBaseReg = true;611}612if (!Bad.empty()) {613const SCEV *Sum = SE.getAddExpr(Bad);614if (!Sum->isZero())615BaseRegs.push_back(Sum);616HasBaseReg = true;617}618canonicalize(*L);619}620621static bool containsAddRecDependentOnLoop(const SCEV *S, const Loop &L) {622return SCEVExprContains(S, [&L](const SCEV *S) {623return isa<SCEVAddRecExpr>(S) && (cast<SCEVAddRecExpr>(S)->getLoop() == &L);624});625}626627/// Check whether or not this formula satisfies the canonical628/// representation.629/// \see Formula::BaseRegs.630bool Formula::isCanonical(const Loop &L) const {631if (!ScaledReg)632return BaseRegs.size() <= 1;633634if (Scale != 1)635return true;636637if (Scale == 1 && BaseRegs.empty())638return false;639640if (containsAddRecDependentOnLoop(ScaledReg, L))641return true;642643// If ScaledReg is not a recurrent expr, or it is but its loop is not current644// loop, meanwhile BaseRegs contains a recurrent expr reg related with current645// loop, we want to swap the reg in BaseRegs with ScaledReg.646return none_of(BaseRegs, [&L](const SCEV *S) {647return containsAddRecDependentOnLoop(S, L);648});649}650651/// Helper method to morph a formula into its canonical representation.652/// \see Formula::BaseRegs.653/// Every formula having more than one base register, must use the ScaledReg654/// field. Otherwise, we would have to do special cases everywhere in LSR655/// to treat reg1 + reg2 + ... the same way as reg1 + 1*reg2 + ...656/// On the other hand, 1*reg should be canonicalized into reg.657void Formula::canonicalize(const Loop &L) {658if (isCanonical(L))659return;660661if (BaseRegs.empty()) {662// No base reg? Use scale reg with scale = 1 as such.663assert(ScaledReg && "Expected 1*reg => reg");664assert(Scale == 1 && "Expected 1*reg => reg");665BaseRegs.push_back(ScaledReg);666Scale = 0;667ScaledReg = nullptr;668return;669}670671// Keep the invariant sum in BaseRegs and one of the variant sum in ScaledReg.672if (!ScaledReg) {673ScaledReg = BaseRegs.pop_back_val();674Scale = 1;675}676677// If ScaledReg is an invariant with respect to L, find the reg from678// BaseRegs containing the recurrent expr related with Loop L. Swap the679// reg with ScaledReg.680if (!containsAddRecDependentOnLoop(ScaledReg, L)) {681auto I = find_if(BaseRegs, [&L](const SCEV *S) {682return containsAddRecDependentOnLoop(S, L);683});684if (I != BaseRegs.end())685std::swap(ScaledReg, *I);686}687assert(isCanonical(L) && "Failed to canonicalize?");688}689690/// Get rid of the scale in the formula.691/// In other words, this method morphes reg1 + 1*reg2 into reg1 + reg2.692/// \return true if it was possible to get rid of the scale, false otherwise.693/// \note After this operation the formula may not be in the canonical form.694bool Formula::unscale() {695if (Scale != 1)696return false;697Scale = 0;698BaseRegs.push_back(ScaledReg);699ScaledReg = nullptr;700return true;701}702703bool Formula::hasZeroEnd() const {704if (UnfoldedOffset || BaseOffset)705return false;706if (BaseRegs.size() != 1 || ScaledReg)707return false;708return true;709}710711/// Return the total number of register operands used by this formula. This does712/// not include register uses implied by non-constant addrec strides.713size_t Formula::getNumRegs() const {714return !!ScaledReg + BaseRegs.size();715}716717/// Return the type of this formula, if it has one, or null otherwise. This type718/// is meaningless except for the bit size.719Type *Formula::getType() const {720return !BaseRegs.empty() ? BaseRegs.front()->getType() :721ScaledReg ? ScaledReg->getType() :722BaseGV ? BaseGV->getType() :723nullptr;724}725726/// Delete the given base reg from the BaseRegs list.727void Formula::deleteBaseReg(const SCEV *&S) {728if (&S != &BaseRegs.back())729std::swap(S, BaseRegs.back());730BaseRegs.pop_back();731}732733/// Test if this formula references the given register.734bool Formula::referencesReg(const SCEV *S) const {735return S == ScaledReg || is_contained(BaseRegs, S);736}737738/// Test whether this formula uses registers which are used by uses other than739/// the use with the given index.740bool Formula::hasRegsUsedByUsesOtherThan(size_t LUIdx,741const RegUseTracker &RegUses) const {742if (ScaledReg)743if (RegUses.isRegUsedByUsesOtherThan(ScaledReg, LUIdx))744return true;745for (const SCEV *BaseReg : BaseRegs)746if (RegUses.isRegUsedByUsesOtherThan(BaseReg, LUIdx))747return true;748return false;749}750751#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)752void Formula::print(raw_ostream &OS) const {753bool First = true;754if (BaseGV) {755if (!First) OS << " + "; else First = false;756BaseGV->printAsOperand(OS, /*PrintType=*/false);757}758if (BaseOffset.isNonZero()) {759if (!First) OS << " + "; else First = false;760OS << BaseOffset;761}762for (const SCEV *BaseReg : BaseRegs) {763if (!First) OS << " + "; else First = false;764OS << "reg(" << *BaseReg << ')';765}766if (HasBaseReg && BaseRegs.empty()) {767if (!First) OS << " + "; else First = false;768OS << "**error: HasBaseReg**";769} else if (!HasBaseReg && !BaseRegs.empty()) {770if (!First) OS << " + "; else First = false;771OS << "**error: !HasBaseReg**";772}773if (Scale != 0) {774if (!First) OS << " + "; else First = false;775OS << Scale << "*reg(";776if (ScaledReg)777OS << *ScaledReg;778else779OS << "<unknown>";780OS << ')';781}782if (UnfoldedOffset.isNonZero()) {783if (!First) OS << " + ";784OS << "imm(" << UnfoldedOffset << ')';785}786}787788LLVM_DUMP_METHOD void Formula::dump() const {789print(errs()); errs() << '\n';790}791#endif792793/// Return true if the given addrec can be sign-extended without changing its794/// value.795static bool isAddRecSExtable(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {796Type *WideTy =797IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(AR->getType()) + 1);798return isa<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));799}800801/// Return true if the given add can be sign-extended without changing its802/// value.803static bool isAddSExtable(const SCEVAddExpr *A, ScalarEvolution &SE) {804Type *WideTy =805IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(A->getType()) + 1);806return isa<SCEVAddExpr>(SE.getSignExtendExpr(A, WideTy));807}808809/// Return true if the given mul can be sign-extended without changing its810/// value.811static bool isMulSExtable(const SCEVMulExpr *M, ScalarEvolution &SE) {812Type *WideTy =813IntegerType::get(SE.getContext(),814SE.getTypeSizeInBits(M->getType()) * M->getNumOperands());815return isa<SCEVMulExpr>(SE.getSignExtendExpr(M, WideTy));816}817818/// Return an expression for LHS /s RHS, if it can be determined and if the819/// remainder is known to be zero, or null otherwise. If IgnoreSignificantBits820/// is true, expressions like (X * Y) /s Y are simplified to X, ignoring that821/// the multiplication may overflow, which is useful when the result will be822/// used in a context where the most significant bits are ignored.823static const SCEV *getExactSDiv(const SCEV *LHS, const SCEV *RHS,824ScalarEvolution &SE,825bool IgnoreSignificantBits = false) {826// Handle the trivial case, which works for any SCEV type.827if (LHS == RHS)828return SE.getConstant(LHS->getType(), 1);829830// Handle a few RHS special cases.831const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS);832if (RC) {833const APInt &RA = RC->getAPInt();834// Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do835// some folding.836if (RA.isAllOnes()) {837if (LHS->getType()->isPointerTy())838return nullptr;839return SE.getMulExpr(LHS, RC);840}841// Handle x /s 1 as x.842if (RA == 1)843return LHS;844}845846// Check for a division of a constant by a constant.847if (const SCEVConstant *C = dyn_cast<SCEVConstant>(LHS)) {848if (!RC)849return nullptr;850const APInt &LA = C->getAPInt();851const APInt &RA = RC->getAPInt();852if (LA.srem(RA) != 0)853return nullptr;854return SE.getConstant(LA.sdiv(RA));855}856857// Distribute the sdiv over addrec operands, if the addrec doesn't overflow.858if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) {859if ((IgnoreSignificantBits || isAddRecSExtable(AR, SE)) && AR->isAffine()) {860const SCEV *Step = getExactSDiv(AR->getStepRecurrence(SE), RHS, SE,861IgnoreSignificantBits);862if (!Step) return nullptr;863const SCEV *Start = getExactSDiv(AR->getStart(), RHS, SE,864IgnoreSignificantBits);865if (!Start) return nullptr;866// FlagNW is independent of the start value, step direction, and is867// preserved with smaller magnitude steps.868// FIXME: AR->getNoWrapFlags(SCEV::FlagNW)869return SE.getAddRecExpr(Start, Step, AR->getLoop(), SCEV::FlagAnyWrap);870}871return nullptr;872}873874// Distribute the sdiv over add operands, if the add doesn't overflow.875if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(LHS)) {876if (IgnoreSignificantBits || isAddSExtable(Add, SE)) {877SmallVector<const SCEV *, 8> Ops;878for (const SCEV *S : Add->operands()) {879const SCEV *Op = getExactSDiv(S, RHS, SE, IgnoreSignificantBits);880if (!Op) return nullptr;881Ops.push_back(Op);882}883return SE.getAddExpr(Ops);884}885return nullptr;886}887888// Check for a multiply operand that we can pull RHS out of.889if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS)) {890if (IgnoreSignificantBits || isMulSExtable(Mul, SE)) {891// Handle special case C1*X*Y /s C2*X*Y.892if (const SCEVMulExpr *MulRHS = dyn_cast<SCEVMulExpr>(RHS)) {893if (IgnoreSignificantBits || isMulSExtable(MulRHS, SE)) {894const SCEVConstant *LC = dyn_cast<SCEVConstant>(Mul->getOperand(0));895const SCEVConstant *RC =896dyn_cast<SCEVConstant>(MulRHS->getOperand(0));897if (LC && RC) {898SmallVector<const SCEV *, 4> LOps(drop_begin(Mul->operands()));899SmallVector<const SCEV *, 4> ROps(drop_begin(MulRHS->operands()));900if (LOps == ROps)901return getExactSDiv(LC, RC, SE, IgnoreSignificantBits);902}903}904}905906SmallVector<const SCEV *, 4> Ops;907bool Found = false;908for (const SCEV *S : Mul->operands()) {909if (!Found)910if (const SCEV *Q = getExactSDiv(S, RHS, SE,911IgnoreSignificantBits)) {912S = Q;913Found = true;914}915Ops.push_back(S);916}917return Found ? SE.getMulExpr(Ops) : nullptr;918}919return nullptr;920}921922// Otherwise we don't know.923return nullptr;924}925926/// If S involves the addition of a constant integer value, return that integer927/// value, and mutate S to point to a new SCEV with that value excluded.928static Immediate ExtractImmediate(const SCEV *&S, ScalarEvolution &SE) {929if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {930if (C->getAPInt().getSignificantBits() <= 64) {931S = SE.getConstant(C->getType(), 0);932return Immediate::getFixed(C->getValue()->getSExtValue());933}934} else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {935SmallVector<const SCEV *, 8> NewOps(Add->operands());936Immediate Result = ExtractImmediate(NewOps.front(), SE);937if (Result.isNonZero())938S = SE.getAddExpr(NewOps);939return Result;940} else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {941SmallVector<const SCEV *, 8> NewOps(AR->operands());942Immediate Result = ExtractImmediate(NewOps.front(), SE);943if (Result.isNonZero())944S = SE.getAddRecExpr(NewOps, AR->getLoop(),945// FIXME: AR->getNoWrapFlags(SCEV::FlagNW)946SCEV::FlagAnyWrap);947return Result;948} else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {949if (EnableVScaleImmediates && M->getNumOperands() == 2) {950if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))951if (isa<SCEVVScale>(M->getOperand(1))) {952S = SE.getConstant(M->getType(), 0);953return Immediate::getScalable(C->getValue()->getSExtValue());954}955}956}957return Immediate::getZero();958}959960/// If S involves the addition of a GlobalValue address, return that symbol, and961/// mutate S to point to a new SCEV with that value excluded.962static GlobalValue *ExtractSymbol(const SCEV *&S, ScalarEvolution &SE) {963if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {964if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) {965S = SE.getConstant(GV->getType(), 0);966return GV;967}968} else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {969SmallVector<const SCEV *, 8> NewOps(Add->operands());970GlobalValue *Result = ExtractSymbol(NewOps.back(), SE);971if (Result)972S = SE.getAddExpr(NewOps);973return Result;974} else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {975SmallVector<const SCEV *, 8> NewOps(AR->operands());976GlobalValue *Result = ExtractSymbol(NewOps.front(), SE);977if (Result)978S = SE.getAddRecExpr(NewOps, AR->getLoop(),979// FIXME: AR->getNoWrapFlags(SCEV::FlagNW)980SCEV::FlagAnyWrap);981return Result;982}983return nullptr;984}985986/// Returns true if the specified instruction is using the specified value as an987/// address.988static bool isAddressUse(const TargetTransformInfo &TTI,989Instruction *Inst, Value *OperandVal) {990bool isAddress = isa<LoadInst>(Inst);991if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {992if (SI->getPointerOperand() == OperandVal)993isAddress = true;994} else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {995// Addressing modes can also be folded into prefetches and a variety996// of intrinsics.997switch (II->getIntrinsicID()) {998case Intrinsic::memset:999case Intrinsic::prefetch:1000case Intrinsic::masked_load:1001if (II->getArgOperand(0) == OperandVal)1002isAddress = true;1003break;1004case Intrinsic::masked_store:1005if (II->getArgOperand(1) == OperandVal)1006isAddress = true;1007break;1008case Intrinsic::memmove:1009case Intrinsic::memcpy:1010if (II->getArgOperand(0) == OperandVal ||1011II->getArgOperand(1) == OperandVal)1012isAddress = true;1013break;1014default: {1015MemIntrinsicInfo IntrInfo;1016if (TTI.getTgtMemIntrinsic(II, IntrInfo)) {1017if (IntrInfo.PtrVal == OperandVal)1018isAddress = true;1019}1020}1021}1022} else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(Inst)) {1023if (RMW->getPointerOperand() == OperandVal)1024isAddress = true;1025} else if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst)) {1026if (CmpX->getPointerOperand() == OperandVal)1027isAddress = true;1028}1029return isAddress;1030}10311032/// Return the type of the memory being accessed.1033static MemAccessTy getAccessType(const TargetTransformInfo &TTI,1034Instruction *Inst, Value *OperandVal) {1035MemAccessTy AccessTy = MemAccessTy::getUnknown(Inst->getContext());10361037// First get the type of memory being accessed.1038if (Type *Ty = Inst->getAccessType())1039AccessTy.MemTy = Ty;10401041// Then get the pointer address space.1042if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {1043AccessTy.AddrSpace = SI->getPointerAddressSpace();1044} else if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) {1045AccessTy.AddrSpace = LI->getPointerAddressSpace();1046} else if (const AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(Inst)) {1047AccessTy.AddrSpace = RMW->getPointerAddressSpace();1048} else if (const AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst)) {1049AccessTy.AddrSpace = CmpX->getPointerAddressSpace();1050} else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {1051switch (II->getIntrinsicID()) {1052case Intrinsic::prefetch:1053case Intrinsic::memset:1054AccessTy.AddrSpace = II->getArgOperand(0)->getType()->getPointerAddressSpace();1055AccessTy.MemTy = OperandVal->getType();1056break;1057case Intrinsic::memmove:1058case Intrinsic::memcpy:1059AccessTy.AddrSpace = OperandVal->getType()->getPointerAddressSpace();1060AccessTy.MemTy = OperandVal->getType();1061break;1062case Intrinsic::masked_load:1063AccessTy.AddrSpace =1064II->getArgOperand(0)->getType()->getPointerAddressSpace();1065break;1066case Intrinsic::masked_store:1067AccessTy.AddrSpace =1068II->getArgOperand(1)->getType()->getPointerAddressSpace();1069break;1070default: {1071MemIntrinsicInfo IntrInfo;1072if (TTI.getTgtMemIntrinsic(II, IntrInfo) && IntrInfo.PtrVal) {1073AccessTy.AddrSpace1074= IntrInfo.PtrVal->getType()->getPointerAddressSpace();1075}10761077break;1078}1079}1080}10811082return AccessTy;1083}10841085/// Return true if this AddRec is already a phi in its loop.1086static bool isExistingPhi(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {1087for (PHINode &PN : AR->getLoop()->getHeader()->phis()) {1088if (SE.isSCEVable(PN.getType()) &&1089(SE.getEffectiveSCEVType(PN.getType()) ==1090SE.getEffectiveSCEVType(AR->getType())) &&1091SE.getSCEV(&PN) == AR)1092return true;1093}1094return false;1095}10961097/// Check if expanding this expression is likely to incur significant cost. This1098/// is tricky because SCEV doesn't track which expressions are actually computed1099/// by the current IR.1100///1101/// We currently allow expansion of IV increments that involve adds,1102/// multiplication by constants, and AddRecs from existing phis.1103///1104/// TODO: Allow UDivExpr if we can find an existing IV increment that is an1105/// obvious multiple of the UDivExpr.1106static bool isHighCostExpansion(const SCEV *S,1107SmallPtrSetImpl<const SCEV*> &Processed,1108ScalarEvolution &SE) {1109// Zero/One operand expressions1110switch (S->getSCEVType()) {1111case scUnknown:1112case scConstant:1113case scVScale:1114return false;1115case scTruncate:1116return isHighCostExpansion(cast<SCEVTruncateExpr>(S)->getOperand(),1117Processed, SE);1118case scZeroExtend:1119return isHighCostExpansion(cast<SCEVZeroExtendExpr>(S)->getOperand(),1120Processed, SE);1121case scSignExtend:1122return isHighCostExpansion(cast<SCEVSignExtendExpr>(S)->getOperand(),1123Processed, SE);1124default:1125break;1126}11271128if (!Processed.insert(S).second)1129return false;11301131if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {1132for (const SCEV *S : Add->operands()) {1133if (isHighCostExpansion(S, Processed, SE))1134return true;1135}1136return false;1137}11381139if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {1140if (Mul->getNumOperands() == 2) {1141// Multiplication by a constant is ok1142if (isa<SCEVConstant>(Mul->getOperand(0)))1143return isHighCostExpansion(Mul->getOperand(1), Processed, SE);11441145// If we have the value of one operand, check if an existing1146// multiplication already generates this expression.1147if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Mul->getOperand(1))) {1148Value *UVal = U->getValue();1149for (User *UR : UVal->users()) {1150// If U is a constant, it may be used by a ConstantExpr.1151Instruction *UI = dyn_cast<Instruction>(UR);1152if (UI && UI->getOpcode() == Instruction::Mul &&1153SE.isSCEVable(UI->getType())) {1154return SE.getSCEV(UI) == Mul;1155}1156}1157}1158}1159}11601161if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {1162if (isExistingPhi(AR, SE))1163return false;1164}11651166// Fow now, consider any other type of expression (div/mul/min/max) high cost.1167return true;1168}11691170namespace {11711172class LSRUse;11731174} // end anonymous namespace11751176/// Check if the addressing mode defined by \p F is completely1177/// folded in \p LU at isel time.1178/// This includes address-mode folding and special icmp tricks.1179/// This function returns true if \p LU can accommodate what \p F1180/// defines and up to 1 base + 1 scaled + offset.1181/// In other words, if \p F has several base registers, this function may1182/// still return true. Therefore, users still need to account for1183/// additional base registers and/or unfolded offsets to derive an1184/// accurate cost model.1185static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,1186const LSRUse &LU, const Formula &F);11871188// Get the cost of the scaling factor used in F for LU.1189static InstructionCost getScalingFactorCost(const TargetTransformInfo &TTI,1190const LSRUse &LU, const Formula &F,1191const Loop &L);11921193namespace {11941195/// This class is used to measure and compare candidate formulae.1196class Cost {1197const Loop *L = nullptr;1198ScalarEvolution *SE = nullptr;1199const TargetTransformInfo *TTI = nullptr;1200TargetTransformInfo::LSRCost C;1201TTI::AddressingModeKind AMK = TTI::AMK_None;12021203public:1204Cost() = delete;1205Cost(const Loop *L, ScalarEvolution &SE, const TargetTransformInfo &TTI,1206TTI::AddressingModeKind AMK) :1207L(L), SE(&SE), TTI(&TTI), AMK(AMK) {1208C.Insns = 0;1209C.NumRegs = 0;1210C.AddRecCost = 0;1211C.NumIVMuls = 0;1212C.NumBaseAdds = 0;1213C.ImmCost = 0;1214C.SetupCost = 0;1215C.ScaleCost = 0;1216}12171218bool isLess(const Cost &Other) const;12191220void Lose();12211222#ifndef NDEBUG1223// Once any of the metrics loses, they must all remain losers.1224bool isValid() {1225return ((C.Insns | C.NumRegs | C.AddRecCost | C.NumIVMuls | C.NumBaseAdds1226| C.ImmCost | C.SetupCost | C.ScaleCost) != ~0u)1227|| ((C.Insns & C.NumRegs & C.AddRecCost & C.NumIVMuls & C.NumBaseAdds1228& C.ImmCost & C.SetupCost & C.ScaleCost) == ~0u);1229}1230#endif12311232bool isLoser() {1233assert(isValid() && "invalid cost");1234return C.NumRegs == ~0u;1235}12361237void RateFormula(const Formula &F,1238SmallPtrSetImpl<const SCEV *> &Regs,1239const DenseSet<const SCEV *> &VisitedRegs,1240const LSRUse &LU,1241SmallPtrSetImpl<const SCEV *> *LoserRegs = nullptr);12421243void print(raw_ostream &OS) const;1244void dump() const;12451246private:1247void RateRegister(const Formula &F, const SCEV *Reg,1248SmallPtrSetImpl<const SCEV *> &Regs);1249void RatePrimaryRegister(const Formula &F, const SCEV *Reg,1250SmallPtrSetImpl<const SCEV *> &Regs,1251SmallPtrSetImpl<const SCEV *> *LoserRegs);1252};12531254/// An operand value in an instruction which is to be replaced with some1255/// equivalent, possibly strength-reduced, replacement.1256struct LSRFixup {1257/// The instruction which will be updated.1258Instruction *UserInst = nullptr;12591260/// The operand of the instruction which will be replaced. The operand may be1261/// used more than once; every instance will be replaced.1262Value *OperandValToReplace = nullptr;12631264/// If this user is to use the post-incremented value of an induction1265/// variable, this set is non-empty and holds the loops associated with the1266/// induction variable.1267PostIncLoopSet PostIncLoops;12681269/// A constant offset to be added to the LSRUse expression. This allows1270/// multiple fixups to share the same LSRUse with different offsets, for1271/// example in an unrolled loop.1272Immediate Offset = Immediate::getZero();12731274LSRFixup() = default;12751276bool isUseFullyOutsideLoop(const Loop *L) const;12771278void print(raw_ostream &OS) const;1279void dump() const;1280};12811282/// A DenseMapInfo implementation for holding DenseMaps and DenseSets of sorted1283/// SmallVectors of const SCEV*.1284struct UniquifierDenseMapInfo {1285static SmallVector<const SCEV *, 4> getEmptyKey() {1286SmallVector<const SCEV *, 4> V;1287V.push_back(reinterpret_cast<const SCEV *>(-1));1288return V;1289}12901291static SmallVector<const SCEV *, 4> getTombstoneKey() {1292SmallVector<const SCEV *, 4> V;1293V.push_back(reinterpret_cast<const SCEV *>(-2));1294return V;1295}12961297static unsigned getHashValue(const SmallVector<const SCEV *, 4> &V) {1298return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));1299}13001301static bool isEqual(const SmallVector<const SCEV *, 4> &LHS,1302const SmallVector<const SCEV *, 4> &RHS) {1303return LHS == RHS;1304}1305};13061307/// This class holds the state that LSR keeps for each use in IVUsers, as well1308/// as uses invented by LSR itself. It includes information about what kinds of1309/// things can be folded into the user, information about the user itself, and1310/// information about how the use may be satisfied. TODO: Represent multiple1311/// users of the same expression in common?1312class LSRUse {1313DenseSet<SmallVector<const SCEV *, 4>, UniquifierDenseMapInfo> Uniquifier;13141315public:1316/// An enum for a kind of use, indicating what types of scaled and immediate1317/// operands it might support.1318enum KindType {1319Basic, ///< A normal use, with no folding.1320Special, ///< A special case of basic, allowing -1 scales.1321Address, ///< An address use; folding according to TargetLowering1322ICmpZero ///< An equality icmp with both operands folded into one.1323// TODO: Add a generic icmp too?1324};13251326using SCEVUseKindPair = PointerIntPair<const SCEV *, 2, KindType>;13271328KindType Kind;1329MemAccessTy AccessTy;13301331/// The list of operands which are to be replaced.1332SmallVector<LSRFixup, 8> Fixups;13331334/// Keep track of the min and max offsets of the fixups.1335Immediate MinOffset = Immediate::getFixedMax();1336Immediate MaxOffset = Immediate::getFixedMin();13371338/// This records whether all of the fixups using this LSRUse are outside of1339/// the loop, in which case some special-case heuristics may be used.1340bool AllFixupsOutsideLoop = true;13411342/// RigidFormula is set to true to guarantee that this use will be associated1343/// with a single formula--the one that initially matched. Some SCEV1344/// expressions cannot be expanded. This allows LSR to consider the registers1345/// used by those expressions without the need to expand them later after1346/// changing the formula.1347bool RigidFormula = false;13481349/// This records the widest use type for any fixup using this1350/// LSRUse. FindUseWithSimilarFormula can't consider uses with different max1351/// fixup widths to be equivalent, because the narrower one may be relying on1352/// the implicit truncation to truncate away bogus bits.1353Type *WidestFixupType = nullptr;13541355/// A list of ways to build a value that can satisfy this user. After the1356/// list is populated, one of these is selected heuristically and used to1357/// formulate a replacement for OperandValToReplace in UserInst.1358SmallVector<Formula, 12> Formulae;13591360/// The set of register candidates used by all formulae in this LSRUse.1361SmallPtrSet<const SCEV *, 4> Regs;13621363LSRUse(KindType K, MemAccessTy AT) : Kind(K), AccessTy(AT) {}13641365LSRFixup &getNewFixup() {1366Fixups.push_back(LSRFixup());1367return Fixups.back();1368}13691370void pushFixup(LSRFixup &f) {1371Fixups.push_back(f);1372if (Immediate::isKnownGT(f.Offset, MaxOffset))1373MaxOffset = f.Offset;1374if (Immediate::isKnownLT(f.Offset, MinOffset))1375MinOffset = f.Offset;1376}13771378bool HasFormulaWithSameRegs(const Formula &F) const;1379float getNotSelectedProbability(const SCEV *Reg) const;1380bool InsertFormula(const Formula &F, const Loop &L);1381void DeleteFormula(Formula &F);1382void RecomputeRegs(size_t LUIdx, RegUseTracker &Reguses);13831384void print(raw_ostream &OS) const;1385void dump() const;1386};13871388} // end anonymous namespace13891390static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,1391LSRUse::KindType Kind, MemAccessTy AccessTy,1392GlobalValue *BaseGV, Immediate BaseOffset,1393bool HasBaseReg, int64_t Scale,1394Instruction *Fixup = nullptr);13951396static unsigned getSetupCost(const SCEV *Reg, unsigned Depth) {1397if (isa<SCEVUnknown>(Reg) || isa<SCEVConstant>(Reg))1398return 1;1399if (Depth == 0)1400return 0;1401if (const auto *S = dyn_cast<SCEVAddRecExpr>(Reg))1402return getSetupCost(S->getStart(), Depth - 1);1403if (auto S = dyn_cast<SCEVIntegralCastExpr>(Reg))1404return getSetupCost(S->getOperand(), Depth - 1);1405if (auto S = dyn_cast<SCEVNAryExpr>(Reg))1406return std::accumulate(S->operands().begin(), S->operands().end(), 0,1407[&](unsigned i, const SCEV *Reg) {1408return i + getSetupCost(Reg, Depth - 1);1409});1410if (auto S = dyn_cast<SCEVUDivExpr>(Reg))1411return getSetupCost(S->getLHS(), Depth - 1) +1412getSetupCost(S->getRHS(), Depth - 1);1413return 0;1414}14151416/// Tally up interesting quantities from the given register.1417void Cost::RateRegister(const Formula &F, const SCEV *Reg,1418SmallPtrSetImpl<const SCEV *> &Regs) {1419if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Reg)) {1420// If this is an addrec for another loop, it should be an invariant1421// with respect to L since L is the innermost loop (at least1422// for now LSR only handles innermost loops).1423if (AR->getLoop() != L) {1424// If the AddRec exists, consider it's register free and leave it alone.1425if (isExistingPhi(AR, *SE) && AMK != TTI::AMK_PostIndexed)1426return;14271428// It is bad to allow LSR for current loop to add induction variables1429// for its sibling loops.1430if (!AR->getLoop()->contains(L)) {1431Lose();1432return;1433}14341435// Otherwise, it will be an invariant with respect to Loop L.1436++C.NumRegs;1437return;1438}14391440unsigned LoopCost = 1;1441if (TTI->isIndexedLoadLegal(TTI->MIM_PostInc, AR->getType()) ||1442TTI->isIndexedStoreLegal(TTI->MIM_PostInc, AR->getType())) {14431444// If the step size matches the base offset, we could use pre-indexed1445// addressing.1446if (AMK == TTI::AMK_PreIndexed && F.BaseOffset.isFixed()) {1447if (auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE)))1448if (Step->getAPInt() == F.BaseOffset.getFixedValue())1449LoopCost = 0;1450} else if (AMK == TTI::AMK_PostIndexed) {1451const SCEV *LoopStep = AR->getStepRecurrence(*SE);1452if (isa<SCEVConstant>(LoopStep)) {1453const SCEV *LoopStart = AR->getStart();1454if (!isa<SCEVConstant>(LoopStart) &&1455SE->isLoopInvariant(LoopStart, L))1456LoopCost = 0;1457}1458}1459}1460C.AddRecCost += LoopCost;14611462// Add the step value register, if it needs one.1463// TODO: The non-affine case isn't precisely modeled here.1464if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1))) {1465if (!Regs.count(AR->getOperand(1))) {1466RateRegister(F, AR->getOperand(1), Regs);1467if (isLoser())1468return;1469}1470}1471}1472++C.NumRegs;14731474// Rough heuristic; favor registers which don't require extra setup1475// instructions in the preheader.1476C.SetupCost += getSetupCost(Reg, SetupCostDepthLimit);1477// Ensure we don't, even with the recusion limit, produce invalid costs.1478C.SetupCost = std::min<unsigned>(C.SetupCost, 1 << 16);14791480C.NumIVMuls += isa<SCEVMulExpr>(Reg) &&1481SE->hasComputableLoopEvolution(Reg, L);1482}14831484/// Record this register in the set. If we haven't seen it before, rate1485/// it. Optional LoserRegs provides a way to declare any formula that refers to1486/// one of those regs an instant loser.1487void Cost::RatePrimaryRegister(const Formula &F, const SCEV *Reg,1488SmallPtrSetImpl<const SCEV *> &Regs,1489SmallPtrSetImpl<const SCEV *> *LoserRegs) {1490if (LoserRegs && LoserRegs->count(Reg)) {1491Lose();1492return;1493}1494if (Regs.insert(Reg).second) {1495RateRegister(F, Reg, Regs);1496if (LoserRegs && isLoser())1497LoserRegs->insert(Reg);1498}1499}15001501void Cost::RateFormula(const Formula &F,1502SmallPtrSetImpl<const SCEV *> &Regs,1503const DenseSet<const SCEV *> &VisitedRegs,1504const LSRUse &LU,1505SmallPtrSetImpl<const SCEV *> *LoserRegs) {1506if (isLoser())1507return;1508assert(F.isCanonical(*L) && "Cost is accurate only for canonical formula");1509// Tally up the registers.1510unsigned PrevAddRecCost = C.AddRecCost;1511unsigned PrevNumRegs = C.NumRegs;1512unsigned PrevNumBaseAdds = C.NumBaseAdds;1513if (const SCEV *ScaledReg = F.ScaledReg) {1514if (VisitedRegs.count(ScaledReg)) {1515Lose();1516return;1517}1518RatePrimaryRegister(F, ScaledReg, Regs, LoserRegs);1519if (isLoser())1520return;1521}1522for (const SCEV *BaseReg : F.BaseRegs) {1523if (VisitedRegs.count(BaseReg)) {1524Lose();1525return;1526}1527RatePrimaryRegister(F, BaseReg, Regs, LoserRegs);1528if (isLoser())1529return;1530}15311532// Determine how many (unfolded) adds we'll need inside the loop.1533size_t NumBaseParts = F.getNumRegs();1534if (NumBaseParts > 1)1535// Do not count the base and a possible second register if the target1536// allows to fold 2 registers.1537C.NumBaseAdds +=1538NumBaseParts - (1 + (F.Scale && isAMCompletelyFolded(*TTI, LU, F)));1539C.NumBaseAdds += (F.UnfoldedOffset.isNonZero());15401541// Accumulate non-free scaling amounts.1542C.ScaleCost += *getScalingFactorCost(*TTI, LU, F, *L).getValue();15431544// Tally up the non-zero immediates.1545for (const LSRFixup &Fixup : LU.Fixups) {1546if (Fixup.Offset.isCompatibleImmediate(F.BaseOffset)) {1547Immediate Offset = Fixup.Offset.addUnsigned(F.BaseOffset);1548if (F.BaseGV)1549C.ImmCost += 64; // Handle symbolic values conservatively.1550// TODO: This should probably be the pointer size.1551else if (Offset.isNonZero())1552C.ImmCost +=1553APInt(64, Offset.getKnownMinValue(), true).getSignificantBits();15541555// Check with target if this offset with this instruction is1556// specifically not supported.1557if (LU.Kind == LSRUse::Address && Offset.isNonZero() &&1558!isAMCompletelyFolded(*TTI, LSRUse::Address, LU.AccessTy, F.BaseGV,1559Offset, F.HasBaseReg, F.Scale, Fixup.UserInst))1560C.NumBaseAdds++;1561} else {1562// Incompatible immediate type, increase cost to avoid using1563C.ImmCost += 2048;1564}1565}15661567// If we don't count instruction cost exit here.1568if (!InsnsCost) {1569assert(isValid() && "invalid cost");1570return;1571}15721573// Treat every new register that exceeds TTI.getNumberOfRegisters() - 1 as1574// additional instruction (at least fill).1575// TODO: Need distinguish register class?1576unsigned TTIRegNum = TTI->getNumberOfRegisters(1577TTI->getRegisterClassForType(false, F.getType())) - 1;1578if (C.NumRegs > TTIRegNum) {1579// Cost already exceeded TTIRegNum, then only newly added register can add1580// new instructions.1581if (PrevNumRegs > TTIRegNum)1582C.Insns += (C.NumRegs - PrevNumRegs);1583else1584C.Insns += (C.NumRegs - TTIRegNum);1585}15861587// If ICmpZero formula ends with not 0, it could not be replaced by1588// just add or sub. We'll need to compare final result of AddRec.1589// That means we'll need an additional instruction. But if the target can1590// macro-fuse a compare with a branch, don't count this extra instruction.1591// For -10 + {0, +, 1}:1592// i = i + 1;1593// cmp i, 101594//1595// For {-10, +, 1}:1596// i = i + 1;1597if (LU.Kind == LSRUse::ICmpZero && !F.hasZeroEnd() &&1598!TTI->canMacroFuseCmp())1599C.Insns++;1600// Each new AddRec adds 1 instruction to calculation.1601C.Insns += (C.AddRecCost - PrevAddRecCost);16021603// BaseAdds adds instructions for unfolded registers.1604if (LU.Kind != LSRUse::ICmpZero)1605C.Insns += C.NumBaseAdds - PrevNumBaseAdds;1606assert(isValid() && "invalid cost");1607}16081609/// Set this cost to a losing value.1610void Cost::Lose() {1611C.Insns = std::numeric_limits<unsigned>::max();1612C.NumRegs = std::numeric_limits<unsigned>::max();1613C.AddRecCost = std::numeric_limits<unsigned>::max();1614C.NumIVMuls = std::numeric_limits<unsigned>::max();1615C.NumBaseAdds = std::numeric_limits<unsigned>::max();1616C.ImmCost = std::numeric_limits<unsigned>::max();1617C.SetupCost = std::numeric_limits<unsigned>::max();1618C.ScaleCost = std::numeric_limits<unsigned>::max();1619}16201621/// Choose the lower cost.1622bool Cost::isLess(const Cost &Other) const {1623if (InsnsCost.getNumOccurrences() > 0 && InsnsCost &&1624C.Insns != Other.C.Insns)1625return C.Insns < Other.C.Insns;1626return TTI->isLSRCostLess(C, Other.C);1627}16281629#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)1630void Cost::print(raw_ostream &OS) const {1631if (InsnsCost)1632OS << C.Insns << " instruction" << (C.Insns == 1 ? " " : "s ");1633OS << C.NumRegs << " reg" << (C.NumRegs == 1 ? "" : "s");1634if (C.AddRecCost != 0)1635OS << ", with addrec cost " << C.AddRecCost;1636if (C.NumIVMuls != 0)1637OS << ", plus " << C.NumIVMuls << " IV mul"1638<< (C.NumIVMuls == 1 ? "" : "s");1639if (C.NumBaseAdds != 0)1640OS << ", plus " << C.NumBaseAdds << " base add"1641<< (C.NumBaseAdds == 1 ? "" : "s");1642if (C.ScaleCost != 0)1643OS << ", plus " << C.ScaleCost << " scale cost";1644if (C.ImmCost != 0)1645OS << ", plus " << C.ImmCost << " imm cost";1646if (C.SetupCost != 0)1647OS << ", plus " << C.SetupCost << " setup cost";1648}16491650LLVM_DUMP_METHOD void Cost::dump() const {1651print(errs()); errs() << '\n';1652}1653#endif16541655/// Test whether this fixup always uses its value outside of the given loop.1656bool LSRFixup::isUseFullyOutsideLoop(const Loop *L) const {1657// PHI nodes use their value in their incoming blocks.1658if (const PHINode *PN = dyn_cast<PHINode>(UserInst)) {1659for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)1660if (PN->getIncomingValue(i) == OperandValToReplace &&1661L->contains(PN->getIncomingBlock(i)))1662return false;1663return true;1664}16651666return !L->contains(UserInst);1667}16681669#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)1670void LSRFixup::print(raw_ostream &OS) const {1671OS << "UserInst=";1672// Store is common and interesting enough to be worth special-casing.1673if (StoreInst *Store = dyn_cast<StoreInst>(UserInst)) {1674OS << "store ";1675Store->getOperand(0)->printAsOperand(OS, /*PrintType=*/false);1676} else if (UserInst->getType()->isVoidTy())1677OS << UserInst->getOpcodeName();1678else1679UserInst->printAsOperand(OS, /*PrintType=*/false);16801681OS << ", OperandValToReplace=";1682OperandValToReplace->printAsOperand(OS, /*PrintType=*/false);16831684for (const Loop *PIL : PostIncLoops) {1685OS << ", PostIncLoop=";1686PIL->getHeader()->printAsOperand(OS, /*PrintType=*/false);1687}16881689if (Offset.isNonZero())1690OS << ", Offset=" << Offset;1691}16921693LLVM_DUMP_METHOD void LSRFixup::dump() const {1694print(errs()); errs() << '\n';1695}1696#endif16971698/// Test whether this use as a formula which has the same registers as the given1699/// formula.1700bool LSRUse::HasFormulaWithSameRegs(const Formula &F) const {1701SmallVector<const SCEV *, 4> Key = F.BaseRegs;1702if (F.ScaledReg) Key.push_back(F.ScaledReg);1703// Unstable sort by host order ok, because this is only used for uniquifying.1704llvm::sort(Key);1705return Uniquifier.count(Key);1706}17071708/// The function returns a probability of selecting formula without Reg.1709float LSRUse::getNotSelectedProbability(const SCEV *Reg) const {1710unsigned FNum = 0;1711for (const Formula &F : Formulae)1712if (F.referencesReg(Reg))1713FNum++;1714return ((float)(Formulae.size() - FNum)) / Formulae.size();1715}17161717/// If the given formula has not yet been inserted, add it to the list, and1718/// return true. Return false otherwise. The formula must be in canonical form.1719bool LSRUse::InsertFormula(const Formula &F, const Loop &L) {1720assert(F.isCanonical(L) && "Invalid canonical representation");17211722if (!Formulae.empty() && RigidFormula)1723return false;17241725SmallVector<const SCEV *, 4> Key = F.BaseRegs;1726if (F.ScaledReg) Key.push_back(F.ScaledReg);1727// Unstable sort by host order ok, because this is only used for uniquifying.1728llvm::sort(Key);17291730if (!Uniquifier.insert(Key).second)1731return false;17321733// Using a register to hold the value of 0 is not profitable.1734assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&1735"Zero allocated in a scaled register!");1736#ifndef NDEBUG1737for (const SCEV *BaseReg : F.BaseRegs)1738assert(!BaseReg->isZero() && "Zero allocated in a base register!");1739#endif17401741// Add the formula to the list.1742Formulae.push_back(F);17431744// Record registers now being used by this use.1745Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());1746if (F.ScaledReg)1747Regs.insert(F.ScaledReg);17481749return true;1750}17511752/// Remove the given formula from this use's list.1753void LSRUse::DeleteFormula(Formula &F) {1754if (&F != &Formulae.back())1755std::swap(F, Formulae.back());1756Formulae.pop_back();1757}17581759/// Recompute the Regs field, and update RegUses.1760void LSRUse::RecomputeRegs(size_t LUIdx, RegUseTracker &RegUses) {1761// Now that we've filtered out some formulae, recompute the Regs set.1762SmallPtrSet<const SCEV *, 4> OldRegs = std::move(Regs);1763Regs.clear();1764for (const Formula &F : Formulae) {1765if (F.ScaledReg) Regs.insert(F.ScaledReg);1766Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());1767}17681769// Update the RegTracker.1770for (const SCEV *S : OldRegs)1771if (!Regs.count(S))1772RegUses.dropRegister(S, LUIdx);1773}17741775#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)1776void LSRUse::print(raw_ostream &OS) const {1777OS << "LSR Use: Kind=";1778switch (Kind) {1779case Basic: OS << "Basic"; break;1780case Special: OS << "Special"; break;1781case ICmpZero: OS << "ICmpZero"; break;1782case Address:1783OS << "Address of ";1784if (AccessTy.MemTy->isPointerTy())1785OS << "pointer"; // the full pointer type could be really verbose1786else {1787OS << *AccessTy.MemTy;1788}17891790OS << " in addrspace(" << AccessTy.AddrSpace << ')';1791}17921793OS << ", Offsets={";1794bool NeedComma = false;1795for (const LSRFixup &Fixup : Fixups) {1796if (NeedComma) OS << ',';1797OS << Fixup.Offset;1798NeedComma = true;1799}1800OS << '}';18011802if (AllFixupsOutsideLoop)1803OS << ", all-fixups-outside-loop";18041805if (WidestFixupType)1806OS << ", widest fixup type: " << *WidestFixupType;1807}18081809LLVM_DUMP_METHOD void LSRUse::dump() const {1810print(errs()); errs() << '\n';1811}1812#endif18131814static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,1815LSRUse::KindType Kind, MemAccessTy AccessTy,1816GlobalValue *BaseGV, Immediate BaseOffset,1817bool HasBaseReg, int64_t Scale,1818Instruction *Fixup /* = nullptr */) {1819switch (Kind) {1820case LSRUse::Address: {1821int64_t FixedOffset =1822BaseOffset.isScalable() ? 0 : BaseOffset.getFixedValue();1823int64_t ScalableOffset =1824BaseOffset.isScalable() ? BaseOffset.getKnownMinValue() : 0;1825return TTI.isLegalAddressingMode(AccessTy.MemTy, BaseGV, FixedOffset,1826HasBaseReg, Scale, AccessTy.AddrSpace,1827Fixup, ScalableOffset);1828}1829case LSRUse::ICmpZero:1830// There's not even a target hook for querying whether it would be legal to1831// fold a GV into an ICmp.1832if (BaseGV)1833return false;18341835// ICmp only has two operands; don't allow more than two non-trivial parts.1836if (Scale != 0 && HasBaseReg && BaseOffset.isNonZero())1837return false;18381839// ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by1840// putting the scaled register in the other operand of the icmp.1841if (Scale != 0 && Scale != -1)1842return false;18431844// If we have low-level target information, ask the target if it can fold an1845// integer immediate on an icmp.1846if (BaseOffset.isNonZero()) {1847// We don't have an interface to query whether the target supports1848// icmpzero against scalable quantities yet.1849if (BaseOffset.isScalable())1850return false;18511852// We have one of:1853// ICmpZero BaseReg + BaseOffset => ICmp BaseReg, -BaseOffset1854// ICmpZero -1*ScaleReg + BaseOffset => ICmp ScaleReg, BaseOffset1855// Offs is the ICmp immediate.1856if (Scale == 0)1857// The cast does the right thing with1858// std::numeric_limits<int64_t>::min().1859BaseOffset = BaseOffset.getFixed(-(uint64_t)BaseOffset.getFixedValue());1860return TTI.isLegalICmpImmediate(BaseOffset.getFixedValue());1861}18621863// ICmpZero BaseReg + -1*ScaleReg => ICmp BaseReg, ScaleReg1864return true;18651866case LSRUse::Basic:1867// Only handle single-register values.1868return !BaseGV && Scale == 0 && BaseOffset.isZero();18691870case LSRUse::Special:1871// Special case Basic to handle -1 scales.1872return !BaseGV && (Scale == 0 || Scale == -1) && BaseOffset.isZero();1873}18741875llvm_unreachable("Invalid LSRUse Kind!");1876}18771878static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,1879Immediate MinOffset, Immediate MaxOffset,1880LSRUse::KindType Kind, MemAccessTy AccessTy,1881GlobalValue *BaseGV, Immediate BaseOffset,1882bool HasBaseReg, int64_t Scale) {1883if (BaseOffset.isNonZero() &&1884(BaseOffset.isScalable() != MinOffset.isScalable() ||1885BaseOffset.isScalable() != MaxOffset.isScalable()))1886return false;1887// Check for overflow.1888int64_t Base = BaseOffset.getKnownMinValue();1889int64_t Min = MinOffset.getKnownMinValue();1890int64_t Max = MaxOffset.getKnownMinValue();1891if (((int64_t)((uint64_t)Base + Min) > Base) != (Min > 0))1892return false;1893MinOffset = Immediate::get((uint64_t)Base + Min, MinOffset.isScalable());1894if (((int64_t)((uint64_t)Base + Max) > Base) != (Max > 0))1895return false;1896MaxOffset = Immediate::get((uint64_t)Base + Max, MaxOffset.isScalable());18971898return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MinOffset,1899HasBaseReg, Scale) &&1900isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MaxOffset,1901HasBaseReg, Scale);1902}19031904static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,1905Immediate MinOffset, Immediate MaxOffset,1906LSRUse::KindType Kind, MemAccessTy AccessTy,1907const Formula &F, const Loop &L) {1908// For the purpose of isAMCompletelyFolded either having a canonical formula1909// or a scale not equal to zero is correct.1910// Problems may arise from non canonical formulae having a scale == 0.1911// Strictly speaking it would best to just rely on canonical formulae.1912// However, when we generate the scaled formulae, we first check that the1913// scaling factor is profitable before computing the actual ScaledReg for1914// compile time sake.1915assert((F.isCanonical(L) || F.Scale != 0));1916return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy,1917F.BaseGV, F.BaseOffset, F.HasBaseReg, F.Scale);1918}19191920/// Test whether we know how to expand the current formula.1921static bool isLegalUse(const TargetTransformInfo &TTI, Immediate MinOffset,1922Immediate MaxOffset, LSRUse::KindType Kind,1923MemAccessTy AccessTy, GlobalValue *BaseGV,1924Immediate BaseOffset, bool HasBaseReg, int64_t Scale) {1925// We know how to expand completely foldable formulae.1926return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV,1927BaseOffset, HasBaseReg, Scale) ||1928// Or formulae that use a base register produced by a sum of base1929// registers.1930(Scale == 1 &&1931isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy,1932BaseGV, BaseOffset, true, 0));1933}19341935static bool isLegalUse(const TargetTransformInfo &TTI, Immediate MinOffset,1936Immediate MaxOffset, LSRUse::KindType Kind,1937MemAccessTy AccessTy, const Formula &F) {1938return isLegalUse(TTI, MinOffset, MaxOffset, Kind, AccessTy, F.BaseGV,1939F.BaseOffset, F.HasBaseReg, F.Scale);1940}19411942static bool isLegalAddImmediate(const TargetTransformInfo &TTI,1943Immediate Offset) {1944if (Offset.isScalable())1945return TTI.isLegalAddScalableImmediate(Offset.getKnownMinValue());19461947return TTI.isLegalAddImmediate(Offset.getFixedValue());1948}19491950static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,1951const LSRUse &LU, const Formula &F) {1952// Target may want to look at the user instructions.1953if (LU.Kind == LSRUse::Address && TTI.LSRWithInstrQueries()) {1954for (const LSRFixup &Fixup : LU.Fixups)1955if (!isAMCompletelyFolded(TTI, LSRUse::Address, LU.AccessTy, F.BaseGV,1956(F.BaseOffset + Fixup.Offset), F.HasBaseReg,1957F.Scale, Fixup.UserInst))1958return false;1959return true;1960}19611962return isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind,1963LU.AccessTy, F.BaseGV, F.BaseOffset, F.HasBaseReg,1964F.Scale);1965}19661967static InstructionCost getScalingFactorCost(const TargetTransformInfo &TTI,1968const LSRUse &LU, const Formula &F,1969const Loop &L) {1970if (!F.Scale)1971return 0;19721973// If the use is not completely folded in that instruction, we will have to1974// pay an extra cost only for scale != 1.1975if (!isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind,1976LU.AccessTy, F, L))1977return F.Scale != 1;19781979switch (LU.Kind) {1980case LSRUse::Address: {1981// Check the scaling factor cost with both the min and max offsets.1982int64_t ScalableMin = 0, ScalableMax = 0, FixedMin = 0, FixedMax = 0;1983if (F.BaseOffset.isScalable()) {1984ScalableMin = (F.BaseOffset + LU.MinOffset).getKnownMinValue();1985ScalableMax = (F.BaseOffset + LU.MaxOffset).getKnownMinValue();1986} else {1987FixedMin = (F.BaseOffset + LU.MinOffset).getFixedValue();1988FixedMax = (F.BaseOffset + LU.MaxOffset).getFixedValue();1989}1990InstructionCost ScaleCostMinOffset = TTI.getScalingFactorCost(1991LU.AccessTy.MemTy, F.BaseGV, StackOffset::get(FixedMin, ScalableMin),1992F.HasBaseReg, F.Scale, LU.AccessTy.AddrSpace);1993InstructionCost ScaleCostMaxOffset = TTI.getScalingFactorCost(1994LU.AccessTy.MemTy, F.BaseGV, StackOffset::get(FixedMax, ScalableMax),1995F.HasBaseReg, F.Scale, LU.AccessTy.AddrSpace);19961997assert(ScaleCostMinOffset.isValid() && ScaleCostMaxOffset.isValid() &&1998"Legal addressing mode has an illegal cost!");1999return std::max(ScaleCostMinOffset, ScaleCostMaxOffset);2000}2001case LSRUse::ICmpZero:2002case LSRUse::Basic:2003case LSRUse::Special:2004// The use is completely folded, i.e., everything is folded into the2005// instruction.2006return 0;2007}20082009llvm_unreachable("Invalid LSRUse Kind!");2010}20112012static bool isAlwaysFoldable(const TargetTransformInfo &TTI,2013LSRUse::KindType Kind, MemAccessTy AccessTy,2014GlobalValue *BaseGV, Immediate BaseOffset,2015bool HasBaseReg) {2016// Fast-path: zero is always foldable.2017if (BaseOffset.isZero() && !BaseGV)2018return true;20192020// Conservatively, create an address with an immediate and a2021// base and a scale.2022int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;20232024// Canonicalize a scale of 1 to a base register if the formula doesn't2025// already have a base register.2026if (!HasBaseReg && Scale == 1) {2027Scale = 0;2028HasBaseReg = true;2029}20302031// FIXME: Try with + without a scale? Maybe based on TTI?2032// I think basereg + scaledreg + immediateoffset isn't a good 'conservative'2033// default for many architectures, not just AArch64 SVE. More investigation2034// needed later to determine if this should be used more widely than just2035// on scalable types.2036if (HasBaseReg && BaseOffset.isNonZero() && Kind != LSRUse::ICmpZero &&2037AccessTy.MemTy && AccessTy.MemTy->isScalableTy() && DropScaledForVScale)2038Scale = 0;20392040return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, BaseOffset,2041HasBaseReg, Scale);2042}20432044static bool isAlwaysFoldable(const TargetTransformInfo &TTI,2045ScalarEvolution &SE, Immediate MinOffset,2046Immediate MaxOffset, LSRUse::KindType Kind,2047MemAccessTy AccessTy, const SCEV *S,2048bool HasBaseReg) {2049// Fast-path: zero is always foldable.2050if (S->isZero()) return true;20512052// Conservatively, create an address with an immediate and a2053// base and a scale.2054Immediate BaseOffset = ExtractImmediate(S, SE);2055GlobalValue *BaseGV = ExtractSymbol(S, SE);20562057// If there's anything else involved, it's not foldable.2058if (!S->isZero()) return false;20592060// Fast-path: zero is always foldable.2061if (BaseOffset.isZero() && !BaseGV)2062return true;20632064if (BaseOffset.isScalable())2065return false;20662067// Conservatively, create an address with an immediate and a2068// base and a scale.2069int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;20702071return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV,2072BaseOffset, HasBaseReg, Scale);2073}20742075namespace {20762077/// An individual increment in a Chain of IV increments. Relate an IV user to2078/// an expression that computes the IV it uses from the IV used by the previous2079/// link in the Chain.2080///2081/// For the head of a chain, IncExpr holds the absolute SCEV expression for the2082/// original IVOperand. The head of the chain's IVOperand is only valid during2083/// chain collection, before LSR replaces IV users. During chain generation,2084/// IncExpr can be used to find the new IVOperand that computes the same2085/// expression.2086struct IVInc {2087Instruction *UserInst;2088Value* IVOperand;2089const SCEV *IncExpr;20902091IVInc(Instruction *U, Value *O, const SCEV *E)2092: UserInst(U), IVOperand(O), IncExpr(E) {}2093};20942095// The list of IV increments in program order. We typically add the head of a2096// chain without finding subsequent links.2097struct IVChain {2098SmallVector<IVInc, 1> Incs;2099const SCEV *ExprBase = nullptr;21002101IVChain() = default;2102IVChain(const IVInc &Head, const SCEV *Base)2103: Incs(1, Head), ExprBase(Base) {}21042105using const_iterator = SmallVectorImpl<IVInc>::const_iterator;21062107// Return the first increment in the chain.2108const_iterator begin() const {2109assert(!Incs.empty());2110return std::next(Incs.begin());2111}2112const_iterator end() const {2113return Incs.end();2114}21152116// Returns true if this chain contains any increments.2117bool hasIncs() const { return Incs.size() >= 2; }21182119// Add an IVInc to the end of this chain.2120void add(const IVInc &X) { Incs.push_back(X); }21212122// Returns the last UserInst in the chain.2123Instruction *tailUserInst() const { return Incs.back().UserInst; }21242125// Returns true if IncExpr can be profitably added to this chain.2126bool isProfitableIncrement(const SCEV *OperExpr,2127const SCEV *IncExpr,2128ScalarEvolution&);2129};21302131/// Helper for CollectChains to track multiple IV increment uses. Distinguish2132/// between FarUsers that definitely cross IV increments and NearUsers that may2133/// be used between IV increments.2134struct ChainUsers {2135SmallPtrSet<Instruction*, 4> FarUsers;2136SmallPtrSet<Instruction*, 4> NearUsers;2137};21382139/// This class holds state for the main loop strength reduction logic.2140class LSRInstance {2141IVUsers &IU;2142ScalarEvolution &SE;2143DominatorTree &DT;2144LoopInfo &LI;2145AssumptionCache &AC;2146TargetLibraryInfo &TLI;2147const TargetTransformInfo &TTI;2148Loop *const L;2149MemorySSAUpdater *MSSAU;2150TTI::AddressingModeKind AMK;2151mutable SCEVExpander Rewriter;2152bool Changed = false;21532154/// This is the insert position that the current loop's induction variable2155/// increment should be placed. In simple loops, this is the latch block's2156/// terminator. But in more complicated cases, this is a position which will2157/// dominate all the in-loop post-increment users.2158Instruction *IVIncInsertPos = nullptr;21592160/// Interesting factors between use strides.2161///2162/// We explicitly use a SetVector which contains a SmallSet, instead of the2163/// default, a SmallDenseSet, because we need to use the full range of2164/// int64_ts, and there's currently no good way of doing that with2165/// SmallDenseSet.2166SetVector<int64_t, SmallVector<int64_t, 8>, SmallSet<int64_t, 8>> Factors;21672168/// The cost of the current SCEV, the best solution by LSR will be dropped if2169/// the solution is not profitable.2170Cost BaselineCost;21712172/// Interesting use types, to facilitate truncation reuse.2173SmallSetVector<Type *, 4> Types;21742175/// The list of interesting uses.2176mutable SmallVector<LSRUse, 16> Uses;21772178/// Track which uses use which register candidates.2179RegUseTracker RegUses;21802181// Limit the number of chains to avoid quadratic behavior. We don't expect to2182// have more than a few IV increment chains in a loop. Missing a Chain falls2183// back to normal LSR behavior for those uses.2184static const unsigned MaxChains = 8;21852186/// IV users can form a chain of IV increments.2187SmallVector<IVChain, MaxChains> IVChainVec;21882189/// IV users that belong to profitable IVChains.2190SmallPtrSet<Use*, MaxChains> IVIncSet;21912192/// Induction variables that were generated and inserted by the SCEV Expander.2193SmallVector<llvm::WeakVH, 2> ScalarEvolutionIVs;21942195void OptimizeShadowIV();2196bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse);2197ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse);2198void OptimizeLoopTermCond();21992200void ChainInstruction(Instruction *UserInst, Instruction *IVOper,2201SmallVectorImpl<ChainUsers> &ChainUsersVec);2202void FinalizeChain(IVChain &Chain);2203void CollectChains();2204void GenerateIVChain(const IVChain &Chain,2205SmallVectorImpl<WeakTrackingVH> &DeadInsts);22062207void CollectInterestingTypesAndFactors();2208void CollectFixupsAndInitialFormulae();22092210// Support for sharing of LSRUses between LSRFixups.2211using UseMapTy = DenseMap<LSRUse::SCEVUseKindPair, size_t>;2212UseMapTy UseMap;22132214bool reconcileNewOffset(LSRUse &LU, Immediate NewOffset, bool HasBaseReg,2215LSRUse::KindType Kind, MemAccessTy AccessTy);22162217std::pair<size_t, Immediate> getUse(const SCEV *&Expr, LSRUse::KindType Kind,2218MemAccessTy AccessTy);22192220void DeleteUse(LSRUse &LU, size_t LUIdx);22212222LSRUse *FindUseWithSimilarFormula(const Formula &F, const LSRUse &OrigLU);22232224void InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);2225void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);2226void CountRegisters(const Formula &F, size_t LUIdx);2227bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F);22282229void CollectLoopInvariantFixupsAndFormulae();22302231void GenerateReassociations(LSRUse &LU, unsigned LUIdx, Formula Base,2232unsigned Depth = 0);22332234void GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx,2235const Formula &Base, unsigned Depth,2236size_t Idx, bool IsScaledReg = false);2237void GenerateCombinations(LSRUse &LU, unsigned LUIdx, Formula Base);2238void GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx,2239const Formula &Base, size_t Idx,2240bool IsScaledReg = false);2241void GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);2242void GenerateConstantOffsetsImpl(LSRUse &LU, unsigned LUIdx,2243const Formula &Base,2244const SmallVectorImpl<Immediate> &Worklist,2245size_t Idx, bool IsScaledReg = false);2246void GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);2247void GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, Formula Base);2248void GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base);2249void GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base);2250void GenerateCrossUseConstantOffsets();2251void GenerateAllReuseFormulae();22522253void FilterOutUndesirableDedicatedRegisters();22542255size_t EstimateSearchSpaceComplexity() const;2256void NarrowSearchSpaceByDetectingSupersets();2257void NarrowSearchSpaceByCollapsingUnrolledCode();2258void NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();2259void NarrowSearchSpaceByFilterFormulaWithSameScaledReg();2260void NarrowSearchSpaceByFilterPostInc();2261void NarrowSearchSpaceByDeletingCostlyFormulas();2262void NarrowSearchSpaceByPickingWinnerRegs();2263void NarrowSearchSpaceUsingHeuristics();22642265void SolveRecurse(SmallVectorImpl<const Formula *> &Solution,2266Cost &SolutionCost,2267SmallVectorImpl<const Formula *> &Workspace,2268const Cost &CurCost,2269const SmallPtrSet<const SCEV *, 16> &CurRegs,2270DenseSet<const SCEV *> &VisitedRegs) const;2271void Solve(SmallVectorImpl<const Formula *> &Solution) const;22722273BasicBlock::iterator2274HoistInsertPosition(BasicBlock::iterator IP,2275const SmallVectorImpl<Instruction *> &Inputs) const;2276BasicBlock::iterator AdjustInsertPositionForExpand(BasicBlock::iterator IP,2277const LSRFixup &LF,2278const LSRUse &LU) const;22792280Value *Expand(const LSRUse &LU, const LSRFixup &LF, const Formula &F,2281BasicBlock::iterator IP,2282SmallVectorImpl<WeakTrackingVH> &DeadInsts) const;2283void RewriteForPHI(PHINode *PN, const LSRUse &LU, const LSRFixup &LF,2284const Formula &F,2285SmallVectorImpl<WeakTrackingVH> &DeadInsts) const;2286void Rewrite(const LSRUse &LU, const LSRFixup &LF, const Formula &F,2287SmallVectorImpl<WeakTrackingVH> &DeadInsts) const;2288void ImplementSolution(const SmallVectorImpl<const Formula *> &Solution);22892290public:2291LSRInstance(Loop *L, IVUsers &IU, ScalarEvolution &SE, DominatorTree &DT,2292LoopInfo &LI, const TargetTransformInfo &TTI, AssumptionCache &AC,2293TargetLibraryInfo &TLI, MemorySSAUpdater *MSSAU);22942295bool getChanged() const { return Changed; }2296const SmallVectorImpl<WeakVH> &getScalarEvolutionIVs() const {2297return ScalarEvolutionIVs;2298}22992300void print_factors_and_types(raw_ostream &OS) const;2301void print_fixups(raw_ostream &OS) const;2302void print_uses(raw_ostream &OS) const;2303void print(raw_ostream &OS) const;2304void dump() const;2305};23062307} // end anonymous namespace23082309/// If IV is used in a int-to-float cast inside the loop then try to eliminate2310/// the cast operation.2311void LSRInstance::OptimizeShadowIV() {2312const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);2313if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))2314return;23152316for (IVUsers::const_iterator UI = IU.begin(), E = IU.end();2317UI != E; /* empty */) {2318IVUsers::const_iterator CandidateUI = UI;2319++UI;2320Instruction *ShadowUse = CandidateUI->getUser();2321Type *DestTy = nullptr;2322bool IsSigned = false;23232324/* If shadow use is a int->float cast then insert a second IV2325to eliminate this cast.23262327for (unsigned i = 0; i < n; ++i)2328foo((double)i);23292330is transformed into23312332double d = 0.0;2333for (unsigned i = 0; i < n; ++i, ++d)2334foo(d);2335*/2336if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser())) {2337IsSigned = false;2338DestTy = UCast->getDestTy();2339}2340else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser())) {2341IsSigned = true;2342DestTy = SCast->getDestTy();2343}2344if (!DestTy) continue;23452346// If target does not support DestTy natively then do not apply2347// this transformation.2348if (!TTI.isTypeLegal(DestTy)) continue;23492350PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));2351if (!PH) continue;2352if (PH->getNumIncomingValues() != 2) continue;23532354// If the calculation in integers overflows, the result in FP type will2355// differ. So we only can do this transformation if we are guaranteed to not2356// deal with overflowing values2357const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(PH));2358if (!AR) continue;2359if (IsSigned && !AR->hasNoSignedWrap()) continue;2360if (!IsSigned && !AR->hasNoUnsignedWrap()) continue;23612362Type *SrcTy = PH->getType();2363int Mantissa = DestTy->getFPMantissaWidth();2364if (Mantissa == -1) continue;2365if ((int)SE.getTypeSizeInBits(SrcTy) > Mantissa)2366continue;23672368unsigned Entry, Latch;2369if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {2370Entry = 0;2371Latch = 1;2372} else {2373Entry = 1;2374Latch = 0;2375}23762377ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));2378if (!Init) continue;2379Constant *NewInit = ConstantFP::get(DestTy, IsSigned ?2380(double)Init->getSExtValue() :2381(double)Init->getZExtValue());23822383BinaryOperator *Incr =2384dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));2385if (!Incr) continue;2386if (Incr->getOpcode() != Instruction::Add2387&& Incr->getOpcode() != Instruction::Sub)2388continue;23892390/* Initialize new IV, double d = 0.0 in above example. */2391ConstantInt *C = nullptr;2392if (Incr->getOperand(0) == PH)2393C = dyn_cast<ConstantInt>(Incr->getOperand(1));2394else if (Incr->getOperand(1) == PH)2395C = dyn_cast<ConstantInt>(Incr->getOperand(0));2396else2397continue;23982399if (!C) continue;24002401// Ignore negative constants, as the code below doesn't handle them2402// correctly. TODO: Remove this restriction.2403if (!C->getValue().isStrictlyPositive())2404continue;24052406/* Add new PHINode. */2407PHINode *NewPH = PHINode::Create(DestTy, 2, "IV.S.", PH->getIterator());2408NewPH->setDebugLoc(PH->getDebugLoc());24092410/* create new increment. '++d' in above example. */2411Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue());2412BinaryOperator *NewIncr = BinaryOperator::Create(2413Incr->getOpcode() == Instruction::Add ? Instruction::FAdd2414: Instruction::FSub,2415NewPH, CFP, "IV.S.next.", Incr->getIterator());2416NewIncr->setDebugLoc(Incr->getDebugLoc());24172418NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));2419NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));24202421/* Remove cast operation */2422ShadowUse->replaceAllUsesWith(NewPH);2423ShadowUse->eraseFromParent();2424Changed = true;2425break;2426}2427}24282429/// If Cond has an operand that is an expression of an IV, set the IV user and2430/// stride information and return true, otherwise return false.2431bool LSRInstance::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse) {2432for (IVStrideUse &U : IU)2433if (U.getUser() == Cond) {2434// NOTE: we could handle setcc instructions with multiple uses here, but2435// InstCombine does it as well for simple uses, it's not clear that it2436// occurs enough in real life to handle.2437CondUse = &U;2438return true;2439}2440return false;2441}24422443/// Rewrite the loop's terminating condition if it uses a max computation.2444///2445/// This is a narrow solution to a specific, but acute, problem. For loops2446/// like this:2447///2448/// i = 0;2449/// do {2450/// p[i] = 0.0;2451/// } while (++i < n);2452///2453/// the trip count isn't just 'n', because 'n' might not be positive. And2454/// unfortunately this can come up even for loops where the user didn't use2455/// a C do-while loop. For example, seemingly well-behaved top-test loops2456/// will commonly be lowered like this:2457///2458/// if (n > 0) {2459/// i = 0;2460/// do {2461/// p[i] = 0.0;2462/// } while (++i < n);2463/// }2464///2465/// and then it's possible for subsequent optimization to obscure the if2466/// test in such a way that indvars can't find it.2467///2468/// When indvars can't find the if test in loops like this, it creates a2469/// max expression, which allows it to give the loop a canonical2470/// induction variable:2471///2472/// i = 0;2473/// max = n < 1 ? 1 : n;2474/// do {2475/// p[i] = 0.0;2476/// } while (++i != max);2477///2478/// Canonical induction variables are necessary because the loop passes2479/// are designed around them. The most obvious example of this is the2480/// LoopInfo analysis, which doesn't remember trip count values. It2481/// expects to be able to rediscover the trip count each time it is2482/// needed, and it does this using a simple analysis that only succeeds if2483/// the loop has a canonical induction variable.2484///2485/// However, when it comes time to generate code, the maximum operation2486/// can be quite costly, especially if it's inside of an outer loop.2487///2488/// This function solves this problem by detecting this type of loop and2489/// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting2490/// the instructions for the maximum computation.2491ICmpInst *LSRInstance::OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse) {2492// Check that the loop matches the pattern we're looking for.2493if (Cond->getPredicate() != CmpInst::ICMP_EQ &&2494Cond->getPredicate() != CmpInst::ICMP_NE)2495return Cond;24962497SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));2498if (!Sel || !Sel->hasOneUse()) return Cond;24992500const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);2501if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))2502return Cond;2503const SCEV *One = SE.getConstant(BackedgeTakenCount->getType(), 1);25042505// Add one to the backedge-taken count to get the trip count.2506const SCEV *IterationCount = SE.getAddExpr(One, BackedgeTakenCount);2507if (IterationCount != SE.getSCEV(Sel)) return Cond;25082509// Check for a max calculation that matches the pattern. There's no check2510// for ICMP_ULE here because the comparison would be with zero, which2511// isn't interesting.2512CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;2513const SCEVNAryExpr *Max = nullptr;2514if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(BackedgeTakenCount)) {2515Pred = ICmpInst::ICMP_SLE;2516Max = S;2517} else if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(IterationCount)) {2518Pred = ICmpInst::ICMP_SLT;2519Max = S;2520} else if (const SCEVUMaxExpr *U = dyn_cast<SCEVUMaxExpr>(IterationCount)) {2521Pred = ICmpInst::ICMP_ULT;2522Max = U;2523} else {2524// No match; bail.2525return Cond;2526}25272528// To handle a max with more than two operands, this optimization would2529// require additional checking and setup.2530if (Max->getNumOperands() != 2)2531return Cond;25322533const SCEV *MaxLHS = Max->getOperand(0);2534const SCEV *MaxRHS = Max->getOperand(1);25352536// ScalarEvolution canonicalizes constants to the left. For < and >, look2537// for a comparison with 1. For <= and >=, a comparison with zero.2538if (!MaxLHS ||2539(ICmpInst::isTrueWhenEqual(Pred) ? !MaxLHS->isZero() : (MaxLHS != One)))2540return Cond;25412542// Check the relevant induction variable for conformance to2543// the pattern.2544const SCEV *IV = SE.getSCEV(Cond->getOperand(0));2545const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);2546if (!AR || !AR->isAffine() ||2547AR->getStart() != One ||2548AR->getStepRecurrence(SE) != One)2549return Cond;25502551assert(AR->getLoop() == L &&2552"Loop condition operand is an addrec in a different loop!");25532554// Check the right operand of the select, and remember it, as it will2555// be used in the new comparison instruction.2556Value *NewRHS = nullptr;2557if (ICmpInst::isTrueWhenEqual(Pred)) {2558// Look for n+1, and grab n.2559if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(1)))2560if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1)))2561if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS)2562NewRHS = BO->getOperand(0);2563if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(2)))2564if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1)))2565if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS)2566NewRHS = BO->getOperand(0);2567if (!NewRHS)2568return Cond;2569} else if (SE.getSCEV(Sel->getOperand(1)) == MaxRHS)2570NewRHS = Sel->getOperand(1);2571else if (SE.getSCEV(Sel->getOperand(2)) == MaxRHS)2572NewRHS = Sel->getOperand(2);2573else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(MaxRHS))2574NewRHS = SU->getValue();2575else2576// Max doesn't match expected pattern.2577return Cond;25782579// Determine the new comparison opcode. It may be signed or unsigned,2580// and the original comparison may be either equality or inequality.2581if (Cond->getPredicate() == CmpInst::ICMP_EQ)2582Pred = CmpInst::getInversePredicate(Pred);25832584// Ok, everything looks ok to change the condition into an SLT or SGE and2585// delete the max calculation.2586ICmpInst *NewCond = new ICmpInst(Cond->getIterator(), Pred,2587Cond->getOperand(0), NewRHS, "scmp");25882589// Delete the max calculation instructions.2590NewCond->setDebugLoc(Cond->getDebugLoc());2591Cond->replaceAllUsesWith(NewCond);2592CondUse->setUser(NewCond);2593Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));2594Cond->eraseFromParent();2595Sel->eraseFromParent();2596if (Cmp->use_empty())2597Cmp->eraseFromParent();2598return NewCond;2599}26002601/// Change loop terminating condition to use the postinc iv when possible.2602void2603LSRInstance::OptimizeLoopTermCond() {2604SmallPtrSet<Instruction *, 4> PostIncs;26052606// We need a different set of heuristics for rotated and non-rotated loops.2607// If a loop is rotated then the latch is also the backedge, so inserting2608// post-inc expressions just before the latch is ideal. To reduce live ranges2609// it also makes sense to rewrite terminating conditions to use post-inc2610// expressions.2611//2612// If the loop is not rotated then the latch is not a backedge; the latch2613// check is done in the loop head. Adding post-inc expressions before the2614// latch will cause overlapping live-ranges of pre-inc and post-inc expressions2615// in the loop body. In this case we do *not* want to use post-inc expressions2616// in the latch check, and we want to insert post-inc expressions before2617// the backedge.2618BasicBlock *LatchBlock = L->getLoopLatch();2619SmallVector<BasicBlock*, 8> ExitingBlocks;2620L->getExitingBlocks(ExitingBlocks);2621if (!llvm::is_contained(ExitingBlocks, LatchBlock)) {2622// The backedge doesn't exit the loop; treat this as a head-tested loop.2623IVIncInsertPos = LatchBlock->getTerminator();2624return;2625}26262627// Otherwise treat this as a rotated loop.2628for (BasicBlock *ExitingBlock : ExitingBlocks) {2629// Get the terminating condition for the loop if possible. If we2630// can, we want to change it to use a post-incremented version of its2631// induction variable, to allow coalescing the live ranges for the IV into2632// one register value.26332634BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());2635if (!TermBr)2636continue;2637// FIXME: Overly conservative, termination condition could be an 'or' etc..2638if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))2639continue;26402641// Search IVUsesByStride to find Cond's IVUse if there is one.2642IVStrideUse *CondUse = nullptr;2643ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());2644if (!FindIVUserForCond(Cond, CondUse))2645continue;26462647// If the trip count is computed in terms of a max (due to ScalarEvolution2648// being unable to find a sufficient guard, for example), change the loop2649// comparison to use SLT or ULT instead of NE.2650// One consequence of doing this now is that it disrupts the count-down2651// optimization. That's not always a bad thing though, because in such2652// cases it may still be worthwhile to avoid a max.2653Cond = OptimizeMax(Cond, CondUse);26542655// If this exiting block dominates the latch block, it may also use2656// the post-inc value if it won't be shared with other uses.2657// Check for dominance.2658if (!DT.dominates(ExitingBlock, LatchBlock))2659continue;26602661// Conservatively avoid trying to use the post-inc value in non-latch2662// exits if there may be pre-inc users in intervening blocks.2663if (LatchBlock != ExitingBlock)2664for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)2665// Test if the use is reachable from the exiting block. This dominator2666// query is a conservative approximation of reachability.2667if (&*UI != CondUse &&2668!DT.properlyDominates(UI->getUser()->getParent(), ExitingBlock)) {2669// Conservatively assume there may be reuse if the quotient of their2670// strides could be a legal scale.2671const SCEV *A = IU.getStride(*CondUse, L);2672const SCEV *B = IU.getStride(*UI, L);2673if (!A || !B) continue;2674if (SE.getTypeSizeInBits(A->getType()) !=2675SE.getTypeSizeInBits(B->getType())) {2676if (SE.getTypeSizeInBits(A->getType()) >2677SE.getTypeSizeInBits(B->getType()))2678B = SE.getSignExtendExpr(B, A->getType());2679else2680A = SE.getSignExtendExpr(A, B->getType());2681}2682if (const SCEVConstant *D =2683dyn_cast_or_null<SCEVConstant>(getExactSDiv(B, A, SE))) {2684const ConstantInt *C = D->getValue();2685// Stride of one or negative one can have reuse with non-addresses.2686if (C->isOne() || C->isMinusOne())2687goto decline_post_inc;2688// Avoid weird situations.2689if (C->getValue().getSignificantBits() >= 64 ||2690C->getValue().isMinSignedValue())2691goto decline_post_inc;2692// Check for possible scaled-address reuse.2693if (isAddressUse(TTI, UI->getUser(), UI->getOperandValToReplace())) {2694MemAccessTy AccessTy = getAccessType(2695TTI, UI->getUser(), UI->getOperandValToReplace());2696int64_t Scale = C->getSExtValue();2697if (TTI.isLegalAddressingMode(AccessTy.MemTy, /*BaseGV=*/nullptr,2698/*BaseOffset=*/0,2699/*HasBaseReg=*/true, Scale,2700AccessTy.AddrSpace))2701goto decline_post_inc;2702Scale = -Scale;2703if (TTI.isLegalAddressingMode(AccessTy.MemTy, /*BaseGV=*/nullptr,2704/*BaseOffset=*/0,2705/*HasBaseReg=*/true, Scale,2706AccessTy.AddrSpace))2707goto decline_post_inc;2708}2709}2710}27112712LLVM_DEBUG(dbgs() << " Change loop exiting icmp to use postinc iv: "2713<< *Cond << '\n');27142715// It's possible for the setcc instruction to be anywhere in the loop, and2716// possible for it to have multiple users. If it is not immediately before2717// the exiting block branch, move it.2718if (Cond->getNextNonDebugInstruction() != TermBr) {2719if (Cond->hasOneUse()) {2720Cond->moveBefore(TermBr);2721} else {2722// Clone the terminating condition and insert into the loopend.2723ICmpInst *OldCond = Cond;2724Cond = cast<ICmpInst>(Cond->clone());2725Cond->setName(L->getHeader()->getName() + ".termcond");2726Cond->insertInto(ExitingBlock, TermBr->getIterator());27272728// Clone the IVUse, as the old use still exists!2729CondUse = &IU.AddUser(Cond, CondUse->getOperandValToReplace());2730TermBr->replaceUsesOfWith(OldCond, Cond);2731}2732}27332734// If we get to here, we know that we can transform the setcc instruction to2735// use the post-incremented version of the IV, allowing us to coalesce the2736// live ranges for the IV correctly.2737CondUse->transformToPostInc(L);2738Changed = true;27392740PostIncs.insert(Cond);2741decline_post_inc:;2742}27432744// Determine an insertion point for the loop induction variable increment. It2745// must dominate all the post-inc comparisons we just set up, and it must2746// dominate the loop latch edge.2747IVIncInsertPos = L->getLoopLatch()->getTerminator();2748for (Instruction *Inst : PostIncs)2749IVIncInsertPos = DT.findNearestCommonDominator(IVIncInsertPos, Inst);2750}27512752/// Determine if the given use can accommodate a fixup at the given offset and2753/// other details. If so, update the use and return true.2754bool LSRInstance::reconcileNewOffset(LSRUse &LU, Immediate NewOffset,2755bool HasBaseReg, LSRUse::KindType Kind,2756MemAccessTy AccessTy) {2757Immediate NewMinOffset = LU.MinOffset;2758Immediate NewMaxOffset = LU.MaxOffset;2759MemAccessTy NewAccessTy = AccessTy;27602761// Check for a mismatched kind. It's tempting to collapse mismatched kinds to2762// something conservative, however this can pessimize in the case that one of2763// the uses will have all its uses outside the loop, for example.2764if (LU.Kind != Kind)2765return false;27662767// Check for a mismatched access type, and fall back conservatively as needed.2768// TODO: Be less conservative when the type is similar and can use the same2769// addressing modes.2770if (Kind == LSRUse::Address) {2771if (AccessTy.MemTy != LU.AccessTy.MemTy) {2772NewAccessTy = MemAccessTy::getUnknown(AccessTy.MemTy->getContext(),2773AccessTy.AddrSpace);2774}2775}27762777// Conservatively assume HasBaseReg is true for now.2778if (Immediate::isKnownLT(NewOffset, LU.MinOffset)) {2779if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr,2780LU.MaxOffset - NewOffset, HasBaseReg))2781return false;2782NewMinOffset = NewOffset;2783} else if (Immediate::isKnownGT(NewOffset, LU.MaxOffset)) {2784if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr,2785NewOffset - LU.MinOffset, HasBaseReg))2786return false;2787NewMaxOffset = NewOffset;2788}27892790// FIXME: We should be able to handle some level of scalable offset support2791// for 'void', but in order to get basic support up and running this is2792// being left out.2793if (NewAccessTy.MemTy && NewAccessTy.MemTy->isVoidTy() &&2794(NewMinOffset.isScalable() || NewMaxOffset.isScalable()))2795return false;27962797// Update the use.2798LU.MinOffset = NewMinOffset;2799LU.MaxOffset = NewMaxOffset;2800LU.AccessTy = NewAccessTy;2801return true;2802}28032804/// Return an LSRUse index and an offset value for a fixup which needs the given2805/// expression, with the given kind and optional access type. Either reuse an2806/// existing use or create a new one, as needed.2807std::pair<size_t, Immediate> LSRInstance::getUse(const SCEV *&Expr,2808LSRUse::KindType Kind,2809MemAccessTy AccessTy) {2810const SCEV *Copy = Expr;2811Immediate Offset = ExtractImmediate(Expr, SE);28122813// Basic uses can't accept any offset, for example.2814if (!isAlwaysFoldable(TTI, Kind, AccessTy, /*BaseGV=*/ nullptr,2815Offset, /*HasBaseReg=*/ true)) {2816Expr = Copy;2817Offset = Immediate::getFixed(0);2818}28192820std::pair<UseMapTy::iterator, bool> P =2821UseMap.insert(std::make_pair(LSRUse::SCEVUseKindPair(Expr, Kind), 0));2822if (!P.second) {2823// A use already existed with this base.2824size_t LUIdx = P.first->second;2825LSRUse &LU = Uses[LUIdx];2826if (reconcileNewOffset(LU, Offset, /*HasBaseReg=*/true, Kind, AccessTy))2827// Reuse this use.2828return std::make_pair(LUIdx, Offset);2829}28302831// Create a new use.2832size_t LUIdx = Uses.size();2833P.first->second = LUIdx;2834Uses.push_back(LSRUse(Kind, AccessTy));2835LSRUse &LU = Uses[LUIdx];28362837LU.MinOffset = Offset;2838LU.MaxOffset = Offset;2839return std::make_pair(LUIdx, Offset);2840}28412842/// Delete the given use from the Uses list.2843void LSRInstance::DeleteUse(LSRUse &LU, size_t LUIdx) {2844if (&LU != &Uses.back())2845std::swap(LU, Uses.back());2846Uses.pop_back();28472848// Update RegUses.2849RegUses.swapAndDropUse(LUIdx, Uses.size());2850}28512852/// Look for a use distinct from OrigLU which is has a formula that has the same2853/// registers as the given formula.2854LSRUse *2855LSRInstance::FindUseWithSimilarFormula(const Formula &OrigF,2856const LSRUse &OrigLU) {2857// Search all uses for the formula. This could be more clever.2858for (LSRUse &LU : Uses) {2859// Check whether this use is close enough to OrigLU, to see whether it's2860// worthwhile looking through its formulae.2861// Ignore ICmpZero uses because they may contain formulae generated by2862// GenerateICmpZeroScales, in which case adding fixup offsets may2863// be invalid.2864if (&LU != &OrigLU &&2865LU.Kind != LSRUse::ICmpZero &&2866LU.Kind == OrigLU.Kind && OrigLU.AccessTy == LU.AccessTy &&2867LU.WidestFixupType == OrigLU.WidestFixupType &&2868LU.HasFormulaWithSameRegs(OrigF)) {2869// Scan through this use's formulae.2870for (const Formula &F : LU.Formulae) {2871// Check to see if this formula has the same registers and symbols2872// as OrigF.2873if (F.BaseRegs == OrigF.BaseRegs &&2874F.ScaledReg == OrigF.ScaledReg &&2875F.BaseGV == OrigF.BaseGV &&2876F.Scale == OrigF.Scale &&2877F.UnfoldedOffset == OrigF.UnfoldedOffset) {2878if (F.BaseOffset.isZero())2879return &LU;2880// This is the formula where all the registers and symbols matched;2881// there aren't going to be any others. Since we declined it, we2882// can skip the rest of the formulae and proceed to the next LSRUse.2883break;2884}2885}2886}2887}28882889// Nothing looked good.2890return nullptr;2891}28922893void LSRInstance::CollectInterestingTypesAndFactors() {2894SmallSetVector<const SCEV *, 4> Strides;28952896// Collect interesting types and strides.2897SmallVector<const SCEV *, 4> Worklist;2898for (const IVStrideUse &U : IU) {2899const SCEV *Expr = IU.getExpr(U);2900if (!Expr)2901continue;29022903// Collect interesting types.2904Types.insert(SE.getEffectiveSCEVType(Expr->getType()));29052906// Add strides for mentioned loops.2907Worklist.push_back(Expr);2908do {2909const SCEV *S = Worklist.pop_back_val();2910if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {2911if (AR->getLoop() == L)2912Strides.insert(AR->getStepRecurrence(SE));2913Worklist.push_back(AR->getStart());2914} else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {2915append_range(Worklist, Add->operands());2916}2917} while (!Worklist.empty());2918}29192920// Compute interesting factors from the set of interesting strides.2921for (SmallSetVector<const SCEV *, 4>::const_iterator2922I = Strides.begin(), E = Strides.end(); I != E; ++I)2923for (SmallSetVector<const SCEV *, 4>::const_iterator NewStrideIter =2924std::next(I); NewStrideIter != E; ++NewStrideIter) {2925const SCEV *OldStride = *I;2926const SCEV *NewStride = *NewStrideIter;29272928if (SE.getTypeSizeInBits(OldStride->getType()) !=2929SE.getTypeSizeInBits(NewStride->getType())) {2930if (SE.getTypeSizeInBits(OldStride->getType()) >2931SE.getTypeSizeInBits(NewStride->getType()))2932NewStride = SE.getSignExtendExpr(NewStride, OldStride->getType());2933else2934OldStride = SE.getSignExtendExpr(OldStride, NewStride->getType());2935}2936if (const SCEVConstant *Factor =2937dyn_cast_or_null<SCEVConstant>(getExactSDiv(NewStride, OldStride,2938SE, true))) {2939if (Factor->getAPInt().getSignificantBits() <= 64 && !Factor->isZero())2940Factors.insert(Factor->getAPInt().getSExtValue());2941} else if (const SCEVConstant *Factor =2942dyn_cast_or_null<SCEVConstant>(getExactSDiv(OldStride,2943NewStride,2944SE, true))) {2945if (Factor->getAPInt().getSignificantBits() <= 64 && !Factor->isZero())2946Factors.insert(Factor->getAPInt().getSExtValue());2947}2948}29492950// If all uses use the same type, don't bother looking for truncation-based2951// reuse.2952if (Types.size() == 1)2953Types.clear();29542955LLVM_DEBUG(print_factors_and_types(dbgs()));2956}29572958/// Helper for CollectChains that finds an IV operand (computed by an AddRec in2959/// this loop) within [OI,OE) or returns OE. If IVUsers mapped Instructions to2960/// IVStrideUses, we could partially skip this.2961static User::op_iterator2962findIVOperand(User::op_iterator OI, User::op_iterator OE,2963Loop *L, ScalarEvolution &SE) {2964for(; OI != OE; ++OI) {2965if (Instruction *Oper = dyn_cast<Instruction>(*OI)) {2966if (!SE.isSCEVable(Oper->getType()))2967continue;29682969if (const SCEVAddRecExpr *AR =2970dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Oper))) {2971if (AR->getLoop() == L)2972break;2973}2974}2975}2976return OI;2977}29782979/// IVChain logic must consistently peek base TruncInst operands, so wrap it in2980/// a convenient helper.2981static Value *getWideOperand(Value *Oper) {2982if (TruncInst *Trunc = dyn_cast<TruncInst>(Oper))2983return Trunc->getOperand(0);2984return Oper;2985}29862987/// Return an approximation of this SCEV expression's "base", or NULL for any2988/// constant. Returning the expression itself is conservative. Returning a2989/// deeper subexpression is more precise and valid as long as it isn't less2990/// complex than another subexpression. For expressions involving multiple2991/// unscaled values, we need to return the pointer-type SCEVUnknown. This avoids2992/// forming chains across objects, such as: PrevOper==a[i], IVOper==b[i],2993/// IVInc==b-a.2994///2995/// Since SCEVUnknown is the rightmost type, and pointers are the rightmost2996/// SCEVUnknown, we simply return the rightmost SCEV operand.2997static const SCEV *getExprBase(const SCEV *S) {2998switch (S->getSCEVType()) {2999default: // including scUnknown.3000return S;3001case scConstant:3002case scVScale:3003return nullptr;3004case scTruncate:3005return getExprBase(cast<SCEVTruncateExpr>(S)->getOperand());3006case scZeroExtend:3007return getExprBase(cast<SCEVZeroExtendExpr>(S)->getOperand());3008case scSignExtend:3009return getExprBase(cast<SCEVSignExtendExpr>(S)->getOperand());3010case scAddExpr: {3011// Skip over scaled operands (scMulExpr) to follow add operands as long as3012// there's nothing more complex.3013// FIXME: not sure if we want to recognize negation.3014const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);3015for (const SCEV *SubExpr : reverse(Add->operands())) {3016if (SubExpr->getSCEVType() == scAddExpr)3017return getExprBase(SubExpr);30183019if (SubExpr->getSCEVType() != scMulExpr)3020return SubExpr;3021}3022return S; // all operands are scaled, be conservative.3023}3024case scAddRecExpr:3025return getExprBase(cast<SCEVAddRecExpr>(S)->getStart());3026}3027llvm_unreachable("Unknown SCEV kind!");3028}30293030/// Return true if the chain increment is profitable to expand into a loop3031/// invariant value, which may require its own register. A profitable chain3032/// increment will be an offset relative to the same base. We allow such offsets3033/// to potentially be used as chain increment as long as it's not obviously3034/// expensive to expand using real instructions.3035bool IVChain::isProfitableIncrement(const SCEV *OperExpr,3036const SCEV *IncExpr,3037ScalarEvolution &SE) {3038// Aggressively form chains when -stress-ivchain.3039if (StressIVChain)3040return true;30413042// Do not replace a constant offset from IV head with a nonconstant IV3043// increment.3044if (!isa<SCEVConstant>(IncExpr)) {3045const SCEV *HeadExpr = SE.getSCEV(getWideOperand(Incs[0].IVOperand));3046if (isa<SCEVConstant>(SE.getMinusSCEV(OperExpr, HeadExpr)))3047return false;3048}30493050SmallPtrSet<const SCEV*, 8> Processed;3051return !isHighCostExpansion(IncExpr, Processed, SE);3052}30533054/// Return true if the number of registers needed for the chain is estimated to3055/// be less than the number required for the individual IV users. First prohibit3056/// any IV users that keep the IV live across increments (the Users set should3057/// be empty). Next count the number and type of increments in the chain.3058///3059/// Chaining IVs can lead to considerable code bloat if ISEL doesn't3060/// effectively use postinc addressing modes. Only consider it profitable it the3061/// increments can be computed in fewer registers when chained.3062///3063/// TODO: Consider IVInc free if it's already used in another chains.3064static bool isProfitableChain(IVChain &Chain,3065SmallPtrSetImpl<Instruction *> &Users,3066ScalarEvolution &SE,3067const TargetTransformInfo &TTI) {3068if (StressIVChain)3069return true;30703071if (!Chain.hasIncs())3072return false;30733074if (!Users.empty()) {3075LLVM_DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " users:\n";3076for (Instruction *Inst3077: Users) { dbgs() << " " << *Inst << "\n"; });3078return false;3079}3080assert(!Chain.Incs.empty() && "empty IV chains are not allowed");30813082// The chain itself may require a register, so intialize cost to 1.3083int cost = 1;30843085// A complete chain likely eliminates the need for keeping the original IV in3086// a register. LSR does not currently know how to form a complete chain unless3087// the header phi already exists.3088if (isa<PHINode>(Chain.tailUserInst())3089&& SE.getSCEV(Chain.tailUserInst()) == Chain.Incs[0].IncExpr) {3090--cost;3091}3092const SCEV *LastIncExpr = nullptr;3093unsigned NumConstIncrements = 0;3094unsigned NumVarIncrements = 0;3095unsigned NumReusedIncrements = 0;30963097if (TTI.isProfitableLSRChainElement(Chain.Incs[0].UserInst))3098return true;30993100for (const IVInc &Inc : Chain) {3101if (TTI.isProfitableLSRChainElement(Inc.UserInst))3102return true;3103if (Inc.IncExpr->isZero())3104continue;31053106// Incrementing by zero or some constant is neutral. We assume constants can3107// be folded into an addressing mode or an add's immediate operand.3108if (isa<SCEVConstant>(Inc.IncExpr)) {3109++NumConstIncrements;3110continue;3111}31123113if (Inc.IncExpr == LastIncExpr)3114++NumReusedIncrements;3115else3116++NumVarIncrements;31173118LastIncExpr = Inc.IncExpr;3119}3120// An IV chain with a single increment is handled by LSR's postinc3121// uses. However, a chain with multiple increments requires keeping the IV's3122// value live longer than it needs to be if chained.3123if (NumConstIncrements > 1)3124--cost;31253126// Materializing increment expressions in the preheader that didn't exist in3127// the original code may cost a register. For example, sign-extended array3128// indices can produce ridiculous increments like this:3129// IV + ((sext i32 (2 * %s) to i64) + (-1 * (sext i32 %s to i64)))3130cost += NumVarIncrements;31313132// Reusing variable increments likely saves a register to hold the multiple of3133// the stride.3134cost -= NumReusedIncrements;31353136LLVM_DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " Cost: " << cost3137<< "\n");31383139return cost < 0;3140}31413142/// Add this IV user to an existing chain or make it the head of a new chain.3143void LSRInstance::ChainInstruction(Instruction *UserInst, Instruction *IVOper,3144SmallVectorImpl<ChainUsers> &ChainUsersVec) {3145// When IVs are used as types of varying widths, they are generally converted3146// to a wider type with some uses remaining narrow under a (free) trunc.3147Value *const NextIV = getWideOperand(IVOper);3148const SCEV *const OperExpr = SE.getSCEV(NextIV);3149const SCEV *const OperExprBase = getExprBase(OperExpr);31503151// Visit all existing chains. Check if its IVOper can be computed as a3152// profitable loop invariant increment from the last link in the Chain.3153unsigned ChainIdx = 0, NChains = IVChainVec.size();3154const SCEV *LastIncExpr = nullptr;3155for (; ChainIdx < NChains; ++ChainIdx) {3156IVChain &Chain = IVChainVec[ChainIdx];31573158// Prune the solution space aggressively by checking that both IV operands3159// are expressions that operate on the same unscaled SCEVUnknown. This3160// "base" will be canceled by the subsequent getMinusSCEV call. Checking3161// first avoids creating extra SCEV expressions.3162if (!StressIVChain && Chain.ExprBase != OperExprBase)3163continue;31643165Value *PrevIV = getWideOperand(Chain.Incs.back().IVOperand);3166if (PrevIV->getType() != NextIV->getType())3167continue;31683169// A phi node terminates a chain.3170if (isa<PHINode>(UserInst) && isa<PHINode>(Chain.tailUserInst()))3171continue;31723173// The increment must be loop-invariant so it can be kept in a register.3174const SCEV *PrevExpr = SE.getSCEV(PrevIV);3175const SCEV *IncExpr = SE.getMinusSCEV(OperExpr, PrevExpr);3176if (isa<SCEVCouldNotCompute>(IncExpr) || !SE.isLoopInvariant(IncExpr, L))3177continue;31783179if (Chain.isProfitableIncrement(OperExpr, IncExpr, SE)) {3180LastIncExpr = IncExpr;3181break;3182}3183}3184// If we haven't found a chain, create a new one, unless we hit the max. Don't3185// bother for phi nodes, because they must be last in the chain.3186if (ChainIdx == NChains) {3187if (isa<PHINode>(UserInst))3188return;3189if (NChains >= MaxChains && !StressIVChain) {3190LLVM_DEBUG(dbgs() << "IV Chain Limit\n");3191return;3192}3193LastIncExpr = OperExpr;3194// IVUsers may have skipped over sign/zero extensions. We don't currently3195// attempt to form chains involving extensions unless they can be hoisted3196// into this loop's AddRec.3197if (!isa<SCEVAddRecExpr>(LastIncExpr))3198return;3199++NChains;3200IVChainVec.push_back(IVChain(IVInc(UserInst, IVOper, LastIncExpr),3201OperExprBase));3202ChainUsersVec.resize(NChains);3203LLVM_DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Head: (" << *UserInst3204<< ") IV=" << *LastIncExpr << "\n");3205} else {3206LLVM_DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Inc: (" << *UserInst3207<< ") IV+" << *LastIncExpr << "\n");3208// Add this IV user to the end of the chain.3209IVChainVec[ChainIdx].add(IVInc(UserInst, IVOper, LastIncExpr));3210}3211IVChain &Chain = IVChainVec[ChainIdx];32123213SmallPtrSet<Instruction*,4> &NearUsers = ChainUsersVec[ChainIdx].NearUsers;3214// This chain's NearUsers become FarUsers.3215if (!LastIncExpr->isZero()) {3216ChainUsersVec[ChainIdx].FarUsers.insert(NearUsers.begin(),3217NearUsers.end());3218NearUsers.clear();3219}32203221// All other uses of IVOperand become near uses of the chain.3222// We currently ignore intermediate values within SCEV expressions, assuming3223// they will eventually be used be the current chain, or can be computed3224// from one of the chain increments. To be more precise we could3225// transitively follow its user and only add leaf IV users to the set.3226for (User *U : IVOper->users()) {3227Instruction *OtherUse = dyn_cast<Instruction>(U);3228if (!OtherUse)3229continue;3230// Uses in the chain will no longer be uses if the chain is formed.3231// Include the head of the chain in this iteration (not Chain.begin()).3232IVChain::const_iterator IncIter = Chain.Incs.begin();3233IVChain::const_iterator IncEnd = Chain.Incs.end();3234for( ; IncIter != IncEnd; ++IncIter) {3235if (IncIter->UserInst == OtherUse)3236break;3237}3238if (IncIter != IncEnd)3239continue;32403241if (SE.isSCEVable(OtherUse->getType())3242&& !isa<SCEVUnknown>(SE.getSCEV(OtherUse))3243&& IU.isIVUserOrOperand(OtherUse)) {3244continue;3245}3246NearUsers.insert(OtherUse);3247}32483249// Since this user is part of the chain, it's no longer considered a use3250// of the chain.3251ChainUsersVec[ChainIdx].FarUsers.erase(UserInst);3252}32533254/// Populate the vector of Chains.3255///3256/// This decreases ILP at the architecture level. Targets with ample registers,3257/// multiple memory ports, and no register renaming probably don't want3258/// this. However, such targets should probably disable LSR altogether.3259///3260/// The job of LSR is to make a reasonable choice of induction variables across3261/// the loop. Subsequent passes can easily "unchain" computation exposing more3262/// ILP *within the loop* if the target wants it.3263///3264/// Finding the best IV chain is potentially a scheduling problem. Since LSR3265/// will not reorder memory operations, it will recognize this as a chain, but3266/// will generate redundant IV increments. Ideally this would be corrected later3267/// by a smart scheduler:3268/// = A[i]3269/// = A[i+x]3270/// A[i] =3271/// A[i+x] =3272///3273/// TODO: Walk the entire domtree within this loop, not just the path to the3274/// loop latch. This will discover chains on side paths, but requires3275/// maintaining multiple copies of the Chains state.3276void LSRInstance::CollectChains() {3277LLVM_DEBUG(dbgs() << "Collecting IV Chains.\n");3278SmallVector<ChainUsers, 8> ChainUsersVec;32793280SmallVector<BasicBlock *,8> LatchPath;3281BasicBlock *LoopHeader = L->getHeader();3282for (DomTreeNode *Rung = DT.getNode(L->getLoopLatch());3283Rung->getBlock() != LoopHeader; Rung = Rung->getIDom()) {3284LatchPath.push_back(Rung->getBlock());3285}3286LatchPath.push_back(LoopHeader);32873288// Walk the instruction stream from the loop header to the loop latch.3289for (BasicBlock *BB : reverse(LatchPath)) {3290for (Instruction &I : *BB) {3291// Skip instructions that weren't seen by IVUsers analysis.3292if (isa<PHINode>(I) || !IU.isIVUserOrOperand(&I))3293continue;32943295// Ignore users that are part of a SCEV expression. This way we only3296// consider leaf IV Users. This effectively rediscovers a portion of3297// IVUsers analysis but in program order this time.3298if (SE.isSCEVable(I.getType()) && !isa<SCEVUnknown>(SE.getSCEV(&I)))3299continue;33003301// Remove this instruction from any NearUsers set it may be in.3302for (unsigned ChainIdx = 0, NChains = IVChainVec.size();3303ChainIdx < NChains; ++ChainIdx) {3304ChainUsersVec[ChainIdx].NearUsers.erase(&I);3305}3306// Search for operands that can be chained.3307SmallPtrSet<Instruction*, 4> UniqueOperands;3308User::op_iterator IVOpEnd = I.op_end();3309User::op_iterator IVOpIter = findIVOperand(I.op_begin(), IVOpEnd, L, SE);3310while (IVOpIter != IVOpEnd) {3311Instruction *IVOpInst = cast<Instruction>(*IVOpIter);3312if (UniqueOperands.insert(IVOpInst).second)3313ChainInstruction(&I, IVOpInst, ChainUsersVec);3314IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);3315}3316} // Continue walking down the instructions.3317} // Continue walking down the domtree.3318// Visit phi backedges to determine if the chain can generate the IV postinc.3319for (PHINode &PN : L->getHeader()->phis()) {3320if (!SE.isSCEVable(PN.getType()))3321continue;33223323Instruction *IncV =3324dyn_cast<Instruction>(PN.getIncomingValueForBlock(L->getLoopLatch()));3325if (IncV)3326ChainInstruction(&PN, IncV, ChainUsersVec);3327}3328// Remove any unprofitable chains.3329unsigned ChainIdx = 0;3330for (unsigned UsersIdx = 0, NChains = IVChainVec.size();3331UsersIdx < NChains; ++UsersIdx) {3332if (!isProfitableChain(IVChainVec[UsersIdx],3333ChainUsersVec[UsersIdx].FarUsers, SE, TTI))3334continue;3335// Preserve the chain at UsesIdx.3336if (ChainIdx != UsersIdx)3337IVChainVec[ChainIdx] = IVChainVec[UsersIdx];3338FinalizeChain(IVChainVec[ChainIdx]);3339++ChainIdx;3340}3341IVChainVec.resize(ChainIdx);3342}33433344void LSRInstance::FinalizeChain(IVChain &Chain) {3345assert(!Chain.Incs.empty() && "empty IV chains are not allowed");3346LLVM_DEBUG(dbgs() << "Final Chain: " << *Chain.Incs[0].UserInst << "\n");33473348for (const IVInc &Inc : Chain) {3349LLVM_DEBUG(dbgs() << " Inc: " << *Inc.UserInst << "\n");3350auto UseI = find(Inc.UserInst->operands(), Inc.IVOperand);3351assert(UseI != Inc.UserInst->op_end() && "cannot find IV operand");3352IVIncSet.insert(UseI);3353}3354}33553356/// Return true if the IVInc can be folded into an addressing mode.3357static bool canFoldIVIncExpr(const SCEV *IncExpr, Instruction *UserInst,3358Value *Operand, const TargetTransformInfo &TTI) {3359const SCEVConstant *IncConst = dyn_cast<SCEVConstant>(IncExpr);3360Immediate IncOffset = Immediate::getZero();3361if (IncConst) {3362if (IncConst && IncConst->getAPInt().getSignificantBits() > 64)3363return false;3364IncOffset = Immediate::getFixed(IncConst->getValue()->getSExtValue());3365} else {3366// Look for mul(vscale, constant), to detect a scalable offset.3367auto *IncVScale = dyn_cast<SCEVMulExpr>(IncExpr);3368if (!IncVScale || IncVScale->getNumOperands() != 2 ||3369!isa<SCEVVScale>(IncVScale->getOperand(1)))3370return false;3371auto *Scale = dyn_cast<SCEVConstant>(IncVScale->getOperand(0));3372if (!Scale || Scale->getType()->getScalarSizeInBits() > 64)3373return false;3374IncOffset = Immediate::getScalable(Scale->getValue()->getSExtValue());3375}33763377if (!isAddressUse(TTI, UserInst, Operand))3378return false;33793380MemAccessTy AccessTy = getAccessType(TTI, UserInst, Operand);3381if (!isAlwaysFoldable(TTI, LSRUse::Address, AccessTy, /*BaseGV=*/nullptr,3382IncOffset, /*HasBaseReg=*/false))3383return false;33843385return true;3386}33873388/// Generate an add or subtract for each IVInc in a chain to materialize the IV3389/// user's operand from the previous IV user's operand.3390void LSRInstance::GenerateIVChain(const IVChain &Chain,3391SmallVectorImpl<WeakTrackingVH> &DeadInsts) {3392// Find the new IVOperand for the head of the chain. It may have been replaced3393// by LSR.3394const IVInc &Head = Chain.Incs[0];3395User::op_iterator IVOpEnd = Head.UserInst->op_end();3396// findIVOperand returns IVOpEnd if it can no longer find a valid IV user.3397User::op_iterator IVOpIter = findIVOperand(Head.UserInst->op_begin(),3398IVOpEnd, L, SE);3399Value *IVSrc = nullptr;3400while (IVOpIter != IVOpEnd) {3401IVSrc = getWideOperand(*IVOpIter);34023403// If this operand computes the expression that the chain needs, we may use3404// it. (Check this after setting IVSrc which is used below.)3405//3406// Note that if Head.IncExpr is wider than IVSrc, then this phi is too3407// narrow for the chain, so we can no longer use it. We do allow using a3408// wider phi, assuming the LSR checked for free truncation. In that case we3409// should already have a truncate on this operand such that3410// getSCEV(IVSrc) == IncExpr.3411if (SE.getSCEV(*IVOpIter) == Head.IncExpr3412|| SE.getSCEV(IVSrc) == Head.IncExpr) {3413break;3414}3415IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);3416}3417if (IVOpIter == IVOpEnd) {3418// Gracefully give up on this chain.3419LLVM_DEBUG(dbgs() << "Concealed chain head: " << *Head.UserInst << "\n");3420return;3421}3422assert(IVSrc && "Failed to find IV chain source");34233424LLVM_DEBUG(dbgs() << "Generate chain at: " << *IVSrc << "\n");3425Type *IVTy = IVSrc->getType();3426Type *IntTy = SE.getEffectiveSCEVType(IVTy);3427const SCEV *LeftOverExpr = nullptr;3428const SCEV *Accum = SE.getZero(IntTy);3429SmallVector<std::pair<const SCEV *, Value *>> Bases;3430Bases.emplace_back(Accum, IVSrc);34313432for (const IVInc &Inc : Chain) {3433Instruction *InsertPt = Inc.UserInst;3434if (isa<PHINode>(InsertPt))3435InsertPt = L->getLoopLatch()->getTerminator();34363437// IVOper will replace the current IV User's operand. IVSrc is the IV3438// value currently held in a register.3439Value *IVOper = IVSrc;3440if (!Inc.IncExpr->isZero()) {3441// IncExpr was the result of subtraction of two narrow values, so must3442// be signed.3443const SCEV *IncExpr = SE.getNoopOrSignExtend(Inc.IncExpr, IntTy);3444Accum = SE.getAddExpr(Accum, IncExpr);3445LeftOverExpr = LeftOverExpr ?3446SE.getAddExpr(LeftOverExpr, IncExpr) : IncExpr;3447}34483449// Look through each base to see if any can produce a nice addressing mode.3450bool FoundBase = false;3451for (auto [MapScev, MapIVOper] : reverse(Bases)) {3452const SCEV *Remainder = SE.getMinusSCEV(Accum, MapScev);3453if (canFoldIVIncExpr(Remainder, Inc.UserInst, Inc.IVOperand, TTI)) {3454if (!Remainder->isZero()) {3455Rewriter.clearPostInc();3456Value *IncV = Rewriter.expandCodeFor(Remainder, IntTy, InsertPt);3457const SCEV *IVOperExpr =3458SE.getAddExpr(SE.getUnknown(MapIVOper), SE.getUnknown(IncV));3459IVOper = Rewriter.expandCodeFor(IVOperExpr, IVTy, InsertPt);3460} else {3461IVOper = MapIVOper;3462}34633464FoundBase = true;3465break;3466}3467}3468if (!FoundBase && LeftOverExpr && !LeftOverExpr->isZero()) {3469// Expand the IV increment.3470Rewriter.clearPostInc();3471Value *IncV = Rewriter.expandCodeFor(LeftOverExpr, IntTy, InsertPt);3472const SCEV *IVOperExpr = SE.getAddExpr(SE.getUnknown(IVSrc),3473SE.getUnknown(IncV));3474IVOper = Rewriter.expandCodeFor(IVOperExpr, IVTy, InsertPt);34753476// If an IV increment can't be folded, use it as the next IV value.3477if (!canFoldIVIncExpr(LeftOverExpr, Inc.UserInst, Inc.IVOperand, TTI)) {3478assert(IVTy == IVOper->getType() && "inconsistent IV increment type");3479Bases.emplace_back(Accum, IVOper);3480IVSrc = IVOper;3481LeftOverExpr = nullptr;3482}3483}3484Type *OperTy = Inc.IVOperand->getType();3485if (IVTy != OperTy) {3486assert(SE.getTypeSizeInBits(IVTy) >= SE.getTypeSizeInBits(OperTy) &&3487"cannot extend a chained IV");3488IRBuilder<> Builder(InsertPt);3489IVOper = Builder.CreateTruncOrBitCast(IVOper, OperTy, "lsr.chain");3490}3491Inc.UserInst->replaceUsesOfWith(Inc.IVOperand, IVOper);3492if (auto *OperandIsInstr = dyn_cast<Instruction>(Inc.IVOperand))3493DeadInsts.emplace_back(OperandIsInstr);3494}3495// If LSR created a new, wider phi, we may also replace its postinc. We only3496// do this if we also found a wide value for the head of the chain.3497if (isa<PHINode>(Chain.tailUserInst())) {3498for (PHINode &Phi : L->getHeader()->phis()) {3499if (Phi.getType() != IVSrc->getType())3500continue;3501Instruction *PostIncV = dyn_cast<Instruction>(3502Phi.getIncomingValueForBlock(L->getLoopLatch()));3503if (!PostIncV || (SE.getSCEV(PostIncV) != SE.getSCEV(IVSrc)))3504continue;3505Value *IVOper = IVSrc;3506Type *PostIncTy = PostIncV->getType();3507if (IVTy != PostIncTy) {3508assert(PostIncTy->isPointerTy() && "mixing int/ptr IV types");3509IRBuilder<> Builder(L->getLoopLatch()->getTerminator());3510Builder.SetCurrentDebugLocation(PostIncV->getDebugLoc());3511IVOper = Builder.CreatePointerCast(IVSrc, PostIncTy, "lsr.chain");3512}3513Phi.replaceUsesOfWith(PostIncV, IVOper);3514DeadInsts.emplace_back(PostIncV);3515}3516}3517}35183519void LSRInstance::CollectFixupsAndInitialFormulae() {3520BranchInst *ExitBranch = nullptr;3521bool SaveCmp = TTI.canSaveCmp(L, &ExitBranch, &SE, &LI, &DT, &AC, &TLI);35223523// For calculating baseline cost3524SmallPtrSet<const SCEV *, 16> Regs;3525DenseSet<const SCEV *> VisitedRegs;3526DenseSet<size_t> VisitedLSRUse;35273528for (const IVStrideUse &U : IU) {3529Instruction *UserInst = U.getUser();3530// Skip IV users that are part of profitable IV Chains.3531User::op_iterator UseI =3532find(UserInst->operands(), U.getOperandValToReplace());3533assert(UseI != UserInst->op_end() && "cannot find IV operand");3534if (IVIncSet.count(UseI)) {3535LLVM_DEBUG(dbgs() << "Use is in profitable chain: " << **UseI << '\n');3536continue;3537}35383539LSRUse::KindType Kind = LSRUse::Basic;3540MemAccessTy AccessTy;3541if (isAddressUse(TTI, UserInst, U.getOperandValToReplace())) {3542Kind = LSRUse::Address;3543AccessTy = getAccessType(TTI, UserInst, U.getOperandValToReplace());3544}35453546const SCEV *S = IU.getExpr(U);3547if (!S)3548continue;3549PostIncLoopSet TmpPostIncLoops = U.getPostIncLoops();35503551// Equality (== and !=) ICmps are special. We can rewrite (i == N) as3552// (N - i == 0), and this allows (N - i) to be the expression that we work3553// with rather than just N or i, so we can consider the register3554// requirements for both N and i at the same time. Limiting this code to3555// equality icmps is not a problem because all interesting loops use3556// equality icmps, thanks to IndVarSimplify.3557if (ICmpInst *CI = dyn_cast<ICmpInst>(UserInst)) {3558// If CI can be saved in some target, like replaced inside hardware loop3559// in PowerPC, no need to generate initial formulae for it.3560if (SaveCmp && CI == dyn_cast<ICmpInst>(ExitBranch->getCondition()))3561continue;3562if (CI->isEquality()) {3563// Swap the operands if needed to put the OperandValToReplace on the3564// left, for consistency.3565Value *NV = CI->getOperand(1);3566if (NV == U.getOperandValToReplace()) {3567CI->setOperand(1, CI->getOperand(0));3568CI->setOperand(0, NV);3569NV = CI->getOperand(1);3570Changed = true;3571}35723573// x == y --> x - y == 03574const SCEV *N = SE.getSCEV(NV);3575if (SE.isLoopInvariant(N, L) && Rewriter.isSafeToExpand(N) &&3576(!NV->getType()->isPointerTy() ||3577SE.getPointerBase(N) == SE.getPointerBase(S))) {3578// S is normalized, so normalize N before folding it into S3579// to keep the result normalized.3580N = normalizeForPostIncUse(N, TmpPostIncLoops, SE);3581if (!N)3582continue;3583Kind = LSRUse::ICmpZero;3584S = SE.getMinusSCEV(N, S);3585} else if (L->isLoopInvariant(NV) &&3586(!isa<Instruction>(NV) ||3587DT.dominates(cast<Instruction>(NV), L->getHeader())) &&3588!NV->getType()->isPointerTy()) {3589// If we can't generally expand the expression (e.g. it contains3590// a divide), but it is already at a loop invariant point before the3591// loop, wrap it in an unknown (to prevent the expander from trying3592// to re-expand in a potentially unsafe way.) The restriction to3593// integer types is required because the unknown hides the base, and3594// SCEV can't compute the difference of two unknown pointers.3595N = SE.getUnknown(NV);3596N = normalizeForPostIncUse(N, TmpPostIncLoops, SE);3597if (!N)3598continue;3599Kind = LSRUse::ICmpZero;3600S = SE.getMinusSCEV(N, S);3601assert(!isa<SCEVCouldNotCompute>(S));3602}36033604// -1 and the negations of all interesting strides (except the negation3605// of -1) are now also interesting.3606for (size_t i = 0, e = Factors.size(); i != e; ++i)3607if (Factors[i] != -1)3608Factors.insert(-(uint64_t)Factors[i]);3609Factors.insert(-1);3610}3611}36123613// Get or create an LSRUse.3614std::pair<size_t, Immediate> P = getUse(S, Kind, AccessTy);3615size_t LUIdx = P.first;3616Immediate Offset = P.second;3617LSRUse &LU = Uses[LUIdx];36183619// Record the fixup.3620LSRFixup &LF = LU.getNewFixup();3621LF.UserInst = UserInst;3622LF.OperandValToReplace = U.getOperandValToReplace();3623LF.PostIncLoops = TmpPostIncLoops;3624LF.Offset = Offset;3625LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);36263627// Create SCEV as Formula for calculating baseline cost3628if (!VisitedLSRUse.count(LUIdx) && !LF.isUseFullyOutsideLoop(L)) {3629Formula F;3630F.initialMatch(S, L, SE);3631BaselineCost.RateFormula(F, Regs, VisitedRegs, LU);3632VisitedLSRUse.insert(LUIdx);3633}36343635if (!LU.WidestFixupType ||3636SE.getTypeSizeInBits(LU.WidestFixupType) <3637SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))3638LU.WidestFixupType = LF.OperandValToReplace->getType();36393640// If this is the first use of this LSRUse, give it a formula.3641if (LU.Formulae.empty()) {3642InsertInitialFormula(S, LU, LUIdx);3643CountRegisters(LU.Formulae.back(), LUIdx);3644}3645}36463647LLVM_DEBUG(print_fixups(dbgs()));3648}36493650/// Insert a formula for the given expression into the given use, separating out3651/// loop-variant portions from loop-invariant and loop-computable portions.3652void LSRInstance::InsertInitialFormula(const SCEV *S, LSRUse &LU,3653size_t LUIdx) {3654// Mark uses whose expressions cannot be expanded.3655if (!Rewriter.isSafeToExpand(S))3656LU.RigidFormula = true;36573658Formula F;3659F.initialMatch(S, L, SE);3660bool Inserted = InsertFormula(LU, LUIdx, F);3661assert(Inserted && "Initial formula already exists!"); (void)Inserted;3662}36633664/// Insert a simple single-register formula for the given expression into the3665/// given use.3666void3667LSRInstance::InsertSupplementalFormula(const SCEV *S,3668LSRUse &LU, size_t LUIdx) {3669Formula F;3670F.BaseRegs.push_back(S);3671F.HasBaseReg = true;3672bool Inserted = InsertFormula(LU, LUIdx, F);3673assert(Inserted && "Supplemental formula already exists!"); (void)Inserted;3674}36753676/// Note which registers are used by the given formula, updating RegUses.3677void LSRInstance::CountRegisters(const Formula &F, size_t LUIdx) {3678if (F.ScaledReg)3679RegUses.countRegister(F.ScaledReg, LUIdx);3680for (const SCEV *BaseReg : F.BaseRegs)3681RegUses.countRegister(BaseReg, LUIdx);3682}36833684/// If the given formula has not yet been inserted, add it to the list, and3685/// return true. Return false otherwise.3686bool LSRInstance::InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F) {3687// Do not insert formula that we will not be able to expand.3688assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F) &&3689"Formula is illegal");36903691if (!LU.InsertFormula(F, *L))3692return false;36933694CountRegisters(F, LUIdx);3695return true;3696}36973698/// Check for other uses of loop-invariant values which we're tracking. These3699/// other uses will pin these values in registers, making them less profitable3700/// for elimination.3701/// TODO: This currently misses non-constant addrec step registers.3702/// TODO: Should this give more weight to users inside the loop?3703void3704LSRInstance::CollectLoopInvariantFixupsAndFormulae() {3705SmallVector<const SCEV *, 8> Worklist(RegUses.begin(), RegUses.end());3706SmallPtrSet<const SCEV *, 32> Visited;37073708// Don't collect outside uses if we are favoring postinc - the instructions in3709// the loop are more important than the ones outside of it.3710if (AMK == TTI::AMK_PostIndexed)3711return;37123713while (!Worklist.empty()) {3714const SCEV *S = Worklist.pop_back_val();37153716// Don't process the same SCEV twice3717if (!Visited.insert(S).second)3718continue;37193720if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S))3721append_range(Worklist, N->operands());3722else if (const SCEVIntegralCastExpr *C = dyn_cast<SCEVIntegralCastExpr>(S))3723Worklist.push_back(C->getOperand());3724else if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {3725Worklist.push_back(D->getLHS());3726Worklist.push_back(D->getRHS());3727} else if (const SCEVUnknown *US = dyn_cast<SCEVUnknown>(S)) {3728const Value *V = US->getValue();3729if (const Instruction *Inst = dyn_cast<Instruction>(V)) {3730// Look for instructions defined outside the loop.3731if (L->contains(Inst)) continue;3732} else if (isa<Constant>(V))3733// Constants can be re-materialized.3734continue;3735for (const Use &U : V->uses()) {3736const Instruction *UserInst = dyn_cast<Instruction>(U.getUser());3737// Ignore non-instructions.3738if (!UserInst)3739continue;3740// Don't bother if the instruction is an EHPad.3741if (UserInst->isEHPad())3742continue;3743// Ignore instructions in other functions (as can happen with3744// Constants).3745if (UserInst->getParent()->getParent() != L->getHeader()->getParent())3746continue;3747// Ignore instructions not dominated by the loop.3748const BasicBlock *UseBB = !isa<PHINode>(UserInst) ?3749UserInst->getParent() :3750cast<PHINode>(UserInst)->getIncomingBlock(3751PHINode::getIncomingValueNumForOperand(U.getOperandNo()));3752if (!DT.dominates(L->getHeader(), UseBB))3753continue;3754// Don't bother if the instruction is in a BB which ends in an EHPad.3755if (UseBB->getTerminator()->isEHPad())3756continue;37573758// Ignore cases in which the currently-examined value could come from3759// a basic block terminated with an EHPad. This checks all incoming3760// blocks of the phi node since it is possible that the same incoming3761// value comes from multiple basic blocks, only some of which may end3762// in an EHPad. If any of them do, a subsequent rewrite attempt by this3763// pass would try to insert instructions into an EHPad, hitting an3764// assertion.3765if (isa<PHINode>(UserInst)) {3766const auto *PhiNode = cast<PHINode>(UserInst);3767bool HasIncompatibleEHPTerminatedBlock = false;3768llvm::Value *ExpectedValue = U;3769for (unsigned int I = 0; I < PhiNode->getNumIncomingValues(); I++) {3770if (PhiNode->getIncomingValue(I) == ExpectedValue) {3771if (PhiNode->getIncomingBlock(I)->getTerminator()->isEHPad()) {3772HasIncompatibleEHPTerminatedBlock = true;3773break;3774}3775}3776}3777if (HasIncompatibleEHPTerminatedBlock) {3778continue;3779}3780}37813782// Don't bother rewriting PHIs in catchswitch blocks.3783if (isa<CatchSwitchInst>(UserInst->getParent()->getTerminator()))3784continue;3785// Ignore uses which are part of other SCEV expressions, to avoid3786// analyzing them multiple times.3787if (SE.isSCEVable(UserInst->getType())) {3788const SCEV *UserS = SE.getSCEV(const_cast<Instruction *>(UserInst));3789// If the user is a no-op, look through to its uses.3790if (!isa<SCEVUnknown>(UserS))3791continue;3792if (UserS == US) {3793Worklist.push_back(3794SE.getUnknown(const_cast<Instruction *>(UserInst)));3795continue;3796}3797}3798// Ignore icmp instructions which are already being analyzed.3799if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) {3800unsigned OtherIdx = !U.getOperandNo();3801Value *OtherOp = const_cast<Value *>(ICI->getOperand(OtherIdx));3802if (SE.hasComputableLoopEvolution(SE.getSCEV(OtherOp), L))3803continue;3804}38053806std::pair<size_t, Immediate> P =3807getUse(S, LSRUse::Basic, MemAccessTy());3808size_t LUIdx = P.first;3809Immediate Offset = P.second;3810LSRUse &LU = Uses[LUIdx];3811LSRFixup &LF = LU.getNewFixup();3812LF.UserInst = const_cast<Instruction *>(UserInst);3813LF.OperandValToReplace = U;3814LF.Offset = Offset;3815LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);3816if (!LU.WidestFixupType ||3817SE.getTypeSizeInBits(LU.WidestFixupType) <3818SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))3819LU.WidestFixupType = LF.OperandValToReplace->getType();3820InsertSupplementalFormula(US, LU, LUIdx);3821CountRegisters(LU.Formulae.back(), Uses.size() - 1);3822break;3823}3824}3825}3826}38273828/// Split S into subexpressions which can be pulled out into separate3829/// registers. If C is non-null, multiply each subexpression by C.3830///3831/// Return remainder expression after factoring the subexpressions captured by3832/// Ops. If Ops is complete, return NULL.3833static const SCEV *CollectSubexprs(const SCEV *S, const SCEVConstant *C,3834SmallVectorImpl<const SCEV *> &Ops,3835const Loop *L,3836ScalarEvolution &SE,3837unsigned Depth = 0) {3838// Arbitrarily cap recursion to protect compile time.3839if (Depth >= 3)3840return S;38413842if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {3843// Break out add operands.3844for (const SCEV *S : Add->operands()) {3845const SCEV *Remainder = CollectSubexprs(S, C, Ops, L, SE, Depth+1);3846if (Remainder)3847Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder);3848}3849return nullptr;3850} else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {3851// Split a non-zero base out of an addrec.3852if (AR->getStart()->isZero() || !AR->isAffine())3853return S;38543855const SCEV *Remainder = CollectSubexprs(AR->getStart(),3856C, Ops, L, SE, Depth+1);3857// Split the non-zero AddRec unless it is part of a nested recurrence that3858// does not pertain to this loop.3859if (Remainder && (AR->getLoop() == L || !isa<SCEVAddRecExpr>(Remainder))) {3860Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder);3861Remainder = nullptr;3862}3863if (Remainder != AR->getStart()) {3864if (!Remainder)3865Remainder = SE.getConstant(AR->getType(), 0);3866return SE.getAddRecExpr(Remainder,3867AR->getStepRecurrence(SE),3868AR->getLoop(),3869//FIXME: AR->getNoWrapFlags(SCEV::FlagNW)3870SCEV::FlagAnyWrap);3871}3872} else if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {3873// Break (C * (a + b + c)) into C*a + C*b + C*c.3874if (Mul->getNumOperands() != 2)3875return S;3876if (const SCEVConstant *Op0 =3877dyn_cast<SCEVConstant>(Mul->getOperand(0))) {3878C = C ? cast<SCEVConstant>(SE.getMulExpr(C, Op0)) : Op0;3879const SCEV *Remainder =3880CollectSubexprs(Mul->getOperand(1), C, Ops, L, SE, Depth+1);3881if (Remainder)3882Ops.push_back(SE.getMulExpr(C, Remainder));3883return nullptr;3884}3885}3886return S;3887}38883889/// Return true if the SCEV represents a value that may end up as a3890/// post-increment operation.3891static bool mayUsePostIncMode(const TargetTransformInfo &TTI,3892LSRUse &LU, const SCEV *S, const Loop *L,3893ScalarEvolution &SE) {3894if (LU.Kind != LSRUse::Address ||3895!LU.AccessTy.getType()->isIntOrIntVectorTy())3896return false;3897const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);3898if (!AR)3899return false;3900const SCEV *LoopStep = AR->getStepRecurrence(SE);3901if (!isa<SCEVConstant>(LoopStep))3902return false;3903// Check if a post-indexed load/store can be used.3904if (TTI.isIndexedLoadLegal(TTI.MIM_PostInc, AR->getType()) ||3905TTI.isIndexedStoreLegal(TTI.MIM_PostInc, AR->getType())) {3906const SCEV *LoopStart = AR->getStart();3907if (!isa<SCEVConstant>(LoopStart) && SE.isLoopInvariant(LoopStart, L))3908return true;3909}3910return false;3911}39123913/// Helper function for LSRInstance::GenerateReassociations.3914void LSRInstance::GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx,3915const Formula &Base,3916unsigned Depth, size_t Idx,3917bool IsScaledReg) {3918const SCEV *BaseReg = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];3919// Don't generate reassociations for the base register of a value that3920// may generate a post-increment operator. The reason is that the3921// reassociations cause extra base+register formula to be created,3922// and possibly chosen, but the post-increment is more efficient.3923if (AMK == TTI::AMK_PostIndexed && mayUsePostIncMode(TTI, LU, BaseReg, L, SE))3924return;3925SmallVector<const SCEV *, 8> AddOps;3926const SCEV *Remainder = CollectSubexprs(BaseReg, nullptr, AddOps, L, SE);3927if (Remainder)3928AddOps.push_back(Remainder);39293930if (AddOps.size() == 1)3931return;39323933for (SmallVectorImpl<const SCEV *>::const_iterator J = AddOps.begin(),3934JE = AddOps.end();3935J != JE; ++J) {3936// Loop-variant "unknown" values are uninteresting; we won't be able to3937// do anything meaningful with them.3938if (isa<SCEVUnknown>(*J) && !SE.isLoopInvariant(*J, L))3939continue;39403941// Don't pull a constant into a register if the constant could be folded3942// into an immediate field.3943if (isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind,3944LU.AccessTy, *J, Base.getNumRegs() > 1))3945continue;39463947// Collect all operands except *J.3948SmallVector<const SCEV *, 8> InnerAddOps(3949((const SmallVector<const SCEV *, 8> &)AddOps).begin(), J);3950InnerAddOps.append(std::next(J),3951((const SmallVector<const SCEV *, 8> &)AddOps).end());39523953// Don't leave just a constant behind in a register if the constant could3954// be folded into an immediate field.3955if (InnerAddOps.size() == 1 &&3956isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind,3957LU.AccessTy, InnerAddOps[0], Base.getNumRegs() > 1))3958continue;39593960const SCEV *InnerSum = SE.getAddExpr(InnerAddOps);3961if (InnerSum->isZero())3962continue;3963Formula F = Base;39643965if (F.UnfoldedOffset.isNonZero() && F.UnfoldedOffset.isScalable())3966continue;39673968// Add the remaining pieces of the add back into the new formula.3969const SCEVConstant *InnerSumSC = dyn_cast<SCEVConstant>(InnerSum);3970if (InnerSumSC && SE.getTypeSizeInBits(InnerSumSC->getType()) <= 64 &&3971TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset.getFixedValue() +3972InnerSumSC->getValue()->getZExtValue())) {3973F.UnfoldedOffset =3974Immediate::getFixed((uint64_t)F.UnfoldedOffset.getFixedValue() +3975InnerSumSC->getValue()->getZExtValue());3976if (IsScaledReg)3977F.ScaledReg = nullptr;3978else3979F.BaseRegs.erase(F.BaseRegs.begin() + Idx);3980} else if (IsScaledReg)3981F.ScaledReg = InnerSum;3982else3983F.BaseRegs[Idx] = InnerSum;39843985// Add J as its own register, or an unfolded immediate.3986const SCEVConstant *SC = dyn_cast<SCEVConstant>(*J);3987if (SC && SE.getTypeSizeInBits(SC->getType()) <= 64 &&3988TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset.getFixedValue() +3989SC->getValue()->getZExtValue()))3990F.UnfoldedOffset =3991Immediate::getFixed((uint64_t)F.UnfoldedOffset.getFixedValue() +3992SC->getValue()->getZExtValue());3993else3994F.BaseRegs.push_back(*J);3995// We may have changed the number of register in base regs, adjust the3996// formula accordingly.3997F.canonicalize(*L);39983999if (InsertFormula(LU, LUIdx, F))4000// If that formula hadn't been seen before, recurse to find more like4001// it.4002// Add check on Log16(AddOps.size()) - same as Log2_32(AddOps.size()) >> 2)4003// Because just Depth is not enough to bound compile time.4004// This means that every time AddOps.size() is greater 16^x we will add4005// x to Depth.4006GenerateReassociations(LU, LUIdx, LU.Formulae.back(),4007Depth + 1 + (Log2_32(AddOps.size()) >> 2));4008}4009}40104011/// Split out subexpressions from adds and the bases of addrecs.4012void LSRInstance::GenerateReassociations(LSRUse &LU, unsigned LUIdx,4013Formula Base, unsigned Depth) {4014assert(Base.isCanonical(*L) && "Input must be in the canonical form");4015// Arbitrarily cap recursion to protect compile time.4016if (Depth >= 3)4017return;40184019for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)4020GenerateReassociationsImpl(LU, LUIdx, Base, Depth, i);40214022if (Base.Scale == 1)4023GenerateReassociationsImpl(LU, LUIdx, Base, Depth,4024/* Idx */ -1, /* IsScaledReg */ true);4025}40264027/// Generate a formula consisting of all of the loop-dominating registers added4028/// into a single register.4029void LSRInstance::GenerateCombinations(LSRUse &LU, unsigned LUIdx,4030Formula Base) {4031// This method is only interesting on a plurality of registers.4032if (Base.BaseRegs.size() + (Base.Scale == 1) +4033(Base.UnfoldedOffset.isNonZero()) <=40341)4035return;40364037// Flatten the representation, i.e., reg1 + 1*reg2 => reg1 + reg2, before4038// processing the formula.4039Base.unscale();4040SmallVector<const SCEV *, 4> Ops;4041Formula NewBase = Base;4042NewBase.BaseRegs.clear();4043Type *CombinedIntegerType = nullptr;4044for (const SCEV *BaseReg : Base.BaseRegs) {4045if (SE.properlyDominates(BaseReg, L->getHeader()) &&4046!SE.hasComputableLoopEvolution(BaseReg, L)) {4047if (!CombinedIntegerType)4048CombinedIntegerType = SE.getEffectiveSCEVType(BaseReg->getType());4049Ops.push_back(BaseReg);4050}4051else4052NewBase.BaseRegs.push_back(BaseReg);4053}40544055// If no register is relevant, we're done.4056if (Ops.size() == 0)4057return;40584059// Utility function for generating the required variants of the combined4060// registers.4061auto GenerateFormula = [&](const SCEV *Sum) {4062Formula F = NewBase;40634064// TODO: If Sum is zero, it probably means ScalarEvolution missed an4065// opportunity to fold something. For now, just ignore such cases4066// rather than proceed with zero in a register.4067if (Sum->isZero())4068return;40694070F.BaseRegs.push_back(Sum);4071F.canonicalize(*L);4072(void)InsertFormula(LU, LUIdx, F);4073};40744075// If we collected at least two registers, generate a formula combining them.4076if (Ops.size() > 1) {4077SmallVector<const SCEV *, 4> OpsCopy(Ops); // Don't let SE modify Ops.4078GenerateFormula(SE.getAddExpr(OpsCopy));4079}40804081// If we have an unfolded offset, generate a formula combining it with the4082// registers collected.4083if (NewBase.UnfoldedOffset.isNonZero() && NewBase.UnfoldedOffset.isFixed()) {4084assert(CombinedIntegerType && "Missing a type for the unfolded offset");4085Ops.push_back(SE.getConstant(CombinedIntegerType,4086NewBase.UnfoldedOffset.getFixedValue(), true));4087NewBase.UnfoldedOffset = Immediate::getFixed(0);4088GenerateFormula(SE.getAddExpr(Ops));4089}4090}40914092/// Helper function for LSRInstance::GenerateSymbolicOffsets.4093void LSRInstance::GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx,4094const Formula &Base, size_t Idx,4095bool IsScaledReg) {4096const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];4097GlobalValue *GV = ExtractSymbol(G, SE);4098if (G->isZero() || !GV)4099return;4100Formula F = Base;4101F.BaseGV = GV;4102if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F))4103return;4104if (IsScaledReg)4105F.ScaledReg = G;4106else4107F.BaseRegs[Idx] = G;4108(void)InsertFormula(LU, LUIdx, F);4109}41104111/// Generate reuse formulae using symbolic offsets.4112void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx,4113Formula Base) {4114// We can't add a symbolic offset if the address already contains one.4115if (Base.BaseGV) return;41164117for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)4118GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, i);4119if (Base.Scale == 1)4120GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, /* Idx */ -1,4121/* IsScaledReg */ true);4122}41234124/// Helper function for LSRInstance::GenerateConstantOffsets.4125void LSRInstance::GenerateConstantOffsetsImpl(4126LSRUse &LU, unsigned LUIdx, const Formula &Base,4127const SmallVectorImpl<Immediate> &Worklist, size_t Idx, bool IsScaledReg) {41284129auto GenerateOffset = [&](const SCEV *G, Immediate Offset) {4130Formula F = Base;4131if (!Base.BaseOffset.isCompatibleImmediate(Offset))4132return;4133F.BaseOffset = Base.BaseOffset.subUnsigned(Offset);41344135if (isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F)) {4136// Add the offset to the base register.4137const SCEV *NewOffset = Offset.getSCEV(SE, G->getType());4138const SCEV *NewG = SE.getAddExpr(NewOffset, G);4139// If it cancelled out, drop the base register, otherwise update it.4140if (NewG->isZero()) {4141if (IsScaledReg) {4142F.Scale = 0;4143F.ScaledReg = nullptr;4144} else4145F.deleteBaseReg(F.BaseRegs[Idx]);4146F.canonicalize(*L);4147} else if (IsScaledReg)4148F.ScaledReg = NewG;4149else4150F.BaseRegs[Idx] = NewG;41514152(void)InsertFormula(LU, LUIdx, F);4153}4154};41554156const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];41574158// With constant offsets and constant steps, we can generate pre-inc4159// accesses by having the offset equal the step. So, for access #0 with a4160// step of 8, we generate a G - 8 base which would require the first access4161// to be ((G - 8) + 8),+,8. The pre-indexed access then updates the pointer4162// for itself and hopefully becomes the base for other accesses. This means4163// means that a single pre-indexed access can be generated to become the new4164// base pointer for each iteration of the loop, resulting in no extra add/sub4165// instructions for pointer updating.4166if (AMK == TTI::AMK_PreIndexed && LU.Kind == LSRUse::Address) {4167if (auto *GAR = dyn_cast<SCEVAddRecExpr>(G)) {4168if (auto *StepRec =4169dyn_cast<SCEVConstant>(GAR->getStepRecurrence(SE))) {4170const APInt &StepInt = StepRec->getAPInt();4171int64_t Step = StepInt.isNegative() ?4172StepInt.getSExtValue() : StepInt.getZExtValue();41734174for (Immediate Offset : Worklist) {4175if (Offset.isFixed()) {4176Offset = Immediate::getFixed(Offset.getFixedValue() - Step);4177GenerateOffset(G, Offset);4178}4179}4180}4181}4182}4183for (Immediate Offset : Worklist)4184GenerateOffset(G, Offset);41854186Immediate Imm = ExtractImmediate(G, SE);4187if (G->isZero() || Imm.isZero() ||4188!Base.BaseOffset.isCompatibleImmediate(Imm))4189return;4190Formula F = Base;4191F.BaseOffset = F.BaseOffset.addUnsigned(Imm);4192if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F))4193return;4194if (IsScaledReg) {4195F.ScaledReg = G;4196} else {4197F.BaseRegs[Idx] = G;4198// We may generate non canonical Formula if G is a recurrent expr reg4199// related with current loop while F.ScaledReg is not.4200F.canonicalize(*L);4201}4202(void)InsertFormula(LU, LUIdx, F);4203}42044205/// GenerateConstantOffsets - Generate reuse formulae using symbolic offsets.4206void LSRInstance::GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx,4207Formula Base) {4208// TODO: For now, just add the min and max offset, because it usually isn't4209// worthwhile looking at everything inbetween.4210SmallVector<Immediate, 2> Worklist;4211Worklist.push_back(LU.MinOffset);4212if (LU.MaxOffset != LU.MinOffset)4213Worklist.push_back(LU.MaxOffset);42144215for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)4216GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, i);4217if (Base.Scale == 1)4218GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, /* Idx */ -1,4219/* IsScaledReg */ true);4220}42214222/// For ICmpZero, check to see if we can scale up the comparison. For example, x4223/// == y -> x*c == y*c.4224void LSRInstance::GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx,4225Formula Base) {4226if (LU.Kind != LSRUse::ICmpZero) return;42274228// Determine the integer type for the base formula.4229Type *IntTy = Base.getType();4230if (!IntTy) return;4231if (SE.getTypeSizeInBits(IntTy) > 64) return;42324233// Don't do this if there is more than one offset.4234if (LU.MinOffset != LU.MaxOffset) return;42354236// Check if transformation is valid. It is illegal to multiply pointer.4237if (Base.ScaledReg && Base.ScaledReg->getType()->isPointerTy())4238return;4239for (const SCEV *BaseReg : Base.BaseRegs)4240if (BaseReg->getType()->isPointerTy())4241return;4242assert(!Base.BaseGV && "ICmpZero use is not legal!");42434244// Check each interesting stride.4245for (int64_t Factor : Factors) {4246// Check that Factor can be represented by IntTy4247if (!ConstantInt::isValueValidForType(IntTy, Factor))4248continue;4249// Check that the multiplication doesn't overflow.4250if (Base.BaseOffset.isMin() && Factor == -1)4251continue;4252// Not supporting scalable immediates.4253if (Base.BaseOffset.isNonZero() && Base.BaseOffset.isScalable())4254continue;4255Immediate NewBaseOffset = Base.BaseOffset.mulUnsigned(Factor);4256assert(Factor != 0 && "Zero factor not expected!");4257if (NewBaseOffset.getFixedValue() / Factor !=4258Base.BaseOffset.getFixedValue())4259continue;4260// If the offset will be truncated at this use, check that it is in bounds.4261if (!IntTy->isPointerTy() &&4262!ConstantInt::isValueValidForType(IntTy, NewBaseOffset.getFixedValue()))4263continue;42644265// Check that multiplying with the use offset doesn't overflow.4266Immediate Offset = LU.MinOffset;4267if (Offset.isMin() && Factor == -1)4268continue;4269Offset = Offset.mulUnsigned(Factor);4270if (Offset.getFixedValue() / Factor != LU.MinOffset.getFixedValue())4271continue;4272// If the offset will be truncated at this use, check that it is in bounds.4273if (!IntTy->isPointerTy() &&4274!ConstantInt::isValueValidForType(IntTy, Offset.getFixedValue()))4275continue;42764277Formula F = Base;4278F.BaseOffset = NewBaseOffset;42794280// Check that this scale is legal.4281if (!isLegalUse(TTI, Offset, Offset, LU.Kind, LU.AccessTy, F))4282continue;42834284// Compensate for the use having MinOffset built into it.4285F.BaseOffset = F.BaseOffset.addUnsigned(Offset).subUnsigned(LU.MinOffset);42864287const SCEV *FactorS = SE.getConstant(IntTy, Factor);42884289// Check that multiplying with each base register doesn't overflow.4290for (size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) {4291F.BaseRegs[i] = SE.getMulExpr(F.BaseRegs[i], FactorS);4292if (getExactSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i])4293goto next;4294}42954296// Check that multiplying with the scaled register doesn't overflow.4297if (F.ScaledReg) {4298F.ScaledReg = SE.getMulExpr(F.ScaledReg, FactorS);4299if (getExactSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg)4300continue;4301}43024303// Check that multiplying with the unfolded offset doesn't overflow.4304if (F.UnfoldedOffset.isNonZero()) {4305if (F.UnfoldedOffset.isMin() && Factor == -1)4306continue;4307F.UnfoldedOffset = F.UnfoldedOffset.mulUnsigned(Factor);4308if (F.UnfoldedOffset.getFixedValue() / Factor !=4309Base.UnfoldedOffset.getFixedValue())4310continue;4311// If the offset will be truncated, check that it is in bounds.4312if (!IntTy->isPointerTy() && !ConstantInt::isValueValidForType(4313IntTy, F.UnfoldedOffset.getFixedValue()))4314continue;4315}43164317// If we make it here and it's legal, add it.4318(void)InsertFormula(LU, LUIdx, F);4319next:;4320}4321}43224323/// Generate stride factor reuse formulae by making use of scaled-offset address4324/// modes, for example.4325void LSRInstance::GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base) {4326// Determine the integer type for the base formula.4327Type *IntTy = Base.getType();4328if (!IntTy) return;43294330// If this Formula already has a scaled register, we can't add another one.4331// Try to unscale the formula to generate a better scale.4332if (Base.Scale != 0 && !Base.unscale())4333return;43344335assert(Base.Scale == 0 && "unscale did not did its job!");43364337// Check each interesting stride.4338for (int64_t Factor : Factors) {4339Base.Scale = Factor;4340Base.HasBaseReg = Base.BaseRegs.size() > 1;4341// Check whether this scale is going to be legal.4342if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,4343Base)) {4344// As a special-case, handle special out-of-loop Basic users specially.4345// TODO: Reconsider this special case.4346if (LU.Kind == LSRUse::Basic &&4347isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LSRUse::Special,4348LU.AccessTy, Base) &&4349LU.AllFixupsOutsideLoop)4350LU.Kind = LSRUse::Special;4351else4352continue;4353}4354// For an ICmpZero, negating a solitary base register won't lead to4355// new solutions.4356if (LU.Kind == LSRUse::ICmpZero && !Base.HasBaseReg &&4357Base.BaseOffset.isZero() && !Base.BaseGV)4358continue;4359// For each addrec base reg, if its loop is current loop, apply the scale.4360for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {4361const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Base.BaseRegs[i]);4362if (AR && (AR->getLoop() == L || LU.AllFixupsOutsideLoop)) {4363const SCEV *FactorS = SE.getConstant(IntTy, Factor);4364if (FactorS->isZero())4365continue;4366// Divide out the factor, ignoring high bits, since we'll be4367// scaling the value back up in the end.4368if (const SCEV *Quotient = getExactSDiv(AR, FactorS, SE, true))4369if (!Quotient->isZero()) {4370// TODO: This could be optimized to avoid all the copying.4371Formula F = Base;4372F.ScaledReg = Quotient;4373F.deleteBaseReg(F.BaseRegs[i]);4374// The canonical representation of 1*reg is reg, which is already in4375// Base. In that case, do not try to insert the formula, it will be4376// rejected anyway.4377if (F.Scale == 1 && (F.BaseRegs.empty() ||4378(AR->getLoop() != L && LU.AllFixupsOutsideLoop)))4379continue;4380// If AllFixupsOutsideLoop is true and F.Scale is 1, we may generate4381// non canonical Formula with ScaledReg's loop not being L.4382if (F.Scale == 1 && LU.AllFixupsOutsideLoop)4383F.canonicalize(*L);4384(void)InsertFormula(LU, LUIdx, F);4385}4386}4387}4388}4389}43904391/// Extend/Truncate \p Expr to \p ToTy considering post-inc uses in \p Loops.4392/// For all PostIncLoopSets in \p Loops, first de-normalize \p Expr, then4393/// perform the extension/truncate and normalize again, as the normalized form4394/// can result in folds that are not valid in the post-inc use contexts. The4395/// expressions for all PostIncLoopSets must match, otherwise return nullptr.4396static const SCEV *4397getAnyExtendConsideringPostIncUses(ArrayRef<PostIncLoopSet> Loops,4398const SCEV *Expr, Type *ToTy,4399ScalarEvolution &SE) {4400const SCEV *Result = nullptr;4401for (auto &L : Loops) {4402auto *DenormExpr = denormalizeForPostIncUse(Expr, L, SE);4403const SCEV *NewDenormExpr = SE.getAnyExtendExpr(DenormExpr, ToTy);4404const SCEV *New = normalizeForPostIncUse(NewDenormExpr, L, SE);4405if (!New || (Result && New != Result))4406return nullptr;4407Result = New;4408}44094410assert(Result && "failed to create expression");4411return Result;4412}44134414/// Generate reuse formulae from different IV types.4415void LSRInstance::GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base) {4416// Don't bother truncating symbolic values.4417if (Base.BaseGV) return;44184419// Determine the integer type for the base formula.4420Type *DstTy = Base.getType();4421if (!DstTy) return;4422if (DstTy->isPointerTy())4423return;44244425// It is invalid to extend a pointer type so exit early if ScaledReg or4426// any of the BaseRegs are pointers.4427if (Base.ScaledReg && Base.ScaledReg->getType()->isPointerTy())4428return;4429if (any_of(Base.BaseRegs,4430[](const SCEV *S) { return S->getType()->isPointerTy(); }))4431return;44324433SmallVector<PostIncLoopSet> Loops;4434for (auto &LF : LU.Fixups)4435Loops.push_back(LF.PostIncLoops);44364437for (Type *SrcTy : Types) {4438if (SrcTy != DstTy && TTI.isTruncateFree(SrcTy, DstTy)) {4439Formula F = Base;44404441// Sometimes SCEV is able to prove zero during ext transform. It may4442// happen if SCEV did not do all possible transforms while creating the4443// initial node (maybe due to depth limitations), but it can do them while4444// taking ext.4445if (F.ScaledReg) {4446const SCEV *NewScaledReg =4447getAnyExtendConsideringPostIncUses(Loops, F.ScaledReg, SrcTy, SE);4448if (!NewScaledReg || NewScaledReg->isZero())4449continue;4450F.ScaledReg = NewScaledReg;4451}4452bool HasZeroBaseReg = false;4453for (const SCEV *&BaseReg : F.BaseRegs) {4454const SCEV *NewBaseReg =4455getAnyExtendConsideringPostIncUses(Loops, BaseReg, SrcTy, SE);4456if (!NewBaseReg || NewBaseReg->isZero()) {4457HasZeroBaseReg = true;4458break;4459}4460BaseReg = NewBaseReg;4461}4462if (HasZeroBaseReg)4463continue;44644465// TODO: This assumes we've done basic processing on all uses and4466// have an idea what the register usage is.4467if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses))4468continue;44694470F.canonicalize(*L);4471(void)InsertFormula(LU, LUIdx, F);4472}4473}4474}44754476namespace {44774478/// Helper class for GenerateCrossUseConstantOffsets. It's used to defer4479/// modifications so that the search phase doesn't have to worry about the data4480/// structures moving underneath it.4481struct WorkItem {4482size_t LUIdx;4483Immediate Imm;4484const SCEV *OrigReg;44854486WorkItem(size_t LI, Immediate I, const SCEV *R)4487: LUIdx(LI), Imm(I), OrigReg(R) {}44884489void print(raw_ostream &OS) const;4490void dump() const;4491};44924493} // end anonymous namespace44944495#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)4496void WorkItem::print(raw_ostream &OS) const {4497OS << "in formulae referencing " << *OrigReg << " in use " << LUIdx4498<< " , add offset " << Imm;4499}45004501LLVM_DUMP_METHOD void WorkItem::dump() const {4502print(errs()); errs() << '\n';4503}4504#endif45054506/// Look for registers which are a constant distance apart and try to form reuse4507/// opportunities between them.4508void LSRInstance::GenerateCrossUseConstantOffsets() {4509// Group the registers by their value without any added constant offset.4510using ImmMapTy = std::map<Immediate, const SCEV *, KeyOrderTargetImmediate>;45114512DenseMap<const SCEV *, ImmMapTy> Map;4513DenseMap<const SCEV *, SmallBitVector> UsedByIndicesMap;4514SmallVector<const SCEV *, 8> Sequence;4515for (const SCEV *Use : RegUses) {4516const SCEV *Reg = Use; // Make a copy for ExtractImmediate to modify.4517Immediate Imm = ExtractImmediate(Reg, SE);4518auto Pair = Map.insert(std::make_pair(Reg, ImmMapTy()));4519if (Pair.second)4520Sequence.push_back(Reg);4521Pair.first->second.insert(std::make_pair(Imm, Use));4522UsedByIndicesMap[Reg] |= RegUses.getUsedByIndices(Use);4523}45244525// Now examine each set of registers with the same base value. Build up4526// a list of work to do and do the work in a separate step so that we're4527// not adding formulae and register counts while we're searching.4528SmallVector<WorkItem, 32> WorkItems;4529SmallSet<std::pair<size_t, Immediate>, 32, KeyOrderSizeTAndImmediate>4530UniqueItems;4531for (const SCEV *Reg : Sequence) {4532const ImmMapTy &Imms = Map.find(Reg)->second;45334534// It's not worthwhile looking for reuse if there's only one offset.4535if (Imms.size() == 1)4536continue;45374538LLVM_DEBUG(dbgs() << "Generating cross-use offsets for " << *Reg << ':';4539for (const auto &Entry4540: Imms) dbgs()4541<< ' ' << Entry.first;4542dbgs() << '\n');45434544// Examine each offset.4545for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();4546J != JE; ++J) {4547const SCEV *OrigReg = J->second;45484549Immediate JImm = J->first;4550const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg);45514552if (!isa<SCEVConstant>(OrigReg) &&4553UsedByIndicesMap[Reg].count() == 1) {4554LLVM_DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg4555<< '\n');4556continue;4557}45584559// Conservatively examine offsets between this orig reg a few selected4560// other orig regs.4561Immediate First = Imms.begin()->first;4562Immediate Last = std::prev(Imms.end())->first;4563if (!First.isCompatibleImmediate(Last)) {4564LLVM_DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg4565<< "\n");4566continue;4567}4568// Only scalable if both terms are scalable, or if one is scalable and4569// the other is 0.4570bool Scalable = First.isScalable() || Last.isScalable();4571int64_t FI = First.getKnownMinValue();4572int64_t LI = Last.getKnownMinValue();4573// Compute (First + Last) / 2 without overflow using the fact that4574// First + Last = 2 * (First + Last) + (First ^ Last).4575int64_t Avg = (FI & LI) + ((FI ^ LI) >> 1);4576// If the result is negative and FI is odd and LI even (or vice versa),4577// we rounded towards -inf. Add 1 in that case, to round towards 0.4578Avg = Avg + ((FI ^ LI) & ((uint64_t)Avg >> 63));4579ImmMapTy::const_iterator OtherImms[] = {4580Imms.begin(), std::prev(Imms.end()),4581Imms.lower_bound(Immediate::get(Avg, Scalable))};4582for (const auto &M : OtherImms) {4583if (M == J || M == JE) continue;4584if (!JImm.isCompatibleImmediate(M->first))4585continue;45864587// Compute the difference between the two.4588Immediate Imm = JImm.subUnsigned(M->first);4589for (unsigned LUIdx : UsedByIndices.set_bits())4590// Make a memo of this use, offset, and register tuple.4591if (UniqueItems.insert(std::make_pair(LUIdx, Imm)).second)4592WorkItems.push_back(WorkItem(LUIdx, Imm, OrigReg));4593}4594}4595}45964597Map.clear();4598Sequence.clear();4599UsedByIndicesMap.clear();4600UniqueItems.clear();46014602// Now iterate through the worklist and add new formulae.4603for (const WorkItem &WI : WorkItems) {4604size_t LUIdx = WI.LUIdx;4605LSRUse &LU = Uses[LUIdx];4606Immediate Imm = WI.Imm;4607const SCEV *OrigReg = WI.OrigReg;46084609Type *IntTy = SE.getEffectiveSCEVType(OrigReg->getType());4610const SCEV *NegImmS = Imm.getNegativeSCEV(SE, IntTy);4611unsigned BitWidth = SE.getTypeSizeInBits(IntTy);46124613// TODO: Use a more targeted data structure.4614for (size_t L = 0, LE = LU.Formulae.size(); L != LE; ++L) {4615Formula F = LU.Formulae[L];4616// FIXME: The code for the scaled and unscaled registers looks4617// very similar but slightly different. Investigate if they4618// could be merged. That way, we would not have to unscale the4619// Formula.4620F.unscale();4621// Use the immediate in the scaled register.4622if (F.ScaledReg == OrigReg) {4623if (!F.BaseOffset.isCompatibleImmediate(Imm))4624continue;4625Immediate Offset = F.BaseOffset.addUnsigned(Imm.mulUnsigned(F.Scale));4626// Don't create 50 + reg(-50).4627const SCEV *S = Offset.getNegativeSCEV(SE, IntTy);4628if (F.referencesReg(S))4629continue;4630Formula NewF = F;4631NewF.BaseOffset = Offset;4632if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,4633NewF))4634continue;4635NewF.ScaledReg = SE.getAddExpr(NegImmS, NewF.ScaledReg);46364637// If the new scale is a constant in a register, and adding the constant4638// value to the immediate would produce a value closer to zero than the4639// immediate itself, then the formula isn't worthwhile.4640if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewF.ScaledReg)) {4641// FIXME: Do we need to do something for scalable immediates here?4642// A scalable SCEV won't be constant, but we might still have4643// something in the offset? Bail out for now to be safe.4644if (NewF.BaseOffset.isNonZero() && NewF.BaseOffset.isScalable())4645continue;4646if (C->getValue()->isNegative() !=4647(NewF.BaseOffset.isLessThanZero()) &&4648(C->getAPInt().abs() * APInt(BitWidth, F.Scale))4649.ule(std::abs(NewF.BaseOffset.getFixedValue())))4650continue;4651}46524653// OK, looks good.4654NewF.canonicalize(*this->L);4655(void)InsertFormula(LU, LUIdx, NewF);4656} else {4657// Use the immediate in a base register.4658for (size_t N = 0, NE = F.BaseRegs.size(); N != NE; ++N) {4659const SCEV *BaseReg = F.BaseRegs[N];4660if (BaseReg != OrigReg)4661continue;4662Formula NewF = F;4663if (!NewF.BaseOffset.isCompatibleImmediate(Imm) ||4664!NewF.UnfoldedOffset.isCompatibleImmediate(Imm) ||4665!NewF.BaseOffset.isCompatibleImmediate(NewF.UnfoldedOffset))4666continue;4667NewF.BaseOffset = NewF.BaseOffset.addUnsigned(Imm);4668if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset,4669LU.Kind, LU.AccessTy, NewF)) {4670if (AMK == TTI::AMK_PostIndexed &&4671mayUsePostIncMode(TTI, LU, OrigReg, this->L, SE))4672continue;4673Immediate NewUnfoldedOffset = NewF.UnfoldedOffset.addUnsigned(Imm);4674if (!isLegalAddImmediate(TTI, NewUnfoldedOffset))4675continue;4676NewF = F;4677NewF.UnfoldedOffset = NewUnfoldedOffset;4678}4679NewF.BaseRegs[N] = SE.getAddExpr(NegImmS, BaseReg);46804681// If the new formula has a constant in a register, and adding the4682// constant value to the immediate would produce a value closer to4683// zero than the immediate itself, then the formula isn't worthwhile.4684for (const SCEV *NewReg : NewF.BaseRegs)4685if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewReg)) {4686if (NewF.BaseOffset.isNonZero() && NewF.BaseOffset.isScalable())4687goto skip_formula;4688if ((C->getAPInt() + NewF.BaseOffset.getFixedValue())4689.abs()4690.slt(std::abs(NewF.BaseOffset.getFixedValue())) &&4691(C->getAPInt() + NewF.BaseOffset.getFixedValue())4692.countr_zero() >=4693(unsigned)llvm::countr_zero<uint64_t>(4694NewF.BaseOffset.getFixedValue()))4695goto skip_formula;4696}46974698// Ok, looks good.4699NewF.canonicalize(*this->L);4700(void)InsertFormula(LU, LUIdx, NewF);4701break;4702skip_formula:;4703}4704}4705}4706}4707}47084709/// Generate formulae for each use.4710void4711LSRInstance::GenerateAllReuseFormulae() {4712// This is split into multiple loops so that hasRegsUsedByUsesOtherThan4713// queries are more precise.4714for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {4715LSRUse &LU = Uses[LUIdx];4716for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)4717GenerateReassociations(LU, LUIdx, LU.Formulae[i]);4718for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)4719GenerateCombinations(LU, LUIdx, LU.Formulae[i]);4720}4721for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {4722LSRUse &LU = Uses[LUIdx];4723for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)4724GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]);4725for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)4726GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]);4727for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)4728GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]);4729for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)4730GenerateScales(LU, LUIdx, LU.Formulae[i]);4731}4732for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {4733LSRUse &LU = Uses[LUIdx];4734for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)4735GenerateTruncates(LU, LUIdx, LU.Formulae[i]);4736}47374738GenerateCrossUseConstantOffsets();47394740LLVM_DEBUG(dbgs() << "\n"4741"After generating reuse formulae:\n";4742print_uses(dbgs()));4743}47444745/// If there are multiple formulae with the same set of registers used4746/// by other uses, pick the best one and delete the others.4747void LSRInstance::FilterOutUndesirableDedicatedRegisters() {4748DenseSet<const SCEV *> VisitedRegs;4749SmallPtrSet<const SCEV *, 16> Regs;4750SmallPtrSet<const SCEV *, 16> LoserRegs;4751#ifndef NDEBUG4752bool ChangedFormulae = false;4753#endif47544755// Collect the best formula for each unique set of shared registers. This4756// is reset for each use.4757using BestFormulaeTy =4758DenseMap<SmallVector<const SCEV *, 4>, size_t, UniquifierDenseMapInfo>;47594760BestFormulaeTy BestFormulae;47614762for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {4763LSRUse &LU = Uses[LUIdx];4764LLVM_DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs());4765dbgs() << '\n');47664767bool Any = false;4768for (size_t FIdx = 0, NumForms = LU.Formulae.size();4769FIdx != NumForms; ++FIdx) {4770Formula &F = LU.Formulae[FIdx];47714772// Some formulas are instant losers. For example, they may depend on4773// nonexistent AddRecs from other loops. These need to be filtered4774// immediately, otherwise heuristics could choose them over others leading4775// to an unsatisfactory solution. Passing LoserRegs into RateFormula here4776// avoids the need to recompute this information across formulae using the4777// same bad AddRec. Passing LoserRegs is also essential unless we remove4778// the corresponding bad register from the Regs set.4779Cost CostF(L, SE, TTI, AMK);4780Regs.clear();4781CostF.RateFormula(F, Regs, VisitedRegs, LU, &LoserRegs);4782if (CostF.isLoser()) {4783// During initial formula generation, undesirable formulae are generated4784// by uses within other loops that have some non-trivial address mode or4785// use the postinc form of the IV. LSR needs to provide these formulae4786// as the basis of rediscovering the desired formula that uses an AddRec4787// corresponding to the existing phi. Once all formulae have been4788// generated, these initial losers may be pruned.4789LLVM_DEBUG(dbgs() << " Filtering loser "; F.print(dbgs());4790dbgs() << "\n");4791}4792else {4793SmallVector<const SCEV *, 4> Key;4794for (const SCEV *Reg : F.BaseRegs) {4795if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx))4796Key.push_back(Reg);4797}4798if (F.ScaledReg &&4799RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx))4800Key.push_back(F.ScaledReg);4801// Unstable sort by host order ok, because this is only used for4802// uniquifying.4803llvm::sort(Key);48044805std::pair<BestFormulaeTy::const_iterator, bool> P =4806BestFormulae.insert(std::make_pair(Key, FIdx));4807if (P.second)4808continue;48094810Formula &Best = LU.Formulae[P.first->second];48114812Cost CostBest(L, SE, TTI, AMK);4813Regs.clear();4814CostBest.RateFormula(Best, Regs, VisitedRegs, LU);4815if (CostF.isLess(CostBest))4816std::swap(F, Best);4817LLVM_DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs());4818dbgs() << "\n"4819" in favor of formula ";4820Best.print(dbgs()); dbgs() << '\n');4821}4822#ifndef NDEBUG4823ChangedFormulae = true;4824#endif4825LU.DeleteFormula(F);4826--FIdx;4827--NumForms;4828Any = true;4829}48304831// Now that we've filtered out some formulae, recompute the Regs set.4832if (Any)4833LU.RecomputeRegs(LUIdx, RegUses);48344835// Reset this to prepare for the next use.4836BestFormulae.clear();4837}48384839LLVM_DEBUG(if (ChangedFormulae) {4840dbgs() << "\n"4841"After filtering out undesirable candidates:\n";4842print_uses(dbgs());4843});4844}48454846/// Estimate the worst-case number of solutions the solver might have to4847/// consider. It almost never considers this many solutions because it prune the4848/// search space, but the pruning isn't always sufficient.4849size_t LSRInstance::EstimateSearchSpaceComplexity() const {4850size_t Power = 1;4851for (const LSRUse &LU : Uses) {4852size_t FSize = LU.Formulae.size();4853if (FSize >= ComplexityLimit) {4854Power = ComplexityLimit;4855break;4856}4857Power *= FSize;4858if (Power >= ComplexityLimit)4859break;4860}4861return Power;4862}48634864/// When one formula uses a superset of the registers of another formula, it4865/// won't help reduce register pressure (though it may not necessarily hurt4866/// register pressure); remove it to simplify the system.4867void LSRInstance::NarrowSearchSpaceByDetectingSupersets() {4868if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {4869LLVM_DEBUG(dbgs() << "The search space is too complex.\n");48704871LLVM_DEBUG(dbgs() << "Narrowing the search space by eliminating formulae "4872"which use a superset of registers used by other "4873"formulae.\n");48744875for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {4876LSRUse &LU = Uses[LUIdx];4877bool Any = false;4878for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {4879Formula &F = LU.Formulae[i];4880if (F.BaseOffset.isNonZero() && F.BaseOffset.isScalable())4881continue;4882// Look for a formula with a constant or GV in a register. If the use4883// also has a formula with that same value in an immediate field,4884// delete the one that uses a register.4885for (SmallVectorImpl<const SCEV *>::const_iterator4886I = F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I) {4887if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*I)) {4888Formula NewF = F;4889//FIXME: Formulas should store bitwidth to do wrapping properly.4890// See PR41034.4891NewF.BaseOffset =4892Immediate::getFixed(NewF.BaseOffset.getFixedValue() +4893(uint64_t)C->getValue()->getSExtValue());4894NewF.BaseRegs.erase(NewF.BaseRegs.begin() +4895(I - F.BaseRegs.begin()));4896if (LU.HasFormulaWithSameRegs(NewF)) {4897LLVM_DEBUG(dbgs() << " Deleting "; F.print(dbgs());4898dbgs() << '\n');4899LU.DeleteFormula(F);4900--i;4901--e;4902Any = true;4903break;4904}4905} else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(*I)) {4906if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue()))4907if (!F.BaseGV) {4908Formula NewF = F;4909NewF.BaseGV = GV;4910NewF.BaseRegs.erase(NewF.BaseRegs.begin() +4911(I - F.BaseRegs.begin()));4912if (LU.HasFormulaWithSameRegs(NewF)) {4913LLVM_DEBUG(dbgs() << " Deleting "; F.print(dbgs());4914dbgs() << '\n');4915LU.DeleteFormula(F);4916--i;4917--e;4918Any = true;4919break;4920}4921}4922}4923}4924}4925if (Any)4926LU.RecomputeRegs(LUIdx, RegUses);4927}49284929LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));4930}4931}49324933/// When there are many registers for expressions like A, A+1, A+2, etc.,4934/// allocate a single register for them.4935void LSRInstance::NarrowSearchSpaceByCollapsingUnrolledCode() {4936if (EstimateSearchSpaceComplexity() < ComplexityLimit)4937return;49384939LLVM_DEBUG(4940dbgs() << "The search space is too complex.\n"4941"Narrowing the search space by assuming that uses separated "4942"by a constant offset will use the same registers.\n");49434944// This is especially useful for unrolled loops.49454946for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {4947LSRUse &LU = Uses[LUIdx];4948for (const Formula &F : LU.Formulae) {4949if (F.BaseOffset.isZero() || (F.Scale != 0 && F.Scale != 1))4950continue;49514952LSRUse *LUThatHas = FindUseWithSimilarFormula(F, LU);4953if (!LUThatHas)4954continue;49554956if (!reconcileNewOffset(*LUThatHas, F.BaseOffset, /*HasBaseReg=*/ false,4957LU.Kind, LU.AccessTy))4958continue;49594960LLVM_DEBUG(dbgs() << " Deleting use "; LU.print(dbgs()); dbgs() << '\n');49614962LUThatHas->AllFixupsOutsideLoop &= LU.AllFixupsOutsideLoop;49634964// Transfer the fixups of LU to LUThatHas.4965for (LSRFixup &Fixup : LU.Fixups) {4966Fixup.Offset += F.BaseOffset;4967LUThatHas->pushFixup(Fixup);4968LLVM_DEBUG(dbgs() << "New fixup has offset " << Fixup.Offset << '\n');4969}49704971// Delete formulae from the new use which are no longer legal.4972bool Any = false;4973for (size_t i = 0, e = LUThatHas->Formulae.size(); i != e; ++i) {4974Formula &F = LUThatHas->Formulae[i];4975if (!isLegalUse(TTI, LUThatHas->MinOffset, LUThatHas->MaxOffset,4976LUThatHas->Kind, LUThatHas->AccessTy, F)) {4977LLVM_DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');4978LUThatHas->DeleteFormula(F);4979--i;4980--e;4981Any = true;4982}4983}49844985if (Any)4986LUThatHas->RecomputeRegs(LUThatHas - &Uses.front(), RegUses);49874988// Delete the old use.4989DeleteUse(LU, LUIdx);4990--LUIdx;4991--NumUses;4992break;4993}4994}49954996LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));4997}49984999/// Call FilterOutUndesirableDedicatedRegisters again, if necessary, now that5000/// we've done more filtering, as it may be able to find more formulae to5001/// eliminate.5002void LSRInstance::NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters(){5003if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {5004LLVM_DEBUG(dbgs() << "The search space is too complex.\n");50055006LLVM_DEBUG(dbgs() << "Narrowing the search space by re-filtering out "5007"undesirable dedicated registers.\n");50085009FilterOutUndesirableDedicatedRegisters();50105011LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));5012}5013}50145015/// If a LSRUse has multiple formulae with the same ScaledReg and Scale.5016/// Pick the best one and delete the others.5017/// This narrowing heuristic is to keep as many formulae with different5018/// Scale and ScaledReg pair as possible while narrowing the search space.5019/// The benefit is that it is more likely to find out a better solution5020/// from a formulae set with more Scale and ScaledReg variations than5021/// a formulae set with the same Scale and ScaledReg. The picking winner5022/// reg heuristic will often keep the formulae with the same Scale and5023/// ScaledReg and filter others, and we want to avoid that if possible.5024void LSRInstance::NarrowSearchSpaceByFilterFormulaWithSameScaledReg() {5025if (EstimateSearchSpaceComplexity() < ComplexityLimit)5026return;50275028LLVM_DEBUG(5029dbgs() << "The search space is too complex.\n"5030"Narrowing the search space by choosing the best Formula "5031"from the Formulae with the same Scale and ScaledReg.\n");50325033// Map the "Scale * ScaledReg" pair to the best formula of current LSRUse.5034using BestFormulaeTy = DenseMap<std::pair<const SCEV *, int64_t>, size_t>;50355036BestFormulaeTy BestFormulae;5037#ifndef NDEBUG5038bool ChangedFormulae = false;5039#endif5040DenseSet<const SCEV *> VisitedRegs;5041SmallPtrSet<const SCEV *, 16> Regs;50425043for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {5044LSRUse &LU = Uses[LUIdx];5045LLVM_DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs());5046dbgs() << '\n');50475048// Return true if Formula FA is better than Formula FB.5049auto IsBetterThan = [&](Formula &FA, Formula &FB) {5050// First we will try to choose the Formula with fewer new registers.5051// For a register used by current Formula, the more the register is5052// shared among LSRUses, the less we increase the register number5053// counter of the formula.5054size_t FARegNum = 0;5055for (const SCEV *Reg : FA.BaseRegs) {5056const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(Reg);5057FARegNum += (NumUses - UsedByIndices.count() + 1);5058}5059size_t FBRegNum = 0;5060for (const SCEV *Reg : FB.BaseRegs) {5061const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(Reg);5062FBRegNum += (NumUses - UsedByIndices.count() + 1);5063}5064if (FARegNum != FBRegNum)5065return FARegNum < FBRegNum;50665067// If the new register numbers are the same, choose the Formula with5068// less Cost.5069Cost CostFA(L, SE, TTI, AMK);5070Cost CostFB(L, SE, TTI, AMK);5071Regs.clear();5072CostFA.RateFormula(FA, Regs, VisitedRegs, LU);5073Regs.clear();5074CostFB.RateFormula(FB, Regs, VisitedRegs, LU);5075return CostFA.isLess(CostFB);5076};50775078bool Any = false;5079for (size_t FIdx = 0, NumForms = LU.Formulae.size(); FIdx != NumForms;5080++FIdx) {5081Formula &F = LU.Formulae[FIdx];5082if (!F.ScaledReg)5083continue;5084auto P = BestFormulae.insert({{F.ScaledReg, F.Scale}, FIdx});5085if (P.second)5086continue;50875088Formula &Best = LU.Formulae[P.first->second];5089if (IsBetterThan(F, Best))5090std::swap(F, Best);5091LLVM_DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs());5092dbgs() << "\n"5093" in favor of formula ";5094Best.print(dbgs()); dbgs() << '\n');5095#ifndef NDEBUG5096ChangedFormulae = true;5097#endif5098LU.DeleteFormula(F);5099--FIdx;5100--NumForms;5101Any = true;5102}5103if (Any)5104LU.RecomputeRegs(LUIdx, RegUses);51055106// Reset this to prepare for the next use.5107BestFormulae.clear();5108}51095110LLVM_DEBUG(if (ChangedFormulae) {5111dbgs() << "\n"5112"After filtering out undesirable candidates:\n";5113print_uses(dbgs());5114});5115}51165117/// If we are over the complexity limit, filter out any post-inc prefering5118/// variables to only post-inc values.5119void LSRInstance::NarrowSearchSpaceByFilterPostInc() {5120if (AMK != TTI::AMK_PostIndexed)5121return;5122if (EstimateSearchSpaceComplexity() < ComplexityLimit)5123return;51245125LLVM_DEBUG(dbgs() << "The search space is too complex.\n"5126"Narrowing the search space by choosing the lowest "5127"register Formula for PostInc Uses.\n");51285129for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {5130LSRUse &LU = Uses[LUIdx];51315132if (LU.Kind != LSRUse::Address)5133continue;5134if (!TTI.isIndexedLoadLegal(TTI.MIM_PostInc, LU.AccessTy.getType()) &&5135!TTI.isIndexedStoreLegal(TTI.MIM_PostInc, LU.AccessTy.getType()))5136continue;51375138size_t MinRegs = std::numeric_limits<size_t>::max();5139for (const Formula &F : LU.Formulae)5140MinRegs = std::min(F.getNumRegs(), MinRegs);51415142bool Any = false;5143for (size_t FIdx = 0, NumForms = LU.Formulae.size(); FIdx != NumForms;5144++FIdx) {5145Formula &F = LU.Formulae[FIdx];5146if (F.getNumRegs() > MinRegs) {5147LLVM_DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs());5148dbgs() << "\n");5149LU.DeleteFormula(F);5150--FIdx;5151--NumForms;5152Any = true;5153}5154}5155if (Any)5156LU.RecomputeRegs(LUIdx, RegUses);51575158if (EstimateSearchSpaceComplexity() < ComplexityLimit)5159break;5160}51615162LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));5163}51645165/// The function delete formulas with high registers number expectation.5166/// Assuming we don't know the value of each formula (already delete5167/// all inefficient), generate probability of not selecting for each5168/// register.5169/// For example,5170/// Use1:5171/// reg(a) + reg({0,+,1})5172/// reg(a) + reg({-1,+,1}) + 15173/// reg({a,+,1})5174/// Use2:5175/// reg(b) + reg({0,+,1})5176/// reg(b) + reg({-1,+,1}) + 15177/// reg({b,+,1})5178/// Use3:5179/// reg(c) + reg(b) + reg({0,+,1})5180/// reg(c) + reg({b,+,1})5181///5182/// Probability of not selecting5183/// Use1 Use2 Use35184/// reg(a) (1/3) * 1 * 15185/// reg(b) 1 * (1/3) * (1/2)5186/// reg({0,+,1}) (2/3) * (2/3) * (1/2)5187/// reg({-1,+,1}) (2/3) * (2/3) * 15188/// reg({a,+,1}) (2/3) * 1 * 15189/// reg({b,+,1}) 1 * (2/3) * (2/3)5190/// reg(c) 1 * 1 * 05191///5192/// Now count registers number mathematical expectation for each formula:5193/// Note that for each use we exclude probability if not selecting for the use.5194/// For example for Use1 probability for reg(a) would be just 1 * 1 (excluding5195/// probabilty 1/3 of not selecting for Use1).5196/// Use1:5197/// reg(a) + reg({0,+,1}) 1 + 1/3 -- to be deleted5198/// reg(a) + reg({-1,+,1}) + 1 1 + 4/9 -- to be deleted5199/// reg({a,+,1}) 15200/// Use2:5201/// reg(b) + reg({0,+,1}) 1/2 + 1/3 -- to be deleted5202/// reg(b) + reg({-1,+,1}) + 1 1/2 + 2/3 -- to be deleted5203/// reg({b,+,1}) 2/35204/// Use3:5205/// reg(c) + reg(b) + reg({0,+,1}) 1 + 1/3 + 4/9 -- to be deleted5206/// reg(c) + reg({b,+,1}) 1 + 2/35207void LSRInstance::NarrowSearchSpaceByDeletingCostlyFormulas() {5208if (EstimateSearchSpaceComplexity() < ComplexityLimit)5209return;5210// Ok, we have too many of formulae on our hands to conveniently handle.5211// Use a rough heuristic to thin out the list.52125213// Set of Regs wich will be 100% used in final solution.5214// Used in each formula of a solution (in example above this is reg(c)).5215// We can skip them in calculations.5216SmallPtrSet<const SCEV *, 4> UniqRegs;5217LLVM_DEBUG(dbgs() << "The search space is too complex.\n");52185219// Map each register to probability of not selecting5220DenseMap <const SCEV *, float> RegNumMap;5221for (const SCEV *Reg : RegUses) {5222if (UniqRegs.count(Reg))5223continue;5224float PNotSel = 1;5225for (const LSRUse &LU : Uses) {5226if (!LU.Regs.count(Reg))5227continue;5228float P = LU.getNotSelectedProbability(Reg);5229if (P != 0.0)5230PNotSel *= P;5231else5232UniqRegs.insert(Reg);5233}5234RegNumMap.insert(std::make_pair(Reg, PNotSel));5235}52365237LLVM_DEBUG(5238dbgs() << "Narrowing the search space by deleting costly formulas\n");52395240// Delete formulas where registers number expectation is high.5241for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {5242LSRUse &LU = Uses[LUIdx];5243// If nothing to delete - continue.5244if (LU.Formulae.size() < 2)5245continue;5246// This is temporary solution to test performance. Float should be5247// replaced with round independent type (based on integers) to avoid5248// different results for different target builds.5249float FMinRegNum = LU.Formulae[0].getNumRegs();5250float FMinARegNum = LU.Formulae[0].getNumRegs();5251size_t MinIdx = 0;5252for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {5253Formula &F = LU.Formulae[i];5254float FRegNum = 0;5255float FARegNum = 0;5256for (const SCEV *BaseReg : F.BaseRegs) {5257if (UniqRegs.count(BaseReg))5258continue;5259FRegNum += RegNumMap[BaseReg] / LU.getNotSelectedProbability(BaseReg);5260if (isa<SCEVAddRecExpr>(BaseReg))5261FARegNum +=5262RegNumMap[BaseReg] / LU.getNotSelectedProbability(BaseReg);5263}5264if (const SCEV *ScaledReg = F.ScaledReg) {5265if (!UniqRegs.count(ScaledReg)) {5266FRegNum +=5267RegNumMap[ScaledReg] / LU.getNotSelectedProbability(ScaledReg);5268if (isa<SCEVAddRecExpr>(ScaledReg))5269FARegNum +=5270RegNumMap[ScaledReg] / LU.getNotSelectedProbability(ScaledReg);5271}5272}5273if (FMinRegNum > FRegNum ||5274(FMinRegNum == FRegNum && FMinARegNum > FARegNum)) {5275FMinRegNum = FRegNum;5276FMinARegNum = FARegNum;5277MinIdx = i;5278}5279}5280LLVM_DEBUG(dbgs() << " The formula "; LU.Formulae[MinIdx].print(dbgs());5281dbgs() << " with min reg num " << FMinRegNum << '\n');5282if (MinIdx != 0)5283std::swap(LU.Formulae[MinIdx], LU.Formulae[0]);5284while (LU.Formulae.size() != 1) {5285LLVM_DEBUG(dbgs() << " Deleting "; LU.Formulae.back().print(dbgs());5286dbgs() << '\n');5287LU.Formulae.pop_back();5288}5289LU.RecomputeRegs(LUIdx, RegUses);5290assert(LU.Formulae.size() == 1 && "Should be exactly 1 min regs formula");5291Formula &F = LU.Formulae[0];5292LLVM_DEBUG(dbgs() << " Leaving only "; F.print(dbgs()); dbgs() << '\n');5293// When we choose the formula, the regs become unique.5294UniqRegs.insert(F.BaseRegs.begin(), F.BaseRegs.end());5295if (F.ScaledReg)5296UniqRegs.insert(F.ScaledReg);5297}5298LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));5299}53005301// Check if Best and Reg are SCEVs separated by a constant amount C, and if so5302// would the addressing offset +C would be legal where the negative offset -C is5303// not.5304static bool IsSimplerBaseSCEVForTarget(const TargetTransformInfo &TTI,5305ScalarEvolution &SE, const SCEV *Best,5306const SCEV *Reg,5307MemAccessTy AccessType) {5308if (Best->getType() != Reg->getType() ||5309(isa<SCEVAddRecExpr>(Best) && isa<SCEVAddRecExpr>(Reg) &&5310cast<SCEVAddRecExpr>(Best)->getLoop() !=5311cast<SCEVAddRecExpr>(Reg)->getLoop()))5312return false;5313const auto *Diff = dyn_cast<SCEVConstant>(SE.getMinusSCEV(Best, Reg));5314if (!Diff)5315return false;53165317return TTI.isLegalAddressingMode(5318AccessType.MemTy, /*BaseGV=*/nullptr,5319/*BaseOffset=*/Diff->getAPInt().getSExtValue(),5320/*HasBaseReg=*/true, /*Scale=*/0, AccessType.AddrSpace) &&5321!TTI.isLegalAddressingMode(5322AccessType.MemTy, /*BaseGV=*/nullptr,5323/*BaseOffset=*/-Diff->getAPInt().getSExtValue(),5324/*HasBaseReg=*/true, /*Scale=*/0, AccessType.AddrSpace);5325}53265327/// Pick a register which seems likely to be profitable, and then in any use5328/// which has any reference to that register, delete all formulae which do not5329/// reference that register.5330void LSRInstance::NarrowSearchSpaceByPickingWinnerRegs() {5331// With all other options exhausted, loop until the system is simple5332// enough to handle.5333SmallPtrSet<const SCEV *, 4> Taken;5334while (EstimateSearchSpaceComplexity() >= ComplexityLimit) {5335// Ok, we have too many of formulae on our hands to conveniently handle.5336// Use a rough heuristic to thin out the list.5337LLVM_DEBUG(dbgs() << "The search space is too complex.\n");53385339// Pick the register which is used by the most LSRUses, which is likely5340// to be a good reuse register candidate.5341const SCEV *Best = nullptr;5342unsigned BestNum = 0;5343for (const SCEV *Reg : RegUses) {5344if (Taken.count(Reg))5345continue;5346if (!Best) {5347Best = Reg;5348BestNum = RegUses.getUsedByIndices(Reg).count();5349} else {5350unsigned Count = RegUses.getUsedByIndices(Reg).count();5351if (Count > BestNum) {5352Best = Reg;5353BestNum = Count;5354}53555356// If the scores are the same, but the Reg is simpler for the target5357// (for example {x,+,1} as opposed to {x+C,+,1}, where the target can5358// handle +C but not -C), opt for the simpler formula.5359if (Count == BestNum) {5360int LUIdx = RegUses.getUsedByIndices(Reg).find_first();5361if (LUIdx >= 0 && Uses[LUIdx].Kind == LSRUse::Address &&5362IsSimplerBaseSCEVForTarget(TTI, SE, Best, Reg,5363Uses[LUIdx].AccessTy)) {5364Best = Reg;5365BestNum = Count;5366}5367}5368}5369}5370assert(Best && "Failed to find best LSRUse candidate");53715372LLVM_DEBUG(dbgs() << "Narrowing the search space by assuming " << *Best5373<< " will yield profitable reuse.\n");5374Taken.insert(Best);53755376// In any use with formulae which references this register, delete formulae5377// which don't reference it.5378for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {5379LSRUse &LU = Uses[LUIdx];5380if (!LU.Regs.count(Best)) continue;53815382bool Any = false;5383for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {5384Formula &F = LU.Formulae[i];5385if (!F.referencesReg(Best)) {5386LLVM_DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');5387LU.DeleteFormula(F);5388--e;5389--i;5390Any = true;5391assert(e != 0 && "Use has no formulae left! Is Regs inconsistent?");5392continue;5393}5394}53955396if (Any)5397LU.RecomputeRegs(LUIdx, RegUses);5398}53995400LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));5401}5402}54035404/// If there are an extraordinary number of formulae to choose from, use some5405/// rough heuristics to prune down the number of formulae. This keeps the main5406/// solver from taking an extraordinary amount of time in some worst-case5407/// scenarios.5408void LSRInstance::NarrowSearchSpaceUsingHeuristics() {5409NarrowSearchSpaceByDetectingSupersets();5410NarrowSearchSpaceByCollapsingUnrolledCode();5411NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();5412if (FilterSameScaledReg)5413NarrowSearchSpaceByFilterFormulaWithSameScaledReg();5414NarrowSearchSpaceByFilterPostInc();5415if (LSRExpNarrow)5416NarrowSearchSpaceByDeletingCostlyFormulas();5417else5418NarrowSearchSpaceByPickingWinnerRegs();5419}54205421/// This is the recursive solver.5422void LSRInstance::SolveRecurse(SmallVectorImpl<const Formula *> &Solution,5423Cost &SolutionCost,5424SmallVectorImpl<const Formula *> &Workspace,5425const Cost &CurCost,5426const SmallPtrSet<const SCEV *, 16> &CurRegs,5427DenseSet<const SCEV *> &VisitedRegs) const {5428// Some ideas:5429// - prune more:5430// - use more aggressive filtering5431// - sort the formula so that the most profitable solutions are found first5432// - sort the uses too5433// - search faster:5434// - don't compute a cost, and then compare. compare while computing a cost5435// and bail early.5436// - track register sets with SmallBitVector54375438const LSRUse &LU = Uses[Workspace.size()];54395440// If this use references any register that's already a part of the5441// in-progress solution, consider it a requirement that a formula must5442// reference that register in order to be considered. This prunes out5443// unprofitable searching.5444SmallSetVector<const SCEV *, 4> ReqRegs;5445for (const SCEV *S : CurRegs)5446if (LU.Regs.count(S))5447ReqRegs.insert(S);54485449SmallPtrSet<const SCEV *, 16> NewRegs;5450Cost NewCost(L, SE, TTI, AMK);5451for (const Formula &F : LU.Formulae) {5452// Ignore formulae which may not be ideal in terms of register reuse of5453// ReqRegs. The formula should use all required registers before5454// introducing new ones.5455// This can sometimes (notably when trying to favour postinc) lead to5456// sub-optimial decisions. There it is best left to the cost modelling to5457// get correct.5458if (AMK != TTI::AMK_PostIndexed || LU.Kind != LSRUse::Address) {5459int NumReqRegsToFind = std::min(F.getNumRegs(), ReqRegs.size());5460for (const SCEV *Reg : ReqRegs) {5461if ((F.ScaledReg && F.ScaledReg == Reg) ||5462is_contained(F.BaseRegs, Reg)) {5463--NumReqRegsToFind;5464if (NumReqRegsToFind == 0)5465break;5466}5467}5468if (NumReqRegsToFind != 0) {5469// If none of the formulae satisfied the required registers, then we could5470// clear ReqRegs and try again. Currently, we simply give up in this case.5471continue;5472}5473}54745475// Evaluate the cost of the current formula. If it's already worse than5476// the current best, prune the search at that point.5477NewCost = CurCost;5478NewRegs = CurRegs;5479NewCost.RateFormula(F, NewRegs, VisitedRegs, LU);5480if (NewCost.isLess(SolutionCost)) {5481Workspace.push_back(&F);5482if (Workspace.size() != Uses.size()) {5483SolveRecurse(Solution, SolutionCost, Workspace, NewCost,5484NewRegs, VisitedRegs);5485if (F.getNumRegs() == 1 && Workspace.size() == 1)5486VisitedRegs.insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]);5487} else {5488LLVM_DEBUG(dbgs() << "New best at "; NewCost.print(dbgs());5489dbgs() << ".\nRegs:\n";5490for (const SCEV *S : NewRegs) dbgs()5491<< "- " << *S << "\n";5492dbgs() << '\n');54935494SolutionCost = NewCost;5495Solution = Workspace;5496}5497Workspace.pop_back();5498}5499}5500}55015502/// Choose one formula from each use. Return the results in the given Solution5503/// vector.5504void LSRInstance::Solve(SmallVectorImpl<const Formula *> &Solution) const {5505SmallVector<const Formula *, 8> Workspace;5506Cost SolutionCost(L, SE, TTI, AMK);5507SolutionCost.Lose();5508Cost CurCost(L, SE, TTI, AMK);5509SmallPtrSet<const SCEV *, 16> CurRegs;5510DenseSet<const SCEV *> VisitedRegs;5511Workspace.reserve(Uses.size());55125513// SolveRecurse does all the work.5514SolveRecurse(Solution, SolutionCost, Workspace, CurCost,5515CurRegs, VisitedRegs);5516if (Solution.empty()) {5517LLVM_DEBUG(dbgs() << "\nNo Satisfactory Solution\n");5518return;5519}55205521// Ok, we've now made all our decisions.5522LLVM_DEBUG(dbgs() << "\n"5523"The chosen solution requires ";5524SolutionCost.print(dbgs()); dbgs() << ":\n";5525for (size_t i = 0, e = Uses.size(); i != e; ++i) {5526dbgs() << " ";5527Uses[i].print(dbgs());5528dbgs() << "\n"5529" ";5530Solution[i]->print(dbgs());5531dbgs() << '\n';5532});55335534assert(Solution.size() == Uses.size() && "Malformed solution!");55355536const bool EnableDropUnprofitableSolution = [&] {5537switch (AllowDropSolutionIfLessProfitable) {5538case cl::BOU_TRUE:5539return true;5540case cl::BOU_FALSE:5541return false;5542case cl::BOU_UNSET:5543return TTI.shouldDropLSRSolutionIfLessProfitable();5544}5545llvm_unreachable("Unhandled cl::boolOrDefault enum");5546}();55475548if (BaselineCost.isLess(SolutionCost)) {5549if (!EnableDropUnprofitableSolution)5550LLVM_DEBUG(5551dbgs() << "Baseline is more profitable than chosen solution, "5552"add option 'lsr-drop-solution' to drop LSR solution.\n");5553else {5554LLVM_DEBUG(dbgs() << "Baseline is more profitable than chosen "5555"solution, dropping LSR solution.\n";);5556Solution.clear();5557}5558}5559}55605561/// Helper for AdjustInsertPositionForExpand. Climb up the dominator tree far as5562/// we can go while still being dominated by the input positions. This helps5563/// canonicalize the insert position, which encourages sharing.5564BasicBlock::iterator5565LSRInstance::HoistInsertPosition(BasicBlock::iterator IP,5566const SmallVectorImpl<Instruction *> &Inputs)5567const {5568Instruction *Tentative = &*IP;5569while (true) {5570bool AllDominate = true;5571Instruction *BetterPos = nullptr;5572// Don't bother attempting to insert before a catchswitch, their basic block5573// cannot have other non-PHI instructions.5574if (isa<CatchSwitchInst>(Tentative))5575return IP;55765577for (Instruction *Inst : Inputs) {5578if (Inst == Tentative || !DT.dominates(Inst, Tentative)) {5579AllDominate = false;5580break;5581}5582// Attempt to find an insert position in the middle of the block,5583// instead of at the end, so that it can be used for other expansions.5584if (Tentative->getParent() == Inst->getParent() &&5585(!BetterPos || !DT.dominates(Inst, BetterPos)))5586BetterPos = &*std::next(BasicBlock::iterator(Inst));5587}5588if (!AllDominate)5589break;5590if (BetterPos)5591IP = BetterPos->getIterator();5592else5593IP = Tentative->getIterator();55945595const Loop *IPLoop = LI.getLoopFor(IP->getParent());5596unsigned IPLoopDepth = IPLoop ? IPLoop->getLoopDepth() : 0;55975598BasicBlock *IDom;5599for (DomTreeNode *Rung = DT.getNode(IP->getParent()); ; ) {5600if (!Rung) return IP;5601Rung = Rung->getIDom();5602if (!Rung) return IP;5603IDom = Rung->getBlock();56045605// Don't climb into a loop though.5606const Loop *IDomLoop = LI.getLoopFor(IDom);5607unsigned IDomDepth = IDomLoop ? IDomLoop->getLoopDepth() : 0;5608if (IDomDepth <= IPLoopDepth &&5609(IDomDepth != IPLoopDepth || IDomLoop == IPLoop))5610break;5611}56125613Tentative = IDom->getTerminator();5614}56155616return IP;5617}56185619/// Determine an input position which will be dominated by the operands and5620/// which will dominate the result.5621BasicBlock::iterator LSRInstance::AdjustInsertPositionForExpand(5622BasicBlock::iterator LowestIP, const LSRFixup &LF, const LSRUse &LU) const {5623// Collect some instructions which must be dominated by the5624// expanding replacement. These must be dominated by any operands that5625// will be required in the expansion.5626SmallVector<Instruction *, 4> Inputs;5627if (Instruction *I = dyn_cast<Instruction>(LF.OperandValToReplace))5628Inputs.push_back(I);5629if (LU.Kind == LSRUse::ICmpZero)5630if (Instruction *I =5631dyn_cast<Instruction>(cast<ICmpInst>(LF.UserInst)->getOperand(1)))5632Inputs.push_back(I);5633if (LF.PostIncLoops.count(L)) {5634if (LF.isUseFullyOutsideLoop(L))5635Inputs.push_back(L->getLoopLatch()->getTerminator());5636else5637Inputs.push_back(IVIncInsertPos);5638}5639// The expansion must also be dominated by the increment positions of any5640// loops it for which it is using post-inc mode.5641for (const Loop *PIL : LF.PostIncLoops) {5642if (PIL == L) continue;56435644// Be dominated by the loop exit.5645SmallVector<BasicBlock *, 4> ExitingBlocks;5646PIL->getExitingBlocks(ExitingBlocks);5647if (!ExitingBlocks.empty()) {5648BasicBlock *BB = ExitingBlocks[0];5649for (unsigned i = 1, e = ExitingBlocks.size(); i != e; ++i)5650BB = DT.findNearestCommonDominator(BB, ExitingBlocks[i]);5651Inputs.push_back(BB->getTerminator());5652}5653}56545655assert(!isa<PHINode>(LowestIP) && !LowestIP->isEHPad()5656&& !isa<DbgInfoIntrinsic>(LowestIP) &&5657"Insertion point must be a normal instruction");56585659// Then, climb up the immediate dominator tree as far as we can go while5660// still being dominated by the input positions.5661BasicBlock::iterator IP = HoistInsertPosition(LowestIP, Inputs);56625663// Don't insert instructions before PHI nodes.5664while (isa<PHINode>(IP)) ++IP;56655666// Ignore landingpad instructions.5667while (IP->isEHPad()) ++IP;56685669// Ignore debug intrinsics.5670while (isa<DbgInfoIntrinsic>(IP)) ++IP;56715672// Set IP below instructions recently inserted by SCEVExpander. This keeps the5673// IP consistent across expansions and allows the previously inserted5674// instructions to be reused by subsequent expansion.5675while (Rewriter.isInsertedInstruction(&*IP) && IP != LowestIP)5676++IP;56775678return IP;5679}56805681/// Emit instructions for the leading candidate expression for this LSRUse (this5682/// is called "expanding").5683Value *LSRInstance::Expand(const LSRUse &LU, const LSRFixup &LF,5684const Formula &F, BasicBlock::iterator IP,5685SmallVectorImpl<WeakTrackingVH> &DeadInsts) const {5686if (LU.RigidFormula)5687return LF.OperandValToReplace;56885689// Determine an input position which will be dominated by the operands and5690// which will dominate the result.5691IP = AdjustInsertPositionForExpand(IP, LF, LU);5692Rewriter.setInsertPoint(&*IP);56935694// Inform the Rewriter if we have a post-increment use, so that it can5695// perform an advantageous expansion.5696Rewriter.setPostInc(LF.PostIncLoops);56975698// This is the type that the user actually needs.5699Type *OpTy = LF.OperandValToReplace->getType();5700// This will be the type that we'll initially expand to.5701Type *Ty = F.getType();5702if (!Ty)5703// No type known; just expand directly to the ultimate type.5704Ty = OpTy;5705else if (SE.getEffectiveSCEVType(Ty) == SE.getEffectiveSCEVType(OpTy))5706// Expand directly to the ultimate type if it's the right size.5707Ty = OpTy;5708// This is the type to do integer arithmetic in.5709Type *IntTy = SE.getEffectiveSCEVType(Ty);57105711// Build up a list of operands to add together to form the full base.5712SmallVector<const SCEV *, 8> Ops;57135714// Expand the BaseRegs portion.5715for (const SCEV *Reg : F.BaseRegs) {5716assert(!Reg->isZero() && "Zero allocated in a base register!");57175718// If we're expanding for a post-inc user, make the post-inc adjustment.5719Reg = denormalizeForPostIncUse(Reg, LF.PostIncLoops, SE);5720Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, nullptr)));5721}57225723// Expand the ScaledReg portion.5724Value *ICmpScaledV = nullptr;5725if (F.Scale != 0) {5726const SCEV *ScaledS = F.ScaledReg;57275728// If we're expanding for a post-inc user, make the post-inc adjustment.5729PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);5730ScaledS = denormalizeForPostIncUse(ScaledS, Loops, SE);57315732if (LU.Kind == LSRUse::ICmpZero) {5733// Expand ScaleReg as if it was part of the base regs.5734if (F.Scale == 1)5735Ops.push_back(5736SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr)));5737else {5738// An interesting way of "folding" with an icmp is to use a negated5739// scale, which we'll implement by inserting it into the other operand5740// of the icmp.5741assert(F.Scale == -1 &&5742"The only scale supported by ICmpZero uses is -1!");5743ICmpScaledV = Rewriter.expandCodeFor(ScaledS, nullptr);5744}5745} else {5746// Otherwise just expand the scaled register and an explicit scale,5747// which is expected to be matched as part of the address.57485749// Flush the operand list to suppress SCEVExpander hoisting address modes.5750// Unless the addressing mode will not be folded.5751if (!Ops.empty() && LU.Kind == LSRUse::Address &&5752isAMCompletelyFolded(TTI, LU, F)) {5753Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), nullptr);5754Ops.clear();5755Ops.push_back(SE.getUnknown(FullV));5756}5757ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr));5758if (F.Scale != 1)5759ScaledS =5760SE.getMulExpr(ScaledS, SE.getConstant(ScaledS->getType(), F.Scale));5761Ops.push_back(ScaledS);5762}5763}57645765// Expand the GV portion.5766if (F.BaseGV) {5767// Flush the operand list to suppress SCEVExpander hoisting.5768if (!Ops.empty()) {5769Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), IntTy);5770Ops.clear();5771Ops.push_back(SE.getUnknown(FullV));5772}5773Ops.push_back(SE.getUnknown(F.BaseGV));5774}57755776// Flush the operand list to suppress SCEVExpander hoisting of both folded and5777// unfolded offsets. LSR assumes they both live next to their uses.5778if (!Ops.empty()) {5779Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty);5780Ops.clear();5781Ops.push_back(SE.getUnknown(FullV));5782}57835784// FIXME: Are we sure we won't get a mismatch here? Is there a way to bail5785// out at this point, or should we generate a SCEV adding together mixed5786// offsets?5787assert(F.BaseOffset.isCompatibleImmediate(LF.Offset) &&5788"Expanding mismatched offsets\n");5789// Expand the immediate portion.5790Immediate Offset = F.BaseOffset.addUnsigned(LF.Offset);5791if (Offset.isNonZero()) {5792if (LU.Kind == LSRUse::ICmpZero) {5793// The other interesting way of "folding" with an ICmpZero is to use a5794// negated immediate.5795if (!ICmpScaledV)5796ICmpScaledV =5797ConstantInt::get(IntTy, -(uint64_t)Offset.getFixedValue());5798else {5799Ops.push_back(SE.getUnknown(ICmpScaledV));5800ICmpScaledV = ConstantInt::get(IntTy, Offset.getFixedValue());5801}5802} else {5803// Just add the immediate values. These again are expected to be matched5804// as part of the address.5805Ops.push_back(Offset.getUnknownSCEV(SE, IntTy));5806}5807}58085809// Expand the unfolded offset portion.5810Immediate UnfoldedOffset = F.UnfoldedOffset;5811if (UnfoldedOffset.isNonZero()) {5812// Just add the immediate values.5813Ops.push_back(UnfoldedOffset.getUnknownSCEV(SE, IntTy));5814}58155816// Emit instructions summing all the operands.5817const SCEV *FullS = Ops.empty() ?5818SE.getConstant(IntTy, 0) :5819SE.getAddExpr(Ops);5820Value *FullV = Rewriter.expandCodeFor(FullS, Ty);58215822// We're done expanding now, so reset the rewriter.5823Rewriter.clearPostInc();58245825// An ICmpZero Formula represents an ICmp which we're handling as a5826// comparison against zero. Now that we've expanded an expression for that5827// form, update the ICmp's other operand.5828if (LU.Kind == LSRUse::ICmpZero) {5829ICmpInst *CI = cast<ICmpInst>(LF.UserInst);5830if (auto *OperandIsInstr = dyn_cast<Instruction>(CI->getOperand(1)))5831DeadInsts.emplace_back(OperandIsInstr);5832assert(!F.BaseGV && "ICmp does not support folding a global value and "5833"a scale at the same time!");5834if (F.Scale == -1) {5835if (ICmpScaledV->getType() != OpTy) {5836Instruction *Cast = CastInst::Create(5837CastInst::getCastOpcode(ICmpScaledV, false, OpTy, false),5838ICmpScaledV, OpTy, "tmp", CI->getIterator());5839ICmpScaledV = Cast;5840}5841CI->setOperand(1, ICmpScaledV);5842} else {5843// A scale of 1 means that the scale has been expanded as part of the5844// base regs.5845assert((F.Scale == 0 || F.Scale == 1) &&5846"ICmp does not support folding a global value and "5847"a scale at the same time!");5848Constant *C = ConstantInt::getSigned(SE.getEffectiveSCEVType(OpTy),5849-(uint64_t)Offset.getFixedValue());5850if (C->getType() != OpTy) {5851C = ConstantFoldCastOperand(5852CastInst::getCastOpcode(C, false, OpTy, false), C, OpTy,5853CI->getDataLayout());5854assert(C && "Cast of ConstantInt should have folded");5855}58565857CI->setOperand(1, C);5858}5859}58605861return FullV;5862}58635864/// Helper for Rewrite. PHI nodes are special because the use of their operands5865/// effectively happens in their predecessor blocks, so the expression may need5866/// to be expanded in multiple places.5867void LSRInstance::RewriteForPHI(5868PHINode *PN, const LSRUse &LU, const LSRFixup &LF, const Formula &F,5869SmallVectorImpl<WeakTrackingVH> &DeadInsts) const {5870DenseMap<BasicBlock *, Value *> Inserted;58715872// Inserting instructions in the loop and using them as PHI's input could5873// break LCSSA in case if PHI's parent block is not a loop exit (i.e. the5874// corresponding incoming block is not loop exiting). So collect all such5875// instructions to form LCSSA for them later.5876SmallVector<Instruction *, 4> InsertedNonLCSSAInsts;58775878for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)5879if (PN->getIncomingValue(i) == LF.OperandValToReplace) {5880bool needUpdateFixups = false;5881BasicBlock *BB = PN->getIncomingBlock(i);58825883// If this is a critical edge, split the edge so that we do not insert5884// the code on all predecessor/successor paths. We do this unless this5885// is the canonical backedge for this loop, which complicates post-inc5886// users.5887if (e != 1 && BB->getTerminator()->getNumSuccessors() > 1 &&5888!isa<IndirectBrInst>(BB->getTerminator()) &&5889!isa<CatchSwitchInst>(BB->getTerminator())) {5890BasicBlock *Parent = PN->getParent();5891Loop *PNLoop = LI.getLoopFor(Parent);5892if (!PNLoop || Parent != PNLoop->getHeader()) {5893// Split the critical edge.5894BasicBlock *NewBB = nullptr;5895if (!Parent->isLandingPad()) {5896NewBB =5897SplitCriticalEdge(BB, Parent,5898CriticalEdgeSplittingOptions(&DT, &LI, MSSAU)5899.setMergeIdenticalEdges()5900.setKeepOneInputPHIs());5901} else {5902SmallVector<BasicBlock*, 2> NewBBs;5903DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);5904SplitLandingPadPredecessors(Parent, BB, "", "", NewBBs, &DTU, &LI);5905NewBB = NewBBs[0];5906}5907// If NewBB==NULL, then SplitCriticalEdge refused to split because all5908// phi predecessors are identical. The simple thing to do is skip5909// splitting in this case rather than complicate the API.5910if (NewBB) {5911// If PN is outside of the loop and BB is in the loop, we want to5912// move the block to be immediately before the PHI block, not5913// immediately after BB.5914if (L->contains(BB) && !L->contains(PN))5915NewBB->moveBefore(PN->getParent());59165917// Splitting the edge can reduce the number of PHI entries we have.5918e = PN->getNumIncomingValues();5919BB = NewBB;5920i = PN->getBasicBlockIndex(BB);59215922needUpdateFixups = true;5923}5924}5925}59265927std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> Pair =5928Inserted.insert(std::make_pair(BB, static_cast<Value *>(nullptr)));5929if (!Pair.second)5930PN->setIncomingValue(i, Pair.first->second);5931else {5932Value *FullV =5933Expand(LU, LF, F, BB->getTerminator()->getIterator(), DeadInsts);59345935// If this is reuse-by-noop-cast, insert the noop cast.5936Type *OpTy = LF.OperandValToReplace->getType();5937if (FullV->getType() != OpTy)5938FullV = CastInst::Create(5939CastInst::getCastOpcode(FullV, false, OpTy, false), FullV,5940LF.OperandValToReplace->getType(), "tmp",5941BB->getTerminator()->getIterator());59425943// If the incoming block for this value is not in the loop, it means the5944// current PHI is not in a loop exit, so we must create a LCSSA PHI for5945// the inserted value.5946if (auto *I = dyn_cast<Instruction>(FullV))5947if (L->contains(I) && !L->contains(BB))5948InsertedNonLCSSAInsts.push_back(I);59495950PN->setIncomingValue(i, FullV);5951Pair.first->second = FullV;5952}59535954// If LSR splits critical edge and phi node has other pending5955// fixup operands, we need to update those pending fixups. Otherwise5956// formulae will not be implemented completely and some instructions5957// will not be eliminated.5958if (needUpdateFixups) {5959for (LSRUse &LU : Uses)5960for (LSRFixup &Fixup : LU.Fixups)5961// If fixup is supposed to rewrite some operand in the phi5962// that was just updated, it may be already moved to5963// another phi node. Such fixup requires update.5964if (Fixup.UserInst == PN) {5965// Check if the operand we try to replace still exists in the5966// original phi.5967bool foundInOriginalPHI = false;5968for (const auto &val : PN->incoming_values())5969if (val == Fixup.OperandValToReplace) {5970foundInOriginalPHI = true;5971break;5972}59735974// If fixup operand found in original PHI - nothing to do.5975if (foundInOriginalPHI)5976continue;59775978// Otherwise it might be moved to another PHI and requires update.5979// If fixup operand not found in any of the incoming blocks that5980// means we have already rewritten it - nothing to do.5981for (const auto &Block : PN->blocks())5982for (BasicBlock::iterator I = Block->begin(); isa<PHINode>(I);5983++I) {5984PHINode *NewPN = cast<PHINode>(I);5985for (const auto &val : NewPN->incoming_values())5986if (val == Fixup.OperandValToReplace)5987Fixup.UserInst = NewPN;5988}5989}5990}5991}59925993formLCSSAForInstructions(InsertedNonLCSSAInsts, DT, LI, &SE);5994}59955996/// Emit instructions for the leading candidate expression for this LSRUse (this5997/// is called "expanding"), and update the UserInst to reference the newly5998/// expanded value.5999void LSRInstance::Rewrite(const LSRUse &LU, const LSRFixup &LF,6000const Formula &F,6001SmallVectorImpl<WeakTrackingVH> &DeadInsts) const {6002// First, find an insertion point that dominates UserInst. For PHI nodes,6003// find the nearest block which dominates all the relevant uses.6004if (PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) {6005RewriteForPHI(PN, LU, LF, F, DeadInsts);6006} else {6007Value *FullV = Expand(LU, LF, F, LF.UserInst->getIterator(), DeadInsts);60086009// If this is reuse-by-noop-cast, insert the noop cast.6010Type *OpTy = LF.OperandValToReplace->getType();6011if (FullV->getType() != OpTy) {6012Instruction *Cast =6013CastInst::Create(CastInst::getCastOpcode(FullV, false, OpTy, false),6014FullV, OpTy, "tmp", LF.UserInst->getIterator());6015FullV = Cast;6016}60176018// Update the user. ICmpZero is handled specially here (for now) because6019// Expand may have updated one of the operands of the icmp already, and6020// its new value may happen to be equal to LF.OperandValToReplace, in6021// which case doing replaceUsesOfWith leads to replacing both operands6022// with the same value. TODO: Reorganize this.6023if (LU.Kind == LSRUse::ICmpZero)6024LF.UserInst->setOperand(0, FullV);6025else6026LF.UserInst->replaceUsesOfWith(LF.OperandValToReplace, FullV);6027}60286029if (auto *OperandIsInstr = dyn_cast<Instruction>(LF.OperandValToReplace))6030DeadInsts.emplace_back(OperandIsInstr);6031}60326033// Trying to hoist the IVInc to loop header if all IVInc users are in6034// the loop header. It will help backend to generate post index load/store6035// when the latch block is different from loop header block.6036static bool canHoistIVInc(const TargetTransformInfo &TTI, const LSRFixup &Fixup,6037const LSRUse &LU, Instruction *IVIncInsertPos,6038Loop *L) {6039if (LU.Kind != LSRUse::Address)6040return false;60416042// For now this code do the conservative optimization, only work for6043// the header block. Later we can hoist the IVInc to the block post6044// dominate all users.6045BasicBlock *LHeader = L->getHeader();6046if (IVIncInsertPos->getParent() == LHeader)6047return false;60486049if (!Fixup.OperandValToReplace ||6050any_of(Fixup.OperandValToReplace->users(), [&LHeader](User *U) {6051Instruction *UI = cast<Instruction>(U);6052return UI->getParent() != LHeader;6053}))6054return false;60556056Instruction *I = Fixup.UserInst;6057Type *Ty = I->getType();6058return Ty->isIntegerTy() &&6059((isa<LoadInst>(I) && TTI.isIndexedLoadLegal(TTI.MIM_PostInc, Ty)) ||6060(isa<StoreInst>(I) && TTI.isIndexedStoreLegal(TTI.MIM_PostInc, Ty)));6061}60626063/// Rewrite all the fixup locations with new values, following the chosen6064/// solution.6065void LSRInstance::ImplementSolution(6066const SmallVectorImpl<const Formula *> &Solution) {6067// Keep track of instructions we may have made dead, so that6068// we can remove them after we are done working.6069SmallVector<WeakTrackingVH, 16> DeadInsts;60706071// Mark phi nodes that terminate chains so the expander tries to reuse them.6072for (const IVChain &Chain : IVChainVec) {6073if (PHINode *PN = dyn_cast<PHINode>(Chain.tailUserInst()))6074Rewriter.setChainedPhi(PN);6075}60766077// Expand the new value definitions and update the users.6078for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx)6079for (const LSRFixup &Fixup : Uses[LUIdx].Fixups) {6080Instruction *InsertPos =6081canHoistIVInc(TTI, Fixup, Uses[LUIdx], IVIncInsertPos, L)6082? L->getHeader()->getTerminator()6083: IVIncInsertPos;6084Rewriter.setIVIncInsertPos(L, InsertPos);6085Rewrite(Uses[LUIdx], Fixup, *Solution[LUIdx], DeadInsts);6086Changed = true;6087}60886089for (const IVChain &Chain : IVChainVec) {6090GenerateIVChain(Chain, DeadInsts);6091Changed = true;6092}60936094for (const WeakVH &IV : Rewriter.getInsertedIVs())6095if (IV && dyn_cast<Instruction>(&*IV)->getParent())6096ScalarEvolutionIVs.push_back(IV);60976098// Clean up after ourselves. This must be done before deleting any6099// instructions.6100Rewriter.clear();61016102Changed |= RecursivelyDeleteTriviallyDeadInstructionsPermissive(DeadInsts,6103&TLI, MSSAU);61046105// In our cost analysis above, we assume that each addrec consumes exactly6106// one register, and arrange to have increments inserted just before the6107// latch to maximimize the chance this is true. However, if we reused6108// existing IVs, we now need to move the increments to match our6109// expectations. Otherwise, our cost modeling results in us having a6110// chosen a non-optimal result for the actual schedule. (And yes, this6111// scheduling decision does impact later codegen.)6112for (PHINode &PN : L->getHeader()->phis()) {6113BinaryOperator *BO = nullptr;6114Value *Start = nullptr, *Step = nullptr;6115if (!matchSimpleRecurrence(&PN, BO, Start, Step))6116continue;61176118switch (BO->getOpcode()) {6119case Instruction::Sub:6120if (BO->getOperand(0) != &PN)6121// sub is non-commutative - match handling elsewhere in LSR6122continue;6123break;6124case Instruction::Add:6125break;6126default:6127continue;6128};61296130if (!isa<Constant>(Step))6131// If not a constant step, might increase register pressure6132// (We assume constants have been canonicalized to RHS)6133continue;61346135if (BO->getParent() == IVIncInsertPos->getParent())6136// Only bother moving across blocks. Isel can handle block local case.6137continue;61386139// Can we legally schedule inc at the desired point?6140if (!llvm::all_of(BO->uses(),6141[&](Use &U) {return DT.dominates(IVIncInsertPos, U);}))6142continue;6143BO->moveBefore(IVIncInsertPos);6144Changed = true;6145}614661476148}61496150LSRInstance::LSRInstance(Loop *L, IVUsers &IU, ScalarEvolution &SE,6151DominatorTree &DT, LoopInfo &LI,6152const TargetTransformInfo &TTI, AssumptionCache &AC,6153TargetLibraryInfo &TLI, MemorySSAUpdater *MSSAU)6154: IU(IU), SE(SE), DT(DT), LI(LI), AC(AC), TLI(TLI), TTI(TTI), L(L),6155MSSAU(MSSAU), AMK(PreferredAddresingMode.getNumOccurrences() > 06156? PreferredAddresingMode6157: TTI.getPreferredAddressingMode(L, &SE)),6158Rewriter(SE, L->getHeader()->getDataLayout(), "lsr", false),6159BaselineCost(L, SE, TTI, AMK) {6160// If LoopSimplify form is not available, stay out of trouble.6161if (!L->isLoopSimplifyForm())6162return;61636164// If there's no interesting work to be done, bail early.6165if (IU.empty()) return;61666167// If there's too much analysis to be done, bail early. We won't be able to6168// model the problem anyway.6169unsigned NumUsers = 0;6170for (const IVStrideUse &U : IU) {6171if (++NumUsers > MaxIVUsers) {6172(void)U;6173LLVM_DEBUG(dbgs() << "LSR skipping loop, too many IV Users in " << U6174<< "\n");6175return;6176}6177// Bail out if we have a PHI on an EHPad that gets a value from a6178// CatchSwitchInst. Because the CatchSwitchInst cannot be split, there is6179// no good place to stick any instructions.6180if (auto *PN = dyn_cast<PHINode>(U.getUser())) {6181auto *FirstNonPHI = PN->getParent()->getFirstNonPHI();6182if (isa<FuncletPadInst>(FirstNonPHI) ||6183isa<CatchSwitchInst>(FirstNonPHI))6184for (BasicBlock *PredBB : PN->blocks())6185if (isa<CatchSwitchInst>(PredBB->getFirstNonPHI()))6186return;6187}6188}61896190LLVM_DEBUG(dbgs() << "\nLSR on loop ";6191L->getHeader()->printAsOperand(dbgs(), /*PrintType=*/false);6192dbgs() << ":\n");61936194// Configure SCEVExpander already now, so the correct mode is used for6195// isSafeToExpand() checks.6196#ifndef NDEBUG6197Rewriter.setDebugType(DEBUG_TYPE);6198#endif6199Rewriter.disableCanonicalMode();6200Rewriter.enableLSRMode();62016202// First, perform some low-level loop optimizations.6203OptimizeShadowIV();6204OptimizeLoopTermCond();62056206// If loop preparation eliminates all interesting IV users, bail.6207if (IU.empty()) return;62086209// Skip nested loops until we can model them better with formulae.6210if (!L->isInnermost()) {6211LLVM_DEBUG(dbgs() << "LSR skipping outer loop " << *L << "\n");6212return;6213}62146215// Start collecting data and preparing for the solver.6216// If number of registers is not the major cost, we cannot benefit from the6217// current profitable chain optimization which is based on number of6218// registers.6219// FIXME: add profitable chain optimization for other kinds major cost, for6220// example number of instructions.6221if (TTI.isNumRegsMajorCostOfLSR() || StressIVChain)6222CollectChains();6223CollectInterestingTypesAndFactors();6224CollectFixupsAndInitialFormulae();6225CollectLoopInvariantFixupsAndFormulae();62266227if (Uses.empty())6228return;62296230LLVM_DEBUG(dbgs() << "LSR found " << Uses.size() << " uses:\n";6231print_uses(dbgs()));6232LLVM_DEBUG(dbgs() << "The baseline solution requires ";6233BaselineCost.print(dbgs()); dbgs() << "\n");62346235// Now use the reuse data to generate a bunch of interesting ways6236// to formulate the values needed for the uses.6237GenerateAllReuseFormulae();62386239FilterOutUndesirableDedicatedRegisters();6240NarrowSearchSpaceUsingHeuristics();62416242SmallVector<const Formula *, 8> Solution;6243Solve(Solution);62446245// Release memory that is no longer needed.6246Factors.clear();6247Types.clear();6248RegUses.clear();62496250if (Solution.empty())6251return;62526253#ifndef NDEBUG6254// Formulae should be legal.6255for (const LSRUse &LU : Uses) {6256for (const Formula &F : LU.Formulae)6257assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,6258F) && "Illegal formula generated!");6259};6260#endif62616262// Now that we've decided what we want, make it so.6263ImplementSolution(Solution);6264}62656266#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)6267void LSRInstance::print_factors_and_types(raw_ostream &OS) const {6268if (Factors.empty() && Types.empty()) return;62696270OS << "LSR has identified the following interesting factors and types: ";6271bool First = true;62726273for (int64_t Factor : Factors) {6274if (!First) OS << ", ";6275First = false;6276OS << '*' << Factor;6277}62786279for (Type *Ty : Types) {6280if (!First) OS << ", ";6281First = false;6282OS << '(' << *Ty << ')';6283}6284OS << '\n';6285}62866287void LSRInstance::print_fixups(raw_ostream &OS) const {6288OS << "LSR is examining the following fixup sites:\n";6289for (const LSRUse &LU : Uses)6290for (const LSRFixup &LF : LU.Fixups) {6291dbgs() << " ";6292LF.print(OS);6293OS << '\n';6294}6295}62966297void LSRInstance::print_uses(raw_ostream &OS) const {6298OS << "LSR is examining the following uses:\n";6299for (const LSRUse &LU : Uses) {6300dbgs() << " ";6301LU.print(OS);6302OS << '\n';6303for (const Formula &F : LU.Formulae) {6304OS << " ";6305F.print(OS);6306OS << '\n';6307}6308}6309}63106311void LSRInstance::print(raw_ostream &OS) const {6312print_factors_and_types(OS);6313print_fixups(OS);6314print_uses(OS);6315}63166317LLVM_DUMP_METHOD void LSRInstance::dump() const {6318print(errs()); errs() << '\n';6319}6320#endif63216322namespace {63236324class LoopStrengthReduce : public LoopPass {6325public:6326static char ID; // Pass ID, replacement for typeid63276328LoopStrengthReduce();63296330private:6331bool runOnLoop(Loop *L, LPPassManager &LPM) override;6332void getAnalysisUsage(AnalysisUsage &AU) const override;6333};63346335} // end anonymous namespace63366337LoopStrengthReduce::LoopStrengthReduce() : LoopPass(ID) {6338initializeLoopStrengthReducePass(*PassRegistry::getPassRegistry());6339}63406341void LoopStrengthReduce::getAnalysisUsage(AnalysisUsage &AU) const {6342// We split critical edges, so we change the CFG. However, we do update6343// many analyses if they are around.6344AU.addPreservedID(LoopSimplifyID);63456346AU.addRequired<LoopInfoWrapperPass>();6347AU.addPreserved<LoopInfoWrapperPass>();6348AU.addRequiredID(LoopSimplifyID);6349AU.addRequired<DominatorTreeWrapperPass>();6350AU.addPreserved<DominatorTreeWrapperPass>();6351AU.addRequired<ScalarEvolutionWrapperPass>();6352AU.addPreserved<ScalarEvolutionWrapperPass>();6353AU.addRequired<AssumptionCacheTracker>();6354AU.addRequired<TargetLibraryInfoWrapperPass>();6355// Requiring LoopSimplify a second time here prevents IVUsers from running6356// twice, since LoopSimplify was invalidated by running ScalarEvolution.6357AU.addRequiredID(LoopSimplifyID);6358AU.addRequired<IVUsersWrapperPass>();6359AU.addPreserved<IVUsersWrapperPass>();6360AU.addRequired<TargetTransformInfoWrapperPass>();6361AU.addPreserved<MemorySSAWrapperPass>();6362}63636364namespace {63656366/// Enables more convenient iteration over a DWARF expression vector.6367static iterator_range<llvm::DIExpression::expr_op_iterator>6368ToDwarfOpIter(SmallVectorImpl<uint64_t> &Expr) {6369llvm::DIExpression::expr_op_iterator Begin =6370llvm::DIExpression::expr_op_iterator(Expr.begin());6371llvm::DIExpression::expr_op_iterator End =6372llvm::DIExpression::expr_op_iterator(Expr.end());6373return {Begin, End};6374}63756376struct SCEVDbgValueBuilder {6377SCEVDbgValueBuilder() = default;6378SCEVDbgValueBuilder(const SCEVDbgValueBuilder &Base) { clone(Base); }63796380void clone(const SCEVDbgValueBuilder &Base) {6381LocationOps = Base.LocationOps;6382Expr = Base.Expr;6383}63846385void clear() {6386LocationOps.clear();6387Expr.clear();6388}63896390/// The DIExpression as we translate the SCEV.6391SmallVector<uint64_t, 6> Expr;6392/// The location ops of the DIExpression.6393SmallVector<Value *, 2> LocationOps;63946395void pushOperator(uint64_t Op) { Expr.push_back(Op); }6396void pushUInt(uint64_t Operand) { Expr.push_back(Operand); }63976398/// Add a DW_OP_LLVM_arg to the expression, followed by the index of the value6399/// in the set of values referenced by the expression.6400void pushLocation(llvm::Value *V) {6401Expr.push_back(llvm::dwarf::DW_OP_LLVM_arg);6402auto *It = llvm::find(LocationOps, V);6403unsigned ArgIndex = 0;6404if (It != LocationOps.end()) {6405ArgIndex = std::distance(LocationOps.begin(), It);6406} else {6407ArgIndex = LocationOps.size();6408LocationOps.push_back(V);6409}6410Expr.push_back(ArgIndex);6411}64126413void pushValue(const SCEVUnknown *U) {6414llvm::Value *V = cast<SCEVUnknown>(U)->getValue();6415pushLocation(V);6416}64176418bool pushConst(const SCEVConstant *C) {6419if (C->getAPInt().getSignificantBits() > 64)6420return false;6421Expr.push_back(llvm::dwarf::DW_OP_consts);6422Expr.push_back(C->getAPInt().getSExtValue());6423return true;6424}64256426// Iterating the expression as DWARF ops is convenient when updating6427// DWARF_OP_LLVM_args.6428iterator_range<llvm::DIExpression::expr_op_iterator> expr_ops() {6429return ToDwarfOpIter(Expr);6430}64316432/// Several SCEV types are sequences of the same arithmetic operator applied6433/// to constants and values that may be extended or truncated.6434bool pushArithmeticExpr(const llvm::SCEVCommutativeExpr *CommExpr,6435uint64_t DwarfOp) {6436assert((isa<llvm::SCEVAddExpr>(CommExpr) || isa<SCEVMulExpr>(CommExpr)) &&6437"Expected arithmetic SCEV type");6438bool Success = true;6439unsigned EmitOperator = 0;6440for (const auto &Op : CommExpr->operands()) {6441Success &= pushSCEV(Op);64426443if (EmitOperator >= 1)6444pushOperator(DwarfOp);6445++EmitOperator;6446}6447return Success;6448}64496450// TODO: Identify and omit noop casts.6451bool pushCast(const llvm::SCEVCastExpr *C, bool IsSigned) {6452const llvm::SCEV *Inner = C->getOperand(0);6453const llvm::Type *Type = C->getType();6454uint64_t ToWidth = Type->getIntegerBitWidth();6455bool Success = pushSCEV(Inner);6456uint64_t CastOps[] = {dwarf::DW_OP_LLVM_convert, ToWidth,6457IsSigned ? llvm::dwarf::DW_ATE_signed6458: llvm::dwarf::DW_ATE_unsigned};6459for (const auto &Op : CastOps)6460pushOperator(Op);6461return Success;6462}64636464// TODO: MinMax - although these haven't been encountered in the test suite.6465bool pushSCEV(const llvm::SCEV *S) {6466bool Success = true;6467if (const SCEVConstant *StartInt = dyn_cast<SCEVConstant>(S)) {6468Success &= pushConst(StartInt);64696470} else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {6471if (!U->getValue())6472return false;6473pushLocation(U->getValue());64746475} else if (const SCEVMulExpr *MulRec = dyn_cast<SCEVMulExpr>(S)) {6476Success &= pushArithmeticExpr(MulRec, llvm::dwarf::DW_OP_mul);64776478} else if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {6479Success &= pushSCEV(UDiv->getLHS());6480Success &= pushSCEV(UDiv->getRHS());6481pushOperator(llvm::dwarf::DW_OP_div);64826483} else if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(S)) {6484// Assert if a new and unknown SCEVCastEXpr type is encountered.6485assert((isa<SCEVZeroExtendExpr>(Cast) || isa<SCEVTruncateExpr>(Cast) ||6486isa<SCEVPtrToIntExpr>(Cast) || isa<SCEVSignExtendExpr>(Cast)) &&6487"Unexpected cast type in SCEV.");6488Success &= pushCast(Cast, (isa<SCEVSignExtendExpr>(Cast)));64896490} else if (const SCEVAddExpr *AddExpr = dyn_cast<SCEVAddExpr>(S)) {6491Success &= pushArithmeticExpr(AddExpr, llvm::dwarf::DW_OP_plus);64926493} else if (isa<SCEVAddRecExpr>(S)) {6494// Nested SCEVAddRecExpr are generated by nested loops and are currently6495// unsupported.6496return false;64976498} else {6499return false;6500}6501return Success;6502}65036504/// Return true if the combination of arithmetic operator and underlying6505/// SCEV constant value is an identity function.6506bool isIdentityFunction(uint64_t Op, const SCEV *S) {6507if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {6508if (C->getAPInt().getSignificantBits() > 64)6509return false;6510int64_t I = C->getAPInt().getSExtValue();6511switch (Op) {6512case llvm::dwarf::DW_OP_plus:6513case llvm::dwarf::DW_OP_minus:6514return I == 0;6515case llvm::dwarf::DW_OP_mul:6516case llvm::dwarf::DW_OP_div:6517return I == 1;6518}6519}6520return false;6521}65226523/// Convert a SCEV of a value to a DIExpression that is pushed onto the6524/// builder's expression stack. The stack should already contain an6525/// expression for the iteration count, so that it can be multiplied by6526/// the stride and added to the start.6527/// Components of the expression are omitted if they are an identity function.6528/// Chain (non-affine) SCEVs are not supported.6529bool SCEVToValueExpr(const llvm::SCEVAddRecExpr &SAR, ScalarEvolution &SE) {6530assert(SAR.isAffine() && "Expected affine SCEV");6531// TODO: Is this check needed?6532if (isa<SCEVAddRecExpr>(SAR.getStart()))6533return false;65346535const SCEV *Start = SAR.getStart();6536const SCEV *Stride = SAR.getStepRecurrence(SE);65376538// Skip pushing arithmetic noops.6539if (!isIdentityFunction(llvm::dwarf::DW_OP_mul, Stride)) {6540if (!pushSCEV(Stride))6541return false;6542pushOperator(llvm::dwarf::DW_OP_mul);6543}6544if (!isIdentityFunction(llvm::dwarf::DW_OP_plus, Start)) {6545if (!pushSCEV(Start))6546return false;6547pushOperator(llvm::dwarf::DW_OP_plus);6548}6549return true;6550}65516552/// Create an expression that is an offset from a value (usually the IV).6553void createOffsetExpr(int64_t Offset, Value *OffsetValue) {6554pushLocation(OffsetValue);6555DIExpression::appendOffset(Expr, Offset);6556LLVM_DEBUG(6557dbgs() << "scev-salvage: Generated IV offset expression. Offset: "6558<< std::to_string(Offset) << "\n");6559}65606561/// Combine a translation of the SCEV and the IV to create an expression that6562/// recovers a location's value.6563/// returns true if an expression was created.6564bool createIterCountExpr(const SCEV *S,6565const SCEVDbgValueBuilder &IterationCount,6566ScalarEvolution &SE) {6567// SCEVs for SSA values are most frquently of the form6568// {start,+,stride}, but sometimes they are ({start,+,stride} + %a + ..).6569// This is because %a is a PHI node that is not the IV. However, these6570// SCEVs have not been observed to result in debuginfo-lossy optimisations,6571// so its not expected this point will be reached.6572if (!isa<SCEVAddRecExpr>(S))6573return false;65746575LLVM_DEBUG(dbgs() << "scev-salvage: Location to salvage SCEV: " << *S6576<< '\n');65776578const auto *Rec = cast<SCEVAddRecExpr>(S);6579if (!Rec->isAffine())6580return false;65816582if (S->getExpressionSize() > MaxSCEVSalvageExpressionSize)6583return false;65846585// Initialise a new builder with the iteration count expression. In6586// combination with the value's SCEV this enables recovery.6587clone(IterationCount);6588if (!SCEVToValueExpr(*Rec, SE))6589return false;65906591return true;6592}65936594/// Convert a SCEV of a value to a DIExpression that is pushed onto the6595/// builder's expression stack. The stack should already contain an6596/// expression for the iteration count, so that it can be multiplied by6597/// the stride and added to the start.6598/// Components of the expression are omitted if they are an identity function.6599bool SCEVToIterCountExpr(const llvm::SCEVAddRecExpr &SAR,6600ScalarEvolution &SE) {6601assert(SAR.isAffine() && "Expected affine SCEV");6602if (isa<SCEVAddRecExpr>(SAR.getStart())) {6603LLVM_DEBUG(dbgs() << "scev-salvage: IV SCEV. Unsupported nested AddRec: "6604<< SAR << '\n');6605return false;6606}6607const SCEV *Start = SAR.getStart();6608const SCEV *Stride = SAR.getStepRecurrence(SE);66096610// Skip pushing arithmetic noops.6611if (!isIdentityFunction(llvm::dwarf::DW_OP_minus, Start)) {6612if (!pushSCEV(Start))6613return false;6614pushOperator(llvm::dwarf::DW_OP_minus);6615}6616if (!isIdentityFunction(llvm::dwarf::DW_OP_div, Stride)) {6617if (!pushSCEV(Stride))6618return false;6619pushOperator(llvm::dwarf::DW_OP_div);6620}6621return true;6622}66236624// Append the current expression and locations to a location list and an6625// expression list. Modify the DW_OP_LLVM_arg indexes to account for6626// the locations already present in the destination list.6627void appendToVectors(SmallVectorImpl<uint64_t> &DestExpr,6628SmallVectorImpl<Value *> &DestLocations) {6629assert(!DestLocations.empty() &&6630"Expected the locations vector to contain the IV");6631// The DWARF_OP_LLVM_arg arguments of the expression being appended must be6632// modified to account for the locations already in the destination vector.6633// All builders contain the IV as the first location op.6634assert(!LocationOps.empty() &&6635"Expected the location ops to contain the IV.");6636// DestIndexMap[n] contains the index in DestLocations for the nth6637// location in this SCEVDbgValueBuilder.6638SmallVector<uint64_t, 2> DestIndexMap;6639for (const auto &Op : LocationOps) {6640auto It = find(DestLocations, Op);6641if (It != DestLocations.end()) {6642// Location already exists in DestLocations, reuse existing ArgIndex.6643DestIndexMap.push_back(std::distance(DestLocations.begin(), It));6644continue;6645}6646// Location is not in DestLocations, add it.6647DestIndexMap.push_back(DestLocations.size());6648DestLocations.push_back(Op);6649}66506651for (const auto &Op : expr_ops()) {6652if (Op.getOp() != dwarf::DW_OP_LLVM_arg) {6653Op.appendToVector(DestExpr);6654continue;6655}66566657DestExpr.push_back(dwarf::DW_OP_LLVM_arg);6658// `DW_OP_LLVM_arg n` represents the nth LocationOp in this SCEV,6659// DestIndexMap[n] contains its new index in DestLocations.6660uint64_t NewIndex = DestIndexMap[Op.getArg(0)];6661DestExpr.push_back(NewIndex);6662}6663}6664};66656666/// Holds all the required data to salvage a dbg.value using the pre-LSR SCEVs6667/// and DIExpression.6668struct DVIRecoveryRec {6669DVIRecoveryRec(DbgValueInst *DbgValue)6670: DbgRef(DbgValue), Expr(DbgValue->getExpression()),6671HadLocationArgList(false) {}6672DVIRecoveryRec(DbgVariableRecord *DVR)6673: DbgRef(DVR), Expr(DVR->getExpression()), HadLocationArgList(false) {}66746675PointerUnion<DbgValueInst *, DbgVariableRecord *> DbgRef;6676DIExpression *Expr;6677bool HadLocationArgList;6678SmallVector<WeakVH, 2> LocationOps;6679SmallVector<const llvm::SCEV *, 2> SCEVs;6680SmallVector<std::unique_ptr<SCEVDbgValueBuilder>, 2> RecoveryExprs;66816682void clear() {6683for (auto &RE : RecoveryExprs)6684RE.reset();6685RecoveryExprs.clear();6686}66876688~DVIRecoveryRec() { clear(); }6689};6690} // namespace66916692/// Returns the total number of DW_OP_llvm_arg operands in the expression.6693/// This helps in determining if a DIArglist is necessary or can be omitted from6694/// the dbg.value.6695static unsigned numLLVMArgOps(SmallVectorImpl<uint64_t> &Expr) {6696auto expr_ops = ToDwarfOpIter(Expr);6697unsigned Count = 0;6698for (auto Op : expr_ops)6699if (Op.getOp() == dwarf::DW_OP_LLVM_arg)6700Count++;6701return Count;6702}67036704/// Overwrites DVI with the location and Ops as the DIExpression. This will6705/// create an invalid expression if Ops has any dwarf::DW_OP_llvm_arg operands,6706/// because a DIArglist is not created for the first argument of the dbg.value.6707template <typename T>6708static void updateDVIWithLocation(T &DbgVal, Value *Location,6709SmallVectorImpl<uint64_t> &Ops) {6710assert(numLLVMArgOps(Ops) == 0 && "Expected expression that does not "6711"contain any DW_OP_llvm_arg operands.");6712DbgVal.setRawLocation(ValueAsMetadata::get(Location));6713DbgVal.setExpression(DIExpression::get(DbgVal.getContext(), Ops));6714DbgVal.setExpression(DIExpression::get(DbgVal.getContext(), Ops));6715}67166717/// Overwrite DVI with locations placed into a DIArglist.6718template <typename T>6719static void updateDVIWithLocations(T &DbgVal,6720SmallVectorImpl<Value *> &Locations,6721SmallVectorImpl<uint64_t> &Ops) {6722assert(numLLVMArgOps(Ops) != 0 &&6723"Expected expression that references DIArglist locations using "6724"DW_OP_llvm_arg operands.");6725SmallVector<ValueAsMetadata *, 3> MetadataLocs;6726for (Value *V : Locations)6727MetadataLocs.push_back(ValueAsMetadata::get(V));6728auto ValArrayRef = llvm::ArrayRef<llvm::ValueAsMetadata *>(MetadataLocs);6729DbgVal.setRawLocation(llvm::DIArgList::get(DbgVal.getContext(), ValArrayRef));6730DbgVal.setExpression(DIExpression::get(DbgVal.getContext(), Ops));6731}67326733/// Write the new expression and new location ops for the dbg.value. If possible6734/// reduce the szie of the dbg.value intrinsic by omitting DIArglist. This6735/// can be omitted if:6736/// 1. There is only a single location, refenced by a single DW_OP_llvm_arg.6737/// 2. The DW_OP_LLVM_arg is the first operand in the expression.6738static void UpdateDbgValueInst(DVIRecoveryRec &DVIRec,6739SmallVectorImpl<Value *> &NewLocationOps,6740SmallVectorImpl<uint64_t> &NewExpr) {6741auto UpdateDbgValueInstImpl = [&](auto *DbgVal) {6742unsigned NumLLVMArgs = numLLVMArgOps(NewExpr);6743if (NumLLVMArgs == 0) {6744// Location assumed to be on the stack.6745updateDVIWithLocation(*DbgVal, NewLocationOps[0], NewExpr);6746} else if (NumLLVMArgs == 1 && NewExpr[0] == dwarf::DW_OP_LLVM_arg) {6747// There is only a single DW_OP_llvm_arg at the start of the expression,6748// so it can be omitted along with DIArglist.6749assert(NewExpr[1] == 0 &&6750"Lone LLVM_arg in a DIExpression should refer to location-op 0.");6751llvm::SmallVector<uint64_t, 6> ShortenedOps(llvm::drop_begin(NewExpr, 2));6752updateDVIWithLocation(*DbgVal, NewLocationOps[0], ShortenedOps);6753} else {6754// Multiple DW_OP_llvm_arg, so DIArgList is strictly necessary.6755updateDVIWithLocations(*DbgVal, NewLocationOps, NewExpr);6756}67576758// If the DIExpression was previously empty then add the stack terminator.6759// Non-empty expressions have only had elements inserted into them and so6760// the terminator should already be present e.g. stack_value or fragment.6761DIExpression *SalvageExpr = DbgVal->getExpression();6762if (!DVIRec.Expr->isComplex() && SalvageExpr->isComplex()) {6763SalvageExpr =6764DIExpression::append(SalvageExpr, {dwarf::DW_OP_stack_value});6765DbgVal->setExpression(SalvageExpr);6766}6767};6768if (isa<DbgValueInst *>(DVIRec.DbgRef))6769UpdateDbgValueInstImpl(cast<DbgValueInst *>(DVIRec.DbgRef));6770else6771UpdateDbgValueInstImpl(cast<DbgVariableRecord *>(DVIRec.DbgRef));6772}67736774/// Cached location ops may be erased during LSR, in which case a poison is6775/// required when restoring from the cache. The type of that location is no6776/// longer available, so just use int8. The poison will be replaced by one or6777/// more locations later when a SCEVDbgValueBuilder selects alternative6778/// locations to use for the salvage.6779static Value *getValueOrPoison(WeakVH &VH, LLVMContext &C) {6780return (VH) ? VH : PoisonValue::get(llvm::Type::getInt8Ty(C));6781}67826783/// Restore the DVI's pre-LSR arguments. Substitute undef for any erased values.6784static void restorePreTransformState(DVIRecoveryRec &DVIRec) {6785auto RestorePreTransformStateImpl = [&](auto *DbgVal) {6786LLVM_DEBUG(dbgs() << "scev-salvage: restore dbg.value to pre-LSR state\n"6787<< "scev-salvage: post-LSR: " << *DbgVal << '\n');6788assert(DVIRec.Expr && "Expected an expression");6789DbgVal->setExpression(DVIRec.Expr);67906791// Even a single location-op may be inside a DIArgList and referenced with6792// DW_OP_LLVM_arg, which is valid only with a DIArgList.6793if (!DVIRec.HadLocationArgList) {6794assert(DVIRec.LocationOps.size() == 1 &&6795"Unexpected number of location ops.");6796// LSR's unsuccessful salvage attempt may have added DIArgList, which in6797// this case was not present before, so force the location back to a6798// single uncontained Value.6799Value *CachedValue =6800getValueOrPoison(DVIRec.LocationOps[0], DbgVal->getContext());6801DbgVal->setRawLocation(ValueAsMetadata::get(CachedValue));6802} else {6803SmallVector<ValueAsMetadata *, 3> MetadataLocs;6804for (WeakVH VH : DVIRec.LocationOps) {6805Value *CachedValue = getValueOrPoison(VH, DbgVal->getContext());6806MetadataLocs.push_back(ValueAsMetadata::get(CachedValue));6807}6808auto ValArrayRef = llvm::ArrayRef<llvm::ValueAsMetadata *>(MetadataLocs);6809DbgVal->setRawLocation(6810llvm::DIArgList::get(DbgVal->getContext(), ValArrayRef));6811}6812LLVM_DEBUG(dbgs() << "scev-salvage: pre-LSR: " << *DbgVal << '\n');6813};6814if (isa<DbgValueInst *>(DVIRec.DbgRef))6815RestorePreTransformStateImpl(cast<DbgValueInst *>(DVIRec.DbgRef));6816else6817RestorePreTransformStateImpl(cast<DbgVariableRecord *>(DVIRec.DbgRef));6818}68196820static bool SalvageDVI(llvm::Loop *L, ScalarEvolution &SE,6821llvm::PHINode *LSRInductionVar, DVIRecoveryRec &DVIRec,6822const SCEV *SCEVInductionVar,6823SCEVDbgValueBuilder IterCountExpr) {68246825if (isa<DbgValueInst *>(DVIRec.DbgRef)6826? !cast<DbgValueInst *>(DVIRec.DbgRef)->isKillLocation()6827: !cast<DbgVariableRecord *>(DVIRec.DbgRef)->isKillLocation())6828return false;68296830// LSR may have caused several changes to the dbg.value in the failed salvage6831// attempt. So restore the DIExpression, the location ops and also the6832// location ops format, which is always DIArglist for multiple ops, but only6833// sometimes for a single op.6834restorePreTransformState(DVIRec);68356836// LocationOpIndexMap[i] will store the post-LSR location index of6837// the non-optimised out location at pre-LSR index i.6838SmallVector<int64_t, 2> LocationOpIndexMap;6839LocationOpIndexMap.assign(DVIRec.LocationOps.size(), -1);6840SmallVector<Value *, 2> NewLocationOps;6841NewLocationOps.push_back(LSRInductionVar);68426843for (unsigned i = 0; i < DVIRec.LocationOps.size(); i++) {6844WeakVH VH = DVIRec.LocationOps[i];6845// Place the locations not optimised out in the list first, avoiding6846// inserts later. The map is used to update the DIExpression's6847// DW_OP_LLVM_arg arguments as the expression is updated.6848if (VH && !isa<UndefValue>(VH)) {6849NewLocationOps.push_back(VH);6850LocationOpIndexMap[i] = NewLocationOps.size() - 1;6851LLVM_DEBUG(dbgs() << "scev-salvage: Location index " << i6852<< " now at index " << LocationOpIndexMap[i] << "\n");6853continue;6854}68556856// It's possible that a value referred to in the SCEV may have been6857// optimised out by LSR.6858if (SE.containsErasedValue(DVIRec.SCEVs[i]) ||6859SE.containsUndefs(DVIRec.SCEVs[i])) {6860LLVM_DEBUG(dbgs() << "scev-salvage: SCEV for location at index: " << i6861<< " refers to a location that is now undef or erased. "6862"Salvage abandoned.\n");6863return false;6864}68656866LLVM_DEBUG(dbgs() << "scev-salvage: salvaging location at index " << i6867<< " with SCEV: " << *DVIRec.SCEVs[i] << "\n");68686869DVIRec.RecoveryExprs[i] = std::make_unique<SCEVDbgValueBuilder>();6870SCEVDbgValueBuilder *SalvageExpr = DVIRec.RecoveryExprs[i].get();68716872// Create an offset-based salvage expression if possible, as it requires6873// less DWARF ops than an iteration count-based expression.6874if (std::optional<APInt> Offset =6875SE.computeConstantDifference(DVIRec.SCEVs[i], SCEVInductionVar)) {6876if (Offset->getSignificantBits() <= 64)6877SalvageExpr->createOffsetExpr(Offset->getSExtValue(), LSRInductionVar);6878} else if (!SalvageExpr->createIterCountExpr(DVIRec.SCEVs[i], IterCountExpr,6879SE))6880return false;6881}68826883// Merge the DbgValueBuilder generated expressions and the original6884// DIExpression, place the result into an new vector.6885SmallVector<uint64_t, 3> NewExpr;6886if (DVIRec.Expr->getNumElements() == 0) {6887assert(DVIRec.RecoveryExprs.size() == 1 &&6888"Expected only a single recovery expression for an empty "6889"DIExpression.");6890assert(DVIRec.RecoveryExprs[0] &&6891"Expected a SCEVDbgSalvageBuilder for location 0");6892SCEVDbgValueBuilder *B = DVIRec.RecoveryExprs[0].get();6893B->appendToVectors(NewExpr, NewLocationOps);6894}6895for (const auto &Op : DVIRec.Expr->expr_ops()) {6896// Most Ops needn't be updated.6897if (Op.getOp() != dwarf::DW_OP_LLVM_arg) {6898Op.appendToVector(NewExpr);6899continue;6900}69016902uint64_t LocationArgIndex = Op.getArg(0);6903SCEVDbgValueBuilder *DbgBuilder =6904DVIRec.RecoveryExprs[LocationArgIndex].get();6905// The location doesn't have s SCEVDbgValueBuilder, so LSR did not6906// optimise it away. So just translate the argument to the updated6907// location index.6908if (!DbgBuilder) {6909NewExpr.push_back(dwarf::DW_OP_LLVM_arg);6910assert(LocationOpIndexMap[Op.getArg(0)] != -1 &&6911"Expected a positive index for the location-op position.");6912NewExpr.push_back(LocationOpIndexMap[Op.getArg(0)]);6913continue;6914}6915// The location has a recovery expression.6916DbgBuilder->appendToVectors(NewExpr, NewLocationOps);6917}69186919UpdateDbgValueInst(DVIRec, NewLocationOps, NewExpr);6920if (isa<DbgValueInst *>(DVIRec.DbgRef))6921LLVM_DEBUG(dbgs() << "scev-salvage: Updated DVI: "6922<< *cast<DbgValueInst *>(DVIRec.DbgRef) << "\n");6923else6924LLVM_DEBUG(dbgs() << "scev-salvage: Updated DVI: "6925<< *cast<DbgVariableRecord *>(DVIRec.DbgRef) << "\n");6926return true;6927}69286929/// Obtain an expression for the iteration count, then attempt to salvage the6930/// dbg.value intrinsics.6931static void DbgRewriteSalvageableDVIs(6932llvm::Loop *L, ScalarEvolution &SE, llvm::PHINode *LSRInductionVar,6933SmallVector<std::unique_ptr<DVIRecoveryRec>, 2> &DVIToUpdate) {6934if (DVIToUpdate.empty())6935return;69366937const llvm::SCEV *SCEVInductionVar = SE.getSCEV(LSRInductionVar);6938assert(SCEVInductionVar &&6939"Anticipated a SCEV for the post-LSR induction variable");69406941if (const SCEVAddRecExpr *IVAddRec =6942dyn_cast<SCEVAddRecExpr>(SCEVInductionVar)) {6943if (!IVAddRec->isAffine())6944return;69456946// Prevent translation using excessive resources.6947if (IVAddRec->getExpressionSize() > MaxSCEVSalvageExpressionSize)6948return;69496950// The iteration count is required to recover location values.6951SCEVDbgValueBuilder IterCountExpr;6952IterCountExpr.pushLocation(LSRInductionVar);6953if (!IterCountExpr.SCEVToIterCountExpr(*IVAddRec, SE))6954return;69556956LLVM_DEBUG(dbgs() << "scev-salvage: IV SCEV: " << *SCEVInductionVar6957<< '\n');69586959for (auto &DVIRec : DVIToUpdate) {6960SalvageDVI(L, SE, LSRInductionVar, *DVIRec, SCEVInductionVar,6961IterCountExpr);6962}6963}6964}69656966/// Identify and cache salvageable DVI locations and expressions along with the6967/// corresponding SCEV(s). Also ensure that the DVI is not deleted between6968/// cacheing and salvaging.6969static void DbgGatherSalvagableDVI(6970Loop *L, ScalarEvolution &SE,6971SmallVector<std::unique_ptr<DVIRecoveryRec>, 2> &SalvageableDVISCEVs,6972SmallSet<AssertingVH<DbgValueInst>, 2> &DVIHandles) {6973for (const auto &B : L->getBlocks()) {6974for (auto &I : *B) {6975auto ProcessDbgValue = [&](auto *DbgVal) -> bool {6976// Ensure that if any location op is undef that the dbg.vlue is not6977// cached.6978if (DbgVal->isKillLocation())6979return false;69806981// Check that the location op SCEVs are suitable for translation to6982// DIExpression.6983const auto &HasTranslatableLocationOps =6984[&](const auto *DbgValToTranslate) -> bool {6985for (const auto LocOp : DbgValToTranslate->location_ops()) {6986if (!LocOp)6987return false;69886989if (!SE.isSCEVable(LocOp->getType()))6990return false;69916992const SCEV *S = SE.getSCEV(LocOp);6993if (SE.containsUndefs(S))6994return false;6995}6996return true;6997};69986999if (!HasTranslatableLocationOps(DbgVal))7000return false;70017002std::unique_ptr<DVIRecoveryRec> NewRec =7003std::make_unique<DVIRecoveryRec>(DbgVal);7004// Each location Op may need a SCEVDbgValueBuilder in order to recover7005// it. Pre-allocating a vector will enable quick lookups of the builder7006// later during the salvage.7007NewRec->RecoveryExprs.resize(DbgVal->getNumVariableLocationOps());7008for (const auto LocOp : DbgVal->location_ops()) {7009NewRec->SCEVs.push_back(SE.getSCEV(LocOp));7010NewRec->LocationOps.push_back(LocOp);7011NewRec->HadLocationArgList = DbgVal->hasArgList();7012}7013SalvageableDVISCEVs.push_back(std::move(NewRec));7014return true;7015};7016for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {7017if (DVR.isDbgValue() || DVR.isDbgAssign())7018ProcessDbgValue(&DVR);7019}7020auto DVI = dyn_cast<DbgValueInst>(&I);7021if (!DVI)7022continue;7023if (ProcessDbgValue(DVI))7024DVIHandles.insert(DVI);7025}7026}7027}70287029/// Ideally pick the PHI IV inserted by ScalarEvolutionExpander. As a fallback7030/// any PHi from the loop header is usable, but may have less chance of7031/// surviving subsequent transforms.7032static llvm::PHINode *GetInductionVariable(const Loop &L, ScalarEvolution &SE,7033const LSRInstance &LSR) {70347035auto IsSuitableIV = [&](PHINode *P) {7036if (!SE.isSCEVable(P->getType()))7037return false;7038if (const SCEVAddRecExpr *Rec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(P)))7039return Rec->isAffine() && !SE.containsUndefs(SE.getSCEV(P));7040return false;7041};70427043// For now, just pick the first IV that was generated and inserted by7044// ScalarEvolution. Ideally pick an IV that is unlikely to be optimised away7045// by subsequent transforms.7046for (const WeakVH &IV : LSR.getScalarEvolutionIVs()) {7047if (!IV)7048continue;70497050// There should only be PHI node IVs.7051PHINode *P = cast<PHINode>(&*IV);70527053if (IsSuitableIV(P))7054return P;7055}70567057for (PHINode &P : L.getHeader()->phis()) {7058if (IsSuitableIV(&P))7059return &P;7060}7061return nullptr;7062}70637064static std::optional<std::tuple<PHINode *, PHINode *, const SCEV *, bool>>7065canFoldTermCondOfLoop(Loop *L, ScalarEvolution &SE, DominatorTree &DT,7066const LoopInfo &LI, const TargetTransformInfo &TTI) {7067if (!L->isInnermost()) {7068LLVM_DEBUG(dbgs() << "Cannot fold on non-innermost loop\n");7069return std::nullopt;7070}7071// Only inspect on simple loop structure7072if (!L->isLoopSimplifyForm()) {7073LLVM_DEBUG(dbgs() << "Cannot fold on non-simple loop\n");7074return std::nullopt;7075}70767077if (!SE.hasLoopInvariantBackedgeTakenCount(L)) {7078LLVM_DEBUG(dbgs() << "Cannot fold on backedge that is loop variant\n");7079return std::nullopt;7080}70817082BasicBlock *LoopLatch = L->getLoopLatch();7083BranchInst *BI = dyn_cast<BranchInst>(LoopLatch->getTerminator());7084if (!BI || BI->isUnconditional())7085return std::nullopt;7086auto *TermCond = dyn_cast<ICmpInst>(BI->getCondition());7087if (!TermCond) {7088LLVM_DEBUG(7089dbgs() << "Cannot fold on branching condition that is not an ICmpInst");7090return std::nullopt;7091}7092if (!TermCond->hasOneUse()) {7093LLVM_DEBUG(7094dbgs()7095<< "Cannot replace terminating condition with more than one use\n");7096return std::nullopt;7097}70987099BinaryOperator *LHS = dyn_cast<BinaryOperator>(TermCond->getOperand(0));7100Value *RHS = TermCond->getOperand(1);7101if (!LHS || !L->isLoopInvariant(RHS))7102// We could pattern match the inverse form of the icmp, but that is7103// non-canonical, and this pass is running *very* late in the pipeline.7104return std::nullopt;71057106// Find the IV used by the current exit condition.7107PHINode *ToFold;7108Value *ToFoldStart, *ToFoldStep;7109if (!matchSimpleRecurrence(LHS, ToFold, ToFoldStart, ToFoldStep))7110return std::nullopt;71117112// Ensure the simple recurrence is a part of the current loop.7113if (ToFold->getParent() != L->getHeader())7114return std::nullopt;71157116// If that IV isn't dead after we rewrite the exit condition in terms of7117// another IV, there's no point in doing the transform.7118if (!isAlmostDeadIV(ToFold, LoopLatch, TermCond))7119return std::nullopt;71207121// Inserting instructions in the preheader has a runtime cost, scale7122// the allowed cost with the loops trip count as best we can.7123const unsigned ExpansionBudget = [&]() {7124unsigned Budget = 2 * SCEVCheapExpansionBudget;7125if (unsigned SmallTC = SE.getSmallConstantMaxTripCount(L))7126return std::min(Budget, SmallTC);7127if (std::optional<unsigned> SmallTC = getLoopEstimatedTripCount(L))7128return std::min(Budget, *SmallTC);7129// Unknown trip count, assume long running by default.7130return Budget;7131}();71327133const SCEV *BECount = SE.getBackedgeTakenCount(L);7134const DataLayout &DL = L->getHeader()->getDataLayout();7135SCEVExpander Expander(SE, DL, "lsr_fold_term_cond");71367137PHINode *ToHelpFold = nullptr;7138const SCEV *TermValueS = nullptr;7139bool MustDropPoison = false;7140auto InsertPt = L->getLoopPreheader()->getTerminator();7141for (PHINode &PN : L->getHeader()->phis()) {7142if (ToFold == &PN)7143continue;71447145if (!SE.isSCEVable(PN.getType())) {7146LLVM_DEBUG(dbgs() << "IV of phi '" << PN7147<< "' is not SCEV-able, not qualified for the "7148"terminating condition folding.\n");7149continue;7150}7151const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(&PN));7152// Only speculate on affine AddRec7153if (!AddRec || !AddRec->isAffine()) {7154LLVM_DEBUG(dbgs() << "SCEV of phi '" << PN7155<< "' is not an affine add recursion, not qualified "7156"for the terminating condition folding.\n");7157continue;7158}71597160// Check that we can compute the value of AddRec on the exiting iteration7161// without soundness problems. evaluateAtIteration internally needs7162// to multiply the stride of the iteration number - which may wrap around.7163// The issue here is subtle because computing the result accounting for7164// wrap is insufficient. In order to use the result in an exit test, we7165// must also know that AddRec doesn't take the same value on any previous7166// iteration. The simplest case to consider is a candidate IV which is7167// narrower than the trip count (and thus original IV), but this can7168// also happen due to non-unit strides on the candidate IVs.7169if (!AddRec->hasNoSelfWrap() ||7170!SE.isKnownNonZero(AddRec->getStepRecurrence(SE)))7171continue;71727173const SCEVAddRecExpr *PostInc = AddRec->getPostIncExpr(SE);7174const SCEV *TermValueSLocal = PostInc->evaluateAtIteration(BECount, SE);7175if (!Expander.isSafeToExpand(TermValueSLocal)) {7176LLVM_DEBUG(7177dbgs() << "Is not safe to expand terminating value for phi node" << PN7178<< "\n");7179continue;7180}71817182if (Expander.isHighCostExpansion(TermValueSLocal, L, ExpansionBudget,7183&TTI, InsertPt)) {7184LLVM_DEBUG(7185dbgs() << "Is too expensive to expand terminating value for phi node"7186<< PN << "\n");7187continue;7188}71897190// The candidate IV may have been otherwise dead and poison from the7191// very first iteration. If we can't disprove that, we can't use the IV.7192if (!mustExecuteUBIfPoisonOnPathTo(&PN, LoopLatch->getTerminator(), &DT)) {7193LLVM_DEBUG(dbgs() << "Can not prove poison safety for IV "7194<< PN << "\n");7195continue;7196}71977198// The candidate IV may become poison on the last iteration. If this7199// value is not branched on, this is a well defined program. We're7200// about to add a new use to this IV, and we have to ensure we don't7201// insert UB which didn't previously exist.7202bool MustDropPoisonLocal = false;7203Instruction *PostIncV =7204cast<Instruction>(PN.getIncomingValueForBlock(LoopLatch));7205if (!mustExecuteUBIfPoisonOnPathTo(PostIncV, LoopLatch->getTerminator(),7206&DT)) {7207LLVM_DEBUG(dbgs() << "Can not prove poison safety to insert use"7208<< PN << "\n");72097210// If this is a complex recurrance with multiple instructions computing7211// the backedge value, we might need to strip poison flags from all of7212// them.7213if (PostIncV->getOperand(0) != &PN)7214continue;72157216// In order to perform the transform, we need to drop the poison generating7217// flags on this instruction (if any).7218MustDropPoisonLocal = PostIncV->hasPoisonGeneratingFlags();7219}72207221// We pick the last legal alternate IV. We could expore choosing an optimal7222// alternate IV if we had a decent heuristic to do so.7223ToHelpFold = &PN;7224TermValueS = TermValueSLocal;7225MustDropPoison = MustDropPoisonLocal;7226}72277228LLVM_DEBUG(if (ToFold && !ToHelpFold) dbgs()7229<< "Cannot find other AddRec IV to help folding\n";);72307231LLVM_DEBUG(if (ToFold && ToHelpFold) dbgs()7232<< "\nFound loop that can fold terminating condition\n"7233<< " BECount (SCEV): " << *SE.getBackedgeTakenCount(L) << "\n"7234<< " TermCond: " << *TermCond << "\n"7235<< " BrandInst: " << *BI << "\n"7236<< " ToFold: " << *ToFold << "\n"7237<< " ToHelpFold: " << *ToHelpFold << "\n");72387239if (!ToFold || !ToHelpFold)7240return std::nullopt;7241return std::make_tuple(ToFold, ToHelpFold, TermValueS, MustDropPoison);7242}72437244static bool ReduceLoopStrength(Loop *L, IVUsers &IU, ScalarEvolution &SE,7245DominatorTree &DT, LoopInfo &LI,7246const TargetTransformInfo &TTI,7247AssumptionCache &AC, TargetLibraryInfo &TLI,7248MemorySSA *MSSA) {72497250// Debug preservation - before we start removing anything identify which DVI7251// meet the salvageable criteria and store their DIExpression and SCEVs.7252SmallVector<std::unique_ptr<DVIRecoveryRec>, 2> SalvageableDVIRecords;7253SmallSet<AssertingVH<DbgValueInst>, 2> DVIHandles;7254DbgGatherSalvagableDVI(L, SE, SalvageableDVIRecords, DVIHandles);72557256bool Changed = false;7257std::unique_ptr<MemorySSAUpdater> MSSAU;7258if (MSSA)7259MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);72607261// Run the main LSR transformation.7262const LSRInstance &Reducer =7263LSRInstance(L, IU, SE, DT, LI, TTI, AC, TLI, MSSAU.get());7264Changed |= Reducer.getChanged();72657266// Remove any extra phis created by processing inner loops.7267Changed |= DeleteDeadPHIs(L->getHeader(), &TLI, MSSAU.get());7268if (EnablePhiElim && L->isLoopSimplifyForm()) {7269SmallVector<WeakTrackingVH, 16> DeadInsts;7270const DataLayout &DL = L->getHeader()->getDataLayout();7271SCEVExpander Rewriter(SE, DL, "lsr", false);7272#ifndef NDEBUG7273Rewriter.setDebugType(DEBUG_TYPE);7274#endif7275unsigned numFolded = Rewriter.replaceCongruentIVs(L, &DT, DeadInsts, &TTI);7276Rewriter.clear();7277if (numFolded) {7278Changed = true;7279RecursivelyDeleteTriviallyDeadInstructionsPermissive(DeadInsts, &TLI,7280MSSAU.get());7281DeleteDeadPHIs(L->getHeader(), &TLI, MSSAU.get());7282}7283}7284// LSR may at times remove all uses of an induction variable from a loop.7285// The only remaining use is the PHI in the exit block.7286// When this is the case, if the exit value of the IV can be calculated using7287// SCEV, we can replace the exit block PHI with the final value of the IV and7288// skip the updates in each loop iteration.7289if (L->isRecursivelyLCSSAForm(DT, LI) && L->getExitBlock()) {7290SmallVector<WeakTrackingVH, 16> DeadInsts;7291const DataLayout &DL = L->getHeader()->getDataLayout();7292SCEVExpander Rewriter(SE, DL, "lsr", true);7293int Rewrites = rewriteLoopExitValues(L, &LI, &TLI, &SE, &TTI, Rewriter, &DT,7294UnusedIndVarInLoop, DeadInsts);7295Rewriter.clear();7296if (Rewrites) {7297Changed = true;7298RecursivelyDeleteTriviallyDeadInstructionsPermissive(DeadInsts, &TLI,7299MSSAU.get());7300DeleteDeadPHIs(L->getHeader(), &TLI, MSSAU.get());7301}7302}73037304const bool EnableFormTerm = [&] {7305switch (AllowTerminatingConditionFoldingAfterLSR) {7306case cl::BOU_TRUE:7307return true;7308case cl::BOU_FALSE:7309return false;7310case cl::BOU_UNSET:7311return TTI.shouldFoldTerminatingConditionAfterLSR();7312}7313llvm_unreachable("Unhandled cl::boolOrDefault enum");7314}();73157316if (EnableFormTerm) {7317if (auto Opt = canFoldTermCondOfLoop(L, SE, DT, LI, TTI)) {7318auto [ToFold, ToHelpFold, TermValueS, MustDrop] = *Opt;73197320Changed = true;7321NumTermFold++;73227323BasicBlock *LoopPreheader = L->getLoopPreheader();7324BasicBlock *LoopLatch = L->getLoopLatch();73257326(void)ToFold;7327LLVM_DEBUG(dbgs() << "To fold phi-node:\n"7328<< *ToFold << "\n"7329<< "New term-cond phi-node:\n"7330<< *ToHelpFold << "\n");73317332Value *StartValue = ToHelpFold->getIncomingValueForBlock(LoopPreheader);7333(void)StartValue;7334Value *LoopValue = ToHelpFold->getIncomingValueForBlock(LoopLatch);73357336// See comment in canFoldTermCondOfLoop on why this is sufficient.7337if (MustDrop)7338cast<Instruction>(LoopValue)->dropPoisonGeneratingFlags();73397340// SCEVExpander for both use in preheader and latch7341const DataLayout &DL = L->getHeader()->getDataLayout();7342SCEVExpander Expander(SE, DL, "lsr_fold_term_cond");73437344assert(Expander.isSafeToExpand(TermValueS) &&7345"Terminating value was checked safe in canFoldTerminatingCondition");73467347// Create new terminating value at loop preheader7348Value *TermValue = Expander.expandCodeFor(TermValueS, ToHelpFold->getType(),7349LoopPreheader->getTerminator());73507351LLVM_DEBUG(dbgs() << "Start value of new term-cond phi-node:\n"7352<< *StartValue << "\n"7353<< "Terminating value of new term-cond phi-node:\n"7354<< *TermValue << "\n");73557356// Create new terminating condition at loop latch7357BranchInst *BI = cast<BranchInst>(LoopLatch->getTerminator());7358ICmpInst *OldTermCond = cast<ICmpInst>(BI->getCondition());7359IRBuilder<> LatchBuilder(LoopLatch->getTerminator());7360Value *NewTermCond =7361LatchBuilder.CreateICmp(CmpInst::ICMP_EQ, LoopValue, TermValue,7362"lsr_fold_term_cond.replaced_term_cond");7363// Swap successors to exit loop body if IV equals to new TermValue7364if (BI->getSuccessor(0) == L->getHeader())7365BI->swapSuccessors();73667367LLVM_DEBUG(dbgs() << "Old term-cond:\n"7368<< *OldTermCond << "\n"7369<< "New term-cond:\n" << *NewTermCond << "\n");73707371BI->setCondition(NewTermCond);73727373Expander.clear();7374OldTermCond->eraseFromParent();7375DeleteDeadPHIs(L->getHeader(), &TLI, MSSAU.get());7376}7377}73787379if (SalvageableDVIRecords.empty())7380return Changed;73817382// Obtain relevant IVs and attempt to rewrite the salvageable DVIs with7383// expressions composed using the derived iteration count.7384// TODO: Allow for multiple IV references for nested AddRecSCEVs7385for (const auto &L : LI) {7386if (llvm::PHINode *IV = GetInductionVariable(*L, SE, Reducer))7387DbgRewriteSalvageableDVIs(L, SE, IV, SalvageableDVIRecords);7388else {7389LLVM_DEBUG(dbgs() << "scev-salvage: SCEV salvaging not possible. An IV "7390"could not be identified.\n");7391}7392}73937394for (auto &Rec : SalvageableDVIRecords)7395Rec->clear();7396SalvageableDVIRecords.clear();7397DVIHandles.clear();7398return Changed;7399}74007401bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager & /*LPM*/) {7402if (skipLoop(L))7403return false;74047405auto &IU = getAnalysis<IVUsersWrapperPass>().getIU();7406auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();7407auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();7408auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();7409const auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(7410*L->getHeader()->getParent());7411auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(7412*L->getHeader()->getParent());7413auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(7414*L->getHeader()->getParent());7415auto *MSSAAnalysis = getAnalysisIfAvailable<MemorySSAWrapperPass>();7416MemorySSA *MSSA = nullptr;7417if (MSSAAnalysis)7418MSSA = &MSSAAnalysis->getMSSA();7419return ReduceLoopStrength(L, IU, SE, DT, LI, TTI, AC, TLI, MSSA);7420}74217422PreservedAnalyses LoopStrengthReducePass::run(Loop &L, LoopAnalysisManager &AM,7423LoopStandardAnalysisResults &AR,7424LPMUpdater &) {7425if (!ReduceLoopStrength(&L, AM.getResult<IVUsersAnalysis>(L, AR), AR.SE,7426AR.DT, AR.LI, AR.TTI, AR.AC, AR.TLI, AR.MSSA))7427return PreservedAnalyses::all();74287429auto PA = getLoopPassPreservedAnalyses();7430if (AR.MSSA)7431PA.preserve<MemorySSAAnalysis>();7432return PA;7433}74347435char LoopStrengthReduce::ID = 0;74367437INITIALIZE_PASS_BEGIN(LoopStrengthReduce, "loop-reduce",7438"Loop Strength Reduction", false, false)7439INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)7440INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)7441INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)7442INITIALIZE_PASS_DEPENDENCY(IVUsersWrapperPass)7443INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)7444INITIALIZE_PASS_DEPENDENCY(LoopSimplify)7445INITIALIZE_PASS_END(LoopStrengthReduce, "loop-reduce",7446"Loop Strength Reduction", false, false)74477448Pass *llvm::createLoopStrengthReducePass() { return new LoopStrengthReduce(); }744974507451