LLVM 24.0.0git
SPIRVTargetMachine.cpp
Go to the documentation of this file.
1//===- SPIRVTargetMachine.cpp - Define TargetMachine for SPIR-V -*- 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// Implements the info about SPIR-V target spec.
10//
11//===----------------------------------------------------------------------===//
12
13#include "SPIRVTargetMachine.h"
15#include "SPIRV.h"
16#include "SPIRVGlobalRegistry.h"
17#include "SPIRVLegalizerInfo.h"
28#include "llvm/CodeGen/Passes.h"
33#include "llvm/Pass.h"
41#include <optional>
42
43using namespace llvm;
44
46 // Register the target.
51
77}
78
79static Reloc::Model getEffectiveRelocModel(std::optional<Reloc::Model> RM) {
80 if (!RM)
81 return Reloc::PIC_;
82 return *RM;
83}
84
85// Pin SPIRVTargetObjectFile's vtables to this file.
87
89 StringRef CPU, StringRef FS,
91 std::optional<Reloc::Model> RM,
92 std::optional<CodeModel::Model> CM,
93 CodeGenOptLevel OL, bool JIT)
94 : CodeGenTargetMachineImpl(T, TT, CPU, FS, Options,
96 getEffectiveCodeModel(CM, CodeModel::Small), OL),
97 CLOpts(cl::LibraryOptionsContext::get<SPIRVOptions>(
98 Options.MCOptions.LibraryOptions)),
99 TLOF(std::make_unique<SPIRVTargetObjectFile>()),
100 Subtarget(TT, CPU.str(), FS.str(), *this) {
101 initAsmInfo();
103 setGlobalISel(true);
104 setFastISel(false);
105 setO0WantsFastISel(false);
107}
108
109namespace {
110// SPIR-V Code Generator Pass Configuration Options.
111class SPIRVPassConfig : public TargetPassConfig {
112public:
113 SPIRVPassConfig(SPIRVTargetMachine &TM, PassManagerBase &PM)
114 : TargetPassConfig(TM, PM), TM(TM) {
115 // Logical SPIR-V cannot express the pointer induction variables that loop
116 // strength reduction creates.
118 EnableLoopStrengthReduce = false;
119 }
120
121 void addMachineSSAOptimization() override;
122 void addIRPasses() override;
123 void addISelPrepare() override;
124
125 bool addIRTranslator() override;
126 void addPreLegalizeMachineIR() override;
127 bool addLegalizeMachineIR() override;
128 bool addRegBankSelect() override;
129 bool addGlobalInstructionSelect() override;
130
131 void addFastRegAlloc() override {}
132 void addOptimizedRegAlloc() override {}
133
134 void addPostRegAlloc() override;
135 void addPreEmitPass2() override;
136
137private:
138 const SPIRVTargetMachine &TM;
139};
140} // namespace
141
142// A place to disable passes that may break CFG.
143void SPIRVPassConfig::addMachineSSAOptimization() {
145}
146
147void SPIRVPassConfig::addPostRegAlloc() {
148 // Does not work with vregs instead of physical regs.
149 disablePass(&LiveDebugValuesID);
150
151 // Do not work with OpPhi.
152 disablePass(&BranchFolderPassID);
153 disablePass(&MachineBlockPlacementID);
154
156}
157
158void SPIRVPassConfig::addPreEmitPass2() {
160}
161
164 return TargetTransformInfo(std::make_unique<SPIRVTTIImpl>(this, F));
165}
166
168 return new SPIRVPassConfig(*this, PM);
169}
170
171// CSE can merge same-LLT values with different SPIR-V types.
175
180
185
188 SMDiagnostic &Error, SMRange &SourceRange) const {
189 const auto &YamlMFI =
190 static_cast<const yaml::SPIRVMachineFunctionInfo &>(MFI);
191 MachineFunction &MF = PFS.MF;
192 // SPIRVPrepareFunctions resolves the environment, but does not run on MIR.
193 // Resolve it once, before restoring types, because it resets the registry.
194 SPIRVSubtarget &ST =
195 *const_cast<SPIRVTargetMachine *>(this)->getMutableSubtargetImpl();
196 if (ST.getEnv() == SPIRVSubtarget::Unknown)
197 ST.resolveEnvFromModule(*MF.getFunction().getParent());
198 SPIRVGlobalRegistry *GR = ST.getSPIRVGlobalRegistry();
199 const SPIRVInstrInfo &TII = *ST.getInstrInfo();
200 const MachineRegisterInfo &MRI = MF.getRegInfo();
201
202 auto ParseVReg = [&](const yaml::StringValue &RegName, VRegInfo *&Info) {
203 if (!parseVirtualRegisterReference(PFS, Info, RegName.Value, Error))
204 return false;
205 SourceRange = RegName.SourceRange;
206 return true;
207 };
208 auto Diagnose = [&](const yaml::StringValue &RegName, StringRef Msg) {
209 const MemoryBuffer &Buffer =
210 *PFS.SM->getMemoryBuffer(PFS.SM->getMainFileID());
211 Error = SMDiagnostic(*PFS.SM, SMLoc(), Buffer.getBufferIdentifier(), 1,
212 static_cast<int>(RegName.Value.size()),
213 SourceMgr::DK_Error, Msg, RegName.Value, {}, {});
214 SourceRange = RegName.SourceRange;
215 return true;
216 };
217
218 for (const yaml::SPIRVVRegType &Entry : YamlMFI.VRegTypes) {
219 VRegInfo *RegInfo, *TypeInfo;
220 if (ParseVReg(Entry.Reg, RegInfo) || ParseVReg(Entry.Type, TypeInfo))
221 return true;
222 if (MRI.reg_empty(RegInfo->VReg))
223 return Diagnose(Entry.Reg, "virtual register is not used or defined");
224 const MachineInstr *TypeMI = MRI.getUniqueVRegDef(TypeInfo->VReg);
225 if (!TypeMI || !TII.isTypeDeclInstr(*TypeMI))
226 return Diagnose(Entry.Type, "expected a SPIR-V type register");
227 GR->assignSPIRVTypeToVReg(TypeMI, RegInfo->VReg, MF);
228 }
229 if (!YamlMFI.LastInsertedType.Value.empty()) {
230 VRegInfo *RegInfo;
231 if (ParseVReg(YamlMFI.LastInsertedType, RegInfo))
232 return true;
233 MachineInstr *MI = MRI.getUniqueVRegDef(RegInfo->VReg);
234 if (!MI)
235 return Diagnose(YamlMFI.LastInsertedType,
236 "virtual register is not defined");
237 GR->setLastInsertedType(MF, MI);
238 }
239 GR->restoreFromMIR(MF);
240 return false;
241}
242
243void SPIRVPassConfig::addIRPasses() {
245
247
249
250 if (TM.getSubtargetImpl()->isShader()) {
251 if (getOptLevel() != CodeGenOptLevel::None)
254 } else {
255 // Variadic function calls aren't supported in shader code.
256 // This needs to come before SPIRVPrepareFunctions because this
257 // may introduce intrinsic calls.
259 }
260
263 // LowerDynamicLocalMemoryPass must run after ctor/dtor lowering:
264 // the kernels CtorDtorLowering creates also need the trailing dynamic local
265 // memory argument, since runtimes pass it to every kernel of a module using
266 // such memory.
270}
271
272void SPIRVPassConfig::addISelPrepare() {
273 if (TM.getSubtargetImpl()->isShader()) {
274 // Vulkan does not allow address space casts. This pass is run to remove
275 // address space casts that can be removed.
276 // If an address space cast is not removed while targeting Vulkan, lowering
277 // will fail during MIR lowering.
279
280 // 1. Simplify loop for subsequent transformations. After this steps, loops
281 // have the following properties:
282 // - loops have a single entry edge (pre-header to loop header).
283 // - all loop exits are dominated by the loop pre-header.
284 // - loops have a single back-edge.
285 addPass(createLoopSimplifyPass());
286
287 // 2. Removes registers whose lifetime spans across basic blocks. Also
288 // removes phi nodes. This will greatly simplify the next steps.
289 addPass(createRegToMemWrapperPass());
290
291 // 3. Merge the convergence region exit nodes into one. After this step,
292 // regions are single-entry, single-exit. This will help determine the
293 // correct merge block.
295
296 // 4. Structurize.
298
299 // 5. Reduce the amount of variables required by pushing some operations
300 // back to virtual registers.
302 } else {
303 // Canonicalize loops so they have a single latch and preheader.
304 // This enables OpLoopMerge emission for non-shader targets.
305 addPass(createLoopSimplifyPass());
306 }
317}
318
319bool SPIRVPassConfig::addIRTranslator() {
320 addPass(new IRTranslatorLegacy(getOptLevel()));
321 return false;
322}
323
324void SPIRVPassConfig::addPreLegalizeMachineIR() {
327}
328
329// Use the default legalizer.
330bool SPIRVPassConfig::addLegalizeMachineIR() {
331 addPass(new LegalizerLegacy());
333 return false;
334}
335
336// Do not add the RegBankSelect pass, as we only ever need virtual registers.
337bool SPIRVPassConfig::addRegBankSelect() {
338 disablePass(&RegBankSelectLegacy::ID);
339 return false;
340}
341
342// Add the custom SPIRVInstructionSelect from above.
343bool SPIRVPassConfig::addGlobalInstructionSelect() {
344 addPass(new InstructionSelectLegacy(getOptLevel()));
345 return false;
346}
const AArch64InstrInfo & TII
static Reloc::Model getEffectiveRelocModel()
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
#define LLVM_ABI
Definition Compiler.h:211
#define LLVM_EXTERNAL_VISIBILITY
Definition Compiler.h:132
IRTranslator LLVM IR MI
This file declares the IRTranslator pass.
#define RegName(no)
#define F(x, y, z)
Definition MD5.cpp:54
#define T
This file describes the interface of the MachineFunctionPass responsible for assigning the generic vi...
const GCNTargetMachine & getTM(const GCNSubtarget *STI)
const char * Msg
LLVM_ABI LLVM_EXTERNAL_VISIBILITY void LLVMInitializeSPIRVTarget()
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
Target-Independent Code Generator Pass Configuration Options pass.
CodeGenTargetMachineImpl(const Target &T, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOptLevel OL)
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
Module * getParent()
Get the module that this global value is contained inside of...
This pass is responsible for selecting generic machine instructions to target-specific instructions.
static void setUseExtended(bool Enable)
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Representation of each machine instruction.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
This interface provides simple read-only access to a block of memory, and provides simple methods for...
virtual StringRef getBufferIdentifier() const
Return an identifier for this buffer, typically the filename it was read from.
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition SourceMgr.h:307
Represents a location in source code.
Definition SMLoc.h:22
Represents a range in source code.
Definition SMLoc.h:47
void assignSPIRVTypeToVReg(SPIRVTypeInst Type, Register VReg, const MachineFunction &MF)
void setLastInsertedType(const MachineFunction &MF, MachineInstr *MI)
void restoreFromMIR(const MachineFunction &MF)
bool isLogicalSPIRV() const
SPIRVTargetMachine(const Target &T, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, std::optional< Reloc::Model > RM, std::optional< CodeModel::Model > CM, CodeGenOptLevel OL, bool JIT)
yaml::MachineFunctionInfo * convertFuncInfoToYAML(const MachineFunction &MF) const override
Allocate and initialize an instance of the YAML representation of the MachineFunctionInfo.
const SPIRVSubtarget * getSubtargetImpl() const
TargetTransformInfo getTargetTransformInfo(const Function &F) const override
Get a TargetTransformInfo implementation for the target.
bool parseMachineFunctionInfo(const yaml::MachineFunctionInfo &, PerFunctionMIParsingState &PFS, SMDiagnostic &Error, SMRange &SourceRange) const override
Parse out the target's MachineFunctionInfo from the YAML reprsentation.
yaml::MachineFunctionInfo * createDefaultFuncInfoYAML() const override
Allocate and return a default initialized instance of the YAML representation for the MachineFunction...
TargetPassConfig * createPassConfig(PassManagerBase &PM) override
Create a pass configuration object to be used by addPassToEmitX methods for generating a pipeline of ...
SPIRVSubtarget * getMutableSubtargetImpl()
CSEConfigBase * createCSEConfig() const override
GlobalISel CSEConfig for the new PM. Return NULL for the standard one.
unsigned getMainFileID() const
Definition SourceMgr.h:150
const MemoryBuffer * getMemoryBuffer(unsigned i) const
Definition SourceMgr.h:141
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
void setFastISel(bool Enable)
void setRequiresStructuredCFG(bool Value)
void setGlobalISel(bool Enable)
TargetOptions Options
void setO0WantsFastISel(bool Enable)
std::unique_ptr< const MCRegisterInfo > MRI
Target-Independent Code Generator Pass Configuration Options.
virtual void addPostRegAlloc()
This method may be implemented by targets that want to run passes after register allocation pass pipe...
virtual void addIRPasses()
Add common target configurable passes that perform LLVM IR to IR transforms following machine indepen...
virtual void addMachineSSAOptimization()
addMachineSSAOptimization - Add standard passes that optimize machine instructions in SSA form.
virtual void addISelPrepare()
Add common passes that perform LLVM IR to IR transforms in preparation for instruction selection.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
PassManagerBase - An abstract interface to allow code to add passes to a pass manager without having ...
Registers T with cl::parseCommandLineOptions.
Interfaces for registering analysis passes, producing common pass manager configurations,...
This namespace contains all of the command line option processing machinery.
This is an optimization pass for GlobalISel generic memory operations.
ModulePass * createSPIRVPushConstantAccessLegacyPass(SPIRVTargetMachine *TM)
ModulePass * createSPIRVCtorDtorLoweringLegacyPass()
FunctionPass * createSPIRVStructurizerPass()
ModulePass * createSPIRVEmitIntrinsicsPass(const SPIRVTargetMachine &TM)
ModulePass * createSPIRVLowerResourceNamesLegacyPass()
LLVM_ABI FunctionPass * createPromoteMemoryToRegisterPass()
Definition Mem2Reg.cpp:114
Target & getTheSPIRV32Target()
LLVM_ABI FunctionPass * createRegToMemWrapperPass()
Definition Reg2Mem.cpp:139
void initializeSPIRVPushConstantAccessLegacyPass(PassRegistry &)
void initializeSPIRVLegalizePointerCastLegacyPass(PassRegistry &)
void initializeSPIRVPrepareFunctionsLegacyPass(PassRegistry &)
ModulePass * createSPIRVRemoveUnusedResourcesLegacyPass()
LLVM_ABI char & LiveDebugValuesID
LiveDebugValues pass.
static Reloc::Model getEffectiveRelocModel(std::optional< Reloc::Model > RM)
void initializeSPIRVLowerDynamicLocalMemoryLegacyPass(PassRegistry &)
FunctionPass * createSPIRVPreLegalizerCombinerLegacyPass()
CodeModel::Model getEffectiveCodeModel(std::optional< CodeModel::Model > CM, CodeModel::Model Default)
Helper method for getting the code model, returning Default if CM does not have a value.
LLVM_ABI ModulePass * createExpandVariadicsPass(ExpandVariadicsMode)
FunctionPass * createSPIRVPostLegalizerLegacyPass()
void initializeSPIRVLegalizeZeroSizeArraysLegacyPass(PassRegistry &)
ModulePass * createSPIRVFinalizeShaderLinkagePass(const SPIRVTargetMachine &TM)
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
ModulePass * createSPIRVPrepareGlobalsPass()
void initializeSPIRVEmitIntrinsicsLegacyPass(PassRegistry &)
FunctionPass * createSPIRVPrepareModuleAnalysisLegacyPass()
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:280
ModulePass * createSPIRVLowerDynamicLocalMemoryPass(const SPIRVTargetMachine &TM)
Target & getTheSPIRV64Target()
void initializeSPIRVPrepareModuleAnalysisLegacyPass(PassRegistry &)
ModulePass * createSPIRVLegalizeZeroSizeArraysPass(const SPIRVTargetMachine &TM)
LLVM_ABI FunctionPass * createStripConvergenceIntrinsicsPass()
void initializeSPIRVCBufferAccessLegacyPass(PassRegistry &)
ModulePass * createSPIRVCBufferAccessLegacyPass()
LLVM_ABI void initializeGlobalISel(PassRegistry &)
Initialize all passes linked into the GlobalISel library.
void initializeSPIRVPostLegalizerLegacyPass(PassRegistry &)
void initializeSPIRVModuleAnalysisWrapperPassPass(PassRegistry &)
void initializeSPIRVRemoveUnusedResourcesLegacyPass(PassRegistry &)
void initializeSPIRVPrepareGlobalsLegacyPass(PassRegistry &)
Target & getTheSPIRVLogicalTarget()
void initializeSPIRVAsmPrinterPass(PassRegistry &)
void initializeSPIRVRegularizerLegacyPass(PassRegistry &)
FunctionPass * createSPIRVRegularizerPass()
void initializeSPIRVStructurizerPass(PassRegistry &)
FunctionPass * createSPIRVMergeRegionExitTargetsPass()
LLVM_ABI FunctionPass * createInferAddressSpacesPass(unsigned AddressSpace=~0u)
void initializeSPIRVPreLegalizerCombinerLegacyPass(PassRegistry &)
void initializeSPIRVPreLegalizerLegacyPass(PassRegistry &)
FunctionPass * createSPIRVPreLegalizerLegacyPass()
void initializeSPIRVConvergenceRegionAnalysisWrapperPassPass(PassRegistry &)
LLVM_ABI char & MachineBlockPlacementID
MachineBlockPlacement - This pass places basic blocks based on branch probabilities.
LLVM_ABI bool parseVirtualRegisterReference(PerFunctionMIParsingState &PFS, VRegInfo *&Info, StringRef Src, SMDiagnostic &Error)
LLVM_ABI FunctionPass * createAtomicExpandLegacyPass()
AtomicExpandPass - At IR level this pass replace atomic instructions with __atomic_* library calls,...
LLVM_ABI char & BranchFolderPassID
BranchFolding - This pass performs machine code CFG based optimizations to delete branches to branche...
ModulePass * createSPIRVPrepareFunctionsPass(const SPIRVTargetMachine &TM)
FunctionPass * createSPIRVLegalizePointerCastPass(SPIRVTargetMachine *TM)
LLVM_ABI Pass * createLoopSimplifyPass()
ModulePass * createSPIRVLegalizeResourceBindingPass()
void initializeSPIRVCtorDtorLoweringLegacyPass(PassRegistry &)
void initializeSPIRVLowerResourceNamesLegacyPass(PassRegistry &)
void initializeSPIRVMergeRegionExitTargetsLegacyPass(PassRegistry &)
void initializeSPIRVLegalizeResourceBindingLegacyPass(PassRegistry &)
void initializeSPIRVFinalizeShaderLinkageLegacyPass(PassRegistry &)
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
RegisterTargetMachine - Helper template for registering a target machine implementation,...
Register VReg
Definition MIParser.h:48
Targets should override this in a way that mirrors the implementation of llvm::MachineFunctionInfo.
A wrapper around std::string which contains a source range that's being set during parsing.