Source file src/cmd/compile/internal/inline/inl.go

     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.
     4  //
     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.
     9  //
    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
    12  // are not supported.
    13  //      0: disabled
    14  //      1: 80-nodes leaf functions, oneliners, panic, lazy typechecking (default)
    15  //      2: (unassigned)
    16  //      3: (unassigned)
    17  //      4: allow non-leaf functions
    18  //
    19  // At some point this may get another default and become switch-offable with -N.
    20  //
    21  // The -d typcheckinl flag enables early typechecking of all imported bodies,
    22  // which is useful to flush out bugs.
    23  //
    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.
    26  
    27  package inline
    28  
    29  import (
    30  	"fmt"
    31  	"go/constant"
    32  	"internal/buildcfg"
    33  	"strconv"
    34  	"strings"
    35  
    36  	"cmd/compile/internal/base"
    37  	"cmd/compile/internal/inline/inlheur"
    38  	"cmd/compile/internal/ir"
    39  	"cmd/compile/internal/logopt"
    40  	"cmd/compile/internal/pgoir"
    41  	"cmd/compile/internal/typecheck"
    42  	"cmd/compile/internal/types"
    43  	"cmd/internal/obj"
    44  	"cmd/internal/pgo"
    45  	"cmd/internal/src"
    46  )
    47  
    48  // Inlining budget parameters, gathered in one place
    49  const (
    50  	inlineMaxBudget       = 80
    51  	inlineExtraAppendCost = 0
    52  	// default is to inline if there's at most one call. -l=4 overrides this by using 1 instead.
    53  	inlineExtraCallCost  = 57              // 57 was benchmarked to provided most benefit with no bad surprises; see https://github.com/golang/go/issues/19348#issuecomment-439370742
    54  	inlineParamCallCost  = 17              // calling a parameter only costs this much extra (inlining might expose a constant function)
    55  	inlineExtraPanicCost = 1               // do not penalize inlining panics.
    56  	inlineExtraThrowCost = inlineMaxBudget // with current (2018-05/1.11) code, inlining runtime.throw does not help.
    57  
    58  	inlineBigFunctionNodes      = 5000                 // Functions with this many nodes are considered "big".
    59  	inlineBigFunctionMaxCost    = 20                   // Max cost of inlinee when inlining into a "big" function.
    60  	inlineClosureCalledOnceCost = 10 * inlineMaxBudget // if a closure is just called once, inline it.
    61  )
    62  
    63  var (
    64  	// List of all hot callee nodes.
    65  	// TODO(prattmic): Make this non-global.
    66  	candHotCalleeMap = make(map[*pgoir.IRNode]struct{})
    67  
    68  	// Set of functions that contain hot call sites.
    69  	hasHotCall = make(map[*ir.Func]struct{})
    70  
    71  	// List of all hot call sites. CallSiteInfo.Callee is always nil.
    72  	// TODO(prattmic): Make this non-global.
    73  	candHotEdgeMap = make(map[pgoir.CallSiteInfo]struct{})
    74  
    75  	// Threshold in percentage for hot callsite inlining.
    76  	inlineHotCallSiteThresholdPercent float64
    77  
    78  	// Threshold in CDF percentage for hot callsite inlining,
    79  	// that is, for a threshold of X the hottest callsites that
    80  	// make up the top X% of total edge weight will be
    81  	// considered hot for inlining candidates.
    82  	inlineCDFHotCallSiteThresholdPercent = float64(99)
    83  
    84  	// Budget increased due to hotness.
    85  	inlineHotMaxBudget int32 = 2000
    86  )
    87  
    88  func IsPgoHotFunc(fn *ir.Func, profile *pgoir.Profile) bool {
    89  	if profile == nil {
    90  		return false
    91  	}
    92  	if n, ok := profile.WeightedCG.IRNodes[ir.LinkFuncName(fn)]; ok {
    93  		_, ok := candHotCalleeMap[n]
    94  		return ok
    95  	}
    96  	return false
    97  }
    98  
    99  func HasPgoHotInline(fn *ir.Func) bool {
   100  	_, has := hasHotCall[fn]
   101  	return has
   102  }
   103  
   104  // PGOInlinePrologue records the hot callsites from ir-graph.
   105  func PGOInlinePrologue(p *pgoir.Profile) {
   106  	if base.Debug.PGOInlineCDFThreshold != "" {
   107  		if s, err := strconv.ParseFloat(base.Debug.PGOInlineCDFThreshold, 64); err == nil && s >= 0 && s <= 100 {
   108  			inlineCDFHotCallSiteThresholdPercent = s
   109  		} else {
   110  			base.Fatalf("invalid PGOInlineCDFThreshold, must be between 0 and 100")
   111  		}
   112  	}
   113  	var hotCallsites []pgo.NamedCallEdge
   114  	inlineHotCallSiteThresholdPercent, hotCallsites = hotNodesFromCDF(p)
   115  	if base.Debug.PGODebug > 0 {
   116  		fmt.Printf("hot-callsite-thres-from-CDF=%v\n", inlineHotCallSiteThresholdPercent)
   117  	}
   118  
   119  	if x := base.Debug.PGOInlineBudget; x != 0 {
   120  		inlineHotMaxBudget = int32(x)
   121  	}
   122  
   123  	for _, n := range hotCallsites {
   124  		// mark inlineable callees from hot edges
   125  		if callee := p.WeightedCG.IRNodes[n.CalleeName]; callee != nil {
   126  			candHotCalleeMap[callee] = struct{}{}
   127  		}
   128  		// mark hot call sites
   129  		if caller := p.WeightedCG.IRNodes[n.CallerName]; caller != nil && caller.AST != nil {
   130  			csi := pgoir.CallSiteInfo{LineOffset: n.CallSiteOffset, Caller: caller.AST}
   131  			candHotEdgeMap[csi] = struct{}{}
   132  		}
   133  	}
   134  
   135  	if base.Debug.PGODebug >= 3 {
   136  		fmt.Printf("hot-cg before inline in dot format:")
   137  		p.PrintWeightedCallGraphDOT(inlineHotCallSiteThresholdPercent)
   138  	}
   139  }
   140  
   141  // hotNodesFromCDF computes an edge weight threshold and the list of hot
   142  // nodes that make up the given percentage of the CDF. The threshold, as
   143  // a percent, is the lower bound of weight for nodes to be considered hot
   144  // (currently only used in debug prints) (in case of equal weights,
   145  // comparing with the threshold may not accurately reflect which nodes are
   146  // considered hot).
   147  func hotNodesFromCDF(p *pgoir.Profile) (float64, []pgo.NamedCallEdge) {
   148  	cum := int64(0)
   149  	for i, n := range p.NamedEdgeMap.ByWeight {
   150  		w := p.NamedEdgeMap.Weight[n]
   151  		cum += w
   152  		if pgo.WeightInPercentage(cum, p.TotalWeight) > inlineCDFHotCallSiteThresholdPercent {
   153  			// nodes[:i+1] to include the very last node that makes it to go over the threshold.
   154  			// (Say, if the CDF threshold is 50% and one hot node takes 60% of weight, we want to
   155  			// include that node instead of excluding it.)
   156  			return pgo.WeightInPercentage(w, p.TotalWeight), p.NamedEdgeMap.ByWeight[:i+1]
   157  		}
   158  	}
   159  	return 0, p.NamedEdgeMap.ByWeight
   160  }
   161  
   162  // CanInlineFuncs computes whether a batch of functions are inlinable.
   163  func CanInlineFuncs(funcs []*ir.Func, profile *pgoir.Profile) {
   164  	if profile != nil {
   165  		PGOInlinePrologue(profile)
   166  	}
   167  
   168  	if base.Flag.LowerL == 0 {
   169  		return
   170  	}
   171  
   172  	ir.VisitFuncsBottomUp(funcs, func(funcs []*ir.Func, recursive bool) {
   173  		for _, fn := range funcs {
   174  			CanInline(fn, profile)
   175  			if inlheur.Enabled() {
   176  				analyzeFuncProps(fn, profile)
   177  			}
   178  		}
   179  	})
   180  }
   181  
   182  func simdCreditMultiplier(fn *ir.Func) int32 {
   183  	for _, field := range fn.Type().RecvParamsResults() {
   184  		if field.Type.IsSIMD() {
   185  			return 3
   186  		}
   187  	}
   188  	// Sometimes code uses closures, that do not take simd
   189  	// parameters, to perform repetitive SIMD operations.
   190  	// fn.  These really need to be inlined, or the anticipated
   191  	// awesome SIMD performance will be missed.
   192  	for _, v := range fn.ClosureVars {
   193  		if v.Type().IsSIMD() {
   194  			return 11 // 11 ought to be enough.
   195  		}
   196  	}
   197  
   198  	return 1
   199  }
   200  
   201  // inlineBudget determines the max budget for function 'fn' prior to
   202  // analyzing the hairiness of the body of 'fn'. We pass in the pgo
   203  // profile if available (which can change the budget), also a
   204  // 'relaxed' flag, which expands the budget slightly to allow for the
   205  // possibility that a call to the function might have its score
   206  // adjusted downwards. If 'verbose' is set, then print a remark where
   207  // we boost the budget due to PGO.
   208  // Note that inlineCostOk has the final say on whether an inline will
   209  // happen; changes here merely make inlines possible.
   210  func inlineBudget(fn *ir.Func, profile *pgoir.Profile, relaxed bool, verbose bool) int32 {
   211  	// Update the budget for profile-guided inlining.
   212  	budget := int32(inlineMaxBudget)
   213  
   214  	budget *= simdCreditMultiplier(fn)
   215  
   216  	if IsPgoHotFunc(fn, profile) {
   217  		budget = inlineHotMaxBudget
   218  		if verbose {
   219  			fmt.Printf("hot-node enabled increased budget=%v for func=%v\n", budget, ir.PkgFuncName(fn))
   220  		}
   221  	}
   222  	if relaxed {
   223  		budget += inlheur.BudgetExpansion(inlineMaxBudget)
   224  	}
   225  	if fn.ClosureParent != nil {
   226  		// be very liberal here, if the closure is only called once, the budget is large
   227  		budget = max(budget, inlineClosureCalledOnceCost)
   228  	}
   229  
   230  	return budget
   231  }
   232  
   233  // CanInline determines whether fn is inlineable.
   234  // If so, CanInline saves copies of fn.Body and fn.Dcl in fn.Inl.
   235  // fn and fn.Body will already have been typechecked.
   236  func CanInline(fn *ir.Func, profile *pgoir.Profile) {
   237  	if fn.Nname == nil {
   238  		base.Fatalf("CanInline no nname %+v", fn)
   239  	}
   240  
   241  	var reason string // reason, if any, that the function was not inlined
   242  	if base.Flag.LowerM > 1 || logopt.Enabled() {
   243  		defer func() {
   244  			if reason != "" {
   245  				if base.Flag.LowerM > 1 {
   246  					fmt.Printf("%v: cannot inline %v: %s\n", ir.Line(fn), fn.Nname, reason)
   247  				}
   248  				if logopt.Enabled() {
   249  					logopt.LogOpt(fn.Pos(), "cannotInlineFunction", "inline", ir.FuncName(fn), reason)
   250  				}
   251  			}
   252  		}()
   253  	}
   254  
   255  	reason = InlineImpossible(fn)
   256  	if reason != "" {
   257  		return
   258  	}
   259  	if fn.Typecheck() == 0 {
   260  		base.Fatalf("CanInline on non-typechecked function %v", fn)
   261  	}
   262  
   263  	n := fn.Nname
   264  	if n.Func.InlinabilityChecked() {
   265  		return
   266  	}
   267  	defer n.Func.SetInlinabilityChecked(true)
   268  
   269  	cc := int32(inlineExtraCallCost)
   270  	if base.Flag.LowerL == 4 {
   271  		cc = 1 // this appears to yield better performance than 0.
   272  	}
   273  
   274  	// Used a "relaxed" inline budget if the new inliner is enabled.
   275  	relaxed := inlheur.Enabled()
   276  
   277  	// Compute the inline budget for this func.
   278  	budget := inlineBudget(fn, profile, relaxed, base.Debug.PGODebug > 0)
   279  
   280  	// At this point in the game the function we're looking at may
   281  	// have "stale" autos, vars that still appear in the Dcl list, but
   282  	// which no longer have any uses in the function body (due to
   283  	// elimination by deadcode). We'd like to exclude these dead vars
   284  	// when creating the "Inline.Dcl" field below; to accomplish this,
   285  	// the hairyVisitor below builds up a map of used/referenced
   286  	// locals, and we use this map to produce a pruned Inline.Dcl
   287  	// list. See issue 25459 for more context.
   288  
   289  	visitor := hairyVisitor{
   290  		curFunc:       fn,
   291  		debug:         isDebugFn(fn),
   292  		isBigFunc:     IsBigFunc(fn),
   293  		budget:        budget,
   294  		maxBudget:     budget,
   295  		extraCallCost: cc,
   296  		profile:       profile,
   297  	}
   298  	if visitor.tooHairy(fn) {
   299  		reason = visitor.reason
   300  		return
   301  	}
   302  
   303  	n.Func.Inl = &ir.Inline{
   304  		Cost:            budget - visitor.budget,
   305  		Dcl:             pruneUnusedAutos(n.Func.Dcl, &visitor),
   306  		HaveDcl:         true,
   307  		CanDelayResults: canDelayResults(fn),
   308  	}
   309  	if base.Flag.LowerM != 0 || logopt.Enabled() {
   310  		noteInlinableFunc(n, fn, budget-visitor.budget)
   311  	}
   312  }
   313  
   314  // noteInlinableFunc issues a message to the user that the specified
   315  // function is inlinable.
   316  func noteInlinableFunc(n *ir.Name, fn *ir.Func, cost int32) {
   317  	if base.Flag.LowerM > 1 {
   318  		fmt.Printf("%v: can inline %v with cost %d as: %v { %v }\n", ir.Line(fn), n, cost, fn.Type(), fn.Body)
   319  	} else if base.Flag.LowerM != 0 {
   320  		fmt.Printf("%v: can inline %v\n", ir.Line(fn), n)
   321  	}
   322  	// JSON optimization log output.
   323  	if logopt.Enabled() {
   324  		logopt.LogOpt(fn.Pos(), "canInlineFunction", "inline", ir.FuncName(fn), fmt.Sprintf("cost: %d", cost))
   325  	}
   326  }
   327  
   328  // InlineImpossible returns a non-empty reason string if fn is impossible to
   329  // inline regardless of cost or contents.
   330  func InlineImpossible(fn *ir.Func) string {
   331  	var reason string // reason, if any, that the function can not be inlined.
   332  	if fn.Nname == nil {
   333  		reason = "no name"
   334  		return reason
   335  	}
   336  
   337  	// If marked "go:noinline", don't inline.
   338  	if fn.Pragma&ir.Noinline != 0 {
   339  		reason = "marked go:noinline"
   340  		return reason
   341  	}
   342  
   343  	// If marked "go:norace" and -race compilation, don't inline.
   344  	if base.Flag.Race && fn.Pragma&ir.Norace != 0 {
   345  		reason = "marked go:norace with -race compilation"
   346  		return reason
   347  	}
   348  
   349  	// If marked "go:nocheckptr" and -d checkptr compilation, don't inline.
   350  	if base.Debug.Checkptr != 0 && fn.Pragma&ir.NoCheckPtr != 0 {
   351  		reason = "marked go:nocheckptr"
   352  		return reason
   353  	}
   354  
   355  	// If marked "go:cgo_unsafe_args", don't inline, since the function
   356  	// makes assumptions about its argument frame layout.
   357  	if fn.Pragma&ir.CgoUnsafeArgs != 0 {
   358  		reason = "marked go:cgo_unsafe_args"
   359  		return reason
   360  	}
   361  
   362  	// If marked as "go:uintptrkeepalive", don't inline, since the keep
   363  	// alive information is lost during inlining.
   364  	//
   365  	// TODO(prattmic): This is handled on calls during escape analysis,
   366  	// which is after inlining. Move prior to inlining so the keep-alive is
   367  	// maintained after inlining.
   368  	if fn.Pragma&ir.UintptrKeepAlive != 0 {
   369  		reason = "marked as having a keep-alive uintptr argument"
   370  		return reason
   371  	}
   372  
   373  	// If marked as "go:uintptrescapes", don't inline, since the escape
   374  	// information is lost during inlining.
   375  	if fn.Pragma&ir.UintptrEscapes != 0 {
   376  		reason = "marked as having an escaping uintptr argument"
   377  		return reason
   378  	}
   379  
   380  	// The nowritebarrierrec checker currently works at function
   381  	// granularity, so inlining yeswritebarrierrec functions can confuse it
   382  	// (#22342). As a workaround, disallow inlining them for now.
   383  	if fn.Pragma&ir.Yeswritebarrierrec != 0 {
   384  		reason = "marked go:yeswritebarrierrec"
   385  		return reason
   386  	}
   387  
   388  	// If a local function has no fn.Body (is defined outside of Go), cannot inline it.
   389  	// Imported functions don't have fn.Body but might have inline body in fn.Inl.
   390  	if len(fn.Body) == 0 && !typecheck.HaveInlineBody(fn) {
   391  		reason = "no function body"
   392  		return reason
   393  	}
   394  
   395  	return ""
   396  }
   397  
   398  // canDelayResults reports whether inlined calls to fn can delay
   399  // declaring the result parameter until the "return" statement.
   400  func canDelayResults(fn *ir.Func) bool {
   401  	// We can delay declaring+initializing result parameters if:
   402  	// (1) there's exactly one "return" statement in the inlined function;
   403  	// (2) it's not an empty return statement (#44355); and
   404  	// (3) the result parameters aren't named.
   405  
   406  	nreturns := 0
   407  	ir.VisitList(fn.Body, func(n ir.Node) {
   408  		if n, ok := n.(*ir.ReturnStmt); ok {
   409  			nreturns++
   410  			if len(n.Results) == 0 {
   411  				nreturns++ // empty return statement (case 2)
   412  			}
   413  		}
   414  	})
   415  
   416  	if nreturns != 1 {
   417  		return false // not exactly one return statement (case 1)
   418  	}
   419  
   420  	// temporaries for return values.
   421  	for _, param := range fn.Type().Results() {
   422  		if sym := param.Sym; sym != nil && !sym.IsBlank() {
   423  			return false // found a named result parameter (case 3)
   424  		}
   425  	}
   426  
   427  	return true
   428  }
   429  
   430  // hairyVisitor visits a function body to determine its inlining
   431  // hairiness and whether or not it can be inlined.
   432  type hairyVisitor struct {
   433  	// This is needed to access the current caller in the doNode function.
   434  	curFunc       *ir.Func
   435  	isBigFunc     bool
   436  	debug         bool
   437  	budget        int32
   438  	maxBudget     int32
   439  	reason        string
   440  	extraCallCost int32
   441  	usedLocals    ir.NameSet
   442  	do            func(ir.Node) bool
   443  	profile       *pgoir.Profile
   444  }
   445  
   446  func isDebugFn(fn *ir.Func) bool {
   447  	// if n := fn.Nname; n != nil {
   448  	// 	if n.Sym().Name == "Int32x8.Transpose8" && n.Sym().Pkg.Path == "simd/archsimd" {
   449  	// 		fmt.Printf("isDebugFn '%s' DOT '%s'\n", n.Sym().Pkg.Path, n.Sym().Name)
   450  	// 		return true
   451  	// 	}
   452  	// }
   453  	return false
   454  }
   455  
   456  func (v *hairyVisitor) tooHairy(fn *ir.Func) bool {
   457  	v.do = v.doNode // cache closure
   458  	if ir.DoChildren(fn, v.do) {
   459  		return true
   460  	}
   461  	if v.budget < 0 {
   462  		v.reason = fmt.Sprintf("function too complex: cost %d exceeds budget %d", v.maxBudget-v.budget, v.maxBudget)
   463  		return true
   464  	}
   465  	return false
   466  }
   467  
   468  // doNode visits n and its children, updates the state in v, and returns true if
   469  // n makes the current function too hairy for inlining.
   470  func (v *hairyVisitor) doNode(n ir.Node) bool {
   471  	if n == nil {
   472  		return false
   473  	}
   474  	if v.debug {
   475  		fmt.Printf("%v: doNode %v budget is %d\n", ir.Line(n), n.Op(), v.budget)
   476  	}
   477  opSwitch:
   478  	switch n.Op() {
   479  	// Call is okay if inlinable and we have the budget for the body.
   480  	case ir.OCALLFUNC:
   481  		n := n.(*ir.CallExpr)
   482  		var cheap bool
   483  		if n.Fun.Op() == ir.ONAME {
   484  			name := n.Fun.(*ir.Name)
   485  			if name.Class == ir.PFUNC {
   486  				s := name.Sym()
   487  				fn := s.Name
   488  				switch s.Pkg.Path {
   489  				case "internal/abi":
   490  					switch fn {
   491  					case "NoEscape":
   492  						// Special case for internal/abi.NoEscape. It does just type
   493  						// conversions to appease the escape analysis, and doesn't
   494  						// generate code.
   495  						cheap = true
   496  					}
   497  					if strings.HasPrefix(fn, "EscapeNonString[") {
   498  						// internal/abi.EscapeNonString[T] is a compiler intrinsic
   499  						// implemented in the escape analysis phase.
   500  						cheap = true
   501  					}
   502  				case "internal/runtime/sys":
   503  					switch fn {
   504  					case "GetCallerPC", "GetCallerSP":
   505  						// Functions that call GetCallerPC/SP can not be inlined
   506  						// because users expect the PC/SP of the logical caller,
   507  						// but GetCallerPC/SP returns the physical caller.
   508  						v.reason = "call to " + fn
   509  						return true
   510  					}
   511  				case "go.runtime":
   512  					switch fn {
   513  					case "throw":
   514  						// runtime.throw is a "cheap call" like panic in normal code.
   515  						v.budget -= inlineExtraThrowCost
   516  						break opSwitch
   517  					case "panicrangestate":
   518  						cheap = true
   519  					case "deferrangefunc":
   520  						v.reason = "defer call in range func"
   521  						return true
   522  					}
   523  				}
   524  			}
   525  			// Special case for coverage counter updates; although
   526  			// these correspond to real operations, we treat them as
   527  			// zero cost for the moment. This is due to the existence
   528  			// of tests that are sensitive to inlining-- if the
   529  			// insertion of coverage instrumentation happens to tip a
   530  			// given function over the threshold and move it from
   531  			// "inlinable" to "not-inlinable", this can cause changes
   532  			// in allocation behavior, which can then result in test
   533  			// failures (a good example is the TestAllocations in
   534  			// crypto/ed25519).
   535  			if isAtomicCoverageCounterUpdate(n) {
   536  				return false
   537  			}
   538  		}
   539  		if n.Fun.Op() == ir.OMETHEXPR {
   540  			if meth := ir.MethodExprName(n.Fun); meth != nil {
   541  				if fn := meth.Func; fn != nil {
   542  					s := fn.Sym()
   543  					if types.RuntimeSymName(s) == "heapBits.nextArena" {
   544  						// Special case: explicitly allow mid-stack inlining of
   545  						// runtime.heapBits.next even though it calls slow-path
   546  						// runtime.heapBits.nextArena.
   547  						cheap = true
   548  					}
   549  					// Special case: on architectures that can do unaligned loads,
   550  					// explicitly mark encoding/binary methods as cheap,
   551  					// because in practice they are, even though our inlining
   552  					// budgeting system does not see that. See issue 42958.
   553  					if base.Ctxt.Arch.CanMergeLoads && s.Pkg.Path == "encoding/binary" {
   554  						switch s.Name {
   555  						case "littleEndian.Uint64", "littleEndian.Uint32", "littleEndian.Uint16",
   556  							"bigEndian.Uint64", "bigEndian.Uint32", "bigEndian.Uint16",
   557  							"littleEndian.PutUint64", "littleEndian.PutUint32", "littleEndian.PutUint16",
   558  							"bigEndian.PutUint64", "bigEndian.PutUint32", "bigEndian.PutUint16",
   559  							"littleEndian.AppendUint64", "littleEndian.AppendUint32", "littleEndian.AppendUint16",
   560  							"bigEndian.AppendUint64", "bigEndian.AppendUint32", "bigEndian.AppendUint16":
   561  							cheap = true
   562  						}
   563  					}
   564  				}
   565  			}
   566  		}
   567  
   568  		// A call to a parameter is optimistically a cheap call, if it's a constant function
   569  		// perhaps it will inline, it also can simplify escape analysis.
   570  		extraCost := v.extraCallCost
   571  
   572  		if n.Fun.Op() == ir.ONAME {
   573  			name := n.Fun.(*ir.Name)
   574  			if name.Class == ir.PFUNC {
   575  				// Special case: on architectures that can do unaligned loads,
   576  				// explicitly mark internal/byteorder methods as cheap,
   577  				// because in practice they are, even though our inlining
   578  				// budgeting system does not see that. See issue 42958.
   579  				if base.Ctxt.Arch.CanMergeLoads && name.Sym().Pkg.Path == "internal/byteorder" {
   580  					switch name.Sym().Name {
   581  					case "LEUint64", "LEUint32", "LEUint16",
   582  						"BEUint64", "BEUint32", "BEUint16",
   583  						"LEPutUint64", "LEPutUint32", "LEPutUint16",
   584  						"BEPutUint64", "BEPutUint32", "BEPutUint16",
   585  						"LEAppendUint64", "LEAppendUint32", "LEAppendUint16",
   586  						"BEAppendUint64", "BEAppendUint32", "BEAppendUint16":
   587  						cheap = true
   588  					}
   589  				}
   590  			}
   591  			if name.Class == ir.PPARAM || name.Class == ir.PAUTOHEAP && name.IsClosureVar() {
   592  				extraCost = min(extraCost, inlineParamCallCost)
   593  			}
   594  		}
   595  
   596  		if cheap {
   597  			if v.debug {
   598  				if ir.IsIntrinsicCall(n) {
   599  					fmt.Printf("%v: cheap call is also intrinsic, %v\n", ir.Line(n), n)
   600  				}
   601  			}
   602  			break // treat like any other node, that is, cost of 1
   603  		}
   604  
   605  		if ir.IsIntrinsicCall(n) {
   606  			if v.debug {
   607  				fmt.Printf("%v: intrinsic call, %v\n", ir.Line(n), n)
   608  			}
   609  			break // Treat like any other node.
   610  		}
   611  
   612  		if callee := inlCallee(v.curFunc, n.Fun, v.profile, false); callee != nil && typecheck.HaveInlineBody(callee) {
   613  			// Check whether we'd actually inline this call. Set
   614  			// log == false since we aren't actually doing inlining
   615  			// yet.
   616  			if ok, _, _ := canInlineCallExpr(v.curFunc, n, callee, v.isBigFunc, false, false); ok {
   617  				// mkinlcall would inline this call [1], so use
   618  				// the cost of the inline body as the cost of
   619  				// the call, as that is what will actually
   620  				// appear in the code.
   621  				//
   622  				// [1] This is almost a perfect match to the
   623  				// mkinlcall logic, except that
   624  				// canInlineCallExpr considers inlining cycles
   625  				// by looking at what has already been inlined.
   626  				// Since we haven't done any inlining yet we
   627  				// will miss those.
   628  				//
   629  				// TODO: in the case of a single-call closure, the inlining budget here is potentially much, much larger.
   630  				//
   631  				v.budget -= callee.Inl.Cost
   632  				break
   633  			}
   634  		}
   635  
   636  		if v.debug {
   637  			fmt.Printf("%v: costly OCALLFUNC %v\n", ir.Line(n), n)
   638  		}
   639  
   640  		// Call cost for non-leaf inlining.
   641  		v.budget -= extraCost
   642  
   643  	case ir.OCALLMETH:
   644  		base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
   645  
   646  	// Things that are too hairy, irrespective of the budget
   647  	case ir.OCALL, ir.OCALLINTER:
   648  		// Call cost for non-leaf inlining.
   649  		if v.debug {
   650  			fmt.Printf("%v: costly OCALL %v\n", ir.Line(n), n)
   651  		}
   652  		v.budget -= v.extraCallCost
   653  
   654  	case ir.OPANIC:
   655  		n := n.(*ir.UnaryExpr)
   656  		if n.X.Op() == ir.OCONVIFACE && n.X.(*ir.ConvExpr).Implicit() {
   657  			// Hack to keep reflect.flag.mustBe inlinable for TestIntendedInlining.
   658  			// Before CL 284412, these conversions were introduced later in the
   659  			// compiler, so they didn't count against inlining budget.
   660  			v.budget++
   661  		}
   662  		v.budget -= inlineExtraPanicCost
   663  
   664  	case ir.ORECOVER:
   665  		// TODO: maybe we could allow inlining of recover() now?
   666  		v.reason = "call to recover"
   667  		return true
   668  
   669  	case ir.OCLOSURE:
   670  		if base.Debug.InlFuncsWithClosures == 0 {
   671  			v.reason = "not inlining functions with closures"
   672  			return true
   673  		}
   674  
   675  		// TODO(danscales): Maybe make budget proportional to number of closure
   676  		// variables, e.g.:
   677  		//v.budget -= int32(len(n.(*ir.ClosureExpr).Func.ClosureVars) * 3)
   678  		// TODO(austin): However, if we're able to inline this closure into
   679  		// v.curFunc, then we actually pay nothing for the closure captures. We
   680  		// should try to account for that if we're going to account for captures.
   681  		v.budget -= 15
   682  
   683  	case ir.OGO, ir.ODEFER, ir.OTAILCALL:
   684  		v.reason = "unhandled op " + n.Op().String()
   685  		return true
   686  
   687  	case ir.OAPPEND:
   688  		v.budget -= inlineExtraAppendCost
   689  
   690  	case ir.OADDR:
   691  		n := n.(*ir.AddrExpr)
   692  		// Make "&s.f" cost 0 when f's offset is zero.
   693  		if dot, ok := n.X.(*ir.SelectorExpr); ok && (dot.Op() == ir.ODOT || dot.Op() == ir.ODOTPTR) {
   694  			if _, ok := dot.X.(*ir.Name); ok && dot.Selection.Offset == 0 {
   695  				v.budget += 2 // undo ir.OADDR+ir.ODOT/ir.ODOTPTR
   696  			}
   697  		}
   698  
   699  	case ir.ODEREF:
   700  		// *(*X)(unsafe.Pointer(&x)) is low-cost
   701  		n := n.(*ir.StarExpr)
   702  
   703  		ptr := n.X
   704  		for ptr.Op() == ir.OCONVNOP {
   705  			ptr = ptr.(*ir.ConvExpr).X
   706  		}
   707  		if ptr.Op() == ir.OADDR {
   708  			v.budget += 1 // undo half of default cost of ir.ODEREF+ir.OADDR
   709  		}
   710  
   711  	case ir.OCONVNOP:
   712  		// This doesn't produce code, but the children might.
   713  		v.budget++ // undo default cost
   714  
   715  	case ir.OFALL, ir.OTYPE:
   716  		// These nodes don't produce code; omit from inlining budget.
   717  		return false
   718  
   719  	case ir.OIF:
   720  		n := n.(*ir.IfStmt)
   721  		if ir.IsConst(n.Cond, constant.Bool) {
   722  			// This if and the condition cost nothing.
   723  			if doList(n.Init(), v.do) {
   724  				return true
   725  			}
   726  			if ir.BoolVal(n.Cond) {
   727  				return doList(n.Body, v.do)
   728  			} else {
   729  				return doList(n.Else, v.do)
   730  			}
   731  		}
   732  
   733  	case ir.ONAME:
   734  		n := n.(*ir.Name)
   735  		if n.Class == ir.PAUTO {
   736  			v.usedLocals.Add(n)
   737  		}
   738  
   739  	case ir.OBLOCK:
   740  		// The only OBLOCK we should see at this point is an empty one.
   741  		// In any event, let the visitList(n.List()) below take care of the statements,
   742  		// and don't charge for the OBLOCK itself. The ++ undoes the -- below.
   743  		v.budget++
   744  
   745  	case ir.OMETHVALUE, ir.OSLICELIT:
   746  		v.budget-- // Hack for toolstash -cmp.
   747  
   748  	case ir.OMETHEXPR:
   749  		v.budget++ // Hack for toolstash -cmp.
   750  
   751  	case ir.OAS2:
   752  		n := n.(*ir.AssignListStmt)
   753  
   754  		// Unified IR unconditionally rewrites:
   755  		//
   756  		//	a, b = f()
   757  		//
   758  		// into:
   759  		//
   760  		//	DCL tmp1
   761  		//	DCL tmp2
   762  		//	tmp1, tmp2 = f()
   763  		//	a, b = tmp1, tmp2
   764  		//
   765  		// so that it can insert implicit conversions as necessary. To
   766  		// minimize impact to the existing inlining heuristics (in
   767  		// particular, to avoid breaking the existing inlinability regress
   768  		// tests), we need to compensate for this here.
   769  		//
   770  		// See also identical logic in IsBigFunc.
   771  		if len(n.Rhs) > 0 {
   772  			if init := n.Rhs[0].Init(); len(init) == 1 {
   773  				if _, ok := init[0].(*ir.AssignListStmt); ok {
   774  					// 4 for each value, because each temporary variable now
   775  					// appears 3 times (DCL, LHS, RHS), plus an extra DCL node.
   776  					//
   777  					// 1 for the extra "tmp1, tmp2 = f()" assignment statement.
   778  					v.budget += 4*int32(len(n.Lhs)) + 1
   779  				}
   780  			}
   781  		}
   782  
   783  	case ir.OAS:
   784  		// Special case for coverage counter updates and coverage
   785  		// function registrations. Although these correspond to real
   786  		// operations, we treat them as zero cost for the moment. This
   787  		// is primarily due to the existence of tests that are
   788  		// sensitive to inlining-- if the insertion of coverage
   789  		// instrumentation happens to tip a given function over the
   790  		// threshold and move it from "inlinable" to "not-inlinable",
   791  		// this can cause changes in allocation behavior, which can
   792  		// then result in test failures (a good example is the
   793  		// TestAllocations in crypto/ed25519).
   794  		n := n.(*ir.AssignStmt)
   795  		if n.X.Op() == ir.OINDEX && isIndexingCoverageCounter(n.X) {
   796  			return false
   797  		}
   798  
   799  	case ir.OSLICE, ir.OSLICEARR, ir.OSLICESTR, ir.OSLICE3, ir.OSLICE3ARR:
   800  		n := n.(*ir.SliceExpr)
   801  
   802  		// Ignore superfluous slicing.
   803  		if n.Low != nil && n.Low.Op() == ir.OLITERAL && ir.Int64Val(n.Low) == 0 {
   804  			v.budget++
   805  		}
   806  		if n.High != nil && n.High.Op() == ir.OLEN && n.High.(*ir.UnaryExpr).X == n.X {
   807  			v.budget += 2
   808  		}
   809  	}
   810  
   811  	v.budget--
   812  
   813  	// When debugging, don't stop early, to get full cost of inlining this function
   814  	if v.budget < 0 && base.Flag.LowerM < 2 && !logopt.Enabled() && !v.debug {
   815  		v.reason = "too expensive"
   816  		return true
   817  	}
   818  
   819  	return ir.DoChildren(n, v.do)
   820  }
   821  
   822  // IsBigFunc reports whether fn is a "big" function.
   823  //
   824  // Note: The criteria for "big" is heuristic and subject to change.
   825  func IsBigFunc(fn *ir.Func) bool {
   826  	budget := inlineBigFunctionNodes
   827  	return ir.Any(fn, func(n ir.Node) bool {
   828  		// See logic in hairyVisitor.doNode, explaining unified IR's
   829  		// handling of "a, b = f()" assignments.
   830  		if n, ok := n.(*ir.AssignListStmt); ok && n.Op() == ir.OAS2 && len(n.Rhs) > 0 {
   831  			if init := n.Rhs[0].Init(); len(init) == 1 {
   832  				if _, ok := init[0].(*ir.AssignListStmt); ok {
   833  					budget += 4*len(n.Lhs) + 1
   834  				}
   835  			}
   836  		}
   837  
   838  		budget--
   839  		return budget <= 0
   840  	})
   841  }
   842  
   843  // inlineCallCheck returns whether a call will never be inlineable
   844  // for basic reasons, and whether the call is an intrinisic call.
   845  // The intrinsic result singles out intrinsic calls for debug logging.
   846  func inlineCallCheck(callerfn *ir.Func, call *ir.CallExpr) (bool, bool) {
   847  	if base.Flag.LowerL == 0 {
   848  		return false, false
   849  	}
   850  	if call.Op() != ir.OCALLFUNC {
   851  		return false, false
   852  	}
   853  	if call.GoDefer || call.NoInline {
   854  		return false, false
   855  	}
   856  
   857  	// Prevent inlining some reflect.Value methods when using checkptr,
   858  	// even when package reflect was compiled without it (#35073).
   859  	if base.Debug.Checkptr != 0 && call.Fun.Op() == ir.OMETHEXPR {
   860  		if method := ir.MethodExprName(call.Fun); method != nil {
   861  			switch types.ReflectSymName(method.Sym()) {
   862  			case "Value.UnsafeAddr", "Value.Pointer":
   863  				return false, false
   864  			}
   865  		}
   866  	}
   867  
   868  	// internal/abi.EscapeNonString[T] is a compiler intrinsic implemented
   869  	// in the escape analysis phase.
   870  	if fn := ir.StaticCalleeName(call.Fun); fn != nil && fn.Sym().Pkg.Path == "internal/abi" &&
   871  		strings.HasPrefix(fn.Sym().Name, "EscapeNonString[") {
   872  		return false, true
   873  	}
   874  
   875  	if ir.IsIntrinsicCall(call) {
   876  		return false, true
   877  	}
   878  	return true, false
   879  }
   880  
   881  // InlineCallTarget returns the resolved-for-inlining target of a call.
   882  // It does not necessarily guarantee that the target can be inlined, though
   883  // obvious exclusions are applied.
   884  func InlineCallTarget(callerfn *ir.Func, call *ir.CallExpr, profile *pgoir.Profile) *ir.Func {
   885  	if mightInline, _ := inlineCallCheck(callerfn, call); !mightInline {
   886  		return nil
   887  	}
   888  	return inlCallee(callerfn, call.Fun, profile, true)
   889  }
   890  
   891  // TryInlineCall returns an inlined call expression for call, or nil
   892  // if inlining is not possible.
   893  func TryInlineCall(callerfn *ir.Func, call *ir.CallExpr, bigCaller bool, profile *pgoir.Profile, closureCalledOnce bool) *ir.InlinedCallExpr {
   894  	mightInline, isIntrinsic := inlineCallCheck(callerfn, call)
   895  
   896  	// Preserve old logging behavior
   897  	if (mightInline || isIntrinsic) && base.Flag.LowerM > 3 {
   898  		fmt.Printf("%v:call to func %+v\n", ir.Line(call), call.Fun)
   899  	}
   900  	if !mightInline {
   901  		return nil
   902  	}
   903  
   904  	if fn := inlCallee(callerfn, call.Fun, profile, false); fn != nil && typecheck.HaveInlineBody(fn) {
   905  		return mkinlcall(callerfn, call, fn, bigCaller, closureCalledOnce)
   906  	}
   907  	return nil
   908  }
   909  
   910  // inlCallee takes a function-typed expression and returns the underlying function ONAME
   911  // that it refers to if statically known. Otherwise, it returns nil.
   912  // resolveOnly skips cost-based inlineability checks for closures; the result may not actually be inlineable.
   913  func inlCallee(caller *ir.Func, fn ir.Node, profile *pgoir.Profile, resolveOnly bool) (res *ir.Func) {
   914  	fn = ir.StaticValue(fn)
   915  	switch fn.Op() {
   916  	case ir.OMETHEXPR:
   917  		fn := fn.(*ir.SelectorExpr)
   918  		n := ir.MethodExprName(fn)
   919  		// Check that receiver type matches fn.X.
   920  		// TODO(mdempsky): Handle implicit dereference
   921  		// of pointer receiver argument?
   922  		if n == nil || !types.Identical(n.Type().Recv().Type, fn.X.Type()) {
   923  			return nil
   924  		}
   925  		return n.Func
   926  	case ir.ONAME:
   927  		fn := fn.(*ir.Name)
   928  		if fn.Class == ir.PFUNC {
   929  			return fn.Func
   930  		}
   931  	case ir.OCLOSURE:
   932  		fn := fn.(*ir.ClosureExpr)
   933  		c := fn.Func
   934  		if len(c.ClosureVars) != 0 && c.ClosureVars[0].Outer.Curfn != caller {
   935  			return nil // inliner doesn't support inlining across closure frames
   936  		}
   937  		if !resolveOnly {
   938  			CanInline(c, profile)
   939  		}
   940  		return c
   941  	}
   942  	return nil
   943  }
   944  
   945  var inlgen int
   946  
   947  // SSADumpInline gives the SSA back end a chance to dump the function
   948  // when producing output for debugging the compiler itself.
   949  var SSADumpInline = func(*ir.Func) {}
   950  
   951  // InlineCall allows the inliner implementation to be overridden.
   952  // If it returns nil, the function will not be inlined.
   953  var InlineCall = func(callerfn *ir.Func, call *ir.CallExpr, fn *ir.Func, inlIndex int) *ir.InlinedCallExpr {
   954  	base.Fatalf("inline.InlineCall not overridden")
   955  	panic("unreachable")
   956  }
   957  
   958  // inlineCostOK returns true if call n from caller to callee is cheap enough to
   959  // inline. bigCaller indicates that caller is a big function.
   960  //
   961  // In addition to the "cost OK" boolean, it also returns
   962  //   - the "max cost" limit used to make the decision (which may differ depending on func size)
   963  //   - the score assigned to this specific callsite
   964  //   - whether the inlined function is "hot" according to PGO.
   965  func inlineCostOK(n *ir.CallExpr, caller, callee *ir.Func, bigCaller, closureCalledOnce bool) (bool, int32, int32, bool) {
   966  	maxCost := int32(inlineMaxBudget)
   967  
   968  	if bigCaller {
   969  		// We use this to restrict inlining into very big functions.
   970  		// See issue 26546 and 17566.
   971  		maxCost = inlineBigFunctionMaxCost
   972  	}
   973  
   974  	simdMaxCost := simdCreditMultiplier(callee) * maxCost
   975  
   976  	if callee.ClosureParent != nil {
   977  		maxCost *= 2           // favor inlining closures
   978  		if closureCalledOnce { // really favor inlining the one call to this closure
   979  			maxCost = max(maxCost, inlineClosureCalledOnceCost)
   980  		}
   981  	}
   982  
   983  	maxCost = max(maxCost, simdMaxCost)
   984  
   985  	metric := callee.Inl.Cost
   986  	if inlheur.Enabled() {
   987  		score, ok := inlheur.GetCallSiteScore(caller, n)
   988  		if ok {
   989  			metric = int32(score)
   990  		}
   991  	}
   992  
   993  	lineOffset := pgoir.NodeLineOffset(n, caller)
   994  	csi := pgoir.CallSiteInfo{LineOffset: lineOffset, Caller: caller}
   995  	_, hot := candHotEdgeMap[csi]
   996  
   997  	if metric <= maxCost {
   998  		// Simple case. Function is already cheap enough.
   999  		return true, 0, metric, hot
  1000  	}
  1001  
  1002  	// We'll also allow inlining of hot functions below inlineHotMaxBudget,
  1003  	// but only in small functions.
  1004  
  1005  	if !hot {
  1006  		// Cold
  1007  		return false, maxCost, metric, false
  1008  	}
  1009  
  1010  	// Hot
  1011  
  1012  	if bigCaller {
  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))
  1015  		}
  1016  		return false, maxCost, metric, false
  1017  	}
  1018  
  1019  	if metric > inlineHotMaxBudget {
  1020  		return false, inlineHotMaxBudget, metric, false
  1021  	}
  1022  
  1023  	if !base.PGOHash.MatchPosWithInfo(n.Pos(), "inline", nil) {
  1024  		// De-selected by PGO Hash.
  1025  		return false, maxCost, metric, false
  1026  	}
  1027  
  1028  	if base.Debug.PGODebug > 0 {
  1029  		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  	}
  1031  
  1032  	return true, 0, metric, hot
  1033  }
  1034  
  1035  // parsePos returns all the inlining positions and the innermost position.
  1036  func parsePos(pos src.XPos, posTmp []src.Pos) ([]src.Pos, src.Pos) {
  1037  	ctxt := base.Ctxt
  1038  	ctxt.AllPos(pos, func(p src.Pos) {
  1039  		posTmp = append(posTmp, p)
  1040  	})
  1041  	l := len(posTmp) - 1
  1042  	return posTmp[:l], posTmp[l]
  1043  }
  1044  
  1045  // canInlineCallExpr returns true if the call n from caller to callee
  1046  // can be inlined, plus the score computed for the call expr in question,
  1047  // and whether the callee is hot according to PGO.
  1048  // bigCaller indicates that caller is a big function. log
  1049  // indicates that the 'cannot inline' reason should be logged.
  1050  //
  1051  // Preconditions: CanInline(callee) has already been called.
  1052  func canInlineCallExpr(callerfn *ir.Func, n *ir.CallExpr, callee *ir.Func, bigCaller, closureCalledOnce bool, log bool) (bool, int32, bool) {
  1053  	if callee.Inl == nil {
  1054  		// callee is never inlinable.
  1055  		if log && logopt.Enabled() {
  1056  			logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
  1057  				fmt.Sprintf("%s cannot be inlined", ir.PkgFuncName(callee)))
  1058  		}
  1059  		return false, 0, false
  1060  	}
  1061  
  1062  	ok, maxCost, callSiteScore, hot := inlineCostOK(n, callerfn, callee, bigCaller, closureCalledOnce)
  1063  	if !ok {
  1064  		// callee cost too high for this call site.
  1065  		if log && logopt.Enabled() {
  1066  			logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
  1067  				fmt.Sprintf("cost %d of %s exceeds max caller cost %d", callee.Inl.Cost, ir.PkgFuncName(callee), maxCost))
  1068  		}
  1069  		return false, 0, false
  1070  	}
  1071  
  1072  	callees, calleeInner := parsePos(n.Pos(), make([]src.Pos, 0, 10))
  1073  
  1074  	for _, p := range callees {
  1075  		if p.Line() == calleeInner.Line() && p.Col() == calleeInner.Col() && p.AbsFilename() == calleeInner.AbsFilename() {
  1076  			if log && logopt.Enabled() {
  1077  				logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", fmt.Sprintf("recursive call to %s", ir.FuncName(callerfn)))
  1078  			}
  1079  			return false, 0, false
  1080  		}
  1081  	}
  1082  
  1083  	if base.Flag.Cfg.Instrumenting && types.IsNoInstrumentPkg(callee.Sym().Pkg) {
  1084  		// Runtime package must not be instrumented.
  1085  		// Instrument skips runtime package. However, some runtime code can be
  1086  		// inlined into other packages and instrumented there. To avoid this,
  1087  		// we disable inlining of runtime functions when instrumenting.
  1088  		// The example that we observed is inlining of LockOSThread,
  1089  		// which lead to false race reports on m contents.
  1090  		if log && logopt.Enabled() {
  1091  			logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
  1092  				fmt.Sprintf("call to runtime function %s in instrumented build", ir.PkgFuncName(callee)))
  1093  		}
  1094  		return false, 0, false
  1095  	}
  1096  
  1097  	if base.Flag.Race && types.IsNoRacePkg(callee.Sym().Pkg) {
  1098  		if log && logopt.Enabled() {
  1099  			logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
  1100  				fmt.Sprintf(`call to into "no-race" package function %s in race build`, ir.PkgFuncName(callee)))
  1101  		}
  1102  		return false, 0, false
  1103  	}
  1104  
  1105  	if base.Debug.Checkptr != 0 && types.IsRuntimePkg(callee.Sym().Pkg) {
  1106  		// We don't instrument runtime packages for checkptr (see base/flag.go).
  1107  		if log && logopt.Enabled() {
  1108  			logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
  1109  				fmt.Sprintf(`call to into runtime package function %s in -d=checkptr build`, ir.PkgFuncName(callee)))
  1110  		}
  1111  		return false, 0, false
  1112  	}
  1113  
  1114  	// Check if we've already inlined this function at this particular
  1115  	// call site, in order to stop inlining when we reach the beginning
  1116  	// of a recursion cycle again. We don't inline immediately recursive
  1117  	// functions, but allow inlining if there is a recursion cycle of
  1118  	// many functions. Most likely, the inlining will stop before we
  1119  	// even hit the beginning of the cycle again, but this catches the
  1120  	// unusual case.
  1121  	parent := base.Ctxt.PosTable.Pos(n.Pos()).Base().InliningIndex()
  1122  	sym := callee.Linksym()
  1123  	for inlIndex := parent; inlIndex >= 0; inlIndex = base.Ctxt.InlTree.Parent(inlIndex) {
  1124  		if base.Ctxt.InlTree.InlinedFunction(inlIndex) == sym {
  1125  			if log {
  1126  				if base.Flag.LowerM > 1 {
  1127  					fmt.Printf("%v: cannot inline %v into %v: repeated recursive cycle\n", ir.Line(n), callee, ir.FuncName(callerfn))
  1128  				}
  1129  				if logopt.Enabled() {
  1130  					logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
  1131  						fmt.Sprintf("repeated recursive cycle to %s", ir.PkgFuncName(callee)))
  1132  				}
  1133  			}
  1134  			return false, 0, false
  1135  		}
  1136  	}
  1137  
  1138  	return true, callSiteScore, hot
  1139  }
  1140  
  1141  // mkinlcall returns an OINLCALL node that can replace OCALLFUNC n, or
  1142  // nil if it cannot be inlined. callerfn is the function that contains
  1143  // n, and fn is the function being called.
  1144  //
  1145  // The result of mkinlcall MUST be assigned back to n, e.g.
  1146  //
  1147  //	n.Left = mkinlcall(n.Left, fn, isddd)
  1148  func mkinlcall(callerfn *ir.Func, n *ir.CallExpr, fn *ir.Func, bigCaller, closureCalledOnce bool) *ir.InlinedCallExpr {
  1149  	ok, score, hot := canInlineCallExpr(callerfn, n, fn, bigCaller, closureCalledOnce, true)
  1150  	if !ok {
  1151  		return nil
  1152  	}
  1153  	if hot {
  1154  		hasHotCall[callerfn] = struct{}{}
  1155  	}
  1156  	typecheck.AssertFixedCall(n)
  1157  
  1158  	parent := base.Ctxt.PosTable.Pos(n.Pos()).Base().InliningIndex()
  1159  	sym := fn.Linksym()
  1160  	inlIndex := base.Ctxt.InlTree.Add(parent, n.Pos(), sym, ir.FuncName(fn))
  1161  
  1162  	closureInitLSym := func(n *ir.CallExpr, fn *ir.Func) {
  1163  		// The linker needs FuncInfo metadata for all inlined
  1164  		// functions. This is typically handled by gc.enqueueFunc
  1165  		// calling ir.InitLSym for all function declarations in
  1166  		// typecheck.Target.Decls (ir.UseClosure adds all closures to
  1167  		// Decls).
  1168  		//
  1169  		// However, closures in Decls are ignored, and are
  1170  		// instead enqueued when walk of the calling function
  1171  		// discovers them.
  1172  		//
  1173  		// This presents a problem for direct calls to closures.
  1174  		// Inlining will replace the entire closure definition with its
  1175  		// body, which hides the closure from walk and thus suppresses
  1176  		// symbol creation.
  1177  		//
  1178  		// Explicitly create a symbol early in this edge case to ensure
  1179  		// we keep this metadata.
  1180  		//
  1181  		// TODO: Refactor to keep a reference so this can all be done
  1182  		// by enqueueFunc.
  1183  
  1184  		if n.Op() != ir.OCALLFUNC {
  1185  			// Not a standard call.
  1186  			return
  1187  		}
  1188  
  1189  		var nf = n.Fun
  1190  		// Skips ir.OCONVNOPs, see issue #73716.
  1191  		for nf.Op() == ir.OCONVNOP {
  1192  			nf = nf.(*ir.ConvExpr).X
  1193  		}
  1194  		if nf.Op() != ir.OCLOSURE {
  1195  			// Not a direct closure call or one with type conversion.
  1196  			return
  1197  		}
  1198  
  1199  		clo := nf.(*ir.ClosureExpr)
  1200  		if !clo.Func.IsClosure() {
  1201  			// enqueueFunc will handle non closures anyways.
  1202  			return
  1203  		}
  1204  
  1205  		ir.InitLSym(fn, true)
  1206  	}
  1207  
  1208  	closureInitLSym(n, fn)
  1209  
  1210  	if base.Flag.GenDwarfInl > 0 {
  1211  		if !sym.WasInlined() {
  1212  			base.Ctxt.DwFixups.SetPrecursorFunc(sym, fn)
  1213  			sym.Set(obj.AttrWasInlined, true)
  1214  		}
  1215  	}
  1216  
  1217  	if base.Flag.LowerM != 0 {
  1218  		if buildcfg.Experiment.NewInliner {
  1219  			fmt.Printf("%v: inlining call to %v with score %d\n",
  1220  				ir.Line(n), fn, score)
  1221  		} else {
  1222  			fmt.Printf("%v: inlining call to %v\n", ir.Line(n), fn)
  1223  		}
  1224  	}
  1225  	if base.Flag.LowerM > 2 {
  1226  		fmt.Printf("%v: Before inlining: %+v\n", ir.Line(n), n)
  1227  	}
  1228  
  1229  	res := InlineCall(callerfn, n, fn, inlIndex)
  1230  
  1231  	if res == nil {
  1232  		base.FatalfAt(n.Pos(), "inlining call to %v failed", fn)
  1233  	}
  1234  
  1235  	if base.Flag.LowerM > 2 {
  1236  		fmt.Printf("%v: After inlining %+v\n\n", ir.Line(res), res)
  1237  	}
  1238  
  1239  	if inlheur.Enabled() {
  1240  		inlheur.UpdateCallsiteTable(callerfn, n, res)
  1241  	}
  1242  
  1243  	return res
  1244  }
  1245  
  1246  // CalleeEffects appends any side effects from evaluating callee to init.
  1247  func CalleeEffects(init *ir.Nodes, callee ir.Node) {
  1248  	for {
  1249  		init.Append(ir.TakeInit(callee)...)
  1250  
  1251  		switch callee.Op() {
  1252  		case ir.ONAME, ir.OCLOSURE, ir.OMETHEXPR:
  1253  			return // done
  1254  
  1255  		case ir.OCONVNOP:
  1256  			conv := callee.(*ir.ConvExpr)
  1257  			callee = conv.X
  1258  
  1259  		case ir.OINLCALL:
  1260  			ic := callee.(*ir.InlinedCallExpr)
  1261  			init.Append(ic.Body.Take()...)
  1262  			callee = ic.SingleResult()
  1263  
  1264  		default:
  1265  			base.FatalfAt(callee.Pos(), "unexpected callee expression: %v", callee)
  1266  		}
  1267  	}
  1268  }
  1269  
  1270  func pruneUnusedAutos(ll []*ir.Name, vis *hairyVisitor) []*ir.Name {
  1271  	s := make([]*ir.Name, 0, len(ll))
  1272  	for _, n := range ll {
  1273  		if n.Class == ir.PAUTO {
  1274  			if !vis.usedLocals.Has(n) {
  1275  				// TODO(mdempsky): Simplify code after confident that this
  1276  				// never happens anymore.
  1277  				base.FatalfAt(n.Pos(), "unused auto: %v", n)
  1278  				continue
  1279  			}
  1280  		}
  1281  		s = append(s, n)
  1282  	}
  1283  	return s
  1284  }
  1285  
  1286  func doList(list []ir.Node, do func(ir.Node) bool) bool {
  1287  	for _, x := range list {
  1288  		if x != nil {
  1289  			if do(x) {
  1290  				return true
  1291  			}
  1292  		}
  1293  	}
  1294  	return false
  1295  }
  1296  
  1297  // isIndexingCoverageCounter returns true if the specified node 'n' is indexing
  1298  // into a coverage counter array.
  1299  func isIndexingCoverageCounter(n ir.Node) bool {
  1300  	if n.Op() != ir.OINDEX {
  1301  		return false
  1302  	}
  1303  	ixn := n.(*ir.IndexExpr)
  1304  	if ixn.X.Op() != ir.ONAME || !ixn.X.Type().IsArray() {
  1305  		return false
  1306  	}
  1307  	nn := ixn.X.(*ir.Name)
  1308  	// CoverageAuxVar implies either a coverage counter or a package
  1309  	// ID; since the cover tool never emits code to index into ID vars
  1310  	// this is effectively testing whether nn is a coverage counter.
  1311  	return nn.CoverageAuxVar()
  1312  }
  1313  
  1314  // isAtomicCoverageCounterUpdate examines the specified node to
  1315  // determine whether it represents a call to sync/atomic.AddUint32 to
  1316  // increment a coverage counter.
  1317  func isAtomicCoverageCounterUpdate(cn *ir.CallExpr) bool {
  1318  	if cn.Fun.Op() != ir.ONAME {
  1319  		return false
  1320  	}
  1321  	name := cn.Fun.(*ir.Name)
  1322  	if name.Class != ir.PFUNC {
  1323  		return false
  1324  	}
  1325  	fn := name.Sym().Name
  1326  	if name.Sym().Pkg.Path != "sync/atomic" ||
  1327  		(fn != "AddUint32" && fn != "StoreUint32") {
  1328  		return false
  1329  	}
  1330  	if len(cn.Args) != 2 || cn.Args[0].Op() != ir.OADDR {
  1331  		return false
  1332  	}
  1333  	adn := cn.Args[0].(*ir.AddrExpr)
  1334  	v := isIndexingCoverageCounter(adn.X)
  1335  	return v
  1336  }
  1337  
  1338  func PostProcessCallSites(profile *pgoir.Profile) {
  1339  	if base.Debug.DumpInlCallSiteScores != 0 {
  1340  		budgetCallback := func(fn *ir.Func, prof *pgoir.Profile) (int32, bool) {
  1341  			v := inlineBudget(fn, prof, false, false)
  1342  			return v, v == inlineHotMaxBudget
  1343  		}
  1344  		inlheur.DumpInlCallSiteScores(profile, budgetCallback)
  1345  	}
  1346  }
  1347  
  1348  func analyzeFuncProps(fn *ir.Func, p *pgoir.Profile) {
  1349  	canInline := func(fn *ir.Func) { CanInline(fn, p) }
  1350  	budgetForFunc := func(fn *ir.Func) int32 {
  1351  		return inlineBudget(fn, p, true, false)
  1352  	}
  1353  	inlheur.AnalyzeFunc(fn, canInline, budgetForFunc, inlineMaxBudget)
  1354  }
  1355  

View as plain text