2 * TCC - Tiny C Compiler
4 * Copyright (c) 2001, 2002, 2003 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
36 #include <sys/timeb.h>
40 #include <sys/ucontext.h>
44 #ifndef CONFIG_TCC_STATIC
52 /* preprocessor debug */
54 /* include file debug */
62 /* target selection */
63 //#define TCC_TARGET_I386 /* i386 code generator */
64 //#define TCC_TARGET_ARM /* ARMv4 code generator */
65 //#define TCC_TARGET_C67 /* TMS320C67xx code generator */
67 /* default target is I386 */
68 #if !defined(TCC_TARGET_I386) && !defined(TCC_TARGET_ARM) && \
69 !defined(TCC_TARGET_C67)
70 #define TCC_TARGET_I386
73 #if !defined(WIN32) && !defined(TCC_UCLIBC) && !defined(TCC_TARGET_ARM) && \
74 !defined(TCC_TARGET_C67)
75 #define CONFIG_TCC_BCHECK /* enable bound checking code */
78 /* define it to include assembler support */
79 #if !defined(TCC_TARGET_ARM) && !defined(TCC_TARGET_C67)
80 #define CONFIG_TCC_ASM
83 /* object format selection */
84 #if defined(TCC_TARGET_C67)
85 #define TCC_TARGET_COFF
96 /* path to find crt1.o, crti.o and crtn.o. Only needed when generating
97 executables or dlls */
98 #define CONFIG_TCC_CRT_PREFIX "/usr/lib"
100 #define INCLUDE_STACK_SIZE 32
101 #define IFDEF_STACK_SIZE 64
102 #define VSTACK_SIZE 64
103 #define STRING_MAX_SIZE 1024
105 #define TOK_HASH_SIZE 2048 /* must be a power of two */
106 #define TOK_ALLOC_INCR 512 /* must be a power of two */
107 #define TOK_STR_ALLOC_INCR_BITS 6
108 #define TOK_STR_ALLOC_INCR (1 << TOK_STR_ALLOC_INCR_BITS)
109 #define TOK_MAX_SIZE 4 /* token max size in int unit when stored in string */
111 /* token symbol management */
112 typedef struct TokenSym
{
113 struct TokenSym
*hash_next
;
114 struct Sym
*sym_define
; /* direct pointer to define */
115 struct Sym
*sym_label
; /* direct pointer to label */
116 struct Sym
*sym_struct
; /* direct pointer to structure */
117 struct Sym
*sym_identifier
; /* direct pointer to identifier */
118 int tok
; /* token number */
123 typedef struct CString
{
124 int size
; /* size in bytes */
125 void *data
; /* either 'char *' or 'int *' */
127 void *data_allocated
; /* if non NULL, data has been malloced */
130 /* type definition */
131 typedef struct CType
{
137 typedef union CValue
{
143 unsigned int ul
; /* address (should be unsigned long on 64 bit cpu) */
145 unsigned long long ull
;
146 struct CString
*cstr
;
152 typedef struct SValue
{
153 CType type
; /* type */
154 unsigned short r
; /* register + flags */
155 unsigned short r2
; /* second register, used for 'long long'
156 type. If not used, set to VT_CONST */
157 CValue c
; /* constant, if VT_CONST */
158 struct Sym
*sym
; /* symbol, if (VT_SYM | VT_CONST) */
161 /* symbol management */
163 int v
; /* symbol token */
164 int r
; /* associated register */
165 int c
; /* associated number */
166 CType type
; /* associated type */
167 struct Sym
*next
; /* next related symbol */
168 struct Sym
*prev
; /* prev symbol in stack */
169 struct Sym
*prev_tok
; /* previous symbol for this token */
172 /* section definition */
173 /* XXX: use directly ELF structure for parameters ? */
174 /* special flag to indicate that the section should not be linked to
176 #define SHF_PRIVATE 0x80000000
178 typedef struct Section
{
179 unsigned long data_offset
; /* current data offset */
180 unsigned char *data
; /* section data */
181 unsigned long data_allocated
; /* used for realloc() handling */
182 int sh_name
; /* elf section name (only used during output) */
183 int sh_num
; /* elf section number */
184 int sh_type
; /* elf section type */
185 int sh_flags
; /* elf section flags */
186 int sh_info
; /* elf section info */
187 int sh_addralign
; /* elf section alignment */
188 int sh_entsize
; /* elf entry size */
189 unsigned long sh_size
; /* section size (only used during output) */
190 unsigned long sh_addr
; /* address at which the section is relocated */
191 unsigned long sh_offset
; /* address at which the section is relocated */
192 int nb_hashed_syms
; /* used to resize the hash table */
193 struct Section
*link
; /* link to another section */
194 struct Section
*reloc
; /* corresponding section for relocation, if any */
195 struct Section
*hash
; /* hash table for symbols */
196 struct Section
*next
;
197 char name
[1]; /* section name */
200 typedef struct DLLReference
{
205 /* GNUC attribute definition */
206 typedef struct AttributeDef
{
209 unsigned char func_call
; /* FUNC_CDECL or FUNC_STDCALL */
212 #define SYM_STRUCT 0x40000000 /* struct/union/enum symbol space */
213 #define SYM_FIELD 0x20000000 /* struct/union field symbol space */
214 #define SYM_FIRST_ANOM (1 << (31 - VT_STRUCT_SHIFT)) /* first anonymous sym */
216 /* stored in 'Sym.c' field */
217 #define FUNC_NEW 1 /* ansi function prototype */
218 #define FUNC_OLD 2 /* old function prototype */
219 #define FUNC_ELLIPSIS 3 /* ansi function prototype with ... */
221 /* stored in 'Sym.r' field */
222 #define FUNC_CDECL 0 /* standard c call */
223 #define FUNC_STDCALL 1 /* pascal c call */
225 /* field 'Sym.t' for macros */
226 #define MACRO_OBJ 0 /* object like macro */
227 #define MACRO_FUNC 1 /* function like macro */
229 /* field 'Sym.r' for C labels */
230 #define LABEL_DEFINED 0 /* label is defined */
231 #define LABEL_FORWARD 1 /* label is forward defined */
232 #define LABEL_DECLARED 2 /* label is declared but never used */
234 /* type_decl() types */
235 #define TYPE_ABSTRACT 1 /* type without variable */
236 #define TYPE_DIRECT 2 /* type with variable */
238 #define IO_BUF_SIZE 8192
240 typedef struct BufferedFile
{
244 int line_num
; /* current line number - here to simplify code */
245 int ifndef_macro
; /* #ifndef macro / #endif search */
246 int ifndef_macro_saved
; /* saved ifndef_macro */
247 int *ifdef_stack_ptr
; /* ifdef_stack value at the start of the file */
248 char inc_type
; /* type of include */
249 char inc_filename
[512]; /* filename specified by the user */
250 char filename
[1024]; /* current filename - here to simplify code */
251 unsigned char buffer
[IO_BUF_SIZE
+ 1]; /* extra size for CH_EOB char */
254 #define CH_EOB '\\' /* end of buffer or '\0' char in file */
255 #define CH_EOF (-1) /* end of file */
257 /* parsing state (used to save parser state to reparse part of the
258 source several times) */
259 typedef struct ParseState
{
266 /* used to record tokens */
267 typedef struct TokenString
{
274 /* include file cache, used to find files faster and also to eliminate
275 inclusion if the include file is protected by #ifndef ... #endif */
276 typedef struct CachedInclude
{
278 char type
; /* '"' or '>' to give include type */
279 char filename
[1]; /* path specified in #include */
283 static struct BufferedFile
*file
;
286 static CString tokcstr
; /* current parsed string, if any */
287 /* additional informations about token */
288 static int tok_flags
;
289 #define TOK_FLAG_BOL 0x0001 /* beginning of line before */
290 #define TOK_FLAG_BOF 0x0002 /* beginning of file before */
291 #define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */
293 static int *macro_ptr
, *macro_ptr_allocated
;
294 static int *unget_saved_macro_ptr
;
295 static int unget_saved_buffer
[TOK_MAX_SIZE
+ 1];
296 static int unget_buffer_enabled
;
297 static int parse_flags
;
298 #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
299 #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
300 #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
301 token. line feed is also
304 static Section
*text_section
, *data_section
, *bss_section
; /* predefined sections */
305 static Section
*cur_text_section
; /* current section where function code is
307 /* bound check related sections */
308 static Section
*bounds_section
; /* contains global data bound description */
309 static Section
*lbounds_section
; /* contains local data bound description */
310 /* symbol sections */
311 static Section
*symtab_section
, *strtab_section
;
314 static Section
*stab_section
, *stabstr_section
;
316 /* loc : local variable index
317 ind : output code index
319 anon_sym: anonymous symbol index
321 static int rsym
, anon_sym
, ind
, loc
;
322 /* expression generation modifiers */
323 static int const_wanted
; /* true if constant wanted */
324 static int nocode_wanted
; /* true if no code generation wanted for an expression */
325 static int global_expr
; /* true if compound literals must be allocated
326 globally (used during initializers parsing */
327 static CType func_vt
; /* current function return type (used by return
330 static int last_line_num
, last_ind
, func_ind
; /* debug last line number and pc */
331 static int tok_ident
;
332 static TokenSym
**table_ident
;
333 static TokenSym
*hash_ident
[TOK_HASH_SIZE
];
334 static char token_buf
[STRING_MAX_SIZE
+ 1];
335 static char *funcname
;
336 static Sym
*global_stack
, *local_stack
;
337 static Sym
*define_stack
;
338 static Sym
*global_label_stack
, *local_label_stack
;
340 static SValue vstack
[VSTACK_SIZE
], *vtop
;
341 /* some predefined types */
342 static CType char_pointer_type
, func_old_type
, int_type
;
343 /* true if isid(c) || isnum(c) */
344 static unsigned char isidnum_table
[256];
346 /* compile with debug symbol (and use them if error during execution) */
347 static int do_debug
= 0;
349 /* compile with built-in memory and bounds checker */
350 static int do_bounds_check
= 0;
352 /* display benchmark infos */
354 static int do_bench
= 0;
356 static int total_lines
;
357 static int total_bytes
;
359 /* use GNU C extensions */
360 static int gnu_ext
= 1;
362 /* use Tiny C extensions */
363 static int tcc_ext
= 1;
365 /* max number of callers shown if error */
366 static int num_callers
= 6;
367 static const char **rt_bound_error_msg
;
369 /* XXX: get rid of this ASAP */
370 static struct TCCState
*tcc_state
;
372 /* give the path of the tcc libraries */
373 static const char *tcc_lib_path
= CONFIG_TCC_LIBDIR
"/tcc";
378 BufferedFile
**include_stack_ptr
;
379 int *ifdef_stack_ptr
;
381 /* include file handling */
382 char **include_paths
;
383 int nb_include_paths
;
384 char **sysinclude_paths
;
385 int nb_sysinclude_paths
;
386 CachedInclude
**cached_includes
;
387 int nb_cached_includes
;
389 char **library_paths
;
390 int nb_library_paths
;
392 /* array of all loaded dlls (including those referenced by loaded
394 DLLReference
**loaded_dlls
;
399 int nb_sections
; /* number of sections, including first dummy section */
404 unsigned long *got_offsets
;
406 /* give the correspondance from symtab indexes to dynsym indexes */
407 int *symtab_to_dynsym
;
409 /* temporary dynamic symbol sections (for dll loading) */
410 Section
*dynsymtab_section
;
411 /* exported dynamic symbol section */
414 int nostdinc
; /* if true, no standard headers are added */
415 int nostdlib
; /* if true, no standard libraries are added */
417 /* if true, static linking is performed */
420 /* if true, all symbols are exported */
423 /* if true, only link in referenced objects from archive */
426 /* C language options */
427 int char_is_unsigned
;
429 /* warning switches */
430 int warn_write_strings
;
431 int warn_unsupported
;
434 int warn_implicit_function_declaration
;
438 void (*error_func
)(void *opaque
, const char *msg
);
439 int error_set_jmp_enabled
;
440 jmp_buf error_jmp_buf
;
443 /* tiny assembler state */
446 /* see include_stack_ptr */
447 BufferedFile
*include_stack
[INCLUDE_STACK_SIZE
];
449 /* see ifdef_stack_ptr */
450 int ifdef_stack
[IFDEF_STACK_SIZE
];
453 /* The current value can be: */
454 #define VT_VALMASK 0x00ff
455 #define VT_CONST 0x00f0 /* constant in vc
456 (must be first non register value) */
457 #define VT_LLOCAL 0x00f1 /* lvalue, offset on stack */
458 #define VT_LOCAL 0x00f2 /* offset on stack */
459 #define VT_CMP 0x00f3 /* the value is stored in processor flags (in vc) */
460 #define VT_JMP 0x00f4 /* value is the consequence of jmp true (even) */
461 #define VT_JMPI 0x00f5 /* value is the consequence of jmp false (odd) */
462 #define VT_LVAL 0x0100 /* var is an lvalue */
463 #define VT_SYM 0x0200 /* a symbol value is added */
464 #define VT_MUSTCAST 0x0400 /* value must be casted to be correct (used for
465 char/short stored in integer registers) */
466 #define VT_MUSTBOUND 0x0800 /* bound checking must be done before
467 dereferencing value */
468 #define VT_BOUNDED 0x8000 /* value is bounded. The address of the
469 bounding function call point is in vc */
470 #define VT_LVAL_BYTE 0x1000 /* lvalue is a byte */
471 #define VT_LVAL_SHORT 0x2000 /* lvalue is a short */
472 #define VT_LVAL_UNSIGNED 0x4000 /* lvalue is unsigned */
473 #define VT_LVAL_TYPE (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
476 #define VT_INT 0 /* integer type */
477 #define VT_BYTE 1 /* signed byte type */
478 #define VT_SHORT 2 /* short type */
479 #define VT_VOID 3 /* void type */
480 #define VT_PTR 4 /* pointer */
481 #define VT_ENUM 5 /* enum definition */
482 #define VT_FUNC 6 /* function type */
483 #define VT_STRUCT 7 /* struct/union definition */
484 #define VT_FLOAT 8 /* IEEE float */
485 #define VT_DOUBLE 9 /* IEEE double */
486 #define VT_LDOUBLE 10 /* IEEE long double */
487 #define VT_BOOL 11 /* ISOC99 boolean type */
488 #define VT_LLONG 12 /* 64 bit integer */
489 #define VT_LONG 13 /* long integer (NEVER USED as type, only
491 #define VT_BTYPE 0x000f /* mask for basic type */
492 #define VT_UNSIGNED 0x0010 /* unsigned type */
493 #define VT_ARRAY 0x0020 /* array type (also has VT_PTR) */
494 #define VT_BITFIELD 0x0040 /* bitfield modifier */
495 #define VT_CONSTANT 0x0800 /* const modifier */
496 #define VT_VOLATILE 0x1000 /* volatile modifier */
497 #define VT_SIGNED 0x2000 /* signed type */
500 #define VT_EXTERN 0x00000080 /* extern definition */
501 #define VT_STATIC 0x00000100 /* static variable */
502 #define VT_TYPEDEF 0x00000200 /* typedef definition */
503 #define VT_INLINE 0x00000400 /* inline definition */
505 #define VT_STRUCT_SHIFT 16 /* shift for bitfield shift values */
507 /* type mask (except storage) */
508 #define VT_STORAGE (VT_EXTERN | VT_STATIC | VT_TYPEDEF | VT_INLINE)
509 #define VT_TYPE (~(VT_STORAGE))
513 /* warning: the following compare tokens depend on i386 asm code */
525 #define TOK_LAND 0xa0
529 #define TOK_MID 0xa3 /* inc/dec, to void constant */
531 #define TOK_UDIV 0xb0 /* unsigned division */
532 #define TOK_UMOD 0xb1 /* unsigned modulo */
533 #define TOK_PDIV 0xb2 /* fast division with undefined rounding for pointers */
534 #define TOK_CINT 0xb3 /* number in tokc */
535 #define TOK_CCHAR 0xb4 /* char constant in tokc */
536 #define TOK_STR 0xb5 /* pointer to string in tokc */
537 #define TOK_TWOSHARPS 0xb6 /* ## preprocessing token */
538 #define TOK_LCHAR 0xb7
539 #define TOK_LSTR 0xb8
540 #define TOK_CFLOAT 0xb9 /* float constant */
541 #define TOK_LINENUM 0xba /* line number info */
542 #define TOK_CDOUBLE 0xc0 /* double constant */
543 #define TOK_CLDOUBLE 0xc1 /* long double constant */
544 #define TOK_UMULL 0xc2 /* unsigned 32x32 -> 64 mul */
545 #define TOK_ADDC1 0xc3 /* add with carry generation */
546 #define TOK_ADDC2 0xc4 /* add with carry use */
547 #define TOK_SUBC1 0xc5 /* add with carry generation */
548 #define TOK_SUBC2 0xc6 /* add with carry use */
549 #define TOK_CUINT 0xc8 /* unsigned int constant */
550 #define TOK_CLLONG 0xc9 /* long long constant */
551 #define TOK_CULLONG 0xca /* unsigned long long constant */
552 #define TOK_ARROW 0xcb
553 #define TOK_DOTS 0xcc /* three dots */
554 #define TOK_SHR 0xcd /* unsigned shift right */
555 #define TOK_PPNUM 0xce /* preprocessor number */
557 #define TOK_SHL 0x01 /* shift left */
558 #define TOK_SAR 0x02 /* signed shift right */
560 /* assignement operators : normal operator or 0x80 */
561 #define TOK_A_MOD 0xa5
562 #define TOK_A_AND 0xa6
563 #define TOK_A_MUL 0xaa
564 #define TOK_A_ADD 0xab
565 #define TOK_A_SUB 0xad
566 #define TOK_A_DIV 0xaf
567 #define TOK_A_XOR 0xde
568 #define TOK_A_OR 0xfc
569 #define TOK_A_SHL 0x81
570 #define TOK_A_SAR 0x82
573 #define offsetof(type, field) ((size_t) &((type *)0)->field)
577 #define countof(tab) (sizeof(tab) / sizeof((tab)[0]))
580 /* WARNING: the content of this string encodes token numbers */
581 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";
583 #define TOK_EOF (-1) /* end of file */
584 #define TOK_LINEFEED 10 /* line feed */
586 /* all identificators and strings have token above that */
587 #define TOK_IDENT 256
589 /* only used for i386 asm opcodes definitions */
590 #define DEF_ASM(x) DEF(TOK_ASM_ ## x, #x)
593 DEF(TOK_ASM_ ## x ## b, #x "b") \
594 DEF(TOK_ASM_ ## x ## w, #x "w") \
595 DEF(TOK_ASM_ ## x ## l, #x "l") \
596 DEF(TOK_ASM_ ## x, #x)
599 DEF(TOK_ASM_ ## x ## w, #x "w") \
600 DEF(TOK_ASM_ ## x ## l, #x "l") \
601 DEF(TOK_ASM_ ## x, #x)
604 DEF(TOK_ASM_ ## f ## x ## s, "f" #x "s") \
605 DEF(TOK_ASM_ ## fi ## x ## l, "fi" #x "l") \
606 DEF(TOK_ASM_ ## f ## x ## l, "f" #x "l") \
607 DEF(TOK_ASM_ ## fi ## x ## s, "fi" #x "s")
610 DEF(TOK_ASM_ ## f ## x, "f" #x ) \
611 DEF(TOK_ASM_ ## f ## x ## p, "f" #x "p") \
614 #define DEF_ASMTEST(x) \
646 #define TOK_ASM_int TOK_INT
649 TOK_LAST
= TOK_IDENT
- 1,
650 #define DEF(id, str) id,
655 static const char tcc_keywords
[] =
656 #define DEF(id, str) str "\0"
661 #define TOK_UIDENT TOK_DEFINE
664 #define snprintf _snprintf
665 #define vsnprintf _vsnprintf
668 #if defined(WIN32) || defined(TCC_UCLIBC) || defined(__FreeBSD__)
669 /* currently incorrect */
670 long double strtold(const char *nptr
, char **endptr
)
672 return (long double)strtod(nptr
, endptr
);
674 float strtof(const char *nptr
, char **endptr
)
676 return (float)strtod(nptr
, endptr
);
679 /* XXX: need to define this to use them in non ISOC99 context */
680 extern float strtof (const char *__nptr
, char **__endptr
);
681 extern long double strtold (const char *__nptr
, char **__endptr
);
684 static char *pstrcpy(char *buf
, int buf_size
, const char *s
);
685 static char *pstrcat(char *buf
, int buf_size
, const char *s
);
687 static void next(void);
688 static void next_nomacro(void);
689 static void parse_expr_type(CType
*type
);
690 static void expr_type(CType
*type
);
691 static void unary_type(CType
*type
);
692 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
693 int case_reg
, int is_expr
);
694 static int expr_const(void);
695 static void expr_eq(void);
696 static void gexpr(void);
697 static void decl(int l
);
698 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
699 int first
, int size_only
);
700 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
701 int has_init
, int v
, int scope
);
703 void gv2(int rc1
, int rc2
);
704 void move_reg(int r
, int s
);
705 void save_regs(int n
);
706 void save_reg(int r
);
711 int get_reg_ex(int rc
,int rc2
);
713 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
714 const int *macro_str
, int can_read_stream
);
715 int save_reg_forced(int r
);
717 void force_charshort_cast(int t
);
718 static void gen_cast(CType
*type
);
720 static Sym
*sym_find(int v
);
721 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
);
724 static int type_size(CType
*type
, int *a
);
725 static inline CType
*pointed_type(CType
*type
);
726 static int pointed_size(CType
*type
);
727 static int lvalue_type(int t
);
728 static int parse_btype(CType
*type
, AttributeDef
*ad
);
729 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
);
730 static int is_compatible_types(CType
*type1
, CType
*type2
);
732 int ieee_finite(double d
);
733 void error(const char *fmt
, ...);
737 void lexpand_nr(void);
738 static void vpush_global_sym(CType
*type
, int v
);
739 void vset(CType
*type
, int r
, int v
);
740 void type_to_str(char *buf
, int buf_size
,
741 CType
*type
, const char *varstr
);
742 char *get_tok_str(int v
, CValue
*cv
);
743 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
744 unsigned long offset
, unsigned long size
);
745 static Sym
*external_global_sym(int v
, CType
*type
, int r
);
747 /* section generation */
748 static void section_realloc(Section
*sec
, unsigned long new_size
);
749 static void *section_ptr_add(Section
*sec
, unsigned long size
);
750 static void put_extern_sym(Sym
*sym
, Section
*section
,
751 unsigned long value
, unsigned long size
);
752 static void greloc(Section
*s
, Sym
*sym
, unsigned long addr
, int type
);
753 static int put_elf_str(Section
*s
, const char *sym
);
754 static int put_elf_sym(Section
*s
,
755 unsigned long value
, unsigned long size
,
756 int info
, int other
, int shndx
, const char *name
);
757 static int add_elf_sym(Section
*s
, unsigned long value
, unsigned long size
,
758 int info
, int sh_num
, const char *name
);
759 static void put_elf_reloc(Section
*symtab
, Section
*s
, unsigned long offset
,
760 int type
, int symbol
);
761 static void put_stabs(const char *str
, int type
, int other
, int desc
,
762 unsigned long value
);
763 static void put_stabs_r(const char *str
, int type
, int other
, int desc
,
764 unsigned long value
, Section
*sec
, int sym_index
);
765 static void put_stabn(int type
, int other
, int desc
, int value
);
766 static void put_stabd(int type
, int other
, int desc
);
767 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
);
769 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
770 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
771 static int tcc_add_file_internal(TCCState
*s
, const char *filename
, int flags
);
774 int tcc_output_coff(TCCState
*s1
, const char *OutFile
);
778 #ifdef CONFIG_TCC_ASM
780 typedef struct ExprValue
{
785 #define MAX_ASM_OPERANDS 30
787 typedef struct ASMOperand
{
788 int id
; /* GCC 3 optionnal identifier (0 if number only supported */
790 char asm_str
[16]; /* computed asm string for operand */
791 SValue
*vt
; /* C value of the expression */
792 int ref_index
; /* if >= 0, gives reference to a output constraint */
793 int priority
; /* priority, used to assign registers */
794 int reg
; /* if >= 0, register number used for this operand */
795 int is_llong
; /* true if double register value */
798 static void asm_expr(TCCState
*s1
, ExprValue
*pe
);
799 static int asm_int_expr(TCCState
*s1
);
800 static int find_constraint(ASMOperand
*operands
, int nb_operands
,
801 const char *name
, const char **pp
);
803 static int tcc_assemble(TCCState
*s1
, int do_preprocess
);
807 static void asm_instr(void);
809 /* true if float/double/long double type */
810 static inline int is_float(int t
)
814 return bt
== VT_LDOUBLE
|| bt
== VT_DOUBLE
|| bt
== VT_FLOAT
;
817 #ifdef TCC_TARGET_I386
818 #include "i386-gen.c"
821 #ifdef TCC_TARGET_ARM
825 #ifdef TCC_TARGET_C67
829 #ifdef CONFIG_TCC_STATIC
831 #define RTLD_LAZY 0x001
832 #define RTLD_NOW 0x002
833 #define RTLD_GLOBAL 0x100
834 #define RTLD_DEFAULT NULL
836 /* dummy function for profiling */
837 void *dlopen(const char *filename
, int flag
)
842 const char *dlerror(void)
847 typedef struct TCCSyms
{
852 #define TCCSYM(a) { #a, &a, },
854 /* add the symbol you want here if no dynamic linking is done */
855 static TCCSyms tcc_syms
[] = {
863 void *dlsym(void *handle
, const char *symbol
)
867 while (p
->str
!= NULL
) {
868 if (!strcmp(p
->str
, symbol
))
877 /********************************************************/
879 /* we use our own 'finite' function to avoid potential problems with
880 non standard math libs */
881 /* XXX: endianness dependent */
882 int ieee_finite(double d
)
885 return ((unsigned)((p
[1] | 0x800fffff) + 1)) >> 31;
888 /* copy a string and truncate it. */
889 static char *pstrcpy(char *buf
, int buf_size
, const char *s
)
896 q_end
= buf
+ buf_size
- 1;
908 /* strcat and truncate. */
909 static char *pstrcat(char *buf
, int buf_size
, const char *s
)
914 pstrcpy(buf
+ len
, buf_size
- len
, s
);
918 /* memory management */
924 static inline void tcc_free(void *ptr
)
927 mem_cur_size
-= malloc_usable_size(ptr
);
932 static void *tcc_malloc(unsigned long size
)
937 error("memory full");
939 mem_cur_size
+= malloc_usable_size(ptr
);
940 if (mem_cur_size
> mem_max_size
)
941 mem_max_size
= mem_cur_size
;
946 static void *tcc_mallocz(unsigned long size
)
949 ptr
= tcc_malloc(size
);
950 memset(ptr
, 0, size
);
954 static inline void *tcc_realloc(void *ptr
, unsigned long size
)
958 mem_cur_size
-= malloc_usable_size(ptr
);
960 ptr1
= realloc(ptr
, size
);
962 /* NOTE: count not correct if alloc error, but not critical */
963 mem_cur_size
+= malloc_usable_size(ptr1
);
964 if (mem_cur_size
> mem_max_size
)
965 mem_max_size
= mem_cur_size
;
970 static char *tcc_strdup(const char *str
)
973 ptr
= tcc_malloc(strlen(str
) + 1);
978 #define free(p) use_tcc_free(p)
979 #define malloc(s) use_tcc_malloc(s)
980 #define realloc(p, s) use_tcc_realloc(p, s)
982 static void dynarray_add(void ***ptab
, int *nb_ptr
, void *data
)
989 /* every power of two we double array size */
990 if ((nb
& (nb
- 1)) == 0) {
995 pp
= tcc_realloc(pp
, nb_alloc
* sizeof(void *));
997 error("memory full");
1004 Section
*new_section(TCCState
*s1
, const char *name
, int sh_type
, int sh_flags
)
1008 sec
= tcc_mallocz(sizeof(Section
) + strlen(name
));
1009 strcpy(sec
->name
, name
);
1010 sec
->sh_type
= sh_type
;
1011 sec
->sh_flags
= sh_flags
;
1018 sec
->sh_addralign
= 4;
1021 sec
->sh_addralign
= 1;
1024 sec
->sh_addralign
= 32; /* default conservative alignment */
1028 /* only add section if not private */
1029 if (!(sh_flags
& SHF_PRIVATE
)) {
1030 sec
->sh_num
= s1
->nb_sections
;
1031 dynarray_add((void ***)&s1
->sections
, &s1
->nb_sections
, sec
);
1036 static void free_section(Section
*s
)
1042 /* realloc section and set its content to zero */
1043 static void section_realloc(Section
*sec
, unsigned long new_size
)
1046 unsigned char *data
;
1048 size
= sec
->data_allocated
;
1051 while (size
< new_size
)
1053 data
= tcc_realloc(sec
->data
, size
);
1055 error("memory full");
1056 memset(data
+ sec
->data_allocated
, 0, size
- sec
->data_allocated
);
1058 sec
->data_allocated
= size
;
1061 /* reserve at least 'size' bytes in section 'sec' from
1062 sec->data_offset. */
1063 static void *section_ptr_add(Section
*sec
, unsigned long size
)
1065 unsigned long offset
, offset1
;
1067 offset
= sec
->data_offset
;
1068 offset1
= offset
+ size
;
1069 if (offset1
> sec
->data_allocated
)
1070 section_realloc(sec
, offset1
);
1071 sec
->data_offset
= offset1
;
1072 return sec
->data
+ offset
;
1075 /* return a reference to a section, and create it if it does not
1077 Section
*find_section(TCCState
*s1
, const char *name
)
1081 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1082 sec
= s1
->sections
[i
];
1083 if (!strcmp(name
, sec
->name
))
1086 /* sections are created as PROGBITS */
1087 return new_section(s1
, name
, SHT_PROGBITS
, SHF_ALLOC
);
1090 /* update sym->c so that it points to an external symbol in section
1091 'section' with value 'value' */
1092 static void put_extern_sym(Sym
*sym
, Section
*section
,
1093 unsigned long value
, unsigned long size
)
1095 int sym_type
, sym_bind
, sh_num
, info
;
1100 sh_num
= section
->sh_num
;
1104 if ((sym
->type
.t
& VT_BTYPE
) == VT_FUNC
)
1105 sym_type
= STT_FUNC
;
1107 sym_type
= STT_OBJECT
;
1108 if (sym
->type
.t
& VT_STATIC
)
1109 sym_bind
= STB_LOCAL
;
1111 sym_bind
= STB_GLOBAL
;
1113 name
= get_tok_str(sym
->v
, NULL
);
1114 #ifdef CONFIG_TCC_BCHECK
1115 if (do_bounds_check
) {
1118 /* XXX: avoid doing that for statics ? */
1119 /* if bound checking is activated, we change some function
1120 names by adding the "__bound" prefix */
1123 /* XXX: we rely only on malloc hooks */
1135 strcpy(buf
, "__bound_");
1142 info
= ELF32_ST_INFO(sym_bind
, sym_type
);
1143 sym
->c
= add_elf_sym(symtab_section
, value
, size
, info
, sh_num
, name
);
1145 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
1146 esym
->st_value
= value
;
1147 esym
->st_size
= size
;
1148 esym
->st_shndx
= sh_num
;
1152 /* add a new relocation entry to symbol 'sym' in section 's' */
1153 static void greloc(Section
*s
, Sym
*sym
, unsigned long offset
, int type
)
1156 put_extern_sym(sym
, NULL
, 0, 0);
1157 /* now we can add ELF relocation info */
1158 put_elf_reloc(symtab_section
, s
, offset
, type
, sym
->c
);
1161 static inline int isid(int c
)
1163 return (c
>= 'a' && c
<= 'z') ||
1164 (c
>= 'A' && c
<= 'Z') ||
1168 static inline int isnum(int c
)
1170 return c
>= '0' && c
<= '9';
1173 static inline int isoct(int c
)
1175 return c
>= '0' && c
<= '7';
1178 static inline int toup(int c
)
1180 if (c
>= 'a' && c
<= 'z')
1181 return c
- 'a' + 'A';
1186 static void strcat_vprintf(char *buf
, int buf_size
, const char *fmt
, va_list ap
)
1190 vsnprintf(buf
+ len
, buf_size
- len
, fmt
, ap
);
1193 static void strcat_printf(char *buf
, int buf_size
, const char *fmt
, ...)
1197 strcat_vprintf(buf
, buf_size
, fmt
, ap
);
1201 void error1(TCCState
*s1
, int is_warning
, const char *fmt
, va_list ap
)
1208 for(f
= s1
->include_stack
; f
< s1
->include_stack_ptr
; f
++)
1209 strcat_printf(buf
, sizeof(buf
), "In file included from %s:%d:\n",
1210 (*f
)->filename
, (*f
)->line_num
);
1211 if (file
->line_num
> 0) {
1212 strcat_printf(buf
, sizeof(buf
),
1213 "%s:%d: ", file
->filename
, file
->line_num
);
1215 strcat_printf(buf
, sizeof(buf
),
1216 "%s: ", file
->filename
);
1219 strcat_printf(buf
, sizeof(buf
),
1223 strcat_printf(buf
, sizeof(buf
), "warning: ");
1224 strcat_vprintf(buf
, sizeof(buf
), fmt
, ap
);
1226 if (!s1
->error_func
) {
1227 /* default case: stderr */
1228 fprintf(stderr
, "%s\n", buf
);
1230 s1
->error_func(s1
->error_opaque
, buf
);
1232 if (!is_warning
|| s1
->warn_error
)
1237 void tcc_set_error_func(TCCState
*s
, void *error_opaque
,
1238 void (*error_func
)(void *opaque
, const char *msg
))
1240 s
->error_opaque
= error_opaque
;
1241 s
->error_func
= error_func
;
1245 /* error without aborting current compilation */
1246 void error_noabort(const char *fmt
, ...)
1248 TCCState
*s1
= tcc_state
;
1252 error1(s1
, 0, fmt
, ap
);
1256 void error(const char *fmt
, ...)
1258 TCCState
*s1
= tcc_state
;
1262 error1(s1
, 0, fmt
, ap
);
1264 /* better than nothing: in some cases, we accept to handle errors */
1265 if (s1
->error_set_jmp_enabled
) {
1266 longjmp(s1
->error_jmp_buf
, 1);
1268 /* XXX: eliminate this someday */
1273 void expect(const char *msg
)
1275 error("%s expected", msg
);
1278 void warning(const char *fmt
, ...)
1280 TCCState
*s1
= tcc_state
;
1287 error1(s1
, 1, fmt
, ap
);
1294 error("'%c' expected", c
);
1298 static void test_lvalue(void)
1300 if (!(vtop
->r
& VT_LVAL
))
1304 /* allocate a new token */
1305 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
1307 TokenSym
*ts
, **ptable
;
1310 if (tok_ident
>= SYM_FIRST_ANOM
)
1311 error("memory full");
1313 /* expand token table if needed */
1314 i
= tok_ident
- TOK_IDENT
;
1315 if ((i
% TOK_ALLOC_INCR
) == 0) {
1316 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
1318 error("memory full");
1319 table_ident
= ptable
;
1322 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
1323 table_ident
[i
] = ts
;
1324 ts
->tok
= tok_ident
++;
1325 ts
->sym_define
= NULL
;
1326 ts
->sym_label
= NULL
;
1327 ts
->sym_struct
= NULL
;
1328 ts
->sym_identifier
= NULL
;
1330 ts
->hash_next
= NULL
;
1331 memcpy(ts
->str
, str
, len
);
1332 ts
->str
[len
] = '\0';
1337 #define TOK_HASH_INIT 1
1338 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
1340 /* find a token and add it if not found */
1341 static TokenSym
*tok_alloc(const char *str
, int len
)
1343 TokenSym
*ts
, **pts
;
1349 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
1350 h
&= (TOK_HASH_SIZE
- 1);
1352 pts
= &hash_ident
[h
];
1357 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
1359 pts
= &(ts
->hash_next
);
1361 return tok_alloc_new(pts
, str
, len
);
1364 /* CString handling */
1366 static void cstr_realloc(CString
*cstr
, int new_size
)
1371 size
= cstr
->size_allocated
;
1373 size
= 8; /* no need to allocate a too small first string */
1374 while (size
< new_size
)
1376 data
= tcc_realloc(cstr
->data_allocated
, size
);
1378 error("memory full");
1379 cstr
->data_allocated
= data
;
1380 cstr
->size_allocated
= size
;
1385 static void cstr_ccat(CString
*cstr
, int ch
)
1388 size
= cstr
->size
+ 1;
1389 if (size
> cstr
->size_allocated
)
1390 cstr_realloc(cstr
, size
);
1391 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
1395 static void cstr_cat(CString
*cstr
, const char *str
)
1407 /* add a wide char */
1408 static void cstr_wccat(CString
*cstr
, int ch
)
1411 size
= cstr
->size
+ sizeof(int);
1412 if (size
> cstr
->size_allocated
)
1413 cstr_realloc(cstr
, size
);
1414 *(int *)(((unsigned char *)cstr
->data
) + size
- sizeof(int)) = ch
;
1418 static void cstr_new(CString
*cstr
)
1420 memset(cstr
, 0, sizeof(CString
));
1423 /* free string and reset it to NULL */
1424 static void cstr_free(CString
*cstr
)
1426 tcc_free(cstr
->data_allocated
);
1430 #define cstr_reset(cstr) cstr_free(cstr)
1432 static CString
*cstr_dup(CString
*cstr1
)
1437 cstr
= tcc_malloc(sizeof(CString
));
1440 cstr
->size_allocated
= size
;
1441 cstr
->data_allocated
= tcc_malloc(size
);
1442 cstr
->data
= cstr
->data_allocated
;
1443 memcpy(cstr
->data_allocated
, cstr1
->data_allocated
, size
);
1447 /* XXX: unicode ? */
1448 static void add_char(CString
*cstr
, int c
)
1450 if (c
== '\'' || c
== '\"' || c
== '\\') {
1451 /* XXX: could be more precise if char or string */
1452 cstr_ccat(cstr
, '\\');
1454 if (c
>= 32 && c
<= 126) {
1457 cstr_ccat(cstr
, '\\');
1459 cstr_ccat(cstr
, 'n');
1461 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
1462 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
1463 cstr_ccat(cstr
, '0' + (c
& 7));
1468 /* XXX: buffer overflow */
1469 /* XXX: float tokens */
1470 char *get_tok_str(int v
, CValue
*cv
)
1472 static char buf
[STRING_MAX_SIZE
+ 1];
1473 static CString cstr_buf
;
1479 /* NOTE: to go faster, we give a fixed buffer for small strings */
1480 cstr_reset(&cstr_buf
);
1481 cstr_buf
.data
= buf
;
1482 cstr_buf
.size_allocated
= sizeof(buf
);
1488 /* XXX: not quite exact, but only useful for testing */
1489 sprintf(p
, "%u", cv
->ui
);
1493 /* XXX: not quite exact, but only useful for testing */
1494 sprintf(p
, "%Lu", cv
->ull
);
1498 cstr_ccat(&cstr_buf
, '\'');
1499 add_char(&cstr_buf
, cv
->i
);
1500 cstr_ccat(&cstr_buf
, '\'');
1501 cstr_ccat(&cstr_buf
, '\0');
1505 len
= cstr
->size
- 1;
1507 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1508 cstr_ccat(&cstr_buf
, '\0');
1513 cstr_ccat(&cstr_buf
, '\"');
1515 len
= cstr
->size
- 1;
1517 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1519 len
= (cstr
->size
/ sizeof(int)) - 1;
1521 add_char(&cstr_buf
, ((int *)cstr
->data
)[i
]);
1523 cstr_ccat(&cstr_buf
, '\"');
1524 cstr_ccat(&cstr_buf
, '\0');
1533 return strcpy(p
, "<<=");
1535 return strcpy(p
, ">>=");
1537 if (v
< TOK_IDENT
) {
1538 /* search in two bytes table */
1552 } else if (v
< tok_ident
) {
1553 return table_ident
[v
- TOK_IDENT
]->str
;
1554 } else if (v
>= SYM_FIRST_ANOM
) {
1555 /* special name for anonymous symbol */
1556 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
1558 /* should never happen */
1563 return cstr_buf
.data
;
1566 /* push, without hashing */
1567 static Sym
*sym_push2(Sym
**ps
, int v
, int t
, int c
)
1570 s
= tcc_malloc(sizeof(Sym
));
1581 /* find a symbol and return its associated structure. 's' is the top
1582 of the symbol stack */
1583 static Sym
*sym_find2(Sym
*s
, int v
)
1593 /* structure lookup */
1594 static inline Sym
*struct_find(int v
)
1597 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1599 return table_ident
[v
]->sym_struct
;
1602 /* find an identifier */
1603 static inline Sym
*sym_find(int v
)
1606 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1608 return table_ident
[v
]->sym_identifier
;
1611 /* push a given symbol on the symbol stack */
1612 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
)
1621 s
= sym_push2(ps
, v
, type
->t
, c
);
1622 s
->type
.ref
= type
->ref
;
1624 /* don't record fields or anonymous symbols */
1626 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1627 /* record symbol in token array */
1628 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1630 ps
= &ts
->sym_struct
;
1632 ps
= &ts
->sym_identifier
;
1639 /* push a global identifier */
1640 static Sym
*global_identifier_push(int v
, int t
, int c
)
1643 s
= sym_push2(&global_stack
, v
, t
, c
);
1644 /* don't record anonymous symbol */
1645 if (v
< SYM_FIRST_ANOM
) {
1646 ps
= &table_ident
[v
- TOK_IDENT
]->sym_identifier
;
1647 /* modify the top most local identifier, so that
1648 sym_identifier will point to 's' when popped */
1650 ps
= &(*ps
)->prev_tok
;
1657 /* pop symbols until top reaches 'b' */
1658 static void sym_pop(Sym
**ptop
, Sym
*b
)
1668 /* remove symbol in token array */
1670 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1671 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1673 ps
= &ts
->sym_struct
;
1675 ps
= &ts
->sym_identifier
;
1686 BufferedFile
*tcc_open(TCCState
*s1
, const char *filename
)
1691 fd
= open(filename
, O_RDONLY
);
1694 bf
= tcc_malloc(sizeof(BufferedFile
));
1700 bf
->buf_ptr
= bf
->buffer
;
1701 bf
->buf_end
= bf
->buffer
;
1702 bf
->buffer
[0] = CH_EOB
; /* put eob symbol */
1703 pstrcpy(bf
->filename
, sizeof(bf
->filename
), filename
);
1705 bf
->ifndef_macro
= 0;
1706 bf
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
1707 // printf("opening '%s'\n", filename);
1711 void tcc_close(BufferedFile
*bf
)
1713 total_lines
+= bf
->line_num
;
1718 /* fill input buffer and peek next char */
1719 static int tcc_peekc_slow(BufferedFile
*bf
)
1722 /* only tries to read if really end of buffer */
1723 if (bf
->buf_ptr
>= bf
->buf_end
) {
1725 #if defined(PARSE_DEBUG)
1730 len
= read(bf
->fd
, bf
->buffer
, len
);
1737 bf
->buf_ptr
= bf
->buffer
;
1738 bf
->buf_end
= bf
->buffer
+ len
;
1739 *bf
->buf_end
= CH_EOB
;
1741 if (bf
->buf_ptr
< bf
->buf_end
) {
1742 return bf
->buf_ptr
[0];
1744 bf
->buf_ptr
= bf
->buf_end
;
1749 /* return the current character, handling end of block if necessary
1751 static int handle_eob(void)
1753 return tcc_peekc_slow(file
);
1756 /* read next char from current input file and handle end of input buffer */
1757 static inline void inp(void)
1759 ch
= *(++(file
->buf_ptr
));
1760 /* end of buffer/file handling */
1765 /* handle '\[\r]\n' */
1766 static void handle_stray(void)
1768 while (ch
== '\\') {
1773 } else if (ch
== '\r') {
1781 error("stray '\\' in program");
1786 /* skip the stray and handle the \\n case. Output an error if
1787 incorrect char after the stray */
1788 static int handle_stray1(uint8_t *p
)
1792 if (p
>= file
->buf_end
) {
1809 /* handle just the EOB case, but not stray */
1810 #define PEEKC_EOB(c, p)\
1821 /* handle the complicated stray case */
1822 #define PEEKC(c, p)\
1827 c = handle_stray1(p);\
1832 /* input with '\[\r]\n' handling. Note that this function cannot
1833 handle other characters after '\', so you cannot call it inside
1834 strings or comments */
1835 static void minp(void)
1843 /* single line C++ comments */
1844 static uint8_t *parse_line_comment(uint8_t *p
)
1852 if (c
== '\n' || c
== CH_EOF
) {
1854 } else if (c
== '\\') {
1863 } else if (c
== '\r') {
1881 static uint8_t *parse_comment(uint8_t *p
)
1887 /* fast skip loop */
1890 if (c
== '\n' || c
== '*' || c
== '\\')
1894 if (c
== '\n' || c
== '*' || c
== '\\')
1898 /* now we can handle all the cases */
1902 } else if (c
== '*') {
1908 } else if (c
== '/') {
1909 goto end_of_comment
;
1910 } else if (c
== '\\') {
1915 /* skip '\[\r]\n', otherwise just skip the stray */
1921 } else if (c
== '\r') {
1938 /* stray, eob or eof */
1943 error("unexpected end of file in comment");
1944 } else if (c
== '\\') {
1956 /* space exlcuding newline */
1957 static inline int is_space(int ch
)
1959 return ch
== ' ' || ch
== '\t' || ch
== '\v' || ch
== '\f' || ch
== '\r';
1962 static inline void skip_spaces(void)
1964 while (is_space(ch
))
1968 /* parse a string without interpreting escapes */
1969 static uint8_t *parse_pp_string(uint8_t *p
,
1970 int sep
, CString
*str
)
1978 } else if (c
== '\\') {
1983 unterminated_string
:
1984 /* XXX: indicate line number of start of string */
1985 error("missing terminating %c character", sep
);
1986 } else if (c
== '\\') {
1987 /* escape : just skip \[\r]\n */
1992 } else if (c
== '\r') {
1995 expect("'\n' after '\r'");
1998 } else if (c
== CH_EOF
) {
1999 goto unterminated_string
;
2002 cstr_ccat(str
, '\\');
2008 } else if (c
== '\n') {
2011 } else if (c
== '\r') {
2014 cstr_ccat(str
, '\r');
2030 /* skip block of text until #else, #elif or #endif. skip also pairs of
2032 void preprocess_skip(void)
2034 int a
, start_of_line
, c
;
2061 } else if (c
== '\\') {
2062 /* XXX: incorrect: should not give an error */
2063 ch
= file
->buf_ptr
[0];
2071 p
= parse_pp_string(p
, c
, NULL
);
2080 p
= parse_comment(p
);
2081 } else if (ch
== '/') {
2082 p
= parse_line_comment(p
);
2088 if (start_of_line
) {
2093 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
2095 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
2097 else if (tok
== TOK_ENDIF
)
2111 /* ParseState handling */
2113 /* XXX: currently, no include file info is stored. Thus, we cannot display
2114 accurate messages if the function or data definition spans multiple
2117 /* save current parse state in 's' */
2118 void save_parse_state(ParseState
*s
)
2120 s
->line_num
= file
->line_num
;
2121 s
->macro_ptr
= macro_ptr
;
2126 /* restore parse state from 's' */
2127 void restore_parse_state(ParseState
*s
)
2129 file
->line_num
= s
->line_num
;
2130 macro_ptr
= s
->macro_ptr
;
2135 /* return the number of additional 'ints' necessary to store the
2137 static inline int tok_ext_size(int t
)
2156 return LDOUBLE_SIZE
/ 4;
2162 /* token string handling */
2164 static inline void tok_str_new(TokenString
*s
)
2168 s
->allocated_len
= 0;
2169 s
->last_line_num
= -1;
2172 static void tok_str_free(int *str
)
2181 /* NOTE: we test zero separately so that GCC can generate a
2182 table for the following switch */
2197 /* XXX: use a macro to be portable on 64 bit ? */
2198 cstr
= (CString
*)p
[1];
2209 p
+= 1 + (LDOUBLE_SIZE
/ 4);
2219 static int *tok_str_realloc(TokenString
*s
)
2223 len
= s
->allocated_len
+ TOK_STR_ALLOC_INCR
;
2224 str
= tcc_realloc(s
->str
, len
* sizeof(int));
2226 error("memory full");
2227 s
->allocated_len
= len
;
2232 static void tok_str_add(TokenString
*s
, int t
)
2238 if (len
>= s
->allocated_len
)
2239 str
= tok_str_realloc(s
);
2244 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
2251 /* allocate space for worst case */
2252 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
2253 str
= tok_str_realloc(s
);
2262 str
[len
++] = cv
->tab
[0];
2267 str
[len
++] = (int)cstr_dup(cv
->cstr
);
2272 #if LDOUBLE_SIZE == 8
2275 str
[len
++] = cv
->tab
[0];
2276 str
[len
++] = cv
->tab
[1];
2278 #if LDOUBLE_SIZE == 12
2280 str
[len
++] = cv
->tab
[0];
2281 str
[len
++] = cv
->tab
[1];
2282 str
[len
++] = cv
->tab
[2];
2283 #elif LDOUBLE_SIZE != 8
2284 #error add long double size support
2293 /* add the current parse token in token string 's' */
2294 static void tok_str_add_tok(TokenString
*s
)
2298 /* save line number info */
2299 if (file
->line_num
!= s
->last_line_num
) {
2300 s
->last_line_num
= file
->line_num
;
2301 cval
.i
= s
->last_line_num
;
2302 tok_str_add2(s
, TOK_LINENUM
, &cval
);
2304 tok_str_add2(s
, tok
, &tokc
);
2307 #if LDOUBLE_SIZE == 12
2308 #define LDOUBLE_GET(p, cv) \
2312 #elif LDOUBLE_SIZE == 8
2313 #define LDOUBLE_GET(p, cv) \
2317 #error add long double size support
2321 /* get a token from an integer array and increment pointer
2322 accordingly. we code it as a macro to avoid pointer aliasing. */
2323 #define TOK_GET(t, p, cv) \
2345 case TOK_CLDOUBLE: \
2346 LDOUBLE_GET(p, cv); \
2347 p += LDOUBLE_SIZE / 4; \
2354 /* defines handling */
2355 static inline void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
2359 s
= sym_push2(&define_stack
, v
, macro_type
, (int)str
);
2360 s
->next
= first_arg
;
2361 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
2364 /* undefined a define symbol. Its name is just set to zero */
2365 static void define_undef(Sym
*s
)
2369 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2370 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2374 static inline Sym
*define_find(int v
)
2377 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2379 return table_ident
[v
]->sym_define
;
2382 /* free define stack until top reaches 'b' */
2383 static void free_defines(Sym
*b
)
2391 /* do not free args or predefined defines */
2393 tok_str_free((int *)top
->c
);
2395 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2396 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2404 static Sym
*label_find(int v
)
2407 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2409 return table_ident
[v
]->sym_label
;
2412 static Sym
*label_push(Sym
**ptop
, int v
, int flags
)
2415 s
= sym_push2(ptop
, v
, 0, 0);
2417 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
2418 if (ptop
== &global_label_stack
) {
2419 /* modify the top most local identifier, so that
2420 sym_identifier will point to 's' when popped */
2422 ps
= &(*ps
)->prev_tok
;
2429 /* pop labels until element last is reached. Look if any labels are
2430 undefined. Define symbols if '&&label' was used. */
2431 static void label_pop(Sym
**ptop
, Sym
*slast
)
2434 for(s
= *ptop
; s
!= slast
; s
= s1
) {
2436 if (s
->r
== LABEL_DECLARED
) {
2437 warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
2438 } else if (s
->r
== LABEL_FORWARD
) {
2439 error("label '%s' used but not defined",
2440 get_tok_str(s
->v
, NULL
));
2443 /* define corresponding symbol. A size of
2445 put_extern_sym(s
, cur_text_section
, (long)s
->next
, 1);
2449 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
2455 /* eval an expression for #if/#elif */
2456 static int expr_preprocess(void)
2462 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2463 next(); /* do macro subst */
2464 if (tok
== TOK_DEFINED
) {
2469 c
= define_find(tok
) != 0;
2474 } else if (tok
>= TOK_IDENT
) {
2475 /* if undefined macro */
2479 tok_str_add_tok(&str
);
2481 tok_str_add(&str
, -1); /* simulate end of file */
2482 tok_str_add(&str
, 0);
2483 /* now evaluate C constant expression */
2484 macro_ptr
= str
.str
;
2488 tok_str_free(str
.str
);
2492 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
2493 static void tok_print(int *str
)
2499 TOK_GET(t
, str
, cval
);
2502 printf(" %s", get_tok_str(t
, &cval
));
2508 /* parse after #define */
2509 static void parse_define(void)
2511 Sym
*s
, *first
, **ps
;
2512 int v
, t
, varg
, is_vaargs
, c
;
2517 error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
2518 /* XXX: should check if same macro (ANSI) */
2521 /* '(' must be just after macro definition for MACRO_FUNC */
2522 c
= file
->buf_ptr
[0];
2524 c
= handle_stray1(file
->buf_ptr
);
2529 while (tok
!= ')') {
2533 if (varg
== TOK_DOTS
) {
2534 varg
= TOK___VA_ARGS__
;
2536 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
2540 if (varg
< TOK_IDENT
)
2541 error("badly punctuated parameter list");
2542 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
2553 /* EOF testing necessary for '-D' handling */
2554 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2555 tok_str_add2(&str
, tok
, &tokc
);
2558 tok_str_add(&str
, 0);
2560 printf("define %s %d: ", get_tok_str(v
, NULL
), t
);
2563 define_push(v
, t
, str
.str
, first
);
2566 /* XXX: use a token or a hash table to accelerate matching ? */
2567 static CachedInclude
*search_cached_include(TCCState
*s1
,
2568 int type
, const char *filename
)
2573 for(i
= 0;i
< s1
->nb_cached_includes
; i
++) {
2574 e
= s1
->cached_includes
[i
];
2575 if (e
->type
== type
&& !strcmp(e
->filename
, filename
))
2581 static inline void add_cached_include(TCCState
*s1
, int type
,
2582 const char *filename
, int ifndef_macro
)
2586 if (search_cached_include(s1
, type
, filename
))
2589 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
2591 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
2595 strcpy(e
->filename
, filename
);
2596 e
->ifndef_macro
= ifndef_macro
;
2597 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
2600 /* is_bof is true if first non space token at beginning of file */
2601 static void preprocess(int is_bof
)
2603 TCCState
*s1
= tcc_state
;
2604 int size
, i
, c
, n
, saved_parse_flags
;
2605 char buf
[1024], *q
, *p
;
2611 saved_parse_flags
= parse_flags
;
2612 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
|
2613 PARSE_FLAG_LINEFEED
;
2623 s
= define_find(tok
);
2624 /* undefine symbol by putting an invalid name */
2629 ch
= file
->buf_ptr
[0];
2630 /* XXX: incorrect if comments : use next_nomacro with a special mode */
2635 } else if (ch
== '\"') {
2638 /* XXX: better stray handling */
2641 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
2642 if ((q
- buf
) < sizeof(buf
) - 1)
2649 /* eat all spaces and comments after include */
2650 /* XXX: slightly incorrect */
2651 while (ch1
!= '\n' && ch1
!= CH_EOF
)
2655 /* computed #include : either we have only strings or
2656 we have anything enclosed in '<>' */
2659 if (tok
== TOK_STR
) {
2660 while (tok
!= TOK_LINEFEED
) {
2661 if (tok
!= TOK_STR
) {
2663 error("'#include' expects \"FILENAME\" or <FILENAME>");
2665 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
2671 while (tok
!= TOK_LINEFEED
) {
2672 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
2676 /* check syntax and remove '<>' */
2677 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
2678 goto include_syntax
;
2679 memmove(buf
, buf
+ 1, len
- 2);
2680 buf
[len
- 2] = '\0';
2685 e
= search_cached_include(s1
, c
, buf
);
2686 if (e
&& define_find(e
->ifndef_macro
)) {
2687 /* no need to parse the include because the 'ifndef macro'
2690 printf("%s: skipping %s\n", file
->filename
, buf
);
2694 /* first search in current dir if "header.h" */
2696 p
= strrchr(file
->filename
, '/');
2698 size
= p
+ 1 - file
->filename
;
2699 if (size
> sizeof(buf1
) - 1)
2700 size
= sizeof(buf1
) - 1;
2701 memcpy(buf1
, file
->filename
, size
);
2703 pstrcat(buf1
, sizeof(buf1
), buf
);
2704 f
= tcc_open(s1
, buf1
);
2708 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
2709 error("#include recursion too deep");
2710 /* now search in all the include paths */
2711 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
2712 for(i
= 0; i
< n
; i
++) {
2714 if (i
< s1
->nb_include_paths
)
2715 path
= s1
->include_paths
[i
];
2717 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
2718 pstrcpy(buf1
, sizeof(buf1
), path
);
2719 pstrcat(buf1
, sizeof(buf1
), "/");
2720 pstrcat(buf1
, sizeof(buf1
), buf
);
2721 f
= tcc_open(s1
, buf1
);
2725 error("include file '%s' not found", buf
);
2729 printf("%s: including %s\n", file
->filename
, buf1
);
2732 pstrcpy(f
->inc_filename
, sizeof(f
->inc_filename
), buf
);
2733 /* push current file in stack */
2734 /* XXX: fix current line init */
2735 *s1
->include_stack_ptr
++ = file
;
2737 /* add include file debug info */
2739 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
2741 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
2742 ch
= file
->buf_ptr
[0];
2750 c
= expr_preprocess();
2756 if (tok
< TOK_IDENT
)
2757 error("invalid argument for '#if%sdef'", c
? "n" : "");
2761 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
2763 file
->ifndef_macro
= tok
;
2766 c
= (define_find(tok
) != 0) ^ c
;
2768 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
2769 error("memory full");
2770 *s1
->ifdef_stack_ptr
++ = c
;
2773 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
2774 error("#else without matching #if");
2775 if (s1
->ifdef_stack_ptr
[-1] & 2)
2776 error("#else after #else");
2777 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
2780 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
2781 error("#elif without matching #if");
2782 c
= s1
->ifdef_stack_ptr
[-1];
2784 error("#elif after #else");
2785 /* last #if/#elif expression was true: we skip */
2788 c
= expr_preprocess();
2789 s1
->ifdef_stack_ptr
[-1] = c
;
2799 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
2800 error("#endif without matching #if");
2801 s1
->ifdef_stack_ptr
--;
2802 /* '#ifndef macro' was at the start of file. Now we check if
2803 an '#endif' is exactly at the end of file */
2804 if (file
->ifndef_macro
&&
2805 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
2806 file
->ifndef_macro_saved
= file
->ifndef_macro
;
2807 /* need to set to zero to avoid false matches if another
2808 #ifndef at middle of file */
2809 file
->ifndef_macro
= 0;
2810 while (tok
!= TOK_LINEFEED
)
2812 tok_flags
|= TOK_FLAG_ENDIF
;
2818 if (tok
!= TOK_CINT
)
2820 file
->line_num
= tokc
.i
- 1; /* the line number will be incremented after */
2822 if (tok
!= TOK_LINEFEED
) {
2825 pstrcpy(file
->filename
, sizeof(file
->filename
),
2826 (char *)tokc
.cstr
->data
);
2832 ch
= file
->buf_ptr
[0];
2835 while (ch
!= '\n' && ch
!= CH_EOF
) {
2836 if ((q
- buf
) < sizeof(buf
) - 1)
2842 error("#error %s", buf
);
2844 warning("#warning %s", buf
);
2850 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_CINT
) {
2851 /* '!' is ignored to allow C scripts. numbers are ignored
2852 to emulate cpp behaviour */
2854 error("invalid preprocessing directive #%s", get_tok_str(tok
, &tokc
));
2858 /* ignore other preprocess commands or #! for C scripts */
2859 while (tok
!= TOK_LINEFEED
)
2862 parse_flags
= saved_parse_flags
;
2865 /* evaluate escape codes in a string. */
2866 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
2881 case '0': case '1': case '2': case '3':
2882 case '4': case '5': case '6': case '7':
2883 /* at most three octal digits */
2888 n
= n
* 8 + c
- '0';
2892 n
= n
* 8 + c
- '0';
2897 goto add_char_nonext
;
2903 if (c
>= 'a' && c
<= 'f')
2905 else if (c
>= 'A' && c
<= 'F')
2915 goto add_char_nonext
;
2939 goto invalid_escape
;
2949 if (c
>= '!' && c
<= '~')
2950 warning("unknown escape sequence: \'\\%c\'", c
);
2952 warning("unknown escape sequence: \'\\x%x\'", c
);
2959 cstr_ccat(outstr
, c
);
2961 cstr_wccat(outstr
, c
);
2963 /* add a trailing '\0' */
2965 cstr_ccat(outstr
, '\0');
2967 cstr_wccat(outstr
, '\0');
2970 /* we use 64 bit numbers */
2973 /* bn = (bn << shift) | or_val */
2974 void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
2978 for(i
=0;i
<BN_SIZE
;i
++) {
2980 bn
[i
] = (v
<< shift
) | or_val
;
2981 or_val
= v
>> (32 - shift
);
2985 void bn_zero(unsigned int *bn
)
2988 for(i
=0;i
<BN_SIZE
;i
++) {
2993 /* parse number in null terminated string 'p' and return it in the
2995 void parse_number(const char *p
)
2997 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
2999 unsigned int bn
[BN_SIZE
];
3010 goto float_frac_parse
;
3011 } else if (t
== '0') {
3012 if (ch
== 'x' || ch
== 'X') {
3016 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
3022 /* parse all digits. cannot check octal numbers at this stage
3023 because of floating point constants */
3025 if (ch
>= 'a' && ch
<= 'f')
3027 else if (ch
>= 'A' && ch
<= 'F')
3035 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
3037 error("number too long");
3043 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
3044 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
3046 /* NOTE: strtox should support that for hexa numbers, but
3047 non ISOC99 libcs do not support it, so we prefer to do
3049 /* hexadecimal or binary floats */
3050 /* XXX: handle overflows */
3062 } else if (t
>= 'a') {
3064 } else if (t
>= 'A') {
3069 bn_lshift(bn
, shift
, t
);
3076 if (t
>= 'a' && t
<= 'f') {
3078 } else if (t
>= 'A' && t
<= 'F') {
3080 } else if (t
>= '0' && t
<= '9') {
3086 error("invalid digit");
3087 bn_lshift(bn
, shift
, t
);
3092 if (ch
!= 'p' && ch
!= 'P')
3099 } else if (ch
== '-') {
3103 if (ch
< '0' || ch
> '9')
3104 expect("exponent digits");
3105 while (ch
>= '0' && ch
<= '9') {
3106 exp_val
= exp_val
* 10 + ch
- '0';
3109 exp_val
= exp_val
* s
;
3111 /* now we can generate the number */
3112 /* XXX: should patch directly float number */
3113 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
3114 d
= ldexp(d
, exp_val
- frac_bits
);
3119 /* float : should handle overflow */
3121 } else if (t
== 'L') {
3124 /* XXX: not large enough */
3125 tokc
.ld
= (long double)d
;
3131 /* decimal floats */
3133 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3138 while (ch
>= '0' && ch
<= '9') {
3139 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3145 if (ch
== 'e' || ch
== 'E') {
3146 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3150 if (ch
== '-' || ch
== '+') {
3151 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3156 if (ch
< '0' || ch
> '9')
3157 expect("exponent digits");
3158 while (ch
>= '0' && ch
<= '9') {
3159 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3171 tokc
.f
= strtof(token_buf
, NULL
);
3172 } else if (t
== 'L') {
3175 tokc
.ld
= strtold(token_buf
, NULL
);
3178 tokc
.d
= strtod(token_buf
, NULL
);
3182 unsigned long long n
, n1
;
3185 /* integer number */
3188 if (b
== 10 && *q
== '0') {
3195 /* no need for checks except for base 10 / 8 errors */
3198 } else if (t
>= 'a') {
3200 } else if (t
>= 'A') {
3205 error("invalid digit");
3209 /* detect overflow */
3210 /* XXX: this test is not reliable */
3212 error("integer constant overflow");
3215 /* XXX: not exactly ANSI compliant */
3216 if ((n
& 0xffffffff00000000LL
) != 0) {
3221 } else if (n
> 0x7fffffff) {
3232 error("three 'l's in integer constant");
3235 if (tok
== TOK_CINT
)
3237 else if (tok
== TOK_CUINT
)
3241 } else if (t
== 'U') {
3243 error("two 'u's in integer constant");
3245 if (tok
== TOK_CINT
)
3247 else if (tok
== TOK_CLLONG
)
3254 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
3262 #define PARSE2(c1, tok1, c2, tok2) \
3273 /* return next token without macro substitution */
3274 static inline void next_nomacro1(void)
3294 /* first look if it is in fact an end of buffer */
3295 if (p
>= file
->buf_end
) {
3299 if (p
>= file
->buf_end
)
3312 TCCState
*s1
= tcc_state
;
3313 if (parse_flags
& PARSE_FLAG_LINEFEED
) {
3315 } else if (s1
->include_stack_ptr
== s1
->include_stack
||
3316 !(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3317 /* no include left : end of file. */
3320 /* pop include file */
3322 /* test if previous '#endif' was after a #ifdef at
3324 if (tok_flags
& TOK_FLAG_ENDIF
) {
3326 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
3328 add_cached_include(s1
, file
->inc_type
, file
->inc_filename
,
3329 file
->ifndef_macro_saved
);
3332 /* add end of include file debug info */
3334 put_stabd(N_EINCL
, 0, 0);
3336 /* pop include stack */
3338 s1
->include_stack_ptr
--;
3339 file
= *s1
->include_stack_ptr
;
3347 if (parse_flags
& PARSE_FLAG_LINEFEED
) {
3351 tok_flags
|= TOK_FLAG_BOL
;
3360 if ((tok_flags
& TOK_FLAG_BOL
) &&
3361 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3363 preprocess(tok_flags
& TOK_FLAG_BOF
);
3369 tok
= TOK_TWOSHARPS
;
3376 case 'a': case 'b': case 'c': case 'd':
3377 case 'e': case 'f': case 'g': case 'h':
3378 case 'i': case 'j': case 'k': case 'l':
3379 case 'm': case 'n': case 'o': case 'p':
3380 case 'q': case 'r': case 's': case 't':
3381 case 'u': case 'v': case 'w': case 'x':
3383 case 'A': case 'B': case 'C': case 'D':
3384 case 'E': case 'F': case 'G': case 'H':
3385 case 'I': case 'J': case 'K':
3386 case 'M': case 'N': case 'O': case 'P':
3387 case 'Q': case 'R': case 'S': case 'T':
3388 case 'U': case 'V': case 'W': case 'X':
3394 h
= TOK_HASH_FUNC(h
, c
);
3398 if (!isidnum_table
[c
])
3400 h
= TOK_HASH_FUNC(h
, c
);
3407 /* fast case : no stray found, so we have the full token
3408 and we have already hashed it */
3410 h
&= (TOK_HASH_SIZE
- 1);
3411 pts
= &hash_ident
[h
];
3416 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
3418 pts
= &(ts
->hash_next
);
3420 ts
= tok_alloc_new(pts
, p1
, len
);
3424 cstr_reset(&tokcstr
);
3427 cstr_ccat(&tokcstr
, *p1
);
3433 while (isidnum_table
[c
]) {
3434 cstr_ccat(&tokcstr
, c
);
3437 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
3443 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
3445 goto parse_ident_fast
;
3448 if (c
== '\'' || c
== '\"') {
3452 cstr_reset(&tokcstr
);
3453 cstr_ccat(&tokcstr
, 'L');
3454 goto parse_ident_slow
;
3458 case '0': case '1': case '2': case '3':
3459 case '4': case '5': case '6': case '7':
3462 cstr_reset(&tokcstr
);
3463 /* after the first digit, accept digits, alpha, '.' or sign if
3464 prefixed by 'eEpP' */
3468 cstr_ccat(&tokcstr
, c
);
3470 if (!(isnum(c
) || isid(c
) || c
== '.' ||
3471 ((c
== '+' || c
== '-') &&
3472 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
3475 /* We add a trailing '\0' to ease parsing */
3476 cstr_ccat(&tokcstr
, '\0');
3477 tokc
.cstr
= &tokcstr
;
3481 /* special dot handling because it can also start a number */
3484 cstr_reset(&tokcstr
);
3485 cstr_ccat(&tokcstr
, '.');
3487 } else if (c
== '.') {
3507 /* parse the string */
3509 p
= parse_pp_string(p
, sep
, &str
);
3510 cstr_ccat(&str
, '\0');
3512 /* eval the escape (should be done as TOK_PPNUM) */
3513 cstr_reset(&tokcstr
);
3514 parse_escape_string(&tokcstr
, str
.data
, is_long
);
3519 /* XXX: make it portable */
3523 char_size
= sizeof(int);
3524 if (tokcstr
.size
<= char_size
)
3525 error("empty character constant");
3526 if (tokcstr
.size
> 2 * char_size
)
3527 warning("multi-character character constant");
3529 tokc
.i
= *(int8_t *)tokcstr
.data
;
3532 tokc
.i
= *(int *)tokcstr
.data
;
3536 tokc
.cstr
= &tokcstr
;
3550 } else if (c
== '<') {
3568 } else if (c
== '>') {
3586 } else if (c
== '=') {
3599 } else if (c
== '=') {
3612 } else if (c
== '=') {
3625 } else if (c
== '=') {
3628 } else if (c
== '>') {
3636 PARSE2('!', '!', '=', TOK_NE
)
3637 PARSE2('=', '=', '=', TOK_EQ
)
3638 PARSE2('*', '*', '=', TOK_A_MUL
)
3639 PARSE2('%', '%', '=', TOK_A_MOD
)
3640 PARSE2('^', '^', '=', TOK_A_XOR
)
3642 /* comments or operator */
3646 p
= parse_comment(p
);
3648 } else if (c
== '/') {
3649 p
= parse_line_comment(p
);
3651 } else if (c
== '=') {
3671 case '$': /* only used in assembler */
3676 error("unrecognized character \\x%02x", c
);
3681 #if defined(PARSE_DEBUG)
3682 printf("token = %s\n", get_tok_str(tok
, &tokc
));
3686 /* return next token without macro substitution. Can read input from
3688 static void next_nomacro(void)
3694 TOK_GET(tok
, macro_ptr
, tokc
);
3695 if (tok
== TOK_LINENUM
) {
3696 file
->line_num
= tokc
.i
;
3705 /* substitute args in macro_str and return allocated string */
3706 static int *macro_arg_subst(Sym
**nested_list
, int *macro_str
, Sym
*args
)
3708 int *st
, last_tok
, t
, notfirst
;
3717 TOK_GET(t
, macro_str
, cval
);
3722 TOK_GET(t
, macro_str
, cval
);
3725 s
= sym_find2(args
, t
);
3732 cstr_ccat(&cstr
, ' ');
3733 TOK_GET(t
, st
, cval
);
3734 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
3737 cstr_ccat(&cstr
, '\0');
3739 printf("stringize: %s\n", (char *)cstr
.data
);
3743 tok_str_add2(&str
, TOK_STR
, &cval
);
3746 tok_str_add2(&str
, t
, &cval
);
3748 } else if (t
>= TOK_IDENT
) {
3749 s
= sym_find2(args
, t
);
3752 /* if '##' is present before or after, no arg substitution */
3753 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
3754 /* special case for var arg macros : ## eats the
3755 ',' if empty VA_ARGS variable. */
3756 /* XXX: test of the ',' is not 100%
3757 reliable. should fix it to avoid security
3759 if (gnu_ext
&& s
->type
.t
&&
3760 last_tok
== TOK_TWOSHARPS
&&
3761 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
3763 /* suppress ',' '##' */
3766 /* suppress '##' and add variable */
3774 TOK_GET(t1
, st
, cval
);
3777 tok_str_add2(&str
, t1
, &cval
);
3781 /* NOTE: the stream cannot be read when macro
3782 substituing an argument */
3783 macro_subst(&str
, nested_list
, st
, 0);
3786 tok_str_add(&str
, t
);
3789 tok_str_add2(&str
, t
, &cval
);
3793 tok_str_add(&str
, 0);
3797 static char const ab_month_name
[12][4] =
3799 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3800 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3803 /* do macro substitution of current token with macro 's' and add
3804 result to (tok_str,tok_len). 'nested_list' is the list of all
3805 macros we got inside to avoid recursing. Return non zero if no
3806 substitution needs to be done */
3807 static int macro_subst_tok(TokenString
*tok_str
,
3808 Sym
**nested_list
, Sym
*s
, int can_read_stream
)
3810 Sym
*args
, *sa
, *sa1
;
3811 int mstr_allocated
, parlevel
, *mstr
, t
, t1
;
3818 /* if symbol is a macro, prepare substitution */
3820 /* special macros */
3821 if (tok
== TOK___LINE__
) {
3822 snprintf(buf
, sizeof(buf
), "%d", file
->line_num
);
3826 } else if (tok
== TOK___FILE__
) {
3827 cstrval
= file
->filename
;
3829 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
3834 tm
= localtime(&ti
);
3835 if (tok
== TOK___DATE__
) {
3836 snprintf(buf
, sizeof(buf
), "%s %2d %d",
3837 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
3839 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
3840 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
3847 cstr_cat(&cstr
, cstrval
);
3848 cstr_ccat(&cstr
, '\0');
3850 tok_str_add2(tok_str
, t1
, &cval
);
3855 if (s
->type
.t
== MACRO_FUNC
) {
3856 /* NOTE: we do not use next_nomacro to avoid eating the
3857 next token. XXX: find better solution */
3860 if (t
== 0 && can_read_stream
) {
3861 /* end of macro stream: we must look at the token
3862 after in the file */
3868 /* XXX: incorrect with comments */
3869 ch
= file
->buf_ptr
[0];
3870 while (is_space(ch
) || ch
== '\n')
3874 if (t
!= '(') /* no macro subst */
3877 /* argument macro */
3882 /* NOTE: empty args are allowed, except if no args */
3884 /* handle '()' case */
3885 if (!args
&& !sa
&& tok
== ')')
3888 error("macro '%s' used with too many args",
3889 get_tok_str(s
->v
, 0));
3892 /* NOTE: non zero sa->t indicates VA_ARGS */
3893 while ((parlevel
> 0 ||
3895 (tok
!= ',' || sa
->type
.t
))) &&
3899 else if (tok
== ')')
3901 tok_str_add2(&str
, tok
, &tokc
);
3904 tok_str_add(&str
, 0);
3905 sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, (int)str
.str
);
3908 /* special case for gcc var args: add an empty
3909 var arg argument if it is omitted */
3910 if (sa
&& sa
->type
.t
&& gnu_ext
)
3920 error("macro '%s' used with too few args",
3921 get_tok_str(s
->v
, 0));
3924 /* now subst each arg */
3925 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3930 tok_str_free((int *)sa
->c
);
3936 sym_push2(nested_list
, s
->v
, 0, 0);
3937 macro_subst(tok_str
, nested_list
, mstr
, 1);
3938 /* pop nested defined symbol */
3940 *nested_list
= sa1
->prev
;
3948 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3949 return the resulting string (which must be freed). */
3950 static inline int *macro_twosharps(const int *macro_str
)
3953 const int *macro_ptr1
, *start_macro_ptr
, *ptr
, *saved_macro_ptr
;
3955 const char *p1
, *p2
;
3957 TokenString macro_str1
;
3960 start_macro_ptr
= macro_str
;
3961 /* we search the first '##' */
3963 macro_ptr1
= macro_str
;
3964 TOK_GET(t
, macro_str
, cval
);
3965 /* nothing more to do if end of string */
3968 if (*macro_str
== TOK_TWOSHARPS
)
3972 /* we saw '##', so we need more processing to handle it */
3974 tok_str_new(¯o_str1
);
3978 /* add all tokens seen so far */
3979 for(ptr
= start_macro_ptr
; ptr
< macro_ptr1
;) {
3980 TOK_GET(t
, ptr
, cval
);
3981 tok_str_add2(¯o_str1
, t
, &cval
);
3983 saved_macro_ptr
= macro_ptr
;
3984 /* XXX: get rid of the use of macro_ptr here */
3985 macro_ptr
= (int *)macro_str
;
3987 while (*macro_ptr
== TOK_TWOSHARPS
) {
3989 macro_ptr1
= macro_ptr
;
3992 TOK_GET(t
, macro_ptr
, cval
);
3993 /* We concatenate the two tokens if we have an
3994 identifier or a preprocessing number */
3996 p1
= get_tok_str(tok
, &tokc
);
3997 cstr_cat(&cstr
, p1
);
3998 p2
= get_tok_str(t
, &cval
);
3999 cstr_cat(&cstr
, p2
);
4000 cstr_ccat(&cstr
, '\0');
4002 if ((tok
>= TOK_IDENT
|| tok
== TOK_PPNUM
) &&
4003 (t
>= TOK_IDENT
|| t
== TOK_PPNUM
)) {
4004 if (tok
== TOK_PPNUM
) {
4005 /* if number, then create a number token */
4006 /* NOTE: no need to allocate because
4007 tok_str_add2() does it */
4010 /* if identifier, we must do a test to
4011 validate we have a correct identifier */
4012 if (t
== TOK_PPNUM
) {
4022 if (!isnum(c
) && !isid(c
))
4026 ts
= tok_alloc(cstr
.data
, strlen(cstr
.data
));
4027 tok
= ts
->tok
; /* modify current token */
4030 const char *str
= cstr
.data
;
4031 const unsigned char *q
;
4033 /* we look for a valid token */
4034 /* XXX: do more extensive checks */
4035 if (!strcmp(str
, ">>=")) {
4037 } else if (!strcmp(str
, "<<=")) {
4039 } else if (strlen(str
) == 2) {
4040 /* search in two bytes table */
4045 if (q
[0] == str
[0] && q
[1] == str
[1])
4052 /* NOTE: because get_tok_str use a static buffer,
4055 p1
= get_tok_str(tok
, &tokc
);
4056 cstr_cat(&cstr
, p1
);
4057 cstr_ccat(&cstr
, '\0');
4058 p2
= get_tok_str(t
, &cval
);
4059 warning("pasting \"%s\" and \"%s\" does not give a valid preprocessing token", cstr
.data
, p2
);
4060 /* cannot merge tokens: just add them separately */
4061 tok_str_add2(¯o_str1
, tok
, &tokc
);
4062 /* XXX: free associated memory ? */
4069 tok_str_add2(¯o_str1
, tok
, &tokc
);
4074 macro_ptr
= (int *)saved_macro_ptr
;
4076 tok_str_add(¯o_str1
, 0);
4077 return macro_str1
.str
;
4081 /* do macro substitution of macro_str and add result to
4082 (tok_str,tok_len). 'nested_list' is the list of all macros we got
4083 inside to avoid recursing. */
4084 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
4085 const int *macro_str
, int can_read_stream
)
4088 int *saved_macro_ptr
, *macro_str1
;
4093 /* first scan for '##' operator handling */
4095 macro_str1
= macro_twosharps(ptr
);
4099 /* NOTE: ptr == NULL can only happen if tokens are read from
4100 file stream due to a macro function call */
4103 TOK_GET(t
, ptr
, cval
);
4108 /* if nested substitution, do nothing */
4109 if (sym_find2(*nested_list
, t
))
4111 saved_macro_ptr
= macro_ptr
;
4112 macro_ptr
= (int *)ptr
;
4114 ret
= macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
4115 ptr
= (int *)macro_ptr
;
4116 macro_ptr
= saved_macro_ptr
;
4121 tok_str_add2(tok_str
, t
, &cval
);
4125 tok_str_free(macro_str1
);
4128 /* return next token with macro substitution */
4129 static void next(void)
4131 Sym
*nested_list
, *s
;
4137 /* if not reading from macro substituted string, then try
4138 to substitute macros */
4139 if (tok
>= TOK_IDENT
&&
4140 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
4141 s
= define_find(tok
);
4143 /* we have a macro: we try to substitute */
4146 if (macro_subst_tok(&str
, &nested_list
, s
, 1) == 0) {
4147 /* substitution done, NOTE: maybe empty */
4148 tok_str_add(&str
, 0);
4149 macro_ptr
= str
.str
;
4150 macro_ptr_allocated
= str
.str
;
4157 /* end of macro or end of unget buffer */
4158 if (unget_buffer_enabled
) {
4159 macro_ptr
= unget_saved_macro_ptr
;
4160 unget_buffer_enabled
= 0;
4162 /* end of macro string: free it */
4163 tok_str_free(macro_ptr_allocated
);
4170 /* convert preprocessor tokens into C tokens */
4171 if (tok
== TOK_PPNUM
&&
4172 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
4173 parse_number((char *)tokc
.cstr
->data
);
4177 /* push back current token and set current token to 'last_tok'. Only
4178 identifier case handled for labels. */
4179 static inline void unget_tok(int last_tok
)
4183 unget_saved_macro_ptr
= macro_ptr
;
4184 unget_buffer_enabled
= 1;
4185 q
= unget_saved_buffer
;
4188 n
= tok_ext_size(tok
) - 1;
4191 *q
= 0; /* end of token string */
4196 void swap(int *p
, int *q
)
4204 void vsetc(CType
*type
, int r
, CValue
*vc
)
4208 if (vtop
>= vstack
+ VSTACK_SIZE
)
4209 error("memory full");
4210 /* cannot let cpu flags if other instruction are generated. Also
4211 avoid leaving VT_JMP anywhere except on the top of the stack
4212 because it would complicate the code generator. */
4213 if (vtop
>= vstack
) {
4214 v
= vtop
->r
& VT_VALMASK
;
4215 if (v
== VT_CMP
|| (v
& ~1) == VT_JMP
)
4221 vtop
->r2
= VT_CONST
;
4225 /* push integer constant */
4230 vsetc(&int_type
, VT_CONST
, &cval
);
4233 /* Return a static symbol pointing to a section */
4234 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
4235 unsigned long offset
, unsigned long size
)
4241 sym
= global_identifier_push(v
, type
->t
| VT_STATIC
, 0);
4242 sym
->type
.ref
= type
->ref
;
4243 sym
->r
= VT_CONST
| VT_SYM
;
4244 put_extern_sym(sym
, sec
, offset
, size
);
4248 /* push a reference to a section offset by adding a dummy symbol */
4249 static void vpush_ref(CType
*type
, Section
*sec
, unsigned long offset
, unsigned long size
)
4254 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4255 vtop
->sym
= get_sym_ref(type
, sec
, offset
, size
);
4258 /* define a new external reference to a symbol 'v' of type 'u' */
4259 static Sym
*external_global_sym(int v
, CType
*type
, int r
)
4265 /* push forward reference */
4266 s
= global_identifier_push(v
, type
->t
| VT_EXTERN
, 0);
4267 s
->type
.ref
= type
->ref
;
4268 s
->r
= r
| VT_CONST
| VT_SYM
;
4273 /* define a new external reference to a symbol 'v' of type 'u' */
4274 static Sym
*external_sym(int v
, CType
*type
, int r
)
4280 /* push forward reference */
4281 s
= sym_push(v
, type
, r
| VT_CONST
| VT_SYM
, 0);
4282 s
->type
.t
|= VT_EXTERN
;
4284 if (!is_compatible_types(&s
->type
, type
))
4285 error("incompatible types for redefinition of '%s'",
4286 get_tok_str(v
, NULL
));
4291 /* push a reference to global symbol v */
4292 static void vpush_global_sym(CType
*type
, int v
)
4297 sym
= external_global_sym(v
, type
, 0);
4299 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4303 void vset(CType
*type
, int r
, int v
)
4308 vsetc(type
, r
, &cval
);
4311 void vseti(int r
, int v
)
4327 void vpushv(SValue
*v
)
4329 if (vtop
>= vstack
+ VSTACK_SIZE
)
4330 error("memory full");
4340 /* save r to the memory stack, and mark it as being free */
4341 void save_reg(int r
)
4343 int l
, saved
, size
, align
;
4347 /* modify all stack values */
4350 for(p
=vstack
;p
<=vtop
;p
++) {
4351 if ((p
->r
& VT_VALMASK
) == r
||
4352 (p
->r2
& VT_VALMASK
) == r
) {
4353 /* must save value on stack if not already done */
4355 /* NOTE: must reload 'r' because r might be equal to r2 */
4356 r
= p
->r
& VT_VALMASK
;
4357 /* store register in the stack */
4359 if ((p
->r
& VT_LVAL
) ||
4360 (!is_float(type
->t
) && (type
->t
& VT_BTYPE
) != VT_LLONG
))
4362 size
= type_size(type
, &align
);
4363 loc
= (loc
- size
) & -align
;
4364 sv
.type
.t
= type
->t
;
4365 sv
.r
= VT_LOCAL
| VT_LVAL
;
4368 #ifdef TCC_TARGET_I386
4369 /* x86 specific: need to pop fp register ST0 if saved */
4370 if (r
== TREG_ST0
) {
4371 o(0xd9dd); /* fstp %st(1) */
4374 /* special long long case */
4375 if ((type
->t
& VT_BTYPE
) == VT_LLONG
) {
4382 /* mark that stack entry as being saved on the stack */
4383 if (p
->r
& VT_LVAL
) {
4384 /* also clear the bounded flag because the
4385 relocation address of the function was stored in
4387 p
->r
= (p
->r
& ~(VT_VALMASK
| VT_BOUNDED
)) | VT_LLOCAL
;
4389 p
->r
= lvalue_type(p
->type
.t
) | VT_LOCAL
;
4397 /* find a register of class 'rc2' with at most one reference on stack.
4398 * If none, call get_reg(rc) */
4399 int get_reg_ex(int rc
, int rc2
)
4404 for(r
=0;r
<NB_REGS
;r
++) {
4405 if (reg_classes
[r
] & rc2
) {
4408 for(p
= vstack
; p
<= vtop
; p
++) {
4409 if ((p
->r
& VT_VALMASK
) == r
||
4410 (p
->r2
& VT_VALMASK
) == r
)
4420 /* find a free register of class 'rc'. If none, save one register */
4426 /* find a free register */
4427 for(r
=0;r
<NB_REGS
;r
++) {
4428 if (reg_classes
[r
] & rc
) {
4429 for(p
=vstack
;p
<=vtop
;p
++) {
4430 if ((p
->r
& VT_VALMASK
) == r
||
4431 (p
->r2
& VT_VALMASK
) == r
)
4439 /* no register left : free the first one on the stack (VERY
4440 IMPORTANT to start from the bottom to ensure that we don't
4441 spill registers used in gen_opi()) */
4442 for(p
=vstack
;p
<=vtop
;p
++) {
4443 r
= p
->r
& VT_VALMASK
;
4444 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
))
4446 /* also look at second register (if long long) */
4447 r
= p
->r2
& VT_VALMASK
;
4448 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
)) {
4454 /* Should never comes here */
4458 /* save registers up to (vtop - n) stack entry */
4459 void save_regs(int n
)
4464 for(p
= vstack
;p
<= p1
; p
++) {
4465 r
= p
->r
& VT_VALMASK
;
4472 /* move register 's' to 'r', and flush previous value of r to memory
4474 void move_reg(int r
, int s
)
4487 /* get address of vtop (vtop MUST BE an lvalue) */
4490 vtop
->r
&= ~VT_LVAL
;
4491 /* tricky: if saved lvalue, then we can go back to lvalue */
4492 if ((vtop
->r
& VT_VALMASK
) == VT_LLOCAL
)
4493 vtop
->r
= (vtop
->r
& ~(VT_VALMASK
| VT_LVAL_TYPE
)) | VT_LOCAL
| VT_LVAL
;
4496 #ifdef CONFIG_TCC_BCHECK
4497 /* generate lvalue bound code */
4503 vtop
->r
&= ~VT_MUSTBOUND
;
4504 /* if lvalue, then use checking code before dereferencing */
4505 if (vtop
->r
& VT_LVAL
) {
4506 /* if not VT_BOUNDED value, then make one */
4507 if (!(vtop
->r
& VT_BOUNDED
)) {
4508 lval_type
= vtop
->r
& (VT_LVAL_TYPE
| VT_LVAL
);
4509 /* must save type because we must set it to int to get pointer */
4511 vtop
->type
.t
= VT_INT
;
4514 gen_bounded_ptr_add();
4515 vtop
->r
|= lval_type
;
4518 /* then check for dereferencing */
4519 gen_bounded_ptr_deref();
4524 /* store vtop a register belonging to class 'rc'. lvalues are
4525 converted to values. Cannot be used if cannot be converted to
4526 register value (such as structures). */
4529 int r
, r2
, rc2
, bit_pos
, bit_size
, size
, align
, i
;
4530 unsigned long long ll
;
4532 /* NOTE: get_reg can modify vstack[] */
4533 if (vtop
->type
.t
& VT_BITFIELD
) {
4534 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
4535 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
4536 /* remove bit field info to avoid loops */
4537 vtop
->type
.t
&= ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
4538 /* generate shifts */
4539 vpushi(32 - (bit_pos
+ bit_size
));
4541 vpushi(32 - bit_size
);
4542 /* NOTE: transformed to SHR if unsigned */
4546 if (is_float(vtop
->type
.t
) &&
4547 (vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4550 unsigned long offset
;
4552 /* XXX: unify with initializers handling ? */
4553 /* CPUs usually cannot use float constants, so we store them
4554 generically in data segment */
4555 size
= type_size(&vtop
->type
, &align
);
4556 offset
= (data_section
->data_offset
+ align
- 1) & -align
;
4557 data_section
->data_offset
= offset
;
4558 /* XXX: not portable yet */
4559 ptr
= section_ptr_add(data_section
, size
);
4562 ptr
[i
] = vtop
->c
.tab
[i
];
4563 sym
= get_sym_ref(&vtop
->type
, data_section
, offset
, size
<< 2);
4564 vtop
->r
|= VT_LVAL
| VT_SYM
;
4568 #ifdef CONFIG_TCC_BCHECK
4569 if (vtop
->r
& VT_MUSTBOUND
)
4573 r
= vtop
->r
& VT_VALMASK
;
4574 /* need to reload if:
4576 - lvalue (need to dereference pointer)
4577 - already a register, but not in the right class */
4578 if (r
>= VT_CONST
||
4579 (vtop
->r
& VT_LVAL
) ||
4580 !(reg_classes
[r
] & rc
) ||
4581 ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
&&
4582 !(reg_classes
[vtop
->r2
] & rc
))) {
4584 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
) {
4585 /* two register type load : expand to two words
4587 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4590 vtop
->c
.ui
= ll
; /* first word */
4592 vtop
->r
= r
; /* save register value */
4593 vpushi(ll
>> 32); /* second word */
4594 } else if (r
>= VT_CONST
||
4595 (vtop
->r
& VT_LVAL
)) {
4596 /* load from memory */
4599 vtop
[-1].r
= r
; /* save register value */
4600 /* increment pointer to get second word */
4601 vtop
->type
.t
= VT_INT
;
4607 /* move registers */
4610 vtop
[-1].r
= r
; /* save register value */
4611 vtop
->r
= vtop
[-1].r2
;
4613 /* allocate second register */
4620 /* write second register */
4622 } else if ((vtop
->r
& VT_LVAL
) && !is_float(vtop
->type
.t
)) {
4624 /* lvalue of scalar type : need to use lvalue type
4625 because of possible cast */
4628 /* compute memory access type */
4629 if (vtop
->r
& VT_LVAL_BYTE
)
4631 else if (vtop
->r
& VT_LVAL_SHORT
)
4633 if (vtop
->r
& VT_LVAL_UNSIGNED
)
4637 /* restore wanted type */
4640 /* one register type load */
4645 #ifdef TCC_TARGET_C67
4646 /* uses register pairs for doubles */
4647 if ((vtop
->type
.t
& VT_BTYPE
) == VT_DOUBLE
)
4654 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
4655 void gv2(int rc1
, int rc2
)
4659 /* generate more generic register first. But VT_JMP or VT_CMP
4660 values must be generated first in all cases to avoid possible
4662 v
= vtop
[0].r
& VT_VALMASK
;
4663 if (v
!= VT_CMP
&& (v
& ~1) != VT_JMP
&& rc1
<= rc2
) {
4668 /* test if reload is needed for first register */
4669 if ((vtop
[-1].r
& VT_VALMASK
) >= VT_CONST
) {
4679 /* test if reload is needed for first register */
4680 if ((vtop
[0].r
& VT_VALMASK
) >= VT_CONST
) {
4686 /* expand long long on stack in two int registers */
4691 u
= vtop
->type
.t
& VT_UNSIGNED
;
4694 vtop
[0].r
= vtop
[-1].r2
;
4695 vtop
[0].r2
= VT_CONST
;
4696 vtop
[-1].r2
= VT_CONST
;
4697 vtop
[0].type
.t
= VT_INT
| u
;
4698 vtop
[-1].type
.t
= VT_INT
| u
;
4701 #ifdef TCC_TARGET_ARM
4702 /* expand long long on stack */
4703 void lexpand_nr(void)
4707 u
= vtop
->type
.t
& VT_UNSIGNED
;
4709 vtop
->r2
= VT_CONST
;
4710 vtop
->type
.t
= VT_INT
| u
;
4711 v
=vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
);
4712 if (v
== VT_CONST
) {
4713 vtop
[-1].c
.ui
= vtop
->c
.ull
;
4714 vtop
->c
.ui
= vtop
->c
.ull
>> 32;
4716 } else if (v
== (VT_LVAL
|VT_CONST
) || v
== (VT_LVAL
|VT_LOCAL
)) {
4718 vtop
->r
= vtop
[-1].r
;
4719 } else if (v
> VT_CONST
) {
4723 vtop
->r
= vtop
[-1].r2
;
4724 vtop
[-1].r2
= VT_CONST
;
4725 vtop
[-1].type
.t
= VT_INT
| u
;
4729 /* build a long long from two ints */
4732 gv2(RC_INT
, RC_INT
);
4733 vtop
[-1].r2
= vtop
[0].r
;
4734 vtop
[-1].type
.t
= t
;
4738 /* rotate n first stack elements to the bottom
4739 I1 ... In -> I2 ... In I1 [top is right]
4747 for(i
=-n
+1;i
!=0;i
++)
4748 vtop
[i
] = vtop
[i
+1];
4752 /* rotate n first stack elements to the top
4753 I1 ... In -> In I1 ... I(n-1) [top is right]
4761 for(i
= 0;i
< n
- 1; i
++)
4762 vtop
[-i
] = vtop
[-i
- 1];
4766 #ifdef TCC_TARGET_ARM
4767 /* like vrott but in other direction
4768 In ... I1 -> I(n-1) ... I1 In [top is right]
4776 for(i
= n
- 1; i
> 0; i
--)
4777 vtop
[-i
] = vtop
[-i
+ 1];
4782 /* pop stack value */
4786 v
= vtop
->r
& VT_VALMASK
;
4787 #ifdef TCC_TARGET_I386
4788 /* for x86, we need to pop the FP stack */
4789 if (v
== TREG_ST0
&& !nocode_wanted
) {
4790 o(0xd9dd); /* fstp %st(1) */
4793 if (v
== VT_JMP
|| v
== VT_JMPI
) {
4794 /* need to put correct jump if && or || without test */
4800 /* convert stack entry to register and duplicate its value in another
4808 if ((t
& VT_BTYPE
) == VT_LLONG
) {
4815 /* stack: H L L1 H1 */
4823 /* duplicate value */
4834 load(r1
, &sv
); /* move r to r1 */
4836 /* duplicates value */
4841 /* generate CPU independent (unsigned) long long operations */
4842 void gen_opl(int op
)
4844 int t
, a
, b
, op1
, c
, i
;
4851 func
= TOK___divdi3
;
4854 func
= TOK___udivdi3
;
4857 func
= TOK___moddi3
;
4860 func
= TOK___umoddi3
;
4862 /* call generic long long function */
4863 vpush_global_sym(&func_old_type
, func
);
4868 vtop
->r2
= REG_LRET
;
4881 /* stack: L1 H1 L2 H2 */
4886 vtop
[-2] = vtop
[-3];
4889 /* stack: H1 H2 L1 L2 */
4895 /* stack: H1 H2 L1 L2 ML MH */
4898 /* stack: ML MH H1 H2 L1 L2 */
4902 /* stack: ML MH H1 L2 H2 L1 */
4907 /* stack: ML MH M1 M2 */
4910 } else if (op
== '+' || op
== '-') {
4911 /* XXX: add non carry method too (for MIPS or alpha) */
4917 /* stack: H1 H2 (L1 op L2) */
4920 gen_op(op1
+ 1); /* TOK_xxxC2 */
4923 /* stack: H1 H2 (L1 op L2) */
4926 /* stack: (L1 op L2) H1 H2 */
4928 /* stack: (L1 op L2) (H1 op H2) */
4936 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) {
4937 t
= vtop
[-1].type
.t
;
4941 /* stack: L H shift */
4943 /* constant: simpler */
4944 /* NOTE: all comments are for SHL. the other cases are
4945 done by swaping words */
4956 if (op
!= TOK_SAR
) {
4989 /* XXX: should provide a faster fallback on x86 ? */
4992 func
= TOK___sardi3
;
4995 func
= TOK___shrdi3
;
4998 func
= TOK___shldi3
;
5004 /* compare operations */
5010 /* stack: L1 H1 L2 H2 */
5012 vtop
[-1] = vtop
[-2];
5014 /* stack: L1 L2 H1 H2 */
5017 /* when values are equal, we need to compare low words. since
5018 the jump is inverted, we invert the test too. */
5021 else if (op1
== TOK_GT
)
5023 else if (op1
== TOK_ULT
)
5025 else if (op1
== TOK_UGT
)
5030 if (op1
!= TOK_NE
) {
5034 /* generate non equal test */
5035 /* XXX: NOT PORTABLE yet */
5039 #if defined(TCC_TARGET_I386)
5040 b
= psym(0x850f, 0);
5041 #elif defined(TCC_TARGET_ARM)
5043 o(0x1A000000 | encbranch(ind
, 0, 1));
5044 #elif defined(TCC_TARGET_C67)
5045 error("not implemented");
5047 #error not supported
5051 /* compare low. Always unsigned */
5055 else if (op1
== TOK_LE
)
5057 else if (op1
== TOK_GT
)
5059 else if (op1
== TOK_GE
)
5069 /* handle integer constant optimizations and various machine
5071 void gen_opic(int op
)
5078 /* currently, we cannot do computations with forward symbols */
5079 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5080 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5084 case '+': v1
->c
.i
+= fc
; break;
5085 case '-': v1
->c
.i
-= fc
; break;
5086 case '&': v1
->c
.i
&= fc
; break;
5087 case '^': v1
->c
.i
^= fc
; break;
5088 case '|': v1
->c
.i
|= fc
; break;
5089 case '*': v1
->c
.i
*= fc
; break;
5096 /* if division by zero, generate explicit division */
5099 error("division by zero in constant");
5103 default: v1
->c
.i
/= fc
; break;
5104 case '%': v1
->c
.i
%= fc
; break;
5105 case TOK_UDIV
: v1
->c
.i
= (unsigned)v1
->c
.i
/ fc
; break;
5106 case TOK_UMOD
: v1
->c
.i
= (unsigned)v1
->c
.i
% fc
; break;
5109 case TOK_SHL
: v1
->c
.i
<<= fc
; break;
5110 case TOK_SHR
: v1
->c
.i
= (unsigned)v1
->c
.i
>> fc
; break;
5111 case TOK_SAR
: v1
->c
.i
>>= fc
; break;
5113 case TOK_ULT
: v1
->c
.i
= (unsigned)v1
->c
.i
< (unsigned)fc
; break;
5114 case TOK_UGE
: v1
->c
.i
= (unsigned)v1
->c
.i
>= (unsigned)fc
; break;
5115 case TOK_EQ
: v1
->c
.i
= v1
->c
.i
== fc
; break;
5116 case TOK_NE
: v1
->c
.i
= v1
->c
.i
!= fc
; break;
5117 case TOK_ULE
: v1
->c
.i
= (unsigned)v1
->c
.i
<= (unsigned)fc
; break;
5118 case TOK_UGT
: v1
->c
.i
= (unsigned)v1
->c
.i
> (unsigned)fc
; break;
5119 case TOK_LT
: v1
->c
.i
= v1
->c
.i
< fc
; break;
5120 case TOK_GE
: v1
->c
.i
= v1
->c
.i
>= fc
; break;
5121 case TOK_LE
: v1
->c
.i
= v1
->c
.i
<= fc
; break;
5122 case TOK_GT
: v1
->c
.i
= v1
->c
.i
> fc
; break;
5124 case TOK_LAND
: v1
->c
.i
= v1
->c
.i
&& fc
; break;
5125 case TOK_LOR
: v1
->c
.i
= v1
->c
.i
|| fc
; break;
5131 /* if commutative ops, put c2 as constant */
5132 if (c1
&& (op
== '+' || op
== '&' || op
== '^' ||
5133 op
== '|' || op
== '*')) {
5138 if (c2
&& (((op
== '*' || op
== '/' || op
== TOK_UDIV
||
5141 ((op
== '+' || op
== '-' || op
== '|' || op
== '^' ||
5142 op
== TOK_SHL
|| op
== TOK_SHR
|| op
== TOK_SAR
) &&
5148 } else if (c2
&& (op
== '*' || op
== TOK_PDIV
|| op
== TOK_UDIV
)) {
5149 /* try to use shifts instead of muls or divs */
5150 if (fc
> 0 && (fc
& (fc
- 1)) == 0) {
5159 else if (op
== TOK_PDIV
)
5165 } else if (c2
&& (op
== '+' || op
== '-') &&
5166 (vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) ==
5167 (VT_CONST
| VT_SYM
)) {
5168 /* symbol + constant case */
5175 if (!nocode_wanted
) {
5176 /* call low level op generator */
5185 /* generate a floating point operation with constant propagation */
5186 void gen_opif(int op
)
5194 /* currently, we cannot do computations with forward symbols */
5195 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5196 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5198 if (v1
->type
.t
== VT_FLOAT
) {
5201 } else if (v1
->type
.t
== VT_DOUBLE
) {
5209 /* NOTE: we only do constant propagation if finite number (not
5210 NaN or infinity) (ANSI spec) */
5211 if (!ieee_finite(f1
) || !ieee_finite(f2
))
5215 case '+': f1
+= f2
; break;
5216 case '-': f1
-= f2
; break;
5217 case '*': f1
*= f2
; break;
5221 error("division by zero in constant");
5226 /* XXX: also handles tests ? */
5230 /* XXX: overflow test ? */
5231 if (v1
->type
.t
== VT_FLOAT
) {
5233 } else if (v1
->type
.t
== VT_DOUBLE
) {
5241 if (!nocode_wanted
) {
5249 static int pointed_size(CType
*type
)
5252 return type_size(pointed_type(type
), &align
);
5255 static inline int is_null_pointer(SValue
*p
)
5257 if ((p
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
5259 return ((p
->type
.t
& VT_BTYPE
) == VT_INT
&& p
->c
.i
== 0) ||
5260 ((p
->type
.t
& VT_BTYPE
) == VT_LLONG
&& p
->c
.ll
== 0);
5263 static inline int is_integer_btype(int bt
)
5265 return (bt
== VT_BYTE
|| bt
== VT_SHORT
||
5266 bt
== VT_INT
|| bt
== VT_LLONG
);
5269 /* check types for comparison or substraction of pointers */
5270 static void check_comparison_pointer_types(SValue
*p1
, SValue
*p2
, int op
)
5272 CType
*type1
, *type2
, tmp_type1
, tmp_type2
;
5275 /* null pointers are accepted for all comparisons as gcc */
5276 if (is_null_pointer(p1
) || is_null_pointer(p2
))
5280 bt1
= type1
->t
& VT_BTYPE
;
5281 bt2
= type2
->t
& VT_BTYPE
;
5282 /* accept comparison between pointer and integer with a warning */
5283 if ((is_integer_btype(bt1
) || is_integer_btype(bt2
)) && op
!= '-') {
5284 warning("comparison between pointer and integer");
5288 /* both must be pointers or implicit function pointers */
5289 if (bt1
== VT_PTR
) {
5290 type1
= pointed_type(type1
);
5291 } else if (bt1
!= VT_FUNC
)
5292 goto invalid_operands
;
5294 if (bt2
== VT_PTR
) {
5295 type2
= pointed_type(type2
);
5296 } else if (bt2
!= VT_FUNC
) {
5298 error("invalid operands to binary %s", get_tok_str(op
, NULL
));
5300 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
5301 (type2
->t
& VT_BTYPE
) == VT_VOID
)
5305 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5306 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5307 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
5308 /* gcc-like error if '-' is used */
5310 goto invalid_operands
;
5312 warning("comparison of distinct pointer types lacks a cast");
5316 /* generic gen_op: handles types problems */
5319 int u
, t1
, t2
, bt1
, bt2
, t
;
5322 t1
= vtop
[-1].type
.t
;
5323 t2
= vtop
[0].type
.t
;
5324 bt1
= t1
& VT_BTYPE
;
5325 bt2
= t2
& VT_BTYPE
;
5327 if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
5328 /* at least one operand is a pointer */
5329 /* relationnal op: must be both pointers */
5330 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5331 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5332 /* pointers are handled are unsigned */
5333 t
= VT_INT
| VT_UNSIGNED
;
5336 /* if both pointers, then it must be the '-' op */
5337 if (bt1
== VT_PTR
&& bt2
== VT_PTR
) {
5339 error("cannot use pointers here");
5340 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5341 /* XXX: check that types are compatible */
5342 u
= pointed_size(&vtop
[-1].type
);
5344 /* set to integer type */
5345 vtop
->type
.t
= VT_INT
;
5349 /* exactly one pointer : must be '+' or '-'. */
5350 if (op
!= '-' && op
!= '+')
5351 error("cannot use pointers here");
5352 /* Put pointer as first operand */
5353 if (bt2
== VT_PTR
) {
5357 type1
= vtop
[-1].type
;
5358 /* XXX: cast to int ? (long long case) */
5359 vpushi(pointed_size(&vtop
[-1].type
));
5361 #ifdef CONFIG_TCC_BCHECK
5362 /* if evaluating constant expression, no code should be
5363 generated, so no bound check */
5364 if (do_bounds_check
&& !const_wanted
) {
5365 /* if bounded pointers, we generate a special code to
5372 gen_bounded_ptr_add();
5378 /* put again type if gen_opic() swaped operands */
5381 } else if (is_float(bt1
) || is_float(bt2
)) {
5382 /* compute bigger type and do implicit casts */
5383 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
5385 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
5390 /* floats can only be used for a few operations */
5391 if (op
!= '+' && op
!= '-' && op
!= '*' && op
!= '/' &&
5392 (op
< TOK_ULT
|| op
> TOK_GT
))
5393 error("invalid operands for binary operation");
5395 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
5396 /* cast to biggest op */
5398 /* convert to unsigned if it does not fit in a long long */
5399 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
5400 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
5404 /* integer operations */
5406 /* convert to unsigned if it does not fit in an integer */
5407 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
5408 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
5411 /* XXX: currently, some unsigned operations are explicit, so
5412 we modify them here */
5413 if (t
& VT_UNSIGNED
) {
5420 else if (op
== TOK_LT
)
5422 else if (op
== TOK_GT
)
5424 else if (op
== TOK_LE
)
5426 else if (op
== TOK_GE
)
5433 /* special case for shifts and long long: we keep the shift as
5435 if (op
== TOK_SHR
|| op
== TOK_SAR
|| op
== TOK_SHL
)
5440 else if ((t
& VT_BTYPE
) == VT_LLONG
)
5444 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5445 /* relationnal op: the result is an int */
5446 vtop
->type
.t
= VT_INT
;
5453 /* generic itof for unsigned long long case */
5454 void gen_cvt_itof1(int t
)
5456 if ((vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
)) ==
5457 (VT_LLONG
| VT_UNSIGNED
)) {
5460 vpush_global_sym(&func_old_type
, TOK___ulltof
);
5461 else if (t
== VT_DOUBLE
)
5462 vpush_global_sym(&func_old_type
, TOK___ulltod
);
5464 vpush_global_sym(&func_old_type
, TOK___ulltold
);
5474 /* generic ftoi for unsigned long long case */
5475 void gen_cvt_ftoi1(int t
)
5479 if (t
== (VT_LLONG
| VT_UNSIGNED
)) {
5480 /* not handled natively */
5481 st
= vtop
->type
.t
& VT_BTYPE
;
5483 vpush_global_sym(&func_old_type
, TOK___fixunssfdi
);
5484 else if (st
== VT_DOUBLE
)
5485 vpush_global_sym(&func_old_type
, TOK___fixunsdfdi
);
5487 vpush_global_sym(&func_old_type
, TOK___fixunsxfdi
);
5492 vtop
->r2
= REG_LRET
;
5498 /* force char or short cast */
5499 void force_charshort_cast(int t
)
5503 /* XXX: add optimization if lvalue : just change type and offset */
5508 if (t
& VT_UNSIGNED
) {
5509 vpushi((1 << bits
) - 1);
5520 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
5521 static void gen_cast(CType
*type
)
5523 int sbt
, dbt
, sf
, df
, c
;
5525 /* special delayed cast for char/short */
5526 /* XXX: in some cases (multiple cascaded casts), it may still
5528 if (vtop
->r
& VT_MUSTCAST
) {
5529 vtop
->r
&= ~VT_MUSTCAST
;
5530 force_charshort_cast(vtop
->type
.t
);
5533 /* bitfields first get cast to ints */
5534 if (vtop
->type
.t
& VT_BITFIELD
) {
5538 dbt
= type
->t
& (VT_BTYPE
| VT_UNSIGNED
);
5539 sbt
= vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
);
5541 if (sbt
!= dbt
&& !nocode_wanted
) {
5544 c
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5546 /* convert from fp to fp */
5548 /* constant case: we can do it now */
5549 /* XXX: in ISOC, cannot do it if error in convert */
5550 if (dbt
== VT_FLOAT
&& sbt
== VT_DOUBLE
)
5551 vtop
->c
.f
= (float)vtop
->c
.d
;
5552 else if (dbt
== VT_FLOAT
&& sbt
== VT_LDOUBLE
)
5553 vtop
->c
.f
= (float)vtop
->c
.ld
;
5554 else if (dbt
== VT_DOUBLE
&& sbt
== VT_FLOAT
)
5555 vtop
->c
.d
= (double)vtop
->c
.f
;
5556 else if (dbt
== VT_DOUBLE
&& sbt
== VT_LDOUBLE
)
5557 vtop
->c
.d
= (double)vtop
->c
.ld
;
5558 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_FLOAT
)
5559 vtop
->c
.ld
= (long double)vtop
->c
.f
;
5560 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_DOUBLE
)
5561 vtop
->c
.ld
= (long double)vtop
->c
.d
;
5563 /* non constant case: generate code */
5567 /* convert int to fp */
5570 case VT_LLONG
| VT_UNSIGNED
:
5572 /* XXX: add const cases for long long */
5574 case VT_INT
| VT_UNSIGNED
:
5576 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.ui
; break;
5577 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.ui
; break;
5578 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.ui
; break;
5583 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.i
; break;
5584 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.i
; break;
5585 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.i
; break;
5591 #if !defined(TCC_TARGET_ARM)
5598 /* convert fp to int */
5599 /* we handle char/short/etc... with generic code */
5600 if (dbt
!= (VT_INT
| VT_UNSIGNED
) &&
5601 dbt
!= (VT_LLONG
| VT_UNSIGNED
) &&
5606 case VT_LLONG
| VT_UNSIGNED
:
5608 /* XXX: add const cases for long long */
5610 case VT_INT
| VT_UNSIGNED
:
5612 case VT_FLOAT
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5613 case VT_DOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5614 case VT_LDOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5620 case VT_FLOAT
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5621 case VT_DOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5622 case VT_LDOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5630 if (dbt
== VT_INT
&& (type
->t
& (VT_BTYPE
| VT_UNSIGNED
)) != dbt
) {
5631 /* additional cast for char/short/bool... */
5635 } else if ((dbt
& VT_BTYPE
) == VT_LLONG
) {
5636 if ((sbt
& VT_BTYPE
) != VT_LLONG
) {
5637 /* scalar to long long */
5639 if (sbt
== (VT_INT
| VT_UNSIGNED
))
5640 vtop
->c
.ll
= vtop
->c
.ui
;
5642 vtop
->c
.ll
= vtop
->c
.i
;
5644 /* machine independent conversion */
5646 /* generate high word */
5647 if (sbt
== (VT_INT
| VT_UNSIGNED
)) {
5655 /* patch second register */
5656 vtop
[-1].r2
= vtop
->r
;
5660 } else if (dbt
== VT_BOOL
) {
5661 /* scalar to bool */
5664 } else if ((dbt
& VT_BTYPE
) == VT_BYTE
||
5665 (dbt
& VT_BTYPE
) == VT_SHORT
) {
5666 force_charshort_cast(dbt
);
5667 } else if ((dbt
& VT_BTYPE
) == VT_INT
) {
5669 if (sbt
== VT_LLONG
) {
5670 /* from long long: just take low order word */
5674 /* if lvalue and single word type, nothing to do because
5675 the lvalue already contains the real type size (see
5676 VT_LVAL_xxx constants) */
5682 /* return type size. Put alignment at 'a' */
5683 static int type_size(CType
*type
, int *a
)
5688 bt
= type
->t
& VT_BTYPE
;
5689 if (bt
== VT_STRUCT
) {
5694 } else if (bt
== VT_PTR
) {
5695 if (type
->t
& VT_ARRAY
) {
5697 return type_size(&s
->type
, a
) * s
->c
;
5702 } else if (bt
== VT_LDOUBLE
) {
5704 return LDOUBLE_SIZE
;
5705 } else if (bt
== VT_DOUBLE
|| bt
== VT_LLONG
) {
5706 #ifdef TCC_TARGET_I386
5712 } else if (bt
== VT_INT
|| bt
== VT_ENUM
|| bt
== VT_FLOAT
) {
5715 } else if (bt
== VT_SHORT
) {
5719 /* char, void, function, _Bool */
5725 /* return the pointed type of t */
5726 static inline CType
*pointed_type(CType
*type
)
5728 return &type
->ref
->type
;
5731 /* modify type so that its it is a pointer to type. */
5732 static void mk_pointer(CType
*type
)
5735 s
= sym_push(SYM_FIELD
, type
, 0, -1);
5736 type
->t
= VT_PTR
| (type
->t
& ~VT_TYPE
);
5740 /* compare function types. OLD functions match any new functions */
5741 static int is_compatible_func(CType
*type1
, CType
*type2
)
5747 if (!is_compatible_types(&s1
->type
, &s2
->type
))
5749 /* XXX: not complete */
5750 if (s1
->c
== FUNC_OLD
|| s2
->c
== FUNC_OLD
)
5754 while (s1
!= NULL
) {
5757 if (!is_compatible_types(&s1
->type
, &s2
->type
))
5767 /* return true if type1 and type2 are exactly the same (including
5770 - enums are not checked as gcc __builtin_types_compatible_p ()
5772 static int is_compatible_types(CType
*type1
, CType
*type2
)
5776 t1
= type1
->t
& VT_TYPE
;
5777 t2
= type2
->t
& VT_TYPE
;
5778 /* XXX: bitfields ? */
5781 /* test more complicated cases */
5782 bt1
= t1
& VT_BTYPE
;
5783 if (bt1
== VT_PTR
) {
5784 type1
= pointed_type(type1
);
5785 type2
= pointed_type(type2
);
5786 return is_compatible_types(type1
, type2
);
5787 } else if (bt1
== VT_STRUCT
) {
5788 return (type1
->ref
== type2
->ref
);
5789 } else if (bt1
== VT_FUNC
) {
5790 return is_compatible_func(type1
, type2
);
5796 /* print a type. If 'varstr' is not NULL, then the variable is also
5797 printed in the type */
5799 /* XXX: add array and function pointers */
5800 void type_to_str(char *buf
, int buf_size
,
5801 CType
*type
, const char *varstr
)
5808 t
= type
->t
& VT_TYPE
;
5811 if (t
& VT_CONSTANT
)
5812 pstrcat(buf
, buf_size
, "const ");
5813 if (t
& VT_VOLATILE
)
5814 pstrcat(buf
, buf_size
, "volatile ");
5815 if (t
& VT_UNSIGNED
)
5816 pstrcat(buf
, buf_size
, "unsigned ");
5846 tstr
= "long double";
5848 pstrcat(buf
, buf_size
, tstr
);
5852 if (bt
== VT_STRUCT
)
5856 pstrcat(buf
, buf_size
, tstr
);
5857 v
= type
->ref
->v
& ~SYM_STRUCT
;
5858 if (v
>= SYM_FIRST_ANOM
)
5859 pstrcat(buf
, buf_size
, "<anonymous>");
5861 pstrcat(buf
, buf_size
, get_tok_str(v
, NULL
));
5865 type_to_str(buf
, buf_size
, &s
->type
, varstr
);
5866 pstrcat(buf
, buf_size
, "(");
5868 while (sa
!= NULL
) {
5869 type_to_str(buf1
, sizeof(buf1
), &sa
->type
, NULL
);
5870 pstrcat(buf
, buf_size
, buf1
);
5873 pstrcat(buf
, buf_size
, ", ");
5875 pstrcat(buf
, buf_size
, ")");
5879 pstrcpy(buf1
, sizeof(buf1
), "*");
5881 pstrcat(buf1
, sizeof(buf1
), varstr
);
5882 type_to_str(buf
, buf_size
, &s
->type
, buf1
);
5886 pstrcat(buf
, buf_size
, " ");
5887 pstrcat(buf
, buf_size
, varstr
);
5892 /* verify type compatibility to store vtop in 'dt' type, and generate
5894 static void gen_assign_cast(CType
*dt
)
5896 CType
*st
, *type1
, *type2
, tmp_type1
, tmp_type2
;
5897 char buf1
[256], buf2
[256];
5900 st
= &vtop
->type
; /* source type */
5901 dbt
= dt
->t
& VT_BTYPE
;
5902 sbt
= st
->t
& VT_BTYPE
;
5903 if (dt
->t
& VT_CONSTANT
)
5904 warning("assignment of read-only location");
5907 /* special cases for pointers */
5908 /* '0' can also be a pointer */
5909 if (is_null_pointer(vtop
))
5911 /* accept implicit pointer to integer cast with warning */
5912 if (is_integer_btype(sbt
)) {
5913 warning("assignment makes pointer from integer without a cast");
5916 type1
= pointed_type(dt
);
5917 /* a function is implicitely a function pointer */
5918 if (sbt
== VT_FUNC
) {
5919 if ((type1
->t
& VT_BTYPE
) != VT_VOID
&&
5920 !is_compatible_types(pointed_type(dt
), st
))
5927 type2
= pointed_type(st
);
5928 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
5929 (type2
->t
& VT_BTYPE
) == VT_VOID
) {
5930 /* void * can match anything */
5932 /* exact type match, except for unsigned */
5935 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5936 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5937 if (!is_compatible_types(&tmp_type1
, &tmp_type2
))
5940 /* check const and volatile */
5941 if ((!(type1
->t
& VT_CONSTANT
) && (type2
->t
& VT_CONSTANT
)) ||
5942 (!(type1
->t
& VT_VOLATILE
) && (type2
->t
& VT_VOLATILE
)))
5943 warning("assignment discards qualifiers from pointer target type");
5949 if (sbt
== VT_PTR
|| sbt
== VT_FUNC
) {
5950 warning("assignment makes integer from pointer without a cast");
5952 /* XXX: more tests */
5957 tmp_type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
5958 tmp_type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
5959 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
5961 type_to_str(buf1
, sizeof(buf1
), st
, NULL
);
5962 type_to_str(buf2
, sizeof(buf2
), dt
, NULL
);
5963 error("cannot cast '%s' to '%s'", buf1
, buf2
);
5971 /* store vtop in lvalue pushed on stack */
5974 int sbt
, dbt
, ft
, r
, t
, size
, align
, bit_size
, bit_pos
, rc
, delayed_cast
;
5976 ft
= vtop
[-1].type
.t
;
5977 sbt
= vtop
->type
.t
& VT_BTYPE
;
5978 dbt
= ft
& VT_BTYPE
;
5979 if (((sbt
== VT_INT
|| sbt
== VT_SHORT
) && dbt
== VT_BYTE
) ||
5980 (sbt
== VT_INT
&& dbt
== VT_SHORT
)) {
5981 /* optimize char/short casts */
5982 delayed_cast
= VT_MUSTCAST
;
5983 vtop
->type
.t
= ft
& VT_TYPE
;
5984 /* XXX: factorize */
5985 if (ft
& VT_CONSTANT
)
5986 warning("assignment of read-only location");
5989 gen_assign_cast(&vtop
[-1].type
);
5992 if (sbt
== VT_STRUCT
) {
5993 /* if structure, only generate pointer */
5994 /* structure assignment : generate memcpy */
5995 /* XXX: optimize if small size */
5996 if (!nocode_wanted
) {
5997 size
= type_size(&vtop
->type
, &align
);
5999 vpush_global_sym(&func_old_type
, TOK_memcpy
);
6003 vtop
->type
.t
= VT_INT
;
6007 vtop
->type
.t
= VT_INT
;
6019 /* leave source on stack */
6020 } else if (ft
& VT_BITFIELD
) {
6021 /* bitfield store handling */
6022 bit_pos
= (ft
>> VT_STRUCT_SHIFT
) & 0x3f;
6023 bit_size
= (ft
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
6024 /* remove bit field info to avoid loops */
6025 vtop
[-1].type
.t
= ft
& ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
6027 /* duplicate destination */
6029 vtop
[-1] = vtop
[-2];
6031 /* mask and shift source */
6032 vpushi((1 << bit_size
) - 1);
6036 /* load destination, mask and or with source */
6038 vpushi(~(((1 << bit_size
) - 1) << bit_pos
));
6044 #ifdef CONFIG_TCC_BCHECK
6045 /* bound check case */
6046 if (vtop
[-1].r
& VT_MUSTBOUND
) {
6052 if (!nocode_wanted
) {
6056 r
= gv(rc
); /* generate value */
6057 /* if lvalue was saved on stack, must read it */
6058 if ((vtop
[-1].r
& VT_VALMASK
) == VT_LLOCAL
) {
6060 t
= get_reg(RC_INT
);
6062 sv
.r
= VT_LOCAL
| VT_LVAL
;
6063 sv
.c
.ul
= vtop
[-1].c
.ul
;
6065 vtop
[-1].r
= t
| VT_LVAL
;
6068 /* two word case handling : store second register at word + 4 */
6069 if ((ft
& VT_BTYPE
) == VT_LLONG
) {
6071 /* convert to int to increment easily */
6072 vtop
->type
.t
= VT_INT
;
6078 /* XXX: it works because r2 is spilled last ! */
6079 store(vtop
->r2
, vtop
- 1);
6083 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
6084 vtop
->r
|= delayed_cast
;
6088 /* post defines POST/PRE add. c is the token ++ or -- */
6089 void inc(int post
, int c
)
6092 vdup(); /* save lvalue */
6094 gv_dup(); /* duplicate value */
6099 vpushi(c
- TOK_MID
);
6101 vstore(); /* store value */
6103 vpop(); /* if post op, return saved value */
6106 /* Parse GNUC __attribute__ extension. Currently, the following
6107 extensions are recognized:
6108 - aligned(n) : set data/function alignment.
6109 - section(x) : generate data/code in this section.
6110 - unused : currently ignored, but may be used someday.
6112 static void parse_attribute(AttributeDef
*ad
)
6116 while (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
) {
6120 while (tok
!= ')') {
6121 if (tok
< TOK_IDENT
)
6122 expect("attribute name");
6130 expect("section name");
6131 ad
->section
= find_section(tcc_state
, (char *)tokc
.cstr
->data
);
6140 if (n
<= 0 || (n
& (n
- 1)) != 0)
6141 error("alignment must be a positive power of two");
6150 /* currently, no need to handle it because tcc does not
6151 track unused objects */
6155 /* currently, no need to handle it because tcc does not
6156 track unused objects */
6161 ad
->func_call
= FUNC_CDECL
;
6166 ad
->func_call
= FUNC_STDCALL
;
6169 if (tcc_state
->warn_unsupported
)
6170 warning("'%s' attribute ignored", get_tok_str(t
, NULL
));
6171 /* skip parameters */
6172 /* XXX: skip parenthesis too */
6175 while (tok
!= ')' && tok
!= -1)
6190 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
6191 static void struct_decl(CType
*type
, int u
)
6193 int a
, v
, size
, align
, maxalign
, c
, offset
;
6194 int bit_size
, bit_pos
, bsize
, bt
, lbit_pos
;
6199 a
= tok
; /* save decl type */
6204 /* struct already defined ? return it */
6206 expect("struct/union/enum name");
6210 error("invalid type");
6217 /* we put an undefined size for struct/union */
6218 s
= sym_push(v
| SYM_STRUCT
, &type1
, 0, -1);
6219 s
->r
= 0; /* default alignment is zero as gcc */
6220 /* put struct/union/enum name in type */
6228 error("struct/union/enum already defined");
6229 /* cannot be empty */
6231 /* non empty enums are not allowed */
6232 if (a
== TOK_ENUM
) {
6236 expect("identifier");
6242 /* enum symbols have static storage */
6243 ss
= sym_push(v
, &int_type
, VT_CONST
, c
);
6244 ss
->type
.t
|= VT_STATIC
;
6249 /* NOTE: we accept a trailing comma */
6259 while (tok
!= '}') {
6260 parse_btype(&btype
, &ad
);
6266 type_decl(&type1
, &ad
, &v
, TYPE_DIRECT
);
6267 if ((type1
.t
& VT_BTYPE
) == VT_FUNC
||
6268 (type1
.t
& (VT_TYPEDEF
| VT_STATIC
| VT_EXTERN
| VT_INLINE
)))
6269 error("invalid type for '%s'",
6270 get_tok_str(v
, NULL
));
6274 bit_size
= expr_const();
6275 /* XXX: handle v = 0 case for messages */
6277 error("negative width in bit-field '%s'",
6278 get_tok_str(v
, NULL
));
6279 if (v
&& bit_size
== 0)
6280 error("zero width for bit-field '%s'",
6281 get_tok_str(v
, NULL
));
6283 size
= type_size(&type1
, &align
);
6285 if (bit_size
>= 0) {
6286 bt
= type1
.t
& VT_BTYPE
;
6291 error("bitfields must have scalar type");
6293 if (bit_size
> bsize
) {
6294 error("width of '%s' exceeds its type",
6295 get_tok_str(v
, NULL
));
6296 } else if (bit_size
== bsize
) {
6297 /* no need for bit fields */
6299 } else if (bit_size
== 0) {
6300 /* XXX: what to do if only padding in a
6302 /* zero size: means to pad */
6306 /* we do not have enough room ? */
6307 if ((bit_pos
+ bit_size
) > bsize
)
6310 /* XXX: handle LSB first */
6311 type1
.t
|= VT_BITFIELD
|
6312 (bit_pos
<< VT_STRUCT_SHIFT
) |
6313 (bit_size
<< (VT_STRUCT_SHIFT
+ 6));
6314 bit_pos
+= bit_size
;
6320 /* add new memory data only if starting
6322 if (lbit_pos
== 0) {
6323 if (a
== TOK_STRUCT
) {
6324 c
= (c
+ align
- 1) & -align
;
6332 if (align
> maxalign
)
6336 printf("add field %s offset=%d",
6337 get_tok_str(v
, NULL
), offset
);
6338 if (type1
.t
& VT_BITFIELD
) {
6339 printf(" pos=%d size=%d",
6340 (type1
.t
>> VT_STRUCT_SHIFT
) & 0x3f,
6341 (type1
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f);
6345 ss
= sym_push(v
| SYM_FIELD
, &type1
, 0, offset
);
6349 if (tok
== ';' || tok
== TOK_EOF
)
6356 /* store size and alignment */
6357 s
->c
= (c
+ maxalign
- 1) & -maxalign
;
6363 /* return 0 if no type declaration. otherwise, return the basic type
6366 static int parse_btype(CType
*type
, AttributeDef
*ad
)
6368 int t
, u
, type_found
, typespec_found
;
6372 memset(ad
, 0, sizeof(AttributeDef
));
6379 /* currently, we really ignore extension */
6389 if ((t
& VT_BTYPE
) != 0)
6390 error("too many basic types");
6406 if ((t
& VT_BTYPE
) == VT_DOUBLE
) {
6407 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6408 } else if ((t
& VT_BTYPE
) == VT_LONG
) {
6409 t
= (t
& ~VT_BTYPE
) | VT_LLONG
;
6423 if ((t
& VT_BTYPE
) == VT_LONG
) {
6424 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6431 struct_decl(&type1
, VT_ENUM
);
6434 type
->ref
= type1
.ref
;
6438 struct_decl(&type1
, VT_STRUCT
);
6441 /* type modifiers */
6494 /* GNUC attribute */
6495 case TOK_ATTRIBUTE1
:
6496 case TOK_ATTRIBUTE2
:
6497 parse_attribute(ad
);
6504 parse_expr_type(&type1
);
6510 if (!s
|| !(s
->type
.t
& VT_TYPEDEF
))
6512 t
|= (s
->type
.t
& ~VT_TYPEDEF
);
6513 type
->ref
= s
->type
.ref
;
6520 if ((t
& (VT_SIGNED
|VT_UNSIGNED
)) == (VT_SIGNED
|VT_UNSIGNED
))
6521 error("signed and unsigned modifier");
6522 if (tcc_state
->char_is_unsigned
) {
6523 if ((t
& (VT_SIGNED
|VT_UNSIGNED
|VT_BTYPE
)) == VT_BYTE
)
6528 /* long is never used as type */
6529 if ((t
& VT_BTYPE
) == VT_LONG
)
6530 t
= (t
& ~VT_BTYPE
) | VT_INT
;
6535 /* convert a function parameter type (array to pointer and function to
6536 function pointer) */
6537 static inline void convert_parameter_type(CType
*pt
)
6539 /* array must be transformed to pointer according to ANSI C */
6541 if ((pt
->t
& VT_BTYPE
) == VT_FUNC
) {
6546 static void post_type(CType
*type
, AttributeDef
*ad
)
6549 Sym
**plast
, *s
, *first
;
6554 /* function declaration */
6559 while (tok
!= ')') {
6560 /* read param name and compute offset */
6561 if (l
!= FUNC_OLD
) {
6562 if (!parse_btype(&pt
, &ad1
)) {
6564 error("invalid type");
6571 if ((pt
.t
& VT_BTYPE
) == VT_VOID
&& tok
== ')')
6573 type_decl(&pt
, &ad1
, &n
, TYPE_DIRECT
| TYPE_ABSTRACT
);
6574 if ((pt
.t
& VT_BTYPE
) == VT_VOID
)
6575 error("parameter declared as void");
6582 convert_parameter_type(&pt
);
6583 s
= sym_push(n
| SYM_FIELD
, &pt
, 0, 0);
6588 if (l
== FUNC_NEW
&& tok
== TOK_DOTS
) {
6595 /* if no parameters, then old type prototype */
6599 t1
= type
->t
& VT_STORAGE
;
6600 /* NOTE: const is ignored in returned type as it has a special
6601 meaning in gcc / C++ */
6602 type
->t
&= ~(VT_STORAGE
| VT_CONSTANT
);
6603 post_type(type
, ad
);
6604 /* we push a anonymous symbol which will contain the function prototype */
6605 s
= sym_push(SYM_FIELD
, type
, ad
->func_call
, l
);
6607 type
->t
= t1
| VT_FUNC
;
6609 } else if (tok
== '[') {
6610 /* array definition */
6616 error("invalid array size");
6619 /* parse next post type */
6620 t1
= type
->t
& VT_STORAGE
;
6621 type
->t
&= ~VT_STORAGE
;
6622 post_type(type
, ad
);
6624 /* we push a anonymous symbol which will contain the array
6626 s
= sym_push(SYM_FIELD
, type
, 0, n
);
6627 type
->t
= t1
| VT_ARRAY
| VT_PTR
;
6632 /* Parse a type declaration (except basic type), and return the type
6633 in 'type'. 'td' is a bitmask indicating which kind of type decl is
6634 expected. 'type' should contain the basic type. 'ad' is the
6635 attribute definition of the basic type. It can be modified by
6638 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
)
6641 CType type1
, *type2
;
6644 while (tok
== '*') {
6652 qualifiers
|= VT_CONSTANT
;
6657 qualifiers
|= VT_VOLATILE
;
6665 type
->t
|= qualifiers
;
6668 /* XXX: clarify attribute handling */
6669 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6670 parse_attribute(ad
);
6672 /* recursive type */
6673 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
6674 type1
.t
= 0; /* XXX: same as int */
6677 /* XXX: this is not correct to modify 'ad' at this point, but
6678 the syntax is not clear */
6679 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6680 parse_attribute(ad
);
6681 type_decl(&type1
, ad
, v
, td
);
6684 /* type identifier */
6685 if (tok
>= TOK_IDENT
&& (td
& TYPE_DIRECT
)) {
6689 if (!(td
& TYPE_ABSTRACT
))
6690 expect("identifier");
6694 post_type(type
, ad
);
6695 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6696 parse_attribute(ad
);
6699 /* append type at the end of type1 */
6712 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
6713 static int lvalue_type(int t
)
6718 if (bt
== VT_BYTE
|| bt
== VT_BOOL
)
6720 else if (bt
== VT_SHORT
)
6724 if (t
& VT_UNSIGNED
)
6725 r
|= VT_LVAL_UNSIGNED
;
6729 /* indirection with full error checking and bound check */
6730 static void indir(void)
6732 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
6734 if ((vtop
->r
& VT_LVAL
) && !nocode_wanted
)
6736 vtop
->type
= *pointed_type(&vtop
->type
);
6737 /* an array is never an lvalue */
6738 if (!(vtop
->type
.t
& VT_ARRAY
)) {
6739 vtop
->r
|= lvalue_type(vtop
->type
.t
);
6740 /* if bound checking, the referenced pointer must be checked */
6741 if (do_bounds_check
)
6742 vtop
->r
|= VT_MUSTBOUND
;
6746 /* pass a parameter to a function and do type checking and casting */
6747 static void gfunc_param_typed(Sym
*func
, Sym
*arg
)
6752 func_type
= func
->c
;
6753 if (func_type
== FUNC_OLD
||
6754 (func_type
== FUNC_ELLIPSIS
&& arg
== NULL
)) {
6755 /* default casting : only need to convert float to double */
6756 if ((vtop
->type
.t
& VT_BTYPE
) == VT_FLOAT
) {
6760 } else if (arg
== NULL
) {
6761 error("too many arguments to function");
6764 type
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
6765 gen_assign_cast(&type
);
6769 /* parse an expression of the form '(type)' or '(expr)' and return its
6771 static void parse_expr_type(CType
*type
)
6777 if (parse_btype(type
, &ad
)) {
6778 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
6785 static void parse_type(CType
*type
)
6790 if (!parse_btype(type
, &ad
)) {
6793 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
6796 static void vpush_tokc(int t
)
6800 vsetc(&type
, VT_CONST
, &tokc
);
6803 static void unary(void)
6805 int n
, t
, align
, size
, r
;
6810 /* XXX: GCC 2.95.3 does not generate a table although it should be
6824 vpush_tokc(VT_INT
| VT_UNSIGNED
);
6828 vpush_tokc(VT_LLONG
);
6832 vpush_tokc(VT_LLONG
| VT_UNSIGNED
);
6836 vpush_tokc(VT_FLOAT
);
6840 vpush_tokc(VT_DOUBLE
);
6844 vpush_tokc(VT_LDOUBLE
);
6847 case TOK___FUNCTION__
:
6849 goto tok_identifier
;
6855 /* special function name identifier */
6856 len
= strlen(funcname
) + 1;
6857 /* generate char[len] type */
6862 vpush_ref(&type
, data_section
, data_section
->data_offset
, len
);
6863 ptr
= section_ptr_add(data_section
, len
);
6864 memcpy(ptr
, funcname
, len
);
6872 /* string parsing */
6875 if (tcc_state
->warn_write_strings
)
6880 memset(&ad
, 0, sizeof(AttributeDef
));
6881 decl_initializer_alloc(&type
, &ad
, VT_CONST
, 2, 0, 0);
6886 if (parse_btype(&type
, &ad
)) {
6887 type_decl(&type
, &ad
, &n
, TYPE_ABSTRACT
);
6889 /* check ISOC99 compound literal */
6891 /* data is allocated locally by default */
6896 /* all except arrays are lvalues */
6897 if (!(type
.t
& VT_ARRAY
))
6898 r
|= lvalue_type(type
.t
);
6899 memset(&ad
, 0, sizeof(AttributeDef
));
6900 decl_initializer_alloc(&type
, &ad
, r
, 1, 0, 0);
6905 } else if (tok
== '{') {
6906 /* save all registers */
6908 /* statement expression : we do not accept break/continue
6909 inside as GCC does */
6910 block(NULL
, NULL
, NULL
, NULL
, 0, 1);
6925 /* functions names must be treated as function pointers,
6926 except for unary '&' and sizeof. Since we consider that
6927 functions are not lvalues, we only have to handle it
6928 there and in function calls. */
6929 /* arrays can also be used although they are not lvalues */
6930 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
&&
6931 !(vtop
->type
.t
& VT_ARRAY
))
6933 mk_pointer(&vtop
->type
);
6939 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
)
6940 vtop
->c
.i
= !vtop
->c
.i
;
6941 else if ((vtop
->r
& VT_VALMASK
) == VT_CMP
)
6942 vtop
->c
.i
= vtop
->c
.i
^ 1;
6944 vseti(VT_JMP
, gtst(1, 0));
6954 /* in order to force cast, we add zero */
6956 if ((vtop
->type
.t
& VT_BTYPE
) == VT_PTR
)
6957 error("pointer not accepted for unary plus");
6967 parse_expr_type(&type
);
6971 size
= type_size(&type
, &align
);
6972 if (t
== TOK_SIZEOF
) {
6974 error("sizeof applied to an incomplete type");
6981 case TOK_builtin_types_compatible_p
:
6990 type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6991 type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6992 vpushi(is_compatible_types(&type1
, &type2
));
6995 case TOK_builtin_constant_p
:
6997 int saved_nocode_wanted
, res
;
7000 saved_nocode_wanted
= nocode_wanted
;
7003 res
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
7005 nocode_wanted
= saved_nocode_wanted
;
7025 goto tok_identifier
;
7027 /* allow to take the address of a label */
7028 if (tok
< TOK_UIDENT
)
7029 expect("label identifier");
7030 s
= label_find(tok
);
7032 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
7034 if (s
->r
== LABEL_DECLARED
)
7035 s
->r
= LABEL_FORWARD
;
7038 s
->type
.t
= VT_VOID
;
7039 mk_pointer(&s
->type
);
7040 s
->type
.t
|= VT_STATIC
;
7042 vset(&s
->type
, VT_CONST
| VT_SYM
, 0);
7051 expect("identifier");
7055 error("'%s' undeclared", get_tok_str(t
, NULL
));
7056 /* for simple function calls, we tolerate undeclared
7057 external reference to int() function */
7058 if (tcc_state
->warn_implicit_function_declaration
)
7059 warning("implicit declaration of function '%s'",
7060 get_tok_str(t
, NULL
));
7061 s
= external_global_sym(t
, &func_old_type
, 0);
7063 vset(&s
->type
, s
->r
, s
->c
);
7064 /* if forward reference, we must point to s */
7065 if (vtop
->r
& VT_SYM
) {
7072 /* post operations */
7074 if (tok
== TOK_INC
|| tok
== TOK_DEC
) {
7077 } else if (tok
== '.' || tok
== TOK_ARROW
) {
7079 if (tok
== TOK_ARROW
)
7084 /* expect pointer on structure */
7085 if ((vtop
->type
.t
& VT_BTYPE
) != VT_STRUCT
)
7086 expect("struct or union");
7090 while ((s
= s
->next
) != NULL
) {
7095 error("field not found");
7096 /* add field offset to pointer */
7097 vtop
->type
= char_pointer_type
; /* change type to 'char *' */
7100 /* change type to field type, and set to lvalue */
7101 vtop
->type
= s
->type
;
7102 /* an array is never an lvalue */
7103 if (!(vtop
->type
.t
& VT_ARRAY
)) {
7104 vtop
->r
|= lvalue_type(vtop
->type
.t
);
7105 /* if bound checking, the referenced pointer must be checked */
7106 if (do_bounds_check
)
7107 vtop
->r
|= VT_MUSTBOUND
;
7110 } else if (tok
== '[') {
7116 } else if (tok
== '(') {
7122 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
) {
7123 /* pointer test (no array accepted) */
7124 if ((vtop
->type
.t
& (VT_BTYPE
| VT_ARRAY
)) == VT_PTR
) {
7125 vtop
->type
= *pointed_type(&vtop
->type
);
7126 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
)
7130 expect("function pointer");
7133 vtop
->r
&= ~VT_LVAL
; /* no lvalue */
7135 /* get return type */
7138 sa
= s
->next
; /* first parameter */
7140 /* compute first implicit argument if a structure is returned */
7141 if ((s
->type
.t
& VT_BTYPE
) == VT_STRUCT
) {
7142 /* get some space for the returned structure */
7143 size
= type_size(&s
->type
, &align
);
7144 loc
= (loc
- size
) & -align
;
7146 ret
.r
= VT_LOCAL
| VT_LVAL
;
7147 /* pass it as 'int' to avoid structure arg passing
7149 vseti(VT_LOCAL
, loc
);
7155 /* return in register */
7156 if (is_float(ret
.type
.t
)) {
7159 if ((ret
.type
.t
& VT_BTYPE
) == VT_LLONG
)
7168 gfunc_param_typed(s
, sa
);
7178 error("too few arguments to function");
7180 if (!nocode_wanted
) {
7181 gfunc_call(nb_args
);
7183 vtop
-= (nb_args
+ 1);
7186 vsetc(&ret
.type
, ret
.r
, &ret
.c
);
7194 static void uneq(void)
7200 (tok
>= TOK_A_MOD
&& tok
<= TOK_A_DIV
) ||
7201 tok
== TOK_A_XOR
|| tok
== TOK_A_OR
||
7202 tok
== TOK_A_SHL
|| tok
== TOK_A_SAR
) {
7217 static void expr_prod(void)
7222 while (tok
== '*' || tok
== '/' || tok
== '%') {
7230 static void expr_sum(void)
7235 while (tok
== '+' || tok
== '-') {
7243 static void expr_shift(void)
7248 while (tok
== TOK_SHL
|| tok
== TOK_SAR
) {
7256 static void expr_cmp(void)
7261 while ((tok
>= TOK_ULE
&& tok
<= TOK_GT
) ||
7262 tok
== TOK_ULT
|| tok
== TOK_UGE
) {
7270 static void expr_cmpeq(void)
7275 while (tok
== TOK_EQ
|| tok
== TOK_NE
) {
7283 static void expr_and(void)
7286 while (tok
== '&') {
7293 static void expr_xor(void)
7296 while (tok
== '^') {
7303 static void expr_or(void)
7306 while (tok
== '|') {
7313 /* XXX: fix this mess */
7314 static void expr_land_const(void)
7317 while (tok
== TOK_LAND
) {
7324 /* XXX: fix this mess */
7325 static void expr_lor_const(void)
7328 while (tok
== TOK_LOR
) {
7335 /* only used if non constant */
7336 static void expr_land(void)
7341 if (tok
== TOK_LAND
) {
7345 if (tok
!= TOK_LAND
) {
7355 static void expr_lor(void)
7360 if (tok
== TOK_LOR
) {
7364 if (tok
!= TOK_LOR
) {
7374 /* XXX: better constant handling */
7375 static void expr_eq(void)
7377 int tt
, u
, r1
, r2
, rc
, t1
, t2
, bt1
, bt2
;
7379 CType type
, type1
, type2
;
7388 if (tok
== ':' && gnu_ext
) {
7404 if (vtop
!= vstack
) {
7405 /* needed to avoid having different registers saved in
7407 if (is_float(vtop
->type
.t
))
7414 if (tok
== ':' && gnu_ext
) {
7422 sv
= *vtop
; /* save value to handle it later */
7423 vtop
--; /* no vpop so that FP stack is not flushed */
7431 bt1
= t1
& VT_BTYPE
;
7433 bt2
= t2
& VT_BTYPE
;
7434 /* cast operands to correct type according to ISOC rules */
7435 if (is_float(bt1
) || is_float(bt2
)) {
7436 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
7437 type
.t
= VT_LDOUBLE
;
7438 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
7443 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
7444 /* cast to biggest op */
7446 /* convert to unsigned if it does not fit in a long long */
7447 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
7448 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
7449 type
.t
|= VT_UNSIGNED
;
7450 } else if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
7451 /* XXX: test pointer compatibility */
7453 } else if (bt1
== VT_STRUCT
|| bt2
== VT_STRUCT
) {
7454 /* XXX: test structure compatibility */
7456 } else if (bt1
== VT_VOID
|| bt2
== VT_VOID
) {
7457 /* NOTE: as an extension, we accept void on only one side */
7460 /* integer operations */
7462 /* convert to unsigned if it does not fit in an integer */
7463 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
7464 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
7465 type
.t
|= VT_UNSIGNED
;
7468 /* now we convert second operand */
7471 if (is_float(type
.t
)) {
7473 } else if ((type
.t
& VT_BTYPE
) == VT_LLONG
) {
7474 /* for long longs, we use fixed registers to avoid having
7475 to handle a complicated move */
7480 /* this is horrible, but we must also convert first
7484 /* put again first value and cast it */
7495 static void gexpr(void)
7506 /* parse an expression and return its type without any side effect. */
7507 static void expr_type(CType
*type
)
7509 int saved_nocode_wanted
;
7511 saved_nocode_wanted
= nocode_wanted
;
7516 nocode_wanted
= saved_nocode_wanted
;
7519 /* parse a unary expression and return its type without any side
7521 static void unary_type(CType
*type
)
7533 /* parse a constant expression and return value in vtop. */
7534 static void expr_const1(void)
7543 /* parse an integer constant and return its value. */
7544 static int expr_const(void)
7548 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
7549 expect("constant expression");
7555 /* return the label token if current token is a label, otherwise
7557 static int is_label(void)
7561 /* fast test first */
7562 if (tok
< TOK_UIDENT
)
7564 /* no need to save tokc because tok is an identifier */
7571 unget_tok(last_tok
);
7576 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
7577 int case_reg
, int is_expr
)
7582 /* generate line number info */
7584 (last_line_num
!= file
->line_num
|| last_ind
!= ind
)) {
7585 put_stabn(N_SLINE
, 0, file
->line_num
, ind
- func_ind
);
7587 last_line_num
= file
->line_num
;
7591 /* default return value is (void) */
7593 vtop
->type
.t
= VT_VOID
;
7596 if (tok
== TOK_IF
) {
7603 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7605 if (c
== TOK_ELSE
) {
7609 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7610 gsym(d
); /* patch else jmp */
7613 } else if (tok
== TOK_WHILE
) {
7621 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7625 } else if (tok
== '{') {
7629 /* record local declaration stack position */
7631 llabel
= local_label_stack
;
7632 /* handle local labels declarations */
7633 if (tok
== TOK_LABEL
) {
7636 if (tok
< TOK_UIDENT
)
7637 expect("label identifier");
7638 label_push(&local_label_stack
, tok
, LABEL_DECLARED
);
7648 while (tok
!= '}') {
7653 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
7656 /* pop locally defined labels */
7657 label_pop(&local_label_stack
, llabel
);
7658 /* pop locally defined symbols */
7659 sym_pop(&local_stack
, s
);
7661 } else if (tok
== TOK_RETURN
) {
7665 gen_assign_cast(&func_vt
);
7666 if ((func_vt
.t
& VT_BTYPE
) == VT_STRUCT
) {
7668 /* if returning structure, must copy it to implicit
7669 first pointer arg location */
7672 vset(&type
, VT_LOCAL
| VT_LVAL
, func_vc
);
7675 /* copy structure value to pointer */
7677 } else if (is_float(func_vt
.t
)) {
7682 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
7685 rsym
= gjmp(rsym
); /* jmp */
7686 } else if (tok
== TOK_BREAK
) {
7689 error("cannot break");
7690 *bsym
= gjmp(*bsym
);
7693 } else if (tok
== TOK_CONTINUE
) {
7696 error("cannot continue");
7697 *csym
= gjmp(*csym
);
7700 } else if (tok
== TOK_FOR
) {
7727 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7732 if (tok
== TOK_DO
) {
7737 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7748 if (tok
== TOK_SWITCH
) {
7752 /* XXX: other types than integer */
7753 case_reg
= gv(RC_INT
);
7757 b
= gjmp(0); /* jump to first case */
7759 block(&a
, csym
, &b
, &c
, case_reg
, 0);
7760 /* if no default, jmp after switch */
7768 if (tok
== TOK_CASE
) {
7775 if (gnu_ext
&& tok
== TOK_DOTS
) {
7779 warning("empty case range");
7781 /* since a case is like a label, we must skip it with a jmp */
7788 *case_sym
= gtst(1, 0);
7791 *case_sym
= gtst(1, 0);
7795 *case_sym
= gtst(1, *case_sym
);
7800 goto block_after_label
;
7802 if (tok
== TOK_DEFAULT
) {
7808 error("too many 'default'");
7811 goto block_after_label
;
7813 if (tok
== TOK_GOTO
) {
7815 if (tok
== '*' && gnu_ext
) {
7819 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
7822 } else if (tok
>= TOK_UIDENT
) {
7823 s
= label_find(tok
);
7824 /* put forward definition if needed */
7826 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
7828 if (s
->r
== LABEL_DECLARED
)
7829 s
->r
= LABEL_FORWARD
;
7831 /* label already defined */
7832 if (s
->r
& LABEL_FORWARD
)
7833 s
->next
= (void *)gjmp((long)s
->next
);
7835 gjmp_addr((long)s
->next
);
7838 expect("label identifier");
7841 } else if (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
) {
7849 if (s
->r
== LABEL_DEFINED
)
7850 error("duplicate label '%s'", get_tok_str(s
->v
, NULL
));
7851 gsym((long)s
->next
);
7852 s
->r
= LABEL_DEFINED
;
7854 s
= label_push(&global_label_stack
, b
, LABEL_DEFINED
);
7856 s
->next
= (void *)ind
;
7857 /* we accept this, but it is a mistake */
7860 warning("deprecated use of label at end of compound statement");
7864 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
7867 /* expression case */
7882 /* t is the array or struct type. c is the array or struct
7883 address. cur_index/cur_field is the pointer to the current
7884 value. 'size_only' is true if only size info is needed (only used
7886 static void decl_designator(CType
*type
, Section
*sec
, unsigned long c
,
7887 int *cur_index
, Sym
**cur_field
,
7891 int notfirst
, index
, index_last
, align
, l
, nb_elems
, elem_size
;
7897 if (gnu_ext
&& (l
= is_label()) != 0)
7899 while (tok
== '[' || tok
== '.') {
7901 if (!(type
->t
& VT_ARRAY
))
7902 expect("array type");
7905 index
= expr_const();
7906 if (index
< 0 || (s
->c
>= 0 && index
>= s
->c
))
7907 expect("invalid index");
7908 if (tok
== TOK_DOTS
&& gnu_ext
) {
7910 index_last
= expr_const();
7911 if (index_last
< 0 ||
7912 (s
->c
>= 0 && index_last
>= s
->c
) ||
7914 expect("invalid index");
7920 *cur_index
= index_last
;
7921 type
= pointed_type(type
);
7922 elem_size
= type_size(type
, &align
);
7923 c
+= index
* elem_size
;
7924 /* NOTE: we only support ranges for last designator */
7925 nb_elems
= index_last
- index
+ 1;
7926 if (nb_elems
!= 1) {
7935 if ((type
->t
& VT_BTYPE
) != VT_STRUCT
)
7936 expect("struct/union type");
7949 /* XXX: fix this mess by using explicit storage field */
7951 type1
.t
|= (type
->t
& ~VT_TYPE
);
7965 if (type
->t
& VT_ARRAY
) {
7967 type
= pointed_type(type
);
7968 c
+= index
* type_size(type
, &align
);
7972 error("too many field init");
7973 /* XXX: fix this mess by using explicit storage field */
7975 type1
.t
|= (type
->t
& ~VT_TYPE
);
7980 decl_initializer(type
, sec
, c
, 0, size_only
);
7982 /* XXX: make it more general */
7983 if (!size_only
&& nb_elems
> 1) {
7984 unsigned long c_end
;
7989 error("range init not supported yet for dynamic storage");
7990 c_end
= c
+ nb_elems
* elem_size
;
7991 if (c_end
> sec
->data_allocated
)
7992 section_realloc(sec
, c_end
);
7993 src
= sec
->data
+ c
;
7995 for(i
= 1; i
< nb_elems
; i
++) {
7997 memcpy(dst
, src
, elem_size
);
8003 #define EXPR_CONST 1
8006 /* store a value or an expression directly in global data or in local array */
8007 static void init_putv(CType
*type
, Section
*sec
, unsigned long c
,
8008 int v
, int expr_type
)
8010 int saved_global_expr
, bt
, bit_pos
, bit_size
;
8012 unsigned long long bit_mask
;
8020 /* compound literals must be allocated globally in this case */
8021 saved_global_expr
= global_expr
;
8024 global_expr
= saved_global_expr
;
8025 /* NOTE: symbols are accepted */
8026 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) != VT_CONST
)
8027 error("initializer element is not constant");
8035 dtype
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
8038 /* XXX: not portable */
8039 /* XXX: generate error if incorrect relocation */
8040 gen_assign_cast(&dtype
);
8041 bt
= type
->t
& VT_BTYPE
;
8042 ptr
= sec
->data
+ c
;
8043 /* XXX: make code faster ? */
8044 if (!(type
->t
& VT_BITFIELD
)) {
8049 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
8050 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
8051 bit_mask
= (1LL << bit_size
) - 1;
8053 if ((vtop
->r
& VT_SYM
) &&
8059 (bt
== VT_INT
&& bit_size
!= 32)))
8060 error("initializer element is not computable at load time");
8063 *(char *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8066 *(short *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8069 *(double *)ptr
= vtop
->c
.d
;
8072 *(long double *)ptr
= vtop
->c
.ld
;
8075 *(long long *)ptr
|= (vtop
->c
.ll
& bit_mask
) << bit_pos
;
8078 if (vtop
->r
& VT_SYM
) {
8079 greloc(sec
, vtop
->sym
, c
, R_DATA_32
);
8081 *(int *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8086 vset(&dtype
, VT_LOCAL
, c
);
8093 /* put zeros for variable based init */
8094 static void init_putz(CType
*t
, Section
*sec
, unsigned long c
, int size
)
8097 /* nothing to do because globals are already set to zero */
8099 vpush_global_sym(&func_old_type
, TOK_memset
);
8107 /* 't' contains the type and storage info. 'c' is the offset of the
8108 object in section 'sec'. If 'sec' is NULL, it means stack based
8109 allocation. 'first' is true if array '{' must be read (multi
8110 dimension implicit array init handling). 'size_only' is true if
8111 size only evaluation is wanted (only for arrays). */
8112 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
8113 int first
, int size_only
)
8115 int index
, array_length
, n
, no_oblock
, nb
, parlevel
, i
;
8116 int size1
, align1
, expr_type
;
8120 if (type
->t
& VT_ARRAY
) {
8124 t1
= pointed_type(type
);
8125 size1
= type_size(t1
, &align1
);
8128 if ((first
&& tok
!= TOK_LSTR
&& tok
!= TOK_STR
) ||
8134 /* only parse strings here if correct type (otherwise: handle
8135 them as ((w)char *) expressions */
8136 if ((tok
== TOK_LSTR
&&
8137 (t1
->t
& VT_BTYPE
) == VT_INT
) ||
8139 (t1
->t
& VT_BTYPE
) == VT_BYTE
)) {
8140 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
8145 /* compute maximum number of chars wanted */
8147 cstr_len
= cstr
->size
;
8149 cstr_len
= cstr
->size
/ sizeof(int);
8152 if (n
>= 0 && nb
> (n
- array_length
))
8153 nb
= n
- array_length
;
8156 warning("initializer-string for array is too long");
8157 /* in order to go faster for common case (char
8158 string in global variable, we handle it
8160 if (sec
&& tok
== TOK_STR
&& size1
== 1) {
8161 memcpy(sec
->data
+ c
+ array_length
, cstr
->data
, nb
);
8165 ch
= ((unsigned char *)cstr
->data
)[i
];
8167 ch
= ((int *)cstr
->data
)[i
];
8168 init_putv(t1
, sec
, c
+ (array_length
+ i
) * size1
,
8176 /* only add trailing zero if enough storage (no
8177 warning in this case since it is standard) */
8178 if (n
< 0 || array_length
< n
) {
8180 init_putv(t1
, sec
, c
+ (array_length
* size1
), 0, EXPR_VAL
);
8186 while (tok
!= '}') {
8187 decl_designator(type
, sec
, c
, &index
, NULL
, size_only
);
8188 if (n
>= 0 && index
>= n
)
8189 error("index too large");
8190 /* must put zero in holes (note that doing it that way
8191 ensures that it even works with designators) */
8192 if (!size_only
&& array_length
< index
) {
8193 init_putz(t1
, sec
, c
+ array_length
* size1
,
8194 (index
- array_length
) * size1
);
8197 if (index
> array_length
)
8198 array_length
= index
;
8199 /* special test for multi dimensional arrays (may not
8200 be strictly correct if designators are used at the
8202 if (index
>= n
&& no_oblock
)
8211 /* put zeros at the end */
8212 if (!size_only
&& n
>= 0 && array_length
< n
) {
8213 init_putz(t1
, sec
, c
+ array_length
* size1
,
8214 (n
- array_length
) * size1
);
8216 /* patch type size if needed */
8218 s
->c
= array_length
;
8219 } else if ((type
->t
& VT_BTYPE
) == VT_STRUCT
&&
8220 (sec
|| !first
|| tok
== '{')) {
8223 /* NOTE: the previous test is a specific case for automatic
8224 struct/union init */
8225 /* XXX: union needs only one init */
8227 /* XXX: this test is incorrect for local initializers
8228 beginning with ( without {. It would be much more difficult
8229 to do it correctly (ideally, the expression parser should
8230 be used in all cases) */
8236 while (tok
== '(') {
8240 if (!parse_btype(&type1
, &ad1
))
8242 type_decl(&type1
, &ad1
, &n
, TYPE_ABSTRACT
);
8244 if (!is_assignable_types(type
, &type1
))
8245 error("invalid type for cast");
8250 if (first
|| tok
== '{') {
8259 while (tok
!= '}') {
8260 decl_designator(type
, sec
, c
, NULL
, &f
, size_only
);
8262 if (!size_only
&& array_length
< index
) {
8263 init_putz(type
, sec
, c
+ array_length
,
8264 index
- array_length
);
8266 index
= index
+ type_size(&f
->type
, &align1
);
8267 if (index
> array_length
)
8268 array_length
= index
;
8270 if (no_oblock
&& f
== NULL
)
8276 /* put zeros at the end */
8277 if (!size_only
&& array_length
< n
) {
8278 init_putz(type
, sec
, c
+ array_length
,
8287 } else if (tok
== '{') {
8289 decl_initializer(type
, sec
, c
, first
, size_only
);
8291 } else if (size_only
) {
8292 /* just skip expression */
8294 while ((parlevel
> 0 || (tok
!= '}' && tok
!= ',')) &&
8298 else if (tok
== ')')
8303 /* currently, we always use constant expression for globals
8304 (may change for scripting case) */
8305 expr_type
= EXPR_CONST
;
8307 expr_type
= EXPR_ANY
;
8308 init_putv(type
, sec
, c
, 0, expr_type
);
8312 /* parse an initializer for type 't' if 'has_init' is non zero, and
8313 allocate space in local or global data space ('r' is either
8314 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
8315 variable 'v' of scope 'scope' is declared before initializers are
8316 parsed. If 'v' is zero, then a reference to the new object is put
8317 in the value stack. If 'has_init' is 2, a special parsing is done
8318 to handle string constants. */
8319 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
8320 int has_init
, int v
, int scope
)
8322 int size
, align
, addr
, data_offset
;
8324 ParseState saved_parse_state
;
8325 TokenString init_str
;
8328 size
= type_size(type
, &align
);
8329 /* If unknown size, we must evaluate it before
8330 evaluating initializers because
8331 initializers can generate global data too
8332 (e.g. string pointers or ISOC99 compound
8333 literals). It also simplifies local
8334 initializers handling */
8335 tok_str_new(&init_str
);
8338 error("unknown type size");
8339 /* get all init string */
8340 if (has_init
== 2) {
8341 /* only get strings */
8342 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
8343 tok_str_add_tok(&init_str
);
8348 while (level
> 0 || (tok
!= ',' && tok
!= ';')) {
8350 error("unexpected end of file in initializer");
8351 tok_str_add_tok(&init_str
);
8354 else if (tok
== '}') {
8362 tok_str_add(&init_str
, -1);
8363 tok_str_add(&init_str
, 0);
8366 save_parse_state(&saved_parse_state
);
8368 macro_ptr
= init_str
.str
;
8370 decl_initializer(type
, NULL
, 0, 1, 1);
8371 /* prepare second initializer parsing */
8372 macro_ptr
= init_str
.str
;
8375 /* if still unknown size, error */
8376 size
= type_size(type
, &align
);
8378 error("unknown type size");
8380 /* take into account specified alignment if bigger */
8381 if (ad
->aligned
> align
)
8382 align
= ad
->aligned
;
8383 if ((r
& VT_VALMASK
) == VT_LOCAL
) {
8385 if (do_bounds_check
&& (type
->t
& VT_ARRAY
))
8387 loc
= (loc
- size
) & -align
;
8389 /* handles bounds */
8390 /* XXX: currently, since we do only one pass, we cannot track
8391 '&' operators, so we add only arrays */
8392 if (do_bounds_check
&& (type
->t
& VT_ARRAY
)) {
8393 unsigned long *bounds_ptr
;
8394 /* add padding between regions */
8396 /* then add local bound info */
8397 bounds_ptr
= section_ptr_add(lbounds_section
, 2 * sizeof(unsigned long));
8398 bounds_ptr
[0] = addr
;
8399 bounds_ptr
[1] = size
;
8402 /* local variable */
8403 sym_push(v
, type
, r
, addr
);
8405 /* push local reference */
8406 vset(type
, r
, addr
);
8412 if (v
&& scope
== VT_CONST
) {
8413 /* see if the symbol was already defined */
8416 if (!is_compatible_types(&sym
->type
, type
))
8417 error("incompatible types for redefinition of '%s'",
8418 get_tok_str(v
, NULL
));
8419 if (sym
->type
.t
& VT_EXTERN
) {
8420 /* if the variable is extern, it was not allocated */
8421 sym
->type
.t
&= ~VT_EXTERN
;
8423 /* we accept several definitions of the same
8424 global variable. this is tricky, because we
8425 must play with the SHN_COMMON type of the symbol */
8426 /* XXX: should check if the variable was already
8427 initialized. It is incorrect to initialized it
8429 /* no init data, we won't add more to the symbol */
8436 /* allocate symbol in corresponding section */
8443 data_offset
= sec
->data_offset
;
8444 data_offset
= (data_offset
+ align
- 1) & -align
;
8446 /* very important to increment global pointer at this time
8447 because initializers themselves can create new initializers */
8448 data_offset
+= size
;
8449 /* add padding if bound check */
8450 if (do_bounds_check
)
8452 sec
->data_offset
= data_offset
;
8453 /* allocate section space to put the data */
8454 if (sec
->sh_type
!= SHT_NOBITS
&&
8455 data_offset
> sec
->data_allocated
)
8456 section_realloc(sec
, data_offset
);
8458 addr
= 0; /* avoid warning */
8462 if (scope
== VT_CONST
) {
8467 sym
= sym_push(v
, type
, r
| VT_SYM
, 0);
8469 /* update symbol definition */
8471 put_extern_sym(sym
, sec
, addr
, size
);
8474 /* put a common area */
8475 put_extern_sym(sym
, NULL
, align
, size
);
8476 /* XXX: find a nicer way */
8477 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
8478 esym
->st_shndx
= SHN_COMMON
;
8483 /* push global reference */
8484 sym
= get_sym_ref(type
, sec
, addr
, size
);
8486 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
8490 /* handles bounds now because the symbol must be defined
8491 before for the relocation */
8492 if (do_bounds_check
) {
8493 unsigned long *bounds_ptr
;
8495 greloc(bounds_section
, sym
, bounds_section
->data_offset
, R_DATA_32
);
8496 /* then add global bound info */
8497 bounds_ptr
= section_ptr_add(bounds_section
, 2 * sizeof(long));
8498 bounds_ptr
[0] = 0; /* relocated */
8499 bounds_ptr
[1] = size
;
8503 decl_initializer(type
, sec
, addr
, 1, 0);
8504 /* restore parse state if needed */
8506 tok_str_free(init_str
.str
);
8507 restore_parse_state(&saved_parse_state
);
8513 void put_func_debug(Sym
*sym
)
8518 /* XXX: we put here a dummy type */
8519 snprintf(buf
, sizeof(buf
), "%s:%c1",
8520 funcname
, sym
->type
.t
& VT_STATIC
? 'f' : 'F');
8521 put_stabs_r(buf
, N_FUN
, 0, file
->line_num
, 0,
8522 cur_text_section
, sym
->c
);
8527 /* not finished : try to put some local vars in registers */
8528 //#define CONFIG_REG_VARS
8530 #ifdef CONFIG_REG_VARS
8531 void add_var_ref(int t
)
8533 printf("%s:%d: &%s\n",
8534 file
->filename
, file
->line_num
,
8535 get_tok_str(t
, NULL
));
8538 /* first pass on a function with heuristic to extract variable usage
8539 and pointer references to local variables for register allocation */
8540 void analyse_function(void)
8547 /* any symbol coming after '&' is considered as being a
8548 variable whose reference is taken. It is highly unaccurate
8549 but it is difficult to do better without a complete parse */
8552 /* if '& number', then no need to examine next tokens */
8553 if (tok
== TOK_CINT
||
8555 tok
== TOK_CLLONG
||
8556 tok
== TOK_CULLONG
) {
8558 } else if (tok
>= TOK_UIDENT
) {
8559 /* if '& ident [' or '& ident ->', then ident address
8563 if (tok
!= '[' && tok
!= TOK_ARROW
)
8567 while (tok
!= '}' && tok
!= ';' &&
8568 !((tok
== ',' || tok
== ')') && level
== 0)) {
8569 if (tok
>= TOK_UIDENT
) {
8571 } else if (tok
== '(') {
8573 } else if (tok
== ')') {
8586 /* parse an old style function declaration list */
8587 /* XXX: check multiple parameter */
8588 static void func_decl_list(Sym
*func_sym
)
8595 /* parse each declaration */
8596 while (tok
!= '{' && tok
!= ';' && tok
!= ',' && tok
!= TOK_EOF
) {
8597 if (!parse_btype(&btype
, &ad
))
8598 expect("declaration list");
8599 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
8600 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
8602 /* we accept no variable after */
8606 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
8607 /* find parameter in function parameter list */
8610 if ((s
->v
& ~SYM_FIELD
) == v
)
8614 error("declaration for parameter '%s' but no such parameter",
8615 get_tok_str(v
, NULL
));
8617 /* check that no storage specifier except 'register' was given */
8618 if (type
.t
& VT_STORAGE
)
8619 error("storage class specified for '%s'", get_tok_str(v
, NULL
));
8620 convert_parameter_type(&type
);
8621 /* we can add the type (NOTE: it could be local to the function) */
8623 /* accept other parameters */
8634 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
8635 static void decl(int l
)
8643 if (!parse_btype(&btype
, &ad
)) {
8644 /* skip redundant ';' */
8645 /* XXX: find more elegant solution */
8650 /* special test for old K&R protos without explicit int
8651 type. Only accepted when defining global data */
8652 if (l
== VT_LOCAL
|| tok
< TOK_DEFINE
)
8656 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
8657 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
8659 /* we accept no variable after */
8663 while (1) { /* iterate thru each declaration */
8665 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
8669 type_to_str(buf
, sizeof(buf
), t
, get_tok_str(v
, NULL
));
8670 printf("type = '%s'\n", buf
);
8673 if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
8674 /* if old style function prototype, we accept a
8677 if (sym
->c
== FUNC_OLD
)
8678 func_decl_list(sym
);
8682 #ifdef CONFIG_REG_VARS
8683 TokenString func_str
;
8684 ParseState saved_parse_state
;
8689 error("cannot use local functions");
8690 if (!(type
.t
& VT_FUNC
))
8691 expect("function definition");
8693 /* reject abstract declarators in function definition */
8695 while ((sym
= sym
->next
) != NULL
)
8696 if (!(sym
->v
& ~SYM_FIELD
))
8697 expect("identifier");
8699 /* XXX: cannot do better now: convert extern line to static inline */
8700 if ((type
.t
& (VT_EXTERN
| VT_INLINE
)) == (VT_EXTERN
| VT_INLINE
))
8701 type
.t
= (type
.t
& ~VT_EXTERN
) | VT_STATIC
;
8703 #ifdef CONFIG_REG_VARS
8704 /* parse all function code and record it */
8706 tok_str_new(&func_str
);
8712 error("unexpected end of file");
8713 tok_str_add_tok(&func_str
);
8718 } else if (t
== '}') {
8720 if (block_level
== 0)
8724 tok_str_add(&func_str
, -1);
8725 tok_str_add(&func_str
, 0);
8727 save_parse_state(&saved_parse_state
);
8729 macro_ptr
= func_str
.str
;
8734 /* compute text section */
8735 cur_text_section
= ad
.section
;
8736 if (!cur_text_section
)
8737 cur_text_section
= text_section
;
8738 ind
= cur_text_section
->data_offset
;
8739 funcname
= get_tok_str(v
, NULL
);
8742 /* if symbol is already defined, then put complete type */
8745 /* put function symbol */
8746 sym
= global_identifier_push(v
, type
.t
, 0);
8747 sym
->type
.ref
= type
.ref
;
8749 /* NOTE: we patch the symbol size later */
8750 put_extern_sym(sym
, cur_text_section
, ind
, 0);
8752 sym
->r
= VT_SYM
| VT_CONST
;
8753 /* put debug symbol */
8755 put_func_debug(sym
);
8756 /* push a dummy symbol to enable local sym storage */
8757 sym_push2(&local_stack
, SYM_FIELD
, 0, 0);
8758 gfunc_prolog(&type
);
8760 #ifdef CONFIG_REG_VARS
8761 macro_ptr
= func_str
.str
;
8764 block(NULL
, NULL
, NULL
, NULL
, 0, 0);
8767 cur_text_section
->data_offset
= ind
;
8768 label_pop(&global_label_stack
, NULL
);
8769 sym_pop(&local_stack
, NULL
); /* reset local stack */
8770 /* end of function */
8771 /* patch symbol size */
8772 ((Elf32_Sym
*)symtab_section
->data
)[sym
->c
].st_size
=
8775 put_stabn(N_FUN
, 0, 0, ind
- func_ind
);
8777 funcname
= ""; /* for safety */
8778 func_vt
.t
= VT_VOID
; /* for safety */
8779 ind
= 0; /* for safety */
8781 #ifdef CONFIG_REG_VARS
8782 tok_str_free(func_str
.str
);
8783 restore_parse_state(&saved_parse_state
);
8787 if (btype
.t
& VT_TYPEDEF
) {
8788 /* save typedefed type */
8789 /* XXX: test storage specifiers ? */
8790 sym
= sym_push(v
, &type
, 0, 0);
8791 sym
->type
.t
|= VT_TYPEDEF
;
8792 } else if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
8793 /* external function definition */
8794 external_sym(v
, &type
, 0);
8796 /* not lvalue if array */
8798 if (!(type
.t
& VT_ARRAY
))
8799 r
|= lvalue_type(type
.t
);
8800 has_init
= (tok
== '=');
8801 if ((btype
.t
& VT_EXTERN
) ||
8802 ((type
.t
& VT_ARRAY
) && (type
.t
& VT_STATIC
) &&
8803 !has_init
&& l
== VT_CONST
&& type
.ref
->c
< 0)) {
8804 /* external variable */
8805 /* NOTE: as GCC, uninitialized global static
8806 arrays of null size are considered as
8808 external_sym(v
, &type
, r
);
8810 if (type
.t
& VT_STATIC
)
8816 decl_initializer_alloc(&type
, &ad
, r
,
8830 /* better than nothing, but needs extension to handle '-E' option
8832 static void preprocess_init(TCCState
*s1
)
8834 s1
->include_stack_ptr
= s1
->include_stack
;
8835 /* XXX: move that before to avoid having to initialize
8836 file->ifdef_stack_ptr ? */
8837 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
8838 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
8840 /* XXX: not ANSI compliant: bound checking says error */
8844 /* compile the C file opened in 'file'. Return non zero if errors. */
8845 static int tcc_compile(TCCState
*s1
)
8849 volatile int section_sym
;
8852 printf("%s: **** new file\n", file
->filename
);
8854 preprocess_init(s1
);
8857 anon_sym
= SYM_FIRST_ANOM
;
8859 /* file info: full path + filename */
8860 section_sym
= 0; /* avoid warning */
8862 section_sym
= put_elf_sym(symtab_section
, 0, 0,
8863 ELF32_ST_INFO(STB_LOCAL
, STT_SECTION
), 0,
8864 text_section
->sh_num
, NULL
);
8865 getcwd(buf
, sizeof(buf
));
8866 pstrcat(buf
, sizeof(buf
), "/");
8867 put_stabs_r(buf
, N_SO
, 0, 0,
8868 text_section
->data_offset
, text_section
, section_sym
);
8869 put_stabs_r(file
->filename
, N_SO
, 0, 0,
8870 text_section
->data_offset
, text_section
, section_sym
);
8872 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
8873 symbols can be safely used */
8874 put_elf_sym(symtab_section
, 0, 0,
8875 ELF32_ST_INFO(STB_LOCAL
, STT_FILE
), 0,
8876 SHN_ABS
, file
->filename
);
8878 /* define some often used types */
8879 int_type
.t
= VT_INT
;
8881 char_pointer_type
.t
= VT_BYTE
;
8882 mk_pointer(&char_pointer_type
);
8884 func_old_type
.t
= VT_FUNC
;
8885 func_old_type
.ref
= sym_push(SYM_FIELD
, &int_type
, FUNC_CDECL
, FUNC_OLD
);
8888 /* define 'void *alloca(unsigned int)' builtin function */
8893 sym
= sym_push(p
, mk_pointer(VT_VOID
), FUNC_CDECL
, FUNC_NEW
);
8894 s1
= sym_push(SYM_FIELD
, VT_UNSIGNED
| VT_INT
, 0, 0);
8897 sym_push(TOK_alloca
, VT_FUNC
| (p
<< VT_STRUCT_SHIFT
), VT_CONST
, 0);
8901 define_start
= define_stack
;
8903 if (setjmp(s1
->error_jmp_buf
) == 0) {
8905 s1
->error_set_jmp_enabled
= 1;
8907 ch
= file
->buf_ptr
[0];
8908 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
8909 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
;
8913 expect("declaration");
8915 /* end of translation unit info */
8917 put_stabs_r(NULL
, N_SO
, 0, 0,
8918 text_section
->data_offset
, text_section
, section_sym
);
8921 s1
->error_set_jmp_enabled
= 0;
8923 /* reset define stack, but leave -Dsymbols (may be incorrect if
8924 they are undefined) */
8925 free_defines(define_start
);
8927 sym_pop(&global_stack
, NULL
);
8929 return s1
->nb_errors
!= 0 ? -1 : 0;
8933 int tcc_compile_string(TCCState
*s
, const char *str
)
8935 BufferedFile bf1
, *bf
= &bf1
;
8939 /* init file structure */
8941 /* XXX: avoid copying */
8943 buf
= tcc_malloc(len
+ 1);
8946 memcpy(buf
, str
, len
);
8949 bf
->buf_end
= buf
+ len
;
8950 pstrcpy(bf
->filename
, sizeof(bf
->filename
), "<string>");
8954 ret
= tcc_compile(s
);
8958 /* currently, no need to close */
8963 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
8964 void tcc_define_symbol(TCCState
*s1
, const char *sym
, const char *value
)
8966 BufferedFile bf1
, *bf
= &bf1
;
8968 pstrcpy(bf
->buffer
, IO_BUF_SIZE
, sym
);
8969 pstrcat(bf
->buffer
, IO_BUF_SIZE
, " ");
8973 pstrcat(bf
->buffer
, IO_BUF_SIZE
, value
);
8975 /* init file structure */
8977 bf
->buf_ptr
= bf
->buffer
;
8978 bf
->buf_end
= bf
->buffer
+ strlen(bf
->buffer
);
8979 *bf
->buf_end
= CH_EOB
;
8980 bf
->filename
[0] = '\0';
8984 s1
->include_stack_ptr
= s1
->include_stack
;
8986 /* parse with define parser */
8987 ch
= file
->buf_ptr
[0];
8993 /* undefine a preprocessor symbol */
8994 void tcc_undefine_symbol(TCCState
*s1
, const char *sym
)
8998 ts
= tok_alloc(sym
, strlen(sym
));
8999 s
= define_find(ts
->tok
);
9000 /* undefine symbol by putting an invalid name */
9005 #ifdef CONFIG_TCC_ASM
9007 #ifdef TCC_TARGET_I386
9008 #include "i386-asm.c"
9013 static void asm_instr(void)
9015 error("inline asm() not supported");
9021 #ifdef TCC_TARGET_COFF
9022 #include "tcccoff.c"
9025 /* print the position in the source file of PC value 'pc' by reading
9026 the stabs debug information */
9027 static void rt_printline(unsigned long wanted_pc
)
9029 Stab_Sym
*sym
, *sym_end
;
9030 char func_name
[128], last_func_name
[128];
9031 unsigned long func_addr
, last_pc
, pc
;
9032 const char *incl_files
[INCLUDE_STACK_SIZE
];
9033 int incl_index
, len
, last_line_num
, i
;
9034 const char *str
, *p
;
9036 fprintf(stderr
, "0x%08lx:", wanted_pc
);
9038 func_name
[0] = '\0';
9041 last_func_name
[0] = '\0';
9042 last_pc
= 0xffffffff;
9044 sym
= (Stab_Sym
*)stab_section
->data
+ 1;
9045 sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
9046 while (sym
< sym_end
) {
9047 switch(sym
->n_type
) {
9048 /* function start or end */
9050 if (sym
->n_strx
== 0) {
9051 /* we test if between last line and end of function */
9052 pc
= sym
->n_value
+ func_addr
;
9053 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
9055 func_name
[0] = '\0';
9058 str
= stabstr_section
->data
+ sym
->n_strx
;
9059 p
= strchr(str
, ':');
9061 pstrcpy(func_name
, sizeof(func_name
), str
);
9064 if (len
> sizeof(func_name
) - 1)
9065 len
= sizeof(func_name
) - 1;
9066 memcpy(func_name
, str
, len
);
9067 func_name
[len
] = '\0';
9069 func_addr
= sym
->n_value
;
9072 /* line number info */
9074 pc
= sym
->n_value
+ func_addr
;
9075 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
9078 last_line_num
= sym
->n_desc
;
9080 strcpy(last_func_name
, func_name
);
9084 str
= stabstr_section
->data
+ sym
->n_strx
;
9086 if (incl_index
< INCLUDE_STACK_SIZE
) {
9087 incl_files
[incl_index
++] = str
;
9095 if (sym
->n_strx
== 0) {
9096 incl_index
= 0; /* end of translation unit */
9098 str
= stabstr_section
->data
+ sym
->n_strx
;
9099 /* do not add path */
9101 if (len
> 0 && str
[len
- 1] != '/')
9109 /* second pass: we try symtab symbols (no line number info) */
9112 Elf32_Sym
*sym
, *sym_end
;
9115 sym_end
= (Elf32_Sym
*)(symtab_section
->data
+ symtab_section
->data_offset
);
9116 for(sym
= (Elf32_Sym
*)symtab_section
->data
+ 1;
9119 type
= ELF32_ST_TYPE(sym
->st_info
);
9120 if (type
== STT_FUNC
) {
9121 if (wanted_pc
>= sym
->st_value
&&
9122 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
9123 pstrcpy(last_func_name
, sizeof(last_func_name
),
9124 strtab_section
->data
+ sym
->st_name
);
9130 /* did not find any info: */
9131 fprintf(stderr
, " ???\n");
9134 if (last_func_name
[0] != '\0') {
9135 fprintf(stderr
, " %s()", last_func_name
);
9137 if (incl_index
> 0) {
9138 fprintf(stderr
, " (%s:%d",
9139 incl_files
[incl_index
- 1], last_line_num
);
9140 for(i
= incl_index
- 2; i
>= 0; i
--)
9141 fprintf(stderr
, ", included from %s", incl_files
[i
]);
9142 fprintf(stderr
, ")");
9144 fprintf(stderr
, "\n");
9151 /* fix for glibc 2.1 */
9157 /* return the PC at frame level 'level'. Return non zero if not found */
9158 static int rt_get_caller_pc(unsigned long *paddr
,
9159 ucontext_t
*uc
, int level
)
9165 #if defined(__FreeBSD__)
9166 *paddr
= uc
->uc_mcontext
.mc_eip
;
9167 #elif defined(__dietlibc__)
9168 *paddr
= uc
->uc_mcontext
.eip
;
9170 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
9174 #if defined(__FreeBSD__)
9175 fp
= uc
->uc_mcontext
.mc_ebp
;
9176 #elif defined(__dietlibc__)
9177 fp
= uc
->uc_mcontext
.ebp
;
9179 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
9181 for(i
=1;i
<level
;i
++) {
9182 /* XXX: check address validity with program info */
9183 if (fp
<= 0x1000 || fp
>= 0xc0000000)
9185 fp
= ((unsigned long *)fp
)[0];
9187 *paddr
= ((unsigned long *)fp
)[1];
9193 #warning add arch specific rt_get_caller_pc()
9195 static int rt_get_caller_pc(unsigned long *paddr
,
9196 ucontext_t
*uc
, int level
)
9202 /* emit a run time error at position 'pc' */
9203 void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
9210 fprintf(stderr
, "Runtime error: ");
9211 vfprintf(stderr
, fmt
, ap
);
9212 fprintf(stderr
, "\n");
9213 for(i
=0;i
<num_callers
;i
++) {
9214 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
9217 fprintf(stderr
, "at ");
9219 fprintf(stderr
, "by ");
9226 /* signal handler for fatal errors */
9227 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
9229 ucontext_t
*uc
= puc
;
9233 switch(siginf
->si_code
) {
9236 rt_error(uc
, "division by zero");
9239 rt_error(uc
, "floating point exception");
9245 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
9246 rt_error(uc
, *rt_bound_error_msg
);
9248 rt_error(uc
, "dereferencing invalid pointer");
9251 rt_error(uc
, "illegal instruction");
9254 rt_error(uc
, "abort() called");
9257 rt_error(uc
, "caught signal %d", signum
);
9264 /* do all relocations (needed before using tcc_get_symbol()) */
9265 int tcc_relocate(TCCState
*s1
)
9272 tcc_add_runtime(s1
);
9274 build_got_entries(s1
);
9276 relocate_common_syms();
9278 /* compute relocation address : section are relocated in place. We
9279 also alloc the bss space */
9280 for(i
= 1; i
< s1
->nb_sections
; i
++) {
9281 s
= s1
->sections
[i
];
9282 if (s
->sh_flags
& SHF_ALLOC
) {
9283 if (s
->sh_type
== SHT_NOBITS
)
9284 s
->data
= tcc_mallocz(s
->data_offset
);
9285 s
->sh_addr
= (unsigned long)s
->data
;
9289 relocate_syms(s1
, 1);
9291 if (s1
->nb_errors
!= 0)
9294 /* relocate each section */
9295 for(i
= 1; i
< s1
->nb_sections
; i
++) {
9296 s
= s1
->sections
[i
];
9298 relocate_section(s1
, s
);
9303 /* launch the compiled program with the given arguments */
9304 int tcc_run(TCCState
*s1
, int argc
, char **argv
)
9306 int (*prog_main
)(int, char **);
9308 if (tcc_relocate(s1
) < 0)
9311 prog_main
= tcc_get_symbol_err(s1
, "main");
9315 error("debug mode currently not available for Windows");
9317 struct sigaction sigact
;
9318 /* install TCC signal handlers to print debug info on fatal
9320 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
9321 sigact
.sa_sigaction
= sig_error
;
9322 sigemptyset(&sigact
.sa_mask
);
9323 sigaction(SIGFPE
, &sigact
, NULL
);
9324 sigaction(SIGILL
, &sigact
, NULL
);
9325 sigaction(SIGSEGV
, &sigact
, NULL
);
9326 sigaction(SIGBUS
, &sigact
, NULL
);
9327 sigaction(SIGABRT
, &sigact
, NULL
);
9331 #ifdef CONFIG_TCC_BCHECK
9332 if (do_bounds_check
) {
9333 void (*bound_init
)(void);
9335 /* set error function */
9336 rt_bound_error_msg
= (void *)tcc_get_symbol_err(s1
,
9337 "__bound_error_msg");
9339 /* XXX: use .init section so that it also work in binary ? */
9340 bound_init
= (void *)tcc_get_symbol_err(s1
, "__bound_init");
9344 return (*prog_main
)(argc
, argv
);
9347 TCCState
*tcc_new(void)
9354 s
= tcc_mallocz(sizeof(TCCState
));
9358 s
->output_type
= TCC_OUTPUT_MEMORY
;
9360 /* init isid table */
9362 isidnum_table
[i
] = isid(i
) || isnum(i
);
9364 /* add all tokens */
9366 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
9368 tok_ident
= TOK_IDENT
;
9377 ts
= tok_alloc(p
, r
- p
- 1);
9381 /* we add dummy defines for some special macros to speed up tests
9382 and to have working defined() */
9383 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
9384 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
9385 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
9386 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
9388 /* standard defines */
9389 tcc_define_symbol(s
, "__STDC__", NULL
);
9390 #if defined(TCC_TARGET_I386)
9391 tcc_define_symbol(s
, "__i386__", NULL
);
9393 #if defined(TCC_TARGET_ARM)
9394 tcc_define_symbol(s
, "__ARM_ARCH_4__", NULL
);
9395 tcc_define_symbol(s
, "__arm_elf__", NULL
);
9396 tcc_define_symbol(s
, "__arm_elf", NULL
);
9397 tcc_define_symbol(s
, "arm_elf", NULL
);
9398 tcc_define_symbol(s
, "__arm__", NULL
);
9399 tcc_define_symbol(s
, "__arm", NULL
);
9400 tcc_define_symbol(s
, "arm", NULL
);
9401 tcc_define_symbol(s
, "__APCS_32__", NULL
);
9404 tcc_define_symbol(s
, "__linux__", NULL
);
9405 tcc_define_symbol(s
, "linux", NULL
);
9407 /* tiny C specific defines */
9408 tcc_define_symbol(s
, "__TINYC__", NULL
);
9410 /* tiny C & gcc defines */
9411 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned int");
9412 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "int");
9413 tcc_define_symbol(s
, "__WCHAR_TYPE__", "int");
9415 /* default library paths */
9416 tcc_add_library_path(s
, "/usr/local/lib");
9417 tcc_add_library_path(s
, "/usr/lib");
9418 tcc_add_library_path(s
, "/lib");
9420 /* no section zero */
9421 dynarray_add((void ***)&s
->sections
, &s
->nb_sections
, NULL
);
9423 /* create standard sections */
9424 text_section
= new_section(s
, ".text", SHT_PROGBITS
, SHF_ALLOC
| SHF_EXECINSTR
);
9425 data_section
= new_section(s
, ".data", SHT_PROGBITS
, SHF_ALLOC
| SHF_WRITE
);
9426 bss_section
= new_section(s
, ".bss", SHT_NOBITS
, SHF_ALLOC
| SHF_WRITE
);
9428 /* symbols are always generated for linking stage */
9429 symtab_section
= new_symtab(s
, ".symtab", SHT_SYMTAB
, 0,
9431 ".hashtab", SHF_PRIVATE
);
9432 strtab_section
= symtab_section
->link
;
9434 /* private symbol table for dynamic symbols */
9435 s
->dynsymtab_section
= new_symtab(s
, ".dynsymtab", SHT_SYMTAB
, SHF_PRIVATE
,
9437 ".dynhashtab", SHF_PRIVATE
);
9438 s
->alacarte_link
= 1;
9440 #ifdef CHAR_IS_UNSIGNED
9441 s
->char_is_unsigned
= 1;
9446 void tcc_delete(TCCState
*s1
)
9450 /* free -D defines */
9454 n
= tok_ident
- TOK_IDENT
;
9455 for(i
= 0; i
< n
; i
++)
9456 tcc_free(table_ident
[i
]);
9457 tcc_free(table_ident
);
9459 /* free all sections */
9461 free_section(symtab_section
->hash
);
9463 free_section(s1
->dynsymtab_section
->hash
);
9464 free_section(s1
->dynsymtab_section
->link
);
9465 free_section(s1
->dynsymtab_section
);
9467 for(i
= 1; i
< s1
->nb_sections
; i
++)
9468 free_section(s1
->sections
[i
]);
9469 tcc_free(s1
->sections
);
9471 /* free loaded dlls array */
9472 for(i
= 0; i
< s1
->nb_loaded_dlls
; i
++)
9473 tcc_free(s1
->loaded_dlls
[i
]);
9474 tcc_free(s1
->loaded_dlls
);
9477 for(i
= 0; i
< s1
->nb_library_paths
; i
++)
9478 tcc_free(s1
->library_paths
[i
]);
9479 tcc_free(s1
->library_paths
);
9481 /* cached includes */
9482 for(i
= 0; i
< s1
->nb_cached_includes
; i
++)
9483 tcc_free(s1
->cached_includes
[i
]);
9484 tcc_free(s1
->cached_includes
);
9486 for(i
= 0; i
< s1
->nb_include_paths
; i
++)
9487 tcc_free(s1
->include_paths
[i
]);
9488 tcc_free(s1
->include_paths
);
9490 for(i
= 0; i
< s1
->nb_sysinclude_paths
; i
++)
9491 tcc_free(s1
->sysinclude_paths
[i
]);
9492 tcc_free(s1
->sysinclude_paths
);
9497 int tcc_add_include_path(TCCState
*s1
, const char *pathname
)
9501 pathname1
= tcc_strdup(pathname
);
9502 dynarray_add((void ***)&s1
->include_paths
, &s1
->nb_include_paths
, pathname1
);
9506 int tcc_add_sysinclude_path(TCCState
*s1
, const char *pathname
)
9510 pathname1
= tcc_strdup(pathname
);
9511 dynarray_add((void ***)&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
, pathname1
);
9515 static int tcc_add_file_internal(TCCState
*s1
, const char *filename
, int flags
)
9517 const char *ext
, *filename1
;
9520 BufferedFile
*saved_file
;
9522 /* find source file type with extension */
9523 filename1
= strrchr(filename
, '/');
9527 filename1
= filename
;
9528 ext
= strrchr(filename1
, '.');
9534 file
= tcc_open(s1
, filename
);
9536 if (flags
& AFF_PRINT_ERROR
) {
9537 error_noabort("file '%s' not found", filename
);
9543 if (!ext
|| !strcmp(ext
, "c")) {
9544 /* C file assumed */
9545 ret
= tcc_compile(s1
);
9547 #ifdef CONFIG_TCC_ASM
9548 if (!strcmp(ext
, "S")) {
9549 /* preprocessed assembler */
9550 ret
= tcc_assemble(s1
, 1);
9551 } else if (!strcmp(ext
, "s")) {
9552 /* non preprocessed assembler */
9553 ret
= tcc_assemble(s1
, 0);
9558 /* assume executable format: auto guess file type */
9559 ret
= read(fd
, &ehdr
, sizeof(ehdr
));
9560 lseek(fd
, 0, SEEK_SET
);
9562 error_noabort("could not read header");
9564 } else if (ret
!= sizeof(ehdr
)) {
9565 goto try_load_script
;
9568 if (ehdr
.e_ident
[0] == ELFMAG0
&&
9569 ehdr
.e_ident
[1] == ELFMAG1
&&
9570 ehdr
.e_ident
[2] == ELFMAG2
&&
9571 ehdr
.e_ident
[3] == ELFMAG3
) {
9572 file
->line_num
= 0; /* do not display line number if error */
9573 if (ehdr
.e_type
== ET_REL
) {
9574 ret
= tcc_load_object_file(s1
, fd
, 0);
9575 } else if (ehdr
.e_type
== ET_DYN
) {
9576 if (s1
->output_type
== TCC_OUTPUT_MEMORY
) {
9578 h
= dlopen(filename
, RTLD_GLOBAL
| RTLD_LAZY
);
9584 ret
= tcc_load_dll(s1
, fd
, filename
,
9585 (flags
& AFF_REFERENCED_DLL
) != 0);
9588 error_noabort("unrecognized ELF file");
9591 } else if (memcmp((char *)&ehdr
, ARMAG
, 8) == 0) {
9592 file
->line_num
= 0; /* do not display line number if error */
9593 ret
= tcc_load_archive(s1
, fd
);
9595 #ifdef TCC_TARGET_COFF
9596 if (*(uint16_t *)(&ehdr
) == COFF_C67_MAGIC
) {
9597 ret
= tcc_load_coff(s1
, fd
);
9601 /* as GNU ld, consider it is an ld script if not recognized */
9603 ret
= tcc_load_ldscript(s1
);
9605 error_noabort("unrecognized file type");
9620 int tcc_add_file(TCCState
*s
, const char *filename
)
9622 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
);
9625 int tcc_add_library_path(TCCState
*s
, const char *pathname
)
9629 pathname1
= tcc_strdup(pathname
);
9630 dynarray_add((void ***)&s
->library_paths
, &s
->nb_library_paths
, pathname1
);
9634 /* find and load a dll. Return non zero if not found */
9635 /* XXX: add '-rpath' option support ? */
9636 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
)
9641 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
9642 snprintf(buf
, sizeof(buf
), "%s/%s",
9643 s
->library_paths
[i
], filename
);
9644 if (tcc_add_file_internal(s
, buf
, flags
) == 0)
9650 /* the library name is the same as the argument of the '-l' option */
9651 int tcc_add_library(TCCState
*s
, const char *libraryname
)
9656 /* first we look for the dynamic library if not static linking */
9657 if (!s
->static_link
) {
9658 snprintf(buf
, sizeof(buf
), "lib%s.so", libraryname
);
9659 if (tcc_add_dll(s
, buf
, 0) == 0)
9663 /* then we look for the static library */
9664 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
9665 snprintf(buf
, sizeof(buf
), "%s/lib%s.a",
9666 s
->library_paths
[i
], libraryname
);
9667 if (tcc_add_file_internal(s
, buf
, 0) == 0)
9673 int tcc_add_symbol(TCCState
*s
, const char *name
, unsigned long val
)
9675 add_elf_sym(symtab_section
, val
, 0,
9676 ELF32_ST_INFO(STB_GLOBAL
, STT_NOTYPE
),
9681 int tcc_set_output_type(TCCState
*s
, int output_type
)
9685 s
->output_type
= output_type
;
9688 /* default include paths */
9689 /* XXX: reverse order needed if -isystem support */
9690 tcc_add_sysinclude_path(s
, "/usr/local/include");
9691 tcc_add_sysinclude_path(s
, "/usr/include");
9692 snprintf(buf
, sizeof(buf
), "%s/include", tcc_lib_path
);
9693 tcc_add_sysinclude_path(s
, buf
);
9696 /* if bound checking, then add corresponding sections */
9697 #ifdef CONFIG_TCC_BCHECK
9698 if (do_bounds_check
) {
9700 tcc_define_symbol(s
, "__BOUNDS_CHECKING_ON", NULL
);
9701 /* create bounds sections */
9702 bounds_section
= new_section(s
, ".bounds",
9703 SHT_PROGBITS
, SHF_ALLOC
);
9704 lbounds_section
= new_section(s
, ".lbounds",
9705 SHT_PROGBITS
, SHF_ALLOC
);
9709 if (s
->char_is_unsigned
) {
9710 tcc_define_symbol(s
, "__CHAR_UNSIGNED__", NULL
);
9713 /* add debug sections */
9716 stab_section
= new_section(s
, ".stab", SHT_PROGBITS
, 0);
9717 stab_section
->sh_entsize
= sizeof(Stab_Sym
);
9718 stabstr_section
= new_section(s
, ".stabstr", SHT_STRTAB
, 0);
9719 put_elf_str(stabstr_section
, "");
9720 stab_section
->link
= stabstr_section
;
9721 /* put first entry */
9722 put_stabs("", 0, 0, 0, 0);
9725 /* add libc crt1/crti objects */
9726 if ((output_type
== TCC_OUTPUT_EXE
|| output_type
== TCC_OUTPUT_DLL
) &&
9728 if (output_type
!= TCC_OUTPUT_DLL
)
9729 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crt1.o");
9730 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crti.o");
9735 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
9736 #define FD_INVERT 0x0002 /* invert value before storing */
9738 typedef struct FlagDef
{
9744 static const FlagDef warning_defs
[] = {
9745 { offsetof(TCCState
, warn_unsupported
), 0, "unsupported" },
9746 { offsetof(TCCState
, warn_write_strings
), 0, "write-strings" },
9747 { offsetof(TCCState
, warn_error
), 0, "error" },
9748 { offsetof(TCCState
, warn_implicit_function_declaration
), WD_ALL
,
9749 "implicit-function-declaration" },
9752 static int set_flag(TCCState
*s
, const FlagDef
*flags
, int nb_flags
,
9753 const char *name
, int value
)
9760 if (r
[0] == 'n' && r
[1] == 'o' && r
[2] == '-') {
9764 for(i
= 0, p
= flags
; i
< nb_flags
; i
++, p
++) {
9765 if (!strcmp(r
, p
->name
))
9770 if (p
->flags
& FD_INVERT
)
9772 *(int *)((uint8_t *)s
+ p
->offset
) = value
;
9777 /* set/reset a warning */
9778 int tcc_set_warning(TCCState
*s
, const char *warning_name
, int value
)
9783 if (!strcmp(warning_name
, "all")) {
9784 for(i
= 0, p
= warning_defs
; i
< countof(warning_defs
); i
++, p
++) {
9785 if (p
->flags
& WD_ALL
)
9786 *(int *)((uint8_t *)s
+ p
->offset
) = 1;
9790 return set_flag(s
, warning_defs
, countof(warning_defs
),
9791 warning_name
, value
);
9795 static const FlagDef flag_defs
[] = {
9796 { offsetof(TCCState
, char_is_unsigned
), 0, "unsigned-char" },
9797 { offsetof(TCCState
, char_is_unsigned
), FD_INVERT
, "signed-char" },
9800 /* set/reset a flag */
9801 int tcc_set_flag(TCCState
*s
, const char *flag_name
, int value
)
9803 return set_flag(s
, flag_defs
, countof(flag_defs
),
9807 #if !defined(LIBTCC)
9809 /* extract the basename of a file */
9810 static const char *tcc_basename(const char *name
)
9813 p
= strrchr(name
, '/');
9816 p
= strrchr(name
, '\\');
9825 static int64_t getclock_us(void)
9830 return (tb
.time
* 1000LL + tb
.millitm
) * 1000LL;
9833 gettimeofday(&tv
, NULL
);
9834 return tv
.tv_sec
* 1000000LL + tv
.tv_usec
;
9840 printf("tcc version " TCC_VERSION
" - Tiny C Compiler - Copyright (C) 2001-2003 Fabrice Bellard\n"
9841 "usage: tcc [-v] [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"
9842 " [-Wwarn] [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-static]\n"
9843 " [infile1 infile2...] [-run infile args...]\n"
9845 "General options:\n"
9846 " -v display current version\n"
9847 " -c compile only - generate an object file\n"
9848 " -o outfile set output filename\n"
9849 " -Bdir set tcc internal library path\n"
9850 " -bench output compilation statistics\n"
9851 " -run run compiled source\n"
9852 " -fflag set or reset (with 'no-' prefix) 'flag' (see man page)\n"
9853 " -Wwarning set or reset (with 'no-' prefix) 'warning' (see man page)\n"
9854 " -w disable all warnings\n"
9855 "Preprocessor options:\n"
9856 " -Idir add include path 'dir'\n"
9857 " -Dsym[=val] define 'sym' with value 'val'\n"
9858 " -Usym undefine 'sym'\n"
9860 " -Ldir add library path 'dir'\n"
9861 " -llib link with dynamic or static library 'lib'\n"
9862 " -shared generate a shared library\n"
9863 " -static static linking\n"
9864 " -rdynamic export all global symbols to dynamic linker\n"
9865 " -r relocatable output\n"
9866 "Debugger options:\n"
9867 " -g generate runtime debug info\n"
9868 #ifdef CONFIG_TCC_BCHECK
9869 " -b compile with built-in memory and bounds checker (implies -g)\n"
9871 " -bt N show N callers in stack traces\n"
9875 #define TCC_OPTION_HAS_ARG 0x0001
9876 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
9878 typedef struct TCCOption
{
9905 TCC_OPTION_nostdinc
,
9906 TCC_OPTION_nostdlib
,
9907 TCC_OPTION_print_search_dirs
,
9908 TCC_OPTION_rdynamic
,
9914 static const TCCOption tcc_options
[] = {
9915 { "h", TCC_OPTION_HELP
, 0 },
9916 { "?", TCC_OPTION_HELP
, 0 },
9917 { "I", TCC_OPTION_I
, TCC_OPTION_HAS_ARG
},
9918 { "D", TCC_OPTION_D
, TCC_OPTION_HAS_ARG
},
9919 { "U", TCC_OPTION_U
, TCC_OPTION_HAS_ARG
},
9920 { "L", TCC_OPTION_L
, TCC_OPTION_HAS_ARG
},
9921 { "B", TCC_OPTION_B
, TCC_OPTION_HAS_ARG
},
9922 { "l", TCC_OPTION_l
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9923 { "bench", TCC_OPTION_bench
, 0 },
9924 { "bt", TCC_OPTION_bt
, TCC_OPTION_HAS_ARG
},
9925 #ifdef CONFIG_TCC_BCHECK
9926 { "b", TCC_OPTION_b
, 0 },
9928 { "g", TCC_OPTION_g
, 0 },
9929 { "c", TCC_OPTION_c
, 0 },
9930 { "static", TCC_OPTION_static
, 0 },
9931 { "shared", TCC_OPTION_shared
, 0 },
9932 { "o", TCC_OPTION_o
, TCC_OPTION_HAS_ARG
},
9933 { "run", TCC_OPTION_run
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9934 { "rdynamic", TCC_OPTION_rdynamic
, 0 },
9935 { "r", TCC_OPTION_r
, 0 },
9936 { "W", TCC_OPTION_W
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9937 { "O", TCC_OPTION_O
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9938 { "m", TCC_OPTION_m
, TCC_OPTION_HAS_ARG
},
9939 { "f", TCC_OPTION_f
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9940 { "nostdinc", TCC_OPTION_nostdinc
, 0 },
9941 { "nostdlib", TCC_OPTION_nostdlib
, 0 },
9942 { "print-search-dirs", TCC_OPTION_print_search_dirs
, 0 },
9943 { "v", TCC_OPTION_v
, 0 },
9944 { "w", TCC_OPTION_w
, 0 },
9948 /* convert 'str' into an array of space separated strings */
9949 static int expand_args(char ***pargv
, const char *str
)
9958 while (is_space(*str
))
9963 while (*str
!= '\0' && !is_space(*str
))
9966 arg
= tcc_malloc(len
+ 1);
9967 memcpy(arg
, s1
, len
);
9969 dynarray_add((void ***)&argv
, &argc
, arg
);
9975 static char **files
;
9976 static int nb_files
, nb_libraries
;
9977 static int multiple_files
;
9978 static int print_search_dirs
;
9979 static int output_type
;
9980 static int reloc_output
;
9981 static const char *outfile
;
9983 int parse_args(TCCState
*s
, int argc
, char **argv
)
9986 const TCCOption
*popt
;
9987 const char *optarg
, *p1
, *r1
;
9992 if (optind
>= argc
) {
9993 if (nb_files
== 0 && !print_search_dirs
)
10000 /* add a new file */
10001 dynarray_add((void ***)&files
, &nb_files
, r
);
10002 if (!multiple_files
) {
10004 /* argv[0] will be this file */
10008 /* find option in table (match only the first chars */
10009 popt
= tcc_options
;
10013 error("invalid option -- '%s'", r
);
10026 if (popt
->flags
& TCC_OPTION_HAS_ARG
) {
10027 if (*r1
!= '\0' || (popt
->flags
& TCC_OPTION_NOSEP
)) {
10030 if (optind
>= argc
)
10031 error("argument to '%s' is missing", r
);
10032 optarg
= argv
[optind
++];
10040 switch(popt
->index
) {
10041 case TCC_OPTION_HELP
:
10046 if (tcc_add_include_path(s
, optarg
) < 0)
10047 error("too many include paths");
10052 sym
= (char *)optarg
;
10053 value
= strchr(sym
, '=');
10058 tcc_define_symbol(s
, sym
, value
);
10062 tcc_undefine_symbol(s
, optarg
);
10065 tcc_add_library_path(s
, optarg
);
10068 /* set tcc utilities path (mainly for tcc development) */
10069 tcc_lib_path
= optarg
;
10072 dynarray_add((void ***)&files
, &nb_files
, r
);
10075 case TCC_OPTION_bench
:
10078 case TCC_OPTION_bt
:
10079 num_callers
= atoi(optarg
);
10081 #ifdef CONFIG_TCC_BCHECK
10083 do_bounds_check
= 1;
10091 multiple_files
= 1;
10092 output_type
= TCC_OUTPUT_OBJ
;
10094 case TCC_OPTION_static
:
10095 s
->static_link
= 1;
10097 case TCC_OPTION_shared
:
10098 output_type
= TCC_OUTPUT_DLL
;
10101 multiple_files
= 1;
10105 /* generate a .o merging several output files */
10107 output_type
= TCC_OUTPUT_OBJ
;
10109 case TCC_OPTION_nostdinc
:
10112 case TCC_OPTION_nostdlib
:
10115 case TCC_OPTION_print_search_dirs
:
10116 print_search_dirs
= 1;
10118 case TCC_OPTION_run
:
10122 argc1
= expand_args(&argv1
, optarg
);
10124 parse_args(s
, argc1
, argv1
);
10126 multiple_files
= 0;
10127 output_type
= TCC_OUTPUT_MEMORY
;
10131 printf("tcc version %s\n", TCC_VERSION
);
10134 if (tcc_set_flag(s
, optarg
, 1) < 0 && s
->warn_unsupported
)
10135 goto unsupported_option
;
10138 if (tcc_set_warning(s
, optarg
, 1) < 0 &&
10139 s
->warn_unsupported
)
10140 goto unsupported_option
;
10145 case TCC_OPTION_rdynamic
:
10149 if (s
->warn_unsupported
) {
10150 unsupported_option
:
10151 warning("unsupported option '%s'", r
);
10160 int main(int argc
, char **argv
)
10164 int nb_objfiles
, ret
, optind
;
10165 char objfilename
[1024];
10166 int64_t start_time
= 0;
10169 output_type
= TCC_OUTPUT_EXE
;
10171 multiple_files
= 1;
10176 print_search_dirs
= 0;
10178 optind
= parse_args(s
, argc
- 1, argv
+ 1) + 1;
10180 if (print_search_dirs
) {
10181 /* enough for Linux kernel */
10182 printf("install: %s/\n", tcc_lib_path
);
10186 nb_objfiles
= nb_files
- nb_libraries
;
10188 /* if outfile provided without other options, we output an
10190 if (outfile
&& output_type
== TCC_OUTPUT_MEMORY
)
10191 output_type
= TCC_OUTPUT_EXE
;
10193 /* check -c consistency : only single file handled. XXX: checks file type */
10194 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
10195 /* accepts only a single input file */
10196 if (nb_objfiles
!= 1)
10197 error("cannot specify multiple files with -c");
10198 if (nb_libraries
!= 0)
10199 error("cannot specify libraries with -c");
10202 /* compute default outfile name */
10203 if (output_type
!= TCC_OUTPUT_MEMORY
&& !outfile
) {
10204 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
10207 pstrcpy(objfilename
, sizeof(objfilename
) - 1,
10208 tcc_basename(files
[0]));
10209 /* add .o extension */
10210 ext
= strrchr(objfilename
, '.');
10212 goto default_outfile
;
10213 strcpy(ext
+ 1, "o");
10216 pstrcpy(objfilename
, sizeof(objfilename
), "a.out");
10218 outfile
= objfilename
;
10222 start_time
= getclock_us();
10225 tcc_set_output_type(s
, output_type
);
10227 /* compile or add each files or library */
10228 for(i
= 0;i
< nb_files
; i
++) {
10229 const char *filename
;
10231 filename
= files
[i
];
10232 if (filename
[0] == '-') {
10233 if (tcc_add_library(s
, filename
+ 2) < 0)
10234 error("cannot find %s", filename
);
10236 if (tcc_add_file(s
, filename
) < 0) {
10243 /* free all files */
10248 total_time
= (double)(getclock_us() - start_time
) / 1000000.0;
10249 if (total_time
< 0.001)
10250 total_time
= 0.001;
10251 if (total_bytes
< 1)
10253 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
10254 tok_ident
- TOK_IDENT
, total_lines
, total_bytes
,
10255 total_time
, (int)(total_lines
/ total_time
),
10256 total_bytes
/ total_time
/ 1000000.0);
10259 if (s
->output_type
!= TCC_OUTPUT_MEMORY
) {
10260 tcc_output_file(s
, outfile
);
10263 ret
= tcc_run(s
, argc
- optind
, argv
+ optind
);
10266 /* XXX: cannot do it with bound checking because of the malloc hooks */
10267 if (!do_bounds_check
)
10272 printf("memory: %d bytes, max = %d bytes\n", mem_cur_size
, mem_max_size
);