Tiny C Compiler Reference Documentation

This manual documents version 0.9.28rc of the Tiny C Compiler.

Table of Contents


1 Introduction

TinyCC (aka TCC) is a small but hyper fast C compiler. Unlike other C compilers, it is meant to be self-relying: you do not need an external assembler or linker because TCC does that for you.

TCC compiles so fast that even for big projects Makefiles may not be necessary.

TCC not only supports ANSI C, but also most of the ISO C99 standard, many ISO C11 features, and many GNUC extensions including inline assembly.

TCC can also be used to make C scripts, i.e. pieces of C source that you run as a Perl or Python script. Compilation is so fast that your script will be as fast as if it was an executable.

TCC can also automatically generate memory and bound checks (see TinyCC Memory and Bound checks) while allowing all C pointers operations. TCC can do these checks even if non patched libraries are used.

With libtcc, you can use TCC as a backend for dynamic code generation (see The libtcc library).

TCC supports the following target and platform combinations:

OSi386x86-64ARMARM64RISC-V 64C67
Linuxyesyesyesyesyesyes
macOSyesyes
WindowsyesyesWinCEyes
Androidyesyesyesyes
FreeBSDyesyes
NetBSDyesyesyes
OpenBSDyesyesyesyes
DragonFlyyes

The TMS320C67xx (C67) target is a cross compiler for the digital signal processors of that family. It outputs COFF instead of ELF and has neither libtcc1.a nor bound checking.

For usage on Windows, see also tcc-win32.txt.


2 Command line invocation

2.1 Quick start

usage: tcc [options] [infile1 infile2...] [-run infile args...]

TCC options are very much like gcc options. The main difference is that TCC can also execute directly the resulting program and give it runtime arguments.

Here are some examples to understand the logic:

‘tcc -run a.c’

Compile a.c and execute it directly

‘tcc -run a.c arg1’

Compile a.c and execute it directly. arg1 is given as first argument to the main() of a.c.

‘tcc a.c -run b.c arg1’

Compile a.c and b.c, link them together and execute them. arg1 is given as first argument to the main() of the resulting program.

‘tcc -o myprog a.c b.c’

Compile a.c and b.c, link them and generate the executable myprog.

‘tcc -o myprog a.o b.o’

link a.o and b.o together and generate the executable myprog.

‘tcc -c a.c’

Compile a.c and generate object file a.o.

‘tcc -c asmfile.S’

Preprocess with C preprocess and assemble asmfile.S and generate object file asmfile.o.

‘tcc -c asmfile.s’

Assemble (but not preprocess) asmfile.s and generate object file asmfile.o.

‘tcc -r -o ab.o a.c b.c’

Compile a.c and b.c, link them together and generate the object file ab.o.

Scripting:

TCC can be invoked from scripts, just as shell scripts. You just need to add #!/usr/local/bin/tcc -run at the start of your C source:

#!/usr/local/bin/tcc -run
#include <stdio.h>

int main()
{
    printf("Hello World\n");
    return 0;
}

TCC can read C source code from standard input when - is used in place of infile. Example:

echo 'main(){puts("hello");}' | tcc -run -

2.2 Option summary

General Options

-c

Generate an object file.

-o outfile

Put object file, executable, or dll into output file outfile.

-run source [args...]

Compile file source and run it with the command line arguments args. In order to be able to give more than one argument to a script, several TCC options can be given after the -run option, separated by spaces:

tcc "-run -L/usr/X11R6/lib -lX11" ex4.c

In a script, it gives the following header:

#!/usr/local/bin/tcc -run -L/usr/X11R6/lib -lX11
-rstdin file

With -run: reopen standard input from file before executing the program. This is mainly useful when the C source itself was read from standard input (see - above).

-v

Display TCC version.

-vv

Show included files. As sole argument, print search dirs. -vvv shows tries too.

-bench

Display compilation statistics.

-dumpmachine

Print target machine architecture triplet.

-dumpversion

Print TCC compiler version.

Preprocessor Options

-Idir

Specify an additional include path. Include paths are searched in the order they are specified.

System include paths are always searched after. The defaults are tccdir/include and then /usr/include, where tccdir is the tcc private directory (PREFIX/lib/tcc, see -B; PREFIX is usually /usr or /usr/local). On Windows the defaults are tccdir/include and tccdir/include/winapi. Use -vv as sole argument to print the paths of the current build.

-isystem dir

Specify a system include path to be added to the defaults.

-nostdinc

Do not search the default system include paths; only search include paths provided on the command line.

-include file

Include file above each input file.

-Dsym[=val]

Define preprocessor symbol ‘sym’ to val. If val is not present, its value is ‘1’. Function-like macros can also be defined: -DF(a)=a+1

-Usym

Undefine preprocessor symbol ‘sym’.

-E

Preprocess only, to stdout or file (with -o).

-P

Do not output #line directives.

-P1

Output alternative #line directives.

-dD, -dM

Output #define directives.

-Wp,-opt

Same as -opt.

Compilation Flags

Note: each of the following options has a negative form beginning with -fno-.

-funsigned-char

Let the char type be unsigned.

-fsigned-char

Let the char type be signed.

-fcommon

Generate common symbols for uninitialized data. The default is -fno-common, which puts tentative definitions directly in the bss section.

-fleading-underscore

Add a leading underscore at the beginning of each C symbol.

-fms-extensions

Allow a MS C compiler extensions to the language. Currently this assumes a nested named structure declaration without an identifier behaves like an unnamed one.

-fdollars-in-identifiers

Allow dollar signs in identifiers

-freverse-funcargs

Evaluate function arguments right to left.

-fgnu89-inline

extern inline is like static inline.

-fasynchronous-unwind-tables

Create eh_frame section [on]

-ftest-coverage

Create code coverage code. After running the resulting code an executable.tcov or sofile.tcov file is generated with code coverage.

Warning Options

-w

Disable all warnings.

Note: each of the following warning options has a negative form beginning with -Wno-.

-Wimplicit-function-declaration

Warn about implicit function declaration (missing prototype).

-Wdiscarded-qualifiers

Warn when const is dropped.

-Wunsupported

Warn about unsupported GCC features that are ignored by TCC.

-Wwrite-strings

Make string constants be of type const char * instead of char *.

-Werror

