blob: 0020817aee4112b763999790374a60644ae5e506 [file] [log] [blame]
Sam Cleggbafe6902017-12-15 00:17:10 +00001//===-- WebAssemblyLowerGlobalDtors.cpp - Lower @llvm.global_dtors --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief Lower @llvm.global_dtors.
12///
13/// WebAssembly doesn't have a builtin way to invoke static destructors.
14/// Implement @llvm.global_dtors by creating wrapper functions that are
15/// registered in @llvm.global_ctors and which contain a call to
16/// `__cxa_atexit` to register their destructor functions.
17///
18//===----------------------------------------------------------------------===//
19
20#include "WebAssembly.h"
21#include "llvm/IR/Constants.h"
22#include "llvm/IR/Instructions.h"
23#include "llvm/IR/Intrinsics.h"
24#include "llvm/IR/Module.h"
25#include "llvm/Transforms/Utils/ModuleUtils.h"
26#include "llvm/Pass.h"
27#include "llvm/ADT/MapVector.h"
28#include "llvm/Support/Debug.h"
29#include "llvm/Support/raw_ostream.h"
30using namespace llvm;
31
32#define DEBUG_TYPE "wasm-lower-global-dtors"
33
34namespace {
35class LowerGlobalDtors final : public ModulePass {
36 StringRef getPassName() const override {
37 return "WebAssembly Lower @llvm.global_dtors";
38 }
39
40 void getAnalysisUsage(AnalysisUsage &AU) const override {
41 AU.setPreservesCFG();
42 ModulePass::getAnalysisUsage(AU);
43 }
44
45 bool runOnModule(Module &M) override;
46
47public:
48 static char ID;
49 LowerGlobalDtors() : ModulePass(ID) {}
50};
51} // End anonymous namespace
52
53char LowerGlobalDtors::ID = 0;
54ModulePass *llvm::createWebAssemblyLowerGlobalDtors() {
55 return new LowerGlobalDtors();
56}
57
58bool LowerGlobalDtors::runOnModule(Module &M) {
59 GlobalVariable *GV = M.getGlobalVariable("llvm.global_dtors");
60 if (!GV)
61 return false;
62
63 const ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
64 if (!InitList)
65 return false;
66
67 // Sanity-check @llvm.global_dtor's type.
68 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
69 if (!ETy || ETy->getNumElements() != 3 ||
70 !ETy->getTypeAtIndex(0U)->isIntegerTy() ||
71 !ETy->getTypeAtIndex(1U)->isPointerTy() ||
72 !ETy->getTypeAtIndex(2U)->isPointerTy())
73 return false; // Not (int, ptr, ptr).
74
75 // Collect the contents of @llvm.global_dtors, collated by priority and
76 // associated symbol.
77 std::map<uint16_t, MapVector<Constant *, std::vector<Constant *> > > DtorFuncs;
78 for (Value *O : InitList->operands()) {
79 ConstantStruct *CS = dyn_cast<ConstantStruct>(O);
80 if (!CS) continue; // Malformed.
81
82 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
83 if (!Priority) continue; // Malformed.
84 uint16_t PriorityValue = Priority->getLimitedValue(UINT16_MAX);
85
86 Constant *DtorFunc = CS->getOperand(1);
87 if (DtorFunc->isNullValue())
88 break; // Found a null terminator, skip the rest.
89
90 Constant *Associated = CS->getOperand(2);
91 Associated = cast<Constant>(Associated->stripPointerCastsNoFollowAliases());
92
93 DtorFuncs[PriorityValue][Associated].push_back(DtorFunc);
94 }
95 if (DtorFuncs.empty())
96 return false;
97
98 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
99 LLVMContext &C = M.getContext();
100 PointerType *VoidStar = Type::getInt8PtrTy(C);
101 Type *AtExitFuncArgs[] = { VoidStar };
102 FunctionType *AtExitFuncTy = FunctionType::get(
103 Type::getVoidTy(C),
104 AtExitFuncArgs,
105 /*isVarArg=*/false);
106
107 Type *AtExitArgs[] = {
108 PointerType::get(AtExitFuncTy, 0),
109 VoidStar,
110 VoidStar
111 };
112 FunctionType *AtExitTy = FunctionType::get(
113 Type::getInt32Ty(C),
114 AtExitArgs,
115 /*isVarArg=*/false);
116 Constant *AtExit = M.getOrInsertFunction("__cxa_atexit", AtExitTy);
117
118 // Declare __dso_local.
119 Constant *DsoHandle = M.getNamedValue("__dso_handle");
120 if (!DsoHandle) {
121 Type *DsoHandleTy = Type::getInt8Ty(C);
122 GlobalVariable *Handle =
123 new GlobalVariable(M, DsoHandleTy, /*isConstant=*/true,
124 GlobalVariable::ExternalWeakLinkage,
125 nullptr, "__dso_handle");
126 Handle->setVisibility(GlobalVariable::HiddenVisibility);
127 DsoHandle = Handle;
128 }
129
130 // For each unique priority level and associated symbol, generate a function
131 // to call all the destructors at that level, and a function to register the
132 // first function with __cxa_atexit.
133 for (auto &PriorityAndMore : DtorFuncs) {
134 uint16_t Priority = PriorityAndMore.first;
135 for (auto &AssociatedAndMore : PriorityAndMore.second) {
136 Constant *Associated = AssociatedAndMore.first;
137
138 Function *CallDtors = Function::Create(
139 AtExitFuncTy, Function::PrivateLinkage,
140 "call_dtors" +
141 (Priority != UINT16_MAX ?
142 (Twine(".") + Twine(Priority)) : Twine()) +
143 (!Associated->isNullValue() ?
144 (Twine(".") + Associated->getName()) : Twine()),
145 &M);
146 BasicBlock *BB = BasicBlock::Create(C, "body", CallDtors);
147
148 for (auto Dtor : AssociatedAndMore.second)
149 CallInst::Create(Dtor, "", BB);
150 ReturnInst::Create(C, BB);
151
152 FunctionType *VoidVoid = FunctionType::get(Type::getVoidTy(C),
153 /*isVarArg=*/false);
154 Function *RegisterCallDtors = Function::Create(
155 VoidVoid, Function::PrivateLinkage,
156 "register_call_dtors" +
157 (Priority != UINT16_MAX ?
158 (Twine(".") + Twine(Priority)) : Twine()) +
159 (!Associated->isNullValue() ?
160 (Twine(".") + Associated->getName()) : Twine()),
161 &M);
162 BasicBlock *EntryBB = BasicBlock::Create(C, "entry", RegisterCallDtors);
163 BasicBlock *FailBB = BasicBlock::Create(C, "fail", RegisterCallDtors);
164 BasicBlock *RetBB = BasicBlock::Create(C, "return", RegisterCallDtors);
165
166 Value *Null = ConstantPointerNull::get(VoidStar);
167 Value *Args[] = { CallDtors, Null, DsoHandle };
168 Value *Res = CallInst::Create(AtExit, Args, "call", EntryBB);
169 Value *Cmp = new ICmpInst(*EntryBB, ICmpInst::ICMP_NE, Res,
170 Constant::getNullValue(Res->getType()));
171 BranchInst::Create(FailBB, RetBB, Cmp, EntryBB);
172
173 // If `__cxa_atexit` hits out-of-memory, trap, so that we don't misbehave.
174 // This should be very rare, because if the process is running out of memory
175 // before main has even started, something is wrong.
176 CallInst::Create(Intrinsic::getDeclaration(&M, Intrinsic::trap),
177 "", FailBB);
178 new UnreachableInst(C, FailBB);
179
180 ReturnInst::Create(C, RetBB);
181
182 // Now register the registration function with @llvm.global_ctors.
183 appendToGlobalCtors(M, RegisterCallDtors, Priority, Associated);
184 }
185 }
186
187 // Now that we've lowered everything, remove @llvm.global_dtors.
188 GV->eraseFromParent();
189
190 return true;
191}