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.
5 package irutil // import "honnef.co/go/tools/ir/irutil"
7 import "honnef.co/go/tools/ir"
9 // This file defines utilities for visiting the IR of
12 // TODO(adonovan): test coverage.
14 // AllFunctions finds and returns the set of functions potentially
15 // needed by program prog, as determined by a simple linker-style
16 // reachability algorithm starting from the members and method-sets of
17 // each package. The result may include anonymous functions and
18 // synthetic wrappers.
20 // Precondition: all packages are built.
22 func AllFunctions(prog *ir.Program) map[*ir.Function]bool {
25 seen: make(map[*ir.Function]bool),
33 seen map[*ir.Function]bool
36 func (visit *visitor) program() {
37 for _, pkg := range visit.prog.AllPackages() {
38 for _, mem := range pkg.Members {
39 if fn, ok := mem.(*ir.Function); ok {
44 for _, T := range visit.prog.RuntimeTypes() {
45 mset := visit.prog.MethodSets.MethodSet(T)
46 for i, n := 0, mset.Len(); i < n; i++ {
47 visit.function(visit.prog.MethodValue(mset.At(i)))
52 func (visit *visitor) function(fn *ir.Function) {
55 var buf [10]*ir.Value // avoid alloc in common case
56 for _, b := range fn.Blocks {
57 for _, instr := range b.Instrs {
58 for _, op := range instr.Operands(buf[:0]) {
59 if fn, ok := (*op).(*ir.Function); ok {
68 // MainPackages returns the subset of the specified packages
69 // named "main" that define a main function.
70 // The result may include synthetic "testmain" packages.
71 func MainPackages(pkgs []*ir.Package) []*ir.Package {
72 var mains []*ir.Package
73 for _, pkg := range pkgs {
74 if pkg.Pkg.Name() == "main" && pkg.Func("main") != nil {
75 mains = append(mains, pkg)