Debian Codegraph @

go/callgraph/rta/rta.go

raw symbols SCIP
1 // Copyright 2013 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // This package provides Rapid Type Analysis (RTA) for Go, a fast
6 // algorithm for call graph construction and discovery of reachable code
7 // (and hence dead code) and runtime types. The algorithm was first
8 // described in:
9 //
10 // David F. Bacon and Peter F. Sweeney. 1996.
11 // Fast static analysis of C++ virtual function calls. (OOPSLA '96)
12 // http://doi.acm.org/10.1145/236337.236371
13 //
14 // The algorithm uses dynamic programming to tabulate the cross-product
15 // of the set of known "address-taken" functions with the set of known
16 // dynamic calls of the same type. As each new address-taken function
17 // is discovered, call graph edges are added from each known callsite,
18 // and as each new call site is discovered, call graph edges are added
19 // from it to each known address-taken function.
20 //
21 // A similar approach is used for dynamic calls via interfaces: it
22 // tabulates the cross-product of the set of known "runtime types",
23 // i.e. types that may appear in an interface value, or may be derived from
24 // one via reflection, with the set of known "invoke"-mode dynamic
25 // calls. As each new runtime type is discovered, call edges are
26 // added from the known call sites, and as each new call site is
27 // discovered, call graph edges are added to each compatible
28 // method.
29 //
30 // In addition, we must consider as reachable all address-taken
31 // functions and all exported methods of any runtime type, since they
32 // may be called via reflection.
33 //
34 // Each time a newly added call edge causes a new function to become
35 // reachable, the code of that function is analyzed for more call sites,
36 // address-taken functions, and runtime types. The process continues
37 // until a fixed point is reached.
38 package rta // import "golang.org/x/tools/go/callgraph/rta"
39
40 import (
41 "fmt"
42 "go/types"
43 "hash/crc32"
44
45 "golang.org/x/tools/go/callgraph"
46 "golang.org/x/tools/go/ssa"
47 "golang.org/x/tools/go/types/typeutil"
48 )
49
50 // A Result holds the results of Rapid Type Analysis, which includes the
51 // set of reachable functions/methods, runtime types, and the call graph.
52 type Result struct {
53 // CallGraph is the discovered callgraph.
54 // It does not include edges for calls made via reflection.
55 CallGraph *callgraph.Graph
56
57 // Reachable contains the set of reachable functions and methods.
58 // This includes exported methods of runtime types, since
59 // they may be accessed via reflection.
60 // The value indicates whether the function is address-taken.
61 //
62 // (We wrap the bool in a struct to avoid inadvertent use of
63 // "if Reachable[f] {" to test for set membership.)
64 Reachable map[*ssa.Function]struct{ AddrTaken bool }
65
66 // RuntimeTypes contains the set of types that are needed at
67 // runtime, for interfaces or reflection.
68 //
69 // The value indicates whether the type is inaccessible to reflection.
70 // Consider:
71 // type A struct{B}
72 // fmt.Println(new(A))
73 // Types *A, A and B are accessible to reflection, but the unnamed
74 // type struct{B} is not.
75 RuntimeTypes typeutil.Map
76 }
77
78 // Working state of the RTA algorithm.
79 type rta struct {
80 result *Result
81
82 prog *ssa.Program
83
84 reflectValueCall *ssa.Function // (*reflect.Value).Call, iff part of prog
85
86 worklist []*ssa.Function // list of functions to visit
87
88 // addrTakenFuncsBySig contains all address-taken *Functions, grouped by signature.
89 // Keys are *types.Signature, values are map[*ssa.Function]bool sets.
90 addrTakenFuncsBySig typeutil.Map
91
92 // dynCallSites contains all dynamic "call"-mode call sites, grouped by signature.
93 // Keys are *types.Signature, values are unordered []ssa.CallInstruction.
94 dynCallSites typeutil.Map
95
96 // invokeSites contains all "invoke"-mode call sites, grouped by interface.
97 // Keys are *types.Interface (never *types.Named),
98 // Values are unordered []ssa.CallInstruction sets.
99 invokeSites typeutil.Map
100
101 // The following two maps together define the subset of the
102 // m:n "implements" relation needed by the algorithm.
103
104 // concreteTypes maps each concrete type to information about it.
105 // Keys are types.Type, values are *concreteTypeInfo.
106 // Only concrete types used as MakeInterface operands are included.
107 concreteTypes typeutil.Map
108
109 // interfaceTypes maps each interface type to information about it.
110 // Keys are *types.Interface, values are *interfaceTypeInfo.
111 // Only interfaces used in "invoke"-mode CallInstructions are included.
112 interfaceTypes typeutil.Map
113 }
114
115 type concreteTypeInfo struct {
116 C types.Type
117 fprint uint64 // fingerprint of method set
118 implements []*types.Interface // unordered set of implemented interfaces
119 }
120
121 type interfaceTypeInfo struct {
122 I *types.Interface
123 fprint uint64 // fingerprint of method set
124 implementations []types.Type // unordered set of concrete implementations
125 }
126
127 // addReachable marks a function as potentially callable at run-time,
128 // and ensures that it gets processed.
129 func (r *rta) addReachable(f *ssa.Function, addrTaken bool) {
130 reachable := r.result.Reachable
131 n := len(reachable)
132 v := reachable[f]
133 if addrTaken {
134 v.AddrTaken = true
135 }
136 reachable[f] = v
137 if len(reachable) > n {
138 // First time seeing f. Add it to the worklist.
139 r.worklist = append(r.worklist, f)
140 }
141 }
142
143 // addEdge adds the specified call graph edge, and marks it reachable.
144 // addrTaken indicates whether to mark the callee as "address-taken".
145 // site is nil for calls made via reflection.
146 func (r *rta) addEdge(caller *ssa.Function, site ssa.CallInstruction, callee *ssa.Function, addrTaken bool) {
147 r.addReachable(callee, addrTaken)
148
149 if g := r.result.CallGraph; g != nil {
150 if caller == nil {
151 panic(site)
152 }
153 from := g.CreateNode(caller)
154 to := g.CreateNode(callee)
155 callgraph.AddEdge(from, site, to)
156 }
157 }
158
159 // ---------- addrTakenFuncs × dynCallSites ----------
160
161 // visitAddrTakenFunc is called each time we encounter an address-taken function f.
162 func (r *rta) visitAddrTakenFunc(f *ssa.Function) {
163 // Create two-level map (Signature -> Function -> bool).
164 S := f.Signature
165 funcs, _ := r.addrTakenFuncsBySig.At(S).(map[*ssa.Function]bool)
166 if funcs == nil {
167 funcs = make(map[*ssa.Function]bool)
168 r.addrTakenFuncsBySig.Set(S, funcs)
169 }
170 if !funcs[f] {
171 // First time seeing f.
172 funcs[f] = true
173
174 // If we've seen any dyncalls of this type, mark it reachable,
175 // and add call graph edges.
176 sites, _ := r.dynCallSites.At(S).([]ssa.CallInstruction)
177 for _, site := range sites {
178 r.addEdge(site.Parent(), site, f, true)
179 }
180
181 // If the program includes (*reflect.Value).Call,
182 // add a dynamic call edge from it to any address-taken
183 // function, regardless of signature.
184 //
185 // This isn't perfect.
186 // - The actual call comes from an internal function
187 // called reflect.call, but we can't rely on that here.
188 // - reflect.Value.CallSlice behaves similarly,
189 // but we don't bother to create callgraph edges from
190 // it as well as it wouldn't fundamentally change the
191 // reachability but it would add a bunch more edges.
192 // - We assume that if reflect.Value.Call is among
193 // the dependencies of the application, it is itself
194 // reachable. (It would be more accurate to defer
195 // all the addEdges below until r.V.Call itself
196 // becomes reachable.)
197 // - Fake call graph edges are added from r.V.Call to
198 // each address-taken function, but not to every
199 // method reachable through a materialized rtype,
200 // which is a little inconsistent. Still, the
201 // reachable set includes both kinds, which is what
202 // matters for e.g. deadcode detection.)
203 if r.reflectValueCall != nil {
204 var site ssa.CallInstruction = nil // can't find actual call site
205 r.addEdge(r.reflectValueCall, site, f, true)
206 }
207 }
208 }
209
210 // visitDynCall is called each time we encounter a dynamic "call"-mode call.
211 func (r *rta) visitDynCall(site ssa.CallInstruction) {
212 S := site.Common().Signature()
213
214 // Record the call site.
215 sites, _ := r.dynCallSites.At(S).([]ssa.CallInstruction)
216 r.dynCallSites.Set(S, append(sites, site))
217
218 // For each function of signature S that we know is address-taken,
219 // add an edge and mark it reachable.
220 funcs, _ := r.addrTakenFuncsBySig.At(S).(map[*ssa.Function]bool)
221 for g := range funcs {
222 r.addEdge(site.Parent(), site, g, true)
223 }
224 }
225
226 // ---------- concrete types × invoke sites ----------
227
228 // addInvokeEdge is called for each new pair (site, C) in the matrix.
229 func (r *rta) addInvokeEdge(site ssa.CallInstruction, C types.Type) {
230 // Ascertain the concrete method of C to be called.
231 imethod := site.Common().Method
232 cmethod := r.prog.LookupMethod(C, imethod.Pkg(), imethod.Name())
233 r.addEdge(site.Parent(), site, cmethod, true)
234 }
235
236 // visitInvoke is called each time the algorithm encounters an "invoke"-mode call.
237 func (r *rta) visitInvoke(site ssa.CallInstruction) {
238 I := site.Common().Value.Type().Underlying().(*types.Interface)
239
240 // Record the invoke site.
241 sites, _ := r.invokeSites.At(I).([]ssa.CallInstruction)
242 r.invokeSites.Set(I, append(sites, site))
243
244 // Add callgraph edge for each existing
245 // address-taken concrete type implementing I.
246 for _, C := range r.implementations(I) {
247 r.addInvokeEdge(site, C)
248 }
249 }
250
251 // ---------- main algorithm ----------
252
253 // visitFunc processes function f.
254 func (r *rta) visitFunc(f *ssa.Function) {
255 var space [32]*ssa.Value // preallocate space for common case
256
257 for _, b := range f.Blocks {
258 for _, instr := range b.Instrs {
259 rands := instr.Operands(space[:0])
260
261 switch instr := instr.(type) {
262 case ssa.CallInstruction:
263 call := instr.Common()
264 if call.IsInvoke() {
265 r.visitInvoke(instr)
266 } else if g := call.StaticCallee(); g != nil {
267 r.addEdge(f, instr, g, false)
268 } else if _, ok := call.Value.(*ssa.Builtin); !ok {
269 r.visitDynCall(instr)
270 }
271
272 // Ignore the call-position operand when
273 // looking for address-taken Functions.
274 // Hack: assume this is rands[0].
275 rands = rands[1:]
276
277 case *ssa.MakeInterface:
278 // Converting a value of type T to an
279 // interface materializes its runtime
280 // type, allowing any of its exported
281 // methods to be called though reflection.
282 r.addRuntimeType(instr.X.Type(), false)
283 }
284
285 // Process all address-taken functions.
286 for _, op := range rands {
287 if g, ok := (*op).(*ssa.Function); ok {
288 r.visitAddrTakenFunc(g)
289 }
290 }
291 }
292 }
293 }
294
295 // Analyze performs Rapid Type Analysis, starting at the specified root
296 // functions. It returns nil if no roots were specified.
297 //
298 // The root functions must be one or more entrypoints (main and init
299 // functions) of a complete SSA program, with function bodies for all
300 // dependencies, constructed with the [ssa.InstantiateGenerics] mode
301 // flag.
302 //
303 // If buildCallGraph is true, Result.CallGraph will contain a call
304 // graph; otherwise, only the other fields (reachable functions) are
305 // populated.
306 func Analyze(roots []*ssa.Function, buildCallGraph bool) *Result {
307 if len(roots) == 0 {
308 return nil
309 }
310
311 r := &rta{
312 result: &Result{Reachable: make(map[*ssa.Function]struct{ AddrTaken bool })},
313 prog: roots[0].Prog,
314 }
315
316 if buildCallGraph {
317 // TODO(adonovan): change callgraph API to eliminate the
318 // notion of a distinguished root node. Some callgraphs
319 // have many roots, or none.
320 r.result.CallGraph = callgraph.New(roots[0])
321 }
322
323 // Grab ssa.Function for (*reflect.Value).Call,
324 // if "reflect" is among the dependencies.
325 if reflectPkg := r.prog.ImportedPackage("reflect"); reflectPkg != nil {
326 reflectValue := reflectPkg.Members["Value"].(*ssa.Type)
327 r.reflectValueCall = r.prog.LookupMethod(reflectValue.Object().Type(), reflectPkg.Pkg, "Call")
328 }
329
330 hasher := typeutil.MakeHasher()
331 r.result.RuntimeTypes.SetHasher(hasher)
332 r.addrTakenFuncsBySig.SetHasher(hasher)
333 r.dynCallSites.SetHasher(hasher)
334 r.invokeSites.SetHasher(hasher)
335 r.concreteTypes.SetHasher(hasher)
336 r.interfaceTypes.SetHasher(hasher)
337
338 for _, root := range roots {
339 r.addReachable(root, false)
340 }
341
342 // Visit functions, processing their instructions, and adding
343 // new functions to the worklist, until a fixed point is
344 // reached.
345 var shadow []*ssa.Function // for efficiency, we double-buffer the worklist
346 for len(r.worklist) > 0 {
347 shadow, r.worklist = r.worklist, shadow[:0]
348 for _, f := range shadow {
349 r.visitFunc(f)
350 }
351 }
352 return r.result
353 }
354
355 // interfaces(C) returns all currently known interfaces implemented by C.
356 func (r *rta) interfaces(C types.Type) []*types.Interface {
357 // Create an info for C the first time we see it.
358 var cinfo *concreteTypeInfo
359 if v := r.concreteTypes.At(C); v != nil {
360 cinfo = v.(*concreteTypeInfo)
361 } else {
362 cinfo = &concreteTypeInfo{
363 C: C,
364 fprint: fingerprint(r.prog.MethodSets.MethodSet(C)),
365 }
366 r.concreteTypes.Set(C, cinfo)
367
368 // Ascertain set of interfaces C implements
369 // and update the 'implements' relation.
370 r.interfaceTypes.Iterate(func(I types.Type, v any) {
371 iinfo := v.(*interfaceTypeInfo)
372 if I := types.Unalias(I).(*types.Interface); implements(cinfo, iinfo) {
373 iinfo.implementations = append(iinfo.implementations, C)
374 cinfo.implements = append(cinfo.implements, I)
375 }
376 })
377 }
378
379 return cinfo.implements
380 }
381
382 // implementations(I) returns all currently known concrete types that implement I.
383 func (r *rta) implementations(I *types.Interface) []types.Type {
384 // Create an info for I the first time we see it.
385 var iinfo *interfaceTypeInfo
386 if v := r.interfaceTypes.At(I); v != nil {
387 iinfo = v.(*interfaceTypeInfo)
388 } else {
389 iinfo = &interfaceTypeInfo{
390 I: I,
391 fprint: fingerprint(r.prog.MethodSets.MethodSet(I)),
392 }
393 r.interfaceTypes.Set(I, iinfo)
394
395 // Ascertain set of concrete types that implement I
396 // and update the 'implements' relation.
397 r.concreteTypes.Iterate(func(C types.Type, v any) {
398 cinfo := v.(*concreteTypeInfo)
399 if implements(cinfo, iinfo) {
400 cinfo.implements = append(cinfo.implements, I)
401 iinfo.implementations = append(iinfo.implementations, C)
402 }
403 })
404 }
405 return iinfo.implementations
406 }
407
408 // addRuntimeType is called for each concrete type that can be the
409 // dynamic type of some interface or reflect.Value.
410 // Adapted from needMethods in go/ssa/builder.go
411 func (r *rta) addRuntimeType(T types.Type, skip bool) {
412 // Never record aliases.
413 T = types.Unalias(T)
414
415 if prev, ok := r.result.RuntimeTypes.At(T).(bool); ok {
416 if skip && !prev {
417 r.result.RuntimeTypes.Set(T, skip)
418 }
419 return
420 }
421 r.result.RuntimeTypes.Set(T, skip)
422
423 mset := r.prog.MethodSets.MethodSet(T)
424
425 if _, ok := T.Underlying().(*types.Interface); !ok {
426 // T is a new concrete type.
427 for i, n := 0, mset.Len(); i < n; i++ {
428 sel := mset.At(i)
429 m := sel.Obj()
430
431 if m.Exported() {
432 // Exported methods are always potentially callable via reflection.
433 r.addReachable(r.prog.MethodValue(sel), true)
434 }
435 }
436
437 // Add callgraph edge for each existing dynamic
438 // "invoke"-mode call via that interface.
439 for _, I := range r.interfaces(T) {
440 sites, _ := r.invokeSites.At(I).([]ssa.CallInstruction)
441 for _, site := range sites {
442 r.addInvokeEdge(site, T)
443 }
444 }
445 }
446
447 // Precondition: T is not a method signature (*Signature with Recv()!=nil).
448 // Recursive case: skip => don't call makeMethods(T).
449 // Each package maintains its own set of types it has visited.
450
451 var n *types.Named
452 switch T := types.Unalias(T).(type) {
453 case *types.Named:
454 n = T
455 case *types.Pointer:
456 n, _ = types.Unalias(T.Elem()).(*types.Named)
457 }
458 if n != nil {
459 owner := n.Obj().Pkg()
460 if owner == nil {
461 return // built-in error type
462 }
463 }
464
465 // Recursion over signatures of each exported method.
466 for method := range mset.Methods() {
467 if method.Obj().Exported() {
468 sig := method.Type().(*types.Signature)
469 r.addRuntimeType(sig.Params(), true) // skip the Tuple itself
470 r.addRuntimeType(sig.Results(), true) // skip the Tuple itself
471 }
472 }
473
474 switch t := T.(type) {
475 case *types.Alias:
476 panic("unreachable")
477
478 case *types.Basic:
479 // nop
480
481 case *types.Interface:
482 // nop---handled by recursion over method set.
483
484 case *types.Pointer:
485 r.addRuntimeType(t.Elem(), false)
486
487 case *types.Slice:
488 r.addRuntimeType(t.Elem(), false)
489
490 case *types.Chan:
491 r.addRuntimeType(t.Elem(), false)
492
493 case *types.Map:
494 r.addRuntimeType(t.Key(), false)
495 r.addRuntimeType(t.Elem(), false)
496
497 case *types.Signature:
498 if t.Recv() != nil {
499 panic(fmt.Sprintf("Signature %s has Recv %s", t, t.Recv()))
500 }
501 r.addRuntimeType(t.Params(), true) // skip the Tuple itself
502 r.addRuntimeType(t.Results(), true) // skip the Tuple itself
503
504 case *types.Named:
505 // A pointer-to-named type can be derived from a named
506 // type via reflection. It may have methods too.
507 r.addRuntimeType(types.NewPointer(T), false)
508
509 // Consider 'type T struct{S}' where S has methods.
510 // Reflection provides no way to get from T to struct{S},
511 // only to S, so the method set of struct{S} is unwanted,
512 // so set 'skip' flag during recursion.
513 r.addRuntimeType(t.Underlying(), true)
514
515 case *types.Array:
516 r.addRuntimeType(t.Elem(), false)
517
518 case *types.Struct:
519 for i, n := 0, t.NumFields(); i < n; i++ {
520 r.addRuntimeType(t.Field(i).Type(), false)
521 }
522
523 case *types.Tuple:
524 for i, n := 0, t.Len(); i < n; i++ {
525 r.addRuntimeType(t.At(i).Type(), false)
526 }
527
528 default:
529 panic(T)
530 }
531 }
532
533 // fingerprint returns a bitmask with one bit set per method id,
534 // enabling 'implements' to quickly reject most candidates.
535 func fingerprint(mset *types.MethodSet) uint64 {
536 var space [64]byte
537 var mask uint64
538 for method := range mset.Methods() {
539 method := method.Obj()
540 sig := method.Type().(*types.Signature)
541 if sig.TypeParams() != nil {
542 continue // skip generic methods since interfaces don't have them
543 }
544 sum := crc32.ChecksumIEEE(fmt.Appendf(space[:], "%s/%d/%d",
545 method.Id(),
546 sig.Params().Len(),
547 sig.Results().Len()))
548 mask |= 1 << (sum % 64)
549 }
550 return mask
551 }
552
553 // implements reports whether types.Implements(cinfo.C, iinfo.I),
554 // but more efficiently.
555 func implements(cinfo *concreteTypeInfo, iinfo *interfaceTypeInfo) (got bool) {
556 // The concrete type must have at least the methods
557 // (bits) of the interface type. Use a bitwise subset
558 // test to reject most candidates quickly.
559 return iinfo.fprint & ^cinfo.fprint == 0 && types.Implements(cinfo.C, iinfo.I)
560 }