automatic man page generation from tcc-doc.texi
[tinycc.git] / tcc-doc.texi
blob830f40b2b97fb1c407a234759fe46aee63d0aeca
1 \input texinfo @c -*- texinfo -*-
2 @c %**start of header
3 @setfilename tcc-doc.info
4 @settitle Tiny C Compiler Reference Documentation
5 @c %**end of header
7 @include config.texi
9 @iftex
10 @titlepage
11 @afourpaper
12 @sp 7
13 @center @titlefont{Tiny C Compiler Reference Documentation}
14 @sp 3
15 @end titlepage
16 @headings double
17 @end iftex
19 @c @ifhtml
20 @contents
21 @c @end ifhtml
23 @ifnothtml
24 @node Top, Introduction, (dir), (dir)
25 @top Tiny C Compiler Reference Documentation
27 This manual documents version @value{VERSION} of the Tiny C Compiler.
29 @menu
30 * Introduction::                Introduction to tcc.
31 * Invoke::                      Invocation of tcc (command line, options).
32 * Bounds::                      Automatic bounds-checking of C code.
33 * Libtcc::                      The libtcc library.
34 @end menu
35 @end ifnothtml
37 @node Introduction
38 @chapter Introduction
40 TinyCC (aka TCC) is a small but hyper fast C compiler. Unlike other C
41 compilers, it is meant to be self-relying: you do not need an
42 external assembler or linker because TCC does that for you.
44 TCC compiles so @emph{fast} that even for big projects @code{Makefile}s may
45 not be necessary. 
47 TCC not only supports ANSI C, but also most of the new ISO C99
48 standard and many GNUC extensions including inline assembly.
50 TCC can also be used to make @emph{C scripts}, i.e. pieces of C source
51 that you run as a Perl or Python script. Compilation is so fast that
52 your script will be as fast as if it was an executable.
54 TCC can also automatically generate memory and bound checks
55 (@pxref{Bounds}) while allowing all C pointers operations. TCC can do
56 these checks even if non patched libraries are used.
58 With @code{libtcc}, you can use TCC as a backend for dynamic code
59 generation (@pxref{Libtcc}).
61 @node Invoke
62 @chapter Command line invocation
64 [This manual documents version @value{VERSION} of the Tiny C Compiler]
66 @section Quick start
68 @example
69 @c man begin SYNOPSIS
70 usage: tcc [@option{-v}] [@option{-c}] [@option{-o}@var{outfile}] [@option{-B}@var{dir}] [@option{-bench}] [@option{-I}@var{dir}] [@option{-D}@var{sym[=val]}] [@option{-U}@var{sym}]
71            [@option{-g}] [@option{-b}] [@option{-bt}@var{N}] [@option{-L}@var{dir}] [@option{-l}@var{lib}] [@option{-shared}] [@option{-static}]
72            [@var{infile1} @var{infile2}@dots{}] [@option{run} @var{infile} @var{args}@dots{}]
73 @c man end
74 @end example
76 @noindent
77 @c man begin DESCRIPTION
78 TCC options are a very much like gcc options. The main difference is that TCC
79 can also execute directly the resulting program and give it runtime
80 arguments.
82 Here are some examples to understand the logic:
84 @table @code
85 @item @samp{tcc -run a.c}
86 Compile @file{a.c} and execute it directly
88 @item @samp{tcc -run a.c arg1}
89 Compile a.c and execute it directly. arg1 is given as first argument to
90 the @code{main()} of a.c.
92 @item @samp{tcc a.c -run b.c arg1}
93 Compile @file{a.c} and @file{b.c}, link them together and execute them. arg1 is given
94 as first argument to the @code{main()} of the resulting program. Because
95 multiple C files are specified, @option{--} are necessary to clearly separate the
96 program arguments from the TCC options.
98 @item @samp{tcc -o myprog a.c b.c}
99 Compile @file{a.c} and @file{b.c}, link them and generate the executable @file{myprog}.
101 @item @samp{tcc -o myprog a.o b.o}
102 link @file{a.o} and @file{b.o} together and generate the executable @file{myprog}.
104 @item @samp{tcc -c a.c}
105 Compile @file{a.c} and generate object file @file{a.o}.
107 @item @samp{tcc -c asmfile.S}
108 Preprocess with C preprocess and assemble @file{asmfile.S} and generate
109 object file @file{asmfile.o}.
111 @item @samp{tcc -c asmfile.s}
112 Assemble (but not preprocess) @file{asmfile.s} and generate object file
113 @file{asmfile.o}.
115 @item @samp{tcc -r -o ab.o a.c b.c}
116 Compile @file{a.c} and @file{b.c}, link them together and generate the object file @file{ab.o}.
118 @end table
120 Scripting:
122 TCC can be invoked from @emph{scripts}, just as shell scripts. You just
123 need to add @code{#!/usr/local/bin/tcc -run} at the start of your C source:
125 @example
126 #!/usr/local/bin/tcc -run
127 #include <stdio.h>
129 int main() 
131     printf("Hello World\n");
132     return 0;
134 @end example
135 @c man end
137 @section Option summary
139 General Options:
141 @c man begin OPTIONS
142 @table @option
143 @item -v
144 Display current TCC version.
146 @item -c
147 Generate an object file (@option{-o} option must also be given).
149 @item -o outfile
150 Put object file, executable, or dll into output file @file{outfile}.
152 @item -Bdir
153 Set the path where the tcc internal libraries can be found (default is
154 @file{PREFIX/lib/tcc}).
156 @item -bench
157 Output compilation statistics.
159 @item -run
160 Run compiled source.
161 @end table
163 Preprocessor options:
165 @table @option
166 @item -Idir
167 Specify an additional include path. Include paths are searched in the
168 order they are specified.
170 System include paths are always searched after. The default system
171 include paths are: @file{/usr/local/include}, @file{/usr/include}
172 and @file{PREFIX/lib/tcc/include}. (@file{PREFIX} is usually
173 @file{/usr} or @file{/usr/local}).
175 @item -Dsym[=val]
176 Define preprocessor symbol @samp{sym} to
177 val. If val is not present, its value is @samp{1}. Function-like macros can
178 also be defined: @option{-DF(a)=a+1}
180 @item -Usym
181 Undefine preprocessor symbol @samp{sym}.
182 @end table
184 Linker options:
186 @table @option
187 @item -Ldir
188 Specify an additional static library path for the @option{-l} option. The
189 default library paths are @file{/usr/local/lib}, @file{/usr/lib} and @file{/lib}.
191 @item -lxxx
192 Link your program with dynamic library libxxx.so or static library
193 libxxx.a. The library is searched in the paths specified by the
194 @option{-L} option.
196 @item -shared
197 Generate a shared library instead of an executable (@option{-o} option
198 must also be given).
200 @item -static
201 Generate a statically linked executable (default is a shared linked
202 executable) (@option{-o} option must also be given).
204 @item -r
205 Generate an object file combining all input files (@option{-o} option must
206 also be given).
208 @end table
210 Debugger options:
212 @table @option
213 @item -g
214 Generate run time debug information so that you get clear run time
215 error messages: @code{ test.c:68: in function 'test5()': dereferencing
216 invalid pointer} instead of the laconic @code{Segmentation
217 fault}.
219 @item -b
220 Generate additional support code to check
221 memory allocations and array/pointer bounds. @option{-g} is implied. Note
222 that the generated code is slower and bigger in this case.
224 @item -bt N
225 Display N callers in stack traces. This is useful with @option{-g} or
226 @option{-b}.
228 @end table
230 Note: GCC options @option{-Ox}, @option{-Wx}, @option{-fx} and @option{-mx} are
231 ignored.
232 @c man end
234 @ignore
236 @setfilename tcc
237 @settitle Tiny C Compiler
239 @c man begin SEEALSO
240 gcc(1)
241 @c man end
243 @c man begin AUTHOR
244 Fabrice Bellard
245 @c man end
247 @end ignore
249 @chapter C language support
251 @section ANSI C
253 TCC implements all the ANSI C standard, including structure bit fields
254 and floating point numbers (@code{long double}, @code{double}, and
255 @code{float} fully supported).
257 @section ISOC99 extensions
259 TCC implements many features of the new C standard: ISO C99. Currently
260 missing items are: complex and imaginary numbers and variable length
261 arrays.
263 Currently implemented ISOC99 features:
265 @itemize
267 @item 64 bit @code{long long} types are fully supported.
269 @item The boolean type @code{_Bool} is supported.
271 @item @code{__func__} is a string variable containing the current
272 function name.
274 @item Variadic macros: @code{__VA_ARGS__} can be used for
275    function-like macros:
276 @example
277     #define dprintf(level, __VA_ARGS__) printf(__VA_ARGS__)
278 @end example
280 @noindent
281 @code{dprintf} can then be used with a variable number of parameters.
283 @item Declarations can appear anywhere in a block (as in C++).
285 @item Array and struct/union elements can be initialized in any order by
286   using designators:
287 @example
288     struct @{ int x, y; @} st[10] = @{ [0].x = 1, [0].y = 2 @};
290     int tab[10] = @{ 1, 2, [5] = 5, [9] = 9@};
291 @end example
292     
293 @item Compound initializers are supported:
294 @example
295     int *p = (int [])@{ 1, 2, 3 @};
296 @end example
297 to initialize a pointer pointing to an initialized array. The same
298 works for structures and strings.
300 @item Hexadecimal floating point constants are supported:
301 @example
302           double d = 0x1234p10;
303 @end example
305 @noindent
306 is the same as writing 
307 @example
308           double d = 4771840.0;
309 @end example
311 @item @code{inline} keyword is ignored.
313 @item @code{restrict} keyword is ignored.
314 @end itemize
316 @section GNU C extensions
318 TCC implements some GNU C extensions:
320 @itemize
322 @item array designators can be used without '=': 
323 @example
324     int a[10] = @{ [0] 1, [5] 2, 3, 4 @};
325 @end example
327 @item Structure field designators can be a label: 
328 @example
329     struct @{ int x, y; @} st = @{ x: 1, y: 1@};
330 @end example
331 instead of
332 @example
333     struct @{ int x, y; @} st = @{ .x = 1, .y = 1@};
334 @end example
336 @item @code{\e} is ASCII character 27.
338 @item case ranges : ranges can be used in @code{case}s:
339 @example
340     switch(a) @{
341     case 1 @dots{} 9:
342           printf("range 1 to 9\n");
343           break;
344     default:
345           printf("unexpected\n");
346           break;
347     @}
348 @end example
350 @item The keyword @code{__attribute__} is handled to specify variable or
351 function attributes. The following attributes are supported:
352   @itemize
353   @item @code{aligned(n)}: align data to n bytes (must be a power of two).
355   @item @code{section(name)}: generate function or data in assembly
356   section name (name is a string containing the section name) instead
357   of the default section.
359   @item @code{unused}: specify that the variable or the function is unused.
361   @item @code{cdecl}: use standard C calling convention.
363   @item @code{stdcall}: use Pascal-like calling convention.
365   @end itemize
367 Here are some examples:
368 @example
369     int a __attribute__ ((aligned(8), section(".mysection")));
370 @end example
372 @noindent
373 align variable @code{a} to 8 bytes and put it in section @code{.mysection}.
375 @example
376     int my_add(int a, int b) __attribute__ ((section(".mycodesection"))) 
377     @{
378         return a + b;
379     @}
380 @end example
382 @noindent
383 generate function @code{my_add} in section @code{.mycodesection}.
385 @item GNU style variadic macros:
386 @example
387     #define dprintf(fmt, args@dots{}) printf(fmt, ## args)
389     dprintf("no arg\n");
390     dprintf("one arg %d\n", 1);
391 @end example
393 @item @code{__FUNCTION__} is interpreted as C99 @code{__func__} 
394 (so it has not exactly the same semantics as string literal GNUC
395 where it is a string literal).
397 @item The @code{__alignof__} keyword can be used as @code{sizeof} 
398 to get the alignment of a type or an expression.
400 @item The @code{typeof(x)} returns the type of @code{x}. 
401 @code{x} is an expression or a type.
403 @item Computed gotos: @code{&&label} returns a pointer of type 
404 @code{void *} on the goto label @code{label}. @code{goto *expr} can be
405 used to jump on the pointer resulting from @code{expr}.
407 @item Inline assembly with asm instruction:
408 @cindex inline assembly
409 @cindex assembly, inline
410 @cindex __asm__
411 @example
412 static inline void * my_memcpy(void * to, const void * from, size_t n)
414 int d0, d1, d2;
415 __asm__ __volatile__(
416         "rep ; movsl\n\t"
417         "testb $2,%b4\n\t"
418         "je 1f\n\t"
419         "movsw\n"
420         "1:\ttestb $1,%b4\n\t"
421         "je 2f\n\t"
422         "movsb\n"
423         "2:"
424         : "=&c" (d0), "=&D" (d1), "=&S" (d2)
425         :"0" (n/4), "q" (n),"1" ((long) to),"2" ((long) from)
426         : "memory");
427 return (to);
429 @end example
431 @noindent
432 @cindex gas
433 TCC includes its own x86 inline assembler with a @code{gas}-like (GNU
434 assembler) syntax. No intermediate files are generated. GCC 3.x named
435 operands are supported.
437 @end itemize
439 @section TinyCC extensions
441 @itemize
443 @item @code{__TINYC__} is a predefined macro to @code{1} to
444 indicate that you use TCC.
446 @item @code{#!} at the start of a line is ignored to allow scripting.
448 @item Binary digits can be entered (@code{0b101} instead of
449 @code{5}).
451 @item @code{__BOUNDS_CHECKING_ON} is defined if bound checking is activated.
453 @end itemize
455 @chapter TinyCC Assembler
457 Since version 0.9.16, TinyCC integrates its own assembler. TinyCC
458 assembler supports a gas-like syntax (GNU assembler). You can
459 desactivate assembler support if you want a smaller TinyCC executable
460 (the C compiler does not rely on the assembler).
462 TinyCC Assembler is used to handle files with @file{.S} (C
463 preprocessed assembler) and @file{.s} extensions. It is also used to
464 handle the GNU inline assembler with the @code{asm} keyword.
466 @section Syntax
468 TinyCC Assembler supports most of the gas syntax. The tokens are the
469 same as C.
471 @itemize
473 @item C and C++ comments are supported.
475 @item Identifiers are the same as C, so you cannot use '.' or '$'.
477 @item Only 32 bit integer numbers are supported.
479 @end itemize
481 @section Expressions
483 @itemize
485 @item Integers in decimal, octal and hexa are supported.
487 @item Unary operators: +, -, ~.
489 @item Binary operators in decreasing priority order:
491 @enumerate
492 @item *, /, %
493 @item &, |, ^
494 @item +, -
495 @end enumerate
497 @item A value is either an absolute number or a label plus an offset. 
498 All operators accept absolute values except '+' and '-'. '+' or '-' can be
499 used to add an offset to a label. '-' supports two labels only if they
500 are the same or if they are both defined and in the same section.
502 @end itemize
504 @section Labels
506 @itemize
508 @item All labels are considered as local, except undefined ones.
510 @item Numeric labels can be used as local @code{gas}-like labels. 
511 They can be defined several times in the same source. Use 'b'
512 (backward) or 'f' (forward) as suffix to reference them:
514 @example
515  1:
516       jmp 1b /* jump to '1' label before */
517       jmp 1f /* jump to '1' label after */
518  1:
519 @end example
521 @end itemize
523 @section Directives
524 @cindex assembler directives
525 @cindex directives, assembler
526 @cindex .align
527 @cindex .skip
528 @cindex .space
529 @cindex .byte
530 @cindex .word
531 @cindex .short
532 @cindex .int
533 @cindex .long
535 All directives are preceeded by a '.'. The following directives are
536 supported:
538 @itemize
539 @item .align n[,value]
540 @item .skip n[,value]
541 @item .space n[,value]
542 @item .byte value1[,value2...]
543 @item .word value1[,value2...]
544 @item .short value1[,value2...]
545 @item .int value1[,value2...]
546 @item .long value1[,value2...]
547 @end itemize
549 @section X86 Assembler
550 @cindex assembler
552 All X86 opcodes are supported. Only ATT syntax is supported (source
553 then destination operand order). If no size suffix is given, TinyCC
554 tries to guess it from the operand sizes.
556 Currently, MMX opcodes are supported but not SSE ones.
558 @chapter TinyCC Linker
559 @cindex linker
561 @section ELF file generation
562 @cindex ELF
564 TCC can directly output relocatable ELF files (object files),
565 executable ELF files and dynamic ELF libraries without relying on an
566 external linker.
568 Dynamic ELF libraries can be output but the C compiler does not generate
569 position independent code (PIC). It means that the dynamic librairy
570 code generated by TCC cannot be factorized among processes yet.
572 TCC linker cannot currently eliminate unused object code. But TCC
573 will soon integrate a novel feature not found in GNU tools: unused code
574 will be eliminated at the function or variable level, provided you only
575 use TCC to compile your files.
577 @section ELF file loader
579 TCC can load ELF object files, archives (.a files) and dynamic
580 libraries (.so).
582 @section GNU Linker Scripts
583 @cindex scripts, linker
584 @cindex linker scripts
585 @cindex GROUP, linker command
586 @cindex FILE, linker command
588 Because on many Linux systems some dynamic libraries (such as
589 @file{/usr/lib/libc.so}) are in fact GNU ld link scripts (horrible!),
590 the TCC linker also supports a subset of GNU ld scripts.
592 The @code{GROUP} and @code{FILE} commands are supported.
594 Example from @file{/usr/lib/libc.so}:
595 @example
596 /* GNU ld script
597    Use the shared library, but some functions are only in
598    the static library, so try that secondarily.  */
599 GROUP ( /lib/libc.so.6 /usr/lib/libc_nonshared.a )
600 @end example
602 @node Bounds
603 @chapter TinyCC Memory and Bound checks
604 @cindex bound checks
605 @cindex memory checks
607 This feature is activated with the @option{-b} (@pxref{Invoke}).
609 Note that pointer size is @emph{unchanged} and that code generated
610 with bound checks is @emph{fully compatible} with unchecked
611 code. When a pointer comes from unchecked code, it is assumed to be
612 valid. Even very obscure C code with casts should work correctly.
614 For more information about the ideas behind this method, see
615 @url{http://www.doc.ic.ac.uk/~phjk/BoundsChecking.html}.
617 Here are some examples of caught errors:
619 @table @asis
621 @item Invalid range with standard string function:
622 @example
624     char tab[10];
625     memset(tab, 0, 11);
627 @end example
629 @item Out of bounds-error in global or local arrays:
630 @example
632     int tab[10];
633     for(i=0;i<11;i++) @{
634         sum += tab[i];
635     @}
637 @end example
639 @item Out of bounds-error in malloc'ed data:
640 @example
642     int *tab;
643     tab = malloc(20 * sizeof(int));
644     for(i=0;i<21;i++) @{
645         sum += tab4[i];
646     @}
647     free(tab);
649 @end example
651 @item Access of freed memory:
652 @example
654     int *tab;
655     tab = malloc(20 * sizeof(int));
656     free(tab);
657     for(i=0;i<20;i++) @{
658         sum += tab4[i];
659     @}
661 @end example
663 @item Double free:
664 @example
666     int *tab;
667     tab = malloc(20 * sizeof(int));
668     free(tab);
669     free(tab);
671 @end example
673 @end table
675 @node Libtcc
676 @chapter The @code{libtcc} library
678 The @code{libtcc} library enables you to use TCC as a backend for
679 dynamic code generation. 
681 Read the @file{libtcc.h} to have an overview of the API. Read
682 @file{libtcc_test.c} to have a very simple example.
684 The idea consists in giving a C string containing the program you want
685 to compile directly to @code{libtcc}. Then you can access to any global
686 symbol (function or variable) defined.
688 @chapter Developer's guide
690 This chapter gives some hints to understand how TCC works. You can skip
691 it if you do not intend to modify the TCC code.
693 @section File reading
695 The @code{BufferedFile} structure contains the context needed to read a
696 file, including the current line number. @code{tcc_open()} opens a new
697 file and @code{tcc_close()} closes it. @code{inp()} returns the next
698 character.
700 @section Lexer
702 @code{next()} reads the next token in the current
703 file. @code{next_nomacro()} reads the next token without macro
704 expansion.
706 @code{tok} contains the current token (see @code{TOK_xxx})
707 constants. Identifiers and keywords are also keywords. @code{tokc}
708 contains additional infos about the token (for example a constant value
709 if number or string token).
711 @section Parser
713 The parser is hardcoded (yacc is not necessary). It does only one pass,
714 except:
716 @itemize
718 @item For initialized arrays with unknown size, a first pass 
719 is done to count the number of elements.
721 @item For architectures where arguments are evaluated in 
722 reverse order, a first pass is done to reverse the argument order.
724 @end itemize
726 @section Types
728 The types are stored in a single 'int' variable. It was choosen in the
729 first stages of development when tcc was much simpler. Now, it may not
730 be the best solution.
732 @example
733 #define VT_INT        0  /* integer type */
734 #define VT_BYTE       1  /* signed byte type */
735 #define VT_SHORT      2  /* short type */
736 #define VT_VOID       3  /* void type */
737 #define VT_PTR        4  /* pointer */
738 #define VT_ENUM       5  /* enum definition */
739 #define VT_FUNC       6  /* function type */
740 #define VT_STRUCT     7  /* struct/union definition */
741 #define VT_FLOAT      8  /* IEEE float */
742 #define VT_DOUBLE     9  /* IEEE double */
743 #define VT_LDOUBLE   10  /* IEEE long double */
744 #define VT_BOOL      11  /* ISOC99 boolean type */
745 #define VT_LLONG     12  /* 64 bit integer */
746 #define VT_LONG      13  /* long integer (NEVER USED as type, only
747                             during parsing) */
748 #define VT_BTYPE      0x000f /* mask for basic type */
749 #define VT_UNSIGNED   0x0010  /* unsigned type */
750 #define VT_ARRAY      0x0020  /* array type (also has VT_PTR) */
751 #define VT_BITFIELD   0x0040  /* bitfield modifier */
753 #define VT_STRUCT_SHIFT 16   /* structure/enum name shift (16 bits left) */
754 @end example
756 When a reference to another type is needed (for pointers, functions and
757 structures), the @code{32 - VT_STRUCT_SHIFT} high order bits are used to
758 store an identifier reference.
760 The @code{VT_UNSIGNED} flag can be set for chars, shorts, ints and long
761 longs.
763 Arrays are considered as pointers @code{VT_PTR} with the flag
764 @code{VT_ARRAY} set.
766 The @code{VT_BITFIELD} flag can be set for chars, shorts, ints and long
767 longs. If it is set, then the bitfield position is stored from bits
768 VT_STRUCT_SHIFT to VT_STRUCT_SHIFT + 5 and the bit field size is stored
769 from bits VT_STRUCT_SHIFT + 6 to VT_STRUCT_SHIFT + 11.
771 @code{VT_LONG} is never used except during parsing.
773 During parsing, the storage of an object is also stored in the type
774 integer:
776 @example
777 #define VT_EXTERN  0x00000080  /* extern definition */
778 #define VT_STATIC  0x00000100  /* static variable */
779 #define VT_TYPEDEF 0x00000200  /* typedef definition */
780 @end example
782 @section Symbols
784 All symbols are stored in hashed symbol stacks. Each symbol stack
785 contains @code{Sym} structures.
787 @code{Sym.v} contains the symbol name (remember
788 an idenfier is also a token, so a string is never necessary to store
789 it). @code{Sym.t} gives the type of the symbol. @code{Sym.r} is usually
790 the register in which the corresponding variable is stored. @code{Sym.c} is
791 usually a constant associated to the symbol.
793 Four main symbol stacks are defined:
795 @table @code
797 @item define_stack
798 for the macros (@code{#define}s).
800 @item global_stack
801 for the global variables, functions and types.
803 @item local_stack
804 for the local variables, functions and types.
806 @item global_label_stack
807 for the local labels (for @code{goto}).
809 @item label_stack
810 for GCC block local labels (see the @code{__label__} keyword).
812 @end table
814 @code{sym_push()} is used to add a new symbol in the local symbol
815 stack. If no local symbol stack is active, it is added in the global
816 symbol stack.
818 @code{sym_pop(st,b)} pops symbols from the symbol stack @var{st} until
819 the symbol @var{b} is on the top of stack. If @var{b} is NULL, the stack
820 is emptied.
822 @code{sym_find(v)} return the symbol associated to the identifier
823 @var{v}. The local stack is searched first from top to bottom, then the
824 global stack.
826 @section Sections
828 The generated code and datas are written in sections. The structure
829 @code{Section} contains all the necessary information for a given
830 section. @code{new_section()} creates a new section. ELF file semantics
831 is assumed for each section.
833 The following sections are predefined:
835 @table @code
837 @item text_section
838 is the section containing the generated code. @var{ind} contains the
839 current position in the code section.
841 @item data_section
842 contains initialized data
844 @item bss_section
845 contains uninitialized data
847 @item bounds_section
848 @itemx lbounds_section
849 are used when bound checking is activated
851 @item stab_section
852 @itemx stabstr_section
853 are used when debugging is actived to store debug information
855 @item symtab_section
856 @itemx strtab_section
857 contain the exported symbols (currently only used for debugging).
859 @end table
861 @section Code generation
862 @cindex code generation
864 @subsection Introduction
866 The TCC code generator directly generates linked binary code in one
867 pass. It is rather unusual these days (see gcc for example which
868 generates text assembly), but it can be very fast and surprisingly
869 little complicated.
871 The TCC code generator is register based. Optimization is only done at
872 the expression level. No intermediate representation of expression is
873 kept except the current values stored in the @emph{value stack}.
875 On x86, three temporary registers are used. When more registers are
876 needed, one register is spilled into a new temporary variable on the stack.
878 @subsection The value stack
879 @cindex value stack, introduction
881 When an expression is parsed, its value is pushed on the value stack
882 (@var{vstack}). The top of the value stack is @var{vtop}. Each value
883 stack entry is the structure @code{SValue}.
885 @code{SValue.t} is the type. @code{SValue.r} indicates how the value is
886 currently stored in the generated code. It is usually a CPU register
887 index (@code{REG_xxx} constants), but additional values and flags are
888 defined:
890 @example
891 #define VT_CONST     0x00f0
892 #define VT_LLOCAL    0x00f1
893 #define VT_LOCAL     0x00f2
894 #define VT_CMP       0x00f3
895 #define VT_JMP       0x00f4
896 #define VT_JMPI      0x00f5
897 #define VT_LVAL      0x0100
898 #define VT_SYM       0x0200
899 #define VT_MUSTCAST  0x0400
900 #define VT_MUSTBOUND 0x0800
901 #define VT_BOUNDED   0x8000
902 #define VT_LVAL_BYTE     0x1000
903 #define VT_LVAL_SHORT    0x2000
904 #define VT_LVAL_UNSIGNED 0x4000
905 #define VT_LVAL_TYPE     (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
906 @end example
908 @table @code
910 @item VT_CONST
911 indicates that the value is a constant. It is stored in the union
912 @code{SValue.c}, depending on its type.
914 @item VT_LOCAL
915 indicates a local variable pointer at offset @code{SValue.c.i} in the
916 stack.
918 @item VT_CMP
919 indicates that the value is actually stored in the CPU flags (i.e. the
920 value is the consequence of a test). The value is either 0 or 1. The
921 actual CPU flags used is indicated in @code{SValue.c.i}. 
923 If any code is generated which destroys the CPU flags, this value MUST be
924 put in a normal register.
926 @item VT_JMP
927 @itemx VT_JMPI
928 indicates that the value is the consequence of a conditional jump. For VT_JMP,
929 it is 1 if the jump is taken, 0 otherwise. For VT_JMPI it is inverted.
931 These values are used to compile the @code{||} and @code{&&} logical
932 operators.
934 If any code is generated, this value MUST be put in a normal
935 register. Otherwise, the generated code won't be executed if the jump is
936 taken.
938 @item VT_LVAL
939 is a flag indicating that the value is actually an lvalue (left value of
940 an assignment). It means that the value stored is actually a pointer to
941 the wanted value. 
943 Understanding the use @code{VT_LVAL} is very important if you want to
944 understand how TCC works.
946 @item VT_LVAL_BYTE
947 @itemx VT_LVAL_SHORT
948 @itemx VT_LVAL_UNSIGNED
949 if the lvalue has an integer type, then these flags give its real
950 type. The type alone is not enough in case of cast optimisations.
952 @item VT_LLOCAL
953 is a saved lvalue on the stack. @code{VT_LLOCAL} should be eliminated
954 ASAP because its semantics are rather complicated.
956 @item VT_MUSTCAST
957 indicates that a cast to the value type must be performed if the value
958 is used (lazy casting).
960 @item VT_SYM
961 indicates that the symbol @code{SValue.sym} must be added to the constant.
963 @item VT_MUSTBOUND
964 @itemx VT_BOUNDED
965 are only used for optional bound checking.
967 @end table
969 @subsection Manipulating the value stack
970 @cindex value stack
972 @code{vsetc()} and @code{vset()} pushes a new value on the value
973 stack. If the previous @var{vtop} was stored in a very unsafe place(for
974 example in the CPU flags), then some code is generated to put the
975 previous @var{vtop} in a safe storage.
977 @code{vpop()} pops @var{vtop}. In some cases, it also generates cleanup
978 code (for example if stacked floating point registers are used as on
979 x86).
981 The @code{gv(rc)} function generates code to evaluate @var{vtop} (the
982 top value of the stack) into registers. @var{rc} selects in which
983 register class the value should be put. @code{gv()} is the @emph{most
984 important function} of the code generator.
986 @code{gv2()} is the same as @code{gv()} but for the top two stack
987 entries.
989 @subsection CPU dependent code generation
990 @cindex CPU dependent
991 See the @file{i386-gen.c} file to have an example.
993 @table @code
995 @item load()
996 must generate the code needed to load a stack value into a register.
998 @item store()
999 must generate the code needed to store a register into a stack value
1000 lvalue.
1002 @item gfunc_start()
1003 @itemx gfunc_param()
1004 @itemx gfunc_call()
1005 should generate a function call
1007 @item gfunc_prolog()
1008 @itemx gfunc_epilog()
1009 should generate a function prolog/epilog.
1011 @item gen_opi(op)
1012 must generate the binary integer operation @var{op} on the two top
1013 entries of the stack which are guaranted to contain integer types.
1015 The result value should be put on the stack.
1017 @item gen_opf(op)
1018 same as @code{gen_opi()} for floating point operations. The two top
1019 entries of the stack are guaranted to contain floating point values of
1020 same types.
1022 @item gen_cvt_itof()
1023 integer to floating point conversion.
1025 @item gen_cvt_ftoi()
1026 floating point to integer conversion.
1028 @item gen_cvt_ftof()
1029 floating point to floating point of different size conversion.
1031 @item gen_bounded_ptr_add()
1032 @item gen_bounded_ptr_deref()
1033 are only used for bounds checking.
1035 @end table
1037 @section Optimizations done
1038 @cindex optimizations
1039 @cindex constant propagation
1040 @cindex strength reduction
1041 @cindex comparison operators
1042 @cindex caching processor flags
1043 @cindex flags, caching
1044 @cindex jump optimization
1045 Constant propagation is done for all operations. Multiplications and
1046 divisions are optimized to shifts when appropriate. Comparison
1047 operators are optimized by maintaining a special cache for the
1048 processor flags. &&, || and ! are optimized by maintaining a special
1049 'jump target' value. No other jump optimization is currently performed
1050 because it would require to store the code in a more abstract fashion.
1052 @unnumbered Concept Index
1053 @printindex cp
1055 @bye
1057 @c Local variables:
1058 @c fill-column: 78
1059 @c texinfo-column-for-description: 32
1060 @c End: