2 * TCC - Tiny C Compiler
4 * Copyright (c) 2001, 2002, 2003 Fabrice Bellard
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program 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
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, 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 */
65 /* default target is I386 */
66 #if !defined(TCC_TARGET_I386)
67 #define TCC_TARGET_I386
70 #if !defined(WIN32) && !defined(TCC_UCLIBC)
71 #define CONFIG_TCC_BCHECK /* enable bound checking code */
74 /* define it to include assembler support */
75 #define CONFIG_TCC_ASM
77 /* path to find crt1.o, crti.o and crtn.o. Only needed when generating
78 executables or dlls */
79 #define CONFIG_TCC_CRT_PREFIX "/usr/lib"
81 #define INCLUDE_STACK_SIZE 32
82 #define IFDEF_STACK_SIZE 64
83 #define VSTACK_SIZE 64
84 #define STRING_MAX_SIZE 1024
86 #define TOK_HASH_SIZE 2048 /* must be a power of two */
87 #define TOK_ALLOC_INCR 512 /* must be a power of two */
88 #define TOK_STR_ALLOC_INCR_BITS 6
89 #define TOK_STR_ALLOC_INCR (1 << TOK_STR_ALLOC_INCR_BITS)
90 #define TOK_MAX_SIZE 4 /* token max size in int unit when stored in string */
92 /* token symbol management */
93 typedef struct TokenSym
{
94 struct TokenSym
*hash_next
;
95 struct Sym
*sym_define
; /* direct pointer to define */
96 struct Sym
*sym_label
; /* direct pointer to label */
97 struct Sym
*sym_struct
; /* direct pointer to structure */
98 struct Sym
*sym_identifier
; /* direct pointer to identifier */
99 int tok
; /* token number */
104 typedef struct CString
{
105 int size
; /* size in bytes */
106 void *data
; /* either 'char *' or 'int *' */
108 void *data_allocated
; /* if non NULL, data has been malloced */
111 /* type definition */
112 typedef struct CType
{
118 typedef union CValue
{
124 unsigned int ul
; /* address (should be unsigned long on 64 bit cpu) */
126 unsigned long long ull
;
127 struct CString
*cstr
;
133 typedef struct SValue
{
134 CType type
; /* type */
135 unsigned short r
; /* register + flags */
136 unsigned short r2
; /* second register, used for 'long long'
137 type. If not used, set to VT_CONST */
138 CValue c
; /* constant, if VT_CONST */
139 struct Sym
*sym
; /* symbol, if (VT_SYM | VT_CONST) */
142 /* symbol management */
144 int v
; /* symbol token */
145 int r
; /* associated register */
146 int c
; /* associated number */
147 CType type
; /* associated type */
148 struct Sym
*next
; /* next related symbol */
149 struct Sym
*prev
; /* prev symbol in stack */
150 struct Sym
*prev_tok
; /* previous symbol for this token */
153 /* section definition */
154 /* XXX: use directly ELF structure for parameters ? */
155 /* special flag to indicate that the section should not be linked to
157 #define SHF_PRIVATE 0x80000000
159 typedef struct Section
{
160 unsigned long data_offset
; /* current data offset */
161 unsigned char *data
; /* section data */
162 unsigned long data_allocated
; /* used for realloc() handling */
163 int sh_name
; /* elf section name (only used during output) */
164 int sh_num
; /* elf section number */
165 int sh_type
; /* elf section type */
166 int sh_flags
; /* elf section flags */
167 int sh_info
; /* elf section info */
168 int sh_addralign
; /* elf section alignment */
169 int sh_entsize
; /* elf entry size */
170 unsigned long sh_size
; /* section size (only used during output) */
171 unsigned long sh_addr
; /* address at which the section is relocated */
172 unsigned long sh_offset
; /* address at which the section is relocated */
173 int nb_hashed_syms
; /* used to resize the hash table */
174 struct Section
*link
; /* link to another section */
175 struct Section
*reloc
; /* corresponding section for relocation, if any */
176 struct Section
*hash
; /* hash table for symbols */
177 struct Section
*next
;
178 char name
[64]; /* section name */
181 typedef struct DLLReference
{
186 /* GNUC attribute definition */
187 typedef struct AttributeDef
{
190 unsigned char func_call
; /* FUNC_CDECL or FUNC_STDCALL */
193 #define SYM_STRUCT 0x40000000 /* struct/union/enum symbol space */
194 #define SYM_FIELD 0x20000000 /* struct/union field symbol space */
195 #define SYM_FIRST_ANOM (1 << (31 - VT_STRUCT_SHIFT)) /* first anonymous sym */
197 /* stored in 'Sym.c' field */
198 #define FUNC_NEW 1 /* ansi function prototype */
199 #define FUNC_OLD 2 /* old function prototype */
200 #define FUNC_ELLIPSIS 3 /* ansi function prototype with ... */
202 /* stored in 'Sym.r' field */
203 #define FUNC_CDECL 0 /* standard c call */
204 #define FUNC_STDCALL 1 /* pascal c call */
206 /* field 'Sym.t' for macros */
207 #define MACRO_OBJ 0 /* object like macro */
208 #define MACRO_FUNC 1 /* function like macro */
210 /* field 'Sym.r' for C labels */
211 #define LABEL_DEFINED 0 /* label is defined */
212 #define LABEL_FORWARD 1 /* label is forward defined */
213 #define LABEL_DECLARED 2 /* label is declared but never used */
215 /* type_decl() types */
216 #define TYPE_ABSTRACT 1 /* type without variable */
217 #define TYPE_DIRECT 2 /* type with variable */
219 #define IO_BUF_SIZE 8192
221 typedef struct BufferedFile
{
225 int line_num
; /* current line number - here to simplify code */
226 int ifndef_macro
; /* #ifndef macro / #endif search */
227 int ifndef_macro_saved
; /* saved ifndef_macro */
228 int *ifdef_stack_ptr
; /* ifdef_stack value at the start of the file */
229 char inc_type
; /* type of include */
230 char inc_filename
[512]; /* filename specified by the user */
231 char filename
[1024]; /* current filename - here to simplify code */
232 unsigned char buffer
[IO_BUF_SIZE
+ 1]; /* extra size for CH_EOB char */
235 #define CH_EOB '\\' /* end of buffer or '\0' char in file */
236 #define CH_EOF (-1) /* end of file */
238 /* parsing state (used to save parser state to reparse part of the
239 source several times) */
240 typedef struct ParseState
{
247 /* used to record tokens */
248 typedef struct TokenString
{
255 /* include file cache, used to find files faster and also to eliminate
256 inclusion if the include file is protected by #ifndef ... #endif */
257 typedef struct CachedInclude
{
259 char type
; /* '"' or '>' to give include type */
260 char filename
[1]; /* path specified in #include */
264 static struct BufferedFile
*file
;
267 static CString tokcstr
; /* current parsed string, if any */
268 /* additional informations about token */
269 static int tok_flags
;
270 #define TOK_FLAG_BOL 0x0001 /* beginning of line before */
271 #define TOK_FLAG_BOF 0x0002 /* beginning of file before */
272 #define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */
274 static int *macro_ptr
, *macro_ptr_allocated
;
275 static int *unget_saved_macro_ptr
;
276 static int unget_saved_buffer
[TOK_MAX_SIZE
+ 1];
277 static int unget_buffer_enabled
;
278 static int parse_flags
;
279 #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
280 #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
281 #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
282 token. line feed is also
285 static Section
*text_section
, *data_section
, *bss_section
; /* predefined sections */
286 static Section
*cur_text_section
; /* current section where function code is
288 /* bound check related sections */
289 static Section
*bounds_section
; /* contains global data bound description */
290 static Section
*lbounds_section
; /* contains local data bound description */
291 /* symbol sections */
292 static Section
*symtab_section
, *strtab_section
;
295 static Section
*stab_section
, *stabstr_section
;
297 /* loc : local variable index
298 ind : output code index
300 anon_sym: anonymous symbol index
302 static int rsym
, anon_sym
, ind
, loc
;
303 /* expression generation modifiers */
304 static int const_wanted
; /* true if constant wanted */
305 static int nocode_wanted
; /* true if no code generation wanted for an expression */
306 static int global_expr
; /* true if compound literals must be allocated
307 globally (used during initializers parsing */
308 static CType func_vt
; /* current function return type (used by return
311 static int last_line_num
, last_ind
, func_ind
; /* debug last line number and pc */
312 static int tok_ident
;
313 static TokenSym
**table_ident
;
314 static TokenSym
*hash_ident
[TOK_HASH_SIZE
];
315 static char token_buf
[STRING_MAX_SIZE
+ 1];
316 static char *funcname
;
317 static Sym
*global_stack
, *local_stack
;
318 static Sym
*define_stack
;
319 static Sym
*global_label_stack
, *local_label_stack
;
321 static SValue vstack
[VSTACK_SIZE
], *vtop
;
322 /* some predefined types */
323 static CType char_pointer_type
, func_old_type
, int_type
;
324 /* true if isid(c) || isnum(c) */
325 static unsigned char isidnum_table
[256];
327 /* compile with debug symbol (and use them if error during execution) */
328 static int do_debug
= 0;
330 /* compile with built-in memory and bounds checker */
331 static int do_bounds_check
= 0;
333 /* display benchmark infos */
335 static int do_bench
= 0;
337 static int total_lines
;
338 static int total_bytes
;
340 /* use GNU C extensions */
341 static int gnu_ext
= 1;
343 /* use Tiny C extensions */
344 static int tcc_ext
= 1;
346 /* max number of callers shown if error */
347 static int num_callers
= 6;
348 static const char **rt_bound_error_msg
;
350 /* XXX: get rid of this ASAP */
351 static struct TCCState
*tcc_state
;
353 /* give the path of the tcc libraries */
354 static const char *tcc_lib_path
= CONFIG_TCC_LIBDIR
"/tcc";
359 BufferedFile
**include_stack_ptr
;
360 int *ifdef_stack_ptr
;
362 /* include file handling */
363 char **include_paths
;
364 int nb_include_paths
;
365 char **sysinclude_paths
;
366 int nb_sysinclude_paths
;
367 CachedInclude
**cached_includes
;
368 int nb_cached_includes
;
370 char **library_paths
;
371 int nb_library_paths
;
373 /* array of all loaded dlls (including those referenced by loaded
375 DLLReference
**loaded_dlls
;
380 int nb_sections
; /* number of sections, including first dummy section */
385 unsigned long *got_offsets
;
387 /* give the correspondance from symtab indexes to dynsym indexes */
388 int *symtab_to_dynsym
;
390 /* temporary dynamic symbol sections (for dll loading) */
391 Section
*dynsymtab_section
;
392 /* exported dynamic symbol section */
395 /* if true, no standard headers are added */
398 /* if true, static linking is performed */
401 /* warning switches */
402 int warn_write_strings
;
403 int warn_unsupported
;
408 void (*error_func
)(void *opaque
, const char *msg
);
409 int error_set_jmp_enabled
;
410 jmp_buf error_jmp_buf
;
413 /* tiny assembler state */
416 /* see include_stack_ptr */
417 BufferedFile
*include_stack
[INCLUDE_STACK_SIZE
];
419 /* see ifdef_stack_ptr */
420 int ifdef_stack
[IFDEF_STACK_SIZE
];
423 /* The current value can be: */
424 #define VT_VALMASK 0x00ff
425 #define VT_CONST 0x00f0 /* constant in vc
426 (must be first non register value) */
427 #define VT_LLOCAL 0x00f1 /* lvalue, offset on stack */
428 #define VT_LOCAL 0x00f2 /* offset on stack */
429 #define VT_CMP 0x00f3 /* the value is stored in processor flags (in vc) */
430 #define VT_JMP 0x00f4 /* value is the consequence of jmp true (even) */
431 #define VT_JMPI 0x00f5 /* value is the consequence of jmp false (odd) */
432 #define VT_LVAL 0x0100 /* var is an lvalue */
433 #define VT_SYM 0x0200 /* a symbol value is added */
434 #define VT_MUSTCAST 0x0400 /* value must be casted to be correct (used for
435 char/short stored in integer registers) */
436 #define VT_MUSTBOUND 0x0800 /* bound checking must be done before
437 dereferencing value */
438 #define VT_BOUNDED 0x8000 /* value is bounded. The address of the
439 bounding function call point is in vc */
440 #define VT_LVAL_BYTE 0x1000 /* lvalue is a byte */
441 #define VT_LVAL_SHORT 0x2000 /* lvalue is a short */
442 #define VT_LVAL_UNSIGNED 0x4000 /* lvalue is unsigned */
443 #define VT_LVAL_TYPE (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
446 #define VT_INT 0 /* integer type */
447 #define VT_BYTE 1 /* signed byte type */
448 #define VT_SHORT 2 /* short type */
449 #define VT_VOID 3 /* void type */
450 #define VT_PTR 4 /* pointer */
451 #define VT_ENUM 5 /* enum definition */
452 #define VT_FUNC 6 /* function type */
453 #define VT_STRUCT 7 /* struct/union definition */
454 #define VT_FLOAT 8 /* IEEE float */
455 #define VT_DOUBLE 9 /* IEEE double */
456 #define VT_LDOUBLE 10 /* IEEE long double */
457 #define VT_BOOL 11 /* ISOC99 boolean type */
458 #define VT_LLONG 12 /* 64 bit integer */
459 #define VT_LONG 13 /* long integer (NEVER USED as type, only
461 #define VT_BTYPE 0x000f /* mask for basic type */
462 #define VT_UNSIGNED 0x0010 /* unsigned type */
463 #define VT_ARRAY 0x0020 /* array type (also has VT_PTR) */
464 #define VT_BITFIELD 0x0040 /* bitfield modifier */
465 #define VT_CONSTANT 0x0800 /* const modifier */
466 #define VT_VOLATILE 0x1000 /* volatile modifier */
469 #define VT_EXTERN 0x00000080 /* extern definition */
470 #define VT_STATIC 0x00000100 /* static variable */
471 #define VT_TYPEDEF 0x00000200 /* typedef definition */
472 #define VT_INLINE 0x00000400 /* inline definition */
474 #define VT_STRUCT_SHIFT 16 /* shift for bitfield shift values */
476 /* type mask (except storage) */
477 #define VT_STORAGE (VT_EXTERN | VT_STATIC | VT_TYPEDEF | VT_INLINE)
478 #define VT_TYPE (~(VT_STORAGE))
482 /* warning: the following compare tokens depend on i386 asm code */
494 #define TOK_LAND 0xa0
498 #define TOK_MID 0xa3 /* inc/dec, to void constant */
500 #define TOK_UDIV 0xb0 /* unsigned division */
501 #define TOK_UMOD 0xb1 /* unsigned modulo */
502 #define TOK_PDIV 0xb2 /* fast division with undefined rounding for pointers */
503 #define TOK_CINT 0xb3 /* number in tokc */
504 #define TOK_CCHAR 0xb4 /* char constant in tokc */
505 #define TOK_STR 0xb5 /* pointer to string in tokc */
506 #define TOK_TWOSHARPS 0xb6 /* ## preprocessing token */
507 #define TOK_LCHAR 0xb7
508 #define TOK_LSTR 0xb8
509 #define TOK_CFLOAT 0xb9 /* float constant */
510 #define TOK_LINENUM 0xba /* line number info */
511 #define TOK_CDOUBLE 0xc0 /* double constant */
512 #define TOK_CLDOUBLE 0xc1 /* long double constant */
513 #define TOK_UMULL 0xc2 /* unsigned 32x32 -> 64 mul */
514 #define TOK_ADDC1 0xc3 /* add with carry generation */
515 #define TOK_ADDC2 0xc4 /* add with carry use */
516 #define TOK_SUBC1 0xc5 /* add with carry generation */
517 #define TOK_SUBC2 0xc6 /* add with carry use */
518 #define TOK_CUINT 0xc8 /* unsigned int constant */
519 #define TOK_CLLONG 0xc9 /* long long constant */
520 #define TOK_CULLONG 0xca /* unsigned long long constant */
521 #define TOK_ARROW 0xcb
522 #define TOK_DOTS 0xcc /* three dots */
523 #define TOK_SHR 0xcd /* unsigned shift right */
524 #define TOK_PPNUM 0xce /* preprocessor number */
526 #define TOK_SHL 0x01 /* shift left */
527 #define TOK_SAR 0x02 /* signed shift right */
529 /* assignement operators : normal operator or 0x80 */
530 #define TOK_A_MOD 0xa5
531 #define TOK_A_AND 0xa6
532 #define TOK_A_MUL 0xaa
533 #define TOK_A_ADD 0xab
534 #define TOK_A_SUB 0xad
535 #define TOK_A_DIV 0xaf
536 #define TOK_A_XOR 0xde
537 #define TOK_A_OR 0xfc
538 #define TOK_A_SHL 0x81
539 #define TOK_A_SAR 0x82
542 #define offsetof(type, field) ((size_t) &((type *)0)->field)
546 #define countof(tab) (sizeof(tab) / sizeof((tab)[0]))
549 /* WARNING: the content of this string encodes token numbers */
550 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";
552 #define TOK_EOF (-1) /* end of file */
553 #define TOK_LINEFEED 10 /* line feed */
555 /* all identificators and strings have token above that */
556 #define TOK_IDENT 256
558 /* only used for i386 asm opcodes definitions */
559 #define DEF_ASM(x) DEF(TOK_ASM_ ## x, #x)
562 DEF(TOK_ASM_ ## x ## b, #x "b") \
563 DEF(TOK_ASM_ ## x ## w, #x "w") \
564 DEF(TOK_ASM_ ## x ## l, #x "l") \
565 DEF(TOK_ASM_ ## x, #x)
568 DEF(TOK_ASM_ ## x ## w, #x "w") \
569 DEF(TOK_ASM_ ## x ## l, #x "l") \
570 DEF(TOK_ASM_ ## x, #x)
573 DEF(TOK_ASM_ ## f ## x ## s, "f" #x "s") \
574 DEF(TOK_ASM_ ## fi ## x ## l, "fi" #x "l") \
575 DEF(TOK_ASM_ ## f ## x ## l, "f" #x "l") \
576 DEF(TOK_ASM_ ## fi ## x ## s, "fi" #x "s")
579 DEF(TOK_ASM_ ## f ## x, "f" #x ) \
580 DEF(TOK_ASM_ ## f ## x ## p, "f" #x "p") \
583 #define DEF_ASMTEST(x) \
615 #define TOK_ASM_int TOK_INT
618 TOK_LAST
= TOK_IDENT
- 1,
619 #define DEF(id, str) id,
624 static const char tcc_keywords
[] =
625 #define DEF(id, str) str "\0"
630 #define TOK_UIDENT TOK_DEFINE
633 #define snprintf _snprintf
634 #define vsnprintf _vsnprintf
637 #if defined(WIN32) || defined(TCC_UCLIBC) || defined(__FreeBSD__)
638 /* currently incorrect */
639 long double strtold(const char *nptr
, char **endptr
)
641 return (long double)strtod(nptr
, endptr
);
643 float strtof(const char *nptr
, char **endptr
)
645 return (float)strtod(nptr
, endptr
);
648 /* XXX: need to define this to use them in non ISOC99 context */
649 extern float strtof (const char *__nptr
, char **__endptr
);
650 extern long double strtold (const char *__nptr
, char **__endptr
);
653 static char *pstrcpy(char *buf
, int buf_size
, const char *s
);
654 static char *pstrcat(char *buf
, int buf_size
, const char *s
);
656 static void next(void);
657 static void next_nomacro(void);
658 static void parse_expr_type(CType
*type
);
659 static void expr_type(CType
*type
);
660 static void unary_type(CType
*type
);
661 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
662 int case_reg
, int is_expr
);
663 static int expr_const(void);
664 static void expr_eq(void);
665 static void gexpr(void);
666 static void decl(int l
);
667 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
668 int first
, int size_only
);
669 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
670 int has_init
, int v
, int scope
);
672 void gv2(int rc1
, int rc2
);
673 void move_reg(int r
, int s
);
674 void save_regs(int n
);
675 void save_reg(int r
);
681 static void macro_subst(TokenString
*tok_str
,
682 Sym
**nested_list
, const int *macro_str
);
683 int save_reg_forced(int r
);
685 void force_charshort_cast(int t
);
686 static void gen_cast(CType
*type
);
688 static Sym
*sym_find(int v
);
689 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
);
692 static int type_size(CType
*type
, int *a
);
693 static inline CType
*pointed_type(CType
*type
);
694 static int pointed_size(CType
*type
);
695 static int lvalue_type(int t
);
696 static int parse_btype(CType
*type
, AttributeDef
*ad
);
697 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
);
698 static int is_compatible_types(CType
*type1
, CType
*type2
);
700 void error(const char *fmt
, ...);
702 void vset(CType
*type
, int r
, int v
);
703 void type_to_str(char *buf
, int buf_size
,
704 CType
*type
, const char *varstr
);
705 char *get_tok_str(int v
, CValue
*cv
);
706 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
707 unsigned long offset
, unsigned long size
);
708 static Sym
*external_global_sym(int v
, CType
*type
, int r
);
710 /* section generation */
711 static void section_realloc(Section
*sec
, unsigned long new_size
);
712 static void *section_ptr_add(Section
*sec
, unsigned long size
);
713 static void put_extern_sym(Sym
*sym
, Section
*section
,
714 unsigned long value
, unsigned long size
);
715 static void greloc(Section
*s
, Sym
*sym
, unsigned long addr
, int type
);
716 static int put_elf_str(Section
*s
, const char *sym
);
717 static int put_elf_sym(Section
*s
,
718 unsigned long value
, unsigned long size
,
719 int info
, int other
, int shndx
, const char *name
);
720 static int add_elf_sym(Section
*s
, unsigned long value
, unsigned long size
,
721 int info
, int sh_num
, const char *name
);
722 static void put_elf_reloc(Section
*symtab
, Section
*s
, unsigned long offset
,
723 int type
, int symbol
);
724 static void put_stabs(const char *str
, int type
, int other
, int desc
,
725 unsigned long value
);
726 static void put_stabs_r(const char *str
, int type
, int other
, int desc
,
727 unsigned long value
, Section
*sec
, int sym_index
);
728 static void put_stabn(int type
, int other
, int desc
, int value
);
729 static void put_stabd(int type
, int other
, int desc
);
730 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
);
732 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
733 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
734 static int tcc_add_file_internal(TCCState
*s
, const char *filename
, int flags
);
738 #ifdef CONFIG_TCC_ASM
740 typedef struct ExprValue
{
745 #define MAX_ASM_OPERANDS 30
747 typedef struct ASMOperand
{
748 int id
; /* GCC 3 optionnal identifier (0 if number only supported */
750 char asm_str
[16]; /* computed asm string for operand */
751 SValue
*vt
; /* C value of the expression */
752 int ref_index
; /* if >= 0, gives reference to a output constraint */
753 int priority
; /* priority, used to assign registers */
754 int reg
; /* if >= 0, register number used for this operand */
755 int is_llong
; /* true if double register value */
758 static void asm_expr(TCCState
*s1
, ExprValue
*pe
);
759 static int asm_int_expr(TCCState
*s1
);
760 static int find_constraint(ASMOperand
*operands
, int nb_operands
,
761 const char *name
, const char **pp
);
763 static int tcc_assemble(TCCState
*s1
, int do_preprocess
);
767 static void asm_instr(void);
769 /* true if float/double/long double type */
770 static inline int is_float(int t
)
774 return bt
== VT_LDOUBLE
|| bt
== VT_DOUBLE
|| bt
== VT_FLOAT
;
777 #ifdef TCC_TARGET_I386
778 #include "i386-gen.c"
781 #ifdef CONFIG_TCC_STATIC
783 #define RTLD_LAZY 0x001
784 #define RTLD_NOW 0x002
785 #define RTLD_GLOBAL 0x100
786 #define RTLD_DEFAULT NULL
788 /* dummy function for profiling */
789 void *dlopen(const char *filename
, int flag
)
794 const char *dlerror(void)
799 typedef struct TCCSyms
{
804 #define TCCSYM(a) { #a, &a, },
806 /* add the symbol you want here if no dynamic linking is done */
807 static TCCSyms tcc_syms
[] = {
815 void *dlsym(void *handle
, const char *symbol
)
819 while (p
->str
!= NULL
) {
820 if (!strcmp(p
->str
, symbol
))
829 /********************************************************/
831 /* we use our own 'finite' function to avoid potential problems with
832 non standard math libs */
833 /* XXX: endianness dependent */
834 int ieee_finite(double d
)
837 return ((unsigned)((p
[1] | 0x800fffff) + 1)) >> 31;
840 /* copy a string and truncate it. */
841 static char *pstrcpy(char *buf
, int buf_size
, const char *s
)
848 q_end
= buf
+ buf_size
- 1;
860 /* strcat and truncate. */
861 static char *pstrcat(char *buf
, int buf_size
, const char *s
)
866 pstrcpy(buf
+ len
, buf_size
- len
, s
);
870 /* memory management */
876 static inline void tcc_free(void *ptr
)
879 mem_cur_size
-= malloc_usable_size(ptr
);
884 static void *tcc_malloc(unsigned long size
)
889 error("memory full");
891 mem_cur_size
+= malloc_usable_size(ptr
);
892 if (mem_cur_size
> mem_max_size
)
893 mem_max_size
= mem_cur_size
;
898 static void *tcc_mallocz(unsigned long size
)
901 ptr
= tcc_malloc(size
);
902 memset(ptr
, 0, size
);
906 static inline void *tcc_realloc(void *ptr
, unsigned long size
)
910 mem_cur_size
-= malloc_usable_size(ptr
);
912 ptr1
= realloc(ptr
, size
);
914 /* NOTE: count not correct if alloc error, but not critical */
915 mem_cur_size
+= malloc_usable_size(ptr1
);
916 if (mem_cur_size
> mem_max_size
)
917 mem_max_size
= mem_cur_size
;
922 static char *tcc_strdup(const char *str
)
925 ptr
= tcc_malloc(strlen(str
) + 1);
930 #define free(p) use_tcc_free(p)
931 #define malloc(s) use_tcc_malloc(s)
932 #define realloc(p, s) use_tcc_realloc(p, s)
934 static void dynarray_add(void ***ptab
, int *nb_ptr
, void *data
)
941 /* every power of two we double array size */
942 if ((nb
& (nb
- 1)) == 0) {
947 pp
= tcc_realloc(pp
, nb_alloc
* sizeof(void *));
949 error("memory full");
956 Section
*new_section(TCCState
*s1
, const char *name
, int sh_type
, int sh_flags
)
960 sec
= tcc_mallocz(sizeof(Section
));
961 pstrcpy(sec
->name
, sizeof(sec
->name
), name
);
962 sec
->sh_type
= sh_type
;
963 sec
->sh_flags
= sh_flags
;
970 sec
->sh_addralign
= 4;
973 sec
->sh_addralign
= 1;
976 sec
->sh_addralign
= 32; /* default conservative alignment */
980 /* only add section if not private */
981 if (!(sh_flags
& SHF_PRIVATE
)) {
982 sec
->sh_num
= s1
->nb_sections
;
983 dynarray_add((void ***)&s1
->sections
, &s1
->nb_sections
, sec
);
988 static void free_section(Section
*s
)
994 /* realloc section and set its content to zero */
995 static void section_realloc(Section
*sec
, unsigned long new_size
)
1000 size
= sec
->data_allocated
;
1003 while (size
< new_size
)
1005 data
= tcc_realloc(sec
->data
, size
);
1007 error("memory full");
1008 memset(data
+ sec
->data_allocated
, 0, size
- sec
->data_allocated
);
1010 sec
->data_allocated
= size
;
1013 /* reserve at least 'size' bytes in section 'sec' from
1014 sec->data_offset. */
1015 static void *section_ptr_add(Section
*sec
, unsigned long size
)
1017 unsigned long offset
, offset1
;
1019 offset
= sec
->data_offset
;
1020 offset1
= offset
+ size
;
1021 if (offset1
> sec
->data_allocated
)
1022 section_realloc(sec
, offset1
);
1023 sec
->data_offset
= offset1
;
1024 return sec
->data
+ offset
;
1027 /* return a reference to a section, and create it if it does not
1029 Section
*find_section(TCCState
*s1
, const char *name
)
1033 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1034 sec
= s1
->sections
[i
];
1035 if (!strcmp(name
, sec
->name
))
1038 /* sections are created as PROGBITS */
1039 return new_section(s1
, name
, SHT_PROGBITS
, SHF_ALLOC
);
1042 /* update sym->c so that it points to an external symbol in section
1043 'section' with value 'value' */
1044 static void put_extern_sym(Sym
*sym
, Section
*section
,
1045 unsigned long value
, unsigned long size
)
1047 int sym_type
, sym_bind
, sh_num
, info
;
1052 sh_num
= section
->sh_num
;
1056 if ((sym
->type
.t
& VT_BTYPE
) == VT_FUNC
)
1057 sym_type
= STT_FUNC
;
1059 sym_type
= STT_OBJECT
;
1060 if (sym
->type
.t
& VT_STATIC
)
1061 sym_bind
= STB_LOCAL
;
1063 sym_bind
= STB_GLOBAL
;
1065 name
= get_tok_str(sym
->v
, NULL
);
1066 #ifdef CONFIG_TCC_BCHECK
1067 if (do_bounds_check
) {
1070 /* XXX: avoid doing that for statics ? */
1071 /* if bound checking is activated, we change some function
1072 names by adding the "__bound" prefix */
1075 /* XXX: we rely only on malloc hooks */
1087 strcpy(buf
, "__bound_");
1094 info
= ELF32_ST_INFO(sym_bind
, sym_type
);
1095 sym
->c
= add_elf_sym(symtab_section
, value
, size
, info
, sh_num
, name
);
1097 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
1098 esym
->st_value
= value
;
1099 esym
->st_size
= size
;
1100 esym
->st_shndx
= sh_num
;
1104 /* add a new relocation entry to symbol 'sym' in section 's' */
1105 static void greloc(Section
*s
, Sym
*sym
, unsigned long offset
, int type
)
1108 put_extern_sym(sym
, NULL
, 0, 0);
1109 /* now we can add ELF relocation info */
1110 put_elf_reloc(symtab_section
, s
, offset
, type
, sym
->c
);
1113 static inline int isid(int c
)
1115 return (c
>= 'a' && c
<= 'z') ||
1116 (c
>= 'A' && c
<= 'Z') ||
1120 static inline int isnum(int c
)
1122 return c
>= '0' && c
<= '9';
1125 static inline int isoct(int c
)
1127 return c
>= '0' && c
<= '7';
1130 static inline int toup(int c
)
1132 if (c
>= 'a' && c
<= 'z')
1133 return c
- 'a' + 'A';
1138 static void strcat_vprintf(char *buf
, int buf_size
, const char *fmt
, va_list ap
)
1142 vsnprintf(buf
+ len
, buf_size
- len
, fmt
, ap
);
1145 static void strcat_printf(char *buf
, int buf_size
, const char *fmt
, ...)
1149 strcat_vprintf(buf
, buf_size
, fmt
, ap
);
1153 void error1(TCCState
*s1
, int is_warning
, const char *fmt
, va_list ap
)
1160 for(f
= s1
->include_stack
; f
< s1
->include_stack_ptr
; f
++)
1161 strcat_printf(buf
, sizeof(buf
), "In file included from %s:%d:\n",
1162 (*f
)->filename
, (*f
)->line_num
);
1163 if (file
->line_num
> 0) {
1164 strcat_printf(buf
, sizeof(buf
),
1165 "%s:%d: ", file
->filename
, file
->line_num
);
1167 strcat_printf(buf
, sizeof(buf
),
1168 "%s: ", file
->filename
);
1171 strcat_printf(buf
, sizeof(buf
),
1175 strcat_printf(buf
, sizeof(buf
), "warning: ");
1176 strcat_vprintf(buf
, sizeof(buf
), fmt
, ap
);
1178 if (!s1
->error_func
) {
1179 /* default case: stderr */
1180 fprintf(stderr
, "%s\n", buf
);
1182 s1
->error_func(s1
->error_opaque
, buf
);
1184 if (!is_warning
|| s1
->warn_error
)
1189 void tcc_set_error_func(TCCState
*s
, void *error_opaque
,
1190 void (*error_func
)(void *opaque
, const char *msg
))
1192 s
->error_opaque
= error_opaque
;
1193 s
->error_func
= error_func
;
1197 /* error without aborting current compilation */
1198 void error_noabort(const char *fmt
, ...)
1200 TCCState
*s1
= tcc_state
;
1204 error1(s1
, 0, fmt
, ap
);
1208 void error(const char *fmt
, ...)
1210 TCCState
*s1
= tcc_state
;
1214 error1(s1
, 0, fmt
, ap
);
1216 /* better than nothing: in some cases, we accept to handle errors */
1217 if (s1
->error_set_jmp_enabled
) {
1218 longjmp(s1
->error_jmp_buf
, 1);
1220 /* XXX: eliminate this someday */
1225 void expect(const char *msg
)
1227 error("%s expected", msg
);
1230 void warning(const char *fmt
, ...)
1232 TCCState
*s1
= tcc_state
;
1236 error1(s1
, 1, fmt
, ap
);
1243 error("'%c' expected", c
);
1247 static void test_lvalue(void)
1249 if (!(vtop
->r
& VT_LVAL
))
1253 /* allocate a new token */
1254 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
1256 TokenSym
*ts
, **ptable
;
1259 if (tok_ident
>= SYM_FIRST_ANOM
)
1260 error("memory full");
1262 /* expand token table if needed */
1263 i
= tok_ident
- TOK_IDENT
;
1264 if ((i
% TOK_ALLOC_INCR
) == 0) {
1265 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
1267 error("memory full");
1268 table_ident
= ptable
;
1271 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
1272 table_ident
[i
] = ts
;
1273 ts
->tok
= tok_ident
++;
1274 ts
->sym_define
= NULL
;
1275 ts
->sym_label
= NULL
;
1276 ts
->sym_struct
= NULL
;
1277 ts
->sym_identifier
= NULL
;
1279 ts
->hash_next
= NULL
;
1280 memcpy(ts
->str
, str
, len
);
1281 ts
->str
[len
] = '\0';
1286 #define TOK_HASH_INIT 1
1287 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
1289 /* find a token and add it if not found */
1290 static TokenSym
*tok_alloc(const char *str
, int len
)
1292 TokenSym
*ts
, **pts
;
1298 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
1299 h
&= (TOK_HASH_SIZE
- 1);
1301 pts
= &hash_ident
[h
];
1306 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
1308 pts
= &(ts
->hash_next
);
1310 return tok_alloc_new(pts
, str
, len
);
1313 /* CString handling */
1315 static void cstr_realloc(CString
*cstr
, int new_size
)
1320 size
= cstr
->size_allocated
;
1322 size
= 8; /* no need to allocate a too small first string */
1323 while (size
< new_size
)
1325 data
= tcc_realloc(cstr
->data_allocated
, size
);
1327 error("memory full");
1328 cstr
->data_allocated
= data
;
1329 cstr
->size_allocated
= size
;
1334 static void cstr_ccat(CString
*cstr
, int ch
)
1337 size
= cstr
->size
+ 1;
1338 if (size
> cstr
->size_allocated
)
1339 cstr_realloc(cstr
, size
);
1340 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
1344 static void cstr_cat(CString
*cstr
, const char *str
)
1356 /* add a wide char */
1357 static void cstr_wccat(CString
*cstr
, int ch
)
1360 size
= cstr
->size
+ sizeof(int);
1361 if (size
> cstr
->size_allocated
)
1362 cstr_realloc(cstr
, size
);
1363 *(int *)(((unsigned char *)cstr
->data
) + size
- sizeof(int)) = ch
;
1367 static void cstr_new(CString
*cstr
)
1369 memset(cstr
, 0, sizeof(CString
));
1372 /* free string and reset it to NULL */
1373 static void cstr_free(CString
*cstr
)
1375 tcc_free(cstr
->data_allocated
);
1379 #define cstr_reset(cstr) cstr_free(cstr)
1381 static CString
*cstr_dup(CString
*cstr1
)
1386 cstr
= tcc_malloc(sizeof(CString
));
1389 cstr
->size_allocated
= size
;
1390 cstr
->data_allocated
= tcc_malloc(size
);
1391 cstr
->data
= cstr
->data_allocated
;
1392 memcpy(cstr
->data_allocated
, cstr1
->data_allocated
, size
);
1396 /* XXX: unicode ? */
1397 static void add_char(CString
*cstr
, int c
)
1399 if (c
== '\'' || c
== '\"' || c
== '\\') {
1400 /* XXX: could be more precise if char or string */
1401 cstr_ccat(cstr
, '\\');
1403 if (c
>= 32 && c
<= 126) {
1406 cstr_ccat(cstr
, '\\');
1408 cstr_ccat(cstr
, 'n');
1410 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
1411 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
1412 cstr_ccat(cstr
, '0' + (c
& 7));
1417 /* XXX: buffer overflow */
1418 /* XXX: float tokens */
1419 char *get_tok_str(int v
, CValue
*cv
)
1421 static char buf
[STRING_MAX_SIZE
+ 1];
1422 static CString cstr_buf
;
1428 /* NOTE: to go faster, we give a fixed buffer for small strings */
1429 cstr_reset(&cstr_buf
);
1430 cstr_buf
.data
= buf
;
1431 cstr_buf
.size_allocated
= sizeof(buf
);
1437 /* XXX: not quite exact, but only useful for testing */
1438 sprintf(p
, "%u", cv
->ui
);
1442 /* XXX: not quite exact, but only useful for testing */
1443 sprintf(p
, "%Lu", cv
->ull
);
1447 cstr_ccat(&cstr_buf
, '\'');
1448 add_char(&cstr_buf
, cv
->i
);
1449 cstr_ccat(&cstr_buf
, '\'');
1450 cstr_ccat(&cstr_buf
, '\0');
1454 len
= cstr
->size
- 1;
1456 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1457 cstr_ccat(&cstr_buf
, '\0');
1462 cstr_ccat(&cstr_buf
, '\"');
1464 len
= cstr
->size
- 1;
1466 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1468 len
= (cstr
->size
/ sizeof(int)) - 1;
1470 add_char(&cstr_buf
, ((int *)cstr
->data
)[i
]);
1472 cstr_ccat(&cstr_buf
, '\"');
1473 cstr_ccat(&cstr_buf
, '\0');
1482 return strcpy(p
, "<<=");
1484 return strcpy(p
, ">>=");
1486 if (v
< TOK_IDENT
) {
1487 /* search in two bytes table */
1501 } else if (v
< tok_ident
) {
1502 return table_ident
[v
- TOK_IDENT
]->str
;
1503 } else if (v
>= SYM_FIRST_ANOM
) {
1504 /* special name for anonymous symbol */
1505 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
1507 /* should never happen */
1512 return cstr_buf
.data
;
1515 /* push, without hashing */
1516 static Sym
*sym_push2(Sym
**ps
, int v
, int t
, int c
)
1519 s
= tcc_malloc(sizeof(Sym
));
1530 /* find a symbol and return its associated structure. 's' is the top
1531 of the symbol stack */
1532 static Sym
*sym_find2(Sym
*s
, int v
)
1542 /* structure lookup */
1543 static inline Sym
*struct_find(int v
)
1546 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1548 return table_ident
[v
]->sym_struct
;
1551 /* find an identifier */
1552 static inline Sym
*sym_find(int v
)
1555 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1557 return table_ident
[v
]->sym_identifier
;
1560 /* push a given symbol on the symbol stack */
1561 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
)
1570 s
= sym_push2(ps
, v
, type
->t
, c
);
1571 s
->type
.ref
= type
->ref
;
1573 /* don't record fields or anonymous symbols */
1575 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1576 /* record symbol in token array */
1577 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1579 ps
= &ts
->sym_struct
;
1581 ps
= &ts
->sym_identifier
;
1588 /* push a global identifier */
1589 static Sym
*global_identifier_push(int v
, int t
, int c
)
1592 s
= sym_push2(&global_stack
, v
, t
, c
);
1593 /* don't record anonymous symbol */
1594 if (v
< SYM_FIRST_ANOM
) {
1595 ps
= &table_ident
[v
- TOK_IDENT
]->sym_identifier
;
1596 /* modify the top most local identifier, so that
1597 sym_identifier will point to 's' when popped */
1599 ps
= &(*ps
)->prev_tok
;
1606 /* pop symbols until top reaches 'b' */
1607 static void sym_pop(Sym
**ptop
, Sym
*b
)
1617 /* remove symbol in token array */
1619 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1620 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1622 ps
= &ts
->sym_struct
;
1624 ps
= &ts
->sym_identifier
;
1635 BufferedFile
*tcc_open(TCCState
*s1
, const char *filename
)
1640 fd
= open(filename
, O_RDONLY
);
1643 bf
= tcc_malloc(sizeof(BufferedFile
));
1649 bf
->buf_ptr
= bf
->buffer
;
1650 bf
->buf_end
= bf
->buffer
;
1651 bf
->buffer
[0] = CH_EOB
; /* put eob symbol */
1652 pstrcpy(bf
->filename
, sizeof(bf
->filename
), filename
);
1654 bf
->ifndef_macro
= 0;
1655 bf
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
1656 // printf("opening '%s'\n", filename);
1660 void tcc_close(BufferedFile
*bf
)
1662 total_lines
+= bf
->line_num
;
1667 /* fill input buffer and peek next char */
1668 static int tcc_peekc_slow(BufferedFile
*bf
)
1671 /* only tries to read if really end of buffer */
1672 if (bf
->buf_ptr
>= bf
->buf_end
) {
1674 #if defined(PARSE_DEBUG)
1679 len
= read(bf
->fd
, bf
->buffer
, len
);
1686 bf
->buf_ptr
= bf
->buffer
;
1687 bf
->buf_end
= bf
->buffer
+ len
;
1688 *bf
->buf_end
= CH_EOB
;
1690 if (bf
->buf_ptr
< bf
->buf_end
) {
1691 return bf
->buf_ptr
[0];
1693 bf
->buf_ptr
= bf
->buf_end
;
1698 /* return the current character, handling end of block if necessary
1700 static int handle_eob(void)
1702 return tcc_peekc_slow(file
);
1705 /* read next char from current input file and handle end of input buffer */
1706 static inline void inp(void)
1708 ch
= *(++(file
->buf_ptr
));
1709 /* end of buffer/file handling */
1714 /* handle '\[\r]\n' */
1715 static void handle_stray(void)
1717 while (ch
== '\\') {
1722 } else if (ch
== '\r') {
1730 error("stray '\\' in program");
1735 /* skip the stray and handle the \\n case. Output an error if
1736 incorrect char after the stray */
1737 static int handle_stray1(uint8_t *p
)
1741 if (p
>= file
->buf_end
) {
1758 /* handle just the EOB case, but not stray */
1759 #define PEEKC_EOB(c, p)\
1770 /* handle the complicated stray case */
1771 #define PEEKC(c, p)\
1776 c = handle_stray1(p);\
1781 /* input with '\[\r]\n' handling. Note that this function cannot
1782 handle other characters after '\', so you cannot call it inside
1783 strings or comments */
1784 static void minp(void)
1792 /* single line C++ comments */
1793 static uint8_t *parse_line_comment(uint8_t *p
)
1800 if (c
== '\n' || c
== CH_EOF
) {
1802 } else if (c
== '\\') {
1807 } else if (c
== '\r') {
1822 static uint8_t *parse_comment(uint8_t *p
)
1828 /* fast skip loop */
1831 if (c
== '\n' || c
== '*' || c
== '\\')
1835 if (c
== '\n' || c
== '*' || c
== '\\')
1839 /* now we can handle all the cases */
1843 } else if (c
== '*') {
1849 } else if (c
== '/') {
1850 goto end_of_comment
;
1851 } else if (c
== '\\') {
1856 /* skip '\[\r]\n', otherwise just skip the stray */
1862 } else if (c
== '\r') {
1879 /* stray, eob or eof */
1884 error("unexpected end of file in comment");
1885 } else if (c
== '\\') {
1897 /* space exlcuding newline */
1898 static inline int is_space(int ch
)
1900 return ch
== ' ' || ch
== '\t' || ch
== '\v' || ch
== '\f' || ch
== '\r';
1903 static inline void skip_spaces(void)
1905 while (is_space(ch
))
1909 /* parse a string without interpreting escapes */
1910 static uint8_t *parse_pp_string(uint8_t *p
,
1911 int sep
, CString
*str
)
1919 } else if (c
== '\\') {
1924 unterminated_string
:
1925 /* XXX: indicate line number of start of string */
1926 error("missing terminating %c character", sep
);
1927 } else if (c
== '\\') {
1928 /* escape : just skip \[\r]\n */
1933 } else if (c
== '\r') {
1936 expect("'\n' after '\r'");
1939 } else if (c
== CH_EOF
) {
1940 goto unterminated_string
;
1943 cstr_ccat(str
, '\\');
1949 } else if (c
== '\n') {
1952 } else if (c
== '\r') {
1955 cstr_ccat(str
, '\r');
1971 /* skip block of text until #else, #elif or #endif. skip also pairs of
1973 void preprocess_skip(void)
1975 int a
, start_of_line
, c
;
2002 } else if (c
== '\\') {
2003 /* XXX: incorrect: should not give an error */
2004 ch
= file
->buf_ptr
[0];
2012 p
= parse_pp_string(p
, c
, NULL
);
2021 p
= parse_comment(p
);
2022 } else if (ch
== '/') {
2023 p
= parse_line_comment(p
);
2029 if (start_of_line
) {
2034 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
2036 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
2038 else if (tok
== TOK_ENDIF
)
2052 /* ParseState handling */
2054 /* XXX: currently, no include file info is stored. Thus, we cannot display
2055 accurate messages if the function or data definition spans multiple
2058 /* save current parse state in 's' */
2059 void save_parse_state(ParseState
*s
)
2061 s
->line_num
= file
->line_num
;
2062 s
->macro_ptr
= macro_ptr
;
2067 /* restore parse state from 's' */
2068 void restore_parse_state(ParseState
*s
)
2070 file
->line_num
= s
->line_num
;
2071 macro_ptr
= s
->macro_ptr
;
2076 /* return the number of additional 'ints' necessary to store the
2078 static inline int tok_ext_size(int t
)
2097 return LDOUBLE_SIZE
/ 4;
2103 /* token string handling */
2105 static inline void tok_str_new(TokenString
*s
)
2109 s
->allocated_len
= 0;
2110 s
->last_line_num
= -1;
2113 static void tok_str_free(int *str
)
2122 /* NOTE: we test zero separately so that GCC can generate a
2123 table for the following switch */
2138 /* XXX: use a macro to be portable on 64 bit ? */
2139 cstr
= (CString
*)p
[1];
2150 p
+= 1 + (LDOUBLE_SIZE
/ 4);
2160 static int *tok_str_realloc(TokenString
*s
)
2164 len
= s
->allocated_len
+ TOK_STR_ALLOC_INCR
;
2165 str
= tcc_realloc(s
->str
, len
* sizeof(int));
2167 error("memory full");
2168 s
->allocated_len
= len
;
2173 static void tok_str_add(TokenString
*s
, int t
)
2179 if (len
>= s
->allocated_len
)
2180 str
= tok_str_realloc(s
);
2185 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
2192 /* allocate space for worst case */
2193 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
2194 str
= tok_str_realloc(s
);
2203 str
[len
++] = cv
->tab
[0];
2208 str
[len
++] = (int)cstr_dup(cv
->cstr
);
2213 str
[len
++] = cv
->tab
[0];
2214 str
[len
++] = cv
->tab
[1];
2217 #if LDOUBLE_SIZE == 12
2218 str
[len
++] = cv
->tab
[0];
2219 str
[len
++] = cv
->tab
[1];
2220 str
[len
++] = cv
->tab
[2];
2222 #error add long double size support
2231 /* add the current parse token in token string 's' */
2232 static void tok_str_add_tok(TokenString
*s
)
2236 /* save line number info */
2237 if (file
->line_num
!= s
->last_line_num
) {
2238 s
->last_line_num
= file
->line_num
;
2239 cval
.i
= s
->last_line_num
;
2240 tok_str_add2(s
, TOK_LINENUM
, &cval
);
2242 tok_str_add2(s
, tok
, &tokc
);
2245 #if LDOUBLE_SIZE == 12
2246 #define LDOUBLE_GET(p, cv) \
2251 #error add long double size support
2255 /* get a token from an integer array and increment pointer
2256 accordingly. we code it as a macro to avoid pointer aliasing. */
2257 #define TOK_GET(t, p, cv) \
2279 case TOK_CLDOUBLE: \
2280 LDOUBLE_GET(p, cv); \
2281 p += LDOUBLE_SIZE / 4; \
2288 /* defines handling */
2289 static inline void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
2293 s
= sym_push2(&define_stack
, v
, macro_type
, (int)str
);
2294 s
->next
= first_arg
;
2295 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
2298 /* undefined a define symbol. Its name is just set to zero */
2299 static void define_undef(Sym
*s
)
2303 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2304 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2308 static inline Sym
*define_find(int v
)
2311 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2313 return table_ident
[v
]->sym_define
;
2316 /* free define stack until top reaches 'b' */
2317 static void free_defines(Sym
*b
)
2325 /* do not free args or predefined defines */
2327 tok_str_free((int *)top
->c
);
2329 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2330 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2338 static Sym
*label_find(int v
)
2341 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2343 return table_ident
[v
]->sym_label
;
2346 static Sym
*label_push(Sym
**ptop
, int v
, int flags
)
2349 s
= sym_push2(ptop
, v
, 0, 0);
2351 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
2352 if (ptop
== &global_label_stack
) {
2353 /* modify the top most local identifier, so that
2354 sym_identifier will point to 's' when popped */
2356 ps
= &(*ps
)->prev_tok
;
2363 /* pop labels until element last is reached. Look if any labels are
2364 undefined. Define symbols if '&&label' was used. */
2365 static void label_pop(Sym
**ptop
, Sym
*slast
)
2368 for(s
= *ptop
; s
!= slast
; s
= s1
) {
2370 if (s
->r
== LABEL_DECLARED
) {
2371 warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
2372 } else if (s
->r
== LABEL_FORWARD
) {
2373 error("label '%s' used but not defined",
2374 get_tok_str(s
->v
, NULL
));
2377 /* define corresponding symbol. A size of
2379 put_extern_sym(s
, cur_text_section
, (long)s
->next
, 1);
2383 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
2389 /* eval an expression for #if/#elif */
2390 static int expr_preprocess(void)
2396 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2397 next(); /* do macro subst */
2398 if (tok
== TOK_DEFINED
) {
2403 c
= define_find(tok
) != 0;
2408 } else if (tok
>= TOK_IDENT
) {
2409 /* if undefined macro */
2413 tok_str_add_tok(&str
);
2415 tok_str_add(&str
, -1); /* simulate end of file */
2416 tok_str_add(&str
, 0);
2417 /* now evaluate C constant expression */
2418 macro_ptr
= str
.str
;
2422 tok_str_free(str
.str
);
2426 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
2427 static void tok_print(int *str
)
2433 TOK_GET(t
, str
, cval
);
2436 printf(" %s", get_tok_str(t
, &cval
));
2442 /* parse after #define */
2443 static void parse_define(void)
2445 Sym
*s
, *first
, **ps
;
2446 int v
, t
, varg
, is_vaargs
, c
;
2451 error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
2452 /* XXX: should check if same macro (ANSI) */
2455 /* '(' must be just after macro definition for MACRO_FUNC */
2456 c
= file
->buf_ptr
[0];
2458 c
= handle_stray1(file
->buf_ptr
);
2463 while (tok
!= ')') {
2467 if (varg
== TOK_DOTS
) {
2468 varg
= TOK___VA_ARGS__
;
2470 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
2474 if (varg
< TOK_IDENT
)
2475 error("badly punctuated parameter list");
2476 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
2487 /* EOF testing necessary for '-D' handling */
2488 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2489 tok_str_add2(&str
, tok
, &tokc
);
2492 tok_str_add(&str
, 0);
2494 printf("define %s %d: ", get_tok_str(v
, NULL
), t
);
2497 define_push(v
, t
, str
.str
, first
);
2500 /* XXX: use a token or a hash table to accelerate matching ? */
2501 static CachedInclude
*search_cached_include(TCCState
*s1
,
2502 int type
, const char *filename
)
2507 for(i
= 0;i
< s1
->nb_cached_includes
; i
++) {
2508 e
= s1
->cached_includes
[i
];
2509 if (e
->type
== type
&& !strcmp(e
->filename
, filename
))
2515 static inline void add_cached_include(TCCState
*s1
, int type
,
2516 const char *filename
, int ifndef_macro
)
2520 if (search_cached_include(s1
, type
, filename
))
2523 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
2525 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
2529 strcpy(e
->filename
, filename
);
2530 e
->ifndef_macro
= ifndef_macro
;
2531 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
2534 /* is_bof is true if first non space token at beginning of file */
2535 static void preprocess(int is_bof
)
2537 TCCState
*s1
= tcc_state
;
2538 int size
, i
, c
, n
, saved_parse_flags
;
2539 char buf
[1024], *q
, *p
;
2545 saved_parse_flags
= parse_flags
;
2546 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
|
2547 PARSE_FLAG_LINEFEED
;
2557 s
= define_find(tok
);
2558 /* undefine symbol by putting an invalid name */
2563 ch
= file
->buf_ptr
[0];
2564 /* XXX: incorrect if comments : use next_nomacro with a special mode */
2569 } else if (ch
== '\"') {
2572 /* XXX: better stray handling */
2575 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
2576 if ((q
- buf
) < sizeof(buf
) - 1)
2583 /* eat all spaces and comments after include */
2584 /* XXX: slightly incorrect */
2585 while (ch1
!= '\n' && ch1
!= CH_EOF
)
2589 /* computed #include : either we have only strings or
2590 we have anything enclosed in '<>' */
2593 if (tok
== TOK_STR
) {
2594 while (tok
!= TOK_LINEFEED
) {
2595 if (tok
!= TOK_STR
) {
2597 error("'#include' expects \"FILENAME\" or <FILENAME>");
2599 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
2605 while (tok
!= TOK_LINEFEED
) {
2606 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
2610 /* check syntax and remove '<>' */
2611 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
2612 goto include_syntax
;
2613 memmove(buf
, buf
+ 1, len
- 2);
2614 buf
[len
- 2] = '\0';
2619 e
= search_cached_include(s1
, c
, buf
);
2620 if (e
&& define_find(e
->ifndef_macro
)) {
2621 /* no need to parse the include because the 'ifndef macro'
2624 printf("%s: skipping %s\n", file
->filename
, buf
);
2628 /* first search in current dir if "header.h" */
2630 p
= strrchr(file
->filename
, '/');
2632 size
= p
+ 1 - file
->filename
;
2633 if (size
> sizeof(buf1
) - 1)
2634 size
= sizeof(buf1
) - 1;
2635 memcpy(buf1
, file
->filename
, size
);
2637 pstrcat(buf1
, sizeof(buf1
), buf
);
2638 f
= tcc_open(s1
, buf1
);
2642 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
2643 error("#include recursion too deep");
2644 /* now search in all the include paths */
2645 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
2646 for(i
= 0; i
< n
; i
++) {
2648 if (i
< s1
->nb_include_paths
)
2649 path
= s1
->include_paths
[i
];
2651 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
2652 pstrcpy(buf1
, sizeof(buf1
), path
);
2653 pstrcat(buf1
, sizeof(buf1
), "/");
2654 pstrcat(buf1
, sizeof(buf1
), buf
);
2655 f
= tcc_open(s1
, buf1
);
2659 error("include file '%s' not found", buf
);
2663 printf("%s: including %s\n", file
->filename
, buf1
);
2666 pstrcpy(f
->inc_filename
, sizeof(f
->inc_filename
), buf
);
2667 /* push current file in stack */
2668 /* XXX: fix current line init */
2669 *s1
->include_stack_ptr
++ = file
;
2671 /* add include file debug info */
2673 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
2675 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
2676 ch
= file
->buf_ptr
[0];
2684 c
= expr_preprocess();
2690 if (tok
< TOK_IDENT
)
2691 error("invalid argument for '#if%sdef'", c
? "n" : "");
2695 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
2697 file
->ifndef_macro
= tok
;
2700 c
= (define_find(tok
) != 0) ^ c
;
2702 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
2703 error("memory full");
2704 *s1
->ifdef_stack_ptr
++ = c
;
2707 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
2708 error("#else without matching #if");
2709 if (s1
->ifdef_stack_ptr
[-1] & 2)
2710 error("#else after #else");
2711 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
2714 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
2715 error("#elif without matching #if");
2716 c
= s1
->ifdef_stack_ptr
[-1];
2718 error("#elif after #else");
2719 /* last #if/#elif expression was true: we skip */
2722 c
= expr_preprocess();
2723 s1
->ifdef_stack_ptr
[-1] = c
;
2733 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
2734 error("#endif without matching #if");
2735 s1
->ifdef_stack_ptr
--;
2736 /* '#ifndef macro' was at the start of file. Now we check if
2737 an '#endif' is exactly at the end of file */
2738 if (file
->ifndef_macro
&&
2739 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
2740 file
->ifndef_macro_saved
= file
->ifndef_macro
;
2741 /* need to set to zero to avoid false matches if another
2742 #ifndef at middle of file */
2743 file
->ifndef_macro
= 0;
2744 while (tok
!= TOK_LINEFEED
)
2746 tok_flags
|= TOK_FLAG_ENDIF
;
2752 if (tok
!= TOK_CINT
)
2754 file
->line_num
= tokc
.i
- 1; /* the line number will be incremented after */
2756 if (tok
!= TOK_LINEFEED
) {
2759 pstrcpy(file
->filename
, sizeof(file
->filename
),
2760 (char *)tokc
.cstr
->data
);
2766 ch
= file
->buf_ptr
[0];
2769 while (ch
!= '\n' && ch
!= CH_EOF
) {
2770 if ((q
- buf
) < sizeof(buf
) - 1)
2776 error("#error %s", buf
);
2778 warning("#warning %s", buf
);
2784 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_CINT
) {
2785 /* '!' is ignored to allow C scripts. numbers are ignored
2786 to emulate cpp behaviour */
2788 error("invalid preprocessing directive #%s", get_tok_str(tok
, &tokc
));
2792 /* ignore other preprocess commands or #! for C scripts */
2793 while (tok
!= TOK_LINEFEED
)
2796 parse_flags
= saved_parse_flags
;
2799 /* evaluate escape codes in a string. */
2800 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
2815 case '0': case '1': case '2': case '3':
2816 case '4': case '5': case '6': case '7':
2817 /* at most three octal digits */
2822 n
= n
* 8 + c
- '0';
2826 n
= n
* 8 + c
- '0';
2831 goto add_char_nonext
;
2837 if (c
>= 'a' && c
<= 'f')
2839 else if (c
>= 'A' && c
<= 'F')
2849 goto add_char_nonext
;
2873 goto invalid_escape
;
2883 error("invalid escaped char");
2889 cstr_ccat(outstr
, c
);
2891 cstr_wccat(outstr
, c
);
2893 /* add a trailing '\0' */
2895 cstr_ccat(outstr
, '\0');
2897 cstr_wccat(outstr
, '\0');
2900 /* we use 64 bit numbers */
2903 /* bn = (bn << shift) | or_val */
2904 void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
2908 for(i
=0;i
<BN_SIZE
;i
++) {
2910 bn
[i
] = (v
<< shift
) | or_val
;
2911 or_val
= v
>> (32 - shift
);
2915 void bn_zero(unsigned int *bn
)
2918 for(i
=0;i
<BN_SIZE
;i
++) {
2923 /* parse number in null terminated string 'p' and return it in the
2925 void parse_number(const char *p
)
2927 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
2929 unsigned int bn
[BN_SIZE
];
2940 goto float_frac_parse
;
2941 } else if (t
== '0') {
2942 if (ch
== 'x' || ch
== 'X') {
2946 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
2952 /* parse all digits. cannot check octal numbers at this stage
2953 because of floating point constants */
2955 if (ch
>= 'a' && ch
<= 'f')
2957 else if (ch
>= 'A' && ch
<= 'F')
2965 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
2967 error("number too long");
2973 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
2974 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
2976 /* NOTE: strtox should support that for hexa numbers, but
2977 non ISOC99 libcs do not support it, so we prefer to do
2979 /* hexadecimal or binary floats */
2980 /* XXX: handle overflows */
2992 } else if (t
>= 'a') {
2994 } else if (t
>= 'A') {
2999 bn_lshift(bn
, shift
, t
);
3006 if (t
>= 'a' && t
<= 'f') {
3008 } else if (t
>= 'A' && t
<= 'F') {
3010 } else if (t
>= '0' && t
<= '9') {
3016 error("invalid digit");
3017 bn_lshift(bn
, shift
, t
);
3022 if (ch
!= 'p' && ch
!= 'P')
3029 } else if (ch
== '-') {
3033 if (ch
< '0' || ch
> '9')
3034 expect("exponent digits");
3035 while (ch
>= '0' && ch
<= '9') {
3036 exp_val
= exp_val
* 10 + ch
- '0';
3039 exp_val
= exp_val
* s
;
3041 /* now we can generate the number */
3042 /* XXX: should patch directly float number */
3043 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
3044 d
= ldexp(d
, exp_val
- frac_bits
);
3049 /* float : should handle overflow */
3051 } else if (t
== 'L') {
3054 /* XXX: not large enough */
3055 tokc
.ld
= (long double)d
;
3061 /* decimal floats */
3063 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3068 while (ch
>= '0' && ch
<= '9') {
3069 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3075 if (ch
== 'e' || ch
== 'E') {
3076 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3080 if (ch
== '-' || ch
== '+') {
3081 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3086 if (ch
< '0' || ch
> '9')
3087 expect("exponent digits");
3088 while (ch
>= '0' && ch
<= '9') {
3089 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3101 tokc
.f
= strtof(token_buf
, NULL
);
3102 } else if (t
== 'L') {
3105 tokc
.ld
= strtold(token_buf
, NULL
);
3108 tokc
.d
= strtod(token_buf
, NULL
);
3112 unsigned long long n
, n1
;
3115 /* integer number */
3118 if (b
== 10 && *q
== '0') {
3125 /* no need for checks except for base 10 / 8 errors */
3128 } else if (t
>= 'a') {
3130 } else if (t
>= 'A') {
3135 error("invalid digit");
3139 /* detect overflow */
3140 /* XXX: this test is not reliable */
3142 error("integer constant overflow");
3145 /* XXX: not exactly ANSI compliant */
3146 if ((n
& 0xffffffff00000000LL
) != 0) {
3151 } else if (n
> 0x7fffffff) {
3162 error("three 'l's in integer constant");
3165 if (tok
== TOK_CINT
)
3167 else if (tok
== TOK_CUINT
)
3171 } else if (t
== 'U') {
3173 error("two 'u's in integer constant");
3175 if (tok
== TOK_CINT
)
3177 else if (tok
== TOK_CLLONG
)
3184 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
3192 #define PARSE2(c1, tok1, c2, tok2) \
3203 /* return next token without macro substitution */
3204 static inline void next_nomacro1(void)
3224 /* first look if it is in fact an end of buffer */
3225 if (p
>= file
->buf_end
) {
3229 if (p
>= file
->buf_end
)
3242 TCCState
*s1
= tcc_state
;
3243 if (parse_flags
& PARSE_FLAG_LINEFEED
) {
3245 } else if (s1
->include_stack_ptr
== s1
->include_stack
||
3246 !(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3247 /* no include left : end of file. */
3250 /* pop include file */
3252 /* test if previous '#endif' was after a #ifdef at
3254 if (tok_flags
& TOK_FLAG_ENDIF
) {
3256 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
3258 add_cached_include(s1
, file
->inc_type
, file
->inc_filename
,
3259 file
->ifndef_macro_saved
);
3262 /* add end of include file debug info */
3264 put_stabd(N_EINCL
, 0, 0);
3266 /* pop include stack */
3268 s1
->include_stack_ptr
--;
3269 file
= *s1
->include_stack_ptr
;
3277 if (parse_flags
& PARSE_FLAG_LINEFEED
) {
3281 tok_flags
|= TOK_FLAG_BOL
;
3290 if ((tok_flags
& TOK_FLAG_BOL
) &&
3291 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3293 preprocess(tok_flags
& TOK_FLAG_BOF
);
3299 tok
= TOK_TWOSHARPS
;
3306 case 'a': case 'b': case 'c': case 'd':
3307 case 'e': case 'f': case 'g': case 'h':
3308 case 'i': case 'j': case 'k': case 'l':
3309 case 'm': case 'n': case 'o': case 'p':
3310 case 'q': case 'r': case 's': case 't':
3311 case 'u': case 'v': case 'w': case 'x':
3313 case 'A': case 'B': case 'C': case 'D':
3314 case 'E': case 'F': case 'G': case 'H':
3315 case 'I': case 'J': case 'K':
3316 case 'M': case 'N': case 'O': case 'P':
3317 case 'Q': case 'R': case 'S': case 'T':
3318 case 'U': case 'V': case 'W': case 'X':
3324 h
= TOK_HASH_FUNC(h
, c
);
3328 if (!isidnum_table
[c
])
3330 h
= TOK_HASH_FUNC(h
, c
);
3337 /* fast case : no stray found, so we have the full token
3338 and we have already hashed it */
3340 h
&= (TOK_HASH_SIZE
- 1);
3341 pts
= &hash_ident
[h
];
3346 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
3348 pts
= &(ts
->hash_next
);
3350 ts
= tok_alloc_new(pts
, p1
, len
);
3354 cstr_reset(&tokcstr
);
3357 cstr_ccat(&tokcstr
, *p1
);
3363 while (isidnum_table
[c
]) {
3364 cstr_ccat(&tokcstr
, c
);
3367 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
3373 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
3375 goto parse_ident_fast
;
3378 if (c
== '\'' || c
== '\"') {
3382 cstr_reset(&tokcstr
);
3383 cstr_ccat(&tokcstr
, 'L');
3384 goto parse_ident_slow
;
3388 case '0': case '1': case '2': case '3':
3389 case '4': case '5': case '6': case '7':
3392 cstr_reset(&tokcstr
);
3393 /* after the first digit, accept digits, alpha, '.' or sign if
3394 prefixed by 'eEpP' */
3398 cstr_ccat(&tokcstr
, c
);
3400 if (!(isnum(c
) || isid(c
) || c
== '.' ||
3401 ((c
== '+' || c
== '-') &&
3402 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
3405 /* We add a trailing '\0' to ease parsing */
3406 cstr_ccat(&tokcstr
, '\0');
3407 tokc
.cstr
= &tokcstr
;
3411 /* special dot handling because it can also start a number */
3414 cstr_reset(&tokcstr
);
3415 cstr_ccat(&tokcstr
, '.');
3417 } else if (c
== '.') {
3437 /* parse the string */
3439 p
= parse_pp_string(p
, sep
, &str
);
3440 cstr_ccat(&str
, '\0');
3442 /* eval the escape (should be done as TOK_PPNUM) */
3443 cstr_reset(&tokcstr
);
3444 parse_escape_string(&tokcstr
, str
.data
, is_long
);
3449 /* XXX: make it portable */
3453 char_size
= sizeof(int);
3454 if (tokcstr
.size
<= char_size
)
3455 error("empty character constant");
3456 if (tokcstr
.size
> 2 * char_size
)
3457 warning("multi-character character constant");
3459 tokc
.i
= *(int8_t *)tokcstr
.data
;
3462 tokc
.i
= *(int *)tokcstr
.data
;
3466 tokc
.cstr
= &tokcstr
;
3480 } else if (c
== '<') {
3498 } else if (c
== '>') {
3516 } else if (c
== '=') {
3529 } else if (c
== '=') {
3542 } else if (c
== '=') {
3555 } else if (c
== '=') {
3558 } else if (c
== '>') {
3566 PARSE2('!', '!', '=', TOK_NE
)
3567 PARSE2('=', '=', '=', TOK_EQ
)
3568 PARSE2('*', '*', '=', TOK_A_MUL
)
3569 PARSE2('%', '%', '=', TOK_A_MOD
)
3570 PARSE2('^', '^', '=', TOK_A_XOR
)
3572 /* comments or operator */
3576 p
= parse_comment(p
);
3578 } else if (c
== '/') {
3579 p
= parse_line_comment(p
);
3581 } else if (c
== '=') {
3601 case '$': /* only used in assembler */
3606 error("unrecognized character \\x%02x", c
);
3611 #if defined(PARSE_DEBUG)
3612 printf("token = %s\n", get_tok_str(tok
, &tokc
));
3616 /* return next token without macro substitution. Can read input from
3618 static void next_nomacro(void)
3624 TOK_GET(tok
, macro_ptr
, tokc
);
3625 if (tok
== TOK_LINENUM
) {
3626 file
->line_num
= tokc
.i
;
3635 /* substitute args in macro_str and return allocated string */
3636 static int *macro_arg_subst(Sym
**nested_list
, int *macro_str
, Sym
*args
)
3638 int *st
, last_tok
, t
, notfirst
;
3647 TOK_GET(t
, macro_str
, cval
);
3652 TOK_GET(t
, macro_str
, cval
);
3655 s
= sym_find2(args
, t
);
3662 cstr_ccat(&cstr
, ' ');
3663 TOK_GET(t
, st
, cval
);
3664 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
3667 cstr_ccat(&cstr
, '\0');
3669 printf("stringize: %s\n", (char *)cstr
.data
);
3673 tok_str_add2(&str
, TOK_STR
, &cval
);
3676 tok_str_add2(&str
, t
, &cval
);
3678 } else if (t
>= TOK_IDENT
) {
3679 s
= sym_find2(args
, t
);
3682 /* if '##' is present before or after, no arg substitution */
3683 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
3684 /* special case for var arg macros : ## eats the
3685 ',' if empty VA_ARGS variable. */
3686 /* XXX: test of the ',' is not 100%
3687 reliable. should fix it to avoid security
3689 if (gnu_ext
&& s
->type
.t
&&
3690 last_tok
== TOK_TWOSHARPS
&&
3691 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
3693 /* suppress ',' '##' */
3696 /* suppress '##' and add variable */
3704 TOK_GET(t1
, st
, cval
);
3707 tok_str_add2(&str
, t1
, &cval
);
3711 macro_subst(&str
, nested_list
, st
);
3714 tok_str_add(&str
, t
);
3717 tok_str_add2(&str
, t
, &cval
);
3721 tok_str_add(&str
, 0);
3725 static char const ab_month_name
[12][4] =
3727 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3728 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3731 /* do macro substitution of current token with macro 's' and add
3732 result to (tok_str,tok_len). 'nested_list' is the list of all
3733 macros we got inside to avoid recursing. Return non zero if no
3734 substitution needs to be done */
3735 static int macro_subst_tok(TokenString
*tok_str
,
3736 Sym
**nested_list
, Sym
*s
)
3738 Sym
*args
, *sa
, *sa1
;
3739 int mstr_allocated
, parlevel
, *mstr
, t
;
3745 /* if symbol is a macro, prepare substitution */
3747 /* special macros */
3748 if (tok
== TOK___LINE__
) {
3749 cval
.i
= file
->line_num
;
3750 tok_str_add2(tok_str
, TOK_CINT
, &cval
);
3751 } else if (tok
== TOK___FILE__
) {
3752 cstrval
= file
->filename
;
3754 tok_str_add2(tok_str
, TOK_STR
, &cval
);
3755 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
3761 tm
= localtime(&ti
);
3762 if (tok
== TOK___DATE__
) {
3763 snprintf(buf
, sizeof(buf
), "%s %2d %d",
3764 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
3766 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
3767 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
3772 cstr_cat(&cstr
, cstrval
);
3773 cstr_ccat(&cstr
, '\0');
3775 tok_str_add2(tok_str
, TOK_STR
, &cval
);
3780 if (s
->type
.t
== MACRO_FUNC
) {
3781 /* NOTE: we do not use next_nomacro to avoid eating the
3782 next token. XXX: find better solution */
3786 /* end of macro stream: we must look at the token
3787 after in the file */
3793 /* XXX: incorrect with comments */
3794 ch
= file
->buf_ptr
[0];
3795 while (is_space(ch
) || ch
== '\n')
3799 if (t
!= '(') /* no macro subst */
3802 /* argument macro */
3807 /* NOTE: empty args are allowed, except if no args */
3809 /* handle '()' case */
3810 if (!args
&& tok
== ')')
3813 error("macro '%s' used with too many args",
3814 get_tok_str(s
->v
, 0));
3817 /* NOTE: non zero sa->t indicates VA_ARGS */
3818 while ((parlevel
> 0 ||
3820 (tok
!= ',' || sa
->type
.t
))) &&
3824 else if (tok
== ')')
3826 tok_str_add2(&str
, tok
, &tokc
);
3829 tok_str_add(&str
, 0);
3830 sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, (int)str
.str
);
3833 /* special case for gcc var args: add an empty
3834 var arg argument if it is omitted */
3835 if (sa
&& sa
->type
.t
&& gnu_ext
)
3845 error("macro '%s' used with too few args",
3846 get_tok_str(s
->v
, 0));
3849 /* now subst each arg */
3850 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3855 tok_str_free((int *)sa
->c
);
3861 sym_push2(nested_list
, s
->v
, 0, 0);
3862 macro_subst(tok_str
, nested_list
, mstr
);
3863 /* pop nested defined symbol */
3865 *nested_list
= sa1
->prev
;
3873 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3874 return the resulting string (which must be freed). */
3875 static inline int *macro_twosharps(const int *macro_str
)
3878 const int *macro_ptr1
, *start_macro_ptr
, *ptr
, *saved_macro_ptr
;
3880 const char *p1
, *p2
;
3882 TokenString macro_str1
;
3885 start_macro_ptr
= macro_str
;
3886 /* we search the first '##' */
3888 macro_ptr1
= macro_str
;
3889 TOK_GET(t
, macro_str
, cval
);
3890 /* nothing more to do if end of string */
3893 if (*macro_str
== TOK_TWOSHARPS
)
3897 /* we saw '##', so we need more processing to handle it */
3899 tok_str_new(¯o_str1
);
3903 /* add all tokens seen so far */
3904 for(ptr
= start_macro_ptr
; ptr
< macro_ptr1
;) {
3905 TOK_GET(t
, ptr
, cval
);
3906 tok_str_add2(¯o_str1
, t
, &cval
);
3908 saved_macro_ptr
= macro_ptr
;
3909 /* XXX: get rid of the use of macro_ptr here */
3910 macro_ptr
= (int *)macro_str
;
3912 while (*macro_ptr
== TOK_TWOSHARPS
) {
3914 macro_ptr1
= macro_ptr
;
3917 TOK_GET(t
, macro_ptr
, cval
);
3918 /* We concatenate the two tokens if we have an
3919 identifier or a preprocessing number */
3921 p1
= get_tok_str(tok
, &tokc
);
3922 cstr_cat(&cstr
, p1
);
3923 p2
= get_tok_str(t
, &cval
);
3924 cstr_cat(&cstr
, p2
);
3925 cstr_ccat(&cstr
, '\0');
3927 if ((tok
>= TOK_IDENT
|| tok
== TOK_PPNUM
) &&
3928 (t
>= TOK_IDENT
|| t
== TOK_PPNUM
)) {
3929 if (tok
== TOK_PPNUM
) {
3930 /* if number, then create a number token */
3931 /* NOTE: no need to allocate because
3932 tok_str_add2() does it */
3935 /* if identifier, we must do a test to
3936 validate we have a correct identifier */
3937 if (t
== TOK_PPNUM
) {
3947 if (!isnum(c
) && !isid(c
))
3951 ts
= tok_alloc(cstr
.data
, strlen(cstr
.data
));
3952 tok
= ts
->tok
; /* modify current token */
3955 const char *str
= cstr
.data
;
3956 const unsigned char *q
;
3958 /* we look for a valid token */
3959 /* XXX: do more extensive checks */
3960 if (!strcmp(str
, ">>=")) {
3962 } else if (!strcmp(str
, "<<=")) {
3964 } else if (strlen(str
) == 2) {
3965 /* search in two bytes table */
3970 if (q
[0] == str
[0] && q
[1] == str
[1])
3977 /* NOTE: because get_tok_str use a static buffer,
3980 p1
= get_tok_str(tok
, &tokc
);
3981 cstr_cat(&cstr
, p1
);
3982 cstr_ccat(&cstr
, '\0');
3983 p2
= get_tok_str(t
, &cval
);
3984 warning("pasting \"%s\" and \"%s\" does not give a valid preprocessing token", cstr
.data
, p2
);
3985 /* cannot merge tokens: just add them separately */
3986 tok_str_add2(¯o_str1
, tok
, &tokc
);
3987 /* XXX: free associated memory ? */
3994 tok_str_add2(¯o_str1
, tok
, &tokc
);
3999 macro_ptr
= (int *)saved_macro_ptr
;
4001 tok_str_add(¯o_str1
, 0);
4002 return macro_str1
.str
;
4006 /* do macro substitution of macro_str and add result to
4007 (tok_str,tok_len). 'nested_list' is the list of all macros we got
4008 inside to avoid recursing. */
4009 static void macro_subst(TokenString
*tok_str
,
4010 Sym
**nested_list
, const int *macro_str
)
4013 int *saved_macro_ptr
, *macro_str1
;
4018 /* first scan for '##' operator handling */
4020 macro_str1
= macro_twosharps(ptr
);
4024 /* NOTE: ptr == NULL can only happen if tokens are read from
4025 file stream due to a macro function call */
4028 TOK_GET(t
, ptr
, cval
);
4033 /* if nested substitution, do nothing */
4034 if (sym_find2(*nested_list
, t
))
4036 saved_macro_ptr
= macro_ptr
;
4037 macro_ptr
= (int *)ptr
;
4039 ret
= macro_subst_tok(tok_str
, nested_list
, s
);
4040 ptr
= (int *)macro_ptr
;
4041 macro_ptr
= saved_macro_ptr
;
4046 tok_str_add2(tok_str
, t
, &cval
);
4050 tok_str_free(macro_str1
);
4053 /* return next token with macro substitution */
4054 static void next(void)
4056 Sym
*nested_list
, *s
;
4062 /* if not reading from macro substituted string, then try
4063 to substitute macros */
4064 if (tok
>= TOK_IDENT
&&
4065 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
4066 s
= define_find(tok
);
4068 /* we have a macro: we try to substitute */
4071 if (macro_subst_tok(&str
, &nested_list
, s
) == 0) {
4072 /* substitution done, NOTE: maybe empty */
4073 tok_str_add(&str
, 0);
4074 macro_ptr
= str
.str
;
4075 macro_ptr_allocated
= str
.str
;
4082 /* end of macro or end of unget buffer */
4083 if (unget_buffer_enabled
) {
4084 macro_ptr
= unget_saved_macro_ptr
;
4085 unget_buffer_enabled
= 0;
4087 /* end of macro string: free it */
4088 tok_str_free(macro_ptr_allocated
);
4095 /* convert preprocessor tokens into C tokens */
4096 if (tok
== TOK_PPNUM
&&
4097 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
4098 parse_number((char *)tokc
.cstr
->data
);
4102 /* push back current token and set current token to 'last_tok'. Only
4103 identifier case handled for labels. */
4104 static inline void unget_tok(int last_tok
)
4108 unget_saved_macro_ptr
= macro_ptr
;
4109 unget_buffer_enabled
= 1;
4110 q
= unget_saved_buffer
;
4113 n
= tok_ext_size(tok
) - 1;
4116 *q
= 0; /* end of token string */
4121 void swap(int *p
, int *q
)
4129 void vsetc(CType
*type
, int r
, CValue
*vc
)
4133 if (vtop
>= vstack
+ VSTACK_SIZE
)
4134 error("memory full");
4135 /* cannot let cpu flags if other instruction are generated. Also
4136 avoid leaving VT_JMP anywhere except on the top of the stack
4137 because it would complicate the code generator. */
4138 if (vtop
>= vstack
) {
4139 v
= vtop
->r
& VT_VALMASK
;
4140 if (v
== VT_CMP
|| (v
& ~1) == VT_JMP
)
4146 vtop
->r2
= VT_CONST
;
4150 /* push integer constant */
4155 vsetc(&int_type
, VT_CONST
, &cval
);
4158 /* Return a static symbol pointing to a section */
4159 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
4160 unsigned long offset
, unsigned long size
)
4166 sym
= global_identifier_push(v
, type
->t
| VT_STATIC
, 0);
4167 sym
->type
.ref
= type
->ref
;
4168 sym
->r
= VT_CONST
| VT_SYM
;
4169 put_extern_sym(sym
, sec
, offset
, size
);
4173 /* push a reference to a section offset by adding a dummy symbol */
4174 static void vpush_ref(CType
*type
, Section
*sec
, unsigned long offset
, unsigned long size
)
4179 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4180 vtop
->sym
= get_sym_ref(type
, sec
, offset
, size
);
4183 /* define a new external reference to a symbol 'v' of type 'u' */
4184 static Sym
*external_global_sym(int v
, CType
*type
, int r
)
4190 /* push forward reference */
4191 s
= global_identifier_push(v
, type
->t
| VT_EXTERN
, 0);
4192 s
->type
.ref
= type
->ref
;
4193 s
->r
= r
| VT_CONST
| VT_SYM
;
4198 /* define a new external reference to a symbol 'v' of type 'u' */
4199 static Sym
*external_sym(int v
, CType
*type
, int r
)
4205 /* push forward reference */
4206 s
= sym_push(v
, type
, r
| VT_CONST
| VT_SYM
, 0);
4207 s
->type
.t
|= VT_EXTERN
;
4209 if (!is_compatible_types(&s
->type
, type
))
4210 error("incompatible types for redefinition of '%s'",
4211 get_tok_str(v
, NULL
));
4216 /* push a reference to global symbol v */
4217 static void vpush_global_sym(CType
*type
, int v
)
4222 sym
= external_global_sym(v
, type
, 0);
4224 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4228 void vset(CType
*type
, int r
, int v
)
4233 vsetc(type
, r
, &cval
);
4236 void vseti(int r
, int v
)
4252 void vpushv(SValue
*v
)
4254 if (vtop
>= vstack
+ VSTACK_SIZE
)
4255 error("memory full");
4265 /* save r to the memory stack, and mark it as being free */
4266 void save_reg(int r
)
4268 int l
, saved
, size
, align
;
4272 /* modify all stack values */
4275 for(p
=vstack
;p
<=vtop
;p
++) {
4276 if ((p
->r
& VT_VALMASK
) == r
||
4277 (p
->r2
& VT_VALMASK
) == r
) {
4278 /* must save value on stack if not already done */
4280 /* NOTE: must reload 'r' because r might be equal to r2 */
4281 r
= p
->r
& VT_VALMASK
;
4282 /* store register in the stack */
4284 if ((p
->r
& VT_LVAL
) ||
4285 (!is_float(type
->t
) && (type
->t
& VT_BTYPE
) != VT_LLONG
))
4287 size
= type_size(type
, &align
);
4288 loc
= (loc
- size
) & -align
;
4289 sv
.type
.t
= type
->t
;
4290 sv
.r
= VT_LOCAL
| VT_LVAL
;
4293 #ifdef TCC_TARGET_I386
4294 /* x86 specific: need to pop fp register ST0 if saved */
4295 if (r
== TREG_ST0
) {
4296 o(0xd9dd); /* fstp %st(1) */
4299 /* special long long case */
4300 if ((type
->t
& VT_BTYPE
) == VT_LLONG
) {
4307 /* mark that stack entry as being saved on the stack */
4308 if (p
->r
& VT_LVAL
) {
4309 /* also clear the bounded flag because the
4310 relocation address of the function was stored in
4312 p
->r
= (p
->r
& ~(VT_VALMASK
| VT_BOUNDED
)) | VT_LLOCAL
;
4314 p
->r
= lvalue_type(p
->type
.t
) | VT_LOCAL
;
4322 /* find a free register of class 'rc'. If none, save one register */
4328 /* find a free register */
4329 for(r
=0;r
<NB_REGS
;r
++) {
4330 if (reg_classes
[r
] & rc
) {
4331 for(p
=vstack
;p
<=vtop
;p
++) {
4332 if ((p
->r
& VT_VALMASK
) == r
||
4333 (p
->r2
& VT_VALMASK
) == r
)
4341 /* no register left : free the first one on the stack (VERY
4342 IMPORTANT to start from the bottom to ensure that we don't
4343 spill registers used in gen_opi()) */
4344 for(p
=vstack
;p
<=vtop
;p
++) {
4345 r
= p
->r
& VT_VALMASK
;
4346 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
))
4348 /* also look at second register (if long long) */
4349 r
= p
->r2
& VT_VALMASK
;
4350 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
)) {
4356 /* Should never comes here */
4360 /* save registers up to (vtop - n) stack entry */
4361 void save_regs(int n
)
4366 for(p
= vstack
;p
<= p1
; p
++) {
4367 r
= p
->r
& VT_VALMASK
;
4374 /* move register 's' to 'r', and flush previous value of r to memory
4376 void move_reg(int r
, int s
)
4389 /* get address of vtop (vtop MUST BE an lvalue) */
4392 vtop
->r
&= ~VT_LVAL
;
4393 /* tricky: if saved lvalue, then we can go back to lvalue */
4394 if ((vtop
->r
& VT_VALMASK
) == VT_LLOCAL
)
4395 vtop
->r
= (vtop
->r
& ~(VT_VALMASK
| VT_LVAL_TYPE
)) | VT_LOCAL
| VT_LVAL
;
4398 #ifdef CONFIG_TCC_BCHECK
4399 /* generate lvalue bound code */
4405 vtop
->r
&= ~VT_MUSTBOUND
;
4406 /* if lvalue, then use checking code before dereferencing */
4407 if (vtop
->r
& VT_LVAL
) {
4408 /* if not VT_BOUNDED value, then make one */
4409 if (!(vtop
->r
& VT_BOUNDED
)) {
4410 lval_type
= vtop
->r
& (VT_LVAL_TYPE
| VT_LVAL
);
4411 /* must save type because we must set it to int to get pointer */
4413 vtop
->type
.t
= VT_INT
;
4416 gen_bounded_ptr_add();
4417 vtop
->r
|= lval_type
;
4420 /* then check for dereferencing */
4421 gen_bounded_ptr_deref();
4426 /* store vtop a register belonging to class 'rc'. lvalues are
4427 converted to values. Cannot be used if cannot be converted to
4428 register value (such as structures). */
4431 int r
, r2
, rc2
, bit_pos
, bit_size
, size
, align
, i
;
4432 unsigned long long ll
;
4434 /* NOTE: get_reg can modify vstack[] */
4435 if (vtop
->type
.t
& VT_BITFIELD
) {
4436 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
4437 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
4438 /* remove bit field info to avoid loops */
4439 vtop
->type
.t
&= ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
4440 /* generate shifts */
4441 vpushi(32 - (bit_pos
+ bit_size
));
4443 vpushi(32 - bit_size
);
4444 /* NOTE: transformed to SHR if unsigned */
4448 if (is_float(vtop
->type
.t
) &&
4449 (vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4452 unsigned long offset
;
4454 /* XXX: unify with initializers handling ? */
4455 /* CPUs usually cannot use float constants, so we store them
4456 generically in data segment */
4457 size
= type_size(&vtop
->type
, &align
);
4458 offset
= (data_section
->data_offset
+ align
- 1) & -align
;
4459 data_section
->data_offset
= offset
;
4460 /* XXX: not portable yet */
4461 ptr
= section_ptr_add(data_section
, size
);
4464 ptr
[i
] = vtop
->c
.tab
[i
];
4465 sym
= get_sym_ref(&vtop
->type
, data_section
, offset
, size
<< 2);
4466 vtop
->r
|= VT_LVAL
| VT_SYM
;
4470 #ifdef CONFIG_TCC_BCHECK
4471 if (vtop
->r
& VT_MUSTBOUND
)
4475 r
= vtop
->r
& VT_VALMASK
;
4476 /* need to reload if:
4478 - lvalue (need to dereference pointer)
4479 - already a register, but not in the right class */
4480 if (r
>= VT_CONST
||
4481 (vtop
->r
& VT_LVAL
) ||
4482 !(reg_classes
[r
] & rc
) ||
4483 ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
&&
4484 !(reg_classes
[vtop
->r2
] & rc
))) {
4486 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
) {
4487 /* two register type load : expand to two words
4489 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4492 vtop
->c
.ui
= ll
; /* first word */
4494 vtop
->r
= r
; /* save register value */
4495 vpushi(ll
>> 32); /* second word */
4496 } else if (r
>= VT_CONST
||
4497 (vtop
->r
& VT_LVAL
)) {
4498 /* load from memory */
4501 vtop
[-1].r
= r
; /* save register value */
4502 /* increment pointer to get second word */
4503 vtop
->type
.t
= VT_INT
;
4509 /* move registers */
4512 vtop
[-1].r
= r
; /* save register value */
4513 vtop
->r
= vtop
[-1].r2
;
4515 /* allocate second register */
4522 /* write second register */
4524 } else if ((vtop
->r
& VT_LVAL
) && !is_float(vtop
->type
.t
)) {
4526 /* lvalue of scalar type : need to use lvalue type
4527 because of possible cast */
4530 /* compute memory access type */
4531 if (vtop
->r
& VT_LVAL_BYTE
)
4533 else if (vtop
->r
& VT_LVAL_SHORT
)
4535 if (vtop
->r
& VT_LVAL_UNSIGNED
)
4539 /* restore wanted type */
4542 /* one register type load */
4551 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
4552 void gv2(int rc1
, int rc2
)
4556 /* generate more generic register first. But VT_JMP or VT_CMP
4557 values must be generated first in all cases to avoid possible
4559 v
= vtop
[0].r
& VT_VALMASK
;
4560 if (v
!= VT_CMP
&& (v
& ~1) != VT_JMP
&& rc1
<= rc2
) {
4565 /* test if reload is needed for first register */
4566 if ((vtop
[-1].r
& VT_VALMASK
) >= VT_CONST
) {
4576 /* test if reload is needed for first register */
4577 if ((vtop
[0].r
& VT_VALMASK
) >= VT_CONST
) {
4583 /* expand long long on stack in two int registers */
4588 u
= vtop
->type
.t
& VT_UNSIGNED
;
4591 vtop
[0].r
= vtop
[-1].r2
;
4592 vtop
[0].r2
= VT_CONST
;
4593 vtop
[-1].r2
= VT_CONST
;
4594 vtop
[0].type
.t
= VT_INT
| u
;
4595 vtop
[-1].type
.t
= VT_INT
| u
;
4598 /* build a long long from two ints */
4601 gv2(RC_INT
, RC_INT
);
4602 vtop
[-1].r2
= vtop
[0].r
;
4603 vtop
[-1].type
.t
= t
;
4607 /* rotate n first stack elements to the bottom
4608 I1 ... In -> I2 ... In I1 [top is right]
4616 for(i
=-n
+1;i
!=0;i
++)
4617 vtop
[i
] = vtop
[i
+1];
4621 /* rotate n first stack elements to the top
4622 I1 ... In -> In I1 ... I(n-1) [top is right]
4630 for(i
= 0;i
< n
- 1; i
++)
4631 vtop
[-i
] = vtop
[-i
- 1];
4635 /* pop stack value */
4639 v
= vtop
->r
& VT_VALMASK
;
4640 #ifdef TCC_TARGET_I386
4641 /* for x86, we need to pop the FP stack */
4642 if (v
== TREG_ST0
&& !nocode_wanted
) {
4643 o(0xd9dd); /* fstp %st(1) */
4646 if (v
== VT_JMP
|| v
== VT_JMPI
) {
4647 /* need to put correct jump if && or || without test */
4653 /* convert stack entry to register and duplicate its value in another
4661 if ((t
& VT_BTYPE
) == VT_LLONG
) {
4668 /* stack: H L L1 H1 */
4676 /* duplicate value */
4687 load(r1
, &sv
); /* move r to r1 */
4689 /* duplicates value */
4694 /* generate CPU independent (unsigned) long long operations */
4695 void gen_opl(int op
)
4697 int t
, a
, b
, op1
, c
, i
;
4704 func
= TOK___divdi3
;
4707 func
= TOK___udivdi3
;
4710 func
= TOK___moddi3
;
4713 func
= TOK___umoddi3
;
4715 /* call generic long long function */
4716 vpush_global_sym(&func_old_type
, func
);
4721 vtop
->r2
= REG_LRET
;
4734 /* stack: L1 H1 L2 H2 */
4739 vtop
[-2] = vtop
[-3];
4742 /* stack: H1 H2 L1 L2 */
4748 /* stack: H1 H2 L1 L2 ML MH */
4751 /* stack: ML MH H1 H2 L1 L2 */
4755 /* stack: ML MH H1 L2 H2 L1 */
4760 /* stack: ML MH M1 M2 */
4763 } else if (op
== '+' || op
== '-') {
4764 /* XXX: add non carry method too (for MIPS or alpha) */
4770 /* stack: H1 H2 (L1 op L2) */
4773 gen_op(op1
+ 1); /* TOK_xxxC2 */
4776 /* stack: H1 H2 (L1 op L2) */
4779 /* stack: (L1 op L2) H1 H2 */
4781 /* stack: (L1 op L2) (H1 op H2) */
4789 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) {
4790 t
= vtop
[-1].type
.t
;
4794 /* stack: L H shift */
4796 /* constant: simpler */
4797 /* NOTE: all comments are for SHL. the other cases are
4798 done by swaping words */
4809 if (op
!= TOK_SAR
) {
4842 /* XXX: should provide a faster fallback on x86 ? */
4845 func
= TOK___sardi3
;
4848 func
= TOK___shrdi3
;
4851 func
= TOK___shldi3
;
4857 /* compare operations */
4863 /* stack: L1 H1 L2 H2 */
4865 vtop
[-1] = vtop
[-2];
4867 /* stack: L1 L2 H1 H2 */
4870 /* when values are equal, we need to compare low words. since
4871 the jump is inverted, we invert the test too. */
4874 else if (op1
== TOK_GT
)
4876 else if (op1
== TOK_ULT
)
4878 else if (op1
== TOK_UGT
)
4883 if (op1
!= TOK_NE
) {
4887 /* generate non equal test */
4888 /* XXX: NOT PORTABLE yet */
4892 #ifdef TCC_TARGET_I386
4893 b
= psym(0x850f, 0);
4895 error("not implemented");
4899 /* compare low. Always unsigned */
4903 else if (op1
== TOK_LE
)
4905 else if (op1
== TOK_GT
)
4907 else if (op1
== TOK_GE
)
4917 /* handle integer constant optimizations and various machine
4919 void gen_opic(int op
)
4926 /* currently, we cannot do computations with forward symbols */
4927 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
4928 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
4932 case '+': v1
->c
.i
+= fc
; break;
4933 case '-': v1
->c
.i
-= fc
; break;
4934 case '&': v1
->c
.i
&= fc
; break;
4935 case '^': v1
->c
.i
^= fc
; break;
4936 case '|': v1
->c
.i
|= fc
; break;
4937 case '*': v1
->c
.i
*= fc
; break;
4944 /* if division by zero, generate explicit division */
4947 error("division by zero in constant");
4951 default: v1
->c
.i
/= fc
; break;
4952 case '%': v1
->c
.i
%= fc
; break;
4953 case TOK_UDIV
: v1
->c
.i
= (unsigned)v1
->c
.i
/ fc
; break;
4954 case TOK_UMOD
: v1
->c
.i
= (unsigned)v1
->c
.i
% fc
; break;
4957 case TOK_SHL
: v1
->c
.i
<<= fc
; break;
4958 case TOK_SHR
: v1
->c
.i
= (unsigned)v1
->c
.i
>> fc
; break;
4959 case TOK_SAR
: v1
->c
.i
>>= fc
; break;
4961 case TOK_ULT
: v1
->c
.i
= (unsigned)v1
->c
.i
< (unsigned)fc
; break;
4962 case TOK_UGE
: v1
->c
.i
= (unsigned)v1
->c
.i
>= (unsigned)fc
; break;
4963 case TOK_EQ
: v1
->c
.i
= v1
->c
.i
== fc
; break;
4964 case TOK_NE
: v1
->c
.i
= v1
->c
.i
!= fc
; break;
4965 case TOK_ULE
: v1
->c
.i
= (unsigned)v1
->c
.i
<= (unsigned)fc
; break;
4966 case TOK_UGT
: v1
->c
.i
= (unsigned)v1
->c
.i
> (unsigned)fc
; break;
4967 case TOK_LT
: v1
->c
.i
= v1
->c
.i
< fc
; break;
4968 case TOK_GE
: v1
->c
.i
= v1
->c
.i
>= fc
; break;
4969 case TOK_LE
: v1
->c
.i
= v1
->c
.i
<= fc
; break;
4970 case TOK_GT
: v1
->c
.i
= v1
->c
.i
> fc
; break;
4972 case TOK_LAND
: v1
->c
.i
= v1
->c
.i
&& fc
; break;
4973 case TOK_LOR
: v1
->c
.i
= v1
->c
.i
|| fc
; break;
4979 /* if commutative ops, put c2 as constant */
4980 if (c1
&& (op
== '+' || op
== '&' || op
== '^' ||
4981 op
== '|' || op
== '*')) {
4986 if (c2
&& (((op
== '*' || op
== '/' || op
== TOK_UDIV
||
4989 ((op
== '+' || op
== '-' || op
== '|' || op
== '^' ||
4990 op
== TOK_SHL
|| op
== TOK_SHR
|| op
== TOK_SAR
) &&
4996 } else if (c2
&& (op
== '*' || op
== TOK_PDIV
|| op
== TOK_UDIV
)) {
4997 /* try to use shifts instead of muls or divs */
4998 if (fc
> 0 && (fc
& (fc
- 1)) == 0) {
5007 else if (op
== TOK_PDIV
)
5013 } else if (c2
&& (op
== '+' || op
== '-') &&
5014 (vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) ==
5015 (VT_CONST
| VT_SYM
)) {
5016 /* symbol + constant case */
5023 if (!nocode_wanted
) {
5024 /* call low level op generator */
5033 /* generate a floating point operation with constant propagation */
5034 void gen_opif(int op
)
5042 /* currently, we cannot do computations with forward symbols */
5043 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5044 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5046 if (v1
->type
.t
== VT_FLOAT
) {
5049 } else if (v1
->type
.t
== VT_DOUBLE
) {
5057 /* NOTE: we only do constant propagation if finite number (not
5058 NaN or infinity) (ANSI spec) */
5059 if (!ieee_finite(f1
) || !ieee_finite(f2
))
5063 case '+': f1
+= f2
; break;
5064 case '-': f1
-= f2
; break;
5065 case '*': f1
*= f2
; break;
5069 error("division by zero in constant");
5074 /* XXX: also handles tests ? */
5078 /* XXX: overflow test ? */
5079 if (v1
->type
.t
== VT_FLOAT
) {
5081 } else if (v1
->type
.t
== VT_DOUBLE
) {
5089 if (!nocode_wanted
) {
5097 static int pointed_size(CType
*type
)
5100 return type_size(pointed_type(type
), &align
);
5103 static inline int is_null_pointer(SValue
*p
)
5105 if ((p
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
5107 return ((p
->type
.t
& VT_BTYPE
) == VT_INT
&& p
->c
.i
== 0) ||
5108 ((p
->type
.t
& VT_BTYPE
) == VT_LLONG
&& p
->c
.ll
== 0);
5111 static inline int is_integer_btype(int bt
)
5113 return (bt
== VT_BYTE
|| bt
== VT_SHORT
||
5114 bt
== VT_INT
|| bt
== VT_LLONG
);
5117 /* check types for comparison or substraction of pointers */
5118 static void check_comparison_pointer_types(SValue
*p1
, SValue
*p2
, int op
)
5120 CType
*type1
, *type2
, tmp_type1
, tmp_type2
;
5123 /* null pointers are accepted for all comparisons as gcc */
5124 if (is_null_pointer(p1
) || is_null_pointer(p2
))
5128 bt1
= type1
->t
& VT_BTYPE
;
5129 bt2
= type2
->t
& VT_BTYPE
;
5130 /* accept comparison between pointer and integer with a warning */
5131 if ((is_integer_btype(bt1
) || is_integer_btype(bt2
)) && op
!= '-') {
5132 warning("comparison between pointer and integer");
5136 /* both must be pointers or implicit function pointers */
5137 if (bt1
== VT_PTR
) {
5138 type1
= pointed_type(type1
);
5139 } else if (bt1
!= VT_FUNC
)
5140 goto invalid_operands
;
5142 if (bt2
== VT_PTR
) {
5143 type2
= pointed_type(type2
);
5144 } else if (bt2
!= VT_FUNC
) {
5146 error("invalid operands to binary %s", get_tok_str(op
, NULL
));
5148 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
5149 (type2
->t
& VT_BTYPE
) == VT_VOID
)
5153 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5154 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5155 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
5156 /* gcc-like error if '-' is used */
5158 goto invalid_operands
;
5160 warning("comparison of distinct pointer types lacks a cast");
5164 /* generic gen_op: handles types problems */
5167 int u
, t1
, t2
, bt1
, bt2
, t
;
5170 t1
= vtop
[-1].type
.t
;
5171 t2
= vtop
[0].type
.t
;
5172 bt1
= t1
& VT_BTYPE
;
5173 bt2
= t2
& VT_BTYPE
;
5175 if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
5176 /* at least one operand is a pointer */
5177 /* relationnal op: must be both pointers */
5178 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5179 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5180 /* pointers are handled are unsigned */
5181 t
= VT_INT
| VT_UNSIGNED
;
5184 /* if both pointers, then it must be the '-' op */
5185 if (bt1
== VT_PTR
&& bt2
== VT_PTR
) {
5187 error("cannot use pointers here");
5188 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5189 /* XXX: check that types are compatible */
5190 u
= pointed_size(&vtop
[-1].type
);
5192 /* set to integer type */
5193 vtop
->type
.t
= VT_INT
;
5197 /* exactly one pointer : must be '+' or '-'. */
5198 if (op
!= '-' && op
!= '+')
5199 error("cannot use pointers here");
5200 /* Put pointer as first operand */
5201 if (bt2
== VT_PTR
) {
5205 type1
= vtop
[-1].type
;
5206 /* XXX: cast to int ? (long long case) */
5207 vpushi(pointed_size(&vtop
[-1].type
));
5209 #ifdef CONFIG_TCC_BCHECK
5210 /* if evaluating constant expression, no code should be
5211 generated, so no bound check */
5212 if (do_bounds_check
&& !const_wanted
) {
5213 /* if bounded pointers, we generate a special code to
5220 gen_bounded_ptr_add();
5226 /* put again type if gen_opic() swaped operands */
5229 } else if (is_float(bt1
) || is_float(bt2
)) {
5230 /* compute bigger type and do implicit casts */
5231 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
5233 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
5238 /* floats can only be used for a few operations */
5239 if (op
!= '+' && op
!= '-' && op
!= '*' && op
!= '/' &&
5240 (op
< TOK_ULT
|| op
> TOK_GT
))
5241 error("invalid operands for binary operation");
5243 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
5244 /* cast to biggest op */
5246 /* convert to unsigned if it does not fit in a long long */
5247 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
5248 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
5252 /* integer operations */
5254 /* convert to unsigned if it does not fit in an integer */
5255 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
5256 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
5259 /* XXX: currently, some unsigned operations are explicit, so
5260 we modify them here */
5261 if (t
& VT_UNSIGNED
) {
5268 else if (op
== TOK_LT
)
5270 else if (op
== TOK_GT
)
5272 else if (op
== TOK_LE
)
5274 else if (op
== TOK_GE
)
5281 /* special case for shifts and long long: we keep the shift as
5283 if (op
== TOK_SHR
|| op
== TOK_SAR
|| op
== TOK_SHL
)
5288 else if ((t
& VT_BTYPE
) == VT_LLONG
)
5292 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5293 /* relationnal op: the result is an int */
5294 vtop
->type
.t
= VT_INT
;
5301 /* generic itof for unsigned long long case */
5302 void gen_cvt_itof1(int t
)
5304 if ((vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
)) ==
5305 (VT_LLONG
| VT_UNSIGNED
)) {
5308 vpush_global_sym(&func_old_type
, TOK___ulltof
);
5309 else if (t
== VT_DOUBLE
)
5310 vpush_global_sym(&func_old_type
, TOK___ulltod
);
5312 vpush_global_sym(&func_old_type
, TOK___ulltold
);
5322 /* generic ftoi for unsigned long long case */
5323 void gen_cvt_ftoi1(int t
)
5327 if (t
== (VT_LLONG
| VT_UNSIGNED
)) {
5328 /* not handled natively */
5329 st
= vtop
->type
.t
& VT_BTYPE
;
5331 vpush_global_sym(&func_old_type
, TOK___fixunssfdi
);
5332 else if (st
== VT_DOUBLE
)
5333 vpush_global_sym(&func_old_type
, TOK___fixunsdfdi
);
5335 vpush_global_sym(&func_old_type
, TOK___fixunsxfdi
);
5340 vtop
->r2
= REG_LRET
;
5346 /* force char or short cast */
5347 void force_charshort_cast(int t
)
5351 /* XXX: add optimization if lvalue : just change type and offset */
5356 if (t
& VT_UNSIGNED
) {
5357 vpushi((1 << bits
) - 1);
5368 /* cast 'vtop' to 'type' */
5369 static void gen_cast(CType
*type
)
5371 int sbt
, dbt
, sf
, df
, c
;
5373 /* special delayed cast for char/short */
5374 /* XXX: in some cases (multiple cascaded casts), it may still
5376 if (vtop
->r
& VT_MUSTCAST
) {
5377 vtop
->r
&= ~VT_MUSTCAST
;
5378 force_charshort_cast(vtop
->type
.t
);
5381 dbt
= type
->t
& (VT_BTYPE
| VT_UNSIGNED
);
5382 sbt
= vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
);
5384 if (sbt
!= dbt
&& !nocode_wanted
) {
5387 c
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5389 /* convert from fp to fp */
5391 /* constant case: we can do it now */
5392 /* XXX: in ISOC, cannot do it if error in convert */
5393 if (dbt
== VT_FLOAT
&& sbt
== VT_DOUBLE
)
5394 vtop
->c
.f
= (float)vtop
->c
.d
;
5395 else if (dbt
== VT_FLOAT
&& sbt
== VT_LDOUBLE
)
5396 vtop
->c
.f
= (float)vtop
->c
.ld
;
5397 else if (dbt
== VT_DOUBLE
&& sbt
== VT_FLOAT
)
5398 vtop
->c
.d
= (double)vtop
->c
.f
;
5399 else if (dbt
== VT_DOUBLE
&& sbt
== VT_LDOUBLE
)
5400 vtop
->c
.d
= (double)vtop
->c
.ld
;
5401 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_FLOAT
)
5402 vtop
->c
.ld
= (long double)vtop
->c
.f
;
5403 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_DOUBLE
)
5404 vtop
->c
.ld
= (long double)vtop
->c
.d
;
5406 /* non constant case: generate code */
5410 /* convert int to fp */
5413 case VT_LLONG
| VT_UNSIGNED
:
5415 /* XXX: add const cases for long long */
5417 case VT_INT
| VT_UNSIGNED
:
5419 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.ui
; break;
5420 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.ui
; break;
5421 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.ui
; break;
5426 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.i
; break;
5427 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.i
; break;
5428 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.i
; break;
5437 /* convert fp to int */
5438 /* we handle char/short/etc... with generic code */
5439 if (dbt
!= (VT_INT
| VT_UNSIGNED
) &&
5440 dbt
!= (VT_LLONG
| VT_UNSIGNED
) &&
5445 case VT_LLONG
| VT_UNSIGNED
:
5447 /* XXX: add const cases for long long */
5449 case VT_INT
| VT_UNSIGNED
:
5451 case VT_FLOAT
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5452 case VT_DOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5453 case VT_LDOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5459 case VT_FLOAT
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5460 case VT_DOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5461 case VT_LDOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5469 if (dbt
== VT_INT
&& (type
->t
& (VT_BTYPE
| VT_UNSIGNED
)) != dbt
) {
5470 /* additional cast for char/short/bool... */
5474 } else if ((dbt
& VT_BTYPE
) == VT_LLONG
) {
5475 if ((sbt
& VT_BTYPE
) != VT_LLONG
) {
5476 /* scalar to long long */
5478 if (sbt
== (VT_INT
| VT_UNSIGNED
))
5479 vtop
->c
.ll
= vtop
->c
.ui
;
5481 vtop
->c
.ll
= vtop
->c
.i
;
5483 /* machine independent conversion */
5485 /* generate high word */
5486 if (sbt
== (VT_INT
| VT_UNSIGNED
)) {
5494 /* patch second register */
5495 vtop
[-1].r2
= vtop
->r
;
5499 } else if (dbt
== VT_BOOL
) {
5500 /* scalar to bool */
5503 } else if ((dbt
& VT_BTYPE
) == VT_BYTE
||
5504 (dbt
& VT_BTYPE
) == VT_SHORT
) {
5505 force_charshort_cast(dbt
);
5506 } else if ((dbt
& VT_BTYPE
) == VT_INT
) {
5508 if (sbt
== VT_LLONG
) {
5509 /* from long long: just take low order word */
5513 /* if lvalue and single word type, nothing to do because
5514 the lvalue already contains the real type size (see
5515 VT_LVAL_xxx constants) */
5521 /* return type size. Put alignment at 'a' */
5522 static int type_size(CType
*type
, int *a
)
5527 bt
= type
->t
& VT_BTYPE
;
5528 if (bt
== VT_STRUCT
) {
5533 } else if (bt
== VT_PTR
) {
5534 if (type
->t
& VT_ARRAY
) {
5536 return type_size(&s
->type
, a
) * s
->c
;
5541 } else if (bt
== VT_LDOUBLE
) {
5543 return LDOUBLE_SIZE
;
5544 } else if (bt
== VT_DOUBLE
|| bt
== VT_LLONG
) {
5545 *a
= 4; /* XXX: i386 specific */
5547 } else if (bt
== VT_INT
|| bt
== VT_ENUM
|| bt
== VT_FLOAT
) {
5550 } else if (bt
== VT_SHORT
) {
5554 /* char, void, function, _Bool */
5560 /* return the pointed type of t */
5561 static inline CType
*pointed_type(CType
*type
)
5563 return &type
->ref
->type
;
5566 /* modify type so that its it is a pointer to type. */
5567 static void mk_pointer(CType
*type
)
5570 s
= sym_push(SYM_FIELD
, type
, 0, -1);
5571 type
->t
= VT_PTR
| (type
->t
& ~VT_TYPE
);
5575 /* compare function types. OLD functions match any new functions */
5576 static int is_compatible_func(CType
*type1
, CType
*type2
)
5582 if (!is_compatible_types(&s1
->type
, &s2
->type
))
5584 /* XXX: not complete */
5585 if (s1
->c
== FUNC_OLD
|| s2
->c
== FUNC_OLD
)
5589 while (s1
!= NULL
) {
5592 if (!is_compatible_types(&s1
->type
, &s2
->type
))
5602 /* return true if type1 and type2 are exactly the same (including
5605 - enums are not checked as gcc __builtin_types_compatible_p ()
5607 static int is_compatible_types(CType
*type1
, CType
*type2
)
5611 t1
= type1
->t
& VT_TYPE
;
5612 t2
= type2
->t
& VT_TYPE
;
5613 /* XXX: bitfields ? */
5616 /* test more complicated cases */
5617 bt1
= t1
& VT_BTYPE
;
5618 if (bt1
== VT_PTR
) {
5619 type1
= pointed_type(type1
);
5620 type2
= pointed_type(type2
);
5621 return is_compatible_types(type1
, type2
);
5622 } else if (bt1
== VT_STRUCT
) {
5623 return (type1
->ref
== type2
->ref
);
5624 } else if (bt1
== VT_FUNC
) {
5625 return is_compatible_func(type1
, type2
);
5631 /* print a type. If 'varstr' is not NULL, then the variable is also
5632 printed in the type */
5634 /* XXX: add array and function pointers */
5635 void type_to_str(char *buf
, int buf_size
,
5636 CType
*type
, const char *varstr
)
5643 t
= type
->t
& VT_TYPE
;
5646 if (t
& VT_CONSTANT
)
5647 pstrcat(buf
, buf_size
, "const ");
5648 if (t
& VT_VOLATILE
)
5649 pstrcat(buf
, buf_size
, "volatile ");
5650 if (t
& VT_UNSIGNED
)
5651 pstrcat(buf
, buf_size
, "unsigned ");
5681 tstr
= "long double";
5683 pstrcat(buf
, buf_size
, tstr
);
5687 if (bt
== VT_STRUCT
)
5691 pstrcat(buf
, buf_size
, tstr
);
5692 v
= type
->ref
->v
& ~SYM_STRUCT
;
5693 if (v
>= SYM_FIRST_ANOM
)
5694 pstrcat(buf
, buf_size
, "<anonymous>");
5696 pstrcat(buf
, buf_size
, get_tok_str(v
, NULL
));
5700 type_to_str(buf
, buf_size
, &s
->type
, varstr
);
5701 pstrcat(buf
, buf_size
, "(");
5703 while (sa
!= NULL
) {
5704 type_to_str(buf1
, sizeof(buf1
), &sa
->type
, NULL
);
5705 pstrcat(buf
, buf_size
, buf1
);
5708 pstrcat(buf
, buf_size
, ", ");
5710 pstrcat(buf
, buf_size
, ")");
5714 pstrcpy(buf1
, sizeof(buf1
), "*");
5716 pstrcat(buf1
, sizeof(buf1
), varstr
);
5717 type_to_str(buf
, buf_size
, &s
->type
, buf1
);
5721 pstrcat(buf
, buf_size
, " ");
5722 pstrcat(buf
, buf_size
, varstr
);
5727 /* verify type compatibility to store vtop in 'dt' type, and generate
5729 static void gen_assign_cast(CType
*dt
)
5731 CType
*st
, *type1
, *type2
, tmp_type1
, tmp_type2
;
5732 char buf1
[256], buf2
[256];
5735 st
= &vtop
->type
; /* source type */
5736 dbt
= dt
->t
& VT_BTYPE
;
5737 sbt
= st
->t
& VT_BTYPE
;
5738 if (dt
->t
& VT_CONSTANT
)
5739 warning("assignment of read-only location");
5742 /* special cases for pointers */
5743 /* '0' can also be a pointer */
5744 if (is_null_pointer(vtop
))
5746 /* accept implicit pointer to integer cast with warning */
5747 if (is_integer_btype(sbt
)) {
5748 warning("assignment makes pointer from integer without a cast");
5751 type1
= pointed_type(dt
);
5752 /* a function is implicitely a function pointer */
5753 if (sbt
== VT_FUNC
) {
5754 if ((type1
->t
& VT_BTYPE
) != VT_VOID
&&
5755 !is_compatible_types(pointed_type(dt
), st
))
5762 type2
= pointed_type(st
);
5763 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
5764 (type2
->t
& VT_BTYPE
) == VT_VOID
) {
5765 /* void * can match anything */
5767 /* exact type match, except for unsigned */
5770 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5771 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5772 if (!is_compatible_types(&tmp_type1
, &tmp_type2
))
5775 /* check const and volatile */
5776 if ((!(type1
->t
& VT_CONSTANT
) && (type2
->t
& VT_CONSTANT
)) ||
5777 (!(type1
->t
& VT_VOLATILE
) && (type2
->t
& VT_VOLATILE
)))
5778 warning("assignment discards qualifiers from pointer target type");
5784 if (sbt
== VT_PTR
|| sbt
== VT_FUNC
) {
5785 warning("assignment makes integer from pointer without a cast");
5787 /* XXX: more tests */
5790 if (!is_compatible_types(dt
, st
)) {
5792 type_to_str(buf1
, sizeof(buf1
), st
, NULL
);
5793 type_to_str(buf2
, sizeof(buf2
), dt
, NULL
);
5794 error("cannot cast '%s' to '%s'", buf1
, buf2
);
5802 /* store vtop in lvalue pushed on stack */
5805 int sbt
, dbt
, ft
, r
, t
, size
, align
, bit_size
, bit_pos
, rc
, delayed_cast
;
5807 ft
= vtop
[-1].type
.t
;
5808 sbt
= vtop
->type
.t
& VT_BTYPE
;
5809 dbt
= ft
& VT_BTYPE
;
5810 if (((sbt
== VT_INT
|| sbt
== VT_SHORT
) && dbt
== VT_BYTE
) ||
5811 (sbt
== VT_INT
&& dbt
== VT_SHORT
)) {
5812 /* optimize char/short casts */
5813 delayed_cast
= VT_MUSTCAST
;
5814 vtop
->type
.t
= ft
& VT_TYPE
;
5815 /* XXX: factorize */
5816 if (ft
& VT_CONSTANT
)
5817 warning("assignment of read-only location");
5820 gen_assign_cast(&vtop
[-1].type
);
5823 if (sbt
== VT_STRUCT
) {
5824 /* if structure, only generate pointer */
5825 /* structure assignment : generate memcpy */
5826 /* XXX: optimize if small size */
5827 if (!nocode_wanted
) {
5828 size
= type_size(&vtop
->type
, &align
);
5830 vpush_global_sym(&func_old_type
, TOK_memcpy
);
5834 vtop
->type
.t
= VT_INT
;
5838 vtop
->type
.t
= VT_INT
;
5850 /* leave source on stack */
5851 } else if (ft
& VT_BITFIELD
) {
5852 /* bitfield store handling */
5853 bit_pos
= (ft
>> VT_STRUCT_SHIFT
) & 0x3f;
5854 bit_size
= (ft
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
5855 /* remove bit field info to avoid loops */
5856 vtop
[-1].type
.t
= ft
& ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
5858 /* duplicate destination */
5860 vtop
[-1] = vtop
[-2];
5862 /* mask and shift source */
5863 vpushi((1 << bit_size
) - 1);
5867 /* load destination, mask and or with source */
5869 vpushi(~(((1 << bit_size
) - 1) << bit_pos
));
5875 #ifdef CONFIG_TCC_BCHECK
5876 /* bound check case */
5877 if (vtop
[-1].r
& VT_MUSTBOUND
) {
5883 if (!nocode_wanted
) {
5887 r
= gv(rc
); /* generate value */
5888 /* if lvalue was saved on stack, must read it */
5889 if ((vtop
[-1].r
& VT_VALMASK
) == VT_LLOCAL
) {
5891 t
= get_reg(RC_INT
);
5893 sv
.r
= VT_LOCAL
| VT_LVAL
;
5894 sv
.c
.ul
= vtop
[-1].c
.ul
;
5896 vtop
[-1].r
= t
| VT_LVAL
;
5899 /* two word case handling : store second register at word + 4 */
5900 if ((ft
& VT_BTYPE
) == VT_LLONG
) {
5902 /* convert to int to increment easily */
5903 vtop
->type
.t
= VT_INT
;
5909 /* XXX: it works because r2 is spilled last ! */
5910 store(vtop
->r2
, vtop
- 1);
5914 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
5915 vtop
->r
|= delayed_cast
;
5919 /* post defines POST/PRE add. c is the token ++ or -- */
5920 void inc(int post
, int c
)
5923 vdup(); /* save lvalue */
5925 gv_dup(); /* duplicate value */
5930 vpushi(c
- TOK_MID
);
5932 vstore(); /* store value */
5934 vpop(); /* if post op, return saved value */
5937 /* Parse GNUC __attribute__ extension. Currently, the following
5938 extensions are recognized:
5939 - aligned(n) : set data/function alignment.
5940 - section(x) : generate data/code in this section.
5941 - unused : currently ignored, but may be used someday.
5943 static void parse_attribute(AttributeDef
*ad
)
5947 while (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
) {
5951 while (tok
!= ')') {
5952 if (tok
< TOK_IDENT
)
5953 expect("attribute name");
5961 expect("section name");
5962 ad
->section
= find_section(tcc_state
, (char *)tokc
.cstr
->data
);
5971 if (n
<= 0 || (n
& (n
- 1)) != 0)
5972 error("alignment must be a positive power of two");
5981 /* currently, no need to handle it because tcc does not
5982 track unused objects */
5986 /* currently, no need to handle it because tcc does not
5987 track unused objects */
5992 ad
->func_call
= FUNC_CDECL
;
5997 ad
->func_call
= FUNC_STDCALL
;
6000 if (tcc_state
->warn_unsupported
)
6001 warning("'%s' attribute ignored", get_tok_str(t
, NULL
));
6002 /* skip parameters */
6003 /* XXX: skip parenthesis too */
6006 while (tok
!= ')' && tok
!= -1)
6021 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
6022 static void struct_decl(CType
*type
, int u
)
6024 int a
, v
, size
, align
, maxalign
, c
, offset
;
6025 int bit_size
, bit_pos
, bsize
, bt
, lbit_pos
;
6030 a
= tok
; /* save decl type */
6035 /* struct already defined ? return it */
6037 expect("struct/union/enum name");
6041 error("invalid type");
6048 /* we put an undefined size for struct/union */
6049 s
= sym_push(v
| SYM_STRUCT
, &type1
, 0, -1);
6050 s
->r
= 0; /* default alignment is zero as gcc */
6051 /* put struct/union/enum name in type */
6059 error("struct/union/enum already defined");
6060 /* cannot be empty */
6062 /* non empty enums are not allowed */
6063 if (a
== TOK_ENUM
) {
6067 expect("identifier");
6073 /* enum symbols have static storage */
6074 ss
= sym_push(v
, &int_type
, VT_CONST
, c
);
6075 ss
->type
.t
|= VT_STATIC
;
6080 /* NOTE: we accept a trailing comma */
6090 while (tok
!= '}') {
6091 parse_btype(&btype
, &ad
);
6097 type_decl(&type1
, &ad
, &v
, TYPE_DIRECT
);
6098 if ((type1
.t
& VT_BTYPE
) == VT_FUNC
||
6099 (type1
.t
& (VT_TYPEDEF
| VT_STATIC
| VT_EXTERN
| VT_INLINE
)))
6100 error("invalid type for '%s'",
6101 get_tok_str(v
, NULL
));
6105 bit_size
= expr_const();
6106 /* XXX: handle v = 0 case for messages */
6108 error("negative width in bit-field '%s'",
6109 get_tok_str(v
, NULL
));
6110 if (v
&& bit_size
== 0)
6111 error("zero width for bit-field '%s'",
6112 get_tok_str(v
, NULL
));
6114 size
= type_size(&type1
, &align
);
6116 if (bit_size
>= 0) {
6117 bt
= type1
.t
& VT_BTYPE
;
6122 error("bitfields must have scalar type");
6124 if (bit_size
> bsize
) {
6125 error("width of '%s' exceeds its type",
6126 get_tok_str(v
, NULL
));
6127 } else if (bit_size
== bsize
) {
6128 /* no need for bit fields */
6130 } else if (bit_size
== 0) {
6131 /* XXX: what to do if only padding in a
6133 /* zero size: means to pad */
6137 /* we do not have enough room ? */
6138 if ((bit_pos
+ bit_size
) > bsize
)
6141 /* XXX: handle LSB first */
6142 type1
.t
|= VT_BITFIELD
|
6143 (bit_pos
<< VT_STRUCT_SHIFT
) |
6144 (bit_size
<< (VT_STRUCT_SHIFT
+ 6));
6145 bit_pos
+= bit_size
;
6151 /* add new memory data only if starting
6153 if (lbit_pos
== 0) {
6154 if (a
== TOK_STRUCT
) {
6155 c
= (c
+ align
- 1) & -align
;
6163 if (align
> maxalign
)
6167 printf("add field %s offset=%d",
6168 get_tok_str(v
, NULL
), offset
);
6169 if (type1
.t
& VT_BITFIELD
) {
6170 printf(" pos=%d size=%d",
6171 (type1
.t
>> VT_STRUCT_SHIFT
) & 0x3f,
6172 (type1
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f);
6176 ss
= sym_push(v
| SYM_FIELD
, &type1
, 0, offset
);
6180 if (tok
== ';' || tok
== TOK_EOF
)
6187 /* store size and alignment */
6188 s
->c
= (c
+ maxalign
- 1) & -maxalign
;
6194 /* return 0 if no type declaration. otherwise, return the basic type
6197 static int parse_btype(CType
*type
, AttributeDef
*ad
)
6199 int t
, u
, type_found
;
6203 memset(ad
, 0, sizeof(AttributeDef
));
6209 /* currently, we really ignore extension */
6219 if ((t
& VT_BTYPE
) != 0)
6220 error("too many basic types");
6234 if ((t
& VT_BTYPE
) == VT_DOUBLE
) {
6235 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6236 } else if ((t
& VT_BTYPE
) == VT_LONG
) {
6237 t
= (t
& ~VT_BTYPE
) | VT_LLONG
;
6251 if ((t
& VT_BTYPE
) == VT_LONG
) {
6252 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6259 struct_decl(&type1
, VT_ENUM
);
6262 type
->ref
= type1
.ref
;
6266 struct_decl(&type1
, VT_STRUCT
);
6269 /* type modifiers */
6317 /* GNUC attribute */
6318 case TOK_ATTRIBUTE1
:
6319 case TOK_ATTRIBUTE2
:
6320 parse_attribute(ad
);
6327 parse_expr_type(&type1
);
6331 if (!s
|| !(s
->type
.t
& VT_TYPEDEF
))
6333 t
|= (s
->type
.t
& ~VT_TYPEDEF
);
6334 type
->ref
= s
->type
.ref
;
6341 /* long is never used as type */
6342 if ((t
& VT_BTYPE
) == VT_LONG
)
6343 t
= (t
& ~VT_BTYPE
) | VT_INT
;
6348 /* convert a function parameter type (array to pointer and function to
6349 function pointer) */
6350 static inline void convert_parameter_type(CType
*pt
)
6352 /* array must be transformed to pointer according to ANSI C */
6354 if ((pt
->t
& VT_BTYPE
) == VT_FUNC
) {
6359 static void post_type(CType
*type
, AttributeDef
*ad
)
6362 Sym
**plast
, *s
, *first
;
6367 /* function declaration */
6372 while (tok
!= ')') {
6373 /* read param name and compute offset */
6374 if (l
!= FUNC_OLD
) {
6375 if (!parse_btype(&pt
, &ad1
)) {
6377 error("invalid type");
6384 if ((pt
.t
& VT_BTYPE
) == VT_VOID
&& tok
== ')')
6386 type_decl(&pt
, &ad1
, &n
, TYPE_DIRECT
| TYPE_ABSTRACT
);
6387 if ((pt
.t
& VT_BTYPE
) == VT_VOID
)
6388 error("parameter declared as void");
6395 convert_parameter_type(&pt
);
6396 s
= sym_push(n
| SYM_FIELD
, &pt
, 0, 0);
6401 if (l
== FUNC_NEW
&& tok
== TOK_DOTS
) {
6408 /* if no parameters, then old type prototype */
6412 t1
= type
->t
& VT_STORAGE
;
6413 /* NOTE: const is ignored in returned type as it has a special
6414 meaning in gcc / C++ */
6415 type
->t
&= ~(VT_STORAGE
| VT_CONSTANT
);
6416 post_type(type
, ad
);
6417 /* we push a anonymous symbol which will contain the function prototype */
6418 s
= sym_push(SYM_FIELD
, type
, ad
->func_call
, l
);
6420 type
->t
= t1
| VT_FUNC
;
6422 } else if (tok
== '[') {
6423 /* array definition */
6429 error("invalid array size");
6432 /* parse next post type */
6433 t1
= type
->t
& VT_STORAGE
;
6434 type
->t
&= ~VT_STORAGE
;
6435 post_type(type
, ad
);
6437 /* we push a anonymous symbol which will contain the array
6439 s
= sym_push(SYM_FIELD
, type
, 0, n
);
6440 type
->t
= t1
| VT_ARRAY
| VT_PTR
;
6445 /* Parse a type declaration (except basic type), and return the type
6446 in 'type'. 'td' is a bitmask indicating which kind of type decl is
6447 expected. 'type' should contain the basic type. 'ad' is the
6448 attribute definition of the basic type. It can be modified by
6451 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
)
6454 CType type1
, *type2
;
6457 while (tok
== '*') {
6465 qualifiers
|= VT_CONSTANT
;
6470 qualifiers
|= VT_VOLATILE
;
6478 type
->t
|= qualifiers
;
6481 /* XXX: clarify attribute handling */
6482 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6483 parse_attribute(ad
);
6485 /* recursive type */
6486 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
6487 type1
.t
= 0; /* XXX: same as int */
6490 /* XXX: this is not correct to modify 'ad' at this point, but
6491 the syntax is not clear */
6492 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6493 parse_attribute(ad
);
6494 type_decl(&type1
, ad
, v
, td
);
6497 /* type identifier */
6498 if (tok
>= TOK_IDENT
&& (td
& TYPE_DIRECT
)) {
6502 if (!(td
& TYPE_ABSTRACT
))
6503 expect("identifier");
6507 post_type(type
, ad
);
6508 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6509 parse_attribute(ad
);
6512 /* append type at the end of type1 */
6525 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
6526 static int lvalue_type(int t
)
6531 if (bt
== VT_BYTE
|| bt
== VT_BOOL
)
6533 else if (bt
== VT_SHORT
)
6537 if (t
& VT_UNSIGNED
)
6538 r
|= VT_LVAL_UNSIGNED
;
6542 /* indirection with full error checking and bound check */
6543 static void indir(void)
6545 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
6547 if ((vtop
->r
& VT_LVAL
) && !nocode_wanted
)
6549 vtop
->type
= *pointed_type(&vtop
->type
);
6550 /* an array is never an lvalue */
6551 if (!(vtop
->type
.t
& VT_ARRAY
)) {
6552 vtop
->r
|= lvalue_type(vtop
->type
.t
);
6553 /* if bound checking, the referenced pointer must be checked */
6554 if (do_bounds_check
)
6555 vtop
->r
|= VT_MUSTBOUND
;
6559 /* pass a parameter to a function and do type checking and casting */
6560 static void gfunc_param_typed(Sym
*func
, Sym
*arg
)
6565 func_type
= func
->c
;
6566 if (func_type
== FUNC_OLD
||
6567 (func_type
== FUNC_ELLIPSIS
&& arg
== NULL
)) {
6568 /* default casting : only need to convert float to double */
6569 if ((vtop
->type
.t
& VT_BTYPE
) == VT_FLOAT
) {
6573 } else if (arg
== NULL
) {
6574 error("too many arguments to function");
6576 gen_assign_cast(&arg
->type
);
6580 /* parse an expression of the form '(type)' or '(expr)' and return its
6582 static void parse_expr_type(CType
*type
)
6588 if (parse_btype(type
, &ad
)) {
6589 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
6596 static void parse_type(CType
*type
)
6601 if (!parse_btype(type
, &ad
)) {
6604 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
6607 static void vpush_tokc(int t
)
6611 vsetc(&type
, VT_CONST
, &tokc
);
6614 static void unary(void)
6616 int n
, t
, align
, size
, r
;
6621 /* XXX: GCC 2.95.3 does not generate a table although it should be
6635 vpush_tokc(VT_INT
| VT_UNSIGNED
);
6639 vpush_tokc(VT_LLONG
);
6643 vpush_tokc(VT_LLONG
| VT_UNSIGNED
);
6647 vpush_tokc(VT_FLOAT
);
6651 vpush_tokc(VT_DOUBLE
);
6655 vpush_tokc(VT_LDOUBLE
);
6658 case TOK___FUNCTION__
:
6660 goto tok_identifier
;
6666 /* special function name identifier */
6667 len
= strlen(funcname
) + 1;
6668 /* generate char[len] type */
6673 vpush_ref(&type
, data_section
, data_section
->data_offset
, len
);
6674 ptr
= section_ptr_add(data_section
, len
);
6675 memcpy(ptr
, funcname
, len
);
6683 /* string parsing */
6686 if (tcc_state
->warn_write_strings
)
6691 memset(&ad
, 0, sizeof(AttributeDef
));
6692 decl_initializer_alloc(&type
, &ad
, VT_CONST
, 2, 0, 0);
6697 if (parse_btype(&type
, &ad
)) {
6698 type_decl(&type
, &ad
, &n
, TYPE_ABSTRACT
);
6700 /* check ISOC99 compound literal */
6702 /* data is allocated locally by default */
6707 /* all except arrays are lvalues */
6708 if (!(type
.t
& VT_ARRAY
))
6709 r
|= lvalue_type(type
.t
);
6710 memset(&ad
, 0, sizeof(AttributeDef
));
6711 decl_initializer_alloc(&type
, &ad
, r
, 1, 0, 0);
6716 } else if (tok
== '{') {
6717 /* save all registers */
6719 /* statement expression : we do not accept break/continue
6720 inside as GCC does */
6721 block(NULL
, NULL
, NULL
, NULL
, 0, 1);
6736 /* functions names must be treated as function pointers,
6737 except for unary '&' and sizeof. Since we consider that
6738 functions are not lvalues, we only have to handle it
6739 there and in function calls. */
6740 /* arrays can also be used although they are not lvalues */
6741 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
&&
6742 !(vtop
->type
.t
& VT_ARRAY
))
6744 mk_pointer(&vtop
->type
);
6750 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
)
6751 vtop
->c
.i
= !vtop
->c
.i
;
6752 else if ((vtop
->r
& VT_VALMASK
) == VT_CMP
)
6753 vtop
->c
.i
= vtop
->c
.i
^ 1;
6755 vseti(VT_JMP
, gtst(1, 0));
6765 /* in order to force cast, we add zero */
6767 if ((vtop
->type
.t
& VT_BTYPE
) == VT_PTR
)
6768 error("pointer not accepted for unary plus");
6778 parse_expr_type(&type
);
6782 size
= type_size(&type
, &align
);
6783 if (t
== TOK_SIZEOF
) {
6785 error("sizeof applied to an incomplete type");
6792 case TOK_builtin_types_compatible_p
:
6801 type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6802 type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6803 vpushi(is_compatible_types(&type1
, &type2
));
6806 case TOK_builtin_constant_p
:
6808 int saved_nocode_wanted
, res
;
6811 saved_nocode_wanted
= nocode_wanted
;
6814 res
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
6816 nocode_wanted
= saved_nocode_wanted
;
6836 goto tok_identifier
;
6838 /* allow to take the address of a label */
6839 if (tok
< TOK_UIDENT
)
6840 expect("label identifier");
6841 s
= label_find(tok
);
6843 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
6845 if (s
->r
== LABEL_DECLARED
)
6846 s
->r
= LABEL_FORWARD
;
6849 s
->type
.t
= VT_VOID
;
6850 mk_pointer(&s
->type
);
6851 s
->type
.t
|= VT_STATIC
;
6853 vset(&s
->type
, VT_CONST
| VT_SYM
, 0);
6862 expect("identifier");
6866 error("'%s' undeclared", get_tok_str(t
, NULL
));
6867 /* for simple function calls, we tolerate undeclared
6868 external reference to int() function */
6869 s
= external_global_sym(t
, &func_old_type
, 0);
6871 vset(&s
->type
, s
->r
, s
->c
);
6872 /* if forward reference, we must point to s */
6873 if (vtop
->r
& VT_SYM
) {
6880 /* post operations */
6882 if (tok
== TOK_INC
|| tok
== TOK_DEC
) {
6885 } else if (tok
== '.' || tok
== TOK_ARROW
) {
6887 if (tok
== TOK_ARROW
)
6892 /* expect pointer on structure */
6893 if ((vtop
->type
.t
& VT_BTYPE
) != VT_STRUCT
)
6894 expect("struct or union");
6898 while ((s
= s
->next
) != NULL
) {
6903 error("field not found");
6904 /* add field offset to pointer */
6905 vtop
->type
= char_pointer_type
; /* change type to 'char *' */
6908 /* change type to field type, and set to lvalue */
6909 vtop
->type
= s
->type
;
6910 /* an array is never an lvalue */
6911 if (!(vtop
->type
.t
& VT_ARRAY
)) {
6912 vtop
->r
|= lvalue_type(vtop
->type
.t
);
6913 /* if bound checking, the referenced pointer must be checked */
6914 if (do_bounds_check
)
6915 vtop
->r
|= VT_MUSTBOUND
;
6918 } else if (tok
== '[') {
6924 } else if (tok
== '(') {
6930 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
) {
6931 /* pointer test (no array accepted) */
6932 if ((vtop
->type
.t
& (VT_BTYPE
| VT_ARRAY
)) == VT_PTR
) {
6933 vtop
->type
= *pointed_type(&vtop
->type
);
6934 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
)
6938 expect("function pointer");
6941 vtop
->r
&= ~VT_LVAL
; /* no lvalue */
6943 /* get return type */
6946 sa
= s
->next
; /* first parameter */
6948 /* compute first implicit argument if a structure is returned */
6949 if ((s
->type
.t
& VT_BTYPE
) == VT_STRUCT
) {
6950 /* get some space for the returned structure */
6951 size
= type_size(&s
->type
, &align
);
6952 loc
= (loc
- size
) & -align
;
6954 ret
.r
= VT_LOCAL
| VT_LVAL
;
6955 /* pass it as 'int' to avoid structure arg passing
6957 vseti(VT_LOCAL
, loc
);
6963 /* return in register */
6964 if (is_float(ret
.type
.t
)) {
6967 if ((ret
.type
.t
& VT_BTYPE
) == VT_LLONG
)
6976 gfunc_param_typed(s
, sa
);
6986 error("too few arguments to function");
6988 if (!nocode_wanted
) {
6989 gfunc_call(nb_args
);
6991 vtop
-= (nb_args
+ 1);
6994 vsetc(&ret
.type
, ret
.r
, &ret
.c
);
7002 static void uneq(void)
7008 (tok
>= TOK_A_MOD
&& tok
<= TOK_A_DIV
) ||
7009 tok
== TOK_A_XOR
|| tok
== TOK_A_OR
||
7010 tok
== TOK_A_SHL
|| tok
== TOK_A_SAR
) {
7025 static void expr_prod(void)
7030 while (tok
== '*' || tok
== '/' || tok
== '%') {
7038 static void expr_sum(void)
7043 while (tok
== '+' || tok
== '-') {
7051 static void expr_shift(void)
7056 while (tok
== TOK_SHL
|| tok
== TOK_SAR
) {
7064 static void expr_cmp(void)
7069 while ((tok
>= TOK_ULE
&& tok
<= TOK_GT
) ||
7070 tok
== TOK_ULT
|| tok
== TOK_UGE
) {
7078 static void expr_cmpeq(void)
7083 while (tok
== TOK_EQ
|| tok
== TOK_NE
) {
7091 static void expr_and(void)
7094 while (tok
== '&') {
7101 static void expr_xor(void)
7104 while (tok
== '^') {
7111 static void expr_or(void)
7114 while (tok
== '|') {
7121 /* XXX: fix this mess */
7122 static void expr_land_const(void)
7125 while (tok
== TOK_LAND
) {
7132 /* XXX: fix this mess */
7133 static void expr_lor_const(void)
7136 while (tok
== TOK_LOR
) {
7143 /* only used if non constant */
7144 static void expr_land(void)
7149 if (tok
== TOK_LAND
) {
7153 if (tok
!= TOK_LAND
) {
7163 static void expr_lor(void)
7168 if (tok
== TOK_LOR
) {
7172 if (tok
!= TOK_LOR
) {
7182 /* XXX: better constant handling */
7183 static void expr_eq(void)
7185 int tt
, u
, r1
, r2
, rc
, t1
, t2
, bt1
, bt2
;
7187 CType type
, type1
, type2
;
7196 if (tok
== ':' && gnu_ext
) {
7212 if (vtop
!= vstack
) {
7213 /* needed to avoid having different registers saved in
7215 if (is_float(vtop
->type
.t
))
7222 if (tok
== ':' && gnu_ext
) {
7230 sv
= *vtop
; /* save value to handle it later */
7231 vtop
--; /* no vpop so that FP stack is not flushed */
7239 bt1
= t1
& VT_BTYPE
;
7241 bt2
= t2
& VT_BTYPE
;
7242 /* cast operands to correct type according to ISOC rules */
7243 if (is_float(bt1
) || is_float(bt2
)) {
7244 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
7245 type
.t
= VT_LDOUBLE
;
7246 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
7251 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
7252 /* cast to biggest op */
7254 /* convert to unsigned if it does not fit in a long long */
7255 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
7256 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
7257 type
.t
|= VT_UNSIGNED
;
7258 } else if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
7259 /* XXX: test pointer compatibility */
7261 } else if (bt1
== VT_STRUCT
|| bt2
== VT_STRUCT
) {
7262 /* XXX: test structure compatibility */
7264 } else if (bt1
== VT_VOID
|| bt2
== VT_VOID
) {
7265 /* NOTE: as an extension, we accept void on only one side */
7268 /* integer operations */
7270 /* convert to unsigned if it does not fit in an integer */
7271 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
7272 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
7273 type
.t
|= VT_UNSIGNED
;
7276 /* now we convert second operand */
7279 if (is_float(type
.t
)) {
7281 } else if ((type
.t
& VT_BTYPE
) == VT_LLONG
) {
7282 /* for long longs, we use fixed registers to avoid having
7283 to handle a complicated move */
7288 /* this is horrible, but we must also convert first
7292 /* put again first value and cast it */
7303 static void gexpr(void)
7314 /* parse an expression and return its type without any side effect. */
7315 static void expr_type(CType
*type
)
7317 int saved_nocode_wanted
;
7319 saved_nocode_wanted
= nocode_wanted
;
7324 nocode_wanted
= saved_nocode_wanted
;
7327 /* parse a unary expression and return its type without any side
7329 static void unary_type(CType
*type
)
7341 /* parse a constant expression and return value in vtop. */
7342 static void expr_const1(void)
7351 /* parse an integer constant and return its value. */
7352 static int expr_const(void)
7356 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
7357 expect("constant expression");
7363 /* return the label token if current token is a label, otherwise
7365 static int is_label(void)
7369 /* fast test first */
7370 if (tok
< TOK_UIDENT
)
7372 /* no need to save tokc because tok is an identifier */
7379 unget_tok(last_tok
);
7384 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
7385 int case_reg
, int is_expr
)
7390 /* generate line number info */
7392 (last_line_num
!= file
->line_num
|| last_ind
!= ind
)) {
7393 put_stabn(N_SLINE
, 0, file
->line_num
, ind
- func_ind
);
7395 last_line_num
= file
->line_num
;
7399 /* default return value is (void) */
7401 vtop
->type
.t
= VT_VOID
;
7404 if (tok
== TOK_IF
) {
7411 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7413 if (c
== TOK_ELSE
) {
7417 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7418 gsym(d
); /* patch else jmp */
7421 } else if (tok
== TOK_WHILE
) {
7429 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7433 } else if (tok
== '{') {
7437 /* record local declaration stack position */
7439 llabel
= local_label_stack
;
7440 /* handle local labels declarations */
7441 if (tok
== TOK_LABEL
) {
7444 if (tok
< TOK_UIDENT
)
7445 expect("label identifier");
7446 label_push(&local_label_stack
, tok
, LABEL_DECLARED
);
7456 while (tok
!= '}') {
7461 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
7464 /* pop locally defined labels */
7465 label_pop(&local_label_stack
, llabel
);
7466 /* pop locally defined symbols */
7467 sym_pop(&local_stack
, s
);
7469 } else if (tok
== TOK_RETURN
) {
7473 gen_assign_cast(&func_vt
);
7474 if ((func_vt
.t
& VT_BTYPE
) == VT_STRUCT
) {
7476 /* if returning structure, must copy it to implicit
7477 first pointer arg location */
7480 vset(&type
, VT_LOCAL
| VT_LVAL
, func_vc
);
7483 /* copy structure value to pointer */
7485 } else if (is_float(func_vt
.t
)) {
7490 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
7493 rsym
= gjmp(rsym
); /* jmp */
7494 } else if (tok
== TOK_BREAK
) {
7497 error("cannot break");
7498 *bsym
= gjmp(*bsym
);
7501 } else if (tok
== TOK_CONTINUE
) {
7504 error("cannot continue");
7505 *csym
= gjmp(*csym
);
7508 } else if (tok
== TOK_FOR
) {
7535 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7540 if (tok
== TOK_DO
) {
7545 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7556 if (tok
== TOK_SWITCH
) {
7560 /* XXX: other types than integer */
7561 case_reg
= gv(RC_INT
);
7565 b
= gjmp(0); /* jump to first case */
7567 block(&a
, csym
, &b
, &c
, case_reg
, 0);
7568 /* if no default, jmp after switch */
7576 if (tok
== TOK_CASE
) {
7583 if (gnu_ext
&& tok
== TOK_DOTS
) {
7587 warning("empty case range");
7589 /* since a case is like a label, we must skip it with a jmp */
7596 *case_sym
= gtst(1, 0);
7599 *case_sym
= gtst(1, 0);
7603 *case_sym
= gtst(1, *case_sym
);
7608 goto block_after_label
;
7610 if (tok
== TOK_DEFAULT
) {
7616 error("too many 'default'");
7619 goto block_after_label
;
7621 if (tok
== TOK_GOTO
) {
7623 if (tok
== '*' && gnu_ext
) {
7627 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
7630 } else if (tok
>= TOK_UIDENT
) {
7631 s
= label_find(tok
);
7632 /* put forward definition if needed */
7634 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
7636 if (s
->r
== LABEL_DECLARED
)
7637 s
->r
= LABEL_FORWARD
;
7639 /* label already defined */
7640 if (s
->r
& LABEL_FORWARD
)
7641 s
->next
= (void *)gjmp((long)s
->next
);
7643 gjmp_addr((long)s
->next
);
7646 expect("label identifier");
7649 } else if (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
) {
7657 if (s
->r
== LABEL_DEFINED
)
7658 error("duplicate label '%s'", get_tok_str(s
->v
, NULL
));
7659 gsym((long)s
->next
);
7660 s
->r
= LABEL_DEFINED
;
7662 s
= label_push(&global_label_stack
, b
, LABEL_DEFINED
);
7664 s
->next
= (void *)ind
;
7665 /* we accept this, but it is a mistake */
7668 warning("deprecated use of label at end of compound statement");
7672 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
7675 /* expression case */
7690 /* t is the array or struct type. c is the array or struct
7691 address. cur_index/cur_field is the pointer to the current
7692 value. 'size_only' is true if only size info is needed (only used
7694 static void decl_designator(CType
*type
, Section
*sec
, unsigned long c
,
7695 int *cur_index
, Sym
**cur_field
,
7699 int notfirst
, index
, index_last
, align
, l
, nb_elems
, elem_size
;
7705 if (gnu_ext
&& (l
= is_label()) != 0)
7707 while (tok
== '[' || tok
== '.') {
7709 if (!(type
->t
& VT_ARRAY
))
7710 expect("array type");
7713 index
= expr_const();
7714 if (index
< 0 || (s
->c
>= 0 && index
>= s
->c
))
7715 expect("invalid index");
7716 if (tok
== TOK_DOTS
&& gnu_ext
) {
7718 index_last
= expr_const();
7719 if (index_last
< 0 ||
7720 (s
->c
>= 0 && index_last
>= s
->c
) ||
7722 expect("invalid index");
7728 *cur_index
= index_last
;
7729 type
= pointed_type(type
);
7730 elem_size
= type_size(type
, &align
);
7731 c
+= index
* elem_size
;
7732 /* NOTE: we only support ranges for last designator */
7733 nb_elems
= index_last
- index
+ 1;
7734 if (nb_elems
!= 1) {
7743 if ((type
->t
& VT_BTYPE
) != VT_STRUCT
)
7744 expect("struct/union type");
7757 /* XXX: fix this mess by using explicit storage field */
7759 type1
.t
|= (type
->t
& ~VT_TYPE
);
7773 if (type
->t
& VT_ARRAY
) {
7775 type
= pointed_type(type
);
7776 c
+= index
* type_size(type
, &align
);
7780 error("too many field init");
7781 /* XXX: fix this mess by using explicit storage field */
7783 type1
.t
|= (type
->t
& ~VT_TYPE
);
7788 decl_initializer(type
, sec
, c
, 0, size_only
);
7790 /* XXX: make it more general */
7791 if (!size_only
&& nb_elems
> 1) {
7792 unsigned long c_end
;
7797 error("range init not supported yet for dynamic storage");
7798 c_end
= c
+ nb_elems
* elem_size
;
7799 if (c_end
> sec
->data_allocated
)
7800 section_realloc(sec
, c_end
);
7801 src
= sec
->data
+ c
;
7803 for(i
= 1; i
< nb_elems
; i
++) {
7805 memcpy(dst
, src
, elem_size
);
7811 #define EXPR_CONST 1
7814 /* store a value or an expression directly in global data or in local array */
7815 static void init_putv(CType
*type
, Section
*sec
, unsigned long c
,
7816 int v
, int expr_type
)
7818 int saved_global_expr
, bt
, bit_pos
, bit_size
;
7820 unsigned long long bit_mask
;
7828 /* compound literals must be allocated globally in this case */
7829 saved_global_expr
= global_expr
;
7832 global_expr
= saved_global_expr
;
7833 /* NOTE: symbols are accepted */
7834 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) != VT_CONST
)
7835 error("initializer element is not constant");
7843 dtype
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
7846 /* XXX: not portable */
7847 /* XXX: generate error if incorrect relocation */
7848 gen_assign_cast(&dtype
);
7849 bt
= type
->t
& VT_BTYPE
;
7850 ptr
= sec
->data
+ c
;
7851 /* XXX: make code faster ? */
7852 if (!(type
->t
& VT_BITFIELD
)) {
7857 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
7858 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
7859 bit_mask
= (1LL << bit_size
) - 1;
7861 if ((vtop
->r
& VT_SYM
) &&
7867 (bt
== VT_INT
&& bit_size
!= 32)))
7868 error("initializer element is not computable at load time");
7871 *(char *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
7874 *(short *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
7877 *(double *)ptr
= vtop
->c
.d
;
7880 *(long double *)ptr
= vtop
->c
.ld
;
7883 *(long long *)ptr
|= (vtop
->c
.ll
& bit_mask
) << bit_pos
;
7886 if (vtop
->r
& VT_SYM
) {
7887 greloc(sec
, vtop
->sym
, c
, R_DATA_32
);
7889 *(int *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
7894 vset(&dtype
, VT_LOCAL
, c
);
7901 /* put zeros for variable based init */
7902 static void init_putz(CType
*t
, Section
*sec
, unsigned long c
, int size
)
7905 /* nothing to do because globals are already set to zero */
7907 vpush_global_sym(&func_old_type
, TOK_memset
);
7915 /* 't' contains the type and storage info. 'c' is the offset of the
7916 object in section 'sec'. If 'sec' is NULL, it means stack based
7917 allocation. 'first' is true if array '{' must be read (multi
7918 dimension implicit array init handling). 'size_only' is true if
7919 size only evaluation is wanted (only for arrays). */
7920 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
7921 int first
, int size_only
)
7923 int index
, array_length
, n
, no_oblock
, nb
, parlevel
, i
;
7924 int size1
, align1
, expr_type
;
7928 if (type
->t
& VT_ARRAY
) {
7932 t1
= pointed_type(type
);
7933 size1
= type_size(t1
, &align1
);
7936 if ((first
&& tok
!= TOK_LSTR
&& tok
!= TOK_STR
) ||
7942 /* only parse strings here if correct type (otherwise: handle
7943 them as ((w)char *) expressions */
7944 if ((tok
== TOK_LSTR
&&
7945 (t1
->t
& VT_BTYPE
) == VT_INT
) ||
7947 (t1
->t
& VT_BTYPE
) == VT_BYTE
)) {
7948 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
7953 /* compute maximum number of chars wanted */
7955 cstr_len
= cstr
->size
;
7957 cstr_len
= cstr
->size
/ sizeof(int);
7960 if (n
>= 0 && nb
> (n
- array_length
))
7961 nb
= n
- array_length
;
7964 warning("initializer-string for array is too long");
7965 /* in order to go faster for common case (char
7966 string in global variable, we handle it
7968 if (sec
&& tok
== TOK_STR
&& size1
== 1) {
7969 memcpy(sec
->data
+ c
+ array_length
, cstr
->data
, nb
);
7973 ch
= ((unsigned char *)cstr
->data
)[i
];
7975 ch
= ((int *)cstr
->data
)[i
];
7976 init_putv(t1
, sec
, c
+ (array_length
+ i
) * size1
,
7984 /* only add trailing zero if enough storage (no
7985 warning in this case since it is standard) */
7986 if (n
< 0 || array_length
< n
) {
7988 init_putv(t1
, sec
, c
+ (array_length
* size1
), 0, EXPR_VAL
);
7994 while (tok
!= '}') {
7995 decl_designator(type
, sec
, c
, &index
, NULL
, size_only
);
7996 if (n
>= 0 && index
>= n
)
7997 error("index too large");
7998 /* must put zero in holes (note that doing it that way
7999 ensures that it even works with designators) */
8000 if (!size_only
&& array_length
< index
) {
8001 init_putz(t1
, sec
, c
+ array_length
* size1
,
8002 (index
- array_length
) * size1
);
8005 if (index
> array_length
)
8006 array_length
= index
;
8007 /* special test for multi dimensional arrays (may not
8008 be strictly correct if designators are used at the
8010 if (index
>= n
&& no_oblock
)
8019 /* put zeros at the end */
8020 if (!size_only
&& n
>= 0 && array_length
< n
) {
8021 init_putz(t1
, sec
, c
+ array_length
* size1
,
8022 (n
- array_length
) * size1
);
8024 /* patch type size if needed */
8026 s
->c
= array_length
;
8027 } else if ((type
->t
& VT_BTYPE
) == VT_STRUCT
&&
8028 (sec
|| !first
|| tok
== '{')) {
8031 /* NOTE: the previous test is a specific case for automatic
8032 struct/union init */
8033 /* XXX: union needs only one init */
8035 /* XXX: this test is incorrect for local initializers
8036 beginning with ( without {. It would be much more difficult
8037 to do it correctly (ideally, the expression parser should
8038 be used in all cases) */
8044 while (tok
== '(') {
8048 if (!parse_btype(&type1
, &ad1
))
8050 type_decl(&type1
, &ad1
, &n
, TYPE_ABSTRACT
);
8052 if (!is_assignable_types(type
, &type1
))
8053 error("invalid type for cast");
8058 if (first
|| tok
== '{') {
8067 while (tok
!= '}') {
8068 decl_designator(type
, sec
, c
, NULL
, &f
, size_only
);
8070 if (!size_only
&& array_length
< index
) {
8071 init_putz(type
, sec
, c
+ array_length
,
8072 index
- array_length
);
8074 index
= index
+ type_size(&f
->type
, &align1
);
8075 if (index
> array_length
)
8076 array_length
= index
;
8078 if (no_oblock
&& f
== NULL
)
8084 /* put zeros at the end */
8085 if (!size_only
&& array_length
< n
) {
8086 init_putz(type
, sec
, c
+ array_length
,
8095 } else if (tok
== '{') {
8097 decl_initializer(type
, sec
, c
, first
, size_only
);
8099 } else if (size_only
) {
8100 /* just skip expression */
8102 while ((parlevel
> 0 || (tok
!= '}' && tok
!= ',')) &&
8106 else if (tok
== ')')
8111 /* currently, we always use constant expression for globals
8112 (may change for scripting case) */
8113 expr_type
= EXPR_CONST
;
8115 expr_type
= EXPR_ANY
;
8116 init_putv(type
, sec
, c
, 0, expr_type
);
8120 /* parse an initializer for type 't' if 'has_init' is non zero, and
8121 allocate space in local or global data space ('r' is either
8122 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
8123 variable 'v' of scope 'scope' is declared before initializers are
8124 parsed. If 'v' is zero, then a reference to the new object is put
8125 in the value stack. If 'has_init' is 2, a special parsing is done
8126 to handle string constants. */
8127 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
8128 int has_init
, int v
, int scope
)
8130 int size
, align
, addr
, data_offset
;
8132 ParseState saved_parse_state
;
8133 TokenString init_str
;
8136 size
= type_size(type
, &align
);
8137 /* If unknown size, we must evaluate it before
8138 evaluating initializers because
8139 initializers can generate global data too
8140 (e.g. string pointers or ISOC99 compound
8141 literals). It also simplifies local
8142 initializers handling */
8143 tok_str_new(&init_str
);
8146 error("unknown type size");
8147 /* get all init string */
8148 if (has_init
== 2) {
8149 /* only get strings */
8150 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
8151 tok_str_add_tok(&init_str
);
8156 while (level
> 0 || (tok
!= ',' && tok
!= ';')) {
8158 error("unexpected end of file in initializer");
8159 tok_str_add_tok(&init_str
);
8162 else if (tok
== '}') {
8170 tok_str_add(&init_str
, -1);
8171 tok_str_add(&init_str
, 0);
8174 save_parse_state(&saved_parse_state
);
8176 macro_ptr
= init_str
.str
;
8178 decl_initializer(type
, NULL
, 0, 1, 1);
8179 /* prepare second initializer parsing */
8180 macro_ptr
= init_str
.str
;
8183 /* if still unknown size, error */
8184 size
= type_size(type
, &align
);
8186 error("unknown type size");
8188 /* take into account specified alignment if bigger */
8189 if (ad
->aligned
> align
)
8190 align
= ad
->aligned
;
8191 if ((r
& VT_VALMASK
) == VT_LOCAL
) {
8193 if (do_bounds_check
&& (type
->t
& VT_ARRAY
))
8195 loc
= (loc
- size
) & -align
;
8197 /* handles bounds */
8198 /* XXX: currently, since we do only one pass, we cannot track
8199 '&' operators, so we add only arrays */
8200 if (do_bounds_check
&& (type
->t
& VT_ARRAY
)) {
8201 unsigned long *bounds_ptr
;
8202 /* add padding between regions */
8204 /* then add local bound info */
8205 bounds_ptr
= section_ptr_add(lbounds_section
, 2 * sizeof(unsigned long));
8206 bounds_ptr
[0] = addr
;
8207 bounds_ptr
[1] = size
;
8210 /* local variable */
8211 sym_push(v
, type
, r
, addr
);
8213 /* push local reference */
8214 vset(type
, r
, addr
);
8220 if (v
&& scope
== VT_CONST
) {
8221 /* see if the symbol was already defined */
8224 if (!is_compatible_types(&sym
->type
, type
))
8225 error("incompatible types for redefinition of '%s'",
8226 get_tok_str(v
, NULL
));
8227 if (sym
->type
.t
& VT_EXTERN
) {
8228 /* if the variable is extern, it was not allocated */
8229 sym
->type
.t
&= ~VT_EXTERN
;
8231 /* we accept several definitions of the same
8232 global variable. this is tricky, because we
8233 must play with the SHN_COMMON type of the symbol */
8234 /* XXX: should check if the variable was already
8235 initialized. It is incorrect to initialized it
8237 /* no init data, we won't add more to the symbol */
8244 /* allocate symbol in corresponding section */
8251 data_offset
= sec
->data_offset
;
8252 data_offset
= (data_offset
+ align
- 1) & -align
;
8254 /* very important to increment global pointer at this time
8255 because initializers themselves can create new initializers */
8256 data_offset
+= size
;
8257 /* add padding if bound check */
8258 if (do_bounds_check
)
8260 sec
->data_offset
= data_offset
;
8261 /* allocate section space to put the data */
8262 if (sec
->sh_type
!= SHT_NOBITS
&&
8263 data_offset
> sec
->data_allocated
)
8264 section_realloc(sec
, data_offset
);
8266 addr
= 0; /* avoid warning */
8270 if (scope
== VT_CONST
) {
8275 sym
= sym_push(v
, type
, r
| VT_SYM
, 0);
8277 /* update symbol definition */
8279 put_extern_sym(sym
, sec
, addr
, size
);
8282 /* put a common area */
8283 put_extern_sym(sym
, NULL
, align
, size
);
8284 /* XXX: find a nicer way */
8285 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
8286 esym
->st_shndx
= SHN_COMMON
;
8291 /* push global reference */
8292 sym
= get_sym_ref(type
, sec
, addr
, size
);
8294 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
8298 /* handles bounds now because the symbol must be defined
8299 before for the relocation */
8300 if (do_bounds_check
) {
8301 unsigned long *bounds_ptr
;
8303 greloc(bounds_section
, sym
, bounds_section
->data_offset
, R_DATA_32
);
8304 /* then add global bound info */
8305 bounds_ptr
= section_ptr_add(bounds_section
, 2 * sizeof(long));
8306 bounds_ptr
[0] = 0; /* relocated */
8307 bounds_ptr
[1] = size
;
8311 decl_initializer(type
, sec
, addr
, 1, 0);
8312 /* restore parse state if needed */
8314 tok_str_free(init_str
.str
);
8315 restore_parse_state(&saved_parse_state
);
8321 void put_func_debug(Sym
*sym
)
8326 /* XXX: we put here a dummy type */
8327 snprintf(buf
, sizeof(buf
), "%s:%c1",
8328 funcname
, sym
->type
.t
& VT_STATIC
? 'f' : 'F');
8329 put_stabs_r(buf
, N_FUN
, 0, file
->line_num
, 0,
8330 cur_text_section
, sym
->c
);
8335 /* not finished : try to put some local vars in registers */
8336 //#define CONFIG_REG_VARS
8338 #ifdef CONFIG_REG_VARS
8339 void add_var_ref(int t
)
8341 printf("%s:%d: &%s\n",
8342 file
->filename
, file
->line_num
,
8343 get_tok_str(t
, NULL
));
8346 /* first pass on a function with heuristic to extract variable usage
8347 and pointer references to local variables for register allocation */
8348 void analyse_function(void)
8355 /* any symbol coming after '&' is considered as being a
8356 variable whose reference is taken. It is highly unaccurate
8357 but it is difficult to do better without a complete parse */
8360 /* if '& number', then no need to examine next tokens */
8361 if (tok
== TOK_CINT
||
8363 tok
== TOK_CLLONG
||
8364 tok
== TOK_CULLONG
) {
8366 } else if (tok
>= TOK_UIDENT
) {
8367 /* if '& ident [' or '& ident ->', then ident address
8371 if (tok
!= '[' && tok
!= TOK_ARROW
)
8375 while (tok
!= '}' && tok
!= ';' &&
8376 !((tok
== ',' || tok
== ')') && level
== 0)) {
8377 if (tok
>= TOK_UIDENT
) {
8379 } else if (tok
== '(') {
8381 } else if (tok
== ')') {
8394 /* parse an old style function declaration list */
8395 /* XXX: check multiple parameter */
8396 static void func_decl_list(Sym
*func_sym
)
8403 /* parse each declaration */
8404 while (tok
!= '{' && tok
!= ';' && tok
!= ',' && tok
!= TOK_EOF
) {
8405 if (!parse_btype(&btype
, &ad
))
8406 expect("declaration list");
8407 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
8408 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
8410 /* we accept no variable after */
8414 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
8415 /* find parameter in function parameter list */
8418 if ((s
->v
& ~SYM_FIELD
) == v
)
8422 error("declaration for parameter '%s' but no such parameter",
8423 get_tok_str(v
, NULL
));
8425 /* check that no storage specifier except 'register' was given */
8426 if (type
.t
& VT_STORAGE
)
8427 error("storage class specified for '%s'", get_tok_str(v
, NULL
));
8428 convert_parameter_type(&type
);
8429 /* we can add the type (NOTE: it could be local to the function) */
8431 /* accept other parameters */
8442 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
8443 static void decl(int l
)
8451 if (!parse_btype(&btype
, &ad
)) {
8452 /* skip redundant ';' */
8453 /* XXX: find more elegant solution */
8458 /* special test for old K&R protos without explicit int
8459 type. Only accepted when defining global data */
8460 if (l
== VT_LOCAL
|| tok
< TOK_DEFINE
)
8464 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
8465 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
8467 /* we accept no variable after */
8471 while (1) { /* iterate thru each declaration */
8473 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
8477 type_to_str(buf
, sizeof(buf
), t
, get_tok_str(v
, NULL
));
8478 printf("type = '%s'\n", buf
);
8481 if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
8482 /* if old style function prototype, we accept a
8485 if (sym
->c
== FUNC_OLD
)
8486 func_decl_list(sym
);
8490 #ifdef CONFIG_REG_VARS
8491 TokenString func_str
;
8492 ParseState saved_parse_state
;
8497 error("cannot use local functions");
8498 if (!(type
.t
& VT_FUNC
))
8499 expect("function definition");
8500 /* XXX: cannot do better now: convert extern line to static inline */
8501 if ((type
.t
& (VT_EXTERN
| VT_INLINE
)) == (VT_EXTERN
| VT_INLINE
))
8502 type
.t
= (type
.t
& ~VT_EXTERN
) | VT_STATIC
;
8504 #ifdef CONFIG_REG_VARS
8505 /* parse all function code and record it */
8507 tok_str_new(&func_str
);
8513 error("unexpected end of file");
8514 tok_str_add_tok(&func_str
);
8519 } else if (t
== '}') {
8521 if (block_level
== 0)
8525 tok_str_add(&func_str
, -1);
8526 tok_str_add(&func_str
, 0);
8528 save_parse_state(&saved_parse_state
);
8530 macro_ptr
= func_str
.str
;
8535 /* compute text section */
8536 cur_text_section
= ad
.section
;
8537 if (!cur_text_section
)
8538 cur_text_section
= text_section
;
8539 ind
= cur_text_section
->data_offset
;
8540 funcname
= get_tok_str(v
, NULL
);
8543 /* if symbol is already defined, then put complete type */
8546 /* put function symbol */
8547 sym
= global_identifier_push(v
, type
.t
, 0);
8548 sym
->type
.ref
= type
.ref
;
8550 /* NOTE: we patch the symbol size later */
8551 put_extern_sym(sym
, cur_text_section
, ind
, 0);
8553 sym
->r
= VT_SYM
| VT_CONST
;
8554 /* put debug symbol */
8556 put_func_debug(sym
);
8557 /* push a dummy symbol to enable local sym storage */
8558 sym_push2(&local_stack
, SYM_FIELD
, 0, 0);
8559 gfunc_prolog(&type
);
8562 #ifdef CONFIG_REG_VARS
8563 macro_ptr
= func_str
.str
;
8566 block(NULL
, NULL
, NULL
, NULL
, 0, 0);
8569 cur_text_section
->data_offset
= ind
;
8570 label_pop(&global_label_stack
, NULL
);
8571 sym_pop(&local_stack
, NULL
); /* reset local stack */
8572 /* end of function */
8573 /* patch symbol size */
8574 ((Elf32_Sym
*)symtab_section
->data
)[sym
->c
].st_size
=
8577 put_stabn(N_FUN
, 0, 0, ind
- func_ind
);
8579 funcname
= ""; /* for safety */
8580 func_vt
.t
= VT_VOID
; /* for safety */
8581 ind
= 0; /* for safety */
8583 #ifdef CONFIG_REG_VARS
8584 tok_str_free(func_str
.str
);
8585 restore_parse_state(&saved_parse_state
);
8589 if (btype
.t
& VT_TYPEDEF
) {
8590 /* save typedefed type */
8591 /* XXX: test storage specifiers ? */
8592 sym
= sym_push(v
, &type
, 0, 0);
8593 sym
->type
.t
|= VT_TYPEDEF
;
8594 } else if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
8595 /* external function definition */
8596 external_sym(v
, &type
, 0);
8598 /* not lvalue if array */
8600 if (!(type
.t
& VT_ARRAY
))
8601 r
|= lvalue_type(type
.t
);
8602 has_init
= (tok
== '=');
8603 if ((btype
.t
& VT_EXTERN
) ||
8604 ((type
.t
& VT_ARRAY
) && (type
.t
& VT_STATIC
) &&
8605 !has_init
&& l
== VT_CONST
&& type
.ref
->c
< 0)) {
8606 /* external variable */
8607 /* NOTE: as GCC, uninitialized global static
8608 arrays of null size are considered as
8610 external_sym(v
, &type
, r
);
8612 if (type
.t
& VT_STATIC
)
8618 decl_initializer_alloc(&type
, &ad
, r
,
8632 /* better than nothing, but needs extension to handle '-E' option
8634 static void preprocess_init(TCCState
*s1
)
8636 s1
->include_stack_ptr
= s1
->include_stack
;
8637 /* XXX: move that before to avoid having to initialize
8638 file->ifdef_stack_ptr ? */
8639 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
8640 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
8642 /* XXX: not ANSI compliant: bound checking says error */
8646 /* compile the C file opened in 'file'. Return non zero if errors. */
8647 static int tcc_compile(TCCState
*s1
)
8651 volatile int section_sym
;
8654 printf("%s: **** new file\n", file
->filename
);
8656 preprocess_init(s1
);
8659 anon_sym
= SYM_FIRST_ANOM
;
8661 /* file info: full path + filename */
8662 section_sym
= 0; /* avoid warning */
8664 section_sym
= put_elf_sym(symtab_section
, 0, 0,
8665 ELF32_ST_INFO(STB_LOCAL
, STT_SECTION
), 0,
8666 text_section
->sh_num
, NULL
);
8667 getcwd(buf
, sizeof(buf
));
8668 pstrcat(buf
, sizeof(buf
), "/");
8669 put_stabs_r(buf
, N_SO
, 0, 0,
8670 text_section
->data_offset
, text_section
, section_sym
);
8671 put_stabs_r(file
->filename
, N_SO
, 0, 0,
8672 text_section
->data_offset
, text_section
, section_sym
);
8674 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
8675 symbols can be safely used */
8676 put_elf_sym(symtab_section
, 0, 0,
8677 ELF32_ST_INFO(STB_LOCAL
, STT_FILE
), 0,
8678 SHN_ABS
, file
->filename
);
8680 /* define some often used types */
8681 int_type
.t
= VT_INT
;
8683 char_pointer_type
.t
= VT_BYTE
;
8684 mk_pointer(&char_pointer_type
);
8686 func_old_type
.t
= VT_FUNC
;
8687 func_old_type
.ref
= sym_push(SYM_FIELD
, &int_type
, FUNC_CDECL
, FUNC_OLD
);
8690 /* define 'void *alloca(unsigned int)' builtin function */
8695 sym
= sym_push(p
, mk_pointer(VT_VOID
), FUNC_CDECL
, FUNC_NEW
);
8696 s1
= sym_push(SYM_FIELD
, VT_UNSIGNED
| VT_INT
, 0, 0);
8699 sym_push(TOK_alloca
, VT_FUNC
| (p
<< VT_STRUCT_SHIFT
), VT_CONST
, 0);
8703 define_start
= define_stack
;
8705 if (setjmp(s1
->error_jmp_buf
) == 0) {
8707 s1
->error_set_jmp_enabled
= 1;
8709 ch
= file
->buf_ptr
[0];
8710 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
8711 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
;
8715 expect("declaration");
8717 /* end of translation unit info */
8719 put_stabs_r(NULL
, N_SO
, 0, 0,
8720 text_section
->data_offset
, text_section
, section_sym
);
8723 s1
->error_set_jmp_enabled
= 0;
8725 /* reset define stack, but leave -Dsymbols (may be incorrect if
8726 they are undefined) */
8727 free_defines(define_start
);
8729 sym_pop(&global_stack
, NULL
);
8731 return s1
->nb_errors
!= 0 ? -1 : 0;
8735 int tcc_compile_string(TCCState
*s
, const char *str
)
8737 BufferedFile bf1
, *bf
= &bf1
;
8741 /* init file structure */
8743 /* XXX: avoid copying */
8745 buf
= tcc_malloc(len
+ 1);
8748 memcpy(buf
, str
, len
);
8751 bf
->buf_end
= buf
+ len
;
8752 pstrcpy(bf
->filename
, sizeof(bf
->filename
), "<string>");
8756 ret
= tcc_compile(s
);
8760 /* currently, no need to close */
8765 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
8766 void tcc_define_symbol(TCCState
*s1
, const char *sym
, const char *value
)
8768 BufferedFile bf1
, *bf
= &bf1
;
8770 pstrcpy(bf
->buffer
, IO_BUF_SIZE
, sym
);
8771 pstrcat(bf
->buffer
, IO_BUF_SIZE
, " ");
8775 pstrcat(bf
->buffer
, IO_BUF_SIZE
, value
);
8777 /* init file structure */
8779 bf
->buf_ptr
= bf
->buffer
;
8780 bf
->buf_end
= bf
->buffer
+ strlen(bf
->buffer
);
8781 *bf
->buf_end
= CH_EOB
;
8782 bf
->filename
[0] = '\0';
8786 s1
->include_stack_ptr
= s1
->include_stack
;
8788 /* parse with define parser */
8789 ch
= file
->buf_ptr
[0];
8795 /* undefine a preprocessor symbol */
8796 void tcc_undefine_symbol(TCCState
*s1
, const char *sym
)
8800 ts
= tok_alloc(sym
, strlen(sym
));
8801 s
= define_find(ts
->tok
);
8802 /* undefine symbol by putting an invalid name */
8807 #ifdef CONFIG_TCC_ASM
8809 #include "i386-asm.c"
8813 static void asm_instr(void)
8815 error("inline asm() not supported");
8821 /* print the position in the source file of PC value 'pc' by reading
8822 the stabs debug information */
8823 static void rt_printline(unsigned long wanted_pc
)
8825 Stab_Sym
*sym
, *sym_end
;
8826 char func_name
[128], last_func_name
[128];
8827 unsigned long func_addr
, last_pc
, pc
;
8828 const char *incl_files
[INCLUDE_STACK_SIZE
];
8829 int incl_index
, len
, last_line_num
, i
;
8830 const char *str
, *p
;
8832 fprintf(stderr
, "0x%08lx:", wanted_pc
);
8834 func_name
[0] = '\0';
8837 last_func_name
[0] = '\0';
8838 last_pc
= 0xffffffff;
8840 sym
= (Stab_Sym
*)stab_section
->data
+ 1;
8841 sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
8842 while (sym
< sym_end
) {
8843 switch(sym
->n_type
) {
8844 /* function start or end */
8846 if (sym
->n_strx
== 0) {
8847 /* we test if between last line and end of function */
8848 pc
= sym
->n_value
+ func_addr
;
8849 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
8851 func_name
[0] = '\0';
8854 str
= stabstr_section
->data
+ sym
->n_strx
;
8855 p
= strchr(str
, ':');
8857 pstrcpy(func_name
, sizeof(func_name
), str
);
8860 if (len
> sizeof(func_name
) - 1)
8861 len
= sizeof(func_name
) - 1;
8862 memcpy(func_name
, str
, len
);
8863 func_name
[len
] = '\0';
8865 func_addr
= sym
->n_value
;
8868 /* line number info */
8870 pc
= sym
->n_value
+ func_addr
;
8871 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
8874 last_line_num
= sym
->n_desc
;
8876 strcpy(last_func_name
, func_name
);
8880 str
= stabstr_section
->data
+ sym
->n_strx
;
8882 if (incl_index
< INCLUDE_STACK_SIZE
) {
8883 incl_files
[incl_index
++] = str
;
8891 if (sym
->n_strx
== 0) {
8892 incl_index
= 0; /* end of translation unit */
8894 str
= stabstr_section
->data
+ sym
->n_strx
;
8895 /* do not add path */
8897 if (len
> 0 && str
[len
- 1] != '/')
8905 /* second pass: we try symtab symbols (no line number info) */
8908 Elf32_Sym
*sym
, *sym_end
;
8911 sym_end
= (Elf32_Sym
*)(symtab_section
->data
+ symtab_section
->data_offset
);
8912 for(sym
= (Elf32_Sym
*)symtab_section
->data
+ 1;
8915 type
= ELF32_ST_TYPE(sym
->st_info
);
8916 if (type
== STT_FUNC
) {
8917 if (wanted_pc
>= sym
->st_value
&&
8918 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
8919 pstrcpy(last_func_name
, sizeof(last_func_name
),
8920 strtab_section
->data
+ sym
->st_name
);
8926 /* did not find any info: */
8927 fprintf(stderr
, " ???\n");
8930 if (last_func_name
[0] != '\0') {
8931 fprintf(stderr
, " %s()", last_func_name
);
8933 if (incl_index
> 0) {
8934 fprintf(stderr
, " (%s:%d",
8935 incl_files
[incl_index
- 1], last_line_num
);
8936 for(i
= incl_index
- 2; i
>= 0; i
--)
8937 fprintf(stderr
, ", included from %s", incl_files
[i
]);
8938 fprintf(stderr
, ")");
8940 fprintf(stderr
, "\n");
8947 /* fix for glibc 2.1 */
8953 /* return the PC at frame level 'level'. Return non zero if not found */
8954 static int rt_get_caller_pc(unsigned long *paddr
,
8955 ucontext_t
*uc
, int level
)
8962 *paddr
= uc
->uc_mcontext
.mc_eip
;
8964 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
8969 fp
= uc
->uc_mcontext
.mc_ebp
;
8971 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
8973 for(i
=1;i
<level
;i
++) {
8974 /* XXX: check address validity with program info */
8975 if (fp
<= 0x1000 || fp
>= 0xc0000000)
8977 fp
= ((unsigned long *)fp
)[0];
8979 *paddr
= ((unsigned long *)fp
)[1];
8984 #error add arch specific rt_get_caller_pc()
8987 /* emit a run time error at position 'pc' */
8988 void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
8995 fprintf(stderr
, "Runtime error: ");
8996 vfprintf(stderr
, fmt
, ap
);
8997 fprintf(stderr
, "\n");
8998 for(i
=0;i
<num_callers
;i
++) {
8999 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
9002 fprintf(stderr
, "at ");
9004 fprintf(stderr
, "by ");
9011 /* signal handler for fatal errors */
9012 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
9014 ucontext_t
*uc
= puc
;
9018 switch(siginf
->si_code
) {
9021 rt_error(uc
, "division by zero");
9024 rt_error(uc
, "floating point exception");
9030 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
9031 rt_error(uc
, *rt_bound_error_msg
);
9033 rt_error(uc
, "dereferencing invalid pointer");
9036 rt_error(uc
, "illegal instruction");
9039 rt_error(uc
, "abort() called");
9042 rt_error(uc
, "caught signal %d", signum
);
9049 /* do all relocations (needed before using tcc_get_symbol()) */
9050 int tcc_relocate(TCCState
*s1
)
9057 tcc_add_runtime(s1
);
9059 relocate_common_syms();
9061 /* compute relocation address : section are relocated in place. We
9062 also alloc the bss space */
9063 for(i
= 1; i
< s1
->nb_sections
; i
++) {
9064 s
= s1
->sections
[i
];
9065 if (s
->sh_flags
& SHF_ALLOC
) {
9066 if (s
->sh_type
== SHT_NOBITS
)
9067 s
->data
= tcc_mallocz(s
->data_offset
);
9068 s
->sh_addr
= (unsigned long)s
->data
;
9072 relocate_syms(s1
, 1);
9074 if (s1
->nb_errors
!= 0)
9077 /* relocate each section */
9078 for(i
= 1; i
< s1
->nb_sections
; i
++) {
9079 s
= s1
->sections
[i
];
9081 relocate_section(s1
, s
);
9086 /* launch the compiled program with the given arguments */
9087 int tcc_run(TCCState
*s1
, int argc
, char **argv
)
9089 int (*prog_main
)(int, char **);
9091 if (tcc_relocate(s1
) < 0)
9094 prog_main
= tcc_get_symbol(s1
, "main");
9098 error("debug mode currently not available for Windows");
9100 struct sigaction sigact
;
9101 /* install TCC signal handlers to print debug info on fatal
9103 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
9104 sigact
.sa_sigaction
= sig_error
;
9105 sigemptyset(&sigact
.sa_mask
);
9106 sigaction(SIGFPE
, &sigact
, NULL
);
9107 sigaction(SIGILL
, &sigact
, NULL
);
9108 sigaction(SIGSEGV
, &sigact
, NULL
);
9109 sigaction(SIGBUS
, &sigact
, NULL
);
9110 sigaction(SIGABRT
, &sigact
, NULL
);
9114 #ifdef CONFIG_TCC_BCHECK
9115 if (do_bounds_check
) {
9116 void (*bound_init
)(void);
9118 /* set error function */
9119 rt_bound_error_msg
= (void *)tcc_get_symbol(s1
, "__bound_error_msg");
9121 /* XXX: use .init section so that it also work in binary ? */
9122 bound_init
= (void *)tcc_get_symbol(s1
, "__bound_init");
9126 return (*prog_main
)(argc
, argv
);
9129 TCCState
*tcc_new(void)
9136 s
= tcc_mallocz(sizeof(TCCState
));
9140 s
->output_type
= TCC_OUTPUT_MEMORY
;
9142 /* init isid table */
9144 isidnum_table
[i
] = isid(i
) || isnum(i
);
9146 /* add all tokens */
9148 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
9150 tok_ident
= TOK_IDENT
;
9159 ts
= tok_alloc(p
, r
- p
- 1);
9163 /* we add dummy defines for some special macros to speed up tests
9164 and to have working defined() */
9165 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
9166 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
9167 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
9168 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
9170 /* standard defines */
9171 tcc_define_symbol(s
, "__STDC__", NULL
);
9172 #if defined(TCC_TARGET_I386)
9173 tcc_define_symbol(s
, "__i386__", NULL
);
9176 tcc_define_symbol(s
, "__linux__", NULL
);
9177 tcc_define_symbol(s
, "linux", NULL
);
9179 /* tiny C specific defines */
9180 tcc_define_symbol(s
, "__TINYC__", NULL
);
9182 /* tiny C & gcc defines */
9183 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned int");
9184 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "int");
9185 tcc_define_symbol(s
, "__WCHAR_TYPE__", "int");
9187 /* default library paths */
9188 tcc_add_library_path(s
, "/usr/local/lib");
9189 tcc_add_library_path(s
, "/usr/lib");
9190 tcc_add_library_path(s
, "/lib");
9192 /* no section zero */
9193 dynarray_add((void ***)&s
->sections
, &s
->nb_sections
, NULL
);
9195 /* create standard sections */
9196 text_section
= new_section(s
, ".text", SHT_PROGBITS
, SHF_ALLOC
| SHF_EXECINSTR
);
9197 data_section
= new_section(s
, ".data", SHT_PROGBITS
, SHF_ALLOC
| SHF_WRITE
);
9198 bss_section
= new_section(s
, ".bss", SHT_NOBITS
, SHF_ALLOC
| SHF_WRITE
);
9200 /* symbols are always generated for linking stage */
9201 symtab_section
= new_symtab(s
, ".symtab", SHT_SYMTAB
, 0,
9203 ".hashtab", SHF_PRIVATE
);
9204 strtab_section
= symtab_section
->link
;
9206 /* private symbol table for dynamic symbols */
9207 s
->dynsymtab_section
= new_symtab(s
, ".dynsymtab", SHT_SYMTAB
, SHF_PRIVATE
,
9209 ".dynhashtab", SHF_PRIVATE
);
9213 void tcc_delete(TCCState
*s1
)
9217 /* free -D defines */
9221 n
= tok_ident
- TOK_IDENT
;
9222 for(i
= 0; i
< n
; i
++)
9223 tcc_free(table_ident
[i
]);
9224 tcc_free(table_ident
);
9226 /* free all sections */
9228 free_section(symtab_section
->hash
);
9230 free_section(s1
->dynsymtab_section
->hash
);
9231 free_section(s1
->dynsymtab_section
->link
);
9232 free_section(s1
->dynsymtab_section
);
9234 for(i
= 1; i
< s1
->nb_sections
; i
++)
9235 free_section(s1
->sections
[i
]);
9236 tcc_free(s1
->sections
);
9238 /* free loaded dlls array */
9239 for(i
= 0; i
< s1
->nb_loaded_dlls
; i
++)
9240 tcc_free(s1
->loaded_dlls
[i
]);
9241 tcc_free(s1
->loaded_dlls
);
9244 for(i
= 0; i
< s1
->nb_library_paths
; i
++)
9245 tcc_free(s1
->library_paths
[i
]);
9246 tcc_free(s1
->library_paths
);
9248 /* cached includes */
9249 for(i
= 0; i
< s1
->nb_cached_includes
; i
++)
9250 tcc_free(s1
->cached_includes
[i
]);
9251 tcc_free(s1
->cached_includes
);
9253 for(i
= 0; i
< s1
->nb_include_paths
; i
++)
9254 tcc_free(s1
->include_paths
[i
]);
9255 tcc_free(s1
->include_paths
);
9257 for(i
= 0; i
< s1
->nb_sysinclude_paths
; i
++)
9258 tcc_free(s1
->sysinclude_paths
[i
]);
9259 tcc_free(s1
->sysinclude_paths
);
9264 int tcc_add_include_path(TCCState
*s1
, const char *pathname
)
9268 pathname1
= tcc_strdup(pathname
);
9269 dynarray_add((void ***)&s1
->include_paths
, &s1
->nb_include_paths
, pathname1
);
9273 int tcc_add_sysinclude_path(TCCState
*s1
, const char *pathname
)
9277 pathname1
= tcc_strdup(pathname
);
9278 dynarray_add((void ***)&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
, pathname1
);
9282 static int tcc_add_file_internal(TCCState
*s1
, const char *filename
, int flags
)
9284 const char *ext
, *filename1
;
9287 BufferedFile
*saved_file
;
9289 /* find source file type with extension */
9290 filename1
= strrchr(filename
, '/');
9294 filename1
= filename
;
9295 ext
= strrchr(filename1
, '.');
9301 file
= tcc_open(s1
, filename
);
9303 if (flags
& AFF_PRINT_ERROR
) {
9304 error_noabort("file '%s' not found", filename
);
9310 if (!ext
|| !strcmp(ext
, "c")) {
9311 /* C file assumed */
9312 ret
= tcc_compile(s1
);
9314 #ifdef CONFIG_TCC_ASM
9315 if (!strcmp(ext
, "S")) {
9316 /* preprocessed assembler */
9317 ret
= tcc_assemble(s1
, 1);
9318 } else if (!strcmp(ext
, "s")) {
9319 /* non preprocessed assembler */
9320 ret
= tcc_assemble(s1
, 0);
9325 /* assume executable format: auto guess file type */
9326 if (read(fd
, &ehdr
, sizeof(ehdr
)) != sizeof(ehdr
)) {
9327 error_noabort("could not read header");
9330 lseek(fd
, 0, SEEK_SET
);
9332 if (ehdr
.e_ident
[0] == ELFMAG0
&&
9333 ehdr
.e_ident
[1] == ELFMAG1
&&
9334 ehdr
.e_ident
[2] == ELFMAG2
&&
9335 ehdr
.e_ident
[3] == ELFMAG3
) {
9336 file
->line_num
= 0; /* do not display line number if error */
9337 if (ehdr
.e_type
== ET_REL
) {
9338 ret
= tcc_load_object_file(s1
, fd
, 0);
9339 } else if (ehdr
.e_type
== ET_DYN
) {
9340 ret
= tcc_load_dll(s1
, fd
, filename
,
9341 (flags
& AFF_REFERENCED_DLL
) != 0);
9343 error_noabort("unrecognized ELF file");
9346 } else if (memcmp((char *)&ehdr
, ARMAG
, 8) == 0) {
9347 file
->line_num
= 0; /* do not display line number if error */
9348 ret
= tcc_load_archive(s1
, fd
);
9350 /* as GNU ld, consider it is an ld script if not recognized */
9351 ret
= tcc_load_ldscript(s1
);
9353 error_noabort("unrecognized file type");
9368 int tcc_add_file(TCCState
*s
, const char *filename
)
9370 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
);
9373 int tcc_add_library_path(TCCState
*s
, const char *pathname
)
9377 pathname1
= tcc_strdup(pathname
);
9378 dynarray_add((void ***)&s
->library_paths
, &s
->nb_library_paths
, pathname1
);
9382 /* find and load a dll. Return non zero if not found */
9383 /* XXX: add '-rpath' option support ? */
9384 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
)
9389 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
9390 snprintf(buf
, sizeof(buf
), "%s/%s",
9391 s
->library_paths
[i
], filename
);
9392 if (tcc_add_file_internal(s
, buf
, flags
) == 0)
9398 /* the library name is the same as the argument of the '-l' option */
9399 int tcc_add_library(TCCState
*s
, const char *libraryname
)
9405 /* first we look for the dynamic library if not static linking */
9406 if (!s
->static_link
) {
9407 snprintf(buf
, sizeof(buf
), "lib%s.so", libraryname
);
9408 /* if we output to memory, then we simply we dlopen(). */
9409 if (s
->output_type
== TCC_OUTPUT_MEMORY
) {
9410 /* Since the libc is already loaded, we don't need to load it again */
9411 if (!strcmp(libraryname
, "c"))
9413 h
= dlopen(buf
, RTLD_GLOBAL
| RTLD_LAZY
);
9417 if (tcc_add_dll(s
, buf
, 0) == 0)
9422 /* then we look for the static library */
9423 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
9424 snprintf(buf
, sizeof(buf
), "%s/lib%s.a",
9425 s
->library_paths
[i
], libraryname
);
9426 if (tcc_add_file_internal(s
, buf
, 0) == 0)
9432 int tcc_add_symbol(TCCState
*s
, const char *name
, unsigned long val
)
9434 add_elf_sym(symtab_section
, val
, 0,
9435 ELF32_ST_INFO(STB_GLOBAL
, STT_NOTYPE
),
9440 int tcc_set_output_type(TCCState
*s
, int output_type
)
9444 s
->output_type
= output_type
;
9447 /* default include paths */
9448 /* XXX: reverse order needed if -isystem support */
9449 tcc_add_sysinclude_path(s
, "/usr/local/include");
9450 tcc_add_sysinclude_path(s
, "/usr/include");
9451 snprintf(buf
, sizeof(buf
), "%s/include", tcc_lib_path
);
9452 tcc_add_sysinclude_path(s
, buf
);
9455 /* if bound checking, then add corresponding sections */
9456 #ifdef CONFIG_TCC_BCHECK
9457 if (do_bounds_check
) {
9459 tcc_define_symbol(s
, "__BOUNDS_CHECKING_ON", NULL
);
9460 /* create bounds sections */
9461 bounds_section
= new_section(s
, ".bounds",
9462 SHT_PROGBITS
, SHF_ALLOC
);
9463 lbounds_section
= new_section(s
, ".lbounds",
9464 SHT_PROGBITS
, SHF_ALLOC
);
9468 /* add debug sections */
9471 stab_section
= new_section(s
, ".stab", SHT_PROGBITS
, 0);
9472 stab_section
->sh_entsize
= sizeof(Stab_Sym
);
9473 stabstr_section
= new_section(s
, ".stabstr", SHT_STRTAB
, 0);
9474 put_elf_str(stabstr_section
, "");
9475 stab_section
->link
= stabstr_section
;
9476 /* put first entry */
9477 put_stabs("", 0, 0, 0, 0);
9480 /* add libc crt1/crti objects */
9481 if (output_type
== TCC_OUTPUT_EXE
||
9482 output_type
== TCC_OUTPUT_DLL
) {
9483 if (output_type
!= TCC_OUTPUT_DLL
)
9484 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crt1.o");
9485 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crti.o");
9490 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
9492 typedef struct WarningDef
{
9498 static const WarningDef warning_defs
[] = {
9499 { offsetof(TCCState
, warn_unsupported
), 0, "unsupported" },
9500 { offsetof(TCCState
, warn_write_strings
), 0, "write-strings" },
9501 { offsetof(TCCState
, warn_error
), 0, "error" },
9504 /* set/reset a warning */
9505 int tcc_set_warning(TCCState
*s
, const char *warning_name
, int value
)
9508 const WarningDef
*p
;
9509 if (!strcmp(warning_name
, "all")) {
9510 for(i
= 0, p
= warning_defs
; i
< countof(warning_defs
); i
++, p
++) {
9511 if (p
->flags
& WD_ALL
)
9512 *(int *)((uint8_t *)s
+ p
->offset
) = 1;
9515 for(i
= 0, p
= warning_defs
; i
< countof(warning_defs
); i
++, p
++) {
9516 if (!strcmp(warning_name
, p
->name
))
9521 *(int *)((uint8_t *)s
+ p
->offset
) = value
;
9527 #if !defined(LIBTCC)
9529 /* extract the basename of a file */
9530 static const char *tcc_basename(const char *name
)
9533 p
= strrchr(name
, '/');
9536 p
= strrchr(name
, '\\');
9545 static int64_t getclock_us(void)
9550 return (tb
.time
* 1000LL + tb
.millitm
) * 1000LL;
9553 gettimeofday(&tv
, NULL
);
9554 return tv
.tv_sec
* 1000000LL + tv
.tv_usec
;
9560 printf("tcc version " TCC_VERSION
" - Tiny C Compiler - Copyright (C) 2001-2003 Fabrice Bellard\n"
9561 "usage: tcc [-v] [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"
9562 " [-Wwarn] [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-static]\n"
9563 " [infile1 infile2...] [-run infile args...]\n"
9565 "General options:\n"
9566 " -v display current version\n"
9567 " -c compile only - generate an object file\n"
9568 " -o outfile set output filename\n"
9569 " -Bdir set tcc internal library path\n"
9570 " -bench output compilation statistics\n"
9571 " -run run compiled source\n"
9572 " -Wwarning set or reset (with 'no-' prefix) 'warning'\n"
9573 "Preprocessor options:\n"
9574 " -Idir add include path 'dir'\n"
9575 " -Dsym[=val] define 'sym' with value 'val'\n"
9576 " -Usym undefine 'sym'\n"
9578 " -Ldir add library path 'dir'\n"
9579 " -llib link with dynamic or static library 'lib'\n"
9580 " -shared generate a shared library\n"
9581 " -static static linking\n"
9582 " -r relocatable output\n"
9583 "Debugger options:\n"
9584 " -g generate runtime debug info\n"
9585 #ifdef CONFIG_TCC_BCHECK
9586 " -b compile with built-in memory and bounds checker (implies -g)\n"
9588 " -bt N show N callers in stack traces\n"
9592 #define TCC_OPTION_HAS_ARG 0x0001
9593 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
9595 typedef struct TCCOption
{
9622 TCC_OPTION_nostdinc
,
9623 TCC_OPTION_print_search_dirs
,
9624 TCC_OPTION_rdynamic
,
9629 static const TCCOption tcc_options
[] = {
9630 { "h", TCC_OPTION_HELP
, 0 },
9631 { "?", TCC_OPTION_HELP
, 0 },
9632 { "I", TCC_OPTION_I
, TCC_OPTION_HAS_ARG
},
9633 { "D", TCC_OPTION_D
, TCC_OPTION_HAS_ARG
},
9634 { "U", TCC_OPTION_U
, TCC_OPTION_HAS_ARG
},
9635 { "L", TCC_OPTION_L
, TCC_OPTION_HAS_ARG
},
9636 { "B", TCC_OPTION_B
, TCC_OPTION_HAS_ARG
},
9637 { "l", TCC_OPTION_l
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9638 { "bench", TCC_OPTION_bench
, 0 },
9639 { "bt", TCC_OPTION_bt
, TCC_OPTION_HAS_ARG
},
9640 #ifdef CONFIG_TCC_BCHECK
9641 { "b", TCC_OPTION_b
, 0 },
9643 { "g", TCC_OPTION_g
, 0 },
9644 { "c", TCC_OPTION_c
, 0 },
9645 { "static", TCC_OPTION_static
, 0 },
9646 { "shared", TCC_OPTION_shared
, 0 },
9647 { "o", TCC_OPTION_o
, TCC_OPTION_HAS_ARG
},
9648 { "run", TCC_OPTION_run
, 0 },
9649 { "rdynamic", TCC_OPTION_rdynamic
, 0 }, /* currently ignored */
9650 { "r", TCC_OPTION_r
, 0 },
9651 { "W", TCC_OPTION_W
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9652 { "O", TCC_OPTION_O
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9653 { "m", TCC_OPTION_m
, TCC_OPTION_HAS_ARG
},
9654 { "f", TCC_OPTION_f
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9655 { "nostdinc", TCC_OPTION_nostdinc
, 0 },
9656 { "print-search-dirs", TCC_OPTION_print_search_dirs
, 0 },
9657 { "v", TCC_OPTION_v
, 0 },
9661 int main(int argc
, char **argv
)
9664 int optind
, output_type
, multiple_files
, i
, reloc_output
;
9667 int nb_files
, nb_libraries
, nb_objfiles
, dminus
, ret
;
9668 char objfilename
[1024];
9669 int64_t start_time
= 0;
9670 const TCCOption
*popt
;
9671 const char *optarg
, *p1
, *r1
, *outfile
;
9672 int print_search_dirs
;
9675 output_type
= TCC_OUTPUT_EXE
;
9685 print_search_dirs
= 0;
9687 if (optind
>= argc
) {
9688 if (nb_files
== 0 && !print_search_dirs
)
9695 /* add a new file */
9696 dynarray_add((void ***)&files
, &nb_files
, r
);
9697 if (!multiple_files
) {
9699 /* argv[0] will be this file */
9703 /* find option in table (match only the first chars */
9708 error("invalid option -- '%s'", r
);
9721 if (popt
->flags
& TCC_OPTION_HAS_ARG
) {
9722 if (*r1
!= '\0' || (popt
->flags
& TCC_OPTION_NOSEP
)) {
9726 error("argument to '%s' is missing", r
);
9727 optarg
= argv
[optind
++];
9735 switch(popt
->index
) {
9736 case TCC_OPTION_HELP
:
9741 if (tcc_add_include_path(s
, optarg
) < 0)
9742 error("too many include paths");
9747 sym
= (char *)optarg
;
9748 value
= strchr(sym
, '=');
9753 tcc_define_symbol(s
, sym
, value
);
9757 tcc_undefine_symbol(s
, optarg
);
9760 tcc_add_library_path(s
, optarg
);
9763 /* set tcc utilities path (mainly for tcc development) */
9764 tcc_lib_path
= optarg
;
9767 dynarray_add((void ***)&files
, &nb_files
, r
);
9770 case TCC_OPTION_bench
:
9774 num_callers
= atoi(optarg
);
9776 #ifdef CONFIG_TCC_BCHECK
9778 do_bounds_check
= 1;
9787 output_type
= TCC_OUTPUT_OBJ
;
9789 case TCC_OPTION_static
:
9792 case TCC_OPTION_shared
:
9793 output_type
= TCC_OUTPUT_DLL
;
9800 /* generate a .o merging several output files */
9802 output_type
= TCC_OUTPUT_OBJ
;
9804 case TCC_OPTION_nostdinc
:
9807 case TCC_OPTION_print_search_dirs
:
9808 print_search_dirs
= 1;
9810 case TCC_OPTION_run
:
9812 output_type
= TCC_OUTPUT_MEMORY
;
9815 printf("tcc version %s\n", TCC_VERSION
);
9819 const char *p
= optarg
;
9822 if (p
[0] == 'n' && p
[1] == 'o' && p
[2] == '-') {
9826 if (tcc_set_warning(s
, p
, value
) < 0 && s
->warn_unsupported
)
9827 goto unsupported_option
;
9831 if (s
->warn_unsupported
) {
9833 warning("unsupported option '%s'", r
);
9839 if (print_search_dirs
) {
9840 /* enough for Linux kernel */
9841 printf("install: %s/\n", tcc_lib_path
);
9845 nb_objfiles
= nb_files
- nb_libraries
;
9847 /* if outfile provided without other options, we output an
9849 if (outfile
&& output_type
== TCC_OUTPUT_MEMORY
)
9850 output_type
= TCC_OUTPUT_EXE
;
9852 /* check -c consistency : only single file handled. XXX: checks file type */
9853 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
9854 /* accepts only a single input file */
9855 if (nb_objfiles
!= 1)
9856 error("cannot specify multiple files with -c");
9857 if (nb_libraries
!= 0)
9858 error("cannot specify libraries with -c");
9861 /* compute default outfile name */
9862 if (output_type
!= TCC_OUTPUT_MEMORY
&& !outfile
) {
9863 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
9866 pstrcpy(objfilename
, sizeof(objfilename
) - 1,
9867 tcc_basename(files
[0]));
9868 /* add .o extension */
9869 ext
= strrchr(objfilename
, '.');
9871 goto default_outfile
;
9872 strcpy(ext
+ 1, "o");
9875 pstrcpy(objfilename
, sizeof(objfilename
), "a.out");
9877 outfile
= objfilename
;
9881 start_time
= getclock_us();
9884 tcc_set_output_type(s
, output_type
);
9886 /* compile or add each files or library */
9887 for(i
= 0;i
< nb_files
; i
++) {
9888 const char *filename
;
9890 filename
= files
[i
];
9891 if (filename
[0] == '-') {
9892 if (tcc_add_library(s
, filename
+ 2) < 0)
9893 error("cannot find %s", filename
);
9895 if (tcc_add_file(s
, filename
) < 0) {
9902 /* free all files */
9907 total_time
= (double)(getclock_us() - start_time
) / 1000000.0;
9908 if (total_time
< 0.001)
9910 if (total_bytes
< 1)
9912 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
9913 tok_ident
- TOK_IDENT
, total_lines
, total_bytes
,
9914 total_time
, (int)(total_lines
/ total_time
),
9915 total_bytes
/ total_time
/ 1000000.0);
9918 if (s
->output_type
!= TCC_OUTPUT_MEMORY
) {
9919 tcc_output_file(s
, outfile
);
9922 ret
= tcc_run(s
, argc
- optind
, argv
+ optind
);
9925 /* XXX: cannot do it with bound checking because of the malloc hooks */
9926 if (!do_bounds_check
)
9931 printf("memory: %d bytes, max = %d bytes\n", mem_cur_size
, mem_max_size
);