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