2 * TCC - Tiny C Compiler
4 * Copyright (c) 2001, 2002, 2003 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
36 #include <sys/timeb.h>
40 #include <sys/ucontext.h>
44 #ifndef CONFIG_TCC_STATIC
52 /* preprocessor debug */
54 /* include file debug */
62 /* target selection */
63 //#define TCC_TARGET_I386 /* i386 code generator */
64 //#define TCC_TARGET_ARM /* ARMv4 code generator */
66 /* default target is I386 */
67 #if !defined(TCC_TARGET_I386) && !defined(TCC_TARGET_ARM)
68 #define TCC_TARGET_I386
71 #if !defined(WIN32) && !defined(TCC_UCLIBC) && !defined(TCC_TARGET_ARM)
72 #define CONFIG_TCC_BCHECK /* enable bound checking code */
75 /* define it to include assembler support */
76 #if !defined(TCC_TARGET_ARM)
77 #define CONFIG_TCC_ASM
80 /* path to find crt1.o, crti.o and crtn.o. Only needed when generating
81 executables or dlls */
82 #define CONFIG_TCC_CRT_PREFIX "/usr/lib"
84 #define INCLUDE_STACK_SIZE 32
85 #define IFDEF_STACK_SIZE 64
86 #define VSTACK_SIZE 64
87 #define STRING_MAX_SIZE 1024
89 #define TOK_HASH_SIZE 2048 /* must be a power of two */
90 #define TOK_ALLOC_INCR 512 /* must be a power of two */
91 #define TOK_STR_ALLOC_INCR_BITS 6
92 #define TOK_STR_ALLOC_INCR (1 << TOK_STR_ALLOC_INCR_BITS)
93 #define TOK_MAX_SIZE 4 /* token max size in int unit when stored in string */
95 /* token symbol management */
96 typedef struct TokenSym
{
97 struct TokenSym
*hash_next
;
98 struct Sym
*sym_define
; /* direct pointer to define */
99 struct Sym
*sym_label
; /* direct pointer to label */
100 struct Sym
*sym_struct
; /* direct pointer to structure */
101 struct Sym
*sym_identifier
; /* direct pointer to identifier */
102 int tok
; /* token number */
107 typedef struct CString
{
108 int size
; /* size in bytes */
109 void *data
; /* either 'char *' or 'int *' */
111 void *data_allocated
; /* if non NULL, data has been malloced */
114 /* type definition */
115 typedef struct CType
{
121 typedef union CValue
{
127 unsigned int ul
; /* address (should be unsigned long on 64 bit cpu) */
129 unsigned long long ull
;
130 struct CString
*cstr
;
136 typedef struct SValue
{
137 CType type
; /* type */
138 unsigned short r
; /* register + flags */
139 unsigned short r2
; /* second register, used for 'long long'
140 type. If not used, set to VT_CONST */
141 CValue c
; /* constant, if VT_CONST */
142 struct Sym
*sym
; /* symbol, if (VT_SYM | VT_CONST) */
145 /* symbol management */
147 int v
; /* symbol token */
148 int r
; /* associated register */
149 int c
; /* associated number */
150 CType type
; /* associated type */
151 struct Sym
*next
; /* next related symbol */
152 struct Sym
*prev
; /* prev symbol in stack */
153 struct Sym
*prev_tok
; /* previous symbol for this token */
156 /* section definition */
157 /* XXX: use directly ELF structure for parameters ? */
158 /* special flag to indicate that the section should not be linked to
160 #define SHF_PRIVATE 0x80000000
162 typedef struct Section
{
163 unsigned long data_offset
; /* current data offset */
164 unsigned char *data
; /* section data */
165 unsigned long data_allocated
; /* used for realloc() handling */
166 int sh_name
; /* elf section name (only used during output) */
167 int sh_num
; /* elf section number */
168 int sh_type
; /* elf section type */
169 int sh_flags
; /* elf section flags */
170 int sh_info
; /* elf section info */
171 int sh_addralign
; /* elf section alignment */
172 int sh_entsize
; /* elf entry size */
173 unsigned long sh_size
; /* section size (only used during output) */
174 unsigned long sh_addr
; /* address at which the section is relocated */
175 unsigned long sh_offset
; /* address at which the section is relocated */
176 int nb_hashed_syms
; /* used to resize the hash table */
177 struct Section
*link
; /* link to another section */
178 struct Section
*reloc
; /* corresponding section for relocation, if any */
179 struct Section
*hash
; /* hash table for symbols */
180 struct Section
*next
;
181 char name
[1]; /* section name */
184 typedef struct DLLReference
{
189 /* GNUC attribute definition */
190 typedef struct AttributeDef
{
193 unsigned char func_call
; /* FUNC_CDECL or FUNC_STDCALL */
196 #define SYM_STRUCT 0x40000000 /* struct/union/enum symbol space */
197 #define SYM_FIELD 0x20000000 /* struct/union field symbol space */
198 #define SYM_FIRST_ANOM (1 << (31 - VT_STRUCT_SHIFT)) /* first anonymous sym */
200 /* stored in 'Sym.c' field */
201 #define FUNC_NEW 1 /* ansi function prototype */
202 #define FUNC_OLD 2 /* old function prototype */
203 #define FUNC_ELLIPSIS 3 /* ansi function prototype with ... */
205 /* stored in 'Sym.r' field */
206 #define FUNC_CDECL 0 /* standard c call */
207 #define FUNC_STDCALL 1 /* pascal c call */
209 /* field 'Sym.t' for macros */
210 #define MACRO_OBJ 0 /* object like macro */
211 #define MACRO_FUNC 1 /* function like macro */
213 /* field 'Sym.r' for C labels */
214 #define LABEL_DEFINED 0 /* label is defined */
215 #define LABEL_FORWARD 1 /* label is forward defined */
216 #define LABEL_DECLARED 2 /* label is declared but never used */
218 /* type_decl() types */
219 #define TYPE_ABSTRACT 1 /* type without variable */
220 #define TYPE_DIRECT 2 /* type with variable */
222 #define IO_BUF_SIZE 8192
224 typedef struct BufferedFile
{
228 int line_num
; /* current line number - here to simplify code */
229 int ifndef_macro
; /* #ifndef macro / #endif search */
230 int ifndef_macro_saved
; /* saved ifndef_macro */
231 int *ifdef_stack_ptr
; /* ifdef_stack value at the start of the file */
232 char inc_type
; /* type of include */
233 char inc_filename
[512]; /* filename specified by the user */
234 char filename
[1024]; /* current filename - here to simplify code */
235 unsigned char buffer
[IO_BUF_SIZE
+ 1]; /* extra size for CH_EOB char */
238 #define CH_EOB '\\' /* end of buffer or '\0' char in file */
239 #define CH_EOF (-1) /* end of file */
241 /* parsing state (used to save parser state to reparse part of the
242 source several times) */
243 typedef struct ParseState
{
250 /* used to record tokens */
251 typedef struct TokenString
{
258 /* include file cache, used to find files faster and also to eliminate
259 inclusion if the include file is protected by #ifndef ... #endif */
260 typedef struct CachedInclude
{
262 char type
; /* '"' or '>' to give include type */
263 char filename
[1]; /* path specified in #include */
267 static struct BufferedFile
*file
;
270 static CString tokcstr
; /* current parsed string, if any */
271 /* additional informations about token */
272 static int tok_flags
;
273 #define TOK_FLAG_BOL 0x0001 /* beginning of line before */
274 #define TOK_FLAG_BOF 0x0002 /* beginning of file before */
275 #define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */
277 static int *macro_ptr
, *macro_ptr_allocated
;
278 static int *unget_saved_macro_ptr
;
279 static int unget_saved_buffer
[TOK_MAX_SIZE
+ 1];
280 static int unget_buffer_enabled
;
281 static int parse_flags
;
282 #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
283 #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
284 #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
285 token. line feed is also
288 static Section
*text_section
, *data_section
, *bss_section
; /* predefined sections */
289 static Section
*cur_text_section
; /* current section where function code is
291 /* bound check related sections */
292 static Section
*bounds_section
; /* contains global data bound description */
293 static Section
*lbounds_section
; /* contains local data bound description */
294 /* symbol sections */
295 static Section
*symtab_section
, *strtab_section
;
298 static Section
*stab_section
, *stabstr_section
;
300 /* loc : local variable index
301 ind : output code index
303 anon_sym: anonymous symbol index
305 static int rsym
, anon_sym
, ind
, loc
;
306 /* expression generation modifiers */
307 static int const_wanted
; /* true if constant wanted */
308 static int nocode_wanted
; /* true if no code generation wanted for an expression */
309 static int global_expr
; /* true if compound literals must be allocated
310 globally (used during initializers parsing */
311 static CType func_vt
; /* current function return type (used by return
314 static int last_line_num
, last_ind
, func_ind
; /* debug last line number and pc */
315 static int tok_ident
;
316 static TokenSym
**table_ident
;
317 static TokenSym
*hash_ident
[TOK_HASH_SIZE
];
318 static char token_buf
[STRING_MAX_SIZE
+ 1];
319 static char *funcname
;
320 static Sym
*global_stack
, *local_stack
;
321 static Sym
*define_stack
;
322 static Sym
*global_label_stack
, *local_label_stack
;
324 static SValue vstack
[VSTACK_SIZE
], *vtop
;
325 /* some predefined types */
326 static CType char_pointer_type
, func_old_type
, int_type
;
327 /* true if isid(c) || isnum(c) */
328 static unsigned char isidnum_table
[256];
330 /* compile with debug symbol (and use them if error during execution) */
331 static int do_debug
= 0;
333 /* compile with built-in memory and bounds checker */
334 static int do_bounds_check
= 0;
336 /* display benchmark infos */
338 static int do_bench
= 0;
340 static int total_lines
;
341 static int total_bytes
;
343 /* use GNU C extensions */
344 static int gnu_ext
= 1;
346 /* use Tiny C extensions */
347 static int tcc_ext
= 1;
349 /* max number of callers shown if error */
350 static int num_callers
= 6;
351 static const char **rt_bound_error_msg
;
353 /* XXX: get rid of this ASAP */
354 static struct TCCState
*tcc_state
;
356 /* give the path of the tcc libraries */
357 static const char *tcc_lib_path
= CONFIG_TCC_LIBDIR
"/tcc";
362 BufferedFile
**include_stack_ptr
;
363 int *ifdef_stack_ptr
;
365 /* include file handling */
366 char **include_paths
;
367 int nb_include_paths
;
368 char **sysinclude_paths
;
369 int nb_sysinclude_paths
;
370 CachedInclude
**cached_includes
;
371 int nb_cached_includes
;
373 char **library_paths
;
374 int nb_library_paths
;
376 /* array of all loaded dlls (including those referenced by loaded
378 DLLReference
**loaded_dlls
;
383 int nb_sections
; /* number of sections, including first dummy section */
388 unsigned long *got_offsets
;
390 /* give the correspondance from symtab indexes to dynsym indexes */
391 int *symtab_to_dynsym
;
393 /* temporary dynamic symbol sections (for dll loading) */
394 Section
*dynsymtab_section
;
395 /* exported dynamic symbol section */
398 int nostdinc
; /* if true, no standard headers are added */
399 int nostdlib
; /* if true, no standard libraries are added */
401 /* if true, static linking is performed */
404 /* if true, all symbols are exported */
407 /* if true, only link in referenced objects from archive */
410 /* C language options */
411 int char_is_unsigned
;
413 /* warning switches */
414 int warn_write_strings
;
415 int warn_unsupported
;
418 int warn_implicit_function_declaration
;
422 void (*error_func
)(void *opaque
, const char *msg
);
423 int error_set_jmp_enabled
;
424 jmp_buf error_jmp_buf
;
427 /* tiny assembler state */
430 /* see include_stack_ptr */
431 BufferedFile
*include_stack
[INCLUDE_STACK_SIZE
];
433 /* see ifdef_stack_ptr */
434 int ifdef_stack
[IFDEF_STACK_SIZE
];
437 /* The current value can be: */
438 #define VT_VALMASK 0x00ff
439 #define VT_CONST 0x00f0 /* constant in vc
440 (must be first non register value) */
441 #define VT_LLOCAL 0x00f1 /* lvalue, offset on stack */
442 #define VT_LOCAL 0x00f2 /* offset on stack */
443 #define VT_CMP 0x00f3 /* the value is stored in processor flags (in vc) */
444 #define VT_JMP 0x00f4 /* value is the consequence of jmp true (even) */
445 #define VT_JMPI 0x00f5 /* value is the consequence of jmp false (odd) */
446 #define VT_LVAL 0x0100 /* var is an lvalue */
447 #define VT_SYM 0x0200 /* a symbol value is added */
448 #define VT_MUSTCAST 0x0400 /* value must be casted to be correct (used for
449 char/short stored in integer registers) */
450 #define VT_MUSTBOUND 0x0800 /* bound checking must be done before
451 dereferencing value */
452 #define VT_BOUNDED 0x8000 /* value is bounded. The address of the
453 bounding function call point is in vc */
454 #define VT_LVAL_BYTE 0x1000 /* lvalue is a byte */
455 #define VT_LVAL_SHORT 0x2000 /* lvalue is a short */
456 #define VT_LVAL_UNSIGNED 0x4000 /* lvalue is unsigned */
457 #define VT_LVAL_TYPE (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
460 #define VT_INT 0 /* integer type */
461 #define VT_BYTE 1 /* signed byte type */
462 #define VT_SHORT 2 /* short type */
463 #define VT_VOID 3 /* void type */
464 #define VT_PTR 4 /* pointer */
465 #define VT_ENUM 5 /* enum definition */
466 #define VT_FUNC 6 /* function type */
467 #define VT_STRUCT 7 /* struct/union definition */
468 #define VT_FLOAT 8 /* IEEE float */
469 #define VT_DOUBLE 9 /* IEEE double */
470 #define VT_LDOUBLE 10 /* IEEE long double */
471 #define VT_BOOL 11 /* ISOC99 boolean type */
472 #define VT_LLONG 12 /* 64 bit integer */
473 #define VT_LONG 13 /* long integer (NEVER USED as type, only
475 #define VT_BTYPE 0x000f /* mask for basic type */
476 #define VT_UNSIGNED 0x0010 /* unsigned type */
477 #define VT_ARRAY 0x0020 /* array type (also has VT_PTR) */
478 #define VT_BITFIELD 0x0040 /* bitfield modifier */
479 #define VT_CONSTANT 0x0800 /* const modifier */
480 #define VT_VOLATILE 0x1000 /* volatile modifier */
481 #define VT_SIGNED 0x2000 /* signed type */
484 #define VT_EXTERN 0x00000080 /* extern definition */
485 #define VT_STATIC 0x00000100 /* static variable */
486 #define VT_TYPEDEF 0x00000200 /* typedef definition */
487 #define VT_INLINE 0x00000400 /* inline definition */
489 #define VT_STRUCT_SHIFT 16 /* shift for bitfield shift values */
491 /* type mask (except storage) */
492 #define VT_STORAGE (VT_EXTERN | VT_STATIC | VT_TYPEDEF | VT_INLINE)
493 #define VT_TYPE (~(VT_STORAGE))
497 /* warning: the following compare tokens depend on i386 asm code */
509 #define TOK_LAND 0xa0
513 #define TOK_MID 0xa3 /* inc/dec, to void constant */
515 #define TOK_UDIV 0xb0 /* unsigned division */
516 #define TOK_UMOD 0xb1 /* unsigned modulo */
517 #define TOK_PDIV 0xb2 /* fast division with undefined rounding for pointers */
518 #define TOK_CINT 0xb3 /* number in tokc */
519 #define TOK_CCHAR 0xb4 /* char constant in tokc */
520 #define TOK_STR 0xb5 /* pointer to string in tokc */
521 #define TOK_TWOSHARPS 0xb6 /* ## preprocessing token */
522 #define TOK_LCHAR 0xb7
523 #define TOK_LSTR 0xb8
524 #define TOK_CFLOAT 0xb9 /* float constant */
525 #define TOK_LINENUM 0xba /* line number info */
526 #define TOK_CDOUBLE 0xc0 /* double constant */
527 #define TOK_CLDOUBLE 0xc1 /* long double constant */
528 #define TOK_UMULL 0xc2 /* unsigned 32x32 -> 64 mul */
529 #define TOK_ADDC1 0xc3 /* add with carry generation */
530 #define TOK_ADDC2 0xc4 /* add with carry use */
531 #define TOK_SUBC1 0xc5 /* add with carry generation */
532 #define TOK_SUBC2 0xc6 /* add with carry use */
533 #define TOK_CUINT 0xc8 /* unsigned int constant */
534 #define TOK_CLLONG 0xc9 /* long long constant */
535 #define TOK_CULLONG 0xca /* unsigned long long constant */
536 #define TOK_ARROW 0xcb
537 #define TOK_DOTS 0xcc /* three dots */
538 #define TOK_SHR 0xcd /* unsigned shift right */
539 #define TOK_PPNUM 0xce /* preprocessor number */
541 #define TOK_SHL 0x01 /* shift left */
542 #define TOK_SAR 0x02 /* signed shift right */
544 /* assignement operators : normal operator or 0x80 */
545 #define TOK_A_MOD 0xa5
546 #define TOK_A_AND 0xa6
547 #define TOK_A_MUL 0xaa
548 #define TOK_A_ADD 0xab
549 #define TOK_A_SUB 0xad
550 #define TOK_A_DIV 0xaf
551 #define TOK_A_XOR 0xde
552 #define TOK_A_OR 0xfc
553 #define TOK_A_SHL 0x81
554 #define TOK_A_SAR 0x82
557 #define offsetof(type, field) ((size_t) &((type *)0)->field)
561 #define countof(tab) (sizeof(tab) / sizeof((tab)[0]))
564 /* WARNING: the content of this string encodes token numbers */
565 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";
567 #define TOK_EOF (-1) /* end of file */
568 #define TOK_LINEFEED 10 /* line feed */
570 /* all identificators and strings have token above that */
571 #define TOK_IDENT 256
573 /* only used for i386 asm opcodes definitions */
574 #define DEF_ASM(x) DEF(TOK_ASM_ ## x, #x)
577 DEF(TOK_ASM_ ## x ## b, #x "b") \
578 DEF(TOK_ASM_ ## x ## w, #x "w") \
579 DEF(TOK_ASM_ ## x ## l, #x "l") \
580 DEF(TOK_ASM_ ## x, #x)
583 DEF(TOK_ASM_ ## x ## w, #x "w") \
584 DEF(TOK_ASM_ ## x ## l, #x "l") \
585 DEF(TOK_ASM_ ## x, #x)
588 DEF(TOK_ASM_ ## f ## x ## s, "f" #x "s") \
589 DEF(TOK_ASM_ ## fi ## x ## l, "fi" #x "l") \
590 DEF(TOK_ASM_ ## f ## x ## l, "f" #x "l") \
591 DEF(TOK_ASM_ ## fi ## x ## s, "fi" #x "s")
594 DEF(TOK_ASM_ ## f ## x, "f" #x ) \
595 DEF(TOK_ASM_ ## f ## x ## p, "f" #x "p") \
598 #define DEF_ASMTEST(x) \
630 #define TOK_ASM_int TOK_INT
633 TOK_LAST
= TOK_IDENT
- 1,
634 #define DEF(id, str) id,
639 static const char tcc_keywords
[] =
640 #define DEF(id, str) str "\0"
645 #define TOK_UIDENT TOK_DEFINE
648 #define snprintf _snprintf
649 #define vsnprintf _vsnprintf
652 #if defined(WIN32) || defined(TCC_UCLIBC) || defined(__FreeBSD__)
653 /* currently incorrect */
654 long double strtold(const char *nptr
, char **endptr
)
656 return (long double)strtod(nptr
, endptr
);
658 float strtof(const char *nptr
, char **endptr
)
660 return (float)strtod(nptr
, endptr
);
663 /* XXX: need to define this to use them in non ISOC99 context */
664 extern float strtof (const char *__nptr
, char **__endptr
);
665 extern long double strtold (const char *__nptr
, char **__endptr
);
668 static char *pstrcpy(char *buf
, int buf_size
, const char *s
);
669 static char *pstrcat(char *buf
, int buf_size
, const char *s
);
671 static void next(void);
672 static void next_nomacro(void);
673 static void parse_expr_type(CType
*type
);
674 static void expr_type(CType
*type
);
675 static void unary_type(CType
*type
);
676 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
677 int case_reg
, int is_expr
);
678 static int expr_const(void);
679 static void expr_eq(void);
680 static void gexpr(void);
681 static void decl(int l
);
682 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
683 int first
, int size_only
);
684 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
685 int has_init
, int v
, int scope
);
687 void gv2(int rc1
, int rc2
);
688 void move_reg(int r
, int s
);
689 void save_regs(int n
);
690 void save_reg(int r
);
695 int get_reg_ex(int rc
,int rc2
);
697 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
698 const int *macro_str
, int can_read_stream
);
699 int save_reg_forced(int r
);
701 void force_charshort_cast(int t
);
702 static void gen_cast(CType
*type
);
704 static Sym
*sym_find(int v
);
705 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
);
708 static int type_size(CType
*type
, int *a
);
709 static inline CType
*pointed_type(CType
*type
);
710 static int pointed_size(CType
*type
);
711 static int lvalue_type(int t
);
712 static int parse_btype(CType
*type
, AttributeDef
*ad
);
713 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
);
714 static int is_compatible_types(CType
*type1
, CType
*type2
);
716 int ieee_finite(double d
);
717 void error(const char *fmt
, ...);
720 static void vpush_global_sym(CType
*type
, int v
);
721 void vset(CType
*type
, int r
, int v
);
722 void type_to_str(char *buf
, int buf_size
,
723 CType
*type
, const char *varstr
);
724 char *get_tok_str(int v
, CValue
*cv
);
725 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
726 unsigned long offset
, unsigned long size
);
727 static Sym
*external_global_sym(int v
, CType
*type
, int r
);
729 /* section generation */
730 static void section_realloc(Section
*sec
, unsigned long new_size
);
731 static void *section_ptr_add(Section
*sec
, unsigned long size
);
732 static void put_extern_sym(Sym
*sym
, Section
*section
,
733 unsigned long value
, unsigned long size
);
734 static void greloc(Section
*s
, Sym
*sym
, unsigned long addr
, int type
);
735 static int put_elf_str(Section
*s
, const char *sym
);
736 static int put_elf_sym(Section
*s
,
737 unsigned long value
, unsigned long size
,
738 int info
, int other
, int shndx
, const char *name
);
739 static int add_elf_sym(Section
*s
, unsigned long value
, unsigned long size
,
740 int info
, int sh_num
, const char *name
);
741 static void put_elf_reloc(Section
*symtab
, Section
*s
, unsigned long offset
,
742 int type
, int symbol
);
743 static void put_stabs(const char *str
, int type
, int other
, int desc
,
744 unsigned long value
);
745 static void put_stabs_r(const char *str
, int type
, int other
, int desc
,
746 unsigned long value
, Section
*sec
, int sym_index
);
747 static void put_stabn(int type
, int other
, int desc
, int value
);
748 static void put_stabd(int type
, int other
, int desc
);
749 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
);
751 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
752 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
753 static int tcc_add_file_internal(TCCState
*s
, const char *filename
, int flags
);
757 #ifdef CONFIG_TCC_ASM
759 typedef struct ExprValue
{
764 #define MAX_ASM_OPERANDS 30
766 typedef struct ASMOperand
{
767 int id
; /* GCC 3 optionnal identifier (0 if number only supported */
769 char asm_str
[16]; /* computed asm string for operand */
770 SValue
*vt
; /* C value of the expression */
771 int ref_index
; /* if >= 0, gives reference to a output constraint */
772 int priority
; /* priority, used to assign registers */
773 int reg
; /* if >= 0, register number used for this operand */
774 int is_llong
; /* true if double register value */
777 static void asm_expr(TCCState
*s1
, ExprValue
*pe
);
778 static int asm_int_expr(TCCState
*s1
);
779 static int find_constraint(ASMOperand
*operands
, int nb_operands
,
780 const char *name
, const char **pp
);
782 static int tcc_assemble(TCCState
*s1
, int do_preprocess
);
786 static void asm_instr(void);
788 /* true if float/double/long double type */
789 static inline int is_float(int t
)
793 return bt
== VT_LDOUBLE
|| bt
== VT_DOUBLE
|| bt
== VT_FLOAT
;
796 #ifdef TCC_TARGET_I386
797 #include "i386-gen.c"
800 #ifdef TCC_TARGET_ARM
804 #ifdef CONFIG_TCC_STATIC
806 #define RTLD_LAZY 0x001
807 #define RTLD_NOW 0x002
808 #define RTLD_GLOBAL 0x100
809 #define RTLD_DEFAULT NULL
811 /* dummy function for profiling */
812 void *dlopen(const char *filename
, int flag
)
817 const char *dlerror(void)
822 typedef struct TCCSyms
{
827 #define TCCSYM(a) { #a, &a, },
829 /* add the symbol you want here if no dynamic linking is done */
830 static TCCSyms tcc_syms
[] = {
838 void *dlsym(void *handle
, const char *symbol
)
842 while (p
->str
!= NULL
) {
843 if (!strcmp(p
->str
, symbol
))
852 /********************************************************/
854 /* we use our own 'finite' function to avoid potential problems with
855 non standard math libs */
856 /* XXX: endianness dependent */
857 int ieee_finite(double d
)
860 return ((unsigned)((p
[1] | 0x800fffff) + 1)) >> 31;
863 /* copy a string and truncate it. */
864 static char *pstrcpy(char *buf
, int buf_size
, const char *s
)
871 q_end
= buf
+ buf_size
- 1;
883 /* strcat and truncate. */
884 static char *pstrcat(char *buf
, int buf_size
, const char *s
)
889 pstrcpy(buf
+ len
, buf_size
- len
, s
);
893 /* memory management */
899 static inline void tcc_free(void *ptr
)
902 mem_cur_size
-= malloc_usable_size(ptr
);
907 static void *tcc_malloc(unsigned long size
)
912 error("memory full");
914 mem_cur_size
+= malloc_usable_size(ptr
);
915 if (mem_cur_size
> mem_max_size
)
916 mem_max_size
= mem_cur_size
;
921 static void *tcc_mallocz(unsigned long size
)
924 ptr
= tcc_malloc(size
);
925 memset(ptr
, 0, size
);
929 static inline void *tcc_realloc(void *ptr
, unsigned long size
)
933 mem_cur_size
-= malloc_usable_size(ptr
);
935 ptr1
= realloc(ptr
, size
);
937 /* NOTE: count not correct if alloc error, but not critical */
938 mem_cur_size
+= malloc_usable_size(ptr1
);
939 if (mem_cur_size
> mem_max_size
)
940 mem_max_size
= mem_cur_size
;
945 static char *tcc_strdup(const char *str
)
948 ptr
= tcc_malloc(strlen(str
) + 1);
953 #define free(p) use_tcc_free(p)
954 #define malloc(s) use_tcc_malloc(s)
955 #define realloc(p, s) use_tcc_realloc(p, s)
957 static void dynarray_add(void ***ptab
, int *nb_ptr
, void *data
)
964 /* every power of two we double array size */
965 if ((nb
& (nb
- 1)) == 0) {
970 pp
= tcc_realloc(pp
, nb_alloc
* sizeof(void *));
972 error("memory full");
979 Section
*new_section(TCCState
*s1
, const char *name
, int sh_type
, int sh_flags
)
983 sec
= tcc_mallocz(sizeof(Section
) + strlen(name
));
984 strcpy(sec
->name
, name
);
985 sec
->sh_type
= sh_type
;
986 sec
->sh_flags
= sh_flags
;
993 sec
->sh_addralign
= 4;
996 sec
->sh_addralign
= 1;
999 sec
->sh_addralign
= 32; /* default conservative alignment */
1003 /* only add section if not private */
1004 if (!(sh_flags
& SHF_PRIVATE
)) {
1005 sec
->sh_num
= s1
->nb_sections
;
1006 dynarray_add((void ***)&s1
->sections
, &s1
->nb_sections
, sec
);
1011 static void free_section(Section
*s
)
1017 /* realloc section and set its content to zero */
1018 static void section_realloc(Section
*sec
, unsigned long new_size
)
1021 unsigned char *data
;
1023 size
= sec
->data_allocated
;
1026 while (size
< new_size
)
1028 data
= tcc_realloc(sec
->data
, size
);
1030 error("memory full");
1031 memset(data
+ sec
->data_allocated
, 0, size
- sec
->data_allocated
);
1033 sec
->data_allocated
= size
;
1036 /* reserve at least 'size' bytes in section 'sec' from
1037 sec->data_offset. */
1038 static void *section_ptr_add(Section
*sec
, unsigned long size
)
1040 unsigned long offset
, offset1
;
1042 offset
= sec
->data_offset
;
1043 offset1
= offset
+ size
;
1044 if (offset1
> sec
->data_allocated
)
1045 section_realloc(sec
, offset1
);
1046 sec
->data_offset
= offset1
;
1047 return sec
->data
+ offset
;
1050 /* return a reference to a section, and create it if it does not
1052 Section
*find_section(TCCState
*s1
, const char *name
)
1056 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1057 sec
= s1
->sections
[i
];
1058 if (!strcmp(name
, sec
->name
))
1061 /* sections are created as PROGBITS */
1062 return new_section(s1
, name
, SHT_PROGBITS
, SHF_ALLOC
);
1065 /* update sym->c so that it points to an external symbol in section
1066 'section' with value 'value' */
1067 static void put_extern_sym(Sym
*sym
, Section
*section
,
1068 unsigned long value
, unsigned long size
)
1070 int sym_type
, sym_bind
, sh_num
, info
;
1075 sh_num
= section
->sh_num
;
1079 if ((sym
->type
.t
& VT_BTYPE
) == VT_FUNC
)
1080 sym_type
= STT_FUNC
;
1082 sym_type
= STT_OBJECT
;
1083 if (sym
->type
.t
& VT_STATIC
)
1084 sym_bind
= STB_LOCAL
;
1086 sym_bind
= STB_GLOBAL
;
1088 name
= get_tok_str(sym
->v
, NULL
);
1089 #ifdef CONFIG_TCC_BCHECK
1090 if (do_bounds_check
) {
1093 /* XXX: avoid doing that for statics ? */
1094 /* if bound checking is activated, we change some function
1095 names by adding the "__bound" prefix */
1098 /* XXX: we rely only on malloc hooks */
1110 strcpy(buf
, "__bound_");
1117 info
= ELF32_ST_INFO(sym_bind
, sym_type
);
1118 sym
->c
= add_elf_sym(symtab_section
, value
, size
, info
, sh_num
, name
);
1120 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
1121 esym
->st_value
= value
;
1122 esym
->st_size
= size
;
1123 esym
->st_shndx
= sh_num
;
1127 /* add a new relocation entry to symbol 'sym' in section 's' */
1128 static void greloc(Section
*s
, Sym
*sym
, unsigned long offset
, int type
)
1131 put_extern_sym(sym
, NULL
, 0, 0);
1132 /* now we can add ELF relocation info */
1133 put_elf_reloc(symtab_section
, s
, offset
, type
, sym
->c
);
1136 static inline int isid(int c
)
1138 return (c
>= 'a' && c
<= 'z') ||
1139 (c
>= 'A' && c
<= 'Z') ||
1143 static inline int isnum(int c
)
1145 return c
>= '0' && c
<= '9';
1148 static inline int isoct(int c
)
1150 return c
>= '0' && c
<= '7';
1153 static inline int toup(int c
)
1155 if (c
>= 'a' && c
<= 'z')
1156 return c
- 'a' + 'A';
1161 static void strcat_vprintf(char *buf
, int buf_size
, const char *fmt
, va_list ap
)
1165 vsnprintf(buf
+ len
, buf_size
- len
, fmt
, ap
);
1168 static void strcat_printf(char *buf
, int buf_size
, const char *fmt
, ...)
1172 strcat_vprintf(buf
, buf_size
, fmt
, ap
);
1176 void error1(TCCState
*s1
, int is_warning
, const char *fmt
, va_list ap
)
1183 for(f
= s1
->include_stack
; f
< s1
->include_stack_ptr
; f
++)
1184 strcat_printf(buf
, sizeof(buf
), "In file included from %s:%d:\n",
1185 (*f
)->filename
, (*f
)->line_num
);
1186 if (file
->line_num
> 0) {
1187 strcat_printf(buf
, sizeof(buf
),
1188 "%s:%d: ", file
->filename
, file
->line_num
);
1190 strcat_printf(buf
, sizeof(buf
),
1191 "%s: ", file
->filename
);
1194 strcat_printf(buf
, sizeof(buf
),
1198 strcat_printf(buf
, sizeof(buf
), "warning: ");
1199 strcat_vprintf(buf
, sizeof(buf
), fmt
, ap
);
1201 if (!s1
->error_func
) {
1202 /* default case: stderr */
1203 fprintf(stderr
, "%s\n", buf
);
1205 s1
->error_func(s1
->error_opaque
, buf
);
1207 if (!is_warning
|| s1
->warn_error
)
1212 void tcc_set_error_func(TCCState
*s
, void *error_opaque
,
1213 void (*error_func
)(void *opaque
, const char *msg
))
1215 s
->error_opaque
= error_opaque
;
1216 s
->error_func
= error_func
;
1220 /* error without aborting current compilation */
1221 void error_noabort(const char *fmt
, ...)
1223 TCCState
*s1
= tcc_state
;
1227 error1(s1
, 0, fmt
, ap
);
1231 void error(const char *fmt
, ...)
1233 TCCState
*s1
= tcc_state
;
1237 error1(s1
, 0, fmt
, ap
);
1239 /* better than nothing: in some cases, we accept to handle errors */
1240 if (s1
->error_set_jmp_enabled
) {
1241 longjmp(s1
->error_jmp_buf
, 1);
1243 /* XXX: eliminate this someday */
1248 void expect(const char *msg
)
1250 error("%s expected", msg
);
1253 void warning(const char *fmt
, ...)
1255 TCCState
*s1
= tcc_state
;
1262 error1(s1
, 1, fmt
, ap
);
1269 error("'%c' expected", c
);
1273 static void test_lvalue(void)
1275 if (!(vtop
->r
& VT_LVAL
))
1279 /* allocate a new token */
1280 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
1282 TokenSym
*ts
, **ptable
;
1285 if (tok_ident
>= SYM_FIRST_ANOM
)
1286 error("memory full");
1288 /* expand token table if needed */
1289 i
= tok_ident
- TOK_IDENT
;
1290 if ((i
% TOK_ALLOC_INCR
) == 0) {
1291 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
1293 error("memory full");
1294 table_ident
= ptable
;
1297 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
1298 table_ident
[i
] = ts
;
1299 ts
->tok
= tok_ident
++;
1300 ts
->sym_define
= NULL
;
1301 ts
->sym_label
= NULL
;
1302 ts
->sym_struct
= NULL
;
1303 ts
->sym_identifier
= NULL
;
1305 ts
->hash_next
= NULL
;
1306 memcpy(ts
->str
, str
, len
);
1307 ts
->str
[len
] = '\0';
1312 #define TOK_HASH_INIT 1
1313 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
1315 /* find a token and add it if not found */
1316 static TokenSym
*tok_alloc(const char *str
, int len
)
1318 TokenSym
*ts
, **pts
;
1324 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
1325 h
&= (TOK_HASH_SIZE
- 1);
1327 pts
= &hash_ident
[h
];
1332 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
1334 pts
= &(ts
->hash_next
);
1336 return tok_alloc_new(pts
, str
, len
);
1339 /* CString handling */
1341 static void cstr_realloc(CString
*cstr
, int new_size
)
1346 size
= cstr
->size_allocated
;
1348 size
= 8; /* no need to allocate a too small first string */
1349 while (size
< new_size
)
1351 data
= tcc_realloc(cstr
->data_allocated
, size
);
1353 error("memory full");
1354 cstr
->data_allocated
= data
;
1355 cstr
->size_allocated
= size
;
1360 static void cstr_ccat(CString
*cstr
, int ch
)
1363 size
= cstr
->size
+ 1;
1364 if (size
> cstr
->size_allocated
)
1365 cstr_realloc(cstr
, size
);
1366 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
1370 static void cstr_cat(CString
*cstr
, const char *str
)
1382 /* add a wide char */
1383 static void cstr_wccat(CString
*cstr
, int ch
)
1386 size
= cstr
->size
+ sizeof(int);
1387 if (size
> cstr
->size_allocated
)
1388 cstr_realloc(cstr
, size
);
1389 *(int *)(((unsigned char *)cstr
->data
) + size
- sizeof(int)) = ch
;
1393 static void cstr_new(CString
*cstr
)
1395 memset(cstr
, 0, sizeof(CString
));
1398 /* free string and reset it to NULL */
1399 static void cstr_free(CString
*cstr
)
1401 tcc_free(cstr
->data_allocated
);
1405 #define cstr_reset(cstr) cstr_free(cstr)
1407 static CString
*cstr_dup(CString
*cstr1
)
1412 cstr
= tcc_malloc(sizeof(CString
));
1415 cstr
->size_allocated
= size
;
1416 cstr
->data_allocated
= tcc_malloc(size
);
1417 cstr
->data
= cstr
->data_allocated
;
1418 memcpy(cstr
->data_allocated
, cstr1
->data_allocated
, size
);
1422 /* XXX: unicode ? */
1423 static void add_char(CString
*cstr
, int c
)
1425 if (c
== '\'' || c
== '\"' || c
== '\\') {
1426 /* XXX: could be more precise if char or string */
1427 cstr_ccat(cstr
, '\\');
1429 if (c
>= 32 && c
<= 126) {
1432 cstr_ccat(cstr
, '\\');
1434 cstr_ccat(cstr
, 'n');
1436 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
1437 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
1438 cstr_ccat(cstr
, '0' + (c
& 7));
1443 /* XXX: buffer overflow */
1444 /* XXX: float tokens */
1445 char *get_tok_str(int v
, CValue
*cv
)
1447 static char buf
[STRING_MAX_SIZE
+ 1];
1448 static CString cstr_buf
;
1454 /* NOTE: to go faster, we give a fixed buffer for small strings */
1455 cstr_reset(&cstr_buf
);
1456 cstr_buf
.data
= buf
;
1457 cstr_buf
.size_allocated
= sizeof(buf
);
1463 /* XXX: not quite exact, but only useful for testing */
1464 sprintf(p
, "%u", cv
->ui
);
1468 /* XXX: not quite exact, but only useful for testing */
1469 sprintf(p
, "%Lu", cv
->ull
);
1473 cstr_ccat(&cstr_buf
, '\'');
1474 add_char(&cstr_buf
, cv
->i
);
1475 cstr_ccat(&cstr_buf
, '\'');
1476 cstr_ccat(&cstr_buf
, '\0');
1480 len
= cstr
->size
- 1;
1482 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1483 cstr_ccat(&cstr_buf
, '\0');
1488 cstr_ccat(&cstr_buf
, '\"');
1490 len
= cstr
->size
- 1;
1492 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1494 len
= (cstr
->size
/ sizeof(int)) - 1;
1496 add_char(&cstr_buf
, ((int *)cstr
->data
)[i
]);
1498 cstr_ccat(&cstr_buf
, '\"');
1499 cstr_ccat(&cstr_buf
, '\0');
1508 return strcpy(p
, "<<=");
1510 return strcpy(p
, ">>=");
1512 if (v
< TOK_IDENT
) {
1513 /* search in two bytes table */
1527 } else if (v
< tok_ident
) {
1528 return table_ident
[v
- TOK_IDENT
]->str
;
1529 } else if (v
>= SYM_FIRST_ANOM
) {
1530 /* special name for anonymous symbol */
1531 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
1533 /* should never happen */
1538 return cstr_buf
.data
;
1541 /* push, without hashing */
1542 static Sym
*sym_push2(Sym
**ps
, int v
, int t
, int c
)
1545 s
= tcc_malloc(sizeof(Sym
));
1556 /* find a symbol and return its associated structure. 's' is the top
1557 of the symbol stack */
1558 static Sym
*sym_find2(Sym
*s
, int v
)
1568 /* structure lookup */
1569 static inline Sym
*struct_find(int v
)
1572 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1574 return table_ident
[v
]->sym_struct
;
1577 /* find an identifier */
1578 static inline Sym
*sym_find(int v
)
1581 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1583 return table_ident
[v
]->sym_identifier
;
1586 /* push a given symbol on the symbol stack */
1587 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
)
1596 s
= sym_push2(ps
, v
, type
->t
, c
);
1597 s
->type
.ref
= type
->ref
;
1599 /* don't record fields or anonymous symbols */
1601 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1602 /* record symbol in token array */
1603 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1605 ps
= &ts
->sym_struct
;
1607 ps
= &ts
->sym_identifier
;
1614 /* push a global identifier */
1615 static Sym
*global_identifier_push(int v
, int t
, int c
)
1618 s
= sym_push2(&global_stack
, v
, t
, c
);
1619 /* don't record anonymous symbol */
1620 if (v
< SYM_FIRST_ANOM
) {
1621 ps
= &table_ident
[v
- TOK_IDENT
]->sym_identifier
;
1622 /* modify the top most local identifier, so that
1623 sym_identifier will point to 's' when popped */
1625 ps
= &(*ps
)->prev_tok
;
1632 /* pop symbols until top reaches 'b' */
1633 static void sym_pop(Sym
**ptop
, Sym
*b
)
1643 /* remove symbol in token array */
1645 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1646 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1648 ps
= &ts
->sym_struct
;
1650 ps
= &ts
->sym_identifier
;
1661 BufferedFile
*tcc_open(TCCState
*s1
, const char *filename
)
1666 fd
= open(filename
, O_RDONLY
);
1669 bf
= tcc_malloc(sizeof(BufferedFile
));
1675 bf
->buf_ptr
= bf
->buffer
;
1676 bf
->buf_end
= bf
->buffer
;
1677 bf
->buffer
[0] = CH_EOB
; /* put eob symbol */
1678 pstrcpy(bf
->filename
, sizeof(bf
->filename
), filename
);
1680 bf
->ifndef_macro
= 0;
1681 bf
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
1682 // printf("opening '%s'\n", filename);
1686 void tcc_close(BufferedFile
*bf
)
1688 total_lines
+= bf
->line_num
;
1693 /* fill input buffer and peek next char */
1694 static int tcc_peekc_slow(BufferedFile
*bf
)
1697 /* only tries to read if really end of buffer */
1698 if (bf
->buf_ptr
>= bf
->buf_end
) {
1700 #if defined(PARSE_DEBUG)
1705 len
= read(bf
->fd
, bf
->buffer
, len
);
1712 bf
->buf_ptr
= bf
->buffer
;
1713 bf
->buf_end
= bf
->buffer
+ len
;
1714 *bf
->buf_end
= CH_EOB
;
1716 if (bf
->buf_ptr
< bf
->buf_end
) {
1717 return bf
->buf_ptr
[0];
1719 bf
->buf_ptr
= bf
->buf_end
;
1724 /* return the current character, handling end of block if necessary
1726 static int handle_eob(void)
1728 return tcc_peekc_slow(file
);
1731 /* read next char from current input file and handle end of input buffer */
1732 static inline void inp(void)
1734 ch
= *(++(file
->buf_ptr
));
1735 /* end of buffer/file handling */
1740 /* handle '\[\r]\n' */
1741 static void handle_stray(void)
1743 while (ch
== '\\') {
1748 } else if (ch
== '\r') {
1756 error("stray '\\' in program");
1761 /* skip the stray and handle the \\n case. Output an error if
1762 incorrect char after the stray */
1763 static int handle_stray1(uint8_t *p
)
1767 if (p
>= file
->buf_end
) {
1784 /* handle just the EOB case, but not stray */
1785 #define PEEKC_EOB(c, p)\
1796 /* handle the complicated stray case */
1797 #define PEEKC(c, p)\
1802 c = handle_stray1(p);\
1807 /* input with '\[\r]\n' handling. Note that this function cannot
1808 handle other characters after '\', so you cannot call it inside
1809 strings or comments */
1810 static void minp(void)
1818 /* single line C++ comments */
1819 static uint8_t *parse_line_comment(uint8_t *p
)
1826 if (c
== '\n' || c
== CH_EOF
) {
1828 } else if (c
== '\\') {
1833 } else if (c
== '\r') {
1848 static uint8_t *parse_comment(uint8_t *p
)
1854 /* fast skip loop */
1857 if (c
== '\n' || c
== '*' || c
== '\\')
1861 if (c
== '\n' || c
== '*' || c
== '\\')
1865 /* now we can handle all the cases */
1869 } else if (c
== '*') {
1875 } else if (c
== '/') {
1876 goto end_of_comment
;
1877 } else if (c
== '\\') {
1882 /* skip '\[\r]\n', otherwise just skip the stray */
1888 } else if (c
== '\r') {
1905 /* stray, eob or eof */
1910 error("unexpected end of file in comment");
1911 } else if (c
== '\\') {
1923 /* space exlcuding newline */
1924 static inline int is_space(int ch
)
1926 return ch
== ' ' || ch
== '\t' || ch
== '\v' || ch
== '\f' || ch
== '\r';
1929 static inline void skip_spaces(void)
1931 while (is_space(ch
))
1935 /* parse a string without interpreting escapes */
1936 static uint8_t *parse_pp_string(uint8_t *p
,
1937 int sep
, CString
*str
)
1945 } else if (c
== '\\') {
1950 unterminated_string
:
1951 /* XXX: indicate line number of start of string */
1952 error("missing terminating %c character", sep
);
1953 } else if (c
== '\\') {
1954 /* escape : just skip \[\r]\n */
1959 } else if (c
== '\r') {
1962 expect("'\n' after '\r'");
1965 } else if (c
== CH_EOF
) {
1966 goto unterminated_string
;
1969 cstr_ccat(str
, '\\');
1975 } else if (c
== '\n') {
1978 } else if (c
== '\r') {
1981 cstr_ccat(str
, '\r');
1997 /* skip block of text until #else, #elif or #endif. skip also pairs of
1999 void preprocess_skip(void)
2001 int a
, start_of_line
, c
;
2028 } else if (c
== '\\') {
2029 /* XXX: incorrect: should not give an error */
2030 ch
= file
->buf_ptr
[0];
2038 p
= parse_pp_string(p
, c
, NULL
);
2047 p
= parse_comment(p
);
2048 } else if (ch
== '/') {
2049 p
= parse_line_comment(p
);
2055 if (start_of_line
) {
2060 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
2062 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
2064 else if (tok
== TOK_ENDIF
)
2078 /* ParseState handling */
2080 /* XXX: currently, no include file info is stored. Thus, we cannot display
2081 accurate messages if the function or data definition spans multiple
2084 /* save current parse state in 's' */
2085 void save_parse_state(ParseState
*s
)
2087 s
->line_num
= file
->line_num
;
2088 s
->macro_ptr
= macro_ptr
;
2093 /* restore parse state from 's' */
2094 void restore_parse_state(ParseState
*s
)
2096 file
->line_num
= s
->line_num
;
2097 macro_ptr
= s
->macro_ptr
;
2102 /* return the number of additional 'ints' necessary to store the
2104 static inline int tok_ext_size(int t
)
2123 return LDOUBLE_SIZE
/ 4;
2129 /* token string handling */
2131 static inline void tok_str_new(TokenString
*s
)
2135 s
->allocated_len
= 0;
2136 s
->last_line_num
= -1;
2139 static void tok_str_free(int *str
)
2148 /* NOTE: we test zero separately so that GCC can generate a
2149 table for the following switch */
2164 /* XXX: use a macro to be portable on 64 bit ? */
2165 cstr
= (CString
*)p
[1];
2176 p
+= 1 + (LDOUBLE_SIZE
/ 4);
2186 static int *tok_str_realloc(TokenString
*s
)
2190 len
= s
->allocated_len
+ TOK_STR_ALLOC_INCR
;
2191 str
= tcc_realloc(s
->str
, len
* sizeof(int));
2193 error("memory full");
2194 s
->allocated_len
= len
;
2199 static void tok_str_add(TokenString
*s
, int t
)
2205 if (len
>= s
->allocated_len
)
2206 str
= tok_str_realloc(s
);
2211 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
2218 /* allocate space for worst case */
2219 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
2220 str
= tok_str_realloc(s
);
2229 str
[len
++] = cv
->tab
[0];
2234 str
[len
++] = (int)cstr_dup(cv
->cstr
);
2239 #if LDOUBLE_SIZE == 8
2242 str
[len
++] = cv
->tab
[0];
2243 str
[len
++] = cv
->tab
[1];
2245 #if LDOUBLE_SIZE == 12
2247 str
[len
++] = cv
->tab
[0];
2248 str
[len
++] = cv
->tab
[1];
2249 str
[len
++] = cv
->tab
[2];
2250 #elif LDOUBLE_SIZE != 8
2251 #error add long double size support
2260 /* add the current parse token in token string 's' */
2261 static void tok_str_add_tok(TokenString
*s
)
2265 /* save line number info */
2266 if (file
->line_num
!= s
->last_line_num
) {
2267 s
->last_line_num
= file
->line_num
;
2268 cval
.i
= s
->last_line_num
;
2269 tok_str_add2(s
, TOK_LINENUM
, &cval
);
2271 tok_str_add2(s
, tok
, &tokc
);
2274 #if LDOUBLE_SIZE == 12
2275 #define LDOUBLE_GET(p, cv) \
2279 #elif LDOUBLE_SIZE == 8
2280 #define LDOUBLE_GET(p, cv) \
2284 #error add long double size support
2288 /* get a token from an integer array and increment pointer
2289 accordingly. we code it as a macro to avoid pointer aliasing. */
2290 #define TOK_GET(t, p, cv) \
2312 case TOK_CLDOUBLE: \
2313 LDOUBLE_GET(p, cv); \
2314 p += LDOUBLE_SIZE / 4; \
2321 /* defines handling */
2322 static inline void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
2326 s
= sym_push2(&define_stack
, v
, macro_type
, (int)str
);
2327 s
->next
= first_arg
;
2328 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
2331 /* undefined a define symbol. Its name is just set to zero */
2332 static void define_undef(Sym
*s
)
2336 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2337 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2341 static inline Sym
*define_find(int v
)
2344 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2346 return table_ident
[v
]->sym_define
;
2349 /* free define stack until top reaches 'b' */
2350 static void free_defines(Sym
*b
)
2358 /* do not free args or predefined defines */
2360 tok_str_free((int *)top
->c
);
2362 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2363 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2371 static Sym
*label_find(int v
)
2374 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2376 return table_ident
[v
]->sym_label
;
2379 static Sym
*label_push(Sym
**ptop
, int v
, int flags
)
2382 s
= sym_push2(ptop
, v
, 0, 0);
2384 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
2385 if (ptop
== &global_label_stack
) {
2386 /* modify the top most local identifier, so that
2387 sym_identifier will point to 's' when popped */
2389 ps
= &(*ps
)->prev_tok
;
2396 /* pop labels until element last is reached. Look if any labels are
2397 undefined. Define symbols if '&&label' was used. */
2398 static void label_pop(Sym
**ptop
, Sym
*slast
)
2401 for(s
= *ptop
; s
!= slast
; s
= s1
) {
2403 if (s
->r
== LABEL_DECLARED
) {
2404 warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
2405 } else if (s
->r
== LABEL_FORWARD
) {
2406 error("label '%s' used but not defined",
2407 get_tok_str(s
->v
, NULL
));
2410 /* define corresponding symbol. A size of
2412 put_extern_sym(s
, cur_text_section
, (long)s
->next
, 1);
2416 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
2422 /* eval an expression for #if/#elif */
2423 static int expr_preprocess(void)
2429 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2430 next(); /* do macro subst */
2431 if (tok
== TOK_DEFINED
) {
2436 c
= define_find(tok
) != 0;
2441 } else if (tok
>= TOK_IDENT
) {
2442 /* if undefined macro */
2446 tok_str_add_tok(&str
);
2448 tok_str_add(&str
, -1); /* simulate end of file */
2449 tok_str_add(&str
, 0);
2450 /* now evaluate C constant expression */
2451 macro_ptr
= str
.str
;
2455 tok_str_free(str
.str
);
2459 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
2460 static void tok_print(int *str
)
2466 TOK_GET(t
, str
, cval
);
2469 printf(" %s", get_tok_str(t
, &cval
));
2475 /* parse after #define */
2476 static void parse_define(void)
2478 Sym
*s
, *first
, **ps
;
2479 int v
, t
, varg
, is_vaargs
, c
;
2484 error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
2485 /* XXX: should check if same macro (ANSI) */
2488 /* '(' must be just after macro definition for MACRO_FUNC */
2489 c
= file
->buf_ptr
[0];
2491 c
= handle_stray1(file
->buf_ptr
);
2496 while (tok
!= ')') {
2500 if (varg
== TOK_DOTS
) {
2501 varg
= TOK___VA_ARGS__
;
2503 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
2507 if (varg
< TOK_IDENT
)
2508 error("badly punctuated parameter list");
2509 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
2520 /* EOF testing necessary for '-D' handling */
2521 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2522 tok_str_add2(&str
, tok
, &tokc
);
2525 tok_str_add(&str
, 0);
2527 printf("define %s %d: ", get_tok_str(v
, NULL
), t
);
2530 define_push(v
, t
, str
.str
, first
);
2533 /* XXX: use a token or a hash table to accelerate matching ? */
2534 static CachedInclude
*search_cached_include(TCCState
*s1
,
2535 int type
, const char *filename
)
2540 for(i
= 0;i
< s1
->nb_cached_includes
; i
++) {
2541 e
= s1
->cached_includes
[i
];
2542 if (e
->type
== type
&& !strcmp(e
->filename
, filename
))
2548 static inline void add_cached_include(TCCState
*s1
, int type
,
2549 const char *filename
, int ifndef_macro
)
2553 if (search_cached_include(s1
, type
, filename
))
2556 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
2558 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
2562 strcpy(e
->filename
, filename
);
2563 e
->ifndef_macro
= ifndef_macro
;
2564 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
2567 /* is_bof is true if first non space token at beginning of file */
2568 static void preprocess(int is_bof
)
2570 TCCState
*s1
= tcc_state
;
2571 int size
, i
, c
, n
, saved_parse_flags
;
2572 char buf
[1024], *q
, *p
;
2578 saved_parse_flags
= parse_flags
;
2579 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
|
2580 PARSE_FLAG_LINEFEED
;
2590 s
= define_find(tok
);
2591 /* undefine symbol by putting an invalid name */
2596 ch
= file
->buf_ptr
[0];
2597 /* XXX: incorrect if comments : use next_nomacro with a special mode */
2602 } else if (ch
== '\"') {
2605 /* XXX: better stray handling */
2608 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
2609 if ((q
- buf
) < sizeof(buf
) - 1)
2616 /* eat all spaces and comments after include */
2617 /* XXX: slightly incorrect */
2618 while (ch1
!= '\n' && ch1
!= CH_EOF
)
2622 /* computed #include : either we have only strings or
2623 we have anything enclosed in '<>' */
2626 if (tok
== TOK_STR
) {
2627 while (tok
!= TOK_LINEFEED
) {
2628 if (tok
!= TOK_STR
) {
2630 error("'#include' expects \"FILENAME\" or <FILENAME>");
2632 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
2638 while (tok
!= TOK_LINEFEED
) {
2639 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
2643 /* check syntax and remove '<>' */
2644 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
2645 goto include_syntax
;
2646 memmove(buf
, buf
+ 1, len
- 2);
2647 buf
[len
- 2] = '\0';
2652 e
= search_cached_include(s1
, c
, buf
);
2653 if (e
&& define_find(e
->ifndef_macro
)) {
2654 /* no need to parse the include because the 'ifndef macro'
2657 printf("%s: skipping %s\n", file
->filename
, buf
);
2661 /* first search in current dir if "header.h" */
2663 p
= strrchr(file
->filename
, '/');
2665 size
= p
+ 1 - file
->filename
;
2666 if (size
> sizeof(buf1
) - 1)
2667 size
= sizeof(buf1
) - 1;
2668 memcpy(buf1
, file
->filename
, size
);
2670 pstrcat(buf1
, sizeof(buf1
), buf
);
2671 f
= tcc_open(s1
, buf1
);
2675 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
2676 error("#include recursion too deep");
2677 /* now search in all the include paths */
2678 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
2679 for(i
= 0; i
< n
; i
++) {
2681 if (i
< s1
->nb_include_paths
)
2682 path
= s1
->include_paths
[i
];
2684 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
2685 pstrcpy(buf1
, sizeof(buf1
), path
);
2686 pstrcat(buf1
, sizeof(buf1
), "/");
2687 pstrcat(buf1
, sizeof(buf1
), buf
);
2688 f
= tcc_open(s1
, buf1
);
2692 error("include file '%s' not found", buf
);
2696 printf("%s: including %s\n", file
->filename
, buf1
);
2699 pstrcpy(f
->inc_filename
, sizeof(f
->inc_filename
), buf
);
2700 /* push current file in stack */
2701 /* XXX: fix current line init */
2702 *s1
->include_stack_ptr
++ = file
;
2704 /* add include file debug info */
2706 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
2708 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
2709 ch
= file
->buf_ptr
[0];
2717 c
= expr_preprocess();
2723 if (tok
< TOK_IDENT
)
2724 error("invalid argument for '#if%sdef'", c
? "n" : "");
2728 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
2730 file
->ifndef_macro
= tok
;
2733 c
= (define_find(tok
) != 0) ^ c
;
2735 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
2736 error("memory full");
2737 *s1
->ifdef_stack_ptr
++ = c
;
2740 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
2741 error("#else without matching #if");
2742 if (s1
->ifdef_stack_ptr
[-1] & 2)
2743 error("#else after #else");
2744 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
2747 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
2748 error("#elif without matching #if");
2749 c
= s1
->ifdef_stack_ptr
[-1];
2751 error("#elif after #else");
2752 /* last #if/#elif expression was true: we skip */
2755 c
= expr_preprocess();
2756 s1
->ifdef_stack_ptr
[-1] = c
;
2766 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
2767 error("#endif without matching #if");
2768 s1
->ifdef_stack_ptr
--;
2769 /* '#ifndef macro' was at the start of file. Now we check if
2770 an '#endif' is exactly at the end of file */
2771 if (file
->ifndef_macro
&&
2772 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
2773 file
->ifndef_macro_saved
= file
->ifndef_macro
;
2774 /* need to set to zero to avoid false matches if another
2775 #ifndef at middle of file */
2776 file
->ifndef_macro
= 0;
2777 while (tok
!= TOK_LINEFEED
)
2779 tok_flags
|= TOK_FLAG_ENDIF
;
2785 if (tok
!= TOK_CINT
)
2787 file
->line_num
= tokc
.i
- 1; /* the line number will be incremented after */
2789 if (tok
!= TOK_LINEFEED
) {
2792 pstrcpy(file
->filename
, sizeof(file
->filename
),
2793 (char *)tokc
.cstr
->data
);
2799 ch
= file
->buf_ptr
[0];
2802 while (ch
!= '\n' && ch
!= CH_EOF
) {
2803 if ((q
- buf
) < sizeof(buf
) - 1)
2809 error("#error %s", buf
);
2811 warning("#warning %s", buf
);
2817 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_CINT
) {
2818 /* '!' is ignored to allow C scripts. numbers are ignored
2819 to emulate cpp behaviour */
2821 error("invalid preprocessing directive #%s", get_tok_str(tok
, &tokc
));
2825 /* ignore other preprocess commands or #! for C scripts */
2826 while (tok
!= TOK_LINEFEED
)
2829 parse_flags
= saved_parse_flags
;
2832 /* evaluate escape codes in a string. */
2833 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
2848 case '0': case '1': case '2': case '3':
2849 case '4': case '5': case '6': case '7':
2850 /* at most three octal digits */
2855 n
= n
* 8 + c
- '0';
2859 n
= n
* 8 + c
- '0';
2864 goto add_char_nonext
;
2870 if (c
>= 'a' && c
<= 'f')
2872 else if (c
>= 'A' && c
<= 'F')
2882 goto add_char_nonext
;
2906 goto invalid_escape
;
2916 if (c
>= '!' && c
<= '~')
2917 warning("unknown escape sequence: \'\\%c\'", c
);
2919 warning("unknown escape sequence: \'\\x%x\'", c
);
2926 cstr_ccat(outstr
, c
);
2928 cstr_wccat(outstr
, c
);
2930 /* add a trailing '\0' */
2932 cstr_ccat(outstr
, '\0');
2934 cstr_wccat(outstr
, '\0');
2937 /* we use 64 bit numbers */
2940 /* bn = (bn << shift) | or_val */
2941 void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
2945 for(i
=0;i
<BN_SIZE
;i
++) {
2947 bn
[i
] = (v
<< shift
) | or_val
;
2948 or_val
= v
>> (32 - shift
);
2952 void bn_zero(unsigned int *bn
)
2955 for(i
=0;i
<BN_SIZE
;i
++) {
2960 /* parse number in null terminated string 'p' and return it in the
2962 void parse_number(const char *p
)
2964 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
2966 unsigned int bn
[BN_SIZE
];
2977 goto float_frac_parse
;
2978 } else if (t
== '0') {
2979 if (ch
== 'x' || ch
== 'X') {
2983 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
2989 /* parse all digits. cannot check octal numbers at this stage
2990 because of floating point constants */
2992 if (ch
>= 'a' && ch
<= 'f')
2994 else if (ch
>= 'A' && ch
<= 'F')
3002 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
3004 error("number too long");
3010 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
3011 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
3013 /* NOTE: strtox should support that for hexa numbers, but
3014 non ISOC99 libcs do not support it, so we prefer to do
3016 /* hexadecimal or binary floats */
3017 /* XXX: handle overflows */
3029 } else if (t
>= 'a') {
3031 } else if (t
>= 'A') {
3036 bn_lshift(bn
, shift
, t
);
3043 if (t
>= 'a' && t
<= 'f') {
3045 } else if (t
>= 'A' && t
<= 'F') {
3047 } else if (t
>= '0' && t
<= '9') {
3053 error("invalid digit");
3054 bn_lshift(bn
, shift
, t
);
3059 if (ch
!= 'p' && ch
!= 'P')
3066 } else if (ch
== '-') {
3070 if (ch
< '0' || ch
> '9')
3071 expect("exponent digits");
3072 while (ch
>= '0' && ch
<= '9') {
3073 exp_val
= exp_val
* 10 + ch
- '0';
3076 exp_val
= exp_val
* s
;
3078 /* now we can generate the number */
3079 /* XXX: should patch directly float number */
3080 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
3081 d
= ldexp(d
, exp_val
- frac_bits
);
3086 /* float : should handle overflow */
3088 } else if (t
== 'L') {
3091 /* XXX: not large enough */
3092 tokc
.ld
= (long double)d
;
3098 /* decimal floats */
3100 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3105 while (ch
>= '0' && ch
<= '9') {
3106 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3112 if (ch
== 'e' || ch
== 'E') {
3113 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3117 if (ch
== '-' || ch
== '+') {
3118 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3123 if (ch
< '0' || ch
> '9')
3124 expect("exponent digits");
3125 while (ch
>= '0' && ch
<= '9') {
3126 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3138 tokc
.f
= strtof(token_buf
, NULL
);
3139 } else if (t
== 'L') {
3142 tokc
.ld
= strtold(token_buf
, NULL
);
3145 tokc
.d
= strtod(token_buf
, NULL
);
3149 unsigned long long n
, n1
;
3152 /* integer number */
3155 if (b
== 10 && *q
== '0') {
3162 /* no need for checks except for base 10 / 8 errors */
3165 } else if (t
>= 'a') {
3167 } else if (t
>= 'A') {
3172 error("invalid digit");
3176 /* detect overflow */
3177 /* XXX: this test is not reliable */
3179 error("integer constant overflow");
3182 /* XXX: not exactly ANSI compliant */
3183 if ((n
& 0xffffffff00000000LL
) != 0) {
3188 } else if (n
> 0x7fffffff) {
3199 error("three 'l's in integer constant");
3202 if (tok
== TOK_CINT
)
3204 else if (tok
== TOK_CUINT
)
3208 } else if (t
== 'U') {
3210 error("two 'u's in integer constant");
3212 if (tok
== TOK_CINT
)
3214 else if (tok
== TOK_CLLONG
)
3221 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
3229 #define PARSE2(c1, tok1, c2, tok2) \
3240 /* return next token without macro substitution */
3241 static inline void next_nomacro1(void)
3261 /* first look if it is in fact an end of buffer */
3262 if (p
>= file
->buf_end
) {
3266 if (p
>= file
->buf_end
)
3279 TCCState
*s1
= tcc_state
;
3280 if (parse_flags
& PARSE_FLAG_LINEFEED
) {
3282 } else if (s1
->include_stack_ptr
== s1
->include_stack
||
3283 !(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3284 /* no include left : end of file. */
3287 /* pop include file */
3289 /* test if previous '#endif' was after a #ifdef at
3291 if (tok_flags
& TOK_FLAG_ENDIF
) {
3293 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
3295 add_cached_include(s1
, file
->inc_type
, file
->inc_filename
,
3296 file
->ifndef_macro_saved
);
3299 /* add end of include file debug info */
3301 put_stabd(N_EINCL
, 0, 0);
3303 /* pop include stack */
3305 s1
->include_stack_ptr
--;
3306 file
= *s1
->include_stack_ptr
;
3314 if (parse_flags
& PARSE_FLAG_LINEFEED
) {
3318 tok_flags
|= TOK_FLAG_BOL
;
3327 if ((tok_flags
& TOK_FLAG_BOL
) &&
3328 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3330 preprocess(tok_flags
& TOK_FLAG_BOF
);
3336 tok
= TOK_TWOSHARPS
;
3343 case 'a': case 'b': case 'c': case 'd':
3344 case 'e': case 'f': case 'g': case 'h':
3345 case 'i': case 'j': case 'k': case 'l':
3346 case 'm': case 'n': case 'o': case 'p':
3347 case 'q': case 'r': case 's': case 't':
3348 case 'u': case 'v': case 'w': case 'x':
3350 case 'A': case 'B': case 'C': case 'D':
3351 case 'E': case 'F': case 'G': case 'H':
3352 case 'I': case 'J': case 'K':
3353 case 'M': case 'N': case 'O': case 'P':
3354 case 'Q': case 'R': case 'S': case 'T':
3355 case 'U': case 'V': case 'W': case 'X':
3361 h
= TOK_HASH_FUNC(h
, c
);
3365 if (!isidnum_table
[c
])
3367 h
= TOK_HASH_FUNC(h
, c
);
3374 /* fast case : no stray found, so we have the full token
3375 and we have already hashed it */
3377 h
&= (TOK_HASH_SIZE
- 1);
3378 pts
= &hash_ident
[h
];
3383 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
3385 pts
= &(ts
->hash_next
);
3387 ts
= tok_alloc_new(pts
, p1
, len
);
3391 cstr_reset(&tokcstr
);
3394 cstr_ccat(&tokcstr
, *p1
);
3400 while (isidnum_table
[c
]) {
3401 cstr_ccat(&tokcstr
, c
);
3404 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
3410 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
3412 goto parse_ident_fast
;
3415 if (c
== '\'' || c
== '\"') {
3419 cstr_reset(&tokcstr
);
3420 cstr_ccat(&tokcstr
, 'L');
3421 goto parse_ident_slow
;
3425 case '0': case '1': case '2': case '3':
3426 case '4': case '5': case '6': case '7':
3429 cstr_reset(&tokcstr
);
3430 /* after the first digit, accept digits, alpha, '.' or sign if
3431 prefixed by 'eEpP' */
3435 cstr_ccat(&tokcstr
, c
);
3437 if (!(isnum(c
) || isid(c
) || c
== '.' ||
3438 ((c
== '+' || c
== '-') &&
3439 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
3442 /* We add a trailing '\0' to ease parsing */
3443 cstr_ccat(&tokcstr
, '\0');
3444 tokc
.cstr
= &tokcstr
;
3448 /* special dot handling because it can also start a number */
3451 cstr_reset(&tokcstr
);
3452 cstr_ccat(&tokcstr
, '.');
3454 } else if (c
== '.') {
3474 /* parse the string */
3476 p
= parse_pp_string(p
, sep
, &str
);
3477 cstr_ccat(&str
, '\0');
3479 /* eval the escape (should be done as TOK_PPNUM) */
3480 cstr_reset(&tokcstr
);
3481 parse_escape_string(&tokcstr
, str
.data
, is_long
);
3486 /* XXX: make it portable */
3490 char_size
= sizeof(int);
3491 if (tokcstr
.size
<= char_size
)
3492 error("empty character constant");
3493 if (tokcstr
.size
> 2 * char_size
)
3494 warning("multi-character character constant");
3496 tokc
.i
= *(int8_t *)tokcstr
.data
;
3499 tokc
.i
= *(int *)tokcstr
.data
;
3503 tokc
.cstr
= &tokcstr
;
3517 } else if (c
== '<') {
3535 } else if (c
== '>') {
3553 } else if (c
== '=') {
3566 } else if (c
== '=') {
3579 } else if (c
== '=') {
3592 } else if (c
== '=') {
3595 } else if (c
== '>') {
3603 PARSE2('!', '!', '=', TOK_NE
)
3604 PARSE2('=', '=', '=', TOK_EQ
)
3605 PARSE2('*', '*', '=', TOK_A_MUL
)
3606 PARSE2('%', '%', '=', TOK_A_MOD
)
3607 PARSE2('^', '^', '=', TOK_A_XOR
)
3609 /* comments or operator */
3613 p
= parse_comment(p
);
3615 } else if (c
== '/') {
3616 p
= parse_line_comment(p
);
3618 } else if (c
== '=') {
3638 case '$': /* only used in assembler */
3643 error("unrecognized character \\x%02x", c
);
3648 #if defined(PARSE_DEBUG)
3649 printf("token = %s\n", get_tok_str(tok
, &tokc
));
3653 /* return next token without macro substitution. Can read input from
3655 static void next_nomacro(void)
3661 TOK_GET(tok
, macro_ptr
, tokc
);
3662 if (tok
== TOK_LINENUM
) {
3663 file
->line_num
= tokc
.i
;
3672 /* substitute args in macro_str and return allocated string */
3673 static int *macro_arg_subst(Sym
**nested_list
, int *macro_str
, Sym
*args
)
3675 int *st
, last_tok
, t
, notfirst
;
3684 TOK_GET(t
, macro_str
, cval
);
3689 TOK_GET(t
, macro_str
, cval
);
3692 s
= sym_find2(args
, t
);
3699 cstr_ccat(&cstr
, ' ');
3700 TOK_GET(t
, st
, cval
);
3701 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
3704 cstr_ccat(&cstr
, '\0');
3706 printf("stringize: %s\n", (char *)cstr
.data
);
3710 tok_str_add2(&str
, TOK_STR
, &cval
);
3713 tok_str_add2(&str
, t
, &cval
);
3715 } else if (t
>= TOK_IDENT
) {
3716 s
= sym_find2(args
, t
);
3719 /* if '##' is present before or after, no arg substitution */
3720 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
3721 /* special case for var arg macros : ## eats the
3722 ',' if empty VA_ARGS variable. */
3723 /* XXX: test of the ',' is not 100%
3724 reliable. should fix it to avoid security
3726 if (gnu_ext
&& s
->type
.t
&&
3727 last_tok
== TOK_TWOSHARPS
&&
3728 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
3730 /* suppress ',' '##' */
3733 /* suppress '##' and add variable */
3741 TOK_GET(t1
, st
, cval
);
3744 tok_str_add2(&str
, t1
, &cval
);
3748 /* NOTE: the stream cannot be read when macro
3749 substituing an argument */
3750 macro_subst(&str
, nested_list
, st
, 0);
3753 tok_str_add(&str
, t
);
3756 tok_str_add2(&str
, t
, &cval
);
3760 tok_str_add(&str
, 0);
3764 static char const ab_month_name
[12][4] =
3766 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3767 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3770 /* do macro substitution of current token with macro 's' and add
3771 result to (tok_str,tok_len). 'nested_list' is the list of all
3772 macros we got inside to avoid recursing. Return non zero if no
3773 substitution needs to be done */
3774 static int macro_subst_tok(TokenString
*tok_str
,
3775 Sym
**nested_list
, Sym
*s
, int can_read_stream
)
3777 Sym
*args
, *sa
, *sa1
;
3778 int mstr_allocated
, parlevel
, *mstr
, t
;
3784 /* if symbol is a macro, prepare substitution */
3786 /* special macros */
3787 if (tok
== TOK___LINE__
) {
3788 cval
.i
= file
->line_num
;
3789 tok_str_add2(tok_str
, TOK_CINT
, &cval
);
3790 } else if (tok
== TOK___FILE__
) {
3791 cstrval
= file
->filename
;
3793 tok_str_add2(tok_str
, TOK_STR
, &cval
);
3794 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
3800 tm
= localtime(&ti
);
3801 if (tok
== TOK___DATE__
) {
3802 snprintf(buf
, sizeof(buf
), "%s %2d %d",
3803 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
3805 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
3806 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
3811 cstr_cat(&cstr
, cstrval
);
3812 cstr_ccat(&cstr
, '\0');
3814 tok_str_add2(tok_str
, TOK_STR
, &cval
);
3819 if (s
->type
.t
== MACRO_FUNC
) {
3820 /* NOTE: we do not use next_nomacro to avoid eating the
3821 next token. XXX: find better solution */
3824 if (t
== 0 && can_read_stream
) {
3825 /* end of macro stream: we must look at the token
3826 after in the file */
3832 /* XXX: incorrect with comments */
3833 ch
= file
->buf_ptr
[0];
3834 while (is_space(ch
) || ch
== '\n')
3838 if (t
!= '(') /* no macro subst */
3841 /* argument macro */
3846 /* NOTE: empty args are allowed, except if no args */
3848 /* handle '()' case */
3849 if (!args
&& !sa
&& tok
== ')')
3852 error("macro '%s' used with too many args",
3853 get_tok_str(s
->v
, 0));
3856 /* NOTE: non zero sa->t indicates VA_ARGS */
3857 while ((parlevel
> 0 ||
3859 (tok
!= ',' || sa
->type
.t
))) &&
3863 else if (tok
== ')')
3865 tok_str_add2(&str
, tok
, &tokc
);
3868 tok_str_add(&str
, 0);
3869 sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, (int)str
.str
);
3872 /* special case for gcc var args: add an empty
3873 var arg argument if it is omitted */
3874 if (sa
&& sa
->type
.t
&& gnu_ext
)
3884 error("macro '%s' used with too few args",
3885 get_tok_str(s
->v
, 0));
3888 /* now subst each arg */
3889 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3894 tok_str_free((int *)sa
->c
);
3900 sym_push2(nested_list
, s
->v
, 0, 0);
3901 macro_subst(tok_str
, nested_list
, mstr
, 1);
3902 /* pop nested defined symbol */
3904 *nested_list
= sa1
->prev
;
3912 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3913 return the resulting string (which must be freed). */
3914 static inline int *macro_twosharps(const int *macro_str
)
3917 const int *macro_ptr1
, *start_macro_ptr
, *ptr
, *saved_macro_ptr
;
3919 const char *p1
, *p2
;
3921 TokenString macro_str1
;
3924 start_macro_ptr
= macro_str
;
3925 /* we search the first '##' */
3927 macro_ptr1
= macro_str
;
3928 TOK_GET(t
, macro_str
, cval
);
3929 /* nothing more to do if end of string */
3932 if (*macro_str
== TOK_TWOSHARPS
)
3936 /* we saw '##', so we need more processing to handle it */
3938 tok_str_new(¯o_str1
);
3942 /* add all tokens seen so far */
3943 for(ptr
= start_macro_ptr
; ptr
< macro_ptr1
;) {
3944 TOK_GET(t
, ptr
, cval
);
3945 tok_str_add2(¯o_str1
, t
, &cval
);
3947 saved_macro_ptr
= macro_ptr
;
3948 /* XXX: get rid of the use of macro_ptr here */
3949 macro_ptr
= (int *)macro_str
;
3951 while (*macro_ptr
== TOK_TWOSHARPS
) {
3953 macro_ptr1
= macro_ptr
;
3956 TOK_GET(t
, macro_ptr
, cval
);
3957 /* We concatenate the two tokens if we have an
3958 identifier or a preprocessing number */
3960 p1
= get_tok_str(tok
, &tokc
);
3961 cstr_cat(&cstr
, p1
);
3962 p2
= get_tok_str(t
, &cval
);
3963 cstr_cat(&cstr
, p2
);
3964 cstr_ccat(&cstr
, '\0');
3966 if ((tok
>= TOK_IDENT
|| tok
== TOK_PPNUM
) &&
3967 (t
>= TOK_IDENT
|| t
== TOK_PPNUM
)) {
3968 if (tok
== TOK_PPNUM
) {
3969 /* if number, then create a number token */
3970 /* NOTE: no need to allocate because
3971 tok_str_add2() does it */
3974 /* if identifier, we must do a test to
3975 validate we have a correct identifier */
3976 if (t
== TOK_PPNUM
) {
3986 if (!isnum(c
) && !isid(c
))
3990 ts
= tok_alloc(cstr
.data
, strlen(cstr
.data
));
3991 tok
= ts
->tok
; /* modify current token */
3994 const char *str
= cstr
.data
;
3995 const unsigned char *q
;
3997 /* we look for a valid token */
3998 /* XXX: do more extensive checks */
3999 if (!strcmp(str
, ">>=")) {
4001 } else if (!strcmp(str
, "<<=")) {
4003 } else if (strlen(str
) == 2) {
4004 /* search in two bytes table */
4009 if (q
[0] == str
[0] && q
[1] == str
[1])
4016 /* NOTE: because get_tok_str use a static buffer,
4019 p1
= get_tok_str(tok
, &tokc
);
4020 cstr_cat(&cstr
, p1
);
4021 cstr_ccat(&cstr
, '\0');
4022 p2
= get_tok_str(t
, &cval
);
4023 warning("pasting \"%s\" and \"%s\" does not give a valid preprocessing token", cstr
.data
, p2
);
4024 /* cannot merge tokens: just add them separately */
4025 tok_str_add2(¯o_str1
, tok
, &tokc
);
4026 /* XXX: free associated memory ? */
4033 tok_str_add2(¯o_str1
, tok
, &tokc
);
4038 macro_ptr
= (int *)saved_macro_ptr
;
4040 tok_str_add(¯o_str1
, 0);
4041 return macro_str1
.str
;
4045 /* do macro substitution of macro_str and add result to
4046 (tok_str,tok_len). 'nested_list' is the list of all macros we got
4047 inside to avoid recursing. */
4048 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
4049 const int *macro_str
, int can_read_stream
)
4052 int *saved_macro_ptr
, *macro_str1
;
4057 /* first scan for '##' operator handling */
4059 macro_str1
= macro_twosharps(ptr
);
4063 /* NOTE: ptr == NULL can only happen if tokens are read from
4064 file stream due to a macro function call */
4067 TOK_GET(t
, ptr
, cval
);
4072 /* if nested substitution, do nothing */
4073 if (sym_find2(*nested_list
, t
))
4075 saved_macro_ptr
= macro_ptr
;
4076 macro_ptr
= (int *)ptr
;
4078 ret
= macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
4079 ptr
= (int *)macro_ptr
;
4080 macro_ptr
= saved_macro_ptr
;
4085 tok_str_add2(tok_str
, t
, &cval
);
4089 tok_str_free(macro_str1
);
4092 /* return next token with macro substitution */
4093 static void next(void)
4095 Sym
*nested_list
, *s
;
4101 /* if not reading from macro substituted string, then try
4102 to substitute macros */
4103 if (tok
>= TOK_IDENT
&&
4104 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
4105 s
= define_find(tok
);
4107 /* we have a macro: we try to substitute */
4110 if (macro_subst_tok(&str
, &nested_list
, s
, 1) == 0) {
4111 /* substitution done, NOTE: maybe empty */
4112 tok_str_add(&str
, 0);
4113 macro_ptr
= str
.str
;
4114 macro_ptr_allocated
= str
.str
;
4121 /* end of macro or end of unget buffer */
4122 if (unget_buffer_enabled
) {
4123 macro_ptr
= unget_saved_macro_ptr
;
4124 unget_buffer_enabled
= 0;
4126 /* end of macro string: free it */
4127 tok_str_free(macro_ptr_allocated
);
4134 /* convert preprocessor tokens into C tokens */
4135 if (tok
== TOK_PPNUM
&&
4136 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
4137 parse_number((char *)tokc
.cstr
->data
);
4141 /* push back current token and set current token to 'last_tok'. Only
4142 identifier case handled for labels. */
4143 static inline void unget_tok(int last_tok
)
4147 unget_saved_macro_ptr
= macro_ptr
;
4148 unget_buffer_enabled
= 1;
4149 q
= unget_saved_buffer
;
4152 n
= tok_ext_size(tok
) - 1;
4155 *q
= 0; /* end of token string */
4160 void swap(int *p
, int *q
)
4168 void vsetc(CType
*type
, int r
, CValue
*vc
)
4172 if (vtop
>= vstack
+ VSTACK_SIZE
)
4173 error("memory full");
4174 /* cannot let cpu flags if other instruction are generated. Also
4175 avoid leaving VT_JMP anywhere except on the top of the stack
4176 because it would complicate the code generator. */
4177 if (vtop
>= vstack
) {
4178 v
= vtop
->r
& VT_VALMASK
;
4179 if (v
== VT_CMP
|| (v
& ~1) == VT_JMP
)
4185 vtop
->r2
= VT_CONST
;
4189 /* push integer constant */
4194 vsetc(&int_type
, VT_CONST
, &cval
);
4197 /* Return a static symbol pointing to a section */
4198 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
4199 unsigned long offset
, unsigned long size
)
4205 sym
= global_identifier_push(v
, type
->t
| VT_STATIC
, 0);
4206 sym
->type
.ref
= type
->ref
;
4207 sym
->r
= VT_CONST
| VT_SYM
;
4208 put_extern_sym(sym
, sec
, offset
, size
);
4212 /* push a reference to a section offset by adding a dummy symbol */
4213 static void vpush_ref(CType
*type
, Section
*sec
, unsigned long offset
, unsigned long size
)
4218 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4219 vtop
->sym
= get_sym_ref(type
, sec
, offset
, size
);
4222 /* define a new external reference to a symbol 'v' of type 'u' */
4223 static Sym
*external_global_sym(int v
, CType
*type
, int r
)
4229 /* push forward reference */
4230 s
= global_identifier_push(v
, type
->t
| VT_EXTERN
, 0);
4231 s
->type
.ref
= type
->ref
;
4232 s
->r
= r
| VT_CONST
| VT_SYM
;
4237 /* define a new external reference to a symbol 'v' of type 'u' */
4238 static Sym
*external_sym(int v
, CType
*type
, int r
)
4244 /* push forward reference */
4245 s
= sym_push(v
, type
, r
| VT_CONST
| VT_SYM
, 0);
4246 s
->type
.t
|= VT_EXTERN
;
4248 if (!is_compatible_types(&s
->type
, type
))
4249 error("incompatible types for redefinition of '%s'",
4250 get_tok_str(v
, NULL
));
4255 /* push a reference to global symbol v */
4256 static void vpush_global_sym(CType
*type
, int v
)
4261 sym
= external_global_sym(v
, type
, 0);
4263 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4267 void vset(CType
*type
, int r
, int v
)
4272 vsetc(type
, r
, &cval
);
4275 void vseti(int r
, int v
)
4291 void vpushv(SValue
*v
)
4293 if (vtop
>= vstack
+ VSTACK_SIZE
)
4294 error("memory full");
4304 /* save r to the memory stack, and mark it as being free */
4305 void save_reg(int r
)
4307 int l
, saved
, size
, align
;
4311 /* modify all stack values */
4314 for(p
=vstack
;p
<=vtop
;p
++) {
4315 if ((p
->r
& VT_VALMASK
) == r
||
4316 (p
->r2
& VT_VALMASK
) == r
) {
4317 /* must save value on stack if not already done */
4319 /* NOTE: must reload 'r' because r might be equal to r2 */
4320 r
= p
->r
& VT_VALMASK
;
4321 /* store register in the stack */
4323 if ((p
->r
& VT_LVAL
) ||
4324 (!is_float(type
->t
) && (type
->t
& VT_BTYPE
) != VT_LLONG
))
4326 size
= type_size(type
, &align
);
4327 loc
= (loc
- size
) & -align
;
4328 sv
.type
.t
= type
->t
;
4329 sv
.r
= VT_LOCAL
| VT_LVAL
;
4332 #ifdef TCC_TARGET_I386
4333 /* x86 specific: need to pop fp register ST0 if saved */
4334 if (r
== TREG_ST0
) {
4335 o(0xd9dd); /* fstp %st(1) */
4338 /* special long long case */
4339 if ((type
->t
& VT_BTYPE
) == VT_LLONG
) {
4346 /* mark that stack entry as being saved on the stack */
4347 if (p
->r
& VT_LVAL
) {
4348 /* also clear the bounded flag because the
4349 relocation address of the function was stored in
4351 p
->r
= (p
->r
& ~(VT_VALMASK
| VT_BOUNDED
)) | VT_LLOCAL
;
4353 p
->r
= lvalue_type(p
->type
.t
) | VT_LOCAL
;
4361 /* find a register of class 'rc2' with at most one reference on stack.
4362 * If none, call get_reg(rc) */
4363 int get_reg_ex(int rc
, int rc2
)
4368 for(r
=0;r
<NB_REGS
;r
++) {
4369 if (reg_classes
[r
] & rc2
) {
4372 for(p
= vstack
; p
<= vtop
; p
++) {
4373 if ((p
->r
& VT_VALMASK
) == r
||
4374 (p
->r2
& VT_VALMASK
) == r
)
4384 /* find a free register of class 'rc'. If none, save one register */
4390 /* find a free register */
4391 for(r
=0;r
<NB_REGS
;r
++) {
4392 if (reg_classes
[r
] & rc
) {
4393 for(p
=vstack
;p
<=vtop
;p
++) {
4394 if ((p
->r
& VT_VALMASK
) == r
||
4395 (p
->r2
& VT_VALMASK
) == r
)
4403 /* no register left : free the first one on the stack (VERY
4404 IMPORTANT to start from the bottom to ensure that we don't
4405 spill registers used in gen_opi()) */
4406 for(p
=vstack
;p
<=vtop
;p
++) {
4407 r
= p
->r
& VT_VALMASK
;
4408 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
))
4410 /* also look at second register (if long long) */
4411 r
= p
->r2
& VT_VALMASK
;
4412 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
)) {
4418 /* Should never comes here */
4422 /* save registers up to (vtop - n) stack entry */
4423 void save_regs(int n
)
4428 for(p
= vstack
;p
<= p1
; p
++) {
4429 r
= p
->r
& VT_VALMASK
;
4436 /* move register 's' to 'r', and flush previous value of r to memory
4438 void move_reg(int r
, int s
)
4451 /* get address of vtop (vtop MUST BE an lvalue) */
4454 vtop
->r
&= ~VT_LVAL
;
4455 /* tricky: if saved lvalue, then we can go back to lvalue */
4456 if ((vtop
->r
& VT_VALMASK
) == VT_LLOCAL
)
4457 vtop
->r
= (vtop
->r
& ~(VT_VALMASK
| VT_LVAL_TYPE
)) | VT_LOCAL
| VT_LVAL
;
4460 #ifdef CONFIG_TCC_BCHECK
4461 /* generate lvalue bound code */
4467 vtop
->r
&= ~VT_MUSTBOUND
;
4468 /* if lvalue, then use checking code before dereferencing */
4469 if (vtop
->r
& VT_LVAL
) {
4470 /* if not VT_BOUNDED value, then make one */
4471 if (!(vtop
->r
& VT_BOUNDED
)) {
4472 lval_type
= vtop
->r
& (VT_LVAL_TYPE
| VT_LVAL
);
4473 /* must save type because we must set it to int to get pointer */
4475 vtop
->type
.t
= VT_INT
;
4478 gen_bounded_ptr_add();
4479 vtop
->r
|= lval_type
;
4482 /* then check for dereferencing */
4483 gen_bounded_ptr_deref();
4488 /* store vtop a register belonging to class 'rc'. lvalues are
4489 converted to values. Cannot be used if cannot be converted to
4490 register value (such as structures). */
4493 int r
, r2
, rc2
, bit_pos
, bit_size
, size
, align
, i
;
4494 unsigned long long ll
;
4496 /* NOTE: get_reg can modify vstack[] */
4497 if (vtop
->type
.t
& VT_BITFIELD
) {
4498 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
4499 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
4500 /* remove bit field info to avoid loops */
4501 vtop
->type
.t
&= ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
4502 /* generate shifts */
4503 vpushi(32 - (bit_pos
+ bit_size
));
4505 vpushi(32 - bit_size
);
4506 /* NOTE: transformed to SHR if unsigned */
4510 if (is_float(vtop
->type
.t
) &&
4511 (vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4514 unsigned long offset
;
4516 /* XXX: unify with initializers handling ? */
4517 /* CPUs usually cannot use float constants, so we store them
4518 generically in data segment */
4519 size
= type_size(&vtop
->type
, &align
);
4520 offset
= (data_section
->data_offset
+ align
- 1) & -align
;
4521 data_section
->data_offset
= offset
;
4522 /* XXX: not portable yet */
4523 ptr
= section_ptr_add(data_section
, size
);
4526 ptr
[i
] = vtop
->c
.tab
[i
];
4527 sym
= get_sym_ref(&vtop
->type
, data_section
, offset
, size
<< 2);
4528 vtop
->r
|= VT_LVAL
| VT_SYM
;
4532 #ifdef CONFIG_TCC_BCHECK
4533 if (vtop
->r
& VT_MUSTBOUND
)
4537 r
= vtop
->r
& VT_VALMASK
;
4538 /* need to reload if:
4540 - lvalue (need to dereference pointer)
4541 - already a register, but not in the right class */
4542 if (r
>= VT_CONST
||
4543 (vtop
->r
& VT_LVAL
) ||
4544 !(reg_classes
[r
] & rc
) ||
4545 ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
&&
4546 !(reg_classes
[vtop
->r2
] & rc
))) {
4548 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
) {
4549 /* two register type load : expand to two words
4551 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4554 vtop
->c
.ui
= ll
; /* first word */
4556 vtop
->r
= r
; /* save register value */
4557 vpushi(ll
>> 32); /* second word */
4558 } else if (r
>= VT_CONST
||
4559 (vtop
->r
& VT_LVAL
)) {
4560 /* load from memory */
4563 vtop
[-1].r
= r
; /* save register value */
4564 /* increment pointer to get second word */
4565 vtop
->type
.t
= VT_INT
;
4571 /* move registers */
4574 vtop
[-1].r
= r
; /* save register value */
4575 vtop
->r
= vtop
[-1].r2
;
4577 /* allocate second register */
4584 /* write second register */
4586 } else if ((vtop
->r
& VT_LVAL
) && !is_float(vtop
->type
.t
)) {
4588 /* lvalue of scalar type : need to use lvalue type
4589 because of possible cast */
4592 /* compute memory access type */
4593 if (vtop
->r
& VT_LVAL_BYTE
)
4595 else if (vtop
->r
& VT_LVAL_SHORT
)
4597 if (vtop
->r
& VT_LVAL_UNSIGNED
)
4601 /* restore wanted type */
4604 /* one register type load */
4613 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
4614 void gv2(int rc1
, int rc2
)
4618 /* generate more generic register first. But VT_JMP or VT_CMP
4619 values must be generated first in all cases to avoid possible
4621 v
= vtop
[0].r
& VT_VALMASK
;
4622 if (v
!= VT_CMP
&& (v
& ~1) != VT_JMP
&& rc1
<= rc2
) {
4627 /* test if reload is needed for first register */
4628 if ((vtop
[-1].r
& VT_VALMASK
) >= VT_CONST
) {
4638 /* test if reload is needed for first register */
4639 if ((vtop
[0].r
& VT_VALMASK
) >= VT_CONST
) {
4645 /* expand long long on stack in two int registers */
4650 u
= vtop
->type
.t
& VT_UNSIGNED
;
4653 vtop
[0].r
= vtop
[-1].r2
;
4654 vtop
[0].r2
= VT_CONST
;
4655 vtop
[-1].r2
= VT_CONST
;
4656 vtop
[0].type
.t
= VT_INT
| u
;
4657 vtop
[-1].type
.t
= VT_INT
| u
;
4660 /* build a long long from two ints */
4663 gv2(RC_INT
, RC_INT
);
4664 vtop
[-1].r2
= vtop
[0].r
;
4665 vtop
[-1].type
.t
= t
;
4669 /* rotate n first stack elements to the bottom
4670 I1 ... In -> I2 ... In I1 [top is right]
4678 for(i
=-n
+1;i
!=0;i
++)
4679 vtop
[i
] = vtop
[i
+1];
4683 /* rotate n first stack elements to the top
4684 I1 ... In -> In I1 ... I(n-1) [top is right]
4692 for(i
= 0;i
< n
- 1; i
++)
4693 vtop
[-i
] = vtop
[-i
- 1];
4697 /* pop stack value */
4701 v
= vtop
->r
& VT_VALMASK
;
4702 #ifdef TCC_TARGET_I386
4703 /* for x86, we need to pop the FP stack */
4704 if (v
== TREG_ST0
&& !nocode_wanted
) {
4705 o(0xd9dd); /* fstp %st(1) */
4708 if (v
== VT_JMP
|| v
== VT_JMPI
) {
4709 /* need to put correct jump if && or || without test */
4715 /* convert stack entry to register and duplicate its value in another
4723 if ((t
& VT_BTYPE
) == VT_LLONG
) {
4730 /* stack: H L L1 H1 */
4738 /* duplicate value */
4749 load(r1
, &sv
); /* move r to r1 */
4751 /* duplicates value */
4756 /* generate CPU independent (unsigned) long long operations */
4757 void gen_opl(int op
)
4759 int t
, a
, b
, op1
, c
, i
;
4766 func
= TOK___divdi3
;
4769 func
= TOK___udivdi3
;
4772 func
= TOK___moddi3
;
4775 func
= TOK___umoddi3
;
4777 /* call generic long long function */
4778 vpush_global_sym(&func_old_type
, func
);
4783 vtop
->r2
= REG_LRET
;
4796 /* stack: L1 H1 L2 H2 */
4801 vtop
[-2] = vtop
[-3];
4804 /* stack: H1 H2 L1 L2 */
4810 /* stack: H1 H2 L1 L2 ML MH */
4813 /* stack: ML MH H1 H2 L1 L2 */
4817 /* stack: ML MH H1 L2 H2 L1 */
4822 /* stack: ML MH M1 M2 */
4825 } else if (op
== '+' || op
== '-') {
4826 /* XXX: add non carry method too (for MIPS or alpha) */
4832 /* stack: H1 H2 (L1 op L2) */
4835 gen_op(op1
+ 1); /* TOK_xxxC2 */
4838 /* stack: H1 H2 (L1 op L2) */
4841 /* stack: (L1 op L2) H1 H2 */
4843 /* stack: (L1 op L2) (H1 op H2) */
4851 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) {
4852 t
= vtop
[-1].type
.t
;
4856 /* stack: L H shift */
4858 /* constant: simpler */
4859 /* NOTE: all comments are for SHL. the other cases are
4860 done by swaping words */
4871 if (op
!= TOK_SAR
) {
4904 /* XXX: should provide a faster fallback on x86 ? */
4907 func
= TOK___sardi3
;
4910 func
= TOK___shrdi3
;
4913 func
= TOK___shldi3
;
4919 /* compare operations */
4925 /* stack: L1 H1 L2 H2 */
4927 vtop
[-1] = vtop
[-2];
4929 /* stack: L1 L2 H1 H2 */
4932 /* when values are equal, we need to compare low words. since
4933 the jump is inverted, we invert the test too. */
4936 else if (op1
== TOK_GT
)
4938 else if (op1
== TOK_ULT
)
4940 else if (op1
== TOK_UGT
)
4945 if (op1
!= TOK_NE
) {
4949 /* generate non equal test */
4950 /* XXX: NOT PORTABLE yet */
4954 #if defined(TCC_TARGET_I386)
4955 b
= psym(0x850f, 0);
4956 #elif defined(TCC_TARGET_ARM)
4958 o(0x1A000000 | encbranch(ind
, 0, 1));
4960 #error not supported
4964 /* compare low. Always unsigned */
4968 else if (op1
== TOK_LE
)
4970 else if (op1
== TOK_GT
)
4972 else if (op1
== TOK_GE
)
4982 /* handle integer constant optimizations and various machine
4984 void gen_opic(int op
)
4991 /* currently, we cannot do computations with forward symbols */
4992 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
4993 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
4997 case '+': v1
->c
.i
+= fc
; break;
4998 case '-': v1
->c
.i
-= fc
; break;
4999 case '&': v1
->c
.i
&= fc
; break;
5000 case '^': v1
->c
.i
^= fc
; break;
5001 case '|': v1
->c
.i
|= fc
; break;
5002 case '*': v1
->c
.i
*= fc
; break;
5009 /* if division by zero, generate explicit division */
5012 error("division by zero in constant");
5016 default: v1
->c
.i
/= fc
; break;
5017 case '%': v1
->c
.i
%= fc
; break;
5018 case TOK_UDIV
: v1
->c
.i
= (unsigned)v1
->c
.i
/ fc
; break;
5019 case TOK_UMOD
: v1
->c
.i
= (unsigned)v1
->c
.i
% fc
; break;
5022 case TOK_SHL
: v1
->c
.i
<<= fc
; break;
5023 case TOK_SHR
: v1
->c
.i
= (unsigned)v1
->c
.i
>> fc
; break;
5024 case TOK_SAR
: v1
->c
.i
>>= fc
; break;
5026 case TOK_ULT
: v1
->c
.i
= (unsigned)v1
->c
.i
< (unsigned)fc
; break;
5027 case TOK_UGE
: v1
->c
.i
= (unsigned)v1
->c
.i
>= (unsigned)fc
; break;
5028 case TOK_EQ
: v1
->c
.i
= v1
->c
.i
== fc
; break;
5029 case TOK_NE
: v1
->c
.i
= v1
->c
.i
!= fc
; break;
5030 case TOK_ULE
: v1
->c
.i
= (unsigned)v1
->c
.i
<= (unsigned)fc
; break;
5031 case TOK_UGT
: v1
->c
.i
= (unsigned)v1
->c
.i
> (unsigned)fc
; break;
5032 case TOK_LT
: v1
->c
.i
= v1
->c
.i
< fc
; break;
5033 case TOK_GE
: v1
->c
.i
= v1
->c
.i
>= fc
; break;
5034 case TOK_LE
: v1
->c
.i
= v1
->c
.i
<= fc
; break;
5035 case TOK_GT
: v1
->c
.i
= v1
->c
.i
> fc
; break;
5037 case TOK_LAND
: v1
->c
.i
= v1
->c
.i
&& fc
; break;
5038 case TOK_LOR
: v1
->c
.i
= v1
->c
.i
|| fc
; break;
5044 /* if commutative ops, put c2 as constant */
5045 if (c1
&& (op
== '+' || op
== '&' || op
== '^' ||
5046 op
== '|' || op
== '*')) {
5051 if (c2
&& (((op
== '*' || op
== '/' || op
== TOK_UDIV
||
5054 ((op
== '+' || op
== '-' || op
== '|' || op
== '^' ||
5055 op
== TOK_SHL
|| op
== TOK_SHR
|| op
== TOK_SAR
) &&
5061 } else if (c2
&& (op
== '*' || op
== TOK_PDIV
|| op
== TOK_UDIV
)) {
5062 /* try to use shifts instead of muls or divs */
5063 if (fc
> 0 && (fc
& (fc
- 1)) == 0) {
5072 else if (op
== TOK_PDIV
)
5078 } else if (c2
&& (op
== '+' || op
== '-') &&
5079 (vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) ==
5080 (VT_CONST
| VT_SYM
)) {
5081 /* symbol + constant case */
5088 if (!nocode_wanted
) {
5089 /* call low level op generator */
5098 /* generate a floating point operation with constant propagation */
5099 void gen_opif(int op
)
5107 /* currently, we cannot do computations with forward symbols */
5108 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5109 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5111 if (v1
->type
.t
== VT_FLOAT
) {
5114 } else if (v1
->type
.t
== VT_DOUBLE
) {
5122 /* NOTE: we only do constant propagation if finite number (not
5123 NaN or infinity) (ANSI spec) */
5124 if (!ieee_finite(f1
) || !ieee_finite(f2
))
5128 case '+': f1
+= f2
; break;
5129 case '-': f1
-= f2
; break;
5130 case '*': f1
*= f2
; break;
5134 error("division by zero in constant");
5139 /* XXX: also handles tests ? */
5143 /* XXX: overflow test ? */
5144 if (v1
->type
.t
== VT_FLOAT
) {
5146 } else if (v1
->type
.t
== VT_DOUBLE
) {
5154 if (!nocode_wanted
) {
5162 static int pointed_size(CType
*type
)
5165 return type_size(pointed_type(type
), &align
);
5168 static inline int is_null_pointer(SValue
*p
)
5170 if ((p
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
5172 return ((p
->type
.t
& VT_BTYPE
) == VT_INT
&& p
->c
.i
== 0) ||
5173 ((p
->type
.t
& VT_BTYPE
) == VT_LLONG
&& p
->c
.ll
== 0);
5176 static inline int is_integer_btype(int bt
)
5178 return (bt
== VT_BYTE
|| bt
== VT_SHORT
||
5179 bt
== VT_INT
|| bt
== VT_LLONG
);
5182 /* check types for comparison or substraction of pointers */
5183 static void check_comparison_pointer_types(SValue
*p1
, SValue
*p2
, int op
)
5185 CType
*type1
, *type2
, tmp_type1
, tmp_type2
;
5188 /* null pointers are accepted for all comparisons as gcc */
5189 if (is_null_pointer(p1
) || is_null_pointer(p2
))
5193 bt1
= type1
->t
& VT_BTYPE
;
5194 bt2
= type2
->t
& VT_BTYPE
;
5195 /* accept comparison between pointer and integer with a warning */
5196 if ((is_integer_btype(bt1
) || is_integer_btype(bt2
)) && op
!= '-') {
5197 warning("comparison between pointer and integer");
5201 /* both must be pointers or implicit function pointers */
5202 if (bt1
== VT_PTR
) {
5203 type1
= pointed_type(type1
);
5204 } else if (bt1
!= VT_FUNC
)
5205 goto invalid_operands
;
5207 if (bt2
== VT_PTR
) {
5208 type2
= pointed_type(type2
);
5209 } else if (bt2
!= VT_FUNC
) {
5211 error("invalid operands to binary %s", get_tok_str(op
, NULL
));
5213 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
5214 (type2
->t
& VT_BTYPE
) == VT_VOID
)
5218 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5219 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5220 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
5221 /* gcc-like error if '-' is used */
5223 goto invalid_operands
;
5225 warning("comparison of distinct pointer types lacks a cast");
5229 /* generic gen_op: handles types problems */
5232 int u
, t1
, t2
, bt1
, bt2
, t
;
5235 t1
= vtop
[-1].type
.t
;
5236 t2
= vtop
[0].type
.t
;
5237 bt1
= t1
& VT_BTYPE
;
5238 bt2
= t2
& VT_BTYPE
;
5240 if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
5241 /* at least one operand is a pointer */
5242 /* relationnal op: must be both pointers */
5243 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5244 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5245 /* pointers are handled are unsigned */
5246 t
= VT_INT
| VT_UNSIGNED
;
5249 /* if both pointers, then it must be the '-' op */
5250 if (bt1
== VT_PTR
&& bt2
== VT_PTR
) {
5252 error("cannot use pointers here");
5253 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5254 /* XXX: check that types are compatible */
5255 u
= pointed_size(&vtop
[-1].type
);
5257 /* set to integer type */
5258 vtop
->type
.t
= VT_INT
;
5262 /* exactly one pointer : must be '+' or '-'. */
5263 if (op
!= '-' && op
!= '+')
5264 error("cannot use pointers here");
5265 /* Put pointer as first operand */
5266 if (bt2
== VT_PTR
) {
5270 type1
= vtop
[-1].type
;
5271 /* XXX: cast to int ? (long long case) */
5272 vpushi(pointed_size(&vtop
[-1].type
));
5274 #ifdef CONFIG_TCC_BCHECK
5275 /* if evaluating constant expression, no code should be
5276 generated, so no bound check */
5277 if (do_bounds_check
&& !const_wanted
) {
5278 /* if bounded pointers, we generate a special code to
5285 gen_bounded_ptr_add();
5291 /* put again type if gen_opic() swaped operands */
5294 } else if (is_float(bt1
) || is_float(bt2
)) {
5295 /* compute bigger type and do implicit casts */
5296 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
5298 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
5303 /* floats can only be used for a few operations */
5304 if (op
!= '+' && op
!= '-' && op
!= '*' && op
!= '/' &&
5305 (op
< TOK_ULT
|| op
> TOK_GT
))
5306 error("invalid operands for binary operation");
5308 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
5309 /* cast to biggest op */
5311 /* convert to unsigned if it does not fit in a long long */
5312 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
5313 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
5317 /* integer operations */
5319 /* convert to unsigned if it does not fit in an integer */
5320 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
5321 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
5324 /* XXX: currently, some unsigned operations are explicit, so
5325 we modify them here */
5326 if (t
& VT_UNSIGNED
) {
5333 else if (op
== TOK_LT
)
5335 else if (op
== TOK_GT
)
5337 else if (op
== TOK_LE
)
5339 else if (op
== TOK_GE
)
5346 /* special case for shifts and long long: we keep the shift as
5348 if (op
== TOK_SHR
|| op
== TOK_SAR
|| op
== TOK_SHL
)
5353 else if ((t
& VT_BTYPE
) == VT_LLONG
)
5357 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5358 /* relationnal op: the result is an int */
5359 vtop
->type
.t
= VT_INT
;
5366 /* generic itof for unsigned long long case */
5367 void gen_cvt_itof1(int t
)
5369 if ((vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
)) ==
5370 (VT_LLONG
| VT_UNSIGNED
)) {
5373 vpush_global_sym(&func_old_type
, TOK___ulltof
);
5374 else if (t
== VT_DOUBLE
)
5375 vpush_global_sym(&func_old_type
, TOK___ulltod
);
5377 vpush_global_sym(&func_old_type
, TOK___ulltold
);
5387 /* generic ftoi for unsigned long long case */
5388 void gen_cvt_ftoi1(int t
)
5392 if (t
== (VT_LLONG
| VT_UNSIGNED
)) {
5393 /* not handled natively */
5394 st
= vtop
->type
.t
& VT_BTYPE
;
5396 vpush_global_sym(&func_old_type
, TOK___fixunssfdi
);
5397 else if (st
== VT_DOUBLE
)
5398 vpush_global_sym(&func_old_type
, TOK___fixunsdfdi
);
5400 vpush_global_sym(&func_old_type
, TOK___fixunsxfdi
);
5405 vtop
->r2
= REG_LRET
;
5411 /* force char or short cast */
5412 void force_charshort_cast(int t
)
5416 /* XXX: add optimization if lvalue : just change type and offset */
5421 if (t
& VT_UNSIGNED
) {
5422 vpushi((1 << bits
) - 1);
5433 /* cast 'vtop' to 'type' */
5434 static void gen_cast(CType
*type
)
5436 int sbt
, dbt
, sf
, df
, c
;
5438 /* special delayed cast for char/short */
5439 /* XXX: in some cases (multiple cascaded casts), it may still
5441 if (vtop
->r
& VT_MUSTCAST
) {
5442 vtop
->r
&= ~VT_MUSTCAST
;
5443 force_charshort_cast(vtop
->type
.t
);
5446 dbt
= type
->t
& (VT_BTYPE
| VT_UNSIGNED
);
5447 sbt
= vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
);
5449 if (sbt
!= dbt
&& !nocode_wanted
) {
5452 c
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5454 /* convert from fp to fp */
5456 /* constant case: we can do it now */
5457 /* XXX: in ISOC, cannot do it if error in convert */
5458 if (dbt
== VT_FLOAT
&& sbt
== VT_DOUBLE
)
5459 vtop
->c
.f
= (float)vtop
->c
.d
;
5460 else if (dbt
== VT_FLOAT
&& sbt
== VT_LDOUBLE
)
5461 vtop
->c
.f
= (float)vtop
->c
.ld
;
5462 else if (dbt
== VT_DOUBLE
&& sbt
== VT_FLOAT
)
5463 vtop
->c
.d
= (double)vtop
->c
.f
;
5464 else if (dbt
== VT_DOUBLE
&& sbt
== VT_LDOUBLE
)
5465 vtop
->c
.d
= (double)vtop
->c
.ld
;
5466 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_FLOAT
)
5467 vtop
->c
.ld
= (long double)vtop
->c
.f
;
5468 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_DOUBLE
)
5469 vtop
->c
.ld
= (long double)vtop
->c
.d
;
5471 /* non constant case: generate code */
5475 /* convert int to fp */
5478 case VT_LLONG
| VT_UNSIGNED
:
5480 /* XXX: add const cases for long long */
5482 case VT_INT
| VT_UNSIGNED
:
5484 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.ui
; break;
5485 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.ui
; break;
5486 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.ui
; break;
5491 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.i
; break;
5492 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.i
; break;
5493 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.i
; break;
5499 #if !defined(TCC_TARGET_ARM)
5506 /* convert fp to int */
5507 /* we handle char/short/etc... with generic code */
5508 if (dbt
!= (VT_INT
| VT_UNSIGNED
) &&
5509 dbt
!= (VT_LLONG
| VT_UNSIGNED
) &&
5514 case VT_LLONG
| VT_UNSIGNED
:
5516 /* XXX: add const cases for long long */
5518 case VT_INT
| VT_UNSIGNED
:
5520 case VT_FLOAT
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5521 case VT_DOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5522 case VT_LDOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5528 case VT_FLOAT
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5529 case VT_DOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5530 case VT_LDOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5538 if (dbt
== VT_INT
&& (type
->t
& (VT_BTYPE
| VT_UNSIGNED
)) != dbt
) {
5539 /* additional cast for char/short/bool... */
5543 } else if ((dbt
& VT_BTYPE
) == VT_LLONG
) {
5544 if ((sbt
& VT_BTYPE
) != VT_LLONG
) {
5545 /* scalar to long long */
5547 if (sbt
== (VT_INT
| VT_UNSIGNED
))
5548 vtop
->c
.ll
= vtop
->c
.ui
;
5550 vtop
->c
.ll
= vtop
->c
.i
;
5552 /* machine independent conversion */
5554 /* generate high word */
5555 if (sbt
== (VT_INT
| VT_UNSIGNED
)) {
5563 /* patch second register */
5564 vtop
[-1].r2
= vtop
->r
;
5568 } else if (dbt
== VT_BOOL
) {
5569 /* scalar to bool */
5572 } else if ((dbt
& VT_BTYPE
) == VT_BYTE
||
5573 (dbt
& VT_BTYPE
) == VT_SHORT
) {
5574 force_charshort_cast(dbt
);
5575 } else if ((dbt
& VT_BTYPE
) == VT_INT
) {
5577 if (sbt
== VT_LLONG
) {
5578 /* from long long: just take low order word */
5582 /* if lvalue and single word type, nothing to do because
5583 the lvalue already contains the real type size (see
5584 VT_LVAL_xxx constants) */
5590 /* return type size. Put alignment at 'a' */
5591 static int type_size(CType
*type
, int *a
)
5596 bt
= type
->t
& VT_BTYPE
;
5597 if (bt
== VT_STRUCT
) {
5602 } else if (bt
== VT_PTR
) {
5603 if (type
->t
& VT_ARRAY
) {
5605 return type_size(&s
->type
, a
) * s
->c
;
5610 } else if (bt
== VT_LDOUBLE
) {
5612 return LDOUBLE_SIZE
;
5613 } else if (bt
== VT_DOUBLE
|| bt
== VT_LLONG
) {
5614 *a
= 4; /* XXX: i386 specific */
5616 } else if (bt
== VT_INT
|| bt
== VT_ENUM
|| bt
== VT_FLOAT
) {
5619 } else if (bt
== VT_SHORT
) {
5623 /* char, void, function, _Bool */
5629 /* return the pointed type of t */
5630 static inline CType
*pointed_type(CType
*type
)
5632 return &type
->ref
->type
;
5635 /* modify type so that its it is a pointer to type. */
5636 static void mk_pointer(CType
*type
)
5639 s
= sym_push(SYM_FIELD
, type
, 0, -1);
5640 type
->t
= VT_PTR
| (type
->t
& ~VT_TYPE
);
5644 /* compare function types. OLD functions match any new functions */
5645 static int is_compatible_func(CType
*type1
, CType
*type2
)
5651 if (!is_compatible_types(&s1
->type
, &s2
->type
))
5653 /* XXX: not complete */
5654 if (s1
->c
== FUNC_OLD
|| s2
->c
== FUNC_OLD
)
5658 while (s1
!= NULL
) {
5661 if (!is_compatible_types(&s1
->type
, &s2
->type
))
5671 /* return true if type1 and type2 are exactly the same (including
5674 - enums are not checked as gcc __builtin_types_compatible_p ()
5676 static int is_compatible_types(CType
*type1
, CType
*type2
)
5680 t1
= type1
->t
& VT_TYPE
;
5681 t2
= type2
->t
& VT_TYPE
;
5682 /* XXX: bitfields ? */
5685 /* test more complicated cases */
5686 bt1
= t1
& VT_BTYPE
;
5687 if (bt1
== VT_PTR
) {
5688 type1
= pointed_type(type1
);
5689 type2
= pointed_type(type2
);
5690 return is_compatible_types(type1
, type2
);
5691 } else if (bt1
== VT_STRUCT
) {
5692 return (type1
->ref
== type2
->ref
);
5693 } else if (bt1
== VT_FUNC
) {
5694 return is_compatible_func(type1
, type2
);
5700 /* print a type. If 'varstr' is not NULL, then the variable is also
5701 printed in the type */
5703 /* XXX: add array and function pointers */
5704 void type_to_str(char *buf
, int buf_size
,
5705 CType
*type
, const char *varstr
)
5712 t
= type
->t
& VT_TYPE
;
5715 if (t
& VT_CONSTANT
)
5716 pstrcat(buf
, buf_size
, "const ");
5717 if (t
& VT_VOLATILE
)
5718 pstrcat(buf
, buf_size
, "volatile ");
5719 if (t
& VT_UNSIGNED
)
5720 pstrcat(buf
, buf_size
, "unsigned ");
5750 tstr
= "long double";
5752 pstrcat(buf
, buf_size
, tstr
);
5756 if (bt
== VT_STRUCT
)
5760 pstrcat(buf
, buf_size
, tstr
);
5761 v
= type
->ref
->v
& ~SYM_STRUCT
;
5762 if (v
>= SYM_FIRST_ANOM
)
5763 pstrcat(buf
, buf_size
, "<anonymous>");
5765 pstrcat(buf
, buf_size
, get_tok_str(v
, NULL
));
5769 type_to_str(buf
, buf_size
, &s
->type
, varstr
);
5770 pstrcat(buf
, buf_size
, "(");
5772 while (sa
!= NULL
) {
5773 type_to_str(buf1
, sizeof(buf1
), &sa
->type
, NULL
);
5774 pstrcat(buf
, buf_size
, buf1
);
5777 pstrcat(buf
, buf_size
, ", ");
5779 pstrcat(buf
, buf_size
, ")");
5783 pstrcpy(buf1
, sizeof(buf1
), "*");
5785 pstrcat(buf1
, sizeof(buf1
), varstr
);
5786 type_to_str(buf
, buf_size
, &s
->type
, buf1
);
5790 pstrcat(buf
, buf_size
, " ");
5791 pstrcat(buf
, buf_size
, varstr
);
5796 /* verify type compatibility to store vtop in 'dt' type, and generate
5798 static void gen_assign_cast(CType
*dt
)
5800 CType
*st
, *type1
, *type2
, tmp_type1
, tmp_type2
;
5801 char buf1
[256], buf2
[256];
5804 st
= &vtop
->type
; /* source type */
5805 dbt
= dt
->t
& VT_BTYPE
;
5806 sbt
= st
->t
& VT_BTYPE
;
5807 if (dt
->t
& VT_CONSTANT
)
5808 warning("assignment of read-only location");
5811 /* special cases for pointers */
5812 /* '0' can also be a pointer */
5813 if (is_null_pointer(vtop
))
5815 /* accept implicit pointer to integer cast with warning */
5816 if (is_integer_btype(sbt
)) {
5817 warning("assignment makes pointer from integer without a cast");
5820 type1
= pointed_type(dt
);
5821 /* a function is implicitely a function pointer */
5822 if (sbt
== VT_FUNC
) {
5823 if ((type1
->t
& VT_BTYPE
) != VT_VOID
&&
5824 !is_compatible_types(pointed_type(dt
), st
))
5831 type2
= pointed_type(st
);
5832 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
5833 (type2
->t
& VT_BTYPE
) == VT_VOID
) {
5834 /* void * can match anything */
5836 /* exact type match, except for unsigned */
5839 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5840 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5841 if (!is_compatible_types(&tmp_type1
, &tmp_type2
))
5844 /* check const and volatile */
5845 if ((!(type1
->t
& VT_CONSTANT
) && (type2
->t
& VT_CONSTANT
)) ||
5846 (!(type1
->t
& VT_VOLATILE
) && (type2
->t
& VT_VOLATILE
)))
5847 warning("assignment discards qualifiers from pointer target type");
5853 if (sbt
== VT_PTR
|| sbt
== VT_FUNC
) {
5854 warning("assignment makes integer from pointer without a cast");
5856 /* XXX: more tests */
5859 if (!is_compatible_types(dt
, st
)) {
5861 type_to_str(buf1
, sizeof(buf1
), st
, NULL
);
5862 type_to_str(buf2
, sizeof(buf2
), dt
, NULL
);
5863 error("cannot cast '%s' to '%s'", buf1
, buf2
);
5871 /* store vtop in lvalue pushed on stack */
5874 int sbt
, dbt
, ft
, r
, t
, size
, align
, bit_size
, bit_pos
, rc
, delayed_cast
;
5876 ft
= vtop
[-1].type
.t
;
5877 sbt
= vtop
->type
.t
& VT_BTYPE
;
5878 dbt
= ft
& VT_BTYPE
;
5879 if (((sbt
== VT_INT
|| sbt
== VT_SHORT
) && dbt
== VT_BYTE
) ||
5880 (sbt
== VT_INT
&& dbt
== VT_SHORT
)) {
5881 /* optimize char/short casts */
5882 delayed_cast
= VT_MUSTCAST
;
5883 vtop
->type
.t
= ft
& VT_TYPE
;
5884 /* XXX: factorize */
5885 if (ft
& VT_CONSTANT
)
5886 warning("assignment of read-only location");
5889 gen_assign_cast(&vtop
[-1].type
);
5892 if (sbt
== VT_STRUCT
) {
5893 /* if structure, only generate pointer */
5894 /* structure assignment : generate memcpy */
5895 /* XXX: optimize if small size */
5896 if (!nocode_wanted
) {
5897 size
= type_size(&vtop
->type
, &align
);
5899 vpush_global_sym(&func_old_type
, TOK_memcpy
);
5903 vtop
->type
.t
= VT_INT
;
5907 vtop
->type
.t
= VT_INT
;
5919 /* leave source on stack */
5920 } else if (ft
& VT_BITFIELD
) {
5921 /* bitfield store handling */
5922 bit_pos
= (ft
>> VT_STRUCT_SHIFT
) & 0x3f;
5923 bit_size
= (ft
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
5924 /* remove bit field info to avoid loops */
5925 vtop
[-1].type
.t
= ft
& ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
5927 /* duplicate destination */
5929 vtop
[-1] = vtop
[-2];
5931 /* mask and shift source */
5932 vpushi((1 << bit_size
) - 1);
5936 /* load destination, mask and or with source */
5938 vpushi(~(((1 << bit_size
) - 1) << bit_pos
));
5944 #ifdef CONFIG_TCC_BCHECK
5945 /* bound check case */
5946 if (vtop
[-1].r
& VT_MUSTBOUND
) {
5952 if (!nocode_wanted
) {
5956 r
= gv(rc
); /* generate value */
5957 /* if lvalue was saved on stack, must read it */
5958 if ((vtop
[-1].r
& VT_VALMASK
) == VT_LLOCAL
) {
5960 t
= get_reg(RC_INT
);
5962 sv
.r
= VT_LOCAL
| VT_LVAL
;
5963 sv
.c
.ul
= vtop
[-1].c
.ul
;
5965 vtop
[-1].r
= t
| VT_LVAL
;
5968 /* two word case handling : store second register at word + 4 */
5969 if ((ft
& VT_BTYPE
) == VT_LLONG
) {
5971 /* convert to int to increment easily */
5972 vtop
->type
.t
= VT_INT
;
5978 /* XXX: it works because r2 is spilled last ! */
5979 store(vtop
->r2
, vtop
- 1);
5983 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
5984 vtop
->r
|= delayed_cast
;
5988 /* post defines POST/PRE add. c is the token ++ or -- */
5989 void inc(int post
, int c
)
5992 vdup(); /* save lvalue */
5994 gv_dup(); /* duplicate value */
5999 vpushi(c
- TOK_MID
);
6001 vstore(); /* store value */
6003 vpop(); /* if post op, return saved value */
6006 /* Parse GNUC __attribute__ extension. Currently, the following
6007 extensions are recognized:
6008 - aligned(n) : set data/function alignment.
6009 - section(x) : generate data/code in this section.
6010 - unused : currently ignored, but may be used someday.
6012 static void parse_attribute(AttributeDef
*ad
)
6016 while (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
) {
6020 while (tok
!= ')') {
6021 if (tok
< TOK_IDENT
)
6022 expect("attribute name");
6030 expect("section name");
6031 ad
->section
= find_section(tcc_state
, (char *)tokc
.cstr
->data
);
6040 if (n
<= 0 || (n
& (n
- 1)) != 0)
6041 error("alignment must be a positive power of two");
6050 /* currently, no need to handle it because tcc does not
6051 track unused objects */
6055 /* currently, no need to handle it because tcc does not
6056 track unused objects */
6061 ad
->func_call
= FUNC_CDECL
;
6066 ad
->func_call
= FUNC_STDCALL
;
6069 if (tcc_state
->warn_unsupported
)
6070 warning("'%s' attribute ignored", get_tok_str(t
, NULL
));
6071 /* skip parameters */
6072 /* XXX: skip parenthesis too */
6075 while (tok
!= ')' && tok
!= -1)
6090 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
6091 static void struct_decl(CType
*type
, int u
)
6093 int a
, v
, size
, align
, maxalign
, c
, offset
;
6094 int bit_size
, bit_pos
, bsize
, bt
, lbit_pos
;
6099 a
= tok
; /* save decl type */
6104 /* struct already defined ? return it */
6106 expect("struct/union/enum name");
6110 error("invalid type");
6117 /* we put an undefined size for struct/union */
6118 s
= sym_push(v
| SYM_STRUCT
, &type1
, 0, -1);
6119 s
->r
= 0; /* default alignment is zero as gcc */
6120 /* put struct/union/enum name in type */
6128 error("struct/union/enum already defined");
6129 /* cannot be empty */
6131 /* non empty enums are not allowed */
6132 if (a
== TOK_ENUM
) {
6136 expect("identifier");
6142 /* enum symbols have static storage */
6143 ss
= sym_push(v
, &int_type
, VT_CONST
, c
);
6144 ss
->type
.t
|= VT_STATIC
;
6149 /* NOTE: we accept a trailing comma */
6159 while (tok
!= '}') {
6160 parse_btype(&btype
, &ad
);
6166 type_decl(&type1
, &ad
, &v
, TYPE_DIRECT
);
6167 if ((type1
.t
& VT_BTYPE
) == VT_FUNC
||
6168 (type1
.t
& (VT_TYPEDEF
| VT_STATIC
| VT_EXTERN
| VT_INLINE
)))
6169 error("invalid type for '%s'",
6170 get_tok_str(v
, NULL
));
6174 bit_size
= expr_const();
6175 /* XXX: handle v = 0 case for messages */
6177 error("negative width in bit-field '%s'",
6178 get_tok_str(v
, NULL
));
6179 if (v
&& bit_size
== 0)
6180 error("zero width for bit-field '%s'",
6181 get_tok_str(v
, NULL
));
6183 size
= type_size(&type1
, &align
);
6185 if (bit_size
>= 0) {
6186 bt
= type1
.t
& VT_BTYPE
;
6191 error("bitfields must have scalar type");
6193 if (bit_size
> bsize
) {
6194 error("width of '%s' exceeds its type",
6195 get_tok_str(v
, NULL
));
6196 } else if (bit_size
== bsize
) {
6197 /* no need for bit fields */
6199 } else if (bit_size
== 0) {
6200 /* XXX: what to do if only padding in a
6202 /* zero size: means to pad */
6206 /* we do not have enough room ? */
6207 if ((bit_pos
+ bit_size
) > bsize
)
6210 /* XXX: handle LSB first */
6211 type1
.t
|= VT_BITFIELD
|
6212 (bit_pos
<< VT_STRUCT_SHIFT
) |
6213 (bit_size
<< (VT_STRUCT_SHIFT
+ 6));
6214 bit_pos
+= bit_size
;
6220 /* add new memory data only if starting
6222 if (lbit_pos
== 0) {
6223 if (a
== TOK_STRUCT
) {
6224 c
= (c
+ align
- 1) & -align
;
6232 if (align
> maxalign
)
6236 printf("add field %s offset=%d",
6237 get_tok_str(v
, NULL
), offset
);
6238 if (type1
.t
& VT_BITFIELD
) {
6239 printf(" pos=%d size=%d",
6240 (type1
.t
>> VT_STRUCT_SHIFT
) & 0x3f,
6241 (type1
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f);
6245 ss
= sym_push(v
| SYM_FIELD
, &type1
, 0, offset
);
6249 if (tok
== ';' || tok
== TOK_EOF
)
6256 /* store size and alignment */
6257 s
->c
= (c
+ maxalign
- 1) & -maxalign
;
6263 /* return 0 if no type declaration. otherwise, return the basic type
6266 static int parse_btype(CType
*type
, AttributeDef
*ad
)
6268 int t
, u
, type_found
, typespec_found
;
6272 memset(ad
, 0, sizeof(AttributeDef
));
6279 /* currently, we really ignore extension */
6289 if ((t
& VT_BTYPE
) != 0)
6290 error("too many basic types");
6306 if ((t
& VT_BTYPE
) == VT_DOUBLE
) {
6307 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6308 } else if ((t
& VT_BTYPE
) == VT_LONG
) {
6309 t
= (t
& ~VT_BTYPE
) | VT_LLONG
;
6323 if ((t
& VT_BTYPE
) == VT_LONG
) {
6324 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6331 struct_decl(&type1
, VT_ENUM
);
6334 type
->ref
= type1
.ref
;
6338 struct_decl(&type1
, VT_STRUCT
);
6341 /* type modifiers */
6394 /* GNUC attribute */
6395 case TOK_ATTRIBUTE1
:
6396 case TOK_ATTRIBUTE2
:
6397 parse_attribute(ad
);
6404 parse_expr_type(&type1
);
6410 if (!s
|| !(s
->type
.t
& VT_TYPEDEF
))
6412 t
|= (s
->type
.t
& ~VT_TYPEDEF
);
6413 type
->ref
= s
->type
.ref
;
6420 if ((t
& (VT_SIGNED
|VT_UNSIGNED
)) == (VT_SIGNED
|VT_UNSIGNED
))
6421 error("signed and unsigned modifier");
6422 if (tcc_state
->char_is_unsigned
) {
6423 if ((t
& (VT_SIGNED
|VT_UNSIGNED
|VT_BTYPE
)) == VT_BYTE
)
6428 /* long is never used as type */
6429 if ((t
& VT_BTYPE
) == VT_LONG
)
6430 t
= (t
& ~VT_BTYPE
) | VT_INT
;
6435 /* convert a function parameter type (array to pointer and function to
6436 function pointer) */
6437 static inline void convert_parameter_type(CType
*pt
)
6439 /* array must be transformed to pointer according to ANSI C */
6441 if ((pt
->t
& VT_BTYPE
) == VT_FUNC
) {
6446 static void post_type(CType
*type
, AttributeDef
*ad
)
6449 Sym
**plast
, *s
, *first
;
6454 /* function declaration */
6459 while (tok
!= ')') {
6460 /* read param name and compute offset */
6461 if (l
!= FUNC_OLD
) {
6462 if (!parse_btype(&pt
, &ad1
)) {
6464 error("invalid type");
6471 if ((pt
.t
& VT_BTYPE
) == VT_VOID
&& tok
== ')')
6473 type_decl(&pt
, &ad1
, &n
, TYPE_DIRECT
| TYPE_ABSTRACT
);
6474 if ((pt
.t
& VT_BTYPE
) == VT_VOID
)
6475 error("parameter declared as void");
6482 convert_parameter_type(&pt
);
6483 s
= sym_push(n
| SYM_FIELD
, &pt
, 0, 0);
6488 if (l
== FUNC_NEW
&& tok
== TOK_DOTS
) {
6495 /* if no parameters, then old type prototype */
6499 t1
= type
->t
& VT_STORAGE
;
6500 /* NOTE: const is ignored in returned type as it has a special
6501 meaning in gcc / C++ */
6502 type
->t
&= ~(VT_STORAGE
| VT_CONSTANT
);
6503 post_type(type
, ad
);
6504 /* we push a anonymous symbol which will contain the function prototype */
6505 s
= sym_push(SYM_FIELD
, type
, ad
->func_call
, l
);
6507 type
->t
= t1
| VT_FUNC
;
6509 } else if (tok
== '[') {
6510 /* array definition */
6516 error("invalid array size");
6519 /* parse next post type */
6520 t1
= type
->t
& VT_STORAGE
;
6521 type
->t
&= ~VT_STORAGE
;
6522 post_type(type
, ad
);
6524 /* we push a anonymous symbol which will contain the array
6526 s
= sym_push(SYM_FIELD
, type
, 0, n
);
6527 type
->t
= t1
| VT_ARRAY
| VT_PTR
;
6532 /* Parse a type declaration (except basic type), and return the type
6533 in 'type'. 'td' is a bitmask indicating which kind of type decl is
6534 expected. 'type' should contain the basic type. 'ad' is the
6535 attribute definition of the basic type. It can be modified by
6538 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
)
6541 CType type1
, *type2
;
6544 while (tok
== '*') {
6552 qualifiers
|= VT_CONSTANT
;
6557 qualifiers
|= VT_VOLATILE
;
6565 type
->t
|= qualifiers
;
6568 /* XXX: clarify attribute handling */
6569 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6570 parse_attribute(ad
);
6572 /* recursive type */
6573 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
6574 type1
.t
= 0; /* XXX: same as int */
6577 /* XXX: this is not correct to modify 'ad' at this point, but
6578 the syntax is not clear */
6579 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6580 parse_attribute(ad
);
6581 type_decl(&type1
, ad
, v
, td
);
6584 /* type identifier */
6585 if (tok
>= TOK_IDENT
&& (td
& TYPE_DIRECT
)) {
6589 if (!(td
& TYPE_ABSTRACT
))
6590 expect("identifier");
6594 post_type(type
, ad
);
6595 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6596 parse_attribute(ad
);
6599 /* append type at the end of type1 */
6612 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
6613 static int lvalue_type(int t
)
6618 if (bt
== VT_BYTE
|| bt
== VT_BOOL
)
6620 else if (bt
== VT_SHORT
)
6624 if (t
& VT_UNSIGNED
)
6625 r
|= VT_LVAL_UNSIGNED
;
6629 /* indirection with full error checking and bound check */
6630 static void indir(void)
6632 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
6634 if ((vtop
->r
& VT_LVAL
) && !nocode_wanted
)
6636 vtop
->type
= *pointed_type(&vtop
->type
);
6637 /* an array is never an lvalue */
6638 if (!(vtop
->type
.t
& VT_ARRAY
)) {
6639 vtop
->r
|= lvalue_type(vtop
->type
.t
);
6640 /* if bound checking, the referenced pointer must be checked */
6641 if (do_bounds_check
)
6642 vtop
->r
|= VT_MUSTBOUND
;
6646 /* pass a parameter to a function and do type checking and casting */
6647 static void gfunc_param_typed(Sym
*func
, Sym
*arg
)
6652 func_type
= func
->c
;
6653 if (func_type
== FUNC_OLD
||
6654 (func_type
== FUNC_ELLIPSIS
&& arg
== NULL
)) {
6655 /* default casting : only need to convert float to double */
6656 if ((vtop
->type
.t
& VT_BTYPE
) == VT_FLOAT
) {
6660 } else if (arg
== NULL
) {
6661 error("too many arguments to function");
6664 type
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
6665 gen_assign_cast(&type
);
6669 /* parse an expression of the form '(type)' or '(expr)' and return its
6671 static void parse_expr_type(CType
*type
)
6677 if (parse_btype(type
, &ad
)) {
6678 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
6685 static void parse_type(CType
*type
)
6690 if (!parse_btype(type
, &ad
)) {
6693 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
6696 static void vpush_tokc(int t
)
6700 vsetc(&type
, VT_CONST
, &tokc
);
6703 static void unary(void)
6705 int n
, t
, align
, size
, r
;
6710 /* XXX: GCC 2.95.3 does not generate a table although it should be
6724 vpush_tokc(VT_INT
| VT_UNSIGNED
);
6728 vpush_tokc(VT_LLONG
);
6732 vpush_tokc(VT_LLONG
| VT_UNSIGNED
);
6736 vpush_tokc(VT_FLOAT
);
6740 vpush_tokc(VT_DOUBLE
);
6744 vpush_tokc(VT_LDOUBLE
);
6747 case TOK___FUNCTION__
:
6749 goto tok_identifier
;
6755 /* special function name identifier */
6756 len
= strlen(funcname
) + 1;
6757 /* generate char[len] type */
6762 vpush_ref(&type
, data_section
, data_section
->data_offset
, len
);
6763 ptr
= section_ptr_add(data_section
, len
);
6764 memcpy(ptr
, funcname
, len
);
6772 /* string parsing */
6775 if (tcc_state
->warn_write_strings
)
6780 memset(&ad
, 0, sizeof(AttributeDef
));
6781 decl_initializer_alloc(&type
, &ad
, VT_CONST
, 2, 0, 0);
6786 if (parse_btype(&type
, &ad
)) {
6787 type_decl(&type
, &ad
, &n
, TYPE_ABSTRACT
);
6789 /* check ISOC99 compound literal */
6791 /* data is allocated locally by default */
6796 /* all except arrays are lvalues */
6797 if (!(type
.t
& VT_ARRAY
))
6798 r
|= lvalue_type(type
.t
);
6799 memset(&ad
, 0, sizeof(AttributeDef
));
6800 decl_initializer_alloc(&type
, &ad
, r
, 1, 0, 0);
6805 } else if (tok
== '{') {
6806 /* save all registers */
6808 /* statement expression : we do not accept break/continue
6809 inside as GCC does */
6810 block(NULL
, NULL
, NULL
, NULL
, 0, 1);
6825 /* functions names must be treated as function pointers,
6826 except for unary '&' and sizeof. Since we consider that
6827 functions are not lvalues, we only have to handle it
6828 there and in function calls. */
6829 /* arrays can also be used although they are not lvalues */
6830 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
&&
6831 !(vtop
->type
.t
& VT_ARRAY
))
6833 mk_pointer(&vtop
->type
);
6839 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
)
6840 vtop
->c
.i
= !vtop
->c
.i
;
6841 else if ((vtop
->r
& VT_VALMASK
) == VT_CMP
)
6842 vtop
->c
.i
= vtop
->c
.i
^ 1;
6844 vseti(VT_JMP
, gtst(1, 0));
6854 /* in order to force cast, we add zero */
6856 if ((vtop
->type
.t
& VT_BTYPE
) == VT_PTR
)
6857 error("pointer not accepted for unary plus");
6867 parse_expr_type(&type
);
6871 size
= type_size(&type
, &align
);
6872 if (t
== TOK_SIZEOF
) {
6874 error("sizeof applied to an incomplete type");
6881 case TOK_builtin_types_compatible_p
:
6890 type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6891 type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6892 vpushi(is_compatible_types(&type1
, &type2
));
6895 case TOK_builtin_constant_p
:
6897 int saved_nocode_wanted
, res
;
6900 saved_nocode_wanted
= nocode_wanted
;
6903 res
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
6905 nocode_wanted
= saved_nocode_wanted
;
6925 goto tok_identifier
;
6927 /* allow to take the address of a label */
6928 if (tok
< TOK_UIDENT
)
6929 expect("label identifier");
6930 s
= label_find(tok
);
6932 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
6934 if (s
->r
== LABEL_DECLARED
)
6935 s
->r
= LABEL_FORWARD
;
6938 s
->type
.t
= VT_VOID
;
6939 mk_pointer(&s
->type
);
6940 s
->type
.t
|= VT_STATIC
;
6942 vset(&s
->type
, VT_CONST
| VT_SYM
, 0);
6951 expect("identifier");
6955 error("'%s' undeclared", get_tok_str(t
, NULL
));
6956 /* for simple function calls, we tolerate undeclared
6957 external reference to int() function */
6958 if (tcc_state
->warn_implicit_function_declaration
)
6959 warning("implicit declaration of function '%s'",
6960 get_tok_str(t
, NULL
));
6961 s
= external_global_sym(t
, &func_old_type
, 0);
6963 vset(&s
->type
, s
->r
, s
->c
);
6964 /* if forward reference, we must point to s */
6965 if (vtop
->r
& VT_SYM
) {
6972 /* post operations */
6974 if (tok
== TOK_INC
|| tok
== TOK_DEC
) {
6977 } else if (tok
== '.' || tok
== TOK_ARROW
) {
6979 if (tok
== TOK_ARROW
)
6984 /* expect pointer on structure */
6985 if ((vtop
->type
.t
& VT_BTYPE
) != VT_STRUCT
)
6986 expect("struct or union");
6990 while ((s
= s
->next
) != NULL
) {
6995 error("field not found");
6996 /* add field offset to pointer */
6997 vtop
->type
= char_pointer_type
; /* change type to 'char *' */
7000 /* change type to field type, and set to lvalue */
7001 vtop
->type
= s
->type
;
7002 /* an array is never an lvalue */
7003 if (!(vtop
->type
.t
& VT_ARRAY
)) {
7004 vtop
->r
|= lvalue_type(vtop
->type
.t
);
7005 /* if bound checking, the referenced pointer must be checked */
7006 if (do_bounds_check
)
7007 vtop
->r
|= VT_MUSTBOUND
;
7010 } else if (tok
== '[') {
7016 } else if (tok
== '(') {
7022 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
) {
7023 /* pointer test (no array accepted) */
7024 if ((vtop
->type
.t
& (VT_BTYPE
| VT_ARRAY
)) == VT_PTR
) {
7025 vtop
->type
= *pointed_type(&vtop
->type
);
7026 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
)
7030 expect("function pointer");
7033 vtop
->r
&= ~VT_LVAL
; /* no lvalue */
7035 /* get return type */
7038 sa
= s
->next
; /* first parameter */
7040 /* compute first implicit argument if a structure is returned */
7041 if ((s
->type
.t
& VT_BTYPE
) == VT_STRUCT
) {
7042 /* get some space for the returned structure */
7043 size
= type_size(&s
->type
, &align
);
7044 loc
= (loc
- size
) & -align
;
7046 ret
.r
= VT_LOCAL
| VT_LVAL
;
7047 /* pass it as 'int' to avoid structure arg passing
7049 vseti(VT_LOCAL
, loc
);
7055 /* return in register */
7056 if (is_float(ret
.type
.t
)) {
7059 if ((ret
.type
.t
& VT_BTYPE
) == VT_LLONG
)
7068 gfunc_param_typed(s
, sa
);
7078 error("too few arguments to function");
7080 if (!nocode_wanted
) {
7081 gfunc_call(nb_args
);
7083 vtop
-= (nb_args
+ 1);
7086 vsetc(&ret
.type
, ret
.r
, &ret
.c
);
7094 static void uneq(void)
7100 (tok
>= TOK_A_MOD
&& tok
<= TOK_A_DIV
) ||
7101 tok
== TOK_A_XOR
|| tok
== TOK_A_OR
||
7102 tok
== TOK_A_SHL
|| tok
== TOK_A_SAR
) {
7117 static void expr_prod(void)
7122 while (tok
== '*' || tok
== '/' || tok
== '%') {
7130 static void expr_sum(void)
7135 while (tok
== '+' || tok
== '-') {
7143 static void expr_shift(void)
7148 while (tok
== TOK_SHL
|| tok
== TOK_SAR
) {
7156 static void expr_cmp(void)
7161 while ((tok
>= TOK_ULE
&& tok
<= TOK_GT
) ||
7162 tok
== TOK_ULT
|| tok
== TOK_UGE
) {
7170 static void expr_cmpeq(void)
7175 while (tok
== TOK_EQ
|| tok
== TOK_NE
) {
7183 static void expr_and(void)
7186 while (tok
== '&') {
7193 static void expr_xor(void)
7196 while (tok
== '^') {
7203 static void expr_or(void)
7206 while (tok
== '|') {
7213 /* XXX: fix this mess */
7214 static void expr_land_const(void)
7217 while (tok
== TOK_LAND
) {
7224 /* XXX: fix this mess */
7225 static void expr_lor_const(void)
7228 while (tok
== TOK_LOR
) {
7235 /* only used if non constant */
7236 static void expr_land(void)
7241 if (tok
== TOK_LAND
) {
7245 if (tok
!= TOK_LAND
) {
7255 static void expr_lor(void)
7260 if (tok
== TOK_LOR
) {
7264 if (tok
!= TOK_LOR
) {
7274 /* XXX: better constant handling */
7275 static void expr_eq(void)
7277 int tt
, u
, r1
, r2
, rc
, t1
, t2
, bt1
, bt2
;
7279 CType type
, type1
, type2
;
7288 if (tok
== ':' && gnu_ext
) {
7304 if (vtop
!= vstack
) {
7305 /* needed to avoid having different registers saved in
7307 if (is_float(vtop
->type
.t
))
7314 if (tok
== ':' && gnu_ext
) {
7322 sv
= *vtop
; /* save value to handle it later */
7323 vtop
--; /* no vpop so that FP stack is not flushed */
7331 bt1
= t1
& VT_BTYPE
;
7333 bt2
= t2
& VT_BTYPE
;
7334 /* cast operands to correct type according to ISOC rules */
7335 if (is_float(bt1
) || is_float(bt2
)) {
7336 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
7337 type
.t
= VT_LDOUBLE
;
7338 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
7343 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
7344 /* cast to biggest op */
7346 /* convert to unsigned if it does not fit in a long long */
7347 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
7348 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
7349 type
.t
|= VT_UNSIGNED
;
7350 } else if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
7351 /* XXX: test pointer compatibility */
7353 } else if (bt1
== VT_STRUCT
|| bt2
== VT_STRUCT
) {
7354 /* XXX: test structure compatibility */
7356 } else if (bt1
== VT_VOID
|| bt2
== VT_VOID
) {
7357 /* NOTE: as an extension, we accept void on only one side */
7360 /* integer operations */
7362 /* convert to unsigned if it does not fit in an integer */
7363 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
7364 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
7365 type
.t
|= VT_UNSIGNED
;
7368 /* now we convert second operand */
7371 if (is_float(type
.t
)) {
7373 } else if ((type
.t
& VT_BTYPE
) == VT_LLONG
) {
7374 /* for long longs, we use fixed registers to avoid having
7375 to handle a complicated move */
7380 /* this is horrible, but we must also convert first
7384 /* put again first value and cast it */
7395 static void gexpr(void)
7406 /* parse an expression and return its type without any side effect. */
7407 static void expr_type(CType
*type
)
7409 int saved_nocode_wanted
;
7411 saved_nocode_wanted
= nocode_wanted
;
7416 nocode_wanted
= saved_nocode_wanted
;
7419 /* parse a unary expression and return its type without any side
7421 static void unary_type(CType
*type
)
7433 /* parse a constant expression and return value in vtop. */
7434 static void expr_const1(void)
7443 /* parse an integer constant and return its value. */
7444 static int expr_const(void)
7448 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
7449 expect("constant expression");
7455 /* return the label token if current token is a label, otherwise
7457 static int is_label(void)
7461 /* fast test first */
7462 if (tok
< TOK_UIDENT
)
7464 /* no need to save tokc because tok is an identifier */
7471 unget_tok(last_tok
);
7476 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
7477 int case_reg
, int is_expr
)
7482 /* generate line number info */
7484 (last_line_num
!= file
->line_num
|| last_ind
!= ind
)) {
7485 put_stabn(N_SLINE
, 0, file
->line_num
, ind
- func_ind
);
7487 last_line_num
= file
->line_num
;
7491 /* default return value is (void) */
7493 vtop
->type
.t
= VT_VOID
;
7496 if (tok
== TOK_IF
) {
7503 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7505 if (c
== TOK_ELSE
) {
7509 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7510 gsym(d
); /* patch else jmp */
7513 } else if (tok
== TOK_WHILE
) {
7521 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7525 } else if (tok
== '{') {
7529 /* record local declaration stack position */
7531 llabel
= local_label_stack
;
7532 /* handle local labels declarations */
7533 if (tok
== TOK_LABEL
) {
7536 if (tok
< TOK_UIDENT
)
7537 expect("label identifier");
7538 label_push(&local_label_stack
, tok
, LABEL_DECLARED
);
7548 while (tok
!= '}') {
7553 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
7556 /* pop locally defined labels */
7557 label_pop(&local_label_stack
, llabel
);
7558 /* pop locally defined symbols */
7559 sym_pop(&local_stack
, s
);
7561 } else if (tok
== TOK_RETURN
) {
7565 gen_assign_cast(&func_vt
);
7566 if ((func_vt
.t
& VT_BTYPE
) == VT_STRUCT
) {
7568 /* if returning structure, must copy it to implicit
7569 first pointer arg location */
7572 vset(&type
, VT_LOCAL
| VT_LVAL
, func_vc
);
7575 /* copy structure value to pointer */
7577 } else if (is_float(func_vt
.t
)) {
7582 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
7585 rsym
= gjmp(rsym
); /* jmp */
7586 } else if (tok
== TOK_BREAK
) {
7589 error("cannot break");
7590 *bsym
= gjmp(*bsym
);
7593 } else if (tok
== TOK_CONTINUE
) {
7596 error("cannot continue");
7597 *csym
= gjmp(*csym
);
7600 } else if (tok
== TOK_FOR
) {
7627 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7632 if (tok
== TOK_DO
) {
7637 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7648 if (tok
== TOK_SWITCH
) {
7652 /* XXX: other types than integer */
7653 case_reg
= gv(RC_INT
);
7657 b
= gjmp(0); /* jump to first case */
7659 block(&a
, csym
, &b
, &c
, case_reg
, 0);
7660 /* if no default, jmp after switch */
7668 if (tok
== TOK_CASE
) {
7675 if (gnu_ext
&& tok
== TOK_DOTS
) {
7679 warning("empty case range");
7681 /* since a case is like a label, we must skip it with a jmp */
7688 *case_sym
= gtst(1, 0);
7691 *case_sym
= gtst(1, 0);
7695 *case_sym
= gtst(1, *case_sym
);
7700 goto block_after_label
;
7702 if (tok
== TOK_DEFAULT
) {
7708 error("too many 'default'");
7711 goto block_after_label
;
7713 if (tok
== TOK_GOTO
) {
7715 if (tok
== '*' && gnu_ext
) {
7719 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
7722 } else if (tok
>= TOK_UIDENT
) {
7723 s
= label_find(tok
);
7724 /* put forward definition if needed */
7726 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
7728 if (s
->r
== LABEL_DECLARED
)
7729 s
->r
= LABEL_FORWARD
;
7731 /* label already defined */
7732 if (s
->r
& LABEL_FORWARD
)
7733 s
->next
= (void *)gjmp((long)s
->next
);
7735 gjmp_addr((long)s
->next
);
7738 expect("label identifier");
7741 } else if (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
) {
7749 if (s
->r
== LABEL_DEFINED
)
7750 error("duplicate label '%s'", get_tok_str(s
->v
, NULL
));
7751 gsym((long)s
->next
);
7752 s
->r
= LABEL_DEFINED
;
7754 s
= label_push(&global_label_stack
, b
, LABEL_DEFINED
);
7756 s
->next
= (void *)ind
;
7757 /* we accept this, but it is a mistake */
7760 warning("deprecated use of label at end of compound statement");
7764 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
7767 /* expression case */
7782 /* t is the array or struct type. c is the array or struct
7783 address. cur_index/cur_field is the pointer to the current
7784 value. 'size_only' is true if only size info is needed (only used
7786 static void decl_designator(CType
*type
, Section
*sec
, unsigned long c
,
7787 int *cur_index
, Sym
**cur_field
,
7791 int notfirst
, index
, index_last
, align
, l
, nb_elems
, elem_size
;
7797 if (gnu_ext
&& (l
= is_label()) != 0)
7799 while (tok
== '[' || tok
== '.') {
7801 if (!(type
->t
& VT_ARRAY
))
7802 expect("array type");
7805 index
= expr_const();
7806 if (index
< 0 || (s
->c
>= 0 && index
>= s
->c
))
7807 expect("invalid index");
7808 if (tok
== TOK_DOTS
&& gnu_ext
) {
7810 index_last
= expr_const();
7811 if (index_last
< 0 ||
7812 (s
->c
>= 0 && index_last
>= s
->c
) ||
7814 expect("invalid index");
7820 *cur_index
= index_last
;
7821 type
= pointed_type(type
);
7822 elem_size
= type_size(type
, &align
);
7823 c
+= index
* elem_size
;
7824 /* NOTE: we only support ranges for last designator */
7825 nb_elems
= index_last
- index
+ 1;
7826 if (nb_elems
!= 1) {
7835 if ((type
->t
& VT_BTYPE
) != VT_STRUCT
)
7836 expect("struct/union type");
7849 /* XXX: fix this mess by using explicit storage field */
7851 type1
.t
|= (type
->t
& ~VT_TYPE
);
7865 if (type
->t
& VT_ARRAY
) {
7867 type
= pointed_type(type
);
7868 c
+= index
* type_size(type
, &align
);
7872 error("too many field init");
7873 /* XXX: fix this mess by using explicit storage field */
7875 type1
.t
|= (type
->t
& ~VT_TYPE
);
7880 decl_initializer(type
, sec
, c
, 0, size_only
);
7882 /* XXX: make it more general */
7883 if (!size_only
&& nb_elems
> 1) {
7884 unsigned long c_end
;
7889 error("range init not supported yet for dynamic storage");
7890 c_end
= c
+ nb_elems
* elem_size
;
7891 if (c_end
> sec
->data_allocated
)
7892 section_realloc(sec
, c_end
);
7893 src
= sec
->data
+ c
;
7895 for(i
= 1; i
< nb_elems
; i
++) {
7897 memcpy(dst
, src
, elem_size
);
7903 #define EXPR_CONST 1
7906 /* store a value or an expression directly in global data or in local array */
7907 static void init_putv(CType
*type
, Section
*sec
, unsigned long c
,
7908 int v
, int expr_type
)
7910 int saved_global_expr
, bt
, bit_pos
, bit_size
;
7912 unsigned long long bit_mask
;
7920 /* compound literals must be allocated globally in this case */
7921 saved_global_expr
= global_expr
;
7924 global_expr
= saved_global_expr
;
7925 /* NOTE: symbols are accepted */
7926 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) != VT_CONST
)
7927 error("initializer element is not constant");
7935 dtype
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
7938 /* XXX: not portable */
7939 /* XXX: generate error if incorrect relocation */
7940 gen_assign_cast(&dtype
);
7941 bt
= type
->t
& VT_BTYPE
;
7942 ptr
= sec
->data
+ c
;
7943 /* XXX: make code faster ? */
7944 if (!(type
->t
& VT_BITFIELD
)) {
7949 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
7950 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
7951 bit_mask
= (1LL << bit_size
) - 1;
7953 if ((vtop
->r
& VT_SYM
) &&
7959 (bt
== VT_INT
&& bit_size
!= 32)))
7960 error("initializer element is not computable at load time");
7963 *(char *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
7966 *(short *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
7969 *(double *)ptr
= vtop
->c
.d
;
7972 *(long double *)ptr
= vtop
->c
.ld
;
7975 *(long long *)ptr
|= (vtop
->c
.ll
& bit_mask
) << bit_pos
;
7978 if (vtop
->r
& VT_SYM
) {
7979 greloc(sec
, vtop
->sym
, c
, R_DATA_32
);
7981 *(int *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
7986 vset(&dtype
, VT_LOCAL
, c
);
7993 /* put zeros for variable based init */
7994 static void init_putz(CType
*t
, Section
*sec
, unsigned long c
, int size
)
7997 /* nothing to do because globals are already set to zero */
7999 vpush_global_sym(&func_old_type
, TOK_memset
);
8007 /* 't' contains the type and storage info. 'c' is the offset of the
8008 object in section 'sec'. If 'sec' is NULL, it means stack based
8009 allocation. 'first' is true if array '{' must be read (multi
8010 dimension implicit array init handling). 'size_only' is true if
8011 size only evaluation is wanted (only for arrays). */
8012 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
8013 int first
, int size_only
)
8015 int index
, array_length
, n
, no_oblock
, nb
, parlevel
, i
;
8016 int size1
, align1
, expr_type
;
8020 if (type
->t
& VT_ARRAY
) {
8024 t1
= pointed_type(type
);
8025 size1
= type_size(t1
, &align1
);
8028 if ((first
&& tok
!= TOK_LSTR
&& tok
!= TOK_STR
) ||
8034 /* only parse strings here if correct type (otherwise: handle
8035 them as ((w)char *) expressions */
8036 if ((tok
== TOK_LSTR
&&
8037 (t1
->t
& VT_BTYPE
) == VT_INT
) ||
8039 (t1
->t
& VT_BTYPE
) == VT_BYTE
)) {
8040 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
8045 /* compute maximum number of chars wanted */
8047 cstr_len
= cstr
->size
;
8049 cstr_len
= cstr
->size
/ sizeof(int);
8052 if (n
>= 0 && nb
> (n
- array_length
))
8053 nb
= n
- array_length
;
8056 warning("initializer-string for array is too long");
8057 /* in order to go faster for common case (char
8058 string in global variable, we handle it
8060 if (sec
&& tok
== TOK_STR
&& size1
== 1) {
8061 memcpy(sec
->data
+ c
+ array_length
, cstr
->data
, nb
);
8065 ch
= ((unsigned char *)cstr
->data
)[i
];
8067 ch
= ((int *)cstr
->data
)[i
];
8068 init_putv(t1
, sec
, c
+ (array_length
+ i
) * size1
,
8076 /* only add trailing zero if enough storage (no
8077 warning in this case since it is standard) */
8078 if (n
< 0 || array_length
< n
) {
8080 init_putv(t1
, sec
, c
+ (array_length
* size1
), 0, EXPR_VAL
);
8086 while (tok
!= '}') {
8087 decl_designator(type
, sec
, c
, &index
, NULL
, size_only
);
8088 if (n
>= 0 && index
>= n
)
8089 error("index too large");
8090 /* must put zero in holes (note that doing it that way
8091 ensures that it even works with designators) */
8092 if (!size_only
&& array_length
< index
) {
8093 init_putz(t1
, sec
, c
+ array_length
* size1
,
8094 (index
- array_length
) * size1
);
8097 if (index
> array_length
)
8098 array_length
= index
;
8099 /* special test for multi dimensional arrays (may not
8100 be strictly correct if designators are used at the
8102 if (index
>= n
&& no_oblock
)
8111 /* put zeros at the end */
8112 if (!size_only
&& n
>= 0 && array_length
< n
) {
8113 init_putz(t1
, sec
, c
+ array_length
* size1
,
8114 (n
- array_length
) * size1
);
8116 /* patch type size if needed */
8118 s
->c
= array_length
;
8119 } else if ((type
->t
& VT_BTYPE
) == VT_STRUCT
&&
8120 (sec
|| !first
|| tok
== '{')) {
8123 /* NOTE: the previous test is a specific case for automatic
8124 struct/union init */
8125 /* XXX: union needs only one init */
8127 /* XXX: this test is incorrect for local initializers
8128 beginning with ( without {. It would be much more difficult
8129 to do it correctly (ideally, the expression parser should
8130 be used in all cases) */
8136 while (tok
== '(') {
8140 if (!parse_btype(&type1
, &ad1
))
8142 type_decl(&type1
, &ad1
, &n
, TYPE_ABSTRACT
);
8144 if (!is_assignable_types(type
, &type1
))
8145 error("invalid type for cast");
8150 if (first
|| tok
== '{') {
8159 while (tok
!= '}') {
8160 decl_designator(type
, sec
, c
, NULL
, &f
, size_only
);
8162 if (!size_only
&& array_length
< index
) {
8163 init_putz(type
, sec
, c
+ array_length
,
8164 index
- array_length
);
8166 index
= index
+ type_size(&f
->type
, &align1
);
8167 if (index
> array_length
)
8168 array_length
= index
;
8170 if (no_oblock
&& f
== NULL
)
8176 /* put zeros at the end */
8177 if (!size_only
&& array_length
< n
) {
8178 init_putz(type
, sec
, c
+ array_length
,
8187 } else if (tok
== '{') {
8189 decl_initializer(type
, sec
, c
, first
, size_only
);
8191 } else if (size_only
) {
8192 /* just skip expression */
8194 while ((parlevel
> 0 || (tok
!= '}' && tok
!= ',')) &&
8198 else if (tok
== ')')
8203 /* currently, we always use constant expression for globals
8204 (may change for scripting case) */
8205 expr_type
= EXPR_CONST
;
8207 expr_type
= EXPR_ANY
;
8208 init_putv(type
, sec
, c
, 0, expr_type
);
8212 /* parse an initializer for type 't' if 'has_init' is non zero, and
8213 allocate space in local or global data space ('r' is either
8214 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
8215 variable 'v' of scope 'scope' is declared before initializers are
8216 parsed. If 'v' is zero, then a reference to the new object is put
8217 in the value stack. If 'has_init' is 2, a special parsing is done
8218 to handle string constants. */
8219 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
8220 int has_init
, int v
, int scope
)
8222 int size
, align
, addr
, data_offset
;
8224 ParseState saved_parse_state
;
8225 TokenString init_str
;
8228 size
= type_size(type
, &align
);
8229 /* If unknown size, we must evaluate it before
8230 evaluating initializers because
8231 initializers can generate global data too
8232 (e.g. string pointers or ISOC99 compound
8233 literals). It also simplifies local
8234 initializers handling */
8235 tok_str_new(&init_str
);
8238 error("unknown type size");
8239 /* get all init string */
8240 if (has_init
== 2) {
8241 /* only get strings */
8242 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
8243 tok_str_add_tok(&init_str
);
8248 while (level
> 0 || (tok
!= ',' && tok
!= ';')) {
8250 error("unexpected end of file in initializer");
8251 tok_str_add_tok(&init_str
);
8254 else if (tok
== '}') {
8262 tok_str_add(&init_str
, -1);
8263 tok_str_add(&init_str
, 0);
8266 save_parse_state(&saved_parse_state
);
8268 macro_ptr
= init_str
.str
;
8270 decl_initializer(type
, NULL
, 0, 1, 1);
8271 /* prepare second initializer parsing */
8272 macro_ptr
= init_str
.str
;
8275 /* if still unknown size, error */
8276 size
= type_size(type
, &align
);
8278 error("unknown type size");
8280 /* take into account specified alignment if bigger */
8281 if (ad
->aligned
> align
)
8282 align
= ad
->aligned
;
8283 if ((r
& VT_VALMASK
) == VT_LOCAL
) {
8285 if (do_bounds_check
&& (type
->t
& VT_ARRAY
))
8287 loc
= (loc
- size
) & -align
;
8289 /* handles bounds */
8290 /* XXX: currently, since we do only one pass, we cannot track
8291 '&' operators, so we add only arrays */
8292 if (do_bounds_check
&& (type
->t
& VT_ARRAY
)) {
8293 unsigned long *bounds_ptr
;
8294 /* add padding between regions */
8296 /* then add local bound info */
8297 bounds_ptr
= section_ptr_add(lbounds_section
, 2 * sizeof(unsigned long));
8298 bounds_ptr
[0] = addr
;
8299 bounds_ptr
[1] = size
;
8302 /* local variable */
8303 sym_push(v
, type
, r
, addr
);
8305 /* push local reference */
8306 vset(type
, r
, addr
);
8312 if (v
&& scope
== VT_CONST
) {
8313 /* see if the symbol was already defined */
8316 if (!is_compatible_types(&sym
->type
, type
))
8317 error("incompatible types for redefinition of '%s'",
8318 get_tok_str(v
, NULL
));
8319 if (sym
->type
.t
& VT_EXTERN
) {
8320 /* if the variable is extern, it was not allocated */
8321 sym
->type
.t
&= ~VT_EXTERN
;
8323 /* we accept several definitions of the same
8324 global variable. this is tricky, because we
8325 must play with the SHN_COMMON type of the symbol */
8326 /* XXX: should check if the variable was already
8327 initialized. It is incorrect to initialized it
8329 /* no init data, we won't add more to the symbol */
8336 /* allocate symbol in corresponding section */
8343 data_offset
= sec
->data_offset
;
8344 data_offset
= (data_offset
+ align
- 1) & -align
;
8346 /* very important to increment global pointer at this time
8347 because initializers themselves can create new initializers */
8348 data_offset
+= size
;
8349 /* add padding if bound check */
8350 if (do_bounds_check
)
8352 sec
->data_offset
= data_offset
;
8353 /* allocate section space to put the data */
8354 if (sec
->sh_type
!= SHT_NOBITS
&&
8355 data_offset
> sec
->data_allocated
)
8356 section_realloc(sec
, data_offset
);
8358 addr
= 0; /* avoid warning */
8362 if (scope
== VT_CONST
) {
8367 sym
= sym_push(v
, type
, r
| VT_SYM
, 0);
8369 /* update symbol definition */
8371 put_extern_sym(sym
, sec
, addr
, size
);
8374 /* put a common area */
8375 put_extern_sym(sym
, NULL
, align
, size
);
8376 /* XXX: find a nicer way */
8377 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
8378 esym
->st_shndx
= SHN_COMMON
;
8383 /* push global reference */
8384 sym
= get_sym_ref(type
, sec
, addr
, size
);
8386 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
8390 /* handles bounds now because the symbol must be defined
8391 before for the relocation */
8392 if (do_bounds_check
) {
8393 unsigned long *bounds_ptr
;
8395 greloc(bounds_section
, sym
, bounds_section
->data_offset
, R_DATA_32
);
8396 /* then add global bound info */
8397 bounds_ptr
= section_ptr_add(bounds_section
, 2 * sizeof(long));
8398 bounds_ptr
[0] = 0; /* relocated */
8399 bounds_ptr
[1] = size
;
8403 decl_initializer(type
, sec
, addr
, 1, 0);
8404 /* restore parse state if needed */
8406 tok_str_free(init_str
.str
);
8407 restore_parse_state(&saved_parse_state
);
8413 void put_func_debug(Sym
*sym
)
8418 /* XXX: we put here a dummy type */
8419 snprintf(buf
, sizeof(buf
), "%s:%c1",
8420 funcname
, sym
->type
.t
& VT_STATIC
? 'f' : 'F');
8421 put_stabs_r(buf
, N_FUN
, 0, file
->line_num
, 0,
8422 cur_text_section
, sym
->c
);
8427 /* not finished : try to put some local vars in registers */
8428 //#define CONFIG_REG_VARS
8430 #ifdef CONFIG_REG_VARS
8431 void add_var_ref(int t
)
8433 printf("%s:%d: &%s\n",
8434 file
->filename
, file
->line_num
,
8435 get_tok_str(t
, NULL
));
8438 /* first pass on a function with heuristic to extract variable usage
8439 and pointer references to local variables for register allocation */
8440 void analyse_function(void)
8447 /* any symbol coming after '&' is considered as being a
8448 variable whose reference is taken. It is highly unaccurate
8449 but it is difficult to do better without a complete parse */
8452 /* if '& number', then no need to examine next tokens */
8453 if (tok
== TOK_CINT
||
8455 tok
== TOK_CLLONG
||
8456 tok
== TOK_CULLONG
) {
8458 } else if (tok
>= TOK_UIDENT
) {
8459 /* if '& ident [' or '& ident ->', then ident address
8463 if (tok
!= '[' && tok
!= TOK_ARROW
)
8467 while (tok
!= '}' && tok
!= ';' &&
8468 !((tok
== ',' || tok
== ')') && level
== 0)) {
8469 if (tok
>= TOK_UIDENT
) {
8471 } else if (tok
== '(') {
8473 } else if (tok
== ')') {
8486 /* parse an old style function declaration list */
8487 /* XXX: check multiple parameter */
8488 static void func_decl_list(Sym
*func_sym
)
8495 /* parse each declaration */
8496 while (tok
!= '{' && tok
!= ';' && tok
!= ',' && tok
!= TOK_EOF
) {
8497 if (!parse_btype(&btype
, &ad
))
8498 expect("declaration list");
8499 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
8500 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
8502 /* we accept no variable after */
8506 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
8507 /* find parameter in function parameter list */
8510 if ((s
->v
& ~SYM_FIELD
) == v
)
8514 error("declaration for parameter '%s' but no such parameter",
8515 get_tok_str(v
, NULL
));
8517 /* check that no storage specifier except 'register' was given */
8518 if (type
.t
& VT_STORAGE
)
8519 error("storage class specified for '%s'", get_tok_str(v
, NULL
));
8520 convert_parameter_type(&type
);
8521 /* we can add the type (NOTE: it could be local to the function) */
8523 /* accept other parameters */
8534 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
8535 static void decl(int l
)
8543 if (!parse_btype(&btype
, &ad
)) {
8544 /* skip redundant ';' */
8545 /* XXX: find more elegant solution */
8550 /* special test for old K&R protos without explicit int
8551 type. Only accepted when defining global data */
8552 if (l
== VT_LOCAL
|| tok
< TOK_DEFINE
)
8556 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
8557 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
8559 /* we accept no variable after */
8563 while (1) { /* iterate thru each declaration */
8565 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
8569 type_to_str(buf
, sizeof(buf
), t
, get_tok_str(v
, NULL
));
8570 printf("type = '%s'\n", buf
);
8573 if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
8574 /* if old style function prototype, we accept a
8577 if (sym
->c
== FUNC_OLD
)
8578 func_decl_list(sym
);
8582 #ifdef CONFIG_REG_VARS
8583 TokenString func_str
;
8584 ParseState saved_parse_state
;
8589 error("cannot use local functions");
8590 if (!(type
.t
& VT_FUNC
))
8591 expect("function definition");
8593 /* reject abstract declarators in function definition */
8595 while ((sym
= sym
->next
) != NULL
)
8596 if (!(sym
->v
& ~SYM_FIELD
))
8597 expect("identifier");
8599 /* XXX: cannot do better now: convert extern line to static inline */
8600 if ((type
.t
& (VT_EXTERN
| VT_INLINE
)) == (VT_EXTERN
| VT_INLINE
))
8601 type
.t
= (type
.t
& ~VT_EXTERN
) | VT_STATIC
;
8603 #ifdef CONFIG_REG_VARS
8604 /* parse all function code and record it */
8606 tok_str_new(&func_str
);
8612 error("unexpected end of file");
8613 tok_str_add_tok(&func_str
);
8618 } else if (t
== '}') {
8620 if (block_level
== 0)
8624 tok_str_add(&func_str
, -1);
8625 tok_str_add(&func_str
, 0);
8627 save_parse_state(&saved_parse_state
);
8629 macro_ptr
= func_str
.str
;
8634 /* compute text section */
8635 cur_text_section
= ad
.section
;
8636 if (!cur_text_section
)
8637 cur_text_section
= text_section
;
8638 ind
= cur_text_section
->data_offset
;
8639 funcname
= get_tok_str(v
, NULL
);
8642 /* if symbol is already defined, then put complete type */
8645 /* put function symbol */
8646 sym
= global_identifier_push(v
, type
.t
, 0);
8647 sym
->type
.ref
= type
.ref
;
8649 /* NOTE: we patch the symbol size later */
8650 put_extern_sym(sym
, cur_text_section
, ind
, 0);
8652 sym
->r
= VT_SYM
| VT_CONST
;
8653 /* put debug symbol */
8655 put_func_debug(sym
);
8656 /* push a dummy symbol to enable local sym storage */
8657 sym_push2(&local_stack
, SYM_FIELD
, 0, 0);
8658 gfunc_prolog(&type
);
8661 #ifdef CONFIG_REG_VARS
8662 macro_ptr
= func_str
.str
;
8665 block(NULL
, NULL
, NULL
, NULL
, 0, 0);
8668 cur_text_section
->data_offset
= ind
;
8669 label_pop(&global_label_stack
, NULL
);
8670 sym_pop(&local_stack
, NULL
); /* reset local stack */
8671 /* end of function */
8672 /* patch symbol size */
8673 ((Elf32_Sym
*)symtab_section
->data
)[sym
->c
].st_size
=
8676 put_stabn(N_FUN
, 0, 0, ind
- func_ind
);
8678 funcname
= ""; /* for safety */
8679 func_vt
.t
= VT_VOID
; /* for safety */
8680 ind
= 0; /* for safety */
8682 #ifdef CONFIG_REG_VARS
8683 tok_str_free(func_str
.str
);
8684 restore_parse_state(&saved_parse_state
);
8688 if (btype
.t
& VT_TYPEDEF
) {
8689 /* save typedefed type */
8690 /* XXX: test storage specifiers ? */
8691 sym
= sym_push(v
, &type
, 0, 0);
8692 sym
->type
.t
|= VT_TYPEDEF
;
8693 } else if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
8694 /* external function definition */
8695 external_sym(v
, &type
, 0);
8697 /* not lvalue if array */
8699 if (!(type
.t
& VT_ARRAY
))
8700 r
|= lvalue_type(type
.t
);
8701 has_init
= (tok
== '=');
8702 if ((btype
.t
& VT_EXTERN
) ||
8703 ((type
.t
& VT_ARRAY
) && (type
.t
& VT_STATIC
) &&
8704 !has_init
&& l
== VT_CONST
&& type
.ref
->c
< 0)) {
8705 /* external variable */
8706 /* NOTE: as GCC, uninitialized global static
8707 arrays of null size are considered as
8709 external_sym(v
, &type
, r
);
8711 if (type
.t
& VT_STATIC
)
8717 decl_initializer_alloc(&type
, &ad
, r
,
8731 /* better than nothing, but needs extension to handle '-E' option
8733 static void preprocess_init(TCCState
*s1
)
8735 s1
->include_stack_ptr
= s1
->include_stack
;
8736 /* XXX: move that before to avoid having to initialize
8737 file->ifdef_stack_ptr ? */
8738 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
8739 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
8741 /* XXX: not ANSI compliant: bound checking says error */
8745 /* compile the C file opened in 'file'. Return non zero if errors. */
8746 static int tcc_compile(TCCState
*s1
)
8750 volatile int section_sym
;
8753 printf("%s: **** new file\n", file
->filename
);
8755 preprocess_init(s1
);
8758 anon_sym
= SYM_FIRST_ANOM
;
8760 /* file info: full path + filename */
8761 section_sym
= 0; /* avoid warning */
8763 section_sym
= put_elf_sym(symtab_section
, 0, 0,
8764 ELF32_ST_INFO(STB_LOCAL
, STT_SECTION
), 0,
8765 text_section
->sh_num
, NULL
);
8766 getcwd(buf
, sizeof(buf
));
8767 pstrcat(buf
, sizeof(buf
), "/");
8768 put_stabs_r(buf
, N_SO
, 0, 0,
8769 text_section
->data_offset
, text_section
, section_sym
);
8770 put_stabs_r(file
->filename
, N_SO
, 0, 0,
8771 text_section
->data_offset
, text_section
, section_sym
);
8773 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
8774 symbols can be safely used */
8775 put_elf_sym(symtab_section
, 0, 0,
8776 ELF32_ST_INFO(STB_LOCAL
, STT_FILE
), 0,
8777 SHN_ABS
, file
->filename
);
8779 /* define some often used types */
8780 int_type
.t
= VT_INT
;
8782 char_pointer_type
.t
= VT_BYTE
;
8783 mk_pointer(&char_pointer_type
);
8785 func_old_type
.t
= VT_FUNC
;
8786 func_old_type
.ref
= sym_push(SYM_FIELD
, &int_type
, FUNC_CDECL
, FUNC_OLD
);
8789 /* define 'void *alloca(unsigned int)' builtin function */
8794 sym
= sym_push(p
, mk_pointer(VT_VOID
), FUNC_CDECL
, FUNC_NEW
);
8795 s1
= sym_push(SYM_FIELD
, VT_UNSIGNED
| VT_INT
, 0, 0);
8798 sym_push(TOK_alloca
, VT_FUNC
| (p
<< VT_STRUCT_SHIFT
), VT_CONST
, 0);
8802 define_start
= define_stack
;
8804 if (setjmp(s1
->error_jmp_buf
) == 0) {
8806 s1
->error_set_jmp_enabled
= 1;
8808 ch
= file
->buf_ptr
[0];
8809 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
8810 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
;
8814 expect("declaration");
8816 /* end of translation unit info */
8818 put_stabs_r(NULL
, N_SO
, 0, 0,
8819 text_section
->data_offset
, text_section
, section_sym
);
8822 s1
->error_set_jmp_enabled
= 0;
8824 /* reset define stack, but leave -Dsymbols (may be incorrect if
8825 they are undefined) */
8826 free_defines(define_start
);
8828 sym_pop(&global_stack
, NULL
);
8830 return s1
->nb_errors
!= 0 ? -1 : 0;
8834 int tcc_compile_string(TCCState
*s
, const char *str
)
8836 BufferedFile bf1
, *bf
= &bf1
;
8840 /* init file structure */
8842 /* XXX: avoid copying */
8844 buf
= tcc_malloc(len
+ 1);
8847 memcpy(buf
, str
, len
);
8850 bf
->buf_end
= buf
+ len
;
8851 pstrcpy(bf
->filename
, sizeof(bf
->filename
), "<string>");
8855 ret
= tcc_compile(s
);
8859 /* currently, no need to close */
8864 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
8865 void tcc_define_symbol(TCCState
*s1
, const char *sym
, const char *value
)
8867 BufferedFile bf1
, *bf
= &bf1
;
8869 pstrcpy(bf
->buffer
, IO_BUF_SIZE
, sym
);
8870 pstrcat(bf
->buffer
, IO_BUF_SIZE
, " ");
8874 pstrcat(bf
->buffer
, IO_BUF_SIZE
, value
);
8876 /* init file structure */
8878 bf
->buf_ptr
= bf
->buffer
;
8879 bf
->buf_end
= bf
->buffer
+ strlen(bf
->buffer
);
8880 *bf
->buf_end
= CH_EOB
;
8881 bf
->filename
[0] = '\0';
8885 s1
->include_stack_ptr
= s1
->include_stack
;
8887 /* parse with define parser */
8888 ch
= file
->buf_ptr
[0];
8894 /* undefine a preprocessor symbol */
8895 void tcc_undefine_symbol(TCCState
*s1
, const char *sym
)
8899 ts
= tok_alloc(sym
, strlen(sym
));
8900 s
= define_find(ts
->tok
);
8901 /* undefine symbol by putting an invalid name */
8906 #ifdef CONFIG_TCC_ASM
8908 #ifdef TCC_TARGET_I386
8909 #include "i386-asm.c"
8914 static void asm_instr(void)
8916 error("inline asm() not supported");
8922 /* print the position in the source file of PC value 'pc' by reading
8923 the stabs debug information */
8924 static void rt_printline(unsigned long wanted_pc
)
8926 Stab_Sym
*sym
, *sym_end
;
8927 char func_name
[128], last_func_name
[128];
8928 unsigned long func_addr
, last_pc
, pc
;
8929 const char *incl_files
[INCLUDE_STACK_SIZE
];
8930 int incl_index
, len
, last_line_num
, i
;
8931 const char *str
, *p
;
8933 fprintf(stderr
, "0x%08lx:", wanted_pc
);
8935 func_name
[0] = '\0';
8938 last_func_name
[0] = '\0';
8939 last_pc
= 0xffffffff;
8941 sym
= (Stab_Sym
*)stab_section
->data
+ 1;
8942 sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
8943 while (sym
< sym_end
) {
8944 switch(sym
->n_type
) {
8945 /* function start or end */
8947 if (sym
->n_strx
== 0) {
8948 /* we test if between last line and end of function */
8949 pc
= sym
->n_value
+ func_addr
;
8950 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
8952 func_name
[0] = '\0';
8955 str
= stabstr_section
->data
+ sym
->n_strx
;
8956 p
= strchr(str
, ':');
8958 pstrcpy(func_name
, sizeof(func_name
), str
);
8961 if (len
> sizeof(func_name
) - 1)
8962 len
= sizeof(func_name
) - 1;
8963 memcpy(func_name
, str
, len
);
8964 func_name
[len
] = '\0';
8966 func_addr
= sym
->n_value
;
8969 /* line number info */
8971 pc
= sym
->n_value
+ func_addr
;
8972 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
8975 last_line_num
= sym
->n_desc
;
8977 strcpy(last_func_name
, func_name
);
8981 str
= stabstr_section
->data
+ sym
->n_strx
;
8983 if (incl_index
< INCLUDE_STACK_SIZE
) {
8984 incl_files
[incl_index
++] = str
;
8992 if (sym
->n_strx
== 0) {
8993 incl_index
= 0; /* end of translation unit */
8995 str
= stabstr_section
->data
+ sym
->n_strx
;
8996 /* do not add path */
8998 if (len
> 0 && str
[len
- 1] != '/')
9006 /* second pass: we try symtab symbols (no line number info) */
9009 Elf32_Sym
*sym
, *sym_end
;
9012 sym_end
= (Elf32_Sym
*)(symtab_section
->data
+ symtab_section
->data_offset
);
9013 for(sym
= (Elf32_Sym
*)symtab_section
->data
+ 1;
9016 type
= ELF32_ST_TYPE(sym
->st_info
);
9017 if (type
== STT_FUNC
) {
9018 if (wanted_pc
>= sym
->st_value
&&
9019 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
9020 pstrcpy(last_func_name
, sizeof(last_func_name
),
9021 strtab_section
->data
+ sym
->st_name
);
9027 /* did not find any info: */
9028 fprintf(stderr
, " ???\n");
9031 if (last_func_name
[0] != '\0') {
9032 fprintf(stderr
, " %s()", last_func_name
);
9034 if (incl_index
> 0) {
9035 fprintf(stderr
, " (%s:%d",
9036 incl_files
[incl_index
- 1], last_line_num
);
9037 for(i
= incl_index
- 2; i
>= 0; i
--)
9038 fprintf(stderr
, ", included from %s", incl_files
[i
]);
9039 fprintf(stderr
, ")");
9041 fprintf(stderr
, "\n");
9048 /* fix for glibc 2.1 */
9054 /* return the PC at frame level 'level'. Return non zero if not found */
9055 static int rt_get_caller_pc(unsigned long *paddr
,
9056 ucontext_t
*uc
, int level
)
9063 *paddr
= uc
->uc_mcontext
.mc_eip
;
9065 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
9070 fp
= uc
->uc_mcontext
.mc_ebp
;
9072 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
9074 for(i
=1;i
<level
;i
++) {
9075 /* XXX: check address validity with program info */
9076 if (fp
<= 0x1000 || fp
>= 0xc0000000)
9078 fp
= ((unsigned long *)fp
)[0];
9080 *paddr
= ((unsigned long *)fp
)[1];
9086 #warning add arch specific rt_get_caller_pc()
9088 static int rt_get_caller_pc(unsigned long *paddr
,
9089 ucontext_t
*uc
, int level
)
9095 /* emit a run time error at position 'pc' */
9096 void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
9103 fprintf(stderr
, "Runtime error: ");
9104 vfprintf(stderr
, fmt
, ap
);
9105 fprintf(stderr
, "\n");
9106 for(i
=0;i
<num_callers
;i
++) {
9107 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
9110 fprintf(stderr
, "at ");
9112 fprintf(stderr
, "by ");
9119 /* signal handler for fatal errors */
9120 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
9122 ucontext_t
*uc
= puc
;
9126 switch(siginf
->si_code
) {
9129 rt_error(uc
, "division by zero");
9132 rt_error(uc
, "floating point exception");
9138 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
9139 rt_error(uc
, *rt_bound_error_msg
);
9141 rt_error(uc
, "dereferencing invalid pointer");
9144 rt_error(uc
, "illegal instruction");
9147 rt_error(uc
, "abort() called");
9150 rt_error(uc
, "caught signal %d", signum
);
9157 /* do all relocations (needed before using tcc_get_symbol()) */
9158 int tcc_relocate(TCCState
*s1
)
9165 tcc_add_runtime(s1
);
9167 build_got_entries(s1
);
9169 relocate_common_syms();
9171 /* compute relocation address : section are relocated in place. We
9172 also alloc the bss space */
9173 for(i
= 1; i
< s1
->nb_sections
; i
++) {
9174 s
= s1
->sections
[i
];
9175 if (s
->sh_flags
& SHF_ALLOC
) {
9176 if (s
->sh_type
== SHT_NOBITS
)
9177 s
->data
= tcc_mallocz(s
->data_offset
);
9178 s
->sh_addr
= (unsigned long)s
->data
;
9182 relocate_syms(s1
, 1);
9184 if (s1
->nb_errors
!= 0)
9187 /* relocate each section */
9188 for(i
= 1; i
< s1
->nb_sections
; i
++) {
9189 s
= s1
->sections
[i
];
9191 relocate_section(s1
, s
);
9196 /* launch the compiled program with the given arguments */
9197 int tcc_run(TCCState
*s1
, int argc
, char **argv
)
9199 int (*prog_main
)(int, char **);
9201 if (tcc_relocate(s1
) < 0)
9204 prog_main
= tcc_get_symbol_err(s1
, "main");
9208 error("debug mode currently not available for Windows");
9210 struct sigaction sigact
;
9211 /* install TCC signal handlers to print debug info on fatal
9213 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
9214 sigact
.sa_sigaction
= sig_error
;
9215 sigemptyset(&sigact
.sa_mask
);
9216 sigaction(SIGFPE
, &sigact
, NULL
);
9217 sigaction(SIGILL
, &sigact
, NULL
);
9218 sigaction(SIGSEGV
, &sigact
, NULL
);
9219 sigaction(SIGBUS
, &sigact
, NULL
);
9220 sigaction(SIGABRT
, &sigact
, NULL
);
9224 #ifdef CONFIG_TCC_BCHECK
9225 if (do_bounds_check
) {
9226 void (*bound_init
)(void);
9228 /* set error function */
9229 rt_bound_error_msg
= (void *)tcc_get_symbol_err(s1
,
9230 "__bound_error_msg");
9232 /* XXX: use .init section so that it also work in binary ? */
9233 bound_init
= (void *)tcc_get_symbol_err(s1
, "__bound_init");
9237 return (*prog_main
)(argc
, argv
);
9240 TCCState
*tcc_new(void)
9247 s
= tcc_mallocz(sizeof(TCCState
));
9251 s
->output_type
= TCC_OUTPUT_MEMORY
;
9253 /* init isid table */
9255 isidnum_table
[i
] = isid(i
) || isnum(i
);
9257 /* add all tokens */
9259 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
9261 tok_ident
= TOK_IDENT
;
9270 ts
= tok_alloc(p
, r
- p
- 1);
9274 /* we add dummy defines for some special macros to speed up tests
9275 and to have working defined() */
9276 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
9277 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
9278 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
9279 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
9281 /* standard defines */
9282 tcc_define_symbol(s
, "__STDC__", NULL
);
9283 #if defined(TCC_TARGET_I386)
9284 tcc_define_symbol(s
, "__i386__", NULL
);
9286 #if defined(TCC_TARGET_ARM)
9287 tcc_define_symbol(s
, "__ARM_ARCH_4__", NULL
);
9288 tcc_define_symbol(s
, "__arm_elf__", NULL
);
9289 tcc_define_symbol(s
, "__arm_elf", NULL
);
9290 tcc_define_symbol(s
, "arm_elf", NULL
);
9291 tcc_define_symbol(s
, "__arm__", NULL
);
9292 tcc_define_symbol(s
, "__arm", NULL
);
9293 tcc_define_symbol(s
, "arm", NULL
);
9294 tcc_define_symbol(s
, "__APCS_32__", NULL
);
9297 tcc_define_symbol(s
, "__linux__", NULL
);
9298 tcc_define_symbol(s
, "linux", NULL
);
9300 /* tiny C specific defines */
9301 tcc_define_symbol(s
, "__TINYC__", NULL
);
9303 /* tiny C & gcc defines */
9304 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned int");
9305 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "int");
9306 tcc_define_symbol(s
, "__WCHAR_TYPE__", "int");
9308 /* default library paths */
9309 tcc_add_library_path(s
, "/usr/local/lib");
9310 tcc_add_library_path(s
, "/usr/lib");
9311 tcc_add_library_path(s
, "/lib");
9313 /* no section zero */
9314 dynarray_add((void ***)&s
->sections
, &s
->nb_sections
, NULL
);
9316 /* create standard sections */
9317 text_section
= new_section(s
, ".text", SHT_PROGBITS
, SHF_ALLOC
| SHF_EXECINSTR
);
9318 data_section
= new_section(s
, ".data", SHT_PROGBITS
, SHF_ALLOC
| SHF_WRITE
);
9319 bss_section
= new_section(s
, ".bss", SHT_NOBITS
, SHF_ALLOC
| SHF_WRITE
);
9321 /* symbols are always generated for linking stage */
9322 symtab_section
= new_symtab(s
, ".symtab", SHT_SYMTAB
, 0,
9324 ".hashtab", SHF_PRIVATE
);
9325 strtab_section
= symtab_section
->link
;
9327 /* private symbol table for dynamic symbols */
9328 s
->dynsymtab_section
= new_symtab(s
, ".dynsymtab", SHT_SYMTAB
, SHF_PRIVATE
,
9330 ".dynhashtab", SHF_PRIVATE
);
9331 s
->alacarte_link
= 1;
9333 #ifdef CHAR_IS_UNSIGNED
9334 s
->char_is_unsigned
= 1;
9339 void tcc_delete(TCCState
*s1
)
9343 /* free -D defines */
9347 n
= tok_ident
- TOK_IDENT
;
9348 for(i
= 0; i
< n
; i
++)
9349 tcc_free(table_ident
[i
]);
9350 tcc_free(table_ident
);
9352 /* free all sections */
9354 free_section(symtab_section
->hash
);
9356 free_section(s1
->dynsymtab_section
->hash
);
9357 free_section(s1
->dynsymtab_section
->link
);
9358 free_section(s1
->dynsymtab_section
);
9360 for(i
= 1; i
< s1
->nb_sections
; i
++)
9361 free_section(s1
->sections
[i
]);
9362 tcc_free(s1
->sections
);
9364 /* free loaded dlls array */
9365 for(i
= 0; i
< s1
->nb_loaded_dlls
; i
++)
9366 tcc_free(s1
->loaded_dlls
[i
]);
9367 tcc_free(s1
->loaded_dlls
);
9370 for(i
= 0; i
< s1
->nb_library_paths
; i
++)
9371 tcc_free(s1
->library_paths
[i
]);
9372 tcc_free(s1
->library_paths
);
9374 /* cached includes */
9375 for(i
= 0; i
< s1
->nb_cached_includes
; i
++)
9376 tcc_free(s1
->cached_includes
[i
]);
9377 tcc_free(s1
->cached_includes
);
9379 for(i
= 0; i
< s1
->nb_include_paths
; i
++)
9380 tcc_free(s1
->include_paths
[i
]);
9381 tcc_free(s1
->include_paths
);
9383 for(i
= 0; i
< s1
->nb_sysinclude_paths
; i
++)
9384 tcc_free(s1
->sysinclude_paths
[i
]);
9385 tcc_free(s1
->sysinclude_paths
);
9390 int tcc_add_include_path(TCCState
*s1
, const char *pathname
)
9394 pathname1
= tcc_strdup(pathname
);
9395 dynarray_add((void ***)&s1
->include_paths
, &s1
->nb_include_paths
, pathname1
);
9399 int tcc_add_sysinclude_path(TCCState
*s1
, const char *pathname
)
9403 pathname1
= tcc_strdup(pathname
);
9404 dynarray_add((void ***)&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
, pathname1
);
9408 static int tcc_add_file_internal(TCCState
*s1
, const char *filename
, int flags
)
9410 const char *ext
, *filename1
;
9413 BufferedFile
*saved_file
;
9415 /* find source file type with extension */
9416 filename1
= strrchr(filename
, '/');
9420 filename1
= filename
;
9421 ext
= strrchr(filename1
, '.');
9427 file
= tcc_open(s1
, filename
);
9429 if (flags
& AFF_PRINT_ERROR
) {
9430 error_noabort("file '%s' not found", filename
);
9436 if (!ext
|| !strcmp(ext
, "c")) {
9437 /* C file assumed */
9438 ret
= tcc_compile(s1
);
9440 #ifdef CONFIG_TCC_ASM
9441 if (!strcmp(ext
, "S")) {
9442 /* preprocessed assembler */
9443 ret
= tcc_assemble(s1
, 1);
9444 } else if (!strcmp(ext
, "s")) {
9445 /* non preprocessed assembler */
9446 ret
= tcc_assemble(s1
, 0);
9451 /* assume executable format: auto guess file type */
9452 ret
= read(fd
, &ehdr
, sizeof(ehdr
));
9453 lseek(fd
, 0, SEEK_SET
);
9455 error_noabort("could not read header");
9457 } else if (ret
!= sizeof(ehdr
)) {
9458 goto try_load_script
;
9461 if (ehdr
.e_ident
[0] == ELFMAG0
&&
9462 ehdr
.e_ident
[1] == ELFMAG1
&&
9463 ehdr
.e_ident
[2] == ELFMAG2
&&
9464 ehdr
.e_ident
[3] == ELFMAG3
) {
9465 file
->line_num
= 0; /* do not display line number if error */
9466 if (ehdr
.e_type
== ET_REL
) {
9467 ret
= tcc_load_object_file(s1
, fd
, 0);
9468 } else if (ehdr
.e_type
== ET_DYN
) {
9469 if (s1
->output_type
== TCC_OUTPUT_MEMORY
) {
9471 h
= dlopen(filename
, RTLD_GLOBAL
| RTLD_LAZY
);
9477 ret
= tcc_load_dll(s1
, fd
, filename
,
9478 (flags
& AFF_REFERENCED_DLL
) != 0);
9481 error_noabort("unrecognized ELF file");
9484 } else if (memcmp((char *)&ehdr
, ARMAG
, 8) == 0) {
9485 file
->line_num
= 0; /* do not display line number if error */
9486 ret
= tcc_load_archive(s1
, fd
);
9488 /* as GNU ld, consider it is an ld script if not recognized */
9490 ret
= tcc_load_ldscript(s1
);
9492 error_noabort("unrecognized file type");
9507 int tcc_add_file(TCCState
*s
, const char *filename
)
9509 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
);
9512 int tcc_add_library_path(TCCState
*s
, const char *pathname
)
9516 pathname1
= tcc_strdup(pathname
);
9517 dynarray_add((void ***)&s
->library_paths
, &s
->nb_library_paths
, pathname1
);
9521 /* find and load a dll. Return non zero if not found */
9522 /* XXX: add '-rpath' option support ? */
9523 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
)
9528 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
9529 snprintf(buf
, sizeof(buf
), "%s/%s",
9530 s
->library_paths
[i
], filename
);
9531 if (tcc_add_file_internal(s
, buf
, flags
) == 0)
9537 /* the library name is the same as the argument of the '-l' option */
9538 int tcc_add_library(TCCState
*s
, const char *libraryname
)
9543 /* first we look for the dynamic library if not static linking */
9544 if (!s
->static_link
) {
9545 snprintf(buf
, sizeof(buf
), "lib%s.so", libraryname
);
9546 if (tcc_add_dll(s
, buf
, 0) == 0)
9550 /* then we look for the static library */
9551 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
9552 snprintf(buf
, sizeof(buf
), "%s/lib%s.a",
9553 s
->library_paths
[i
], libraryname
);
9554 if (tcc_add_file_internal(s
, buf
, 0) == 0)
9560 int tcc_add_symbol(TCCState
*s
, const char *name
, unsigned long val
)
9562 add_elf_sym(symtab_section
, val
, 0,
9563 ELF32_ST_INFO(STB_GLOBAL
, STT_NOTYPE
),
9568 int tcc_set_output_type(TCCState
*s
, int output_type
)
9572 s
->output_type
= output_type
;
9575 /* default include paths */
9576 /* XXX: reverse order needed if -isystem support */
9577 tcc_add_sysinclude_path(s
, "/usr/local/include");
9578 tcc_add_sysinclude_path(s
, "/usr/include");
9579 snprintf(buf
, sizeof(buf
), "%s/include", tcc_lib_path
);
9580 tcc_add_sysinclude_path(s
, buf
);
9583 /* if bound checking, then add corresponding sections */
9584 #ifdef CONFIG_TCC_BCHECK
9585 if (do_bounds_check
) {
9587 tcc_define_symbol(s
, "__BOUNDS_CHECKING_ON", NULL
);
9588 /* create bounds sections */
9589 bounds_section
= new_section(s
, ".bounds",
9590 SHT_PROGBITS
, SHF_ALLOC
);
9591 lbounds_section
= new_section(s
, ".lbounds",
9592 SHT_PROGBITS
, SHF_ALLOC
);
9596 if (s
->char_is_unsigned
) {
9597 tcc_define_symbol(s
, "__CHAR_UNSIGNED__", NULL
);
9600 /* add debug sections */
9603 stab_section
= new_section(s
, ".stab", SHT_PROGBITS
, 0);
9604 stab_section
->sh_entsize
= sizeof(Stab_Sym
);
9605 stabstr_section
= new_section(s
, ".stabstr", SHT_STRTAB
, 0);
9606 put_elf_str(stabstr_section
, "");
9607 stab_section
->link
= stabstr_section
;
9608 /* put first entry */
9609 put_stabs("", 0, 0, 0, 0);
9612 /* add libc crt1/crti objects */
9613 if ((output_type
== TCC_OUTPUT_EXE
|| output_type
== TCC_OUTPUT_DLL
) &&
9615 if (output_type
!= TCC_OUTPUT_DLL
)
9616 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crt1.o");
9617 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crti.o");
9622 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
9623 #define FD_INVERT 0x0002 /* invert value before storing */
9625 typedef struct FlagDef
{
9631 static const FlagDef warning_defs
[] = {
9632 { offsetof(TCCState
, warn_unsupported
), 0, "unsupported" },
9633 { offsetof(TCCState
, warn_write_strings
), 0, "write-strings" },
9634 { offsetof(TCCState
, warn_error
), 0, "error" },
9635 { offsetof(TCCState
, warn_implicit_function_declaration
), WD_ALL
,
9636 "implicit-function-declaration" },
9639 static int set_flag(TCCState
*s
, const FlagDef
*flags
, int nb_flags
,
9640 const char *name
, int value
)
9647 if (r
[0] == 'n' && r
[1] == 'o' && r
[2] == '-') {
9651 for(i
= 0, p
= flags
; i
< nb_flags
; i
++, p
++) {
9652 if (!strcmp(r
, p
->name
))
9657 if (p
->flags
& FD_INVERT
)
9659 *(int *)((uint8_t *)s
+ p
->offset
) = value
;
9664 /* set/reset a warning */
9665 int tcc_set_warning(TCCState
*s
, const char *warning_name
, int value
)
9670 if (!strcmp(warning_name
, "all")) {
9671 for(i
= 0, p
= warning_defs
; i
< countof(warning_defs
); i
++, p
++) {
9672 if (p
->flags
& WD_ALL
)
9673 *(int *)((uint8_t *)s
+ p
->offset
) = 1;
9677 return set_flag(s
, warning_defs
, countof(warning_defs
),
9678 warning_name
, value
);
9682 static const FlagDef flag_defs
[] = {
9683 { offsetof(TCCState
, char_is_unsigned
), 0, "unsigned-char" },
9684 { offsetof(TCCState
, char_is_unsigned
), FD_INVERT
, "signed-char" },
9687 /* set/reset a flag */
9688 int tcc_set_flag(TCCState
*s
, const char *flag_name
, int value
)
9690 return set_flag(s
, flag_defs
, countof(flag_defs
),
9694 #if !defined(LIBTCC)
9696 /* extract the basename of a file */
9697 static const char *tcc_basename(const char *name
)
9700 p
= strrchr(name
, '/');
9703 p
= strrchr(name
, '\\');
9712 static int64_t getclock_us(void)
9717 return (tb
.time
* 1000LL + tb
.millitm
) * 1000LL;
9720 gettimeofday(&tv
, NULL
);
9721 return tv
.tv_sec
* 1000000LL + tv
.tv_usec
;
9727 printf("tcc version " TCC_VERSION
" - Tiny C Compiler - Copyright (C) 2001-2003 Fabrice Bellard\n"
9728 "usage: tcc [-v] [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"
9729 " [-Wwarn] [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-static]\n"
9730 " [infile1 infile2...] [-run infile args...]\n"
9732 "General options:\n"
9733 " -v display current version\n"
9734 " -c compile only - generate an object file\n"
9735 " -o outfile set output filename\n"
9736 " -Bdir set tcc internal library path\n"
9737 " -bench output compilation statistics\n"
9738 " -run run compiled source\n"
9739 " -fflag set or reset (with 'no-' prefix) 'flag' (see man page)\n"
9740 " -Wwarning set or reset (with 'no-' prefix) 'warning' (see man page)\n"
9741 " -w disable all warnings\n"
9742 "Preprocessor options:\n"
9743 " -Idir add include path 'dir'\n"
9744 " -Dsym[=val] define 'sym' with value 'val'\n"
9745 " -Usym undefine 'sym'\n"
9747 " -Ldir add library path 'dir'\n"
9748 " -llib link with dynamic or static library 'lib'\n"
9749 " -shared generate a shared library\n"
9750 " -static static linking\n"
9751 " -rdynamic export all global symbols to dynamic linker\n"
9752 " -r relocatable output\n"
9753 "Debugger options:\n"
9754 " -g generate runtime debug info\n"
9755 #ifdef CONFIG_TCC_BCHECK
9756 " -b compile with built-in memory and bounds checker (implies -g)\n"
9758 " -bt N show N callers in stack traces\n"
9762 #define TCC_OPTION_HAS_ARG 0x0001
9763 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
9765 typedef struct TCCOption
{
9792 TCC_OPTION_nostdinc
,
9793 TCC_OPTION_nostdlib
,
9794 TCC_OPTION_print_search_dirs
,
9795 TCC_OPTION_rdynamic
,
9801 static const TCCOption tcc_options
[] = {
9802 { "h", TCC_OPTION_HELP
, 0 },
9803 { "?", TCC_OPTION_HELP
, 0 },
9804 { "I", TCC_OPTION_I
, TCC_OPTION_HAS_ARG
},
9805 { "D", TCC_OPTION_D
, TCC_OPTION_HAS_ARG
},
9806 { "U", TCC_OPTION_U
, TCC_OPTION_HAS_ARG
},
9807 { "L", TCC_OPTION_L
, TCC_OPTION_HAS_ARG
},
9808 { "B", TCC_OPTION_B
, TCC_OPTION_HAS_ARG
},
9809 { "l", TCC_OPTION_l
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9810 { "bench", TCC_OPTION_bench
, 0 },
9811 { "bt", TCC_OPTION_bt
, TCC_OPTION_HAS_ARG
},
9812 #ifdef CONFIG_TCC_BCHECK
9813 { "b", TCC_OPTION_b
, 0 },
9815 { "g", TCC_OPTION_g
, 0 },
9816 { "c", TCC_OPTION_c
, 0 },
9817 { "static", TCC_OPTION_static
, 0 },
9818 { "shared", TCC_OPTION_shared
, 0 },
9819 { "o", TCC_OPTION_o
, TCC_OPTION_HAS_ARG
},
9820 { "run", TCC_OPTION_run
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9821 { "rdynamic", TCC_OPTION_rdynamic
, 0 },
9822 { "r", TCC_OPTION_r
, 0 },
9823 { "W", TCC_OPTION_W
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9824 { "O", TCC_OPTION_O
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9825 { "m", TCC_OPTION_m
, TCC_OPTION_HAS_ARG
},
9826 { "f", TCC_OPTION_f
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9827 { "nostdinc", TCC_OPTION_nostdinc
, 0 },
9828 { "nostdlib", TCC_OPTION_nostdlib
, 0 },
9829 { "print-search-dirs", TCC_OPTION_print_search_dirs
, 0 },
9830 { "v", TCC_OPTION_v
, 0 },
9831 { "w", TCC_OPTION_w
, 0 },
9835 /* convert 'str' into an array of space separated strings */
9836 static int expand_args(char ***pargv
, const char *str
)
9845 while (is_space(*str
))
9850 while (*str
!= '\0' && !is_space(*str
))
9853 arg
= tcc_malloc(len
+ 1);
9854 memcpy(arg
, s1
, len
);
9856 dynarray_add((void ***)&argv
, &argc
, arg
);
9862 static char **files
;
9863 static int nb_files
, nb_libraries
;
9864 static int multiple_files
;
9865 static int print_search_dirs
;
9866 static int output_type
;
9867 static int reloc_output
;
9868 static const char *outfile
;
9870 int parse_args(TCCState
*s
, int argc
, char **argv
)
9873 const TCCOption
*popt
;
9874 const char *optarg
, *p1
, *r1
;
9879 if (optind
>= argc
) {
9880 if (nb_files
== 0 && !print_search_dirs
)
9887 /* add a new file */
9888 dynarray_add((void ***)&files
, &nb_files
, r
);
9889 if (!multiple_files
) {
9891 /* argv[0] will be this file */
9895 /* find option in table (match only the first chars */
9900 error("invalid option -- '%s'", r
);
9913 if (popt
->flags
& TCC_OPTION_HAS_ARG
) {
9914 if (*r1
!= '\0' || (popt
->flags
& TCC_OPTION_NOSEP
)) {
9918 error("argument to '%s' is missing", r
);
9919 optarg
= argv
[optind
++];
9927 switch(popt
->index
) {
9928 case TCC_OPTION_HELP
:
9933 if (tcc_add_include_path(s
, optarg
) < 0)
9934 error("too many include paths");
9939 sym
= (char *)optarg
;
9940 value
= strchr(sym
, '=');
9945 tcc_define_symbol(s
, sym
, value
);
9949 tcc_undefine_symbol(s
, optarg
);
9952 tcc_add_library_path(s
, optarg
);
9955 /* set tcc utilities path (mainly for tcc development) */
9956 tcc_lib_path
= optarg
;
9959 dynarray_add((void ***)&files
, &nb_files
, r
);
9962 case TCC_OPTION_bench
:
9966 num_callers
= atoi(optarg
);
9968 #ifdef CONFIG_TCC_BCHECK
9970 do_bounds_check
= 1;
9979 output_type
= TCC_OUTPUT_OBJ
;
9981 case TCC_OPTION_static
:
9984 case TCC_OPTION_shared
:
9985 output_type
= TCC_OUTPUT_DLL
;
9992 /* generate a .o merging several output files */
9994 output_type
= TCC_OUTPUT_OBJ
;
9996 case TCC_OPTION_nostdinc
:
9999 case TCC_OPTION_nostdlib
:
10002 case TCC_OPTION_print_search_dirs
:
10003 print_search_dirs
= 1;
10005 case TCC_OPTION_run
:
10009 argc1
= expand_args(&argv1
, optarg
);
10011 parse_args(s
, argc1
, argv1
);
10013 multiple_files
= 0;
10014 output_type
= TCC_OUTPUT_MEMORY
;
10018 printf("tcc version %s\n", TCC_VERSION
);
10021 if (tcc_set_flag(s
, optarg
, 1) < 0 && s
->warn_unsupported
)
10022 goto unsupported_option
;
10025 if (tcc_set_warning(s
, optarg
, 1) < 0 &&
10026 s
->warn_unsupported
)
10027 goto unsupported_option
;
10032 case TCC_OPTION_rdynamic
:
10036 if (s
->warn_unsupported
) {
10037 unsupported_option
:
10038 warning("unsupported option '%s'", r
);
10047 int main(int argc
, char **argv
)
10051 int nb_objfiles
, ret
, optind
;
10052 char objfilename
[1024];
10053 int64_t start_time
= 0;
10056 output_type
= TCC_OUTPUT_EXE
;
10058 multiple_files
= 1;
10063 print_search_dirs
= 0;
10065 optind
= parse_args(s
, argc
- 1, argv
+ 1) + 1;
10067 if (print_search_dirs
) {
10068 /* enough for Linux kernel */
10069 printf("install: %s/\n", tcc_lib_path
);
10073 nb_objfiles
= nb_files
- nb_libraries
;
10075 /* if outfile provided without other options, we output an
10077 if (outfile
&& output_type
== TCC_OUTPUT_MEMORY
)
10078 output_type
= TCC_OUTPUT_EXE
;
10080 /* check -c consistency : only single file handled. XXX: checks file type */
10081 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
10082 /* accepts only a single input file */
10083 if (nb_objfiles
!= 1)
10084 error("cannot specify multiple files with -c");
10085 if (nb_libraries
!= 0)
10086 error("cannot specify libraries with -c");
10089 /* compute default outfile name */
10090 if (output_type
!= TCC_OUTPUT_MEMORY
&& !outfile
) {
10091 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
10094 pstrcpy(objfilename
, sizeof(objfilename
) - 1,
10095 tcc_basename(files
[0]));
10096 /* add .o extension */
10097 ext
= strrchr(objfilename
, '.');
10099 goto default_outfile
;
10100 strcpy(ext
+ 1, "o");
10103 pstrcpy(objfilename
, sizeof(objfilename
), "a.out");
10105 outfile
= objfilename
;
10109 start_time
= getclock_us();
10112 tcc_set_output_type(s
, output_type
);
10114 /* compile or add each files or library */
10115 for(i
= 0;i
< nb_files
; i
++) {
10116 const char *filename
;
10118 filename
= files
[i
];
10119 if (filename
[0] == '-') {
10120 if (tcc_add_library(s
, filename
+ 2) < 0)
10121 error("cannot find %s", filename
);
10123 if (tcc_add_file(s
, filename
) < 0) {
10130 /* free all files */
10135 total_time
= (double)(getclock_us() - start_time
) / 1000000.0;
10136 if (total_time
< 0.001)
10137 total_time
= 0.001;
10138 if (total_bytes
< 1)
10140 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
10141 tok_ident
- TOK_IDENT
, total_lines
, total_bytes
,
10142 total_time
, (int)(total_lines
/ total_time
),
10143 total_bytes
/ total_time
/ 1000000.0);
10146 if (s
->output_type
!= TCC_OUTPUT_MEMORY
) {
10147 tcc_output_file(s
, outfile
);
10150 ret
= tcc_run(s
, argc
- optind
, argv
+ optind
);
10153 /* XXX: cannot do it with bound checking because of the malloc hooks */
10154 if (!do_bounds_check
)
10159 printf("memory: %d bytes, max = %d bytes\n", mem_cur_size
, mem_max_size
);