| 1 | # sum |
| 2 | |
| 3 | Sum a slice of `uint64`s. |
| 4 | |
| 5 | [embedmd]:# (asm.go go /func main/ /^}/) |
| 6 | ```go |
| 7 | func main() { |
| 8 | TEXT("Sum", NOSPLIT, "func(xs []uint64) uint64") |
| 9 | Doc("Sum returns the sum of the elements in xs.") |
| 10 | ptr := Load(Param("xs").Base(), GP64()) |
| 11 | n := Load(Param("xs").Len(), GP64()) |
| 12 | |
| 13 | Comment("Initialize sum register to zero.") |
| 14 | s := GP64() |
| 15 | XORQ(s, s) |
| 16 | |
| 17 | Label("loop") |
| 18 | Comment("Loop until zero bytes remain.") |
| 19 | CMPQ(n, Imm(0)) |
| 20 | JE(LabelRef("done")) |
| 21 | |
| 22 | Comment("Load from pointer and add to running sum.") |
| 23 | ADDQ(Mem{Base: ptr}, s) |
| 24 | |
| 25 | Comment("Advance pointer, decrement byte count.") |
| 26 | ADDQ(Imm(8), ptr) |
| 27 | DECQ(n) |
| 28 | JMP(LabelRef("loop")) |
| 29 | |
| 30 | Label("done") |
| 31 | Comment("Store sum to return value.") |
| 32 | Store(s, ReturnIndex(0)) |
| 33 | RET() |
| 34 | Generate() |
| 35 | } |
| 36 | ``` |