Skip to content

Commit ceec695

Browse files
committed
[LV] Teach the vectorizer to cost and vectorize llvm.sincos intrinsics
This teaches the loop vectorizer that `llvm.sincos` is trivially vectorizable. Additionally, this patch updates the cost model to cost intrinsics that return multiple values correctly. Previously, the cost model only thought intrinsics that return `VectorType` need scalarizing, which meant it cost intrinsics that return multiple vectors (that need scalarizing) way too cheap (giving it the cost of a single function call). The `llvm.sincos` intrinsic also has a custom cost when a vector function library is available, as certain VFs can be expanded (later in code-gen) to a vector function, reducing the cost to a single call (+ the possible loads from the vector function returns values via output pointers).
1 parent 69945a0 commit ceec695

File tree

12 files changed

+640
-64
lines changed

12 files changed

+640
-64
lines changed

llvm/include/llvm/Analysis/TargetTransformInfo.h

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -126,12 +126,13 @@ class IntrinsicCostAttributes {
126126
// If ScalarizationCost is UINT_MAX, the cost of scalarizing the
127127
// arguments and the return value will be computed based on types.
128128
InstructionCost ScalarizationCost = InstructionCost::getInvalid();
129+
TargetLibraryInfo const *LibInfo = nullptr;
129130

130131
public:
131132
IntrinsicCostAttributes(
132133
Intrinsic::ID Id, const CallBase &CI,
133134
InstructionCost ScalarCost = InstructionCost::getInvalid(),
134-
bool TypeBasedOnly = false);
135+
bool TypeBasedOnly = false, TargetLibraryInfo const *LibInfo = nullptr);
135136

136137
IntrinsicCostAttributes(
137138
Intrinsic::ID Id, Type *RTy, ArrayRef<Type *> Tys,
@@ -145,7 +146,8 @@ class IntrinsicCostAttributes {
145146
Intrinsic::ID Id, Type *RTy, ArrayRef<const Value *> Args,
146147
ArrayRef<Type *> Tys, FastMathFlags Flags = FastMathFlags(),
147148
const IntrinsicInst *I = nullptr,
148-
InstructionCost ScalarCost = InstructionCost::getInvalid());
149+
InstructionCost ScalarCost = InstructionCost::getInvalid(),
150+
TargetLibraryInfo const *LibInfo = nullptr);
149151

