Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

x/tools/go/cfg: parsed control graph incomprehensible #39523

Open
wuhuizuo opened this issue Jun 11, 2020 · 1 comment
Open

x/tools/go/cfg: parsed control graph incomprehensible #39523

wuhuizuo opened this issue Jun 11, 2020 · 1 comment
Labels
NeedsInvestigation Someone must examine and confirm this is a valid issue and not a duplicate of an existing one. Tools This label describes issues relating to any tools in the x/tools repository.
Milestone

Comments

@wuhuizuo
Copy link

wuhuizuo commented Jun 11, 2020

What version of Go are you using (go version)?

$ go version
go version go1.14.1 linux/amd64

Does this issue reproduce with the latest release?

yes

What operating system and processor architecture are you using (go env)?

go env
$ go env
GO111MODULE=""
GOARCH="amd64"
GOBIN=""
GOCACHE="/data/go/.cache"
GOENV="/root/.config/go/env"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOINSECURE=""
GONOPROXY="git.code.oa.com"
GONOSUMDB="git.code.oa.com"
GOOS="linux"
GOPATH="/data/go"
GOPRIVATE="git.code.oa.com"
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/usr/local/go"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/usr/local/go/pkg/tool/linux_amd64"
GCCGO="gccgo"
AR="ar"
CC="gcc"
CXX="g++"
CGO_ENABLED="1"
GOMOD="/data/apps/git.code.oa.com/flarezuo/testability/go.mod"
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build389890088=/tmp/go-build -gno-record-gcc-switches"

What did you do?

I write a main.go file to debug output the CFG(control flow graph) of a function following:

func abc(a int) int {
	if a == 0 {
		return a * 2
	}
	
	a++
	return a
}

main.go:

package main

import (
	"bytes"
	"fmt"
	"go/ast"
	"go/format"
	"go/parser"
	"go/token"
	"io"
	"os"
	"strings"

	"golang.org/x/tools/go/ast/inspector"
	"golang.org/x/tools/go/cfg"
)

// PrintCFG print control flow graph with graphviz dot format.
func printCFG(w io.Writer, graph *cfg.CFG) {
	if graph == nil {
		return
	}

	fset := token.NewFileSet()

	fmt.Fprintln(w, "digraph structs {")
	fmt.Fprintln(w, "\tnode [shape=Mrecord]")

	// output nodes
	for _, b := range graph.Blocks {
		var labels []string
		labels = append(labels, fmt.Sprintf("<name> %s", b.String()))

		var codes []string
		for _, n := range b.Nodes {
			codes = append(codes, formatNode(fset, n))
		}
		fmt.Fprintf(w, "\t"+`%d [label="%s" tooltip="%s"]`+"\n",
			b.Index,
			strings.Join(labels, "|"),
			strings.Join(codes, "\n"),
		)
	}

        // output eges
	for _, b := range graph.Blocks {
		for _, s := range b.Succs {
			fmt.Fprintf(w, "\t"+`%d -> %d`+"\n", b.Index, s.Index)
		}
	}

	// output edges
	fmt.Fprintln(w, "}")
}

func formatNode(fset *token.FileSet, n ast.Node) string {
	var buf bytes.Buffer
	format.Node(&buf, fset, n)
	return fmt.Sprintf("%d:", n.Pos()) + buf.String()
}

func Debug(source string) {
	fset := token.NewFileSet()
	file, err := parser.ParseFile(fset, "demo.go", source, parser.ParseComments)
	if err != nil {
		panic(err)
	}

	nodeFilter := []ast.Node{(*ast.FuncDecl)(nil)}
	inspector.New([]*ast.File{file}).Preorder(nodeFilter, func(n ast.Node) {
		fn, ok := n.(*ast.FuncDecl)
		if !ok {
			return
		}
		graph := cfg.New(fn.Body, func(_ *ast.CallExpr) bool { return false })
		printCFG(os.Stdout, graph)
	})
}

func main() {
	src := `
	package testdata

	func abc(a int) int {
		if a == 0 {
			return a * 2
		}
	
		a++
		return a
	}
	`
	Debug(src)
}

What did you expect to see?

correct flow graph

What did you see instead?

Got incomprehensible graph:

digraph structs {
        node [shape=Mrecord]
        0 [label="<name> block 0 (entry)" tooltip="49:a == 0"]
        1 [label="<name> block 1 (if.then)" tooltip="61:return a * 2"]
        2 [label="<name> block 2 (if.done)" tooltip="82:a++
88:return a"]
        3 [label="<name> block 3 (unreachable.return)" tooltip=""]
        4 [label="<name> block 4 (unreachable.return)" tooltip=""]
        0 -> 1
        0 -> 2
        3 -> 2
}

image

@gopherbot gopherbot added the Tools This label describes issues relating to any tools in the x/tools repository. label Jun 11, 2020
@gopherbot gopherbot added this to the Unreleased milestone Jun 11, 2020
@toothrot toothrot added the NeedsInvestigation Someone must examine and confirm this is a valid issue and not a duplicate of an existing one. label Jun 12, 2020
@toothrot
Copy link
Contributor

/cc @golang/tools-team

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
NeedsInvestigation Someone must examine and confirm this is a valid issue and not a duplicate of an existing one. Tools This label describes issues relating to any tools in the x/tools repository.
Projects
None yet
Development

No branches or pull requests

3 participants