blob: 7197f28e1fe2362d02deb1ea78ac4bd615c8a457 [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//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
Heejin Ahn23d57102016-08-31 22:40:34 +000011/// \brief This file lowers exception-related instructions and setjmp/longjmp
12/// function calls in order to use Emscripten's JavaScript try and catch
13/// mechanism.
Derek Schufff41f67d2016-08-01 21:34:04 +000014///
Heejin Ahn23d57102016-08-31 22:40:34 +000015/// To handle exceptions and setjmp/longjmps, this scheme relies on JavaScript's
16/// try and catch syntax and relevant exception-related libraries implemented
17/// in JavaScript glue code that will be produced by Emscripten. This is similar
18/// to the current Emscripten asm.js exception handling in fastcomp. For
19/// fastcomp's EH / SjLj scheme, see these files in fastcomp LLVM branch:
Derek Schufff41f67d2016-08-01 21:34:04 +000020/// (Location: https://github.com/kripken/emscripten-fastcomp)
21/// lib/Target/JSBackend/NaCl/LowerEmExceptionsPass.cpp
Heejin Ahn23d57102016-08-31 22:40:34 +000022/// lib/Target/JSBackend/NaCl/LowerEmSetjmp.cpp
Derek Schufff41f67d2016-08-01 21:34:04 +000023/// lib/Target/JSBackend/JSBackend.cpp
24/// lib/Target/JSBackend/CallHandlers.h
25///
Heejin Ahn23d57102016-08-31 22:40:34 +000026/// * Exception handling
27/// This pass lowers invokes and landingpads into library functions in JS glue
28/// code. Invokes are lowered into function wrappers called invoke wrappers that
29/// exist in JS side, which wraps the original function call with JS try-catch.
30/// If an exception occurred, cxa_throw() function in JS side sets some
31/// variables (see below) so we can check whether an exception occurred from
32/// wasm code and handle it appropriately.
Derek Schufff41f67d2016-08-01 21:34:04 +000033///
Heejin Ahn23d57102016-08-31 22:40:34 +000034/// * Setjmp-longjmp handling
35/// This pass lowers setjmp to a reasonably-performant approach for emscripten.
36/// The idea is that each block with a setjmp is broken up into two parts: the
37/// part containing setjmp and the part right after the setjmp. The latter part
38/// is either reached from the setjmp, or later from a longjmp. To handle the
39/// longjmp, all calls that might longjmp are also called using invoke wrappers
40/// and thus JS / try-catch. JS longjmp() function also sets some variables so
41/// we can check / whether a longjmp occurred from wasm code. Each block with a
42/// function call that might longjmp is also split up after the longjmp call.
43/// After the longjmp call, we check whether a longjmp occurred, and if it did,
44/// which setjmp it corresponds to, and jump to the right post-setjmp block.
45/// We assume setjmp-longjmp handling always run after EH handling, which means
46/// we don't expect any exception-related instructions when SjLj runs.
47/// FIXME Currently this scheme does not support indirect call of setjmp,
48/// because of the limitation of the scheme itself. fastcomp does not support it
49/// either.
50///
51/// In detail, this pass does following things:
52///
53/// 1) Create three global variables: __THREW__, __threwValue, and __tempRet0.
54/// __tempRet0 will be set within __cxa_find_matching_catch() function in
Derek Schuffccdceda2016-08-18 15:27:25 +000055/// JS library, and __THREW__ and __threwValue will be set in invoke wrappers
Heejin Ahn23d57102016-08-31 22:40:34 +000056/// in JS glue code. For what invoke wrappers are, refer to 3). These
57/// variables are used for both exceptions and setjmp/longjmps.
58/// __THREW__ indicates whether an exception or a longjmp occurred or not. 0
59/// means nothing occurred, 1 means an exception occurred, and other numbers
60/// mean a longjmp occurred. In the case of longjmp, threwValue variable
61/// indicates the corresponding setjmp buffer the longjmp corresponds to.
62/// In exception handling, __tempRet0 indicates the type of an exception
63/// caught, and in setjmp/longjmp, it means the second argument to longjmp
64/// function.
65///
66/// * Exception handling
Derek Schufff41f67d2016-08-01 21:34:04 +000067///
68/// 2) Create setThrew and setTempRet0 functions.
69/// The global variables created in 1) will exist in wasm address space,
70/// but their values should be set in JS code, so we provide these functions
71/// as interfaces to JS glue code. These functions are equivalent to the
72/// following JS functions, which actually exist in asm.js version of JS
73/// library.
74///
75/// function setThrew(threw, value) {
76/// if (__THREW__ == 0) {
77/// __THREW__ = threw;
Derek Schuffccdceda2016-08-18 15:27:25 +000078/// __threwValue = value;
Derek Schufff41f67d2016-08-01 21:34:04 +000079/// }
80/// }
81///
82/// function setTempRet0(value) {
Heejin Ahn23d57102016-08-31 22:40:34 +000083/// __tempRet0 = value;
Derek Schufff41f67d2016-08-01 21:34:04 +000084/// }
85///
86/// 3) Lower
87/// invoke @func(arg1, arg2) to label %invoke.cont unwind label %lpad
88/// into
89/// __THREW__ = 0;
90/// call @invoke_SIG(func, arg1, arg2)
91/// %__THREW__.val = __THREW__;
92/// __THREW__ = 0;
93/// br %__THREW__.val, label %lpad, label %invoke.cont
94/// SIG is a mangled string generated based on the LLVM IR-level function
95/// signature. After LLVM IR types are lowered to the target wasm types,
96/// the names for these wrappers will change based on wasm types as well,
97/// as in invoke_vi (function takes an int and returns void). The bodies of
98/// these wrappers will be generated in JS glue code, and inside those
99/// wrappers we use JS try-catch to generate actual exception effects. It
100/// also calls the original callee function. An example wrapper in JS code
101/// would look like this:
102/// function invoke_vi(index,a1) {
103/// try {
104/// Module["dynCall_vi"](index,a1); // This calls original callee
105/// } catch(e) {
106/// if (typeof e !== 'number' && e !== 'longjmp') throw e;
107/// asm["setThrew"](1, 0); // setThrew is called here
108/// }
109/// }
110/// If an exception is thrown, __THREW__ will be set to true in a wrapper,
111/// so we can jump to the right BB based on this value.
112///
113/// 4) Lower
114/// %val = landingpad catch c1 catch c2 catch c3 ...
115/// ... use %val ...
116/// into
Derek Schuff53b9af02016-08-09 00:29:55 +0000117/// %fmc = call @__cxa_find_matching_catch_N(c1, c2, c3, ...)
Heejin Ahn23d57102016-08-31 22:40:34 +0000118/// %val = {%fmc, __tempRet0}
Derek Schufff41f67d2016-08-01 21:34:04 +0000119/// ... use %val ...
120/// Here N is a number calculated based on the number of clauses.
Heejin Ahn23d57102016-08-31 22:40:34 +0000121/// Global variable __tempRet0 is set within __cxa_find_matching_catch() in
Derek Schufff41f67d2016-08-01 21:34:04 +0000122/// JS glue code.
123///
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 Ahn23d57102016-08-31 22:40:34 +0000136/// * Setjmp / Longjmp handling
137///
138/// 7) In the function entry that calls setjmp, initialize setjmpTable and
139/// sejmpTableSize as follows:
140/// setjmpTableSize = 4;
141/// setjmpTable = (int *) malloc(40);
142/// setjmpTable[0] = 0;
143/// setjmpTable and setjmpTableSize are used in saveSetjmp() function in JS
144/// code.
145///
146/// 8) Lower
147/// setjmp(buf)
148/// into
149/// setjmpTable = saveSetjmp(buf, label, setjmpTable, setjmpTableSize);
150/// setjmpTableSize = __tempRet0;
151/// For each dynamic setjmp call, setjmpTable stores its ID (a number which
152/// is incrementally assigned from 0) and its label (a unique number that
153/// represents each callsite of setjmp). When we need more entries in
154/// setjmpTable, it is reallocated in saveSetjmp() in JS code and it will
155/// return the new table address, and assign the new table size in
156/// __tempRet0. saveSetjmp also stores the setjmp's ID into the buffer buf.
157/// A BB with setjmp is split into two after setjmp call in order to make the
158/// post-setjmp BB the possible destination of longjmp BB.
159///
160/// 9) Lower
161/// longjmp(buf, value)
162/// into
163/// emscripten_longjmp_jmpbuf(buf, value)
164/// emscripten_longjmp_jmpbuf will be lowered to emscripten_longjmp later.
165///
166/// 10) Lower every call that might longjmp into
167/// __THREW__ = 0;
168/// call @invoke_SIG(func, arg1, arg2)
169/// %__THREW__.val = __THREW__;
170/// __THREW__ = 0;
171/// if (%__THREW__.val != 0 & threwValue != 0) {
172/// %label = testSetjmp(mem[%__THREW__.val], setjmpTable,
173/// setjmpTableSize);
174/// if (%label == 0)
175/// emscripten_longjmp(%__THREW__.val, threwValue);
176/// __tempRet0 = threwValue;
177/// } else {
178/// %label = -1;
179/// }
180/// longjmp_result = __tempRet0;
181/// switch label {
182/// label 1: post-setjmp BB 1
183/// label 2: post-setjmp BB 2
184/// ...
185/// default: splited next BB
186/// }
187/// testSetjmp examines setjmpTable to see if there is a matching setjmp
188/// call. After calling an invoke wrapper, if a longjmp occurred, __THREW__
189/// will be the address of matching jmp_buf buffer and threwValue be the
190/// second argument to longjmp. mem[__THREW__.val] is a setjmp ID that is
191/// stored in saveSetjmp. testSetjmp returns a setjmp label, a unique ID to
192/// each setjmp callsite. Label 0 means this longjmp buffer does not
193/// correspond to one of the setjmp callsites in this function, so in this
194/// case we just chain the longjmp to the caller. (Here we call
195/// emscripten_longjmp, which is different from emscripten_longjmp_jmpbuf.
196/// emscripten_longjmp_jmpbuf takes jmp_buf as its first argument, while
197/// emscripten_longjmp takes an int. Both of them will eventually be lowered
198/// to emscripten_longjmp in s2wasm, but here we need two signatures - we
199/// can't translate an int value to a jmp_buf.)
200/// Label -1 means no longjmp occurred. Otherwise we jump to the right
201/// post-setjmp BB based on the label.
202///
Derek Schufff41f67d2016-08-01 21:34:04 +0000203///===----------------------------------------------------------------------===//
204
205#include "WebAssembly.h"
Derek Schuff53b9af02016-08-09 00:29:55 +0000206#include "llvm/IR/CallSite.h"
Heejin Ahn23d57102016-08-31 22:40:34 +0000207#include "llvm/IR/Dominators.h"
Derek Schufff41f67d2016-08-01 21:34:04 +0000208#include "llvm/IR/IRBuilder.h"
Heejin Ahn23d57102016-08-31 22:40:34 +0000209#include "llvm/Transforms/Utils/BasicBlockUtils.h"
210#include "llvm/Transforms/Utils/SSAUpdater.h"
Derek Schufff41f67d2016-08-01 21:34:04 +0000211
212using namespace llvm;
213
Derek Schuffccdceda2016-08-18 15:27:25 +0000214#define DEBUG_TYPE "wasm-lower-em-ehsjlj"
Derek Schufff41f67d2016-08-01 21:34:04 +0000215
Derek Schuff66641322016-08-09 22:37:00 +0000216static cl::list<std::string>
Derek Schuffccdceda2016-08-18 15:27:25 +0000217 EHWhitelist("emscripten-cxx-exceptions-whitelist",
218 cl::desc("The list of function names in which Emscripten-style "
219 "exception handling is enabled (see emscripten "
220 "EMSCRIPTEN_CATCHING_WHITELIST options)"),
221 cl::CommaSeparated);
Derek Schuff66641322016-08-09 22:37:00 +0000222
Derek Schufff41f67d2016-08-01 21:34:04 +0000223namespace {
Derek Schuffccdceda2016-08-18 15:27:25 +0000224class WebAssemblyLowerEmscriptenEHSjLj final : public ModulePass {
225 static const char *ThrewGVName;
226 static const char *ThrewValueGVName;
227 static const char *TempRet0GVName;
228 static const char *ResumeFName;
229 static const char *EHTypeIDFName;
230 static const char *SetThrewFName;
231 static const char *SetTempRet0FName;
Heejin Ahn23d57102016-08-31 22:40:34 +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 Ahn23d57102016-08-31 22:40:34 +0000239 bool EnableEH; // Enable exception handling
240 bool EnableSjLj; // Enable setjmp/longjmp handling
Derek Schuffccdceda2016-08-18 15:27:25 +0000241
242 GlobalVariable *ThrewGV;
243 GlobalVariable *ThrewValueGV;
244 GlobalVariable *TempRet0GV;
245 Function *ResumeF;
246 Function *EHTypeIDF;
Heejin Ahn23d57102016-08-31 22:40:34 +0000247 Function *EmLongjmpF;
248 Function *EmLongjmpJmpbufF;
249 Function *SaveSetjmpF;
250 Function *TestSetjmpF;
251
Derek Schuffccdceda2016-08-18 15:27:25 +0000252 // __cxa_find_matching_catch_N functions.
253 // Indexed by the number of clauses in an original landingpad instruction.
254 DenseMap<int, Function *> FindMatchingCatches;
255 // Map of <function signature string, invoke_ wrappers>
256 StringMap<Function *> InvokeWrappers;
257 // Set of whitelisted function names for exception handling
258 std::set<std::string> EHWhitelistSet;
259
Derek Schufff41f67d2016-08-01 21:34:04 +0000260 const char *getPassName() const override {
261 return "WebAssembly Lower Emscripten Exceptions";
262 }
263
Derek Schuffccdceda2016-08-18 15:27:25 +0000264 bool runEHOnFunction(Function &F);
265 bool runSjLjOnFunction(Function &F);
Derek Schufff41f67d2016-08-01 21:34:04 +0000266 Function *getFindMatchingCatch(Module &M, unsigned NumClauses);
267
Heejin Ahn23d57102016-08-31 22:40:34 +0000268 template <typename CallOrInvoke> Value *wrapInvoke(CallOrInvoke *CI);
269 void wrapTestSetjmp(BasicBlock *BB, Instruction *InsertPt, Value *Threw,
270 Value *SetjmpTable, Value *SetjmpTableSize, Value *&Label,
271 Value *&LongjmpResult, BasicBlock *&EndBB);
272 template <typename CallOrInvoke> Function *getInvokeWrapper(CallOrInvoke *CI);
273
Derek Schuffccdceda2016-08-18 15:27:25 +0000274 bool areAllExceptionsAllowed() const { return EHWhitelistSet.empty(); }
Heejin Ahn23d57102016-08-31 22:40:34 +0000275 bool canLongjmp(Module &M, const Value *Callee) const;
276
277 void createSetThrewFunction(Module &M);
278 void createSetTempRet0Function(Module &M);
279
280 void rebuildSSA(Function &F);
Derek Schufff41f67d2016-08-01 21:34:04 +0000281
282public:
283 static char ID;
284
Heejin Ahn23d57102016-08-31 22:40:34 +0000285 WebAssemblyLowerEmscriptenEHSjLj(bool EnableEH = true, bool EnableSjLj = true)
286 : ModulePass(ID), EnableEH(EnableEH), EnableSjLj(EnableSjLj),
287 ThrewGV(nullptr), ThrewValueGV(nullptr), TempRet0GV(nullptr),
288 ResumeF(nullptr), EHTypeIDF(nullptr), EmLongjmpF(nullptr),
289 EmLongjmpJmpbufF(nullptr), SaveSetjmpF(nullptr), TestSetjmpF(nullptr) {
Derek Schuffccdceda2016-08-18 15:27:25 +0000290 EHWhitelistSet.insert(EHWhitelist.begin(), EHWhitelist.end());
Derek Schuff66641322016-08-09 22:37:00 +0000291 }
Derek Schufff41f67d2016-08-01 21:34:04 +0000292 bool runOnModule(Module &M) override;
Heejin Ahn23d57102016-08-31 22:40:34 +0000293
294 void getAnalysisUsage(AnalysisUsage &AU) const override {
295 AU.addRequired<DominatorTreeWrapperPass>();
296 }
Derek Schufff41f67d2016-08-01 21:34:04 +0000297};
298} // End anonymous namespace
299
Derek Schuffccdceda2016-08-18 15:27:25 +0000300const char *WebAssemblyLowerEmscriptenEHSjLj::ThrewGVName = "__THREW__";
301const char *WebAssemblyLowerEmscriptenEHSjLj::ThrewValueGVName = "__threwValue";
302const char *WebAssemblyLowerEmscriptenEHSjLj::TempRet0GVName = "__tempRet0";
303const char *WebAssemblyLowerEmscriptenEHSjLj::ResumeFName = "__resumeException";
304const char *WebAssemblyLowerEmscriptenEHSjLj::EHTypeIDFName =
305 "llvm_eh_typeid_for";
306const char *WebAssemblyLowerEmscriptenEHSjLj::SetThrewFName = "setThrew";
307const char *WebAssemblyLowerEmscriptenEHSjLj::SetTempRet0FName = "setTempRet0";
Heejin Ahn23d57102016-08-31 22:40:34 +0000308const char *WebAssemblyLowerEmscriptenEHSjLj::EmLongjmpFName =
309 "emscripten_longjmp";
310const char *WebAssemblyLowerEmscriptenEHSjLj::EmLongjmpJmpbufFName =
311 "emscripten_longjmp_jmpbuf";
312const char *WebAssemblyLowerEmscriptenEHSjLj::SaveSetjmpFName = "saveSetjmp";
313const char *WebAssemblyLowerEmscriptenEHSjLj::TestSetjmpFName = "testSetjmp";
Derek Schuffccdceda2016-08-18 15:27:25 +0000314const char *WebAssemblyLowerEmscriptenEHSjLj::FindMatchingCatchPrefix =
315 "__cxa_find_matching_catch_";
316const char *WebAssemblyLowerEmscriptenEHSjLj::InvokePrefix = "__invoke_";
Derek Schufff41f67d2016-08-01 21:34:04 +0000317
Derek Schuffccdceda2016-08-18 15:27:25 +0000318char WebAssemblyLowerEmscriptenEHSjLj::ID = 0;
319INITIALIZE_PASS(WebAssemblyLowerEmscriptenEHSjLj, DEBUG_TYPE,
320 "WebAssembly Lower Emscripten Exceptions / Setjmp / Longjmp",
321 false, false)
322
Heejin Ahn23d57102016-08-31 22:40:34 +0000323ModulePass *llvm::createWebAssemblyLowerEmscriptenEHSjLj(bool EnableEH,
324 bool EnableSjLj) {
325 return new WebAssemblyLowerEmscriptenEHSjLj(EnableEH, EnableSjLj);
Derek Schufff41f67d2016-08-01 21:34:04 +0000326}
327
328static bool canThrow(const Value *V) {
329 if (const auto *F = dyn_cast<const Function>(V)) {
330 // Intrinsics cannot throw
331 if (F->isIntrinsic())
332 return false;
333 StringRef Name = F->getName();
334 // leave setjmp and longjmp (mostly) alone, we process them properly later
335 if (Name == "setjmp" || Name == "longjmp")
336 return false;
Heejin Ahn23d57102016-08-31 22:40:34 +0000337 return !F->doesNotThrow();
Derek Schufff41f67d2016-08-01 21:34:04 +0000338 }
Heejin Ahnb6cd5122016-08-24 22:53:00 +0000339 // not a function, so an indirect call - can throw, we can't tell
340 return true;
Derek Schufff41f67d2016-08-01 21:34:04 +0000341}
342
343// Returns an available name for a global value.
344// If the proposed name already exists in the module, adds '_' at the end of
345// the name until the name is available.
346static inline std::string createGlobalValueName(const Module &M,
347 const std::string &Propose) {
348 std::string Name = Propose;
349 while (M.getNamedGlobal(Name))
350 Name += "_";
351 return Name;
352}
353
354// Simple function name mangler.
355// This function simply takes LLVM's string representation of parameter types
Derek Schuff53b9af02016-08-09 00:29:55 +0000356// and concatenate them with '_'. There are non-alphanumeric characters but llc
357// is ok with it, and we need to postprocess these names after the lowering
358// phase anyway.
Derek Schufff41f67d2016-08-01 21:34:04 +0000359static std::string getSignature(FunctionType *FTy) {
360 std::string Sig;
361 raw_string_ostream OS(Sig);
362 OS << *FTy->getReturnType();
363 for (Type *ParamTy : FTy->params())
364 OS << "_" << *ParamTy;
365 if (FTy->isVarArg())
366 OS << "_...";
367 Sig = OS.str();
David Majnemerc7004902016-08-12 04:32:37 +0000368 Sig.erase(remove_if(Sig, isspace), Sig.end());
Derek Schuff53b9af02016-08-09 00:29:55 +0000369 // When s2wasm parses .s file, a comma means the end of an argument. So a
370 // mangled function name can contain any character but a comma.
371 std::replace(Sig.begin(), Sig.end(), ',', '.');
Derek Schufff41f67d2016-08-01 21:34:04 +0000372 return Sig;
373}
374
Heejin Ahn23d57102016-08-31 22:40:34 +0000375// Returns __cxa_find_matching_catch_N function, where N = NumClauses + 2.
376// This is because a landingpad instruction contains two more arguments, a
377// personality function and a cleanup bit, and __cxa_find_matching_catch_N
378// functions are named after the number of arguments in the original landingpad
379// instruction.
Derek Schuffccdceda2016-08-18 15:27:25 +0000380Function *
381WebAssemblyLowerEmscriptenEHSjLj::getFindMatchingCatch(Module &M,
382 unsigned NumClauses) {
Derek Schufff41f67d2016-08-01 21:34:04 +0000383 if (FindMatchingCatches.count(NumClauses))
384 return FindMatchingCatches[NumClauses];
385 PointerType *Int8PtrTy = Type::getInt8PtrTy(M.getContext());
386 SmallVector<Type *, 16> Args(NumClauses, Int8PtrTy);
387 FunctionType *FTy = FunctionType::get(Int8PtrTy, Args, false);
Derek Schuffccdceda2016-08-18 15:27:25 +0000388 Function *F =
389 Function::Create(FTy, GlobalValue::ExternalLinkage,
390 FindMatchingCatchPrefix + Twine(NumClauses + 2), &M);
Derek Schufff41f67d2016-08-01 21:34:04 +0000391 FindMatchingCatches[NumClauses] = F;
392 return F;
393}
394
Heejin Ahn23d57102016-08-31 22:40:34 +0000395// Generate invoke wrapper seqence with preamble and postamble
396// Preamble:
397// __THREW__ = 0;
398// Postamble:
399// %__THREW__.val = __THREW__; __THREW__ = 0;
400// Returns %__THREW__.val, which indicates whether an exception is thrown (or
401// whether longjmp occurred), for future use.
402template <typename CallOrInvoke>
403Value *WebAssemblyLowerEmscriptenEHSjLj::wrapInvoke(CallOrInvoke *CI) {
404 LLVMContext &C = CI->getModule()->getContext();
405
406 // If we are calling a function that is noreturn, we must remove that
407 // attribute. The code we insert here does expect it to return, after we
408 // catch the exception.
409 if (CI->doesNotReturn()) {
410 if (auto *F = dyn_cast<Function>(CI->getCalledValue()))
411 F->removeFnAttr(Attribute::NoReturn);
412 CI->removeAttribute(AttributeSet::FunctionIndex, Attribute::NoReturn);
413 }
414
415 IRBuilder<> IRB(C);
416 IRB.SetInsertPoint(CI);
417
418 // Pre-invoke
419 // __THREW__ = 0;
420 IRB.CreateStore(IRB.getInt32(0), ThrewGV);
421
422 // Invoke function wrapper in JavaScript
423 SmallVector<Value *, 16> Args;
424 // Put the pointer to the callee as first argument, so it can be called
425 // within the invoke wrapper later
426 Args.push_back(CI->getCalledValue());
427 Args.append(CI->arg_begin(), CI->arg_end());
428 CallInst *NewCall = IRB.CreateCall(getInvokeWrapper(CI), Args);
429 NewCall->takeName(CI);
430 NewCall->setCallingConv(CI->getCallingConv());
431 NewCall->setDebugLoc(CI->getDebugLoc());
432
433 // Because we added the pointer to the callee as first argument, all
434 // argument attribute indices have to be incremented by one.
435 SmallVector<AttributeSet, 8> AttributesVec;
436 const AttributeSet &InvokePAL = CI->getAttributes();
437 CallSite::arg_iterator AI = CI->arg_begin();
438 unsigned i = 1; // Argument attribute index starts from 1
439 for (unsigned e = CI->getNumArgOperands(); i <= e; ++AI, ++i) {
440 if (InvokePAL.hasAttributes(i)) {
441 AttrBuilder B(InvokePAL, i);
442 AttributesVec.push_back(AttributeSet::get(C, i + 1, B));
443 }
444 }
445 // Add any return attributes.
446 if (InvokePAL.hasAttributes(AttributeSet::ReturnIndex))
447 AttributesVec.push_back(AttributeSet::get(C, InvokePAL.getRetAttributes()));
448 // Add any function attributes.
449 if (InvokePAL.hasAttributes(AttributeSet::FunctionIndex))
450 AttributesVec.push_back(AttributeSet::get(C, InvokePAL.getFnAttributes()));
451 // Reconstruct the AttributesList based on the vector we constructed.
452 AttributeSet NewCallPAL = AttributeSet::get(C, AttributesVec);
453 NewCall->setAttributes(NewCallPAL);
454
455 CI->replaceAllUsesWith(NewCall);
456
457 // Post-invoke
458 // %__THREW__.val = __THREW__; __THREW__ = 0;
459 Value *Threw = IRB.CreateLoad(ThrewGV, ThrewGV->getName() + ".val");
460 IRB.CreateStore(IRB.getInt32(0), ThrewGV);
461 return Threw;
462}
463
464// Get matching invoke wrapper based on callee signature
465template <typename CallOrInvoke>
466Function *WebAssemblyLowerEmscriptenEHSjLj::getInvokeWrapper(CallOrInvoke *CI) {
467 Module *M = CI->getModule();
Derek Schufff41f67d2016-08-01 21:34:04 +0000468 SmallVector<Type *, 16> ArgTys;
Heejin Ahn23d57102016-08-31 22:40:34 +0000469 Value *Callee = CI->getCalledValue();
Derek Schufff41f67d2016-08-01 21:34:04 +0000470 FunctionType *CalleeFTy;
471 if (auto *F = dyn_cast<Function>(Callee))
472 CalleeFTy = F->getFunctionType();
473 else {
Heejin Ahn23d57102016-08-31 22:40:34 +0000474 auto *CalleeTy = cast<PointerType>(Callee->getType())->getElementType();
Derek Schufff41f67d2016-08-01 21:34:04 +0000475 CalleeFTy = dyn_cast<FunctionType>(CalleeTy);
476 }
477
478 std::string Sig = getSignature(CalleeFTy);
479 if (InvokeWrappers.find(Sig) != InvokeWrappers.end())
480 return InvokeWrappers[Sig];
481
482 // Put the pointer to the callee as first argument
483 ArgTys.push_back(PointerType::getUnqual(CalleeFTy));
484 // Add argument types
485 ArgTys.append(CalleeFTy->param_begin(), CalleeFTy->param_end());
486
487 FunctionType *FTy = FunctionType::get(CalleeFTy->getReturnType(), ArgTys,
488 CalleeFTy->isVarArg());
489 Function *F = Function::Create(FTy, GlobalValue::ExternalLinkage,
Heejin Ahn23d57102016-08-31 22:40:34 +0000490 InvokePrefix + Sig, M);
Derek Schufff41f67d2016-08-01 21:34:04 +0000491 InvokeWrappers[Sig] = F;
492 return F;
493}
494
Heejin Ahn23d57102016-08-31 22:40:34 +0000495bool WebAssemblyLowerEmscriptenEHSjLj::canLongjmp(Module &M,
496 const Value *Callee) const {
497 if (auto *CalleeF = dyn_cast<Function>(Callee))
498 if (CalleeF->isIntrinsic())
499 return false;
Derek Schufff41f67d2016-08-01 21:34:04 +0000500
Heejin Ahn23d57102016-08-31 22:40:34 +0000501 // The reason we include malloc/free here is to exclude the malloc/free
502 // calls generated in setjmp prep / cleanup routines.
503 Function *SetjmpF = M.getFunction("setjmp");
504 Function *MallocF = M.getFunction("malloc");
505 Function *FreeF = M.getFunction("free");
506 if (Callee == SetjmpF || Callee == MallocF || Callee == FreeF)
Derek Schufff41f67d2016-08-01 21:34:04 +0000507 return false;
508
Heejin Ahn23d57102016-08-31 22:40:34 +0000509 // There are functions in JS glue code
510 if (Callee == ResumeF || Callee == EHTypeIDF || Callee == SaveSetjmpF ||
511 Callee == TestSetjmpF)
512 return false;
Derek Schufff41f67d2016-08-01 21:34:04 +0000513
Heejin Ahn23d57102016-08-31 22:40:34 +0000514 // __cxa_find_matching_catch_N functions cannot longjmp
515 if (Callee->getName().startswith(FindMatchingCatchPrefix))
516 return false;
517
518 // Exception-catching related functions
519 Function *BeginCatchF = M.getFunction("__cxa_begin_catch");
520 Function *EndCatchF = M.getFunction("__cxa_end_catch");
521 Function *AllocExceptionF = M.getFunction("__cxa_allocate_exception");
522 Function *ThrowF = M.getFunction("__cxa_throw");
523 Function *TerminateF = M.getFunction("__clang_call_terminate");
524 if (Callee == BeginCatchF || Callee == EndCatchF ||
525 Callee == AllocExceptionF || Callee == ThrowF || Callee == TerminateF)
526 return false;
527
528 // Otherwise we don't know
529 return true;
530}
531
532// Generate testSetjmp function call seqence with preamble and postamble.
533// The code this generates is equivalent to the following JavaScript code:
534// if (%__THREW__.val != 0 & threwValue != 0) {
535// %label = _testSetjmp(mem[%__THREW__.val], setjmpTable, setjmpTableSize);
536// if (%label == 0)
537// emscripten_longjmp(%__THREW__.val, threwValue);
538// __tempRet0 = threwValue;
539// } else {
540// %label = -1;
541// }
542// %longjmp_result = __tempRet0;
543//
544// As output parameters. returns %label, %longjmp_result, and the BB the last
545// instruction (%longjmp_result = ...) is in.
546void WebAssemblyLowerEmscriptenEHSjLj::wrapTestSetjmp(
547 BasicBlock *BB, Instruction *InsertPt, Value *Threw, Value *SetjmpTable,
548 Value *SetjmpTableSize, Value *&Label, Value *&LongjmpResult,
549 BasicBlock *&EndBB) {
550 Function *F = BB->getParent();
551 LLVMContext &C = BB->getModule()->getContext();
552 IRBuilder<> IRB(C);
553 IRB.SetInsertPoint(InsertPt);
554
555 // if (%__THREW__.val != 0 & threwValue != 0)
556 IRB.SetInsertPoint(BB);
557 BasicBlock *ThenBB1 = BasicBlock::Create(C, "if.then1", F);
558 BasicBlock *ElseBB1 = BasicBlock::Create(C, "if.else1", F);
559 BasicBlock *EndBB1 = BasicBlock::Create(C, "if.end", F);
560 Value *ThrewCmp = IRB.CreateICmpNE(Threw, IRB.getInt32(0));
561 Value *ThrewValue =
562 IRB.CreateLoad(ThrewValueGV, ThrewValueGV->getName() + ".val");
563 Value *ThrewValueCmp = IRB.CreateICmpNE(ThrewValue, IRB.getInt32(0));
564 Value *Cmp1 = IRB.CreateAnd(ThrewCmp, ThrewValueCmp, "cmp1");
565 IRB.CreateCondBr(Cmp1, ThenBB1, ElseBB1);
566
567 // %label = _testSetjmp(mem[%__THREW__.val], _setjmpTable, _setjmpTableSize);
568 // if (%label == 0)
569 IRB.SetInsertPoint(ThenBB1);
570 BasicBlock *ThenBB2 = BasicBlock::Create(C, "if.then2", F);
571 BasicBlock *EndBB2 = BasicBlock::Create(C, "if.end2", F);
572 Value *ThrewInt = IRB.CreateIntToPtr(Threw, Type::getInt32PtrTy(C),
573 Threw->getName() + ".i32p");
574 Value *LoadedThrew =
575 IRB.CreateLoad(ThrewInt, ThrewInt->getName() + ".loaded");
576 Value *ThenLabel = IRB.CreateCall(
577 TestSetjmpF, {LoadedThrew, SetjmpTable, SetjmpTableSize}, "label");
578 Value *Cmp2 = IRB.CreateICmpEQ(ThenLabel, IRB.getInt32(0));
579 IRB.CreateCondBr(Cmp2, ThenBB2, EndBB2);
580
581 // emscripten_longjmp(%__THREW__.val, threwValue);
582 IRB.SetInsertPoint(ThenBB2);
583 IRB.CreateCall(EmLongjmpF, {Threw, ThrewValue});
584 IRB.CreateUnreachable();
585
586 // __tempRet0 = threwValue;
587 IRB.SetInsertPoint(EndBB2);
588 IRB.CreateStore(ThrewValue, TempRet0GV);
589 IRB.CreateBr(EndBB1);
590
591 IRB.SetInsertPoint(ElseBB1);
592 IRB.CreateBr(EndBB1);
593
594 // longjmp_result = __tempRet0;
595 IRB.SetInsertPoint(EndBB1);
596 PHINode *LabelPHI = IRB.CreatePHI(IRB.getInt32Ty(), 2, "label");
597 LabelPHI->addIncoming(ThenLabel, EndBB2);
598
599 LabelPHI->addIncoming(IRB.getInt32(-1), ElseBB1);
600
601 // Output parameter assignment
602 Label = LabelPHI;
603 EndBB = EndBB1;
604 LongjmpResult = IRB.CreateLoad(TempRet0GV, "longjmp_result");
605}
606
607// Create setThrew function
608// function setThrew(threw, value) {
609// if (__THREW__ == 0) {
610// __THREW__ = threw;
611// __threwValue = value;
612// }
613// }
614void WebAssemblyLowerEmscriptenEHSjLj::createSetThrewFunction(Module &M) {
615 LLVMContext &C = M.getContext();
616 IRBuilder<> IRB(C);
617
618 assert(!M.getNamedGlobal(SetThrewFName) && "setThrew already exists");
619 Type *Params[] = {IRB.getInt32Ty(), IRB.getInt32Ty()};
620 FunctionType *FTy = FunctionType::get(IRB.getVoidTy(), Params, false);
Derek Schufff41f67d2016-08-01 21:34:04 +0000621 Function *F =
Derek Schuffccdceda2016-08-18 15:27:25 +0000622 Function::Create(FTy, GlobalValue::ExternalLinkage, SetThrewFName, &M);
Derek Schufff41f67d2016-08-01 21:34:04 +0000623 Argument *Arg1 = &*(F->arg_begin());
624 Argument *Arg2 = &*(++F->arg_begin());
625 Arg1->setName("threw");
626 Arg2->setName("value");
Derek Schuff53b9af02016-08-09 00:29:55 +0000627 BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F);
628 BasicBlock *ThenBB = BasicBlock::Create(C, "if.then", F);
629 BasicBlock *EndBB = BasicBlock::Create(C, "if.end", F);
Derek Schufff41f67d2016-08-01 21:34:04 +0000630
Derek Schuffccdceda2016-08-18 15:27:25 +0000631 IRB.SetInsertPoint(EntryBB);
632 Value *Threw = IRB.CreateLoad(ThrewGV, ThrewGV->getName() + ".val");
Heejin Ahn23d57102016-08-31 22:40:34 +0000633 Value *Cmp = IRB.CreateICmpEQ(Threw, IRB.getInt32(0), "cmp");
Derek Schuffccdceda2016-08-18 15:27:25 +0000634 IRB.CreateCondBr(Cmp, ThenBB, EndBB);
Derek Schufff41f67d2016-08-01 21:34:04 +0000635
Derek Schuffccdceda2016-08-18 15:27:25 +0000636 IRB.SetInsertPoint(ThenBB);
637 IRB.CreateStore(Arg1, ThrewGV);
638 IRB.CreateStore(Arg2, ThrewValueGV);
639 IRB.CreateBr(EndBB);
Derek Schufff41f67d2016-08-01 21:34:04 +0000640
Derek Schuffccdceda2016-08-18 15:27:25 +0000641 IRB.SetInsertPoint(EndBB);
642 IRB.CreateRetVoid();
Heejin Ahn23d57102016-08-31 22:40:34 +0000643}
Derek Schufff41f67d2016-08-01 21:34:04 +0000644
Heejin Ahn23d57102016-08-31 22:40:34 +0000645// Create setTempRet0 function
646// function setTempRet0(value) {
647// __tempRet0 = value;
648// }
649void WebAssemblyLowerEmscriptenEHSjLj::createSetTempRet0Function(Module &M) {
650 LLVMContext &C = M.getContext();
651 IRBuilder<> IRB(C);
652
653 assert(!M.getNamedGlobal(SetTempRet0FName) && "setTempRet0 already exists");
654 Type *Params[] = {IRB.getInt32Ty()};
655 FunctionType *FTy = FunctionType::get(IRB.getVoidTy(), Params, false);
656 Function *F =
657 Function::Create(FTy, GlobalValue::ExternalLinkage, SetTempRet0FName, &M);
Derek Schufff41f67d2016-08-01 21:34:04 +0000658 F->arg_begin()->setName("value");
Heejin Ahn23d57102016-08-31 22:40:34 +0000659 BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F);
Derek Schuffccdceda2016-08-18 15:27:25 +0000660 IRB.SetInsertPoint(EntryBB);
661 IRB.CreateStore(&*F->arg_begin(), TempRet0GV);
662 IRB.CreateRetVoid();
Heejin Ahn23d57102016-08-31 22:40:34 +0000663}
664
665void WebAssemblyLowerEmscriptenEHSjLj::rebuildSSA(Function &F) {
666 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
667 DT.recalculate(F); // CFG has been changed
668 SSAUpdater SSA;
669 for (BasicBlock &BB : F) {
670 for (Instruction &I : BB) {
671 for (auto UI = I.use_begin(), UE = I.use_end(); UI != UE;) {
672 Use &U = *UI;
673 ++UI;
674 SSA.Initialize(I.getType(), I.getName());
675 SSA.AddAvailableValue(&BB, &I);
676 Instruction *User = cast<Instruction>(U.getUser());
677 if (User->getParent() == &BB)
678 continue;
679
680 if (PHINode *UserPN = dyn_cast<PHINode>(User))
681 if (UserPN->getIncomingBlock(U) == &BB)
682 continue;
683
684 if (DT.dominates(&I, User))
685 continue;
686 SSA.RewriteUseAfterInsertions(U);
687 }
688 }
689 }
690}
691
692bool WebAssemblyLowerEmscriptenEHSjLj::runOnModule(Module &M) {
693 LLVMContext &C = M.getContext();
694 IRBuilder<> IRB(C);
695
696 Function *SetjmpF = M.getFunction("setjmp");
697 Function *LongjmpF = M.getFunction("longjmp");
698 bool SetjmpUsed = SetjmpF && !SetjmpF->use_empty();
699 bool LongjmpUsed = LongjmpF && !LongjmpF->use_empty();
700 bool DoSjLj = EnableSjLj && (SetjmpUsed || LongjmpUsed);
701
702 // Create global variables __THREW__, threwValue, and __tempRet0, which are
703 // used in common for both exception handling and setjmp/longjmp handling
704 ThrewGV = new GlobalVariable(M, IRB.getInt32Ty(), false,
705 GlobalValue::ExternalLinkage, IRB.getInt32(0),
706 createGlobalValueName(M, ThrewGVName));
707 ThrewValueGV = new GlobalVariable(
708 M, IRB.getInt32Ty(), false, GlobalValue::ExternalLinkage, IRB.getInt32(0),
709 createGlobalValueName(M, ThrewValueGVName));
710 TempRet0GV = new GlobalVariable(M, IRB.getInt32Ty(), false,
711 GlobalValue::ExternalLinkage, IRB.getInt32(0),
712 createGlobalValueName(M, TempRet0GVName));
713
714 bool Changed = false;
715
716 // Exception handling
717 if (EnableEH) {
718 // Register __resumeException function
719 FunctionType *ResumeFTy =
720 FunctionType::get(IRB.getVoidTy(), IRB.getInt8PtrTy(), false);
721 ResumeF = Function::Create(ResumeFTy, GlobalValue::ExternalLinkage,
722 ResumeFName, &M);
723
724 // Register llvm_eh_typeid_for function
725 FunctionType *EHTypeIDTy =
726 FunctionType::get(IRB.getInt32Ty(), IRB.getInt8PtrTy(), false);
727 EHTypeIDF = Function::Create(EHTypeIDTy, GlobalValue::ExternalLinkage,
728 EHTypeIDFName, &M);
729
730 for (Function &F : M) {
731 if (F.isDeclaration())
732 continue;
733 Changed |= runEHOnFunction(F);
734 }
735 }
736
737 // Setjmp/longjmp handling
738 if (DoSjLj) {
739 Changed = true; // We have setjmp or longjmp somewhere
740
741 Function *MallocF = M.getFunction("malloc");
742 Function *FreeF = M.getFunction("free");
743 if (!MallocF || !FreeF)
744 report_fatal_error(
745 "malloc and free must be linked into the module if setjmp is used");
746
747 // Register saveSetjmp function
748 FunctionType *SetjmpFTy = SetjmpF->getFunctionType();
749 SmallVector<Type *, 4> Params = {SetjmpFTy->getParamType(0),
750 IRB.getInt32Ty(), Type::getInt32PtrTy(C),
751 IRB.getInt32Ty()};
752 FunctionType *FTy =
753 FunctionType::get(Type::getInt32PtrTy(C), Params, false);
754 SaveSetjmpF = Function::Create(FTy, GlobalValue::ExternalLinkage,
755 SaveSetjmpFName, &M);
756
757 // Register testSetjmp function
758 Params = {IRB.getInt32Ty(), Type::getInt32PtrTy(C), IRB.getInt32Ty()};
759 FTy = FunctionType::get(IRB.getInt32Ty(), Params, false);
760 TestSetjmpF = Function::Create(FTy, GlobalValue::ExternalLinkage,
761 TestSetjmpFName, &M);
762
763 if (LongjmpF) {
764 // Replace all uses of longjmp with emscripten_longjmp_jmpbuf, which is
765 // defined in JS code
766 EmLongjmpJmpbufF = Function::Create(LongjmpF->getFunctionType(),
767 GlobalValue::ExternalLinkage,
768 EmLongjmpJmpbufFName, &M);
769
770 LongjmpF->replaceAllUsesWith(EmLongjmpJmpbufF);
771 }
772 FTy = FunctionType::get(IRB.getVoidTy(),
773 {IRB.getInt32Ty(), IRB.getInt32Ty()}, false);
774 EmLongjmpF =
775 Function::Create(FTy, GlobalValue::ExternalLinkage, EmLongjmpFName, &M);
776
777 // Only traverse functions that uses setjmp in order not to insert
778 // unnecessary prep / cleanup code in every function
779 SmallPtrSet<Function *, 8> SetjmpUsers;
780 for (User *U : SetjmpF->users()) {
781 auto *UI = cast<Instruction>(U);
782 SetjmpUsers.insert(UI->getFunction());
783 }
784 for (Function *F : SetjmpUsers)
785 runSjLjOnFunction(*F);
786 }
787
788 if (!Changed) {
789 // Delete unused global variables and functions
790 ThrewGV->eraseFromParent();
791 ThrewValueGV->eraseFromParent();
792 TempRet0GV->eraseFromParent();
793 if (ResumeF)
794 ResumeF->eraseFromParent();
795 if (EHTypeIDF)
796 EHTypeIDF->eraseFromParent();
797 if (EmLongjmpF)
798 EmLongjmpF->eraseFromParent();
799 if (SaveSetjmpF)
800 SaveSetjmpF->eraseFromParent();
801 if (TestSetjmpF)
802 TestSetjmpF->eraseFromParent();
803 return false;
804 }
805
806 // If we have made any changes while doing exception handling or
807 // setjmp/longjmp handling, we have to create these functions for JavaScript
808 // to call.
809 createSetThrewFunction(M);
810 createSetTempRet0Function(M);
Derek Schufff41f67d2016-08-01 21:34:04 +0000811
812 return true;
813}
814
Derek Schuffccdceda2016-08-18 15:27:25 +0000815bool WebAssemblyLowerEmscriptenEHSjLj::runEHOnFunction(Function &F) {
Derek Schufff41f67d2016-08-01 21:34:04 +0000816 Module &M = *F.getParent();
Derek Schuff53b9af02016-08-09 00:29:55 +0000817 LLVMContext &C = F.getContext();
Derek Schuffccdceda2016-08-18 15:27:25 +0000818 IRBuilder<> IRB(C);
Derek Schufff41f67d2016-08-01 21:34:04 +0000819 bool Changed = false;
820 SmallVector<Instruction *, 64> ToErase;
821 SmallPtrSet<LandingPadInst *, 32> LandingPads;
Derek Schuff66641322016-08-09 22:37:00 +0000822 bool AllowExceptions =
Derek Schuffccdceda2016-08-18 15:27:25 +0000823 areAllExceptionsAllowed() || EHWhitelistSet.count(F.getName());
Derek Schufff41f67d2016-08-01 21:34:04 +0000824
825 for (BasicBlock &BB : F) {
826 auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
827 if (!II)
828 continue;
829 Changed = true;
830 LandingPads.insert(II->getLandingPadInst());
Derek Schuffccdceda2016-08-18 15:27:25 +0000831 IRB.SetInsertPoint(II);
Derek Schufff41f67d2016-08-01 21:34:04 +0000832
Derek Schuff53b9af02016-08-09 00:29:55 +0000833 bool NeedInvoke = AllowExceptions && canThrow(II->getCalledValue());
834 if (NeedInvoke) {
Heejin Ahn23d57102016-08-31 22:40:34 +0000835 // Wrap invoke with invoke wrapper and generate preamble/postamble
836 Value *Threw = wrapInvoke(II);
Derek Schufff41f67d2016-08-01 21:34:04 +0000837 ToErase.push_back(II);
838
Derek Schufff41f67d2016-08-01 21:34:04 +0000839 // Insert a branch based on __THREW__ variable
Heejin Ahn23d57102016-08-31 22:40:34 +0000840 Value *Cmp = IRB.CreateICmpEQ(Threw, IRB.getInt32(1), "cmp");
841 IRB.CreateCondBr(Cmp, II->getUnwindDest(), II->getNormalDest());
Derek Schufff41f67d2016-08-01 21:34:04 +0000842
843 } else {
844 // This can't throw, and we don't need this invoke, just replace it with a
845 // call+branch
Heejin Ahn23d57102016-08-31 22:40:34 +0000846 SmallVector<Value *, 16> Args(II->arg_begin(), II->arg_end());
847 CallInst *NewCall = IRB.CreateCall(II->getCalledValue(), Args);
Derek Schufff41f67d2016-08-01 21:34:04 +0000848 NewCall->takeName(II);
849 NewCall->setCallingConv(II->getCallingConv());
Derek Schufff41f67d2016-08-01 21:34:04 +0000850 NewCall->setDebugLoc(II->getDebugLoc());
Derek Schuff53b9af02016-08-09 00:29:55 +0000851 NewCall->setAttributes(II->getAttributes());
Derek Schufff41f67d2016-08-01 21:34:04 +0000852 II->replaceAllUsesWith(NewCall);
853 ToErase.push_back(II);
854
Derek Schuffccdceda2016-08-18 15:27:25 +0000855 IRB.CreateBr(II->getNormalDest());
Derek Schufff41f67d2016-08-01 21:34:04 +0000856
857 // Remove any PHI node entries from the exception destination
858 II->getUnwindDest()->removePredecessor(&BB);
859 }
860 }
861
862 // Process resume instructions
863 for (BasicBlock &BB : F) {
864 // Scan the body of the basic block for resumes
865 for (Instruction &I : BB) {
866 auto *RI = dyn_cast<ResumeInst>(&I);
867 if (!RI)
868 continue;
869
870 // Split the input into legal values
871 Value *Input = RI->getValue();
Derek Schuffccdceda2016-08-18 15:27:25 +0000872 IRB.SetInsertPoint(RI);
873 Value *Low = IRB.CreateExtractValue(Input, 0, "low");
Derek Schuff53b9af02016-08-09 00:29:55 +0000874 // Create a call to __resumeException function
Heejin Ahn23d57102016-08-31 22:40:34 +0000875 IRB.CreateCall(ResumeF, {Low});
Derek Schufff41f67d2016-08-01 21:34:04 +0000876 // Add a terminator to the block
Derek Schuffccdceda2016-08-18 15:27:25 +0000877 IRB.CreateUnreachable();
Derek Schufff41f67d2016-08-01 21:34:04 +0000878 ToErase.push_back(RI);
879 }
880 }
881
Derek Schuff53b9af02016-08-09 00:29:55 +0000882 // Process llvm.eh.typeid.for intrinsics
883 for (BasicBlock &BB : F) {
884 for (Instruction &I : BB) {
885 auto *CI = dyn_cast<CallInst>(&I);
886 if (!CI)
887 continue;
888 const Function *Callee = CI->getCalledFunction();
889 if (!Callee)
890 continue;
891 if (Callee->getIntrinsicID() != Intrinsic::eh_typeid_for)
892 continue;
893
Derek Schuffccdceda2016-08-18 15:27:25 +0000894 IRB.SetInsertPoint(CI);
Derek Schuff53b9af02016-08-09 00:29:55 +0000895 CallInst *NewCI =
Derek Schuffccdceda2016-08-18 15:27:25 +0000896 IRB.CreateCall(EHTypeIDF, CI->getArgOperand(0), "typeid");
Derek Schuff53b9af02016-08-09 00:29:55 +0000897 CI->replaceAllUsesWith(NewCI);
898 ToErase.push_back(CI);
899 }
900 }
901
Derek Schufff41f67d2016-08-01 21:34:04 +0000902 // Look for orphan landingpads, can occur in blocks with no predecesors
903 for (BasicBlock &BB : F) {
904 Instruction *I = BB.getFirstNonPHI();
905 if (auto *LPI = dyn_cast<LandingPadInst>(I))
906 LandingPads.insert(LPI);
907 }
908
909 // Handle all the landingpad for this function together, as multiple invokes
910 // may share a single lp
911 for (LandingPadInst *LPI : LandingPads) {
Derek Schuffccdceda2016-08-18 15:27:25 +0000912 IRB.SetInsertPoint(LPI);
Derek Schufff41f67d2016-08-01 21:34:04 +0000913 SmallVector<Value *, 16> FMCArgs;
914 for (unsigned i = 0, e = LPI->getNumClauses(); i < e; ++i) {
915 Constant *Clause = LPI->getClause(i);
916 // As a temporary workaround for the lack of aggregate varargs support
917 // in the interface between JS and wasm, break out filter operands into
918 // their component elements.
919 if (LPI->isFilter(i)) {
Heejin Ahn23d57102016-08-31 22:40:34 +0000920 auto *ATy = cast<ArrayType>(Clause->getType());
Derek Schufff41f67d2016-08-01 21:34:04 +0000921 for (unsigned j = 0, e = ATy->getNumElements(); j < e; ++j) {
Derek Schuffccdceda2016-08-18 15:27:25 +0000922 Value *EV = IRB.CreateExtractValue(Clause, makeArrayRef(j), "filter");
Derek Schufff41f67d2016-08-01 21:34:04 +0000923 FMCArgs.push_back(EV);
924 }
925 } else
926 FMCArgs.push_back(Clause);
927 }
928
Derek Schuff53b9af02016-08-09 00:29:55 +0000929 // Create a call to __cxa_find_matching_catch_N function
Derek Schufff41f67d2016-08-01 21:34:04 +0000930 Function *FMCF = getFindMatchingCatch(M, FMCArgs.size());
Derek Schuffccdceda2016-08-18 15:27:25 +0000931 CallInst *FMCI = IRB.CreateCall(FMCF, FMCArgs, "fmc");
Derek Schufff41f67d2016-08-01 21:34:04 +0000932 Value *Undef = UndefValue::get(LPI->getType());
Derek Schuffccdceda2016-08-18 15:27:25 +0000933 Value *Pair0 = IRB.CreateInsertValue(Undef, FMCI, 0, "pair0");
Heejin Ahn23d57102016-08-31 22:40:34 +0000934 Value *TempRet0 =
935 IRB.CreateLoad(TempRet0GV, TempRet0GV->getName() + ".val");
Derek Schuffccdceda2016-08-18 15:27:25 +0000936 Value *Pair1 = IRB.CreateInsertValue(Pair0, TempRet0, 1, "pair1");
Derek Schufff41f67d2016-08-01 21:34:04 +0000937
938 LPI->replaceAllUsesWith(Pair1);
939 ToErase.push_back(LPI);
940 }
941
942 // Erase everything we no longer need in this function
943 for (Instruction *I : ToErase)
944 I->eraseFromParent();
945
946 return Changed;
947}
Derek Schuffccdceda2016-08-18 15:27:25 +0000948
949bool WebAssemblyLowerEmscriptenEHSjLj::runSjLjOnFunction(Function &F) {
Heejin Ahn23d57102016-08-31 22:40:34 +0000950 Module &M = *F.getParent();
951 LLVMContext &C = F.getContext();
952 IRBuilder<> IRB(C);
953 SmallVector<Instruction *, 64> ToErase;
954 // Vector of %setjmpTable values
955 std::vector<Instruction *> SetjmpTableInsts;
956 // Vector of %setjmpTableSize values
957 std::vector<Instruction *> SetjmpTableSizeInsts;
958
959 // Setjmp preparation
960
961 // This instruction effectively means %setjmpTableSize = 4.
962 // We create this as an instruction intentionally, and we don't want to fold
963 // this instruction to a constant 4, because this value will be used in
964 // SSAUpdater.AddAvailableValue(...) later.
965 BasicBlock &EntryBB = F.getEntryBlock();
966 BinaryOperator *SetjmpTableSize = BinaryOperator::Create(
967 Instruction::Add, IRB.getInt32(4), IRB.getInt32(0), "setjmpTableSize",
968 &*EntryBB.getFirstInsertionPt());
969 // setjmpTable = (int *) malloc(40);
970 Instruction *SetjmpTable = CallInst::CreateMalloc(
971 SetjmpTableSize, IRB.getInt32Ty(), IRB.getInt32Ty(), IRB.getInt32(40),
972 nullptr, nullptr, "setjmpTable");
973 // setjmpTable[0] = 0;
974 IRB.SetInsertPoint(SetjmpTableSize);
975 IRB.CreateStore(IRB.getInt32(0), SetjmpTable);
976 SetjmpTableInsts.push_back(SetjmpTable);
977 SetjmpTableSizeInsts.push_back(SetjmpTableSize);
978
979 // Setjmp transformation
980 std::vector<PHINode *> SetjmpRetPHIs;
981 Function *SetjmpF = M.getFunction("setjmp");
982 for (User *U : SetjmpF->users()) {
983 auto *CI = dyn_cast<CallInst>(U);
984 if (!CI)
985 report_fatal_error("Does not support indirect calls to setjmp");
986
987 BasicBlock *BB = CI->getParent();
988 if (BB->getParent() != &F) // in other function
989 continue;
990
991 // The tail is everything right after the call, and will be reached once
992 // when setjmp is called, and later when longjmp returns to the setjmp
993 BasicBlock *Tail = SplitBlock(BB, CI->getNextNode());
994 // Add a phi to the tail, which will be the output of setjmp, which
995 // indicates if this is the first call or a longjmp back. The phi directly
996 // uses the right value based on where we arrive from
997 IRB.SetInsertPoint(Tail->getFirstNonPHI());
998 PHINode *SetjmpRet = IRB.CreatePHI(IRB.getInt32Ty(), 2, "setjmp.ret");
999
1000 // setjmp initial call returns 0
1001 SetjmpRet->addIncoming(IRB.getInt32(0), BB);
1002 // The proper output is now this, not the setjmp call itself
1003 CI->replaceAllUsesWith(SetjmpRet);
1004 // longjmp returns to the setjmp will add themselves to this phi
1005 SetjmpRetPHIs.push_back(SetjmpRet);
1006
1007 // Fix call target
1008 // Our index in the function is our place in the array + 1 to avoid index
1009 // 0, because index 0 means the longjmp is not ours to handle.
1010 IRB.SetInsertPoint(CI);
1011 Value *Args[] = {CI->getArgOperand(0), IRB.getInt32(SetjmpRetPHIs.size()),
1012 SetjmpTable, SetjmpTableSize};
1013 Instruction *NewSetjmpTable =
1014 IRB.CreateCall(SaveSetjmpF, Args, "setjmpTable");
1015 Instruction *NewSetjmpTableSize =
1016 IRB.CreateLoad(TempRet0GV, "setjmpTableSize");
1017 SetjmpTableInsts.push_back(NewSetjmpTable);
1018 SetjmpTableSizeInsts.push_back(NewSetjmpTableSize);
1019 ToErase.push_back(CI);
1020 }
1021
1022 // Update each call that can longjmp so it can return to a setjmp where
1023 // relevant.
1024
1025 // Because we are creating new BBs while processing and don't want to make
1026 // all these newly created BBs candidates again for longjmp processing, we
1027 // first make the vector of candidate BBs.
1028 std::vector<BasicBlock *> BBs;
1029 for (BasicBlock &BB : F)
1030 BBs.push_back(&BB);
1031
1032 // BBs.size() will change within the loop, so we query it every time
1033 for (unsigned i = 0; i < BBs.size(); i++) {
1034 BasicBlock *BB = BBs[i];
1035 for (Instruction &I : *BB) {
1036 assert(!isa<InvokeInst>(&I));
1037 auto *CI = dyn_cast<CallInst>(&I);
1038 if (!CI)
1039 continue;
1040
1041 const Value *Callee = CI->getCalledValue();
1042 if (!canLongjmp(M, Callee))
1043 continue;
1044
1045 Value *Threw = nullptr;
1046 BasicBlock *Tail;
1047 if (Callee->getName().startswith(InvokePrefix)) {
1048 // If invoke wrapper has already been generated for this call in
1049 // previous EH phase, search for the load instruction
1050 // %__THREW__.val = __THREW__;
1051 // in postamble after the invoke wrapper call
1052 LoadInst *ThrewLI = nullptr;
1053 StoreInst *ThrewResetSI = nullptr;
1054 for (auto I = std::next(BasicBlock::iterator(CI)), IE = BB->end();
1055 I != IE; ++I) {
1056 if (auto *LI = dyn_cast<LoadInst>(I))
1057 if (auto *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand()))
1058 if (GV == ThrewGV) {
1059 Threw = ThrewLI = LI;
1060 break;
1061 }
1062 }
1063 // Search for the store instruction after the load above
1064 // __THREW__ = 0;
1065 for (auto I = std::next(BasicBlock::iterator(ThrewLI)), IE = BB->end();
1066 I != IE; ++I) {
1067 if (auto *SI = dyn_cast<StoreInst>(I))
1068 if (auto *GV = dyn_cast<GlobalVariable>(SI->getPointerOperand()))
1069 if (GV == ThrewGV && SI->getValueOperand() == IRB.getInt32(0)) {
1070 ThrewResetSI = SI;
1071 break;
1072 }
1073 }
1074 assert(Threw && ThrewLI && "Cannot find __THREW__ load after invoke");
1075 assert(ThrewResetSI && "Cannot find __THREW__ store after invoke");
1076 Tail = SplitBlock(BB, ThrewResetSI->getNextNode());
1077
1078 } else {
1079 // Wrap call with invoke wrapper and generate preamble/postamble
1080 Threw = wrapInvoke(CI);
1081 ToErase.push_back(CI);
1082 Tail = SplitBlock(BB, CI->getNextNode());
1083 }
1084
1085 // We need to replace the terminator in Tail - SplitBlock makes BB go
1086 // straight to Tail, we need to check if a longjmp occurred, and go to the
1087 // right setjmp-tail if so
1088 ToErase.push_back(BB->getTerminator());
1089
1090 // Generate a function call to testSetjmp function and preamble/postamble
1091 // code to figure out (1) whether longjmp occurred (2) if longjmp
1092 // occurred, which setjmp it corresponds to
1093 Value *Label = nullptr;
1094 Value *LongjmpResult = nullptr;
1095 BasicBlock *EndBB = nullptr;
1096 wrapTestSetjmp(BB, CI, Threw, SetjmpTable, SetjmpTableSize, Label,
1097 LongjmpResult, EndBB);
1098 assert(Label && LongjmpResult && EndBB);
1099
1100 // Create switch instruction
1101 IRB.SetInsertPoint(EndBB);
1102 SwitchInst *SI = IRB.CreateSwitch(Label, Tail, SetjmpRetPHIs.size());
1103 // -1 means no longjmp happened, continue normally (will hit the default
1104 // switch case). 0 means a longjmp that is not ours to handle, needs a
1105 // rethrow. Otherwise the index is the same as the index in P+1 (to avoid
1106 // 0).
1107 for (unsigned i = 0; i < SetjmpRetPHIs.size(); i++) {
1108 SI->addCase(IRB.getInt32(i + 1), SetjmpRetPHIs[i]->getParent());
1109 SetjmpRetPHIs[i]->addIncoming(LongjmpResult, EndBB);
1110 }
1111
1112 // We are splitting the block here, and must continue to find other calls
1113 // in the block - which is now split. so continue to traverse in the Tail
1114 BBs.push_back(Tail);
1115 }
1116 }
1117
1118 // Erase everything we no longer need in this function
1119 for (Instruction *I : ToErase)
1120 I->eraseFromParent();
1121
1122 // Free setjmpTable buffer before each return instruction
1123 for (BasicBlock &BB : F) {
1124 TerminatorInst *TI = BB.getTerminator();
1125 if (isa<ReturnInst>(TI))
1126 CallInst::CreateFree(SetjmpTable, TI);
1127 }
1128
1129 // Every call to saveSetjmp can change setjmpTable and setjmpTableSize
1130 // (when buffer reallocation occurs)
1131 // entry:
1132 // setjmpTableSize = 4;
1133 // setjmpTable = (int *) malloc(40);
1134 // setjmpTable[0] = 0;
1135 // ...
1136 // somebb:
1137 // setjmpTable = saveSetjmp(buf, label, setjmpTable, setjmpTableSize);
1138 // setjmpTableSize = __tempRet0;
1139 // So we need to make sure the SSA for these variables is valid so that every
1140 // saveSetjmp and testSetjmp calls have the correct arguments.
1141 SSAUpdater SetjmpTableSSA;
1142 SSAUpdater SetjmpTableSizeSSA;
1143 SetjmpTableSSA.Initialize(Type::getInt32PtrTy(C), "setjmpTable");
1144 SetjmpTableSizeSSA.Initialize(Type::getInt32Ty(C), "setjmpTableSize");
1145 for (Instruction *I : SetjmpTableInsts)
1146 SetjmpTableSSA.AddAvailableValue(I->getParent(), I);
1147 for (Instruction *I : SetjmpTableSizeInsts)
1148 SetjmpTableSizeSSA.AddAvailableValue(I->getParent(), I);
1149
1150 for (auto UI = SetjmpTable->use_begin(), UE = SetjmpTable->use_end();
1151 UI != UE;) {
1152 // Grab the use before incrementing the iterator.
1153 Use &U = *UI;
1154 // Increment the iterator before removing the use from the list.
1155 ++UI;
1156 if (Instruction *I = dyn_cast<Instruction>(U.getUser()))
1157 if (I->getParent() != &EntryBB)
1158 SetjmpTableSSA.RewriteUse(U);
1159 }
1160 for (auto UI = SetjmpTableSize->use_begin(), UE = SetjmpTableSize->use_end();
1161 UI != UE;) {
1162 Use &U = *UI;
1163 ++UI;
1164 if (Instruction *I = dyn_cast<Instruction>(U.getUser()))
1165 if (I->getParent() != &EntryBB)
1166 SetjmpTableSizeSSA.RewriteUse(U);
1167 }
1168
1169 // Finally, our modifications to the cfg can break dominance of SSA variables.
1170 // For example, in this code,
1171 // if (x()) { .. setjmp() .. }
1172 // if (y()) { .. longjmp() .. }
1173 // We must split the longjmp block, and it can jump into the block splitted
1174 // from setjmp one. But that means that when we split the setjmp block, it's
1175 // first part no longer dominates its second part - there is a theoretically
1176 // possible control flow path where x() is false, then y() is true and we
1177 // reach the second part of the setjmp block, without ever reaching the first
1178 // part. So, we rebuild SSA form here.
1179 rebuildSSA(F);
1180 return true;
Derek Schuffccdceda2016-08-18 15:27:25 +00001181}