Debian Codegraph @

s2/_generate/gen.go

raw
1 package main
2
3 //go:generate go run gen.go -out ../encodeblock_amd64.s -stubs ../encodeblock_asm.go -pkg=s2
4 //go:generate go run gen.go -out ../encodeblock.s -arch arm64 -arm64gen -pkg=s2
5 //go:generate gofmt -w ../encodeblock_asm.go
6 //go:generate go run cleanup.go ../encodeblock_amd64.s ../encodeblock_arm64.s
7
8 import (
9 "flag"
10 "fmt"
11 "math"
12 "math/rand"
13 "runtime"
14 "strings"
15
16 . "github.com/mmcloughlin/avo/build"
17 "github.com/mmcloughlin/avo/buildtags"
18 . "github.com/mmcloughlin/avo/operand"
19 "github.com/mmcloughlin/avo/reg"
20 )
21
22 // insert extra checks here and there.
23 const debug = false
24
25 // genArm64 emits the arm64 half. It is a separate run rather than a second
26 // -arch on the amd64 one because the two differ in the assembler directives
27 // they need: the GOAMD64 blocks below are meaningless on arm64, and the arm64
28 // lowering refuses directives outright rather than trying to interpret them.
29 // Keeping the amd64 pass unchanged is also what keeps its output identical.
30 var genArm64 = flag.Bool("arm64gen", false, "emit the arm64 half, without the GOAMD64 directive blocks")
31
32 // tzcnt emits a count-trailing-zeros over a value already known to be nonzero.
33 //
34 // TZCNT needs no GOAMD64 guard. Its encoding is BSF's with an F3 prefix, and
35 // processors without the instruction ignore the prefix and execute BSF -- so
36 // one encoding is correct everywhere, and the assembler-level choice this used
37 // to make was never needed.
38 //
39 // The two differ only on a zero input, which cannot reach here: every caller
40 // has already established that the value is nonzero. They also set flags
41 // differently -- TZCNT takes ZF from the result and defines CF, BSF takes ZF
42 // from the source -- which is unobservable here because all seventy call sites
43 // are followed immediately by SARQ, which overwrites the flags without reading
44 // them.
45 //
46 // On arm64 TZCNTQ lowers to RBIT+CLZ, exact even for a zero input.
47 //
48 // Relative cost, from the table this replaces:
49 //
50 // 2016 BMI :TZCNT r64, r64 L: 0.57ns= 2.0c T: 0.29ns= 1.00c
51 // 315 AMD64 :BSF r64, r64 L: 0.88ns= 3.1c T: 0.86ns= 3.00c
52 func tzcnt(r reg.GPVirtual) {
53 TZCNTQ(r, r)
54 }
55
56 const (
57 limit14B = math.MaxUint32
58 // Use 12 bit table when no more than...
59 limit12B = 16<<10 - 1
60 // Use 10 bit table when no more than...
61 limit10B = 4<<10 - 1
62 // Use 8 bit table when no more than...
63 limit8B = 512 - 1
64 )
65
66 func main() {
67 flag.Parse()
68 Constraint(buildtags.Any(buildtags.Term("amd64"), buildtags.Term("arm64")))
69 Constraint(buildtags.Not("appengine").ToConstraint())
70 Constraint(buildtags.Not("noasm").ToConstraint())
71 Constraint(buildtags.Term("gc").ToConstraint())
72 Constraint(buildtags.Not("noasm").ToConstraint())
73
74 if !*genArm64 {
75 // We need a function to add comments.
76 // Promoting v4 to v3 is an amd64 assembler concern; on arm64 the
77 // block is not just unnecessary, it is refused, since the lowering
78 // declines to interpret preprocessor directives at all.
79 TEXT("_dummy_", 0, "func()")
80 Comment("#ifdef GOAMD64_v4")
81 Comment("#ifndef GOAMD64_v3")
82 Comment("#define GOAMD64_v3")
83 Comment("#endif")
84 Comment("#endif")
85 RET()
86 }
87
88 o := options{
89 bmi1: false,
90 bmi2: false,
91 snappy: false,
92 avx2: false,
93 outputMargin: 9,
94 }
95 o.genEncodeBlockAsm("encodeBlockAsm", 14, 6, 6, limit14B)
96 o.genEncodeBlockAsm("encodeBlockAsm4MB", 14, 6, 6, 4<<20)
97 o.genEncodeBlockAsm("encodeBlockAsm12B", 12, 5, 5, limit12B)
98 o.genEncodeBlockAsm("encodeBlockAsm10B", 10, 5, 4, limit10B)
99 o.genEncodeBlockAsm("encodeBlockAsm8B", 8, 4, 4, limit8B)
100
101 o.outputMargin = 6
102 o.maxSkip = 100 // Blocks can be long, limit max skipping.
103 o.genEncodeBetterBlockAsm("encodeBetterBlockAsm", 17, 14, 7, 7, limit14B)
104 o.genEncodeBetterBlockAsm("encodeBetterBlockAsm4MB", 17, 14, 7, 7, 4<<20)
105 o.maxSkip = 0
106 o.genEncodeBetterBlockAsm("encodeBetterBlockAsm12B", 14, 12, 6, 6, limit12B)
107 o.genEncodeBetterBlockAsm("encodeBetterBlockAsm10B", 12, 10, 5, 6, limit10B)
108 o.genEncodeBetterBlockAsm("encodeBetterBlockAsm8B", 10, 8, 4, 6, limit8B)
109
110 // Snappy compatible
111 o.snappy = true
112 o.outputMargin = 9
113 o.genEncodeBlockAsm("encodeSnappyBlockAsm", 14, 6, 6, limit14B)
114 o.genEncodeBlockAsm("encodeSnappyBlockAsm64K", 14, 6, 6, 64<<10-1)
115 o.genEncodeBlockAsm("encodeSnappyBlockAsm12B", 12, 5, 5, limit12B)
116 o.genEncodeBlockAsm("encodeSnappyBlockAsm10B", 10, 5, 4, limit10B)
117 o.genEncodeBlockAsm("encodeSnappyBlockAsm8B", 8, 4, 4, limit8B)
118
119 o.maxSkip = 100
120 o.genEncodeBetterBlockAsm("encodeSnappyBetterBlockAsm", 17, 14, 7, 7, limit14B)
121 o.maxSkip = 0
122 o.genEncodeBetterBlockAsm("encodeSnappyBetterBlockAsm64K", 16, 13, 7, 7, 64<<10-1)
123 o.genEncodeBetterBlockAsm("encodeSnappyBetterBlockAsm12B", 14, 12, 6, 6, limit12B)
124 o.genEncodeBetterBlockAsm("encodeSnappyBetterBlockAsm10B", 12, 10, 5, 6, limit10B)
125 o.genEncodeBetterBlockAsm("encodeSnappyBetterBlockAsm8B", 10, 8, 4, 6, limit8B)
126
127 o.maxSkip = 0
128 o.skipOutput = true
129 o.snappy = true
130 o.genEncodeBlockAsm("calcBlockSize", 13, 5, 6, limit14B)
131 o.genEncodeBlockAsm("calcBlockSizeSmall", 9, 4, 4, 1024)
132 o.skipOutput = false
133 o.snappy = false
134
135 o.snappy = false
136 o.outputMargin = 0
137 o.maxLen = math.MaxUint32
138 o.maxOffset = math.MaxUint32 - 1
139 o.genEmitLiteral()
140 o.genEmitRepeat()
141 o.genEmitCopy()
142 o.snappy = true
143 o.genEmitCopyNoRepeat()
144 o.snappy = false
145 o.genMatchLen()
146 o.cvtLZ4BlockAsm(false)
147 o.cvtLZ4BlockAsm(true)
148 o.snappy = true
149 o.cvtLZ4BlockAsm(false)
150 o.cvtLZ4BlockAsm(true)
151
152 Generate()
153 }
154
155 func debugval(v Op) {
156 value := reg.R15
157 MOVQ(v, value)
158 INT(Imm(3))
159 }
160
161 func debugval32(v Op) {
162 value := reg.R15L
163 MOVL(v, value)
164 INT(Imm(3))
165 }
166
167 var assertCounter int
168
169 // assert will insert code if debug is enabled.
170 // The code should jump to 'ok' is assertion is success.
171 func assert(fn func(ok LabelRef)) {
172 if debug {
173 caller := [100]uintptr{0}
174 runtime.Callers(2, caller[:])
175 frame, _ := runtime.CallersFrames(caller[:]).Next()
176
177 ok := fmt.Sprintf("assert_check_%d_ok_srcline_%d", assertCounter, frame.Line)
178 fn(LabelRef(ok))
179 // Emit several since delve is imprecise.
180 INT(Imm(3))
181 INT(Imm(3))
182 Label(ok)
183 assertCounter++
184 }
185 }
186
187 type regTable struct {
188 r reg.Register
189 disp int
190 }
191
192 func (r regTable) Idx(idx reg.GPVirtual, scale uint8) Mem {
193 return Mem{Base: r.r, Index: idx, Scale: scale, Disp: r.disp}
194 }
195
196 type options struct {
197 snappy bool
198 bmi1 bool
199 bmi2 bool
200 skipOutput bool
201 avx2 bool
202 maxLen int
203 maxOffset int
204 outputMargin int // Should be at least 5.
205 maxSkip int
206 }
207
208 func (o options) genEncodeBlockAsm(name string, tableBits, skipLog, hashBytes, maxLen int) {
209 dstTxt := "dst, "
210 if o.skipOutput {
211 dstTxt = ""
212 }
213
214 var tableSize = 4 * (1 << tableBits)
215 // Memzero needs at least 128 bytes.
216 if tableSize < 128 {
217 panic("tableSize must be at least 128 bytes")
218 }
219
220 arrPtr := fmt.Sprintf(",tmp *[%d]byte", tableSize)
221 TEXT(name, 0, "func("+dstTxt+"src []byte"+arrPtr+") int")
222 Doc(name+" encodes a non-empty src to a guaranteed-large-enough dst.",
223 fmt.Sprintf("Maximum input %d bytes.", maxLen),
224 "It assumes that the varint-encoded length of the decompressed bytes has already been written.", "")
225 Pragma("noescape")
226
227 o.maxLen = maxLen
228 o.maxOffset = maxLen - 1
229 var literalMaxOverhead = maxLitOverheadFor(maxLen)
230
231 // Memzero needs at least 128 bytes.
232 if tableSize < 128 {
233 panic("tableSize must be at least 128 bytes")
234 }
235
236 lenSrcBasic, err := Param("src").Len().Resolve()
237 if err != nil {
238 panic(err)
239 }
240 lenSrcQ := lenSrcBasic.Addr
241
242 var lenDstQ Mem
243 if debug && !o.skipOutput {
244 lenDstBasic, err := Param("dst").Len().Resolve()
245 if err != nil {
246 panic(err)
247 }
248 lenDstQ = lenDstBasic.Addr
249 }
250
251 // Bail if we can't compress to at least this.
252 dstLimitPtrQ := AllocLocal(8)
253
254 // sLimitL is when to stop looking for offset/length copies.
255 sLimitL := AllocLocal(4)
256
257 // nextEmitL keeps track of the point we have emitted to.
258 nextEmitL := AllocLocal(4)
259
260 // Repeat stores the last match offset.
261 repeatL := AllocLocal(4)
262
263 // nextSTempL keeps nextS while other functions are being called.
264 nextSTempL := AllocLocal(4)
265
266 // Load pointer to temp table
267 table := regTable{r: Load(Param("tmp"), GP64())}
268
269 dst := GP64()
270 if !o.skipOutput {
271 dstBaseBasic, err := Param("dst").Base().Resolve()
272 if err != nil {
273 panic(err)
274 }
275 dstBaseQ := dstBaseBasic.Addr
276 MOVQ(dstBaseQ, dst)
277 } else {
278 // Zero dst address
279 XORQ(dst, dst)
280 }
281
282 srcBaseBasic, err := Param("src").Base().Resolve()
283 if err != nil {
284 panic(err)
285 }
286 srcBaseQ := srcBaseBasic.Addr
287
288 // Zero table
289 {
290 iReg := GP64()
291 MOVQ(U32(tableSize/8/16), iReg)
292 tablePtr := GP64()
293 MOVQ(table.r, tablePtr)
294 zeroXmm := XMM()
295 PXOR(zeroXmm, zeroXmm)
296
297 Label("zero_loop_" + name)
298 for i := 0; i < 8; i++ {
299 MOVOU(zeroXmm, Mem{Base: tablePtr, Disp: i * 16})
300 }
301 ADDQ(U8(16*8), tablePtr)
302 DECQ(iReg)
303 JNZ(LabelRef("zero_loop_" + name))
304 }
305
306 {
307 // nextEmit is offset n src where the next emitLiteral should start from.
308 MOVL(U32(0), nextEmitL)
309
310 const inputMargin = 8
311 tmp, tmp2, tmp3 := GP64(), GP64(), GP64()
312 MOVQ(lenSrcQ, tmp)
313 LEAQ(Mem{Base: tmp, Disp: -o.outputMargin}, tmp2)
314 // sLimitL := len(src) - inputMargin
315 LEAQ(Mem{Base: tmp, Disp: -inputMargin}, tmp3)
316
317 assert(func(ok LabelRef) {
318 CMPQ(tmp3, lenSrcQ)
319 JB(ok)
320 })
321
322 MOVL(tmp3.As32(), sLimitL)
323
324 // dstLimit := (len(src) - outputMargin ) - len(src)>>5
325 SHRQ(U8(5), tmp)
326 SUBL(tmp.As32(), tmp2.As32()) // tmp2 = tmp2 - tmp
327
328 assert(func(ok LabelRef) {
329 // if len(src) > len(src) - len(src)>>5 - outputMargin: ok
330 CMPQ(lenSrcQ, tmp2)
331 JAE(ok)
332 })
333
334 LEAQ(Mem{Base: dst, Index: tmp2, Scale: 1}, tmp2)
335 MOVQ(tmp2, dstLimitPtrQ)
336 }
337
338 // s = 1
339 s := GP32()
340 MOVL(U32(1), s)
341 // repeatL = 1
342 MOVL(s, repeatL)
343
344 src := GP64()
345 Load(Param("src").Base(), src)
346
347 // Load cv
348 Label("search_loop_" + name)
349 candidate := GP32()
350 {
351 assert(func(ok LabelRef) {
352 // Check if somebody changed src
353 tmp := GP64()
354 MOVQ(srcBaseQ, tmp)
355 CMPQ(tmp, src)
356 JEQ(ok)
357 })
358
359 cv := GP64()
360 nextS := GP32()
361 // nextS := s + (s-nextEmit)>>6 + 4
362 if o.maxSkip == 0 {
363 tmp := GP64()
364 MOVL(s, tmp.As32()) // tmp = s
365 SUBL(nextEmitL, tmp.As32()) // tmp = s - nextEmit
366 SHRL(U8(skipLog), tmp.As32()) // tmp = (s - nextEmit) >> skipLog
367 LEAL(Mem{Base: s, Disp: 4, Index: tmp, Scale: 1}, nextS)
368 }
369 // if nextS > sLimit {goto emitRemainder}
370 {
371 CMPL(nextS.As32(), sLimitL)
372 JAE(LabelRef("emit_remainder_" + name))
373 }
374 MOVQ(Mem{Base: src, Index: s, Scale: 1}, cv)
375 assert(func(ok LabelRef) {
376 // Check if s is valid (we should have jumped above if not)
377 tmp := GP64()
378 MOVQ(lenSrcQ, tmp)
379 CMPQ(tmp, s.As64())
380 JA(ok)
381 })
382 // move nextS to stack.
383 MOVL(nextS.As32(), nextSTempL)
384
385 candidate2 := GP32()
386 hasher := hashN(hashBytes, tableBits)
387 {
388 hash0, hash1 := GP64(), GP64()
389 MOVQ(cv, hash0)
390 MOVQ(cv, hash1)
391 SHRQ(U8(8), hash1)
392 hasher.hash(hash0)
393 hasher.hash(hash1)
394 MOVL(table.Idx(hash0, 4), candidate)
395 MOVL(table.Idx(hash1, 4), candidate2)
396 assert(func(ok LabelRef) {
397 CMPQ(hash0, U32(tableSize))
398 JB(ok)
399 })
400 assert(func(ok LabelRef) {
401 CMPQ(hash1, U32(tableSize))
402 JB(ok)
403 })
404
405 MOVL(s, table.Idx(hash0, 4))
406 tmp := GP32()
407 LEAL(Mem{Base: s, Disp: 1}, tmp)
408 MOVL(tmp, table.Idx(hash1, 4))
409 }
410
411 // Can be moved up if registers are available.
412 hash2 := GP64()
413 {
414 // hash2 := hash6(cv>>16, tableBits)
415 // hasher = hash6(tableBits)
416 MOVQ(cv, hash2)
417 SHRQ(U8(16), hash2)
418 hasher.hash(hash2)
419 assert(func(ok LabelRef) {
420 CMPQ(hash2, U32(tableSize))
421 JB(ok)
422 })
423 }
424
425 // En/disable repeat matching.
426 if true {
427 // Check repeat at offset checkRep
428 const checkRep = 1
429 {
430 // rep = s - repeat
431 rep := GP32()
432 MOVL(s, rep)
433 SUBL(repeatL, rep) // rep = s - repeat
434
435 // if uint32(cv>>(checkRep*8)) == load32(src, s-repeat+checkRep) {
436 left, right := GP64(), GP64()
437 MOVL(Mem{Base: src, Index: rep, Disp: checkRep, Scale: 1}, right.As32())
438 MOVQ(cv, left)
439 SHRQ(U8(checkRep*8), left)
440 CMPL(left.As32(), right.As32())
441 // BAIL, no repeat.
442 JNE(LabelRef("no_repeat_found_" + name))
443 }
444 // base = s + checkRep
445 base := GP32()
446 LEAL(Mem{Base: s, Disp: checkRep}, base)
447
448 // nextEmit before repeat.
449 nextEmit := GP32()
450 MOVL(nextEmitL, nextEmit)
451
452 // Extend back
453 if true {
454 i := GP32()
455 MOVL(base, i)
456 SUBL(repeatL, i)
457 JZ(LabelRef("repeat_extend_back_end_" + name))
458
459 Label("repeat_extend_back_loop_" + name)
460 // if base <= nextemit {exit}
461 CMPL(base.As32(), nextEmit)
462 JBE(LabelRef("repeat_extend_back_end_" + name))
463 // if src[i-1] == src[base-1]
464 tmp, tmp2 := GP64(), GP64()
465 MOVB(Mem{Base: src, Index: i, Scale: 1, Disp: -1}, tmp.As8())
466 MOVB(Mem{Base: src, Index: base, Scale: 1, Disp: -1}, tmp2.As8())
467 CMPB(tmp.As8(), tmp2.As8())
468 JNE(LabelRef("repeat_extend_back_end_" + name))
469 LEAL(Mem{Base: base, Disp: -1}, base)
470 DECL(i)
471 JNZ(LabelRef("repeat_extend_back_loop_" + name))
472 }
473 Label("repeat_extend_back_end_" + name)
474
475 {
476 // tmp = s-nextEmit
477 tmp := GP64()
478 MOVL(base.As32(), tmp.As32())
479 SUBL(nextEmitL, tmp.As32())
480 // tmp = &dst + s-nextEmit
481 LEAQ(Mem{Base: dst, Index: tmp, Scale: 1, Disp: literalMaxOverhead}, tmp)
482 CMPQ(tmp, dstLimitPtrQ)
483 JB(LabelRef("repeat_dst_size_check_" + name))
484 ri, err := ReturnIndex(0).Resolve()
485 if err != nil {
486 panic(err)
487 }
488 MOVQ(U32(0), ri.Addr)
489 if o.avx2 {
490 VZEROUPPER()
491 }
492 RET()
493 }
494 Label("repeat_dst_size_check_" + name)
495
496 // Base is now at start. Emit until base.
497 // d += emitLiteral(dst[d:], src[nextEmit:base])
498 o.emitLiteralsDstP(nextEmitL, base, src, dst, "repeat_emit_"+name)
499
500 // Extend forward
501 {
502 // s += 4 + checkRep
503 ADDL(U8(4+checkRep), s)
504
505 {
506 // candidate := s - repeat + 4 + checkRep
507 MOVL(s, candidate)
508 SUBL(repeatL, candidate) // candidate = s - repeat
509
510 // srcLeft = len(src) - s
511 srcLeft := GP64()
512 MOVQ(lenSrcQ, srcLeft)
513 SUBL(s, srcLeft.As32())
514 assert(func(ok LabelRef) {
515 // if srcleft < maxint32: ok
516 CMPQ(srcLeft, U32(0x7fffffff))
517 JB(ok)
518 })
519 // Forward address
520 forwardStart := GP64()
521 LEAQ(Mem{Base: src, Index: s, Scale: 1}, forwardStart)
522 // End address
523 backStart := GP64()
524 LEAQ(Mem{Base: src, Index: candidate, Scale: 1}, backStart)
525
526 length := o.matchLen("repeat_extend_"+name, forwardStart, backStart, srcLeft, LabelRef("repeat_extend_forward_end_"+name))
527 forwardStart, backStart, srcLeft = nil, nil, nil
528 Label("repeat_extend_forward_end_" + name)
529 // s+= length
530 ADDL(length.As32(), s)
531 }
532 }
533 // Emit
534 {
535 // length = s-base
536 length := GP32()
537 MOVL(s, length)
538 SUBL(base.As32(), length) // length = s - base
539
540 offsetVal := GP32()
541 MOVL(repeatL, offsetVal)
542
543 if !o.snappy {
544 // if nextEmit == 0 {do copy instead...}
545 TESTL(nextEmit, nextEmit)
546 JZ(LabelRef("repeat_as_copy_" + name))
547
548 // Emit as repeat...
549 o.emitRepeat("match_repeat_"+name, length, offsetVal, nil, dst, LabelRef("repeat_end_emit_"+name), false)
550
551 // Emit as copy instead...
552 Label("repeat_as_copy_" + name)
553 }
554 o.emitCopy("repeat_as_copy_"+name, length, offsetVal, nil, dst, nil, LabelRef("repeat_end_emit_"+name))
555
556 Label("repeat_end_emit_" + name)
557 // Store new dst and nextEmit
558 MOVL(s, nextEmitL)
559 }
560 // if s >= sLimit is picked up on next loop.
561 if false {
562 CMPL(s.As32(), sLimitL)
563 JAE(LabelRef("emit_remainder_" + name))
564 }
565 JMP(LabelRef("search_loop_" + name))
566 }
567 Label("no_repeat_found_" + name)
568 {
569 // Check candidates are ok. All must be < s and < len(src)
570 assert(func(ok LabelRef) {
571 tmp := GP64()
572 MOVQ(lenSrcQ, tmp)
573 CMPL(tmp.As32(), candidate)
574 JA(ok)
575 })
576 assert(func(ok LabelRef) {
577 CMPL(s, candidate)
578 JA(ok)
579 })
580 assert(func(ok LabelRef) {
581 tmp := GP64()
582 MOVQ(lenSrcQ, tmp)
583 CMPL(tmp.As32(), candidate2)
584 JA(ok)
585 })
586 assert(func(ok LabelRef) {
587 CMPL(s, candidate2)
588 JA(ok)
589 })
590
591 CMPL(Mem{Base: src, Index: candidate, Scale: 1}, cv.As32())
592 JEQ(LabelRef("candidate_match_" + name))
593
594 tmp := GP32()
595 // cv >>= 8
596 SHRQ(U8(8), cv)
597
598 // candidate = int(table[hash2]) - load early.
599 MOVL(table.Idx(hash2, 4), candidate)
600 assert(func(ok LabelRef) {
601 tmp := GP64()
602 MOVQ(lenSrcQ, tmp)
603 CMPL(tmp.As32(), candidate)
604 JA(ok)
605 })
606 assert(func(ok LabelRef) {
607 // We may get s and s+1
608 tmp := GP32()
609 LEAL(Mem{Base: s, Disp: 2}, tmp)
610 CMPL(tmp, candidate)
611 JA(ok)
612 })
613
614 LEAL(Mem{Base: s, Disp: 2}, tmp)
615
616 //if uint32(cv>>8) == load32(src, candidate2)
617 CMPL(Mem{Base: src, Index: candidate2, Scale: 1}, cv.As32())
618 JEQ(LabelRef("candidate2_match_" + name))
619
620 // table[hash2] = uint32(s + 2)
621 MOVL(tmp, table.Idx(hash2, 4))
622
623 // cv >>= 8 (>> 16 total)
624 SHRQ(U8(8), cv)
625
626 // if uint32(cv>>16) == load32(src, candidate)
627 CMPL(Mem{Base: src, Index: candidate, Scale: 1}, cv.As32())
628 JEQ(LabelRef("candidate3_match_" + name))
629
630 // No match found, next loop
631 // s = nextS
632 MOVL(nextSTempL, s)
633 JMP(LabelRef("search_loop_" + name))
634
635 // Matches candidate at s + 2 (3rd check)
636 Label("candidate3_match_" + name)
637 ADDL(U8(2), s)
638 JMP(LabelRef("candidate_match_" + name))
639
640 // Match at s + 1 (we calculated the hash, lets store it)
641 Label("candidate2_match_" + name)
642 // table[hash2] = uint32(s + 2)
643 MOVL(tmp, table.Idx(hash2, 4))
644 // s++
645 INCL(s)
646 MOVL(candidate2, candidate)
647 }
648 }
649
650 Label("candidate_match_" + name)
651 // We have a match at 's' with src offset in "candidate" that matches at least 4 bytes.
652 // Extend backwards
653 if true {
654 ne := GP32()
655 MOVL(nextEmitL, ne)
656 TESTL(candidate, candidate)
657 JZ(LabelRef("match_extend_back_end_" + name))
658
659 // candidate is tested when decremented, so we loop back here.
660 Label("match_extend_back_loop_" + name)
661 // if s <= nextEmit {exit}
662 CMPL(s, ne)
663 JBE(LabelRef("match_extend_back_end_" + name))
664 // if src[candidate-1] == src[s-1]
665 tmp, tmp2 := GP64(), GP64()
666 MOVB(Mem{Base: src, Index: candidate, Scale: 1, Disp: -1}, tmp.As8())
667 MOVB(Mem{Base: src, Index: s, Scale: 1, Disp: -1}, tmp2.As8())
668 CMPB(tmp.As8(), tmp2.As8())
669 JNE(LabelRef("match_extend_back_end_" + name))
670 LEAL(Mem{Base: s, Disp: -1}, s)
671 DECL(candidate)
672 JZ(LabelRef("match_extend_back_end_" + name))
673 JMP(LabelRef("match_extend_back_loop_" + name))
674 }
675 Label("match_extend_back_end_" + name)
676
677 // Bail if we exceed the maximum size.
678 {
679 // tmp = s-nextEmit
680 tmp := GP64()
681 MOVL(s, tmp.As32())
682 SUBL(nextEmitL, tmp.As32())
683 // tmp = &dst + s-nextEmit
684 LEAQ(Mem{Base: dst, Index: tmp, Scale: 1, Disp: literalMaxOverhead}, tmp)
685 CMPQ(tmp, dstLimitPtrQ)
686 JB(LabelRef("match_dst_size_check_" + name))
687 ri, err := ReturnIndex(0).Resolve()
688 if err != nil {
689 panic(err)
690 }
691 MOVQ(U32(0), ri.Addr)
692 if o.avx2 {
693 VZEROUPPER()
694 }
695 RET()
696 }
697 Label("match_dst_size_check_" + name)
698 {
699 base := GP32()
700 MOVL(s, base.As32())
701 o.emitLiteralsDstP(nextEmitL, base, src, dst, "match_emit_"+name)
702 }
703 cv := GP64()
704 Label("match_nolit_loop_" + name)
705 {
706 // Update repeat
707 {
708 // repeat = base - candidate
709 repeatVal := GP64().As32()
710 MOVL(s, repeatVal)
711 SUBL(candidate, repeatVal)
712 MOVL(repeatVal, repeatL)
713 }
714 // s+=4, candidate+=4
715 ADDL(U8(4), s)
716 ADDL(U8(4), candidate)
717 // Extend the 4-byte match as long as possible and emit copy.
718 {
719 assert(func(ok LabelRef) {
720 // s must be > candidate cannot be equal.
721 CMPL(s, candidate)
722 JA(ok)
723 })
724 // srcLeft = len(src) - s
725 srcLeft := GP64()
726 MOVQ(lenSrcQ, srcLeft)
727 SUBL(s, srcLeft.As32())
728 assert(func(ok LabelRef) {
729 // if srcleft < maxint32: ok
730 CMPQ(srcLeft, U32(0x7fffffff))
731 JB(ok)
732 })
733
734 a, b := GP64(), GP64()
735 LEAQ(Mem{Base: src, Index: s, Scale: 1}, a)
736 LEAQ(Mem{Base: src, Index: candidate, Scale: 1}, b)
737 length := o.matchLen("match_nolit_"+name,
738 a, b,
739 srcLeft,
740 LabelRef("match_nolit_end_"+name),
741 )
742 Label("match_nolit_end_" + name)
743 assert(func(ok LabelRef) {
744 CMPL(length.As32(), U32(math.MaxInt32))
745 JB(ok)
746 })
747 a, b, srcLeft = nil, nil, nil
748
749 // s += length (length is destroyed, use it now)
750 ADDL(length.As32(), s)
751
752 // Load offset from repeat value.
753 offset := GP64()
754 MOVL(repeatL, offset.As32())
755
756 // length += 4
757 ADDL(U8(4), length.As32())
758 MOVL(s, nextEmitL) // nextEmit = s
759 o.emitCopy("match_nolit_"+name, length, offset, nil, dst, nil, LabelRef("match_nolit_emitcopy_end_"+name))
760 Label("match_nolit_emitcopy_end_" + name)
761
762 // if s >= sLimit { end }
763 {
764 CMPL(s.As32(), sLimitL)
765 JAE(LabelRef("emit_remainder_" + name))
766 }
767 // Start load s-2 as early as possible...
768 MOVQ(Mem{Base: src, Index: s, Scale: 1, Disp: -2}, cv)
769 // Bail if we exceed the maximum size.
770 {
771 CMPQ(dst, dstLimitPtrQ)
772 JB(LabelRef("match_nolit_dst_ok_" + name))
773 ri, err := ReturnIndex(0).Resolve()
774 if err != nil {
775 panic(err)
776 }
777 MOVQ(U32(0), ri.Addr)
778 if o.avx2 {
779 VZEROUPPER()
780 }
781 RET()
782 Label("match_nolit_dst_ok_" + name)
783 }
784 }
785 // cv must be set to value at s-2 before arriving here
786 {
787 // Check for an immediate match, otherwise start search at s+1
788 // Index s-2
789 hasher := hashN(hashBytes, tableBits)
790 hash0, hash1 := GP64(), GP64()
791 MOVQ(cv, hash0) // src[s-2]
792 SHRQ(U8(16), cv)
793 MOVQ(cv, hash1) // src[s]
794 hasher.hash(hash0)
795 hasher.hash(hash1)
796 sm2 := GP32() // s - 2
797 LEAL(Mem{Base: s, Disp: -2}, sm2)
798 assert(func(ok LabelRef) {
799 CMPQ(hash0, U32(tableSize))
800 JB(ok)
801 })
802 assert(func(ok LabelRef) {
803 CMPQ(hash1, U32(tableSize))
804 JB(ok)
805 })
806 addr := GP64()
807 LEAQ(table.Idx(hash1, 4), addr)
808 MOVL(Mem{Base: addr}, candidate)
809 MOVL(sm2, table.Idx(hash0, 4))
810 MOVL(s, Mem{Base: addr})
811 CMPL(Mem{Base: src, Index: candidate, Scale: 1}, cv.As32())
812 JEQ(LabelRef("match_nolit_loop_" + name))
813 INCL(s)
814 }
815 JMP(LabelRef("search_loop_" + name))
816 }
817
818 Label("emit_remainder_" + name)
819 // Bail if we exceed the maximum size.
820 // if d+len(src)-nextEmitL > dstLimitPtrQ { return 0
821 {
822 // remain = len(src) - nextEmit
823 remain := GP64()
824 MOVQ(lenSrcQ, remain)
825 SUBL(nextEmitL, remain.As32())
826
827 dstExpect := GP64()
828 // dst := dst + (len(src)-nextEmitL)
829
830 LEAQ(Mem{Base: dst, Index: remain, Scale: 1, Disp: literalMaxOverhead}, dstExpect)
831 CMPQ(dstExpect, dstLimitPtrQ)
832 JB(LabelRef("emit_remainder_ok_" + name))
833 ri, err := ReturnIndex(0).Resolve()
834 if err != nil {
835 panic(err)
836 }
837 if o.avx2 {
838 VZEROUPPER()
839 }
840 MOVQ(U32(0), ri.Addr)
841 RET()
842 Label("emit_remainder_ok_" + name)
843 }
844 {
845 // emitLiteral(dst[d:], src[nextEmitL:])
846 emitEnd := GP64()
847 MOVQ(lenSrcQ, emitEnd)
848
849 // Emit final literals.
850 // Since we may be at the end of source,
851 // we cannot have output margin.
852 x := o.outputMargin
853 o.outputMargin = 0
854 o.emitLiteralsDstP(nextEmitL, emitEnd, src, dst, "emit_remainder_"+name)
855 o.outputMargin = x
856 // Assert size is < limit
857 assert(func(ok LabelRef) {
858 // if dstBaseQ < dstLimitPtrQ: ok
859 CMPQ(dst, dstLimitPtrQ)
860 JB(ok)
861 })
862 }
863
864 // length := start - base (ptr arithmetic)
865 length := GP64()
866 if !o.skipOutput {
867 base := Load(Param("dst").Base(), GP64())
868 MOVQ(dst, length)
869 SUBQ(base, length)
870 } else {
871 length = dst
872 }
873
874 // Assert size is < len(src)
875 assert(func(ok LabelRef) {
876 // if len(src) >= length: ok
877 CMPQ(lenSrcQ, length)
878 JAE(ok)
879 })
880 // Assert size is < len(dst)
881 if !o.skipOutput {
882 assert(func(ok LabelRef) {
883 // if len(dst) >= length: ok
884 CMPQ(lenDstQ, length)
885 JAE(ok)
886 })
887 }
888 if o.avx2 {
889 VZEROUPPER()
890 }
891 Store(length, ReturnIndex(0))
892 RET()
893 }
894
895 func maxLitOverheadFor(n int) int {
896 switch {
897 case n == 0:
898 return 0
899 case n < 60:
900 return 1
901 case n < 1<<8:
902 return 2
903 case n < 1<<16:
904 return 3
905 case n < 1<<24:
906 return 4
907 }
908 return 5
909 }
910
911 func (o options) genEncodeBetterBlockAsm(name string, lTableBits, sTableBits, skipLog, lHashBytes, maxLen int) {
912 var lTableSize = 4 * (1 << lTableBits)
913 var sTableSize = 4 * (1 << sTableBits)
914 tableSize := lTableSize + sTableSize
915
916 // Memzero needs at least 128 bytes.
917 if tableSize < 128 {
918 panic("tableSize must be at least 128 bytes")
919 }
920 arrPtr := fmt.Sprintf(", tmp *[%d]byte", tableSize)
921
922 TEXT(name, 0, "func(dst, src []byte"+arrPtr+") int")
923 Doc(name+" encodes a non-empty src to a guaranteed-large-enough dst.",
924 fmt.Sprintf("Maximum input %d bytes.", maxLen),
925 "It assumes that the varint-encoded length of the decompressed bytes has already been written.", "")
926 Pragma("noescape")
927
928 if lHashBytes > 7 || lHashBytes <= 4 {
929 panic("lHashBytes must be <= 7 and >4")
930 }
931 var literalMaxOverhead = maxLitOverheadFor(maxLen)
932
933 const sHashBytes = 4
934 o.maxLen = maxLen
935 o.maxOffset = maxLen - 1
936
937 // Memzero needs at least 128 bytes.
938 if (lTableSize + sTableSize) < 128 {
939 panic("tableSize must be at least 128 bytes")
940 }
941
942 lenSrcBasic, err := Param("src").Len().Resolve()
943 if err != nil {
944 panic(err)
945 }
946 lenSrcQ := lenSrcBasic.Addr
947
948 lenDstBasic, err := Param("dst").Len().Resolve()
949 if err != nil {
950 panic(err)
951 }
952 lenDstQ := lenDstBasic.Addr
953
954 // Bail if we can't compress to at least this.
955 dstLimitPtrQ := AllocLocal(8)
956
957 // sLimitL is when to stop looking for offset/length copies.
958 sLimitL := AllocLocal(4)
959
960 // nextEmitL keeps track of the point we have emitted to.
961 nextEmitL := AllocLocal(4)
962
963 // Repeat stores the last match offset.
964 repeatL := AllocLocal(4)
965
966 // nextSTempL keeps nextS while other functions are being called.
967 nextSTempL := AllocLocal(4)
968
969 table := Load(Param("tmp"), GP64())
970 lTab := regTable{r: table}
971 sTab := regTable{r: table, disp: lTableSize}
972
973 dst := GP64()
974 {
975 dstBaseBasic, err := Param("dst").Base().Resolve()
976 if err != nil {
977 panic(err)
978 }
979 dstBaseQ := dstBaseBasic.Addr
980 MOVQ(dstBaseQ, dst)
981 }
982
983 srcBaseBasic, err := Param("src").Base().Resolve()
984 if err != nil {
985 panic(err)
986 }
987 srcBaseQ := srcBaseBasic.Addr
988
989 // Zero table
990 {
991 iReg := GP64()
992 MOVQ(U32((sTableSize+lTableSize)/8/16), iReg)
993 tablePtr := GP64()
994 MOVQ(table, tablePtr)
995 zeroXmm := XMM()
996 PXOR(zeroXmm, zeroXmm)
997
998 Label("zero_loop_" + name)
999 for i := 0; i < 8; i++ {
1000 MOVOU(zeroXmm, Mem{Base: tablePtr, Disp: i * 16})
1001 }
1002 ADDQ(U8(16*8), tablePtr)
1003 DECQ(iReg)
1004 JNZ(LabelRef("zero_loop_" + name))
1005 }
1006
1007 {
1008 // nextEmit is offset n src where the next emitLiteral should start from.
1009 MOVL(U32(0), nextEmitL)
1010
1011 const inputMargin = 8
1012 tmp, tmp2, tmp3 := GP64(), GP64(), GP64()
1013 MOVQ(lenSrcQ, tmp)
1014 LEAQ(Mem{Base: tmp, Disp: -o.outputMargin}, tmp2)
1015 // sLimitL := len(src) - inputMargin
1016 LEAQ(Mem{Base: tmp, Disp: -inputMargin}, tmp3)
1017
1018 assert(func(ok LabelRef) {
1019 CMPQ(tmp3, lenSrcQ)
1020 JB(ok)
1021 })
1022
1023 MOVL(tmp3.As32(), sLimitL)
1024
1025 // dstLimit := (len(src) - 5 ) - len(src)>>5
1026 SHRQ(U8(5), tmp)
1027 SUBL(tmp.As32(), tmp2.As32()) // tmp2 = tmp2 - tmp
1028
1029 assert(func(ok LabelRef) {
1030 // if len(src) > len(src) - len(src)>>5 - 5: ok
1031 CMPQ(lenSrcQ, tmp2)
1032 JAE(ok)
1033 })
1034
1035 LEAQ(Mem{Base: dst, Index: tmp2, Scale: 1}, tmp2)
1036 MOVQ(tmp2, dstLimitPtrQ)
1037 }
1038
1039 // s = 1
1040 s := GP32()
1041 MOVL(U32(1), s)
1042 // repeatL = 0
1043 MOVL(U32(0), repeatL)
1044
1045 src := GP64()
1046 Load(Param("src").Base(), src)
1047
1048 // Load cv
1049 Label("search_loop_" + name)
1050 candidate := GP32()
1051 {
1052 assert(func(ok LabelRef) {
1053 // Check if somebody changed src
1054 tmp := GP64()
1055 MOVQ(srcBaseQ, tmp)
1056 CMPQ(tmp, src)
1057 JEQ(ok)
1058 })
1059
1060 cv := GP64()
1061 nextS := GP32()
1062 // nextS := s + (s-nextEmit)>>skipLog + 1
1063 if o.maxSkip == 0 {
1064 tmp := GP64()
1065 MOVL(s, tmp.As32()) // tmp = s
1066 SUBL(nextEmitL, tmp.As32()) // tmp = s - nextEmit
1067 SHRL(U8(skipLog), tmp.As32()) // tmp = (s - nextEmit) >> skipLog
1068 LEAL(Mem{Base: s, Disp: 1, Index: tmp, Scale: 1}, nextS)
1069 } else {
1070 /*
1071 nextS = (s-nextEmit)>>7 + 1
1072 if nextS > maxSkip {
1073 nextS = s + maxSkip
1074 } else {
1075 nextS += s
1076 }
1077 */
1078 tmp := GP64()
1079 MOVL(s, tmp.As32()) // tmp = s
1080 SUBL(nextEmitL, tmp.As32()) // tmp = s - nextEmit
1081 SHRL(U8(skipLog), tmp.As32()) // tmp = (s - nextEmit) >> skipLog
1082 CMPL(tmp.As32(), U8(o.maxSkip-1))
1083 JBE(LabelRef("check_maxskip_ok_" + name))
1084 LEAL(Mem{Base: s, Disp: o.maxSkip, Scale: 1}, nextS)
1085 JMP(LabelRef("check_maxskip_cont_" + name))
1086
1087 Label("check_maxskip_ok_" + name)
1088 LEAL(Mem{Base: s, Disp: 1, Index: tmp, Scale: 1}, nextS)
1089 Label("check_maxskip_cont_" + name)
1090 }
1091 // if nextS > sLimit {goto emitRemainder}
1092 {
1093 CMPL(nextS.As32(), sLimitL)
1094 JAE(LabelRef("emit_remainder_" + name))
1095 }
1096 MOVQ(Mem{Base: src, Index: s, Scale: 1}, cv)
1097 assert(func(ok LabelRef) {
1098 // Check if s is valid (we should have jumped above if not)
1099 tmp := GP64()
1100 MOVQ(lenSrcQ, tmp)
1101 CMPQ(tmp, s.As64())
1102 JA(ok)
1103 })
1104 // move nextS to stack.
1105 MOVL(nextS.As32(), nextSTempL)
1106
1107 candidateS := GP32()
1108 lHasher := hashN(lHashBytes, lTableBits)
1109 {
1110 sHasher := hashN(sHashBytes, sTableBits)
1111 hash0, hash1 := GP64(), GP64()
1112 MOVQ(cv, hash0)
1113 MOVQ(cv, hash1)
1114 lHasher.hash(hash0)
1115 sHasher.hash(hash1)
1116 MOVL(lTab.Idx(hash0, 4), candidate)
1117 MOVL(sTab.Idx(hash1, 4), candidateS)
1118 assert(func(ok LabelRef) {
1119 CMPQ(hash0, U32(lTableSize))
1120 JB(ok)
1121 })
1122 assert(func(ok LabelRef) {
1123 CMPQ(hash1, U32(sTableSize))
1124 JB(ok)
1125 })
1126
1127 MOVL(s, lTab.Idx(hash0, 4))
1128 MOVL(s, sTab.Idx(hash1, 4))
1129 }
1130
1131 longVal := GP64()
1132 shortVal := GP64()
1133 MOVQ(Mem{Base: src, Index: candidate, Scale: 1}, longVal)
1134 MOVQ(Mem{Base: src, Index: candidateS, Scale: 1}, shortVal)
1135
1136 // If we have at least 8 bytes match, choose that first.
1137 CMPQ(longVal, cv.As64())
1138 JEQ(LabelRef("candidate_match_" + name))
1139
1140 CMPQ(shortVal, cv.As64())
1141 JNE(LabelRef("no_short_found_" + name))
1142 MOVL(candidateS.As32(), candidate.As32())
1143 JMP(LabelRef("candidate_match_" + name))
1144
1145 Label("no_short_found_" + name)
1146 MOVL(longVal.As32(), longVal.As32())
1147
1148 // En/disable repeat matching.
1149 // Too small improvement
1150 if false {
1151 {
1152 CMPL(repeatL, U8(0))
1153 JEQ(LabelRef("no_repeat_found_" + name))
1154 }
1155 // Check repeat at offset checkRep
1156 const checkRep = 1
1157 const wantRepeatBytes = 6
1158 const repeatMask = ((1 << (wantRepeatBytes * 8)) - 1) << (8 * checkRep)
1159 {
1160 // rep = s - repeat
1161 rep := GP32()
1162 MOVL(s, rep)
1163 SUBL(repeatL, rep) // rep = s - repeat
1164
1165 // if uint32(cv>>(checkRep*8)) == load32(src, s-repeat+checkRep) {
1166 tmp := GP64()
1167 mask := GP64()
1168 MOVQ(Mem{Base: src, Index: rep, Disp: 0, Scale: 1}, tmp.As64())
1169 MOVQ(U64(repeatMask), mask)
1170 XORQ(cv.As64(), tmp.As64())
1171 TESTQ(mask.As64(), tmp.As64())
1172 // BAIL, no repeat.
1173 JNE(LabelRef("no_repeat_found_" + name))
1174 }
1175 // base = s + checkRep
1176 base := GP32()
1177 LEAL(Mem{Base: s, Disp: checkRep}, base)
1178
1179 // nextEmit before repeat.
1180 nextEmit := GP32()
1181 MOVL(nextEmitL, nextEmit)
1182
1183 // Extend back
1184 if true {
1185 i := GP32()
1186 MOVL(base, i)
1187 SUBL(repeatL, i)
1188 JZ(LabelRef("repeat_extend_back_end_" + name))
1189
1190 Label("repeat_extend_back_loop_" + name)
1191 // if base <= nextemit {exit}
1192 CMPL(base.As32(), nextEmit)
1193 JBE(LabelRef("repeat_extend_back_end_" + name))
1194 // if src[i-1] == src[base-1]
1195 tmp, tmp2 := GP64(), GP64()
1196 MOVB(Mem{Base: src, Index: i, Scale: 1, Disp: -1}, tmp.As8())
1197 MOVB(Mem{Base: src, Index: base, Scale: 1, Disp: -1}, tmp2.As8())
1198 CMPB(tmp.As8(), tmp2.As8())
1199 JNE(LabelRef("repeat_extend_back_end_" + name))
1200 LEAL(Mem{Base: base, Disp: -1}, base)
1201 DECL(i)
1202 JNZ(LabelRef("repeat_extend_back_loop_" + name))
1203 }
1204 Label("repeat_extend_back_end_" + name)
1205
1206 // Base is now at start. Emit until base.
1207 // d += emitLiteral(dst[d:], src[nextEmit:base])
1208 if true {
1209 o.emitLiteralsDstP(nextEmitL, base, src, dst, "repeat_emit_"+name)
1210 }
1211
1212 // Extend forward
1213 {
1214 // s += 4 + checkRep
1215 ADDL(U8(wantRepeatBytes+checkRep), s)
1216
1217 if true {
1218 // candidate := s - repeat + 4 + checkRep
1219 MOVL(s, candidate)
1220 SUBL(repeatL, candidate) // candidate = s - repeat
1221
1222 // srcLeft = len(src) - s
1223 srcLeft := GP64()
1224 MOVQ(lenSrcQ, srcLeft)
1225 SUBL(s, srcLeft.As32())
1226 assert(func(ok LabelRef) {
1227 // if srcleft < maxint32: ok
1228 CMPQ(srcLeft, U32(0x7fffffff))
1229 JB(ok)
1230 })
1231 // Forward address
1232 forwardStart := GP64()
1233 LEAQ(Mem{Base: src, Index: s, Scale: 1}, forwardStart)
1234 // End address
1235 backStart := GP64()
1236 LEAQ(Mem{Base: src, Index: candidate, Scale: 1}, backStart)
1237
1238 length := o.matchLen("repeat_extend_"+name, forwardStart, backStart, srcLeft, LabelRef("repeat_extend_forward_end_"+name))
1239 forwardStart, backStart, srcLeft = nil, nil, nil
1240 Label("repeat_extend_forward_end_" + name)
1241 // s+= length
1242 ADDL(length.As32(), s)
1243 }
1244 }
1245 // Emit
1246 if true {
1247 // length = s-base
1248 length := GP32()
1249 MOVL(s, length)
1250 SUBL(base.As32(), length) // length = s - base
1251
1252 offsetVal := GP32()
1253 MOVL(repeatL, offsetVal)
1254
1255 // Emit as repeat...
1256 o.emitRepeat("match_repeat_"+name, length, offsetVal, nil, dst, LabelRef("repeat_end_emit_"+name), false)
1257
1258 Label("repeat_end_emit_" + name)
1259 // Store new dst and nextEmit
1260 MOVL(s, nextEmitL)
1261 }
1262 // if s >= sLimit is picked up on next loop.
1263 if false {
1264 CMPL(s.As32(), sLimitL)
1265 JAE(LabelRef("emit_remainder_" + name))
1266 }
1267 JMP(LabelRef("search_loop_" + name))
1268 }
1269 Label("no_repeat_found_" + name)
1270 {
1271 // Check candidates are ok. All must be < s and < len(src)
1272 assert(func(ok LabelRef) {
1273 tmp := GP64()
1274 MOVQ(lenSrcQ, tmp)
1275 CMPL(tmp.As32(), candidate)
1276 JA(ok)
1277 })
1278 assert(func(ok LabelRef) {
1279 CMPL(s, candidate)
1280 JA(ok)
1281 })
1282 assert(func(ok LabelRef) {
1283 tmp := GP64()
1284 MOVQ(lenSrcQ, tmp)
1285 CMPL(tmp.As32(), candidateS)
1286 JA(ok)
1287 })
1288 assert(func(ok LabelRef) {
1289 CMPL(s, candidateS)
1290 JA(ok)
1291 })
1292
1293 CMPL(longVal.As32(), cv.As32())
1294 JEQ(LabelRef("candidate_match_" + name))
1295
1296 //if uint32(cv) == load32(src, candidateS)
1297 CMPL(shortVal.As32(), cv.As32())
1298 JEQ(LabelRef("candidateS_match_" + name))
1299
1300 // No match found, next loop
1301 // s = nextS
1302 MOVL(nextSTempL, s)
1303 JMP(LabelRef("search_loop_" + name))
1304
1305 // Short match at s, try a long candidate at s+1
1306 Label("candidateS_match_" + name)
1307 if true {
1308 hash0 := GP64()
1309 SHRQ(U8(8), cv)
1310 MOVQ(cv, hash0)
1311 lHasher.hash(hash0)
1312 MOVL(lTab.Idx(hash0, 4), candidate)
1313 INCL(s)
1314 assert(func(ok LabelRef) {
1315 CMPQ(hash0, U32(lTableSize))
1316 JB(ok)
1317 })
1318 MOVL(s, lTab.Idx(hash0, 4))
1319 CMPL(Mem{Base: src, Index: candidate, Scale: 1}, cv.As32())
1320 JEQ(LabelRef("candidate_match_" + name))
1321 // No match, decrement s again and use short match at s...
1322 DECL(s)
1323 }
1324 MOVL(candidateS, candidate)
1325 }
1326 }
1327
1328 Label("candidate_match_" + name)
1329 // We have a match at 's' with src offset in "candidate" that matches at least 4 bytes.
1330 // Extend backwards
1331 if true {
1332 ne := GP32()
1333 MOVL(nextEmitL, ne)
1334 TESTL(candidate, candidate)
1335 JZ(LabelRef("match_extend_back_end_" + name))
1336
1337 // candidate is tested when decremented, so we loop back here.
1338 Label("match_extend_back_loop_" + name)
1339 // if s <= nextEmit {exit}
1340 CMPL(s, ne)
1341 JBE(LabelRef("match_extend_back_end_" + name))
1342 // if src[candidate-1] == src[s-1]
1343 tmp, tmp2 := GP64(), GP64()
1344 MOVB(Mem{Base: src, Index: candidate, Scale: 1, Disp: -1}, tmp.As8())
1345 MOVB(Mem{Base: src, Index: s, Scale: 1, Disp: -1}, tmp2.As8())
1346 CMPB(tmp.As8(), tmp2.As8())
1347 JNE(LabelRef("match_extend_back_end_" + name))
1348 LEAL(Mem{Base: s, Disp: -1}, s)
1349 DECL(candidate)
1350 JZ(LabelRef("match_extend_back_end_" + name))
1351 JMP(LabelRef("match_extend_back_loop_" + name))
1352 }
1353 Label("match_extend_back_end_" + name)
1354
1355 // Bail if we exceed the maximum size.
1356 if true {
1357 // tmp = s-nextEmit
1358 tmp := GP64()
1359 MOVL(s, tmp.As32())
1360 SUBL(nextEmitL, tmp.As32())
1361 // tmp = &dst + s-nextEmit
1362 LEAQ(Mem{Base: dst, Index: tmp, Scale: 1, Disp: literalMaxOverhead}, tmp)
1363 CMPQ(tmp, dstLimitPtrQ)
1364 JB(LabelRef("match_dst_size_check_" + name))
1365 ri, err := ReturnIndex(0).Resolve()
1366 if err != nil {
1367 panic(err)
1368 }
1369 MOVQ(U32(0), ri.Addr)
1370 if o.avx2 {
1371 VZEROUPPER()
1372 }
1373 RET()
1374 }
1375 Label("match_dst_size_check_" + name)
1376
1377 base := GP32()
1378 MOVL(s, base.As32())
1379
1380 // s+=4, candidate+=4
1381 ADDL(U8(4), s)
1382 ADDL(U8(4), candidate)
1383 // Extend the 4-byte match as long as possible and emit copy.
1384 {
1385 assert(func(ok LabelRef) {
1386 // s must be > candidate cannot be equal.
1387 CMPL(s, candidate)
1388 JA(ok)
1389 })
1390 // srcLeft = len(src) - s
1391 srcLeft := GP64()
1392 MOVQ(lenSrcQ, srcLeft)
1393 SUBL(s, srcLeft.As32())
1394 assert(func(ok LabelRef) {
1395 // if srcleft < maxint32: ok
1396 CMPQ(srcLeft, U32(0x7fffffff))
1397 JB(ok)
1398 })
1399
1400 a, b := GP64(), GP64()
1401 LEAQ(Mem{Base: src, Index: s, Scale: 1}, a)
1402 LEAQ(Mem{Base: src, Index: candidate, Scale: 1}, b)
1403 length := o.matchLen("match_nolit_"+name,
1404 a, b,
1405 srcLeft,
1406 LabelRef("match_nolit_end_"+name),
1407 )
1408 Label("match_nolit_end_" + name)
1409 assert(func(ok LabelRef) {
1410 CMPL(length.As32(), U32(math.MaxInt32))
1411 JB(ok)
1412 })
1413 a, b, srcLeft = nil, nil, nil
1414
1415 offset := GP64()
1416 offset32 := offset.As32()
1417 {
1418 // offset = base - candidate
1419 MOVL(s, offset32)
1420 SUBL(candidate, offset32)
1421 Comment("Check if repeat")
1422 if !o.snappy {
1423 CMPL(repeatL, offset32)
1424 JEQ(LabelRef("match_is_repeat_" + name))
1425 }
1426
1427 // NOT REPEAT
1428 {
1429 // Check if match is better..
1430 if o.maxOffset > 65535 {
1431 CMPL(length.As32(), U8(1))
1432 JA(LabelRef("match_length_ok_" + name))
1433 CMPL(offset32, U32(65535))
1434 JBE(LabelRef("match_length_ok_" + name))
1435 // Match is equal or worse to the encoding.
1436 MOVL(nextSTempL, s)
1437 INCL(s)
1438 JMP(LabelRef("search_loop_" + name))
1439 Label("match_length_ok_" + name)
1440 }
1441 // Store updated repeat
1442 MOVL(offset32, repeatL)
1443 // Emit....
1444 o.emitLiteralsDstP(nextEmitL, base, src, dst, "match_emit_"+name)
1445 // s += length (length is destroyed, use it now)
1446 ADDL(length.As32(), s)
1447
1448 // length += 4
1449 ADDL(U8(4), length.As32())
1450 MOVL(s, nextEmitL) // nextEmit = s
1451 o.emitCopy("match_nolit_"+name, length, offset, nil, dst, nil, LabelRef("match_nolit_emitcopy_end_"+name))
1452 // Jumps at end
1453 }
1454 // REPEAT
1455 if !o.snappy {
1456 Label("match_is_repeat_" + name)
1457 // Emit....
1458 o.emitLiteralsDstP(nextEmitL, base, src, dst, "match_emit_repeat_"+name)
1459 // s += length (length is destroyed, use it now)
1460 ADDL(length.As32(), s)
1461
1462 // length += 4
1463 ADDL(U8(4), length.As32())
1464 MOVL(s, nextEmitL) // nextEmit = s
1465 o.emitRepeat("match_nolit_repeat_"+name, length, offset, nil, dst, LabelRef("match_nolit_emitcopy_end_"+name), false)
1466 }
1467 }
1468 Label("match_nolit_emitcopy_end_" + name)
1469
1470 // if s >= sLimit { end }
1471 {
1472 CMPL(s.As32(), sLimitL)
1473 JAE(LabelRef("emit_remainder_" + name))
1474 }
1475
1476 // Bail if we exceed the maximum size.
1477 {
1478 CMPQ(dst, dstLimitPtrQ)
1479 JB(LabelRef("match_nolit_dst_ok_" + name))
1480 ri, err := ReturnIndex(0).Resolve()
1481 if err != nil {
1482 panic(err)
1483 }
1484 MOVQ(U32(0), ri.Addr)
1485 if o.avx2 {
1486 VZEROUPPER()
1487 }
1488 RET()
1489 }
1490 }
1491 Label("match_nolit_dst_ok_" + name)
1492 if true {
1493 lHasher := hashN(lHashBytes, lTableBits)
1494 sHasher := hashN(sHashBytes, sTableBits)
1495
1496 index0, index1 := GP64(), GP64()
1497 // index0 := base + 1
1498 LEAQ(Mem{Base: base, Disp: 1}, index0)
1499 // index1 := s - 2
1500 LEAQ(Mem{Base: s, Disp: -2}, index1)
1501 hash0l, hash0s, hash1l, hash1s := GP64(), GP64(), GP64(), GP64()
1502 MOVQ(Mem{Base: src, Index: index0, Scale: 1, Disp: 0}, hash0l)
1503 MOVQ(Mem{Base: src, Index: index0, Scale: 1, Disp: 1}, hash0s)
1504 MOVQ(Mem{Base: src, Index: index1, Scale: 1, Disp: 0}, hash1l)
1505 MOVQ(Mem{Base: src, Index: index1, Scale: 1, Disp: 1}, hash1s)
1506
1507 lHasher.hash(hash0l)
1508 sHasher.hash(hash0s)
1509 lHasher.hash(hash1l)
1510 sHasher.hash(hash1s)
1511
1512 plusone0, plusone1 := GP64(), GP64()
1513 LEAQ(Mem{Base: index0, Disp: 1}, plusone0)
1514 LEAQ(Mem{Base: index1, Disp: 1}, plusone1)
1515 MOVL(index0.As32(), lTab.Idx(hash0l, 4))
1516 MOVL(index1.As32(), lTab.Idx(hash1l, 4))
1517 MOVL(plusone0.As32(), sTab.Idx(hash0s, 4))
1518 MOVL(plusone1.As32(), sTab.Idx(hash1s, 4))
1519
1520 // index2 := (index0 + index1 + 1) >> 1
1521 index2 := GP64()
1522 LEAQ(Mem{Base: index1, Disp: 1, Index: index0, Scale: 1}, index2)
1523 SHRQ(U8(1), index2)
1524
1525 ADDQ(U8(1), index0)
1526 SUBQ(U8(1), index1)
1527
1528 Label("index_loop_" + name)
1529 // for index2 < index1
1530 CMPQ(index2, index1)
1531 JAE(LabelRef("search_loop_" + name))
1532 hash0l, hash1l = GP64(), GP64()
1533 MOVQ(Mem{Base: src, Index: index0, Scale: 1, Disp: 0}, hash0l)
1534 MOVQ(Mem{Base: src, Index: index2, Scale: 1, Disp: 0}, hash1l)
1535
1536 lHasher.hash(hash0l)
1537 lHasher.hash(hash1l)
1538
1539 MOVL(index0.As32(), lTab.Idx(hash0l, 4))
1540 MOVL(index2.As32(), lTab.Idx(hash1l, 4))
1541
1542 ADDQ(U8(2), index0)
1543 ADDQ(U8(2), index2)
1544 JMP(LabelRef("index_loop_" + name))
1545 } else {
1546 lHasher := hashN(lHashBytes, lTableBits)
1547 sHasher := hashN(sHashBytes, sTableBits)
1548
1549 // Index base+1 long, base+2 short...
1550 cv := GP64()
1551 INCL(base)
1552 MOVQ(Mem{Base: src, Index: base, Scale: 1, Disp: 0}, cv)
1553 hash0, hash1, hash2, hash3 := GP64(), GP64(), GP64(), GP64()
1554 MOVQ(cv, hash0) // src[base+1]
1555 MOVQ(cv, hash1)
1556 MOVQ(cv, hash2)
1557 SHRQ(U8(8), hash1) // src[base+2]
1558 MOVQ(hash1, hash3)
1559 SHRQ(U8(16), hash2) // src[base+3]
1560 bp1, bp2 := GP32(), GP32() // base+1
1561 LEAL(Mem{Base: base, Disp: 1}, bp1)
1562 LEAL(Mem{Base: base, Disp: 2}, bp2)
1563
1564 // Load s-2 early
1565 MOVQ(Mem{Base: src, Index: s, Scale: 1, Disp: -2}, cv)
1566
1567 lHasher.hash(hash0)
1568 lHasher.hash(hash3)
1569 sHasher.hash(hash1)
1570 sHasher.hash(hash2)
1571 assert(func(ok LabelRef) {
1572 CMPQ(hash0, U32(lTableSize))
1573 JB(ok)
1574 })
1575 assert(func(ok LabelRef) {
1576 CMPQ(hash3, U32(lTableSize))
1577 JB(ok)
1578 })
1579 assert(func(ok LabelRef) {
1580 CMPQ(hash1, U32(sTableSize))
1581 JB(ok)
1582 })
1583 assert(func(ok LabelRef) {
1584 CMPQ(hash2, U32(sTableSize))
1585 JB(ok)
1586 })
1587 MOVL(base, lTab.Idx(hash0, 4))
1588 MOVL(bp1, lTab.Idx(hash3, 4))
1589 MOVL(bp1, sTab.Idx(hash1, 4))
1590 MOVL(bp2, sTab.Idx(hash2, 4))
1591
1592 // Index s-2 long, s-1 long+short...
1593 MOVQ(cv, hash0) // src[s-2]
1594 MOVQ(cv, hash1) // src[s-1]
1595 SHRQ(U8(8), hash1)
1596 MOVQ(hash1, hash3)
1597 sm1, sm2 := GP32(), GP32() // s -1, s - 2
1598 LEAL(Mem{Base: s, Disp: -2}, sm2)
1599 LEAL(Mem{Base: s, Disp: -1}, sm1)
1600 lHasher.hash(hash0)
1601 sHasher.hash(hash1)
1602 lHasher.hash(hash3)
1603 assert(func(ok LabelRef) {
1604 CMPQ(hash0, U32(lTableSize))
1605 JB(ok)
1606 })
1607 assert(func(ok LabelRef) {
1608 CMPQ(hash3, U32(lTableSize))
1609 JB(ok)
1610 })
1611 assert(func(ok LabelRef) {
1612 CMPQ(hash1, U32(sTableSize))
1613 JB(ok)
1614 })
1615 MOVL(sm2, lTab.Idx(hash0, 4))
1616 MOVL(sm1, sTab.Idx(hash1, 4))
1617 MOVL(sm1, lTab.Idx(hash3, 4))
1618 JMP(LabelRef("search_loop_" + name))
1619 }
1620
1621 Label("emit_remainder_" + name)
1622 // Bail if we exceed the maximum size.
1623 // if d+len(src)-nextEmitL > dstLimitPtrQ { return 0
1624 {
1625 // remain = len(src) - nextEmit
1626 remain := GP64()
1627 MOVQ(lenSrcQ, remain)
1628 SUBL(nextEmitL, remain.As32())
1629
1630 dstExpect := GP64()
1631 // dst := dst + (len(src)-nextEmitL)
1632
1633 LEAQ(Mem{Base: dst, Index: remain, Scale: 1, Disp: literalMaxOverhead}, dstExpect)
1634 CMPQ(dstExpect, dstLimitPtrQ)
1635 JB(LabelRef("emit_remainder_ok_" + name))
1636 ri, err := ReturnIndex(0).Resolve()
1637 if err != nil {
1638 panic(err)
1639 }
1640 MOVQ(U32(0), ri.Addr)
1641 if o.avx2 {
1642 VZEROUPPER()
1643 }
1644 RET()
1645 Label("emit_remainder_ok_" + name)
1646 }
1647 // emitLiteral(dst[d:], src[nextEmitL:])
1648 emitEnd := GP64()
1649 MOVQ(lenSrcQ, emitEnd)
1650
1651 // Emit final literals.
1652 // Since we may be at the end of source,
1653 // we cannot have output margin.
1654 x := o.outputMargin
1655 o.outputMargin = 0
1656 o.emitLiteralsDstP(nextEmitL, emitEnd, src, dst, "emit_remainder_"+name)
1657 o.outputMargin = x
1658
1659 // Assert size is < limit
1660 assert(func(ok LabelRef) {
1661 // if dstBaseQ < dstLimitPtrQ: ok
1662 CMPQ(dst, dstLimitPtrQ)
1663 JB(ok)
1664 })
1665
1666 // length := start - base (ptr arithmetic)
1667 length := GP64()
1668 dstBase := Load(Param("dst").Base(), GP64())
1669 MOVQ(dst, length)
1670 SUBQ(dstBase, length)
1671
1672 // Assert size is < len(src)
1673 assert(func(ok LabelRef) {
1674 // if len(src) >= length: ok
1675 CMPQ(lenSrcQ, length)
1676 JAE(ok)
1677 })
1678 // Assert size is < len(dst)
1679 assert(func(ok LabelRef) {
1680 // if len(dst) >= length: ok
1681 CMPQ(lenDstQ, length)
1682 JAE(ok)
1683 })
1684 Store(length, ReturnIndex(0))
1685 if o.avx2 {
1686 VZEROUPPER()
1687 }
1688 RET()
1689 }
1690
1691 // emitLiterals emits literals from nextEmit to base, updates nextEmit, dstBase.
1692 // Checks if base == nextemit.
1693 // src & base are untouched.
1694 func (o options) emitLiterals(nextEmitL Mem, base reg.GPVirtual, src reg.GPVirtual, dstBase Mem, name string) {
1695 nextEmit, litLen, dstBaseTmp, litBase := GP32(), GP32(), GP64(), GP64()
1696 MOVL(nextEmitL, nextEmit)
1697 CMPL(nextEmit, base.As32())
1698 JEQ(LabelRef("emit_literal_skip_" + name))
1699 MOVL(base.As32(), litLen.As32())
1700
1701 // Base is now next emit.
1702 MOVL(base.As32(), nextEmitL)
1703
1704 // litBase = src[nextEmitL:]
1705 LEAQ(Mem{Base: src, Index: nextEmit, Scale: 1}, litBase)
1706 SUBL(nextEmit, litLen.As32()) // litlen = base - nextEmit
1707
1708 // Load (and store when we return)
1709 MOVQ(dstBase, dstBaseTmp)
1710 o.emitLiteral(name, litLen, nil, dstBaseTmp, litBase, LabelRef("emit_literal_done_"+name), true)
1711 Label("emit_literal_done_" + name)
1712
1713 // Emitted length must be > litlen.
1714 // We have already checked for len(0) above.
1715 assert(func(ok LabelRef) {
1716 tmp := GP64()
1717 MOVQ(dstBaseTmp, tmp)
1718 SUBQ(dstBase, tmp) // tmp = dstBaseTmp - dstBase
1719 // if tmp > litLen: ok
1720 CMPQ(tmp, litLen.As64())
1721 JA(ok)
1722 })
1723 // Store updated dstBase
1724 MOVQ(dstBaseTmp, dstBase)
1725 Label("emit_literal_skip_" + name)
1726 }
1727
1728 // emitLiterals emits literals from nextEmit to base, updates nextEmit, dstBase.
1729 // Checks if base == nextemit.
1730 // src & base are untouched.
1731 func (o options) emitLiteralsDstP(nextEmitL Mem, base reg.GPVirtual, src, dst reg.GPVirtual, name string) {
1732 nextEmit, litLen, litBase := GP32(), GP32(), GP64()
1733 MOVL(nextEmitL, nextEmit)
1734 CMPL(nextEmit, base.As32())
1735 JEQ(LabelRef("emit_literal_done_" + name))
1736 MOVL(base.As32(), litLen.As32())
1737
1738 // Base is now next emit.
1739 MOVL(base.As32(), nextEmitL)
1740
1741 // litBase = src[nextEmitL:]
1742 LEAQ(Mem{Base: src, Index: nextEmit, Scale: 1}, litBase)
1743 SUBL(nextEmit, litLen.As32()) // litlen = base - nextEmit
1744
1745 // Load (and store when we return)
1746 o.emitLiteral(name, litLen, nil, dst, litBase, LabelRef("emit_literal_done_"+name), true)
1747 Label("emit_literal_done_" + name)
1748 }
1749
1750 type hashGen struct {
1751 bytes int
1752 tablebits int
1753 mulreg reg.GPVirtual
1754 }
1755
1756 // hashN uses multiply to get a 'output' hash on the hash of the lowest 'bytes' bytes in value.
1757 func hashN(hashBytes, tablebits int) hashGen {
1758 h := hashGen{
1759 bytes: hashBytes,
1760 tablebits: tablebits,
1761 mulreg: GP64(),
1762 }
1763 primebytes := uint64(0)
1764 switch hashBytes {
1765 case 3:
1766 primebytes = 506832829
1767 case 4:
1768 primebytes = 2654435761
1769 case 5:
1770 primebytes = 889523592379
1771 case 6:
1772 primebytes = 227718039650203
1773 case 7:
1774 primebytes = 58295818150454627
1775 case 8:
1776 primebytes = 0xcf1bbcdcb7a56463
1777 default:
1778 panic("invalid hash length")
1779 }
1780 MOVQ(Imm(primebytes), h.mulreg)
1781 return h
1782 }
1783
1784 // hash uses multiply to get hash of the value.
1785 func (h hashGen) hash(val reg.GPVirtual) {
1786 // Move value to top of register.
1787 if h.bytes < 8 {
1788 SHLQ(U8(64-8*h.bytes), val)
1789 }
1790 // 329 AMD64 :IMUL r64, r64 L: 0.86ns= 3.0c T: 0.29ns= 1.00c
1791 // 2020 BMI2 :MULX r64, r64, r64 L: 1.14ns= 4.0c T: 0.29ns= 1.00c
1792 IMULQ(h.mulreg, val)
1793 // Move value to bottom
1794 // 2032 BMI2 :SHRX r64, r64, r64 L: 0.29ns= 1.0c T: 0.12ns= 0.42c
1795 // 236 AMD64 :SHR r64, imm8 L: 0.29ns= 1.0c T: 0.13ns= 0.46c
1796 SHRQ(U8(64-h.tablebits), val)
1797 }
1798
1799 func (o options) genEmitLiteral() {
1800 TEXT("emitLiteral", NOSPLIT, "func(dst, lit []byte) int")
1801 Doc("emitLiteral writes a literal chunk and returns the number of bytes written.", "",
1802 "It assumes that:",
1803 fmt.Sprintf(" dst is long enough to hold the encoded bytes with margin of %d bytes", o.outputMargin),
1804 " 0 <= len(lit) && len(lit) <= math.MaxUint32", "")
1805 Pragma("noescape")
1806
1807 dstBase, litBase, litLen, retval := GP64(), GP64(), GP64(), GP64()
1808 Load(Param("lit").Len(), litLen)
1809 Load(Param("dst").Base(), dstBase)
1810 Load(Param("lit").Base(), litBase)
1811 TESTQ(litLen, litLen)
1812 JZ(LabelRef("emit_literal_end_standalone_skip"))
1813 o.emitLiteral("standalone", litLen, retval, dstBase, litBase, "emit_literal_end_standalone", false)
1814
1815 Label("emit_literal_end_standalone_skip")
1816 XORQ(retval, retval)
1817
1818 Label("emit_literal_end_standalone")
1819 Store(retval, ReturnIndex(0))
1820 RET()
1821
1822 }
1823
1824 // emitLiteral can be used for inlining an emitLiteral call.
1825 // litLen must be > 0.
1826 // stack must have at least 32 bytes.
1827 // retval will contain emitted bytes, but can be nil if this is not interesting.
1828 // dstBase and litBase are updated.
1829 // Uses 2 GP registers.
1830 // If updateDst is true dstBase will have the updated end pointer and an additional register will be used.
1831 func (o options) emitLiteral(name string, litLen, retval, dstBase, litBase reg.GPVirtual, end LabelRef, updateDst bool) {
1832 n := GP32()
1833 n16 := GP32()
1834
1835 // litLen must be > 0
1836 assert(func(ok LabelRef) {
1837 TESTL(litLen.As32(), litLen.As32())
1838 JNZ(ok)
1839 })
1840
1841 // We always add litLen bytes
1842 if retval != nil {
1843 MOVL(litLen.As32(), retval.As32())
1844 }
1845 // n = litlen - 1
1846 LEAL(Mem{Base: litLen.As32(), Disp: -1}, n)
1847
1848 // Find number of bytes to emit for tag.
1849 CMPL(n.As32(), U8(60))
1850 JB(LabelRef("one_byte_" + name))
1851 CMPL(n.As32(), U32(1<<8))
1852 JB(LabelRef("two_bytes_" + name))
1853 if o.maxLen >= 1<<16 {
1854 CMPL(n.As32(), U32(1<<16))
1855 JB(LabelRef("three_bytes_" + name))
1856 } else {
1857 JB(LabelRef("three_bytes_" + name))
1858 }
1859 if o.maxLen >= 1<<16 {
1860 if o.maxLen >= 1<<24 {
1861 CMPL(n.As32(), U32(1<<24))
1862 JB(LabelRef("four_bytes_" + name))
1863 } else {
1864 JMP(LabelRef("four_bytes_" + name))
1865 }
1866 }
1867 if o.maxLen >= 1<<24 {
1868 Label("five_bytes_" + name)
1869 if !o.skipOutput {
1870 MOVB(U8(252), Mem{Base: dstBase})
1871 MOVL(n.As32(), Mem{Base: dstBase, Disp: 1})
1872 }
1873 if retval != nil {
1874 ADDQ(U8(5), retval)
1875 }
1876 ADDQ(U8(5), dstBase)
1877 JMP(LabelRef("memmove_long_" + name))
1878 }
1879 if o.maxLen >= 1<<16 {
1880 Label("four_bytes_" + name)
1881 if !o.skipOutput {
1882 MOVL(n, n16)
1883 SHRL(U8(16), n16.As32())
1884 MOVB(U8(248), Mem{Base: dstBase})
1885 MOVW(n.As16(), Mem{Base: dstBase, Disp: 1})
1886 MOVB(n16.As8(), Mem{Base: dstBase, Disp: 3})
1887 }
1888 if retval != nil {
1889 ADDQ(U8(4), retval)
1890 }
1891 ADDQ(U8(4), dstBase)
1892 JMP(LabelRef("memmove_long_" + name))
1893 }
1894 Label("three_bytes_" + name)
1895 if !o.skipOutput {
1896 MOVB(U8(0xf4), Mem{Base: dstBase})
1897 MOVW(n.As16(), Mem{Base: dstBase, Disp: 1})
1898 }
1899 if retval != nil {
1900 ADDQ(U8(3), retval)
1901 }
1902 ADDQ(U8(3), dstBase)
1903 JMP(LabelRef("memmove_long_" + name))
1904
1905 Label("two_bytes_" + name)
1906 if !o.skipOutput {
1907 MOVB(U8(0xf0), Mem{Base: dstBase})
1908 MOVB(n.As8(), Mem{Base: dstBase, Disp: 1})
1909 }
1910 if retval != nil {
1911 ADDQ(U8(2), retval)
1912 }
1913 ADDQ(U8(2), dstBase)
1914 CMPL(n.As32(), U8(64))
1915 JB(LabelRef("memmove_" + name))
1916 JMP(LabelRef("memmove_long_" + name))
1917
1918 Label("one_byte_" + name)
1919 if !o.skipOutput {
1920 SHLB(U8(2), n.As8())
1921 MOVB(n.As8(), Mem{Base: dstBase})
1922 }
1923 if retval != nil {
1924 ADDQ(U8(1), retval)
1925 }
1926 ADDQ(U8(1), dstBase)
1927 // Fallthrough
1928
1929 Label("memmove_" + name)
1930
1931 // copy(dst[i:], lit)
1932 dstEnd := GP64()
1933 copyEnd := end
1934 if updateDst {
1935 copyEnd = LabelRef("memmove_end_copy_" + name)
1936 LEAQ(Mem{Base: dstBase, Index: litLen, Scale: 1}, dstEnd)
1937 }
1938 if !o.skipOutput {
1939
1940 length := GP64()
1941 MOVL(litLen.As32(), length.As32())
1942
1943 // We wrote one byte, we have that less in output margin.
1944 o.outputMargin--
1945 // updates litBase.
1946 o.genMemMoveShort("emit_lit_memmove_"+name, dstBase, litBase, length, copyEnd)
1947 o.outputMargin++
1948 }
1949 if updateDst {
1950 Label("memmove_end_copy_" + name)
1951 MOVQ(dstEnd, dstBase)
1952 }
1953 JMP(end)
1954
1955 // > 64 bytes
1956 Label("memmove_long_" + name)
1957
1958 // copy(dst[i:], lit)
1959 dstEnd = GP64()
1960 copyEnd = end
1961 if updateDst {
1962 copyEnd = LabelRef("memmove_end_copy_long_" + name)
1963 LEAQ(Mem{Base: dstBase, Index: litLen, Scale: 1}, dstEnd)
1964 }
1965 if !o.skipOutput {
1966 length := GP64()
1967 MOVL(litLen.As32(), length.As32())
1968
1969 // updates litBase.
1970 o.genMemMoveLong("emit_lit_memmove_long_"+name, dstBase, litBase, length, copyEnd)
1971 }
1972 if updateDst {
1973 Label("memmove_end_copy_long_" + name)
1974 MOVQ(dstEnd, dstBase)
1975 }
1976 JMP(end)
1977 // Should be unreachable
1978 if debug {
1979 INT(Imm(3))
1980 }
1981 return
1982 }
1983
1984 // genEmitRepeat generates a standalone emitRepeat.
1985 func (o options) genEmitRepeat() {
1986 TEXT("emitRepeat", NOSPLIT, "func(dst []byte, offset, length int) int")
1987 Doc("emitRepeat writes a repeat chunk and returns the number of bytes written.",
1988 "Length must be at least 4 and < 1<<32", "")
1989 Pragma("noescape")
1990
1991 dstBase, offset, length, retval := GP64(), GP64(), GP64(), GP64()
1992
1993 // retval = 0
1994 XORQ(retval, retval)
1995
1996 Load(Param("dst").Base(), dstBase)
1997 Load(Param("offset"), offset)
1998 Load(Param("length"), length)
1999 o.emitRepeat("standalone", length, offset, retval, dstBase, LabelRef("gen_emit_repeat_end"), false)
2000 Label("gen_emit_repeat_end")
2001 Store(retval, ReturnIndex(0))
2002 RET()
2003 }
2004
2005 // emitRepeat can be used for inlining an emitRepeat call.
2006 // length >= 4 and < 1<<32
2007 // length is modified. dstBase is updated. retval is added to input.
2008 // retval can be nil.
2009 // Will jump to end label when finished.
2010 // Uses 1 GP register.
2011 // longer indicates we know match will be > 12
2012 func (o options) emitRepeat(name string, length reg.GPVirtual, offset reg.GPVirtual, retval reg.GPVirtual, dstBase reg.GPVirtual, end LabelRef, longer bool) {
2013 Comment("emitRepeat")
2014 if longer {
2015 // Skip initial length tests
2016 LEAL(Mem{Base: length, Disp: -4}, length.As32()) // length -= 4
2017 JMP(LabelRef("cant_repeat_two_offset_" + name))
2018 }
2019 Label("emit_repeat_again_" + name)
2020 tmp := GP32()
2021 MOVL(length.As32(), tmp) // Copy length
2022 LEAL(Mem{Base: length, Disp: -4}, length.As32()) // length -= 4
2023
2024 // if length <= 4 (use copied value)
2025 CMPL(tmp.As32(), U8(8))
2026 JBE(LabelRef("repeat_two_" + name))
2027
2028 // length < 8 && offset < 2048
2029 CMPL(tmp.As32(), U8(12))
2030 JAE(LabelRef("cant_repeat_two_offset_" + name))
2031 if o.maxLen >= 2048 {
2032 CMPL(offset.As32(), U32(2048))
2033 JB(LabelRef("repeat_two_offset_" + name))
2034 }
2035
2036 const maxRepeat = ((1 << 24) - 1) + 65536
2037 Label("cant_repeat_two_offset_" + name)
2038 CMPL(length.As32(), U32((1<<8)+4))
2039 JB(LabelRef("repeat_three_" + name)) // if length < (1<<8)+4
2040 if o.maxLen >= (1<<16)+(1<<8) {
2041 CMPL(length.As32(), U32((1<<16)+(1<<8)))
2042 JB(LabelRef("repeat_four_" + name)) // if length < (1 << 16) + (1 << 8)
2043 } else {
2044 // Not needed, we should skip to it when generating.
2045 // JMP(LabelRef("repeat_four_" + name)) // if length < (1 << 16) + (1 << 8)
2046 }
2047 if o.maxLen >= maxRepeat {
2048 CMPL(length.As32(), U32(maxRepeat))
2049 JB(LabelRef("repeat_five_" + name)) // If less than 24 bits to represent.
2050
2051 if !o.skipOutput {
2052 // We have have more than 24 bits
2053 // Emit so we have at least 4 bytes left.
2054 LEAL(Mem{Base: length, Disp: -(maxRepeat - 4)}, length.As32()) // length -= (maxRepeat - 4)
2055 MOVL(U32(7<<2|tagCopy1|(65531<<16)), Mem{Base: dstBase}) // dst[0] = 7<<2 | tagCopy1, dst[1] = 0 dst[2+3] = 65531
2056 MOVB(U8(255), Mem{Base: dstBase, Disp: 4})
2057 ADDQ(U8(5), dstBase)
2058 }
2059 if retval != nil {
2060 ADDQ(U8(5), retval)
2061 }
2062 JMP(LabelRef("emit_repeat_again_" + name))
2063 } else {
2064 // Not needed.
2065 // JMP(LabelRef("repeat_five_" + name)) // If less than 24 bits to represent.
2066 }
2067
2068 // Must be able to be within 5 bytes.
2069 if o.maxLen >= (1<<16)+(1<<8) {
2070 Label("repeat_five_" + name)
2071 LEAL(Mem{Base: length, Disp: -65536}, length.As32()) // length -= 65536
2072 if !o.skipOutput {
2073 MOVL(length.As32(), offset.As32())
2074 MOVW(U16(7<<2|tagCopy1), Mem{Base: dstBase}) // dst[0] = 7<<2 | tagCopy1, dst[1] = 0
2075 MOVW(length.As16(), Mem{Base: dstBase, Disp: 2}) // dst[2] = uint8(length), dst[3] = uint8(length >> 8)
2076 SARL(U8(16), offset.As32()) // offset = length >> 16
2077 MOVB(offset.As8(), Mem{Base: dstBase, Disp: 4}) // dst[4] = length >> 16
2078 }
2079 if retval != nil {
2080 ADDQ(U8(5), retval) // i += 5
2081 }
2082 ADDQ(U8(5), dstBase) // dst += 5
2083 JMP(end)
2084 }
2085 Label("repeat_four_" + name)
2086 if !o.skipOutput {
2087 LEAL(Mem{Base: length, Disp: -256}, length.As32()) // length -= 256
2088 MOVW(U16(6<<2|tagCopy1), Mem{Base: dstBase}) // dst[0] = 6<<2 | tagCopy1, dst[1] = 0
2089 MOVW(length.As16(), Mem{Base: dstBase, Disp: 2}) // dst[2] = uint8(length), dst[3] = uint8(length >> 8)
2090 }
2091 if retval != nil {
2092 ADDQ(U8(4), retval) // i += 4
2093 }
2094 ADDQ(U8(4), dstBase) // dst += 4
2095 JMP(end)
2096
2097 Label("repeat_three_" + name)
2098 if !o.skipOutput {
2099 LEAL(Mem{Base: length, Disp: -4}, length.As32()) // length -= 4
2100 MOVW(U16(5<<2|tagCopy1), Mem{Base: dstBase}) // dst[0] = 5<<2 | tagCopy1, dst[1] = 0
2101 MOVB(length.As8(), Mem{Base: dstBase, Disp: 2}) // dst[2] = uint8(length)
2102 }
2103 if retval != nil {
2104 ADDQ(U8(3), retval) // i += 3
2105 }
2106 ADDQ(U8(3), dstBase) // dst += 3
2107 JMP(end)
2108
2109 Label("repeat_two_" + name)
2110 // dst[0] = uint8(length)<<2 | tagCopy1, dst[1] = 0
2111 if !o.skipOutput {
2112 SHLL(U8(2), length.As32())
2113 ORL(U8(tagCopy1), length.As32())
2114 MOVW(length.As16(), Mem{Base: dstBase}) // dst[0] = 7<<2 | tagCopy1, dst[1] = 0
2115 }
2116 if retval != nil {
2117 ADDQ(U8(2), retval) // i += 2
2118 }
2119 ADDQ(U8(2), dstBase) // dst += 2
2120 JMP(end)
2121
2122 Label("repeat_two_offset_" + name)
2123 // Emit the remaining copy, encoded as 2 bytes.
2124 // dst[1] = uint8(offset)
2125 // dst[0] = uint8(offset>>8)<<5 | uint8(length)<<2 | tagCopy1
2126 tmp = GP64()
2127 XORQ(tmp, tmp)
2128 // Use scale and displacement to shift and subtract values from length.
2129 if !o.skipOutput {
2130 LEAL(Mem{Base: tmp, Index: length, Scale: 4, Disp: tagCopy1}, length.As32())
2131 MOVB(offset.As8(), Mem{Base: dstBase, Disp: 1}) // Store offset lower byte
2132 SARL(U8(8), offset.As32()) // Remove lower
2133 SHLL(U8(5), offset.As32()) // Shift back up
2134 ORL(offset.As32(), length.As32()) // OR result
2135 MOVB(length.As8(), Mem{Base: dstBase, Disp: 0})
2136 }
2137 if retval != nil {
2138 ADDQ(U8(2), retval) // i += 2
2139 }
2140 ADDQ(U8(2), dstBase) // dst += 2
2141
2142 JMP(end)
2143 }
2144
2145 // emitCopy writes a copy chunk and returns the number of bytes written.
2146 //
2147 // It assumes that:
2148 // dst is long enough to hold the encoded bytes
2149 // 1 <= offset && offset <= math.MaxUint32
2150 // 4 <= length && length <= 1 << 24
2151
2152 // genEmitCopy generates a standalone emitCopy
2153 func (o options) genEmitCopy() {
2154 TEXT("emitCopy", NOSPLIT, "func(dst []byte, offset, length int) int")
2155 Doc("emitCopy writes a copy chunk and returns the number of bytes written.", "",
2156 "It assumes that:",
2157 " dst is long enough to hold the encoded bytes",
2158 " 1 <= offset && offset <= math.MaxUint32",
2159 " 4 <= length && length <= 1 << 24", "")
2160 Pragma("noescape")
2161
2162 dstBase, offset, length, retval := GP64(), GP64(), GP64(), GP64()
2163
2164 // i := 0
2165 XORQ(retval, retval)
2166 Load(Param("dst").Base(), dstBase)
2167 Load(Param("offset"), offset)
2168 Load(Param("length"), length)
2169 o.emitCopy("standalone", length, offset, retval, dstBase, nil, LabelRef("gen_emit_copy_end"))
2170 Label("gen_emit_copy_end")
2171 Store(retval, ReturnIndex(0))
2172 RET()
2173 }
2174
2175 // emitCopy writes a copy chunk and returns the number of bytes written.
2176 //
2177 // It assumes that:
2178 // dst is long enough to hold the encoded bytes
2179 // 1 <= offset && offset <= math.MaxUint32
2180 // 4 <= length && length <= 1 << 24
2181
2182 // genEmitCopy generates a standalone emitCopy
2183 func (o options) genEmitCopyNoRepeat() {
2184 TEXT("emitCopyNoRepeat", NOSPLIT, "func(dst []byte, offset, length int) int")
2185 Doc("emitCopyNoRepeat writes a copy chunk and returns the number of bytes written.", "",
2186 "It assumes that:",
2187 " dst is long enough to hold the encoded bytes",
2188 " 1 <= offset && offset <= math.MaxUint32",
2189 " 4 <= length && length <= 1 << 24", "")
2190 Pragma("noescape")
2191
2192 dstBase, offset, length, retval := GP64(), GP64(), GP64(), GP64()
2193
2194 // i := 0
2195 XORQ(retval, retval)
2196
2197 Load(Param("dst").Base(), dstBase)
2198 Load(Param("offset"), offset)
2199 Load(Param("length"), length)
2200 o.emitCopy("standalone_snappy", length, offset, retval, dstBase, nil, "gen_emit_copy_end_snappy")
2201 Label("gen_emit_copy_end_snappy")
2202 Store(retval, ReturnIndex(0))
2203 RET()
2204 }
2205
2206 const (
2207 tagLiteral = 0x00
2208 tagCopy1 = 0x01
2209 tagCopy2 = 0x02
2210 tagCopy4 = 0x03
2211 )
2212
2213 // emitCopy can be used for inlining an emitCopy call.
2214 // length is modified (and junk). dstBase is updated. retval is added to input.
2215 // retval can be nil.
2216 // Will jump to end label when finished.
2217 // Uses 2 GP registers.
2218 // dstLimit is optional. If set each iteration will check if dstLimit is reached.
2219 // If so, it will jump to "end" without emitting everything.
2220 func (o options) emitCopy(name string, length, offset, retval, dstBase, dstLimit reg.GPVirtual, end LabelRef) {
2221 Comment("emitCopy")
2222
2223 checkDst := func(reg reg.GPVirtual) {
2224 if dstLimit != nil {
2225 CMPQ(reg, dstLimit)
2226 JAE(end)
2227 }
2228 }
2229
2230 if o.maxOffset >= 65536 {
2231 //if offset >= 65536 {
2232 CMPL(offset.As32(), U32(65536))
2233 JB(LabelRef("two_byte_offset_" + name))
2234
2235 // offset is >= 65536
2236 // if length <= 64 goto four_bytes_remain_
2237 Label("four_bytes_loop_back_" + name)
2238 CMPL(length.As32(), U8(64))
2239 JBE(LabelRef("four_bytes_remain_" + name))
2240
2241 if !o.skipOutput {
2242 // Emit a length 64 copy, encoded as 5 bytes.
2243 // dst[0] = 63<<2 | tagCopy4
2244 MOVB(U8(63<<2|tagCopy4), Mem{Base: dstBase})
2245 // dst[4] = uint8(offset >> 24)
2246 // dst[3] = uint8(offset >> 16)
2247 // dst[2] = uint8(offset >> 8)
2248 // dst[1] = uint8(offset)
2249 MOVL(offset.As32(), Mem{Base: dstBase, Disp: 1})
2250 }
2251 // length -= 64
2252 LEAL(Mem{Base: length, Disp: -64}, length.As32())
2253 if retval != nil {
2254 ADDQ(U8(5), retval) // i+=5
2255 }
2256 ADDQ(U8(5), dstBase) // dst+=5
2257
2258 // if length >= 4 {
2259 CMPL(length.As32(), U8(4))
2260 JB(LabelRef("four_bytes_remain_" + name))
2261
2262 // Emit remaining as repeats
2263 // return 5 + emitRepeat(dst[5:], offset, length)
2264 // Inline call to emitRepeat. Will jump to end
2265 if !o.snappy {
2266 o.emitRepeat(name+"_emit_copy", length, offset, retval, dstBase, end, false)
2267 } else {
2268 checkDst(dstBase)
2269 JMP(LabelRef("four_bytes_loop_back_" + name))
2270 }
2271
2272 Label("four_bytes_remain_" + name)
2273 // if length == 0 {
2274 // return i
2275 // }
2276 TESTL(length.As32(), length.As32())
2277 JZ(end)
2278
2279 // Emit a copy, offset encoded as 4 bytes.
2280 // dst[i+0] = uint8(length-1)<<2 | tagCopy4
2281 // dst[i+1] = uint8(offset)
2282 // dst[i+2] = uint8(offset >> 8)
2283 // dst[i+3] = uint8(offset >> 16)
2284 // dst[i+4] = uint8(offset >> 24)
2285 tmp := GP64()
2286 XORL(tmp.As32(), tmp.As32())
2287 // Use displacement to subtract 1 from upshifted length.
2288 if !o.skipOutput {
2289 LEAL(Mem{Base: tmp, Disp: -(1 << 2) | tagCopy4, Index: length, Scale: 4}, length.As32())
2290 MOVB(length.As8(), Mem{Base: dstBase})
2291 MOVL(offset.As32(), Mem{Base: dstBase, Disp: 1})
2292 }
2293 // return i + 5
2294 if retval != nil {
2295 ADDQ(U8(5), retval)
2296 }
2297 ADDQ(U8(5), dstBase)
2298 JMP(end)
2299 }
2300 Label("two_byte_offset_" + name)
2301 // Offset no more than 2 bytes.
2302
2303 //if length > 64 {
2304 CMPL(length.As32(), U8(64))
2305 JBE(LabelRef("two_byte_offset_short_" + name))
2306
2307 // if offset < 2048 {
2308 if !o.snappy {
2309 CMPL(offset.As32(), U32(2048))
2310 JAE(LabelRef("long_offset_short_" + name))
2311 // Emit a length 8 copy, encoded as 2 bytes.
2312 // Emit remaining as repeat value (minimum 4 bytes).
2313 // dst[1] = uint8(offset)
2314 // dst[0] = uint8(offset>>8)<<5 | uint8(8-4)<<2 | tagCopy1
2315 if !o.skipOutput {
2316 tmp := GP64()
2317 MOVL(U32(tagCopy1), tmp.As32())
2318 // Use scale and displacement to shift and subtract values from length.
2319 LEAL(Mem{Base: tmp, Disp: (8 - 4) << 2}, tmp.As32())
2320 MOVB(offset.As8(), Mem{Base: dstBase, Disp: 1}) // Store offset lower byte
2321 tmp2 := GP64()
2322 MOVL(offset.As32(), tmp2.As32())
2323 SHRL(U8(8), tmp2.As32()) // Remove lower
2324 SHLL(U8(5), tmp2.As32()) // Shift back up
2325 ORL(tmp2.As32(), tmp.As32()) // OR result
2326 MOVB(tmp.As8(), Mem{Base: dstBase, Disp: 0})
2327 }
2328 if retval != nil {
2329 ADDQ(U8(2), retval) // i += 2
2330 }
2331 ADDQ(U8(2), dstBase) // dst += 2
2332 SUBL(U8(8), length.As32()) // length -= 8
2333 // emitRepeat(dst[2:], offset, length)
2334 o.emitRepeat(name+"_emit_copy_short_2b", length, offset, retval, dstBase, end, true)
2335
2336 Label("long_offset_short_" + name)
2337 }
2338
2339 // Emit a length 60 copy, encoded as 3 bytes.
2340 // Emit remaining as repeat value (minimum 4 bytes).
2341 // dst[2] = uint8(offset >> 8)
2342 // dst[1] = uint8(offset)
2343 // dst[0] = 59<<2 | tagCopy2
2344 if !o.skipOutput {
2345 MOVB(U8(59<<2|tagCopy2), Mem{Base: dstBase})
2346 MOVW(offset.As16(), Mem{Base: dstBase, Disp: 1})
2347 }
2348 // length -= 60
2349 LEAL(Mem{Base: length, Disp: -60}, length.As32())
2350
2351 // Emit remaining as repeats, at least 4 bytes remain.
2352 // return 3 + emitRepeat(dst[3:], offset, length)
2353 //}
2354 ADDQ(U8(3), dstBase)
2355 if retval != nil {
2356 ADDQ(U8(3), retval)
2357 }
2358 // Inline call to emitRepeat. Will jump to end
2359 if !o.snappy {
2360 o.emitRepeat(name+"_emit_copy_short", length, offset, retval, dstBase, end, false)
2361 } else {
2362 checkDst(dstBase)
2363 JMP(LabelRef("two_byte_offset_" + name))
2364 }
2365
2366 Label("two_byte_offset_short_" + name)
2367
2368 // Create a length * 4 as early as possible.
2369 length4 := GP32()
2370 MOVL(length.As32(), length4)
2371 SHLL(U8(2), length4)
2372
2373 //if length >= 12 || offset >= 2048 {
2374 CMPL(length.As32(), U8(12))
2375 JAE(LabelRef("emit_copy_three_" + name))
2376 if o.maxOffset >= 2048 {
2377 CMPL(offset.As32(), U32(2048))
2378 JAE(LabelRef("emit_copy_three_" + name))
2379 }
2380 // Emit the remaining copy, encoded as 2 bytes.
2381 // dst[1] = uint8(offset)
2382 // dst[0] = uint8(offset>>8)<<5 | uint8(length-4)<<2 | tagCopy1
2383 // Use scale and displacement to shift and subtract values from length.
2384 if !o.skipOutput {
2385 LEAL(Mem{Base: length4, Disp: -(4 << 2) | tagCopy1}, length4.As32())
2386 MOVB(offset.As8(), Mem{Base: dstBase, Disp: 1}) // Store offset lower byte
2387 SHRL(U8(8), offset.As32()) // Remove lower
2388 SHLL(U8(5), offset.As32()) // Shift back up
2389 ORL(offset.As32(), length4.As32()) // OR result
2390 MOVB(length4.As8(), Mem{Base: dstBase, Disp: 0})
2391 }
2392 if retval != nil {
2393 ADDQ(U8(2), retval) // i += 2
2394 }
2395 ADDQ(U8(2), dstBase) // dst += 2
2396 // return 2
2397 JMP(end)
2398
2399 Label("emit_copy_three_" + name)
2400 // // Emit the remaining copy, encoded as 3 bytes.
2401 // dst[2] = uint8(offset >> 8)
2402 // dst[1] = uint8(offset)
2403 // dst[0] = uint8(length-1)<<2 | tagCopy2
2404
2405 if !o.skipOutput {
2406 LEAL(Mem{Base: length4, Disp: -(1 << 2) | tagCopy2}, length4.As32())
2407 MOVB(length4.As8(), Mem{Base: dstBase})
2408 MOVW(offset.As16(), Mem{Base: dstBase, Disp: 1})
2409 }
2410 // return 3
2411 if retval != nil {
2412 ADDQ(U8(3), retval) // i += 3
2413 }
2414 ADDQ(U8(3), dstBase) // dst += 3
2415 JMP(end)
2416 }
2417
2418 // func memmove(to, from unsafe.Pointer, n uintptr)
2419 // src and dst may not overlap.
2420 // Non AVX uses 2 GP register, 16 SSE2 registers.
2421 // AVX uses 4 GP registers 16 AVX/SSE registers.
2422 // All passed registers may be updated.
2423 // Length must be 1 -> 64 bytes
2424 func (o options) genMemMoveShort(name string, dst, src, length reg.GPVirtual, end LabelRef) {
2425 if o.skipOutput {
2426 JMP(end)
2427 return
2428 }
2429 Comment("genMemMoveShort")
2430 AX, CX := GP64(), GP64()
2431 name += "_memmove_"
2432
2433 // Only enable if length can be 0.
2434 if false {
2435 TESTQ(length, length)
2436 JEQ(end)
2437 }
2438 assert(func(ok LabelRef) {
2439 CMPQ(length, U8(64))
2440 JBE(ok)
2441 })
2442 assert(func(ok LabelRef) {
2443 TESTQ(length, length)
2444 JNZ(ok)
2445 })
2446
2447 if o.outputMargin <= 3 {
2448 CMPQ(length, U8(3))
2449 JB(LabelRef(name + "move_1or2"))
2450 JE(LabelRef(name + "move_3"))
2451 } else if o.outputMargin >= 4 && o.outputMargin < 8 {
2452 CMPQ(length, U8(4))
2453 JBE(LabelRef(name + "move_4"))
2454 }
2455 if o.outputMargin <= 7 {
2456 CMPQ(length, U8(8))
2457 JB(LabelRef(name + "move_4through7"))
2458 } else if o.outputMargin >= 8 {
2459 CMPQ(length, U8(8))
2460 JBE(LabelRef(name + "move_8"))
2461 }
2462 CMPQ(length, U8(16))
2463 JBE(LabelRef(name + "move_8through16"))
2464 CMPQ(length, U8(32))
2465 JBE(LabelRef(name + "move_17through32"))
2466 if debug {
2467 CMPQ(length, U8(64))
2468 JBE(LabelRef(name + "move_33through64"))
2469 INT(U8(3))
2470 }
2471 JMP(LabelRef(name + "move_33through64"))
2472
2473 //genMemMoveLong(name, dst, src, length, end)
2474
2475 if o.outputMargin <= 3 {
2476 Label(name + "move_1or2")
2477 MOVB(Mem{Base: src}, AX.As8())
2478 MOVB(Mem{Base: src, Disp: -1, Index: length, Scale: 1}, CX.As8())
2479 MOVB(AX.As8(), Mem{Base: dst})
2480 MOVB(CX.As8(), Mem{Base: dst, Disp: -1, Index: length, Scale: 1})
2481 JMP(end)
2482
2483 Label(name + "move_3")
2484 MOVW(Mem{Base: src}, AX.As16())
2485 MOVB(Mem{Base: src, Disp: 2}, CX.As8())
2486 MOVW(AX.As16(), Mem{Base: dst})
2487 MOVB(CX.As8(), Mem{Base: dst, Disp: 2})
2488 JMP(end)
2489 }
2490
2491 if o.outputMargin >= 4 && o.outputMargin < 8 {
2492 // Use single move.
2493 Label(name + "move_4")
2494 MOVL(Mem{Base: src}, AX.As32())
2495 MOVL(AX.As32(), Mem{Base: dst})
2496 JMP(end)
2497 }
2498 if o.outputMargin < 8 {
2499 Label(name + "move_4through7")
2500 MOVL(Mem{Base: src}, AX.As32())
2501 MOVL(Mem{Base: src, Disp: -4, Index: length, Scale: 1}, CX.As32())
2502 MOVL(AX.As32(), Mem{Base: dst})
2503 MOVL(CX.As32(), Mem{Base: dst, Disp: -4, Index: length, Scale: 1})
2504 JMP(end)
2505 } else {
2506 // Use single move.
2507 Label(name + "move_8")
2508 MOVQ(Mem{Base: src}, AX)
2509 MOVQ(AX, Mem{Base: dst})
2510 JMP(end)
2511 }
2512
2513 Label(name + "move_8through16")
2514 MOVQ(Mem{Base: src}, AX)
2515 MOVQ(Mem{Base: src, Disp: -8, Index: length, Scale: 1}, CX)
2516 MOVQ(AX, Mem{Base: dst})
2517 MOVQ(CX, Mem{Base: dst, Disp: -8, Index: length, Scale: 1})
2518 JMP(end)
2519
2520 Label(name + "move_17through32")
2521 X0, X1, X2, X3 := XMM(), XMM(), XMM(), XMM()
2522
2523 MOVOU(Mem{Base: src}, X0)
2524 MOVOU(Mem{Base: src, Disp: -16, Index: length, Scale: 1}, X1)
2525 MOVOU(X0, Mem{Base: dst})
2526 MOVOU(X1, Mem{Base: dst, Disp: -16, Index: length, Scale: 1})
2527 JMP(end)
2528
2529 Label(name + "move_33through64")
2530 MOVOU(Mem{Base: src}, X0)
2531 MOVOU(Mem{Base: src, Disp: 16}, X1)
2532 MOVOU(Mem{Base: src, Disp: -32, Index: length, Scale: 1}, X2)
2533 MOVOU(Mem{Base: src, Disp: -16, Index: length, Scale: 1}, X3)
2534 MOVOU(X0, Mem{Base: dst})
2535 MOVOU(X1, Mem{Base: dst, Disp: 16})
2536 MOVOU(X2, Mem{Base: dst, Disp: -32, Index: length, Scale: 1})
2537 MOVOU(X3, Mem{Base: dst, Disp: -16, Index: length, Scale: 1})
2538 JMP(end)
2539 }
2540
2541 // func genMemMoveLong(to, from unsafe.Pointer, n uintptr)
2542 // src and dst may not overlap.
2543 // length must be >= 64 bytes.
2544 // Non AVX uses 2 GP register, 16 SSE2 registers.
2545 // AVX uses 4 GP registers 16 AVX/SSE registers.
2546 // All passed registers may be updated.
2547 func (o options) genMemMoveLong(name string, dst, src, length reg.GPVirtual, end LabelRef) {
2548 if o.skipOutput {
2549 JMP(end)
2550 return
2551 }
2552 Comment("genMemMoveLong")
2553 name += "large_"
2554
2555 assert(func(ok LabelRef) {
2556 CMPQ(length, U8(64))
2557 JAE(ok)
2558 })
2559
2560 if *genArm64 {
2561 // Same 32 bytes per iteration, without the flag trick. The loop below
2562 // branches on JA after a DECQ, reading the carry that the SUBQ two
2563 // instructions earlier left: x86 DECQ deliberately preserves CF, and
2564 // the arm64 SUBS it lowers to does not. Here the branch reads a CMPQ
2565 // that immediately precedes it.
2566 //
2567 // Dropping the destination-alignment attempt takes the head/tail
2568 // snapshot with it, which is only safe because every caller that
2569 // reaches this copies literals between two distinct buffers. The
2570 // alignment was tuned for x86 write buffers in any case.
2571 srcPos, dstPos, remain := GP64(), GP64(), GP64()
2572 Xa, Xb := XMM(), XMM()
2573 MOVQ(src, srcPos)
2574 MOVQ(dst, dstPos)
2575 MOVQ(length, remain)
2576
2577 Label(name + "big_loop_back")
2578 MOVOU(Mem{Base: srcPos}, Xa)
2579 MOVOU(Mem{Base: srcPos, Disp: 16}, Xb)
2580 MOVOU(Xa, Mem{Base: dstPos})
2581 MOVOU(Xb, Mem{Base: dstPos, Disp: 16})
2582 ADDQ(U8(32), srcPos)
2583 ADDQ(U8(32), dstPos)
2584 SUBQ(U8(32), remain)
2585 CMPQ(remain, U8(32))
2586 JAE(LabelRef(name + "big_loop_back"))
2587
2588 // Under 32 bytes are left; lay the final 32 over what the loop wrote.
2589 // length >= 64, so this stays in bounds.
2590 MOVOU(Mem{Base: src, Disp: -32, Index: length, Scale: 1}, Xa)
2591 MOVOU(Mem{Base: src, Disp: -16, Index: length, Scale: 1}, Xb)
2592 MOVOU(Xa, Mem{Base: dst, Disp: -32, Index: length, Scale: 1})
2593 MOVOU(Xb, Mem{Base: dst, Disp: -16, Index: length, Scale: 1})
2594 JMP(end)
2595 return
2596 }
2597
2598 // These are disabled.
2599 // AVX is ever so slightly faster, but it is disabled for simplicity.
2600 const branchLoops = false
2601 const avx = false && branchLoops
2602 if branchLoops {
2603 CMPQ(length, U8(128))
2604 JBE(LabelRef(name + "move_65through128"))
2605 CMPQ(length, U32(256))
2606 JBE(LabelRef(name + "move_129through256"))
2607 if avx {
2608 JMP(LabelRef(name + "avxUnaligned"))
2609 } else {
2610 JMP(LabelRef(name + "forward_sse"))
2611 }
2612
2613 X0, X1, X2, X3, X4, X5, X6, X7 := XMM(), XMM(), XMM(), XMM(), XMM(), XMM(), XMM(), XMM()
2614 X8, X9, X10, X11, X12, X13, X14, X15 := XMM(), XMM(), XMM(), XMM(), XMM(), XMM(), XMM(), XMM()
2615 Label(name + "move_65through128")
2616 MOVOU(Mem{Base: src}, X0)
2617 MOVOU(Mem{Base: src, Disp: 16}, X1)
2618 MOVOU(Mem{Base: src, Disp: 32}, X2)
2619 MOVOU(Mem{Base: src, Disp: 48}, X3)
2620 MOVOU(Mem{Base: src, Index: length, Scale: 1, Disp: -64}, X12)
2621 MOVOU(Mem{Base: src, Index: length, Scale: 1, Disp: -48}, X13)
2622 MOVOU(Mem{Base: src, Index: length, Scale: 1, Disp: -32}, X14)
2623 MOVOU(Mem{Base: src, Index: length, Scale: 1, Disp: -16}, X15)
2624 MOVOU(X0, Mem{Base: dst})
2625 MOVOU(X1, Mem{Base: dst, Disp: 16})
2626 MOVOU(X2, Mem{Base: dst, Disp: 32})
2627 MOVOU(X3, Mem{Base: dst, Disp: 48})
2628 MOVOU(X12, Mem{Base: dst, Index: length, Scale: 1, Disp: -64})
2629 MOVOU(X13, Mem{Base: dst, Index: length, Scale: 1, Disp: -48})
2630 MOVOU(X14, Mem{Base: dst, Index: length, Scale: 1, Disp: -32})
2631 MOVOU(X15, Mem{Base: dst, Index: length, Scale: 1, Disp: -16})
2632 JMP(end)
2633
2634 Label(name + "move_129through256")
2635 MOVOU(Mem{Base: src}, X0)
2636 MOVOU(Mem{Base: src, Disp: 16}, X1)
2637 MOVOU(Mem{Base: src, Disp: 32}, X2)
2638 MOVOU(Mem{Base: src, Disp: 48}, X3)
2639 MOVOU(Mem{Base: src, Disp: 64}, X4)
2640 MOVOU(Mem{Base: src, Disp: 80}, X5)
2641 MOVOU(Mem{Base: src, Disp: 96}, X6)
2642 MOVOU(Mem{Base: src, Disp: 112}, X7)
2643 MOVOU(Mem{Base: src, Index: length, Scale: 1, Disp: -128}, X8)
2644 MOVOU(Mem{Base: src, Index: length, Scale: 1, Disp: -112}, X9)
2645 MOVOU(Mem{Base: src, Index: length, Scale: 1, Disp: -96}, X10)
2646 MOVOU(Mem{Base: src, Index: length, Scale: 1, Disp: -80}, X11)
2647 MOVOU(Mem{Base: src, Index: length, Scale: 1, Disp: -64}, X12)
2648 MOVOU(Mem{Base: src, Index: length, Scale: 1, Disp: -48}, X13)
2649 MOVOU(Mem{Base: src, Index: length, Scale: 1, Disp: -32}, X14)
2650 MOVOU(Mem{Base: src, Index: length, Scale: 1, Disp: -16}, X15)
2651 MOVOU(X0, Mem{Base: dst})
2652 MOVOU(X1, Mem{Base: dst, Disp: 16})
2653 MOVOU(X2, Mem{Base: dst, Disp: 32})
2654 MOVOU(X3, Mem{Base: dst, Disp: 48})
2655 MOVOU(X4, Mem{Base: dst, Disp: 64})
2656 MOVOU(X5, Mem{Base: dst, Disp: 80})
2657 MOVOU(X6, Mem{Base: dst, Disp: 96})
2658 MOVOU(X7, Mem{Base: dst, Disp: 112})
2659 MOVOU(X8, Mem{Base: dst, Index: length, Scale: 1, Disp: -128})
2660 MOVOU(X9, Mem{Base: dst, Index: length, Scale: 1, Disp: -112})
2661 MOVOU(X10, Mem{Base: dst, Index: length, Scale: 1, Disp: -96})
2662 MOVOU(X11, Mem{Base: dst, Index: length, Scale: 1, Disp: -80})
2663 MOVOU(X12, Mem{Base: dst, Index: length, Scale: 1, Disp: -64})
2664 MOVOU(X13, Mem{Base: dst, Index: length, Scale: 1, Disp: -48})
2665 MOVOU(X14, Mem{Base: dst, Index: length, Scale: 1, Disp: -32})
2666 MOVOU(X15, Mem{Base: dst, Index: length, Scale: 1, Disp: -16})
2667 JMP(end)
2668 if avx {
2669 Label(name + "avxUnaligned")
2670 AX, CX, R8, R10 := GP64(), GP64(), GP64(), GP64()
2671 // Memory layout on the source side
2672 // src CX
2673 // |<---------length before correction--------->|
2674 // | |<--length corrected-->| |
2675 // | | |<--- AX --->|
2676 // |<-R11->| |<-128 bytes->|
2677 // +----------------------------------------+
2678 // | Head | Body | Tail |
2679 // +-------+------------------+-------------+
2680 // ^ ^ ^
2681 // | | |
2682 // Save head into Y4 Save tail into X5..X12
2683 // |
2684 // src+R11, where R11 = ((dst & -32) + 32) - dst
2685 // Algorithm:
2686 // 1. Unaligned save of the tail's 128 bytes
2687 // 2. Unaligned save of the head's 32 bytes
2688 // 3. Destination-aligned copying of body (128 bytes per iteration)
2689 // 4. Put head on the new place
2690 // 5. Put the tail on the new place
2691 // It can be important to satisfy processor's pipeline requirements for
2692 // small sizes as the cost of unaligned memory region copying is
2693 // comparable with the cost of main loop. So code is slightly messed there.
2694 // There is more clean implementation of that algorithm for bigger sizes
2695 // where the cost of unaligned part copying is negligible.
2696 // You can see it after gobble_big_data_fwd label.
2697 Y0, Y1, Y2, Y3, Y4 := YMM(), YMM(), YMM(), YMM(), YMM()
2698
2699 LEAQ(Mem{Base: src, Index: length, Scale: 1}, CX)
2700 MOVQ(dst, R10)
2701 // CX points to the end of buffer so we need go back slightly. We will use negative offsets there.
2702 MOVOU(Mem{Base: CX, Disp: -0x80}, X5)
2703 MOVOU(Mem{Base: CX, Disp: -0x70}, X6)
2704 MOVQ(U32(0x80), AX)
2705
2706 // Align destination address
2707 ANDQ(U32(0xffffffe0), dst)
2708 ADDQ(U8(32), dst)
2709 // Continue tail saving.
2710 MOVOU(Mem{Base: CX, Disp: -0x60}, X7)
2711 MOVOU(Mem{Base: CX, Disp: -0x50}, X8)
2712 // Make R8 delta between aligned and unaligned destination addresses.
2713 MOVQ(dst, R8)
2714 SUBQ(R10, R8)
2715 // Continue tail saving.
2716 MOVOU(Mem{Base: CX, Disp: -0x40}, X9)
2717 MOVOU(Mem{Base: CX, Disp: -0x30}, X10)
2718 // Let's make bytes-to-copy value adjusted as we've prepared unaligned part for copying.
2719 SUBQ(R8, length)
2720 // Continue tail saving.
2721 MOVOU(Mem{Base: CX, Disp: -0x20}, X11)
2722 MOVOU(Mem{Base: CX, Disp: -0x10}, X12)
2723 // The tail will be put on its place after main body copying.
2724 // It's time for the unaligned heading part.
2725 VMOVDQU(Mem{Base: src}, Y4)
2726 // Adjust source address to point past head.
2727 ADDQ(R8, src)
2728 SUBQ(AX, length)
2729
2730 // Aligned memory copying there
2731 Label(name + "gobble_128_loop")
2732 VMOVDQU(Mem{Base: src}, Y0)
2733 VMOVDQU(Mem{Base: src, Disp: 0x20}, Y1)
2734 VMOVDQU(Mem{Base: src, Disp: 0x40}, Y2)
2735 VMOVDQU(Mem{Base: src, Disp: 0x60}, Y3)
2736 ADDQ(AX, src)
2737 VMOVDQA(Y0, Mem{Base: dst})
2738 VMOVDQA(Y1, Mem{Base: dst, Disp: 0x20})
2739 VMOVDQA(Y2, Mem{Base: dst, Disp: 0x40})
2740 VMOVDQA(Y3, Mem{Base: dst, Disp: 0x60})
2741 ADDQ(AX, dst)
2742 SUBQ(AX, length)
2743 JA(LabelRef(name + "gobble_128_loop"))
2744 // Now we can store unaligned parts.
2745 ADDQ(AX, length)
2746 ADDQ(dst, length)
2747 VMOVDQU(Y4, Mem{Base: R10})
2748 VZEROUPPER()
2749 MOVOU(X5, Mem{Base: length, Disp: -0x80})
2750 MOVOU(X6, Mem{Base: length, Disp: -0x70})
2751 MOVOU(X7, Mem{Base: length, Disp: -0x60})
2752 MOVOU(X8, Mem{Base: length, Disp: -0x50})
2753 MOVOU(X9, Mem{Base: length, Disp: -0x40})
2754 MOVOU(X10, Mem{Base: length, Disp: -0x30})
2755 MOVOU(X11, Mem{Base: length, Disp: -0x20})
2756 MOVOU(X12, Mem{Base: length, Disp: -0x10})
2757 JMP(end)
2758
2759 return
2760 }
2761 }
2762
2763 // Store start and end for sse_tail
2764 Label(name + "forward_sse")
2765 X0, X1, X2, X3, X4, X5 := XMM(), XMM(), XMM(), XMM(), XMM(), XMM()
2766 // X6, X7 := XMM(), XMM()
2767 //X8, X9, X10, X11 := XMM(), XMM(), XMM(), XMM()
2768
2769 MOVOU(Mem{Base: src}, X0)
2770 MOVOU(Mem{Base: src, Disp: 16}, X1)
2771 MOVOU(Mem{Base: src, Disp: -32, Index: length, Scale: 1}, X2)
2772 MOVOU(Mem{Base: src, Disp: -16, Index: length, Scale: 1}, X3)
2773
2774 // forward (only)
2775 dstAlign := GP64()
2776 bigLoops := GP64()
2777 MOVQ(length, bigLoops)
2778 SHRQ(U8(5), bigLoops) // bigLoops = length / 32
2779
2780 MOVQ(dst, dstAlign)
2781 ANDL(U32(31), dstAlign.As32())
2782 srcOff := GP64()
2783 MOVQ(U32(64), srcOff)
2784 SUBQ(dstAlign, srcOff)
2785
2786 // Move 32 bytes/loop
2787 DECQ(bigLoops)
2788 JA(LabelRef(name + "forward_sse_loop_32"))
2789
2790 // Can be moved inside loop for less regs.
2791 srcPos := GP64()
2792 LEAQ(Mem{Disp: -32, Base: src, Scale: 1, Index: srcOff}, srcPos)
2793 dstPos := GP64()
2794 LEAQ(Mem{Disp: -32, Base: dst, Scale: 1, Index: srcOff}, dstPos)
2795
2796 Label(name + "big_loop_back")
2797
2798 MOVOU(Mem{Disp: 0, Base: srcPos}, X4)
2799 MOVOU(Mem{Disp: 16, Base: srcPos}, X5)
2800
2801 MOVOA(X4, Mem{Disp: 0, Base: dstPos})
2802 MOVOA(X5, Mem{Disp: 16, Base: dstPos})
2803 ADDQ(U8(32), dstPos)
2804 ADDQ(U8(32), srcPos)
2805 ADDQ(U8(32), srcOff) // This could be outside the loop, but we lose a reg if we do.
2806 DECQ(bigLoops)
2807 JNA(LabelRef(name + "big_loop_back"))
2808
2809 Label(name + "forward_sse_loop_32")
2810 MOVOU(Mem{Disp: -32, Base: src, Scale: 1, Index: srcOff}, X4)
2811 MOVOU(Mem{Disp: -16, Base: src, Scale: 1, Index: srcOff}, X5)
2812 MOVOA(X4, Mem{Disp: -32, Base: dst, Scale: 1, Index: srcOff})
2813 MOVOA(X5, Mem{Disp: -16, Base: dst, Scale: 1, Index: srcOff})
2814 ADDQ(U8(32), srcOff)
2815 CMPQ(length, srcOff)
2816 JAE(LabelRef(name + "forward_sse_loop_32"))
2817
2818 // sse_tail patches up the beginning and end of the transfer.
2819 MOVOU(X0, Mem{Base: dst, Disp: 0})
2820 MOVOU(X1, Mem{Base: dst, Disp: 16})
2821 MOVOU(X2, Mem{Base: dst, Disp: -32, Index: length, Scale: 1})
2822 MOVOU(X3, Mem{Base: dst, Disp: -16, Index: length, Scale: 1})
2823
2824 JMP(end)
2825 return
2826 }
2827
2828 // genMatchLen generates standalone matchLen.
2829 func (o options) genMatchLen() {
2830 TEXT("matchLen", NOSPLIT, "func(a, b []byte) int")
2831 Doc("matchLen returns how many bytes match in a and b", "",
2832 "It assumes that:",
2833 " len(a) <= len(b)", "")
2834 Pragma("noescape")
2835
2836 aBase, bBase, length := GP64(), GP64(), GP64()
2837
2838 Load(Param("a").Base(), aBase)
2839 Load(Param("b").Base(), bBase)
2840 Load(Param("a").Len(), length)
2841 l := o.matchLen("standalone", aBase, bBase, length, LabelRef("gen_match_len_end"))
2842 Label("gen_match_len_end")
2843 if o.avx2 {
2844 VZEROUPPER()
2845 }
2846 Store(l.As64(), ReturnIndex(0))
2847 RET()
2848 }
2849
2850 // matchLen returns the number of matching bytes of a and b.
2851 // len is the maximum number of bytes to match.
2852 // Will jump to end when done and returns the length.
2853 // Uses 2 GP registers.
2854 func (o options) matchLen(name string, a, b, len reg.GPVirtual, end LabelRef) reg.GPVirtual {
2855 Comment("matchLen")
2856 tmp, matched := GP64(), GP32()
2857 XORL(matched, matched)
2858 if o.avx2 {
2859 // Not faster...
2860 o.matchLenAVX2(name+"Avx2", a, b, len, LabelRef("avx2_continue_"+name), end, matched)
2861 }
2862 Label("avx2_continue_" + name)
2863
2864 Label("matchlen_loopback_16_" + name)
2865 tmp2 := GP64()
2866 CMPL(len.As32(), U8(16))
2867 JB(LabelRef("matchlen_match8_" + name))
2868 MOVQ(Mem{Base: a, Index: matched, Scale: 1}, tmp)
2869 MOVQ(Mem{Base: a, Index: matched, Scale: 1, Disp: 8}, tmp2)
2870 XORQ(Mem{Base: b, Index: matched, Scale: 1}, tmp)
2871 JNZ(LabelRef("matchlen_bsf_8_" + name))
2872 XORQ(Mem{Base: b, Index: matched, Scale: 1, Disp: 8}, tmp2)
2873 JNZ(LabelRef("matchlen_bsf_16" + name))
2874 // All 8 byte matched, update and loop.
2875 LEAL(Mem{Base: len, Disp: -16}, len.As32())
2876 LEAL(Mem{Base: matched, Disp: 16}, matched)
2877 JMP(LabelRef("matchlen_loopback_16_" + name))
2878
2879 Label("matchlen_bsf_16" + name)
2880 // Not all match.
2881 tzcnt(tmp2)
2882
2883 SARQ(U8(3), tmp2)
2884 LEAL(Mem{Base: matched, Index: tmp2, Scale: 1, Disp: 8}, matched)
2885 JMP(end)
2886
2887 Label("matchlen_match8_" + name)
2888 CMPL(len.As32(), U8(8))
2889 JB(LabelRef("matchlen_match4_" + name))
2890 MOVQ(Mem{Base: a, Index: matched, Scale: 1}, tmp)
2891 XORQ(Mem{Base: b, Index: matched, Scale: 1}, tmp)
2892 JNZ(LabelRef("matchlen_bsf_8_" + name))
2893 // All 8 byte matched, update and loop.
2894 LEAL(Mem{Base: len, Disp: -8}, len.As32())
2895 LEAL(Mem{Base: matched, Disp: 8}, matched)
2896 JMP(LabelRef("matchlen_match4_" + name))
2897 Label("matchlen_bsf_8_" + name)
2898
2899 // Not all match.
2900 tzcnt(tmp)
2901
2902 SARQ(U8(3), tmp)
2903 LEAL(Mem{Base: matched, Index: tmp, Scale: 1}, matched)
2904 JMP(end)
2905
2906 // Less than 8 bytes left.
2907 // Test 4 bytes...
2908 Label("matchlen_match4_" + name)
2909 CMPL(len.As32(), U8(4))
2910 JB(LabelRef("matchlen_match2_" + name))
2911 MOVL(Mem{Base: a, Index: matched, Scale: 1}, tmp.As32())
2912 CMPL(Mem{Base: b, Index: matched, Scale: 1}, tmp.As32())
2913 JNE(LabelRef("matchlen_match2_" + name))
2914 LEAL(Mem{Base: len.As32(), Disp: -4}, len.As32())
2915 LEAL(Mem{Base: matched, Disp: 4}, matched)
2916
2917 // Test 2 bytes...
2918 Label("matchlen_match2_" + name)
2919 CMPL(len.As32(), U8(1))
2920 // If we don't have 1, branch appropriately
2921 JE(LabelRef("matchlen_match1_" + name))
2922 JB(end)
2923 // 2 or 3
2924 MOVW(Mem{Base: a, Index: matched, Scale: 1}, tmp.As16())
2925 CMPW(Mem{Base: b, Index: matched, Scale: 1}, tmp.As16())
2926 JNE(LabelRef("matchlen_match1_" + name))
2927 LEAL(Mem{Base: matched, Disp: 2}, matched)
2928 SUBL(U8(2), len.As32())
2929 JZ(end)
2930
2931 // Test 1 byte...
2932 Label("matchlen_match1_" + name)
2933 MOVB(Mem{Base: a, Index: matched, Scale: 1}, tmp.As8())
2934 CMPB(Mem{Base: b, Index: matched, Scale: 1}, tmp.As8())
2935 JNE(end)
2936 LEAL(Mem{Base: matched, Disp: 1}, matched)
2937 JMP(end)
2938 return matched
2939 }
2940
2941 // matchLen returns the number of matching bytes of a and b.
2942 // len is the maximum number of bytes to match.
2943 // Will jump to end when done and returns the length.
2944 // Uses 3 GP registers.
2945 // It is better on longer matches.
2946 func (o options) matchLenAVX2(name string, a, b, len reg.GPVirtual, cont, end LabelRef, dst reg.GPVirtual) {
2947 Comment("matchLenAVX2")
2948
2949 equalMaskBits := GP64()
2950 Label(name + "loop")
2951 {
2952 CMPQ(len, U8(32))
2953 JB(cont)
2954 Comment("load 32 bytes into YMM registers")
2955 adata := YMM()
2956 bdata := YMM()
2957 equalMaskBytes := YMM()
2958 VMOVDQU(Mem{Base: a}, adata)
2959 VMOVDQU(Mem{Base: b}, bdata)
2960 Comment("compare bytes in adata and bdata, like 'bytewise XNOR'",
2961 "if the byte is the same in adata and bdata, VPCMPEQB will store 0xFF in the same position in equalMaskBytes")
2962 VPCMPEQB(adata, bdata, equalMaskBytes)
2963 Comment("like convert byte to bit, store equalMaskBytes into general reg")
2964 VPMOVMSKB(equalMaskBytes, equalMaskBits.As32())
2965 CMPL(equalMaskBits.As32(), U32(0xffffffff))
2966 JNE(LabelRef(name + "cal_prefix"))
2967 ADDQ(U8(32), a)
2968 ADDQ(U8(32), b)
2969 ADDL(U8(32), dst)
2970 SUBQ(U8(32), len)
2971 JZ(end)
2972 JMP(LabelRef(name + "loop"))
2973 }
2974
2975 Label(name + "cal_prefix")
2976 {
2977 NOTQ(equalMaskBits)
2978 if o.bmi1 {
2979 TZCNTQ(equalMaskBits, equalMaskBits)
2980 } else {
2981 BSFQ(equalMaskBits, equalMaskBits)
2982 }
2983 ADDL(equalMaskBits.As32(), dst)
2984 }
2985 JMP(end)
2986 return
2987 }
2988
2989 func (o options) cvtLZ4BlockAsm(lz4s bool) {
2990 snap := "Asm"
2991 name := "lz4_s2_"
2992 srcAlgo := "LZ4"
2993 dstAlgo := "S2"
2994 if o.snappy {
2995 snap = "SnappyAsm"
2996 name = "lz4_snappy_"
2997 dstAlgo = "Snappy"
2998 }
2999 if lz4s {
3000 name = strings.ReplaceAll(name, "lz4", "lz4s")
3001 srcAlgo = "LZ4s"
3002 }
3003 TEXT("cvt"+srcAlgo+"Block"+snap, NOSPLIT, "func(dst, src []byte) (uncompressed int, dstUsed int)")
3004 Doc("cvt"+srcAlgo+"Block converts an "+srcAlgo+" block to "+dstAlgo, "")
3005 Pragma("noescape")
3006 o.outputMargin = 8
3007 o.maxOffset = math.MaxUint16
3008
3009 const (
3010 errCorrupt = -1
3011 errDstTooSmall = -2
3012 )
3013 dst, dstLen, src, srcLen, retval := GP64(), GP64(), GP64(), GP64(), GP64()
3014
3015 // retval = 0
3016 XORQ(retval, retval)
3017
3018 Load(Param("dst").Base(), dst)
3019 Load(Param("dst").Len(), dstLen)
3020 Load(Param("src").Base(), src)
3021 Load(Param("src").Len(), srcLen)
3022 srcEnd, dstEnd := GP64(), GP64()
3023 LEAQ(Mem{Base: src, Index: srcLen, Scale: 1, Disp: 0}, srcEnd)
3024 LEAQ(Mem{Base: dst, Index: dstLen, Scale: 1, Disp: -o.outputMargin}, dstEnd)
3025 lastOffset := GP64()
3026 if !o.snappy {
3027 XORQ(lastOffset, lastOffset)
3028 }
3029
3030 checkSrc := func(reg reg.GPVirtual) {
3031 if debug {
3032 name := fmt.Sprintf(name+"ok_%d", rand.Int31())
3033
3034 CMPQ(reg, srcEnd)
3035 JB(LabelRef(name))
3036 JMP(LabelRef(name + "corrupt"))
3037 Label(name)
3038 } else {
3039 CMPQ(reg, srcEnd)
3040 JAE(LabelRef(name + "corrupt"))
3041 }
3042 }
3043 checkDst := func(reg reg.GPVirtual) {
3044 CMPQ(reg, dstEnd)
3045 JAE(LabelRef(name + "dstfull"))
3046 }
3047
3048 var lz4MinMatch = 4
3049 if lz4s {
3050 lz4MinMatch = 3
3051 }
3052
3053 Label(name + "loop")
3054 checkSrc(src)
3055 checkDst(dst)
3056 token := GP64()
3057 MOVBQZX(Mem{Base: src}, token)
3058 ll, ml := GP64(), GP64()
3059 MOVQ(token, ll)
3060 MOVQ(token, ml)
3061 SHRQ(U8(4), ll)
3062 ANDQ(U8(0xf), ml)
3063
3064 // If upper nibble is 15, literal length is extended
3065 {
3066 CMPQ(token, U8(0xf0))
3067 JB(LabelRef(name + "ll_end"))
3068 Label(name + "ll_loop")
3069 INCQ(src) // s++
3070 checkSrc(src)
3071 val := GP64()
3072 MOVBQZX(Mem{Base: src}, val)
3073 ADDQ(val, ll)
3074 CMPQ(val, U8(255))
3075 JEQ(LabelRef(name + "ll_loop"))
3076 Label(name + "ll_end")
3077 }
3078
3079 // if s+ll >= len(src)
3080 endLits := GP64()
3081 LEAQ(Mem{Base: src, Index: ll, Scale: 1}, endLits)
3082 ADDQ(U8(lz4MinMatch), ml)
3083 checkSrc(endLits)
3084 INCQ(src) // s++
3085 INCQ(endLits)
3086 TESTQ(ll, ll)
3087 JZ(LabelRef(name + "lits_done"))
3088 {
3089 dstEnd := GP64()
3090 LEAQ(Mem{Base: dst, Index: ll, Scale: 1}, dstEnd)
3091 checkDst(dstEnd)
3092 o.outputMargin++
3093 ADDQ(ll, retval)
3094 o.emitLiteral(strings.TrimRight(name, "_"), ll, nil, dst, src, LabelRef(name+"lits_emit_done"), true)
3095 o.outputMargin--
3096 Label(name + "lits_emit_done")
3097 MOVQ(endLits, src)
3098 }
3099 Label(name + "lits_done")
3100 // if s == len(src) && ml == lz4MinMatch
3101 CMPQ(src, srcEnd)
3102 JNE(LabelRef(name + "match"))
3103 CMPQ(ml, U8(lz4MinMatch))
3104 JEQ(LabelRef(name + "done"))
3105 JMP(LabelRef(name + "corrupt"))
3106
3107 Label(name + "match")
3108 if lz4s {
3109 CMPQ(ml, U8(lz4MinMatch))
3110 JEQ(LabelRef(name + "loop"))
3111 }
3112 // if s >= len(src)-2 {
3113 end := GP64()
3114 LEAQ(Mem{Base: src, Disp: 2}, end)
3115 checkSrc(end)
3116 offset := GP64()
3117 MOVWQZX(Mem{Base: src}, offset)
3118 MOVQ(end, src) // s = s + 2
3119
3120 if debug {
3121 // if offset == 0 {
3122 TESTQ(offset, offset)
3123 JNZ(LabelRef(name + "c1"))
3124 JMP(LabelRef(name + "corrupt"))
3125
3126 Label(name + "c1")
3127
3128 // if int(offset) > uncompressed {
3129 CMPQ(offset, retval)
3130 JB(LabelRef(name + "c2"))
3131 JMP(LabelRef(name + "corrupt"))
3132
3133 Label(name + "c2")
3134
3135 } else {
3136 // if offset == 0 {
3137 TESTQ(offset, offset)
3138 JZ(LabelRef(name + "corrupt"))
3139
3140 // if int(offset) > uncompressed {
3141 CMPQ(offset, retval)
3142 JA(LabelRef(name + "corrupt"))
3143 }
3144
3145 // if ml == lz4MinMatch+15 {
3146 {
3147 CMPQ(ml, U8(lz4MinMatch+15))
3148 JNE(LabelRef(name + "ml_done"))
3149
3150 Label(name + "ml_loop")
3151 val := GP64()
3152 MOVBQZX(Mem{Base: src}, val)
3153 INCQ(src) // s++
3154 ADDQ(val, ml) // ml += val
3155 checkSrc(src)
3156 CMPQ(val, U8(255))
3157 JEQ(LabelRef(name + "ml_loop"))
3158 }
3159 Label(name + "ml_done")
3160
3161 // uncompressed += ml
3162 ADDQ(ml, retval)
3163 if !o.snappy {
3164 CMPQ(offset, lastOffset)
3165 JNE(LabelRef(name + "docopy"))
3166 // Offsets can only be 16 bits
3167 {
3168 // emitRepeat16(dst[d:], offset, ml)
3169 o.emitRepeat("lz4_s2", ml, offset, nil, dst, LabelRef(name+"loop"), false)
3170 }
3171 }
3172 Label(name + "docopy")
3173 {
3174 // emitCopy16(dst[d:], offset, ml)
3175 if !o.snappy {
3176 MOVQ(offset, lastOffset)
3177 }
3178 o.emitCopy("lz4_s2", ml, offset, nil, dst, dstEnd, LabelRef(name+"loop"))
3179 }
3180
3181 Label(name + "done")
3182 {
3183 tmp := GP64()
3184 Load(Param("dst").Base(), tmp)
3185 SUBQ(tmp, dst)
3186 Store(retval, ReturnIndex(0))
3187 Store(dst, ReturnIndex(1))
3188 RET()
3189 }
3190 Label(name + "corrupt")
3191 {
3192 tmp := GP64()
3193 if debug {
3194 tmp := GP64()
3195 Load(Param("dst").Base(), tmp)
3196 SUBQ(tmp, dst)
3197 Store(dst, ReturnIndex(1))
3198 }
3199 XORQ(tmp, tmp)
3200 LEAQ(Mem{Base: tmp, Disp: errCorrupt}, retval)
3201 Store(retval, ReturnIndex(0))
3202 RET()
3203 }
3204
3205 Label(name + "dstfull")
3206 {
3207 tmp := GP64()
3208 XORQ(tmp, tmp)
3209 LEAQ(Mem{Base: tmp, Disp: errDstTooSmall}, retval)
3210 Store(retval, ReturnIndex(0))
3211 RET()
3212 }
3213 }