Source file src/cmd/compile/internal/walk/closure.go

     1  // Copyright 2009 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 walk
     6  
     7  import (
     8  	"cmd/compile/internal/base"
     9  	"cmd/compile/internal/ir"
    10  	"cmd/compile/internal/typecheck"
    11  	"cmd/compile/internal/types"
    12  	"cmd/internal/src"
    13  )
    14  
    15  // directClosureCall rewrites a direct call of a function literal into
    16  // a normal function call with closure variables passed as arguments.
    17  // This avoids allocation of a closure object.
    18  //
    19  // For illustration, the following call:
    20  //
    21  //	func(a int) {
    22  //		println(byval)
    23  //		byref++
    24  //	}(42)
    25  //
    26  // becomes:
    27  //
    28  //	func(byval int, &byref *int, a int) {
    29  //		println(byval)
    30  //		(*&byref)++
    31  //	}(byval, &byref, 42)
    32  func directClosureCall(n *ir.CallExpr) {
    33  	clo := n.Fun.(*ir.ClosureExpr)
    34  	clofn := clo.Func
    35  
    36  	if !clofn.IsClosure() {
    37  		return // leave for walkClosure to handle
    38  	}
    39  
    40  	// We are going to insert captured variables before input args.
    41  	var params []*types.Field
    42  	var decls []*ir.Name
    43  	for _, v := range clofn.ClosureVars {
    44  		if !v.Byval() {
    45  			// If v of type T is captured by reference,
    46  			// we introduce function param &v *T
    47  			// and v remains PAUTOHEAP with &v heapaddr
    48  			// (accesses will implicitly deref &v).
    49  
    50  			addr := ir.NewNameAt(clofn.Pos(), typecheck.Lookup("&"+v.Sym().Name), types.NewPtr(v.Type()))
    51  			addr.Curfn = clofn
    52  			v.Heapaddr = addr
    53  			v = addr
    54  		}
    55  
    56  		v.Class = ir.PPARAM
    57  		decls = append(decls, v)
    58  
    59  		fld := types.NewField(src.NoXPos, v.Sym(), v.Type())
    60  		fld.Nname = v
    61  		params = append(params, fld)
    62  	}
    63  
    64  	// f is ONAME of the actual function.
    65  	f := clofn.Nname
    66  	typ := f.Type()
    67  
    68  	// Create new function type with parameters prepended, and
    69  	// then update type and declarations.
    70  	typ = types.NewSignature(nil, append(params, typ.Params()...), typ.Results())
    71  	f.SetType(typ)
    72  	clofn.Dcl = append(decls, clofn.Dcl...)
    73  
    74  	// Rewrite call.
    75  	n.Fun = f
    76  	n.Args.Prepend(closureArgs(clo)...)
    77  
    78  	// Update the call expression's type. We need to do this
    79  	// because typecheck gave it the result type of the OCLOSURE
    80  	// node, but we only rewrote the ONAME node's type. Logically,
    81  	// they're the same, but the stack offsets probably changed.
    82  	if typ.NumResults() == 1 {
    83  		n.SetType(typ.Result(0).Type)
    84  	} else {
    85  		n.SetType(typ.ResultsTuple())
    86  	}
    87  
    88  	// Add to Closures for enqueueFunc. It's no longer a proper
    89  	// closure, but we may have already skipped over it in the
    90  	// functions list, so this just ensures it's compiled.
    91  	ir.CurFunc.Closures = append(ir.CurFunc.Closures, clofn)
    92  }
    93  
    94  func walkClosure(clo *ir.ClosureExpr, init *ir.Nodes) ir.Node {
    95  	clofn := clo.Func
    96  
    97  	// If not a closure, don't bother wrapping.
    98  	if !clofn.IsClosure() {
    99  		if base.Debug.Closure > 0 {
   100  			base.WarnfAt(clo.Pos(), "closure converted to global")
   101  		}
   102  		return clofn.Nname
   103  	}
   104  
   105  	// The closure is not trivial or directly called, so it's going to stay a closure.
   106  	ir.ClosureDebugRuntimeCheck(clo)
   107  	clofn.SetNeedctxt(true)
   108  
   109  	// The closure expression may be walked more than once if it appeared in composite
   110  	// literal initialization (e.g, see issue #49029).
   111  	//
   112  	// Don't add the closure function to compilation queue more than once, since when
   113  	// compiling a function twice would lead to an ICE.
   114  	if !clofn.Walked() {
   115  		clofn.SetWalked(true)
   116  		ir.CurFunc.Closures = append(ir.CurFunc.Closures, clofn)
   117  	}
   118  
   119  	typ := typecheck.ClosureType(clo)
   120  
   121  	clos := ir.NewCompLitExpr(base.Pos, ir.OCOMPLIT, typ, nil)
   122  	clos.SetEsc(clo.Esc())
   123  	clos.List = append([]ir.Node{ir.NewUnaryExpr(base.Pos, ir.OCFUNC, clofn.Nname)}, closureArgs(clo)...)
   124  	for i, value := range clos.List {
   125  		clos.List[i] = ir.NewStructKeyExpr(base.Pos, typ.Field(i), value)
   126  	}
   127  
   128  	addr := typecheck.NodAddr(clos)
   129  	addr.SetEsc(clo.Esc())
   130  
   131  	// Force type conversion from *struct to the func type.
   132  	cfn := typecheck.ConvNop(addr, clo.Type())
   133  
   134  	// non-escaping temp to use, if any.
   135  	if x := clo.Prealloc; x != nil {
   136  		if !types.Identical(typ, x.Type()) {
   137  			panic("closure type does not match order's assigned type")
   138  		}
   139  		addr.Prealloc = x
   140  		clo.Prealloc = nil
   141  	}
   142  
   143  	return walkExpr(cfn, init)
   144  }
   145  
   146  // closureArgs returns a slice of expressions that can be used to
   147  // initialize the given closure's free variables. These correspond
   148  // one-to-one with the variables in clo.Func.ClosureVars, and will be
   149  // either an ONAME node (if the variable is captured by value) or an
   150  // OADDR-of-ONAME node (if not).
   151  func closureArgs(clo *ir.ClosureExpr) []ir.Node {
   152  	fn := clo.Func
   153  
   154  	args := make([]ir.Node, len(fn.ClosureVars))
   155  	for i, v := range fn.ClosureVars {
   156  		var outer ir.Node
   157  		outer = v.Outer
   158  		if !v.Byval() {
   159  			outer = typecheck.NodAddrAt(fn.Pos(), outer)
   160  		}
   161  		args[i] = typecheck.Expr(outer)
   162  	}
   163  	return args
   164  }
   165  
   166  func walkMethodValue(n *ir.SelectorExpr, init *ir.Nodes) ir.Node {
   167  	// Create closure in the form of a composite literal.
   168  	// For x.M with receiver (x) type T, the generated code looks like:
   169  	//
   170  	//	clos = &struct{F uintptr; R T}{T.M·f, x}
   171  	//
   172  	// Like walkClosure above.
   173  
   174  	if n.X.Type().IsInterface() {
   175  		// Trigger panic for method on nil interface now.
   176  		// Otherwise it happens in the wrapper and is confusing.
   177  		n.X = cheapExpr(n.X, init)
   178  		n.X = walkExpr(n.X, nil)
   179  
   180  		tab := ir.NewUnaryExpr(base.Pos, ir.OITAB, n.X)
   181  		check := ir.NewUnaryExpr(base.Pos, ir.OCHECKNIL, tab)
   182  		init.Append(typecheck.Stmt(check))
   183  	}
   184  
   185  	typ := typecheck.MethodValueType(n)
   186  
   187  	clos := ir.NewCompLitExpr(base.Pos, ir.OCOMPLIT, typ, nil)
   188  	clos.SetEsc(n.Esc())
   189  	clos.List = []ir.Node{ir.NewUnaryExpr(base.Pos, ir.OCFUNC, methodValueWrapper(n)), n.X}
   190  
   191  	addr := typecheck.NodAddr(clos)
   192  	addr.SetEsc(n.Esc())
   193  
   194  	// Force type conversion from *struct to the func type.
   195  	cfn := typecheck.ConvNop(addr, n.Type())
   196  
   197  	// non-escaping temp to use, if any.
   198  	if x := n.Prealloc; x != nil {
   199  		if !types.Identical(typ, x.Type()) {
   200  			panic("partial call type does not match order's assigned type")
   201  		}
   202  		addr.Prealloc = x
   203  		n.Prealloc = nil
   204  	}
   205  
   206  	return walkExpr(cfn, init)
   207  }
   208  
   209  // methodValueWrapper returns the ONAME node representing the
   210  // wrapper function (*-fm) needed for the given method value. If the
   211  // wrapper function hasn't already been created yet, it's created and
   212  // added to typecheck.Target.Decls.
   213  func methodValueWrapper(dot *ir.SelectorExpr) *ir.Name {
   214  	if dot.Op() != ir.OMETHVALUE {
   215  		base.Fatalf("methodValueWrapper: unexpected %v (%v)", dot, dot.Op())
   216  	}
   217  
   218  	meth := dot.Sel
   219  	rcvrtype := dot.X.Type()
   220  	sym := ir.MethodSymSuffix(rcvrtype, meth, "-fm")
   221  
   222  	if sym.Uniq() {
   223  		return sym.Def.(*ir.Name)
   224  	}
   225  	sym.SetUniq(true)
   226  
   227  	base.FatalfAt(dot.Pos(), "missing wrapper for %v", meth)
   228  	panic("unreachable")
   229  }
   230  

View as plain text