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