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