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