LLVM 20.0.0git
LowerGlobalDtors.cpp
Go to the documentation of this file.
1//===-- LowerGlobalDtors.cpp - Lower @llvm.global_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/// \file
10/// Lower @llvm.global_dtors.
11///
12/// Implement @llvm.global_dtors by creating wrapper functions that are
13/// registered in @llvm.global_ctors and which contain a call to
14/// `__cxa_atexit` to register their destructor functions.
15///
16//===----------------------------------------------------------------------===//
17
19
20#include "llvm/IR/Constants.h"
22#include "llvm/IR/Intrinsics.h"
23#include "llvm/IR/Module.h"
25#include "llvm/Pass.h"
28#include <map>
29
30using namespace llvm;
31
32#define DEBUG_TYPE "lower-global-dtors"
33
34namespace {
35class LowerGlobalDtorsLegacyPass final : public ModulePass {
36 StringRef getPassName() const override {
37 return "Lower @llvm.global_dtors via `__cxa_atexit`";
38 }
39
40 void getAnalysisUsage(AnalysisUsage &AU) const override {
41 AU.setPreservesCFG();
43 }
44
45 bool runOnModule(Module &M) override;
46
47public:
48 static char ID;
49 LowerGlobalDtorsLegacyPass() : ModulePass(ID) {
51 }
52};
53} // End anonymous namespace
54
55char LowerGlobalDtorsLegacyPass::ID = 0;
56INITIALIZE_PASS(LowerGlobalDtorsLegacyPass, DEBUG_TYPE,
57 "Lower @llvm.global_dtors via `__cxa_atexit`", false, false)
58
60 return new LowerGlobalDtorsLegacyPass();
61}
62
63static bool runImpl(Module &M);
64bool LowerGlobalDtorsLegacyPass::runOnModule(Module &M) { return runImpl(M); }
65
68 bool Changed = runImpl(M);
69 if (!Changed)
71
74 return PA;
75}
76
77static bool runImpl(Module &M) {
78 GlobalVariable *GV = M.getGlobalVariable("llvm.global_dtors");
79 if (!GV || !GV->hasInitializer())
80 return false;
81
82 const ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
83 if (!InitList)
84 return false;
85
86 // Validate @llvm.global_dtor's type.
87 auto *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
88 if (!ETy || ETy->getNumElements() != 3 ||
89 !ETy->getTypeAtIndex(0U)->isIntegerTy() ||
90 !ETy->getTypeAtIndex(1U)->isPointerTy() ||
91 !ETy->getTypeAtIndex(2U)->isPointerTy())
92 return false; // Not (int, ptr, ptr).
93
94 // Collect the contents of @llvm.global_dtors, ordered by priority. Within a
95 // priority, sequences of destructors with the same associated object are
96 // recorded so that we can register them as a group.
97 std::map<
99 std::vector<std::pair<Constant *, std::vector<Constant *>>>
100 > DtorFuncs;
101 for (Value *O : InitList->operands()) {
102 auto *CS = dyn_cast<ConstantStruct>(O);
103 if (!CS)
104 continue; // Malformed.
105
106 auto *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
107 if (!Priority)
108 continue; // Malformed.
109 uint16_t PriorityValue = Priority->getLimitedValue(UINT16_MAX);
110
111 Constant *DtorFunc = CS->getOperand(1);
112 if (DtorFunc->isNullValue())
113 break; // Found a null terminator, skip the rest.
114
115 Constant *Associated = CS->getOperand(2);
116 Associated = cast<Constant>(Associated->stripPointerCasts());
117
118 auto &AtThisPriority = DtorFuncs[PriorityValue];
119 if (AtThisPriority.empty() || AtThisPriority.back().first != Associated) {
120 std::vector<Constant *> NewList;
121 NewList.push_back(DtorFunc);
122 AtThisPriority.push_back(std::make_pair(Associated, NewList));
123 } else {
124 AtThisPriority.back().second.push_back(DtorFunc);
125 }
126 }
127 if (DtorFuncs.empty())
128 return false;
129
130 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
131 LLVMContext &C = M.getContext();
133 Type *AtExitFuncArgs[] = {VoidStar};
134 FunctionType *AtExitFuncTy =
135 FunctionType::get(Type::getVoidTy(C), AtExitFuncArgs,
136 /*isVarArg=*/false);
137
138 FunctionCallee AtExit = M.getOrInsertFunction(
139 "__cxa_atexit",
141 {PointerType::get(AtExitFuncTy, 0), VoidStar, VoidStar},
142 /*isVarArg=*/false));
143
144 // If __cxa_atexit is defined (e.g. in the case of LTO) and arg0 is not
145 // actually used (i.e. it's dummy/stub function as used in emscripten when
146 // the program never exits) we can simply return early and clear out
147 // @llvm.global_dtors.
148 if (auto F = dyn_cast<Function>(AtExit.getCallee())) {
149 if (F && F->hasExactDefinition() && F->getArg(0)->getNumUses() == 0) {
150 GV->eraseFromParent();
151 return true;
152 }
153 }
154
155 // Declare __dso_local.
156 Type *DsoHandleTy = Type::getInt8Ty(C);
157 Constant *DsoHandle = M.getOrInsertGlobal("__dso_handle", DsoHandleTy, [&] {
158 auto *GV = new GlobalVariable(M, DsoHandleTy, /*isConstant=*/true,
160 "__dso_handle");
162 return GV;
163 });
164
165 // For each unique priority level and associated symbol, generate a function
166 // to call all the destructors at that level, and a function to register the
167 // first function with __cxa_atexit.
168 for (auto &PriorityAndMore : DtorFuncs) {
169 uint16_t Priority = PriorityAndMore.first;
170 uint64_t Id = 0;
171 auto &AtThisPriority = PriorityAndMore.second;
172 for (auto &AssociatedAndMore : AtThisPriority) {
173 Constant *Associated = AssociatedAndMore.first;
174 auto ThisId = Id++;
175
176 Function *CallDtors = Function::Create(
177 AtExitFuncTy, Function::PrivateLinkage,
178 "call_dtors" +
179 (Priority != UINT16_MAX ? (Twine(".") + Twine(Priority))
180 : Twine()) +
181 (AtThisPriority.size() > 1 ? Twine("$") + Twine(ThisId)
182 : Twine()) +
183 (!Associated->isNullValue() ? (Twine(".") + Associated->getName())
184 : Twine()),
185 &M);
186 BasicBlock *BB = BasicBlock::Create(C, "body", CallDtors);
188 /*isVarArg=*/false);
189
190 for (auto *Dtor : reverse(AssociatedAndMore.second))
191 CallInst::Create(VoidVoid, Dtor, "", BB);
193
194 Function *RegisterCallDtors = Function::Create(
195 VoidVoid, Function::PrivateLinkage,
196 "register_call_dtors" +
197 (Priority != UINT16_MAX ? (Twine(".") + Twine(Priority))
198 : Twine()) +
199 (AtThisPriority.size() > 1 ? Twine("$") + Twine(ThisId)
200 : Twine()) +
201 (!Associated->isNullValue() ? (Twine(".") + Associated->getName())
202 : Twine()),
203 &M);
204 BasicBlock *EntryBB = BasicBlock::Create(C, "entry", RegisterCallDtors);
205 BasicBlock *FailBB = BasicBlock::Create(C, "fail", RegisterCallDtors);
206 BasicBlock *RetBB = BasicBlock::Create(C, "return", RegisterCallDtors);
207
209 Value *Args[] = {CallDtors, Null, DsoHandle};
210 Value *Res = CallInst::Create(AtExit, Args, "call", EntryBB);
211 Value *Cmp = new ICmpInst(EntryBB, ICmpInst::ICMP_NE, Res,
213 BranchInst::Create(FailBB, RetBB, Cmp, EntryBB);
214
215 // If `__cxa_atexit` hits out-of-memory, trap, so that we don't misbehave.
216 // This should be very rare, because if the process is running out of
217 // memory before main has even started, something is wrong.
218 CallInst::Create(Intrinsic::getDeclaration(&M, Intrinsic::trap), "",
219 FailBB);
220 new UnreachableInst(C, FailBB);
221
222 ReturnInst::Create(C, RetBB);
223
224 // Now register the registration function with @llvm.global_ctors.
225 appendToGlobalCtors(M, RegisterCallDtors, Priority, Associated);
226 }
227 }
228
229 // Now that we've lowered everything, remove @llvm.global_dtors.
230 GV->eraseFromParent();
231
232 return true;
233}
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static bool runImpl(Function &F, const TargetLowering &TLI)
static bool runImpl(Module &M)
#define DEBUG_TYPE
#define F(x, y, z)
Definition: MD5.cpp:55
Module.h This file contains the declarations for the Module class.
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:38
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
Represent the analysis usage information of a pass.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:256
Type * getElementType() const
Definition: DerivedTypes.h:384
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:212
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
Represents analyses that only rely on functions' control flow.
Definition: Analysis.h:72
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
@ ICMP_NE
not equal
Definition: InstrTypes.h:779
ConstantArray - Constant Array Declarations.
Definition: Constants.h:424
ArrayType * getType() const
Specialize the getType() method to always return an ArrayType, which reduces the amount of casting ne...
Definition: Constants.h:443
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1800
This is an important base class in LLVM.
Definition: Constant.h:42
const Constant * stripPointerCasts() const
Definition: Constant.h:218
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:370
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition: Constants.cpp:90
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
Definition: DerivedTypes.h:168
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:172
@ HiddenVisibility
The GV is hidden.
Definition: GlobalValue.h:68
void setVisibility(VisibilityTypes V)
Definition: GlobalValue.h:254
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:60
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition: GlobalValue.h:61
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition: Globals.cpp:481
This instruction compares its operands according to the predicate given to the constructor.
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:251
virtual bool runOnModule(Module &M)=0
runOnModule - Virtual method overriden by subclasses to process the module being operated on.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: Pass.cpp:98
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition: Pass.cpp:81
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
Definition: DerivedTypes.h:662
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:117
void preserveSet()
Mark an analysis set as preserved.
Definition: Analysis.h:146
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
static Type * getVoidTy(LLVMContext &C)
static IntegerType * getInt8Ty(LLVMContext &C)
static IntegerType * getInt32Ty(LLVMContext &C)
This function has undefined behavior.
op_range operands()
Definition: User.h:242
Value * getOperand(unsigned i) const
Definition: User.h:169
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=std::nullopt)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1539
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:419
ModulePass * createLowerGlobalDtorsLegacyPass()
void initializeLowerGlobalDtorsLegacyPassPass(PassRegistry &)
void appendToGlobalCtors(Module &M, Function *F, int Priority, Constant *Data=nullptr)
Append F to the list of global ctors of module M with the given Priority.
Definition: ModuleUtils.cpp:74