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 mset *types.MethodSet
118 fprint uint64 // fingerprint of method set
119 implements []*types.Interface // unordered set of implemented interfaces
120 }
121
122 type interfaceTypeInfo struct {
123 I *types.Interface
124 mset *types.MethodSet
125 fprint uint64
126 implementations []types.Type // unordered set of concrete implementations
127 }
128
129 // addReachable marks a function as potentially callable at run-time,
130 // and ensures that it gets processed.
131 func (r *rta) addReachable(f *ssa.Function, addrTaken bool) {
132 reachable := r.result.Reachable
133 n := len(reachable)
134 v := reachable[f]
135 if addrTaken {
136 v.AddrTaken = true
137 }
138 reachable[f] = v
139 if len(reachable) > n {
140 // First time seeing f. Add it to the worklist.
141 r.worklist = append(r.worklist, f)
142 }
143 }
144
145 // addEdge adds the specified call graph edge, and marks it reachable.
146 // addrTaken indicates whether to mark the callee as "address-taken".
147 // site is nil for calls made via reflection.
148 func (r *rta) addEdge(caller *ssa.Function, site ssa.CallInstruction, callee *ssa.Function, addrTaken bool) {
149 r.addReachable(callee, addrTaken)
150
151 if g := r.result.CallGraph; g != nil {
152 if caller == nil {
153 panic(site)
154 }
155 from := g.CreateNode(caller)
156 to := g.CreateNode(callee)
157 callgraph.AddEdge(from, site, to)
158 }
159 }
160
161 // ---------- addrTakenFuncs × dynCallSites ----------
162
163 // visitAddrTakenFunc is called each time we encounter an address-taken function f.
164 func (r *rta) visitAddrTakenFunc(f *ssa.Function) {
165 // Create two-level map (Signature -> Function -> bool).
166 S := f.Signature
167 funcs, _ := r.addrTakenFuncsBySig.At(S).(map[*ssa.Function]bool)
168 if funcs == nil {
169 funcs = make(map[*ssa.Function]bool)
170 r.addrTakenFuncsBySig.Set(S, funcs)
171 }
172 if !funcs[f] {
173 // First time seeing f.
174 funcs[f] = true
175
176 // If we've seen any dyncalls of this type, mark it reachable,
177 // and add call graph edges.
178 sites, _ := r.dynCallSites.At(S).([]ssa.CallInstruction)
179 for _, site := range sites {
180 r.addEdge(site.Parent(), site, f, true)
181 }
182
183 // If the program includes (*reflect.Value).Call,
184 // add a dynamic call edge from it to any address-taken
185 // function, regardless of signature.
186 //
187 // This isn't perfect.
188 // - The actual call comes from an internal function
189 // called reflect.call, but we can't rely on that here.
190 // - reflect.Value.CallSlice behaves similarly,
191 // but we don't bother to create callgraph edges from
192 // it as well as it wouldn't fundamentally change the
193 // reachability but it would add a bunch more edges.
194 // - We assume that if reflect.Value.Call is among
195 // the dependencies of the application, it is itself
196 // reachable. (It would be more accurate to defer
197 // all the addEdges below until r.V.Call itself
198 // becomes reachable.)
199 // - Fake call graph edges are added from r.V.Call to
200 // each address-taken function, but not to every
201 // method reachable through a materialized rtype,
202 // which is a little inconsistent. Still, the
203 // reachable set includes both kinds, which is what
204 // matters for e.g. deadcode detection.)
205 if r.reflectValueCall != nil {
206 var site ssa.CallInstruction = nil // can't find actual call site
207 r.addEdge(r.reflectValueCall, site, f, true)
208 }
209 }
210 }
211
212 // visitDynCall is called each time we encounter a dynamic "call"-mode call.
213 func (r *rta) visitDynCall(site ssa.CallInstruction) {
214 S := site.Common().Signature()
215
216 // Record the call site.
217 sites, _ := r.dynCallSites.At(S).([]ssa.CallInstruction)
218 r.dynCallSites.Set(S, append(sites, site))
219
220 // For each function of signature S that we know is address-taken,
221 // add an edge and mark it reachable.
222 funcs, _ := r.addrTakenFuncsBySig.At(S).(map[*ssa.Function]bool)
223 for g := range funcs {
224 r.addEdge(site.Parent(), site, g, true)
225 }
226 }
227
228 // ---------- concrete types × invoke sites ----------
229
230 // addInvokeEdge is called for each new pair (site, C) in the matrix.
231 func (r *rta) addInvokeEdge(site ssa.CallInstruction, C types.Type) {
232 // Ascertain the concrete method of C to be called.
233 imethod := site.Common().Method
234 cmethod := r.prog.LookupMethod(C, imethod.Pkg(), imethod.Name())
235 r.addEdge(site.Parent(), site, cmethod, true)
236 }
237
238 // visitInvoke is called each time the algorithm encounters an "invoke"-mode call.
239 func (r *rta) visitInvoke(site ssa.CallInstruction) {
240 I := site.Common().Value.Type().Underlying().(*types.Interface)
241
242 // Record the invoke site.
243 sites, _ := r.invokeSites.At(I).([]ssa.CallInstruction)
244 r.invokeSites.Set(I, append(sites, site))
245
246 // Add callgraph edge for each existing
247 // address-taken concrete type implementing I.
248 for _, C := range r.implementations(I) {
249 r.addInvokeEdge(site, C)
250 }
251 }
252
253 // ---------- main algorithm ----------
254
255 // visitFunc processes function f.
256 func (r *rta) visitFunc(f *ssa.Function) {
257 var space [32]*ssa.Value // preallocate space for common case
258
259 for _, b := range f.Blocks {
260 for _, instr := range b.Instrs {
261 rands := instr.Operands(space[:0])
262
263 switch instr := instr.(type) {
264 case ssa.CallInstruction:
265 call := instr.Common()
266 if call.IsInvoke() {
267 r.visitInvoke(instr)
268 } else if g := call.StaticCallee(); g != nil {
269 r.addEdge(f, instr, g, false)
270 } else if _, ok := call.Value.(*ssa.Builtin); !ok {
271 r.visitDynCall(instr)
272 }
273
274 // Ignore the call-position operand when
275 // looking for address-taken Functions.
276 // Hack: assume this is rands[0].
277 rands = rands[1:]
278
279 case *ssa.MakeInterface:
280 // Converting a value of type T to an
281 // interface materializes its runtime
282 // type, allowing any of its exported
283 // methods to be called though reflection.
284 r.addRuntimeType(instr.X.Type(), false)
285 }
286
287 // Process all address-taken functions.
288 for _, op := range rands {
289 if g, ok := (*op).(*ssa.Function); ok {
290 r.visitAddrTakenFunc(g)
291 }
292 }
293 }
294 }
295 }
296
297 // Analyze performs Rapid Type Analysis, starting at the specified root
298 // functions. It returns nil if no roots were specified.
299 //
300 // The root functions must be one or more entrypoints (main and init
301 // functions) of a complete SSA program, with function bodies for all
302 // dependencies, constructed with the [ssa.InstantiateGenerics] mode
303 // flag.
304 //
305 // If buildCallGraph is true, Result.CallGraph will contain a call
306 // graph; otherwise, only the other fields (reachable functions) are
307 // populated.
308 func Analyze(roots []*ssa.Function, buildCallGraph bool) *Result {
309 if len(roots) == 0 {
310 return nil
311 }
312
313 r := &rta{
314 result: &Result{Reachable: make(map[*ssa.Function]struct{ AddrTaken bool })},
315 prog: roots[0].Prog,
316 }
317
318 if buildCallGraph {
319 // TODO(adonovan): change callgraph API to eliminate the
320 // notion of a distinguished root node. Some callgraphs
321 // have many roots, or none.
322 r.result.CallGraph = callgraph.New(roots[0])
323 }
324
325 // Grab ssa.Function for (*reflect.Value).Call,
326 // if "reflect" is among the dependencies.
327 if reflectPkg := r.prog.ImportedPackage("reflect"); reflectPkg != nil {
328 reflectValue := reflectPkg.Members["Value"].(*ssa.Type)
329 r.reflectValueCall = r.prog.LookupMethod(reflectValue.Object().Type(), reflectPkg.Pkg, "Call")
330 }
331
332 hasher := typeutil.MakeHasher()
333 r.result.RuntimeTypes.SetHasher(hasher)
334 r.addrTakenFuncsBySig.SetHasher(hasher)
335 r.dynCallSites.SetHasher(hasher)
336 r.invokeSites.SetHasher(hasher)
337 r.concreteTypes.SetHasher(hasher)
338 r.interfaceTypes.SetHasher(hasher)
339
340 for _, root := range roots {
341 r.addReachable(root, false)
342 }
343
344 // Visit functions, processing their instructions, and adding
345 // new functions to the worklist, until a fixed point is
346 // reached.
347 var shadow []*ssa.Function // for efficiency, we double-buffer the worklist
348 for len(r.worklist) > 0 {
349 shadow, r.worklist = r.worklist, shadow[:0]
350 for _, f := range shadow {
351 r.visitFunc(f)
352 }
353 }
354 return r.result
355 }
356
357 // interfaces(C) returns all currently known interfaces implemented by C.
358 func (r *rta) interfaces(C types.Type) []*types.Interface {
359 // Create an info for C the first time we see it.
360 var cinfo *concreteTypeInfo
361 if v := r.concreteTypes.At(C); v != nil {
362 cinfo = v.(*concreteTypeInfo)
363 } else {
364 mset := r.prog.MethodSets.MethodSet(C)
365 cinfo = &concreteTypeInfo{
366 C: C,
367 mset: mset,
368 fprint: fingerprint(mset),
369 }
370 r.concreteTypes.Set(C, cinfo)
371
372 // Ascertain set of interfaces C implements
373 // and update the 'implements' relation.
374 r.interfaceTypes.Iterate(func(I types.Type, v any) {
375 iinfo := v.(*interfaceTypeInfo)
376 if I := types.Unalias(I).(*types.Interface); implements(cinfo, iinfo) {
377 iinfo.implementations = append(iinfo.implementations, C)
378 cinfo.implements = append(cinfo.implements, I)
379 }
380 })
381 }
382
383 return cinfo.implements
384 }
385
386 // implementations(I) returns all currently known concrete types that implement I.
387 func (r *rta) implementations(I *types.Interface) []types.Type {
388 // Create an info for I the first time we see it.
389 var iinfo *interfaceTypeInfo
390 if v := r.interfaceTypes.At(I); v != nil {
391 iinfo = v.(*interfaceTypeInfo)
392 } else {
393 mset := r.prog.MethodSets.MethodSet(I)
394 iinfo = &interfaceTypeInfo{
395 I: I,
396 mset: mset,
397 fprint: fingerprint(mset),
398 }
399 r.interfaceTypes.Set(I, iinfo)
400
401 // Ascertain set of concrete types that implement I
402 // and update the 'implements' relation.
403 r.concreteTypes.Iterate(func(C types.Type, v any) {
404 cinfo := v.(*concreteTypeInfo)
405 if implements(cinfo, iinfo) {
406 cinfo.implements = append(cinfo.implements, I)
407 iinfo.implementations = append(iinfo.implementations, C)
408 }
409 })
410 }
411 return iinfo.implementations
412 }
413
414 // addRuntimeType is called for each concrete type that can be the
415 // dynamic type of some interface or reflect.Value.
416 // Adapted from needMethods in go/ssa/builder.go
417 func (r *rta) addRuntimeType(T types.Type, skip bool) {
418 // Never record aliases.
419 T = types.Unalias(T)
420
421 if prev, ok := r.result.RuntimeTypes.At(T).(bool); ok {
422 if skip && !prev {
423 r.result.RuntimeTypes.Set(T, skip)
424 }
425 return
426 }
427 r.result.RuntimeTypes.Set(T, skip)
428
429 mset := r.prog.MethodSets.MethodSet(T)
430
431 if _, ok := T.Underlying().(*types.Interface); !ok {
432 // T is a new concrete type.
433 for i, n := 0, mset.Len(); i < n; i++ {
434 sel := mset.At(i)
435 m := sel.Obj()
436
437 if m.Exported() {
438 // Exported methods are always potentially callable via reflection.
439 r.addReachable(r.prog.MethodValue(sel), true)
440 }
441 }
442
443 // Add callgraph edge for each existing dynamic
444 // "invoke"-mode call via that interface.
445 for _, I := range r.interfaces(T) {
446 sites, _ := r.invokeSites.At(I).([]ssa.CallInstruction)
447 for _, site := range sites {
448 r.addInvokeEdge(site, T)
449 }
450 }
451 }
452
453 // Precondition: T is not a method signature (*Signature with Recv()!=nil).
454 // Recursive case: skip => don't call makeMethods(T).
455 // Each package maintains its own set of types it has visited.
456
457 var n *types.Named
458 switch T := types.Unalias(T).(type) {
459 case *types.Named:
460 n = T
461 case *types.Pointer:
462 n, _ = types.Unalias(T.Elem()).(*types.Named)
463 }
464 if n != nil {
465 owner := n.Obj().Pkg()
466 if owner == nil {
467 return // built-in error type
468 }
469 }
470
471 // Recursion over signatures of each exported method.
472 for method := range mset.Methods() {
473 if method.Obj().Exported() {
474 sig := method.Type().(*types.Signature)
475 r.addRuntimeType(sig.Params(), true) // skip the Tuple itself
476 r.addRuntimeType(sig.Results(), true) // skip the Tuple itself
477 }
478 }
479
480 switch t := T.(type) {
481 case *types.Alias:
482 panic("unreachable")
483
484 case *types.Basic:
485 // nop
486
487 case *types.Interface:
488 // nop---handled by recursion over method set.
489
490 case *types.Pointer:
491 r.addRuntimeType(t.Elem(), false)
492
493 case *types.Slice:
494 r.addRuntimeType(t.Elem(), false)
495
496 case *types.Chan:
497 r.addRuntimeType(t.Elem(), false)
498
499 case *types.Map:
500 r.addRuntimeType(t.Key(), false)
501 r.addRuntimeType(t.Elem(), false)
502
503 case *types.Signature:
504 if t.Recv() != nil {
505 panic(fmt.Sprintf("Signature %s has Recv %s", t, t.Recv()))
506 }
507 r.addRuntimeType(t.Params(), true) // skip the Tuple itself
508 r.addRuntimeType(t.Results(), true) // skip the Tuple itself
509
510 case *types.Named:
511 // A pointer-to-named type can be derived from a named
512 // type via reflection. It may have methods too.
513 r.addRuntimeType(types.NewPointer(T), false)
514
515 // Consider 'type T struct{S}' where S has methods.
516 // Reflection provides no way to get from T to struct{S},
517 // only to S, so the method set of struct{S} is unwanted,
518 // so set 'skip' flag during recursion.
519 r.addRuntimeType(t.Underlying(), true)
520
521 case *types.Array:
522 r.addRuntimeType(t.Elem(), false)
523
524 case *types.Struct:
525 for i, n := 0, t.NumFields(); i < n; i++ {
526 r.addRuntimeType(t.Field(i).Type(), false)
527 }
528
529 case *types.Tuple:
530 for i, n := 0, t.Len(); i < n; i++ {
531 r.addRuntimeType(t.At(i).Type(), false)
532 }
533
534 default:
535 panic(T)
536 }
537 }
538
539 // fingerprint returns a bitmask with one bit set per method id,
540 // enabling 'implements' to quickly reject most candidates.
541 func fingerprint(mset *types.MethodSet) uint64 {
542 var space [64]byte
543 var mask uint64
544 for method := range mset.Methods() {
545 method := method.Obj()
546 sig := method.Type().(*types.Signature)
547 sum := crc32.ChecksumIEEE(fmt.Appendf(space[:], "%s/%d/%d",
548 method.Id(),
549 sig.Params().Len(),
550 sig.Results().Len()))
551 mask |= 1 << (sum % 64)
552 }
553 return mask
554 }
555
556 // implements reports whether types.Implements(cinfo.C, iinfo.I),
557 // but more efficiently.
558 func implements(cinfo *concreteTypeInfo, iinfo *interfaceTypeInfo) (got bool) {
559 // The concrete type must have at least the methods
560 // (bits) of the interface type. Use a bitwise subset
561 // test to reject most candidates quickly.
562 return iinfo.fprint & ^cinfo.fprint == 0 && types.Implements(cinfo.C, iinfo.I)
563 }