1//=== ReplaceWithVeclib.cpp - Replace vector intrinsics with veclib calls -===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Replaces calls to LLVM Intrinsics with matching calls to functions from a
10// vector library (e.g libmvec, SVML) using TargetLibraryInfo interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/CodeGen/ReplaceWithVeclib.h"
15#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/Statistic.h"
17#include "llvm/ADT/StringRef.h"
18#include "llvm/Analysis/DemandedBits.h"
19#include "llvm/Analysis/GlobalsModRef.h"
20#include "llvm/Analysis/OptimizationRemarkEmitter.h"
21#include "llvm/Analysis/TargetLibraryInfo.h"
22#include "llvm/Analysis/VectorUtils.h"
23#include "llvm/CodeGen/Passes.h"
24#include "llvm/IR/DerivedTypes.h"
25#include "llvm/IR/IRBuilder.h"
26#include "llvm/IR/InstIterator.h"
27#include "llvm/IR/IntrinsicInst.h"
28#include "llvm/IR/VFABIDemangler.h"
29#include "llvm/InitializePasses.h"
30#include "llvm/Support/TypeSize.h"
31#include "llvm/Transforms/Utils/ModuleUtils.h"
32
33using namespace llvm;
34
35#define DEBUG_TYPE "replace-with-veclib"
36
37STATISTIC(NumCallsReplaced,
38 "Number of calls to intrinsics that have been replaced.");
39
40STATISTIC(NumTLIFuncDeclAdded,
41 "Number of vector library function declarations added.");
42
43STATISTIC(NumFuncUsedAdded,
44 "Number of functions added to `llvm.compiler.used`");
45
46/// Returns a vector Function that it adds to the Module \p M. When an \p
47/// ScalarFunc is not null, it copies its attributes to the newly created
48/// Function.
49Function *getTLIFunction(Module *M, FunctionType *VectorFTy,
50 const StringRef TLIName,
51 Function *ScalarFunc = nullptr) {
52 Function *TLIFunc = M->getFunction(Name: TLIName);
53 if (!TLIFunc) {
54 TLIFunc =
55 Function::Create(Ty: VectorFTy, Linkage: Function::ExternalLinkage, N: TLIName, M&: *M);
56 if (ScalarFunc)
57 TLIFunc->copyAttributesFrom(Src: ScalarFunc);
58
59 LLVM_DEBUG(dbgs() << DEBUG_TYPE << ": Added vector library function `"
60 << TLIName << "` of type `" << *(TLIFunc->getType())
61 << "` to module.\n");
62
63 ++NumTLIFuncDeclAdded;
64 // Add the freshly created function to llvm.compiler.used, similar to as it
65 // is done in InjectTLIMappings.
66 appendToCompilerUsed(M&: *M, Values: {TLIFunc});
67 LLVM_DEBUG(dbgs() << DEBUG_TYPE << ": Adding `" << TLIName
68 << "` to `@llvm.compiler.used`.\n");
69 ++NumFuncUsedAdded;
70 }
71 return TLIFunc;
72}
73
74/// Replace the intrinsic call \p II to \p TLIVecFunc, which is the
75/// corresponding function from the vector library.
76static void replaceWithTLIFunction(IntrinsicInst *II, VFInfo &Info,
77 Function *TLIVecFunc) {
78 IRBuilder<> IRBuilder(II);
79 SmallVector<Value *> Args(II->args());
80 if (auto OptMaskpos = Info.getParamIndexForOptionalMask()) {
81 auto *MaskTy =
82 VectorType::get(ElementType: Type::getInt1Ty(C&: II->getContext()), EC: Info.Shape.VF);
83 Args.insert(I: Args.begin() + OptMaskpos.value(),
84 Elt: Constant::getAllOnesValue(Ty: MaskTy));
85 }
86
87 // Preserve the operand bundles.
88 SmallVector<OperandBundleDef, 1> OpBundles;
89 II->getOperandBundlesAsDefs(Defs&: OpBundles);
90
91 auto *Replacement = IRBuilder.CreateCall(Callee: TLIVecFunc, Args, OpBundles);
92 II->replaceAllUsesWith(V: Replacement);
93 // Preserve fast math flags for FP math.
94 if (isa<FPMathOperator>(Val: Replacement))
95 Replacement->copyFastMathFlags(I: II);
96}
97
98/// Returns true when successfully replaced \p II, which is a call to a
99/// vectorized intrinsic, with a suitable function taking vector arguments,
100/// based on available mappings in the \p TLI.
101static bool replaceWithCallToVeclib(const TargetLibraryInfo &TLI,
102 IntrinsicInst *II) {
103 assert(II != nullptr && "Intrinsic cannot be null");
104 Intrinsic::ID IID = II->getIntrinsicID();
105 Type *RetTy = II->getType();
106 Type *ScalarRetTy = RetTy->getScalarType();
107 // At the moment VFABI assumes the return type is always widened unless it is
108 // a void type.
109 auto *VTy = dyn_cast<VectorType>(Val: RetTy);
110 ElementCount EC(VTy ? VTy->getElementCount() : ElementCount::getFixed(MinVal: 0));
111
112 // OloadTys collects types used in scalar intrinsic overload name.
113 SmallVector<Type *, 3> OloadTys;
114 if (!RetTy->isVoidTy() &&
115 isVectorIntrinsicWithOverloadTypeAtArg(ID: IID, OpdIdx: -1, /*TTI=*/nullptr))
116 OloadTys.push_back(Elt: ScalarRetTy);
117
118 // Compute the argument types of the corresponding scalar call and check that
119 // all vector operands match the previously found EC.
120 SmallVector<Type *, 8> ScalarArgTypes;
121 for (auto Arg : enumerate(First: II->args())) {
122 auto *ArgTy = Arg.value()->getType();
123 bool IsOloadTy = isVectorIntrinsicWithOverloadTypeAtArg(ID: IID, OpdIdx: Arg.index(),
124 /*TTI=*/nullptr);
125 if (isVectorIntrinsicWithScalarOpAtArg(ID: IID, ScalarOpdIdx: Arg.index(), /*TTI=*/nullptr)) {
126 ScalarArgTypes.push_back(Elt: ArgTy);
127 if (IsOloadTy)
128 OloadTys.push_back(Elt: ArgTy);
129 } else if (auto *VectorArgTy = dyn_cast<VectorType>(Val: ArgTy)) {
130 auto *ScalarArgTy = VectorArgTy->getElementType();
131 ScalarArgTypes.push_back(Elt: ScalarArgTy);
132 if (IsOloadTy)
133 OloadTys.push_back(Elt: ScalarArgTy);
134 // When return type is void, set EC to the first vector argument, and
135 // disallow vector arguments with different ECs.
136 if (EC.isZero())
137 EC = VectorArgTy->getElementCount();
138 else if (EC != VectorArgTy->getElementCount())
139 return false;
140 } else
141 // Exit when it is supposed to be a vector argument but it isn't.
142 return false;
143 }
144
145 // Try to reconstruct the name for the scalar version of the instruction,
146 // using scalar argument types.
147 std::string ScalarName =
148 Intrinsic::isOverloaded(id: IID)
149 ? Intrinsic::getName(Id: IID, Tys: OloadTys, M: II->getModule())
150 : Intrinsic::getName(id: IID).str();
151
152 // Try to find the mapping for the scalar version of this intrinsic and the
153 // exact vector width of the call operands in the TargetLibraryInfo. First,
154 // check with a non-masked variant, and if that fails try with a masked one.
155 const VecDesc *VD =
156 TLI.getVectorMappingInfo(F: ScalarName, VF: EC, /*Masked*/ false);
157 if (!VD && !(VD = TLI.getVectorMappingInfo(F: ScalarName, VF: EC, /*Masked*/ true)))
158 return false;
159
160 LLVM_DEBUG(dbgs() << DEBUG_TYPE << ": Found TLI mapping from: `" << ScalarName
161 << "` and vector width " << EC << " to: `"
162 << VD->getVectorFnName() << "`.\n");
163
164 // Replace the call to the intrinsic with a call to the vector library
165 // function.
166 FunctionType *ScalarFTy =
167 FunctionType::get(Result: ScalarRetTy, Params: ScalarArgTypes, /*isVarArg*/ false);
168 const std::string MangledName = VD->getVectorFunctionABIVariantString();
169 auto OptInfo = VFABI::tryDemangleForVFABI(MangledName, FTy: ScalarFTy);
170 if (!OptInfo)
171 return false;
172
173 // There is no guarantee that the vectorized instructions followed the VFABI
174 // specification when being created, this is why we need to add extra check to
175 // make sure that the operands of the vector function obtained via VFABI match
176 // the operands of the original vector instruction.
177 for (auto &VFParam : OptInfo->Shape.Parameters) {
178 if (VFParam.ParamKind == VFParamKind::GlobalPredicate)
179 continue;
180
181 // tryDemangleForVFABI must return valid ParamPos, otherwise it could be
182 // a bug in the VFABI parser.
183 assert(VFParam.ParamPos < II->arg_size() && "ParamPos has invalid range");
184 Type *OrigTy = II->getArgOperand(i: VFParam.ParamPos)->getType();
185 if (OrigTy->isVectorTy() != (VFParam.ParamKind == VFParamKind::Vector)) {
186 LLVM_DEBUG(dbgs() << DEBUG_TYPE << ": Will not replace: " << ScalarName
187 << ". Wrong type at index " << VFParam.ParamPos << ": "
188 << *OrigTy << "\n");
189 return false;
190 }
191 }
192
193 FunctionType *VectorFTy = VFABI::createFunctionType(Info: *OptInfo, ScalarFTy);
194 if (!VectorFTy)
195 return false;
196
197 Function *TLIFunc =
198 getTLIFunction(M: II->getModule(), VectorFTy, TLIName: VD->getVectorFnName(),
199 ScalarFunc: II->getCalledFunction());
200 replaceWithTLIFunction(II, Info&: *OptInfo, TLIVecFunc: TLIFunc);
201 LLVM_DEBUG(dbgs() << DEBUG_TYPE << ": Replaced call to `" << ScalarName
202 << "` with call to `" << TLIFunc->getName() << "`.\n");
203 ++NumCallsReplaced;
204 return true;
205}
206
207static bool runImpl(const TargetLibraryInfo &TLI, Function &F) {
208 SmallVector<Instruction *> ReplacedCalls;
209 for (auto &I : instructions(F)) {
210 // Process only intrinsic calls that return void or a vector.
211 if (auto *II = dyn_cast<IntrinsicInst>(Val: &I)) {
212 if (II->getIntrinsicID() == Intrinsic::not_intrinsic)
213 continue;
214 if (!II->getType()->isVectorTy() && !II->getType()->isVoidTy())
215 continue;
216
217 if (replaceWithCallToVeclib(TLI, II))
218 ReplacedCalls.push_back(Elt: &I);
219 }
220 }
221 // Erase any intrinsic calls that were replaced with vector library calls.
222 for (auto *I : ReplacedCalls)
223 I->eraseFromParent();
224 return !ReplacedCalls.empty();
225}
226
227////////////////////////////////////////////////////////////////////////////////
228// New pass manager implementation.
229////////////////////////////////////////////////////////////////////////////////
230PreservedAnalyses ReplaceWithVeclib::run(Function &F,
231 FunctionAnalysisManager &AM) {
232 const TargetLibraryInfo &TLI = AM.getResult<TargetLibraryAnalysis>(IR&: F);
233 auto Changed = runImpl(TLI, F);
234 if (Changed) {
235 LLVM_DEBUG(dbgs() << "Intrinsic calls replaced with vector libraries: "
236 << NumCallsReplaced << "\n");
237
238 PreservedAnalyses PA;
239 PA.preserveSet<CFGAnalyses>();
240 PA.preserve<TargetLibraryAnalysis>();
241 PA.preserve<ScalarEvolutionAnalysis>();
242 PA.preserve<LoopAccessAnalysis>();
243 PA.preserve<DemandedBitsAnalysis>();
244 PA.preserve<OptimizationRemarkEmitterAnalysis>();
245 return PA;
246 }
247
248 // The pass did not replace any calls, hence it preserves all analyses.
249 return PreservedAnalyses::all();
250}
251
252////////////////////////////////////////////////////////////////////////////////
253// Legacy PM Implementation.
254////////////////////////////////////////////////////////////////////////////////
255bool ReplaceWithVeclibLegacy::runOnFunction(Function &F) {
256 const TargetLibraryInfo &TLI =
257 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
258 return runImpl(TLI, F);
259}
260
261void ReplaceWithVeclibLegacy::getAnalysisUsage(AnalysisUsage &AU) const {
262 AU.setPreservesCFG();
263 AU.addRequired<TargetLibraryInfoWrapperPass>();
264 AU.addPreserved<TargetLibraryInfoWrapperPass>();
265 AU.addPreserved<ScalarEvolutionWrapperPass>();
266 AU.addPreserved<AAResultsWrapperPass>();
267 AU.addPreserved<OptimizationRemarkEmitterWrapperPass>();
268 AU.addPreserved<GlobalsAAWrapperPass>();
269}
270
271////////////////////////////////////////////////////////////////////////////////
272// Legacy Pass manager initialization
273////////////////////////////////////////////////////////////////////////////////
274char ReplaceWithVeclibLegacy::ID = 0;
275
276INITIALIZE_PASS_BEGIN(ReplaceWithVeclibLegacy, DEBUG_TYPE,
277 "Replace intrinsics with calls to vector library", false,
278 false)
279INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
280INITIALIZE_PASS_END(ReplaceWithVeclibLegacy, DEBUG_TYPE,
281 "Replace intrinsics with calls to vector library", false,
282 false)
283
284FunctionPass *llvm::createReplaceWithVeclibLegacyPass() {
285 return new ReplaceWithVeclibLegacy();
286}
287