forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWebAssemblyLowerEmscriptenEHSjLj.cpp
1752 lines (1600 loc) · 71.2 KB
/
WebAssemblyLowerEmscriptenEHSjLj.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//=== WebAssemblyLowerEmscriptenEHSjLj.cpp - Lower exceptions for Emscripten =//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
///
/// \file
/// This file lowers exception-related instructions and setjmp/longjmp function
/// calls to use Emscripten's library functions. The pass uses JavaScript's try
/// and catch mechanism in case of Emscripten EH/SjLj and Wasm EH intrinsics in
/// case of Emscripten SjLJ.
///
/// * Emscripten exception handling
/// This pass lowers invokes and landingpads into library functions in JS glue
/// code. Invokes are lowered into function wrappers called invoke wrappers that
/// exist in JS side, which wraps the original function call with JS try-catch.
/// If an exception occurred, cxa_throw() function in JS side sets some
/// variables (see below) so we can check whether an exception occurred from
/// wasm code and handle it appropriately.
///
/// * Emscripten setjmp-longjmp handling
/// This pass lowers setjmp to a reasonably-performant approach for emscripten.
/// The idea is that each block with a setjmp is broken up into two parts: the
/// part containing setjmp and the part right after the setjmp. The latter part
/// is either reached from the setjmp, or later from a longjmp. To handle the
/// longjmp, all calls that might longjmp are also called using invoke wrappers
/// and thus JS / try-catch. JS longjmp() function also sets some variables so
/// we can check / whether a longjmp occurred from wasm code. Each block with a
/// function call that might longjmp is also split up after the longjmp call.
/// After the longjmp call, we check whether a longjmp occurred, and if it did,
/// which setjmp it corresponds to, and jump to the right post-setjmp block.
/// We assume setjmp-longjmp handling always run after EH handling, which means
/// we don't expect any exception-related instructions when SjLj runs.
/// FIXME Currently this scheme does not support indirect call of setjmp,
/// because of the limitation of the scheme itself. fastcomp does not support it
/// either.
///
/// In detail, this pass does following things:
///
/// 1) Assumes the existence of global variables: __THREW__, __threwValue
/// __THREW__ and __threwValue are defined in compiler-rt in Emscripten.
/// These variables are used for both exceptions and setjmp/longjmps.
/// __THREW__ indicates whether an exception or a longjmp occurred or not. 0
/// means nothing occurred, 1 means an exception occurred, and other numbers
/// mean a longjmp occurred. In the case of longjmp, __THREW__ variable
/// indicates the corresponding setjmp buffer the longjmp corresponds to.
/// __threwValue is 0 for exceptions, and the argument to longjmp in case of
/// longjmp.
///
/// * Emscripten exception handling
///
/// 2) We assume the existence of setThrew and setTempRet0/getTempRet0 functions
/// at link time. setThrew exists in Emscripten's compiler-rt:
///
/// void setThrew(uintptr_t threw, int value) {
/// if (__THREW__ == 0) {
/// __THREW__ = threw;
/// __threwValue = value;
/// }
/// }
//
/// setTempRet0 is called from __cxa_find_matching_catch() in JS glue code.
/// In exception handling, getTempRet0 indicates the type of an exception
/// caught, and in setjmp/longjmp, it means the second argument to longjmp
/// function.
///
/// 3) Lower
/// invoke @func(arg1, arg2) to label %invoke.cont unwind label %lpad
/// into
/// __THREW__ = 0;
/// call @__invoke_SIG(func, arg1, arg2)
/// %__THREW__.val = __THREW__;
/// __THREW__ = 0;
/// if (%__THREW__.val == 1)
/// goto %lpad
/// else
/// goto %invoke.cont
/// SIG is a mangled string generated based on the LLVM IR-level function
/// signature. After LLVM IR types are lowered to the target wasm types,
/// the names for these wrappers will change based on wasm types as well,
/// as in invoke_vi (function takes an int and returns void). The bodies of
/// these wrappers will be generated in JS glue code, and inside those
/// wrappers we use JS try-catch to generate actual exception effects. It
/// also calls the original callee function. An example wrapper in JS code
/// would look like this:
/// function invoke_vi(index,a1) {
/// try {
/// Module["dynCall_vi"](index,a1); // This calls original callee
/// } catch(e) {
/// if (typeof e !== 'number' && e !== 'longjmp') throw e;
/// _setThrew(1, 0); // setThrew is called here
/// }
/// }
/// If an exception is thrown, __THREW__ will be set to true in a wrapper,
/// so we can jump to the right BB based on this value.
///
/// 4) Lower
/// %val = landingpad catch c1 catch c2 catch c3 ...
/// ... use %val ...
/// into
/// %fmc = call @__cxa_find_matching_catch_N(c1, c2, c3, ...)
/// %val = {%fmc, getTempRet0()}
/// ... use %val ...
/// Here N is a number calculated based on the number of clauses.
/// setTempRet0 is called from __cxa_find_matching_catch() in JS glue code.
///
/// 5) Lower
/// resume {%a, %b}
/// into
/// call @__resumeException(%a)
/// where __resumeException() is a function in JS glue code.
///
/// 6) Lower
/// call @llvm.eh.typeid.for(type) (intrinsic)
/// into
/// call @llvm_eh_typeid_for(type)
/// llvm_eh_typeid_for function will be generated in JS glue code.
///
/// * Emscripten setjmp / longjmp handling
///
/// If there are calls to longjmp()
///
/// 1) Lower
/// longjmp(env, val)
/// into
/// emscripten_longjmp(env, val)
///
/// If there are calls to setjmp()
///
/// 2) In the function entry that calls setjmp, initialize setjmpTable and
/// sejmpTableSize as follows:
/// setjmpTableSize = 4;
/// setjmpTable = (int *) malloc(40);
/// setjmpTable[0] = 0;
/// setjmpTable and setjmpTableSize are used to call saveSetjmp() function in
/// Emscripten compiler-rt.
///
/// 3) Lower
/// setjmp(env)
/// into
/// setjmpTable = saveSetjmp(env, label, setjmpTable, setjmpTableSize);
/// setjmpTableSize = getTempRet0();
/// For each dynamic setjmp call, setjmpTable stores its ID (a number which
/// is incrementally assigned from 0) and its label (a unique number that
/// represents each callsite of setjmp). When we need more entries in
/// setjmpTable, it is reallocated in saveSetjmp() in Emscripten's
/// compiler-rt and it will return the new table address, and assign the new
/// table size in setTempRet0(). saveSetjmp also stores the setjmp's ID into
/// the buffer 'env'. A BB with setjmp is split into two after setjmp call in
/// order to make the post-setjmp BB the possible destination of longjmp BB.
///
/// 4) Lower every call that might longjmp into
/// __THREW__ = 0;
/// call @__invoke_SIG(func, arg1, arg2)
/// %__THREW__.val = __THREW__;
/// __THREW__ = 0;
/// %__threwValue.val = __threwValue;
/// if (%__THREW__.val != 0 & %__threwValue.val != 0) {
/// %label = testSetjmp(mem[%__THREW__.val], setjmpTable,
/// setjmpTableSize);
/// if (%label == 0)
/// emscripten_longjmp(%__THREW__.val, %__threwValue.val);
/// setTempRet0(%__threwValue.val);
/// } else {
/// %label = -1;
/// }
/// longjmp_result = getTempRet0();
/// switch %label {
/// label 1: goto post-setjmp BB 1
/// label 2: goto post-setjmp BB 2
/// ...
/// default: goto splitted next BB
/// }
/// testSetjmp examines setjmpTable to see if there is a matching setjmp
/// call. After calling an invoke wrapper, if a longjmp occurred, __THREW__
/// will be the address of matching jmp_buf buffer and __threwValue be the
/// second argument to longjmp. mem[%__THREW__.val] is a setjmp ID that is
/// stored in saveSetjmp. testSetjmp returns a setjmp label, a unique ID to
/// each setjmp callsite. Label 0 means this longjmp buffer does not
/// correspond to one of the setjmp callsites in this function, so in this
/// case we just chain the longjmp to the caller. Label -1 means no longjmp
/// occurred. Otherwise we jump to the right post-setjmp BB based on the
/// label.
///
/// * Wasm setjmp / longjmp handling
/// This mode still uses some Emscripten library functions but not JavaScript's
/// try-catch mechanism. It instead uses Wasm exception handling intrinsics,
/// which will be lowered to exception handling instructions.
///
/// If there are calls to longjmp()
///
/// 1) Lower
/// longjmp(env, val)
/// into
/// __wasm_longjmp(env, val)
///
/// If there are calls to setjmp()
///
/// 2) and 3): The same as 2) and 3) in Emscripten SjLj.
/// (setjmpTable/setjmpTableSize initialization + setjmp callsite
/// transformation)
///
/// 4) Create a catchpad with a wasm.catch() intrinsic, which returns the value
/// thrown by __wasm_longjmp function. In Emscripten library, we have this
/// struct:
///
/// struct __WasmLongjmpArgs {
/// void *env;
/// int val;
/// };
/// struct __WasmLongjmpArgs __wasm_longjmp_args;
///
/// The thrown value here is a pointer to __wasm_longjmp_args struct object. We
/// use this struct to transfer two values by throwing a single value. Wasm
/// throw and catch instructions are capable of throwing and catching multiple
/// values, but it also requires multivalue support that is currently not very
/// reliable.
/// TODO Switch to throwing and catching two values without using the struct
///
/// All longjmpable function calls will be converted to an invoke that will
/// unwind to this catchpad in case a longjmp occurs. Within the catchpad, we
/// test the thrown values using testSetjmp function as we do for Emscripten
/// SjLj. The main difference is, in Emscripten SjLj, we need to transform every
/// longjmpable callsite into a sequence of code including testSetjmp() call; in
/// Wasm SjLj we do the testing in only one place, in this catchpad.
///
/// After testing calling testSetjmp(), if the longjmp does not correspond to
/// one of the setjmps within the current function, it rethrows the longjmp
/// by calling __wasm_longjmp(). If it corresponds to one of setjmps in the
/// function, we jump to the beginning of the function, which contains a switch
/// to each post-setjmp BB. Again, in Emscripten SjLj, this switch is added for
/// every longjmpable callsite; in Wasm SjLj we do this only once at the top of
/// the function. (after setjmpTable/setjmpTableSize initialization)
///
/// The below is the pseudocode for what we have described
///
/// entry:
/// Initialize setjmpTable and setjmpTableSize
///
/// setjmp.dispatch:
/// switch %label {
/// label 1: goto post-setjmp BB 1
/// label 2: goto post-setjmp BB 2
/// ...
/// default: goto splitted next BB
/// }
/// ...
///
/// bb:
/// invoke void @foo() ;; foo is a longjmpable function
/// to label %next unwind label %catch.dispatch.longjmp
/// ...
///
/// catch.dispatch.longjmp:
/// %0 = catchswitch within none [label %catch.longjmp] unwind to caller
///
/// catch.longjmp:
/// %longjmp.args = wasm.catch() ;; struct __WasmLongjmpArgs
/// %env = load 'env' field from __WasmLongjmpArgs
/// %val = load 'val' field from __WasmLongjmpArgs
/// %label = testSetjmp(mem[%env], setjmpTable, setjmpTableSize);
/// if (%label == 0)
/// __wasm_longjmp(%env, %val)
/// catchret to %setjmp.dispatch
///
///===----------------------------------------------------------------------===//
#include "WebAssembly.h"
#include "WebAssemblyTargetMachine.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/CodeGen/TargetPassConfig.h"
#include "llvm/CodeGen/WasmEHFuncInfo.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/IntrinsicsWebAssembly.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/SSAUpdater.h"
#include "llvm/Transforms/Utils/SSAUpdaterBulk.h"
using namespace llvm;
#define DEBUG_TYPE "wasm-lower-em-ehsjlj"
// Emscripten's asm.js-style exception handling
extern cl::opt<bool> WasmEnableEmEH;
// Emscripten's asm.js-style setjmp/longjmp handling
extern cl::opt<bool> WasmEnableEmSjLj;
// Wasm setjmp/longjmp handling using wasm EH instructions
extern cl::opt<bool> WasmEnableSjLj;
static cl::list<std::string>
EHAllowlist("emscripten-cxx-exceptions-allowed",
cl::desc("The list of function names in which Emscripten-style "
"exception handling is enabled (see emscripten "
"EMSCRIPTEN_CATCHING_ALLOWED options)"),
cl::CommaSeparated);
namespace {
class WebAssemblyLowerEmscriptenEHSjLj final : public ModulePass {
bool EnableEmEH; // Enable Emscripten exception handling
bool EnableEmSjLj; // Enable Emscripten setjmp/longjmp handling
bool EnableWasmSjLj; // Enable Wasm setjmp/longjmp handling
bool DoSjLj; // Whether we actually perform setjmp/longjmp handling
GlobalVariable *ThrewGV = nullptr; // __THREW__ (Emscripten)
GlobalVariable *ThrewValueGV = nullptr; // __threwValue (Emscripten)
Function *GetTempRet0F = nullptr; // getTempRet0() (Emscripten)
Function *SetTempRet0F = nullptr; // setTempRet0() (Emscripten)
Function *ResumeF = nullptr; // __resumeException() (Emscripten)
Function *EHTypeIDF = nullptr; // llvm.eh.typeid.for() (intrinsic)
Function *EmLongjmpF = nullptr; // emscripten_longjmp() (Emscripten)
Function *SaveSetjmpF = nullptr; // saveSetjmp() (Emscripten)
Function *TestSetjmpF = nullptr; // testSetjmp() (Emscripten)
Function *WasmLongjmpF = nullptr; // __wasm_longjmp() (Emscripten)
Function *CatchF = nullptr; // wasm.catch() (intrinsic)
// type of 'struct __WasmLongjmpArgs' defined in emscripten
Type *LongjmpArgsTy = nullptr;
// __cxa_find_matching_catch_N functions.
// Indexed by the number of clauses in an original landingpad instruction.
DenseMap<int, Function *> FindMatchingCatches;
// Map of <function signature string, invoke_ wrappers>
StringMap<Function *> InvokeWrappers;
// Set of allowed function names for exception handling
std::set<std::string> EHAllowlistSet;
// Functions that contains calls to setjmp
SmallPtrSet<Function *, 8> SetjmpUsers;
StringRef getPassName() const override {
return "WebAssembly Lower Emscripten Exceptions";
}
using InstVector = SmallVectorImpl<Instruction *>;
bool runEHOnFunction(Function &F);
bool runSjLjOnFunction(Function &F);
void handleLongjmpableCallsForEmscriptenSjLj(
Function &F, InstVector &SetjmpTableInsts,
InstVector &SetjmpTableSizeInsts,
SmallVectorImpl<PHINode *> &SetjmpRetPHIs);
void
handleLongjmpableCallsForWasmSjLj(Function &F, InstVector &SetjmpTableInsts,
InstVector &SetjmpTableSizeInsts,
SmallVectorImpl<PHINode *> &SetjmpRetPHIs);
Function *getFindMatchingCatch(Module &M, unsigned NumClauses);
Value *wrapInvoke(CallBase *CI);
void wrapTestSetjmp(BasicBlock *BB, DebugLoc DL, Value *Threw,
Value *SetjmpTable, Value *SetjmpTableSize, Value *&Label,
Value *&LongjmpResult, BasicBlock *&CallEmLongjmpBB,
PHINode *&CallEmLongjmpBBThrewPHI,
PHINode *&CallEmLongjmpBBThrewValuePHI,
BasicBlock *&EndBB);
Function *getInvokeWrapper(CallBase *CI);
bool areAllExceptionsAllowed() const { return EHAllowlistSet.empty(); }
bool supportsException(const Function *F) const {
return EnableEmEH && (areAllExceptionsAllowed() ||
EHAllowlistSet.count(std::string(F->getName())));
}
void replaceLongjmpWith(Function *LongjmpF, Function *NewF);
void rebuildSSA(Function &F);
public:
static char ID;
WebAssemblyLowerEmscriptenEHSjLj()
: ModulePass(ID), EnableEmEH(WasmEnableEmEH),
EnableEmSjLj(WasmEnableEmSjLj), EnableWasmSjLj(WasmEnableSjLj) {
assert(!(EnableEmSjLj && EnableWasmSjLj) &&
"Two SjLj modes cannot be turned on at the same time");
assert(!(EnableEmEH && EnableWasmSjLj) &&
"Wasm SjLj should be only used with Wasm EH");
EHAllowlistSet.insert(EHAllowlist.begin(), EHAllowlist.end());
}
bool runOnModule(Module &M) override;
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<DominatorTreeWrapperPass>();
}
};
} // End anonymous namespace
char WebAssemblyLowerEmscriptenEHSjLj::ID = 0;
INITIALIZE_PASS(WebAssemblyLowerEmscriptenEHSjLj, DEBUG_TYPE,
"WebAssembly Lower Emscripten Exceptions / Setjmp / Longjmp",
false, false)
ModulePass *llvm::createWebAssemblyLowerEmscriptenEHSjLj() {
return new WebAssemblyLowerEmscriptenEHSjLj();
}
static bool canThrow(const Value *V) {
if (const auto *F = dyn_cast<const Function>(V)) {
// Intrinsics cannot throw
if (F->isIntrinsic())
return false;
StringRef Name = F->getName();
// leave setjmp and longjmp (mostly) alone, we process them properly later
if (Name == "setjmp" || Name == "longjmp" || Name == "emscripten_longjmp")
return false;
return !F->doesNotThrow();
}
// not a function, so an indirect call - can throw, we can't tell
return true;
}
// Get a global variable with the given name. If it doesn't exist declare it,
// which will generate an import and assume that it will exist at link time.
static GlobalVariable *getGlobalVariable(Module &M, Type *Ty,
WebAssemblyTargetMachine &TM,
const char *Name) {
auto *GV = dyn_cast<GlobalVariable>(M.getOrInsertGlobal(Name, Ty));
if (!GV)
report_fatal_error(Twine("unable to create global: ") + Name);
// If the target supports TLS, make this variable thread-local. We can't just
// unconditionally make it thread-local and depend on
// CoalesceFeaturesAndStripAtomics to downgrade it, because stripping TLS has
// the side effect of disallowing the object from being linked into a
// shared-memory module, which we don't want to be responsible for.
auto *Subtarget = TM.getSubtargetImpl();
auto TLS = Subtarget->hasAtomics() && Subtarget->hasBulkMemory()
? GlobalValue::LocalExecTLSModel
: GlobalValue::NotThreadLocal;
GV->setThreadLocalMode(TLS);
return GV;
}
// Simple function name mangler.
// This function simply takes LLVM's string representation of parameter types
// and concatenate them with '_'. There are non-alphanumeric characters but llc
// is ok with it, and we need to postprocess these names after the lowering
// phase anyway.
static std::string getSignature(FunctionType *FTy) {
std::string Sig;
raw_string_ostream OS(Sig);
OS << *FTy->getReturnType();
for (Type *ParamTy : FTy->params())
OS << "_" << *ParamTy;
if (FTy->isVarArg())
OS << "_...";
Sig = OS.str();
erase_if(Sig, isSpace);
// When s2wasm parses .s file, a comma means the end of an argument. So a
// mangled function name can contain any character but a comma.
std::replace(Sig.begin(), Sig.end(), ',', '.');
return Sig;
}
static Function *getEmscriptenFunction(FunctionType *Ty, const Twine &Name,
Module *M) {
Function* F = Function::Create(Ty, GlobalValue::ExternalLinkage, Name, M);
// Tell the linker that this function is expected to be imported from the
// 'env' module.
if (!F->hasFnAttribute("wasm-import-module")) {
llvm::AttrBuilder B;
B.addAttribute("wasm-import-module", "env");
F->addFnAttrs(B);
}
if (!F->hasFnAttribute("wasm-import-name")) {
llvm::AttrBuilder B;
B.addAttribute("wasm-import-name", F->getName());
F->addFnAttrs(B);
}
return F;
}
// Returns an integer type for the target architecture's address space.
// i32 for wasm32 and i64 for wasm64.
static Type *getAddrIntType(Module *M) {
IRBuilder<> IRB(M->getContext());
return IRB.getIntNTy(M->getDataLayout().getPointerSizeInBits());
}
// Returns an integer pointer type for the target architecture's address space.
// i32* for wasm32 and i64* for wasm64.
static Type *getAddrPtrType(Module *M) {
return Type::getIntNPtrTy(M->getContext(),
M->getDataLayout().getPointerSizeInBits());
}
// Returns an integer whose type is the integer type for the target's address
// space. Returns (i32 C) for wasm32 and (i64 C) for wasm64, when C is the
// integer.
static Value *getAddrSizeInt(Module *M, uint64_t C) {
IRBuilder<> IRB(M->getContext());
return IRB.getIntN(M->getDataLayout().getPointerSizeInBits(), C);
}
// Returns __cxa_find_matching_catch_N function, where N = NumClauses + 2.
// This is because a landingpad instruction contains two more arguments, a
// personality function and a cleanup bit, and __cxa_find_matching_catch_N
// functions are named after the number of arguments in the original landingpad
// instruction.
Function *
WebAssemblyLowerEmscriptenEHSjLj::getFindMatchingCatch(Module &M,
unsigned NumClauses) {
if (FindMatchingCatches.count(NumClauses))
return FindMatchingCatches[NumClauses];
PointerType *Int8PtrTy = Type::getInt8PtrTy(M.getContext());
SmallVector<Type *, 16> Args(NumClauses, Int8PtrTy);
FunctionType *FTy = FunctionType::get(Int8PtrTy, Args, false);
Function *F = getEmscriptenFunction(
FTy, "__cxa_find_matching_catch_" + Twine(NumClauses + 2), &M);
FindMatchingCatches[NumClauses] = F;
return F;
}
// Generate invoke wrapper seqence with preamble and postamble
// Preamble:
// __THREW__ = 0;
// Postamble:
// %__THREW__.val = __THREW__; __THREW__ = 0;
// Returns %__THREW__.val, which indicates whether an exception is thrown (or
// whether longjmp occurred), for future use.
Value *WebAssemblyLowerEmscriptenEHSjLj::wrapInvoke(CallBase *CI) {
Module *M = CI->getModule();
LLVMContext &C = M->getContext();
IRBuilder<> IRB(C);
IRB.SetInsertPoint(CI);
// Pre-invoke
// __THREW__ = 0;
IRB.CreateStore(getAddrSizeInt(M, 0), ThrewGV);
// Invoke function wrapper in JavaScript
SmallVector<Value *, 16> Args;
// Put the pointer to the callee as first argument, so it can be called
// within the invoke wrapper later
Args.push_back(CI->getCalledOperand());
Args.append(CI->arg_begin(), CI->arg_end());
CallInst *NewCall = IRB.CreateCall(getInvokeWrapper(CI), Args);
NewCall->takeName(CI);
NewCall->setCallingConv(CallingConv::WASM_EmscriptenInvoke);
NewCall->setDebugLoc(CI->getDebugLoc());
// Because we added the pointer to the callee as first argument, all
// argument attribute indices have to be incremented by one.
SmallVector<AttributeSet, 8> ArgAttributes;
const AttributeList &InvokeAL = CI->getAttributes();
// No attributes for the callee pointer.
ArgAttributes.push_back(AttributeSet());
// Copy the argument attributes from the original
for (unsigned I = 0, E = CI->arg_size(); I < E; ++I)
ArgAttributes.push_back(InvokeAL.getParamAttrs(I));
AttrBuilder FnAttrs(InvokeAL.getFnAttrs());
if (FnAttrs.contains(Attribute::AllocSize)) {
// The allocsize attribute (if any) referes to parameters by index and needs
// to be adjusted.
unsigned SizeArg;
Optional<unsigned> NEltArg;
std::tie(SizeArg, NEltArg) = FnAttrs.getAllocSizeArgs();
SizeArg += 1;
if (NEltArg.hasValue())
NEltArg = NEltArg.getValue() + 1;
FnAttrs.addAllocSizeAttr(SizeArg, NEltArg);
}
// Reconstruct the AttributesList based on the vector we constructed.
AttributeList NewCallAL = AttributeList::get(
C, AttributeSet::get(C, FnAttrs), InvokeAL.getRetAttrs(), ArgAttributes);
NewCall->setAttributes(NewCallAL);
CI->replaceAllUsesWith(NewCall);
// Post-invoke
// %__THREW__.val = __THREW__; __THREW__ = 0;
Value *Threw =
IRB.CreateLoad(getAddrIntType(M), ThrewGV, ThrewGV->getName() + ".val");
IRB.CreateStore(getAddrSizeInt(M, 0), ThrewGV);
return Threw;
}
// Get matching invoke wrapper based on callee signature
Function *WebAssemblyLowerEmscriptenEHSjLj::getInvokeWrapper(CallBase *CI) {
Module *M = CI->getModule();
SmallVector<Type *, 16> ArgTys;
FunctionType *CalleeFTy = CI->getFunctionType();
std::string Sig = getSignature(CalleeFTy);
if (InvokeWrappers.find(Sig) != InvokeWrappers.end())
return InvokeWrappers[Sig];
// Put the pointer to the callee as first argument
ArgTys.push_back(PointerType::getUnqual(CalleeFTy));
// Add argument types
ArgTys.append(CalleeFTy->param_begin(), CalleeFTy->param_end());
FunctionType *FTy = FunctionType::get(CalleeFTy->getReturnType(), ArgTys,
CalleeFTy->isVarArg());
Function *F = getEmscriptenFunction(FTy, "__invoke_" + Sig, M);
InvokeWrappers[Sig] = F;
return F;
}
static bool canLongjmp(const Value *Callee) {
if (auto *CalleeF = dyn_cast<Function>(Callee))
if (CalleeF->isIntrinsic())
return false;
// Attempting to transform inline assembly will result in something like:
// call void @__invoke_void(void ()* asm ...)
// which is invalid because inline assembly blocks do not have addresses
// and can't be passed by pointer. The result is a crash with illegal IR.
if (isa<InlineAsm>(Callee))
return false;
StringRef CalleeName = Callee->getName();
// The reason we include malloc/free here is to exclude the malloc/free
// calls generated in setjmp prep / cleanup routines.
if (CalleeName == "setjmp" || CalleeName == "malloc" || CalleeName == "free")
return false;
// There are functions in Emscripten's JS glue code or compiler-rt
if (CalleeName == "__resumeException" || CalleeName == "llvm_eh_typeid_for" ||
CalleeName == "saveSetjmp" || CalleeName == "testSetjmp" ||
CalleeName == "getTempRet0" || CalleeName == "setTempRet0")
return false;
// __cxa_find_matching_catch_N functions cannot longjmp
if (Callee->getName().startswith("__cxa_find_matching_catch_"))
return false;
// Exception-catching related functions
if (CalleeName == "__cxa_begin_catch" || CalleeName == "__cxa_end_catch" ||
CalleeName == "__cxa_allocate_exception" || CalleeName == "__cxa_throw" ||
CalleeName == "__clang_call_terminate")
return false;
// Otherwise we don't know
return true;
}
static bool isEmAsmCall(const Value *Callee) {
StringRef CalleeName = Callee->getName();
// This is an exhaustive list from Emscripten's <emscripten/em_asm.h>.
return CalleeName == "emscripten_asm_const_int" ||
CalleeName == "emscripten_asm_const_double" ||
CalleeName == "emscripten_asm_const_int_sync_on_main_thread" ||
CalleeName == "emscripten_asm_const_double_sync_on_main_thread" ||
CalleeName == "emscripten_asm_const_async_on_main_thread";
}
// Generate testSetjmp function call seqence with preamble and postamble.
// The code this generates is equivalent to the following JavaScript code:
// %__threwValue.val = __threwValue;
// if (%__THREW__.val != 0 & %__threwValue.val != 0) {
// %label = testSetjmp(mem[%__THREW__.val], setjmpTable, setjmpTableSize);
// if (%label == 0)
// emscripten_longjmp(%__THREW__.val, %__threwValue.val);
// setTempRet0(%__threwValue.val);
// } else {
// %label = -1;
// }
// %longjmp_result = getTempRet0();
//
// As output parameters. returns %label, %longjmp_result, and the BB the last
// instruction (%longjmp_result = ...) is in.
void WebAssemblyLowerEmscriptenEHSjLj::wrapTestSetjmp(
BasicBlock *BB, DebugLoc DL, Value *Threw, Value *SetjmpTable,
Value *SetjmpTableSize, Value *&Label, Value *&LongjmpResult,
BasicBlock *&CallEmLongjmpBB, PHINode *&CallEmLongjmpBBThrewPHI,
PHINode *&CallEmLongjmpBBThrewValuePHI, BasicBlock *&EndBB) {
Function *F = BB->getParent();
Module *M = F->getParent();
LLVMContext &C = M->getContext();
IRBuilder<> IRB(C);
IRB.SetCurrentDebugLocation(DL);
// if (%__THREW__.val != 0 & %__threwValue.val != 0)
IRB.SetInsertPoint(BB);
BasicBlock *ThenBB1 = BasicBlock::Create(C, "if.then1", F);
BasicBlock *ElseBB1 = BasicBlock::Create(C, "if.else1", F);
BasicBlock *EndBB1 = BasicBlock::Create(C, "if.end", F);
Value *ThrewCmp = IRB.CreateICmpNE(Threw, getAddrSizeInt(M, 0));
Value *ThrewValue = IRB.CreateLoad(IRB.getInt32Ty(), ThrewValueGV,
ThrewValueGV->getName() + ".val");
Value *ThrewValueCmp = IRB.CreateICmpNE(ThrewValue, IRB.getInt32(0));
Value *Cmp1 = IRB.CreateAnd(ThrewCmp, ThrewValueCmp, "cmp1");
IRB.CreateCondBr(Cmp1, ThenBB1, ElseBB1);
// Generate call.em.longjmp BB once and share it within the function
if (!CallEmLongjmpBB) {
// emscripten_longjmp(%__THREW__.val, %__threwValue.val);
CallEmLongjmpBB = BasicBlock::Create(C, "call.em.longjmp", F);
IRB.SetInsertPoint(CallEmLongjmpBB);
CallEmLongjmpBBThrewPHI = IRB.CreatePHI(getAddrIntType(M), 4, "threw.phi");
CallEmLongjmpBBThrewValuePHI =
IRB.CreatePHI(IRB.getInt32Ty(), 4, "threwvalue.phi");
CallEmLongjmpBBThrewPHI->addIncoming(Threw, ThenBB1);
CallEmLongjmpBBThrewValuePHI->addIncoming(ThrewValue, ThenBB1);
IRB.CreateCall(EmLongjmpF,
{CallEmLongjmpBBThrewPHI, CallEmLongjmpBBThrewValuePHI});
IRB.CreateUnreachable();
} else {
CallEmLongjmpBBThrewPHI->addIncoming(Threw, ThenBB1);
CallEmLongjmpBBThrewValuePHI->addIncoming(ThrewValue, ThenBB1);
}
// %label = testSetjmp(mem[%__THREW__.val], setjmpTable, setjmpTableSize);
// if (%label == 0)
IRB.SetInsertPoint(ThenBB1);
BasicBlock *EndBB2 = BasicBlock::Create(C, "if.end2", F);
Value *ThrewPtr =
IRB.CreateIntToPtr(Threw, getAddrPtrType(M), Threw->getName() + ".p");
Value *LoadedThrew = IRB.CreateLoad(getAddrIntType(M), ThrewPtr,
ThrewPtr->getName() + ".loaded");
Value *ThenLabel = IRB.CreateCall(
TestSetjmpF, {LoadedThrew, SetjmpTable, SetjmpTableSize}, "label");
Value *Cmp2 = IRB.CreateICmpEQ(ThenLabel, IRB.getInt32(0));
IRB.CreateCondBr(Cmp2, CallEmLongjmpBB, EndBB2);
// setTempRet0(%__threwValue.val);
IRB.SetInsertPoint(EndBB2);
IRB.CreateCall(SetTempRet0F, ThrewValue);
IRB.CreateBr(EndBB1);
IRB.SetInsertPoint(ElseBB1);
IRB.CreateBr(EndBB1);
// longjmp_result = getTempRet0();
IRB.SetInsertPoint(EndBB1);
PHINode *LabelPHI = IRB.CreatePHI(IRB.getInt32Ty(), 2, "label");
LabelPHI->addIncoming(ThenLabel, EndBB2);
LabelPHI->addIncoming(IRB.getInt32(-1), ElseBB1);
// Output parameter assignment
Label = LabelPHI;
EndBB = EndBB1;
LongjmpResult = IRB.CreateCall(GetTempRet0F, None, "longjmp_result");
}
void WebAssemblyLowerEmscriptenEHSjLj::rebuildSSA(Function &F) {
DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
DT.recalculate(F); // CFG has been changed
SSAUpdaterBulk SSA;
for (BasicBlock &BB : F) {
for (Instruction &I : BB) {
unsigned VarID = SSA.AddVariable(I.getName(), I.getType());
// If a value is defined by an invoke instruction, it is only available in
// its normal destination and not in its unwind destination.
if (auto *II = dyn_cast<InvokeInst>(&I))
SSA.AddAvailableValue(VarID, II->getNormalDest(), II);
else
SSA.AddAvailableValue(VarID, &BB, &I);
for (auto &U : I.uses()) {
auto *User = cast<Instruction>(U.getUser());
if (auto *UserPN = dyn_cast<PHINode>(User))
if (UserPN->getIncomingBlock(U) == &BB)
continue;
if (DT.dominates(&I, User))
continue;
SSA.AddUse(VarID, &U);
}
}
}
SSA.RewriteAllUses(&DT);
}
// Replace uses of longjmp with a new longjmp function in Emscripten library.
// In Emscripten SjLj, the new function is
// void emscripten_longjmp(uintptr_t, i32)
// In Wasm SjLj, the new function is
// void __wasm_longjmp(i8*, i32)
// Because the original libc longjmp function takes (jmp_buf*, i32), we need a
// ptrtoint/bitcast instruction here to make the type match. jmp_buf* will
// eventually be lowered to i32/i64 in the wasm backend.
void WebAssemblyLowerEmscriptenEHSjLj::replaceLongjmpWith(Function *LongjmpF,
Function *NewF) {
assert(NewF == EmLongjmpF || NewF == WasmLongjmpF);
Module *M = LongjmpF->getParent();
SmallVector<CallInst *, 8> ToErase;
LLVMContext &C = LongjmpF->getParent()->getContext();
IRBuilder<> IRB(C);
// For calls to longjmp, replace it with emscripten_longjmp/__wasm_longjmp and
// cast its first argument (jmp_buf*) appropriately
for (User *U : LongjmpF->users()) {
auto *CI = dyn_cast<CallInst>(U);
if (CI && CI->getCalledFunction() == LongjmpF) {
IRB.SetInsertPoint(CI);
Value *Env = nullptr;
if (NewF == EmLongjmpF)
Env =
IRB.CreatePtrToInt(CI->getArgOperand(0), getAddrIntType(M), "env");
else // WasmLongjmpF
Env =
IRB.CreateBitCast(CI->getArgOperand(0), IRB.getInt8PtrTy(), "env");
IRB.CreateCall(NewF, {Env, CI->getArgOperand(1)});
ToErase.push_back(CI);
}
}
for (auto *I : ToErase)
I->eraseFromParent();
// If we have any remaining uses of longjmp's function pointer, replace it
// with (void(*)(jmp_buf*, int))emscripten_longjmp / __wasm_longjmp.
if (!LongjmpF->uses().empty()) {
Value *NewLongjmp =
IRB.CreateBitCast(NewF, LongjmpF->getType(), "longjmp.cast");
LongjmpF->replaceAllUsesWith(NewLongjmp);
}
}
static bool containsLongjmpableCalls(const Function *F) {
for (const auto &BB : *F)
for (const auto &I : BB)
if (const auto *CB = dyn_cast<CallBase>(&I))
if (canLongjmp(CB->getCalledOperand()))
return true;
return false;
}
bool WebAssemblyLowerEmscriptenEHSjLj::runOnModule(Module &M) {
LLVM_DEBUG(dbgs() << "********** Lower Emscripten EH & SjLj **********\n");
LLVMContext &C = M.getContext();
IRBuilder<> IRB(C);
Function *SetjmpF = M.getFunction("setjmp");
Function *LongjmpF = M.getFunction("longjmp");
// In some platforms _setjmp and _longjmp are used instead. Change these to
// use setjmp/longjmp instead, because we later detect these functions by
// their names.
Function *SetjmpF2 = M.getFunction("_setjmp");
Function *LongjmpF2 = M.getFunction("_longjmp");
if (SetjmpF2) {
if (SetjmpF) {
if (SetjmpF->getFunctionType() != SetjmpF2->getFunctionType())
report_fatal_error("setjmp and _setjmp have different function types");
} else {
SetjmpF = Function::Create(SetjmpF2->getFunctionType(),
GlobalValue::ExternalLinkage, "setjmp", M);
}
SetjmpF2->replaceAllUsesWith(SetjmpF);
}
if (LongjmpF2) {
if (LongjmpF) {
if (LongjmpF->getFunctionType() != LongjmpF2->getFunctionType())
report_fatal_error(
"longjmp and _longjmp have different function types");
} else {
LongjmpF = Function::Create(LongjmpF2->getFunctionType(),
GlobalValue::ExternalLinkage, "setjmp", M);
}
LongjmpF2->replaceAllUsesWith(LongjmpF);
}
auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
assert(TPC && "Expected a TargetPassConfig");
auto &TM = TPC->getTM<WebAssemblyTargetMachine>();
// Declare (or get) global variables __THREW__, __threwValue, and
// getTempRet0/setTempRet0 function which are used in common for both
// exception handling and setjmp/longjmp handling
ThrewGV = getGlobalVariable(M, getAddrIntType(&M), TM, "__THREW__");
ThrewValueGV = getGlobalVariable(M, IRB.getInt32Ty(), TM, "__threwValue");
GetTempRet0F = getEmscriptenFunction(
FunctionType::get(IRB.getInt32Ty(), false), "getTempRet0", &M);
SetTempRet0F = getEmscriptenFunction(
FunctionType::get(IRB.getVoidTy(), IRB.getInt32Ty(), false),
"setTempRet0", &M);
GetTempRet0F->setDoesNotThrow();
SetTempRet0F->setDoesNotThrow();
bool Changed = false;
// Function registration for exception handling
if (EnableEmEH) {
// Register __resumeException function
FunctionType *ResumeFTy =
FunctionType::get(IRB.getVoidTy(), IRB.getInt8PtrTy(), false);
ResumeF = getEmscriptenFunction(ResumeFTy, "__resumeException", &M);
ResumeF->addFnAttr(Attribute::NoReturn);
// Register llvm_eh_typeid_for function
FunctionType *EHTypeIDTy =
FunctionType::get(IRB.getInt32Ty(), IRB.getInt8PtrTy(), false);
EHTypeIDF = getEmscriptenFunction(EHTypeIDTy, "llvm_eh_typeid_for", &M);
}
if ((EnableEmSjLj || EnableWasmSjLj) && SetjmpF) {
// Precompute setjmp users
for (User *U : SetjmpF->users()) {
if (auto *CB = dyn_cast<CallBase>(U)) {
auto *UserF = CB->getFunction();
// If a function that calls setjmp does not contain any other calls that
// can longjmp, we don't need to do any transformation on that function,
// so can ignore it
if (containsLongjmpableCalls(UserF))
SetjmpUsers.insert(UserF);
} else {
std::string S;
raw_string_ostream SS(S);
SS << *U;
report_fatal_error(Twine("Indirect use of setjmp is not supported: ") +
SS.str());
}
}
}
bool SetjmpUsed = SetjmpF && !SetjmpUsers.empty();
bool LongjmpUsed = LongjmpF && !LongjmpF->use_empty();
DoSjLj = (EnableEmSjLj | EnableWasmSjLj) && (SetjmpUsed || LongjmpUsed);
// Function registration and data pre-gathering for setjmp/longjmp handling
if (DoSjLj) {
assert(EnableEmSjLj || EnableWasmSjLj);
if (EnableEmSjLj) {
// Register emscripten_longjmp function
FunctionType *FTy = FunctionType::get(
IRB.getVoidTy(), {getAddrIntType(&M), IRB.getInt32Ty()}, false);
EmLongjmpF = getEmscriptenFunction(FTy, "emscripten_longjmp", &M);
EmLongjmpF->addFnAttr(Attribute::NoReturn);
} else { // EnableWasmSjLj
// Register __wasm_longjmp function, which calls __builtin_wasm_longjmp.
FunctionType *FTy = FunctionType::get(
IRB.getVoidTy(), {IRB.getInt8PtrTy(), IRB.getInt32Ty()}, false);
WasmLongjmpF = getEmscriptenFunction(FTy, "__wasm_longjmp", &M);
WasmLongjmpF->addFnAttr(Attribute::NoReturn);
}
if (SetjmpF) {
// Register saveSetjmp function
FunctionType *SetjmpFTy = SetjmpF->getFunctionType();
FunctionType *FTy =
FunctionType::get(Type::getInt32PtrTy(C),
{SetjmpFTy->getParamType(0), IRB.getInt32Ty(),
Type::getInt32PtrTy(C), IRB.getInt32Ty()},
false);
SaveSetjmpF = getEmscriptenFunction(FTy, "saveSetjmp", &M);
// Register testSetjmp function
FTy = FunctionType::get(
IRB.getInt32Ty(),
{getAddrIntType(&M), Type::getInt32PtrTy(C), IRB.getInt32Ty()},
false);
TestSetjmpF = getEmscriptenFunction(FTy, "testSetjmp", &M);
// wasm.catch() will be lowered down to wasm 'catch' instruction in
// instruction selection.
CatchF = Intrinsic::getDeclaration(&M, Intrinsic::wasm_catch);
// Type for struct __WasmLongjmpArgs
LongjmpArgsTy = StructType::get(IRB.getInt8PtrTy(), // env
IRB.getInt32Ty() // val
);
}
}
// Exception handling transformation
if (EnableEmEH) {
for (Function &F : M) {
if (F.isDeclaration())
continue;
Changed |= runEHOnFunction(F);
}
}
// Setjmp/longjmp handling transformation
if (DoSjLj) {
Changed = true; // We have setjmp or longjmp somewhere
if (LongjmpF)
replaceLongjmpWith(LongjmpF, EnableEmSjLj ? EmLongjmpF : WasmLongjmpF);
// Only traverse functions that uses setjmp in order not to insert
// unnecessary prep / cleanup code in every function
if (SetjmpF)
for (Function *F : SetjmpUsers)
runSjLjOnFunction(*F);
}
if (!Changed) {
// Delete unused global variables and functions
if (ResumeF)
ResumeF->eraseFromParent();
if (EHTypeIDF)
EHTypeIDF->eraseFromParent();
if (EmLongjmpF)
EmLongjmpF->eraseFromParent();
if (SaveSetjmpF)
SaveSetjmpF->eraseFromParent();
if (TestSetjmpF)
TestSetjmpF->eraseFromParent();
return false;
}
return true;
}