Debian Codegraph @

internal/cmd/irdump/main.go

raw
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 // irdump: a tool for displaying the IR form of Go programs.
6 package main
7
8 import (
9 "flag"
10 "fmt"
11 "os"
12 "runtime/pprof"
13
14 "honnef.co/go/tools/go/ir"
15 "honnef.co/go/tools/go/ir/irutil"
16
17 "golang.org/x/tools/go/packages"
18 )
19
20 // flags
21 var (
22 mode = ir.BuilderMode(0)
23 testFlag = flag.Bool("test", false, "include implicit test packages and executables")
24 cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
25 memprofile = flag.String("memprofile", "", "write heap profile to file")
26 tagsFlag = flag.String("tags", "", "comma-separated list of extra build tags (see: go help buildconstraint)")
27 )
28
29 func init() {
30 flag.Var(&mode, "build", ir.BuilderModeDoc)
31 }
32
33 const usage = `SSA builder.
34 Usage: irdump [-build=[DBCSNFLG]] [-test] package...
35 Use -help flag to display options.
36
37 Examples:
38 % irdump -build=F hello.go # dump SSA form of a single package
39 % irdump -build=F -test fmt # dump SSA form of a package and its tests
40 `
41
42 func main() {
43 if err := doMain(); err != nil {
44 fmt.Fprintf(os.Stderr, "irdump: %s\n", err)
45 os.Exit(1)
46 }
47 }
48
49 func doMain() error {
50 flag.Parse()
51 if len(flag.Args()) == 0 {
52 fmt.Fprint(os.Stderr, usage)
53 os.Exit(1)
54 }
55
56 cfg := &packages.Config{
57 BuildFlags: []string{"-tags=" + *tagsFlag},
58 Mode: packages.LoadSyntax,
59 Tests: *testFlag,
60 }
61
62 // Profiling support.
63 if *cpuprofile != "" {
64 f, err := os.Create(*cpuprofile)
65 if err != nil {
66 fmt.Fprintln(os.Stderr, err)
67 os.Exit(1)
68 }
69 pprof.StartCPUProfile(f)
70 defer pprof.StopCPUProfile()
71 }
72
73 if *memprofile != "" {
74 f, err := os.Create(*memprofile)
75 if err != nil {
76 fmt.Fprintln(os.Stderr, err)
77 os.Exit(1)
78 }
79 defer f.Close()
80 defer pprof.WriteHeapProfile(f)
81 }
82
83 // Load, parse and type-check the initial packages,
84 // and, if -run, their dependencies.
85 initial, err := packages.Load(cfg, flag.Args()...)
86 if err != nil {
87 return err
88 }
89 if len(initial) == 0 {
90 return fmt.Errorf("no packages")
91 }
92 if packages.PrintErrors(initial) > 0 {
93 return fmt.Errorf("packages contain errors")
94 }
95
96 // Create (and display) SSA only for initial packages and wrappers.
97 _, pkgs := irutil.Packages(initial, mode)
98 for i, p := range pkgs {
99 if p == nil {
100 return fmt.Errorf("cannot build SSA for package %s", initial[i])
101 }
102 p.Build()
103 }
104
105 return nil
106 }