gocc

package module
v0.31.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 29, 2026 License: Apache-2.0 Imports: 21 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

mhr3/gocc
Go Version License

GOCC: Compile C to Go Assembly

This utility transpiles C code to Go assembly. It uses the LLVM toolchain to compile C code to assembly and machine code and generates Go assembly from it, as well as the corresponding Go stubs. This is useful for certain features such as using intrinsics, which are not supported by the Go ecosystem. Generated Go assembly uses Plan 9 mnemonics wherever cmd/asm reassembles them to the same machine code, making the output more suitable for tuning or as a starting point. Instructions cmd/asm cannot express (x87, SETcc/CMOVcc, MOVZX/MOVSX, some legacy SSE names, ...) are emitted as raw bytes with the decoded instruction in a comment; the list is verified against the real assembler by TestAmd64DenylistRoundTrips.

Features

  • Only requires clang and objdump to be installed in order to compile.
  • Auto-detects the appropriate version of clang and objdump to use.
  • Supports cross-compilation.
  • Annotated C functions will have their Go stubs auto-generated.
  • Compiler-emitted helper functions are supported with --with-internal-functions (experimental).
  • Automatically formats go assembly using asmfmt.

Annotating C functions

Only functions with gocc annotation will be compiled into Go functions, note that there's some limitations for parameters - for example when using Go slices, 3 parameters in C have to be used (base pointer, length and capacity). The tool will check whether the C signature is compatible with the go signature.

An example annotation:

// gocc: simd_fn(input string) int64
int64_t simd_fn(char *input1, uint64_t input1_len) {
  ...
}

Slices without their capacity

A slice is three parameters in C. A function that has no use for the capacity can leave it out for the slices it lists in a gocc-omit-cap directive:

// gocc: Dot(a []float32, b []float32) float32
// gocc-omit-cap: a, b
float dot(const float *a, uint64_t a_len, const float *b, uint64_t b_len) {
  ...
}

The listed slices are a pointer and a length in C; the others keep their capacity. Nothing changes for the Go caller: the capacity still has its word in the arguments, the generated code does not load it. This matters where argument registers are short. amd64 has six for integers and pointers, which three slices fill without their capacities and two fill with them.

String and []byte variants of a function

Go code often needs the same routine for strings and for byte slices. A gocc-variant directive adds a second Go signature to a function, without compiling the C code twice:

// gocc: ValidString(data string) bool
// gocc-variant: Valid(data []byte) bool
bool ascii_valid(const unsigned char *data, uint64_t len) {
  ...
}

The signatures of a function may differ only in taking a parameter as a string or as a []byte. Either form can be on the gocc: line, a function can have several variants, and they may mix the two, as in IndexString(haystack string, needle []byte). One of the signatures has to take []byte for every parameter that any of them takes as []byte.

The C function takes a pointer and a length for each string and each slice: a function with variants has no capacity parameters, for any of its slices. For the example above gocc generates (comments omitted):

//go:noescape
func Valid(data []byte) bool

func ValidString(data string) bool {
	return validStringInternal(data, 0)
}

//go:noescape
func validStringInternal(data string, _ int) bool
TEXT ·Valid(SB), NOSPLIT, $0-25
	MOVD data_base+0(FP), R0
	MOVD data_len+8(FP), R1
	...

TEXT ·validStringInternal(SB), NOSPLIT|NOFRAME, $0-25
	JMP ·Valid(SB)

The assembly is declared with the []byte form and loads the pointer and the length; the capacity word of the frame is skipped. The blank int gives a string the size of a slice, so both entry points have the same frame and the string one is a single jump. Calling through it costs one more stored word per string and that jump.

Setting up locally

Building gocc requires Go 1.27 or newer: golang.org/x/arch needs 1.26 for its AVX/AVX-512 decoder, and the set of instructions emitted as Plan 9 text rather than raw bytes was verified against the Go 1.27 assembler. The generated assembly itself has no such requirement.

Before you use gocc, you need to install the LLVM toolchain. On Ubuntu, you can do it with the following commands (LLVM 15 was used the most during development of gocc):

