]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/inline/inl.go
50f06f270eebdfd242b38aa3f616682f64a33692
[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         "strconv"
34
35         "cmd/compile/internal/base"
36         "cmd/compile/internal/inline/inlheur"
37         "cmd/compile/internal/ir"
38         "cmd/compile/internal/logopt"
39         "cmd/compile/internal/pgo"
40         "cmd/compile/internal/typecheck"
41         "cmd/compile/internal/types"
42         "cmd/internal/obj"
43 )
44
45 // Inlining budget parameters, gathered in one place
46 const (
47         inlineMaxBudget       = 80
48         inlineExtraAppendCost = 0
49         // default is to inline if there's at most one call. -l=4 overrides this by using 1 instead.
50         inlineExtraCallCost  = 57              // 57 was benchmarked to provided most benefit with no bad surprises; see https://github.com/golang/go/issues/19348#issuecomment-439370742
51         inlineExtraPanicCost = 1               // do not penalize inlining panics.
52         inlineExtraThrowCost = inlineMaxBudget // with current (2018-05/1.11) code, inlining runtime.throw does not help.
53
54         inlineBigFunctionNodes   = 5000 // Functions with this many nodes are considered "big".
55         inlineBigFunctionMaxCost = 20   // Max cost of inlinee when inlining into a "big" function.
56 )
57
58 var (
59         // List of all hot callee nodes.
60         // TODO(prattmic): Make this non-global.
61         candHotCalleeMap = make(map[*pgo.IRNode]struct{})
62
63         // List of all hot call sites. CallSiteInfo.Callee is always nil.
64         // TODO(prattmic): Make this non-global.
65         candHotEdgeMap = make(map[pgo.CallSiteInfo]struct{})
66
67         // Threshold in percentage for hot callsite inlining.
68         inlineHotCallSiteThresholdPercent float64
69
70         // Threshold in CDF percentage for hot callsite inlining,
71         // that is, for a threshold of X the hottest callsites that
72         // make up the top X% of total edge weight will be
73         // considered hot for inlining candidates.
74         inlineCDFHotCallSiteThresholdPercent = float64(99)
75
76         // Budget increased due to hotness.
77         inlineHotMaxBudget int32 = 2000
78 )
79
80 // pgoInlinePrologue records the hot callsites from ir-graph.
81 func pgoInlinePrologue(p *pgo.Profile, funcs []*ir.Func) {
82         if base.Debug.PGOInlineCDFThreshold != "" {
83                 if s, err := strconv.ParseFloat(base.Debug.PGOInlineCDFThreshold, 64); err == nil && s >= 0 && s <= 100 {
84                         inlineCDFHotCallSiteThresholdPercent = s
85                 } else {
86                         base.Fatalf("invalid PGOInlineCDFThreshold, must be between 0 and 100")
87                 }
88         }
89         var hotCallsites []pgo.NamedCallEdge
90         inlineHotCallSiteThresholdPercent, hotCallsites = hotNodesFromCDF(p)
91         if base.Debug.PGODebug > 0 {
92                 fmt.Printf("hot-callsite-thres-from-CDF=%v\n", inlineHotCallSiteThresholdPercent)
93         }
94
95         if x := base.Debug.PGOInlineBudget; x != 0 {
96                 inlineHotMaxBudget = int32(x)
97         }
98
99         for _, n := range hotCallsites {
100                 // mark inlineable callees from hot edges
101                 if callee := p.WeightedCG.IRNodes[n.CalleeName]; callee != nil {
102                         candHotCalleeMap[callee] = struct{}{}
103                 }
104                 // mark hot call sites
105                 if caller := p.WeightedCG.IRNodes[n.CallerName]; caller != nil && caller.AST != nil {
106                         csi := pgo.CallSiteInfo{LineOffset: n.CallSiteOffset, Caller: caller.AST}
107                         candHotEdgeMap[csi] = struct{}{}
108                 }
109         }
110
111         if base.Debug.PGODebug >= 3 {
112                 fmt.Printf("hot-cg before inline in dot format:")
113                 p.PrintWeightedCallGraphDOT(inlineHotCallSiteThresholdPercent)
114         }
115 }
116
117 // hotNodesFromCDF computes an edge weight threshold and the list of hot
118 // nodes that make up the given percentage of the CDF. The threshold, as
119 // a percent, is the lower bound of weight for nodes to be considered hot
120 // (currently only used in debug prints) (in case of equal weights,
121 // comparing with the threshold may not accurately reflect which nodes are
122 // considiered hot).
123 func hotNodesFromCDF(p *pgo.Profile) (float64, []pgo.NamedCallEdge) {
124         cum := int64(0)
125         for i, n := range p.NamedEdgeMap.ByWeight {
126                 w := p.NamedEdgeMap.Weight[n]
127                 cum += w
128                 if pgo.WeightInPercentage(cum, p.TotalWeight) > inlineCDFHotCallSiteThresholdPercent {
129                         // nodes[:i+1] to include the very last node that makes it to go over the threshold.
130                         // (Say, if the CDF threshold is 50% and one hot node takes 60% of weight, we want to
131                         // include that node instead of excluding it.)
132                         return pgo.WeightInPercentage(w, p.TotalWeight), p.NamedEdgeMap.ByWeight[:i+1]
133                 }
134         }
135         return 0, p.NamedEdgeMap.ByWeight
136 }
137
138 // InlinePackage finds functions that can be inlined and clones them before walk expands them.
139 func InlinePackage(p *pgo.Profile) {
140         if base.Debug.PGOInline == 0 {
141                 p = nil
142         }
143
144         InlineDecls(p, typecheck.Target.Funcs, true)
145
146         // Perform a garbage collection of hidden closures functions that
147         // are no longer reachable from top-level functions following
148         // inlining. See #59404 and #59638 for more context.
149         garbageCollectUnreferencedHiddenClosures()
150
151         if base.Debug.DumpInlFuncProps != "" {
152                 inlheur.DumpFuncProps(nil, base.Debug.DumpInlFuncProps, nil, inlineMaxBudget)
153         }
154         if useNewInliner() {
155                 postProcessCallSites(p)
156         }
157 }
158
159 // InlineDecls applies inlining to the given batch of declarations.
160 func InlineDecls(p *pgo.Profile, funcs []*ir.Func, doInline bool) {
161         if p != nil {
162                 pgoInlinePrologue(p, funcs)
163         }
164
165         doCanInline := func(n *ir.Func, recursive bool, numfns int) {
166                 if !recursive || numfns > 1 {
167                         // We allow inlining if there is no
168                         // recursion, or the recursion cycle is
169                         // across more than one function.
170                         CanInline(n, p)
171                 } else {
172                         if base.Flag.LowerM > 1 && n.OClosure == nil {
173                                 fmt.Printf("%v: cannot inline %v: recursive\n", ir.Line(n), n.Nname)
174                         }
175                 }
176         }
177
178         ir.VisitFuncsBottomUp(funcs, func(list []*ir.Func, recursive bool) {
179                 numfns := numNonClosures(list)
180                 // We visit functions within an SCC in fairly arbitrary order,
181                 // so by computing inlinability for all functions in the SCC
182                 // before performing any inlining, the results are less
183                 // sensitive to the order within the SCC (see #58905 for an
184                 // example).
185
186                 // First compute inlinability for all functions in the SCC ...
187                 for _, n := range list {
188                         doCanInline(n, recursive, numfns)
189                 }
190                 // ... then make a second pass to do inlining of calls.
191                 if doInline {
192                         for _, n := range list {
193                                 InlineCalls(n, p)
194                         }
195                 }
196         })
197 }
198
199 // garbageCollectUnreferencedHiddenClosures makes a pass over all the
200 // top-level (non-hidden-closure) functions looking for nested closure
201 // functions that are reachable, then sweeps through the Target.Decls
202 // list and marks any non-reachable hidden closure function as dead.
203 // See issues #59404 and #59638 for more context.
204 func garbageCollectUnreferencedHiddenClosures() {
205
206         liveFuncs := make(map[*ir.Func]bool)
207
208         var markLiveFuncs func(fn *ir.Func)
209         markLiveFuncs = func(fn *ir.Func) {
210                 if liveFuncs[fn] {
211                         return
212                 }
213                 liveFuncs[fn] = true
214                 ir.Visit(fn, func(n ir.Node) {
215                         if clo, ok := n.(*ir.ClosureExpr); ok {
216                                 markLiveFuncs(clo.Func)
217                         }
218                 })
219         }
220
221         for i := 0; i < len(typecheck.Target.Funcs); i++ {
222                 fn := typecheck.Target.Funcs[i]
223                 if fn.IsHiddenClosure() {
224                         continue
225                 }
226                 markLiveFuncs(fn)
227         }
228
229         for i := 0; i < len(typecheck.Target.Funcs); i++ {
230                 fn := typecheck.Target.Funcs[i]
231                 if !fn.IsHiddenClosure() {
232                         continue
233                 }
234                 if fn.IsDeadcodeClosure() {
235                         continue
236                 }
237                 if liveFuncs[fn] {
238                         continue
239                 }
240                 fn.SetIsDeadcodeClosure(true)
241                 if base.Flag.LowerM > 2 {
242                         fmt.Printf("%v: unreferenced closure %v marked as dead\n", ir.Line(fn), fn)
243                 }
244                 if fn.Inl != nil && fn.LSym == nil {
245                         ir.InitLSym(fn, true)
246                 }
247         }
248 }
249
250 // inlineBudget determines the max budget for function 'fn' prior to
251 // analyzing the hairyness of the body of 'fn'. We pass in the pgo
252 // profile if available (which can change the budget), also a
253 // 'relaxed' flag, which expands the budget slightly to allow for the
254 // possibility that a call to the function might have its score
255 // adjusted downwards. If 'verbose' is set, then print a remark where
256 // we boost the budget due to PGO.
257 func inlineBudget(fn *ir.Func, profile *pgo.Profile, relaxed bool, verbose bool) int32 {
258         // Update the budget for profile-guided inlining.
259         budget := int32(inlineMaxBudget)
260         if profile != nil {
261                 if n, ok := profile.WeightedCG.IRNodes[ir.LinkFuncName(fn)]; ok {
262                         if _, ok := candHotCalleeMap[n]; ok {
263                                 budget = int32(inlineHotMaxBudget)
264                                 if verbose {
265                                         fmt.Printf("hot-node enabled increased budget=%v for func=%v\n", budget, ir.PkgFuncName(fn))
266                                 }
267                         }
268                 }
269         }
270         if relaxed {
271                 budget += inlineMaxBudget
272         }
273         return budget
274 }
275
276 // CanInline determines whether fn is inlineable.
277 // If so, CanInline saves copies of fn.Body and fn.Dcl in fn.Inl.
278 // fn and fn.Body will already have been typechecked.
279 func CanInline(fn *ir.Func, profile *pgo.Profile) {
280         if fn.Nname == nil {
281                 base.Fatalf("CanInline no nname %+v", fn)
282         }
283
284         var funcProps *inlheur.FuncProps
285         if useNewInliner() {
286                 callCanInline := func(fn *ir.Func) { CanInline(fn, profile) }
287                 funcProps = inlheur.AnalyzeFunc(fn, callCanInline, inlineMaxBudget)
288                 budgetForFunc := func(fn *ir.Func) int32 {
289                         return inlineBudget(fn, profile, true, false)
290                 }
291                 defer func() { inlheur.RevisitInlinability(fn, budgetForFunc) }()
292         }
293
294         var reason string // reason, if any, that the function was not inlined
295         if base.Flag.LowerM > 1 || logopt.Enabled() {
296                 defer func() {
297                         if reason != "" {
298                                 if base.Flag.LowerM > 1 {
299                                         fmt.Printf("%v: cannot inline %v: %s\n", ir.Line(fn), fn.Nname, reason)
300                                 }
301                                 if logopt.Enabled() {
302                                         logopt.LogOpt(fn.Pos(), "cannotInlineFunction", "inline", ir.FuncName(fn), reason)
303                                 }
304                         }
305                 }()
306         }
307
308         reason = InlineImpossible(fn)
309         if reason != "" {
310                 return
311         }
312         if fn.Typecheck() == 0 {
313                 base.Fatalf("CanInline on non-typechecked function %v", fn)
314         }
315
316         n := fn.Nname
317         if n.Func.InlinabilityChecked() {
318                 return
319         }
320         defer n.Func.SetInlinabilityChecked(true)
321
322         cc := int32(inlineExtraCallCost)
323         if base.Flag.LowerL == 4 {
324                 cc = 1 // this appears to yield better performance than 0.
325         }
326
327         // Used a "relaxed" inline budget if the new inliner is enabled.
328         relaxed := useNewInliner()
329
330         // Compute the inline budget for this func.
331         budget := inlineBudget(fn, profile, relaxed, base.Debug.PGODebug > 0)
332
333         // At this point in the game the function we're looking at may
334         // have "stale" autos, vars that still appear in the Dcl list, but
335         // which no longer have any uses in the function body (due to
336         // elimination by deadcode). We'd like to exclude these dead vars
337         // when creating the "Inline.Dcl" field below; to accomplish this,
338         // the hairyVisitor below builds up a map of used/referenced
339         // locals, and we use this map to produce a pruned Inline.Dcl
340         // list. See issue 25459 for more context.
341
342         visitor := hairyVisitor{
343                 curFunc:       fn,
344                 isBigFunc:     isBigFunc(fn),
345                 budget:        budget,
346                 maxBudget:     budget,
347                 extraCallCost: cc,
348                 profile:       profile,
349         }
350         if visitor.tooHairy(fn) {
351                 reason = visitor.reason
352                 return
353         }
354
355         n.Func.Inl = &ir.Inline{
356                 Cost:    budget - visitor.budget,
357                 Dcl:     pruneUnusedAutos(n.Func.Dcl, &visitor),
358                 HaveDcl: true,
359
360                 CanDelayResults: canDelayResults(fn),
361         }
362         if useNewInliner() {
363                 n.Func.Inl.Properties = funcProps.SerializeToString()
364         }
365
366         if base.Flag.LowerM > 1 {
367                 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))
368         } else if base.Flag.LowerM != 0 {
369                 fmt.Printf("%v: can inline %v\n", ir.Line(fn), n)
370         }
371         if logopt.Enabled() {
372                 logopt.LogOpt(fn.Pos(), "canInlineFunction", "inline", ir.FuncName(fn), fmt.Sprintf("cost: %d", budget-visitor.budget))
373         }
374 }
375
376 // InlineImpossible returns a non-empty reason string if fn is impossible to
377 // inline regardless of cost or contents.
378 func InlineImpossible(fn *ir.Func) string {
379         var reason string // reason, if any, that the function can not be inlined.
380         if fn.Nname == nil {
381                 reason = "no name"
382                 return reason
383         }
384
385         // If marked "go:noinline", don't inline.
386         if fn.Pragma&ir.Noinline != 0 {
387                 reason = "marked go:noinline"
388                 return reason
389         }
390
391         // If marked "go:norace" and -race compilation, don't inline.
392         if base.Flag.Race && fn.Pragma&ir.Norace != 0 {
393                 reason = "marked go:norace with -race compilation"
394                 return reason
395         }
396
397         // If marked "go:nocheckptr" and -d checkptr compilation, don't inline.
398         if base.Debug.Checkptr != 0 && fn.Pragma&ir.NoCheckPtr != 0 {
399                 reason = "marked go:nocheckptr"
400                 return reason
401         }
402
403         // If marked "go:cgo_unsafe_args", don't inline, since the function
404         // makes assumptions about its argument frame layout.
405         if fn.Pragma&ir.CgoUnsafeArgs != 0 {
406                 reason = "marked go:cgo_unsafe_args"
407                 return reason
408         }
409
410         // If marked as "go:uintptrkeepalive", don't inline, since the keep
411         // alive information is lost during inlining.
412         //
413         // TODO(prattmic): This is handled on calls during escape analysis,
414         // which is after inlining. Move prior to inlining so the keep-alive is
415         // maintained after inlining.
416         if fn.Pragma&ir.UintptrKeepAlive != 0 {
417                 reason = "marked as having a keep-alive uintptr argument"
418                 return reason
419         }
420
421         // If marked as "go:uintptrescapes", don't inline, since the escape
422         // information is lost during inlining.
423         if fn.Pragma&ir.UintptrEscapes != 0 {
424                 reason = "marked as having an escaping uintptr argument"
425                 return reason
426         }
427
428         // The nowritebarrierrec checker currently works at function
429         // granularity, so inlining yeswritebarrierrec functions can confuse it
430         // (#22342). As a workaround, disallow inlining them for now.
431         if fn.Pragma&ir.Yeswritebarrierrec != 0 {
432                 reason = "marked go:yeswritebarrierrec"
433                 return reason
434         }
435
436         // If a local function has no fn.Body (is defined outside of Go), cannot inline it.
437         // Imported functions don't have fn.Body but might have inline body in fn.Inl.
438         if len(fn.Body) == 0 && !typecheck.HaveInlineBody(fn) {
439                 reason = "no function body"
440                 return reason
441         }
442
443         return ""
444 }
445
446 // canDelayResults reports whether inlined calls to fn can delay
447 // declaring the result parameter until the "return" statement.
448 func canDelayResults(fn *ir.Func) bool {
449         // We can delay declaring+initializing result parameters if:
450         // (1) there's exactly one "return" statement in the inlined function;
451         // (2) it's not an empty return statement (#44355); and
452         // (3) the result parameters aren't named.
453
454         nreturns := 0
455         ir.VisitList(fn.Body, func(n ir.Node) {
456                 if n, ok := n.(*ir.ReturnStmt); ok {
457                         nreturns++
458                         if len(n.Results) == 0 {
459                                 nreturns++ // empty return statement (case 2)
460                         }
461                 }
462         })
463
464         if nreturns != 1 {
465                 return false // not exactly one return statement (case 1)
466         }
467
468         // temporaries for return values.
469         for _, param := range fn.Type().Results() {
470                 if sym := param.Sym; sym != nil && !sym.IsBlank() {
471                         return false // found a named result parameter (case 3)
472                 }
473         }
474
475         return true
476 }
477
478 // hairyVisitor visits a function body to determine its inlining
479 // hairiness and whether or not it can be inlined.
480 type hairyVisitor struct {
481         // This is needed to access the current caller in the doNode function.
482         curFunc       *ir.Func
483         isBigFunc     bool
484         budget        int32
485         maxBudget     int32
486         reason        string
487         extraCallCost int32
488         usedLocals    ir.NameSet
489         do            func(ir.Node) bool
490         profile       *pgo.Profile
491 }
492
493 func (v *hairyVisitor) tooHairy(fn *ir.Func) bool {
494         v.do = v.doNode // cache closure
495         if ir.DoChildren(fn, v.do) {
496                 return true
497         }
498         if v.budget < 0 {
499                 v.reason = fmt.Sprintf("function too complex: cost %d exceeds budget %d", v.maxBudget-v.budget, v.maxBudget)
500                 return true
501         }
502         return false
503 }
504
505 // doNode visits n and its children, updates the state in v, and returns true if
506 // n makes the current function too hairy for inlining.
507 func (v *hairyVisitor) doNode(n ir.Node) bool {
508         if n == nil {
509                 return false
510         }
511 opSwitch:
512         switch n.Op() {
513         // Call is okay if inlinable and we have the budget for the body.
514         case ir.OCALLFUNC:
515                 n := n.(*ir.CallExpr)
516                 // Functions that call runtime.getcaller{pc,sp} can not be inlined
517                 // because getcaller{pc,sp} expect a pointer to the caller's first argument.
518                 //
519                 // runtime.throw is a "cheap call" like panic in normal code.
520                 var cheap bool
521                 if n.Fun.Op() == ir.ONAME {
522                         name := n.Fun.(*ir.Name)
523                         if name.Class == ir.PFUNC {
524                                 switch fn := types.RuntimeSymName(name.Sym()); fn {
525                                 case "getcallerpc", "getcallersp":
526                                         v.reason = "call to " + fn
527                                         return true
528                                 case "throw":
529                                         v.budget -= inlineExtraThrowCost
530                                         break opSwitch
531                                 }
532                                 // Special case for reflect.noescape. It does just type
533                                 // conversions to appease the escape analysis, and doesn't
534                                 // generate code.
535                                 if types.ReflectSymName(name.Sym()) == "noescape" {
536                                         cheap = true
537                                 }
538                         }
539                         // Special case for coverage counter updates; although
540                         // these correspond to real operations, we treat them as
541                         // zero cost for the moment. This is due to the existence
542                         // of tests that are sensitive to inlining-- if the
543                         // insertion of coverage instrumentation happens to tip a
544                         // given function over the threshold and move it from
545                         // "inlinable" to "not-inlinable", this can cause changes
546                         // in allocation behavior, which can then result in test
547                         // failures (a good example is the TestAllocations in
548                         // crypto/ed25519).
549                         if isAtomicCoverageCounterUpdate(n) {
550                                 return false
551                         }
552                 }
553                 if n.Fun.Op() == ir.OMETHEXPR {
554                         if meth := ir.MethodExprName(n.Fun); meth != nil {
555                                 if fn := meth.Func; fn != nil {
556                                         s := fn.Sym()
557                                         if types.RuntimeSymName(s) == "heapBits.nextArena" {
558                                                 // Special case: explicitly allow mid-stack inlining of
559                                                 // runtime.heapBits.next even though it calls slow-path
560                                                 // runtime.heapBits.nextArena.
561                                                 cheap = true
562                                         }
563                                         // Special case: on architectures that can do unaligned loads,
564                                         // explicitly mark encoding/binary methods as cheap,
565                                         // because in practice they are, even though our inlining
566                                         // budgeting system does not see that. See issue 42958.
567                                         if base.Ctxt.Arch.CanMergeLoads && s.Pkg.Path == "encoding/binary" {
568                                                 switch s.Name {
569                                                 case "littleEndian.Uint64", "littleEndian.Uint32", "littleEndian.Uint16",
570                                                         "bigEndian.Uint64", "bigEndian.Uint32", "bigEndian.Uint16",
571                                                         "littleEndian.PutUint64", "littleEndian.PutUint32", "littleEndian.PutUint16",
572                                                         "bigEndian.PutUint64", "bigEndian.PutUint32", "bigEndian.PutUint16",
573                                                         "littleEndian.AppendUint64", "littleEndian.AppendUint32", "littleEndian.AppendUint16",
574                                                         "bigEndian.AppendUint64", "bigEndian.AppendUint32", "bigEndian.AppendUint16":
575                                                         cheap = true
576                                                 }
577                                         }
578                                 }
579                         }
580                 }
581                 if cheap {
582                         break // treat like any other node, that is, cost of 1
583                 }
584
585                 if ir.IsIntrinsicCall(n) {
586                         // Treat like any other node.
587                         break
588                 }
589
590                 if callee := inlCallee(v.curFunc, n.Fun, v.profile); callee != nil && typecheck.HaveInlineBody(callee) {
591                         // Check whether we'd actually inline this call. Set
592                         // log == false since we aren't actually doing inlining
593                         // yet.
594                         if canInlineCallExpr(v.curFunc, n, callee, v.isBigFunc, false) {
595                                 // mkinlcall would inline this call [1], so use
596                                 // the cost of the inline body as the cost of
597                                 // the call, as that is what will actually
598                                 // appear in the code.
599                                 //
600                                 // [1] This is almost a perfect match to the
601                                 // mkinlcall logic, except that
602                                 // canInlineCallExpr considers inlining cycles
603                                 // by looking at what has already been inlined.
604                                 // Since we haven't done any inlining yet we
605                                 // will miss those.
606                                 v.budget -= callee.Inl.Cost
607                                 break
608                         }
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 useNewInliner() && !fn.Wrapper() {
802                 inlheur.ScoreCalls(fn)
803                 defer inlheur.ScoreCallsCleanup()
804         }
805         if base.Debug.DumpInlFuncProps != "" && !fn.Wrapper() {
806                 inlheur.DumpFuncProps(fn, base.Debug.DumpInlFuncProps,
807                         func(fn *ir.Func) { CanInline(fn, profile) }, inlineMaxBudget)
808         }
809         savefn := ir.CurFunc
810         ir.CurFunc = fn
811         bigCaller := isBigFunc(fn)
812         if bigCaller && base.Flag.LowerM > 1 {
813                 fmt.Printf("%v: function %v considered 'big'; reducing max cost of inlinees\n", ir.Line(fn), fn)
814         }
815         var inlCalls []*ir.InlinedCallExpr
816         var edit func(ir.Node) ir.Node
817         edit = func(n ir.Node) ir.Node {
818                 return inlnode(fn, n, bigCaller, &inlCalls, edit, profile)
819         }
820         ir.EditChildren(fn, edit)
821
822         // If we inlined any calls, we want to recursively visit their
823         // bodies for further inlining. However, we need to wait until
824         // *after* the original function body has been expanded, or else
825         // inlCallee can have false positives (e.g., #54632).
826         for len(inlCalls) > 0 {
827                 call := inlCalls[0]
828                 inlCalls = inlCalls[1:]
829                 ir.EditChildren(call, edit)
830         }
831
832         ir.CurFunc = savefn
833 }
834
835 // inlnode recurses over the tree to find inlineable calls, which will
836 // be turned into OINLCALLs by mkinlcall. When the recursion comes
837 // back up will examine left, right, list, rlist, ninit, ntest, nincr,
838 // nbody and nelse and use one of the 4 inlconv/glue functions above
839 // to turn the OINLCALL into an expression, a statement, or patch it
840 // in to this nodes list or rlist as appropriate.
841 // NOTE it makes no sense to pass the glue functions down the
842 // recursion to the level where the OINLCALL gets created because they
843 // have to edit /this/ n, so you'd have to push that one down as well,
844 // but then you may as well do it here.  so this is cleaner and
845 // shorter and less complicated.
846 // The result of inlnode MUST be assigned back to n, e.g.
847 //
848 //      n.Left = inlnode(n.Left)
849 func inlnode(callerfn *ir.Func, n ir.Node, bigCaller bool, inlCalls *[]*ir.InlinedCallExpr, edit func(ir.Node) ir.Node, profile *pgo.Profile) ir.Node {
850         if n == nil {
851                 return n
852         }
853
854         switch n.Op() {
855         case ir.ODEFER, ir.OGO:
856                 n := n.(*ir.GoDeferStmt)
857                 switch call := n.Call; call.Op() {
858                 case ir.OCALLMETH:
859                         base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
860                 case ir.OCALLFUNC:
861                         call := call.(*ir.CallExpr)
862                         call.NoInline = true
863                 }
864         case ir.OTAILCALL:
865                 n := n.(*ir.TailCallStmt)
866                 n.Call.NoInline = true // Not inline a tail call for now. Maybe we could inline it just like RETURN fn(arg)?
867
868         // TODO do them here (or earlier),
869         // so escape analysis can avoid more heapmoves.
870         case ir.OCLOSURE:
871                 return n
872         case ir.OCALLMETH:
873                 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
874         case ir.OCALLFUNC:
875                 n := n.(*ir.CallExpr)
876                 if n.Fun.Op() == ir.OMETHEXPR {
877                         // Prevent inlining some reflect.Value methods when using checkptr,
878                         // even when package reflect was compiled without it (#35073).
879                         if meth := ir.MethodExprName(n.Fun); meth != nil {
880                                 s := meth.Sym()
881                                 if base.Debug.Checkptr != 0 {
882                                         switch types.ReflectSymName(s) {
883                                         case "Value.UnsafeAddr", "Value.Pointer":
884                                                 return n
885                                         }
886                                 }
887                         }
888                 }
889         }
890
891         lno := ir.SetPos(n)
892
893         ir.EditChildren(n, edit)
894
895         // with all the branches out of the way, it is now time to
896         // transmogrify this node itself unless inhibited by the
897         // switch at the top of this function.
898         switch n.Op() {
899         case ir.OCALLMETH:
900                 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
901
902         case ir.OCALLFUNC:
903                 call := n.(*ir.CallExpr)
904                 if call.NoInline {
905                         break
906                 }
907                 if base.Flag.LowerM > 3 {
908                         fmt.Printf("%v:call to func %+v\n", ir.Line(n), call.Fun)
909                 }
910                 if ir.IsIntrinsicCall(call) {
911                         break
912                 }
913                 if fn := inlCallee(callerfn, call.Fun, profile); fn != nil && typecheck.HaveInlineBody(fn) {
914                         n = mkinlcall(callerfn, call, fn, bigCaller, inlCalls)
915                 }
916         }
917
918         base.Pos = lno
919
920         return n
921 }
922
923 // inlCallee takes a function-typed expression and returns the underlying function ONAME
924 // that it refers to if statically known. Otherwise, it returns nil.
925 func inlCallee(caller *ir.Func, fn ir.Node, profile *pgo.Profile) (res *ir.Func) {
926         fn = ir.StaticValue(fn)
927         switch fn.Op() {
928         case ir.OMETHEXPR:
929                 fn := fn.(*ir.SelectorExpr)
930                 n := ir.MethodExprName(fn)
931                 // Check that receiver type matches fn.X.
932                 // TODO(mdempsky): Handle implicit dereference
933                 // of pointer receiver argument?
934                 if n == nil || !types.Identical(n.Type().Recv().Type, fn.X.Type()) {
935                         return nil
936                 }
937                 return n.Func
938         case ir.ONAME:
939                 fn := fn.(*ir.Name)
940                 if fn.Class == ir.PFUNC {
941                         return fn.Func
942                 }
943         case ir.OCLOSURE:
944                 fn := fn.(*ir.ClosureExpr)
945                 c := fn.Func
946                 if len(c.ClosureVars) != 0 && c.ClosureVars[0].Outer.Curfn != caller {
947                         return nil // inliner doesn't support inlining across closure frames
948                 }
949                 CanInline(c, profile)
950                 return c
951         }
952         return nil
953 }
954
955 var inlgen int
956
957 // SSADumpInline gives the SSA back end a chance to dump the function
958 // when producing output for debugging the compiler itself.
959 var SSADumpInline = func(*ir.Func) {}
960
961 // InlineCall allows the inliner implementation to be overridden.
962 // If it returns nil, the function will not be inlined.
963 var InlineCall = func(callerfn *ir.Func, call *ir.CallExpr, fn *ir.Func, inlIndex int) *ir.InlinedCallExpr {
964         base.Fatalf("inline.InlineCall not overridden")
965         panic("unreachable")
966 }
967
968 // inlineCostOK returns true if call n from caller to callee is cheap enough to
969 // inline. bigCaller indicates that caller is a big function.
970 //
971 // If inlineCostOK returns false, it also returns the max cost that the callee
972 // exceeded.
973 func inlineCostOK(n *ir.CallExpr, caller, callee *ir.Func, bigCaller bool) (bool, int32) {
974         maxCost := int32(inlineMaxBudget)
975         if bigCaller {
976                 // We use this to restrict inlining into very big functions.
977                 // See issue 26546 and 17566.
978                 maxCost = inlineBigFunctionMaxCost
979         }
980
981         metric := callee.Inl.Cost
982         if useNewInliner() {
983                 score, ok := inlheur.GetCallSiteScore(caller, n)
984                 if ok {
985                         metric = int32(score)
986                 }
987
988         }
989
990         if metric <= maxCost {
991                 // Simple case. Function is already cheap enough.
992                 return true, 0
993         }
994
995         // We'll also allow inlining of hot functions below inlineHotMaxBudget,
996         // but only in small functions.
997
998         lineOffset := pgo.NodeLineOffset(n, caller)
999         csi := pgo.CallSiteInfo{LineOffset: lineOffset, Caller: caller}
1000         if _, ok := candHotEdgeMap[csi]; !ok {
1001                 // Cold
1002                 return false, maxCost
1003         }
1004
1005         // Hot
1006
1007         if bigCaller {
1008                 if base.Debug.PGODebug > 0 {
1009                         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))
1010                 }
1011                 return false, maxCost
1012         }
1013
1014         if metric > inlineHotMaxBudget {
1015                 return false, inlineHotMaxBudget
1016         }
1017
1018         if !base.PGOHash.MatchPosWithInfo(n.Pos(), "inline", nil) {
1019                 // De-selected by PGO Hash.
1020                 return false, maxCost
1021         }
1022
1023         if base.Debug.PGODebug > 0 {
1024                 fmt.Printf("hot-budget check allows inlining for call %s (cost %d) at %v in function %s\n", ir.PkgFuncName(callee), callee.Inl.Cost, ir.Line(n), ir.PkgFuncName(caller))
1025         }
1026
1027         return true, 0
1028 }
1029
1030 // canInlineCallsite returns true if the call n from caller to callee can be
1031 // inlined. bigCaller indicates that caller is a big function. log indicates
1032 // that the 'cannot inline' reason should be logged.
1033 //
1034 // Preconditions: CanInline(callee) has already been called.
1035 func canInlineCallExpr(callerfn *ir.Func, n *ir.CallExpr, callee *ir.Func, bigCaller bool, log bool) bool {
1036         if callee.Inl == nil {
1037                 // callee is never inlinable.
1038                 if log && logopt.Enabled() {
1039                         logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
1040                                 fmt.Sprintf("%s cannot be inlined", ir.PkgFuncName(callee)))
1041                 }
1042                 return false
1043         }
1044
1045         if ok, maxCost := inlineCostOK(n, callerfn, callee, bigCaller); !ok {
1046                 // callee cost too high for this call site.
1047                 if log && logopt.Enabled() {
1048                         logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
1049                                 fmt.Sprintf("cost %d of %s exceeds max caller cost %d", callee.Inl.Cost, ir.PkgFuncName(callee), maxCost))
1050                 }
1051                 return false
1052         }
1053
1054         if callee == callerfn {
1055                 // Can't recursively inline a function into itself.
1056                 if log && logopt.Enabled() {
1057                         logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", fmt.Sprintf("recursive call to %s", ir.FuncName(callerfn)))
1058                 }
1059                 return false
1060         }
1061
1062         if base.Flag.Cfg.Instrumenting && types.IsNoInstrumentPkg(callee.Sym().Pkg) {
1063                 // Runtime package must not be instrumented.
1064                 // Instrument skips runtime package. However, some runtime code can be
1065                 // inlined into other packages and instrumented there. To avoid this,
1066                 // we disable inlining of runtime functions when instrumenting.
1067                 // The example that we observed is inlining of LockOSThread,
1068                 // which lead to false race reports on m contents.
1069                 if log && logopt.Enabled() {
1070                         logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
1071                                 fmt.Sprintf("call to runtime function %s in instrumented build", ir.PkgFuncName(callee)))
1072                 }
1073                 return false
1074         }
1075
1076         if base.Flag.Race && types.IsNoRacePkg(callee.Sym().Pkg) {
1077                 if log && logopt.Enabled() {
1078                         logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
1079                                 fmt.Sprintf(`call to into "no-race" package function %s in race build`, ir.PkgFuncName(callee)))
1080                 }
1081                 return false
1082         }
1083
1084         // Check if we've already inlined this function at this particular
1085         // call site, in order to stop inlining when we reach the beginning
1086         // of a recursion cycle again. We don't inline immediately recursive
1087         // functions, but allow inlining if there is a recursion cycle of
1088         // many functions. Most likely, the inlining will stop before we
1089         // even hit the beginning of the cycle again, but this catches the
1090         // unusual case.
1091         parent := base.Ctxt.PosTable.Pos(n.Pos()).Base().InliningIndex()
1092         sym := callee.Linksym()
1093         for inlIndex := parent; inlIndex >= 0; inlIndex = base.Ctxt.InlTree.Parent(inlIndex) {
1094                 if base.Ctxt.InlTree.InlinedFunction(inlIndex) == sym {
1095                         if log {
1096                                 if base.Flag.LowerM > 1 {
1097                                         fmt.Printf("%v: cannot inline %v into %v: repeated recursive cycle\n", ir.Line(n), callee, ir.FuncName(callerfn))
1098                                 }
1099                                 if logopt.Enabled() {
1100                                         logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
1101                                                 fmt.Sprintf("repeated recursive cycle to %s", ir.PkgFuncName(callee)))
1102                                 }
1103                         }
1104                         return false
1105                 }
1106         }
1107
1108         return true
1109 }
1110
1111 // If n is a OCALLFUNC node, and fn is an ONAME node for a
1112 // function with an inlinable body, return an OINLCALL node that can replace n.
1113 // The returned node's Ninit has the parameter assignments, the Nbody is the
1114 // inlined function body, and (List, Rlist) contain the (input, output)
1115 // parameters.
1116 // The result of mkinlcall MUST be assigned back to n, e.g.
1117 //
1118 //      n.Left = mkinlcall(n.Left, fn, isddd)
1119 func mkinlcall(callerfn *ir.Func, n *ir.CallExpr, fn *ir.Func, bigCaller bool, inlCalls *[]*ir.InlinedCallExpr) ir.Node {
1120         if !canInlineCallExpr(callerfn, n, fn, bigCaller, true) {
1121                 return n
1122         }
1123         typecheck.AssertFixedCall(n)
1124
1125         parent := base.Ctxt.PosTable.Pos(n.Pos()).Base().InliningIndex()
1126         sym := fn.Linksym()
1127         inlIndex := base.Ctxt.InlTree.Add(parent, n.Pos(), sym, ir.FuncName(fn))
1128
1129         closureInitLSym := func(n *ir.CallExpr, fn *ir.Func) {
1130                 // The linker needs FuncInfo metadata for all inlined
1131                 // functions. This is typically handled by gc.enqueueFunc
1132                 // calling ir.InitLSym for all function declarations in
1133                 // typecheck.Target.Decls (ir.UseClosure adds all closures to
1134                 // Decls).
1135                 //
1136                 // However, non-trivial closures in Decls are ignored, and are
1137                 // insteaded enqueued when walk of the calling function
1138                 // discovers them.
1139                 //
1140                 // This presents a problem for direct calls to closures.
1141                 // Inlining will replace the entire closure definition with its
1142                 // body, which hides the closure from walk and thus suppresses
1143                 // symbol creation.
1144                 //
1145                 // Explicitly create a symbol early in this edge case to ensure
1146                 // we keep this metadata.
1147                 //
1148                 // TODO: Refactor to keep a reference so this can all be done
1149                 // by enqueueFunc.
1150
1151                 if n.Op() != ir.OCALLFUNC {
1152                         // Not a standard call.
1153                         return
1154                 }
1155                 if n.Fun.Op() != ir.OCLOSURE {
1156                         // Not a direct closure call.
1157                         return
1158                 }
1159
1160                 clo := n.Fun.(*ir.ClosureExpr)
1161                 if ir.IsTrivialClosure(clo) {
1162                         // enqueueFunc will handle trivial closures anyways.
1163                         return
1164                 }
1165
1166                 ir.InitLSym(fn, true)
1167         }
1168
1169         closureInitLSym(n, fn)
1170
1171         if base.Flag.GenDwarfInl > 0 {
1172                 if !sym.WasInlined() {
1173                         base.Ctxt.DwFixups.SetPrecursorFunc(sym, fn)
1174                         sym.Set(obj.AttrWasInlined, true)
1175                 }
1176         }
1177
1178         if base.Flag.LowerM != 0 {
1179                 fmt.Printf("%v: inlining call to %v\n", ir.Line(n), fn)
1180         }
1181         if base.Flag.LowerM > 2 {
1182                 fmt.Printf("%v: Before inlining: %+v\n", ir.Line(n), n)
1183         }
1184
1185         res := InlineCall(callerfn, n, fn, inlIndex)
1186
1187         if res == nil {
1188                 base.FatalfAt(n.Pos(), "inlining call to %v failed", fn)
1189         }
1190
1191         if base.Flag.LowerM > 2 {
1192                 fmt.Printf("%v: After inlining %+v\n\n", ir.Line(res), res)
1193         }
1194
1195         *inlCalls = append(*inlCalls, res)
1196
1197         return res
1198 }
1199
1200 // CalleeEffects appends any side effects from evaluating callee to init.
1201 func CalleeEffects(init *ir.Nodes, callee ir.Node) {
1202         for {
1203                 init.Append(ir.TakeInit(callee)...)
1204
1205                 switch callee.Op() {
1206                 case ir.ONAME, ir.OCLOSURE, ir.OMETHEXPR:
1207                         return // done
1208
1209                 case ir.OCONVNOP:
1210                         conv := callee.(*ir.ConvExpr)
1211                         callee = conv.X
1212
1213                 case ir.OINLCALL:
1214                         ic := callee.(*ir.InlinedCallExpr)
1215                         init.Append(ic.Body.Take()...)
1216                         callee = ic.SingleResult()
1217
1218                 default:
1219                         base.FatalfAt(callee.Pos(), "unexpected callee expression: %v", callee)
1220                 }
1221         }
1222 }
1223
1224 func pruneUnusedAutos(ll []*ir.Name, vis *hairyVisitor) []*ir.Name {
1225         s := make([]*ir.Name, 0, len(ll))
1226         for _, n := range ll {
1227                 if n.Class == ir.PAUTO {
1228                         if !vis.usedLocals.Has(n) {
1229                                 // TODO(mdempsky): Simplify code after confident that this
1230                                 // never happens anymore.
1231                                 base.FatalfAt(n.Pos(), "unused auto: %v", n)
1232                                 continue
1233                         }
1234                 }
1235                 s = append(s, n)
1236         }
1237         return s
1238 }
1239
1240 // numNonClosures returns the number of functions in list which are not closures.
1241 func numNonClosures(list []*ir.Func) int {
1242         count := 0
1243         for _, fn := range list {
1244                 if fn.OClosure == nil {
1245                         count++
1246                 }
1247         }
1248         return count
1249 }
1250
1251 func doList(list []ir.Node, do func(ir.Node) bool) bool {
1252         for _, x := range list {
1253                 if x != nil {
1254                         if do(x) {
1255                                 return true
1256                         }
1257                 }
1258         }
1259         return false
1260 }
1261
1262 // isIndexingCoverageCounter returns true if the specified node 'n' is indexing
1263 // into a coverage counter array.
1264 func isIndexingCoverageCounter(n ir.Node) bool {
1265         if n.Op() != ir.OINDEX {
1266                 return false
1267         }
1268         ixn := n.(*ir.IndexExpr)
1269         if ixn.X.Op() != ir.ONAME || !ixn.X.Type().IsArray() {
1270                 return false
1271         }
1272         nn := ixn.X.(*ir.Name)
1273         return nn.CoverageCounter()
1274 }
1275
1276 // isAtomicCoverageCounterUpdate examines the specified node to
1277 // determine whether it represents a call to sync/atomic.AddUint32 to
1278 // increment a coverage counter.
1279 func isAtomicCoverageCounterUpdate(cn *ir.CallExpr) bool {
1280         if cn.Fun.Op() != ir.ONAME {
1281                 return false
1282         }
1283         name := cn.Fun.(*ir.Name)
1284         if name.Class != ir.PFUNC {
1285                 return false
1286         }
1287         fn := name.Sym().Name
1288         if name.Sym().Pkg.Path != "sync/atomic" ||
1289                 (fn != "AddUint32" && fn != "StoreUint32") {
1290                 return false
1291         }
1292         if len(cn.Args) != 2 || cn.Args[0].Op() != ir.OADDR {
1293                 return false
1294         }
1295         adn := cn.Args[0].(*ir.AddrExpr)
1296         v := isIndexingCoverageCounter(adn.X)
1297         return v
1298 }
1299
1300 func useNewInliner() bool {
1301         return goexperiment.NewInliner ||
1302                 inlheur.UnitTesting()
1303 }
1304
1305 func postProcessCallSites(profile *pgo.Profile) {
1306         if base.Debug.DumpInlCallSiteScores != 0 {
1307                 budgetCallback := func(fn *ir.Func, prof *pgo.Profile) (int32, bool) {
1308                         v := inlineBudget(fn, prof, false, false)
1309                         return v, v == inlineHotMaxBudget
1310                 }
1311                 inlheur.DumpInlCallSiteScores(profile, budgetCallback)
1312         }
1313 }