150152
Intrinsic::ID getID() const { return IID; }
151153
const IntrinsicInst *getInst() const { return II; }
@@ -154,6 +156,7 @@ class IntrinsicCostAttributes {
154156
InstructionCost getScalarizationCost() const { return ScalarizationCost; }
155157
const SmallVectorImpl<const Value *> &getArgs() const { return Arguments; }
156158
const SmallVectorImpl<Type *> &getArgTypes() const { return ParamTys; }
159+
const TargetLibraryInfo *getLibInfo() const { return LibInfo; }
157160

158161
bool isTypeBasedOnly() const {
159162
return Arguments.empty();

llvm/include/llvm/CodeGen/BasicTTIImpl.h

Lines changed: 95 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
#include "llvm/ADT/SmallVector.h"
2323
#include "llvm/Analysis/LoopInfo.h"
2424
#include "llvm/Analysis/OptimizationRemarkEmitter.h"
25+
#include "llvm/Analysis/TargetLibraryInfo.h"
2526
#include "llvm/Analysis/TargetTransformInfo.h"
2627
#include "llvm/Analysis/TargetTransformInfoImpl.h"
2728
#include "llvm/Analysis/ValueTracking.h"
@@ -285,6 +286,64 @@ class BasicTTIImplBase : public TargetTransformInfoImplCRTPBase<T> {
285286
return false;
286287
}
287288

289+
/// Several intrinsics that return structs (including llvm.sincos[pi] and
290+
/// llvm.modf) can be lowered to a vector library call (for certain VFs). The
291+
/// vector library functions correspond to the scalar calls (e.g. sincos or
292+
/// modf), which unlike the intrinsic return values via output pointers. This
293+
/// helper checks if a vector call exists for the given intrinsic, and returns
294+
/// the cost, which includes the cost of the mask (if required), and the loads
295+
/// for values returned via output pointers. \p LC is the scalar libcall and
296+
/// \p CallRetElementIndex (optional) is the struct element which is mapped to
297+
/// the call return value. If std::nullopt is returned, then no vector library
298+
/// call is available, so the intrinsic should be assigned the default cost
299+
/// (e.g. scalarization).
300+
std::optional<InstructionCost> getMultipleResultIntrinsicVectorLibCallCost(
301+
const IntrinsicCostAttributes &ICA, TTI::TargetCostKind CostKind,
302+
RTLIB::Libcall LC, std::optional<unsigned> CallRetElementIndex = {}) {
303+
Type *RetTy = ICA.getReturnType();
304+
// Vector variants of the intrinsic can be mapped to a vector library call.
305+
auto const *LibInfo = ICA.getLibInfo();
306+
if (!LibInfo || !isa<StructType>(RetTy) ||
307+
!isVectorizedStructTy(cast<StructType>(RetTy)))
308+
return std::nullopt;
309+
310+
// Find associated libcall.
311+
const char *LCName = getTLI()->getLibcallName(LC);
312+
if (!LCName)
313+
return std::nullopt;
314+
315+
// Search for a corresponding vector variant.
316+
LLVMContext &Ctx = RetTy->getContext();
317+
ElementCount VF = getVectorizedTypeVF(RetTy);
318+
VecDesc const *VD = nullptr;
319+
for (bool Masked : {false, true}) {
320+
if ((VD = LibInfo->getVectorMappingInfo(LCName, VF, Masked)))
321+
break;
322+
}
323+
if (!VD)
324+
return std::nullopt;
325+
326+
// Cost the call + mask.
327+
auto Cost =
328+
thisT()->getCallInstrCost(nullptr, RetTy, ICA.getArgTypes(), CostKind);
329+
if (VD->isMasked())
330+
Cost += thisT()->getShuffleCost(
331+
TargetTransformInfo::SK_Broadcast,
332+
VectorType::get(IntegerType::getInt1Ty(Ctx), VF), {}, CostKind, 0,
333+
nullptr, {});
334+
335+
// Lowering to a library call (with output pointers) may require us to emit
336+
// reloads for the results.
337+
for (auto [Idx, VectorTy] : enumerate(getContainedTypes(RetTy))) {
338+
if (Idx == CallRetElementIndex)
339+
continue;
340+
Cost += thisT()->getMemoryOpCost(
341+
Instruction::Load, VectorTy,
342+
thisT()->getDataLayout().getABITypeAlign(VectorTy), 0, CostKind);
343+
}
344+
return Cost;
345+
}
346+
288347
protected:
289348
explicit BasicTTIImplBase(const TargetMachine *TM, const DataLayout &DL)
290349
: BaseT(DL) {}
@@ -1716,9 +1775,9 @@ class BasicTTIImplBase : public TargetTransformInfoImplCRTPBase<T> {
17161775

17171776
Type *RetTy = ICA.getReturnType();
17181777

1719-
ElementCount RetVF =
1720-
(RetTy->isVectorTy() ? cast<VectorType>(RetTy)->getElementCount()
1721-
: ElementCount::getFixed(1));
1778+
ElementCount RetVF = isVectorizedTy(RetTy) ? getVectorizedTypeVF(RetTy)
1779+
: ElementCount::getFixed(1);
1780+
17221781
const IntrinsicInst *I = ICA.getInst();
17231782
const SmallVectorImpl<const Value *> &Args = ICA.getArgs();
17241783
FastMathFlags FMF = ICA.getFlags();
@@ -1971,6 +2030,16 @@ class BasicTTIImplBase : public TargetTransformInfoImplCRTPBase<T> {
19712030
}
19722031
case Intrinsic::experimental_vector_match:
19732032
return thisT()->getTypeBasedIntrinsicInstrCost(ICA, CostKind);
2033+
case Intrinsic::sincos: {
2034+
Type *Ty = getContainedTypes(RetTy).front();
2035+
EVT VT = getTLI()->getValueType(DL, Ty);
2036+
RTLIB::Libcall LC = RTLIB::getFSINCOS(VT.getScalarType());
2037+
if (auto Cost =
2038+
getMultipleResultIntrinsicVectorLibCallCost(ICA, CostKind, LC))
2039+
return *Cost;
2040+
// Otherwise, fallback to default scalarization cost.
2041+
break;
2042+
}
19742043
}
19752044

19762045
// Assume that we need to scalarize this intrinsic.)
@@ -1979,10 +2048,13 @@ class BasicTTIImplBase : public TargetTransformInfoImplCRTPBase<T> {
19792048
InstructionCost ScalarizationCost = InstructionCost::getInvalid();
19802049
if (RetVF.isVector() && !RetVF.isScalable()) {
19812050
ScalarizationCost = 0;
1982-
if (!RetTy->isVoidTy())
1983-
ScalarizationCost += getScalarizationOverhead(
1984-
cast<VectorType>(RetTy),
1985-
/*Insert*/ true, /*Extract*/ false, CostKind);
2051+
if (!RetTy->isVoidTy()) {
2052+
for (Type *VectorTy : getContainedTypes(RetTy)) {
2053+
ScalarizationCost += getScalarizationOverhead(
2054+
cast<VectorType>(VectorTy),
2055+
/*Insert=*/true, /*Extract=*/false, CostKind);
2056+
}
2057+
}
19862058
ScalarizationCost +=
19872059
getOperandsScalarizationOverhead(Args, ICA.getArgTypes(), CostKind);
19882060
}
@@ -2637,27 +2709,32 @@ class BasicTTIImplBase : public TargetTransformInfoImplCRTPBase<T> {
26372709
// Else, assume that we need to scalarize this intrinsic. For math builtins
26382710
// this will emit a costly libcall, adding call overhead and spills. Make it
26392711
// very expensive.
2640-
if (auto *RetVTy = dyn_cast<VectorType>(RetTy)) {
2712+
if (isVectorizedTy(RetTy)) {
2713+
ArrayRef<Type *> RetVTys = getContainedTypes(RetTy);
2714+
26412715
// Scalable vectors cannot be scalarized, so return Invalid.
2642-
if (isa<ScalableVectorType>(RetTy) || any_of(Tys, [](const Type *Ty) {
2643-
return isa<ScalableVectorType>(Ty);
2644-
}))
2716+
if (any_of(concat<Type *const>(RetVTys, Tys),
2717+
[](Type *Ty) { return isa<ScalableVectorType>(Ty); }))
26452718
return InstructionCost::getInvalid();
26462719

2647-
InstructionCost ScalarizationCost =
2648-
SkipScalarizationCost
2649-
? ScalarizationCostPassed
2650-
: getScalarizationOverhead(RetVTy, /*Insert*/ true,
2651-
/*Extract*/ false, CostKind);
2720+
InstructionCost ScalarizationCost = ScalarizationCostPassed;
2721+
if (!SkipScalarizationCost) {
2722+
ScalarizationCost = 0;
2723+
for (Type *RetVTy : RetVTys) {
2724+
ScalarizationCost += getScalarizationOverhead(
2725+
cast<VectorType>(RetVTy), /*Insert=*/true,
2726+
/*Extract=*/false, CostKind);
2727+
}
2728+
}
26522729

2653-
unsigned ScalarCalls = cast<FixedVectorType>(RetVTy)->getNumElements();
2730+
unsigned ScalarCalls = getVectorizedTypeVF(RetTy).getFixedValue();
26542731
SmallVector<Type *, 4> ScalarTys;
26552732
for (Type *Ty : Tys) {
26562733
if (Ty->isVectorTy())
26572734
Ty = Ty->getScalarType();
26582735
ScalarTys.push_back(Ty);
26592736
}
2660-
IntrinsicCostAttributes Attrs(IID, RetTy->getScalarType(), ScalarTys, FMF);
2737+
IntrinsicCostAttributes Attrs(IID, toScalarizedTy(RetTy), ScalarTys, FMF);
26612738
InstructionCost ScalarCost =
26622739
thisT()->getIntrinsicInstrCost(Attrs, CostKind);
26632740
for (Type *Ty : Tys) {

llvm/lib/Analysis/CostModel.cpp

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,15 @@
1717
//===----------------------------------------------------------------------===//
1818

1919
#include "llvm/Analysis/CostModel.h"
20+
#include "llvm/Analysis/TargetLibraryInfo.h"
2021
#include "llvm/Analysis/TargetTransformInfo.h"
2122
#include "llvm/IR/Function.h"
2223
#include "llvm/IR/IntrinsicInst.h"
2324
#include "llvm/IR/PassManager.h"
2425
#include "llvm/Pass.h"
2526
#include "llvm/Support/CommandLine.h"
2627
#include "llvm/Support/raw_ostream.h"
28+
2729
using namespace llvm;
2830

2931
static cl::opt<TargetTransformInfo::TargetCostKind> CostKind(
@@ -42,25 +44,31 @@ static cl::opt<bool> TypeBasedIntrinsicCost("type-based-intrinsic-cost",
4244
cl::desc("Calculate intrinsics cost based only on argument types"),
4345
cl::init(false));
4446

47+
static cl::opt<bool> PreferIntrinsicCost(
48+
"prefer-intrinsic-cost",
49+
cl::desc("Prefer using getIntrinsicInstrCost over getInstructionCost"),
50+
cl::init(false));
51+
4552
#define CM_NAME "cost-model"
4653
#define DEBUG_TYPE CM_NAME
4754

4855
PreservedAnalyses CostModelPrinterPass::run(Function &F,
4956
FunctionAnalysisManager &AM) {
5057
auto &TTI = AM.getResult<TargetIRAnalysis>(F);
58+
auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
5159
OS << "Printing analysis 'Cost Model Analysis' for function '" << F.getName() << "':\n";
5260
for (BasicBlock &B : F) {
5361
for (Instruction &Inst : B) {
5462
// TODO: Use a pass parameter instead of cl::opt CostKind to determine
5563
// which cost kind to print.
5664
InstructionCost Cost;
5765
auto *II = dyn_cast<IntrinsicInst>(&Inst);
58-
if (II && TypeBasedIntrinsicCost) {
59-
IntrinsicCostAttributes ICA(II->getIntrinsicID(), *II,
60-
InstructionCost::getInvalid(), true);
66+
if (II && (PreferIntrinsicCost || TypeBasedIntrinsicCost)) {
67+
IntrinsicCostAttributes ICA(
68+
II->getIntrinsicID(), *II, InstructionCost::getInvalid(),
69+
/*TypeBasedOnly=*/TypeBasedIntrinsicCost, &TLI);
6170
Cost = TTI.getIntrinsicInstrCost(ICA, CostKind);
62-
}
63-
else {
71+
} else {
6472
Cost = TTI.getInstructionCost(&Inst, CostKind);
6573
}
6674

llvm/lib/Analysis/TargetTransformInfo.cpp

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -69,9 +69,9 @@ bool HardwareLoopInfo::canAnalyze(LoopInfo &LI) {
6969

7070
IntrinsicCostAttributes::IntrinsicCostAttributes(
7171
Intrinsic::ID Id, const CallBase &CI, InstructionCost ScalarizationCost,
72-
bool TypeBasedOnly)
72+
bool TypeBasedOnly, const TargetLibraryInfo *LibInfo)
7373
: II(dyn_cast<IntrinsicInst>(&CI)), RetTy(CI.getType()), IID(Id),
74-
ScalarizationCost(ScalarizationCost) {
74+
ScalarizationCost(ScalarizationCost), LibInfo(LibInfo) {
7575

7676
if (const auto *FPMO = dyn_cast<FPMathOperator>(&CI))
7777
FMF = FPMO->getFastMathFlags();
@@ -101,13 +101,12 @@ IntrinsicCostAttributes::IntrinsicCostAttributes(Intrinsic::ID Id, Type *Ty,
101101
ParamTys.push_back(Argument->getType());
102102
}
103103

104-
IntrinsicCostAttributes::IntrinsicCostAttributes(Intrinsic::ID Id, Type *RTy,
105-
ArrayRef<const Value *> Args,
106-
ArrayRef<Type *> Tys,
107-
FastMathFlags Flags,
108-
const IntrinsicInst *I,
109-
InstructionCost ScalarCost)
110-
: II(I), RetTy(RTy), IID(Id), FMF(Flags), ScalarizationCost(ScalarCost) {
104+
IntrinsicCostAttributes::IntrinsicCostAttributes(
105+
Intrinsic::ID Id, Type *RTy, ArrayRef<const Value *> Args,
106+
ArrayRef<Type *> Tys, FastMathFlags Flags, const IntrinsicInst *I,
107+
InstructionCost ScalarCost, TargetLibraryInfo const *LibInfo)
108+
: II(I), RetTy(RTy), IID(Id), FMF(Flags), ScalarizationCost(ScalarCost),
109+
LibInfo(LibInfo) {
111110
ParamTys.insert(ParamTys.begin(), Tys.begin(), Tys.end());
112111
Arguments.insert(Arguments.begin(), Args.begin(), Args.end());
113112
}

llvm/lib/Analysis/VectorUtils.cpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ bool llvm::isTriviallyVectorizable(Intrinsic::ID ID) {
7272
case Intrinsic::atan2:
7373
case Intrinsic::sin:
7474
case Intrinsic::cos:
75+
case Intrinsic::sincos:
7576
case Intrinsic::tan:
7677
case Intrinsic::sinh:
7778
case Intrinsic::cosh:
@@ -179,6 +180,7 @@ bool llvm::isVectorIntrinsicWithOverloadTypeAtArg(
179180
case Intrinsic::ucmp:
180181
case Intrinsic::scmp:
181182
return OpdIdx == -1 || OpdIdx == 0;
183+
case Intrinsic::sincos:
182184
case Intrinsic::is_fpclass:
183185
case Intrinsic::vp_is_fpclass:
184186
return OpdIdx == 0;

llvm/lib/Transforms/Vectorize/LoopVectorize.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2885,7 +2885,8 @@ LoopVectorizationCostModel::getVectorIntrinsicCost(CallInst *CI,
28852885
[&](Type *Ty) { return maybeVectorizeType(Ty, VF); });
28862886

28872887
IntrinsicCostAttributes CostAttrs(ID, RetTy, Arguments, ParamTys, FMF,
2888-
dyn_cast<IntrinsicInst>(CI));
2888+
dyn_cast<IntrinsicInst>(CI),
2889+
InstructionCost::getInvalid(), TLI);
28892890
return TTI.getIntrinsicInstrCost(CostAttrs, CostKind);
28902891
}
28912892

llvm/lib/Transforms/Vectorize/VPlanRecipes.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1151,7 +1151,8 @@ InstructionCost VPWidenIntrinsicRecipe::computeCost(ElementCount VF,
11511151
FastMathFlags FMF = hasFastMathFlags() ? getFastMathFlags() : FastMathFlags();
11521152
IntrinsicCostAttributes CostAttrs(
11531153
VectorIntrinsicID, RetTy, Arguments, ParamTys, FMF,
1154-
dyn_cast_or_null<IntrinsicInst>(getUnderlyingValue()));
1154+
dyn_cast_or_null<IntrinsicInst>(getUnderlyingValue()),
1155+
InstructionCost::getInvalid(), &Ctx.TLI);
11551156
return Ctx.TTI.getIntrinsicInstrCost(CostAttrs, Ctx.CostKind);
11561157
}
11571158

0 commit comments

Comments
 (0)