Abort compilation if a warning is issued. Can be given an option to enable the specified warning and turn it into an error, for example -Werror=unsupported.

-Wall

Activate some useful warnings (-Wimplicit-function-declaration, -Wdiscarded-qualifiers).

Linker Options

-Ldir

Specify an additional static library path for the -l option. The defaults are the tcc private directory (see -B) and /usr/lib, which the build may replace by the library directory of the host (/usr/lib64 or a multiarch triplet directory). On Windows the default is tccdir/lib. Use -vv as sole argument to print the paths of the current build.

-lxxx

Link your program with dynamic library libxxx.so or static library libxxx.a. The library is searched in the paths specified by the -L option and LIBRARY_PATH variable.

-Bdir

Set the path where the tcc internal libraries (and include files) can be found (default is PREFIX/lib/tcc).

-shared

Generate a shared library instead of an executable.

-soname name

set name for shared library to be used at runtime

-static

Generate a statically linked executable (default is a shared linked executable).

-rdynamic

Export global symbols to the dynamic linker. It is useful when a library opened with dlopen() needs to access executable symbols.

-pthread

Preprocess with -D_REENTRANT and link with -lpthread.

-r

Generate an object file combining all input files.

-nostdlib

Don’t implicitly link with libc, the C runtime files, and libtcc1.

-Wl,-nostdlib

Don’t search the default library paths (see -L). Only the paths specified with -L and LIBRARY_PATH are searched.

-Wl,-rpath=path

Put custom search path for dynamic libraries into executable.

-Wl,-Ipath
-Wl,--dynamic-linker=path

Set the ELF interpreter (dynamic linker). This defaults to the value of the environment variable LD_SO if set, or a compiled-in default.

-Wl,--enable-new-dtags

When putting a custom search path for dynamic libraries into the executable, create the new ELF dynamic tag DT_RUNPATH instead of the old legacy DT_RPATH.

-Wl,--oformat=fmt

Use fmt as output format. The supported output formats are:

elf32-i386

ELF output format (default)

binary

Binary image (only for executable output)

coff

COFF output format (only for executable output for TMS320C67xx target)

-Wl,--export-all-symbols
-Wl,--export-dynamic

Export global symbols to the dynamic linker. It is useful when a library opened with dlopen() needs to access executable symbols.

-Wl,-subsystem=console/gui/wince/...

Set type for PE (Windows) executables.

-Wl,-[Ttext=# | section-alignment=# | file-alignment=# | image-base=# | stack=#]

Modify executable layout.

-Wl,-(no-|disable-)[dynamicbase | nxcompat | high-entropy-va | tsaware]

Set or clear PE (Windows) executable header hardening flags. The -Wl,-high-entropy-va option is supported on x86-64 and ARM64 PE targets and implies -Wl,-dynamicbase. Clearing dynamicbase also clears high-entropy-va. When -Wl,-dynamicbase is used for an executable, TCC also enables base relocation emission for Windows ASLR.

-Wl,-Bsymbolic

Set DT_SYMBOLIC tag.

-Wl,-(no-)whole-archive

Turn on/off linking of all objects in archives.

Debugger Options

-g

Generate run time stab debug information so that you get clear run time error messages: test.c:68: in function 'test5()': dereferencing invalid pointer instead of the laconic Segmentation fault.

-gdwarf[-x]

Generate run time dwarf debug information instead of stab debug information.

-b

Generate additional support code to check memory allocations and array/pointer bounds (see TinyCC Memory and Bound checks). -g is implied.

-bt[N]

Display N callers in stack traces. This is useful with -g or -b. When activated, __TCC_BACKTRACE__ is defined.

With executables, additional support for stack traces is included. A function int tcc_backtrace(const char *fmt, ...); is provided to trigger a stack trace with a message on demand.

Misc Options

-std=version

Define __STDC_VERSION__ to 201112 if version is c11 or gnu11; 199901 otherwise.

-x[c|a|b|n]

Specify content of next input file: respectively C, assembly, binary, or none.

-O[n]

Same as -D__OPTIMIZE__ except for -O0. -Os is treated the same as -O1.

-M

Just output makefile fragment with dependencies

-MM

Like -M except mention only user header files, not system header files.

-MD

Generate makefile fragment with dependencies.

-MMD

Like -MD except mention only user header files, not system header files.

-MF depfile

Use depfile as output for -MD.

-MP

Mention all dependencies as targets too.

-print-search-dirs

Print the configured installation directory and a list of library and include directories tcc will search.

-dt

With -run/-E: auto-define ’test_...’ macros

Target Specific Options

-mms-bitfields

Use an algorithm for bitfield alignment consistent with MSVC. Default is gcc’s algorithm.

-mfloat-abi (ARM only)

Select the float ABI. Possible values: softfp and hard

-mno-sse

Do not use sse registers on x86_64

-m32, -m64

Pass command line to the i386/x86_64 cross compiler.

macOS Specific Options (Mach-O Targets Only)

-dynamiclib

Generate a dynamic library instead of an executable.

-install_name name

Set the install name for a dynamic library.

-flat_namespace

Use a flat namespace (ignored, accepted for compatibility).

-two_levelnamespace

Use a two-level namespace (default, accepted for compatibility).

-undefined treatment

Specify how undefined symbols are treated (accepted for compatibility).

-compatibility_version version

Set the compatibility version for a dynamic library.

-current_version version

Set the current version for a dynamic library.

Tool Modes

tcc -ar [crstvx] lib [files]

Create a static library archive. TCC can function as an ar replacement without requiring an external archiver tool. The [abdiopN] keys are not supported.

tcc -impdef lib.dll [-v] [-o lib.def] (Windows only)

Create a .def definition file from a DLL.

Note: GCC options -fx, -mx, -arch, -C, --param, -pedantic, -pie, -no-pie, -pipe, -s, and -traditional are ignored. -Wunsupported makes TCC warn about them.

Environment variables that affect how tcc operates.

CPATH
C_INCLUDE_PATH

A colon-separated list of directories searched for include files, directories given with -I are searched first.

LIBRARY_PATH

A colon-separated list of directories searched for libraries for the -l option, directories given with -L are searched first.


3 C language support

3.1 ANSI C

TCC implements all the ANSI C standard, including structure bit fields and floating point numbers (long double, double, and float fully supported).

3.2 ISOC99 extensions

TCC implements many features of the new C standard: ISO C99. Currently missing items are: complex and imaginary numbers.

Currently implemented ISOC99 features:

  • variable length arrays.
  • 64 bit long long types are fully supported.
  • The boolean type _Bool is supported.
  • __func__ is a string variable containing the current function name.
  • Variadic macros: __VA_ARGS__ can be used for function-like macros:
        #define dprintf(level, __VA_ARGS__) printf(__VA_ARGS__)
    

    dprintf can then be used with a variable number of parameters.

  • Declarations can appear anywhere in a block (as in C++).
  • Array and struct/union elements can be initialized in any order by using designators:
        struct { int x, y; } st[10] = { [0].x = 1, [0].y = 2 };
    
        int tab[10] = { 1, 2, [5] = 5, [9] = 9};
    
  • Compound initializers are supported:
        int *p = (int []){ 1, 2, 3 };
    

    to initialize a pointer pointing to an initialized array. The same works for structures and strings.

  • Hexadecimal floating point constants are supported:
              double d = 0x1234p10;
    

    is the same as writing

              double d = 4771840.0;
    
  • inline keyword is supported. Static inline functions are emitted at the end of the compilation unit only if used. The behavior of extern inline depends on -fgnu89-inline (see Command line invocation).
  • restrict keyword is ignored.

3.3 ISO C11 extensions

TCC implements several features of the ISO C11 standard:

  • _Generic keyword for type-generic expressions:
        #define print_type(x) _Generic((x), \
            int: "int", \
            float: "float", \
            default: "other")
    
  • _Static_assert(expr, msg) for compile-time assertions. The single-argument form _Static_assert(expr) (C23) is also supported.
  • _Atomic type qualifier for atomic types.
  • _Thread_local storage-class specifier for thread-local storage. The GCC extension __thread is also supported.
  • _Noreturn function specifier (equivalent to the __attribute__((noreturn)) GNU extension).
  • _Alignas(n) specifier to request alignment of a variable or structure field.
  • _Alignof operator to query the alignment of a type or expression.

