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