Implement a new TinyCC backend that targets freestanding wasm32 for numeric kernels (for example ../miniexpr), with no WASI dependency and no host OS runtime requirements.
Target profile name in this document:
wasm32-freestanding(equivalent towasm32-unknown-unknown)
Primary outcome:
- Compile C kernel code to a
.wasmmodule exporting selected functions. - Support enough C to compile math-heavy kernels reliably.
- Keep scope constrained to reduce implementation risk.
wasm32pointers (PTR_SIZE=4,LONG_SIZE=4).- C functions with primitive args and returns:
int,unsigned int,long(32-bit),long long/unsigned long long(64-bit),float,double,- pointers.
- Local variables, stack frames, scalar loads/stores.
- Arithmetic and comparisons on integer and floating types.
- Branching:
if/elsewhile,for,doswitch(initially via lowering strategy described below).
- Direct function calls between compiled functions.
- Static/global data (
.data,.bss, rodata) mapped to linear memory. - Emission of valid wasm module sections:
- Type, Function, Memory, Global, Export, Code, Data
- optional Name section for debug.
- WASI and OS integration.
-run, JIT relocation/execution.- Inline/global asm support.
- Variadic functions (
...,va_start,va_arg). - Dynamic linking, ELF shared objects, PLT/GOT logic for wasm.
- Full C ABI compatibility for complex struct passing/return.
- Function pointer calls (
call_indirect) in phase 1. - Threading and full atomics memory model support.
- Debug info parity (DWARF/stabs in wasm).
Use native wasm function signatures for direct calls:
- C integral/fp scalars map directly to wasm params/results.
- Pointer types are
i32.
Struct returns/passing (MVP):
- force memory-based behavior:
- return structs through hidden sret pointer (no multi-register struct return).
- pass large structs by pointer when needed.
Use linear-memory stack with mutable global stack pointer:
- global
__stack_pointer: i32 - function prolog:
- decrement SP by frame size (+ alignment)
- keep frame base in a wasm local
- epilog:
- restore SP
Rationale:
- matches TinyCC expectations for addressable locals and pointer arithmetic.
- avoids trying to map C stack objects directly to wasm locals.
Single wasm memory (minimum 1 page), exported as memory.
- Data segments initialize
.data/rodata. .bssallocated in linear memory as zero-initialized region.- stack region starts above static data high-water mark.
wasm-gen.c- implements target codegen hooks declared in
tcc.h:load,storegfunc_call,gfunc_prolog,gfunc_epiloggen_opi,gen_opf, conversions- jumps and label patch interfaces
- VLA helpers (initially reject or minimally support)
- implements target codegen hooks declared in
wasm-link.c- defines target constants needed by
TARGET_DEFS_ONLYinclude model. - stubs/minimal relocation policy for wasm path.
- defines target constants needed by
tccwasm.c- module writer: takes compiled sections/symbols and emits wasm binary.
TinyCC internally generates unstructured labels/jumps. Wasm requires structured control flow.
Plan:
- Emit a temporary backend IR from
wasm-gen.c:- basic blocks
- pseudo instructions
- explicit branch edges.
- Build CFG per function.
- Lower CFG to structured wasm using a deterministic algorithm:
- phase 1: reducible CFG support (
if, loops, switch lowering). - explicit fallback error for unsupported irreducible patterns.
- phase 1: reducible CFG support (
- Serialize final wasm instructions from structured form.
This avoids fragile direct mapping from TinyCC jump patch lists to wasm branch depths.
TinyCC expects NB_REGS/register classes. wasm has no hardware registers.
Plan:
- Define a virtual register bank in
wasm-gen.c. - Map TinyCC “registers” to wasm locals (
local.get/set/tee). - Preserve TinyCC register-class semantics (
RC_INT,RC_FLOAT) minimally. - Keep load/store semantics consistent with addressable memory model.
configure- accept
--cpu=wasm32(and aliases). - emit
CONFIG_wasm32andTCC_TARGET_WASM32.
- accept
Makefile- add
DEF-wasm32 = -DTCC_TARGET_WASM32. - add
wasm32_FILESlist including new backend/writer files. - add cross target entry (
TCC_X += wasm32) if desired.
- add
lib/Makefile- add
OBJ-wasm32for optional support libs (phase 2+).
- add
tcc.h- add
TCC_TARGET_WASM32in target macro list/default detection. - include
wasm-gen.c/wasm-link.cunderTARGET_DEFS_ONLY. - add wasm-specific prototypes (if needed).
- add
libtcc.c- include new source files in
ONE_SOURCEdispatch.
- include new source files in
tcc.c- add version string target name (
wasm32).
- add version string target name (
README,tcc-doc.texi- mention restricted wasm backend and limits.
- Add new format enum in
tcc.h:TCC_OUTPUT_FORMAT_WASM.
libtcc.c- parse
-Wl,-oformat=wasm(or target default to wasm format).
- parse
tccelf.c/ output dispatcher- route wasm target output to
tcc_output_wasm(...)intccwasm.c. - keep ELF/PE/Mach-O paths untouched for other targets.
- route wasm target output to
tccgen.c,tcctok.h,include/tccdefs.h- disable/reject varargs builtins on wasm backend with clear errors.
tccasm.cpath- keep asm unsupported for wasm; emit clear diagnostic.
- Add backend guard diagnostics for unsupported features:
- function pointers (phase 1)
- VLAs/alloca (phase-gated)
- unsupported long double operations.
Documented supported subset for kernel authors:
- No varargs.
- No inline asm.
- No function pointer calls.
- Prefer POD scalar types and pointers.
- Struct passing/return only within supported ABI path (memory-based).
- No reliance on process/system calls.
This contract must be encoded as compile-time diagnostics, not silent miscompiles.
Deliverables:
- Target macro/build integration compiles.
tcc -vreportswasm32.- Backend stubs linked, with explicit
tcc_error("not implemented")at codegen entry points.
Exit criteria:
makesucceeds for wasm target build artifacts.
Deliverables:
wasm-gen.csupports:- integer constants/ops
- local loads/stores
- function prolog/epilog
- direct calls
- returns
tccwasm.cemits valid module with:- one memory
- one exported function
- code section and minimal data section.
Exit criteria:
- compile/run simple kernels in a wasm runtime:
- add
- mul
- looped sum.
Deliverables:
- Basic-block IR.
- CFG builder.
- Structured lowering for:
if/else- loops
switchlowering.
Exit criteria:
- control-flow kernel tests pass against native reference results.
Deliverables:
gen_opf,gen_cvt_itof,gen_cvt_ftoi,gen_cvt_ftof.- Correct comparisons and boolean lowering.
- Deterministic NaN/inf behavior aligned with wasm semantics.
Exit criteria:
- fp-heavy math kernel tests pass within tolerance.
Deliverables:
- Data/BSS placement and initialization.
- Symbol export policy:
- export all non-static functions by default for MVP, or
- export selected symbols via attribute/option.
- Pointer relocation/fixups for internal data references.
Exit criteria:
- kernels using static lookup tables compile and run.
Deliverables:
- Clear diagnostics for every unsupported construct.
- Test suite additions (backend + runtime validation).
- Documentation of guarantees and non-goals.
Exit criteria:
- stable compile/run behavior for target kernel corpus.
Implemented in this branch:
wasm32target plumbing acrossconfigure,Makefile,tcc.h,libtcc.c,tcc.c,tccelf.c.- Working restricted backend IR in
wasm-gen.cfor:- scalar integer/floating loads/stores and arithmetic,
- split-register
long longlowering bridged to wasmi64(calls/returns,TOK_ADDC*/TOK_SUBC*/TOK_UMULL, int<->fp conversions), - helper/libcall compatibility by lowering common
__*di3helper calls in wasm emission (__divdi3,__udivdi3,__moddi3,__umoddi3,__ash*l*di3,__floatundi*,__fixuns*di), - comparisons and boolean lowering,
- prolog/epilog, direct calls, indirect calls (
call_indirect), returns, - control flow via jump lists.
- Working wasm module writer in
tccwasm.c:- type/function/table/memory/global/export/element/code/data sections,
- linear-memory stack (
__stack_pointerglobal), - static data/rodata segments and bss placement,
- data/rodata relocation application for pointer initializers,
- stable symbol resolution for IR address ops via captured symbol index/token metadata (avoids stale
Sym*dereference issues).
- Control-flow lowering strategy implemented as PC-dispatch in wasm code, enabling unstructured TinyCC jumps (
if/loops/switch/gotopatterns) without CFG structuring pass. - Compile-time diagnostics for unsupported features:
- variadics,
- computed goto,
- VLA/alloca.
Verified with runtime execution (Node wasm instantiation) on:
- Straight-line integer kernels (
add,muladd). - Loop/switch kernels.
- Floating-point kernels (
floatanddouble). - Direct internal function calls.
- Global data/rodata/bss access.
- Dedicated wasm regression suite in
tests/wasm:ll_helpers(i64 helper/libcall lowering),call_indirect(function pointer indirect calls, including i64/f64 signatures),globals(rodata/data/bss initialization and mutation),static_ptr_init(static pointer initializers to internal rodata/functions), wired intotests/Makefileas conditionalwasm-dirwhenwasm32-tccandnodeare available.
Not yet implemented:
- WASI/host import model.
- Dedicated wasm debug info emission.
- Instruction encoding helpers in
tccwasm.c. - CFG to structured wasm lowering on synthetic control-flow graphs.
- Type/signature mapping tests.
Add wasm backend tests under tests/:
- Integer arithmetic kernels.
- Loop and branch kernels.
- Float kernels.
- Pointer indexing kernels.
- Unsupported-feature diagnostics tests.
- Run generated
.wasminwasmtime(or equivalent) in CI. - Compare outputs with native
tcc/clangreference.
- Control-flow lowering complexity
- Mitigation: explicit CFG IR and staged reducible CFG support.
- Mismatch with TinyCC register/value assumptions
- Mitigation: virtual register local mapping and aggressive assertions.
- Silent ABI misbehavior on structs
- Mitigation: force memory-based struct ABI in MVP, add explicit checks.
- Feature creep
- Mitigation: lock MVP contract to kernel-only subset.
- Runtime helper dependencies (libtcc1)
- Mitigation: start with helper-free subset, then add selected helpers.
wasm32target selectable and compiler builds.
- math kernels without branches compile to valid wasm and execute correctly.
if/loop/switchkernel set passes.
- fp kernels match expected numerical behavior.
- selected
../miniexprkernels compile and run as wasm module exports.
- Add target plumbing (
configure,Makefile,tcc.h,libtcc.c,tcc.c). - Create backend skeleton files (
wasm-gen.c,wasm-link.c,tccwasm.c). - Add wasm output dispatch.
- Implement function/module minimal happy path.
- Add first runtime test harness for generated wasm.
- Iterate on control flow and float support.
Backend is considered done for this project scope when:
- Kernel subset compiles to
.wasmreliably. - Generated modules run in a standard wasm runtime without WASI.
- Unsupported language features fail fast with precise diagnostics.
- Added wasm tests are stable in CI.
- Documentation states exact supported subset and known gaps.