3.4 GNU C extensions

TCC implements some GNU C extensions:

  • array designators can be used without ’=’:
        int a[10] = { [0] 1, [5] 2, 3, 4 };
    
  • Structure field designators can be a label:
        struct { int x, y; } st = { x: 1, y: 1};
    

    instead of

        struct { int x, y; } st = { .x = 1, .y = 1};
    
  • \e is ASCII character 27.
  • case ranges : ranges can be used in cases:
        switch(a) {
        case 1 ... 9:
              printf("range 1 to 9\n");
              break;
        default:
              printf("unexpected\n");
              break;
        }
    
  • The keyword __attribute__ is handled to specify variable or function attributes. The following attributes are supported:
    • aligned(n): align a variable or a structure field to n bytes (must be a power of two).
    • packed: force alignment of a variable or a structure field to 1.
    • section(name): generate function or data in assembly section name (name is a string containing the section name) instead of the default section.
    • unused: specify that the variable or the function is unused. Accepted but currently ignored.
    • cleanup(func): specify a function to be called automatically when the variable goes out of scope. The cleanup function must take one parameter, a pointer to a type compatible with the variable, and return void.
    • constructor: specify that the function is to be executed automatically before main() is called.
    • destructor: specify that the function is to be executed automatically after main() returns or exit() is called.
    • always_inline: force inline expansion of the function.
    • alias("target"): declare the function or variable as an alias for symbol target (a string containing the target symbol name).
    • visibility("mode"): set symbol visibility. Supported modes are "default", "hidden", "internal", and "protected".
    • weak: declare the symbol as a weak symbol.
    • noreturn: specify that the function does not return to its caller.
    • cdecl: use standard C calling convention (default).
    • stdcall: use Pascal-like calling convention.
    • fastcall: use fastcall calling convention (i386 only).
    • thiscall: use C++-style thiscall calling convention (i386 only).
    • regparm(n): use fast i386 calling convention. n must be between 1 and 3. The first n function parameters are respectively put in registers %eax, %edx and %ecx.
    • __mode__(mode): specify the data type size mode for integer variables or typedefs (supported modes: __QI__, __HI__, __SI__, __DI__, __word__). The attribute is only taken into account when it is given with the declaration specifiers, that is before the declarator:
          typedef __attribute__ ((__mode__(__QI__))) int int8_type;
      
    • dllexport: export function from dll/executable (win32 only).
    • dllimport: import function from dll/executable (win32 only).
    • nodecorate: do not apply any decorations that would otherwise be applied when exporting function from dll/executable (win32 only).
    • nodebug: suppress debug information for the symbol.
    • format(archetype, fmt_idx, chk_idx): marks functions that take printf- or scanf-style format strings. Accepted but currently ignored (not checked by TCC).
    • used: indicates that the symbol must be retained even if it appears unreferenced. Accepted but currently ignored.

    Here are some examples:

        int a __attribute__ ((aligned(8), section(".mysection")));
    

    align variable a to 8 bytes and put it in section .mysection.

        int my_add(int a, int b) __attribute__ ((section(".mycodesection")))
        {
            return a + b;
        }
    

    generate function my_add in section .mycodesection.

        void free_ptr(void *p) { free(*(void **)p); }
        void foo(void) {
            char *buf __attribute__((cleanup(free_ptr))) = malloc(1024);
            /* buf is freed automatically when leaving foo */
        }
    

    automatically call free_ptr(&buf) when variable buf goes out of scope.

  • GNU style variadic macros:
        #define dprintf(fmt, args...) printf(fmt, ## args)
    
        dprintf("no arg\n");
        dprintf("one arg %d\n", 1);
    
  • __FUNCTION__ is interpreted as C99 __func__ (so it has not exactly the same semantics as string literal GNUC where it is a string literal).
  • The __alignof__ keyword can be used as sizeof to get the alignment of a type or an expression.
  • The typeof(x) returns the type of x. x is an expression or a type.
  • Computed gotos: &&label returns a pointer of type void * on the goto label label. goto *expr can be used to jump on the pointer resulting from expr.
  • Statement expressions: a compound statement enclosed in parentheses may appear as an expression. The value of the expression is the value of the last statement. This is commonly used in macros:
        #define max(a,b) ({ int _a = (a), _b = (b); _a > _b ? _a : _b; })
    
  • The __label__ keyword declares local labels within a block:
        { __label__ done; /* ... */ done: ; }
    
  • The __extension__ keyword suppresses warnings for GNU extensions in strict compilation modes.
  • Inline assembly with asm instruction:
    static inline void * my_memcpy(void * to, const void * from, size_t n)
    {
    int d0, d1, d2;
    __asm__ __volatile__(
            "rep ; movsl\n\t"
            "testb $2,%b4\n\t"
            "je 1f\n\t"
            "movsw\n"
            "1:\ttestb $1,%b4\n\t"
            "je 2f\n\t"
            "movsb\n"
            "2:"
            : "=&c" (d0), "=&D" (d1), "=&S" (d2)
            :"0" (n/4), "q" (n),"1" ((long) to),"2" ((long) from)
            : "memory");
    return (to);
    }
    

    TCC includes its own x86 inline assembler with a gas-like (GNU assembler) syntax. No intermediate files are generated. GCC 3.x named operands are supported. asm goto is also supported for control-flow transfer to C labels:

      asm goto ("jmp %l[label]" : : : : label);
    
  • The following GCC built-in functions are supported:
    • __builtin_types_compatible_p(type1, type2): returns 1 if type1 is compatible with type2, 0 otherwise.
    • __builtin_constant_p(exp): returns 1 if exp evaluates to a compile-time constant, 0 otherwise.
    • __builtin_choose_expr(const_expr, exp1, exp2): evaluates to exp1 if const_expr is non-zero, otherwise exp2.
    • __builtin_expect(expr, expected): branch prediction hint (evaluates to expr).
    • __builtin_unreachable(): informs the compiler that the code location cannot be reached.
    • __builtin_frame_address(level): returns the frame pointer address for stack level level.
    • __builtin_return_address(level): returns the return address for stack level level.
    • __builtin_offsetof(type, field): returns the byte offset of field within structure type.
    • Bit manipulation built-ins: __builtin_clz, __builtin_ctz, __builtin_ffs, __builtin_popcount, __builtin_parity, __builtin_clrsb (and their l / ll type variants).
    • Variadic argument handling built-ins: __builtin_va_start, __builtin_va_arg, __builtin_va_copy, __builtin_va_end.
    • Memory and string built-ins (mapped to libc): __builtin_memcpy, __builtin_memmove, __builtin_memset, __builtin_memcmp, __builtin_strlen, __builtin_strcpy, __builtin_strncpy, __builtin_strcmp, __builtin_strncmp, __builtin_strcat, __builtin_strncat, __builtin_strchr, __builtin_strrchr, __builtin_strdup, __builtin_malloc, __builtin_realloc, __builtin_calloc, __builtin_memalign, __builtin_free, __builtin_alloca, __builtin_abort.
    • Atomic built-ins: __atomic_store, __atomic_load, __atomic_exchange, __atomic_compare_exchange, __atomic_fetch_add, __atomic_fetch_sub, __atomic_fetch_or, __atomic_fetch_xor, __atomic_fetch_and, __atomic_fetch_nand, and their reverse __atomic_add_fetch variants.
  • Pragmas supported by TinyCC:
    • #pragma pack(n), #pragma pack(), #pragma pack(push), #pragma pack(push, n), #pragma pack(pop): set structure alignment or manipulate the packing alignment stack.
    • #pragma push_macro("MACRO") and #pragma pop_macro("MACRO"): push and pop macro definitions to/from a macro stack.
    • #pragma once: ensure the header file is included only once during compilation.
    • #pragma comment(lib, "libname"): specify a library to link automatically.
    • #pragma comment(option, "flags"): pass command line options directly within source code.
  • Preprocessor features:
    • #include_next <file>: include the next file of the same name in the header search path order.
    • #warning "message": emit a preprocessor warning message.
    • GNU empty variadic macro argument pasting: , ##__VA_ARGS__ strips the leading comma when __VA_ARGS__ is empty.
    • __has_include(<file>) and __has_include("file"): test whether a header file exists. Can be used in #if / #elif preprocessor conditions.
    • __has_include_next(<file>): like __has_include but searches in the next include path, for use in wrapper headers.

