Source file src/cmd/compile/internal/pgoir/irgraph.go

     1  // Copyright 2022 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  // A note on line numbers: when working with line numbers, we always use the
     6  // binary-visible relative line number. i.e., the line number as adjusted by
     7  // //line directives (ctxt.InnermostPos(ir.Node.Pos()).RelLine()). Use
     8  // NodeLineOffset to compute line offsets.
     9  //
    10  // If you are thinking, "wait, doesn't that just make things more complex than
    11  // using the real line number?", then you are 100% correct. Unfortunately,
    12  // pprof profiles generated by the runtime always contain line numbers as
    13  // adjusted by //line directives (because that is what we put in pclntab). Thus
    14  // for the best behavior when attempting to match the source with the profile
    15  // it makes sense to use the same line number space.
    16  //
    17  // Some of the effects of this to keep in mind:
    18  //
    19  //  - For files without //line directives there is no impact, as RelLine() ==
    20  //    Line().
    21  //  - For functions entirely covered by the same //line directive (i.e., a
    22  //    directive before the function definition and no directives within the
    23  //    function), there should also be no impact, as line offsets within the
    24  //    function should be the same as the real line offsets.
    25  //  - Functions containing //line directives may be impacted. As fake line
    26  //    numbers need not be monotonic, we may compute negative line offsets. We
    27  //    should accept these and attempt to use them for best-effort matching, as
    28  //    these offsets should still match if the source is unchanged, and may
    29  //    continue to match with changed source depending on the impact of the
    30  //    changes on fake line numbers.
    31  //  - Functions containing //line directives may also contain duplicate lines,
    32  //    making it ambiguous which call the profile is referencing. This is a
    33  //    similar problem to multiple calls on a single real line, as we don't
    34  //    currently track column numbers.
    35  //
    36  // Long term it would be best to extend pprof profiles to include real line
    37  // numbers. Until then, we have to live with these complexities. Luckily,
    38  // //line directives that change line numbers in strange ways should be rare,
    39  // and failing PGO matching on these files is not too big of a loss.
    40  
    41  // Package pgoir associates a PGO profile with the IR of the current package
    42  // compilation.
    43  package pgoir
    44  
    45  import (
    46  	"bufio"
    47  	"cmd/compile/internal/base"
    48  	"cmd/compile/internal/ir"
    49  	"cmd/compile/internal/typecheck"
    50  	"cmd/compile/internal/types"
    51  	"cmd/internal/pgo"
    52  	"fmt"
    53  	"maps"
    54  	"os"
    55  )
    56  
    57  // IRGraph is a call graph with nodes pointing to IRs of functions and edges
    58  // carrying weights and callsite information.
    59  //
    60  // Nodes for indirect calls may have missing IR (IRNode.AST == nil) if the node
    61  // is not visible from this package (e.g., not in the transitive deps). Keeping
    62  // these nodes allows determining the hottest edge from a call even if that
    63  // callee is not available.
    64  //
    65  // TODO(prattmic): Consider merging this data structure with Graph. This is
    66  // effectively a copy of Graph aggregated to line number and pointing to IR.
    67  type IRGraph struct {
    68  	// Nodes of the graph. Each node represents a function, keyed by linker
    69  	// symbol name.
    70  	IRNodes map[string]*IRNode
    71  }
    72  
    73  // IRNode represents a node (function) in the IRGraph.
    74  type IRNode struct {
    75  	// Pointer to the IR of the Function represented by this node.
    76  	AST *ir.Func
    77  	// Linker symbol name of the Function represented by this node.
    78  	// Populated only if AST == nil.
    79  	LinkerSymbolName string
    80  
    81  	// Set of out-edges in the callgraph. The map uniquely identifies each
    82  	// edge based on the callsite and callee, for fast lookup.
    83  	OutEdges map[pgo.NamedCallEdge]*IREdge
    84  }
    85  
    86  // Name returns the symbol name of this function.
    87  func (i *IRNode) Name() string {
    88  	if i.AST != nil {
    89  		return ir.LinkFuncName(i.AST)
    90  	}
    91  	return i.LinkerSymbolName
    92  }
    93  
    94  // IREdge represents a call edge in the IRGraph with source, destination,
    95  // weight, callsite, and line number information.
    96  type IREdge struct {
    97  	// Source and destination of the edge in IRNode.
    98  	Src, Dst       *IRNode
    99  	Weight         int64
   100  	CallSiteOffset int // Line offset from function start line.
   101  }
   102  
   103  // CallSiteInfo captures call-site information and its caller/callee.
   104  type CallSiteInfo struct {
   105  	LineOffset int // Line offset from function start line.
   106  	Caller     *ir.Func
   107  	Callee     *ir.Func
   108  }
   109  
   110  // Profile contains the processed PGO profile and weighted call graph used for
   111  // PGO optimizations.
   112  type Profile struct {
   113  	// Profile is the base data from the raw profile, without IR attribution.
   114  	*pgo.Profile
   115  
   116  	// WeightedCG represents the IRGraph built from profile, which we will
   117  	// update as part of inlining.
   118  	WeightedCG *IRGraph
   119  }
   120  
   121  // New generates a profile-graph from the profile or pre-processed profile.
   122  func New(profileFile string) (*Profile, error) {
   123  	f, err := os.Open(profileFile)
   124  	if err != nil {
   125  		return nil, fmt.Errorf("error opening profile: %w", err)
   126  	}
   127  	defer f.Close()
   128  	r := bufio.NewReader(f)
   129  
   130  	isSerialized, err := pgo.IsSerialized(r)
   131  	if err != nil {
   132  		return nil, fmt.Errorf("error processing profile header: %w", err)
   133  	}
   134  
   135  	var base *pgo.Profile
   136  	if isSerialized {
   137  		base, err = pgo.FromSerialized(r)
   138  		if err != nil {
   139  			return nil, fmt.Errorf("error processing serialized PGO profile: %w", err)
   140  		}
   141  	} else {
   142  		base, err = pgo.FromPProf(r)
   143  		if err != nil {
   144  			return nil, fmt.Errorf("error processing pprof PGO profile: %w", err)
   145  		}
   146  	}
   147  
   148  	if base.TotalWeight == 0 {
   149  		return nil, nil // accept but ignore profile with no samples.
   150  	}
   151  
   152  	// Create package-level call graph with weights from profile and IR.
   153  	wg := createIRGraph(base.NamedEdgeMap)
   154  
   155  	return &Profile{
   156  		Profile:    base,
   157  		WeightedCG: wg,
   158  	}, nil
   159  }
   160  
   161  // initializeIRGraph builds the IRGraph by visiting all the ir.Func in decl list
   162  // of a package.
   163  func createIRGraph(namedEdgeMap pgo.NamedEdgeMap) *IRGraph {
   164  	g := &IRGraph{
   165  		IRNodes: make(map[string]*IRNode),
   166  	}
   167  
   168  	// Bottomup walk over the function to create IRGraph.
   169  	ir.VisitFuncsBottomUp(typecheck.Target.Funcs, func(list []*ir.Func, recursive bool) {
   170  		for _, fn := range list {
   171  			visitIR(fn, namedEdgeMap, g)
   172  		}
   173  	})
   174  
   175  	// Add additional edges for indirect calls. This must be done second so
   176  	// that IRNodes is fully populated (see the dummy node TODO in
   177  	// addIndirectEdges).
   178  	//
   179  	// TODO(prattmic): visitIR above populates the graph via direct calls
   180  	// discovered via the IR. addIndirectEdges populates the graph via
   181  	// calls discovered via the profile. This combination of opposite
   182  	// approaches is a bit awkward, particularly because direct calls are
   183  	// discoverable via the profile as well. Unify these into a single
   184  	// approach.
   185  	addIndirectEdges(g, namedEdgeMap)
   186  
   187  	return g
   188  }
   189  
   190  // visitIR traverses the body of each ir.Func adds edges to g from ir.Func to
   191  // any called function in the body.
   192  func visitIR(fn *ir.Func, namedEdgeMap pgo.NamedEdgeMap, g *IRGraph) {
   193  	name := ir.LinkFuncName(fn)
   194  	node, ok := g.IRNodes[name]
   195  	if !ok {
   196  		node = &IRNode{
   197  			AST: fn,
   198  		}
   199  		g.IRNodes[name] = node
   200  	}
   201  
   202  	// Recursively walk over the body of the function to create IRGraph edges.
   203  	createIRGraphEdge(fn, node, name, namedEdgeMap, g)
   204  }
   205  
   206  // createIRGraphEdge traverses the nodes in the body of ir.Func and adds edges
   207  // between the callernode which points to the ir.Func and the nodes in the
   208  // body.
   209  func createIRGraphEdge(fn *ir.Func, callernode *IRNode, name string, namedEdgeMap pgo.NamedEdgeMap, g *IRGraph) {
   210  	ir.VisitList(fn.Body, func(n ir.Node) {
   211  		switch n.Op() {
   212  		case ir.OCALLFUNC:
   213  			call := n.(*ir.CallExpr)
   214  			// Find the callee function from the call site and add the edge.
   215  			callee := DirectCallee(call.Fun)
   216  			if callee != nil {
   217  				addIREdge(callernode, name, n, callee, namedEdgeMap, g)
   218  			}
   219  		case ir.OCALLMETH:
   220  			call := n.(*ir.CallExpr)
   221  			// Find the callee method from the call site and add the edge.
   222  			callee := ir.MethodExprName(call.Fun).Func
   223  			addIREdge(callernode, name, n, callee, namedEdgeMap, g)
   224  		}
   225  	})
   226  }
   227  
   228  // NodeLineOffset returns the line offset of n in fn.
   229  func NodeLineOffset(n ir.Node, fn *ir.Func) int {
   230  	// See "A note on line numbers" at the top of the file.
   231  	line := int(base.Ctxt.InnermostPos(n.Pos()).RelLine())
   232  	startLine := int(base.Ctxt.InnermostPos(fn.Pos()).RelLine())
   233  	return line - startLine
   234  }
   235  
   236  // addIREdge adds an edge between caller and new node that points to `callee`
   237  // based on the profile-graph and NodeMap.
   238  func addIREdge(callerNode *IRNode, callerName string, call ir.Node, callee *ir.Func, namedEdgeMap pgo.NamedEdgeMap, g *IRGraph) {
   239  	calleeName := ir.LinkFuncName(callee)
   240  	calleeNode, ok := g.IRNodes[calleeName]
   241  	if !ok {
   242  		calleeNode = &IRNode{
   243  			AST: callee,
   244  		}
   245  		g.IRNodes[calleeName] = calleeNode
   246  	}
   247  
   248  	namedEdge := pgo.NamedCallEdge{
   249  		CallerName:     callerName,
   250  		CalleeName:     calleeName,
   251  		CallSiteOffset: NodeLineOffset(call, callerNode.AST),
   252  	}
   253  
   254  	// Add edge in the IRGraph from caller to callee.
   255  	edge := &IREdge{
   256  		Src:            callerNode,
   257  		Dst:            calleeNode,
   258  		Weight:         namedEdgeMap.Weight[namedEdge],
   259  		CallSiteOffset: namedEdge.CallSiteOffset,
   260  	}
   261  
   262  	if callerNode.OutEdges == nil {
   263  		callerNode.OutEdges = make(map[pgo.NamedCallEdge]*IREdge)
   264  	}
   265  	callerNode.OutEdges[namedEdge] = edge
   266  }
   267  
   268  // LookupFunc looks up a function or method in export data. It is expected to
   269  // be overridden by package noder, to break a dependency cycle.
   270  var LookupFunc = func(fullName string) (*ir.Func, error) {
   271  	base.Fatalf("pgoir.LookupMethodFunc not overridden")
   272  	panic("unreachable")
   273  }
   274  
   275  // PostLookupCleanup performs any remaining cleanup operations needed
   276  // after a series of calls to LookupFunc, specifically reading in the
   277  // bodies of functions that may have been delayed due being encountered
   278  // in a stage where the reader's curfn state was not set up.
   279  var PostLookupCleanup = func() {
   280  	base.Fatalf("pgoir.PostLookupCleanup not overridden")
   281  	panic("unreachable")
   282  }
   283  
   284  // addIndirectEdges adds indirect call edges found in the profile to the graph,
   285  // to be used for devirtualization.
   286  //
   287  // N.B. despite the name, addIndirectEdges will add any edges discovered via
   288  // the profile. We don't know for sure that they are indirect, but assume they
   289  // are since direct calls would already be added. (e.g., direct calls that have
   290  // been deleted from source since the profile was taken would be added here).
   291  //
   292  // TODO(prattmic): Devirtualization runs before inlining, so we can't devirtualize
   293  // calls inside inlined call bodies. If we did add that, we'd need edges from
   294  // inlined bodies as well.
   295  func addIndirectEdges(g *IRGraph, namedEdgeMap pgo.NamedEdgeMap) {
   296  	// g.IRNodes is populated with the set of functions in the local
   297  	// package build by VisitIR. We want to filter for local functions
   298  	// below, but we also add unknown callees to IRNodes as we go. So make
   299  	// an initial copy of IRNodes to recall just the local functions.
   300  	localNodes := maps.Clone(g.IRNodes)
   301  
   302  	// N.B. We must consider edges in a stable order because export data
   303  	// lookup order (LookupMethodFunc, below) can impact the export data of
   304  	// this package, which must be stable across different invocations for
   305  	// reproducibility.
   306  	//
   307  	// The weight ordering of ByWeight is irrelevant, it just happens to be
   308  	// an ordered list of edges that is already available.
   309  	for _, key := range namedEdgeMap.ByWeight {
   310  		weight := namedEdgeMap.Weight[key]
   311  		// All callers in the local package build were added to IRNodes
   312  		// in VisitIR. If a caller isn't in the local package build we
   313  		// can skip adding edges, since we won't be devirtualizing in
   314  		// them anyway. This keeps the graph smaller.
   315  		callerNode, ok := localNodes[key.CallerName]
   316  		if !ok {
   317  			continue
   318  		}
   319  
   320  		// Already handled this edge?
   321  		if _, ok := callerNode.OutEdges[key]; ok {
   322  			continue
   323  		}
   324  
   325  		calleeNode, ok := g.IRNodes[key.CalleeName]
   326  		if !ok {
   327  			// IR is missing for this callee. VisitIR populates
   328  			// IRNodes with all functions discovered via local
   329  			// package function declarations and calls. This
   330  			// function may still be available from export data of
   331  			// a transitive dependency.
   332  			//
   333  			// TODO(prattmic): Parameterized types/functions are
   334  			// not supported.
   335  			//
   336  			// TODO(prattmic): This eager lookup during graph load
   337  			// is simple, but wasteful. We are likely to load many
   338  			// functions that we never need. We could delay load
   339  			// until we actually need the method in
   340  			// devirtualization. Instantiation of generic functions
   341  			// will likely need to be done at the devirtualization
   342  			// site, if at all.
   343  			if base.Debug.PGODebug >= 3 {
   344  				fmt.Printf("addIndirectEdges: %s attempting export data lookup\n", key.CalleeName)
   345  			}
   346  			fn, err := LookupFunc(key.CalleeName)
   347  			if err == nil {
   348  				if base.Debug.PGODebug >= 3 {
   349  					fmt.Printf("addIndirectEdges: %s found in export data\n", key.CalleeName)
   350  				}
   351  				calleeNode = &IRNode{AST: fn}
   352  
   353  				// N.B. we could call createIRGraphEdge to add
   354  				// direct calls in this newly-imported
   355  				// function's body to the graph. Similarly, we
   356  				// could add to this function's queue to add
   357  				// indirect calls. However, those would be
   358  				// useless given the visit order of inlining,
   359  				// and the ordering of PGO devirtualization and
   360  				// inlining. This function can only be used as
   361  				// an inlined body. We will never do PGO
   362  				// devirtualization inside an inlined call. Nor
   363  				// will we perform inlining inside an inlined
   364  				// call.
   365  			} else {
   366  				// Still not found. Most likely this is because
   367  				// the callee isn't in the transitive deps of
   368  				// this package.
   369  				//
   370  				// Record this call anyway. If this is the hottest,
   371  				// then we want to skip devirtualization rather than
   372  				// devirtualizing to the second most common callee.
   373  				if base.Debug.PGODebug >= 3 {
   374  					fmt.Printf("addIndirectEdges: %s not found in export data: %v\n", key.CalleeName, err)
   375  				}
   376  				calleeNode = &IRNode{LinkerSymbolName: key.CalleeName}
   377  			}
   378  
   379  			// Add dummy node back to IRNodes. We don't need this
   380  			// directly, but PrintWeightedCallGraphDOT uses these
   381  			// to print nodes.
   382  			g.IRNodes[key.CalleeName] = calleeNode
   383  		}
   384  		edge := &IREdge{
   385  			Src:            callerNode,
   386  			Dst:            calleeNode,
   387  			Weight:         weight,
   388  			CallSiteOffset: key.CallSiteOffset,
   389  		}
   390  
   391  		if callerNode.OutEdges == nil {
   392  			callerNode.OutEdges = make(map[pgo.NamedCallEdge]*IREdge)
   393  		}
   394  		callerNode.OutEdges[key] = edge
   395  	}
   396  
   397  	PostLookupCleanup()
   398  }
   399  
   400  // PrintWeightedCallGraphDOT prints IRGraph in DOT format.
   401  func (p *Profile) PrintWeightedCallGraphDOT(edgeThreshold float64) {
   402  	fmt.Printf("\ndigraph G {\n")
   403  	fmt.Printf("forcelabels=true;\n")
   404  
   405  	// List of functions in this package.
   406  	funcs := make(map[string]struct{})
   407  	ir.VisitFuncsBottomUp(typecheck.Target.Funcs, func(list []*ir.Func, recursive bool) {
   408  		for _, f := range list {
   409  			name := ir.LinkFuncName(f)
   410  			funcs[name] = struct{}{}
   411  		}
   412  	})
   413  
   414  	// Determine nodes of DOT.
   415  	//
   416  	// Note that ir.Func may be nil for functions not visible from this
   417  	// package.
   418  	nodes := make(map[string]*ir.Func)
   419  	for name := range funcs {
   420  		if n, ok := p.WeightedCG.IRNodes[name]; ok {
   421  			for _, e := range n.OutEdges {
   422  				if _, ok := nodes[e.Src.Name()]; !ok {
   423  					nodes[e.Src.Name()] = e.Src.AST
   424  				}
   425  				if _, ok := nodes[e.Dst.Name()]; !ok {
   426  					nodes[e.Dst.Name()] = e.Dst.AST
   427  				}
   428  			}
   429  			if _, ok := nodes[n.Name()]; !ok {
   430  				nodes[n.Name()] = n.AST
   431  			}
   432  		}
   433  	}
   434  
   435  	// Print nodes.
   436  	for name, ast := range nodes {
   437  		if _, ok := p.WeightedCG.IRNodes[name]; ok {
   438  			style := "solid"
   439  			if ast == nil {
   440  				style = "dashed"
   441  			}
   442  
   443  			if ast != nil && ast.Inl != nil {
   444  				fmt.Printf("\"%v\" [color=black, style=%s, label=\"%v,inl_cost=%d\"];\n", name, style, name, ast.Inl.Cost)
   445  			} else {
   446  				fmt.Printf("\"%v\" [color=black, style=%s, label=\"%v\"];\n", name, style, name)
   447  			}
   448  		}
   449  	}
   450  	// Print edges.
   451  	ir.VisitFuncsBottomUp(typecheck.Target.Funcs, func(list []*ir.Func, recursive bool) {
   452  		for _, f := range list {
   453  			name := ir.LinkFuncName(f)
   454  			if n, ok := p.WeightedCG.IRNodes[name]; ok {
   455  				for _, e := range n.OutEdges {
   456  					style := "solid"
   457  					if e.Dst.AST == nil {
   458  						style = "dashed"
   459  					}
   460  					color := "black"
   461  					edgepercent := pgo.WeightInPercentage(e.Weight, p.TotalWeight)
   462  					if edgepercent > edgeThreshold {
   463  						color = "red"
   464  					}
   465  
   466  					fmt.Printf("edge [color=%s, style=%s];\n", color, style)
   467  					fmt.Printf("\"%v\" -> \"%v\" [label=\"%.2f\"];\n", n.Name(), e.Dst.Name(), edgepercent)
   468  				}
   469  			}
   470  		}
   471  	})
   472  	fmt.Printf("}\n")
   473  }
   474  
   475  // DirectCallee takes a function-typed expression and returns the underlying
   476  // function that it refers to if statically known. Otherwise, it returns nil.
   477  //
   478  // Equivalent to inline.inlCallee without calling CanInline on closures.
   479  func DirectCallee(fn ir.Node) *ir.Func {
   480  	fn = ir.StaticValue(fn)
   481  	switch fn.Op() {
   482  	case ir.OMETHEXPR:
   483  		fn := fn.(*ir.SelectorExpr)
   484  		n := ir.MethodExprName(fn)
   485  		// Check that receiver type matches fn.X.
   486  		// TODO(mdempsky): Handle implicit dereference
   487  		// of pointer receiver argument?
   488  		if n == nil || !types.Identical(n.Type().Recv().Type, fn.X.Type()) {
   489  			return nil
   490  		}
   491  		return n.Func
   492  	case ir.ONAME:
   493  		fn := fn.(*ir.Name)
   494  		if fn.Class == ir.PFUNC {
   495  			return fn.Func
   496  		}
   497  	case ir.OCLOSURE:
   498  		fn := fn.(*ir.ClosureExpr)
   499  		c := fn.Func
   500  		return c
   501  	}
   502  	return nil
   503  }
   504  

View as plain text