Debian Codegraph @

simd/block_align_amd64_test.go

raw
1 //go:build amd64
2
3 package simd
4
5 import (
6 "bytes"
7 "encoding/binary"
8 "reflect"
9 "testing"
10 "unsafe"
11
12 "github.com/stretchr/testify/require"
13 )
14
15 // The block loops are placed by BLOCKALIGN / BLOCKALIGN_LONG
16 // (block_align_amd64.h) so that none of their macro-fused
17 // compare-and-branch pairs crosses or ends on a 32-byte boundary, which
18 // the JCC erratum mitigation on Skylake-derived cores punishes with a
19 // decoded-uop-cache miss per iteration. This test reads each kernel's
20 // machine code out of the running binary and checks that property, so a
21 // kernel edit that moves a branch onto a boundary fails here instead of
22 // silently costing throughput; the log lines give each pair's position
23 // relative to the loop head, from which a fitting offset can be chosen.
24 //
25 // The kernels are ABI0 assembly, so a Go func value points at the
26 // ABIInternal wrapper the linker generates; its first CALL leads to the
27 // kernel body. The body's block loop starts at the first non-NOP after
28 // the macro's nine-byte NOPs, and ends at the backward CMPQ SI, R11 /
29 // JBE. Every branch in between is one of the fused pairs enumerated in
30 // fusedPairs, matched on its exact encoding; there is no instruction
31 // decoding here, so a kernel that introduces a branch of a new shape must
32 // add its encoding to the list.
33
34 // blockLoopKernels maps each kernel with a BLOCKALIGN block loop to its
35 // Go declaration.
36 var blockLoopKernels = map[string]any{
37 "memchr2AVX2": memchr2AVX2,
38 "memchr3AVX2": memchr3AVX2,
39 "memchrPairAVX2": memchrPairAVX2,
40 "memchrDigitAVX2": memchrDigitAVX2,
41 "memchrWordAVX2": memchrWordAVX2,
42 "memchrNotWordAVX2": memchrNotWordAVX2,
43 "isASCIIAVX2": isASCIIAVX2,
44 "firstNonASCIIAVX2": firstNonASCIIAVX2,
45 "countNonASCIIAVX2": countNonASCIIAVX2,
46 }
47
48 // fusedPairs lists the encodings of the compare (or decrement) that opens
49 // each fused pair the block loops use. The branch that follows it is
50 // matched by opcode: a short Jcc (0x70-0x7F, two bytes) or a near Jcc
51 // (0x0F 0x80-0x8F, six bytes). The CMPQ SI, R11 / JBE pair is the loop
52 // back-edge, where the scan stops.
53 var fusedPairs = []struct {
54 name string
55 prefix []byte
56 backEdge bool
57 }{
58 {name: "TESTL CX, CX", prefix: []byte{0x85, 0xC9}},
59 {name: "TESTL AX, AX", prefix: []byte{0x85, 0xC0}},
60 {name: "DECQ R13", prefix: []byte{0x49, 0xFF, 0xCD}},
61 {name: "CMPQ SI, R11", prefix: []byte{0x4C, 0x39, 0xDE}, backEdge: true},
62 }
63
64 // nop9 is the canonical nine-byte NOP BLOCKALIGN emits twice and
65 // BLOCKALIGN_LONG three times.
66 var nop9 = []byte{0x66, 0x0F, 0x1F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00}
67
68 // nopForms lists the multi-byte NOP encodings the assembler pads with, so
69 // the loop head can be found as the first non-NOP after the BLOCKALIGN
70 // signature whatever PCALIGN and a kernel's extra pad emitted around it.
71 var nopForms = [][]byte{
72 {0x66, 0x66, 0x66, 0x0F, 0x1F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
73 {0x66, 0x66, 0x0F, 0x1F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
74 nop9,
75 {0x0F, 0x1F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
76 {0x0F, 0x1F, 0x80, 0x00, 0x00, 0x00, 0x00},
77 {0x66, 0x0F, 0x1F, 0x44, 0x00, 0x00},
78 {0x0F, 0x1F, 0x44, 0x00, 0x00},
79 {0x0F, 0x1F, 0x40, 0x00},
80 {0x0F, 0x1F, 0x00},
81 {0x66, 0x90},
82 {0x90},
83 }
84
85 // nopLen returns the length of the NOP encoded at the start of b, or 0.
86 func nopLen(b []byte) int {
87 for _, form := range nopForms {
88 if bytes.HasPrefix(b, form) {
89 return len(form)
90 }
91 }
92 return 0
93 }
94
95 // kernelBody returns the kernel's code bytes and their address, resolved
96 // through the ABI wrapper's first CALL; the body is checked to start with
97 // the MOVQ data_base+0(FP), SI every kernel opens with.
98 func kernelBody(t *testing.T, name string, fn any) ([]byte, uintptr) {
99 t.Helper()
100 wrapper := reflect.ValueOf(fn).UnsafePointer()
101 w := unsafe.Slice((*byte)(wrapper), 128) //nolint:gosec // reading this binary's own text segment
102 call := bytes.IndexByte(w, 0xE8)
103 require.GreaterOrEqual(t, call, 0, "%s: no CALL in the ABI wrapper", name)
104 // The CALL's rel32 is a signed displacement; the conversion reinterprets
105 // its two's-complement bits.
106 rel := int32(binary.LittleEndian.Uint32(w[call+1:]))
107 body := unsafe.Add(wrapper, call+5+int(rel))
108 code := unsafe.Slice((*byte)(body), 2048) //nolint:gosec // reading this binary's own text segment
109 require.True(t, bytes.HasPrefix(code, []byte{0x48, 0x8B, 0x74, 0x24, 0x08}),
110 "%s: wrapper CALL does not lead to the kernel body", name)
111 return code, uintptr(body)
112 }
113
114 // Test_BlockLoopBranchesStayInWindow checks, for every kernel with a
115 // BLOCKALIGN block loop, that no fused compare-and-branch pair of the loop
116 // crosses or ends on a 32-byte boundary; see the file comment.
117 func Test_BlockLoopBranchesStayInWindow(t *testing.T) {
118 signature := append(append([]byte{}, nop9...), nop9...)
119 for name, fn := range blockLoopKernels {
120 code, base := kernelBody(t, name, fn)
121
122 // The signature may also match inside PCALIGN's own padding, and a
123 // kernel may add a NOP of its own after it, so the head is the
124 // first non-NOP byte after the signature.
125 head := bytes.Index(code, signature)
126 require.GreaterOrEqual(t, head, 0, "%s: BLOCKALIGN padding not found", name)
127 head += len(signature)
128 for n := nopLen(code[head:]); n > 0; n = nopLen(code[head:]) {
129 head += n
130 }
131
132 pairs := 0
133 closed := false
134 for i := head; i < len(code)-6 && !closed; i++ {
135 for _, fp := range fusedPairs {
136 if !bytes.HasPrefix(code[i:], fp.prefix) {
137 continue
138 }
139 j := i + len(fp.prefix)
140 var size int
141 switch {
142 case code[j] >= 0x70 && code[j] <= 0x7F:
143 size = 2
144 case code[j] == 0x0F && code[j+1] >= 0x80 && code[j+1] <= 0x8F:
145 size = 6
146 default:
147 continue
148 }
149 start := base + uintptr(i)
150 end := base + uintptr(j+size-1)
151 t.Logf("%s: head mod 32 = %d, fused %s/Jcc at head+%d..head+%d", name, (base+uintptr(head))%32, fp.name, i-head, j+size-1-head)
152 if start/32 != end/32 {
153 t.Errorf("%s: fused %s/Jcc at %#x-%#x crosses a 32-byte boundary", name, fp.name, start, end)
154 }
155 if end%32 == 31 {
156 t.Errorf("%s: fused %s/Jcc at %#x-%#x ends on a 32-byte boundary", name, fp.name, start, end)
157 }
158 pairs++
159 if fp.backEdge {
160 closed = true
161 }
162 i = j + size - 1
163 break
164 }
165 }
166 require.True(t, closed, "%s: block loop back-edge not found", name)
167 require.GreaterOrEqual(t, pairs, 1, "%s: no fused branch found in the block loop", name)
168 }
169 }