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.
14 "cmd/compile/internal/abi"
15 "cmd/compile/internal/base"
16 "cmd/compile/internal/ir"
17 "cmd/compile/internal/objw"
18 "cmd/compile/internal/typecheck"
19 "cmd/compile/internal/types"
21 "cmd/internal/obj/wasm"
24 // SymABIs records information provided by the assembler about symbol
25 // definition ABIs and reference ABIs.
27 defs map[string]obj.ABI
28 refs map[string]obj.ABISet
31 func NewSymABIs() *SymABIs {
33 defs: make(map[string]obj.ABI),
34 refs: make(map[string]obj.ABISet),
38 // canonicalize returns the canonical name used for a linker symbol in
39 // s's maps. Symbols in this package may be written either as "".X or
40 // with the package's import path already in the symbol. This rewrites
41 // both to use the full path, which matches compiler-generated linker
43 func (s *SymABIs) canonicalize(linksym string) string {
44 if strings.HasPrefix(linksym, `"".`) {
45 panic("non-canonical symbol name: " + linksym)
50 // ReadSymABIs reads a symabis file that specifies definitions and
51 // references of text symbols by ABI.
53 // The symabis format is a set of lines, where each line is a sequence
54 // of whitespace-separated fields. The first field is a verb and is
55 // either "def" for defining a symbol ABI or "ref" for referencing a
56 // symbol using an ABI. For both "def" and "ref", the second field is
57 // the symbol name and the third field is the ABI name, as one of the
58 // named cmd/internal/obj.ABI constants.
59 func (s *SymABIs) ReadSymABIs(file string) {
60 data, err := os.ReadFile(file)
62 log.Fatalf("-symabis: %v", err)
65 for lineNum, line := range strings.Split(string(data), "\n") {
67 line = strings.TrimSpace(line)
68 if line == "" || strings.HasPrefix(line, "#") {
72 parts := strings.Fields(line)
77 log.Fatalf(`%s:%d: invalid symabi: syntax is "%s sym abi"`, file, lineNum, parts[0])
79 sym, abistr := parts[1], parts[2]
80 abi, valid := obj.ParseABI(abistr)
82 log.Fatalf(`%s:%d: invalid symabi: unknown abi "%s"`, file, lineNum, abistr)
85 sym = s.canonicalize(sym)
88 if parts[0] == "def" {
91 s.refs[sym] |= obj.ABISetOf(abi)
94 log.Fatalf(`%s:%d: invalid symabi type "%s"`, file, lineNum, parts[0])
99 // GenABIWrappers applies ABI information to Funcs and generates ABI
100 // wrapper functions where necessary.
101 func (s *SymABIs) GenABIWrappers() {
102 // For cgo exported symbols, we tell the linker to export the
103 // definition ABI to C. That also means that we don't want to
104 // create ABI wrappers even if there's a linkname.
106 // TODO(austin): Maybe we want to create the ABI wrappers, but
107 // ensure the linker exports the right ABI definition under
108 // the unmangled name?
109 cgoExports := make(map[string][]*[]string)
110 for i, prag := range typecheck.Target.CgoPragmas {
112 case "cgo_export_static", "cgo_export_dynamic":
113 symName := s.canonicalize(prag[1])
114 pprag := &typecheck.Target.CgoPragmas[i]
115 cgoExports[symName] = append(cgoExports[symName], pprag)
119 // Apply ABI defs and refs to Funcs and generate wrappers.
121 // This may generate new decls for the wrappers, but we
122 // specifically *don't* want to visit those, lest we create
123 // wrappers for wrappers.
124 for _, fn := range typecheck.Target.Funcs {
131 symName := sym.Linkname
133 symName = sym.Pkg.Prefix + "." + sym.Name
135 symName = s.canonicalize(symName)
137 // Apply definitions.
138 defABI, hasDefABI := s.defs[symName]
140 if len(fn.Body) != 0 {
141 base.ErrorfAt(fn.Pos(), 0, "%v defined in both Go and assembly", fn)
146 if fn.Pragma&ir.CgoUnsafeArgs != 0 {
147 // CgoUnsafeArgs indicates the function (or its callee) uses
148 // offsets to dispatch arguments, which currently using ABI0
149 // frame layout. Pin it to ABI0.
153 // If cgo-exported, add the definition ABI to the cgo
155 cgoExport := cgoExports[symName]
156 for _, pprag := range cgoExport {
157 // The export pragmas have the form:
159 // cgo_export_* <local> [<remote>]
161 // If <remote> is omitted, it's the same as
166 // cgo_export_* <local> <remote> <ABI>
167 if len(*pprag) == 2 {
168 *pprag = append(*pprag, (*pprag)[1])
170 // Add the ABI argument.
171 *pprag = append(*pprag, fn.ABI.String())
175 if abis, ok := s.refs[symName]; ok {
178 // Assume all functions are referenced at least as
179 // ABIInternal, since they may be referenced from
181 fn.ABIRefs.Set(obj.ABIInternal, true)
183 // If a symbol is defined in this package (either in
184 // Go or assembly) and given a linkname, it may be
185 // referenced from another package, so make it
186 // callable via any ABI. It's important that we know
187 // it's defined in this package since other packages
188 // may "pull" symbols using linkname and we don't want
189 // to create duplicate ABI wrappers.
191 // However, if it's given a linkname for exporting to
192 // C, then we don't make ABI wrappers because the cgo
193 // tool wants the original definition.
194 hasBody := len(fn.Body) != 0
195 if sym.Linkname != "" && (hasBody || hasDefABI) && len(cgoExport) == 0 {
196 fn.ABIRefs |= obj.ABISetCallable
199 // Double check that cgo-exported symbols don't get
201 if len(cgoExport) > 0 && fn.ABIRefs&^obj.ABISetOf(fn.ABI) != 0 {
202 base.Fatalf("cgo exported function %v cannot have ABI wrappers", fn)
205 if !buildcfg.Experiment.RegabiWrappers {
209 forEachWrapperABI(fn, makeABIWrapper)
213 func forEachWrapperABI(fn *ir.Func, cb func(fn *ir.Func, wrapperABI obj.ABI)) {
214 need := fn.ABIRefs &^ obj.ABISetOf(fn.ABI)
219 for wrapperABI := obj.ABI(0); wrapperABI < obj.ABICount; wrapperABI++ {
220 if !need.Get(wrapperABI) {
227 // makeABIWrapper creates a new function that will be called with
228 // wrapperABI and calls "f" using f.ABI.
229 func makeABIWrapper(f *ir.Func, wrapperABI obj.ABI) {
230 if base.Debug.ABIWrap != 0 {
231 fmt.Fprintf(os.Stderr, "=-= %v to %v wrapper for %v\n", wrapperABI, f.ABI, f)
234 // Q: is this needed?
236 savedcurfn := ir.CurFunc
238 pos := base.AutogeneratedPos
241 // At the moment we don't support wrapping a method, we'd need machinery
242 // below to handle the receiver. Panic if we see this scenario.
244 if ft.NumRecvs() != 0 {
245 base.ErrorfAt(f.Pos(), 0, "makeABIWrapper support for wrapping methods not implemented")
249 // Reuse f's types.Sym to create a new ODCLFUNC/function.
250 // TODO(mdempsky): Means we can't set sym.Def in Declfunc, ugh.
251 fn := ir.NewFunc(pos, pos, f.Sym(), types.NewSignature(nil,
252 typecheck.NewFuncParams(ft.Params(), true),
253 typecheck.NewFuncParams(ft.Results(), false)))
255 typecheck.DeclFunc(fn)
257 fn.SetABIWrapper(true)
260 // ABI0-to-ABIInternal wrappers will be mainly loading params from
261 // stack into registers (and/or storing stack locations back to
262 // registers after the wrapped call); in most cases they won't
263 // need to allocate stack space, so it should be OK to mark them
264 // as NOSPLIT in these cases. In addition, my assumption is that
265 // functions written in assembly are NOSPLIT in most (but not all)
266 // cases. In the case of an ABIInternal target that has too many
267 // parameters to fit into registers, the wrapper would need to
268 // allocate stack space, but this seems like an unlikely scenario.
269 // Hence: mark these wrappers NOSPLIT.
271 // ABIInternal-to-ABI0 wrappers on the other hand will be taking
272 // things in registers and pushing them onto the stack prior to
273 // the ABI0 call, meaning that they will always need to allocate
274 // stack space. If the compiler marks them as NOSPLIT this seems
275 // as though it could lead to situations where the linker's
276 // nosplit-overflow analysis would trigger a link failure. On the
277 // other hand if they not tagged NOSPLIT then this could cause
278 // problems when building the runtime (since there may be calls to
279 // asm routine in cases where it's not safe to grow the stack). In
280 // most cases the wrapper would be (in effect) inlined, but are
281 // there (perhaps) indirect calls from the runtime that could run
282 // into trouble here.
283 // FIXME: at the moment all.bash does not pass when I leave out
284 // NOSPLIT for these wrappers, so all are currently tagged with NOSPLIT.
285 fn.Pragma |= ir.Nosplit
287 // Generate call. Use tail call if no params and no returns,
288 // but a regular call otherwise.
290 // Note: ideally we would be using a tail call in cases where
291 // there are params but no returns for ABI0->ABIInternal wrappers,
292 // provided that all params fit into registers (e.g. we don't have
293 // to allocate any stack space). Doing this will require some
294 // extra work in typecheck/walk/ssa, might want to add a new node
295 // OTAILCALL or something to this effect.
296 tailcall := fn.Type().NumResults() == 0 && fn.Type().NumParams() == 0 && fn.Type().NumRecvs() == 0
297 if base.Ctxt.Arch.Name == "ppc64le" && base.Ctxt.Flag_dynlink {
298 // cannot tailcall on PPC64 with dynamic linking, as we need
299 // to restore R2 after call.
302 if base.Ctxt.Arch.Name == "amd64" && wrapperABI == obj.ABIInternal {
303 // cannot tailcall from ABIInternal to ABI0 on AMD64, as we need
304 // to special registers (X15) when returning to ABIInternal.
309 call := ir.NewCallExpr(base.Pos, ir.OCALL, f.Nname, nil)
310 call.Args = ir.ParamNames(fn.Type())
311 call.IsDDD = fn.Type().IsVariadic()
314 tail = ir.NewTailCallStmt(base.Pos, call)
315 } else if fn.Type().NumResults() > 0 {
316 n := ir.NewReturnStmt(base.Pos, nil)
317 n.Results = []ir.Node{call}
322 typecheck.FinishFuncBody()
325 typecheck.Stmts(fn.Body)
327 // Restore previous context.
329 ir.CurFunc = savedcurfn
332 // CreateWasmImportWrapper creates a wrapper for imported WASM functions to
333 // adapt them to the Go calling convention. The body for this function is
334 // generated in cmd/internal/obj/wasm/wasmobj.go
335 func CreateWasmImportWrapper(fn *ir.Func) bool {
336 if fn.WasmImport == nil {
339 if buildcfg.GOARCH != "wasm" {
340 base.FatalfAt(fn.Pos(), "CreateWasmImportWrapper call not supported on %s: func was %v", buildcfg.GOARCH, fn)
343 ir.InitLSym(fn, true)
347 pp := objw.NewProgs(fn, 0)
349 pp.Text.To.Type = obj.TYPE_TEXTSIZE
350 pp.Text.To.Val = int32(types.RoundUp(fn.Type().ArgWidth(), int64(types.RegSize)))
351 // Wrapper functions never need their own stack frame
352 pp.Text.To.Offset = 0
358 func paramsToWasmFields(f *ir.Func, result *abi.ABIParamResultInfo, abiParams []abi.ABIParamAssignment) []obj.WasmField {
359 wfs := make([]obj.WasmField, len(abiParams))
360 for i, p := range abiParams {
363 case types.TINT32, types.TUINT32:
364 wfs[i].Type = obj.WasmI32
365 case types.TINT64, types.TUINT64:
366 wfs[i].Type = obj.WasmI64
368 wfs[i].Type = obj.WasmF32
370 wfs[i].Type = obj.WasmF64
371 case types.TUNSAFEPTR:
372 wfs[i].Type = obj.WasmPtr
374 base.ErrorfAt(f.Pos(), 0, "go:wasmimport %s %s: unsupported parameter type %s", f.WasmImport.Module, f.WasmImport.Name, t.String())
376 wfs[i].Offset = p.FrameOffset(result)
381 func resultsToWasmFields(f *ir.Func, result *abi.ABIParamResultInfo, abiParams []abi.ABIParamAssignment) []obj.WasmField {
382 if len(abiParams) > 1 {
383 base.ErrorfAt(f.Pos(), 0, "go:wasmimport %s %s: too many return values", f.WasmImport.Module, f.WasmImport.Name)
386 wfs := make([]obj.WasmField, len(abiParams))
387 for i, p := range abiParams {
390 case types.TINT32, types.TUINT32:
391 wfs[i].Type = obj.WasmI32
392 case types.TINT64, types.TUINT64:
393 wfs[i].Type = obj.WasmI64
395 wfs[i].Type = obj.WasmF32
397 wfs[i].Type = obj.WasmF64
399 base.ErrorfAt(f.Pos(), 0, "go:wasmimport %s %s: unsupported result type %s", f.WasmImport.Module, f.WasmImport.Name, t.String())
401 wfs[i].Offset = p.FrameOffset(result)
406 // setupTextLSym initializes the LSym for a with-body text symbol.
407 func setupWasmABI(f *ir.Func) {
408 wi := obj.WasmImport{
409 Module: f.WasmImport.Module,
410 Name: f.WasmImport.Name,
412 if wi.Module == wasm.GojsModule {
413 // Functions that are imported from the "gojs" module use a special
414 // ABI that just accepts the stack pointer.
417 // //go:wasmimport gojs add
418 // func importedAdd(a, b uint) uint
420 // will roughly become
422 // (import "gojs" "add" (func (param i32)))
423 wi.Params = []obj.WasmField{{Type: obj.WasmI32}}
425 // All other imported functions use the normal WASM ABI.
428 // //go:wasmimport a_module add
429 // func importedAdd(a, b uint) uint
431 // will roughly become
433 // (import "a_module" "add" (func (param i32 i32) (result i32)))
434 abiConfig := AbiForBodylessFuncStackMap(f)
435 abiInfo := abiConfig.ABIAnalyzeFuncType(f.Type())
436 wi.Params = paramsToWasmFields(f, abiInfo, abiInfo.InParams())
437 wi.Results = resultsToWasmFields(f, abiInfo, abiInfo.OutParams())
439 f.LSym.Func().WasmImport = &wi