2 * TCC - Tiny C Compiler
4 * Copyright (c) 2001-2004 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26 #define CONFIG_TCC_STATIC
43 #include <sys/timeb.h>
44 #define CONFIG_TCC_STATIC
48 #include <sys/ucontext.h>
51 #endif /* !CONFIG_TCCBOOT */
55 #ifndef CONFIG_TCC_STATIC
66 /* preprocessor debug */
68 /* include file debug */
76 /* target selection */
77 //#define TCC_TARGET_I386 /* i386 code generator */
78 //#define TCC_TARGET_ARM /* ARMv4 code generator */
79 //#define TCC_TARGET_C67 /* TMS320C67xx code generator */
81 /* default target is I386 */
82 #if !defined(TCC_TARGET_I386) && !defined(TCC_TARGET_ARM) && \
83 !defined(TCC_TARGET_C67)
84 #define TCC_TARGET_I386
87 #if !defined(WIN32) && !defined(TCC_UCLIBC) && !defined(TCC_TARGET_ARM) && \
88 !defined(TCC_TARGET_C67)
89 #define CONFIG_TCC_BCHECK /* enable bound checking code */
92 /* define it to include assembler support */
93 #if !defined(TCC_TARGET_ARM) && !defined(TCC_TARGET_C67)
94 #define CONFIG_TCC_ASM
97 /* object format selection */
98 #if defined(TCC_TARGET_C67)
99 #define TCC_TARGET_COFF
108 /* path to find crt1.o, crti.o and crtn.o. Only needed when generating
109 executables or dlls */
110 #define CONFIG_TCC_CRT_PREFIX "/usr/lib"
112 #define INCLUDE_STACK_SIZE 32
113 #define IFDEF_STACK_SIZE 64
114 #define VSTACK_SIZE 64
115 #define STRING_MAX_SIZE 1024
117 #define TOK_HASH_SIZE 8192 /* must be a power of two */
118 #define TOK_ALLOC_INCR 512 /* must be a power of two */
119 #define TOK_MAX_SIZE 4 /* token max size in int unit when stored in string */
121 /* token symbol management */
122 typedef struct TokenSym
{
123 struct TokenSym
*hash_next
;
124 struct Sym
*sym_define
; /* direct pointer to define */
125 struct Sym
*sym_label
; /* direct pointer to label */
126 struct Sym
*sym_struct
; /* direct pointer to structure */
127 struct Sym
*sym_identifier
; /* direct pointer to identifier */
128 int tok
; /* token number */
133 typedef struct CString
{
134 int size
; /* size in bytes */
135 void *data
; /* either 'char *' or 'int *' */
137 void *data_allocated
; /* if non NULL, data has been malloced */
140 /* type definition */
141 typedef struct CType
{
147 typedef union CValue
{
153 unsigned int ul
; /* address (should be unsigned long on 64 bit cpu) */
155 unsigned long long ull
;
156 struct CString
*cstr
;
162 typedef struct SValue
{
163 CType type
; /* type */
164 unsigned short r
; /* register + flags */
165 unsigned short r2
; /* second register, used for 'long long'
166 type. If not used, set to VT_CONST */
167 CValue c
; /* constant, if VT_CONST */
168 struct Sym
*sym
; /* symbol, if (VT_SYM | VT_CONST) */
171 /* symbol management */
173 int v
; /* symbol token */
174 int r
; /* associated register */
175 int c
; /* associated number */
176 CType type
; /* associated type */
177 struct Sym
*next
; /* next related symbol */
178 struct Sym
*prev
; /* prev symbol in stack */
179 struct Sym
*prev_tok
; /* previous symbol for this token */
182 /* section definition */
183 /* XXX: use directly ELF structure for parameters ? */
184 /* special flag to indicate that the section should not be linked to
186 #define SHF_PRIVATE 0x80000000
188 typedef struct Section
{
189 unsigned long data_offset
; /* current data offset */
190 unsigned char *data
; /* section data */
191 unsigned long data_allocated
; /* used for realloc() handling */
192 int sh_name
; /* elf section name (only used during output) */
193 int sh_num
; /* elf section number */
194 int sh_type
; /* elf section type */
195 int sh_flags
; /* elf section flags */
196 int sh_info
; /* elf section info */
197 int sh_addralign
; /* elf section alignment */
198 int sh_entsize
; /* elf entry size */
199 unsigned long sh_size
; /* section size (only used during output) */
200 unsigned long sh_addr
; /* address at which the section is relocated */
201 unsigned long sh_offset
; /* address at which the section is relocated */
202 int nb_hashed_syms
; /* used to resize the hash table */
203 struct Section
*link
; /* link to another section */
204 struct Section
*reloc
; /* corresponding section for relocation, if any */
205 struct Section
*hash
; /* hash table for symbols */
206 struct Section
*next
;
207 char name
[1]; /* section name */
210 typedef struct DLLReference
{
215 /* GNUC attribute definition */
216 typedef struct AttributeDef
{
219 unsigned char func_call
; /* FUNC_CDECL, FUNC_STDCALL, FUNC_FASTCALLx */
222 #define SYM_STRUCT 0x40000000 /* struct/union/enum symbol space */
223 #define SYM_FIELD 0x20000000 /* struct/union field symbol space */
224 #define SYM_FIRST_ANOM 0x10000000 /* first anonymous sym */
226 /* stored in 'Sym.c' field */
227 #define FUNC_NEW 1 /* ansi function prototype */
228 #define FUNC_OLD 2 /* old function prototype */
229 #define FUNC_ELLIPSIS 3 /* ansi function prototype with ... */
231 /* stored in 'Sym.r' field */
232 #define FUNC_CDECL 0 /* standard c call */
233 #define FUNC_STDCALL 1 /* pascal c call */
234 #define FUNC_FASTCALL1 2 /* first param in %eax */
235 #define FUNC_FASTCALL2 3 /* first parameters in %eax, %edx */
236 #define FUNC_FASTCALL3 4 /* first parameter in %eax, %edx, %ecx */
238 /* field 'Sym.t' for macros */
239 #define MACRO_OBJ 0 /* object like macro */
240 #define MACRO_FUNC 1 /* function like macro */
242 /* field 'Sym.r' for C labels */
243 #define LABEL_DEFINED 0 /* label is defined */
244 #define LABEL_FORWARD 1 /* label is forward defined */
245 #define LABEL_DECLARED 2 /* label is declared but never used */
247 /* type_decl() types */
248 #define TYPE_ABSTRACT 1 /* type without variable */
249 #define TYPE_DIRECT 2 /* type with variable */
251 #define IO_BUF_SIZE 8192
253 typedef struct BufferedFile
{
257 int line_num
; /* current line number - here to simplify code */
258 int ifndef_macro
; /* #ifndef macro / #endif search */
259 int ifndef_macro_saved
; /* saved ifndef_macro */
260 int *ifdef_stack_ptr
; /* ifdef_stack value at the start of the file */
261 char inc_type
; /* type of include */
262 char inc_filename
[512]; /* filename specified by the user */
263 char filename
[1024]; /* current filename - here to simplify code */
264 unsigned char buffer
[IO_BUF_SIZE
+ 1]; /* extra size for CH_EOB char */
267 #define CH_EOB '\\' /* end of buffer or '\0' char in file */
268 #define CH_EOF (-1) /* end of file */
270 /* parsing state (used to save parser state to reparse part of the
271 source several times) */
272 typedef struct ParseState
{
279 /* used to record tokens */
280 typedef struct TokenString
{
287 /* include file cache, used to find files faster and also to eliminate
288 inclusion if the include file is protected by #ifndef ... #endif */
289 typedef struct CachedInclude
{
291 char type
; /* '"' or '>' to give include type */
292 char filename
[1]; /* path specified in #include */
296 static struct BufferedFile
*file
;
299 static CString tokcstr
; /* current parsed string, if any */
300 /* additional informations about token */
301 static int tok_flags
;
302 #define TOK_FLAG_BOL 0x0001 /* beginning of line before */
303 #define TOK_FLAG_BOF 0x0002 /* beginning of file before */
304 #define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */
306 static int *macro_ptr
, *macro_ptr_allocated
;
307 static int *unget_saved_macro_ptr
;
308 static int unget_saved_buffer
[TOK_MAX_SIZE
+ 1];
309 static int unget_buffer_enabled
;
310 static int parse_flags
;
311 #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
312 #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
313 #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
314 token. line feed is also
316 #define PARSE_FLAG_ASM_COMMENTS 0x0008 /* '#' can be used for line comment */
318 static Section
*text_section
, *data_section
, *bss_section
; /* predefined sections */
319 static Section
*cur_text_section
; /* current section where function code is
321 static Section
*last_text_section
; /* to handle .previous asm directive */
322 /* bound check related sections */
323 static Section
*bounds_section
; /* contains global data bound description */
324 static Section
*lbounds_section
; /* contains local data bound description */
325 /* symbol sections */
326 static Section
*symtab_section
, *strtab_section
;
329 static Section
*stab_section
, *stabstr_section
;
331 /* loc : local variable index
332 ind : output code index
334 anon_sym: anonymous symbol index
336 static int rsym
, anon_sym
, ind
, loc
;
337 /* expression generation modifiers */
338 static int const_wanted
; /* true if constant wanted */
339 static int nocode_wanted
; /* true if no code generation wanted for an expression */
340 static int global_expr
; /* true if compound literals must be allocated
341 globally (used during initializers parsing */
342 static CType func_vt
; /* current function return type (used by return
345 static int last_line_num
, last_ind
, func_ind
; /* debug last line number and pc */
346 static int tok_ident
;
347 static TokenSym
**table_ident
;
348 static TokenSym
*hash_ident
[TOK_HASH_SIZE
];
349 static char token_buf
[STRING_MAX_SIZE
+ 1];
350 static char *funcname
;
351 static Sym
*global_stack
, *local_stack
;
352 static Sym
*define_stack
;
353 static Sym
*global_label_stack
, *local_label_stack
;
355 static SValue vstack
[VSTACK_SIZE
], *vtop
;
356 /* some predefined types */
357 static CType char_pointer_type
, func_old_type
, int_type
;
358 /* true if isid(c) || isnum(c) */
359 static unsigned char isidnum_table
[256];
361 /* compile with debug symbol (and use them if error during execution) */
362 static int do_debug
= 0;
364 /* compile with built-in memory and bounds checker */
365 static int do_bounds_check
= 0;
367 /* display benchmark infos */
369 static int do_bench
= 0;
371 static int total_lines
;
372 static int total_bytes
;
374 /* use GNU C extensions */
375 static int gnu_ext
= 1;
377 /* use Tiny C extensions */
378 static int tcc_ext
= 1;
380 /* max number of callers shown if error */
381 static int num_callers
= 6;
382 static const char **rt_bound_error_msg
;
384 /* XXX: get rid of this ASAP */
385 static struct TCCState
*tcc_state
;
387 /* give the path of the tcc libraries */
388 static const char *tcc_lib_path
= CONFIG_TCC_LIBDIR
"/tcc";
393 BufferedFile
**include_stack_ptr
;
394 int *ifdef_stack_ptr
;
396 /* include file handling */
397 char **include_paths
;
398 int nb_include_paths
;
399 char **sysinclude_paths
;
400 int nb_sysinclude_paths
;
401 CachedInclude
**cached_includes
;
402 int nb_cached_includes
;
404 char **library_paths
;
405 int nb_library_paths
;
407 /* array of all loaded dlls (including those referenced by loaded
409 DLLReference
**loaded_dlls
;
414 int nb_sections
; /* number of sections, including first dummy section */
419 unsigned long *got_offsets
;
421 /* give the correspondance from symtab indexes to dynsym indexes */
422 int *symtab_to_dynsym
;
424 /* temporary dynamic symbol sections (for dll loading) */
425 Section
*dynsymtab_section
;
426 /* exported dynamic symbol section */
429 int nostdinc
; /* if true, no standard headers are added */
430 int nostdlib
; /* if true, no standard libraries are added */
432 int nocommon
; /* if true, do not use common symbols for .bss data */
434 /* if true, static linking is performed */
437 /* if true, all symbols are exported */
440 /* if true, only link in referenced objects from archive */
443 /* address of text section */
444 unsigned long text_addr
;
447 /* output format, see TCC_OUTPUT_FORMAT_xxx */
450 /* C language options */
451 int char_is_unsigned
;
453 /* warning switches */
454 int warn_write_strings
;
455 int warn_unsupported
;
458 int warn_implicit_function_declaration
;
462 void (*error_func
)(void *opaque
, const char *msg
);
463 int error_set_jmp_enabled
;
464 jmp_buf error_jmp_buf
;
467 /* tiny assembler state */
470 /* see include_stack_ptr */
471 BufferedFile
*include_stack
[INCLUDE_STACK_SIZE
];
473 /* see ifdef_stack_ptr */
474 int ifdef_stack
[IFDEF_STACK_SIZE
];
477 /* The current value can be: */
478 #define VT_VALMASK 0x00ff
479 #define VT_CONST 0x00f0 /* constant in vc
480 (must be first non register value) */
481 #define VT_LLOCAL 0x00f1 /* lvalue, offset on stack */
482 #define VT_LOCAL 0x00f2 /* offset on stack */
483 #define VT_CMP 0x00f3 /* the value is stored in processor flags (in vc) */
484 #define VT_JMP 0x00f4 /* value is the consequence of jmp true (even) */
485 #define VT_JMPI 0x00f5 /* value is the consequence of jmp false (odd) */
486 #define VT_LVAL 0x0100 /* var is an lvalue */
487 #define VT_SYM 0x0200 /* a symbol value is added */
488 #define VT_MUSTCAST 0x0400 /* value must be casted to be correct (used for
489 char/short stored in integer registers) */
490 #define VT_MUSTBOUND 0x0800 /* bound checking must be done before
491 dereferencing value */
492 #define VT_BOUNDED 0x8000 /* value is bounded. The address of the
493 bounding function call point is in vc */
494 #define VT_LVAL_BYTE 0x1000 /* lvalue is a byte */
495 #define VT_LVAL_SHORT 0x2000 /* lvalue is a short */
496 #define VT_LVAL_UNSIGNED 0x4000 /* lvalue is unsigned */
497 #define VT_LVAL_TYPE (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
500 #define VT_INT 0 /* integer type */
501 #define VT_BYTE 1 /* signed byte type */
502 #define VT_SHORT 2 /* short type */
503 #define VT_VOID 3 /* void type */
504 #define VT_PTR 4 /* pointer */
505 #define VT_ENUM 5 /* enum definition */
506 #define VT_FUNC 6 /* function type */
507 #define VT_STRUCT 7 /* struct/union definition */
508 #define VT_FLOAT 8 /* IEEE float */
509 #define VT_DOUBLE 9 /* IEEE double */
510 #define VT_LDOUBLE 10 /* IEEE long double */
511 #define VT_BOOL 11 /* ISOC99 boolean type */
512 #define VT_LLONG 12 /* 64 bit integer */
513 #define VT_LONG 13 /* long integer (NEVER USED as type, only
515 #define VT_BTYPE 0x000f /* mask for basic type */
516 #define VT_UNSIGNED 0x0010 /* unsigned type */
517 #define VT_ARRAY 0x0020 /* array type (also has VT_PTR) */
518 #define VT_BITFIELD 0x0040 /* bitfield modifier */
519 #define VT_CONSTANT 0x0800 /* const modifier */
520 #define VT_VOLATILE 0x1000 /* volatile modifier */
521 #define VT_SIGNED 0x2000 /* signed type */
524 #define VT_EXTERN 0x00000080 /* extern definition */
525 #define VT_STATIC 0x00000100 /* static variable */
526 #define VT_TYPEDEF 0x00000200 /* typedef definition */
527 #define VT_INLINE 0x00000400 /* inline definition */
529 #define VT_STRUCT_SHIFT 16 /* shift for bitfield shift values */
531 /* type mask (except storage) */
532 #define VT_STORAGE (VT_EXTERN | VT_STATIC | VT_TYPEDEF | VT_INLINE)
533 #define VT_TYPE (~(VT_STORAGE))
537 /* warning: the following compare tokens depend on i386 asm code */
549 #define TOK_LAND 0xa0
553 #define TOK_MID 0xa3 /* inc/dec, to void constant */
555 #define TOK_UDIV 0xb0 /* unsigned division */
556 #define TOK_UMOD 0xb1 /* unsigned modulo */
557 #define TOK_PDIV 0xb2 /* fast division with undefined rounding for pointers */
558 #define TOK_CINT 0xb3 /* number in tokc */
559 #define TOK_CCHAR 0xb4 /* char constant in tokc */
560 #define TOK_STR 0xb5 /* pointer to string in tokc */
561 #define TOK_TWOSHARPS 0xb6 /* ## preprocessing token */
562 #define TOK_LCHAR 0xb7
563 #define TOK_LSTR 0xb8
564 #define TOK_CFLOAT 0xb9 /* float constant */
565 #define TOK_LINENUM 0xba /* line number info */
566 #define TOK_CDOUBLE 0xc0 /* double constant */
567 #define TOK_CLDOUBLE 0xc1 /* long double constant */
568 #define TOK_UMULL 0xc2 /* unsigned 32x32 -> 64 mul */
569 #define TOK_ADDC1 0xc3 /* add with carry generation */
570 #define TOK_ADDC2 0xc4 /* add with carry use */
571 #define TOK_SUBC1 0xc5 /* add with carry generation */
572 #define TOK_SUBC2 0xc6 /* add with carry use */
573 #define TOK_CUINT 0xc8 /* unsigned int constant */
574 #define TOK_CLLONG 0xc9 /* long long constant */
575 #define TOK_CULLONG 0xca /* unsigned long long constant */
576 #define TOK_ARROW 0xcb
577 #define TOK_DOTS 0xcc /* three dots */
578 #define TOK_SHR 0xcd /* unsigned shift right */
579 #define TOK_PPNUM 0xce /* preprocessor number */
581 #define TOK_SHL 0x01 /* shift left */
582 #define TOK_SAR 0x02 /* signed shift right */
584 /* assignement operators : normal operator or 0x80 */
585 #define TOK_A_MOD 0xa5
586 #define TOK_A_AND 0xa6
587 #define TOK_A_MUL 0xaa
588 #define TOK_A_ADD 0xab
589 #define TOK_A_SUB 0xad
590 #define TOK_A_DIV 0xaf
591 #define TOK_A_XOR 0xde
592 #define TOK_A_OR 0xfc
593 #define TOK_A_SHL 0x81
594 #define TOK_A_SAR 0x82
597 #define offsetof(type, field) ((size_t) &((type *)0)->field)
601 #define countof(tab) (sizeof(tab) / sizeof((tab)[0]))
604 /* WARNING: the content of this string encodes token numbers */
605 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";
607 #define TOK_EOF (-1) /* end of file */
608 #define TOK_LINEFEED 10 /* line feed */
610 /* all identificators and strings have token above that */
611 #define TOK_IDENT 256
613 /* only used for i386 asm opcodes definitions */
614 #define DEF_ASM(x) DEF(TOK_ASM_ ## x, #x)
617 DEF(TOK_ASM_ ## x ## b, #x "b") \
618 DEF(TOK_ASM_ ## x ## w, #x "w") \
619 DEF(TOK_ASM_ ## x ## l, #x "l") \
620 DEF(TOK_ASM_ ## x, #x)
623 DEF(TOK_ASM_ ## x ## w, #x "w") \
624 DEF(TOK_ASM_ ## x ## l, #x "l") \
625 DEF(TOK_ASM_ ## x, #x)
628 DEF(TOK_ASM_ ## f ## x ## s, "f" #x "s") \
629 DEF(TOK_ASM_ ## fi ## x ## l, "fi" #x "l") \
630 DEF(TOK_ASM_ ## f ## x ## l, "f" #x "l") \
631 DEF(TOK_ASM_ ## fi ## x ## s, "fi" #x "s")
634 DEF(TOK_ASM_ ## f ## x, "f" #x ) \
635 DEF(TOK_ASM_ ## f ## x ## p, "f" #x "p") \
638 #define DEF_ASMTEST(x) \
670 #define TOK_ASM_int TOK_INT
673 TOK_LAST
= TOK_IDENT
- 1,
674 #define DEF(id, str) id,
679 static const char tcc_keywords
[] =
680 #define DEF(id, str) str "\0"
685 #define TOK_UIDENT TOK_DEFINE
688 #define snprintf _snprintf
689 #define vsnprintf _vsnprintf
692 #if defined(WIN32) || defined(TCC_UCLIBC) || defined(__FreeBSD__)
693 /* currently incorrect */
694 long double strtold(const char *nptr
, char **endptr
)
696 return (long double)strtod(nptr
, endptr
);
698 float strtof(const char *nptr
, char **endptr
)
700 return (float)strtod(nptr
, endptr
);
703 /* XXX: need to define this to use them in non ISOC99 context */
704 extern float strtof (const char *__nptr
, char **__endptr
);
705 extern long double strtold (const char *__nptr
, char **__endptr
);
708 static char *pstrcpy(char *buf
, int buf_size
, const char *s
);
709 static char *pstrcat(char *buf
, int buf_size
, const char *s
);
711 static void next(void);
712 static void next_nomacro(void);
713 static void parse_expr_type(CType
*type
);
714 static void expr_type(CType
*type
);
715 static void unary_type(CType
*type
);
716 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
717 int case_reg
, int is_expr
);
718 static int expr_const(void);
719 static void expr_eq(void);
720 static void gexpr(void);
721 static void gen_inline_functions(void);
722 static void decl(int l
);
723 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
724 int first
, int size_only
);
725 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
726 int has_init
, int v
, int scope
);
728 void gv2(int rc1
, int rc2
);
729 void move_reg(int r
, int s
);
730 void save_regs(int n
);
731 void save_reg(int r
);
736 int get_reg_ex(int rc
,int rc2
);
738 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
739 const int *macro_str
, int can_read_stream
);
741 void force_charshort_cast(int t
);
742 static void gen_cast(CType
*type
);
744 static Sym
*sym_find(int v
);
745 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
);
748 static int type_size(CType
*type
, int *a
);
749 static inline CType
*pointed_type(CType
*type
);
750 static int pointed_size(CType
*type
);
751 static int lvalue_type(int t
);
752 static int parse_btype(CType
*type
, AttributeDef
*ad
);
753 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
);
754 static int is_compatible_types(CType
*type1
, CType
*type2
);
756 int ieee_finite(double d
);
757 void error(const char *fmt
, ...);
761 void lexpand_nr(void);
762 static void vpush_global_sym(CType
*type
, int v
);
763 void vset(CType
*type
, int r
, int v
);
764 void type_to_str(char *buf
, int buf_size
,
765 CType
*type
, const char *varstr
);
766 char *get_tok_str(int v
, CValue
*cv
);
767 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
768 unsigned long offset
, unsigned long size
);
769 static Sym
*external_global_sym(int v
, CType
*type
, int r
);
771 /* section generation */
772 static void section_realloc(Section
*sec
, unsigned long new_size
);
773 static void *section_ptr_add(Section
*sec
, unsigned long size
);
774 static void put_extern_sym(Sym
*sym
, Section
*section
,
775 unsigned long value
, unsigned long size
);
776 static void greloc(Section
*s
, Sym
*sym
, unsigned long addr
, int type
);
777 static int put_elf_str(Section
*s
, const char *sym
);
778 static int put_elf_sym(Section
*s
,
779 unsigned long value
, unsigned long size
,
780 int info
, int other
, int shndx
, const char *name
);
781 static int add_elf_sym(Section
*s
, unsigned long value
, unsigned long size
,
782 int info
, int sh_num
, const char *name
);
783 static void put_elf_reloc(Section
*symtab
, Section
*s
, unsigned long offset
,
784 int type
, int symbol
);
785 static void put_stabs(const char *str
, int type
, int other
, int desc
,
786 unsigned long value
);
787 static void put_stabs_r(const char *str
, int type
, int other
, int desc
,
788 unsigned long value
, Section
*sec
, int sym_index
);
789 static void put_stabn(int type
, int other
, int desc
, int value
);
790 static void put_stabd(int type
, int other
, int desc
);
791 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
);
793 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
794 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
795 static int tcc_add_file_internal(TCCState
*s
, const char *filename
, int flags
);
798 int tcc_output_coff(TCCState
*s1
, FILE *f
);
802 #ifdef CONFIG_TCC_ASM
804 typedef struct ExprValue
{
809 #define MAX_ASM_OPERANDS 30
811 typedef struct ASMOperand
{
812 int id
; /* GCC 3 optionnal identifier (0 if number only supported */
814 char asm_str
[16]; /* computed asm string for operand */
815 SValue
*vt
; /* C value of the expression */
816 int ref_index
; /* if >= 0, gives reference to a output constraint */
817 int input_index
; /* if >= 0, gives reference to an input constraint */
818 int priority
; /* priority, used to assign registers */
819 int reg
; /* if >= 0, register number used for this operand */
820 int is_llong
; /* true if double register value */
821 int is_memory
; /* true if memory operand */
822 int is_rw
; /* for '+' modifier */
825 static void asm_expr(TCCState
*s1
, ExprValue
*pe
);
826 static int asm_int_expr(TCCState
*s1
);
827 static int find_constraint(ASMOperand
*operands
, int nb_operands
,
828 const char *name
, const char **pp
);
830 static int tcc_assemble(TCCState
*s1
, int do_preprocess
);
834 static void asm_instr(void);
835 static void asm_global_instr(void);
837 /* true if float/double/long double type */
838 static inline int is_float(int t
)
842 return bt
== VT_LDOUBLE
|| bt
== VT_DOUBLE
|| bt
== VT_FLOAT
;
845 #ifdef TCC_TARGET_I386
846 #include "i386-gen.c"
849 #ifdef TCC_TARGET_ARM
853 #ifdef TCC_TARGET_C67
857 #ifdef CONFIG_TCC_STATIC
859 #define RTLD_LAZY 0x001
860 #define RTLD_NOW 0x002
861 #define RTLD_GLOBAL 0x100
862 #define RTLD_DEFAULT NULL
864 /* dummy function for profiling */
865 void *dlopen(const char *filename
, int flag
)
870 const char *dlerror(void)
875 typedef struct TCCSyms
{
880 #define TCCSYM(a) { #a, &a, },
882 /* add the symbol you want here if no dynamic linking is done */
883 static TCCSyms tcc_syms
[] = {
884 #if !defined(CONFIG_TCCBOOT)
893 void *dlsym(void *handle
, const char *symbol
)
897 while (p
->str
!= NULL
) {
898 if (!strcmp(p
->str
, symbol
))
907 /********************************************************/
909 /* we use our own 'finite' function to avoid potential problems with
910 non standard math libs */
911 /* XXX: endianness dependent */
912 int ieee_finite(double d
)
915 return ((unsigned)((p
[1] | 0x800fffff) + 1)) >> 31;
918 /* copy a string and truncate it. */
919 static char *pstrcpy(char *buf
, int buf_size
, const char *s
)
926 q_end
= buf
+ buf_size
- 1;
938 /* strcat and truncate. */
939 static char *pstrcat(char *buf
, int buf_size
, const char *s
)
944 pstrcpy(buf
+ len
, buf_size
- len
, s
);
948 static int strstart(const char *str
, const char *val
, const char **ptr
)
964 /* memory management */
970 static inline void tcc_free(void *ptr
)
973 mem_cur_size
-= malloc_usable_size(ptr
);
978 static void *tcc_malloc(unsigned long size
)
983 error("memory full");
985 mem_cur_size
+= malloc_usable_size(ptr
);
986 if (mem_cur_size
> mem_max_size
)
987 mem_max_size
= mem_cur_size
;
992 static void *tcc_mallocz(unsigned long size
)
995 ptr
= tcc_malloc(size
);
996 memset(ptr
, 0, size
);
1000 static inline void *tcc_realloc(void *ptr
, unsigned long size
)
1004 mem_cur_size
-= malloc_usable_size(ptr
);
1006 ptr1
= realloc(ptr
, size
);
1008 /* NOTE: count not correct if alloc error, but not critical */
1009 mem_cur_size
+= malloc_usable_size(ptr1
);
1010 if (mem_cur_size
> mem_max_size
)
1011 mem_max_size
= mem_cur_size
;
1016 static char *tcc_strdup(const char *str
)
1019 ptr
= tcc_malloc(strlen(str
) + 1);
1024 #define free(p) use_tcc_free(p)
1025 #define malloc(s) use_tcc_malloc(s)
1026 #define realloc(p, s) use_tcc_realloc(p, s)
1028 static void dynarray_add(void ***ptab
, int *nb_ptr
, void *data
)
1035 /* every power of two we double array size */
1036 if ((nb
& (nb
- 1)) == 0) {
1041 pp
= tcc_realloc(pp
, nb_alloc
* sizeof(void *));
1043 error("memory full");
1050 Section
*new_section(TCCState
*s1
, const char *name
, int sh_type
, int sh_flags
)
1054 sec
= tcc_mallocz(sizeof(Section
) + strlen(name
));
1055 strcpy(sec
->name
, name
);
1056 sec
->sh_type
= sh_type
;
1057 sec
->sh_flags
= sh_flags
;
1064 sec
->sh_addralign
= 4;
1067 sec
->sh_addralign
= 1;
1070 sec
->sh_addralign
= 32; /* default conservative alignment */
1074 /* only add section if not private */
1075 if (!(sh_flags
& SHF_PRIVATE
)) {
1076 sec
->sh_num
= s1
->nb_sections
;
1077 dynarray_add((void ***)&s1
->sections
, &s1
->nb_sections
, sec
);
1082 static void free_section(Section
*s
)
1088 /* realloc section and set its content to zero */
1089 static void section_realloc(Section
*sec
, unsigned long new_size
)
1092 unsigned char *data
;
1094 size
= sec
->data_allocated
;
1097 while (size
< new_size
)
1099 data
= tcc_realloc(sec
->data
, size
);
1101 error("memory full");
1102 memset(data
+ sec
->data_allocated
, 0, size
- sec
->data_allocated
);
1104 sec
->data_allocated
= size
;
1107 /* reserve at least 'size' bytes in section 'sec' from
1108 sec->data_offset. */
1109 static void *section_ptr_add(Section
*sec
, unsigned long size
)
1111 unsigned long offset
, offset1
;
1113 offset
= sec
->data_offset
;
1114 offset1
= offset
+ size
;
1115 if (offset1
> sec
->data_allocated
)
1116 section_realloc(sec
, offset1
);
1117 sec
->data_offset
= offset1
;
1118 return sec
->data
+ offset
;
1121 /* return a reference to a section, and create it if it does not
1123 Section
*find_section(TCCState
*s1
, const char *name
)
1127 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1128 sec
= s1
->sections
[i
];
1129 if (!strcmp(name
, sec
->name
))
1132 /* sections are created as PROGBITS */
1133 return new_section(s1
, name
, SHT_PROGBITS
, SHF_ALLOC
);
1136 #define SECTION_ABS ((void *)1)
1138 /* update sym->c so that it points to an external symbol in section
1139 'section' with value 'value' */
1140 static void put_extern_sym(Sym
*sym
, Section
*section
,
1141 unsigned long value
, unsigned long size
)
1143 int sym_type
, sym_bind
, sh_num
, info
;
1147 if (section
== NULL
)
1149 else if (section
== SECTION_ABS
)
1152 sh_num
= section
->sh_num
;
1154 if ((sym
->type
.t
& VT_BTYPE
) == VT_FUNC
)
1155 sym_type
= STT_FUNC
;
1157 sym_type
= STT_OBJECT
;
1158 if (sym
->type
.t
& VT_STATIC
)
1159 sym_bind
= STB_LOCAL
;
1161 sym_bind
= STB_GLOBAL
;
1163 name
= get_tok_str(sym
->v
, NULL
);
1164 #ifdef CONFIG_TCC_BCHECK
1165 if (do_bounds_check
) {
1168 /* XXX: avoid doing that for statics ? */
1169 /* if bound checking is activated, we change some function
1170 names by adding the "__bound" prefix */
1173 /* XXX: we rely only on malloc hooks */
1185 strcpy(buf
, "__bound_");
1192 info
= ELF32_ST_INFO(sym_bind
, sym_type
);
1193 sym
->c
= add_elf_sym(symtab_section
, value
, size
, info
, sh_num
, name
);
1195 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
1196 esym
->st_value
= value
;
1197 esym
->st_size
= size
;
1198 esym
->st_shndx
= sh_num
;
1202 /* add a new relocation entry to symbol 'sym' in section 's' */
1203 static void greloc(Section
*s
, Sym
*sym
, unsigned long offset
, int type
)
1206 put_extern_sym(sym
, NULL
, 0, 0);
1207 /* now we can add ELF relocation info */
1208 put_elf_reloc(symtab_section
, s
, offset
, type
, sym
->c
);
1211 static inline int isid(int c
)
1213 return (c
>= 'a' && c
<= 'z') ||
1214 (c
>= 'A' && c
<= 'Z') ||
1218 static inline int isnum(int c
)
1220 return c
>= '0' && c
<= '9';
1223 static inline int isoct(int c
)
1225 return c
>= '0' && c
<= '7';
1228 static inline int toup(int c
)
1230 if (c
>= 'a' && c
<= 'z')
1231 return c
- 'a' + 'A';
1236 static void strcat_vprintf(char *buf
, int buf_size
, const char *fmt
, va_list ap
)
1240 vsnprintf(buf
+ len
, buf_size
- len
, fmt
, ap
);
1243 static void strcat_printf(char *buf
, int buf_size
, const char *fmt
, ...)
1247 strcat_vprintf(buf
, buf_size
, fmt
, ap
);
1251 void error1(TCCState
*s1
, int is_warning
, const char *fmt
, va_list ap
)
1258 for(f
= s1
->include_stack
; f
< s1
->include_stack_ptr
; f
++)
1259 strcat_printf(buf
, sizeof(buf
), "In file included from %s:%d:\n",
1260 (*f
)->filename
, (*f
)->line_num
);
1261 if (file
->line_num
> 0) {
1262 strcat_printf(buf
, sizeof(buf
),
1263 "%s:%d: ", file
->filename
, file
->line_num
);
1265 strcat_printf(buf
, sizeof(buf
),
1266 "%s: ", file
->filename
);
1269 strcat_printf(buf
, sizeof(buf
),
1273 strcat_printf(buf
, sizeof(buf
), "warning: ");
1274 strcat_vprintf(buf
, sizeof(buf
), fmt
, ap
);
1276 if (!s1
->error_func
) {
1277 /* default case: stderr */
1278 fprintf(stderr
, "%s\n", buf
);
1280 s1
->error_func(s1
->error_opaque
, buf
);
1282 if (!is_warning
|| s1
->warn_error
)
1287 void tcc_set_error_func(TCCState
*s
, void *error_opaque
,
1288 void (*error_func
)(void *opaque
, const char *msg
))
1290 s
->error_opaque
= error_opaque
;
1291 s
->error_func
= error_func
;
1295 /* error without aborting current compilation */
1296 void error_noabort(const char *fmt
, ...)
1298 TCCState
*s1
= tcc_state
;
1302 error1(s1
, 0, fmt
, ap
);
1306 void error(const char *fmt
, ...)
1308 TCCState
*s1
= tcc_state
;
1312 error1(s1
, 0, fmt
, ap
);
1314 /* better than nothing: in some cases, we accept to handle errors */
1315 if (s1
->error_set_jmp_enabled
) {
1316 longjmp(s1
->error_jmp_buf
, 1);
1318 /* XXX: eliminate this someday */
1323 void expect(const char *msg
)
1325 error("%s expected", msg
);
1328 void warning(const char *fmt
, ...)
1330 TCCState
*s1
= tcc_state
;
1337 error1(s1
, 1, fmt
, ap
);
1344 error("'%c' expected", c
);
1348 static void test_lvalue(void)
1350 if (!(vtop
->r
& VT_LVAL
))
1354 /* allocate a new token */
1355 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
1357 TokenSym
*ts
, **ptable
;
1360 if (tok_ident
>= SYM_FIRST_ANOM
)
1361 error("memory full");
1363 /* expand token table if needed */
1364 i
= tok_ident
- TOK_IDENT
;
1365 if ((i
% TOK_ALLOC_INCR
) == 0) {
1366 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
1368 error("memory full");
1369 table_ident
= ptable
;
1372 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
1373 table_ident
[i
] = ts
;
1374 ts
->tok
= tok_ident
++;
1375 ts
->sym_define
= NULL
;
1376 ts
->sym_label
= NULL
;
1377 ts
->sym_struct
= NULL
;
1378 ts
->sym_identifier
= NULL
;
1380 ts
->hash_next
= NULL
;
1381 memcpy(ts
->str
, str
, len
);
1382 ts
->str
[len
] = '\0';
1387 #define TOK_HASH_INIT 1
1388 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
1390 /* find a token and add it if not found */
1391 static TokenSym
*tok_alloc(const char *str
, int len
)
1393 TokenSym
*ts
, **pts
;
1399 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
1400 h
&= (TOK_HASH_SIZE
- 1);
1402 pts
= &hash_ident
[h
];
1407 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
1409 pts
= &(ts
->hash_next
);
1411 return tok_alloc_new(pts
, str
, len
);
1414 /* CString handling */
1416 static void cstr_realloc(CString
*cstr
, int new_size
)
1421 size
= cstr
->size_allocated
;
1423 size
= 8; /* no need to allocate a too small first string */
1424 while (size
< new_size
)
1426 data
= tcc_realloc(cstr
->data_allocated
, size
);
1428 error("memory full");
1429 cstr
->data_allocated
= data
;
1430 cstr
->size_allocated
= size
;
1435 static void cstr_ccat(CString
*cstr
, int ch
)
1438 size
= cstr
->size
+ 1;
1439 if (size
> cstr
->size_allocated
)
1440 cstr_realloc(cstr
, size
);
1441 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
1445 static void cstr_cat(CString
*cstr
, const char *str
)
1457 /* add a wide char */
1458 static void cstr_wccat(CString
*cstr
, int ch
)
1461 size
= cstr
->size
+ sizeof(int);
1462 if (size
> cstr
->size_allocated
)
1463 cstr_realloc(cstr
, size
);
1464 *(int *)(((unsigned char *)cstr
->data
) + size
- sizeof(int)) = ch
;
1468 static void cstr_new(CString
*cstr
)
1470 memset(cstr
, 0, sizeof(CString
));
1473 /* free string and reset it to NULL */
1474 static void cstr_free(CString
*cstr
)
1476 tcc_free(cstr
->data_allocated
);
1480 #define cstr_reset(cstr) cstr_free(cstr)
1482 static CString
*cstr_dup(CString
*cstr1
)
1487 cstr
= tcc_malloc(sizeof(CString
));
1490 cstr
->size_allocated
= size
;
1491 cstr
->data_allocated
= tcc_malloc(size
);
1492 cstr
->data
= cstr
->data_allocated
;
1493 memcpy(cstr
->data_allocated
, cstr1
->data_allocated
, size
);
1497 /* XXX: unicode ? */
1498 static void add_char(CString
*cstr
, int c
)
1500 if (c
== '\'' || c
== '\"' || c
== '\\') {
1501 /* XXX: could be more precise if char or string */
1502 cstr_ccat(cstr
, '\\');
1504 if (c
>= 32 && c
<= 126) {
1507 cstr_ccat(cstr
, '\\');
1509 cstr_ccat(cstr
, 'n');
1511 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
1512 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
1513 cstr_ccat(cstr
, '0' + (c
& 7));
1518 /* XXX: buffer overflow */
1519 /* XXX: float tokens */
1520 char *get_tok_str(int v
, CValue
*cv
)
1522 static char buf
[STRING_MAX_SIZE
+ 1];
1523 static CString cstr_buf
;
1529 /* NOTE: to go faster, we give a fixed buffer for small strings */
1530 cstr_reset(&cstr_buf
);
1531 cstr_buf
.data
= buf
;
1532 cstr_buf
.size_allocated
= sizeof(buf
);
1538 /* XXX: not quite exact, but only useful for testing */
1539 sprintf(p
, "%u", cv
->ui
);
1543 /* XXX: not quite exact, but only useful for testing */
1544 sprintf(p
, "%Lu", cv
->ull
);
1548 cstr_ccat(&cstr_buf
, '\'');
1549 add_char(&cstr_buf
, cv
->i
);
1550 cstr_ccat(&cstr_buf
, '\'');
1551 cstr_ccat(&cstr_buf
, '\0');
1555 len
= cstr
->size
- 1;
1557 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1558 cstr_ccat(&cstr_buf
, '\0');
1563 cstr_ccat(&cstr_buf
, '\"');
1565 len
= cstr
->size
- 1;
1567 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1569 len
= (cstr
->size
/ sizeof(int)) - 1;
1571 add_char(&cstr_buf
, ((int *)cstr
->data
)[i
]);
1573 cstr_ccat(&cstr_buf
, '\"');
1574 cstr_ccat(&cstr_buf
, '\0');
1583 return strcpy(p
, "<<=");
1585 return strcpy(p
, ">>=");
1587 if (v
< TOK_IDENT
) {
1588 /* search in two bytes table */
1602 } else if (v
< tok_ident
) {
1603 return table_ident
[v
- TOK_IDENT
]->str
;
1604 } else if (v
>= SYM_FIRST_ANOM
) {
1605 /* special name for anonymous symbol */
1606 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
1608 /* should never happen */
1613 return cstr_buf
.data
;
1616 /* push, without hashing */
1617 static Sym
*sym_push2(Sym
**ps
, int v
, int t
, int c
)
1620 s
= tcc_malloc(sizeof(Sym
));
1631 /* find a symbol and return its associated structure. 's' is the top
1632 of the symbol stack */
1633 static Sym
*sym_find2(Sym
*s
, int v
)
1643 /* structure lookup */
1644 static inline Sym
*struct_find(int v
)
1647 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1649 return table_ident
[v
]->sym_struct
;
1652 /* find an identifier */
1653 static inline Sym
*sym_find(int v
)
1656 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1658 return table_ident
[v
]->sym_identifier
;
1661 /* push a given symbol on the symbol stack */
1662 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
)
1671 s
= sym_push2(ps
, v
, type
->t
, c
);
1672 s
->type
.ref
= type
->ref
;
1674 /* don't record fields or anonymous symbols */
1676 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1677 /* record symbol in token array */
1678 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1680 ps
= &ts
->sym_struct
;
1682 ps
= &ts
->sym_identifier
;
1689 /* push a global identifier */
1690 static Sym
*global_identifier_push(int v
, int t
, int c
)
1693 s
= sym_push2(&global_stack
, v
, t
, c
);
1694 /* don't record anonymous symbol */
1695 if (v
< SYM_FIRST_ANOM
) {
1696 ps
= &table_ident
[v
- TOK_IDENT
]->sym_identifier
;
1697 /* modify the top most local identifier, so that
1698 sym_identifier will point to 's' when popped */
1700 ps
= &(*ps
)->prev_tok
;
1707 /* pop symbols until top reaches 'b' */
1708 static void sym_pop(Sym
**ptop
, Sym
*b
)
1718 /* remove symbol in token array */
1720 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1721 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1723 ps
= &ts
->sym_struct
;
1725 ps
= &ts
->sym_identifier
;
1736 BufferedFile
*tcc_open(TCCState
*s1
, const char *filename
)
1741 fd
= open(filename
, O_RDONLY
| O_BINARY
);
1744 bf
= tcc_malloc(sizeof(BufferedFile
));
1750 bf
->buf_ptr
= bf
->buffer
;
1751 bf
->buf_end
= bf
->buffer
;
1752 bf
->buffer
[0] = CH_EOB
; /* put eob symbol */
1753 pstrcpy(bf
->filename
, sizeof(bf
->filename
), filename
);
1755 bf
->ifndef_macro
= 0;
1756 bf
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
1757 // printf("opening '%s'\n", filename);
1761 void tcc_close(BufferedFile
*bf
)
1763 total_lines
+= bf
->line_num
;
1768 /* fill input buffer and peek next char */
1769 static int tcc_peekc_slow(BufferedFile
*bf
)
1772 /* only tries to read if really end of buffer */
1773 if (bf
->buf_ptr
>= bf
->buf_end
) {
1775 #if defined(PARSE_DEBUG)
1780 len
= read(bf
->fd
, bf
->buffer
, len
);
1787 bf
->buf_ptr
= bf
->buffer
;
1788 bf
->buf_end
= bf
->buffer
+ len
;
1789 *bf
->buf_end
= CH_EOB
;
1791 if (bf
->buf_ptr
< bf
->buf_end
) {
1792 return bf
->buf_ptr
[0];
1794 bf
->buf_ptr
= bf
->buf_end
;
1799 /* return the current character, handling end of block if necessary
1801 static int handle_eob(void)
1803 return tcc_peekc_slow(file
);
1806 /* read next char from current input file and handle end of input buffer */
1807 static inline void inp(void)
1809 ch
= *(++(file
->buf_ptr
));
1810 /* end of buffer/file handling */
1815 /* handle '\[\r]\n' */
1816 static void handle_stray(void)
1818 while (ch
== '\\') {
1823 } else if (ch
== '\r') {
1831 error("stray '\\' in program");
1836 /* skip the stray and handle the \\n case. Output an error if
1837 incorrect char after the stray */
1838 static int handle_stray1(uint8_t *p
)
1842 if (p
>= file
->buf_end
) {
1859 /* handle just the EOB case, but not stray */
1860 #define PEEKC_EOB(c, p)\
1871 /* handle the complicated stray case */
1872 #define PEEKC(c, p)\
1877 c = handle_stray1(p);\
1882 /* input with '\[\r]\n' handling. Note that this function cannot
1883 handle other characters after '\', so you cannot call it inside
1884 strings or comments */
1885 static void minp(void)
1893 /* single line C++ comments */
1894 static uint8_t *parse_line_comment(uint8_t *p
)
1902 if (c
== '\n' || c
== CH_EOF
) {
1904 } else if (c
== '\\') {
1913 } else if (c
== '\r') {
1931 static uint8_t *parse_comment(uint8_t *p
)
1937 /* fast skip loop */
1940 if (c
== '\n' || c
== '*' || c
== '\\')
1944 if (c
== '\n' || c
== '*' || c
== '\\')
1948 /* now we can handle all the cases */
1952 } else if (c
== '*') {
1958 } else if (c
== '/') {
1959 goto end_of_comment
;
1960 } else if (c
== '\\') {
1965 /* skip '\[\r]\n', otherwise just skip the stray */
1971 } else if (c
== '\r') {
1988 /* stray, eob or eof */
1993 error("unexpected end of file in comment");
1994 } else if (c
== '\\') {
2006 /* space exlcuding newline */
2007 static inline int is_space(int ch
)
2009 return ch
== ' ' || ch
== '\t' || ch
== '\v' || ch
== '\f' || ch
== '\r';
2012 static inline void skip_spaces(void)
2014 while (is_space(ch
))
2018 /* parse a string without interpreting escapes */
2019 static uint8_t *parse_pp_string(uint8_t *p
,
2020 int sep
, CString
*str
)
2028 } else if (c
== '\\') {
2033 unterminated_string
:
2034 /* XXX: indicate line number of start of string */
2035 error("missing terminating %c character", sep
);
2036 } else if (c
== '\\') {
2037 /* escape : just skip \[\r]\n */
2042 } else if (c
== '\r') {
2045 expect("'\n' after '\r'");
2048 } else if (c
== CH_EOF
) {
2049 goto unterminated_string
;
2052 cstr_ccat(str
, '\\');
2058 } else if (c
== '\n') {
2061 } else if (c
== '\r') {
2065 cstr_ccat(str
, '\r');
2081 /* skip block of text until #else, #elif or #endif. skip also pairs of
2083 void preprocess_skip(void)
2085 int a
, start_of_line
, c
;
2112 } else if (c
== '\\') {
2113 /* XXX: incorrect: should not give an error */
2114 ch
= file
->buf_ptr
[0];
2122 p
= parse_pp_string(p
, c
, NULL
);
2131 p
= parse_comment(p
);
2132 } else if (ch
== '/') {
2133 p
= parse_line_comment(p
);
2139 if (start_of_line
) {
2144 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
2146 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
2148 else if (tok
== TOK_ENDIF
)
2162 /* ParseState handling */
2164 /* XXX: currently, no include file info is stored. Thus, we cannot display
2165 accurate messages if the function or data definition spans multiple
2168 /* save current parse state in 's' */
2169 void save_parse_state(ParseState
*s
)
2171 s
->line_num
= file
->line_num
;
2172 s
->macro_ptr
= macro_ptr
;
2177 /* restore parse state from 's' */
2178 void restore_parse_state(ParseState
*s
)
2180 file
->line_num
= s
->line_num
;
2181 macro_ptr
= s
->macro_ptr
;
2186 /* return the number of additional 'ints' necessary to store the
2188 static inline int tok_ext_size(int t
)
2207 return LDOUBLE_SIZE
/ 4;
2213 /* token string handling */
2215 static inline void tok_str_new(TokenString
*s
)
2219 s
->allocated_len
= 0;
2220 s
->last_line_num
= -1;
2223 static void tok_str_free(int *str
)
2232 /* NOTE: we test zero separately so that GCC can generate a
2233 table for the following switch */
2248 /* XXX: use a macro to be portable on 64 bit ? */
2249 cstr
= (CString
*)p
[1];
2260 p
+= 1 + (LDOUBLE_SIZE
/ 4);
2270 static int *tok_str_realloc(TokenString
*s
)
2274 if (s
->allocated_len
== 0) {
2277 len
= s
->allocated_len
* 2;
2279 str
= tcc_realloc(s
->str
, len
* sizeof(int));
2281 error("memory full");
2282 s
->allocated_len
= len
;
2287 static void tok_str_add(TokenString
*s
, int t
)
2293 if (len
>= s
->allocated_len
)
2294 str
= tok_str_realloc(s
);
2299 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
2306 /* allocate space for worst case */
2307 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
2308 str
= tok_str_realloc(s
);
2317 str
[len
++] = cv
->tab
[0];
2322 str
[len
++] = (int)cstr_dup(cv
->cstr
);
2327 #if LDOUBLE_SIZE == 8
2330 str
[len
++] = cv
->tab
[0];
2331 str
[len
++] = cv
->tab
[1];
2333 #if LDOUBLE_SIZE == 12
2335 str
[len
++] = cv
->tab
[0];
2336 str
[len
++] = cv
->tab
[1];
2337 str
[len
++] = cv
->tab
[2];
2338 #elif LDOUBLE_SIZE != 8
2339 #error add long double size support
2348 /* add the current parse token in token string 's' */
2349 static void tok_str_add_tok(TokenString
*s
)
2353 /* save line number info */
2354 if (file
->line_num
!= s
->last_line_num
) {
2355 s
->last_line_num
= file
->line_num
;
2356 cval
.i
= s
->last_line_num
;
2357 tok_str_add2(s
, TOK_LINENUM
, &cval
);
2359 tok_str_add2(s
, tok
, &tokc
);
2362 #if LDOUBLE_SIZE == 12
2363 #define LDOUBLE_GET(p, cv) \
2367 #elif LDOUBLE_SIZE == 8
2368 #define LDOUBLE_GET(p, cv) \
2372 #error add long double size support
2376 /* get a token from an integer array and increment pointer
2377 accordingly. we code it as a macro to avoid pointer aliasing. */
2378 #define TOK_GET(t, p, cv) \
2400 case TOK_CLDOUBLE: \
2401 LDOUBLE_GET(p, cv); \
2402 p += LDOUBLE_SIZE / 4; \
2409 /* defines handling */
2410 static inline void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
2414 s
= sym_push2(&define_stack
, v
, macro_type
, (int)str
);
2415 s
->next
= first_arg
;
2416 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
2419 /* undefined a define symbol. Its name is just set to zero */
2420 static void define_undef(Sym
*s
)
2424 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2425 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2429 static inline Sym
*define_find(int v
)
2432 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2434 return table_ident
[v
]->sym_define
;
2437 /* free define stack until top reaches 'b' */
2438 static void free_defines(Sym
*b
)
2446 /* do not free args or predefined defines */
2448 tok_str_free((int *)top
->c
);
2450 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2451 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2459 static Sym
*label_find(int v
)
2462 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2464 return table_ident
[v
]->sym_label
;
2467 static Sym
*label_push(Sym
**ptop
, int v
, int flags
)
2470 s
= sym_push2(ptop
, v
, 0, 0);
2472 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
2473 if (ptop
== &global_label_stack
) {
2474 /* modify the top most local identifier, so that
2475 sym_identifier will point to 's' when popped */
2477 ps
= &(*ps
)->prev_tok
;
2484 /* pop labels until element last is reached. Look if any labels are
2485 undefined. Define symbols if '&&label' was used. */
2486 static void label_pop(Sym
**ptop
, Sym
*slast
)
2489 for(s
= *ptop
; s
!= slast
; s
= s1
) {
2491 if (s
->r
== LABEL_DECLARED
) {
2492 warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
2493 } else if (s
->r
== LABEL_FORWARD
) {
2494 error("label '%s' used but not defined",
2495 get_tok_str(s
->v
, NULL
));
2498 /* define corresponding symbol. A size of
2500 put_extern_sym(s
, cur_text_section
, (long)s
->next
, 1);
2504 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
2510 /* eval an expression for #if/#elif */
2511 static int expr_preprocess(void)
2517 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2518 next(); /* do macro subst */
2519 if (tok
== TOK_DEFINED
) {
2524 c
= define_find(tok
) != 0;
2529 } else if (tok
>= TOK_IDENT
) {
2530 /* if undefined macro */
2534 tok_str_add_tok(&str
);
2536 tok_str_add(&str
, -1); /* simulate end of file */
2537 tok_str_add(&str
, 0);
2538 /* now evaluate C constant expression */
2539 macro_ptr
= str
.str
;
2543 tok_str_free(str
.str
);
2547 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
2548 static void tok_print(int *str
)
2554 TOK_GET(t
, str
, cval
);
2557 printf(" %s", get_tok_str(t
, &cval
));
2563 /* parse after #define */
2564 static void parse_define(void)
2566 Sym
*s
, *first
, **ps
;
2567 int v
, t
, varg
, is_vaargs
, c
;
2572 error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
2573 /* XXX: should check if same macro (ANSI) */
2576 /* '(' must be just after macro definition for MACRO_FUNC */
2577 c
= file
->buf_ptr
[0];
2579 c
= handle_stray1(file
->buf_ptr
);
2584 while (tok
!= ')') {
2588 if (varg
== TOK_DOTS
) {
2589 varg
= TOK___VA_ARGS__
;
2591 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
2595 if (varg
< TOK_IDENT
)
2596 error("badly punctuated parameter list");
2597 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
2608 /* EOF testing necessary for '-D' handling */
2609 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2610 tok_str_add2(&str
, tok
, &tokc
);
2613 tok_str_add(&str
, 0);
2615 printf("define %s %d: ", get_tok_str(v
, NULL
), t
);
2618 define_push(v
, t
, str
.str
, first
);
2621 /* XXX: use a token or a hash table to accelerate matching ? */
2622 static CachedInclude
*search_cached_include(TCCState
*s1
,
2623 int type
, const char *filename
)
2628 for(i
= 0;i
< s1
->nb_cached_includes
; i
++) {
2629 e
= s1
->cached_includes
[i
];
2630 if (e
->type
== type
&& !strcmp(e
->filename
, filename
))
2636 static inline void add_cached_include(TCCState
*s1
, int type
,
2637 const char *filename
, int ifndef_macro
)
2641 if (search_cached_include(s1
, type
, filename
))
2644 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
2646 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
2650 strcpy(e
->filename
, filename
);
2651 e
->ifndef_macro
= ifndef_macro
;
2652 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
2655 /* is_bof is true if first non space token at beginning of file */
2656 static void preprocess(int is_bof
)
2658 TCCState
*s1
= tcc_state
;
2659 int size
, i
, c
, n
, saved_parse_flags
;
2660 char buf
[1024], *q
, *p
;
2666 saved_parse_flags
= parse_flags
;
2667 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
|
2668 PARSE_FLAG_LINEFEED
;
2678 s
= define_find(tok
);
2679 /* undefine symbol by putting an invalid name */
2684 ch
= file
->buf_ptr
[0];
2685 /* XXX: incorrect if comments : use next_nomacro with a special mode */
2690 } else if (ch
== '\"') {
2693 /* XXX: better stray handling */
2696 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
2697 if ((q
- buf
) < sizeof(buf
) - 1)
2704 /* eat all spaces and comments after include */
2705 /* XXX: slightly incorrect */
2706 while (ch1
!= '\n' && ch1
!= CH_EOF
)
2710 /* computed #include : either we have only strings or
2711 we have anything enclosed in '<>' */
2714 if (tok
== TOK_STR
) {
2715 while (tok
!= TOK_LINEFEED
) {
2716 if (tok
!= TOK_STR
) {
2718 error("'#include' expects \"FILENAME\" or <FILENAME>");
2720 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
2726 while (tok
!= TOK_LINEFEED
) {
2727 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
2731 /* check syntax and remove '<>' */
2732 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
2733 goto include_syntax
;
2734 memmove(buf
, buf
+ 1, len
- 2);
2735 buf
[len
- 2] = '\0';
2740 e
= search_cached_include(s1
, c
, buf
);
2741 if (e
&& define_find(e
->ifndef_macro
)) {
2742 /* no need to parse the include because the 'ifndef macro'
2745 printf("%s: skipping %s\n", file
->filename
, buf
);
2749 /* first search in current dir if "header.h" */
2751 p
= strrchr(file
->filename
, '/');
2753 size
= p
+ 1 - file
->filename
;
2754 if (size
> sizeof(buf1
) - 1)
2755 size
= sizeof(buf1
) - 1;
2756 memcpy(buf1
, file
->filename
, size
);
2758 pstrcat(buf1
, sizeof(buf1
), buf
);
2759 f
= tcc_open(s1
, buf1
);
2763 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
2764 error("#include recursion too deep");
2765 /* now search in all the include paths */
2766 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
2767 for(i
= 0; i
< n
; i
++) {
2769 if (i
< s1
->nb_include_paths
)
2770 path
= s1
->include_paths
[i
];
2772 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
2773 pstrcpy(buf1
, sizeof(buf1
), path
);
2774 pstrcat(buf1
, sizeof(buf1
), "/");
2775 pstrcat(buf1
, sizeof(buf1
), buf
);
2776 f
= tcc_open(s1
, buf1
);
2780 error("include file '%s' not found", buf
);
2784 printf("%s: including %s\n", file
->filename
, buf1
);
2787 pstrcpy(f
->inc_filename
, sizeof(f
->inc_filename
), buf
);
2788 /* push current file in stack */
2789 /* XXX: fix current line init */
2790 *s1
->include_stack_ptr
++ = file
;
2792 /* add include file debug info */
2794 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
2796 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
2797 ch
= file
->buf_ptr
[0];
2805 c
= expr_preprocess();
2811 if (tok
< TOK_IDENT
)
2812 error("invalid argument for '#if%sdef'", c
? "n" : "");
2816 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
2818 file
->ifndef_macro
= tok
;
2821 c
= (define_find(tok
) != 0) ^ c
;
2823 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
2824 error("memory full");
2825 *s1
->ifdef_stack_ptr
++ = c
;
2828 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
2829 error("#else without matching #if");
2830 if (s1
->ifdef_stack_ptr
[-1] & 2)
2831 error("#else after #else");
2832 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
2835 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
2836 error("#elif without matching #if");
2837 c
= s1
->ifdef_stack_ptr
[-1];
2839 error("#elif after #else");
2840 /* last #if/#elif expression was true: we skip */
2843 c
= expr_preprocess();
2844 s1
->ifdef_stack_ptr
[-1] = c
;
2854 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
2855 error("#endif without matching #if");
2856 s1
->ifdef_stack_ptr
--;
2857 /* '#ifndef macro' was at the start of file. Now we check if
2858 an '#endif' is exactly at the end of file */
2859 if (file
->ifndef_macro
&&
2860 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
2861 file
->ifndef_macro_saved
= file
->ifndef_macro
;
2862 /* need to set to zero to avoid false matches if another
2863 #ifndef at middle of file */
2864 file
->ifndef_macro
= 0;
2865 while (tok
!= TOK_LINEFEED
)
2867 tok_flags
|= TOK_FLAG_ENDIF
;
2873 if (tok
!= TOK_CINT
)
2875 file
->line_num
= tokc
.i
- 1; /* the line number will be incremented after */
2877 if (tok
!= TOK_LINEFEED
) {
2880 pstrcpy(file
->filename
, sizeof(file
->filename
),
2881 (char *)tokc
.cstr
->data
);
2887 ch
= file
->buf_ptr
[0];
2890 while (ch
!= '\n' && ch
!= CH_EOF
) {
2891 if ((q
- buf
) < sizeof(buf
) - 1)
2897 error("#error %s", buf
);
2899 warning("#warning %s", buf
);
2905 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_CINT
) {
2906 /* '!' is ignored to allow C scripts. numbers are ignored
2907 to emulate cpp behaviour */
2909 if (!(saved_parse_flags
& PARSE_FLAG_ASM_COMMENTS
))
2910 error("invalid preprocessing directive #%s", get_tok_str(tok
, &tokc
));
2914 /* ignore other preprocess commands or #! for C scripts */
2915 while (tok
!= TOK_LINEFEED
)
2918 parse_flags
= saved_parse_flags
;
2921 /* evaluate escape codes in a string. */
2922 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
2937 case '0': case '1': case '2': case '3':
2938 case '4': case '5': case '6': case '7':
2939 /* at most three octal digits */
2944 n
= n
* 8 + c
- '0';
2948 n
= n
* 8 + c
- '0';
2953 goto add_char_nonext
;
2959 if (c
>= 'a' && c
<= 'f')
2961 else if (c
>= 'A' && c
<= 'F')
2971 goto add_char_nonext
;
2995 goto invalid_escape
;
3005 if (c
>= '!' && c
<= '~')
3006 warning("unknown escape sequence: \'\\%c\'", c
);
3008 warning("unknown escape sequence: \'\\x%x\'", c
);
3015 cstr_ccat(outstr
, c
);
3017 cstr_wccat(outstr
, c
);
3019 /* add a trailing '\0' */
3021 cstr_ccat(outstr
, '\0');
3023 cstr_wccat(outstr
, '\0');
3026 /* we use 64 bit numbers */
3029 /* bn = (bn << shift) | or_val */
3030 void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
3034 for(i
=0;i
<BN_SIZE
;i
++) {
3036 bn
[i
] = (v
<< shift
) | or_val
;
3037 or_val
= v
>> (32 - shift
);
3041 void bn_zero(unsigned int *bn
)
3044 for(i
=0;i
<BN_SIZE
;i
++) {
3049 /* parse number in null terminated string 'p' and return it in the
3051 void parse_number(const char *p
)
3053 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
3055 unsigned int bn
[BN_SIZE
];
3066 goto float_frac_parse
;
3067 } else if (t
== '0') {
3068 if (ch
== 'x' || ch
== 'X') {
3072 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
3078 /* parse all digits. cannot check octal numbers at this stage
3079 because of floating point constants */
3081 if (ch
>= 'a' && ch
<= 'f')
3083 else if (ch
>= 'A' && ch
<= 'F')
3091 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
3093 error("number too long");
3099 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
3100 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
3102 /* NOTE: strtox should support that for hexa numbers, but
3103 non ISOC99 libcs do not support it, so we prefer to do
3105 /* hexadecimal or binary floats */
3106 /* XXX: handle overflows */
3118 } else if (t
>= 'a') {
3120 } else if (t
>= 'A') {
3125 bn_lshift(bn
, shift
, t
);
3132 if (t
>= 'a' && t
<= 'f') {
3134 } else if (t
>= 'A' && t
<= 'F') {
3136 } else if (t
>= '0' && t
<= '9') {
3142 error("invalid digit");
3143 bn_lshift(bn
, shift
, t
);
3148 if (ch
!= 'p' && ch
!= 'P')
3155 } else if (ch
== '-') {
3159 if (ch
< '0' || ch
> '9')
3160 expect("exponent digits");
3161 while (ch
>= '0' && ch
<= '9') {
3162 exp_val
= exp_val
* 10 + ch
- '0';
3165 exp_val
= exp_val
* s
;
3167 /* now we can generate the number */
3168 /* XXX: should patch directly float number */
3169 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
3170 d
= ldexp(d
, exp_val
- frac_bits
);
3175 /* float : should handle overflow */
3177 } else if (t
== 'L') {
3180 /* XXX: not large enough */
3181 tokc
.ld
= (long double)d
;
3187 /* decimal floats */
3189 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3194 while (ch
>= '0' && ch
<= '9') {
3195 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3201 if (ch
== 'e' || ch
== 'E') {
3202 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3206 if (ch
== '-' || ch
== '+') {
3207 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3212 if (ch
< '0' || ch
> '9')
3213 expect("exponent digits");
3214 while (ch
>= '0' && ch
<= '9') {
3215 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3227 tokc
.f
= strtof(token_buf
, NULL
);
3228 } else if (t
== 'L') {
3231 tokc
.ld
= strtold(token_buf
, NULL
);
3234 tokc
.d
= strtod(token_buf
, NULL
);
3238 unsigned long long n
, n1
;
3241 /* integer number */
3244 if (b
== 10 && *q
== '0') {
3251 /* no need for checks except for base 10 / 8 errors */
3254 } else if (t
>= 'a') {
3256 } else if (t
>= 'A') {
3261 error("invalid digit");
3265 /* detect overflow */
3266 /* XXX: this test is not reliable */
3268 error("integer constant overflow");
3271 /* XXX: not exactly ANSI compliant */
3272 if ((n
& 0xffffffff00000000LL
) != 0) {
3277 } else if (n
> 0x7fffffff) {
3288 error("three 'l's in integer constant");
3291 if (tok
== TOK_CINT
)
3293 else if (tok
== TOK_CUINT
)
3297 } else if (t
== 'U') {
3299 error("two 'u's in integer constant");
3301 if (tok
== TOK_CINT
)
3303 else if (tok
== TOK_CLLONG
)
3310 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
3318 #define PARSE2(c1, tok1, c2, tok2) \
3329 /* return next token without macro substitution */
3330 static inline void next_nomacro1(void)
3350 /* first look if it is in fact an end of buffer */
3351 if (p
>= file
->buf_end
) {
3355 if (p
>= file
->buf_end
)
3368 TCCState
*s1
= tcc_state
;
3369 if (parse_flags
& PARSE_FLAG_LINEFEED
) {
3371 } else if (s1
->include_stack_ptr
== s1
->include_stack
||
3372 !(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3373 /* no include left : end of file. */
3376 /* pop include file */
3378 /* test if previous '#endif' was after a #ifdef at
3380 if (tok_flags
& TOK_FLAG_ENDIF
) {
3382 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
3384 add_cached_include(s1
, file
->inc_type
, file
->inc_filename
,
3385 file
->ifndef_macro_saved
);
3388 /* add end of include file debug info */
3390 put_stabd(N_EINCL
, 0, 0);
3392 /* pop include stack */
3394 s1
->include_stack_ptr
--;
3395 file
= *s1
->include_stack_ptr
;
3403 if (parse_flags
& PARSE_FLAG_LINEFEED
) {
3407 tok_flags
|= TOK_FLAG_BOL
;
3416 if ((tok_flags
& TOK_FLAG_BOL
) &&
3417 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3419 preprocess(tok_flags
& TOK_FLAG_BOF
);
3425 tok
= TOK_TWOSHARPS
;
3427 if (parse_flags
& PARSE_FLAG_ASM_COMMENTS
) {
3428 p
= parse_line_comment(p
- 1);
3437 case 'a': case 'b': case 'c': case 'd':
3438 case 'e': case 'f': case 'g': case 'h':
3439 case 'i': case 'j': case 'k': case 'l':
3440 case 'm': case 'n': case 'o': case 'p':
3441 case 'q': case 'r': case 's': case 't':
3442 case 'u': case 'v': case 'w': case 'x':
3444 case 'A': case 'B': case 'C': case 'D':
3445 case 'E': case 'F': case 'G': case 'H':
3446 case 'I': case 'J': case 'K':
3447 case 'M': case 'N': case 'O': case 'P':
3448 case 'Q': case 'R': case 'S': case 'T':
3449 case 'U': case 'V': case 'W': case 'X':
3455 h
= TOK_HASH_FUNC(h
, c
);
3459 if (!isidnum_table
[c
])
3461 h
= TOK_HASH_FUNC(h
, c
);
3468 /* fast case : no stray found, so we have the full token
3469 and we have already hashed it */
3471 h
&= (TOK_HASH_SIZE
- 1);
3472 pts
= &hash_ident
[h
];
3477 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
3479 pts
= &(ts
->hash_next
);
3481 ts
= tok_alloc_new(pts
, p1
, len
);
3485 cstr_reset(&tokcstr
);
3488 cstr_ccat(&tokcstr
, *p1
);
3494 while (isidnum_table
[c
]) {
3495 cstr_ccat(&tokcstr
, c
);
3498 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
3504 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
3506 goto parse_ident_fast
;
3509 if (c
== '\'' || c
== '\"') {
3513 cstr_reset(&tokcstr
);
3514 cstr_ccat(&tokcstr
, 'L');
3515 goto parse_ident_slow
;
3519 case '0': case '1': case '2': case '3':
3520 case '4': case '5': case '6': case '7':
3523 cstr_reset(&tokcstr
);
3524 /* after the first digit, accept digits, alpha, '.' or sign if
3525 prefixed by 'eEpP' */
3529 cstr_ccat(&tokcstr
, c
);
3531 if (!(isnum(c
) || isid(c
) || c
== '.' ||
3532 ((c
== '+' || c
== '-') &&
3533 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
3536 /* We add a trailing '\0' to ease parsing */
3537 cstr_ccat(&tokcstr
, '\0');
3538 tokc
.cstr
= &tokcstr
;
3542 /* special dot handling because it can also start a number */
3545 cstr_reset(&tokcstr
);
3546 cstr_ccat(&tokcstr
, '.');
3548 } else if (c
== '.') {
3568 /* parse the string */
3570 p
= parse_pp_string(p
, sep
, &str
);
3571 cstr_ccat(&str
, '\0');
3573 /* eval the escape (should be done as TOK_PPNUM) */
3574 cstr_reset(&tokcstr
);
3575 parse_escape_string(&tokcstr
, str
.data
, is_long
);
3580 /* XXX: make it portable */
3584 char_size
= sizeof(int);
3585 if (tokcstr
.size
<= char_size
)
3586 error("empty character constant");
3587 if (tokcstr
.size
> 2 * char_size
)
3588 warning("multi-character character constant");
3590 tokc
.i
= *(int8_t *)tokcstr
.data
;
3593 tokc
.i
= *(int *)tokcstr
.data
;
3597 tokc
.cstr
= &tokcstr
;
3611 } else if (c
== '<') {
3629 } else if (c
== '>') {
3647 } else if (c
== '=') {
3660 } else if (c
== '=') {
3673 } else if (c
== '=') {
3686 } else if (c
== '=') {
3689 } else if (c
== '>') {
3697 PARSE2('!', '!', '=', TOK_NE
)
3698 PARSE2('=', '=', '=', TOK_EQ
)
3699 PARSE2('*', '*', '=', TOK_A_MUL
)
3700 PARSE2('%', '%', '=', TOK_A_MOD
)
3701 PARSE2('^', '^', '=', TOK_A_XOR
)
3703 /* comments or operator */
3707 p
= parse_comment(p
);
3709 } else if (c
== '/') {
3710 p
= parse_line_comment(p
);
3712 } else if (c
== '=') {
3732 case '$': /* only used in assembler */
3737 error("unrecognized character \\x%02x", c
);
3742 #if defined(PARSE_DEBUG)
3743 printf("token = %s\n", get_tok_str(tok
, &tokc
));
3747 /* return next token without macro substitution. Can read input from
3749 static void next_nomacro(void)
3755 TOK_GET(tok
, macro_ptr
, tokc
);
3756 if (tok
== TOK_LINENUM
) {
3757 file
->line_num
= tokc
.i
;
3766 /* substitute args in macro_str and return allocated string */
3767 static int *macro_arg_subst(Sym
**nested_list
, int *macro_str
, Sym
*args
)
3769 int *st
, last_tok
, t
, notfirst
;
3778 TOK_GET(t
, macro_str
, cval
);
3783 TOK_GET(t
, macro_str
, cval
);
3786 s
= sym_find2(args
, t
);
3793 cstr_ccat(&cstr
, ' ');
3794 TOK_GET(t
, st
, cval
);
3795 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
3798 cstr_ccat(&cstr
, '\0');
3800 printf("stringize: %s\n", (char *)cstr
.data
);
3804 tok_str_add2(&str
, TOK_STR
, &cval
);
3807 tok_str_add2(&str
, t
, &cval
);
3809 } else if (t
>= TOK_IDENT
) {
3810 s
= sym_find2(args
, t
);
3813 /* if '##' is present before or after, no arg substitution */
3814 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
3815 /* special case for var arg macros : ## eats the
3816 ',' if empty VA_ARGS variable. */
3817 /* XXX: test of the ',' is not 100%
3818 reliable. should fix it to avoid security
3820 if (gnu_ext
&& s
->type
.t
&&
3821 last_tok
== TOK_TWOSHARPS
&&
3822 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
3824 /* suppress ',' '##' */
3827 /* suppress '##' and add variable */
3835 TOK_GET(t1
, st
, cval
);
3838 tok_str_add2(&str
, t1
, &cval
);
3842 /* NOTE: the stream cannot be read when macro
3843 substituing an argument */
3844 macro_subst(&str
, nested_list
, st
, 0);
3847 tok_str_add(&str
, t
);
3850 tok_str_add2(&str
, t
, &cval
);
3854 tok_str_add(&str
, 0);
3858 static char const ab_month_name
[12][4] =
3860 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3861 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3864 /* do macro substitution of current token with macro 's' and add
3865 result to (tok_str,tok_len). 'nested_list' is the list of all
3866 macros we got inside to avoid recursing. Return non zero if no
3867 substitution needs to be done */
3868 static int macro_subst_tok(TokenString
*tok_str
,
3869 Sym
**nested_list
, Sym
*s
, int can_read_stream
)
3871 Sym
*args
, *sa
, *sa1
;
3872 int mstr_allocated
, parlevel
, *mstr
, t
, t1
;
3879 /* if symbol is a macro, prepare substitution */
3880 /* special macros */
3881 if (tok
== TOK___LINE__
) {
3882 snprintf(buf
, sizeof(buf
), "%d", file
->line_num
);
3886 } else if (tok
== TOK___FILE__
) {
3887 cstrval
= file
->filename
;
3889 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
3894 tm
= localtime(&ti
);
3895 if (tok
== TOK___DATE__
) {
3896 snprintf(buf
, sizeof(buf
), "%s %2d %d",
3897 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
3899 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
3900 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
3907 cstr_cat(&cstr
, cstrval
);
3908 cstr_ccat(&cstr
, '\0');
3910 tok_str_add2(tok_str
, t1
, &cval
);
3915 if (s
->type
.t
== MACRO_FUNC
) {
3916 /* NOTE: we do not use next_nomacro to avoid eating the
3917 next token. XXX: find better solution */
3920 if (t
== 0 && can_read_stream
) {
3921 /* end of macro stream: we must look at the token
3922 after in the file */
3928 /* XXX: incorrect with comments */
3929 ch
= file
->buf_ptr
[0];
3930 while (is_space(ch
) || ch
== '\n')
3934 if (t
!= '(') /* no macro subst */
3937 /* argument macro */
3942 /* NOTE: empty args are allowed, except if no args */
3944 /* handle '()' case */
3945 if (!args
&& !sa
&& tok
== ')')
3948 error("macro '%s' used with too many args",
3949 get_tok_str(s
->v
, 0));
3952 /* NOTE: non zero sa->t indicates VA_ARGS */
3953 while ((parlevel
> 0 ||
3955 (tok
!= ',' || sa
->type
.t
))) &&
3959 else if (tok
== ')')
3961 tok_str_add2(&str
, tok
, &tokc
);
3964 tok_str_add(&str
, 0);
3965 sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, (int)str
.str
);
3968 /* special case for gcc var args: add an empty
3969 var arg argument if it is omitted */
3970 if (sa
&& sa
->type
.t
&& gnu_ext
)
3980 error("macro '%s' used with too few args",
3981 get_tok_str(s
->v
, 0));
3984 /* now subst each arg */
3985 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3990 tok_str_free((int *)sa
->c
);
3996 sym_push2(nested_list
, s
->v
, 0, 0);
3997 macro_subst(tok_str
, nested_list
, mstr
, 1);
3998 /* pop nested defined symbol */
4000 *nested_list
= sa1
->prev
;
4008 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
4009 return the resulting string (which must be freed). */
4010 static inline int *macro_twosharps(const int *macro_str
)
4013 const int *macro_ptr1
, *start_macro_ptr
, *ptr
, *saved_macro_ptr
;
4015 const char *p1
, *p2
;
4017 TokenString macro_str1
;
4020 start_macro_ptr
= macro_str
;
4021 /* we search the first '##' */
4023 macro_ptr1
= macro_str
;
4024 TOK_GET(t
, macro_str
, cval
);
4025 /* nothing more to do if end of string */
4028 if (*macro_str
== TOK_TWOSHARPS
)
4032 /* we saw '##', so we need more processing to handle it */
4034 tok_str_new(¯o_str1
);
4038 /* add all tokens seen so far */
4039 for(ptr
= start_macro_ptr
; ptr
< macro_ptr1
;) {
4040 TOK_GET(t
, ptr
, cval
);
4041 tok_str_add2(¯o_str1
, t
, &cval
);
4043 saved_macro_ptr
= macro_ptr
;
4044 /* XXX: get rid of the use of macro_ptr here */
4045 macro_ptr
= (int *)macro_str
;
4047 while (*macro_ptr
== TOK_TWOSHARPS
) {
4049 macro_ptr1
= macro_ptr
;
4052 TOK_GET(t
, macro_ptr
, cval
);
4053 /* We concatenate the two tokens if we have an
4054 identifier or a preprocessing number */
4056 p1
= get_tok_str(tok
, &tokc
);
4057 cstr_cat(&cstr
, p1
);
4058 p2
= get_tok_str(t
, &cval
);
4059 cstr_cat(&cstr
, p2
);
4060 cstr_ccat(&cstr
, '\0');
4062 if ((tok
>= TOK_IDENT
|| tok
== TOK_PPNUM
) &&
4063 (t
>= TOK_IDENT
|| t
== TOK_PPNUM
)) {
4064 if (tok
== TOK_PPNUM
) {
4065 /* if number, then create a number token */
4066 /* NOTE: no need to allocate because
4067 tok_str_add2() does it */
4070 /* if identifier, we must do a test to
4071 validate we have a correct identifier */
4072 if (t
== TOK_PPNUM
) {
4082 if (!isnum(c
) && !isid(c
))
4086 ts
= tok_alloc(cstr
.data
, strlen(cstr
.data
));
4087 tok
= ts
->tok
; /* modify current token */
4090 const char *str
= cstr
.data
;
4091 const unsigned char *q
;
4093 /* we look for a valid token */
4094 /* XXX: do more extensive checks */
4095 if (!strcmp(str
, ">>=")) {
4097 } else if (!strcmp(str
, "<<=")) {
4099 } else if (strlen(str
) == 2) {
4100 /* search in two bytes table */
4105 if (q
[0] == str
[0] && q
[1] == str
[1])
4112 /* NOTE: because get_tok_str use a static buffer,
4115 p1
= get_tok_str(tok
, &tokc
);
4116 cstr_cat(&cstr
, p1
);
4117 cstr_ccat(&cstr
, '\0');
4118 p2
= get_tok_str(t
, &cval
);
4119 warning("pasting \"%s\" and \"%s\" does not give a valid preprocessing token", cstr
.data
, p2
);
4120 /* cannot merge tokens: just add them separately */
4121 tok_str_add2(¯o_str1
, tok
, &tokc
);
4122 /* XXX: free associated memory ? */
4129 tok_str_add2(¯o_str1
, tok
, &tokc
);
4134 macro_ptr
= (int *)saved_macro_ptr
;
4136 tok_str_add(¯o_str1
, 0);
4137 return macro_str1
.str
;
4141 /* do macro substitution of macro_str and add result to
4142 (tok_str,tok_len). 'nested_list' is the list of all macros we got
4143 inside to avoid recursing. */
4144 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
4145 const int *macro_str
, int can_read_stream
)
4148 int *saved_macro_ptr
, *macro_str1
;
4153 /* first scan for '##' operator handling */
4155 macro_str1
= macro_twosharps(ptr
);
4159 /* NOTE: ptr == NULL can only happen if tokens are read from
4160 file stream due to a macro function call */
4163 TOK_GET(t
, ptr
, cval
);
4168 /* if nested substitution, do nothing */
4169 if (sym_find2(*nested_list
, t
))
4171 saved_macro_ptr
= macro_ptr
;
4172 macro_ptr
= (int *)ptr
;
4174 ret
= macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
4175 ptr
= (int *)macro_ptr
;
4176 macro_ptr
= saved_macro_ptr
;
4181 tok_str_add2(tok_str
, t
, &cval
);
4185 tok_str_free(macro_str1
);
4188 /* return next token with macro substitution */
4189 static void next(void)
4191 Sym
*nested_list
, *s
;
4197 /* if not reading from macro substituted string, then try
4198 to substitute macros */
4199 if (tok
>= TOK_IDENT
&&
4200 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
4201 s
= define_find(tok
);
4203 /* we have a macro: we try to substitute */
4206 if (macro_subst_tok(&str
, &nested_list
, s
, 1) == 0) {
4207 /* substitution done, NOTE: maybe empty */
4208 tok_str_add(&str
, 0);
4209 macro_ptr
= str
.str
;
4210 macro_ptr_allocated
= str
.str
;
4217 /* end of macro or end of unget buffer */
4218 if (unget_buffer_enabled
) {
4219 macro_ptr
= unget_saved_macro_ptr
;
4220 unget_buffer_enabled
= 0;
4222 /* end of macro string: free it */
4223 tok_str_free(macro_ptr_allocated
);
4230 /* convert preprocessor tokens into C tokens */
4231 if (tok
== TOK_PPNUM
&&
4232 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
4233 parse_number((char *)tokc
.cstr
->data
);
4237 /* push back current token and set current token to 'last_tok'. Only
4238 identifier case handled for labels. */
4239 static inline void unget_tok(int last_tok
)
4243 unget_saved_macro_ptr
= macro_ptr
;
4244 unget_buffer_enabled
= 1;
4245 q
= unget_saved_buffer
;
4248 n
= tok_ext_size(tok
) - 1;
4251 *q
= 0; /* end of token string */
4256 void swap(int *p
, int *q
)
4264 void vsetc(CType
*type
, int r
, CValue
*vc
)
4268 if (vtop
>= vstack
+ VSTACK_SIZE
)
4269 error("memory full");
4270 /* cannot let cpu flags if other instruction are generated. Also
4271 avoid leaving VT_JMP anywhere except on the top of the stack
4272 because it would complicate the code generator. */
4273 if (vtop
>= vstack
) {
4274 v
= vtop
->r
& VT_VALMASK
;
4275 if (v
== VT_CMP
|| (v
& ~1) == VT_JMP
)
4281 vtop
->r2
= VT_CONST
;
4285 /* push integer constant */
4290 vsetc(&int_type
, VT_CONST
, &cval
);
4293 /* Return a static symbol pointing to a section */
4294 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
4295 unsigned long offset
, unsigned long size
)
4301 sym
= global_identifier_push(v
, type
->t
| VT_STATIC
, 0);
4302 sym
->type
.ref
= type
->ref
;
4303 sym
->r
= VT_CONST
| VT_SYM
;
4304 put_extern_sym(sym
, sec
, offset
, size
);
4308 /* push a reference to a section offset by adding a dummy symbol */
4309 static void vpush_ref(CType
*type
, Section
*sec
, unsigned long offset
, unsigned long size
)
4314 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4315 vtop
->sym
= get_sym_ref(type
, sec
, offset
, size
);
4318 /* define a new external reference to a symbol 'v' of type 'u' */
4319 static Sym
*external_global_sym(int v
, CType
*type
, int r
)
4325 /* push forward reference */
4326 s
= global_identifier_push(v
, type
->t
| VT_EXTERN
, 0);
4327 s
->type
.ref
= type
->ref
;
4328 s
->r
= r
| VT_CONST
| VT_SYM
;
4333 /* define a new external reference to a symbol 'v' of type 'u' */
4334 static Sym
*external_sym(int v
, CType
*type
, int r
)
4340 /* push forward reference */
4341 s
= sym_push(v
, type
, r
| VT_CONST
| VT_SYM
, 0);
4342 s
->type
.t
|= VT_EXTERN
;
4344 if (!is_compatible_types(&s
->type
, type
))
4345 error("incompatible types for redefinition of '%s'",
4346 get_tok_str(v
, NULL
));
4351 /* push a reference to global symbol v */
4352 static void vpush_global_sym(CType
*type
, int v
)
4357 sym
= external_global_sym(v
, type
, 0);
4359 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4363 void vset(CType
*type
, int r
, int v
)
4368 vsetc(type
, r
, &cval
);
4371 void vseti(int r
, int v
)
4387 void vpushv(SValue
*v
)
4389 if (vtop
>= vstack
+ VSTACK_SIZE
)
4390 error("memory full");
4400 /* save r to the memory stack, and mark it as being free */
4401 void save_reg(int r
)
4403 int l
, saved
, size
, align
;
4407 /* modify all stack values */
4410 for(p
=vstack
;p
<=vtop
;p
++) {
4411 if ((p
->r
& VT_VALMASK
) == r
||
4412 (p
->r2
& VT_VALMASK
) == r
) {
4413 /* must save value on stack if not already done */
4415 /* NOTE: must reload 'r' because r might be equal to r2 */
4416 r
= p
->r
& VT_VALMASK
;
4417 /* store register in the stack */
4419 if ((p
->r
& VT_LVAL
) ||
4420 (!is_float(type
->t
) && (type
->t
& VT_BTYPE
) != VT_LLONG
))
4422 size
= type_size(type
, &align
);
4423 loc
= (loc
- size
) & -align
;
4424 sv
.type
.t
= type
->t
;
4425 sv
.r
= VT_LOCAL
| VT_LVAL
;
4428 #ifdef TCC_TARGET_I386
4429 /* x86 specific: need to pop fp register ST0 if saved */
4430 if (r
== TREG_ST0
) {
4431 o(0xd9dd); /* fstp %st(1) */
4434 /* special long long case */
4435 if ((type
->t
& VT_BTYPE
) == VT_LLONG
) {
4442 /* mark that stack entry as being saved on the stack */
4443 if (p
->r
& VT_LVAL
) {
4444 /* also clear the bounded flag because the
4445 relocation address of the function was stored in
4447 p
->r
= (p
->r
& ~(VT_VALMASK
| VT_BOUNDED
)) | VT_LLOCAL
;
4449 p
->r
= lvalue_type(p
->type
.t
) | VT_LOCAL
;
4457 /* find a register of class 'rc2' with at most one reference on stack.
4458 * If none, call get_reg(rc) */
4459 int get_reg_ex(int rc
, int rc2
)
4464 for(r
=0;r
<NB_REGS
;r
++) {
4465 if (reg_classes
[r
] & rc2
) {
4468 for(p
= vstack
; p
<= vtop
; p
++) {
4469 if ((p
->r
& VT_VALMASK
) == r
||
4470 (p
->r2
& VT_VALMASK
) == r
)
4480 /* find a free register of class 'rc'. If none, save one register */
4486 /* find a free register */
4487 for(r
=0;r
<NB_REGS
;r
++) {
4488 if (reg_classes
[r
] & rc
) {
4489 for(p
=vstack
;p
<=vtop
;p
++) {
4490 if ((p
->r
& VT_VALMASK
) == r
||
4491 (p
->r2
& VT_VALMASK
) == r
)
4499 /* no register left : free the first one on the stack (VERY
4500 IMPORTANT to start from the bottom to ensure that we don't
4501 spill registers used in gen_opi()) */
4502 for(p
=vstack
;p
<=vtop
;p
++) {
4503 r
= p
->r
& VT_VALMASK
;
4504 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
))
4506 /* also look at second register (if long long) */
4507 r
= p
->r2
& VT_VALMASK
;
4508 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
)) {
4514 /* Should never comes here */
4518 /* save registers up to (vtop - n) stack entry */
4519 void save_regs(int n
)
4524 for(p
= vstack
;p
<= p1
; p
++) {
4525 r
= p
->r
& VT_VALMASK
;
4532 /* move register 's' to 'r', and flush previous value of r to memory
4534 void move_reg(int r
, int s
)
4547 /* get address of vtop (vtop MUST BE an lvalue) */
4550 vtop
->r
&= ~VT_LVAL
;
4551 /* tricky: if saved lvalue, then we can go back to lvalue */
4552 if ((vtop
->r
& VT_VALMASK
) == VT_LLOCAL
)
4553 vtop
->r
= (vtop
->r
& ~(VT_VALMASK
| VT_LVAL_TYPE
)) | VT_LOCAL
| VT_LVAL
;
4556 #ifdef CONFIG_TCC_BCHECK
4557 /* generate lvalue bound code */
4563 vtop
->r
&= ~VT_MUSTBOUND
;
4564 /* if lvalue, then use checking code before dereferencing */
4565 if (vtop
->r
& VT_LVAL
) {
4566 /* if not VT_BOUNDED value, then make one */
4567 if (!(vtop
->r
& VT_BOUNDED
)) {
4568 lval_type
= vtop
->r
& (VT_LVAL_TYPE
| VT_LVAL
);
4569 /* must save type because we must set it to int to get pointer */
4571 vtop
->type
.t
= VT_INT
;
4574 gen_bounded_ptr_add();
4575 vtop
->r
|= lval_type
;
4578 /* then check for dereferencing */
4579 gen_bounded_ptr_deref();
4584 /* store vtop a register belonging to class 'rc'. lvalues are
4585 converted to values. Cannot be used if cannot be converted to
4586 register value (such as structures). */
4589 int r
, r2
, rc2
, bit_pos
, bit_size
, size
, align
, i
;
4590 unsigned long long ll
;
4592 /* NOTE: get_reg can modify vstack[] */
4593 if (vtop
->type
.t
& VT_BITFIELD
) {
4594 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
4595 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
4596 /* remove bit field info to avoid loops */
4597 vtop
->type
.t
&= ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
4598 /* generate shifts */
4599 vpushi(32 - (bit_pos
+ bit_size
));
4601 vpushi(32 - bit_size
);
4602 /* NOTE: transformed to SHR if unsigned */
4606 if (is_float(vtop
->type
.t
) &&
4607 (vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4610 unsigned long offset
;
4612 /* XXX: unify with initializers handling ? */
4613 /* CPUs usually cannot use float constants, so we store them
4614 generically in data segment */
4615 size
= type_size(&vtop
->type
, &align
);
4616 offset
= (data_section
->data_offset
+ align
- 1) & -align
;
4617 data_section
->data_offset
= offset
;
4618 /* XXX: not portable yet */
4619 ptr
= section_ptr_add(data_section
, size
);
4622 ptr
[i
] = vtop
->c
.tab
[i
];
4623 sym
= get_sym_ref(&vtop
->type
, data_section
, offset
, size
<< 2);
4624 vtop
->r
|= VT_LVAL
| VT_SYM
;
4628 #ifdef CONFIG_TCC_BCHECK
4629 if (vtop
->r
& VT_MUSTBOUND
)
4633 r
= vtop
->r
& VT_VALMASK
;
4634 /* need to reload if:
4636 - lvalue (need to dereference pointer)
4637 - already a register, but not in the right class */
4638 if (r
>= VT_CONST
||
4639 (vtop
->r
& VT_LVAL
) ||
4640 !(reg_classes
[r
] & rc
) ||
4641 ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
&&
4642 !(reg_classes
[vtop
->r2
] & rc
))) {
4644 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
) {
4645 /* two register type load : expand to two words
4647 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4650 vtop
->c
.ui
= ll
; /* first word */
4652 vtop
->r
= r
; /* save register value */
4653 vpushi(ll
>> 32); /* second word */
4654 } else if (r
>= VT_CONST
|| /* XXX: test to VT_CONST incorrect ? */
4655 (vtop
->r
& VT_LVAL
)) {
4656 /* We do not want to modifier the long long
4657 pointer here, so the safest (and less
4658 efficient) is to save all the other registers
4659 in the stack. XXX: totally inefficient. */
4661 /* load from memory */
4664 vtop
[-1].r
= r
; /* save register value */
4665 /* increment pointer to get second word */
4666 vtop
->type
.t
= VT_INT
;
4672 /* move registers */
4675 vtop
[-1].r
= r
; /* save register value */
4676 vtop
->r
= vtop
[-1].r2
;
4678 /* allocate second register */
4685 /* write second register */
4687 } else if ((vtop
->r
& VT_LVAL
) && !is_float(vtop
->type
.t
)) {
4689 /* lvalue of scalar type : need to use lvalue type
4690 because of possible cast */
4693 /* compute memory access type */
4694 if (vtop
->r
& VT_LVAL_BYTE
)
4696 else if (vtop
->r
& VT_LVAL_SHORT
)
4698 if (vtop
->r
& VT_LVAL_UNSIGNED
)
4702 /* restore wanted type */
4705 /* one register type load */
4710 #ifdef TCC_TARGET_C67
4711 /* uses register pairs for doubles */
4712 if ((vtop
->type
.t
& VT_BTYPE
) == VT_DOUBLE
)
4719 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
4720 void gv2(int rc1
, int rc2
)
4724 /* generate more generic register first. But VT_JMP or VT_CMP
4725 values must be generated first in all cases to avoid possible
4727 v
= vtop
[0].r
& VT_VALMASK
;
4728 if (v
!= VT_CMP
&& (v
& ~1) != VT_JMP
&& rc1
<= rc2
) {
4733 /* test if reload is needed for first register */
4734 if ((vtop
[-1].r
& VT_VALMASK
) >= VT_CONST
) {
4744 /* test if reload is needed for first register */
4745 if ((vtop
[0].r
& VT_VALMASK
) >= VT_CONST
) {
4751 /* expand long long on stack in two int registers */
4756 u
= vtop
->type
.t
& VT_UNSIGNED
;
4759 vtop
[0].r
= vtop
[-1].r2
;
4760 vtop
[0].r2
= VT_CONST
;
4761 vtop
[-1].r2
= VT_CONST
;
4762 vtop
[0].type
.t
= VT_INT
| u
;
4763 vtop
[-1].type
.t
= VT_INT
| u
;
4766 #ifdef TCC_TARGET_ARM
4767 /* expand long long on stack */
4768 void lexpand_nr(void)
4772 u
= vtop
->type
.t
& VT_UNSIGNED
;
4774 vtop
->r2
= VT_CONST
;
4775 vtop
->type
.t
= VT_INT
| u
;
4776 v
=vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
);
4777 if (v
== VT_CONST
) {
4778 vtop
[-1].c
.ui
= vtop
->c
.ull
;
4779 vtop
->c
.ui
= vtop
->c
.ull
>> 32;
4781 } else if (v
== (VT_LVAL
|VT_CONST
) || v
== (VT_LVAL
|VT_LOCAL
)) {
4783 vtop
->r
= vtop
[-1].r
;
4784 } else if (v
> VT_CONST
) {
4788 vtop
->r
= vtop
[-1].r2
;
4789 vtop
[-1].r2
= VT_CONST
;
4790 vtop
[-1].type
.t
= VT_INT
| u
;
4794 /* build a long long from two ints */
4797 gv2(RC_INT
, RC_INT
);
4798 vtop
[-1].r2
= vtop
[0].r
;
4799 vtop
[-1].type
.t
= t
;
4803 /* rotate n first stack elements to the bottom
4804 I1 ... In -> I2 ... In I1 [top is right]
4812 for(i
=-n
+1;i
!=0;i
++)
4813 vtop
[i
] = vtop
[i
+1];
4817 /* rotate n first stack elements to the top
4818 I1 ... In -> In I1 ... I(n-1) [top is right]
4826 for(i
= 0;i
< n
- 1; i
++)
4827 vtop
[-i
] = vtop
[-i
- 1];
4831 #ifdef TCC_TARGET_ARM
4832 /* like vrott but in other direction
4833 In ... I1 -> I(n-1) ... I1 In [top is right]
4841 for(i
= n
- 1; i
> 0; i
--)
4842 vtop
[-i
] = vtop
[-i
+ 1];
4847 /* pop stack value */
4851 v
= vtop
->r
& VT_VALMASK
;
4852 #ifdef TCC_TARGET_I386
4853 /* for x86, we need to pop the FP stack */
4854 if (v
== TREG_ST0
&& !nocode_wanted
) {
4855 o(0xd9dd); /* fstp %st(1) */
4858 if (v
== VT_JMP
|| v
== VT_JMPI
) {
4859 /* need to put correct jump if && or || without test */
4865 /* convert stack entry to register and duplicate its value in another
4873 if ((t
& VT_BTYPE
) == VT_LLONG
) {
4880 /* stack: H L L1 H1 */
4888 /* duplicate value */
4899 load(r1
, &sv
); /* move r to r1 */
4901 /* duplicates value */
4906 /* generate CPU independent (unsigned) long long operations */
4907 void gen_opl(int op
)
4909 int t
, a
, b
, op1
, c
, i
;
4916 func
= TOK___divdi3
;
4919 func
= TOK___udivdi3
;
4922 func
= TOK___moddi3
;
4925 func
= TOK___umoddi3
;
4927 /* call generic long long function */
4928 vpush_global_sym(&func_old_type
, func
);
4933 vtop
->r2
= REG_LRET
;
4946 /* stack: L1 H1 L2 H2 */
4951 vtop
[-2] = vtop
[-3];
4954 /* stack: H1 H2 L1 L2 */
4960 /* stack: H1 H2 L1 L2 ML MH */
4963 /* stack: ML MH H1 H2 L1 L2 */
4967 /* stack: ML MH H1 L2 H2 L1 */
4972 /* stack: ML MH M1 M2 */
4975 } else if (op
== '+' || op
== '-') {
4976 /* XXX: add non carry method too (for MIPS or alpha) */
4982 /* stack: H1 H2 (L1 op L2) */
4985 gen_op(op1
+ 1); /* TOK_xxxC2 */
4988 /* stack: H1 H2 (L1 op L2) */
4991 /* stack: (L1 op L2) H1 H2 */
4993 /* stack: (L1 op L2) (H1 op H2) */
5001 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) {
5002 t
= vtop
[-1].type
.t
;
5006 /* stack: L H shift */
5008 /* constant: simpler */
5009 /* NOTE: all comments are for SHL. the other cases are
5010 done by swaping words */
5021 if (op
!= TOK_SAR
) {
5054 /* XXX: should provide a faster fallback on x86 ? */
5057 func
= TOK___sardi3
;
5060 func
= TOK___shrdi3
;
5063 func
= TOK___shldi3
;
5069 /* compare operations */
5075 /* stack: L1 H1 L2 H2 */
5077 vtop
[-1] = vtop
[-2];
5079 /* stack: L1 L2 H1 H2 */
5082 /* when values are equal, we need to compare low words. since
5083 the jump is inverted, we invert the test too. */
5086 else if (op1
== TOK_GT
)
5088 else if (op1
== TOK_ULT
)
5090 else if (op1
== TOK_UGT
)
5095 if (op1
!= TOK_NE
) {
5099 /* generate non equal test */
5100 /* XXX: NOT PORTABLE yet */
5104 #if defined(TCC_TARGET_I386)
5105 b
= psym(0x850f, 0);
5106 #elif defined(TCC_TARGET_ARM)
5108 o(0x1A000000 | encbranch(ind
, 0, 1));
5109 #elif defined(TCC_TARGET_C67)
5110 error("not implemented");
5112 #error not supported
5116 /* compare low. Always unsigned */
5120 else if (op1
== TOK_LE
)
5122 else if (op1
== TOK_GT
)
5124 else if (op1
== TOK_GE
)
5134 /* handle integer constant optimizations and various machine
5136 void gen_opic(int op
)
5143 /* currently, we cannot do computations with forward symbols */
5144 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5145 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5149 case '+': v1
->c
.i
+= fc
; break;
5150 case '-': v1
->c
.i
-= fc
; break;
5151 case '&': v1
->c
.i
&= fc
; break;
5152 case '^': v1
->c
.i
^= fc
; break;
5153 case '|': v1
->c
.i
|= fc
; break;
5154 case '*': v1
->c
.i
*= fc
; break;
5161 /* if division by zero, generate explicit division */
5164 error("division by zero in constant");
5168 default: v1
->c
.i
/= fc
; break;
5169 case '%': v1
->c
.i
%= fc
; break;
5170 case TOK_UDIV
: v1
->c
.i
= (unsigned)v1
->c
.i
/ fc
; break;
5171 case TOK_UMOD
: v1
->c
.i
= (unsigned)v1
->c
.i
% fc
; break;
5174 case TOK_SHL
: v1
->c
.i
<<= fc
; break;
5175 case TOK_SHR
: v1
->c
.i
= (unsigned)v1
->c
.i
>> fc
; break;
5176 case TOK_SAR
: v1
->c
.i
>>= fc
; break;
5178 case TOK_ULT
: v1
->c
.i
= (unsigned)v1
->c
.i
< (unsigned)fc
; break;
5179 case TOK_UGE
: v1
->c
.i
= (unsigned)v1
->c
.i
>= (unsigned)fc
; break;
5180 case TOK_EQ
: v1
->c
.i
= v1
->c
.i
== fc
; break;
5181 case TOK_NE
: v1
->c
.i
= v1
->c
.i
!= fc
; break;
5182 case TOK_ULE
: v1
->c
.i
= (unsigned)v1
->c
.i
<= (unsigned)fc
; break;
5183 case TOK_UGT
: v1
->c
.i
= (unsigned)v1
->c
.i
> (unsigned)fc
; break;
5184 case TOK_LT
: v1
->c
.i
= v1
->c
.i
< fc
; break;
5185 case TOK_GE
: v1
->c
.i
= v1
->c
.i
>= fc
; break;
5186 case TOK_LE
: v1
->c
.i
= v1
->c
.i
<= fc
; break;
5187 case TOK_GT
: v1
->c
.i
= v1
->c
.i
> fc
; break;
5189 case TOK_LAND
: v1
->c
.i
= v1
->c
.i
&& fc
; break;
5190 case TOK_LOR
: v1
->c
.i
= v1
->c
.i
|| fc
; break;
5196 /* if commutative ops, put c2 as constant */
5197 if (c1
&& (op
== '+' || op
== '&' || op
== '^' ||
5198 op
== '|' || op
== '*')) {
5203 if (c2
&& (((op
== '*' || op
== '/' || op
== TOK_UDIV
||
5206 ((op
== '+' || op
== '-' || op
== '|' || op
== '^' ||
5207 op
== TOK_SHL
|| op
== TOK_SHR
|| op
== TOK_SAR
) &&
5213 } else if (c2
&& (op
== '*' || op
== TOK_PDIV
|| op
== TOK_UDIV
)) {
5214 /* try to use shifts instead of muls or divs */
5215 if (fc
> 0 && (fc
& (fc
- 1)) == 0) {
5224 else if (op
== TOK_PDIV
)
5230 } else if (c2
&& (op
== '+' || op
== '-') &&
5231 (vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) ==
5232 (VT_CONST
| VT_SYM
)) {
5233 /* symbol + constant case */
5240 if (!nocode_wanted
) {
5241 /* call low level op generator */
5250 /* generate a floating point operation with constant propagation */
5251 void gen_opif(int op
)
5259 /* currently, we cannot do computations with forward symbols */
5260 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5261 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5263 if (v1
->type
.t
== VT_FLOAT
) {
5266 } else if (v1
->type
.t
== VT_DOUBLE
) {
5274 /* NOTE: we only do constant propagation if finite number (not
5275 NaN or infinity) (ANSI spec) */
5276 if (!ieee_finite(f1
) || !ieee_finite(f2
))
5280 case '+': f1
+= f2
; break;
5281 case '-': f1
-= f2
; break;
5282 case '*': f1
*= f2
; break;
5286 error("division by zero in constant");
5291 /* XXX: also handles tests ? */
5295 /* XXX: overflow test ? */
5296 if (v1
->type
.t
== VT_FLOAT
) {
5298 } else if (v1
->type
.t
== VT_DOUBLE
) {
5306 if (!nocode_wanted
) {
5314 static int pointed_size(CType
*type
)
5317 return type_size(pointed_type(type
), &align
);
5320 static inline int is_null_pointer(SValue
*p
)
5322 if ((p
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
5324 return ((p
->type
.t
& VT_BTYPE
) == VT_INT
&& p
->c
.i
== 0) ||
5325 ((p
->type
.t
& VT_BTYPE
) == VT_LLONG
&& p
->c
.ll
== 0);
5328 static inline int is_integer_btype(int bt
)
5330 return (bt
== VT_BYTE
|| bt
== VT_SHORT
||
5331 bt
== VT_INT
|| bt
== VT_LLONG
);
5334 /* check types for comparison or substraction of pointers */
5335 static void check_comparison_pointer_types(SValue
*p1
, SValue
*p2
, int op
)
5337 CType
*type1
, *type2
, tmp_type1
, tmp_type2
;
5340 /* null pointers are accepted for all comparisons as gcc */
5341 if (is_null_pointer(p1
) || is_null_pointer(p2
))
5345 bt1
= type1
->t
& VT_BTYPE
;
5346 bt2
= type2
->t
& VT_BTYPE
;
5347 /* accept comparison between pointer and integer with a warning */
5348 if ((is_integer_btype(bt1
) || is_integer_btype(bt2
)) && op
!= '-') {
5349 warning("comparison between pointer and integer");
5353 /* both must be pointers or implicit function pointers */
5354 if (bt1
== VT_PTR
) {
5355 type1
= pointed_type(type1
);
5356 } else if (bt1
!= VT_FUNC
)
5357 goto invalid_operands
;
5359 if (bt2
== VT_PTR
) {
5360 type2
= pointed_type(type2
);
5361 } else if (bt2
!= VT_FUNC
) {
5363 error("invalid operands to binary %s", get_tok_str(op
, NULL
));
5365 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
5366 (type2
->t
& VT_BTYPE
) == VT_VOID
)
5370 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5371 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5372 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
5373 /* gcc-like error if '-' is used */
5375 goto invalid_operands
;
5377 warning("comparison of distinct pointer types lacks a cast");
5381 /* generic gen_op: handles types problems */
5384 int u
, t1
, t2
, bt1
, bt2
, t
;
5387 t1
= vtop
[-1].type
.t
;
5388 t2
= vtop
[0].type
.t
;
5389 bt1
= t1
& VT_BTYPE
;
5390 bt2
= t2
& VT_BTYPE
;
5392 if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
5393 /* at least one operand is a pointer */
5394 /* relationnal op: must be both pointers */
5395 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5396 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5397 /* pointers are handled are unsigned */
5398 t
= VT_INT
| VT_UNSIGNED
;
5401 /* if both pointers, then it must be the '-' op */
5402 if (bt1
== VT_PTR
&& bt2
== VT_PTR
) {
5404 error("cannot use pointers here");
5405 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5406 /* XXX: check that types are compatible */
5407 u
= pointed_size(&vtop
[-1].type
);
5409 /* set to integer type */
5410 vtop
->type
.t
= VT_INT
;
5414 /* exactly one pointer : must be '+' or '-'. */
5415 if (op
!= '-' && op
!= '+')
5416 error("cannot use pointers here");
5417 /* Put pointer as first operand */
5418 if (bt2
== VT_PTR
) {
5422 type1
= vtop
[-1].type
;
5423 /* XXX: cast to int ? (long long case) */
5424 vpushi(pointed_size(&vtop
[-1].type
));
5426 #ifdef CONFIG_TCC_BCHECK
5427 /* if evaluating constant expression, no code should be
5428 generated, so no bound check */
5429 if (do_bounds_check
&& !const_wanted
) {
5430 /* if bounded pointers, we generate a special code to
5437 gen_bounded_ptr_add();
5443 /* put again type if gen_opic() swaped operands */
5446 } else if (is_float(bt1
) || is_float(bt2
)) {
5447 /* compute bigger type and do implicit casts */
5448 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
5450 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
5455 /* floats can only be used for a few operations */
5456 if (op
!= '+' && op
!= '-' && op
!= '*' && op
!= '/' &&
5457 (op
< TOK_ULT
|| op
> TOK_GT
))
5458 error("invalid operands for binary operation");
5460 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
5461 /* cast to biggest op */
5463 /* convert to unsigned if it does not fit in a long long */
5464 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
5465 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
5469 /* integer operations */
5471 /* convert to unsigned if it does not fit in an integer */
5472 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
5473 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
5476 /* XXX: currently, some unsigned operations are explicit, so
5477 we modify them here */
5478 if (t
& VT_UNSIGNED
) {
5485 else if (op
== TOK_LT
)
5487 else if (op
== TOK_GT
)
5489 else if (op
== TOK_LE
)
5491 else if (op
== TOK_GE
)
5498 /* special case for shifts and long long: we keep the shift as
5500 if (op
== TOK_SHR
|| op
== TOK_SAR
|| op
== TOK_SHL
)
5505 else if ((t
& VT_BTYPE
) == VT_LLONG
)
5509 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5510 /* relationnal op: the result is an int */
5511 vtop
->type
.t
= VT_INT
;
5518 /* generic itof for unsigned long long case */
5519 void gen_cvt_itof1(int t
)
5521 if ((vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
)) ==
5522 (VT_LLONG
| VT_UNSIGNED
)) {
5525 vpush_global_sym(&func_old_type
, TOK___ulltof
);
5526 else if (t
== VT_DOUBLE
)
5527 vpush_global_sym(&func_old_type
, TOK___ulltod
);
5529 vpush_global_sym(&func_old_type
, TOK___ulltold
);
5539 /* generic ftoi for unsigned long long case */
5540 void gen_cvt_ftoi1(int t
)
5544 if (t
== (VT_LLONG
| VT_UNSIGNED
)) {
5545 /* not handled natively */
5546 st
= vtop
->type
.t
& VT_BTYPE
;
5548 vpush_global_sym(&func_old_type
, TOK___fixunssfdi
);
5549 else if (st
== VT_DOUBLE
)
5550 vpush_global_sym(&func_old_type
, TOK___fixunsdfdi
);
5552 vpush_global_sym(&func_old_type
, TOK___fixunsxfdi
);
5557 vtop
->r2
= REG_LRET
;
5563 /* force char or short cast */
5564 void force_charshort_cast(int t
)
5568 /* XXX: add optimization if lvalue : just change type and offset */
5573 if (t
& VT_UNSIGNED
) {
5574 vpushi((1 << bits
) - 1);
5585 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
5586 static void gen_cast(CType
*type
)
5588 int sbt
, dbt
, sf
, df
, c
;
5590 /* special delayed cast for char/short */
5591 /* XXX: in some cases (multiple cascaded casts), it may still
5593 if (vtop
->r
& VT_MUSTCAST
) {
5594 vtop
->r
&= ~VT_MUSTCAST
;
5595 force_charshort_cast(vtop
->type
.t
);
5598 /* bitfields first get cast to ints */
5599 if (vtop
->type
.t
& VT_BITFIELD
) {
5603 dbt
= type
->t
& (VT_BTYPE
| VT_UNSIGNED
);
5604 sbt
= vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
);
5606 if (sbt
!= dbt
&& !nocode_wanted
) {
5609 c
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5611 /* convert from fp to fp */
5613 /* constant case: we can do it now */
5614 /* XXX: in ISOC, cannot do it if error in convert */
5615 if (dbt
== VT_FLOAT
&& sbt
== VT_DOUBLE
)
5616 vtop
->c
.f
= (float)vtop
->c
.d
;
5617 else if (dbt
== VT_FLOAT
&& sbt
== VT_LDOUBLE
)
5618 vtop
->c
.f
= (float)vtop
->c
.ld
;
5619 else if (dbt
== VT_DOUBLE
&& sbt
== VT_FLOAT
)
5620 vtop
->c
.d
= (double)vtop
->c
.f
;
5621 else if (dbt
== VT_DOUBLE
&& sbt
== VT_LDOUBLE
)
5622 vtop
->c
.d
= (double)vtop
->c
.ld
;
5623 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_FLOAT
)
5624 vtop
->c
.ld
= (long double)vtop
->c
.f
;
5625 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_DOUBLE
)
5626 vtop
->c
.ld
= (long double)vtop
->c
.d
;
5628 /* non constant case: generate code */
5632 /* convert int to fp */
5635 case VT_LLONG
| VT_UNSIGNED
:
5637 /* XXX: add const cases for long long */
5639 case VT_INT
| VT_UNSIGNED
:
5641 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.ui
; break;
5642 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.ui
; break;
5643 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.ui
; break;
5648 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.i
; break;
5649 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.i
; break;
5650 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.i
; break;
5656 #if !defined(TCC_TARGET_ARM)
5663 /* convert fp to int */
5664 /* we handle char/short/etc... with generic code */
5665 if (dbt
!= (VT_INT
| VT_UNSIGNED
) &&
5666 dbt
!= (VT_LLONG
| VT_UNSIGNED
) &&
5671 case VT_LLONG
| VT_UNSIGNED
:
5673 /* XXX: add const cases for long long */
5675 case VT_INT
| VT_UNSIGNED
:
5677 case VT_FLOAT
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5678 case VT_DOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5679 case VT_LDOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5685 case VT_FLOAT
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5686 case VT_DOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5687 case VT_LDOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5695 if (dbt
== VT_INT
&& (type
->t
& (VT_BTYPE
| VT_UNSIGNED
)) != dbt
) {
5696 /* additional cast for char/short/bool... */
5700 } else if ((dbt
& VT_BTYPE
) == VT_LLONG
) {
5701 if ((sbt
& VT_BTYPE
) != VT_LLONG
) {
5702 /* scalar to long long */
5704 if (sbt
== (VT_INT
| VT_UNSIGNED
))
5705 vtop
->c
.ll
= vtop
->c
.ui
;
5707 vtop
->c
.ll
= vtop
->c
.i
;
5709 /* machine independent conversion */
5711 /* generate high word */
5712 if (sbt
== (VT_INT
| VT_UNSIGNED
)) {
5720 /* patch second register */
5721 vtop
[-1].r2
= vtop
->r
;
5725 } else if (dbt
== VT_BOOL
) {
5726 /* scalar to bool */
5729 } else if ((dbt
& VT_BTYPE
) == VT_BYTE
||
5730 (dbt
& VT_BTYPE
) == VT_SHORT
) {
5731 force_charshort_cast(dbt
);
5732 } else if ((dbt
& VT_BTYPE
) == VT_INT
) {
5734 if (sbt
== VT_LLONG
) {
5735 /* from long long: just take low order word */
5739 /* if lvalue and single word type, nothing to do because
5740 the lvalue already contains the real type size (see
5741 VT_LVAL_xxx constants) */
5747 /* return type size. Put alignment at 'a' */
5748 static int type_size(CType
*type
, int *a
)
5753 bt
= type
->t
& VT_BTYPE
;
5754 if (bt
== VT_STRUCT
) {
5759 } else if (bt
== VT_PTR
) {
5760 if (type
->t
& VT_ARRAY
) {
5762 return type_size(&s
->type
, a
) * s
->c
;
5767 } else if (bt
== VT_LDOUBLE
) {
5769 return LDOUBLE_SIZE
;
5770 } else if (bt
== VT_DOUBLE
|| bt
== VT_LLONG
) {
5771 #ifdef TCC_TARGET_I386
5777 } else if (bt
== VT_INT
|| bt
== VT_ENUM
|| bt
== VT_FLOAT
) {
5780 } else if (bt
== VT_SHORT
) {
5784 /* char, void, function, _Bool */
5790 /* return the pointed type of t */
5791 static inline CType
*pointed_type(CType
*type
)
5793 return &type
->ref
->type
;
5796 /* modify type so that its it is a pointer to type. */
5797 static void mk_pointer(CType
*type
)
5800 s
= sym_push(SYM_FIELD
, type
, 0, -1);
5801 type
->t
= VT_PTR
| (type
->t
& ~VT_TYPE
);
5805 /* compare function types. OLD functions match any new functions */
5806 static int is_compatible_func(CType
*type1
, CType
*type2
)
5812 if (!is_compatible_types(&s1
->type
, &s2
->type
))
5814 /* check func_call */
5817 /* XXX: not complete */
5818 if (s1
->c
== FUNC_OLD
|| s2
->c
== FUNC_OLD
)
5822 while (s1
!= NULL
) {
5825 if (!is_compatible_types(&s1
->type
, &s2
->type
))
5835 /* return true if type1 and type2 are exactly the same (including
5838 - enums are not checked as gcc __builtin_types_compatible_p ()
5840 static int is_compatible_types(CType
*type1
, CType
*type2
)
5844 t1
= type1
->t
& VT_TYPE
;
5845 t2
= type2
->t
& VT_TYPE
;
5846 /* XXX: bitfields ? */
5849 /* test more complicated cases */
5850 bt1
= t1
& VT_BTYPE
;
5851 if (bt1
== VT_PTR
) {
5852 type1
= pointed_type(type1
);
5853 type2
= pointed_type(type2
);
5854 return is_compatible_types(type1
, type2
);
5855 } else if (bt1
== VT_STRUCT
) {
5856 return (type1
->ref
== type2
->ref
);
5857 } else if (bt1
== VT_FUNC
) {
5858 return is_compatible_func(type1
, type2
);
5864 /* print a type. If 'varstr' is not NULL, then the variable is also
5865 printed in the type */
5867 /* XXX: add array and function pointers */
5868 void type_to_str(char *buf
, int buf_size
,
5869 CType
*type
, const char *varstr
)
5876 t
= type
->t
& VT_TYPE
;
5879 if (t
& VT_CONSTANT
)
5880 pstrcat(buf
, buf_size
, "const ");
5881 if (t
& VT_VOLATILE
)
5882 pstrcat(buf
, buf_size
, "volatile ");
5883 if (t
& VT_UNSIGNED
)
5884 pstrcat(buf
, buf_size
, "unsigned ");
5914 tstr
= "long double";
5916 pstrcat(buf
, buf_size
, tstr
);
5920 if (bt
== VT_STRUCT
)
5924 pstrcat(buf
, buf_size
, tstr
);
5925 v
= type
->ref
->v
& ~SYM_STRUCT
;
5926 if (v
>= SYM_FIRST_ANOM
)
5927 pstrcat(buf
, buf_size
, "<anonymous>");
5929 pstrcat(buf
, buf_size
, get_tok_str(v
, NULL
));
5933 type_to_str(buf
, buf_size
, &s
->type
, varstr
);
5934 pstrcat(buf
, buf_size
, "(");
5936 while (sa
!= NULL
) {
5937 type_to_str(buf1
, sizeof(buf1
), &sa
->type
, NULL
);
5938 pstrcat(buf
, buf_size
, buf1
);
5941 pstrcat(buf
, buf_size
, ", ");
5943 pstrcat(buf
, buf_size
, ")");
5947 pstrcpy(buf1
, sizeof(buf1
), "*");
5949 pstrcat(buf1
, sizeof(buf1
), varstr
);
5950 type_to_str(buf
, buf_size
, &s
->type
, buf1
);
5954 pstrcat(buf
, buf_size
, " ");
5955 pstrcat(buf
, buf_size
, varstr
);
5960 /* verify type compatibility to store vtop in 'dt' type, and generate
5962 static void gen_assign_cast(CType
*dt
)
5964 CType
*st
, *type1
, *type2
, tmp_type1
, tmp_type2
;
5965 char buf1
[256], buf2
[256];
5968 st
= &vtop
->type
; /* source type */
5969 dbt
= dt
->t
& VT_BTYPE
;
5970 sbt
= st
->t
& VT_BTYPE
;
5971 if (dt
->t
& VT_CONSTANT
)
5972 warning("assignment of read-only location");
5975 /* special cases for pointers */
5976 /* '0' can also be a pointer */
5977 if (is_null_pointer(vtop
))
5979 /* accept implicit pointer to integer cast with warning */
5980 if (is_integer_btype(sbt
)) {
5981 warning("assignment makes pointer from integer without a cast");
5984 type1
= pointed_type(dt
);
5985 /* a function is implicitely a function pointer */
5986 if (sbt
== VT_FUNC
) {
5987 if ((type1
->t
& VT_BTYPE
) != VT_VOID
&&
5988 !is_compatible_types(pointed_type(dt
), st
))
5995 type2
= pointed_type(st
);
5996 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
5997 (type2
->t
& VT_BTYPE
) == VT_VOID
) {
5998 /* void * can match anything */
6000 /* exact type match, except for unsigned */
6003 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
6004 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
6005 if (!is_compatible_types(&tmp_type1
, &tmp_type2
))
6008 /* check const and volatile */
6009 if ((!(type1
->t
& VT_CONSTANT
) && (type2
->t
& VT_CONSTANT
)) ||
6010 (!(type1
->t
& VT_VOLATILE
) && (type2
->t
& VT_VOLATILE
)))
6011 warning("assignment discards qualifiers from pointer target type");
6017 if (sbt
== VT_PTR
|| sbt
== VT_FUNC
) {
6018 warning("assignment makes integer from pointer without a cast");
6020 /* XXX: more tests */
6025 tmp_type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6026 tmp_type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6027 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
6029 type_to_str(buf1
, sizeof(buf1
), st
, NULL
);
6030 type_to_str(buf2
, sizeof(buf2
), dt
, NULL
);
6031 error("cannot cast '%s' to '%s'", buf1
, buf2
);
6039 /* store vtop in lvalue pushed on stack */
6042 int sbt
, dbt
, ft
, r
, t
, size
, align
, bit_size
, bit_pos
, rc
, delayed_cast
;
6044 ft
= vtop
[-1].type
.t
;
6045 sbt
= vtop
->type
.t
& VT_BTYPE
;
6046 dbt
= ft
& VT_BTYPE
;
6047 if (((sbt
== VT_INT
|| sbt
== VT_SHORT
) && dbt
== VT_BYTE
) ||
6048 (sbt
== VT_INT
&& dbt
== VT_SHORT
)) {
6049 /* optimize char/short casts */
6050 delayed_cast
= VT_MUSTCAST
;
6051 vtop
->type
.t
= ft
& VT_TYPE
;
6052 /* XXX: factorize */
6053 if (ft
& VT_CONSTANT
)
6054 warning("assignment of read-only location");
6057 if (!(ft
& VT_BITFIELD
))
6058 gen_assign_cast(&vtop
[-1].type
);
6061 if (sbt
== VT_STRUCT
) {
6062 /* if structure, only generate pointer */
6063 /* structure assignment : generate memcpy */
6064 /* XXX: optimize if small size */
6065 if (!nocode_wanted
) {
6066 size
= type_size(&vtop
->type
, &align
);
6068 vpush_global_sym(&func_old_type
, TOK_memcpy
);
6072 vtop
->type
.t
= VT_INT
;
6076 vtop
->type
.t
= VT_INT
;
6088 /* leave source on stack */
6089 } else if (ft
& VT_BITFIELD
) {
6090 /* bitfield store handling */
6091 bit_pos
= (ft
>> VT_STRUCT_SHIFT
) & 0x3f;
6092 bit_size
= (ft
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
6093 /* remove bit field info to avoid loops */
6094 vtop
[-1].type
.t
= ft
& ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
6096 /* duplicate destination */
6098 vtop
[-1] = vtop
[-2];
6100 /* mask and shift source */
6101 vpushi((1 << bit_size
) - 1);
6105 /* load destination, mask and or with source */
6107 vpushi(~(((1 << bit_size
) - 1) << bit_pos
));
6113 #ifdef CONFIG_TCC_BCHECK
6114 /* bound check case */
6115 if (vtop
[-1].r
& VT_MUSTBOUND
) {
6121 if (!nocode_wanted
) {
6125 r
= gv(rc
); /* generate value */
6126 /* if lvalue was saved on stack, must read it */
6127 if ((vtop
[-1].r
& VT_VALMASK
) == VT_LLOCAL
) {
6129 t
= get_reg(RC_INT
);
6131 sv
.r
= VT_LOCAL
| VT_LVAL
;
6132 sv
.c
.ul
= vtop
[-1].c
.ul
;
6134 vtop
[-1].r
= t
| VT_LVAL
;
6137 /* two word case handling : store second register at word + 4 */
6138 if ((ft
& VT_BTYPE
) == VT_LLONG
) {
6140 /* convert to int to increment easily */
6141 vtop
->type
.t
= VT_INT
;
6147 /* XXX: it works because r2 is spilled last ! */
6148 store(vtop
->r2
, vtop
- 1);
6152 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
6153 vtop
->r
|= delayed_cast
;
6157 /* post defines POST/PRE add. c is the token ++ or -- */
6158 void inc(int post
, int c
)
6161 vdup(); /* save lvalue */
6163 gv_dup(); /* duplicate value */
6168 vpushi(c
- TOK_MID
);
6170 vstore(); /* store value */
6172 vpop(); /* if post op, return saved value */
6175 /* Parse GNUC __attribute__ extension. Currently, the following
6176 extensions are recognized:
6177 - aligned(n) : set data/function alignment.
6178 - section(x) : generate data/code in this section.
6179 - unused : currently ignored, but may be used someday.
6181 static void parse_attribute(AttributeDef
*ad
)
6185 while (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
) {
6189 while (tok
!= ')') {
6190 if (tok
< TOK_IDENT
)
6191 expect("attribute name");
6199 expect("section name");
6200 ad
->section
= find_section(tcc_state
, (char *)tokc
.cstr
->data
);
6209 if (n
<= 0 || (n
& (n
- 1)) != 0)
6210 error("alignment must be a positive power of two");
6219 /* currently, no need to handle it because tcc does not
6220 track unused objects */
6224 /* currently, no need to handle it because tcc does not
6225 track unused objects */
6230 ad
->func_call
= FUNC_CDECL
;
6235 ad
->func_call
= FUNC_STDCALL
;
6237 #ifdef TCC_TARGET_I386
6247 ad
->func_call
= FUNC_FASTCALL1
+ n
- 1;
6252 if (tcc_state
->warn_unsupported
)
6253 warning("'%s' attribute ignored", get_tok_str(t
, NULL
));
6254 /* skip parameters */
6255 /* XXX: skip parenthesis too */
6258 while (tok
!= ')' && tok
!= -1)
6273 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
6274 static void struct_decl(CType
*type
, int u
)
6276 int a
, v
, size
, align
, maxalign
, c
, offset
;
6277 int bit_size
, bit_pos
, bsize
, bt
, lbit_pos
;
6282 a
= tok
; /* save decl type */
6287 /* struct already defined ? return it */
6289 expect("struct/union/enum name");
6293 error("invalid type");
6300 /* we put an undefined size for struct/union */
6301 s
= sym_push(v
| SYM_STRUCT
, &type1
, 0, -1);
6302 s
->r
= 0; /* default alignment is zero as gcc */
6303 /* put struct/union/enum name in type */
6311 error("struct/union/enum already defined");
6312 /* cannot be empty */
6314 /* non empty enums are not allowed */
6315 if (a
== TOK_ENUM
) {
6319 expect("identifier");
6325 /* enum symbols have static storage */
6326 ss
= sym_push(v
, &int_type
, VT_CONST
, c
);
6327 ss
->type
.t
|= VT_STATIC
;
6332 /* NOTE: we accept a trailing comma */
6342 while (tok
!= '}') {
6343 parse_btype(&btype
, &ad
);
6349 type_decl(&type1
, &ad
, &v
, TYPE_DIRECT
);
6350 if ((type1
.t
& VT_BTYPE
) == VT_FUNC
||
6351 (type1
.t
& (VT_TYPEDEF
| VT_STATIC
| VT_EXTERN
| VT_INLINE
)))
6352 error("invalid type for '%s'",
6353 get_tok_str(v
, NULL
));
6357 bit_size
= expr_const();
6358 /* XXX: handle v = 0 case for messages */
6360 error("negative width in bit-field '%s'",
6361 get_tok_str(v
, NULL
));
6362 if (v
&& bit_size
== 0)
6363 error("zero width for bit-field '%s'",
6364 get_tok_str(v
, NULL
));
6366 size
= type_size(&type1
, &align
);
6367 if (align
< ad
.aligned
)
6370 if (bit_size
>= 0) {
6371 bt
= type1
.t
& VT_BTYPE
;
6377 error("bitfields must have scalar type");
6379 if (bit_size
> bsize
) {
6380 error("width of '%s' exceeds its type",
6381 get_tok_str(v
, NULL
));
6382 } else if (bit_size
== bsize
) {
6383 /* no need for bit fields */
6385 } else if (bit_size
== 0) {
6386 /* XXX: what to do if only padding in a
6388 /* zero size: means to pad */
6392 /* we do not have enough room ? */
6393 if ((bit_pos
+ bit_size
) > bsize
)
6396 /* XXX: handle LSB first */
6397 type1
.t
|= VT_BITFIELD
|
6398 (bit_pos
<< VT_STRUCT_SHIFT
) |
6399 (bit_size
<< (VT_STRUCT_SHIFT
+ 6));
6400 bit_pos
+= bit_size
;
6406 /* add new memory data only if starting
6408 if (lbit_pos
== 0) {
6409 if (a
== TOK_STRUCT
) {
6410 c
= (c
+ align
- 1) & -align
;
6418 if (align
> maxalign
)
6422 printf("add field %s offset=%d",
6423 get_tok_str(v
, NULL
), offset
);
6424 if (type1
.t
& VT_BITFIELD
) {
6425 printf(" pos=%d size=%d",
6426 (type1
.t
>> VT_STRUCT_SHIFT
) & 0x3f,
6427 (type1
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f);
6431 ss
= sym_push(v
| SYM_FIELD
, &type1
, 0, offset
);
6435 if (tok
== ';' || tok
== TOK_EOF
)
6442 /* store size and alignment */
6443 s
->c
= (c
+ maxalign
- 1) & -maxalign
;
6449 /* return 0 if no type declaration. otherwise, return the basic type
6452 static int parse_btype(CType
*type
, AttributeDef
*ad
)
6454 int t
, u
, type_found
, typespec_found
;
6458 memset(ad
, 0, sizeof(AttributeDef
));
6465 /* currently, we really ignore extension */
6475 if ((t
& VT_BTYPE
) != 0)
6476 error("too many basic types");
6492 if ((t
& VT_BTYPE
) == VT_DOUBLE
) {
6493 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6494 } else if ((t
& VT_BTYPE
) == VT_LONG
) {
6495 t
= (t
& ~VT_BTYPE
) | VT_LLONG
;
6509 if ((t
& VT_BTYPE
) == VT_LONG
) {
6510 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6517 struct_decl(&type1
, VT_ENUM
);
6520 type
->ref
= type1
.ref
;
6524 struct_decl(&type1
, VT_STRUCT
);
6527 /* type modifiers */
6580 /* GNUC attribute */
6581 case TOK_ATTRIBUTE1
:
6582 case TOK_ATTRIBUTE2
:
6583 parse_attribute(ad
);
6590 parse_expr_type(&type1
);
6596 if (!s
|| !(s
->type
.t
& VT_TYPEDEF
))
6598 t
|= (s
->type
.t
& ~VT_TYPEDEF
);
6599 type
->ref
= s
->type
.ref
;
6606 if ((t
& (VT_SIGNED
|VT_UNSIGNED
)) == (VT_SIGNED
|VT_UNSIGNED
))
6607 error("signed and unsigned modifier");
6608 if (tcc_state
->char_is_unsigned
) {
6609 if ((t
& (VT_SIGNED
|VT_UNSIGNED
|VT_BTYPE
)) == VT_BYTE
)
6614 /* long is never used as type */
6615 if ((t
& VT_BTYPE
) == VT_LONG
)
6616 t
= (t
& ~VT_BTYPE
) | VT_INT
;
6621 /* convert a function parameter type (array to pointer and function to
6622 function pointer) */
6623 static inline void convert_parameter_type(CType
*pt
)
6625 /* remove const and volatile qualifiers (XXX: const could be used
6626 to indicate a const function parameter */
6627 pt
->t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6628 /* array must be transformed to pointer according to ANSI C */
6630 if ((pt
->t
& VT_BTYPE
) == VT_FUNC
) {
6635 static void post_type(CType
*type
, AttributeDef
*ad
)
6638 Sym
**plast
, *s
, *first
;
6643 /* function declaration */
6648 while (tok
!= ')') {
6649 /* read param name and compute offset */
6650 if (l
!= FUNC_OLD
) {
6651 if (!parse_btype(&pt
, &ad1
)) {
6653 error("invalid type");
6660 if ((pt
.t
& VT_BTYPE
) == VT_VOID
&& tok
== ')')
6662 type_decl(&pt
, &ad1
, &n
, TYPE_DIRECT
| TYPE_ABSTRACT
);
6663 if ((pt
.t
& VT_BTYPE
) == VT_VOID
)
6664 error("parameter declared as void");
6671 convert_parameter_type(&pt
);
6672 s
= sym_push(n
| SYM_FIELD
, &pt
, 0, 0);
6677 if (l
== FUNC_NEW
&& tok
== TOK_DOTS
) {
6684 /* if no parameters, then old type prototype */
6688 t1
= type
->t
& VT_STORAGE
;
6689 /* NOTE: const is ignored in returned type as it has a special
6690 meaning in gcc / C++ */
6691 type
->t
&= ~(VT_STORAGE
| VT_CONSTANT
);
6692 post_type(type
, ad
);
6693 /* we push a anonymous symbol which will contain the function prototype */
6694 s
= sym_push(SYM_FIELD
, type
, ad
->func_call
, l
);
6696 type
->t
= t1
| VT_FUNC
;
6698 } else if (tok
== '[') {
6699 /* array definition */
6705 error("invalid array size");
6708 /* parse next post type */
6709 t1
= type
->t
& VT_STORAGE
;
6710 type
->t
&= ~VT_STORAGE
;
6711 post_type(type
, ad
);
6713 /* we push a anonymous symbol which will contain the array
6715 s
= sym_push(SYM_FIELD
, type
, 0, n
);
6716 type
->t
= t1
| VT_ARRAY
| VT_PTR
;
6721 /* Parse a type declaration (except basic type), and return the type
6722 in 'type'. 'td' is a bitmask indicating which kind of type decl is
6723 expected. 'type' should contain the basic type. 'ad' is the
6724 attribute definition of the basic type. It can be modified by
6727 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
)
6730 CType type1
, *type2
;
6733 while (tok
== '*') {
6741 qualifiers
|= VT_CONSTANT
;
6746 qualifiers
|= VT_VOLATILE
;
6754 type
->t
|= qualifiers
;
6757 /* XXX: clarify attribute handling */
6758 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6759 parse_attribute(ad
);
6761 /* recursive type */
6762 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
6763 type1
.t
= 0; /* XXX: same as int */
6766 /* XXX: this is not correct to modify 'ad' at this point, but
6767 the syntax is not clear */
6768 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6769 parse_attribute(ad
);
6770 type_decl(&type1
, ad
, v
, td
);
6773 /* type identifier */
6774 if (tok
>= TOK_IDENT
&& (td
& TYPE_DIRECT
)) {
6778 if (!(td
& TYPE_ABSTRACT
))
6779 expect("identifier");
6783 post_type(type
, ad
);
6784 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6785 parse_attribute(ad
);
6788 /* append type at the end of type1 */
6801 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
6802 static int lvalue_type(int t
)
6807 if (bt
== VT_BYTE
|| bt
== VT_BOOL
)
6809 else if (bt
== VT_SHORT
)
6813 if (t
& VT_UNSIGNED
)
6814 r
|= VT_LVAL_UNSIGNED
;
6818 /* indirection with full error checking and bound check */
6819 static void indir(void)
6821 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
6823 if ((vtop
->r
& VT_LVAL
) && !nocode_wanted
)
6825 vtop
->type
= *pointed_type(&vtop
->type
);
6826 /* an array is never an lvalue */
6827 if (!(vtop
->type
.t
& VT_ARRAY
)) {
6828 vtop
->r
|= lvalue_type(vtop
->type
.t
);
6829 /* if bound checking, the referenced pointer must be checked */
6830 if (do_bounds_check
)
6831 vtop
->r
|= VT_MUSTBOUND
;
6835 /* pass a parameter to a function and do type checking and casting */
6836 static void gfunc_param_typed(Sym
*func
, Sym
*arg
)
6841 func_type
= func
->c
;
6842 if (func_type
== FUNC_OLD
||
6843 (func_type
== FUNC_ELLIPSIS
&& arg
== NULL
)) {
6844 /* default casting : only need to convert float to double */
6845 if ((vtop
->type
.t
& VT_BTYPE
) == VT_FLOAT
) {
6849 } else if (arg
== NULL
) {
6850 error("too many arguments to function");
6853 type
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
6854 gen_assign_cast(&type
);
6858 /* parse an expression of the form '(type)' or '(expr)' and return its
6860 static void parse_expr_type(CType
*type
)
6866 if (parse_btype(type
, &ad
)) {
6867 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
6874 static void parse_type(CType
*type
)
6879 if (!parse_btype(type
, &ad
)) {
6882 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
6885 static void vpush_tokc(int t
)
6889 vsetc(&type
, VT_CONST
, &tokc
);
6892 static void unary(void)
6894 int n
, t
, align
, size
, r
;
6899 /* XXX: GCC 2.95.3 does not generate a table although it should be
6913 vpush_tokc(VT_INT
| VT_UNSIGNED
);
6917 vpush_tokc(VT_LLONG
);
6921 vpush_tokc(VT_LLONG
| VT_UNSIGNED
);
6925 vpush_tokc(VT_FLOAT
);
6929 vpush_tokc(VT_DOUBLE
);
6933 vpush_tokc(VT_LDOUBLE
);
6936 case TOK___FUNCTION__
:
6938 goto tok_identifier
;
6944 /* special function name identifier */
6945 len
= strlen(funcname
) + 1;
6946 /* generate char[len] type */
6951 vpush_ref(&type
, data_section
, data_section
->data_offset
, len
);
6952 ptr
= section_ptr_add(data_section
, len
);
6953 memcpy(ptr
, funcname
, len
);
6961 /* string parsing */
6964 if (tcc_state
->warn_write_strings
)
6969 memset(&ad
, 0, sizeof(AttributeDef
));
6970 decl_initializer_alloc(&type
, &ad
, VT_CONST
, 2, 0, 0);
6975 if (parse_btype(&type
, &ad
)) {
6976 type_decl(&type
, &ad
, &n
, TYPE_ABSTRACT
);
6978 /* check ISOC99 compound literal */
6980 /* data is allocated locally by default */
6985 /* all except arrays are lvalues */
6986 if (!(type
.t
& VT_ARRAY
))
6987 r
|= lvalue_type(type
.t
);
6988 memset(&ad
, 0, sizeof(AttributeDef
));
6989 decl_initializer_alloc(&type
, &ad
, r
, 1, 0, 0);
6994 } else if (tok
== '{') {
6995 /* save all registers */
6997 /* statement expression : we do not accept break/continue
6998 inside as GCC does */
6999 block(NULL
, NULL
, NULL
, NULL
, 0, 1);
7014 /* functions names must be treated as function pointers,
7015 except for unary '&' and sizeof. Since we consider that
7016 functions are not lvalues, we only have to handle it
7017 there and in function calls. */
7018 /* arrays can also be used although they are not lvalues */
7019 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
&&
7020 !(vtop
->type
.t
& VT_ARRAY
))
7022 mk_pointer(&vtop
->type
);
7028 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
)
7029 vtop
->c
.i
= !vtop
->c
.i
;
7030 else if ((vtop
->r
& VT_VALMASK
) == VT_CMP
)
7031 vtop
->c
.i
= vtop
->c
.i
^ 1;
7033 vseti(VT_JMP
, gtst(1, 0));
7043 /* in order to force cast, we add zero */
7045 if ((vtop
->type
.t
& VT_BTYPE
) == VT_PTR
)
7046 error("pointer not accepted for unary plus");
7056 parse_expr_type(&type
);
7060 size
= type_size(&type
, &align
);
7061 if (t
== TOK_SIZEOF
) {
7063 error("sizeof applied to an incomplete type");
7070 case TOK_builtin_types_compatible_p
:
7079 type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7080 type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7081 vpushi(is_compatible_types(&type1
, &type2
));
7084 case TOK_builtin_constant_p
:
7086 int saved_nocode_wanted
, res
;
7089 saved_nocode_wanted
= nocode_wanted
;
7092 res
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
7094 nocode_wanted
= saved_nocode_wanted
;
7114 goto tok_identifier
;
7116 /* allow to take the address of a label */
7117 if (tok
< TOK_UIDENT
)
7118 expect("label identifier");
7119 s
= label_find(tok
);
7121 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
7123 if (s
->r
== LABEL_DECLARED
)
7124 s
->r
= LABEL_FORWARD
;
7127 s
->type
.t
= VT_VOID
;
7128 mk_pointer(&s
->type
);
7129 s
->type
.t
|= VT_STATIC
;
7131 vset(&s
->type
, VT_CONST
| VT_SYM
, 0);
7140 expect("identifier");
7144 error("'%s' undeclared", get_tok_str(t
, NULL
));
7145 /* for simple function calls, we tolerate undeclared
7146 external reference to int() function */
7147 if (tcc_state
->warn_implicit_function_declaration
)
7148 warning("implicit declaration of function '%s'",
7149 get_tok_str(t
, NULL
));
7150 s
= external_global_sym(t
, &func_old_type
, 0);
7152 if ((s
->type
.t
& (VT_STATIC
| VT_INLINE
| VT_BTYPE
)) ==
7153 (VT_STATIC
| VT_INLINE
| VT_FUNC
)) {
7154 /* if referencing an inline function, then we generate a
7155 symbol to it if not already done. It will have the
7156 effect to generate code for it at the end of the
7157 compilation unit. Inline function as always
7158 generated in the text section. */
7160 put_extern_sym(s
, text_section
, 0, 0);
7161 r
= VT_SYM
| VT_CONST
;
7165 vset(&s
->type
, r
, s
->c
);
7166 /* if forward reference, we must point to s */
7167 if (vtop
->r
& VT_SYM
) {
7174 /* post operations */
7176 if (tok
== TOK_INC
|| tok
== TOK_DEC
) {
7179 } else if (tok
== '.' || tok
== TOK_ARROW
) {
7181 if (tok
== TOK_ARROW
)
7186 /* expect pointer on structure */
7187 if ((vtop
->type
.t
& VT_BTYPE
) != VT_STRUCT
)
7188 expect("struct or union");
7192 while ((s
= s
->next
) != NULL
) {
7197 error("field not found");
7198 /* add field offset to pointer */
7199 vtop
->type
= char_pointer_type
; /* change type to 'char *' */
7202 /* change type to field type, and set to lvalue */
7203 vtop
->type
= s
->type
;
7204 /* an array is never an lvalue */
7205 if (!(vtop
->type
.t
& VT_ARRAY
)) {
7206 vtop
->r
|= lvalue_type(vtop
->type
.t
);
7207 /* if bound checking, the referenced pointer must be checked */
7208 if (do_bounds_check
)
7209 vtop
->r
|= VT_MUSTBOUND
;
7212 } else if (tok
== '[') {
7218 } else if (tok
== '(') {
7224 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
) {
7225 /* pointer test (no array accepted) */
7226 if ((vtop
->type
.t
& (VT_BTYPE
| VT_ARRAY
)) == VT_PTR
) {
7227 vtop
->type
= *pointed_type(&vtop
->type
);
7228 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
)
7232 expect("function pointer");
7235 vtop
->r
&= ~VT_LVAL
; /* no lvalue */
7237 /* get return type */
7240 sa
= s
->next
; /* first parameter */
7242 /* compute first implicit argument if a structure is returned */
7243 if ((s
->type
.t
& VT_BTYPE
) == VT_STRUCT
) {
7244 /* get some space for the returned structure */
7245 size
= type_size(&s
->type
, &align
);
7246 loc
= (loc
- size
) & -align
;
7248 ret
.r
= VT_LOCAL
| VT_LVAL
;
7249 /* pass it as 'int' to avoid structure arg passing
7251 vseti(VT_LOCAL
, loc
);
7257 /* return in register */
7258 if (is_float(ret
.type
.t
)) {
7261 if ((ret
.type
.t
& VT_BTYPE
) == VT_LLONG
)
7270 gfunc_param_typed(s
, sa
);
7280 error("too few arguments to function");
7282 if (!nocode_wanted
) {
7283 gfunc_call(nb_args
);
7285 vtop
-= (nb_args
+ 1);
7288 vsetc(&ret
.type
, ret
.r
, &ret
.c
);
7296 static void uneq(void)
7302 (tok
>= TOK_A_MOD
&& tok
<= TOK_A_DIV
) ||
7303 tok
== TOK_A_XOR
|| tok
== TOK_A_OR
||
7304 tok
== TOK_A_SHL
|| tok
== TOK_A_SAR
) {
7319 static void expr_prod(void)
7324 while (tok
== '*' || tok
== '/' || tok
== '%') {
7332 static void expr_sum(void)
7337 while (tok
== '+' || tok
== '-') {
7345 static void expr_shift(void)
7350 while (tok
== TOK_SHL
|| tok
== TOK_SAR
) {
7358 static void expr_cmp(void)
7363 while ((tok
>= TOK_ULE
&& tok
<= TOK_GT
) ||
7364 tok
== TOK_ULT
|| tok
== TOK_UGE
) {
7372 static void expr_cmpeq(void)
7377 while (tok
== TOK_EQ
|| tok
== TOK_NE
) {
7385 static void expr_and(void)
7388 while (tok
== '&') {
7395 static void expr_xor(void)
7398 while (tok
== '^') {
7405 static void expr_or(void)
7408 while (tok
== '|') {
7415 /* XXX: fix this mess */
7416 static void expr_land_const(void)
7419 while (tok
== TOK_LAND
) {
7426 /* XXX: fix this mess */
7427 static void expr_lor_const(void)
7430 while (tok
== TOK_LOR
) {
7437 /* only used if non constant */
7438 static void expr_land(void)
7443 if (tok
== TOK_LAND
) {
7447 if (tok
!= TOK_LAND
) {
7457 static void expr_lor(void)
7462 if (tok
== TOK_LOR
) {
7466 if (tok
!= TOK_LOR
) {
7476 /* XXX: better constant handling */
7477 static void expr_eq(void)
7479 int tt
, u
, r1
, r2
, rc
, t1
, t2
, bt1
, bt2
;
7481 CType type
, type1
, type2
;
7490 if (tok
== ':' && gnu_ext
) {
7506 if (vtop
!= vstack
) {
7507 /* needed to avoid having different registers saved in
7509 if (is_float(vtop
->type
.t
))
7516 if (tok
== ':' && gnu_ext
) {
7524 sv
= *vtop
; /* save value to handle it later */
7525 vtop
--; /* no vpop so that FP stack is not flushed */
7533 bt1
= t1
& VT_BTYPE
;
7535 bt2
= t2
& VT_BTYPE
;
7536 /* cast operands to correct type according to ISOC rules */
7537 if (is_float(bt1
) || is_float(bt2
)) {
7538 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
7539 type
.t
= VT_LDOUBLE
;
7540 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
7545 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
7546 /* cast to biggest op */
7548 /* convert to unsigned if it does not fit in a long long */
7549 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
7550 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
7551 type
.t
|= VT_UNSIGNED
;
7552 } else if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
7553 /* XXX: test pointer compatibility */
7555 } else if (bt1
== VT_STRUCT
|| bt2
== VT_STRUCT
) {
7556 /* XXX: test structure compatibility */
7558 } else if (bt1
== VT_VOID
|| bt2
== VT_VOID
) {
7559 /* NOTE: as an extension, we accept void on only one side */
7562 /* integer operations */
7564 /* convert to unsigned if it does not fit in an integer */
7565 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
7566 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
7567 type
.t
|= VT_UNSIGNED
;
7570 /* now we convert second operand */
7573 if (is_float(type
.t
)) {
7575 } else if ((type
.t
& VT_BTYPE
) == VT_LLONG
) {
7576 /* for long longs, we use fixed registers to avoid having
7577 to handle a complicated move */
7582 /* this is horrible, but we must also convert first
7586 /* put again first value and cast it */
7597 static void gexpr(void)
7608 /* parse an expression and return its type without any side effect. */
7609 static void expr_type(CType
*type
)
7611 int saved_nocode_wanted
;
7613 saved_nocode_wanted
= nocode_wanted
;
7618 nocode_wanted
= saved_nocode_wanted
;
7621 /* parse a unary expression and return its type without any side
7623 static void unary_type(CType
*type
)
7635 /* parse a constant expression and return value in vtop. */
7636 static void expr_const1(void)
7645 /* parse an integer constant and return its value. */
7646 static int expr_const(void)
7650 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
7651 expect("constant expression");
7657 /* return the label token if current token is a label, otherwise
7659 static int is_label(void)
7663 /* fast test first */
7664 if (tok
< TOK_UIDENT
)
7666 /* no need to save tokc because tok is an identifier */
7673 unget_tok(last_tok
);
7678 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
7679 int case_reg
, int is_expr
)
7684 /* generate line number info */
7686 (last_line_num
!= file
->line_num
|| last_ind
!= ind
)) {
7687 put_stabn(N_SLINE
, 0, file
->line_num
, ind
- func_ind
);
7689 last_line_num
= file
->line_num
;
7693 /* default return value is (void) */
7695 vtop
->type
.t
= VT_VOID
;
7698 if (tok
== TOK_IF
) {
7705 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7707 if (c
== TOK_ELSE
) {
7711 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7712 gsym(d
); /* patch else jmp */
7715 } else if (tok
== TOK_WHILE
) {
7723 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7727 } else if (tok
== '{') {
7731 /* record local declaration stack position */
7733 llabel
= local_label_stack
;
7734 /* handle local labels declarations */
7735 if (tok
== TOK_LABEL
) {
7738 if (tok
< TOK_UIDENT
)
7739 expect("label identifier");
7740 label_push(&local_label_stack
, tok
, LABEL_DECLARED
);
7750 while (tok
!= '}') {
7755 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
7758 /* pop locally defined labels */
7759 label_pop(&local_label_stack
, llabel
);
7760 /* pop locally defined symbols */
7761 sym_pop(&local_stack
, s
);
7763 } else if (tok
== TOK_RETURN
) {
7767 gen_assign_cast(&func_vt
);
7768 if ((func_vt
.t
& VT_BTYPE
) == VT_STRUCT
) {
7770 /* if returning structure, must copy it to implicit
7771 first pointer arg location */
7774 vset(&type
, VT_LOCAL
| VT_LVAL
, func_vc
);
7777 /* copy structure value to pointer */
7779 } else if (is_float(func_vt
.t
)) {
7784 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
7787 rsym
= gjmp(rsym
); /* jmp */
7788 } else if (tok
== TOK_BREAK
) {
7791 error("cannot break");
7792 *bsym
= gjmp(*bsym
);
7795 } else if (tok
== TOK_CONTINUE
) {
7798 error("cannot continue");
7799 *csym
= gjmp(*csym
);
7802 } else if (tok
== TOK_FOR
) {
7829 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7834 if (tok
== TOK_DO
) {
7839 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7850 if (tok
== TOK_SWITCH
) {
7854 /* XXX: other types than integer */
7855 case_reg
= gv(RC_INT
);
7859 b
= gjmp(0); /* jump to first case */
7861 block(&a
, csym
, &b
, &c
, case_reg
, 0);
7862 /* if no default, jmp after switch */
7870 if (tok
== TOK_CASE
) {
7877 if (gnu_ext
&& tok
== TOK_DOTS
) {
7881 warning("empty case range");
7883 /* since a case is like a label, we must skip it with a jmp */
7890 *case_sym
= gtst(1, 0);
7893 *case_sym
= gtst(1, 0);
7897 *case_sym
= gtst(1, *case_sym
);
7902 goto block_after_label
;
7904 if (tok
== TOK_DEFAULT
) {
7910 error("too many 'default'");
7913 goto block_after_label
;
7915 if (tok
== TOK_GOTO
) {
7917 if (tok
== '*' && gnu_ext
) {
7921 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
7924 } else if (tok
>= TOK_UIDENT
) {
7925 s
= label_find(tok
);
7926 /* put forward definition if needed */
7928 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
7930 if (s
->r
== LABEL_DECLARED
)
7931 s
->r
= LABEL_FORWARD
;
7933 /* label already defined */
7934 if (s
->r
& LABEL_FORWARD
)
7935 s
->next
= (void *)gjmp((long)s
->next
);
7937 gjmp_addr((long)s
->next
);
7940 expect("label identifier");
7943 } else if (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
) {
7951 if (s
->r
== LABEL_DEFINED
)
7952 error("duplicate label '%s'", get_tok_str(s
->v
, NULL
));
7953 gsym((long)s
->next
);
7954 s
->r
= LABEL_DEFINED
;
7956 s
= label_push(&global_label_stack
, b
, LABEL_DEFINED
);
7958 s
->next
= (void *)ind
;
7959 /* we accept this, but it is a mistake */
7962 warning("deprecated use of label at end of compound statement");
7966 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
7969 /* expression case */
7984 /* t is the array or struct type. c is the array or struct
7985 address. cur_index/cur_field is the pointer to the current
7986 value. 'size_only' is true if only size info is needed (only used
7988 static void decl_designator(CType
*type
, Section
*sec
, unsigned long c
,
7989 int *cur_index
, Sym
**cur_field
,
7993 int notfirst
, index
, index_last
, align
, l
, nb_elems
, elem_size
;
7999 if (gnu_ext
&& (l
= is_label()) != 0)
8001 while (tok
== '[' || tok
== '.') {
8003 if (!(type
->t
& VT_ARRAY
))
8004 expect("array type");
8007 index
= expr_const();
8008 if (index
< 0 || (s
->c
>= 0 && index
>= s
->c
))
8009 expect("invalid index");
8010 if (tok
== TOK_DOTS
&& gnu_ext
) {
8012 index_last
= expr_const();
8013 if (index_last
< 0 ||
8014 (s
->c
>= 0 && index_last
>= s
->c
) ||
8016 expect("invalid index");
8022 *cur_index
= index_last
;
8023 type
= pointed_type(type
);
8024 elem_size
= type_size(type
, &align
);
8025 c
+= index
* elem_size
;
8026 /* NOTE: we only support ranges for last designator */
8027 nb_elems
= index_last
- index
+ 1;
8028 if (nb_elems
!= 1) {
8037 if ((type
->t
& VT_BTYPE
) != VT_STRUCT
)
8038 expect("struct/union type");
8051 /* XXX: fix this mess by using explicit storage field */
8053 type1
.t
|= (type
->t
& ~VT_TYPE
);
8067 if (type
->t
& VT_ARRAY
) {
8069 type
= pointed_type(type
);
8070 c
+= index
* type_size(type
, &align
);
8074 error("too many field init");
8075 /* XXX: fix this mess by using explicit storage field */
8077 type1
.t
|= (type
->t
& ~VT_TYPE
);
8082 decl_initializer(type
, sec
, c
, 0, size_only
);
8084 /* XXX: make it more general */
8085 if (!size_only
&& nb_elems
> 1) {
8086 unsigned long c_end
;
8091 error("range init not supported yet for dynamic storage");
8092 c_end
= c
+ nb_elems
* elem_size
;
8093 if (c_end
> sec
->data_allocated
)
8094 section_realloc(sec
, c_end
);
8095 src
= sec
->data
+ c
;
8097 for(i
= 1; i
< nb_elems
; i
++) {
8099 memcpy(dst
, src
, elem_size
);
8105 #define EXPR_CONST 1
8108 /* store a value or an expression directly in global data or in local array */
8109 static void init_putv(CType
*type
, Section
*sec
, unsigned long c
,
8110 int v
, int expr_type
)
8112 int saved_global_expr
, bt
, bit_pos
, bit_size
;
8114 unsigned long long bit_mask
;
8122 /* compound literals must be allocated globally in this case */
8123 saved_global_expr
= global_expr
;
8126 global_expr
= saved_global_expr
;
8127 /* NOTE: symbols are accepted */
8128 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) != VT_CONST
)
8129 error("initializer element is not constant");
8137 dtype
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
8140 /* XXX: not portable */
8141 /* XXX: generate error if incorrect relocation */
8142 gen_assign_cast(&dtype
);
8143 bt
= type
->t
& VT_BTYPE
;
8144 ptr
= sec
->data
+ c
;
8145 /* XXX: make code faster ? */
8146 if (!(type
->t
& VT_BITFIELD
)) {
8151 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
8152 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
8153 bit_mask
= (1LL << bit_size
) - 1;
8155 if ((vtop
->r
& VT_SYM
) &&
8161 (bt
== VT_INT
&& bit_size
!= 32)))
8162 error("initializer element is not computable at load time");
8165 *(char *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8168 *(short *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8171 *(double *)ptr
= vtop
->c
.d
;
8174 *(long double *)ptr
= vtop
->c
.ld
;
8177 *(long long *)ptr
|= (vtop
->c
.ll
& bit_mask
) << bit_pos
;
8180 if (vtop
->r
& VT_SYM
) {
8181 greloc(sec
, vtop
->sym
, c
, R_DATA_32
);
8183 *(int *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8188 vset(&dtype
, VT_LOCAL
, c
);
8195 /* put zeros for variable based init */
8196 static void init_putz(CType
*t
, Section
*sec
, unsigned long c
, int size
)
8199 /* nothing to do because globals are already set to zero */
8201 vpush_global_sym(&func_old_type
, TOK_memset
);
8209 /* 't' contains the type and storage info. 'c' is the offset of the
8210 object in section 'sec'. If 'sec' is NULL, it means stack based
8211 allocation. 'first' is true if array '{' must be read (multi
8212 dimension implicit array init handling). 'size_only' is true if
8213 size only evaluation is wanted (only for arrays). */
8214 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
8215 int first
, int size_only
)
8217 int index
, array_length
, n
, no_oblock
, nb
, parlevel
, i
;
8218 int size1
, align1
, expr_type
;
8222 if (type
->t
& VT_ARRAY
) {
8226 t1
= pointed_type(type
);
8227 size1
= type_size(t1
, &align1
);
8230 if ((first
&& tok
!= TOK_LSTR
&& tok
!= TOK_STR
) ||
8236 /* only parse strings here if correct type (otherwise: handle
8237 them as ((w)char *) expressions */
8238 if ((tok
== TOK_LSTR
&&
8239 (t1
->t
& VT_BTYPE
) == VT_INT
) ||
8241 (t1
->t
& VT_BTYPE
) == VT_BYTE
)) {
8242 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
8247 /* compute maximum number of chars wanted */
8249 cstr_len
= cstr
->size
;
8251 cstr_len
= cstr
->size
/ sizeof(int);
8254 if (n
>= 0 && nb
> (n
- array_length
))
8255 nb
= n
- array_length
;
8258 warning("initializer-string for array is too long");
8259 /* in order to go faster for common case (char
8260 string in global variable, we handle it
8262 if (sec
&& tok
== TOK_STR
&& size1
== 1) {
8263 memcpy(sec
->data
+ c
+ array_length
, cstr
->data
, nb
);
8267 ch
= ((unsigned char *)cstr
->data
)[i
];
8269 ch
= ((int *)cstr
->data
)[i
];
8270 init_putv(t1
, sec
, c
+ (array_length
+ i
) * size1
,
8278 /* only add trailing zero if enough storage (no
8279 warning in this case since it is standard) */
8280 if (n
< 0 || array_length
< n
) {
8282 init_putv(t1
, sec
, c
+ (array_length
* size1
), 0, EXPR_VAL
);
8288 while (tok
!= '}') {
8289 decl_designator(type
, sec
, c
, &index
, NULL
, size_only
);
8290 if (n
>= 0 && index
>= n
)
8291 error("index too large");
8292 /* must put zero in holes (note that doing it that way
8293 ensures that it even works with designators) */
8294 if (!size_only
&& array_length
< index
) {
8295 init_putz(t1
, sec
, c
+ array_length
* size1
,
8296 (index
- array_length
) * size1
);
8299 if (index
> array_length
)
8300 array_length
= index
;
8301 /* special test for multi dimensional arrays (may not
8302 be strictly correct if designators are used at the
8304 if (index
>= n
&& no_oblock
)
8313 /* put zeros at the end */
8314 if (!size_only
&& n
>= 0 && array_length
< n
) {
8315 init_putz(t1
, sec
, c
+ array_length
* size1
,
8316 (n
- array_length
) * size1
);
8318 /* patch type size if needed */
8320 s
->c
= array_length
;
8321 } else if ((type
->t
& VT_BTYPE
) == VT_STRUCT
&&
8322 (sec
|| !first
|| tok
== '{')) {
8325 /* NOTE: the previous test is a specific case for automatic
8326 struct/union init */
8327 /* XXX: union needs only one init */
8329 /* XXX: this test is incorrect for local initializers
8330 beginning with ( without {. It would be much more difficult
8331 to do it correctly (ideally, the expression parser should
8332 be used in all cases) */
8338 while (tok
== '(') {
8342 if (!parse_btype(&type1
, &ad1
))
8344 type_decl(&type1
, &ad1
, &n
, TYPE_ABSTRACT
);
8346 if (!is_assignable_types(type
, &type1
))
8347 error("invalid type for cast");
8352 if (first
|| tok
== '{') {
8361 while (tok
!= '}') {
8362 decl_designator(type
, sec
, c
, NULL
, &f
, size_only
);
8364 if (!size_only
&& array_length
< index
) {
8365 init_putz(type
, sec
, c
+ array_length
,
8366 index
- array_length
);
8368 index
= index
+ type_size(&f
->type
, &align1
);
8369 if (index
> array_length
)
8370 array_length
= index
;
8372 if (no_oblock
&& f
== NULL
)
8378 /* put zeros at the end */
8379 if (!size_only
&& array_length
< n
) {
8380 init_putz(type
, sec
, c
+ array_length
,
8389 } else if (tok
== '{') {
8391 decl_initializer(type
, sec
, c
, first
, size_only
);
8393 } else if (size_only
) {
8394 /* just skip expression */
8396 while ((parlevel
> 0 || (tok
!= '}' && tok
!= ',')) &&
8400 else if (tok
== ')')
8405 /* currently, we always use constant expression for globals
8406 (may change for scripting case) */
8407 expr_type
= EXPR_CONST
;
8409 expr_type
= EXPR_ANY
;
8410 init_putv(type
, sec
, c
, 0, expr_type
);
8414 /* parse an initializer for type 't' if 'has_init' is non zero, and
8415 allocate space in local or global data space ('r' is either
8416 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
8417 variable 'v' of scope 'scope' is declared before initializers are
8418 parsed. If 'v' is zero, then a reference to the new object is put
8419 in the value stack. If 'has_init' is 2, a special parsing is done
8420 to handle string constants. */
8421 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
8422 int has_init
, int v
, int scope
)
8424 int size
, align
, addr
, data_offset
;
8426 ParseState saved_parse_state
;
8427 TokenString init_str
;
8430 size
= type_size(type
, &align
);
8431 /* If unknown size, we must evaluate it before
8432 evaluating initializers because
8433 initializers can generate global data too
8434 (e.g. string pointers or ISOC99 compound
8435 literals). It also simplifies local
8436 initializers handling */
8437 tok_str_new(&init_str
);
8440 error("unknown type size");
8441 /* get all init string */
8442 if (has_init
== 2) {
8443 /* only get strings */
8444 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
8445 tok_str_add_tok(&init_str
);
8450 while (level
> 0 || (tok
!= ',' && tok
!= ';')) {
8452 error("unexpected end of file in initializer");
8453 tok_str_add_tok(&init_str
);
8456 else if (tok
== '}') {
8464 tok_str_add(&init_str
, -1);
8465 tok_str_add(&init_str
, 0);
8468 save_parse_state(&saved_parse_state
);
8470 macro_ptr
= init_str
.str
;
8472 decl_initializer(type
, NULL
, 0, 1, 1);
8473 /* prepare second initializer parsing */
8474 macro_ptr
= init_str
.str
;
8477 /* if still unknown size, error */
8478 size
= type_size(type
, &align
);
8480 error("unknown type size");
8482 /* take into account specified alignment if bigger */
8483 if (ad
->aligned
> align
)
8484 align
= ad
->aligned
;
8485 if ((r
& VT_VALMASK
) == VT_LOCAL
) {
8487 if (do_bounds_check
&& (type
->t
& VT_ARRAY
))
8489 loc
= (loc
- size
) & -align
;
8491 /* handles bounds */
8492 /* XXX: currently, since we do only one pass, we cannot track
8493 '&' operators, so we add only arrays */
8494 if (do_bounds_check
&& (type
->t
& VT_ARRAY
)) {
8495 unsigned long *bounds_ptr
;
8496 /* add padding between regions */
8498 /* then add local bound info */
8499 bounds_ptr
= section_ptr_add(lbounds_section
, 2 * sizeof(unsigned long));
8500 bounds_ptr
[0] = addr
;
8501 bounds_ptr
[1] = size
;
8504 /* local variable */
8505 sym_push(v
, type
, r
, addr
);
8507 /* push local reference */
8508 vset(type
, r
, addr
);
8514 if (v
&& scope
== VT_CONST
) {
8515 /* see if the symbol was already defined */
8518 if (!is_compatible_types(&sym
->type
, type
))
8519 error("incompatible types for redefinition of '%s'",
8520 get_tok_str(v
, NULL
));
8521 if (sym
->type
.t
& VT_EXTERN
) {
8522 /* if the variable is extern, it was not allocated */
8523 sym
->type
.t
&= ~VT_EXTERN
;
8524 /* set array size if it was ommited in extern
8526 if ((sym
->type
.t
& VT_ARRAY
) &&
8527 sym
->type
.ref
->c
< 0 &&
8529 sym
->type
.ref
->c
= type
->ref
->c
;
8531 /* we accept several definitions of the same
8532 global variable. this is tricky, because we
8533 must play with the SHN_COMMON type of the symbol */
8534 /* XXX: should check if the variable was already
8535 initialized. It is incorrect to initialized it
8537 /* no init data, we won't add more to the symbol */
8544 /* allocate symbol in corresponding section */
8549 else if (tcc_state
->nocommon
)
8553 data_offset
= sec
->data_offset
;
8554 data_offset
= (data_offset
+ align
- 1) & -align
;
8556 /* very important to increment global pointer at this time
8557 because initializers themselves can create new initializers */
8558 data_offset
+= size
;
8559 /* add padding if bound check */
8560 if (do_bounds_check
)
8562 sec
->data_offset
= data_offset
;
8563 /* allocate section space to put the data */
8564 if (sec
->sh_type
!= SHT_NOBITS
&&
8565 data_offset
> sec
->data_allocated
)
8566 section_realloc(sec
, data_offset
);
8567 /* align section if needed */
8568 if (align
> sec
->sh_addralign
)
8569 sec
->sh_addralign
= align
;
8571 addr
= 0; /* avoid warning */
8575 if (scope
== VT_CONST
) {
8580 sym
= sym_push(v
, type
, r
| VT_SYM
, 0);
8582 /* update symbol definition */
8584 put_extern_sym(sym
, sec
, addr
, size
);
8587 /* put a common area */
8588 put_extern_sym(sym
, NULL
, align
, size
);
8589 /* XXX: find a nicer way */
8590 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
8591 esym
->st_shndx
= SHN_COMMON
;
8596 /* push global reference */
8597 sym
= get_sym_ref(type
, sec
, addr
, size
);
8599 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
8603 /* handles bounds now because the symbol must be defined
8604 before for the relocation */
8605 if (do_bounds_check
) {
8606 unsigned long *bounds_ptr
;
8608 greloc(bounds_section
, sym
, bounds_section
->data_offset
, R_DATA_32
);
8609 /* then add global bound info */
8610 bounds_ptr
= section_ptr_add(bounds_section
, 2 * sizeof(long));
8611 bounds_ptr
[0] = 0; /* relocated */
8612 bounds_ptr
[1] = size
;
8616 decl_initializer(type
, sec
, addr
, 1, 0);
8617 /* restore parse state if needed */
8619 tok_str_free(init_str
.str
);
8620 restore_parse_state(&saved_parse_state
);
8626 void put_func_debug(Sym
*sym
)
8631 /* XXX: we put here a dummy type */
8632 snprintf(buf
, sizeof(buf
), "%s:%c1",
8633 funcname
, sym
->type
.t
& VT_STATIC
? 'f' : 'F');
8634 put_stabs_r(buf
, N_FUN
, 0, file
->line_num
, 0,
8635 cur_text_section
, sym
->c
);
8640 /* parse an old style function declaration list */
8641 /* XXX: check multiple parameter */
8642 static void func_decl_list(Sym
*func_sym
)
8649 /* parse each declaration */
8650 while (tok
!= '{' && tok
!= ';' && tok
!= ',' && tok
!= TOK_EOF
) {
8651 if (!parse_btype(&btype
, &ad
))
8652 expect("declaration list");
8653 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
8654 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
8656 /* we accept no variable after */
8660 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
8661 /* find parameter in function parameter list */
8664 if ((s
->v
& ~SYM_FIELD
) == v
)
8668 error("declaration for parameter '%s' but no such parameter",
8669 get_tok_str(v
, NULL
));
8671 /* check that no storage specifier except 'register' was given */
8672 if (type
.t
& VT_STORAGE
)
8673 error("storage class specified for '%s'", get_tok_str(v
, NULL
));
8674 convert_parameter_type(&type
);
8675 /* we can add the type (NOTE: it could be local to the function) */
8677 /* accept other parameters */
8688 /* parse a function defined by symbol 'sym' and generate its code in
8689 'cur_text_section' */
8690 static void gen_function(Sym
*sym
)
8692 ind
= cur_text_section
->data_offset
;
8693 /* NOTE: we patch the symbol size later */
8694 put_extern_sym(sym
, cur_text_section
, ind
, 0);
8695 funcname
= get_tok_str(sym
->v
, NULL
);
8697 /* put debug symbol */
8699 put_func_debug(sym
);
8700 /* push a dummy symbol to enable local sym storage */
8701 sym_push2(&local_stack
, SYM_FIELD
, 0, 0);
8702 gfunc_prolog(&sym
->type
);
8704 block(NULL
, NULL
, NULL
, NULL
, 0, 0);
8707 cur_text_section
->data_offset
= ind
;
8708 label_pop(&global_label_stack
, NULL
);
8709 sym_pop(&local_stack
, NULL
); /* reset local stack */
8710 /* end of function */
8711 /* patch symbol size */
8712 ((Elf32_Sym
*)symtab_section
->data
)[sym
->c
].st_size
=
8715 put_stabn(N_FUN
, 0, 0, ind
- func_ind
);
8717 funcname
= ""; /* for safety */
8718 func_vt
.t
= VT_VOID
; /* for safety */
8719 ind
= 0; /* for safety */
8722 static void gen_inline_functions(void)
8726 int *str
, inline_generated
;
8728 /* iterate while inline function are referenced */
8730 inline_generated
= 0;
8731 for(sym
= global_stack
; sym
!= NULL
; sym
= sym
->prev
) {
8733 if (((type
->t
& VT_BTYPE
) == VT_FUNC
) &&
8734 (type
->t
& (VT_STATIC
| VT_INLINE
)) ==
8735 (VT_STATIC
| VT_INLINE
) &&
8737 /* the function was used: generate its code and
8738 convert it to a normal function */
8739 str
= (int *)sym
->r
;
8740 sym
->r
= VT_SYM
| VT_CONST
;
8741 type
->t
&= ~VT_INLINE
;
8745 cur_text_section
= text_section
;
8747 macro_ptr
= NULL
; /* fail safe */
8750 inline_generated
= 1;
8753 if (!inline_generated
)
8757 /* free all remaining inline function tokens */
8758 for(sym
= global_stack
; sym
!= NULL
; sym
= sym
->prev
) {
8760 if (((type
->t
& VT_BTYPE
) == VT_FUNC
) &&
8761 (type
->t
& (VT_STATIC
| VT_INLINE
)) ==
8762 (VT_STATIC
| VT_INLINE
)) {
8763 str
= (int *)sym
->r
;
8765 sym
->r
= 0; /* fail safe */
8770 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
8771 static void decl(int l
)
8779 if (!parse_btype(&btype
, &ad
)) {
8780 /* skip redundant ';' */
8781 /* XXX: find more elegant solution */
8786 if (l
== VT_CONST
&&
8787 (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
)) {
8788 /* global asm block */
8792 /* special test for old K&R protos without explicit int
8793 type. Only accepted when defining global data */
8794 if (l
== VT_LOCAL
|| tok
< TOK_DEFINE
)
8798 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
8799 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
8801 /* we accept no variable after */
8805 while (1) { /* iterate thru each declaration */
8807 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
8811 type_to_str(buf
, sizeof(buf
), t
, get_tok_str(v
, NULL
));
8812 printf("type = '%s'\n", buf
);
8815 if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
8816 /* if old style function prototype, we accept a
8819 if (sym
->c
== FUNC_OLD
)
8820 func_decl_list(sym
);
8825 error("cannot use local functions");
8826 if (!(type
.t
& VT_FUNC
))
8827 expect("function definition");
8829 /* reject abstract declarators in function definition */
8831 while ((sym
= sym
->next
) != NULL
)
8832 if (!(sym
->v
& ~SYM_FIELD
))
8833 expect("identifier");
8835 /* XXX: cannot do better now: convert extern line to static inline */
8836 if ((type
.t
& (VT_EXTERN
| VT_INLINE
)) == (VT_EXTERN
| VT_INLINE
))
8837 type
.t
= (type
.t
& ~VT_EXTERN
) | VT_STATIC
;
8841 if ((sym
->type
.t
& VT_BTYPE
) != VT_FUNC
)
8843 /* specific case: if not func_call defined, we put
8844 the one of the prototype */
8845 /* XXX: should have default value */
8846 if (sym
->type
.ref
->r
!= FUNC_CDECL
&&
8847 type
.ref
->r
== FUNC_CDECL
)
8848 type
.ref
->r
= sym
->type
.ref
->r
;
8849 if (!is_compatible_types(&sym
->type
, &type
)) {
8851 error("incompatible types for redefinition of '%s'",
8852 get_tok_str(v
, NULL
));
8854 /* if symbol is already defined, then put complete type */
8857 /* put function symbol */
8858 sym
= global_identifier_push(v
, type
.t
, 0);
8859 sym
->type
.ref
= type
.ref
;
8862 /* static inline functions are just recorded as a kind
8863 of macro. Their code will be emitted at the end of
8864 the compilation unit only if they are used */
8865 if ((type
.t
& (VT_INLINE
| VT_STATIC
)) ==
8866 (VT_INLINE
| VT_STATIC
)) {
8867 TokenString func_str
;
8870 tok_str_new(&func_str
);
8876 error("unexpected end of file");
8877 tok_str_add_tok(&func_str
);
8882 } else if (t
== '}') {
8884 if (block_level
== 0)
8888 tok_str_add(&func_str
, -1);
8889 tok_str_add(&func_str
, 0);
8890 sym
->r
= (int)func_str
.str
;
8892 /* compute text section */
8893 cur_text_section
= ad
.section
;
8894 if (!cur_text_section
)
8895 cur_text_section
= text_section
;
8896 sym
->r
= VT_SYM
| VT_CONST
;
8901 if (btype
.t
& VT_TYPEDEF
) {
8902 /* save typedefed type */
8903 /* XXX: test storage specifiers ? */
8904 sym
= sym_push(v
, &type
, 0, 0);
8905 sym
->type
.t
|= VT_TYPEDEF
;
8906 } else if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
8907 /* external function definition */
8908 /* specific case for func_call attribute */
8910 type
.ref
->r
= ad
.func_call
;
8911 external_sym(v
, &type
, 0);
8913 /* not lvalue if array */
8915 if (!(type
.t
& VT_ARRAY
))
8916 r
|= lvalue_type(type
.t
);
8917 has_init
= (tok
== '=');
8918 if ((btype
.t
& VT_EXTERN
) ||
8919 ((type
.t
& VT_ARRAY
) && (type
.t
& VT_STATIC
) &&
8920 !has_init
&& l
== VT_CONST
&& type
.ref
->c
< 0)) {
8921 /* external variable */
8922 /* NOTE: as GCC, uninitialized global static
8923 arrays of null size are considered as
8925 external_sym(v
, &type
, r
);
8927 if (type
.t
& VT_STATIC
)
8933 decl_initializer_alloc(&type
, &ad
, r
,
8947 /* better than nothing, but needs extension to handle '-E' option
8949 static void preprocess_init(TCCState
*s1
)
8951 s1
->include_stack_ptr
= s1
->include_stack
;
8952 /* XXX: move that before to avoid having to initialize
8953 file->ifdef_stack_ptr ? */
8954 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
8955 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
8957 /* XXX: not ANSI compliant: bound checking says error */
8961 /* compile the C file opened in 'file'. Return non zero if errors. */
8962 static int tcc_compile(TCCState
*s1
)
8966 volatile int section_sym
;
8969 printf("%s: **** new file\n", file
->filename
);
8971 preprocess_init(s1
);
8974 anon_sym
= SYM_FIRST_ANOM
;
8976 /* file info: full path + filename */
8977 section_sym
= 0; /* avoid warning */
8979 section_sym
= put_elf_sym(symtab_section
, 0, 0,
8980 ELF32_ST_INFO(STB_LOCAL
, STT_SECTION
), 0,
8981 text_section
->sh_num
, NULL
);
8982 getcwd(buf
, sizeof(buf
));
8983 pstrcat(buf
, sizeof(buf
), "/");
8984 put_stabs_r(buf
, N_SO
, 0, 0,
8985 text_section
->data_offset
, text_section
, section_sym
);
8986 put_stabs_r(file
->filename
, N_SO
, 0, 0,
8987 text_section
->data_offset
, text_section
, section_sym
);
8989 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
8990 symbols can be safely used */
8991 put_elf_sym(symtab_section
, 0, 0,
8992 ELF32_ST_INFO(STB_LOCAL
, STT_FILE
), 0,
8993 SHN_ABS
, file
->filename
);
8995 /* define some often used types */
8996 int_type
.t
= VT_INT
;
8998 char_pointer_type
.t
= VT_BYTE
;
8999 mk_pointer(&char_pointer_type
);
9001 func_old_type
.t
= VT_FUNC
;
9002 func_old_type
.ref
= sym_push(SYM_FIELD
, &int_type
, FUNC_CDECL
, FUNC_OLD
);
9005 /* define 'void *alloca(unsigned int)' builtin function */
9010 sym
= sym_push(p
, mk_pointer(VT_VOID
), FUNC_CDECL
, FUNC_NEW
);
9011 s1
= sym_push(SYM_FIELD
, VT_UNSIGNED
| VT_INT
, 0, 0);
9014 sym_push(TOK_alloca
, VT_FUNC
| (p
<< VT_STRUCT_SHIFT
), VT_CONST
, 0);
9018 define_start
= define_stack
;
9020 if (setjmp(s1
->error_jmp_buf
) == 0) {
9022 s1
->error_set_jmp_enabled
= 1;
9024 ch
= file
->buf_ptr
[0];
9025 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
9026 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
;
9030 expect("declaration");
9032 /* end of translation unit info */
9034 put_stabs_r(NULL
, N_SO
, 0, 0,
9035 text_section
->data_offset
, text_section
, section_sym
);
9038 s1
->error_set_jmp_enabled
= 0;
9040 /* reset define stack, but leave -Dsymbols (may be incorrect if
9041 they are undefined) */
9042 free_defines(define_start
);
9044 gen_inline_functions();
9046 sym_pop(&global_stack
, NULL
);
9048 return s1
->nb_errors
!= 0 ? -1 : 0;
9052 int tcc_compile_string(TCCState
*s
, const char *str
)
9054 BufferedFile bf1
, *bf
= &bf1
;
9058 /* init file structure */
9060 /* XXX: avoid copying */
9062 buf
= tcc_malloc(len
+ 1);
9065 memcpy(buf
, str
, len
);
9068 bf
->buf_end
= buf
+ len
;
9069 pstrcpy(bf
->filename
, sizeof(bf
->filename
), "<string>");
9073 ret
= tcc_compile(s
);
9077 /* currently, no need to close */
9082 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
9083 void tcc_define_symbol(TCCState
*s1
, const char *sym
, const char *value
)
9085 BufferedFile bf1
, *bf
= &bf1
;
9087 pstrcpy(bf
->buffer
, IO_BUF_SIZE
, sym
);
9088 pstrcat(bf
->buffer
, IO_BUF_SIZE
, " ");
9092 pstrcat(bf
->buffer
, IO_BUF_SIZE
, value
);
9094 /* init file structure */
9096 bf
->buf_ptr
= bf
->buffer
;
9097 bf
->buf_end
= bf
->buffer
+ strlen(bf
->buffer
);
9098 *bf
->buf_end
= CH_EOB
;
9099 bf
->filename
[0] = '\0';
9103 s1
->include_stack_ptr
= s1
->include_stack
;
9105 /* parse with define parser */
9106 ch
= file
->buf_ptr
[0];
9112 /* undefine a preprocessor symbol */
9113 void tcc_undefine_symbol(TCCState
*s1
, const char *sym
)
9117 ts
= tok_alloc(sym
, strlen(sym
));
9118 s
= define_find(ts
->tok
);
9119 /* undefine symbol by putting an invalid name */
9124 #ifdef CONFIG_TCC_ASM
9126 #ifdef TCC_TARGET_I386
9127 #include "i386-asm.c"
9132 static void asm_instr(void)
9134 error("inline asm() not supported");
9136 static void asm_global_instr(void)
9138 error("inline asm() not supported");
9144 #ifdef TCC_TARGET_COFF
9145 #include "tcccoff.c"
9148 /* print the position in the source file of PC value 'pc' by reading
9149 the stabs debug information */
9150 static void rt_printline(unsigned long wanted_pc
)
9152 Stab_Sym
*sym
, *sym_end
;
9153 char func_name
[128], last_func_name
[128];
9154 unsigned long func_addr
, last_pc
, pc
;
9155 const char *incl_files
[INCLUDE_STACK_SIZE
];
9156 int incl_index
, len
, last_line_num
, i
;
9157 const char *str
, *p
;
9159 fprintf(stderr
, "0x%08lx:", wanted_pc
);
9161 func_name
[0] = '\0';
9164 last_func_name
[0] = '\0';
9165 last_pc
= 0xffffffff;
9167 sym
= (Stab_Sym
*)stab_section
->data
+ 1;
9168 sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
9169 while (sym
< sym_end
) {
9170 switch(sym
->n_type
) {
9171 /* function start or end */
9173 if (sym
->n_strx
== 0) {
9174 /* we test if between last line and end of function */
9175 pc
= sym
->n_value
+ func_addr
;
9176 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
9178 func_name
[0] = '\0';
9181 str
= stabstr_section
->data
+ sym
->n_strx
;
9182 p
= strchr(str
, ':');
9184 pstrcpy(func_name
, sizeof(func_name
), str
);
9187 if (len
> sizeof(func_name
) - 1)
9188 len
= sizeof(func_name
) - 1;
9189 memcpy(func_name
, str
, len
);
9190 func_name
[len
] = '\0';
9192 func_addr
= sym
->n_value
;
9195 /* line number info */
9197 pc
= sym
->n_value
+ func_addr
;
9198 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
9201 last_line_num
= sym
->n_desc
;
9203 strcpy(last_func_name
, func_name
);
9207 str
= stabstr_section
->data
+ sym
->n_strx
;
9209 if (incl_index
< INCLUDE_STACK_SIZE
) {
9210 incl_files
[incl_index
++] = str
;
9218 if (sym
->n_strx
== 0) {
9219 incl_index
= 0; /* end of translation unit */
9221 str
= stabstr_section
->data
+ sym
->n_strx
;
9222 /* do not add path */
9224 if (len
> 0 && str
[len
- 1] != '/')
9232 /* second pass: we try symtab symbols (no line number info) */
9235 Elf32_Sym
*sym
, *sym_end
;
9238 sym_end
= (Elf32_Sym
*)(symtab_section
->data
+ symtab_section
->data_offset
);
9239 for(sym
= (Elf32_Sym
*)symtab_section
->data
+ 1;
9242 type
= ELF32_ST_TYPE(sym
->st_info
);
9243 if (type
== STT_FUNC
) {
9244 if (wanted_pc
>= sym
->st_value
&&
9245 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
9246 pstrcpy(last_func_name
, sizeof(last_func_name
),
9247 strtab_section
->data
+ sym
->st_name
);
9253 /* did not find any info: */
9254 fprintf(stderr
, " ???\n");
9257 if (last_func_name
[0] != '\0') {
9258 fprintf(stderr
, " %s()", last_func_name
);
9260 if (incl_index
> 0) {
9261 fprintf(stderr
, " (%s:%d",
9262 incl_files
[incl_index
- 1], last_line_num
);
9263 for(i
= incl_index
- 2; i
>= 0; i
--)
9264 fprintf(stderr
, ", included from %s", incl_files
[i
]);
9265 fprintf(stderr
, ")");
9267 fprintf(stderr
, "\n");
9270 #if !defined(WIN32) && !defined(CONFIG_TCCBOOT)
9274 /* fix for glibc 2.1 */
9280 /* return the PC at frame level 'level'. Return non zero if not found */
9281 static int rt_get_caller_pc(unsigned long *paddr
,
9282 ucontext_t
*uc
, int level
)
9288 #if defined(__FreeBSD__)
9289 *paddr
= uc
->uc_mcontext
.mc_eip
;
9290 #elif defined(__dietlibc__)
9291 *paddr
= uc
->uc_mcontext
.eip
;
9293 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
9297 #if defined(__FreeBSD__)
9298 fp
= uc
->uc_mcontext
.mc_ebp
;
9299 #elif defined(__dietlibc__)
9300 fp
= uc
->uc_mcontext
.ebp
;
9302 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
9304 for(i
=1;i
<level
;i
++) {
9305 /* XXX: check address validity with program info */
9306 if (fp
<= 0x1000 || fp
>= 0xc0000000)
9308 fp
= ((unsigned long *)fp
)[0];
9310 *paddr
= ((unsigned long *)fp
)[1];
9316 #warning add arch specific rt_get_caller_pc()
9318 static int rt_get_caller_pc(unsigned long *paddr
,
9319 ucontext_t
*uc
, int level
)
9325 /* emit a run time error at position 'pc' */
9326 void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
9333 fprintf(stderr
, "Runtime error: ");
9334 vfprintf(stderr
, fmt
, ap
);
9335 fprintf(stderr
, "\n");
9336 for(i
=0;i
<num_callers
;i
++) {
9337 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
9340 fprintf(stderr
, "at ");
9342 fprintf(stderr
, "by ");
9349 /* signal handler for fatal errors */
9350 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
9352 ucontext_t
*uc
= puc
;
9356 switch(siginf
->si_code
) {
9359 rt_error(uc
, "division by zero");
9362 rt_error(uc
, "floating point exception");
9368 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
9369 rt_error(uc
, *rt_bound_error_msg
);
9371 rt_error(uc
, "dereferencing invalid pointer");
9374 rt_error(uc
, "illegal instruction");
9377 rt_error(uc
, "abort() called");
9380 rt_error(uc
, "caught signal %d", signum
);
9387 /* do all relocations (needed before using tcc_get_symbol()) */
9388 int tcc_relocate(TCCState
*s1
)
9395 tcc_add_runtime(s1
);
9397 build_got_entries(s1
);
9399 relocate_common_syms();
9401 /* compute relocation address : section are relocated in place. We
9402 also alloc the bss space */
9403 for(i
= 1; i
< s1
->nb_sections
; i
++) {
9404 s
= s1
->sections
[i
];
9405 if (s
->sh_flags
& SHF_ALLOC
) {
9406 if (s
->sh_type
== SHT_NOBITS
)
9407 s
->data
= tcc_mallocz(s
->data_offset
);
9408 s
->sh_addr
= (unsigned long)s
->data
;
9412 relocate_syms(s1
, 1);
9414 if (s1
->nb_errors
!= 0)
9417 /* relocate each section */
9418 for(i
= 1; i
< s1
->nb_sections
; i
++) {
9419 s
= s1
->sections
[i
];
9421 relocate_section(s1
, s
);
9426 /* launch the compiled program with the given arguments */
9427 int tcc_run(TCCState
*s1
, int argc
, char **argv
)
9429 int (*prog_main
)(int, char **);
9431 if (tcc_relocate(s1
) < 0)
9434 prog_main
= tcc_get_symbol_err(s1
, "main");
9437 #if defined(WIN32) || defined(CONFIG_TCCBOOT)
9438 error("debug mode currently not available for Windows");
9440 struct sigaction sigact
;
9441 /* install TCC signal handlers to print debug info on fatal
9443 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
9444 sigact
.sa_sigaction
= sig_error
;
9445 sigemptyset(&sigact
.sa_mask
);
9446 sigaction(SIGFPE
, &sigact
, NULL
);
9447 sigaction(SIGILL
, &sigact
, NULL
);
9448 sigaction(SIGSEGV
, &sigact
, NULL
);
9449 sigaction(SIGBUS
, &sigact
, NULL
);
9450 sigaction(SIGABRT
, &sigact
, NULL
);
9454 #ifdef CONFIG_TCC_BCHECK
9455 if (do_bounds_check
) {
9456 void (*bound_init
)(void);
9458 /* set error function */
9459 rt_bound_error_msg
= (void *)tcc_get_symbol_err(s1
,
9460 "__bound_error_msg");
9462 /* XXX: use .init section so that it also work in binary ? */
9463 bound_init
= (void *)tcc_get_symbol_err(s1
, "__bound_init");
9467 return (*prog_main
)(argc
, argv
);
9470 TCCState
*tcc_new(void)
9477 s
= tcc_mallocz(sizeof(TCCState
));
9481 s
->output_type
= TCC_OUTPUT_MEMORY
;
9483 /* init isid table */
9485 isidnum_table
[i
] = isid(i
) || isnum(i
);
9487 /* add all tokens */
9489 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
9491 tok_ident
= TOK_IDENT
;
9500 ts
= tok_alloc(p
, r
- p
- 1);
9504 /* we add dummy defines for some special macros to speed up tests
9505 and to have working defined() */
9506 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
9507 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
9508 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
9509 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
9511 /* standard defines */
9512 tcc_define_symbol(s
, "__STDC__", NULL
);
9513 #if defined(TCC_TARGET_I386)
9514 tcc_define_symbol(s
, "__i386__", NULL
);
9516 #if defined(TCC_TARGET_ARM)
9517 tcc_define_symbol(s
, "__ARM_ARCH_4__", NULL
);
9518 tcc_define_symbol(s
, "__arm_elf__", NULL
);
9519 tcc_define_symbol(s
, "__arm_elf", NULL
);
9520 tcc_define_symbol(s
, "arm_elf", NULL
);
9521 tcc_define_symbol(s
, "__arm__", NULL
);
9522 tcc_define_symbol(s
, "__arm", NULL
);
9523 tcc_define_symbol(s
, "arm", NULL
);
9524 tcc_define_symbol(s
, "__APCS_32__", NULL
);
9527 tcc_define_symbol(s
, "__linux__", NULL
);
9528 tcc_define_symbol(s
, "linux", NULL
);
9530 /* tiny C specific defines */
9531 tcc_define_symbol(s
, "__TINYC__", NULL
);
9533 /* tiny C & gcc defines */
9534 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned int");
9535 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "int");
9536 tcc_define_symbol(s
, "__WCHAR_TYPE__", "int");
9538 /* default library paths */
9539 tcc_add_library_path(s
, "/usr/local/lib");
9540 tcc_add_library_path(s
, "/usr/lib");
9541 tcc_add_library_path(s
, "/lib");
9543 /* no section zero */
9544 dynarray_add((void ***)&s
->sections
, &s
->nb_sections
, NULL
);
9546 /* create standard sections */
9547 text_section
= new_section(s
, ".text", SHT_PROGBITS
, SHF_ALLOC
| SHF_EXECINSTR
);
9548 data_section
= new_section(s
, ".data", SHT_PROGBITS
, SHF_ALLOC
| SHF_WRITE
);
9549 bss_section
= new_section(s
, ".bss", SHT_NOBITS
, SHF_ALLOC
| SHF_WRITE
);
9551 /* symbols are always generated for linking stage */
9552 symtab_section
= new_symtab(s
, ".symtab", SHT_SYMTAB
, 0,
9554 ".hashtab", SHF_PRIVATE
);
9555 strtab_section
= symtab_section
->link
;
9557 /* private symbol table for dynamic symbols */
9558 s
->dynsymtab_section
= new_symtab(s
, ".dynsymtab", SHT_SYMTAB
, SHF_PRIVATE
,
9560 ".dynhashtab", SHF_PRIVATE
);
9561 s
->alacarte_link
= 1;
9563 #ifdef CHAR_IS_UNSIGNED
9564 s
->char_is_unsigned
= 1;
9569 void tcc_delete(TCCState
*s1
)
9573 /* free -D defines */
9577 n
= tok_ident
- TOK_IDENT
;
9578 for(i
= 0; i
< n
; i
++)
9579 tcc_free(table_ident
[i
]);
9580 tcc_free(table_ident
);
9582 /* free all sections */
9584 free_section(symtab_section
->hash
);
9586 free_section(s1
->dynsymtab_section
->hash
);
9587 free_section(s1
->dynsymtab_section
->link
);
9588 free_section(s1
->dynsymtab_section
);
9590 for(i
= 1; i
< s1
->nb_sections
; i
++)
9591 free_section(s1
->sections
[i
]);
9592 tcc_free(s1
->sections
);
9594 /* free loaded dlls array */
9595 for(i
= 0; i
< s1
->nb_loaded_dlls
; i
++)
9596 tcc_free(s1
->loaded_dlls
[i
]);
9597 tcc_free(s1
->loaded_dlls
);
9600 for(i
= 0; i
< s1
->nb_library_paths
; i
++)
9601 tcc_free(s1
->library_paths
[i
]);
9602 tcc_free(s1
->library_paths
);
9604 /* cached includes */
9605 for(i
= 0; i
< s1
->nb_cached_includes
; i
++)
9606 tcc_free(s1
->cached_includes
[i
]);
9607 tcc_free(s1
->cached_includes
);
9609 for(i
= 0; i
< s1
->nb_include_paths
; i
++)
9610 tcc_free(s1
->include_paths
[i
]);
9611 tcc_free(s1
->include_paths
);
9613 for(i
= 0; i
< s1
->nb_sysinclude_paths
; i
++)
9614 tcc_free(s1
->sysinclude_paths
[i
]);
9615 tcc_free(s1
->sysinclude_paths
);
9620 int tcc_add_include_path(TCCState
*s1
, const char *pathname
)
9624 pathname1
= tcc_strdup(pathname
);
9625 dynarray_add((void ***)&s1
->include_paths
, &s1
->nb_include_paths
, pathname1
);
9629 int tcc_add_sysinclude_path(TCCState
*s1
, const char *pathname
)
9633 pathname1
= tcc_strdup(pathname
);
9634 dynarray_add((void ***)&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
, pathname1
);
9638 static int tcc_add_file_internal(TCCState
*s1
, const char *filename
, int flags
)
9640 const char *ext
, *filename1
;
9643 BufferedFile
*saved_file
;
9645 /* find source file type with extension */
9646 filename1
= strrchr(filename
, '/');
9650 filename1
= filename
;
9651 ext
= strrchr(filename1
, '.');
9657 file
= tcc_open(s1
, filename
);
9659 if (flags
& AFF_PRINT_ERROR
) {
9660 error_noabort("file '%s' not found", filename
);
9666 if (!ext
|| !strcmp(ext
, "c")) {
9667 /* C file assumed */
9668 ret
= tcc_compile(s1
);
9670 #ifdef CONFIG_TCC_ASM
9671 if (!strcmp(ext
, "S")) {
9672 /* preprocessed assembler */
9673 ret
= tcc_assemble(s1
, 1);
9674 } else if (!strcmp(ext
, "s")) {
9675 /* non preprocessed assembler */
9676 ret
= tcc_assemble(s1
, 0);
9681 /* assume executable format: auto guess file type */
9682 ret
= read(fd
, &ehdr
, sizeof(ehdr
));
9683 lseek(fd
, 0, SEEK_SET
);
9685 error_noabort("could not read header");
9687 } else if (ret
!= sizeof(ehdr
)) {
9688 goto try_load_script
;
9691 if (ehdr
.e_ident
[0] == ELFMAG0
&&
9692 ehdr
.e_ident
[1] == ELFMAG1
&&
9693 ehdr
.e_ident
[2] == ELFMAG2
&&
9694 ehdr
.e_ident
[3] == ELFMAG3
) {
9695 file
->line_num
= 0; /* do not display line number if error */
9696 if (ehdr
.e_type
== ET_REL
) {
9697 ret
= tcc_load_object_file(s1
, fd
, 0);
9698 } else if (ehdr
.e_type
== ET_DYN
) {
9699 if (s1
->output_type
== TCC_OUTPUT_MEMORY
) {
9701 h
= dlopen(filename
, RTLD_GLOBAL
| RTLD_LAZY
);
9707 ret
= tcc_load_dll(s1
, fd
, filename
,
9708 (flags
& AFF_REFERENCED_DLL
) != 0);
9711 error_noabort("unrecognized ELF file");
9714 } else if (memcmp((char *)&ehdr
, ARMAG
, 8) == 0) {
9715 file
->line_num
= 0; /* do not display line number if error */
9716 ret
= tcc_load_archive(s1
, fd
);
9718 #ifdef TCC_TARGET_COFF
9719 if (*(uint16_t *)(&ehdr
) == COFF_C67_MAGIC
) {
9720 ret
= tcc_load_coff(s1
, fd
);
9724 /* as GNU ld, consider it is an ld script if not recognized */
9726 ret
= tcc_load_ldscript(s1
);
9728 error_noabort("unrecognized file type");
9743 int tcc_add_file(TCCState
*s
, const char *filename
)
9745 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
);
9748 int tcc_add_library_path(TCCState
*s
, const char *pathname
)
9752 pathname1
= tcc_strdup(pathname
);
9753 dynarray_add((void ***)&s
->library_paths
, &s
->nb_library_paths
, pathname1
);
9757 /* find and load a dll. Return non zero if not found */
9758 /* XXX: add '-rpath' option support ? */
9759 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
)
9764 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
9765 snprintf(buf
, sizeof(buf
), "%s/%s",
9766 s
->library_paths
[i
], filename
);
9767 if (tcc_add_file_internal(s
, buf
, flags
) == 0)
9773 /* the library name is the same as the argument of the '-l' option */
9774 int tcc_add_library(TCCState
*s
, const char *libraryname
)
9779 /* first we look for the dynamic library if not static linking */
9780 if (!s
->static_link
) {
9781 snprintf(buf
, sizeof(buf
), "lib%s.so", libraryname
);
9782 if (tcc_add_dll(s
, buf
, 0) == 0)
9786 /* then we look for the static library */
9787 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
9788 snprintf(buf
, sizeof(buf
), "%s/lib%s.a",
9789 s
->library_paths
[i
], libraryname
);
9790 if (tcc_add_file_internal(s
, buf
, 0) == 0)
9796 int tcc_add_symbol(TCCState
*s
, const char *name
, unsigned long val
)
9798 add_elf_sym(symtab_section
, val
, 0,
9799 ELF32_ST_INFO(STB_GLOBAL
, STT_NOTYPE
),
9804 int tcc_set_output_type(TCCState
*s
, int output_type
)
9808 s
->output_type
= output_type
;
9811 /* default include paths */
9812 /* XXX: reverse order needed if -isystem support */
9813 tcc_add_sysinclude_path(s
, "/usr/local/include");
9814 tcc_add_sysinclude_path(s
, "/usr/include");
9815 snprintf(buf
, sizeof(buf
), "%s/include", tcc_lib_path
);
9816 tcc_add_sysinclude_path(s
, buf
);
9819 /* if bound checking, then add corresponding sections */
9820 #ifdef CONFIG_TCC_BCHECK
9821 if (do_bounds_check
) {
9823 tcc_define_symbol(s
, "__BOUNDS_CHECKING_ON", NULL
);
9824 /* create bounds sections */
9825 bounds_section
= new_section(s
, ".bounds",
9826 SHT_PROGBITS
, SHF_ALLOC
);
9827 lbounds_section
= new_section(s
, ".lbounds",
9828 SHT_PROGBITS
, SHF_ALLOC
);
9832 if (s
->char_is_unsigned
) {
9833 tcc_define_symbol(s
, "__CHAR_UNSIGNED__", NULL
);
9836 /* add debug sections */
9839 stab_section
= new_section(s
, ".stab", SHT_PROGBITS
, 0);
9840 stab_section
->sh_entsize
= sizeof(Stab_Sym
);
9841 stabstr_section
= new_section(s
, ".stabstr", SHT_STRTAB
, 0);
9842 put_elf_str(stabstr_section
, "");
9843 stab_section
->link
= stabstr_section
;
9844 /* put first entry */
9845 put_stabs("", 0, 0, 0, 0);
9848 /* add libc crt1/crti objects */
9849 if ((output_type
== TCC_OUTPUT_EXE
|| output_type
== TCC_OUTPUT_DLL
) &&
9851 if (output_type
!= TCC_OUTPUT_DLL
)
9852 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crt1.o");
9853 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crti.o");
9858 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
9859 #define FD_INVERT 0x0002 /* invert value before storing */
9861 typedef struct FlagDef
{
9867 static const FlagDef warning_defs
[] = {
9868 { offsetof(TCCState
, warn_unsupported
), 0, "unsupported" },
9869 { offsetof(TCCState
, warn_write_strings
), 0, "write-strings" },
9870 { offsetof(TCCState
, warn_error
), 0, "error" },
9871 { offsetof(TCCState
, warn_implicit_function_declaration
), WD_ALL
,
9872 "implicit-function-declaration" },
9875 static int set_flag(TCCState
*s
, const FlagDef
*flags
, int nb_flags
,
9876 const char *name
, int value
)
9883 if (r
[0] == 'n' && r
[1] == 'o' && r
[2] == '-') {
9887 for(i
= 0, p
= flags
; i
< nb_flags
; i
++, p
++) {
9888 if (!strcmp(r
, p
->name
))
9893 if (p
->flags
& FD_INVERT
)
9895 *(int *)((uint8_t *)s
+ p
->offset
) = value
;
9900 /* set/reset a warning */
9901 int tcc_set_warning(TCCState
*s
, const char *warning_name
, int value
)
9906 if (!strcmp(warning_name
, "all")) {
9907 for(i
= 0, p
= warning_defs
; i
< countof(warning_defs
); i
++, p
++) {
9908 if (p
->flags
& WD_ALL
)
9909 *(int *)((uint8_t *)s
+ p
->offset
) = 1;
9913 return set_flag(s
, warning_defs
, countof(warning_defs
),
9914 warning_name
, value
);
9918 static const FlagDef flag_defs
[] = {
9919 { offsetof(TCCState
, char_is_unsigned
), 0, "unsigned-char" },
9920 { offsetof(TCCState
, char_is_unsigned
), FD_INVERT
, "signed-char" },
9921 { offsetof(TCCState
, nocommon
), FD_INVERT
, "common" },
9924 /* set/reset a flag */
9925 int tcc_set_flag(TCCState
*s
, const char *flag_name
, int value
)
9927 return set_flag(s
, flag_defs
, countof(flag_defs
),
9931 #if !defined(LIBTCC)
9933 /* extract the basename of a file */
9934 static const char *tcc_basename(const char *name
)
9937 p
= strrchr(name
, '/');
9940 p
= strrchr(name
, '\\');
9949 static int64_t getclock_us(void)
9954 return (tb
.time
* 1000LL + tb
.millitm
) * 1000LL;
9957 gettimeofday(&tv
, NULL
);
9958 return tv
.tv_sec
* 1000000LL + tv
.tv_usec
;
9964 printf("tcc version " TCC_VERSION
" - Tiny C Compiler - Copyright (C) 2001-2004 Fabrice Bellard\n"
9965 "usage: tcc [-v] [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"
9966 " [-Wwarn] [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-static]\n"
9967 " [infile1 infile2...] [-run infile args...]\n"
9969 "General options:\n"
9970 " -v display current version\n"
9971 " -c compile only - generate an object file\n"
9972 " -o outfile set output filename\n"
9973 " -Bdir set tcc internal library path\n"
9974 " -bench output compilation statistics\n"
9975 " -run run compiled source\n"
9976 " -fflag set or reset (with 'no-' prefix) 'flag' (see man page)\n"
9977 " -Wwarning set or reset (with 'no-' prefix) 'warning' (see man page)\n"
9978 " -w disable all warnings\n"
9979 "Preprocessor options:\n"
9980 " -Idir add include path 'dir'\n"
9981 " -Dsym[=val] define 'sym' with value 'val'\n"
9982 " -Usym undefine 'sym'\n"
9984 " -Ldir add library path 'dir'\n"
9985 " -llib link with dynamic or static library 'lib'\n"
9986 " -shared generate a shared library\n"
9987 " -static static linking\n"
9988 " -rdynamic export all global symbols to dynamic linker\n"
9989 " -r relocatable output\n"
9990 "Debugger options:\n"
9991 " -g generate runtime debug info\n"
9992 #ifdef CONFIG_TCC_BCHECK
9993 " -b compile with built-in memory and bounds checker (implies -g)\n"
9995 " -bt N show N callers in stack traces\n"
9999 #define TCC_OPTION_HAS_ARG 0x0001
10000 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
10002 typedef struct TCCOption
{
10030 TCC_OPTION_nostdinc
,
10031 TCC_OPTION_nostdlib
,
10032 TCC_OPTION_print_search_dirs
,
10033 TCC_OPTION_rdynamic
,
10039 static const TCCOption tcc_options
[] = {
10040 { "h", TCC_OPTION_HELP
, 0 },
10041 { "?", TCC_OPTION_HELP
, 0 },
10042 { "I", TCC_OPTION_I
, TCC_OPTION_HAS_ARG
},
10043 { "D", TCC_OPTION_D
, TCC_OPTION_HAS_ARG
},
10044 { "U", TCC_OPTION_U
, TCC_OPTION_HAS_ARG
},
10045 { "L", TCC_OPTION_L
, TCC_OPTION_HAS_ARG
},
10046 { "B", TCC_OPTION_B
, TCC_OPTION_HAS_ARG
},
10047 { "l", TCC_OPTION_l
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10048 { "bench", TCC_OPTION_bench
, 0 },
10049 { "bt", TCC_OPTION_bt
, TCC_OPTION_HAS_ARG
},
10050 #ifdef CONFIG_TCC_BCHECK
10051 { "b", TCC_OPTION_b
, 0 },
10053 { "g", TCC_OPTION_g
, 0 },
10054 { "c", TCC_OPTION_c
, 0 },
10055 { "static", TCC_OPTION_static
, 0 },
10056 { "shared", TCC_OPTION_shared
, 0 },
10057 { "o", TCC_OPTION_o
, TCC_OPTION_HAS_ARG
},
10058 { "run", TCC_OPTION_run
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10059 { "rdynamic", TCC_OPTION_rdynamic
, 0 },
10060 { "r", TCC_OPTION_r
, 0 },
10061 { "Wl,", TCC_OPTION_Wl
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10062 { "W", TCC_OPTION_W
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10063 { "O", TCC_OPTION_O
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10064 { "m", TCC_OPTION_m
, TCC_OPTION_HAS_ARG
},
10065 { "f", TCC_OPTION_f
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10066 { "nostdinc", TCC_OPTION_nostdinc
, 0 },
10067 { "nostdlib", TCC_OPTION_nostdlib
, 0 },
10068 { "print-search-dirs", TCC_OPTION_print_search_dirs
, 0 },
10069 { "v", TCC_OPTION_v
, 0 },
10070 { "w", TCC_OPTION_w
, 0 },
10074 /* convert 'str' into an array of space separated strings */
10075 static int expand_args(char ***pargv
, const char *str
)
10084 while (is_space(*str
))
10089 while (*str
!= '\0' && !is_space(*str
))
10092 arg
= tcc_malloc(len
+ 1);
10093 memcpy(arg
, s1
, len
);
10095 dynarray_add((void ***)&argv
, &argc
, arg
);
10101 static char **files
;
10102 static int nb_files
, nb_libraries
;
10103 static int multiple_files
;
10104 static int print_search_dirs
;
10105 static int output_type
;
10106 static int reloc_output
;
10107 static const char *outfile
;
10109 int parse_args(TCCState
*s
, int argc
, char **argv
)
10112 const TCCOption
*popt
;
10113 const char *optarg
, *p1
, *r1
;
10118 if (optind
>= argc
) {
10119 if (nb_files
== 0 && !print_search_dirs
)
10124 r
= argv
[optind
++];
10126 /* add a new file */
10127 dynarray_add((void ***)&files
, &nb_files
, r
);
10128 if (!multiple_files
) {
10130 /* argv[0] will be this file */
10134 /* find option in table (match only the first chars */
10135 popt
= tcc_options
;
10139 error("invalid option -- '%s'", r
);
10152 if (popt
->flags
& TCC_OPTION_HAS_ARG
) {
10153 if (*r1
!= '\0' || (popt
->flags
& TCC_OPTION_NOSEP
)) {
10156 if (optind
>= argc
)
10157 error("argument to '%s' is missing", r
);
10158 optarg
= argv
[optind
++];
10166 switch(popt
->index
) {
10167 case TCC_OPTION_HELP
:
10172 if (tcc_add_include_path(s
, optarg
) < 0)
10173 error("too many include paths");
10178 sym
= (char *)optarg
;
10179 value
= strchr(sym
, '=');
10184 tcc_define_symbol(s
, sym
, value
);
10188 tcc_undefine_symbol(s
, optarg
);
10191 tcc_add_library_path(s
, optarg
);
10194 /* set tcc utilities path (mainly for tcc development) */
10195 tcc_lib_path
= optarg
;
10198 dynarray_add((void ***)&files
, &nb_files
, r
);
10201 case TCC_OPTION_bench
:
10204 case TCC_OPTION_bt
:
10205 num_callers
= atoi(optarg
);
10207 #ifdef CONFIG_TCC_BCHECK
10209 do_bounds_check
= 1;
10217 multiple_files
= 1;
10218 output_type
= TCC_OUTPUT_OBJ
;
10220 case TCC_OPTION_static
:
10221 s
->static_link
= 1;
10223 case TCC_OPTION_shared
:
10224 output_type
= TCC_OUTPUT_DLL
;
10227 multiple_files
= 1;
10231 /* generate a .o merging several output files */
10233 output_type
= TCC_OUTPUT_OBJ
;
10235 case TCC_OPTION_nostdinc
:
10238 case TCC_OPTION_nostdlib
:
10241 case TCC_OPTION_print_search_dirs
:
10242 print_search_dirs
= 1;
10244 case TCC_OPTION_run
:
10248 argc1
= expand_args(&argv1
, optarg
);
10250 parse_args(s
, argc1
, argv1
);
10252 multiple_files
= 0;
10253 output_type
= TCC_OUTPUT_MEMORY
;
10257 printf("tcc version %s\n", TCC_VERSION
);
10260 if (tcc_set_flag(s
, optarg
, 1) < 0 && s
->warn_unsupported
)
10261 goto unsupported_option
;
10264 if (tcc_set_warning(s
, optarg
, 1) < 0 &&
10265 s
->warn_unsupported
)
10266 goto unsupported_option
;
10271 case TCC_OPTION_rdynamic
:
10274 case TCC_OPTION_Wl
:
10277 if (strstart(optarg
, "-Ttext,", &p
)) {
10278 s
->text_addr
= strtoul(p
, NULL
, 16);
10279 s
->has_text_addr
= 1;
10280 } else if (strstart(optarg
, "--oformat,", &p
)) {
10281 if (strstart(p
, "elf32-", NULL
)) {
10282 s
->output_format
= TCC_OUTPUT_FORMAT_ELF
;
10283 } else if (!strcmp(p
, "binary")) {
10284 s
->output_format
= TCC_OUTPUT_FORMAT_BINARY
;
10286 #ifdef TCC_TARGET_COFF
10287 if (!strcmp(p
, "coff")) {
10288 s
->output_format
= TCC_OUTPUT_FORMAT_COFF
;
10292 error("target %s not found", p
);
10295 error("unsupported linker option '%s'", optarg
);
10300 if (s
->warn_unsupported
) {
10301 unsupported_option
:
10302 warning("unsupported option '%s'", r
);
10311 int main(int argc
, char **argv
)
10315 int nb_objfiles
, ret
, optind
;
10316 char objfilename
[1024];
10317 int64_t start_time
= 0;
10320 output_type
= TCC_OUTPUT_EXE
;
10322 multiple_files
= 1;
10327 print_search_dirs
= 0;
10329 optind
= parse_args(s
, argc
- 1, argv
+ 1) + 1;
10331 if (print_search_dirs
) {
10332 /* enough for Linux kernel */
10333 printf("install: %s/\n", tcc_lib_path
);
10337 nb_objfiles
= nb_files
- nb_libraries
;
10339 /* if outfile provided without other options, we output an
10341 if (outfile
&& output_type
== TCC_OUTPUT_MEMORY
)
10342 output_type
= TCC_OUTPUT_EXE
;
10344 /* check -c consistency : only single file handled. XXX: checks file type */
10345 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
10346 /* accepts only a single input file */
10347 if (nb_objfiles
!= 1)
10348 error("cannot specify multiple files with -c");
10349 if (nb_libraries
!= 0)
10350 error("cannot specify libraries with -c");
10353 /* compute default outfile name */
10354 if (output_type
!= TCC_OUTPUT_MEMORY
&& !outfile
) {
10355 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
10358 pstrcpy(objfilename
, sizeof(objfilename
) - 1,
10359 tcc_basename(files
[0]));
10360 /* add .o extension */
10361 ext
= strrchr(objfilename
, '.');
10363 goto default_outfile
;
10364 strcpy(ext
+ 1, "o");
10367 pstrcpy(objfilename
, sizeof(objfilename
), "a.out");
10369 outfile
= objfilename
;
10373 start_time
= getclock_us();
10376 tcc_set_output_type(s
, output_type
);
10378 /* compile or add each files or library */
10379 for(i
= 0;i
< nb_files
; i
++) {
10380 const char *filename
;
10382 filename
= files
[i
];
10383 if (filename
[0] == '-') {
10384 if (tcc_add_library(s
, filename
+ 2) < 0)
10385 error("cannot find %s", filename
);
10387 if (tcc_add_file(s
, filename
) < 0) {
10394 /* free all files */
10399 total_time
= (double)(getclock_us() - start_time
) / 1000000.0;
10400 if (total_time
< 0.001)
10401 total_time
= 0.001;
10402 if (total_bytes
< 1)
10404 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
10405 tok_ident
- TOK_IDENT
, total_lines
, total_bytes
,
10406 total_time
, (int)(total_lines
/ total_time
),
10407 total_bytes
/ total_time
/ 1000000.0);
10410 if (s
->output_type
!= TCC_OUTPUT_MEMORY
) {
10411 tcc_output_file(s
, outfile
);
10414 ret
= tcc_run(s
, argc
- optind
, argv
+ optind
);
10417 /* XXX: cannot do it with bound checking because of the malloc hooks */
10418 if (!do_bounds_check
)
10423 printf("memory: %d bytes, max = %d bytes\n", mem_cur_size
, mem_max_size
);