LLVM 22.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"
14#include "SPIRV.h"
15#include "SPIRVCBufferAccess.h"
16#include "SPIRVGlobalRegistry.h"
18#include "SPIRVLegalizerInfo.h"
28#include "llvm/CodeGen/Passes.h"
32#include "llvm/Pass.h"
38#include <optional>
39
40using namespace llvm;
41
69
70static Reloc::Model getEffectiveRelocModel(std::optional<Reloc::Model> RM) {
71 if (!RM)
72 return Reloc::PIC_;
73 return *RM;
74}
75
76// Pin SPIRVTargetObjectFile's vtables to this file.
78
80 StringRef CPU, StringRef FS,
82 std::optional<Reloc::Model> RM,
83 std::optional<CodeModel::Model> CM,
84 CodeGenOptLevel OL, bool JIT)
85 : CodeGenTargetMachineImpl(T, TT.computeDataLayout(), TT, CPU, FS, Options,
87 getEffectiveCodeModel(CM, CodeModel::Small), OL),
88 TLOF(std::make_unique<SPIRVTargetObjectFile>()),
89 Subtarget(TT, CPU.str(), FS.str(), *this) {
91 setGlobalISel(true);
92 setFastISel(false);
93 setO0WantsFastISel(false);
95}
96
98#define GET_PASS_REGISTRY "SPIRVPassRegistry.def"
100}
101
102namespace {
103// SPIR-V Code Generator Pass Configuration Options.
104class SPIRVPassConfig : public TargetPassConfig {
105public:
106 SPIRVPassConfig(SPIRVTargetMachine &TM, PassManagerBase &PM)
107 : TargetPassConfig(TM, PM), TM(TM) {}
108
109 SPIRVTargetMachine &getSPIRVTargetMachine() const {
111 }
112 void addMachineSSAOptimization() override;
113 void addIRPasses() override;
114 void addISelPrepare() override;
115
116 bool addIRTranslator() override;
117 void addPreLegalizeMachineIR() override;
118 bool addLegalizeMachineIR() override;
119 bool addRegBankSelect() override;
120 bool addGlobalInstructionSelect() override;
121
122 FunctionPass *createTargetRegisterAllocator(bool) override;
123 void addFastRegAlloc() override {}
124 void addOptimizedRegAlloc() override {}
125
126 void addPostRegAlloc() override;
127 void addPreEmitPass() override;
128
129private:
130 const SPIRVTargetMachine &TM;
131};
132} // namespace
133
134// We do not use physical registers, and maintain virtual registers throughout
135// the entire pipeline, so return nullptr to disable register allocation.
136FunctionPass *SPIRVPassConfig::createTargetRegisterAllocator(bool) {
137 return nullptr;
138}
139
140// A place to disable passes that may break CFG.
141void SPIRVPassConfig::addMachineSSAOptimization() {
143}
144
145// Disable passes that break from assuming no virtual registers exist.
146void SPIRVPassConfig::addPostRegAlloc() {
147 // Do not work with vregs instead of physical regs.
148 disablePass(&MachineCopyPropagationID);
149 disablePass(&PostRAMachineSinkingID);
150 disablePass(&PostRASchedulerID);
151 disablePass(&FuncletLayoutID);
152 disablePass(&StackMapLivenessID);
153 disablePass(&PatchableFunctionID);
154 disablePass(&ShrinkWrapID);
155 disablePass(&LiveDebugValuesID);
156 disablePass(&MachineLateInstrsCleanupID);
157 disablePass(&RemoveLoadsIntoFakeUsesID);
158
159 // Do not work with OpPhi.
160 disablePass(&BranchFolderPassID);
161 disablePass(&MachineBlockPlacementID);
162
164}
165
168 return TargetTransformInfo(std::make_unique<SPIRVTTIImpl>(this, F));
169}
170
172 return new SPIRVPassConfig(*this, PM);
173}
174
175void SPIRVPassConfig::addIRPasses() {
177
181}
182
183void SPIRVPassConfig::addISelPrepare() {
184 if (TM.getSubtargetImpl()->isShader()) {
185 // Vulkan does not allow address space casts. This pass is run to remove
186 // address space casts that can be removed.
187 // If an address space cast is not removed while targeting Vulkan, lowering
188 // will fail during MIR lowering.
190
191 // 1. Simplify loop for subsequent transformations. After this steps, loops
192 // have the following properties:
193 // - loops have a single entry edge (pre-header to loop header).
194 // - all loop exits are dominated by the loop pre-header.
195 // - loops have a single back-edge.
196 addPass(createLoopSimplifyPass());
197
198 // 2. Removes registers whose lifetime spans across basic blocks. Also
199 // removes phi nodes. This will greatly simplify the next steps.
200 addPass(createRegToMemWrapperPass());
201
202 // 3. Merge the convergence region exit nodes into one. After this step,
203 // regions are single-entry, single-exit. This will help determine the
204 // correct merge block.
206
207 // 4. Structurize.
209
210 // 5. Reduce the amount of variables required by pushing some operations
211 // back to virtual registers.
213 }
220 addPass(createSPIRVEmitIntrinsicsPass(&TM));
224}
225
226bool SPIRVPassConfig::addIRTranslator() {
227 addPass(new IRTranslator(getOptLevel()));
228 return false;
229}
230
231void SPIRVPassConfig::addPreLegalizeMachineIR() {
234}
235
236// Use the default legalizer.
237bool SPIRVPassConfig::addLegalizeMachineIR() {
238 addPass(new Legalizer());
240 return false;
241}
242
243// Do not add the RegBankSelect pass, as we only ever need virtual registers.
244bool SPIRVPassConfig::addRegBankSelect() {
245 disablePass(&RegBankSelect::ID);
246 return false;
247}
248
250 "spv-emit-nonsemantic-debug-info",
251 cl::desc("Emit SPIR-V NonSemantic.Shader.DebugInfo.100 instructions"),
252 cl::Optional, cl::init(false));
253
254void SPIRVPassConfig::addPreEmitPass() {
256 getSPIRVTargetMachine().getTargetTriple().getVendor() == Triple::AMD) {
258 }
259}
260
261namespace {
262// A custom subclass of InstructionSelect, which is mostly the same except from
263// not requiring RegBankSelect to occur previously.
264class SPIRVInstructionSelect : public InstructionSelect {
265 // We don't use register banks, so unset the requirement for them
266 MachineFunctionProperties getRequiredProperties() const override {
267 return InstructionSelect::getRequiredProperties().resetRegBankSelected();
268 }
269};
270} // namespace
271
272// Add the custom SPIRVInstructionSelect from above.
273bool SPIRVPassConfig::addGlobalInstructionSelect() {
274 addPass(new SPIRVInstructionSelect());
275 return false;
276}
static Reloc::Model getEffectiveRelocModel()
#define LLVM_ABI
Definition Compiler.h:213
#define LLVM_EXTERNAL_VISIBILITY
Definition Compiler.h:132
DXIL Legalizer
This file declares the IRTranslator pass.
#define F(x, y, z)
Definition MD5.cpp:54
#define T
PassBuilder PB(Machine, PassOpts->PTO, std::nullopt, &PIC)
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("Emit SPIR-V NonSemantic.Shader.DebugInfo.100 instructions"), cl::Optional, cl::init(false))
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static TableGen::Emitter::OptClass< SkeletonEmitter > X("gen-skeleton-class", "Generate example skeleton class")
Target-Independent Code Generator Pass Configuration Options pass.
CodeGenTargetMachineImpl(const Target &T, StringRef DataLayoutString, 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:314
This pass is responsible for selecting generic machine instructions to target-specific instructions.
MachineFunctionProperties getRequiredProperties() const override
This class provides access to building LLVM's passes.
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
void registerPassBuilderCallbacks(PassBuilder &PB) override
Allow the target to modify the pass pipeline.
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 ...
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
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:47
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.
Definition Types.h:26
ModulePass * createSPIRVPushConstantAccessLegacyPass(SPIRVTargetMachine *TM)
void initializeSPIRVEmitIntrinsicsPass(PassRegistry &)
FunctionPass * createSPIRVStructurizerPass()
LLVM_ABI FunctionPass * createPromoteMemoryToRegisterPass()
Definition Mem2Reg.cpp:114
MachineFunctionPass * createSPIRVEmitNonSemanticDIPass(SPIRVTargetMachine *TM)
Target & getTheSPIRV32Target()
ModulePass * createSPIRVEmitIntrinsicsPass(SPIRVTargetMachine *TM)
void initializeSPIRVPrepareFunctionsPass(PassRegistry &)
LLVM_ABI FunctionPass * createRegToMemWrapperPass()
Definition Reg2Mem.cpp:146
FunctionPass * createSPIRVPreLegalizerPass()
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 initializeSPIRVMergeRegionExitTargetsPass(PassRegistry &)
FunctionPass * createSPIRVStripConvergenceIntrinsicsPass()
void initializeSPIRVPreLegalizerCombinerPass(PassRegistry &)
LLVM_ABI char & LiveDebugValuesID
LiveDebugValues pass.
void initializeSPIRVLegalizePointerCastPass(PassRegistry &)
FunctionPass * createSPIRVPreLegalizerCombiner()
void initializeSPIRVModuleAnalysisPass(PassRegistry &)
static Reloc::Model getEffectiveRelocModel(std::optional< Reloc::Model > RM)
FunctionPass * createSPIRVPostLegalizerPass()
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 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 * createSPIRVPrepareGlobalsPass()
void initializeSPIRVRegularizerPass(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.
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:82
Target & getTheSPIRV64Target()
ModulePass * createSPIRVLegalizeZeroSizeArraysPass(const SPIRVTargetMachine &TM)
void initializeSPIRVPostLegalizerPass(PassRegistry &)
void initializeSPIRVCBufferAccessLegacyPass(PassRegistry &)
ModulePass * createSPIRVCBufferAccessLegacyPass()
LLVM_ABI void initializeGlobalISel(PassRegistry &)
Initialize all passes linked into the GlobalISel library.
Target & getTheSPIRVLogicalTarget()
void initializeSPIRVAsmPrinterPass(PassRegistry &)
FunctionPass * createSPIRVRegularizerPass()
void initializeSPIRVStructurizerPass(PassRegistry &)
void initializeSPIRVEmitNonSemanticDIPass(PassRegistry &)
FunctionPass * createSPIRVMergeRegionExitTargetsPass()
LLVM_ABI FunctionPass * createInferAddressSpacesPass(unsigned AddressSpace=~0u)
void initializeSPIRVPreLegalizerPass(PassRegistry &)
void initializeSPIRVConvergenceRegionAnalysisWrapperPassPass(PassRegistry &)
LLVM_ABI char & MachineBlockPlacementID
MachineBlockPlacement - This pass places basic blocks based on branch probabilities.
LLVM_ABI char & BranchFolderPassID
BranchFolding - This pass performs machine code CFG based optimizations to delete branches to branche...
ModulePass * createSPIRVPrepareFunctionsPass(const SPIRVTargetMachine &TM)
void initializeSPIRVPrepareGlobalsPass(PassRegistry &)
FunctionPass * createSPIRVLegalizePointerCastPass(SPIRVTargetMachine *TM)
LLVM_ABI Pass * createLoopSimplifyPass()
LLVM_ABI char & MachineCopyPropagationID
MachineCopyPropagation - This pass performs copy propagation on machine instructions.
void initializeSPIRVStripConvergentIntrinsicsPass(PassRegistry &)
ModulePass * createSPIRVLegalizeImplicitBindingPass()
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:870
RegisterTargetMachine - Helper template for registering a target machine implementation,...