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.
7 // A note on line numbers: when working with line numbers, we always use the
8 // binary-visible relative line number. i.e., the line number as adjusted by
9 // //line directives (ctxt.InnermostPos(ir.Node.Pos()).RelLine()). Use
10 // NodeLineOffset to compute line offsets.
12 // If you are thinking, "wait, doesn't that just make things more complex than
13 // using the real line number?", then you are 100% correct. Unfortunately,
14 // pprof profiles generated by the runtime always contain line numbers as
15 // adjusted by //line directives (because that is what we put in pclntab). Thus
16 // for the best behavior when attempting to match the source with the profile
17 // it makes sense to use the same line number space.
19 // Some of the effects of this to keep in mind:
21 // - For files without //line directives there is no impact, as RelLine() ==
23 // - For functions entirely covered by the same //line directive (i.e., a
24 // directive before the function definition and no directives within the
25 // function), there should also be no impact, as line offsets within the
26 // function should be the same as the real line offsets.
27 // - Functions containing //line directives may be impacted. As fake line
28 // numbers need not be monotonic, we may compute negative line offsets. We
29 // should accept these and attempt to use them for best-effort matching, as
30 // these offsets should still match if the source is unchanged, and may
31 // continue to match with changed source depending on the impact of the
32 // changes on fake line numbers.
33 // - Functions containing //line directives may also contain duplicate lines,
34 // making it ambiguous which call the profile is referencing. This is a
35 // similar problem to multiple calls on a single real line, as we don't
36 // currently track column numbers.
38 // Long term it would be best to extend pprof profiles to include real line
39 // numbers. Until then, we have to live with these complexities. Luckily,
40 // //line directives that change line numbers in strange ways should be rare,
41 // and failing PGO matching on these files is not too big of a loss.
46 "cmd/compile/internal/base"
47 "cmd/compile/internal/ir"
48 "cmd/compile/internal/typecheck"
49 "cmd/compile/internal/types"
56 // IRGraph is the key datastrcture that is built from profile. It is
57 // essentially a call graph with nodes pointing to IRs of functions and edges
58 // carrying weights and callsite information. The graph is bidirectional that
59 // helps in removing nodes efficiently.
62 IRNodes map[string]*IRNode
67 // IRNode represents a node in the IRGraph.
69 // Pointer to the IR of the Function represented by this node.
71 // Flat weight of the IRNode, obtained from profile.
73 // Cumulative weight of the IRNode.
77 // IREdgeMap maps an IRNode to its successors.
78 type IREdgeMap map[*IRNode][]*IREdge
80 // IREdge represents a call edge in the IRGraph with source, destination,
81 // weight, callsite, and line number information.
83 // Source and destination of the edge in IRNode.
86 CallSiteOffset int // Line offset from function start line.
89 // NodeMapKey represents a hash key to identify unique call-edges in profile
90 // and in IR. Used for deduplication of call edges found in profile.
91 type NodeMapKey struct {
94 CallSiteOffset int // Line offset from function start line.
97 // Weights capture both node weight and edge weight.
104 // CallSiteInfo captures call-site information and its caller/callee.
105 type CallSiteInfo struct {
106 LineOffset int // Line offset from function start line.
111 // Profile contains the processed PGO profile and weighted call graph used for
112 // PGO optimizations.
113 type Profile struct {
114 // Aggregated NodeWeights and EdgeWeights across the profile. This
115 // helps us determine the percentage threshold for hot/cold
117 TotalNodeWeight int64
118 TotalEdgeWeight int64
120 // NodeMap contains all unique call-edges in the profile and their
121 // aggregated weight.
122 NodeMap map[NodeMapKey]*Weights
124 // WeightedCG represents the IRGraph built from profile, which we will
125 // update as part of inlining.
129 // New generates a profile-graph from the profile.
130 func New(profileFile string) *Profile {
131 f, err := os.Open(profileFile)
133 log.Fatal("failed to open file " + profileFile)
137 profile, err := profile.Parse(f)
139 log.Fatal("failed to Parse profile file.")
143 g, _ := newGraph(profile, &Options{
145 SampleValue: func(v []int64) int64 { return v[1] },
149 NodeMap: make(map[NodeMapKey]*Weights),
150 WeightedCG: &IRGraph{
151 IRNodes: make(map[string]*IRNode),
155 // Build the node map and totals from the profile graph.
156 p.processprofileGraph(g)
158 // Create package-level call graph with weights from profile and IR.
159 p.initializeIRGraph()
164 // processprofileGraph builds various maps from the profile-graph.
166 // It initializes NodeMap and Total{Node,Edge}Weight based on the name and
167 // callsite to compute node and edge weights which will be used later on to
168 // create edges for WeightedCG.
169 func (p *Profile) processprofileGraph(g *Graph) {
170 nFlat := make(map[string]int64)
171 nCum := make(map[string]int64)
172 seenStartLine := false
174 // Accummulate weights for the same node.
175 for _, n := range g.Nodes {
176 canonicalName := n.Info.Name
177 nFlat[canonicalName] += n.FlatValue()
178 nCum[canonicalName] += n.CumValue()
181 // Process graph and build various node and edge maps which will
182 // be consumed by AST walk.
183 for _, n := range g.Nodes {
184 seenStartLine = seenStartLine || n.Info.StartLine != 0
186 p.TotalNodeWeight += n.FlatValue()
187 canonicalName := n.Info.Name
188 // Create the key to the nodeMapKey.
189 nodeinfo := NodeMapKey{
190 CallerName: canonicalName,
191 CallSiteOffset: n.Info.Lineno - n.Info.StartLine,
194 for _, e := range n.Out {
195 p.TotalEdgeWeight += e.WeightValue()
196 nodeinfo.CalleeName = e.Dest.Info.Name
197 if w, ok := p.NodeMap[nodeinfo]; ok {
198 w.EWeight += e.WeightValue()
200 weights := new(Weights)
201 weights.NFlat = nFlat[canonicalName]
202 weights.NCum = nCum[canonicalName]
203 weights.EWeight = e.WeightValue()
204 p.NodeMap[nodeinfo] = weights
210 // TODO(prattic): If Function.start_line is missing we could
211 // fall back to using absolute line numbers, which is better
213 log.Fatal("PGO profile missing Function.start_line data")
217 // initializeIRGraph builds the IRGraph by visting all the ir.Func in decl list
219 func (p *Profile) initializeIRGraph() {
220 // Bottomup walk over the function to create IRGraph.
221 ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
222 for _, n := range list {
223 p.VisitIR(n, recursive)
228 // VisitIR traverses the body of each ir.Func and use NodeMap to determine if
229 // we need to add an edge from ir.Func and any node in the ir.Func body.
230 func (p *Profile) VisitIR(fn *ir.Func, recursive bool) {
233 if g.IRNodes == nil {
234 g.IRNodes = make(map[string]*IRNode)
236 if g.OutEdges == nil {
237 g.OutEdges = make(map[*IRNode][]*IREdge)
239 if g.InEdges == nil {
240 g.InEdges = make(map[*IRNode][]*IREdge)
242 name := ir.PkgFuncName(fn)
245 if g.IRNodes[name] == nil {
246 g.IRNodes[name] = node
248 // Create the key for the NodeMapKey.
249 nodeinfo := NodeMapKey{
254 // If the node exists, then update its node weight.
255 if weights, ok := p.NodeMap[nodeinfo]; ok {
256 g.IRNodes[name].Flat = weights.NFlat
257 g.IRNodes[name].Cum = weights.NCum
260 // Recursively walk over the body of the function to create IRGraph edges.
261 p.createIRGraphEdge(fn, g.IRNodes[name], name)
264 // NodeLineOffset returns the line offset of n in fn.
265 func NodeLineOffset(n ir.Node, fn *ir.Func) int {
266 // See "A note on line numbers" at the top of the file.
267 line := int(base.Ctxt.InnermostPos(n.Pos()).RelLine())
268 startLine := int(base.Ctxt.InnermostPos(fn.Pos()).RelLine())
269 return line - startLine
272 // addIREdge adds an edge between caller and new node that points to `callee`
273 // based on the profile-graph and NodeMap.
274 func (p *Profile) addIREdge(caller *IRNode, callername string, call ir.Node, callee *ir.Func) {
277 // Create an IRNode for the callee.
278 calleenode := new(IRNode)
279 calleenode.AST = callee
280 calleename := ir.PkgFuncName(callee)
282 // Create key for NodeMapKey.
283 nodeinfo := NodeMapKey{
284 CallerName: callername,
285 CalleeName: calleename,
286 CallSiteOffset: NodeLineOffset(call, caller.AST),
289 // Create the callee node with node weight.
290 if g.IRNodes[calleename] == nil {
291 g.IRNodes[calleename] = calleenode
292 nodeinfo2 := NodeMapKey{
293 CallerName: calleename,
297 if weights, ok := p.NodeMap[nodeinfo2]; ok {
298 g.IRNodes[calleename].Flat = weights.NFlat
299 g.IRNodes[calleename].Cum = weights.NCum
303 if weights, ok := p.NodeMap[nodeinfo]; ok {
304 caller.Flat = weights.NFlat
305 caller.Cum = weights.NCum
307 // Add edge in the IRGraph from caller to callee.
308 info := &IREdge{Src: caller, Dst: g.IRNodes[calleename], Weight: weights.EWeight, CallSiteOffset: nodeinfo.CallSiteOffset}
309 g.OutEdges[caller] = append(g.OutEdges[caller], info)
310 g.InEdges[g.IRNodes[calleename]] = append(g.InEdges[g.IRNodes[calleename]], info)
312 nodeinfo.CalleeName = ""
313 nodeinfo.CallSiteOffset = 0
314 if weights, ok := p.NodeMap[nodeinfo]; ok {
315 caller.Flat = weights.NFlat
316 caller.Cum = weights.NCum
317 info := &IREdge{Src: caller, Dst: g.IRNodes[calleename], Weight: 0, CallSiteOffset: nodeinfo.CallSiteOffset}
318 g.OutEdges[caller] = append(g.OutEdges[caller], info)
319 g.InEdges[g.IRNodes[calleename]] = append(g.InEdges[g.IRNodes[calleename]], info)
321 info := &IREdge{Src: caller, Dst: g.IRNodes[calleename], Weight: 0, CallSiteOffset: nodeinfo.CallSiteOffset}
322 g.OutEdges[caller] = append(g.OutEdges[caller], info)
323 g.InEdges[g.IRNodes[calleename]] = append(g.InEdges[g.IRNodes[calleename]], info)
328 // createIRGraphEdge traverses the nodes in the body of ir.Func and add edges between callernode which points to the ir.Func and the nodes in the body.
329 func (p *Profile) createIRGraphEdge(fn *ir.Func, callernode *IRNode, name string) {
330 var doNode func(ir.Node) bool
331 doNode = func(n ir.Node) bool {
334 ir.DoChildren(n, doNode)
336 call := n.(*ir.CallExpr)
337 // Find the callee function from the call site and add the edge.
338 callee := inlCallee(call.X)
340 p.addIREdge(callernode, name, n, callee)
343 call := n.(*ir.CallExpr)
344 // Find the callee method from the call site and add the edge.
345 callee := ir.MethodExprName(call.X).Func
346 p.addIREdge(callernode, name, n, callee)
353 // WeightInPercentage converts profile weights to a percentage.
354 func WeightInPercentage(value int64, total int64) float64 {
357 ratio = (float64(value) / float64(total)) * 100
362 // PrintWeightedCallGraphDOT prints IRGraph in DOT format.
363 func (p *Profile) PrintWeightedCallGraphDOT(edgeThreshold float64) {
364 fmt.Printf("\ndigraph G {\n")
365 fmt.Printf("forcelabels=true;\n")
367 // List of functions in this package.
368 funcs := make(map[string]struct{})
369 ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
370 for _, f := range list {
371 name := ir.PkgFuncName(f)
372 funcs[name] = struct{}{}
376 // Determine nodes of DOT.
377 nodes := make(map[string]*ir.Func)
378 for name, _ := range funcs {
379 if n, ok := p.WeightedCG.IRNodes[name]; ok {
380 for _, e := range p.WeightedCG.OutEdges[n] {
381 if _, ok := nodes[ir.PkgFuncName(e.Src.AST)]; !ok {
382 nodes[ir.PkgFuncName(e.Src.AST)] = e.Src.AST
384 if _, ok := nodes[ir.PkgFuncName(e.Dst.AST)]; !ok {
385 nodes[ir.PkgFuncName(e.Dst.AST)] = e.Dst.AST
388 if _, ok := nodes[ir.PkgFuncName(n.AST)]; !ok {
389 nodes[ir.PkgFuncName(n.AST)] = n.AST
395 for name, ast := range nodes {
396 if n, ok := p.WeightedCG.IRNodes[name]; ok {
397 nodeweight := WeightInPercentage(n.Flat, p.TotalNodeWeight)
400 fmt.Printf("\"%v\" [color=%v,label=\"%v,freq=%.2f,inl_cost=%d\"];\n", ir.PkgFuncName(ast), color, ir.PkgFuncName(ast), nodeweight, ast.Inl.Cost)
402 fmt.Printf("\"%v\" [color=%v, label=\"%v,freq=%.2f\"];\n", ir.PkgFuncName(ast), color, ir.PkgFuncName(ast), nodeweight)
407 ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
408 for _, f := range list {
409 name := ir.PkgFuncName(f)
410 if n, ok := p.WeightedCG.IRNodes[name]; ok {
411 for _, e := range p.WeightedCG.OutEdges[n] {
412 edgepercent := WeightInPercentage(e.Weight, p.TotalEdgeWeight)
413 if edgepercent > edgeThreshold {
414 fmt.Printf("edge [color=red, style=solid];\n")
416 fmt.Printf("edge [color=black, style=solid];\n")
419 fmt.Printf("\"%v\" -> \"%v\" [label=\"%.2f\"];\n", ir.PkgFuncName(n.AST), ir.PkgFuncName(e.Dst.AST), edgepercent)
427 // RedirectEdges deletes and redirects out-edges from node cur based on
428 // inlining information via inlinedCallSites.
430 // CallSiteInfo.Callee must be nil.
431 func (p *Profile) RedirectEdges(cur *IRNode, inlinedCallSites map[CallSiteInfo]struct{}) {
434 for i, outEdge := range g.OutEdges[cur] {
435 if _, found := inlinedCallSites[CallSiteInfo{LineOffset: outEdge.CallSiteOffset, Caller: cur.AST}]; !found {
436 for _, InEdge := range g.InEdges[cur] {
437 if _, ok := inlinedCallSites[CallSiteInfo{LineOffset: InEdge.CallSiteOffset, Caller: InEdge.Src.AST}]; ok {
438 weight := g.calculateWeight(InEdge.Src, cur)
439 g.redirectEdge(InEdge.Src, cur, outEdge, weight, i)
448 // redirectEdges deletes the cur node out-edges and redirect them so now these
449 // edges are the parent node out-edges.
450 func (g *IRGraph) redirectEdges(parent *IRNode, cur *IRNode) {
451 for _, outEdge := range g.OutEdges[cur] {
453 g.OutEdges[parent] = append(g.OutEdges[parent], outEdge)
455 delete(g.OutEdges, cur)
458 // redirectEdge deletes the cur-node's out-edges and redirect them so now these
459 // edges are the parent node out-edges.
460 func (g *IRGraph) redirectEdge(parent *IRNode, cur *IRNode, outEdge *IREdge, weight int64, idx int) {
462 outEdge.Weight = weight * outEdge.Weight
463 g.OutEdges[parent] = append(g.OutEdges[parent], outEdge)
467 // remove deletes the cur-node's out-edges at index idx.
468 func (g *IRGraph) remove(cur *IRNode, i int) {
469 if len(g.OutEdges[cur]) >= 2 {
470 g.OutEdges[cur][i] = g.OutEdges[cur][len(g.OutEdges[cur])-1]
471 g.OutEdges[cur] = g.OutEdges[cur][:len(g.OutEdges[cur])-1]
473 delete(g.OutEdges, cur)
477 // calculateWeight calculates the weight of the new redirected edge.
478 func (g *IRGraph) calculateWeight(parent *IRNode, cur *IRNode) int64 {
481 for _, InEdge := range g.InEdges[cur] {
482 sum = sum + InEdge.Weight
483 if InEdge.Src == parent {
496 // inlCallee is same as the implementation for inl.go with one change. The change is that we do not invoke CanInline on a closure.
497 func inlCallee(fn ir.Node) *ir.Func {
498 fn = ir.StaticValue(fn)
501 fn := fn.(*ir.SelectorExpr)
502 n := ir.MethodExprName(fn)
503 // Check that receiver type matches fn.X.
504 // TODO(mdempsky): Handle implicit dereference
505 // of pointer receiver argument?
506 if n == nil || !types.Identical(n.Type().Recv().Type, fn.X.Type()) {
512 if fn.Class == ir.PFUNC {
516 fn := fn.(*ir.ClosureExpr)