LLVM 24.0.0git
SPIRVCtorDtorLowering.cpp
Go to the documentation of this file.
1//===-- SPIRVCtorDtorLowering.cpp - Handle global ctors and dtors --------===//
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// This pass creates a unified init and fini kernel with the required metadata
10// to call global constructors and destructors on SPIR-V targets.
11//
12//===----------------------------------------------------------------------===//
13
14#include "SPIRV.h"
15#include "SPIRVSubtarget.h"
18#include "llvm/IR/CallingConv.h"
19#include "llvm/IR/Constants.h"
20#include "llvm/IR/Function.h"
22#include "llvm/IR/IRBuilder.h"
23#include "llvm/IR/Module.h"
24#include "llvm/IR/Value.h"
25#include "llvm/Pass.h"
26#include "llvm/Support/MD5.h"
29
30using namespace llvm;
31
32#define DEBUG_TYPE "spirv-lower-ctor-dtor"
33
34namespace {
35std::string getHash(StringRef Str) {
36 llvm::MD5 Hasher;
38 Hasher.update(Str);
39 Hasher.final(Hash);
40 return llvm::utohexstr(Hash.low(), /*LowerCase=*/true);
41}
42
43void addKernelAttrs(Function *F) {
44 F->setCallingConv(CallingConv::SPIR_KERNEL);
45 F->addFnAttr("uniform-work-group-size", "true");
46}
47
48Function *createInitOrFiniKernelFunction(Module &M, bool IsCtor) {
49 StringRef InitOrFiniKernelName =
50 IsCtor ? "spirv$device$init" : "spirv$device$fini";
51 if (M.getFunction(InitOrFiniKernelName))
52 return nullptr;
53
54 Function *InitOrFiniKernel = Function::createWithDefaultAttr(
55 FunctionType::get(Type::getVoidTy(M.getContext()), false),
56 GlobalValue::WeakODRLinkage, 0, InitOrFiniKernelName, &M);
57 addKernelAttrs(InitOrFiniKernel);
58
59 return InitOrFiniKernel;
60}
61
62// We create the IR required to call each callback in this section. This is
63// equivalent to the following code. Normally, the linker would provide us with
64// the definitions of the init and fini array sections. The 'spirv-link' linker
65// does not do this so initializing these values is done by the offload runtime.
66//
67// extern "C" void **__init_array_start = nullptr;
68// extern "C" void **__init_array_end = nullptr;
69// extern "C" void **__fini_array_start = nullptr;
70// extern "C" void **__fini_array_end = nullptr;
71//
72// using InitCallback = void();
73// using FiniCallback = void();
74//
75// void call_init_array_callbacks() {
76// for (auto start = __init_array_start; start != __init_array_end; ++start)
77// reinterpret_cast<InitCallback *>(*start)();
78// }
79//
80// void call_fini_array_callbacks() {
81// size_t fini_array_size = __fini_array_end - __fini_array_start;
82// for (size_t i = fini_array_size; i > 0; --i)
83// reinterpret_cast<FiniCallback *>(__fini_array_start[i - 1])();
84// }
85void createInitOrFiniCalls(Function &F, bool IsCtor) {
86 Module &M = *F.getParent();
87 LLVMContext &C = M.getContext();
88
89 IRBuilder<> IRB(BasicBlock::Create(C, "entry", &F));
90 auto *LoopBB = BasicBlock::Create(C, "while.entry", &F);
91 auto *ExitBB = BasicBlock::Create(C, "while.end", &F);
93
94 auto CreateGlobal = [&](const char *Name) -> GlobalVariable * {
95 auto *GV = new GlobalVariable(
97 /*isConstant=*/false, GlobalValue::WeakAnyLinkage,
99 /*InsertBefore=*/nullptr, GlobalVariable::NotThreadLocal,
100 /*AddressSpace=*/SPIRVAS::CrossWorkgroup);
101 GV->setVisibility(GlobalVariable::ProtectedVisibility);
102 return GV;
103 };
104
105 auto *Begin = M.getOrInsertGlobal(
106 IsCtor ? "__init_array_start" : "__fini_array_start",
108 return CreateGlobal(IsCtor ? "__init_array_start"
109 : "__fini_array_start");
110 }));
111 auto *End = M.getOrInsertGlobal(
112 IsCtor ? "__init_array_end" : "__fini_array_end",
114 return CreateGlobal(IsCtor ? "__init_array_end" : "__fini_array_end");
115 }));
116 auto *CallBackTy = FunctionType::get(IRB.getVoidTy(), {});
117
118 // The destructor array must be called in reverse order. Get an expression to
119 // the end of the array and iterate backwards in that case.
120 Value *BeginVal = IRB.CreateLoad(Begin->getType(), Begin, "begin");
121 Value *EndVal = IRB.CreateLoad(Begin->getType(), End, "stop");
122 if (!IsCtor) {
123 Value *OldBeginVal = BeginVal;
124 BeginVal =
128 "start");
129 EndVal = OldBeginVal;
130 }
131 IRB.CreateCondBr(
132 IRB.CreateCmp(IsCtor ? ICmpInst::ICMP_NE : ICmpInst::ICMP_UGE, BeginVal,
133 EndVal),
134 LoopBB, ExitBB);
135 IRB.SetInsertPoint(LoopBB);
136 auto *CallBackPHI = IRB.CreatePHI(PtrTy, 2, "ptr");
137 auto *CallBack = IRB.CreateLoad(IRB.getPtrTy(F.getAddressSpace()),
138 CallBackPHI, "callback");
139 IRB.CreateCall(CallBackTy, CallBack);
140 auto *NewCallBack =
141 IRB.CreateConstGEP1_64(PtrTy, CallBackPHI, IsCtor ? 1 : -1, "next");
142 auto *EndCmp = IRB.CreateCmp(IsCtor ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_ULT,
143 NewCallBack, EndVal, "end");
144 CallBackPHI->addIncoming(BeginVal, &F.getEntryBlock());
145 CallBackPHI->addIncoming(NewCallBack, LoopBB);
146 IRB.CreateCondBr(EndCmp, ExitBB, LoopBB);
147 IRB.SetInsertPoint(ExitBB);
148 IRB.CreateRetVoid();
149}
150
151bool createInitOrFiniGlobals(const SPIRVOptions &CLOpts, Module &M,
152 GlobalVariable *GV, bool IsCtor) {
154 if (!GA || GA->getNumOperands() == 0)
155 return false;
156
157 // SPIR-V has no way to emit variables at specific sections or support for
158 // the traditional constructor sections. Instead, we emit mangled global
159 // names so the runtime can build the list manually.
160 for (Value *V : GA->operands()) {
161 auto *CS = cast<ConstantStruct>(V);
162 auto *F = cast<Constant>(CS->getOperand(1));
163 uint64_t Priority = cast<ConstantInt>(CS->getOperand(0))->getSExtValue();
164 std::string PriorityStr = "." + std::to_string(Priority);
165 // We append a semi-unique hash and the priority to the global name.
166 std::string GlobalID = !CLOpts.lower_global_ctor_dtor_id.empty()
167 ? CLOpts.lower_global_ctor_dtor_id.str()
168 : getHash(M.getSourceFileName());
169 std::string NameStr =
170 ((IsCtor ? "__init_array_object_" : "__fini_array_object_") +
171 F->getName() + "_" + GlobalID + "_" + std::to_string(Priority))
172 .str();
173 llvm::transform(NameStr, NameStr.begin(),
174 [](char c) { return c == '.' ? '_' : c; });
175
176 auto *GV = new GlobalVariable(M, F->getType(), /*IsConstant=*/true,
179 /*AddressSpace=*/SPIRVAS::CrossWorkgroup);
180 GV->setSection(IsCtor ? ".init_array" + PriorityStr
181 : ".fini_array" + PriorityStr);
183 }
184
185 return true;
186}
187
188bool createInitOrFiniKernel(const SPIRVOptions &CLOpts, Module &M,
189 StringRef GlobalName, bool IsCtor) {
190 GlobalVariable *GV = M.getGlobalVariable(GlobalName);
191 if (!GV || !GV->hasInitializer())
192 return false;
193
194 if (!createInitOrFiniGlobals(CLOpts, M, GV, IsCtor))
195 return false;
196
197 if (!CLOpts.emit_init_fini_kernel)
198 return true;
199
200 Function *InitOrFiniKernel = createInitOrFiniKernelFunction(M, IsCtor);
201 if (!InitOrFiniKernel)
202 return false;
203
204 createInitOrFiniCalls(*InitOrFiniKernel, IsCtor);
205
206 GV->eraseFromParent();
207 return true;
208}
209
210bool lowerCtorsAndDtors(Module &M) {
211 // Logical SPIR-V (shader) modules have no notion of function pointers or
212 // device-side init/fini kernels.
213 if (M.getTargetTriple().isSPIRVLogical())
214 return false;
215
216 const SPIRVOptions &CLOpts =
217 M.getContext().getLibraryOptions().get<SPIRVOptions>();
218 bool Modified = false;
219 Modified |=
220 createInitOrFiniKernel(CLOpts, M, "llvm.global_ctors", /*IsCtor =*/true);
221 Modified |=
222 createInitOrFiniKernel(CLOpts, M, "llvm.global_dtors", /*IsCtor =*/false);
223 return Modified;
224}
225
226class SPIRVCtorDtorLoweringLegacy final : public ModulePass {
227public:
228 static char ID;
229 SPIRVCtorDtorLoweringLegacy() : ModulePass(ID) {}
230 bool runOnModule(Module &M) override { return lowerCtorsAndDtors(M); }
231};
232
233} // End anonymous namespace
234
240
241char SPIRVCtorDtorLoweringLegacy::ID = 0;
242INITIALIZE_PASS(SPIRVCtorDtorLoweringLegacy, DEBUG_TYPE,
243 "SPIRV lower ctors and dtors", false, false)
244
246 return new SPIRVCtorDtorLoweringLegacy();
247}
uint64_t uint64_t
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define DEBUG_TYPE
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
SPIR-V address space definition.
This file contains some functions that are useful when dealing with strings.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
ConstantArray - Constant Array Declarations.
Definition Constants.h:590
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * createWithDefaultAttr(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Creates a function with some attributes recorded in llvm.module.flags and the LLVMContext applied.
Definition Function.cpp:372
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
Definition Globals.cpp:348
@ ProtectedVisibility
The GV is protected.
Definition GlobalValue.h:70
void setVisibility(VisibilityTypes V)
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:58
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition GlobalValue.h:57
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
LLVM_ABI void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Globals.cpp:609
Value * CreateConstGEP1_64(Type *Ty, Value *Ptr, uint64_t Idx0, const Twine &Name="")
Definition IRBuilder.h:2057
CondBrInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
Definition IRBuilder.h:1218
Value * CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
Definition IRBuilder.h:2021
Value * CreateCmp(CmpInst::Predicate Pred, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2595
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Definition IRBuilder.h:2626
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition IRBuilder.h:1913
ReturnInst * CreateRetVoid()
Create a 'ret void' instruction.
Definition IRBuilder.h:1189
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2640
PointerType * getPtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer.
Definition IRBuilder.h:571
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:197
Type * getVoidTy()
Fetch the type representing void.
Definition IRBuilder.h:566
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Updates the hash for the byte stream provided.
Definition MD5.cpp:188
LLVM_ABI void final(MD5Result &Result)
Finishes off the hash and puts the result in result.
Definition MD5.cpp:237
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:253
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:295
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:267
op_range operands()
Definition User.h:267
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
An efficient, type-erasing, non-owning reference to a callable.
@ SPIR_KERNEL
Used for SPIR kernel functions.
This is an optimization pass for GlobalISel generic memory operations.
ModulePass * createSPIRVCtorDtorLoweringLegacyPass()
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
std::string utohexstr(uint64_t X, bool LowerCase=false, unsigned Width=0)
OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere.
Definition STLExtras.h:2042
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
uint64_t low() const
Definition MD5.h:47