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