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()).
11 // If you are thinking, "wait, doesn't that just make things more complex than
12 // using the real line number?", then you are 100% correct. Unfortunately,
13 // pprof profiles generated by the runtime always contain line numbers as
14 // adjusted by //line directives (because that is what we put in pclntab). Thus
15 // for the best behavior when attempting to match the source with the profile
16 // it makes sense to use the same line number space.
18 // Some of the effects of this to keep in mind:
20 // - For files without //line directives there is no impact, as RelLine() ==
22 // - For functions entirely covered by the same //line directive (i.e., a
23 // directive before the function definition and no directives within the
24 // function), there should also be no impact, as line offsets within the
25 // function should be the same as the real line offsets.
26 // - Functions containing //line directives may be impacted. As fake line
27 // numbers need not be monotonic, we may compute negative line offsets. We
28 // should accept these and attempt to use them for best-effort matching, as
29 // these offsets should still match if the source is unchanged, and may
30 // continue to match with changed source depending on the impact of the
31 // changes on fake line numbers.
32 // - Functions containing //line directives may also contain duplicate lines,
33 // making it ambiguous which call the profile is referencing. This is a
34 // similar problem to multiple calls on a single real line, as we don't
35 // currently track column numbers.
37 // Long term it would be best to extend pprof profiles to include real line
38 // numbers. Until then, we have to live with these complexities. Luckily,
39 // //line directives that change line numbers in strange ways should be rare,
40 // and failing PGO matching on these files is not too big of a loss.
45 "cmd/compile/internal/base"
46 "cmd/compile/internal/ir"
47 "cmd/compile/internal/typecheck"
48 "cmd/compile/internal/types"
55 // IRGraph is the key datastrcture that is built from profile. It is
56 // essentially a call graph with nodes pointing to IRs of functions and edges
57 // carrying weights and callsite information. The graph is bidirectional that
58 // helps in removing nodes efficiently.
61 IRNodes map[string]*IRNode
66 // IRNode represents a node in the IRGraph.
68 // Pointer to the IR of the Function represented by this node.
70 // Flat weight of the IRNode, obtained from profile.
72 // Cumulative weight of the IRNode.
76 // IREdgeMap maps an IRNode to its successors.
77 type IREdgeMap map[*IRNode][]*IREdge
79 // IREdge represents a call edge in the IRGraph with source, destination,
80 // weight, callsite, and line number information.
82 // Source and destination of the edge in IRNode.
88 // NodeMapKey represents a hash key to identify unique call-edges in profile
89 // and in IR. Used for deduplication of call edges found in profile.
90 type NodeMapKey struct {
96 // Weights capture both node weight and edge weight.
103 // CallSiteInfo captures call-site information and its caller/callee.
104 type CallSiteInfo struct {
110 // Profile contains the processed PGO profile and weighted call graph used for
111 // PGO optimizations.
112 type Profile struct {
113 // Original profile-graph.
116 // Aggregated NodeWeights and EdgeWeights across the profile. This
117 // helps us determine the percentage threshold for hot/cold
119 TotalNodeWeight int64
120 TotalEdgeWeight int64
122 // NodeMap contains all unique call-edges in the profile and their
123 // aggregated weight.
124 NodeMap map[NodeMapKey]*Weights
126 // WeightedCG represents the IRGraph built from profile, which we will
127 // update as part of inlining.
131 // New generates a profile-graph from the profile.
132 func New(profileFile string) *Profile {
133 f, err := os.Open(profileFile)
135 log.Fatal("failed to open file " + profileFile)
139 profile, err := profile.Parse(f)
141 log.Fatal("failed to Parse profile file.")
145 g, _ := newGraph(profile, &Options{
147 SampleValue: func(v []int64) int64 { return v[1] },
151 NodeMap: make(map[NodeMapKey]*Weights),
153 WeightedCG: &IRGraph{
154 IRNodes: make(map[string]*IRNode),
158 // Build the node map and totals from the profile graph.
159 p.preprocessProfileGraph()
161 // Create package-level call graph with weights from profile and IR.
162 p.initializeIRGraph()
167 // preprocessProfileGraph builds various maps from the profile-graph.
169 // It initializes NodeMap and Total{Node,Edge}Weight based on the name and
170 // callsite to compute node and edge weights which will be used later on to
171 // create edges for WeightedCG.
172 func (p *Profile) preprocessProfileGraph() {
173 nFlat := make(map[string]int64)
174 nCum := make(map[string]int64)
176 // Accummulate weights for the same node.
177 for _, n := range p.ProfileGraph.Nodes {
178 canonicalName := n.Info.Name
179 nFlat[canonicalName] += n.FlatValue()
180 nCum[canonicalName] += n.CumValue()
183 // Process ProfileGraph and build various node and edge maps which will
184 // be consumed by AST walk.
185 for _, n := range p.ProfileGraph.Nodes {
186 p.TotalNodeWeight += n.FlatValue()
187 canonicalName := n.Info.Name
188 // Create the key to the NodeMapKey.
189 nodeinfo := NodeMapKey{
190 CallerName: canonicalName,
191 CallSite: n.Info.Lineno,
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 // initializeIRGraph builds the IRGraph by visting all the ir.Func in decl list
212 func (p *Profile) initializeIRGraph() {
213 // Bottomup walk over the function to create IRGraph.
214 ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
215 for _, n := range list {
216 p.VisitIR(n, recursive)
221 // VisitIR traverses the body of each ir.Func and use NodeMap to determine if
222 // we need to add an edge from ir.Func and any node in the ir.Func body.
223 func (p *Profile) VisitIR(fn *ir.Func, recursive bool) {
226 if g.IRNodes == nil {
227 g.IRNodes = make(map[string]*IRNode)
229 if g.OutEdges == nil {
230 g.OutEdges = make(map[*IRNode][]*IREdge)
232 if g.InEdges == nil {
233 g.InEdges = make(map[*IRNode][]*IREdge)
235 name := ir.PkgFuncName(fn)
238 if g.IRNodes[name] == nil {
239 g.IRNodes[name] = node
241 // Create the key for the NodeMapKey.
242 nodeinfo := NodeMapKey{
247 // If the node exists, then update its node weight.
248 if weights, ok := p.NodeMap[nodeinfo]; ok {
249 g.IRNodes[name].Flat = weights.NFlat
250 g.IRNodes[name].Cum = weights.NCum
253 // Recursively walk over the body of the function to create IRGraph edges.
254 p.createIRGraphEdge(fn, g.IRNodes[name], name)
257 // addIREdge adds an edge between caller and new node that points to `callee`
258 // based on the profile-graph and NodeMap.
259 func (p *Profile) addIREdge(caller *IRNode, callee *ir.Func, n *ir.Node, callername string, line int) {
262 // Create an IRNode for the callee.
263 calleenode := new(IRNode)
264 calleenode.AST = callee
265 calleename := ir.PkgFuncName(callee)
267 // Create key for NodeMapKey.
268 nodeinfo := NodeMapKey{
269 CallerName: callername,
270 CalleeName: calleename,
274 // Create the callee node with node weight.
275 if g.IRNodes[calleename] == nil {
276 g.IRNodes[calleename] = calleenode
277 nodeinfo2 := NodeMapKey{
278 CallerName: calleename,
282 if weights, ok := p.NodeMap[nodeinfo2]; ok {
283 g.IRNodes[calleename].Flat = weights.NFlat
284 g.IRNodes[calleename].Cum = weights.NCum
288 if weights, ok := p.NodeMap[nodeinfo]; ok {
289 caller.Flat = weights.NFlat
290 caller.Cum = weights.NCum
292 // Add edge in the IRGraph from caller to callee.
293 info := &IREdge{Src: caller, Dst: g.IRNodes[calleename], Weight: weights.EWeight, CallSite: line}
294 g.OutEdges[caller] = append(g.OutEdges[caller], info)
295 g.InEdges[g.IRNodes[calleename]] = append(g.InEdges[g.IRNodes[calleename]], info)
297 nodeinfo.CalleeName = ""
298 nodeinfo.CallSite = -1
299 if weights, ok := p.NodeMap[nodeinfo]; ok {
300 caller.Flat = weights.NFlat
301 caller.Cum = weights.NCum
302 info := &IREdge{Src: caller, Dst: g.IRNodes[calleename], Weight: 0, CallSite: line}
303 g.OutEdges[caller] = append(g.OutEdges[caller], info)
304 g.InEdges[g.IRNodes[calleename]] = append(g.InEdges[g.IRNodes[calleename]], info)
306 info := &IREdge{Src: caller, Dst: g.IRNodes[calleename], Weight: 0, CallSite: line}
307 g.OutEdges[caller] = append(g.OutEdges[caller], info)
308 g.InEdges[g.IRNodes[calleename]] = append(g.InEdges[g.IRNodes[calleename]], info)
313 // 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.
314 func (p *Profile) createIRGraphEdge(fn *ir.Func, callernode *IRNode, name string) {
315 var doNode func(ir.Node) bool
316 doNode = func(n ir.Node) bool {
319 ir.DoChildren(n, doNode)
321 call := n.(*ir.CallExpr)
322 line := int(base.Ctxt.InnermostPos(n.Pos()).RelLine())
323 // Find the callee function from the call site and add the edge.
324 f := inlCallee(call.X)
326 p.addIREdge(callernode, f, &n, name, line)
329 call := n.(*ir.CallExpr)
330 // Find the callee method from the call site and add the edge.
331 fn2 := ir.MethodExprName(call.X).Func
332 line := int(base.Ctxt.InnermostPos(n.Pos()).RelLine())
333 p.addIREdge(callernode, fn2, &n, name, line)
340 // WeightInPercentage converts profile weights to a percentage.
341 func WeightInPercentage(value int64, total int64) float64 {
344 ratio = (float64(value) / float64(total)) * 100
349 // PrintWeightedCallGraphDOT prints IRGraph in DOT format.
350 func (p *Profile) PrintWeightedCallGraphDOT(edgeThreshold float64) {
351 fmt.Printf("\ndigraph G {\n")
352 fmt.Printf("forcelabels=true;\n")
354 // List of functions in this package.
355 funcs := make(map[string]struct{})
356 ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
357 for _, f := range list {
358 name := ir.PkgFuncName(f)
359 funcs[name] = struct{}{}
363 // Determine nodes of DOT.
364 nodes := make(map[string]*ir.Func)
365 for name, _ := range funcs {
366 if n, ok := p.WeightedCG.IRNodes[name]; ok {
367 for _, e := range p.WeightedCG.OutEdges[n] {
368 if _, ok := nodes[ir.PkgFuncName(e.Src.AST)]; !ok {
369 nodes[ir.PkgFuncName(e.Src.AST)] = e.Src.AST
371 if _, ok := nodes[ir.PkgFuncName(e.Dst.AST)]; !ok {
372 nodes[ir.PkgFuncName(e.Dst.AST)] = e.Dst.AST
375 if _, ok := nodes[ir.PkgFuncName(n.AST)]; !ok {
376 nodes[ir.PkgFuncName(n.AST)] = n.AST
382 for name, ast := range nodes {
383 if n, ok := p.WeightedCG.IRNodes[name]; ok {
384 nodeweight := WeightInPercentage(n.Flat, p.TotalNodeWeight)
387 fmt.Printf("\"%v\" [color=%v,label=\"%v,freq=%.2f,inl_cost=%d\"];\n", ir.PkgFuncName(ast), color, ir.PkgFuncName(ast), nodeweight, ast.Inl.Cost)
389 fmt.Printf("\"%v\" [color=%v, label=\"%v,freq=%.2f\"];\n", ir.PkgFuncName(ast), color, ir.PkgFuncName(ast), nodeweight)
394 ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
395 for _, f := range list {
396 name := ir.PkgFuncName(f)
397 if n, ok := p.WeightedCG.IRNodes[name]; ok {
398 for _, e := range p.WeightedCG.OutEdges[n] {
399 edgepercent := WeightInPercentage(e.Weight, p.TotalEdgeWeight)
400 if edgepercent > edgeThreshold {
401 fmt.Printf("edge [color=red, style=solid];\n")
403 fmt.Printf("edge [color=black, style=solid];\n")
406 fmt.Printf("\"%v\" -> \"%v\" [label=\"%.2f\"];\n", ir.PkgFuncName(n.AST), ir.PkgFuncName(e.Dst.AST), edgepercent)
414 // RedirectEdges deletes and redirects out-edges from node cur based on
415 // inlining information via inlinedCallSites.
417 // CallSiteInfo.Callee must be nil.
418 func (p *Profile) RedirectEdges(cur *IRNode, inlinedCallSites map[CallSiteInfo]struct{}) {
421 for i, outEdge := range g.OutEdges[cur] {
422 if _, found := inlinedCallSites[CallSiteInfo{Line: outEdge.CallSite, Caller: cur.AST}]; !found {
423 for _, InEdge := range g.InEdges[cur] {
424 if _, ok := inlinedCallSites[CallSiteInfo{Line: InEdge.CallSite, Caller: InEdge.Src.AST}]; ok {
425 weight := g.calculateWeight(InEdge.Src, cur)
426 g.redirectEdge(InEdge.Src, cur, outEdge, weight, i)
430 g.remove(cur, i, outEdge.Dst.AST.Nname)
436 // redirectEdges deletes the cur node out-edges and redirect them so now these
437 // edges are the parent node out-edges.
438 func (g *IRGraph) redirectEdges(parent *IRNode, cur *IRNode) {
439 for _, outEdge := range g.OutEdges[cur] {
441 g.OutEdges[parent] = append(g.OutEdges[parent], outEdge)
443 delete(g.OutEdges, cur)
446 // redirectEdge deletes the cur-node's out-edges and redirect them so now these
447 // edges are the parent node out-edges.
448 func (g *IRGraph) redirectEdge(parent *IRNode, cur *IRNode, outEdge *IREdge, weight int64, idx int) {
450 outEdge.Weight = weight * outEdge.Weight
451 g.OutEdges[parent] = append(g.OutEdges[parent], outEdge)
452 g.remove(cur, idx, outEdge.Dst.AST.Nname)
455 // remove deletes the cur-node's out-edges at index idx.
456 func (g *IRGraph) remove(cur *IRNode, idx int, name *ir.Name) {
457 if len(g.OutEdges[cur]) >= 2 {
458 g.OutEdges[cur][idx] = &IREdge{CallSite: -1}
460 delete(g.OutEdges, cur)
464 // removeall deletes all cur-node's out-edges that marked to be removed .
465 func (g *IRGraph) removeall(cur *IRNode) {
466 for i := len(g.OutEdges[cur]) - 1; i >= 0; i-- {
467 if g.OutEdges[cur][i].CallSite == -1 {
468 g.OutEdges[cur][i] = g.OutEdges[cur][len(g.OutEdges[cur])-1]
469 g.OutEdges[cur] = g.OutEdges[cur][:len(g.OutEdges[cur])-1]
474 // calculateWeight calculates the weight of the new redirected edge.
475 func (g *IRGraph) calculateWeight(parent *IRNode, cur *IRNode) int64 {
478 for _, InEdge := range g.InEdges[cur] {
479 sum = sum + InEdge.Weight
480 if InEdge.Src == parent {
493 // inlCallee is same as the implementation for inl.go with one change. The change is that we do not invoke CanInline on a closure.
494 func inlCallee(fn ir.Node) *ir.Func {
495 fn = ir.StaticValue(fn)
498 fn := fn.(*ir.SelectorExpr)
499 n := ir.MethodExprName(fn)
500 // Check that receiver type matches fn.X.
501 // TODO(mdempsky): Handle implicit dereference
502 // of pointer receiver argument?
503 if n == nil || !types.Identical(n.Type().Recv().Type, fn.X.Type()) {
509 if fn.Class == ir.PFUNC {
513 fn := fn.(*ir.ClosureExpr)