]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/pgo/irgraph.go
cmd/compile: enable PGO-driven call devirtualization
[gostls13.git] / src / cmd / compile / internal / pgo / 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 pgo
42
43 import (
44         "cmd/compile/internal/base"
45         "cmd/compile/internal/ir"
46         "cmd/compile/internal/pgo/internal/graph"
47         "cmd/compile/internal/typecheck"
48         "cmd/compile/internal/types"
49         "fmt"
50         "internal/profile"
51         "os"
52 )
53
54 // IRGraph is a call graph with nodes pointing to IRs of functions and edges
55 // carrying weights and callsite information.
56 //
57 // Nodes for indirect calls may have missing IR (IRNode.AST == nil) if the node
58 // is not visible from this package (e.g., not in the transitive deps). Keeping
59 // these nodes allows determining the hottest edge from a call even if that
60 // callee is not available.
61 //
62 // TODO(prattmic): Consider merging this data structure with Graph. This is
63 // effectively a copy of Graph aggregated to line number and pointing to IR.
64 type IRGraph struct {
65         // Nodes of the graph
66         IRNodes map[string]*IRNode
67 }
68
69 // IRNode represents a node (function) in the IRGraph.
70 type IRNode struct {
71         // Pointer to the IR of the Function represented by this node.
72         AST *ir.Func
73         // Linker symbol name of the Function represented by this node.
74         // Populated only if AST == nil.
75         LinkerSymbolName string
76
77         // Set of out-edges in the callgraph. The map uniquely identifies each
78         // edge based on the callsite and callee, for fast lookup.
79         OutEdges map[NodeMapKey]*IREdge
80 }
81
82 // Name returns the symbol name of this function.
83 func (i *IRNode) Name() string {
84         if i.AST != nil {
85                 return ir.LinkFuncName(i.AST)
86         }
87         return i.LinkerSymbolName
88 }
89
90 // IREdge represents a call edge in the IRGraph with source, destination,
91 // weight, callsite, and line number information.
92 type IREdge struct {
93         // Source and destination of the edge in IRNode.
94         Src, Dst       *IRNode
95         Weight         int64
96         CallSiteOffset int // Line offset from function start line.
97 }
98
99 // NodeMapKey represents a hash key to identify unique call-edges in profile
100 // and in IR. Used for deduplication of call edges found in profile.
101 //
102 // TODO(prattmic): rename to something more descriptive.
103 type NodeMapKey struct {
104         CallerName     string
105         CalleeName     string
106         CallSiteOffset int // Line offset from function start line.
107 }
108
109 // Weights capture both node weight and edge weight.
110 type Weights struct {
111         NFlat   int64
112         NCum    int64
113         EWeight int64
114 }
115
116 // CallSiteInfo captures call-site information and its caller/callee.
117 type CallSiteInfo struct {
118         LineOffset int // Line offset from function start line.
119         Caller     *ir.Func
120         Callee     *ir.Func
121 }
122
123 // Profile contains the processed PGO profile and weighted call graph used for
124 // PGO optimizations.
125 type Profile struct {
126         // Aggregated NodeWeights and EdgeWeights across the profile. This
127         // helps us determine the percentage threshold for hot/cold
128         // partitioning.
129         TotalNodeWeight int64
130         TotalEdgeWeight int64
131
132         // NodeMap contains all unique call-edges in the profile and their
133         // aggregated weight.
134         NodeMap map[NodeMapKey]*Weights
135
136         // WeightedCG represents the IRGraph built from profile, which we will
137         // update as part of inlining.
138         WeightedCG *IRGraph
139 }
140
141 // New generates a profile-graph from the profile.
142 func New(profileFile string) (*Profile, error) {
143         f, err := os.Open(profileFile)
144         if err != nil {
145                 return nil, fmt.Errorf("error opening profile: %w", err)
146         }
147         defer f.Close()
148         profile, err := profile.Parse(f)
149         if err != nil {
150                 return nil, fmt.Errorf("error parsing profile: %w", err)
151         }
152
153         if len(profile.Sample) == 0 {
154                 // We accept empty profiles, but there is nothing to do.
155                 return nil, nil
156         }
157
158         valueIndex := -1
159         for i, s := range profile.SampleType {
160                 // Samples count is the raw data collected, and CPU nanoseconds is just
161                 // a scaled version of it, so either one we can find is fine.
162                 if (s.Type == "samples" && s.Unit == "count") ||
163                         (s.Type == "cpu" && s.Unit == "nanoseconds") {
164                         valueIndex = i
165                         break
166                 }
167         }
168
169         if valueIndex == -1 {
170                 return nil, fmt.Errorf(`profile does not contain a sample index with value/type "samples/count" or cpu/nanoseconds"`)
171         }
172
173         g := graph.NewGraph(profile, &graph.Options{
174                 SampleValue: func(v []int64) int64 { return v[valueIndex] },
175         })
176
177         p := &Profile{
178                 NodeMap: make(map[NodeMapKey]*Weights),
179                 WeightedCG: &IRGraph{
180                         IRNodes: make(map[string]*IRNode),
181                 },
182         }
183
184         // Build the node map and totals from the profile graph.
185         if err := p.processprofileGraph(g); err != nil {
186                 return nil, err
187         }
188
189         if p.TotalNodeWeight == 0 || p.TotalEdgeWeight == 0 {
190                 return nil, nil // accept but ignore profile with no samples.
191         }
192
193         // Create package-level call graph with weights from profile and IR.
194         p.initializeIRGraph()
195
196         return p, nil
197 }
198
199 // processprofileGraph builds various maps from the profile-graph.
200 //
201 // It initializes NodeMap and Total{Node,Edge}Weight based on the name and
202 // callsite to compute node and edge weights which will be used later on to
203 // create edges for WeightedCG.
204 //
205 // Caller should ignore the profile if p.TotalNodeWeight == 0 || p.TotalEdgeWeight == 0.
206 func (p *Profile) processprofileGraph(g *graph.Graph) error {
207         nFlat := make(map[string]int64)
208         nCum := make(map[string]int64)
209         seenStartLine := false
210
211         // Accummulate weights for the same node.
212         for _, n := range g.Nodes {
213                 canonicalName := n.Info.Name
214                 nFlat[canonicalName] += n.FlatValue()
215                 nCum[canonicalName] += n.CumValue()
216         }
217
218         // Process graph and build various node and edge maps which will
219         // be consumed by AST walk.
220         for _, n := range g.Nodes {
221                 seenStartLine = seenStartLine || n.Info.StartLine != 0
222
223                 p.TotalNodeWeight += n.FlatValue()
224                 canonicalName := n.Info.Name
225                 // Create the key to the nodeMapKey.
226                 nodeinfo := NodeMapKey{
227                         CallerName:     canonicalName,
228                         CallSiteOffset: n.Info.Lineno - n.Info.StartLine,
229                 }
230
231                 for _, e := range n.Out {
232                         p.TotalEdgeWeight += e.WeightValue()
233                         nodeinfo.CalleeName = e.Dest.Info.Name
234                         if w, ok := p.NodeMap[nodeinfo]; ok {
235                                 w.EWeight += e.WeightValue()
236                         } else {
237                                 weights := new(Weights)
238                                 weights.NFlat = nFlat[canonicalName]
239                                 weights.NCum = nCum[canonicalName]
240                                 weights.EWeight = e.WeightValue()
241                                 p.NodeMap[nodeinfo] = weights
242                         }
243                 }
244         }
245
246         if p.TotalNodeWeight == 0 || p.TotalEdgeWeight == 0 {
247                 return nil // accept but ignore profile with no samples.
248         }
249
250         if !seenStartLine {
251                 // TODO(prattmic): If Function.start_line is missing we could
252                 // fall back to using absolute line numbers, which is better
253                 // than nothing.
254                 return fmt.Errorf("profile missing Function.start_line data (Go version of profiled application too old? Go 1.20+ automatically adds this to profiles)")
255         }
256
257         return nil
258 }
259
260 // initializeIRGraph builds the IRGraph by visiting all the ir.Func in decl list
261 // of a package.
262 func (p *Profile) initializeIRGraph() {
263         // Bottomup walk over the function to create IRGraph.
264         ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
265                 for _, fn := range list {
266                         p.VisitIR(fn)
267                 }
268         })
269
270         // Add additional edges for indirect calls. This must be done second so
271         // that IRNodes is fully populated (see the dummy node TODO in
272         // addIndirectEdges).
273         //
274         // TODO(prattmic): VisitIR above populates the graph via direct calls
275         // discovered via the IR. addIndirectEdges populates the graph via
276         // calls discovered via the profile. This combination of opposite
277         // approaches is a bit awkward, particularly because direct calls are
278         // discoverable via the profile as well. Unify these into a single
279         // approach.
280         p.addIndirectEdges()
281 }
282
283 // VisitIR traverses the body of each ir.Func and use NodeMap to determine if
284 // we need to add an edge from ir.Func and any node in the ir.Func body.
285 func (p *Profile) VisitIR(fn *ir.Func) {
286         g := p.WeightedCG
287
288         if g.IRNodes == nil {
289                 g.IRNodes = make(map[string]*IRNode)
290         }
291
292         name := ir.LinkFuncName(fn)
293         node, ok := g.IRNodes[name]
294         if !ok {
295                 node = &IRNode{
296                         AST: fn,
297                 }
298                 g.IRNodes[name] = node
299         }
300
301         // Recursively walk over the body of the function to create IRGraph edges.
302         p.createIRGraphEdge(fn, node, name)
303 }
304
305 // NodeLineOffset returns the line offset of n in fn.
306 func NodeLineOffset(n ir.Node, fn *ir.Func) int {
307         // See "A note on line numbers" at the top of the file.
308         line := int(base.Ctxt.InnermostPos(n.Pos()).RelLine())
309         startLine := int(base.Ctxt.InnermostPos(fn.Pos()).RelLine())
310         return line - startLine
311 }
312
313 // addIREdge adds an edge between caller and new node that points to `callee`
314 // based on the profile-graph and NodeMap.
315 func (p *Profile) addIREdge(callerNode *IRNode, callerName string, call ir.Node, callee *ir.Func) {
316         g := p.WeightedCG
317
318         calleeName := ir.LinkFuncName(callee)
319         calleeNode, ok := g.IRNodes[calleeName]
320         if !ok {
321                 calleeNode = &IRNode{
322                         AST: callee,
323                 }
324                 g.IRNodes[calleeName] = calleeNode
325         }
326
327         nodeinfo := NodeMapKey{
328                 CallerName:     callerName,
329                 CalleeName:     calleeName,
330                 CallSiteOffset: NodeLineOffset(call, callerNode.AST),
331         }
332
333         var weight int64
334         if weights, ok := p.NodeMap[nodeinfo]; ok {
335                 weight = weights.EWeight
336         }
337
338         // Add edge in the IRGraph from caller to callee.
339         edge := &IREdge{
340                 Src:            callerNode,
341                 Dst:            calleeNode,
342                 Weight:         weight,
343                 CallSiteOffset: nodeinfo.CallSiteOffset,
344         }
345
346         if callerNode.OutEdges == nil {
347                 callerNode.OutEdges = make(map[NodeMapKey]*IREdge)
348         }
349         callerNode.OutEdges[nodeinfo] = edge
350 }
351
352 // addIndirectEdges adds indirect call edges found in the profile to the graph,
353 // to be used for devirtualization.
354 //
355 // targetDeclFuncs is the set of functions in typecheck.Target.Decls. Only
356 // edges from these functions will be added.
357 //
358 // Devirtualization is only applied to typecheck.Target.Decls functions, so there
359 // is no need to add edges from other functions.
360 //
361 // N.B. despite the name, addIndirectEdges will add any edges discovered via
362 // the profile. We don't know for sure that they are indirect, but assume they
363 // are since direct calls would already be added. (e.g., direct calls that have
364 // been deleted from source since the profile was taken would be added here).
365 //
366 // TODO(prattmic): Devirtualization runs before inlining, so we can't devirtualize
367 // calls inside inlined call bodies. If we did add that, we'd need edges from
368 // inlined bodies as well.
369 func (p *Profile) addIndirectEdges() {
370         g := p.WeightedCG
371
372         // g.IRNodes is populated with the set of functions in the local
373         // package build by VisitIR. We want to filter for local functions
374         // below, but we also add unknown callees to IRNodes as we go. So make
375         // an initial copy of IRNodes to recall just the local functions.
376         localNodes := make(map[string]*IRNode, len(g.IRNodes))
377         for k, v := range g.IRNodes {
378                 localNodes[k] = v
379         }
380
381         for key, weights := range p.NodeMap {
382                 // All callers in the local package build were added to IRNodes
383                 // in VisitIR. If a caller isn't in the local package build we
384                 // can skip adding edges, since we won't be devirtualizing in
385                 // them anyway. This keeps the graph smaller.
386                 callerNode, ok := localNodes[key.CallerName]
387                 if !ok {
388                         continue
389                 }
390
391                 // Already handled this edge?
392                 if _, ok := callerNode.OutEdges[key]; ok {
393                         continue
394                 }
395
396                 calleeNode, ok := g.IRNodes[key.CalleeName]
397                 if !ok {
398                         // IR is missing for this callee. Most likely this is
399                         // because the callee isn't in the transitive deps of
400                         // this package.
401                         //
402                         // Record this call anyway. If this is the hottest,
403                         // then we want to skip devirtualization rather than
404                         // devirtualizing to the second most common callee.
405                         //
406                         // TODO(prattmic): VisitIR populates IRNodes with all
407                         // of the functions discovered via local package
408                         // function declarations and calls. Thus we could miss
409                         // functions that are available in export data of
410                         // transitive deps, but aren't directly reachable. We
411                         // need to do a lookup directly from package export
412                         // data to get complete coverage.
413                         calleeNode = &IRNode{
414                                 LinkerSymbolName: key.CalleeName,
415                                 // TODO: weights? We don't need them.
416                         }
417                         // Add dummy node back to IRNodes. We don't need this
418                         // directly, but PrintWeightedCallGraphDOT uses these
419                         // to print nodes.
420                         g.IRNodes[key.CalleeName] = calleeNode
421                 }
422                 edge := &IREdge{
423                         Src:            callerNode,
424                         Dst:            calleeNode,
425                         Weight:         weights.EWeight,
426                         CallSiteOffset: key.CallSiteOffset,
427                 }
428
429                 if callerNode.OutEdges == nil {
430                         callerNode.OutEdges = make(map[NodeMapKey]*IREdge)
431                 }
432                 callerNode.OutEdges[key] = edge
433         }
434 }
435
436 // createIRGraphEdge traverses the nodes in the body of ir.Func and adds edges
437 // between the callernode which points to the ir.Func and the nodes in the
438 // body.
439 func (p *Profile) createIRGraphEdge(fn *ir.Func, callernode *IRNode, name string) {
440         ir.VisitList(fn.Body, func(n ir.Node) {
441                 switch n.Op() {
442                 case ir.OCALLFUNC:
443                         call := n.(*ir.CallExpr)
444                         // Find the callee function from the call site and add the edge.
445                         callee := DirectCallee(call.X)
446                         if callee != nil {
447                                 p.addIREdge(callernode, name, n, callee)
448                         }
449                 case ir.OCALLMETH:
450                         call := n.(*ir.CallExpr)
451                         // Find the callee method from the call site and add the edge.
452                         callee := ir.MethodExprName(call.X).Func
453                         p.addIREdge(callernode, name, n, callee)
454                 }
455         })
456 }
457
458 // WeightInPercentage converts profile weights to a percentage.
459 func WeightInPercentage(value int64, total int64) float64 {
460         return (float64(value) / float64(total)) * 100
461 }
462
463 // PrintWeightedCallGraphDOT prints IRGraph in DOT format.
464 func (p *Profile) PrintWeightedCallGraphDOT(edgeThreshold float64) {
465         fmt.Printf("\ndigraph G {\n")
466         fmt.Printf("forcelabels=true;\n")
467
468         // List of functions in this package.
469         funcs := make(map[string]struct{})
470         ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
471                 for _, f := range list {
472                         name := ir.LinkFuncName(f)
473                         funcs[name] = struct{}{}
474                 }
475         })
476
477         // Determine nodes of DOT.
478         //
479         // Note that ir.Func may be nil for functions not visible from this
480         // package.
481         nodes := make(map[string]*ir.Func)
482         for name := range funcs {
483                 if n, ok := p.WeightedCG.IRNodes[name]; ok {
484                         for _, e := range n.OutEdges {
485                                 if _, ok := nodes[e.Src.Name()]; !ok {
486                                         nodes[e.Src.Name()] = e.Src.AST
487                                 }
488                                 if _, ok := nodes[e.Dst.Name()]; !ok {
489                                         nodes[e.Dst.Name()] = e.Dst.AST
490                                 }
491                         }
492                         if _, ok := nodes[n.Name()]; !ok {
493                                 nodes[n.Name()] = n.AST
494                         }
495                 }
496         }
497
498         // Print nodes.
499         for name, ast := range nodes {
500                 if _, ok := p.WeightedCG.IRNodes[name]; ok {
501                         style := "solid"
502                         if ast == nil {
503                                 style = "dashed"
504                         }
505
506                         if ast != nil && ast.Inl != nil {
507                                 fmt.Printf("\"%v\" [color=black, style=%s, label=\"%v,inl_cost=%d\"];\n", name, style, name, ast.Inl.Cost)
508                         } else {
509                                 fmt.Printf("\"%v\" [color=black, style=%s, label=\"%v\"];\n", name, style, name)
510                         }
511                 }
512         }
513         // Print edges.
514         ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
515                 for _, f := range list {
516                         name := ir.LinkFuncName(f)
517                         if n, ok := p.WeightedCG.IRNodes[name]; ok {
518                                 for _, e := range n.OutEdges {
519                                         style := "solid"
520                                         if e.Dst.AST == nil {
521                                                 style = "dashed"
522                                         }
523                                         color := "black"
524                                         edgepercent := WeightInPercentage(e.Weight, p.TotalEdgeWeight)
525                                         if edgepercent > edgeThreshold {
526                                                 color = "red"
527                                         }
528
529                                         fmt.Printf("edge [color=%s, style=%s];\n", color, style)
530                                         fmt.Printf("\"%v\" -> \"%v\" [label=\"%.2f\"];\n", n.Name(), e.Dst.Name(), edgepercent)
531                                 }
532                         }
533                 }
534         })
535         fmt.Printf("}\n")
536 }
537
538 // DirectCallee takes a function-typed expression and returns the underlying
539 // function that it refers to if statically known. Otherwise, it returns nil.
540 //
541 // Equivalent to inline.inlCallee without calling CanInline on closures.
542 func DirectCallee(fn ir.Node) *ir.Func {
543         fn = ir.StaticValue(fn)
544         switch fn.Op() {
545         case ir.OMETHEXPR:
546                 fn := fn.(*ir.SelectorExpr)
547                 n := ir.MethodExprName(fn)
548                 // Check that receiver type matches fn.X.
549                 // TODO(mdempsky): Handle implicit dereference
550                 // of pointer receiver argument?
551                 if n == nil || !types.Identical(n.Type().Recv().Type, fn.X.Type()) {
552                         return nil
553                 }
554                 return n.Func
555         case ir.ONAME:
556                 fn := fn.(*ir.Name)
557                 if fn.Class == ir.PFUNC {
558                         return fn.Func
559                 }
560         case ir.OCLOSURE:
561                 fn := fn.(*ir.ClosureExpr)
562                 c := fn.Func
563                 return c
564         }
565         return nil
566 }