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