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