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.
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.
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
14 // 1: 80-nodes leaf functions, oneliners, panic, lazy typechecking (default)
17 // 4: allow non-leaf functions
19 // At some point this may get another default and become switch-offable with -N.
21 // The -d typcheckinl flag enables early typechecking of all imported bodies,
22 // which is useful to flush out bugs.
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.
32 "internal/goexperiment"
36 "cmd/compile/internal/base"
37 "cmd/compile/internal/inline/inlheur"
38 "cmd/compile/internal/ir"
39 "cmd/compile/internal/logopt"
40 "cmd/compile/internal/pgo"
41 "cmd/compile/internal/typecheck"
42 "cmd/compile/internal/types"
46 // Inlining budget parameters, gathered in one place
49 inlineExtraAppendCost = 0
50 // default is to inline if there's at most one call. -l=4 overrides this by using 1 instead.
51 inlineExtraCallCost = 57 // 57 was benchmarked to provided most benefit with no bad surprises; see https://github.com/golang/go/issues/19348#issuecomment-439370742
52 inlineExtraPanicCost = 1 // do not penalize inlining panics.
53 inlineExtraThrowCost = inlineMaxBudget // with current (2018-05/1.11) code, inlining runtime.throw does not help.
55 inlineBigFunctionNodes = 5000 // Functions with this many nodes are considered "big".
56 inlineBigFunctionMaxCost = 20 // Max cost of inlinee when inlining into a "big" function.
60 // List of all hot callee nodes.
61 // TODO(prattmic): Make this non-global.
62 candHotCalleeMap = make(map[*pgo.IRNode]struct{})
64 // List of all hot call sites. CallSiteInfo.Callee is always nil.
65 // TODO(prattmic): Make this non-global.
66 candHotEdgeMap = make(map[pgo.CallSiteInfo]struct{})
68 // Threshold in percentage for hot callsite inlining.
69 inlineHotCallSiteThresholdPercent float64
71 // Threshold in CDF percentage for hot callsite inlining,
72 // that is, for a threshold of X the hottest callsites that
73 // make up the top X% of total edge weight will be
74 // considered hot for inlining candidates.
75 inlineCDFHotCallSiteThresholdPercent = float64(99)
77 // Budget increased due to hotness.
78 inlineHotMaxBudget int32 = 2000
81 // pgoInlinePrologue records the hot callsites from ir-graph.
82 func pgoInlinePrologue(p *pgo.Profile, funcs []*ir.Func) {
83 if base.Debug.PGOInlineCDFThreshold != "" {
84 if s, err := strconv.ParseFloat(base.Debug.PGOInlineCDFThreshold, 64); err == nil && s >= 0 && s <= 100 {
85 inlineCDFHotCallSiteThresholdPercent = s
87 base.Fatalf("invalid PGOInlineCDFThreshold, must be between 0 and 100")
90 var hotCallsites []pgo.NodeMapKey
91 inlineHotCallSiteThresholdPercent, hotCallsites = hotNodesFromCDF(p)
92 if base.Debug.PGODebug > 0 {
93 fmt.Printf("hot-callsite-thres-from-CDF=%v\n", inlineHotCallSiteThresholdPercent)
96 if x := base.Debug.PGOInlineBudget; x != 0 {
97 inlineHotMaxBudget = int32(x)
100 for _, n := range hotCallsites {
101 // mark inlineable callees from hot edges
102 if callee := p.WeightedCG.IRNodes[n.CalleeName]; callee != nil {
103 candHotCalleeMap[callee] = struct{}{}
105 // mark hot call sites
106 if caller := p.WeightedCG.IRNodes[n.CallerName]; caller != nil && caller.AST != nil {
107 csi := pgo.CallSiteInfo{LineOffset: n.CallSiteOffset, Caller: caller.AST}
108 candHotEdgeMap[csi] = struct{}{}
112 if base.Debug.PGODebug >= 3 {
113 fmt.Printf("hot-cg before inline in dot format:")
114 p.PrintWeightedCallGraphDOT(inlineHotCallSiteThresholdPercent)
118 // hotNodesFromCDF computes an edge weight threshold and the list of hot
119 // nodes that make up the given percentage of the CDF. The threshold, as
120 // a percent, is the lower bound of weight for nodes to be considered hot
121 // (currently only used in debug prints) (in case of equal weights,
122 // comparing with the threshold may not accurately reflect which nodes are
124 func hotNodesFromCDF(p *pgo.Profile) (float64, []pgo.NodeMapKey) {
125 nodes := make([]pgo.NodeMapKey, len(p.NodeMap))
127 for n := range p.NodeMap {
131 sort.Slice(nodes, func(i, j int) bool {
132 ni, nj := nodes[i], nodes[j]
133 if wi, wj := p.NodeMap[ni].EWeight, p.NodeMap[nj].EWeight; wi != wj {
134 return wi > wj // want larger weight first
136 // same weight, order by name/line number
137 if ni.CallerName != nj.CallerName {
138 return ni.CallerName < nj.CallerName
140 if ni.CalleeName != nj.CalleeName {
141 return ni.CalleeName < nj.CalleeName
143 return ni.CallSiteOffset < nj.CallSiteOffset
146 for i, n := range nodes {
147 w := p.NodeMap[n].EWeight
149 if pgo.WeightInPercentage(cum, p.TotalEdgeWeight) > inlineCDFHotCallSiteThresholdPercent {
150 // nodes[:i+1] to include the very last node that makes it to go over the threshold.
151 // (Say, if the CDF threshold is 50% and one hot node takes 60% of weight, we want to
152 // include that node instead of excluding it.)
153 return pgo.WeightInPercentage(w, p.TotalEdgeWeight), nodes[:i+1]
159 // InlinePackage finds functions that can be inlined and clones them before walk expands them.
160 func InlinePackage(p *pgo.Profile) {
161 if base.Debug.PGOInline == 0 {
165 InlineDecls(p, typecheck.Target.Funcs, true)
167 // Perform a garbage collection of hidden closures functions that
168 // are no longer reachable from top-level functions following
169 // inlining. See #59404 and #59638 for more context.
170 garbageCollectUnreferencedHiddenClosures()
172 if base.Debug.DumpInlFuncProps != "" {
173 inlheur.DumpFuncProps(nil, base.Debug.DumpInlFuncProps, nil)
175 if goexperiment.NewInliner {
176 postProcessCallSites(p)
180 // InlineDecls applies inlining to the given batch of declarations.
181 func InlineDecls(p *pgo.Profile, funcs []*ir.Func, doInline bool) {
183 pgoInlinePrologue(p, funcs)
186 doCanInline := func(n *ir.Func, recursive bool, numfns int) {
187 if !recursive || numfns > 1 {
188 // We allow inlining if there is no
189 // recursion, or the recursion cycle is
190 // across more than one function.
193 if base.Flag.LowerM > 1 && n.OClosure == nil {
194 fmt.Printf("%v: cannot inline %v: recursive\n", ir.Line(n), n.Nname)
199 ir.VisitFuncsBottomUp(funcs, func(list []*ir.Func, recursive bool) {
200 numfns := numNonClosures(list)
201 // We visit functions within an SCC in fairly arbitrary order,
202 // so by computing inlinability for all functions in the SCC
203 // before performing any inlining, the results are less
204 // sensitive to the order within the SCC (see #58905 for an
207 // First compute inlinability for all functions in the SCC ...
208 for _, n := range list {
209 doCanInline(n, recursive, numfns)
211 // ... then make a second pass to do inlining of calls.
213 for _, n := range list {
220 // garbageCollectUnreferencedHiddenClosures makes a pass over all the
221 // top-level (non-hidden-closure) functions looking for nested closure
222 // functions that are reachable, then sweeps through the Target.Decls
223 // list and marks any non-reachable hidden closure function as dead.
224 // See issues #59404 and #59638 for more context.
225 func garbageCollectUnreferencedHiddenClosures() {
227 liveFuncs := make(map[*ir.Func]bool)
229 var markLiveFuncs func(fn *ir.Func)
230 markLiveFuncs = func(fn *ir.Func) {
235 ir.Visit(fn, func(n ir.Node) {
236 if clo, ok := n.(*ir.ClosureExpr); ok {
237 markLiveFuncs(clo.Func)
242 for i := 0; i < len(typecheck.Target.Funcs); i++ {
243 fn := typecheck.Target.Funcs[i]
244 if fn.IsHiddenClosure() {
250 for i := 0; i < len(typecheck.Target.Funcs); i++ {
251 fn := typecheck.Target.Funcs[i]
252 if !fn.IsHiddenClosure() {
255 if fn.IsDeadcodeClosure() {
261 fn.SetIsDeadcodeClosure(true)
262 if base.Flag.LowerM > 2 {
263 fmt.Printf("%v: unreferenced closure %v marked as dead\n", ir.Line(fn), fn)
265 if fn.Inl != nil && fn.LSym == nil {
266 ir.InitLSym(fn, true)
271 // inlineBudget determines the max budget for function 'fn' prior to
272 // analyzing the hairyness of the body of 'fn'. We pass in the pgo
273 // profile if available (which can change the budget), also a
274 // 'relaxed' flag, which expands the budget slightly to allow for the
275 // possibility that a call to the function might have its score
276 // adjusted downwards. If 'verbose' is set, then print a remark where
277 // we boost the budget due to PGO.
278 func inlineBudget(fn *ir.Func, profile *pgo.Profile, relaxed bool, verbose bool) int32 {
279 // Update the budget for profile-guided inlining.
280 budget := int32(inlineMaxBudget)
282 if n, ok := profile.WeightedCG.IRNodes[ir.LinkFuncName(fn)]; ok {
283 if _, ok := candHotCalleeMap[n]; ok {
284 budget = int32(inlineHotMaxBudget)
286 fmt.Printf("hot-node enabled increased budget=%v for func=%v\n", budget, ir.PkgFuncName(fn))
292 budget += inlineMaxBudget
297 // CanInline determines whether fn is inlineable.
298 // If so, CanInline saves copies of fn.Body and fn.Dcl in fn.Inl.
299 // fn and fn.Body will already have been typechecked.
300 func CanInline(fn *ir.Func, profile *pgo.Profile) {
302 base.Fatalf("CanInline no nname %+v", fn)
305 var funcProps *inlheur.FuncProps
306 if goexperiment.NewInliner || inlheur.UnitTesting() {
307 funcProps = inlheur.AnalyzeFunc(fn,
308 func(fn *ir.Func) { CanInline(fn, profile) })
311 var reason string // reason, if any, that the function was not inlined
312 if base.Flag.LowerM > 1 || logopt.Enabled() {
315 if base.Flag.LowerM > 1 {
316 fmt.Printf("%v: cannot inline %v: %s\n", ir.Line(fn), fn.Nname, reason)
318 if logopt.Enabled() {
319 logopt.LogOpt(fn.Pos(), "cannotInlineFunction", "inline", ir.FuncName(fn), reason)
325 reason = InlineImpossible(fn)
329 if fn.Typecheck() == 0 {
330 base.Fatalf("CanInline on non-typechecked function %v", fn)
334 if n.Func.InlinabilityChecked() {
337 defer n.Func.SetInlinabilityChecked(true)
339 cc := int32(inlineExtraCallCost)
340 if base.Flag.LowerL == 4 {
341 cc = 1 // this appears to yield better performance than 0.
344 // Used a "relaxed" inline budget if goexperiment.NewInliner is in
345 // effect, or if we're producing a debugging dump.
346 relaxed := goexperiment.NewInliner ||
347 (base.Debug.DumpInlFuncProps != "" ||
348 base.Debug.DumpInlCallSiteScores != 0)
350 // Compute the inline budget for this func.
351 budget := inlineBudget(fn, profile, relaxed, base.Debug.PGODebug > 0)
353 // At this point in the game the function we're looking at may
354 // have "stale" autos, vars that still appear in the Dcl list, but
355 // which no longer have any uses in the function body (due to
356 // elimination by deadcode). We'd like to exclude these dead vars
357 // when creating the "Inline.Dcl" field below; to accomplish this,
358 // the hairyVisitor below builds up a map of used/referenced
359 // locals, and we use this map to produce a pruned Inline.Dcl
360 // list. See issue 25459 for more context.
362 visitor := hairyVisitor{
364 isBigFunc: isBigFunc(fn),
370 if visitor.tooHairy(fn) {
371 reason = visitor.reason
375 n.Func.Inl = &ir.Inline{
376 Cost: budget - visitor.budget,
377 Dcl: pruneUnusedAutos(n.Func.Dcl, &visitor),
380 CanDelayResults: canDelayResults(fn),
382 if goexperiment.NewInliner {
383 n.Func.Inl.Properties = funcProps.SerializeToString()
386 if base.Flag.LowerM > 1 {
387 fmt.Printf("%v: can inline %v with cost %d as: %v { %v }\n", ir.Line(fn), n, budget-visitor.budget, fn.Type(), ir.Nodes(fn.Body))
388 } else if base.Flag.LowerM != 0 {
389 fmt.Printf("%v: can inline %v\n", ir.Line(fn), n)
391 if logopt.Enabled() {
392 logopt.LogOpt(fn.Pos(), "canInlineFunction", "inline", ir.FuncName(fn), fmt.Sprintf("cost: %d", budget-visitor.budget))
396 // InlineImpossible returns a non-empty reason string if fn is impossible to
397 // inline regardless of cost or contents.
398 func InlineImpossible(fn *ir.Func) string {
399 var reason string // reason, if any, that the function can not be inlined.
405 // If marked "go:noinline", don't inline.
406 if fn.Pragma&ir.Noinline != 0 {
407 reason = "marked go:noinline"
411 // If marked "go:norace" and -race compilation, don't inline.
412 if base.Flag.Race && fn.Pragma&ir.Norace != 0 {
413 reason = "marked go:norace with -race compilation"
417 // If marked "go:nocheckptr" and -d checkptr compilation, don't inline.
418 if base.Debug.Checkptr != 0 && fn.Pragma&ir.NoCheckPtr != 0 {
419 reason = "marked go:nocheckptr"
423 // If marked "go:cgo_unsafe_args", don't inline, since the function
424 // makes assumptions about its argument frame layout.
425 if fn.Pragma&ir.CgoUnsafeArgs != 0 {
426 reason = "marked go:cgo_unsafe_args"
430 // If marked as "go:uintptrkeepalive", don't inline, since the keep
431 // alive information is lost during inlining.
433 // TODO(prattmic): This is handled on calls during escape analysis,
434 // which is after inlining. Move prior to inlining so the keep-alive is
435 // maintained after inlining.
436 if fn.Pragma&ir.UintptrKeepAlive != 0 {
437 reason = "marked as having a keep-alive uintptr argument"
441 // If marked as "go:uintptrescapes", don't inline, since the escape
442 // information is lost during inlining.
443 if fn.Pragma&ir.UintptrEscapes != 0 {
444 reason = "marked as having an escaping uintptr argument"
448 // The nowritebarrierrec checker currently works at function
449 // granularity, so inlining yeswritebarrierrec functions can confuse it
450 // (#22342). As a workaround, disallow inlining them for now.
451 if fn.Pragma&ir.Yeswritebarrierrec != 0 {
452 reason = "marked go:yeswritebarrierrec"
456 // If a local function has no fn.Body (is defined outside of Go), cannot inline it.
457 // Imported functions don't have fn.Body but might have inline body in fn.Inl.
458 if len(fn.Body) == 0 && !typecheck.HaveInlineBody(fn) {
459 reason = "no function body"
466 // canDelayResults reports whether inlined calls to fn can delay
467 // declaring the result parameter until the "return" statement.
468 func canDelayResults(fn *ir.Func) bool {
469 // We can delay declaring+initializing result parameters if:
470 // (1) there's exactly one "return" statement in the inlined function;
471 // (2) it's not an empty return statement (#44355); and
472 // (3) the result parameters aren't named.
475 ir.VisitList(fn.Body, func(n ir.Node) {
476 if n, ok := n.(*ir.ReturnStmt); ok {
478 if len(n.Results) == 0 {
479 nreturns++ // empty return statement (case 2)
485 return false // not exactly one return statement (case 1)
488 // temporaries for return values.
489 for _, param := range fn.Type().Results() {
490 if sym := param.Sym; sym != nil && !sym.IsBlank() {
491 return false // found a named result parameter (case 3)
498 // hairyVisitor visits a function body to determine its inlining
499 // hairiness and whether or not it can be inlined.
500 type hairyVisitor struct {
501 // This is needed to access the current caller in the doNode function.
508 usedLocals ir.NameSet
509 do func(ir.Node) bool
513 func (v *hairyVisitor) tooHairy(fn *ir.Func) bool {
514 v.do = v.doNode // cache closure
515 if ir.DoChildren(fn, v.do) {
519 v.reason = fmt.Sprintf("function too complex: cost %d exceeds budget %d", v.maxBudget-v.budget, v.maxBudget)
525 // doNode visits n and its children, updates the state in v, and returns true if
526 // n makes the current function too hairy for inlining.
527 func (v *hairyVisitor) doNode(n ir.Node) bool {
533 // Call is okay if inlinable and we have the budget for the body.
535 n := n.(*ir.CallExpr)
536 // Functions that call runtime.getcaller{pc,sp} can not be inlined
537 // because getcaller{pc,sp} expect a pointer to the caller's first argument.
539 // runtime.throw is a "cheap call" like panic in normal code.
541 if n.Fun.Op() == ir.ONAME {
542 name := n.Fun.(*ir.Name)
543 if name.Class == ir.PFUNC {
544 switch fn := types.RuntimeSymName(name.Sym()); fn {
545 case "getcallerpc", "getcallersp":
546 v.reason = "call to " + fn
549 v.budget -= inlineExtraThrowCost
552 // Special case for reflect.noescape. It does just type
553 // conversions to appease the escape analysis, and doesn't
555 if types.ReflectSymName(name.Sym()) == "noescape" {
559 // Special case for coverage counter updates; although
560 // these correspond to real operations, we treat them as
561 // zero cost for the moment. This is due to the existence
562 // of tests that are sensitive to inlining-- if the
563 // insertion of coverage instrumentation happens to tip a
564 // given function over the threshold and move it from
565 // "inlinable" to "not-inlinable", this can cause changes
566 // in allocation behavior, which can then result in test
567 // failures (a good example is the TestAllocations in
569 if isAtomicCoverageCounterUpdate(n) {
573 if n.Fun.Op() == ir.OMETHEXPR {
574 if meth := ir.MethodExprName(n.Fun); meth != nil {
575 if fn := meth.Func; fn != nil {
577 if types.RuntimeSymName(s) == "heapBits.nextArena" {
578 // Special case: explicitly allow mid-stack inlining of
579 // runtime.heapBits.next even though it calls slow-path
580 // runtime.heapBits.nextArena.
583 // Special case: on architectures that can do unaligned loads,
584 // explicitly mark encoding/binary methods as cheap,
585 // because in practice they are, even though our inlining
586 // budgeting system does not see that. See issue 42958.
587 if base.Ctxt.Arch.CanMergeLoads && s.Pkg.Path == "encoding/binary" {
589 case "littleEndian.Uint64", "littleEndian.Uint32", "littleEndian.Uint16",
590 "bigEndian.Uint64", "bigEndian.Uint32", "bigEndian.Uint16",
591 "littleEndian.PutUint64", "littleEndian.PutUint32", "littleEndian.PutUint16",
592 "bigEndian.PutUint64", "bigEndian.PutUint32", "bigEndian.PutUint16",
593 "littleEndian.AppendUint64", "littleEndian.AppendUint32", "littleEndian.AppendUint16",
594 "bigEndian.AppendUint64", "bigEndian.AppendUint32", "bigEndian.AppendUint16":
602 break // treat like any other node, that is, cost of 1
605 if ir.IsIntrinsicCall(n) {
606 // Treat like any other node.
610 if callee := inlCallee(v.curFunc, n.Fun, v.profile); callee != nil && typecheck.HaveInlineBody(callee) {
611 // Check whether we'd actually inline this call. Set
612 // log == false since we aren't actually doing inlining
614 if canInlineCallExpr(v.curFunc, n, callee, v.isBigFunc, false) {
615 // mkinlcall would inline this call [1], so use
616 // the cost of the inline body as the cost of
617 // the call, as that is what will actually
618 // appear in the code.
620 // [1] This is almost a perfect match to the
621 // mkinlcall logic, except that
622 // canInlineCallExpr considers inlining cycles
623 // by looking at what has already been inlined.
624 // Since we haven't done any inlining yet we
626 v.budget -= callee.Inl.Cost
631 // Call cost for non-leaf inlining.
632 v.budget -= v.extraCallCost
635 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
637 // Things that are too hairy, irrespective of the budget
638 case ir.OCALL, ir.OCALLINTER:
639 // Call cost for non-leaf inlining.
640 v.budget -= v.extraCallCost
643 n := n.(*ir.UnaryExpr)
644 if n.X.Op() == ir.OCONVIFACE && n.X.(*ir.ConvExpr).Implicit() {
645 // Hack to keep reflect.flag.mustBe inlinable for TestIntendedInlining.
646 // Before CL 284412, these conversions were introduced later in the
647 // compiler, so they didn't count against inlining budget.
650 v.budget -= inlineExtraPanicCost
653 base.FatalfAt(n.Pos(), "ORECOVER missed typecheck")
655 // recover matches the argument frame pointer to find
656 // the right panic value, so it needs an argument frame.
657 v.reason = "call to recover"
661 if base.Debug.InlFuncsWithClosures == 0 {
662 v.reason = "not inlining functions with closures"
666 // TODO(danscales): Maybe make budget proportional to number of closure
668 //v.budget -= int32(len(n.(*ir.ClosureExpr).Func.ClosureVars) * 3)
669 // TODO(austin): However, if we're able to inline this closure into
670 // v.curFunc, then we actually pay nothing for the closure captures. We
671 // should try to account for that if we're going to account for captures.
674 case ir.OGO, ir.ODEFER, ir.OTAILCALL:
675 v.reason = "unhandled op " + n.Op().String()
679 v.budget -= inlineExtraAppendCost
682 n := n.(*ir.AddrExpr)
683 // Make "&s.f" cost 0 when f's offset is zero.
684 if dot, ok := n.X.(*ir.SelectorExpr); ok && (dot.Op() == ir.ODOT || dot.Op() == ir.ODOTPTR) {
685 if _, ok := dot.X.(*ir.Name); ok && dot.Selection.Offset == 0 {
686 v.budget += 2 // undo ir.OADDR+ir.ODOT/ir.ODOTPTR
691 // *(*X)(unsafe.Pointer(&x)) is low-cost
692 n := n.(*ir.StarExpr)
695 for ptr.Op() == ir.OCONVNOP {
696 ptr = ptr.(*ir.ConvExpr).X
698 if ptr.Op() == ir.OADDR {
699 v.budget += 1 // undo half of default cost of ir.ODEREF+ir.OADDR
703 // This doesn't produce code, but the children might.
704 v.budget++ // undo default cost
706 case ir.OFALL, ir.OTYPE:
707 // These nodes don't produce code; omit from inlining budget.
712 if ir.IsConst(n.Cond, constant.Bool) {
713 // This if and the condition cost nothing.
714 if doList(n.Init(), v.do) {
717 if ir.BoolVal(n.Cond) {
718 return doList(n.Body, v.do)
720 return doList(n.Else, v.do)
726 if n.Class == ir.PAUTO {
731 // The only OBLOCK we should see at this point is an empty one.
732 // In any event, let the visitList(n.List()) below take care of the statements,
733 // and don't charge for the OBLOCK itself. The ++ undoes the -- below.
736 case ir.OMETHVALUE, ir.OSLICELIT:
737 v.budget-- // Hack for toolstash -cmp.
740 v.budget++ // Hack for toolstash -cmp.
743 n := n.(*ir.AssignListStmt)
745 // Unified IR unconditionally rewrites:
756 // so that it can insert implicit conversions as necessary. To
757 // minimize impact to the existing inlining heuristics (in
758 // particular, to avoid breaking the existing inlinability regress
759 // tests), we need to compensate for this here.
761 // See also identical logic in isBigFunc.
762 if init := n.Rhs[0].Init(); len(init) == 1 {
763 if _, ok := init[0].(*ir.AssignListStmt); ok {
764 // 4 for each value, because each temporary variable now
765 // appears 3 times (DCL, LHS, RHS), plus an extra DCL node.
767 // 1 for the extra "tmp1, tmp2 = f()" assignment statement.
768 v.budget += 4*int32(len(n.Lhs)) + 1
773 // Special case for coverage counter updates and coverage
774 // function registrations. Although these correspond to real
775 // operations, we treat them as zero cost for the moment. This
776 // is primarily due to the existence of tests that are
777 // sensitive to inlining-- if the insertion of coverage
778 // instrumentation happens to tip a given function over the
779 // threshold and move it from "inlinable" to "not-inlinable",
780 // this can cause changes in allocation behavior, which can
781 // then result in test failures (a good example is the
782 // TestAllocations in crypto/ed25519).
783 n := n.(*ir.AssignStmt)
784 if n.X.Op() == ir.OINDEX && isIndexingCoverageCounter(n.X) {
791 // When debugging, don't stop early, to get full cost of inlining this function
792 if v.budget < 0 && base.Flag.LowerM < 2 && !logopt.Enabled() {
793 v.reason = "too expensive"
797 return ir.DoChildren(n, v.do)
800 func isBigFunc(fn *ir.Func) bool {
801 budget := inlineBigFunctionNodes
802 return ir.Any(fn, func(n ir.Node) bool {
803 // See logic in hairyVisitor.doNode, explaining unified IR's
804 // handling of "a, b = f()" assignments.
805 if n, ok := n.(*ir.AssignListStmt); ok && n.Op() == ir.OAS2 {
806 if init := n.Rhs[0].Init(); len(init) == 1 {
807 if _, ok := init[0].(*ir.AssignListStmt); ok {
808 budget += 4*len(n.Lhs) + 1
818 // InlineCalls/inlnode walks fn's statements and expressions and substitutes any
819 // calls made to inlineable functions. This is the external entry point.
820 func InlineCalls(fn *ir.Func, profile *pgo.Profile) {
821 if goexperiment.NewInliner && !fn.Wrapper() {
822 inlheur.ScoreCalls(fn)
824 if base.Debug.DumpInlFuncProps != "" && !fn.Wrapper() {
825 inlheur.DumpFuncProps(fn, base.Debug.DumpInlFuncProps,
826 func(fn *ir.Func) { CanInline(fn, profile) })
830 bigCaller := isBigFunc(fn)
831 if bigCaller && base.Flag.LowerM > 1 {
832 fmt.Printf("%v: function %v considered 'big'; reducing max cost of inlinees\n", ir.Line(fn), fn)
834 var inlCalls []*ir.InlinedCallExpr
835 var edit func(ir.Node) ir.Node
836 edit = func(n ir.Node) ir.Node {
837 return inlnode(fn, n, bigCaller, &inlCalls, edit, profile)
839 ir.EditChildren(fn, edit)
841 // If we inlined any calls, we want to recursively visit their
842 // bodies for further inlining. However, we need to wait until
843 // *after* the original function body has been expanded, or else
844 // inlCallee can have false positives (e.g., #54632).
845 for len(inlCalls) > 0 {
847 inlCalls = inlCalls[1:]
848 ir.EditChildren(call, edit)
854 // inlnode recurses over the tree to find inlineable calls, which will
855 // be turned into OINLCALLs by mkinlcall. When the recursion comes
856 // back up will examine left, right, list, rlist, ninit, ntest, nincr,
857 // nbody and nelse and use one of the 4 inlconv/glue functions above
858 // to turn the OINLCALL into an expression, a statement, or patch it
859 // in to this nodes list or rlist as appropriate.
860 // NOTE it makes no sense to pass the glue functions down the
861 // recursion to the level where the OINLCALL gets created because they
862 // have to edit /this/ n, so you'd have to push that one down as well,
863 // but then you may as well do it here. so this is cleaner and
864 // shorter and less complicated.
865 // The result of inlnode MUST be assigned back to n, e.g.
867 // n.Left = inlnode(n.Left)
868 func inlnode(callerfn *ir.Func, n ir.Node, bigCaller bool, inlCalls *[]*ir.InlinedCallExpr, edit func(ir.Node) ir.Node, profile *pgo.Profile) ir.Node {
874 case ir.ODEFER, ir.OGO:
875 n := n.(*ir.GoDeferStmt)
876 switch call := n.Call; call.Op() {
878 base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
880 call := call.(*ir.CallExpr)
884 n := n.(*ir.TailCallStmt)
885 n.Call.NoInline = true // Not inline a tail call for now. Maybe we could inline it just like RETURN fn(arg)?
887 // TODO do them here (or earlier),
888 // so escape analysis can avoid more heapmoves.
892 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
894 n := n.(*ir.CallExpr)
895 if n.Fun.Op() == ir.OMETHEXPR {
896 // Prevent inlining some reflect.Value methods when using checkptr,
897 // even when package reflect was compiled without it (#35073).
898 if meth := ir.MethodExprName(n.Fun); meth != nil {
900 if base.Debug.Checkptr != 0 {
901 switch types.ReflectSymName(s) {
902 case "Value.UnsafeAddr", "Value.Pointer":
912 ir.EditChildren(n, edit)
914 // with all the branches out of the way, it is now time to
915 // transmogrify this node itself unless inhibited by the
916 // switch at the top of this function.
919 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
922 call := n.(*ir.CallExpr)
926 if base.Flag.LowerM > 3 {
927 fmt.Printf("%v:call to func %+v\n", ir.Line(n), call.Fun)
929 if ir.IsIntrinsicCall(call) {
932 if fn := inlCallee(callerfn, call.Fun, profile); fn != nil && typecheck.HaveInlineBody(fn) {
933 n = mkinlcall(callerfn, call, fn, bigCaller, inlCalls)
942 // inlCallee takes a function-typed expression and returns the underlying function ONAME
943 // that it refers to if statically known. Otherwise, it returns nil.
944 func inlCallee(caller *ir.Func, fn ir.Node, profile *pgo.Profile) (res *ir.Func) {
945 fn = ir.StaticValue(fn)
948 fn := fn.(*ir.SelectorExpr)
949 n := ir.MethodExprName(fn)
950 // Check that receiver type matches fn.X.
951 // TODO(mdempsky): Handle implicit dereference
952 // of pointer receiver argument?
953 if n == nil || !types.Identical(n.Type().Recv().Type, fn.X.Type()) {
959 if fn.Class == ir.PFUNC {
963 fn := fn.(*ir.ClosureExpr)
965 if len(c.ClosureVars) != 0 && c.ClosureVars[0].Outer.Curfn != caller {
966 return nil // inliner doesn't support inlining across closure frames
968 CanInline(c, profile)
976 // SSADumpInline gives the SSA back end a chance to dump the function
977 // when producing output for debugging the compiler itself.
978 var SSADumpInline = func(*ir.Func) {}
980 // InlineCall allows the inliner implementation to be overridden.
981 // If it returns nil, the function will not be inlined.
982 var InlineCall = func(callerfn *ir.Func, call *ir.CallExpr, fn *ir.Func, inlIndex int) *ir.InlinedCallExpr {
983 base.Fatalf("inline.InlineCall not overridden")
987 // inlineCostOK returns true if call n from caller to callee is cheap enough to
988 // inline. bigCaller indicates that caller is a big function.
990 // If inlineCostOK returns false, it also returns the max cost that the callee
992 func inlineCostOK(n *ir.CallExpr, caller, callee *ir.Func, bigCaller bool) (bool, int32) {
993 maxCost := int32(inlineMaxBudget)
995 // We use this to restrict inlining into very big functions.
996 // See issue 26546 and 17566.
997 maxCost = inlineBigFunctionMaxCost
1000 metric := callee.Inl.Cost
1001 if goexperiment.NewInliner {
1002 ok, score := inlheur.GetCallSiteScore(n)
1004 metric = int32(score)
1009 if metric <= maxCost {
1010 // Simple case. Function is already cheap enough.
1014 // We'll also allow inlining of hot functions below inlineHotMaxBudget,
1015 // but only in small functions.
1017 lineOffset := pgo.NodeLineOffset(n, caller)
1018 csi := pgo.CallSiteInfo{LineOffset: lineOffset, Caller: caller}
1019 if _, ok := candHotEdgeMap[csi]; !ok {
1021 return false, maxCost
1027 if base.Debug.PGODebug > 0 {
1028 fmt.Printf("hot-big check disallows inlining for call %s (cost %d) at %v in big function %s\n", ir.PkgFuncName(callee), callee.Inl.Cost, ir.Line(n), ir.PkgFuncName(caller))
1030 return false, maxCost
1033 if metric > inlineHotMaxBudget {
1034 return false, inlineHotMaxBudget
1037 if !base.PGOHash.MatchPosWithInfo(n.Pos(), "inline", nil) {
1038 // De-selected by PGO Hash.
1039 return false, maxCost
1042 if base.Debug.PGODebug > 0 {
1043 fmt.Printf("hot-budget check allows inlining for call %s (cost %d) at %v in function %s\n", ir.PkgFuncName(callee), callee.Inl.Cost, ir.Line(n), ir.PkgFuncName(caller))
1049 // canInlineCallsite returns true if the call n from caller to callee can be
1050 // inlined. bigCaller indicates that caller is a big function. log indicates
1051 // that the 'cannot inline' reason should be logged.
1053 // Preconditions: CanInline(callee) has already been called.
1054 func canInlineCallExpr(callerfn *ir.Func, n *ir.CallExpr, callee *ir.Func, bigCaller bool, log bool) bool {
1055 if callee.Inl == nil {
1056 // callee is never inlinable.
1057 if log && logopt.Enabled() {
1058 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
1059 fmt.Sprintf("%s cannot be inlined", ir.PkgFuncName(callee)))
1064 if ok, maxCost := inlineCostOK(n, callerfn, callee, bigCaller); !ok {
1065 // callee cost too high for this call site.
1066 if log && logopt.Enabled() {
1067 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
1068 fmt.Sprintf("cost %d of %s exceeds max caller cost %d", callee.Inl.Cost, ir.PkgFuncName(callee), maxCost))
1073 if callee == callerfn {
1074 // Can't recursively inline a function into itself.
1075 if log && logopt.Enabled() {
1076 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", fmt.Sprintf("recursive call to %s", ir.FuncName(callerfn)))
1081 if base.Flag.Cfg.Instrumenting && types.IsNoInstrumentPkg(callee.Sym().Pkg) {
1082 // Runtime package must not be instrumented.
1083 // Instrument skips runtime package. However, some runtime code can be
1084 // inlined into other packages and instrumented there. To avoid this,
1085 // we disable inlining of runtime functions when instrumenting.
1086 // The example that we observed is inlining of LockOSThread,
1087 // which lead to false race reports on m contents.
1088 if log && logopt.Enabled() {
1089 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
1090 fmt.Sprintf("call to runtime function %s in instrumented build", ir.PkgFuncName(callee)))
1095 if base.Flag.Race && types.IsNoRacePkg(callee.Sym().Pkg) {
1096 if log && logopt.Enabled() {
1097 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
1098 fmt.Sprintf(`call to into "no-race" package function %s in race build`, ir.PkgFuncName(callee)))
1103 // Check if we've already inlined this function at this particular
1104 // call site, in order to stop inlining when we reach the beginning
1105 // of a recursion cycle again. We don't inline immediately recursive
1106 // functions, but allow inlining if there is a recursion cycle of
1107 // many functions. Most likely, the inlining will stop before we
1108 // even hit the beginning of the cycle again, but this catches the
1110 parent := base.Ctxt.PosTable.Pos(n.Pos()).Base().InliningIndex()
1111 sym := callee.Linksym()
1112 for inlIndex := parent; inlIndex >= 0; inlIndex = base.Ctxt.InlTree.Parent(inlIndex) {
1113 if base.Ctxt.InlTree.InlinedFunction(inlIndex) == sym {
1115 if base.Flag.LowerM > 1 {
1116 fmt.Printf("%v: cannot inline %v into %v: repeated recursive cycle\n", ir.Line(n), callee, ir.FuncName(callerfn))
1118 if logopt.Enabled() {
1119 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
1120 fmt.Sprintf("repeated recursive cycle to %s", ir.PkgFuncName(callee)))
1130 // If n is a OCALLFUNC node, and fn is an ONAME node for a
1131 // function with an inlinable body, return an OINLCALL node that can replace n.
1132 // The returned node's Ninit has the parameter assignments, the Nbody is the
1133 // inlined function body, and (List, Rlist) contain the (input, output)
1135 // The result of mkinlcall MUST be assigned back to n, e.g.
1137 // n.Left = mkinlcall(n.Left, fn, isddd)
1138 func mkinlcall(callerfn *ir.Func, n *ir.CallExpr, fn *ir.Func, bigCaller bool, inlCalls *[]*ir.InlinedCallExpr) ir.Node {
1139 if !canInlineCallExpr(callerfn, n, fn, bigCaller, true) {
1142 typecheck.AssertFixedCall(n)
1144 parent := base.Ctxt.PosTable.Pos(n.Pos()).Base().InliningIndex()
1146 inlIndex := base.Ctxt.InlTree.Add(parent, n.Pos(), sym, ir.FuncName(fn))
1148 closureInitLSym := func(n *ir.CallExpr, fn *ir.Func) {
1149 // The linker needs FuncInfo metadata for all inlined
1150 // functions. This is typically handled by gc.enqueueFunc
1151 // calling ir.InitLSym for all function declarations in
1152 // typecheck.Target.Decls (ir.UseClosure adds all closures to
1155 // However, non-trivial closures in Decls are ignored, and are
1156 // insteaded enqueued when walk of the calling function
1159 // This presents a problem for direct calls to closures.
1160 // Inlining will replace the entire closure definition with its
1161 // body, which hides the closure from walk and thus suppresses
1164 // Explicitly create a symbol early in this edge case to ensure
1165 // we keep this metadata.
1167 // TODO: Refactor to keep a reference so this can all be done
1170 if n.Op() != ir.OCALLFUNC {
1171 // Not a standard call.
1174 if n.Fun.Op() != ir.OCLOSURE {
1175 // Not a direct closure call.
1179 clo := n.Fun.(*ir.ClosureExpr)
1180 if ir.IsTrivialClosure(clo) {
1181 // enqueueFunc will handle trivial closures anyways.
1185 ir.InitLSym(fn, true)
1188 closureInitLSym(n, fn)
1190 if base.Flag.GenDwarfInl > 0 {
1191 if !sym.WasInlined() {
1192 base.Ctxt.DwFixups.SetPrecursorFunc(sym, fn)
1193 sym.Set(obj.AttrWasInlined, true)
1197 if base.Flag.LowerM != 0 {
1198 fmt.Printf("%v: inlining call to %v\n", ir.Line(n), fn)
1200 if base.Flag.LowerM > 2 {
1201 fmt.Printf("%v: Before inlining: %+v\n", ir.Line(n), n)
1204 res := InlineCall(callerfn, n, fn, inlIndex)
1207 base.FatalfAt(n.Pos(), "inlining call to %v failed", fn)
1210 if base.Flag.LowerM > 2 {
1211 fmt.Printf("%v: After inlining %+v\n\n", ir.Line(res), res)
1214 *inlCalls = append(*inlCalls, res)
1219 // CalleeEffects appends any side effects from evaluating callee to init.
1220 func CalleeEffects(init *ir.Nodes, callee ir.Node) {
1222 init.Append(ir.TakeInit(callee)...)
1224 switch callee.Op() {
1225 case ir.ONAME, ir.OCLOSURE, ir.OMETHEXPR:
1229 conv := callee.(*ir.ConvExpr)
1233 ic := callee.(*ir.InlinedCallExpr)
1234 init.Append(ic.Body.Take()...)
1235 callee = ic.SingleResult()
1238 base.FatalfAt(callee.Pos(), "unexpected callee expression: %v", callee)
1243 func pruneUnusedAutos(ll []*ir.Name, vis *hairyVisitor) []*ir.Name {
1244 s := make([]*ir.Name, 0, len(ll))
1245 for _, n := range ll {
1246 if n.Class == ir.PAUTO {
1247 if !vis.usedLocals.Has(n) {
1248 // TODO(mdempsky): Simplify code after confident that this
1249 // never happens anymore.
1250 base.FatalfAt(n.Pos(), "unused auto: %v", n)
1259 // numNonClosures returns the number of functions in list which are not closures.
1260 func numNonClosures(list []*ir.Func) int {
1262 for _, fn := range list {
1263 if fn.OClosure == nil {
1270 func doList(list []ir.Node, do func(ir.Node) bool) bool {
1271 for _, x := range list {
1281 // isIndexingCoverageCounter returns true if the specified node 'n' is indexing
1282 // into a coverage counter array.
1283 func isIndexingCoverageCounter(n ir.Node) bool {
1284 if n.Op() != ir.OINDEX {
1287 ixn := n.(*ir.IndexExpr)
1288 if ixn.X.Op() != ir.ONAME || !ixn.X.Type().IsArray() {
1291 nn := ixn.X.(*ir.Name)
1292 return nn.CoverageCounter()
1295 // isAtomicCoverageCounterUpdate examines the specified node to
1296 // determine whether it represents a call to sync/atomic.AddUint32 to
1297 // increment a coverage counter.
1298 func isAtomicCoverageCounterUpdate(cn *ir.CallExpr) bool {
1299 if cn.Fun.Op() != ir.ONAME {
1302 name := cn.Fun.(*ir.Name)
1303 if name.Class != ir.PFUNC {
1306 fn := name.Sym().Name
1307 if name.Sym().Pkg.Path != "sync/atomic" ||
1308 (fn != "AddUint32" && fn != "StoreUint32") {
1311 if len(cn.Args) != 2 || cn.Args[0].Op() != ir.OADDR {
1314 adn := cn.Args[0].(*ir.AddrExpr)
1315 v := isIndexingCoverageCounter(adn.X)
1319 func postProcessCallSites(profile *pgo.Profile) {
1320 if base.Debug.DumpInlCallSiteScores != 0 {
1321 budgetCallback := func(fn *ir.Func, prof *pgo.Profile) (int32, bool) {
1322 v := inlineBudget(fn, prof, false, false)
1323 return v, v == inlineHotMaxBudget
1325 inlheur.DumpInlCallSiteScores(profile, budgetCallback)