]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/inline/inl.go
cmd/compile/internal/pgo: remove ConvertLine2Int
[gostls13.git] / 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         "strconv"
33         "strings"
34
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"
41         "cmd/internal/obj"
42         "cmd/internal/src"
43 )
44
45 // Inlining budget parameters, gathered in one place
46 const (
47         inlineMaxBudget       = 80
48         inlineExtraAppendCost = 0
49         // default is to inline if there's at most one call. -l=4 overrides this by using 1 instead.
50         inlineExtraCallCost  = 57              // 57 was benchmarked to provided most benefit with no bad surprises; see https://github.com/golang/go/issues/19348#issuecomment-439370742
51         inlineExtraPanicCost = 1               // do not penalize inlining panics.
52         inlineExtraThrowCost = inlineMaxBudget // with current (2018-05/1.11) code, inlining runtime.throw does not help.
53
54         inlineBigFunctionNodes   = 5000 // Functions with this many nodes are considered "big".
55         inlineBigFunctionMaxCost = 20   // Max cost of inlinee when inlining into a "big" function.
56 )
57
58 var (
59         // List of all hot ndes.
60         candHotNodeMap = make(map[*pgo.IRNode]struct{})
61
62         // List of all hot call sites.
63         candHotEdgeMap = make(map[pgo.CallSiteInfo]struct{})
64
65         // List of inlined call sites.
66         inlinedCallSites = make(map[pgo.CallSiteInfo]struct{})
67
68         // Threshold in percentage for hot function inlining.
69         inlineHotFuncThresholdPercent = float64(2)
70
71         // Threshold in percentage for hot callsite inlining.
72         inlineHotCallSiteThresholdPercent = float64(0.1)
73
74         // Budget increased due to hotness.
75         inlineHotMaxBudget int32 = 160
76 )
77
78 // InlinePrologue records the hot callsites from ir-graph.
79 func InlinePrologue() {
80         if s, err := strconv.ParseFloat(base.Debug.InlineHotFuncThreshold, 64); err == nil {
81                 inlineHotFuncThresholdPercent = s
82                 if base.Debug.PGOInline > 0 {
83                         fmt.Printf("hot-node-thres=%v\n", inlineHotFuncThresholdPercent)
84                 }
85         }
86
87         if s, err := strconv.ParseFloat(base.Debug.InlineHotCallSiteThreshold, 64); err == nil {
88                 inlineHotCallSiteThresholdPercent = s
89                 if base.Debug.PGOInline > 0 {
90                         fmt.Printf("hot-callsite-thres=%v\n", inlineHotCallSiteThresholdPercent)
91                 }
92         }
93
94         if base.Debug.InlineHotBudget != 0 {
95                 inlineHotMaxBudget = int32(base.Debug.InlineHotBudget)
96         }
97
98         ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
99                 for _, f := range list {
100                         name := ir.PkgFuncName(f)
101                         if n, ok := pgo.WeightedCG.IRNodes[name]; ok {
102                                 nodeweight := pgo.WeightInPercentage(n.Flat, pgo.GlobalTotalNodeWeight)
103                                 if nodeweight > inlineHotFuncThresholdPercent {
104                                         candHotNodeMap[n] = struct{}{}
105                                 }
106                                 for _, e := range pgo.WeightedCG.OutEdges[n] {
107                                         if e.Weight != 0 {
108                                                 edgeweightpercent := pgo.WeightInPercentage(e.Weight, pgo.GlobalTotalEdgeWeight)
109                                                 if edgeweightpercent > inlineHotCallSiteThresholdPercent {
110                                                         csi := pgo.CallSiteInfo{Line: e.CallSite, Caller: n.AST, Callee: e.Dst.AST}
111                                                         if _, ok := candHotEdgeMap[csi]; !ok {
112                                                                 candHotEdgeMap[csi] = struct{}{}
113                                                         }
114                                                 }
115                                         }
116                                 }
117                         }
118                 }
119         })
120         if base.Debug.PGOInline > 0 {
121                 fmt.Printf("hot-cg before inline in dot format:")
122                 pgo.PrintWeightedCallGraphDOT(inlineHotFuncThresholdPercent, inlineHotCallSiteThresholdPercent)
123         }
124 }
125
126 // InlineEpilogue updates IRGraph after inlining.
127 func InlineEpilogue() {
128         if base.Debug.PGOInline > 0 {
129                 ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
130                         for _, f := range list {
131                                 name := ir.PkgFuncName(f)
132                                 if n, ok := pgo.WeightedCG.IRNodes[name]; ok {
133                                         pgo.RedirectEdges(n, inlinedCallSites)
134                                 }
135                         }
136                 })
137                 // Print the call-graph after inlining. This is a debugging feature.
138                 fmt.Printf("hot-cg after inline in dot:")
139                 pgo.PrintWeightedCallGraphDOT(inlineHotFuncThresholdPercent, inlineHotCallSiteThresholdPercent)
140         }
141 }
142
143 // InlinePackage finds functions that can be inlined and clones them before walk expands them.
144 func InlinePackage() {
145         ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
146                 numfns := numNonClosures(list)
147                 for _, n := range list {
148                         if !recursive || numfns > 1 {
149                                 // We allow inlining if there is no
150                                 // recursion, or the recursion cycle is
151                                 // across more than one function.
152                                 CanInline(n)
153                         } else {
154                                 if base.Flag.LowerM > 1 {
155                                         fmt.Printf("%v: cannot inline %v: recursive\n", ir.Line(n), n.Nname)
156                                 }
157                         }
158                         InlineCalls(n)
159                 }
160         })
161 }
162
163 // CanInline determines whether fn is inlineable.
164 // If so, CanInline saves copies of fn.Body and fn.Dcl in fn.Inl.
165 // fn and fn.Body will already have been typechecked.
166 func CanInline(fn *ir.Func) {
167         if fn.Nname == nil {
168                 base.Fatalf("CanInline no nname %+v", fn)
169         }
170
171         // Initialize an empty list of hot callsites for this caller.
172         pgo.ListOfHotCallSites = make(map[pgo.CallSiteInfo]struct{})
173
174         var reason string // reason, if any, that the function was not inlined
175         if base.Flag.LowerM > 1 || logopt.Enabled() {
176                 defer func() {
177                         if reason != "" {
178                                 if base.Flag.LowerM > 1 {
179                                         fmt.Printf("%v: cannot inline %v: %s\n", ir.Line(fn), fn.Nname, reason)
180                                 }
181                                 if logopt.Enabled() {
182                                         logopt.LogOpt(fn.Pos(), "cannotInlineFunction", "inline", ir.FuncName(fn), reason)
183                                 }
184                         }
185                 }()
186         }
187
188         // If marked "go:noinline", don't inline
189         if fn.Pragma&ir.Noinline != 0 {
190                 reason = "marked go:noinline"
191                 return
192         }
193
194         // If marked "go:norace" and -race compilation, don't inline.
195         if base.Flag.Race && fn.Pragma&ir.Norace != 0 {
196                 reason = "marked go:norace with -race compilation"
197                 return
198         }
199
200         // If marked "go:nocheckptr" and -d checkptr compilation, don't inline.
201         if base.Debug.Checkptr != 0 && fn.Pragma&ir.NoCheckPtr != 0 {
202                 reason = "marked go:nocheckptr"
203                 return
204         }
205
206         // If marked "go:cgo_unsafe_args", don't inline, since the
207         // function makes assumptions about its argument frame layout.
208         if fn.Pragma&ir.CgoUnsafeArgs != 0 {
209                 reason = "marked go:cgo_unsafe_args"
210                 return
211         }
212
213         // If marked as "go:uintptrkeepalive", don't inline, since the
214         // keep alive information is lost during inlining.
215         //
216         // TODO(prattmic): This is handled on calls during escape analysis,
217         // which is after inlining. Move prior to inlining so the keep-alive is
218         // maintained after inlining.
219         if fn.Pragma&ir.UintptrKeepAlive != 0 {
220                 reason = "marked as having a keep-alive uintptr argument"
221                 return
222         }
223
224         // If marked as "go:uintptrescapes", don't inline, since the
225         // escape information is lost during inlining.
226         if fn.Pragma&ir.UintptrEscapes != 0 {
227                 reason = "marked as having an escaping uintptr argument"
228                 return
229         }
230
231         // The nowritebarrierrec checker currently works at function
232         // granularity, so inlining yeswritebarrierrec functions can
233         // confuse it (#22342). As a workaround, disallow inlining
234         // them for now.
235         if fn.Pragma&ir.Yeswritebarrierrec != 0 {
236                 reason = "marked go:yeswritebarrierrec"
237                 return
238         }
239
240         // If fn has no body (is defined outside of Go), cannot inline it.
241         if len(fn.Body) == 0 {
242                 reason = "no function body"
243                 return
244         }
245
246         if fn.Typecheck() == 0 {
247                 base.Fatalf("CanInline on non-typechecked function %v", fn)
248         }
249
250         n := fn.Nname
251         if n.Func.InlinabilityChecked() {
252                 return
253         }
254         defer n.Func.SetInlinabilityChecked(true)
255
256         cc := int32(inlineExtraCallCost)
257         if base.Flag.LowerL == 4 {
258                 cc = 1 // this appears to yield better performance than 0.
259         }
260
261         // Update the budget for profile-guided inlining.
262         budget := int32(inlineMaxBudget)
263         if base.Flag.PgoProfile != "" && pgo.WeightedCG != nil {
264                 if n, ok := pgo.WeightedCG.IRNodes[ir.PkgFuncName(fn)]; ok {
265                         if _, ok := candHotNodeMap[n]; ok {
266                                 budget = int32(inlineHotMaxBudget)
267                                 if base.Debug.PGOInline > 0 {
268                                         fmt.Printf("hot-node enabled increased budget=%v for func=%v\n", budget, ir.PkgFuncName(fn))
269                                 }
270                         }
271                 }
272         }
273
274         // At this point in the game the function we're looking at may
275         // have "stale" autos, vars that still appear in the Dcl list, but
276         // which no longer have any uses in the function body (due to
277         // elimination by deadcode). We'd like to exclude these dead vars
278         // when creating the "Inline.Dcl" field below; to accomplish this,
279         // the hairyVisitor below builds up a map of used/referenced
280         // locals, and we use this map to produce a pruned Inline.Dcl
281         // list. See issue 25249 for more context.
282
283         visitor := hairyVisitor{
284                 curFunc:       fn,
285                 budget:        budget,
286                 maxBudget:     budget,
287                 extraCallCost: cc,
288         }
289         if visitor.tooHairy(fn) {
290                 reason = visitor.reason
291                 return
292         }
293
294         n.Func.Inl = &ir.Inline{
295                 Cost: budget - visitor.budget,
296                 Dcl:  pruneUnusedAutos(n.Defn.(*ir.Func).Dcl, &visitor),
297                 Body: inlcopylist(fn.Body),
298
299                 CanDelayResults: canDelayResults(fn),
300         }
301
302         if base.Flag.LowerM > 1 {
303                 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))
304         } else if base.Flag.LowerM != 0 {
305                 fmt.Printf("%v: can inline %v\n", ir.Line(fn), n)
306         }
307         if logopt.Enabled() {
308                 logopt.LogOpt(fn.Pos(), "canInlineFunction", "inline", ir.FuncName(fn), fmt.Sprintf("cost: %d", budget-visitor.budget))
309         }
310 }
311
312 // canDelayResults reports whether inlined calls to fn can delay
313 // declaring the result parameter until the "return" statement.
314 func canDelayResults(fn *ir.Func) bool {
315         // We can delay declaring+initializing result parameters if:
316         // (1) there's exactly one "return" statement in the inlined function;
317         // (2) it's not an empty return statement (#44355); and
318         // (3) the result parameters aren't named.
319
320         nreturns := 0
321         ir.VisitList(fn.Body, func(n ir.Node) {
322                 if n, ok := n.(*ir.ReturnStmt); ok {
323                         nreturns++
324                         if len(n.Results) == 0 {
325                                 nreturns++ // empty return statement (case 2)
326                         }
327                 }
328         })
329
330         if nreturns != 1 {
331                 return false // not exactly one return statement (case 1)
332         }
333
334         // temporaries for return values.
335         for _, param := range fn.Type().Results().FieldSlice() {
336                 if sym := types.OrigSym(param.Sym); sym != nil && !sym.IsBlank() {
337                         return false // found a named result parameter (case 3)
338                 }
339         }
340
341         return true
342 }
343
344 // hairyVisitor visits a function body to determine its inlining
345 // hairiness and whether or not it can be inlined.
346 type hairyVisitor struct {
347         // This is needed to access the current caller in the doNode function.
348         curFunc       *ir.Func
349         budget        int32
350         maxBudget     int32
351         reason        string
352         extraCallCost int32
353         usedLocals    ir.NameSet
354         do            func(ir.Node) bool
355 }
356
357 func (v *hairyVisitor) tooHairy(fn *ir.Func) bool {
358         v.do = v.doNode // cache closure
359         if ir.DoChildren(fn, v.do) {
360                 return true
361         }
362         if v.budget < 0 {
363                 v.reason = fmt.Sprintf("function too complex: cost %d exceeds budget %d", v.maxBudget-v.budget, v.maxBudget)
364                 return true
365         }
366         return false
367 }
368
369 func (v *hairyVisitor) doNode(n ir.Node) bool {
370         if n == nil {
371                 return false
372         }
373         switch n.Op() {
374         // Call is okay if inlinable and we have the budget for the body.
375         case ir.OCALLFUNC:
376                 n := n.(*ir.CallExpr)
377                 // Functions that call runtime.getcaller{pc,sp} can not be inlined
378                 // because getcaller{pc,sp} expect a pointer to the caller's first argument.
379                 //
380                 // runtime.throw is a "cheap call" like panic in normal code.
381                 if n.X.Op() == ir.ONAME {
382                         name := n.X.(*ir.Name)
383                         if name.Class == ir.PFUNC && types.IsRuntimePkg(name.Sym().Pkg) {
384                                 fn := name.Sym().Name
385                                 if fn == "getcallerpc" || fn == "getcallersp" {
386                                         v.reason = "call to " + fn
387                                         return true
388                                 }
389                                 if fn == "throw" {
390                                         v.budget -= inlineExtraThrowCost
391                                         break
392                                 }
393                         }
394                         // Special case for coverage counter updates; although
395                         // these correspond to real operations, we treat them as
396                         // zero cost for the moment. This is due to the existence
397                         // of tests that are sensitive to inlining-- if the
398                         // insertion of coverage instrumentation happens to tip a
399                         // given function over the threshold and move it from
400                         // "inlinable" to "not-inlinable", this can cause changes
401                         // in allocation behavior, which can then result in test
402                         // failures (a good example is the TestAllocations in
403                         // crypto/ed25519).
404                         if isAtomicCoverageCounterUpdate(n) {
405                                 break
406                         }
407                 }
408                 if n.X.Op() == ir.OMETHEXPR {
409                         if meth := ir.MethodExprName(n.X); meth != nil {
410                                 if fn := meth.Func; fn != nil {
411                                         s := fn.Sym()
412                                         var cheap bool
413                                         if types.IsRuntimePkg(s.Pkg) && s.Name == "heapBits.nextArena" {
414                                                 // Special case: explicitly allow mid-stack inlining of
415                                                 // runtime.heapBits.next even though it calls slow-path
416                                                 // runtime.heapBits.nextArena.
417                                                 cheap = true
418                                         }
419                                         // Special case: on architectures that can do unaligned loads,
420                                         // explicitly mark encoding/binary methods as cheap,
421                                         // because in practice they are, even though our inlining
422                                         // budgeting system does not see that. See issue 42958.
423                                         if base.Ctxt.Arch.CanMergeLoads && s.Pkg.Path == "encoding/binary" {
424                                                 switch s.Name {
425                                                 case "littleEndian.Uint64", "littleEndian.Uint32", "littleEndian.Uint16",
426                                                         "bigEndian.Uint64", "bigEndian.Uint32", "bigEndian.Uint16",
427                                                         "littleEndian.PutUint64", "littleEndian.PutUint32", "littleEndian.PutUint16",
428                                                         "bigEndian.PutUint64", "bigEndian.PutUint32", "bigEndian.PutUint16",
429                                                         "littleEndian.AppendUint64", "littleEndian.AppendUint32", "littleEndian.AppendUint16",
430                                                         "bigEndian.AppendUint64", "bigEndian.AppendUint32", "bigEndian.AppendUint16":
431                                                         cheap = true
432                                                 }
433                                         }
434                                         if cheap {
435                                                 break // treat like any other node, that is, cost of 1
436                                         }
437                                 }
438                         }
439                 }
440
441                 // Determine if the callee edge is a for hot callee or not.
442                 if base.Flag.PgoProfile != "" && pgo.WeightedCG != nil && v.curFunc != nil {
443                         if fn := inlCallee(n.X); fn != nil && typecheck.HaveInlineBody(fn) {
444                                 line := int(base.Ctxt.InnermostPos(n.Pos()).RelLine())
445                                 csi := pgo.CallSiteInfo{Line: line, Caller: v.curFunc, Callee: fn}
446                                 if _, o := candHotEdgeMap[csi]; o {
447                                         pgo.ListOfHotCallSites[pgo.CallSiteInfo{Line: line, Caller: v.curFunc}] = struct{}{}
448                                         if base.Debug.PGOInline > 0 {
449                                                 fmt.Printf("hot-callsite identified at line=%v for func=%v\n", ir.Line(n), ir.PkgFuncName(v.curFunc))
450                                         }
451                                 }
452                         }
453                 }
454
455                 if ir.IsIntrinsicCall(n) {
456                         // Treat like any other node.
457                         break
458                 }
459
460                 if fn := inlCallee(n.X); fn != nil && typecheck.HaveInlineBody(fn) {
461                         v.budget -= fn.Inl.Cost
462                         break
463                 }
464
465                 // Call cost for non-leaf inlining.
466                 v.budget -= v.extraCallCost
467
468         case ir.OCALLMETH:
469                 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
470
471         // Things that are too hairy, irrespective of the budget
472         case ir.OCALL, ir.OCALLINTER:
473                 // Call cost for non-leaf inlining.
474                 v.budget -= v.extraCallCost
475
476         case ir.OPANIC:
477                 n := n.(*ir.UnaryExpr)
478                 if n.X.Op() == ir.OCONVIFACE && n.X.(*ir.ConvExpr).Implicit() {
479                         // Hack to keep reflect.flag.mustBe inlinable for TestIntendedInlining.
480                         // Before CL 284412, these conversions were introduced later in the
481                         // compiler, so they didn't count against inlining budget.
482                         v.budget++
483                 }
484                 v.budget -= inlineExtraPanicCost
485
486         case ir.ORECOVER:
487                 // recover matches the argument frame pointer to find
488                 // the right panic value, so it needs an argument frame.
489                 v.reason = "call to recover"
490                 return true
491
492         case ir.OCLOSURE:
493                 if base.Debug.InlFuncsWithClosures == 0 {
494                         v.reason = "not inlining functions with closures"
495                         return true
496                 }
497
498                 // TODO(danscales): Maybe make budget proportional to number of closure
499                 // variables, e.g.:
500                 //v.budget -= int32(len(n.(*ir.ClosureExpr).Func.ClosureVars) * 3)
501                 v.budget -= 15
502                 // Scan body of closure (which DoChildren doesn't automatically
503                 // do) to check for disallowed ops in the body and include the
504                 // body in the budget.
505                 if doList(n.(*ir.ClosureExpr).Func.Body, v.do) {
506                         return true
507                 }
508
509         case ir.OGO,
510                 ir.ODEFER,
511                 ir.ODCLTYPE, // can't print yet
512                 ir.OTAILCALL:
513                 v.reason = "unhandled op " + n.Op().String()
514                 return true
515
516         case ir.OAPPEND:
517                 v.budget -= inlineExtraAppendCost
518
519         case ir.OADDR:
520                 n := n.(*ir.AddrExpr)
521                 // Make "&s.f" cost 0 when f's offset is zero.
522                 if dot, ok := n.X.(*ir.SelectorExpr); ok && (dot.Op() == ir.ODOT || dot.Op() == ir.ODOTPTR) {
523                         if _, ok := dot.X.(*ir.Name); ok && dot.Selection.Offset == 0 {
524                                 v.budget += 2 // undo ir.OADDR+ir.ODOT/ir.ODOTPTR
525                         }
526                 }
527
528         case ir.ODEREF:
529                 // *(*X)(unsafe.Pointer(&x)) is low-cost
530                 n := n.(*ir.StarExpr)
531
532                 ptr := n.X
533                 for ptr.Op() == ir.OCONVNOP {
534                         ptr = ptr.(*ir.ConvExpr).X
535                 }
536                 if ptr.Op() == ir.OADDR {
537                         v.budget += 1 // undo half of default cost of ir.ODEREF+ir.OADDR
538                 }
539
540         case ir.OCONVNOP:
541                 // This doesn't produce code, but the children might.
542                 v.budget++ // undo default cost
543
544         case ir.ODCLCONST, ir.OFALL:
545                 // These nodes don't produce code; omit from inlining budget.
546                 return false
547
548         case ir.OIF:
549                 n := n.(*ir.IfStmt)
550                 if ir.IsConst(n.Cond, constant.Bool) {
551                         // This if and the condition cost nothing.
552                         if doList(n.Init(), v.do) {
553                                 return true
554                         }
555                         if ir.BoolVal(n.Cond) {
556                                 return doList(n.Body, v.do)
557                         } else {
558                                 return doList(n.Else, v.do)
559                         }
560                 }
561
562         case ir.ONAME:
563                 n := n.(*ir.Name)
564                 if n.Class == ir.PAUTO {
565                         v.usedLocals.Add(n)
566                 }
567
568         case ir.OBLOCK:
569                 // The only OBLOCK we should see at this point is an empty one.
570                 // In any event, let the visitList(n.List()) below take care of the statements,
571                 // and don't charge for the OBLOCK itself. The ++ undoes the -- below.
572                 v.budget++
573
574         case ir.OMETHVALUE, ir.OSLICELIT:
575                 v.budget-- // Hack for toolstash -cmp.
576
577         case ir.OMETHEXPR:
578                 v.budget++ // Hack for toolstash -cmp.
579
580         case ir.OAS2:
581                 n := n.(*ir.AssignListStmt)
582
583                 // Unified IR unconditionally rewrites:
584                 //
585                 //      a, b = f()
586                 //
587                 // into:
588                 //
589                 //      DCL tmp1
590                 //      DCL tmp2
591                 //      tmp1, tmp2 = f()
592                 //      a, b = tmp1, tmp2
593                 //
594                 // so that it can insert implicit conversions as necessary. To
595                 // minimize impact to the existing inlining heuristics (in
596                 // particular, to avoid breaking the existing inlinability regress
597                 // tests), we need to compensate for this here.
598                 if base.Debug.Unified != 0 {
599                         if init := n.Rhs[0].Init(); len(init) == 1 {
600                                 if _, ok := init[0].(*ir.AssignListStmt); ok {
601                                         // 4 for each value, because each temporary variable now
602                                         // appears 3 times (DCL, LHS, RHS), plus an extra DCL node.
603                                         //
604                                         // 1 for the extra "tmp1, tmp2 = f()" assignment statement.
605                                         v.budget += 4*int32(len(n.Lhs)) + 1
606                                 }
607                         }
608                 }
609
610         case ir.OAS:
611                 // Special case for coverage counter updates and coverage
612                 // function registrations. Although these correspond to real
613                 // operations, we treat them as zero cost for the moment. This
614                 // is primarily due to the existence of tests that are
615                 // sensitive to inlining-- if the insertion of coverage
616                 // instrumentation happens to tip a given function over the
617                 // threshold and move it from "inlinable" to "not-inlinable",
618                 // this can cause changes in allocation behavior, which can
619                 // then result in test failures (a good example is the
620                 // TestAllocations in crypto/ed25519).
621                 n := n.(*ir.AssignStmt)
622                 if n.X.Op() == ir.OINDEX && isIndexingCoverageCounter(n) {
623                         return false
624                 }
625         }
626
627         v.budget--
628
629         // When debugging, don't stop early, to get full cost of inlining this function
630         if v.budget < 0 && base.Flag.LowerM < 2 && !logopt.Enabled() {
631                 v.reason = "too expensive"
632                 return true
633         }
634
635         return ir.DoChildren(n, v.do)
636 }
637
638 func isBigFunc(fn *ir.Func) bool {
639         budget := inlineBigFunctionNodes
640         return ir.Any(fn, func(n ir.Node) bool {
641                 budget--
642                 return budget <= 0
643         })
644 }
645
646 // inlcopylist (together with inlcopy) recursively copies a list of nodes, except
647 // that it keeps the same ONAME, OTYPE, and OLITERAL nodes. It is used for copying
648 // the body and dcls of an inlineable function.
649 func inlcopylist(ll []ir.Node) []ir.Node {
650         s := make([]ir.Node, len(ll))
651         for i, n := range ll {
652                 s[i] = inlcopy(n)
653         }
654         return s
655 }
656
657 // inlcopy is like DeepCopy(), but does extra work to copy closures.
658 func inlcopy(n ir.Node) ir.Node {
659         var edit func(ir.Node) ir.Node
660         edit = func(x ir.Node) ir.Node {
661                 switch x.Op() {
662                 case ir.ONAME, ir.OTYPE, ir.OLITERAL, ir.ONIL:
663                         return x
664                 }
665                 m := ir.Copy(x)
666                 ir.EditChildren(m, edit)
667                 if x.Op() == ir.OCLOSURE {
668                         x := x.(*ir.ClosureExpr)
669                         // Need to save/duplicate x.Func.Nname,
670                         // x.Func.Nname.Ntype, x.Func.Dcl, x.Func.ClosureVars, and
671                         // x.Func.Body for iexport and local inlining.
672                         oldfn := x.Func
673                         newfn := ir.NewFunc(oldfn.Pos())
674                         m.(*ir.ClosureExpr).Func = newfn
675                         newfn.Nname = ir.NewNameAt(oldfn.Nname.Pos(), oldfn.Nname.Sym())
676                         // XXX OK to share fn.Type() ??
677                         newfn.Nname.SetType(oldfn.Nname.Type())
678                         newfn.Body = inlcopylist(oldfn.Body)
679                         // Make shallow copy of the Dcl and ClosureVar slices
680                         newfn.Dcl = append([]*ir.Name(nil), oldfn.Dcl...)
681                         newfn.ClosureVars = append([]*ir.Name(nil), oldfn.ClosureVars...)
682                 }
683                 return m
684         }
685         return edit(n)
686 }
687
688 // InlineCalls/inlnode walks fn's statements and expressions and substitutes any
689 // calls made to inlineable functions. This is the external entry point.
690 func InlineCalls(fn *ir.Func) {
691         savefn := ir.CurFunc
692         ir.CurFunc = fn
693         maxCost := int32(inlineMaxBudget)
694         if isBigFunc(fn) {
695                 maxCost = inlineBigFunctionMaxCost
696         }
697         var inlCalls []*ir.InlinedCallExpr
698         var edit func(ir.Node) ir.Node
699         edit = func(n ir.Node) ir.Node {
700                 return inlnode(n, maxCost, &inlCalls, edit)
701         }
702         ir.EditChildren(fn, edit)
703
704         // If we inlined any calls, we want to recursively visit their
705         // bodies for further inlining. However, we need to wait until
706         // *after* the original function body has been expanded, or else
707         // inlCallee can have false positives (e.g., #54632).
708         for len(inlCalls) > 0 {
709                 call := inlCalls[0]
710                 inlCalls = inlCalls[1:]
711                 ir.EditChildren(call, edit)
712         }
713
714         ir.CurFunc = savefn
715 }
716
717 // inlnode recurses over the tree to find inlineable calls, which will
718 // be turned into OINLCALLs by mkinlcall. When the recursion comes
719 // back up will examine left, right, list, rlist, ninit, ntest, nincr,
720 // nbody and nelse and use one of the 4 inlconv/glue functions above
721 // to turn the OINLCALL into an expression, a statement, or patch it
722 // in to this nodes list or rlist as appropriate.
723 // NOTE it makes no sense to pass the glue functions down the
724 // recursion to the level where the OINLCALL gets created because they
725 // have to edit /this/ n, so you'd have to push that one down as well,
726 // but then you may as well do it here.  so this is cleaner and
727 // shorter and less complicated.
728 // The result of inlnode MUST be assigned back to n, e.g.
729 //
730 //      n.Left = inlnode(n.Left)
731 func inlnode(n ir.Node, maxCost int32, inlCalls *[]*ir.InlinedCallExpr, edit func(ir.Node) ir.Node) ir.Node {
732         if n == nil {
733                 return n
734         }
735
736         switch n.Op() {
737         case ir.ODEFER, ir.OGO:
738                 n := n.(*ir.GoDeferStmt)
739                 switch call := n.Call; call.Op() {
740                 case ir.OCALLMETH:
741                         base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
742                 case ir.OCALLFUNC:
743                         call := call.(*ir.CallExpr)
744                         call.NoInline = true
745                 }
746         case ir.OTAILCALL:
747                 n := n.(*ir.TailCallStmt)
748                 n.Call.NoInline = true // Not inline a tail call for now. Maybe we could inline it just like RETURN fn(arg)?
749
750         // TODO do them here (or earlier),
751         // so escape analysis can avoid more heapmoves.
752         case ir.OCLOSURE:
753                 return n
754         case ir.OCALLMETH:
755                 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
756         case ir.OCALLFUNC:
757                 n := n.(*ir.CallExpr)
758                 if n.X.Op() == ir.OMETHEXPR {
759                         // Prevent inlining some reflect.Value methods when using checkptr,
760                         // even when package reflect was compiled without it (#35073).
761                         if meth := ir.MethodExprName(n.X); meth != nil {
762                                 s := meth.Sym()
763                                 if base.Debug.Checkptr != 0 && types.IsReflectPkg(s.Pkg) && (s.Name == "Value.UnsafeAddr" || s.Name == "Value.Pointer") {
764                                         return n
765                                 }
766                         }
767                 }
768         }
769
770         lno := ir.SetPos(n)
771
772         ir.EditChildren(n, edit)
773
774         // with all the branches out of the way, it is now time to
775         // transmogrify this node itself unless inhibited by the
776         // switch at the top of this function.
777         switch n.Op() {
778         case ir.OCALLMETH:
779                 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
780
781         case ir.OCALLFUNC:
782                 call := n.(*ir.CallExpr)
783                 if call.NoInline {
784                         break
785                 }
786                 if base.Flag.LowerM > 3 {
787                         fmt.Printf("%v:call to func %+v\n", ir.Line(n), call.X)
788                 }
789                 if ir.IsIntrinsicCall(call) {
790                         break
791                 }
792                 if fn := inlCallee(call.X); fn != nil && typecheck.HaveInlineBody(fn) {
793                         n = mkinlcall(call, fn, maxCost, inlCalls, edit)
794                 }
795         }
796
797         base.Pos = lno
798
799         return n
800 }
801
802 // inlCallee takes a function-typed expression and returns the underlying function ONAME
803 // that it refers to if statically known. Otherwise, it returns nil.
804 func inlCallee(fn ir.Node) *ir.Func {
805         fn = ir.StaticValue(fn)
806         switch fn.Op() {
807         case ir.OMETHEXPR:
808                 fn := fn.(*ir.SelectorExpr)
809                 n := ir.MethodExprName(fn)
810                 // Check that receiver type matches fn.X.
811                 // TODO(mdempsky): Handle implicit dereference
812                 // of pointer receiver argument?
813                 if n == nil || !types.Identical(n.Type().Recv().Type, fn.X.Type()) {
814                         return nil
815                 }
816                 return n.Func
817         case ir.ONAME:
818                 fn := fn.(*ir.Name)
819                 if fn.Class == ir.PFUNC {
820                         return fn.Func
821                 }
822         case ir.OCLOSURE:
823                 fn := fn.(*ir.ClosureExpr)
824                 c := fn.Func
825                 CanInline(c)
826                 return c
827         }
828         return nil
829 }
830
831 func inlParam(t *types.Field, as ir.InitNode, inlvars map[*ir.Name]*ir.Name) ir.Node {
832         if t.Nname == nil {
833                 return ir.BlankNode
834         }
835         n := t.Nname.(*ir.Name)
836         if ir.IsBlank(n) {
837                 return ir.BlankNode
838         }
839         inlvar := inlvars[n]
840         if inlvar == nil {
841                 base.Fatalf("missing inlvar for %v", n)
842         }
843         as.PtrInit().Append(ir.NewDecl(base.Pos, ir.ODCL, inlvar))
844         inlvar.Name().Defn = as
845         return inlvar
846 }
847
848 var inlgen int
849
850 // SSADumpInline gives the SSA back end a chance to dump the function
851 // when producing output for debugging the compiler itself.
852 var SSADumpInline = func(*ir.Func) {}
853
854 // InlineCall allows the inliner implementation to be overridden.
855 // If it returns nil, the function will not be inlined.
856 var InlineCall = oldInlineCall
857
858 // If n is a OCALLFUNC node, and fn is an ONAME node for a
859 // function with an inlinable body, return an OINLCALL node that can replace n.
860 // The returned node's Ninit has the parameter assignments, the Nbody is the
861 // inlined function body, and (List, Rlist) contain the (input, output)
862 // parameters.
863 // The result of mkinlcall MUST be assigned back to n, e.g.
864 //
865 //      n.Left = mkinlcall(n.Left, fn, isddd)
866 func mkinlcall(n *ir.CallExpr, fn *ir.Func, maxCost int32, inlCalls *[]*ir.InlinedCallExpr, edit func(ir.Node) ir.Node) ir.Node {
867         if fn.Inl == nil {
868                 if logopt.Enabled() {
869                         logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
870                                 fmt.Sprintf("%s cannot be inlined", ir.PkgFuncName(fn)))
871                 }
872                 return n
873         }
874         if fn.Inl.Cost > maxCost {
875                 // If the callsite is hot and it is under the inlineHotMaxBudget budget, then try to inline it, or else bail.
876                 line := int(base.Ctxt.InnermostPos(n.Pos()).RelLine())
877                 csi := pgo.CallSiteInfo{Line: line, Caller: ir.CurFunc}
878                 if _, ok := pgo.ListOfHotCallSites[csi]; ok {
879                         if fn.Inl.Cost > inlineHotMaxBudget {
880                                 if logopt.Enabled() {
881                                         logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
882                                                 fmt.Sprintf("cost %d of %s exceeds max large caller cost %d", fn.Inl.Cost, ir.PkgFuncName(fn), inlineHotMaxBudget))
883                                 }
884                                 return n
885                         }
886                         if base.Debug.PGOInline > 0 {
887                                 fmt.Printf("hot-budget check allows inlining for callsite at %v\n", ir.Line(n))
888                         }
889                 } else {
890                         // The inlined function body is too big. Typically we use this check to restrict
891                         // inlining into very big functions.  See issue 26546 and 17566.
892                         if logopt.Enabled() {
893                                 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
894                                         fmt.Sprintf("cost %d of %s exceeds max large caller cost %d", fn.Inl.Cost, ir.PkgFuncName(fn), maxCost))
895                         }
896                         return n
897                 }
898         }
899
900         if fn == ir.CurFunc {
901                 // Can't recursively inline a function into itself.
902                 if logopt.Enabled() {
903                         logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", fmt.Sprintf("recursive call to %s", ir.FuncName(ir.CurFunc)))
904                 }
905                 return n
906         }
907
908         // The non-unified frontend has issues with inlining and shape parameters.
909         if base.Debug.Unified == 0 {
910                 // Don't inline a function fn that has no shape parameters, but is passed at
911                 // least one shape arg. This means we must be inlining a non-generic function
912                 // fn that was passed into a generic function, and can be called with a shape
913                 // arg because it matches an appropriate type parameters. But fn may include
914                 // an interface conversion (that may be applied to a shape arg) that was not
915                 // apparent when we first created the instantiation of the generic function.
916                 // We can't handle this if we actually do the inlining, since we want to know
917                 // all interface conversions immediately after stenciling. So, we avoid
918                 // inlining in this case, see issue #49309. (1)
919                 //
920                 // See discussion on go.dev/cl/406475 for more background.
921                 if !fn.Type().Params().HasShape() {
922                         for _, arg := range n.Args {
923                                 if arg.Type().HasShape() {
924                                         if logopt.Enabled() {
925                                                 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
926                                                         fmt.Sprintf("inlining function %v has no-shape params with shape args", ir.FuncName(fn)))
927                                         }
928                                         return n
929                                 }
930                         }
931                 } else {
932                         // Don't inline a function fn that has shape parameters, but is passed no shape arg.
933                         // See comments (1) above, and issue #51909.
934                         inlineable := len(n.Args) == 0 // Function has shape in type, with no arguments can always be inlined.
935                         for _, arg := range n.Args {
936                                 if arg.Type().HasShape() {
937                                         inlineable = true
938                                         break
939                                 }
940                         }
941                         if !inlineable {
942                                 if logopt.Enabled() {
943                                         logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
944                                                 fmt.Sprintf("inlining function %v has shape params with no-shape args", ir.FuncName(fn)))
945                                 }
946                                 return n
947                         }
948                 }
949         }
950
951         if base.Flag.Cfg.Instrumenting && types.IsRuntimePkg(fn.Sym().Pkg) {
952                 // Runtime package must not be instrumented.
953                 // Instrument skips runtime package. However, some runtime code can be
954                 // inlined into other packages and instrumented there. To avoid this,
955                 // we disable inlining of runtime functions when instrumenting.
956                 // The example that we observed is inlining of LockOSThread,
957                 // which lead to false race reports on m contents.
958                 return n
959         }
960
961         parent := base.Ctxt.PosTable.Pos(n.Pos()).Base().InliningIndex()
962         sym := fn.Linksym()
963
964         // Check if we've already inlined this function at this particular
965         // call site, in order to stop inlining when we reach the beginning
966         // of a recursion cycle again. We don't inline immediately recursive
967         // functions, but allow inlining if there is a recursion cycle of
968         // many functions. Most likely, the inlining will stop before we
969         // even hit the beginning of the cycle again, but this catches the
970         // unusual case.
971         for inlIndex := parent; inlIndex >= 0; inlIndex = base.Ctxt.InlTree.Parent(inlIndex) {
972                 if base.Ctxt.InlTree.InlinedFunction(inlIndex) == sym {
973                         if base.Flag.LowerM > 1 {
974                                 fmt.Printf("%v: cannot inline %v into %v: repeated recursive cycle\n", ir.Line(n), fn, ir.FuncName(ir.CurFunc))
975                         }
976                         return n
977                 }
978         }
979
980         typecheck.FixVariadicCall(n)
981
982         inlIndex := base.Ctxt.InlTree.Add(parent, n.Pos(), sym)
983
984         closureInitLSym := func(n *ir.CallExpr, fn *ir.Func) {
985                 // The linker needs FuncInfo metadata for all inlined
986                 // functions. This is typically handled by gc.enqueueFunc
987                 // calling ir.InitLSym for all function declarations in
988                 // typecheck.Target.Decls (ir.UseClosure adds all closures to
989                 // Decls).
990                 //
991                 // However, non-trivial closures in Decls are ignored, and are
992                 // insteaded enqueued when walk of the calling function
993                 // discovers them.
994                 //
995                 // This presents a problem for direct calls to closures.
996                 // Inlining will replace the entire closure definition with its
997                 // body, which hides the closure from walk and thus suppresses
998                 // symbol creation.
999                 //
1000                 // Explicitly create a symbol early in this edge case to ensure
1001                 // we keep this metadata.
1002                 //
1003                 // TODO: Refactor to keep a reference so this can all be done
1004                 // by enqueueFunc.
1005
1006                 if n.Op() != ir.OCALLFUNC {
1007                         // Not a standard call.
1008                         return
1009                 }
1010                 if n.X.Op() != ir.OCLOSURE {
1011                         // Not a direct closure call.
1012                         return
1013                 }
1014
1015                 clo := n.X.(*ir.ClosureExpr)
1016                 if ir.IsTrivialClosure(clo) {
1017                         // enqueueFunc will handle trivial closures anyways.
1018                         return
1019                 }
1020
1021                 ir.InitLSym(fn, true)
1022         }
1023
1024         closureInitLSym(n, fn)
1025
1026         if base.Flag.GenDwarfInl > 0 {
1027                 if !sym.WasInlined() {
1028                         base.Ctxt.DwFixups.SetPrecursorFunc(sym, fn)
1029                         sym.Set(obj.AttrWasInlined, true)
1030                 }
1031         }
1032
1033         if base.Flag.LowerM != 0 {
1034                 fmt.Printf("%v: inlining call to %v\n", ir.Line(n), fn)
1035         }
1036         if base.Flag.LowerM > 2 {
1037                 fmt.Printf("%v: Before inlining: %+v\n", ir.Line(n), n)
1038         }
1039
1040         if base.Debug.PGOInline > 0 {
1041                 line := int(base.Ctxt.InnermostPos(n.Pos()).RelLine())
1042                 csi := pgo.CallSiteInfo{Line: line, Caller: ir.CurFunc}
1043                 if _, ok := inlinedCallSites[csi]; !ok {
1044                         inlinedCallSites[csi] = struct{}{}
1045                 }
1046         }
1047
1048         res := InlineCall(n, fn, inlIndex)
1049
1050         if res == nil {
1051                 base.FatalfAt(n.Pos(), "inlining call to %v failed", fn)
1052         }
1053
1054         if base.Flag.LowerM > 2 {
1055                 fmt.Printf("%v: After inlining %+v\n\n", ir.Line(res), res)
1056         }
1057
1058         *inlCalls = append(*inlCalls, res)
1059
1060         return res
1061 }
1062
1063 // CalleeEffects appends any side effects from evaluating callee to init.
1064 func CalleeEffects(init *ir.Nodes, callee ir.Node) {
1065         for {
1066                 init.Append(ir.TakeInit(callee)...)
1067
1068                 switch callee.Op() {
1069                 case ir.ONAME, ir.OCLOSURE, ir.OMETHEXPR:
1070                         return // done
1071
1072                 case ir.OCONVNOP:
1073                         conv := callee.(*ir.ConvExpr)
1074                         callee = conv.X
1075
1076                 case ir.OINLCALL:
1077                         ic := callee.(*ir.InlinedCallExpr)
1078                         init.Append(ic.Body.Take()...)
1079                         callee = ic.SingleResult()
1080
1081                 default:
1082                         base.FatalfAt(callee.Pos(), "unexpected callee expression: %v", callee)
1083                 }
1084         }
1085 }
1086
1087 // oldInlineCall creates an InlinedCallExpr to replace the given call
1088 // expression. fn is the callee function to be inlined. inlIndex is
1089 // the inlining tree position index, for use with src.NewInliningBase
1090 // when rewriting positions.
1091 func oldInlineCall(call *ir.CallExpr, fn *ir.Func, inlIndex int) *ir.InlinedCallExpr {
1092         if base.Debug.TypecheckInl == 0 {
1093                 typecheck.ImportedBody(fn)
1094         }
1095
1096         SSADumpInline(fn)
1097
1098         ninit := call.Init()
1099
1100         // For normal function calls, the function callee expression
1101         // may contain side effects. Make sure to preserve these,
1102         // if necessary (#42703).
1103         if call.Op() == ir.OCALLFUNC {
1104                 CalleeEffects(&ninit, call.X)
1105         }
1106
1107         // Make temp names to use instead of the originals.
1108         inlvars := make(map[*ir.Name]*ir.Name)
1109
1110         // record formals/locals for later post-processing
1111         var inlfvars []*ir.Name
1112
1113         for _, ln := range fn.Inl.Dcl {
1114                 if ln.Op() != ir.ONAME {
1115                         continue
1116                 }
1117                 if ln.Class == ir.PPARAMOUT { // return values handled below.
1118                         continue
1119                 }
1120                 inlf := typecheck.Expr(inlvar(ln)).(*ir.Name)
1121                 inlvars[ln] = inlf
1122                 if base.Flag.GenDwarfInl > 0 {
1123                         if ln.Class == ir.PPARAM {
1124                                 inlf.Name().SetInlFormal(true)
1125                         } else {
1126                                 inlf.Name().SetInlLocal(true)
1127                         }
1128                         inlf.SetPos(ln.Pos())
1129                         inlfvars = append(inlfvars, inlf)
1130                 }
1131         }
1132
1133         // We can delay declaring+initializing result parameters if:
1134         // temporaries for return values.
1135         var retvars []ir.Node
1136         for i, t := range fn.Type().Results().Fields().Slice() {
1137                 var m *ir.Name
1138                 if nn := t.Nname; nn != nil && !ir.IsBlank(nn.(*ir.Name)) && !strings.HasPrefix(nn.Sym().Name, "~r") {
1139                         n := nn.(*ir.Name)
1140                         m = inlvar(n)
1141                         m = typecheck.Expr(m).(*ir.Name)
1142                         inlvars[n] = m
1143                 } else {
1144                         // anonymous return values, synthesize names for use in assignment that replaces return
1145                         m = retvar(t, i)
1146                 }
1147
1148                 if base.Flag.GenDwarfInl > 0 {
1149                         // Don't update the src.Pos on a return variable if it
1150                         // was manufactured by the inliner (e.g. "~R2"); such vars
1151                         // were not part of the original callee.
1152                         if !strings.HasPrefix(m.Sym().Name, "~R") {
1153                                 m.Name().SetInlFormal(true)
1154                                 m.SetPos(t.Pos)
1155                                 inlfvars = append(inlfvars, m)
1156                         }
1157                 }
1158
1159                 retvars = append(retvars, m)
1160         }
1161
1162         // Assign arguments to the parameters' temp names.
1163         as := ir.NewAssignListStmt(base.Pos, ir.OAS2, nil, nil)
1164         as.Def = true
1165         if call.Op() == ir.OCALLMETH {
1166                 base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
1167         }
1168         as.Rhs.Append(call.Args...)
1169
1170         if recv := fn.Type().Recv(); recv != nil {
1171                 as.Lhs.Append(inlParam(recv, as, inlvars))
1172         }
1173         for _, param := range fn.Type().Params().Fields().Slice() {
1174                 as.Lhs.Append(inlParam(param, as, inlvars))
1175         }
1176
1177         if len(as.Rhs) != 0 {
1178                 ninit.Append(typecheck.Stmt(as))
1179         }
1180
1181         if !fn.Inl.CanDelayResults {
1182                 // Zero the return parameters.
1183                 for _, n := range retvars {
1184                         ninit.Append(ir.NewDecl(base.Pos, ir.ODCL, n.(*ir.Name)))
1185                         ras := ir.NewAssignStmt(base.Pos, n, nil)
1186                         ninit.Append(typecheck.Stmt(ras))
1187                 }
1188         }
1189
1190         retlabel := typecheck.AutoLabel(".i")
1191
1192         inlgen++
1193
1194         // Add an inline mark just before the inlined body.
1195         // This mark is inline in the code so that it's a reasonable spot
1196         // to put a breakpoint. Not sure if that's really necessary or not
1197         // (in which case it could go at the end of the function instead).
1198         // Note issue 28603.
1199         ninit.Append(ir.NewInlineMarkStmt(call.Pos().WithIsStmt(), int64(inlIndex)))
1200
1201         subst := inlsubst{
1202                 retlabel:    retlabel,
1203                 retvars:     retvars,
1204                 inlvars:     inlvars,
1205                 defnMarker:  ir.NilExpr{},
1206                 bases:       make(map[*src.PosBase]*src.PosBase),
1207                 newInlIndex: inlIndex,
1208                 fn:          fn,
1209         }
1210         subst.edit = subst.node
1211
1212         body := subst.list(ir.Nodes(fn.Inl.Body))
1213
1214         lab := ir.NewLabelStmt(base.Pos, retlabel)
1215         body = append(body, lab)
1216
1217         if base.Flag.GenDwarfInl > 0 {
1218                 for _, v := range inlfvars {
1219                         v.SetPos(subst.updatedPos(v.Pos()))
1220                 }
1221         }
1222
1223         //dumplist("ninit post", ninit);
1224
1225         res := ir.NewInlinedCallExpr(base.Pos, body, retvars)
1226         res.SetInit(ninit)
1227         res.SetType(call.Type())
1228         res.SetTypecheck(1)
1229         return res
1230 }
1231
1232 // Every time we expand a function we generate a new set of tmpnames,
1233 // PAUTO's in the calling functions, and link them off of the
1234 // PPARAM's, PAUTOS and PPARAMOUTs of the called function.
1235 func inlvar(var_ *ir.Name) *ir.Name {
1236         if base.Flag.LowerM > 3 {
1237                 fmt.Printf("inlvar %+v\n", var_)
1238         }
1239
1240         n := typecheck.NewName(var_.Sym())
1241         n.SetType(var_.Type())
1242         n.SetTypecheck(1)
1243         n.Class = ir.PAUTO
1244         n.SetUsed(true)
1245         n.SetAutoTemp(var_.AutoTemp())
1246         n.Curfn = ir.CurFunc // the calling function, not the called one
1247         n.SetAddrtaken(var_.Addrtaken())
1248
1249         ir.CurFunc.Dcl = append(ir.CurFunc.Dcl, n)
1250         return n
1251 }
1252
1253 // Synthesize a variable to store the inlined function's results in.
1254 func retvar(t *types.Field, i int) *ir.Name {
1255         n := typecheck.NewName(typecheck.LookupNum("~R", i))
1256         n.SetType(t.Type)
1257         n.SetTypecheck(1)
1258         n.Class = ir.PAUTO
1259         n.SetUsed(true)
1260         n.Curfn = ir.CurFunc // the calling function, not the called one
1261         ir.CurFunc.Dcl = append(ir.CurFunc.Dcl, n)
1262         return n
1263 }
1264
1265 // The inlsubst type implements the actual inlining of a single
1266 // function call.
1267 type inlsubst struct {
1268         // Target of the goto substituted in place of a return.
1269         retlabel *types.Sym
1270
1271         // Temporary result variables.
1272         retvars []ir.Node
1273
1274         inlvars map[*ir.Name]*ir.Name
1275         // defnMarker is used to mark a Node for reassignment.
1276         // inlsubst.clovar set this during creating new ONAME.
1277         // inlsubst.node will set the correct Defn for inlvar.
1278         defnMarker ir.NilExpr
1279
1280         // bases maps from original PosBase to PosBase with an extra
1281         // inlined call frame.
1282         bases map[*src.PosBase]*src.PosBase
1283
1284         // newInlIndex is the index of the inlined call frame to
1285         // insert for inlined nodes.
1286         newInlIndex int
1287
1288         edit func(ir.Node) ir.Node // cached copy of subst.node method value closure
1289
1290         // If non-nil, we are inside a closure inside the inlined function, and
1291         // newclofn is the Func of the new inlined closure.
1292         newclofn *ir.Func
1293
1294         fn *ir.Func // For debug -- the func that is being inlined
1295
1296         // If true, then don't update source positions during substitution
1297         // (retain old source positions).
1298         noPosUpdate bool
1299 }
1300
1301 // list inlines a list of nodes.
1302 func (subst *inlsubst) list(ll ir.Nodes) []ir.Node {
1303         s := make([]ir.Node, 0, len(ll))
1304         for _, n := range ll {
1305                 s = append(s, subst.node(n))
1306         }
1307         return s
1308 }
1309
1310 // fields returns a list of the fields of a struct type representing receiver,
1311 // params, or results, after duplicating the field nodes and substituting the
1312 // Nname nodes inside the field nodes.
1313 func (subst *inlsubst) fields(oldt *types.Type) []*types.Field {
1314         oldfields := oldt.FieldSlice()
1315         newfields := make([]*types.Field, len(oldfields))
1316         for i := range oldfields {
1317                 newfields[i] = oldfields[i].Copy()
1318                 if oldfields[i].Nname != nil {
1319                         newfields[i].Nname = subst.node(oldfields[i].Nname.(*ir.Name))
1320                 }
1321         }
1322         return newfields
1323 }
1324
1325 // clovar creates a new ONAME node for a local variable or param of a closure
1326 // inside a function being inlined.
1327 func (subst *inlsubst) clovar(n *ir.Name) *ir.Name {
1328         m := ir.NewNameAt(n.Pos(), n.Sym())
1329         m.Class = n.Class
1330         m.SetType(n.Type())
1331         m.SetTypecheck(1)
1332         if n.IsClosureVar() {
1333                 m.SetIsClosureVar(true)
1334         }
1335         if n.Addrtaken() {
1336                 m.SetAddrtaken(true)
1337         }
1338         if n.Used() {
1339                 m.SetUsed(true)
1340         }
1341         m.Defn = n.Defn
1342
1343         m.Curfn = subst.newclofn
1344
1345         switch defn := n.Defn.(type) {
1346         case nil:
1347                 // ok
1348         case *ir.Name:
1349                 if !n.IsClosureVar() {
1350                         base.FatalfAt(n.Pos(), "want closure variable, got: %+v", n)
1351                 }
1352                 if n.Sym().Pkg != types.LocalPkg {
1353                         // If the closure came from inlining a function from
1354                         // another package, must change package of captured
1355                         // variable to localpkg, so that the fields of the closure
1356                         // struct are local package and can be accessed even if
1357                         // name is not exported. If you disable this code, you can
1358                         // reproduce the problem by running 'go test
1359                         // go/internal/srcimporter'. TODO(mdempsky) - maybe change
1360                         // how we create closure structs?
1361                         m.SetSym(types.LocalPkg.Lookup(n.Sym().Name))
1362                 }
1363                 // Make sure any inlvar which is the Defn
1364                 // of an ONAME closure var is rewritten
1365                 // during inlining. Don't substitute
1366                 // if Defn node is outside inlined function.
1367                 if subst.inlvars[n.Defn.(*ir.Name)] != nil {
1368                         m.Defn = subst.node(n.Defn)
1369                 }
1370         case *ir.AssignStmt, *ir.AssignListStmt:
1371                 // Mark node for reassignment at the end of inlsubst.node.
1372                 m.Defn = &subst.defnMarker
1373         case *ir.TypeSwitchGuard:
1374                 // TODO(mdempsky): Set m.Defn properly. See discussion on #45743.
1375         case *ir.RangeStmt:
1376                 // TODO: Set m.Defn properly if we support inlining range statement in the future.
1377         default:
1378                 base.FatalfAt(n.Pos(), "unexpected Defn: %+v", defn)
1379         }
1380
1381         if n.Outer != nil {
1382                 // Either the outer variable is defined in function being inlined,
1383                 // and we will replace it with the substituted variable, or it is
1384                 // defined outside the function being inlined, and we should just
1385                 // skip the outer variable (the closure variable of the function
1386                 // being inlined).
1387                 s := subst.node(n.Outer).(*ir.Name)
1388                 if s == n.Outer {
1389                         s = n.Outer.Outer
1390                 }
1391                 m.Outer = s
1392         }
1393         return m
1394 }
1395
1396 // closure does the necessary substitions for a ClosureExpr n and returns the new
1397 // closure node.
1398 func (subst *inlsubst) closure(n *ir.ClosureExpr) ir.Node {
1399         // Prior to the subst edit, set a flag in the inlsubst to indicate
1400         // that we don't want to update the source positions in the new
1401         // closure function. If we do this, it will appear that the
1402         // closure itself has things inlined into it, which is not the
1403         // case. See issue #46234 for more details. At the same time, we
1404         // do want to update the position in the new ClosureExpr (which is
1405         // part of the function we're working on). See #49171 for an
1406         // example of what happens if we miss that update.
1407         newClosurePos := subst.updatedPos(n.Pos())
1408         defer func(prev bool) { subst.noPosUpdate = prev }(subst.noPosUpdate)
1409         subst.noPosUpdate = true
1410
1411         //fmt.Printf("Inlining func %v with closure into %v\n", subst.fn, ir.FuncName(ir.CurFunc))
1412
1413         oldfn := n.Func
1414         newfn := ir.NewClosureFunc(oldfn.Pos(), true)
1415
1416         if subst.newclofn != nil {
1417                 //fmt.Printf("Inlining a closure with a nested closure\n")
1418         }
1419         prevxfunc := subst.newclofn
1420
1421         // Mark that we are now substituting within a closure (within the
1422         // inlined function), and create new nodes for all the local
1423         // vars/params inside this closure.
1424         subst.newclofn = newfn
1425         newfn.Dcl = nil
1426         newfn.ClosureVars = nil
1427         for _, oldv := range oldfn.Dcl {
1428                 newv := subst.clovar(oldv)
1429                 subst.inlvars[oldv] = newv
1430                 newfn.Dcl = append(newfn.Dcl, newv)
1431         }
1432         for _, oldv := range oldfn.ClosureVars {
1433                 newv := subst.clovar(oldv)
1434                 subst.inlvars[oldv] = newv
1435                 newfn.ClosureVars = append(newfn.ClosureVars, newv)
1436         }
1437
1438         // Need to replace ONAME nodes in
1439         // newfn.Type().FuncType().Receiver/Params/Results.FieldSlice().Nname
1440         oldt := oldfn.Type()
1441         newrecvs := subst.fields(oldt.Recvs())
1442         var newrecv *types.Field
1443         if len(newrecvs) > 0 {
1444                 newrecv = newrecvs[0]
1445         }
1446         newt := types.NewSignature(oldt.Pkg(), newrecv,
1447                 nil, subst.fields(oldt.Params()), subst.fields(oldt.Results()))
1448
1449         newfn.Nname.SetType(newt)
1450         newfn.Body = subst.list(oldfn.Body)
1451
1452         // Remove the nodes for the current closure from subst.inlvars
1453         for _, oldv := range oldfn.Dcl {
1454                 delete(subst.inlvars, oldv)
1455         }
1456         for _, oldv := range oldfn.ClosureVars {
1457                 delete(subst.inlvars, oldv)
1458         }
1459         // Go back to previous closure func
1460         subst.newclofn = prevxfunc
1461
1462         // Actually create the named function for the closure, now that
1463         // the closure is inlined in a specific function.
1464         newclo := newfn.OClosure
1465         newclo.SetPos(newClosurePos)
1466         newclo.SetInit(subst.list(n.Init()))
1467         return typecheck.Expr(newclo)
1468 }
1469
1470 // node recursively copies a node from the saved pristine body of the
1471 // inlined function, substituting references to input/output
1472 // parameters with ones to the tmpnames, and substituting returns with
1473 // assignments to the output.
1474 func (subst *inlsubst) node(n ir.Node) ir.Node {
1475         if n == nil {
1476                 return nil
1477         }
1478
1479         switch n.Op() {
1480         case ir.ONAME:
1481                 n := n.(*ir.Name)
1482
1483                 // Handle captured variables when inlining closures.
1484                 if n.IsClosureVar() && subst.newclofn == nil {
1485                         o := n.Outer
1486
1487                         // Deal with case where sequence of closures are inlined.
1488                         // TODO(danscales) - write test case to see if we need to
1489                         // go up multiple levels.
1490                         if o.Curfn != ir.CurFunc {
1491                                 o = o.Outer
1492                         }
1493
1494                         // make sure the outer param matches the inlining location
1495                         if o == nil || o.Curfn != ir.CurFunc {
1496                                 base.Fatalf("%v: unresolvable capture %v\n", ir.Line(n), n)
1497                         }
1498
1499                         if base.Flag.LowerM > 2 {
1500                                 fmt.Printf("substituting captured name %+v  ->  %+v\n", n, o)
1501                         }
1502                         return o
1503                 }
1504
1505                 if inlvar := subst.inlvars[n]; inlvar != nil { // These will be set during inlnode
1506                         if base.Flag.LowerM > 2 {
1507                                 fmt.Printf("substituting name %+v  ->  %+v\n", n, inlvar)
1508                         }
1509                         return inlvar
1510                 }
1511
1512                 if base.Flag.LowerM > 2 {
1513                         fmt.Printf("not substituting name %+v\n", n)
1514                 }
1515                 return n
1516
1517         case ir.OMETHEXPR:
1518                 n := n.(*ir.SelectorExpr)
1519                 return n
1520
1521         case ir.OLITERAL, ir.ONIL, ir.OTYPE:
1522                 // If n is a named constant or type, we can continue
1523                 // using it in the inline copy. Otherwise, make a copy
1524                 // so we can update the line number.
1525                 if n.Sym() != nil {
1526                         return n
1527                 }
1528
1529         case ir.ORETURN:
1530                 if subst.newclofn != nil {
1531                         // Don't do special substitutions if inside a closure
1532                         break
1533                 }
1534                 // Because of the above test for subst.newclofn,
1535                 // this return is guaranteed to belong to the current inlined function.
1536                 n := n.(*ir.ReturnStmt)
1537                 init := subst.list(n.Init())
1538                 if len(subst.retvars) != 0 && len(n.Results) != 0 {
1539                         as := ir.NewAssignListStmt(base.Pos, ir.OAS2, nil, nil)
1540
1541                         // Make a shallow copy of retvars.
1542                         // Otherwise OINLCALL.Rlist will be the same list,
1543                         // and later walk and typecheck may clobber it.
1544                         for _, n := range subst.retvars {
1545                                 as.Lhs.Append(n)
1546                         }
1547                         as.Rhs = subst.list(n.Results)
1548
1549                         if subst.fn.Inl.CanDelayResults {
1550                                 for _, n := range as.Lhs {
1551                                         as.PtrInit().Append(ir.NewDecl(base.Pos, ir.ODCL, n.(*ir.Name)))
1552                                         n.Name().Defn = as
1553                                 }
1554                         }
1555
1556                         init = append(init, typecheck.Stmt(as))
1557                 }
1558                 init = append(init, ir.NewBranchStmt(base.Pos, ir.OGOTO, subst.retlabel))
1559                 typecheck.Stmts(init)
1560                 return ir.NewBlockStmt(base.Pos, init)
1561
1562         case ir.OGOTO, ir.OBREAK, ir.OCONTINUE:
1563                 if subst.newclofn != nil {
1564                         // Don't do special substitutions if inside a closure
1565                         break
1566                 }
1567                 n := n.(*ir.BranchStmt)
1568                 m := ir.Copy(n).(*ir.BranchStmt)
1569                 m.SetPos(subst.updatedPos(m.Pos()))
1570                 m.SetInit(nil)
1571                 m.Label = translateLabel(n.Label)
1572                 return m
1573
1574         case ir.OLABEL:
1575                 if subst.newclofn != nil {
1576                         // Don't do special substitutions if inside a closure
1577                         break
1578                 }
1579                 n := n.(*ir.LabelStmt)
1580                 m := ir.Copy(n).(*ir.LabelStmt)
1581                 m.SetPos(subst.updatedPos(m.Pos()))
1582                 m.SetInit(nil)
1583                 m.Label = translateLabel(n.Label)
1584                 return m
1585
1586         case ir.OCLOSURE:
1587                 return subst.closure(n.(*ir.ClosureExpr))
1588
1589         }
1590
1591         m := ir.Copy(n)
1592         m.SetPos(subst.updatedPos(m.Pos()))
1593         ir.EditChildren(m, subst.edit)
1594
1595         if subst.newclofn == nil {
1596                 // Translate any label on FOR, RANGE loops, SWITCH or SELECT
1597                 switch m.Op() {
1598                 case ir.OFOR:
1599                         m := m.(*ir.ForStmt)
1600                         m.Label = translateLabel(m.Label)
1601                         return m
1602
1603                 case ir.ORANGE:
1604                         m := m.(*ir.RangeStmt)
1605                         m.Label = translateLabel(m.Label)
1606                         return m
1607
1608                 case ir.OSWITCH:
1609                         m := m.(*ir.SwitchStmt)
1610                         m.Label = translateLabel(m.Label)
1611                         return m
1612
1613                 case ir.OSELECT:
1614                         m := m.(*ir.SelectStmt)
1615                         m.Label = translateLabel(m.Label)
1616                         return m
1617                 }
1618         }
1619
1620         switch m := m.(type) {
1621         case *ir.AssignStmt:
1622                 if lhs, ok := m.X.(*ir.Name); ok && lhs.Defn == &subst.defnMarker {
1623                         lhs.Defn = m
1624                 }
1625         case *ir.AssignListStmt:
1626                 for _, lhs := range m.Lhs {
1627                         if lhs, ok := lhs.(*ir.Name); ok && lhs.Defn == &subst.defnMarker {
1628                                 lhs.Defn = m
1629                         }
1630                 }
1631         }
1632
1633         return m
1634 }
1635
1636 // translateLabel makes a label from an inlined function (if non-nil) be unique by
1637 // adding "·inlgen".
1638 func translateLabel(l *types.Sym) *types.Sym {
1639         if l == nil {
1640                 return nil
1641         }
1642         p := fmt.Sprintf("%s·%d", l.Name, inlgen)
1643         return typecheck.Lookup(p)
1644 }
1645
1646 func (subst *inlsubst) updatedPos(xpos src.XPos) src.XPos {
1647         if subst.noPosUpdate {
1648                 return xpos
1649         }
1650         pos := base.Ctxt.PosTable.Pos(xpos)
1651         oldbase := pos.Base() // can be nil
1652         newbase := subst.bases[oldbase]
1653         if newbase == nil {
1654                 newbase = src.NewInliningBase(oldbase, subst.newInlIndex)
1655                 subst.bases[oldbase] = newbase
1656         }
1657         pos.SetBase(newbase)
1658         return base.Ctxt.PosTable.XPos(pos)
1659 }
1660
1661 func pruneUnusedAutos(ll []*ir.Name, vis *hairyVisitor) []*ir.Name {
1662         s := make([]*ir.Name, 0, len(ll))
1663         for _, n := range ll {
1664                 if n.Class == ir.PAUTO {
1665                         if !vis.usedLocals.Has(n) {
1666                                 continue
1667                         }
1668                 }
1669                 s = append(s, n)
1670         }
1671         return s
1672 }
1673
1674 // numNonClosures returns the number of functions in list which are not closures.
1675 func numNonClosures(list []*ir.Func) int {
1676         count := 0
1677         for _, fn := range list {
1678                 if fn.OClosure == nil {
1679                         count++
1680                 }
1681         }
1682         return count
1683 }
1684
1685 func doList(list []ir.Node, do func(ir.Node) bool) bool {
1686         for _, x := range list {
1687                 if x != nil {
1688                         if do(x) {
1689                                 return true
1690                         }
1691                 }
1692         }
1693         return false
1694 }
1695
1696 // isIndexingCoverageCounter returns true if the specified node 'n' is indexing
1697 // into a coverage counter array.
1698 func isIndexingCoverageCounter(n ir.Node) bool {
1699         if n.Op() != ir.OINDEX {
1700                 return false
1701         }
1702         ixn := n.(*ir.IndexExpr)
1703         if ixn.X.Op() != ir.ONAME || !ixn.X.Type().IsArray() {
1704                 return false
1705         }
1706         nn := ixn.X.(*ir.Name)
1707         return nn.CoverageCounter()
1708 }
1709
1710 // isAtomicCoverageCounterUpdate examines the specified node to
1711 // determine whether it represents a call to sync/atomic.AddUint32 to
1712 // increment a coverage counter.
1713 func isAtomicCoverageCounterUpdate(cn *ir.CallExpr) bool {
1714         if cn.X.Op() != ir.ONAME {
1715                 return false
1716         }
1717         name := cn.X.(*ir.Name)
1718         if name.Class != ir.PFUNC {
1719                 return false
1720         }
1721         fn := name.Sym().Name
1722         if name.Sym().Pkg.Path != "sync/atomic" || fn != "AddUint32" {
1723                 return false
1724         }
1725         if len(cn.Args) != 2 || cn.Args[0].Op() != ir.OADDR {
1726                 return false
1727         }
1728         adn := cn.Args[0].(*ir.AddrExpr)
1729         v := isIndexingCoverageCounter(adn.X)
1730         return v
1731 }