LLVM 22.0.0git
SPIRVModuleAnalysis.h
Go to the documentation of this file.
1//===- SPIRVModuleAnalysis.h - analysis of global instrs & regs -*- C++ -*-===//
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// The analysis collects instructions that should be output at the module level
10// and performs the global register numbering.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_LIB_TARGET_SPIRV_SPIRVMODULEANALYSIS_H
15#define LLVM_LIB_TARGET_SPIRV_SPIRVMODULEANALYSIS_H
16
18#include "SPIRVGlobalRegistry.h"
19#include "SPIRVUtils.h"
20#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/SmallSet.h"
23
24namespace llvm {
25class SPIRVSubtarget;
26class MachineFunction;
27class MachineModuleInfo;
28
29namespace SPIRV {
30// The enum contains logical module sections for the instruction collection.
32 // MB_Capabilities, MB_Extensions, MB_ExtInstImports, MB_MemoryModel,
33 MB_EntryPoints, // All OpEntryPoint instructions (if any).
34 // MB_ExecutionModes, MB_DebugSourceAndStrings,
35 MB_DebugNames, // All OpName and OpMemberName intrs.
36 MB_DebugStrings, // All OpString intrs.
37 MB_DebugModuleProcessed, // All OpModuleProcessed instructions.
38 MB_AliasingInsts, // SPV_INTEL_memory_access_aliasing instructions.
39 MB_Annotations, // OpDecorate, OpMemberDecorate etc.
40 MB_TypeConstVars, // OpTypeXXX, OpConstantXXX, and global OpVariables.
41 MB_NonSemanticGlobalDI, // OpExtInst with e.g. DebugSource, DebugTypeBasic.
42 MB_ExtFuncDecls, // OpFunction etc. to declare for external funcs.
43 NUM_MODULE_SECTIONS // Total number of sections requiring basic blocks.
44};
45
47 const bool IsSatisfiable;
48 const std::optional<Capability::Capability> Cap;
50 const VersionTuple MinVer; // 0 if no min version is required.
51 const VersionTuple MaxVer; // 0 if no max version is required.
52
54 std::optional<Capability::Capability> Cap = {},
57 : IsSatisfiable(IsSatisfiable), Cap(Cap), Exts(std::move(Exts)),
59 Requirements(Capability::Capability Cap) : Requirements(true, {Cap}) {}
60};
61
63private:
64 CapabilityList MinimalCaps;
65
66 // AllCaps and AvailableCaps are related but different. AllCaps is a subset of
67 // AvailableCaps. AvailableCaps is the complete set of capabilities that are
68 // available to the current target. AllCaps is the set of capabilities that
69 // are required by the current module.
71 DenseSet<unsigned> AvailableCaps;
72
74 VersionTuple MinVersion; // 0 if no min version is defined.
75 VersionTuple MaxVersion; // 0 if no max version is defined.
76 // Add capabilities to AllCaps, recursing through their implicitly declared
77 // capabilities too.
78 void recursiveAddCapabilities(const CapabilityList &ToPrune);
79
80 void initAvailableCapabilitiesForOpenCL(const SPIRVSubtarget &ST);
81 void initAvailableCapabilitiesForVulkan(const SPIRVSubtarget &ST);
82
83public:
85 void clear() {
86 MinimalCaps.clear();
87 AllCaps.clear();
88 AvailableCaps.clear();
89 AllExtensions.clear();
90 MinVersion = VersionTuple();
91 MaxVersion = VersionTuple();
92 }
93 const CapabilityList &getMinimalCapabilities() const { return MinimalCaps; }
95 return AllExtensions;
96 }
97 // Add a list of capabilities, ensuring AllCaps captures all the implicitly
98 // declared capabilities, and MinimalCaps has the minimal set of required
99 // capabilities (so all implicitly declared ones are removed).
100 void addCapabilities(const CapabilityList &ToAdd);
101 void addCapability(Capability::Capability ToAdd) { addCapabilities({ToAdd}); }
102 void addExtensions(const ExtensionList &ToAdd) {
103 AllExtensions.insert_range(ToAdd);
104 }
105 void addExtension(Extension::Extension ToAdd) { AllExtensions.insert(ToAdd); }
106 // Add the given requirements to the lists. If constraints conflict, or these
107 // requirements cannot be satisfied, then abort the compilation.
109 // Get requirement and add it to the list.
110 void getAndAddRequirements(SPIRV::OperandCategory::OperandCategory Category,
111 uint32_t i, const SPIRVSubtarget &ST);
112 // Check if all the requirements can be satisfied for the given subtarget, and
113 // if not abort compilation.
114 void checkSatisfiable(const SPIRVSubtarget &ST) const;
116 // Add the given capabilities to available and all their implicitly defined
117 // capabilities too.
119 bool isCapabilityAvailable(Capability::Capability Cap) const {
120 return AvailableCaps.contains(Cap);
121 }
122
123 // Remove capability ToRemove, but only if IfPresent is present.
124 void removeCapabilityIf(const Capability::Capability ToRemove,
125 const Capability::Capability IfPresent);
126};
127
129// Maps a local register to the corresponding global alias.
130using LocalToGlobalRegTable = std::map<Register, MCRegister>;
132 std::map<const MachineFunction *, LocalToGlobalRegTable>;
133
134// The struct contains results of the module analysis and methods
135// to access them.
138 MemoryModel::MemoryModel Mem;
139 AddressingModel::AddressingModel Addr;
140 SourceLanguage::SourceLanguage SrcLang;
143 // Maps ExtInstSet to corresponding ID register.
145 // Contains the list of all global OpVariables in the module.
147 // Maps functions to corresponding function ID registers.
149 // The set contains machine instructions which are necessary
150 // for correct MIR but will not be emitted in function bodies.
152 // The table contains global aliases of local registers for each machine
153 // function. The aliases are used to substitute local registers during
154 // code emission.
156 // The counter holds the maximum ID we have in the module.
157 unsigned MaxID;
158 // The array contains lists of MIs for each module section.
160 // The table maps MBB number to SPIR-V unique ID register.
162
164 assert(F && "Function is null");
165 auto FuncPtrRegPair = FuncMap.find(F);
166 return FuncPtrRegPair == FuncMap.end() ? MCRegister()
167 : FuncPtrRegPair->second;
168 }
169 MCRegister getExtInstSetReg(unsigned SetNum) { return ExtInstSetMap[SetNum]; }
170 InstrList &getMSInstrs(unsigned MSType) { return MS[MSType]; }
173 return InstrsToDelete.contains(MI);
174 }
176 MCRegister AliasReg) {
177 RegisterAliasTable[MF][Reg] = AliasReg;
178 }
180 auto &RegTable = RegisterAliasTable[MF];
181 auto RI = RegTable.find(Reg);
182 if (RI == RegTable.end()) {
183 return MCRegister();
184 }
185 return RI->second;
186 }
188 auto RI = RegisterAliasTable.find(MF);
189 if (RI == RegisterAliasTable.end())
190 return false;
191 return RI->second.find(Reg) != RI->second.end();
192 }
193 unsigned getNextID() { return MaxID++; }
195 return MCRegister((1U << 31) | getNextID());
196 }
198 auto Key = std::make_pair(MBB.getParent(), MBB.getNumber());
199 return BBNumToRegMap.contains(Key);
200 }
201 // Convert MBB's number to corresponding ID register.
203 auto Key = std::make_pair(MBB.getParent(), MBB.getNumber());
204 auto [It, Inserted] = BBNumToRegMap.try_emplace(Key);
205 if (Inserted)
206 It->second = getNextIDRegister();
207 return It->second;
208 }
209};
210} // namespace SPIRV
211
213using InstrTraces = std::set<InstrSignature>;
214using InstrGRegsMap = std::map<SmallVector<size_t>, unsigned>;
215
217 static char ID;
218
219public:
221 : ModulePass(ID), ST(nullptr), GR(nullptr), TII(nullptr), MMI(nullptr) {}
222
223 bool runOnModule(Module &M) override;
224 void getAnalysisUsage(AnalysisUsage &AU) const override;
226
227private:
228 void setBaseInfo(const Module &M);
229 void collectFuncNames(MachineInstr &MI, const Function *F);
230 void processOtherInstrs(const Module &M);
231 void numberRegistersGlobally(const Module &M);
232
233 // analyze dependencies to collect module scope definitions
234 void collectDeclarations(const Module &M);
235 void visitDecl(const MachineRegisterInfo &MRI, InstrGRegsMap &SignatureToGReg,
236 std::map<const Value *, unsigned> &GlobalToGReg,
237 const MachineFunction *MF, const MachineInstr &MI);
238 MCRegister handleVariable(const MachineFunction *MF, const MachineInstr &MI,
239 std::map<const Value *, unsigned> &GlobalToGReg);
240 MCRegister handleTypeDeclOrConstant(const MachineInstr &MI,
241 InstrGRegsMap &SignatureToGReg);
243 handleFunctionOrParameter(const MachineFunction *MF, const MachineInstr &MI,
244 std::map<const Value *, unsigned> &GlobalToGReg,
245 bool &IsFunDef);
246 void visitFunPtrUse(Register OpReg, InstrGRegsMap &SignatureToGReg,
247 std::map<const Value *, unsigned> &GlobalToGReg,
248 const MachineFunction *MF, const MachineInstr &MI);
249 bool isDeclSection(const MachineRegisterInfo &MRI, const MachineInstr &MI);
250
251 const SPIRVSubtarget *ST;
253 const SPIRVInstrInfo *TII;
255};
256} // namespace llvm
257#endif // LLVM_LIB_TARGET_SPIRV_SPIRVMODULEANALYSIS_H
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
ReachingDefAnalysis InstSet & ToRemove
MachineBasicBlock & MBB
This file defines the DenseMap class.
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition: MD5.cpp:55
Register Reg
spirv structurize SPIRV
This file defines the SmallSet class.
This file defines the SmallVector class.
Represent the analysis usage information of a pass.
Implements a dense probed hash-table based set.
Definition: DenseSet.h:263
Wrapper class representing physical registers. Should be passed by value.
Definition: MCRegister.h:33
Representation of each machine instruction.
Definition: MachineInstr.h:72
This class contains meta information specific to a module.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:255
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:67
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:134
void insert_range(Range &&R)
Definition: SmallSet.h:194
void clear()
Definition: SmallSet.h:209
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition: SmallSet.h:182
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
StringSet - A wrapper for StringMap that provides set-like functionality.
Definition: StringSet.h:25
Represents a version number in the form major[.minor[.subminor[.build]]].
Definition: VersionTuple.h:30
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition: DenseSet.h:169
std::map< const MachineFunction *, LocalToGlobalRegTable > RegisterAliasMapTy
std::map< Register, MCRegister > LocalToGlobalRegTable
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
std::set< InstrSignature > InstrTraces
std::map< SmallVector< size_t >, unsigned > InstrGRegsMap
static struct SPIRV::ModuleAnalysisInfo MAI
bool runOnModule(Module &M) override
runOnModule - Virtual method overriden by subclasses to process the module being operated on.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
SmallVector< const MachineInstr *, 4 > GlobalVarList
MCRegister getExtInstSetReg(unsigned SetNum)
bool hasMBBRegister(const MachineBasicBlock &MBB)
DenseMap< std::pair< const MachineFunction *, int >, MCRegister > BBNumToRegMap
DenseMap< unsigned, MCRegister > ExtInstSetMap
void setSkipEmission(const MachineInstr *MI)
DenseSet< const MachineInstr * > InstrsToDelete
bool hasRegisterAlias(const MachineFunction *MF, Register Reg)
DenseMap< const Function *, MCRegister > FuncMap
InstrList & getMSInstrs(unsigned MSType)
MCRegister getRegisterAlias(const MachineFunction *MF, Register Reg)
bool getSkipEmission(const MachineInstr *MI)
MCRegister getOrCreateMBBRegister(const MachineBasicBlock &MBB)
InstrList MS[NUM_MODULE_SECTIONS]
AddressingModel::AddressingModel Addr
void setRegisterAlias(const MachineFunction *MF, Register Reg, MCRegister AliasReg)
SourceLanguage::SourceLanguage SrcLang
MCRegister getFuncReg(const Function *F)
void addCapabilities(const CapabilityList &ToAdd)
bool isCapabilityAvailable(Capability::Capability Cap) const
void addExtensions(const ExtensionList &ToAdd)
void checkSatisfiable(const SPIRVSubtarget &ST) const
void getAndAddRequirements(SPIRV::OperandCategory::OperandCategory Category, uint32_t i, const SPIRVSubtarget &ST)
void addExtension(Extension::Extension ToAdd)
void initAvailableCapabilities(const SPIRVSubtarget &ST)
void removeCapabilityIf(const Capability::Capability ToRemove, const Capability::Capability IfPresent)
void addCapability(Capability::Capability ToAdd)
void addAvailableCaps(const CapabilityList &ToAdd)
const CapabilityList & getMinimalCapabilities() const
const SmallSet< Extension::Extension, 4 > & getExtensions() const
void addRequirements(const Requirements &Req)
Requirements(bool IsSatisfiable=false, std::optional< Capability::Capability > Cap={}, ExtensionList Exts={}, VersionTuple MinVer=VersionTuple(), VersionTuple MaxVer=VersionTuple())
const std::optional< Capability::Capability > Cap
Requirements(Capability::Capability Cap)