]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/inline/inl.go
cmd/compile/internal/inline: analyze function result properties
[gostls13.git] / src / cmd / compile / internal / inline / inl.go
1 // Copyright 2011 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 // The inlining facility makes 2 passes: first CanInline determines which
6 // functions are suitable for inlining, and for those that are it
7 // saves a copy of the body. Then InlineCalls walks each function body to
8 // expand calls to inlinable functions.
9 //
10 // The Debug.l flag controls the aggressiveness. Note that main() swaps level 0 and 1,
11 // making 1 the default and -l disable. Additional levels (beyond -l) may be buggy and
12 // are not supported.
13 //      0: disabled
14 //      1: 80-nodes leaf functions, oneliners, panic, lazy typechecking (default)
15 //      2: (unassigned)
16 //      3: (unassigned)
17 //      4: allow non-leaf functions
18 //
19 // At some point this may get another default and become switch-offable with -N.
20 //
21 // The -d typcheckinl flag enables early typechecking of all imported bodies,
22 // which is useful to flush out bugs.
23 //
24 // The Debug.m flag enables diagnostic output.  a single -m is useful for verifying
25 // which calls get inlined or not, more is for debugging, and may go away at any point.
26
27 package inline
28
29 import (
30         "fmt"
31         "go/constant"
32         "sort"
33         "strconv"
34
35         "cmd/compile/internal/base"
36         "cmd/compile/internal/inline/inlheur"
37         "cmd/compile/internal/ir"
38         "cmd/compile/internal/logopt"
39         "cmd/compile/internal/pgo"
40         "cmd/compile/internal/typecheck"
41         "cmd/compile/internal/types"
42         "cmd/internal/obj"
43 )
44
45 // Inlining budget parameters, gathered in one place
46 const (
47         inlineMaxBudget       = 80
48         inlineExtraAppendCost = 0
49         // default is to inline if there's at most one call. -l=4 overrides this by using 1 instead.
50         inlineExtraCallCost  = 57              // 57 was benchmarked to provided most benefit with no bad surprises; see https://github.com/golang/go/issues/19348#issuecomment-439370742
51         inlineExtraPanicCost = 1               // do not penalize inlining panics.
52         inlineExtraThrowCost = inlineMaxBudget // with current (2018-05/1.11) code, inlining runtime.throw does not help.
53
54         inlineBigFunctionNodes   = 5000 // Functions with this many nodes are considered "big".
55         inlineBigFunctionMaxCost = 20   // Max cost of inlinee when inlining into a "big" function.
56 )
57
58 var (
59         // List of all hot callee nodes.
60         // TODO(prattmic): Make this non-global.
61         candHotCalleeMap = make(map[*pgo.IRNode]struct{})
62
63         // List of all hot call sites. CallSiteInfo.Callee is always nil.
64         // TODO(prattmic): Make this non-global.
65         candHotEdgeMap = make(map[pgo.CallSiteInfo]struct{})
66
67         // Threshold in percentage for hot callsite inlining.
68         inlineHotCallSiteThresholdPercent float64
69
70         // Threshold in CDF percentage for hot callsite inlining,
71         // that is, for a threshold of X the hottest callsites that
72         // make up the top X% of total edge weight will be
73         // considered hot for inlining candidates.
74         inlineCDFHotCallSiteThresholdPercent = float64(99)
75
76         // Budget increased due to hotness.
77         inlineHotMaxBudget int32 = 2000
78 )
79
80 // pgoInlinePrologue records the hot callsites from ir-graph.
81 func pgoInlinePrologue(p *pgo.Profile, funcs []*ir.Func) {
82         if base.Debug.PGOInlineCDFThreshold != "" {
83                 if s, err := strconv.ParseFloat(base.Debug.PGOInlineCDFThreshold, 64); err == nil && s >= 0 && s <= 100 {
84                         inlineCDFHotCallSiteThresholdPercent = s
85                 } else {
86                         base.Fatalf("invalid PGOInlineCDFThreshold, must be between 0 and 100")
87                 }
88         }
89         var hotCallsites []pgo.NodeMapKey
90         inlineHotCallSiteThresholdPercent, hotCallsites = hotNodesFromCDF(p)
91         if base.Debug.PGODebug > 0 {
92                 fmt.Printf("hot-callsite-thres-from-CDF=%v\n", inlineHotCallSiteThresholdPercent)
93         }
94
95         if x := base.Debug.PGOInlineBudget; x != 0 {
96                 inlineHotMaxBudget = int32(x)
97         }
98
99         for _, n := range hotCallsites {
100                 // mark inlineable callees from hot edges
101                 if callee := p.WeightedCG.IRNodes[n.CalleeName]; callee != nil {
102                         candHotCalleeMap[callee] = struct{}{}
103                 }
104                 // mark hot call sites
105                 if caller := p.WeightedCG.IRNodes[n.CallerName]; caller != nil && caller.AST != nil {
106                         csi := pgo.CallSiteInfo{LineOffset: n.CallSiteOffset, Caller: caller.AST}
107                         candHotEdgeMap[csi] = struct{}{}
108                 }
109         }
110
111         if base.Debug.PGODebug >= 3 {
112                 fmt.Printf("hot-cg before inline in dot format:")
113                 p.PrintWeightedCallGraphDOT(inlineHotCallSiteThresholdPercent)
114         }
115 }
116
117 // hotNodesFromCDF computes an edge weight threshold and the list of hot
118 // nodes that make up the given percentage of the CDF. The threshold, as
119 // a percent, is the lower bound of weight for nodes to be considered hot
120 // (currently only used in debug prints) (in case of equal weights,
121 // comparing with the threshold may not accurately reflect which nodes are
122 // considiered hot).
123 func hotNodesFromCDF(p *pgo.Profile) (float64, []pgo.NodeMapKey) {
124         nodes := make([]pgo.NodeMapKey, len(p.NodeMap))
125         i := 0
126         for n := range p.NodeMap {
127                 nodes[i] = n
128                 i++
129         }
130         sort.Slice(nodes, func(i, j int) bool {
131                 ni, nj := nodes[i], nodes[j]
132                 if wi, wj := p.NodeMap[ni].EWeight, p.NodeMap[nj].EWeight; wi != wj {
133                         return wi > wj // want larger weight first
134                 }
135                 // same weight, order by name/line number
136                 if ni.CallerName != nj.CallerName {
137                         return ni.CallerName < nj.CallerName
138                 }
139                 if ni.CalleeName != nj.CalleeName {
140                         return ni.CalleeName < nj.CalleeName
141                 }
142                 return ni.CallSiteOffset < nj.CallSiteOffset
143         })
144         cum := int64(0)
145         for i, n := range nodes {
146                 w := p.NodeMap[n].EWeight
147                 cum += w
148                 if pgo.WeightInPercentage(cum, p.TotalEdgeWeight) > inlineCDFHotCallSiteThresholdPercent {
149                         // nodes[:i+1] to include the very last node that makes it to go over the threshold.
150                         // (Say, if the CDF threshold is 50% and one hot node takes 60% of weight, we want to
151                         // include that node instead of excluding it.)
152                         return pgo.WeightInPercentage(w, p.TotalEdgeWeight), nodes[:i+1]
153                 }
154         }
155         return 0, nodes
156 }
157
158 // InlinePackage finds functions that can be inlined and clones them before walk expands them.
159 func InlinePackage(p *pgo.Profile) {
160         if base.Debug.PGOInline == 0 {
161                 p = nil
162         }
163
164         InlineDecls(p, typecheck.Target.Funcs, true)
165
166         // Perform a garbage collection of hidden closures functions that
167         // are no longer reachable from top-level functions following
168         // inlining. See #59404 and #59638 for more context.
169         garbageCollectUnreferencedHiddenClosures()
170
171         if base.Debug.DumpInlFuncProps != "" {
172                 inlheur.DumpFuncProps(nil, base.Debug.DumpInlFuncProps, nil)
173         }
174 }
175
176 // InlineDecls applies inlining to the given batch of declarations.
177 func InlineDecls(p *pgo.Profile, funcs []*ir.Func, doInline bool) {
178         if p != nil {
179                 pgoInlinePrologue(p, funcs)
180         }
181
182         doCanInline := func(n *ir.Func, recursive bool, numfns int) {
183                 if !recursive || numfns > 1 {
184                         // We allow inlining if there is no
185                         // recursion, or the recursion cycle is
186                         // across more than one function.
187                         CanInline(n, p)
188                 } else {
189                         if base.Flag.LowerM > 1 && n.OClosure == nil {
190                                 fmt.Printf("%v: cannot inline %v: recursive\n", ir.Line(n), n.Nname)
191                         }
192                 }
193         }
194
195         ir.VisitFuncsBottomUp(funcs, func(list []*ir.Func, recursive bool) {
196                 numfns := numNonClosures(list)
197                 // We visit functions within an SCC in fairly arbitrary order,
198                 // so by computing inlinability for all functions in the SCC
199                 // before performing any inlining, the results are less
200                 // sensitive to the order within the SCC (see #58905 for an
201                 // example).
202
203                 // First compute inlinability for all functions in the SCC ...
204                 for _, n := range list {
205                         doCanInline(n, recursive, numfns)
206                 }
207                 // ... then make a second pass to do inlining of calls.
208                 if doInline {
209                         for _, n := range list {
210                                 InlineCalls(n, p)
211                         }
212                 }
213         })
214 }
215
216 // garbageCollectUnreferencedHiddenClosures makes a pass over all the
217 // top-level (non-hidden-closure) functions looking for nested closure
218 // functions that are reachable, then sweeps through the Target.Decls
219 // list and marks any non-reachable hidden closure function as dead.
220 // See issues #59404 and #59638 for more context.
221 func garbageCollectUnreferencedHiddenClosures() {
222
223         liveFuncs := make(map[*ir.Func]bool)
224
225         var markLiveFuncs func(fn *ir.Func)
226         markLiveFuncs = func(fn *ir.Func) {
227                 if liveFuncs[fn] {
228                         return
229                 }
230                 liveFuncs[fn] = true
231                 ir.Visit(fn, func(n ir.Node) {
232                         if clo, ok := n.(*ir.ClosureExpr); ok {
233                                 markLiveFuncs(clo.Func)
234                         }
235                 })
236         }
237
238         for i := 0; i < len(typecheck.Target.Funcs); i++ {
239                 fn := typecheck.Target.Funcs[i]
240                 if fn.IsHiddenClosure() {
241                         continue
242                 }
243                 markLiveFuncs(fn)
244         }
245
246         for i := 0; i < len(typecheck.Target.Funcs); i++ {
247                 fn := typecheck.Target.Funcs[i]
248                 if !fn.IsHiddenClosure() {
249                         continue
250                 }
251                 if fn.IsDeadcodeClosure() {
252                         continue
253                 }
254                 if liveFuncs[fn] {
255                         continue
256                 }
257                 fn.SetIsDeadcodeClosure(true)
258                 if base.Flag.LowerM > 2 {
259                         fmt.Printf("%v: unreferenced closure %v marked as dead\n", ir.Line(fn), fn)
260                 }
261                 if fn.Inl != nil && fn.LSym == nil {
262                         ir.InitLSym(fn, true)
263                 }
264         }
265 }
266
267 // inlineBudget determines the max budget for function 'fn' prior to
268 // analyzing the hairyness of the body of 'fn'. We pass in the pgo
269 // profile if available, which can change the budget. If 'verbose' is
270 // set, then print a remark where we boost the budget due to PGO.
271 func inlineBudget(fn *ir.Func, profile *pgo.Profile, verbose bool) int32 {
272         // Update the budget for profile-guided inlining.
273         budget := int32(inlineMaxBudget)
274         if profile != nil {
275                 if n, ok := profile.WeightedCG.IRNodes[ir.LinkFuncName(fn)]; ok {
276                         if _, ok := candHotCalleeMap[n]; ok {
277                                 budget = int32(inlineHotMaxBudget)
278                                 if verbose {
279                                         fmt.Printf("hot-node enabled increased budget=%v for func=%v\n", budget, ir.PkgFuncName(fn))
280                                 }
281                         }
282                 }
283         }
284         return budget
285 }
286
287 // CanInline determines whether fn is inlineable.
288 // If so, CanInline saves copies of fn.Body and fn.Dcl in fn.Inl.
289 // fn and fn.Body will already have been typechecked.
290 func CanInline(fn *ir.Func, profile *pgo.Profile) {
291         if fn.Nname == nil {
292                 base.Fatalf("CanInline no nname %+v", fn)
293         }
294
295         if base.Debug.DumpInlFuncProps != "" {
296                 inlheur.DumpFuncProps(fn, base.Debug.DumpInlFuncProps,
297                         func(fn *ir.Func) {
298                                 CanInline(fn, profile)
299                         })
300         }
301
302         var reason string // reason, if any, that the function was not inlined
303         if base.Flag.LowerM > 1 || logopt.Enabled() {
304                 defer func() {
305                         if reason != "" {
306                                 if base.Flag.LowerM > 1 {
307                                         fmt.Printf("%v: cannot inline %v: %s\n", ir.Line(fn), fn.Nname, reason)
308                                 }
309                                 if logopt.Enabled() {
310                                         logopt.LogOpt(fn.Pos(), "cannotInlineFunction", "inline", ir.FuncName(fn), reason)
311                                 }
312                         }
313                 }()
314         }
315
316         reason = InlineImpossible(fn)
317         if reason != "" {
318                 return
319         }
320         if fn.Typecheck() == 0 {
321                 base.Fatalf("CanInline on non-typechecked function %v", fn)
322         }
323
324         n := fn.Nname
325         if n.Func.InlinabilityChecked() {
326                 return
327         }
328         defer n.Func.SetInlinabilityChecked(true)
329
330         cc := int32(inlineExtraCallCost)
331         if base.Flag.LowerL == 4 {
332                 cc = 1 // this appears to yield better performance than 0.
333         }
334
335         // Compute the inline budget for this function.
336         budget := inlineBudget(fn, profile, base.Debug.PGODebug > 0)
337
338         // At this point in the game the function we're looking at may
339         // have "stale" autos, vars that still appear in the Dcl list, but
340         // which no longer have any uses in the function body (due to
341         // elimination by deadcode). We'd like to exclude these dead vars
342         // when creating the "Inline.Dcl" field below; to accomplish this,
343         // the hairyVisitor below builds up a map of used/referenced
344         // locals, and we use this map to produce a pruned Inline.Dcl
345         // list. See issue 25459 for more context.
346
347         visitor := hairyVisitor{
348                 curFunc:       fn,
349                 budget:        budget,
350                 maxBudget:     budget,
351                 extraCallCost: cc,
352                 profile:       profile,
353         }
354         if visitor.tooHairy(fn) {
355                 reason = visitor.reason
356                 return
357         }
358
359         n.Func.Inl = &ir.Inline{
360                 Cost:    budget - visitor.budget,
361                 Dcl:     pruneUnusedAutos(n.Func.Dcl, &visitor),
362                 HaveDcl: true,
363
364                 CanDelayResults: canDelayResults(fn),
365         }
366
367         if base.Flag.LowerM > 1 {
368                 fmt.Printf("%v: can inline %v with cost %d as: %v { %v }\n", ir.Line(fn), n, budget-visitor.budget, fn.Type(), ir.Nodes(fn.Body))
369         } else if base.Flag.LowerM != 0 {
370                 fmt.Printf("%v: can inline %v\n", ir.Line(fn), n)
371         }
372         if logopt.Enabled() {
373                 logopt.LogOpt(fn.Pos(), "canInlineFunction", "inline", ir.FuncName(fn), fmt.Sprintf("cost: %d", budget-visitor.budget))
374         }
375 }
376
377 // InlineImpossible returns a non-empty reason string if fn is impossible to
378 // inline regardless of cost or contents.
379 func InlineImpossible(fn *ir.Func) string {
380         var reason string // reason, if any, that the function can not be inlined.
381         if fn.Nname == nil {
382                 reason = "no name"
383                 return reason
384         }
385
386         // If marked "go:noinline", don't inline.
387         if fn.Pragma&ir.Noinline != 0 {
388                 reason = "marked go:noinline"
389                 return reason
390         }
391
392         // If marked "go:norace" and -race compilation, don't inline.
393         if base.Flag.Race && fn.Pragma&ir.Norace != 0 {
394                 reason = "marked go:norace with -race compilation"
395                 return reason
396         }
397
398         // If marked "go:nocheckptr" and -d checkptr compilation, don't inline.
399         if base.Debug.Checkptr != 0 && fn.Pragma&ir.NoCheckPtr != 0 {
400                 reason = "marked go:nocheckptr"
401                 return reason
402         }
403
404         // If marked "go:cgo_unsafe_args", don't inline, since the function
405         // makes assumptions about its argument frame layout.
406         if fn.Pragma&ir.CgoUnsafeArgs != 0 {
407                 reason = "marked go:cgo_unsafe_args"
408                 return reason
409         }
410
411         // If marked as "go:uintptrkeepalive", don't inline, since the keep
412         // alive information is lost during inlining.
413         //
414         // TODO(prattmic): This is handled on calls during escape analysis,
415         // which is after inlining. Move prior to inlining so the keep-alive is
416         // maintained after inlining.
417         if fn.Pragma&ir.UintptrKeepAlive != 0 {
418                 reason = "marked as having a keep-alive uintptr argument"
419                 return reason
420         }
421
422         // If marked as "go:uintptrescapes", don't inline, since the escape
423         // information is lost during inlining.
424         if fn.Pragma&ir.UintptrEscapes != 0 {
425                 reason = "marked as having an escaping uintptr argument"
426                 return reason
427         }
428
429         // The nowritebarrierrec checker currently works at function
430         // granularity, so inlining yeswritebarrierrec functions can confuse it
431         // (#22342). As a workaround, disallow inlining them for now.
432         if fn.Pragma&ir.Yeswritebarrierrec != 0 {
433                 reason = "marked go:yeswritebarrierrec"
434                 return reason
435         }
436
437         // If a local function has no fn.Body (is defined outside of Go), cannot inline it.
438         // Imported functions don't have fn.Body but might have inline body in fn.Inl.
439         if len(fn.Body) == 0 && !typecheck.HaveInlineBody(fn) {
440                 reason = "no function body"
441                 return reason
442         }
443
444         return ""
445 }
446
447 // canDelayResults reports whether inlined calls to fn can delay
448 // declaring the result parameter until the "return" statement.
449 func canDelayResults(fn *ir.Func) bool {
450         // We can delay declaring+initializing result parameters if:
451         // (1) there's exactly one "return" statement in the inlined function;
452         // (2) it's not an empty return statement (#44355); and
453         // (3) the result parameters aren't named.
454
455         nreturns := 0
456         ir.VisitList(fn.Body, func(n ir.Node) {
457                 if n, ok := n.(*ir.ReturnStmt); ok {
458                         nreturns++
459                         if len(n.Results) == 0 {
460                                 nreturns++ // empty return statement (case 2)
461                         }
462                 }
463         })
464
465         if nreturns != 1 {
466                 return false // not exactly one return statement (case 1)
467         }
468
469         // temporaries for return values.
470         for _, param := range fn.Type().Results() {
471                 if sym := types.OrigSym(param.Sym); sym != nil && !sym.IsBlank() {
472                         return false // found a named result parameter (case 3)
473                 }
474         }
475
476         return true
477 }
478
479 // hairyVisitor visits a function body to determine its inlining
480 // hairiness and whether or not it can be inlined.
481 type hairyVisitor struct {
482         // This is needed to access the current caller in the doNode function.
483         curFunc       *ir.Func
484         budget        int32
485         maxBudget     int32
486         reason        string
487         extraCallCost int32
488         usedLocals    ir.NameSet
489         do            func(ir.Node) bool
490         profile       *pgo.Profile
491 }
492
493 func (v *hairyVisitor) tooHairy(fn *ir.Func) bool {
494         v.do = v.doNode // cache closure
495         if ir.DoChildren(fn, v.do) {
496                 return true
497         }
498         if v.budget < 0 {
499                 v.reason = fmt.Sprintf("function too complex: cost %d exceeds budget %d", v.maxBudget-v.budget, v.maxBudget)
500                 return true
501         }
502         return false
503 }
504
505 // doNode visits n and its children, updates the state in v, and returns true if
506 // n makes the current function too hairy for inlining.
507 func (v *hairyVisitor) doNode(n ir.Node) bool {
508         if n == nil {
509                 return false
510         }
511 opSwitch:
512         switch n.Op() {
513         // Call is okay if inlinable and we have the budget for the body.
514         case ir.OCALLFUNC:
515                 n := n.(*ir.CallExpr)
516                 // Functions that call runtime.getcaller{pc,sp} can not be inlined
517                 // because getcaller{pc,sp} expect a pointer to the caller's first argument.
518                 //
519                 // runtime.throw is a "cheap call" like panic in normal code.
520                 var cheap bool
521                 if n.X.Op() == ir.ONAME {
522                         name := n.X.(*ir.Name)
523                         if name.Class == ir.PFUNC {
524                                 switch fn := types.RuntimeSymName(name.Sym()); fn {
525                                 case "getcallerpc", "getcallersp":
526                                         v.reason = "call to " + fn
527                                         return true
528                                 case "throw":
529                                         v.budget -= inlineExtraThrowCost
530                                         break opSwitch
531                                 }
532                                 // Special case for reflect.noescape. It does just type
533                                 // conversions to appease the escape analysis, and doesn't
534                                 // generate code.
535                                 if types.ReflectSymName(name.Sym()) == "noescape" {
536                                         cheap = true
537                                 }
538                         }
539                         // Special case for coverage counter updates; although
540                         // these correspond to real operations, we treat them as
541                         // zero cost for the moment. This is due to the existence
542                         // of tests that are sensitive to inlining-- if the
543                         // insertion of coverage instrumentation happens to tip a
544                         // given function over the threshold and move it from
545                         // "inlinable" to "not-inlinable", this can cause changes
546                         // in allocation behavior, which can then result in test
547                         // failures (a good example is the TestAllocations in
548                         // crypto/ed25519).
549                         if isAtomicCoverageCounterUpdate(n) {
550                                 return false
551                         }
552                 }
553                 if n.X.Op() == ir.OMETHEXPR {
554                         if meth := ir.MethodExprName(n.X); meth != nil {
555                                 if fn := meth.Func; fn != nil {
556                                         s := fn.Sym()
557                                         if types.RuntimeSymName(s) == "heapBits.nextArena" {
558                                                 // Special case: explicitly allow mid-stack inlining of
559                                                 // runtime.heapBits.next even though it calls slow-path
560                                                 // runtime.heapBits.nextArena.
561                                                 cheap = true
562                                         }
563                                         // Special case: on architectures that can do unaligned loads,
564                                         // explicitly mark encoding/binary methods as cheap,
565                                         // because in practice they are, even though our inlining
566                                         // budgeting system does not see that. See issue 42958.
567                                         if base.Ctxt.Arch.CanMergeLoads && s.Pkg.Path == "encoding/binary" {
568                                                 switch s.Name {
569                                                 case "littleEndian.Uint64", "littleEndian.Uint32", "littleEndian.Uint16",
570                                                         "bigEndian.Uint64", "bigEndian.Uint32", "bigEndian.Uint16",
571                                                         "littleEndian.PutUint64", "littleEndian.PutUint32", "littleEndian.PutUint16",
572                                                         "bigEndian.PutUint64", "bigEndian.PutUint32", "bigEndian.PutUint16",
573                                                         "littleEndian.AppendUint64", "littleEndian.AppendUint32", "littleEndian.AppendUint16",
574                                                         "bigEndian.AppendUint64", "bigEndian.AppendUint32", "bigEndian.AppendUint16":
575                                                         cheap = true
576                                                 }
577                                         }
578                                 }
579                         }
580                 }
581                 if cheap {
582                         break // treat like any other node, that is, cost of 1
583                 }
584
585                 // Determine if the callee edge is for an inlinable hot callee or not.
586                 if v.profile != nil && v.curFunc != nil {
587                         if fn := inlCallee(v.curFunc, n.X, v.profile); fn != nil && typecheck.HaveInlineBody(fn) {
588                                 lineOffset := pgo.NodeLineOffset(n, fn)
589                                 csi := pgo.CallSiteInfo{LineOffset: lineOffset, Caller: v.curFunc}
590                                 if _, o := candHotEdgeMap[csi]; o {
591                                         if base.Debug.PGODebug > 0 {
592                                                 fmt.Printf("hot-callsite identified at line=%v for func=%v\n", ir.Line(n), ir.PkgFuncName(v.curFunc))
593                                         }
594                                 }
595                         }
596                 }
597
598                 if ir.IsIntrinsicCall(n) {
599                         // Treat like any other node.
600                         break
601                 }
602
603                 if fn := inlCallee(v.curFunc, n.X, v.profile); fn != nil && typecheck.HaveInlineBody(fn) {
604                         v.budget -= fn.Inl.Cost
605                         break
606                 }
607
608                 // Call cost for non-leaf inlining.
609                 v.budget -= v.extraCallCost
610
611         case ir.OCALLMETH:
612                 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
613
614         // Things that are too hairy, irrespective of the budget
615         case ir.OCALL, ir.OCALLINTER:
616                 // Call cost for non-leaf inlining.
617                 v.budget -= v.extraCallCost
618
619         case ir.OPANIC:
620                 n := n.(*ir.UnaryExpr)
621                 if n.X.Op() == ir.OCONVIFACE && n.X.(*ir.ConvExpr).Implicit() {
622                         // Hack to keep reflect.flag.mustBe inlinable for TestIntendedInlining.
623                         // Before CL 284412, these conversions were introduced later in the
624                         // compiler, so they didn't count against inlining budget.
625                         v.budget++
626                 }
627                 v.budget -= inlineExtraPanicCost
628
629         case ir.ORECOVER:
630                 base.FatalfAt(n.Pos(), "ORECOVER missed typecheck")
631         case ir.ORECOVERFP:
632                 // recover matches the argument frame pointer to find
633                 // the right panic value, so it needs an argument frame.
634                 v.reason = "call to recover"
635                 return true
636
637         case ir.OCLOSURE:
638                 if base.Debug.InlFuncsWithClosures == 0 {
639                         v.reason = "not inlining functions with closures"
640                         return true
641                 }
642
643                 // TODO(danscales): Maybe make budget proportional to number of closure
644                 // variables, e.g.:
645                 //v.budget -= int32(len(n.(*ir.ClosureExpr).Func.ClosureVars) * 3)
646                 // TODO(austin): However, if we're able to inline this closure into
647                 // v.curFunc, then we actually pay nothing for the closure captures. We
648                 // should try to account for that if we're going to account for captures.
649                 v.budget -= 15
650
651         case ir.OGO, ir.ODEFER, ir.OTAILCALL:
652                 v.reason = "unhandled op " + n.Op().String()
653                 return true
654
655         case ir.OAPPEND:
656                 v.budget -= inlineExtraAppendCost
657
658         case ir.OADDR:
659                 n := n.(*ir.AddrExpr)
660                 // Make "&s.f" cost 0 when f's offset is zero.
661                 if dot, ok := n.X.(*ir.SelectorExpr); ok && (dot.Op() == ir.ODOT || dot.Op() == ir.ODOTPTR) {
662                         if _, ok := dot.X.(*ir.Name); ok && dot.Selection.Offset == 0 {
663                                 v.budget += 2 // undo ir.OADDR+ir.ODOT/ir.ODOTPTR
664                         }
665                 }
666
667         case ir.ODEREF:
668                 // *(*X)(unsafe.Pointer(&x)) is low-cost
669                 n := n.(*ir.StarExpr)
670
671                 ptr := n.X
672                 for ptr.Op() == ir.OCONVNOP {
673                         ptr = ptr.(*ir.ConvExpr).X
674                 }
675                 if ptr.Op() == ir.OADDR {
676                         v.budget += 1 // undo half of default cost of ir.ODEREF+ir.OADDR
677                 }
678
679         case ir.OCONVNOP:
680                 // This doesn't produce code, but the children might.
681                 v.budget++ // undo default cost
682
683         case ir.OFALL, ir.OTYPE:
684                 // These nodes don't produce code; omit from inlining budget.
685                 return false
686
687         case ir.OIF:
688                 n := n.(*ir.IfStmt)
689                 if ir.IsConst(n.Cond, constant.Bool) {
690                         // This if and the condition cost nothing.
691                         if doList(n.Init(), v.do) {
692                                 return true
693                         }
694                         if ir.BoolVal(n.Cond) {
695                                 return doList(n.Body, v.do)
696                         } else {
697                                 return doList(n.Else, v.do)
698                         }
699                 }
700
701         case ir.ONAME:
702                 n := n.(*ir.Name)
703                 if n.Class == ir.PAUTO {
704                         v.usedLocals.Add(n)
705                 }
706
707         case ir.OBLOCK:
708                 // The only OBLOCK we should see at this point is an empty one.
709                 // In any event, let the visitList(n.List()) below take care of the statements,
710                 // and don't charge for the OBLOCK itself. The ++ undoes the -- below.
711                 v.budget++
712
713         case ir.OMETHVALUE, ir.OSLICELIT:
714                 v.budget-- // Hack for toolstash -cmp.
715
716         case ir.OMETHEXPR:
717                 v.budget++ // Hack for toolstash -cmp.
718
719         case ir.OAS2:
720                 n := n.(*ir.AssignListStmt)
721
722                 // Unified IR unconditionally rewrites:
723                 //
724                 //      a, b = f()
725                 //
726                 // into:
727                 //
728                 //      DCL tmp1
729                 //      DCL tmp2
730                 //      tmp1, tmp2 = f()
731                 //      a, b = tmp1, tmp2
732                 //
733                 // so that it can insert implicit conversions as necessary. To
734                 // minimize impact to the existing inlining heuristics (in
735                 // particular, to avoid breaking the existing inlinability regress
736                 // tests), we need to compensate for this here.
737                 //
738                 // See also identical logic in isBigFunc.
739                 if init := n.Rhs[0].Init(); len(init) == 1 {
740                         if _, ok := init[0].(*ir.AssignListStmt); ok {
741                                 // 4 for each value, because each temporary variable now
742                                 // appears 3 times (DCL, LHS, RHS), plus an extra DCL node.
743                                 //
744                                 // 1 for the extra "tmp1, tmp2 = f()" assignment statement.
745                                 v.budget += 4*int32(len(n.Lhs)) + 1
746                         }
747                 }
748
749         case ir.OAS:
750                 // Special case for coverage counter updates and coverage
751                 // function registrations. Although these correspond to real
752                 // operations, we treat them as zero cost for the moment. This
753                 // is primarily due to the existence of tests that are
754                 // sensitive to inlining-- if the insertion of coverage
755                 // instrumentation happens to tip a given function over the
756                 // threshold and move it from "inlinable" to "not-inlinable",
757                 // this can cause changes in allocation behavior, which can
758                 // then result in test failures (a good example is the
759                 // TestAllocations in crypto/ed25519).
760                 n := n.(*ir.AssignStmt)
761                 if n.X.Op() == ir.OINDEX && isIndexingCoverageCounter(n.X) {
762                         return false
763                 }
764         }
765
766         v.budget--
767
768         // When debugging, don't stop early, to get full cost of inlining this function
769         if v.budget < 0 && base.Flag.LowerM < 2 && !logopt.Enabled() {
770                 v.reason = "too expensive"
771                 return true
772         }
773
774         return ir.DoChildren(n, v.do)
775 }
776
777 func isBigFunc(fn *ir.Func) bool {
778         budget := inlineBigFunctionNodes
779         return ir.Any(fn, func(n ir.Node) bool {
780                 // See logic in hairyVisitor.doNode, explaining unified IR's
781                 // handling of "a, b = f()" assignments.
782                 if n, ok := n.(*ir.AssignListStmt); ok && n.Op() == ir.OAS2 {
783                         if init := n.Rhs[0].Init(); len(init) == 1 {
784                                 if _, ok := init[0].(*ir.AssignListStmt); ok {
785                                         budget += 4*len(n.Lhs) + 1
786                                 }
787                         }
788                 }
789
790                 budget--
791                 return budget <= 0
792         })
793 }
794
795 // InlineCalls/inlnode walks fn's statements and expressions and substitutes any
796 // calls made to inlineable functions. This is the external entry point.
797 func InlineCalls(fn *ir.Func, profile *pgo.Profile) {
798         savefn := ir.CurFunc
799         ir.CurFunc = fn
800         bigCaller := isBigFunc(fn)
801         if bigCaller && base.Flag.LowerM > 1 {
802                 fmt.Printf("%v: function %v considered 'big'; reducing max cost of inlinees\n", ir.Line(fn), fn)
803         }
804         var inlCalls []*ir.InlinedCallExpr
805         var edit func(ir.Node) ir.Node
806         edit = func(n ir.Node) ir.Node {
807                 return inlnode(fn, n, bigCaller, &inlCalls, edit, profile)
808         }
809         ir.EditChildren(fn, edit)
810
811         // If we inlined any calls, we want to recursively visit their
812         // bodies for further inlining. However, we need to wait until
813         // *after* the original function body has been expanded, or else
814         // inlCallee can have false positives (e.g., #54632).
815         for len(inlCalls) > 0 {
816                 call := inlCalls[0]
817                 inlCalls = inlCalls[1:]
818                 ir.EditChildren(call, edit)
819         }
820
821         ir.CurFunc = savefn
822 }
823
824 // inlnode recurses over the tree to find inlineable calls, which will
825 // be turned into OINLCALLs by mkinlcall. When the recursion comes
826 // back up will examine left, right, list, rlist, ninit, ntest, nincr,
827 // nbody and nelse and use one of the 4 inlconv/glue functions above
828 // to turn the OINLCALL into an expression, a statement, or patch it
829 // in to this nodes list or rlist as appropriate.
830 // NOTE it makes no sense to pass the glue functions down the
831 // recursion to the level where the OINLCALL gets created because they
832 // have to edit /this/ n, so you'd have to push that one down as well,
833 // but then you may as well do it here.  so this is cleaner and
834 // shorter and less complicated.
835 // The result of inlnode MUST be assigned back to n, e.g.
836 //
837 //      n.Left = inlnode(n.Left)
838 func inlnode(callerfn *ir.Func, n ir.Node, bigCaller bool, inlCalls *[]*ir.InlinedCallExpr, edit func(ir.Node) ir.Node, profile *pgo.Profile) ir.Node {
839         if n == nil {
840                 return n
841         }
842
843         switch n.Op() {
844         case ir.ODEFER, ir.OGO:
845                 n := n.(*ir.GoDeferStmt)
846                 switch call := n.Call; call.Op() {
847                 case ir.OCALLMETH:
848                         base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
849                 case ir.OCALLFUNC:
850                         call := call.(*ir.CallExpr)
851                         call.NoInline = true
852                 }
853         case ir.OTAILCALL:
854                 n := n.(*ir.TailCallStmt)
855                 n.Call.NoInline = true // Not inline a tail call for now. Maybe we could inline it just like RETURN fn(arg)?
856
857         // TODO do them here (or earlier),
858         // so escape analysis can avoid more heapmoves.
859         case ir.OCLOSURE:
860                 return n
861         case ir.OCALLMETH:
862                 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
863         case ir.OCALLFUNC:
864                 n := n.(*ir.CallExpr)
865                 if n.X.Op() == ir.OMETHEXPR {
866                         // Prevent inlining some reflect.Value methods when using checkptr,
867                         // even when package reflect was compiled without it (#35073).
868                         if meth := ir.MethodExprName(n.X); meth != nil {
869                                 s := meth.Sym()
870                                 if base.Debug.Checkptr != 0 {
871                                         switch types.ReflectSymName(s) {
872                                         case "Value.UnsafeAddr", "Value.Pointer":
873                                                 return n
874                                         }
875                                 }
876                         }
877                 }
878         }
879
880         lno := ir.SetPos(n)
881
882         ir.EditChildren(n, edit)
883
884         // with all the branches out of the way, it is now time to
885         // transmogrify this node itself unless inhibited by the
886         // switch at the top of this function.
887         switch n.Op() {
888         case ir.OCALLMETH:
889                 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
890
891         case ir.OCALLFUNC:
892                 call := n.(*ir.CallExpr)
893                 if call.NoInline {
894                         break
895                 }
896                 if base.Flag.LowerM > 3 {
897                         fmt.Printf("%v:call to func %+v\n", ir.Line(n), call.X)
898                 }
899                 if ir.IsIntrinsicCall(call) {
900                         break
901                 }
902                 if fn := inlCallee(callerfn, call.X, profile); fn != nil && typecheck.HaveInlineBody(fn) {
903                         n = mkinlcall(callerfn, call, fn, bigCaller, inlCalls)
904                 }
905         }
906
907         base.Pos = lno
908
909         return n
910 }
911
912 // inlCallee takes a function-typed expression and returns the underlying function ONAME
913 // that it refers to if statically known. Otherwise, it returns nil.
914 func inlCallee(caller *ir.Func, fn ir.Node, profile *pgo.Profile) (res *ir.Func) {
915         fn = ir.StaticValue(fn)
916         switch fn.Op() {
917         case ir.OMETHEXPR:
918                 fn := fn.(*ir.SelectorExpr)
919                 n := ir.MethodExprName(fn)
920                 // Check that receiver type matches fn.X.
921                 // TODO(mdempsky): Handle implicit dereference
922                 // of pointer receiver argument?
923                 if n == nil || !types.Identical(n.Type().Recv().Type, fn.X.Type()) {
924                         return nil
925                 }
926                 return n.Func
927         case ir.ONAME:
928                 fn := fn.(*ir.Name)
929                 if fn.Class == ir.PFUNC {
930                         return fn.Func
931                 }
932         case ir.OCLOSURE:
933                 fn := fn.(*ir.ClosureExpr)
934                 c := fn.Func
935                 if len(c.ClosureVars) != 0 && c.ClosureVars[0].Outer.Curfn != caller {
936                         return nil // inliner doesn't support inlining across closure frames
937                 }
938                 CanInline(c, profile)
939                 return c
940         }
941         return nil
942 }
943
944 var inlgen int
945
946 // SSADumpInline gives the SSA back end a chance to dump the function
947 // when producing output for debugging the compiler itself.
948 var SSADumpInline = func(*ir.Func) {}
949
950 // InlineCall allows the inliner implementation to be overridden.
951 // If it returns nil, the function will not be inlined.
952 var InlineCall = func(callerfn *ir.Func, call *ir.CallExpr, fn *ir.Func, inlIndex int) *ir.InlinedCallExpr {
953         base.Fatalf("inline.InlineCall not overridden")
954         panic("unreachable")
955 }
956
957 // inlineCostOK returns true if call n from caller to callee is cheap enough to
958 // inline. bigCaller indicates that caller is a big function.
959 //
960 // If inlineCostOK returns false, it also returns the max cost that the callee
961 // exceeded.
962 func inlineCostOK(n *ir.CallExpr, caller, callee *ir.Func, bigCaller bool) (bool, int32) {
963         maxCost := int32(inlineMaxBudget)
964         if bigCaller {
965                 // We use this to restrict inlining into very big functions.
966                 // See issue 26546 and 17566.
967                 maxCost = inlineBigFunctionMaxCost
968         }
969
970         if callee.Inl.Cost <= maxCost {
971                 // Simple case. Function is already cheap enough.
972                 return true, 0
973         }
974
975         // We'll also allow inlining of hot functions below inlineHotMaxBudget,
976         // but only in small functions.
977
978         lineOffset := pgo.NodeLineOffset(n, caller)
979         csi := pgo.CallSiteInfo{LineOffset: lineOffset, Caller: caller}
980         if _, ok := candHotEdgeMap[csi]; !ok {
981                 // Cold
982                 return false, maxCost
983         }
984
985         // Hot
986
987         if bigCaller {
988                 if base.Debug.PGODebug > 0 {
989                         fmt.Printf("hot-big check disallows inlining for call %s (cost %d) at %v in big function %s\n", ir.PkgFuncName(callee), callee.Inl.Cost, ir.Line(n), ir.PkgFuncName(caller))
990                 }
991                 return false, maxCost
992         }
993
994         if callee.Inl.Cost > inlineHotMaxBudget {
995                 return false, inlineHotMaxBudget
996         }
997
998         if base.Debug.PGODebug > 0 {
999                 fmt.Printf("hot-budget check allows inlining for call %s (cost %d) at %v in function %s\n", ir.PkgFuncName(callee), callee.Inl.Cost, ir.Line(n), ir.PkgFuncName(caller))
1000         }
1001
1002         return true, 0
1003 }
1004
1005 // If n is a OCALLFUNC node, and fn is an ONAME node for a
1006 // function with an inlinable body, return an OINLCALL node that can replace n.
1007 // The returned node's Ninit has the parameter assignments, the Nbody is the
1008 // inlined function body, and (List, Rlist) contain the (input, output)
1009 // parameters.
1010 // The result of mkinlcall MUST be assigned back to n, e.g.
1011 //
1012 //      n.Left = mkinlcall(n.Left, fn, isddd)
1013 func mkinlcall(callerfn *ir.Func, n *ir.CallExpr, fn *ir.Func, bigCaller bool, inlCalls *[]*ir.InlinedCallExpr) ir.Node {
1014         if fn.Inl == nil {
1015                 if logopt.Enabled() {
1016                         logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
1017                                 fmt.Sprintf("%s cannot be inlined", ir.PkgFuncName(fn)))
1018                 }
1019                 return n
1020         }
1021
1022         if ok, maxCost := inlineCostOK(n, callerfn, fn, bigCaller); !ok {
1023                 if logopt.Enabled() {
1024                         logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
1025                                 fmt.Sprintf("cost %d of %s exceeds max caller cost %d", fn.Inl.Cost, ir.PkgFuncName(fn), maxCost))
1026                 }
1027                 return n
1028         }
1029
1030         if fn == callerfn {
1031                 // Can't recursively inline a function into itself.
1032                 if logopt.Enabled() {
1033                         logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", fmt.Sprintf("recursive call to %s", ir.FuncName(callerfn)))
1034                 }
1035                 return n
1036         }
1037
1038         if base.Flag.Cfg.Instrumenting && types.IsNoInstrumentPkg(fn.Sym().Pkg) {
1039                 // Runtime package must not be instrumented.
1040                 // Instrument skips runtime package. However, some runtime code can be
1041                 // inlined into other packages and instrumented there. To avoid this,
1042                 // we disable inlining of runtime functions when instrumenting.
1043                 // The example that we observed is inlining of LockOSThread,
1044                 // which lead to false race reports on m contents.
1045                 return n
1046         }
1047         if base.Flag.Race && types.IsNoRacePkg(fn.Sym().Pkg) {
1048                 return n
1049         }
1050
1051         parent := base.Ctxt.PosTable.Pos(n.Pos()).Base().InliningIndex()
1052         sym := fn.Linksym()
1053
1054         // Check if we've already inlined this function at this particular
1055         // call site, in order to stop inlining when we reach the beginning
1056         // of a recursion cycle again. We don't inline immediately recursive
1057         // functions, but allow inlining if there is a recursion cycle of
1058         // many functions. Most likely, the inlining will stop before we
1059         // even hit the beginning of the cycle again, but this catches the
1060         // unusual case.
1061         for inlIndex := parent; inlIndex >= 0; inlIndex = base.Ctxt.InlTree.Parent(inlIndex) {
1062                 if base.Ctxt.InlTree.InlinedFunction(inlIndex) == sym {
1063                         if base.Flag.LowerM > 1 {
1064                                 fmt.Printf("%v: cannot inline %v into %v: repeated recursive cycle\n", ir.Line(n), fn, ir.FuncName(callerfn))
1065                         }
1066                         return n
1067                 }
1068         }
1069
1070         typecheck.AssertFixedCall(n)
1071
1072         inlIndex := base.Ctxt.InlTree.Add(parent, n.Pos(), sym, ir.FuncName(fn))
1073
1074         closureInitLSym := func(n *ir.CallExpr, fn *ir.Func) {
1075                 // The linker needs FuncInfo metadata for all inlined
1076                 // functions. This is typically handled by gc.enqueueFunc
1077                 // calling ir.InitLSym for all function declarations in
1078                 // typecheck.Target.Decls (ir.UseClosure adds all closures to
1079                 // Decls).
1080                 //
1081                 // However, non-trivial closures in Decls are ignored, and are
1082                 // insteaded enqueued when walk of the calling function
1083                 // discovers them.
1084                 //
1085                 // This presents a problem for direct calls to closures.
1086                 // Inlining will replace the entire closure definition with its
1087                 // body, which hides the closure from walk and thus suppresses
1088                 // symbol creation.
1089                 //
1090                 // Explicitly create a symbol early in this edge case to ensure
1091                 // we keep this metadata.
1092                 //
1093                 // TODO: Refactor to keep a reference so this can all be done
1094                 // by enqueueFunc.
1095
1096                 if n.Op() != ir.OCALLFUNC {
1097                         // Not a standard call.
1098                         return
1099                 }
1100                 if n.X.Op() != ir.OCLOSURE {
1101                         // Not a direct closure call.
1102                         return
1103                 }
1104
1105                 clo := n.X.(*ir.ClosureExpr)
1106                 if ir.IsTrivialClosure(clo) {
1107                         // enqueueFunc will handle trivial closures anyways.
1108                         return
1109                 }
1110
1111                 ir.InitLSym(fn, true)
1112         }
1113
1114         closureInitLSym(n, fn)
1115
1116         if base.Flag.GenDwarfInl > 0 {
1117                 if !sym.WasInlined() {
1118                         base.Ctxt.DwFixups.SetPrecursorFunc(sym, fn)
1119                         sym.Set(obj.AttrWasInlined, true)
1120                 }
1121         }
1122
1123         if base.Flag.LowerM != 0 {
1124                 fmt.Printf("%v: inlining call to %v\n", ir.Line(n), fn)
1125         }
1126         if base.Flag.LowerM > 2 {
1127                 fmt.Printf("%v: Before inlining: %+v\n", ir.Line(n), n)
1128         }
1129
1130         res := InlineCall(callerfn, n, fn, inlIndex)
1131
1132         if res == nil {
1133                 base.FatalfAt(n.Pos(), "inlining call to %v failed", fn)
1134         }
1135
1136         if base.Flag.LowerM > 2 {
1137                 fmt.Printf("%v: After inlining %+v\n\n", ir.Line(res), res)
1138         }
1139
1140         *inlCalls = append(*inlCalls, res)
1141
1142         return res
1143 }
1144
1145 // CalleeEffects appends any side effects from evaluating callee to init.
1146 func CalleeEffects(init *ir.Nodes, callee ir.Node) {
1147         for {
1148                 init.Append(ir.TakeInit(callee)...)
1149
1150                 switch callee.Op() {
1151                 case ir.ONAME, ir.OCLOSURE, ir.OMETHEXPR:
1152                         return // done
1153
1154                 case ir.OCONVNOP:
1155                         conv := callee.(*ir.ConvExpr)
1156                         callee = conv.X
1157
1158                 case ir.OINLCALL:
1159                         ic := callee.(*ir.InlinedCallExpr)
1160                         init.Append(ic.Body.Take()...)
1161                         callee = ic.SingleResult()
1162
1163                 default:
1164                         base.FatalfAt(callee.Pos(), "unexpected callee expression: %v", callee)
1165                 }
1166         }
1167 }
1168
1169 func pruneUnusedAutos(ll []*ir.Name, vis *hairyVisitor) []*ir.Name {
1170         s := make([]*ir.Name, 0, len(ll))
1171         for _, n := range ll {
1172                 if n.Class == ir.PAUTO {
1173                         if !vis.usedLocals.Has(n) {
1174                                 // TODO(mdempsky): Simplify code after confident that this
1175                                 // never happens anymore.
1176                                 base.FatalfAt(n.Pos(), "unused auto: %v", n)
1177                                 continue
1178                         }
1179                 }
1180                 s = append(s, n)
1181         }
1182         return s
1183 }
1184
1185 // numNonClosures returns the number of functions in list which are not closures.
1186 func numNonClosures(list []*ir.Func) int {
1187         count := 0
1188         for _, fn := range list {
1189                 if fn.OClosure == nil {
1190                         count++
1191                 }
1192         }
1193         return count
1194 }
1195
1196 func doList(list []ir.Node, do func(ir.Node) bool) bool {
1197         for _, x := range list {
1198                 if x != nil {
1199                         if do(x) {
1200                                 return true
1201                         }
1202                 }
1203         }
1204         return false
1205 }
1206
1207 // isIndexingCoverageCounter returns true if the specified node 'n' is indexing
1208 // into a coverage counter array.
1209 func isIndexingCoverageCounter(n ir.Node) bool {
1210         if n.Op() != ir.OINDEX {
1211                 return false
1212         }
1213         ixn := n.(*ir.IndexExpr)
1214         if ixn.X.Op() != ir.ONAME || !ixn.X.Type().IsArray() {
1215                 return false
1216         }
1217         nn := ixn.X.(*ir.Name)
1218         return nn.CoverageCounter()
1219 }
1220
1221 // isAtomicCoverageCounterUpdate examines the specified node to
1222 // determine whether it represents a call to sync/atomic.AddUint32 to
1223 // increment a coverage counter.
1224 func isAtomicCoverageCounterUpdate(cn *ir.CallExpr) bool {
1225         if cn.X.Op() != ir.ONAME {
1226                 return false
1227         }
1228         name := cn.X.(*ir.Name)
1229         if name.Class != ir.PFUNC {
1230                 return false
1231         }
1232         fn := name.Sym().Name
1233         if name.Sym().Pkg.Path != "sync/atomic" ||
1234                 (fn != "AddUint32" && fn != "StoreUint32") {
1235                 return false
1236         }
1237         if len(cn.Args) != 2 || cn.Args[0].Op() != ir.OADDR {
1238                 return false
1239         }
1240         adn := cn.Args[0].(*ir.AddrExpr)
1241         v := isIndexingCoverageCounter(adn.X)
1242         return v
1243 }