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 // List of inlined call sites. CallSiteInfo.Callee is always nil.
67 // TODO(prattmic): Make this non-global.
68 inlinedCallSites = make(map[pgo.CallSiteInfo]struct{})
70 // Threshold in percentage for hot callsite inlining.
71 inlineHotCallSiteThresholdPercent float64
73 // Threshold in CDF percentage for hot callsite inlining,
74 // that is, for a threshold of X the hottest callsites that
75 // make up the top X% of total edge weight will be
76 // considered hot for inlining candidates.
77 inlineCDFHotCallSiteThresholdPercent = float64(99)
79 // Budget increased due to hotness.
80 inlineHotMaxBudget int32 = 2000
83 // pgoInlinePrologue records the hot callsites from ir-graph.
84 func pgoInlinePrologue(p *pgo.Profile, decls []ir.Node) {
85 if base.Debug.PGOInlineCDFThreshold != "" {
86 if s, err := strconv.ParseFloat(base.Debug.PGOInlineCDFThreshold, 64); err == nil && s >= 0 && s <= 100 {
87 inlineCDFHotCallSiteThresholdPercent = s
89 base.Fatalf("invalid PGOInlineCDFThreshold, must be between 0 and 100")
92 var hotCallsites []pgo.NodeMapKey
93 inlineHotCallSiteThresholdPercent, hotCallsites = hotNodesFromCDF(p)
94 if base.Debug.PGOInline > 0 {
95 fmt.Printf("hot-callsite-thres-from-CDF=%v\n", inlineHotCallSiteThresholdPercent)
98 if x := base.Debug.PGOInlineBudget; x != 0 {
99 inlineHotMaxBudget = int32(x)
102 for _, n := range hotCallsites {
103 // mark inlineable callees from hot edges
104 if callee := p.WeightedCG.IRNodes[n.CalleeName]; callee != nil {
105 candHotCalleeMap[callee] = struct{}{}
107 // mark hot call sites
108 if caller := p.WeightedCG.IRNodes[n.CallerName]; caller != nil {
109 csi := pgo.CallSiteInfo{LineOffset: n.CallSiteOffset, Caller: caller.AST}
110 candHotEdgeMap[csi] = struct{}{}
114 if base.Debug.PGOInline >= 2 {
115 fmt.Printf("hot-cg before inline in dot format:")
116 p.PrintWeightedCallGraphDOT(inlineHotCallSiteThresholdPercent)
120 // hotNodesFromCDF computes an edge weight threshold and the list of hot
121 // nodes that make up the given percentage of the CDF. The threshold, as
122 // a percent, is the lower bound of weight for nodes to be considered hot
123 // (currently only used in debug prints) (in case of equal weights,
124 // comparing with the threshold may not accurately reflect which nodes are
126 func hotNodesFromCDF(p *pgo.Profile) (float64, []pgo.NodeMapKey) {
127 nodes := make([]pgo.NodeMapKey, len(p.NodeMap))
129 for n := range p.NodeMap {
133 sort.Slice(nodes, func(i, j int) bool {
134 ni, nj := nodes[i], nodes[j]
135 if wi, wj := p.NodeMap[ni].EWeight, p.NodeMap[nj].EWeight; wi != wj {
136 return wi > wj // want larger weight first
138 // same weight, order by name/line number
139 if ni.CallerName != nj.CallerName {
140 return ni.CallerName < nj.CallerName
142 if ni.CalleeName != nj.CalleeName {
143 return ni.CalleeName < nj.CalleeName
145 return ni.CallSiteOffset < nj.CallSiteOffset
148 for i, n := range nodes {
149 w := p.NodeMap[n].EWeight
151 if pgo.WeightInPercentage(cum, p.TotalEdgeWeight) > inlineCDFHotCallSiteThresholdPercent {
152 // nodes[:i+1] to include the very last node that makes it to go over the threshold.
153 // (Say, if the CDF threshold is 50% and one hot node takes 60% of weight, we want to
154 // include that node instead of excluding it.)
155 return pgo.WeightInPercentage(w, p.TotalEdgeWeight), nodes[:i+1]
161 // pgoInlineEpilogue updates IRGraph after inlining.
162 func pgoInlineEpilogue(p *pgo.Profile, decls []ir.Node) {
163 if base.Debug.PGOInline >= 2 {
164 ir.VisitFuncsBottomUp(decls, func(list []*ir.Func, recursive bool) {
165 for _, f := range list {
166 name := ir.PkgFuncName(f)
167 if n, ok := p.WeightedCG.IRNodes[name]; ok {
168 p.RedirectEdges(n, inlinedCallSites)
172 // Print the call-graph after inlining. This is a debugging feature.
173 fmt.Printf("hot-cg after inline in dot:")
174 p.PrintWeightedCallGraphDOT(inlineHotCallSiteThresholdPercent)
178 // InlinePackage finds functions that can be inlined and clones them before walk expands them.
179 func InlinePackage(p *pgo.Profile) {
180 InlineDecls(p, typecheck.Target.Decls, true)
183 // InlineDecls applies inlining to the given batch of declarations.
184 func InlineDecls(p *pgo.Profile, decls []ir.Node, doInline bool) {
186 pgoInlinePrologue(p, decls)
189 doCanInline := func(n *ir.Func, recursive bool, numfns int) {
190 if !recursive || numfns > 1 {
191 // We allow inlining if there is no
192 // recursion, or the recursion cycle is
193 // across more than one function.
196 if base.Flag.LowerM > 1 && n.OClosure == nil {
197 fmt.Printf("%v: cannot inline %v: recursive\n", ir.Line(n), n.Nname)
202 ir.VisitFuncsBottomUp(decls, func(list []*ir.Func, recursive bool) {
203 numfns := numNonClosures(list)
204 // We visit functions within an SCC in fairly arbitrary order,
205 // so by computing inlinability for all functions in the SCC
206 // before performing any inlining, the results are less
207 // sensitive to the order within the SCC (see #58905 for an
209 if base.Debug.InlineSCCOnePass == 0 {
210 // Compute inlinability for all functions in the SCC ...
211 for _, n := range list {
212 doCanInline(n, recursive, numfns)
214 // ... then make a second pass to do inlining of calls.
216 for _, n := range list {
221 // Legacy ordering to make it easier to triage any bugs
222 // or compile time issues that might crop up.
223 for _, n := range list {
224 doCanInline(n, recursive, numfns)
232 // Perform a garbage collection of hidden closures functions that
233 // are no longer reachable from top-level functions following
234 // inlining. See #59404 and #59638 for more context.
235 garbageCollectUnreferencedHiddenClosures()
238 pgoInlineEpilogue(p, decls)
242 // garbageCollectUnreferencedHiddenClosures makes a pass over all the
243 // top-level (non-hidden-closure) functions looking for nested closure
244 // functions that are reachable, then sweeps through the Target.Decls
245 // list and marks any non-reachable hidden closure function as dead.
246 // See issues #59404 and #59638 for more context.
247 func garbageCollectUnreferencedHiddenClosures() {
249 liveFuncs := make(map[*ir.Func]bool)
251 var markLiveFuncs func(fn *ir.Func)
252 markLiveFuncs = func(fn *ir.Func) {
254 var vis func(node ir.Node)
255 vis = func(node ir.Node) {
256 if clo, ok := node.(*ir.ClosureExpr); ok {
257 if !liveFuncs[clo.Func] {
258 liveFuncs[clo.Func] = true
259 markLiveFuncs(clo.Func)
266 for i := 0; i < len(typecheck.Target.Decls); i++ {
267 if fn, ok := typecheck.Target.Decls[i].(*ir.Func); ok {
268 if fn.IsHiddenClosure() {
275 for i := 0; i < len(typecheck.Target.Decls); i++ {
276 if fn, ok := typecheck.Target.Decls[i].(*ir.Func); ok {
277 if !fn.IsHiddenClosure() {
280 if fn.IsDeadcodeClosure() {
286 fn.SetIsDeadcodeClosure(true)
287 if base.Flag.LowerM > 2 {
288 fmt.Printf("%v: unreferenced closure %v marked as dead\n", ir.Line(fn), fn)
290 if fn.Inl != nil && fn.LSym == nil {
291 ir.InitLSym(fn, true)
297 // CanInline determines whether fn is inlineable.
298 // If so, CanInline saves copies of fn.Body and fn.Dcl in fn.Inl.
299 // fn and fn.Body will already have been typechecked.
300 func CanInline(fn *ir.Func, profile *pgo.Profile) {
302 base.Fatalf("CanInline no nname %+v", fn)
305 var reason string // reason, if any, that the function was not inlined
306 if base.Flag.LowerM > 1 || logopt.Enabled() {
309 if base.Flag.LowerM > 1 {
310 fmt.Printf("%v: cannot inline %v: %s\n", ir.Line(fn), fn.Nname, reason)
312 if logopt.Enabled() {
313 logopt.LogOpt(fn.Pos(), "cannotInlineFunction", "inline", ir.FuncName(fn), reason)
319 // If marked "go:noinline", don't inline
320 if fn.Pragma&ir.Noinline != 0 {
321 reason = "marked go:noinline"
325 // If marked "go:norace" and -race compilation, don't inline.
326 if base.Flag.Race && fn.Pragma&ir.Norace != 0 {
327 reason = "marked go:norace with -race compilation"
331 // If marked "go:nocheckptr" and -d checkptr compilation, don't inline.
332 if base.Debug.Checkptr != 0 && fn.Pragma&ir.NoCheckPtr != 0 {
333 reason = "marked go:nocheckptr"
337 // If marked "go:cgo_unsafe_args", don't inline, since the
338 // function makes assumptions about its argument frame layout.
339 if fn.Pragma&ir.CgoUnsafeArgs != 0 {
340 reason = "marked go:cgo_unsafe_args"
344 // If marked as "go:uintptrkeepalive", don't inline, since the
345 // keep alive information is lost during inlining.
347 // TODO(prattmic): This is handled on calls during escape analysis,
348 // which is after inlining. Move prior to inlining so the keep-alive is
349 // maintained after inlining.
350 if fn.Pragma&ir.UintptrKeepAlive != 0 {
351 reason = "marked as having a keep-alive uintptr argument"
355 // If marked as "go:uintptrescapes", don't inline, since the
356 // escape information is lost during inlining.
357 if fn.Pragma&ir.UintptrEscapes != 0 {
358 reason = "marked as having an escaping uintptr argument"
362 // The nowritebarrierrec checker currently works at function
363 // granularity, so inlining yeswritebarrierrec functions can
364 // confuse it (#22342). As a workaround, disallow inlining
366 if fn.Pragma&ir.Yeswritebarrierrec != 0 {
367 reason = "marked go:yeswritebarrierrec"
371 // If fn has no body (is defined outside of Go), cannot inline it.
372 if len(fn.Body) == 0 {
373 reason = "no function body"
377 // If fn is synthetic hash or eq function, cannot inline it.
378 // The function is not generated in Unified IR frontend at this moment.
379 if ir.IsEqOrHashFunc(fn) {
380 reason = "type eq/hash function"
384 if fn.Typecheck() == 0 {
385 base.Fatalf("CanInline on non-typechecked function %v", fn)
389 if n.Func.InlinabilityChecked() {
392 defer n.Func.SetInlinabilityChecked(true)
394 cc := int32(inlineExtraCallCost)
395 if base.Flag.LowerL == 4 {
396 cc = 1 // this appears to yield better performance than 0.
399 // Update the budget for profile-guided inlining.
400 budget := int32(inlineMaxBudget)
402 if n, ok := profile.WeightedCG.IRNodes[ir.PkgFuncName(fn)]; ok {
403 if _, ok := candHotCalleeMap[n]; ok {
404 budget = int32(inlineHotMaxBudget)
405 if base.Debug.PGOInline > 0 {
406 fmt.Printf("hot-node enabled increased budget=%v for func=%v\n", budget, ir.PkgFuncName(fn))
412 // At this point in the game the function we're looking at may
413 // have "stale" autos, vars that still appear in the Dcl list, but
414 // which no longer have any uses in the function body (due to
415 // elimination by deadcode). We'd like to exclude these dead vars
416 // when creating the "Inline.Dcl" field below; to accomplish this,
417 // the hairyVisitor below builds up a map of used/referenced
418 // locals, and we use this map to produce a pruned Inline.Dcl
419 // list. See issue 25249 for more context.
421 visitor := hairyVisitor{
428 if visitor.tooHairy(fn) {
429 reason = visitor.reason
433 n.Func.Inl = &ir.Inline{
434 Cost: budget - visitor.budget,
435 Dcl: pruneUnusedAutos(n.Defn.(*ir.Func).Dcl, &visitor),
436 Body: inlcopylist(fn.Body),
438 CanDelayResults: canDelayResults(fn),
441 if base.Flag.LowerM > 1 {
442 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))
443 } else if base.Flag.LowerM != 0 {
444 fmt.Printf("%v: can inline %v\n", ir.Line(fn), n)
446 if logopt.Enabled() {
447 logopt.LogOpt(fn.Pos(), "canInlineFunction", "inline", ir.FuncName(fn), fmt.Sprintf("cost: %d", budget-visitor.budget))
451 // canDelayResults reports whether inlined calls to fn can delay
452 // declaring the result parameter until the "return" statement.
453 func canDelayResults(fn *ir.Func) bool {
454 // We can delay declaring+initializing result parameters if:
455 // (1) there's exactly one "return" statement in the inlined function;
456 // (2) it's not an empty return statement (#44355); and
457 // (3) the result parameters aren't named.
460 ir.VisitList(fn.Body, func(n ir.Node) {
461 if n, ok := n.(*ir.ReturnStmt); ok {
463 if len(n.Results) == 0 {
464 nreturns++ // empty return statement (case 2)
470 return false // not exactly one return statement (case 1)
473 // temporaries for return values.
474 for _, param := range fn.Type().Results().FieldSlice() {
475 if sym := types.OrigSym(param.Sym); sym != nil && !sym.IsBlank() {
476 return false // found a named result parameter (case 3)
483 // hairyVisitor visits a function body to determine its inlining
484 // hairiness and whether or not it can be inlined.
485 type hairyVisitor struct {
486 // This is needed to access the current caller in the doNode function.
492 usedLocals ir.NameSet
493 do func(ir.Node) bool
497 func (v *hairyVisitor) tooHairy(fn *ir.Func) bool {
498 v.do = v.doNode // cache closure
499 if ir.DoChildren(fn, v.do) {
503 v.reason = fmt.Sprintf("function too complex: cost %d exceeds budget %d", v.maxBudget-v.budget, v.maxBudget)
509 func (v *hairyVisitor) doNode(n ir.Node) bool {
514 // Call is okay if inlinable and we have the budget for the body.
516 n := n.(*ir.CallExpr)
517 // Functions that call runtime.getcaller{pc,sp} can not be inlined
518 // because getcaller{pc,sp} expect a pointer to the caller's first argument.
520 // runtime.throw is a "cheap call" like panic in normal code.
521 if n.X.Op() == ir.ONAME {
522 name := n.X.(*ir.Name)
523 if name.Class == ir.PFUNC && types.IsRuntimePkg(name.Sym().Pkg) {
524 fn := name.Sym().Name
525 if fn == "getcallerpc" || fn == "getcallersp" {
526 v.reason = "call to " + fn
530 v.budget -= inlineExtraThrowCost
534 // Special case for coverage counter updates; although
535 // these correspond to real operations, we treat them as
536 // zero cost for the moment. This is due to the existence
537 // of tests that are sensitive to inlining-- if the
538 // insertion of coverage instrumentation happens to tip a
539 // given function over the threshold and move it from
540 // "inlinable" to "not-inlinable", this can cause changes
541 // in allocation behavior, which can then result in test
542 // failures (a good example is the TestAllocations in
544 if isAtomicCoverageCounterUpdate(n) {
548 if n.X.Op() == ir.OMETHEXPR {
549 if meth := ir.MethodExprName(n.X); meth != nil {
550 if fn := meth.Func; fn != nil {
553 if types.IsRuntimePkg(s.Pkg) && s.Name == "heapBits.nextArena" {
554 // Special case: explicitly allow mid-stack inlining of
555 // runtime.heapBits.next even though it calls slow-path
556 // runtime.heapBits.nextArena.
559 // Special case: on architectures that can do unaligned loads,
560 // explicitly mark encoding/binary methods as cheap,
561 // because in practice they are, even though our inlining
562 // budgeting system does not see that. See issue 42958.
563 if base.Ctxt.Arch.CanMergeLoads && s.Pkg.Path == "encoding/binary" {
565 case "littleEndian.Uint64", "littleEndian.Uint32", "littleEndian.Uint16",
566 "bigEndian.Uint64", "bigEndian.Uint32", "bigEndian.Uint16",
567 "littleEndian.PutUint64", "littleEndian.PutUint32", "littleEndian.PutUint16",
568 "bigEndian.PutUint64", "bigEndian.PutUint32", "bigEndian.PutUint16",
569 "littleEndian.AppendUint64", "littleEndian.AppendUint32", "littleEndian.AppendUint16",
570 "bigEndian.AppendUint64", "bigEndian.AppendUint32", "bigEndian.AppendUint16":
575 break // treat like any other node, that is, cost of 1
581 // Determine if the callee edge is for an inlinable hot callee or not.
582 if v.profile != nil && v.curFunc != nil {
583 if fn := inlCallee(n.X, v.profile); fn != nil && typecheck.HaveInlineBody(fn) {
584 lineOffset := pgo.NodeLineOffset(n, fn)
585 csi := pgo.CallSiteInfo{LineOffset: lineOffset, Caller: v.curFunc}
586 if _, o := candHotEdgeMap[csi]; o {
587 if base.Debug.PGOInline > 0 {
588 fmt.Printf("hot-callsite identified at line=%v for func=%v\n", ir.Line(n), ir.PkgFuncName(v.curFunc))
594 if ir.IsIntrinsicCall(n) {
595 // Treat like any other node.
599 if fn := inlCallee(n.X, v.profile); fn != nil && typecheck.HaveInlineBody(fn) {
600 v.budget -= fn.Inl.Cost
604 // Call cost for non-leaf inlining.
605 v.budget -= v.extraCallCost
608 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
610 // Things that are too hairy, irrespective of the budget
611 case ir.OCALL, ir.OCALLINTER:
612 // Call cost for non-leaf inlining.
613 v.budget -= v.extraCallCost
616 n := n.(*ir.UnaryExpr)
617 if n.X.Op() == ir.OCONVIFACE && n.X.(*ir.ConvExpr).Implicit() {
618 // Hack to keep reflect.flag.mustBe inlinable for TestIntendedInlining.
619 // Before CL 284412, these conversions were introduced later in the
620 // compiler, so they didn't count against inlining budget.
623 v.budget -= inlineExtraPanicCost
626 // recover matches the argument frame pointer to find
627 // the right panic value, so it needs an argument frame.
628 v.reason = "call to recover"
632 if base.Debug.InlFuncsWithClosures == 0 {
633 v.reason = "not inlining functions with closures"
637 // TODO(danscales): Maybe make budget proportional to number of closure
639 //v.budget -= int32(len(n.(*ir.ClosureExpr).Func.ClosureVars) * 3)
641 // Scan body of closure (which DoChildren doesn't automatically
642 // do) to check for disallowed ops in the body and include the
643 // body in the budget.
644 if doList(n.(*ir.ClosureExpr).Func.Body, v.do) {
650 ir.ODCLTYPE, // can't print yet
652 v.reason = "unhandled op " + n.Op().String()
656 v.budget -= inlineExtraAppendCost
659 n := n.(*ir.AddrExpr)
660 // Make "&s.f" cost 0 when f's offset is zero.
661 if dot, ok := n.X.(*ir.SelectorExpr); ok && (dot.Op() == ir.ODOT || dot.Op() == ir.ODOTPTR) {
662 if _, ok := dot.X.(*ir.Name); ok && dot.Selection.Offset == 0 {
663 v.budget += 2 // undo ir.OADDR+ir.ODOT/ir.ODOTPTR
668 // *(*X)(unsafe.Pointer(&x)) is low-cost
669 n := n.(*ir.StarExpr)
672 for ptr.Op() == ir.OCONVNOP {
673 ptr = ptr.(*ir.ConvExpr).X
675 if ptr.Op() == ir.OADDR {
676 v.budget += 1 // undo half of default cost of ir.ODEREF+ir.OADDR
680 // This doesn't produce code, but the children might.
681 v.budget++ // undo default cost
683 case ir.ODCLCONST, ir.OFALL:
684 // These nodes don't produce code; omit from inlining budget.
689 if ir.IsConst(n.Cond, constant.Bool) {
690 // This if and the condition cost nothing.
691 if doList(n.Init(), v.do) {
694 if ir.BoolVal(n.Cond) {
695 return doList(n.Body, v.do)
697 return doList(n.Else, v.do)
703 if n.Class == ir.PAUTO {
708 // The only OBLOCK we should see at this point is an empty one.
709 // In any event, let the visitList(n.List()) below take care of the statements,
710 // and don't charge for the OBLOCK itself. The ++ undoes the -- below.
713 case ir.OMETHVALUE, ir.OSLICELIT:
714 v.budget-- // Hack for toolstash -cmp.
717 v.budget++ // Hack for toolstash -cmp.
720 n := n.(*ir.AssignListStmt)
722 // Unified IR unconditionally rewrites:
733 // so that it can insert implicit conversions as necessary. To
734 // minimize impact to the existing inlining heuristics (in
735 // particular, to avoid breaking the existing inlinability regress
736 // tests), we need to compensate for this here.
738 // See also identical logic in isBigFunc.
739 if init := n.Rhs[0].Init(); len(init) == 1 {
740 if _, ok := init[0].(*ir.AssignListStmt); ok {
741 // 4 for each value, because each temporary variable now
742 // appears 3 times (DCL, LHS, RHS), plus an extra DCL node.
744 // 1 for the extra "tmp1, tmp2 = f()" assignment statement.
745 v.budget += 4*int32(len(n.Lhs)) + 1
750 // Special case for coverage counter updates and coverage
751 // function registrations. Although these correspond to real
752 // operations, we treat them as zero cost for the moment. This
753 // is primarily due to the existence of tests that are
754 // sensitive to inlining-- if the insertion of coverage
755 // instrumentation happens to tip a given function over the
756 // threshold and move it from "inlinable" to "not-inlinable",
757 // this can cause changes in allocation behavior, which can
758 // then result in test failures (a good example is the
759 // TestAllocations in crypto/ed25519).
760 n := n.(*ir.AssignStmt)
761 if n.X.Op() == ir.OINDEX && isIndexingCoverageCounter(n.X) {
768 // When debugging, don't stop early, to get full cost of inlining this function
769 if v.budget < 0 && base.Flag.LowerM < 2 && !logopt.Enabled() {
770 v.reason = "too expensive"
774 return ir.DoChildren(n, v.do)
777 func isBigFunc(fn *ir.Func) bool {
778 budget := inlineBigFunctionNodes
779 return ir.Any(fn, func(n ir.Node) bool {
780 // See logic in hairyVisitor.doNode, explaining unified IR's
781 // handling of "a, b = f()" assignments.
782 if n, ok := n.(*ir.AssignListStmt); ok && n.Op() == ir.OAS2 {
783 if init := n.Rhs[0].Init(); len(init) == 1 {
784 if _, ok := init[0].(*ir.AssignListStmt); ok {
785 budget += 4*len(n.Lhs) + 1
795 // inlcopylist (together with inlcopy) recursively copies a list of nodes, except
796 // that it keeps the same ONAME, OTYPE, and OLITERAL nodes. It is used for copying
797 // the body and dcls of an inlineable function.
798 func inlcopylist(ll []ir.Node) []ir.Node {
799 s := make([]ir.Node, len(ll))
800 for i, n := range ll {
806 // inlcopy is like DeepCopy(), but does extra work to copy closures.
807 func inlcopy(n ir.Node) ir.Node {
808 var edit func(ir.Node) ir.Node
809 edit = func(x ir.Node) ir.Node {
811 case ir.ONAME, ir.OTYPE, ir.OLITERAL, ir.ONIL:
815 ir.EditChildren(m, edit)
816 if x.Op() == ir.OCLOSURE {
817 x := x.(*ir.ClosureExpr)
818 // Need to save/duplicate x.Func.Nname,
819 // x.Func.Nname.Ntype, x.Func.Dcl, x.Func.ClosureVars, and
820 // x.Func.Body for iexport and local inlining.
822 newfn := ir.NewFunc(oldfn.Pos())
823 m.(*ir.ClosureExpr).Func = newfn
824 newfn.Nname = ir.NewNameAt(oldfn.Nname.Pos(), oldfn.Nname.Sym())
825 // XXX OK to share fn.Type() ??
826 newfn.Nname.SetType(oldfn.Nname.Type())
827 newfn.Body = inlcopylist(oldfn.Body)
828 // Make shallow copy of the Dcl and ClosureVar slices
829 newfn.Dcl = append([]*ir.Name(nil), oldfn.Dcl...)
830 newfn.ClosureVars = append([]*ir.Name(nil), oldfn.ClosureVars...)
837 // InlineCalls/inlnode walks fn's statements and expressions and substitutes any
838 // calls made to inlineable functions. This is the external entry point.
839 func InlineCalls(fn *ir.Func, profile *pgo.Profile) {
842 bigCaller := isBigFunc(fn)
843 if bigCaller && base.Flag.LowerM > 1 {
844 fmt.Printf("%v: function %v considered 'big'; reducing max cost of inlinees\n", ir.Line(fn), fn)
846 var inlCalls []*ir.InlinedCallExpr
847 var edit func(ir.Node) ir.Node
848 edit = func(n ir.Node) ir.Node {
849 return inlnode(n, bigCaller, &inlCalls, edit, profile)
851 ir.EditChildren(fn, edit)
853 // If we inlined any calls, we want to recursively visit their
854 // bodies for further inlining. However, we need to wait until
855 // *after* the original function body has been expanded, or else
856 // inlCallee can have false positives (e.g., #54632).
857 for len(inlCalls) > 0 {
859 inlCalls = inlCalls[1:]
860 ir.EditChildren(call, edit)
866 // inlnode recurses over the tree to find inlineable calls, which will
867 // be turned into OINLCALLs by mkinlcall. When the recursion comes
868 // back up will examine left, right, list, rlist, ninit, ntest, nincr,
869 // nbody and nelse and use one of the 4 inlconv/glue functions above
870 // to turn the OINLCALL into an expression, a statement, or patch it
871 // in to this nodes list or rlist as appropriate.
872 // NOTE it makes no sense to pass the glue functions down the
873 // recursion to the level where the OINLCALL gets created because they
874 // have to edit /this/ n, so you'd have to push that one down as well,
875 // but then you may as well do it here. so this is cleaner and
876 // shorter and less complicated.
877 // The result of inlnode MUST be assigned back to n, e.g.
879 // n.Left = inlnode(n.Left)
880 func inlnode(n ir.Node, bigCaller bool, inlCalls *[]*ir.InlinedCallExpr, edit func(ir.Node) ir.Node, profile *pgo.Profile) ir.Node {
886 case ir.ODEFER, ir.OGO:
887 n := n.(*ir.GoDeferStmt)
888 switch call := n.Call; call.Op() {
890 base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
892 call := call.(*ir.CallExpr)
896 n := n.(*ir.TailCallStmt)
897 n.Call.NoInline = true // Not inline a tail call for now. Maybe we could inline it just like RETURN fn(arg)?
899 // TODO do them here (or earlier),
900 // so escape analysis can avoid more heapmoves.
904 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
906 n := n.(*ir.CallExpr)
907 if n.X.Op() == ir.OMETHEXPR {
908 // Prevent inlining some reflect.Value methods when using checkptr,
909 // even when package reflect was compiled without it (#35073).
910 if meth := ir.MethodExprName(n.X); meth != nil {
912 if base.Debug.Checkptr != 0 && types.IsReflectPkg(s.Pkg) && (s.Name == "Value.UnsafeAddr" || s.Name == "Value.Pointer") {
921 ir.EditChildren(n, edit)
923 // with all the branches out of the way, it is now time to
924 // transmogrify this node itself unless inhibited by the
925 // switch at the top of this function.
928 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
931 call := n.(*ir.CallExpr)
935 if base.Flag.LowerM > 3 {
936 fmt.Printf("%v:call to func %+v\n", ir.Line(n), call.X)
938 if ir.IsIntrinsicCall(call) {
941 if fn := inlCallee(call.X, profile); fn != nil && typecheck.HaveInlineBody(fn) {
942 n = mkinlcall(call, fn, bigCaller, inlCalls, edit)
951 // inlCallee takes a function-typed expression and returns the underlying function ONAME
952 // that it refers to if statically known. Otherwise, it returns nil.
953 func inlCallee(fn ir.Node, profile *pgo.Profile) *ir.Func {
954 fn = ir.StaticValue(fn)
957 fn := fn.(*ir.SelectorExpr)
958 n := ir.MethodExprName(fn)
959 // Check that receiver type matches fn.X.
960 // TODO(mdempsky): Handle implicit dereference
961 // of pointer receiver argument?
962 if n == nil || !types.Identical(n.Type().Recv().Type, fn.X.Type()) {
968 if fn.Class == ir.PFUNC {
972 fn := fn.(*ir.ClosureExpr)
974 CanInline(c, profile)
982 // SSADumpInline gives the SSA back end a chance to dump the function
983 // when producing output for debugging the compiler itself.
984 var SSADumpInline = func(*ir.Func) {}
986 // InlineCall allows the inliner implementation to be overridden.
987 // If it returns nil, the function will not be inlined.
988 var InlineCall = func(call *ir.CallExpr, fn *ir.Func, inlIndex int) *ir.InlinedCallExpr {
989 base.Fatalf("inline.InlineCall not overridden")
993 // inlineCostOK returns true if call n from caller to callee is cheap enough to
994 // inline. bigCaller indicates that caller is a big function.
996 // If inlineCostOK returns false, it also returns the max cost that the callee
998 func inlineCostOK(n *ir.CallExpr, caller, callee *ir.Func, bigCaller bool) (bool, int32) {
999 maxCost := int32(inlineMaxBudget)
1001 // We use this to restrict inlining into very big functions.
1002 // See issue 26546 and 17566.
1003 maxCost = inlineBigFunctionMaxCost
1006 if callee.Inl.Cost <= maxCost {
1007 // Simple case. Function is already cheap enough.
1011 // We'll also allow inlining of hot functions below inlineHotMaxBudget,
1012 // but only in small functions.
1014 lineOffset := pgo.NodeLineOffset(n, caller)
1015 csi := pgo.CallSiteInfo{LineOffset: lineOffset, Caller: caller}
1016 if _, ok := candHotEdgeMap[csi]; !ok {
1018 return false, maxCost
1024 if base.Debug.PGOInline > 0 {
1025 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))
1027 return false, maxCost
1030 if callee.Inl.Cost > inlineHotMaxBudget {
1031 return false, inlineHotMaxBudget
1034 if base.Debug.PGOInline > 0 {
1035 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))
1041 // If n is a OCALLFUNC node, and fn is an ONAME node for a
1042 // function with an inlinable body, return an OINLCALL node that can replace n.
1043 // The returned node's Ninit has the parameter assignments, the Nbody is the
1044 // inlined function body, and (List, Rlist) contain the (input, output)
1046 // The result of mkinlcall MUST be assigned back to n, e.g.
1048 // n.Left = mkinlcall(n.Left, fn, isddd)
1049 func mkinlcall(n *ir.CallExpr, fn *ir.Func, bigCaller bool, inlCalls *[]*ir.InlinedCallExpr, edit func(ir.Node) ir.Node) ir.Node {
1051 if logopt.Enabled() {
1052 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
1053 fmt.Sprintf("%s cannot be inlined", ir.PkgFuncName(fn)))
1058 if ok, maxCost := inlineCostOK(n, ir.CurFunc, fn, bigCaller); !ok {
1059 if logopt.Enabled() {
1060 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
1061 fmt.Sprintf("cost %d of %s exceeds max caller cost %d", fn.Inl.Cost, ir.PkgFuncName(fn), maxCost))
1066 if fn == ir.CurFunc {
1067 // Can't recursively inline a function into itself.
1068 if logopt.Enabled() {
1069 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", fmt.Sprintf("recursive call to %s", ir.FuncName(ir.CurFunc)))
1074 if base.Flag.Cfg.Instrumenting && types.IsRuntimePkg(fn.Sym().Pkg) {
1075 // Runtime package must not be instrumented.
1076 // Instrument skips runtime package. However, some runtime code can be
1077 // inlined into other packages and instrumented there. To avoid this,
1078 // we disable inlining of runtime functions when instrumenting.
1079 // The example that we observed is inlining of LockOSThread,
1080 // which lead to false race reports on m contents.
1084 parent := base.Ctxt.PosTable.Pos(n.Pos()).Base().InliningIndex()
1087 // Check if we've already inlined this function at this particular
1088 // call site, in order to stop inlining when we reach the beginning
1089 // of a recursion cycle again. We don't inline immediately recursive
1090 // functions, but allow inlining if there is a recursion cycle of
1091 // many functions. Most likely, the inlining will stop before we
1092 // even hit the beginning of the cycle again, but this catches the
1094 for inlIndex := parent; inlIndex >= 0; inlIndex = base.Ctxt.InlTree.Parent(inlIndex) {
1095 if base.Ctxt.InlTree.InlinedFunction(inlIndex) == sym {
1096 if base.Flag.LowerM > 1 {
1097 fmt.Printf("%v: cannot inline %v into %v: repeated recursive cycle\n", ir.Line(n), fn, ir.FuncName(ir.CurFunc))
1103 typecheck.AssertFixedCall(n)
1105 inlIndex := base.Ctxt.InlTree.Add(parent, n.Pos(), sym)
1107 closureInitLSym := func(n *ir.CallExpr, fn *ir.Func) {
1108 // The linker needs FuncInfo metadata for all inlined
1109 // functions. This is typically handled by gc.enqueueFunc
1110 // calling ir.InitLSym for all function declarations in
1111 // typecheck.Target.Decls (ir.UseClosure adds all closures to
1114 // However, non-trivial closures in Decls are ignored, and are
1115 // insteaded enqueued when walk of the calling function
1118 // This presents a problem for direct calls to closures.
1119 // Inlining will replace the entire closure definition with its
1120 // body, which hides the closure from walk and thus suppresses
1123 // Explicitly create a symbol early in this edge case to ensure
1124 // we keep this metadata.
1126 // TODO: Refactor to keep a reference so this can all be done
1129 if n.Op() != ir.OCALLFUNC {
1130 // Not a standard call.
1133 if n.X.Op() != ir.OCLOSURE {
1134 // Not a direct closure call.
1138 clo := n.X.(*ir.ClosureExpr)
1139 if ir.IsTrivialClosure(clo) {
1140 // enqueueFunc will handle trivial closures anyways.
1144 ir.InitLSym(fn, true)
1147 closureInitLSym(n, fn)
1149 if base.Flag.GenDwarfInl > 0 {
1150 if !sym.WasInlined() {
1151 base.Ctxt.DwFixups.SetPrecursorFunc(sym, fn)
1152 sym.Set(obj.AttrWasInlined, true)
1156 if base.Flag.LowerM != 0 {
1157 fmt.Printf("%v: inlining call to %v\n", ir.Line(n), fn)
1159 if base.Flag.LowerM > 2 {
1160 fmt.Printf("%v: Before inlining: %+v\n", ir.Line(n), n)
1163 if base.Debug.PGOInline > 0 {
1164 csi := pgo.CallSiteInfo{LineOffset: pgo.NodeLineOffset(n, fn), Caller: ir.CurFunc}
1165 if _, ok := inlinedCallSites[csi]; !ok {
1166 inlinedCallSites[csi] = struct{}{}
1170 res := InlineCall(n, fn, inlIndex)
1173 base.FatalfAt(n.Pos(), "inlining call to %v failed", fn)
1176 if base.Flag.LowerM > 2 {
1177 fmt.Printf("%v: After inlining %+v\n\n", ir.Line(res), res)
1180 *inlCalls = append(*inlCalls, res)
1185 // CalleeEffects appends any side effects from evaluating callee to init.
1186 func CalleeEffects(init *ir.Nodes, callee ir.Node) {
1188 init.Append(ir.TakeInit(callee)...)
1190 switch callee.Op() {
1191 case ir.ONAME, ir.OCLOSURE, ir.OMETHEXPR:
1195 conv := callee.(*ir.ConvExpr)
1199 ic := callee.(*ir.InlinedCallExpr)
1200 init.Append(ic.Body.Take()...)
1201 callee = ic.SingleResult()
1204 base.FatalfAt(callee.Pos(), "unexpected callee expression: %v", callee)
1209 func pruneUnusedAutos(ll []*ir.Name, vis *hairyVisitor) []*ir.Name {
1210 s := make([]*ir.Name, 0, len(ll))
1211 for _, n := range ll {
1212 if n.Class == ir.PAUTO {
1213 if !vis.usedLocals.Has(n) {
1222 // numNonClosures returns the number of functions in list which are not closures.
1223 func numNonClosures(list []*ir.Func) int {
1225 for _, fn := range list {
1226 if fn.OClosure == nil {
1233 func doList(list []ir.Node, do func(ir.Node) bool) bool {
1234 for _, x := range list {
1244 // isIndexingCoverageCounter returns true if the specified node 'n' is indexing
1245 // into a coverage counter array.
1246 func isIndexingCoverageCounter(n ir.Node) bool {
1247 if n.Op() != ir.OINDEX {
1250 ixn := n.(*ir.IndexExpr)
1251 if ixn.X.Op() != ir.ONAME || !ixn.X.Type().IsArray() {
1254 nn := ixn.X.(*ir.Name)
1255 return nn.CoverageCounter()
1258 // isAtomicCoverageCounterUpdate examines the specified node to
1259 // determine whether it represents a call to sync/atomic.AddUint32 to
1260 // increment a coverage counter.
1261 func isAtomicCoverageCounterUpdate(cn *ir.CallExpr) bool {
1262 if cn.X.Op() != ir.ONAME {
1265 name := cn.X.(*ir.Name)
1266 if name.Class != ir.PFUNC {
1269 fn := name.Sym().Name
1270 if name.Sym().Pkg.Path != "sync/atomic" ||
1271 (fn != "AddUint32" && fn != "StoreUint32") {
1274 if len(cn.Args) != 2 || cn.Args[0].Op() != ir.OADDR {
1277 adn := cn.Args[0].(*ir.AddrExpr)
1278 v := isIndexingCoverageCounter(adn.X)