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