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