LLVM 24.0.0git
WasmEHPrepare.cpp
Go to the documentation of this file.
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.catch(WebAssembly::CPP_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// personality_fn(exn);
32// selector = __wasm_lpad_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// transferred to WebAssembly 'catch' instruction.
40//
41// Unwinding the stack is not done by libunwind but the VM, so the personality
42// function (e.g. in libcxxabi) cannot be called from libunwind during the
43// unwinding process. So after a catch instruction, we insert a direct call to
44// the personality instead.
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 instruction, 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 communication 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// We pass a landing pad index, and the address of LSDA for the current function
64// to the personality function, and we retrieve the selector after it returns.
65//
66//===----------------------------------------------------------------------===//
67
70#include "llvm/CodeGen/Passes.h"
73#include "llvm/IR/IRBuilder.h"
74#include "llvm/IR/IntrinsicsWebAssembly.h"
75#include "llvm/IR/Module.h"
79
80using namespace llvm;
81
82#define DEBUG_TYPE "wasm-eh-prepare"
83
84namespace {
85class WasmEHPrepareImpl {
86 friend class WasmEHPrepare;
87
88 Type *LPadContextTy = nullptr; // type of 'struct _Unwind_LandingPadContext'
89 GlobalVariable *LPadContextGV = nullptr; // __wasm_lpad_context
90
91 // Field addresses of struct _Unwind_LandingPadContext
92 Value *LPadIndexField = nullptr; // lpad_index field
93 Value *LSDAField = nullptr; // lsda field
94 Value *SelectorField = nullptr; // selector
95
96 Function *ThrowF = nullptr; // wasm.throw() intrinsic
97 Function *LPadIndexF = nullptr; // wasm.landingpad.index() intrinsic
98 Function *LSDAF = nullptr; // wasm.lsda() intrinsic
99 Function *GetExnF = nullptr; // wasm.get.exception() intrinsic
100 Function *CatchF = nullptr; // wasm.catch() intrinsic
101 Function *GetSelectorF = nullptr; // wasm.get.ehselector() intrinsic
102 FunctionCallee PersonalityF = nullptr;
103
104 bool prepareThrows(Function &F);
105 bool prepareEHPads(Function &F);
106 void prepareEHPad(BasicBlock *BB, bool NeedPersonality, unsigned Index = 0);
107
108public:
109 WasmEHPrepareImpl() = default;
110 WasmEHPrepareImpl(Type *LPadContextTy_) : LPadContextTy(LPadContextTy_) {}
111 bool runOnFunction(Function &F);
112};
113
114class WasmEHPrepare : public FunctionPass {
115 WasmEHPrepareImpl P;
116
117public:
118 static char ID; // Pass identification, replacement for typeid
119
120 WasmEHPrepare() : FunctionPass(ID) {}
121 bool doInitialization(Module &M) override;
122 bool runOnFunction(Function &F) override { return P.runOnFunction(F); }
123
124 StringRef getPassName() const override {
125 return "WebAssembly Exception handling preparation";
126 }
127};
128
129} // end anonymous namespace
130
133 auto &Context = F.getContext();
134 auto *I32Ty = Type::getInt32Ty(Context);
135 auto *PtrTy = PointerType::get(Context, 0);
136 auto *LPadContextTy =
137 StructType::get(I32Ty /*lpad_index*/, PtrTy /*lsda*/, I32Ty /*selector*/);
138 WasmEHPrepareImpl P(LPadContextTy);
139 bool Changed = P.runOnFunction(F);
140 return Changed ? PreservedAnalyses::none() : PreservedAnalyses ::all();
141}
142
143char WasmEHPrepare::ID = 0;
145 "Prepare WebAssembly exceptions", false, false)
146INITIALIZE_PASS_END(WasmEHPrepare, DEBUG_TYPE, "Prepare WebAssembly exceptions",
148
149FunctionPass *llvm::createWasmEHPass() { return new WasmEHPrepare(); }
150
151bool WasmEHPrepare::doInitialization(Module &M) {
152 IRBuilder<> IRB(M.getContext());
153 P.LPadContextTy = StructType::get(IRB.getInt32Ty(), // lpad_index
154 IRB.getPtrTy(), // lsda
155 IRB.getInt32Ty() // selector
156 );
157 return false;
158}
159
160// Erase the specified BBs if the BB does not have any remaining predecessors,
161// and also all its dead children.
162template <typename Container>
163static void eraseDeadBBsAndChildren(const Container &BBs) {
164 SmallVector<BasicBlock *, 8> WL(BBs.begin(), BBs.end());
165 while (!WL.empty()) {
166 auto *BB = WL.pop_back_val();
167 if (!pred_empty(BB))
168 continue;
169 WL.append(succ_begin(BB), succ_end(BB));
170 DeleteDeadBlock(BB);
171 }
172}
173
174bool WasmEHPrepareImpl::runOnFunction(Function &F) {
175 bool Changed = false;
176 Changed |= prepareThrows(F);
177 Changed |= prepareEHPads(F);
178 return Changed;
179}
180
181bool WasmEHPrepareImpl::prepareThrows(Function &F) {
182 Module &M = *F.getParent();
183 IRBuilder<> IRB(F.getContext());
184 bool Changed = false;
185
186 // wasm.throw() intinsic, which will be lowered to wasm 'throw' instruction.
187 ThrowF = Intrinsic::getOrInsertDeclaration(&M, Intrinsic::wasm_throw);
188 // Insert an unreachable instruction after a call to @llvm.wasm.throw and
189 // delete all following instructions within the BB, and delete all the dead
190 // children of the BB as well.
191 for (User *U : ThrowF->users()) {
192 auto *ThrowI = dyn_cast<CallInst>(U);
193 if (!ThrowI || ThrowI->getFunction() != &F)
194 continue;
195 Changed = true;
196 auto *BB = ThrowI->getParent();
198 BB->erase(std::next(BasicBlock::iterator(ThrowI)), BB->end());
199 IRB.SetInsertPoint(BB);
200 IRB.CreateUnreachable();
202 }
203
204 return Changed;
205}
206
207bool WasmEHPrepareImpl::prepareEHPads(Function &F) {
208 Module &M = *F.getParent();
209 LLVMContext &Ctx = M.getContext();
210 const DataLayout &DL = M.getDataLayout();
211
214 for (BasicBlock &BB : F) {
215 if (!BB.isEHPad())
216 continue;
217 BasicBlock::iterator Pad = BB.getFirstNonPHIIt();
218 if (isa<CatchPadInst>(Pad))
219 CatchPads.push_back(&BB);
220 else if (isa<CleanupPadInst>(Pad))
221 CleanupPads.push_back(&BB);
222 }
223 if (CatchPads.empty() && CleanupPads.empty())
224 return false;
225
226 if (!F.hasPersonalityFn())
227 return false;
228
229 auto Personality = classifyEHPersonality(F.getPersonalityFn());
230
231 if (!isScopedEHPersonality(Personality)) {
232 report_fatal_error("Function '" + F.getName() +
233 "' does not have a supported Wasm personality function");
234 }
235 assert(F.hasPersonalityFn() && "Personality function not found");
236
237 // __wasm_lpad_context global variable.
238 // This variable should be thread local. If the target does not support TLS,
239 // we depend on CoalesceFeaturesAndStripAtomics to downgrade it to
240 // non-thread-local ones, in which case we don't allow this object to be
241 // linked with other objects using shared memory.
242 LPadContextGV = M.getOrInsertGlobal("__wasm_lpad_context", LPadContextTy);
243 LPadContextGV->setThreadLocalMode(GlobalValue::GeneralDynamicTLSModel);
244
245 LPadIndexField = LPadContextGV;
246 LSDAField =
247 ConstantExpr::getGetElementPtr(DL, LPadContextTy, LPadContextGV,
248 {ConstantInt::get(Ctx, APInt(32, 0)),
249 ConstantInt::get(Ctx, APInt(32, 1))},
251 SelectorField =
252 ConstantExpr::getGetElementPtr(DL, LPadContextTy, LPadContextGV,
253 {ConstantInt::get(Ctx, APInt(32, 0)),
254 ConstantInt::get(Ctx, APInt(32, 2))},
256
257 // wasm.landingpad.index() intrinsic, which is to specify landingpad index
258 LPadIndexF =
259 Intrinsic::getOrInsertDeclaration(&M, Intrinsic::wasm_landingpad_index);
260 // wasm.lsda() intrinsic. Returns the address of LSDA table for the current
261 // function.
262 LSDAF = Intrinsic::getOrInsertDeclaration(&M, Intrinsic::wasm_lsda);
263 // wasm.get.exception() and wasm.get.ehselector() intrinsics. Calls to these
264 // are generated in clang.
265 GetExnF =
266 Intrinsic::getOrInsertDeclaration(&M, Intrinsic::wasm_get_exception);
267 GetSelectorF =
268 Intrinsic::getOrInsertDeclaration(&M, Intrinsic::wasm_get_ehselector);
269
270 // wasm.catch() will be lowered down to wasm 'catch' instruction in
271 // instruction selection.
272 CatchF = Intrinsic::getOrInsertDeclaration(&M, Intrinsic::wasm_catch);
273
274 auto *PersPrototype = FunctionType::get(Type::getInt32Ty(Ctx),
275 {PointerType::getUnqual(Ctx)}, false);
276 PersonalityF =
277 M.getOrInsertFunction(getEHPersonalityName(Personality), PersPrototype);
278
279 if (Function *F = dyn_cast<Function>(PersonalityF.getCallee()))
280 F->setDoesNotThrow();
281
282 unsigned Index = 0;
283 for (auto *BB : CatchPads) {
284 auto *CPI = cast<CatchPadInst>(BB->getFirstNonPHIIt());
285 // In case of a single catch (...), we don't need to emit a personalify
286 // function call
287 if (CPI->arg_size() == 1 &&
288 cast<Constant>(CPI->getArgOperand(0))->isNullValue())
289 prepareEHPad(BB, false);
290 else
291 prepareEHPad(BB, true, Index++);
292 }
293
294 // Cleanup pads don't need a personality function call.
295 for (auto *BB : CleanupPads)
296 prepareEHPad(BB, false);
297
298 return true;
299}
300
301// Prepare an EH pad for Wasm EH handling. If NeedPersonality is false, Index is
302// ignored.
303void WasmEHPrepareImpl::prepareEHPad(BasicBlock *BB, bool NeedPersonality,
304 unsigned Index) {
305 assert(BB->isEHPad() && "BB is not an EHPad!");
306 IRBuilder<> IRB(BB->getContext());
307 IRB.SetInsertPoint(BB, BB->getFirstInsertionPt());
308
309 auto *FPI = cast<FuncletPadInst>(BB->getFirstNonPHIIt());
310 Instruction *GetExnCI = nullptr, *GetSelectorCI = nullptr;
311 for (auto &U : FPI->uses()) {
312 if (auto *CI = dyn_cast<CallInst>(U.getUser())) {
313 if (CI->getCalledOperand() == GetExnF)
314 GetExnCI = CI;
315 if (CI->getCalledOperand() == GetSelectorF)
316 GetSelectorCI = CI;
317 }
318 }
319
320 // Cleanup pads do not have any of wasm.get.exception() or
321 // wasm.get.ehselector() calls. We need to do nothing.
322 if (!GetExnCI) {
323 assert(!GetSelectorCI &&
324 "wasm.get.ehselector() cannot exist w/o wasm.get.exception()");
325 return;
326 }
327
328 // Replace wasm.get.exception intrinsic with wasm.catch intrinsic, which will
329 // be lowered to wasm 'catch' instruction. We do this mainly because
330 // instruction selection cannot handle wasm.get.exception intrinsic's token
331 // argument.
332 Instruction *CatchCI =
333 IRB.CreateCall(CatchF, {IRB.getInt32(WebAssembly::CPP_EXCEPTION)}, "exn");
334 GetExnCI->replaceAllUsesWith(CatchCI);
335 GetExnCI->eraseFromParent();
336
337 // In case it is a catchpad with single catch (...) or a cleanuppad, we don't
338 // need to call personality function because we don't need a selector.
339 if (!NeedPersonality) {
340 if (GetSelectorCI) {
341 assert(GetSelectorCI->use_empty() &&
342 "wasm.get.ehselector() still has uses!");
343 GetSelectorCI->eraseFromParent();
344 }
345 return;
346 }
347 IRB.SetInsertPoint(CatchCI->getNextNode());
348
349 // This is to create a map of <landingpad EH label, landingpad index> in
350 // SelectionDAGISel, which is to be used in EHStreamer to emit LSDA tables.
351 // Pseudocode: wasm.landingpad.index(Index);
352 IRB.CreateCall(LPadIndexF, {FPI, IRB.getInt32(Index)});
353
354 // Pseudocode: __wasm_lpad_context.lpad_index = index;
355 IRB.CreateStore(IRB.getInt32(Index), LPadIndexField);
356
357 // TODO Sometimes storing the LSDA address every time is not necessary, in
358 // case it is already set in a dominating EH pad and there is no function call
359 // between from that EH pad to here. Consider optimizing those cases.
360 // Pseudocode: __wasm_lpad_context.lsda = wasm.lsda();
361 IRB.CreateStore(IRB.CreateCall(LSDAF), LSDAField);
362
363 // Pseudocode: personality_fn(exn);
364 CallInst *PersCI =
365 IRB.CreateCall(PersonalityF, CatchCI, OperandBundleDef("funclet", FPI));
366 PersCI->setDoesNotThrow();
367
368 // Pseudocode: int selector = __wasm_lpad_context.selector;
369 Instruction *Selector =
370 IRB.CreateLoad(IRB.getInt32Ty(), SelectorField, "selector");
371
372 // Replace the return value from wasm.get.ehselector() with the selector value
373 // loaded from __wasm_lpad_context.selector.
374 assert(GetSelectorCI && "wasm.get.ehselector() call does not exist");
375 GetSelectorCI->replaceAllUsesWith(Selector);
376 GetSelectorCI->eraseFromParent();
377}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static bool runOnFunction(Function &F, bool PostInlining)
#define DEBUG_TYPE
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define P(N)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
static void eraseDeadBBsAndChildren(const Container &BBs)
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
bool isEHPad() const
Return true if this basic block is an exception handling block.
Definition BasicBlock.h:689
void setDoesNotThrow()
This class represents a function call, abstracting a target machine's calling convention.
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition Constants.h:1474
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static GEPNoWrapFlags inBounds()
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2903
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:887
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:467
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
iterator_range< user_iterator > users()
Definition Value.h:428
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM)
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
Changed
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI StringRef getEHPersonalityName(EHPersonality Pers)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
LLVM_ABI FunctionPass * createWasmEHPass()
createWasmEHPass - This pass adapts exception handling code to use WebAssembly's exception handling s...
LLVM_ABI void DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified block, which must have no predecessors.
bool isScopedEHPersonality(EHPersonality Pers)
Returns true if this personality uses scope-style EH IR instructions: catchswitch,...
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
RNSuccIterator< NodeRef, BlockT, RegionT > succ_begin(NodeRef Node)
RNSuccIterator< NodeRef, BlockT, RegionT > succ_end(NodeRef Node)
OperandBundleDefT< Value * > OperandBundleDef
Definition AutoUpgrade.h:34
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.