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