/
jiterpreter-trace-generator.ts
3143 lines (2871 loc) · 140 KB
/
jiterpreter-trace-generator.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, MonoMethod } from "./types";
import { NativePointer } from "./types/emscripten";
import {
getU16, getI16,
getU32_unaligned, getI32_unaligned, getF32_unaligned, getF64_unaligned,
} from "./memory";
import { WasmOpcode } from "./jiterpreter-opcodes";
import { MintOpcode, OpcodeInfo } from "./mintops";
import cwraps from "./cwraps";
import {
MintOpcodePtr, WasmValtype, WasmBuilder,
append_memset_dest, append_bailout, append_exit,
append_memmove_dest_src, try_append_memset_fast,
try_append_memmove_fast, counters,
getMemberOffset, JiterpMember, BailoutReason,
} from "./jiterpreter-support";
import {
sizeOfDataItem,
disabledOpcodes, countCallTargets,
callTargetCounts, trapTraceErrors,
trace, traceOnError, traceOnRuntimeError,
emitPadding, traceBranchDisplacements,
traceEip, nullCheckValidation,
abortAtJittedLoopBodies, traceNullCheckOptimizations,
nullCheckCaching, traceBackBranches,
mostRecentOptions,
record_abort,
} from "./jiterpreter";
/*
struct MonoVTable {
MonoClass *klass; // 0
MonoGCDescriptor gc_descr; // 4
MonoDomain *domain; // 8
gpointer type; // 12
guint8 *interface_bitmap; // 16
guint32 max_interface_id; // 20
guint8 rank; // 21
guint8 initialized; // 22
guint8 flags;
*/
/*
struct InterpFrame {
InterpFrame *parent; // 0
InterpMethod *imethod; // 4
stackval *retval; // 8
stackval *stack; // 12
InterpFrame *next_free; // 16
InterpState state; // 20
};
struct InterpMethod {
MonoMethod *method;
InterpMethod *next_jit_code_hash;
// Sort pointers ahead of integers to minimize padding for alignment.
unsigned short *code;
MonoPIFunc func;
MonoExceptionClause *clauses; // num_clauses
void **data_items;
*/
const enum JiterpSpecialOpcode {
CNE_UN_R4 = 0xFFFF + 0,
CGE_UN_R4 = 0xFFFF + 1,
CLE_UN_R4 = 0xFFFF + 2,
CNE_UN_R8 = 0xFFFF + 3,
CGE_UN_R8 = 0xFFFF + 4,
CLE_UN_R8 = 0xFFFF + 5,
}
// indexPlusOne so that ip[1] in the interpreter becomes getArgU16(ip, 1)
function getArgU16 (ip: MintOpcodePtr, indexPlusOne: number) {
return getU16(<any>ip + (2 * indexPlusOne));
}
function getArgI16 (ip: MintOpcodePtr, indexPlusOne: number) {
return getI16(<any>ip + (2 * indexPlusOne));
}
function getArgI32 (ip: MintOpcodePtr, indexPlusOne: number) {
const src = <any>ip + (2 * indexPlusOne);
return getI32_unaligned(src);
}
function getArgU32 (ip: MintOpcodePtr, indexPlusOne: number) {
const src = <any>ip + (2 * indexPlusOne);
return getU32_unaligned(src);
}
function getArgF32 (ip: MintOpcodePtr, indexPlusOne: number) {
const src = <any>ip + (2 * indexPlusOne);
return getF32_unaligned(src);
}
function getArgF64 (ip: MintOpcodePtr, indexPlusOne: number) {
const src = <any>ip + (2 * indexPlusOne);
return getF64_unaligned(src);
}
function get_imethod_data (frame: NativePointer, index: number) {
// FIXME: Encoding this data directly into the trace will prevent trace reuse
const iMethod = getU32_unaligned(<any>frame + getMemberOffset(JiterpMember.Imethod));
const pData = getU32_unaligned(iMethod + getMemberOffset(JiterpMember.DataItems));
const dataOffset = pData + (index * sizeOfDataItem);
return getU32_unaligned(dataOffset);
}
function get_imethod_clause_data_offset (frame: NativePointer, index: number) {
// FIXME: Encoding this data directly into the trace will prevent trace reuse
const iMethod = getU32_unaligned(<any>frame + getMemberOffset(JiterpMember.Imethod));
const pData = getU32_unaligned(iMethod + getMemberOffset(JiterpMember.ClauseDataOffsets));
const dataOffset = pData + (index * sizeOfDataItem);
return getU32_unaligned(dataOffset);
}
function is_backward_branch_target (
ip: MintOpcodePtr, startOfBody: MintOpcodePtr,
backwardBranchTable: Uint16Array | null
) {
if (!backwardBranchTable)
return false;
for (let i = 0; i < backwardBranchTable.length; i++) {
const actualOffset = (backwardBranchTable[i] * 2) + <any>startOfBody;
if (actualOffset === ip)
return true;
}
return false;
}
export function generate_wasm_body (
frame: NativePointer, traceName: string, ip: MintOpcodePtr,
startOfBody: MintOpcodePtr, endOfBody: MintOpcodePtr,
builder: WasmBuilder, instrumentedTraceId: number,
backwardBranchTable: Uint16Array | null
) : number {
const abort = <MintOpcodePtr><any>0;
let isFirstInstruction = true, isConditionallyExecuted = false,
firstOpcodeInBlock = true;
let result = 0,
prologueOpcodeCounter = 0,
conditionalOpcodeCounter = 0;
const traceIp = ip;
addressTakenLocals.clear();
eraseInferredState();
// Skip over the enter opcode
ip += <any>(OpcodeInfo[MintOpcode.MINT_TIER_ENTER_JITERPRETER][1] * 2);
let rip = ip;
builder.cfg.entry(ip);
while (ip) {
builder.cfg.ip = ip;
if (ip >= endOfBody) {
record_abort(traceIp, ip, traceName, "end-of-body");
if (instrumentedTraceId)
console.log(`instrumented trace ${traceName} exited at end of body @${(<any>ip).toString(16)}`);
break;
}
// HACK: Browsers set a limit of 4KB, we lower it slightly since a single opcode
// might generate a ton of code and we generate a bit of an epilogue after
// we finish
const maxBytesGenerated = 3840,
spaceLeft = maxBytesGenerated - builder.bytesGeneratedSoFar - builder.cfg.overheadBytes;
if (builder.size >= spaceLeft) {
// console.log(`trace too big, estimated size is ${builder.size + builder.bytesGeneratedSoFar}`);
record_abort(traceIp, ip, traceName, "trace-too-big");
if (instrumentedTraceId)
console.log(`instrumented trace ${traceName} exited because of size limit at @${(<any>ip).toString(16)} (spaceLeft=${spaceLeft}b)`);
break;
}
if (instrumentedTraceId && traceEip) {
builder.i32_const(instrumentedTraceId);
builder.ip_const(ip);
builder.callImport("trace_eip");
}
let opcode = getU16(ip);
const info = OpcodeInfo[opcode];
mono_assert(info, () => `invalid opcode ${opcode}`);
const opname = info[0];
const _ip = ip;
const isBackBranchTarget = builder.options.noExitBackwardBranches &&
is_backward_branch_target(ip, startOfBody, backwardBranchTable),
isForwardBranchTarget = builder.branchTargets.has(ip),
startBranchBlock = isBackBranchTarget || isForwardBranchTarget ||
// If a method contains backward branches, we also need to check eip at the first insn
// because a backward branch might target a point in the middle of the trace
(isFirstInstruction && backwardBranchTable),
// We want to approximate the number of unconditionally executed instructions along with
// the ones that were probably conditionally executed by the time we reached the exit point
// We don't know the exact path that would have taken us to a given point, but it's a reasonable
// guess that methods dense with branches are more likely to take a complex path to reach
// a given exit
exitOpcodeCounter = conditionalOpcodeCounter + prologueOpcodeCounter +
builder.branchTargets.size;
let isLowValueOpcode = false,
skipDregInvalidation = false;
// We record the offset of each backward branch we encounter, so that later branch
// opcodes know that it's available by branching to the top of the dispatch loop
if (isBackBranchTarget) {
if (traceBackBranches > 1)
console.log(`${traceName} recording back branch target 0x${(<any>ip).toString(16)}`);
builder.backBranchOffsets.push(ip);
}
if (startBranchBlock) {
// If execution runs past the end of the current branch block, ensure
// that the instruction pointer is updated appropriately. This will
// also guarantee that the branch target block's comparison will
// succeed so that execution continues.
// We make sure above that this isn't done for the start of the trace,
// otherwise loops will run forever and never terminate since after
// branching to the top of the loop we would blow away eip
append_branch_target_block(builder, ip, isBackBranchTarget);
isConditionallyExecuted = true;
firstOpcodeInBlock = true;
eraseInferredState();
// Monitoring wants an opcode count that is a measurement of how many opcodes
// we definitely executed, so we want to ignore any opcodes that might
// have been skipped due to forward branching. This gives us an approximation
// of that by only counting how far we are from the most recent branch target
conditionalOpcodeCounter = 0;
}
isFirstInstruction = false;
if (disabledOpcodes.indexOf(opcode) >= 0) {
append_bailout(builder, ip, BailoutReason.Debugging);
opcode = MintOpcode.MINT_NOP;
// Intentionally leave the correct info in place so we skip the right number of bytes
}
switch (opcode) {
case MintOpcode.MINT_INITLOCAL:
case MintOpcode.MINT_INITLOCALS: {
// FIXME: We should move the first entry point after initlocals if it exists
const startOffsetInBytes = getArgU16(ip, 1),
sizeInBytes = getArgU16(ip, 2);
append_memset_local(builder, startOffsetInBytes, 0, sizeInBytes);
break;
}
case MintOpcode.MINT_LOCALLOC: {
// dest
append_ldloca(builder, getArgU16(ip, 1));
// len
append_ldloc(builder, getArgU16(ip, 2), WasmOpcode.i32_load);
// frame
builder.local("frame");
builder.callImport("localloc");
break;
}
case MintOpcode.MINT_INITOBJ: {
append_ldloc(builder, getArgU16(ip, 1), WasmOpcode.i32_load);
append_memset_dest(builder, 0, getArgU16(ip, 2));
break;
}
case MintOpcode.MINT_CPBLK: {
// size (FIXME: uint32 not int32)
append_ldloc(builder, getArgU16(ip, 3), WasmOpcode.i32_load);
builder.local("math_rhs32", WasmOpcode.tee_local);
// if size is 0 then don't do anything
builder.block(WasmValtype.void, WasmOpcode.if_); // if #1
// stash dest then check for null
append_ldloc(builder, getArgU16(ip, 1), WasmOpcode.i32_load);
builder.local("temp_ptr", WasmOpcode.tee_local);
builder.appendU8(WasmOpcode.i32_eqz);
// stash src then check for null
append_ldloc(builder, getArgU16(ip, 2), WasmOpcode.i32_load);
builder.local("math_lhs32", WasmOpcode.tee_local);
builder.appendU8(WasmOpcode.i32_eqz);
// now we memmove if both dest and src are valid. The stack currently has
// the eqz result for each pointer so we can stash a bailout inside of an if
builder.appendU8(WasmOpcode.i32_or);
builder.block(WasmValtype.void, WasmOpcode.if_); // if #2
append_bailout(builder, ip, BailoutReason.NullCheck);
builder.endBlock(); // if #2
// We passed the null check so now prepare the stack
builder.local("temp_ptr");
builder.local("math_lhs32");
builder.local("math_rhs32");
// wasm memmove with stack layout dest, src, count
builder.appendU8(WasmOpcode.PREFIX_sat);
builder.appendU8(10);
builder.appendU8(0);
builder.appendU8(0);
builder.endBlock(); // if #1
break;
}
case MintOpcode.MINT_INITBLK: {
// FIXME: This will cause an erroneous bailout if dest and size are both 0
// but that really shouldn't ever happen, and it will only cause a slowdown
// dest
append_ldloc_cknull(builder, getArgU16(ip, 1), ip, true);
// value
append_ldloc(builder, getArgU16(ip, 2), WasmOpcode.i32_load);
// size (FIXME: uint32 not int32)
append_ldloc(builder, getArgU16(ip, 3), WasmOpcode.i32_load);
// spec: pop n, pop val, pop d, fill from d[0] to d[n] with value val
builder.appendU8(WasmOpcode.PREFIX_sat);
builder.appendU8(11);
builder.appendU8(0);
break;
}
// Other conditional branch types are handled by the relop table.
case MintOpcode.MINT_BRFALSE_I4_S:
case MintOpcode.MINT_BRTRUE_I4_S:
case MintOpcode.MINT_BRFALSE_I4_SP:
case MintOpcode.MINT_BRTRUE_I4_SP:
case MintOpcode.MINT_BRFALSE_I8_S:
case MintOpcode.MINT_BRTRUE_I8_S:
if (!emit_branch(builder, ip, frame, opcode))
ip = abort;
else
isConditionallyExecuted = true;
break;
case MintOpcode.MINT_LEAVE_S:
case MintOpcode.MINT_BR_S:
case MintOpcode.MINT_CALL_HANDLER:
case MintOpcode.MINT_CALL_HANDLER_S:
if (!emit_branch(builder, ip, frame, opcode))
ip = abort;
else
// Technically incorrect, but the instructions following this one may not be executed
// since we might have skipped over them.
// FIXME: Identify when we should actually set the conditionally executed flag, perhaps
// by doing a simple static flow analysis based on the displacements. Update heuristic too!
isConditionallyExecuted = true;
break;
case MintOpcode.MINT_CKNULL: {
// if (locals[ip[2]]) locals[ip[1]] = locals[ip[2]] else throw
const src = getArgU16(ip, 2),
dest = getArgU16(ip, 1);
// locals[n] = cknull(locals[n]) is a common pattern, and we don't
// need to do the write for it since it can't change the value
if (src !== dest) {
builder.local("pLocals");
append_ldloc_cknull(builder, src, ip, true);
append_stloc_tail(builder, dest, WasmOpcode.i32_store);
} else {
append_ldloc_cknull(builder, src, ip, false);
}
// We will have bailed out if the object was null
if (builder.allowNullCheckOptimization) {
if (traceNullCheckOptimizations)
console.log(`(0x${(<any>ip).toString(16)}) locals[${dest}] passed cknull`);
notNullSince.set(dest, <any>ip);
}
skipDregInvalidation = true;
break;
}
case MintOpcode.MINT_TIER_ENTER_METHOD:
case MintOpcode.MINT_TIER_PATCHPOINT: {
// We need to make sure to notify the interpreter about tiering opcodes
// so that tiering up will still happen
const iMethod = getU32_unaligned(<any>frame + getMemberOffset(JiterpMember.Imethod));
builder.ptr_const(iMethod);
// increase_entry_count will return 1 if we can continue, otherwise
// we need to bail out into the interpreter so it can perform tiering
builder.callImport("entry");
builder.block(WasmValtype.void, WasmOpcode.if_);
append_bailout(builder, ip, BailoutReason.InterpreterTiering);
builder.endBlock();
break;
}
case MintOpcode.MINT_TIER_ENTER_JITERPRETER:
isLowValueOpcode = true;
// If we hit an enter opcode and we're not currently in a branch block
// or the enter opcode is the first opcode in a branch block, this likely
// indicates that we've reached a loop body that was already jitted before
// we were, and we should stop our trace here.
// Most loops have a prologue before them and having the loop body inside
// the prologue trace is not going to especially boost throughput, while it
// will make the prologue trace bigger (and thus slower to compile.)
// We don't want to abort before our trace is long enough though, since that
// will result in decent trace candidates becoming nops which adds overhead
// and leaves us in the interp.
if (
abortAtJittedLoopBodies &&
(result >= builder.options.minimumTraceLength) &&
// This is an unproductive heuristic if backward branches are on
!builder.options.noExitBackwardBranches
) {
if (!isConditionallyExecuted || firstOpcodeInBlock) {
// Use mono_jiterp_trace_transfer to call the target trace recursively
// Ideally we would import the trace function to do a direct call instead
// of an indirect one, but right now the import section is generated
// before we generate the function body, so it would be non-trivial to
// do this. It's still faster than returning to the interpreter main loop
const targetTrace = getArgU32(ip, 1);
builder.ip_const(ip);
builder.i32_const(targetTrace);
builder.local("frame");
builder.local("pLocals");
builder.local("cinfo");
builder.callImport("transfer");
builder.appendU8(WasmOpcode.return_);
ip = abort;
}
}
break;
case MintOpcode.MINT_TIER_MONITOR_JITERPRETER:
case MintOpcode.MINT_TIER_PREPARE_JITERPRETER:
case MintOpcode.MINT_TIER_NOP_JITERPRETER: // FIXME: Should we abort for NOPs like ENTERs?
case MintOpcode.MINT_NOP:
case MintOpcode.MINT_DEF:
case MintOpcode.MINT_DUMMY_USE:
case MintOpcode.MINT_IL_SEQ_POINT:
case MintOpcode.MINT_TIER_PATCHPOINT_DATA:
case MintOpcode.MINT_MONO_MEMORY_BARRIER:
case MintOpcode.MINT_SDB_BREAKPOINT:
case MintOpcode.MINT_SDB_INTR_LOC:
case MintOpcode.MINT_SDB_SEQ_POINT:
isLowValueOpcode = true;
break;
case MintOpcode.MINT_SAFEPOINT:
append_safepoint(builder, ip);
break;
case MintOpcode.MINT_LDLOCA_S:
// Pre-load locals for the store op
builder.local("pLocals");
// locals[ip[1]] = &locals[ip[2]]
append_ldloca(builder, getArgU16(ip, 2));
append_stloc_tail(builder, getArgU16(ip, 1), WasmOpcode.i32_store);
break;
case MintOpcode.MINT_LDSTR:
case MintOpcode.MINT_LDFTN:
case MintOpcode.MINT_LDFTN_ADDR:
case MintOpcode.MINT_LDPTR: {
// Pre-load locals for the store op
builder.local("pLocals");
// frame->imethod->data_items [ip [2]]
let data = get_imethod_data(frame, getArgU16(ip, 2));
if (opcode === MintOpcode.MINT_LDFTN)
data = <any>cwraps.mono_jiterp_imethod_to_ftnptr(<any>data);
builder.ptr_const(data);
append_stloc_tail(builder, getArgU16(ip, 1), WasmOpcode.i32_store);
break;
}
case MintOpcode.MINT_CPOBJ_VT: {
const klass = get_imethod_data(frame, getArgU16(ip, 3));
append_ldloc(builder, getArgU16(ip, 1), WasmOpcode.i32_load);
append_ldloc(builder, getArgU16(ip, 2), WasmOpcode.i32_load);
builder.ptr_const(klass);
builder.callImport("value_copy");
break;
}
case MintOpcode.MINT_CPOBJ_VT_NOREF: {
const sizeBytes = getArgU16(ip, 3);
append_ldloc(builder, getArgU16(ip, 1), WasmOpcode.i32_load);
append_ldloc(builder, getArgU16(ip, 2), WasmOpcode.i32_load);
append_memmove_dest_src(builder, sizeBytes);
break;
}
case MintOpcode.MINT_LDOBJ_VT: {
const size = getArgU16(ip, 3);
append_ldloca(builder, getArgU16(ip, 1), size, true);
append_ldloc_cknull(builder, getArgU16(ip, 2), ip, true);
append_memmove_dest_src(builder, size);
break;
}
case MintOpcode.MINT_STOBJ_VT: {
const klass = get_imethod_data(frame, getArgU16(ip, 3));
append_ldloc(builder, getArgU16(ip, 1), WasmOpcode.i32_load);
append_ldloca(builder, getArgU16(ip, 2), 0, true);
builder.ptr_const(klass);
builder.callImport("value_copy");
break;
}
case MintOpcode.MINT_STOBJ_VT_NOREF: {
const sizeBytes = getArgU16(ip, 3);
append_ldloc(builder, getArgU16(ip, 1), WasmOpcode.i32_load);
append_ldloca(builder, getArgU16(ip, 2), 0, true);
append_memmove_dest_src(builder, sizeBytes);
break;
}
case MintOpcode.MINT_STRLEN: {
builder.local("pLocals");
append_ldloc_cknull(builder, getArgU16(ip, 2), ip, true);
builder.appendU8(WasmOpcode.i32_load);
builder.appendMemarg(getMemberOffset(JiterpMember.StringLength), 2);
append_stloc_tail(builder, getArgU16(ip, 1), WasmOpcode.i32_store);
break;
}
case MintOpcode.MINT_GETCHR: {
builder.block();
// index
append_ldloc(builder, getArgU16(ip, 3), WasmOpcode.i32_load);
// stash it, we'll be using it multiple times
builder.local("math_lhs32", WasmOpcode.tee_local);
// str
append_ldloc_cknull(builder, getArgU16(ip, 2), ip, true);
// get string length
builder.appendU8(WasmOpcode.i32_load);
builder.appendMemarg(getMemberOffset(JiterpMember.StringLength), 2);
// index < length
builder.appendU8(WasmOpcode.i32_lt_s);
// index >= 0
builder.local("math_lhs32");
builder.i32_const(0);
builder.appendU8(WasmOpcode.i32_ge_s);
// (index >= 0) && (index < length)
builder.appendU8(WasmOpcode.i32_and);
// If either of the index checks failed we will fall through to the bailout
builder.appendU8(WasmOpcode.br_if);
builder.appendULeb(0);
append_bailout(builder, ip, BailoutReason.StringOperationFailed);
builder.endBlock();
// The null check and range check both passed so we can load the character now
// Pre-load destination for the stloc at the end (we can't do this inside the block above)
builder.local("pLocals");
// (index * 2) + offsetof(MonoString, chars) + pString
builder.local("math_lhs32");
builder.i32_const(2);
builder.appendU8(WasmOpcode.i32_mul);
builder.local("cknull_ptr");
builder.appendU8(WasmOpcode.i32_add);
// Load char
builder.appendU8(WasmOpcode.i32_load16_u);
builder.appendMemarg(getMemberOffset(JiterpMember.StringData), 1);
// Store into result
append_stloc_tail(builder, getArgU16(ip, 1), WasmOpcode.i32_store);
break;
}
case MintOpcode.MINT_GETITEM_SPAN:
case MintOpcode.MINT_GETITEM_LOCALSPAN: {
const elementSize = getArgI16(ip, 4);
builder.block();
// Load index and stash it in lhs32
append_ldloc(builder, getArgU16(ip, 3), WasmOpcode.i32_load);
builder.local("math_lhs32", WasmOpcode.tee_local);
// Load address of the span structure
if (opcode === MintOpcode.MINT_GETITEM_SPAN) {
// span = *(MonoSpanOfVoid *)locals[2]
append_ldloc_cknull(builder, getArgU16(ip, 2), ip, true);
} else {
// span = (MonoSpanOfVoid)locals[2]
append_ldloca(builder, getArgU16(ip, 2), 0);
builder.local("cknull_ptr", WasmOpcode.tee_local);
cknullOffset = -1;
}
// length = span->length
builder.appendU8(WasmOpcode.i32_load);
builder.appendMemarg(getMemberOffset(JiterpMember.SpanLength), 2);
// index < length
builder.appendU8(WasmOpcode.i32_lt_u);
// index >= 0
// FIXME: It would be nice to optimize this down to a single (index < length) comparison
// but interp.c doesn't do it - presumably because a span could be bigger than 2gb?
builder.local("math_lhs32");
builder.i32_const(0);
builder.appendU8(WasmOpcode.i32_ge_s);
// (index >= 0) && (index < length)
builder.appendU8(WasmOpcode.i32_and);
builder.appendU8(WasmOpcode.br_if);
builder.appendULeb(0);
append_bailout(builder, ip, BailoutReason.SpanOperationFailed);
builder.endBlock();
// We successfully null checked and bounds checked. Now compute
// the address and store it to the destination
builder.local("pLocals");
// src = span->_reference + (index * element_size);
builder.local("cknull_ptr");
builder.appendU8(WasmOpcode.i32_load);
builder.appendMemarg(getMemberOffset(JiterpMember.SpanData), 2);
builder.local("math_lhs32");
builder.i32_const(elementSize);
builder.appendU8(WasmOpcode.i32_mul);
builder.appendU8(WasmOpcode.i32_add);
append_stloc_tail(builder, getArgU16(ip, 1), WasmOpcode.i32_store);
break;
}
case MintOpcode.MINT_INTRINS_SPAN_CTOR: {
// if (len < 0) bailout
builder.block();
// int len = LOCAL_VAR (ip [3], gint32);
append_ldloc(builder, getArgU16(ip, 3), WasmOpcode.i32_load);
builder.local("math_rhs32", WasmOpcode.tee_local);
builder.i32_const(0);
builder.appendU8(WasmOpcode.i32_ge_s);
builder.appendU8(WasmOpcode.br_if);
builder.appendULeb(0);
append_bailout(builder, ip, BailoutReason.SpanOperationFailed);
builder.endBlock();
// gpointer span = locals + ip [1];
append_ldloca(builder, getArgU16(ip, 1), 16, true);
builder.local("math_lhs32", WasmOpcode.tee_local);
// *(gpointer*)span = ptr;
append_ldloc(builder, getArgU16(ip, 2), WasmOpcode.i32_load);
builder.appendU8(WasmOpcode.i32_store);
builder.appendMemarg(0, 0);
// *(gint32*)((gpointer*)span + 1) = len;
builder.local("math_lhs32");
builder.local("math_rhs32");
builder.appendU8(WasmOpcode.i32_store);
builder.appendMemarg(4, 0);
break;
}
case MintOpcode.MINT_LD_DELEGATE_METHOD_PTR: {
// FIXME: ldloca invalidation size
append_ldloca(builder, getArgU16(ip, 1), 8, true);
append_ldloca(builder, getArgU16(ip, 2), 8, true);
builder.callImport("ld_del_ptr");
break;
}
case MintOpcode.MINT_LDTSFLDA: {
append_ldloca(builder, getArgU16(ip, 1), 4, true);
// This value is unsigned but I32 is probably right
builder.ptr_const(getArgI32(ip, 2));
builder.callImport("ldtsflda");
break;
}
case MintOpcode.MINT_INTRINS_GET_TYPE:
builder.block();
// dest, src
append_ldloca(builder, getArgU16(ip, 1), 4, true);
append_ldloca(builder, getArgU16(ip, 2), 0);
builder.callImport("gettype");
// bailout if gettype failed
builder.appendU8(WasmOpcode.br_if);
builder.appendULeb(0);
append_bailout(builder, ip, BailoutReason.NullCheck);
builder.endBlock();
break;
case MintOpcode.MINT_INTRINS_ENUM_HASFLAG: {
const klass = get_imethod_data(frame, getArgU16(ip, 4));
builder.ptr_const(klass);
append_ldloca(builder, getArgU16(ip, 1), 4, true);
append_ldloca(builder, getArgU16(ip, 2), 0);
append_ldloca(builder, getArgU16(ip, 3), 0);
builder.callImport("hasflag");
break;
}
case MintOpcode.MINT_INTRINS_MEMORYMARSHAL_GETARRAYDATAREF: {
const offset = getMemberOffset(JiterpMember.ArrayData);
builder.local("pLocals");
append_ldloc_cknull(builder, getArgU16(ip, 2), ip, true);
builder.i32_const(offset);
builder.appendU8(WasmOpcode.i32_add);
append_stloc_tail(builder, getArgU16(ip, 1), WasmOpcode.i32_store);
break;
}
case MintOpcode.MINT_INTRINS_GET_HASHCODE:
builder.local("pLocals");
append_ldloca(builder, getArgU16(ip, 2), 0);
builder.callImport("hashcode");
append_stloc_tail(builder, getArgU16(ip, 1), WasmOpcode.i32_store);
break;
case MintOpcode.MINT_INTRINS_TRY_GET_HASHCODE:
builder.local("pLocals");
append_ldloca(builder, getArgU16(ip, 2), 0);
builder.callImport("try_hash");
append_stloc_tail(builder, getArgU16(ip, 1), WasmOpcode.i32_store);
break;
case MintOpcode.MINT_INTRINS_RUNTIMEHELPERS_OBJECT_HAS_COMPONENT_SIZE:
builder.local("pLocals");
append_ldloca(builder, getArgU16(ip, 2), 0);
builder.callImport("hascsize");
append_stloc_tail(builder, getArgU16(ip, 1), WasmOpcode.i32_store);
break;
case MintOpcode.MINT_INTRINS_ORDINAL_IGNORE_CASE_ASCII: {
builder.local("pLocals");
// valueA (cache in lhs32, we need it again later)
append_ldloc(builder, getArgU16(ip, 2), WasmOpcode.i32_load);
builder.local("math_lhs32", WasmOpcode.tee_local);
// valueB
append_ldloc(builder, getArgU16(ip, 3), WasmOpcode.i32_load);
// compute differentBits = (valueA ^ valueB) << 2
builder.appendU8(WasmOpcode.i32_xor);
builder.i32_const(2);
builder.appendU8(WasmOpcode.i32_shl);
builder.local("math_rhs32", WasmOpcode.set_local);
// compute indicator
builder.local("math_lhs32");
builder.i32_const(0x00050005);
builder.appendU8(WasmOpcode.i32_add);
builder.i32_const(0x00A000A0);
builder.appendU8(WasmOpcode.i32_or);
builder.i32_const(0x001A001A);
builder.appendU8(WasmOpcode.i32_add);
builder.i32_const(-8388737); // 0xFF7FFF7F == 4286578559U == -8388737
builder.appendU8(WasmOpcode.i32_or);
// result = (differentBits & indicator) == 0
builder.local("math_rhs32");
builder.appendU8(WasmOpcode.i32_and);
builder.appendU8(WasmOpcode.i32_eqz);
append_stloc_tail(builder, getArgU16(ip, 1), WasmOpcode.i32_store);
break;
}
case MintOpcode.MINT_ARRAY_RANK:
case MintOpcode.MINT_ARRAY_ELEMENT_SIZE: {
builder.block();
// dest, src
append_ldloca(builder, getArgU16(ip, 1), 4, true);
append_ldloca(builder, getArgU16(ip, 2), 0);
builder.callImport(opcode === MintOpcode.MINT_ARRAY_RANK ? "array_rank" : "a_elesize");
// If the array was null we will bail out, otherwise continue
builder.appendU8(WasmOpcode.br_if);
builder.appendULeb(0);
append_bailout(builder, ip, BailoutReason.NullCheck);
builder.endBlock();
break;
}
case MintOpcode.MINT_CASTCLASS:
case MintOpcode.MINT_ISINST:
case MintOpcode.MINT_CASTCLASS_COMMON:
case MintOpcode.MINT_ISINST_COMMON:
case MintOpcode.MINT_CASTCLASS_INTERFACE:
case MintOpcode.MINT_ISINST_INTERFACE: {
builder.block();
// dest, src
append_ldloca(builder, getArgU16(ip, 1), 4, true);
append_ldloca(builder, getArgU16(ip, 2), 0);
// klass
builder.ptr_const(get_imethod_data(frame, getArgU16(ip, 3)));
// opcode
builder.i32_const(opcode);
builder.callImport("cast");
// if cast operation succeeded, skip the bailout
builder.appendU8(WasmOpcode.br_if);
builder.appendULeb(0);
append_bailout(builder, ip, BailoutReason.CastFailed);
builder.endBlock();
break;
}
case MintOpcode.MINT_BOX:
case MintOpcode.MINT_BOX_VT: {
// MonoVTable *vtable = (MonoVTable*)frame->imethod->data_items [ip [3]];
builder.ptr_const(get_imethod_data(frame, getArgU16(ip, 3)));
// dest, src
append_ldloca(builder, getArgU16(ip, 1), 4, true);
append_ldloca(builder, getArgU16(ip, 2), 0);
builder.i32_const(opcode === MintOpcode.MINT_BOX_VT ? 1 : 0);
builder.callImport("box");
break;
}
case MintOpcode.MINT_UNBOX: {
builder.block();
// MonoClass *c = (MonoClass*)frame->imethod->data_items [ip [3]];
builder.ptr_const(get_imethod_data(frame, getArgU16(ip, 3)));
// dest, src
append_ldloca(builder, getArgU16(ip, 1), 4, true);
append_ldloca(builder, getArgU16(ip, 2), 0);
builder.callImport("try_unbox");
// If the unbox operation succeeded, continue, otherwise bailout
builder.appendU8(WasmOpcode.br_if);
builder.appendULeb(0);
append_bailout(builder, ip, BailoutReason.UnboxFailed);
builder.endBlock();
break;
}
case MintOpcode.MINT_NEWSTR: {
builder.block();
append_ldloca(builder, getArgU16(ip, 1), 4, true);
append_ldloc(builder, getArgU16(ip, 2), WasmOpcode.i32_load);
builder.callImport("newstr");
// If the newstr operation succeeded, continue, otherwise bailout
// Note that this assumes the newstr operation will fail again when the interpreter does it
// (the only reason for a newstr to fail I can think of is an out-of-memory condition)
builder.appendU8(WasmOpcode.br_if);
builder.appendULeb(0);
append_bailout(builder, ip, BailoutReason.AllocFailed);
builder.endBlock();
break;
}
case MintOpcode.MINT_NEWOBJ_INLINED: {
builder.block();
// MonoObject *o = mono_gc_alloc_obj (vtable, m_class_get_instance_size (vtable->klass));
append_ldloca(builder, getArgU16(ip, 1), 4, true);
builder.ptr_const(get_imethod_data(frame, getArgU16(ip, 2)));
// LOCAL_VAR (ip [1], MonoObject*) = o;
builder.callImport("newobj_i");
// If the newobj operation succeeded, continue, otherwise bailout
builder.appendU8(WasmOpcode.br_if);
builder.appendULeb(0);
append_bailout(builder, ip, BailoutReason.AllocFailed);
builder.endBlock();
break;
}
case MintOpcode.MINT_NEWOBJ_VT_INLINED: {
const ret_size = getArgU16(ip, 3);
// memset (this_vt, 0, ret_size);
append_ldloca(builder, getArgU16(ip, 2), ret_size, true);
append_memset_dest(builder, 0, ret_size);
// LOCAL_VAR (ip [1], gpointer) = this_vt;
builder.local("pLocals");
append_ldloca(builder, getArgU16(ip, 2), ret_size, true);
append_stloc_tail(builder, getArgU16(ip, 1), WasmOpcode.i32_store);
break;
}
case MintOpcode.MINT_NEWOBJ:
case MintOpcode.MINT_NEWOBJ_VT:
case MintOpcode.MINT_CALLVIRT_FAST:
case MintOpcode.MINT_CALL: {
if (countCallTargets) {
const targetImethod = get_imethod_data(frame, getArgU16(ip, 3));
const targetMethod = <MonoMethod><any>getU32_unaligned(targetImethod);
const count = callTargetCounts[<any>targetMethod];
if (typeof (count) === "number")
callTargetCounts[<any>targetMethod] = count + 1;
else
callTargetCounts[<any>targetMethod] = 1;
}
if (isConditionallyExecuted) {
// We generate a bailout instead of aborting, because we don't want calls
// to abort the entire trace if we have branch support enabled - the call
// might be infrequently hit and as a result it's worth it to keep going.
append_exit(builder, ip, exitOpcodeCounter, BailoutReason.Call);
isLowValueOpcode = true;
} else {
// We're in a block that executes unconditionally, and no branches have been
// executed before now so the trace will always need to bail out into the
// interpreter here. No point in compiling more.
ip = abort;
}
break;
}
// TODO: Verify that this isn't worse. I think these may only show up in wrappers?
// case MintOpcode.MINT_JIT_CALL:
case MintOpcode.MINT_CALLI:
case MintOpcode.MINT_CALLI_NAT:
case MintOpcode.MINT_CALLI_NAT_DYNAMIC:
case MintOpcode.MINT_CALLI_NAT_FAST:
case MintOpcode.MINT_CALL_DELEGATE:
// See comments for MINT_CALL
if (isConditionallyExecuted) {
append_exit(builder, ip, exitOpcodeCounter,
opcode == MintOpcode.MINT_CALL_DELEGATE
? BailoutReason.CallDelegate
: BailoutReason.Call
);
isLowValueOpcode = true;
} else {
ip = abort;
}
break;
// TODO: Verify that this isn't worse
case MintOpcode.MINT_ICALL_V_P:
case MintOpcode.MINT_ICALL_V_V:
case MintOpcode.MINT_ICALL_P_P:
case MintOpcode.MINT_ICALL_P_V:
case MintOpcode.MINT_ICALL_PP_V:
case MintOpcode.MINT_ICALL_PP_P:
// See comments for MINT_CALL
if (isConditionallyExecuted) {
append_bailout(builder, ip, BailoutReason.Icall);
isLowValueOpcode = true;
} else {
ip = abort;
}
break;
// Unlike regular rethrow which will only appear in catch blocks,
// MONO_RETHROW appears to show up in other places, so it's worth conditional bailout
case MintOpcode.MINT_MONO_RETHROW:
case MintOpcode.MINT_THROW:
// Not an exit, because throws are by definition unlikely
// We shouldn't make optimization decisions based on them.
append_bailout(builder, ip, BailoutReason.Throw);
isLowValueOpcode = true;
break;
case MintOpcode.MINT_ENDFINALLY:
// This one might make sense to partially implement, but the jump target
// is computed at runtime which would make it hard to figure out where
// we need to put branch targets. Not worth just doing a conditional
// bailout since finally blocks always run
ip = abort;
break;
case MintOpcode.MINT_RETHROW:
case MintOpcode.MINT_PROF_EXIT:
case MintOpcode.MINT_PROF_EXIT_VOID:
ip = abort;
break;
// Generating code for these is kind of complex due to the intersection of JS and int64,
// and it would bloat the implementation so we handle them all in C instead and match
// the interp implementation. Most of these are rare in runtime tests or browser bench
case MintOpcode.MINT_CONV_OVF_I4_I8:
case MintOpcode.MINT_CONV_OVF_U4_I8:
case MintOpcode.MINT_CONV_OVF_I4_U8:
case MintOpcode.MINT_CONV_OVF_I4_R8:
case MintOpcode.MINT_CONV_OVF_I8_R8:
case MintOpcode.MINT_CONV_OVF_I4_R4:
case MintOpcode.MINT_CONV_OVF_I8_R4:
case MintOpcode.MINT_CONV_OVF_U4_I4:
builder.block();
// dest, src
append_ldloca(builder, getArgU16(ip, 1), 8, true);
append_ldloca(builder, getArgU16(ip, 2), 0);
builder.i32_const(opcode);
builder.callImport("conv");
// If the conversion succeeded, continue, otherwise bailout
builder.appendU8(WasmOpcode.br_if);
builder.appendULeb(0);
append_bailout(builder, ip, BailoutReason.Overflow); // could be underflow but awkward to tell
builder.endBlock();
break;
/*
* The native conversion opcodes for these are not specified for nan/inf, and v8
* chooses to throw, so we have to do some tricks to identify non-finite values
* and substitute INTnn_MIN, like clang would.
* This attempts to reproduce what clang does in -O3 with no special flags set:
*
* f64 -> i64
*
* block
* local.get 0
* f64.abs
* f64.const 0x1p63
* f64.lt
* i32.eqz
* br_if 0 # 0: down to label0
* local.get 0
* i64.trunc_f64_s
* return
* end_block # label0:
* i64.const -9223372036854775808
*
* f32 -> i32
*
* block
* local.get 0
* f32.abs
* f32.const 0x1p31
* f32.lt
* i32.eqz
* br_if 0 # 0: down to label3
* local.get 0
* i32.trunc_f32_s
* return
* end_block # label3:
* i32.const -2147483648
*/
case MintOpcode.MINT_CONV_I4_R4:
case MintOpcode.MINT_CONV_I4_R8:
case MintOpcode.MINT_CONV_I8_R4:
case MintOpcode.MINT_CONV_I8_R8: {
const isF32 = (opcode === MintOpcode.MINT_CONV_I4_R4) ||
(opcode === MintOpcode.MINT_CONV_I8_R4),
isI64 = (opcode === MintOpcode.MINT_CONV_I8_R4) ||
(opcode === MintOpcode.MINT_CONV_I8_R8),
limit = isI64