- don't use GCC_MAJOR to see if we're not using gcc as GCC_MAJOR might be set
[tinycc.git] / tcc-doc.texi
blob0d6e97074edf90be760583618706990a37685006
1 \input texinfo @c -*- texinfo -*-
2 @c %**start of header
3 @setfilename tcc-doc.info
4 @settitle Tiny C Compiler Reference Documentation
5 @dircategory Software development
6 @direntry
7 * TCC: (tcc-doc).               The Tiny C Compiler.
8 @end direntry
9 @c %**end of header
11 @include config.texi
13 @iftex
14 @titlepage
15 @afourpaper
16 @sp 7
17 @center @titlefont{Tiny C Compiler Reference Documentation}
18 @sp 3
19 @end titlepage
20 @headings double
21 @end iftex
23 @contents
25 @node Top, Introduction, (dir), (dir)
26 @top Tiny C Compiler Reference Documentation
28 This manual documents version @value{VERSION} of the Tiny C Compiler.
30 @menu
31 * Introduction::                Introduction to tcc.
32 * Invoke::                      Invocation of tcc (command line, options).
33 * Clang::                       ANSI C and extensions.
34 * asm::                         Assembler syntax.
35 * linker::                      Output file generation and supported targets.
36 * Bounds::                      Automatic bounds-checking of C code.
37 * Libtcc::                      The libtcc library.
38 * devel::                       Guide for Developers.
39 @end menu
42 @node Introduction
43 @chapter Introduction
45 TinyCC (aka TCC) is a small but hyper fast C compiler. Unlike other C
46 compilers, it is meant to be self-relying: you do not need an
47 external assembler or linker because TCC does that for you.
49 TCC compiles so @emph{fast} that even for big projects @code{Makefile}s may
50 not be necessary.
52 TCC not only supports ANSI C, but also most of the new ISO C99
53 standard and many GNUC extensions including inline assembly.
55 TCC can also be used to make @emph{C scripts}, i.e. pieces of C source
56 that you run as a Perl or Python script. Compilation is so fast that
57 your script will be as fast as if it was an executable.
59 TCC can also automatically generate memory and bound checks
60 (@pxref{Bounds}) while allowing all C pointers operations. TCC can do
61 these checks even if non patched libraries are used.
63 With @code{libtcc}, you can use TCC as a backend for dynamic code
64 generation (@pxref{Libtcc}).
66 TCC mainly supports the i386 target on Linux and Windows. There are alpha
67 ports for the ARM (@code{arm-tcc}) and the TMS320C67xx targets
68 (@code{c67-tcc}). More information about the ARM port is available at
69 @url{http://lists.gnu.org/archive/html/tinycc-devel/2003-10/msg00044.html}.
71 For usage on Windows, see also @url{tcc-win32.txt}.
73 @node Invoke
74 @chapter Command line invocation
76 @section Quick start
78 @example
79 @c man begin SYNOPSIS
80 usage: tcc [options] [@var{infile1} @var{infile2}@dots{}] [@option{-run} @var{infile} @var{args}@dots{}]
81 @c man end
82 @end example
84 @noindent
85 @c man begin DESCRIPTION
86 TCC options are a very much like gcc options. The main difference is that TCC
87 can also execute directly the resulting program and give it runtime
88 arguments.
90 Here are some examples to understand the logic:
92 @table @code
93 @item @samp{tcc -run a.c}
94 Compile @file{a.c} and execute it directly
96 @item @samp{tcc -run a.c arg1}
97 Compile a.c and execute it directly. arg1 is given as first argument to
98 the @code{main()} of a.c.
100 @item @samp{tcc a.c -run b.c arg1}
101 Compile @file{a.c} and @file{b.c}, link them together and execute them. arg1 is given
102 as first argument to the @code{main()} of the resulting program. 
103 @ignore 
104 Because multiple C files are specified, @option{--} are necessary to clearly 
105 separate the program arguments from the TCC options.
106 @end ignore
108 @item @samp{tcc -o myprog a.c b.c}
109 Compile @file{a.c} and @file{b.c}, link them and generate the executable @file{myprog}.
111 @item @samp{tcc -o myprog a.o b.o}
112 link @file{a.o} and @file{b.o} together and generate the executable @file{myprog}.
114 @item @samp{tcc -c a.c}
115 Compile @file{a.c} and generate object file @file{a.o}.
117 @item @samp{tcc -c asmfile.S}
118 Preprocess with C preprocess and assemble @file{asmfile.S} and generate
119 object file @file{asmfile.o}.
121 @item @samp{tcc -c asmfile.s}
122 Assemble (but not preprocess) @file{asmfile.s} and generate object file
123 @file{asmfile.o}.
125 @item @samp{tcc -r -o ab.o a.c b.c}
126 Compile @file{a.c} and @file{b.c}, link them together and generate the object file @file{ab.o}.
128 @end table
130 Scripting:
132 TCC can be invoked from @emph{scripts}, just as shell scripts. You just
133 need to add @code{#!/usr/local/bin/tcc -run} at the start of your C source:
135 @example
136 #!/usr/local/bin/tcc -run
137 #include <stdio.h>
139 int main() 
141     printf("Hello World\n");
142     return 0;
144 @end example
146 TCC can read C source code from @emph{standard input} when @option{-} is used in 
147 place of @option{infile}. Example:
149 @example
150 echo 'main()@{puts("hello");@}' | tcc -run -
151 @end example
152 @c man end
154 @section Option summary
156 General Options:
158 @c man begin OPTIONS
159 @table @option
160 @item -c
161 Generate an object file.
163 @item -o outfile
164 Put object file, executable, or dll into output file @file{outfile}.
166 @item -run source [args...]
167 Compile file @var{source} and run it with the command line arguments
168 @var{args}. In order to be able to give more than one argument to a
169 script, several TCC options can be given @emph{after} the
170 @option{-run} option, separated by spaces:
171 @example
172 tcc "-run -L/usr/X11R6/lib -lX11" ex4.c
173 @end example
174 In a script, it gives the following header:
175 @example
176 #!/usr/local/bin/tcc -run -L/usr/X11R6/lib -lX11
177 @end example
179 @item -v
180 Display TCC version.
182 @item -vv
183 Show included files.  As sole argument, print search dirs (as below).
185 @item -bench
186 Display compilation statistics.
188 @item -print-search-dirs
189 Print the configured installation directory and a list of library
190 and include directories tcc will search.
192 @end table
194 Preprocessor options:
196 @table @option
197 @item -Idir
198 Specify an additional include path. Include paths are searched in the
199 order they are specified.
201 System include paths are always searched after. The default system
202 include paths are: @file{/usr/local/include}, @file{/usr/include}
203 and @file{PREFIX/lib/tcc/include}. (@file{PREFIX} is usually
204 @file{/usr} or @file{/usr/local}).
206 @item -Dsym[=val]
207 Define preprocessor symbol @samp{sym} to
208 val. If val is not present, its value is @samp{1}. Function-like macros can
209 also be defined: @option{-DF(a)=a+1}
211 @item -Usym
212 Undefine preprocessor symbol @samp{sym}.
213 @end table
215 Compilation flags:
217 Note: each of the following warning options has a negative form beginning with
218 @option{-fno-}.
220 @table @option
221 @item -funsigned-char
222 Let the @code{char} type be unsigned.
224 @item -fsigned-char
225 Let the @code{char} type be signed.
227 @item -fno-common
228 Do not generate common symbols for uninitialized data.
230 @item -fleading-underscore
231 Add a leading underscore at the beginning of each C symbol.
233 @end table
235 Warning options:
237 @table @option
238 @item -w
239 Disable all warnings.
241 @end table
243 Note: each of the following warning options has a negative form beginning with
244 @option{-Wno-}.
246 @table @option
247 @item -Wimplicit-function-declaration
248 Warn about implicit function declaration.
250 @item -Wunsupported
251 Warn about unsupported GCC features that are ignored by TCC.
253 @item -Wwrite-strings
254 Make string constants be of type @code{const char *} instead of @code{char
257 @item -Werror
258 Abort compilation if warnings are issued.
260 @item -Wall 
261 Activate all warnings, except @option{-Werror}, @option{-Wunusupported} and
262 @option{-Wwrite-strings}.
264 @end table
266 Linker options:
268 @table @option
269 @item -Ldir
270 Specify an additional static library path for the @option{-l} option. The
271 default library paths are @file{/usr/local/lib}, @file{/usr/lib} and @file{/lib}.
273 @item -lxxx
274 Link your program with dynamic library libxxx.so or static library
275 libxxx.a. The library is searched in the paths specified by the
276 @option{-L} option.
278 @item -Bdir
279 Set the path where the tcc internal libraries (and include files) can be
280 found (default is @file{PREFIX/lib/tcc}).
282 @item -shared
283 Generate a shared library instead of an executable.
285 @item -soname name
286 set name for shared library to be used at runtime
288 @item -static
289 Generate a statically linked executable (default is a shared linked
290 executable).
292 @item -rdynamic
293 Export global symbols to the dynamic linker. It is useful when a library
294 opened with @code{dlopen()} needs to access executable symbols.
296 @item -r
297 Generate an object file combining all input files.
299 @item -Wl,-rpath=path
300 Put custom seatch path for dynamic libraries into executable.
302 @item -Wl,--oformat=fmt
303 Use @var{fmt} as output format. The supported output formats are:
304 @table @code
305 @item elf32-i386
306 ELF output format (default)
307 @item binary
308 Binary image (only for executable output)
309 @item coff
310 COFF output format (only for executable output for TMS320C67xx target)
311 @end table
313 @item -Wl,-subsystem=console/gui/wince/...
314 Set type for PE (Windows) executables.
316 @item -Wl,-[Ttext=# | section-alignment=# | file-alignment=# | image-base=# | stack=#]
317 Modify executable layout.
319 @item -Wl,-Bsymbolic
320 Set DT_SYMBOLIC tag.
322 @end table
324 Debugger options:
326 @table @option
327 @item -g
328 Generate run time debug information so that you get clear run time
329 error messages: @code{ test.c:68: in function 'test5()': dereferencing
330 invalid pointer} instead of the laconic @code{Segmentation
331 fault}.
333 @item -b
334 Generate additional support code to check
335 memory allocations and array/pointer bounds. @option{-g} is implied. Note
336 that the generated code is slower and bigger in this case.
338 Note: @option{-b} is only available on i386 for the moment.
340 @item -bt N
341 Display N callers in stack traces. This is useful with @option{-g} or
342 @option{-b}.
344 @end table
346 Misc options:
348 @table @option
349 @item -MD
350 Generate makefile fragment with dependencies.
352 @item -MF depfile
353 Use @file{depfile} as output for -MD.
355 @end table
357 Note: GCC options @option{-Ox}, @option{-fx} and @option{-mx} are
358 ignored.
359 @c man end
361 @ignore
363 @setfilename tcc
364 @settitle Tiny C Compiler
366 @c man begin SEEALSO
367 gcc(1)
368 @c man end
370 @c man begin AUTHOR
371 Fabrice Bellard
372 @c man end
374 @end ignore
376 @node Clang
377 @chapter C language support
379 @section ANSI C
381 TCC implements all the ANSI C standard, including structure bit fields
382 and floating point numbers (@code{long double}, @code{double}, and
383 @code{float} fully supported).
385 @section ISOC99 extensions
387 TCC implements many features of the new C standard: ISO C99. Currently
388 missing items are: complex and imaginary numbers and variable length
389 arrays.
391 Currently implemented ISOC99 features:
393 @itemize
395 @item 64 bit @code{long long} types are fully supported.
397 @item The boolean type @code{_Bool} is supported.
399 @item @code{__func__} is a string variable containing the current
400 function name.
402 @item Variadic macros: @code{__VA_ARGS__} can be used for
403    function-like macros:
404 @example
405     #define dprintf(level, __VA_ARGS__) printf(__VA_ARGS__)
406 @end example
408 @noindent
409 @code{dprintf} can then be used with a variable number of parameters.
411 @item Declarations can appear anywhere in a block (as in C++).
413 @item Array and struct/union elements can be initialized in any order by
414   using designators:
415 @example
416     struct @{ int x, y; @} st[10] = @{ [0].x = 1, [0].y = 2 @};
418     int tab[10] = @{ 1, 2, [5] = 5, [9] = 9@};
419 @end example
420     
421 @item Compound initializers are supported:
422 @example
423     int *p = (int [])@{ 1, 2, 3 @};
424 @end example
425 to initialize a pointer pointing to an initialized array. The same
426 works for structures and strings.
428 @item Hexadecimal floating point constants are supported:
429 @example
430           double d = 0x1234p10;
431 @end example
433 @noindent
434 is the same as writing 
435 @example
436           double d = 4771840.0;
437 @end example
439 @item @code{inline} keyword is ignored.
441 @item @code{restrict} keyword is ignored.
442 @end itemize
444 @section GNU C extensions
446 TCC implements some GNU C extensions:
448 @itemize
450 @item array designators can be used without '=': 
451 @example
452     int a[10] = @{ [0] 1, [5] 2, 3, 4 @};
453 @end example
455 @item Structure field designators can be a label: 
456 @example
457     struct @{ int x, y; @} st = @{ x: 1, y: 1@};
458 @end example
459 instead of
460 @example
461     struct @{ int x, y; @} st = @{ .x = 1, .y = 1@};
462 @end example
464 @item @code{\e} is ASCII character 27.
466 @item case ranges : ranges can be used in @code{case}s:
467 @example
468     switch(a) @{
469     case 1 @dots{} 9:
470           printf("range 1 to 9\n");
471           break;
472     default:
473           printf("unexpected\n");
474           break;
475     @}
476 @end example
478 @cindex aligned attribute
479 @cindex packed attribute
480 @cindex section attribute
481 @cindex unused attribute
482 @cindex cdecl attribute
483 @cindex stdcall attribute
484 @cindex regparm attribute
485 @cindex dllexport attribute
487 @item The keyword @code{__attribute__} is handled to specify variable or
488 function attributes. The following attributes are supported:
489   @itemize
491   @item @code{aligned(n)}: align a variable or a structure field to n bytes
492 (must be a power of two).
494   @item @code{packed}: force alignment of a variable or a structure field to
495   1.
497   @item @code{section(name)}: generate function or data in assembly section
498 name (name is a string containing the section name) instead of the default
499 section.
501   @item @code{unused}: specify that the variable or the function is unused.
503   @item @code{cdecl}: use standard C calling convention (default).
505   @item @code{stdcall}: use Pascal-like calling convention.
507   @item @code{regparm(n)}: use fast i386 calling convention. @var{n} must be
508 between 1 and 3. The first @var{n} function parameters are respectively put in
509 registers @code{%eax}, @code{%edx} and @code{%ecx}.
511   @item @code{dllexport}: export function from dll/executable (win32 only)
513   @end itemize
515 Here are some examples:
516 @example
517     int a __attribute__ ((aligned(8), section(".mysection")));
518 @end example
520 @noindent
521 align variable @code{a} to 8 bytes and put it in section @code{.mysection}.
523 @example
524     int my_add(int a, int b) __attribute__ ((section(".mycodesection"))) 
525     @{
526         return a + b;
527     @}
528 @end example
530 @noindent
531 generate function @code{my_add} in section @code{.mycodesection}.
533 @item GNU style variadic macros:
534 @example
535     #define dprintf(fmt, args@dots{}) printf(fmt, ## args)
537     dprintf("no arg\n");
538     dprintf("one arg %d\n", 1);
539 @end example
541 @item @code{__FUNCTION__} is interpreted as C99 @code{__func__} 
542 (so it has not exactly the same semantics as string literal GNUC
543 where it is a string literal).
545 @item The @code{__alignof__} keyword can be used as @code{sizeof} 
546 to get the alignment of a type or an expression.
548 @item The @code{typeof(x)} returns the type of @code{x}. 
549 @code{x} is an expression or a type.
551 @item Computed gotos: @code{&&label} returns a pointer of type 
552 @code{void *} on the goto label @code{label}. @code{goto *expr} can be
553 used to jump on the pointer resulting from @code{expr}.
555 @item Inline assembly with asm instruction:
556 @cindex inline assembly
557 @cindex assembly, inline
558 @cindex __asm__
559 @example
560 static inline void * my_memcpy(void * to, const void * from, size_t n)
562 int d0, d1, d2;
563 __asm__ __volatile__(
564         "rep ; movsl\n\t"
565         "testb $2,%b4\n\t"
566         "je 1f\n\t"
567         "movsw\n"
568         "1:\ttestb $1,%b4\n\t"
569         "je 2f\n\t"
570         "movsb\n"
571         "2:"
572         : "=&c" (d0), "=&D" (d1), "=&S" (d2)
573         :"0" (n/4), "q" (n),"1" ((long) to),"2" ((long) from)
574         : "memory");
575 return (to);
577 @end example
579 @noindent
580 @cindex gas
581 TCC includes its own x86 inline assembler with a @code{gas}-like (GNU
582 assembler) syntax. No intermediate files are generated. GCC 3.x named
583 operands are supported.
585 @item @code{__builtin_types_compatible_p()} and @code{__builtin_constant_p()} 
586 are supported.
588 @item @code{#pragma pack} is supported for win32 compatibility.
590 @end itemize
592 @section TinyCC extensions
594 @itemize
596 @item @code{__TINYC__} is a predefined macro to @code{1} to
597 indicate that you use TCC.
599 @item @code{#!} at the start of a line is ignored to allow scripting.
601 @item Binary digits can be entered (@code{0b101} instead of
602 @code{5}).
604 @item @code{__BOUNDS_CHECKING_ON} is defined if bound checking is activated.
606 @end itemize
608 @node asm
609 @chapter TinyCC Assembler
611 Since version 0.9.16, TinyCC integrates its own assembler. TinyCC
612 assembler supports a gas-like syntax (GNU assembler). You can
613 desactivate assembler support if you want a smaller TinyCC executable
614 (the C compiler does not rely on the assembler).
616 TinyCC Assembler is used to handle files with @file{.S} (C
617 preprocessed assembler) and @file{.s} extensions. It is also used to
618 handle the GNU inline assembler with the @code{asm} keyword.
620 @section Syntax
622 TinyCC Assembler supports most of the gas syntax. The tokens are the
623 same as C.
625 @itemize
627 @item C and C++ comments are supported.
629 @item Identifiers are the same as C, so you cannot use '.' or '$'.
631 @item Only 32 bit integer numbers are supported.
633 @end itemize
635 @section Expressions
637 @itemize
639 @item Integers in decimal, octal and hexa are supported.
641 @item Unary operators: +, -, ~.
643 @item Binary operators in decreasing priority order:
645 @enumerate
646 @item *, /, %
647 @item &, |, ^
648 @item +, -
649 @end enumerate
651 @item A value is either an absolute number or a label plus an offset. 
652 All operators accept absolute values except '+' and '-'. '+' or '-' can be
653 used to add an offset to a label. '-' supports two labels only if they
654 are the same or if they are both defined and in the same section.
656 @end itemize
658 @section Labels
660 @itemize
662 @item All labels are considered as local, except undefined ones.
664 @item Numeric labels can be used as local @code{gas}-like labels. 
665 They can be defined several times in the same source. Use 'b'
666 (backward) or 'f' (forward) as suffix to reference them:
668 @example
669  1:
670       jmp 1b /* jump to '1' label before */
671       jmp 1f /* jump to '1' label after */
672  1:
673 @end example
675 @end itemize
677 @section Directives
678 @cindex assembler directives
679 @cindex directives, assembler
680 @cindex align directive
681 @cindex skip directive
682 @cindex space directive
683 @cindex byte directive
684 @cindex word directive
685 @cindex short directive
686 @cindex int directive
687 @cindex long directive
688 @cindex quad directive
689 @cindex globl directive
690 @cindex global directive
691 @cindex section directive
692 @cindex text directive
693 @cindex data directive
694 @cindex bss directive
695 @cindex fill directive
696 @cindex org directive
697 @cindex previous directive
698 @cindex string directive
699 @cindex asciz directive
700 @cindex ascii directive
702 All directives are preceeded by a '.'. The following directives are
703 supported:
705 @itemize
706 @item .align n[,value]
707 @item .skip n[,value]
708 @item .space n[,value]
709 @item .byte value1[,...]
710 @item .word value1[,...]
711 @item .short value1[,...]
712 @item .int value1[,...]
713 @item .long value1[,...]
714 @item .quad immediate_value1[,...]
715 @item .globl symbol
716 @item .global symbol
717 @item .section section
718 @item .text
719 @item .data
720 @item .bss
721 @item .fill repeat[,size[,value]]
722 @item .org n
723 @item .previous
724 @item .string string[,...]
725 @item .asciz string[,...]
726 @item .ascii string[,...]
727 @end itemize
729 @section X86 Assembler
730 @cindex assembler
732 All X86 opcodes are supported. Only ATT syntax is supported (source
733 then destination operand order). If no size suffix is given, TinyCC
734 tries to guess it from the operand sizes.
736 Currently, MMX opcodes are supported but not SSE ones.
738 @node linker
739 @chapter TinyCC Linker
740 @cindex linker
742 @section ELF file generation
743 @cindex ELF
745 TCC can directly output relocatable ELF files (object files),
746 executable ELF files and dynamic ELF libraries without relying on an
747 external linker.
749 Dynamic ELF libraries can be output but the C compiler does not generate
750 position independent code (PIC). It means that the dynamic library
751 code generated by TCC cannot be factorized among processes yet.
753 TCC linker eliminates unreferenced object code in libraries. A single pass is
754 done on the object and library list, so the order in which object files and
755 libraries are specified is important (same constraint as GNU ld). No grouping
756 options (@option{--start-group} and @option{--end-group}) are supported.
758 @section ELF file loader
760 TCC can load ELF object files, archives (.a files) and dynamic
761 libraries (.so).
763 @section PE-i386 file generation
764 @cindex PE-i386
766 TCC for Windows supports the native Win32 executable file format (PE-i386).  It
767 generates EXE files (console and gui) and DLL files.
769 For usage on Windows, see also tcc-win32.txt.
771 @section GNU Linker Scripts
772 @cindex scripts, linker
773 @cindex linker scripts
774 @cindex GROUP, linker command
775 @cindex FILE, linker command
776 @cindex OUTPUT_FORMAT, linker command
777 @cindex TARGET, linker command
779 Because on many Linux systems some dynamic libraries (such as
780 @file{/usr/lib/libc.so}) are in fact GNU ld link scripts (horrible!),
781 the TCC linker also supports a subset of GNU ld scripts.
783 The @code{GROUP} and @code{FILE} commands are supported. @code{OUTPUT_FORMAT}
784 and @code{TARGET} are ignored.
786 Example from @file{/usr/lib/libc.so}:
787 @example
788 /* GNU ld script
789    Use the shared library, but some functions are only in
790    the static library, so try that secondarily.  */
791 GROUP ( /lib/libc.so.6 /usr/lib/libc_nonshared.a )
792 @end example
794 @node Bounds
795 @chapter TinyCC Memory and Bound checks
796 @cindex bound checks
797 @cindex memory checks
799 This feature is activated with the @option{-b} (@pxref{Invoke}).
801 Note that pointer size is @emph{unchanged} and that code generated
802 with bound checks is @emph{fully compatible} with unchecked
803 code. When a pointer comes from unchecked code, it is assumed to be
804 valid. Even very obscure C code with casts should work correctly.
806 For more information about the ideas behind this method, see
807 @url{http://www.doc.ic.ac.uk/~phjk/BoundsChecking.html}.
809 Here are some examples of caught errors:
811 @table @asis
813 @item Invalid range with standard string function:
814 @example
816     char tab[10];
817     memset(tab, 0, 11);
819 @end example
821 @item Out of bounds-error in global or local arrays:
822 @example
824     int tab[10];
825     for(i=0;i<11;i++) @{
826         sum += tab[i];
827     @}
829 @end example
831 @item Out of bounds-error in malloc'ed data:
832 @example
834     int *tab;
835     tab = malloc(20 * sizeof(int));
836     for(i=0;i<21;i++) @{
837         sum += tab4[i];
838     @}
839     free(tab);
841 @end example
843 @item Access of freed memory:
844 @example
846     int *tab;
847     tab = malloc(20 * sizeof(int));
848     free(tab);
849     for(i=0;i<20;i++) @{
850         sum += tab4[i];
851     @}
853 @end example
855 @item Double free:
856 @example
858     int *tab;
859     tab = malloc(20 * sizeof(int));
860     free(tab);
861     free(tab);
863 @end example
865 @end table
867 @node Libtcc
868 @chapter The @code{libtcc} library
870 The @code{libtcc} library enables you to use TCC as a backend for
871 dynamic code generation. 
873 Read the @file{libtcc.h} to have an overview of the API. Read
874 @file{libtcc_test.c} to have a very simple example.
876 The idea consists in giving a C string containing the program you want
877 to compile directly to @code{libtcc}. Then you can access to any global
878 symbol (function or variable) defined.
880 @node devel
881 @chapter Developer's guide
883 This chapter gives some hints to understand how TCC works. You can skip
884 it if you do not intend to modify the TCC code.
886 @section File reading
888 The @code{BufferedFile} structure contains the context needed to read a
889 file, including the current line number. @code{tcc_open()} opens a new
890 file and @code{tcc_close()} closes it. @code{inp()} returns the next
891 character.
893 @section Lexer
895 @code{next()} reads the next token in the current
896 file. @code{next_nomacro()} reads the next token without macro
897 expansion.
899 @code{tok} contains the current token (see @code{TOK_xxx})
900 constants. Identifiers and keywords are also keywords. @code{tokc}
901 contains additional infos about the token (for example a constant value
902 if number or string token).
904 @section Parser
906 The parser is hardcoded (yacc is not necessary). It does only one pass,
907 except:
909 @itemize
911 @item For initialized arrays with unknown size, a first pass 
912 is done to count the number of elements.
914 @item For architectures where arguments are evaluated in 
915 reverse order, a first pass is done to reverse the argument order.
917 @end itemize
919 @section Types
921 The types are stored in a single 'int' variable. It was choosen in the
922 first stages of development when tcc was much simpler. Now, it may not
923 be the best solution.
925 @example
926 #define VT_INT        0  /* integer type */
927 #define VT_BYTE       1  /* signed byte type */
928 #define VT_SHORT      2  /* short type */
929 #define VT_VOID       3  /* void type */
930 #define VT_PTR        4  /* pointer */
931 #define VT_ENUM       5  /* enum definition */
932 #define VT_FUNC       6  /* function type */
933 #define VT_STRUCT     7  /* struct/union definition */
934 #define VT_FLOAT      8  /* IEEE float */
935 #define VT_DOUBLE     9  /* IEEE double */
936 #define VT_LDOUBLE   10  /* IEEE long double */
937 #define VT_BOOL      11  /* ISOC99 boolean type */
938 #define VT_LLONG     12  /* 64 bit integer */
939 #define VT_LONG      13  /* long integer (NEVER USED as type, only
940                             during parsing) */
941 #define VT_BTYPE      0x000f /* mask for basic type */
942 #define VT_UNSIGNED   0x0010  /* unsigned type */
943 #define VT_ARRAY      0x0020  /* array type (also has VT_PTR) */
944 #define VT_VLA        0x20000 /* VLA type (also has VT_PTR and VT_ARRAY) */
945 #define VT_BITFIELD   0x0040  /* bitfield modifier */
946 #define VT_CONSTANT   0x0800  /* const modifier */
947 #define VT_VOLATILE   0x1000  /* volatile modifier */
948 #define VT_SIGNED     0x2000  /* signed type */
950 #define VT_STRUCT_SHIFT 18   /* structure/enum name shift (14 bits left) */
951 @end example
953 When a reference to another type is needed (for pointers, functions and
954 structures), the @code{32 - VT_STRUCT_SHIFT} high order bits are used to
955 store an identifier reference.
957 The @code{VT_UNSIGNED} flag can be set for chars, shorts, ints and long
958 longs.
960 Arrays are considered as pointers @code{VT_PTR} with the flag
961 @code{VT_ARRAY} set. Variable length arrays are considered as special
962 arrays and have flag @code{VT_VLA} set instead of @code{VT_ARRAY}.
964 The @code{VT_BITFIELD} flag can be set for chars, shorts, ints and long
965 longs. If it is set, then the bitfield position is stored from bits
966 VT_STRUCT_SHIFT to VT_STRUCT_SHIFT + 5 and the bit field size is stored
967 from bits VT_STRUCT_SHIFT + 6 to VT_STRUCT_SHIFT + 11.
969 @code{VT_LONG} is never used except during parsing.
971 During parsing, the storage of an object is also stored in the type
972 integer:
974 @example
975 #define VT_EXTERN  0x00000080  /* extern definition */
976 #define VT_STATIC  0x00000100  /* static variable */
977 #define VT_TYPEDEF 0x00000200  /* typedef definition */
978 #define VT_INLINE  0x00000400  /* inline definition */
979 #define VT_IMPORT  0x00004000  /* win32: extern data imported from dll */
980 #define VT_EXPORT  0x00008000  /* win32: data exported from dll */
981 #define VT_WEAK    0x00010000  /* win32: data exported from dll */
982 @end example
984 @section Symbols
986 All symbols are stored in hashed symbol stacks. Each symbol stack
987 contains @code{Sym} structures.
989 @code{Sym.v} contains the symbol name (remember
990 an idenfier is also a token, so a string is never necessary to store
991 it). @code{Sym.t} gives the type of the symbol. @code{Sym.r} is usually
992 the register in which the corresponding variable is stored. @code{Sym.c} is
993 usually a constant associated to the symbol like its address for normal
994 symbols, and the number of entries for symbols representing arrays.
995 Variable length array types use @code{Sym.c} as a location on the stack
996 which holds the runtime sizeof for the type.
998 Four main symbol stacks are defined:
1000 @table @code
1002 @item define_stack
1003 for the macros (@code{#define}s).
1005 @item global_stack
1006 for the global variables, functions and types.
1008 @item local_stack
1009 for the local variables, functions and types.
1011 @item global_label_stack
1012 for the local labels (for @code{goto}).
1014 @item label_stack
1015 for GCC block local labels (see the @code{__label__} keyword).
1017 @end table
1019 @code{sym_push()} is used to add a new symbol in the local symbol
1020 stack. If no local symbol stack is active, it is added in the global
1021 symbol stack.
1023 @code{sym_pop(st,b)} pops symbols from the symbol stack @var{st} until
1024 the symbol @var{b} is on the top of stack. If @var{b} is NULL, the stack
1025 is emptied.
1027 @code{sym_find(v)} return the symbol associated to the identifier
1028 @var{v}. The local stack is searched first from top to bottom, then the
1029 global stack.
1031 @section Sections
1033 The generated code and datas are written in sections. The structure
1034 @code{Section} contains all the necessary information for a given
1035 section. @code{new_section()} creates a new section. ELF file semantics
1036 is assumed for each section.
1038 The following sections are predefined:
1040 @table @code
1042 @item text_section
1043 is the section containing the generated code. @var{ind} contains the
1044 current position in the code section.
1046 @item data_section
1047 contains initialized data
1049 @item bss_section
1050 contains uninitialized data
1052 @item bounds_section
1053 @itemx lbounds_section
1054 are used when bound checking is activated
1056 @item stab_section
1057 @itemx stabstr_section
1058 are used when debugging is actived to store debug information
1060 @item symtab_section
1061 @itemx strtab_section
1062 contain the exported symbols (currently only used for debugging).
1064 @end table
1066 @section Code generation
1067 @cindex code generation
1069 @subsection Introduction
1071 The TCC code generator directly generates linked binary code in one
1072 pass. It is rather unusual these days (see gcc for example which
1073 generates text assembly), but it can be very fast and surprisingly
1074 little complicated.
1076 The TCC code generator is register based. Optimization is only done at
1077 the expression level. No intermediate representation of expression is
1078 kept except the current values stored in the @emph{value stack}.
1080 On x86, three temporary registers are used. When more registers are
1081 needed, one register is spilled into a new temporary variable on the stack.
1083 @subsection The value stack
1084 @cindex value stack, introduction
1086 When an expression is parsed, its value is pushed on the value stack
1087 (@var{vstack}). The top of the value stack is @var{vtop}. Each value
1088 stack entry is the structure @code{SValue}.
1090 @code{SValue.t} is the type. @code{SValue.r} indicates how the value is
1091 currently stored in the generated code. It is usually a CPU register
1092 index (@code{REG_xxx} constants), but additional values and flags are
1093 defined:
1095 @example
1096 #define VT_CONST     0x00f0
1097 #define VT_LLOCAL    0x00f1
1098 #define VT_LOCAL     0x00f2
1099 #define VT_CMP       0x00f3
1100 #define VT_JMP       0x00f4
1101 #define VT_JMPI      0x00f5
1102 #define VT_LVAL      0x0100
1103 #define VT_SYM       0x0200
1104 #define VT_MUSTCAST  0x0400
1105 #define VT_MUSTBOUND 0x0800
1106 #define VT_BOUNDED   0x8000
1107 #define VT_LVAL_BYTE     0x1000
1108 #define VT_LVAL_SHORT    0x2000
1109 #define VT_LVAL_UNSIGNED 0x4000
1110 #define VT_LVAL_TYPE     (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
1111 @end example
1113 @table @code
1115 @item VT_CONST
1116 indicates that the value is a constant. It is stored in the union
1117 @code{SValue.c}, depending on its type.
1119 @item VT_LOCAL
1120 indicates a local variable pointer at offset @code{SValue.c.i} in the
1121 stack.
1123 @item VT_CMP
1124 indicates that the value is actually stored in the CPU flags (i.e. the
1125 value is the consequence of a test). The value is either 0 or 1. The
1126 actual CPU flags used is indicated in @code{SValue.c.i}. 
1128 If any code is generated which destroys the CPU flags, this value MUST be
1129 put in a normal register.
1131 @item VT_JMP
1132 @itemx VT_JMPI
1133 indicates that the value is the consequence of a conditional jump. For VT_JMP,
1134 it is 1 if the jump is taken, 0 otherwise. For VT_JMPI it is inverted.
1136 These values are used to compile the @code{||} and @code{&&} logical
1137 operators.
1139 If any code is generated, this value MUST be put in a normal
1140 register. Otherwise, the generated code won't be executed if the jump is
1141 taken.
1143 @item VT_LVAL
1144 is a flag indicating that the value is actually an lvalue (left value of
1145 an assignment). It means that the value stored is actually a pointer to
1146 the wanted value. 
1148 Understanding the use @code{VT_LVAL} is very important if you want to
1149 understand how TCC works.
1151 @item VT_LVAL_BYTE
1152 @itemx VT_LVAL_SHORT
1153 @itemx VT_LVAL_UNSIGNED
1154 if the lvalue has an integer type, then these flags give its real
1155 type. The type alone is not enough in case of cast optimisations.
1157 @item VT_LLOCAL
1158 is a saved lvalue on the stack. @code{VT_LLOCAL} should be eliminated
1159 ASAP because its semantics are rather complicated.
1161 @item VT_MUSTCAST
1162 indicates that a cast to the value type must be performed if the value
1163 is used (lazy casting).
1165 @item VT_SYM
1166 indicates that the symbol @code{SValue.sym} must be added to the constant.
1168 @item VT_MUSTBOUND
1169 @itemx VT_BOUNDED
1170 are only used for optional bound checking.
1172 @end table
1174 @subsection Manipulating the value stack
1175 @cindex value stack
1177 @code{vsetc()} and @code{vset()} pushes a new value on the value
1178 stack. If the previous @var{vtop} was stored in a very unsafe place(for
1179 example in the CPU flags), then some code is generated to put the
1180 previous @var{vtop} in a safe storage.
1182 @code{vpop()} pops @var{vtop}. In some cases, it also generates cleanup
1183 code (for example if stacked floating point registers are used as on
1184 x86).
1186 The @code{gv(rc)} function generates code to evaluate @var{vtop} (the
1187 top value of the stack) into registers. @var{rc} selects in which
1188 register class the value should be put. @code{gv()} is the @emph{most
1189 important function} of the code generator.
1191 @code{gv2()} is the same as @code{gv()} but for the top two stack
1192 entries.
1194 @subsection CPU dependent code generation
1195 @cindex CPU dependent
1196 See the @file{i386-gen.c} file to have an example.
1198 @table @code
1200 @item load()
1201 must generate the code needed to load a stack value into a register.
1203 @item store()
1204 must generate the code needed to store a register into a stack value
1205 lvalue.
1207 @item gfunc_start()
1208 @itemx gfunc_param()
1209 @itemx gfunc_call()
1210 should generate a function call
1212 @item gfunc_prolog()
1213 @itemx gfunc_epilog()
1214 should generate a function prolog/epilog.
1216 @item gen_opi(op)
1217 must generate the binary integer operation @var{op} on the two top
1218 entries of the stack which are guaranted to contain integer types.
1220 The result value should be put on the stack.
1222 @item gen_opf(op)
1223 same as @code{gen_opi()} for floating point operations. The two top
1224 entries of the stack are guaranted to contain floating point values of
1225 same types.
1227 @item gen_cvt_itof()
1228 integer to floating point conversion.
1230 @item gen_cvt_ftoi()
1231 floating point to integer conversion.
1233 @item gen_cvt_ftof()
1234 floating point to floating point of different size conversion.
1236 @item gen_bounded_ptr_add()
1237 @item gen_bounded_ptr_deref()
1238 are only used for bounds checking.
1240 @end table
1242 @section Optimizations done
1243 @cindex optimizations
1244 @cindex constant propagation
1245 @cindex strength reduction
1246 @cindex comparison operators
1247 @cindex caching processor flags
1248 @cindex flags, caching
1249 @cindex jump optimization
1250 Constant propagation is done for all operations. Multiplications and
1251 divisions are optimized to shifts when appropriate. Comparison
1252 operators are optimized by maintaining a special cache for the
1253 processor flags. &&, || and ! are optimized by maintaining a special
1254 'jump target' value. No other jump optimization is currently performed
1255 because it would require to store the code in a more abstract fashion.
1257 @unnumbered Concept Index
1258 @printindex cp
1260 @bye
1262 @c Local variables:
1263 @c fill-column: 78
1264 @c texinfo-column-for-description: 32
1265 @c End: