1 // Copyright 2018 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.
10 "cmd/compile/internal/base"
11 "cmd/compile/internal/ir"
12 "cmd/compile/internal/logopt"
13 "cmd/compile/internal/typecheck"
14 "cmd/compile/internal/types"
20 // Here we analyze functions to determine which Go variables
21 // (including implicit allocations such as calls to "new" or "make",
22 // composite literals, etc.) can be allocated on the stack. The two
23 // key invariants we have to ensure are: (1) pointers to stack objects
24 // cannot be stored in the heap, and (2) pointers to a stack object
25 // cannot outlive that object (e.g., because the declaring function
26 // returned and destroyed the object's stack frame, or its space is
27 // reused across loop iterations for logically distinct variables).
29 // We implement this with a static data-flow analysis of the AST.
30 // First, we construct a directed weighted graph where vertices
31 // (termed "locations") represent variables allocated by statements
32 // and expressions, and edges represent assignments between variables
33 // (with weights representing addressing/dereference counts).
35 // Next we walk the graph looking for assignment paths that might
36 // violate the invariants stated above. If a variable v's address is
37 // stored in the heap or elsewhere that may outlive it, then v is
38 // marked as requiring heap allocation.
40 // To support interprocedural analysis, we also record data-flow from
41 // each function's parameters to the heap and to its result
42 // parameters. This information is summarized as "parameter tags",
43 // which are used at static call sites to improve escape analysis of
44 // function arguments.
46 // Constructing the location graph.
48 // Every allocating statement (e.g., variable declaration) or
49 // expression (e.g., "new" or "make") is first mapped to a unique
52 // We also model every Go assignment as a directed edges between
53 // locations. The number of dereference operations minus the number of
54 // addressing operations is recorded as the edge's weight (termed
55 // "derefs"). For example:
64 // Note that the & operator can only be applied to addressable
65 // expressions, and the expression &x itself is not addressable, so
66 // derefs cannot go below -1.
68 // Every Go language construct is lowered into this representation,
69 // generally without sensitivity to flow, path, or context; and
70 // without distinguishing elements within a compound variable. For
73 // var x struct { f, g *int }
78 // is modeled simply as
82 // That is, we don't distinguish x.f from x.g, or u[0] from u[1],
83 // u[2], etc. However, we do record the implicit dereference involved
84 // in indexing a slice.
86 // A batch holds escape analysis state that's shared across an entire
87 // batch of functions being analyzed at once.
98 // A closure holds a closure expression and its spill hole (i.e.,
99 // where the hole representing storing into its closure record).
100 type closure struct {
105 // An escape holds state specific to a single function being analyzed
110 curfn *ir.Func // function being analyzed
112 labels map[*types.Sym]labelState // known labels
114 // loopDepth counts the current loop nesting depth within
115 // curfn. It increments within each "for" loop and at each
116 // label with a corresponding backwards "goto" (i.e.,
117 // unstructured loop).
121 func Funcs(all []*ir.Func) {
122 ir.VisitFuncsBottomUp(all, Batch)
125 // Batch performs escape analysis on a minimal batch of
127 func Batch(fns []*ir.Func, recursive bool) {
128 for _, fn := range fns {
129 if fn.Op() != ir.ODCLFUNC {
130 base.Fatalf("unexpected node: %v", fn)
135 b.heapLoc.attrs = attrEscapes | attrPersists | attrMutates | attrCalls
136 b.mutatorLoc.attrs = attrMutates
137 b.calleeLoc.attrs = attrCalls
139 // Construct data-flow graph from syntax trees.
140 for _, fn := range fns {
142 s := fmt.Sprintf("\nbefore escape %v", fn)
147 for _, fn := range fns {
148 if !fn.IsHiddenClosure() {
153 // We've walked the function bodies, so we've seen everywhere a
154 // variable might be reassigned or have it's address taken. Now we
155 // can decide whether closures should capture their free variables
156 // by value or reference.
157 for _, closure := range b.closures {
158 b.flowClosure(closure.k, closure.clo)
162 for _, loc := range b.allLocs {
163 if why := HeapAllocReason(loc.n); why != "" {
164 b.flow(b.heapHole().addr(loc.n, why), loc)
172 func (b *batch) with(fn *ir.Func) *escape {
180 func (b *batch) initFunc(fn *ir.Func) {
182 if fn.Esc() != escFuncUnknown {
183 base.Fatalf("unexpected node: %v", fn)
185 fn.SetEsc(escFuncPlanned)
186 if base.Flag.LowerM > 3 {
187 ir.Dump("escAnalyze", fn)
190 // Allocate locations for local variables.
191 for _, n := range fn.Dcl {
195 // Also for hidden parameters (e.g., the ".this" parameter to a
196 // method value wrapper).
197 if fn.OClosure == nil {
198 for _, n := range fn.ClosureVars {
199 e.newLoc(n.Canonical(), true)
203 // Initialize resultIndex for result parameters.
204 for i, f := range fn.Type().Results().FieldSlice() {
205 e.oldLoc(f.Nname.(*ir.Name)).resultIndex = 1 + i
209 func (b *batch) walkFunc(fn *ir.Func) {
211 fn.SetEsc(escFuncStarted)
213 // Identify labels that mark the head of an unstructured loop.
214 ir.Visit(fn, func(n ir.Node) {
217 n := n.(*ir.LabelStmt)
218 if n.Label.IsBlank() {
222 e.labels = make(map[*types.Sym]labelState)
224 e.labels[n.Label] = nonlooping
227 // If we visited the label before the goto,
228 // then this is a looping label.
229 n := n.(*ir.BranchStmt)
230 if e.labels[n.Label] == nonlooping {
231 e.labels[n.Label] = looping
238 if len(e.labels) != 0 {
239 base.FatalfAt(fn.Pos(), "leftover labels after walkFunc")
243 func (b *batch) flowClosure(k hole, clo *ir.ClosureExpr) {
244 for _, cv := range clo.Func.ClosureVars {
248 base.FatalfAt(cv.Pos(), "closure variable never captured: %v", cv)
251 // Capture by value for variables <= 128 bytes that are never reassigned.
252 n.SetByval(!loc.addrtaken && !loc.reassigned && n.Type().Size() <= 128)
255 if n.Sym().Name == typecheck.LocalDictName {
256 base.FatalfAt(n.Pos(), "dictionary variable not captured by value")
260 if base.Flag.LowerM > 1 {
265 base.WarnfAt(n.Pos(), "%v capturing by %s: %v (addr=%v assign=%v width=%d)", n.Curfn, how, n, loc.addrtaken, loc.reassigned, n.Type().Size())
268 // Flow captured variables to closure.
271 k = k.addr(cv, "reference")
273 b.flow(k.note(cv, "captured by a closure"), loc)
277 func (b *batch) finish(fns []*ir.Func) {
278 // Record parameter tags for package export data.
279 for _, fn := range fns {
280 fn.SetEsc(escFuncTagged)
283 for _, fs := range &types.RecvsParams {
284 for _, f := range fs(fn.Type()).Fields().Slice() {
286 f.Note = b.paramTag(fn, narg, f)
291 for _, loc := range b.allLocs {
297 if n.Op() == ir.ONAME {
302 // Update n.Esc based on escape analysis results.
304 // Omit escape diagnostics for go/defer wrappers, at least for now.
305 // Historically, we haven't printed them, and test cases don't expect them.
306 // TODO(mdempsky): Update tests to expect this.
307 goDeferWrapper := n.Op() == ir.OCLOSURE && n.(*ir.ClosureExpr).Func.Wrapper()
309 if loc.hasAttr(attrEscapes) {
310 if n.Op() == ir.ONAME {
311 if base.Flag.CompilingRuntime {
312 base.ErrorfAt(n.Pos(), 0, "%v escapes to heap, not allowed in runtime", n)
314 if base.Flag.LowerM != 0 {
315 base.WarnfAt(n.Pos(), "moved to heap: %v", n)
318 if base.Flag.LowerM != 0 && !goDeferWrapper {
319 base.WarnfAt(n.Pos(), "%v escapes to heap", n)
321 if logopt.Enabled() {
322 var e_curfn *ir.Func // TODO(mdempsky): Fix.
323 logopt.LogOpt(n.Pos(), "escape", "escape", ir.FuncName(e_curfn))
328 if base.Flag.LowerM != 0 && n.Op() != ir.ONAME && !goDeferWrapper {
329 base.WarnfAt(n.Pos(), "%v does not escape", n)
332 if !loc.hasAttr(attrPersists) {
335 n := n.(*ir.ClosureExpr)
338 n := n.(*ir.SelectorExpr)
341 n := n.(*ir.CompLitExpr)
347 // If the result of a string->[]byte conversion is never mutated,
348 // then it can simply reuse the string's memory directly.
349 if base.Debug.ZeroCopy != 0 {
350 if n, ok := n.(*ir.ConvExpr); ok && n.Op() == ir.OSTR2BYTES && !loc.hasAttr(attrMutates) {
351 if base.Flag.LowerM >= 1 {
352 base.WarnfAt(n.Pos(), "zero-copy string->[]byte conversion")
354 n.SetOp(ir.OSTR2BYTESTMP)
360 // inMutualBatch reports whether function fn is in the batch of
361 // mutually recursive functions being analyzed. When this is true,
362 // fn has not yet been analyzed, so its parameters and results
363 // should be incorporated directly into the flow graph instead of
364 // relying on its escape analysis tagging.
365 func (b *batch) inMutualBatch(fn *ir.Name) bool {
366 if fn.Defn != nil && fn.Defn.Esc() < escFuncTagged {
367 if fn.Defn.Esc() == escFuncUnknown {
368 base.FatalfAt(fn.Pos(), "graph inconsistency: %v", fn)
376 escFuncUnknown = 0 + iota
382 // Mark labels that have no backjumps to them as not increasing e.loopdepth.
386 looping labelState = 1 + iota
390 func (b *batch) paramTag(fn *ir.Func, narg int, f *types.Field) string {
391 name := func() string {
395 return fmt.Sprintf("arg#%d", narg)
398 // Only report diagnostics for user code;
399 // not for wrappers generated around them.
400 // TODO(mdempsky): Generalize this.
401 diagnose := base.Flag.LowerM != 0 && !(fn.Wrapper() || fn.Dupok())
403 if len(fn.Body) == 0 {
404 // Assume that uintptr arguments must be held live across the call.
405 // This is most important for syscall.Syscall.
406 // See golang.org/issue/13372.
407 // This really doesn't have much to do with escape analysis per se,
408 // but we are reusing the ability to annotate an individual function
409 // argument and pass those annotations along to importing code.
410 fn.Pragma |= ir.UintptrKeepAlive
412 if f.Type.IsUintptr() {
414 base.WarnfAt(f.Pos, "assuming %v is unsafe uintptr", name())
419 if !f.Type.HasPointers() { // don't bother tagging for scalars
425 // External functions are assumed unsafe, unless
426 // //go:noescape is given before the declaration.
427 if fn.Pragma&ir.Noescape != 0 {
428 if diagnose && f.Sym != nil {
429 base.WarnfAt(f.Pos, "%v does not escape", name())
434 if diagnose && f.Sym != nil {
435 base.WarnfAt(f.Pos, "leaking param: %v", name())
443 if fn.Pragma&ir.UintptrEscapes != 0 {
444 if f.Type.IsUintptr() {
446 base.WarnfAt(f.Pos, "marking %v as escaping uintptr", name())
450 if f.IsDDD() && f.Type.Elem().IsUintptr() {
451 // final argument is ...uintptr.
453 base.WarnfAt(f.Pos, "marking %v as escaping ...uintptr", name())
459 if !f.Type.HasPointers() { // don't bother tagging for scalars
463 // Unnamed parameters are unused and therefore do not escape.
464 if f.Sym == nil || f.Sym.IsBlank() {
469 n := f.Nname.(*ir.Name)
474 if diagnose && !loc.hasAttr(attrEscapes) {
475 b.reportLeaks(f.Pos, name(), esc, fn.Type())
481 func (b *batch) reportLeaks(pos src.XPos, name string, esc leaks, sig *types.Type) {
483 if x := esc.Heap(); x >= 0 {
485 base.WarnfAt(pos, "leaking param: %v", name)
487 // TODO(mdempsky): Mention level=x like below?
488 base.WarnfAt(pos, "leaking param content: %v", name)
492 for i := 0; i < numEscResults; i++ {
493 if x := esc.Result(i); x >= 0 {
494 res := sig.Results().Field(i).Sym
495 base.WarnfAt(pos, "leaking param: %v to result %v level=%d", name, res, x)
500 if base.Debug.EscapeMutationsCalls <= 0 {
502 base.WarnfAt(pos, "%v does not escape", name)
507 if x := esc.Mutator(); x >= 0 {
508 base.WarnfAt(pos, "mutates param: %v derefs=%v", name, x)
511 if x := esc.Callee(); x >= 0 {
512 base.WarnfAt(pos, "calls param: %v derefs=%v", name, x)
517 base.WarnfAt(pos, "%v does not escape, mutate, or call", name)