Source file src/cmd/compile/internal/bloop/bloop.go

     1  // Copyright 2025 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  package bloop
     6  
     7  // This file contains support routines for keeping
     8  // statements alive
     9  // in such loops (example):
    10  //
    11  //	for b.Loop() {
    12  //		var a, b int
    13  //		a = 5
    14  //		b = 6
    15  //		f(a, b)
    16  //	}
    17  //
    18  // The results of a, b and f(a, b) will be kept alive.
    19  //
    20  // Formally, the lhs (if they are [ir.Name]-s) of
    21  // [ir.AssignStmt], [ir.AssignListStmt],
    22  // [ir.AssignOpStmt], and the results of [ir.CallExpr]
    23  // or its args if it doesn't return a value will be kept
    24  // alive.
    25  //
    26  // The keep alive logic is implemented with as wrapping a
    27  // runtime.KeepAlive around the Name.
    28  //
    29  // TODO: currently this is implemented with KeepAlive
    30  // because it will prevent DSE and DCE which is probably
    31  // what we want right now. And KeepAlive takes an ssa
    32  // value instead of a symbol, which is easier to manage.
    33  // But since KeepAlive's context was mainly in the runtime
    34  // and GC, should we implement a new intrinsic that lowers
    35  // to OpVarLive? Peeling out the symbols is a bit tricky
    36  // and also VarLive seems to assume that there exists a
    37  // VarDef on the same symbol that dominates it.
    38  
    39  import (
    40  	"cmd/compile/internal/base"
    41  	"cmd/compile/internal/ir"
    42  	"cmd/compile/internal/reflectdata"
    43  	"cmd/compile/internal/typecheck"
    44  	"cmd/compile/internal/types"
    45  	"cmd/internal/src"
    46  )
    47  
    48  // getNameFromNode tries to iteratively peel down the node to
    49  // get the name.
    50  func getNameFromNode(n ir.Node) *ir.Name {
    51  	// Tries to iteratively peel down the node to get the names.
    52  	for n != nil {
    53  		switch n.Op() {
    54  		case ir.ONAME:
    55  			// Found the name, stop the loop.
    56  			return n.(*ir.Name)
    57  		case ir.OSLICE, ir.OSLICE3:
    58  			n = n.(*ir.SliceExpr).X
    59  		case ir.ODOT:
    60  			n = n.(*ir.SelectorExpr).X
    61  		case ir.OCONV, ir.OCONVIFACE, ir.OCONVNOP:
    62  			n = n.(*ir.ConvExpr).X
    63  		case ir.OADDR:
    64  			n = n.(*ir.AddrExpr).X
    65  		case ir.ODOTPTR:
    66  			n = n.(*ir.SelectorExpr).X
    67  		case ir.OINDEX, ir.OINDEXMAP:
    68  			n = n.(*ir.IndexExpr).X
    69  		default:
    70  			n = nil
    71  		}
    72  	}
    73  	return nil
    74  }
    75  
    76  // getAddressableNameFromNode is like getNameFromNode but returns nil if the node is not addressable.
    77  func getAddressableNameFromNode(n ir.Node) *ir.Name {
    78  	if name := getNameFromNode(n); name != nil && ir.IsAddressable(name) {
    79  		return name
    80  	}
    81  	return nil
    82  }
    83  
    84  // keepAliveAt returns a statement that is either curNode, or a
    85  // block containing curNode followed by a call to runtime.KeepAlive for each
    86  // node in ns. These calls ensure that nodes in ns will be live until
    87  // after curNode's execution.
    88  func keepAliveAt(ns []ir.Node, curNode ir.Node) ir.Node {
    89  	if len(ns) == 0 {
    90  		return curNode
    91  	}
    92  
    93  	pos := curNode.Pos()
    94  	calls := []ir.Node{curNode}
    95  	for _, n := range ns {
    96  		if n == nil {
    97  			continue
    98  		}
    99  		if n.Sym() == nil {
   100  			continue
   101  		}
   102  		if n.Sym().IsBlank() {
   103  			continue
   104  		}
   105  		if !ir.IsAddressable(n) {
   106  			base.FatalfAt(n.Pos(), "keepAliveAt: node %v is not addressable", n)
   107  		}
   108  		arg := ir.NewConvExpr(pos, ir.OCONV, types.Types[types.TUNSAFEPTR], typecheck.NodAddr(n))
   109  		if !n.Type().IsInterface() {
   110  			srcRType0 := reflectdata.TypePtrAt(pos, n.Type())
   111  			arg.TypeWord = srcRType0
   112  			arg.SrcRType = srcRType0
   113  		}
   114  		callExpr := typecheck.Call(pos,
   115  			typecheck.LookupRuntime("KeepAlive"),
   116  			[]ir.Node{arg}, false).(*ir.CallExpr)
   117  		callExpr.IsCompilerVarLive = true
   118  		callExpr.NoInline = true
   119  		calls = append(calls, callExpr)
   120  	}
   121  
   122  	return ir.NewBlockStmt(pos, calls)
   123  }
   124  
   125  func debugName(name *ir.Name, pos src.XPos) {
   126  	if base.Flag.LowerM > 1 {
   127  		if name.Linksym() != nil {
   128  			base.WarnfAt(pos, "%s will be kept alive", name.Linksym().Name)
   129  		} else {
   130  			base.WarnfAt(pos, "expr will be kept alive")
   131  		}
   132  	}
   133  }
   134  
   135  // preserveStmt transforms stmt so that any names defined/assigned within it
   136  // are used after stmt's execution, preventing their dead code elimination
   137  // and dead store elimination. The return value is the transformed statement.
   138  func preserveStmt(curFn *ir.Func, stmt ir.Node) (ret ir.Node) {
   139  	ret = stmt
   140  	switch n := stmt.(type) {
   141  	case *ir.AssignStmt:
   142  		// Peel down struct and slice indexing to get the names
   143  		name := getAddressableNameFromNode(n.X)
   144  		if name != nil {
   145  			debugName(name, n.Pos())
   146  			ret = keepAliveAt([]ir.Node{name}, n)
   147  		} else if deref := n.X.(*ir.StarExpr); deref != nil {
   148  			ret = keepAliveAt([]ir.Node{deref}, n)
   149  			if base.Flag.LowerM > 1 {
   150  				base.WarnfAt(n.Pos(), "dereference will be kept alive")
   151  			}
   152  		} else if base.Flag.LowerM > 1 {
   153  			base.WarnfAt(n.Pos(), "expr is unknown to bloop pass")
   154  		}
   155  	case *ir.AssignListStmt:
   156  		ns := []ir.Node{}
   157  		for _, lhs := range n.Lhs {
   158  			name := getAddressableNameFromNode(lhs)
   159  			if name != nil {
   160  				debugName(name, n.Pos())
   161  				ns = append(ns, name)
   162  			} else if deref := lhs.(*ir.StarExpr); deref != nil {
   163  				ns = append(ns, deref)
   164  				if base.Flag.LowerM > 1 {
   165  					base.WarnfAt(n.Pos(), "dereference will be kept alive")
   166  				}
   167  			} else if base.Flag.LowerM > 1 {
   168  				base.WarnfAt(n.Pos(), "expr is unknown to bloop pass")
   169  			}
   170  		}
   171  		ret = keepAliveAt(ns, n)
   172  	case *ir.AssignOpStmt:
   173  		name := getAddressableNameFromNode(n.X)
   174  		if name != nil {
   175  			debugName(name, n.Pos())
   176  			ret = keepAliveAt([]ir.Node{name}, n)
   177  		} else if deref := n.X.(*ir.StarExpr); deref != nil {
   178  			ret = keepAliveAt([]ir.Node{deref}, n)
   179  			if base.Flag.LowerM > 1 {
   180  				base.WarnfAt(n.Pos(), "dereference will be kept alive")
   181  			}
   182  		} else if base.Flag.LowerM > 1 {
   183  			base.WarnfAt(n.Pos(), "expr is unknown to bloop pass")
   184  		}
   185  	case *ir.CallExpr:
   186  		curNode := stmt
   187  		if n.Fun != nil && n.Fun.Type() != nil && n.Fun.Type().NumResults() != 0 {
   188  			ns := []ir.Node{}
   189  			// This function's results are not assigned, assign them to
   190  			// auto tmps and then keepAliveAt these autos.
   191  			// Note: markStmt assumes the context that it's called - this CallExpr is
   192  			// not within another OAS2, which is guaranteed by the case above.
   193  			results := n.Fun.Type().Results()
   194  			lhs := make([]ir.Node, len(results))
   195  			for i, res := range results {
   196  				tmp := typecheck.TempAt(n.Pos(), curFn, res.Type)
   197  				lhs[i] = tmp
   198  				ns = append(ns, tmp)
   199  			}
   200  
   201  			// Create an assignment statement.
   202  			assign := typecheck.AssignExpr(
   203  				ir.NewAssignListStmt(n.Pos(), ir.OAS2, lhs,
   204  					[]ir.Node{n})).(*ir.AssignListStmt)
   205  			assign.Def = true
   206  			curNode = assign
   207  			plural := ""
   208  			if len(results) > 1 {
   209  				plural = "s"
   210  			}
   211  			if base.Flag.LowerM > 1 {
   212  				base.WarnfAt(n.Pos(), "function result%s will be kept alive", plural)
   213  			}
   214  			ret = keepAliveAt(ns, curNode)
   215  		} else {
   216  			// This function probably doesn't return anything, keep its args alive.
   217  			argTmps := []ir.Node{}
   218  			names := []ir.Node{}
   219  			for i, a := range n.Args {
   220  				if name := getAddressableNameFromNode(a); name != nil {
   221  					// If they are name, keep them alive directly.
   222  					debugName(name, n.Pos())
   223  					names = append(names, name)
   224  				} else if a.Op() == ir.OSLICELIT {
   225  					// variadic args are encoded as slice literal.
   226  					s := a.(*ir.CompLitExpr)
   227  					ns := []ir.Node{}
   228  					for i, elem := range s.List {
   229  						if name := getAddressableNameFromNode(elem); name != nil {
   230  							debugName(name, n.Pos())
   231  							ns = append(ns, name)
   232  						} else {
   233  							// We need a temporary to save this arg.
   234  							tmp := typecheck.TempAt(elem.Pos(), curFn, elem.Type())
   235  							argTmps = append(argTmps, typecheck.AssignExpr(ir.NewAssignStmt(elem.Pos(), tmp, elem)))
   236  							names = append(names, tmp)
   237  							s.List[i] = tmp
   238  							if base.Flag.LowerM > 1 {
   239  								base.WarnfAt(n.Pos(), "function arg will be kept alive")
   240  							}
   241  						}
   242  					}
   243  					names = append(names, ns...)
   244  				} else {
   245  					// expressions, we need to assign them to temps and change the original arg to reference
   246  					// them.
   247  					tmp := typecheck.TempAt(n.Pos(), curFn, a.Type())
   248  					argTmps = append(argTmps, typecheck.AssignExpr(ir.NewAssignStmt(n.Pos(), tmp, a)))
   249  					names = append(names, tmp)
   250  					n.Args[i] = tmp
   251  					if base.Flag.LowerM > 1 {
   252  						base.WarnfAt(n.Pos(), "function arg will be kept alive")
   253  					}
   254  				}
   255  			}
   256  			if len(argTmps) > 0 {
   257  				argTmps = append(argTmps, n)
   258  				curNode = ir.NewBlockStmt(n.Pos(), argTmps)
   259  			}
   260  			ret = keepAliveAt(names, curNode)
   261  		}
   262  	}
   263  	return
   264  }
   265  
   266  func preserveStmts(curFn *ir.Func, list ir.Nodes) {
   267  	for i := range list {
   268  		list[i] = preserveStmt(curFn, list[i])
   269  	}
   270  }
   271  
   272  // isTestingBLoop returns true if it matches the node as a
   273  // testing.(*B).Loop. See issue #61515.
   274  func isTestingBLoop(t ir.Node) bool {
   275  	if t.Op() != ir.OFOR {
   276  		return false
   277  	}
   278  	nFor, ok := t.(*ir.ForStmt)
   279  	if !ok || nFor.Cond == nil || nFor.Cond.Op() != ir.OCALLFUNC {
   280  		return false
   281  	}
   282  	n, ok := nFor.Cond.(*ir.CallExpr)
   283  	if !ok || n.Fun == nil || n.Fun.Op() != ir.OMETHEXPR {
   284  		return false
   285  	}
   286  	name := ir.MethodExprName(n.Fun)
   287  	if name == nil {
   288  		return false
   289  	}
   290  	if fSym := name.Sym(); fSym != nil && name.Class == ir.PFUNC && fSym.Pkg != nil &&
   291  		fSym.Name == "(*B).Loop" && fSym.Pkg.Path == "testing" {
   292  		// Attempting to match a function call to testing.(*B).Loop
   293  		return true
   294  	}
   295  	return false
   296  }
   297  
   298  type editor struct {
   299  	inBloop bool
   300  	curFn   *ir.Func
   301  }
   302  
   303  func (e editor) edit(n ir.Node) ir.Node {
   304  	e.inBloop = isTestingBLoop(n) || e.inBloop
   305  	// It's in bloop, mark the stmts with bodies.
   306  	ir.EditChildren(n, e.edit)
   307  	if e.inBloop {
   308  		switch n := n.(type) {
   309  		case *ir.ForStmt:
   310  			preserveStmts(e.curFn, n.Body)
   311  		case *ir.IfStmt:
   312  			preserveStmts(e.curFn, n.Body)
   313  			preserveStmts(e.curFn, n.Else)
   314  		case *ir.BlockStmt:
   315  			preserveStmts(e.curFn, n.List)
   316  		case *ir.CaseClause:
   317  			preserveStmts(e.curFn, n.List)
   318  			preserveStmts(e.curFn, n.Body)
   319  		case *ir.CommClause:
   320  			preserveStmts(e.curFn, n.Body)
   321  		case *ir.RangeStmt:
   322  			preserveStmts(e.curFn, n.Body)
   323  		}
   324  	}
   325  	return n
   326  }
   327  
   328  // BloopWalk performs a walk on all functions in the package
   329  // if it imports testing and wrap the results of all qualified
   330  // statements in a runtime.KeepAlive intrinsic call. See package
   331  // doc for more details.
   332  //
   333  //	for b.Loop() {...}
   334  //
   335  // loop's body.
   336  func BloopWalk(pkg *ir.Package) {
   337  	hasTesting := false
   338  	for _, i := range pkg.Imports {
   339  		if i.Path == "testing" {
   340  			hasTesting = true
   341  			break
   342  		}
   343  	}
   344  	if !hasTesting {
   345  		return
   346  	}
   347  	for _, fn := range pkg.Funcs {
   348  		e := editor{false, fn}
   349  		ir.EditChildren(fn, e.edit)
   350  	}
   351  }
   352  

View as plain text