1326938Sdim//===-- WebAssemblyLowerGlobalDtors.cpp - Lower @llvm.global_dtors --------===//
2326938Sdim//
3353358Sdim// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4353358Sdim// See https://llvm.org/LICENSE.txt for license information.
5353358Sdim// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6326938Sdim//
7326938Sdim//===----------------------------------------------------------------------===//
8326938Sdim///
9326938Sdim/// \file
10341825Sdim/// Lower @llvm.global_dtors.
11326938Sdim///
12326938Sdim/// WebAssembly doesn't have a builtin way to invoke static destructors.
13326938Sdim/// Implement @llvm.global_dtors by creating wrapper functions that are
14326938Sdim/// registered in @llvm.global_ctors and which contain a call to
15326938Sdim/// `__cxa_atexit` to register their destructor functions.
16326938Sdim///
17326938Sdim//===----------------------------------------------------------------------===//
18326938Sdim
19326938Sdim#include "WebAssembly.h"
20344779Sdim#include "llvm/ADT/MapVector.h"
21326938Sdim#include "llvm/IR/Constants.h"
22326938Sdim#include "llvm/IR/Instructions.h"
23326938Sdim#include "llvm/IR/Intrinsics.h"
24326938Sdim#include "llvm/IR/Module.h"
25326938Sdim#include "llvm/Pass.h"
26326938Sdim#include "llvm/Support/Debug.h"
27326938Sdim#include "llvm/Support/raw_ostream.h"
28344779Sdim#include "llvm/Transforms/Utils/ModuleUtils.h"
29326938Sdimusing namespace llvm;
30326938Sdim
31326938Sdim#define DEBUG_TYPE "wasm-lower-global-dtors"
32326938Sdim
33326938Sdimnamespace {
34326938Sdimclass LowerGlobalDtors final : public ModulePass {
35326938Sdim  StringRef getPassName() const override {
36326938Sdim    return "WebAssembly Lower @llvm.global_dtors";
37326938Sdim  }
38326938Sdim
39326938Sdim  void getAnalysisUsage(AnalysisUsage &AU) const override {
40326938Sdim    AU.setPreservesCFG();
41326938Sdim    ModulePass::getAnalysisUsage(AU);
42326938Sdim  }
43326938Sdim
44326938Sdim  bool runOnModule(Module &M) override;
45326938Sdim
46326938Sdimpublic:
47326938Sdim  static char ID;
48326938Sdim  LowerGlobalDtors() : ModulePass(ID) {}
49326938Sdim};
50326938Sdim} // End anonymous namespace
51326938Sdim
52326938Sdimchar LowerGlobalDtors::ID = 0;
53341825SdimINITIALIZE_PASS(LowerGlobalDtors, DEBUG_TYPE,
54341825Sdim                "Lower @llvm.global_dtors for WebAssembly", false, false)
55341825Sdim
56326938SdimModulePass *llvm::createWebAssemblyLowerGlobalDtors() {
57326938Sdim  return new LowerGlobalDtors();
58326938Sdim}
59326938Sdim
60326938Sdimbool LowerGlobalDtors::runOnModule(Module &M) {
61344779Sdim  LLVM_DEBUG(dbgs() << "********** Lower Global Destructors **********\n");
62344779Sdim
63326938Sdim  GlobalVariable *GV = M.getGlobalVariable("llvm.global_dtors");
64353358Sdim  if (!GV || !GV->hasInitializer())
65326938Sdim    return false;
66326938Sdim
67326938Sdim  const ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
68326938Sdim  if (!InitList)
69326938Sdim    return false;
70326938Sdim
71326938Sdim  // Sanity-check @llvm.global_dtor's type.
72353358Sdim  auto *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
73326938Sdim  if (!ETy || ETy->getNumElements() != 3 ||
74326938Sdim      !ETy->getTypeAtIndex(0U)->isIntegerTy() ||
75326938Sdim      !ETy->getTypeAtIndex(1U)->isPointerTy() ||
76326938Sdim      !ETy->getTypeAtIndex(2U)->isPointerTy())
77326938Sdim    return false; // Not (int, ptr, ptr).
78326938Sdim
79326938Sdim  // Collect the contents of @llvm.global_dtors, collated by priority and
80326938Sdim  // associated symbol.
81344779Sdim  std::map<uint16_t, MapVector<Constant *, std::vector<Constant *>>> DtorFuncs;
82326938Sdim  for (Value *O : InitList->operands()) {
83353358Sdim    auto *CS = dyn_cast<ConstantStruct>(O);
84344779Sdim    if (!CS)
85344779Sdim      continue; // Malformed.
86326938Sdim
87353358Sdim    auto *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
88344779Sdim    if (!Priority)
89344779Sdim      continue; // Malformed.
90326938Sdim    uint16_t PriorityValue = Priority->getLimitedValue(UINT16_MAX);
91326938Sdim
92326938Sdim    Constant *DtorFunc = CS->getOperand(1);
93326938Sdim    if (DtorFunc->isNullValue())
94344779Sdim      break; // Found a null terminator, skip the rest.
95326938Sdim
96326938Sdim    Constant *Associated = CS->getOperand(2);
97360784Sdim    Associated = cast<Constant>(Associated->stripPointerCasts());
98326938Sdim
99326938Sdim    DtorFuncs[PriorityValue][Associated].push_back(DtorFunc);
100326938Sdim  }
101326938Sdim  if (DtorFuncs.empty())
102326938Sdim    return false;
103326938Sdim
104326938Sdim  // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
105326938Sdim  LLVMContext &C = M.getContext();
106326938Sdim  PointerType *VoidStar = Type::getInt8PtrTy(C);
107344779Sdim  Type *AtExitFuncArgs[] = {VoidStar};
108344779Sdim  FunctionType *AtExitFuncTy =
109344779Sdim      FunctionType::get(Type::getVoidTy(C), AtExitFuncArgs,
110344779Sdim                        /*isVarArg=*/false);
111326938Sdim
112353358Sdim  FunctionCallee AtExit = M.getOrInsertFunction(
113353358Sdim      "__cxa_atexit",
114353358Sdim      FunctionType::get(Type::getInt32Ty(C),
115353358Sdim                        {PointerType::get(AtExitFuncTy, 0), VoidStar, VoidStar},
116353358Sdim                        /*isVarArg=*/false));
117326938Sdim
118326938Sdim  // Declare __dso_local.
119326938Sdim  Constant *DsoHandle = M.getNamedValue("__dso_handle");
120326938Sdim  if (!DsoHandle) {
121326938Sdim    Type *DsoHandleTy = Type::getInt8Ty(C);
122344779Sdim    GlobalVariable *Handle = new GlobalVariable(
123344779Sdim        M, DsoHandleTy, /*isConstant=*/true,
124344779Sdim        GlobalVariable::ExternalWeakLinkage, nullptr, "__dso_handle");
125326938Sdim    Handle->setVisibility(GlobalVariable::HiddenVisibility);
126326938Sdim    DsoHandle = Handle;
127326938Sdim  }
128326938Sdim
129326938Sdim  // For each unique priority level and associated symbol, generate a function
130326938Sdim  // to call all the destructors at that level, and a function to register the
131326938Sdim  // first function with __cxa_atexit.
132326938Sdim  for (auto &PriorityAndMore : DtorFuncs) {
133326938Sdim    uint16_t Priority = PriorityAndMore.first;
134326938Sdim    for (auto &AssociatedAndMore : PriorityAndMore.second) {
135326938Sdim      Constant *Associated = AssociatedAndMore.first;
136326938Sdim
137326938Sdim      Function *CallDtors = Function::Create(
138344779Sdim          AtExitFuncTy, Function::PrivateLinkage,
139344779Sdim          "call_dtors" +
140344779Sdim              (Priority != UINT16_MAX ? (Twine(".") + Twine(Priority))
141344779Sdim                                      : Twine()) +
142344779Sdim              (!Associated->isNullValue() ? (Twine(".") + Associated->getName())
143344779Sdim                                          : Twine()),
144344779Sdim          &M);
145326938Sdim      BasicBlock *BB = BasicBlock::Create(C, "body", CallDtors);
146353358Sdim      FunctionType *VoidVoid = FunctionType::get(Type::getVoidTy(C),
147353358Sdim                                                 /*isVarArg=*/false);
148326938Sdim
149326938Sdim      for (auto Dtor : AssociatedAndMore.second)
150353358Sdim        CallInst::Create(VoidVoid, Dtor, "", BB);
151326938Sdim      ReturnInst::Create(C, BB);
152326938Sdim
153326938Sdim      Function *RegisterCallDtors = Function::Create(
154344779Sdim          VoidVoid, Function::PrivateLinkage,
155344779Sdim          "register_call_dtors" +
156344779Sdim              (Priority != UINT16_MAX ? (Twine(".") + Twine(Priority))
157344779Sdim                                      : Twine()) +
158344779Sdim              (!Associated->isNullValue() ? (Twine(".") + Associated->getName())
159344779Sdim                                          : Twine()),
160344779Sdim          &M);
161326938Sdim      BasicBlock *EntryBB = BasicBlock::Create(C, "entry", RegisterCallDtors);
162326938Sdim      BasicBlock *FailBB = BasicBlock::Create(C, "fail", RegisterCallDtors);
163326938Sdim      BasicBlock *RetBB = BasicBlock::Create(C, "return", RegisterCallDtors);
164326938Sdim
165326938Sdim      Value *Null = ConstantPointerNull::get(VoidStar);
166344779Sdim      Value *Args[] = {CallDtors, Null, DsoHandle};
167326938Sdim      Value *Res = CallInst::Create(AtExit, Args, "call", EntryBB);
168326938Sdim      Value *Cmp = new ICmpInst(*EntryBB, ICmpInst::ICMP_NE, Res,
169326938Sdim                                Constant::getNullValue(Res->getType()));
170326938Sdim      BranchInst::Create(FailBB, RetBB, Cmp, EntryBB);
171326938Sdim
172326938Sdim      // If `__cxa_atexit` hits out-of-memory, trap, so that we don't misbehave.
173344779Sdim      // This should be very rare, because if the process is running out of
174344779Sdim      // memory before main has even started, something is wrong.
175344779Sdim      CallInst::Create(Intrinsic::getDeclaration(&M, Intrinsic::trap), "",
176344779Sdim                       FailBB);
177326938Sdim      new UnreachableInst(C, FailBB);
178326938Sdim
179326938Sdim      ReturnInst::Create(C, RetBB);
180326938Sdim
181326938Sdim      // Now register the registration function with @llvm.global_ctors.
182326938Sdim      appendToGlobalCtors(M, RegisterCallDtors, Priority, Associated);
183326938Sdim    }
184326938Sdim  }
185326938Sdim
186326938Sdim  // Now that we've lowered everything, remove @llvm.global_dtors.
187326938Sdim  GV->eraseFromParent();
188326938Sdim
189326938Sdim  return true;
190326938Sdim}
191