Debian Codegraph @

go/ir/wrappers.go

raw
1 // Copyright 2013 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 ir
6
7 // This file defines synthesis of Functions that delegate to declared
8 // methods; they come in three kinds:
9 //
10 // (1) wrappers: methods that wrap declared methods, performing
11 // implicit pointer indirections and embedded field selections.
12 //
13 // (2) thunks: funcs that wrap declared methods. Like wrappers,
14 // thunks perform indirections and field selections. The thunk's
15 // first parameter is used as the receiver for the method call.
16 //
17 // (3) bounds: funcs that wrap declared methods. The bound's sole
18 // free variable, supplied by a closure, is used as the receiver
19 // for the method call. No indirections or field selections are
20 // performed since they can be done before the call.
21
22 import (
23 "fmt"
24 "go/types"
25 )
26
27 // -- wrappers -----------------------------------------------------------
28
29 // createWrapper returns a synthetic method that delegates to the
30 // declared method denoted by meth.Obj(), first performing any
31 // necessary pointer indirections or field selections implied by meth.
32 //
33 // The resulting method's receiver type is meth.Recv().
34 //
35 // This function is versatile but quite subtle! Consider the
36 // following axes of variation when making changes:
37 // - optional receiver indirection
38 // - optional implicit field selections
39 // - optional method type arguments
40 // - meth.Obj() may denote a concrete or an interface method
41 // - the result may be a thunk or a wrapper.
42 func createWrapper(prog *Program, sel *selection, targs []types.Type) *Function {
43 obj := sel.obj.(*types.Func) // the declared function
44 name, sig := maybeInstance(prog, obj.Name(), sel.typ.(*types.Signature), targs)
45
46 var recv *types.Var // wrapper's receiver or thunk's params[0]
47 var description string
48 if sel.kind == types.MethodExpr {
49 name += "$thunk"
50 description = "thunk"
51 recv = sig.Params().At(0)
52 } else {
53 description = "wrapper"
54 recv = sig.Recv()
55 }
56
57 description = fmt.Sprintf("%s for %s", description, obj)
58 if prog.mode&LogSource != 0 {
59 defer logStack("create %s to (%s)", description, recv.Type())()
60 }
61 /* method wrapper */
62 return &Function{
63 name: name,
64 method: sel,
65 object: obj,
66 Signature: sig,
67 Synthetic: description,
68 Prog: prog,
69 pos: obj.Pos(),
70 typeargs: targs,
71 // wrappers have no syntax
72 build: (*builder).buildWrapper,
73 info: nil,
74 goversion: "",
75 }
76 }
77
78 // maybeInstance returns name and sig instantiated to reflect any type arguments in targs.
79 func maybeInstance(prog *Program, name string, sig *types.Signature, targs []types.Type) (string, *types.Signature) {
80 if len(targs) > 0 {
81 name = fmt.Sprintf("%s%s", name, targstr(targs))
82 instSig, err := types.Instantiate(prog.ctxt, sig, targs, false)
83 if err != nil {
84 // validate was false, we should never get an error
85 panic(err)
86 }
87 sig = prog.canon.Type(instSig).(*types.Signature)
88 }
89 return name, sig
90 }
91
92 // buildWrapper builds fn.Body for a method wrapper.
93 func (b *builder) buildWrapper(fn *Function) {
94 var recv *types.Var // wrapper's receiver or thunk's params[0]
95 var start int // first regular param
96 if fn.method.kind == types.MethodExpr {
97 recv = fn.Signature.Params().At(0)
98 start = 1
99 } else {
100 recv = fn.Signature.Recv()
101 }
102
103 fn.startBody()
104 fn.addSpilledParam(recv, nil)
105 createParams(fn, start)
106
107 indices := fn.method.index
108
109 var v Value = fn.Locals[0] // spilled receiver
110 if isPointer(fn.method.recv) {
111 v = emitLoad(fn, v, nil)
112
113 // For simple indirection wrappers, perform an informative nil-check:
114 // "value method (T).f called using nil *T pointer"
115 if len(indices) == 1 && !isPointer(recvType(fn.object)) {
116 var c Call
117 c.Call.Value = &Builtin{
118 name: "ssa:wrapnilchk",
119 sig: types.NewSignatureType(nil, nil, nil, types.NewTuple(anonVar(fn.method.recv), anonVar(tString), anonVar(tString)), types.NewTuple(anonVar(fn.method.recv)), false),
120 }
121 c.Call.Args = []Value{
122 v,
123 stringConst(deref(fn.method.recv).String(), nil),
124 stringConst(fn.method.obj.Name(), nil),
125 }
126 c.setType(v.Type())
127 v = fn.emit(&c, nil)
128 }
129 }
130
131 // Invariant: v is a pointer, either
132 // value of *A receiver param, or
133 // address of A spilled receiver.
134
135 // We use pointer arithmetic (FieldAddr possibly followed by
136 // Load) in preference to value extraction (Field possibly
137 // preceded by Load).
138
139 v = emitImplicitSelections(fn, v, indices[:len(indices)-1], nil)
140
141 // Invariant: v is a pointer, either
142 // value of implicit *C field, or
143 // address of implicit C field.
144
145 var c Call
146 if r := recvType(fn.object); !types.IsInterface(r) { // concrete method
147 if !isPointer(r) {
148 v = emitLoad(fn, v, nil)
149 }
150 c.Call.Value = fn.Prog.objectMethod(fn.object, fn.typeargs, b)
151 c.Call.Args = append(c.Call.Args, v)
152 } else {
153 c.Call.Method = fn.object
154 c.Call.Value = emitLoad(fn, v, nil) // interface (possibly a typeparam)
155 }
156 for _, arg := range fn.Params[1:] {
157 c.Call.Args = append(c.Call.Args, arg)
158 }
159 emitTailCall(fn, &c, nil)
160 fn.finishBody()
161 }
162
163 // createParams creates parameters for wrapper method fn based on its
164 // Signature.Params, which do not include the receiver.
165 // start is the index of the first regular parameter to use.
166 func createParams(fn *Function, start int) {
167 tparams := fn.Signature.Params()
168 for i, n := start, tparams.Len(); i < n; i++ {
169 fn.addParamVar(tparams.At(i), nil)
170 }
171 }
172
173 // -- bounds -----------------------------------------------------------
174
175 // createBound returns a bound method wrapper (or "bound"), a synthetic
176 // function that delegates to a concrete or interface method denoted
177 // by obj. The resulting function has no receiver, but has one free
178 // variable which will be used as the method's receiver in the
179 // tail-call.
180 //
181 // Use MakeClosure with such a wrapper to construct a bound method
182 // closure. e.g.:
183 //
184 // type T int or: type T interface { meth() }
185 // func (t T) meth()
186 // var t T
187 // f := t.meth
188 // f() // calls t.meth()
189 //
190 // f is a closure of a synthetic wrapper defined as if by:
191 //
192 // f := func() { return t.meth() }
193 //
194 // Unlike createWrapper, createBound need perform no indirection or field
195 // selections because that can be done before the closure is
196 // constructed.
197 func createBound(prog *Program, obj *types.Func, targs []types.Type) *Function {
198 description := fmt.Sprintf("bound method wrapper for %s", obj)
199 if prog.mode&LogSource != 0 {
200 defer logStack("%s", description)()
201 }
202 name, sig := maybeInstance(prog, obj.Name(), obj.Type().(*types.Signature), targs)
203
204 /* bound method wrapper */
205 fn := &Function{
206 name: name + "$bound",
207 object: obj,
208 Signature: changeRecv(sig, nil), // drop receiver
209 Synthetic: description,
210 Prog: prog,
211 pos: obj.Pos(),
212 typeargs: targs,
213 // wrappers have no syntax
214 build: (*builder).buildBound,
215 info: nil,
216 goversion: "",
217 }
218 fn.FreeVars = []*FreeVar{{name: "recv", typ: recvType(obj), parent: fn}} // (cyclic)
219 return fn
220 }
221
222 // buildBound builds fn.Body for a bound method closure.
223 func (b *builder) buildBound(fn *Function) {
224 fn.startBody()
225 createParams(fn, 0)
226 var c Call
227
228 recv := fn.FreeVars[0]
229 if !types.IsInterface(recvType(fn.object)) { // concrete
230 c.Call.Value = fn.Prog.objectMethod(fn.object, fn.typeargs, b)
231 c.Call.Args = []Value{recv}
232 } else {
233 c.Call.Method = fn.object
234 c.Call.Value = recv // interface (possibly a typeparam)
235 }
236 for _, arg := range fn.Params {
237 c.Call.Args = append(c.Call.Args, arg)
238 }
239 emitTailCall(fn, &c, nil)
240 fn.finishBody()
241 }
242
243 // -- thunks -----------------------------------------------------------
244
245 // createThunk returns a thunk, a synthetic function that delegates to a
246 // concrete or interface method denoted by sel.obj. The resulting
247 // function has no receiver, but has an additional (first) regular
248 // parameter.
249 //
250 // Precondition: sel.kind == types.MethodExpr.
251 //
252 // type T int or: type T interface { meth() }
253 // func (t T) meth()
254 // f := T.meth
255 // var t T
256 // f(t) // calls t.meth()
257 //
258 // f is a synthetic wrapper defined as if by:
259 //
260 // f := func(t T) { return t.meth() }
261 func createThunk(prog *Program, sel *selection, targs []types.Type) *Function {
262 if sel.kind != types.MethodExpr {
263 panic(sel)
264 }
265
266 fn := createWrapper(prog, sel, targs)
267 if fn.Signature.Recv() != nil {
268 panic(fn) // unexpected receiver
269 }
270 return fn
271 }
272
273 func changeRecv(s *types.Signature, recv *types.Var) *types.Signature {
274 return types.NewSignatureType(recv, nil, nil, s.Params(), s.Results(), s.Variadic())
275 }
276
277 // A local version of *types.Selection.
278 // Needed for some additional control, such as creating a MethodExpr for an instantiation.
279 type selection struct {
280 kind types.SelectionKind
281 recv types.Type
282 typ types.Type
283 obj types.Object
284 index []int
285 indirect bool
286 }
287
288 func toSelection(sel *types.Selection) *selection {
289 return &selection{
290 kind: sel.Kind(),
291 recv: sel.Recv(),
292 typ: sel.Type(),
293 obj: sel.Obj(),
294 index: sel.Index(),
295 indirect: sel.Indirect(),
296 }
297 }
298
299 // -- instantiations --------------------------------------------------
300
301 // buildInstantiationWrapper builds the body of an instantiation
302 // wrapper fn. The body calls the original generic function,
303 // bracketed by ChangeType conversions on its arguments and results.
304 func (b *builder) buildInstantiationWrapper(fn *Function) {
305 orig := fn.topLevelOrigin
306 sig := fn.Signature
307
308 fn.startBody()
309 if sig.Recv() != nil {
310 fn.addParamVar(sig.Recv(), nil)
311 }
312 createParams(fn, 0)
313
314 // Create body. Add a call to origin generic function
315 // and make type changes between argument and parameters,
316 // as well as return values.
317 var c Call
318 c.Call.Value = orig
319 if res := orig.Signature.Results(); res.Len() == 1 {
320 c.typ = res.At(0).Type()
321 } else {
322 c.typ = res
323 }
324
325 // parameter of instance becomes an argument to the call
326 // to the original generic function.
327 argOffset := 0
328 for i, arg := range fn.Params {
329 var typ types.Type
330 if i == 0 && sig.Recv() != nil {
331 typ = orig.Signature.Recv().Type()
332 argOffset = 1
333 } else {
334 typ = orig.Signature.Params().At(i - argOffset).Type()
335 }
336 c.Call.Args = append(c.Call.Args, emitTypeCoercion(fn, arg, typ, nil))
337 }
338
339 results := fn.emit(&c, nil)
340 var ret Return
341 switch res := sig.Results(); res.Len() {
342 case 0:
343 // no results, do nothing.
344 case 1:
345 ret.Results = []Value{emitTypeCoercion(fn, results, res.At(0).Type(), nil)}
346 default:
347 for i := 0; i < sig.Results().Len(); i++ {
348 v := emitExtract(fn, results, i, nil)
349 ret.Results = append(ret.Results, emitTypeCoercion(fn, v, res.At(i).Type(), nil))
350 }
351 }
352
353 fn.emit(&ret, nil)
354 fn.currentBlock = nil
355
356 fn.finishBody()
357 }