File size: 12,242 Bytes
fc11197
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
// Copyright 2025 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package bloop

// This file contains support routines for keeping
// statements alive
// in such loops (example):
//
//	for b.Loop() {
//		var a, b int
//		a = 5
//		b = 6
//		f(a, b)
//	}
//
// The results of a, b and f(a, b) will be kept alive.
//
// Formally, the lhs (if they are [ir.Name]-s) of
// [ir.AssignStmt], [ir.AssignListStmt],
// [ir.AssignOpStmt], and the results of [ir.CallExpr]
// or its args if it doesn't return a value will be kept
// alive.
//
// The keep alive logic is implemented with as wrapping a
// runtime.KeepAlive around the Name.
//
// TODO: currently this is implemented with KeepAlive
// because it will prevent DSE and DCE which is probably
// what we want right now. And KeepAlive takes an ssa
// value instead of a symbol, which is easier to manage.
// But since KeepAlive's context was mainly in the runtime
// and GC, should we implement a new intrinsic that lowers
// to OpVarLive? Peeling out the symbols is a bit tricky
// and also VarLive seems to assume that there exists a
// VarDef on the same symbol that dominates it.

import (
	"cmd/compile/internal/base"
	"cmd/compile/internal/ir"
	"cmd/compile/internal/reflectdata"
	"cmd/compile/internal/typecheck"
	"cmd/compile/internal/types"
	"cmd/internal/src"
)

// getNameFromNode tries to iteratively peel down the node to
// get the name.
func getNameFromNode(n ir.Node) *ir.Name {
	// Tries to iteratively peel down the node to get the names.
	for n != nil {
		switch n.Op() {
		case ir.ONAME:
			// Found the name, stop the loop.
			return n.(*ir.Name)
		case ir.OSLICE, ir.OSLICE3:
			n = n.(*ir.SliceExpr).X
		case ir.ODOT:
			n = n.(*ir.SelectorExpr).X
		case ir.OCONV, ir.OCONVIFACE, ir.OCONVNOP:
			n = n.(*ir.ConvExpr).X
		case ir.OADDR:
			n = n.(*ir.AddrExpr).X
		case ir.ODOTPTR:
			n = n.(*ir.SelectorExpr).X
		case ir.OINDEX, ir.OINDEXMAP:
			n = n.(*ir.IndexExpr).X
		default:
			n = nil
		}
	}
	return nil
}

// getAddressableNameFromNode is like getNameFromNode but returns nil if the node is not addressable.
func getAddressableNameFromNode(n ir.Node) *ir.Name {
	if name := getNameFromNode(n); name != nil && ir.IsAddressable(name) {
		return name
	}
	return nil
}

// keepAliveAt returns a statement that is either curNode, or a
// block containing curNode followed by a call to runtime.KeepAlive for each
// node in ns. These calls ensure that nodes in ns will be live until
// after curNode's execution.
func keepAliveAt(ns []ir.Node, curNode ir.Node) ir.Node {
	if len(ns) == 0 {
		return curNode
	}

	pos := curNode.Pos()
	calls := []ir.Node{curNode}
	for _, n := range ns {
		if n == nil {
			continue
		}
		if n.Sym() == nil {
			continue
		}
		if n.Sym().IsBlank() {
			continue
		}
		if !ir.IsAddressable(n) {
			base.FatalfAt(n.Pos(), "keepAliveAt: node %v is not addressable", n)
		}
		arg := ir.NewConvExpr(pos, ir.OCONV, types.Types[types.TUNSAFEPTR], typecheck.NodAddr(n))
		if !n.Type().IsInterface() {
			srcRType0 := reflectdata.TypePtrAt(pos, n.Type())
			arg.TypeWord = srcRType0
			arg.SrcRType = srcRType0
		}
		callExpr := typecheck.Call(pos,
			typecheck.LookupRuntime("KeepAlive"),
			[]ir.Node{arg}, false).(*ir.CallExpr)
		callExpr.IsCompilerVarLive = true
		callExpr.NoInline = true
		calls = append(calls, callExpr)
	}

	return ir.NewBlockStmt(pos, calls)
}

func debugName(name *ir.Name, pos src.XPos) {
	if base.Flag.LowerM > 1 {
		if name.Linksym() != nil {
			base.WarnfAt(pos, "%s will be kept alive", name.Linksym().Name)
		} else {
			base.WarnfAt(pos, "expr will be kept alive")
		}
	}
}

