blob: 3988189ba7ce73eaad2a591208da78c0ec20dab7 [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
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000011/// Lower @llvm.global_dtors.
Sam Cleggbafe6902017-12-15 00:17:10 +000012///
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"
Heejin Ahnf208f632018-09-05 01:27:38 +000021#include "llvm/ADT/MapVector.h"
Sam Cleggbafe6902017-12-15 00:17:10 +000022#include "llvm/IR/Constants.h"
23#include "llvm/IR/Instructions.h"
24#include "llvm/IR/Intrinsics.h"
25#include "llvm/IR/Module.h"
Sam Cleggbafe6902017-12-15 00:17:10 +000026#include "llvm/Pass.h"
Sam Cleggbafe6902017-12-15 00:17:10 +000027#include "llvm/Support/Debug.h"
28#include "llvm/Support/raw_ostream.h"
Heejin Ahnf208f632018-09-05 01:27:38 +000029#include "llvm/Transforms/Utils/ModuleUtils.h"
Sam Cleggbafe6902017-12-15 00:17:10 +000030using 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;
Jacob Gravelle40926452018-03-30 20:36:58 +000054INITIALIZE_PASS(LowerGlobalDtors, DEBUG_TYPE,
55 "Lower @llvm.global_dtors for WebAssembly", false, false)
56
Sam Cleggbafe6902017-12-15 00:17:10 +000057ModulePass *llvm::createWebAssemblyLowerGlobalDtors() {
58 return new LowerGlobalDtors();
59}
60
61bool LowerGlobalDtors::runOnModule(Module &M) {
62 GlobalVariable *GV = M.getGlobalVariable("llvm.global_dtors");
63 if (!GV)
64 return false;
65
66 const ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
67 if (!InitList)
68 return false;
69
70 // Sanity-check @llvm.global_dtor's type.
71 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
72 if (!ETy || ETy->getNumElements() != 3 ||
73 !ETy->getTypeAtIndex(0U)->isIntegerTy() ||
74 !ETy->getTypeAtIndex(1U)->isPointerTy() ||
75 !ETy->getTypeAtIndex(2U)->isPointerTy())
76 return false; // Not (int, ptr, ptr).
77
78 // Collect the contents of @llvm.global_dtors, collated by priority and
79 // associated symbol.
Heejin Ahnf208f632018-09-05 01:27:38 +000080 std::map<uint16_t, MapVector<Constant *, std::vector<Constant *>>> DtorFuncs;
Sam Cleggbafe6902017-12-15 00:17:10 +000081 for (Value *O : InitList->operands()) {
82 ConstantStruct *CS = dyn_cast<ConstantStruct>(O);
Heejin Ahnf208f632018-09-05 01:27:38 +000083 if (!CS)
84 continue; // Malformed.
Sam Cleggbafe6902017-12-15 00:17:10 +000085
86 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
Heejin Ahnf208f632018-09-05 01:27:38 +000087 if (!Priority)
88 continue; // Malformed.
Sam Cleggbafe6902017-12-15 00:17:10 +000089 uint16_t PriorityValue = Priority->getLimitedValue(UINT16_MAX);
90
91 Constant *DtorFunc = CS->getOperand(1);
92 if (DtorFunc->isNullValue())
Heejin Ahnf208f632018-09-05 01:27:38 +000093 break; // Found a null terminator, skip the rest.
Sam Cleggbafe6902017-12-15 00:17:10 +000094
95 Constant *Associated = CS->getOperand(2);
96 Associated = cast<Constant>(Associated->stripPointerCastsNoFollowAliases());
97
98 DtorFuncs[PriorityValue][Associated].push_back(DtorFunc);
99 }
100 if (DtorFuncs.empty())
101 return false;
102
103 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
104 LLVMContext &C = M.getContext();
105 PointerType *VoidStar = Type::getInt8PtrTy(C);
Heejin Ahnf208f632018-09-05 01:27:38 +0000106 Type *AtExitFuncArgs[] = {VoidStar};
107 FunctionType *AtExitFuncTy =
108 FunctionType::get(Type::getVoidTy(C), AtExitFuncArgs,
109 /*isVarArg=*/false);
Sam Cleggbafe6902017-12-15 00:17:10 +0000110
Heejin Ahnf208f632018-09-05 01:27:38 +0000111 Type *AtExitArgs[] = {PointerType::get(AtExitFuncTy, 0), VoidStar, VoidStar};
112 FunctionType *AtExitTy = FunctionType::get(Type::getInt32Ty(C), AtExitArgs,
113 /*isVarArg=*/false);
Sam Cleggbafe6902017-12-15 00:17:10 +0000114 Constant *AtExit = M.getOrInsertFunction("__cxa_atexit", AtExitTy);
115
116 // Declare __dso_local.
117 Constant *DsoHandle = M.getNamedValue("__dso_handle");
118 if (!DsoHandle) {
119 Type *DsoHandleTy = Type::getInt8Ty(C);
Heejin Ahnf208f632018-09-05 01:27:38 +0000120 GlobalVariable *Handle = new GlobalVariable(
121 M, DsoHandleTy, /*isConstant=*/true,
122 GlobalVariable::ExternalWeakLinkage, nullptr, "__dso_handle");
Sam Cleggbafe6902017-12-15 00:17:10 +0000123 Handle->setVisibility(GlobalVariable::HiddenVisibility);
124 DsoHandle = Handle;
125 }
126
127 // For each unique priority level and associated symbol, generate a function
128 // to call all the destructors at that level, and a function to register the
129 // first function with __cxa_atexit.
130 for (auto &PriorityAndMore : DtorFuncs) {
131 uint16_t Priority = PriorityAndMore.first;
132 for (auto &AssociatedAndMore : PriorityAndMore.second) {
133 Constant *Associated = AssociatedAndMore.first;
134
135 Function *CallDtors = Function::Create(
Heejin Ahnf208f632018-09-05 01:27:38 +0000136 AtExitFuncTy, Function::PrivateLinkage,
137 "call_dtors" +
138 (Priority != UINT16_MAX ? (Twine(".") + Twine(Priority))
139 : Twine()) +
140 (!Associated->isNullValue() ? (Twine(".") + Associated->getName())
141 : Twine()),
142 &M);
Sam Cleggbafe6902017-12-15 00:17:10 +0000143 BasicBlock *BB = BasicBlock::Create(C, "body", CallDtors);
144
145 for (auto Dtor : AssociatedAndMore.second)
146 CallInst::Create(Dtor, "", BB);
147 ReturnInst::Create(C, BB);
148
149 FunctionType *VoidVoid = FunctionType::get(Type::getVoidTy(C),
150 /*isVarArg=*/false);
151 Function *RegisterCallDtors = Function::Create(
Heejin Ahnf208f632018-09-05 01:27:38 +0000152 VoidVoid, Function::PrivateLinkage,
153 "register_call_dtors" +
154 (Priority != UINT16_MAX ? (Twine(".") + Twine(Priority))
155 : Twine()) +
156 (!Associated->isNullValue() ? (Twine(".") + Associated->getName())
157 : Twine()),
158 &M);
Sam Cleggbafe6902017-12-15 00:17:10 +0000159 BasicBlock *EntryBB = BasicBlock::Create(C, "entry", RegisterCallDtors);
160 BasicBlock *FailBB = BasicBlock::Create(C, "fail", RegisterCallDtors);
161 BasicBlock *RetBB = BasicBlock::Create(C, "return", RegisterCallDtors);
162
163 Value *Null = ConstantPointerNull::get(VoidStar);
Heejin Ahnf208f632018-09-05 01:27:38 +0000164 Value *Args[] = {CallDtors, Null, DsoHandle};
Sam Cleggbafe6902017-12-15 00:17:10 +0000165 Value *Res = CallInst::Create(AtExit, Args, "call", EntryBB);
166 Value *Cmp = new ICmpInst(*EntryBB, ICmpInst::ICMP_NE, Res,
167 Constant::getNullValue(Res->getType()));
168 BranchInst::Create(FailBB, RetBB, Cmp, EntryBB);
169
170 // If `__cxa_atexit` hits out-of-memory, trap, so that we don't misbehave.
Heejin Ahnf208f632018-09-05 01:27:38 +0000171 // This should be very rare, because if the process is running out of
172 // memory before main has even started, something is wrong.
173 CallInst::Create(Intrinsic::getDeclaration(&M, Intrinsic::trap), "",
174 FailBB);
Sam Cleggbafe6902017-12-15 00:17:10 +0000175 new UnreachableInst(C, FailBB);
176
177 ReturnInst::Create(C, RetBB);
178
179 // Now register the registration function with @llvm.global_ctors.
180 appendToGlobalCtors(M, RegisterCallDtors, Priority, Associated);
181 }
182 }
183
184 // Now that we've lowered everything, remove @llvm.global_dtors.
185 GV->eraseFromParent();
186
187 return true;
188}