-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
jiterpreter-support.ts
1724 lines (1514 loc) · 60.2 KB
/
jiterpreter-support.ts
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
import { mono_assert } from "./types";
import { NativePointer, ManagedPointer, VoidPtr } from "./types/emscripten";
import { Module, runtimeHelpers } from "./imports";
import { WasmOpcode } from "./jiterpreter-opcodes";
import cwraps from "./cwraps";
export const maxFailures = 2,
maxMemsetSize = 64,
maxMemmoveSize = 64,
shortNameBase = 36;
// uint16
export declare interface MintOpcodePtr extends NativePointer {
__brand: "MintOpcodePtr"
}
export const enum JiterpNumberMode {
U32 = 0,
I32 = 1,
F32 = 2,
F64 = 3
}
export const enum BailoutReason {
Unknown,
InterpreterTiering,
NullCheck,
VtableNotInitialized,
Branch,
BackwardBranch,
ConditionalBranch,
ConditionalBackwardBranch,
ComplexBranch,
ArrayLoadFailed,
ArrayStoreFailed,
StringOperationFailed,
DivideByZero,
Overflow,
Return,
Call,
Throw,
AllocFailed,
SpanOperationFailed,
CastFailed,
SafepointBranchTaken,
UnboxFailed,
CallDelegate,
Debugging,
Icall,
}
export const BailoutReasonNames = [
"Unknown",
"InterpreterTiering",
"NullCheck",
"VtableNotInitialized",
"Branch",
"BackwardBranch",
"ConditionalBranch",
"ConditionalBackwardBranch",
"ComplexBranch",
"ArrayLoadFailed",
"ArrayStoreFailed",
"StringOperationFailed",
"DivideByZero",
"Overflow",
"Return",
"Call",
"Throw",
"AllocFailed",
"SpanOperationFailed",
"CastFailed",
"SafepointBranchTaken",
"UnboxFailed",
"CallDelegate",
"Debugging",
"Icall",
];
type FunctionType = [
index: FunctionTypeIndex,
parameters: { [name: string]: WasmValtype },
returnType: WasmValtype,
signature: string,
permanent: boolean,
];
type FunctionTypeIndex = number;
type FunctionTypeByIndex = [
parameters: { [name: string]: WasmValtype },
parameterCount: number,
returnType: WasmValtype,
];
type FunctionInfo = {
index: number;
name: string;
typeName: string;
typeIndex: number;
locals: { [name: string]: WasmValtype };
export: boolean;
generator: Function;
error: Error | null;
blob: Uint8Array | null;
}
type ImportedFunctionInfo = {
index?: number;
typeIndex: number;
module: string;
name: string;
assumeUsed: boolean;
func: Function;
}
const compressedNameCache : { [number: number] : string } = {};
export class WasmBuilder {
cfg: Cfg;
stack: Array<BlobBuilder>;
stackSize!: number;
inSection!: boolean;
inFunction!: boolean;
allowNullCheckOptimization!: boolean;
locals = new Map<string, number>();
permanentFunctionTypeCount = 0;
permanentFunctionTypes: { [name: string] : FunctionType } = {};
permanentFunctionTypesByShape: { [shape: string] : FunctionTypeIndex } = {};
permanentFunctionTypesByIndex: { [index: number] : FunctionTypeByIndex } = {};
functionTypeCount!: number;
functionTypes!: { [name: string] : FunctionType };
functionTypesByShape!: { [shape: string] : FunctionTypeIndex };
functionTypesByIndex: { [index: number] : FunctionTypeByIndex } = {};
permanentImportedFunctionCount = 0;
permanentImportedFunctions: { [name: string] : ImportedFunctionInfo } = {};
importedFunctionCount!: number;
importedFunctions!: { [name: string] : ImportedFunctionInfo };
nextImportIndex = 0;
functions: Array<FunctionInfo> = [];
estimatedExportBytes = 0;
argumentCount!: number;
activeBlocks!: number;
base!: MintOpcodePtr;
traceBuf: Array<string> = [];
branchTargets = new Set<MintOpcodePtr>();
options!: JiterpreterOptions;
constantSlots: Array<number> = [];
backBranchOffsets: Array<MintOpcodePtr> = [];
nextConstantSlot = 0;
compressImportNames = false;
constructor (constantSlotCount: number) {
this.stack = [new BlobBuilder()];
this.clear(constantSlotCount);
this.cfg = new Cfg(this);
}
clear (constantSlotCount: number) {
this.options = getOptions();
this.stackSize = 1;
this.inSection = false;
this.inFunction = false;
this.locals.clear();
this.functionTypeCount = this.permanentFunctionTypeCount;
this.functionTypes = Object.create(this.permanentFunctionTypes);
this.functionTypesByShape = Object.create(this.permanentFunctionTypesByShape);
this.functionTypesByIndex = Object.create(this.permanentFunctionTypesByIndex);
this.nextImportIndex = 0;
this.importedFunctionCount = this.permanentImportedFunctionCount;
this.importedFunctions = Object.create(this.permanentImportedFunctions);
for (const k in this.importedFunctions) {
const f = this.importedFunctions[k];
if (!f.assumeUsed)
f.index = undefined;
}
this.functions.length = 0;
this.estimatedExportBytes = 0;
this.argumentCount = 0;
this.current.clear();
this.traceBuf.length = 0;
this.branchTargets.clear();
this.activeBlocks = 0;
this.nextConstantSlot = 0;
this.constantSlots.length = this.options.useConstants ? constantSlotCount : 0;
for (let i = 0; i < this.constantSlots.length; i++)
this.constantSlots[i] = 0;
this.backBranchOffsets.length = 0;
this.allowNullCheckOptimization = this.options.eliminateNullChecks;
}
_push () {
this.stackSize++;
if (this.stackSize >= this.stack.length)
this.stack.push(new BlobBuilder());
this.current.clear();
}
_pop (writeToOutput: boolean) {
if (this.stackSize <= 1)
throw new Error("Stack empty");
const current = this.current;
this.stackSize--;
if (writeToOutput) {
this.appendULeb(current.size);
current.copyTo(this.current);
return null;
} else
return current.getArrayView(false).slice(0, current.size);
}
// HACK: Approximate amount of space we need to generate the full module at present
// FIXME: This does not take into account any other functions already generated if they weren't
// emitted into the module immediately
get bytesGeneratedSoFar () {
return this.stack[0].size +
// HACK: A random constant for section headers and padding
32 +
// mod (2 bytes) name (2-3 bytes) type (1 byte) typeidx (1-2 bytes)
(this.importedFunctionCount * 8) +
// type index for each function
(this.functions.length * 2) +
// export entry for each export
this.estimatedExportBytes;
}
get current() {
return this.stack[this.stackSize - 1];
}
get size() {
return this.current.size;
}
appendU8 (value: number | WasmOpcode) {
if ((value != value >>> 0) || (value > 255))
throw new Error(`Byte out of range: ${value}`);
return this.current.appendU8(value);
}
appendU32 (value: number) {
return this.current.appendU32(value);
}
appendF32 (value: number) {
return this.current.appendF32(value);
}
appendF64 (value: number) {
return this.current.appendF64(value);
}
appendBoundaryValue (bits: number, sign: number) {
return this.current.appendBoundaryValue(bits, sign);
}
appendULeb (value: number | MintOpcodePtr) {
return this.current.appendULeb(<any>value);
}
appendLeb (value: number) {
return this.current.appendLeb(value);
}
appendLebRef (sourceAddress: VoidPtr, signed: boolean) {
return this.current.appendLebRef(sourceAddress, signed);
}
appendBytes (bytes: Uint8Array) {
return this.current.appendBytes(bytes);
}
appendName (text: string) {
return this.current.appendName(text);
}
ret (ip: MintOpcodePtr) {
this.ip_const(ip);
this.appendU8(WasmOpcode.return_);
}
i32_const (value: number | ManagedPointer | NativePointer) {
this.appendU8(WasmOpcode.i32_const);
this.appendLeb(<any>value);
}
ptr_const (pointer: number | ManagedPointer | NativePointer) {
let idx = this.options.useConstants ? this.constantSlots.indexOf(<any>pointer) : -1;
if (
this.options.useConstants &&
(idx < 0) && (this.nextConstantSlot < this.constantSlots.length)
) {
idx = this.nextConstantSlot++;
this.constantSlots[idx] = <any>pointer;
}
if (idx >= 0) {
this.appendU8(WasmOpcode.get_global);
this.appendLeb(idx);
} else {
// console.log(`Warning: no constant slot for ${pointer} (${this.nextConstantSlot} slots used)`);
this.i32_const(pointer);
}
}
ip_const (value: MintOpcodePtr) {
this.appendU8(WasmOpcode.i32_const);
this.appendLeb(<any>value - <any>this.base);
}
i52_const (value: number) {
this.appendU8(WasmOpcode.i64_const);
this.appendLeb(value);
}
defineType (
name: string, parameters: { [name: string]: WasmValtype }, returnType: WasmValtype,
permanent: boolean
) {
if (this.functionTypes[name])
throw new Error(`Function type ${name} already defined`);
if (permanent && (this.functionTypeCount > this.permanentFunctionTypeCount))
throw new Error("New permanent function types cannot be defined after non-permanent ones");
let shape = "";
for (const k in parameters)
shape += parameters[k] + ",";
shape += returnType;
let index = this.functionTypesByShape[shape];
if (typeof (index) !== "number") {
index = this.functionTypeCount++;
if (permanent) {
this.permanentFunctionTypeCount++;
this.permanentFunctionTypesByShape[shape] = index;
this.permanentFunctionTypesByIndex[index] = [
parameters,
Object.values(parameters).length,
returnType
];
} else {
this.functionTypesByShape[shape] = index;
this.functionTypesByIndex[index] = [
parameters,
Object.values(parameters).length,
returnType
];
}
}
const tup : FunctionType = [
index, parameters, returnType,
`(${JSON.stringify(parameters)}) -> ${returnType}`, permanent
];
if (permanent)
this.permanentFunctionTypes[name] = tup;
else
this.functionTypes[name] = tup;
return index;
}
generateTypeSection () {
this.beginSection(1);
this.appendULeb(this.functionTypeCount);
/*
if (trace > 1)
console.log(`Generated ${this.functionTypeCount} wasm type(s) from ${Object.keys(this.functionTypes).length} named function types`);
*/
for (let i = 0; i < this.functionTypeCount; i++) {
const parameters = this.functionTypesByIndex[i][0],
parameterCount = this.functionTypesByIndex[i][1],
returnType = this.functionTypesByIndex[i][2];
this.appendU8(0x60);
// Parameters
this.appendULeb(parameterCount);
for (const k in parameters)
this.appendU8(parameters[k]);
// Return type(s)
if (returnType !== WasmValtype.void) {
this.appendULeb(1);
this.appendU8(returnType);
} else
this.appendULeb(0);
}
this.endSection();
}
getImportedFunctionTable () : any {
const imports : any = {};
for (const k in this.importedFunctions) {
const f = this.importedFunctions[k];
const name = this.getCompressedName(f);
imports[name] = f.func;
}
return imports;
}
getCompressedName (ifi: ImportedFunctionInfo) {
if (!this.compressImportNames || typeof(ifi.index) !== "number")
return ifi.name;
let result = compressedNameCache[ifi.index!];
if (typeof (result) !== "string")
compressedNameCache[ifi.index!] = result = ifi.index!.toString(shortNameBase);
return result;
}
_generateImportSection () {
const importsToEmit = [];
for (const k in this.importedFunctions) {
const f = this.importedFunctions[k];
if (f.index !== undefined)
importsToEmit.push(f);
}
importsToEmit.sort((lhs, rhs) => lhs.index! - rhs.index!);
// Import section
this.beginSection(2);
this.appendULeb(1 + importsToEmit.length + this.constantSlots.length);
// console.log(`referenced ${importsToEmit.length}/${allImports.length} import(s)`);
for (let i = 0; i < importsToEmit.length; i++) {
const ifi = importsToEmit[i];
// console.log(` #${ifi.index} ${ifi.module}.${ifi.name} = ${ifi.friendlyName}`);
this.appendName(ifi.module);
this.appendName(this.getCompressedName(ifi));
this.appendU8(0x0); // function
this.appendU8(ifi.typeIndex);
}
for (let i = 0; i < this.constantSlots.length; i++) {
this.appendName("c");
this.appendName(i.toString(shortNameBase));
this.appendU8(0x03); // global
this.appendU8(WasmValtype.i32); // all constants are pointers right now
this.appendU8(0x00); // constant
}
this.appendName("m");
this.appendName("h");
// memtype (limits = { min=0x01, max=infinity })
this.appendU8(0x02);
this.appendU8(0x00);
// Minimum size is in 64k pages, not bytes
this.appendULeb(0x01);
}
defineImportedFunction (
module: string, name: string, functionTypeName: string,
assumeUsed: boolean, permanent: boolean, func: Function | number
) : ImportedFunctionInfo {
if (permanent && (this.importedFunctionCount > this.permanentImportedFunctionCount))
throw new Error("New permanent imports cannot be defined after non-permanent ones");
const type = this.functionTypes[functionTypeName];
if (!type)
throw new Error("No function type named " + functionTypeName);
if (permanent && !type[4])
throw new Error("A permanent import must have a permanent function type");
const typeIndex = type[0];
const table = permanent ? this.permanentImportedFunctions : this.importedFunctions;
const index = assumeUsed
? (
permanent
? this.permanentImportedFunctionCount++
: this.importedFunctionCount++
)
: undefined;
if (typeof (func) === "number")
func = getWasmFunctionTable().get(func);
if (typeof (func) !== "function")
throw new Error(`Value passed for imported function ${name} was not a function or valid function pointer`);
const result = table[name] = {
index,
typeIndex,
module,
name,
assumeUsed,
func
};
return result;
}
defineFunction (
options: {
type: string,
name: string,
export: boolean,
locals: { [name: string]: WasmValtype },
}, generator: Function
) {
const rec : FunctionInfo = {
index: this.functions.length,
name: options.name,
typeName: options.type,
typeIndex: this.functionTypes[options.type][0],
export: options.export,
locals: options.locals,
generator,
error: null,
blob: null,
};
this.functions.push(rec);
if (rec.export)
this.estimatedExportBytes += rec.name.length + 8;
return rec;
}
emitImportsAndFunctions () {
let exportCount = 0;
for (let i = 0; i < this.functions.length; i++) {
const func = this.functions[i];
if (func.export)
exportCount++;
this.beginFunction(func.typeName, func.locals);
func.blob = func.generator();
if (!func.blob)
func.blob = this.endFunction(false);
}
this._generateImportSection();
// Function section
this.beginSection(3);
this.appendULeb(this.functions.length);
for (let i = 0; i < this.functions.length; i++)
this.appendULeb(this.functions[i].typeIndex);
// Export section
this.beginSection(7);
this.appendULeb(exportCount);
for (let i = 0; i < this.functions.length; i++) {
const func = this.functions[i];
if (!func.export)
continue;
// FIXME: This combined with the initial cost of decoding the function name is somewhat expensive
// It might be ideal to keep the original C name function pointer around and copy that directly into the buffer.
this.appendName(func.name);
this.appendU8(0); // func export
this.appendULeb(this.importedFunctionCount + i);
}
// Code section
this.beginSection(10);
this.appendULeb(this.functions.length);
for (let i = 0; i < this.functions.length; i++) {
const func = this.functions[i];
mono_assert(func.blob, () => `expected function ${func.name} to have a body`);
this.appendULeb(func.blob.length);
this.appendBytes(func.blob);
}
this.endSection();
}
callImport (name: string) {
const func = this.importedFunctions[name];
if (!func)
throw new Error("No imported function named " + name);
if (func.index === undefined)
func.index = this.importedFunctionCount++;
this.appendU8(WasmOpcode.call);
this.appendULeb(func.index);
}
beginSection (type: number) {
if (this.inSection)
this._pop(true);
this.appendU8(type);
this._push();
this.inSection = true;
}
endSection () {
if (!this.inSection)
throw new Error("Not in section");
if (this.inFunction)
this.endFunction(true);
this._pop(true);
this.inSection = false;
}
_assignParameterIndices = (parms: {[name: string] : WasmValtype}) => {
let result = 0;
for (const k in parms) {
this.locals.set(k, result);
// console.log(`parm ${k} -> ${result}`);
result++;
}
return result;
};
_assignLocalIndices (
counts: any, locals: {[name: string] : WasmValtype},
base: number, localGroupCount: number
) {
counts[WasmValtype.i32] = 0;
counts[WasmValtype.i64] = 0;
counts[WasmValtype.f32] = 0;
counts[WasmValtype.f64] = 0;
for (const k in locals) {
const ty = locals[k];
if (counts[ty] <= 0)
localGroupCount++;
counts[ty]++;
}
const offi32 = 0,
offi64 = counts[WasmValtype.i32],
offf32 = offi64 + counts[WasmValtype.i64],
offf64 = offf32 + counts[WasmValtype.f32];
counts[WasmValtype.i32] = 0;
counts[WasmValtype.i64] = 0;
counts[WasmValtype.f32] = 0;
counts[WasmValtype.f64] = 0;
for (const k in locals) {
const ty = locals[k];
let idx = 0;
switch (ty) {
case WasmValtype.i32:
idx = (counts[ty]++) + offi32 + base;
this.locals.set(k, idx);
break;
case WasmValtype.i64:
idx = (counts[ty]++) + offi64 + base;
this.locals.set(k, idx);
break;
case WasmValtype.f32:
idx = (counts[ty]++) + offf32 + base;
this.locals.set(k, idx);
break;
case WasmValtype.f64:
idx = (counts[ty]++) + offf64 + base;
this.locals.set(k, idx);
break;
}
// console.log(`local ${k} ${locals[k]} -> ${idx}`);
}
return localGroupCount;
}
beginFunction (
type: string,
locals?: {[name: string]: WasmValtype}
) {
if (this.inFunction)
throw new Error("Already in function");
this._push();
const signature = this.functionTypes[type];
this.locals.clear();
this.branchTargets.clear();
let counts: any = {};
const tk = [WasmValtype.i32, WasmValtype.i64, WasmValtype.f32, WasmValtype.f64];
// We first assign the parameters local indices and then
// we assign the named locals indices, because parameters
// come first in the local space. Imagine if parameters
// had their own opcode and weren't mutable??????
let localGroupCount = 0;
// Assign indices for the parameter list from the function signature
const localBaseIndex = this._assignParameterIndices(signature[1]);
if (locals)
// Now if we have any locals, assign indices for those
localGroupCount = this._assignLocalIndices(counts, locals, localBaseIndex, localGroupCount);
else
// Otherwise erase the counts table from the parameter assignment
counts = {};
// Write the number of types and then write a count for each type
this.appendULeb(localGroupCount);
for (let i = 0; i < tk.length; i++) {
const k = tk[i];
const c = counts[k];
if (!c)
continue;
// console.log(`${k} x${c}`);
this.appendULeb(c);
this.appendU8(<any>k);
}
this.inFunction = true;
}
endFunction (writeToOutput: boolean) {
if (!this.inFunction)
throw new Error("Not in function");
if (this.activeBlocks > 0)
throw new Error(`${this.activeBlocks} unclosed block(s) at end of function`);
const result = this._pop(writeToOutput);
this.inFunction = false;
return result;
}
block (type?: WasmValtype, opcode?: WasmOpcode) {
const result = this.appendU8(opcode || WasmOpcode.block);
if (type)
this.appendU8(type);
else
this.appendU8(WasmValtype.void);
this.activeBlocks++;
return result;
}
endBlock () {
if (this.activeBlocks <= 0)
throw new Error("No blocks active");
this.activeBlocks--;
this.appendU8(WasmOpcode.end);
}
arg (name: string | number, opcode?: WasmOpcode) {
const index = typeof(name) === "string"
? (this.locals.has(name) ? this.locals.get(name)! : undefined)
: name;
if (typeof (index) !== "number")
throw new Error("No local named " + name);
if (opcode)
this.appendU8(opcode);
this.appendULeb(index);
}
local (name: string | number, opcode?: WasmOpcode) {
const index = typeof(name) === "string"
? (this.locals.has(name) ? this.locals.get(name)! : undefined)
: name + this.argumentCount;
if (typeof (index) !== "number")
throw new Error("No local named " + name);
if (opcode)
this.appendU8(opcode);
else
this.appendU8(WasmOpcode.get_local);
this.appendULeb(index);
}
appendMemarg (offset: number, alignPower: number) {
this.appendULeb(alignPower);
this.appendULeb(offset);
}
/*
generates either (u32)get_local(ptr) + offset or (u32)ptr1 + offset
*/
lea (ptr1: string | number, offset: number) {
if (typeof (ptr1) === "string")
this.local(ptr1);
else
this.i32_const(ptr1);
this.i32_const(offset);
// FIXME: How do we make sure this has correct semantics for pointers over 2gb?
this.appendU8(WasmOpcode.i32_add);
}
getArrayView (fullCapacity?: boolean) {
if (this.stackSize > 1)
throw new Error("Jiterpreter block stack not empty");
return this.stack[0].getArrayView(fullCapacity);
}
getConstants () {
const result : { [key: string]: number } = {};
for (let i = 0; i < this.constantSlots.length; i++)
result[i.toString(shortNameBase)] = this.constantSlots[i];
return result;
}
}
export class BlobBuilder {
buffer: number;
size: number;
capacity: number;
encoder?: TextEncoder;
textBuf = new Uint8Array(1024);
constructor () {
this.capacity = 16 * 1024;
this.buffer = <any>Module._malloc(this.capacity);
Module.HEAPU8.fill(0, this.buffer, this.buffer + this.capacity);
this.size = 0;
this.clear();
if (typeof (TextEncoder) === "function")
this.encoder = new TextEncoder();
}
clear () {
this.size = 0;
}
appendU8 (value: number | WasmOpcode) {
if (this.size >= this.capacity)
throw new Error("Buffer full");
const result = this.size;
Module.HEAPU8[this.buffer + (this.size++)] = value;
return result;
}
appendU32 (value: number) {
const result = this.size;
cwraps.mono_jiterp_write_number_unaligned(<any>this.buffer + this.size, value, JiterpNumberMode.U32);
this.size += 4;
return result;
}
appendI32 (value: number) {
const result = this.size;
cwraps.mono_jiterp_write_number_unaligned(<any>this.buffer + this.size, value, JiterpNumberMode.I32);
this.size += 4;
return result;
}
appendF32 (value: number) {
const result = this.size;
cwraps.mono_jiterp_write_number_unaligned(<any>this.buffer + this.size, value, JiterpNumberMode.F32);
this.size += 4;
return result;
}
appendF64 (value: number) {
const result = this.size;
cwraps.mono_jiterp_write_number_unaligned(<any>this.buffer + this.size, value, JiterpNumberMode.F64);
this.size += 8;
return result;
}
appendBoundaryValue (bits: number, sign: number) {
if (this.size + 8 >= this.capacity)
throw new Error("Buffer full");
const bytesWritten = cwraps.mono_jiterp_encode_leb_signed_boundary(<any>(this.buffer + this.size), bits, sign);
if (bytesWritten < 1)
throw new Error(`Failed to encode ${bits} bit boundary value with sign ${sign}`);
this.size += bytesWritten;
return bytesWritten;
}
appendULeb (value: number) {
mono_assert(value >= 0, "cannot pass negative value to appendULeb");
if (value < 0x7F) {
if (this.size + 1 >= this.capacity)
throw new Error("Buffer full");
this.appendU8(value);
return 1;
}
if (this.size + 8 >= this.capacity)
throw new Error("Buffer full");
const bytesWritten = cwraps.mono_jiterp_encode_leb52(<any>(this.buffer + this.size), value, 0);
if (bytesWritten < 1)
throw new Error(`Failed to encode value '${value}' as unsigned leb`);
this.size += bytesWritten;
return bytesWritten;
}
appendLeb (value: number) {
if (this.size + 8 >= this.capacity)
throw new Error("Buffer full");
const bytesWritten = cwraps.mono_jiterp_encode_leb52(<any>(this.buffer + this.size), value, 1);
if (bytesWritten < 1)
throw new Error(`Failed to encode value '${value}' as signed leb`);
this.size += bytesWritten;
return bytesWritten;
}
appendLebRef (sourceAddress: VoidPtr, signed: boolean) {
if (this.size + 8 >= this.capacity)
throw new Error("Buffer full");
const bytesWritten = cwraps.mono_jiterp_encode_leb64_ref(<any>(this.buffer + this.size), sourceAddress, signed ? 1 : 0);
if (bytesWritten < 1)
throw new Error("Failed to encode value as leb");
this.size += bytesWritten;
return bytesWritten;
}
copyTo (destination: BlobBuilder, count?: number) {
if (typeof (count) !== "number")
count = this.size;
Module.HEAPU8.copyWithin(destination.buffer + destination.size, this.buffer, this.buffer + count);
destination.size += count;
}
appendBytes (bytes: Uint8Array, count?: number) {
const result = this.size;
if (bytes.buffer === Module.HEAPU8.buffer) {
if (typeof (count) !== "number")
count = bytes.length;
Module.HEAPU8.copyWithin(this.buffer + result, bytes.byteOffset, bytes.byteOffset + count);
this.size += count;
} else {
if (typeof (count) === "number")
bytes = new Uint8Array(bytes.buffer, bytes.byteOffset, count);
// FIXME: Find a way to avoid temporarily allocating a view for every appendBytes
// The problem is that if we cache it and the native heap grows, the view will become detached
const av = this.getArrayView(true);
av.set(bytes, this.size);
this.size += bytes.length;
}
return result;
}
appendName (text: string) {
let count = text.length;
// TextEncoder overhead is significant for short strings, and lots of our strings
// are single-character import names, so add a fast path for single characters
let singleChar = text.length === 1 ? text.charCodeAt(0) : -1;
if (singleChar > 0x7F)
singleChar = -1;
// Also don't bother running the encode path for empty strings
if (count && (singleChar < 0)) {
if (this.encoder) {
// The ideal would be to encodeInto directly into a heap buffer so we can copyWithin,
// or even encodeInto the destination. But that would require allocating a subarray
// every time we encode text, which is probably worse.
// This is somehow one of the most expensive parts of the compiler :(
const temp = this.encoder.encodeInto(text, this.textBuf);
count = temp.written || 0;
} else {
for (let i = 0; i < count; i++) {
const ch = text.charCodeAt(i);
if (ch > 0x7F)
throw new Error("Out of range character and no TextEncoder available");
else
this.textBuf[i] = ch;
}
}
}
this.appendULeb(count);
if (singleChar >= 0)
this.appendU8(singleChar);
else if (count > 1)
this.appendBytes(this.textBuf, count);
}
getArrayView (fullCapacity?: boolean) {
return new Uint8Array(Module.HEAPU8.buffer, this.buffer, fullCapacity ? this.capacity : this.size);
}
}
type CfgBlob = {
type: "blob";
ip: MintOpcodePtr;
start: number;
length: number;
}
type CfgBranchBlockHeader = {
type: "branch-block-header";
ip: MintOpcodePtr;
isBackBranchTarget: boolean;
}
type CfgBranch = {
type: "branch";
from: MintOpcodePtr;
target: MintOpcodePtr;
isBackward: boolean; // FIXME: This should be inferred automatically
isConditional: boolean;
}
type CfgSegment = CfgBlob | CfgBranchBlockHeader | CfgBranch;
class Cfg {
builder: WasmBuilder;
startOfBody!: MintOpcodePtr;
segments: Array<CfgSegment> = [];
backBranchTargets: Uint16Array | null = null;
base!: MintOpcodePtr;