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