| 1 | package pass |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "fmt" |
| 6 | |
| 7 | "github.com/mmcloughlin/avo/ir" |
| 8 | ) |
| 9 | |
| 10 | // LabelTarget populates the LabelTarget of the given function. This maps from |
| 11 | // label name to the following instruction. |
| 12 | func LabelTarget(fn *ir.Function) error { |
| 13 | target := map[ir.Label]*ir.Instruction{} |
| 14 | var pending []ir.Label |
| 15 | for _, node := range fn.Nodes { |
| 16 | switch n := node.(type) { |
| 17 | case ir.Label: |
| 18 | if _, found := target[n]; found { |
| 19 | return fmt.Errorf("duplicate label \"%s\"", n) |
| 20 | } |
| 21 | pending = append(pending, n) |
| 22 | case *ir.Instruction: |
| 23 | for _, label := range pending { |
| 24 | target[label] = n |
| 25 | } |
| 26 | pending = nil |
| 27 | } |
| 28 | } |
| 29 | if len(pending) != 0 { |
| 30 | return errors.New("function ends with label") |
| 31 | } |
| 32 | fn.LabelTarget = target |
| 33 | return nil |
| 34 | } |
| 35 | |
| 36 | // CFG constructs the call-flow-graph for the function. |
| 37 | func CFG(fn *ir.Function) error { |
| 38 | is := fn.Instructions() |
| 39 | n := len(is) |
| 40 | |
| 41 | // Populate successors. |
| 42 | for i := 0; i < n; i++ { |
| 43 | cur := is[i] |
| 44 | var nxt *ir.Instruction |
| 45 | if i+1 < n { |
| 46 | nxt = is[i+1] |
| 47 | } |
| 48 | |
| 49 | // If it's a branch, locate the target. |
| 50 | if cur.IsBranch { |
| 51 | lbl := cur.TargetLabel() |
| 52 | if lbl == nil { |
| 53 | return errors.New("no label for branch instruction") |
| 54 | } |
| 55 | target, found := fn.LabelTarget[*lbl] |
| 56 | if !found { |
| 57 | return fmt.Errorf("unknown label %q", *lbl) |
| 58 | } |
| 59 | cur.Succ = append(cur.Succ, target) |
| 60 | } |
| 61 | |
| 62 | // Otherwise, could continue to the following instruction. |
| 63 | switch { |
| 64 | case cur.IsTerminal: |
| 65 | case cur.IsUnconditionalBranch(): |
| 66 | default: |
| 67 | cur.Succ = append(cur.Succ, nxt) |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | // Populate predecessors. |
| 72 | for _, i := range is { |
| 73 | for _, s := range i.Succ { |
| 74 | if s != nil { |
| 75 | s.Pred = append(s.Pred, i) |
| 76 | } |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | return nil |
| 81 | } |