Debian Codegraph @

zstd/_generate/gen.go

raw
1 package main
2
3 //go:generate go run gen.go -out ../seqdec.s -arch amd64,arm64 -pkg=zstd
4
5 import (
6 "flag"
7 "fmt"
8 "runtime"
9
10 _ "github.com/klauspost/compress"
11
12 . "github.com/mmcloughlin/avo/build"
13 "github.com/mmcloughlin/avo/buildtags"
14 "github.com/mmcloughlin/avo/gotypes"
15 . "github.com/mmcloughlin/avo/operand"
16 "github.com/mmcloughlin/avo/reg"
17 )
18
19 // insert extra checks here and there.
20 const debug = false
21
22 // error reported when mo == 0 && ml > 0
23 const errorMatchLenOfsMismatch = 1
24
25 // error reported when ml > maxMatchLen
26 const errorMatchLenTooBig = 2
27
28 // error reported when mo > t or mo > s.windowSize
29 const errorMatchOffTooBig = 3
30
31 // error reported when the sum of literal lengths exceeds the literal buffer size
32 const errorNotEnoughLiterals = 4
33
34 // error reported when capacity of `out` is too small
35 const errorNotEnoughSpace = 5
36
37 // error reported when bits are overread.
38 const errorOverread = 6
39
40 const maxMatchLen = 131074
41
42 // compressedBlockOverAlloc mirrors the constant of the same name in the zstd
43 // package: the number of extra bytes callers over-allocate so the extended
44 // (16-byte-block) copies may overrun a run by up to this many bytes minus one.
45 const compressedBlockOverAlloc = 16
46
47 // size of struct seqVals
48 const seqValsSize = 24
49
50 func main() {
51 flag.Parse()
52
53 Constraint(buildtags.Not("appengine").ToConstraint())
54 Constraint(buildtags.Not("noasm").ToConstraint())
55 Constraint(buildtags.Term("gc").ToConstraint())
56 Constraint(buildtags.Not("noasm").ToConstraint())
57
58 o := options{
59 bmi2: false,
60 fiftysix: false,
61 useSeqs: true,
62 }
63 o.genDecodeSeqAsm("sequenceDecs_decode_amd64")
64 o.fiftysix = true
65 o.genDecodeSeqAsm("sequenceDecs_decode_56_amd64")
66 o.bmi2 = true
67 o.fiftysix = false
68 o.genDecodeSeqAsm("sequenceDecs_decode_bmi2")
69 o.fiftysix = true
70 o.genDecodeSeqAsm("sequenceDecs_decode_56_bmi2")
71
72 exec := executeSimple{
73 useSeqs: true,
74 safeMem: false,
75 }
76 exec.generateProcedure("sequenceDecs_executeSimple_amd64")
77 exec.safeMem = true
78 exec.generateProcedure("sequenceDecs_executeSimple_safe_amd64")
79
80 decodeSync := decodeSync{}
81 decodeSync.setBMI2(false)
82 decodeSync.generateProcedure("sequenceDecs_decodeSync_amd64")
83 decodeSync.setBMI2(true)
84 decodeSync.generateProcedure("sequenceDecs_decodeSync_bmi2")
85
86 decodeSync.execute.safeMem = true
87 decodeSync.setBMI2(false)
88 decodeSync.generateProcedure("sequenceDecs_decodeSync_safe_amd64")
89 decodeSync.setBMI2(true)
90 decodeSync.generateProcedure("sequenceDecs_decodeSync_safe_bmi2")
91
92 Generate()
93 }
94
95 func debugval(v Op) {
96 value := reg.R15
97 MOVQ(v, value)
98 INT(Imm(3))
99 }
100
101 func debugval32(v Op) {
102 value := reg.R15L
103 MOVL(v, value)
104 INT(Imm(3))
105 }
106
107 var assertCounter int
108
109 // assert will insert code if debug is enabled.
110 // The code should jump to 'ok' is assertion is success.
111 func assert(fn func(ok LabelRef)) {
112 if debug {
113 caller := [100]uintptr{0}
114 runtime.Callers(2, caller[:])
115 frame, _ := runtime.CallersFrames(caller[:]).Next()
116
117 ok := fmt.Sprintf("assert_check_%d_ok_srcline_%d", assertCounter, frame.Line)
118 fn(LabelRef(ok))
119 // Emit several since delve is imprecise.
120 INT(Imm(3))
121 INT(Imm(3))
122 Label(ok)
123 assertCounter++
124 }
125 }
126
127 type options struct {
128 bmi2 bool
129 fiftysix bool // Less than max 56 bits/loop
130 useSeqs bool // Generate code that uses the `seqs` auxiliary table
131 }
132
133 func (o options) genDecodeSeqAsm(name string) {
134 Package("github.com/klauspost/compress/zstd")
135 TEXT(name, 0, "func(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int")
136 Doc(name+" decodes a sequence", "")
137 Pragma("noescape")
138
139 nop := func(ctx *executeSingleTripleContext, handleLoop func()) {}
140
141 o.generateBody(name, nop)
142 }
143
144 func (o options) generateBody(name string, executeSingleTriple func(ctx *executeSingleTripleContext, handleLoop func())) {
145 // registers used by `decode`
146 brValue := GP64()
147 brBitsRead := GP64()
148 brOffset := GP64()
149 llState := GP64()
150 mlState := GP64()
151 ofState := GP64()
152 var seqBase reg.GPVirtual // allocated only when o.useSeqs is true
153
154 // values used by `execute` (allocated only when o.useSeqs is false)
155 ec := executeSingleTripleContext{}
156
157 // 1. load bitReader (done once)
158 brPointerStash := AllocLocal(8)
159 {
160 br := Dereference(Param("br"))
161 brPointer := GP64()
162 Load(br.Field("value"), brValue)
163 Load(br.Field("bitsRead"), brBitsRead)
164 Load(br.Field("in").Base(), brPointer)
165 Load(br.Field("cursor"), brOffset)
166 ADDQ(brOffset, brPointer) // Add current offset to read pointer.
167 MOVQ(brPointer, brPointerStash)
168 }
169
170 // 2. load states (done once)
171 var moP Mem
172 var mlP Mem
173 var llP Mem
174
175 {
176 ctx := Dereference(Param("ctx"))
177 Load(ctx.Field("llState"), llState)
178 Load(ctx.Field("mlState"), mlState)
179 Load(ctx.Field("ofState"), ofState)
180
181 if o.useSeqs {
182 seqBase = GP64()
183 Load(ctx.Field("seqs").Base(), seqBase)
184 moP = Mem{Base: seqBase, Disp: 2 * 8} // Pointer to current mo
185 mlP = Mem{Base: seqBase, Disp: 1 * 8} // Pointer to current ml
186 llP = Mem{Base: seqBase, Disp: 0 * 8} // Pointer to current ll
187 } else {
188 moP = AllocLocal(8)
189 mlP = AllocLocal(8)
190 llP = AllocLocal(8)
191 ec.moPtr = moP
192 ec.mlPtr = mlP
193 ec.llPtr = llP
194 zero := GP64()
195 XORQ(zero, zero)
196 MOVQ(zero, moP)
197 MOVQ(zero, mlP)
198 MOVQ(zero, llP)
199
200 ec.outBase = GP64()
201 ec.outEndPtr = AllocLocal(8)
202 ec.literals = GP64()
203 ec.outPosition = GP64()
204 ec.histLenPtr = AllocLocal(8)
205 ec.histBasePtr = AllocLocal(8)
206 ec.windowSizePtr = AllocLocal(8)
207
208 loadField := func(field gotypes.Component, target Mem) {
209 tmp := GP64()
210 Load(field, tmp)
211 MOVQ(tmp, target)
212 }
213
214 Load(ctx.Field("out").Base(), ec.outBase)
215 loadField(ctx.Field("out").Cap(), ec.outEndPtr)
216 Load(ctx.Field("literals").Base(), ec.literals)
217 Load(ctx.Field("outPosition"), ec.outPosition)
218 loadField(ctx.Field("windowSize"), ec.windowSizePtr)
219 loadField(ctx.Field("history").Base(), ec.histBasePtr)
220 loadField(ctx.Field("history").Len(), ec.histLenPtr)
221
222 {
223 tmp := GP64()
224 MOVQ(ec.histLenPtr, tmp)
225 ADDQ(tmp, ec.histBasePtr) // Note: we always copy from &hist[len(hist) - v]
226 }
227
228 Comment("Calculate pointer to s.out[cap(s.out)] (a past-end pointer)")
229 ADDQ(ec.outBase, ec.outEndPtr)
230
231 Comment("outBase += outPosition")
232 ADDQ(ec.outPosition, ec.outBase)
233
234 }
235 }
236
237 // Store previous offsets in registers.
238 var offsets [3]reg.GPVirtual
239 if o.useSeqs {
240 s := Dereference(Param("s"))
241 for i := range offsets {
242 offsets[i] = GP64()
243 po, err := s.Field("prevOffset").Index(i).Resolve()
244 if err != nil {
245 panic(err)
246 }
247
248 MOVQ(po.Addr, offsets[i])
249 }
250 }
251
252 // MAIN LOOP:
253 Label(name + "_main_loop")
254
255 {
256 brPointer := GP64()
257 MOVQ(brPointerStash, brPointer)
258
259 Comment("Fill bitreader to have enough for the offset and match length.")
260 o.bitreaderFill(name+"_fill", brValue, brBitsRead, brOffset, brPointer, LabelRef("error_overread"))
261
262 Comment("Update offset")
263 // Up to 32 extra bits
264 o.updateLength(name+"_of_update", brValue, brBitsRead, ofState, moP)
265
266 Comment("Update match length")
267 // Up to 16 extra bits
268 o.updateLength(name+"_ml_update", brValue, brBitsRead, mlState, mlP)
269
270 // If we need more than 56 in total, we must refill here.
271 if !o.fiftysix {
272 Comment("Fill bitreader to have enough for the remaining")
273 o.bitreaderFill(name+"_fill_2", brValue, brBitsRead, brOffset, brPointer, LabelRef("error_overread"))
274 }
275
276 Comment("Update literal length")
277 // Up to 16 bits
278 o.updateLength(name+"_ll_update", brValue, brBitsRead, llState, llP)
279
280 Comment("Fill bitreader for state updates")
281 MOVQ(brPointer, brPointerStash)
282 }
283
284 R14 := GP64()
285 if o.bmi2 {
286 tmp := GP64()
287 MOVQ(U32(8|(8<<8)), tmp)
288 BEXTRQ(tmp, ofState, R14)
289 } else {
290 MOVQ(ofState, R14) // copy ofState, its current value is needed below
291 SHRQ(U8(8), R14) // moB (from the ofState before its update)
292 MOVBQZX(R14.As8(), R14)
293 }
294
295 // Reload ctx
296 ctx := Dereference(Param("ctx"))
297 iteration, err := ctx.Field("iteration").Resolve()
298 if err != nil {
299 panic(err)
300 }
301 // if ctx.iteration != 0, do update
302 CMPQ(iteration.Addr, U8(0))
303 JZ(LabelRef(name + "_skip_update"))
304
305 // Update states, max tablelog 28
306 {
307 if o.bmi2 {
308 // Get total number of bits (it is safe, as nBits is <= 9, thus 3*9 < 255)
309 total := GP64()
310 LEAQ(Mem{Base: llState, Index: mlState, Scale: 1}, total)
311 ADDQ(ofState, total)
312 MOVBQZX(total.As8(), total) // total = llState.As8() + mlState.As8() + ofState.As8()
313
314 // Read `total` bits
315 bits := o.getBits(total, brValue, brBitsRead)
316
317 // Update states
318 Comment("Update Offset State")
319 {
320 nBits := ofState // Note: SHRXQ uses lower 6 bits of shift amount and BZHIQ lower 8 bits of count
321 lowBits := GP64()
322 BZHIQ(nBits, bits, lowBits) // lowBits = bits & ((1 << nBits) - 1))
323 SHRXQ(nBits, bits, bits) // bits >>= nBits
324 o.nextState(ofState, lowBits, "ofTable")
325 }
326 Comment("Update Match Length State")
327 {
328 nBits := mlState
329 lowBits := GP64()
330 BZHIQ(nBits, bits, lowBits) // lowBits = bits & ((1 << nBits) - 1))
331 SHRXQ(nBits, bits, bits) // lowBits >>= nBits
332 o.nextState(mlState, lowBits, "mlTable")
333 }
334 Comment("Update Literal Length State")
335 {
336 nBits := llState
337 lowBits := GP64()
338 BZHIQ(nBits, bits, lowBits) // lowBits = bits & ((1 << nBits) - 1))
339 o.nextState(llState, lowBits, "llTable")
340 }
341 } else {
342 Comment("Update Literal Length State")
343 o.updateState(llState, brValue, brBitsRead, "llTable")
344 Comment("Update Match Length State")
345 o.updateState(mlState, brValue, brBitsRead, "mlTable")
346 Comment("Update Offset State")
347 o.updateState(ofState, brValue, brBitsRead, "ofTable")
348 }
349 }
350 Label(name + "_skip_update")
351
352 Comment("Adjust offset")
353
354 var offset reg.GPVirtual
355 end := LabelRef(name + "_after_adjust")
356 if o.useSeqs {
357 offset = o.adjustOffset(name+"_adjust", moP, llP, R14, &offsets, end)
358 } else {
359 offset = o.adjustOffsetInMemory(name+"_adjust", moP, llP, R14, end)
360 }
361 Label(name + "_after_adjust")
362
363 MOVQ(offset, moP) // Store offset
364
365 Comment("Check values")
366 ml := GP64()
367 MOVQ(mlP, ml)
368 ll := GP64()
369 MOVQ(llP, ll)
370
371 // Update length
372 {
373 length := GP64()
374 LEAQ(Mem{Base: ml, Index: ll, Scale: 1}, length)
375 s := Dereference(Param("s"))
376 seqSizeP, err := s.Field("seqSize").Resolve()
377 if err != nil {
378 panic(err)
379 }
380 ADDQ(length, seqSizeP.Addr) // s.seqSize += ml + ll
381 }
382
383 // Reload ctx
384 ctx = Dereference(Param("ctx"))
385 litRemainP, err := ctx.Field("litRemain").Resolve()
386 if err != nil {
387 panic(err)
388 }
389 SUBQ(ll, litRemainP.Addr) // ctx.litRemain -= ll
390 JS(LabelRef("error_not_enough_literals"))
391 {
392 // if ml > maxMatchLen {
393 // return fmt.Errorf("match len (%d) bigger than max allowed length", ml)
394 // }
395 CMPQ(ml, U32(maxMatchLen))
396 JA(LabelRef(name + "_error_match_len_too_big"))
397 }
398 {
399 // if mo == 0 && ml > 0 {
400 // return fmt.Errorf("zero matchoff and matchlen (%d) > 0", ml)
401 // }
402 TESTQ(offset, offset)
403 JNZ(LabelRef(name + "_match_len_ofs_ok")) // mo != 0
404 TESTQ(ml, ml)
405 JNZ(LabelRef(name + "_error_match_len_ofs_mismatch"))
406 }
407
408 Label(name + "_match_len_ofs_ok")
409
410 if !o.useSeqs {
411 handleLoop := func() {
412 JMP(LabelRef("handle_loop"))
413 }
414
415 executeSingleTriple(&ec, handleLoop)
416 }
417
418 Label("handle_loop")
419 if o.useSeqs {
420 ADDQ(U8(seqValsSize), seqBase)
421 }
422 ctx = Dereference(Param("ctx"))
423 iterationP, err := ctx.Field("iteration").Resolve()
424 if err != nil {
425 panic(err)
426 }
427
428 DECQ(iterationP.Addr)
429 JNS(LabelRef(name + "_main_loop"))
430
431 Label("loop_finished")
432
433 // Store offsets
434 if o.useSeqs {
435 s := Dereference(Param("s"))
436 for i := range offsets {
437 po, _ := s.Field("prevOffset").Index(i).Resolve()
438 MOVQ(offsets[i], po.Addr)
439 }
440 }
441
442 // update bitreader state before returning
443 br := Dereference(Param("br"))
444 Store(brValue, br.Field("value"))
445 Store(brBitsRead.As8(), br.Field("bitsRead"))
446 Store(brOffset, br.Field("cursor"))
447
448 if !o.useSeqs {
449 Comment("Update the context")
450 ctx := Dereference(Param("ctx"))
451 Store(ec.outPosition, ctx.Field("outPosition"))
452
453 // compute litPosition
454 tmp := GP64()
455 Load(ctx.Field("literals").Base(), tmp)
456 SUBQ(tmp, ec.literals) // litPosition := current - initial literals pointer
457 Store(ec.literals, ctx.Field("litPosition"))
458 }
459
460 Comment("Return success")
461 o.returnWithCode(0)
462
463 Comment("Return with match length error")
464 {
465 Label(name + "_error_match_len_ofs_mismatch")
466 if !o.useSeqs {
467 tmp := GP64()
468 MOVQ(mlP, tmp)
469 ctx := Dereference(Param("ctx"))
470 Store(tmp, ctx.Field("ml"))
471 }
472 o.returnWithCode(errorMatchLenOfsMismatch)
473 }
474
475 Comment("Return with match too long error")
476 {
477 Label(name + "_error_match_len_too_big")
478 if !o.useSeqs {
479 ctx := Dereference(Param("ctx"))
480 tmp := GP64()
481 MOVQ(mlP, tmp)
482 Store(tmp, ctx.Field("ml"))
483 }
484 o.returnWithCode(errorMatchLenTooBig)
485 }
486
487 Comment("Return with match offset too long error")
488 {
489 Label("error_match_off_too_big")
490 if !o.useSeqs {
491 ctx := Dereference(Param("ctx"))
492 tmp := GP64()
493 MOVQ(moP, tmp)
494 Store(tmp, ctx.Field("mo"))
495 Store(ec.outPosition, ctx.Field("outPosition"))
496 }
497 o.returnWithCode(errorMatchOffTooBig)
498 }
499
500 Comment("Return with not enough literals error")
501 {
502 Label("error_not_enough_literals")
503 if !o.useSeqs {
504 ctx := Dereference(Param("ctx"))
505 tmp := GP64()
506 MOVQ(llP, tmp)
507 Store(tmp, ctx.Field("ll"))
508 }
509 // Note: the `litRemain` field is updated in-place (for both useSeqs values)
510
511 o.returnWithCode(errorNotEnoughLiterals)
512 }
513
514 Comment("Return with overread error")
515 {
516 Label("error_overread")
517 o.returnWithCode(errorOverread)
518 }
519
520 if !o.useSeqs {
521 Comment("Return with not enough output space error")
522 Label("error_not_enough_space")
523 {
524 ctx := Dereference(Param("ctx"))
525 tmp := GP64()
526 MOVQ(llP, tmp)
527 Store(tmp, ctx.Field("ll"))
528 MOVQ(mlP, tmp)
529 Store(tmp, ctx.Field("ml"))
530 Store(ec.outPosition, ctx.Field("outPosition"))
531
532 o.returnWithCode(errorNotEnoughSpace)
533 }
534 }
535 }
536
537 func (o options) returnWithCode(returnCode uint32) {
538 a, err := ReturnIndex(0).Resolve()
539 if err != nil {
540 panic(err)
541 }
542 MOVQ(U32(returnCode), a.Addr)
543 RET()
544 }
545
546 // bitreaderFill will make sure at least 56 bits are available.
547 func (o options) bitreaderFill(name string, brValue, brBitsRead, brOffset, brPointer reg.GPVirtual, overread LabelRef) {
548 // bitreader_fill begin
549 CMPQ(brOffset, U8(8)) // b.off >= 8
550 JL(LabelRef(name + "_byte_by_byte"))
551
552 off := GP64()
553 MOVQ(brBitsRead, off)
554 SHRQ(U8(3), off) // off = brBitsRead / 8
555 SUBQ(off, brPointer) // brPointer = brPointer - off
556 MOVQ(Mem{Base: brPointer}, brValue) // brValue = brPointer[0]
557 SUBQ(off, brOffset) // brOffset = brOffset - off
558 ANDQ(U8(7), brBitsRead) // brBitsRead = brBitsRead & 7
559 JMP(LabelRef(name + "_end"))
560
561 Label(name + "_byte_by_byte")
562 CMPQ(brOffset, U8(0)) /* for b.off > 0 */
563 JLE(LabelRef(name + "_check_overread"))
564
565 CMPQ(brBitsRead, U8(7)) /* for brBitsRead > 7 */
566 JLE(LabelRef(name + "_end"))
567
568 SHLQ(U8(8), brValue) /* b.value << 8 | uint8(mem) */
569 SUBQ(U8(1), brPointer)
570 SUBQ(U8(1), brOffset)
571 SUBQ(U8(8), brBitsRead)
572
573 if false {
574 // Appears slightly worse (AMD Zen2)
575 MOVB(Mem{Base: brPointer}, brValue.As8L())
576 } else {
577 tmp := GP64()
578 MOVBQZX(Mem{Base: brPointer}, tmp)
579 ORQ(tmp, brValue)
580 }
581 JMP(LabelRef(name + "_byte_by_byte"))
582
583 Label(name + "_check_overread")
584 CMPQ(brBitsRead, U8(64))
585 JA(overread)
586
587 Label(name + "_end")
588 }
589
590 func (o options) updateLength(name string, brValue, brBitsRead, state reg.GPVirtual, out Mem) {
591 if o.bmi2 {
592 DX := GP64()
593 extr := GP64()
594 MOVQ(U32(8|(8<<8)), extr)
595 BEXTRQ(extr, state, DX) // addBits = (state >> 8) &xff
596 BX := GP64()
597 MOVQ(brValue, BX)
598 // TODO: We should be able to extra bits with BEXTRQ
599 CX := reg.CL
600 LEAQ(Mem{Base: brBitsRead, Index: DX, Scale: 1}, CX.As64()) // CX: shift = r.bitsRead + n
601 ROLQ(CX, BX)
602 BZHIQ(DX.As64(), BX, BX)
603 MOVQ(CX.As64(), brBitsRead) // br.bitsRead += moB
604 res := GP64() // AX
605 MOVQ(state, res)
606 SHRQ(U8(32), res) // AX = mo (ofState.baselineInt(), that's the higher dword of moState)
607 ADDQ(BX, res) // AX - mo + br.getBits(moB)
608 MOVQ(res, out)
609 } else {
610 BX := GP64()
611 CX := reg.CL
612 AX := reg.RAX
613 MOVQ(state, AX.As64()) // So we can grab high bytes.
614 MOVQ(brBitsRead, CX.As64())
615 MOVQ(brValue, BX)
616 SHLQ(CX, BX) // BX = br.value << br.bitsRead (part of getBits)
617 // Zero-extending write: the full CX must equal addBits below, which a
618 // MOVB into CL only achieves because brBitsRead <= 64 leaves the upper
619 // bits zero. MOVBLZX is unconditionally correct, avoids the
620 // partial-register merge, and lowers to a single fresh UBFX on arm64.
621 MOVBLZX(AX.As8H(), CX.As32()) // CX = moB (ofState.addBits(), that is byte #1 of moState)
622 SHRQ(U8(32), AX) // AX = mo (ofState.baselineInt(), that's the higher dword of moState)
623 // If addBits == 0, skip
624 TESTQ(CX.As64(), CX.As64())
625 JZ(LabelRef(name + "_zero"))
626
627 ADDQ(CX.As64(), brBitsRead) // br.bitsRead += n (part of getBits)
628 // If overread, skip
629 CMPQ(brBitsRead, U8(64))
630 JA(LabelRef(name + "_zero"))
631 CMPQ(CX.As64(), U8(64))
632 JAE(LabelRef(name + "_zero"))
633
634 NEGQ(CX.As64()) // CX = 64 - n
635 SHRQ(CX, BX) // BX = (br.value << br.bitsRead) >> (64 - n) -- getBits() result
636 ADDQ(BX, AX) // AX - mo + br.getBits(moB)
637
638 Label(name + "_zero")
639 MOVQ(AX, out) // Store result
640 }
641 }
642
643 func (o options) updateState(state, brValue, brBitsRead reg.GPVirtual, table string) {
644 AX := GP64()
645 MOVBQZX(state.As8(), AX) // AX = nBits
646 // Check we have a reasonable nBits
647 assert(func(ok LabelRef) {
648 CMPQ(AX, U8(9))
649 JBE(ok)
650 })
651
652 DX := GP64()
653 MOVL(state.As32(), DX.As32()) // Clear the top 32 bits.
654 SHRL(U8(16), DX.As32())
655
656 {
657 lowBits := o.getBits(AX, brValue, brBitsRead)
658 // Check if below tablelog
659 assert(func(ok LabelRef) {
660 CMPQ(lowBits, U32(512))
661 JB(ok)
662 })
663 ADDQ(lowBits, DX)
664 }
665
666 // Load table pointer
667 tablePtr := GP64()
668 Comment("Load ctx." + table)
669 ctx := Dereference(Param("ctx"))
670 tableA, err := ctx.Field(table).Base().Resolve()
671 if err != nil {
672 panic(err)
673 }
674 MOVQ(tableA.Addr, tablePtr)
675
676 // Check if below tablelog
677 assert(func(ok LabelRef) {
678 CMPQ(DX, U32(512))
679 JB(ok)
680 })
681 // Load new state
682 MOVQ(Mem{Base: tablePtr, Index: DX, Scale: 8}, state)
683 }
684
685 func (o options) nextState(state, lowBits reg.GPVirtual, table string) {
686 DX := GP64()
687 MOVL(state.As32(), DX.As32()) // Clear the top 32 bits.
688 SHRL(U8(16), DX.As32())
689
690 ADDQ(lowBits, DX)
691
692 // Load table pointer
693 tablePtr := GP64()
694 Comment("Load ctx." + table)
695 ctx := Dereference(Param("ctx"))
696 tableA, err := ctx.Field(table).Base().Resolve()
697 if err != nil {
698 panic(err)
699 }
700 MOVQ(tableA.Addr, tablePtr)
701
702 // Check if below tablelog
703 assert(func(ok LabelRef) {
704 CMPQ(DX, U32(512))
705 JB(ok)
706 })
707 // Load new state
708 MOVQ(Mem{Base: tablePtr, Index: DX, Scale: 8}, state)
709 }
710
711 // getBits will return nbits bits from brValue.
712 func (o options) getBits(nBits, brValue, brBitsRead reg.GPVirtual) reg.GPVirtual {
713 BX := GP64()
714 CX := reg.CL
715
716 LEAQ(Mem{Base: brBitsRead, Index: nBits, Scale: 1}, CX.As64())
717 MOVQ(brValue, BX)
718 MOVQ(CX.As64(), brBitsRead)
719 ROLQ(CX, BX)
720
721 // BX &= (1<<nBits) - 1
722 if o.bmi2 {
723 BZHIQ(nBits, BX, BX)
724 } else {
725 mask := GP32()
726 MOVL(U32(1), mask)
727 // Zero-extending write rather than a MOVB into CL: SHLL only reads CL,
728 // but the partial write would merge into the stale RCX (the bitsRead
729 // sum from the LEAQ above) and lower to a UBFX+BFI read-modify-write
730 // pair on arm64; MOVBLZX is a fresh def on both.
731 MOVBLZX(nBits.As8(), CX.As32())
732 SHLL(CX, mask)
733 DECL(mask)
734 ANDQ(mask.As64(), BX)
735 }
736 return BX
737 }
738
739 func (o options) adjustOffset(name string, moP, llP Mem, offsetB reg.GPVirtual, offsets *[3]reg.GPVirtual, end LabelRef) (offset reg.GPVirtual) {
740 offset = GP64()
741 MOVQ(moP, offset)
742 {
743 // if offsetB > 1 {
744 // s.prevOffset[2] = s.prevOffset[1]
745 // s.prevOffset[1] = s.prevOffset[0]
746 // s.prevOffset[0] = offset
747 // return offset
748 // }
749 CMPQ(offsetB, U8(1))
750 JBE(LabelRef(name + "_offsetB_1_or_0"))
751
752 MOVQ(offsets[1], offsets[2]) // s.prevOffset[2] = s.prevOffset[1]
753 MOVQ(offsets[0], offsets[1]) // s.prevOffset[1] = s.prevOffset[0]
754 MOVQ(offset, offsets[0]) // s.prevOffset[0] = offset
755 JMP(end)
756 }
757
758 Label(name + "_offsetB_1_or_0")
759 // if litLen == 0 {
760 // offset++
761 // }
762 {
763 if true {
764 CMPQ(llP, U32(0))
765 JNE(LabelRef(name + "_offset_maybezero"))
766 INCQ(offset)
767 JMP(LabelRef(name + "_offset_nonzero"))
768 } else {
769 // No idea why this doesn't work:
770 tmp := GP64()
771 LEAQ(Mem{Base: offset, Disp: 1}, tmp)
772 CMPQ(llP, U32(0))
773 CMOVQEQ(tmp, offset)
774 }
775
776 // if offset == 0 {
777 // return s.prevOffset[0]
778 // }
779 {
780 Label(name + "_offset_maybezero")
781 TESTQ(offset, offset)
782 JNZ(LabelRef(name + "_offset_nonzero"))
783 MOVQ(offsets[0], offset)
784 JMP(end)
785 }
786 }
787 Label(name + "_offset_nonzero")
788 {
789 // if offset == 3 {
790 // temp = s.prevOffset[0] - 1
791 // } else {
792 // temp = s.prevOffset[offset]
793 // }
794 temp := GP64()
795 CMPQ(offset, U8(1))
796 JB(LabelRef(name + "_zero"))
797 JEQ(LabelRef(name + "_one"))
798 CMPQ(offset, U8(2))
799 JA(LabelRef(name + "_three"))
800 JMP(LabelRef(name + "_two"))
801
802 Label(name + "_zero")
803 MOVQ(offsets[0], temp)
804 JMP(LabelRef(name + "_test_temp_valid"))
805
806 Label(name + "_one")
807 MOVQ(offsets[1], temp)
808 JMP(LabelRef(name + "_test_temp_valid"))
809
810 Label(name + "_two")
811 MOVQ(offsets[2], temp)
812 JMP(LabelRef(name + "_test_temp_valid"))
813
814 Label(name + "_three")
815 LEAQ(Mem{Base: offsets[0], Disp: -1}, temp)
816
817 Label(name + "_test_temp_valid")
818 // if temp == 0 {
819 // temp = 1
820 // }
821 TESTQ(temp, temp)
822 JNZ(LabelRef(name + "_temp_valid"))
823 MOVQ(U32(1), temp)
824
825 Label(name + "_temp_valid")
826 // if offset != 1 {
827 // s.prevOffset[2] = s.prevOffset[1]
828 // }
829 CMPQ(offset, U8(1))
830 if false {
831 JZ(LabelRef(name + "_skip"))
832 MOVQ(offsets[1], offsets[2]) // s.prevOffset[2] = s.prevOffset[1]
833 Label(name + "_skip")
834 } else {
835 CMOVQNE(offsets[1], offsets[2])
836 }
837 // s.prevOffset[1] = s.prevOffset[0]
838 // s.prevOffset[0] = temp
839 MOVQ(offsets[0], offsets[1])
840 MOVQ(temp, offsets[0])
841 MOVQ(temp, offset) // return temp
842 }
843 JMP(end)
844 return offset
845 }
846
847 // adjustOffsetInMemory is an adjustOffset version that does not cache prevOffset values in registers.
848 // It fetches and stores values directly into the fields of `sequenceDecs` structure.
849 func (o options) adjustOffsetInMemory(name string, moP, llP Mem, offsetB reg.GPVirtual, end LabelRef) (offset reg.GPVirtual) {
850 s := Dereference(Param("s"))
851
852 po0, _ := s.Field("prevOffset").Index(0).Resolve()
853 po1, _ := s.Field("prevOffset").Index(1).Resolve()
854 po2, _ := s.Field("prevOffset").Index(2).Resolve()
855 offset = GP64()
856 MOVQ(moP, offset)
857 {
858 // if offsetB > 1 {
859 // s.prevOffset[2] = s.prevOffset[1]
860 // s.prevOffset[1] = s.prevOffset[0]
861 // s.prevOffset[0] = offset
862 // return offset
863 // }
864 CMPQ(offsetB, U8(1))
865 JBE(LabelRef(name + "_offsetB_1_or_0"))
866
867 tmp := XMM()
868 MOVUPS(po0.Addr, tmp) // tmp = (s.prevOffset[0], s.prevOffset[1])
869 MOVQ(offset, po0.Addr) // s.prevOffset[0] = offset
870 MOVUPS(tmp, po1.Addr) // s.prevOffset[1], s.prevOffset[2] = s.prevOffset[0], s.prevOffset[1]
871 JMP(end)
872 }
873
874 Label(name + "_offsetB_1_or_0")
875 // if litLen == 0 {
876 // offset++
877 // }
878
879 {
880 CMPQ(llP, U32(0))
881 JNE(LabelRef(name + "_offset_maybezero"))
882 INCQ(offset)
883 JMP(LabelRef(name + "_offset_nonzero"))
884
885 // if offset == 0 {
886 // return s.prevOffset[0]
887 // }
888 {
889 Label(name + "_offset_maybezero")
890 TESTQ(offset, offset)
891 JNZ(LabelRef(name + "_offset_nonzero"))
892 MOVQ(po0.Addr, offset)
893 JMP(end)
894 }
895 }
896 Label(name + "_offset_nonzero")
897 {
898 // Offset must be 1 -> 3
899 assert(func(ok LabelRef) {
900 // Test is above or equal (shouldn't be equal)
901 CMPQ(offset, U32(0))
902 JAE(ok)
903 })
904 assert(func(ok LabelRef) {
905 // Check if Above 0.
906 CMPQ(offset, U32(0))
907 JA(ok)
908 })
909 assert(func(ok LabelRef) {
910 // Check if Below or Equal to 3.
911 CMPQ(offset, U32(3))
912 JBE(ok)
913 })
914 // if offset == 3 {
915 // temp = s.prevOffset[0] - 1
916 // } else {
917 // temp = s.prevOffset[offset]
918 // }
919 //
920 // this if got transformed into:
921 //
922 // ofs := offset
923 // shift := 0
924 // if offset == 3 {
925 // ofs = 0
926 // shift = -1
927 // }
928 // temp := s.prevOffset[ofs] + shift
929 // TODO: This should be easier...
930 CX, DX, R15 := GP64(), GP64(), GP64()
931 MOVQ(offset, CX)
932 XORQ(DX, DX)
933 MOVQ(I32(-1), R15)
934 CMPQ(offset, U8(3))
935 CMOVQEQ(DX, CX)
936 CMOVQEQ(R15, DX)
937 assert(func(ok LabelRef) {
938 CMPQ(CX, U32(0))
939 JAE(ok)
940 })
941 assert(func(ok LabelRef) {
942 CMPQ(CX, U32(3))
943 JB(ok)
944 })
945 if po0.Addr.Index != nil {
946 // Use temporary (not currently needed)
947 prevOffset := GP64()
948 LEAQ(po0.Addr, prevOffset) // &prevOffset[0]
949 ADDQ(Mem{Base: prevOffset, Index: CX, Scale: 8}, DX)
950 } else {
951 ADDQ(Mem{Base: po0.Addr.Base, Disp: po0.Addr.Disp, Index: CX, Scale: 8}, DX)
952 }
953
954 temp := DX
955 // if temp == 0 {
956 // temp = 1
957 // }
958 JNZ(LabelRef(name + "_temp_valid"))
959 MOVQ(U32(1), temp)
960
961 Label(name + "_temp_valid")
962 // if offset != 1 {
963 // s.prevOffset[2] = s.prevOffset[1]
964 // }
965 CMPQ(offset, U8(1))
966 JZ(LabelRef(name + "_skip"))
967 tmp := GP64()
968 MOVQ(po1.Addr, tmp)
969 MOVQ(tmp, po2.Addr) // s.prevOffset[2] = s.prevOffset[1]
970
971 Label(name + "_skip")
972 // s.prevOffset[1] = s.prevOffset[0]
973 // s.prevOffset[0] = temp
974 tmp = GP64()
975 MOVQ(po0.Addr, tmp)
976 MOVQ(tmp, po1.Addr) // s.prevOffset[1] = s.prevOffset[0]
977 MOVQ(temp, po0.Addr) // s.prevOffset[0] = temp
978 MOVQ(temp, offset) // return temp
979 }
980 JMP(end)
981 return offset
982 }
983
984 type executeSimple struct {
985 useSeqs bool // Generate code that uses the `seqs` auxiliary table
986 safeMem bool
987 }
988
989 func (e executeSimple) generateProcedure(name string) {
990 Package("github.com/klauspost/compress/zstd")
991 TEXT(name, 0, "func (ctx *executeAsmContext) bool")
992 Doc(name+" implements the main loop of sequenceDecs.decode in x86 asm", "")
993 Pragma("noescape")
994
995 seqsBase := GP64()
996 seqsLen := GP64()
997 seqIndex := GP64()
998 outBase := GP64()
999 literals := GP64()
1000 outPosition := GP64()
1001 windowSize := GP64()
1002 histBase := GP64()
1003 histLen := GP64()
1004
1005 {
1006 ctx := Dereference(Param("ctx"))
1007 tmp := GP64()
1008 Load(ctx.Field("seqs").Len(), seqsLen)
1009 TESTQ(seqsLen, seqsLen)
1010 JZ(LabelRef("empty_seqs"))
1011 Load(ctx.Field("seqs").Base(), seqsBase)
1012 Load(ctx.Field("seqIndex"), seqIndex)
1013 Load(ctx.Field("out").Base(), outBase)
1014 Load(ctx.Field("literals").Base(), literals)
1015 Load(ctx.Field("outPosition"), outPosition)
1016 Load(ctx.Field("windowSize"), windowSize)
1017 Load(ctx.Field("history").Base(), histBase)
1018 Load(ctx.Field("history").Len(), histLen)
1019
1020 ADDQ(histLen, histBase) // Note: we always copy from &hist[len(hist) - v]
1021
1022 Comment("seqsBase += 24 * seqIndex")
1023 LEAQ(Mem{Base: seqIndex, Index: seqIndex, Scale: 2}, tmp) // * 3
1024 SHLQ(U8(3), tmp) // * 8
1025 ADDQ(tmp, seqsBase)
1026
1027 Comment("outBase += outPosition")
1028 ADDQ(outPosition, outBase)
1029 }
1030
1031 Label("main_loop")
1032
1033 moPtr := Mem{Base: seqsBase, Disp: 2 * 8}
1034 mlPtr := Mem{Base: seqsBase, Disp: 1 * 8}
1035 llPtr := Mem{Base: seqsBase, Disp: 0 * 8}
1036
1037 // generates the loop tail
1038 handleLoop := func() {
1039 ADDQ(U8(seqValsSize), seqsBase) // seqs += sizeof(seqVals)
1040 INCQ(seqIndex)
1041 CMPQ(seqIndex, seqsLen)
1042 JB(LabelRef("main_loop"))
1043 }
1044
1045 ctx := executeSingleTripleContext{
1046 llPtr: llPtr,
1047 moPtr: moPtr,
1048 mlPtr: mlPtr,
1049 literals: literals,
1050 outBase: outBase,
1051 outPosition: outPosition,
1052 histBase: histBase,
1053 histLen: histLen,
1054 windowSize: windowSize,
1055 }
1056
1057 e.executeSingleTriple(&ctx, handleLoop)
1058
1059 Label("handle_loop")
1060 handleLoop()
1061
1062 ret, err := ReturnIndex(0).Resolve()
1063 if err != nil {
1064 panic(err)
1065 }
1066
1067 returnValue := func(val int) {
1068
1069 Comment("Return value")
1070 MOVB(U8(val), ret.Addr)
1071
1072 Comment("Update the context")
1073 ctx := Dereference(Param("ctx"))
1074 Store(seqIndex, ctx.Field("seqIndex"))
1075 Store(outPosition, ctx.Field("outPosition"))
1076
1077 // litPosition := current - initial literals pointer
1078 litField, _ := ctx.Field("literals").Base().Resolve()
1079 SUBQ(litField.Addr, literals)
1080 Store(literals, ctx.Field("litPosition"))
1081 }
1082 Label("loop_finished")
1083 returnValue(1)
1084 RET()
1085
1086 Label("error_match_off_too_big")
1087 returnValue(0)
1088 RET()
1089
1090 Label("empty_seqs")
1091 Comment("Return value")
1092 MOVB(U8(1), ret.Addr)
1093 RET()
1094 }
1095
1096 type executeSingleTripleContext struct {
1097 // common values
1098 llPtr Mem
1099 moPtr Mem
1100 mlPtr Mem
1101
1102 literals reg.GPVirtual
1103 outBase reg.GPVirtual
1104 outPosition reg.GPVirtual
1105
1106 // values used when useSeqs is true
1107 histBase reg.GPVirtual
1108 histLen reg.GPVirtual
1109 windowSize reg.GPVirtual
1110
1111 // values used when useSeqs is false
1112 outEndPtr Mem // pointer to s.out[cap(s.out)]
1113 histBasePtr Mem
1114 histLenPtr Mem
1115 windowSizePtr Mem
1116 }
1117
1118 // executeSingleTriple performs copy from literals and history according
1119 // to the decoded values ll, mo and ml.
1120 func (e executeSimple) executeSingleTriple(c *executeSingleTripleContext, handleLoop func()) {
1121 ll := GP64()
1122 MOVQ(c.llPtr, ll)
1123 mo := GP64()
1124 MOVQ(c.moPtr, mo)
1125 ml := GP64()
1126 MOVQ(c.mlPtr, ml)
1127
1128 if !e.useSeqs {
1129 Comment("Check if we have enough space in s.out")
1130 {
1131 // baseAfterCopy = ll + ml + c.outBase (+ compressedBlockOverAlloc
1132 // on the unsafe path, folded into the LEAQ displacement below).
1133 //
1134 // The extended copies below write in 16-byte blocks and overrun
1135 // the logical end by up to compressedBlockOverAlloc-1 bytes.
1136 // Reserve that margin so the overrun stays within cap(s.out);
1137 // otherwise a stream whose decoded length lands inside the
1138 // over-allocation slack passes this check yet writes past cap.
1139 addMargin := 0
1140 if !e.safeMem {
1141 addMargin = compressedBlockOverAlloc
1142 }
1143 baseAfterCopy := GP64()
1144 LEAQ(Mem{Base: ll, Index: ml, Scale: 1, Disp: addMargin}, baseAfterCopy)
1145 ADDQ(c.outBase, baseAfterCopy)
1146 CMPQ(baseAfterCopy, c.outEndPtr)
1147 JA(LabelRef("error_not_enough_space"))
1148 }
1149 }
1150
1151 Comment("Copy literals")
1152 Label("copy_literals")
1153 {
1154 TESTQ(ll, ll)
1155 JZ(LabelRef("check_offset"))
1156 // TODO: Investigate if it is possible to consistently overallocate literals.
1157 if e.safeMem {
1158 e.copyMemoryPrecise("1", c.literals, c.outBase, ll, 1)
1159 } else {
1160 e.copyMemoryND("1", c.literals, c.outBase, ll)
1161 ADDQ(ll, c.literals)
1162 ADDQ(ll, c.outBase)
1163 }
1164 ADDQ(ll, c.outPosition)
1165 }
1166
1167 Comment("Malformed input if seq.mo > t+len(hist) || seq.mo > s.windowSize)")
1168 {
1169 Label("check_offset")
1170
1171 tmp := GP64()
1172 if e.useSeqs {
1173 LEAQ(Mem{Base: c.outPosition, Index: c.histLen, Scale: 1}, tmp)
1174 } else {
1175 MOVQ(c.outPosition, tmp)
1176 ADDQ(c.histLenPtr, tmp)
1177 }
1178 CMPQ(mo, tmp)
1179 JG(LabelRef("error_match_off_too_big"))
1180
1181 if e.useSeqs {
1182 CMPQ(mo, c.windowSize)
1183 } else {
1184 CMPQ(mo, c.windowSizePtr)
1185 }
1186 JG(LabelRef("error_match_off_too_big"))
1187 }
1188
1189 Comment("Copy match from history")
1190 {
1191 v := GP64()
1192 MOVQ(mo, v)
1193
1194 // v := seq.mo - outPosition
1195 SUBQ(c.outPosition, v)
1196 JLS(LabelRef("copy_match")) // do nothing if v <= 0
1197
1198 // v := seq.mo - t; v > 0 {
1199 // start := len(hist) - v
1200 // ...
1201 // }
1202 assert(func(ok LabelRef) {
1203 if e.useSeqs {
1204 TESTQ(c.histLen, c.histLen)
1205 } else {
1206 t := GP64()
1207 MOVQ(c.histLenPtr, t)
1208 TESTQ(t, t)
1209 }
1210 JNZ(ok)
1211 })
1212 ptr := GP64()
1213 if e.useSeqs {
1214 MOVQ(c.histBase, ptr)
1215 } else {
1216 MOVQ(c.histBasePtr, ptr)
1217 }
1218 SUBQ(v, ptr) // ptr := &hist[len(hist) - v]
1219 CMPQ(ml, v)
1220 JG(LabelRef("copy_all_from_history"))
1221 /* if ml <= v {
1222 copy(out[outPosition:], hist[start:start+seq.ml])
1223 t += seq.ml
1224 continue
1225 }
1226 */
1227 // We know ml will be at least 3, since we didn't copy anything yet.
1228 e.copyMemoryPrecise("4", ptr, c.outBase, ml, 3)
1229 ADDQ(ml, c.outPosition)
1230 // Note: for the current go tests this branch is taken in 99.53% cases,
1231 // this is why we repeat a little code here.
1232 handleLoop()
1233 JMP(LabelRef("loop_finished"))
1234
1235 Label("copy_all_from_history")
1236 /* if seq.ml > v {
1237 // Some goes into current block.
1238 // Copy remainder of history
1239 copy(out[outPosition:], hist[start:])
1240 outPosition += v
1241 seq.ml -= v
1242 }
1243 */
1244 e.copyMemoryPrecise("5", ptr, c.outBase, v, 1)
1245 ADDQ(v, c.outPosition)
1246 SUBQ(v, ml)
1247 // ml cannot be 0, since we only jump here is ml > v.
1248 // Copy rest from current block.
1249 }
1250
1251 Comment("Copy match from the current buffer")
1252 Label("copy_match")
1253 {
1254 src := GP64()
1255 MOVQ(c.outBase, src)
1256 SUBQ(mo, src) // src = &s.out[t - mo]
1257
1258 // start := t - mo
1259 // if ml <= t-start {
1260 // // no overlap
1261 // } else {
1262 // // overlapping copy
1263 // }
1264 //
1265 // Note: ml <= t - start
1266 // ml <= t - (t - mo)
1267 // ml <= mo
1268 Comment("ml <= mo")
1269 CMPQ(ml, mo)
1270 JA(LabelRef("copy_overlapping_match"))
1271
1272 Comment("Copy non-overlapping match")
1273 {
1274 ADDQ(ml, c.outPosition)
1275 if e.safeMem {
1276 e.copyMemoryPrecise("2", src, c.outBase, ml, 1)
1277 } else {
1278 dst := GP64()
1279 MOVQ(c.outBase, dst)
1280 ADDQ(ml, c.outBase)
1281 e.copyMemory("2", src, dst, ml)
1282 }
1283
1284 JMP(LabelRef("handle_loop"))
1285 }
1286
1287 Comment("Copy overlapping match")
1288 Label("copy_overlapping_match")
1289 {
1290 ADDQ(ml, c.outPosition)
1291 e.copyOverlappedMemory("3", src, c.outBase, ml)
1292 }
1293 }
1294 }
1295
1296 // copyMemory will copy memory in blocks of 16 bytes,
1297 // overwriting up to 15 extra bytes.
1298 // src and dst are updated. length will be zero or less.
1299 func (e executeSimple) copyMemory(suffix string, src, dst, length reg.GPVirtual) {
1300 label := "copy_" + suffix
1301
1302 Label(label)
1303 t := XMM()
1304 MOVUPS(Mem{Base: src}, t)
1305 MOVUPS(t, Mem{Base: dst})
1306 ADDQ(U8(16), src)
1307 ADDQ(U8(16), dst)
1308 SUBQ(U8(16), length)
1309 // jump if (CF == 0 and ZF == 0).
1310 JHI(LabelRef(label))
1311 }
1312
1313 // copyMemoryND will copy memory in blocks of 16 bytes,
1314 // overwriting up to 15 extra bytes.
1315 // All parameters are preserved.
1316 func (e executeSimple) copyMemoryND(suffix string, src, dst, length reg.GPVirtual) {
1317 label := "copy_" + suffix
1318
1319 ofs := GP64()
1320 s := Mem{Base: src, Index: ofs, Scale: 1}
1321 d := Mem{Base: dst, Index: ofs, Scale: 1}
1322
1323 XORQ(ofs, ofs)
1324 Label(label)
1325 t := XMM()
1326 MOVUPS(s, t)
1327 MOVUPS(t, d)
1328 ADDQ(U8(16), ofs)
1329 CMPQ(ofs, length)
1330 JB(LabelRef(label))
1331 }
1332
1333 // copyMemoryPrecise will copy memory in blocks of 16 bytes,
1334 // without overreading. It adds length to src and dst,
1335 // preserving length.
1336 func (e executeSimple) copyMemoryPrecise(suffix string, src, dst, length reg.GPVirtual, minLength int) {
1337 assert(func(ok LabelRef) {
1338 // if length >= minLength, ok
1339 CMPQ(length, U8(minLength))
1340 JAE(ok)
1341 })
1342 if minLength == 0 {
1343 TESTQ(length, length)
1344 JZ(LabelRef("copy_" + suffix + "_end"))
1345 }
1346 n := GP64()
1347 MOVQ(length, n)
1348 SUBQ(U8(16), n)
1349 JB(LabelRef("copy_" + suffix + "_small"))
1350
1351 // If length >= 16, copy blocks of 16 bytes and handle any remainder
1352 // by a block copy that overlaps with the last full block.
1353 {
1354 t := XMM()
1355
1356 loop := "copy_" + suffix + "_loop"
1357 Label(loop)
1358 {
1359 MOVUPS(Mem{Base: src}, t)
1360 MOVUPS(t, Mem{Base: dst})
1361 ADDQ(U8(16), src)
1362 ADDQ(U8(16), dst)
1363 SUBQ(U8(16), n)
1364 JAE(LabelRef(loop))
1365 }
1366
1367 // n is now the range [-16,-1].
1368 // -16 means we copy the entire last block again.
1369 // That should happen about 1/16th of the time,
1370 // so we don't bother to check for it.
1371 LEAQ(Mem{Base: src, Index: n, Disp: 16, Scale: 1}, src)
1372 LEAQ(Mem{Base: dst, Index: n, Disp: 16, Scale: 1}, dst)
1373 MOVUPS(Mem{Base: src, Disp: -16}, t)
1374 MOVUPS(t, Mem{Base: dst, Disp: -16})
1375
1376 JMP(LabelRef("copy_" + suffix + "_end"))
1377 }
1378
1379 Label("copy_" + suffix + "_small")
1380 {
1381 name := "copy_" + suffix + "_"
1382 end := LabelRef("copy_" + suffix + "_end")
1383 CMPQ(length, U8(3))
1384 JE(LabelRef(name + "move_3"))
1385 if minLength < 3 {
1386 JB(LabelRef(name + "move_1or2"))
1387 }
1388 CMPQ(length, U8(8))
1389 JB(LabelRef(name + "move_4through7"))
1390 JMP(LabelRef(name + "move_8through16"))
1391 AX, CX := GP64(), GP64()
1392
1393 if minLength < 3 {
1394 Label(name + "move_1or2")
1395 MOVB(Mem{Base: src}, AX.As8())
1396 MOVB(Mem{Base: src, Disp: -1, Index: length, Scale: 1}, CX.As8())
1397 MOVB(AX.As8(), Mem{Base: dst})
1398 MOVB(CX.As8(), Mem{Base: dst, Disp: -1, Index: length, Scale: 1})
1399 ADDQ(length, src)
1400 ADDQ(length, dst)
1401 JMP(end)
1402 }
1403
1404 Label(name + "move_3")
1405 MOVWQZX(Mem{Base: src}, AX.As64())
1406 MOVB(Mem{Base: src, Disp: 2}, CX.As8())
1407 MOVW(AX.As16(), Mem{Base: dst})
1408 MOVB(CX.As8(), Mem{Base: dst, Disp: 2})
1409 ADDQ(length, src)
1410 ADDQ(length, dst)
1411 JMP(end)
1412
1413 Label(name + "move_4through7")
1414 MOVL(Mem{Base: src}, AX.As32())
1415 MOVL(Mem{Base: src, Disp: -4, Index: length, Scale: 1}, CX.As32())
1416 MOVL(AX.As32(), Mem{Base: dst})
1417 MOVL(CX.As32(), Mem{Base: dst, Disp: -4, Index: length, Scale: 1})
1418 ADDQ(length, src)
1419 ADDQ(length, dst)
1420 JMP(end)
1421
1422 Label(name + "move_8through16")
1423 MOVQ(Mem{Base: src}, AX)
1424 MOVQ(Mem{Base: src, Disp: -8, Index: length, Scale: 1}, CX)
1425 MOVQ(AX, Mem{Base: dst})
1426 MOVQ(CX, Mem{Base: dst, Disp: -8, Index: length, Scale: 1})
1427 ADDQ(length, src)
1428 ADDQ(length, dst)
1429 JMP(end)
1430 }
1431 Label("copy_" + suffix + "_end")
1432 }
1433
1434 // copyOverlappedMemory will copy one byte at the time from src to dst.
1435 // src and dst are updated. length will be zero.
1436 func (e executeSimple) copyOverlappedMemory(suffix string, src, dst, length reg.GPVirtual) {
1437 label := "copy_slow_" + suffix
1438 tmp := GP64()
1439
1440 Label(label)
1441 MOVBQZX(Mem{Base: src}, tmp) // fresh full-register def; avoids a false RMW dependency on tmp's stale upper bits across iterations
1442 MOVB(tmp.As8(), Mem{Base: dst})
1443 INCQ(src)
1444 INCQ(dst)
1445 DECQ(length)
1446 JNZ(LabelRef(label))
1447 }
1448
1449 type decodeSync struct {
1450 decode options
1451 execute executeSimple
1452 }
1453
1454 func (d *decodeSync) setBMI2(flag bool) {
1455 d.decode.bmi2 = flag
1456 }
1457
1458 func (d *decodeSync) generateProcedure(name string) {
1459 Package("github.com/klauspost/compress/zstd")
1460 TEXT(name, 0, "func (s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int")
1461 Doc(name+" implements the main loop of sequenceDecs.decodeSync in x86 asm", "")
1462 Pragma("noescape")
1463
1464 d.decode.generateBody(name, d.execute.executeSingleTriple)
1465 }