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 ndes.
60 candHotNodeMap = make(map[*pgo.IRNode]struct{})
62 // List of all hot call sites.
63 candHotEdgeMap = make(map[pgo.CallSiteInfo]struct{})
65 // List of inlined call sites.
66 inlinedCallSites = make(map[pgo.CallSiteInfo]struct{})
68 // Threshold in percentage for hot function inlining.
69 inlineHotFuncThresholdPercent = float64(2)
71 // Threshold in percentage for hot callsite inlining.
72 inlineHotCallSiteThresholdPercent = float64(0.1)
74 // Budget increased due to hotness.
75 inlineHotMaxBudget int32 = 160
78 // pgoInlinePrologue records the hot callsites from ir-graph.
79 func pgoInlinePrologue(p *pgo.Profile) {
80 if s, err := strconv.ParseFloat(base.Debug.InlineHotFuncThreshold, 64); err == nil {
81 inlineHotFuncThresholdPercent = s
82 if base.Debug.PGOInline > 0 {
83 fmt.Printf("hot-node-thres=%v\n", inlineHotFuncThresholdPercent)
87 if s, err := strconv.ParseFloat(base.Debug.InlineHotCallSiteThreshold, 64); err == nil {
88 inlineHotCallSiteThresholdPercent = s
89 if base.Debug.PGOInline > 0 {
90 fmt.Printf("hot-callsite-thres=%v\n", inlineHotCallSiteThresholdPercent)
94 if base.Debug.InlineHotBudget != 0 {
95 inlineHotMaxBudget = int32(base.Debug.InlineHotBudget)
98 ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
99 for _, f := range list {
100 name := ir.PkgFuncName(f)
101 if n, ok := p.WeightedCG.IRNodes[name]; ok {
102 nodeweight := pgo.WeightInPercentage(n.Flat, p.TotalNodeWeight)
103 if nodeweight > inlineHotFuncThresholdPercent {
104 candHotNodeMap[n] = struct{}{}
106 for _, e := range p.WeightedCG.OutEdges[n] {
108 edgeweightpercent := pgo.WeightInPercentage(e.Weight, p.TotalEdgeWeight)
109 if edgeweightpercent > inlineHotCallSiteThresholdPercent {
110 csi := pgo.CallSiteInfo{Line: e.CallSite, Caller: n.AST, Callee: e.Dst.AST}
111 if _, ok := candHotEdgeMap[csi]; !ok {
112 candHotEdgeMap[csi] = struct{}{}
120 if base.Debug.PGOInline > 0 {
121 fmt.Printf("hot-cg before inline in dot format:")
122 p.PrintWeightedCallGraphDOT(inlineHotFuncThresholdPercent, inlineHotCallSiteThresholdPercent)
126 // pgoInlineEpilogue updates IRGraph after inlining.
127 func pgoInlineEpilogue(p *pgo.Profile) {
128 if base.Debug.PGOInline > 0 {
129 ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
130 for _, f := range list {
131 name := ir.PkgFuncName(f)
132 if n, ok := p.WeightedCG.IRNodes[name]; ok {
133 p.RedirectEdges(n, inlinedCallSites)
137 // Print the call-graph after inlining. This is a debugging feature.
138 fmt.Printf("hot-cg after inline in dot:")
139 p.PrintWeightedCallGraphDOT(inlineHotFuncThresholdPercent, inlineHotCallSiteThresholdPercent)
143 // InlinePackage finds functions that can be inlined and clones them before walk expands them.
144 func InlinePackage(p *pgo.Profile) {
149 ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
150 numfns := numNonClosures(list)
151 for _, n := range list {
152 if !recursive || numfns > 1 {
153 // We allow inlining if there is no
154 // recursion, or the recursion cycle is
155 // across more than one function.
158 if base.Flag.LowerM > 1 {
159 fmt.Printf("%v: cannot inline %v: recursive\n", ir.Line(n), n.Nname)
171 // CanInline determines whether fn is inlineable.
172 // If so, CanInline saves copies of fn.Body and fn.Dcl in fn.Inl.
173 // fn and fn.Body will already have been typechecked.
174 func CanInline(fn *ir.Func, profile *pgo.Profile) {
176 base.Fatalf("CanInline no nname %+v", fn)
179 // Initialize an empty list of hot callsites for this caller.
180 pgo.ListOfHotCallSites = make(map[pgo.CallSiteInfo]struct{})
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 a for 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, Callee: fn}
456 if _, o := candHotEdgeMap[csi]; o {
457 pgo.ListOfHotCallSites[pgo.CallSiteInfo{Line: line, Caller: v.curFunc}] = struct{}{}
458 if base.Debug.PGOInline > 0 {
459 fmt.Printf("hot-callsite identified at line=%v for func=%v\n", ir.Line(n), ir.PkgFuncName(v.curFunc))
465 if ir.IsIntrinsicCall(n) {
466 // Treat like any other node.
470 if fn := inlCallee(n.X, v.profile); fn != nil && typecheck.HaveInlineBody(fn) {
471 v.budget -= fn.Inl.Cost
475 // Call cost for non-leaf inlining.
476 v.budget -= v.extraCallCost
479 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
481 // Things that are too hairy, irrespective of the budget
482 case ir.OCALL, ir.OCALLINTER:
483 // Call cost for non-leaf inlining.
484 v.budget -= v.extraCallCost
487 n := n.(*ir.UnaryExpr)
488 if n.X.Op() == ir.OCONVIFACE && n.X.(*ir.ConvExpr).Implicit() {
489 // Hack to keep reflect.flag.mustBe inlinable for TestIntendedInlining.
490 // Before CL 284412, these conversions were introduced later in the
491 // compiler, so they didn't count against inlining budget.
494 v.budget -= inlineExtraPanicCost
497 // recover matches the argument frame pointer to find
498 // the right panic value, so it needs an argument frame.
499 v.reason = "call to recover"
503 if base.Debug.InlFuncsWithClosures == 0 {
504 v.reason = "not inlining functions with closures"
508 // TODO(danscales): Maybe make budget proportional to number of closure
510 //v.budget -= int32(len(n.(*ir.ClosureExpr).Func.ClosureVars) * 3)
512 // Scan body of closure (which DoChildren doesn't automatically
513 // do) to check for disallowed ops in the body and include the
514 // body in the budget.
515 if doList(n.(*ir.ClosureExpr).Func.Body, v.do) {
521 ir.ODCLTYPE, // can't print yet
523 v.reason = "unhandled op " + n.Op().String()
527 v.budget -= inlineExtraAppendCost
530 n := n.(*ir.AddrExpr)
531 // Make "&s.f" cost 0 when f's offset is zero.
532 if dot, ok := n.X.(*ir.SelectorExpr); ok && (dot.Op() == ir.ODOT || dot.Op() == ir.ODOTPTR) {
533 if _, ok := dot.X.(*ir.Name); ok && dot.Selection.Offset == 0 {
534 v.budget += 2 // undo ir.OADDR+ir.ODOT/ir.ODOTPTR
539 // *(*X)(unsafe.Pointer(&x)) is low-cost
540 n := n.(*ir.StarExpr)
543 for ptr.Op() == ir.OCONVNOP {
544 ptr = ptr.(*ir.ConvExpr).X
546 if ptr.Op() == ir.OADDR {
547 v.budget += 1 // undo half of default cost of ir.ODEREF+ir.OADDR
551 // This doesn't produce code, but the children might.
552 v.budget++ // undo default cost
554 case ir.ODCLCONST, ir.OFALL:
555 // These nodes don't produce code; omit from inlining budget.
560 if ir.IsConst(n.Cond, constant.Bool) {
561 // This if and the condition cost nothing.
562 if doList(n.Init(), v.do) {
565 if ir.BoolVal(n.Cond) {
566 return doList(n.Body, v.do)
568 return doList(n.Else, v.do)
574 if n.Class == ir.PAUTO {
579 // The only OBLOCK we should see at this point is an empty one.
580 // In any event, let the visitList(n.List()) below take care of the statements,
581 // and don't charge for the OBLOCK itself. The ++ undoes the -- below.
584 case ir.OMETHVALUE, ir.OSLICELIT:
585 v.budget-- // Hack for toolstash -cmp.
588 v.budget++ // Hack for toolstash -cmp.
591 n := n.(*ir.AssignListStmt)
593 // Unified IR unconditionally rewrites:
604 // so that it can insert implicit conversions as necessary. To
605 // minimize impact to the existing inlining heuristics (in
606 // particular, to avoid breaking the existing inlinability regress
607 // tests), we need to compensate for this here.
608 if base.Debug.Unified != 0 {
609 if init := n.Rhs[0].Init(); len(init) == 1 {
610 if _, ok := init[0].(*ir.AssignListStmt); ok {
611 // 4 for each value, because each temporary variable now
612 // appears 3 times (DCL, LHS, RHS), plus an extra DCL node.
614 // 1 for the extra "tmp1, tmp2 = f()" assignment statement.
615 v.budget += 4*int32(len(n.Lhs)) + 1
621 // Special case for coverage counter updates and coverage
622 // function registrations. Although these correspond to real
623 // operations, we treat them as zero cost for the moment. This
624 // is primarily due to the existence of tests that are
625 // sensitive to inlining-- if the insertion of coverage
626 // instrumentation happens to tip a given function over the
627 // threshold and move it from "inlinable" to "not-inlinable",
628 // this can cause changes in allocation behavior, which can
629 // then result in test failures (a good example is the
630 // TestAllocations in crypto/ed25519).
631 n := n.(*ir.AssignStmt)
632 if n.X.Op() == ir.OINDEX && isIndexingCoverageCounter(n.X) {
639 // When debugging, don't stop early, to get full cost of inlining this function
640 if v.budget < 0 && base.Flag.LowerM < 2 && !logopt.Enabled() {
641 v.reason = "too expensive"
645 return ir.DoChildren(n, v.do)
648 func isBigFunc(fn *ir.Func) bool {
649 budget := inlineBigFunctionNodes
650 return ir.Any(fn, func(n ir.Node) bool {
656 // inlcopylist (together with inlcopy) recursively copies a list of nodes, except
657 // that it keeps the same ONAME, OTYPE, and OLITERAL nodes. It is used for copying
658 // the body and dcls of an inlineable function.
659 func inlcopylist(ll []ir.Node) []ir.Node {
660 s := make([]ir.Node, len(ll))
661 for i, n := range ll {
667 // inlcopy is like DeepCopy(), but does extra work to copy closures.
668 func inlcopy(n ir.Node) ir.Node {
669 var edit func(ir.Node) ir.Node
670 edit = func(x ir.Node) ir.Node {
672 case ir.ONAME, ir.OTYPE, ir.OLITERAL, ir.ONIL:
676 ir.EditChildren(m, edit)
677 if x.Op() == ir.OCLOSURE {
678 x := x.(*ir.ClosureExpr)
679 // Need to save/duplicate x.Func.Nname,
680 // x.Func.Nname.Ntype, x.Func.Dcl, x.Func.ClosureVars, and
681 // x.Func.Body for iexport and local inlining.
683 newfn := ir.NewFunc(oldfn.Pos())
684 m.(*ir.ClosureExpr).Func = newfn
685 newfn.Nname = ir.NewNameAt(oldfn.Nname.Pos(), oldfn.Nname.Sym())
686 // XXX OK to share fn.Type() ??
687 newfn.Nname.SetType(oldfn.Nname.Type())
688 newfn.Body = inlcopylist(oldfn.Body)
689 // Make shallow copy of the Dcl and ClosureVar slices
690 newfn.Dcl = append([]*ir.Name(nil), oldfn.Dcl...)
691 newfn.ClosureVars = append([]*ir.Name(nil), oldfn.ClosureVars...)
698 // InlineCalls/inlnode walks fn's statements and expressions and substitutes any
699 // calls made to inlineable functions. This is the external entry point.
700 func InlineCalls(fn *ir.Func, profile *pgo.Profile) {
703 maxCost := int32(inlineMaxBudget)
705 maxCost = inlineBigFunctionMaxCost
707 var inlCalls []*ir.InlinedCallExpr
708 var edit func(ir.Node) ir.Node
709 edit = func(n ir.Node) ir.Node {
710 return inlnode(n, maxCost, &inlCalls, edit, profile)
712 ir.EditChildren(fn, edit)
714 // If we inlined any calls, we want to recursively visit their
715 // bodies for further inlining. However, we need to wait until
716 // *after* the original function body has been expanded, or else
717 // inlCallee can have false positives (e.g., #54632).
718 for len(inlCalls) > 0 {
720 inlCalls = inlCalls[1:]
721 ir.EditChildren(call, edit)
727 // inlnode recurses over the tree to find inlineable calls, which will
728 // be turned into OINLCALLs by mkinlcall. When the recursion comes
729 // back up will examine left, right, list, rlist, ninit, ntest, nincr,
730 // nbody and nelse and use one of the 4 inlconv/glue functions above
731 // to turn the OINLCALL into an expression, a statement, or patch it
732 // in to this nodes list or rlist as appropriate.
733 // NOTE it makes no sense to pass the glue functions down the
734 // recursion to the level where the OINLCALL gets created because they
735 // have to edit /this/ n, so you'd have to push that one down as well,
736 // but then you may as well do it here. so this is cleaner and
737 // shorter and less complicated.
738 // The result of inlnode MUST be assigned back to n, e.g.
740 // n.Left = inlnode(n.Left)
741 func inlnode(n ir.Node, maxCost int32, inlCalls *[]*ir.InlinedCallExpr, edit func(ir.Node) ir.Node, profile *pgo.Profile) ir.Node {
747 case ir.ODEFER, ir.OGO:
748 n := n.(*ir.GoDeferStmt)
749 switch call := n.Call; call.Op() {
751 base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
753 call := call.(*ir.CallExpr)
757 n := n.(*ir.TailCallStmt)
758 n.Call.NoInline = true // Not inline a tail call for now. Maybe we could inline it just like RETURN fn(arg)?
760 // TODO do them here (or earlier),
761 // so escape analysis can avoid more heapmoves.
765 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
767 n := n.(*ir.CallExpr)
768 if n.X.Op() == ir.OMETHEXPR {
769 // Prevent inlining some reflect.Value methods when using checkptr,
770 // even when package reflect was compiled without it (#35073).
771 if meth := ir.MethodExprName(n.X); meth != nil {
773 if base.Debug.Checkptr != 0 && types.IsReflectPkg(s.Pkg) && (s.Name == "Value.UnsafeAddr" || s.Name == "Value.Pointer") {
782 ir.EditChildren(n, edit)
784 // with all the branches out of the way, it is now time to
785 // transmogrify this node itself unless inhibited by the
786 // switch at the top of this function.
789 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
792 call := n.(*ir.CallExpr)
796 if base.Flag.LowerM > 3 {
797 fmt.Printf("%v:call to func %+v\n", ir.Line(n), call.X)
799 if ir.IsIntrinsicCall(call) {
802 if fn := inlCallee(call.X, profile); fn != nil && typecheck.HaveInlineBody(fn) {
803 n = mkinlcall(call, fn, maxCost, inlCalls, edit)
812 // inlCallee takes a function-typed expression and returns the underlying function ONAME
813 // that it refers to if statically known. Otherwise, it returns nil.
814 func inlCallee(fn ir.Node, profile *pgo.Profile) *ir.Func {
815 fn = ir.StaticValue(fn)
818 fn := fn.(*ir.SelectorExpr)
819 n := ir.MethodExprName(fn)
820 // Check that receiver type matches fn.X.
821 // TODO(mdempsky): Handle implicit dereference
822 // of pointer receiver argument?
823 if n == nil || !types.Identical(n.Type().Recv().Type, fn.X.Type()) {
829 if fn.Class == ir.PFUNC {
833 fn := fn.(*ir.ClosureExpr)
835 CanInline(c, profile)
841 func inlParam(t *types.Field, as ir.InitNode, inlvars map[*ir.Name]*ir.Name) ir.Node {
845 n := t.Nname.(*ir.Name)
851 base.Fatalf("missing inlvar for %v", n)
853 as.PtrInit().Append(ir.NewDecl(base.Pos, ir.ODCL, inlvar))
854 inlvar.Name().Defn = as
860 // SSADumpInline gives the SSA back end a chance to dump the function
861 // when producing output for debugging the compiler itself.
862 var SSADumpInline = func(*ir.Func) {}
864 // InlineCall allows the inliner implementation to be overridden.
865 // If it returns nil, the function will not be inlined.
866 var InlineCall = oldInlineCall
868 // If n is a OCALLFUNC node, and fn is an ONAME node for a
869 // function with an inlinable body, return an OINLCALL node that can replace n.
870 // The returned node's Ninit has the parameter assignments, the Nbody is the
871 // inlined function body, and (List, Rlist) contain the (input, output)
873 // The result of mkinlcall MUST be assigned back to n, e.g.
875 // n.Left = mkinlcall(n.Left, fn, isddd)
876 func mkinlcall(n *ir.CallExpr, fn *ir.Func, maxCost int32, inlCalls *[]*ir.InlinedCallExpr, edit func(ir.Node) ir.Node) ir.Node {
878 if logopt.Enabled() {
879 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
880 fmt.Sprintf("%s cannot be inlined", ir.PkgFuncName(fn)))
884 if fn.Inl.Cost > maxCost {
885 // If the callsite is hot and it is under the inlineHotMaxBudget budget, then try to inline it, or else bail.
886 line := int(base.Ctxt.InnermostPos(n.Pos()).RelLine())
887 csi := pgo.CallSiteInfo{Line: line, Caller: ir.CurFunc}
888 if _, ok := pgo.ListOfHotCallSites[csi]; ok {
889 if fn.Inl.Cost > inlineHotMaxBudget {
890 if logopt.Enabled() {
891 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
892 fmt.Sprintf("cost %d of %s exceeds max large caller cost %d", fn.Inl.Cost, ir.PkgFuncName(fn), inlineHotMaxBudget))
896 if base.Debug.PGOInline > 0 {
897 fmt.Printf("hot-budget check allows inlining for callsite at %v\n", ir.Line(n))
900 // The inlined function body is too big. Typically we use this check to restrict
901 // inlining into very big functions. See issue 26546 and 17566.
902 if logopt.Enabled() {
903 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
904 fmt.Sprintf("cost %d of %s exceeds max large caller cost %d", fn.Inl.Cost, ir.PkgFuncName(fn), maxCost))
910 if fn == ir.CurFunc {
911 // Can't recursively inline a function into itself.
912 if logopt.Enabled() {
913 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", fmt.Sprintf("recursive call to %s", ir.FuncName(ir.CurFunc)))
918 // The non-unified frontend has issues with inlining and shape parameters.
919 if base.Debug.Unified == 0 {
920 // Don't inline a function fn that has no shape parameters, but is passed at
921 // least one shape arg. This means we must be inlining a non-generic function
922 // fn that was passed into a generic function, and can be called with a shape
923 // arg because it matches an appropriate type parameters. But fn may include
924 // an interface conversion (that may be applied to a shape arg) that was not
925 // apparent when we first created the instantiation of the generic function.
926 // We can't handle this if we actually do the inlining, since we want to know
927 // all interface conversions immediately after stenciling. So, we avoid
928 // inlining in this case, see issue #49309. (1)
930 // See discussion on go.dev/cl/406475 for more background.
931 if !fn.Type().Params().HasShape() {
932 for _, arg := range n.Args {
933 if arg.Type().HasShape() {
934 if logopt.Enabled() {
935 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
936 fmt.Sprintf("inlining function %v has no-shape params with shape args", ir.FuncName(fn)))
942 // Don't inline a function fn that has shape parameters, but is passed no shape arg.
943 // See comments (1) above, and issue #51909.
944 inlineable := len(n.Args) == 0 // Function has shape in type, with no arguments can always be inlined.
945 for _, arg := range n.Args {
946 if arg.Type().HasShape() {
952 if logopt.Enabled() {
953 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
954 fmt.Sprintf("inlining function %v has shape params with no-shape args", ir.FuncName(fn)))
961 if base.Flag.Cfg.Instrumenting && types.IsRuntimePkg(fn.Sym().Pkg) {
962 // Runtime package must not be instrumented.
963 // Instrument skips runtime package. However, some runtime code can be
964 // inlined into other packages and instrumented there. To avoid this,
965 // we disable inlining of runtime functions when instrumenting.
966 // The example that we observed is inlining of LockOSThread,
967 // which lead to false race reports on m contents.
971 parent := base.Ctxt.PosTable.Pos(n.Pos()).Base().InliningIndex()
974 // Check if we've already inlined this function at this particular
975 // call site, in order to stop inlining when we reach the beginning
976 // of a recursion cycle again. We don't inline immediately recursive
977 // functions, but allow inlining if there is a recursion cycle of
978 // many functions. Most likely, the inlining will stop before we
979 // even hit the beginning of the cycle again, but this catches the
981 for inlIndex := parent; inlIndex >= 0; inlIndex = base.Ctxt.InlTree.Parent(inlIndex) {
982 if base.Ctxt.InlTree.InlinedFunction(inlIndex) == sym {
983 if base.Flag.LowerM > 1 {
984 fmt.Printf("%v: cannot inline %v into %v: repeated recursive cycle\n", ir.Line(n), fn, ir.FuncName(ir.CurFunc))
990 typecheck.FixVariadicCall(n)
992 inlIndex := base.Ctxt.InlTree.Add(parent, n.Pos(), sym)
994 closureInitLSym := func(n *ir.CallExpr, fn *ir.Func) {
995 // The linker needs FuncInfo metadata for all inlined
996 // functions. This is typically handled by gc.enqueueFunc
997 // calling ir.InitLSym for all function declarations in
998 // typecheck.Target.Decls (ir.UseClosure adds all closures to
1001 // However, non-trivial closures in Decls are ignored, and are
1002 // insteaded enqueued when walk of the calling function
1005 // This presents a problem for direct calls to closures.
1006 // Inlining will replace the entire closure definition with its
1007 // body, which hides the closure from walk and thus suppresses
1010 // Explicitly create a symbol early in this edge case to ensure
1011 // we keep this metadata.
1013 // TODO: Refactor to keep a reference so this can all be done
1016 if n.Op() != ir.OCALLFUNC {
1017 // Not a standard call.
1020 if n.X.Op() != ir.OCLOSURE {
1021 // Not a direct closure call.
1025 clo := n.X.(*ir.ClosureExpr)
1026 if ir.IsTrivialClosure(clo) {
1027 // enqueueFunc will handle trivial closures anyways.
1031 ir.InitLSym(fn, true)
1034 closureInitLSym(n, fn)
1036 if base.Flag.GenDwarfInl > 0 {
1037 if !sym.WasInlined() {
1038 base.Ctxt.DwFixups.SetPrecursorFunc(sym, fn)
1039 sym.Set(obj.AttrWasInlined, true)
1043 if base.Flag.LowerM != 0 {
1044 fmt.Printf("%v: inlining call to %v\n", ir.Line(n), fn)
1046 if base.Flag.LowerM > 2 {
1047 fmt.Printf("%v: Before inlining: %+v\n", ir.Line(n), n)
1050 if base.Debug.PGOInline > 0 {
1051 line := int(base.Ctxt.InnermostPos(n.Pos()).RelLine())
1052 csi := pgo.CallSiteInfo{Line: line, Caller: ir.CurFunc}
1053 if _, ok := inlinedCallSites[csi]; !ok {
1054 inlinedCallSites[csi] = struct{}{}
1058 res := InlineCall(n, fn, inlIndex)
1061 base.FatalfAt(n.Pos(), "inlining call to %v failed", fn)
1064 if base.Flag.LowerM > 2 {
1065 fmt.Printf("%v: After inlining %+v\n\n", ir.Line(res), res)
1068 *inlCalls = append(*inlCalls, res)
1073 // CalleeEffects appends any side effects from evaluating callee to init.
1074 func CalleeEffects(init *ir.Nodes, callee ir.Node) {
1076 init.Append(ir.TakeInit(callee)...)
1078 switch callee.Op() {
1079 case ir.ONAME, ir.OCLOSURE, ir.OMETHEXPR:
1083 conv := callee.(*ir.ConvExpr)
1087 ic := callee.(*ir.InlinedCallExpr)
1088 init.Append(ic.Body.Take()...)
1089 callee = ic.SingleResult()
1092 base.FatalfAt(callee.Pos(), "unexpected callee expression: %v", callee)
1097 // oldInlineCall creates an InlinedCallExpr to replace the given call
1098 // expression. fn is the callee function to be inlined. inlIndex is
1099 // the inlining tree position index, for use with src.NewInliningBase
1100 // when rewriting positions.
1101 func oldInlineCall(call *ir.CallExpr, fn *ir.Func, inlIndex int) *ir.InlinedCallExpr {
1102 if base.Debug.TypecheckInl == 0 {
1103 typecheck.ImportedBody(fn)
1108 ninit := call.Init()
1110 // For normal function calls, the function callee expression
1111 // may contain side effects. Make sure to preserve these,
1112 // if necessary (#42703).
1113 if call.Op() == ir.OCALLFUNC {
1114 CalleeEffects(&ninit, call.X)
1117 // Make temp names to use instead of the originals.
1118 inlvars := make(map[*ir.Name]*ir.Name)
1120 // record formals/locals for later post-processing
1121 var inlfvars []*ir.Name
1123 for _, ln := range fn.Inl.Dcl {
1124 if ln.Op() != ir.ONAME {
1127 if ln.Class == ir.PPARAMOUT { // return values handled below.
1130 inlf := typecheck.Expr(inlvar(ln)).(*ir.Name)
1132 if base.Flag.GenDwarfInl > 0 {
1133 if ln.Class == ir.PPARAM {
1134 inlf.Name().SetInlFormal(true)
1136 inlf.Name().SetInlLocal(true)
1138 inlf.SetPos(ln.Pos())
1139 inlfvars = append(inlfvars, inlf)
1143 // We can delay declaring+initializing result parameters if:
1144 // temporaries for return values.
1145 var retvars []ir.Node
1146 for i, t := range fn.Type().Results().Fields().Slice() {
1148 if nn := t.Nname; nn != nil && !ir.IsBlank(nn.(*ir.Name)) && !strings.HasPrefix(nn.Sym().Name, "~r") {
1151 m = typecheck.Expr(m).(*ir.Name)
1154 // anonymous return values, synthesize names for use in assignment that replaces return
1158 if base.Flag.GenDwarfInl > 0 {
1159 // Don't update the src.Pos on a return variable if it
1160 // was manufactured by the inliner (e.g. "~R2"); such vars
1161 // were not part of the original callee.
1162 if !strings.HasPrefix(m.Sym().Name, "~R") {
1163 m.Name().SetInlFormal(true)
1165 inlfvars = append(inlfvars, m)
1169 retvars = append(retvars, m)
1172 // Assign arguments to the parameters' temp names.
1173 as := ir.NewAssignListStmt(base.Pos, ir.OAS2, nil, nil)
1175 if call.Op() == ir.OCALLMETH {
1176 base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
1178 as.Rhs.Append(call.Args...)
1180 if recv := fn.Type().Recv(); recv != nil {
1181 as.Lhs.Append(inlParam(recv, as, inlvars))
1183 for _, param := range fn.Type().Params().Fields().Slice() {
1184 as.Lhs.Append(inlParam(param, as, inlvars))
1187 if len(as.Rhs) != 0 {
1188 ninit.Append(typecheck.Stmt(as))
1191 if !fn.Inl.CanDelayResults {
1192 // Zero the return parameters.
1193 for _, n := range retvars {
1194 ninit.Append(ir.NewDecl(base.Pos, ir.ODCL, n.(*ir.Name)))
1195 ras := ir.NewAssignStmt(base.Pos, n, nil)
1196 ninit.Append(typecheck.Stmt(ras))
1200 retlabel := typecheck.AutoLabel(".i")
1204 // Add an inline mark just before the inlined body.
1205 // This mark is inline in the code so that it's a reasonable spot
1206 // to put a breakpoint. Not sure if that's really necessary or not
1207 // (in which case it could go at the end of the function instead).
1208 // Note issue 28603.
1209 ninit.Append(ir.NewInlineMarkStmt(call.Pos().WithIsStmt(), int64(inlIndex)))
1215 defnMarker: ir.NilExpr{},
1216 bases: make(map[*src.PosBase]*src.PosBase),
1217 newInlIndex: inlIndex,
1220 subst.edit = subst.node
1222 body := subst.list(ir.Nodes(fn.Inl.Body))
1224 lab := ir.NewLabelStmt(base.Pos, retlabel)
1225 body = append(body, lab)
1227 if base.Flag.GenDwarfInl > 0 {
1228 for _, v := range inlfvars {
1229 v.SetPos(subst.updatedPos(v.Pos()))
1233 //dumplist("ninit post", ninit);
1235 res := ir.NewInlinedCallExpr(base.Pos, body, retvars)
1237 res.SetType(call.Type())
1242 // Every time we expand a function we generate a new set of tmpnames,
1243 // PAUTO's in the calling functions, and link them off of the
1244 // PPARAM's, PAUTOS and PPARAMOUTs of the called function.
1245 func inlvar(var_ *ir.Name) *ir.Name {
1246 if base.Flag.LowerM > 3 {
1247 fmt.Printf("inlvar %+v\n", var_)
1250 n := typecheck.NewName(var_.Sym())
1251 n.SetType(var_.Type())
1255 n.SetAutoTemp(var_.AutoTemp())
1256 n.Curfn = ir.CurFunc // the calling function, not the called one
1257 n.SetAddrtaken(var_.Addrtaken())
1259 ir.CurFunc.Dcl = append(ir.CurFunc.Dcl, n)
1263 // Synthesize a variable to store the inlined function's results in.
1264 func retvar(t *types.Field, i int) *ir.Name {
1265 n := typecheck.NewName(typecheck.LookupNum("~R", i))
1270 n.Curfn = ir.CurFunc // the calling function, not the called one
1271 ir.CurFunc.Dcl = append(ir.CurFunc.Dcl, n)
1275 // The inlsubst type implements the actual inlining of a single
1277 type inlsubst struct {
1278 // Target of the goto substituted in place of a return.
1281 // Temporary result variables.
1284 inlvars map[*ir.Name]*ir.Name
1285 // defnMarker is used to mark a Node for reassignment.
1286 // inlsubst.clovar set this during creating new ONAME.
1287 // inlsubst.node will set the correct Defn for inlvar.
1288 defnMarker ir.NilExpr
1290 // bases maps from original PosBase to PosBase with an extra
1291 // inlined call frame.
1292 bases map[*src.PosBase]*src.PosBase
1294 // newInlIndex is the index of the inlined call frame to
1295 // insert for inlined nodes.
1298 edit func(ir.Node) ir.Node // cached copy of subst.node method value closure
1300 // If non-nil, we are inside a closure inside the inlined function, and
1301 // newclofn is the Func of the new inlined closure.
1304 fn *ir.Func // For debug -- the func that is being inlined
1306 // If true, then don't update source positions during substitution
1307 // (retain old source positions).
1311 // list inlines a list of nodes.
1312 func (subst *inlsubst) list(ll ir.Nodes) []ir.Node {
1313 s := make([]ir.Node, 0, len(ll))
1314 for _, n := range ll {
1315 s = append(s, subst.node(n))
1320 // fields returns a list of the fields of a struct type representing receiver,
1321 // params, or results, after duplicating the field nodes and substituting the
1322 // Nname nodes inside the field nodes.
1323 func (subst *inlsubst) fields(oldt *types.Type) []*types.Field {
1324 oldfields := oldt.FieldSlice()
1325 newfields := make([]*types.Field, len(oldfields))
1326 for i := range oldfields {
1327 newfields[i] = oldfields[i].Copy()
1328 if oldfields[i].Nname != nil {
1329 newfields[i].Nname = subst.node(oldfields[i].Nname.(*ir.Name))
1335 // clovar creates a new ONAME node for a local variable or param of a closure
1336 // inside a function being inlined.
1337 func (subst *inlsubst) clovar(n *ir.Name) *ir.Name {
1338 m := ir.NewNameAt(n.Pos(), n.Sym())
1342 if n.IsClosureVar() {
1343 m.SetIsClosureVar(true)
1346 m.SetAddrtaken(true)
1353 m.Curfn = subst.newclofn
1355 switch defn := n.Defn.(type) {
1359 if !n.IsClosureVar() {
1360 base.FatalfAt(n.Pos(), "want closure variable, got: %+v", n)
1362 if n.Sym().Pkg != types.LocalPkg {
1363 // If the closure came from inlining a function from
1364 // another package, must change package of captured
1365 // variable to localpkg, so that the fields of the closure
1366 // struct are local package and can be accessed even if
1367 // name is not exported. If you disable this code, you can
1368 // reproduce the problem by running 'go test
1369 // go/internal/srcimporter'. TODO(mdempsky) - maybe change
1370 // how we create closure structs?
1371 m.SetSym(types.LocalPkg.Lookup(n.Sym().Name))
1373 // Make sure any inlvar which is the Defn
1374 // of an ONAME closure var is rewritten
1375 // during inlining. Don't substitute
1376 // if Defn node is outside inlined function.
1377 if subst.inlvars[n.Defn.(*ir.Name)] != nil {
1378 m.Defn = subst.node(n.Defn)
1380 case *ir.AssignStmt, *ir.AssignListStmt:
1381 // Mark node for reassignment at the end of inlsubst.node.
1382 m.Defn = &subst.defnMarker
1383 case *ir.TypeSwitchGuard:
1384 // TODO(mdempsky): Set m.Defn properly. See discussion on #45743.
1386 // TODO: Set m.Defn properly if we support inlining range statement in the future.
1388 base.FatalfAt(n.Pos(), "unexpected Defn: %+v", defn)
1392 // Either the outer variable is defined in function being inlined,
1393 // and we will replace it with the substituted variable, or it is
1394 // defined outside the function being inlined, and we should just
1395 // skip the outer variable (the closure variable of the function
1397 s := subst.node(n.Outer).(*ir.Name)
1406 // closure does the necessary substitions for a ClosureExpr n and returns the new
1408 func (subst *inlsubst) closure(n *ir.ClosureExpr) ir.Node {
1409 // Prior to the subst edit, set a flag in the inlsubst to indicate
1410 // that we don't want to update the source positions in the new
1411 // closure function. If we do this, it will appear that the
1412 // closure itself has things inlined into it, which is not the
1413 // case. See issue #46234 for more details. At the same time, we
1414 // do want to update the position in the new ClosureExpr (which is
1415 // part of the function we're working on). See #49171 for an
1416 // example of what happens if we miss that update.
1417 newClosurePos := subst.updatedPos(n.Pos())
1418 defer func(prev bool) { subst.noPosUpdate = prev }(subst.noPosUpdate)
1419 subst.noPosUpdate = true
1421 //fmt.Printf("Inlining func %v with closure into %v\n", subst.fn, ir.FuncName(ir.CurFunc))
1424 newfn := ir.NewClosureFunc(oldfn.Pos(), true)
1426 if subst.newclofn != nil {
1427 //fmt.Printf("Inlining a closure with a nested closure\n")
1429 prevxfunc := subst.newclofn
1431 // Mark that we are now substituting within a closure (within the
1432 // inlined function), and create new nodes for all the local
1433 // vars/params inside this closure.
1434 subst.newclofn = newfn
1436 newfn.ClosureVars = nil
1437 for _, oldv := range oldfn.Dcl {
1438 newv := subst.clovar(oldv)
1439 subst.inlvars[oldv] = newv
1440 newfn.Dcl = append(newfn.Dcl, newv)
1442 for _, oldv := range oldfn.ClosureVars {
1443 newv := subst.clovar(oldv)
1444 subst.inlvars[oldv] = newv
1445 newfn.ClosureVars = append(newfn.ClosureVars, newv)
1448 // Need to replace ONAME nodes in
1449 // newfn.Type().FuncType().Receiver/Params/Results.FieldSlice().Nname
1450 oldt := oldfn.Type()
1451 newrecvs := subst.fields(oldt.Recvs())
1452 var newrecv *types.Field
1453 if len(newrecvs) > 0 {
1454 newrecv = newrecvs[0]
1456 newt := types.NewSignature(oldt.Pkg(), newrecv,
1457 nil, subst.fields(oldt.Params()), subst.fields(oldt.Results()))
1459 newfn.Nname.SetType(newt)
1460 newfn.Body = subst.list(oldfn.Body)
1462 // Remove the nodes for the current closure from subst.inlvars
1463 for _, oldv := range oldfn.Dcl {
1464 delete(subst.inlvars, oldv)
1466 for _, oldv := range oldfn.ClosureVars {
1467 delete(subst.inlvars, oldv)
1469 // Go back to previous closure func
1470 subst.newclofn = prevxfunc
1472 // Actually create the named function for the closure, now that
1473 // the closure is inlined in a specific function.
1474 newclo := newfn.OClosure
1475 newclo.SetPos(newClosurePos)
1476 newclo.SetInit(subst.list(n.Init()))
1477 return typecheck.Expr(newclo)
1480 // node recursively copies a node from the saved pristine body of the
1481 // inlined function, substituting references to input/output
1482 // parameters with ones to the tmpnames, and substituting returns with
1483 // assignments to the output.
1484 func (subst *inlsubst) node(n ir.Node) ir.Node {
1493 // Handle captured variables when inlining closures.
1494 if n.IsClosureVar() && subst.newclofn == nil {
1497 // Deal with case where sequence of closures are inlined.
1498 // TODO(danscales) - write test case to see if we need to
1499 // go up multiple levels.
1500 if o.Curfn != ir.CurFunc {
1504 // make sure the outer param matches the inlining location
1505 if o == nil || o.Curfn != ir.CurFunc {
1506 base.Fatalf("%v: unresolvable capture %v\n", ir.Line(n), n)
1509 if base.Flag.LowerM > 2 {
1510 fmt.Printf("substituting captured name %+v -> %+v\n", n, o)
1515 if inlvar := subst.inlvars[n]; inlvar != nil { // These will be set during inlnode
1516 if base.Flag.LowerM > 2 {
1517 fmt.Printf("substituting name %+v -> %+v\n", n, inlvar)
1522 if base.Flag.LowerM > 2 {
1523 fmt.Printf("not substituting name %+v\n", n)
1528 n := n.(*ir.SelectorExpr)
1531 case ir.OLITERAL, ir.ONIL, ir.OTYPE:
1532 // If n is a named constant or type, we can continue
1533 // using it in the inline copy. Otherwise, make a copy
1534 // so we can update the line number.
1540 if subst.newclofn != nil {
1541 // Don't do special substitutions if inside a closure
1544 // Because of the above test for subst.newclofn,
1545 // this return is guaranteed to belong to the current inlined function.
1546 n := n.(*ir.ReturnStmt)
1547 init := subst.list(n.Init())
1548 if len(subst.retvars) != 0 && len(n.Results) != 0 {
1549 as := ir.NewAssignListStmt(base.Pos, ir.OAS2, nil, nil)
1551 // Make a shallow copy of retvars.
1552 // Otherwise OINLCALL.Rlist will be the same list,
1553 // and later walk and typecheck may clobber it.
1554 for _, n := range subst.retvars {
1557 as.Rhs = subst.list(n.Results)
1559 if subst.fn.Inl.CanDelayResults {
1560 for _, n := range as.Lhs {
1561 as.PtrInit().Append(ir.NewDecl(base.Pos, ir.ODCL, n.(*ir.Name)))
1566 init = append(init, typecheck.Stmt(as))
1568 init = append(init, ir.NewBranchStmt(base.Pos, ir.OGOTO, subst.retlabel))
1569 typecheck.Stmts(init)
1570 return ir.NewBlockStmt(base.Pos, init)
1572 case ir.OGOTO, ir.OBREAK, ir.OCONTINUE:
1573 if subst.newclofn != nil {
1574 // Don't do special substitutions if inside a closure
1577 n := n.(*ir.BranchStmt)
1578 m := ir.Copy(n).(*ir.BranchStmt)
1579 m.SetPos(subst.updatedPos(m.Pos()))
1581 m.Label = translateLabel(n.Label)
1585 if subst.newclofn != nil {
1586 // Don't do special substitutions if inside a closure
1589 n := n.(*ir.LabelStmt)
1590 m := ir.Copy(n).(*ir.LabelStmt)
1591 m.SetPos(subst.updatedPos(m.Pos()))
1593 m.Label = translateLabel(n.Label)
1597 return subst.closure(n.(*ir.ClosureExpr))
1602 m.SetPos(subst.updatedPos(m.Pos()))
1603 ir.EditChildren(m, subst.edit)
1605 if subst.newclofn == nil {
1606 // Translate any label on FOR, RANGE loops, SWITCH or SELECT
1609 m := m.(*ir.ForStmt)
1610 m.Label = translateLabel(m.Label)
1614 m := m.(*ir.RangeStmt)
1615 m.Label = translateLabel(m.Label)
1619 m := m.(*ir.SwitchStmt)
1620 m.Label = translateLabel(m.Label)
1624 m := m.(*ir.SelectStmt)
1625 m.Label = translateLabel(m.Label)
1630 switch m := m.(type) {
1631 case *ir.AssignStmt:
1632 if lhs, ok := m.X.(*ir.Name); ok && lhs.Defn == &subst.defnMarker {
1635 case *ir.AssignListStmt:
1636 for _, lhs := range m.Lhs {
1637 if lhs, ok := lhs.(*ir.Name); ok && lhs.Defn == &subst.defnMarker {
1646 // translateLabel makes a label from an inlined function (if non-nil) be unique by
1647 // adding "·inlgen".
1648 func translateLabel(l *types.Sym) *types.Sym {
1652 p := fmt.Sprintf("%s·%d", l.Name, inlgen)
1653 return typecheck.Lookup(p)
1656 func (subst *inlsubst) updatedPos(xpos src.XPos) src.XPos {
1657 if subst.noPosUpdate {
1660 pos := base.Ctxt.PosTable.Pos(xpos)
1661 oldbase := pos.Base() // can be nil
1662 newbase := subst.bases[oldbase]
1664 newbase = src.NewInliningBase(oldbase, subst.newInlIndex)
1665 subst.bases[oldbase] = newbase
1667 pos.SetBase(newbase)
1668 return base.Ctxt.PosTable.XPos(pos)
1671 func pruneUnusedAutos(ll []*ir.Name, vis *hairyVisitor) []*ir.Name {
1672 s := make([]*ir.Name, 0, len(ll))
1673 for _, n := range ll {
1674 if n.Class == ir.PAUTO {
1675 if !vis.usedLocals.Has(n) {
1684 // numNonClosures returns the number of functions in list which are not closures.
1685 func numNonClosures(list []*ir.Func) int {
1687 for _, fn := range list {
1688 if fn.OClosure == nil {
1695 func doList(list []ir.Node, do func(ir.Node) bool) bool {
1696 for _, x := range list {
1706 // isIndexingCoverageCounter returns true if the specified node 'n' is indexing
1707 // into a coverage counter array.
1708 func isIndexingCoverageCounter(n ir.Node) bool {
1709 if n.Op() != ir.OINDEX {
1712 ixn := n.(*ir.IndexExpr)
1713 if ixn.X.Op() != ir.ONAME || !ixn.X.Type().IsArray() {
1716 nn := ixn.X.(*ir.Name)
1717 return nn.CoverageCounter()
1720 // isAtomicCoverageCounterUpdate examines the specified node to
1721 // determine whether it represents a call to sync/atomic.AddUint32 to
1722 // increment a coverage counter.
1723 func isAtomicCoverageCounterUpdate(cn *ir.CallExpr) bool {
1724 if cn.X.Op() != ir.ONAME {
1727 name := cn.X.(*ir.Name)
1728 if name.Class != ir.PFUNC {
1731 fn := name.Sym().Name
1732 if name.Sym().Pkg.Path != "sync/atomic" ||
1733 (fn != "AddUint32" && fn != "StoreUint32") {
1736 if len(cn.Args) != 2 || cn.Args[0].Op() != ir.OADDR {
1739 adn := cn.Args[0].(*ir.AddrExpr)
1740 v := isIndexingCoverageCounter(adn.X)