blob: 9c33508a3df18fe0de1cb685f7c818bbf649b136 [file] [log] [blame]
Derek Schuffccdceda2016-08-18 15:27:25 +00001//=== WebAssemblyLowerEmscriptenEHSjLj.cpp - Lower exceptions for Emscripten =//
Derek Schufff41f67d2016-08-01 21:34:04 +00002//
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
Derek Schufff41f67d2016-08-01 21:34:04 +00006//
7//===----------------------------------------------------------------------===//
8///
9/// \file
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000010/// This file lowers exception-related instructions and setjmp/longjmp
Heejin Ahnc0f18172016-09-01 21:05:15 +000011/// function calls in order to use Emscripten's JavaScript try and catch
12/// mechanism.
Derek Schufff41f67d2016-08-01 21:34:04 +000013///
Heejin Ahnc0f18172016-09-01 21:05:15 +000014/// To handle exceptions and setjmp/longjmps, this scheme relies on JavaScript's
15/// try and catch syntax and relevant exception-related libraries implemented
16/// in JavaScript glue code that will be produced by Emscripten. This is similar
17/// to the current Emscripten asm.js exception handling in fastcomp. For
18/// fastcomp's EH / SjLj scheme, see these files in fastcomp LLVM branch:
Derek Schufff41f67d2016-08-01 21:34:04 +000019/// (Location: https://github.com/kripken/emscripten-fastcomp)
20/// lib/Target/JSBackend/NaCl/LowerEmExceptionsPass.cpp
Heejin Ahnc0f18172016-09-01 21:05:15 +000021/// lib/Target/JSBackend/NaCl/LowerEmSetjmp.cpp
Derek Schufff41f67d2016-08-01 21:34:04 +000022/// lib/Target/JSBackend/JSBackend.cpp
23/// lib/Target/JSBackend/CallHandlers.h
24///
Heejin Ahnc0f18172016-09-01 21:05:15 +000025/// * Exception handling
26/// This pass lowers invokes and landingpads into library functions in JS glue
27/// code. Invokes are lowered into function wrappers called invoke wrappers that
28/// exist in JS side, which wraps the original function call with JS try-catch.
29/// If an exception occurred, cxa_throw() function in JS side sets some
30/// variables (see below) so we can check whether an exception occurred from
31/// wasm code and handle it appropriately.
Derek Schufff41f67d2016-08-01 21:34:04 +000032///
Heejin Ahnc0f18172016-09-01 21:05:15 +000033/// * Setjmp-longjmp handling
34/// This pass lowers setjmp to a reasonably-performant approach for emscripten.
35/// The idea is that each block with a setjmp is broken up into two parts: the
36/// part containing setjmp and the part right after the setjmp. The latter part
37/// is either reached from the setjmp, or later from a longjmp. To handle the
38/// longjmp, all calls that might longjmp are also called using invoke wrappers
39/// and thus JS / try-catch. JS longjmp() function also sets some variables so
40/// we can check / whether a longjmp occurred from wasm code. Each block with a
41/// function call that might longjmp is also split up after the longjmp call.
42/// After the longjmp call, we check whether a longjmp occurred, and if it did,
43/// which setjmp it corresponds to, and jump to the right post-setjmp block.
44/// We assume setjmp-longjmp handling always run after EH handling, which means
45/// we don't expect any exception-related instructions when SjLj runs.
46/// FIXME Currently this scheme does not support indirect call of setjmp,
47/// because of the limitation of the scheme itself. fastcomp does not support it
48/// either.
49///
50/// In detail, this pass does following things:
51///
Sam Clegg4791a662018-11-20 19:25:07 +000052/// 1) Assumes the existence of global variables: __THREW__, __threwValue
53/// __THREW__ and __threwValue will be set in invoke wrappers
Heejin Ahnc0f18172016-09-01 21:05:15 +000054/// in JS glue code. For what invoke wrappers are, refer to 3). These
55/// variables are used for both exceptions and setjmp/longjmps.
56/// __THREW__ indicates whether an exception or a longjmp occurred or not. 0
57/// means nothing occurred, 1 means an exception occurred, and other numbers
Heejin Ahn99bd16b2016-09-10 02:33:47 +000058/// mean a longjmp occurred. In the case of longjmp, __threwValue variable
Heejin Ahnc0f18172016-09-01 21:05:15 +000059/// indicates the corresponding setjmp buffer the longjmp corresponds to.
Heejin Ahnc0f18172016-09-01 21:05:15 +000060///
61/// * Exception handling
Derek Schufff41f67d2016-08-01 21:34:04 +000062///
Sam Clegg4791a662018-11-20 19:25:07 +000063/// 2) We assume the existence of setThrew and setTempRet0/getTempRet0 functions
64/// at link time.
Sam Cleggb2486f12018-10-02 22:12:15 +000065/// The global variables in 1) will exist in wasm address space,
66/// but their values should be set in JS code, so these functions
Derek Schufff41f67d2016-08-01 21:34:04 +000067/// as interfaces to JS glue code. These functions are equivalent to the
68/// following JS functions, which actually exist in asm.js version of JS
69/// library.
70///
71/// function setThrew(threw, value) {
72/// if (__THREW__ == 0) {
73/// __THREW__ = threw;
Derek Schuffccdceda2016-08-18 15:27:25 +000074/// __threwValue = value;
Derek Schufff41f67d2016-08-01 21:34:04 +000075/// }
76/// }
Sam Clegg4791a662018-11-20 19:25:07 +000077//
78/// setTempRet0 is called from __cxa_find_matching_catch() in JS glue code.
Derek Schufff41f67d2016-08-01 21:34:04 +000079///
Sam Clegg4791a662018-11-20 19:25:07 +000080/// In exception handling, getTempRet0 indicates the type of an exception
81/// caught, and in setjmp/longjmp, it means the second argument to longjmp
82/// function.
Derek Schufff41f67d2016-08-01 21:34:04 +000083///
84/// 3) Lower
85/// invoke @func(arg1, arg2) to label %invoke.cont unwind label %lpad
86/// into
87/// __THREW__ = 0;
Heejin Ahn99bd16b2016-09-10 02:33:47 +000088/// call @__invoke_SIG(func, arg1, arg2)
Derek Schufff41f67d2016-08-01 21:34:04 +000089/// %__THREW__.val = __THREW__;
90/// __THREW__ = 0;
Heejin Ahn99bd16b2016-09-10 02:33:47 +000091/// if (%__THREW__.val == 1)
92/// goto %lpad
93/// else
94/// goto %invoke.cont
Derek Schufff41f67d2016-08-01 21:34:04 +000095/// SIG is a mangled string generated based on the LLVM IR-level function
96/// signature. After LLVM IR types are lowered to the target wasm types,
97/// the names for these wrappers will change based on wasm types as well,
98/// as in invoke_vi (function takes an int and returns void). The bodies of
99/// these wrappers will be generated in JS glue code, and inside those
100/// wrappers we use JS try-catch to generate actual exception effects. It
101/// also calls the original callee function. An example wrapper in JS code
102/// would look like this:
103/// function invoke_vi(index,a1) {
104/// try {
105/// Module["dynCall_vi"](index,a1); // This calls original callee
106/// } catch(e) {
107/// if (typeof e !== 'number' && e !== 'longjmp') throw e;
108/// asm["setThrew"](1, 0); // setThrew is called here
109/// }
110/// }
111/// If an exception is thrown, __THREW__ will be set to true in a wrapper,
112/// so we can jump to the right BB based on this value.
113///
114/// 4) Lower
115/// %val = landingpad catch c1 catch c2 catch c3 ...
116/// ... use %val ...
117/// into
Derek Schuff53b9af02016-08-09 00:29:55 +0000118/// %fmc = call @__cxa_find_matching_catch_N(c1, c2, c3, ...)
Sam Clegg4791a662018-11-20 19:25:07 +0000119/// %val = {%fmc, getTempRet0()}
Derek Schufff41f67d2016-08-01 21:34:04 +0000120/// ... use %val ...
121/// Here N is a number calculated based on the number of clauses.
Sam Clegg4791a662018-11-20 19:25:07 +0000122/// setTempRet0 is called from __cxa_find_matching_catch() in JS glue code.
Derek Schufff41f67d2016-08-01 21:34:04 +0000123///
124/// 5) Lower
125/// resume {%a, %b}
126/// into
Derek Schuff53b9af02016-08-09 00:29:55 +0000127/// call @__resumeException(%a)
128/// where __resumeException() is a function in JS glue code.
Derek Schufff41f67d2016-08-01 21:34:04 +0000129///
Derek Schuff53b9af02016-08-09 00:29:55 +0000130/// 6) Lower
131/// call @llvm.eh.typeid.for(type) (intrinsic)
132/// into
133/// call @llvm_eh_typeid_for(type)
134/// llvm_eh_typeid_for function will be generated in JS glue code.
Derek Schufff41f67d2016-08-01 21:34:04 +0000135///
Heejin Ahnc0f18172016-09-01 21:05:15 +0000136/// * Setjmp / Longjmp handling
137///
Heejin Ahn0c68a872018-11-08 22:56:26 +0000138/// In case calls to longjmp() exists
139///
140/// 1) Lower
141/// longjmp(buf, value)
142/// into
143/// emscripten_longjmp_jmpbuf(buf, value)
144/// emscripten_longjmp_jmpbuf will be lowered to emscripten_longjmp later.
145///
146/// In case calls to setjmp() exists
147///
148/// 2) In the function entry that calls setjmp, initialize setjmpTable and
Heejin Ahnc0f18172016-09-01 21:05:15 +0000149/// sejmpTableSize as follows:
150/// setjmpTableSize = 4;
151/// setjmpTable = (int *) malloc(40);
152/// setjmpTable[0] = 0;
153/// setjmpTable and setjmpTableSize are used in saveSetjmp() function in JS
154/// code.
155///
Heejin Ahn0c68a872018-11-08 22:56:26 +0000156/// 3) Lower
Heejin Ahnc0f18172016-09-01 21:05:15 +0000157/// setjmp(buf)
158/// into
159/// setjmpTable = saveSetjmp(buf, label, setjmpTable, setjmpTableSize);
Sam Clegg4791a662018-11-20 19:25:07 +0000160/// setjmpTableSize = getTempRet0();
Heejin Ahnc0f18172016-09-01 21:05:15 +0000161/// For each dynamic setjmp call, setjmpTable stores its ID (a number which
162/// is incrementally assigned from 0) and its label (a unique number that
163/// represents each callsite of setjmp). When we need more entries in
164/// setjmpTable, it is reallocated in saveSetjmp() in JS code and it will
165/// return the new table address, and assign the new table size in
Sam Clegg4791a662018-11-20 19:25:07 +0000166/// setTempRet0(). saveSetjmp also stores the setjmp's ID into the buffer
167/// buf. A BB with setjmp is split into two after setjmp call in order to
168/// make the post-setjmp BB the possible destination of longjmp BB.
Heejin Ahnc0f18172016-09-01 21:05:15 +0000169///
Heejin Ahnc0f18172016-09-01 21:05:15 +0000170///
Heejin Ahn0c68a872018-11-08 22:56:26 +0000171/// 4) Lower every call that might longjmp into
Heejin Ahnc0f18172016-09-01 21:05:15 +0000172/// __THREW__ = 0;
Heejin Ahn99bd16b2016-09-10 02:33:47 +0000173/// call @__invoke_SIG(func, arg1, arg2)
Heejin Ahnc0f18172016-09-01 21:05:15 +0000174/// %__THREW__.val = __THREW__;
175/// __THREW__ = 0;
Heejin Ahn99bd16b2016-09-10 02:33:47 +0000176/// if (%__THREW__.val != 0 & __threwValue != 0) {
Heejin Ahnc0f18172016-09-01 21:05:15 +0000177/// %label = testSetjmp(mem[%__THREW__.val], setjmpTable,
178/// setjmpTableSize);
179/// if (%label == 0)
Heejin Ahn99bd16b2016-09-10 02:33:47 +0000180/// emscripten_longjmp(%__THREW__.val, __threwValue);
Sam Clegg4791a662018-11-20 19:25:07 +0000181/// setTempRet0(__threwValue);
Heejin Ahnc0f18172016-09-01 21:05:15 +0000182/// } else {
183/// %label = -1;
184/// }
Sam Clegg4791a662018-11-20 19:25:07 +0000185/// longjmp_result = getTempRet0();
Heejin Ahnc0f18172016-09-01 21:05:15 +0000186/// switch label {
Heejin Ahn99bd16b2016-09-10 02:33:47 +0000187/// label 1: goto post-setjmp BB 1
188/// label 2: goto post-setjmp BB 2
Heejin Ahnc0f18172016-09-01 21:05:15 +0000189/// ...
Heejin Ahn99bd16b2016-09-10 02:33:47 +0000190/// default: goto splitted next BB
Heejin Ahnc0f18172016-09-01 21:05:15 +0000191/// }
Heejin Ahn0c68a872018-11-08 22:56:26 +0000192/// testSetjmp examines setjmpTable to see if there is a matching setjmp
193/// call. After calling an invoke wrapper, if a longjmp occurred, __THREW__
194/// will be the address of matching jmp_buf buffer and __threwValue be the
195/// second argument to longjmp. mem[__THREW__.val] is a setjmp ID that is
196/// stored in saveSetjmp. testSetjmp returns a setjmp label, a unique ID to
197/// each setjmp callsite. Label 0 means this longjmp buffer does not
198/// correspond to one of the setjmp callsites in this function, so in this
199/// case we just chain the longjmp to the caller. (Here we call
200/// emscripten_longjmp, which is different from emscripten_longjmp_jmpbuf.
201/// emscripten_longjmp_jmpbuf takes jmp_buf as its first argument, while
202/// emscripten_longjmp takes an int. Both of them will eventually be lowered
203/// to emscripten_longjmp in s2wasm, but here we need two signatures - we
204/// can't translate an int value to a jmp_buf.)
205/// Label -1 means no longjmp occurred. Otherwise we jump to the right
206/// post-setjmp BB based on the label.
Heejin Ahnc0f18172016-09-01 21:05:15 +0000207///
Derek Schufff41f67d2016-08-01 21:34:04 +0000208///===----------------------------------------------------------------------===//
209
210#include "WebAssembly.h"
Derek Schuff53b9af02016-08-09 00:29:55 +0000211#include "llvm/IR/CallSite.h"
Heejin Ahnc0f18172016-09-01 21:05:15 +0000212#include "llvm/IR/Dominators.h"
Derek Schufff41f67d2016-08-01 21:34:04 +0000213#include "llvm/IR/IRBuilder.h"
Heejin Ahnc0f18172016-09-01 21:05:15 +0000214#include "llvm/Transforms/Utils/BasicBlockUtils.h"
215#include "llvm/Transforms/Utils/SSAUpdater.h"
Derek Schufff41f67d2016-08-01 21:34:04 +0000216
217using namespace llvm;
218
Derek Schuffccdceda2016-08-18 15:27:25 +0000219#define DEBUG_TYPE "wasm-lower-em-ehsjlj"
Derek Schufff41f67d2016-08-01 21:34:04 +0000220
Derek Schuff66641322016-08-09 22:37:00 +0000221static cl::list<std::string>
Derek Schuffccdceda2016-08-18 15:27:25 +0000222 EHWhitelist("emscripten-cxx-exceptions-whitelist",
223 cl::desc("The list of function names in which Emscripten-style "
224 "exception handling is enabled (see emscripten "
225 "EMSCRIPTEN_CATCHING_WHITELIST options)"),
226 cl::CommaSeparated);
Derek Schuff66641322016-08-09 22:37:00 +0000227
Derek Schufff41f67d2016-08-01 21:34:04 +0000228namespace {
Derek Schuffccdceda2016-08-18 15:27:25 +0000229class WebAssemblyLowerEmscriptenEHSjLj final : public ModulePass {
Derek Schuffccdceda2016-08-18 15:27:25 +0000230 static const char *ResumeFName;
231 static const char *EHTypeIDFName;
Heejin Ahnc0f18172016-09-01 21:05:15 +0000232 static const char *EmLongjmpFName;
233 static const char *EmLongjmpJmpbufFName;
234 static const char *SaveSetjmpFName;
235 static const char *TestSetjmpFName;
Derek Schuffccdceda2016-08-18 15:27:25 +0000236 static const char *FindMatchingCatchPrefix;
237 static const char *InvokePrefix;
238
Heejin Ahnc0f18172016-09-01 21:05:15 +0000239 bool EnableEH; // Enable exception handling
240 bool EnableSjLj; // Enable setjmp/longjmp handling
Derek Schuffccdceda2016-08-18 15:27:25 +0000241
Heejin Ahn18c56a02019-02-04 19:13:39 +0000242 GlobalVariable *ThrewGV = nullptr;
243 GlobalVariable *ThrewValueGV = nullptr;
244 Function *GetTempRet0Func = nullptr;
245 Function *SetTempRet0Func = nullptr;
246 Function *ResumeF = nullptr;
247 Function *EHTypeIDF = nullptr;
248 Function *EmLongjmpF = nullptr;
249 Function *EmLongjmpJmpbufF = nullptr;
250 Function *SaveSetjmpF = nullptr;
251 Function *TestSetjmpF = nullptr;
Heejin Ahnc0f18172016-09-01 21:05:15 +0000252
Derek Schuffccdceda2016-08-18 15:27:25 +0000253 // __cxa_find_matching_catch_N functions.
254 // Indexed by the number of clauses in an original landingpad instruction.
255 DenseMap<int, Function *> FindMatchingCatches;
256 // Map of <function signature string, invoke_ wrappers>
257 StringMap<Function *> InvokeWrappers;
258 // Set of whitelisted function names for exception handling
259 std::set<std::string> EHWhitelistSet;
260
Mehdi Amini117296c2016-10-01 02:56:57 +0000261 StringRef getPassName() const override {
Derek Schufff41f67d2016-08-01 21:34:04 +0000262 return "WebAssembly Lower Emscripten Exceptions";
263 }
264
Derek Schuffccdceda2016-08-18 15:27:25 +0000265 bool runEHOnFunction(Function &F);
266 bool runSjLjOnFunction(Function &F);
Derek Schufff41f67d2016-08-01 21:34:04 +0000267 Function *getFindMatchingCatch(Module &M, unsigned NumClauses);
268
Heejin Ahnc0f18172016-09-01 21:05:15 +0000269 template <typename CallOrInvoke> Value *wrapInvoke(CallOrInvoke *CI);
270 void wrapTestSetjmp(BasicBlock *BB, Instruction *InsertPt, Value *Threw,
271 Value *SetjmpTable, Value *SetjmpTableSize, Value *&Label,
272 Value *&LongjmpResult, BasicBlock *&EndBB);
273 template <typename CallOrInvoke> Function *getInvokeWrapper(CallOrInvoke *CI);
274
Derek Schuffccdceda2016-08-18 15:27:25 +0000275 bool areAllExceptionsAllowed() const { return EHWhitelistSet.empty(); }
Heejin Ahnc0f18172016-09-01 21:05:15 +0000276 bool canLongjmp(Module &M, const Value *Callee) const;
277
Heejin Ahnc0f18172016-09-01 21:05:15 +0000278 void rebuildSSA(Function &F);
Derek Schufff41f67d2016-08-01 21:34:04 +0000279
280public:
281 static char ID;
282
Heejin Ahnc0f18172016-09-01 21:05:15 +0000283 WebAssemblyLowerEmscriptenEHSjLj(bool EnableEH = true, bool EnableSjLj = true)
Heejin Ahn18c56a02019-02-04 19:13:39 +0000284 : ModulePass(ID), EnableEH(EnableEH), EnableSjLj(EnableSjLj) {
Derek Schuffccdceda2016-08-18 15:27:25 +0000285 EHWhitelistSet.insert(EHWhitelist.begin(), EHWhitelist.end());
Derek Schuff66641322016-08-09 22:37:00 +0000286 }
Derek Schufff41f67d2016-08-01 21:34:04 +0000287 bool runOnModule(Module &M) override;
Heejin Ahnc0f18172016-09-01 21:05:15 +0000288
289 void getAnalysisUsage(AnalysisUsage &AU) const override {
290 AU.addRequired<DominatorTreeWrapperPass>();
291 }
Derek Schufff41f67d2016-08-01 21:34:04 +0000292};
293} // End anonymous namespace
294
Derek Schuffccdceda2016-08-18 15:27:25 +0000295const char *WebAssemblyLowerEmscriptenEHSjLj::ResumeFName = "__resumeException";
296const char *WebAssemblyLowerEmscriptenEHSjLj::EHTypeIDFName =
297 "llvm_eh_typeid_for";
Heejin Ahnc0f18172016-09-01 21:05:15 +0000298const char *WebAssemblyLowerEmscriptenEHSjLj::EmLongjmpFName =
299 "emscripten_longjmp";
300const char *WebAssemblyLowerEmscriptenEHSjLj::EmLongjmpJmpbufFName =
301 "emscripten_longjmp_jmpbuf";
302const char *WebAssemblyLowerEmscriptenEHSjLj::SaveSetjmpFName = "saveSetjmp";
303const char *WebAssemblyLowerEmscriptenEHSjLj::TestSetjmpFName = "testSetjmp";
Derek Schuffccdceda2016-08-18 15:27:25 +0000304const char *WebAssemblyLowerEmscriptenEHSjLj::FindMatchingCatchPrefix =
305 "__cxa_find_matching_catch_";
306const char *WebAssemblyLowerEmscriptenEHSjLj::InvokePrefix = "__invoke_";
Derek Schufff41f67d2016-08-01 21:34:04 +0000307
Derek Schuffccdceda2016-08-18 15:27:25 +0000308char WebAssemblyLowerEmscriptenEHSjLj::ID = 0;
309INITIALIZE_PASS(WebAssemblyLowerEmscriptenEHSjLj, DEBUG_TYPE,
310 "WebAssembly Lower Emscripten Exceptions / Setjmp / Longjmp",
311 false, false)
312
Heejin Ahnc0f18172016-09-01 21:05:15 +0000313ModulePass *llvm::createWebAssemblyLowerEmscriptenEHSjLj(bool EnableEH,
314 bool EnableSjLj) {
315 return new WebAssemblyLowerEmscriptenEHSjLj(EnableEH, EnableSjLj);
Derek Schufff41f67d2016-08-01 21:34:04 +0000316}
317
318static bool canThrow(const Value *V) {
319 if (const auto *F = dyn_cast<const Function>(V)) {
320 // Intrinsics cannot throw
321 if (F->isIntrinsic())
322 return false;
323 StringRef Name = F->getName();
324 // leave setjmp and longjmp (mostly) alone, we process them properly later
325 if (Name == "setjmp" || Name == "longjmp")
326 return false;
Heejin Ahnc0f18172016-09-01 21:05:15 +0000327 return !F->doesNotThrow();
Derek Schufff41f67d2016-08-01 21:34:04 +0000328 }
Heejin Ahnb6cd5122016-08-24 22:53:00 +0000329 // not a function, so an indirect call - can throw, we can't tell
330 return true;
Derek Schufff41f67d2016-08-01 21:34:04 +0000331}
332
Sam Cleggb2486f12018-10-02 22:12:15 +0000333// Get a global variable with the given name. If it doesn't exist declare it,
334// which will generate an import and asssumes that it will exist at link time.
335static GlobalVariable *getGlobalVariableI32(Module &M, IRBuilder<> &IRB,
336 const char *Name) {
Sam Clegg28b3e992018-07-17 16:40:03 +0000337 if (M.getNamedGlobal(Name))
338 report_fatal_error(Twine("variable name is reserved: ") + Name);
339
340 return new GlobalVariable(M, IRB.getInt32Ty(), false,
Sam Cleggb2486f12018-10-02 22:12:15 +0000341 GlobalValue::ExternalLinkage, nullptr, Name);
Derek Schufff41f67d2016-08-01 21:34:04 +0000342}
343
344// Simple function name mangler.
345// This function simply takes LLVM's string representation of parameter types
Derek Schuff53b9af02016-08-09 00:29:55 +0000346// and concatenate them with '_'. There are non-alphanumeric characters but llc
347// is ok with it, and we need to postprocess these names after the lowering
348// phase anyway.
Derek Schufff41f67d2016-08-01 21:34:04 +0000349static std::string getSignature(FunctionType *FTy) {
350 std::string Sig;
351 raw_string_ostream OS(Sig);
352 OS << *FTy->getReturnType();
353 for (Type *ParamTy : FTy->params())
354 OS << "_" << *ParamTy;
355 if (FTy->isVarArg())
356 OS << "_...";
357 Sig = OS.str();
David Majnemerc7004902016-08-12 04:32:37 +0000358 Sig.erase(remove_if(Sig, isspace), Sig.end());
Derek Schuff53b9af02016-08-09 00:29:55 +0000359 // When s2wasm parses .s file, a comma means the end of an argument. So a
360 // mangled function name can contain any character but a comma.
361 std::replace(Sig.begin(), Sig.end(), ',', '.');
Derek Schufff41f67d2016-08-01 21:34:04 +0000362 return Sig;
363}
364
Heejin Ahnc0f18172016-09-01 21:05:15 +0000365// Returns __cxa_find_matching_catch_N function, where N = NumClauses + 2.
366// This is because a landingpad instruction contains two more arguments, a
367// personality function and a cleanup bit, and __cxa_find_matching_catch_N
368// functions are named after the number of arguments in the original landingpad
369// instruction.
Derek Schuffccdceda2016-08-18 15:27:25 +0000370Function *
371WebAssemblyLowerEmscriptenEHSjLj::getFindMatchingCatch(Module &M,
372 unsigned NumClauses) {
Derek Schufff41f67d2016-08-01 21:34:04 +0000373 if (FindMatchingCatches.count(NumClauses))
374 return FindMatchingCatches[NumClauses];
375 PointerType *Int8PtrTy = Type::getInt8PtrTy(M.getContext());
376 SmallVector<Type *, 16> Args(NumClauses, Int8PtrTy);
377 FunctionType *FTy = FunctionType::get(Int8PtrTy, Args, false);
Derek Schuffccdceda2016-08-18 15:27:25 +0000378 Function *F =
379 Function::Create(FTy, GlobalValue::ExternalLinkage,
380 FindMatchingCatchPrefix + Twine(NumClauses + 2), &M);
Derek Schufff41f67d2016-08-01 21:34:04 +0000381 FindMatchingCatches[NumClauses] = F;
382 return F;
383}
384
Heejin Ahnc0f18172016-09-01 21:05:15 +0000385// Generate invoke wrapper seqence with preamble and postamble
386// Preamble:
387// __THREW__ = 0;
388// Postamble:
389// %__THREW__.val = __THREW__; __THREW__ = 0;
390// Returns %__THREW__.val, which indicates whether an exception is thrown (or
391// whether longjmp occurred), for future use.
392template <typename CallOrInvoke>
393Value *WebAssemblyLowerEmscriptenEHSjLj::wrapInvoke(CallOrInvoke *CI) {
394 LLVMContext &C = CI->getModule()->getContext();
395
396 // If we are calling a function that is noreturn, we must remove that
397 // attribute. The code we insert here does expect it to return, after we
398 // catch the exception.
399 if (CI->doesNotReturn()) {
400 if (auto *F = dyn_cast<Function>(CI->getCalledValue()))
401 F->removeFnAttr(Attribute::NoReturn);
Reid Klecknerb5180542017-03-21 16:57:19 +0000402 CI->removeAttribute(AttributeList::FunctionIndex, Attribute::NoReturn);
Heejin Ahnc0f18172016-09-01 21:05:15 +0000403 }
404
405 IRBuilder<> IRB(C);
406 IRB.SetInsertPoint(CI);
407
408 // Pre-invoke
409 // __THREW__ = 0;
410 IRB.CreateStore(IRB.getInt32(0), ThrewGV);
411
412 // Invoke function wrapper in JavaScript
413 SmallVector<Value *, 16> Args;
414 // Put the pointer to the callee as first argument, so it can be called
415 // within the invoke wrapper later
416 Args.push_back(CI->getCalledValue());
417 Args.append(CI->arg_begin(), CI->arg_end());
418 CallInst *NewCall = IRB.CreateCall(getInvokeWrapper(CI), Args);
419 NewCall->takeName(CI);
420 NewCall->setCallingConv(CI->getCallingConv());
421 NewCall->setDebugLoc(CI->getDebugLoc());
422
423 // Because we added the pointer to the callee as first argument, all
424 // argument attribute indices have to be incremented by one.
Reid Kleckner7f720332017-04-13 00:58:09 +0000425 SmallVector<AttributeSet, 8> ArgAttributes;
Derek Schuff0db0ca32017-04-12 16:03:00 +0000426 const AttributeList &InvokeAL = CI->getAttributes();
427
Derek Schuff0db0ca32017-04-12 16:03:00 +0000428 // No attributes for the callee pointer.
Reid Kleckner7f720332017-04-13 00:58:09 +0000429 ArgAttributes.push_back(AttributeSet());
Derek Schuff0db0ca32017-04-12 16:03:00 +0000430 // Copy the argument attributes from the original
Heejin Ahn18c56a02019-02-04 19:13:39 +0000431 for (unsigned I = 0, E = CI->getNumArgOperands(); I < E; ++I)
432 ArgAttributes.push_back(InvokeAL.getParamAttributes(I));
Derek Schuff0db0ca32017-04-12 16:03:00 +0000433
Heejin Ahnc0f18172016-09-01 21:05:15 +0000434 // Reconstruct the AttributesList based on the vector we constructed.
Reid Kleckner7f720332017-04-13 00:58:09 +0000435 AttributeList NewCallAL =
436 AttributeList::get(C, InvokeAL.getFnAttributes(),
437 InvokeAL.getRetAttributes(), ArgAttributes);
Derek Schuff0db0ca32017-04-12 16:03:00 +0000438 NewCall->setAttributes(NewCallAL);
Heejin Ahnc0f18172016-09-01 21:05:15 +0000439
440 CI->replaceAllUsesWith(NewCall);
441
442 // Post-invoke
443 // %__THREW__.val = __THREW__; __THREW__ = 0;
James Y Knight14359ef2019-02-01 20:44:24 +0000444 Value *Threw =
445 IRB.CreateLoad(IRB.getInt32Ty(), ThrewGV, ThrewGV->getName() + ".val");
Heejin Ahnc0f18172016-09-01 21:05:15 +0000446 IRB.CreateStore(IRB.getInt32(0), ThrewGV);
447 return Threw;
448}
449
450// Get matching invoke wrapper based on callee signature
451template <typename CallOrInvoke>
452Function *WebAssemblyLowerEmscriptenEHSjLj::getInvokeWrapper(CallOrInvoke *CI) {
453 Module *M = CI->getModule();
Derek Schufff41f67d2016-08-01 21:34:04 +0000454 SmallVector<Type *, 16> ArgTys;
Heejin Ahnc0f18172016-09-01 21:05:15 +0000455 Value *Callee = CI->getCalledValue();
Derek Schufff41f67d2016-08-01 21:34:04 +0000456 FunctionType *CalleeFTy;
457 if (auto *F = dyn_cast<Function>(Callee))
458 CalleeFTy = F->getFunctionType();
459 else {
Heejin Ahnc0f18172016-09-01 21:05:15 +0000460 auto *CalleeTy = cast<PointerType>(Callee->getType())->getElementType();
Derek Schufff41f67d2016-08-01 21:34:04 +0000461 CalleeFTy = dyn_cast<FunctionType>(CalleeTy);
462 }
463
464 std::string Sig = getSignature(CalleeFTy);
465 if (InvokeWrappers.find(Sig) != InvokeWrappers.end())
466 return InvokeWrappers[Sig];
467
468 // Put the pointer to the callee as first argument
469 ArgTys.push_back(PointerType::getUnqual(CalleeFTy));
470 // Add argument types
471 ArgTys.append(CalleeFTy->param_begin(), CalleeFTy->param_end());
472
473 FunctionType *FTy = FunctionType::get(CalleeFTy->getReturnType(), ArgTys,
474 CalleeFTy->isVarArg());
475 Function *F = Function::Create(FTy, GlobalValue::ExternalLinkage,
Heejin Ahnc0f18172016-09-01 21:05:15 +0000476 InvokePrefix + Sig, M);
Derek Schufff41f67d2016-08-01 21:34:04 +0000477 InvokeWrappers[Sig] = F;
478 return F;
479}
480
Heejin Ahnc0f18172016-09-01 21:05:15 +0000481bool WebAssemblyLowerEmscriptenEHSjLj::canLongjmp(Module &M,
482 const Value *Callee) const {
483 if (auto *CalleeF = dyn_cast<Function>(Callee))
484 if (CalleeF->isIntrinsic())
485 return false;
Heejin Ahn23d57102016-08-31 22:40:34 +0000486
Heejin Ahnc0f18172016-09-01 21:05:15 +0000487 // The reason we include malloc/free here is to exclude the malloc/free
488 // calls generated in setjmp prep / cleanup routines.
489 Function *SetjmpF = M.getFunction("setjmp");
490 Function *MallocF = M.getFunction("malloc");
491 Function *FreeF = M.getFunction("free");
492 if (Callee == SetjmpF || Callee == MallocF || Callee == FreeF)
Heejin Ahn10a70862016-09-01 00:44:37 +0000493 return false;
494
Heejin Ahnc0f18172016-09-01 21:05:15 +0000495 // There are functions in JS glue code
496 if (Callee == ResumeF || Callee == EHTypeIDF || Callee == SaveSetjmpF ||
497 Callee == TestSetjmpF)
498 return false;
Heejin Ahn10a70862016-09-01 00:44:37 +0000499
Heejin Ahnc0f18172016-09-01 21:05:15 +0000500 // __cxa_find_matching_catch_N functions cannot longjmp
501 if (Callee->getName().startswith(FindMatchingCatchPrefix))
502 return false;
503
504 // Exception-catching related functions
505 Function *BeginCatchF = M.getFunction("__cxa_begin_catch");
506 Function *EndCatchF = M.getFunction("__cxa_end_catch");
507 Function *AllocExceptionF = M.getFunction("__cxa_allocate_exception");
508 Function *ThrowF = M.getFunction("__cxa_throw");
509 Function *TerminateF = M.getFunction("__clang_call_terminate");
510 if (Callee == BeginCatchF || Callee == EndCatchF ||
Sam Clegg4791a662018-11-20 19:25:07 +0000511 Callee == AllocExceptionF || Callee == ThrowF || Callee == TerminateF ||
512 Callee == GetTempRet0Func || Callee == SetTempRet0Func)
Heejin Ahnc0f18172016-09-01 21:05:15 +0000513 return false;
514
515 // Otherwise we don't know
516 return true;
517}
518
519// Generate testSetjmp function call seqence with preamble and postamble.
520// The code this generates is equivalent to the following JavaScript code:
521// if (%__THREW__.val != 0 & threwValue != 0) {
522// %label = _testSetjmp(mem[%__THREW__.val], setjmpTable, setjmpTableSize);
523// if (%label == 0)
524// emscripten_longjmp(%__THREW__.val, threwValue);
Sam Clegg4791a662018-11-20 19:25:07 +0000525// setTempRet0(threwValue);
Heejin Ahnc0f18172016-09-01 21:05:15 +0000526// } else {
527// %label = -1;
528// }
Sam Clegg4791a662018-11-20 19:25:07 +0000529// %longjmp_result = getTempRet0();
Heejin Ahnc0f18172016-09-01 21:05:15 +0000530//
531// As output parameters. returns %label, %longjmp_result, and the BB the last
532// instruction (%longjmp_result = ...) is in.
533void WebAssemblyLowerEmscriptenEHSjLj::wrapTestSetjmp(
534 BasicBlock *BB, Instruction *InsertPt, Value *Threw, Value *SetjmpTable,
535 Value *SetjmpTableSize, Value *&Label, Value *&LongjmpResult,
536 BasicBlock *&EndBB) {
537 Function *F = BB->getParent();
538 LLVMContext &C = BB->getModule()->getContext();
539 IRBuilder<> IRB(C);
540 IRB.SetInsertPoint(InsertPt);
541
542 // if (%__THREW__.val != 0 & threwValue != 0)
543 IRB.SetInsertPoint(BB);
544 BasicBlock *ThenBB1 = BasicBlock::Create(C, "if.then1", F);
545 BasicBlock *ElseBB1 = BasicBlock::Create(C, "if.else1", F);
546 BasicBlock *EndBB1 = BasicBlock::Create(C, "if.end", F);
547 Value *ThrewCmp = IRB.CreateICmpNE(Threw, IRB.getInt32(0));
James Y Knight14359ef2019-02-01 20:44:24 +0000548 Value *ThrewValue = IRB.CreateLoad(IRB.getInt32Ty(), ThrewValueGV,
549 ThrewValueGV->getName() + ".val");
Heejin Ahnc0f18172016-09-01 21:05:15 +0000550 Value *ThrewValueCmp = IRB.CreateICmpNE(ThrewValue, IRB.getInt32(0));
551 Value *Cmp1 = IRB.CreateAnd(ThrewCmp, ThrewValueCmp, "cmp1");
552 IRB.CreateCondBr(Cmp1, ThenBB1, ElseBB1);
553
554 // %label = _testSetjmp(mem[%__THREW__.val], _setjmpTable, _setjmpTableSize);
555 // if (%label == 0)
556 IRB.SetInsertPoint(ThenBB1);
557 BasicBlock *ThenBB2 = BasicBlock::Create(C, "if.then2", F);
558 BasicBlock *EndBB2 = BasicBlock::Create(C, "if.end2", F);
559 Value *ThrewInt = IRB.CreateIntToPtr(Threw, Type::getInt32PtrTy(C),
560 Threw->getName() + ".i32p");
James Y Knight14359ef2019-02-01 20:44:24 +0000561 Value *LoadedThrew = IRB.CreateLoad(IRB.getInt32Ty(), ThrewInt,
562 ThrewInt->getName() + ".loaded");
Heejin Ahnc0f18172016-09-01 21:05:15 +0000563 Value *ThenLabel = IRB.CreateCall(
564 TestSetjmpF, {LoadedThrew, SetjmpTable, SetjmpTableSize}, "label");
565 Value *Cmp2 = IRB.CreateICmpEQ(ThenLabel, IRB.getInt32(0));
566 IRB.CreateCondBr(Cmp2, ThenBB2, EndBB2);
567
568 // emscripten_longjmp(%__THREW__.val, threwValue);
569 IRB.SetInsertPoint(ThenBB2);
570 IRB.CreateCall(EmLongjmpF, {Threw, ThrewValue});
571 IRB.CreateUnreachable();
572
Sam Clegg4791a662018-11-20 19:25:07 +0000573 // setTempRet0(threwValue);
Heejin Ahnc0f18172016-09-01 21:05:15 +0000574 IRB.SetInsertPoint(EndBB2);
Sam Clegg4791a662018-11-20 19:25:07 +0000575 IRB.CreateCall(SetTempRet0Func, ThrewValue);
Heejin Ahnc0f18172016-09-01 21:05:15 +0000576 IRB.CreateBr(EndBB1);
577
578 IRB.SetInsertPoint(ElseBB1);
579 IRB.CreateBr(EndBB1);
580
Sam Clegg4791a662018-11-20 19:25:07 +0000581 // longjmp_result = getTempRet0();
Heejin Ahnc0f18172016-09-01 21:05:15 +0000582 IRB.SetInsertPoint(EndBB1);
583 PHINode *LabelPHI = IRB.CreatePHI(IRB.getInt32Ty(), 2, "label");
584 LabelPHI->addIncoming(ThenLabel, EndBB2);
585
586 LabelPHI->addIncoming(IRB.getInt32(-1), ElseBB1);
587
588 // Output parameter assignment
589 Label = LabelPHI;
590 EndBB = EndBB1;
Sam Clegg4791a662018-11-20 19:25:07 +0000591 LongjmpResult = IRB.CreateCall(GetTempRet0Func, None, "longjmp_result");
Heejin Ahnc0f18172016-09-01 21:05:15 +0000592}
593
Heejin Ahnc0f18172016-09-01 21:05:15 +0000594void WebAssemblyLowerEmscriptenEHSjLj::rebuildSSA(Function &F) {
595 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
596 DT.recalculate(F); // CFG has been changed
597 SSAUpdater SSA;
598 for (BasicBlock &BB : F) {
599 for (Instruction &I : BB) {
600 for (auto UI = I.use_begin(), UE = I.use_end(); UI != UE;) {
601 Use &U = *UI;
602 ++UI;
603 SSA.Initialize(I.getType(), I.getName());
604 SSA.AddAvailableValue(&BB, &I);
Heejin Ahn18c56a02019-02-04 19:13:39 +0000605 auto *User = cast<Instruction>(U.getUser());
Heejin Ahnc0f18172016-09-01 21:05:15 +0000606 if (User->getParent() == &BB)
607 continue;
608
Heejin Ahn18c56a02019-02-04 19:13:39 +0000609 if (auto *UserPN = dyn_cast<PHINode>(User))
Heejin Ahnc0f18172016-09-01 21:05:15 +0000610 if (UserPN->getIncomingBlock(U) == &BB)
611 continue;
612
613 if (DT.dominates(&I, User))
614 continue;
615 SSA.RewriteUseAfterInsertions(U);
616 }
617 }
618 }
619}
620
621bool WebAssemblyLowerEmscriptenEHSjLj::runOnModule(Module &M) {
Heejin Ahn569f0902019-01-09 23:05:21 +0000622 LLVM_DEBUG(dbgs() << "********** Lower Emscripten EH & SjLj **********\n");
623
Heejin Ahnc0f18172016-09-01 21:05:15 +0000624 LLVMContext &C = M.getContext();
625 IRBuilder<> IRB(C);
626
627 Function *SetjmpF = M.getFunction("setjmp");
628 Function *LongjmpF = M.getFunction("longjmp");
629 bool SetjmpUsed = SetjmpF && !SetjmpF->use_empty();
630 bool LongjmpUsed = LongjmpF && !LongjmpF->use_empty();
631 bool DoSjLj = EnableSjLj && (SetjmpUsed || LongjmpUsed);
632
Sam Clegg4791a662018-11-20 19:25:07 +0000633 // Declare (or get) global variables __THREW__, __threwValue, and
634 // getTempRet0/setTempRet0 function which are used in common for both
635 // exception handling and setjmp/longjmp handling
Sam Cleggb2486f12018-10-02 22:12:15 +0000636 ThrewGV = getGlobalVariableI32(M, IRB, "__THREW__");
637 ThrewValueGV = getGlobalVariableI32(M, IRB, "__threwValue");
Sam Clegg4791a662018-11-20 19:25:07 +0000638 GetTempRet0Func =
639 Function::Create(FunctionType::get(IRB.getInt32Ty(), false),
640 GlobalValue::ExternalLinkage, "getTempRet0", &M);
641 SetTempRet0Func = Function::Create(
642 FunctionType::get(IRB.getVoidTy(), IRB.getInt32Ty(), false),
643 GlobalValue::ExternalLinkage, "setTempRet0", &M);
644 GetTempRet0Func->setDoesNotThrow();
645 SetTempRet0Func->setDoesNotThrow();
Heejin Ahnc0f18172016-09-01 21:05:15 +0000646
647 bool Changed = false;
648
649 // Exception handling
650 if (EnableEH) {
651 // Register __resumeException function
652 FunctionType *ResumeFTy =
653 FunctionType::get(IRB.getVoidTy(), IRB.getInt8PtrTy(), false);
654 ResumeF = Function::Create(ResumeFTy, GlobalValue::ExternalLinkage,
655 ResumeFName, &M);
656
657 // Register llvm_eh_typeid_for function
658 FunctionType *EHTypeIDTy =
659 FunctionType::get(IRB.getInt32Ty(), IRB.getInt8PtrTy(), false);
660 EHTypeIDF = Function::Create(EHTypeIDTy, GlobalValue::ExternalLinkage,
661 EHTypeIDFName, &M);
662
663 for (Function &F : M) {
664 if (F.isDeclaration())
665 continue;
666 Changed |= runEHOnFunction(F);
667 }
668 }
669
670 // Setjmp/longjmp handling
671 if (DoSjLj) {
672 Changed = true; // We have setjmp or longjmp somewhere
673
Heejin Ahnc0f18172016-09-01 21:05:15 +0000674 if (LongjmpF) {
675 // Replace all uses of longjmp with emscripten_longjmp_jmpbuf, which is
676 // defined in JS code
677 EmLongjmpJmpbufF = Function::Create(LongjmpF->getFunctionType(),
678 GlobalValue::ExternalLinkage,
679 EmLongjmpJmpbufFName, &M);
680
681 LongjmpF->replaceAllUsesWith(EmLongjmpJmpbufF);
682 }
Heejin Ahnc0f18172016-09-01 21:05:15 +0000683
Heejin Ahn0c68a872018-11-08 22:56:26 +0000684 if (SetjmpF) {
685 // Register saveSetjmp function
686 FunctionType *SetjmpFTy = SetjmpF->getFunctionType();
687 SmallVector<Type *, 4> Params = {SetjmpFTy->getParamType(0),
688 IRB.getInt32Ty(), Type::getInt32PtrTy(C),
689 IRB.getInt32Ty()};
690 FunctionType *FTy =
691 FunctionType::get(Type::getInt32PtrTy(C), Params, false);
692 SaveSetjmpF = Function::Create(FTy, GlobalValue::ExternalLinkage,
693 SaveSetjmpFName, &M);
694
695 // Register testSetjmp function
696 Params = {IRB.getInt32Ty(), Type::getInt32PtrTy(C), IRB.getInt32Ty()};
697 FTy = FunctionType::get(IRB.getInt32Ty(), Params, false);
698 TestSetjmpF = Function::Create(FTy, GlobalValue::ExternalLinkage,
699 TestSetjmpFName, &M);
700
701 FTy = FunctionType::get(IRB.getVoidTy(),
702 {IRB.getInt32Ty(), IRB.getInt32Ty()}, false);
703 EmLongjmpF = Function::Create(FTy, GlobalValue::ExternalLinkage,
704 EmLongjmpFName, &M);
705
706 // Only traverse functions that uses setjmp in order not to insert
707 // unnecessary prep / cleanup code in every function
708 SmallPtrSet<Function *, 8> SetjmpUsers;
709 for (User *U : SetjmpF->users()) {
710 auto *UI = cast<Instruction>(U);
711 SetjmpUsers.insert(UI->getFunction());
712 }
713 for (Function *F : SetjmpUsers)
714 runSjLjOnFunction(*F);
Heejin Ahnc0f18172016-09-01 21:05:15 +0000715 }
Heejin Ahnc0f18172016-09-01 21:05:15 +0000716 }
717
718 if (!Changed) {
719 // Delete unused global variables and functions
Heejin Ahnc0f18172016-09-01 21:05:15 +0000720 if (ResumeF)
721 ResumeF->eraseFromParent();
722 if (EHTypeIDF)
723 EHTypeIDF->eraseFromParent();
724 if (EmLongjmpF)
725 EmLongjmpF->eraseFromParent();
726 if (SaveSetjmpF)
727 SaveSetjmpF->eraseFromParent();
728 if (TestSetjmpF)
729 TestSetjmpF->eraseFromParent();
730 return false;
731 }
732
Derek Schufff41f67d2016-08-01 21:34:04 +0000733 return true;
734}
735
Derek Schuffccdceda2016-08-18 15:27:25 +0000736bool WebAssemblyLowerEmscriptenEHSjLj::runEHOnFunction(Function &F) {
Derek Schufff41f67d2016-08-01 21:34:04 +0000737 Module &M = *F.getParent();
Derek Schuff53b9af02016-08-09 00:29:55 +0000738 LLVMContext &C = F.getContext();
Derek Schuffccdceda2016-08-18 15:27:25 +0000739 IRBuilder<> IRB(C);
Derek Schufff41f67d2016-08-01 21:34:04 +0000740 bool Changed = false;
741 SmallVector<Instruction *, 64> ToErase;
742 SmallPtrSet<LandingPadInst *, 32> LandingPads;
Derek Schuff66641322016-08-09 22:37:00 +0000743 bool AllowExceptions =
Derek Schuffccdceda2016-08-18 15:27:25 +0000744 areAllExceptionsAllowed() || EHWhitelistSet.count(F.getName());
Derek Schufff41f67d2016-08-01 21:34:04 +0000745
746 for (BasicBlock &BB : F) {
747 auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
748 if (!II)
749 continue;
750 Changed = true;
751 LandingPads.insert(II->getLandingPadInst());
Derek Schuffccdceda2016-08-18 15:27:25 +0000752 IRB.SetInsertPoint(II);
Derek Schufff41f67d2016-08-01 21:34:04 +0000753
Derek Schuff53b9af02016-08-09 00:29:55 +0000754 bool NeedInvoke = AllowExceptions && canThrow(II->getCalledValue());
755 if (NeedInvoke) {
Heejin Ahnc0f18172016-09-01 21:05:15 +0000756 // Wrap invoke with invoke wrapper and generate preamble/postamble
757 Value *Threw = wrapInvoke(II);
Derek Schufff41f67d2016-08-01 21:34:04 +0000758 ToErase.push_back(II);
759
Derek Schufff41f67d2016-08-01 21:34:04 +0000760 // Insert a branch based on __THREW__ variable
Heejin Ahnc0f18172016-09-01 21:05:15 +0000761 Value *Cmp = IRB.CreateICmpEQ(Threw, IRB.getInt32(1), "cmp");
762 IRB.CreateCondBr(Cmp, II->getUnwindDest(), II->getNormalDest());
Derek Schufff41f67d2016-08-01 21:34:04 +0000763
764 } else {
765 // This can't throw, and we don't need this invoke, just replace it with a
766 // call+branch
Heejin Ahnc0f18172016-09-01 21:05:15 +0000767 SmallVector<Value *, 16> Args(II->arg_begin(), II->arg_end());
James Y Knight7976eb52019-02-01 20:43:25 +0000768 CallInst *NewCall =
769 IRB.CreateCall(II->getFunctionType(), II->getCalledValue(), Args);
Derek Schufff41f67d2016-08-01 21:34:04 +0000770 NewCall->takeName(II);
771 NewCall->setCallingConv(II->getCallingConv());
Derek Schufff41f67d2016-08-01 21:34:04 +0000772 NewCall->setDebugLoc(II->getDebugLoc());
Derek Schuff53b9af02016-08-09 00:29:55 +0000773 NewCall->setAttributes(II->getAttributes());
Derek Schufff41f67d2016-08-01 21:34:04 +0000774 II->replaceAllUsesWith(NewCall);
775 ToErase.push_back(II);
776
Derek Schuffccdceda2016-08-18 15:27:25 +0000777 IRB.CreateBr(II->getNormalDest());
Derek Schufff41f67d2016-08-01 21:34:04 +0000778
779 // Remove any PHI node entries from the exception destination
780 II->getUnwindDest()->removePredecessor(&BB);
781 }
782 }
783
784 // Process resume instructions
785 for (BasicBlock &BB : F) {
786 // Scan the body of the basic block for resumes
787 for (Instruction &I : BB) {
788 auto *RI = dyn_cast<ResumeInst>(&I);
789 if (!RI)
790 continue;
791
792 // Split the input into legal values
793 Value *Input = RI->getValue();
Derek Schuffccdceda2016-08-18 15:27:25 +0000794 IRB.SetInsertPoint(RI);
795 Value *Low = IRB.CreateExtractValue(Input, 0, "low");
Derek Schuff53b9af02016-08-09 00:29:55 +0000796 // Create a call to __resumeException function
Heejin Ahnc0f18172016-09-01 21:05:15 +0000797 IRB.CreateCall(ResumeF, {Low});
Derek Schufff41f67d2016-08-01 21:34:04 +0000798 // Add a terminator to the block
Derek Schuffccdceda2016-08-18 15:27:25 +0000799 IRB.CreateUnreachable();
Derek Schufff41f67d2016-08-01 21:34:04 +0000800 ToErase.push_back(RI);
801 }
802 }
803
Derek Schuff53b9af02016-08-09 00:29:55 +0000804 // Process llvm.eh.typeid.for intrinsics
805 for (BasicBlock &BB : F) {
806 for (Instruction &I : BB) {
807 auto *CI = dyn_cast<CallInst>(&I);
808 if (!CI)
809 continue;
810 const Function *Callee = CI->getCalledFunction();
811 if (!Callee)
812 continue;
813 if (Callee->getIntrinsicID() != Intrinsic::eh_typeid_for)
814 continue;
815
Derek Schuffccdceda2016-08-18 15:27:25 +0000816 IRB.SetInsertPoint(CI);
Derek Schuff53b9af02016-08-09 00:29:55 +0000817 CallInst *NewCI =
Derek Schuffccdceda2016-08-18 15:27:25 +0000818 IRB.CreateCall(EHTypeIDF, CI->getArgOperand(0), "typeid");
Derek Schuff53b9af02016-08-09 00:29:55 +0000819 CI->replaceAllUsesWith(NewCI);
820 ToErase.push_back(CI);
821 }
822 }
823
Hiroshi Inouec3969642017-06-30 07:17:53 +0000824 // Look for orphan landingpads, can occur in blocks with no predecessors
Derek Schufff41f67d2016-08-01 21:34:04 +0000825 for (BasicBlock &BB : F) {
826 Instruction *I = BB.getFirstNonPHI();
827 if (auto *LPI = dyn_cast<LandingPadInst>(I))
828 LandingPads.insert(LPI);
829 }
830
831 // Handle all the landingpad for this function together, as multiple invokes
832 // may share a single lp
833 for (LandingPadInst *LPI : LandingPads) {
Derek Schuffccdceda2016-08-18 15:27:25 +0000834 IRB.SetInsertPoint(LPI);
Derek Schufff41f67d2016-08-01 21:34:04 +0000835 SmallVector<Value *, 16> FMCArgs;
Heejin Ahn18c56a02019-02-04 19:13:39 +0000836 for (unsigned I = 0, E = LPI->getNumClauses(); I < E; ++I) {
837 Constant *Clause = LPI->getClause(I);
Derek Schufff41f67d2016-08-01 21:34:04 +0000838 // As a temporary workaround for the lack of aggregate varargs support
839 // in the interface between JS and wasm, break out filter operands into
840 // their component elements.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000841 if (LPI->isFilter(I)) {
Heejin Ahnc0f18172016-09-01 21:05:15 +0000842 auto *ATy = cast<ArrayType>(Clause->getType());
Heejin Ahn18c56a02019-02-04 19:13:39 +0000843 for (unsigned J = 0, E = ATy->getNumElements(); J < E; ++J) {
844 Value *EV = IRB.CreateExtractValue(Clause, makeArrayRef(J), "filter");
Derek Schufff41f67d2016-08-01 21:34:04 +0000845 FMCArgs.push_back(EV);
846 }
847 } else
848 FMCArgs.push_back(Clause);
849 }
850
Derek Schuff53b9af02016-08-09 00:29:55 +0000851 // Create a call to __cxa_find_matching_catch_N function
Derek Schufff41f67d2016-08-01 21:34:04 +0000852 Function *FMCF = getFindMatchingCatch(M, FMCArgs.size());
Derek Schuffccdceda2016-08-18 15:27:25 +0000853 CallInst *FMCI = IRB.CreateCall(FMCF, FMCArgs, "fmc");
Derek Schufff41f67d2016-08-01 21:34:04 +0000854 Value *Undef = UndefValue::get(LPI->getType());
Derek Schuffccdceda2016-08-18 15:27:25 +0000855 Value *Pair0 = IRB.CreateInsertValue(Undef, FMCI, 0, "pair0");
Sam Clegg4791a662018-11-20 19:25:07 +0000856 Value *TempRet0 = IRB.CreateCall(GetTempRet0Func, None, "tempret0");
Derek Schuffccdceda2016-08-18 15:27:25 +0000857 Value *Pair1 = IRB.CreateInsertValue(Pair0, TempRet0, 1, "pair1");
Derek Schufff41f67d2016-08-01 21:34:04 +0000858
859 LPI->replaceAllUsesWith(Pair1);
860 ToErase.push_back(LPI);
861 }
862
863 // Erase everything we no longer need in this function
864 for (Instruction *I : ToErase)
865 I->eraseFromParent();
866
867 return Changed;
868}
Derek Schuffccdceda2016-08-18 15:27:25 +0000869
870bool WebAssemblyLowerEmscriptenEHSjLj::runSjLjOnFunction(Function &F) {
Heejin Ahnc0f18172016-09-01 21:05:15 +0000871 Module &M = *F.getParent();
872 LLVMContext &C = F.getContext();
873 IRBuilder<> IRB(C);
874 SmallVector<Instruction *, 64> ToErase;
875 // Vector of %setjmpTable values
876 std::vector<Instruction *> SetjmpTableInsts;
877 // Vector of %setjmpTableSize values
878 std::vector<Instruction *> SetjmpTableSizeInsts;
879
880 // Setjmp preparation
881
882 // This instruction effectively means %setjmpTableSize = 4.
883 // We create this as an instruction intentionally, and we don't want to fold
884 // this instruction to a constant 4, because this value will be used in
885 // SSAUpdater.AddAvailableValue(...) later.
886 BasicBlock &EntryBB = F.getEntryBlock();
887 BinaryOperator *SetjmpTableSize = BinaryOperator::Create(
888 Instruction::Add, IRB.getInt32(4), IRB.getInt32(0), "setjmpTableSize",
889 &*EntryBB.getFirstInsertionPt());
890 // setjmpTable = (int *) malloc(40);
891 Instruction *SetjmpTable = CallInst::CreateMalloc(
892 SetjmpTableSize, IRB.getInt32Ty(), IRB.getInt32Ty(), IRB.getInt32(40),
893 nullptr, nullptr, "setjmpTable");
894 // setjmpTable[0] = 0;
895 IRB.SetInsertPoint(SetjmpTableSize);
896 IRB.CreateStore(IRB.getInt32(0), SetjmpTable);
897 SetjmpTableInsts.push_back(SetjmpTable);
898 SetjmpTableSizeInsts.push_back(SetjmpTableSize);
899
900 // Setjmp transformation
901 std::vector<PHINode *> SetjmpRetPHIs;
902 Function *SetjmpF = M.getFunction("setjmp");
903 for (User *U : SetjmpF->users()) {
904 auto *CI = dyn_cast<CallInst>(U);
905 if (!CI)
906 report_fatal_error("Does not support indirect calls to setjmp");
907
908 BasicBlock *BB = CI->getParent();
909 if (BB->getParent() != &F) // in other function
910 continue;
911
912 // The tail is everything right after the call, and will be reached once
913 // when setjmp is called, and later when longjmp returns to the setjmp
914 BasicBlock *Tail = SplitBlock(BB, CI->getNextNode());
915 // Add a phi to the tail, which will be the output of setjmp, which
916 // indicates if this is the first call or a longjmp back. The phi directly
917 // uses the right value based on where we arrive from
918 IRB.SetInsertPoint(Tail->getFirstNonPHI());
919 PHINode *SetjmpRet = IRB.CreatePHI(IRB.getInt32Ty(), 2, "setjmp.ret");
920
921 // setjmp initial call returns 0
922 SetjmpRet->addIncoming(IRB.getInt32(0), BB);
923 // The proper output is now this, not the setjmp call itself
924 CI->replaceAllUsesWith(SetjmpRet);
925 // longjmp returns to the setjmp will add themselves to this phi
926 SetjmpRetPHIs.push_back(SetjmpRet);
927
928 // Fix call target
929 // Our index in the function is our place in the array + 1 to avoid index
930 // 0, because index 0 means the longjmp is not ours to handle.
931 IRB.SetInsertPoint(CI);
932 Value *Args[] = {CI->getArgOperand(0), IRB.getInt32(SetjmpRetPHIs.size()),
933 SetjmpTable, SetjmpTableSize};
934 Instruction *NewSetjmpTable =
935 IRB.CreateCall(SaveSetjmpF, Args, "setjmpTable");
936 Instruction *NewSetjmpTableSize =
Sam Clegg4791a662018-11-20 19:25:07 +0000937 IRB.CreateCall(GetTempRet0Func, None, "setjmpTableSize");
Heejin Ahnc0f18172016-09-01 21:05:15 +0000938 SetjmpTableInsts.push_back(NewSetjmpTable);
939 SetjmpTableSizeInsts.push_back(NewSetjmpTableSize);
940 ToErase.push_back(CI);
941 }
942
943 // Update each call that can longjmp so it can return to a setjmp where
944 // relevant.
945
946 // Because we are creating new BBs while processing and don't want to make
947 // all these newly created BBs candidates again for longjmp processing, we
948 // first make the vector of candidate BBs.
949 std::vector<BasicBlock *> BBs;
950 for (BasicBlock &BB : F)
951 BBs.push_back(&BB);
952
953 // BBs.size() will change within the loop, so we query it every time
Heejin Ahn18c56a02019-02-04 19:13:39 +0000954 for (unsigned I = 0; I < BBs.size(); I++) {
955 BasicBlock *BB = BBs[I];
Heejin Ahnc0f18172016-09-01 21:05:15 +0000956 for (Instruction &I : *BB) {
957 assert(!isa<InvokeInst>(&I));
958 auto *CI = dyn_cast<CallInst>(&I);
959 if (!CI)
960 continue;
961
962 const Value *Callee = CI->getCalledValue();
963 if (!canLongjmp(M, Callee))
964 continue;
965
966 Value *Threw = nullptr;
967 BasicBlock *Tail;
968 if (Callee->getName().startswith(InvokePrefix)) {
969 // If invoke wrapper has already been generated for this call in
970 // previous EH phase, search for the load instruction
971 // %__THREW__.val = __THREW__;
972 // in postamble after the invoke wrapper call
973 LoadInst *ThrewLI = nullptr;
974 StoreInst *ThrewResetSI = nullptr;
975 for (auto I = std::next(BasicBlock::iterator(CI)), IE = BB->end();
976 I != IE; ++I) {
977 if (auto *LI = dyn_cast<LoadInst>(I))
978 if (auto *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand()))
979 if (GV == ThrewGV) {
980 Threw = ThrewLI = LI;
981 break;
982 }
983 }
984 // Search for the store instruction after the load above
985 // __THREW__ = 0;
986 for (auto I = std::next(BasicBlock::iterator(ThrewLI)), IE = BB->end();
987 I != IE; ++I) {
988 if (auto *SI = dyn_cast<StoreInst>(I))
989 if (auto *GV = dyn_cast<GlobalVariable>(SI->getPointerOperand()))
990 if (GV == ThrewGV && SI->getValueOperand() == IRB.getInt32(0)) {
991 ThrewResetSI = SI;
992 break;
993 }
994 }
995 assert(Threw && ThrewLI && "Cannot find __THREW__ load after invoke");
996 assert(ThrewResetSI && "Cannot find __THREW__ store after invoke");
997 Tail = SplitBlock(BB, ThrewResetSI->getNextNode());
998
999 } else {
1000 // Wrap call with invoke wrapper and generate preamble/postamble
1001 Threw = wrapInvoke(CI);
1002 ToErase.push_back(CI);
1003 Tail = SplitBlock(BB, CI->getNextNode());
1004 }
1005
1006 // We need to replace the terminator in Tail - SplitBlock makes BB go
1007 // straight to Tail, we need to check if a longjmp occurred, and go to the
1008 // right setjmp-tail if so
1009 ToErase.push_back(BB->getTerminator());
1010
1011 // Generate a function call to testSetjmp function and preamble/postamble
1012 // code to figure out (1) whether longjmp occurred (2) if longjmp
1013 // occurred, which setjmp it corresponds to
1014 Value *Label = nullptr;
1015 Value *LongjmpResult = nullptr;
1016 BasicBlock *EndBB = nullptr;
1017 wrapTestSetjmp(BB, CI, Threw, SetjmpTable, SetjmpTableSize, Label,
1018 LongjmpResult, EndBB);
1019 assert(Label && LongjmpResult && EndBB);
1020
1021 // Create switch instruction
1022 IRB.SetInsertPoint(EndBB);
1023 SwitchInst *SI = IRB.CreateSwitch(Label, Tail, SetjmpRetPHIs.size());
1024 // -1 means no longjmp happened, continue normally (will hit the default
1025 // switch case). 0 means a longjmp that is not ours to handle, needs a
1026 // rethrow. Otherwise the index is the same as the index in P+1 (to avoid
1027 // 0).
Heejin Ahn18c56a02019-02-04 19:13:39 +00001028 for (unsigned I = 0; I < SetjmpRetPHIs.size(); I++) {
1029 SI->addCase(IRB.getInt32(I + 1), SetjmpRetPHIs[I]->getParent());
1030 SetjmpRetPHIs[I]->addIncoming(LongjmpResult, EndBB);
Heejin Ahnc0f18172016-09-01 21:05:15 +00001031 }
1032
1033 // We are splitting the block here, and must continue to find other calls
1034 // in the block - which is now split. so continue to traverse in the Tail
1035 BBs.push_back(Tail);
1036 }
1037 }
1038
1039 // Erase everything we no longer need in this function
1040 for (Instruction *I : ToErase)
1041 I->eraseFromParent();
1042
1043 // Free setjmpTable buffer before each return instruction
1044 for (BasicBlock &BB : F) {
Chandler Carruthedb12a82018-10-15 10:04:59 +00001045 Instruction *TI = BB.getTerminator();
Heejin Ahnc0f18172016-09-01 21:05:15 +00001046 if (isa<ReturnInst>(TI))
1047 CallInst::CreateFree(SetjmpTable, TI);
1048 }
1049
1050 // Every call to saveSetjmp can change setjmpTable and setjmpTableSize
1051 // (when buffer reallocation occurs)
1052 // entry:
1053 // setjmpTableSize = 4;
1054 // setjmpTable = (int *) malloc(40);
1055 // setjmpTable[0] = 0;
1056 // ...
1057 // somebb:
1058 // setjmpTable = saveSetjmp(buf, label, setjmpTable, setjmpTableSize);
Sam Clegg4791a662018-11-20 19:25:07 +00001059 // setjmpTableSize = getTempRet0();
Heejin Ahnc0f18172016-09-01 21:05:15 +00001060 // So we need to make sure the SSA for these variables is valid so that every
1061 // saveSetjmp and testSetjmp calls have the correct arguments.
1062 SSAUpdater SetjmpTableSSA;
1063 SSAUpdater SetjmpTableSizeSSA;
1064 SetjmpTableSSA.Initialize(Type::getInt32PtrTy(C), "setjmpTable");
1065 SetjmpTableSizeSSA.Initialize(Type::getInt32Ty(C), "setjmpTableSize");
1066 for (Instruction *I : SetjmpTableInsts)
1067 SetjmpTableSSA.AddAvailableValue(I->getParent(), I);
1068 for (Instruction *I : SetjmpTableSizeInsts)
1069 SetjmpTableSizeSSA.AddAvailableValue(I->getParent(), I);
1070
1071 for (auto UI = SetjmpTable->use_begin(), UE = SetjmpTable->use_end();
1072 UI != UE;) {
1073 // Grab the use before incrementing the iterator.
1074 Use &U = *UI;
1075 // Increment the iterator before removing the use from the list.
1076 ++UI;
Heejin Ahn18c56a02019-02-04 19:13:39 +00001077 if (auto *I = dyn_cast<Instruction>(U.getUser()))
Heejin Ahnc0f18172016-09-01 21:05:15 +00001078 if (I->getParent() != &EntryBB)
1079 SetjmpTableSSA.RewriteUse(U);
1080 }
1081 for (auto UI = SetjmpTableSize->use_begin(), UE = SetjmpTableSize->use_end();
1082 UI != UE;) {
1083 Use &U = *UI;
1084 ++UI;
Heejin Ahn18c56a02019-02-04 19:13:39 +00001085 if (auto *I = dyn_cast<Instruction>(U.getUser()))
Heejin Ahnc0f18172016-09-01 21:05:15 +00001086 if (I->getParent() != &EntryBB)
1087 SetjmpTableSizeSSA.RewriteUse(U);
1088 }
1089
1090 // Finally, our modifications to the cfg can break dominance of SSA variables.
1091 // For example, in this code,
1092 // if (x()) { .. setjmp() .. }
1093 // if (y()) { .. longjmp() .. }
1094 // We must split the longjmp block, and it can jump into the block splitted
1095 // from setjmp one. But that means that when we split the setjmp block, it's
1096 // first part no longer dominates its second part - there is a theoretically
1097 // possible control flow path where x() is false, then y() is true and we
1098 // reach the second part of the setjmp block, without ever reaching the first
1099 // part. So, we rebuild SSA form here.
1100 rebuildSSA(F);
1101 return true;
Derek Schuffccdceda2016-08-18 15:27:25 +00001102}