1 //===- InjectTLIMAppings.cpp - TLI to VFABI attribute injection  ----------===//
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 // Populates the VFABI attribute with the scalar-to-vector mappings
10 // from the TargetLibraryInfo.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/Analysis/DemandedBits.h"
17 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
18 #include "llvm/Analysis/VectorUtils.h"
19 #include "llvm/IR/InstIterator.h"
20 #include "llvm/Transforms/Utils.h"
21 #include "llvm/Transforms/Utils/ModuleUtils.h"
22 
23 using namespace llvm;
24 
25 #define DEBUG_TYPE "inject-tli-mappings"
26 
27 STATISTIC(NumCallInjected,
28           "Number of calls in which the mappings have been injected.");
29 
30 STATISTIC(NumVFDeclAdded,
31           "Number of function declarations that have been added.");
32 STATISTIC(NumCompUsedAdded,
33           "Number of `@llvm.compiler.used` operands that have been added.");
34 
35 /// Helper function to map the TLI name to a strings that holds
36 /// scalar-to-vector mapping.
37 ///
38 ///    _ZGV<isa><mask><vlen><vparams>_<scalarname>(<vectorname>)
39 ///
40 /// where:
41 ///
42 /// <isa> = "_LLVM_"
43 /// <mask> = "N". Note: TLI does not support masked interfaces.
44 /// <vlen> = Number of concurrent lanes, stored in the `VectorizationFactor`
45 ///          field of the `VecDesc` struct.
46 /// <vparams> = "v", as many as are the number of parameters of CI.
47 /// <scalarname> = the name of the scalar function called by CI.
48 /// <vectorname> = the name of the vector function mapped by the TLI.
49 static std::string mangleTLIName(StringRef VectorName, const CallInst &CI,
50                                  unsigned VF) {
51   SmallString<256> Buffer;
52   llvm::raw_svector_ostream Out(Buffer);
53   Out << "_ZGV" << VFABI::_LLVM_ << "N" << VF;
54   for (unsigned I = 0; I < CI.getNumArgOperands(); ++I)
55     Out << "v";
56   Out << "_" << CI.getCalledFunction()->getName() << "(" << VectorName << ")";
57   return Out.str();
58 }
59 
60 /// A helper function for converting Scalar types to vector types.
61 /// If the incoming type is void, we return void. If the VF is 1, we return
62 /// the scalar type.
63 static Type *ToVectorTy(Type *Scalar, unsigned VF, bool isScalable = false) {
64   if (Scalar->isVoidTy() || VF == 1)
65     return Scalar;
66   return VectorType::get(Scalar, {VF, isScalable});
67 }
68 
69 /// A helper function that adds the vector function declaration that
70 /// vectorizes the CallInst CI with a vectorization factor of VF
71 /// lanes. The TLI assumes that all parameters and the return type of
72 /// CI (other than void) need to be widened to a VectorType of VF
73 /// lanes.
74 static void addVariantDeclaration(CallInst &CI, const unsigned VF,
75                                   const StringRef VFName) {
76   Module *M = CI.getModule();
77 
78   // Add function declaration.
79   Type *RetTy = ToVectorTy(CI.getType(), VF);
80   SmallVector<Type *, 4> Tys;
81   for (Value *ArgOperand : CI.arg_operands())
82     Tys.push_back(ToVectorTy(ArgOperand->getType(), VF));
83   assert(!CI.getFunctionType()->isVarArg() &&
84          "VarArg functions are not supported.");
85   FunctionType *FTy = FunctionType::get(RetTy, Tys, /*isVarArg=*/false);
86   Function *VectorF =
87       Function::Create(FTy, Function::ExternalLinkage, VFName, M);
88   VectorF->copyAttributesFrom(CI.getCalledFunction());
89   ++NumVFDeclAdded;
90   LLVM_DEBUG(dbgs() << DEBUG_TYPE << ": Added to the module: `" << VFName
91                     << "` of type " << *(VectorF->getType()) << "\n");
92 
93   // Make function declaration (without a body) "sticky" in the IR by
94   // listing it in the @llvm.compiler.used intrinsic.
95   assert(!VectorF->size() && "VFABI attribute requires `@llvm.compiler.used` "
96                              "only on declarations.");
97   appendToCompilerUsed(*M, {VectorF});
98   LLVM_DEBUG(dbgs() << DEBUG_TYPE << ": Adding `" << VFName
99                     << "` to `@llvm.compiler.used`.\n");
100   ++NumCompUsedAdded;
101 }
102 
103 static void addMappingsFromTLI(const TargetLibraryInfo &TLI, CallInst &CI) {
104   // This is needed to make sure we don't query the TLI for calls to
105   // bitcast of function pointers, like `%call = call i32 (i32*, ...)
106   // bitcast (i32 (...)* @goo to i32 (i32*, ...)*)(i32* nonnull %i)`,
107   // as such calls make the `isFunctionVectorizable` raise an
108   // exception.
109   if (CI.isNoBuiltin() || !CI.getCalledFunction())
110     return;
111 
112   const std::string ScalarName = CI.getCalledFunction()->getName();
113   // Nothing to be done if the TLI thinks the function is not
114   // vectorizable.
115   if (!TLI.isFunctionVectorizable(ScalarName))
116     return;
117   SmallVector<std::string, 8> Mappings;
118   VFABI::getVectorVariantNames(CI, Mappings);
119   Module *M = CI.getModule();
120   const SetVector<StringRef> OriginalSetOfMappings(Mappings.begin(),
121                                                    Mappings.end());
122   //  All VFs in the TLI are powers of 2.
123   for (unsigned VF = 2, WidestVF = TLI.getWidestVF(ScalarName); VF <= WidestVF;
124        VF *= 2) {
125     const std::string TLIName = TLI.getVectorizedFunction(ScalarName, VF);
126     if (!TLIName.empty()) {
127       std::string MangledName = mangleTLIName(TLIName, CI, VF);
128       if (!OriginalSetOfMappings.count(MangledName)) {
129         Mappings.push_back(MangledName);
130         ++NumCallInjected;
131       }
132       Function *VariantF = M->getFunction(TLIName);
133       if (!VariantF)
134         addVariantDeclaration(CI, VF, TLIName);
135     }
136   }
137 
138   VFABI::setVectorVariantNames(&CI, Mappings);
139 }
140 
141 static bool runImpl(const TargetLibraryInfo &TLI, Function &F) {
142   for (auto &I : instructions(F))
143     if (auto CI = dyn_cast<CallInst>(&I))
144       addMappingsFromTLI(TLI, *CI);
145   // Even if the pass adds IR attributes, the analyses are preserved.
146   return false;
147 }
148 
149 ////////////////////////////////////////////////////////////////////////////////
150 // New pass manager implementation.
151 ////////////////////////////////////////////////////////////////////////////////
152 PreservedAnalyses InjectTLIMappings::run(Function &F,
153                                          FunctionAnalysisManager &AM) {
154   const TargetLibraryInfo &TLI = AM.getResult<TargetLibraryAnalysis>(F);
155   runImpl(TLI, F);
156   // Even if the pass adds IR attributes, the analyses are preserved.
157   return PreservedAnalyses::all();
158 }
159 
160 ////////////////////////////////////////////////////////////////////////////////
161 // Legacy PM Implementation.
162 ////////////////////////////////////////////////////////////////////////////////
163 bool InjectTLIMappingsLegacy::runOnFunction(Function &F) {
164   const TargetLibraryInfo &TLI =
165       getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
166   return runImpl(TLI, F);
167 }
168 
169 void InjectTLIMappingsLegacy::getAnalysisUsage(AnalysisUsage &AU) const {
170   AU.setPreservesCFG();
171   AU.addRequired<TargetLibraryInfoWrapperPass>();
172   AU.addPreserved<TargetLibraryInfoWrapperPass>();
173   AU.addPreserved<ScalarEvolutionWrapperPass>();
174   AU.addPreserved<AAResultsWrapperPass>();
175   AU.addPreserved<LoopAccessLegacyAnalysis>();
176   AU.addPreserved<DemandedBitsWrapperPass>();
177   AU.addPreserved<OptimizationRemarkEmitterWrapperPass>();
178 }
179 
180 ////////////////////////////////////////////////////////////////////////////////
181 // Legacy Pass manager initialization
182 ////////////////////////////////////////////////////////////////////////////////
183 char InjectTLIMappingsLegacy::ID = 0;
184 
185 INITIALIZE_PASS_BEGIN(InjectTLIMappingsLegacy, DEBUG_TYPE,
186                       "Inject TLI Mappings", false, false)
187 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
188 INITIALIZE_PASS_END(InjectTLIMappingsLegacy, DEBUG_TYPE, "Inject TLI Mappings",
189                     false, false)
190 
191 FunctionPass *llvm::createInjectTLIMappingsLegacyPass() {
192   return new InjectTLIMappingsLegacy();
193 }
194