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