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