// preserveStmt transforms stmt so that any names defined/assigned within it
// are used after stmt's execution, preventing their dead code elimination
// and dead store elimination. The return value is the transformed statement.
func preserveStmt(curFn *ir.Func, stmt ir.Node) (ret ir.Node) {
	ret = stmt
	switch n := stmt.(type) {
	case *ir.AssignStmt:
		// If the left hand side is blank, we need to assign it to a temp
		// so that it can be kept alive.
		if ir.IsBlank(n.X) {
			tmp := typecheck.TempAt(n.Pos(), curFn, n.Y.Type())
			n.X = tmp
			n.Def = true
			n.PtrInit().Append(typecheck.Stmt(ir.NewDecl(n.Pos(), ir.ODCL, tmp)))
			stmt = typecheck.AssignExpr(n)
			n = stmt.(*ir.AssignStmt)
		}
		// Peel down struct and slice indexing to get the names
		name := getAddressableNameFromNode(n.X)
		if name != nil {
			debugName(name, n.Pos())
			ret = keepAliveAt([]ir.Node{name}, n)
		} else if deref, ok := n.X.(*ir.StarExpr); ok && deref != nil {
			ret = keepAliveAt([]ir.Node{deref}, n)
			if base.Flag.LowerM > 1 {
				base.WarnfAt(n.Pos(), "dereference will be kept alive")
			}
		} else if base.Flag.LowerM > 1 {
			base.WarnfAt(n.Pos(), "expr is unknown to bloop pass")
		}
	case *ir.AssignListStmt:
		ns := []ir.Node{}
		hasBlank := false
		for i, lhs := range n.Lhs {
			if ir.IsBlank(lhs) {
				// If the left hand side has blanks, we need to assign them to temps
				// so that they can be kept alive.
				var typ *types.Type
				// AssignListStmt can have tuple or a list of expressions on the right hand side.
				if len(n.Rhs) == 1 && n.Rhs[0].Type() != nil &&
					n.Rhs[0].Type().IsTuple() &&
					len(n.Lhs) == n.Rhs[0].Type().NumFields() {
					typ = n.Rhs[0].Type().Field(i).Type
				} else if len(n.Rhs) == len(n.Lhs) {
					typ = n.Rhs[i].Type()
				} else {
					// Unrecognized shapes, skip?
					base.WarnfAt(n.Pos(), "unrecognized shape for assign list stmt for blank assignment")
					continue
				}
				tmp := typecheck.TempAt(n.Pos(), curFn, typ)
				n.Lhs[i] = tmp
				n.PtrInit().Append(typecheck.Stmt(ir.NewDecl(n.Pos(), ir.ODCL, tmp)))
				hasBlank = true
				lhs = tmp
			}
			name := getAddressableNameFromNode(lhs)
			if name != nil {
				debugName(name, n.Pos())
				ns = append(ns, name)
			} else if deref, ok := lhs.(*ir.StarExpr); ok && deref != nil {
				ns = append(ns, deref)
				if base.Flag.LowerM > 1 {
					base.WarnfAt(n.Pos(), "dereference will be kept alive")
				}
			} else if base.Flag.LowerM > 1 {
				base.WarnfAt(n.Pos(), "expr is unknown to bloop pass")
			}
		}
		if hasBlank {
			// blank nodes are rewritten to temps, we need to typecheck the node again.
			n.Def = true
			stmt = typecheck.AssignExpr(n)
			n = stmt.(*ir.AssignListStmt)
		}
		ret = keepAliveAt(ns, n)
	case *ir.AssignOpStmt:
		name := getAddressableNameFromNode(n.X)
		if name != nil {
			debugName(name, n.Pos())
			ret = keepAliveAt([]ir.Node{name}, n)
		} else if deref, ok := n.X.(*ir.StarExpr); ok && deref != nil {
			ret = keepAliveAt([]ir.Node{deref}, n)
			if base.Flag.LowerM > 1 {
				base.WarnfAt(n.Pos(), "dereference will be kept alive")
			}
		} else if base.Flag.LowerM > 1 {
			base.WarnfAt(n.Pos(), "expr is unknown to bloop pass")
		}
	case *ir.CallExpr:
		curNode := stmt
		if n.Fun != nil && n.Fun.Type() != nil && n.Fun.Type().NumResults() != 0 {
			ns := []ir.Node{}
			// This function's results are not assigned, assign them to
			// auto tmps and then keepAliveAt these autos.
			// Note: markStmt assumes the context that it's called - this CallExpr is
			// not within another OAS2, which is guaranteed by the case above.
			results := n.Fun.Type().Results()
			lhs := make([]ir.Node, len(results))
			for i, res := range results {
				tmp := typecheck.TempAt(n.Pos(), curFn, res.Type)
				lhs[i] = tmp
				ns = append(ns, tmp)
			}

			// Create an assignment statement.
			assign := typecheck.AssignExpr(
				ir.NewAssignListStmt(n.Pos(), ir.OAS2, lhs,
					[]ir.Node{n})).(*ir.AssignListStmt)
			assign.Def = true
			for _, tmp := range lhs {
				// Place temp declarations in the loop body to help escape analysis.
				assign.PtrInit().Append(typecheck.Stmt(ir.NewDecl(assign.Pos(), ir.ODCL, tmp.(*ir.Name))))
			}
			curNode = assign
			plural := ""
			if len(results) > 1 {
				plural = "s"
			}
			if base.Flag.LowerM > 1 {
				base.WarnfAt(n.Pos(), "function result%s will be kept alive", plural)
			}
			ret = keepAliveAt(ns, curNode)
		} else {
			// This function probably doesn't return anything, keep its args alive.
			argTmps := []ir.Node{}
			names := []ir.Node{}
			for i, a := range n.Args {
				if name := getAddressableNameFromNode(a); name != nil {
					// If they are name, keep them alive directly.
					debugName(name, n.Pos())
					names = append(names, name)
				} else if a.Op() == ir.OSLICELIT {
					// variadic args are encoded as slice literal.
					s := a.(*ir.CompLitExpr)
					ns := []ir.Node{}
					for i, elem := range s.List {
						if name := getAddressableNameFromNode(elem); name != nil {
							debugName(name, n.Pos())
							ns = append(ns, name)
						} else {
							// We need a temporary to save this arg.
							tmp := typecheck.TempAt(elem.Pos(), curFn, elem.Type())
							assign := ir.NewAssignStmt(elem.Pos(), tmp, elem)
							assign.Def = true
							// Place temp declarations in the loop body to help escape analysis.
							assign.PtrInit().Append(typecheck.Stmt(ir.NewDecl(assign.Pos(), ir.ODCL, tmp)))
							argTmps = append(argTmps, typecheck.AssignExpr(assign))
							names = append(names, tmp)
							s.List[i] = tmp
							if base.Flag.LowerM > 1 {
								base.WarnfAt(n.Pos(), "function arg will be kept alive")
							}
						}
					}
					names = append(names, ns...)
				} else {
					// expressions, we need to assign them to temps and change the original arg to reference
					// them.
					tmp := typecheck.TempAt(n.Pos(), curFn, a.Type())
					assign := ir.NewAssignStmt(n.Pos(), tmp, a)
					assign.Def = true
					// Place temp declarations in the loop body to help escape analysis.
					assign.PtrInit().Append(typecheck.Stmt(ir.NewDecl(assign.Pos(), ir.ODCL, tmp)))
					argTmps = append(argTmps, typecheck.AssignExpr(assign))
					names = append(names, tmp)
					n.Args[i] = tmp
					if base.Flag.LowerM > 1 {
						base.WarnfAt(n.Pos(), "function arg will be kept alive")
					}
				}
			}
			if len(argTmps) > 0 {
				argTmps = append(argTmps, n)
				curNode = ir.NewBlockStmt(n.Pos(), argTmps)
			}
			ret = keepAliveAt(names, curNode)
		}
	}
	return
}

