1 // Copyright 2023 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.
8 "cmd/compile/internal/base"
9 "cmd/compile/internal/ir"
10 "cmd/compile/internal/pgo"
17 type callSiteAnalyzer struct {
20 ptab map[ir.Node]pstate
26 func makeCallSiteAnalyzer(fn *ir.Func, ptab map[ir.Node]pstate) *callSiteAnalyzer {
27 isInit := fn.IsPackageInit() || strings.HasPrefix(fn.Sym().Name, "init.")
28 return &callSiteAnalyzer{
30 cstab: make(CallSiteTab),
36 func computeCallSiteTable(fn *ir.Func, ptab map[ir.Node]pstate) CallSiteTab {
38 fmt.Fprintf(os.Stderr, "=-= making callsite table for func %v:\n",
41 csa := makeCallSiteAnalyzer(fn, ptab)
42 var doNode func(ir.Node) bool
43 doNode = func(n ir.Node) bool {
45 ir.DoChildren(n, doNode)
53 func (csa *callSiteAnalyzer) flagsForNode(call *ir.CallExpr) CSPropBits {
56 if debugTrace&debugTraceCalls != 0 {
57 fmt.Fprintf(os.Stderr, "=-= analyzing call at %s\n",
58 fmtFullPos(call.Pos()))
61 // Set a bit if this call is within a loop.
66 // Set a bit if the call is within an init function (either
67 // compiler-generated or user-written).
69 r |= CallSiteInInitFunc
72 // Decide whether to apply the panic path heuristic. Hack: don't
73 // apply this heuristic in the function "main.main" (mostly just
74 // to avoid annoying users).
75 if !isMainMain(csa.fn) {
76 r = csa.determinePanicPathBits(call, r)
82 // determinePanicPathBits updates the CallSiteOnPanicPath bit within
83 // "r" if we think this call is on an unconditional path to
84 // panic/exit. Do this by walking back up the node stack to see if we
85 // can find either A) an enclosing panic, or B) a statement node that
86 // we've determined leads to a panic/exit.
87 func (csa *callSiteAnalyzer) determinePanicPathBits(call ir.Node, r CSPropBits) CSPropBits {
88 csa.nstack = append(csa.nstack, call)
90 csa.nstack = csa.nstack[:len(csa.nstack)-1]
93 for ri := range csa.nstack[:len(csa.nstack)-1] {
94 i := len(csa.nstack) - ri - 1
96 _, isCallExpr := n.(*ir.CallExpr)
97 _, isStmt := n.(ir.Stmt)
102 if debugTrace&debugTraceCalls != 0 {
103 ps, inps := csa.ptab[n]
104 fmt.Fprintf(os.Stderr, "=-= callpar %d op=%s ps=%s inptab=%v stmt=%v\n", i, n.Op().String(), ps.String(), inps, isStmt)
107 if n.Op() == ir.OPANIC {
108 r |= CallSiteOnPanicPath
111 if v, ok := csa.ptab[n]; ok {
112 if v == psCallsPanic {
113 r |= CallSiteOnPanicPath
124 func (csa *callSiteAnalyzer) addCallSite(callee *ir.Func, call *ir.CallExpr) {
125 flags := csa.flagsForNode(call)
126 // FIXME: maybe bulk-allocate these?
130 Assign: csa.containingAssignment(call),
132 ID: uint(len(csa.cstab)),
134 if _, ok := csa.cstab[call]; ok {
135 fmt.Fprintf(os.Stderr, "*** cstab duplicate entry at: %s\n",
136 fmtFullPos(call.Pos()))
137 fmt.Fprintf(os.Stderr, "*** call: %+v\n", call)
140 if callee.Inl != nil {
141 // Set initial score for callsite to the cost computed
142 // by CanInline; this score will be refined later based
144 cs.Score = int(callee.Inl.Cost)
148 if debugTrace&debugTraceCalls != 0 {
149 fmt.Fprintf(os.Stderr, "=-= added callsite: callee=%s call=%v\n",
150 callee.Sym().Name, callee)
154 // ScoreCalls assigns numeric scores to each of the callsites in
155 // function 'fn'; the lower the score, the more helpful we think it
156 // will be to inline.
158 // Unlike a lot of the other inline heuristics machinery, callsite
159 // scoring can't be done as part of the CanInline call for a function,
160 // due to fact that we may be working on a non-trivial SCC. So for
161 // example with this SCC:
163 // func foo(x int) { func bar(x int, f func()) {
165 // bar(x, func(){}) foo(x-1)
169 // We don't want to perform scoring for the 'foo' call in "bar" until
170 // after foo has been analyzed, but it's conceivable that CanInline
171 // might visit bar before foo for this SCC.
172 func ScoreCalls(fn *ir.Func) {
173 enableDebugTraceIfEnv()
174 defer disableDebugTrace()
175 if debugTrace&debugTraceScoring != 0 {
176 fmt.Fprintf(os.Stderr, "=-= ScoreCalls(%v)\n", ir.FuncName(fn))
181 // TODO: add an assert/panic here.
185 resultNameTab := make(map[*ir.Name]resultPropAndCS)
187 // Sort callsites to avoid any surprises with non deterministic
188 // map iteration order (this is probably not needed, but here just
190 csl := make([]*CallSite, 0, len(fih.cstab))
191 for _, cs := range fih.cstab {
192 csl = append(csl, cs)
194 sort.Slice(csl, func(i, j int) bool {
195 return csl[i].ID < csl[j].ID
198 // Score each call site.
199 for _, cs := range csl {
200 var cprops *FuncProps
203 if fih, ok := fpmap[cs.Callee]; ok {
206 } else if cs.Callee.Inl != nil {
207 cprops = DeserializeFromString(cs.Callee.Inl.Properties)
210 if base.Debug.DumpInlFuncProps != "" {
211 fmt.Fprintf(os.Stderr, "=-= *** unable to score call to %s from %s\n", cs.Callee.Sym().Name, fmtFullPos(cs.Call.Pos()))
212 panic("should never happen")
217 cs.Score, cs.ScoreMask = computeCallSiteScore(cs.Callee, cprops, cs.Call, cs.Flags)
219 examineCallResults(cs, resultNameTab)
221 if debugTrace&debugTraceScoring != 0 {
222 fmt.Fprintf(os.Stderr, "=-= scoring call at %s: flags=%d score=%d fih=%v deser=%v\n", fmtFullPos(cs.Call.Pos()), cs.Flags, cs.Score, fihcprops, desercprops)
226 rescoreBasedOnCallResultUses(fn, resultNameTab, fih.cstab)
229 func (csa *callSiteAnalyzer) nodeVisitPre(n ir.Node) {
231 case ir.ORANGE, ir.OFOR:
232 if !hasTopLevelLoopBodyReturnOrBreak(loopBody(n)) {
236 ce := n.(*ir.CallExpr)
237 callee := pgo.DirectCallee(ce.X)
238 if callee != nil && callee.Inl != nil {
239 csa.addCallSite(callee, ce)
242 csa.nstack = append(csa.nstack, n)
245 func (csa *callSiteAnalyzer) nodeVisitPost(n ir.Node) {
246 csa.nstack = csa.nstack[:len(csa.nstack)-1]
248 case ir.ORANGE, ir.OFOR:
249 if !hasTopLevelLoopBodyReturnOrBreak(loopBody(n)) {
255 func loopBody(n ir.Node) ir.Nodes {
256 if forst, ok := n.(*ir.ForStmt); ok {
259 if rst, ok := n.(*ir.RangeStmt); ok {
265 // hasTopLevelLoopBodyReturnOrBreak examines the body of a "for" or
266 // "range" loop to try to verify that it is a real loop, as opposed to
267 // a construct that is syntactically loopy but doesn't actually iterate
268 // multiple times, like:
275 // [Remark: the pattern above crops up quite a bit in the source code
276 // for the compiler itself, e.g. the auto-generated rewrite code]
278 // Note that we don't look for GOTO statements here, so it's possible
279 // we'll get the wrong result for a loop with complicated control
281 func hasTopLevelLoopBodyReturnOrBreak(loopBody ir.Nodes) bool {
282 for _, n := range loopBody {
283 if n.Op() == ir.ORETURN || n.Op() == ir.OBREAK {
290 // containingAssignment returns the top-level assignment statement
291 // for a statement level function call "n". Examples:
294 // x, y := bar(z, baz())
297 // Here the top-level assignment statement for the foo() call is the
298 // statement assigning to "x"; the top-level assignment for "bar()"
299 // call is the assignment to x,y. For the baz() and blah() calls,
300 // there is no top level assignment statement.
302 // The unstated goal here is that we want to use the containing
303 // assignment to establish a connection between a given call and the
304 // variables to which its results/returns are being assigned.
306 // Note that for the "bar" command above, the front end sometimes
307 // decomposes this into two assignments, the first one assigning the
308 // call to a pair of auto-temps, then the second one assigning the
309 // auto-temps to the user-visible vars. This helper will return the
310 // second (outer) of these two.
311 func (csa *callSiteAnalyzer) containingAssignment(n ir.Node) ir.Node {
312 parent := csa.nstack[len(csa.nstack)-1]
314 // assignsOnlyAutoTemps returns TRUE of the specified OAS2FUNC
315 // node assigns only auto-temps.
316 assignsOnlyAutoTemps := func(x ir.Node) bool {
317 alst := x.(*ir.AssignListStmt)
318 oa2init := alst.Init()
319 if len(oa2init) == 0 {
322 for _, v := range oa2init {
324 if !ir.IsAutoTmp(d.X) {
331 // Simple case: x := foo()
332 if parent.Op() == ir.OAS {
336 // Multi-return case: x, y := bar()
337 if parent.Op() == ir.OAS2FUNC {
338 // Hack city: if the result vars are auto-temps, try looking
339 // for an outer assignment in the tree. The code shape we're
340 // looking for here is:
342 // OAS1({x,y},OCONVNOP(OAS2FUNC({auto1,auto2},OCALLFUNC(bar))))
344 if assignsOnlyAutoTemps(parent) {
345 par2 := csa.nstack[len(csa.nstack)-2]
346 if par2.Op() == ir.OAS2 {
349 if par2.Op() == ir.OCONVNOP {
350 par3 := csa.nstack[len(csa.nstack)-3]
351 if par3.Op() == ir.OAS2 {