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