func preserveStmts(curFn *ir.Func, list ir.Nodes) {
	for i := range list {
		list[i] = preserveStmt(curFn, list[i])
	}
}

// isTestingBLoop returns true if it matches the node as a
// testing.(*B).Loop. See issue #61515.
func isTestingBLoop(t ir.Node) bool {
	if t.Op() != ir.OFOR {
		return false
	}
	nFor, ok := t.(*ir.ForStmt)
	if !ok || nFor.Cond == nil || nFor.Cond.Op() != ir.OCALLFUNC {
		return false
	}
	n, ok := nFor.Cond.(*ir.CallExpr)
	if !ok || n.Fun == nil || n.Fun.Op() != ir.OMETHEXPR {
		return false
	}
	name := ir.MethodExprName(n.Fun)
	if name == nil {
		return false
	}
	if fSym := name.Sym(); fSym != nil && name.Class == ir.PFUNC && fSym.Pkg != nil &&
		fSym.Name == "(*B).Loop" && fSym.Pkg.Path == "testing" {
		// Attempting to match a function call to testing.(*B).Loop
		return true
	}
	return false
}

type editor struct {
	inBloop bool
	curFn   *ir.Func
}

func (e editor) edit(n ir.Node) ir.Node {
	e.inBloop = isTestingBLoop(n) || e.inBloop
	// It's in bloop, mark the stmts with bodies.
	ir.EditChildren(n, e.edit)
	if e.inBloop {
		switch n := n.(type) {
		case *ir.ForStmt:
			preserveStmts(e.curFn, n.Body)
		case *ir.IfStmt:
			preserveStmts(e.curFn, n.Body)
			preserveStmts(e.curFn, n.Else)
		case *ir.BlockStmt:
			preserveStmts(e.curFn, n.List)
		case *ir.CaseClause:
			preserveStmts(e.curFn, n.List)
			preserveStmts(e.curFn, n.Body)
		case *ir.CommClause:
			preserveStmts(e.curFn, n.Body)
		case *ir.RangeStmt:
			preserveStmts(e.curFn, n.Body)
		}
	}
	return n
}

// BloopWalk performs a walk on all functions in the package
// if it imports testing and wrap the results of all qualified
// statements in a runtime.KeepAlive intrinsic call. See package
// doc for more details.
//
//	for b.Loop() {...}
//
// loop's body.
func BloopWalk(pkg *ir.Package) {
	hasTesting := false
	for _, i := range pkg.Imports {
		if i.Path == "testing" {
			hasTesting = true
			break
		}
	}
	if !hasTesting {
		return
	}
	for _, fn := range pkg.Funcs {
		e := editor{false, fn}
		ir.EditChildren(fn, e.edit)
	}
}