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