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 caninl 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.
34 "cmd/compile/internal/base"
35 "cmd/compile/internal/ir"
36 "cmd/compile/internal/logopt"
37 "cmd/compile/internal/typecheck"
38 "cmd/compile/internal/types"
43 // Inlining budget parameters, gathered in one place
46 inlineExtraAppendCost = 0
47 // default is to inline if there's at most one call. -l=4 overrides this by using 1 instead.
48 inlineExtraCallCost = 57 // 57 was benchmarked to provided most benefit with no bad surprises; see https://github.com/golang/go/issues/19348#issuecomment-439370742
49 inlineExtraPanicCost = 1 // do not penalize inlining panics.
50 inlineExtraThrowCost = inlineMaxBudget // with current (2018-05/1.11) code, inlining runtime.throw does not help.
52 inlineBigFunctionNodes = 5000 // Functions with this many nodes are considered "big".
53 inlineBigFunctionMaxCost = 20 // Max cost of inlinee when inlining into a "big" function.
56 // InlinePackage finds functions that can be inlined and clones them before walk expands them.
57 func InlinePackage() {
58 ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
59 numfns := numNonClosures(list)
60 for _, n := range list {
61 if !recursive || numfns > 1 {
62 // We allow inlining if there is no
63 // recursion, or the recursion cycle is
64 // across more than one function.
67 if base.Flag.LowerM > 1 {
68 fmt.Printf("%v: cannot inline %v: recursive\n", ir.Line(n), n.Nname)
76 // CanInline determines whether fn is inlineable.
77 // If so, CanInline saves copies of fn.Body and fn.Dcl in fn.Inl.
78 // fn and fn.Body will already have been typechecked.
79 func CanInline(fn *ir.Func) {
81 base.Fatalf("CanInline no nname %+v", fn)
84 var reason string // reason, if any, that the function was not inlined
85 if base.Flag.LowerM > 1 || logopt.Enabled() {
88 if base.Flag.LowerM > 1 {
89 fmt.Printf("%v: cannot inline %v: %s\n", ir.Line(fn), fn.Nname, reason)
92 logopt.LogOpt(fn.Pos(), "cannotInlineFunction", "inline", ir.FuncName(fn), reason)
98 // If marked "go:noinline", don't inline
99 if fn.Pragma&ir.Noinline != 0 {
100 reason = "marked go:noinline"
104 // If marked "go:norace" and -race compilation, don't inline.
105 if base.Flag.Race && fn.Pragma&ir.Norace != 0 {
106 reason = "marked go:norace with -race compilation"
110 // If marked "go:nocheckptr" and -d checkptr compilation, don't inline.
111 if base.Debug.Checkptr != 0 && fn.Pragma&ir.NoCheckPtr != 0 {
112 reason = "marked go:nocheckptr"
116 // If marked "go:cgo_unsafe_args", don't inline, since the
117 // function makes assumptions about its argument frame layout.
118 if fn.Pragma&ir.CgoUnsafeArgs != 0 {
119 reason = "marked go:cgo_unsafe_args"
123 // If marked as "go:uintptrkeepalive", don't inline, since the
124 // keep alive information is lost during inlining.
126 // TODO(prattmic): This is handled on calls during escape analysis,
127 // which is after inlining. Move prior to inlining so the keep-alive is
128 // maintained after inlining.
129 if fn.Pragma&ir.UintptrKeepAlive != 0 {
130 reason = "marked as having a keep-alive uintptr argument"
134 // If marked as "go:uintptrescapes", don't inline, since the
135 // escape information is lost during inlining.
136 if fn.Pragma&ir.UintptrEscapes != 0 {
137 reason = "marked as having an escaping uintptr argument"
141 // The nowritebarrierrec checker currently works at function
142 // granularity, so inlining yeswritebarrierrec functions can
143 // confuse it (#22342). As a workaround, disallow inlining
145 if fn.Pragma&ir.Yeswritebarrierrec != 0 {
146 reason = "marked go:yeswritebarrierrec"
150 // If fn has no body (is defined outside of Go), cannot inline it.
151 if len(fn.Body) == 0 {
152 reason = "no function body"
156 if fn.Typecheck() == 0 {
157 base.Fatalf("CanInline on non-typechecked function %v", fn)
161 if n.Func.InlinabilityChecked() {
164 defer n.Func.SetInlinabilityChecked(true)
166 cc := int32(inlineExtraCallCost)
167 if base.Flag.LowerL == 4 {
168 cc = 1 // this appears to yield better performance than 0.
171 // At this point in the game the function we're looking at may
172 // have "stale" autos, vars that still appear in the Dcl list, but
173 // which no longer have any uses in the function body (due to
174 // elimination by deadcode). We'd like to exclude these dead vars
175 // when creating the "Inline.Dcl" field below; to accomplish this,
176 // the hairyVisitor below builds up a map of used/referenced
177 // locals, and we use this map to produce a pruned Inline.Dcl
178 // list. See issue 25249 for more context.
180 visitor := hairyVisitor{
181 budget: inlineMaxBudget,
184 if visitor.tooHairy(fn) {
185 reason = visitor.reason
189 n.Func.Inl = &ir.Inline{
190 Cost: inlineMaxBudget - visitor.budget,
191 Dcl: pruneUnusedAutos(n.Defn.(*ir.Func).Dcl, &visitor),
192 Body: inlcopylist(fn.Body),
194 CanDelayResults: canDelayResults(fn),
197 if base.Flag.LowerM > 1 {
198 fmt.Printf("%v: can inline %v with cost %d as: %v { %v }\n", ir.Line(fn), n, inlineMaxBudget-visitor.budget, fn.Type(), ir.Nodes(n.Func.Inl.Body))
199 } else if base.Flag.LowerM != 0 {
200 fmt.Printf("%v: can inline %v\n", ir.Line(fn), n)
202 if logopt.Enabled() {
203 logopt.LogOpt(fn.Pos(), "canInlineFunction", "inline", ir.FuncName(fn), fmt.Sprintf("cost: %d", inlineMaxBudget-visitor.budget))
207 // canDelayResults reports whether inlined calls to fn can delay
208 // declaring the result parameter until the "return" statement.
209 func canDelayResults(fn *ir.Func) bool {
210 // We can delay declaring+initializing result parameters if:
211 // (1) there's exactly one "return" statement in the inlined function;
212 // (2) it's not an empty return statement (#44355); and
213 // (3) the result parameters aren't named.
216 ir.VisitList(fn.Body, func(n ir.Node) {
217 if n, ok := n.(*ir.ReturnStmt); ok {
219 if len(n.Results) == 0 {
220 nreturns++ // empty return statement (case 2)
226 return false // not exactly one return statement (case 1)
229 // temporaries for return values.
230 for _, param := range fn.Type().Results().FieldSlice() {
231 if sym := types.OrigSym(param.Sym); sym != nil && !sym.IsBlank() {
232 return false // found a named result parameter (case 3)
239 // hairyVisitor visits a function body to determine its inlining
240 // hairiness and whether or not it can be inlined.
241 type hairyVisitor struct {
245 usedLocals ir.NameSet
246 do func(ir.Node) bool
249 func (v *hairyVisitor) tooHairy(fn *ir.Func) bool {
250 v.do = v.doNode // cache closure
251 if ir.DoChildren(fn, v.do) {
255 v.reason = fmt.Sprintf("function too complex: cost %d exceeds budget %d", inlineMaxBudget-v.budget, inlineMaxBudget)
261 func (v *hairyVisitor) doNode(n ir.Node) bool {
266 // Call is okay if inlinable and we have the budget for the body.
268 n := n.(*ir.CallExpr)
269 // Functions that call runtime.getcaller{pc,sp} can not be inlined
270 // because getcaller{pc,sp} expect a pointer to the caller's first argument.
272 // runtime.throw is a "cheap call" like panic in normal code.
273 if n.X.Op() == ir.ONAME {
274 name := n.X.(*ir.Name)
275 if name.Class == ir.PFUNC && types.IsRuntimePkg(name.Sym().Pkg) {
276 fn := name.Sym().Name
277 if fn == "getcallerpc" || fn == "getcallersp" {
278 v.reason = "call to " + fn
282 v.budget -= inlineExtraThrowCost
287 if n.X.Op() == ir.OMETHEXPR {
288 if meth := ir.MethodExprName(n.X); meth != nil {
289 if fn := meth.Func; fn != nil {
292 if types.IsRuntimePkg(s.Pkg) && s.Name == "heapBits.nextArena" {
293 // Special case: explicitly allow mid-stack inlining of
294 // runtime.heapBits.next even though it calls slow-path
295 // runtime.heapBits.nextArena.
298 // Special case: on architectures that can do unaligned loads,
299 // explicitly mark encoding/binary methods as cheap,
300 // because in practice they are, even though our inlining
301 // budgeting system does not see that. See issue 42958.
302 if base.Ctxt.Arch.CanMergeLoads && s.Pkg.Path == "encoding/binary" {
304 case "littleEndian.Uint64", "littleEndian.Uint32", "littleEndian.Uint16",
305 "bigEndian.Uint64", "bigEndian.Uint32", "bigEndian.Uint16",
306 "littleEndian.PutUint64", "littleEndian.PutUint32", "littleEndian.PutUint16",
307 "bigEndian.PutUint64", "bigEndian.PutUint32", "bigEndian.PutUint16",
308 "littleEndian.AppendUint64", "littleEndian.AppendUint32", "littleEndian.AppendUint16",
309 "bigEndian.AppendUint64", "bigEndian.AppendUint32", "bigEndian.AppendUint16":
314 break // treat like any other node, that is, cost of 1
320 if ir.IsIntrinsicCall(n) {
321 // Treat like any other node.
325 if fn := inlCallee(n.X); fn != nil && typecheck.HaveInlineBody(fn) {
326 v.budget -= fn.Inl.Cost
330 // Call cost for non-leaf inlining.
331 v.budget -= v.extraCallCost
334 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
336 // Things that are too hairy, irrespective of the budget
337 case ir.OCALL, ir.OCALLINTER:
338 // Call cost for non-leaf inlining.
339 v.budget -= v.extraCallCost
342 n := n.(*ir.UnaryExpr)
343 if n.X.Op() == ir.OCONVIFACE && n.X.(*ir.ConvExpr).Implicit() {
344 // Hack to keep reflect.flag.mustBe inlinable for TestIntendedInlining.
345 // Before CL 284412, these conversions were introduced later in the
346 // compiler, so they didn't count against inlining budget.
349 v.budget -= inlineExtraPanicCost
352 // recover matches the argument frame pointer to find
353 // the right panic value, so it needs an argument frame.
354 v.reason = "call to recover"
358 if base.Debug.InlFuncsWithClosures == 0 {
359 v.reason = "not inlining functions with closures"
363 // TODO(danscales): Maybe make budget proportional to number of closure
365 //v.budget -= int32(len(n.(*ir.ClosureExpr).Func.ClosureVars) * 3)
367 // Scan body of closure (which DoChildren doesn't automatically
368 // do) to check for disallowed ops in the body and include the
369 // body in the budget.
370 if doList(n.(*ir.ClosureExpr).Func.Body, v.do) {
376 ir.ODCLTYPE, // can't print yet
378 v.reason = "unhandled op " + n.Op().String()
382 v.budget -= inlineExtraAppendCost
385 n := n.(*ir.AddrExpr)
386 // Make "&s.f" cost 0 when f's offset is zero.
387 if dot, ok := n.X.(*ir.SelectorExpr); ok && (dot.Op() == ir.ODOT || dot.Op() == ir.ODOTPTR) {
388 if _, ok := dot.X.(*ir.Name); ok && dot.Selection.Offset == 0 {
389 v.budget += 2 // undo ir.OADDR+ir.ODOT/ir.ODOTPTR
394 // *(*X)(unsafe.Pointer(&x)) is low-cost
395 n := n.(*ir.StarExpr)
398 for ptr.Op() == ir.OCONVNOP {
399 ptr = ptr.(*ir.ConvExpr).X
401 if ptr.Op() == ir.OADDR {
402 v.budget += 1 // undo half of default cost of ir.ODEREF+ir.OADDR
406 // This doesn't produce code, but the children might.
407 v.budget++ // undo default cost
409 case ir.ODCLCONST, ir.OFALL:
410 // These nodes don't produce code; omit from inlining budget.
415 if ir.IsConst(n.Cond, constant.Bool) {
416 // This if and the condition cost nothing.
417 if doList(n.Init(), v.do) {
420 if ir.BoolVal(n.Cond) {
421 return doList(n.Body, v.do)
423 return doList(n.Else, v.do)
429 if n.Class == ir.PAUTO {
434 // The only OBLOCK we should see at this point is an empty one.
435 // In any event, let the visitList(n.List()) below take care of the statements,
436 // and don't charge for the OBLOCK itself. The ++ undoes the -- below.
439 case ir.OMETHVALUE, ir.OSLICELIT:
440 v.budget-- // Hack for toolstash -cmp.
443 v.budget++ // Hack for toolstash -cmp.
446 n := n.(*ir.AssignListStmt)
448 // Unified IR unconditionally rewrites:
459 // so that it can insert implicit conversions as necessary. To
460 // minimize impact to the existing inlining heuristics (in
461 // particular, to avoid breaking the existing inlinability regress
462 // tests), we need to compensate for this here.
463 if base.Debug.Unified != 0 {
464 if init := n.Rhs[0].Init(); len(init) == 1 {
465 if _, ok := init[0].(*ir.AssignListStmt); ok {
466 // 4 for each value, because each temporary variable now
467 // appears 3 times (DCL, LHS, RHS), plus an extra DCL node.
469 // 1 for the extra "tmp1, tmp2 = f()" assignment statement.
470 v.budget += 4*int32(len(n.Lhs)) + 1
478 // When debugging, don't stop early, to get full cost of inlining this function
479 if v.budget < 0 && base.Flag.LowerM < 2 && !logopt.Enabled() {
480 v.reason = "too expensive"
484 return ir.DoChildren(n, v.do)
487 func isBigFunc(fn *ir.Func) bool {
488 budget := inlineBigFunctionNodes
489 return ir.Any(fn, func(n ir.Node) bool {
495 // inlcopylist (together with inlcopy) recursively copies a list of nodes, except
496 // that it keeps the same ONAME, OTYPE, and OLITERAL nodes. It is used for copying
497 // the body and dcls of an inlineable function.
498 func inlcopylist(ll []ir.Node) []ir.Node {
499 s := make([]ir.Node, len(ll))
500 for i, n := range ll {
506 // inlcopy is like DeepCopy(), but does extra work to copy closures.
507 func inlcopy(n ir.Node) ir.Node {
508 var edit func(ir.Node) ir.Node
509 edit = func(x ir.Node) ir.Node {
511 case ir.ONAME, ir.OTYPE, ir.OLITERAL, ir.ONIL:
515 ir.EditChildren(m, edit)
516 if x.Op() == ir.OCLOSURE {
517 x := x.(*ir.ClosureExpr)
518 // Need to save/duplicate x.Func.Nname,
519 // x.Func.Nname.Ntype, x.Func.Dcl, x.Func.ClosureVars, and
520 // x.Func.Body for iexport and local inlining.
522 newfn := ir.NewFunc(oldfn.Pos())
523 m.(*ir.ClosureExpr).Func = newfn
524 newfn.Nname = ir.NewNameAt(oldfn.Nname.Pos(), oldfn.Nname.Sym())
525 // XXX OK to share fn.Type() ??
526 newfn.Nname.SetType(oldfn.Nname.Type())
527 newfn.Body = inlcopylist(oldfn.Body)
528 // Make shallow copy of the Dcl and ClosureVar slices
529 newfn.Dcl = append([]*ir.Name(nil), oldfn.Dcl...)
530 newfn.ClosureVars = append([]*ir.Name(nil), oldfn.ClosureVars...)
537 // InlineCalls/inlnode walks fn's statements and expressions and substitutes any
538 // calls made to inlineable functions. This is the external entry point.
539 func InlineCalls(fn *ir.Func) {
542 maxCost := int32(inlineMaxBudget)
544 maxCost = inlineBigFunctionMaxCost
546 var inlCalls []*ir.InlinedCallExpr
547 var edit func(ir.Node) ir.Node
548 edit = func(n ir.Node) ir.Node {
549 return inlnode(n, maxCost, &inlCalls, edit)
551 ir.EditChildren(fn, edit)
553 // If we inlined any calls, we want to recursively visit their
554 // bodies for further inlining. However, we need to wait until
555 // *after* the original function body has been expanded, or else
556 // inlCallee can have false positives (e.g., #54632).
557 for len(inlCalls) > 0 {
559 inlCalls = inlCalls[1:]
560 ir.EditChildren(call, edit)
566 // inlnode recurses over the tree to find inlineable calls, which will
567 // be turned into OINLCALLs by mkinlcall. When the recursion comes
568 // back up will examine left, right, list, rlist, ninit, ntest, nincr,
569 // nbody and nelse and use one of the 4 inlconv/glue functions above
570 // to turn the OINLCALL into an expression, a statement, or patch it
571 // in to this nodes list or rlist as appropriate.
572 // NOTE it makes no sense to pass the glue functions down the
573 // recursion to the level where the OINLCALL gets created because they
574 // have to edit /this/ n, so you'd have to push that one down as well,
575 // but then you may as well do it here. so this is cleaner and
576 // shorter and less complicated.
577 // The result of inlnode MUST be assigned back to n, e.g.
579 // n.Left = inlnode(n.Left)
580 func inlnode(n ir.Node, maxCost int32, inlCalls *[]*ir.InlinedCallExpr, edit func(ir.Node) ir.Node) ir.Node {
586 case ir.ODEFER, ir.OGO:
587 n := n.(*ir.GoDeferStmt)
588 switch call := n.Call; call.Op() {
590 base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
592 call := call.(*ir.CallExpr)
596 n := n.(*ir.TailCallStmt)
597 n.Call.NoInline = true // Not inline a tail call for now. Maybe we could inline it just like RETURN fn(arg)?
599 // TODO do them here (or earlier),
600 // so escape analysis can avoid more heapmoves.
604 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
606 n := n.(*ir.CallExpr)
607 if n.X.Op() == ir.OMETHEXPR {
608 // Prevent inlining some reflect.Value methods when using checkptr,
609 // even when package reflect was compiled without it (#35073).
610 if meth := ir.MethodExprName(n.X); meth != nil {
612 if base.Debug.Checkptr != 0 && types.IsReflectPkg(s.Pkg) && (s.Name == "Value.UnsafeAddr" || s.Name == "Value.Pointer") {
621 ir.EditChildren(n, edit)
623 // with all the branches out of the way, it is now time to
624 // transmogrify this node itself unless inhibited by the
625 // switch at the top of this function.
628 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
631 call := n.(*ir.CallExpr)
635 if base.Flag.LowerM > 3 {
636 fmt.Printf("%v:call to func %+v\n", ir.Line(n), call.X)
638 if ir.IsIntrinsicCall(call) {
641 if fn := inlCallee(call.X); fn != nil && typecheck.HaveInlineBody(fn) {
642 n = mkinlcall(call, fn, maxCost, inlCalls, edit)
651 // inlCallee takes a function-typed expression and returns the underlying function ONAME
652 // that it refers to if statically known. Otherwise, it returns nil.
653 func inlCallee(fn ir.Node) *ir.Func {
654 fn = ir.StaticValue(fn)
657 fn := fn.(*ir.SelectorExpr)
658 n := ir.MethodExprName(fn)
659 // Check that receiver type matches fn.X.
660 // TODO(mdempsky): Handle implicit dereference
661 // of pointer receiver argument?
662 if n == nil || !types.Identical(n.Type().Recv().Type, fn.X.Type()) {
668 if fn.Class == ir.PFUNC {
672 fn := fn.(*ir.ClosureExpr)
680 func inlParam(t *types.Field, as ir.InitNode, inlvars map[*ir.Name]*ir.Name) ir.Node {
684 n := t.Nname.(*ir.Name)
690 base.Fatalf("missing inlvar for %v", n)
692 as.PtrInit().Append(ir.NewDecl(base.Pos, ir.ODCL, inlvar))
693 inlvar.Name().Defn = as
699 // SSADumpInline gives the SSA back end a chance to dump the function
700 // when producing output for debugging the compiler itself.
701 var SSADumpInline = func(*ir.Func) {}
703 // InlineCall allows the inliner implementation to be overridden.
704 // If it returns nil, the function will not be inlined.
705 var InlineCall = oldInlineCall
707 // If n is a OCALLFUNC node, and fn is an ONAME node for a
708 // function with an inlinable body, return an OINLCALL node that can replace n.
709 // The returned node's Ninit has the parameter assignments, the Nbody is the
710 // inlined function body, and (List, Rlist) contain the (input, output)
712 // The result of mkinlcall MUST be assigned back to n, e.g.
714 // n.Left = mkinlcall(n.Left, fn, isddd)
715 func mkinlcall(n *ir.CallExpr, fn *ir.Func, maxCost int32, inlCalls *[]*ir.InlinedCallExpr, edit func(ir.Node) ir.Node) ir.Node {
717 if logopt.Enabled() {
718 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
719 fmt.Sprintf("%s cannot be inlined", ir.PkgFuncName(fn)))
723 if fn.Inl.Cost > maxCost {
724 // The inlined function body is too big. Typically we use this check to restrict
725 // inlining into very big functions. See issue 26546 and 17566.
726 if logopt.Enabled() {
727 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
728 fmt.Sprintf("cost %d of %s exceeds max large caller cost %d", fn.Inl.Cost, ir.PkgFuncName(fn), maxCost))
733 if fn == ir.CurFunc {
734 // Can't recursively inline a function into itself.
735 if logopt.Enabled() {
736 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", fmt.Sprintf("recursive call to %s", ir.FuncName(ir.CurFunc)))
741 // The non-unified frontend has issues with inlining and shape parameters.
742 if base.Debug.Unified == 0 {
743 // Don't inline a function fn that has no shape parameters, but is passed at
744 // least one shape arg. This means we must be inlining a non-generic function
745 // fn that was passed into a generic function, and can be called with a shape
746 // arg because it matches an appropriate type parameters. But fn may include
747 // an interface conversion (that may be applied to a shape arg) that was not
748 // apparent when we first created the instantiation of the generic function.
749 // We can't handle this if we actually do the inlining, since we want to know
750 // all interface conversions immediately after stenciling. So, we avoid
751 // inlining in this case, see issue #49309. (1)
753 // See discussion on go.dev/cl/406475 for more background.
754 if !fn.Type().Params().HasShape() {
755 for _, arg := range n.Args {
756 if arg.Type().HasShape() {
757 if logopt.Enabled() {
758 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
759 fmt.Sprintf("inlining function %v has no-shape params with shape args", ir.FuncName(fn)))
765 // Don't inline a function fn that has shape parameters, but is passed no shape arg.
766 // See comments (1) above, and issue #51909.
767 inlineable := len(n.Args) == 0 // Function has shape in type, with no arguments can always be inlined.
768 for _, arg := range n.Args {
769 if arg.Type().HasShape() {
775 if logopt.Enabled() {
776 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
777 fmt.Sprintf("inlining function %v has shape params with no-shape args", ir.FuncName(fn)))
784 if base.Flag.Cfg.Instrumenting && types.IsRuntimePkg(fn.Sym().Pkg) {
785 // Runtime package must not be instrumented.
786 // Instrument skips runtime package. However, some runtime code can be
787 // inlined into other packages and instrumented there. To avoid this,
788 // we disable inlining of runtime functions when instrumenting.
789 // The example that we observed is inlining of LockOSThread,
790 // which lead to false race reports on m contents.
794 parent := base.Ctxt.PosTable.Pos(n.Pos()).Base().InliningIndex()
797 // Check if we've already inlined this function at this particular
798 // call site, in order to stop inlining when we reach the beginning
799 // of a recursion cycle again. We don't inline immediately recursive
800 // functions, but allow inlining if there is a recursion cycle of
801 // many functions. Most likely, the inlining will stop before we
802 // even hit the beginning of the cycle again, but this catches the
804 for inlIndex := parent; inlIndex >= 0; inlIndex = base.Ctxt.InlTree.Parent(inlIndex) {
805 if base.Ctxt.InlTree.InlinedFunction(inlIndex) == sym {
806 if base.Flag.LowerM > 1 {
807 fmt.Printf("%v: cannot inline %v into %v: repeated recursive cycle\n", ir.Line(n), fn, ir.FuncName(ir.CurFunc))
813 typecheck.FixVariadicCall(n)
815 inlIndex := base.Ctxt.InlTree.Add(parent, n.Pos(), sym)
817 if base.Flag.GenDwarfInl > 0 {
818 if !sym.WasInlined() {
819 base.Ctxt.DwFixups.SetPrecursorFunc(sym, fn)
820 sym.Set(obj.AttrWasInlined, true)
824 if base.Flag.LowerM != 0 {
825 fmt.Printf("%v: inlining call to %v\n", ir.Line(n), fn)
827 if base.Flag.LowerM > 2 {
828 fmt.Printf("%v: Before inlining: %+v\n", ir.Line(n), n)
831 res := InlineCall(n, fn, inlIndex)
833 base.FatalfAt(n.Pos(), "inlining call to %v failed", fn)
836 if base.Flag.LowerM > 2 {
837 fmt.Printf("%v: After inlining %+v\n\n", ir.Line(res), res)
840 *inlCalls = append(*inlCalls, res)
845 // CalleeEffects appends any side effects from evaluating callee to init.
846 func CalleeEffects(init *ir.Nodes, callee ir.Node) {
848 init.Append(ir.TakeInit(callee)...)
851 case ir.ONAME, ir.OCLOSURE, ir.OMETHEXPR:
855 conv := callee.(*ir.ConvExpr)
859 ic := callee.(*ir.InlinedCallExpr)
860 init.Append(ic.Body.Take()...)
861 callee = ic.SingleResult()
864 base.FatalfAt(callee.Pos(), "unexpected callee expression: %v", callee)
869 // oldInlineCall creates an InlinedCallExpr to replace the given call
870 // expression. fn is the callee function to be inlined. inlIndex is
871 // the inlining tree position index, for use with src.NewInliningBase
872 // when rewriting positions.
873 func oldInlineCall(call *ir.CallExpr, fn *ir.Func, inlIndex int) *ir.InlinedCallExpr {
874 if base.Debug.TypecheckInl == 0 {
875 typecheck.ImportedBody(fn)
882 // For normal function calls, the function callee expression
883 // may contain side effects. Make sure to preserve these,
884 // if necessary (#42703).
885 if call.Op() == ir.OCALLFUNC {
886 CalleeEffects(&ninit, call.X)
889 // Make temp names to use instead of the originals.
890 inlvars := make(map[*ir.Name]*ir.Name)
892 // record formals/locals for later post-processing
893 var inlfvars []*ir.Name
895 for _, ln := range fn.Inl.Dcl {
896 if ln.Op() != ir.ONAME {
899 if ln.Class == ir.PPARAMOUT { // return values handled below.
902 inlf := typecheck.Expr(inlvar(ln)).(*ir.Name)
904 if base.Flag.GenDwarfInl > 0 {
905 if ln.Class == ir.PPARAM {
906 inlf.Name().SetInlFormal(true)
908 inlf.Name().SetInlLocal(true)
910 inlf.SetPos(ln.Pos())
911 inlfvars = append(inlfvars, inlf)
915 // We can delay declaring+initializing result parameters if:
916 // temporaries for return values.
917 var retvars []ir.Node
918 for i, t := range fn.Type().Results().Fields().Slice() {
920 if nn := t.Nname; nn != nil && !ir.IsBlank(nn.(*ir.Name)) && !strings.HasPrefix(nn.Sym().Name, "~r") {
923 m = typecheck.Expr(m).(*ir.Name)
926 // anonymous return values, synthesize names for use in assignment that replaces return
930 if base.Flag.GenDwarfInl > 0 {
931 // Don't update the src.Pos on a return variable if it
932 // was manufactured by the inliner (e.g. "~R2"); such vars
933 // were not part of the original callee.
934 if !strings.HasPrefix(m.Sym().Name, "~R") {
935 m.Name().SetInlFormal(true)
937 inlfvars = append(inlfvars, m)
941 retvars = append(retvars, m)
944 // Assign arguments to the parameters' temp names.
945 as := ir.NewAssignListStmt(base.Pos, ir.OAS2, nil, nil)
947 if call.Op() == ir.OCALLMETH {
948 base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
950 as.Rhs.Append(call.Args...)
952 if recv := fn.Type().Recv(); recv != nil {
953 as.Lhs.Append(inlParam(recv, as, inlvars))
955 for _, param := range fn.Type().Params().Fields().Slice() {
956 as.Lhs.Append(inlParam(param, as, inlvars))
959 if len(as.Rhs) != 0 {
960 ninit.Append(typecheck.Stmt(as))
963 if !fn.Inl.CanDelayResults {
964 // Zero the return parameters.
965 for _, n := range retvars {
966 ninit.Append(ir.NewDecl(base.Pos, ir.ODCL, n.(*ir.Name)))
967 ras := ir.NewAssignStmt(base.Pos, n, nil)
968 ninit.Append(typecheck.Stmt(ras))
972 retlabel := typecheck.AutoLabel(".i")
976 // Add an inline mark just before the inlined body.
977 // This mark is inline in the code so that it's a reasonable spot
978 // to put a breakpoint. Not sure if that's really necessary or not
979 // (in which case it could go at the end of the function instead).
981 ninit.Append(ir.NewInlineMarkStmt(call.Pos().WithIsStmt(), int64(inlIndex)))
987 defnMarker: ir.NilExpr{},
988 bases: make(map[*src.PosBase]*src.PosBase),
989 newInlIndex: inlIndex,
992 subst.edit = subst.node
994 body := subst.list(ir.Nodes(fn.Inl.Body))
996 lab := ir.NewLabelStmt(base.Pos, retlabel)
997 body = append(body, lab)
999 if base.Flag.GenDwarfInl > 0 {
1000 for _, v := range inlfvars {
1001 v.SetPos(subst.updatedPos(v.Pos()))
1005 //dumplist("ninit post", ninit);
1007 res := ir.NewInlinedCallExpr(base.Pos, body, retvars)
1009 res.SetType(call.Type())
1014 // Every time we expand a function we generate a new set of tmpnames,
1015 // PAUTO's in the calling functions, and link them off of the
1016 // PPARAM's, PAUTOS and PPARAMOUTs of the called function.
1017 func inlvar(var_ *ir.Name) *ir.Name {
1018 if base.Flag.LowerM > 3 {
1019 fmt.Printf("inlvar %+v\n", var_)
1022 n := typecheck.NewName(var_.Sym())
1023 n.SetType(var_.Type())
1027 n.SetAutoTemp(var_.AutoTemp())
1028 n.Curfn = ir.CurFunc // the calling function, not the called one
1029 n.SetAddrtaken(var_.Addrtaken())
1031 ir.CurFunc.Dcl = append(ir.CurFunc.Dcl, n)
1035 // Synthesize a variable to store the inlined function's results in.
1036 func retvar(t *types.Field, i int) *ir.Name {
1037 n := typecheck.NewName(typecheck.LookupNum("~R", i))
1042 n.Curfn = ir.CurFunc // the calling function, not the called one
1043 ir.CurFunc.Dcl = append(ir.CurFunc.Dcl, n)
1047 // The inlsubst type implements the actual inlining of a single
1049 type inlsubst struct {
1050 // Target of the goto substituted in place of a return.
1053 // Temporary result variables.
1056 inlvars map[*ir.Name]*ir.Name
1057 // defnMarker is used to mark a Node for reassignment.
1058 // inlsubst.clovar set this during creating new ONAME.
1059 // inlsubst.node will set the correct Defn for inlvar.
1060 defnMarker ir.NilExpr
1062 // bases maps from original PosBase to PosBase with an extra
1063 // inlined call frame.
1064 bases map[*src.PosBase]*src.PosBase
1066 // newInlIndex is the index of the inlined call frame to
1067 // insert for inlined nodes.
1070 edit func(ir.Node) ir.Node // cached copy of subst.node method value closure
1072 // If non-nil, we are inside a closure inside the inlined function, and
1073 // newclofn is the Func of the new inlined closure.
1076 fn *ir.Func // For debug -- the func that is being inlined
1078 // If true, then don't update source positions during substitution
1079 // (retain old source positions).
1083 // list inlines a list of nodes.
1084 func (subst *inlsubst) list(ll ir.Nodes) []ir.Node {
1085 s := make([]ir.Node, 0, len(ll))
1086 for _, n := range ll {
1087 s = append(s, subst.node(n))
1092 // fields returns a list of the fields of a struct type representing receiver,
1093 // params, or results, after duplicating the field nodes and substituting the
1094 // Nname nodes inside the field nodes.
1095 func (subst *inlsubst) fields(oldt *types.Type) []*types.Field {
1096 oldfields := oldt.FieldSlice()
1097 newfields := make([]*types.Field, len(oldfields))
1098 for i := range oldfields {
1099 newfields[i] = oldfields[i].Copy()
1100 if oldfields[i].Nname != nil {
1101 newfields[i].Nname = subst.node(oldfields[i].Nname.(*ir.Name))
1107 // clovar creates a new ONAME node for a local variable or param of a closure
1108 // inside a function being inlined.
1109 func (subst *inlsubst) clovar(n *ir.Name) *ir.Name {
1110 m := ir.NewNameAt(n.Pos(), n.Sym())
1114 if n.IsClosureVar() {
1115 m.SetIsClosureVar(true)
1118 m.SetAddrtaken(true)
1125 m.Curfn = subst.newclofn
1127 switch defn := n.Defn.(type) {
1131 if !n.IsClosureVar() {
1132 base.FatalfAt(n.Pos(), "want closure variable, got: %+v", n)
1134 if n.Sym().Pkg != types.LocalPkg {
1135 // If the closure came from inlining a function from
1136 // another package, must change package of captured
1137 // variable to localpkg, so that the fields of the closure
1138 // struct are local package and can be accessed even if
1139 // name is not exported. If you disable this code, you can
1140 // reproduce the problem by running 'go test
1141 // go/internal/srcimporter'. TODO(mdempsky) - maybe change
1142 // how we create closure structs?
1143 m.SetSym(types.LocalPkg.Lookup(n.Sym().Name))
1145 // Make sure any inlvar which is the Defn
1146 // of an ONAME closure var is rewritten
1147 // during inlining. Don't substitute
1148 // if Defn node is outside inlined function.
1149 if subst.inlvars[n.Defn.(*ir.Name)] != nil {
1150 m.Defn = subst.node(n.Defn)
1152 case *ir.AssignStmt, *ir.AssignListStmt:
1153 // Mark node for reassignment at the end of inlsubst.node.
1154 m.Defn = &subst.defnMarker
1155 case *ir.TypeSwitchGuard:
1156 // TODO(mdempsky): Set m.Defn properly. See discussion on #45743.
1158 // TODO: Set m.Defn properly if we support inlining range statement in the future.
1160 base.FatalfAt(n.Pos(), "unexpected Defn: %+v", defn)
1164 // Either the outer variable is defined in function being inlined,
1165 // and we will replace it with the substituted variable, or it is
1166 // defined outside the function being inlined, and we should just
1167 // skip the outer variable (the closure variable of the function
1169 s := subst.node(n.Outer).(*ir.Name)
1178 // closure does the necessary substitions for a ClosureExpr n and returns the new
1180 func (subst *inlsubst) closure(n *ir.ClosureExpr) ir.Node {
1181 // Prior to the subst edit, set a flag in the inlsubst to indicate
1182 // that we don't want to update the source positions in the new
1183 // closure function. If we do this, it will appear that the
1184 // closure itself has things inlined into it, which is not the
1185 // case. See issue #46234 for more details. At the same time, we
1186 // do want to update the position in the new ClosureExpr (which is
1187 // part of the function we're working on). See #49171 for an
1188 // example of what happens if we miss that update.
1189 newClosurePos := subst.updatedPos(n.Pos())
1190 defer func(prev bool) { subst.noPosUpdate = prev }(subst.noPosUpdate)
1191 subst.noPosUpdate = true
1193 //fmt.Printf("Inlining func %v with closure into %v\n", subst.fn, ir.FuncName(ir.CurFunc))
1196 newfn := ir.NewClosureFunc(oldfn.Pos(), true)
1198 if subst.newclofn != nil {
1199 //fmt.Printf("Inlining a closure with a nested closure\n")
1201 prevxfunc := subst.newclofn
1203 // Mark that we are now substituting within a closure (within the
1204 // inlined function), and create new nodes for all the local
1205 // vars/params inside this closure.
1206 subst.newclofn = newfn
1208 newfn.ClosureVars = nil
1209 for _, oldv := range oldfn.Dcl {
1210 newv := subst.clovar(oldv)
1211 subst.inlvars[oldv] = newv
1212 newfn.Dcl = append(newfn.Dcl, newv)
1214 for _, oldv := range oldfn.ClosureVars {
1215 newv := subst.clovar(oldv)
1216 subst.inlvars[oldv] = newv
1217 newfn.ClosureVars = append(newfn.ClosureVars, newv)
1220 // Need to replace ONAME nodes in
1221 // newfn.Type().FuncType().Receiver/Params/Results.FieldSlice().Nname
1222 oldt := oldfn.Type()
1223 newrecvs := subst.fields(oldt.Recvs())
1224 var newrecv *types.Field
1225 if len(newrecvs) > 0 {
1226 newrecv = newrecvs[0]
1228 newt := types.NewSignature(oldt.Pkg(), newrecv,
1229 nil, subst.fields(oldt.Params()), subst.fields(oldt.Results()))
1231 newfn.Nname.SetType(newt)
1232 newfn.Body = subst.list(oldfn.Body)
1234 // Remove the nodes for the current closure from subst.inlvars
1235 for _, oldv := range oldfn.Dcl {
1236 delete(subst.inlvars, oldv)
1238 for _, oldv := range oldfn.ClosureVars {
1239 delete(subst.inlvars, oldv)
1241 // Go back to previous closure func
1242 subst.newclofn = prevxfunc
1244 // Actually create the named function for the closure, now that
1245 // the closure is inlined in a specific function.
1246 newclo := newfn.OClosure
1247 newclo.SetPos(newClosurePos)
1248 newclo.SetInit(subst.list(n.Init()))
1249 return typecheck.Expr(newclo)
1252 // node recursively copies a node from the saved pristine body of the
1253 // inlined function, substituting references to input/output
1254 // parameters with ones to the tmpnames, and substituting returns with
1255 // assignments to the output.
1256 func (subst *inlsubst) node(n ir.Node) ir.Node {
1265 // Handle captured variables when inlining closures.
1266 if n.IsClosureVar() && subst.newclofn == nil {
1269 // Deal with case where sequence of closures are inlined.
1270 // TODO(danscales) - write test case to see if we need to
1271 // go up multiple levels.
1272 if o.Curfn != ir.CurFunc {
1276 // make sure the outer param matches the inlining location
1277 if o == nil || o.Curfn != ir.CurFunc {
1278 base.Fatalf("%v: unresolvable capture %v\n", ir.Line(n), n)
1281 if base.Flag.LowerM > 2 {
1282 fmt.Printf("substituting captured name %+v -> %+v\n", n, o)
1287 if inlvar := subst.inlvars[n]; inlvar != nil { // These will be set during inlnode
1288 if base.Flag.LowerM > 2 {
1289 fmt.Printf("substituting name %+v -> %+v\n", n, inlvar)
1294 if base.Flag.LowerM > 2 {
1295 fmt.Printf("not substituting name %+v\n", n)
1300 n := n.(*ir.SelectorExpr)
1303 case ir.OLITERAL, ir.ONIL, ir.OTYPE:
1304 // If n is a named constant or type, we can continue
1305 // using it in the inline copy. Otherwise, make a copy
1306 // so we can update the line number.
1312 if subst.newclofn != nil {
1313 // Don't do special substitutions if inside a closure
1316 // Because of the above test for subst.newclofn,
1317 // this return is guaranteed to belong to the current inlined function.
1318 n := n.(*ir.ReturnStmt)
1319 init := subst.list(n.Init())
1320 if len(subst.retvars) != 0 && len(n.Results) != 0 {
1321 as := ir.NewAssignListStmt(base.Pos, ir.OAS2, nil, nil)
1323 // Make a shallow copy of retvars.
1324 // Otherwise OINLCALL.Rlist will be the same list,
1325 // and later walk and typecheck may clobber it.
1326 for _, n := range subst.retvars {
1329 as.Rhs = subst.list(n.Results)
1331 if subst.fn.Inl.CanDelayResults {
1332 for _, n := range as.Lhs {
1333 as.PtrInit().Append(ir.NewDecl(base.Pos, ir.ODCL, n.(*ir.Name)))
1338 init = append(init, typecheck.Stmt(as))
1340 init = append(init, ir.NewBranchStmt(base.Pos, ir.OGOTO, subst.retlabel))
1341 typecheck.Stmts(init)
1342 return ir.NewBlockStmt(base.Pos, init)
1344 case ir.OGOTO, ir.OBREAK, ir.OCONTINUE:
1345 if subst.newclofn != nil {
1346 // Don't do special substitutions if inside a closure
1349 n := n.(*ir.BranchStmt)
1350 m := ir.Copy(n).(*ir.BranchStmt)
1351 m.SetPos(subst.updatedPos(m.Pos()))
1353 m.Label = translateLabel(n.Label)
1357 if subst.newclofn != nil {
1358 // Don't do special substitutions if inside a closure
1361 n := n.(*ir.LabelStmt)
1362 m := ir.Copy(n).(*ir.LabelStmt)
1363 m.SetPos(subst.updatedPos(m.Pos()))
1365 m.Label = translateLabel(n.Label)
1369 return subst.closure(n.(*ir.ClosureExpr))
1374 m.SetPos(subst.updatedPos(m.Pos()))
1375 ir.EditChildren(m, subst.edit)
1377 if subst.newclofn == nil {
1378 // Translate any label on FOR, RANGE loops, SWITCH or SELECT
1381 m := m.(*ir.ForStmt)
1382 m.Label = translateLabel(m.Label)
1386 m := m.(*ir.RangeStmt)
1387 m.Label = translateLabel(m.Label)
1391 m := m.(*ir.SwitchStmt)
1392 m.Label = translateLabel(m.Label)
1396 m := m.(*ir.SelectStmt)
1397 m.Label = translateLabel(m.Label)
1402 switch m := m.(type) {
1403 case *ir.AssignStmt:
1404 if lhs, ok := m.X.(*ir.Name); ok && lhs.Defn == &subst.defnMarker {
1407 case *ir.AssignListStmt:
1408 for _, lhs := range m.Lhs {
1409 if lhs, ok := lhs.(*ir.Name); ok && lhs.Defn == &subst.defnMarker {
1418 // translateLabel makes a label from an inlined function (if non-nil) be unique by
1419 // adding "·inlgen".
1420 func translateLabel(l *types.Sym) *types.Sym {
1424 p := fmt.Sprintf("%s·%d", l.Name, inlgen)
1425 return typecheck.Lookup(p)
1428 func (subst *inlsubst) updatedPos(xpos src.XPos) src.XPos {
1429 if subst.noPosUpdate {
1432 pos := base.Ctxt.PosTable.Pos(xpos)
1433 oldbase := pos.Base() // can be nil
1434 newbase := subst.bases[oldbase]
1436 newbase = src.NewInliningBase(oldbase, subst.newInlIndex)
1437 subst.bases[oldbase] = newbase
1439 pos.SetBase(newbase)
1440 return base.Ctxt.PosTable.XPos(pos)
1443 func pruneUnusedAutos(ll []*ir.Name, vis *hairyVisitor) []*ir.Name {
1444 s := make([]*ir.Name, 0, len(ll))
1445 for _, n := range ll {
1446 if n.Class == ir.PAUTO {
1447 if !vis.usedLocals.Has(n) {
1456 // numNonClosures returns the number of functions in list which are not closures.
1457 func numNonClosures(list []*ir.Func) int {
1459 for _, fn := range list {
1460 if fn.OClosure == nil {
1467 func doList(list []ir.Node, do func(ir.Node) bool) bool {
1468 for _, x := range list {