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
75}
76
77static Reloc::Model getEffectiveRelocModel(std::optional<Reloc::Model> RM) {
78 if (!RM)
79 return Reloc::PIC_;
80 return *RM;
81}
82
83// Pin SPIRVTargetObjectFile's vtables to this file.
85
87 StringRef CPU, StringRef FS,
89 std::optional<Reloc::Model> RM,
90 std::optional<CodeModel::Model> CM,
91 CodeGenOptLevel OL, bool JIT)
92 : CodeGenTargetMachineImpl(T, TT, CPU, FS, Options,
94 getEffectiveCodeModel(CM, CodeModel::Small), OL),
95 CLOpts(cl::LibraryOptionsContext::get<SPIRVOptions>(
96 Options.MCOptions.LibraryOptions)),
97 TLOF(std::make_unique<SPIRVTargetObjectFile>()),
98 Subtarget(TT, CPU.str(), FS.str(), *this) {
101 setGlobalISel(true);
102 setFastISel(false);
103 setO0WantsFastISel(false);
105}
106
107namespace {
108// SPIR-V Code Generator Pass Configuration Options.
109class SPIRVPassConfig : public TargetPassConfig {
110public:
111 SPIRVPassConfig(SPIRVTargetMachine &TM, PassManagerBase &PM)
112 : TargetPassConfig(TM, PM), TM(TM) {
113 // Logical SPIR-V cannot express the pointer induction variables that loop
114 // strength reduction creates.
116 EnableLoopStrengthReduce = false;
117 }
118
119 void addMachineSSAOptimization() override;
120 void addIRPasses() override;
121 void addISelPrepare() override;
122
123 bool addIRTranslator() override;
124 void addPreLegalizeMachineIR() override;
125 bool addLegalizeMachineIR() override;
126 bool addRegBankSelect() override;
127 bool addGlobalInstructionSelect() override;
128
129 void addFastRegAlloc() override {}
130 void addOptimizedRegAlloc() override {}
131
132 void addPostRegAlloc() override;
133 void addPreEmitPass2() override;
134
135private:
136 const SPIRVTargetMachine &TM;
137};
138} // namespace
139
140// A place to disable passes that may break CFG.
141void SPIRVPassConfig::addMachineSSAOptimization() {
143}
144
145void SPIRVPassConfig::addPostRegAlloc() {
146 // Does not work with vregs instead of physical regs.
147 disablePass(&LiveDebugValuesID);
148
149 // Do not work with OpPhi.
150 disablePass(&BranchFolderPassID);
151 disablePass(&MachineBlockPlacementID);
152
154}
155
156void SPIRVPassConfig::addPreEmitPass2() {
158}
159
162 return TargetTransformInfo(std::make_unique<SPIRVTTIImpl>(this, F));
163}
164
166 return new SPIRVPassConfig(*this, PM);
167}
168
169// CSE can merge same-LLT values with different SPIR-V types.
173
178
183
186 SMDiagnostic &Error, SMRange &SourceRange) const {
187 const auto &YamlMFI =
188 static_cast<const yaml::SPIRVMachineFunctionInfo &>(MFI);
189 MachineFunction &MF = PFS.MF;
190 // SPIRVPrepareFunctions resolves the environment, but does not run on MIR.
191 // Resolve it once, before restoring types, because it resets the registry.
192 SPIRVSubtarget &ST =
193 *const_cast<SPIRVTargetMachine *>(this)->getMutableSubtargetImpl();
194 if (ST.getEnv() == SPIRVSubtarget::Unknown)
195 ST.resolveEnvFromModule(*MF.getFunction().getParent());
196 SPIRVGlobalRegistry *GR = ST.getSPIRVGlobalRegistry();
197 const SPIRVInstrInfo &TII = *ST.getInstrInfo();
198 const MachineRegisterInfo &MRI = MF.getRegInfo();
199
200 auto ParseVReg = [&](const yaml::StringValue &RegName, VRegInfo *&Info) {
201 if (!parseVirtualRegisterReference(PFS, Info, RegName.Value, Error))
202 return false;
203 SourceRange = RegName.SourceRange;
204 return true;
205 };
206 auto Diagnose = [&](const yaml::StringValue &RegName, StringRef Msg) {
207 const MemoryBuffer &Buffer =
208 *PFS.SM->getMemoryBuffer(PFS.SM->getMainFileID());
209 Error = SMDiagnostic(*PFS.SM, SMLoc(), Buffer.getBufferIdentifier(), 1,
210 static_cast<int>(RegName.Value.size()),
211 SourceMgr::DK_Error, Msg, RegName.Value, {}, {});
212 SourceRange = RegName.SourceRange;
213 return true;
214 };
215
216 for (const yaml::SPIRVVRegType &Entry : YamlMFI.VRegTypes) {
217 VRegInfo *RegInfo, *TypeInfo;
218 if (ParseVReg(Entry.Reg, RegInfo) || ParseVReg(Entry.Type, TypeInfo))
219 return true;
220 if (MRI.reg_empty(RegInfo->VReg))
221 return Diagnose(Entry.Reg, "virtual register is not used or defined");
222 const MachineInstr *TypeMI = MRI.getUniqueVRegDef(TypeInfo->VReg);
223 if (!TypeMI || !TII.isTypeDeclInstr(*TypeMI))
224 return Diagnose(Entry.Type, "expected a SPIR-V type register");
225 GR->assignSPIRVTypeToVReg(TypeMI, RegInfo->VReg, MF);
226 }
227 GR->restoreFromMIR(MF);
228 return false;
229}
230
231void SPIRVPassConfig::addIRPasses() {
233
235
236 if (TM.getSubtargetImpl()->isShader()) {
237 if (getOptLevel() != CodeGenOptLevel::None)
240 } else {
241 // Variadic function calls aren't supported in shader code.
242 // This needs to come before SPIRVPrepareFunctions because this
243 // may introduce intrinsic calls.
245 }
246
251}
252
253void SPIRVPassConfig::addISelPrepare() {
254 if (TM.getSubtargetImpl()->isShader()) {
255 // Vulkan does not allow address space casts. This pass is run to remove
256 // address space casts that can be removed.
257 // If an address space cast is not removed while targeting Vulkan, lowering
258 // will fail during MIR lowering.
260
261 // 1. Simplify loop for subsequent transformations. After this steps, loops
262 // have the following properties:
263 // - loops have a single entry edge (pre-header to loop header).
264 // - all loop exits are dominated by the loop pre-header.
265 // - loops have a single back-edge.
266 addPass(createLoopSimplifyPass());
267
268 // 2. Removes registers whose lifetime spans across basic blocks. Also
269 // removes phi nodes. This will greatly simplify the next steps.
270 addPass(createRegToMemWrapperPass());
271
272 // 3. Merge the convergence region exit nodes into one. After this step,
273 // regions are single-entry, single-exit. This will help determine the
274 // correct merge block.
276
277 // 4. Structurize.
279
280 // 5. Reduce the amount of variables required by pushing some operations
281 // back to virtual registers.
283 } else {
284 // Canonicalize loops so they have a single latch and preheader.
285 // This enables OpLoopMerge emission for non-shader targets.
286 addPass(createLoopSimplifyPass());
287 }
298}
299
300bool SPIRVPassConfig::addIRTranslator() {
301 addPass(new IRTranslatorLegacy(getOptLevel()));
302 return false;
303}
304
305void SPIRVPassConfig::addPreLegalizeMachineIR() {
308}
309
310// Use the default legalizer.
311bool SPIRVPassConfig::addLegalizeMachineIR() {
312 addPass(new LegalizerLegacy());
314 return false;
315}
316
317// Do not add the RegBankSelect pass, as we only ever need virtual registers.
318bool SPIRVPassConfig::addRegBankSelect() {
319 disablePass(&RegBankSelectLegacy::ID);
320 return false;
321}
322
323// Add the custom SPIRVInstructionSelect from above.
324bool SPIRVPassConfig::addGlobalInstructionSelect() {
325 addPass(new InstructionSelectLegacy(getOptLevel()));
326 return false;
327}
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
const HexagonInstrInfo * TII
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 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)
LLVM_ABI FunctionPass * createPromoteMemoryToRegisterPass()
Definition Mem2Reg.cpp:114
Target & getTheSPIRV32Target()
LLVM_ABI FunctionPass * createRegToMemWrapperPass()
Definition Reg2Mem.cpp:140
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)
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
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 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.