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