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.
35 "cmd/compile/internal/base"
36 "cmd/compile/internal/ir"
37 "cmd/compile/internal/logopt"
38 "cmd/compile/internal/pgo"
39 "cmd/compile/internal/typecheck"
40 "cmd/compile/internal/types"
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 nodes.
60 // TODO(prattmic): Make this non-global.
61 candHotNodeMap = 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 // List of inlined call sites. CallSiteInfo.Callee is always nil.
68 // TODO(prattmic): Make this non-global.
69 inlinedCallSites = make(map[pgo.CallSiteInfo]struct{})
71 // Threshold in percentage for hot function inlining.
72 inlineHotFuncThresholdPercent = float64(2)
74 // Threshold in percentage for hot callsite inlining.
75 inlineHotCallSiteThresholdPercent = float64(0.1)
77 // Budget increased due to hotness.
78 inlineHotMaxBudget int32 = 160
81 // pgoInlinePrologue records the hot callsites from ir-graph.
82 func pgoInlinePrologue(p *pgo.Profile) {
83 if s, err := strconv.ParseFloat(base.Debug.InlineHotFuncThreshold, 64); err == nil {
84 inlineHotFuncThresholdPercent = s
85 if base.Debug.PGOInline > 0 {
86 fmt.Printf("hot-node-thres=%v\n", inlineHotFuncThresholdPercent)
90 if s, err := strconv.ParseFloat(base.Debug.InlineHotCallSiteThreshold, 64); err == nil {
91 inlineHotCallSiteThresholdPercent = s
92 if base.Debug.PGOInline > 0 {
93 fmt.Printf("hot-callsite-thres=%v\n", inlineHotCallSiteThresholdPercent)
97 if base.Debug.InlineHotBudget != 0 {
98 inlineHotMaxBudget = int32(base.Debug.InlineHotBudget)
101 ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
102 for _, f := range list {
103 name := ir.PkgFuncName(f)
104 if n, ok := p.WeightedCG.IRNodes[name]; ok {
105 nodeweight := pgo.WeightInPercentage(n.Flat, p.TotalNodeWeight)
106 if nodeweight > inlineHotFuncThresholdPercent {
107 candHotNodeMap[n] = struct{}{}
109 for _, e := range p.WeightedCG.OutEdges[n] {
111 edgeweightpercent := pgo.WeightInPercentage(e.Weight, p.TotalEdgeWeight)
112 if edgeweightpercent > inlineHotCallSiteThresholdPercent {
113 csi := pgo.CallSiteInfo{Line: e.CallSite, Caller: n.AST}
114 if _, ok := candHotEdgeMap[csi]; !ok {
115 candHotEdgeMap[csi] = struct{}{}
123 if base.Debug.PGOInline > 0 {
124 fmt.Printf("hot-cg before inline in dot format:")
125 p.PrintWeightedCallGraphDOT(inlineHotFuncThresholdPercent, inlineHotCallSiteThresholdPercent)
129 // pgoInlineEpilogue updates IRGraph after inlining.
130 func pgoInlineEpilogue(p *pgo.Profile) {
131 if base.Debug.PGOInline > 0 {
132 ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
133 for _, f := range list {
134 name := ir.PkgFuncName(f)
135 if n, ok := p.WeightedCG.IRNodes[name]; ok {
136 p.RedirectEdges(n, inlinedCallSites)
140 // Print the call-graph after inlining. This is a debugging feature.
141 fmt.Printf("hot-cg after inline in dot:")
142 p.PrintWeightedCallGraphDOT(inlineHotFuncThresholdPercent, inlineHotCallSiteThresholdPercent)
146 // InlinePackage finds functions that can be inlined and clones them before walk expands them.
147 func InlinePackage(p *pgo.Profile) {
152 ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
153 numfns := numNonClosures(list)
154 for _, n := range list {
155 if !recursive || numfns > 1 {
156 // We allow inlining if there is no
157 // recursion, or the recursion cycle is
158 // across more than one function.
161 if base.Flag.LowerM > 1 {
162 fmt.Printf("%v: cannot inline %v: recursive\n", ir.Line(n), n.Nname)
174 // CanInline determines whether fn is inlineable.
175 // If so, CanInline saves copies of fn.Body and fn.Dcl in fn.Inl.
176 // fn and fn.Body will already have been typechecked.
177 func CanInline(fn *ir.Func, profile *pgo.Profile) {
179 base.Fatalf("CanInline no nname %+v", fn)
182 var reason string // reason, if any, that the function was not inlined
183 if base.Flag.LowerM > 1 || logopt.Enabled() {
186 if base.Flag.LowerM > 1 {
187 fmt.Printf("%v: cannot inline %v: %s\n", ir.Line(fn), fn.Nname, reason)
189 if logopt.Enabled() {
190 logopt.LogOpt(fn.Pos(), "cannotInlineFunction", "inline", ir.FuncName(fn), reason)
196 // If marked "go:noinline", don't inline
197 if fn.Pragma&ir.Noinline != 0 {
198 reason = "marked go:noinline"
202 // If marked "go:norace" and -race compilation, don't inline.
203 if base.Flag.Race && fn.Pragma&ir.Norace != 0 {
204 reason = "marked go:norace with -race compilation"
208 // If marked "go:nocheckptr" and -d checkptr compilation, don't inline.
209 if base.Debug.Checkptr != 0 && fn.Pragma&ir.NoCheckPtr != 0 {
210 reason = "marked go:nocheckptr"
214 // If marked "go:cgo_unsafe_args", don't inline, since the
215 // function makes assumptions about its argument frame layout.
216 if fn.Pragma&ir.CgoUnsafeArgs != 0 {
217 reason = "marked go:cgo_unsafe_args"
221 // If marked as "go:uintptrkeepalive", don't inline, since the
222 // keep alive information is lost during inlining.
224 // TODO(prattmic): This is handled on calls during escape analysis,
225 // which is after inlining. Move prior to inlining so the keep-alive is
226 // maintained after inlining.
227 if fn.Pragma&ir.UintptrKeepAlive != 0 {
228 reason = "marked as having a keep-alive uintptr argument"
232 // If marked as "go:uintptrescapes", don't inline, since the
233 // escape information is lost during inlining.
234 if fn.Pragma&ir.UintptrEscapes != 0 {
235 reason = "marked as having an escaping uintptr argument"
239 // The nowritebarrierrec checker currently works at function
240 // granularity, so inlining yeswritebarrierrec functions can
241 // confuse it (#22342). As a workaround, disallow inlining
243 if fn.Pragma&ir.Yeswritebarrierrec != 0 {
244 reason = "marked go:yeswritebarrierrec"
248 // If fn has no body (is defined outside of Go), cannot inline it.
249 if len(fn.Body) == 0 {
250 reason = "no function body"
254 if fn.Typecheck() == 0 {
255 base.Fatalf("CanInline on non-typechecked function %v", fn)
259 if n.Func.InlinabilityChecked() {
262 defer n.Func.SetInlinabilityChecked(true)
264 cc := int32(inlineExtraCallCost)
265 if base.Flag.LowerL == 4 {
266 cc = 1 // this appears to yield better performance than 0.
269 // Update the budget for profile-guided inlining.
270 budget := int32(inlineMaxBudget)
272 if n, ok := profile.WeightedCG.IRNodes[ir.PkgFuncName(fn)]; ok {
273 if _, ok := candHotNodeMap[n]; ok {
274 budget = int32(inlineHotMaxBudget)
275 if base.Debug.PGOInline > 0 {
276 fmt.Printf("hot-node enabled increased budget=%v for func=%v\n", budget, ir.PkgFuncName(fn))
282 // At this point in the game the function we're looking at may
283 // have "stale" autos, vars that still appear in the Dcl list, but
284 // which no longer have any uses in the function body (due to
285 // elimination by deadcode). We'd like to exclude these dead vars
286 // when creating the "Inline.Dcl" field below; to accomplish this,
287 // the hairyVisitor below builds up a map of used/referenced
288 // locals, and we use this map to produce a pruned Inline.Dcl
289 // list. See issue 25249 for more context.
291 visitor := hairyVisitor{
298 if visitor.tooHairy(fn) {
299 reason = visitor.reason
303 n.Func.Inl = &ir.Inline{
304 Cost: budget - visitor.budget,
305 Dcl: pruneUnusedAutos(n.Defn.(*ir.Func).Dcl, &visitor),
306 Body: inlcopylist(fn.Body),
308 CanDelayResults: canDelayResults(fn),
311 if base.Flag.LowerM > 1 {
312 fmt.Printf("%v: can inline %v with cost %d as: %v { %v }\n", ir.Line(fn), n, budget-visitor.budget, fn.Type(), ir.Nodes(n.Func.Inl.Body))
313 } else if base.Flag.LowerM != 0 {
314 fmt.Printf("%v: can inline %v\n", ir.Line(fn), n)
316 if logopt.Enabled() {
317 logopt.LogOpt(fn.Pos(), "canInlineFunction", "inline", ir.FuncName(fn), fmt.Sprintf("cost: %d", budget-visitor.budget))
321 // canDelayResults reports whether inlined calls to fn can delay
322 // declaring the result parameter until the "return" statement.
323 func canDelayResults(fn *ir.Func) bool {
324 // We can delay declaring+initializing result parameters if:
325 // (1) there's exactly one "return" statement in the inlined function;
326 // (2) it's not an empty return statement (#44355); and
327 // (3) the result parameters aren't named.
330 ir.VisitList(fn.Body, func(n ir.Node) {
331 if n, ok := n.(*ir.ReturnStmt); ok {
333 if len(n.Results) == 0 {
334 nreturns++ // empty return statement (case 2)
340 return false // not exactly one return statement (case 1)
343 // temporaries for return values.
344 for _, param := range fn.Type().Results().FieldSlice() {
345 if sym := types.OrigSym(param.Sym); sym != nil && !sym.IsBlank() {
346 return false // found a named result parameter (case 3)
353 // hairyVisitor visits a function body to determine its inlining
354 // hairiness and whether or not it can be inlined.
355 type hairyVisitor struct {
356 // This is needed to access the current caller in the doNode function.
362 usedLocals ir.NameSet
363 do func(ir.Node) bool
367 func (v *hairyVisitor) tooHairy(fn *ir.Func) bool {
368 v.do = v.doNode // cache closure
369 if ir.DoChildren(fn, v.do) {
373 v.reason = fmt.Sprintf("function too complex: cost %d exceeds budget %d", v.maxBudget-v.budget, v.maxBudget)
379 func (v *hairyVisitor) doNode(n ir.Node) bool {
384 // Call is okay if inlinable and we have the budget for the body.
386 n := n.(*ir.CallExpr)
387 // Functions that call runtime.getcaller{pc,sp} can not be inlined
388 // because getcaller{pc,sp} expect a pointer to the caller's first argument.
390 // runtime.throw is a "cheap call" like panic in normal code.
391 if n.X.Op() == ir.ONAME {
392 name := n.X.(*ir.Name)
393 if name.Class == ir.PFUNC && types.IsRuntimePkg(name.Sym().Pkg) {
394 fn := name.Sym().Name
395 if fn == "getcallerpc" || fn == "getcallersp" {
396 v.reason = "call to " + fn
400 v.budget -= inlineExtraThrowCost
404 // Special case for coverage counter updates; although
405 // these correspond to real operations, we treat them as
406 // zero cost for the moment. This is due to the existence
407 // of tests that are sensitive to inlining-- if the
408 // insertion of coverage instrumentation happens to tip a
409 // given function over the threshold and move it from
410 // "inlinable" to "not-inlinable", this can cause changes
411 // in allocation behavior, which can then result in test
412 // failures (a good example is the TestAllocations in
414 if isAtomicCoverageCounterUpdate(n) {
418 if n.X.Op() == ir.OMETHEXPR {
419 if meth := ir.MethodExprName(n.X); meth != nil {
420 if fn := meth.Func; fn != nil {
423 if types.IsRuntimePkg(s.Pkg) && s.Name == "heapBits.nextArena" {
424 // Special case: explicitly allow mid-stack inlining of
425 // runtime.heapBits.next even though it calls slow-path
426 // runtime.heapBits.nextArena.
429 // Special case: on architectures that can do unaligned loads,
430 // explicitly mark encoding/binary methods as cheap,
431 // because in practice they are, even though our inlining
432 // budgeting system does not see that. See issue 42958.
433 if base.Ctxt.Arch.CanMergeLoads && s.Pkg.Path == "encoding/binary" {
435 case "littleEndian.Uint64", "littleEndian.Uint32", "littleEndian.Uint16",
436 "bigEndian.Uint64", "bigEndian.Uint32", "bigEndian.Uint16",
437 "littleEndian.PutUint64", "littleEndian.PutUint32", "littleEndian.PutUint16",
438 "bigEndian.PutUint64", "bigEndian.PutUint32", "bigEndian.PutUint16",
439 "littleEndian.AppendUint64", "littleEndian.AppendUint32", "littleEndian.AppendUint16",
440 "bigEndian.AppendUint64", "bigEndian.AppendUint32", "bigEndian.AppendUint16":
445 break // treat like any other node, that is, cost of 1
451 // Determine if the callee edge is for an inlinable hot callee or not.
452 if v.profile != nil && v.curFunc != nil {
453 if fn := inlCallee(n.X, v.profile); fn != nil && typecheck.HaveInlineBody(fn) {
454 line := int(base.Ctxt.InnermostPos(n.Pos()).RelLine())
455 csi := pgo.CallSiteInfo{Line: line, Caller: v.curFunc}
456 if _, o := candHotEdgeMap[csi]; o {
457 if base.Debug.PGOInline > 0 {
458 fmt.Printf("hot-callsite identified at line=%v for func=%v\n", ir.Line(n), ir.PkgFuncName(v.curFunc))
464 if ir.IsIntrinsicCall(n) {
465 // Treat like any other node.
469 if fn := inlCallee(n.X, v.profile); fn != nil && typecheck.HaveInlineBody(fn) {
470 v.budget -= fn.Inl.Cost
474 // Call cost for non-leaf inlining.
475 v.budget -= v.extraCallCost
478 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
480 // Things that are too hairy, irrespective of the budget
481 case ir.OCALL, ir.OCALLINTER:
482 // Call cost for non-leaf inlining.
483 v.budget -= v.extraCallCost
486 n := n.(*ir.UnaryExpr)
487 if n.X.Op() == ir.OCONVIFACE && n.X.(*ir.ConvExpr).Implicit() {
488 // Hack to keep reflect.flag.mustBe inlinable for TestIntendedInlining.
489 // Before CL 284412, these conversions were introduced later in the
490 // compiler, so they didn't count against inlining budget.
493 v.budget -= inlineExtraPanicCost
496 // recover matches the argument frame pointer to find
497 // the right panic value, so it needs an argument frame.
498 v.reason = "call to recover"
502 if base.Debug.InlFuncsWithClosures == 0 {
503 v.reason = "not inlining functions with closures"
507 // TODO(danscales): Maybe make budget proportional to number of closure
509 //v.budget -= int32(len(n.(*ir.ClosureExpr).Func.ClosureVars) * 3)
511 // Scan body of closure (which DoChildren doesn't automatically
512 // do) to check for disallowed ops in the body and include the
513 // body in the budget.
514 if doList(n.(*ir.ClosureExpr).Func.Body, v.do) {
520 ir.ODCLTYPE, // can't print yet
522 v.reason = "unhandled op " + n.Op().String()
526 v.budget -= inlineExtraAppendCost
529 n := n.(*ir.AddrExpr)
530 // Make "&s.f" cost 0 when f's offset is zero.
531 if dot, ok := n.X.(*ir.SelectorExpr); ok && (dot.Op() == ir.ODOT || dot.Op() == ir.ODOTPTR) {
532 if _, ok := dot.X.(*ir.Name); ok && dot.Selection.Offset == 0 {
533 v.budget += 2 // undo ir.OADDR+ir.ODOT/ir.ODOTPTR
538 // *(*X)(unsafe.Pointer(&x)) is low-cost
539 n := n.(*ir.StarExpr)
542 for ptr.Op() == ir.OCONVNOP {
543 ptr = ptr.(*ir.ConvExpr).X
545 if ptr.Op() == ir.OADDR {
546 v.budget += 1 // undo half of default cost of ir.ODEREF+ir.OADDR
550 // This doesn't produce code, but the children might.
551 v.budget++ // undo default cost
553 case ir.ODCLCONST, ir.OFALL:
554 // These nodes don't produce code; omit from inlining budget.
559 if ir.IsConst(n.Cond, constant.Bool) {
560 // This if and the condition cost nothing.
561 if doList(n.Init(), v.do) {
564 if ir.BoolVal(n.Cond) {
565 return doList(n.Body, v.do)
567 return doList(n.Else, v.do)
573 if n.Class == ir.PAUTO {
578 // The only OBLOCK we should see at this point is an empty one.
579 // In any event, let the visitList(n.List()) below take care of the statements,
580 // and don't charge for the OBLOCK itself. The ++ undoes the -- below.
583 case ir.OMETHVALUE, ir.OSLICELIT:
584 v.budget-- // Hack for toolstash -cmp.
587 v.budget++ // Hack for toolstash -cmp.
590 n := n.(*ir.AssignListStmt)
592 // Unified IR unconditionally rewrites:
603 // so that it can insert implicit conversions as necessary. To
604 // minimize impact to the existing inlining heuristics (in
605 // particular, to avoid breaking the existing inlinability regress
606 // tests), we need to compensate for this here.
607 if base.Debug.Unified != 0 {
608 if init := n.Rhs[0].Init(); len(init) == 1 {
609 if _, ok := init[0].(*ir.AssignListStmt); ok {
610 // 4 for each value, because each temporary variable now
611 // appears 3 times (DCL, LHS, RHS), plus an extra DCL node.
613 // 1 for the extra "tmp1, tmp2 = f()" assignment statement.
614 v.budget += 4*int32(len(n.Lhs)) + 1
620 // Special case for coverage counter updates and coverage
621 // function registrations. Although these correspond to real
622 // operations, we treat them as zero cost for the moment. This
623 // is primarily due to the existence of tests that are
624 // sensitive to inlining-- if the insertion of coverage
625 // instrumentation happens to tip a given function over the
626 // threshold and move it from "inlinable" to "not-inlinable",
627 // this can cause changes in allocation behavior, which can
628 // then result in test failures (a good example is the
629 // TestAllocations in crypto/ed25519).
630 n := n.(*ir.AssignStmt)
631 if n.X.Op() == ir.OINDEX && isIndexingCoverageCounter(n.X) {
638 // When debugging, don't stop early, to get full cost of inlining this function
639 if v.budget < 0 && base.Flag.LowerM < 2 && !logopt.Enabled() {
640 v.reason = "too expensive"
644 return ir.DoChildren(n, v.do)
647 func isBigFunc(fn *ir.Func) bool {
648 budget := inlineBigFunctionNodes
649 return ir.Any(fn, func(n ir.Node) bool {
655 // inlcopylist (together with inlcopy) recursively copies a list of nodes, except
656 // that it keeps the same ONAME, OTYPE, and OLITERAL nodes. It is used for copying
657 // the body and dcls of an inlineable function.
658 func inlcopylist(ll []ir.Node) []ir.Node {
659 s := make([]ir.Node, len(ll))
660 for i, n := range ll {
666 // inlcopy is like DeepCopy(), but does extra work to copy closures.
667 func inlcopy(n ir.Node) ir.Node {
668 var edit func(ir.Node) ir.Node
669 edit = func(x ir.Node) ir.Node {
671 case ir.ONAME, ir.OTYPE, ir.OLITERAL, ir.ONIL:
675 ir.EditChildren(m, edit)
676 if x.Op() == ir.OCLOSURE {
677 x := x.(*ir.ClosureExpr)
678 // Need to save/duplicate x.Func.Nname,
679 // x.Func.Nname.Ntype, x.Func.Dcl, x.Func.ClosureVars, and
680 // x.Func.Body for iexport and local inlining.
682 newfn := ir.NewFunc(oldfn.Pos())
683 m.(*ir.ClosureExpr).Func = newfn
684 newfn.Nname = ir.NewNameAt(oldfn.Nname.Pos(), oldfn.Nname.Sym())
685 // XXX OK to share fn.Type() ??
686 newfn.Nname.SetType(oldfn.Nname.Type())
687 newfn.Body = inlcopylist(oldfn.Body)
688 // Make shallow copy of the Dcl and ClosureVar slices
689 newfn.Dcl = append([]*ir.Name(nil), oldfn.Dcl...)
690 newfn.ClosureVars = append([]*ir.Name(nil), oldfn.ClosureVars...)
697 // InlineCalls/inlnode walks fn's statements and expressions and substitutes any
698 // calls made to inlineable functions. This is the external entry point.
699 func InlineCalls(fn *ir.Func, profile *pgo.Profile) {
702 maxCost := int32(inlineMaxBudget)
704 maxCost = inlineBigFunctionMaxCost
706 var inlCalls []*ir.InlinedCallExpr
707 var edit func(ir.Node) ir.Node
708 edit = func(n ir.Node) ir.Node {
709 return inlnode(n, maxCost, &inlCalls, edit, profile)
711 ir.EditChildren(fn, edit)
713 // If we inlined any calls, we want to recursively visit their
714 // bodies for further inlining. However, we need to wait until
715 // *after* the original function body has been expanded, or else
716 // inlCallee can have false positives (e.g., #54632).
717 for len(inlCalls) > 0 {
719 inlCalls = inlCalls[1:]
720 ir.EditChildren(call, edit)
726 // inlnode recurses over the tree to find inlineable calls, which will
727 // be turned into OINLCALLs by mkinlcall. When the recursion comes
728 // back up will examine left, right, list, rlist, ninit, ntest, nincr,
729 // nbody and nelse and use one of the 4 inlconv/glue functions above
730 // to turn the OINLCALL into an expression, a statement, or patch it
731 // in to this nodes list or rlist as appropriate.
732 // NOTE it makes no sense to pass the glue functions down the
733 // recursion to the level where the OINLCALL gets created because they
734 // have to edit /this/ n, so you'd have to push that one down as well,
735 // but then you may as well do it here. so this is cleaner and
736 // shorter and less complicated.
737 // The result of inlnode MUST be assigned back to n, e.g.
739 // n.Left = inlnode(n.Left)
740 func inlnode(n ir.Node, maxCost int32, inlCalls *[]*ir.InlinedCallExpr, edit func(ir.Node) ir.Node, profile *pgo.Profile) ir.Node {
746 case ir.ODEFER, ir.OGO:
747 n := n.(*ir.GoDeferStmt)
748 switch call := n.Call; call.Op() {
750 base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
752 call := call.(*ir.CallExpr)
756 n := n.(*ir.TailCallStmt)
757 n.Call.NoInline = true // Not inline a tail call for now. Maybe we could inline it just like RETURN fn(arg)?
759 // TODO do them here (or earlier),
760 // so escape analysis can avoid more heapmoves.
764 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
766 n := n.(*ir.CallExpr)
767 if n.X.Op() == ir.OMETHEXPR {
768 // Prevent inlining some reflect.Value methods when using checkptr,
769 // even when package reflect was compiled without it (#35073).
770 if meth := ir.MethodExprName(n.X); meth != nil {
772 if base.Debug.Checkptr != 0 && types.IsReflectPkg(s.Pkg) && (s.Name == "Value.UnsafeAddr" || s.Name == "Value.Pointer") {
781 ir.EditChildren(n, edit)
783 // with all the branches out of the way, it is now time to
784 // transmogrify this node itself unless inhibited by the
785 // switch at the top of this function.
788 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
791 call := n.(*ir.CallExpr)
795 if base.Flag.LowerM > 3 {
796 fmt.Printf("%v:call to func %+v\n", ir.Line(n), call.X)
798 if ir.IsIntrinsicCall(call) {
801 if fn := inlCallee(call.X, profile); fn != nil && typecheck.HaveInlineBody(fn) {
802 n = mkinlcall(call, fn, maxCost, inlCalls, edit)
811 // inlCallee takes a function-typed expression and returns the underlying function ONAME
812 // that it refers to if statically known. Otherwise, it returns nil.
813 func inlCallee(fn ir.Node, profile *pgo.Profile) *ir.Func {
814 fn = ir.StaticValue(fn)
817 fn := fn.(*ir.SelectorExpr)
818 n := ir.MethodExprName(fn)
819 // Check that receiver type matches fn.X.
820 // TODO(mdempsky): Handle implicit dereference
821 // of pointer receiver argument?
822 if n == nil || !types.Identical(n.Type().Recv().Type, fn.X.Type()) {
828 if fn.Class == ir.PFUNC {
832 fn := fn.(*ir.ClosureExpr)
834 CanInline(c, profile)
840 func inlParam(t *types.Field, as ir.InitNode, inlvars map[*ir.Name]*ir.Name) ir.Node {
844 n := t.Nname.(*ir.Name)
850 base.Fatalf("missing inlvar for %v", n)
852 as.PtrInit().Append(ir.NewDecl(base.Pos, ir.ODCL, inlvar))
853 inlvar.Name().Defn = as
859 // SSADumpInline gives the SSA back end a chance to dump the function
860 // when producing output for debugging the compiler itself.
861 var SSADumpInline = func(*ir.Func) {}
863 // InlineCall allows the inliner implementation to be overridden.
864 // If it returns nil, the function will not be inlined.
865 var InlineCall = oldInlineCall
867 // If n is a OCALLFUNC node, and fn is an ONAME node for a
868 // function with an inlinable body, return an OINLCALL node that can replace n.
869 // The returned node's Ninit has the parameter assignments, the Nbody is the
870 // inlined function body, and (List, Rlist) contain the (input, output)
872 // The result of mkinlcall MUST be assigned back to n, e.g.
874 // n.Left = mkinlcall(n.Left, fn, isddd)
875 func mkinlcall(n *ir.CallExpr, fn *ir.Func, maxCost int32, inlCalls *[]*ir.InlinedCallExpr, edit func(ir.Node) ir.Node) ir.Node {
877 if logopt.Enabled() {
878 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
879 fmt.Sprintf("%s cannot be inlined", ir.PkgFuncName(fn)))
883 if fn.Inl.Cost > maxCost {
884 // If the callsite is hot and it is under the inlineHotMaxBudget budget, then try to inline it, or else bail.
885 line := int(base.Ctxt.InnermostPos(n.Pos()).RelLine())
886 csi := pgo.CallSiteInfo{Line: line, Caller: ir.CurFunc}
887 if _, ok := candHotEdgeMap[csi]; ok {
888 if fn.Inl.Cost > inlineHotMaxBudget {
889 if logopt.Enabled() {
890 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
891 fmt.Sprintf("cost %d of %s exceeds max large caller cost %d", fn.Inl.Cost, ir.PkgFuncName(fn), inlineHotMaxBudget))
895 if base.Debug.PGOInline > 0 {
896 fmt.Printf("hot-budget check allows inlining for callsite at %v\n", ir.Line(n))
899 // The inlined function body is too big. Typically we use this check to restrict
900 // inlining into very big functions. See issue 26546 and 17566.
901 if logopt.Enabled() {
902 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
903 fmt.Sprintf("cost %d of %s exceeds max large caller cost %d", fn.Inl.Cost, ir.PkgFuncName(fn), maxCost))
909 if fn == ir.CurFunc {
910 // Can't recursively inline a function into itself.
911 if logopt.Enabled() {
912 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", fmt.Sprintf("recursive call to %s", ir.FuncName(ir.CurFunc)))
917 // The non-unified frontend has issues with inlining and shape parameters.
918 if base.Debug.Unified == 0 {
919 // Don't inline a function fn that has no shape parameters, but is passed at
920 // least one shape arg. This means we must be inlining a non-generic function
921 // fn that was passed into a generic function, and can be called with a shape
922 // arg because it matches an appropriate type parameters. But fn may include
923 // an interface conversion (that may be applied to a shape arg) that was not
924 // apparent when we first created the instantiation of the generic function.
925 // We can't handle this if we actually do the inlining, since we want to know
926 // all interface conversions immediately after stenciling. So, we avoid
927 // inlining in this case, see issue #49309. (1)
929 // See discussion on go.dev/cl/406475 for more background.
930 if !fn.Type().Params().HasShape() {
931 for _, arg := range n.Args {
932 if arg.Type().HasShape() {
933 if logopt.Enabled() {
934 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
935 fmt.Sprintf("inlining function %v has no-shape params with shape args", ir.FuncName(fn)))
941 // Don't inline a function fn that has shape parameters, but is passed no shape arg.
942 // See comments (1) above, and issue #51909.
943 inlineable := len(n.Args) == 0 // Function has shape in type, with no arguments can always be inlined.
944 for _, arg := range n.Args {
945 if arg.Type().HasShape() {
951 if logopt.Enabled() {
952 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
953 fmt.Sprintf("inlining function %v has shape params with no-shape args", ir.FuncName(fn)))
960 if base.Flag.Cfg.Instrumenting && types.IsRuntimePkg(fn.Sym().Pkg) {
961 // Runtime package must not be instrumented.
962 // Instrument skips runtime package. However, some runtime code can be
963 // inlined into other packages and instrumented there. To avoid this,
964 // we disable inlining of runtime functions when instrumenting.
965 // The example that we observed is inlining of LockOSThread,
966 // which lead to false race reports on m contents.
970 parent := base.Ctxt.PosTable.Pos(n.Pos()).Base().InliningIndex()
973 // Check if we've already inlined this function at this particular
974 // call site, in order to stop inlining when we reach the beginning
975 // of a recursion cycle again. We don't inline immediately recursive
976 // functions, but allow inlining if there is a recursion cycle of
977 // many functions. Most likely, the inlining will stop before we
978 // even hit the beginning of the cycle again, but this catches the
980 for inlIndex := parent; inlIndex >= 0; inlIndex = base.Ctxt.InlTree.Parent(inlIndex) {
981 if base.Ctxt.InlTree.InlinedFunction(inlIndex) == sym {
982 if base.Flag.LowerM > 1 {
983 fmt.Printf("%v: cannot inline %v into %v: repeated recursive cycle\n", ir.Line(n), fn, ir.FuncName(ir.CurFunc))
989 typecheck.FixVariadicCall(n)
991 inlIndex := base.Ctxt.InlTree.Add(parent, n.Pos(), sym)
993 closureInitLSym := func(n *ir.CallExpr, fn *ir.Func) {
994 // The linker needs FuncInfo metadata for all inlined
995 // functions. This is typically handled by gc.enqueueFunc
996 // calling ir.InitLSym for all function declarations in
997 // typecheck.Target.Decls (ir.UseClosure adds all closures to
1000 // However, non-trivial closures in Decls are ignored, and are
1001 // insteaded enqueued when walk of the calling function
1004 // This presents a problem for direct calls to closures.
1005 // Inlining will replace the entire closure definition with its
1006 // body, which hides the closure from walk and thus suppresses
1009 // Explicitly create a symbol early in this edge case to ensure
1010 // we keep this metadata.
1012 // TODO: Refactor to keep a reference so this can all be done
1015 if n.Op() != ir.OCALLFUNC {
1016 // Not a standard call.
1019 if n.X.Op() != ir.OCLOSURE {
1020 // Not a direct closure call.
1024 clo := n.X.(*ir.ClosureExpr)
1025 if ir.IsTrivialClosure(clo) {
1026 // enqueueFunc will handle trivial closures anyways.
1030 ir.InitLSym(fn, true)
1033 closureInitLSym(n, fn)
1035 if base.Flag.GenDwarfInl > 0 {
1036 if !sym.WasInlined() {
1037 base.Ctxt.DwFixups.SetPrecursorFunc(sym, fn)
1038 sym.Set(obj.AttrWasInlined, true)
1042 if base.Flag.LowerM != 0 {
1043 fmt.Printf("%v: inlining call to %v\n", ir.Line(n), fn)
1045 if base.Flag.LowerM > 2 {
1046 fmt.Printf("%v: Before inlining: %+v\n", ir.Line(n), n)
1049 if base.Debug.PGOInline > 0 {
1050 line := int(base.Ctxt.InnermostPos(n.Pos()).RelLine())
1051 csi := pgo.CallSiteInfo{Line: line, Caller: ir.CurFunc}
1052 if _, ok := inlinedCallSites[csi]; !ok {
1053 inlinedCallSites[csi] = struct{}{}
1057 res := InlineCall(n, fn, inlIndex)
1060 base.FatalfAt(n.Pos(), "inlining call to %v failed", fn)
1063 if base.Flag.LowerM > 2 {
1064 fmt.Printf("%v: After inlining %+v\n\n", ir.Line(res), res)
1067 *inlCalls = append(*inlCalls, res)
1072 // CalleeEffects appends any side effects from evaluating callee to init.
1073 func CalleeEffects(init *ir.Nodes, callee ir.Node) {
1075 init.Append(ir.TakeInit(callee)...)
1077 switch callee.Op() {
1078 case ir.ONAME, ir.OCLOSURE, ir.OMETHEXPR:
1082 conv := callee.(*ir.ConvExpr)
1086 ic := callee.(*ir.InlinedCallExpr)
1087 init.Append(ic.Body.Take()...)
1088 callee = ic.SingleResult()
1091 base.FatalfAt(callee.Pos(), "unexpected callee expression: %v", callee)
1096 // oldInlineCall creates an InlinedCallExpr to replace the given call
1097 // expression. fn is the callee function to be inlined. inlIndex is
1098 // the inlining tree position index, for use with src.NewInliningBase
1099 // when rewriting positions.
1100 func oldInlineCall(call *ir.CallExpr, fn *ir.Func, inlIndex int) *ir.InlinedCallExpr {
1101 if base.Debug.TypecheckInl == 0 {
1102 typecheck.ImportedBody(fn)
1107 ninit := call.Init()
1109 // For normal function calls, the function callee expression
1110 // may contain side effects. Make sure to preserve these,
1111 // if necessary (#42703).
1112 if call.Op() == ir.OCALLFUNC {
1113 CalleeEffects(&ninit, call.X)
1116 // Make temp names to use instead of the originals.
1117 inlvars := make(map[*ir.Name]*ir.Name)
1119 // record formals/locals for later post-processing
1120 var inlfvars []*ir.Name
1122 for _, ln := range fn.Inl.Dcl {
1123 if ln.Op() != ir.ONAME {
1126 if ln.Class == ir.PPARAMOUT { // return values handled below.
1129 inlf := typecheck.Expr(inlvar(ln)).(*ir.Name)
1131 if base.Flag.GenDwarfInl > 0 {
1132 if ln.Class == ir.PPARAM {
1133 inlf.Name().SetInlFormal(true)
1135 inlf.Name().SetInlLocal(true)
1137 inlf.SetPos(ln.Pos())
1138 inlfvars = append(inlfvars, inlf)
1142 // We can delay declaring+initializing result parameters if:
1143 // temporaries for return values.
1144 var retvars []ir.Node
1145 for i, t := range fn.Type().Results().Fields().Slice() {
1147 if nn := t.Nname; nn != nil && !ir.IsBlank(nn.(*ir.Name)) && !strings.HasPrefix(nn.Sym().Name, "~r") {
1150 m = typecheck.Expr(m).(*ir.Name)
1153 // anonymous return values, synthesize names for use in assignment that replaces return
1157 if base.Flag.GenDwarfInl > 0 {
1158 // Don't update the src.Pos on a return variable if it
1159 // was manufactured by the inliner (e.g. "~R2"); such vars
1160 // were not part of the original callee.
1161 if !strings.HasPrefix(m.Sym().Name, "~R") {
1162 m.Name().SetInlFormal(true)
1164 inlfvars = append(inlfvars, m)
1168 retvars = append(retvars, m)
1171 // Assign arguments to the parameters' temp names.
1172 as := ir.NewAssignListStmt(base.Pos, ir.OAS2, nil, nil)
1174 if call.Op() == ir.OCALLMETH {
1175 base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
1177 as.Rhs.Append(call.Args...)
1179 if recv := fn.Type().Recv(); recv != nil {
1180 as.Lhs.Append(inlParam(recv, as, inlvars))
1182 for _, param := range fn.Type().Params().Fields().Slice() {
1183 as.Lhs.Append(inlParam(param, as, inlvars))
1186 if len(as.Rhs) != 0 {
1187 ninit.Append(typecheck.Stmt(as))
1190 if !fn.Inl.CanDelayResults {
1191 // Zero the return parameters.
1192 for _, n := range retvars {
1193 ninit.Append(ir.NewDecl(base.Pos, ir.ODCL, n.(*ir.Name)))
1194 ras := ir.NewAssignStmt(base.Pos, n, nil)
1195 ninit.Append(typecheck.Stmt(ras))
1199 retlabel := typecheck.AutoLabel(".i")
1203 // Add an inline mark just before the inlined body.
1204 // This mark is inline in the code so that it's a reasonable spot
1205 // to put a breakpoint. Not sure if that's really necessary or not
1206 // (in which case it could go at the end of the function instead).
1207 // Note issue 28603.
1208 ninit.Append(ir.NewInlineMarkStmt(call.Pos().WithIsStmt(), int64(inlIndex)))
1214 defnMarker: ir.NilExpr{},
1215 bases: make(map[*src.PosBase]*src.PosBase),
1216 newInlIndex: inlIndex,
1219 subst.edit = subst.node
1221 body := subst.list(ir.Nodes(fn.Inl.Body))
1223 lab := ir.NewLabelStmt(base.Pos, retlabel)
1224 body = append(body, lab)
1226 if base.Flag.GenDwarfInl > 0 {
1227 for _, v := range inlfvars {
1228 v.SetPos(subst.updatedPos(v.Pos()))
1232 //dumplist("ninit post", ninit);
1234 res := ir.NewInlinedCallExpr(base.Pos, body, retvars)
1236 res.SetType(call.Type())
1241 // Every time we expand a function we generate a new set of tmpnames,
1242 // PAUTO's in the calling functions, and link them off of the
1243 // PPARAM's, PAUTOS and PPARAMOUTs of the called function.
1244 func inlvar(var_ *ir.Name) *ir.Name {
1245 if base.Flag.LowerM > 3 {
1246 fmt.Printf("inlvar %+v\n", var_)
1249 n := typecheck.NewName(var_.Sym())
1250 n.SetType(var_.Type())
1254 n.SetAutoTemp(var_.AutoTemp())
1255 n.Curfn = ir.CurFunc // the calling function, not the called one
1256 n.SetAddrtaken(var_.Addrtaken())
1258 ir.CurFunc.Dcl = append(ir.CurFunc.Dcl, n)
1262 // Synthesize a variable to store the inlined function's results in.
1263 func retvar(t *types.Field, i int) *ir.Name {
1264 n := typecheck.NewName(typecheck.LookupNum("~R", i))
1269 n.Curfn = ir.CurFunc // the calling function, not the called one
1270 ir.CurFunc.Dcl = append(ir.CurFunc.Dcl, n)
1274 // The inlsubst type implements the actual inlining of a single
1276 type inlsubst struct {
1277 // Target of the goto substituted in place of a return.
1280 // Temporary result variables.
1283 inlvars map[*ir.Name]*ir.Name
1284 // defnMarker is used to mark a Node for reassignment.
1285 // inlsubst.clovar set this during creating new ONAME.
1286 // inlsubst.node will set the correct Defn for inlvar.
1287 defnMarker ir.NilExpr
1289 // bases maps from original PosBase to PosBase with an extra
1290 // inlined call frame.
1291 bases map[*src.PosBase]*src.PosBase
1293 // newInlIndex is the index of the inlined call frame to
1294 // insert for inlined nodes.
1297 edit func(ir.Node) ir.Node // cached copy of subst.node method value closure
1299 // If non-nil, we are inside a closure inside the inlined function, and
1300 // newclofn is the Func of the new inlined closure.
1303 fn *ir.Func // For debug -- the func that is being inlined
1305 // If true, then don't update source positions during substitution
1306 // (retain old source positions).
1310 // list inlines a list of nodes.
1311 func (subst *inlsubst) list(ll ir.Nodes) []ir.Node {
1312 s := make([]ir.Node, 0, len(ll))
1313 for _, n := range ll {
1314 s = append(s, subst.node(n))
1319 // fields returns a list of the fields of a struct type representing receiver,
1320 // params, or results, after duplicating the field nodes and substituting the
1321 // Nname nodes inside the field nodes.
1322 func (subst *inlsubst) fields(oldt *types.Type) []*types.Field {
1323 oldfields := oldt.FieldSlice()
1324 newfields := make([]*types.Field, len(oldfields))
1325 for i := range oldfields {
1326 newfields[i] = oldfields[i].Copy()
1327 if oldfields[i].Nname != nil {
1328 newfields[i].Nname = subst.node(oldfields[i].Nname.(*ir.Name))
1334 // clovar creates a new ONAME node for a local variable or param of a closure
1335 // inside a function being inlined.
1336 func (subst *inlsubst) clovar(n *ir.Name) *ir.Name {
1337 m := ir.NewNameAt(n.Pos(), n.Sym())
1341 if n.IsClosureVar() {
1342 m.SetIsClosureVar(true)
1345 m.SetAddrtaken(true)
1352 m.Curfn = subst.newclofn
1354 switch defn := n.Defn.(type) {
1358 if !n.IsClosureVar() {
1359 base.FatalfAt(n.Pos(), "want closure variable, got: %+v", n)
1361 if n.Sym().Pkg != types.LocalPkg {
1362 // If the closure came from inlining a function from
1363 // another package, must change package of captured
1364 // variable to localpkg, so that the fields of the closure
1365 // struct are local package and can be accessed even if
1366 // name is not exported. If you disable this code, you can
1367 // reproduce the problem by running 'go test
1368 // go/internal/srcimporter'. TODO(mdempsky) - maybe change
1369 // how we create closure structs?
1370 m.SetSym(types.LocalPkg.Lookup(n.Sym().Name))
1372 // Make sure any inlvar which is the Defn
1373 // of an ONAME closure var is rewritten
1374 // during inlining. Don't substitute
1375 // if Defn node is outside inlined function.
1376 if subst.inlvars[n.Defn.(*ir.Name)] != nil {
1377 m.Defn = subst.node(n.Defn)
1379 case *ir.AssignStmt, *ir.AssignListStmt:
1380 // Mark node for reassignment at the end of inlsubst.node.
1381 m.Defn = &subst.defnMarker
1382 case *ir.TypeSwitchGuard:
1383 // TODO(mdempsky): Set m.Defn properly. See discussion on #45743.
1385 // TODO: Set m.Defn properly if we support inlining range statement in the future.
1387 base.FatalfAt(n.Pos(), "unexpected Defn: %+v", defn)
1391 // Either the outer variable is defined in function being inlined,
1392 // and we will replace it with the substituted variable, or it is
1393 // defined outside the function being inlined, and we should just
1394 // skip the outer variable (the closure variable of the function
1396 s := subst.node(n.Outer).(*ir.Name)
1405 // closure does the necessary substitions for a ClosureExpr n and returns the new
1407 func (subst *inlsubst) closure(n *ir.ClosureExpr) ir.Node {
1408 // Prior to the subst edit, set a flag in the inlsubst to indicate
1409 // that we don't want to update the source positions in the new
1410 // closure function. If we do this, it will appear that the
1411 // closure itself has things inlined into it, which is not the
1412 // case. See issue #46234 for more details. At the same time, we
1413 // do want to update the position in the new ClosureExpr (which is
1414 // part of the function we're working on). See #49171 for an
1415 // example of what happens if we miss that update.
1416 newClosurePos := subst.updatedPos(n.Pos())
1417 defer func(prev bool) { subst.noPosUpdate = prev }(subst.noPosUpdate)
1418 subst.noPosUpdate = true
1420 //fmt.Printf("Inlining func %v with closure into %v\n", subst.fn, ir.FuncName(ir.CurFunc))
1423 newfn := ir.NewClosureFunc(oldfn.Pos(), true)
1425 if subst.newclofn != nil {
1426 //fmt.Printf("Inlining a closure with a nested closure\n")
1428 prevxfunc := subst.newclofn
1430 // Mark that we are now substituting within a closure (within the
1431 // inlined function), and create new nodes for all the local
1432 // vars/params inside this closure.
1433 subst.newclofn = newfn
1435 newfn.ClosureVars = nil
1436 for _, oldv := range oldfn.Dcl {
1437 newv := subst.clovar(oldv)
1438 subst.inlvars[oldv] = newv
1439 newfn.Dcl = append(newfn.Dcl, newv)
1441 for _, oldv := range oldfn.ClosureVars {
1442 newv := subst.clovar(oldv)
1443 subst.inlvars[oldv] = newv
1444 newfn.ClosureVars = append(newfn.ClosureVars, newv)
1447 // Need to replace ONAME nodes in
1448 // newfn.Type().FuncType().Receiver/Params/Results.FieldSlice().Nname
1449 oldt := oldfn.Type()
1450 newrecvs := subst.fields(oldt.Recvs())
1451 var newrecv *types.Field
1452 if len(newrecvs) > 0 {
1453 newrecv = newrecvs[0]
1455 newt := types.NewSignature(oldt.Pkg(), newrecv,
1456 nil, subst.fields(oldt.Params()), subst.fields(oldt.Results()))
1458 newfn.Nname.SetType(newt)
1459 newfn.Body = subst.list(oldfn.Body)
1461 // Remove the nodes for the current closure from subst.inlvars
1462 for _, oldv := range oldfn.Dcl {
1463 delete(subst.inlvars, oldv)
1465 for _, oldv := range oldfn.ClosureVars {
1466 delete(subst.inlvars, oldv)
1468 // Go back to previous closure func
1469 subst.newclofn = prevxfunc
1471 // Actually create the named function for the closure, now that
1472 // the closure is inlined in a specific function.
1473 newclo := newfn.OClosure
1474 newclo.SetPos(newClosurePos)
1475 newclo.SetInit(subst.list(n.Init()))
1476 return typecheck.Expr(newclo)
1479 // node recursively copies a node from the saved pristine body of the
1480 // inlined function, substituting references to input/output
1481 // parameters with ones to the tmpnames, and substituting returns with
1482 // assignments to the output.
1483 func (subst *inlsubst) node(n ir.Node) ir.Node {
1492 // Handle captured variables when inlining closures.
1493 if n.IsClosureVar() && subst.newclofn == nil {
1496 // Deal with case where sequence of closures are inlined.
1497 // TODO(danscales) - write test case to see if we need to
1498 // go up multiple levels.
1499 if o.Curfn != ir.CurFunc {
1503 // make sure the outer param matches the inlining location
1504 if o == nil || o.Curfn != ir.CurFunc {
1505 base.Fatalf("%v: unresolvable capture %v\n", ir.Line(n), n)
1508 if base.Flag.LowerM > 2 {
1509 fmt.Printf("substituting captured name %+v -> %+v\n", n, o)
1514 if inlvar := subst.inlvars[n]; inlvar != nil { // These will be set during inlnode
1515 if base.Flag.LowerM > 2 {
1516 fmt.Printf("substituting name %+v -> %+v\n", n, inlvar)
1521 if base.Flag.LowerM > 2 {
1522 fmt.Printf("not substituting name %+v\n", n)
1527 n := n.(*ir.SelectorExpr)
1530 case ir.OLITERAL, ir.ONIL, ir.OTYPE:
1531 // If n is a named constant or type, we can continue
1532 // using it in the inline copy. Otherwise, make a copy
1533 // so we can update the line number.
1539 if subst.newclofn != nil {
1540 // Don't do special substitutions if inside a closure
1543 // Because of the above test for subst.newclofn,
1544 // this return is guaranteed to belong to the current inlined function.
1545 n := n.(*ir.ReturnStmt)
1546 init := subst.list(n.Init())
1547 if len(subst.retvars) != 0 && len(n.Results) != 0 {
1548 as := ir.NewAssignListStmt(base.Pos, ir.OAS2, nil, nil)
1550 // Make a shallow copy of retvars.
1551 // Otherwise OINLCALL.Rlist will be the same list,
1552 // and later walk and typecheck may clobber it.
1553 for _, n := range subst.retvars {
1556 as.Rhs = subst.list(n.Results)
1558 if subst.fn.Inl.CanDelayResults {
1559 for _, n := range as.Lhs {
1560 as.PtrInit().Append(ir.NewDecl(base.Pos, ir.ODCL, n.(*ir.Name)))
1565 init = append(init, typecheck.Stmt(as))
1567 init = append(init, ir.NewBranchStmt(base.Pos, ir.OGOTO, subst.retlabel))
1568 typecheck.Stmts(init)
1569 return ir.NewBlockStmt(base.Pos, init)
1571 case ir.OGOTO, ir.OBREAK, ir.OCONTINUE:
1572 if subst.newclofn != nil {
1573 // Don't do special substitutions if inside a closure
1576 n := n.(*ir.BranchStmt)
1577 m := ir.Copy(n).(*ir.BranchStmt)
1578 m.SetPos(subst.updatedPos(m.Pos()))
1580 m.Label = translateLabel(n.Label)
1584 if subst.newclofn != nil {
1585 // Don't do special substitutions if inside a closure
1588 n := n.(*ir.LabelStmt)
1589 m := ir.Copy(n).(*ir.LabelStmt)
1590 m.SetPos(subst.updatedPos(m.Pos()))
1592 m.Label = translateLabel(n.Label)
1596 return subst.closure(n.(*ir.ClosureExpr))
1601 m.SetPos(subst.updatedPos(m.Pos()))
1602 ir.EditChildren(m, subst.edit)
1604 if subst.newclofn == nil {
1605 // Translate any label on FOR, RANGE loops, SWITCH or SELECT
1608 m := m.(*ir.ForStmt)
1609 m.Label = translateLabel(m.Label)
1613 m := m.(*ir.RangeStmt)
1614 m.Label = translateLabel(m.Label)
1618 m := m.(*ir.SwitchStmt)
1619 m.Label = translateLabel(m.Label)
1623 m := m.(*ir.SelectStmt)
1624 m.Label = translateLabel(m.Label)
1629 switch m := m.(type) {
1630 case *ir.AssignStmt:
1631 if lhs, ok := m.X.(*ir.Name); ok && lhs.Defn == &subst.defnMarker {
1634 case *ir.AssignListStmt:
1635 for _, lhs := range m.Lhs {
1636 if lhs, ok := lhs.(*ir.Name); ok && lhs.Defn == &subst.defnMarker {
1645 // translateLabel makes a label from an inlined function (if non-nil) be unique by
1646 // adding "·inlgen".
1647 func translateLabel(l *types.Sym) *types.Sym {
1651 p := fmt.Sprintf("%s·%d", l.Name, inlgen)
1652 return typecheck.Lookup(p)
1655 func (subst *inlsubst) updatedPos(xpos src.XPos) src.XPos {
1656 if subst.noPosUpdate {
1659 pos := base.Ctxt.PosTable.Pos(xpos)
1660 oldbase := pos.Base() // can be nil
1661 newbase := subst.bases[oldbase]
1663 newbase = src.NewInliningBase(oldbase, subst.newInlIndex)
1664 subst.bases[oldbase] = newbase
1666 pos.SetBase(newbase)
1667 return base.Ctxt.PosTable.XPos(pos)
1670 func pruneUnusedAutos(ll []*ir.Name, vis *hairyVisitor) []*ir.Name {
1671 s := make([]*ir.Name, 0, len(ll))
1672 for _, n := range ll {
1673 if n.Class == ir.PAUTO {
1674 if !vis.usedLocals.Has(n) {
1683 // numNonClosures returns the number of functions in list which are not closures.
1684 func numNonClosures(list []*ir.Func) int {
1686 for _, fn := range list {
1687 if fn.OClosure == nil {
1694 func doList(list []ir.Node, do func(ir.Node) bool) bool {
1695 for _, x := range list {
1705 // isIndexingCoverageCounter returns true if the specified node 'n' is indexing
1706 // into a coverage counter array.
1707 func isIndexingCoverageCounter(n ir.Node) bool {
1708 if n.Op() != ir.OINDEX {
1711 ixn := n.(*ir.IndexExpr)
1712 if ixn.X.Op() != ir.ONAME || !ixn.X.Type().IsArray() {
1715 nn := ixn.X.(*ir.Name)
1716 return nn.CoverageCounter()
1719 // isAtomicCoverageCounterUpdate examines the specified node to
1720 // determine whether it represents a call to sync/atomic.AddUint32 to
1721 // increment a coverage counter.
1722 func isAtomicCoverageCounterUpdate(cn *ir.CallExpr) bool {
1723 if cn.X.Op() != ir.ONAME {
1726 name := cn.X.(*ir.Name)
1727 if name.Class != ir.PFUNC {
1730 fn := name.Sym().Name
1731 if name.Sym().Pkg.Path != "sync/atomic" ||
1732 (fn != "AddUint32" && fn != "StoreUint32") {
1735 if len(cn.Args) != 2 || cn.Args[0].Op() != ir.OADDR {
1738 adn := cn.Args[0].(*ir.AddrExpr)
1739 v := isIndexingCoverageCounter(adn.X)