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"
17#include "llvm/IR/CallingConv.h"
18#include "llvm/IR/Constants.h"
19#include "llvm/IR/Function.h"
21#include "llvm/IR/IRBuilder.h"
22#include "llvm/IR/Module.h"
23#include "llvm/IR/Value.h"
24#include "llvm/Pass.h"
26#include "llvm/Support/MD5.h"
30
31using namespace llvm;
32
33#define DEBUG_TYPE "spirv-lower-ctor-dtor"
34
36 GlobalStr("spirv-lower-global-ctor-dtor-id",
37 cl::desc("Override unique ID of ctor/dtor globals."),
38 cl::init(""), cl::Hidden);
39
40static cl::opt<bool>
41 CreateKernels("spirv-emit-init-fini-kernel",
42 cl::desc("Emit kernels to call ctor/dtor globals."),
43 cl::init(true), cl::Hidden);
44
45namespace {
46std::string getHash(StringRef Str) {
47 llvm::MD5 Hasher;
49 Hasher.update(Str);
50 Hasher.final(Hash);
51 return llvm::utohexstr(Hash.low(), /*LowerCase=*/true);
52}
53
54void addKernelAttrs(Function *F) {
55 F->setCallingConv(CallingConv::SPIR_KERNEL);
56 F->addFnAttr("uniform-work-group-size", "true");
57}
58
59Function *createInitOrFiniKernelFunction(Module &M, bool IsCtor) {
60 StringRef InitOrFiniKernelName =
61 IsCtor ? "spirv$device$init" : "spirv$device$fini";
62 if (M.getFunction(InitOrFiniKernelName))
63 return nullptr;
64
65 Function *InitOrFiniKernel = Function::createWithDefaultAttr(
66 FunctionType::get(Type::getVoidTy(M.getContext()), false),
67 GlobalValue::WeakODRLinkage, 0, InitOrFiniKernelName, &M);
68 addKernelAttrs(InitOrFiniKernel);
69
70 return InitOrFiniKernel;
71}
72
73// We create the IR required to call each callback in this section. This is
74// equivalent to the following code. Normally, the linker would provide us with
75// the definitions of the init and fini array sections. The 'spirv-link' linker
76// does not do this so initializing these values is done by the offload runtime.
77//
78// extern "C" void **__init_array_start = nullptr;
79// extern "C" void **__init_array_end = nullptr;
80// extern "C" void **__fini_array_start = nullptr;
81// extern "C" void **__fini_array_end = nullptr;
82//
83// using InitCallback = void();
84// using FiniCallback = void();
85//
86// void call_init_array_callbacks() {
87// for (auto start = __init_array_start; start != __init_array_end; ++start)
88// reinterpret_cast<InitCallback *>(*start)();
89// }
90//
91// void call_fini_array_callbacks() {
92// size_t fini_array_size = __fini_array_end - __fini_array_start;
93// for (size_t i = fini_array_size; i > 0; --i)
94// reinterpret_cast<FiniCallback *>(__fini_array_start[i - 1])();
95// }
96void createInitOrFiniCalls(Function &F, bool IsCtor) {
97 Module &M = *F.getParent();
98 LLVMContext &C = M.getContext();
99
100 IRBuilder<> IRB(BasicBlock::Create(C, "entry", &F));
101 auto *LoopBB = BasicBlock::Create(C, "while.entry", &F);
102 auto *ExitBB = BasicBlock::Create(C, "while.end", &F);
103 Type *PtrTy = IRB.getPtrTy(SPIRVAS::CrossWorkgroup);
104
105 auto CreateGlobal = [&](const char *Name) -> GlobalVariable * {
106 auto *GV = new GlobalVariable(
108 /*isConstant=*/false, GlobalValue::WeakAnyLinkage,
110 /*InsertBefore=*/nullptr, GlobalVariable::NotThreadLocal,
111 /*AddressSpace=*/SPIRVAS::CrossWorkgroup);
112 GV->setVisibility(GlobalVariable::ProtectedVisibility);
113 return GV;
114 };
115
116 auto *Begin = M.getOrInsertGlobal(
117 IsCtor ? "__init_array_start" : "__fini_array_start",
119 return CreateGlobal(IsCtor ? "__init_array_start"
120 : "__fini_array_start");
121 }));
122 auto *End = M.getOrInsertGlobal(
123 IsCtor ? "__init_array_end" : "__fini_array_end",
125 return CreateGlobal(IsCtor ? "__init_array_end" : "__fini_array_end");
126 }));
127 auto *CallBackTy = FunctionType::get(IRB.getVoidTy(), {});
128
129 // The destructor array must be called in reverse order. Get an expression to
130 // the end of the array and iterate backwards in that case.
131 Value *BeginVal = IRB.CreateLoad(Begin->getType(), Begin, "begin");
132 Value *EndVal = IRB.CreateLoad(Begin->getType(), End, "stop");
133 if (!IsCtor) {
134 Value *OldBeginVal = BeginVal;
135 BeginVal =
136 IRB.CreateInBoundsGEP(PointerType::getUnqual(C), EndVal,
139 "start");
140 EndVal = OldBeginVal;
141 }
142 IRB.CreateCondBr(
143 IRB.CreateCmp(IsCtor ? ICmpInst::ICMP_NE : ICmpInst::ICMP_UGE, BeginVal,
144 EndVal),
145 LoopBB, ExitBB);
146 IRB.SetInsertPoint(LoopBB);
147 auto *CallBackPHI = IRB.CreatePHI(PtrTy, 2, "ptr");
148 auto *CallBack = IRB.CreateLoad(IRB.getPtrTy(F.getAddressSpace()),
149 CallBackPHI, "callback");
150 IRB.CreateCall(CallBackTy, CallBack);
151 auto *NewCallBack =
152 IRB.CreateConstGEP1_64(PtrTy, CallBackPHI, IsCtor ? 1 : -1, "next");
153 auto *EndCmp = IRB.CreateCmp(IsCtor ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_ULT,
154 NewCallBack, EndVal, "end");
155 CallBackPHI->addIncoming(BeginVal, &F.getEntryBlock());
156 CallBackPHI->addIncoming(NewCallBack, LoopBB);
157 IRB.CreateCondBr(EndCmp, ExitBB, LoopBB);
158 IRB.SetInsertPoint(ExitBB);
159 IRB.CreateRetVoid();
160}
161
162bool createInitOrFiniGlobals(Module &M, GlobalVariable *GV, bool IsCtor) {
164 if (!GA || GA->getNumOperands() == 0)
165 return false;
166
167 // SPIR-V has no way to emit variables at specific sections or support for
168 // the traditional constructor sections. Instead, we emit mangled global
169 // names so the runtime can build the list manually.
170 for (Value *V : GA->operands()) {
171 auto *CS = cast<ConstantStruct>(V);
172 auto *F = cast<Constant>(CS->getOperand(1));
173 uint64_t Priority = cast<ConstantInt>(CS->getOperand(0))->getSExtValue();
174 std::string PriorityStr = "." + std::to_string(Priority);
175 // We append a semi-unique hash and the priority to the global name.
176 std::string GlobalID =
177 !GlobalStr.empty() ? GlobalStr : getHash(M.getSourceFileName());
178 std::string NameStr =
179 ((IsCtor ? "__init_array_object_" : "__fini_array_object_") +
180 F->getName() + "_" + GlobalID + "_" + std::to_string(Priority))
181 .str();
182 llvm::transform(NameStr, NameStr.begin(),
183 [](char c) { return c == '.' ? '_' : c; });
184
185 auto *GV = new GlobalVariable(M, F->getType(), /*IsConstant=*/true,
188 /*AddressSpace=*/SPIRVAS::CrossWorkgroup);
189 GV->setSection(IsCtor ? ".init_array" + PriorityStr
190 : ".fini_array" + PriorityStr);
192 }
193
194 return true;
195}
196
197bool createInitOrFiniKernel(Module &M, StringRef GlobalName, bool IsCtor) {
198 GlobalVariable *GV = M.getGlobalVariable(GlobalName);
199 if (!GV || !GV->hasInitializer())
200 return false;
201
202 if (!createInitOrFiniGlobals(M, GV, IsCtor))
203 return false;
204
205 if (!CreateKernels)
206 return true;
207
208 Function *InitOrFiniKernel = createInitOrFiniKernelFunction(M, IsCtor);
209 if (!InitOrFiniKernel)
210 return false;
211
212 createInitOrFiniCalls(*InitOrFiniKernel, IsCtor);
213
214 GV->eraseFromParent();
215 return true;
216}
217
218bool lowerCtorsAndDtors(Module &M) {
219 // Only run this pass for OpenMP offload compilation
221 return false;
222
223 bool Modified = false;
224 Modified |= createInitOrFiniKernel(M, "llvm.global_ctors", /*IsCtor =*/true);
225 Modified |= createInitOrFiniKernel(M, "llvm.global_dtors", /*IsCtor =*/false);
226 return Modified;
227}
228
229class SPIRVCtorDtorLoweringLegacy final : public ModulePass {
230public:
231 static char ID;
232 SPIRVCtorDtorLoweringLegacy() : ModulePass(ID) {}
233 bool runOnModule(Module &M) override { return lowerCtorsAndDtors(M); }
234};
235
236} // End anonymous namespace
237
243
244char SPIRVCtorDtorLoweringLegacy::ID = 0;
245INITIALIZE_PASS(SPIRVCtorDtorLoweringLegacy, DEBUG_TYPE,
246 "SPIRV lower ctors and dtors", false, false)
247
249 return new SPIRVCtorDtorLoweringLegacy();
250}
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
static cl::opt< bool > CreateKernels("nvptx-emit-init-fini-kernel", cl::desc("Emit kernels to call ctor/dtor globals."), cl::init(true), cl::Hidden)
static cl::opt< std::string > GlobalStr("nvptx-lower-global-ctor-dtor-id", cl::desc("Override unique ID of ctor/dtor globals."), cl::init(""), cl::Hidden)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
SPIR-V address space definition.
static cl::opt< std::string > GlobalStr("spirv-lower-global-ctor-dtor-id", cl::desc("Override unique ID of ctor/dtor globals."), cl::init(""), cl::Hidden)
static cl::opt< bool > CreateKernels("spirv-emit-init-fini-kernel", cl::desc("Emit kernels to call ctor/dtor globals."), cl::init(true), cl::Hidden)
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
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2909
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:233
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:300
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:272
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.
initializer< Ty > init(const Ty &Val)
LLVM_ABI bool isOpenMPDevice(Module &M)
Helper to determine if M is a OpenMP target offloading device module.
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