3.5 TinyCC extensions

  • __TINYC__ is a predefined macro to indicate that you use TCC.
  • #! at the start of a line is ignored to allow scripting.
  • Binary digits can be entered (0b101 instead of 5).

4 TinyCC Assembler

Since version 0.9.16, TinyCC integrates its own assembler. TinyCC assembler supports a gas-like syntax (GNU assembler). You can deactivate assembler support if you want a smaller TinyCC executable (the C compiler does not rely on the assembler).

TinyCC Assembler is used to handle files with .S (C preprocessed assembler) and .s extensions. It is also used to handle the GNU inline assembler with the asm keyword.

4.1 Syntax

TinyCC Assembler supports most of the gas syntax. The tokens are the same as C.

  • C and C++ comments are supported.
  • Identifiers are mostly the same as C. The dot (.) is accepted as an identifier character in assembler code. The dollar sign ($) is accepted with -fdollars-in-identifiers, except in inline assembly on targets other than x86-64 and RISC-V 64.
  • 64-bit integer numbers are supported.

4.2 Expressions

  • Integers in decimal, octal and hexa are supported.
  • Unary operators: +, -, ~.
  • Binary operators in decreasing priority order:
    1. *, /, %, <<, >>
    2. &, |, ^
    3. +, -
  • A value is either an absolute number or a label plus an offset. Only the + and - operators can be used with labels (to add or subtract an offset). All other operators require absolute values. - supports two labels only if they are the same or if they are both defined and in the same section.

4.3 Labels

  • All labels are considered as local, except undefined ones.
  • Numeric labels can be used as local gas-like labels. They can be defined several times in the same source. Use ’b’ (backward) or ’f’ (forward) as suffix to reference them:
     1:
          jmp 1b /* jump to '1' label before */
          jmp 1f /* jump to '1' label after */
     1:
    

4.4 Directives