sudo apt install build-essential
bash -c "$(wget -O - https://apt.llvm.org/llvm.sh)"

For cross-compilation you will also need to install the appropriate toolchain. For example, for ARM Linux:

sudo apt install -qy binutils-aarch64-linux-gnu gcc-aarch64-linux-gnu g++-aarch64-linux-gnu

On macOS, you'll need to install Xcode, which includes clang and other build essentials:

xcode-select --install

The example folder includes matrix multiplication using intrinsics compiled for amd64 and arm64, as well as an example that only uses clang's auto-vectorization. See the example/gen.sh script to see how gocc can be invoked.

Compiling on another machine

gocc compiles on the machine it runs on. To have every machine use the compiler of one of them, or to generate code on a machine without clang, run the web server on the machine that has the toolchain:

GOCC_TOKEN=some-secret go run github.com/mhr3/gocc/cmd/webserver@latest --listen :8080

and point gocc at it from the others, with the --server flag or the environment:

export GOCC_SERVER=http://that-machine:8080 GOCC_TOKEN=some-secret
gocc csrc/ascii_neon.c -p ascii -o ./ -a arm64 -O3

The client sends the source together with the files it includes with quotes (#include "x.h"), as far as they exist next to the including file, and writes the generated files as a local run would. All options work the same; --with-os-tag uses the operating system of the client. -l compiles locally even when GOCC_SERVER is set.

The server is for machines and networks you trust. A client picks the compiler options and the source, and with them can make the compiler read and write files as the user running the server. The token keeps strangers out, it does not make the server safe to offer to them. Without --listen it only accepts connections from its own machine, which is enough behind an SSH tunnel (ssh -L 8080:localhost:8080 that-machine). GET /health reports its compiler.

Limitations

This tool does not support most of the C features, it's not a replacement for C/Go. If you are using this for production code, make sure to test the generated code thoroughly. Also, this is not meant to be general-purpose tool, but rather a tool for solving my own problems of speeding up certain routines.

  • Only supports C code that can be compiled by clang.
  • Does not support C++ code or templates for now.
  • Calls to external C libraries are not supported. Internal helper calls (including tail calls) require --with-internal-functions, which is experimental; recursive helpers and helpers reachable from multiple exported functions are rejected, as are helpers that take arguments on the stack (more than 8 integer arguments on arm64, 6 on amd64).
  • No dynamic stack allocation: VLAs and alloca are rejected. Go only keeps the amd64 stack 8-byte aligned; aligned vector moves to and from the stack are rewritten to unaligned ones. A function whose code still depends on the alignment of its frame realigns SP inside it: one with a legacy SSE instruction that takes its operand from the stack, or one that passes the address of a local to code using aligned accesses, such as a helper taking a __m128i *. That makes it SPWRITE for the Go toolchain, so tracebacks, CPU profiles included, end at it. Compile with AVX to avoid the first case. Over-aligned locals are only 16-byte aligned on arm64.
  • No dynamic memory allocation.
  • Currently limited to 6 arguments per function.
  • Function-local static const tables are supported on arm64; on amd64 clang's Intel-syntax assembler cannot re-assemble the dotted fn.table symbol it emits, so use file-scope static const tables instead.

Resources

The ideas of this are built on top of others who have done similar things, such as

Documentation

Overview

Copyright 2022 gorse Project Authors Copyright 2023 Roman Atachiants

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CompileRequest added in v0.31.0

type CompileRequest struct {
	Arch    string   `json:"arch"`
	Package string   `json:"package"`
	Options []string `json:"options,omitempty"`
	// Suffix is added to the names of the generated files, FunctionSuffix to
	// the names of the generated functions.
	Suffix         string `json:"suffix,omitempty"`
	FunctionSuffix string `json:"functionSuffix,omitempty"`
	// OS, when set, is added to the build tags of the generated files. It is
	// the operating system of the client: the server may run another one.
	OS                    string `json:"os,omitempty"`
	WithInternalFunctions bool   `json:"withInternalFunctions,omitempty"`
	// Source names the file to translate among Files.
	Source string `json:"source"`
	// Files holds the source and the files it includes, by their
	// slash-separated path relative to a common directory.
	Files map[string][]byte `json:"files"`
}

CompileRequest is what a Remote sends to a Server: a C source, the files it includes and the options of the translation.

type CompileResult added in v0.31.0

type CompileResult struct {
	Asm File `json:"asm"`
	Go  File `json:"go"`
	// Diagnostics is what the compiler printed while succeeding: its warnings.
	Diagnostics string `json:"diagnostics,omitempty"`
}

CompileResult is the answer of a Server to a CompileRequest.

type File

type File struct {
	Name string `json:"name"`
	Body []byte `json:"body"`
}

File is a generated file, named without a directory.

type Local

type Local struct {
	Arch       *config.Arch
	Clang      *cc.Compiler
	ObjDump    *cc.Disassembler
	Source     string
	FuncSuffix string
	Assembly   string
	Object     string
	GoAssembly string
	GoStub     string
	Package    string
	Options    []string
	// WithInternalFunctions enables the compiler and ABI conventions required
	// for C functions that call compiler-emitted helper functions.
	WithInternalFunctions bool
}

Local translates a C file to Go assembly

func NewLocal

func NewLocal(arch *config.Arch, source, outputDir, suffix, functionSuffix, packageName string, options ...string) (*Local, error)

NewLocal creates a new translator that uses locally installed toolchain

func (*Local) Close

func (t *Local) Close() error

Cleanup cleans up the temporary files

func (*Local) Output

func (t *Local) Output() (*CompileResult, error)

Output returns the generated files, named without their directory.

func (*Local) Translate

func (t *Local) Translate() error

Translate translates the source file to Go assembly

func (*Local) TranslateContext added in v0.31.0

func (t *Local) TranslateContext(ctx context.Context) error

TranslateContext translates the source file to Go assembly. The compiler and the disassembler are killed when ctx ends.

type Remote

type Remote struct {
	// Server is the address of the server, such as http://mac.local:8080.
	Server string
	// Token is the secret the server was started with, if any.
	Token string

	Arch                  string
	Source                string
	Output                string // directory the generated files are written to
	Package               string // name of that directory when empty
	Suffix                string
	FuncSuffix            string
	OS                    string
	Options               []string
	WithInternalFunctions bool

	// Client is used for the request; one with a timeout longer than a
	// compilation should take when nil.
	Client *http.Client
}

Remote translates a C file to Go assembly on another machine, which runs a Server. The machine running the Remote needs no C toolchain.

func (*Remote) Translate

func (t *Remote) Translate() error

Translate has the server translate the source file and writes the generated files to the output directory.

type Server added in v0.31.0

type Server struct {
	// Token, when set, has to be presented by every client.
	Token string
	// Timeout is the time one translation may take. Two minutes when zero.
	Timeout time.Duration
	// MaxRequestBytes limits the size of a request. 32 MiB when zero.
	MaxRequestBytes int64
	// Concurrency is the number of translations running at once; further
	// requests wait. The number of CPUs when zero.
	Concurrency int
	// contains filtered or unexported fields
}

Server translates the C sources that Remote clients send it, with the toolchain of the machine it runs on.

It is meant for machines and networks you trust. A client chooses the compiler options and the source, and so can make the compiler read and write files as the user running the server. Token keeps strangers out; it does not make the server safe to expose to them.

func (*Server) Handler added in v0.31.0

func (s *Server) Handler() http.Handler

Handler returns the HTTP handler of the server: POST /compile takes a CompileRequest and answers with a CompileResult, GET /health describes the toolchain.

Directories

Path Synopsis
cmd
gocc command
webserver command
The webserver translates C sources for gocc clients that have no C toolchain of their own, or that should all use the compiler of one machine.
The webserver translates C sources for gocc clients that have no C toolchain of their own, or that should all use the compiler of one machine.
example
internal
asm
cc

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址