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 callee nodes.
60 // TODO(prattmic): Make this non-global.
61 candHotCalleeMap = make(map[*pgo.IRNode]struct{})
63 // List of all hot call sites. CallSiteInfo.Callee is always nil.
64 // TODO(prattmic): Make this non-global.
65 candHotEdgeMap = make(map[pgo.CallSiteInfo]struct{})
67 // List of inlined call sites. CallSiteInfo.Callee is always nil.
68 // TODO(prattmic): Make this non-global.
69 inlinedCallSites = make(map[pgo.CallSiteInfo]struct{})
71 // Threshold in percentage for hot 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.InlineHotCallSiteThreshold, 64); err == nil {
81 inlineHotCallSiteThresholdPercent = s
82 if base.Debug.PGOInline > 0 {
83 fmt.Printf("hot-callsite-thres=%v\n", inlineHotCallSiteThresholdPercent)
87 if base.Debug.InlineHotBudget != 0 {
88 inlineHotMaxBudget = int32(base.Debug.InlineHotBudget)
91 ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
92 for _, f := range list {
93 name := ir.PkgFuncName(f)
94 if n, ok := p.WeightedCG.IRNodes[name]; ok {
95 for _, e := range p.WeightedCG.OutEdges[n] {
97 edgeweightpercent := pgo.WeightInPercentage(e.Weight, p.TotalEdgeWeight)
98 if edgeweightpercent > inlineHotCallSiteThresholdPercent {
99 csi := pgo.CallSiteInfo{Line: e.CallSite, Caller: n.AST}
100 if _, ok := candHotEdgeMap[csi]; !ok {
101 candHotEdgeMap[csi] = struct{}{}
102 candHotCalleeMap[e.Dst] = struct{}{}
110 if base.Debug.PGOInline > 0 {
111 fmt.Printf("hot-cg before inline in dot format:")
112 p.PrintWeightedCallGraphDOT(inlineHotCallSiteThresholdPercent)
116 // pgoInlineEpilogue updates IRGraph after inlining.
117 func pgoInlineEpilogue(p *pgo.Profile) {
118 if base.Debug.PGOInline > 0 {
119 ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
120 for _, f := range list {
121 name := ir.PkgFuncName(f)
122 if n, ok := p.WeightedCG.IRNodes[name]; ok {
123 p.RedirectEdges(n, inlinedCallSites)
127 // Print the call-graph after inlining. This is a debugging feature.
128 fmt.Printf("hot-cg after inline in dot:")
129 p.PrintWeightedCallGraphDOT(inlineHotCallSiteThresholdPercent)
133 // InlinePackage finds functions that can be inlined and clones them before walk expands them.
134 func InlinePackage(p *pgo.Profile) {
139 ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
140 numfns := numNonClosures(list)
141 for _, n := range list {
142 if !recursive || numfns > 1 {
143 // We allow inlining if there is no
144 // recursion, or the recursion cycle is
145 // across more than one function.
148 if base.Flag.LowerM > 1 {
149 fmt.Printf("%v: cannot inline %v: recursive\n", ir.Line(n), n.Nname)
161 // CanInline determines whether fn is inlineable.
162 // If so, CanInline saves copies of fn.Body and fn.Dcl in fn.Inl.
163 // fn and fn.Body will already have been typechecked.
164 func CanInline(fn *ir.Func, profile *pgo.Profile) {
166 base.Fatalf("CanInline no nname %+v", fn)
169 var reason string // reason, if any, that the function was not inlined
170 if base.Flag.LowerM > 1 || logopt.Enabled() {
173 if base.Flag.LowerM > 1 {
174 fmt.Printf("%v: cannot inline %v: %s\n", ir.Line(fn), fn.Nname, reason)
176 if logopt.Enabled() {
177 logopt.LogOpt(fn.Pos(), "cannotInlineFunction", "inline", ir.FuncName(fn), reason)
183 // If marked "go:noinline", don't inline
184 if fn.Pragma&ir.Noinline != 0 {
185 reason = "marked go:noinline"
189 // If marked "go:norace" and -race compilation, don't inline.
190 if base.Flag.Race && fn.Pragma&ir.Norace != 0 {
191 reason = "marked go:norace with -race compilation"
195 // If marked "go:nocheckptr" and -d checkptr compilation, don't inline.
196 if base.Debug.Checkptr != 0 && fn.Pragma&ir.NoCheckPtr != 0 {
197 reason = "marked go:nocheckptr"
201 // If marked "go:cgo_unsafe_args", don't inline, since the
202 // function makes assumptions about its argument frame layout.
203 if fn.Pragma&ir.CgoUnsafeArgs != 0 {
204 reason = "marked go:cgo_unsafe_args"
208 // If marked as "go:uintptrkeepalive", don't inline, since the
209 // keep alive information is lost during inlining.
211 // TODO(prattmic): This is handled on calls during escape analysis,
212 // which is after inlining. Move prior to inlining so the keep-alive is
213 // maintained after inlining.
214 if fn.Pragma&ir.UintptrKeepAlive != 0 {
215 reason = "marked as having a keep-alive uintptr argument"
219 // If marked as "go:uintptrescapes", don't inline, since the
220 // escape information is lost during inlining.
221 if fn.Pragma&ir.UintptrEscapes != 0 {
222 reason = "marked as having an escaping uintptr argument"
226 // The nowritebarrierrec checker currently works at function
227 // granularity, so inlining yeswritebarrierrec functions can
228 // confuse it (#22342). As a workaround, disallow inlining
230 if fn.Pragma&ir.Yeswritebarrierrec != 0 {
231 reason = "marked go:yeswritebarrierrec"
235 // If fn has no body (is defined outside of Go), cannot inline it.
236 if len(fn.Body) == 0 {
237 reason = "no function body"
241 if fn.Typecheck() == 0 {
242 base.Fatalf("CanInline on non-typechecked function %v", fn)
246 if n.Func.InlinabilityChecked() {
249 defer n.Func.SetInlinabilityChecked(true)
251 cc := int32(inlineExtraCallCost)
252 if base.Flag.LowerL == 4 {
253 cc = 1 // this appears to yield better performance than 0.
256 // Update the budget for profile-guided inlining.
257 budget := int32(inlineMaxBudget)
259 if n, ok := profile.WeightedCG.IRNodes[ir.PkgFuncName(fn)]; ok {
260 if _, ok := candHotCalleeMap[n]; ok {
261 budget = int32(inlineHotMaxBudget)
262 if base.Debug.PGOInline > 0 {
263 fmt.Printf("hot-node enabled increased budget=%v for func=%v\n", budget, ir.PkgFuncName(fn))
269 // At this point in the game the function we're looking at may
270 // have "stale" autos, vars that still appear in the Dcl list, but
271 // which no longer have any uses in the function body (due to
272 // elimination by deadcode). We'd like to exclude these dead vars
273 // when creating the "Inline.Dcl" field below; to accomplish this,
274 // the hairyVisitor below builds up a map of used/referenced
275 // locals, and we use this map to produce a pruned Inline.Dcl
276 // list. See issue 25249 for more context.
278 visitor := hairyVisitor{
285 if visitor.tooHairy(fn) {
286 reason = visitor.reason
290 n.Func.Inl = &ir.Inline{
291 Cost: budget - visitor.budget,
292 Dcl: pruneUnusedAutos(n.Defn.(*ir.Func).Dcl, &visitor),
293 Body: inlcopylist(fn.Body),
295 CanDelayResults: canDelayResults(fn),
298 if base.Flag.LowerM > 1 {
299 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))
300 } else if base.Flag.LowerM != 0 {
301 fmt.Printf("%v: can inline %v\n", ir.Line(fn), n)
303 if logopt.Enabled() {
304 logopt.LogOpt(fn.Pos(), "canInlineFunction", "inline", ir.FuncName(fn), fmt.Sprintf("cost: %d", budget-visitor.budget))
308 // canDelayResults reports whether inlined calls to fn can delay
309 // declaring the result parameter until the "return" statement.
310 func canDelayResults(fn *ir.Func) bool {
311 // We can delay declaring+initializing result parameters if:
312 // (1) there's exactly one "return" statement in the inlined function;
313 // (2) it's not an empty return statement (#44355); and
314 // (3) the result parameters aren't named.
317 ir.VisitList(fn.Body, func(n ir.Node) {
318 if n, ok := n.(*ir.ReturnStmt); ok {
320 if len(n.Results) == 0 {
321 nreturns++ // empty return statement (case 2)
327 return false // not exactly one return statement (case 1)
330 // temporaries for return values.
331 for _, param := range fn.Type().Results().FieldSlice() {
332 if sym := types.OrigSym(param.Sym); sym != nil && !sym.IsBlank() {
333 return false // found a named result parameter (case 3)
340 // hairyVisitor visits a function body to determine its inlining
341 // hairiness and whether or not it can be inlined.
342 type hairyVisitor struct {
343 // This is needed to access the current caller in the doNode function.
349 usedLocals ir.NameSet
350 do func(ir.Node) bool
354 func (v *hairyVisitor) tooHairy(fn *ir.Func) bool {
355 v.do = v.doNode // cache closure
356 if ir.DoChildren(fn, v.do) {
360 v.reason = fmt.Sprintf("function too complex: cost %d exceeds budget %d", v.maxBudget-v.budget, v.maxBudget)
366 func (v *hairyVisitor) doNode(n ir.Node) bool {
371 // Call is okay if inlinable and we have the budget for the body.
373 n := n.(*ir.CallExpr)
374 // Functions that call runtime.getcaller{pc,sp} can not be inlined
375 // because getcaller{pc,sp} expect a pointer to the caller's first argument.
377 // runtime.throw is a "cheap call" like panic in normal code.
378 if n.X.Op() == ir.ONAME {
379 name := n.X.(*ir.Name)
380 if name.Class == ir.PFUNC && types.IsRuntimePkg(name.Sym().Pkg) {
381 fn := name.Sym().Name
382 if fn == "getcallerpc" || fn == "getcallersp" {
383 v.reason = "call to " + fn
387 v.budget -= inlineExtraThrowCost
391 // Special case for coverage counter updates; although
392 // these correspond to real operations, we treat them as
393 // zero cost for the moment. This is due to the existence
394 // of tests that are sensitive to inlining-- if the
395 // insertion of coverage instrumentation happens to tip a
396 // given function over the threshold and move it from
397 // "inlinable" to "not-inlinable", this can cause changes
398 // in allocation behavior, which can then result in test
399 // failures (a good example is the TestAllocations in
401 if isAtomicCoverageCounterUpdate(n) {
405 if n.X.Op() == ir.OMETHEXPR {
406 if meth := ir.MethodExprName(n.X); meth != nil {
407 if fn := meth.Func; fn != nil {
410 if types.IsRuntimePkg(s.Pkg) && s.Name == "heapBits.nextArena" {
411 // Special case: explicitly allow mid-stack inlining of
412 // runtime.heapBits.next even though it calls slow-path
413 // runtime.heapBits.nextArena.
416 // Special case: on architectures that can do unaligned loads,
417 // explicitly mark encoding/binary methods as cheap,
418 // because in practice they are, even though our inlining
419 // budgeting system does not see that. See issue 42958.
420 if base.Ctxt.Arch.CanMergeLoads && s.Pkg.Path == "encoding/binary" {
422 case "littleEndian.Uint64", "littleEndian.Uint32", "littleEndian.Uint16",
423 "bigEndian.Uint64", "bigEndian.Uint32", "bigEndian.Uint16",
424 "littleEndian.PutUint64", "littleEndian.PutUint32", "littleEndian.PutUint16",
425 "bigEndian.PutUint64", "bigEndian.PutUint32", "bigEndian.PutUint16",
426 "littleEndian.AppendUint64", "littleEndian.AppendUint32", "littleEndian.AppendUint16",
427 "bigEndian.AppendUint64", "bigEndian.AppendUint32", "bigEndian.AppendUint16":
432 break // treat like any other node, that is, cost of 1
438 // Determine if the callee edge is for an inlinable hot callee or not.
439 if v.profile != nil && v.curFunc != nil {
440 if fn := inlCallee(n.X, v.profile); fn != nil && typecheck.HaveInlineBody(fn) {
441 line := int(base.Ctxt.InnermostPos(n.Pos()).RelLine())
442 csi := pgo.CallSiteInfo{Line: line, Caller: v.curFunc}
443 if _, o := candHotEdgeMap[csi]; o {
444 if base.Debug.PGOInline > 0 {
445 fmt.Printf("hot-callsite identified at line=%v for func=%v\n", ir.Line(n), ir.PkgFuncName(v.curFunc))
451 if ir.IsIntrinsicCall(n) {
452 // Treat like any other node.
456 if fn := inlCallee(n.X, v.profile); fn != nil && typecheck.HaveInlineBody(fn) {
457 v.budget -= fn.Inl.Cost
461 // Call cost for non-leaf inlining.
462 v.budget -= v.extraCallCost
465 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
467 // Things that are too hairy, irrespective of the budget
468 case ir.OCALL, ir.OCALLINTER:
469 // Call cost for non-leaf inlining.
470 v.budget -= v.extraCallCost
473 n := n.(*ir.UnaryExpr)
474 if n.X.Op() == ir.OCONVIFACE && n.X.(*ir.ConvExpr).Implicit() {
475 // Hack to keep reflect.flag.mustBe inlinable for TestIntendedInlining.
476 // Before CL 284412, these conversions were introduced later in the
477 // compiler, so they didn't count against inlining budget.
480 v.budget -= inlineExtraPanicCost
483 // recover matches the argument frame pointer to find
484 // the right panic value, so it needs an argument frame.
485 v.reason = "call to recover"
489 if base.Debug.InlFuncsWithClosures == 0 {
490 v.reason = "not inlining functions with closures"
494 // TODO(danscales): Maybe make budget proportional to number of closure
496 //v.budget -= int32(len(n.(*ir.ClosureExpr).Func.ClosureVars) * 3)
498 // Scan body of closure (which DoChildren doesn't automatically
499 // do) to check for disallowed ops in the body and include the
500 // body in the budget.
501 if doList(n.(*ir.ClosureExpr).Func.Body, v.do) {
507 ir.ODCLTYPE, // can't print yet
509 v.reason = "unhandled op " + n.Op().String()
513 v.budget -= inlineExtraAppendCost
516 n := n.(*ir.AddrExpr)
517 // Make "&s.f" cost 0 when f's offset is zero.
518 if dot, ok := n.X.(*ir.SelectorExpr); ok && (dot.Op() == ir.ODOT || dot.Op() == ir.ODOTPTR) {
519 if _, ok := dot.X.(*ir.Name); ok && dot.Selection.Offset == 0 {
520 v.budget += 2 // undo ir.OADDR+ir.ODOT/ir.ODOTPTR
525 // *(*X)(unsafe.Pointer(&x)) is low-cost
526 n := n.(*ir.StarExpr)
529 for ptr.Op() == ir.OCONVNOP {
530 ptr = ptr.(*ir.ConvExpr).X
532 if ptr.Op() == ir.OADDR {
533 v.budget += 1 // undo half of default cost of ir.ODEREF+ir.OADDR
537 // This doesn't produce code, but the children might.
538 v.budget++ // undo default cost
540 case ir.ODCLCONST, ir.OFALL:
541 // These nodes don't produce code; omit from inlining budget.
546 if ir.IsConst(n.Cond, constant.Bool) {
547 // This if and the condition cost nothing.
548 if doList(n.Init(), v.do) {
551 if ir.BoolVal(n.Cond) {
552 return doList(n.Body, v.do)
554 return doList(n.Else, v.do)
560 if n.Class == ir.PAUTO {
565 // The only OBLOCK we should see at this point is an empty one.
566 // In any event, let the visitList(n.List()) below take care of the statements,
567 // and don't charge for the OBLOCK itself. The ++ undoes the -- below.
570 case ir.OMETHVALUE, ir.OSLICELIT:
571 v.budget-- // Hack for toolstash -cmp.
574 v.budget++ // Hack for toolstash -cmp.
577 n := n.(*ir.AssignListStmt)
579 // Unified IR unconditionally rewrites:
590 // so that it can insert implicit conversions as necessary. To
591 // minimize impact to the existing inlining heuristics (in
592 // particular, to avoid breaking the existing inlinability regress
593 // tests), we need to compensate for this here.
594 if base.Debug.Unified != 0 {
595 if init := n.Rhs[0].Init(); len(init) == 1 {
596 if _, ok := init[0].(*ir.AssignListStmt); ok {
597 // 4 for each value, because each temporary variable now
598 // appears 3 times (DCL, LHS, RHS), plus an extra DCL node.
600 // 1 for the extra "tmp1, tmp2 = f()" assignment statement.
601 v.budget += 4*int32(len(n.Lhs)) + 1
607 // Special case for coverage counter updates and coverage
608 // function registrations. Although these correspond to real
609 // operations, we treat them as zero cost for the moment. This
610 // is primarily due to the existence of tests that are
611 // sensitive to inlining-- if the insertion of coverage
612 // instrumentation happens to tip a given function over the
613 // threshold and move it from "inlinable" to "not-inlinable",
614 // this can cause changes in allocation behavior, which can
615 // then result in test failures (a good example is the
616 // TestAllocations in crypto/ed25519).
617 n := n.(*ir.AssignStmt)
618 if n.X.Op() == ir.OINDEX && isIndexingCoverageCounter(n.X) {
625 // When debugging, don't stop early, to get full cost of inlining this function
626 if v.budget < 0 && base.Flag.LowerM < 2 && !logopt.Enabled() {
627 v.reason = "too expensive"
631 return ir.DoChildren(n, v.do)
634 func isBigFunc(fn *ir.Func) bool {
635 budget := inlineBigFunctionNodes
636 return ir.Any(fn, func(n ir.Node) bool {
642 // inlcopylist (together with inlcopy) recursively copies a list of nodes, except
643 // that it keeps the same ONAME, OTYPE, and OLITERAL nodes. It is used for copying
644 // the body and dcls of an inlineable function.
645 func inlcopylist(ll []ir.Node) []ir.Node {
646 s := make([]ir.Node, len(ll))
647 for i, n := range ll {
653 // inlcopy is like DeepCopy(), but does extra work to copy closures.
654 func inlcopy(n ir.Node) ir.Node {
655 var edit func(ir.Node) ir.Node
656 edit = func(x ir.Node) ir.Node {
658 case ir.ONAME, ir.OTYPE, ir.OLITERAL, ir.ONIL:
662 ir.EditChildren(m, edit)
663 if x.Op() == ir.OCLOSURE {
664 x := x.(*ir.ClosureExpr)
665 // Need to save/duplicate x.Func.Nname,
666 // x.Func.Nname.Ntype, x.Func.Dcl, x.Func.ClosureVars, and
667 // x.Func.Body for iexport and local inlining.
669 newfn := ir.NewFunc(oldfn.Pos())
670 m.(*ir.ClosureExpr).Func = newfn
671 newfn.Nname = ir.NewNameAt(oldfn.Nname.Pos(), oldfn.Nname.Sym())
672 // XXX OK to share fn.Type() ??
673 newfn.Nname.SetType(oldfn.Nname.Type())
674 newfn.Body = inlcopylist(oldfn.Body)
675 // Make shallow copy of the Dcl and ClosureVar slices
676 newfn.Dcl = append([]*ir.Name(nil), oldfn.Dcl...)
677 newfn.ClosureVars = append([]*ir.Name(nil), oldfn.ClosureVars...)
684 // InlineCalls/inlnode walks fn's statements and expressions and substitutes any
685 // calls made to inlineable functions. This is the external entry point.
686 func InlineCalls(fn *ir.Func, profile *pgo.Profile) {
689 maxCost := int32(inlineMaxBudget)
691 maxCost = inlineBigFunctionMaxCost
693 var inlCalls []*ir.InlinedCallExpr
694 var edit func(ir.Node) ir.Node
695 edit = func(n ir.Node) ir.Node {
696 return inlnode(n, maxCost, &inlCalls, edit, profile)
698 ir.EditChildren(fn, edit)
700 // If we inlined any calls, we want to recursively visit their
701 // bodies for further inlining. However, we need to wait until
702 // *after* the original function body has been expanded, or else
703 // inlCallee can have false positives (e.g., #54632).
704 for len(inlCalls) > 0 {
706 inlCalls = inlCalls[1:]
707 ir.EditChildren(call, edit)
713 // inlnode recurses over the tree to find inlineable calls, which will
714 // be turned into OINLCALLs by mkinlcall. When the recursion comes
715 // back up will examine left, right, list, rlist, ninit, ntest, nincr,
716 // nbody and nelse and use one of the 4 inlconv/glue functions above
717 // to turn the OINLCALL into an expression, a statement, or patch it
718 // in to this nodes list or rlist as appropriate.
719 // NOTE it makes no sense to pass the glue functions down the
720 // recursion to the level where the OINLCALL gets created because they
721 // have to edit /this/ n, so you'd have to push that one down as well,
722 // but then you may as well do it here. so this is cleaner and
723 // shorter and less complicated.
724 // The result of inlnode MUST be assigned back to n, e.g.
726 // n.Left = inlnode(n.Left)
727 func inlnode(n ir.Node, maxCost int32, inlCalls *[]*ir.InlinedCallExpr, edit func(ir.Node) ir.Node, profile *pgo.Profile) ir.Node {
733 case ir.ODEFER, ir.OGO:
734 n := n.(*ir.GoDeferStmt)
735 switch call := n.Call; call.Op() {
737 base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
739 call := call.(*ir.CallExpr)
743 n := n.(*ir.TailCallStmt)
744 n.Call.NoInline = true // Not inline a tail call for now. Maybe we could inline it just like RETURN fn(arg)?
746 // TODO do them here (or earlier),
747 // so escape analysis can avoid more heapmoves.
751 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
753 n := n.(*ir.CallExpr)
754 if n.X.Op() == ir.OMETHEXPR {
755 // Prevent inlining some reflect.Value methods when using checkptr,
756 // even when package reflect was compiled without it (#35073).
757 if meth := ir.MethodExprName(n.X); meth != nil {
759 if base.Debug.Checkptr != 0 && types.IsReflectPkg(s.Pkg) && (s.Name == "Value.UnsafeAddr" || s.Name == "Value.Pointer") {
768 ir.EditChildren(n, edit)
770 // with all the branches out of the way, it is now time to
771 // transmogrify this node itself unless inhibited by the
772 // switch at the top of this function.
775 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
778 call := n.(*ir.CallExpr)
782 if base.Flag.LowerM > 3 {
783 fmt.Printf("%v:call to func %+v\n", ir.Line(n), call.X)
785 if ir.IsIntrinsicCall(call) {
788 if fn := inlCallee(call.X, profile); fn != nil && typecheck.HaveInlineBody(fn) {
789 n = mkinlcall(call, fn, maxCost, inlCalls, edit)
798 // inlCallee takes a function-typed expression and returns the underlying function ONAME
799 // that it refers to if statically known. Otherwise, it returns nil.
800 func inlCallee(fn ir.Node, profile *pgo.Profile) *ir.Func {
801 fn = ir.StaticValue(fn)
804 fn := fn.(*ir.SelectorExpr)
805 n := ir.MethodExprName(fn)
806 // Check that receiver type matches fn.X.
807 // TODO(mdempsky): Handle implicit dereference
808 // of pointer receiver argument?
809 if n == nil || !types.Identical(n.Type().Recv().Type, fn.X.Type()) {
815 if fn.Class == ir.PFUNC {
819 fn := fn.(*ir.ClosureExpr)
821 CanInline(c, profile)
827 func inlParam(t *types.Field, as ir.InitNode, inlvars map[*ir.Name]*ir.Name) ir.Node {
831 n := t.Nname.(*ir.Name)
837 base.Fatalf("missing inlvar for %v", n)
839 as.PtrInit().Append(ir.NewDecl(base.Pos, ir.ODCL, inlvar))
840 inlvar.Name().Defn = as
846 // SSADumpInline gives the SSA back end a chance to dump the function
847 // when producing output for debugging the compiler itself.
848 var SSADumpInline = func(*ir.Func) {}
850 // InlineCall allows the inliner implementation to be overridden.
851 // If it returns nil, the function will not be inlined.
852 var InlineCall = oldInlineCall
854 // If n is a OCALLFUNC node, and fn is an ONAME node for a
855 // function with an inlinable body, return an OINLCALL node that can replace n.
856 // The returned node's Ninit has the parameter assignments, the Nbody is the
857 // inlined function body, and (List, Rlist) contain the (input, output)
859 // The result of mkinlcall MUST be assigned back to n, e.g.
861 // n.Left = mkinlcall(n.Left, fn, isddd)
862 func mkinlcall(n *ir.CallExpr, fn *ir.Func, maxCost int32, inlCalls *[]*ir.InlinedCallExpr, edit func(ir.Node) ir.Node) ir.Node {
864 if logopt.Enabled() {
865 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
866 fmt.Sprintf("%s cannot be inlined", ir.PkgFuncName(fn)))
870 if fn.Inl.Cost > maxCost {
871 // If the callsite is hot and it is under the inlineHotMaxBudget budget, then try to inline it, or else bail.
872 line := int(base.Ctxt.InnermostPos(n.Pos()).RelLine())
873 csi := pgo.CallSiteInfo{Line: line, Caller: ir.CurFunc}
874 if _, ok := candHotEdgeMap[csi]; ok {
875 if fn.Inl.Cost > inlineHotMaxBudget {
876 if logopt.Enabled() {
877 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
878 fmt.Sprintf("cost %d of %s exceeds max large caller cost %d", fn.Inl.Cost, ir.PkgFuncName(fn), inlineHotMaxBudget))
882 if base.Debug.PGOInline > 0 {
883 fmt.Printf("hot-budget check allows inlining for callsite at %v\n", ir.Line(n))
886 // The inlined function body is too big. Typically we use this check to restrict
887 // inlining into very big functions. See issue 26546 and 17566.
888 if logopt.Enabled() {
889 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
890 fmt.Sprintf("cost %d of %s exceeds max large caller cost %d", fn.Inl.Cost, ir.PkgFuncName(fn), maxCost))
896 if fn == ir.CurFunc {
897 // Can't recursively inline a function into itself.
898 if logopt.Enabled() {
899 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", fmt.Sprintf("recursive call to %s", ir.FuncName(ir.CurFunc)))
904 // The non-unified frontend has issues with inlining and shape parameters.
905 if base.Debug.Unified == 0 {
906 // Don't inline a function fn that has no shape parameters, but is passed at
907 // least one shape arg. This means we must be inlining a non-generic function
908 // fn that was passed into a generic function, and can be called with a shape
909 // arg because it matches an appropriate type parameters. But fn may include
910 // an interface conversion (that may be applied to a shape arg) that was not
911 // apparent when we first created the instantiation of the generic function.
912 // We can't handle this if we actually do the inlining, since we want to know
913 // all interface conversions immediately after stenciling. So, we avoid
914 // inlining in this case, see issue #49309. (1)
916 // See discussion on go.dev/cl/406475 for more background.
917 if !fn.Type().Params().HasShape() {
918 for _, arg := range n.Args {
919 if arg.Type().HasShape() {
920 if logopt.Enabled() {
921 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
922 fmt.Sprintf("inlining function %v has no-shape params with shape args", ir.FuncName(fn)))
928 // Don't inline a function fn that has shape parameters, but is passed no shape arg.
929 // See comments (1) above, and issue #51909.
930 inlineable := len(n.Args) == 0 // Function has shape in type, with no arguments can always be inlined.
931 for _, arg := range n.Args {
932 if arg.Type().HasShape() {
938 if logopt.Enabled() {
939 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
940 fmt.Sprintf("inlining function %v has shape params with no-shape args", ir.FuncName(fn)))
947 if base.Flag.Cfg.Instrumenting && types.IsRuntimePkg(fn.Sym().Pkg) {
948 // Runtime package must not be instrumented.
949 // Instrument skips runtime package. However, some runtime code can be
950 // inlined into other packages and instrumented there. To avoid this,
951 // we disable inlining of runtime functions when instrumenting.
952 // The example that we observed is inlining of LockOSThread,
953 // which lead to false race reports on m contents.
957 parent := base.Ctxt.PosTable.Pos(n.Pos()).Base().InliningIndex()
960 // Check if we've already inlined this function at this particular
961 // call site, in order to stop inlining when we reach the beginning
962 // of a recursion cycle again. We don't inline immediately recursive
963 // functions, but allow inlining if there is a recursion cycle of
964 // many functions. Most likely, the inlining will stop before we
965 // even hit the beginning of the cycle again, but this catches the
967 for inlIndex := parent; inlIndex >= 0; inlIndex = base.Ctxt.InlTree.Parent(inlIndex) {
968 if base.Ctxt.InlTree.InlinedFunction(inlIndex) == sym {
969 if base.Flag.LowerM > 1 {
970 fmt.Printf("%v: cannot inline %v into %v: repeated recursive cycle\n", ir.Line(n), fn, ir.FuncName(ir.CurFunc))
976 typecheck.FixVariadicCall(n)
978 inlIndex := base.Ctxt.InlTree.Add(parent, n.Pos(), sym)
980 closureInitLSym := func(n *ir.CallExpr, fn *ir.Func) {
981 // The linker needs FuncInfo metadata for all inlined
982 // functions. This is typically handled by gc.enqueueFunc
983 // calling ir.InitLSym for all function declarations in
984 // typecheck.Target.Decls (ir.UseClosure adds all closures to
987 // However, non-trivial closures in Decls are ignored, and are
988 // insteaded enqueued when walk of the calling function
991 // This presents a problem for direct calls to closures.
992 // Inlining will replace the entire closure definition with its
993 // body, which hides the closure from walk and thus suppresses
996 // Explicitly create a symbol early in this edge case to ensure
997 // we keep this metadata.
999 // TODO: Refactor to keep a reference so this can all be done
1002 if n.Op() != ir.OCALLFUNC {
1003 // Not a standard call.
1006 if n.X.Op() != ir.OCLOSURE {
1007 // Not a direct closure call.
1011 clo := n.X.(*ir.ClosureExpr)
1012 if ir.IsTrivialClosure(clo) {
1013 // enqueueFunc will handle trivial closures anyways.
1017 ir.InitLSym(fn, true)
1020 closureInitLSym(n, fn)
1022 if base.Flag.GenDwarfInl > 0 {
1023 if !sym.WasInlined() {
1024 base.Ctxt.DwFixups.SetPrecursorFunc(sym, fn)
1025 sym.Set(obj.AttrWasInlined, true)
1029 if base.Flag.LowerM != 0 {
1030 fmt.Printf("%v: inlining call to %v\n", ir.Line(n), fn)
1032 if base.Flag.LowerM > 2 {
1033 fmt.Printf("%v: Before inlining: %+v\n", ir.Line(n), n)
1036 if base.Debug.PGOInline > 0 {
1037 line := int(base.Ctxt.InnermostPos(n.Pos()).RelLine())
1038 csi := pgo.CallSiteInfo{Line: line, Caller: ir.CurFunc}
1039 if _, ok := inlinedCallSites[csi]; !ok {
1040 inlinedCallSites[csi] = struct{}{}
1044 res := InlineCall(n, fn, inlIndex)
1047 base.FatalfAt(n.Pos(), "inlining call to %v failed", fn)
1050 if base.Flag.LowerM > 2 {
1051 fmt.Printf("%v: After inlining %+v\n\n", ir.Line(res), res)
1054 *inlCalls = append(*inlCalls, res)
1059 // CalleeEffects appends any side effects from evaluating callee to init.
1060 func CalleeEffects(init *ir.Nodes, callee ir.Node) {
1062 init.Append(ir.TakeInit(callee)...)
1064 switch callee.Op() {
1065 case ir.ONAME, ir.OCLOSURE, ir.OMETHEXPR:
1069 conv := callee.(*ir.ConvExpr)
1073 ic := callee.(*ir.InlinedCallExpr)
1074 init.Append(ic.Body.Take()...)
1075 callee = ic.SingleResult()
1078 base.FatalfAt(callee.Pos(), "unexpected callee expression: %v", callee)
1083 // oldInlineCall creates an InlinedCallExpr to replace the given call
1084 // expression. fn is the callee function to be inlined. inlIndex is
1085 // the inlining tree position index, for use with src.NewInliningBase
1086 // when rewriting positions.
1087 func oldInlineCall(call *ir.CallExpr, fn *ir.Func, inlIndex int) *ir.InlinedCallExpr {
1088 if base.Debug.TypecheckInl == 0 {
1089 typecheck.ImportedBody(fn)
1094 ninit := call.Init()
1096 // For normal function calls, the function callee expression
1097 // may contain side effects. Make sure to preserve these,
1098 // if necessary (#42703).
1099 if call.Op() == ir.OCALLFUNC {
1100 CalleeEffects(&ninit, call.X)
1103 // Make temp names to use instead of the originals.
1104 inlvars := make(map[*ir.Name]*ir.Name)
1106 // record formals/locals for later post-processing
1107 var inlfvars []*ir.Name
1109 for _, ln := range fn.Inl.Dcl {
1110 if ln.Op() != ir.ONAME {
1113 if ln.Class == ir.PPARAMOUT { // return values handled below.
1116 inlf := typecheck.Expr(inlvar(ln)).(*ir.Name)
1118 if base.Flag.GenDwarfInl > 0 {
1119 if ln.Class == ir.PPARAM {
1120 inlf.Name().SetInlFormal(true)
1122 inlf.Name().SetInlLocal(true)
1124 inlf.SetPos(ln.Pos())
1125 inlfvars = append(inlfvars, inlf)
1129 // We can delay declaring+initializing result parameters if:
1130 // temporaries for return values.
1131 var retvars []ir.Node
1132 for i, t := range fn.Type().Results().Fields().Slice() {
1134 if nn := t.Nname; nn != nil && !ir.IsBlank(nn.(*ir.Name)) && !strings.HasPrefix(nn.Sym().Name, "~r") {
1137 m = typecheck.Expr(m).(*ir.Name)
1140 // anonymous return values, synthesize names for use in assignment that replaces return
1144 if base.Flag.GenDwarfInl > 0 {
1145 // Don't update the src.Pos on a return variable if it
1146 // was manufactured by the inliner (e.g. "~R2"); such vars
1147 // were not part of the original callee.
1148 if !strings.HasPrefix(m.Sym().Name, "~R") {
1149 m.Name().SetInlFormal(true)
1151 inlfvars = append(inlfvars, m)
1155 retvars = append(retvars, m)
1158 // Assign arguments to the parameters' temp names.
1159 as := ir.NewAssignListStmt(base.Pos, ir.OAS2, nil, nil)
1161 if call.Op() == ir.OCALLMETH {
1162 base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
1164 as.Rhs.Append(call.Args...)
1166 if recv := fn.Type().Recv(); recv != nil {
1167 as.Lhs.Append(inlParam(recv, as, inlvars))
1169 for _, param := range fn.Type().Params().Fields().Slice() {
1170 as.Lhs.Append(inlParam(param, as, inlvars))
1173 if len(as.Rhs) != 0 {
1174 ninit.Append(typecheck.Stmt(as))
1177 if !fn.Inl.CanDelayResults {
1178 // Zero the return parameters.
1179 for _, n := range retvars {
1180 ninit.Append(ir.NewDecl(base.Pos, ir.ODCL, n.(*ir.Name)))
1181 ras := ir.NewAssignStmt(base.Pos, n, nil)
1182 ninit.Append(typecheck.Stmt(ras))
1186 retlabel := typecheck.AutoLabel(".i")
1190 // Add an inline mark just before the inlined body.
1191 // This mark is inline in the code so that it's a reasonable spot
1192 // to put a breakpoint. Not sure if that's really necessary or not
1193 // (in which case it could go at the end of the function instead).
1194 // Note issue 28603.
1195 ninit.Append(ir.NewInlineMarkStmt(call.Pos().WithIsStmt(), int64(inlIndex)))
1201 defnMarker: ir.NilExpr{},
1202 bases: make(map[*src.PosBase]*src.PosBase),
1203 newInlIndex: inlIndex,
1206 subst.edit = subst.node
1208 body := subst.list(ir.Nodes(fn.Inl.Body))
1210 lab := ir.NewLabelStmt(base.Pos, retlabel)
1211 body = append(body, lab)
1213 if base.Flag.GenDwarfInl > 0 {
1214 for _, v := range inlfvars {
1215 v.SetPos(subst.updatedPos(v.Pos()))
1219 //dumplist("ninit post", ninit);
1221 res := ir.NewInlinedCallExpr(base.Pos, body, retvars)
1223 res.SetType(call.Type())
1228 // Every time we expand a function we generate a new set of tmpnames,
1229 // PAUTO's in the calling functions, and link them off of the
1230 // PPARAM's, PAUTOS and PPARAMOUTs of the called function.
1231 func inlvar(var_ *ir.Name) *ir.Name {
1232 if base.Flag.LowerM > 3 {
1233 fmt.Printf("inlvar %+v\n", var_)
1236 n := typecheck.NewName(var_.Sym())
1237 n.SetType(var_.Type())
1241 n.SetAutoTemp(var_.AutoTemp())
1242 n.Curfn = ir.CurFunc // the calling function, not the called one
1243 n.SetAddrtaken(var_.Addrtaken())
1245 ir.CurFunc.Dcl = append(ir.CurFunc.Dcl, n)
1249 // Synthesize a variable to store the inlined function's results in.
1250 func retvar(t *types.Field, i int) *ir.Name {
1251 n := typecheck.NewName(typecheck.LookupNum("~R", i))
1256 n.Curfn = ir.CurFunc // the calling function, not the called one
1257 ir.CurFunc.Dcl = append(ir.CurFunc.Dcl, n)
1261 // The inlsubst type implements the actual inlining of a single
1263 type inlsubst struct {
1264 // Target of the goto substituted in place of a return.
1267 // Temporary result variables.
1270 inlvars map[*ir.Name]*ir.Name
1271 // defnMarker is used to mark a Node for reassignment.
1272 // inlsubst.clovar set this during creating new ONAME.
1273 // inlsubst.node will set the correct Defn for inlvar.
1274 defnMarker ir.NilExpr
1276 // bases maps from original PosBase to PosBase with an extra
1277 // inlined call frame.
1278 bases map[*src.PosBase]*src.PosBase
1280 // newInlIndex is the index of the inlined call frame to
1281 // insert for inlined nodes.
1284 edit func(ir.Node) ir.Node // cached copy of subst.node method value closure
1286 // If non-nil, we are inside a closure inside the inlined function, and
1287 // newclofn is the Func of the new inlined closure.
1290 fn *ir.Func // For debug -- the func that is being inlined
1292 // If true, then don't update source positions during substitution
1293 // (retain old source positions).
1297 // list inlines a list of nodes.
1298 func (subst *inlsubst) list(ll ir.Nodes) []ir.Node {
1299 s := make([]ir.Node, 0, len(ll))
1300 for _, n := range ll {
1301 s = append(s, subst.node(n))
1306 // fields returns a list of the fields of a struct type representing receiver,
1307 // params, or results, after duplicating the field nodes and substituting the
1308 // Nname nodes inside the field nodes.
1309 func (subst *inlsubst) fields(oldt *types.Type) []*types.Field {
1310 oldfields := oldt.FieldSlice()
1311 newfields := make([]*types.Field, len(oldfields))
1312 for i := range oldfields {
1313 newfields[i] = oldfields[i].Copy()
1314 if oldfields[i].Nname != nil {
1315 newfields[i].Nname = subst.node(oldfields[i].Nname.(*ir.Name))
1321 // clovar creates a new ONAME node for a local variable or param of a closure
1322 // inside a function being inlined.
1323 func (subst *inlsubst) clovar(n *ir.Name) *ir.Name {
1324 m := ir.NewNameAt(n.Pos(), n.Sym())
1328 if n.IsClosureVar() {
1329 m.SetIsClosureVar(true)
1332 m.SetAddrtaken(true)
1339 m.Curfn = subst.newclofn
1341 switch defn := n.Defn.(type) {
1345 if !n.IsClosureVar() {
1346 base.FatalfAt(n.Pos(), "want closure variable, got: %+v", n)
1348 if n.Sym().Pkg != types.LocalPkg {
1349 // If the closure came from inlining a function from
1350 // another package, must change package of captured
1351 // variable to localpkg, so that the fields of the closure
1352 // struct are local package and can be accessed even if
1353 // name is not exported. If you disable this code, you can
1354 // reproduce the problem by running 'go test
1355 // go/internal/srcimporter'. TODO(mdempsky) - maybe change
1356 // how we create closure structs?
1357 m.SetSym(types.LocalPkg.Lookup(n.Sym().Name))
1359 // Make sure any inlvar which is the Defn
1360 // of an ONAME closure var is rewritten
1361 // during inlining. Don't substitute
1362 // if Defn node is outside inlined function.
1363 if subst.inlvars[n.Defn.(*ir.Name)] != nil {
1364 m.Defn = subst.node(n.Defn)
1366 case *ir.AssignStmt, *ir.AssignListStmt:
1367 // Mark node for reassignment at the end of inlsubst.node.
1368 m.Defn = &subst.defnMarker
1369 case *ir.TypeSwitchGuard:
1370 // TODO(mdempsky): Set m.Defn properly. See discussion on #45743.
1372 // TODO: Set m.Defn properly if we support inlining range statement in the future.
1374 base.FatalfAt(n.Pos(), "unexpected Defn: %+v", defn)
1378 // Either the outer variable is defined in function being inlined,
1379 // and we will replace it with the substituted variable, or it is
1380 // defined outside the function being inlined, and we should just
1381 // skip the outer variable (the closure variable of the function
1383 s := subst.node(n.Outer).(*ir.Name)
1392 // closure does the necessary substitions for a ClosureExpr n and returns the new
1394 func (subst *inlsubst) closure(n *ir.ClosureExpr) ir.Node {
1395 // Prior to the subst edit, set a flag in the inlsubst to indicate
1396 // that we don't want to update the source positions in the new
1397 // closure function. If we do this, it will appear that the
1398 // closure itself has things inlined into it, which is not the
1399 // case. See issue #46234 for more details. At the same time, we
1400 // do want to update the position in the new ClosureExpr (which is
1401 // part of the function we're working on). See #49171 for an
1402 // example of what happens if we miss that update.
1403 newClosurePos := subst.updatedPos(n.Pos())
1404 defer func(prev bool) { subst.noPosUpdate = prev }(subst.noPosUpdate)
1405 subst.noPosUpdate = true
1407 //fmt.Printf("Inlining func %v with closure into %v\n", subst.fn, ir.FuncName(ir.CurFunc))
1410 newfn := ir.NewClosureFunc(oldfn.Pos(), true)
1412 if subst.newclofn != nil {
1413 //fmt.Printf("Inlining a closure with a nested closure\n")
1415 prevxfunc := subst.newclofn
1417 // Mark that we are now substituting within a closure (within the
1418 // inlined function), and create new nodes for all the local
1419 // vars/params inside this closure.
1420 subst.newclofn = newfn
1422 newfn.ClosureVars = nil
1423 for _, oldv := range oldfn.Dcl {
1424 newv := subst.clovar(oldv)
1425 subst.inlvars[oldv] = newv
1426 newfn.Dcl = append(newfn.Dcl, newv)
1428 for _, oldv := range oldfn.ClosureVars {
1429 newv := subst.clovar(oldv)
1430 subst.inlvars[oldv] = newv
1431 newfn.ClosureVars = append(newfn.ClosureVars, newv)
1434 // Need to replace ONAME nodes in
1435 // newfn.Type().FuncType().Receiver/Params/Results.FieldSlice().Nname
1436 oldt := oldfn.Type()
1437 newrecvs := subst.fields(oldt.Recvs())
1438 var newrecv *types.Field
1439 if len(newrecvs) > 0 {
1440 newrecv = newrecvs[0]
1442 newt := types.NewSignature(oldt.Pkg(), newrecv,
1443 nil, subst.fields(oldt.Params()), subst.fields(oldt.Results()))
1445 newfn.Nname.SetType(newt)
1446 newfn.Body = subst.list(oldfn.Body)
1448 // Remove the nodes for the current closure from subst.inlvars
1449 for _, oldv := range oldfn.Dcl {
1450 delete(subst.inlvars, oldv)
1452 for _, oldv := range oldfn.ClosureVars {
1453 delete(subst.inlvars, oldv)
1455 // Go back to previous closure func
1456 subst.newclofn = prevxfunc
1458 // Actually create the named function for the closure, now that
1459 // the closure is inlined in a specific function.
1460 newclo := newfn.OClosure
1461 newclo.SetPos(newClosurePos)
1462 newclo.SetInit(subst.list(n.Init()))
1463 return typecheck.Expr(newclo)
1466 // node recursively copies a node from the saved pristine body of the
1467 // inlined function, substituting references to input/output
1468 // parameters with ones to the tmpnames, and substituting returns with
1469 // assignments to the output.
1470 func (subst *inlsubst) node(n ir.Node) ir.Node {
1479 // Handle captured variables when inlining closures.
1480 if n.IsClosureVar() && subst.newclofn == nil {
1483 // Deal with case where sequence of closures are inlined.
1484 // TODO(danscales) - write test case to see if we need to
1485 // go up multiple levels.
1486 if o.Curfn != ir.CurFunc {
1490 // make sure the outer param matches the inlining location
1491 if o == nil || o.Curfn != ir.CurFunc {
1492 base.Fatalf("%v: unresolvable capture %v\n", ir.Line(n), n)
1495 if base.Flag.LowerM > 2 {
1496 fmt.Printf("substituting captured name %+v -> %+v\n", n, o)
1501 if inlvar := subst.inlvars[n]; inlvar != nil { // These will be set during inlnode
1502 if base.Flag.LowerM > 2 {
1503 fmt.Printf("substituting name %+v -> %+v\n", n, inlvar)
1508 if base.Flag.LowerM > 2 {
1509 fmt.Printf("not substituting name %+v\n", n)
1514 n := n.(*ir.SelectorExpr)
1517 case ir.OLITERAL, ir.ONIL, ir.OTYPE:
1518 // If n is a named constant or type, we can continue
1519 // using it in the inline copy. Otherwise, make a copy
1520 // so we can update the line number.
1526 if subst.newclofn != nil {
1527 // Don't do special substitutions if inside a closure
1530 // Because of the above test for subst.newclofn,
1531 // this return is guaranteed to belong to the current inlined function.
1532 n := n.(*ir.ReturnStmt)
1533 init := subst.list(n.Init())
1534 if len(subst.retvars) != 0 && len(n.Results) != 0 {
1535 as := ir.NewAssignListStmt(base.Pos, ir.OAS2, nil, nil)
1537 // Make a shallow copy of retvars.
1538 // Otherwise OINLCALL.Rlist will be the same list,
1539 // and later walk and typecheck may clobber it.
1540 for _, n := range subst.retvars {
1543 as.Rhs = subst.list(n.Results)
1545 if subst.fn.Inl.CanDelayResults {
1546 for _, n := range as.Lhs {
1547 as.PtrInit().Append(ir.NewDecl(base.Pos, ir.ODCL, n.(*ir.Name)))
1552 init = append(init, typecheck.Stmt(as))
1554 init = append(init, ir.NewBranchStmt(base.Pos, ir.OGOTO, subst.retlabel))
1555 typecheck.Stmts(init)
1556 return ir.NewBlockStmt(base.Pos, init)
1558 case ir.OGOTO, ir.OBREAK, ir.OCONTINUE:
1559 if subst.newclofn != nil {
1560 // Don't do special substitutions if inside a closure
1563 n := n.(*ir.BranchStmt)
1564 m := ir.Copy(n).(*ir.BranchStmt)
1565 m.SetPos(subst.updatedPos(m.Pos()))
1567 m.Label = translateLabel(n.Label)
1571 if subst.newclofn != nil {
1572 // Don't do special substitutions if inside a closure
1575 n := n.(*ir.LabelStmt)
1576 m := ir.Copy(n).(*ir.LabelStmt)
1577 m.SetPos(subst.updatedPos(m.Pos()))
1579 m.Label = translateLabel(n.Label)
1583 return subst.closure(n.(*ir.ClosureExpr))
1588 m.SetPos(subst.updatedPos(m.Pos()))
1589 ir.EditChildren(m, subst.edit)
1591 if subst.newclofn == nil {
1592 // Translate any label on FOR, RANGE loops, SWITCH or SELECT
1595 m := m.(*ir.ForStmt)
1596 m.Label = translateLabel(m.Label)
1600 m := m.(*ir.RangeStmt)
1601 m.Label = translateLabel(m.Label)
1605 m := m.(*ir.SwitchStmt)
1606 m.Label = translateLabel(m.Label)
1610 m := m.(*ir.SelectStmt)
1611 m.Label = translateLabel(m.Label)
1616 switch m := m.(type) {
1617 case *ir.AssignStmt:
1618 if lhs, ok := m.X.(*ir.Name); ok && lhs.Defn == &subst.defnMarker {
1621 case *ir.AssignListStmt:
1622 for _, lhs := range m.Lhs {
1623 if lhs, ok := lhs.(*ir.Name); ok && lhs.Defn == &subst.defnMarker {
1632 // translateLabel makes a label from an inlined function (if non-nil) be unique by
1633 // adding "·inlgen".
1634 func translateLabel(l *types.Sym) *types.Sym {
1638 p := fmt.Sprintf("%s·%d", l.Name, inlgen)
1639 return typecheck.Lookup(p)
1642 func (subst *inlsubst) updatedPos(xpos src.XPos) src.XPos {
1643 if subst.noPosUpdate {
1646 pos := base.Ctxt.PosTable.Pos(xpos)
1647 oldbase := pos.Base() // can be nil
1648 newbase := subst.bases[oldbase]
1650 newbase = src.NewInliningBase(oldbase, subst.newInlIndex)
1651 subst.bases[oldbase] = newbase
1653 pos.SetBase(newbase)
1654 return base.Ctxt.PosTable.XPos(pos)
1657 func pruneUnusedAutos(ll []*ir.Name, vis *hairyVisitor) []*ir.Name {
1658 s := make([]*ir.Name, 0, len(ll))
1659 for _, n := range ll {
1660 if n.Class == ir.PAUTO {
1661 if !vis.usedLocals.Has(n) {
1670 // numNonClosures returns the number of functions in list which are not closures.
1671 func numNonClosures(list []*ir.Func) int {
1673 for _, fn := range list {
1674 if fn.OClosure == nil {
1681 func doList(list []ir.Node, do func(ir.Node) bool) bool {
1682 for _, x := range list {
1692 // isIndexingCoverageCounter returns true if the specified node 'n' is indexing
1693 // into a coverage counter array.
1694 func isIndexingCoverageCounter(n ir.Node) bool {
1695 if n.Op() != ir.OINDEX {
1698 ixn := n.(*ir.IndexExpr)
1699 if ixn.X.Op() != ir.ONAME || !ixn.X.Type().IsArray() {
1702 nn := ixn.X.(*ir.Name)
1703 return nn.CoverageCounter()
1706 // isAtomicCoverageCounterUpdate examines the specified node to
1707 // determine whether it represents a call to sync/atomic.AddUint32 to
1708 // increment a coverage counter.
1709 func isAtomicCoverageCounterUpdate(cn *ir.CallExpr) bool {
1710 if cn.X.Op() != ir.ONAME {
1713 name := cn.X.(*ir.Name)
1714 if name.Class != ir.PFUNC {
1717 fn := name.Sym().Name
1718 if name.Sym().Pkg.Path != "sync/atomic" ||
1719 (fn != "AddUint32" && fn != "StoreUint32") {
1722 if len(cn.Args) != 2 || cn.Args[0].Op() != ir.OADDR {
1725 adn := cn.Args[0].(*ir.AddrExpr)
1726 v := isIndexingCoverageCounter(adn.X)