This repository has been archived by the owner on Jan 24, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
impl_amd64.go
5885 lines (5073 loc) · 222 KB
/
impl_amd64.go
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
package compiler
// This file implements the compiler for amd64/x86_64 target.
// Please refer to https://www.felixcloutier.com/x86/index.html
// if unfamiliar with amd64 instructions used here.
import (
"fmt"
"math"
"github.com/wasilibs/wazerox/internal/asm"
"github.com/wasilibs/wazerox/internal/asm/amd64"
"github.com/wasilibs/wazerox/internal/platform"
"github.com/wasilibs/wazerox/internal/u32"
"github.com/wasilibs/wazerox/internal/u64"
"github.com/wasilibs/wazerox/internal/wasm"
"github.com/wasilibs/wazerox/internal/wazeroir"
)
var (
_minimum32BitSignedInt int32 = math.MinInt32
_maximum32BitSignedInt int32 = math.MaxInt32
_maximum32BitUnsignedInt uint32 = math.MaxUint32
_minimum64BitSignedInt int64 = math.MinInt64
_maximum64BitSignedInt int64 = math.MaxInt64
_maximum64BitUnsignedInt uint64 = math.MaxUint64
_float32SignBitMask uint32 = 1 << 31
_float32RestBitMask = ^_float32SignBitMask
_float64SignBitMask uint64 = 1 << 63
_float64RestBitMask = ^_float64SignBitMask
_float32ForMinimumSigned32bitInteger = uint32(0xCF00_0000)
_float64ForMinimumSigned32bitInteger = uint64(0xC1E0_0000_0020_0000)
_float32ForMinimumSigned64bitInteger = uint32(0xDF00_0000)
_float64ForMinimumSigned64bitInteger = uint64(0xC3E0_0000_0000_0000)
_float32ForMaximumSigned32bitIntPlusOne = uint32(0x4F00_0000)
_float64ForMaximumSigned32bitIntPlusOne = uint64(0x41E0_0000_0000_0000)
_float32ForMaximumSigned64bitIntPlusOne = uint32(0x5F00_0000)
_float64ForMaximumSigned64bitIntPlusOne = uint64(0x43E0_0000_0000_0000)
)
var (
// amd64ReservedRegisterForCallEngine: pointer to callEngine (i.e. *callEngine as uintptr)
amd64ReservedRegisterForCallEngine = amd64.RegR13
// amd64ReservedRegisterForStackBasePointerAddress: stack base pointer's address (callEngine.stackBasePointer) in the current function call.
amd64ReservedRegisterForStackBasePointerAddress = amd64.RegR14
// amd64ReservedRegisterForMemory: pointer to the memory slice's data (i.e. &memory.Buffer[0] as uintptr).
amd64ReservedRegisterForMemory = amd64.RegR15
)
var (
amd64UnreservedVectorRegisters = []asm.Register{ //nolint
amd64.RegX0, amd64.RegX1, amd64.RegX2, amd64.RegX3,
amd64.RegX4, amd64.RegX5, amd64.RegX6, amd64.RegX7,
amd64.RegX8, amd64.RegX9, amd64.RegX10, amd64.RegX11,
amd64.RegX12, amd64.RegX13, amd64.RegX14, amd64.RegX15,
}
// Note that we never invoke "call" instruction,
// so we don't need to care about the calling convention.
// TODO: Maybe it is safe just save rbp, rsp somewhere
// in Go-allocated variables, and reuse these registers
// in compiled functions and write them back before returns.
amd64UnreservedGeneralPurposeRegisters = []asm.Register{ //nolint
amd64.RegAX, amd64.RegCX, amd64.RegDX, amd64.RegBX,
amd64.RegSI, amd64.RegDI, amd64.RegR8, amd64.RegR9,
amd64.RegR10, amd64.RegR11, amd64.RegR12,
}
)
// amd64CallingConventionDestinationFunctionModuleInstanceAddressRegister holds *wasm.ModuleInstance of the
// next executing function instance. The value is set and used when making function calls
// or function returns in the ModuleContextInitialization. See compileModuleContextInitialization.
var amd64CallingConventionDestinationFunctionModuleInstanceAddressRegister = amd64.RegR12
func (c *amd64Compiler) String() string {
return c.locationStack.String()
}
// compileNOP implements compiler.compileNOP for the amd64 architecture.
func (c *amd64Compiler) compileNOP() asm.Node {
return c.assembler.CompileStandAlone(amd64.NOP)
}
type amd64Compiler struct {
assembler amd64.Assembler
ir *wazeroir.CompilationResult
cpuFeatures platform.CpuFeatureFlags
// locationStack holds the state of wazeroir virtual stack.
// and each item is either placed in register or the actual memory stack.
locationStack *runtimeValueLocationStack
// labels hold per wazeroir label specific information in this function.
labels [wazeroir.LabelKindNum][]amd64LabelInfo
// stackPointerCeil is the greatest stack pointer value (from runtimeValueLocationStack) seen during compilation.
stackPointerCeil uint64
// assignStackPointerCeilNeeded holds an asm.Node whose AssignDestinationConstant must be called with the determined stack pointer ceiling.
assignStackPointerCeilNeeded asm.Node
compiledTrapTargets [nativeCallStatusModuleClosed]asm.Node
withListener bool
typ *wasm.FunctionType
// locationStackForEntrypoint is the initial location stack for all functions. To reuse the allocated stack,
// we cache it here, and reset and set to .locationStack in the Init method.
locationStackForEntrypoint runtimeValueLocationStack
// frameIDMax tracks the maximum value of frame id per function.
frameIDMax int
brTableTmp []runtimeValueLocation
fourZeros,
eightZeros,
minimum32BitSignedInt,
maximum32BitSignedInt,
maximum32BitUnsignedInt,
minimum64BitSignedInt,
maximum64BitSignedInt,
maximum64BitUnsignedInt,
float32SignBitMask,
float32RestBitMask,
float64SignBitMask,
float64RestBitMask,
float32ForMinimumSigned32bitInteger,
float64ForMinimumSigned32bitInteger,
float32ForMinimumSigned64bitInteger,
float64ForMinimumSigned64bitInteger,
float32ForMaximumSigned32bitIntPlusOne,
float64ForMaximumSigned32bitIntPlusOne,
float32ForMaximumSigned64bitIntPlusOne,
float64ForMaximumSigned64bitIntPlusOne *asm.StaticConst
}
func newAmd64Compiler() compiler {
c := &amd64Compiler{
assembler: amd64.NewAssembler(),
locationStackForEntrypoint: newRuntimeValueLocationStack(),
cpuFeatures: platform.CpuFeatures,
}
c.fourZeros = asm.NewStaticConst([]byte{0, 0, 0, 0})
c.eightZeros = asm.NewStaticConst([]byte{0, 0, 0, 0, 0, 0, 0, 0})
c.minimum32BitSignedInt = asm.NewStaticConst(u32.LeBytes(uint32(_minimum32BitSignedInt)))
c.maximum32BitSignedInt = asm.NewStaticConst(u32.LeBytes(uint32(_maximum32BitSignedInt)))
c.maximum32BitUnsignedInt = asm.NewStaticConst(u32.LeBytes(_maximum32BitUnsignedInt))
c.minimum64BitSignedInt = asm.NewStaticConst(u64.LeBytes(uint64(_minimum64BitSignedInt)))
c.maximum64BitSignedInt = asm.NewStaticConst(u64.LeBytes(uint64(_maximum64BitSignedInt)))
c.maximum64BitUnsignedInt = asm.NewStaticConst(u64.LeBytes(_maximum64BitUnsignedInt))
c.float32SignBitMask = asm.NewStaticConst(u32.LeBytes(_float32SignBitMask))
c.float32RestBitMask = asm.NewStaticConst(u32.LeBytes(_float32RestBitMask))
c.float64SignBitMask = asm.NewStaticConst(u64.LeBytes(_float64SignBitMask))
c.float64RestBitMask = asm.NewStaticConst(u64.LeBytes(_float64RestBitMask))
c.float32ForMinimumSigned32bitInteger = asm.NewStaticConst(u32.LeBytes(_float32ForMinimumSigned32bitInteger))
c.float64ForMinimumSigned32bitInteger = asm.NewStaticConst(u64.LeBytes(_float64ForMinimumSigned32bitInteger))
c.float32ForMinimumSigned64bitInteger = asm.NewStaticConst(u32.LeBytes(_float32ForMinimumSigned64bitInteger))
c.float64ForMinimumSigned64bitInteger = asm.NewStaticConst(u64.LeBytes(_float64ForMinimumSigned64bitInteger))
c.float32ForMaximumSigned32bitIntPlusOne = asm.NewStaticConst(u32.LeBytes(_float32ForMaximumSigned32bitIntPlusOne))
c.float64ForMaximumSigned32bitIntPlusOne = asm.NewStaticConst(u64.LeBytes(_float64ForMaximumSigned32bitIntPlusOne))
c.float32ForMaximumSigned64bitIntPlusOne = asm.NewStaticConst(u32.LeBytes(_float32ForMaximumSigned64bitIntPlusOne))
c.float64ForMaximumSigned64bitIntPlusOne = asm.NewStaticConst(u64.LeBytes(_float64ForMaximumSigned64bitIntPlusOne))
return c
}
// Init implements compiler.Init.
func (c *amd64Compiler) Init(typ *wasm.FunctionType, ir *wazeroir.CompilationResult, withListener bool) {
c.assembler.Reset()
c.locationStackForEntrypoint.reset()
c.resetLabels()
*c = amd64Compiler{
ir: ir,
withListener: withListener,
typ: typ,
assembler: c.assembler,
cpuFeatures: c.cpuFeatures,
labels: c.labels,
locationStackForEntrypoint: c.locationStackForEntrypoint,
brTableTmp: c.brTableTmp,
fourZeros: c.fourZeros,
eightZeros: c.eightZeros,
minimum32BitSignedInt: c.minimum32BitSignedInt,
maximum32BitSignedInt: c.maximum32BitSignedInt,
maximum32BitUnsignedInt: c.maximum32BitUnsignedInt,
minimum64BitSignedInt: c.minimum64BitSignedInt,
maximum64BitSignedInt: c.maximum64BitSignedInt,
maximum64BitUnsignedInt: c.maximum64BitUnsignedInt,
float32SignBitMask: c.float32SignBitMask,
float32RestBitMask: c.float32RestBitMask,
float64SignBitMask: c.float64SignBitMask,
float64RestBitMask: c.float64RestBitMask,
float32ForMinimumSigned32bitInteger: c.float32ForMinimumSigned32bitInteger,
float64ForMinimumSigned32bitInteger: c.float64ForMinimumSigned32bitInteger,
float32ForMinimumSigned64bitInteger: c.float32ForMinimumSigned64bitInteger,
float64ForMinimumSigned64bitInteger: c.float64ForMinimumSigned64bitInteger,
float32ForMaximumSigned32bitIntPlusOne: c.float32ForMaximumSigned32bitIntPlusOne,
float64ForMaximumSigned32bitIntPlusOne: c.float64ForMaximumSigned32bitIntPlusOne,
float32ForMaximumSigned64bitIntPlusOne: c.float32ForMaximumSigned64bitIntPlusOne,
float64ForMaximumSigned64bitIntPlusOne: c.float64ForMaximumSigned64bitIntPlusOne,
}
// Reuses the initial location stack for the compilation of subsequent functions.
c.locationStack = &c.locationStackForEntrypoint
}
// resetLabels resets the existing content in arm64Compiler.labels so that
// we could reuse the allocated slices and stacks in the subsequent compilations.
func (c *amd64Compiler) resetLabels() {
for i := range c.labels {
for j := range c.labels[i] {
if j > c.frameIDMax {
// Only need to reset until the maximum frame id. This makes the compilation faster for large binary.
break
}
l := &c.labels[i][j]
l.initialInstruction = nil
l.stackInitialized = false
l.initialStack.reset()
}
}
}
// runtimeValueLocationStack implements compilerImpl.runtimeValueLocationStack for the amd64 architecture.
func (c *amd64Compiler) runtimeValueLocationStack() *runtimeValueLocationStack {
return c.locationStack
}
// setLocationStack sets the given runtimeValueLocationStack to .locationStack field,
// while allowing us to track runtimeValueLocationStack.stackPointerCeil across multiple stacks.
// This is called when we branch into different block.
func (c *amd64Compiler) setLocationStack(newStack *runtimeValueLocationStack) {
if c.stackPointerCeil < c.locationStack.stackPointerCeil {
c.stackPointerCeil = c.locationStack.stackPointerCeil
}
c.locationStack = newStack
}
// pushRuntimeValueLocationOnRegister implements compiler.pushRuntimeValueLocationOnRegister for amd64.
func (c *amd64Compiler) pushRuntimeValueLocationOnRegister(reg asm.Register, vt runtimeValueType) (ret *runtimeValueLocation) {
ret = c.locationStack.pushRuntimeValueLocationOnRegister(reg, vt)
c.locationStack.markRegisterUsed(reg)
return
}
// pushVectorRuntimeValueLocationOnRegister implements compiler.pushVectorRuntimeValueLocationOnRegister for amd64.
func (c *amd64Compiler) pushVectorRuntimeValueLocationOnRegister(reg asm.Register) (lowerBitsLocation *runtimeValueLocation) {
lowerBitsLocation = c.locationStack.pushRuntimeValueLocationOnRegister(reg, runtimeValueTypeV128Lo)
c.locationStack.pushRuntimeValueLocationOnRegister(reg, runtimeValueTypeV128Hi)
c.locationStack.markRegisterUsed(reg)
return
}
type amd64LabelInfo struct {
// initialInstruction is the initial instruction for this label so other block can jump into it.
initialInstruction asm.Node
// initialStack is the initial value location stack from which we start compiling this label.
initialStack runtimeValueLocationStack
stackInitialized bool
}
func (c *amd64Compiler) label(label wazeroir.Label) *amd64LabelInfo {
kind := label.Kind()
frames := c.labels[kind]
frameID := label.FrameID()
if c.frameIDMax < frameID {
c.frameIDMax = frameID
}
// If the frameID is not allocated yet, expand the slice by twice of the diff,
// so that we could reduce the allocation in the subsequent compilation.
if diff := frameID - len(frames) + 1; diff > 0 {
for i := 0; i < diff; i++ {
frames = append(frames, amd64LabelInfo{initialStack: newRuntimeValueLocationStack()})
}
c.labels[kind] = frames
}
return &frames[frameID]
}
// compileBuiltinFunctionCheckExitCode implements compiler.compileBuiltinFunctionCheckExitCode for the amd64 architecture.
func (c *amd64Compiler) compileBuiltinFunctionCheckExitCode() error {
if err := c.compileCallBuiltinFunction(builtinFunctionIndexCheckExitCode); err != nil {
return err
}
// After the function call, we have to initialize the stack base pointer and memory reserved registers.
c.compileReservedStackBasePointerInitialization()
c.compileReservedMemoryPointerInitialization()
return nil
}
// compileGoDefinedHostFunction constructs the entire code to enter the host function implementation,
// and return to the caller.
func (c *amd64Compiler) compileGoDefinedHostFunction() error {
// First we must update the location stack to reflect the number of host function inputs.
c.locationStack.init(c.typ)
if c.withListener {
if err := c.compileCallBuiltinFunction(builtinFunctionIndexFunctionListenerBefore); err != nil {
return err
}
}
// Host function needs access to the caller's Function Instance, and the caller's information is stored in the stack
// (as described in the doc of callEngine.stack). Here, we get the caller's *wasm.FunctionInstance from the stack,
// and save it in callEngine.exitContext.callerFunctionInstance so we can pass it to the host function
// without sacrificing the performance.
c.compileReservedStackBasePointerInitialization()
// Alias for readability.
tmp := amd64.RegAX
// Get the location of the callerFunction (*function) in the stack, which depends on the signature.
_, _, callerFunction := c.locationStack.getCallFrameLocations(c.typ)
// Load the value into the tmp register: tmp = &function{..}
callerFunction.setRegister(tmp)
c.compileLoadValueOnStackToRegister(callerFunction)
// tmp = *(tmp+functionSourceOffset) = &wasm.ModuleInstance{...}
c.assembler.CompileMemoryToRegister(amd64.MOVQ, tmp, functionModuleInstanceOffset, tmp)
// Load it onto callEngine.exitContext.callerFunctionInstance.
c.assembler.CompileRegisterToMemory(amd64.MOVQ,
tmp,
amd64ReservedRegisterForCallEngine, callEngineExitContextCallerModuleInstanceOffset)
// Reset the state of callerFunction value location so that we won't mess up subsequent code generation below.
c.locationStack.releaseRegister(callerFunction)
if err := c.compileCallGoHostFunction(); err != nil {
return err
}
// Initializes the reserved stack base pointer which is used to retrieve the call frame stack.
c.compileReservedStackBasePointerInitialization()
// Go function can change the module state in arbitrary way, so we have to force
// the callEngine.moduleContext initialization on the function return. To do so,
// we zero-out callEngine.moduleInstance.
c.assembler.CompileConstToMemory(amd64.MOVQ,
0, amd64ReservedRegisterForCallEngine, callEngineModuleContextModuleInstanceOffset)
return c.compileReturnFunction()
}
// compile implements compiler.compile for the amd64 architecture.
func (c *amd64Compiler) compile(buf asm.Buffer) (stackPointerCeil uint64, err error) {
// c.stackPointerCeil tracks the stack pointer ceiling (max seen) value across all runtimeValueLocationStack(s)
// used for all labels (via setLocationStack), excluding the current one.
// Hence, we check here if the final block's max one exceeds the current c.stackPointerCeil.
stackPointerCeil = c.stackPointerCeil
if stackPointerCeil < c.locationStack.stackPointerCeil {
stackPointerCeil = c.locationStack.stackPointerCeil
}
// Now that the max stack pointer is determined, we are invoking the callback.
// Note this MUST be called before Assemble() below.
c.assignStackPointerCeil(stackPointerCeil)
err = c.assembler.Assemble(buf)
return
}
// compileUnreachable implements compiler.compileUnreachable for the amd64 architecture.
func (c *amd64Compiler) compileUnreachable() error {
c.compileExitFromNativeCode(nativeCallStatusCodeUnreachable)
return nil
}
// assignStackPointerCeil implements compilerImpl.assignStackPointerCeil for the amd64 architecture.
func (c *amd64Compiler) assignStackPointerCeil(ceil uint64) {
if c.assignStackPointerCeilNeeded != nil {
c.assignStackPointerCeilNeeded.AssignDestinationConstant(int64(ceil) << 3)
}
}
// compileSet implements compiler.compileSet for the amd64 architecture.
func (c *amd64Compiler) compileSet(o *wazeroir.UnionOperation) error {
depth := int(o.U1)
isTargetVector := o.B3
setTargetIndex := int(c.locationStack.sp) - 1 - depth
if isTargetVector {
_ = c.locationStack.pop() // ignore the higher 64-bits.
}
v := c.locationStack.pop()
if err := c.compileEnsureOnRegister(v); err != nil {
return err
}
targetLocation := &c.locationStack.stack[setTargetIndex]
if targetLocation.onRegister() {
// We no longer need the register previously used by the target location.
c.locationStack.markRegisterUnused(targetLocation.register)
}
reg := v.register
targetLocation.setRegister(reg)
targetLocation.valueType = v.valueType
if isTargetVector {
hi := &c.locationStack.stack[setTargetIndex+1]
hi.setRegister(reg)
}
return nil
}
// compileGlobalGet implements compiler.compileGlobalGet for the amd64 architecture.
func (c *amd64Compiler) compileGlobalGet(o *wazeroir.UnionOperation) error {
if err := c.maybeCompileMoveTopConditionalToGeneralPurposeRegister(); err != nil {
return err
}
intReg, err := c.allocateRegister(registerTypeGeneralPurpose)
if err != nil {
return err
}
// First, move the pointer to the global slice into the allocated register.
c.assembler.CompileMemoryToRegister(amd64.MOVQ, amd64ReservedRegisterForCallEngine, callEngineModuleContextGlobalElement0AddressOffset, intReg)
index := o.U1
// Now, move the location of the global instance into the register.
c.assembler.CompileMemoryToRegister(amd64.MOVQ, intReg, 8*int64(index), intReg)
// When an integer, reuse the pointer register for the value. Otherwise, allocate a float register for it.
valueReg := intReg
var vt runtimeValueType
var inst asm.Instruction
switch c.ir.Globals[index].ValType {
case wasm.ValueTypeI32:
inst = amd64.MOVL
vt = runtimeValueTypeI32
case wasm.ValueTypeI64, wasm.ValueTypeExternref, wasm.ValueTypeFuncref:
inst = amd64.MOVQ
vt = runtimeValueTypeI64
case wasm.ValueTypeF32:
inst = amd64.MOVL
vt = runtimeValueTypeF32
valueReg, err = c.allocateRegister(registerTypeVector)
if err != nil {
return err
}
case wasm.ValueTypeF64:
inst = amd64.MOVQ
vt = runtimeValueTypeF64
valueReg, err = c.allocateRegister(registerTypeVector)
if err != nil {
return err
}
case wasm.ValueTypeV128:
inst = amd64.MOVDQU
vt = runtimeValueTypeV128Lo
valueReg, err = c.allocateRegister(registerTypeVector)
if err != nil {
return err
}
default:
panic("BUG: unknown runtime value type")
}
// Using the register holding the pointer to the target instance, move its value into a register.
c.assembler.CompileMemoryToRegister(inst, intReg, globalInstanceValueOffset, valueReg)
// Record that the retrieved global value on the top of the stack is now in a register.
if vt == runtimeValueTypeV128Lo {
c.pushVectorRuntimeValueLocationOnRegister(valueReg)
} else {
c.pushRuntimeValueLocationOnRegister(valueReg, vt)
}
return nil
}
// compileGlobalSet implements compiler.compileGlobalSet for the amd64 architecture.
func (c *amd64Compiler) compileGlobalSet(o *wazeroir.UnionOperation) error {
index := o.U1
wasmValueType := c.ir.Globals[index].ValType
isV128 := wasmValueType == wasm.ValueTypeV128
// First, move the value to set into a temporary register.
val := c.locationStack.pop()
if isV128 {
// The previous val is higher 64-bits, and have to use lower 64-bit's runtimeValueLocation for allocation, etc.
val = c.locationStack.pop()
}
if err := c.compileEnsureOnRegister(val); err != nil {
return err
}
// Allocate a register to hold the memory location of the target global instance.
intReg, err := c.allocateRegister(registerTypeGeneralPurpose)
if err != nil {
return err
}
// First, move the pointer to the global slice into the allocated register.
c.assembler.CompileMemoryToRegister(amd64.MOVQ, amd64ReservedRegisterForCallEngine, callEngineModuleContextGlobalElement0AddressOffset, intReg)
// Now, move the location of the global instance into the register.
c.assembler.CompileMemoryToRegister(amd64.MOVQ, intReg, 8*int64(index), intReg)
// Now ready to write the value to the global instance location.
var inst asm.Instruction
if isV128 {
inst = amd64.MOVDQU
} else if wasmValueType == wasm.ValueTypeI32 || wasmValueType == wasm.ValueTypeF32 {
inst = amd64.MOVL
} else {
inst = amd64.MOVQ
}
c.assembler.CompileRegisterToMemory(inst, val.register, intReg, globalInstanceValueOffset)
// Since the value is now written to memory, release the value register.
c.locationStack.releaseRegister(val)
return nil
}
// compileBr implements compiler.compileBr for the amd64 architecture.
func (c *amd64Compiler) compileBr(o *wazeroir.UnionOperation) error {
if err := c.maybeCompileMoveTopConditionalToGeneralPurposeRegister(); err != nil {
return err
}
return c.branchInto(wazeroir.Label(o.U1))
}
// branchInto adds instruction necessary to jump into the given branch target.
func (c *amd64Compiler) branchInto(target wazeroir.Label) error {
if target.IsReturnTarget() {
return c.compileReturnFunction()
} else {
if c.ir.LabelCallers[target] > 1 {
// We can only re-use register state if when there's a single call-site.
// Release existing values on registers to the stack if there's multiple ones to have
// the consistent value location state at the beginning of label.
if err := c.compileReleaseAllRegistersToStack(); err != nil {
return err
}
}
// Set the initial stack of the target label, so we can start compiling the label
// with the appropriate value locations. Note we clone the stack here as we maybe
// manipulate the stack before compiler reaches the label.
targetLabel := c.label(target)
if !targetLabel.stackInitialized {
targetLabel.initialStack.cloneFrom(*c.locationStack)
targetLabel.stackInitialized = true
}
jmp := c.assembler.CompileJump(amd64.JMP)
c.assignJumpTarget(target, jmp)
}
return nil
}
// compileBrIf implements compiler.compileBrIf for the amd64 architecture.
func (c *amd64Compiler) compileBrIf(o *wazeroir.UnionOperation) error {
cond := c.locationStack.pop()
var jmpWithCond asm.Node
if cond.onConditionalRegister() {
var inst asm.Instruction
switch cond.conditionalRegister {
case amd64.ConditionalRegisterStateE:
inst = amd64.JEQ
case amd64.ConditionalRegisterStateNE:
inst = amd64.JNE
case amd64.ConditionalRegisterStateS:
inst = amd64.JMI
case amd64.ConditionalRegisterStateNS:
inst = amd64.JPL
case amd64.ConditionalRegisterStateG:
inst = amd64.JGT
case amd64.ConditionalRegisterStateGE:
inst = amd64.JGE
case amd64.ConditionalRegisterStateL:
inst = amd64.JLT
case amd64.ConditionalRegisterStateLE:
inst = amd64.JLE
case amd64.ConditionalRegisterStateA:
inst = amd64.JHI
case amd64.ConditionalRegisterStateAE:
inst = amd64.JCC
case amd64.ConditionalRegisterStateB:
inst = amd64.JCS
case amd64.ConditionalRegisterStateBE:
inst = amd64.JLS
}
jmpWithCond = c.assembler.CompileJump(inst)
} else {
// Usually the comparison operand for br_if is on the conditional register,
// but in some cases, they are on the stack or register.
// For example, the following code
// i64.const 1
// local.get 1
// i64.add
// br_if ....
// will try to use the result of i64.add, which resides on the (virtual) stack,
// as the operand for br_if instruction.
if err := c.compileEnsureOnRegister(cond); err != nil {
return err
}
// Check if the value not equals zero.
c.assembler.CompileRegisterToRegister(amd64.TESTQ, cond.register, cond.register)
// Emit jump instruction which jumps when the value does not equals zero.
jmpWithCond = c.assembler.CompileJump(amd64.JNE)
c.locationStack.markRegisterUnused(cond.register)
}
// Make sure that the next coming label is the else jump target.
thenTarget := wazeroir.Label(o.U1)
elseTarget := wazeroir.Label(o.U2)
thenToDrop := o.U3
// Here's the diagram of how we organize the instructions necessarily for brif operation.
//
// jmp_with_cond -> jmp (.Else) -> Then operations...
// |---------(satisfied)------------^^^
//
// Note that .Else branch doesn't have ToDrop as .Else is in reality
// corresponding to either If's Else block or Br_if's else block in Wasm.
// Emit the else branch.
if elseTarget.IsReturnTarget() {
if err := c.compileReturnFunction(); err != nil {
return err
}
} else {
labelInfo := c.label(elseTarget)
if !labelInfo.stackInitialized {
labelInfo.initialStack.cloneFrom(*c.locationStack)
labelInfo.stackInitialized = true
}
elseJmp := c.assembler.CompileJump(amd64.JMP)
c.assignJumpTarget(elseTarget, elseJmp)
}
// Handle then branch.
c.assembler.SetJumpTargetOnNext(jmpWithCond)
if err := compileDropRange(c, thenToDrop); err != nil {
return err
}
if thenTarget.IsReturnTarget() {
return c.compileReturnFunction()
} else {
thenLabel := thenTarget
if c.ir.LabelCallers[thenLabel] > 1 {
// We can only re-use register state if when there's a single call-site.
// Release existing values on registers to the stack if there's multiple ones to have
// the consistent value location state at the beginning of label.
if err := c.compileReleaseAllRegistersToStack(); err != nil {
return err
}
}
// Set the initial stack of the target label, so we can start compiling the label
// with the appropriate value locations. Note we clone the stack here as we maybe
// manipulate the stack before compiler reaches the label.
labelInfo := c.label(thenLabel)
if !labelInfo.stackInitialized {
labelInfo.initialStack.cloneFrom(*c.locationStack)
labelInfo.stackInitialized = true
}
thenJmp := c.assembler.CompileJump(amd64.JMP)
c.assignJumpTarget(thenLabel, thenJmp)
return nil
}
}
// compileBrTable implements compiler.compileBrTable for the amd64 architecture.
func (c *amd64Compiler) compileBrTable(o *wazeroir.UnionOperation) error {
index := c.locationStack.pop()
// If the operation only consists of the default target, we branch into it and return early.
if len(o.Us) == 2 {
c.locationStack.releaseRegister(index)
if err := compileDropRange(c, o.Us[1]); err != nil {
return err
}
return c.branchInto(wazeroir.Label(o.Us[0]))
}
// Otherwise, we jump into the selected branch.
if err := c.compileEnsureOnRegister(index); err != nil {
return err
}
tmp, err := c.allocateRegister(registerTypeGeneralPurpose)
if err != nil {
return err
}
// First, we move the length of target list into the tmp register.
c.assembler.CompileConstToRegister(amd64.MOVQ, int64(len(o.Us)/2-1), tmp)
// Then, we compare the value with the length of targets.
c.assembler.CompileRegisterToRegister(amd64.CMPL, tmp, index.register)
// If the value is larger than the length,
// we round the index to the length as the spec states that
// if the index is larger than or equal the length of list,
// branch into the default branch.
c.assembler.CompileRegisterToRegister(amd64.CMOVQCS, tmp, index.register)
// We prepare the static data which holds the offset of
// each target's first instruction (incl. default)
// relative to the beginning of label tables.
//
// For example, if we have targets=[L0, L1] and default=L_DEFAULT,
// we emit the the code like this at [Emit the code for each targets and default branch] below.
//
// L0:
// 0x123001: XXXX, ...
// .....
// L1:
// 0x123005: YYY, ...
// .....
// L_DEFAULT:
// 0x123009: ZZZ, ...
//
// then offsetData becomes like [0x0, 0x5, 0x8].
// By using this offset list, we could jump into the label for the index by
// "jmp offsetData[index]+0x123001" and "0x123001" can be acquired by "LEA"
// instruction.
//
// Note: We store each offset of 32-bite unsigned integer as 4 consecutive bytes. So more precisely,
// the above example's offsetData would be [0x0, 0x0, 0x0, 0x0, 0x5, 0x0, 0x0, 0x0, 0x8, 0x0, 0x0, 0x0].
//
// Note: this is similar to how GCC implements Switch statements in C.
offsetData := asm.NewStaticConst(make([]byte, 4*(len(o.Us)/2)))
// Load the offsetData's address into tmp.
if err = c.assembler.CompileStaticConstToRegister(amd64.LEAQ, offsetData, tmp); err != nil {
return err
}
// Now we have the address of first byte of offsetData in tmp register.
// So the target offset's first byte is at tmp+index*4 as we store
// the offset as 4 bytes for a 32-byte integer.
// Here, we store the offset into the index.register.
c.assembler.CompileMemoryWithIndexToRegister(amd64.MOVL, tmp, 0, index.register, 4, index.register)
// Now we read the address of the beginning of the jump table.
// In the above example, this corresponds to reading the address of 0x123001.
c.assembler.CompileReadInstructionAddress(tmp, amd64.JMP)
// Now we have the address of L0 in tmp register, and the offset to the target label in the index.register.
// So we could achieve the br_table jump by adding them and jump into the resulting address.
c.assembler.CompileRegisterToRegister(amd64.ADDQ, index.register, tmp)
c.assembler.CompileJumpToRegister(amd64.JMP, tmp)
// We no longer need the index's register, so mark it unused.
c.locationStack.markRegisterUnused(index.register)
// [Emit the code for each targets and default branch]
labelInitialInstructions := make([]asm.Node, len(o.Us)/2)
// Since we might end up having the different stack state in each branch,
// we need to save the initial stack state here, and use the same initial state
// for each iteration.
initialLocationStack := c.getSavedTemporaryLocationStack()
for i := range labelInitialInstructions {
// Emit the initial instruction of each target.
// We use NOP as we don't yet know the next instruction in each label.
// Assembler would optimize out this NOP during code generation, so this is harmless.
labelInitialInstructions[i] = c.assembler.CompileStandAlone(amd64.NOP)
targetLabel := wazeroir.Label(o.Us[i*2])
targetToDrop := o.Us[i*2+1]
if err = compileDropRange(c, targetToDrop); err != nil {
return err
}
if err = c.branchInto(targetLabel); err != nil {
return err
}
// After the iteration, reset the stack's state with initialLocationStack.
c.locationStack.cloneFrom(initialLocationStack)
}
c.assembler.BuildJumpTable(offsetData, labelInitialInstructions)
return nil
}
func (c *amd64Compiler) getSavedTemporaryLocationStack() runtimeValueLocationStack {
initialLocationStack := *c.locationStack // Take copy!
// Use c.brTableTmp for the underlying stack so that we could reduce the allocations.
if diff := int(initialLocationStack.sp) - len(c.brTableTmp); diff > 0 {
c.brTableTmp = append(c.brTableTmp, make([]runtimeValueLocation, diff)...)
}
copy(c.brTableTmp, initialLocationStack.stack[:initialLocationStack.sp])
initialLocationStack.stack = c.brTableTmp
return initialLocationStack
}
func (c *amd64Compiler) assignJumpTarget(label wazeroir.Label, jmpInstruction asm.Node) {
jmpTargetLabel := c.label(label)
targetInst := jmpTargetLabel.initialInstruction
if targetInst == nil {
// If the label isn't compiled yet, allocate the NOP node, and set as the initial instruction.
targetInst = c.assembler.AllocateNOP()
jmpTargetLabel.initialInstruction = targetInst
}
jmpInstruction.AssignJumpTarget(targetInst)
}
// compileLabel implements compiler.compileLabel for the amd64 architecture.
func (c *amd64Compiler) compileLabel(o *wazeroir.UnionOperation) (skipLabel bool) {
label := wazeroir.Label(o.U1)
labelInfo := c.label(label)
// If initialStack is not set, that means this label has never been reached.
if !labelInfo.stackInitialized {
skipLabel = true
return
}
// We use NOP as a beginning of instructions in a label.
if labelBegin := labelInfo.initialInstruction; labelBegin == nil {
// We use NOP as a beginning of instructions in a label.
// This should be eventually optimized out by assembler.
labelInfo.initialInstruction = c.assembler.CompileStandAlone(amd64.NOP)
} else {
c.assembler.Add(labelBegin)
}
// Set the initial stack.
c.setLocationStack(&labelInfo.initialStack)
return
}
// compileCall implements compiler.compileCall for the amd64 architecture.
func (c *amd64Compiler) compileCall(o *wazeroir.UnionOperation) error {
if err := c.maybeCompileMoveTopConditionalToGeneralPurposeRegister(); err != nil {
return err
}
functionIndex := o.U1
target := c.ir.Functions[functionIndex]
targetType := &c.ir.Types[target]
targetAddressRegister, err := c.allocateRegister(registerTypeGeneralPurpose)
if err != nil {
return err
}
// First, push the index to the callEngine.functionsElement0Address into the target register.
c.assembler.CompileConstToRegister(amd64.MOVQ, int64(functionIndex)*functionSize, targetAddressRegister)
// Next, we add the address of the first item of callEngine.functions slice (= &callEngine.functions[0])
// to the target register.
c.assembler.CompileMemoryToRegister(amd64.ADDQ, amd64ReservedRegisterForCallEngine,
callEngineModuleContextFunctionsElement0AddressOffset, targetAddressRegister)
if err := c.compileCallFunctionImpl(targetAddressRegister, targetType); err != nil {
return err
}
return nil
}
// compileCallIndirect implements compiler.compileCallIndirect for the amd64 architecture.
func (c *amd64Compiler) compileCallIndirect(o *wazeroir.UnionOperation) error {
offset := c.locationStack.pop()
if err := c.compileEnsureOnRegister(offset); err != nil {
return nil
}
typeIndex := o.U1
tableIndex := o.U2
tmp, err := c.allocateRegister(registerTypeGeneralPurpose)
if err != nil {
return err
}
c.locationStack.markRegisterUsed(tmp)
tmp2, err := c.allocateRegister(registerTypeGeneralPurpose)
if err != nil {
return err
}
c.locationStack.markRegisterUsed(tmp2)
// Load the address of the target table: tmp = &module.Tables[0]
c.assembler.CompileMemoryToRegister(amd64.MOVQ, amd64ReservedRegisterForCallEngine, callEngineModuleContextTablesElement0AddressOffset, tmp)
// tmp = &module.Tables[0] + Index*8 = &module.Tables[0] + sizeOf(*TableInstance)*index = module.Tables[o.TableIndex].
c.assembler.CompileMemoryToRegister(amd64.MOVQ, tmp, int64(tableIndex*8), tmp)
// Then, we need to trap if the offset exceeds the length of table.
c.assembler.CompileMemoryToRegister(amd64.CMPQ, tmp, tableInstanceTableLenOffset, offset.register)
c.compileMaybeExitFromNativeCode(amd64.JHI, nativeCallStatusCodeInvalidTableAccess)
// next we check if the target's type matches the operation's one.
// In order to get the type instance's address, we have to multiply the offset
// by 8 as the offset is the "length" of table in Go's "[]uintptr{}",
// and size of uintptr equals 8 bytes == (2^3).
c.assembler.CompileConstToRegister(amd64.SHLQ, pointerSizeLog2, offset.register)
// Adds the address of wasm.Table[0] stored as callEngine.tableElement0Address to the offset.
c.assembler.CompileMemoryToRegister(amd64.ADDQ,
tmp, tableInstanceTableOffset, offset.register)
// "offset = (*offset) (== table[offset] == *code type)"
c.assembler.CompileMemoryToRegister(amd64.MOVQ, offset.register, 0, offset.register)
// At this point offset.register holds the address of *code (as uintptr) at wasm.Table[offset].
//
// Check if the value of table[offset] equals zero, meaning that the target is uninitialized.
c.assembler.CompileRegisterToRegister(amd64.TESTQ, offset.register, offset.register)
// Skipped if the target is initialized.
c.compileMaybeExitFromNativeCode(amd64.JNE, nativeCallStatusCodeInvalidTableAccess)
// Next, we need to check the type matches, i.e. table[offset].source.TypeID == targetFunctionType's typeID.
//
// "tmp2 = [&moduleInstance.TypeIDs[0] + index * 4] (== moduleInstance.TypeIDs[index])"
c.assembler.CompileMemoryToRegister(amd64.MOVQ,
amd64ReservedRegisterForCallEngine, callEngineModuleContextTypeIDsElement0AddressOffset,
tmp2)
c.assembler.CompileMemoryToRegister(amd64.MOVL, tmp2, int64(typeIndex)*4, tmp2)
// Skipped if the type matches.
c.assembler.CompileMemoryToRegister(amd64.CMPL, offset.register, functionTypeIDOffset, tmp2)
c.compileMaybeExitFromNativeCode(amd64.JEQ, nativeCallStatusCodeTypeMismatchOnIndirectCall)
targetFunctionType := &c.ir.Types[typeIndex]
if err = c.compileCallFunctionImpl(offset.register, targetFunctionType); err != nil {
return nil
}
// The offset register should be marked as un-used as we consumed in the function call.
c.locationStack.markRegisterUnused(offset.register, tmp, tmp2)
return nil
}
// compileDrop implements compiler.compileDrop for the amd64 architecture.
func (c *amd64Compiler) compileDrop(o *wazeroir.UnionOperation) error {
return compileDropRange(c, o.U1)
}
// compileSelectV128Impl implements compileSelect for vector values.
func (c *amd64Compiler) compileSelectV128Impl(selectorReg asm.Register) error {
x2 := c.locationStack.popV128()
if err := c.compileEnsureOnRegister(x2); err != nil {
return err
}
x1 := c.locationStack.popV128()
if err := c.compileEnsureOnRegister(x1); err != nil {
return err
}
// Compare the conditional value with zero.
c.assembler.CompileRegisterToRegister(amd64.TESTQ, selectorReg, selectorReg)
// Set the jump if the top value is not zero.
jmpIfNotZero := c.assembler.CompileJump(amd64.JNE)
// In this branch, we select the value of x2, so we move the value into x1.register so that
// we can have the result in x1.register regardless of the selection.
c.assembler.CompileRegisterToRegister(amd64.MOVDQU, x2.register, x1.register)
// Else, we don't need to adjust value, just need to jump to the next instruction.
c.assembler.SetJumpTargetOnNext(jmpIfNotZero)
// As noted, the result exists in x1.register regardless of the selector.
c.pushVectorRuntimeValueLocationOnRegister(x1.register)
// Plus, x2.register is no longer used.
c.locationStack.markRegisterUnused(x2.register)
c.locationStack.markRegisterUnused(selectorReg)
return nil
}
// compileSelect implements compiler.compileSelect for the amd64 architecture.
//
// The emitted native code depends on whether the values are on
// the physical registers or memory stack, or maybe conditional register.
func (c *amd64Compiler) compileSelect(o *wazeroir.UnionOperation) error {
cv := c.locationStack.pop()
if err := c.compileEnsureOnRegister(cv); err != nil {
return err
}
isTargetVector := o.B3
if isTargetVector {
return c.compileSelectV128Impl(cv.register)
}
x2 := c.locationStack.pop()
// We do not consume x1 here, but modify the value according to
// the conditional value "c" above.
peekedX1 := c.locationStack.peek()
// Compare the conditional value with zero.
c.assembler.CompileRegisterToRegister(amd64.TESTQ, cv.register, cv.register)
// Now we can use c.register as temporary location.
// We alias it here for readability.
tmpRegister := cv.register
// Set the jump if the top value is not zero.
jmpIfNotZero := c.assembler.CompileJump(amd64.JNE)
// If the value is zero, we must place the value of x2 onto the stack position of x1.
// First we copy the value of x2 to the temporary register if x2 is not currently on a register.
if x2.onStack() {
x2.register = tmpRegister
c.compileLoadValueOnStackToRegister(x2)
}
//
// At this point x2's value is always on a register.
//
// Then release the value in the x2's register to the x1's stack position.
if peekedX1.onRegister() {