Debian Codegraph @

go/ir/irutil/stub.go

raw
1 package irutil
2
3 import (
4 "honnef.co/go/tools/go/ir"
5 )
6
7 // IsStub reports whether a function is a stub. A function is
8 // considered a stub if it has no instructions or if all it does is
9 // return a fixed value (either an actual constant or a new allocation).
10 func IsStub(fn *ir.Function) bool {
11 if fn.Source() == nil {
12 // External functions have to be assumed to not be stubs.
13 return false
14 }
15
16 for _, b := range fn.Blocks {
17 for _, instr := range b.Instrs {
18 switch instr.(type) {
19 case *ir.Panic:
20 // panic is a stub if it only uses constants
21 case *ir.Return:
22 // return is a stub if it only uses constants
23 case *ir.Jump:
24 // if there are no disallowed instructions, then we're
25 // only jumping to the exit block (or possibly
26 // somewhere else that's stubby?)
27 case *ir.MakeInterface:
28 // this can only be wrapping Const and HeapAlloc, which is fine.
29 case *ir.Alloc:
30 // allocating is fine as long as all we do with the allocation
31 // is return it (possibly in an interface value)
32 default:
33 // all other instructions are assumed to do actual work
34 return false
35 }
36 }
37 }
38 return true
39 }
40
41 // IsTrivial reports whether a function is trivial. A function is
42 // considered trivial if it is a stub, only returns a global variable, or calls
43 // another trivial function.
44 func IsTrivial(fn *ir.Function) bool {
45 return isTrivial(fn, nil)
46 }
47
48 func isTrivial(fn *ir.Function, seen map[*ir.Function]struct{}) bool {
49 if fn.Source() == nil {
50 // External functions have to be assumed to be nontrivial.
51 return false
52 }
53
54 if _, ok := seen[fn]; ok {
55 // Mutual recursion is not trivial
56 return false
57 }
58
59 // We delay adding to seen until a call, to avoid creating garbage in the
60 // common case.
61 for _, b := range fn.Blocks {
62 for _, instr := range b.Instrs {
63 switch instr := instr.(type) {
64 case *ir.Panic:
65 // panic is a stub if it only uses constants
66 case *ir.Return:
67 // return is a stub if it only uses constants
68 case *ir.Jump:
69 // if there are no disallowed instructions, then we're
70 // only jumping to the exit block (or possibly
71 // somewhere else that's stubby?)
72 case *ir.MakeInterface:
73 // this can only be wrapping allowed instructions
74 case *ir.Alloc:
75 // allocating is fine as long as all we do with the allocation
76 // is return it (possibly in an interface value)
77 case *ir.Load:
78 if _, ok := instr.X.(*ir.Global); !ok {
79 return false
80 }
81 case *ir.Call:
82 if seen == nil {
83 seen = make(map[*ir.Function]struct{})
84 }
85 seen[fn] = struct{}{}
86 callee := instr.Call.StaticCallee()
87 if callee == nil || !isTrivial(callee, seen) {
88 return false
89 }
90 default:
91 // all other instructions are assumed to do actual work
92 return false
93 }
94 }
95 }
96 return true
97 }