| 1 | package pass_test |
| 2 | |
| 3 | import ( |
| 4 | "reflect" |
| 5 | "testing" |
| 6 | |
| 7 | "github.com/mmcloughlin/avo/build" |
| 8 | "github.com/mmcloughlin/avo/ir" |
| 9 | "github.com/mmcloughlin/avo/operand" |
| 10 | "github.com/mmcloughlin/avo/pass" |
| 11 | "github.com/mmcloughlin/avo/reg" |
| 12 | ) |
| 13 | |
| 14 | func TestPruneSelfMoves(t *testing.T) { |
| 15 | // Construct a function containing a self-move. |
| 16 | ctx := build.NewContext() |
| 17 | ctx.Function("add") |
| 18 | ctx.MOVQ(operand.U64(1), reg.RAX) |
| 19 | ctx.MOVQ(operand.U64(2), reg.RCX) |
| 20 | ctx.MOVQ(reg.RAX, reg.RAX) // self move |
| 21 | ctx.MOVQ(reg.RCX, reg.R8) |
| 22 | ctx.ADDQ(reg.R8, reg.RAX) |
| 23 | |
| 24 | // Build the function without the pass and save the nodes. |
| 25 | fn := BuildFunction(t, ctx) |
| 26 | pre := append([]ir.Node{}, fn.Nodes...) |
| 27 | |
| 28 | // Apply the pass. |
| 29 | if err := pass.PruneSelfMoves(fn); err != nil { |
| 30 | t.Fatal(err) |
| 31 | } |
| 32 | |
| 33 | // Confirm the self-move was removed and everything else was untouched. |
| 34 | expect := []ir.Node{} |
| 35 | for i, n := range pre { |
| 36 | if i != 2 { |
| 37 | expect = append(expect, n) |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | if !reflect.DeepEqual(fn.Nodes, expect) { |
| 42 | t.Fatal("unexpected result from self-move pruning") |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | func TestPruneJumpToFollowingLabel(t *testing.T) { |
| 47 | // Construct a function containing a jump to following. |
| 48 | ctx := build.NewContext() |
| 49 | ctx.Function("add") |
| 50 | ctx.XORQ(reg.RAX, reg.RAX) |
| 51 | ctx.JMP(operand.LabelRef("next")) |
| 52 | ctx.Label("next") |
| 53 | ctx.XORQ(reg.RAX, reg.RAX) |
| 54 | |
| 55 | // Build the function with the PruneJumpToFollowingLabel pass. |
| 56 | fn := BuildFunction(t, ctx, pass.PruneJumpToFollowingLabel) |
| 57 | |
| 58 | // Confirm no JMP instruction remains. |
| 59 | for _, i := range fn.Instructions() { |
| 60 | if i.Opcode == "JMP" { |
| 61 | t.Fatal("JMP instruction not removed") |
| 62 | } |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | func TestPruneDanglingLabels(t *testing.T) { |
| 67 | // Construct a function containing an unreferenced label. |
| 68 | ctx := build.NewContext() |
| 69 | ctx.Function("add") |
| 70 | ctx.XORQ(reg.RAX, reg.RAX) |
| 71 | ctx.JMP(operand.LabelRef("referenced")) |
| 72 | ctx.XORQ(reg.RAX, reg.RAX) |
| 73 | ctx.Label("dangling") |
| 74 | ctx.XORQ(reg.RAX, reg.RAX) |
| 75 | ctx.Label("referenced") |
| 76 | ctx.XORQ(reg.RAX, reg.RAX) |
| 77 | |
| 78 | // Build the function with the PruneDanglingLabels pass. |
| 79 | fn := BuildFunction(t, ctx, pass.PruneDanglingLabels) |
| 80 | |
| 81 | // Confirm the only label remaining is "referenced". |
| 82 | expect := []ir.Label{"referenced"} |
| 83 | if !reflect.DeepEqual(expect, fn.Labels()) { |
| 84 | t.Fatal("expected dangling label to be removed") |
| 85 | } |
| 86 | } |