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"
26#include "llvm/CodeGen/Passes.h"
30#include "llvm/Pass.h"
38#include <optional>
39
40using namespace llvm;
41
72
73static Reloc::Model getEffectiveRelocModel(std::optional<Reloc::Model> RM) {
74 if (!RM)
75 return Reloc::PIC_;
76 return *RM;
77}
78
79// Pin SPIRVTargetObjectFile's vtables to this file.
81
83 StringRef CPU, StringRef FS,
85 std::optional<Reloc::Model> RM,
86 std::optional<CodeModel::Model> CM,
87 CodeGenOptLevel OL, bool JIT)
88 : CodeGenTargetMachineImpl(T, TT, CPU, FS, Options,
90 getEffectiveCodeModel(CM, CodeModel::Small), OL),
91 TLOF(std::make_unique<SPIRVTargetObjectFile>()),
92 Subtarget(TT, CPU.str(), FS.str(), *this) {
94 setGlobalISel(true);
95 setFastISel(false);
96 setO0WantsFastISel(false);
98}
99
100namespace {
101// SPIR-V Code Generator Pass Configuration Options.
102class SPIRVPassConfig : public TargetPassConfig {
103public:
104 SPIRVPassConfig(SPIRVTargetMachine &TM, PassManagerBase &PM)
105 : TargetPassConfig(TM, PM), TM(TM) {}
106
107 void addMachineSSAOptimization() override;
108 void addIRPasses() override;
109 void addISelPrepare() override;
110
111 bool addIRTranslator() override;
112 void addPreLegalizeMachineIR() override;
113 bool addLegalizeMachineIR() override;
114 bool addRegBankSelect() override;
115 bool addGlobalInstructionSelect() override;
116
117 FunctionPass *createTargetRegisterAllocator(bool) override;
118 void addFastRegAlloc() override {}
119 void addOptimizedRegAlloc() override {}
120
121 void addPostRegAlloc() override;
122 void addPreEmitPass2() override;
123
124private:
125 const SPIRVTargetMachine &TM;
126};
127} // namespace
128
129// We do not use physical registers, and maintain virtual registers throughout
130// the entire pipeline, so return nullptr to disable register allocation.
131FunctionPass *SPIRVPassConfig::createTargetRegisterAllocator(bool) {
132 return nullptr;
133}
134
135// A place to disable passes that may break CFG.
136void SPIRVPassConfig::addMachineSSAOptimization() {
138}
139
140// Disable passes that break from assuming no virtual registers exist.
141void SPIRVPassConfig::addPostRegAlloc() {
142 // Do not work with vregs instead of physical regs.
143 disablePass(&MachineCopyPropagationID);
144 disablePass(&PostRAMachineSinkingID);
145 disablePass(&PostRASchedulerID);
146 disablePass(&FuncletLayoutID);
147 disablePass(&StackMapLivenessID);
148 disablePass(&PatchableFunctionID);
149 disablePass(&ShrinkWrapID);
150 disablePass(&LiveDebugValuesID);
151 disablePass(&MachineLateInstrsCleanupID);
152 disablePass(&RemoveLoadsIntoFakeUsesID);
153
154 // Do not work with OpPhi.
155 disablePass(&BranchFolderPassID);
156 disablePass(&MachineBlockPlacementID);
157
159}
160
161void SPIRVPassConfig::addPreEmitPass2() {
163}
164
167 return TargetTransformInfo(std::make_unique<SPIRVTTIImpl>(this, F));
168}
169
171 return new SPIRVPassConfig(*this, PM);
172}
173
174// CSE can merge same-LLT values with different SPIR-V types.
178
179void SPIRVPassConfig::addIRPasses() {
181
183
184 if (TM.getSubtargetImpl()->isShader()) {
185 if (getOptLevel() != CodeGenOptLevel::None)
188 } else {
189 // Variadic function calls aren't supported in shader code.
190 // This needs to come before SPIRVPrepareFunctions because this
191 // may introduce intrinsic calls.
193 }
194
199}
200
201void SPIRVPassConfig::addISelPrepare() {
202 if (TM.getSubtargetImpl()->isShader()) {
203 // Vulkan does not allow address space casts. This pass is run to remove
204 // address space casts that can be removed.
205 // If an address space cast is not removed while targeting Vulkan, lowering
206 // will fail during MIR lowering.
208
209 // 1. Simplify loop for subsequent transformations. After this steps, loops
210 // have the following properties:
211 // - loops have a single entry edge (pre-header to loop header).
212 // - all loop exits are dominated by the loop pre-header.
213 // - loops have a single back-edge.
214 addPass(createLoopSimplifyPass());
215
216 // 2. Removes registers whose lifetime spans across basic blocks. Also
217 // removes phi nodes. This will greatly simplify the next steps.
218 addPass(createRegToMemWrapperPass());
219
220 // 3. Merge the convergence region exit nodes into one. After this step,
221 // regions are single-entry, single-exit. This will help determine the
222 // correct merge block.
224
225 // 4. Structurize.
227
228 // 5. Reduce the amount of variables required by pushing some operations
229 // back to virtual registers.
231 } else {
232 // Canonicalize loops so they have a single latch and preheader.
233 // This enables OpLoopMerge emission for non-shader targets.
234 addPass(createLoopSimplifyPass());
235 }
246}
247
248bool SPIRVPassConfig::addIRTranslator() {
249 addPass(new IRTranslatorLegacy(getOptLevel()));
250 return false;
251}
252
253void SPIRVPassConfig::addPreLegalizeMachineIR() {
256}
257
258// Use the default legalizer.
259bool SPIRVPassConfig::addLegalizeMachineIR() {
260 addPass(new LegalizerLegacy());
262 return false;
263}
264
265// Do not add the RegBankSelect pass, as we only ever need virtual registers.
266bool SPIRVPassConfig::addRegBankSelect() {
267 disablePass(&RegBankSelectLegacy::ID);
268 return false;
269}
270
271// Deprecated flag kept for backward compatibility. NSDI emission is now handled
272// by SPIRVNonSemanticDebugHandler, registered in SPIRVAsmPrinter::
273// doInitialization() when the module contains debug info (llvm.dbg.cu).
274// TODO: Remove this option after a deprecation period. Callers that used
275// -spv-emit-nonsemantic-debug-info should switch to -g.
277 "spv-emit-nonsemantic-debug-info",
278 cl::desc("Deprecated. Use -g to emit SPIR-V NonSemantic.Shader.DebugInfo "
279 "instructions"),
280 cl::init(false));
281
282// Add the custom SPIRVInstructionSelect from above.
283bool SPIRVPassConfig::addGlobalInstructionSelect() {
284 addPass(new InstructionSelectLegacy(getOptLevel(),
285 /*RequireRegBankSelection=*/false));
286 return false;
287}
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
This file declares the IRTranslator pass.
#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)
LLVM_ABI LLVM_EXTERNAL_VISIBILITY void LLVMInitializeSPIRVTarget()
static cl::opt< bool > SPVEnableNonSemanticDI("spv-emit-nonsemantic-debug-info", cl::desc("Deprecated. Use -g to emit SPIR-V NonSemantic.Shader.DebugInfo " "instructions"), cl::init(false))
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)
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
This pass is responsible for selecting generic machine instructions to target-specific instructions.
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...
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)
const SPIRVSubtarget * getSubtargetImpl() const
TargetTransformInfo getTargetTransformInfo(const Function &F) const override
Get a TargetTransformInfo implementation for the target.
TargetPassConfig * createPassConfig(PassManagerBase &PM) override
Create a pass configuration object to be used by addPassToEmitX methods for generating a pipeline of ...
CSEConfigBase * createCSEConfig() const override
GlobalISel CSEConfig for the new PM. Return NULL for the standard one.
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)
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 ...
Interfaces for registering analysis passes, producing common pass manager configurations,...
initializer< Ty > init(const Ty &Val)
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 &)
LLVM_ABI char & PatchableFunctionID
This pass implements the "patchable-function" attribute.
LLVM_ABI char & PostRASchedulerID
PostRAScheduler - This pass performs post register allocation scheduling.
LLVM_ABI char & RemoveLoadsIntoFakeUsesID
RemoveLoadsIntoFakeUses pass.
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()
LLVM_ABI char & ShrinkWrapID
ShrinkWrap pass. Look for the best place to insert save and restore.
LLVM_ABI char & MachineLateInstrsCleanupID
MachineLateInstrsCleanup - This pass removes redundant identical instructions after register allocati...
void initializeSPIRVLegalizeZeroSizeArraysLegacyPass(PassRegistry &)
ModulePass * createSPIRVFinalizeShaderLinkagePass(const SPIRVTargetMachine &TM)
ModulePass * createSPIRVPrepareGlobalsPass()
void initializeSPIRVEmitIntrinsicsLegacyPass(PassRegistry &)
LLVM_ABI char & StackMapLivenessID
StackMapLiveness - This pass analyses the register live-out set of stackmap/patchpoint intrinsics and...
LLVM_ABI char & FuncletLayoutID
This pass lays out funclets contiguously.
LLVM_ABI char & PostRAMachineSinkingID
This pass perform post-ra machine sink for COPY instructions.
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 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 &)
LLVM_ABI char & MachineCopyPropagationID
MachineCopyPropagation - This pass performs copy propagation on machine instructions.
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:878
RegisterTargetMachine - Helper template for registering a target machine implementation,...