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"
44 // Inlining budget parameters, gathered in one place
47 inlineExtraAppendCost = 0
48 // default is to inline if there's at most one call. -l=4 overrides this by using 1 instead.
49 inlineExtraCallCost = 57 // 57 was benchmarked to provided most benefit with no bad surprises; see https://github.com/golang/go/issues/19348#issuecomment-439370742
50 inlineExtraPanicCost = 1 // do not penalize inlining panics.
51 inlineExtraThrowCost = inlineMaxBudget // with current (2018-05/1.11) code, inlining runtime.throw does not help.
53 inlineBigFunctionNodes = 5000 // Functions with this many nodes are considered "big".
54 inlineBigFunctionMaxCost = 20 // Max cost of inlinee when inlining into a "big" function.
58 // List of all hot callee nodes.
59 // TODO(prattmic): Make this non-global.
60 candHotCalleeMap = make(map[*pgo.IRNode]struct{})
62 // List of all hot call sites. CallSiteInfo.Callee is always nil.
63 // TODO(prattmic): Make this non-global.
64 candHotEdgeMap = make(map[pgo.CallSiteInfo]struct{})
66 // Threshold in percentage for hot callsite inlining.
67 inlineHotCallSiteThresholdPercent float64
69 // Threshold in CDF percentage for hot callsite inlining,
70 // that is, for a threshold of X the hottest callsites that
71 // make up the top X% of total edge weight will be
72 // considered hot for inlining candidates.
73 inlineCDFHotCallSiteThresholdPercent = float64(99)
75 // Budget increased due to hotness.
76 inlineHotMaxBudget int32 = 2000
79 // pgoInlinePrologue records the hot callsites from ir-graph.
80 func pgoInlinePrologue(p *pgo.Profile, decls []ir.Node) {
81 if base.Debug.PGOInlineCDFThreshold != "" {
82 if s, err := strconv.ParseFloat(base.Debug.PGOInlineCDFThreshold, 64); err == nil && s >= 0 && s <= 100 {
83 inlineCDFHotCallSiteThresholdPercent = s
85 base.Fatalf("invalid PGOInlineCDFThreshold, must be between 0 and 100")
88 var hotCallsites []pgo.NodeMapKey
89 inlineHotCallSiteThresholdPercent, hotCallsites = hotNodesFromCDF(p)
90 if base.Debug.PGODebug > 0 {
91 fmt.Printf("hot-callsite-thres-from-CDF=%v\n", inlineHotCallSiteThresholdPercent)
94 if x := base.Debug.PGOInlineBudget; x != 0 {
95 inlineHotMaxBudget = int32(x)
98 for _, n := range hotCallsites {
99 // mark inlineable callees from hot edges
100 if callee := p.WeightedCG.IRNodes[n.CalleeName]; callee != nil {
101 candHotCalleeMap[callee] = struct{}{}
103 // mark hot call sites
104 if caller := p.WeightedCG.IRNodes[n.CallerName]; caller != nil && caller.AST != nil {
105 csi := pgo.CallSiteInfo{LineOffset: n.CallSiteOffset, Caller: caller.AST}
106 candHotEdgeMap[csi] = struct{}{}
110 if base.Debug.PGODebug >= 3 {
111 fmt.Printf("hot-cg before inline in dot format:")
112 p.PrintWeightedCallGraphDOT(inlineHotCallSiteThresholdPercent)
116 // hotNodesFromCDF computes an edge weight threshold and the list of hot
117 // nodes that make up the given percentage of the CDF. The threshold, as
118 // a percent, is the lower bound of weight for nodes to be considered hot
119 // (currently only used in debug prints) (in case of equal weights,
120 // comparing with the threshold may not accurately reflect which nodes are
122 func hotNodesFromCDF(p *pgo.Profile) (float64, []pgo.NodeMapKey) {
123 nodes := make([]pgo.NodeMapKey, len(p.NodeMap))
125 for n := range p.NodeMap {
129 sort.Slice(nodes, func(i, j int) bool {
130 ni, nj := nodes[i], nodes[j]
131 if wi, wj := p.NodeMap[ni].EWeight, p.NodeMap[nj].EWeight; wi != wj {
132 return wi > wj // want larger weight first
134 // same weight, order by name/line number
135 if ni.CallerName != nj.CallerName {
136 return ni.CallerName < nj.CallerName
138 if ni.CalleeName != nj.CalleeName {
139 return ni.CalleeName < nj.CalleeName
141 return ni.CallSiteOffset < nj.CallSiteOffset
144 for i, n := range nodes {
145 w := p.NodeMap[n].EWeight
147 if pgo.WeightInPercentage(cum, p.TotalEdgeWeight) > inlineCDFHotCallSiteThresholdPercent {
148 // nodes[:i+1] to include the very last node that makes it to go over the threshold.
149 // (Say, if the CDF threshold is 50% and one hot node takes 60% of weight, we want to
150 // include that node instead of excluding it.)
151 return pgo.WeightInPercentage(w, p.TotalEdgeWeight), nodes[:i+1]
157 // InlinePackage finds functions that can be inlined and clones them before walk expands them.
158 func InlinePackage(p *pgo.Profile) {
159 if base.Debug.PGOInline == 0 {
163 InlineDecls(p, typecheck.Target.Decls, true)
165 // Perform a garbage collection of hidden closures functions that
166 // are no longer reachable from top-level functions following
167 // inlining. See #59404 and #59638 for more context.
168 garbageCollectUnreferencedHiddenClosures()
171 // InlineDecls applies inlining to the given batch of declarations.
172 func InlineDecls(p *pgo.Profile, decls []ir.Node, doInline bool) {
174 pgoInlinePrologue(p, decls)
177 doCanInline := func(n *ir.Func, recursive bool, numfns int) {
178 if !recursive || numfns > 1 {
179 // We allow inlining if there is no
180 // recursion, or the recursion cycle is
181 // across more than one function.
184 if base.Flag.LowerM > 1 && n.OClosure == nil {
185 fmt.Printf("%v: cannot inline %v: recursive\n", ir.Line(n), n.Nname)
190 ir.VisitFuncsBottomUp(decls, func(list []*ir.Func, recursive bool) {
191 numfns := numNonClosures(list)
192 // We visit functions within an SCC in fairly arbitrary order,
193 // so by computing inlinability for all functions in the SCC
194 // before performing any inlining, the results are less
195 // sensitive to the order within the SCC (see #58905 for an
198 // First compute inlinability for all functions in the SCC ...
199 for _, n := range list {
200 doCanInline(n, recursive, numfns)
202 // ... then make a second pass to do inlining of calls.
204 for _, n := range list {
211 // garbageCollectUnreferencedHiddenClosures makes a pass over all the
212 // top-level (non-hidden-closure) functions looking for nested closure
213 // functions that are reachable, then sweeps through the Target.Decls
214 // list and marks any non-reachable hidden closure function as dead.
215 // See issues #59404 and #59638 for more context.
216 func garbageCollectUnreferencedHiddenClosures() {
218 liveFuncs := make(map[*ir.Func]bool)
220 var markLiveFuncs func(fn *ir.Func)
221 markLiveFuncs = func(fn *ir.Func) {
226 ir.Visit(fn, func(n ir.Node) {
227 if clo, ok := n.(*ir.ClosureExpr); ok {
228 markLiveFuncs(clo.Func)
233 for i := 0; i < len(typecheck.Target.Decls); i++ {
234 if fn, ok := typecheck.Target.Decls[i].(*ir.Func); ok {
235 if fn.IsHiddenClosure() {
242 for i := 0; i < len(typecheck.Target.Decls); i++ {
243 if fn, ok := typecheck.Target.Decls[i].(*ir.Func); ok {
244 if !fn.IsHiddenClosure() {
247 if fn.IsDeadcodeClosure() {
253 fn.SetIsDeadcodeClosure(true)
254 if base.Flag.LowerM > 2 {
255 fmt.Printf("%v: unreferenced closure %v marked as dead\n", ir.Line(fn), fn)
257 if fn.Inl != nil && fn.LSym == nil {
258 ir.InitLSym(fn, true)
264 // CanInline determines whether fn is inlineable.
265 // If so, CanInline saves copies of fn.Body and fn.Dcl in fn.Inl.
266 // fn and fn.Body will already have been typechecked.
267 func CanInline(fn *ir.Func, profile *pgo.Profile) {
269 base.Fatalf("CanInline no nname %+v", fn)
272 var reason string // reason, if any, that the function was not inlined
273 if base.Flag.LowerM > 1 || logopt.Enabled() {
276 if base.Flag.LowerM > 1 {
277 fmt.Printf("%v: cannot inline %v: %s\n", ir.Line(fn), fn.Nname, reason)
279 if logopt.Enabled() {
280 logopt.LogOpt(fn.Pos(), "cannotInlineFunction", "inline", ir.FuncName(fn), reason)
286 reason = InlineImpossible(fn)
290 if fn.Typecheck() == 0 {
291 base.Fatalf("CanInline on non-typechecked function %v", fn)
295 if n.Func.InlinabilityChecked() {
298 defer n.Func.SetInlinabilityChecked(true)
300 cc := int32(inlineExtraCallCost)
301 if base.Flag.LowerL == 4 {
302 cc = 1 // this appears to yield better performance than 0.
305 // Update the budget for profile-guided inlining.
306 budget := int32(inlineMaxBudget)
308 if n, ok := profile.WeightedCG.IRNodes[ir.LinkFuncName(fn)]; ok {
309 if _, ok := candHotCalleeMap[n]; ok {
310 budget = int32(inlineHotMaxBudget)
311 if base.Debug.PGODebug > 0 {
312 fmt.Printf("hot-node enabled increased budget=%v for func=%v\n", budget, ir.PkgFuncName(fn))
318 // At this point in the game the function we're looking at may
319 // have "stale" autos, vars that still appear in the Dcl list, but
320 // which no longer have any uses in the function body (due to
321 // elimination by deadcode). We'd like to exclude these dead vars
322 // when creating the "Inline.Dcl" field below; to accomplish this,
323 // the hairyVisitor below builds up a map of used/referenced
324 // locals, and we use this map to produce a pruned Inline.Dcl
325 // list. See issue 25249 for more context.
327 visitor := hairyVisitor{
334 if visitor.tooHairy(fn) {
335 reason = visitor.reason
339 n.Func.Inl = &ir.Inline{
340 Cost: budget - visitor.budget,
341 Dcl: pruneUnusedAutos(n.Defn.(*ir.Func).Dcl, &visitor),
342 Body: inlcopylist(fn.Body),
344 CanDelayResults: canDelayResults(fn),
347 if base.Flag.LowerM > 1 {
348 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))
349 } else if base.Flag.LowerM != 0 {
350 fmt.Printf("%v: can inline %v\n", ir.Line(fn), n)
352 if logopt.Enabled() {
353 logopt.LogOpt(fn.Pos(), "canInlineFunction", "inline", ir.FuncName(fn), fmt.Sprintf("cost: %d", budget-visitor.budget))
357 // InlineImpossible returns a non-empty reason string if fn is impossible to
358 // inline regardless of cost or contents.
359 func InlineImpossible(fn *ir.Func) string {
360 var reason string // reason, if any, that the function can not be inlined.
366 // If marked "go:noinline", don't inline.
367 if fn.Pragma&ir.Noinline != 0 {
368 reason = "marked go:noinline"
372 // If marked "go:norace" and -race compilation, don't inline.
373 if base.Flag.Race && fn.Pragma&ir.Norace != 0 {
374 reason = "marked go:norace with -race compilation"
378 // If marked "go:nocheckptr" and -d checkptr compilation, don't inline.
379 if base.Debug.Checkptr != 0 && fn.Pragma&ir.NoCheckPtr != 0 {
380 reason = "marked go:nocheckptr"
384 // If marked "go:cgo_unsafe_args", don't inline, since the function
385 // makes assumptions about its argument frame layout.
386 if fn.Pragma&ir.CgoUnsafeArgs != 0 {
387 reason = "marked go:cgo_unsafe_args"
391 // If marked as "go:uintptrkeepalive", don't inline, since the keep
392 // alive information is lost during inlining.
394 // TODO(prattmic): This is handled on calls during escape analysis,
395 // which is after inlining. Move prior to inlining so the keep-alive is
396 // maintained after inlining.
397 if fn.Pragma&ir.UintptrKeepAlive != 0 {
398 reason = "marked as having a keep-alive uintptr argument"
402 // If marked as "go:uintptrescapes", don't inline, since the escape
403 // information is lost during inlining.
404 if fn.Pragma&ir.UintptrEscapes != 0 {
405 reason = "marked as having an escaping uintptr argument"
409 // The nowritebarrierrec checker currently works at function
410 // granularity, so inlining yeswritebarrierrec functions can confuse it
411 // (#22342). As a workaround, disallow inlining them for now.
412 if fn.Pragma&ir.Yeswritebarrierrec != 0 {
413 reason = "marked go:yeswritebarrierrec"
417 // If fn has no body (is defined outside of Go), cannot inline it.
418 if len(fn.Body) == 0 {
419 reason = "no function body"
423 // If fn is synthetic hash or eq function, cannot inline it.
424 // The function is not generated in Unified IR frontend at this moment.
425 if ir.IsEqOrHashFunc(fn) {
426 reason = "type eq/hash function"
433 // canDelayResults reports whether inlined calls to fn can delay
434 // declaring the result parameter until the "return" statement.
435 func canDelayResults(fn *ir.Func) bool {
436 // We can delay declaring+initializing result parameters if:
437 // (1) there's exactly one "return" statement in the inlined function;
438 // (2) it's not an empty return statement (#44355); and
439 // (3) the result parameters aren't named.
442 ir.VisitList(fn.Body, func(n ir.Node) {
443 if n, ok := n.(*ir.ReturnStmt); ok {
445 if len(n.Results) == 0 {
446 nreturns++ // empty return statement (case 2)
452 return false // not exactly one return statement (case 1)
455 // temporaries for return values.
456 for _, param := range fn.Type().Results().FieldSlice() {
457 if sym := types.OrigSym(param.Sym); sym != nil && !sym.IsBlank() {
458 return false // found a named result parameter (case 3)
465 // hairyVisitor visits a function body to determine its inlining
466 // hairiness and whether or not it can be inlined.
467 type hairyVisitor struct {
468 // This is needed to access the current caller in the doNode function.
474 usedLocals ir.NameSet
475 do func(ir.Node) bool
479 func (v *hairyVisitor) tooHairy(fn *ir.Func) bool {
480 v.do = v.doNode // cache closure
481 if ir.DoChildren(fn, v.do) {
485 v.reason = fmt.Sprintf("function too complex: cost %d exceeds budget %d", v.maxBudget-v.budget, v.maxBudget)
491 // doNode visits n and its children, updates the state in v, and returns true if
492 // n makes the current function too hairy for inlining.
493 func (v *hairyVisitor) doNode(n ir.Node) bool {
498 // Call is okay if inlinable and we have the budget for the body.
500 n := n.(*ir.CallExpr)
501 // Functions that call runtime.getcaller{pc,sp} can not be inlined
502 // because getcaller{pc,sp} expect a pointer to the caller's first argument.
504 // runtime.throw is a "cheap call" like panic in normal code.
506 if n.X.Op() == ir.ONAME {
507 name := n.X.(*ir.Name)
508 if name.Class == ir.PFUNC && types.IsRuntimePkg(name.Sym().Pkg) {
509 fn := name.Sym().Name
510 if fn == "getcallerpc" || fn == "getcallersp" {
511 v.reason = "call to " + fn
515 v.budget -= inlineExtraThrowCost
519 // Special case for reflect.noescpae. It does just type
520 // conversions to appease the escape analysis, and doesn't
522 if name.Class == ir.PFUNC && types.IsReflectPkg(name.Sym().Pkg) {
523 if name.Sym().Name == "noescape" {
527 // Special case for coverage counter updates; although
528 // these correspond to real operations, we treat them as
529 // zero cost for the moment. This is due to the existence
530 // of tests that are sensitive to inlining-- if the
531 // insertion of coverage instrumentation happens to tip a
532 // given function over the threshold and move it from
533 // "inlinable" to "not-inlinable", this can cause changes
534 // in allocation behavior, which can then result in test
535 // failures (a good example is the TestAllocations in
537 if isAtomicCoverageCounterUpdate(n) {
541 if n.X.Op() == ir.OMETHEXPR {
542 if meth := ir.MethodExprName(n.X); meth != nil {
543 if fn := meth.Func; fn != nil {
545 if types.IsRuntimePkg(s.Pkg) && s.Name == "heapBits.nextArena" {
546 // Special case: explicitly allow mid-stack inlining of
547 // runtime.heapBits.next even though it calls slow-path
548 // runtime.heapBits.nextArena.
551 // Special case: on architectures that can do unaligned loads,
552 // explicitly mark encoding/binary methods as cheap,
553 // because in practice they are, even though our inlining
554 // budgeting system does not see that. See issue 42958.
555 if base.Ctxt.Arch.CanMergeLoads && s.Pkg.Path == "encoding/binary" {
557 case "littleEndian.Uint64", "littleEndian.Uint32", "littleEndian.Uint16",
558 "bigEndian.Uint64", "bigEndian.Uint32", "bigEndian.Uint16",
559 "littleEndian.PutUint64", "littleEndian.PutUint32", "littleEndian.PutUint16",
560 "bigEndian.PutUint64", "bigEndian.PutUint32", "bigEndian.PutUint16",
561 "littleEndian.AppendUint64", "littleEndian.AppendUint32", "littleEndian.AppendUint16",
562 "bigEndian.AppendUint64", "bigEndian.AppendUint32", "bigEndian.AppendUint16":
570 break // treat like any other node, that is, cost of 1
573 // Determine if the callee edge is for an inlinable hot callee or not.
574 if v.profile != nil && v.curFunc != nil {
575 if fn := inlCallee(n.X, v.profile); fn != nil && typecheck.HaveInlineBody(fn) {
576 lineOffset := pgo.NodeLineOffset(n, fn)
577 csi := pgo.CallSiteInfo{LineOffset: lineOffset, Caller: v.curFunc}
578 if _, o := candHotEdgeMap[csi]; o {
579 if base.Debug.PGODebug > 0 {
580 fmt.Printf("hot-callsite identified at line=%v for func=%v\n", ir.Line(n), ir.PkgFuncName(v.curFunc))
586 if ir.IsIntrinsicCall(n) {
587 // Treat like any other node.
591 if fn := inlCallee(n.X, v.profile); fn != nil && typecheck.HaveInlineBody(fn) {
592 v.budget -= fn.Inl.Cost
596 // Call cost for non-leaf inlining.
597 v.budget -= v.extraCallCost
600 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
602 // Things that are too hairy, irrespective of the budget
603 case ir.OCALL, ir.OCALLINTER:
604 // Call cost for non-leaf inlining.
605 v.budget -= v.extraCallCost
608 n := n.(*ir.UnaryExpr)
609 if n.X.Op() == ir.OCONVIFACE && n.X.(*ir.ConvExpr).Implicit() {
610 // Hack to keep reflect.flag.mustBe inlinable for TestIntendedInlining.
611 // Before CL 284412, these conversions were introduced later in the
612 // compiler, so they didn't count against inlining budget.
615 v.budget -= inlineExtraPanicCost
618 // recover matches the argument frame pointer to find
619 // the right panic value, so it needs an argument frame.
620 v.reason = "call to recover"
624 if base.Debug.InlFuncsWithClosures == 0 {
625 v.reason = "not inlining functions with closures"
629 // TODO(danscales): Maybe make budget proportional to number of closure
631 //v.budget -= int32(len(n.(*ir.ClosureExpr).Func.ClosureVars) * 3)
632 // TODO(austin): However, if we're able to inline this closure into
633 // v.curFunc, then we actually pay nothing for the closure captures. We
634 // should try to account for that if we're going to account for captures.
639 ir.ODCLTYPE, // can't print yet
641 v.reason = "unhandled op " + n.Op().String()
645 v.budget -= inlineExtraAppendCost
648 n := n.(*ir.AddrExpr)
649 // Make "&s.f" cost 0 when f's offset is zero.
650 if dot, ok := n.X.(*ir.SelectorExpr); ok && (dot.Op() == ir.ODOT || dot.Op() == ir.ODOTPTR) {
651 if _, ok := dot.X.(*ir.Name); ok && dot.Selection.Offset == 0 {
652 v.budget += 2 // undo ir.OADDR+ir.ODOT/ir.ODOTPTR
657 // *(*X)(unsafe.Pointer(&x)) is low-cost
658 n := n.(*ir.StarExpr)
661 for ptr.Op() == ir.OCONVNOP {
662 ptr = ptr.(*ir.ConvExpr).X
664 if ptr.Op() == ir.OADDR {
665 v.budget += 1 // undo half of default cost of ir.ODEREF+ir.OADDR
669 // This doesn't produce code, but the children might.
670 v.budget++ // undo default cost
672 case ir.ODCLCONST, ir.OFALL, ir.OTYPE:
673 // These nodes don't produce code; omit from inlining budget.
678 if ir.IsConst(n.Cond, constant.Bool) {
679 // This if and the condition cost nothing.
680 if doList(n.Init(), v.do) {
683 if ir.BoolVal(n.Cond) {
684 return doList(n.Body, v.do)
686 return doList(n.Else, v.do)
692 if n.Class == ir.PAUTO {
697 // The only OBLOCK we should see at this point is an empty one.
698 // In any event, let the visitList(n.List()) below take care of the statements,
699 // and don't charge for the OBLOCK itself. The ++ undoes the -- below.
702 case ir.OMETHVALUE, ir.OSLICELIT:
703 v.budget-- // Hack for toolstash -cmp.
706 v.budget++ // Hack for toolstash -cmp.
709 n := n.(*ir.AssignListStmt)
711 // Unified IR unconditionally rewrites:
722 // so that it can insert implicit conversions as necessary. To
723 // minimize impact to the existing inlining heuristics (in
724 // particular, to avoid breaking the existing inlinability regress
725 // tests), we need to compensate for this here.
727 // See also identical logic in isBigFunc.
728 if init := n.Rhs[0].Init(); len(init) == 1 {
729 if _, ok := init[0].(*ir.AssignListStmt); ok {
730 // 4 for each value, because each temporary variable now
731 // appears 3 times (DCL, LHS, RHS), plus an extra DCL node.
733 // 1 for the extra "tmp1, tmp2 = f()" assignment statement.
734 v.budget += 4*int32(len(n.Lhs)) + 1
739 // Special case for coverage counter updates and coverage
740 // function registrations. Although these correspond to real
741 // operations, we treat them as zero cost for the moment. This
742 // is primarily due to the existence of tests that are
743 // sensitive to inlining-- if the insertion of coverage
744 // instrumentation happens to tip a given function over the
745 // threshold and move it from "inlinable" to "not-inlinable",
746 // this can cause changes in allocation behavior, which can
747 // then result in test failures (a good example is the
748 // TestAllocations in crypto/ed25519).
749 n := n.(*ir.AssignStmt)
750 if n.X.Op() == ir.OINDEX && isIndexingCoverageCounter(n.X) {
757 // When debugging, don't stop early, to get full cost of inlining this function
758 if v.budget < 0 && base.Flag.LowerM < 2 && !logopt.Enabled() {
759 v.reason = "too expensive"
763 return ir.DoChildren(n, v.do)
766 func isBigFunc(fn *ir.Func) bool {
767 budget := inlineBigFunctionNodes
768 return ir.Any(fn, func(n ir.Node) bool {
769 // See logic in hairyVisitor.doNode, explaining unified IR's
770 // handling of "a, b = f()" assignments.
771 if n, ok := n.(*ir.AssignListStmt); ok && n.Op() == ir.OAS2 {
772 if init := n.Rhs[0].Init(); len(init) == 1 {
773 if _, ok := init[0].(*ir.AssignListStmt); ok {
774 budget += 4*len(n.Lhs) + 1
784 // inlcopylist (together with inlcopy) recursively copies a list of nodes, except
785 // that it keeps the same ONAME, OTYPE, and OLITERAL nodes. It is used for copying
786 // the body and dcls of an inlineable function.
787 func inlcopylist(ll []ir.Node) []ir.Node {
788 s := make([]ir.Node, len(ll))
789 for i, n := range ll {
795 // inlcopy is like DeepCopy(), but does extra work to copy closures.
796 func inlcopy(n ir.Node) ir.Node {
797 var edit func(ir.Node) ir.Node
798 edit = func(x ir.Node) ir.Node {
800 case ir.ONAME, ir.OTYPE, ir.OLITERAL, ir.ONIL:
804 ir.EditChildren(m, edit)
805 if x.Op() == ir.OCLOSURE {
806 x := x.(*ir.ClosureExpr)
807 // Need to save/duplicate x.Func.Nname,
808 // x.Func.Nname.Ntype, x.Func.Dcl, x.Func.ClosureVars, and
809 // x.Func.Body for iexport and local inlining.
811 newfn := ir.NewFunc(oldfn.Pos())
812 m.(*ir.ClosureExpr).Func = newfn
813 newfn.Nname = ir.NewNameAt(oldfn.Nname.Pos(), oldfn.Nname.Sym())
814 // XXX OK to share fn.Type() ??
815 newfn.Nname.SetType(oldfn.Nname.Type())
816 newfn.Body = inlcopylist(oldfn.Body)
817 // Make shallow copy of the Dcl and ClosureVar slices
818 newfn.Dcl = append([]*ir.Name(nil), oldfn.Dcl...)
819 newfn.ClosureVars = append([]*ir.Name(nil), oldfn.ClosureVars...)
826 // InlineCalls/inlnode walks fn's statements and expressions and substitutes any
827 // calls made to inlineable functions. This is the external entry point.
828 func InlineCalls(fn *ir.Func, profile *pgo.Profile) {
831 bigCaller := isBigFunc(fn)
832 if bigCaller && base.Flag.LowerM > 1 {
833 fmt.Printf("%v: function %v considered 'big'; reducing max cost of inlinees\n", ir.Line(fn), fn)
835 var inlCalls []*ir.InlinedCallExpr
836 var edit func(ir.Node) ir.Node
837 edit = func(n ir.Node) ir.Node {
838 return inlnode(n, bigCaller, &inlCalls, edit, profile)
840 ir.EditChildren(fn, edit)
842 // If we inlined any calls, we want to recursively visit their
843 // bodies for further inlining. However, we need to wait until
844 // *after* the original function body has been expanded, or else
845 // inlCallee can have false positives (e.g., #54632).
846 for len(inlCalls) > 0 {
848 inlCalls = inlCalls[1:]
849 ir.EditChildren(call, edit)
855 // inlnode recurses over the tree to find inlineable calls, which will
856 // be turned into OINLCALLs by mkinlcall. When the recursion comes
857 // back up will examine left, right, list, rlist, ninit, ntest, nincr,
858 // nbody and nelse and use one of the 4 inlconv/glue functions above
859 // to turn the OINLCALL into an expression, a statement, or patch it
860 // in to this nodes list or rlist as appropriate.
861 // NOTE it makes no sense to pass the glue functions down the
862 // recursion to the level where the OINLCALL gets created because they
863 // have to edit /this/ n, so you'd have to push that one down as well,
864 // but then you may as well do it here. so this is cleaner and
865 // shorter and less complicated.
866 // The result of inlnode MUST be assigned back to n, e.g.
868 // n.Left = inlnode(n.Left)
869 func inlnode(n ir.Node, bigCaller bool, inlCalls *[]*ir.InlinedCallExpr, edit func(ir.Node) ir.Node, profile *pgo.Profile) ir.Node {
875 case ir.ODEFER, ir.OGO:
876 n := n.(*ir.GoDeferStmt)
877 switch call := n.Call; call.Op() {
879 base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
881 call := call.(*ir.CallExpr)
885 n := n.(*ir.TailCallStmt)
886 n.Call.NoInline = true // Not inline a tail call for now. Maybe we could inline it just like RETURN fn(arg)?
888 // TODO do them here (or earlier),
889 // so escape analysis can avoid more heapmoves.
893 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
895 n := n.(*ir.CallExpr)
896 if n.X.Op() == ir.OMETHEXPR {
897 // Prevent inlining some reflect.Value methods when using checkptr,
898 // even when package reflect was compiled without it (#35073).
899 if meth := ir.MethodExprName(n.X); meth != nil {
901 if base.Debug.Checkptr != 0 && types.IsReflectPkg(s.Pkg) && (s.Name == "Value.UnsafeAddr" || s.Name == "Value.Pointer") {
910 ir.EditChildren(n, edit)
912 // with all the branches out of the way, it is now time to
913 // transmogrify this node itself unless inhibited by the
914 // switch at the top of this function.
917 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
920 call := n.(*ir.CallExpr)
924 if base.Flag.LowerM > 3 {
925 fmt.Printf("%v:call to func %+v\n", ir.Line(n), call.X)
927 if ir.IsIntrinsicCall(call) {
930 if fn := inlCallee(call.X, profile); fn != nil && typecheck.HaveInlineBody(fn) {
931 n = mkinlcall(call, fn, bigCaller, inlCalls)
940 // inlCallee takes a function-typed expression and returns the underlying function ONAME
941 // that it refers to if statically known. Otherwise, it returns nil.
942 func inlCallee(fn ir.Node, profile *pgo.Profile) *ir.Func {
943 fn = ir.StaticValue(fn)
946 fn := fn.(*ir.SelectorExpr)
947 n := ir.MethodExprName(fn)
948 // Check that receiver type matches fn.X.
949 // TODO(mdempsky): Handle implicit dereference
950 // of pointer receiver argument?
951 if n == nil || !types.Identical(n.Type().Recv().Type, fn.X.Type()) {
957 if fn.Class == ir.PFUNC {
961 fn := fn.(*ir.ClosureExpr)
963 CanInline(c, profile)
971 // SSADumpInline gives the SSA back end a chance to dump the function
972 // when producing output for debugging the compiler itself.
973 var SSADumpInline = func(*ir.Func) {}
975 // InlineCall allows the inliner implementation to be overridden.
976 // If it returns nil, the function will not be inlined.
977 var InlineCall = func(call *ir.CallExpr, fn *ir.Func, inlIndex int) *ir.InlinedCallExpr {
978 base.Fatalf("inline.InlineCall not overridden")
982 // inlineCostOK returns true if call n from caller to callee is cheap enough to
983 // inline. bigCaller indicates that caller is a big function.
985 // If inlineCostOK returns false, it also returns the max cost that the callee
987 func inlineCostOK(n *ir.CallExpr, caller, callee *ir.Func, bigCaller bool) (bool, int32) {
988 maxCost := int32(inlineMaxBudget)
990 // We use this to restrict inlining into very big functions.
991 // See issue 26546 and 17566.
992 maxCost = inlineBigFunctionMaxCost
995 if callee.Inl.Cost <= maxCost {
996 // Simple case. Function is already cheap enough.
1000 // We'll also allow inlining of hot functions below inlineHotMaxBudget,
1001 // but only in small functions.
1003 lineOffset := pgo.NodeLineOffset(n, caller)
1004 csi := pgo.CallSiteInfo{LineOffset: lineOffset, Caller: caller}
1005 if _, ok := candHotEdgeMap[csi]; !ok {
1007 return false, maxCost
1013 if base.Debug.PGODebug > 0 {
1014 fmt.Printf("hot-big check disallows inlining for call %s (cost %d) at %v in big function %s\n", ir.PkgFuncName(callee), callee.Inl.Cost, ir.Line(n), ir.PkgFuncName(caller))
1016 return false, maxCost
1019 if callee.Inl.Cost > inlineHotMaxBudget {
1020 return false, inlineHotMaxBudget
1023 if base.Debug.PGODebug > 0 {
1024 fmt.Printf("hot-budget check allows inlining for call %s (cost %d) at %v in function %s\n", ir.PkgFuncName(callee), callee.Inl.Cost, ir.Line(n), ir.PkgFuncName(caller))
1030 // If n is a OCALLFUNC node, and fn is an ONAME node for a
1031 // function with an inlinable body, return an OINLCALL node that can replace n.
1032 // The returned node's Ninit has the parameter assignments, the Nbody is the
1033 // inlined function body, and (List, Rlist) contain the (input, output)
1035 // The result of mkinlcall MUST be assigned back to n, e.g.
1037 // n.Left = mkinlcall(n.Left, fn, isddd)
1038 func mkinlcall(n *ir.CallExpr, fn *ir.Func, bigCaller bool, inlCalls *[]*ir.InlinedCallExpr) ir.Node {
1040 if logopt.Enabled() {
1041 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
1042 fmt.Sprintf("%s cannot be inlined", ir.PkgFuncName(fn)))
1047 if ok, maxCost := inlineCostOK(n, ir.CurFunc, fn, bigCaller); !ok {
1048 if logopt.Enabled() {
1049 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
1050 fmt.Sprintf("cost %d of %s exceeds max caller cost %d", fn.Inl.Cost, ir.PkgFuncName(fn), maxCost))
1055 if fn == ir.CurFunc {
1056 // Can't recursively inline a function into itself.
1057 if logopt.Enabled() {
1058 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", fmt.Sprintf("recursive call to %s", ir.FuncName(ir.CurFunc)))
1063 if base.Flag.Cfg.Instrumenting && types.IsNoInstrumentPkg(fn.Sym().Pkg) {
1064 // Runtime package must not be instrumented.
1065 // Instrument skips runtime package. However, some runtime code can be
1066 // inlined into other packages and instrumented there. To avoid this,
1067 // we disable inlining of runtime functions when instrumenting.
1068 // The example that we observed is inlining of LockOSThread,
1069 // which lead to false race reports on m contents.
1072 if base.Flag.Race && types.IsNoRacePkg(fn.Sym().Pkg) {
1076 parent := base.Ctxt.PosTable.Pos(n.Pos()).Base().InliningIndex()
1079 // Check if we've already inlined this function at this particular
1080 // call site, in order to stop inlining when we reach the beginning
1081 // of a recursion cycle again. We don't inline immediately recursive
1082 // functions, but allow inlining if there is a recursion cycle of
1083 // many functions. Most likely, the inlining will stop before we
1084 // even hit the beginning of the cycle again, but this catches the
1086 for inlIndex := parent; inlIndex >= 0; inlIndex = base.Ctxt.InlTree.Parent(inlIndex) {
1087 if base.Ctxt.InlTree.InlinedFunction(inlIndex) == sym {
1088 if base.Flag.LowerM > 1 {
1089 fmt.Printf("%v: cannot inline %v into %v: repeated recursive cycle\n", ir.Line(n), fn, ir.FuncName(ir.CurFunc))
1095 typecheck.AssertFixedCall(n)
1097 inlIndex := base.Ctxt.InlTree.Add(parent, n.Pos(), sym, ir.FuncName(fn))
1099 closureInitLSym := func(n *ir.CallExpr, fn *ir.Func) {
1100 // The linker needs FuncInfo metadata for all inlined
1101 // functions. This is typically handled by gc.enqueueFunc
1102 // calling ir.InitLSym for all function declarations in
1103 // typecheck.Target.Decls (ir.UseClosure adds all closures to
1106 // However, non-trivial closures in Decls are ignored, and are
1107 // insteaded enqueued when walk of the calling function
1110 // This presents a problem for direct calls to closures.
1111 // Inlining will replace the entire closure definition with its
1112 // body, which hides the closure from walk and thus suppresses
1115 // Explicitly create a symbol early in this edge case to ensure
1116 // we keep this metadata.
1118 // TODO: Refactor to keep a reference so this can all be done
1121 if n.Op() != ir.OCALLFUNC {
1122 // Not a standard call.
1125 if n.X.Op() != ir.OCLOSURE {
1126 // Not a direct closure call.
1130 clo := n.X.(*ir.ClosureExpr)
1131 if ir.IsTrivialClosure(clo) {
1132 // enqueueFunc will handle trivial closures anyways.
1136 ir.InitLSym(fn, true)
1139 closureInitLSym(n, fn)
1141 if base.Flag.GenDwarfInl > 0 {
1142 if !sym.WasInlined() {
1143 base.Ctxt.DwFixups.SetPrecursorFunc(sym, fn)
1144 sym.Set(obj.AttrWasInlined, true)
1148 if base.Flag.LowerM != 0 {
1149 fmt.Printf("%v: inlining call to %v\n", ir.Line(n), fn)
1151 if base.Flag.LowerM > 2 {
1152 fmt.Printf("%v: Before inlining: %+v\n", ir.Line(n), n)
1155 res := InlineCall(n, fn, inlIndex)
1158 base.FatalfAt(n.Pos(), "inlining call to %v failed", fn)
1161 if base.Flag.LowerM > 2 {
1162 fmt.Printf("%v: After inlining %+v\n\n", ir.Line(res), res)
1165 *inlCalls = append(*inlCalls, res)
1170 // CalleeEffects appends any side effects from evaluating callee to init.
1171 func CalleeEffects(init *ir.Nodes, callee ir.Node) {
1173 init.Append(ir.TakeInit(callee)...)
1175 switch callee.Op() {
1176 case ir.ONAME, ir.OCLOSURE, ir.OMETHEXPR:
1180 conv := callee.(*ir.ConvExpr)
1184 ic := callee.(*ir.InlinedCallExpr)
1185 init.Append(ic.Body.Take()...)
1186 callee = ic.SingleResult()
1189 base.FatalfAt(callee.Pos(), "unexpected callee expression: %v", callee)
1194 func pruneUnusedAutos(ll []*ir.Name, vis *hairyVisitor) []*ir.Name {
1195 s := make([]*ir.Name, 0, len(ll))
1196 for _, n := range ll {
1197 if n.Class == ir.PAUTO {
1198 if !vis.usedLocals.Has(n) {
1207 // numNonClosures returns the number of functions in list which are not closures.
1208 func numNonClosures(list []*ir.Func) int {
1210 for _, fn := range list {
1211 if fn.OClosure == nil {
1218 func doList(list []ir.Node, do func(ir.Node) bool) bool {
1219 for _, x := range list {
1229 // isIndexingCoverageCounter returns true if the specified node 'n' is indexing
1230 // into a coverage counter array.
1231 func isIndexingCoverageCounter(n ir.Node) bool {
1232 if n.Op() != ir.OINDEX {
1235 ixn := n.(*ir.IndexExpr)
1236 if ixn.X.Op() != ir.ONAME || !ixn.X.Type().IsArray() {
1239 nn := ixn.X.(*ir.Name)
1240 return nn.CoverageCounter()
1243 // isAtomicCoverageCounterUpdate examines the specified node to
1244 // determine whether it represents a call to sync/atomic.AddUint32 to
1245 // increment a coverage counter.
1246 func isAtomicCoverageCounterUpdate(cn *ir.CallExpr) bool {
1247 if cn.X.Op() != ir.ONAME {
1250 name := cn.X.(*ir.Name)
1251 if name.Class != ir.PFUNC {
1254 fn := name.Sym().Name
1255 if name.Sym().Pkg.Path != "sync/atomic" ||
1256 (fn != "AddUint32" && fn != "StoreUint32") {
1259 if len(cn.Args) != 2 || cn.Args[0].Op() != ir.OADDR {
1262 adn := cn.Args[0].(*ir.AddrExpr)
1263 v := isIndexingCoverageCounter(adn.X)