1 //===-- WasmEHPrepare - Prepare excepton handling for WebAssembly --------===//
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 transformation is designed for use by code generators which use
10 // WebAssembly exception handling scheme. This currently supports C++
11 // exceptions.
12 //
13 // WebAssembly exception handling uses Windows exception IR for the middle level
14 // representation. This pass does the following transformation for every
15 // catchpad block:
16 // (In C-style pseudocode)
17 //
18 // - Before:
19 //   catchpad ...
20 //   exn = wasm.get.exception();
21 //   selector = wasm.get.selector();
22 //   ...
23 //
24 // - After:
25 //   catchpad ...
26 //   exn = wasm.extract.exception();
27 //   // Only add below in case it's not a single catch (...)
28 //   wasm.landingpad.index(index);
29 //   __wasm_lpad_context.lpad_index = index;
30 //   __wasm_lpad_context.lsda = wasm.lsda();
31 //   _Unwind_CallPersonality(exn);
32 //   selector = __wasm.landingpad_context.selector;
33 //   ...
34 //
35 //
36 // * Background: Direct personality function call
37 // In WebAssembly EH, the VM is responsible for unwinding the stack once an
38 // exception is thrown. After the stack is unwound, the control flow is
39 // transfered to WebAssembly 'catch' instruction.
40 //
41 // Unwinding the stack is not done by libunwind but the VM, so the personality
42 // function in libcxxabi cannot be called from libunwind during the unwinding
43 // process. So after a catch instruction, we insert a call to a wrapper function
44 // in libunwind that in turn calls the real personality function.
45 //
46 // In Itanium EH, if the personality function decides there is no matching catch
47 // clause in a call frame and no cleanup action to perform, the unwinder doesn't
48 // stop there and continues unwinding. But in Wasm EH, the unwinder stops at
49 // every call frame with a catch intruction, after which the personality
50 // function is called from the compiler-generated user code here.
51 //
52 // In libunwind, we have this struct that serves as a communincation channel
53 // between the compiler-generated user code and the personality function in
54 // libcxxabi.
55 //
56 // struct _Unwind_LandingPadContext {
57 //   uintptr_t lpad_index;
58 //   uintptr_t lsda;
59 //   uintptr_t selector;
60 // };
61 // struct _Unwind_LandingPadContext __wasm_lpad_context = ...;
62 //
63 // And this wrapper in libunwind calls the personality function.
64 //
65 // _Unwind_Reason_Code _Unwind_CallPersonality(void *exception_ptr) {
66 //   struct _Unwind_Exception *exception_obj =
67 //       (struct _Unwind_Exception *)exception_ptr;
68 //   _Unwind_Reason_Code ret = __gxx_personality_v0(
69 //       1, _UA_CLEANUP_PHASE, exception_obj->exception_class, exception_obj,
70 //       (struct _Unwind_Context *)__wasm_lpad_context);
71 //   return ret;
72 // }
73 //
74 // We pass a landing pad index, and the address of LSDA for the current function
75 // to the wrapper function _Unwind_CallPersonality in libunwind, and we retrieve
76 // the selector after it returns.
77 //
78 //===----------------------------------------------------------------------===//
79 
80 #include "llvm/ADT/SetVector.h"
81 #include "llvm/ADT/Statistic.h"
82 #include "llvm/ADT/Triple.h"
83 #include "llvm/CodeGen/Passes.h"
84 #include "llvm/CodeGen/TargetLowering.h"
85 #include "llvm/CodeGen/TargetSubtargetInfo.h"
86 #include "llvm/CodeGen/WasmEHFuncInfo.h"
87 #include "llvm/IR/Dominators.h"
88 #include "llvm/IR/IRBuilder.h"
89 #include "llvm/IR/Intrinsics.h"
90 #include "llvm/InitializePasses.h"
91 #include "llvm/Pass.h"
92 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
93 
94 using namespace llvm;
95 
96 #define DEBUG_TYPE "wasmehprepare"
97 
98 namespace {
99 class WasmEHPrepare : public FunctionPass {
100   Type *LPadContextTy = nullptr; // type of 'struct _Unwind_LandingPadContext'
101   GlobalVariable *LPadContextGV = nullptr; // __wasm_lpad_context
102 
103   // Field addresses of struct _Unwind_LandingPadContext
104   Value *LPadIndexField = nullptr; // lpad_index field
105   Value *LSDAField = nullptr;      // lsda field
106   Value *SelectorField = nullptr;  // selector
107 
108   Function *ThrowF = nullptr;       // wasm.throw() intrinsic
109   Function *LPadIndexF = nullptr;   // wasm.landingpad.index() intrinsic
110   Function *LSDAF = nullptr;        // wasm.lsda() intrinsic
111   Function *GetExnF = nullptr;      // wasm.get.exception() intrinsic
112   Function *ExtractExnF = nullptr;  // wasm.extract.exception() intrinsic
113   Function *GetSelectorF = nullptr; // wasm.get.ehselector() intrinsic
114   FunctionCallee CallPersonalityF =
115       nullptr; // _Unwind_CallPersonality() wrapper
116 
117   bool prepareEHPads(Function &F);
118   bool prepareThrows(Function &F);
119 
120   void prepareEHPad(BasicBlock *BB, bool NeedLSDA, unsigned Index = 0);
121   void prepareTerminateCleanupPad(BasicBlock *BB);
122 
123 public:
124   static char ID; // Pass identification, replacement for typeid
125 
126   WasmEHPrepare() : FunctionPass(ID) {}
127 
128   bool doInitialization(Module &M) override;
129   bool runOnFunction(Function &F) override;
130 
131   StringRef getPassName() const override {
132     return "WebAssembly Exception handling preparation";
133   }
134 };
135 } // end anonymous namespace
136 
137 char WasmEHPrepare::ID = 0;
138 INITIALIZE_PASS(WasmEHPrepare, DEBUG_TYPE, "Prepare WebAssembly exceptions",
139                 false, false)
140 
141 FunctionPass *llvm::createWasmEHPass() { return new WasmEHPrepare(); }
142 
143 bool WasmEHPrepare::doInitialization(Module &M) {
144   IRBuilder<> IRB(M.getContext());
145   LPadContextTy = StructType::get(IRB.getInt32Ty(),   // lpad_index
146                                   IRB.getInt8PtrTy(), // lsda
147                                   IRB.getInt32Ty()    // selector
148   );
149   return false;
150 }
151 
152 // Erase the specified BBs if the BB does not have any remaining predecessors,
153 // and also all its dead children.
154 template <typename Container>
155 static void eraseDeadBBsAndChildren(const Container &BBs) {
156   SmallVector<BasicBlock *, 8> WL(BBs.begin(), BBs.end());
157   while (!WL.empty()) {
158     auto *BB = WL.pop_back_val();
159     if (pred_begin(BB) != pred_end(BB))
160       continue;
161     WL.append(succ_begin(BB), succ_end(BB));
162     DeleteDeadBlock(BB);
163   }
164 }
165 
166 bool WasmEHPrepare::runOnFunction(Function &F) {
167   bool Changed = false;
168   Changed |= prepareThrows(F);
169   Changed |= prepareEHPads(F);
170   return Changed;
171 }
172 
173 bool WasmEHPrepare::prepareThrows(Function &F) {
174   Module &M = *F.getParent();
175   IRBuilder<> IRB(F.getContext());
176   bool Changed = false;
177 
178   // wasm.throw() intinsic, which will be lowered to wasm 'throw' instruction.
179   ThrowF = Intrinsic::getDeclaration(&M, Intrinsic::wasm_throw);
180   // Insert an unreachable instruction after a call to @llvm.wasm.throw and
181   // delete all following instructions within the BB, and delete all the dead
182   // children of the BB as well.
183   for (User *U : ThrowF->users()) {
184     // A call to @llvm.wasm.throw() is only generated from __cxa_throw()
185     // builtin call within libcxxabi, and cannot be an InvokeInst.
186     auto *ThrowI = cast<CallInst>(U);
187     if (ThrowI->getFunction() != &F)
188       continue;
189     Changed = true;
190     auto *BB = ThrowI->getParent();
191     SmallVector<BasicBlock *, 4> Succs(succ_begin(BB), succ_end(BB));
192     auto &InstList = BB->getInstList();
193     InstList.erase(std::next(BasicBlock::iterator(ThrowI)), InstList.end());
194     IRB.SetInsertPoint(BB);
195     IRB.CreateUnreachable();
196     eraseDeadBBsAndChildren(Succs);
197   }
198 
199   return Changed;
200 }
201 
202 bool WasmEHPrepare::prepareEHPads(Function &F) {
203   Module &M = *F.getParent();
204   IRBuilder<> IRB(F.getContext());
205 
206   SmallVector<BasicBlock *, 16> CatchPads;
207   SmallVector<BasicBlock *, 16> CleanupPads;
208   for (BasicBlock &BB : F) {
209     if (!BB.isEHPad())
210       continue;
211     auto *Pad = BB.getFirstNonPHI();
212     if (isa<CatchPadInst>(Pad))
213       CatchPads.push_back(&BB);
214     else if (isa<CleanupPadInst>(Pad))
215       CleanupPads.push_back(&BB);
216   }
217 
218   if (CatchPads.empty() && CleanupPads.empty())
219     return false;
220   assert(F.hasPersonalityFn() && "Personality function not found");
221 
222   // __wasm_lpad_context global variable
223   LPadContextGV = cast<GlobalVariable>(
224       M.getOrInsertGlobal("__wasm_lpad_context", LPadContextTy));
225   LPadIndexField = IRB.CreateConstGEP2_32(LPadContextTy, LPadContextGV, 0, 0,
226                                           "lpad_index_gep");
227   LSDAField =
228       IRB.CreateConstGEP2_32(LPadContextTy, LPadContextGV, 0, 1, "lsda_gep");
229   SelectorField = IRB.CreateConstGEP2_32(LPadContextTy, LPadContextGV, 0, 2,
230                                          "selector_gep");
231 
232   // wasm.landingpad.index() intrinsic, which is to specify landingpad index
233   LPadIndexF = Intrinsic::getDeclaration(&M, Intrinsic::wasm_landingpad_index);
234   // wasm.lsda() intrinsic. Returns the address of LSDA table for the current
235   // function.
236   LSDAF = Intrinsic::getDeclaration(&M, Intrinsic::wasm_lsda);
237   // wasm.get.exception() and wasm.get.ehselector() intrinsics. Calls to these
238   // are generated in clang.
239   GetExnF = Intrinsic::getDeclaration(&M, Intrinsic::wasm_get_exception);
240   GetSelectorF = Intrinsic::getDeclaration(&M, Intrinsic::wasm_get_ehselector);
241 
242   // wasm.extract.exception() is the same as wasm.get.exception() but it does
243   // not take a token argument. This will be lowered down to EXTRACT_EXCEPTION
244   // pseudo instruction in instruction selection, which will be expanded using
245   // 'br_on_exn' instruction later.
246   ExtractExnF =
247       Intrinsic::getDeclaration(&M, Intrinsic::wasm_extract_exception);
248 
249   // _Unwind_CallPersonality() wrapper function, which calls the personality
250   CallPersonalityF = M.getOrInsertFunction(
251       "_Unwind_CallPersonality", IRB.getInt32Ty(), IRB.getInt8PtrTy());
252   if (Function *F = dyn_cast<Function>(CallPersonalityF.getCallee()))
253     F->setDoesNotThrow();
254 
255   unsigned Index = 0;
256   for (auto *BB : CatchPads) {
257     auto *CPI = cast<CatchPadInst>(BB->getFirstNonPHI());
258     // In case of a single catch (...), we don't need to emit LSDA
259     if (CPI->getNumArgOperands() == 1 &&
260         cast<Constant>(CPI->getArgOperand(0))->isNullValue())
261       prepareEHPad(BB, false);
262     else
263       prepareEHPad(BB, true, Index++);
264   }
265 
266   // Cleanup pads don't need LSDA.
267   for (auto *BB : CleanupPads)
268     prepareEHPad(BB, false);
269 
270   return true;
271 }
272 
273 // Prepare an EH pad for Wasm EH handling. If NeedLSDA is false, Index is
274 // ignored.
275 void WasmEHPrepare::prepareEHPad(BasicBlock *BB, bool NeedLSDA,
276                                  unsigned Index) {
277   assert(BB->isEHPad() && "BB is not an EHPad!");
278   IRBuilder<> IRB(BB->getContext());
279   IRB.SetInsertPoint(&*BB->getFirstInsertionPt());
280 
281   auto *FPI = cast<FuncletPadInst>(BB->getFirstNonPHI());
282   Instruction *GetExnCI = nullptr, *GetSelectorCI = nullptr;
283   for (auto &U : FPI->uses()) {
284     if (auto *CI = dyn_cast<CallInst>(U.getUser())) {
285       if (CI->getCalledValue() == GetExnF)
286         GetExnCI = CI;
287       if (CI->getCalledValue() == GetSelectorF)
288         GetSelectorCI = CI;
289     }
290   }
291 
292   // Cleanup pads w/o __clang_call_terminate call do not have any of
293   // wasm.get.exception() or wasm.get.ehselector() calls. We need to do nothing.
294   if (!GetExnCI) {
295     assert(!GetSelectorCI &&
296            "wasm.get.ehselector() cannot exist w/o wasm.get.exception()");
297     return;
298   }
299 
300   Instruction *ExtractExnCI = IRB.CreateCall(ExtractExnF, {}, "exn");
301   GetExnCI->replaceAllUsesWith(ExtractExnCI);
302   GetExnCI->eraseFromParent();
303 
304   // In case it is a catchpad with single catch (...) or a cleanuppad, we don't
305   // need to call personality function because we don't need a selector.
306   if (!NeedLSDA) {
307     if (GetSelectorCI) {
308       assert(GetSelectorCI->use_empty() &&
309              "wasm.get.ehselector() still has uses!");
310       GetSelectorCI->eraseFromParent();
311     }
312     return;
313   }
314   IRB.SetInsertPoint(ExtractExnCI->getNextNode());
315 
316   // This is to create a map of <landingpad EH label, landingpad index> in
317   // SelectionDAGISel, which is to be used in EHStreamer to emit LSDA tables.
318   // Pseudocode: wasm.landingpad.index(Index);
319   IRB.CreateCall(LPadIndexF, {FPI, IRB.getInt32(Index)});
320 
321   // Pseudocode: __wasm_lpad_context.lpad_index = index;
322   IRB.CreateStore(IRB.getInt32(Index), LPadIndexField);
323 
324   // Store LSDA address only if this catchpad belongs to a top-level
325   // catchswitch. If there is another catchpad that dominates this pad, we don't
326   // need to store LSDA address again, because they are the same throughout the
327   // function and have been already stored before.
328   // TODO Can we not store LSDA address in user function but make libcxxabi
329   // compute it?
330   auto *CPI = cast<CatchPadInst>(FPI);
331   if (isa<ConstantTokenNone>(CPI->getCatchSwitch()->getParentPad()))
332     // Pseudocode: __wasm_lpad_context.lsda = wasm.lsda();
333     IRB.CreateStore(IRB.CreateCall(LSDAF), LSDAField);
334 
335   // Pseudocode: _Unwind_CallPersonality(exn);
336   CallInst *PersCI = IRB.CreateCall(CallPersonalityF, ExtractExnCI,
337                                     OperandBundleDef("funclet", CPI));
338   PersCI->setDoesNotThrow();
339 
340   // Pseudocode: int selector = __wasm.landingpad_context.selector;
341   Instruction *Selector =
342       IRB.CreateLoad(IRB.getInt32Ty(), SelectorField, "selector");
343 
344   // Replace the return value from wasm.get.ehselector() with the selector value
345   // loaded from __wasm_lpad_context.selector.
346   assert(GetSelectorCI && "wasm.get.ehselector() call does not exist");
347   GetSelectorCI->replaceAllUsesWith(Selector);
348   GetSelectorCI->eraseFromParent();
349 }
350 
351 void llvm::calculateWasmEHInfo(const Function *F, WasmEHFuncInfo &EHInfo) {
352   // If an exception is not caught by a catchpad (i.e., it is a foreign
353   // exception), it will unwind to its parent catchswitch's unwind destination.
354   // We don't record an unwind destination for cleanuppads because every
355   // exception should be caught by it.
356   for (const auto &BB : *F) {
357     if (!BB.isEHPad())
358       continue;
359     const Instruction *Pad = BB.getFirstNonPHI();
360 
361     if (const auto *CatchPad = dyn_cast<CatchPadInst>(Pad)) {
362       const auto *UnwindBB = CatchPad->getCatchSwitch()->getUnwindDest();
363       if (!UnwindBB)
364         continue;
365       const Instruction *UnwindPad = UnwindBB->getFirstNonPHI();
366       if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(UnwindPad))
367         // Currently there should be only one handler per a catchswitch.
368         EHInfo.setEHPadUnwindDest(&BB, *CatchSwitch->handlers().begin());
369       else // cleanuppad
370         EHInfo.setEHPadUnwindDest(&BB, UnwindBB);
371     }
372   }
373 }
374