-
Notifications
You must be signed in to change notification settings - Fork 39
/
zion.go
295 lines (259 loc) · 7.44 KB
/
zion.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
// Copyright 2023 Sneller, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package vm
import (
"encoding/binary"
"fmt"
"slices"
"unsafe"
"github.com/SnellerInc/sneller/ion"
"github.com/SnellerInc/sneller/ion/zion/zll"
"github.com/SnellerInc/sneller/internal/memops"
)
type zionState struct {
shape zll.Shape
buckets zll.Buckets
blocksize int64
}
type zionConsumer interface {
symbolize(st *symtab, aux *auxbindings) error
zionOk(fields []string) bool
writeZion(state *zionState) error
}
// zionFlattener is a wrapper for rowConsumers
// that do not implement zionConsumer
type zionFlattener struct {
rowConsumer // inherit writeRows, Close(), next(), etc.
infields []string
// cached structures:
myaux auxbindings
strided []vmref
params rowParams
tape []ion.Symbol
empty []vmref
}
// we only flatten when the number of fields is small;
// otherwise we have to allocate a bunch of space to
// write out all the vmrefs (columns * rows, 8 bytes each)
// which might actually be *larger* than the data we have to copy...
const maxFlatten = 8
func (z *zionFlattener) zionOk(fields []string) bool {
if len(fields) > 0 && len(fields) < maxFlatten {
z.infields = append(z.infields[:0], fields...)
return true
}
return false
}
func (z *zionFlattener) symbolize(st *symtab, aux *auxbindings) error {
if len(aux.bound) != 0 {
panic("zionFlattener not the top element in the rowConsumer chain?")
}
z.tape = z.tape[:0]
for _, name := range z.infields {
sym, ok := st.Symbolize(name)
if !ok {
continue
}
z.tape = append(z.tape, sym)
}
slices.Sort(z.tape)
// we're going to bind auxbound in symbol order
z.myaux.reset()
for i := range z.tape {
z.myaux.push(st.Get(z.tape[i]))
}
return z.rowConsumer.symbolize(st, &z.myaux)
}
const (
//lint:ignore U1000 used in assembly
zllBucketPos = unsafe.Offsetof(zll.Buckets{}.Pos)
zllBucketDecompressed = unsafe.Offsetof(zll.Buckets{}.Decompressed)
// We try to process zionStride rows at a time from the shape. Must be a power of 2.
zionStrideLog2 = 8
zionStride = 1 << zionStrideLog2
)
func empty(src []vmref, n int) []vmref {
if cap(src) >= n {
for i := range src {
src[i] = vmref{}
}
return src[:n]
}
return make([]vmref, n)
}
// convert a writeZion into a writeRows
// by projecting into auxparams
func (z *zionFlattener) writeZion(state *zionState) error {
if len(z.tape) == 0 {
// unusual edge-case: none of the matched symbols
// are part of the symbol table; just count
// the number of rows and emit empty rows
n, err := state.shape.Count()
if err != nil {
return err
}
z.params.auxbound = z.params.auxbound[:0]
z.empty = empty(z.empty, n)
return z.writeRows(z.empty, &z.params)
}
// force decompression of the buckets we want
err := state.buckets.SelectSymbols(z.tape)
if err != nil {
return err
}
// allocate space for up to zionStride rows * columns;
// each "column" starts at z.strided[column * zionStride:]
// which simplifies the assembly a bit
z.strided = sanitizeAux(z.strided, len(z.tape)*zionStride)
posn := state.buckets.Pos
// set slice sizes for all the fields
z.params.auxbound = shrink(z.params.auxbound, len(z.tape))
pos := state.shape.Start
for pos < len(state.shape.Bits) {
in, out := zionflatten(state.shape.Bits[pos:], &state.buckets, z.strided, z.tape)
pos += in
if pos > len(state.shape.Bits) {
panic("read out-of-bounds")
}
if out > zionStride {
panic("write out-of-bounds")
}
if out <= 0 || in <= 0 {
err = fmt.Errorf("couldn't copy out zion data (data corruption?)")
break
}
for i := range z.params.auxbound {
z.params.auxbound[i] = sanitizeAux(z.strided[i*zionStride:], out)
}
// the callee is allowed to clobber this,
// so it has to be re-zeroed on each iteration
z.empty = empty(z.empty, out)
err = z.writeRows(z.empty, &z.params)
if err != nil {
break
}
}
state.buckets.Pos = posn // restore bucket positions
return err
}
func load64(buf []byte) uint64 {
if cap(buf) >= 8 {
return binary.LittleEndian.Uint64(buf[:8])
}
u := uint64(0)
for i, b := range buf {
u |= uint64(b) << (i * 8)
}
return u
}
func zionflattenReference(shape []byte, buckets *zll.Buckets, fields []vmref, tape []ion.Symbol) (in, out int) {
memops.ZeroMemory(fields)
// TODO: should be provided for testing purposes and for the non-x64 platforms
initShapeLen := len(shape)
outCnt := 0
fieldOffs := 0
tapeOffs := 0
for len(shape) > 0 {
fc := shape[0] & 0x1f
if fc > 16 {
fmt.Printf("zion.Decoder.walk: fc = %x", fc)
return 0, outCnt
}
skip := int((fc + 3) / 2)
if len(shape) < skip {
fmt.Printf("zion.Decoder.walk: skip %d > len(shape)=%d", skip, len(shape))
return 0, outCnt
}
// decode nibbles into structure fields
nibbles := load64(shape[1:])
shape = shape[skip:]
for i := 0; i < int(fc); i++ {
b := nibbles & 0xf
nibbles >>= 4
if buckets.Pos[b] < 0 {
continue // bucket not decompressed
}
buf := buckets.Decompressed[buckets.Pos[b]:]
if len(buf) == 0 {
fmt.Printf("zion.Decoder.walk: unexpected bucket EOF")
return 0, outCnt
}
sym, rest, err := ion.ReadLabel(buf)
if err != nil {
fmt.Printf("zion.Decoder.walk: %s (%d bytes remaining)", err, len(buf))
return 0, outCnt
}
for {
if tapeOffs >= len(tape) || sym < tape[tapeOffs] {
fieldsize := ion.SizeOf(rest)
if fieldsize <= 0 || fieldsize > len(rest) {
fmt.Printf("zion.Decoder.walk: SizeOf=%d", fieldsize)
return 0, outCnt
}
size := fieldsize + (len(buf) - len(rest))
buckets.Pos[b] += int32(size)
break
} else if sym == tape[tapeOffs] {
tapeOffs++
fieldsize := ion.SizeOf(rest)
if fieldsize <= 0 || fieldsize > len(rest) {
fmt.Printf("zion.Decoder.walk: SizeOf=%d", fieldsize)
return 0, outCnt
}
size := fieldsize + (len(buf) - len(rest))
buckets.Pos[b] += int32(size)
d, ok := vmdispl(rest)
if !ok {
fmt.Printf("vmdispl failed")
return 0, outCnt
}
fields[fieldOffs+outCnt] = vmref{d, uint32(fieldsize)}
fieldOffs += zionStride
break
} else { // sym > tape[tapeOffs]
fields[fieldOffs+outCnt] = vmref{0, 0}
fieldOffs += zionStride
tapeOffs++
}
}
}
if fc < 16 {
for tapeOffs < len(tape) {
fields[fieldOffs+outCnt] = vmref{0, 0}
fieldOffs += zionStride
tapeOffs++
}
outCnt++
if outCnt == zionStride {
break
}
fieldOffs = 0
tapeOffs = 0
}
}
return initShapeLen - len(shape), outCnt
}
// zionflatten unpacks the contents of buckets that match 'tape'
// into the corresponding vmref slices
//
// prerequisites:
// - len(fields) == len(tape)*zionStride
// - len(shape) > 0
// - len(tape) > 0
func zionflatten(shape []byte, buckets *zll.Buckets, fields []vmref, tape []ion.Symbol) (int, int) {
if globalOptimizationLevel >= OptimizationLevelAVX512V1 {
return zionFlattenAsm(shape, buckets, fields, tape)
}
return zionflattenReference(shape, buckets, fields, tape)
}