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"
35 "cmd/compile/internal/base"
36 "cmd/compile/internal/inline/inlheur"
37 "cmd/compile/internal/ir"
38 "cmd/compile/internal/logopt"
39 "cmd/compile/internal/pgo"
40 "cmd/compile/internal/typecheck"
41 "cmd/compile/internal/types"
45 // Inlining budget parameters, gathered in one place
48 inlineExtraAppendCost = 0
49 // default is to inline if there's at most one call. -l=4 overrides this by using 1 instead.
50 inlineExtraCallCost = 57 // 57 was benchmarked to provided most benefit with no bad surprises; see https://github.com/golang/go/issues/19348#issuecomment-439370742
51 inlineExtraPanicCost = 1 // do not penalize inlining panics.
52 inlineExtraThrowCost = inlineMaxBudget // with current (2018-05/1.11) code, inlining runtime.throw does not help.
54 inlineBigFunctionNodes = 5000 // Functions with this many nodes are considered "big".
55 inlineBigFunctionMaxCost = 20 // Max cost of inlinee when inlining into a "big" function.
59 // List of all hot callee nodes.
60 // TODO(prattmic): Make this non-global.
61 candHotCalleeMap = make(map[*pgo.IRNode]struct{})
63 // List of all hot call sites. CallSiteInfo.Callee is always nil.
64 // TODO(prattmic): Make this non-global.
65 candHotEdgeMap = make(map[pgo.CallSiteInfo]struct{})
67 // Threshold in percentage for hot callsite inlining.
68 inlineHotCallSiteThresholdPercent float64
70 // Threshold in CDF percentage for hot callsite inlining,
71 // that is, for a threshold of X the hottest callsites that
72 // make up the top X% of total edge weight will be
73 // considered hot for inlining candidates.
74 inlineCDFHotCallSiteThresholdPercent = float64(99)
76 // Budget increased due to hotness.
77 inlineHotMaxBudget int32 = 2000
80 // pgoInlinePrologue records the hot callsites from ir-graph.
81 func pgoInlinePrologue(p *pgo.Profile, funcs []*ir.Func) {
82 if base.Debug.PGOInlineCDFThreshold != "" {
83 if s, err := strconv.ParseFloat(base.Debug.PGOInlineCDFThreshold, 64); err == nil && s >= 0 && s <= 100 {
84 inlineCDFHotCallSiteThresholdPercent = s
86 base.Fatalf("invalid PGOInlineCDFThreshold, must be between 0 and 100")
89 var hotCallsites []pgo.NamedCallEdge
90 inlineHotCallSiteThresholdPercent, hotCallsites = hotNodesFromCDF(p)
91 if base.Debug.PGODebug > 0 {
92 fmt.Printf("hot-callsite-thres-from-CDF=%v\n", inlineHotCallSiteThresholdPercent)
95 if x := base.Debug.PGOInlineBudget; x != 0 {
96 inlineHotMaxBudget = int32(x)
99 for _, n := range hotCallsites {
100 // mark inlineable callees from hot edges
101 if callee := p.WeightedCG.IRNodes[n.CalleeName]; callee != nil {
102 candHotCalleeMap[callee] = struct{}{}
104 // mark hot call sites
105 if caller := p.WeightedCG.IRNodes[n.CallerName]; caller != nil && caller.AST != nil {
106 csi := pgo.CallSiteInfo{LineOffset: n.CallSiteOffset, Caller: caller.AST}
107 candHotEdgeMap[csi] = struct{}{}
111 if base.Debug.PGODebug >= 3 {
112 fmt.Printf("hot-cg before inline in dot format:")
113 p.PrintWeightedCallGraphDOT(inlineHotCallSiteThresholdPercent)
117 // hotNodesFromCDF computes an edge weight threshold and the list of hot
118 // nodes that make up the given percentage of the CDF. The threshold, as
119 // a percent, is the lower bound of weight for nodes to be considered hot
120 // (currently only used in debug prints) (in case of equal weights,
121 // comparing with the threshold may not accurately reflect which nodes are
123 func hotNodesFromCDF(p *pgo.Profile) (float64, []pgo.NamedCallEdge) {
125 for i, n := range p.NamedEdgeMap.ByWeight {
126 w := p.NamedEdgeMap.Weight[n]
128 if pgo.WeightInPercentage(cum, p.TotalWeight) > inlineCDFHotCallSiteThresholdPercent {
129 // nodes[:i+1] to include the very last node that makes it to go over the threshold.
130 // (Say, if the CDF threshold is 50% and one hot node takes 60% of weight, we want to
131 // include that node instead of excluding it.)
132 return pgo.WeightInPercentage(w, p.TotalWeight), p.NamedEdgeMap.ByWeight[:i+1]
135 return 0, p.NamedEdgeMap.ByWeight
138 // InlinePackage finds functions that can be inlined and clones them before walk expands them.
139 func InlinePackage(p *pgo.Profile) {
140 if base.Debug.PGOInline == 0 {
144 InlineDecls(p, typecheck.Target.Funcs, true)
146 // Perform a garbage collection of hidden closures functions that
147 // are no longer reachable from top-level functions following
148 // inlining. See #59404 and #59638 for more context.
149 garbageCollectUnreferencedHiddenClosures()
151 if base.Debug.DumpInlFuncProps != "" {
152 inlheur.DumpFuncProps(nil, base.Debug.DumpInlFuncProps, nil, inlineMaxBudget)
154 if goexperiment.NewInliner {
155 postProcessCallSites(p)
159 // InlineDecls applies inlining to the given batch of declarations.
160 func InlineDecls(p *pgo.Profile, funcs []*ir.Func, doInline bool) {
162 pgoInlinePrologue(p, funcs)
165 doCanInline := func(n *ir.Func, recursive bool, numfns int) {
166 if !recursive || numfns > 1 {
167 // We allow inlining if there is no
168 // recursion, or the recursion cycle is
169 // across more than one function.
172 if base.Flag.LowerM > 1 && n.OClosure == nil {
173 fmt.Printf("%v: cannot inline %v: recursive\n", ir.Line(n), n.Nname)
178 ir.VisitFuncsBottomUp(funcs, func(list []*ir.Func, recursive bool) {
179 numfns := numNonClosures(list)
180 // We visit functions within an SCC in fairly arbitrary order,
181 // so by computing inlinability for all functions in the SCC
182 // before performing any inlining, the results are less
183 // sensitive to the order within the SCC (see #58905 for an
186 // First compute inlinability for all functions in the SCC ...
187 for _, n := range list {
188 doCanInline(n, recursive, numfns)
190 // ... then make a second pass to do inlining of calls.
192 for _, n := range list {
199 // garbageCollectUnreferencedHiddenClosures makes a pass over all the
200 // top-level (non-hidden-closure) functions looking for nested closure
201 // functions that are reachable, then sweeps through the Target.Decls
202 // list and marks any non-reachable hidden closure function as dead.
203 // See issues #59404 and #59638 for more context.
204 func garbageCollectUnreferencedHiddenClosures() {
206 liveFuncs := make(map[*ir.Func]bool)
208 var markLiveFuncs func(fn *ir.Func)
209 markLiveFuncs = func(fn *ir.Func) {
214 ir.Visit(fn, func(n ir.Node) {
215 if clo, ok := n.(*ir.ClosureExpr); ok {
216 markLiveFuncs(clo.Func)
221 for i := 0; i < len(typecheck.Target.Funcs); i++ {
222 fn := typecheck.Target.Funcs[i]
223 if fn.IsHiddenClosure() {
229 for i := 0; i < len(typecheck.Target.Funcs); i++ {
230 fn := typecheck.Target.Funcs[i]
231 if !fn.IsHiddenClosure() {
234 if fn.IsDeadcodeClosure() {
240 fn.SetIsDeadcodeClosure(true)
241 if base.Flag.LowerM > 2 {
242 fmt.Printf("%v: unreferenced closure %v marked as dead\n", ir.Line(fn), fn)
244 if fn.Inl != nil && fn.LSym == nil {
245 ir.InitLSym(fn, true)
250 // inlineBudget determines the max budget for function 'fn' prior to
251 // analyzing the hairyness of the body of 'fn'. We pass in the pgo
252 // profile if available (which can change the budget), also a
253 // 'relaxed' flag, which expands the budget slightly to allow for the
254 // possibility that a call to the function might have its score
255 // adjusted downwards. If 'verbose' is set, then print a remark where
256 // we boost the budget due to PGO.
257 func inlineBudget(fn *ir.Func, profile *pgo.Profile, relaxed bool, verbose bool) int32 {
258 // Update the budget for profile-guided inlining.
259 budget := int32(inlineMaxBudget)
261 if n, ok := profile.WeightedCG.IRNodes[ir.LinkFuncName(fn)]; ok {
262 if _, ok := candHotCalleeMap[n]; ok {
263 budget = int32(inlineHotMaxBudget)
265 fmt.Printf("hot-node enabled increased budget=%v for func=%v\n", budget, ir.PkgFuncName(fn))
271 budget += inlineMaxBudget
276 // CanInline determines whether fn is inlineable.
277 // If so, CanInline saves copies of fn.Body and fn.Dcl in fn.Inl.
278 // fn and fn.Body will already have been typechecked.
279 func CanInline(fn *ir.Func, profile *pgo.Profile) {
281 base.Fatalf("CanInline no nname %+v", fn)
284 var funcProps *inlheur.FuncProps
285 if goexperiment.NewInliner || inlheur.UnitTesting() {
286 callCanInline := func(fn *ir.Func) { CanInline(fn, profile) }
287 funcProps = inlheur.AnalyzeFunc(fn, callCanInline, inlineMaxBudget)
290 var reason string // reason, if any, that the function was not inlined
291 if base.Flag.LowerM > 1 || logopt.Enabled() {
294 if base.Flag.LowerM > 1 {
295 fmt.Printf("%v: cannot inline %v: %s\n", ir.Line(fn), fn.Nname, reason)
297 if logopt.Enabled() {
298 logopt.LogOpt(fn.Pos(), "cannotInlineFunction", "inline", ir.FuncName(fn), reason)
304 reason = InlineImpossible(fn)
308 if fn.Typecheck() == 0 {
309 base.Fatalf("CanInline on non-typechecked function %v", fn)
313 if n.Func.InlinabilityChecked() {
316 defer n.Func.SetInlinabilityChecked(true)
318 cc := int32(inlineExtraCallCost)
319 if base.Flag.LowerL == 4 {
320 cc = 1 // this appears to yield better performance than 0.
323 // Used a "relaxed" inline budget if goexperiment.NewInliner is in
324 // effect, or if we're producing a debugging dump.
325 relaxed := goexperiment.NewInliner ||
326 (base.Debug.DumpInlFuncProps != "" ||
327 base.Debug.DumpInlCallSiteScores != 0)
329 // Compute the inline budget for this func.
330 budget := inlineBudget(fn, profile, relaxed, base.Debug.PGODebug > 0)
332 // At this point in the game the function we're looking at may
333 // have "stale" autos, vars that still appear in the Dcl list, but
334 // which no longer have any uses in the function body (due to
335 // elimination by deadcode). We'd like to exclude these dead vars
336 // when creating the "Inline.Dcl" field below; to accomplish this,
337 // the hairyVisitor below builds up a map of used/referenced
338 // locals, and we use this map to produce a pruned Inline.Dcl
339 // list. See issue 25459 for more context.
341 visitor := hairyVisitor{
343 isBigFunc: isBigFunc(fn),
349 if visitor.tooHairy(fn) {
350 reason = visitor.reason
354 n.Func.Inl = &ir.Inline{
355 Cost: budget - visitor.budget,
356 Dcl: pruneUnusedAutos(n.Func.Dcl, &visitor),
359 CanDelayResults: canDelayResults(fn),
361 if goexperiment.NewInliner {
362 n.Func.Inl.Properties = funcProps.SerializeToString()
365 if base.Flag.LowerM > 1 {
366 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))
367 } else if base.Flag.LowerM != 0 {
368 fmt.Printf("%v: can inline %v\n", ir.Line(fn), n)
370 if logopt.Enabled() {
371 logopt.LogOpt(fn.Pos(), "canInlineFunction", "inline", ir.FuncName(fn), fmt.Sprintf("cost: %d", budget-visitor.budget))
375 // InlineImpossible returns a non-empty reason string if fn is impossible to
376 // inline regardless of cost or contents.
377 func InlineImpossible(fn *ir.Func) string {
378 var reason string // reason, if any, that the function can not be inlined.
384 // If marked "go:noinline", don't inline.
385 if fn.Pragma&ir.Noinline != 0 {
386 reason = "marked go:noinline"
390 // If marked "go:norace" and -race compilation, don't inline.
391 if base.Flag.Race && fn.Pragma&ir.Norace != 0 {
392 reason = "marked go:norace with -race compilation"
396 // If marked "go:nocheckptr" and -d checkptr compilation, don't inline.
397 if base.Debug.Checkptr != 0 && fn.Pragma&ir.NoCheckPtr != 0 {
398 reason = "marked go:nocheckptr"
402 // If marked "go:cgo_unsafe_args", don't inline, since the function
403 // makes assumptions about its argument frame layout.
404 if fn.Pragma&ir.CgoUnsafeArgs != 0 {
405 reason = "marked go:cgo_unsafe_args"
409 // If marked as "go:uintptrkeepalive", don't inline, since the keep
410 // alive information is lost during inlining.
412 // TODO(prattmic): This is handled on calls during escape analysis,
413 // which is after inlining. Move prior to inlining so the keep-alive is
414 // maintained after inlining.
415 if fn.Pragma&ir.UintptrKeepAlive != 0 {
416 reason = "marked as having a keep-alive uintptr argument"
420 // If marked as "go:uintptrescapes", don't inline, since the escape
421 // information is lost during inlining.
422 if fn.Pragma&ir.UintptrEscapes != 0 {
423 reason = "marked as having an escaping uintptr argument"
427 // The nowritebarrierrec checker currently works at function
428 // granularity, so inlining yeswritebarrierrec functions can confuse it
429 // (#22342). As a workaround, disallow inlining them for now.
430 if fn.Pragma&ir.Yeswritebarrierrec != 0 {
431 reason = "marked go:yeswritebarrierrec"
435 // If a local function has no fn.Body (is defined outside of Go), cannot inline it.
436 // Imported functions don't have fn.Body but might have inline body in fn.Inl.
437 if len(fn.Body) == 0 && !typecheck.HaveInlineBody(fn) {
438 reason = "no function body"
445 // canDelayResults reports whether inlined calls to fn can delay
446 // declaring the result parameter until the "return" statement.
447 func canDelayResults(fn *ir.Func) bool {
448 // We can delay declaring+initializing result parameters if:
449 // (1) there's exactly one "return" statement in the inlined function;
450 // (2) it's not an empty return statement (#44355); and
451 // (3) the result parameters aren't named.
454 ir.VisitList(fn.Body, func(n ir.Node) {
455 if n, ok := n.(*ir.ReturnStmt); ok {
457 if len(n.Results) == 0 {
458 nreturns++ // empty return statement (case 2)
464 return false // not exactly one return statement (case 1)
467 // temporaries for return values.
468 for _, param := range fn.Type().Results() {
469 if sym := param.Sym; sym != nil && !sym.IsBlank() {
470 return false // found a named result parameter (case 3)
477 // hairyVisitor visits a function body to determine its inlining
478 // hairiness and whether or not it can be inlined.
479 type hairyVisitor struct {
480 // This is needed to access the current caller in the doNode function.
487 usedLocals ir.NameSet
488 do func(ir.Node) bool
492 func (v *hairyVisitor) tooHairy(fn *ir.Func) bool {
493 v.do = v.doNode // cache closure
494 if ir.DoChildren(fn, v.do) {
498 v.reason = fmt.Sprintf("function too complex: cost %d exceeds budget %d", v.maxBudget-v.budget, v.maxBudget)
504 // doNode visits n and its children, updates the state in v, and returns true if
505 // n makes the current function too hairy for inlining.
506 func (v *hairyVisitor) doNode(n ir.Node) bool {
512 // Call is okay if inlinable and we have the budget for the body.
514 n := n.(*ir.CallExpr)
515 // Functions that call runtime.getcaller{pc,sp} can not be inlined
516 // because getcaller{pc,sp} expect a pointer to the caller's first argument.
518 // runtime.throw is a "cheap call" like panic in normal code.
520 if n.Fun.Op() == ir.ONAME {
521 name := n.Fun.(*ir.Name)
522 if name.Class == ir.PFUNC {
523 switch fn := types.RuntimeSymName(name.Sym()); fn {
524 case "getcallerpc", "getcallersp":
525 v.reason = "call to " + fn
528 v.budget -= inlineExtraThrowCost
531 // Special case for reflect.noescape. It does just type
532 // conversions to appease the escape analysis, and doesn't
534 if types.ReflectSymName(name.Sym()) == "noescape" {
538 // Special case for coverage counter updates; although
539 // these correspond to real operations, we treat them as
540 // zero cost for the moment. This is due to the existence
541 // of tests that are sensitive to inlining-- if the
542 // insertion of coverage instrumentation happens to tip a
543 // given function over the threshold and move it from
544 // "inlinable" to "not-inlinable", this can cause changes
545 // in allocation behavior, which can then result in test
546 // failures (a good example is the TestAllocations in
548 if isAtomicCoverageCounterUpdate(n) {
552 if n.Fun.Op() == ir.OMETHEXPR {
553 if meth := ir.MethodExprName(n.Fun); meth != nil {
554 if fn := meth.Func; fn != nil {
556 if types.RuntimeSymName(s) == "heapBits.nextArena" {
557 // Special case: explicitly allow mid-stack inlining of
558 // runtime.heapBits.next even though it calls slow-path
559 // runtime.heapBits.nextArena.
562 // Special case: on architectures that can do unaligned loads,
563 // explicitly mark encoding/binary methods as cheap,
564 // because in practice they are, even though our inlining
565 // budgeting system does not see that. See issue 42958.
566 if base.Ctxt.Arch.CanMergeLoads && s.Pkg.Path == "encoding/binary" {
568 case "littleEndian.Uint64", "littleEndian.Uint32", "littleEndian.Uint16",
569 "bigEndian.Uint64", "bigEndian.Uint32", "bigEndian.Uint16",
570 "littleEndian.PutUint64", "littleEndian.PutUint32", "littleEndian.PutUint16",
571 "bigEndian.PutUint64", "bigEndian.PutUint32", "bigEndian.PutUint16",
572 "littleEndian.AppendUint64", "littleEndian.AppendUint32", "littleEndian.AppendUint16",
573 "bigEndian.AppendUint64", "bigEndian.AppendUint32", "bigEndian.AppendUint16":
581 break // treat like any other node, that is, cost of 1
584 if ir.IsIntrinsicCall(n) {
585 // Treat like any other node.
589 if callee := inlCallee(v.curFunc, n.Fun, v.profile); callee != nil && typecheck.HaveInlineBody(callee) {
590 // Check whether we'd actually inline this call. Set
591 // log == false since we aren't actually doing inlining
593 if canInlineCallExpr(v.curFunc, n, callee, v.isBigFunc, false) {
594 // mkinlcall would inline this call [1], so use
595 // the cost of the inline body as the cost of
596 // the call, as that is what will actually
597 // appear in the code.
599 // [1] This is almost a perfect match to the
600 // mkinlcall logic, except that
601 // canInlineCallExpr considers inlining cycles
602 // by looking at what has already been inlined.
603 // Since we haven't done any inlining yet we
605 v.budget -= callee.Inl.Cost
610 // Call cost for non-leaf inlining.
611 v.budget -= v.extraCallCost
614 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
616 // Things that are too hairy, irrespective of the budget
617 case ir.OCALL, ir.OCALLINTER:
618 // Call cost for non-leaf inlining.
619 v.budget -= v.extraCallCost
622 n := n.(*ir.UnaryExpr)
623 if n.X.Op() == ir.OCONVIFACE && n.X.(*ir.ConvExpr).Implicit() {
624 // Hack to keep reflect.flag.mustBe inlinable for TestIntendedInlining.
625 // Before CL 284412, these conversions were introduced later in the
626 // compiler, so they didn't count against inlining budget.
629 v.budget -= inlineExtraPanicCost
632 base.FatalfAt(n.Pos(), "ORECOVER missed typecheck")
634 // recover matches the argument frame pointer to find
635 // the right panic value, so it needs an argument frame.
636 v.reason = "call to recover"
640 if base.Debug.InlFuncsWithClosures == 0 {
641 v.reason = "not inlining functions with closures"
645 // TODO(danscales): Maybe make budget proportional to number of closure
647 //v.budget -= int32(len(n.(*ir.ClosureExpr).Func.ClosureVars) * 3)
648 // TODO(austin): However, if we're able to inline this closure into
649 // v.curFunc, then we actually pay nothing for the closure captures. We
650 // should try to account for that if we're going to account for captures.
653 case ir.OGO, ir.ODEFER, ir.OTAILCALL:
654 v.reason = "unhandled op " + n.Op().String()
658 v.budget -= inlineExtraAppendCost
661 n := n.(*ir.AddrExpr)
662 // Make "&s.f" cost 0 when f's offset is zero.
663 if dot, ok := n.X.(*ir.SelectorExpr); ok && (dot.Op() == ir.ODOT || dot.Op() == ir.ODOTPTR) {
664 if _, ok := dot.X.(*ir.Name); ok && dot.Selection.Offset == 0 {
665 v.budget += 2 // undo ir.OADDR+ir.ODOT/ir.ODOTPTR
670 // *(*X)(unsafe.Pointer(&x)) is low-cost
671 n := n.(*ir.StarExpr)
674 for ptr.Op() == ir.OCONVNOP {
675 ptr = ptr.(*ir.ConvExpr).X
677 if ptr.Op() == ir.OADDR {
678 v.budget += 1 // undo half of default cost of ir.ODEREF+ir.OADDR
682 // This doesn't produce code, but the children might.
683 v.budget++ // undo default cost
685 case ir.OFALL, ir.OTYPE:
686 // These nodes don't produce code; omit from inlining budget.
691 if ir.IsConst(n.Cond, constant.Bool) {
692 // This if and the condition cost nothing.
693 if doList(n.Init(), v.do) {
696 if ir.BoolVal(n.Cond) {
697 return doList(n.Body, v.do)
699 return doList(n.Else, v.do)
705 if n.Class == ir.PAUTO {
710 // The only OBLOCK we should see at this point is an empty one.
711 // In any event, let the visitList(n.List()) below take care of the statements,
712 // and don't charge for the OBLOCK itself. The ++ undoes the -- below.
715 case ir.OMETHVALUE, ir.OSLICELIT:
716 v.budget-- // Hack for toolstash -cmp.
719 v.budget++ // Hack for toolstash -cmp.
722 n := n.(*ir.AssignListStmt)
724 // Unified IR unconditionally rewrites:
735 // so that it can insert implicit conversions as necessary. To
736 // minimize impact to the existing inlining heuristics (in
737 // particular, to avoid breaking the existing inlinability regress
738 // tests), we need to compensate for this here.
740 // See also identical logic in isBigFunc.
741 if init := n.Rhs[0].Init(); len(init) == 1 {
742 if _, ok := init[0].(*ir.AssignListStmt); ok {
743 // 4 for each value, because each temporary variable now
744 // appears 3 times (DCL, LHS, RHS), plus an extra DCL node.
746 // 1 for the extra "tmp1, tmp2 = f()" assignment statement.
747 v.budget += 4*int32(len(n.Lhs)) + 1
752 // Special case for coverage counter updates and coverage
753 // function registrations. Although these correspond to real
754 // operations, we treat them as zero cost for the moment. This
755 // is primarily due to the existence of tests that are
756 // sensitive to inlining-- if the insertion of coverage
757 // instrumentation happens to tip a given function over the
758 // threshold and move it from "inlinable" to "not-inlinable",
759 // this can cause changes in allocation behavior, which can
760 // then result in test failures (a good example is the
761 // TestAllocations in crypto/ed25519).
762 n := n.(*ir.AssignStmt)
763 if n.X.Op() == ir.OINDEX && isIndexingCoverageCounter(n.X) {
770 // When debugging, don't stop early, to get full cost of inlining this function
771 if v.budget < 0 && base.Flag.LowerM < 2 && !logopt.Enabled() {
772 v.reason = "too expensive"
776 return ir.DoChildren(n, v.do)
779 func isBigFunc(fn *ir.Func) bool {
780 budget := inlineBigFunctionNodes
781 return ir.Any(fn, func(n ir.Node) bool {
782 // See logic in hairyVisitor.doNode, explaining unified IR's
783 // handling of "a, b = f()" assignments.
784 if n, ok := n.(*ir.AssignListStmt); ok && n.Op() == ir.OAS2 {
785 if init := n.Rhs[0].Init(); len(init) == 1 {
786 if _, ok := init[0].(*ir.AssignListStmt); ok {
787 budget += 4*len(n.Lhs) + 1
797 // InlineCalls/inlnode walks fn's statements and expressions and substitutes any
798 // calls made to inlineable functions. This is the external entry point.
799 func InlineCalls(fn *ir.Func, profile *pgo.Profile) {
800 if goexperiment.NewInliner && !fn.Wrapper() {
801 inlheur.ScoreCalls(fn)
803 if base.Debug.DumpInlFuncProps != "" && !fn.Wrapper() {
804 inlheur.DumpFuncProps(fn, base.Debug.DumpInlFuncProps,
805 func(fn *ir.Func) { CanInline(fn, profile) }, inlineMaxBudget)
809 bigCaller := isBigFunc(fn)
810 if bigCaller && base.Flag.LowerM > 1 {
811 fmt.Printf("%v: function %v considered 'big'; reducing max cost of inlinees\n", ir.Line(fn), fn)
813 var inlCalls []*ir.InlinedCallExpr
814 var edit func(ir.Node) ir.Node
815 edit = func(n ir.Node) ir.Node {
816 return inlnode(fn, n, bigCaller, &inlCalls, edit, profile)
818 ir.EditChildren(fn, edit)
820 // If we inlined any calls, we want to recursively visit their
821 // bodies for further inlining. However, we need to wait until
822 // *after* the original function body has been expanded, or else
823 // inlCallee can have false positives (e.g., #54632).
824 for len(inlCalls) > 0 {
826 inlCalls = inlCalls[1:]
827 ir.EditChildren(call, edit)
833 // inlnode recurses over the tree to find inlineable calls, which will
834 // be turned into OINLCALLs by mkinlcall. When the recursion comes
835 // back up will examine left, right, list, rlist, ninit, ntest, nincr,
836 // nbody and nelse and use one of the 4 inlconv/glue functions above
837 // to turn the OINLCALL into an expression, a statement, or patch it
838 // in to this nodes list or rlist as appropriate.
839 // NOTE it makes no sense to pass the glue functions down the
840 // recursion to the level where the OINLCALL gets created because they
841 // have to edit /this/ n, so you'd have to push that one down as well,
842 // but then you may as well do it here. so this is cleaner and
843 // shorter and less complicated.
844 // The result of inlnode MUST be assigned back to n, e.g.
846 // n.Left = inlnode(n.Left)
847 func inlnode(callerfn *ir.Func, n ir.Node, bigCaller bool, inlCalls *[]*ir.InlinedCallExpr, edit func(ir.Node) ir.Node, profile *pgo.Profile) ir.Node {
853 case ir.ODEFER, ir.OGO:
854 n := n.(*ir.GoDeferStmt)
855 switch call := n.Call; call.Op() {
857 base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
859 call := call.(*ir.CallExpr)
863 n := n.(*ir.TailCallStmt)
864 n.Call.NoInline = true // Not inline a tail call for now. Maybe we could inline it just like RETURN fn(arg)?
866 // TODO do them here (or earlier),
867 // so escape analysis can avoid more heapmoves.
871 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
873 n := n.(*ir.CallExpr)
874 if n.Fun.Op() == ir.OMETHEXPR {
875 // Prevent inlining some reflect.Value methods when using checkptr,
876 // even when package reflect was compiled without it (#35073).
877 if meth := ir.MethodExprName(n.Fun); meth != nil {
879 if base.Debug.Checkptr != 0 {
880 switch types.ReflectSymName(s) {
881 case "Value.UnsafeAddr", "Value.Pointer":
891 ir.EditChildren(n, edit)
893 // with all the branches out of the way, it is now time to
894 // transmogrify this node itself unless inhibited by the
895 // switch at the top of this function.
898 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
901 call := n.(*ir.CallExpr)
905 if base.Flag.LowerM > 3 {
906 fmt.Printf("%v:call to func %+v\n", ir.Line(n), call.Fun)
908 if ir.IsIntrinsicCall(call) {
911 if fn := inlCallee(callerfn, call.Fun, profile); fn != nil && typecheck.HaveInlineBody(fn) {
912 n = mkinlcall(callerfn, call, fn, bigCaller, inlCalls)
921 // inlCallee takes a function-typed expression and returns the underlying function ONAME
922 // that it refers to if statically known. Otherwise, it returns nil.
923 func inlCallee(caller *ir.Func, fn ir.Node, profile *pgo.Profile) (res *ir.Func) {
924 fn = ir.StaticValue(fn)
927 fn := fn.(*ir.SelectorExpr)
928 n := ir.MethodExprName(fn)
929 // Check that receiver type matches fn.X.
930 // TODO(mdempsky): Handle implicit dereference
931 // of pointer receiver argument?
932 if n == nil || !types.Identical(n.Type().Recv().Type, fn.X.Type()) {
938 if fn.Class == ir.PFUNC {
942 fn := fn.(*ir.ClosureExpr)
944 if len(c.ClosureVars) != 0 && c.ClosureVars[0].Outer.Curfn != caller {
945 return nil // inliner doesn't support inlining across closure frames
947 CanInline(c, profile)
955 // SSADumpInline gives the SSA back end a chance to dump the function
956 // when producing output for debugging the compiler itself.
957 var SSADumpInline = func(*ir.Func) {}
959 // InlineCall allows the inliner implementation to be overridden.
960 // If it returns nil, the function will not be inlined.
961 var InlineCall = func(callerfn *ir.Func, call *ir.CallExpr, fn *ir.Func, inlIndex int) *ir.InlinedCallExpr {
962 base.Fatalf("inline.InlineCall not overridden")
966 // inlineCostOK returns true if call n from caller to callee is cheap enough to
967 // inline. bigCaller indicates that caller is a big function.
969 // If inlineCostOK returns false, it also returns the max cost that the callee
971 func inlineCostOK(n *ir.CallExpr, caller, callee *ir.Func, bigCaller bool) (bool, int32) {
972 maxCost := int32(inlineMaxBudget)
974 // We use this to restrict inlining into very big functions.
975 // See issue 26546 and 17566.
976 maxCost = inlineBigFunctionMaxCost
979 metric := callee.Inl.Cost
980 if goexperiment.NewInliner {
981 score, ok := inlheur.GetCallSiteScore(caller, n)
983 metric = int32(score)
988 if metric <= maxCost {
989 // Simple case. Function is already cheap enough.
993 // We'll also allow inlining of hot functions below inlineHotMaxBudget,
994 // but only in small functions.
996 lineOffset := pgo.NodeLineOffset(n, caller)
997 csi := pgo.CallSiteInfo{LineOffset: lineOffset, Caller: caller}
998 if _, ok := candHotEdgeMap[csi]; !ok {
1000 return false, maxCost
1006 if base.Debug.PGODebug > 0 {
1007 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))
1009 return false, maxCost
1012 if metric > inlineHotMaxBudget {
1013 return false, inlineHotMaxBudget
1016 if !base.PGOHash.MatchPosWithInfo(n.Pos(), "inline", nil) {
1017 // De-selected by PGO Hash.
1018 return false, maxCost
1021 if base.Debug.PGODebug > 0 {
1022 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))
1028 // canInlineCallsite returns true if the call n from caller to callee can be
1029 // inlined. bigCaller indicates that caller is a big function. log indicates
1030 // that the 'cannot inline' reason should be logged.
1032 // Preconditions: CanInline(callee) has already been called.
1033 func canInlineCallExpr(callerfn *ir.Func, n *ir.CallExpr, callee *ir.Func, bigCaller bool, log bool) bool {
1034 if callee.Inl == nil {
1035 // callee is never inlinable.
1036 if log && logopt.Enabled() {
1037 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
1038 fmt.Sprintf("%s cannot be inlined", ir.PkgFuncName(callee)))
1043 if ok, maxCost := inlineCostOK(n, callerfn, callee, bigCaller); !ok {
1044 // callee cost too high for this call site.
1045 if log && logopt.Enabled() {
1046 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
1047 fmt.Sprintf("cost %d of %s exceeds max caller cost %d", callee.Inl.Cost, ir.PkgFuncName(callee), maxCost))
1052 if callee == callerfn {
1053 // Can't recursively inline a function into itself.
1054 if log && logopt.Enabled() {
1055 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", fmt.Sprintf("recursive call to %s", ir.FuncName(callerfn)))
1060 if base.Flag.Cfg.Instrumenting && types.IsNoInstrumentPkg(callee.Sym().Pkg) {
1061 // Runtime package must not be instrumented.
1062 // Instrument skips runtime package. However, some runtime code can be
1063 // inlined into other packages and instrumented there. To avoid this,
1064 // we disable inlining of runtime functions when instrumenting.
1065 // The example that we observed is inlining of LockOSThread,
1066 // which lead to false race reports on m contents.
1067 if log && logopt.Enabled() {
1068 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
1069 fmt.Sprintf("call to runtime function %s in instrumented build", ir.PkgFuncName(callee)))
1074 if base.Flag.Race && types.IsNoRacePkg(callee.Sym().Pkg) {
1075 if log && logopt.Enabled() {
1076 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
1077 fmt.Sprintf(`call to into "no-race" package function %s in race build`, ir.PkgFuncName(callee)))
1082 // Check if we've already inlined this function at this particular
1083 // call site, in order to stop inlining when we reach the beginning
1084 // of a recursion cycle again. We don't inline immediately recursive
1085 // functions, but allow inlining if there is a recursion cycle of
1086 // many functions. Most likely, the inlining will stop before we
1087 // even hit the beginning of the cycle again, but this catches the
1089 parent := base.Ctxt.PosTable.Pos(n.Pos()).Base().InliningIndex()
1090 sym := callee.Linksym()
1091 for inlIndex := parent; inlIndex >= 0; inlIndex = base.Ctxt.InlTree.Parent(inlIndex) {
1092 if base.Ctxt.InlTree.InlinedFunction(inlIndex) == sym {
1094 if base.Flag.LowerM > 1 {
1095 fmt.Printf("%v: cannot inline %v into %v: repeated recursive cycle\n", ir.Line(n), callee, ir.FuncName(callerfn))
1097 if logopt.Enabled() {
1098 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
1099 fmt.Sprintf("repeated recursive cycle to %s", ir.PkgFuncName(callee)))
1109 // If n is a OCALLFUNC node, and fn is an ONAME node for a
1110 // function with an inlinable body, return an OINLCALL node that can replace n.
1111 // The returned node's Ninit has the parameter assignments, the Nbody is the
1112 // inlined function body, and (List, Rlist) contain the (input, output)
1114 // The result of mkinlcall MUST be assigned back to n, e.g.
1116 // n.Left = mkinlcall(n.Left, fn, isddd)
1117 func mkinlcall(callerfn *ir.Func, n *ir.CallExpr, fn *ir.Func, bigCaller bool, inlCalls *[]*ir.InlinedCallExpr) ir.Node {
1118 if !canInlineCallExpr(callerfn, n, fn, bigCaller, true) {
1121 typecheck.AssertFixedCall(n)
1123 parent := base.Ctxt.PosTable.Pos(n.Pos()).Base().InliningIndex()
1125 inlIndex := base.Ctxt.InlTree.Add(parent, n.Pos(), sym, ir.FuncName(fn))
1127 closureInitLSym := func(n *ir.CallExpr, fn *ir.Func) {
1128 // The linker needs FuncInfo metadata for all inlined
1129 // functions. This is typically handled by gc.enqueueFunc
1130 // calling ir.InitLSym for all function declarations in
1131 // typecheck.Target.Decls (ir.UseClosure adds all closures to
1134 // However, non-trivial closures in Decls are ignored, and are
1135 // insteaded enqueued when walk of the calling function
1138 // This presents a problem for direct calls to closures.
1139 // Inlining will replace the entire closure definition with its
1140 // body, which hides the closure from walk and thus suppresses
1143 // Explicitly create a symbol early in this edge case to ensure
1144 // we keep this metadata.
1146 // TODO: Refactor to keep a reference so this can all be done
1149 if n.Op() != ir.OCALLFUNC {
1150 // Not a standard call.
1153 if n.Fun.Op() != ir.OCLOSURE {
1154 // Not a direct closure call.
1158 clo := n.Fun.(*ir.ClosureExpr)
1159 if ir.IsTrivialClosure(clo) {
1160 // enqueueFunc will handle trivial closures anyways.
1164 ir.InitLSym(fn, true)
1167 closureInitLSym(n, fn)
1169 if base.Flag.GenDwarfInl > 0 {
1170 if !sym.WasInlined() {
1171 base.Ctxt.DwFixups.SetPrecursorFunc(sym, fn)
1172 sym.Set(obj.AttrWasInlined, true)
1176 if base.Flag.LowerM != 0 {
1177 fmt.Printf("%v: inlining call to %v\n", ir.Line(n), fn)
1179 if base.Flag.LowerM > 2 {
1180 fmt.Printf("%v: Before inlining: %+v\n", ir.Line(n), n)
1183 res := InlineCall(callerfn, n, fn, inlIndex)
1186 base.FatalfAt(n.Pos(), "inlining call to %v failed", fn)
1189 if base.Flag.LowerM > 2 {
1190 fmt.Printf("%v: After inlining %+v\n\n", ir.Line(res), res)
1193 *inlCalls = append(*inlCalls, res)
1198 // CalleeEffects appends any side effects from evaluating callee to init.
1199 func CalleeEffects(init *ir.Nodes, callee ir.Node) {
1201 init.Append(ir.TakeInit(callee)...)
1203 switch callee.Op() {
1204 case ir.ONAME, ir.OCLOSURE, ir.OMETHEXPR:
1208 conv := callee.(*ir.ConvExpr)
1212 ic := callee.(*ir.InlinedCallExpr)
1213 init.Append(ic.Body.Take()...)
1214 callee = ic.SingleResult()
1217 base.FatalfAt(callee.Pos(), "unexpected callee expression: %v", callee)
1222 func pruneUnusedAutos(ll []*ir.Name, vis *hairyVisitor) []*ir.Name {
1223 s := make([]*ir.Name, 0, len(ll))
1224 for _, n := range ll {
1225 if n.Class == ir.PAUTO {
1226 if !vis.usedLocals.Has(n) {
1227 // TODO(mdempsky): Simplify code after confident that this
1228 // never happens anymore.
1229 base.FatalfAt(n.Pos(), "unused auto: %v", n)
1238 // numNonClosures returns the number of functions in list which are not closures.
1239 func numNonClosures(list []*ir.Func) int {
1241 for _, fn := range list {
1242 if fn.OClosure == nil {
1249 func doList(list []ir.Node, do func(ir.Node) bool) bool {
1250 for _, x := range list {
1260 // isIndexingCoverageCounter returns true if the specified node 'n' is indexing
1261 // into a coverage counter array.
1262 func isIndexingCoverageCounter(n ir.Node) bool {
1263 if n.Op() != ir.OINDEX {
1266 ixn := n.(*ir.IndexExpr)
1267 if ixn.X.Op() != ir.ONAME || !ixn.X.Type().IsArray() {
1270 nn := ixn.X.(*ir.Name)
1271 return nn.CoverageCounter()
1274 // isAtomicCoverageCounterUpdate examines the specified node to
1275 // determine whether it represents a call to sync/atomic.AddUint32 to
1276 // increment a coverage counter.
1277 func isAtomicCoverageCounterUpdate(cn *ir.CallExpr) bool {
1278 if cn.Fun.Op() != ir.ONAME {
1281 name := cn.Fun.(*ir.Name)
1282 if name.Class != ir.PFUNC {
1285 fn := name.Sym().Name
1286 if name.Sym().Pkg.Path != "sync/atomic" ||
1287 (fn != "AddUint32" && fn != "StoreUint32") {
1290 if len(cn.Args) != 2 || cn.Args[0].Op() != ir.OADDR {
1293 adn := cn.Args[0].(*ir.AddrExpr)
1294 v := isIndexingCoverageCounter(adn.X)
1298 func postProcessCallSites(profile *pgo.Profile) {
1299 if base.Debug.DumpInlCallSiteScores != 0 {
1300 budgetCallback := func(fn *ir.Func, prof *pgo.Profile) (int32, bool) {
1301 v := inlineBudget(fn, prof, false, false)
1302 return v, v == inlineHotMaxBudget
1304 inlheur.DumpInlCallSiteScores(profile, budgetCallback)