All directives are preceded by a ’.’. The following directives are supported:

  • .align n[,value]
  • .skip n[,value]
  • .space n[,value]
  • .byte value1[,...]
  • .word value1[,...]
  • .short value1[,...]
  • .int value1[,...]
  • .long value1[,...]
  • .quad immediate_value1[,...]
  • .globl symbol
  • .global symbol
  • .section section
  • .text
  • .data
  • .bss
  • .fill repeat[,size[,value]]
  • .org n
  • .previous
  • .string string[,...]
  • .asciz string[,...]
  • .ascii string[,...]
  • .p2align n
  • .balign n[,value]
  • .pushsection section
  • .popsection
  • .set symbol, expr
  • .weak symbol
  • .hidden symbol
  • .type symbol, type

4.5 X86 Assembler

All i386 opcodes are supported. Most common x86_64 opcodes are supported, including MMX and a subset of the SSE instruction set; SSE2 support is limited to a couple of instructions. Only AT&T syntax is supported (source then destination operand order). If no size suffix is given, TinyCC tries to guess it from the operand sizes. Note that more recent extensions such as AVX, AVX2, and AVX-512 are not supported.

x86_64 adds 64-bit operand support (the q suffix), additional registers (%r8–%r15), and instructions such as cqto, pushfq, popfq, bswapq, cmpxchg16b, movnti, prefetch*, lfence, mfence, sfence, and endbr64 (Control-Flow Enforcement).

4.6 ARM, ARM64 and RISC-V Assemblers

TCC also includes assemblers for the ARM (32-bit), ARM64 (AArch64) and RISC-V 64 targets. These handle the same .S and .s file extensions and support the same inline assembly mechanism as the x86 assemblers.


5 TinyCC Linker

TCC includes its own linker and can directly output executables, shared libraries, and object files without relying on an external linker.

5.1 ELF file generation

TCC can directly output relocatable ELF files (object files), executable ELF files and dynamic ELF libraries without relying on an external linker.

Dynamic ELF libraries can be output but the C compiler does not generate position independent code (PIC). It means that the dynamic library code generated by TCC cannot be factorized among processes yet.

TCC linker eliminates unreferenced object code in libraries. A single pass is done on the object and library list, so the order in which object files and libraries are specified is important (same constraint as GNU ld). No grouping options (--start-group and --end-group) are supported.

TCC generates standard ELF sections including .text, .data, .data.ro (read only data), .bss, .plt, .got, and .eh_frame. Shared libraries additionally get .gnu.hash, .gnu.version, .dynamic, and relocation sections (.rela.got, .rela.plt).

TCC automatically defines section boundary symbols __start_SEC and __stop_SEC for every allocated section whose name, without the leading dot, is a valid C identifier. These are useful for iterating over section contents from C code:

extern char __start_text[], __stop_text[];
size_t text_size = __stop_text - __start_text;

5.2 ELF file loader

TCC can load ELF object files, archives (.a files) and dynamic libraries (.so).

5.3 PE file generation

TCC for Windows supports the native Win32 executable file format (PE-i386). It generates PE32 (i386) and PE32+ (x86-64) executables, as well as DLL files. TCC also supports PE with ARM64 machine type, including .pdata unwind information for structured exception handling.

PE executables can target several subsystems (see the -Wl,-subsystem option); which ones are available depends on the target. Standard PE sections are emitted (.text, .data, .rdata, .bss, .rsrc, .pdata, .idata, .reloc); the export directory goes to .rdata.

5.4 Mach-O file generation

TCC on macOS produces Mach-O executables and dynamic libraries (.dylib) for x86-64 and ARM64 (AArch64). The files TCC writes always contain a single architecture.

TCC can load Mach-O dynamic libraries and text-based stub files (.tbd) for linking against system frameworks. Fat (universal) libraries are accepted, the slice matching the target being selected.

Mach-O output uses dyld chained fixups on both x86-64 and ARM64.

5.5 Binary and COFF output

In addition to the platform-native container formats, TCC supports:

Binary image

Raw binary output with no container headers. Selected via -Wl,--oformat=binary (see Command line invocation). Useful for bootloaders, kernels, and embedded targets. Only valid for executable output.

COFF

The TMS320C67xx (C67) target outputs COFF executables. Object files are always written as ELF.

5.6 GNU Linker Scripts

Because on many Linux systems some dynamic libraries (such as /usr/lib/libc.so) are in fact GNU ld link scripts (horrible!), the TCC linker also supports a subset of GNU ld scripts.

The GROUP and FILE commands are supported. OUTPUT_FORMAT and TARGET are ignored.

Example from /usr/lib/libc.so:

/* GNU ld script
   Use the shared library, but some functions are only in
   the static library, so try that secondarily.  */
GROUP ( /lib/libc.so.6 /usr/lib/libc_nonshared.a )

6 TinyCC Memory and Bound checks

This feature is activated with the -b option (see Command line invocation). Here are some examples of caught errors:

Invalid range with standard string function:
{
    char tab[10];
    memset(tab, 0, 11);
}
Out of bounds-error in global or local arrays:
{
    int tab[10];
    for(i=0;i<11;i++) {
        sum += tab[i];
    }
}
Out of bounds-error in malloc’ed data:
{
    int *tab;
    tab = malloc(20 * sizeof(int));
    for(i=0;i<21;i++) {
        sum += tab[i];
    }
    free(tab);
}
Out of bounds-error in alloca’ed data:
{
    char *p = alloca(10);
    memset(p, 'a', 11);
}
Out of bounds-error in variable length arrays:
{
    int tab[n];
    for(i=0;i<n+1;i++) {
        sum += tab[i];
    }
}
Access of freed memory:
{
    int *tab;
    tab = malloc(20 * sizeof(int));
    free(tab);
    for(i=0;i<20;i++) {
        sum += tab[i];
    }
}
Double free:
{
    int *tab;
    tab = malloc(20 * sizeof(int));
    free(tab);
    free(tab);
}
Overlapping regions in memory and string functions:
{
    char tab[10];
    memcpy(tab, tab + 1, 5);
}

The checks are not limited to the code generated by TCC: the bound checking runtime also replaces the memory allocation functions (malloc, calloc, realloc, memalign, free) and the most common memory and string functions (memcpy, memmove, memset, memcmp, strlen, strcpy, strncpy, strcmp, strncmp, strcat, strncat, strchr, strrchr, strdup) by versions checking their arguments. Regions created by alloca, by variable length arrays and (except on Windows) by mmap are tracked as well. setjmp and longjmp (and sigsetjmp and siglongjmp) are handled so that the regions of the abandoned stack frames are released.

