| 1 |
|
| 2 |
|
| 3 |
package main |
| 4 |
|
| 5 |
import ( |
| 6 |
. "github.com/mmcloughlin/avo/build" |
| 7 |
. "github.com/mmcloughlin/avo/operand" |
| 8 |
) |
| 9 |
|
| 10 |
func main() { |
| 11 |
TEXT("Triangle", NOSPLIT, "func(n uint64) uint64") |
| 12 |
Doc("Triangle computes the nth triangle number.") |
| 13 |
n := Load(Param("n"), GP64()) |
| 14 |
|
| 15 |
Comment("Initialize sum register to zero.") |
| 16 |
s := GP64() |
| 17 |
XORQ(s, s) |
| 18 |
|
| 19 |
|
| 20 |
Label("loop_even") |
| 21 |
Label("loop_odd") |
| 22 |
Comment("Loop until n is zero.") |
| 23 |
CMPQ(n, Imm(0)) |
| 24 |
JE(LabelRef("done")) |
| 25 |
|
| 26 |
Comment("Add n to sum.") |
| 27 |
ADDQ(n, s) |
| 28 |
|
| 29 |
Comment("Decrement n.") |
| 30 |
DECQ(n) |
| 31 |
|
| 32 |
Comment("Jump to one of the loop labels depending on parity.") |
| 33 |
TESTQ(U32(1), n) |
| 34 |
JZ(LabelRef("loop_even")) |
| 35 |
JMP(LabelRef("loop_odd")) |
| 36 |
|
| 37 |
Label("done") |
| 38 |
Comment("Store sum to return value.") |
| 39 |
Store(s, ReturnIndex(0)) |
| 40 |
RET() |
| 41 |
Generate() |
| 42 |
} |