1 \input texinfo @c -*- texinfo -*-
3 @settitle Tiny C Compiler Reference Documentation
6 @center @titlefont{Tiny C Compiler Reference Documentation}
12 TinyCC (aka TCC) is a small but hyper fast C compiler. Unlike other C
13 compilers, it is meant to be self-suffisant: you do not need an
14 external assembler or linker because TCC does that for you.
16 TCC compiles so @emph{fast} that even for big projects @code{Makefile}s may
19 TCC not only supports ANSI C, but also most of the new ISO C99
20 standard and many GNUC extensions.
22 TCC can also be used to make @emph{C scripts}, i.e. pieces of C source
23 that you run as a Perl or Python script. Compilation is so fast that
24 your script will be as fast as if it was an executable.
26 TCC can also automatically generate memory and bound checks
27 (@xref{bounds}) while allowing all C pointers operations. TCC can do
28 these checks even if non patched libraries are used.
30 With @code{libtcc}, you can use TCC as a backend for dynamic code
31 generation (@xref{libtcc}).
34 @chapter Command line invocation
39 usage: tcc [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]
40 [-g] [-b] [-Ldir] [-llib] [-shared] [-static]
41 [--] infile1 [infile2... --] [infile_args...]
44 TCC options are a very much like gcc. The main difference is that TCC
45 can also execute directly the resulting program and give it runtime
48 Here are some examples to understand the logic:
52 Compile a.c and execute it directly
55 Compile a.c and execute it directly. arg1 is given as first argument to
56 the @code{main()} of a.c.
58 @item tcc -- a.c b.c -- arg1
59 Compile a.c and b.c, link them together and execute them. arg1 is given
60 as first argument to the @code{main()} of the resulting program. Because
61 multiple C files are specified, @code{--} are necessary to clearly separate the
62 program arguments from the TCC options.
64 @item tcc -o myprog a.c b.c
65 Compile a.c and b.c, link them and generate the executable myprog.
67 @item tcc -o myprog a.o b.o
68 link a.o and b.o together and generate the executable myprog.
71 Compile a.c and generate object file a.o
73 @item tcc -r -o ab.o a.c b.c
74 Compile a.c and b.c, link them together and generate the object file ab.o.
80 TCC can be invoked from @emph{scripts}, just as shell scripts. You just
81 need to add @code{#!/usr/local/bin/tcc} at the start of your C source:
89 printf("Hello World\n");
94 @section Option summary
100 Generate an object file (@samp{-o} option must also be given).
103 Put object file, executable, or dll into output file @file{outfile}.
106 Set the path where the tcc internal libraries can be found (default is
107 @file{PREFIX/lib/tcc}).
110 Output compilation statistics.
113 Preprocessor options:
117 Specify an additionnal include path. Include paths are searched in the
118 order they are specified.
120 System include paths are always searched after. The default system
121 include paths are: @file{/usr/local/include}, @file{/usr/include}
122 and @file{PREFIX/lib/tcc/include}. (@code{PREFIX} is usually
123 @file{/usr} or @file{/usr/local}).
126 Define preprocessor symbol 'sym' to
127 val. If val is not present, its value is '1'. Function-like macros can
128 also be defined: @code{'-DF(a)=a+1'}
131 Undefine preprocessor symbol 'sym'.
138 Generate run time debug information so that you get clear run time
139 error messages: @code{ test.c:68: in function 'test5()': dereferencing
140 invalid pointer} instead of the laconic @code{Segmentation
144 Generate additionnal support code to check
145 memory allocations and array/pointer bounds. '-g' is implied. Note
146 that the generated code is slower and bigger in this case.
153 Specify an additionnal static library path for the @samp{-l} option. The
154 default library paths are @file{/usr/local/lib}, @file{/usr/lib} and @file{/lib}.
157 Link your program with dynamic library libxxx.so or static library
158 libxxx.a. The library is searched in the paths specified by the
162 Generate a shared library instead of an executable (@samp{-o} option
166 Generate a statically linked executable (default is a shared linked
167 executable) (@samp{-o} option must also be given).
170 Generate an object file combining all input files (@samp{-o} option must
175 @chapter C language support
179 TCC implements all the ANSI C standard, including structure bit fields
180 and floating point numbers (@code{long double}, @code{double}, and
181 @code{float} fully supported). The following limitations are known:
184 @item The preprocessor tokens are the same as C. It means that in some
185 rare cases, preprocessed numbers are not handled exactly as in ANSI
186 C. This approach has the advantage of being simpler and FAST!
189 @section ISOC99 extensions
191 TCC implements many features of the new C standard: ISO C99. Currently
192 missing items are: complex and imaginary numbers and variable length
195 Currently implemented ISOC99 features:
199 @item 64 bit @code{'long long'} types are fully supported.
201 @item The boolean type @code{'_Bool'} is supported.
203 @item @code{'__func__'} is a string variable containing the current
206 @item Variadic macros: @code{__VA_ARGS__} can be used for
207 function-like macros:
209 #define dprintf(level, __VA_ARGS__) printf(__VA_ARGS__)
211 @code{dprintf} can then be used with a variable number of parameters.
213 @item Declarations can appear anywhere in a block (as in C++).
215 @item Array and struct/union elements can be initialized in any order by
218 struct { int x, y; } st[10] = { [0].x = 1, [0].y = 2 };
220 int tab[10] = { 1, 2, [5] = 5, [9] = 9};
223 @item Compound initializers are supported:
225 int *p = (int []){ 1, 2, 3 };
227 to initialize a pointer pointing to an initialized array. The same
228 works for structures and strings.
230 @item Hexadecimal floating point constants are supported:
232 double d = 0x1234p10;
234 is the same as writing
236 double d = 4771840.0;
239 @item @code{'inline'} keyword is ignored.
241 @item @code{'restrict'} keyword is ignored.
244 @section GNU C extensions
246 TCC implements some GNU C extensions:
250 @item array designators can be used without '=':
252 int a[10] = { [0] 1, [5] 2, 3, 4 };
255 @item Structure field designators can be a label:
257 struct { int x, y; } st = { x: 1, y: 1};
261 struct { int x, y; } st = { .x = 1, .y = 1};
264 @item @code{'\e'} is ASCII character 27.
266 @item case ranges : ranges can be used in @code{case}s:
270 printf("range 1 to 9\n");
273 printf("unexpected\n");
278 @item The keyword @code{__attribute__} is handled to specify variable or
279 function attributes. The following attributes are supported:
281 @item @code{aligned(n)}: align data to n bytes (must be a power of two).
283 @item @code{section(name)}: generate function or data in assembly
284 section name (name is a string containing the section name) instead
285 of the default section.
287 @item @code{unused}: specify that the variable or the function is unused.
289 @item @code{cdecl}: use standard C calling convention.
291 @item @code{stdcall}: use Pascal-like calling convention.
295 Here are some examples:
297 int a __attribute__ ((aligned(8), section(".mysection")));
300 align variable @code{'a'} to 8 bytes and put it in section @code{.mysection}.
303 int my_add(int a, int b) __attribute__ ((section(".mycodesection")))
309 generate function @code{'my_add'} in section @code{.mycodesection}.
311 @item GNU style variadic macros:
313 #define dprintf(fmt, args...) printf(fmt, ## args)
316 dprintf("one arg %d\n", 1);
319 @item @code{__FUNCTION__} is interpreted as C99 @code{__func__}
320 (so it has not exactly the same semantics as string literal GNUC
321 where it is a string literal).
325 @section TinyCC extensions
329 @item @code{__TINYC__} is a predefined macro to @code{'1'} to
330 indicate that you use TCC.
332 @item @code{'#!'} at the start of a line is ignored to allow scripting.
334 @item Binary digits can be entered (@code{'0b101'} instead of
337 @item @code{__BOUNDS_CHECKING_ON} is defined if bound checking is activated.
341 @chapter TinyCC Linker
343 @section ELF file generation
345 TCC can directly output relocatable ELF files (object files),
346 executable ELF files and dynamic ELF libraries without relying on an
349 Dynamic ELF libraries can be output but the C compiler does not generate
350 position independant code (PIC) code. It means that the dynamic librairy
351 code generated by TCC cannot be factorized among processes yet.
353 TCC linker cannot currently suppress unused object code. But TCC
354 will soon integrate a novel feature not found in GNU tools: unused code
355 will be suppressed at the function or variable level, provided you only
356 use TCC to compile your files.
358 @section ELF file loader
360 TCC can load ELF object files, archives (.a files) and dynamic
363 @section GNU Linker Scripts
365 Because on many Linux systems some dynamic libraries (such as
366 @file{/usr/lib/libc.so}) are in fact GNU ld link scripts (horrible!),
367 TCC linker also support a subset of GNU ld scripts.
369 The @code{GROUP} and @code{FILE} commands are supported.
371 Example from @file{/usr/lib/libc.so}:
374 Use the shared library, but some functions are only in
375 the static library, so try that secondarily. */
376 GROUP ( /lib/libc.so.6 /usr/lib/libc_nonshared.a )
380 @chapter TinyCC Memory and Bound checks
382 This feature is activated with the @code{'-b'} (@xref{invoke}).
384 Note that pointer size is @emph{unchanged} and that code generated
385 with bound checks is @emph{fully compatible} with unchecked
386 code. When a pointer comes from unchecked code, it is assumed to be
387 valid. Even very obscure C code with casts should work correctly.
389 To have more information about the ideas behind this method, check at
390 @url{http://www.doc.ic.ac.uk/~phjk/BoundsChecking.html}.
392 Here are some examples of catched errors:
396 @item Invalid range with standard string function:
404 @item Bound error in global or local arrays:
414 @item Bound error in allocated data:
418 tab = malloc(20 * sizeof(int));
426 @item Access to a freed region:
430 tab = malloc(20 * sizeof(int));
438 @item Freeing an already freed region:
442 tab = malloc(20 * sizeof(int));
451 @chapter The @code{libtcc} library
453 The @code{libtcc} library enables you to use TCC as a backend for
454 dynamic code generation.
456 Read the @file{libtcc.h} to have an overview of the API. Read
457 @file{libtcc_test.c} to have a very simple example.
459 The idea consists in giving a C string containing the program you want
460 to compile directly to @code{libtcc}. Then the @code{main()} function of
461 the compiled string can be launched.
463 @chapter Developper's guide
465 This chapter gives some hints to understand how TCC works. You can skip
466 it if you do not intend to modify the TCC code.
468 @section File reading
470 The @code{BufferedFile} structure contains the context needed to read a
471 file, including the current line number. @code{tcc_open()} opens a new
472 file and @code{tcc_close()} closes it. @code{inp()} returns the next
477 @code{next()} reads the next token in the current
478 file. @code{next_nomacro()} reads the next token without macro
481 @code{tok} contains the current token (see @code{TOK_xxx})
482 constants. Identifiers and keywords are also keywords. @code{tokc}
483 contains additionnal infos about the token (for example a constant value
484 if number or string token).
488 The parser is hardcoded (yacc is not necessary). It does only one pass,
493 @item For initialized arrays with unknown size, a first pass
494 is done to count the number of elements.
496 @item For architectures where arguments are evaluated in
497 reverse order, a first pass is done to reverse the argument order.
503 The types are stored in a single 'int' variable. It was choosen in the
504 first stages of development when tcc was much simpler. Now, it may not
505 be the best solution.
508 #define VT_INT 0 /* integer type */
509 #define VT_BYTE 1 /* signed byte type */
510 #define VT_SHORT 2 /* short type */
511 #define VT_VOID 3 /* void type */
512 #define VT_PTR 4 /* pointer */
513 #define VT_ENUM 5 /* enum definition */
514 #define VT_FUNC 6 /* function type */
515 #define VT_STRUCT 7 /* struct/union definition */
516 #define VT_FLOAT 8 /* IEEE float */
517 #define VT_DOUBLE 9 /* IEEE double */
518 #define VT_LDOUBLE 10 /* IEEE long double */
519 #define VT_BOOL 11 /* ISOC99 boolean type */
520 #define VT_LLONG 12 /* 64 bit integer */
521 #define VT_LONG 13 /* long integer (NEVER USED as type, only
523 #define VT_BTYPE 0x000f /* mask for basic type */
524 #define VT_UNSIGNED 0x0010 /* unsigned type */
525 #define VT_ARRAY 0x0020 /* array type (also has VT_PTR) */
526 #define VT_BITFIELD 0x0040 /* bitfield modifier */
528 #define VT_STRUCT_SHIFT 16 /* structure/enum name shift (16 bits left) */
531 When a reference to another type is needed (for pointers, functions and
532 structures), the @code{32 - VT_STRUCT_SHIFT} high order bits are used to
533 store an identifier reference.
535 The @code{VT_UNSIGNED} flag can be set for chars, shorts, ints and long
538 Arrays are considered as pointers @code{VT_PTR} with the flag
541 The @code{VT_BITFIELD} flag can be set for chars, shorts, ints and long
542 longs. If it is set, then the bitfield position is stored from bits
543 VT_STRUCT_SHIFT to VT_STRUCT_SHIFT + 5 and the bit field size is stored
544 from bits VT_STRUCT_SHIFT + 6 to VT_STRUCT_SHIFT + 11.
546 @code{VT_LONG} is never used except during parsing.
548 During parsing, the storage of an object is also stored in the type
552 #define VT_EXTERN 0x00000080 /* extern definition */
553 #define VT_STATIC 0x00000100 /* static variable */
554 #define VT_TYPEDEF 0x00000200 /* typedef definition */
559 All symbols are stored in hashed symbol stacks. Each symbol stack
560 contains @code{Sym} structures.
562 @code{Sym.v} contains the symbol name (remember
563 an idenfier is also a token, so a string is never necessary to store
564 it). @code{Sym.t} gives the type of the symbol. @code{Sym.r} is usually
565 the register in which the corresponding variable is stored. @code{Sym.c} is
566 usually a constant associated to the symbol.
568 Four main symbol stacks are defined:
573 for the macros (@code{#define}s).
576 for the global variables, functions and types.
579 for the local variables, functions and types.
582 for the local labels (for @code{goto}).
586 @code{sym_push()} is used to add a new symbol in the local symbol
587 stack. If no local symbol stack is active, it is added in the global
590 @code{sym_pop(st,b)} pops symbols from the symbol stack @var{st} until
591 the symbol @var{b} is on the top of stack. If @var{b} is NULL, the stack
594 @code{sym_find(v)} return the symbol associated to the identifier
595 @var{v}. The local stack is searched first from top to bottom, then the
600 The generated code and datas are written in sections. The structure
601 @code{Section} contains all the necessary information for a given
602 section. @code{new_section()} creates a new section. ELF file semantics
603 is assumed for each section.
605 The following sections are predefined:
610 is the section containing the generated code. @var{ind} contains the
611 current position in the code section.
614 contains initialized data
617 contains uninitialized data
620 @itemx lbounds_section
621 are used when bound checking is activated
624 @itemx stabstr_section
625 are used when debugging is actived to store debug information
628 @itemx strtab_section
629 contain the exported symbols (currently only used for debugging).
633 @section Code generation
635 @subsection Introduction
637 The TCC code generator directly generates linked binary code in one
638 pass. It is rather unusual these days (see gcc for example which
639 generates text assembly), but it allows to be very fast and surprisingly
642 The TCC code generator is register based. Optimization is only done at
643 the expression level. No intermediate representation of expression is
644 kept except the current values stored in the @emph{value stack}.
646 On x86, three temporary registers are used. When more registers are
647 needed, one register is flushed in a new local variable.
649 @subsection The value stack
651 When an expression is parsed, its value is pushed on the value stack
652 (@var{vstack}). The top of the value stack is @var{vtop}. Each value
653 stack entry is the structure @code{SValue}.
655 @code{SValue.t} is the type. @code{SValue.r} indicates how the value is
656 currently stored in the generated code. It is usually a CPU register
657 index (@code{REG_xxx} constants), but additionnal values and flags are
661 #define VT_CONST 0x00f0
662 #define VT_LLOCAL 0x00f1
663 #define VT_LOCAL 0x00f2
664 #define VT_CMP 0x00f3
665 #define VT_JMP 0x00f4
666 #define VT_JMPI 0x00f5
667 #define VT_LVAL 0x0100
668 #define VT_SYM 0x0200
669 #define VT_MUSTCAST 0x0400
670 #define VT_MUSTBOUND 0x0800
671 #define VT_BOUNDED 0x8000
672 #define VT_LVAL_BYTE 0x1000
673 #define VT_LVAL_SHORT 0x2000
674 #define VT_LVAL_UNSIGNED 0x4000
675 #define VT_LVAL_TYPE (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
681 indicates that the value is a constant. It is stored in the union
682 @code{SValue.c}, depending on its type.
685 indicates a local variable pointer at offset @code{SValue.c.i} in the
689 indicates that the value is actually stored in the CPU flags (i.e. the
690 value is the consequence of a test). The value is either 0 or 1. The
691 actual CPU flags used is indicated in @code{SValue.c.i}.
693 If any code is generated which destroys the CPU flags, this value MUST be
694 put in a normal register.
698 indicates that the value is the consequence of a jmp. For VT_JMP, it is
699 1 if the jump is taken, 0 otherwise. For VT_JMPI it is inverted.
701 These values are used to compile the @code{||} and @code{&&} logical
704 If any code is generated, this value MUST be put in a normal
705 register. Otherwise, the generated code won't be executed if the jump is
709 is a flag indicating that the value is actually an lvalue (left value of
710 an assignment). It means that the value stored is actually a pointer to
713 Understanding the use @code{VT_LVAL} is very important if you want to
714 understand how TCC works.
718 @itemx VT_LVAL_UNSIGNED
719 if the lvalue has an integer type, then these flags give its real
720 type. The type alone is not suffisant in case of cast optimisations.
723 is a saved lvalue on the stack. @code{VT_LLOCAL} should be suppressed
724 ASAP because its semantics are rather complicated.
727 indicates that a cast to the value type must be performed if the value
728 is used (lazy casting).
731 indicates that the symbol @code{SValue.sym} must be added to the constant.
735 are only used for optional bound checking.
739 @subsection Manipulating the value stack
741 @code{vsetc()} and @code{vset()} pushes a new value on the value
742 stack. If the previous @code{vtop} was stored in a very unsafe place(for
743 example in the CPU flags), then some code is generated to put the
744 previous @code{vtop} in a safe storage.
746 @code{vpop()} pops @code{vtop}. In some cases, it also generates cleanup
747 code (for example if stacked floating point registers are used as on
750 The @code{gv(rc)} function generates code to evaluate @code{vtop} (the
751 top value of the stack) into registers. @var{rc} selects in which
752 register class the value should be put. @code{gv()} is the @emph{most
753 important function} of the code generator.
755 @code{gv2()} is the same as @code{gv()} but for the top two stack
758 @subsection CPU dependent code generation
760 See the @file{i386-gen.c} file to have an example.
765 must generate the code needed to load a stack value into a register.
768 must generate the code needed to store a register into a stack value
774 should generate a function call
777 @itemx gfunc_epilog()
778 should generate a function prolog/epilog.
781 must generate the binary integer operation @var{op} on the two top
782 entries of the stack which are guaranted to contain integer types.
784 The result value should be put on the stack.
787 same as @code{gen_opi()} for floating point operations. The two top
788 entries of the stack are guaranted to contain floating point values of
792 integer to floating point conversion.
795 floating point to integer conversion.
798 floating point to floating point of different size conversion.
800 @item gen_bounded_ptr_add()
801 @item gen_bounded_ptr_deref()
802 are only used for bound checking.
806 @section Optimizations done
808 Constant propagation is done for all operations. Multiplications and
809 divisions are optimized to shifts when appropriate. Comparison
810 operators are optimized by maintaining a special cache for the
811 processor flags. &&, || and ! are optimized by maintaining a special
812 'jump target' value. No other jump optimization is currently performed
813 because it would require to store the code in a more abstract fashion.