TCC defines __TCC_BCHECK__ if activated.

There are five environment variables that can be used to control the behavior:

Also, a function __bounds_checking(x) can be used to turn off/on bounds checking from usercode (see below).

Notes:

#ifdef __TCC_BCHECK__
extern void __bounds_checking (int x);
# define BOUNDS_CHECKING_OFF __bounds_checking(1)
# define BOUNDS_CHECKING_ON  __bounds_checking(-1)
#else
# define BOUNDS_CHECKING_OFF
# define BOUNDS_CHECKING_ON
#endif

For more information about the ideas behind this method, see http://www.doc.ic.ac.uk/~phjk/BoundsChecking.html.


7 The libtcc library

The libtcc library enables you to use TCC as a backend for dynamic code generation.

Read the libtcc.h to have an overview of the API. Read tests/libtcc_test.c to have a very simple example.

The idea consists in giving a C string containing the program you want to compile directly to libtcc. Then you can access to any global symbol (function or variable) defined.

A typical session creates a compilation state with tcc_new(), selects the output type with tcc_set_output_type() (this must be done before any compilation), passes command line options with tcc_set_options() and adds input with tcc_compile_string() or tcc_add_file(). The result is then either written to a file with tcc_output_file(), run with tcc_run(), or relocated in memory with tcc_relocate() so that the compiled functions and variables can be retrieved with tcc_get_symbol(). tcc_output_file() and tcc_run() do the relocation themselves, so tcc_relocate() must not be called before them. Symbols of the host program are made visible to the compiled code with tcc_add_symbol(). The state and everything it allocated is released by tcc_delete().

Errors and warnings go to stderr unless a callback is installed with tcc_set_error_func(). Several states may be used at the same time from different threads; see tests/libtcc_test_mt.c, which also shows how tcc_setjmp() catches the runtime exceptions of code compiled with -b or -bt.


8 Developer’s guide

This chapter gives some hints to understand how TCC works. You can skip it if you do not intend to modify the TCC code.

8.1 File reading

The BufferedFile structure contains the context needed to read a file, including the current line number. tcc_open() opens a new file and tcc_close() closes it. tcc_open_bf() builds the same context for a memory buffer instead of a file; it is used for the -D options of the command line and for token pasting.

The contexts are stacked through the BufferedFile.prev field, so the current file is always the innermost #include. next_c() returns the next character and calls handle_eob() to refill the buffer when it is exhausted.

8.2 Lexer

next() reads the next token in the current file. next_nomacro() reads the next token without macro expansion.

tok contains the current token (see TOK_xxx constants). Identifiers and keywords are also tokens: they are entered in the table_ident array of TokenSym structures, so a string is never needed to designate them. tokc contains additional infos about the token (for example a constant value if number or string token).

8.3 Parser

The parser is hardcoded (yacc is not necessary). It does only one pass, except:

  • For initialized arrays with unknown size, a first pass is done to count the number of elements.
  • For architectures where arguments are evaluated in reverse order, a first pass is done to reverse the argument order.
  • For inline functions, the body is recorded as a token string and parsed again where the function is really needed.

8.4 Types

The types are stored in a CType structure. CType.t is a single ’int’ holding the basic type, the type modifiers and, during parsing, the storage class. CType.ref points to the Sym describing the referenced type: the pointed type for pointers, the element type for arrays, the return type and the parameters for functions, and the fields for structures and unions.

#define VT_BTYPE       0x000f  /* mask for basic type */
#define VT_VOID             0  /* void type */
#define VT_BYTE             1  /* signed byte type */
#define VT_SHORT            2  /* short type */
#define VT_INT              3  /* integer type */
#define VT_LLONG            4  /* 64 bit integer */
#define VT_PTR              5  /* pointer */
#define VT_FUNC             6  /* function type */
#define VT_STRUCT           7  /* struct/union definition */
#define VT_FLOAT            8  /* IEEE float */
#define VT_DOUBLE           9  /* IEEE double */
#define VT_LDOUBLE         10  /* IEEE long double */
#define VT_BOOL            11  /* ISOC99 boolean type */
#define VT_QLONG           13  /* 128-bit integer, only for the x86-64 ABI */
#define VT_QFLOAT          14  /* 128-bit float, only for the x86-64 ABI */

#define VT_UNSIGNED    0x0010  /* unsigned type */
#define VT_DEFSIGN     0x0020  /* explicitly signed or unsigned */
#define VT_ARRAY       0x0040  /* array type (also has VT_PTR) */
#define VT_BITFIELD    0x0080  /* bitfield modifier */
#define VT_CONSTANT    0x0100  /* const modifier */
#define VT_VOLATILE    0x0200  /* volatile modifier */
#define VT_VLA         0x0400  /* VLA type (also has VT_PTR and VT_ARRAY) */
#define VT_LONG        0x0800  /* long type (also has VT_INT rsp. VT_LLONG) */

#define VT_STRUCT_SHIFT 20     /* shift for bitfield shift values */

The VT_UNSIGNED flag can be set for chars, shorts, ints and long longs. VT_DEFSIGN tells whether the signedness was written explicitly; compare_types() only looks at it for char, the one type whose default signedness differs from an explicit one.

Arrays are considered as pointers VT_PTR with the flag VT_ARRAY set. Variable length arrays have VT_VLA set in addition to VT_PTR and VT_ARRAY.

VT_LONG is a modifier, not a basic type: long is VT_LONG | VT_INT or VT_LONG | VT_LLONG depending on the target. It does not change the generated code, but it is part of the type so that long stays distinct from int rsp. long long for type compatibility, for _Generic and in diagnostics.

If VT_BITFIELD is set, then the bitfield position is stored in the 6 bits starting at VT_STRUCT_SHIFT and the bitfield size in the 6 bits above it (macros BIT_POS() and BIT_SIZE()).

The same high order bits also distinguish types which share a basic type: VT_UNION is a VT_STRUCT with 1 there, VT_ENUM and VT_ENUM_VAL mark an integral type which is really an enum or an enum constant, and VT_ASM marks a symbol which was created by the assembler.

During parsing, the storage of an object is also stored in the type integer:

#define VT_EXTERN  0x00001000  /* extern definition */
#define VT_STATIC  0x00002000  /* static variable */
#define VT_TYPEDEF 0x00004000  /* typedef definition */
#define VT_INLINE  0x00008000  /* inline definition */
#define VT_TLS     0x00010000  /* thread-local storage */

The declaration properties which do not fit in the type integer (alignment, packing, visibility, weak, dllimport/dllexport, calling convention, …) are kept in the SymAttr and FuncAttr bitfields of the Sym structure.

8.5 Symbols

All symbols are stored in symbol stacks, chained through the Sym.prev field. Each symbol stack contains Sym structures.

Sym.v contains the symbol name (remember an identifier is also a token, so a string is never necessary to store it). Sym.type gives the type of the symbol. Sym.r is usually the register in which the corresponding variable is stored. Sym.c is usually a constant associated to the symbol like its address for normal symbols, and the number of entries for symbols representing arrays. Variable length array types use Sym.c as a location on the stack which holds the runtime sizeof for the type.

Five main symbol stacks are defined:

define_stack

for the macros (#defines).

global_stack

for the global variables, functions and types.

local_stack

for the local variables, functions and types.

global_label_stack

for the function local labels (for goto).

local_label_stack

for GCC block local labels (see the __label__ keyword).

sym_push() is used to add a new symbol in the local symbol stack. If no local symbol stack is active, it is added in the global symbol stack.

sym_pop(st,b,keep) pops symbols from the symbol stack st until the symbol b is on the top of stack. If b is NULL, the stack is emptied. The symbols are always made invisible to the parser, but if keep is non zero they are not freed, which is needed as long as the recorded body of an inline function may still refer to them.

sym_find(v) returns the symbol associated to the identifier v. No stack is searched: each TokenSym of table_ident directly holds the innermost visible Sym for its identifier, and sym_pop() restores the previous one. Tags of structures, unions and enums live in their own namespace and are looked up with struct_find(), labels with label_find().

8.6 Sections

The generated code and data are written in sections. The structure Section contains all the necessary information for a given section. new_section() creates a new section. ELF file semantics is assumed for each section.

The following sections are predefined:

text_section

is the section containing the generated code. ind contains the current position in the code section. cur_text_section is the section the code of the current function goes to, which is another section when the function has a section attribute.

data_section

contains initialized data

rodata_section

contains read only data: the literal strings and the objects declared const

bss_section

contains uninitialized data

common_section

receives the tentative definitions when -fcommon is given. Its symbols are SHN_COMMON, with the alignment in the symbol value, and resolve_common_syms() allocates them in bss_section at link time. By default TCC does not use common symbols and puts tentative definitions directly in bss_section

bounds_section
lbounds_section

are used when bound checking is activated

stab_section
stabstr_section

are used when debugging is active and stabs debug information is selected

dwarf_info_section
dwarf_abbrev_section
dwarf_line_section
dwarf_aranges_section
dwarf_str_section
dwarf_line_str_section

are used when debugging is active and dwarf debug information is selected, which is the default on macOS and Android and can be enabled elsewhere with the --config-dwarf option of configure

tcov_section

contains the counters used by -ftest-coverage

symtab_section

contains the symbols and their names (in symtab_section->link). It is needed for linking, not only for debugging.

8.7 Code generation

8.7.1 Introduction

The TCC code generator directly generates linked binary code in one pass. It is rather unusual these days (see gcc for example which generates text assembly), but it can be very fast and surprisingly little complicated.

The TCC code generator is register based. Optimization is only done at the expression level. No intermediate representation of expression is kept except the current values stored in the value stack.

Each target declares the registers the code generator may use in reg_classes[], and NB_REGS gives their number: five on i386 (eax, ecx, edx, ebx, which is only usable when USE_EBX is set, and the top of the x87 stack), 25 on x86-64, 28 on arm64. When more registers are needed, one register is spilled into a new temporary variable on the stack.

8.7.2 The value stack

When an expression is parsed, its value is pushed on the value stack (vstack). The top of the value stack is vtop. Each value stack entry is the structure SValue.

SValue.type is the type. SValue.r indicates how the value is currently stored in the generated code. It is usually a CPU register index (REG_xxx constants), but additional values and flags are defined:

#define VT_VALMASK   0x003f  /* mask for value location, register or: */
#define VT_CONST     0x0030  /* constant in vc */
#define VT_LLOCAL    0x0031  /* lvalue, offset on stack */
#define VT_LOCAL     0x0032  /* offset on stack */
#define VT_CMP       0x0033  /* the value is stored in processor flags */
#define VT_JMP       0x0034  /* value is the consequence of jmp true (even) */
#define VT_JMPI      0x0035  /* value is the consequence of jmp false (odd) */
#define VT_LVAL      0x0100  /* var is an lvalue */
#define VT_SYM       0x0200  /* a symbol value is added */
#define VT_MUSTCAST  0x0C00  /* value must be casted to be correct */
#define VT_NONCONST  0x1000  /* VT_CONST, but not an (C standard) integer
                                constant expression */
#define VT_MUSTBOUND 0x4000  /* bound checking must be done before
                                dereferencing value */
#define VT_BOUNDED   0x8000  /* value is bounded */

SValue.r2 holds the second register when a value needs two of them, as for a long long on a 32 bit target. It is set to VT_CONST when it is not used.

VT_CONST

indicates that the value is a constant. It is stored in the union SValue.c, depending on its type.

VT_LOCAL

indicates a local variable pointer at offset SValue.c.i in the stack.

VT_CMP

indicates that the value is actually stored in the CPU flags (i.e. the value is the consequence of a test). The value is either 0 or 1. The comparison which set the flags is kept in SValue.cmp_op; SValue.cmp_r is left to the code generator, which uses it to remember where the compared values are on the targets that have no flags register.

If any code is generated which destroys the CPU flags, this value MUST be put in a normal register. vcheck_cmp() does it, and the functions which manipulate the value stack call it before generating code.

VT_JMP
VT_JMPI

indicates that the value is the consequence of a conditional jump. For VT_JMP, it is 1 if the jump is taken, 0 otherwise. For VT_JMPI it is inverted.

These values are used to compile the || and && logical operators. The jumps which still have to be resolved are chained in SValue.jtrue and SValue.jfalse; gvtst() adds to these lists and generates the final test.

If any code is generated, this value MUST be put in a normal register. Otherwise, the generated code won’t be executed if the jump is taken.

VT_LVAL

is a flag indicating that the value is actually an lvalue (left value of an assignment). It means that the value stored is actually a pointer to the wanted value.

Understanding the use VT_LVAL is very important if you want to understand how TCC works.

VT_LLOCAL

is a saved lvalue on the stack. VT_LVAL must also be set with VT_LLOCAL. VT_LLOCAL can arise when a VT_LVAL in a register has to be saved to the stack, or it can come from an architecture-specific calling convention.

VT_MUSTCAST

indicates that a cast to the value type must be performed if the value is used (lazy casting), as for a char or a short kept in an integer register. It is a two bit field, so that the width the value has to be casted from (int or long long) is remembered too.

VT_SYM

indicates that the symbol SValue.sym must be added to the constant.

VT_NONCONST

marks a VT_CONST value which only became constant through optimization. Such a value is folded like any other constant, but it is not a constant expression in the sense of the C standard: it is rejected where the language requires one (expr_const64()) and it is not a null pointer constant.

VT_MUSTBOUND
VT_BOUNDED

are only used for optional bound checking.

8.7.3 Manipulating the value stack

vsetc() and vset() pushes a new value on the value stack. If the previous vtop was stored in a very unsafe place(for example in the CPU flags), then some code is generated to put the previous vtop in a safe storage.

vpop() pops vtop. In some cases, it also generates cleanup code (for example if stacked floating point registers are used as on x86).

vdup(), vswap(), vrotb() and vrott() duplicate, exchange and rotate the topmost entries. They all go through vcheck_cmp() first, because a VT_CMP value may only stay on top of the stack.

The gv(rc) function generates code to evaluate vtop (the top value of the stack) into registers. rc selects in which register class the value should be put. gv() is the most important function of the code generator.

gv2() is the same as gv() but for the top two stack entries.

get_reg(rc) returns a free register of the class rc. When they are all busy it spills the one held by the oldest value stack entry, starting from the bottom of the stack so that the registers of the operation being generated are never taken away. The spill itself is done by save_reg(), which copies to the stack every value living in a given register.

8.7.4 CPU dependent code generation

See the i386-gen.c file to have an example.

load()

must generate the code needed to load a stack value into a register.

store()

must generate the code needed to store a register into a stack value lvalue.

gfunc_call(nb_args)

should generate a function call, the arguments and the function address being the nb_args + 1 topmost entries of the value stack. gfunc_sret() tells the parser how a structure return value is passed for the target ABI.

gfunc_prolog()
gfunc_epilog()

should generate a function prolog/epilog.

gen_opi(op)

must generate the binary integer operation op on the two top entries of the stack which are guaranteed to contain integer types.

The result value should be put on the stack.

gen_opf(op)

same as gen_opi() for floating point operations. The two top entries of the stack are guaranteed to contain floating point values of same types.

gen_cvt_itof()

integer to floating point conversion.

gen_cvt_ftoi()

floating point to integer conversion.

gen_cvt_ftof()

floating point to floating point of different size conversion.

gen_cvt_csti()

performs the delayed cast of a char or a short held in an integer register (see VT_MUSTCAST).

gjmp()
gjmp_addr()
gjmp_cond()
gsym_addr()

generate unconditional and conditional jumps, and patch the jumps whose target was not known yet.

gen_vla_alloc()
gen_vla_sp_save()
gen_vla_sp_restore()

allocate a variable length array on the stack, and save and restore the stack pointer around it.

8.8 Optimizations done

Constant propagation is done for all operations. Multiplications and divisions by a power of two are optimized to shifts, and operations which are a no-operation for the given constant (x*1, x-0, x&-1, …) are dropped. Constants added to a symbol or to a local variable address are folded into the address. Comparison operators are optimized by maintaining a special cache for the processor flags. &&, || and ! are optimized by maintaining a special ’jump target’ value. No other jump optimization is currently performed because it would require to store the code in a more abstract fashion.

Concept Index

Jump to:   _  
A   B   C   D   E   F   G   H   I   J   L   M   N   O   P   Q   R   S   T   U   V   W  

_
__asm__Clang
__start_SEClinker
__stop_SEClinker

A
alias attributeClang
align directiveasm
aligned attributeClang
always_inline attributeClang
ascii directiveasm
asciz directiveasm
assemblerasm
assemblerasm
assembler directivesasm
assembly, inlineClang

B
balign directiveasm
binary outputlinker
bound checksBounds
bss directiveasm
byte directiveasm

C
caching processor flagsdevel
cdecl attributeClang
cleanup attributeClang
code generationdevel
COFFlinker
comparison operatorsdevel
constant propagationdevel
constructor attributeClang
CPU dependentdevel

D
data directiveasm
destructor attributeClang
directives, assemblerasm
dllexport attributeClang
dllimport attributeClang

E
ELFlinker
ELF loaderlinker

F
fastcall attributeClang
FILE, linker commandlinker
fill directiveasm
flags, cachingdevel
format attributeClang

G
gasClang
global directiveasm
globl directiveasm
GROUP, linker commandlinker

H
hidden directiveasm

I
inline assemblyClang
int directiveasm

J
jump optimizationdevel

L
linkerlinker
linker scriptslinker
long directiveasm

M
Mach-Olinker
macOSlinker
memory checksBounds
mode attributeClang

N
nodebug attributeClang
nodecorate attributeClang
noreturn attributeClang

O
optimizationsdevel
org directiveasm
OUTPUT_FORMAT, linker commandlinker

P
p2align directiveasm
packed attributeClang
PElinker
PE-i386linker
PE32+linker
popsection directiveasm
previous directiveasm
pushsection directiveasm

Q
quad directiveasm

R
regparm attributeClang

S
scripts, linkerlinker
section attributeClang
section boundary symbolslinker
section directiveasm
set directiveasm
short directiveasm
skip directiveasm
space directiveasm
stdcall attributeClang
strength reductiondevel
string directiveasm

T
TARGET, linker commandlinker
text directiveasm
thiscall attributeClang
type directiveasm

U
unused attributeClang
used attributeClang

V
value stackdevel
value stack, introductiondevel
visibility attributeClang

W
weak attributeClang
weak directiveasm
word directiveasm