LLVM  12.0.0git
InjectTLIMappings.cpp
Go to the documentation of this file.
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 
15 #include "llvm/ADT/Statistic.h"
21 #include "llvm/IR/InstIterator.h"
22 #include "llvm/IR/IntrinsicInst.h"
23 #include "llvm/Transforms/Utils.h"
25 
26 using namespace llvm;
27 
28 #define DEBUG_TYPE "inject-tli-mappings"
29 
30 STATISTIC(NumCallInjected,
31  "Number of calls in which the mappings have been injected.");
32 
33 STATISTIC(NumVFDeclAdded,
34  "Number of function declarations that have been added.");
35 STATISTIC(NumCompUsedAdded,
36  "Number of `@llvm.compiler.used` operands that have been added.");
37 
38 /// A helper function that adds the vector function declaration that
39 /// vectorizes the CallInst CI with a vectorization factor of VF
40 /// lanes. The TLI assumes that all parameters and the return type of
41 /// CI (other than void) need to be widened to a VectorType of VF
42 /// lanes.
43 static void addVariantDeclaration(CallInst &CI, const unsigned VF,
44  const StringRef VFName) {
45  Module *M = CI.getModule();
46 
47  // Add function declaration.
48  Type *RetTy = ToVectorTy(CI.getType(), VF);
50  for (Value *ArgOperand : CI.arg_operands())
51  Tys.push_back(ToVectorTy(ArgOperand->getType(), VF));
52  assert(!CI.getFunctionType()->isVarArg() &&
53  "VarArg functions are not supported.");
54  FunctionType *FTy = FunctionType::get(RetTy, Tys, /*isVarArg=*/false);
55  Function *VectorF =
58  ++NumVFDeclAdded;
59  LLVM_DEBUG(dbgs() << DEBUG_TYPE << ": Added to the module: `" << VFName
60  << "` of type " << *(VectorF->getType()) << "\n");
61 
62  // Make function declaration (without a body) "sticky" in the IR by
63  // listing it in the @llvm.compiler.used intrinsic.
64  assert(!VectorF->size() && "VFABI attribute requires `@llvm.compiler.used` "
65  "only on declarations.");
66  appendToCompilerUsed(*M, {VectorF});
67  LLVM_DEBUG(dbgs() << DEBUG_TYPE << ": Adding `" << VFName
68  << "` to `@llvm.compiler.used`.\n");
69  ++NumCompUsedAdded;
70 }
71 
72 static void addMappingsFromTLI(const TargetLibraryInfo &TLI, CallInst &CI) {
73  // This is needed to make sure we don't query the TLI for calls to
74  // bitcast of function pointers, like `%call = call i32 (i32*, ...)
75  // bitcast (i32 (...)* @goo to i32 (i32*, ...)*)(i32* nonnull %i)`,
76  // as such calls make the `isFunctionVectorizable` raise an
77  // exception.
78  if (CI.isNoBuiltin() || !CI.getCalledFunction())
79  return;
80 
81  StringRef ScalarName = CI.getCalledFunction()->getName();
82 
83  // Nothing to be done if the TLI thinks the function is not
84  // vectorizable.
85  if (!TLI.isFunctionVectorizable(ScalarName))
86  return;
89  Module *M = CI.getModule();
90  const SetVector<StringRef> OriginalSetOfMappings(Mappings.begin(),
91  Mappings.end());
92  // All VFs in the TLI are powers of 2.
93  for (unsigned VF = 2, WidestVF = TLI.getWidestVF(ScalarName); VF <= WidestVF;
94  VF *= 2) {
95  const std::string TLIName =
96  std::string(TLI.getVectorizedFunction(ScalarName, VF));
97  if (!TLIName.empty()) {
98  std::string MangledName = VFABI::mangleTLIVectorName(
99  TLIName, ScalarName, CI.getNumArgOperands(), VF);
100  if (!OriginalSetOfMappings.count(MangledName)) {
101  Mappings.push_back(MangledName);
102  ++NumCallInjected;
103  }
104  Function *VariantF = M->getFunction(TLIName);
105  if (!VariantF)
106  addVariantDeclaration(CI, VF, TLIName);
107  }
108  }
109 
111 }
112 
113 static bool runImpl(const TargetLibraryInfo &TLI, Function &F) {
114  for (auto &I : instructions(F))
115  if (auto CI = dyn_cast<CallInst>(&I))
116  addMappingsFromTLI(TLI, *CI);
117  // Even if the pass adds IR attributes, the analyses are preserved.
118  return false;
119 }
120 
121 ////////////////////////////////////////////////////////////////////////////////
122 // New pass manager implementation.
123 ////////////////////////////////////////////////////////////////////////////////
127  runImpl(TLI, F);
128  // Even if the pass adds IR attributes, the analyses are preserved.
129  return PreservedAnalyses::all();
130 }
131 
132 ////////////////////////////////////////////////////////////////////////////////
133 // Legacy PM Implementation.
134 ////////////////////////////////////////////////////////////////////////////////
136  const TargetLibraryInfo &TLI =
137  getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
138  return runImpl(TLI, F);
139 }
140 
142  AU.setPreservesCFG();
151 }
152 
153 ////////////////////////////////////////////////////////////////////////////////
154 // Legacy Pass manager initialization
155 ////////////////////////////////////////////////////////////////////////////////
157 
159  "Inject TLI Mappings", false, false)
162  false, false)
163 
165  return new InjectTLIMappingsLegacy();
166 }
Legacy wrapper pass to provide the GlobalsAAResult object.
size_t size() const
Definition: Function.h:752
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
void getVectorVariantNames(const CallInst &CI, SmallVectorImpl< std::string > &VariantMappings)
Populates a set of strings representing the Vector Function ABI variants associated to the CallInst C...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:785
void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
This class represents lattice values for constants.
Definition: AllocatorList.h:23
This is the interface for a simple mod/ref and alias analysis over globals.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:67
void push_back(const T &Elt)
Definition: SmallVector.h:379
This class represents a function call, abstracting a target machine's calling convention.
Inject TLI Mappings
Externally visible function.
Definition: GlobalValue.h:48
STATISTIC(NumFunctions, "Total number of functions")
F(f)
AnalysisUsage & addRequired()
#define DEBUG_TYPE
Class to represent function types.
Definition: DerivedTypes.h:102
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:246
bool isVarArg() const
Definition: DerivedTypes.h:122
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
Definition: Type.cpp:321
iterator_range< User::op_iterator > arg_operands()
Definition: InstrTypes.h:1315
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:137
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:155
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:46
bool isNoBuiltin() const
Return true if the call should not be treated as a call to a builtin.
Definition: InstrTypes.h:1736
This analysis provides dependence information for the memory accesses of a loop.
static void addMappingsFromTLI(const TargetLibraryInfo &TLI, CallInst &CI)
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
Definition: Function.cpp:621
FunctionType * getFunctionType() const
Definition: InstrTypes.h:1226
Represent the analysis usage information of a pass.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
FunctionPass * createInjectTLIMappingsLegacyPass()
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:161
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
bool isFunctionVectorizable(StringRef F, unsigned VF) const
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1116
Provides information about what library functions are available for the current target.
INITIALIZE_PASS_BEGIN(InjectTLIMappingsLegacy, DEBUG_TYPE, "Inject TLI Mappings", false, false) INITIALIZE_PASS_END(InjectTLIMappingsLegacy
Type * ToVectorTy(Type *Scalar, ElementCount EC)
A helper function for converting Scalar types to vector types.
Definition: VectorUtils.h:306
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:253
StringRef getVectorizedFunction(StringRef F, unsigned VF) const
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:65
unsigned getNumArgOperands() const
Definition: InstrTypes.h:1321
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:295
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation.
Definition: InstrTypes.h:1378
#define I(x, y, z)
Definition: MD5.cpp:59
static void addVariantDeclaration(CallInst &CI, const unsigned VF, const StringRef VFName)
A helper function that adds the vector function declaration that vectorizes the CallInst CI with a ve...
Analysis pass providing the TargetLibraryInfo.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:75
A vector that has set insertion semantics.
Definition: SetVector.h:40
std::string mangleTLIVectorName(StringRef VectorName, StringRef ScalarName, unsigned numArgs, unsigned VF)
This routine mangles the given VectorName according to the LangRef specification for vector-function-...
OptimizationRemarkEmitter legacy analysis pass.
static bool runImpl(const TargetLibraryInfo &TLI, Function &F)
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:57
inst_range instructions(Function *F)
Definition: InstIterator.h:133
A container for analyses that lazily runs them and caches their results.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
#define LLVM_DEBUG(X)
Definition: Debug.h:122
unsigned getWidestVF(StringRef ScalarF) const
Returns the largest vectorization factor used in the list of vector functions.
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:271
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
void setVectorVariantNames(CallInst *CI, const SmallVector< std::string, 8 > &VariantMappings)
Overwrite the Vector Function ABI variants attribute with the names provide in VariantMappings.