1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // The inlining facility makes 2 passes: first CanInline determines which
6 // functions are suitable for inlining, and for those that are it
7 // saves a copy of the body. Then InlineCalls walks each function body to
8 // expand calls to inlinable functions.
10 // The Debug.l flag controls the aggressiveness. Note that main() swaps level 0 and 1,
11 // making 1 the default and -l disable. Additional levels (beyond -l) may be buggy and
14 // 1: 80-nodes leaf functions, oneliners, panic, lazy typechecking (default)
17 // 4: allow non-leaf functions
19 // At some point this may get another default and become switch-offable with -N.
21 // The -d typcheckinl flag enables early typechecking of all imported bodies,
22 // which is useful to flush out bugs.
24 // The Debug.m flag enables diagnostic output. a single -m is useful for verifying
25 // which calls get inlined or not, more is for debugging, and may go away at any point.
36 "cmd/compile/internal/base"
37 "cmd/compile/internal/ir"
38 "cmd/compile/internal/logopt"
39 "cmd/compile/internal/pgo"
40 "cmd/compile/internal/typecheck"
41 "cmd/compile/internal/types"
46 // Inlining budget parameters, gathered in one place
49 inlineExtraAppendCost = 0
50 // default is to inline if there's at most one call. -l=4 overrides this by using 1 instead.
51 inlineExtraCallCost = 57 // 57 was benchmarked to provided most benefit with no bad surprises; see https://github.com/golang/go/issues/19348#issuecomment-439370742
52 inlineExtraPanicCost = 1 // do not penalize inlining panics.
53 inlineExtraThrowCost = inlineMaxBudget // with current (2018-05/1.11) code, inlining runtime.throw does not help.
55 inlineBigFunctionNodes = 5000 // Functions with this many nodes are considered "big".
56 inlineBigFunctionMaxCost = 20 // Max cost of inlinee when inlining into a "big" function.
60 // List of all hot callee nodes.
61 // TODO(prattmic): Make this non-global.
62 candHotCalleeMap = make(map[*pgo.IRNode]struct{})
64 // List of all hot call sites. CallSiteInfo.Callee is always nil.
65 // TODO(prattmic): Make this non-global.
66 candHotEdgeMap = make(map[pgo.CallSiteInfo]struct{})
68 // List of inlined call sites. CallSiteInfo.Callee is always nil.
69 // TODO(prattmic): Make this non-global.
70 inlinedCallSites = make(map[pgo.CallSiteInfo]struct{})
72 // Threshold in percentage for hot callsite inlining.
73 inlineHotCallSiteThresholdPercent float64
75 // Threshold in CDF percentage for hot callsite inlining,
76 // that is, for a threshold of X the hottest callsites that
77 // make up the top X% of total edge weight will be
78 // considered hot for inlining candidates.
79 inlineCDFHotCallSiteThresholdPercent = float64(99)
81 // Budget increased due to hotness.
82 inlineHotMaxBudget int32 = 2000
85 // pgoInlinePrologue records the hot callsites from ir-graph.
86 func pgoInlinePrologue(p *pgo.Profile, decls []ir.Node) {
87 if base.Debug.PGOInlineCDFThreshold != "" {
88 if s, err := strconv.ParseFloat(base.Debug.PGOInlineCDFThreshold, 64); err == nil && s >= 0 && s <= 100 {
89 inlineCDFHotCallSiteThresholdPercent = s
91 base.Fatalf("invalid PGOInlineCDFThreshold, must be between 0 and 100")
94 var hotCallsites []pgo.NodeMapKey
95 inlineHotCallSiteThresholdPercent, hotCallsites = hotNodesFromCDF(p)
96 if base.Debug.PGOInline > 0 {
97 fmt.Printf("hot-callsite-thres-from-CDF=%v\n", inlineHotCallSiteThresholdPercent)
100 if x := base.Debug.PGOInlineBudget; x != 0 {
101 inlineHotMaxBudget = int32(x)
104 for _, n := range hotCallsites {
105 // mark inlineable callees from hot edges
106 if callee := p.WeightedCG.IRNodes[n.CalleeName]; callee != nil {
107 candHotCalleeMap[callee] = struct{}{}
109 // mark hot call sites
110 if caller := p.WeightedCG.IRNodes[n.CallerName]; caller != nil {
111 csi := pgo.CallSiteInfo{LineOffset: n.CallSiteOffset, Caller: caller.AST}
112 candHotEdgeMap[csi] = struct{}{}
116 if base.Debug.PGOInline >= 2 {
117 fmt.Printf("hot-cg before inline in dot format:")
118 p.PrintWeightedCallGraphDOT(inlineHotCallSiteThresholdPercent)
122 // hotNodesFromCDF computes an edge weight threshold and the list of hot
123 // nodes that make up the given percentage of the CDF. The threshold, as
124 // a percent, is the lower bound of weight for nodes to be considered hot
125 // (currently only used in debug prints) (in case of equal weights,
126 // comparing with the threshold may not accurately reflect which nodes are
128 func hotNodesFromCDF(p *pgo.Profile) (float64, []pgo.NodeMapKey) {
129 nodes := make([]pgo.NodeMapKey, len(p.NodeMap))
131 for n := range p.NodeMap {
135 sort.Slice(nodes, func(i, j int) bool {
136 ni, nj := nodes[i], nodes[j]
137 if wi, wj := p.NodeMap[ni].EWeight, p.NodeMap[nj].EWeight; wi != wj {
138 return wi > wj // want larger weight first
140 // same weight, order by name/line number
141 if ni.CallerName != nj.CallerName {
142 return ni.CallerName < nj.CallerName
144 if ni.CalleeName != nj.CalleeName {
145 return ni.CalleeName < nj.CalleeName
147 return ni.CallSiteOffset < nj.CallSiteOffset
150 for i, n := range nodes {
151 w := p.NodeMap[n].EWeight
153 if pgo.WeightInPercentage(cum, p.TotalEdgeWeight) > inlineCDFHotCallSiteThresholdPercent {
154 // nodes[:i+1] to include the very last node that makes it to go over the threshold.
155 // (Say, if the CDF threshold is 50% and one hot node takes 60% of weight, we want to
156 // include that node instead of excluding it.)
157 return pgo.WeightInPercentage(w, p.TotalEdgeWeight), nodes[:i+1]
163 // pgoInlineEpilogue updates IRGraph after inlining.
164 func pgoInlineEpilogue(p *pgo.Profile, decls []ir.Node) {
165 if base.Debug.PGOInline >= 2 {
166 ir.VisitFuncsBottomUp(decls, func(list []*ir.Func, recursive bool) {
167 for _, f := range list {
168 name := ir.PkgFuncName(f)
169 if n, ok := p.WeightedCG.IRNodes[name]; ok {
170 p.RedirectEdges(n, inlinedCallSites)
174 // Print the call-graph after inlining. This is a debugging feature.
175 fmt.Printf("hot-cg after inline in dot:")
176 p.PrintWeightedCallGraphDOT(inlineHotCallSiteThresholdPercent)
180 // InlinePackage finds functions that can be inlined and clones them before walk expands them.
181 func InlinePackage(p *pgo.Profile) {
182 InlineDecls(p, typecheck.Target.Decls, true)
185 // InlineDecls applies inlining to the given batch of declarations.
186 func InlineDecls(p *pgo.Profile, decls []ir.Node, doInline bool) {
188 pgoInlinePrologue(p, decls)
191 ir.VisitFuncsBottomUp(decls, func(list []*ir.Func, recursive bool) {
192 numfns := numNonClosures(list)
193 for _, n := range list {
194 if !recursive || numfns > 1 {
195 // We allow inlining if there is no
196 // recursion, or the recursion cycle is
197 // across more than one function.
200 if base.Flag.LowerM > 1 {
201 fmt.Printf("%v: cannot inline %v: recursive\n", ir.Line(n), n.Nname)
211 pgoInlineEpilogue(p, decls)
215 // CanInline determines whether fn is inlineable.
216 // If so, CanInline saves copies of fn.Body and fn.Dcl in fn.Inl.
217 // fn and fn.Body will already have been typechecked.
218 func CanInline(fn *ir.Func, profile *pgo.Profile) {
220 base.Fatalf("CanInline no nname %+v", fn)
223 var reason string // reason, if any, that the function was not inlined
224 if base.Flag.LowerM > 1 || logopt.Enabled() {
227 if base.Flag.LowerM > 1 {
228 fmt.Printf("%v: cannot inline %v: %s\n", ir.Line(fn), fn.Nname, reason)
230 if logopt.Enabled() {
231 logopt.LogOpt(fn.Pos(), "cannotInlineFunction", "inline", ir.FuncName(fn), reason)
237 // If marked "go:noinline", don't inline
238 if fn.Pragma&ir.Noinline != 0 {
239 reason = "marked go:noinline"
243 // If marked "go:norace" and -race compilation, don't inline.
244 if base.Flag.Race && fn.Pragma&ir.Norace != 0 {
245 reason = "marked go:norace with -race compilation"
249 // If marked "go:nocheckptr" and -d checkptr compilation, don't inline.
250 if base.Debug.Checkptr != 0 && fn.Pragma&ir.NoCheckPtr != 0 {
251 reason = "marked go:nocheckptr"
255 // If marked "go:cgo_unsafe_args", don't inline, since the
256 // function makes assumptions about its argument frame layout.
257 if fn.Pragma&ir.CgoUnsafeArgs != 0 {
258 reason = "marked go:cgo_unsafe_args"
262 // If marked as "go:uintptrkeepalive", don't inline, since the
263 // keep alive information is lost during inlining.
265 // TODO(prattmic): This is handled on calls during escape analysis,
266 // which is after inlining. Move prior to inlining so the keep-alive is
267 // maintained after inlining.
268 if fn.Pragma&ir.UintptrKeepAlive != 0 {
269 reason = "marked as having a keep-alive uintptr argument"
273 // If marked as "go:uintptrescapes", don't inline, since the
274 // escape information is lost during inlining.
275 if fn.Pragma&ir.UintptrEscapes != 0 {
276 reason = "marked as having an escaping uintptr argument"
280 // The nowritebarrierrec checker currently works at function
281 // granularity, so inlining yeswritebarrierrec functions can
282 // confuse it (#22342). As a workaround, disallow inlining
284 if fn.Pragma&ir.Yeswritebarrierrec != 0 {
285 reason = "marked go:yeswritebarrierrec"
289 // If fn has no body (is defined outside of Go), cannot inline it.
290 if len(fn.Body) == 0 {
291 reason = "no function body"
295 if fn.Typecheck() == 0 {
296 base.Fatalf("CanInline on non-typechecked function %v", fn)
300 if n.Func.InlinabilityChecked() {
303 defer n.Func.SetInlinabilityChecked(true)
305 cc := int32(inlineExtraCallCost)
306 if base.Flag.LowerL == 4 {
307 cc = 1 // this appears to yield better performance than 0.
310 // Update the budget for profile-guided inlining.
311 budget := int32(inlineMaxBudget)
313 if n, ok := profile.WeightedCG.IRNodes[ir.PkgFuncName(fn)]; ok {
314 if _, ok := candHotCalleeMap[n]; ok {
315 budget = int32(inlineHotMaxBudget)
316 if base.Debug.PGOInline > 0 {
317 fmt.Printf("hot-node enabled increased budget=%v for func=%v\n", budget, ir.PkgFuncName(fn))
323 // At this point in the game the function we're looking at may
324 // have "stale" autos, vars that still appear in the Dcl list, but
325 // which no longer have any uses in the function body (due to
326 // elimination by deadcode). We'd like to exclude these dead vars
327 // when creating the "Inline.Dcl" field below; to accomplish this,
328 // the hairyVisitor below builds up a map of used/referenced
329 // locals, and we use this map to produce a pruned Inline.Dcl
330 // list. See issue 25249 for more context.
332 visitor := hairyVisitor{
339 if visitor.tooHairy(fn) {
340 reason = visitor.reason
344 n.Func.Inl = &ir.Inline{
345 Cost: budget - visitor.budget,
346 Dcl: pruneUnusedAutos(n.Defn.(*ir.Func).Dcl, &visitor),
347 Body: inlcopylist(fn.Body),
349 CanDelayResults: canDelayResults(fn),
352 if base.Flag.LowerM > 1 {
353 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))
354 } else if base.Flag.LowerM != 0 {
355 fmt.Printf("%v: can inline %v\n", ir.Line(fn), n)
357 if logopt.Enabled() {
358 logopt.LogOpt(fn.Pos(), "canInlineFunction", "inline", ir.FuncName(fn), fmt.Sprintf("cost: %d", budget-visitor.budget))
362 // canDelayResults reports whether inlined calls to fn can delay
363 // declaring the result parameter until the "return" statement.
364 func canDelayResults(fn *ir.Func) bool {
365 // We can delay declaring+initializing result parameters if:
366 // (1) there's exactly one "return" statement in the inlined function;
367 // (2) it's not an empty return statement (#44355); and
368 // (3) the result parameters aren't named.
371 ir.VisitList(fn.Body, func(n ir.Node) {
372 if n, ok := n.(*ir.ReturnStmt); ok {
374 if len(n.Results) == 0 {
375 nreturns++ // empty return statement (case 2)
381 return false // not exactly one return statement (case 1)
384 // temporaries for return values.
385 for _, param := range fn.Type().Results().FieldSlice() {
386 if sym := types.OrigSym(param.Sym); sym != nil && !sym.IsBlank() {
387 return false // found a named result parameter (case 3)
394 // hairyVisitor visits a function body to determine its inlining
395 // hairiness and whether or not it can be inlined.
396 type hairyVisitor struct {
397 // This is needed to access the current caller in the doNode function.
403 usedLocals ir.NameSet
404 do func(ir.Node) bool
408 func (v *hairyVisitor) tooHairy(fn *ir.Func) bool {
409 v.do = v.doNode // cache closure
410 if ir.DoChildren(fn, v.do) {
414 v.reason = fmt.Sprintf("function too complex: cost %d exceeds budget %d", v.maxBudget-v.budget, v.maxBudget)
420 func (v *hairyVisitor) doNode(n ir.Node) bool {
425 // Call is okay if inlinable and we have the budget for the body.
427 n := n.(*ir.CallExpr)
428 // Functions that call runtime.getcaller{pc,sp} can not be inlined
429 // because getcaller{pc,sp} expect a pointer to the caller's first argument.
431 // runtime.throw is a "cheap call" like panic in normal code.
432 if n.X.Op() == ir.ONAME {
433 name := n.X.(*ir.Name)
434 if name.Class == ir.PFUNC && types.IsRuntimePkg(name.Sym().Pkg) {
435 fn := name.Sym().Name
436 if fn == "getcallerpc" || fn == "getcallersp" {
437 v.reason = "call to " + fn
441 v.budget -= inlineExtraThrowCost
445 // Special case for coverage counter updates; although
446 // these correspond to real operations, we treat them as
447 // zero cost for the moment. This is due to the existence
448 // of tests that are sensitive to inlining-- if the
449 // insertion of coverage instrumentation happens to tip a
450 // given function over the threshold and move it from
451 // "inlinable" to "not-inlinable", this can cause changes
452 // in allocation behavior, which can then result in test
453 // failures (a good example is the TestAllocations in
455 if isAtomicCoverageCounterUpdate(n) {
459 if n.X.Op() == ir.OMETHEXPR {
460 if meth := ir.MethodExprName(n.X); meth != nil {
461 if fn := meth.Func; fn != nil {
464 if types.IsRuntimePkg(s.Pkg) && s.Name == "heapBits.nextArena" {
465 // Special case: explicitly allow mid-stack inlining of
466 // runtime.heapBits.next even though it calls slow-path
467 // runtime.heapBits.nextArena.
470 // Special case: on architectures that can do unaligned loads,
471 // explicitly mark encoding/binary methods as cheap,
472 // because in practice they are, even though our inlining
473 // budgeting system does not see that. See issue 42958.
474 if base.Ctxt.Arch.CanMergeLoads && s.Pkg.Path == "encoding/binary" {
476 case "littleEndian.Uint64", "littleEndian.Uint32", "littleEndian.Uint16",
477 "bigEndian.Uint64", "bigEndian.Uint32", "bigEndian.Uint16",
478 "littleEndian.PutUint64", "littleEndian.PutUint32", "littleEndian.PutUint16",
479 "bigEndian.PutUint64", "bigEndian.PutUint32", "bigEndian.PutUint16",
480 "littleEndian.AppendUint64", "littleEndian.AppendUint32", "littleEndian.AppendUint16",
481 "bigEndian.AppendUint64", "bigEndian.AppendUint32", "bigEndian.AppendUint16":
486 break // treat like any other node, that is, cost of 1
492 // Determine if the callee edge is for an inlinable hot callee or not.
493 if v.profile != nil && v.curFunc != nil {
494 if fn := inlCallee(n.X, v.profile); fn != nil && typecheck.HaveInlineBody(fn) {
495 lineOffset := pgo.NodeLineOffset(n, fn)
496 csi := pgo.CallSiteInfo{LineOffset: lineOffset, Caller: v.curFunc}
497 if _, o := candHotEdgeMap[csi]; o {
498 if base.Debug.PGOInline > 0 {
499 fmt.Printf("hot-callsite identified at line=%v for func=%v\n", ir.Line(n), ir.PkgFuncName(v.curFunc))
505 if ir.IsIntrinsicCall(n) {
506 // Treat like any other node.
510 if fn := inlCallee(n.X, v.profile); fn != nil && typecheck.HaveInlineBody(fn) {
511 v.budget -= fn.Inl.Cost
515 // Call cost for non-leaf inlining.
516 v.budget -= v.extraCallCost
519 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
521 // Things that are too hairy, irrespective of the budget
522 case ir.OCALL, ir.OCALLINTER:
523 // Call cost for non-leaf inlining.
524 v.budget -= v.extraCallCost
527 n := n.(*ir.UnaryExpr)
528 if n.X.Op() == ir.OCONVIFACE && n.X.(*ir.ConvExpr).Implicit() {
529 // Hack to keep reflect.flag.mustBe inlinable for TestIntendedInlining.
530 // Before CL 284412, these conversions were introduced later in the
531 // compiler, so they didn't count against inlining budget.
534 v.budget -= inlineExtraPanicCost
537 // recover matches the argument frame pointer to find
538 // the right panic value, so it needs an argument frame.
539 v.reason = "call to recover"
543 if base.Debug.InlFuncsWithClosures == 0 {
544 v.reason = "not inlining functions with closures"
548 // TODO(danscales): Maybe make budget proportional to number of closure
550 //v.budget -= int32(len(n.(*ir.ClosureExpr).Func.ClosureVars) * 3)
552 // Scan body of closure (which DoChildren doesn't automatically
553 // do) to check for disallowed ops in the body and include the
554 // body in the budget.
555 if doList(n.(*ir.ClosureExpr).Func.Body, v.do) {
561 ir.ODCLTYPE, // can't print yet
563 v.reason = "unhandled op " + n.Op().String()
567 v.budget -= inlineExtraAppendCost
570 n := n.(*ir.AddrExpr)
571 // Make "&s.f" cost 0 when f's offset is zero.
572 if dot, ok := n.X.(*ir.SelectorExpr); ok && (dot.Op() == ir.ODOT || dot.Op() == ir.ODOTPTR) {
573 if _, ok := dot.X.(*ir.Name); ok && dot.Selection.Offset == 0 {
574 v.budget += 2 // undo ir.OADDR+ir.ODOT/ir.ODOTPTR
579 // *(*X)(unsafe.Pointer(&x)) is low-cost
580 n := n.(*ir.StarExpr)
583 for ptr.Op() == ir.OCONVNOP {
584 ptr = ptr.(*ir.ConvExpr).X
586 if ptr.Op() == ir.OADDR {
587 v.budget += 1 // undo half of default cost of ir.ODEREF+ir.OADDR
591 // This doesn't produce code, but the children might.
592 v.budget++ // undo default cost
594 case ir.ODCLCONST, ir.OFALL:
595 // These nodes don't produce code; omit from inlining budget.
600 if ir.IsConst(n.Cond, constant.Bool) {
601 // This if and the condition cost nothing.
602 if doList(n.Init(), v.do) {
605 if ir.BoolVal(n.Cond) {
606 return doList(n.Body, v.do)
608 return doList(n.Else, v.do)
614 if n.Class == ir.PAUTO {
619 // The only OBLOCK we should see at this point is an empty one.
620 // In any event, let the visitList(n.List()) below take care of the statements,
621 // and don't charge for the OBLOCK itself. The ++ undoes the -- below.
624 case ir.OMETHVALUE, ir.OSLICELIT:
625 v.budget-- // Hack for toolstash -cmp.
628 v.budget++ // Hack for toolstash -cmp.
631 n := n.(*ir.AssignListStmt)
633 // Unified IR unconditionally rewrites:
644 // so that it can insert implicit conversions as necessary. To
645 // minimize impact to the existing inlining heuristics (in
646 // particular, to avoid breaking the existing inlinability regress
647 // tests), we need to compensate for this here.
648 if init := n.Rhs[0].Init(); len(init) == 1 {
649 if _, ok := init[0].(*ir.AssignListStmt); ok {
650 // 4 for each value, because each temporary variable now
651 // appears 3 times (DCL, LHS, RHS), plus an extra DCL node.
653 // 1 for the extra "tmp1, tmp2 = f()" assignment statement.
654 v.budget += 4*int32(len(n.Lhs)) + 1
659 // Special case for coverage counter updates and coverage
660 // function registrations. Although these correspond to real
661 // operations, we treat them as zero cost for the moment. This
662 // is primarily due to the existence of tests that are
663 // sensitive to inlining-- if the insertion of coverage
664 // instrumentation happens to tip a given function over the
665 // threshold and move it from "inlinable" to "not-inlinable",
666 // this can cause changes in allocation behavior, which can
667 // then result in test failures (a good example is the
668 // TestAllocations in crypto/ed25519).
669 n := n.(*ir.AssignStmt)
670 if n.X.Op() == ir.OINDEX && isIndexingCoverageCounter(n.X) {
677 // When debugging, don't stop early, to get full cost of inlining this function
678 if v.budget < 0 && base.Flag.LowerM < 2 && !logopt.Enabled() {
679 v.reason = "too expensive"
683 return ir.DoChildren(n, v.do)
686 func isBigFunc(fn *ir.Func) bool {
687 budget := inlineBigFunctionNodes
688 return ir.Any(fn, func(n ir.Node) bool {
694 // inlcopylist (together with inlcopy) recursively copies a list of nodes, except
695 // that it keeps the same ONAME, OTYPE, and OLITERAL nodes. It is used for copying
696 // the body and dcls of an inlineable function.
697 func inlcopylist(ll []ir.Node) []ir.Node {
698 s := make([]ir.Node, len(ll))
699 for i, n := range ll {
705 // inlcopy is like DeepCopy(), but does extra work to copy closures.
706 func inlcopy(n ir.Node) ir.Node {
707 var edit func(ir.Node) ir.Node
708 edit = func(x ir.Node) ir.Node {
710 case ir.ONAME, ir.OTYPE, ir.OLITERAL, ir.ONIL:
714 ir.EditChildren(m, edit)
715 if x.Op() == ir.OCLOSURE {
716 x := x.(*ir.ClosureExpr)
717 // Need to save/duplicate x.Func.Nname,
718 // x.Func.Nname.Ntype, x.Func.Dcl, x.Func.ClosureVars, and
719 // x.Func.Body for iexport and local inlining.
721 newfn := ir.NewFunc(oldfn.Pos())
722 m.(*ir.ClosureExpr).Func = newfn
723 newfn.Nname = ir.NewNameAt(oldfn.Nname.Pos(), oldfn.Nname.Sym())
724 // XXX OK to share fn.Type() ??
725 newfn.Nname.SetType(oldfn.Nname.Type())
726 newfn.Body = inlcopylist(oldfn.Body)
727 // Make shallow copy of the Dcl and ClosureVar slices
728 newfn.Dcl = append([]*ir.Name(nil), oldfn.Dcl...)
729 newfn.ClosureVars = append([]*ir.Name(nil), oldfn.ClosureVars...)
736 // InlineCalls/inlnode walks fn's statements and expressions and substitutes any
737 // calls made to inlineable functions. This is the external entry point.
738 func InlineCalls(fn *ir.Func, profile *pgo.Profile) {
741 maxCost := int32(inlineMaxBudget)
743 if base.Flag.LowerM > 1 {
744 fmt.Printf("%v: function %v considered 'big'; revising maxCost from %d to %d\n", ir.Line(fn), fn, maxCost, inlineBigFunctionMaxCost)
746 maxCost = inlineBigFunctionMaxCost
748 var inlCalls []*ir.InlinedCallExpr
749 var edit func(ir.Node) ir.Node
750 edit = func(n ir.Node) ir.Node {
751 return inlnode(n, maxCost, &inlCalls, edit, profile)
753 ir.EditChildren(fn, edit)
755 // If we inlined any calls, we want to recursively visit their
756 // bodies for further inlining. However, we need to wait until
757 // *after* the original function body has been expanded, or else
758 // inlCallee can have false positives (e.g., #54632).
759 for len(inlCalls) > 0 {
761 inlCalls = inlCalls[1:]
762 ir.EditChildren(call, edit)
768 // inlnode recurses over the tree to find inlineable calls, which will
769 // be turned into OINLCALLs by mkinlcall. When the recursion comes
770 // back up will examine left, right, list, rlist, ninit, ntest, nincr,
771 // nbody and nelse and use one of the 4 inlconv/glue functions above
772 // to turn the OINLCALL into an expression, a statement, or patch it
773 // in to this nodes list or rlist as appropriate.
774 // NOTE it makes no sense to pass the glue functions down the
775 // recursion to the level where the OINLCALL gets created because they
776 // have to edit /this/ n, so you'd have to push that one down as well,
777 // but then you may as well do it here. so this is cleaner and
778 // shorter and less complicated.
779 // The result of inlnode MUST be assigned back to n, e.g.
781 // n.Left = inlnode(n.Left)
782 func inlnode(n ir.Node, maxCost int32, inlCalls *[]*ir.InlinedCallExpr, edit func(ir.Node) ir.Node, profile *pgo.Profile) ir.Node {
788 case ir.ODEFER, ir.OGO:
789 n := n.(*ir.GoDeferStmt)
790 switch call := n.Call; call.Op() {
792 base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
794 call := call.(*ir.CallExpr)
798 n := n.(*ir.TailCallStmt)
799 n.Call.NoInline = true // Not inline a tail call for now. Maybe we could inline it just like RETURN fn(arg)?
801 // TODO do them here (or earlier),
802 // so escape analysis can avoid more heapmoves.
806 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
808 n := n.(*ir.CallExpr)
809 if n.X.Op() == ir.OMETHEXPR {
810 // Prevent inlining some reflect.Value methods when using checkptr,
811 // even when package reflect was compiled without it (#35073).
812 if meth := ir.MethodExprName(n.X); meth != nil {
814 if base.Debug.Checkptr != 0 && types.IsReflectPkg(s.Pkg) && (s.Name == "Value.UnsafeAddr" || s.Name == "Value.Pointer") {
823 ir.EditChildren(n, edit)
825 // with all the branches out of the way, it is now time to
826 // transmogrify this node itself unless inhibited by the
827 // switch at the top of this function.
830 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
833 call := n.(*ir.CallExpr)
837 if base.Flag.LowerM > 3 {
838 fmt.Printf("%v:call to func %+v\n", ir.Line(n), call.X)
840 if ir.IsIntrinsicCall(call) {
843 if fn := inlCallee(call.X, profile); fn != nil && typecheck.HaveInlineBody(fn) {
844 n = mkinlcall(call, fn, maxCost, inlCalls, edit)
853 // inlCallee takes a function-typed expression and returns the underlying function ONAME
854 // that it refers to if statically known. Otherwise, it returns nil.
855 func inlCallee(fn ir.Node, profile *pgo.Profile) *ir.Func {
856 fn = ir.StaticValue(fn)
859 fn := fn.(*ir.SelectorExpr)
860 n := ir.MethodExprName(fn)
861 // Check that receiver type matches fn.X.
862 // TODO(mdempsky): Handle implicit dereference
863 // of pointer receiver argument?
864 if n == nil || !types.Identical(n.Type().Recv().Type, fn.X.Type()) {
870 if fn.Class == ir.PFUNC {
874 fn := fn.(*ir.ClosureExpr)
876 CanInline(c, profile)
882 func inlParam(t *types.Field, as ir.InitNode, inlvars map[*ir.Name]*ir.Name) ir.Node {
886 n := t.Nname.(*ir.Name)
892 base.Fatalf("missing inlvar for %v", n)
894 as.PtrInit().Append(ir.NewDecl(base.Pos, ir.ODCL, inlvar))
895 inlvar.Name().Defn = as
901 // SSADumpInline gives the SSA back end a chance to dump the function
902 // when producing output for debugging the compiler itself.
903 var SSADumpInline = func(*ir.Func) {}
905 // InlineCall allows the inliner implementation to be overridden.
906 // If it returns nil, the function will not be inlined.
907 var InlineCall = oldInlineCall
909 // If n is a OCALLFUNC node, and fn is an ONAME node for a
910 // function with an inlinable body, return an OINLCALL node that can replace n.
911 // The returned node's Ninit has the parameter assignments, the Nbody is the
912 // inlined function body, and (List, Rlist) contain the (input, output)
914 // The result of mkinlcall MUST be assigned back to n, e.g.
916 // n.Left = mkinlcall(n.Left, fn, isddd)
917 func mkinlcall(n *ir.CallExpr, fn *ir.Func, maxCost int32, inlCalls *[]*ir.InlinedCallExpr, edit func(ir.Node) ir.Node) ir.Node {
919 if logopt.Enabled() {
920 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
921 fmt.Sprintf("%s cannot be inlined", ir.PkgFuncName(fn)))
925 if fn.Inl.Cost > maxCost {
926 // If the callsite is hot and it is under the inlineHotMaxBudget budget, then try to inline it, or else bail.
927 lineOffset := pgo.NodeLineOffset(n, ir.CurFunc)
928 csi := pgo.CallSiteInfo{LineOffset: lineOffset, Caller: ir.CurFunc}
929 if _, ok := candHotEdgeMap[csi]; ok {
930 if fn.Inl.Cost > inlineHotMaxBudget {
931 if logopt.Enabled() {
932 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
933 fmt.Sprintf("cost %d of %s exceeds max large caller cost %d", fn.Inl.Cost, ir.PkgFuncName(fn), inlineHotMaxBudget))
937 if base.Debug.PGOInline > 0 {
938 fmt.Printf("hot-budget check allows inlining for call %s at %v\n", ir.PkgFuncName(fn), ir.Line(n))
941 // The inlined function body is too big. Typically we use this check to restrict
942 // inlining into very big functions. See issue 26546 and 17566.
943 if logopt.Enabled() {
944 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
945 fmt.Sprintf("cost %d of %s exceeds max large caller cost %d", fn.Inl.Cost, ir.PkgFuncName(fn), maxCost))
951 if fn == ir.CurFunc {
952 // Can't recursively inline a function into itself.
953 if logopt.Enabled() {
954 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", fmt.Sprintf("recursive call to %s", ir.FuncName(ir.CurFunc)))
959 if base.Flag.Cfg.Instrumenting && types.IsRuntimePkg(fn.Sym().Pkg) {
960 // Runtime package must not be instrumented.
961 // Instrument skips runtime package. However, some runtime code can be
962 // inlined into other packages and instrumented there. To avoid this,
963 // we disable inlining of runtime functions when instrumenting.
964 // The example that we observed is inlining of LockOSThread,
965 // which lead to false race reports on m contents.
969 parent := base.Ctxt.PosTable.Pos(n.Pos()).Base().InliningIndex()
972 // Check if we've already inlined this function at this particular
973 // call site, in order to stop inlining when we reach the beginning
974 // of a recursion cycle again. We don't inline immediately recursive
975 // functions, but allow inlining if there is a recursion cycle of
976 // many functions. Most likely, the inlining will stop before we
977 // even hit the beginning of the cycle again, but this catches the
979 for inlIndex := parent; inlIndex >= 0; inlIndex = base.Ctxt.InlTree.Parent(inlIndex) {
980 if base.Ctxt.InlTree.InlinedFunction(inlIndex) == sym {
981 if base.Flag.LowerM > 1 {
982 fmt.Printf("%v: cannot inline %v into %v: repeated recursive cycle\n", ir.Line(n), fn, ir.FuncName(ir.CurFunc))
988 typecheck.FixVariadicCall(n)
990 inlIndex := base.Ctxt.InlTree.Add(parent, n.Pos(), sym)
992 closureInitLSym := func(n *ir.CallExpr, fn *ir.Func) {
993 // The linker needs FuncInfo metadata for all inlined
994 // functions. This is typically handled by gc.enqueueFunc
995 // calling ir.InitLSym for all function declarations in
996 // typecheck.Target.Decls (ir.UseClosure adds all closures to
999 // However, non-trivial closures in Decls are ignored, and are
1000 // insteaded enqueued when walk of the calling function
1003 // This presents a problem for direct calls to closures.
1004 // Inlining will replace the entire closure definition with its
1005 // body, which hides the closure from walk and thus suppresses
1008 // Explicitly create a symbol early in this edge case to ensure
1009 // we keep this metadata.
1011 // TODO: Refactor to keep a reference so this can all be done
1014 if n.Op() != ir.OCALLFUNC {
1015 // Not a standard call.
1018 if n.X.Op() != ir.OCLOSURE {
1019 // Not a direct closure call.
1023 clo := n.X.(*ir.ClosureExpr)
1024 if ir.IsTrivialClosure(clo) {
1025 // enqueueFunc will handle trivial closures anyways.
1029 ir.InitLSym(fn, true)
1032 closureInitLSym(n, fn)
1034 if base.Flag.GenDwarfInl > 0 {
1035 if !sym.WasInlined() {
1036 base.Ctxt.DwFixups.SetPrecursorFunc(sym, fn)
1037 sym.Set(obj.AttrWasInlined, true)
1041 if base.Flag.LowerM != 0 {
1042 fmt.Printf("%v: inlining call to %v\n", ir.Line(n), fn)
1044 if base.Flag.LowerM > 2 {
1045 fmt.Printf("%v: Before inlining: %+v\n", ir.Line(n), n)
1048 if base.Debug.PGOInline > 0 {
1049 csi := pgo.CallSiteInfo{LineOffset: pgo.NodeLineOffset(n, fn), Caller: ir.CurFunc}
1050 if _, ok := inlinedCallSites[csi]; !ok {
1051 inlinedCallSites[csi] = struct{}{}
1055 res := InlineCall(n, fn, inlIndex)
1058 base.FatalfAt(n.Pos(), "inlining call to %v failed", fn)
1061 if base.Flag.LowerM > 2 {
1062 fmt.Printf("%v: After inlining %+v\n\n", ir.Line(res), res)
1065 *inlCalls = append(*inlCalls, res)
1070 // CalleeEffects appends any side effects from evaluating callee to init.
1071 func CalleeEffects(init *ir.Nodes, callee ir.Node) {
1073 init.Append(ir.TakeInit(callee)...)
1075 switch callee.Op() {
1076 case ir.ONAME, ir.OCLOSURE, ir.OMETHEXPR:
1080 conv := callee.(*ir.ConvExpr)
1084 ic := callee.(*ir.InlinedCallExpr)
1085 init.Append(ic.Body.Take()...)
1086 callee = ic.SingleResult()
1089 base.FatalfAt(callee.Pos(), "unexpected callee expression: %v", callee)
1094 // oldInlineCall creates an InlinedCallExpr to replace the given call
1095 // expression. fn is the callee function to be inlined. inlIndex is
1096 // the inlining tree position index, for use with src.NewInliningBase
1097 // when rewriting positions.
1098 func oldInlineCall(call *ir.CallExpr, fn *ir.Func, inlIndex int) *ir.InlinedCallExpr {
1101 ninit := call.Init()
1103 // For normal function calls, the function callee expression
1104 // may contain side effects. Make sure to preserve these,
1105 // if necessary (#42703).
1106 if call.Op() == ir.OCALLFUNC {
1107 CalleeEffects(&ninit, call.X)
1110 // Make temp names to use instead of the originals.
1111 inlvars := make(map[*ir.Name]*ir.Name)
1113 // record formals/locals for later post-processing
1114 var inlfvars []*ir.Name
1116 for _, ln := range fn.Inl.Dcl {
1117 if ln.Op() != ir.ONAME {
1120 if ln.Class == ir.PPARAMOUT { // return values handled below.
1123 inlf := typecheck.Expr(inlvar(ln)).(*ir.Name)
1125 if base.Flag.GenDwarfInl > 0 {
1126 if ln.Class == ir.PPARAM {
1127 inlf.Name().SetInlFormal(true)
1129 inlf.Name().SetInlLocal(true)
1131 inlf.SetPos(ln.Pos())
1132 inlfvars = append(inlfvars, inlf)
1136 // We can delay declaring+initializing result parameters if:
1137 // temporaries for return values.
1138 var retvars []ir.Node
1139 for i, t := range fn.Type().Results().Fields().Slice() {
1141 if nn := t.Nname; nn != nil && !ir.IsBlank(nn.(*ir.Name)) && !strings.HasPrefix(nn.Sym().Name, "~r") {
1144 m = typecheck.Expr(m).(*ir.Name)
1147 // anonymous return values, synthesize names for use in assignment that replaces return
1151 if base.Flag.GenDwarfInl > 0 {
1152 // Don't update the src.Pos on a return variable if it
1153 // was manufactured by the inliner (e.g. "~R2"); such vars
1154 // were not part of the original callee.
1155 if !strings.HasPrefix(m.Sym().Name, "~R") {
1156 m.Name().SetInlFormal(true)
1158 inlfvars = append(inlfvars, m)
1162 retvars = append(retvars, m)
1165 // Assign arguments to the parameters' temp names.
1166 as := ir.NewAssignListStmt(base.Pos, ir.OAS2, nil, nil)
1168 if call.Op() == ir.OCALLMETH {
1169 base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
1171 as.Rhs.Append(call.Args...)
1173 if recv := fn.Type().Recv(); recv != nil {
1174 as.Lhs.Append(inlParam(recv, as, inlvars))
1176 for _, param := range fn.Type().Params().Fields().Slice() {
1177 as.Lhs.Append(inlParam(param, as, inlvars))
1180 if len(as.Rhs) != 0 {
1181 ninit.Append(typecheck.Stmt(as))
1184 if !fn.Inl.CanDelayResults {
1185 // Zero the return parameters.
1186 for _, n := range retvars {
1187 ninit.Append(ir.NewDecl(base.Pos, ir.ODCL, n.(*ir.Name)))
1188 ras := ir.NewAssignStmt(base.Pos, n, nil)
1189 ninit.Append(typecheck.Stmt(ras))
1193 retlabel := typecheck.AutoLabel(".i")
1197 // Add an inline mark just before the inlined body.
1198 // This mark is inline in the code so that it's a reasonable spot
1199 // to put a breakpoint. Not sure if that's really necessary or not
1200 // (in which case it could go at the end of the function instead).
1201 // Note issue 28603.
1202 ninit.Append(ir.NewInlineMarkStmt(call.Pos().WithIsStmt(), int64(inlIndex)))
1208 defnMarker: ir.NilExpr{},
1209 bases: make(map[*src.PosBase]*src.PosBase),
1210 newInlIndex: inlIndex,
1213 subst.edit = subst.node
1215 body := subst.list(ir.Nodes(fn.Inl.Body))
1217 lab := ir.NewLabelStmt(base.Pos, retlabel)
1218 body = append(body, lab)
1220 if base.Flag.GenDwarfInl > 0 {
1221 for _, v := range inlfvars {
1222 v.SetPos(subst.updatedPos(v.Pos()))
1226 //dumplist("ninit post", ninit);
1228 res := ir.NewInlinedCallExpr(base.Pos, body, retvars)
1230 res.SetType(call.Type())
1235 // Every time we expand a function we generate a new set of tmpnames,
1236 // PAUTO's in the calling functions, and link them off of the
1237 // PPARAM's, PAUTOS and PPARAMOUTs of the called function.
1238 func inlvar(var_ *ir.Name) *ir.Name {
1239 if base.Flag.LowerM > 3 {
1240 fmt.Printf("inlvar %+v\n", var_)
1243 n := typecheck.NewName(var_.Sym())
1244 n.SetType(var_.Type())
1248 n.SetAutoTemp(var_.AutoTemp())
1249 n.Curfn = ir.CurFunc // the calling function, not the called one
1250 n.SetAddrtaken(var_.Addrtaken())
1252 ir.CurFunc.Dcl = append(ir.CurFunc.Dcl, n)
1256 // Synthesize a variable to store the inlined function's results in.
1257 func retvar(t *types.Field, i int) *ir.Name {
1258 n := typecheck.NewName(typecheck.LookupNum("~R", i))
1263 n.Curfn = ir.CurFunc // the calling function, not the called one
1264 ir.CurFunc.Dcl = append(ir.CurFunc.Dcl, n)
1268 // The inlsubst type implements the actual inlining of a single
1270 type inlsubst struct {
1271 // Target of the goto substituted in place of a return.
1274 // Temporary result variables.
1277 inlvars map[*ir.Name]*ir.Name
1278 // defnMarker is used to mark a Node for reassignment.
1279 // inlsubst.clovar set this during creating new ONAME.
1280 // inlsubst.node will set the correct Defn for inlvar.
1281 defnMarker ir.NilExpr
1283 // bases maps from original PosBase to PosBase with an extra
1284 // inlined call frame.
1285 bases map[*src.PosBase]*src.PosBase
1287 // newInlIndex is the index of the inlined call frame to
1288 // insert for inlined nodes.
1291 edit func(ir.Node) ir.Node // cached copy of subst.node method value closure
1293 // If non-nil, we are inside a closure inside the inlined function, and
1294 // newclofn is the Func of the new inlined closure.
1297 fn *ir.Func // For debug -- the func that is being inlined
1299 // If true, then don't update source positions during substitution
1300 // (retain old source positions).
1304 // list inlines a list of nodes.
1305 func (subst *inlsubst) list(ll ir.Nodes) []ir.Node {
1306 s := make([]ir.Node, 0, len(ll))
1307 for _, n := range ll {
1308 s = append(s, subst.node(n))
1313 // fields returns a list of the fields of a struct type representing receiver,
1314 // params, or results, after duplicating the field nodes and substituting the
1315 // Nname nodes inside the field nodes.
1316 func (subst *inlsubst) fields(oldt *types.Type) []*types.Field {
1317 oldfields := oldt.FieldSlice()
1318 newfields := make([]*types.Field, len(oldfields))
1319 for i := range oldfields {
1320 newfields[i] = oldfields[i].Copy()
1321 if oldfields[i].Nname != nil {
1322 newfields[i].Nname = subst.node(oldfields[i].Nname.(*ir.Name))
1328 // clovar creates a new ONAME node for a local variable or param of a closure
1329 // inside a function being inlined.
1330 func (subst *inlsubst) clovar(n *ir.Name) *ir.Name {
1331 m := ir.NewNameAt(n.Pos(), n.Sym())
1335 if n.IsClosureVar() {
1336 m.SetIsClosureVar(true)
1339 m.SetAddrtaken(true)
1346 m.Curfn = subst.newclofn
1348 switch defn := n.Defn.(type) {
1352 if !n.IsClosureVar() {
1353 base.FatalfAt(n.Pos(), "want closure variable, got: %+v", n)
1355 if n.Sym().Pkg != types.LocalPkg {
1356 // If the closure came from inlining a function from
1357 // another package, must change package of captured
1358 // variable to localpkg, so that the fields of the closure
1359 // struct are local package and can be accessed even if
1360 // name is not exported. If you disable this code, you can
1361 // reproduce the problem by running 'go test
1362 // go/internal/srcimporter'. TODO(mdempsky) - maybe change
1363 // how we create closure structs?
1364 m.SetSym(types.LocalPkg.Lookup(n.Sym().Name))
1366 // Make sure any inlvar which is the Defn
1367 // of an ONAME closure var is rewritten
1368 // during inlining. Don't substitute
1369 // if Defn node is outside inlined function.
1370 if subst.inlvars[n.Defn.(*ir.Name)] != nil {
1371 m.Defn = subst.node(n.Defn)
1373 case *ir.AssignStmt, *ir.AssignListStmt:
1374 // Mark node for reassignment at the end of inlsubst.node.
1375 m.Defn = &subst.defnMarker
1376 case *ir.TypeSwitchGuard:
1377 // TODO(mdempsky): Set m.Defn properly. See discussion on #45743.
1379 // TODO: Set m.Defn properly if we support inlining range statement in the future.
1381 base.FatalfAt(n.Pos(), "unexpected Defn: %+v", defn)
1385 // Either the outer variable is defined in function being inlined,
1386 // and we will replace it with the substituted variable, or it is
1387 // defined outside the function being inlined, and we should just
1388 // skip the outer variable (the closure variable of the function
1390 s := subst.node(n.Outer).(*ir.Name)
1399 // closure does the necessary substitutions for a ClosureExpr n and returns the new
1401 func (subst *inlsubst) closure(n *ir.ClosureExpr) ir.Node {
1402 // Prior to the subst edit, set a flag in the inlsubst to indicate
1403 // that we don't want to update the source positions in the new
1404 // closure function. If we do this, it will appear that the
1405 // closure itself has things inlined into it, which is not the
1406 // case. See issue #46234 for more details. At the same time, we
1407 // do want to update the position in the new ClosureExpr (which is
1408 // part of the function we're working on). See #49171 for an
1409 // example of what happens if we miss that update.
1410 newClosurePos := subst.updatedPos(n.Pos())
1411 defer func(prev bool) { subst.noPosUpdate = prev }(subst.noPosUpdate)
1412 subst.noPosUpdate = true
1414 //fmt.Printf("Inlining func %v with closure into %v\n", subst.fn, ir.FuncName(ir.CurFunc))
1417 newfn := ir.NewClosureFunc(oldfn.Pos(), true)
1419 if subst.newclofn != nil {
1420 //fmt.Printf("Inlining a closure with a nested closure\n")
1422 prevxfunc := subst.newclofn
1424 // Mark that we are now substituting within a closure (within the
1425 // inlined function), and create new nodes for all the local
1426 // vars/params inside this closure.
1427 subst.newclofn = newfn
1429 newfn.ClosureVars = nil
1430 for _, oldv := range oldfn.Dcl {
1431 newv := subst.clovar(oldv)
1432 subst.inlvars[oldv] = newv
1433 newfn.Dcl = append(newfn.Dcl, newv)
1435 for _, oldv := range oldfn.ClosureVars {
1436 newv := subst.clovar(oldv)
1437 subst.inlvars[oldv] = newv
1438 newfn.ClosureVars = append(newfn.ClosureVars, newv)
1441 // Need to replace ONAME nodes in
1442 // newfn.Type().FuncType().Receiver/Params/Results.FieldSlice().Nname
1443 oldt := oldfn.Type()
1444 newrecvs := subst.fields(oldt.Recvs())
1445 var newrecv *types.Field
1446 if len(newrecvs) > 0 {
1447 newrecv = newrecvs[0]
1449 newt := types.NewSignature(oldt.Pkg(), newrecv,
1450 nil, subst.fields(oldt.Params()), subst.fields(oldt.Results()))
1452 newfn.Nname.SetType(newt)
1453 newfn.Body = subst.list(oldfn.Body)
1455 // Remove the nodes for the current closure from subst.inlvars
1456 for _, oldv := range oldfn.Dcl {
1457 delete(subst.inlvars, oldv)
1459 for _, oldv := range oldfn.ClosureVars {
1460 delete(subst.inlvars, oldv)
1462 // Go back to previous closure func
1463 subst.newclofn = prevxfunc
1465 // Actually create the named function for the closure, now that
1466 // the closure is inlined in a specific function.
1467 newclo := newfn.OClosure
1468 newclo.SetPos(newClosurePos)
1469 newclo.SetInit(subst.list(n.Init()))
1470 return typecheck.Expr(newclo)
1473 // node recursively copies a node from the saved pristine body of the
1474 // inlined function, substituting references to input/output
1475 // parameters with ones to the tmpnames, and substituting returns with
1476 // assignments to the output.
1477 func (subst *inlsubst) node(n ir.Node) ir.Node {
1486 // Handle captured variables when inlining closures.
1487 if n.IsClosureVar() && subst.newclofn == nil {
1490 // Deal with case where sequence of closures are inlined.
1491 // TODO(danscales) - write test case to see if we need to
1492 // go up multiple levels.
1493 if o.Curfn != ir.CurFunc {
1497 // make sure the outer param matches the inlining location
1498 if o == nil || o.Curfn != ir.CurFunc {
1499 base.Fatalf("%v: unresolvable capture %v\n", ir.Line(n), n)
1502 if base.Flag.LowerM > 2 {
1503 fmt.Printf("substituting captured name %+v -> %+v\n", n, o)
1508 if inlvar := subst.inlvars[n]; inlvar != nil { // These will be set during inlnode
1509 if base.Flag.LowerM > 2 {
1510 fmt.Printf("substituting name %+v -> %+v\n", n, inlvar)
1515 if base.Flag.LowerM > 2 {
1516 fmt.Printf("not substituting name %+v\n", n)
1521 n := n.(*ir.SelectorExpr)
1524 case ir.OLITERAL, ir.ONIL, ir.OTYPE:
1525 // If n is a named constant or type, we can continue
1526 // using it in the inline copy. Otherwise, make a copy
1527 // so we can update the line number.
1533 if subst.newclofn != nil {
1534 // Don't do special substitutions if inside a closure
1537 // Because of the above test for subst.newclofn,
1538 // this return is guaranteed to belong to the current inlined function.
1539 n := n.(*ir.ReturnStmt)
1540 init := subst.list(n.Init())
1541 if len(subst.retvars) != 0 && len(n.Results) != 0 {
1542 as := ir.NewAssignListStmt(base.Pos, ir.OAS2, nil, nil)
1544 // Make a shallow copy of retvars.
1545 // Otherwise OINLCALL.Rlist will be the same list,
1546 // and later walk and typecheck may clobber it.
1547 for _, n := range subst.retvars {
1550 as.Rhs = subst.list(n.Results)
1552 if subst.fn.Inl.CanDelayResults {
1553 for _, n := range as.Lhs {
1554 as.PtrInit().Append(ir.NewDecl(base.Pos, ir.ODCL, n.(*ir.Name)))
1559 init = append(init, typecheck.Stmt(as))
1561 init = append(init, ir.NewBranchStmt(base.Pos, ir.OGOTO, subst.retlabel))
1562 typecheck.Stmts(init)
1563 return ir.NewBlockStmt(base.Pos, init)
1565 case ir.OGOTO, ir.OBREAK, ir.OCONTINUE:
1566 if subst.newclofn != nil {
1567 // Don't do special substitutions if inside a closure
1570 n := n.(*ir.BranchStmt)
1571 m := ir.Copy(n).(*ir.BranchStmt)
1572 m.SetPos(subst.updatedPos(m.Pos()))
1574 m.Label = translateLabel(n.Label)
1578 if subst.newclofn != nil {
1579 // Don't do special substitutions if inside a closure
1582 n := n.(*ir.LabelStmt)
1583 m := ir.Copy(n).(*ir.LabelStmt)
1584 m.SetPos(subst.updatedPos(m.Pos()))
1586 m.Label = translateLabel(n.Label)
1590 return subst.closure(n.(*ir.ClosureExpr))
1595 m.SetPos(subst.updatedPos(m.Pos()))
1596 ir.EditChildren(m, subst.edit)
1598 if subst.newclofn == nil {
1599 // Translate any label on FOR, RANGE loops, SWITCH or SELECT
1602 m := m.(*ir.ForStmt)
1603 m.Label = translateLabel(m.Label)
1607 m := m.(*ir.RangeStmt)
1608 m.Label = translateLabel(m.Label)
1612 m := m.(*ir.SwitchStmt)
1613 m.Label = translateLabel(m.Label)
1617 m := m.(*ir.SelectStmt)
1618 m.Label = translateLabel(m.Label)
1623 switch m := m.(type) {
1624 case *ir.AssignStmt:
1625 if lhs, ok := m.X.(*ir.Name); ok && lhs.Defn == &subst.defnMarker {
1628 case *ir.AssignListStmt:
1629 for _, lhs := range m.Lhs {
1630 if lhs, ok := lhs.(*ir.Name); ok && lhs.Defn == &subst.defnMarker {
1639 // translateLabel makes a label from an inlined function (if non-nil) be unique by
1640 // adding "·inlgen".
1641 func translateLabel(l *types.Sym) *types.Sym {
1645 p := fmt.Sprintf("%s·%d", l.Name, inlgen)
1646 return typecheck.Lookup(p)
1649 func (subst *inlsubst) updatedPos(xpos src.XPos) src.XPos {
1650 if subst.noPosUpdate {
1653 pos := base.Ctxt.PosTable.Pos(xpos)
1654 oldbase := pos.Base() // can be nil
1655 newbase := subst.bases[oldbase]
1657 newbase = src.NewInliningBase(oldbase, subst.newInlIndex)
1658 subst.bases[oldbase] = newbase
1660 pos.SetBase(newbase)
1661 return base.Ctxt.PosTable.XPos(pos)
1664 func pruneUnusedAutos(ll []*ir.Name, vis *hairyVisitor) []*ir.Name {
1665 s := make([]*ir.Name, 0, len(ll))
1666 for _, n := range ll {
1667 if n.Class == ir.PAUTO {
1668 if !vis.usedLocals.Has(n) {
1677 // numNonClosures returns the number of functions in list which are not closures.
1678 func numNonClosures(list []*ir.Func) int {
1680 for _, fn := range list {
1681 if fn.OClosure == nil {
1688 func doList(list []ir.Node, do func(ir.Node) bool) bool {
1689 for _, x := range list {
1699 // isIndexingCoverageCounter returns true if the specified node 'n' is indexing
1700 // into a coverage counter array.
1701 func isIndexingCoverageCounter(n ir.Node) bool {
1702 if n.Op() != ir.OINDEX {
1705 ixn := n.(*ir.IndexExpr)
1706 if ixn.X.Op() != ir.ONAME || !ixn.X.Type().IsArray() {
1709 nn := ixn.X.(*ir.Name)
1710 return nn.CoverageCounter()
1713 // isAtomicCoverageCounterUpdate examines the specified node to
1714 // determine whether it represents a call to sync/atomic.AddUint32 to
1715 // increment a coverage counter.
1716 func isAtomicCoverageCounterUpdate(cn *ir.CallExpr) bool {
1717 if cn.X.Op() != ir.ONAME {
1720 name := cn.X.(*ir.Name)
1721 if name.Class != ir.PFUNC {
1724 fn := name.Sym().Name
1725 if name.Sym().Pkg.Path != "sync/atomic" ||
1726 (fn != "AddUint32" && fn != "StoreUint32") {
1729 if len(cn.Args) != 2 || cn.Args[0].Op() != ir.OADDR {
1732 adn := cn.Args[0].(*ir.AddrExpr)
1733 v := isIndexingCoverageCounter(adn.X)