Generate PIC code so that we can create shared objects properly.
[tinycc/kirr.git] / tcc.c
blob02da926aab6df49724087bc65a6a8c72483d4f2a
1 /*
2 * TCC - Tiny C Compiler
3 *
4 * Copyright (c) 2001-2004 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 #define _GNU_SOURCE
21 #include "config.h"
23 #ifdef CONFIG_TCCBOOT
25 #include "tccboot.h"
26 #define CONFIG_TCC_STATIC
28 #else
30 #include <stdlib.h>
31 #include <stdio.h>
32 #include <stdarg.h>
33 #include <string.h>
34 #include <errno.h>
35 #include <math.h>
36 #include <signal.h>
37 #include <fcntl.h>
38 #include <setjmp.h>
39 #include <time.h>
41 #ifdef _WIN32
42 #include <windows.h>
43 #include <sys/timeb.h>
44 #ifdef _MSC_VER
45 #define inline __inline
46 #endif
47 #endif
49 #ifndef _WIN32
50 #include <unistd.h>
51 #include <sys/time.h>
52 #include <sys/ucontext.h>
53 #include <sys/mman.h>
54 #endif
56 #endif /* !CONFIG_TCCBOOT */
58 #ifndef PAGESIZE
59 #define PAGESIZE 4096
60 #endif
62 #include "elf.h"
63 #include "stab.h"
65 #ifndef O_BINARY
66 #define O_BINARY 0
67 #endif
69 #include "libtcc.h"
71 /* parser debug */
72 //#define PARSE_DEBUG
73 /* preprocessor debug */
74 //#define PP_DEBUG
75 /* include file debug */
76 //#define INC_DEBUG
78 //#define MEM_DEBUG
80 /* assembler debug */
81 //#define ASM_DEBUG
83 /* target selection */
84 //#define TCC_TARGET_I386 /* i386 code generator */
85 //#define TCC_TARGET_ARM /* ARMv4 code generator */
86 //#define TCC_TARGET_C67 /* TMS320C67xx code generator */
87 //#define TCC_TARGET_X86_64 /* x86-64 code generator */
89 /* default target is I386 */
90 #if !defined(TCC_TARGET_I386) && !defined(TCC_TARGET_ARM) && \
91 !defined(TCC_TARGET_C67) && !defined(TCC_TARGET_X86_64)
92 #define TCC_TARGET_I386
93 #endif
95 #if !defined(_WIN32) && !defined(TCC_UCLIBC) && !defined(TCC_TARGET_ARM) && \
96 !defined(TCC_TARGET_C67) && !defined(TCC_TARGET_X86_64)
97 #define CONFIG_TCC_BCHECK /* enable bound checking code */
98 #endif
100 #if defined(_WIN32) && !defined(TCC_TARGET_PE)
101 #define CONFIG_TCC_STATIC
102 #endif
104 /* define it to include assembler support */
105 #if !defined(TCC_TARGET_ARM) && !defined(TCC_TARGET_C67) && \
106 !defined(TCC_TARGET_X86_64)
107 #define CONFIG_TCC_ASM
108 #endif
110 /* object format selection */
111 #if defined(TCC_TARGET_C67)
112 #define TCC_TARGET_COFF
113 #endif
115 #define FALSE 0
116 #define false 0
117 #define TRUE 1
118 #define true 1
119 typedef int BOOL;
121 /* path to find crt1.o, crti.o and crtn.o. Only needed when generating
122 executables or dlls */
123 #define CONFIG_TCC_CRT_PREFIX CONFIG_SYSROOT "/usr/lib"
125 #define INCLUDE_STACK_SIZE 32
126 #define IFDEF_STACK_SIZE 64
127 #define VSTACK_SIZE 256
128 #define STRING_MAX_SIZE 1024
129 #define PACK_STACK_SIZE 8
131 #define TOK_HASH_SIZE 8192 /* must be a power of two */
132 #define TOK_ALLOC_INCR 512 /* must be a power of two */
133 #define TOK_MAX_SIZE 4 /* token max size in int unit when stored in string */
135 /* token symbol management */
136 typedef struct TokenSym {
137 struct TokenSym *hash_next;
138 struct Sym *sym_define; /* direct pointer to define */
139 struct Sym *sym_label; /* direct pointer to label */
140 struct Sym *sym_struct; /* direct pointer to structure */
141 struct Sym *sym_identifier; /* direct pointer to identifier */
142 int tok; /* token number */
143 int len;
144 char str[1];
145 } TokenSym;
147 #ifdef TCC_TARGET_PE
148 typedef unsigned short nwchar_t;
149 #else
150 typedef int nwchar_t;
151 #endif
153 typedef struct CString {
154 int size; /* size in bytes */
155 void *data; /* either 'char *' or 'nwchar_t *' */
156 int size_allocated;
157 void *data_allocated; /* if non NULL, data has been malloced */
158 } CString;
160 /* type definition */
161 typedef struct CType {
162 int t;
163 struct Sym *ref;
164 } CType;
166 /* constant value */
167 typedef union CValue {
168 long double ld;
169 double d;
170 float f;
171 int i;
172 unsigned int ui;
173 unsigned int ul; /* address (should be unsigned long on 64 bit cpu) */
174 long long ll;
175 unsigned long long ull;
176 struct CString *cstr;
177 void *ptr;
178 int tab[1];
179 } CValue;
181 /* value on stack */
182 typedef struct SValue {
183 CType type; /* type */
184 unsigned short r; /* register + flags */
185 unsigned short r2; /* second register, used for 'long long'
186 type. If not used, set to VT_CONST */
187 CValue c; /* constant, if VT_CONST */
188 struct Sym *sym; /* symbol, if (VT_SYM | VT_CONST) */
189 } SValue;
191 /* symbol management */
192 typedef struct Sym {
193 int v; /* symbol token */
194 long r; /* associated register */
195 long c; /* associated number */
196 CType type; /* associated type */
197 struct Sym *next; /* next related symbol */
198 struct Sym *prev; /* prev symbol in stack */
199 struct Sym *prev_tok; /* previous symbol for this token */
200 } Sym;
202 /* section definition */
203 /* XXX: use directly ELF structure for parameters ? */
204 /* special flag to indicate that the section should not be linked to
205 the other ones */
206 #define SHF_PRIVATE 0x80000000
208 typedef struct Section {
209 unsigned long data_offset; /* current data offset */
210 unsigned char *data; /* section data */
211 unsigned long data_allocated; /* used for realloc() handling */
212 int sh_name; /* elf section name (only used during output) */
213 int sh_num; /* elf section number */
214 int sh_type; /* elf section type */
215 int sh_flags; /* elf section flags */
216 int sh_info; /* elf section info */
217 int sh_addralign; /* elf section alignment */
218 int sh_entsize; /* elf entry size */
219 unsigned long sh_size; /* section size (only used during output) */
220 unsigned long sh_addr; /* address at which the section is relocated */
221 unsigned long sh_offset; /* file offset */
222 int nb_hashed_syms; /* used to resize the hash table */
223 struct Section *link; /* link to another section */
224 struct Section *reloc; /* corresponding section for relocation, if any */
225 struct Section *hash; /* hash table for symbols */
226 struct Section *next;
227 char name[1]; /* section name */
228 } Section;
230 typedef struct DLLReference {
231 int level;
232 void *handle;
233 char name[1];
234 } DLLReference;
236 /* GNUC attribute definition */
237 typedef struct AttributeDef {
238 int aligned;
239 int packed;
240 Section *section;
241 int func_attr; /* calling convention, exports, ... */
242 } AttributeDef;
244 /* -------------------------------------------------- */
245 /* gr: wrappers for casting sym->r for other purposes */
246 typedef struct {
247 unsigned
248 func_call : 8,
249 func_args : 8,
250 func_export : 1;
251 } func_attr_t;
253 #define FUNC_CALL(r) (((func_attr_t*)&(r))->func_call)
254 #define FUNC_EXPORT(r) (((func_attr_t*)&(r))->func_export)
255 #define FUNC_ARGS(r) (((func_attr_t*)&(r))->func_args)
256 #define INLINE_DEF(r) (*(int **)&(r))
257 /* -------------------------------------------------- */
259 #define SYM_STRUCT 0x40000000 /* struct/union/enum symbol space */
260 #define SYM_FIELD 0x20000000 /* struct/union field symbol space */
261 #define SYM_FIRST_ANOM 0x10000000 /* first anonymous sym */
263 /* stored in 'Sym.c' field */
264 #define FUNC_NEW 1 /* ansi function prototype */
265 #define FUNC_OLD 2 /* old function prototype */
266 #define FUNC_ELLIPSIS 3 /* ansi function prototype with ... */
268 /* stored in 'Sym.r' field */
269 #define FUNC_CDECL 0 /* standard c call */
270 #define FUNC_STDCALL 1 /* pascal c call */
271 #define FUNC_FASTCALL1 2 /* first param in %eax */
272 #define FUNC_FASTCALL2 3 /* first parameters in %eax, %edx */
273 #define FUNC_FASTCALL3 4 /* first parameter in %eax, %edx, %ecx */
274 #define FUNC_FASTCALLW 5 /* first parameter in %ecx, %edx */
276 /* field 'Sym.t' for macros */
277 #define MACRO_OBJ 0 /* object like macro */
278 #define MACRO_FUNC 1 /* function like macro */
280 /* field 'Sym.r' for C labels */
281 #define LABEL_DEFINED 0 /* label is defined */
282 #define LABEL_FORWARD 1 /* label is forward defined */
283 #define LABEL_DECLARED 2 /* label is declared but never used */
285 /* type_decl() types */
286 #define TYPE_ABSTRACT 1 /* type without variable */
287 #define TYPE_DIRECT 2 /* type with variable */
289 #define IO_BUF_SIZE 8192
291 typedef struct BufferedFile {
292 uint8_t *buf_ptr;
293 uint8_t *buf_end;
294 int fd;
295 int line_num; /* current line number - here to simplify code */
296 int ifndef_macro; /* #ifndef macro / #endif search */
297 int ifndef_macro_saved; /* saved ifndef_macro */
298 int *ifdef_stack_ptr; /* ifdef_stack value at the start of the file */
299 char inc_type; /* type of include */
300 char inc_filename[512]; /* filename specified by the user */
301 char filename[1024]; /* current filename - here to simplify code */
302 unsigned char buffer[IO_BUF_SIZE + 1]; /* extra size for CH_EOB char */
303 } BufferedFile;
305 #define CH_EOB '\\' /* end of buffer or '\0' char in file */
306 #define CH_EOF (-1) /* end of file */
308 /* parsing state (used to save parser state to reparse part of the
309 source several times) */
310 typedef struct ParseState {
311 int *macro_ptr;
312 int line_num;
313 int tok;
314 CValue tokc;
315 } ParseState;
317 /* used to record tokens */
318 typedef struct TokenString {
319 int *str;
320 int len;
321 int allocated_len;
322 int last_line_num;
323 } TokenString;
325 /* include file cache, used to find files faster and also to eliminate
326 inclusion if the include file is protected by #ifndef ... #endif */
327 typedef struct CachedInclude {
328 int ifndef_macro;
329 int hash_next; /* -1 if none */
330 char type; /* '"' or '>' to give include type */
331 char filename[1]; /* path specified in #include */
332 } CachedInclude;
334 #define CACHED_INCLUDES_HASH_SIZE 512
336 /* parser */
337 static struct BufferedFile *file;
338 static int ch, tok;
339 static CString tok_spaces; /* spaces before current token */
340 static CValue tokc;
341 static CString tokcstr; /* current parsed string, if any */
342 /* additional informations about token */
343 static int tok_flags;
344 #define TOK_FLAG_BOL 0x0001 /* beginning of line before */
345 #define TOK_FLAG_BOF 0x0002 /* beginning of file before */
346 #define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */
347 #define TOK_FLAG_EOF 0x0008 /* end of file */
349 static int *macro_ptr, *macro_ptr_allocated;
350 static int *unget_saved_macro_ptr;
351 static int unget_saved_buffer[TOK_MAX_SIZE + 1];
352 static int unget_buffer_enabled;
353 static int parse_flags;
354 #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
355 #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
356 #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
357 token. line feed is also
358 returned at eof */
359 #define PARSE_FLAG_ASM_COMMENTS 0x0008 /* '#' can be used for line comment */
361 static Section *text_section, *data_section, *bss_section; /* predefined sections */
362 static Section *cur_text_section; /* current section where function code is
363 generated */
364 #ifdef CONFIG_TCC_ASM
365 static Section *last_text_section; /* to handle .previous asm directive */
366 #endif
367 /* bound check related sections */
368 static Section *bounds_section; /* contains global data bound description */
369 static Section *lbounds_section; /* contains local data bound description */
370 /* symbol sections */
371 static Section *symtab_section, *strtab_section;
373 /* debug sections */
374 static Section *stab_section, *stabstr_section;
376 /* loc : local variable index
377 ind : output code index
378 rsym: return symbol
379 anon_sym: anonymous symbol index
381 static int rsym, anon_sym, ind, loc;
382 /* expression generation modifiers */
383 static int const_wanted; /* true if constant wanted */
384 static int nocode_wanted; /* true if no code generation wanted for an expression */
385 static int global_expr; /* true if compound literals must be allocated
386 globally (used during initializers parsing */
387 static CType func_vt; /* current function return type (used by return
388 instruction) */
389 static int func_vc;
390 static int last_line_num, last_ind, func_ind; /* debug last line number and pc */
391 static int tok_ident;
392 static TokenSym **table_ident;
393 static TokenSym *hash_ident[TOK_HASH_SIZE];
394 static char token_buf[STRING_MAX_SIZE + 1];
395 static char *funcname;
396 static Sym *global_stack, *local_stack;
397 static Sym *define_stack;
398 static Sym *global_label_stack, *local_label_stack;
399 /* symbol allocator */
400 #define SYM_POOL_NB (8192 / sizeof(Sym))
401 static Sym *sym_free_first;
402 static void **sym_pools;
403 static int nb_sym_pools;
405 static SValue vstack[VSTACK_SIZE], *vtop;
406 /* some predefined types */
407 static CType char_pointer_type, func_old_type, int_type;
408 /* true if isid(c) || isnum(c) */
409 static unsigned char isidnum_table[256-CH_EOF];
411 /* display some information during compilation */
412 static int verbose = 0;
414 /* compile with debug symbol (and use them if error during execution) */
415 static int do_debug = 0;
417 /* compile with built-in memory and bounds checker */
418 static int do_bounds_check = 0;
420 /* display benchmark infos */
421 #if !defined(LIBTCC)
422 static int do_bench = 0;
423 #endif
424 static int total_lines;
425 static int total_bytes;
427 /* use GNU C extensions */
428 static int gnu_ext = 1;
430 /* use Tiny C extensions */
431 static int tcc_ext = 1;
433 /* max number of callers shown if error */
434 static int num_callers = 6;
435 static const char **rt_bound_error_msg;
437 /* XXX: get rid of this ASAP */
438 static struct TCCState *tcc_state;
440 /* give the path of the tcc libraries */
441 static const char *tcc_lib_path = CONFIG_TCCDIR;
443 struct TCCState {
444 int output_type;
446 BufferedFile **include_stack_ptr;
447 int *ifdef_stack_ptr;
449 /* include file handling */
450 char **include_paths;
451 int nb_include_paths;
452 char **sysinclude_paths;
453 int nb_sysinclude_paths;
454 CachedInclude **cached_includes;
455 int nb_cached_includes;
457 char **library_paths;
458 int nb_library_paths;
460 /* array of all loaded dlls (including those referenced by loaded
461 dlls) */
462 DLLReference **loaded_dlls;
463 int nb_loaded_dlls;
465 /* sections */
466 Section **sections;
467 int nb_sections; /* number of sections, including first dummy section */
469 Section **priv_sections;
470 int nb_priv_sections; /* number of private sections */
472 /* got handling */
473 Section *got;
474 Section *plt;
475 unsigned long *got_offsets;
476 int nb_got_offsets;
477 /* give the correspondance from symtab indexes to dynsym indexes */
478 int *symtab_to_dynsym;
480 /* temporary dynamic symbol sections (for dll loading) */
481 Section *dynsymtab_section;
482 /* exported dynamic symbol section */
483 Section *dynsym;
485 int nostdinc; /* if true, no standard headers are added */
486 int nostdlib; /* if true, no standard libraries are added */
488 int nocommon; /* if true, do not use common symbols for .bss data */
490 /* if true, static linking is performed */
491 int static_link;
493 /* soname as specified on the command line (-soname) */
494 const char *soname;
496 /* if true, all symbols are exported */
497 int rdynamic;
499 /* if true, only link in referenced objects from archive */
500 int alacarte_link;
502 /* address of text section */
503 unsigned long text_addr;
504 int has_text_addr;
506 /* output format, see TCC_OUTPUT_FORMAT_xxx */
507 int output_format;
509 /* C language options */
510 int char_is_unsigned;
511 int leading_underscore;
513 /* warning switches */
514 int warn_write_strings;
515 int warn_unsupported;
516 int warn_error;
517 int warn_none;
518 int warn_implicit_function_declaration;
520 /* error handling */
521 void *error_opaque;
522 void (*error_func)(void *opaque, const char *msg);
523 int error_set_jmp_enabled;
524 jmp_buf error_jmp_buf;
525 int nb_errors;
527 /* tiny assembler state */
528 Sym *asm_labels;
530 /* see include_stack_ptr */
531 BufferedFile *include_stack[INCLUDE_STACK_SIZE];
533 /* see ifdef_stack_ptr */
534 int ifdef_stack[IFDEF_STACK_SIZE];
536 /* see cached_includes */
537 int cached_includes_hash[CACHED_INCLUDES_HASH_SIZE];
539 /* pack stack */
540 int pack_stack[PACK_STACK_SIZE];
541 int *pack_stack_ptr;
543 /* output file for preprocessing */
544 FILE *outfile;
546 #ifdef TCC_TARGET_X86_64
547 /* buffer to store jump tables used when the output is memory */
548 char *jmp_table;
549 int jmp_table_num;
550 /* buffer to store got tables used when the output is memory */
551 void **got_table;
552 int got_table_num;
553 #endif
556 /* The current value can be: */
557 #define VT_VALMASK 0x00ff
558 #define VT_CONST 0x00f0 /* constant in vc
559 (must be first non register value) */
560 #define VT_LLOCAL 0x00f1 /* lvalue, offset on stack */
561 #define VT_LOCAL 0x00f2 /* offset on stack */
562 #define VT_CMP 0x00f3 /* the value is stored in processor flags (in vc) */
563 #define VT_JMP 0x00f4 /* value is the consequence of jmp true (even) */
564 #define VT_JMPI 0x00f5 /* value is the consequence of jmp false (odd) */
565 #define VT_LVAL 0x0100 /* var is an lvalue */
566 #define VT_SYM 0x0200 /* a symbol value is added */
567 #define VT_MUSTCAST 0x0400 /* value must be casted to be correct (used for
568 char/short stored in integer registers) */
569 #define VT_MUSTBOUND 0x0800 /* bound checking must be done before
570 dereferencing value */
571 #define VT_BOUNDED 0x8000 /* value is bounded. The address of the
572 bounding function call point is in vc */
573 #define VT_LVAL_BYTE 0x1000 /* lvalue is a byte */
574 #define VT_LVAL_SHORT 0x2000 /* lvalue is a short */
575 #define VT_LVAL_UNSIGNED 0x4000 /* lvalue is unsigned */
576 #define VT_LVAL_TYPE (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
578 /* types */
579 #define VT_INT 0 /* integer type */
580 #define VT_BYTE 1 /* signed byte type */
581 #define VT_SHORT 2 /* short type */
582 #define VT_VOID 3 /* void type */
583 #define VT_PTR 4 /* pointer */
584 #define VT_ENUM 5 /* enum definition */
585 #define VT_FUNC 6 /* function type */
586 #define VT_STRUCT 7 /* struct/union definition */
587 #define VT_FLOAT 8 /* IEEE float */
588 #define VT_DOUBLE 9 /* IEEE double */
589 #define VT_LDOUBLE 10 /* IEEE long double */
590 #define VT_BOOL 11 /* ISOC99 boolean type */
591 #define VT_LLONG 12 /* 64 bit integer */
592 #define VT_LONG 13 /* long integer (NEVER USED as type, only
593 during parsing) */
594 #define VT_BTYPE 0x000f /* mask for basic type */
595 #define VT_UNSIGNED 0x0010 /* unsigned type */
596 #define VT_ARRAY 0x0020 /* array type (also has VT_PTR) */
597 #define VT_BITFIELD 0x0040 /* bitfield modifier */
598 #define VT_CONSTANT 0x0800 /* const modifier */
599 #define VT_VOLATILE 0x1000 /* volatile modifier */
600 #define VT_SIGNED 0x2000 /* signed type */
602 /* storage */
603 #define VT_EXTERN 0x00000080 /* extern definition */
604 #define VT_STATIC 0x00000100 /* static variable */
605 #define VT_TYPEDEF 0x00000200 /* typedef definition */
606 #define VT_INLINE 0x00000400 /* inline definition */
608 #define VT_STRUCT_SHIFT 16 /* shift for bitfield shift values */
610 /* type mask (except storage) */
611 #define VT_STORAGE (VT_EXTERN | VT_STATIC | VT_TYPEDEF | VT_INLINE)
612 #define VT_TYPE (~(VT_STORAGE))
614 /* token values */
616 /* warning: the following compare tokens depend on i386 asm code */
617 #define TOK_ULT 0x92
618 #define TOK_UGE 0x93
619 #define TOK_EQ 0x94
620 #define TOK_NE 0x95
621 #define TOK_ULE 0x96
622 #define TOK_UGT 0x97
623 #define TOK_Nset 0x98
624 #define TOK_Nclear 0x99
625 #define TOK_LT 0x9c
626 #define TOK_GE 0x9d
627 #define TOK_LE 0x9e
628 #define TOK_GT 0x9f
630 #define TOK_LAND 0xa0
631 #define TOK_LOR 0xa1
633 #define TOK_DEC 0xa2
634 #define TOK_MID 0xa3 /* inc/dec, to void constant */
635 #define TOK_INC 0xa4
636 #define TOK_UDIV 0xb0 /* unsigned division */
637 #define TOK_UMOD 0xb1 /* unsigned modulo */
638 #define TOK_PDIV 0xb2 /* fast division with undefined rounding for pointers */
639 #define TOK_CINT 0xb3 /* number in tokc */
640 #define TOK_CCHAR 0xb4 /* char constant in tokc */
641 #define TOK_STR 0xb5 /* pointer to string in tokc */
642 #define TOK_TWOSHARPS 0xb6 /* ## preprocessing token */
643 #define TOK_LCHAR 0xb7
644 #define TOK_LSTR 0xb8
645 #define TOK_CFLOAT 0xb9 /* float constant */
646 #define TOK_LINENUM 0xba /* line number info */
647 #define TOK_CDOUBLE 0xc0 /* double constant */
648 #define TOK_CLDOUBLE 0xc1 /* long double constant */
649 #define TOK_UMULL 0xc2 /* unsigned 32x32 -> 64 mul */
650 #define TOK_ADDC1 0xc3 /* add with carry generation */
651 #define TOK_ADDC2 0xc4 /* add with carry use */
652 #define TOK_SUBC1 0xc5 /* add with carry generation */
653 #define TOK_SUBC2 0xc6 /* add with carry use */
654 #define TOK_CUINT 0xc8 /* unsigned int constant */
655 #define TOK_CLLONG 0xc9 /* long long constant */
656 #define TOK_CULLONG 0xca /* unsigned long long constant */
657 #define TOK_ARROW 0xcb
658 #define TOK_DOTS 0xcc /* three dots */
659 #define TOK_SHR 0xcd /* unsigned shift right */
660 #define TOK_PPNUM 0xce /* preprocessor number */
662 #define TOK_SHL 0x01 /* shift left */
663 #define TOK_SAR 0x02 /* signed shift right */
665 /* assignement operators : normal operator or 0x80 */
666 #define TOK_A_MOD 0xa5
667 #define TOK_A_AND 0xa6
668 #define TOK_A_MUL 0xaa
669 #define TOK_A_ADD 0xab
670 #define TOK_A_SUB 0xad
671 #define TOK_A_DIV 0xaf
672 #define TOK_A_XOR 0xde
673 #define TOK_A_OR 0xfc
674 #define TOK_A_SHL 0x81
675 #define TOK_A_SAR 0x82
677 #ifndef offsetof
678 #define offsetof(type, field) ((size_t) &((type *)0)->field)
679 #endif
681 #ifndef countof
682 #define countof(tab) (sizeof(tab) / sizeof((tab)[0]))
683 #endif
685 /* WARNING: the content of this string encodes token numbers */
686 static char tok_two_chars[] = "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
688 #define TOK_EOF (-1) /* end of file */
689 #define TOK_LINEFEED 10 /* line feed */
691 /* all identificators and strings have token above that */
692 #define TOK_IDENT 256
694 /* only used for i386 asm opcodes definitions */
695 #define DEF_ASM(x) DEF(TOK_ASM_ ## x, #x)
697 #define DEF_BWL(x) \
698 DEF(TOK_ASM_ ## x ## b, #x "b") \
699 DEF(TOK_ASM_ ## x ## w, #x "w") \
700 DEF(TOK_ASM_ ## x ## l, #x "l") \
701 DEF(TOK_ASM_ ## x, #x)
703 #define DEF_WL(x) \
704 DEF(TOK_ASM_ ## x ## w, #x "w") \
705 DEF(TOK_ASM_ ## x ## l, #x "l") \
706 DEF(TOK_ASM_ ## x, #x)
708 #define DEF_FP1(x) \
709 DEF(TOK_ASM_ ## f ## x ## s, "f" #x "s") \
710 DEF(TOK_ASM_ ## fi ## x ## l, "fi" #x "l") \
711 DEF(TOK_ASM_ ## f ## x ## l, "f" #x "l") \
712 DEF(TOK_ASM_ ## fi ## x ## s, "fi" #x "s")
714 #define DEF_FP(x) \
715 DEF(TOK_ASM_ ## f ## x, "f" #x ) \
716 DEF(TOK_ASM_ ## f ## x ## p, "f" #x "p") \
717 DEF_FP1(x)
719 #define DEF_ASMTEST(x) \
720 DEF_ASM(x ## o) \
721 DEF_ASM(x ## no) \
722 DEF_ASM(x ## b) \
723 DEF_ASM(x ## c) \
724 DEF_ASM(x ## nae) \
725 DEF_ASM(x ## nb) \
726 DEF_ASM(x ## nc) \
727 DEF_ASM(x ## ae) \
728 DEF_ASM(x ## e) \
729 DEF_ASM(x ## z) \
730 DEF_ASM(x ## ne) \
731 DEF_ASM(x ## nz) \
732 DEF_ASM(x ## be) \
733 DEF_ASM(x ## na) \
734 DEF_ASM(x ## nbe) \
735 DEF_ASM(x ## a) \
736 DEF_ASM(x ## s) \
737 DEF_ASM(x ## ns) \
738 DEF_ASM(x ## p) \
739 DEF_ASM(x ## pe) \
740 DEF_ASM(x ## np) \
741 DEF_ASM(x ## po) \
742 DEF_ASM(x ## l) \
743 DEF_ASM(x ## nge) \
744 DEF_ASM(x ## nl) \
745 DEF_ASM(x ## ge) \
746 DEF_ASM(x ## le) \
747 DEF_ASM(x ## ng) \
748 DEF_ASM(x ## nle) \
749 DEF_ASM(x ## g)
751 #define TOK_ASM_int TOK_INT
753 enum tcc_token {
754 TOK_LAST = TOK_IDENT - 1,
755 #define DEF(id, str) id,
756 #include "tcctok.h"
757 #undef DEF
760 static const char tcc_keywords[] =
761 #define DEF(id, str) str "\0"
762 #include "tcctok.h"
763 #undef DEF
766 #define TOK_UIDENT TOK_DEFINE
768 #ifdef _WIN32
769 #define snprintf _snprintf
770 #define vsnprintf _vsnprintf
771 #ifndef __GNUC__
772 #define strtold (long double)strtod
773 #define strtof (float)strtod
774 #define strtoll (long long)strtol
775 #endif
776 #elif defined(TCC_UCLIBC) || defined(__FreeBSD__) || defined(__DragonFly__) \
777 || defined(__OpenBSD__)
778 /* currently incorrect */
779 long double strtold(const char *nptr, char **endptr)
781 return (long double)strtod(nptr, endptr);
783 float strtof(const char *nptr, char **endptr)
785 return (float)strtod(nptr, endptr);
787 #else
788 /* XXX: need to define this to use them in non ISOC99 context */
789 extern float strtof (const char *__nptr, char **__endptr);
790 extern long double strtold (const char *__nptr, char **__endptr);
791 #endif
793 static char *pstrcpy(char *buf, int buf_size, const char *s);
794 static char *pstrcat(char *buf, int buf_size, const char *s);
795 static char *tcc_basename(const char *name);
796 static char *tcc_fileextension (const char *p);
798 static void next(void);
799 static void next_nomacro(void);
800 static void parse_expr_type(CType *type);
801 static void expr_type(CType *type);
802 static void unary_type(CType *type);
803 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
804 int case_reg, int is_expr);
805 static int expr_const(void);
806 static void expr_eq(void);
807 static void gexpr(void);
808 static void gen_inline_functions(void);
809 static void decl(int l);
810 static void decl_initializer(CType *type, Section *sec, unsigned long c,
811 int first, int size_only);
812 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
813 int has_init, int v, int scope);
814 int gv(int rc);
815 void gv2(int rc1, int rc2);
816 void move_reg(int r, int s);
817 void save_regs(int n);
818 void save_reg(int r);
819 void vpop(void);
820 void vswap(void);
821 void vdup(void);
822 int get_reg(int rc);
823 int get_reg_ex(int rc,int rc2);
825 struct macro_level {
826 struct macro_level *prev;
827 int *p;
830 static void macro_subst(TokenString *tok_str, Sym **nested_list,
831 const int *macro_str, struct macro_level **can_read_stream);
832 void gen_op(int op);
833 void force_charshort_cast(int t);
834 static void gen_cast(CType *type);
835 void vstore(void);
836 static Sym *sym_find(int v);
837 static Sym *sym_push(int v, CType *type, int r, int c);
839 /* type handling */
840 static int type_size(CType *type, int *a);
841 static inline CType *pointed_type(CType *type);
842 static int pointed_size(CType *type);
843 static int lvalue_type(int t);
844 static int parse_btype(CType *type, AttributeDef *ad);
845 static void type_decl(CType *type, AttributeDef *ad, int *v, int td);
846 static int compare_types(CType *type1, CType *type2, int unqualified);
847 static int is_compatible_types(CType *type1, CType *type2);
848 static int is_compatible_parameter_types(CType *type1, CType *type2);
850 int ieee_finite(double d);
851 void error(const char *fmt, ...);
852 void vpushi(int v);
853 void vpushll(long long v);
854 void vrott(int n);
855 void vnrott(int n);
856 void lexpand_nr(void);
857 static void vpush_global_sym(CType *type, int v);
858 void vset(CType *type, int r, int v);
859 void type_to_str(char *buf, int buf_size,
860 CType *type, const char *varstr);
861 char *get_tok_str(int v, CValue *cv);
862 static Sym *get_sym_ref(CType *type, Section *sec,
863 unsigned long offset, unsigned long size);
864 static Sym *external_global_sym(int v, CType *type, int r);
866 /* section generation */
867 static void section_realloc(Section *sec, unsigned long new_size);
868 static void *section_ptr_add(Section *sec, unsigned long size);
869 static void put_extern_sym(Sym *sym, Section *section,
870 unsigned long value, unsigned long size);
871 static void greloc(Section *s, Sym *sym, unsigned long addr, int type);
872 static int put_elf_str(Section *s, const char *sym);
873 static int put_elf_sym(Section *s,
874 unsigned long value, unsigned long size,
875 int info, int other, int shndx, const char *name);
876 static int add_elf_sym(Section *s, unsigned long value, unsigned long size,
877 int info, int other, int sh_num, const char *name);
878 static void put_elf_reloc(Section *symtab, Section *s, unsigned long offset,
879 int type, int symbol);
880 static void put_stabs(const char *str, int type, int other, int desc,
881 unsigned long value);
882 static void put_stabs_r(const char *str, int type, int other, int desc,
883 unsigned long value, Section *sec, int sym_index);
884 static void put_stabn(int type, int other, int desc, int value);
885 static void put_stabd(int type, int other, int desc);
886 static int tcc_add_dll(TCCState *s, const char *filename, int flags);
888 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
889 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
890 #define AFF_PREPROCESS 0x0004 /* preprocess file */
891 static int tcc_add_file_internal(TCCState *s, const char *filename, int flags);
893 /* tcccoff.c */
894 int tcc_output_coff(TCCState *s1, FILE *f);
896 /* tccpe.c */
897 void *resolve_sym(TCCState *s1, const char *sym, int type);
898 int pe_load_def_file(struct TCCState *s1, int fd);
899 int pe_test_res_file(void *v, int size);
900 int pe_load_res_file(struct TCCState *s1, int fd);
901 void pe_add_runtime(struct TCCState *s1);
902 void pe_guess_outfile(char *objfilename, int output_type);
903 int pe_output_file(struct TCCState *s1, const char *filename);
905 /* tccasm.c */
907 #ifdef CONFIG_TCC_ASM
909 typedef struct ExprValue {
910 uint32_t v;
911 Sym *sym;
912 } ExprValue;
914 #define MAX_ASM_OPERANDS 30
916 typedef struct ASMOperand {
917 int id; /* GCC 3 optionnal identifier (0 if number only supported */
918 char *constraint;
919 char asm_str[16]; /* computed asm string for operand */
920 SValue *vt; /* C value of the expression */
921 int ref_index; /* if >= 0, gives reference to a output constraint */
922 int input_index; /* if >= 0, gives reference to an input constraint */
923 int priority; /* priority, used to assign registers */
924 int reg; /* if >= 0, register number used for this operand */
925 int is_llong; /* true if double register value */
926 int is_memory; /* true if memory operand */
927 int is_rw; /* for '+' modifier */
928 } ASMOperand;
930 static void asm_expr(TCCState *s1, ExprValue *pe);
931 static int asm_int_expr(TCCState *s1);
932 static int find_constraint(ASMOperand *operands, int nb_operands,
933 const char *name, const char **pp);
935 static int tcc_assemble(TCCState *s1, int do_preprocess);
937 #endif
939 static void asm_instr(void);
940 static void asm_global_instr(void);
942 /* true if float/double/long double type */
943 static inline int is_float(int t)
945 int bt;
946 bt = t & VT_BTYPE;
947 return bt == VT_LDOUBLE || bt == VT_DOUBLE || bt == VT_FLOAT;
950 #ifdef TCC_TARGET_I386
951 #include "i386-gen.c"
952 #endif
954 #ifdef TCC_TARGET_ARM
955 #include "arm-gen.c"
956 #endif
958 #ifdef TCC_TARGET_C67
959 #include "c67-gen.c"
960 #endif
962 #ifdef TCC_TARGET_X86_64
963 #include "x86_64-gen.c"
964 #endif
966 #ifdef CONFIG_TCC_STATIC
968 #define RTLD_LAZY 0x001
969 #define RTLD_NOW 0x002
970 #define RTLD_GLOBAL 0x100
971 #define RTLD_DEFAULT NULL
973 /* dummy function for profiling */
974 void *dlopen(const char *filename, int flag)
976 return NULL;
979 const char *dlerror(void)
981 return "error";
984 typedef struct TCCSyms {
985 char *str;
986 void *ptr;
987 } TCCSyms;
989 #define TCCSYM(a) { #a, &a, },
991 /* add the symbol you want here if no dynamic linking is done */
992 static TCCSyms tcc_syms[] = {
993 #if !defined(CONFIG_TCCBOOT)
994 TCCSYM(printf)
995 TCCSYM(fprintf)
996 TCCSYM(fopen)
997 TCCSYM(fclose)
998 #endif
999 { NULL, NULL },
1002 void *resolve_sym(TCCState *s1, const char *symbol, int type)
1004 TCCSyms *p;
1005 p = tcc_syms;
1006 while (p->str != NULL) {
1007 if (!strcmp(p->str, symbol))
1008 return p->ptr;
1009 p++;
1011 return NULL;
1014 #elif !defined(_WIN32)
1016 #include <dlfcn.h>
1018 void *resolve_sym(TCCState *s1, const char *sym, int type)
1020 return dlsym(RTLD_DEFAULT, sym);
1023 #endif
1025 /********************************************************/
1027 /* we use our own 'finite' function to avoid potential problems with
1028 non standard math libs */
1029 /* XXX: endianness dependent */
1030 int ieee_finite(double d)
1032 int *p = (int *)&d;
1033 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
1036 /* copy a string and truncate it. */
1037 static char *pstrcpy(char *buf, int buf_size, const char *s)
1039 char *q, *q_end;
1040 int c;
1042 if (buf_size > 0) {
1043 q = buf;
1044 q_end = buf + buf_size - 1;
1045 while (q < q_end) {
1046 c = *s++;
1047 if (c == '\0')
1048 break;
1049 *q++ = c;
1051 *q = '\0';
1053 return buf;
1056 /* strcat and truncate. */
1057 static char *pstrcat(char *buf, int buf_size, const char *s)
1059 int len;
1060 len = strlen(buf);
1061 if (len < buf_size)
1062 pstrcpy(buf + len, buf_size - len, s);
1063 return buf;
1066 #ifndef LIBTCC
1067 static int strstart(const char *str, const char *val, const char **ptr)
1069 const char *p, *q;
1070 p = str;
1071 q = val;
1072 while (*q != '\0') {
1073 if (*p != *q)
1074 return 0;
1075 p++;
1076 q++;
1078 if (ptr)
1079 *ptr = p;
1080 return 1;
1082 #endif
1084 #ifdef _WIN32
1085 #define IS_PATHSEP(c) (c == '/' || c == '\\')
1086 #define IS_ABSPATH(p) (IS_PATHSEP(p[0]) || (p[0] && p[1] == ':' && IS_PATHSEP(p[2])))
1087 #else
1088 #define IS_PATHSEP(c) (c == '/')
1089 #define IS_ABSPATH(p) IS_PATHSEP(p[0])
1090 #endif
1092 /* extract the basename of a file */
1093 static char *tcc_basename(const char *name)
1095 char *p = strchr(name, 0);
1096 while (p > name && !IS_PATHSEP(p[-1]))
1097 --p;
1098 return p;
1101 static char *tcc_fileextension (const char *name)
1103 char *b = tcc_basename(name);
1104 char *e = strrchr(b, '.');
1105 return e ? e : strchr(b, 0);
1108 #ifdef _WIN32
1109 char *normalize_slashes(char *path)
1111 char *p;
1112 for (p = path; *p; ++p)
1113 if (*p == '\\')
1114 *p = '/';
1115 return path;
1118 char *w32_tcc_lib_path(void)
1120 /* on win32, we suppose the lib and includes are at the location
1121 of 'tcc.exe' */
1122 char path[1024], *p;
1123 GetModuleFileNameA(NULL, path, sizeof path);
1124 p = tcc_basename(normalize_slashes(strlwr(path)));
1125 if (p - 5 > path && 0 == strncmp(p - 5, "/bin/", 5))
1126 p -= 5;
1127 else if (p > path)
1128 p--;
1129 *p = 0;
1130 return strdup(path);
1132 #endif
1134 void set_pages_executable(void *ptr, unsigned long length)
1136 #ifdef _WIN32
1137 unsigned long old_protect;
1138 VirtualProtect(ptr, length, PAGE_EXECUTE_READWRITE, &old_protect);
1139 #else
1140 unsigned long start, end;
1141 start = (unsigned long)ptr & ~(PAGESIZE - 1);
1142 end = (unsigned long)ptr + length;
1143 end = (end + PAGESIZE - 1) & ~(PAGESIZE - 1);
1144 mprotect((void *)start, end - start, PROT_READ | PROT_WRITE | PROT_EXEC);
1145 #endif
1148 /* memory management */
1149 #ifdef MEM_DEBUG
1150 int mem_cur_size;
1151 int mem_max_size;
1152 unsigned malloc_usable_size(void*);
1153 #endif
1155 static inline void tcc_free(void *ptr)
1157 #ifdef MEM_DEBUG
1158 mem_cur_size -= malloc_usable_size(ptr);
1159 #endif
1160 free(ptr);
1163 static void *tcc_malloc(unsigned long size)
1165 void *ptr;
1166 ptr = malloc(size);
1167 if (!ptr && size)
1168 error("memory full");
1169 #ifdef MEM_DEBUG
1170 mem_cur_size += malloc_usable_size(ptr);
1171 if (mem_cur_size > mem_max_size)
1172 mem_max_size = mem_cur_size;
1173 #endif
1174 return ptr;
1177 static void *tcc_mallocz(unsigned long size)
1179 void *ptr;
1180 ptr = tcc_malloc(size);
1181 memset(ptr, 0, size);
1182 return ptr;
1185 static inline void *tcc_realloc(void *ptr, unsigned long size)
1187 void *ptr1;
1188 #ifdef MEM_DEBUG
1189 mem_cur_size -= malloc_usable_size(ptr);
1190 #endif
1191 ptr1 = realloc(ptr, size);
1192 #ifdef MEM_DEBUG
1193 /* NOTE: count not correct if alloc error, but not critical */
1194 mem_cur_size += malloc_usable_size(ptr1);
1195 if (mem_cur_size > mem_max_size)
1196 mem_max_size = mem_cur_size;
1197 #endif
1198 return ptr1;
1201 static char *tcc_strdup(const char *str)
1203 char *ptr;
1204 ptr = tcc_malloc(strlen(str) + 1);
1205 strcpy(ptr, str);
1206 return ptr;
1209 #define free(p) use_tcc_free(p)
1210 #define malloc(s) use_tcc_malloc(s)
1211 #define realloc(p, s) use_tcc_realloc(p, s)
1213 static void dynarray_add(void ***ptab, int *nb_ptr, void *data)
1215 int nb, nb_alloc;
1216 void **pp;
1218 nb = *nb_ptr;
1219 pp = *ptab;
1220 /* every power of two we double array size */
1221 if ((nb & (nb - 1)) == 0) {
1222 if (!nb)
1223 nb_alloc = 1;
1224 else
1225 nb_alloc = nb * 2;
1226 pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
1227 if (!pp)
1228 error("memory full");
1229 *ptab = pp;
1231 pp[nb++] = data;
1232 *nb_ptr = nb;
1235 static void dynarray_reset(void *pp, int *n)
1237 void **p;
1238 for (p = *(void***)pp; *n; ++p, --*n)
1239 if (*p)
1240 tcc_free(*p);
1241 tcc_free(*(void**)pp);
1242 *(void**)pp = NULL;
1245 /* symbol allocator */
1246 static Sym *__sym_malloc(void)
1248 Sym *sym_pool, *sym, *last_sym;
1249 int i;
1251 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
1252 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
1254 last_sym = sym_free_first;
1255 sym = sym_pool;
1256 for(i = 0; i < SYM_POOL_NB; i++) {
1257 sym->next = last_sym;
1258 last_sym = sym;
1259 sym++;
1261 sym_free_first = last_sym;
1262 return last_sym;
1265 static inline Sym *sym_malloc(void)
1267 Sym *sym;
1268 sym = sym_free_first;
1269 if (!sym)
1270 sym = __sym_malloc();
1271 sym_free_first = sym->next;
1272 return sym;
1275 static inline void sym_free(Sym *sym)
1277 sym->next = sym_free_first;
1278 sym_free_first = sym;
1281 Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags)
1283 Section *sec;
1285 sec = tcc_mallocz(sizeof(Section) + strlen(name));
1286 strcpy(sec->name, name);
1287 sec->sh_type = sh_type;
1288 sec->sh_flags = sh_flags;
1289 switch(sh_type) {
1290 case SHT_HASH:
1291 case SHT_REL:
1292 case SHT_RELA:
1293 case SHT_DYNSYM:
1294 case SHT_SYMTAB:
1295 case SHT_DYNAMIC:
1296 sec->sh_addralign = 4;
1297 break;
1298 case SHT_STRTAB:
1299 sec->sh_addralign = 1;
1300 break;
1301 default:
1302 sec->sh_addralign = 32; /* default conservative alignment */
1303 break;
1306 if (sh_flags & SHF_PRIVATE) {
1307 dynarray_add((void ***)&s1->priv_sections, &s1->nb_priv_sections, sec);
1308 } else {
1309 sec->sh_num = s1->nb_sections;
1310 dynarray_add((void ***)&s1->sections, &s1->nb_sections, sec);
1313 return sec;
1316 static void free_section(Section *s)
1318 tcc_free(s->data);
1321 /* realloc section and set its content to zero */
1322 static void section_realloc(Section *sec, unsigned long new_size)
1324 unsigned long size;
1325 unsigned char *data;
1327 size = sec->data_allocated;
1328 if (size == 0)
1329 size = 1;
1330 while (size < new_size)
1331 size = size * 2;
1332 data = tcc_realloc(sec->data, size);
1333 if (!data)
1334 error("memory full");
1335 memset(data + sec->data_allocated, 0, size - sec->data_allocated);
1336 sec->data = data;
1337 sec->data_allocated = size;
1340 /* reserve at least 'size' bytes in section 'sec' from
1341 sec->data_offset. */
1342 static void *section_ptr_add(Section *sec, unsigned long size)
1344 unsigned long offset, offset1;
1346 offset = sec->data_offset;
1347 offset1 = offset + size;
1348 if (offset1 > sec->data_allocated)
1349 section_realloc(sec, offset1);
1350 sec->data_offset = offset1;
1351 return sec->data + offset;
1354 /* return a reference to a section, and create it if it does not
1355 exists */
1356 Section *find_section(TCCState *s1, const char *name)
1358 Section *sec;
1359 int i;
1360 for(i = 1; i < s1->nb_sections; i++) {
1361 sec = s1->sections[i];
1362 if (!strcmp(name, sec->name))
1363 return sec;
1365 /* sections are created as PROGBITS */
1366 return new_section(s1, name, SHT_PROGBITS, SHF_ALLOC);
1369 #define SECTION_ABS ((void *)1)
1371 /* update sym->c so that it points to an external symbol in section
1372 'section' with value 'value' */
1373 static void put_extern_sym2(Sym *sym, Section *section,
1374 unsigned long value, unsigned long size,
1375 int can_add_underscore)
1377 int sym_type, sym_bind, sh_num, info, other, attr;
1378 ElfW(Sym) *esym;
1379 const char *name;
1380 char buf1[256];
1382 if (section == NULL)
1383 sh_num = SHN_UNDEF;
1384 else if (section == SECTION_ABS)
1385 sh_num = SHN_ABS;
1386 else
1387 sh_num = section->sh_num;
1389 other = attr = 0;
1391 if ((sym->type.t & VT_BTYPE) == VT_FUNC) {
1392 sym_type = STT_FUNC;
1393 #ifdef TCC_TARGET_PE
1394 if (sym->type.ref)
1395 attr = sym->type.ref->r;
1396 if (FUNC_EXPORT(attr))
1397 other |= 1;
1398 if (FUNC_CALL(attr) == FUNC_STDCALL)
1399 other |= 2;
1400 #endif
1401 } else {
1402 sym_type = STT_OBJECT;
1405 if (sym->type.t & VT_STATIC)
1406 sym_bind = STB_LOCAL;
1407 else
1408 sym_bind = STB_GLOBAL;
1410 if (!sym->c) {
1411 name = get_tok_str(sym->v, NULL);
1412 #ifdef CONFIG_TCC_BCHECK
1413 if (do_bounds_check) {
1414 char buf[32];
1416 /* XXX: avoid doing that for statics ? */
1417 /* if bound checking is activated, we change some function
1418 names by adding the "__bound" prefix */
1419 switch(sym->v) {
1420 #if 0
1421 /* XXX: we rely only on malloc hooks */
1422 case TOK_malloc:
1423 case TOK_free:
1424 case TOK_realloc:
1425 case TOK_memalign:
1426 case TOK_calloc:
1427 #endif
1428 case TOK_memcpy:
1429 case TOK_memmove:
1430 case TOK_memset:
1431 case TOK_strlen:
1432 case TOK_strcpy:
1433 case TOK__alloca:
1434 strcpy(buf, "__bound_");
1435 strcat(buf, name);
1436 name = buf;
1437 break;
1440 #endif
1442 #ifdef TCC_TARGET_PE
1443 if ((other & 2) && can_add_underscore) {
1444 sprintf(buf1, "_%s@%d", name, FUNC_ARGS(attr));
1445 name = buf1;
1446 } else
1447 #endif
1448 if (tcc_state->leading_underscore && can_add_underscore) {
1449 buf1[0] = '_';
1450 pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
1451 name = buf1;
1453 info = ELFW(ST_INFO)(sym_bind, sym_type);
1454 sym->c = add_elf_sym(symtab_section, value, size, info, other, sh_num, name);
1455 } else {
1456 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
1457 esym->st_value = value;
1458 esym->st_size = size;
1459 esym->st_shndx = sh_num;
1460 esym->st_other |= other;
1464 static void put_extern_sym(Sym *sym, Section *section,
1465 unsigned long value, unsigned long size)
1467 put_extern_sym2(sym, section, value, size, 1);
1470 /* add a new relocation entry to symbol 'sym' in section 's' */
1471 static void greloc(Section *s, Sym *sym, unsigned long offset, int type)
1473 if (!sym->c)
1474 put_extern_sym(sym, NULL, 0, 0);
1475 /* now we can add ELF relocation info */
1476 put_elf_reloc(symtab_section, s, offset, type, sym->c);
1479 static inline int isid(int c)
1481 return (c >= 'a' && c <= 'z') ||
1482 (c >= 'A' && c <= 'Z') ||
1483 c == '_';
1486 static inline int isnum(int c)
1488 return c >= '0' && c <= '9';
1491 static inline int isoct(int c)
1493 return c >= '0' && c <= '7';
1496 static inline int toup(int c)
1498 if (c >= 'a' && c <= 'z')
1499 return c - 'a' + 'A';
1500 else
1501 return c;
1504 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
1506 int len;
1507 len = strlen(buf);
1508 vsnprintf(buf + len, buf_size - len, fmt, ap);
1511 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
1513 va_list ap;
1514 va_start(ap, fmt);
1515 strcat_vprintf(buf, buf_size, fmt, ap);
1516 va_end(ap);
1519 void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
1521 char buf[2048];
1522 BufferedFile **f;
1524 buf[0] = '\0';
1525 if (file) {
1526 for(f = s1->include_stack; f < s1->include_stack_ptr; f++)
1527 strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
1528 (*f)->filename, (*f)->line_num);
1529 if (file->line_num > 0) {
1530 strcat_printf(buf, sizeof(buf),
1531 "%s:%d: ", file->filename, file->line_num);
1532 } else {
1533 strcat_printf(buf, sizeof(buf),
1534 "%s: ", file->filename);
1536 } else {
1537 strcat_printf(buf, sizeof(buf),
1538 "tcc: ");
1540 if (is_warning)
1541 strcat_printf(buf, sizeof(buf), "warning: ");
1542 strcat_vprintf(buf, sizeof(buf), fmt, ap);
1544 if (!s1->error_func) {
1545 /* default case: stderr */
1546 fprintf(stderr, "%s\n", buf);
1547 } else {
1548 s1->error_func(s1->error_opaque, buf);
1550 if (!is_warning || s1->warn_error)
1551 s1->nb_errors++;
1554 #ifdef LIBTCC
1555 void tcc_set_error_func(TCCState *s, void *error_opaque,
1556 void (*error_func)(void *opaque, const char *msg))
1558 s->error_opaque = error_opaque;
1559 s->error_func = error_func;
1561 #endif
1563 /* error without aborting current compilation */
1564 void error_noabort(const char *fmt, ...)
1566 TCCState *s1 = tcc_state;
1567 va_list ap;
1569 va_start(ap, fmt);
1570 error1(s1, 0, fmt, ap);
1571 va_end(ap);
1574 void error(const char *fmt, ...)
1576 TCCState *s1 = tcc_state;
1577 va_list ap;
1579 va_start(ap, fmt);
1580 error1(s1, 0, fmt, ap);
1581 va_end(ap);
1582 /* better than nothing: in some cases, we accept to handle errors */
1583 if (s1->error_set_jmp_enabled) {
1584 longjmp(s1->error_jmp_buf, 1);
1585 } else {
1586 /* XXX: eliminate this someday */
1587 exit(1);
1591 void expect(const char *msg)
1593 error("%s expected", msg);
1596 void warning(const char *fmt, ...)
1598 TCCState *s1 = tcc_state;
1599 va_list ap;
1601 if (s1->warn_none)
1602 return;
1604 va_start(ap, fmt);
1605 error1(s1, 1, fmt, ap);
1606 va_end(ap);
1609 void skip(int c)
1611 if (tok != c)
1612 error("'%c' expected", c);
1613 next();
1616 static void test_lvalue(void)
1618 if (!(vtop->r & VT_LVAL))
1619 expect("lvalue");
1622 /* allocate a new token */
1623 static TokenSym *tok_alloc_new(TokenSym **pts, const char *str, int len)
1625 TokenSym *ts, **ptable;
1626 int i;
1628 if (tok_ident >= SYM_FIRST_ANOM)
1629 error("memory full");
1631 /* expand token table if needed */
1632 i = tok_ident - TOK_IDENT;
1633 if ((i % TOK_ALLOC_INCR) == 0) {
1634 ptable = tcc_realloc(table_ident, (i + TOK_ALLOC_INCR) * sizeof(TokenSym *));
1635 if (!ptable)
1636 error("memory full");
1637 table_ident = ptable;
1640 ts = tcc_malloc(sizeof(TokenSym) + len);
1641 table_ident[i] = ts;
1642 ts->tok = tok_ident++;
1643 ts->sym_define = NULL;
1644 ts->sym_label = NULL;
1645 ts->sym_struct = NULL;
1646 ts->sym_identifier = NULL;
1647 ts->len = len;
1648 ts->hash_next = NULL;
1649 memcpy(ts->str, str, len);
1650 ts->str[len] = '\0';
1651 *pts = ts;
1652 return ts;
1655 #define TOK_HASH_INIT 1
1656 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
1658 /* find a token and add it if not found */
1659 static TokenSym *tok_alloc(const char *str, int len)
1661 TokenSym *ts, **pts;
1662 int i;
1663 unsigned int h;
1665 h = TOK_HASH_INIT;
1666 for(i=0;i<len;i++)
1667 h = TOK_HASH_FUNC(h, ((unsigned char *)str)[i]);
1668 h &= (TOK_HASH_SIZE - 1);
1670 pts = &hash_ident[h];
1671 for(;;) {
1672 ts = *pts;
1673 if (!ts)
1674 break;
1675 if (ts->len == len && !memcmp(ts->str, str, len))
1676 return ts;
1677 pts = &(ts->hash_next);
1679 return tok_alloc_new(pts, str, len);
1682 /* CString handling */
1684 static void cstr_realloc(CString *cstr, int new_size)
1686 int size;
1687 void *data;
1689 size = cstr->size_allocated;
1690 if (size == 0)
1691 size = 8; /* no need to allocate a too small first string */
1692 while (size < new_size)
1693 size = size * 2;
1694 data = tcc_realloc(cstr->data_allocated, size);
1695 if (!data)
1696 error("memory full");
1697 cstr->data_allocated = data;
1698 cstr->size_allocated = size;
1699 cstr->data = data;
1702 /* add a byte */
1703 static inline void cstr_ccat(CString *cstr, int ch)
1705 int size;
1706 size = cstr->size + 1;
1707 if (size > cstr->size_allocated)
1708 cstr_realloc(cstr, size);
1709 ((unsigned char *)cstr->data)[size - 1] = ch;
1710 cstr->size = size;
1713 static void cstr_cat(CString *cstr, const char *str)
1715 int c;
1716 for(;;) {
1717 c = *str;
1718 if (c == '\0')
1719 break;
1720 cstr_ccat(cstr, c);
1721 str++;
1725 /* add a wide char */
1726 static void cstr_wccat(CString *cstr, int ch)
1728 int size;
1729 size = cstr->size + sizeof(nwchar_t);
1730 if (size > cstr->size_allocated)
1731 cstr_realloc(cstr, size);
1732 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
1733 cstr->size = size;
1736 static void cstr_new(CString *cstr)
1738 memset(cstr, 0, sizeof(CString));
1741 /* free string and reset it to NULL */
1742 static void cstr_free(CString *cstr)
1744 tcc_free(cstr->data_allocated);
1745 cstr_new(cstr);
1748 #define cstr_reset(cstr) cstr_free(cstr)
1750 /* XXX: unicode ? */
1751 static void add_char(CString *cstr, int c)
1753 if (c == '\'' || c == '\"' || c == '\\') {
1754 /* XXX: could be more precise if char or string */
1755 cstr_ccat(cstr, '\\');
1757 if (c >= 32 && c <= 126) {
1758 cstr_ccat(cstr, c);
1759 } else {
1760 cstr_ccat(cstr, '\\');
1761 if (c == '\n') {
1762 cstr_ccat(cstr, 'n');
1763 } else {
1764 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
1765 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
1766 cstr_ccat(cstr, '0' + (c & 7));
1771 /* XXX: buffer overflow */
1772 /* XXX: float tokens */
1773 char *get_tok_str(int v, CValue *cv)
1775 static char buf[STRING_MAX_SIZE + 1];
1776 static CString cstr_buf;
1777 CString *cstr;
1778 unsigned char *q;
1779 char *p;
1780 int i, len;
1782 /* NOTE: to go faster, we give a fixed buffer for small strings */
1783 cstr_reset(&cstr_buf);
1784 cstr_buf.data = buf;
1785 cstr_buf.size_allocated = sizeof(buf);
1786 p = buf;
1788 switch(v) {
1789 case TOK_CINT:
1790 case TOK_CUINT:
1791 /* XXX: not quite exact, but only useful for testing */
1792 sprintf(p, "%u", cv->ui);
1793 break;
1794 case TOK_CLLONG:
1795 case TOK_CULLONG:
1796 /* XXX: not quite exact, but only useful for testing */
1797 sprintf(p, "%Lu", cv->ull);
1798 break;
1799 case TOK_LCHAR:
1800 cstr_ccat(&cstr_buf, 'L');
1801 case TOK_CCHAR:
1802 cstr_ccat(&cstr_buf, '\'');
1803 add_char(&cstr_buf, cv->i);
1804 cstr_ccat(&cstr_buf, '\'');
1805 cstr_ccat(&cstr_buf, '\0');
1806 break;
1807 case TOK_PPNUM:
1808 cstr = cv->cstr;
1809 len = cstr->size - 1;
1810 for(i=0;i<len;i++)
1811 add_char(&cstr_buf, ((unsigned char *)cstr->data)[i]);
1812 cstr_ccat(&cstr_buf, '\0');
1813 break;
1814 case TOK_LSTR:
1815 cstr_ccat(&cstr_buf, 'L');
1816 case TOK_STR:
1817 cstr = cv->cstr;
1818 cstr_ccat(&cstr_buf, '\"');
1819 if (v == TOK_STR) {
1820 len = cstr->size - 1;
1821 for(i=0;i<len;i++)
1822 add_char(&cstr_buf, ((unsigned char *)cstr->data)[i]);
1823 } else {
1824 len = (cstr->size / sizeof(nwchar_t)) - 1;
1825 for(i=0;i<len;i++)
1826 add_char(&cstr_buf, ((nwchar_t *)cstr->data)[i]);
1828 cstr_ccat(&cstr_buf, '\"');
1829 cstr_ccat(&cstr_buf, '\0');
1830 break;
1831 case TOK_LT:
1832 v = '<';
1833 goto addv;
1834 case TOK_GT:
1835 v = '>';
1836 goto addv;
1837 case TOK_DOTS:
1838 return strcpy(p, "...");
1839 case TOK_A_SHL:
1840 return strcpy(p, "<<=");
1841 case TOK_A_SAR:
1842 return strcpy(p, ">>=");
1843 default:
1844 if (v < TOK_IDENT) {
1845 /* search in two bytes table */
1846 q = tok_two_chars;
1847 while (*q) {
1848 if (q[2] == v) {
1849 *p++ = q[0];
1850 *p++ = q[1];
1851 *p = '\0';
1852 return buf;
1854 q += 3;
1856 addv:
1857 *p++ = v;
1858 *p = '\0';
1859 } else if (v < tok_ident) {
1860 return table_ident[v - TOK_IDENT]->str;
1861 } else if (v >= SYM_FIRST_ANOM) {
1862 /* special name for anonymous symbol */
1863 sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
1864 } else {
1865 /* should never happen */
1866 return NULL;
1868 break;
1870 return cstr_buf.data;
1873 /* push, without hashing */
1874 static Sym *sym_push2(Sym **ps, int v, int t, long c)
1876 Sym *s;
1877 s = sym_malloc();
1878 s->v = v;
1879 s->type.t = t;
1880 s->c = c;
1881 s->next = NULL;
1882 /* add in stack */
1883 s->prev = *ps;
1884 *ps = s;
1885 return s;
1888 /* find a symbol and return its associated structure. 's' is the top
1889 of the symbol stack */
1890 static Sym *sym_find2(Sym *s, int v)
1892 while (s) {
1893 if (s->v == v)
1894 return s;
1895 s = s->prev;
1897 return NULL;
1900 /* structure lookup */
1901 static inline Sym *struct_find(int v)
1903 v -= TOK_IDENT;
1904 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1905 return NULL;
1906 return table_ident[v]->sym_struct;
1909 /* find an identifier */
1910 static inline Sym *sym_find(int v)
1912 v -= TOK_IDENT;
1913 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1914 return NULL;
1915 return table_ident[v]->sym_identifier;
1918 /* push a given symbol on the symbol stack */
1919 static Sym *sym_push(int v, CType *type, int r, int c)
1921 Sym *s, **ps;
1922 TokenSym *ts;
1924 if (local_stack)
1925 ps = &local_stack;
1926 else
1927 ps = &global_stack;
1928 s = sym_push2(ps, v, type->t, c);
1929 s->type.ref = type->ref;
1930 s->r = r;
1931 /* don't record fields or anonymous symbols */
1932 /* XXX: simplify */
1933 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
1934 /* record symbol in token array */
1935 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
1936 if (v & SYM_STRUCT)
1937 ps = &ts->sym_struct;
1938 else
1939 ps = &ts->sym_identifier;
1940 s->prev_tok = *ps;
1941 *ps = s;
1943 return s;
1946 /* push a global identifier */
1947 static Sym *global_identifier_push(int v, int t, int c)
1949 Sym *s, **ps;
1950 s = sym_push2(&global_stack, v, t, c);
1951 /* don't record anonymous symbol */
1952 if (v < SYM_FIRST_ANOM) {
1953 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
1954 /* modify the top most local identifier, so that
1955 sym_identifier will point to 's' when popped */
1956 while (*ps != NULL)
1957 ps = &(*ps)->prev_tok;
1958 s->prev_tok = NULL;
1959 *ps = s;
1961 return s;
1964 /* pop symbols until top reaches 'b' */
1965 static void sym_pop(Sym **ptop, Sym *b)
1967 Sym *s, *ss, **ps;
1968 TokenSym *ts;
1969 int v;
1971 s = *ptop;
1972 while(s != b) {
1973 ss = s->prev;
1974 v = s->v;
1975 /* remove symbol in token array */
1976 /* XXX: simplify */
1977 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
1978 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
1979 if (v & SYM_STRUCT)
1980 ps = &ts->sym_struct;
1981 else
1982 ps = &ts->sym_identifier;
1983 *ps = s->prev_tok;
1985 sym_free(s);
1986 s = ss;
1988 *ptop = b;
1991 /* I/O layer */
1993 BufferedFile *tcc_open(TCCState *s1, const char *filename)
1995 int fd;
1996 BufferedFile *bf;
1998 if (strcmp(filename, "-") == 0)
1999 fd = 0, filename = "stdin";
2000 else
2001 fd = open(filename, O_RDONLY | O_BINARY);
2002 if ((verbose == 2 && fd >= 0) || verbose == 3)
2003 printf("%s %*s%s\n", fd < 0 ? "nf":"->",
2004 (s1->include_stack_ptr - s1->include_stack), "", filename);
2005 if (fd < 0)
2006 return NULL;
2007 bf = tcc_malloc(sizeof(BufferedFile));
2008 bf->fd = fd;
2009 bf->buf_ptr = bf->buffer;
2010 bf->buf_end = bf->buffer;
2011 bf->buffer[0] = CH_EOB; /* put eob symbol */
2012 pstrcpy(bf->filename, sizeof(bf->filename), filename);
2013 #ifdef _WIN32
2014 normalize_slashes(bf->filename);
2015 #endif
2016 bf->line_num = 1;
2017 bf->ifndef_macro = 0;
2018 bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
2019 // printf("opening '%s'\n", filename);
2020 return bf;
2023 void tcc_close(BufferedFile *bf)
2025 total_lines += bf->line_num;
2026 close(bf->fd);
2027 tcc_free(bf);
2030 /* fill input buffer and peek next char */
2031 static int tcc_peekc_slow(BufferedFile *bf)
2033 int len;
2034 /* only tries to read if really end of buffer */
2035 if (bf->buf_ptr >= bf->buf_end) {
2036 if (bf->fd != -1) {
2037 #if defined(PARSE_DEBUG)
2038 len = 8;
2039 #else
2040 len = IO_BUF_SIZE;
2041 #endif
2042 len = read(bf->fd, bf->buffer, len);
2043 if (len < 0)
2044 len = 0;
2045 } else {
2046 len = 0;
2048 total_bytes += len;
2049 bf->buf_ptr = bf->buffer;
2050 bf->buf_end = bf->buffer + len;
2051 *bf->buf_end = CH_EOB;
2053 if (bf->buf_ptr < bf->buf_end) {
2054 return bf->buf_ptr[0];
2055 } else {
2056 bf->buf_ptr = bf->buf_end;
2057 return CH_EOF;
2061 /* return the current character, handling end of block if necessary
2062 (but not stray) */
2063 static int handle_eob(void)
2065 return tcc_peekc_slow(file);
2068 /* read next char from current input file and handle end of input buffer */
2069 static inline void inp(void)
2071 ch = *(++(file->buf_ptr));
2072 /* end of buffer/file handling */
2073 if (ch == CH_EOB)
2074 ch = handle_eob();
2077 /* handle '\[\r]\n' */
2078 static int handle_stray_noerror(void)
2080 while (ch == '\\') {
2081 inp();
2082 if (ch == '\n') {
2083 file->line_num++;
2084 inp();
2085 } else if (ch == '\r') {
2086 inp();
2087 if (ch != '\n')
2088 goto fail;
2089 file->line_num++;
2090 inp();
2091 } else {
2092 fail:
2093 return 1;
2096 return 0;
2099 static void handle_stray(void)
2101 if (handle_stray_noerror())
2102 error("stray '\\' in program");
2105 /* skip the stray and handle the \\n case. Output an error if
2106 incorrect char after the stray */
2107 static int handle_stray1(uint8_t *p)
2109 int c;
2111 if (p >= file->buf_end) {
2112 file->buf_ptr = p;
2113 c = handle_eob();
2114 p = file->buf_ptr;
2115 if (c == '\\')
2116 goto parse_stray;
2117 } else {
2118 parse_stray:
2119 file->buf_ptr = p;
2120 ch = *p;
2121 handle_stray();
2122 p = file->buf_ptr;
2123 c = *p;
2125 return c;
2128 /* handle just the EOB case, but not stray */
2129 #define PEEKC_EOB(c, p)\
2131 p++;\
2132 c = *p;\
2133 if (c == '\\') {\
2134 file->buf_ptr = p;\
2135 c = handle_eob();\
2136 p = file->buf_ptr;\
2140 /* handle the complicated stray case */
2141 #define PEEKC(c, p)\
2143 p++;\
2144 c = *p;\
2145 if (c == '\\') {\
2146 c = handle_stray1(p);\
2147 p = file->buf_ptr;\
2151 /* input with '\[\r]\n' handling. Note that this function cannot
2152 handle other characters after '\', so you cannot call it inside
2153 strings or comments */
2154 static void minp(void)
2156 inp();
2157 if (ch == '\\')
2158 handle_stray();
2162 /* single line C++ comments */
2163 static uint8_t *parse_line_comment(uint8_t *p)
2165 int c;
2167 p++;
2168 for(;;) {
2169 c = *p;
2170 redo:
2171 if (c == '\n' || c == CH_EOF) {
2172 break;
2173 } else if (c == '\\') {
2174 file->buf_ptr = p;
2175 c = handle_eob();
2176 p = file->buf_ptr;
2177 if (c == '\\') {
2178 PEEKC_EOB(c, p);
2179 if (c == '\n') {
2180 file->line_num++;
2181 PEEKC_EOB(c, p);
2182 } else if (c == '\r') {
2183 PEEKC_EOB(c, p);
2184 if (c == '\n') {
2185 file->line_num++;
2186 PEEKC_EOB(c, p);
2189 } else {
2190 goto redo;
2192 } else {
2193 p++;
2196 return p;
2199 /* C comments */
2200 static uint8_t *parse_comment(uint8_t *p)
2202 int c;
2204 p++;
2205 for(;;) {
2206 /* fast skip loop */
2207 for(;;) {
2208 c = *p;
2209 if (c == '\n' || c == '*' || c == '\\')
2210 break;
2211 p++;
2212 c = *p;
2213 if (c == '\n' || c == '*' || c == '\\')
2214 break;
2215 p++;
2217 /* now we can handle all the cases */
2218 if (c == '\n') {
2219 file->line_num++;
2220 p++;
2221 } else if (c == '*') {
2222 p++;
2223 for(;;) {
2224 c = *p;
2225 if (c == '*') {
2226 p++;
2227 } else if (c == '/') {
2228 goto end_of_comment;
2229 } else if (c == '\\') {
2230 file->buf_ptr = p;
2231 c = handle_eob();
2232 p = file->buf_ptr;
2233 if (c == '\\') {
2234 /* skip '\[\r]\n', otherwise just skip the stray */
2235 while (c == '\\') {
2236 PEEKC_EOB(c, p);
2237 if (c == '\n') {
2238 file->line_num++;
2239 PEEKC_EOB(c, p);
2240 } else if (c == '\r') {
2241 PEEKC_EOB(c, p);
2242 if (c == '\n') {
2243 file->line_num++;
2244 PEEKC_EOB(c, p);
2246 } else {
2247 goto after_star;
2251 } else {
2252 break;
2255 after_star: ;
2256 } else {
2257 /* stray, eob or eof */
2258 file->buf_ptr = p;
2259 c = handle_eob();
2260 p = file->buf_ptr;
2261 if (c == CH_EOF) {
2262 error("unexpected end of file in comment");
2263 } else if (c == '\\') {
2264 p++;
2268 end_of_comment:
2269 p++;
2270 return p;
2273 #define cinp minp
2275 /* space exlcuding newline */
2276 static inline int is_space(int ch)
2278 return ch == ' ' || ch == '\t' || ch == '\v' || ch == '\f' || ch == '\r';
2281 static inline void skip_spaces(void)
2283 while (is_space(ch))
2284 cinp();
2287 /* parse a string without interpreting escapes */
2288 static uint8_t *parse_pp_string(uint8_t *p,
2289 int sep, CString *str)
2291 int c;
2292 p++;
2293 for(;;) {
2294 c = *p;
2295 if (c == sep) {
2296 break;
2297 } else if (c == '\\') {
2298 file->buf_ptr = p;
2299 c = handle_eob();
2300 p = file->buf_ptr;
2301 if (c == CH_EOF) {
2302 unterminated_string:
2303 /* XXX: indicate line number of start of string */
2304 error("missing terminating %c character", sep);
2305 } else if (c == '\\') {
2306 /* escape : just skip \[\r]\n */
2307 PEEKC_EOB(c, p);
2308 if (c == '\n') {
2309 file->line_num++;
2310 p++;
2311 } else if (c == '\r') {
2312 PEEKC_EOB(c, p);
2313 if (c != '\n')
2314 expect("'\n' after '\r'");
2315 file->line_num++;
2316 p++;
2317 } else if (c == CH_EOF) {
2318 goto unterminated_string;
2319 } else {
2320 if (str) {
2321 cstr_ccat(str, '\\');
2322 cstr_ccat(str, c);
2324 p++;
2327 } else if (c == '\n') {
2328 file->line_num++;
2329 goto add_char;
2330 } else if (c == '\r') {
2331 PEEKC_EOB(c, p);
2332 if (c != '\n') {
2333 if (str)
2334 cstr_ccat(str, '\r');
2335 } else {
2336 file->line_num++;
2337 goto add_char;
2339 } else {
2340 add_char:
2341 if (str)
2342 cstr_ccat(str, c);
2343 p++;
2346 p++;
2347 return p;
2350 /* skip block of text until #else, #elif or #endif. skip also pairs of
2351 #if/#endif */
2352 void preprocess_skip(void)
2354 int a, start_of_line, c, in_warn_or_error;
2355 uint8_t *p;
2357 p = file->buf_ptr;
2358 a = 0;
2359 redo_start:
2360 start_of_line = 1;
2361 in_warn_or_error = 0;
2362 for(;;) {
2363 redo_no_start:
2364 c = *p;
2365 switch(c) {
2366 case ' ':
2367 case '\t':
2368 case '\f':
2369 case '\v':
2370 case '\r':
2371 p++;
2372 goto redo_no_start;
2373 case '\n':
2374 file->line_num++;
2375 p++;
2376 goto redo_start;
2377 case '\\':
2378 file->buf_ptr = p;
2379 c = handle_eob();
2380 if (c == CH_EOF) {
2381 expect("#endif");
2382 } else if (c == '\\') {
2383 ch = file->buf_ptr[0];
2384 handle_stray_noerror();
2386 p = file->buf_ptr;
2387 goto redo_no_start;
2388 /* skip strings */
2389 case '\"':
2390 case '\'':
2391 if (in_warn_or_error)
2392 goto _default;
2393 p = parse_pp_string(p, c, NULL);
2394 break;
2395 /* skip comments */
2396 case '/':
2397 if (in_warn_or_error)
2398 goto _default;
2399 file->buf_ptr = p;
2400 ch = *p;
2401 minp();
2402 p = file->buf_ptr;
2403 if (ch == '*') {
2404 p = parse_comment(p);
2405 } else if (ch == '/') {
2406 p = parse_line_comment(p);
2408 break;
2409 case '#':
2410 p++;
2411 if (start_of_line) {
2412 file->buf_ptr = p;
2413 next_nomacro();
2414 p = file->buf_ptr;
2415 if (a == 0 &&
2416 (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
2417 goto the_end;
2418 if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
2419 a++;
2420 else if (tok == TOK_ENDIF)
2421 a--;
2422 else if( tok == TOK_ERROR || tok == TOK_WARNING)
2423 in_warn_or_error = 1;
2425 break;
2426 _default:
2427 default:
2428 p++;
2429 break;
2431 start_of_line = 0;
2433 the_end: ;
2434 file->buf_ptr = p;
2437 /* ParseState handling */
2439 /* XXX: currently, no include file info is stored. Thus, we cannot display
2440 accurate messages if the function or data definition spans multiple
2441 files */
2443 /* save current parse state in 's' */
2444 void save_parse_state(ParseState *s)
2446 s->line_num = file->line_num;
2447 s->macro_ptr = macro_ptr;
2448 s->tok = tok;
2449 s->tokc = tokc;
2452 /* restore parse state from 's' */
2453 void restore_parse_state(ParseState *s)
2455 file->line_num = s->line_num;
2456 macro_ptr = s->macro_ptr;
2457 tok = s->tok;
2458 tokc = s->tokc;
2461 /* return the number of additional 'ints' necessary to store the
2462 token */
2463 static inline int tok_ext_size(int t)
2465 switch(t) {
2466 /* 4 bytes */
2467 case TOK_CINT:
2468 case TOK_CUINT:
2469 case TOK_CCHAR:
2470 case TOK_LCHAR:
2471 case TOK_CFLOAT:
2472 case TOK_LINENUM:
2473 return 1;
2474 case TOK_STR:
2475 case TOK_LSTR:
2476 case TOK_PPNUM:
2477 error("unsupported token");
2478 return 1;
2479 case TOK_CDOUBLE:
2480 case TOK_CLLONG:
2481 case TOK_CULLONG:
2482 return 2;
2483 case TOK_CLDOUBLE:
2484 return LDOUBLE_SIZE / 4;
2485 default:
2486 return 0;
2490 /* token string handling */
2492 static inline void tok_str_new(TokenString *s)
2494 s->str = NULL;
2495 s->len = 0;
2496 s->allocated_len = 0;
2497 s->last_line_num = -1;
2500 static void tok_str_free(int *str)
2502 tcc_free(str);
2505 static int *tok_str_realloc(TokenString *s)
2507 int *str, len;
2509 if (s->allocated_len == 0) {
2510 len = 8;
2511 } else {
2512 len = s->allocated_len * 2;
2514 str = tcc_realloc(s->str, len * sizeof(int));
2515 if (!str)
2516 error("memory full");
2517 s->allocated_len = len;
2518 s->str = str;
2519 return str;
2522 static void tok_str_add(TokenString *s, int t)
2524 int len, *str;
2526 len = s->len;
2527 str = s->str;
2528 if (len >= s->allocated_len)
2529 str = tok_str_realloc(s);
2530 str[len++] = t;
2531 s->len = len;
2534 static void tok_str_add2(TokenString *s, int t, CValue *cv)
2536 int len, *str;
2538 len = s->len;
2539 str = s->str;
2541 /* allocate space for worst case */
2542 if (len + TOK_MAX_SIZE > s->allocated_len)
2543 str = tok_str_realloc(s);
2544 str[len++] = t;
2545 switch(t) {
2546 case TOK_CINT:
2547 case TOK_CUINT:
2548 case TOK_CCHAR:
2549 case TOK_LCHAR:
2550 case TOK_CFLOAT:
2551 case TOK_LINENUM:
2552 str[len++] = cv->tab[0];
2553 break;
2554 case TOK_PPNUM:
2555 case TOK_STR:
2556 case TOK_LSTR:
2558 int nb_words;
2559 CString *cstr;
2561 nb_words = (sizeof(CString) + cv->cstr->size + 3) >> 2;
2562 while ((len + nb_words) > s->allocated_len)
2563 str = tok_str_realloc(s);
2564 cstr = (CString *)(str + len);
2565 cstr->data = NULL;
2566 cstr->size = cv->cstr->size;
2567 cstr->data_allocated = NULL;
2568 cstr->size_allocated = cstr->size;
2569 memcpy((char *)cstr + sizeof(CString),
2570 cv->cstr->data, cstr->size);
2571 len += nb_words;
2573 break;
2574 case TOK_CDOUBLE:
2575 case TOK_CLLONG:
2576 case TOK_CULLONG:
2577 #if LDOUBLE_SIZE == 8
2578 case TOK_CLDOUBLE:
2579 #endif
2580 str[len++] = cv->tab[0];
2581 str[len++] = cv->tab[1];
2582 break;
2583 #if LDOUBLE_SIZE == 12
2584 case TOK_CLDOUBLE:
2585 str[len++] = cv->tab[0];
2586 str[len++] = cv->tab[1];
2587 str[len++] = cv->tab[2];
2588 #elif LDOUBLE_SIZE == 16
2589 case TOK_CLDOUBLE:
2590 str[len++] = cv->tab[0];
2591 str[len++] = cv->tab[1];
2592 str[len++] = cv->tab[2];
2593 str[len++] = cv->tab[3];
2594 #elif LDOUBLE_SIZE != 8
2595 #error add long double size support
2596 #endif
2597 break;
2598 default:
2599 break;
2601 s->len = len;
2604 /* add the current parse token in token string 's' */
2605 static void tok_str_add_tok(TokenString *s)
2607 CValue cval;
2609 /* save line number info */
2610 if (file->line_num != s->last_line_num) {
2611 s->last_line_num = file->line_num;
2612 cval.i = s->last_line_num;
2613 tok_str_add2(s, TOK_LINENUM, &cval);
2615 tok_str_add2(s, tok, &tokc);
2618 #if LDOUBLE_SIZE == 16
2619 #define LDOUBLE_GET(p, cv) \
2620 cv.tab[0] = p[0]; \
2621 cv.tab[1] = p[1]; \
2622 cv.tab[2] = p[2]; \
2623 cv.tab[3] = p[3];
2624 #elif LDOUBLE_SIZE == 12
2625 #define LDOUBLE_GET(p, cv) \
2626 cv.tab[0] = p[0]; \
2627 cv.tab[1] = p[1]; \
2628 cv.tab[2] = p[2];
2629 #elif LDOUBLE_SIZE == 8
2630 #define LDOUBLE_GET(p, cv) \
2631 cv.tab[0] = p[0]; \
2632 cv.tab[1] = p[1];
2633 #else
2634 #error add long double size support
2635 #endif
2638 /* get a token from an integer array and increment pointer
2639 accordingly. we code it as a macro to avoid pointer aliasing. */
2640 #define TOK_GET(t, p, cv) \
2642 t = *p++; \
2643 switch(t) { \
2644 case TOK_CINT: \
2645 case TOK_CUINT: \
2646 case TOK_CCHAR: \
2647 case TOK_LCHAR: \
2648 case TOK_CFLOAT: \
2649 case TOK_LINENUM: \
2650 cv.tab[0] = *p++; \
2651 break; \
2652 case TOK_STR: \
2653 case TOK_LSTR: \
2654 case TOK_PPNUM: \
2655 cv.cstr = (CString *)p; \
2656 cv.cstr->data = (char *)p + sizeof(CString);\
2657 p += (sizeof(CString) + cv.cstr->size + 3) >> 2;\
2658 break; \
2659 case TOK_CDOUBLE: \
2660 case TOK_CLLONG: \
2661 case TOK_CULLONG: \
2662 cv.tab[0] = p[0]; \
2663 cv.tab[1] = p[1]; \
2664 p += 2; \
2665 break; \
2666 case TOK_CLDOUBLE: \
2667 LDOUBLE_GET(p, cv); \
2668 p += LDOUBLE_SIZE / 4; \
2669 break; \
2670 default: \
2671 break; \
2675 /* defines handling */
2676 static inline void define_push(int v, int macro_type, int *str, Sym *first_arg)
2678 Sym *s;
2680 s = sym_push2(&define_stack, v, macro_type, (long)str);
2681 s->next = first_arg;
2682 table_ident[v - TOK_IDENT]->sym_define = s;
2685 /* undefined a define symbol. Its name is just set to zero */
2686 static void define_undef(Sym *s)
2688 int v;
2689 v = s->v;
2690 if (v >= TOK_IDENT && v < tok_ident)
2691 table_ident[v - TOK_IDENT]->sym_define = NULL;
2692 s->v = 0;
2695 static inline Sym *define_find(int v)
2697 v -= TOK_IDENT;
2698 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
2699 return NULL;
2700 return table_ident[v]->sym_define;
2703 /* free define stack until top reaches 'b' */
2704 static void free_defines(Sym *b)
2706 Sym *top, *top1;
2707 int v;
2709 top = define_stack;
2710 while (top != b) {
2711 top1 = top->prev;
2712 /* do not free args or predefined defines */
2713 if (top->c)
2714 tok_str_free((int *)top->c);
2715 v = top->v;
2716 if (v >= TOK_IDENT && v < tok_ident)
2717 table_ident[v - TOK_IDENT]->sym_define = NULL;
2718 sym_free(top);
2719 top = top1;
2721 define_stack = b;
2724 /* label lookup */
2725 static Sym *label_find(int v)
2727 v -= TOK_IDENT;
2728 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
2729 return NULL;
2730 return table_ident[v]->sym_label;
2733 static Sym *label_push(Sym **ptop, int v, int flags)
2735 Sym *s, **ps;
2736 s = sym_push2(ptop, v, 0, 0);
2737 s->r = flags;
2738 ps = &table_ident[v - TOK_IDENT]->sym_label;
2739 if (ptop == &global_label_stack) {
2740 /* modify the top most local identifier, so that
2741 sym_identifier will point to 's' when popped */
2742 while (*ps != NULL)
2743 ps = &(*ps)->prev_tok;
2745 s->prev_tok = *ps;
2746 *ps = s;
2747 return s;
2750 /* pop labels until element last is reached. Look if any labels are
2751 undefined. Define symbols if '&&label' was used. */
2752 static void label_pop(Sym **ptop, Sym *slast)
2754 Sym *s, *s1;
2755 for(s = *ptop; s != slast; s = s1) {
2756 s1 = s->prev;
2757 if (s->r == LABEL_DECLARED) {
2758 warning("label '%s' declared but not used", get_tok_str(s->v, NULL));
2759 } else if (s->r == LABEL_FORWARD) {
2760 error("label '%s' used but not defined",
2761 get_tok_str(s->v, NULL));
2762 } else {
2763 if (s->c) {
2764 /* define corresponding symbol. A size of
2765 1 is put. */
2766 put_extern_sym(s, cur_text_section, (long)s->next, 1);
2769 /* remove label */
2770 table_ident[s->v - TOK_IDENT]->sym_label = s->prev_tok;
2771 sym_free(s);
2773 *ptop = slast;
2776 /* eval an expression for #if/#elif */
2777 static int expr_preprocess(void)
2779 int c, t;
2780 TokenString str;
2782 tok_str_new(&str);
2783 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
2784 next(); /* do macro subst */
2785 if (tok == TOK_DEFINED) {
2786 next_nomacro();
2787 t = tok;
2788 if (t == '(')
2789 next_nomacro();
2790 c = define_find(tok) != 0;
2791 if (t == '(')
2792 next_nomacro();
2793 tok = TOK_CINT;
2794 tokc.i = c;
2795 } else if (tok >= TOK_IDENT) {
2796 /* if undefined macro */
2797 tok = TOK_CINT;
2798 tokc.i = 0;
2800 tok_str_add_tok(&str);
2802 tok_str_add(&str, -1); /* simulate end of file */
2803 tok_str_add(&str, 0);
2804 /* now evaluate C constant expression */
2805 macro_ptr = str.str;
2806 next();
2807 c = expr_const();
2808 macro_ptr = NULL;
2809 tok_str_free(str.str);
2810 return c != 0;
2813 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
2814 static void tok_print(int *str)
2816 int t;
2817 CValue cval;
2819 while (1) {
2820 TOK_GET(t, str, cval);
2821 if (!t)
2822 break;
2823 printf(" %s", get_tok_str(t, &cval));
2825 printf("\n");
2827 #endif
2829 /* parse after #define */
2830 static void parse_define(void)
2832 Sym *s, *first, **ps;
2833 int v, t, varg, is_vaargs, c;
2834 TokenString str;
2836 v = tok;
2837 if (v < TOK_IDENT)
2838 error("invalid macro name '%s'", get_tok_str(tok, &tokc));
2839 /* XXX: should check if same macro (ANSI) */
2840 first = NULL;
2841 t = MACRO_OBJ;
2842 /* '(' must be just after macro definition for MACRO_FUNC */
2843 c = file->buf_ptr[0];
2844 if (c == '\\')
2845 c = handle_stray1(file->buf_ptr);
2846 if (c == '(') {
2847 next_nomacro();
2848 next_nomacro();
2849 ps = &first;
2850 while (tok != ')') {
2851 varg = tok;
2852 next_nomacro();
2853 is_vaargs = 0;
2854 if (varg == TOK_DOTS) {
2855 varg = TOK___VA_ARGS__;
2856 is_vaargs = 1;
2857 } else if (tok == TOK_DOTS && gnu_ext) {
2858 is_vaargs = 1;
2859 next_nomacro();
2861 if (varg < TOK_IDENT)
2862 error("badly punctuated parameter list");
2863 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
2864 *ps = s;
2865 ps = &s->next;
2866 if (tok != ',')
2867 break;
2868 next_nomacro();
2870 t = MACRO_FUNC;
2872 tok_str_new(&str);
2873 next_nomacro();
2874 /* EOF testing necessary for '-D' handling */
2875 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
2876 tok_str_add2(&str, tok, &tokc);
2877 next_nomacro();
2879 tok_str_add(&str, 0);
2880 #ifdef PP_DEBUG
2881 printf("define %s %d: ", get_tok_str(v, NULL), t);
2882 tok_print(str.str);
2883 #endif
2884 define_push(v, t, str.str, first);
2887 static inline int hash_cached_include(int type, const char *filename)
2889 const unsigned char *s;
2890 unsigned int h;
2892 h = TOK_HASH_INIT;
2893 h = TOK_HASH_FUNC(h, type);
2894 s = filename;
2895 while (*s) {
2896 h = TOK_HASH_FUNC(h, *s);
2897 s++;
2899 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
2900 return h;
2903 /* XXX: use a token or a hash table to accelerate matching ? */
2904 static CachedInclude *search_cached_include(TCCState *s1,
2905 int type, const char *filename)
2907 CachedInclude *e;
2908 int i, h;
2909 h = hash_cached_include(type, filename);
2910 i = s1->cached_includes_hash[h];
2911 for(;;) {
2912 if (i == 0)
2913 break;
2914 e = s1->cached_includes[i - 1];
2915 if (e->type == type && !strcmp(e->filename, filename))
2916 return e;
2917 i = e->hash_next;
2919 return NULL;
2922 static inline void add_cached_include(TCCState *s1, int type,
2923 const char *filename, int ifndef_macro)
2925 CachedInclude *e;
2926 int h;
2928 if (search_cached_include(s1, type, filename))
2929 return;
2930 #ifdef INC_DEBUG
2931 printf("adding cached '%s' %s\n", filename, get_tok_str(ifndef_macro, NULL));
2932 #endif
2933 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
2934 if (!e)
2935 return;
2936 e->type = type;
2937 strcpy(e->filename, filename);
2938 e->ifndef_macro = ifndef_macro;
2939 dynarray_add((void ***)&s1->cached_includes, &s1->nb_cached_includes, e);
2940 /* add in hash table */
2941 h = hash_cached_include(type, filename);
2942 e->hash_next = s1->cached_includes_hash[h];
2943 s1->cached_includes_hash[h] = s1->nb_cached_includes;
2946 static void pragma_parse(TCCState *s1)
2948 int val;
2950 next();
2951 if (tok == TOK_pack) {
2953 This may be:
2954 #pragma pack(1) // set
2955 #pragma pack() // reset to default
2956 #pragma pack(push,1) // push & set
2957 #pragma pack(pop) // restore previous
2959 next();
2960 skip('(');
2961 if (tok == TOK_ASM_pop) {
2962 next();
2963 if (s1->pack_stack_ptr <= s1->pack_stack) {
2964 stk_error:
2965 error("out of pack stack");
2967 s1->pack_stack_ptr--;
2968 } else {
2969 val = 0;
2970 if (tok != ')') {
2971 if (tok == TOK_ASM_push) {
2972 next();
2973 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
2974 goto stk_error;
2975 s1->pack_stack_ptr++;
2976 skip(',');
2978 if (tok != TOK_CINT) {
2979 pack_error:
2980 error("invalid pack pragma");
2982 val = tokc.i;
2983 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
2984 goto pack_error;
2985 next();
2987 *s1->pack_stack_ptr = val;
2988 skip(')');
2993 /* is_bof is true if first non space token at beginning of file */
2994 static void preprocess(int is_bof)
2996 TCCState *s1 = tcc_state;
2997 int size, i, c, n, saved_parse_flags;
2998 char buf[1024], *q;
2999 char buf1[1024];
3000 BufferedFile *f;
3001 Sym *s;
3002 CachedInclude *e;
3004 saved_parse_flags = parse_flags;
3005 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM |
3006 PARSE_FLAG_LINEFEED;
3007 next_nomacro();
3008 redo:
3009 switch(tok) {
3010 case TOK_DEFINE:
3011 next_nomacro();
3012 parse_define();
3013 break;
3014 case TOK_UNDEF:
3015 next_nomacro();
3016 s = define_find(tok);
3017 /* undefine symbol by putting an invalid name */
3018 if (s)
3019 define_undef(s);
3020 break;
3021 case TOK_INCLUDE:
3022 case TOK_INCLUDE_NEXT:
3023 ch = file->buf_ptr[0];
3024 /* XXX: incorrect if comments : use next_nomacro with a special mode */
3025 skip_spaces();
3026 if (ch == '<') {
3027 c = '>';
3028 goto read_name;
3029 } else if (ch == '\"') {
3030 c = ch;
3031 read_name:
3032 inp();
3033 q = buf;
3034 while (ch != c && ch != '\n' && ch != CH_EOF) {
3035 if ((q - buf) < sizeof(buf) - 1)
3036 *q++ = ch;
3037 if (ch == '\\') {
3038 if (handle_stray_noerror() == 0)
3039 --q;
3040 } else
3041 inp();
3043 *q = '\0';
3044 minp();
3045 #if 0
3046 /* eat all spaces and comments after include */
3047 /* XXX: slightly incorrect */
3048 while (ch1 != '\n' && ch1 != CH_EOF)
3049 inp();
3050 #endif
3051 } else {
3052 /* computed #include : either we have only strings or
3053 we have anything enclosed in '<>' */
3054 next();
3055 buf[0] = '\0';
3056 if (tok == TOK_STR) {
3057 while (tok != TOK_LINEFEED) {
3058 if (tok != TOK_STR) {
3059 include_syntax:
3060 error("'#include' expects \"FILENAME\" or <FILENAME>");
3062 pstrcat(buf, sizeof(buf), (char *)tokc.cstr->data);
3063 next();
3065 c = '\"';
3066 } else {
3067 int len;
3068 while (tok != TOK_LINEFEED) {
3069 pstrcat(buf, sizeof(buf), get_tok_str(tok, &tokc));
3070 next();
3072 len = strlen(buf);
3073 /* check syntax and remove '<>' */
3074 if (len < 2 || buf[0] != '<' || buf[len - 1] != '>')
3075 goto include_syntax;
3076 memmove(buf, buf + 1, len - 2);
3077 buf[len - 2] = '\0';
3078 c = '>';
3082 e = search_cached_include(s1, c, buf);
3083 if (e && define_find(e->ifndef_macro)) {
3084 /* no need to parse the include because the 'ifndef macro'
3085 is defined */
3086 #ifdef INC_DEBUG
3087 printf("%s: skipping %s\n", file->filename, buf);
3088 #endif
3089 } else {
3090 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
3091 error("#include recursion too deep");
3092 /* push current file in stack */
3093 /* XXX: fix current line init */
3094 *s1->include_stack_ptr++ = file;
3096 /* check absolute include path */
3097 if (IS_ABSPATH(buf)) {
3098 f = tcc_open(s1, buf);
3099 if (f)
3100 goto found;
3102 if (c == '\"') {
3103 /* first search in current dir if "header.h" */
3104 size = tcc_basename(file->filename) - file->filename;
3105 if (size > sizeof(buf1) - 1)
3106 size = sizeof(buf1) - 1;
3107 memcpy(buf1, file->filename, size);
3108 buf1[size] = '\0';
3109 pstrcat(buf1, sizeof(buf1), buf);
3110 f = tcc_open(s1, buf1);
3111 if (f) {
3112 if (tok == TOK_INCLUDE_NEXT)
3113 tok = TOK_INCLUDE;
3114 else
3115 goto found;
3118 /* now search in all the include paths */
3119 n = s1->nb_include_paths + s1->nb_sysinclude_paths;
3120 for(i = 0; i < n; i++) {
3121 const char *path;
3122 if (i < s1->nb_include_paths)
3123 path = s1->include_paths[i];
3124 else
3125 path = s1->sysinclude_paths[i - s1->nb_include_paths];
3126 pstrcpy(buf1, sizeof(buf1), path);
3127 pstrcat(buf1, sizeof(buf1), "/");
3128 pstrcat(buf1, sizeof(buf1), buf);
3129 f = tcc_open(s1, buf1);
3130 if (f) {
3131 if (tok == TOK_INCLUDE_NEXT)
3132 tok = TOK_INCLUDE;
3133 else
3134 goto found;
3137 --s1->include_stack_ptr;
3138 error("include file '%s' not found", buf);
3139 break;
3140 found:
3141 #ifdef INC_DEBUG
3142 printf("%s: including %s\n", file->filename, buf1);
3143 #endif
3144 f->inc_type = c;
3145 pstrcpy(f->inc_filename, sizeof(f->inc_filename), buf);
3146 file = f;
3147 /* add include file debug info */
3148 if (do_debug) {
3149 put_stabs(file->filename, N_BINCL, 0, 0, 0);
3151 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
3152 ch = file->buf_ptr[0];
3153 goto the_end;
3155 break;
3156 case TOK_IFNDEF:
3157 c = 1;
3158 goto do_ifdef;
3159 case TOK_IF:
3160 c = expr_preprocess();
3161 goto do_if;
3162 case TOK_IFDEF:
3163 c = 0;
3164 do_ifdef:
3165 next_nomacro();
3166 if (tok < TOK_IDENT)
3167 error("invalid argument for '#if%sdef'", c ? "n" : "");
3168 if (is_bof) {
3169 if (c) {
3170 #ifdef INC_DEBUG
3171 printf("#ifndef %s\n", get_tok_str(tok, NULL));
3172 #endif
3173 file->ifndef_macro = tok;
3176 c = (define_find(tok) != 0) ^ c;
3177 do_if:
3178 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
3179 error("memory full");
3180 *s1->ifdef_stack_ptr++ = c;
3181 goto test_skip;
3182 case TOK_ELSE:
3183 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
3184 error("#else without matching #if");
3185 if (s1->ifdef_stack_ptr[-1] & 2)
3186 error("#else after #else");
3187 c = (s1->ifdef_stack_ptr[-1] ^= 3);
3188 goto test_skip;
3189 case TOK_ELIF:
3190 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
3191 error("#elif without matching #if");
3192 c = s1->ifdef_stack_ptr[-1];
3193 if (c > 1)
3194 error("#elif after #else");
3195 /* last #if/#elif expression was true: we skip */
3196 if (c == 1)
3197 goto skip;
3198 c = expr_preprocess();
3199 s1->ifdef_stack_ptr[-1] = c;
3200 test_skip:
3201 if (!(c & 1)) {
3202 skip:
3203 preprocess_skip();
3204 is_bof = 0;
3205 goto redo;
3207 break;
3208 case TOK_ENDIF:
3209 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
3210 error("#endif without matching #if");
3211 s1->ifdef_stack_ptr--;
3212 /* '#ifndef macro' was at the start of file. Now we check if
3213 an '#endif' is exactly at the end of file */
3214 if (file->ifndef_macro &&
3215 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
3216 file->ifndef_macro_saved = file->ifndef_macro;
3217 /* need to set to zero to avoid false matches if another
3218 #ifndef at middle of file */
3219 file->ifndef_macro = 0;
3220 while (tok != TOK_LINEFEED)
3221 next_nomacro();
3222 tok_flags |= TOK_FLAG_ENDIF;
3223 goto the_end;
3225 break;
3226 case TOK_LINE:
3227 next();
3228 if (tok != TOK_CINT)
3229 error("#line");
3230 file->line_num = tokc.i - 1; /* the line number will be incremented after */
3231 next();
3232 if (tok != TOK_LINEFEED) {
3233 if (tok != TOK_STR)
3234 error("#line");
3235 pstrcpy(file->filename, sizeof(file->filename),
3236 (char *)tokc.cstr->data);
3238 break;
3239 case TOK_ERROR:
3240 case TOK_WARNING:
3241 c = tok;
3242 ch = file->buf_ptr[0];
3243 skip_spaces();
3244 q = buf;
3245 while (ch != '\n' && ch != CH_EOF) {
3246 if ((q - buf) < sizeof(buf) - 1)
3247 *q++ = ch;
3248 if (ch == '\\') {
3249 if (handle_stray_noerror() == 0)
3250 --q;
3251 } else
3252 inp();
3254 *q = '\0';
3255 if (c == TOK_ERROR)
3256 error("#error %s", buf);
3257 else
3258 warning("#warning %s", buf);
3259 break;
3260 case TOK_PRAGMA:
3261 pragma_parse(s1);
3262 break;
3263 default:
3264 if (tok == TOK_LINEFEED || tok == '!' || tok == TOK_CINT) {
3265 /* '!' is ignored to allow C scripts. numbers are ignored
3266 to emulate cpp behaviour */
3267 } else {
3268 if (!(saved_parse_flags & PARSE_FLAG_ASM_COMMENTS))
3269 warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
3271 break;
3273 /* ignore other preprocess commands or #! for C scripts */
3274 while (tok != TOK_LINEFEED)
3275 next_nomacro();
3276 the_end:
3277 parse_flags = saved_parse_flags;
3280 /* evaluate escape codes in a string. */
3281 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
3283 int c, n;
3284 const uint8_t *p;
3286 p = buf;
3287 for(;;) {
3288 c = *p;
3289 if (c == '\0')
3290 break;
3291 if (c == '\\') {
3292 p++;
3293 /* escape */
3294 c = *p;
3295 switch(c) {
3296 case '0': case '1': case '2': case '3':
3297 case '4': case '5': case '6': case '7':
3298 /* at most three octal digits */
3299 n = c - '0';
3300 p++;
3301 c = *p;
3302 if (isoct(c)) {
3303 n = n * 8 + c - '0';
3304 p++;
3305 c = *p;
3306 if (isoct(c)) {
3307 n = n * 8 + c - '0';
3308 p++;
3311 c = n;
3312 goto add_char_nonext;
3313 case 'x':
3314 case 'u':
3315 case 'U':
3316 p++;
3317 n = 0;
3318 for(;;) {
3319 c = *p;
3320 if (c >= 'a' && c <= 'f')
3321 c = c - 'a' + 10;
3322 else if (c >= 'A' && c <= 'F')
3323 c = c - 'A' + 10;
3324 else if (isnum(c))
3325 c = c - '0';
3326 else
3327 break;
3328 n = n * 16 + c;
3329 p++;
3331 c = n;
3332 goto add_char_nonext;
3333 case 'a':
3334 c = '\a';
3335 break;
3336 case 'b':
3337 c = '\b';
3338 break;
3339 case 'f':
3340 c = '\f';
3341 break;
3342 case 'n':
3343 c = '\n';
3344 break;
3345 case 'r':
3346 c = '\r';
3347 break;
3348 case 't':
3349 c = '\t';
3350 break;
3351 case 'v':
3352 c = '\v';
3353 break;
3354 case 'e':
3355 if (!gnu_ext)
3356 goto invalid_escape;
3357 c = 27;
3358 break;
3359 case '\'':
3360 case '\"':
3361 case '\\':
3362 case '?':
3363 break;
3364 default:
3365 invalid_escape:
3366 if (c >= '!' && c <= '~')
3367 warning("unknown escape sequence: \'\\%c\'", c);
3368 else
3369 warning("unknown escape sequence: \'\\x%x\'", c);
3370 break;
3373 p++;
3374 add_char_nonext:
3375 if (!is_long)
3376 cstr_ccat(outstr, c);
3377 else
3378 cstr_wccat(outstr, c);
3380 /* add a trailing '\0' */
3381 if (!is_long)
3382 cstr_ccat(outstr, '\0');
3383 else
3384 cstr_wccat(outstr, '\0');
3387 /* we use 64 bit numbers */
3388 #define BN_SIZE 2
3390 /* bn = (bn << shift) | or_val */
3391 void bn_lshift(unsigned int *bn, int shift, int or_val)
3393 int i;
3394 unsigned int v;
3395 for(i=0;i<BN_SIZE;i++) {
3396 v = bn[i];
3397 bn[i] = (v << shift) | or_val;
3398 or_val = v >> (32 - shift);
3402 void bn_zero(unsigned int *bn)
3404 int i;
3405 for(i=0;i<BN_SIZE;i++) {
3406 bn[i] = 0;
3410 /* parse number in null terminated string 'p' and return it in the
3411 current token */
3412 void parse_number(const char *p)
3414 int b, t, shift, frac_bits, s, exp_val, ch;
3415 char *q;
3416 unsigned int bn[BN_SIZE];
3417 double d;
3419 /* number */
3420 q = token_buf;
3421 ch = *p++;
3422 t = ch;
3423 ch = *p++;
3424 *q++ = t;
3425 b = 10;
3426 if (t == '.') {
3427 goto float_frac_parse;
3428 } else if (t == '0') {
3429 if (ch == 'x' || ch == 'X') {
3430 q--;
3431 ch = *p++;
3432 b = 16;
3433 } else if (tcc_ext && (ch == 'b' || ch == 'B')) {
3434 q--;
3435 ch = *p++;
3436 b = 2;
3439 /* parse all digits. cannot check octal numbers at this stage
3440 because of floating point constants */
3441 while (1) {
3442 if (ch >= 'a' && ch <= 'f')
3443 t = ch - 'a' + 10;
3444 else if (ch >= 'A' && ch <= 'F')
3445 t = ch - 'A' + 10;
3446 else if (isnum(ch))
3447 t = ch - '0';
3448 else
3449 break;
3450 if (t >= b)
3451 break;
3452 if (q >= token_buf + STRING_MAX_SIZE) {
3453 num_too_long:
3454 error("number too long");
3456 *q++ = ch;
3457 ch = *p++;
3459 if (ch == '.' ||
3460 ((ch == 'e' || ch == 'E') && b == 10) ||
3461 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
3462 if (b != 10) {
3463 /* NOTE: strtox should support that for hexa numbers, but
3464 non ISOC99 libcs do not support it, so we prefer to do
3465 it by hand */
3466 /* hexadecimal or binary floats */
3467 /* XXX: handle overflows */
3468 *q = '\0';
3469 if (b == 16)
3470 shift = 4;
3471 else
3472 shift = 2;
3473 bn_zero(bn);
3474 q = token_buf;
3475 while (1) {
3476 t = *q++;
3477 if (t == '\0') {
3478 break;
3479 } else if (t >= 'a') {
3480 t = t - 'a' + 10;
3481 } else if (t >= 'A') {
3482 t = t - 'A' + 10;
3483 } else {
3484 t = t - '0';
3486 bn_lshift(bn, shift, t);
3488 frac_bits = 0;
3489 if (ch == '.') {
3490 ch = *p++;
3491 while (1) {
3492 t = ch;
3493 if (t >= 'a' && t <= 'f') {
3494 t = t - 'a' + 10;
3495 } else if (t >= 'A' && t <= 'F') {
3496 t = t - 'A' + 10;
3497 } else if (t >= '0' && t <= '9') {
3498 t = t - '0';
3499 } else {
3500 break;
3502 if (t >= b)
3503 error("invalid digit");
3504 bn_lshift(bn, shift, t);
3505 frac_bits += shift;
3506 ch = *p++;
3509 if (ch != 'p' && ch != 'P')
3510 expect("exponent");
3511 ch = *p++;
3512 s = 1;
3513 exp_val = 0;
3514 if (ch == '+') {
3515 ch = *p++;
3516 } else if (ch == '-') {
3517 s = -1;
3518 ch = *p++;
3520 if (ch < '0' || ch > '9')
3521 expect("exponent digits");
3522 while (ch >= '0' && ch <= '9') {
3523 exp_val = exp_val * 10 + ch - '0';
3524 ch = *p++;
3526 exp_val = exp_val * s;
3528 /* now we can generate the number */
3529 /* XXX: should patch directly float number */
3530 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
3531 d = ldexp(d, exp_val - frac_bits);
3532 t = toup(ch);
3533 if (t == 'F') {
3534 ch = *p++;
3535 tok = TOK_CFLOAT;
3536 /* float : should handle overflow */
3537 tokc.f = (float)d;
3538 } else if (t == 'L') {
3539 ch = *p++;
3540 tok = TOK_CLDOUBLE;
3541 /* XXX: not large enough */
3542 tokc.ld = (long double)d;
3543 } else {
3544 tok = TOK_CDOUBLE;
3545 tokc.d = d;
3547 } else {
3548 /* decimal floats */
3549 if (ch == '.') {
3550 if (q >= token_buf + STRING_MAX_SIZE)
3551 goto num_too_long;
3552 *q++ = ch;
3553 ch = *p++;
3554 float_frac_parse:
3555 while (ch >= '0' && ch <= '9') {
3556 if (q >= token_buf + STRING_MAX_SIZE)
3557 goto num_too_long;
3558 *q++ = ch;
3559 ch = *p++;
3562 if (ch == 'e' || ch == 'E') {
3563 if (q >= token_buf + STRING_MAX_SIZE)
3564 goto num_too_long;
3565 *q++ = ch;
3566 ch = *p++;
3567 if (ch == '-' || ch == '+') {
3568 if (q >= token_buf + STRING_MAX_SIZE)
3569 goto num_too_long;
3570 *q++ = ch;
3571 ch = *p++;
3573 if (ch < '0' || ch > '9')
3574 expect("exponent digits");
3575 while (ch >= '0' && ch <= '9') {
3576 if (q >= token_buf + STRING_MAX_SIZE)
3577 goto num_too_long;
3578 *q++ = ch;
3579 ch = *p++;
3582 *q = '\0';
3583 t = toup(ch);
3584 errno = 0;
3585 if (t == 'F') {
3586 ch = *p++;
3587 tok = TOK_CFLOAT;
3588 tokc.f = strtof(token_buf, NULL);
3589 } else if (t == 'L') {
3590 ch = *p++;
3591 tok = TOK_CLDOUBLE;
3592 tokc.ld = strtold(token_buf, NULL);
3593 } else {
3594 tok = TOK_CDOUBLE;
3595 tokc.d = strtod(token_buf, NULL);
3598 } else {
3599 unsigned long long n, n1;
3600 int lcount, ucount;
3602 /* integer number */
3603 *q = '\0';
3604 q = token_buf;
3605 if (b == 10 && *q == '0') {
3606 b = 8;
3607 q++;
3609 n = 0;
3610 while(1) {
3611 t = *q++;
3612 /* no need for checks except for base 10 / 8 errors */
3613 if (t == '\0') {
3614 break;
3615 } else if (t >= 'a') {
3616 t = t - 'a' + 10;
3617 } else if (t >= 'A') {
3618 t = t - 'A' + 10;
3619 } else {
3620 t = t - '0';
3621 if (t >= b)
3622 error("invalid digit");
3624 n1 = n;
3625 n = n * b + t;
3626 /* detect overflow */
3627 /* XXX: this test is not reliable */
3628 if (n < n1)
3629 error("integer constant overflow");
3632 /* XXX: not exactly ANSI compliant */
3633 if ((n & 0xffffffff00000000LL) != 0) {
3634 if ((n >> 63) != 0)
3635 tok = TOK_CULLONG;
3636 else
3637 tok = TOK_CLLONG;
3638 } else if (n > 0x7fffffff) {
3639 tok = TOK_CUINT;
3640 } else {
3641 tok = TOK_CINT;
3643 lcount = 0;
3644 ucount = 0;
3645 for(;;) {
3646 t = toup(ch);
3647 if (t == 'L') {
3648 if (lcount >= 2)
3649 error("three 'l's in integer constant");
3650 lcount++;
3651 if (lcount == 2) {
3652 if (tok == TOK_CINT)
3653 tok = TOK_CLLONG;
3654 else if (tok == TOK_CUINT)
3655 tok = TOK_CULLONG;
3657 ch = *p++;
3658 } else if (t == 'U') {
3659 if (ucount >= 1)
3660 error("two 'u's in integer constant");
3661 ucount++;
3662 if (tok == TOK_CINT)
3663 tok = TOK_CUINT;
3664 else if (tok == TOK_CLLONG)
3665 tok = TOK_CULLONG;
3666 ch = *p++;
3667 } else {
3668 break;
3671 if (tok == TOK_CINT || tok == TOK_CUINT)
3672 tokc.ui = n;
3673 else
3674 tokc.ull = n;
3676 if (ch)
3677 error("invalid number\n");
3681 #define PARSE2(c1, tok1, c2, tok2) \
3682 case c1: \
3683 PEEKC(c, p); \
3684 if (c == c2) { \
3685 p++; \
3686 tok = tok2; \
3687 } else { \
3688 tok = tok1; \
3690 break;
3692 /* return next token without macro substitution */
3693 static inline void next_nomacro1(void)
3695 int t, c, is_long;
3696 TokenSym *ts;
3697 uint8_t *p, *p1;
3698 unsigned int h;
3700 cstr_reset(&tok_spaces);
3701 p = file->buf_ptr;
3702 redo_no_start:
3703 c = *p;
3704 switch(c) {
3705 case ' ':
3706 case '\t':
3707 case '\f':
3708 case '\v':
3709 case '\r':
3710 cstr_ccat(&tok_spaces, c);
3711 p++;
3712 goto redo_no_start;
3714 case '\\':
3715 /* first look if it is in fact an end of buffer */
3716 if (p >= file->buf_end) {
3717 file->buf_ptr = p;
3718 handle_eob();
3719 p = file->buf_ptr;
3720 if (p >= file->buf_end)
3721 goto parse_eof;
3722 else
3723 goto redo_no_start;
3724 } else {
3725 file->buf_ptr = p;
3726 ch = *p;
3727 handle_stray();
3728 p = file->buf_ptr;
3729 goto redo_no_start;
3731 parse_eof:
3733 TCCState *s1 = tcc_state;
3734 if ((parse_flags & PARSE_FLAG_LINEFEED)
3735 && !(tok_flags & TOK_FLAG_EOF)) {
3736 tok_flags |= TOK_FLAG_EOF;
3737 tok = TOK_LINEFEED;
3738 goto keep_tok_flags;
3739 } else if (s1->include_stack_ptr == s1->include_stack ||
3740 !(parse_flags & PARSE_FLAG_PREPROCESS)) {
3741 /* no include left : end of file. */
3742 tok = TOK_EOF;
3743 } else {
3744 tok_flags &= ~TOK_FLAG_EOF;
3745 /* pop include file */
3747 /* test if previous '#endif' was after a #ifdef at
3748 start of file */
3749 if (tok_flags & TOK_FLAG_ENDIF) {
3750 #ifdef INC_DEBUG
3751 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
3752 #endif
3753 add_cached_include(s1, file->inc_type, file->inc_filename,
3754 file->ifndef_macro_saved);
3757 /* add end of include file debug info */
3758 if (do_debug) {
3759 put_stabd(N_EINCL, 0, 0);
3761 /* pop include stack */
3762 tcc_close(file);
3763 s1->include_stack_ptr--;
3764 file = *s1->include_stack_ptr;
3765 p = file->buf_ptr;
3766 goto redo_no_start;
3769 break;
3771 case '\n':
3772 file->line_num++;
3773 tok_flags |= TOK_FLAG_BOL;
3774 p++;
3775 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
3776 goto redo_no_start;
3777 tok = TOK_LINEFEED;
3778 goto keep_tok_flags;
3780 case '#':
3781 /* XXX: simplify */
3782 PEEKC(c, p);
3783 if ((tok_flags & TOK_FLAG_BOL) &&
3784 (parse_flags & PARSE_FLAG_PREPROCESS)) {
3785 file->buf_ptr = p;
3786 preprocess(tok_flags & TOK_FLAG_BOF);
3787 p = file->buf_ptr;
3788 goto redo_no_start;
3789 } else {
3790 if (c == '#') {
3791 p++;
3792 tok = TOK_TWOSHARPS;
3793 } else {
3794 if (parse_flags & PARSE_FLAG_ASM_COMMENTS) {
3795 p = parse_line_comment(p - 1);
3796 goto redo_no_start;
3797 } else {
3798 tok = '#';
3802 break;
3804 case 'a': case 'b': case 'c': case 'd':
3805 case 'e': case 'f': case 'g': case 'h':
3806 case 'i': case 'j': case 'k': case 'l':
3807 case 'm': case 'n': case 'o': case 'p':
3808 case 'q': case 'r': case 's': case 't':
3809 case 'u': case 'v': case 'w': case 'x':
3810 case 'y': case 'z':
3811 case 'A': case 'B': case 'C': case 'D':
3812 case 'E': case 'F': case 'G': case 'H':
3813 case 'I': case 'J': case 'K':
3814 case 'M': case 'N': case 'O': case 'P':
3815 case 'Q': case 'R': case 'S': case 'T':
3816 case 'U': case 'V': case 'W': case 'X':
3817 case 'Y': case 'Z':
3818 case '_':
3819 parse_ident_fast:
3820 p1 = p;
3821 h = TOK_HASH_INIT;
3822 h = TOK_HASH_FUNC(h, c);
3823 p++;
3824 for(;;) {
3825 c = *p;
3826 if (!isidnum_table[c-CH_EOF])
3827 break;
3828 h = TOK_HASH_FUNC(h, c);
3829 p++;
3831 if (c != '\\') {
3832 TokenSym **pts;
3833 int len;
3835 /* fast case : no stray found, so we have the full token
3836 and we have already hashed it */
3837 len = p - p1;
3838 h &= (TOK_HASH_SIZE - 1);
3839 pts = &hash_ident[h];
3840 for(;;) {
3841 ts = *pts;
3842 if (!ts)
3843 break;
3844 if (ts->len == len && !memcmp(ts->str, p1, len))
3845 goto token_found;
3846 pts = &(ts->hash_next);
3848 ts = tok_alloc_new(pts, p1, len);
3849 token_found: ;
3850 } else {
3851 /* slower case */
3852 cstr_reset(&tokcstr);
3854 while (p1 < p) {
3855 cstr_ccat(&tokcstr, *p1);
3856 p1++;
3858 p--;
3859 PEEKC(c, p);
3860 parse_ident_slow:
3861 while (isidnum_table[c-CH_EOF]) {
3862 cstr_ccat(&tokcstr, c);
3863 PEEKC(c, p);
3865 ts = tok_alloc(tokcstr.data, tokcstr.size);
3867 tok = ts->tok;
3868 break;
3869 case 'L':
3870 t = p[1];
3871 if (t != '\\' && t != '\'' && t != '\"') {
3872 /* fast case */
3873 goto parse_ident_fast;
3874 } else {
3875 PEEKC(c, p);
3876 if (c == '\'' || c == '\"') {
3877 is_long = 1;
3878 goto str_const;
3879 } else {
3880 cstr_reset(&tokcstr);
3881 cstr_ccat(&tokcstr, 'L');
3882 goto parse_ident_slow;
3885 break;
3886 case '0': case '1': case '2': case '3':
3887 case '4': case '5': case '6': case '7':
3888 case '8': case '9':
3890 cstr_reset(&tokcstr);
3891 /* after the first digit, accept digits, alpha, '.' or sign if
3892 prefixed by 'eEpP' */
3893 parse_num:
3894 for(;;) {
3895 t = c;
3896 cstr_ccat(&tokcstr, c);
3897 PEEKC(c, p);
3898 if (!(isnum(c) || isid(c) || c == '.' ||
3899 ((c == '+' || c == '-') &&
3900 (t == 'e' || t == 'E' || t == 'p' || t == 'P'))))
3901 break;
3903 /* We add a trailing '\0' to ease parsing */
3904 cstr_ccat(&tokcstr, '\0');
3905 tokc.cstr = &tokcstr;
3906 tok = TOK_PPNUM;
3907 break;
3908 case '.':
3909 /* special dot handling because it can also start a number */
3910 PEEKC(c, p);
3911 if (isnum(c)) {
3912 cstr_reset(&tokcstr);
3913 cstr_ccat(&tokcstr, '.');
3914 goto parse_num;
3915 } else if (c == '.') {
3916 PEEKC(c, p);
3917 if (c != '.')
3918 expect("'.'");
3919 PEEKC(c, p);
3920 tok = TOK_DOTS;
3921 } else {
3922 tok = '.';
3924 break;
3925 case '\'':
3926 case '\"':
3927 is_long = 0;
3928 str_const:
3930 CString str;
3931 int sep;
3933 sep = c;
3935 /* parse the string */
3936 cstr_new(&str);
3937 p = parse_pp_string(p, sep, &str);
3938 cstr_ccat(&str, '\0');
3940 /* eval the escape (should be done as TOK_PPNUM) */
3941 cstr_reset(&tokcstr);
3942 parse_escape_string(&tokcstr, str.data, is_long);
3943 cstr_free(&str);
3945 if (sep == '\'') {
3946 int char_size;
3947 /* XXX: make it portable */
3948 if (!is_long)
3949 char_size = 1;
3950 else
3951 char_size = sizeof(nwchar_t);
3952 if (tokcstr.size <= char_size)
3953 error("empty character constant");
3954 if (tokcstr.size > 2 * char_size)
3955 warning("multi-character character constant");
3956 if (!is_long) {
3957 tokc.i = *(int8_t *)tokcstr.data;
3958 tok = TOK_CCHAR;
3959 } else {
3960 tokc.i = *(nwchar_t *)tokcstr.data;
3961 tok = TOK_LCHAR;
3963 } else {
3964 tokc.cstr = &tokcstr;
3965 if (!is_long)
3966 tok = TOK_STR;
3967 else
3968 tok = TOK_LSTR;
3971 break;
3973 case '<':
3974 PEEKC(c, p);
3975 if (c == '=') {
3976 p++;
3977 tok = TOK_LE;
3978 } else if (c == '<') {
3979 PEEKC(c, p);
3980 if (c == '=') {
3981 p++;
3982 tok = TOK_A_SHL;
3983 } else {
3984 tok = TOK_SHL;
3986 } else {
3987 tok = TOK_LT;
3989 break;
3991 case '>':
3992 PEEKC(c, p);
3993 if (c == '=') {
3994 p++;
3995 tok = TOK_GE;
3996 } else if (c == '>') {
3997 PEEKC(c, p);
3998 if (c == '=') {
3999 p++;
4000 tok = TOK_A_SAR;
4001 } else {
4002 tok = TOK_SAR;
4004 } else {
4005 tok = TOK_GT;
4007 break;
4009 case '&':
4010 PEEKC(c, p);
4011 if (c == '&') {
4012 p++;
4013 tok = TOK_LAND;
4014 } else if (c == '=') {
4015 p++;
4016 tok = TOK_A_AND;
4017 } else {
4018 tok = '&';
4020 break;
4022 case '|':
4023 PEEKC(c, p);
4024 if (c == '|') {
4025 p++;
4026 tok = TOK_LOR;
4027 } else if (c == '=') {
4028 p++;
4029 tok = TOK_A_OR;
4030 } else {
4031 tok = '|';
4033 break;
4035 case '+':
4036 PEEKC(c, p);
4037 if (c == '+') {
4038 p++;
4039 tok = TOK_INC;
4040 } else if (c == '=') {
4041 p++;
4042 tok = TOK_A_ADD;
4043 } else {
4044 tok = '+';
4046 break;
4048 case '-':
4049 PEEKC(c, p);
4050 if (c == '-') {
4051 p++;
4052 tok = TOK_DEC;
4053 } else if (c == '=') {
4054 p++;
4055 tok = TOK_A_SUB;
4056 } else if (c == '>') {
4057 p++;
4058 tok = TOK_ARROW;
4059 } else {
4060 tok = '-';
4062 break;
4064 PARSE2('!', '!', '=', TOK_NE)
4065 PARSE2('=', '=', '=', TOK_EQ)
4066 PARSE2('*', '*', '=', TOK_A_MUL)
4067 PARSE2('%', '%', '=', TOK_A_MOD)
4068 PARSE2('^', '^', '=', TOK_A_XOR)
4070 /* comments or operator */
4071 case '/':
4072 PEEKC(c, p);
4073 if (c == '*') {
4074 p = parse_comment(p);
4075 goto redo_no_start;
4076 } else if (c == '/') {
4077 p = parse_line_comment(p);
4078 goto redo_no_start;
4079 } else if (c == '=') {
4080 p++;
4081 tok = TOK_A_DIV;
4082 } else {
4083 tok = '/';
4085 break;
4087 /* simple tokens */
4088 case '(':
4089 case ')':
4090 case '[':
4091 case ']':
4092 case '{':
4093 case '}':
4094 case ',':
4095 case ';':
4096 case ':':
4097 case '?':
4098 case '~':
4099 case '$': /* only used in assembler */
4100 case '@': /* dito */
4101 tok = c;
4102 p++;
4103 break;
4104 default:
4105 error("unrecognized character \\x%02x", c);
4106 break;
4108 tok_flags = 0;
4109 keep_tok_flags:
4110 file->buf_ptr = p;
4111 #if defined(PARSE_DEBUG)
4112 printf("token = %s\n", get_tok_str(tok, &tokc));
4113 #endif
4116 /* return next token without macro substitution. Can read input from
4117 macro_ptr buffer */
4118 static void next_nomacro(void)
4120 if (macro_ptr) {
4121 redo:
4122 tok = *macro_ptr;
4123 if (tok) {
4124 TOK_GET(tok, macro_ptr, tokc);
4125 if (tok == TOK_LINENUM) {
4126 file->line_num = tokc.i;
4127 goto redo;
4130 } else {
4131 next_nomacro1();
4135 /* substitute args in macro_str and return allocated string */
4136 static int *macro_arg_subst(Sym **nested_list, int *macro_str, Sym *args)
4138 int *st, last_tok, t, notfirst;
4139 Sym *s;
4140 CValue cval;
4141 TokenString str;
4142 CString cstr;
4144 tok_str_new(&str);
4145 last_tok = 0;
4146 while(1) {
4147 TOK_GET(t, macro_str, cval);
4148 if (!t)
4149 break;
4150 if (t == '#') {
4151 /* stringize */
4152 TOK_GET(t, macro_str, cval);
4153 if (!t)
4154 break;
4155 s = sym_find2(args, t);
4156 if (s) {
4157 cstr_new(&cstr);
4158 st = (int *)s->c;
4159 notfirst = 0;
4160 while (*st) {
4161 if (notfirst)
4162 cstr_ccat(&cstr, ' ');
4163 TOK_GET(t, st, cval);
4164 cstr_cat(&cstr, get_tok_str(t, &cval));
4165 #ifndef PP_NOSPACES
4166 notfirst = 1;
4167 #endif
4169 cstr_ccat(&cstr, '\0');
4170 #ifdef PP_DEBUG
4171 printf("stringize: %s\n", (char *)cstr.data);
4172 #endif
4173 /* add string */
4174 cval.cstr = &cstr;
4175 tok_str_add2(&str, TOK_STR, &cval);
4176 cstr_free(&cstr);
4177 } else {
4178 tok_str_add2(&str, t, &cval);
4180 } else if (t >= TOK_IDENT) {
4181 s = sym_find2(args, t);
4182 if (s) {
4183 st = (int *)s->c;
4184 /* if '##' is present before or after, no arg substitution */
4185 if (*macro_str == TOK_TWOSHARPS || last_tok == TOK_TWOSHARPS) {
4186 /* special case for var arg macros : ## eats the
4187 ',' if empty VA_ARGS variable. */
4188 /* XXX: test of the ',' is not 100%
4189 reliable. should fix it to avoid security
4190 problems */
4191 if (gnu_ext && s->type.t &&
4192 last_tok == TOK_TWOSHARPS &&
4193 str.len >= 2 && str.str[str.len - 2] == ',') {
4194 if (*st == 0) {
4195 /* suppress ',' '##' */
4196 str.len -= 2;
4197 } else {
4198 /* suppress '##' and add variable */
4199 str.len--;
4200 goto add_var;
4202 } else {
4203 int t1;
4204 add_var:
4205 for(;;) {
4206 TOK_GET(t1, st, cval);
4207 if (!t1)
4208 break;
4209 tok_str_add2(&str, t1, &cval);
4212 } else {
4213 /* NOTE: the stream cannot be read when macro
4214 substituing an argument */
4215 macro_subst(&str, nested_list, st, NULL);
4217 } else {
4218 tok_str_add(&str, t);
4220 } else {
4221 tok_str_add2(&str, t, &cval);
4223 last_tok = t;
4225 tok_str_add(&str, 0);
4226 return str.str;
4229 static char const ab_month_name[12][4] =
4231 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
4232 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
4235 /* do macro substitution of current token with macro 's' and add
4236 result to (tok_str,tok_len). 'nested_list' is the list of all
4237 macros we got inside to avoid recursing. Return non zero if no
4238 substitution needs to be done */
4239 static int macro_subst_tok(TokenString *tok_str,
4240 Sym **nested_list, Sym *s, struct macro_level **can_read_stream)
4242 Sym *args, *sa, *sa1;
4243 int mstr_allocated, parlevel, *mstr, t, t1;
4244 TokenString str;
4245 char *cstrval;
4246 CValue cval;
4247 CString cstr;
4248 char buf[32];
4250 /* if symbol is a macro, prepare substitution */
4251 /* special macros */
4252 if (tok == TOK___LINE__) {
4253 snprintf(buf, sizeof(buf), "%d", file->line_num);
4254 cstrval = buf;
4255 t1 = TOK_PPNUM;
4256 goto add_cstr1;
4257 } else if (tok == TOK___FILE__) {
4258 cstrval = file->filename;
4259 goto add_cstr;
4260 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
4261 time_t ti;
4262 struct tm *tm;
4264 time(&ti);
4265 tm = localtime(&ti);
4266 if (tok == TOK___DATE__) {
4267 snprintf(buf, sizeof(buf), "%s %2d %d",
4268 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
4269 } else {
4270 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
4271 tm->tm_hour, tm->tm_min, tm->tm_sec);
4273 cstrval = buf;
4274 add_cstr:
4275 t1 = TOK_STR;
4276 add_cstr1:
4277 cstr_new(&cstr);
4278 cstr_cat(&cstr, cstrval);
4279 cstr_ccat(&cstr, '\0');
4280 cval.cstr = &cstr;
4281 tok_str_add2(tok_str, t1, &cval);
4282 cstr_free(&cstr);
4283 } else {
4284 mstr = (int *)s->c;
4285 mstr_allocated = 0;
4286 if (s->type.t == MACRO_FUNC) {
4287 /* NOTE: we do not use next_nomacro to avoid eating the
4288 next token. XXX: find better solution */
4289 redo:
4290 if (macro_ptr) {
4291 t = *macro_ptr;
4292 if (t == 0 && can_read_stream) {
4293 /* end of macro stream: we must look at the token
4294 after in the file */
4295 struct macro_level *ml = *can_read_stream;
4296 macro_ptr = NULL;
4297 if (ml)
4299 macro_ptr = ml->p;
4300 ml->p = NULL;
4301 *can_read_stream = ml -> prev;
4303 goto redo;
4305 } else {
4306 /* XXX: incorrect with comments */
4307 ch = file->buf_ptr[0];
4308 while (is_space(ch) || ch == '\n')
4309 cinp();
4310 t = ch;
4312 if (t != '(') /* no macro subst */
4313 return -1;
4315 /* argument macro */
4316 next_nomacro();
4317 next_nomacro();
4318 args = NULL;
4319 sa = s->next;
4320 /* NOTE: empty args are allowed, except if no args */
4321 for(;;) {
4322 /* handle '()' case */
4323 if (!args && !sa && tok == ')')
4324 break;
4325 if (!sa)
4326 error("macro '%s' used with too many args",
4327 get_tok_str(s->v, 0));
4328 tok_str_new(&str);
4329 parlevel = 0;
4330 /* NOTE: non zero sa->t indicates VA_ARGS */
4331 while ((parlevel > 0 ||
4332 (tok != ')' &&
4333 (tok != ',' || sa->type.t))) &&
4334 tok != -1) {
4335 if (tok == '(')
4336 parlevel++;
4337 else if (tok == ')')
4338 parlevel--;
4339 if (tok != TOK_LINEFEED)
4340 tok_str_add2(&str, tok, &tokc);
4341 next_nomacro();
4343 tok_str_add(&str, 0);
4344 sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, (long)str.str);
4345 sa = sa->next;
4346 if (tok == ')') {
4347 /* special case for gcc var args: add an empty
4348 var arg argument if it is omitted */
4349 if (sa && sa->type.t && gnu_ext)
4350 continue;
4351 else
4352 break;
4354 if (tok != ',')
4355 expect(",");
4356 next_nomacro();
4358 if (sa) {
4359 error("macro '%s' used with too few args",
4360 get_tok_str(s->v, 0));
4363 /* now subst each arg */
4364 mstr = macro_arg_subst(nested_list, mstr, args);
4365 /* free memory */
4366 sa = args;
4367 while (sa) {
4368 sa1 = sa->prev;
4369 tok_str_free((int *)sa->c);
4370 sym_free(sa);
4371 sa = sa1;
4373 mstr_allocated = 1;
4375 sym_push2(nested_list, s->v, 0, 0);
4376 macro_subst(tok_str, nested_list, mstr, can_read_stream);
4377 /* pop nested defined symbol */
4378 sa1 = *nested_list;
4379 *nested_list = sa1->prev;
4380 sym_free(sa1);
4381 if (mstr_allocated)
4382 tok_str_free(mstr);
4384 return 0;
4387 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
4388 return the resulting string (which must be freed). */
4389 static inline int *macro_twosharps(const int *macro_str)
4391 TokenSym *ts;
4392 const int *macro_ptr1, *start_macro_ptr, *ptr, *saved_macro_ptr;
4393 int t;
4394 const char *p1, *p2;
4395 CValue cval;
4396 TokenString macro_str1;
4397 CString cstr;
4399 start_macro_ptr = macro_str;
4400 /* we search the first '##' */
4401 for(;;) {
4402 macro_ptr1 = macro_str;
4403 TOK_GET(t, macro_str, cval);
4404 /* nothing more to do if end of string */
4405 if (t == 0)
4406 return NULL;
4407 if (*macro_str == TOK_TWOSHARPS)
4408 break;
4411 /* we saw '##', so we need more processing to handle it */
4412 cstr_new(&cstr);
4413 tok_str_new(&macro_str1);
4414 tok = t;
4415 tokc = cval;
4417 /* add all tokens seen so far */
4418 for(ptr = start_macro_ptr; ptr < macro_ptr1;) {
4419 TOK_GET(t, ptr, cval);
4420 tok_str_add2(&macro_str1, t, &cval);
4422 saved_macro_ptr = macro_ptr;
4423 /* XXX: get rid of the use of macro_ptr here */
4424 macro_ptr = (int *)macro_str;
4425 for(;;) {
4426 while (*macro_ptr == TOK_TWOSHARPS) {
4427 macro_ptr++;
4428 macro_ptr1 = macro_ptr;
4429 t = *macro_ptr;
4430 if (t) {
4431 TOK_GET(t, macro_ptr, cval);
4432 /* We concatenate the two tokens if we have an
4433 identifier or a preprocessing number */
4434 cstr_reset(&cstr);
4435 p1 = get_tok_str(tok, &tokc);
4436 cstr_cat(&cstr, p1);
4437 p2 = get_tok_str(t, &cval);
4438 cstr_cat(&cstr, p2);
4439 cstr_ccat(&cstr, '\0');
4441 if ((tok >= TOK_IDENT || tok == TOK_PPNUM) &&
4442 (t >= TOK_IDENT || t == TOK_PPNUM)) {
4443 if (tok == TOK_PPNUM) {
4444 /* if number, then create a number token */
4445 /* NOTE: no need to allocate because
4446 tok_str_add2() does it */
4447 cstr_reset(&tokcstr);
4448 tokcstr = cstr;
4449 cstr_new(&cstr);
4450 tokc.cstr = &tokcstr;
4451 } else {
4452 /* if identifier, we must do a test to
4453 validate we have a correct identifier */
4454 if (t == TOK_PPNUM) {
4455 const char *p;
4456 int c;
4458 p = p2;
4459 for(;;) {
4460 c = *p;
4461 if (c == '\0')
4462 break;
4463 p++;
4464 if (!isnum(c) && !isid(c))
4465 goto error_pasting;
4468 ts = tok_alloc(cstr.data, strlen(cstr.data));
4469 tok = ts->tok; /* modify current token */
4471 } else {
4472 const char *str = cstr.data;
4473 const unsigned char *q;
4475 /* we look for a valid token */
4476 /* XXX: do more extensive checks */
4477 if (!strcmp(str, ">>=")) {
4478 tok = TOK_A_SAR;
4479 } else if (!strcmp(str, "<<=")) {
4480 tok = TOK_A_SHL;
4481 } else if (strlen(str) == 2) {
4482 /* search in two bytes table */
4483 q = tok_two_chars;
4484 for(;;) {
4485 if (!*q)
4486 goto error_pasting;
4487 if (q[0] == str[0] && q[1] == str[1])
4488 break;
4489 q += 3;
4491 tok = q[2];
4492 } else {
4493 error_pasting:
4494 /* NOTE: because get_tok_str use a static buffer,
4495 we must save it */
4496 cstr_reset(&cstr);
4497 p1 = get_tok_str(tok, &tokc);
4498 cstr_cat(&cstr, p1);
4499 cstr_ccat(&cstr, '\0');
4500 p2 = get_tok_str(t, &cval);
4501 warning("pasting \"%s\" and \"%s\" does not give a valid preprocessing token", cstr.data, p2);
4502 /* cannot merge tokens: just add them separately */
4503 tok_str_add2(&macro_str1, tok, &tokc);
4504 /* XXX: free associated memory ? */
4505 tok = t;
4506 tokc = cval;
4511 tok_str_add2(&macro_str1, tok, &tokc);
4512 next_nomacro();
4513 if (tok == 0)
4514 break;
4516 macro_ptr = (int *)saved_macro_ptr;
4517 cstr_free(&cstr);
4518 tok_str_add(&macro_str1, 0);
4519 return macro_str1.str;
4523 /* do macro substitution of macro_str and add result to
4524 (tok_str,tok_len). 'nested_list' is the list of all macros we got
4525 inside to avoid recursing. */
4526 static void macro_subst(TokenString *tok_str, Sym **nested_list,
4527 const int *macro_str, struct macro_level ** can_read_stream)
4529 Sym *s;
4530 int *macro_str1;
4531 const int *ptr;
4532 int t, ret;
4533 CValue cval;
4534 struct macro_level ml;
4536 /* first scan for '##' operator handling */
4537 ptr = macro_str;
4538 macro_str1 = macro_twosharps(ptr);
4539 if (macro_str1)
4540 ptr = macro_str1;
4541 while (1) {
4542 /* NOTE: ptr == NULL can only happen if tokens are read from
4543 file stream due to a macro function call */
4544 if (ptr == NULL)
4545 break;
4546 TOK_GET(t, ptr, cval);
4547 if (t == 0)
4548 break;
4549 s = define_find(t);
4550 if (s != NULL) {
4551 /* if nested substitution, do nothing */
4552 if (sym_find2(*nested_list, t))
4553 goto no_subst;
4554 ml.p = macro_ptr;
4555 if (can_read_stream)
4556 ml.prev = *can_read_stream, *can_read_stream = &ml;
4557 macro_ptr = (int *)ptr;
4558 tok = t;
4559 ret = macro_subst_tok(tok_str, nested_list, s, can_read_stream);
4560 ptr = (int *)macro_ptr;
4561 macro_ptr = ml.p;
4562 if (can_read_stream && *can_read_stream == &ml)
4563 *can_read_stream = ml.prev;
4564 if (ret != 0)
4565 goto no_subst;
4566 } else {
4567 no_subst:
4568 tok_str_add2(tok_str, t, &cval);
4571 if (macro_str1)
4572 tok_str_free(macro_str1);
4575 /* return next token with macro substitution */
4576 static void next(void)
4578 Sym *nested_list, *s;
4579 TokenString str;
4580 struct macro_level *ml;
4582 redo:
4583 next_nomacro();
4584 if (!macro_ptr) {
4585 /* if not reading from macro substituted string, then try
4586 to substitute macros */
4587 if (tok >= TOK_IDENT &&
4588 (parse_flags & PARSE_FLAG_PREPROCESS)) {
4589 s = define_find(tok);
4590 if (s) {
4591 /* we have a macro: we try to substitute */
4592 tok_str_new(&str);
4593 nested_list = NULL;
4594 ml = NULL;
4595 if (macro_subst_tok(&str, &nested_list, s, &ml) == 0) {
4596 /* substitution done, NOTE: maybe empty */
4597 tok_str_add(&str, 0);
4598 macro_ptr = str.str;
4599 macro_ptr_allocated = str.str;
4600 goto redo;
4604 } else {
4605 if (tok == 0) {
4606 /* end of macro or end of unget buffer */
4607 if (unget_buffer_enabled) {
4608 macro_ptr = unget_saved_macro_ptr;
4609 unget_buffer_enabled = 0;
4610 } else {
4611 /* end of macro string: free it */
4612 tok_str_free(macro_ptr_allocated);
4613 macro_ptr = NULL;
4615 goto redo;
4619 /* convert preprocessor tokens into C tokens */
4620 if (tok == TOK_PPNUM &&
4621 (parse_flags & PARSE_FLAG_TOK_NUM)) {
4622 parse_number((char *)tokc.cstr->data);
4626 /* push back current token and set current token to 'last_tok'. Only
4627 identifier case handled for labels. */
4628 static inline void unget_tok(int last_tok)
4630 int i, n;
4631 int *q;
4632 unget_saved_macro_ptr = macro_ptr;
4633 unget_buffer_enabled = 1;
4634 q = unget_saved_buffer;
4635 macro_ptr = q;
4636 *q++ = tok;
4637 n = tok_ext_size(tok) - 1;
4638 for(i=0;i<n;i++)
4639 *q++ = tokc.tab[i];
4640 *q = 0; /* end of token string */
4641 tok = last_tok;
4645 void swap(int *p, int *q)
4647 int t;
4648 t = *p;
4649 *p = *q;
4650 *q = t;
4653 void vsetc(CType *type, int r, CValue *vc)
4655 int v;
4657 if (vtop >= vstack + (VSTACK_SIZE - 1))
4658 error("memory full");
4659 /* cannot let cpu flags if other instruction are generated. Also
4660 avoid leaving VT_JMP anywhere except on the top of the stack
4661 because it would complicate the code generator. */
4662 if (vtop >= vstack) {
4663 v = vtop->r & VT_VALMASK;
4664 if (v == VT_CMP || (v & ~1) == VT_JMP)
4665 gv(RC_INT);
4667 vtop++;
4668 vtop->type = *type;
4669 vtop->r = r;
4670 vtop->r2 = VT_CONST;
4671 vtop->c = *vc;
4674 /* push integer constant */
4675 void vpushi(int v)
4677 CValue cval;
4678 cval.i = v;
4679 vsetc(&int_type, VT_CONST, &cval);
4682 /* push long long constant */
4683 void vpushll(long long v)
4685 CValue cval;
4686 CType ctype;
4687 ctype.t = VT_LLONG;
4688 cval.ull = v;
4689 vsetc(&ctype, VT_CONST, &cval);
4692 /* Return a static symbol pointing to a section */
4693 static Sym *get_sym_ref(CType *type, Section *sec,
4694 unsigned long offset, unsigned long size)
4696 int v;
4697 Sym *sym;
4699 v = anon_sym++;
4700 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
4701 sym->type.ref = type->ref;
4702 sym->r = VT_CONST | VT_SYM;
4703 put_extern_sym(sym, sec, offset, size);
4704 return sym;
4707 /* push a reference to a section offset by adding a dummy symbol */
4708 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
4710 CValue cval;
4712 cval.ul = 0;
4713 vsetc(type, VT_CONST | VT_SYM, &cval);
4714 vtop->sym = get_sym_ref(type, sec, offset, size);
4717 /* define a new external reference to a symbol 'v' of type 'u' */
4718 static Sym *external_global_sym(int v, CType *type, int r)
4720 Sym *s;
4722 s = sym_find(v);
4723 if (!s) {
4724 /* push forward reference */
4725 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
4726 s->type.ref = type->ref;
4727 s->r = r | VT_CONST | VT_SYM;
4729 return s;
4732 /* define a new external reference to a symbol 'v' of type 'u' */
4733 static Sym *external_sym(int v, CType *type, int r)
4735 Sym *s;
4737 s = sym_find(v);
4738 if (!s) {
4739 /* push forward reference */
4740 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
4741 s->type.t |= VT_EXTERN;
4742 } else {
4743 if (!is_compatible_types(&s->type, type))
4744 error("incompatible types for redefinition of '%s'",
4745 get_tok_str(v, NULL));
4747 return s;
4750 /* push a reference to global symbol v */
4751 static void vpush_global_sym(CType *type, int v)
4753 Sym *sym;
4754 CValue cval;
4756 sym = external_global_sym(v, type, 0);
4757 cval.ul = 0;
4758 vsetc(type, VT_CONST | VT_SYM, &cval);
4759 vtop->sym = sym;
4762 void vset(CType *type, int r, int v)
4764 CValue cval;
4766 cval.i = v;
4767 vsetc(type, r, &cval);
4770 void vseti(int r, int v)
4772 CType type;
4773 type.t = VT_INT;
4774 vset(&type, r, v);
4777 void vswap(void)
4779 SValue tmp;
4781 tmp = vtop[0];
4782 vtop[0] = vtop[-1];
4783 vtop[-1] = tmp;
4786 void vpushv(SValue *v)
4788 if (vtop >= vstack + (VSTACK_SIZE - 1))
4789 error("memory full");
4790 vtop++;
4791 *vtop = *v;
4794 void vdup(void)
4796 vpushv(vtop);
4799 /* save r to the memory stack, and mark it as being free */
4800 void save_reg(int r)
4802 int l, saved, size, align;
4803 SValue *p, sv;
4804 CType *type;
4806 /* modify all stack values */
4807 saved = 0;
4808 l = 0;
4809 for(p=vstack;p<=vtop;p++) {
4810 if ((p->r & VT_VALMASK) == r ||
4811 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
4812 /* must save value on stack if not already done */
4813 if (!saved) {
4814 /* NOTE: must reload 'r' because r might be equal to r2 */
4815 r = p->r & VT_VALMASK;
4816 /* store register in the stack */
4817 type = &p->type;
4818 if ((p->r & VT_LVAL) ||
4819 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
4820 #ifdef TCC_TARGET_X86_64
4821 type = &char_pointer_type;
4822 #else
4823 type = &int_type;
4824 #endif
4825 size = type_size(type, &align);
4826 loc = (loc - size) & -align;
4827 sv.type.t = type->t;
4828 sv.r = VT_LOCAL | VT_LVAL;
4829 sv.c.ul = loc;
4830 store(r, &sv);
4831 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
4832 /* x86 specific: need to pop fp register ST0 if saved */
4833 if (r == TREG_ST0) {
4834 o(0xd9dd); /* fstp %st(1) */
4836 #endif
4837 #ifndef TCC_TARGET_X86_64
4838 /* special long long case */
4839 if ((type->t & VT_BTYPE) == VT_LLONG) {
4840 sv.c.ul += 4;
4841 store(p->r2, &sv);
4843 #endif
4844 l = loc;
4845 saved = 1;
4847 /* mark that stack entry as being saved on the stack */
4848 if (p->r & VT_LVAL) {
4849 /* also clear the bounded flag because the
4850 relocation address of the function was stored in
4851 p->c.ul */
4852 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
4853 } else {
4854 p->r = lvalue_type(p->type.t) | VT_LOCAL;
4856 p->r2 = VT_CONST;
4857 p->c.ul = l;
4862 /* find a register of class 'rc2' with at most one reference on stack.
4863 * If none, call get_reg(rc) */
4864 int get_reg_ex(int rc, int rc2)
4866 int r;
4867 SValue *p;
4869 for(r=0;r<NB_REGS;r++) {
4870 if (reg_classes[r] & rc2) {
4871 int n;
4872 n=0;
4873 for(p = vstack; p <= vtop; p++) {
4874 if ((p->r & VT_VALMASK) == r ||
4875 (p->r2 & VT_VALMASK) == r)
4876 n++;
4878 if (n <= 1)
4879 return r;
4882 return get_reg(rc);
4885 /* find a free register of class 'rc'. If none, save one register */
4886 int get_reg(int rc)
4888 int r;
4889 SValue *p;
4891 /* find a free register */
4892 for(r=0;r<NB_REGS;r++) {
4893 if (reg_classes[r] & rc) {
4894 for(p=vstack;p<=vtop;p++) {
4895 if ((p->r & VT_VALMASK) == r ||
4896 (p->r2 & VT_VALMASK) == r)
4897 goto notfound;
4899 return r;
4901 notfound: ;
4904 /* no register left : free the first one on the stack (VERY
4905 IMPORTANT to start from the bottom to ensure that we don't
4906 spill registers used in gen_opi()) */
4907 for(p=vstack;p<=vtop;p++) {
4908 r = p->r & VT_VALMASK;
4909 if (r < VT_CONST && (reg_classes[r] & rc))
4910 goto save_found;
4911 /* also look at second register (if long long) */
4912 r = p->r2 & VT_VALMASK;
4913 if (r < VT_CONST && (reg_classes[r] & rc)) {
4914 save_found:
4915 save_reg(r);
4916 return r;
4919 /* Should never comes here */
4920 return -1;
4923 /* save registers up to (vtop - n) stack entry */
4924 void save_regs(int n)
4926 int r;
4927 SValue *p, *p1;
4928 p1 = vtop - n;
4929 for(p = vstack;p <= p1; p++) {
4930 r = p->r & VT_VALMASK;
4931 if (r < VT_CONST) {
4932 save_reg(r);
4937 /* move register 's' to 'r', and flush previous value of r to memory
4938 if needed */
4939 void move_reg(int r, int s)
4941 SValue sv;
4943 if (r != s) {
4944 save_reg(r);
4945 sv.type.t = VT_INT;
4946 sv.r = s;
4947 sv.c.ul = 0;
4948 load(r, &sv);
4952 /* get address of vtop (vtop MUST BE an lvalue) */
4953 void gaddrof(void)
4955 vtop->r &= ~VT_LVAL;
4956 /* tricky: if saved lvalue, then we can go back to lvalue */
4957 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
4958 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
4961 #ifdef CONFIG_TCC_BCHECK
4962 /* generate lvalue bound code */
4963 void gbound(void)
4965 int lval_type;
4966 CType type1;
4968 vtop->r &= ~VT_MUSTBOUND;
4969 /* if lvalue, then use checking code before dereferencing */
4970 if (vtop->r & VT_LVAL) {
4971 /* if not VT_BOUNDED value, then make one */
4972 if (!(vtop->r & VT_BOUNDED)) {
4973 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
4974 /* must save type because we must set it to int to get pointer */
4975 type1 = vtop->type;
4976 vtop->type.t = VT_INT;
4977 gaddrof();
4978 vpushi(0);
4979 gen_bounded_ptr_add();
4980 vtop->r |= lval_type;
4981 vtop->type = type1;
4983 /* then check for dereferencing */
4984 gen_bounded_ptr_deref();
4987 #endif
4989 /* store vtop a register belonging to class 'rc'. lvalues are
4990 converted to values. Cannot be used if cannot be converted to
4991 register value (such as structures). */
4992 int gv(int rc)
4994 int r, rc2, bit_pos, bit_size, size, align, i;
4996 /* NOTE: get_reg can modify vstack[] */
4997 if (vtop->type.t & VT_BITFIELD) {
4998 CType type;
4999 int bits = 32;
5000 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5001 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
5002 /* remove bit field info to avoid loops */
5003 vtop->type.t &= ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
5004 /* cast to int to propagate signedness in following ops */
5005 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
5006 type.t = VT_LLONG;
5007 bits = 64;
5008 } else
5009 type.t = VT_INT;
5010 if((vtop->type.t & VT_UNSIGNED) ||
5011 (vtop->type.t & VT_BTYPE) == VT_BOOL)
5012 type.t |= VT_UNSIGNED;
5013 gen_cast(&type);
5014 /* generate shifts */
5015 vpushi(bits - (bit_pos + bit_size));
5016 gen_op(TOK_SHL);
5017 vpushi(bits - bit_size);
5018 /* NOTE: transformed to SHR if unsigned */
5019 gen_op(TOK_SAR);
5020 r = gv(rc);
5021 } else {
5022 if (is_float(vtop->type.t) &&
5023 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
5024 Sym *sym;
5025 int *ptr;
5026 unsigned long offset;
5027 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
5028 CValue check;
5029 #endif
5031 /* XXX: unify with initializers handling ? */
5032 /* CPUs usually cannot use float constants, so we store them
5033 generically in data segment */
5034 size = type_size(&vtop->type, &align);
5035 offset = (data_section->data_offset + align - 1) & -align;
5036 data_section->data_offset = offset;
5037 /* XXX: not portable yet */
5038 #if defined(__i386__) || defined(__x86_64__)
5039 /* Zero pad x87 tenbyte long doubles */
5040 if (size == LDOUBLE_SIZE)
5041 vtop->c.tab[2] &= 0xffff;
5042 #endif
5043 ptr = section_ptr_add(data_section, size);
5044 size = size >> 2;
5045 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
5046 check.d = 1;
5047 if(check.tab[0])
5048 for(i=0;i<size;i++)
5049 ptr[i] = vtop->c.tab[size-1-i];
5050 else
5051 #endif
5052 for(i=0;i<size;i++)
5053 ptr[i] = vtop->c.tab[i];
5054 sym = get_sym_ref(&vtop->type, data_section, offset, size << 2);
5055 vtop->r |= VT_LVAL | VT_SYM;
5056 vtop->sym = sym;
5057 vtop->c.ul = 0;
5059 #ifdef CONFIG_TCC_BCHECK
5060 if (vtop->r & VT_MUSTBOUND)
5061 gbound();
5062 #endif
5064 r = vtop->r & VT_VALMASK;
5065 rc2 = RC_INT;
5066 if (rc == RC_IRET)
5067 rc2 = RC_LRET;
5068 /* need to reload if:
5069 - constant
5070 - lvalue (need to dereference pointer)
5071 - already a register, but not in the right class */
5072 if (r >= VT_CONST ||
5073 (vtop->r & VT_LVAL) ||
5074 !(reg_classes[r] & rc) ||
5075 ((vtop->type.t & VT_BTYPE) == VT_LLONG &&
5076 !(reg_classes[vtop->r2] & rc2))) {
5077 r = get_reg(rc);
5078 #ifndef TCC_TARGET_X86_64
5079 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
5080 int r2;
5081 unsigned long long ll;
5082 /* two register type load : expand to two words
5083 temporarily */
5084 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
5085 /* load constant */
5086 ll = vtop->c.ull;
5087 vtop->c.ui = ll; /* first word */
5088 load(r, vtop);
5089 vtop->r = r; /* save register value */
5090 vpushi(ll >> 32); /* second word */
5091 } else if (r >= VT_CONST || /* XXX: test to VT_CONST incorrect ? */
5092 (vtop->r & VT_LVAL)) {
5093 /* We do not want to modifier the long long
5094 pointer here, so the safest (and less
5095 efficient) is to save all the other registers
5096 in the stack. XXX: totally inefficient. */
5097 save_regs(1);
5098 /* load from memory */
5099 load(r, vtop);
5100 vdup();
5101 vtop[-1].r = r; /* save register value */
5102 /* increment pointer to get second word */
5103 vtop->type.t = VT_INT;
5104 gaddrof();
5105 vpushi(4);
5106 gen_op('+');
5107 vtop->r |= VT_LVAL;
5108 } else {
5109 /* move registers */
5110 load(r, vtop);
5111 vdup();
5112 vtop[-1].r = r; /* save register value */
5113 vtop->r = vtop[-1].r2;
5115 /* allocate second register */
5116 r2 = get_reg(rc2);
5117 load(r2, vtop);
5118 vpop();
5119 /* write second register */
5120 vtop->r2 = r2;
5121 } else
5122 #endif
5123 if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
5124 int t1, t;
5125 /* lvalue of scalar type : need to use lvalue type
5126 because of possible cast */
5127 t = vtop->type.t;
5128 t1 = t;
5129 /* compute memory access type */
5130 if (vtop->r & VT_LVAL_BYTE)
5131 t = VT_BYTE;
5132 else if (vtop->r & VT_LVAL_SHORT)
5133 t = VT_SHORT;
5134 if (vtop->r & VT_LVAL_UNSIGNED)
5135 t |= VT_UNSIGNED;
5136 vtop->type.t = t;
5137 load(r, vtop);
5138 /* restore wanted type */
5139 vtop->type.t = t1;
5140 } else {
5141 /* one register type load */
5142 load(r, vtop);
5145 vtop->r = r;
5146 #ifdef TCC_TARGET_C67
5147 /* uses register pairs for doubles */
5148 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
5149 vtop->r2 = r+1;
5150 #endif
5152 return r;
5155 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
5156 void gv2(int rc1, int rc2)
5158 int v;
5160 /* generate more generic register first. But VT_JMP or VT_CMP
5161 values must be generated first in all cases to avoid possible
5162 reload errors */
5163 v = vtop[0].r & VT_VALMASK;
5164 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
5165 vswap();
5166 gv(rc1);
5167 vswap();
5168 gv(rc2);
5169 /* test if reload is needed for first register */
5170 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
5171 vswap();
5172 gv(rc1);
5173 vswap();
5175 } else {
5176 gv(rc2);
5177 vswap();
5178 gv(rc1);
5179 vswap();
5180 /* test if reload is needed for first register */
5181 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
5182 gv(rc2);
5187 /* expand long long on stack in two int registers */
5188 void lexpand(void)
5190 int u;
5192 u = vtop->type.t & VT_UNSIGNED;
5193 gv(RC_INT);
5194 vdup();
5195 vtop[0].r = vtop[-1].r2;
5196 vtop[0].r2 = VT_CONST;
5197 vtop[-1].r2 = VT_CONST;
5198 vtop[0].type.t = VT_INT | u;
5199 vtop[-1].type.t = VT_INT | u;
5202 #ifdef TCC_TARGET_ARM
5203 /* expand long long on stack */
5204 void lexpand_nr(void)
5206 int u,v;
5208 u = vtop->type.t & VT_UNSIGNED;
5209 vdup();
5210 vtop->r2 = VT_CONST;
5211 vtop->type.t = VT_INT | u;
5212 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
5213 if (v == VT_CONST) {
5214 vtop[-1].c.ui = vtop->c.ull;
5215 vtop->c.ui = vtop->c.ull >> 32;
5216 vtop->r = VT_CONST;
5217 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
5218 vtop->c.ui += 4;
5219 vtop->r = vtop[-1].r;
5220 } else if (v > VT_CONST) {
5221 vtop--;
5222 lexpand();
5223 } else
5224 vtop->r = vtop[-1].r2;
5225 vtop[-1].r2 = VT_CONST;
5226 vtop[-1].type.t = VT_INT | u;
5228 #endif
5230 /* build a long long from two ints */
5231 void lbuild(int t)
5233 gv2(RC_INT, RC_INT);
5234 vtop[-1].r2 = vtop[0].r;
5235 vtop[-1].type.t = t;
5236 vpop();
5239 /* rotate n first stack elements to the bottom
5240 I1 ... In -> I2 ... In I1 [top is right]
5242 void vrotb(int n)
5244 int i;
5245 SValue tmp;
5247 tmp = vtop[-n + 1];
5248 for(i=-n+1;i!=0;i++)
5249 vtop[i] = vtop[i+1];
5250 vtop[0] = tmp;
5253 /* rotate n first stack elements to the top
5254 I1 ... In -> In I1 ... I(n-1) [top is right]
5256 void vrott(int n)
5258 int i;
5259 SValue tmp;
5261 tmp = vtop[0];
5262 for(i = 0;i < n - 1; i++)
5263 vtop[-i] = vtop[-i - 1];
5264 vtop[-n + 1] = tmp;
5267 #ifdef TCC_TARGET_ARM
5268 /* like vrott but in other direction
5269 In ... I1 -> I(n-1) ... I1 In [top is right]
5271 void vnrott(int n)
5273 int i;
5274 SValue tmp;
5276 tmp = vtop[-n + 1];
5277 for(i = n - 1; i > 0; i--)
5278 vtop[-i] = vtop[-i + 1];
5279 vtop[0] = tmp;
5281 #endif
5283 /* pop stack value */
5284 void vpop(void)
5286 int v;
5287 v = vtop->r & VT_VALMASK;
5288 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
5289 /* for x86, we need to pop the FP stack */
5290 if (v == TREG_ST0 && !nocode_wanted) {
5291 o(0xd9dd); /* fstp %st(1) */
5292 } else
5293 #endif
5294 if (v == VT_JMP || v == VT_JMPI) {
5295 /* need to put correct jump if && or || without test */
5296 gsym(vtop->c.ul);
5298 vtop--;
5301 /* convert stack entry to register and duplicate its value in another
5302 register */
5303 void gv_dup(void)
5305 int rc, t, r, r1;
5306 SValue sv;
5308 t = vtop->type.t;
5309 if ((t & VT_BTYPE) == VT_LLONG) {
5310 lexpand();
5311 gv_dup();
5312 vswap();
5313 vrotb(3);
5314 gv_dup();
5315 vrotb(4);
5316 /* stack: H L L1 H1 */
5317 lbuild(t);
5318 vrotb(3);
5319 vrotb(3);
5320 vswap();
5321 lbuild(t);
5322 vswap();
5323 } else {
5324 /* duplicate value */
5325 rc = RC_INT;
5326 sv.type.t = VT_INT;
5327 if (is_float(t)) {
5328 rc = RC_FLOAT;
5329 #ifdef TCC_TARGET_X86_64
5330 if ((t & VT_BTYPE) == VT_LDOUBLE) {
5331 rc = RC_ST0;
5333 #endif
5334 sv.type.t = t;
5336 r = gv(rc);
5337 r1 = get_reg(rc);
5338 sv.r = r;
5339 sv.c.ul = 0;
5340 load(r1, &sv); /* move r to r1 */
5341 vdup();
5342 /* duplicates value */
5343 vtop->r = r1;
5347 #ifndef TCC_TARGET_X86_64
5348 /* generate CPU independent (unsigned) long long operations */
5349 void gen_opl(int op)
5351 int t, a, b, op1, c, i;
5352 int func;
5353 unsigned short reg_iret = REG_IRET;
5354 unsigned short reg_lret = REG_LRET;
5355 SValue tmp;
5357 switch(op) {
5358 case '/':
5359 case TOK_PDIV:
5360 func = TOK___divdi3;
5361 goto gen_func;
5362 case TOK_UDIV:
5363 func = TOK___udivdi3;
5364 goto gen_func;
5365 case '%':
5366 func = TOK___moddi3;
5367 goto gen_mod_func;
5368 case TOK_UMOD:
5369 func = TOK___umoddi3;
5370 gen_mod_func:
5371 #ifdef TCC_ARM_EABI
5372 reg_iret = TREG_R2;
5373 reg_lret = TREG_R3;
5374 #endif
5375 gen_func:
5376 /* call generic long long function */
5377 vpush_global_sym(&func_old_type, func);
5378 vrott(3);
5379 gfunc_call(2);
5380 vpushi(0);
5381 vtop->r = reg_iret;
5382 vtop->r2 = reg_lret;
5383 break;
5384 case '^':
5385 case '&':
5386 case '|':
5387 case '*':
5388 case '+':
5389 case '-':
5390 t = vtop->type.t;
5391 vswap();
5392 lexpand();
5393 vrotb(3);
5394 lexpand();
5395 /* stack: L1 H1 L2 H2 */
5396 tmp = vtop[0];
5397 vtop[0] = vtop[-3];
5398 vtop[-3] = tmp;
5399 tmp = vtop[-2];
5400 vtop[-2] = vtop[-3];
5401 vtop[-3] = tmp;
5402 vswap();
5403 /* stack: H1 H2 L1 L2 */
5404 if (op == '*') {
5405 vpushv(vtop - 1);
5406 vpushv(vtop - 1);
5407 gen_op(TOK_UMULL);
5408 lexpand();
5409 /* stack: H1 H2 L1 L2 ML MH */
5410 for(i=0;i<4;i++)
5411 vrotb(6);
5412 /* stack: ML MH H1 H2 L1 L2 */
5413 tmp = vtop[0];
5414 vtop[0] = vtop[-2];
5415 vtop[-2] = tmp;
5416 /* stack: ML MH H1 L2 H2 L1 */
5417 gen_op('*');
5418 vrotb(3);
5419 vrotb(3);
5420 gen_op('*');
5421 /* stack: ML MH M1 M2 */
5422 gen_op('+');
5423 gen_op('+');
5424 } else if (op == '+' || op == '-') {
5425 /* XXX: add non carry method too (for MIPS or alpha) */
5426 if (op == '+')
5427 op1 = TOK_ADDC1;
5428 else
5429 op1 = TOK_SUBC1;
5430 gen_op(op1);
5431 /* stack: H1 H2 (L1 op L2) */
5432 vrotb(3);
5433 vrotb(3);
5434 gen_op(op1 + 1); /* TOK_xxxC2 */
5435 } else {
5436 gen_op(op);
5437 /* stack: H1 H2 (L1 op L2) */
5438 vrotb(3);
5439 vrotb(3);
5440 /* stack: (L1 op L2) H1 H2 */
5441 gen_op(op);
5442 /* stack: (L1 op L2) (H1 op H2) */
5444 /* stack: L H */
5445 lbuild(t);
5446 break;
5447 case TOK_SAR:
5448 case TOK_SHR:
5449 case TOK_SHL:
5450 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
5451 t = vtop[-1].type.t;
5452 vswap();
5453 lexpand();
5454 vrotb(3);
5455 /* stack: L H shift */
5456 c = (int)vtop->c.i;
5457 /* constant: simpler */
5458 /* NOTE: all comments are for SHL. the other cases are
5459 done by swaping words */
5460 vpop();
5461 if (op != TOK_SHL)
5462 vswap();
5463 if (c >= 32) {
5464 /* stack: L H */
5465 vpop();
5466 if (c > 32) {
5467 vpushi(c - 32);
5468 gen_op(op);
5470 if (op != TOK_SAR) {
5471 vpushi(0);
5472 } else {
5473 gv_dup();
5474 vpushi(31);
5475 gen_op(TOK_SAR);
5477 vswap();
5478 } else {
5479 vswap();
5480 gv_dup();
5481 /* stack: H L L */
5482 vpushi(c);
5483 gen_op(op);
5484 vswap();
5485 vpushi(32 - c);
5486 if (op == TOK_SHL)
5487 gen_op(TOK_SHR);
5488 else
5489 gen_op(TOK_SHL);
5490 vrotb(3);
5491 /* stack: L L H */
5492 vpushi(c);
5493 if (op == TOK_SHL)
5494 gen_op(TOK_SHL);
5495 else
5496 gen_op(TOK_SHR);
5497 gen_op('|');
5499 if (op != TOK_SHL)
5500 vswap();
5501 lbuild(t);
5502 } else {
5503 /* XXX: should provide a faster fallback on x86 ? */
5504 switch(op) {
5505 case TOK_SAR:
5506 func = TOK___ashrdi3;
5507 goto gen_func;
5508 case TOK_SHR:
5509 func = TOK___lshrdi3;
5510 goto gen_func;
5511 case TOK_SHL:
5512 func = TOK___ashldi3;
5513 goto gen_func;
5516 break;
5517 default:
5518 /* compare operations */
5519 t = vtop->type.t;
5520 vswap();
5521 lexpand();
5522 vrotb(3);
5523 lexpand();
5524 /* stack: L1 H1 L2 H2 */
5525 tmp = vtop[-1];
5526 vtop[-1] = vtop[-2];
5527 vtop[-2] = tmp;
5528 /* stack: L1 L2 H1 H2 */
5529 /* compare high */
5530 op1 = op;
5531 /* when values are equal, we need to compare low words. since
5532 the jump is inverted, we invert the test too. */
5533 if (op1 == TOK_LT)
5534 op1 = TOK_LE;
5535 else if (op1 == TOK_GT)
5536 op1 = TOK_GE;
5537 else if (op1 == TOK_ULT)
5538 op1 = TOK_ULE;
5539 else if (op1 == TOK_UGT)
5540 op1 = TOK_UGE;
5541 a = 0;
5542 b = 0;
5543 gen_op(op1);
5544 if (op1 != TOK_NE) {
5545 a = gtst(1, 0);
5547 if (op != TOK_EQ) {
5548 /* generate non equal test */
5549 /* XXX: NOT PORTABLE yet */
5550 if (a == 0) {
5551 b = gtst(0, 0);
5552 } else {
5553 #if defined(TCC_TARGET_I386)
5554 b = psym(0x850f, 0);
5555 #elif defined(TCC_TARGET_ARM)
5556 b = ind;
5557 o(0x1A000000 | encbranch(ind, 0, 1));
5558 #elif defined(TCC_TARGET_C67)
5559 error("not implemented");
5560 #else
5561 #error not supported
5562 #endif
5565 /* compare low. Always unsigned */
5566 op1 = op;
5567 if (op1 == TOK_LT)
5568 op1 = TOK_ULT;
5569 else if (op1 == TOK_LE)
5570 op1 = TOK_ULE;
5571 else if (op1 == TOK_GT)
5572 op1 = TOK_UGT;
5573 else if (op1 == TOK_GE)
5574 op1 = TOK_UGE;
5575 gen_op(op1);
5576 a = gtst(1, a);
5577 gsym(b);
5578 vseti(VT_JMPI, a);
5579 break;
5582 #endif
5584 /* handle integer constant optimizations and various machine
5585 independent opt */
5586 void gen_opic(int op)
5588 int c1, c2, t1, t2, n;
5589 SValue *v1, *v2;
5590 long long l1, l2;
5591 typedef unsigned long long U;
5593 v1 = vtop - 1;
5594 v2 = vtop;
5595 t1 = v1->type.t & VT_BTYPE;
5596 t2 = v2->type.t & VT_BTYPE;
5598 if (t1 == VT_LLONG)
5599 l1 = v1->c.ll;
5600 else if (v1->type.t & VT_UNSIGNED)
5601 l1 = v1->c.ui;
5602 else
5603 l1 = v1->c.i;
5605 if (t2 == VT_LLONG)
5606 l2 = v2->c.ll;
5607 else if (v2->type.t & VT_UNSIGNED)
5608 l2 = v2->c.ui;
5609 else
5610 l2 = v2->c.i;
5612 /* currently, we cannot do computations with forward symbols */
5613 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
5614 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
5615 if (c1 && c2) {
5616 switch(op) {
5617 case '+': l1 += l2; break;
5618 case '-': l1 -= l2; break;
5619 case '&': l1 &= l2; break;
5620 case '^': l1 ^= l2; break;
5621 case '|': l1 |= l2; break;
5622 case '*': l1 *= l2; break;
5624 case TOK_PDIV:
5625 case '/':
5626 case '%':
5627 case TOK_UDIV:
5628 case TOK_UMOD:
5629 /* if division by zero, generate explicit division */
5630 if (l2 == 0) {
5631 if (const_wanted)
5632 error("division by zero in constant");
5633 goto general_case;
5635 switch(op) {
5636 default: l1 /= l2; break;
5637 case '%': l1 %= l2; break;
5638 case TOK_UDIV: l1 = (U)l1 / l2; break;
5639 case TOK_UMOD: l1 = (U)l1 % l2; break;
5641 break;
5642 case TOK_SHL: l1 <<= l2; break;
5643 case TOK_SHR: l1 = (U)l1 >> l2; break;
5644 case TOK_SAR: l1 >>= l2; break;
5645 /* tests */
5646 case TOK_ULT: l1 = (U)l1 < (U)l2; break;
5647 case TOK_UGE: l1 = (U)l1 >= (U)l2; break;
5648 case TOK_EQ: l1 = l1 == l2; break;
5649 case TOK_NE: l1 = l1 != l2; break;
5650 case TOK_ULE: l1 = (U)l1 <= (U)l2; break;
5651 case TOK_UGT: l1 = (U)l1 > (U)l2; break;
5652 case TOK_LT: l1 = l1 < l2; break;
5653 case TOK_GE: l1 = l1 >= l2; break;
5654 case TOK_LE: l1 = l1 <= l2; break;
5655 case TOK_GT: l1 = l1 > l2; break;
5656 /* logical */
5657 case TOK_LAND: l1 = l1 && l2; break;
5658 case TOK_LOR: l1 = l1 || l2; break;
5659 default:
5660 goto general_case;
5662 v1->c.ll = l1;
5663 vtop--;
5664 } else {
5665 /* if commutative ops, put c2 as constant */
5666 if (c1 && (op == '+' || op == '&' || op == '^' ||
5667 op == '|' || op == '*')) {
5668 vswap();
5669 c2 = c1; //c = c1, c1 = c2, c2 = c;
5670 l2 = l1; //l = l1, l1 = l2, l2 = l;
5672 /* Filter out NOP operations like x*1, x-0, x&-1... */
5673 if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
5674 op == TOK_PDIV) &&
5675 l2 == 1) ||
5676 ((op == '+' || op == '-' || op == '|' || op == '^' ||
5677 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
5678 l2 == 0) ||
5679 (op == '&' &&
5680 l2 == -1))) {
5681 /* nothing to do */
5682 vtop--;
5683 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
5684 /* try to use shifts instead of muls or divs */
5685 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
5686 n = -1;
5687 while (l2) {
5688 l2 >>= 1;
5689 n++;
5691 vtop->c.ll = n;
5692 if (op == '*')
5693 op = TOK_SHL;
5694 else if (op == TOK_PDIV)
5695 op = TOK_SAR;
5696 else
5697 op = TOK_SHR;
5699 goto general_case;
5700 } else if (c2 && (op == '+' || op == '-') &&
5701 ((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) ==
5702 (VT_CONST | VT_SYM) ||
5703 (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
5704 /* symbol + constant case */
5705 if (op == '-')
5706 l2 = -l2;
5707 vtop--;
5708 vtop->c.ll += l2;
5709 } else {
5710 general_case:
5711 if (!nocode_wanted) {
5712 /* call low level op generator */
5713 if (t1 == VT_LLONG || t2 == VT_LLONG)
5714 gen_opl(op);
5715 else
5716 gen_opi(op);
5717 } else {
5718 vtop--;
5724 /* generate a floating point operation with constant propagation */
5725 void gen_opif(int op)
5727 int c1, c2;
5728 SValue *v1, *v2;
5729 long double f1, f2;
5731 v1 = vtop - 1;
5732 v2 = vtop;
5733 /* currently, we cannot do computations with forward symbols */
5734 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
5735 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
5736 if (c1 && c2) {
5737 if (v1->type.t == VT_FLOAT) {
5738 f1 = v1->c.f;
5739 f2 = v2->c.f;
5740 } else if (v1->type.t == VT_DOUBLE) {
5741 f1 = v1->c.d;
5742 f2 = v2->c.d;
5743 } else {
5744 f1 = v1->c.ld;
5745 f2 = v2->c.ld;
5748 /* NOTE: we only do constant propagation if finite number (not
5749 NaN or infinity) (ANSI spec) */
5750 if (!ieee_finite(f1) || !ieee_finite(f2))
5751 goto general_case;
5753 switch(op) {
5754 case '+': f1 += f2; break;
5755 case '-': f1 -= f2; break;
5756 case '*': f1 *= f2; break;
5757 case '/':
5758 if (f2 == 0.0) {
5759 if (const_wanted)
5760 error("division by zero in constant");
5761 goto general_case;
5763 f1 /= f2;
5764 break;
5765 /* XXX: also handles tests ? */
5766 default:
5767 goto general_case;
5769 /* XXX: overflow test ? */
5770 if (v1->type.t == VT_FLOAT) {
5771 v1->c.f = f1;
5772 } else if (v1->type.t == VT_DOUBLE) {
5773 v1->c.d = f1;
5774 } else {
5775 v1->c.ld = f1;
5777 vtop--;
5778 } else {
5779 general_case:
5780 if (!nocode_wanted) {
5781 gen_opf(op);
5782 } else {
5783 vtop--;
5788 static int pointed_size(CType *type)
5790 int align;
5791 return type_size(pointed_type(type), &align);
5794 static inline int is_null_pointer(SValue *p)
5796 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
5797 return 0;
5798 return ((p->type.t & VT_BTYPE) == VT_INT && p->c.i == 0) ||
5799 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.ll == 0);
5802 static inline int is_integer_btype(int bt)
5804 return (bt == VT_BYTE || bt == VT_SHORT ||
5805 bt == VT_INT || bt == VT_LLONG);
5808 /* check types for comparison or substraction of pointers */
5809 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
5811 CType *type1, *type2, tmp_type1, tmp_type2;
5812 int bt1, bt2;
5814 /* null pointers are accepted for all comparisons as gcc */
5815 if (is_null_pointer(p1) || is_null_pointer(p2))
5816 return;
5817 type1 = &p1->type;
5818 type2 = &p2->type;
5819 bt1 = type1->t & VT_BTYPE;
5820 bt2 = type2->t & VT_BTYPE;
5821 /* accept comparison between pointer and integer with a warning */
5822 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
5823 if (op != TOK_LOR && op != TOK_LAND )
5824 warning("comparison between pointer and integer");
5825 return;
5828 /* both must be pointers or implicit function pointers */
5829 if (bt1 == VT_PTR) {
5830 type1 = pointed_type(type1);
5831 } else if (bt1 != VT_FUNC)
5832 goto invalid_operands;
5834 if (bt2 == VT_PTR) {
5835 type2 = pointed_type(type2);
5836 } else if (bt2 != VT_FUNC) {
5837 invalid_operands:
5838 error("invalid operands to binary %s", get_tok_str(op, NULL));
5840 if ((type1->t & VT_BTYPE) == VT_VOID ||
5841 (type2->t & VT_BTYPE) == VT_VOID)
5842 return;
5843 tmp_type1 = *type1;
5844 tmp_type2 = *type2;
5845 tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
5846 tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
5847 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
5848 /* gcc-like error if '-' is used */
5849 if (op == '-')
5850 goto invalid_operands;
5851 else
5852 warning("comparison of distinct pointer types lacks a cast");
5856 /* generic gen_op: handles types problems */
5857 void gen_op(int op)
5859 int u, t1, t2, bt1, bt2, t;
5860 CType type1;
5862 t1 = vtop[-1].type.t;
5863 t2 = vtop[0].type.t;
5864 bt1 = t1 & VT_BTYPE;
5865 bt2 = t2 & VT_BTYPE;
5867 if (bt1 == VT_PTR || bt2 == VT_PTR) {
5868 /* at least one operand is a pointer */
5869 /* relationnal op: must be both pointers */
5870 if (op >= TOK_ULT && op <= TOK_LOR) {
5871 check_comparison_pointer_types(vtop - 1, vtop, op);
5872 /* pointers are handled are unsigned */
5873 #ifdef TCC_TARGET_X86_64
5874 t = VT_LLONG | VT_UNSIGNED;
5875 #else
5876 t = VT_INT | VT_UNSIGNED;
5877 #endif
5878 goto std_op;
5880 /* if both pointers, then it must be the '-' op */
5881 if (bt1 == VT_PTR && bt2 == VT_PTR) {
5882 if (op != '-')
5883 error("cannot use pointers here");
5884 check_comparison_pointer_types(vtop - 1, vtop, op);
5885 /* XXX: check that types are compatible */
5886 u = pointed_size(&vtop[-1].type);
5887 gen_opic(op);
5888 /* set to integer type */
5889 #ifdef TCC_TARGET_X86_64
5890 vtop->type.t = VT_LLONG;
5891 #else
5892 vtop->type.t = VT_INT;
5893 #endif
5894 vpushi(u);
5895 gen_op(TOK_PDIV);
5896 } else {
5897 /* exactly one pointer : must be '+' or '-'. */
5898 if (op != '-' && op != '+')
5899 error("cannot use pointers here");
5900 /* Put pointer as first operand */
5901 if (bt2 == VT_PTR) {
5902 vswap();
5903 swap(&t1, &t2);
5905 type1 = vtop[-1].type;
5906 #ifdef TCC_TARGET_X86_64
5907 vpushll(pointed_size(&vtop[-1].type));
5908 #else
5909 /* XXX: cast to int ? (long long case) */
5910 vpushi(pointed_size(&vtop[-1].type));
5911 #endif
5912 gen_op('*');
5913 #ifdef CONFIG_TCC_BCHECK
5914 /* if evaluating constant expression, no code should be
5915 generated, so no bound check */
5916 if (do_bounds_check && !const_wanted) {
5917 /* if bounded pointers, we generate a special code to
5918 test bounds */
5919 if (op == '-') {
5920 vpushi(0);
5921 vswap();
5922 gen_op('-');
5924 gen_bounded_ptr_add();
5925 } else
5926 #endif
5928 gen_opic(op);
5930 /* put again type if gen_opic() swaped operands */
5931 vtop->type = type1;
5933 } else if (is_float(bt1) || is_float(bt2)) {
5934 /* compute bigger type and do implicit casts */
5935 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
5936 t = VT_LDOUBLE;
5937 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
5938 t = VT_DOUBLE;
5939 } else {
5940 t = VT_FLOAT;
5942 /* floats can only be used for a few operations */
5943 if (op != '+' && op != '-' && op != '*' && op != '/' &&
5944 (op < TOK_ULT || op > TOK_GT))
5945 error("invalid operands for binary operation");
5946 goto std_op;
5947 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
5948 /* cast to biggest op */
5949 t = VT_LLONG;
5950 /* convert to unsigned if it does not fit in a long long */
5951 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
5952 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
5953 t |= VT_UNSIGNED;
5954 goto std_op;
5955 } else {
5956 /* integer operations */
5957 t = VT_INT;
5958 /* convert to unsigned if it does not fit in an integer */
5959 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
5960 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
5961 t |= VT_UNSIGNED;
5962 std_op:
5963 /* XXX: currently, some unsigned operations are explicit, so
5964 we modify them here */
5965 if (t & VT_UNSIGNED) {
5966 if (op == TOK_SAR)
5967 op = TOK_SHR;
5968 else if (op == '/')
5969 op = TOK_UDIV;
5970 else if (op == '%')
5971 op = TOK_UMOD;
5972 else if (op == TOK_LT)
5973 op = TOK_ULT;
5974 else if (op == TOK_GT)
5975 op = TOK_UGT;
5976 else if (op == TOK_LE)
5977 op = TOK_ULE;
5978 else if (op == TOK_GE)
5979 op = TOK_UGE;
5981 vswap();
5982 type1.t = t;
5983 gen_cast(&type1);
5984 vswap();
5985 /* special case for shifts and long long: we keep the shift as
5986 an integer */
5987 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
5988 type1.t = VT_INT;
5989 gen_cast(&type1);
5990 if (is_float(t))
5991 gen_opif(op);
5992 else
5993 gen_opic(op);
5994 if (op >= TOK_ULT && op <= TOK_GT) {
5995 /* relationnal op: the result is an int */
5996 vtop->type.t = VT_INT;
5997 } else {
5998 vtop->type.t = t;
6003 #ifndef TCC_TARGET_ARM
6004 /* generic itof for unsigned long long case */
6005 void gen_cvt_itof1(int t)
6007 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
6008 (VT_LLONG | VT_UNSIGNED)) {
6010 if (t == VT_FLOAT)
6011 vpush_global_sym(&func_old_type, TOK___floatundisf);
6012 #if LDOUBLE_SIZE != 8
6013 else if (t == VT_LDOUBLE)
6014 vpush_global_sym(&func_old_type, TOK___floatundixf);
6015 #endif
6016 else
6017 vpush_global_sym(&func_old_type, TOK___floatundidf);
6018 vrott(2);
6019 gfunc_call(1);
6020 vpushi(0);
6021 vtop->r = REG_FRET;
6022 } else {
6023 gen_cvt_itof(t);
6026 #endif
6028 /* generic ftoi for unsigned long long case */
6029 void gen_cvt_ftoi1(int t)
6031 int st;
6033 if (t == (VT_LLONG | VT_UNSIGNED)) {
6034 /* not handled natively */
6035 st = vtop->type.t & VT_BTYPE;
6036 if (st == VT_FLOAT)
6037 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
6038 #if LDOUBLE_SIZE != 8
6039 else if (st == VT_LDOUBLE)
6040 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
6041 #endif
6042 else
6043 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
6044 vrott(2);
6045 gfunc_call(1);
6046 vpushi(0);
6047 vtop->r = REG_IRET;
6048 vtop->r2 = REG_LRET;
6049 } else {
6050 gen_cvt_ftoi(t);
6054 /* force char or short cast */
6055 void force_charshort_cast(int t)
6057 int bits, dbt;
6058 dbt = t & VT_BTYPE;
6059 /* XXX: add optimization if lvalue : just change type and offset */
6060 if (dbt == VT_BYTE)
6061 bits = 8;
6062 else
6063 bits = 16;
6064 if (t & VT_UNSIGNED) {
6065 vpushi((1 << bits) - 1);
6066 gen_op('&');
6067 } else {
6068 bits = 32 - bits;
6069 vpushi(bits);
6070 gen_op(TOK_SHL);
6071 /* result must be signed or the SAR is converted to an SHL
6072 This was not the case when "t" was a signed short
6073 and the last value on the stack was an unsigned int */
6074 vtop->type.t &= ~VT_UNSIGNED;
6075 vpushi(bits);
6076 gen_op(TOK_SAR);
6080 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
6081 static void gen_cast(CType *type)
6083 int sbt, dbt, sf, df, c, p;
6085 /* special delayed cast for char/short */
6086 /* XXX: in some cases (multiple cascaded casts), it may still
6087 be incorrect */
6088 if (vtop->r & VT_MUSTCAST) {
6089 vtop->r &= ~VT_MUSTCAST;
6090 force_charshort_cast(vtop->type.t);
6093 /* bitfields first get cast to ints */
6094 if (vtop->type.t & VT_BITFIELD) {
6095 gv(RC_INT);
6098 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
6099 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
6101 if (sbt != dbt) {
6102 sf = is_float(sbt);
6103 df = is_float(dbt);
6104 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
6105 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
6106 if (c) {
6107 /* constant case: we can do it now */
6108 /* XXX: in ISOC, cannot do it if error in convert */
6109 if (sbt == VT_FLOAT)
6110 vtop->c.ld = vtop->c.f;
6111 else if (sbt == VT_DOUBLE)
6112 vtop->c.ld = vtop->c.d;
6114 if (df) {
6115 if ((sbt & VT_BTYPE) == VT_LLONG) {
6116 if (sbt & VT_UNSIGNED)
6117 vtop->c.ld = vtop->c.ull;
6118 else
6119 vtop->c.ld = vtop->c.ll;
6120 } else if(!sf) {
6121 if (sbt & VT_UNSIGNED)
6122 vtop->c.ld = vtop->c.ui;
6123 else
6124 vtop->c.ld = vtop->c.i;
6127 if (dbt == VT_FLOAT)
6128 vtop->c.f = (float)vtop->c.ld;
6129 else if (dbt == VT_DOUBLE)
6130 vtop->c.d = (double)vtop->c.ld;
6131 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
6132 vtop->c.ull = (unsigned long long)vtop->c.ld;
6133 } else if (sf && dbt == VT_BOOL) {
6134 vtop->c.i = (vtop->c.ld != 0);
6135 } else {
6136 if(sf)
6137 vtop->c.ll = (long long)vtop->c.ld;
6138 else if (sbt == (VT_LLONG|VT_UNSIGNED))
6139 vtop->c.ll = vtop->c.ull;
6140 else if (sbt & VT_UNSIGNED)
6141 vtop->c.ll = vtop->c.ui;
6142 else if (sbt != VT_LLONG)
6143 vtop->c.ll = vtop->c.i;
6145 if (dbt == (VT_LLONG|VT_UNSIGNED))
6146 vtop->c.ull = vtop->c.ll;
6147 else if (dbt == VT_BOOL)
6148 vtop->c.i = (vtop->c.ll != 0);
6149 else if (dbt != VT_LLONG) {
6150 int s = 0;
6151 if ((dbt & VT_BTYPE) == VT_BYTE)
6152 s = 24;
6153 else if ((dbt & VT_BTYPE) == VT_SHORT)
6154 s = 16;
6156 if(dbt & VT_UNSIGNED)
6157 vtop->c.ui = ((unsigned int)vtop->c.ll << s) >> s;
6158 else
6159 vtop->c.i = ((int)vtop->c.ll << s) >> s;
6162 } else if (p && dbt == VT_BOOL) {
6163 vtop->r = VT_CONST;
6164 vtop->c.i = 1;
6165 } else if (!nocode_wanted) {
6166 /* non constant case: generate code */
6167 if (sf && df) {
6168 /* convert from fp to fp */
6169 gen_cvt_ftof(dbt);
6170 } else if (df) {
6171 /* convert int to fp */
6172 gen_cvt_itof1(dbt);
6173 } else if (sf) {
6174 /* convert fp to int */
6175 if (dbt == VT_BOOL) {
6176 vpushi(0);
6177 gen_op(TOK_NE);
6178 } else {
6179 /* we handle char/short/etc... with generic code */
6180 if (dbt != (VT_INT | VT_UNSIGNED) &&
6181 dbt != (VT_LLONG | VT_UNSIGNED) &&
6182 dbt != VT_LLONG)
6183 dbt = VT_INT;
6184 gen_cvt_ftoi1(dbt);
6185 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
6186 /* additional cast for char/short... */
6187 vtop->type.t = dbt;
6188 gen_cast(type);
6191 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
6192 if ((sbt & VT_BTYPE) != VT_LLONG) {
6193 /* scalar to long long */
6194 #ifndef TCC_TARGET_X86_64
6195 /* machine independent conversion */
6196 gv(RC_INT);
6197 /* generate high word */
6198 if (sbt == (VT_INT | VT_UNSIGNED)) {
6199 vpushi(0);
6200 gv(RC_INT);
6201 } else {
6202 gv_dup();
6203 vpushi(31);
6204 gen_op(TOK_SAR);
6206 /* patch second register */
6207 vtop[-1].r2 = vtop->r;
6208 vpop();
6209 #else
6210 int r = gv(RC_INT);
6211 if (sbt != (VT_INT | VT_UNSIGNED)) {
6212 /* x86_64 specific: movslq */
6213 o(0x6348);
6214 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
6216 #endif
6218 } else if (dbt == VT_BOOL) {
6219 /* scalar to bool */
6220 vpushi(0);
6221 gen_op(TOK_NE);
6222 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
6223 (dbt & VT_BTYPE) == VT_SHORT) {
6224 if (sbt == VT_PTR) {
6225 vtop->type.t = VT_INT;
6226 warning("nonportable conversion from pointer to char/short");
6228 force_charshort_cast(dbt);
6229 } else if ((dbt & VT_BTYPE) == VT_INT) {
6230 /* scalar to int */
6231 if (sbt == VT_LLONG) {
6232 /* from long long: just take low order word */
6233 lexpand();
6234 vpop();
6236 /* if lvalue and single word type, nothing to do because
6237 the lvalue already contains the real type size (see
6238 VT_LVAL_xxx constants) */
6241 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
6242 /* if we are casting between pointer types,
6243 we must update the VT_LVAL_xxx size */
6244 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
6245 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
6247 vtop->type = *type;
6250 /* return type size. Put alignment at 'a' */
6251 static int type_size(CType *type, int *a)
6253 Sym *s;
6254 int bt;
6256 bt = type->t & VT_BTYPE;
6257 if (bt == VT_STRUCT) {
6258 /* struct/union */
6259 s = type->ref;
6260 *a = s->r;
6261 return s->c;
6262 } else if (bt == VT_PTR) {
6263 if (type->t & VT_ARRAY) {
6264 int ts;
6266 s = type->ref;
6267 ts = type_size(&s->type, a);
6269 if (ts < 0 && s->c < 0)
6270 ts = -ts;
6272 return ts * s->c;
6273 } else {
6274 *a = PTR_SIZE;
6275 return PTR_SIZE;
6277 } else if (bt == VT_LDOUBLE) {
6278 *a = LDOUBLE_ALIGN;
6279 return LDOUBLE_SIZE;
6280 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
6281 #ifdef TCC_TARGET_I386
6282 #ifdef TCC_TARGET_PE
6283 *a = 8;
6284 #else
6285 *a = 4;
6286 #endif
6287 #elif defined(TCC_TARGET_ARM)
6288 #ifdef TCC_ARM_EABI
6289 *a = 8;
6290 #else
6291 *a = 4;
6292 #endif
6293 #else
6294 *a = 8;
6295 #endif
6296 return 8;
6297 } else if (bt == VT_INT || bt == VT_ENUM || bt == VT_FLOAT) {
6298 *a = 4;
6299 return 4;
6300 } else if (bt == VT_SHORT) {
6301 *a = 2;
6302 return 2;
6303 } else {
6304 /* char, void, function, _Bool */
6305 *a = 1;
6306 return 1;
6310 /* return the pointed type of t */
6311 static inline CType *pointed_type(CType *type)
6313 return &type->ref->type;
6316 /* modify type so that its it is a pointer to type. */
6317 static void mk_pointer(CType *type)
6319 Sym *s;
6320 s = sym_push(SYM_FIELD, type, 0, -1);
6321 type->t = VT_PTR | (type->t & ~VT_TYPE);
6322 type->ref = s;
6325 /* compare function types. OLD functions match any new functions */
6326 static int is_compatible_func(CType *type1, CType *type2)
6328 Sym *s1, *s2;
6330 s1 = type1->ref;
6331 s2 = type2->ref;
6332 if (!is_compatible_types(&s1->type, &s2->type))
6333 return 0;
6334 /* check func_call */
6335 if (FUNC_CALL(s1->r) != FUNC_CALL(s2->r))
6336 return 0;
6337 /* XXX: not complete */
6338 if (s1->c == FUNC_OLD || s2->c == FUNC_OLD)
6339 return 1;
6340 if (s1->c != s2->c)
6341 return 0;
6342 while (s1 != NULL) {
6343 if (s2 == NULL)
6344 return 0;
6345 if (!is_compatible_parameter_types(&s1->type, &s2->type))
6346 return 0;
6347 s1 = s1->next;
6348 s2 = s2->next;
6350 if (s2)
6351 return 0;
6352 return 1;
6355 /* return true if type1 and type2 are the same. If unqualified is
6356 true, qualifiers on the types are ignored.
6358 - enums are not checked as gcc __builtin_types_compatible_p ()
6360 static int compare_types(CType *type1, CType *type2, int unqualified)
6362 int bt1, t1, t2;
6364 t1 = type1->t & VT_TYPE;
6365 t2 = type2->t & VT_TYPE;
6366 if (unqualified) {
6367 /* strip qualifiers before comparing */
6368 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
6369 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
6371 /* XXX: bitfields ? */
6372 if (t1 != t2)
6373 return 0;
6374 /* test more complicated cases */
6375 bt1 = t1 & VT_BTYPE;
6376 if (bt1 == VT_PTR) {
6377 type1 = pointed_type(type1);
6378 type2 = pointed_type(type2);
6379 return is_compatible_types(type1, type2);
6380 } else if (bt1 == VT_STRUCT) {
6381 return (type1->ref == type2->ref);
6382 } else if (bt1 == VT_FUNC) {
6383 return is_compatible_func(type1, type2);
6384 } else {
6385 return 1;
6389 /* return true if type1 and type2 are exactly the same (including
6390 qualifiers).
6392 static int is_compatible_types(CType *type1, CType *type2)
6394 return compare_types(type1,type2,0);
6397 /* return true if type1 and type2 are the same (ignoring qualifiers).
6399 static int is_compatible_parameter_types(CType *type1, CType *type2)
6401 return compare_types(type1,type2,1);
6404 /* print a type. If 'varstr' is not NULL, then the variable is also
6405 printed in the type */
6406 /* XXX: union */
6407 /* XXX: add array and function pointers */
6408 void type_to_str(char *buf, int buf_size,
6409 CType *type, const char *varstr)
6411 int bt, v, t;
6412 Sym *s, *sa;
6413 char buf1[256];
6414 const char *tstr;
6416 t = type->t & VT_TYPE;
6417 bt = t & VT_BTYPE;
6418 buf[0] = '\0';
6419 if (t & VT_CONSTANT)
6420 pstrcat(buf, buf_size, "const ");
6421 if (t & VT_VOLATILE)
6422 pstrcat(buf, buf_size, "volatile ");
6423 if (t & VT_UNSIGNED)
6424 pstrcat(buf, buf_size, "unsigned ");
6425 switch(bt) {
6426 case VT_VOID:
6427 tstr = "void";
6428 goto add_tstr;
6429 case VT_BOOL:
6430 tstr = "_Bool";
6431 goto add_tstr;
6432 case VT_BYTE:
6433 tstr = "char";
6434 goto add_tstr;
6435 case VT_SHORT:
6436 tstr = "short";
6437 goto add_tstr;
6438 case VT_INT:
6439 tstr = "int";
6440 goto add_tstr;
6441 case VT_LONG:
6442 tstr = "long";
6443 goto add_tstr;
6444 case VT_LLONG:
6445 tstr = "long long";
6446 goto add_tstr;
6447 case VT_FLOAT:
6448 tstr = "float";
6449 goto add_tstr;
6450 case VT_DOUBLE:
6451 tstr = "double";
6452 goto add_tstr;
6453 case VT_LDOUBLE:
6454 tstr = "long double";
6455 add_tstr:
6456 pstrcat(buf, buf_size, tstr);
6457 break;
6458 case VT_ENUM:
6459 case VT_STRUCT:
6460 if (bt == VT_STRUCT)
6461 tstr = "struct ";
6462 else
6463 tstr = "enum ";
6464 pstrcat(buf, buf_size, tstr);
6465 v = type->ref->v & ~SYM_STRUCT;
6466 if (v >= SYM_FIRST_ANOM)
6467 pstrcat(buf, buf_size, "<anonymous>");
6468 else
6469 pstrcat(buf, buf_size, get_tok_str(v, NULL));
6470 break;
6471 case VT_FUNC:
6472 s = type->ref;
6473 type_to_str(buf, buf_size, &s->type, varstr);
6474 pstrcat(buf, buf_size, "(");
6475 sa = s->next;
6476 while (sa != NULL) {
6477 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
6478 pstrcat(buf, buf_size, buf1);
6479 sa = sa->next;
6480 if (sa)
6481 pstrcat(buf, buf_size, ", ");
6483 pstrcat(buf, buf_size, ")");
6484 goto no_var;
6485 case VT_PTR:
6486 s = type->ref;
6487 pstrcpy(buf1, sizeof(buf1), "*");
6488 if (varstr)
6489 pstrcat(buf1, sizeof(buf1), varstr);
6490 type_to_str(buf, buf_size, &s->type, buf1);
6491 goto no_var;
6493 if (varstr) {
6494 pstrcat(buf, buf_size, " ");
6495 pstrcat(buf, buf_size, varstr);
6497 no_var: ;
6500 /* verify type compatibility to store vtop in 'dt' type, and generate
6501 casts if needed. */
6502 static void gen_assign_cast(CType *dt)
6504 CType *st, *type1, *type2, tmp_type1, tmp_type2;
6505 char buf1[256], buf2[256];
6506 int dbt, sbt;
6508 st = &vtop->type; /* source type */
6509 dbt = dt->t & VT_BTYPE;
6510 sbt = st->t & VT_BTYPE;
6511 if (dt->t & VT_CONSTANT)
6512 warning("assignment of read-only location");
6513 switch(dbt) {
6514 case VT_PTR:
6515 /* special cases for pointers */
6516 /* '0' can also be a pointer */
6517 if (is_null_pointer(vtop))
6518 goto type_ok;
6519 /* accept implicit pointer to integer cast with warning */
6520 if (is_integer_btype(sbt)) {
6521 warning("assignment makes pointer from integer without a cast");
6522 goto type_ok;
6524 type1 = pointed_type(dt);
6525 /* a function is implicitely a function pointer */
6526 if (sbt == VT_FUNC) {
6527 if ((type1->t & VT_BTYPE) != VT_VOID &&
6528 !is_compatible_types(pointed_type(dt), st))
6529 goto error;
6530 else
6531 goto type_ok;
6533 if (sbt != VT_PTR)
6534 goto error;
6535 type2 = pointed_type(st);
6536 if ((type1->t & VT_BTYPE) == VT_VOID ||
6537 (type2->t & VT_BTYPE) == VT_VOID) {
6538 /* void * can match anything */
6539 } else {
6540 /* exact type match, except for unsigned */
6541 tmp_type1 = *type1;
6542 tmp_type2 = *type2;
6543 tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
6544 tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
6545 if (!is_compatible_types(&tmp_type1, &tmp_type2))
6546 warning("assignment from incompatible pointer type");
6548 /* check const and volatile */
6549 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
6550 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
6551 warning("assignment discards qualifiers from pointer target type");
6552 break;
6553 case VT_BYTE:
6554 case VT_SHORT:
6555 case VT_INT:
6556 case VT_LLONG:
6557 if (sbt == VT_PTR || sbt == VT_FUNC) {
6558 warning("assignment makes integer from pointer without a cast");
6560 /* XXX: more tests */
6561 break;
6562 case VT_STRUCT:
6563 tmp_type1 = *dt;
6564 tmp_type2 = *st;
6565 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
6566 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
6567 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
6568 error:
6569 type_to_str(buf1, sizeof(buf1), st, NULL);
6570 type_to_str(buf2, sizeof(buf2), dt, NULL);
6571 error("cannot cast '%s' to '%s'", buf1, buf2);
6573 break;
6575 type_ok:
6576 gen_cast(dt);
6579 /* store vtop in lvalue pushed on stack */
6580 void vstore(void)
6582 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
6584 ft = vtop[-1].type.t;
6585 sbt = vtop->type.t & VT_BTYPE;
6586 dbt = ft & VT_BTYPE;
6587 if (((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
6588 (sbt == VT_INT && dbt == VT_SHORT)) {
6589 /* optimize char/short casts */
6590 delayed_cast = VT_MUSTCAST;
6591 vtop->type.t = ft & (VT_TYPE & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT)));
6592 /* XXX: factorize */
6593 if (ft & VT_CONSTANT)
6594 warning("assignment of read-only location");
6595 } else {
6596 delayed_cast = 0;
6597 if (!(ft & VT_BITFIELD))
6598 gen_assign_cast(&vtop[-1].type);
6601 if (sbt == VT_STRUCT) {
6602 /* if structure, only generate pointer */
6603 /* structure assignment : generate memcpy */
6604 /* XXX: optimize if small size */
6605 if (!nocode_wanted) {
6606 size = type_size(&vtop->type, &align);
6608 #ifdef TCC_ARM_EABI
6609 if(!(align & 7))
6610 vpush_global_sym(&func_old_type, TOK_memcpy8);
6611 else if(!(align & 3))
6612 vpush_global_sym(&func_old_type, TOK_memcpy4);
6613 else
6614 #endif
6615 vpush_global_sym(&func_old_type, TOK_memcpy);
6617 /* destination */
6618 vpushv(vtop - 2);
6619 vtop->type.t = VT_INT;
6620 gaddrof();
6621 /* source */
6622 vpushv(vtop - 2);
6623 vtop->type.t = VT_INT;
6624 gaddrof();
6625 /* type size */
6626 vpushi(size);
6627 gfunc_call(3);
6629 vswap();
6630 vpop();
6631 } else {
6632 vswap();
6633 vpop();
6635 /* leave source on stack */
6636 } else if (ft & VT_BITFIELD) {
6637 /* bitfield store handling */
6638 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
6639 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
6640 /* remove bit field info to avoid loops */
6641 vtop[-1].type.t = ft & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
6643 /* duplicate source into other register */
6644 gv_dup();
6645 vswap();
6646 vrott(3);
6648 if((ft & VT_BTYPE) == VT_BOOL) {
6649 gen_cast(&vtop[-1].type);
6650 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
6653 /* duplicate destination */
6654 vdup();
6655 vtop[-1] = vtop[-2];
6657 /* mask and shift source */
6658 if((ft & VT_BTYPE) != VT_BOOL) {
6659 if((ft & VT_BTYPE) == VT_LLONG) {
6660 vpushll((1ULL << bit_size) - 1ULL);
6661 } else {
6662 vpushi((1 << bit_size) - 1);
6664 gen_op('&');
6666 vpushi(bit_pos);
6667 gen_op(TOK_SHL);
6668 /* load destination, mask and or with source */
6669 vswap();
6670 if((ft & VT_BTYPE) == VT_LLONG) {
6671 vpushll(~(((1ULL << bit_size) - 1ULL) << bit_pos));
6672 } else {
6673 vpushi(~(((1 << bit_size) - 1) << bit_pos));
6675 gen_op('&');
6676 gen_op('|');
6677 /* store result */
6678 vstore();
6680 /* pop off shifted source from "duplicate source..." above */
6681 vpop();
6683 } else {
6684 #ifdef CONFIG_TCC_BCHECK
6685 /* bound check case */
6686 if (vtop[-1].r & VT_MUSTBOUND) {
6687 vswap();
6688 gbound();
6689 vswap();
6691 #endif
6692 if (!nocode_wanted) {
6693 rc = RC_INT;
6694 if (is_float(ft)) {
6695 rc = RC_FLOAT;
6696 #ifdef TCC_TARGET_X86_64
6697 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
6698 rc = RC_ST0;
6700 #endif
6702 r = gv(rc); /* generate value */
6703 /* if lvalue was saved on stack, must read it */
6704 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
6705 SValue sv;
6706 t = get_reg(RC_INT);
6707 #ifdef TCC_TARGET_X86_64
6708 sv.type.t = VT_PTR;
6709 #else
6710 sv.type.t = VT_INT;
6711 #endif
6712 sv.r = VT_LOCAL | VT_LVAL;
6713 sv.c.ul = vtop[-1].c.ul;
6714 load(t, &sv);
6715 vtop[-1].r = t | VT_LVAL;
6717 store(r, vtop - 1);
6718 #ifndef TCC_TARGET_X86_64
6719 /* two word case handling : store second register at word + 4 */
6720 if ((ft & VT_BTYPE) == VT_LLONG) {
6721 vswap();
6722 /* convert to int to increment easily */
6723 vtop->type.t = VT_INT;
6724 gaddrof();
6725 vpushi(4);
6726 gen_op('+');
6727 vtop->r |= VT_LVAL;
6728 vswap();
6729 /* XXX: it works because r2 is spilled last ! */
6730 store(vtop->r2, vtop - 1);
6732 #endif
6734 vswap();
6735 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
6736 vtop->r |= delayed_cast;
6740 /* post defines POST/PRE add. c is the token ++ or -- */
6741 void inc(int post, int c)
6743 test_lvalue();
6744 vdup(); /* save lvalue */
6745 if (post) {
6746 gv_dup(); /* duplicate value */
6747 vrotb(3);
6748 vrotb(3);
6750 /* add constant */
6751 vpushi(c - TOK_MID);
6752 gen_op('+');
6753 vstore(); /* store value */
6754 if (post)
6755 vpop(); /* if post op, return saved value */
6758 /* Parse GNUC __attribute__ extension. Currently, the following
6759 extensions are recognized:
6760 - aligned(n) : set data/function alignment.
6761 - packed : force data alignment to 1
6762 - section(x) : generate data/code in this section.
6763 - unused : currently ignored, but may be used someday.
6764 - regparm(n) : pass function parameters in registers (i386 only)
6766 static void parse_attribute(AttributeDef *ad)
6768 int t, n;
6770 while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
6771 next();
6772 skip('(');
6773 skip('(');
6774 while (tok != ')') {
6775 if (tok < TOK_IDENT)
6776 expect("attribute name");
6777 t = tok;
6778 next();
6779 switch(t) {
6780 case TOK_SECTION1:
6781 case TOK_SECTION2:
6782 skip('(');
6783 if (tok != TOK_STR)
6784 expect("section name");
6785 ad->section = find_section(tcc_state, (char *)tokc.cstr->data);
6786 next();
6787 skip(')');
6788 break;
6789 case TOK_ALIGNED1:
6790 case TOK_ALIGNED2:
6791 if (tok == '(') {
6792 next();
6793 n = expr_const();
6794 if (n <= 0 || (n & (n - 1)) != 0)
6795 error("alignment must be a positive power of two");
6796 skip(')');
6797 } else {
6798 n = MAX_ALIGN;
6800 ad->aligned = n;
6801 break;
6802 case TOK_PACKED1:
6803 case TOK_PACKED2:
6804 ad->packed = 1;
6805 break;
6806 case TOK_UNUSED1:
6807 case TOK_UNUSED2:
6808 /* currently, no need to handle it because tcc does not
6809 track unused objects */
6810 break;
6811 case TOK_NORETURN1:
6812 case TOK_NORETURN2:
6813 /* currently, no need to handle it because tcc does not
6814 track unused objects */
6815 break;
6816 case TOK_CDECL1:
6817 case TOK_CDECL2:
6818 case TOK_CDECL3:
6819 FUNC_CALL(ad->func_attr) = FUNC_CDECL;
6820 break;
6821 case TOK_STDCALL1:
6822 case TOK_STDCALL2:
6823 case TOK_STDCALL3:
6824 FUNC_CALL(ad->func_attr) = FUNC_STDCALL;
6825 break;
6826 #ifdef TCC_TARGET_I386
6827 case TOK_REGPARM1:
6828 case TOK_REGPARM2:
6829 skip('(');
6830 n = expr_const();
6831 if (n > 3)
6832 n = 3;
6833 else if (n < 0)
6834 n = 0;
6835 if (n > 0)
6836 FUNC_CALL(ad->func_attr) = FUNC_FASTCALL1 + n - 1;
6837 skip(')');
6838 break;
6839 case TOK_FASTCALL1:
6840 case TOK_FASTCALL2:
6841 case TOK_FASTCALL3:
6842 FUNC_CALL(ad->func_attr) = FUNC_FASTCALLW;
6843 break;
6844 #endif
6845 case TOK_DLLEXPORT:
6846 FUNC_EXPORT(ad->func_attr) = 1;
6847 break;
6848 default:
6849 if (tcc_state->warn_unsupported)
6850 warning("'%s' attribute ignored", get_tok_str(t, NULL));
6851 /* skip parameters */
6852 if (tok == '(') {
6853 int parenthesis = 0;
6854 do {
6855 if (tok == '(')
6856 parenthesis++;
6857 else if (tok == ')')
6858 parenthesis--;
6859 next();
6860 } while (parenthesis && tok != -1);
6862 break;
6864 if (tok != ',')
6865 break;
6866 next();
6868 skip(')');
6869 skip(')');
6873 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
6874 static void struct_decl(CType *type, int u)
6876 int a, v, size, align, maxalign, c, offset;
6877 int bit_size, bit_pos, bsize, bt, lbit_pos, prevbt;
6878 Sym *s, *ss, *ass, **ps;
6879 AttributeDef ad;
6880 CType type1, btype;
6882 a = tok; /* save decl type */
6883 next();
6884 if (tok != '{') {
6885 v = tok;
6886 next();
6887 /* struct already defined ? return it */
6888 if (v < TOK_IDENT)
6889 expect("struct/union/enum name");
6890 s = struct_find(v);
6891 if (s) {
6892 if (s->type.t != a)
6893 error("invalid type");
6894 goto do_decl;
6896 } else {
6897 v = anon_sym++;
6899 type1.t = a;
6900 /* we put an undefined size for struct/union */
6901 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
6902 s->r = 0; /* default alignment is zero as gcc */
6903 /* put struct/union/enum name in type */
6904 do_decl:
6905 type->t = u;
6906 type->ref = s;
6908 if (tok == '{') {
6909 next();
6910 if (s->c != -1)
6911 error("struct/union/enum already defined");
6912 /* cannot be empty */
6913 c = 0;
6914 /* non empty enums are not allowed */
6915 if (a == TOK_ENUM) {
6916 for(;;) {
6917 v = tok;
6918 if (v < TOK_UIDENT)
6919 expect("identifier");
6920 next();
6921 if (tok == '=') {
6922 next();
6923 c = expr_const();
6925 /* enum symbols have static storage */
6926 ss = sym_push(v, &int_type, VT_CONST, c);
6927 ss->type.t |= VT_STATIC;
6928 if (tok != ',')
6929 break;
6930 next();
6931 c++;
6932 /* NOTE: we accept a trailing comma */
6933 if (tok == '}')
6934 break;
6936 skip('}');
6937 } else {
6938 maxalign = 1;
6939 ps = &s->next;
6940 prevbt = VT_INT;
6941 bit_pos = 0;
6942 offset = 0;
6943 while (tok != '}') {
6944 parse_btype(&btype, &ad);
6945 while (1) {
6946 bit_size = -1;
6947 v = 0;
6948 type1 = btype;
6949 if (tok != ':') {
6950 type_decl(&type1, &ad, &v, TYPE_DIRECT | TYPE_ABSTRACT);
6951 if (v == 0 && (type1.t & VT_BTYPE) != VT_STRUCT)
6952 expect("identifier");
6953 if ((type1.t & VT_BTYPE) == VT_FUNC ||
6954 (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
6955 error("invalid type for '%s'",
6956 get_tok_str(v, NULL));
6958 if (tok == ':') {
6959 next();
6960 bit_size = expr_const();
6961 /* XXX: handle v = 0 case for messages */
6962 if (bit_size < 0)
6963 error("negative width in bit-field '%s'",
6964 get_tok_str(v, NULL));
6965 if (v && bit_size == 0)
6966 error("zero width for bit-field '%s'",
6967 get_tok_str(v, NULL));
6969 size = type_size(&type1, &align);
6970 if (ad.aligned) {
6971 if (align < ad.aligned)
6972 align = ad.aligned;
6973 } else if (ad.packed) {
6974 align = 1;
6975 } else if (*tcc_state->pack_stack_ptr) {
6976 if (align > *tcc_state->pack_stack_ptr)
6977 align = *tcc_state->pack_stack_ptr;
6979 lbit_pos = 0;
6980 if (bit_size >= 0) {
6981 bt = type1.t & VT_BTYPE;
6982 if (bt != VT_INT &&
6983 bt != VT_BYTE &&
6984 bt != VT_SHORT &&
6985 bt != VT_BOOL &&
6986 bt != VT_ENUM &&
6987 bt != VT_LLONG)
6988 error("bitfields must have scalar type");
6989 bsize = size * 8;
6990 if (bit_size > bsize) {
6991 error("width of '%s' exceeds its type",
6992 get_tok_str(v, NULL));
6993 } else if (bit_size == bsize) {
6994 /* no need for bit fields */
6995 bit_pos = 0;
6996 } else if (bit_size == 0) {
6997 /* XXX: what to do if only padding in a
6998 structure ? */
6999 /* zero size: means to pad */
7000 bit_pos = 0;
7001 } else {
7002 /* we do not have enough room ?
7003 did the type change?
7004 is it a union? */
7005 if ((bit_pos + bit_size) > bsize ||
7006 bt != prevbt || a == TOK_UNION)
7007 bit_pos = 0;
7008 lbit_pos = bit_pos;
7009 /* XXX: handle LSB first */
7010 type1.t |= VT_BITFIELD |
7011 (bit_pos << VT_STRUCT_SHIFT) |
7012 (bit_size << (VT_STRUCT_SHIFT + 6));
7013 bit_pos += bit_size;
7015 prevbt = bt;
7016 } else {
7017 bit_pos = 0;
7019 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
7020 /* add new memory data only if starting
7021 bit field */
7022 if (lbit_pos == 0) {
7023 if (a == TOK_STRUCT) {
7024 c = (c + align - 1) & -align;
7025 offset = c;
7026 if (size > 0)
7027 c += size;
7028 } else {
7029 offset = 0;
7030 if (size > c)
7031 c = size;
7033 if (align > maxalign)
7034 maxalign = align;
7036 #if 0
7037 printf("add field %s offset=%d",
7038 get_tok_str(v, NULL), offset);
7039 if (type1.t & VT_BITFIELD) {
7040 printf(" pos=%d size=%d",
7041 (type1.t >> VT_STRUCT_SHIFT) & 0x3f,
7042 (type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
7044 printf("\n");
7045 #endif
7047 if (v == 0 && (type1.t & VT_BTYPE) == VT_STRUCT) {
7048 ass = type1.ref;
7049 while ((ass = ass->next) != NULL) {
7050 ss = sym_push(ass->v, &ass->type, 0, offset + ass->c);
7051 *ps = ss;
7052 ps = &ss->next;
7054 } else if (v) {
7055 ss = sym_push(v | SYM_FIELD, &type1, 0, offset);
7056 *ps = ss;
7057 ps = &ss->next;
7059 if (tok == ';' || tok == TOK_EOF)
7060 break;
7061 skip(',');
7063 skip(';');
7065 skip('}');
7066 /* store size and alignment */
7067 s->c = (c + maxalign - 1) & -maxalign;
7068 s->r = maxalign;
7073 /* return 0 if no type declaration. otherwise, return the basic type
7074 and skip it.
7076 static int parse_btype(CType *type, AttributeDef *ad)
7078 int t, u, type_found, typespec_found, typedef_found;
7079 Sym *s;
7080 CType type1;
7082 memset(ad, 0, sizeof(AttributeDef));
7083 type_found = 0;
7084 typespec_found = 0;
7085 typedef_found = 0;
7086 t = 0;
7087 while(1) {
7088 switch(tok) {
7089 case TOK_EXTENSION:
7090 /* currently, we really ignore extension */
7091 next();
7092 continue;
7094 /* basic types */
7095 case TOK_CHAR:
7096 u = VT_BYTE;
7097 basic_type:
7098 next();
7099 basic_type1:
7100 if ((t & VT_BTYPE) != 0)
7101 error("too many basic types");
7102 t |= u;
7103 typespec_found = 1;
7104 break;
7105 case TOK_VOID:
7106 u = VT_VOID;
7107 goto basic_type;
7108 case TOK_SHORT:
7109 u = VT_SHORT;
7110 goto basic_type;
7111 case TOK_INT:
7112 next();
7113 typespec_found = 1;
7114 break;
7115 case TOK_LONG:
7116 next();
7117 if ((t & VT_BTYPE) == VT_DOUBLE) {
7118 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
7119 } else if ((t & VT_BTYPE) == VT_LONG) {
7120 t = (t & ~VT_BTYPE) | VT_LLONG;
7121 } else {
7122 u = VT_LONG;
7123 goto basic_type1;
7125 break;
7126 case TOK_BOOL:
7127 u = VT_BOOL;
7128 goto basic_type;
7129 case TOK_FLOAT:
7130 u = VT_FLOAT;
7131 goto basic_type;
7132 case TOK_DOUBLE:
7133 next();
7134 if ((t & VT_BTYPE) == VT_LONG) {
7135 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
7136 } else {
7137 u = VT_DOUBLE;
7138 goto basic_type1;
7140 break;
7141 case TOK_ENUM:
7142 struct_decl(&type1, VT_ENUM);
7143 basic_type2:
7144 u = type1.t;
7145 type->ref = type1.ref;
7146 goto basic_type1;
7147 case TOK_STRUCT:
7148 case TOK_UNION:
7149 struct_decl(&type1, VT_STRUCT);
7150 goto basic_type2;
7152 /* type modifiers */
7153 case TOK_CONST1:
7154 case TOK_CONST2:
7155 case TOK_CONST3:
7156 t |= VT_CONSTANT;
7157 next();
7158 break;
7159 case TOK_VOLATILE1:
7160 case TOK_VOLATILE2:
7161 case TOK_VOLATILE3:
7162 t |= VT_VOLATILE;
7163 next();
7164 break;
7165 case TOK_SIGNED1:
7166 case TOK_SIGNED2:
7167 case TOK_SIGNED3:
7168 typespec_found = 1;
7169 t |= VT_SIGNED;
7170 next();
7171 break;
7172 case TOK_REGISTER:
7173 case TOK_AUTO:
7174 case TOK_RESTRICT1:
7175 case TOK_RESTRICT2:
7176 case TOK_RESTRICT3:
7177 next();
7178 break;
7179 case TOK_UNSIGNED:
7180 t |= VT_UNSIGNED;
7181 next();
7182 typespec_found = 1;
7183 break;
7185 /* storage */
7186 case TOK_EXTERN:
7187 t |= VT_EXTERN;
7188 next();
7189 break;
7190 case TOK_STATIC:
7191 t |= VT_STATIC;
7192 next();
7193 break;
7194 case TOK_TYPEDEF:
7195 t |= VT_TYPEDEF;
7196 next();
7197 break;
7198 case TOK_INLINE1:
7199 case TOK_INLINE2:
7200 case TOK_INLINE3:
7201 t |= VT_INLINE;
7202 next();
7203 break;
7205 /* GNUC attribute */
7206 case TOK_ATTRIBUTE1:
7207 case TOK_ATTRIBUTE2:
7208 parse_attribute(ad);
7209 break;
7210 /* GNUC typeof */
7211 case TOK_TYPEOF1:
7212 case TOK_TYPEOF2:
7213 case TOK_TYPEOF3:
7214 next();
7215 parse_expr_type(&type1);
7216 goto basic_type2;
7217 default:
7218 if (typespec_found || typedef_found)
7219 goto the_end;
7220 s = sym_find(tok);
7221 if (!s || !(s->type.t & VT_TYPEDEF))
7222 goto the_end;
7223 typedef_found = 1;
7224 t |= (s->type.t & ~VT_TYPEDEF);
7225 type->ref = s->type.ref;
7226 next();
7227 typespec_found = 1;
7228 break;
7230 type_found = 1;
7232 the_end:
7233 if ((t & (VT_SIGNED|VT_UNSIGNED)) == (VT_SIGNED|VT_UNSIGNED))
7234 error("signed and unsigned modifier");
7235 if (tcc_state->char_is_unsigned) {
7236 if ((t & (VT_SIGNED|VT_UNSIGNED|VT_BTYPE)) == VT_BYTE)
7237 t |= VT_UNSIGNED;
7239 t &= ~VT_SIGNED;
7241 /* long is never used as type */
7242 if ((t & VT_BTYPE) == VT_LONG)
7243 #ifndef TCC_TARGET_X86_64
7244 t = (t & ~VT_BTYPE) | VT_INT;
7245 #else
7246 t = (t & ~VT_BTYPE) | VT_LLONG;
7247 #endif
7248 type->t = t;
7249 return type_found;
7252 /* convert a function parameter type (array to pointer and function to
7253 function pointer) */
7254 static inline void convert_parameter_type(CType *pt)
7256 /* remove const and volatile qualifiers (XXX: const could be used
7257 to indicate a const function parameter */
7258 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
7259 /* array must be transformed to pointer according to ANSI C */
7260 pt->t &= ~VT_ARRAY;
7261 if ((pt->t & VT_BTYPE) == VT_FUNC) {
7262 mk_pointer(pt);
7266 static void post_type(CType *type, AttributeDef *ad)
7268 int n, l, t1, arg_size, align;
7269 Sym **plast, *s, *first;
7270 AttributeDef ad1;
7271 CType pt;
7273 if (tok == '(') {
7274 /* function declaration */
7275 next();
7276 l = 0;
7277 first = NULL;
7278 plast = &first;
7279 arg_size = 0;
7280 if (tok != ')') {
7281 for(;;) {
7282 /* read param name and compute offset */
7283 if (l != FUNC_OLD) {
7284 if (!parse_btype(&pt, &ad1)) {
7285 if (l) {
7286 error("invalid type");
7287 } else {
7288 l = FUNC_OLD;
7289 goto old_proto;
7292 l = FUNC_NEW;
7293 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
7294 break;
7295 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
7296 if ((pt.t & VT_BTYPE) == VT_VOID)
7297 error("parameter declared as void");
7298 arg_size += (type_size(&pt, &align) + 3) & ~3;
7299 } else {
7300 old_proto:
7301 n = tok;
7302 if (n < TOK_UIDENT)
7303 expect("identifier");
7304 pt.t = VT_INT;
7305 next();
7307 convert_parameter_type(&pt);
7308 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
7309 *plast = s;
7310 plast = &s->next;
7311 if (tok == ')')
7312 break;
7313 skip(',');
7314 if (l == FUNC_NEW && tok == TOK_DOTS) {
7315 l = FUNC_ELLIPSIS;
7316 next();
7317 break;
7321 /* if no parameters, then old type prototype */
7322 if (l == 0)
7323 l = FUNC_OLD;
7324 skip(')');
7325 t1 = type->t & VT_STORAGE;
7326 /* NOTE: const is ignored in returned type as it has a special
7327 meaning in gcc / C++ */
7328 type->t &= ~(VT_STORAGE | VT_CONSTANT);
7329 post_type(type, ad);
7330 /* we push a anonymous symbol which will contain the function prototype */
7331 FUNC_ARGS(ad->func_attr) = arg_size;
7332 s = sym_push(SYM_FIELD, type, ad->func_attr, l);
7333 s->next = first;
7334 type->t = t1 | VT_FUNC;
7335 type->ref = s;
7336 } else if (tok == '[') {
7337 /* array definition */
7338 next();
7339 if (tok == TOK_RESTRICT1)
7340 next();
7341 n = -1;
7342 if (tok != ']') {
7343 n = expr_const();
7344 if (n < 0)
7345 error("invalid array size");
7347 skip(']');
7348 /* parse next post type */
7349 t1 = type->t & VT_STORAGE;
7350 type->t &= ~VT_STORAGE;
7351 post_type(type, ad);
7353 /* we push a anonymous symbol which will contain the array
7354 element type */
7355 s = sym_push(SYM_FIELD, type, 0, n);
7356 type->t = t1 | VT_ARRAY | VT_PTR;
7357 type->ref = s;
7361 /* Parse a type declaration (except basic type), and return the type
7362 in 'type'. 'td' is a bitmask indicating which kind of type decl is
7363 expected. 'type' should contain the basic type. 'ad' is the
7364 attribute definition of the basic type. It can be modified by
7365 type_decl().
7367 static void type_decl(CType *type, AttributeDef *ad, int *v, int td)
7369 Sym *s;
7370 CType type1, *type2;
7371 int qualifiers;
7373 while (tok == '*') {
7374 qualifiers = 0;
7375 redo:
7376 next();
7377 switch(tok) {
7378 case TOK_CONST1:
7379 case TOK_CONST2:
7380 case TOK_CONST3:
7381 qualifiers |= VT_CONSTANT;
7382 goto redo;
7383 case TOK_VOLATILE1:
7384 case TOK_VOLATILE2:
7385 case TOK_VOLATILE3:
7386 qualifiers |= VT_VOLATILE;
7387 goto redo;
7388 case TOK_RESTRICT1:
7389 case TOK_RESTRICT2:
7390 case TOK_RESTRICT3:
7391 goto redo;
7393 mk_pointer(type);
7394 type->t |= qualifiers;
7397 /* XXX: clarify attribute handling */
7398 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
7399 parse_attribute(ad);
7401 /* recursive type */
7402 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
7403 type1.t = 0; /* XXX: same as int */
7404 if (tok == '(') {
7405 next();
7406 /* XXX: this is not correct to modify 'ad' at this point, but
7407 the syntax is not clear */
7408 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
7409 parse_attribute(ad);
7410 type_decl(&type1, ad, v, td);
7411 skip(')');
7412 } else {
7413 /* type identifier */
7414 if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
7415 *v = tok;
7416 next();
7417 } else {
7418 if (!(td & TYPE_ABSTRACT))
7419 expect("identifier");
7420 *v = 0;
7423 post_type(type, ad);
7424 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
7425 parse_attribute(ad);
7426 if (!type1.t)
7427 return;
7428 /* append type at the end of type1 */
7429 type2 = &type1;
7430 for(;;) {
7431 s = type2->ref;
7432 type2 = &s->type;
7433 if (!type2->t) {
7434 *type2 = *type;
7435 break;
7438 *type = type1;
7441 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
7442 static int lvalue_type(int t)
7444 int bt, r;
7445 r = VT_LVAL;
7446 bt = t & VT_BTYPE;
7447 if (bt == VT_BYTE || bt == VT_BOOL)
7448 r |= VT_LVAL_BYTE;
7449 else if (bt == VT_SHORT)
7450 r |= VT_LVAL_SHORT;
7451 else
7452 return r;
7453 if (t & VT_UNSIGNED)
7454 r |= VT_LVAL_UNSIGNED;
7455 return r;
7458 /* indirection with full error checking and bound check */
7459 static void indir(void)
7461 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
7462 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
7463 return;
7464 expect("pointer");
7466 if ((vtop->r & VT_LVAL) && !nocode_wanted)
7467 gv(RC_INT);
7468 vtop->type = *pointed_type(&vtop->type);
7469 /* Arrays and functions are never lvalues */
7470 if (!(vtop->type.t & VT_ARRAY)
7471 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
7472 vtop->r |= lvalue_type(vtop->type.t);
7473 /* if bound checking, the referenced pointer must be checked */
7474 if (do_bounds_check)
7475 vtop->r |= VT_MUSTBOUND;
7479 /* pass a parameter to a function and do type checking and casting */
7480 static void gfunc_param_typed(Sym *func, Sym *arg)
7482 int func_type;
7483 CType type;
7485 func_type = func->c;
7486 if (func_type == FUNC_OLD ||
7487 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
7488 /* default casting : only need to convert float to double */
7489 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
7490 type.t = VT_DOUBLE;
7491 gen_cast(&type);
7493 } else if (arg == NULL) {
7494 error("too many arguments to function");
7495 } else {
7496 type = arg->type;
7497 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
7498 gen_assign_cast(&type);
7502 /* parse an expression of the form '(type)' or '(expr)' and return its
7503 type */
7504 static void parse_expr_type(CType *type)
7506 int n;
7507 AttributeDef ad;
7509 skip('(');
7510 if (parse_btype(type, &ad)) {
7511 type_decl(type, &ad, &n, TYPE_ABSTRACT);
7512 } else {
7513 expr_type(type);
7515 skip(')');
7518 static void parse_type(CType *type)
7520 AttributeDef ad;
7521 int n;
7523 if (!parse_btype(type, &ad)) {
7524 expect("type");
7526 type_decl(type, &ad, &n, TYPE_ABSTRACT);
7529 static void vpush_tokc(int t)
7531 CType type;
7532 type.t = t;
7533 vsetc(&type, VT_CONST, &tokc);
7536 static void unary(void)
7538 int n, t, align, size, r;
7539 CType type;
7540 Sym *s;
7541 AttributeDef ad;
7543 /* XXX: GCC 2.95.3 does not generate a table although it should be
7544 better here */
7545 tok_next:
7546 switch(tok) {
7547 case TOK_EXTENSION:
7548 next();
7549 goto tok_next;
7550 case TOK_CINT:
7551 case TOK_CCHAR:
7552 case TOK_LCHAR:
7553 vpushi(tokc.i);
7554 next();
7555 break;
7556 case TOK_CUINT:
7557 vpush_tokc(VT_INT | VT_UNSIGNED);
7558 next();
7559 break;
7560 case TOK_CLLONG:
7561 vpush_tokc(VT_LLONG);
7562 next();
7563 break;
7564 case TOK_CULLONG:
7565 vpush_tokc(VT_LLONG | VT_UNSIGNED);
7566 next();
7567 break;
7568 case TOK_CFLOAT:
7569 vpush_tokc(VT_FLOAT);
7570 next();
7571 break;
7572 case TOK_CDOUBLE:
7573 vpush_tokc(VT_DOUBLE);
7574 next();
7575 break;
7576 case TOK_CLDOUBLE:
7577 vpush_tokc(VT_LDOUBLE);
7578 next();
7579 break;
7580 case TOK___FUNCTION__:
7581 if (!gnu_ext)
7582 goto tok_identifier;
7583 /* fall thru */
7584 case TOK___FUNC__:
7586 void *ptr;
7587 int len;
7588 /* special function name identifier */
7589 len = strlen(funcname) + 1;
7590 /* generate char[len] type */
7591 type.t = VT_BYTE;
7592 mk_pointer(&type);
7593 type.t |= VT_ARRAY;
7594 type.ref->c = len;
7595 vpush_ref(&type, data_section, data_section->data_offset, len);
7596 ptr = section_ptr_add(data_section, len);
7597 memcpy(ptr, funcname, len);
7598 next();
7600 break;
7601 case TOK_LSTR:
7602 #ifdef TCC_TARGET_PE
7603 t = VT_SHORT | VT_UNSIGNED;
7604 #else
7605 t = VT_INT;
7606 #endif
7607 goto str_init;
7608 case TOK_STR:
7609 /* string parsing */
7610 t = VT_BYTE;
7611 str_init:
7612 if (tcc_state->warn_write_strings)
7613 t |= VT_CONSTANT;
7614 type.t = t;
7615 mk_pointer(&type);
7616 type.t |= VT_ARRAY;
7617 memset(&ad, 0, sizeof(AttributeDef));
7618 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, 0);
7619 break;
7620 case '(':
7621 next();
7622 /* cast ? */
7623 if (parse_btype(&type, &ad)) {
7624 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
7625 skip(')');
7626 /* check ISOC99 compound literal */
7627 if (tok == '{') {
7628 /* data is allocated locally by default */
7629 if (global_expr)
7630 r = VT_CONST;
7631 else
7632 r = VT_LOCAL;
7633 /* all except arrays are lvalues */
7634 if (!(type.t & VT_ARRAY))
7635 r |= lvalue_type(type.t);
7636 memset(&ad, 0, sizeof(AttributeDef));
7637 decl_initializer_alloc(&type, &ad, r, 1, 0, 0);
7638 } else {
7639 unary();
7640 gen_cast(&type);
7642 } else if (tok == '{') {
7643 /* save all registers */
7644 save_regs(0);
7645 /* statement expression : we do not accept break/continue
7646 inside as GCC does */
7647 block(NULL, NULL, NULL, NULL, 0, 1);
7648 skip(')');
7649 } else {
7650 gexpr();
7651 skip(')');
7653 break;
7654 case '*':
7655 next();
7656 unary();
7657 indir();
7658 break;
7659 case '&':
7660 next();
7661 unary();
7662 /* functions names must be treated as function pointers,
7663 except for unary '&' and sizeof. Since we consider that
7664 functions are not lvalues, we only have to handle it
7665 there and in function calls. */
7666 /* arrays can also be used although they are not lvalues */
7667 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
7668 !(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
7669 test_lvalue();
7670 mk_pointer(&vtop->type);
7671 gaddrof();
7672 break;
7673 case '!':
7674 next();
7675 unary();
7676 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
7677 CType boolean;
7678 boolean.t = VT_BOOL;
7679 gen_cast(&boolean);
7680 vtop->c.i = !vtop->c.i;
7681 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
7682 vtop->c.i = vtop->c.i ^ 1;
7683 else {
7684 save_regs(1);
7685 vseti(VT_JMP, gtst(1, 0));
7687 break;
7688 case '~':
7689 next();
7690 unary();
7691 vpushi(-1);
7692 gen_op('^');
7693 break;
7694 case '+':
7695 next();
7696 /* in order to force cast, we add zero */
7697 unary();
7698 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
7699 error("pointer not accepted for unary plus");
7700 vpushi(0);
7701 gen_op('+');
7702 break;
7703 case TOK_SIZEOF:
7704 case TOK_ALIGNOF1:
7705 case TOK_ALIGNOF2:
7706 t = tok;
7707 next();
7708 if (tok == '(') {
7709 parse_expr_type(&type);
7710 } else {
7711 unary_type(&type);
7713 size = type_size(&type, &align);
7714 if (t == TOK_SIZEOF) {
7715 if (size < 0)
7716 error("sizeof applied to an incomplete type");
7717 vpushi(size);
7718 } else {
7719 vpushi(align);
7721 vtop->type.t |= VT_UNSIGNED;
7722 break;
7724 case TOK_builtin_types_compatible_p:
7726 CType type1, type2;
7727 next();
7728 skip('(');
7729 parse_type(&type1);
7730 skip(',');
7731 parse_type(&type2);
7732 skip(')');
7733 type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
7734 type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
7735 vpushi(is_compatible_types(&type1, &type2));
7737 break;
7738 case TOK_builtin_constant_p:
7740 int saved_nocode_wanted, res;
7741 next();
7742 skip('(');
7743 saved_nocode_wanted = nocode_wanted;
7744 nocode_wanted = 1;
7745 gexpr();
7746 res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
7747 vpop();
7748 nocode_wanted = saved_nocode_wanted;
7749 skip(')');
7750 vpushi(res);
7752 break;
7753 case TOK_builtin_frame_address:
7755 CType type;
7756 next();
7757 skip('(');
7758 if (tok != TOK_CINT) {
7759 error("__builtin_frame_address only takes integers");
7761 if (tokc.i != 0) {
7762 error("TCC only supports __builtin_frame_address(0)");
7764 next();
7765 skip(')');
7766 type.t = VT_VOID;
7767 mk_pointer(&type);
7768 vset(&type, VT_LOCAL, 0);
7770 break;
7771 #ifdef TCC_TARGET_X86_64
7772 case TOK_builtin_malloc:
7774 char *p = file->buf_ptr;
7775 file->buf_ptr = "malloc";
7776 next_nomacro1();
7777 file->buf_ptr = p;
7778 goto tok_identifier;
7780 case TOK_builtin_free:
7782 char *p = file->buf_ptr;
7783 file->buf_ptr = "free";
7784 next_nomacro1();
7785 file->buf_ptr = p;
7786 goto tok_identifier;
7788 #endif
7789 case TOK_INC:
7790 case TOK_DEC:
7791 t = tok;
7792 next();
7793 unary();
7794 inc(0, t);
7795 break;
7796 case '-':
7797 next();
7798 vpushi(0);
7799 unary();
7800 gen_op('-');
7801 break;
7802 case TOK_LAND:
7803 if (!gnu_ext)
7804 goto tok_identifier;
7805 next();
7806 /* allow to take the address of a label */
7807 if (tok < TOK_UIDENT)
7808 expect("label identifier");
7809 s = label_find(tok);
7810 if (!s) {
7811 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
7812 } else {
7813 if (s->r == LABEL_DECLARED)
7814 s->r = LABEL_FORWARD;
7816 if (!s->type.t) {
7817 s->type.t = VT_VOID;
7818 mk_pointer(&s->type);
7819 s->type.t |= VT_STATIC;
7821 vset(&s->type, VT_CONST | VT_SYM, 0);
7822 vtop->sym = s;
7823 next();
7824 break;
7825 default:
7826 tok_identifier:
7827 t = tok;
7828 next();
7829 if (t < TOK_UIDENT)
7830 expect("identifier");
7831 s = sym_find(t);
7832 if (!s) {
7833 if (tok != '(')
7834 error("'%s' undeclared", get_tok_str(t, NULL));
7835 /* for simple function calls, we tolerate undeclared
7836 external reference to int() function */
7837 if (tcc_state->warn_implicit_function_declaration)
7838 warning("implicit declaration of function '%s'",
7839 get_tok_str(t, NULL));
7840 s = external_global_sym(t, &func_old_type, 0);
7842 if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
7843 (VT_STATIC | VT_INLINE | VT_FUNC)) {
7844 /* if referencing an inline function, then we generate a
7845 symbol to it if not already done. It will have the
7846 effect to generate code for it at the end of the
7847 compilation unit. Inline function as always
7848 generated in the text section. */
7849 if (!s->c)
7850 put_extern_sym(s, text_section, 0, 0);
7851 r = VT_SYM | VT_CONST;
7852 } else {
7853 r = s->r;
7855 vset(&s->type, r, s->c);
7856 /* if forward reference, we must point to s */
7857 if (vtop->r & VT_SYM) {
7858 vtop->sym = s;
7859 vtop->c.ul = 0;
7861 break;
7864 /* post operations */
7865 while (1) {
7866 if (tok == TOK_INC || tok == TOK_DEC) {
7867 inc(1, tok);
7868 next();
7869 } else if (tok == '.' || tok == TOK_ARROW) {
7870 /* field */
7871 if (tok == TOK_ARROW)
7872 indir();
7873 test_lvalue();
7874 gaddrof();
7875 next();
7876 /* expect pointer on structure */
7877 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
7878 expect("struct or union");
7879 s = vtop->type.ref;
7880 /* find field */
7881 tok |= SYM_FIELD;
7882 while ((s = s->next) != NULL) {
7883 if (s->v == tok)
7884 break;
7886 if (!s)
7887 error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, NULL));
7888 /* add field offset to pointer */
7889 vtop->type = char_pointer_type; /* change type to 'char *' */
7890 vpushi(s->c);
7891 gen_op('+');
7892 /* change type to field type, and set to lvalue */
7893 vtop->type = s->type;
7894 /* an array is never an lvalue */
7895 if (!(vtop->type.t & VT_ARRAY)) {
7896 vtop->r |= lvalue_type(vtop->type.t);
7897 /* if bound checking, the referenced pointer must be checked */
7898 if (do_bounds_check)
7899 vtop->r |= VT_MUSTBOUND;
7901 next();
7902 } else if (tok == '[') {
7903 next();
7904 gexpr();
7905 gen_op('+');
7906 indir();
7907 skip(']');
7908 } else if (tok == '(') {
7909 SValue ret;
7910 Sym *sa;
7911 int nb_args;
7913 /* function call */
7914 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
7915 /* pointer test (no array accepted) */
7916 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
7917 vtop->type = *pointed_type(&vtop->type);
7918 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
7919 goto error_func;
7920 } else {
7921 error_func:
7922 expect("function pointer");
7924 } else {
7925 vtop->r &= ~VT_LVAL; /* no lvalue */
7927 /* get return type */
7928 s = vtop->type.ref;
7929 next();
7930 sa = s->next; /* first parameter */
7931 nb_args = 0;
7932 ret.r2 = VT_CONST;
7933 /* compute first implicit argument if a structure is returned */
7934 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
7935 /* get some space for the returned structure */
7936 size = type_size(&s->type, &align);
7937 loc = (loc - size) & -align;
7938 ret.type = s->type;
7939 ret.r = VT_LOCAL | VT_LVAL;
7940 /* pass it as 'int' to avoid structure arg passing
7941 problems */
7942 vseti(VT_LOCAL, loc);
7943 ret.c = vtop->c;
7944 nb_args++;
7945 } else {
7946 ret.type = s->type;
7947 /* return in register */
7948 if (is_float(ret.type.t)) {
7949 ret.r = REG_FRET;
7950 } else {
7951 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
7952 ret.r2 = REG_LRET;
7953 ret.r = REG_IRET;
7955 ret.c.i = 0;
7957 if (tok != ')') {
7958 for(;;) {
7959 expr_eq();
7960 gfunc_param_typed(s, sa);
7961 nb_args++;
7962 if (sa)
7963 sa = sa->next;
7964 if (tok == ')')
7965 break;
7966 skip(',');
7969 if (sa)
7970 error("too few arguments to function");
7971 skip(')');
7972 if (!nocode_wanted) {
7973 gfunc_call(nb_args);
7974 } else {
7975 vtop -= (nb_args + 1);
7977 /* return value */
7978 vsetc(&ret.type, ret.r, &ret.c);
7979 vtop->r2 = ret.r2;
7980 } else {
7981 break;
7986 static void uneq(void)
7988 int t;
7990 unary();
7991 if (tok == '=' ||
7992 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
7993 tok == TOK_A_XOR || tok == TOK_A_OR ||
7994 tok == TOK_A_SHL || tok == TOK_A_SAR) {
7995 test_lvalue();
7996 t = tok;
7997 next();
7998 if (t == '=') {
7999 expr_eq();
8000 } else {
8001 vdup();
8002 expr_eq();
8003 gen_op(t & 0x7f);
8005 vstore();
8009 static void expr_prod(void)
8011 int t;
8013 uneq();
8014 while (tok == '*' || tok == '/' || tok == '%') {
8015 t = tok;
8016 next();
8017 uneq();
8018 gen_op(t);
8022 static void expr_sum(void)
8024 int t;
8026 expr_prod();
8027 while (tok == '+' || tok == '-') {
8028 t = tok;
8029 next();
8030 expr_prod();
8031 gen_op(t);
8035 static void expr_shift(void)
8037 int t;
8039 expr_sum();
8040 while (tok == TOK_SHL || tok == TOK_SAR) {
8041 t = tok;
8042 next();
8043 expr_sum();
8044 gen_op(t);
8048 static void expr_cmp(void)
8050 int t;
8052 expr_shift();
8053 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
8054 tok == TOK_ULT || tok == TOK_UGE) {
8055 t = tok;
8056 next();
8057 expr_shift();
8058 gen_op(t);
8062 static void expr_cmpeq(void)
8064 int t;
8066 expr_cmp();
8067 while (tok == TOK_EQ || tok == TOK_NE) {
8068 t = tok;
8069 next();
8070 expr_cmp();
8071 gen_op(t);
8075 static void expr_and(void)
8077 expr_cmpeq();
8078 while (tok == '&') {
8079 next();
8080 expr_cmpeq();
8081 gen_op('&');
8085 static void expr_xor(void)
8087 expr_and();
8088 while (tok == '^') {
8089 next();
8090 expr_and();
8091 gen_op('^');
8095 static void expr_or(void)
8097 expr_xor();
8098 while (tok == '|') {
8099 next();
8100 expr_xor();
8101 gen_op('|');
8105 /* XXX: fix this mess */
8106 static void expr_land_const(void)
8108 expr_or();
8109 while (tok == TOK_LAND) {
8110 next();
8111 expr_or();
8112 gen_op(TOK_LAND);
8116 /* XXX: fix this mess */
8117 static void expr_lor_const(void)
8119 expr_land_const();
8120 while (tok == TOK_LOR) {
8121 next();
8122 expr_land_const();
8123 gen_op(TOK_LOR);
8127 /* only used if non constant */
8128 static void expr_land(void)
8130 int t;
8132 expr_or();
8133 if (tok == TOK_LAND) {
8134 t = 0;
8135 save_regs(1);
8136 for(;;) {
8137 t = gtst(1, t);
8138 if (tok != TOK_LAND) {
8139 vseti(VT_JMPI, t);
8140 break;
8142 next();
8143 expr_or();
8148 static void expr_lor(void)
8150 int t;
8152 expr_land();
8153 if (tok == TOK_LOR) {
8154 t = 0;
8155 save_regs(1);
8156 for(;;) {
8157 t = gtst(0, t);
8158 if (tok != TOK_LOR) {
8159 vseti(VT_JMP, t);
8160 break;
8162 next();
8163 expr_land();
8168 /* XXX: better constant handling */
8169 static void expr_eq(void)
8171 int tt, u, r1, r2, rc, t1, t2, bt1, bt2;
8172 SValue sv;
8173 CType type, type1, type2;
8175 if (const_wanted) {
8176 expr_lor_const();
8177 if (tok == '?') {
8178 CType boolean;
8179 int c;
8180 boolean.t = VT_BOOL;
8181 vdup();
8182 gen_cast(&boolean);
8183 c = vtop->c.i;
8184 vpop();
8185 next();
8186 if (tok != ':' || !gnu_ext) {
8187 vpop();
8188 gexpr();
8190 if (!c)
8191 vpop();
8192 skip(':');
8193 expr_eq();
8194 if (c)
8195 vpop();
8197 } else {
8198 expr_lor();
8199 if (tok == '?') {
8200 next();
8201 if (vtop != vstack) {
8202 /* needed to avoid having different registers saved in
8203 each branch */
8204 if (is_float(vtop->type.t)) {
8205 rc = RC_FLOAT;
8206 #ifdef TCC_TARGET_X86_64
8207 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
8208 rc = RC_ST0;
8210 #endif
8212 else
8213 rc = RC_INT;
8214 gv(rc);
8215 save_regs(1);
8217 if (tok == ':' && gnu_ext) {
8218 gv_dup();
8219 tt = gtst(1, 0);
8220 } else {
8221 tt = gtst(1, 0);
8222 gexpr();
8224 type1 = vtop->type;
8225 sv = *vtop; /* save value to handle it later */
8226 vtop--; /* no vpop so that FP stack is not flushed */
8227 skip(':');
8228 u = gjmp(0);
8229 gsym(tt);
8230 expr_eq();
8231 type2 = vtop->type;
8233 t1 = type1.t;
8234 bt1 = t1 & VT_BTYPE;
8235 t2 = type2.t;
8236 bt2 = t2 & VT_BTYPE;
8237 /* cast operands to correct type according to ISOC rules */
8238 if (is_float(bt1) || is_float(bt2)) {
8239 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
8240 type.t = VT_LDOUBLE;
8241 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
8242 type.t = VT_DOUBLE;
8243 } else {
8244 type.t = VT_FLOAT;
8246 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
8247 /* cast to biggest op */
8248 type.t = VT_LLONG;
8249 /* convert to unsigned if it does not fit in a long long */
8250 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
8251 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
8252 type.t |= VT_UNSIGNED;
8253 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
8254 /* XXX: test pointer compatibility */
8255 type = type1;
8256 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
8257 /* XXX: test function pointer compatibility */
8258 type = type1;
8259 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
8260 /* XXX: test structure compatibility */
8261 type = type1;
8262 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
8263 /* NOTE: as an extension, we accept void on only one side */
8264 type.t = VT_VOID;
8265 } else {
8266 /* integer operations */
8267 type.t = VT_INT;
8268 /* convert to unsigned if it does not fit in an integer */
8269 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
8270 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
8271 type.t |= VT_UNSIGNED;
8274 /* now we convert second operand */
8275 gen_cast(&type);
8276 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
8277 gaddrof();
8278 rc = RC_INT;
8279 if (is_float(type.t)) {
8280 rc = RC_FLOAT;
8281 #ifdef TCC_TARGET_X86_64
8282 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
8283 rc = RC_ST0;
8285 #endif
8286 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
8287 /* for long longs, we use fixed registers to avoid having
8288 to handle a complicated move */
8289 rc = RC_IRET;
8292 r2 = gv(rc);
8293 /* this is horrible, but we must also convert first
8294 operand */
8295 tt = gjmp(0);
8296 gsym(u);
8297 /* put again first value and cast it */
8298 *vtop = sv;
8299 gen_cast(&type);
8300 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
8301 gaddrof();
8302 r1 = gv(rc);
8303 move_reg(r2, r1);
8304 vtop->r = r2;
8305 gsym(tt);
8310 static void gexpr(void)
8312 while (1) {
8313 expr_eq();
8314 if (tok != ',')
8315 break;
8316 vpop();
8317 next();
8321 /* parse an expression and return its type without any side effect. */
8322 static void expr_type(CType *type)
8324 int saved_nocode_wanted;
8326 saved_nocode_wanted = nocode_wanted;
8327 nocode_wanted = 1;
8328 gexpr();
8329 *type = vtop->type;
8330 vpop();
8331 nocode_wanted = saved_nocode_wanted;
8334 /* parse a unary expression and return its type without any side
8335 effect. */
8336 static void unary_type(CType *type)
8338 int a;
8340 a = nocode_wanted;
8341 nocode_wanted = 1;
8342 unary();
8343 *type = vtop->type;
8344 vpop();
8345 nocode_wanted = a;
8348 /* parse a constant expression and return value in vtop. */
8349 static void expr_const1(void)
8351 int a;
8352 a = const_wanted;
8353 const_wanted = 1;
8354 expr_eq();
8355 const_wanted = a;
8358 /* parse an integer constant and return its value. */
8359 static int expr_const(void)
8361 int c;
8362 expr_const1();
8363 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
8364 expect("constant expression");
8365 c = vtop->c.i;
8366 vpop();
8367 return c;
8370 /* return the label token if current token is a label, otherwise
8371 return zero */
8372 static int is_label(void)
8374 int last_tok;
8376 /* fast test first */
8377 if (tok < TOK_UIDENT)
8378 return 0;
8379 /* no need to save tokc because tok is an identifier */
8380 last_tok = tok;
8381 next();
8382 if (tok == ':') {
8383 next();
8384 return last_tok;
8385 } else {
8386 unget_tok(last_tok);
8387 return 0;
8391 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
8392 int case_reg, int is_expr)
8394 int a, b, c, d;
8395 Sym *s;
8397 /* generate line number info */
8398 if (do_debug &&
8399 (last_line_num != file->line_num || last_ind != ind)) {
8400 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
8401 last_ind = ind;
8402 last_line_num = file->line_num;
8405 if (is_expr) {
8406 /* default return value is (void) */
8407 vpushi(0);
8408 vtop->type.t = VT_VOID;
8411 if (tok == TOK_IF) {
8412 /* if test */
8413 next();
8414 skip('(');
8415 gexpr();
8416 skip(')');
8417 a = gtst(1, 0);
8418 block(bsym, csym, case_sym, def_sym, case_reg, 0);
8419 c = tok;
8420 if (c == TOK_ELSE) {
8421 next();
8422 d = gjmp(0);
8423 gsym(a);
8424 block(bsym, csym, case_sym, def_sym, case_reg, 0);
8425 gsym(d); /* patch else jmp */
8426 } else
8427 gsym(a);
8428 } else if (tok == TOK_WHILE) {
8429 next();
8430 d = ind;
8431 skip('(');
8432 gexpr();
8433 skip(')');
8434 a = gtst(1, 0);
8435 b = 0;
8436 block(&a, &b, case_sym, def_sym, case_reg, 0);
8437 gjmp_addr(d);
8438 gsym(a);
8439 gsym_addr(b, d);
8440 } else if (tok == '{') {
8441 Sym *llabel;
8443 next();
8444 /* record local declaration stack position */
8445 s = local_stack;
8446 llabel = local_label_stack;
8447 /* handle local labels declarations */
8448 if (tok == TOK_LABEL) {
8449 next();
8450 for(;;) {
8451 if (tok < TOK_UIDENT)
8452 expect("label identifier");
8453 label_push(&local_label_stack, tok, LABEL_DECLARED);
8454 next();
8455 if (tok == ',') {
8456 next();
8457 } else {
8458 skip(';');
8459 break;
8463 while (tok != '}') {
8464 decl(VT_LOCAL);
8465 if (tok != '}') {
8466 if (is_expr)
8467 vpop();
8468 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
8471 /* pop locally defined labels */
8472 label_pop(&local_label_stack, llabel);
8473 /* pop locally defined symbols */
8474 if(is_expr) {
8475 /* XXX: this solution makes only valgrind happy...
8476 triggered by gcc.c-torture/execute/20000917-1.c */
8477 Sym *p;
8478 switch(vtop->type.t & VT_BTYPE) {
8479 case VT_PTR:
8480 case VT_STRUCT:
8481 case VT_ENUM:
8482 case VT_FUNC:
8483 for(p=vtop->type.ref;p;p=p->prev)
8484 if(p->prev==s)
8485 error("unsupported expression type");
8488 sym_pop(&local_stack, s);
8489 next();
8490 } else if (tok == TOK_RETURN) {
8491 next();
8492 if (tok != ';') {
8493 gexpr();
8494 gen_assign_cast(&func_vt);
8495 if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
8496 CType type;
8497 /* if returning structure, must copy it to implicit
8498 first pointer arg location */
8499 #ifdef TCC_ARM_EABI
8500 int align, size;
8501 size = type_size(&func_vt,&align);
8502 if(size <= 4)
8504 if((vtop->r != (VT_LOCAL | VT_LVAL) || (vtop->c.i & 3))
8505 && (align & 3))
8507 int addr;
8508 loc = (loc - size) & -4;
8509 addr = loc;
8510 type = func_vt;
8511 vset(&type, VT_LOCAL | VT_LVAL, addr);
8512 vswap();
8513 vstore();
8514 vset(&int_type, VT_LOCAL | VT_LVAL, addr);
8516 vtop->type = int_type;
8517 gv(RC_IRET);
8518 } else {
8519 #endif
8520 type = func_vt;
8521 mk_pointer(&type);
8522 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
8523 indir();
8524 vswap();
8525 /* copy structure value to pointer */
8526 vstore();
8527 #ifdef TCC_ARM_EABI
8529 #endif
8530 } else if (is_float(func_vt.t)) {
8531 gv(RC_FRET);
8532 } else {
8533 gv(RC_IRET);
8535 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
8537 skip(';');
8538 rsym = gjmp(rsym); /* jmp */
8539 } else if (tok == TOK_BREAK) {
8540 /* compute jump */
8541 if (!bsym)
8542 error("cannot break");
8543 *bsym = gjmp(*bsym);
8544 next();
8545 skip(';');
8546 } else if (tok == TOK_CONTINUE) {
8547 /* compute jump */
8548 if (!csym)
8549 error("cannot continue");
8550 *csym = gjmp(*csym);
8551 next();
8552 skip(';');
8553 } else if (tok == TOK_FOR) {
8554 int e;
8555 next();
8556 skip('(');
8557 if (tok != ';') {
8558 gexpr();
8559 vpop();
8561 skip(';');
8562 d = ind;
8563 c = ind;
8564 a = 0;
8565 b = 0;
8566 if (tok != ';') {
8567 gexpr();
8568 a = gtst(1, 0);
8570 skip(';');
8571 if (tok != ')') {
8572 e = gjmp(0);
8573 c = ind;
8574 gexpr();
8575 vpop();
8576 gjmp_addr(d);
8577 gsym(e);
8579 skip(')');
8580 block(&a, &b, case_sym, def_sym, case_reg, 0);
8581 gjmp_addr(c);
8582 gsym(a);
8583 gsym_addr(b, c);
8584 } else
8585 if (tok == TOK_DO) {
8586 next();
8587 a = 0;
8588 b = 0;
8589 d = ind;
8590 block(&a, &b, case_sym, def_sym, case_reg, 0);
8591 skip(TOK_WHILE);
8592 skip('(');
8593 gsym(b);
8594 gexpr();
8595 c = gtst(0, 0);
8596 gsym_addr(c, d);
8597 skip(')');
8598 gsym(a);
8599 skip(';');
8600 } else
8601 if (tok == TOK_SWITCH) {
8602 next();
8603 skip('(');
8604 gexpr();
8605 /* XXX: other types than integer */
8606 case_reg = gv(RC_INT);
8607 vpop();
8608 skip(')');
8609 a = 0;
8610 b = gjmp(0); /* jump to first case */
8611 c = 0;
8612 block(&a, csym, &b, &c, case_reg, 0);
8613 /* if no default, jmp after switch */
8614 if (c == 0)
8615 c = ind;
8616 /* default label */
8617 gsym_addr(b, c);
8618 /* break label */
8619 gsym(a);
8620 } else
8621 if (tok == TOK_CASE) {
8622 int v1, v2;
8623 if (!case_sym)
8624 expect("switch");
8625 next();
8626 v1 = expr_const();
8627 v2 = v1;
8628 if (gnu_ext && tok == TOK_DOTS) {
8629 next();
8630 v2 = expr_const();
8631 if (v2 < v1)
8632 warning("empty case range");
8634 /* since a case is like a label, we must skip it with a jmp */
8635 b = gjmp(0);
8636 gsym(*case_sym);
8637 vseti(case_reg, 0);
8638 vpushi(v1);
8639 if (v1 == v2) {
8640 gen_op(TOK_EQ);
8641 *case_sym = gtst(1, 0);
8642 } else {
8643 gen_op(TOK_GE);
8644 *case_sym = gtst(1, 0);
8645 vseti(case_reg, 0);
8646 vpushi(v2);
8647 gen_op(TOK_LE);
8648 *case_sym = gtst(1, *case_sym);
8650 gsym(b);
8651 skip(':');
8652 is_expr = 0;
8653 goto block_after_label;
8654 } else
8655 if (tok == TOK_DEFAULT) {
8656 next();
8657 skip(':');
8658 if (!def_sym)
8659 expect("switch");
8660 if (*def_sym)
8661 error("too many 'default'");
8662 *def_sym = ind;
8663 is_expr = 0;
8664 goto block_after_label;
8665 } else
8666 if (tok == TOK_GOTO) {
8667 next();
8668 if (tok == '*' && gnu_ext) {
8669 /* computed goto */
8670 next();
8671 gexpr();
8672 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
8673 expect("pointer");
8674 ggoto();
8675 } else if (tok >= TOK_UIDENT) {
8676 s = label_find(tok);
8677 /* put forward definition if needed */
8678 if (!s) {
8679 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
8680 } else {
8681 if (s->r == LABEL_DECLARED)
8682 s->r = LABEL_FORWARD;
8684 /* label already defined */
8685 if (s->r & LABEL_FORWARD)
8686 s->next = (void *)gjmp((long)s->next);
8687 else
8688 gjmp_addr((long)s->next);
8689 next();
8690 } else {
8691 expect("label identifier");
8693 skip(';');
8694 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
8695 asm_instr();
8696 } else {
8697 b = is_label();
8698 if (b) {
8699 /* label case */
8700 s = label_find(b);
8701 if (s) {
8702 if (s->r == LABEL_DEFINED)
8703 error("duplicate label '%s'", get_tok_str(s->v, NULL));
8704 gsym((long)s->next);
8705 s->r = LABEL_DEFINED;
8706 } else {
8707 s = label_push(&global_label_stack, b, LABEL_DEFINED);
8709 s->next = (void *)ind;
8710 /* we accept this, but it is a mistake */
8711 block_after_label:
8712 if (tok == '}') {
8713 warning("deprecated use of label at end of compound statement");
8714 } else {
8715 if (is_expr)
8716 vpop();
8717 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
8719 } else {
8720 /* expression case */
8721 if (tok != ';') {
8722 if (is_expr) {
8723 vpop();
8724 gexpr();
8725 } else {
8726 gexpr();
8727 vpop();
8730 skip(';');
8735 /* t is the array or struct type. c is the array or struct
8736 address. cur_index/cur_field is the pointer to the current
8737 value. 'size_only' is true if only size info is needed (only used
8738 in arrays) */
8739 static void decl_designator(CType *type, Section *sec, unsigned long c,
8740 int *cur_index, Sym **cur_field,
8741 int size_only)
8743 Sym *s, *f;
8744 int notfirst, index, index_last, align, l, nb_elems, elem_size;
8745 CType type1;
8747 notfirst = 0;
8748 elem_size = 0;
8749 nb_elems = 1;
8750 if (gnu_ext && (l = is_label()) != 0)
8751 goto struct_field;
8752 while (tok == '[' || tok == '.') {
8753 if (tok == '[') {
8754 if (!(type->t & VT_ARRAY))
8755 expect("array type");
8756 s = type->ref;
8757 next();
8758 index = expr_const();
8759 if (index < 0 || (s->c >= 0 && index >= s->c))
8760 expect("invalid index");
8761 if (tok == TOK_DOTS && gnu_ext) {
8762 next();
8763 index_last = expr_const();
8764 if (index_last < 0 ||
8765 (s->c >= 0 && index_last >= s->c) ||
8766 index_last < index)
8767 expect("invalid index");
8768 } else {
8769 index_last = index;
8771 skip(']');
8772 if (!notfirst)
8773 *cur_index = index_last;
8774 type = pointed_type(type);
8775 elem_size = type_size(type, &align);
8776 c += index * elem_size;
8777 /* NOTE: we only support ranges for last designator */
8778 nb_elems = index_last - index + 1;
8779 if (nb_elems != 1) {
8780 notfirst = 1;
8781 break;
8783 } else {
8784 next();
8785 l = tok;
8786 next();
8787 struct_field:
8788 if ((type->t & VT_BTYPE) != VT_STRUCT)
8789 expect("struct/union type");
8790 s = type->ref;
8791 l |= SYM_FIELD;
8792 f = s->next;
8793 while (f) {
8794 if (f->v == l)
8795 break;
8796 f = f->next;
8798 if (!f)
8799 expect("field");
8800 if (!notfirst)
8801 *cur_field = f;
8802 /* XXX: fix this mess by using explicit storage field */
8803 type1 = f->type;
8804 type1.t |= (type->t & ~VT_TYPE);
8805 type = &type1;
8806 c += f->c;
8808 notfirst = 1;
8810 if (notfirst) {
8811 if (tok == '=') {
8812 next();
8813 } else {
8814 if (!gnu_ext)
8815 expect("=");
8817 } else {
8818 if (type->t & VT_ARRAY) {
8819 index = *cur_index;
8820 type = pointed_type(type);
8821 c += index * type_size(type, &align);
8822 } else {
8823 f = *cur_field;
8824 if (!f)
8825 error("too many field init");
8826 /* XXX: fix this mess by using explicit storage field */
8827 type1 = f->type;
8828 type1.t |= (type->t & ~VT_TYPE);
8829 type = &type1;
8830 c += f->c;
8833 decl_initializer(type, sec, c, 0, size_only);
8835 /* XXX: make it more general */
8836 if (!size_only && nb_elems > 1) {
8837 unsigned long c_end;
8838 uint8_t *src, *dst;
8839 int i;
8841 if (!sec)
8842 error("range init not supported yet for dynamic storage");
8843 c_end = c + nb_elems * elem_size;
8844 if (c_end > sec->data_allocated)
8845 section_realloc(sec, c_end);
8846 src = sec->data + c;
8847 dst = src;
8848 for(i = 1; i < nb_elems; i++) {
8849 dst += elem_size;
8850 memcpy(dst, src, elem_size);
8855 #define EXPR_VAL 0
8856 #define EXPR_CONST 1
8857 #define EXPR_ANY 2
8859 /* store a value or an expression directly in global data or in local array */
8860 static void init_putv(CType *type, Section *sec, unsigned long c,
8861 int v, int expr_type)
8863 int saved_global_expr, bt, bit_pos, bit_size;
8864 void *ptr;
8865 unsigned long long bit_mask;
8866 CType dtype;
8868 switch(expr_type) {
8869 case EXPR_VAL:
8870 vpushi(v);
8871 break;
8872 case EXPR_CONST:
8873 /* compound literals must be allocated globally in this case */
8874 saved_global_expr = global_expr;
8875 global_expr = 1;
8876 expr_const1();
8877 global_expr = saved_global_expr;
8878 /* NOTE: symbols are accepted */
8879 if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
8880 error("initializer element is not constant");
8881 break;
8882 case EXPR_ANY:
8883 expr_eq();
8884 break;
8887 dtype = *type;
8888 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
8890 if (sec) {
8891 /* XXX: not portable */
8892 /* XXX: generate error if incorrect relocation */
8893 gen_assign_cast(&dtype);
8894 bt = type->t & VT_BTYPE;
8895 /* we'll write at most 12 bytes */
8896 if (c + 12 > sec->data_allocated) {
8897 section_realloc(sec, c + 12);
8899 ptr = sec->data + c;
8900 /* XXX: make code faster ? */
8901 if (!(type->t & VT_BITFIELD)) {
8902 bit_pos = 0;
8903 bit_size = 32;
8904 bit_mask = -1LL;
8905 } else {
8906 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
8907 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
8908 bit_mask = (1LL << bit_size) - 1;
8910 if ((vtop->r & VT_SYM) &&
8911 (bt == VT_BYTE ||
8912 bt == VT_SHORT ||
8913 bt == VT_DOUBLE ||
8914 bt == VT_LDOUBLE ||
8915 bt == VT_LLONG ||
8916 (bt == VT_INT && bit_size != 32)))
8917 error("initializer element is not computable at load time");
8918 switch(bt) {
8919 case VT_BOOL:
8920 vtop->c.i = (vtop->c.i != 0);
8921 case VT_BYTE:
8922 *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
8923 break;
8924 case VT_SHORT:
8925 *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
8926 break;
8927 case VT_DOUBLE:
8928 *(double *)ptr = vtop->c.d;
8929 break;
8930 case VT_LDOUBLE:
8931 *(long double *)ptr = vtop->c.ld;
8932 break;
8933 case VT_LLONG:
8934 *(long long *)ptr |= (vtop->c.ll & bit_mask) << bit_pos;
8935 break;
8936 default:
8937 if (vtop->r & VT_SYM) {
8938 greloc(sec, vtop->sym, c, R_DATA_32);
8940 *(int *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
8941 break;
8943 vtop--;
8944 } else {
8945 vset(&dtype, VT_LOCAL|VT_LVAL, c);
8946 vswap();
8947 vstore();
8948 vpop();
8952 /* put zeros for variable based init */
8953 static void init_putz(CType *t, Section *sec, unsigned long c, int size)
8955 if (sec) {
8956 /* nothing to do because globals are already set to zero */
8957 } else {
8958 vpush_global_sym(&func_old_type, TOK_memset);
8959 vseti(VT_LOCAL, c);
8960 vpushi(0);
8961 vpushi(size);
8962 gfunc_call(3);
8966 /* 't' contains the type and storage info. 'c' is the offset of the
8967 object in section 'sec'. If 'sec' is NULL, it means stack based
8968 allocation. 'first' is true if array '{' must be read (multi
8969 dimension implicit array init handling). 'size_only' is true if
8970 size only evaluation is wanted (only for arrays). */
8971 static void decl_initializer(CType *type, Section *sec, unsigned long c,
8972 int first, int size_only)
8974 int index, array_length, n, no_oblock, nb, parlevel, i;
8975 int size1, align1, expr_type;
8976 Sym *s, *f;
8977 CType *t1;
8979 if (type->t & VT_ARRAY) {
8980 s = type->ref;
8981 n = s->c;
8982 array_length = 0;
8983 t1 = pointed_type(type);
8984 size1 = type_size(t1, &align1);
8986 no_oblock = 1;
8987 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
8988 tok == '{') {
8989 skip('{');
8990 no_oblock = 0;
8993 /* only parse strings here if correct type (otherwise: handle
8994 them as ((w)char *) expressions */
8995 if ((tok == TOK_LSTR &&
8996 #ifdef TCC_TARGET_PE
8997 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
8998 #else
8999 (t1->t & VT_BTYPE) == VT_INT
9000 #endif
9001 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
9002 while (tok == TOK_STR || tok == TOK_LSTR) {
9003 int cstr_len, ch;
9004 CString *cstr;
9006 cstr = tokc.cstr;
9007 /* compute maximum number of chars wanted */
9008 if (tok == TOK_STR)
9009 cstr_len = cstr->size;
9010 else
9011 cstr_len = cstr->size / sizeof(nwchar_t);
9012 cstr_len--;
9013 nb = cstr_len;
9014 if (n >= 0 && nb > (n - array_length))
9015 nb = n - array_length;
9016 if (!size_only) {
9017 if (cstr_len > nb)
9018 warning("initializer-string for array is too long");
9019 /* in order to go faster for common case (char
9020 string in global variable, we handle it
9021 specifically */
9022 if (sec && tok == TOK_STR && size1 == 1) {
9023 memcpy(sec->data + c + array_length, cstr->data, nb);
9024 } else {
9025 for(i=0;i<nb;i++) {
9026 if (tok == TOK_STR)
9027 ch = ((unsigned char *)cstr->data)[i];
9028 else
9029 ch = ((nwchar_t *)cstr->data)[i];
9030 init_putv(t1, sec, c + (array_length + i) * size1,
9031 ch, EXPR_VAL);
9035 array_length += nb;
9036 next();
9038 /* only add trailing zero if enough storage (no
9039 warning in this case since it is standard) */
9040 if (n < 0 || array_length < n) {
9041 if (!size_only) {
9042 init_putv(t1, sec, c + (array_length * size1), 0, EXPR_VAL);
9044 array_length++;
9046 } else {
9047 index = 0;
9048 while (tok != '}') {
9049 decl_designator(type, sec, c, &index, NULL, size_only);
9050 if (n >= 0 && index >= n)
9051 error("index too large");
9052 /* must put zero in holes (note that doing it that way
9053 ensures that it even works with designators) */
9054 if (!size_only && array_length < index) {
9055 init_putz(t1, sec, c + array_length * size1,
9056 (index - array_length) * size1);
9058 index++;
9059 if (index > array_length)
9060 array_length = index;
9061 /* special test for multi dimensional arrays (may not
9062 be strictly correct if designators are used at the
9063 same time) */
9064 if (index >= n && no_oblock)
9065 break;
9066 if (tok == '}')
9067 break;
9068 skip(',');
9071 if (!no_oblock)
9072 skip('}');
9073 /* put zeros at the end */
9074 if (!size_only && n >= 0 && array_length < n) {
9075 init_putz(t1, sec, c + array_length * size1,
9076 (n - array_length) * size1);
9078 /* patch type size if needed */
9079 if (n < 0)
9080 s->c = array_length;
9081 } else if ((type->t & VT_BTYPE) == VT_STRUCT &&
9082 (sec || !first || tok == '{')) {
9083 int par_count;
9085 /* NOTE: the previous test is a specific case for automatic
9086 struct/union init */
9087 /* XXX: union needs only one init */
9089 /* XXX: this test is incorrect for local initializers
9090 beginning with ( without {. It would be much more difficult
9091 to do it correctly (ideally, the expression parser should
9092 be used in all cases) */
9093 par_count = 0;
9094 if (tok == '(') {
9095 AttributeDef ad1;
9096 CType type1;
9097 next();
9098 while (tok == '(') {
9099 par_count++;
9100 next();
9102 if (!parse_btype(&type1, &ad1))
9103 expect("cast");
9104 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
9105 #if 0
9106 if (!is_assignable_types(type, &type1))
9107 error("invalid type for cast");
9108 #endif
9109 skip(')');
9111 no_oblock = 1;
9112 if (first || tok == '{') {
9113 skip('{');
9114 no_oblock = 0;
9116 s = type->ref;
9117 f = s->next;
9118 array_length = 0;
9119 index = 0;
9120 n = s->c;
9121 while (tok != '}') {
9122 decl_designator(type, sec, c, NULL, &f, size_only);
9123 index = f->c;
9124 if (!size_only && array_length < index) {
9125 init_putz(type, sec, c + array_length,
9126 index - array_length);
9128 index = index + type_size(&f->type, &align1);
9129 if (index > array_length)
9130 array_length = index;
9131 f = f->next;
9132 if (no_oblock && f == NULL)
9133 break;
9134 if (tok == '}')
9135 break;
9136 skip(',');
9138 /* put zeros at the end */
9139 if (!size_only && array_length < n) {
9140 init_putz(type, sec, c + array_length,
9141 n - array_length);
9143 if (!no_oblock)
9144 skip('}');
9145 while (par_count) {
9146 skip(')');
9147 par_count--;
9149 } else if (tok == '{') {
9150 next();
9151 decl_initializer(type, sec, c, first, size_only);
9152 skip('}');
9153 } else if (size_only) {
9154 /* just skip expression */
9155 parlevel = 0;
9156 while ((parlevel > 0 || (tok != '}' && tok != ',')) &&
9157 tok != -1) {
9158 if (tok == '(')
9159 parlevel++;
9160 else if (tok == ')')
9161 parlevel--;
9162 next();
9164 } else {
9165 /* currently, we always use constant expression for globals
9166 (may change for scripting case) */
9167 expr_type = EXPR_CONST;
9168 if (!sec)
9169 expr_type = EXPR_ANY;
9170 init_putv(type, sec, c, 0, expr_type);
9174 /* parse an initializer for type 't' if 'has_init' is non zero, and
9175 allocate space in local or global data space ('r' is either
9176 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
9177 variable 'v' of scope 'scope' is declared before initializers are
9178 parsed. If 'v' is zero, then a reference to the new object is put
9179 in the value stack. If 'has_init' is 2, a special parsing is done
9180 to handle string constants. */
9181 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
9182 int has_init, int v, int scope)
9184 int size, align, addr, data_offset;
9185 int level;
9186 ParseState saved_parse_state;
9187 TokenString init_str;
9188 Section *sec;
9190 size = type_size(type, &align);
9191 /* If unknown size, we must evaluate it before
9192 evaluating initializers because
9193 initializers can generate global data too
9194 (e.g. string pointers or ISOC99 compound
9195 literals). It also simplifies local
9196 initializers handling */
9197 tok_str_new(&init_str);
9198 if (size < 0) {
9199 if (!has_init)
9200 error("unknown type size");
9201 /* get all init string */
9202 if (has_init == 2) {
9203 /* only get strings */
9204 while (tok == TOK_STR || tok == TOK_LSTR) {
9205 tok_str_add_tok(&init_str);
9206 next();
9208 } else {
9209 level = 0;
9210 while (level > 0 || (tok != ',' && tok != ';')) {
9211 if (tok < 0)
9212 error("unexpected end of file in initializer");
9213 tok_str_add_tok(&init_str);
9214 if (tok == '{')
9215 level++;
9216 else if (tok == '}') {
9217 level--;
9218 if (level <= 0) {
9219 next();
9220 break;
9223 next();
9226 tok_str_add(&init_str, -1);
9227 tok_str_add(&init_str, 0);
9229 /* compute size */
9230 save_parse_state(&saved_parse_state);
9232 macro_ptr = init_str.str;
9233 next();
9234 decl_initializer(type, NULL, 0, 1, 1);
9235 /* prepare second initializer parsing */
9236 macro_ptr = init_str.str;
9237 next();
9239 /* if still unknown size, error */
9240 size = type_size(type, &align);
9241 if (size < 0)
9242 error("unknown type size");
9244 /* take into account specified alignment if bigger */
9245 if (ad->aligned) {
9246 if (ad->aligned > align)
9247 align = ad->aligned;
9248 } else if (ad->packed) {
9249 align = 1;
9251 if ((r & VT_VALMASK) == VT_LOCAL) {
9252 sec = NULL;
9253 if (do_bounds_check && (type->t & VT_ARRAY))
9254 loc--;
9255 loc = (loc - size) & -align;
9256 addr = loc;
9257 /* handles bounds */
9258 /* XXX: currently, since we do only one pass, we cannot track
9259 '&' operators, so we add only arrays */
9260 if (do_bounds_check && (type->t & VT_ARRAY)) {
9261 unsigned long *bounds_ptr;
9262 /* add padding between regions */
9263 loc--;
9264 /* then add local bound info */
9265 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(unsigned long));
9266 bounds_ptr[0] = addr;
9267 bounds_ptr[1] = size;
9269 if (v) {
9270 /* local variable */
9271 sym_push(v, type, r, addr);
9272 } else {
9273 /* push local reference */
9274 vset(type, r, addr);
9276 } else {
9277 Sym *sym;
9279 sym = NULL;
9280 if (v && scope == VT_CONST) {
9281 /* see if the symbol was already defined */
9282 sym = sym_find(v);
9283 if (sym) {
9284 if (!is_compatible_types(&sym->type, type))
9285 error("incompatible types for redefinition of '%s'",
9286 get_tok_str(v, NULL));
9287 if (sym->type.t & VT_EXTERN) {
9288 /* if the variable is extern, it was not allocated */
9289 sym->type.t &= ~VT_EXTERN;
9290 /* set array size if it was ommited in extern
9291 declaration */
9292 if ((sym->type.t & VT_ARRAY) &&
9293 sym->type.ref->c < 0 &&
9294 type->ref->c >= 0)
9295 sym->type.ref->c = type->ref->c;
9296 } else {
9297 /* we accept several definitions of the same
9298 global variable. this is tricky, because we
9299 must play with the SHN_COMMON type of the symbol */
9300 /* XXX: should check if the variable was already
9301 initialized. It is incorrect to initialized it
9302 twice */
9303 /* no init data, we won't add more to the symbol */
9304 if (!has_init)
9305 goto no_alloc;
9310 /* allocate symbol in corresponding section */
9311 sec = ad->section;
9312 if (!sec) {
9313 if (has_init)
9314 sec = data_section;
9315 else if (tcc_state->nocommon)
9316 sec = bss_section;
9318 if (sec) {
9319 data_offset = sec->data_offset;
9320 data_offset = (data_offset + align - 1) & -align;
9321 addr = data_offset;
9322 /* very important to increment global pointer at this time
9323 because initializers themselves can create new initializers */
9324 data_offset += size;
9325 /* add padding if bound check */
9326 if (do_bounds_check)
9327 data_offset++;
9328 sec->data_offset = data_offset;
9329 /* allocate section space to put the data */
9330 if (sec->sh_type != SHT_NOBITS &&
9331 data_offset > sec->data_allocated)
9332 section_realloc(sec, data_offset);
9333 /* align section if needed */
9334 if (align > sec->sh_addralign)
9335 sec->sh_addralign = align;
9336 } else {
9337 addr = 0; /* avoid warning */
9340 if (v) {
9341 if (scope != VT_CONST || !sym) {
9342 sym = sym_push(v, type, r | VT_SYM, 0);
9344 /* update symbol definition */
9345 if (sec) {
9346 put_extern_sym(sym, sec, addr, size);
9347 } else {
9348 ElfW(Sym) *esym;
9349 /* put a common area */
9350 put_extern_sym(sym, NULL, align, size);
9351 /* XXX: find a nicer way */
9352 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
9353 esym->st_shndx = SHN_COMMON;
9355 } else {
9356 CValue cval;
9358 /* push global reference */
9359 sym = get_sym_ref(type, sec, addr, size);
9360 cval.ul = 0;
9361 vsetc(type, VT_CONST | VT_SYM, &cval);
9362 vtop->sym = sym;
9365 /* handles bounds now because the symbol must be defined
9366 before for the relocation */
9367 if (do_bounds_check) {
9368 unsigned long *bounds_ptr;
9370 greloc(bounds_section, sym, bounds_section->data_offset, R_DATA_32);
9371 /* then add global bound info */
9372 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(long));
9373 bounds_ptr[0] = 0; /* relocated */
9374 bounds_ptr[1] = size;
9377 if (has_init) {
9378 decl_initializer(type, sec, addr, 1, 0);
9379 /* restore parse state if needed */
9380 if (init_str.str) {
9381 tok_str_free(init_str.str);
9382 restore_parse_state(&saved_parse_state);
9385 no_alloc: ;
9388 void put_func_debug(Sym *sym)
9390 char buf[512];
9392 /* stabs info */
9393 /* XXX: we put here a dummy type */
9394 snprintf(buf, sizeof(buf), "%s:%c1",
9395 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
9396 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
9397 cur_text_section, sym->c);
9398 /* //gr gdb wants a line at the function */
9399 put_stabn(N_SLINE, 0, file->line_num, 0);
9400 last_ind = 0;
9401 last_line_num = 0;
9404 /* parse an old style function declaration list */
9405 /* XXX: check multiple parameter */
9406 static void func_decl_list(Sym *func_sym)
9408 AttributeDef ad;
9409 int v;
9410 Sym *s;
9411 CType btype, type;
9413 /* parse each declaration */
9414 while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF) {
9415 if (!parse_btype(&btype, &ad))
9416 expect("declaration list");
9417 if (((btype.t & VT_BTYPE) == VT_ENUM ||
9418 (btype.t & VT_BTYPE) == VT_STRUCT) &&
9419 tok == ';') {
9420 /* we accept no variable after */
9421 } else {
9422 for(;;) {
9423 type = btype;
9424 type_decl(&type, &ad, &v, TYPE_DIRECT);
9425 /* find parameter in function parameter list */
9426 s = func_sym->next;
9427 while (s != NULL) {
9428 if ((s->v & ~SYM_FIELD) == v)
9429 goto found;
9430 s = s->next;
9432 error("declaration for parameter '%s' but no such parameter",
9433 get_tok_str(v, NULL));
9434 found:
9435 /* check that no storage specifier except 'register' was given */
9436 if (type.t & VT_STORAGE)
9437 error("storage class specified for '%s'", get_tok_str(v, NULL));
9438 convert_parameter_type(&type);
9439 /* we can add the type (NOTE: it could be local to the function) */
9440 s->type = type;
9441 /* accept other parameters */
9442 if (tok == ',')
9443 next();
9444 else
9445 break;
9448 skip(';');
9452 /* parse a function defined by symbol 'sym' and generate its code in
9453 'cur_text_section' */
9454 static void gen_function(Sym *sym)
9456 int saved_nocode_wanted = nocode_wanted;
9457 nocode_wanted = 0;
9458 ind = cur_text_section->data_offset;
9459 /* NOTE: we patch the symbol size later */
9460 put_extern_sym(sym, cur_text_section, ind, 0);
9461 funcname = get_tok_str(sym->v, NULL);
9462 func_ind = ind;
9463 /* put debug symbol */
9464 if (do_debug)
9465 put_func_debug(sym);
9466 /* push a dummy symbol to enable local sym storage */
9467 sym_push2(&local_stack, SYM_FIELD, 0, 0);
9468 gfunc_prolog(&sym->type);
9469 rsym = 0;
9470 block(NULL, NULL, NULL, NULL, 0, 0);
9471 gsym(rsym);
9472 gfunc_epilog();
9473 cur_text_section->data_offset = ind;
9474 label_pop(&global_label_stack, NULL);
9475 sym_pop(&local_stack, NULL); /* reset local stack */
9476 /* end of function */
9477 /* patch symbol size */
9478 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
9479 ind - func_ind;
9480 if (do_debug) {
9481 put_stabn(N_FUN, 0, 0, ind - func_ind);
9483 /* It's better to crash than to generate wrong code */
9484 cur_text_section = NULL;
9485 funcname = ""; /* for safety */
9486 func_vt.t = VT_VOID; /* for safety */
9487 ind = 0; /* for safety */
9488 nocode_wanted = saved_nocode_wanted;
9491 static void gen_inline_functions(void)
9493 Sym *sym;
9494 CType *type;
9495 int *str, inline_generated;
9497 /* iterate while inline function are referenced */
9498 for(;;) {
9499 inline_generated = 0;
9500 for(sym = global_stack; sym != NULL; sym = sym->prev) {
9501 type = &sym->type;
9502 if (((type->t & VT_BTYPE) == VT_FUNC) &&
9503 (type->t & (VT_STATIC | VT_INLINE)) ==
9504 (VT_STATIC | VT_INLINE) &&
9505 sym->c != 0) {
9506 /* the function was used: generate its code and
9507 convert it to a normal function */
9508 str = INLINE_DEF(sym->r);
9509 sym->r = VT_SYM | VT_CONST;
9510 sym->type.t &= ~VT_INLINE;
9512 macro_ptr = str;
9513 next();
9514 cur_text_section = text_section;
9515 gen_function(sym);
9516 macro_ptr = NULL; /* fail safe */
9518 tok_str_free(str);
9519 inline_generated = 1;
9522 if (!inline_generated)
9523 break;
9526 /* free all remaining inline function tokens */
9527 for(sym = global_stack; sym != NULL; sym = sym->prev) {
9528 type = &sym->type;
9529 if (((type->t & VT_BTYPE) == VT_FUNC) &&
9530 (type->t & (VT_STATIC | VT_INLINE)) ==
9531 (VT_STATIC | VT_INLINE)) {
9532 //gr printf("sym %d %s\n", sym->r, get_tok_str(sym->v, NULL));
9533 if (sym->r == (VT_SYM | VT_CONST)) //gr beware!
9534 continue;
9535 str = INLINE_DEF(sym->r);
9536 tok_str_free(str);
9537 sym->r = 0; /* fail safe */
9542 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
9543 static void decl(int l)
9545 int v, has_init, r;
9546 CType type, btype;
9547 Sym *sym;
9548 AttributeDef ad;
9550 while (1) {
9551 if (!parse_btype(&btype, &ad)) {
9552 /* skip redundant ';' */
9553 /* XXX: find more elegant solution */
9554 if (tok == ';') {
9555 next();
9556 continue;
9558 if (l == VT_CONST &&
9559 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
9560 /* global asm block */
9561 asm_global_instr();
9562 continue;
9564 /* special test for old K&R protos without explicit int
9565 type. Only accepted when defining global data */
9566 if (l == VT_LOCAL || tok < TOK_DEFINE)
9567 break;
9568 btype.t = VT_INT;
9570 if (((btype.t & VT_BTYPE) == VT_ENUM ||
9571 (btype.t & VT_BTYPE) == VT_STRUCT) &&
9572 tok == ';') {
9573 /* we accept no variable after */
9574 next();
9575 continue;
9577 while (1) { /* iterate thru each declaration */
9578 type = btype;
9579 type_decl(&type, &ad, &v, TYPE_DIRECT);
9580 #if 0
9582 char buf[500];
9583 type_to_str(buf, sizeof(buf), t, get_tok_str(v, NULL));
9584 printf("type = '%s'\n", buf);
9586 #endif
9587 if ((type.t & VT_BTYPE) == VT_FUNC) {
9588 /* if old style function prototype, we accept a
9589 declaration list */
9590 sym = type.ref;
9591 if (sym->c == FUNC_OLD)
9592 func_decl_list(sym);
9595 if (tok == '{') {
9596 if (l == VT_LOCAL)
9597 error("cannot use local functions");
9598 if ((type.t & VT_BTYPE) != VT_FUNC)
9599 expect("function definition");
9601 /* reject abstract declarators in function definition */
9602 sym = type.ref;
9603 while ((sym = sym->next) != NULL)
9604 if (!(sym->v & ~SYM_FIELD))
9605 expect("identifier");
9607 /* XXX: cannot do better now: convert extern line to static inline */
9608 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
9609 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
9611 sym = sym_find(v);
9612 if (sym) {
9613 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
9614 goto func_error1;
9615 /* specific case: if not func_call defined, we put
9616 the one of the prototype */
9617 /* XXX: should have default value */
9618 r = sym->type.ref->r;
9619 if (FUNC_CALL(r) != FUNC_CDECL
9620 && FUNC_CALL(type.ref->r) == FUNC_CDECL)
9621 FUNC_CALL(type.ref->r) = FUNC_CALL(r);
9622 if (FUNC_EXPORT(r))
9623 FUNC_EXPORT(type.ref->r) = 1;
9625 if (!is_compatible_types(&sym->type, &type)) {
9626 func_error1:
9627 error("incompatible types for redefinition of '%s'",
9628 get_tok_str(v, NULL));
9630 /* if symbol is already defined, then put complete type */
9631 sym->type = type;
9632 } else {
9633 /* put function symbol */
9634 sym = global_identifier_push(v, type.t, 0);
9635 sym->type.ref = type.ref;
9638 /* static inline functions are just recorded as a kind
9639 of macro. Their code will be emitted at the end of
9640 the compilation unit only if they are used */
9641 if ((type.t & (VT_INLINE | VT_STATIC)) ==
9642 (VT_INLINE | VT_STATIC)) {
9643 TokenString func_str;
9644 int block_level;
9646 tok_str_new(&func_str);
9648 block_level = 0;
9649 for(;;) {
9650 int t;
9651 if (tok == TOK_EOF)
9652 error("unexpected end of file");
9653 tok_str_add_tok(&func_str);
9654 t = tok;
9655 next();
9656 if (t == '{') {
9657 block_level++;
9658 } else if (t == '}') {
9659 block_level--;
9660 if (block_level == 0)
9661 break;
9664 tok_str_add(&func_str, -1);
9665 tok_str_add(&func_str, 0);
9666 INLINE_DEF(sym->r) = func_str.str;
9667 } else {
9668 /* compute text section */
9669 cur_text_section = ad.section;
9670 if (!cur_text_section)
9671 cur_text_section = text_section;
9672 sym->r = VT_SYM | VT_CONST;
9673 gen_function(sym);
9675 break;
9676 } else {
9677 if (btype.t & VT_TYPEDEF) {
9678 /* save typedefed type */
9679 /* XXX: test storage specifiers ? */
9680 sym = sym_push(v, &type, 0, 0);
9681 sym->type.t |= VT_TYPEDEF;
9682 } else if ((type.t & VT_BTYPE) == VT_FUNC) {
9683 /* external function definition */
9684 /* specific case for func_call attribute */
9685 if (ad.func_attr)
9686 type.ref->r = ad.func_attr;
9687 external_sym(v, &type, 0);
9688 } else {
9689 /* not lvalue if array */
9690 r = 0;
9691 if (!(type.t & VT_ARRAY))
9692 r |= lvalue_type(type.t);
9693 has_init = (tok == '=');
9694 if ((btype.t & VT_EXTERN) ||
9695 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
9696 !has_init && l == VT_CONST && type.ref->c < 0)) {
9697 /* external variable */
9698 /* NOTE: as GCC, uninitialized global static
9699 arrays of null size are considered as
9700 extern */
9701 external_sym(v, &type, r);
9702 } else {
9703 type.t |= (btype.t & VT_STATIC); /* Retain "static". */
9704 if (type.t & VT_STATIC)
9705 r |= VT_CONST;
9706 else
9707 r |= l;
9708 if (has_init)
9709 next();
9710 decl_initializer_alloc(&type, &ad, r,
9711 has_init, v, l);
9714 if (tok != ',') {
9715 skip(';');
9716 break;
9718 next();
9724 /* better than nothing, but needs extension to handle '-E' option
9725 correctly too */
9726 static void preprocess_init(TCCState *s1)
9728 s1->include_stack_ptr = s1->include_stack;
9729 /* XXX: move that before to avoid having to initialize
9730 file->ifdef_stack_ptr ? */
9731 s1->ifdef_stack_ptr = s1->ifdef_stack;
9732 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
9734 /* XXX: not ANSI compliant: bound checking says error */
9735 vtop = vstack - 1;
9736 s1->pack_stack[0] = 0;
9737 s1->pack_stack_ptr = s1->pack_stack;
9740 /* compile the C file opened in 'file'. Return non zero if errors. */
9741 static int tcc_compile(TCCState *s1)
9743 Sym *define_start;
9744 char buf[512];
9745 volatile int section_sym;
9747 #ifdef INC_DEBUG
9748 printf("%s: **** new file\n", file->filename);
9749 #endif
9750 preprocess_init(s1);
9752 cur_text_section = NULL;
9753 funcname = "";
9754 anon_sym = SYM_FIRST_ANOM;
9756 /* file info: full path + filename */
9757 section_sym = 0; /* avoid warning */
9758 if (do_debug) {
9759 section_sym = put_elf_sym(symtab_section, 0, 0,
9760 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
9761 text_section->sh_num, NULL);
9762 getcwd(buf, sizeof(buf));
9763 #ifdef _WIN32
9764 normalize_slashes(buf);
9765 #endif
9766 pstrcat(buf, sizeof(buf), "/");
9767 put_stabs_r(buf, N_SO, 0, 0,
9768 text_section->data_offset, text_section, section_sym);
9769 put_stabs_r(file->filename, N_SO, 0, 0,
9770 text_section->data_offset, text_section, section_sym);
9772 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
9773 symbols can be safely used */
9774 put_elf_sym(symtab_section, 0, 0,
9775 ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
9776 SHN_ABS, file->filename);
9778 /* define some often used types */
9779 int_type.t = VT_INT;
9781 char_pointer_type.t = VT_BYTE;
9782 mk_pointer(&char_pointer_type);
9784 func_old_type.t = VT_FUNC;
9785 func_old_type.ref = sym_push(SYM_FIELD, &int_type, FUNC_CDECL, FUNC_OLD);
9787 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
9788 float_type.t = VT_FLOAT;
9789 double_type.t = VT_DOUBLE;
9791 func_float_type.t = VT_FUNC;
9792 func_float_type.ref = sym_push(SYM_FIELD, &float_type, FUNC_CDECL, FUNC_OLD);
9793 func_double_type.t = VT_FUNC;
9794 func_double_type.ref = sym_push(SYM_FIELD, &double_type, FUNC_CDECL, FUNC_OLD);
9795 #endif
9797 #if 0
9798 /* define 'void *alloca(unsigned int)' builtin function */
9800 Sym *s1;
9802 p = anon_sym++;
9803 sym = sym_push(p, mk_pointer(VT_VOID), FUNC_CDECL, FUNC_NEW);
9804 s1 = sym_push(SYM_FIELD, VT_UNSIGNED | VT_INT, 0, 0);
9805 s1->next = NULL;
9806 sym->next = s1;
9807 sym_push(TOK_alloca, VT_FUNC | (p << VT_STRUCT_SHIFT), VT_CONST, 0);
9809 #endif
9811 define_start = define_stack;
9812 nocode_wanted = 1;
9814 if (setjmp(s1->error_jmp_buf) == 0) {
9815 s1->nb_errors = 0;
9816 s1->error_set_jmp_enabled = 1;
9818 ch = file->buf_ptr[0];
9819 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
9820 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM;
9821 next();
9822 decl(VT_CONST);
9823 if (tok != TOK_EOF)
9824 expect("declaration");
9826 /* end of translation unit info */
9827 if (do_debug) {
9828 put_stabs_r(NULL, N_SO, 0, 0,
9829 text_section->data_offset, text_section, section_sym);
9832 s1->error_set_jmp_enabled = 0;
9834 /* reset define stack, but leave -Dsymbols (may be incorrect if
9835 they are undefined) */
9836 free_defines(define_start);
9838 gen_inline_functions();
9840 sym_pop(&global_stack, NULL);
9841 sym_pop(&local_stack, NULL);
9843 return s1->nb_errors != 0 ? -1 : 0;
9846 /* Preprocess the current file */
9847 /* XXX: add line and file infos,
9848 * XXX: add options to preserve spaces (partly done, only spaces in macro are
9849 * not preserved)
9851 static int tcc_preprocess(TCCState *s1)
9853 Sym *define_start;
9854 BufferedFile *file_ref;
9855 int token_seen, line_ref;
9857 preprocess_init(s1);
9858 define_start = define_stack;
9859 ch = file->buf_ptr[0];
9861 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
9862 parse_flags = PARSE_FLAG_ASM_COMMENTS | PARSE_FLAG_PREPROCESS |
9863 PARSE_FLAG_LINEFEED;
9865 token_seen = 0;
9866 line_ref = 0;
9867 file_ref = NULL;
9869 for (;;) {
9870 next();
9871 if (tok == TOK_EOF) {
9872 break;
9873 } else if (tok == TOK_LINEFEED) {
9874 if (!token_seen)
9875 continue;
9876 ++line_ref;
9877 token_seen = 0;
9878 } else if (token_seen) {
9879 fwrite(tok_spaces.data, tok_spaces.size, 1, s1->outfile);
9880 } else {
9881 int d = file->line_num - line_ref;
9882 if (file != file_ref || d < 0 || d >= 8)
9883 fprintf(s1->outfile, "# %d \"%s\"\n", file->line_num, file->filename);
9884 else
9885 while (d)
9886 fputs("\n", s1->outfile), --d;
9887 line_ref = (file_ref = file)->line_num;
9888 token_seen = 1;
9890 fputs(get_tok_str(tok, &tokc), s1->outfile);
9892 free_defines(define_start);
9893 return 0;
9896 #ifdef LIBTCC
9897 int tcc_compile_string(TCCState *s, const char *str)
9899 BufferedFile bf1, *bf = &bf1;
9900 int ret, len;
9901 char *buf;
9903 /* init file structure */
9904 bf->fd = -1;
9905 /* XXX: avoid copying */
9906 len = strlen(str);
9907 buf = tcc_malloc(len + 1);
9908 if (!buf)
9909 return -1;
9910 memcpy(buf, str, len);
9911 buf[len] = CH_EOB;
9912 bf->buf_ptr = buf;
9913 bf->buf_end = buf + len;
9914 pstrcpy(bf->filename, sizeof(bf->filename), "<string>");
9915 bf->line_num = 1;
9916 file = bf;
9917 ret = tcc_compile(s);
9918 file = NULL;
9919 tcc_free(buf);
9921 /* currently, no need to close */
9922 return ret;
9924 #endif
9926 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
9927 void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
9929 BufferedFile bf1, *bf = &bf1;
9931 pstrcpy(bf->buffer, IO_BUF_SIZE, sym);
9932 pstrcat(bf->buffer, IO_BUF_SIZE, " ");
9933 /* default value */
9934 if (!value)
9935 value = "1";
9936 pstrcat(bf->buffer, IO_BUF_SIZE, value);
9938 /* init file structure */
9939 bf->fd = -1;
9940 bf->buf_ptr = bf->buffer;
9941 bf->buf_end = bf->buffer + strlen(bf->buffer);
9942 *bf->buf_end = CH_EOB;
9943 bf->filename[0] = '\0';
9944 bf->line_num = 1;
9945 file = bf;
9947 s1->include_stack_ptr = s1->include_stack;
9949 /* parse with define parser */
9950 ch = file->buf_ptr[0];
9951 next_nomacro();
9952 parse_define();
9953 file = NULL;
9956 /* undefine a preprocessor symbol */
9957 void tcc_undefine_symbol(TCCState *s1, const char *sym)
9959 TokenSym *ts;
9960 Sym *s;
9961 ts = tok_alloc(sym, strlen(sym));
9962 s = define_find(ts->tok);
9963 /* undefine symbol by putting an invalid name */
9964 if (s)
9965 define_undef(s);
9968 #ifdef CONFIG_TCC_ASM
9970 #ifdef TCC_TARGET_I386
9971 #include "i386-asm.c"
9972 #endif
9973 #include "tccasm.c"
9975 #else
9976 static void asm_instr(void)
9978 error("inline asm() not supported");
9980 static void asm_global_instr(void)
9982 error("inline asm() not supported");
9984 #endif
9986 #include "tccelf.c"
9988 #ifdef TCC_TARGET_COFF
9989 #include "tcccoff.c"
9990 #endif
9992 #ifdef TCC_TARGET_PE
9993 #include "tccpe.c"
9994 #endif
9996 /* print the position in the source file of PC value 'pc' by reading
9997 the stabs debug information */
9998 static void rt_printline(unsigned long wanted_pc)
10000 Stab_Sym *sym, *sym_end;
10001 char func_name[128], last_func_name[128];
10002 unsigned long func_addr, last_pc, pc;
10003 const char *incl_files[INCLUDE_STACK_SIZE];
10004 int incl_index, len, last_line_num, i;
10005 const char *str, *p;
10007 fprintf(stderr, "0x%08lx:", wanted_pc);
10009 func_name[0] = '\0';
10010 func_addr = 0;
10011 incl_index = 0;
10012 last_func_name[0] = '\0';
10013 last_pc = 0xffffffff;
10014 last_line_num = 1;
10015 sym = (Stab_Sym *)stab_section->data + 1;
10016 sym_end = (Stab_Sym *)(stab_section->data + stab_section->data_offset);
10017 while (sym < sym_end) {
10018 switch(sym->n_type) {
10019 /* function start or end */
10020 case N_FUN:
10021 if (sym->n_strx == 0) {
10022 /* we test if between last line and end of function */
10023 pc = sym->n_value + func_addr;
10024 if (wanted_pc >= last_pc && wanted_pc < pc)
10025 goto found;
10026 func_name[0] = '\0';
10027 func_addr = 0;
10028 } else {
10029 str = stabstr_section->data + sym->n_strx;
10030 p = strchr(str, ':');
10031 if (!p) {
10032 pstrcpy(func_name, sizeof(func_name), str);
10033 } else {
10034 len = p - str;
10035 if (len > sizeof(func_name) - 1)
10036 len = sizeof(func_name) - 1;
10037 memcpy(func_name, str, len);
10038 func_name[len] = '\0';
10040 func_addr = sym->n_value;
10042 break;
10043 /* line number info */
10044 case N_SLINE:
10045 pc = sym->n_value + func_addr;
10046 if (wanted_pc >= last_pc && wanted_pc < pc)
10047 goto found;
10048 last_pc = pc;
10049 last_line_num = sym->n_desc;
10050 /* XXX: slow! */
10051 strcpy(last_func_name, func_name);
10052 break;
10053 /* include files */
10054 case N_BINCL:
10055 str = stabstr_section->data + sym->n_strx;
10056 add_incl:
10057 if (incl_index < INCLUDE_STACK_SIZE) {
10058 incl_files[incl_index++] = str;
10060 break;
10061 case N_EINCL:
10062 if (incl_index > 1)
10063 incl_index--;
10064 break;
10065 case N_SO:
10066 if (sym->n_strx == 0) {
10067 incl_index = 0; /* end of translation unit */
10068 } else {
10069 str = stabstr_section->data + sym->n_strx;
10070 /* do not add path */
10071 len = strlen(str);
10072 if (len > 0 && str[len - 1] != '/')
10073 goto add_incl;
10075 break;
10077 sym++;
10080 /* second pass: we try symtab symbols (no line number info) */
10081 incl_index = 0;
10083 ElfW(Sym) *sym, *sym_end;
10084 int type;
10086 sym_end = (ElfW(Sym) *)(symtab_section->data + symtab_section->data_offset);
10087 for(sym = (ElfW(Sym) *)symtab_section->data + 1;
10088 sym < sym_end;
10089 sym++) {
10090 type = ELFW(ST_TYPE)(sym->st_info);
10091 if (type == STT_FUNC) {
10092 if (wanted_pc >= sym->st_value &&
10093 wanted_pc < sym->st_value + sym->st_size) {
10094 pstrcpy(last_func_name, sizeof(last_func_name),
10095 strtab_section->data + sym->st_name);
10096 goto found;
10101 /* did not find any info: */
10102 fprintf(stderr, " ???\n");
10103 return;
10104 found:
10105 if (last_func_name[0] != '\0') {
10106 fprintf(stderr, " %s()", last_func_name);
10108 if (incl_index > 0) {
10109 fprintf(stderr, " (%s:%d",
10110 incl_files[incl_index - 1], last_line_num);
10111 for(i = incl_index - 2; i >= 0; i--)
10112 fprintf(stderr, ", included from %s", incl_files[i]);
10113 fprintf(stderr, ")");
10115 fprintf(stderr, "\n");
10118 #if !defined(_WIN32) && !defined(CONFIG_TCCBOOT)
10120 #ifdef __i386__
10122 /* fix for glibc 2.1 */
10123 #ifndef REG_EIP
10124 #define REG_EIP EIP
10125 #define REG_EBP EBP
10126 #endif
10128 /* return the PC at frame level 'level'. Return non zero if not found */
10129 static int rt_get_caller_pc(unsigned long *paddr,
10130 ucontext_t *uc, int level)
10132 unsigned long fp;
10133 int i;
10135 if (level == 0) {
10136 #if defined(__FreeBSD__)
10137 *paddr = uc->uc_mcontext.mc_eip;
10138 #elif defined(__dietlibc__)
10139 *paddr = uc->uc_mcontext.eip;
10140 #else
10141 *paddr = uc->uc_mcontext.gregs[REG_EIP];
10142 #endif
10143 return 0;
10144 } else {
10145 #if defined(__FreeBSD__)
10146 fp = uc->uc_mcontext.mc_ebp;
10147 #elif defined(__dietlibc__)
10148 fp = uc->uc_mcontext.ebp;
10149 #else
10150 fp = uc->uc_mcontext.gregs[REG_EBP];
10151 #endif
10152 for(i=1;i<level;i++) {
10153 /* XXX: check address validity with program info */
10154 if (fp <= 0x1000 || fp >= 0xc0000000)
10155 return -1;
10156 fp = ((unsigned long *)fp)[0];
10158 *paddr = ((unsigned long *)fp)[1];
10159 return 0;
10162 #elif defined(__x86_64__)
10163 /* return the PC at frame level 'level'. Return non zero if not found */
10164 static int rt_get_caller_pc(unsigned long *paddr,
10165 ucontext_t *uc, int level)
10167 unsigned long fp;
10168 int i;
10170 if (level == 0) {
10171 /* XXX: only support linux */
10172 *paddr = uc->uc_mcontext.gregs[REG_RIP];
10173 return 0;
10174 } else {
10175 fp = uc->uc_mcontext.gregs[REG_RBP];
10176 for(i=1;i<level;i++) {
10177 /* XXX: check address validity with program info */
10178 if (fp <= 0x1000 || fp >= 0xc0000000)
10179 return -1;
10180 fp = ((unsigned long *)fp)[0];
10182 *paddr = ((unsigned long *)fp)[1];
10183 return 0;
10186 #else
10188 #warning add arch specific rt_get_caller_pc()
10190 static int rt_get_caller_pc(unsigned long *paddr,
10191 ucontext_t *uc, int level)
10193 return -1;
10195 #endif
10197 /* emit a run time error at position 'pc' */
10198 void rt_error(ucontext_t *uc, const char *fmt, ...)
10200 va_list ap;
10201 unsigned long pc;
10202 int i;
10204 va_start(ap, fmt);
10205 fprintf(stderr, "Runtime error: ");
10206 vfprintf(stderr, fmt, ap);
10207 fprintf(stderr, "\n");
10208 for(i=0;i<num_callers;i++) {
10209 if (rt_get_caller_pc(&pc, uc, i) < 0)
10210 break;
10211 if (i == 0)
10212 fprintf(stderr, "at ");
10213 else
10214 fprintf(stderr, "by ");
10215 rt_printline(pc);
10217 exit(255);
10218 va_end(ap);
10221 /* signal handler for fatal errors */
10222 static void sig_error(int signum, siginfo_t *siginf, void *puc)
10224 ucontext_t *uc = puc;
10226 switch(signum) {
10227 case SIGFPE:
10228 switch(siginf->si_code) {
10229 case FPE_INTDIV:
10230 case FPE_FLTDIV:
10231 rt_error(uc, "division by zero");
10232 break;
10233 default:
10234 rt_error(uc, "floating point exception");
10235 break;
10237 break;
10238 case SIGBUS:
10239 case SIGSEGV:
10240 if (rt_bound_error_msg && *rt_bound_error_msg)
10241 rt_error(uc, *rt_bound_error_msg);
10242 else
10243 rt_error(uc, "dereferencing invalid pointer");
10244 break;
10245 case SIGILL:
10246 rt_error(uc, "illegal instruction");
10247 break;
10248 case SIGABRT:
10249 rt_error(uc, "abort() called");
10250 break;
10251 default:
10252 rt_error(uc, "caught signal %d", signum);
10253 break;
10255 exit(255);
10257 #endif
10259 /* do all relocations (needed before using tcc_get_symbol()) */
10260 int tcc_relocate(TCCState *s1)
10262 Section *s;
10263 int i;
10265 s1->nb_errors = 0;
10267 #ifdef TCC_TARGET_PE
10268 pe_add_runtime(s1);
10269 #else
10270 tcc_add_runtime(s1);
10271 #endif
10273 relocate_common_syms();
10275 tcc_add_linker_symbols(s1);
10276 #ifndef TCC_TARGET_PE
10277 build_got_entries(s1);
10278 #endif
10279 /* compute relocation address : section are relocated in place. We
10280 also alloc the bss space */
10281 for(i = 1; i < s1->nb_sections; i++) {
10282 s = s1->sections[i];
10283 if (s->sh_flags & SHF_ALLOC) {
10284 if (s->sh_type == SHT_NOBITS)
10285 s->data = tcc_mallocz(s->data_offset);
10286 s->sh_addr = (unsigned long)s->data;
10290 relocate_syms(s1, 1);
10292 if (s1->nb_errors != 0)
10293 return -1;
10295 /* relocate each section */
10296 for(i = 1; i < s1->nb_sections; i++) {
10297 s = s1->sections[i];
10298 if (s->reloc)
10299 relocate_section(s1, s);
10302 /* mark executable sections as executable in memory */
10303 for(i = 1; i < s1->nb_sections; i++) {
10304 s = s1->sections[i];
10305 if ((s->sh_flags & (SHF_ALLOC | SHF_EXECINSTR)) ==
10306 (SHF_ALLOC | SHF_EXECINSTR))
10307 set_pages_executable(s->data, s->data_offset);
10309 return 0;
10312 /* launch the compiled program with the given arguments */
10313 int tcc_run(TCCState *s1, int argc, char **argv)
10315 int (*prog_main)(int, char **);
10317 if (tcc_relocate(s1) < 0)
10318 return -1;
10320 prog_main = tcc_get_symbol_err(s1, "main");
10322 if (do_debug) {
10323 #if defined(_WIN32) || defined(CONFIG_TCCBOOT)
10324 error("debug mode currently not available for Windows");
10325 #else
10326 struct sigaction sigact;
10327 /* install TCC signal handlers to print debug info on fatal
10328 runtime errors */
10329 sigact.sa_flags = SA_SIGINFO | SA_RESETHAND;
10330 sigact.sa_sigaction = sig_error;
10331 sigemptyset(&sigact.sa_mask);
10332 sigaction(SIGFPE, &sigact, NULL);
10333 sigaction(SIGILL, &sigact, NULL);
10334 sigaction(SIGSEGV, &sigact, NULL);
10335 sigaction(SIGBUS, &sigact, NULL);
10336 sigaction(SIGABRT, &sigact, NULL);
10337 #endif
10340 #ifdef CONFIG_TCC_BCHECK
10341 if (do_bounds_check) {
10342 void (*bound_init)(void);
10344 /* set error function */
10345 rt_bound_error_msg = (void *)tcc_get_symbol_err(s1,
10346 "__bound_error_msg");
10348 /* XXX: use .init section so that it also work in binary ? */
10349 bound_init = (void *)tcc_get_symbol_err(s1, "__bound_init");
10350 bound_init();
10352 #endif
10353 return (*prog_main)(argc, argv);
10356 void tcc_memstats(void)
10358 #ifdef MEM_DEBUG
10359 printf("memory in use: %d\n", mem_cur_size);
10360 #endif
10363 static void tcc_cleanup(void)
10365 int i, n;
10367 if (NULL == tcc_state)
10368 return;
10369 tcc_state = NULL;
10371 /* free -D defines */
10372 free_defines(NULL);
10374 /* free tokens */
10375 n = tok_ident - TOK_IDENT;
10376 for(i = 0; i < n; i++)
10377 tcc_free(table_ident[i]);
10378 tcc_free(table_ident);
10380 /* free sym_pools */
10381 dynarray_reset(&sym_pools, &nb_sym_pools);
10382 /* string buffer */
10383 cstr_free(&tokcstr);
10384 /* reset symbol stack */
10385 sym_free_first = NULL;
10386 /* cleanup from error/setjmp */
10387 macro_ptr = NULL;
10390 TCCState *tcc_new(void)
10392 const char *p, *r;
10393 TCCState *s;
10394 TokenSym *ts;
10395 int i, c;
10397 tcc_cleanup();
10399 s = tcc_mallocz(sizeof(TCCState));
10400 if (!s)
10401 return NULL;
10402 tcc_state = s;
10403 s->output_type = TCC_OUTPUT_MEMORY;
10405 /* init isid table */
10406 for(i=CH_EOF;i<256;i++)
10407 isidnum_table[i-CH_EOF] = isid(i) || isnum(i);
10409 /* add all tokens */
10410 table_ident = NULL;
10411 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
10413 tok_ident = TOK_IDENT;
10414 p = tcc_keywords;
10415 while (*p) {
10416 r = p;
10417 for(;;) {
10418 c = *r++;
10419 if (c == '\0')
10420 break;
10422 ts = tok_alloc(p, r - p - 1);
10423 p = r;
10426 /* we add dummy defines for some special macros to speed up tests
10427 and to have working defined() */
10428 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
10429 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
10430 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
10431 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
10433 /* standard defines */
10434 tcc_define_symbol(s, "__STDC__", NULL);
10435 tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
10436 #if defined(TCC_TARGET_I386)
10437 tcc_define_symbol(s, "__i386__", NULL);
10438 #endif
10439 #if defined(TCC_TARGET_X86_64)
10440 tcc_define_symbol(s, "__x86_64__", NULL);
10441 #endif
10442 #if defined(TCC_TARGET_ARM)
10443 tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
10444 tcc_define_symbol(s, "__arm_elf__", NULL);
10445 tcc_define_symbol(s, "__arm_elf", NULL);
10446 tcc_define_symbol(s, "arm_elf", NULL);
10447 tcc_define_symbol(s, "__arm__", NULL);
10448 tcc_define_symbol(s, "__arm", NULL);
10449 tcc_define_symbol(s, "arm", NULL);
10450 tcc_define_symbol(s, "__APCS_32__", NULL);
10451 #endif
10452 #ifdef TCC_TARGET_PE
10453 tcc_define_symbol(s, "_WIN32", NULL);
10454 #else
10455 tcc_define_symbol(s, "__unix__", NULL);
10456 tcc_define_symbol(s, "__unix", NULL);
10457 #if defined(__linux)
10458 tcc_define_symbol(s, "__linux__", NULL);
10459 tcc_define_symbol(s, "__linux", NULL);
10460 #endif
10461 #endif
10462 /* tiny C specific defines */
10463 tcc_define_symbol(s, "__TINYC__", NULL);
10465 /* tiny C & gcc defines */
10466 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned int");
10467 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "int");
10468 #ifdef TCC_TARGET_PE
10469 tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
10470 #else
10471 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
10472 #endif
10474 #ifndef TCC_TARGET_PE
10475 /* default library paths */
10476 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/local/lib");
10477 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/lib");
10478 tcc_add_library_path(s, CONFIG_SYSROOT "/lib");
10479 #endif
10481 /* no section zero */
10482 dynarray_add((void ***)&s->sections, &s->nb_sections, NULL);
10484 /* create standard sections */
10485 text_section = new_section(s, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
10486 data_section = new_section(s, ".data", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
10487 bss_section = new_section(s, ".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
10489 /* symbols are always generated for linking stage */
10490 symtab_section = new_symtab(s, ".symtab", SHT_SYMTAB, 0,
10491 ".strtab",
10492 ".hashtab", SHF_PRIVATE);
10493 strtab_section = symtab_section->link;
10495 /* private symbol table for dynamic symbols */
10496 s->dynsymtab_section = new_symtab(s, ".dynsymtab", SHT_SYMTAB, SHF_PRIVATE,
10497 ".dynstrtab",
10498 ".dynhashtab", SHF_PRIVATE);
10499 s->alacarte_link = 1;
10501 #ifdef CHAR_IS_UNSIGNED
10502 s->char_is_unsigned = 1;
10503 #endif
10504 #if defined(TCC_TARGET_PE) && 0
10505 /* XXX: currently the PE linker is not ready to support that */
10506 s->leading_underscore = 1;
10507 #endif
10509 #ifdef TCC_TARGET_X86_64
10510 s->jmp_table = NULL;
10511 s->got_table = NULL;
10512 #endif
10513 return s;
10516 void tcc_delete(TCCState *s1)
10518 int i;
10520 tcc_cleanup();
10522 /* free all sections */
10523 for(i = 1; i < s1->nb_sections; i++)
10524 free_section(s1->sections[i]);
10525 dynarray_reset(&s1->sections, &s1->nb_sections);
10527 for(i = 0; i < s1->nb_priv_sections; i++)
10528 free_section(s1->priv_sections[i]);
10529 dynarray_reset(&s1->priv_sections, &s1->nb_priv_sections);
10531 /* free any loaded DLLs */
10532 for ( i = 0; i < s1->nb_loaded_dlls; i++) {
10533 DLLReference *ref = s1->loaded_dlls[i];
10534 if ( ref->handle )
10535 dlclose(ref->handle);
10538 /* free loaded dlls array */
10539 dynarray_reset(&s1->loaded_dlls, &s1->nb_loaded_dlls);
10541 /* free library paths */
10542 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
10544 /* free include paths */
10545 dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
10546 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
10547 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
10549 #ifdef TCC_TARGET_X86_64
10550 tcc_free(s1->jmp_table);
10551 tcc_free(s1->got_table);
10552 #endif
10553 tcc_free(s1);
10556 int tcc_add_include_path(TCCState *s1, const char *pathname)
10558 char *pathname1;
10560 pathname1 = tcc_strdup(pathname);
10561 dynarray_add((void ***)&s1->include_paths, &s1->nb_include_paths, pathname1);
10562 return 0;
10565 int tcc_add_sysinclude_path(TCCState *s1, const char *pathname)
10567 char *pathname1;
10569 pathname1 = tcc_strdup(pathname);
10570 dynarray_add((void ***)&s1->sysinclude_paths, &s1->nb_sysinclude_paths, pathname1);
10571 return 0;
10574 static int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
10576 const char *ext;
10577 ElfW(Ehdr) ehdr;
10578 int fd, ret;
10579 BufferedFile *saved_file;
10581 /* find source file type with extension */
10582 ext = tcc_fileextension(filename);
10583 if (ext[0])
10584 ext++;
10586 /* open the file */
10587 saved_file = file;
10588 file = tcc_open(s1, filename);
10589 if (!file) {
10590 if (flags & AFF_PRINT_ERROR) {
10591 error_noabort("file '%s' not found", filename);
10593 ret = -1;
10594 goto fail1;
10597 if (flags & AFF_PREPROCESS) {
10598 ret = tcc_preprocess(s1);
10599 } else if (!ext[0] || !strcmp(ext, "c")) {
10600 /* C file assumed */
10601 ret = tcc_compile(s1);
10602 } else
10603 #ifdef CONFIG_TCC_ASM
10604 if (!strcmp(ext, "S")) {
10605 /* preprocessed assembler */
10606 ret = tcc_assemble(s1, 1);
10607 } else if (!strcmp(ext, "s")) {
10608 /* non preprocessed assembler */
10609 ret = tcc_assemble(s1, 0);
10610 } else
10611 #endif
10612 #ifdef TCC_TARGET_PE
10613 if (!strcmp(ext, "def")) {
10614 ret = pe_load_def_file(s1, file->fd);
10615 } else
10616 #endif
10618 fd = file->fd;
10619 /* assume executable format: auto guess file type */
10620 ret = read(fd, &ehdr, sizeof(ehdr));
10621 lseek(fd, 0, SEEK_SET);
10622 if (ret <= 0) {
10623 error_noabort("could not read header");
10624 goto fail;
10625 } else if (ret != sizeof(ehdr)) {
10626 goto try_load_script;
10629 if (ehdr.e_ident[0] == ELFMAG0 &&
10630 ehdr.e_ident[1] == ELFMAG1 &&
10631 ehdr.e_ident[2] == ELFMAG2 &&
10632 ehdr.e_ident[3] == ELFMAG3) {
10633 file->line_num = 0; /* do not display line number if error */
10634 if (ehdr.e_type == ET_REL) {
10635 ret = tcc_load_object_file(s1, fd, 0);
10636 } else if (ehdr.e_type == ET_DYN) {
10637 if (s1->output_type == TCC_OUTPUT_MEMORY) {
10638 #ifdef TCC_TARGET_PE
10639 ret = -1;
10640 #else
10641 void *h;
10642 h = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
10643 if (h)
10644 ret = 0;
10645 else
10646 ret = -1;
10647 #endif
10648 } else {
10649 ret = tcc_load_dll(s1, fd, filename,
10650 (flags & AFF_REFERENCED_DLL) != 0);
10652 } else {
10653 error_noabort("unrecognized ELF file");
10654 goto fail;
10656 } else if (memcmp((char *)&ehdr, ARMAG, 8) == 0) {
10657 file->line_num = 0; /* do not display line number if error */
10658 ret = tcc_load_archive(s1, fd);
10659 } else
10660 #ifdef TCC_TARGET_COFF
10661 if (*(uint16_t *)(&ehdr) == COFF_C67_MAGIC) {
10662 ret = tcc_load_coff(s1, fd);
10663 } else
10664 #endif
10665 #ifdef TCC_TARGET_PE
10666 if (pe_test_res_file(&ehdr, ret)) {
10667 ret = pe_load_res_file(s1, fd);
10668 } else
10669 #endif
10671 /* as GNU ld, consider it is an ld script if not recognized */
10672 try_load_script:
10673 ret = tcc_load_ldscript(s1);
10674 if (ret < 0) {
10675 error_noabort("unrecognized file type");
10676 goto fail;
10680 the_end:
10681 tcc_close(file);
10682 fail1:
10683 file = saved_file;
10684 return ret;
10685 fail:
10686 ret = -1;
10687 goto the_end;
10690 int tcc_add_file(TCCState *s, const char *filename)
10692 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR);
10695 int tcc_add_library_path(TCCState *s, const char *pathname)
10697 char *pathname1;
10699 pathname1 = tcc_strdup(pathname);
10700 dynarray_add((void ***)&s->library_paths, &s->nb_library_paths, pathname1);
10701 return 0;
10704 /* find and load a dll. Return non zero if not found */
10705 /* XXX: add '-rpath' option support ? */
10706 static int tcc_add_dll(TCCState *s, const char *filename, int flags)
10708 char buf[1024];
10709 int i;
10711 for(i = 0; i < s->nb_library_paths; i++) {
10712 snprintf(buf, sizeof(buf), "%s/%s",
10713 s->library_paths[i], filename);
10714 if (tcc_add_file_internal(s, buf, flags) == 0)
10715 return 0;
10717 return -1;
10720 /* the library name is the same as the argument of the '-l' option */
10721 int tcc_add_library(TCCState *s, const char *libraryname)
10723 char buf[1024];
10724 int i;
10726 /* first we look for the dynamic library if not static linking */
10727 if (!s->static_link) {
10728 #ifdef TCC_TARGET_PE
10729 snprintf(buf, sizeof(buf), "%s.def", libraryname);
10730 #else
10731 snprintf(buf, sizeof(buf), "lib%s.so", libraryname);
10732 #endif
10733 if (tcc_add_dll(s, buf, 0) == 0)
10734 return 0;
10737 /* then we look for the static library */
10738 for(i = 0; i < s->nb_library_paths; i++) {
10739 snprintf(buf, sizeof(buf), "%s/lib%s.a",
10740 s->library_paths[i], libraryname);
10741 if (tcc_add_file_internal(s, buf, 0) == 0)
10742 return 0;
10744 return -1;
10747 int tcc_add_symbol(TCCState *s, const char *name, unsigned long val)
10749 add_elf_sym(symtab_section, val, 0,
10750 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
10751 SHN_ABS, name);
10752 return 0;
10755 int tcc_set_output_type(TCCState *s, int output_type)
10757 char buf[1024];
10759 s->output_type = output_type;
10761 if (!s->nostdinc) {
10762 /* default include paths */
10763 /* XXX: reverse order needed if -isystem support */
10764 #ifndef TCC_TARGET_PE
10765 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/local/include");
10766 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/include");
10767 #endif
10768 snprintf(buf, sizeof(buf), "%s/include", tcc_lib_path);
10769 tcc_add_sysinclude_path(s, buf);
10770 #ifdef TCC_TARGET_PE
10771 snprintf(buf, sizeof(buf), "%s/include/winapi", tcc_lib_path);
10772 tcc_add_sysinclude_path(s, buf);
10773 #endif
10776 /* if bound checking, then add corresponding sections */
10777 #ifdef CONFIG_TCC_BCHECK
10778 if (do_bounds_check) {
10779 /* define symbol */
10780 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
10781 /* create bounds sections */
10782 bounds_section = new_section(s, ".bounds",
10783 SHT_PROGBITS, SHF_ALLOC);
10784 lbounds_section = new_section(s, ".lbounds",
10785 SHT_PROGBITS, SHF_ALLOC);
10787 #endif
10789 if (s->char_is_unsigned) {
10790 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
10793 /* add debug sections */
10794 if (do_debug) {
10795 /* stab symbols */
10796 stab_section = new_section(s, ".stab", SHT_PROGBITS, 0);
10797 stab_section->sh_entsize = sizeof(Stab_Sym);
10798 stabstr_section = new_section(s, ".stabstr", SHT_STRTAB, 0);
10799 put_elf_str(stabstr_section, "");
10800 stab_section->link = stabstr_section;
10801 /* put first entry */
10802 put_stabs("", 0, 0, 0, 0);
10805 /* add libc crt1/crti objects */
10806 #ifndef TCC_TARGET_PE
10807 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
10808 !s->nostdlib) {
10809 if (output_type != TCC_OUTPUT_DLL)
10810 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crt1.o");
10811 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crti.o");
10813 #endif
10815 #ifdef TCC_TARGET_PE
10816 snprintf(buf, sizeof(buf), "%s/lib", tcc_lib_path);
10817 tcc_add_library_path(s, buf);
10818 #endif
10820 return 0;
10823 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
10824 #define FD_INVERT 0x0002 /* invert value before storing */
10826 typedef struct FlagDef {
10827 uint16_t offset;
10828 uint16_t flags;
10829 const char *name;
10830 } FlagDef;
10832 static const FlagDef warning_defs[] = {
10833 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
10834 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
10835 { offsetof(TCCState, warn_error), 0, "error" },
10836 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
10837 "implicit-function-declaration" },
10840 static int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
10841 const char *name, int value)
10843 int i;
10844 const FlagDef *p;
10845 const char *r;
10847 r = name;
10848 if (r[0] == 'n' && r[1] == 'o' && r[2] == '-') {
10849 r += 3;
10850 value = !value;
10852 for(i = 0, p = flags; i < nb_flags; i++, p++) {
10853 if (!strcmp(r, p->name))
10854 goto found;
10856 return -1;
10857 found:
10858 if (p->flags & FD_INVERT)
10859 value = !value;
10860 *(int *)((uint8_t *)s + p->offset) = value;
10861 return 0;
10865 /* set/reset a warning */
10866 int tcc_set_warning(TCCState *s, const char *warning_name, int value)
10868 int i;
10869 const FlagDef *p;
10871 if (!strcmp(warning_name, "all")) {
10872 for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
10873 if (p->flags & WD_ALL)
10874 *(int *)((uint8_t *)s + p->offset) = 1;
10876 return 0;
10877 } else {
10878 return set_flag(s, warning_defs, countof(warning_defs),
10879 warning_name, value);
10883 static const FlagDef flag_defs[] = {
10884 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
10885 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
10886 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
10887 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
10890 /* set/reset a flag */
10891 int tcc_set_flag(TCCState *s, const char *flag_name, int value)
10893 return set_flag(s, flag_defs, countof(flag_defs),
10894 flag_name, value);
10897 #if !defined(LIBTCC)
10899 static int64_t getclock_us(void)
10901 #ifdef _WIN32
10902 struct _timeb tb;
10903 _ftime(&tb);
10904 return (tb.time * 1000LL + tb.millitm) * 1000LL;
10905 #else
10906 struct timeval tv;
10907 gettimeofday(&tv, NULL);
10908 return tv.tv_sec * 1000000LL + tv.tv_usec;
10909 #endif
10912 void help(void)
10914 printf("tcc version " TCC_VERSION " - Tiny C Compiler - Copyright (C) 2001-2006 Fabrice Bellard\n"
10915 "usage: tcc [-v] [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"
10916 " [-Wwarn] [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-soname name]\n"
10917 " [-static] [infile1 infile2...] [-run infile args...]\n"
10918 "\n"
10919 "General options:\n"
10920 " -v display current version, increase verbosity\n"
10921 " -c compile only - generate an object file\n"
10922 " -o outfile set output filename\n"
10923 " -Bdir set tcc internal library path\n"
10924 " -bench output compilation statistics\n"
10925 " -run run compiled source\n"
10926 " -fflag set or reset (with 'no-' prefix) 'flag' (see man page)\n"
10927 " -Wwarning set or reset (with 'no-' prefix) 'warning' (see man page)\n"
10928 " -w disable all warnings\n"
10929 "Preprocessor options:\n"
10930 " -E preprocess only\n"
10931 " -Idir add include path 'dir'\n"
10932 " -Dsym[=val] define 'sym' with value 'val'\n"
10933 " -Usym undefine 'sym'\n"
10934 "Linker options:\n"
10935 " -Ldir add library path 'dir'\n"
10936 " -llib link with dynamic or static library 'lib'\n"
10937 " -shared generate a shared library\n"
10938 " -soname set name for shared library to be used at runtime\n"
10939 " -static static linking\n"
10940 " -rdynamic export all global symbols to dynamic linker\n"
10941 " -r generate (relocatable) object file\n"
10942 "Debugger options:\n"
10943 " -g generate runtime debug info\n"
10944 #ifdef CONFIG_TCC_BCHECK
10945 " -b compile with built-in memory and bounds checker (implies -g)\n"
10946 #endif
10947 " -bt N show N callers in stack traces\n"
10951 #define TCC_OPTION_HAS_ARG 0x0001
10952 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
10954 typedef struct TCCOption {
10955 const char *name;
10956 uint16_t index;
10957 uint16_t flags;
10958 } TCCOption;
10960 enum {
10961 TCC_OPTION_HELP,
10962 TCC_OPTION_I,
10963 TCC_OPTION_D,
10964 TCC_OPTION_U,
10965 TCC_OPTION_L,
10966 TCC_OPTION_B,
10967 TCC_OPTION_l,
10968 TCC_OPTION_bench,
10969 TCC_OPTION_bt,
10970 TCC_OPTION_b,
10971 TCC_OPTION_g,
10972 TCC_OPTION_c,
10973 TCC_OPTION_static,
10974 TCC_OPTION_shared,
10975 TCC_OPTION_soname,
10976 TCC_OPTION_o,
10977 TCC_OPTION_r,
10978 TCC_OPTION_Wl,
10979 TCC_OPTION_W,
10980 TCC_OPTION_O,
10981 TCC_OPTION_m,
10982 TCC_OPTION_f,
10983 TCC_OPTION_nostdinc,
10984 TCC_OPTION_nostdlib,
10985 TCC_OPTION_print_search_dirs,
10986 TCC_OPTION_rdynamic,
10987 TCC_OPTION_run,
10988 TCC_OPTION_v,
10989 TCC_OPTION_w,
10990 TCC_OPTION_pipe,
10991 TCC_OPTION_E,
10994 static const TCCOption tcc_options[] = {
10995 { "h", TCC_OPTION_HELP, 0 },
10996 { "?", TCC_OPTION_HELP, 0 },
10997 { "I", TCC_OPTION_I, TCC_OPTION_HAS_ARG },
10998 { "D", TCC_OPTION_D, TCC_OPTION_HAS_ARG },
10999 { "U", TCC_OPTION_U, TCC_OPTION_HAS_ARG },
11000 { "L", TCC_OPTION_L, TCC_OPTION_HAS_ARG },
11001 { "B", TCC_OPTION_B, TCC_OPTION_HAS_ARG },
11002 { "l", TCC_OPTION_l, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11003 { "bench", TCC_OPTION_bench, 0 },
11004 { "bt", TCC_OPTION_bt, TCC_OPTION_HAS_ARG },
11005 #ifdef CONFIG_TCC_BCHECK
11006 { "b", TCC_OPTION_b, 0 },
11007 #endif
11008 { "g", TCC_OPTION_g, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11009 { "c", TCC_OPTION_c, 0 },
11010 { "static", TCC_OPTION_static, 0 },
11011 { "shared", TCC_OPTION_shared, 0 },
11012 { "soname", TCC_OPTION_soname, TCC_OPTION_HAS_ARG },
11013 { "o", TCC_OPTION_o, TCC_OPTION_HAS_ARG },
11014 { "run", TCC_OPTION_run, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11015 { "rdynamic", TCC_OPTION_rdynamic, 0 },
11016 { "r", TCC_OPTION_r, 0 },
11017 { "Wl,", TCC_OPTION_Wl, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11018 { "W", TCC_OPTION_W, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11019 { "O", TCC_OPTION_O, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11020 { "m", TCC_OPTION_m, TCC_OPTION_HAS_ARG },
11021 { "f", TCC_OPTION_f, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11022 { "nostdinc", TCC_OPTION_nostdinc, 0 },
11023 { "nostdlib", TCC_OPTION_nostdlib, 0 },
11024 { "print-search-dirs", TCC_OPTION_print_search_dirs, 0 },
11025 { "v", TCC_OPTION_v, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11026 { "w", TCC_OPTION_w, 0 },
11027 { "pipe", TCC_OPTION_pipe, 0},
11028 { "E", TCC_OPTION_E, 0},
11029 { NULL },
11032 /* convert 'str' into an array of space separated strings */
11033 static int expand_args(char ***pargv, const char *str)
11035 const char *s1;
11036 char **argv, *arg;
11037 int argc, len;
11039 argc = 0;
11040 argv = NULL;
11041 for(;;) {
11042 while (is_space(*str))
11043 str++;
11044 if (*str == '\0')
11045 break;
11046 s1 = str;
11047 while (*str != '\0' && !is_space(*str))
11048 str++;
11049 len = str - s1;
11050 arg = tcc_malloc(len + 1);
11051 memcpy(arg, s1, len);
11052 arg[len] = '\0';
11053 dynarray_add((void ***)&argv, &argc, arg);
11055 *pargv = argv;
11056 return argc;
11059 static char **files;
11060 static int nb_files, nb_libraries;
11061 static int multiple_files;
11062 static int print_search_dirs;
11063 static int output_type;
11064 static int reloc_output;
11065 static const char *outfile;
11067 int parse_args(TCCState *s, int argc, char **argv)
11069 int optind;
11070 const TCCOption *popt;
11071 const char *optarg, *p1, *r1;
11072 char *r;
11074 optind = 0;
11075 while (optind < argc) {
11077 r = argv[optind++];
11078 if (r[0] != '-' || r[1] == '\0') {
11079 /* add a new file */
11080 dynarray_add((void ***)&files, &nb_files, r);
11081 if (!multiple_files) {
11082 optind--;
11083 /* argv[0] will be this file */
11084 break;
11086 } else {
11087 /* find option in table (match only the first chars */
11088 popt = tcc_options;
11089 for(;;) {
11090 p1 = popt->name;
11091 if (p1 == NULL)
11092 error("invalid option -- '%s'", r);
11093 r1 = r + 1;
11094 for(;;) {
11095 if (*p1 == '\0')
11096 goto option_found;
11097 if (*r1 != *p1)
11098 break;
11099 p1++;
11100 r1++;
11102 popt++;
11104 option_found:
11105 if (popt->flags & TCC_OPTION_HAS_ARG) {
11106 if (*r1 != '\0' || (popt->flags & TCC_OPTION_NOSEP)) {
11107 optarg = r1;
11108 } else {
11109 if (optind >= argc)
11110 error("argument to '%s' is missing", r);
11111 optarg = argv[optind++];
11113 } else {
11114 if (*r1 != '\0')
11115 return 0;
11116 optarg = NULL;
11119 switch(popt->index) {
11120 case TCC_OPTION_HELP:
11121 return 0;
11123 case TCC_OPTION_I:
11124 if (tcc_add_include_path(s, optarg) < 0)
11125 error("too many include paths");
11126 break;
11127 case TCC_OPTION_D:
11129 char *sym, *value;
11130 sym = (char *)optarg;
11131 value = strchr(sym, '=');
11132 if (value) {
11133 *value = '\0';
11134 value++;
11136 tcc_define_symbol(s, sym, value);
11138 break;
11139 case TCC_OPTION_U:
11140 tcc_undefine_symbol(s, optarg);
11141 break;
11142 case TCC_OPTION_L:
11143 tcc_add_library_path(s, optarg);
11144 break;
11145 case TCC_OPTION_B:
11146 /* set tcc utilities path (mainly for tcc development) */
11147 tcc_lib_path = optarg;
11148 break;
11149 case TCC_OPTION_l:
11150 dynarray_add((void ***)&files, &nb_files, r);
11151 nb_libraries++;
11152 break;
11153 case TCC_OPTION_bench:
11154 do_bench = 1;
11155 break;
11156 case TCC_OPTION_bt:
11157 num_callers = atoi(optarg);
11158 break;
11159 #ifdef CONFIG_TCC_BCHECK
11160 case TCC_OPTION_b:
11161 do_bounds_check = 1;
11162 do_debug = 1;
11163 break;
11164 #endif
11165 case TCC_OPTION_g:
11166 do_debug = 1;
11167 break;
11168 case TCC_OPTION_c:
11169 multiple_files = 1;
11170 output_type = TCC_OUTPUT_OBJ;
11171 break;
11172 case TCC_OPTION_static:
11173 s->static_link = 1;
11174 break;
11175 case TCC_OPTION_shared:
11176 output_type = TCC_OUTPUT_DLL;
11177 break;
11178 case TCC_OPTION_soname:
11179 s->soname = optarg;
11180 break;
11181 case TCC_OPTION_o:
11182 multiple_files = 1;
11183 outfile = optarg;
11184 break;
11185 case TCC_OPTION_r:
11186 /* generate a .o merging several output files */
11187 reloc_output = 1;
11188 output_type = TCC_OUTPUT_OBJ;
11189 break;
11190 case TCC_OPTION_nostdinc:
11191 s->nostdinc = 1;
11192 break;
11193 case TCC_OPTION_nostdlib:
11194 s->nostdlib = 1;
11195 break;
11196 case TCC_OPTION_print_search_dirs:
11197 print_search_dirs = 1;
11198 break;
11199 case TCC_OPTION_run:
11201 int argc1;
11202 char **argv1;
11203 argc1 = expand_args(&argv1, optarg);
11204 if (argc1 > 0) {
11205 parse_args(s, argc1, argv1);
11207 multiple_files = 0;
11208 output_type = TCC_OUTPUT_MEMORY;
11210 break;
11211 case TCC_OPTION_v:
11212 do {
11213 if (0 == verbose++)
11214 printf("tcc version %s\n", TCC_VERSION);
11215 } while (*optarg++ == 'v');
11216 break;
11217 case TCC_OPTION_f:
11218 if (tcc_set_flag(s, optarg, 1) < 0 && s->warn_unsupported)
11219 goto unsupported_option;
11220 break;
11221 case TCC_OPTION_W:
11222 if (tcc_set_warning(s, optarg, 1) < 0 &&
11223 s->warn_unsupported)
11224 goto unsupported_option;
11225 break;
11226 case TCC_OPTION_w:
11227 s->warn_none = 1;
11228 break;
11229 case TCC_OPTION_rdynamic:
11230 s->rdynamic = 1;
11231 break;
11232 case TCC_OPTION_Wl:
11234 const char *p;
11235 if (strstart(optarg, "-Ttext,", &p)) {
11236 s->text_addr = strtoul(p, NULL, 16);
11237 s->has_text_addr = 1;
11238 } else if (strstart(optarg, "--oformat,", &p)) {
11239 if (strstart(p, "elf32-", NULL)) {
11240 s->output_format = TCC_OUTPUT_FORMAT_ELF;
11241 } else if (!strcmp(p, "binary")) {
11242 s->output_format = TCC_OUTPUT_FORMAT_BINARY;
11243 } else
11244 #ifdef TCC_TARGET_COFF
11245 if (!strcmp(p, "coff")) {
11246 s->output_format = TCC_OUTPUT_FORMAT_COFF;
11247 } else
11248 #endif
11250 error("target %s not found", p);
11252 } else {
11253 error("unsupported linker option '%s'", optarg);
11256 break;
11257 case TCC_OPTION_E:
11258 output_type = TCC_OUTPUT_PREPROCESS;
11259 break;
11260 default:
11261 if (s->warn_unsupported) {
11262 unsupported_option:
11263 warning("unsupported option '%s'", r);
11265 break;
11269 return optind + 1;
11272 int main(int argc, char **argv)
11274 int i;
11275 TCCState *s;
11276 int nb_objfiles, ret, optind;
11277 char objfilename[1024];
11278 int64_t start_time = 0;
11280 #ifdef _WIN32
11281 tcc_lib_path = w32_tcc_lib_path();
11282 #endif
11284 s = tcc_new();
11285 output_type = TCC_OUTPUT_EXE;
11286 outfile = NULL;
11287 multiple_files = 1;
11288 files = NULL;
11289 nb_files = 0;
11290 nb_libraries = 0;
11291 reloc_output = 0;
11292 print_search_dirs = 0;
11293 ret = 0;
11295 optind = parse_args(s, argc - 1, argv + 1);
11296 if (print_search_dirs) {
11297 /* enough for Linux kernel */
11298 printf("install: %s/\n", tcc_lib_path);
11299 return 0;
11301 if (optind == 0 || nb_files == 0) {
11302 if (optind && verbose)
11303 return 0;
11304 help();
11305 return 1;
11308 nb_objfiles = nb_files - nb_libraries;
11310 /* if outfile provided without other options, we output an
11311 executable */
11312 if (outfile && output_type == TCC_OUTPUT_MEMORY)
11313 output_type = TCC_OUTPUT_EXE;
11315 /* check -c consistency : only single file handled. XXX: checks file type */
11316 if (output_type == TCC_OUTPUT_OBJ && !reloc_output) {
11317 /* accepts only a single input file */
11318 if (nb_objfiles != 1)
11319 error("cannot specify multiple files with -c");
11320 if (nb_libraries != 0)
11321 error("cannot specify libraries with -c");
11325 if (output_type == TCC_OUTPUT_PREPROCESS) {
11326 if (!outfile) {
11327 s->outfile = stdout;
11328 } else {
11329 s->outfile = fopen(outfile, "w");
11330 if (!s->outfile)
11331 error("could not open '%s", outfile);
11333 } else if (output_type != TCC_OUTPUT_MEMORY) {
11334 if (!outfile) {
11335 /* compute default outfile name */
11336 char *ext;
11337 const char *name =
11338 strcmp(files[0], "-") == 0 ? "a" : tcc_basename(files[0]);
11339 pstrcpy(objfilename, sizeof(objfilename), name);
11340 ext = tcc_fileextension(objfilename);
11341 #ifdef TCC_TARGET_PE
11342 if (output_type == TCC_OUTPUT_DLL)
11343 strcpy(ext, ".dll");
11344 else
11345 if (output_type == TCC_OUTPUT_EXE)
11346 strcpy(ext, ".exe");
11347 else
11348 #endif
11349 if (output_type == TCC_OUTPUT_OBJ && !reloc_output && *ext)
11350 strcpy(ext, ".o");
11351 else
11352 pstrcpy(objfilename, sizeof(objfilename), "a.out");
11353 outfile = objfilename;
11357 if (do_bench) {
11358 start_time = getclock_us();
11361 tcc_set_output_type(s, output_type);
11363 /* compile or add each files or library */
11364 for(i = 0; i < nb_files && ret == 0; i++) {
11365 const char *filename;
11367 filename = files[i];
11368 if (output_type == TCC_OUTPUT_PREPROCESS) {
11369 if (tcc_add_file_internal(s, filename,
11370 AFF_PRINT_ERROR | AFF_PREPROCESS) < 0)
11371 ret = 1;
11372 } else if (filename[0] == '-' && filename[1]) {
11373 if (tcc_add_library(s, filename + 2) < 0)
11374 error("cannot find %s", filename);
11375 } else {
11376 if (1 == verbose)
11377 printf("-> %s\n", filename);
11378 if (tcc_add_file(s, filename) < 0)
11379 ret = 1;
11383 /* free all files */
11384 tcc_free(files);
11386 if (ret)
11387 goto the_end;
11389 if (do_bench) {
11390 double total_time;
11391 total_time = (double)(getclock_us() - start_time) / 1000000.0;
11392 if (total_time < 0.001)
11393 total_time = 0.001;
11394 if (total_bytes < 1)
11395 total_bytes = 1;
11396 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
11397 tok_ident - TOK_IDENT, total_lines, total_bytes,
11398 total_time, (int)(total_lines / total_time),
11399 total_bytes / total_time / 1000000.0);
11402 if (s->output_type == TCC_OUTPUT_PREPROCESS) {
11403 if (outfile)
11404 fclose(s->outfile);
11405 } else if (s->output_type == TCC_OUTPUT_MEMORY) {
11406 ret = tcc_run(s, argc - optind, argv + optind);
11407 } else
11408 ret = tcc_output_file(s, outfile) ? 1 : 0;
11409 the_end:
11410 /* XXX: cannot do it with bound checking because of the malloc hooks */
11411 if (!do_bounds_check)
11412 tcc_delete(s);
11414 #ifdef MEM_DEBUG
11415 if (do_bench) {
11416 printf("memory: %d bytes, max = %d bytes\n", mem_cur_size, mem_max_size);
11418 #endif
11419 return ret;
11422 #endif