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