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.
36 "cmd/compile/internal/base"
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"
46 // Inlining budget parameters, gathered in one place
49 inlineExtraAppendCost = 0
50 // default is to inline if there's at most one call. -l=4 overrides this by using 1 instead.
51 inlineExtraCallCost = 57 // 57 was benchmarked to provided most benefit with no bad surprises; see https://github.com/golang/go/issues/19348#issuecomment-439370742
52 inlineExtraPanicCost = 1 // do not penalize inlining panics.
53 inlineExtraThrowCost = inlineMaxBudget // with current (2018-05/1.11) code, inlining runtime.throw does not help.
55 inlineBigFunctionNodes = 5000 // Functions with this many nodes are considered "big".
56 inlineBigFunctionMaxCost = 20 // Max cost of inlinee when inlining into a "big" function.
60 // List of all hot callee nodes.
61 // TODO(prattmic): Make this non-global.
62 candHotCalleeMap = make(map[*pgo.IRNode]struct{})
64 // List of all hot call sites. CallSiteInfo.Callee is always nil.
65 // TODO(prattmic): Make this non-global.
66 candHotEdgeMap = make(map[pgo.CallSiteInfo]struct{})
68 // List of inlined call sites. CallSiteInfo.Callee is always nil.
69 // TODO(prattmic): Make this non-global.
70 inlinedCallSites = make(map[pgo.CallSiteInfo]struct{})
72 // Threshold in percentage for hot callsite inlining.
73 inlineHotCallSiteThresholdPercent float64
75 // Threshold in CDF percentage for hot callsite inlining,
76 // that is, for a threshold of X the hottest callsites that
77 // make up the top X% of total edge weight will be
78 // considered hot for inlining candidates.
79 inlineCDFHotCallSiteThresholdPercent = float64(95)
81 // Budget increased due to hotness.
82 inlineHotMaxBudget int32 = 160
85 // pgoInlinePrologue records the hot callsites from ir-graph.
86 func pgoInlinePrologue(p *pgo.Profile) {
87 if s, err := strconv.ParseFloat(base.Debug.InlineHotCallSiteCDFThreshold, 64); err == nil {
88 inlineCDFHotCallSiteThresholdPercent = s
90 var hotCallsites []pgo.NodeMapKey
91 inlineHotCallSiteThresholdPercent, hotCallsites = computeThresholdFromCDF(p)
92 if base.Debug.PGOInline > 0 {
93 fmt.Printf("hot-callsite-thres-from-CDF=%v\n", inlineHotCallSiteThresholdPercent)
96 if base.Debug.InlineHotBudget != 0 {
97 inlineHotMaxBudget = int32(base.Debug.InlineHotBudget)
100 // mark inlineable callees from hot edges
101 for _, n := range hotCallsites {
102 if fn := p.WeightedCG.IRNodes[n.CalleeName]; fn != nil {
103 candHotCalleeMap[fn] = struct{}{}
106 // mark hot call sites
107 ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
108 for _, f := range list {
109 name := ir.PkgFuncName(f)
110 if n, ok := p.WeightedCG.IRNodes[name]; ok {
111 for _, e := range p.WeightedCG.OutEdges[n] {
113 edgeweightpercent := pgo.WeightInPercentage(e.Weight, p.TotalEdgeWeight)
114 if edgeweightpercent > inlineHotCallSiteThresholdPercent {
115 csi := pgo.CallSiteInfo{LineOffset: e.CallSiteOffset, Caller: n.AST}
116 if _, ok := candHotEdgeMap[csi]; !ok {
117 candHotEdgeMap[csi] = struct{}{}
125 if base.Debug.PGOInline >= 2 {
126 fmt.Printf("hot-cg before inline in dot format:")
127 p.PrintWeightedCallGraphDOT(inlineHotCallSiteThresholdPercent)
131 // computeThresholdFromCDF computes an edge weight threshold based on the
132 // CDF of edge weights from the profile. Returns the threshold, and the
133 // list of edges that make up the given percentage of the CDF.
134 func computeThresholdFromCDF(p *pgo.Profile) (float64, []pgo.NodeMapKey) {
135 nodes := make([]pgo.NodeMapKey, len(p.NodeMap))
137 for n := range p.NodeMap {
141 sort.Slice(nodes, func(i, j int) bool {
142 ni, nj := nodes[i], nodes[j]
143 if wi, wj := p.NodeMap[ni].EWeight, p.NodeMap[nj].EWeight; wi != wj {
144 return wi > wj // want larger weight first
146 // same weight, order by name/line number
147 if ni.CallerName != nj.CallerName {
148 return ni.CallerName < nj.CallerName
150 if ni.CalleeName != nj.CalleeName {
151 return ni.CalleeName < nj.CalleeName
153 return ni.CallSiteOffset < nj.CallSiteOffset
156 for i, n := range nodes {
157 w := p.NodeMap[n].EWeight
159 if pgo.WeightInPercentage(cum, p.TotalEdgeWeight) > inlineCDFHotCallSiteThresholdPercent {
160 return pgo.WeightInPercentage(w, p.TotalEdgeWeight), nodes[:i]
166 // pgoInlineEpilogue updates IRGraph after inlining.
167 func pgoInlineEpilogue(p *pgo.Profile) {
168 if base.Debug.PGOInline >= 2 {
169 ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
170 for _, f := range list {
171 name := ir.PkgFuncName(f)
172 if n, ok := p.WeightedCG.IRNodes[name]; ok {
173 p.RedirectEdges(n, inlinedCallSites)
177 // Print the call-graph after inlining. This is a debugging feature.
178 fmt.Printf("hot-cg after inline in dot:")
179 p.PrintWeightedCallGraphDOT(inlineHotCallSiteThresholdPercent)
183 // InlinePackage finds functions that can be inlined and clones them before walk expands them.
184 func InlinePackage(p *pgo.Profile) {
189 ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
190 numfns := numNonClosures(list)
191 for _, n := range list {
192 if !recursive || numfns > 1 {
193 // We allow inlining if there is no
194 // recursion, or the recursion cycle is
195 // across more than one function.
198 if base.Flag.LowerM > 1 {
199 fmt.Printf("%v: cannot inline %v: recursive\n", ir.Line(n), n.Nname)
211 // CanInline determines whether fn is inlineable.
212 // If so, CanInline saves copies of fn.Body and fn.Dcl in fn.Inl.
213 // fn and fn.Body will already have been typechecked.
214 func CanInline(fn *ir.Func, profile *pgo.Profile) {
216 base.Fatalf("CanInline no nname %+v", fn)
219 var reason string // reason, if any, that the function was not inlined
220 if base.Flag.LowerM > 1 || logopt.Enabled() {
223 if base.Flag.LowerM > 1 {
224 fmt.Printf("%v: cannot inline %v: %s\n", ir.Line(fn), fn.Nname, reason)
226 if logopt.Enabled() {
227 logopt.LogOpt(fn.Pos(), "cannotInlineFunction", "inline", ir.FuncName(fn), reason)
233 // If marked "go:noinline", don't inline
234 if fn.Pragma&ir.Noinline != 0 {
235 reason = "marked go:noinline"
239 // If marked "go:norace" and -race compilation, don't inline.
240 if base.Flag.Race && fn.Pragma&ir.Norace != 0 {
241 reason = "marked go:norace with -race compilation"
245 // If marked "go:nocheckptr" and -d checkptr compilation, don't inline.
246 if base.Debug.Checkptr != 0 && fn.Pragma&ir.NoCheckPtr != 0 {
247 reason = "marked go:nocheckptr"
251 // If marked "go:cgo_unsafe_args", don't inline, since the
252 // function makes assumptions about its argument frame layout.
253 if fn.Pragma&ir.CgoUnsafeArgs != 0 {
254 reason = "marked go:cgo_unsafe_args"
258 // If marked as "go:uintptrkeepalive", don't inline, since the
259 // keep alive information is lost during inlining.
261 // TODO(prattmic): This is handled on calls during escape analysis,
262 // which is after inlining. Move prior to inlining so the keep-alive is
263 // maintained after inlining.
264 if fn.Pragma&ir.UintptrKeepAlive != 0 {
265 reason = "marked as having a keep-alive uintptr argument"
269 // If marked as "go:uintptrescapes", don't inline, since the
270 // escape information is lost during inlining.
271 if fn.Pragma&ir.UintptrEscapes != 0 {
272 reason = "marked as having an escaping uintptr argument"
276 // The nowritebarrierrec checker currently works at function
277 // granularity, so inlining yeswritebarrierrec functions can
278 // confuse it (#22342). As a workaround, disallow inlining
280 if fn.Pragma&ir.Yeswritebarrierrec != 0 {
281 reason = "marked go:yeswritebarrierrec"
285 // If fn has no body (is defined outside of Go), cannot inline it.
286 if len(fn.Body) == 0 {
287 reason = "no function body"
291 if fn.Typecheck() == 0 {
292 base.Fatalf("CanInline on non-typechecked function %v", fn)
296 if n.Func.InlinabilityChecked() {
299 defer n.Func.SetInlinabilityChecked(true)
301 cc := int32(inlineExtraCallCost)
302 if base.Flag.LowerL == 4 {
303 cc = 1 // this appears to yield better performance than 0.
306 // Update the budget for profile-guided inlining.
307 budget := int32(inlineMaxBudget)
309 if n, ok := profile.WeightedCG.IRNodes[ir.PkgFuncName(fn)]; ok {
310 if _, ok := candHotCalleeMap[n]; ok {
311 budget = int32(inlineHotMaxBudget)
312 if base.Debug.PGOInline > 0 {
313 fmt.Printf("hot-node enabled increased budget=%v for func=%v\n", budget, ir.PkgFuncName(fn))
319 // At this point in the game the function we're looking at may
320 // have "stale" autos, vars that still appear in the Dcl list, but
321 // which no longer have any uses in the function body (due to
322 // elimination by deadcode). We'd like to exclude these dead vars
323 // when creating the "Inline.Dcl" field below; to accomplish this,
324 // the hairyVisitor below builds up a map of used/referenced
325 // locals, and we use this map to produce a pruned Inline.Dcl
326 // list. See issue 25249 for more context.
328 visitor := hairyVisitor{
335 if visitor.tooHairy(fn) {
336 reason = visitor.reason
340 n.Func.Inl = &ir.Inline{
341 Cost: budget - visitor.budget,
342 Dcl: pruneUnusedAutos(n.Defn.(*ir.Func).Dcl, &visitor),
343 Body: inlcopylist(fn.Body),
345 CanDelayResults: canDelayResults(fn),
348 if base.Flag.LowerM > 1 {
349 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))
350 } else if base.Flag.LowerM != 0 {
351 fmt.Printf("%v: can inline %v\n", ir.Line(fn), n)
353 if logopt.Enabled() {
354 logopt.LogOpt(fn.Pos(), "canInlineFunction", "inline", ir.FuncName(fn), fmt.Sprintf("cost: %d", budget-visitor.budget))
358 // canDelayResults reports whether inlined calls to fn can delay
359 // declaring the result parameter until the "return" statement.
360 func canDelayResults(fn *ir.Func) bool {
361 // We can delay declaring+initializing result parameters if:
362 // (1) there's exactly one "return" statement in the inlined function;
363 // (2) it's not an empty return statement (#44355); and
364 // (3) the result parameters aren't named.
367 ir.VisitList(fn.Body, func(n ir.Node) {
368 if n, ok := n.(*ir.ReturnStmt); ok {
370 if len(n.Results) == 0 {
371 nreturns++ // empty return statement (case 2)
377 return false // not exactly one return statement (case 1)
380 // temporaries for return values.
381 for _, param := range fn.Type().Results().FieldSlice() {
382 if sym := types.OrigSym(param.Sym); sym != nil && !sym.IsBlank() {
383 return false // found a named result parameter (case 3)
390 // hairyVisitor visits a function body to determine its inlining
391 // hairiness and whether or not it can be inlined.
392 type hairyVisitor struct {
393 // This is needed to access the current caller in the doNode function.
399 usedLocals ir.NameSet
400 do func(ir.Node) bool
404 func (v *hairyVisitor) tooHairy(fn *ir.Func) bool {
405 v.do = v.doNode // cache closure
406 if ir.DoChildren(fn, v.do) {
410 v.reason = fmt.Sprintf("function too complex: cost %d exceeds budget %d", v.maxBudget-v.budget, v.maxBudget)
416 func (v *hairyVisitor) doNode(n ir.Node) bool {
421 // Call is okay if inlinable and we have the budget for the body.
423 n := n.(*ir.CallExpr)
424 // Functions that call runtime.getcaller{pc,sp} can not be inlined
425 // because getcaller{pc,sp} expect a pointer to the caller's first argument.
427 // runtime.throw is a "cheap call" like panic in normal code.
428 if n.X.Op() == ir.ONAME {
429 name := n.X.(*ir.Name)
430 if name.Class == ir.PFUNC && types.IsRuntimePkg(name.Sym().Pkg) {
431 fn := name.Sym().Name
432 if fn == "getcallerpc" || fn == "getcallersp" {
433 v.reason = "call to " + fn
437 v.budget -= inlineExtraThrowCost
441 // Special case for coverage counter updates; although
442 // these correspond to real operations, we treat them as
443 // zero cost for the moment. This is due to the existence
444 // of tests that are sensitive to inlining-- if the
445 // insertion of coverage instrumentation happens to tip a
446 // given function over the threshold and move it from
447 // "inlinable" to "not-inlinable", this can cause changes
448 // in allocation behavior, which can then result in test
449 // failures (a good example is the TestAllocations in
451 if isAtomicCoverageCounterUpdate(n) {
455 if n.X.Op() == ir.OMETHEXPR {
456 if meth := ir.MethodExprName(n.X); meth != nil {
457 if fn := meth.Func; fn != nil {
460 if types.IsRuntimePkg(s.Pkg) && s.Name == "heapBits.nextArena" {
461 // Special case: explicitly allow mid-stack inlining of
462 // runtime.heapBits.next even though it calls slow-path
463 // runtime.heapBits.nextArena.
466 // Special case: on architectures that can do unaligned loads,
467 // explicitly mark encoding/binary methods as cheap,
468 // because in practice they are, even though our inlining
469 // budgeting system does not see that. See issue 42958.
470 if base.Ctxt.Arch.CanMergeLoads && s.Pkg.Path == "encoding/binary" {
472 case "littleEndian.Uint64", "littleEndian.Uint32", "littleEndian.Uint16",
473 "bigEndian.Uint64", "bigEndian.Uint32", "bigEndian.Uint16",
474 "littleEndian.PutUint64", "littleEndian.PutUint32", "littleEndian.PutUint16",
475 "bigEndian.PutUint64", "bigEndian.PutUint32", "bigEndian.PutUint16",
476 "littleEndian.AppendUint64", "littleEndian.AppendUint32", "littleEndian.AppendUint16",
477 "bigEndian.AppendUint64", "bigEndian.AppendUint32", "bigEndian.AppendUint16":
482 break // treat like any other node, that is, cost of 1
488 // Determine if the callee edge is for an inlinable hot callee or not.
489 if v.profile != nil && v.curFunc != nil {
490 if fn := inlCallee(n.X, v.profile); fn != nil && typecheck.HaveInlineBody(fn) {
491 lineOffset := pgo.NodeLineOffset(n, fn)
492 csi := pgo.CallSiteInfo{LineOffset: lineOffset, Caller: v.curFunc}
493 if _, o := candHotEdgeMap[csi]; o {
494 if base.Debug.PGOInline > 0 {
495 fmt.Printf("hot-callsite identified at line=%v for func=%v\n", ir.Line(n), ir.PkgFuncName(v.curFunc))
501 if ir.IsIntrinsicCall(n) {
502 // Treat like any other node.
506 if fn := inlCallee(n.X, v.profile); fn != nil && typecheck.HaveInlineBody(fn) {
507 v.budget -= fn.Inl.Cost
511 // Call cost for non-leaf inlining.
512 v.budget -= v.extraCallCost
515 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
517 // Things that are too hairy, irrespective of the budget
518 case ir.OCALL, ir.OCALLINTER:
519 // Call cost for non-leaf inlining.
520 v.budget -= v.extraCallCost
523 n := n.(*ir.UnaryExpr)
524 if n.X.Op() == ir.OCONVIFACE && n.X.(*ir.ConvExpr).Implicit() {
525 // Hack to keep reflect.flag.mustBe inlinable for TestIntendedInlining.
526 // Before CL 284412, these conversions were introduced later in the
527 // compiler, so they didn't count against inlining budget.
530 v.budget -= inlineExtraPanicCost
533 // recover matches the argument frame pointer to find
534 // the right panic value, so it needs an argument frame.
535 v.reason = "call to recover"
539 if base.Debug.InlFuncsWithClosures == 0 {
540 v.reason = "not inlining functions with closures"
544 // TODO(danscales): Maybe make budget proportional to number of closure
546 //v.budget -= int32(len(n.(*ir.ClosureExpr).Func.ClosureVars) * 3)
548 // Scan body of closure (which DoChildren doesn't automatically
549 // do) to check for disallowed ops in the body and include the
550 // body in the budget.
551 if doList(n.(*ir.ClosureExpr).Func.Body, v.do) {
557 ir.ODCLTYPE, // can't print yet
559 v.reason = "unhandled op " + n.Op().String()
563 v.budget -= inlineExtraAppendCost
566 n := n.(*ir.AddrExpr)
567 // Make "&s.f" cost 0 when f's offset is zero.
568 if dot, ok := n.X.(*ir.SelectorExpr); ok && (dot.Op() == ir.ODOT || dot.Op() == ir.ODOTPTR) {
569 if _, ok := dot.X.(*ir.Name); ok && dot.Selection.Offset == 0 {
570 v.budget += 2 // undo ir.OADDR+ir.ODOT/ir.ODOTPTR
575 // *(*X)(unsafe.Pointer(&x)) is low-cost
576 n := n.(*ir.StarExpr)
579 for ptr.Op() == ir.OCONVNOP {
580 ptr = ptr.(*ir.ConvExpr).X
582 if ptr.Op() == ir.OADDR {
583 v.budget += 1 // undo half of default cost of ir.ODEREF+ir.OADDR
587 // This doesn't produce code, but the children might.
588 v.budget++ // undo default cost
590 case ir.ODCLCONST, ir.OFALL:
591 // These nodes don't produce code; omit from inlining budget.
596 if ir.IsConst(n.Cond, constant.Bool) {
597 // This if and the condition cost nothing.
598 if doList(n.Init(), v.do) {
601 if ir.BoolVal(n.Cond) {
602 return doList(n.Body, v.do)
604 return doList(n.Else, v.do)
610 if n.Class == ir.PAUTO {
615 // The only OBLOCK we should see at this point is an empty one.
616 // In any event, let the visitList(n.List()) below take care of the statements,
617 // and don't charge for the OBLOCK itself. The ++ undoes the -- below.
620 case ir.OMETHVALUE, ir.OSLICELIT:
621 v.budget-- // Hack for toolstash -cmp.
624 v.budget++ // Hack for toolstash -cmp.
627 n := n.(*ir.AssignListStmt)
629 // Unified IR unconditionally rewrites:
640 // so that it can insert implicit conversions as necessary. To
641 // minimize impact to the existing inlining heuristics (in
642 // particular, to avoid breaking the existing inlinability regress
643 // tests), we need to compensate for this here.
644 if base.Debug.Unified != 0 {
645 if init := n.Rhs[0].Init(); len(init) == 1 {
646 if _, ok := init[0].(*ir.AssignListStmt); ok {
647 // 4 for each value, because each temporary variable now
648 // appears 3 times (DCL, LHS, RHS), plus an extra DCL node.
650 // 1 for the extra "tmp1, tmp2 = f()" assignment statement.
651 v.budget += 4*int32(len(n.Lhs)) + 1
657 // Special case for coverage counter updates and coverage
658 // function registrations. Although these correspond to real
659 // operations, we treat them as zero cost for the moment. This
660 // is primarily due to the existence of tests that are
661 // sensitive to inlining-- if the insertion of coverage
662 // instrumentation happens to tip a given function over the
663 // threshold and move it from "inlinable" to "not-inlinable",
664 // this can cause changes in allocation behavior, which can
665 // then result in test failures (a good example is the
666 // TestAllocations in crypto/ed25519).
667 n := n.(*ir.AssignStmt)
668 if n.X.Op() == ir.OINDEX && isIndexingCoverageCounter(n.X) {
675 // When debugging, don't stop early, to get full cost of inlining this function
676 if v.budget < 0 && base.Flag.LowerM < 2 && !logopt.Enabled() {
677 v.reason = "too expensive"
681 return ir.DoChildren(n, v.do)
684 func isBigFunc(fn *ir.Func) bool {
685 budget := inlineBigFunctionNodes
686 return ir.Any(fn, func(n ir.Node) bool {
692 // inlcopylist (together with inlcopy) recursively copies a list of nodes, except
693 // that it keeps the same ONAME, OTYPE, and OLITERAL nodes. It is used for copying
694 // the body and dcls of an inlineable function.
695 func inlcopylist(ll []ir.Node) []ir.Node {
696 s := make([]ir.Node, len(ll))
697 for i, n := range ll {
703 // inlcopy is like DeepCopy(), but does extra work to copy closures.
704 func inlcopy(n ir.Node) ir.Node {
705 var edit func(ir.Node) ir.Node
706 edit = func(x ir.Node) ir.Node {
708 case ir.ONAME, ir.OTYPE, ir.OLITERAL, ir.ONIL:
712 ir.EditChildren(m, edit)
713 if x.Op() == ir.OCLOSURE {
714 x := x.(*ir.ClosureExpr)
715 // Need to save/duplicate x.Func.Nname,
716 // x.Func.Nname.Ntype, x.Func.Dcl, x.Func.ClosureVars, and
717 // x.Func.Body for iexport and local inlining.
719 newfn := ir.NewFunc(oldfn.Pos())
720 m.(*ir.ClosureExpr).Func = newfn
721 newfn.Nname = ir.NewNameAt(oldfn.Nname.Pos(), oldfn.Nname.Sym())
722 // XXX OK to share fn.Type() ??
723 newfn.Nname.SetType(oldfn.Nname.Type())
724 newfn.Body = inlcopylist(oldfn.Body)
725 // Make shallow copy of the Dcl and ClosureVar slices
726 newfn.Dcl = append([]*ir.Name(nil), oldfn.Dcl...)
727 newfn.ClosureVars = append([]*ir.Name(nil), oldfn.ClosureVars...)
734 // InlineCalls/inlnode walks fn's statements and expressions and substitutes any
735 // calls made to inlineable functions. This is the external entry point.
736 func InlineCalls(fn *ir.Func, profile *pgo.Profile) {
739 maxCost := int32(inlineMaxBudget)
741 maxCost = inlineBigFunctionMaxCost
743 var inlCalls []*ir.InlinedCallExpr
744 var edit func(ir.Node) ir.Node
745 edit = func(n ir.Node) ir.Node {
746 return inlnode(n, maxCost, &inlCalls, edit, profile)
748 ir.EditChildren(fn, edit)
750 // If we inlined any calls, we want to recursively visit their
751 // bodies for further inlining. However, we need to wait until
752 // *after* the original function body has been expanded, or else
753 // inlCallee can have false positives (e.g., #54632).
754 for len(inlCalls) > 0 {
756 inlCalls = inlCalls[1:]
757 ir.EditChildren(call, edit)
763 // inlnode recurses over the tree to find inlineable calls, which will
764 // be turned into OINLCALLs by mkinlcall. When the recursion comes
765 // back up will examine left, right, list, rlist, ninit, ntest, nincr,
766 // nbody and nelse and use one of the 4 inlconv/glue functions above
767 // to turn the OINLCALL into an expression, a statement, or patch it
768 // in to this nodes list or rlist as appropriate.
769 // NOTE it makes no sense to pass the glue functions down the
770 // recursion to the level where the OINLCALL gets created because they
771 // have to edit /this/ n, so you'd have to push that one down as well,
772 // but then you may as well do it here. so this is cleaner and
773 // shorter and less complicated.
774 // The result of inlnode MUST be assigned back to n, e.g.
776 // n.Left = inlnode(n.Left)
777 func inlnode(n ir.Node, maxCost int32, inlCalls *[]*ir.InlinedCallExpr, edit func(ir.Node) ir.Node, profile *pgo.Profile) ir.Node {
783 case ir.ODEFER, ir.OGO:
784 n := n.(*ir.GoDeferStmt)
785 switch call := n.Call; call.Op() {
787 base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
789 call := call.(*ir.CallExpr)
793 n := n.(*ir.TailCallStmt)
794 n.Call.NoInline = true // Not inline a tail call for now. Maybe we could inline it just like RETURN fn(arg)?
796 // TODO do them here (or earlier),
797 // so escape analysis can avoid more heapmoves.
801 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
803 n := n.(*ir.CallExpr)
804 if n.X.Op() == ir.OMETHEXPR {
805 // Prevent inlining some reflect.Value methods when using checkptr,
806 // even when package reflect was compiled without it (#35073).
807 if meth := ir.MethodExprName(n.X); meth != nil {
809 if base.Debug.Checkptr != 0 && types.IsReflectPkg(s.Pkg) && (s.Name == "Value.UnsafeAddr" || s.Name == "Value.Pointer") {
818 ir.EditChildren(n, edit)
820 // with all the branches out of the way, it is now time to
821 // transmogrify this node itself unless inhibited by the
822 // switch at the top of this function.
825 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
828 call := n.(*ir.CallExpr)
832 if base.Flag.LowerM > 3 {
833 fmt.Printf("%v:call to func %+v\n", ir.Line(n), call.X)
835 if ir.IsIntrinsicCall(call) {
838 if fn := inlCallee(call.X, profile); fn != nil && typecheck.HaveInlineBody(fn) {
839 n = mkinlcall(call, fn, maxCost, inlCalls, edit)
848 // inlCallee takes a function-typed expression and returns the underlying function ONAME
849 // that it refers to if statically known. Otherwise, it returns nil.
850 func inlCallee(fn ir.Node, profile *pgo.Profile) *ir.Func {
851 fn = ir.StaticValue(fn)
854 fn := fn.(*ir.SelectorExpr)
855 n := ir.MethodExprName(fn)
856 // Check that receiver type matches fn.X.
857 // TODO(mdempsky): Handle implicit dereference
858 // of pointer receiver argument?
859 if n == nil || !types.Identical(n.Type().Recv().Type, fn.X.Type()) {
865 if fn.Class == ir.PFUNC {
869 fn := fn.(*ir.ClosureExpr)
871 CanInline(c, profile)
877 func inlParam(t *types.Field, as ir.InitNode, inlvars map[*ir.Name]*ir.Name) ir.Node {
881 n := t.Nname.(*ir.Name)
887 base.Fatalf("missing inlvar for %v", n)
889 as.PtrInit().Append(ir.NewDecl(base.Pos, ir.ODCL, inlvar))
890 inlvar.Name().Defn = as
896 // SSADumpInline gives the SSA back end a chance to dump the function
897 // when producing output for debugging the compiler itself.
898 var SSADumpInline = func(*ir.Func) {}
900 // InlineCall allows the inliner implementation to be overridden.
901 // If it returns nil, the function will not be inlined.
902 var InlineCall = oldInlineCall
904 // If n is a OCALLFUNC node, and fn is an ONAME node for a
905 // function with an inlinable body, return an OINLCALL node that can replace n.
906 // The returned node's Ninit has the parameter assignments, the Nbody is the
907 // inlined function body, and (List, Rlist) contain the (input, output)
909 // The result of mkinlcall MUST be assigned back to n, e.g.
911 // n.Left = mkinlcall(n.Left, fn, isddd)
912 func mkinlcall(n *ir.CallExpr, fn *ir.Func, maxCost int32, inlCalls *[]*ir.InlinedCallExpr, edit func(ir.Node) ir.Node) ir.Node {
914 if logopt.Enabled() {
915 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
916 fmt.Sprintf("%s cannot be inlined", ir.PkgFuncName(fn)))
920 if fn.Inl.Cost > maxCost {
921 // If the callsite is hot and it is under the inlineHotMaxBudget budget, then try to inline it, or else bail.
922 lineOffset := pgo.NodeLineOffset(n, ir.CurFunc)
923 csi := pgo.CallSiteInfo{LineOffset: lineOffset, Caller: ir.CurFunc}
924 if _, ok := candHotEdgeMap[csi]; ok {
925 if fn.Inl.Cost > inlineHotMaxBudget {
926 if logopt.Enabled() {
927 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
928 fmt.Sprintf("cost %d of %s exceeds max large caller cost %d", fn.Inl.Cost, ir.PkgFuncName(fn), inlineHotMaxBudget))
932 if base.Debug.PGOInline > 0 {
933 fmt.Printf("hot-budget check allows inlining for call %s at %v\n", ir.PkgFuncName(fn), ir.Line(n))
936 // The inlined function body is too big. Typically we use this check to restrict
937 // inlining into very big functions. See issue 26546 and 17566.
938 if logopt.Enabled() {
939 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
940 fmt.Sprintf("cost %d of %s exceeds max large caller cost %d", fn.Inl.Cost, ir.PkgFuncName(fn), maxCost))
946 if fn == ir.CurFunc {
947 // Can't recursively inline a function into itself.
948 if logopt.Enabled() {
949 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", fmt.Sprintf("recursive call to %s", ir.FuncName(ir.CurFunc)))
954 // The non-unified frontend has issues with inlining and shape parameters.
955 if base.Debug.Unified == 0 {
956 // Don't inline a function fn that has no shape parameters, but is passed at
957 // least one shape arg. This means we must be inlining a non-generic function
958 // fn that was passed into a generic function, and can be called with a shape
959 // arg because it matches an appropriate type parameters. But fn may include
960 // an interface conversion (that may be applied to a shape arg) that was not
961 // apparent when we first created the instantiation of the generic function.
962 // We can't handle this if we actually do the inlining, since we want to know
963 // all interface conversions immediately after stenciling. So, we avoid
964 // inlining in this case, see issue #49309. (1)
966 // See discussion on go.dev/cl/406475 for more background.
967 if !fn.Type().Params().HasShape() {
968 for _, arg := range n.Args {
969 if arg.Type().HasShape() {
970 if logopt.Enabled() {
971 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
972 fmt.Sprintf("inlining function %v has no-shape params with shape args", ir.FuncName(fn)))
978 // Don't inline a function fn that has shape parameters, but is passed no shape arg.
979 // See comments (1) above, and issue #51909.
980 inlineable := len(n.Args) == 0 // Function has shape in type, with no arguments can always be inlined.
981 for _, arg := range n.Args {
982 if arg.Type().HasShape() {
988 if logopt.Enabled() {
989 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
990 fmt.Sprintf("inlining function %v has shape params with no-shape args", ir.FuncName(fn)))
997 if base.Flag.Cfg.Instrumenting && types.IsRuntimePkg(fn.Sym().Pkg) {
998 // Runtime package must not be instrumented.
999 // Instrument skips runtime package. However, some runtime code can be
1000 // inlined into other packages and instrumented there. To avoid this,
1001 // we disable inlining of runtime functions when instrumenting.
1002 // The example that we observed is inlining of LockOSThread,
1003 // which lead to false race reports on m contents.
1007 parent := base.Ctxt.PosTable.Pos(n.Pos()).Base().InliningIndex()
1010 // Check if we've already inlined this function at this particular
1011 // call site, in order to stop inlining when we reach the beginning
1012 // of a recursion cycle again. We don't inline immediately recursive
1013 // functions, but allow inlining if there is a recursion cycle of
1014 // many functions. Most likely, the inlining will stop before we
1015 // even hit the beginning of the cycle again, but this catches the
1017 for inlIndex := parent; inlIndex >= 0; inlIndex = base.Ctxt.InlTree.Parent(inlIndex) {
1018 if base.Ctxt.InlTree.InlinedFunction(inlIndex) == sym {
1019 if base.Flag.LowerM > 1 {
1020 fmt.Printf("%v: cannot inline %v into %v: repeated recursive cycle\n", ir.Line(n), fn, ir.FuncName(ir.CurFunc))
1026 typecheck.FixVariadicCall(n)
1028 inlIndex := base.Ctxt.InlTree.Add(parent, n.Pos(), sym)
1030 closureInitLSym := func(n *ir.CallExpr, fn *ir.Func) {
1031 // The linker needs FuncInfo metadata for all inlined
1032 // functions. This is typically handled by gc.enqueueFunc
1033 // calling ir.InitLSym for all function declarations in
1034 // typecheck.Target.Decls (ir.UseClosure adds all closures to
1037 // However, non-trivial closures in Decls are ignored, and are
1038 // insteaded enqueued when walk of the calling function
1041 // This presents a problem for direct calls to closures.
1042 // Inlining will replace the entire closure definition with its
1043 // body, which hides the closure from walk and thus suppresses
1046 // Explicitly create a symbol early in this edge case to ensure
1047 // we keep this metadata.
1049 // TODO: Refactor to keep a reference so this can all be done
1052 if n.Op() != ir.OCALLFUNC {
1053 // Not a standard call.
1056 if n.X.Op() != ir.OCLOSURE {
1057 // Not a direct closure call.
1061 clo := n.X.(*ir.ClosureExpr)
1062 if ir.IsTrivialClosure(clo) {
1063 // enqueueFunc will handle trivial closures anyways.
1067 ir.InitLSym(fn, true)
1070 closureInitLSym(n, fn)
1072 if base.Flag.GenDwarfInl > 0 {
1073 if !sym.WasInlined() {
1074 base.Ctxt.DwFixups.SetPrecursorFunc(sym, fn)
1075 sym.Set(obj.AttrWasInlined, true)
1079 if base.Flag.LowerM != 0 {
1080 fmt.Printf("%v: inlining call to %v\n", ir.Line(n), fn)
1082 if base.Flag.LowerM > 2 {
1083 fmt.Printf("%v: Before inlining: %+v\n", ir.Line(n), n)
1086 if base.Debug.PGOInline > 0 {
1087 csi := pgo.CallSiteInfo{LineOffset: pgo.NodeLineOffset(n, fn), Caller: ir.CurFunc}
1088 if _, ok := inlinedCallSites[csi]; !ok {
1089 inlinedCallSites[csi] = struct{}{}
1093 res := InlineCall(n, fn, inlIndex)
1096 base.FatalfAt(n.Pos(), "inlining call to %v failed", fn)
1099 if base.Flag.LowerM > 2 {
1100 fmt.Printf("%v: After inlining %+v\n\n", ir.Line(res), res)
1103 *inlCalls = append(*inlCalls, res)
1108 // CalleeEffects appends any side effects from evaluating callee to init.
1109 func CalleeEffects(init *ir.Nodes, callee ir.Node) {
1111 init.Append(ir.TakeInit(callee)...)
1113 switch callee.Op() {
1114 case ir.ONAME, ir.OCLOSURE, ir.OMETHEXPR:
1118 conv := callee.(*ir.ConvExpr)
1122 ic := callee.(*ir.InlinedCallExpr)
1123 init.Append(ic.Body.Take()...)
1124 callee = ic.SingleResult()
1127 base.FatalfAt(callee.Pos(), "unexpected callee expression: %v", callee)
1132 // oldInlineCall creates an InlinedCallExpr to replace the given call
1133 // expression. fn is the callee function to be inlined. inlIndex is
1134 // the inlining tree position index, for use with src.NewInliningBase
1135 // when rewriting positions.
1136 func oldInlineCall(call *ir.CallExpr, fn *ir.Func, inlIndex int) *ir.InlinedCallExpr {
1137 if base.Debug.TypecheckInl == 0 {
1138 typecheck.ImportedBody(fn)
1143 ninit := call.Init()
1145 // For normal function calls, the function callee expression
1146 // may contain side effects. Make sure to preserve these,
1147 // if necessary (#42703).
1148 if call.Op() == ir.OCALLFUNC {
1149 CalleeEffects(&ninit, call.X)
1152 // Make temp names to use instead of the originals.
1153 inlvars := make(map[*ir.Name]*ir.Name)
1155 // record formals/locals for later post-processing
1156 var inlfvars []*ir.Name
1158 for _, ln := range fn.Inl.Dcl {
1159 if ln.Op() != ir.ONAME {
1162 if ln.Class == ir.PPARAMOUT { // return values handled below.
1165 inlf := typecheck.Expr(inlvar(ln)).(*ir.Name)
1167 if base.Flag.GenDwarfInl > 0 {
1168 if ln.Class == ir.PPARAM {
1169 inlf.Name().SetInlFormal(true)
1171 inlf.Name().SetInlLocal(true)
1173 inlf.SetPos(ln.Pos())
1174 inlfvars = append(inlfvars, inlf)
1178 // We can delay declaring+initializing result parameters if:
1179 // temporaries for return values.
1180 var retvars []ir.Node
1181 for i, t := range fn.Type().Results().Fields().Slice() {
1183 if nn := t.Nname; nn != nil && !ir.IsBlank(nn.(*ir.Name)) && !strings.HasPrefix(nn.Sym().Name, "~r") {
1186 m = typecheck.Expr(m).(*ir.Name)
1189 // anonymous return values, synthesize names for use in assignment that replaces return
1193 if base.Flag.GenDwarfInl > 0 {
1194 // Don't update the src.Pos on a return variable if it
1195 // was manufactured by the inliner (e.g. "~R2"); such vars
1196 // were not part of the original callee.
1197 if !strings.HasPrefix(m.Sym().Name, "~R") {
1198 m.Name().SetInlFormal(true)
1200 inlfvars = append(inlfvars, m)
1204 retvars = append(retvars, m)
1207 // Assign arguments to the parameters' temp names.
1208 as := ir.NewAssignListStmt(base.Pos, ir.OAS2, nil, nil)
1210 if call.Op() == ir.OCALLMETH {
1211 base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
1213 as.Rhs.Append(call.Args...)
1215 if recv := fn.Type().Recv(); recv != nil {
1216 as.Lhs.Append(inlParam(recv, as, inlvars))
1218 for _, param := range fn.Type().Params().Fields().Slice() {
1219 as.Lhs.Append(inlParam(param, as, inlvars))
1222 if len(as.Rhs) != 0 {
1223 ninit.Append(typecheck.Stmt(as))
1226 if !fn.Inl.CanDelayResults {
1227 // Zero the return parameters.
1228 for _, n := range retvars {
1229 ninit.Append(ir.NewDecl(base.Pos, ir.ODCL, n.(*ir.Name)))
1230 ras := ir.NewAssignStmt(base.Pos, n, nil)
1231 ninit.Append(typecheck.Stmt(ras))
1235 retlabel := typecheck.AutoLabel(".i")
1239 // Add an inline mark just before the inlined body.
1240 // This mark is inline in the code so that it's a reasonable spot
1241 // to put a breakpoint. Not sure if that's really necessary or not
1242 // (in which case it could go at the end of the function instead).
1243 // Note issue 28603.
1244 ninit.Append(ir.NewInlineMarkStmt(call.Pos().WithIsStmt(), int64(inlIndex)))
1250 defnMarker: ir.NilExpr{},
1251 bases: make(map[*src.PosBase]*src.PosBase),
1252 newInlIndex: inlIndex,
1255 subst.edit = subst.node
1257 body := subst.list(ir.Nodes(fn.Inl.Body))
1259 lab := ir.NewLabelStmt(base.Pos, retlabel)
1260 body = append(body, lab)
1262 if base.Flag.GenDwarfInl > 0 {
1263 for _, v := range inlfvars {
1264 v.SetPos(subst.updatedPos(v.Pos()))
1268 //dumplist("ninit post", ninit);
1270 res := ir.NewInlinedCallExpr(base.Pos, body, retvars)
1272 res.SetType(call.Type())
1277 // Every time we expand a function we generate a new set of tmpnames,
1278 // PAUTO's in the calling functions, and link them off of the
1279 // PPARAM's, PAUTOS and PPARAMOUTs of the called function.
1280 func inlvar(var_ *ir.Name) *ir.Name {
1281 if base.Flag.LowerM > 3 {
1282 fmt.Printf("inlvar %+v\n", var_)
1285 n := typecheck.NewName(var_.Sym())
1286 n.SetType(var_.Type())
1290 n.SetAutoTemp(var_.AutoTemp())
1291 n.Curfn = ir.CurFunc // the calling function, not the called one
1292 n.SetAddrtaken(var_.Addrtaken())
1294 ir.CurFunc.Dcl = append(ir.CurFunc.Dcl, n)
1298 // Synthesize a variable to store the inlined function's results in.
1299 func retvar(t *types.Field, i int) *ir.Name {
1300 n := typecheck.NewName(typecheck.LookupNum("~R", i))
1305 n.Curfn = ir.CurFunc // the calling function, not the called one
1306 ir.CurFunc.Dcl = append(ir.CurFunc.Dcl, n)
1310 // The inlsubst type implements the actual inlining of a single
1312 type inlsubst struct {
1313 // Target of the goto substituted in place of a return.
1316 // Temporary result variables.
1319 inlvars map[*ir.Name]*ir.Name
1320 // defnMarker is used to mark a Node for reassignment.
1321 // inlsubst.clovar set this during creating new ONAME.
1322 // inlsubst.node will set the correct Defn for inlvar.
1323 defnMarker ir.NilExpr
1325 // bases maps from original PosBase to PosBase with an extra
1326 // inlined call frame.
1327 bases map[*src.PosBase]*src.PosBase
1329 // newInlIndex is the index of the inlined call frame to
1330 // insert for inlined nodes.
1333 edit func(ir.Node) ir.Node // cached copy of subst.node method value closure
1335 // If non-nil, we are inside a closure inside the inlined function, and
1336 // newclofn is the Func of the new inlined closure.
1339 fn *ir.Func // For debug -- the func that is being inlined
1341 // If true, then don't update source positions during substitution
1342 // (retain old source positions).
1346 // list inlines a list of nodes.
1347 func (subst *inlsubst) list(ll ir.Nodes) []ir.Node {
1348 s := make([]ir.Node, 0, len(ll))
1349 for _, n := range ll {
1350 s = append(s, subst.node(n))
1355 // fields returns a list of the fields of a struct type representing receiver,
1356 // params, or results, after duplicating the field nodes and substituting the
1357 // Nname nodes inside the field nodes.
1358 func (subst *inlsubst) fields(oldt *types.Type) []*types.Field {
1359 oldfields := oldt.FieldSlice()
1360 newfields := make([]*types.Field, len(oldfields))
1361 for i := range oldfields {
1362 newfields[i] = oldfields[i].Copy()
1363 if oldfields[i].Nname != nil {
1364 newfields[i].Nname = subst.node(oldfields[i].Nname.(*ir.Name))
1370 // clovar creates a new ONAME node for a local variable or param of a closure
1371 // inside a function being inlined.
1372 func (subst *inlsubst) clovar(n *ir.Name) *ir.Name {
1373 m := ir.NewNameAt(n.Pos(), n.Sym())
1377 if n.IsClosureVar() {
1378 m.SetIsClosureVar(true)
1381 m.SetAddrtaken(true)
1388 m.Curfn = subst.newclofn
1390 switch defn := n.Defn.(type) {
1394 if !n.IsClosureVar() {
1395 base.FatalfAt(n.Pos(), "want closure variable, got: %+v", n)
1397 if n.Sym().Pkg != types.LocalPkg {
1398 // If the closure came from inlining a function from
1399 // another package, must change package of captured
1400 // variable to localpkg, so that the fields of the closure
1401 // struct are local package and can be accessed even if
1402 // name is not exported. If you disable this code, you can
1403 // reproduce the problem by running 'go test
1404 // go/internal/srcimporter'. TODO(mdempsky) - maybe change
1405 // how we create closure structs?
1406 m.SetSym(types.LocalPkg.Lookup(n.Sym().Name))
1408 // Make sure any inlvar which is the Defn
1409 // of an ONAME closure var is rewritten
1410 // during inlining. Don't substitute
1411 // if Defn node is outside inlined function.
1412 if subst.inlvars[n.Defn.(*ir.Name)] != nil {
1413 m.Defn = subst.node(n.Defn)
1415 case *ir.AssignStmt, *ir.AssignListStmt:
1416 // Mark node for reassignment at the end of inlsubst.node.
1417 m.Defn = &subst.defnMarker
1418 case *ir.TypeSwitchGuard:
1419 // TODO(mdempsky): Set m.Defn properly. See discussion on #45743.
1421 // TODO: Set m.Defn properly if we support inlining range statement in the future.
1423 base.FatalfAt(n.Pos(), "unexpected Defn: %+v", defn)
1427 // Either the outer variable is defined in function being inlined,
1428 // and we will replace it with the substituted variable, or it is
1429 // defined outside the function being inlined, and we should just
1430 // skip the outer variable (the closure variable of the function
1432 s := subst.node(n.Outer).(*ir.Name)
1441 // closure does the necessary substitions for a ClosureExpr n and returns the new
1443 func (subst *inlsubst) closure(n *ir.ClosureExpr) ir.Node {
1444 // Prior to the subst edit, set a flag in the inlsubst to indicate
1445 // that we don't want to update the source positions in the new
1446 // closure function. If we do this, it will appear that the
1447 // closure itself has things inlined into it, which is not the
1448 // case. See issue #46234 for more details. At the same time, we
1449 // do want to update the position in the new ClosureExpr (which is
1450 // part of the function we're working on). See #49171 for an
1451 // example of what happens if we miss that update.
1452 newClosurePos := subst.updatedPos(n.Pos())
1453 defer func(prev bool) { subst.noPosUpdate = prev }(subst.noPosUpdate)
1454 subst.noPosUpdate = true
1456 //fmt.Printf("Inlining func %v with closure into %v\n", subst.fn, ir.FuncName(ir.CurFunc))
1459 newfn := ir.NewClosureFunc(oldfn.Pos(), true)
1461 if subst.newclofn != nil {
1462 //fmt.Printf("Inlining a closure with a nested closure\n")
1464 prevxfunc := subst.newclofn
1466 // Mark that we are now substituting within a closure (within the
1467 // inlined function), and create new nodes for all the local
1468 // vars/params inside this closure.
1469 subst.newclofn = newfn
1471 newfn.ClosureVars = nil
1472 for _, oldv := range oldfn.Dcl {
1473 newv := subst.clovar(oldv)
1474 subst.inlvars[oldv] = newv
1475 newfn.Dcl = append(newfn.Dcl, newv)
1477 for _, oldv := range oldfn.ClosureVars {
1478 newv := subst.clovar(oldv)
1479 subst.inlvars[oldv] = newv
1480 newfn.ClosureVars = append(newfn.ClosureVars, newv)
1483 // Need to replace ONAME nodes in
1484 // newfn.Type().FuncType().Receiver/Params/Results.FieldSlice().Nname
1485 oldt := oldfn.Type()
1486 newrecvs := subst.fields(oldt.Recvs())
1487 var newrecv *types.Field
1488 if len(newrecvs) > 0 {
1489 newrecv = newrecvs[0]
1491 newt := types.NewSignature(oldt.Pkg(), newrecv,
1492 nil, subst.fields(oldt.Params()), subst.fields(oldt.Results()))
1494 newfn.Nname.SetType(newt)
1495 newfn.Body = subst.list(oldfn.Body)
1497 // Remove the nodes for the current closure from subst.inlvars
1498 for _, oldv := range oldfn.Dcl {
1499 delete(subst.inlvars, oldv)
1501 for _, oldv := range oldfn.ClosureVars {
1502 delete(subst.inlvars, oldv)
1504 // Go back to previous closure func
1505 subst.newclofn = prevxfunc
1507 // Actually create the named function for the closure, now that
1508 // the closure is inlined in a specific function.
1509 newclo := newfn.OClosure
1510 newclo.SetPos(newClosurePos)
1511 newclo.SetInit(subst.list(n.Init()))
1512 return typecheck.Expr(newclo)
1515 // node recursively copies a node from the saved pristine body of the
1516 // inlined function, substituting references to input/output
1517 // parameters with ones to the tmpnames, and substituting returns with
1518 // assignments to the output.
1519 func (subst *inlsubst) node(n ir.Node) ir.Node {
1528 // Handle captured variables when inlining closures.
1529 if n.IsClosureVar() && subst.newclofn == nil {
1532 // Deal with case where sequence of closures are inlined.
1533 // TODO(danscales) - write test case to see if we need to
1534 // go up multiple levels.
1535 if o.Curfn != ir.CurFunc {
1539 // make sure the outer param matches the inlining location
1540 if o == nil || o.Curfn != ir.CurFunc {
1541 base.Fatalf("%v: unresolvable capture %v\n", ir.Line(n), n)
1544 if base.Flag.LowerM > 2 {
1545 fmt.Printf("substituting captured name %+v -> %+v\n", n, o)
1550 if inlvar := subst.inlvars[n]; inlvar != nil { // These will be set during inlnode
1551 if base.Flag.LowerM > 2 {
1552 fmt.Printf("substituting name %+v -> %+v\n", n, inlvar)
1557 if base.Flag.LowerM > 2 {
1558 fmt.Printf("not substituting name %+v\n", n)
1563 n := n.(*ir.SelectorExpr)
1566 case ir.OLITERAL, ir.ONIL, ir.OTYPE:
1567 // If n is a named constant or type, we can continue
1568 // using it in the inline copy. Otherwise, make a copy
1569 // so we can update the line number.
1575 if subst.newclofn != nil {
1576 // Don't do special substitutions if inside a closure
1579 // Because of the above test for subst.newclofn,
1580 // this return is guaranteed to belong to the current inlined function.
1581 n := n.(*ir.ReturnStmt)
1582 init := subst.list(n.Init())
1583 if len(subst.retvars) != 0 && len(n.Results) != 0 {
1584 as := ir.NewAssignListStmt(base.Pos, ir.OAS2, nil, nil)
1586 // Make a shallow copy of retvars.
1587 // Otherwise OINLCALL.Rlist will be the same list,
1588 // and later walk and typecheck may clobber it.
1589 for _, n := range subst.retvars {
1592 as.Rhs = subst.list(n.Results)
1594 if subst.fn.Inl.CanDelayResults {
1595 for _, n := range as.Lhs {
1596 as.PtrInit().Append(ir.NewDecl(base.Pos, ir.ODCL, n.(*ir.Name)))
1601 init = append(init, typecheck.Stmt(as))
1603 init = append(init, ir.NewBranchStmt(base.Pos, ir.OGOTO, subst.retlabel))
1604 typecheck.Stmts(init)
1605 return ir.NewBlockStmt(base.Pos, init)
1607 case ir.OGOTO, ir.OBREAK, ir.OCONTINUE:
1608 if subst.newclofn != nil {
1609 // Don't do special substitutions if inside a closure
1612 n := n.(*ir.BranchStmt)
1613 m := ir.Copy(n).(*ir.BranchStmt)
1614 m.SetPos(subst.updatedPos(m.Pos()))
1616 m.Label = translateLabel(n.Label)
1620 if subst.newclofn != nil {
1621 // Don't do special substitutions if inside a closure
1624 n := n.(*ir.LabelStmt)
1625 m := ir.Copy(n).(*ir.LabelStmt)
1626 m.SetPos(subst.updatedPos(m.Pos()))
1628 m.Label = translateLabel(n.Label)
1632 return subst.closure(n.(*ir.ClosureExpr))
1637 m.SetPos(subst.updatedPos(m.Pos()))
1638 ir.EditChildren(m, subst.edit)
1640 if subst.newclofn == nil {
1641 // Translate any label on FOR, RANGE loops, SWITCH or SELECT
1644 m := m.(*ir.ForStmt)
1645 m.Label = translateLabel(m.Label)
1649 m := m.(*ir.RangeStmt)
1650 m.Label = translateLabel(m.Label)
1654 m := m.(*ir.SwitchStmt)
1655 m.Label = translateLabel(m.Label)
1659 m := m.(*ir.SelectStmt)
1660 m.Label = translateLabel(m.Label)
1665 switch m := m.(type) {
1666 case *ir.AssignStmt:
1667 if lhs, ok := m.X.(*ir.Name); ok && lhs.Defn == &subst.defnMarker {
1670 case *ir.AssignListStmt:
1671 for _, lhs := range m.Lhs {
1672 if lhs, ok := lhs.(*ir.Name); ok && lhs.Defn == &subst.defnMarker {
1681 // translateLabel makes a label from an inlined function (if non-nil) be unique by
1682 // adding "·inlgen".
1683 func translateLabel(l *types.Sym) *types.Sym {
1687 p := fmt.Sprintf("%s·%d", l.Name, inlgen)
1688 return typecheck.Lookup(p)
1691 func (subst *inlsubst) updatedPos(xpos src.XPos) src.XPos {
1692 if subst.noPosUpdate {
1695 pos := base.Ctxt.PosTable.Pos(xpos)
1696 oldbase := pos.Base() // can be nil
1697 newbase := subst.bases[oldbase]
1699 newbase = src.NewInliningBase(oldbase, subst.newInlIndex)
1700 subst.bases[oldbase] = newbase
1702 pos.SetBase(newbase)
1703 return base.Ctxt.PosTable.XPos(pos)
1706 func pruneUnusedAutos(ll []*ir.Name, vis *hairyVisitor) []*ir.Name {
1707 s := make([]*ir.Name, 0, len(ll))
1708 for _, n := range ll {
1709 if n.Class == ir.PAUTO {
1710 if !vis.usedLocals.Has(n) {
1719 // numNonClosures returns the number of functions in list which are not closures.
1720 func numNonClosures(list []*ir.Func) int {
1722 for _, fn := range list {
1723 if fn.OClosure == nil {
1730 func doList(list []ir.Node, do func(ir.Node) bool) bool {
1731 for _, x := range list {
1741 // isIndexingCoverageCounter returns true if the specified node 'n' is indexing
1742 // into a coverage counter array.
1743 func isIndexingCoverageCounter(n ir.Node) bool {
1744 if n.Op() != ir.OINDEX {
1747 ixn := n.(*ir.IndexExpr)
1748 if ixn.X.Op() != ir.ONAME || !ixn.X.Type().IsArray() {
1751 nn := ixn.X.(*ir.Name)
1752 return nn.CoverageCounter()
1755 // isAtomicCoverageCounterUpdate examines the specified node to
1756 // determine whether it represents a call to sync/atomic.AddUint32 to
1757 // increment a coverage counter.
1758 func isAtomicCoverageCounterUpdate(cn *ir.CallExpr) bool {
1759 if cn.X.Op() != ir.ONAME {
1762 name := cn.X.(*ir.Name)
1763 if name.Class != ir.PFUNC {
1766 fn := name.Sym().Name
1767 if name.Sym().Pkg.Path != "sync/atomic" ||
1768 (fn != "AddUint32" && fn != "StoreUint32") {
1771 if len(cn.Args) != 2 || cn.Args[0].Op() != ir.OADDR {
1774 adn := cn.Args[0].(*ir.AddrExpr)
1775 v := isIndexingCoverageCounter(adn.X)