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
42 #include <sys/timeb.h>
47 #include <sys/ucontext.h>
51 #endif /* !CONFIG_TCCBOOT */
68 /* preprocessor debug */
70 /* include file debug */
78 /* target selection */
79 //#define TCC_TARGET_I386 /* i386 code generator */
80 //#define TCC_TARGET_ARM /* ARMv4 code generator */
81 //#define TCC_TARGET_C67 /* TMS320C67xx code generator */
82 //#define TCC_TARGET_X86_64 /* x86-64 code generator */
84 /* default target is I386 */
85 #if !defined(TCC_TARGET_I386) && !defined(TCC_TARGET_ARM) && \
86 !defined(TCC_TARGET_C67) && !defined(TCC_TARGET_X86_64)
87 #define TCC_TARGET_I386
90 #if !defined(_WIN32) && !defined(TCC_UCLIBC) && !defined(TCC_TARGET_ARM) && \
91 !defined(TCC_TARGET_C67) && !defined(TCC_TARGET_X86_64)
92 #define CONFIG_TCC_BCHECK /* enable bound checking code */
95 #if defined(_WIN32) && !defined(TCC_TARGET_PE)
96 #define CONFIG_TCC_STATIC
99 /* define it to include assembler support */
100 #if !defined(TCC_TARGET_ARM) && !defined(TCC_TARGET_C67) && \
101 !defined(TCC_TARGET_X86_64)
102 #define CONFIG_TCC_ASM
105 /* object format selection */
106 #if defined(TCC_TARGET_C67)
107 #define TCC_TARGET_COFF
116 /* path to find crt1.o, crti.o and crtn.o. Only needed when generating
117 executables or dlls */
118 #define CONFIG_TCC_CRT_PREFIX CONFIG_SYSROOT "/usr/lib"
120 #define INCLUDE_STACK_SIZE 32
121 #define IFDEF_STACK_SIZE 64
122 #define VSTACK_SIZE 256
123 #define STRING_MAX_SIZE 1024
124 #define PACK_STACK_SIZE 8
126 #define TOK_HASH_SIZE 8192 /* must be a power of two */
127 #define TOK_ALLOC_INCR 512 /* must be a power of two */
128 #define TOK_MAX_SIZE 4 /* token max size in int unit when stored in string */
130 /* token symbol management */
131 typedef struct TokenSym
{
132 struct TokenSym
*hash_next
;
133 struct Sym
*sym_define
; /* direct pointer to define */
134 struct Sym
*sym_label
; /* direct pointer to label */
135 struct Sym
*sym_struct
; /* direct pointer to structure */
136 struct Sym
*sym_identifier
; /* direct pointer to identifier */
137 int tok
; /* token number */
143 typedef unsigned short nwchar_t
;
145 typedef int nwchar_t
;
148 typedef struct CString
{
149 int size
; /* size in bytes */
150 void *data
; /* either 'char *' or 'nwchar_t *' */
152 void *data_allocated
; /* if non NULL, data has been malloced */
155 /* type definition */
156 typedef struct CType
{
162 typedef union CValue
{
168 unsigned int ul
; /* address (should be unsigned long on 64 bit cpu) */
170 unsigned long long ull
;
171 struct CString
*cstr
;
177 typedef struct SValue
{
178 CType type
; /* type */
179 unsigned short r
; /* register + flags */
180 unsigned short r2
; /* second register, used for 'long long'
181 type. If not used, set to VT_CONST */
182 CValue c
; /* constant, if VT_CONST */
183 struct Sym
*sym
; /* symbol, if (VT_SYM | VT_CONST) */
186 /* symbol management */
188 int v
; /* symbol token */
189 long r
; /* associated register */
190 long c
; /* associated number */
191 CType type
; /* associated type */
192 struct Sym
*next
; /* next related symbol */
193 struct Sym
*prev
; /* prev symbol in stack */
194 struct Sym
*prev_tok
; /* previous symbol for this token */
197 /* section definition */
198 /* XXX: use directly ELF structure for parameters ? */
199 /* special flag to indicate that the section should not be linked to
201 #define SHF_PRIVATE 0x80000000
203 typedef struct Section
{
204 unsigned long data_offset
; /* current data offset */
205 unsigned char *data
; /* section data */
206 unsigned long data_allocated
; /* used for realloc() handling */
207 int sh_name
; /* elf section name (only used during output) */
208 int sh_num
; /* elf section number */
209 int sh_type
; /* elf section type */
210 int sh_flags
; /* elf section flags */
211 int sh_info
; /* elf section info */
212 int sh_addralign
; /* elf section alignment */
213 int sh_entsize
; /* elf entry size */
214 unsigned long sh_size
; /* section size (only used during output) */
215 unsigned long sh_addr
; /* address at which the section is relocated */
216 unsigned long sh_offset
; /* file offset */
217 int nb_hashed_syms
; /* used to resize the hash table */
218 struct Section
*link
; /* link to another section */
219 struct Section
*reloc
; /* corresponding section for relocation, if any */
220 struct Section
*hash
; /* hash table for symbols */
221 struct Section
*next
;
222 char name
[1]; /* section name */
225 typedef struct DLLReference
{
231 /* GNUC attribute definition */
232 typedef struct AttributeDef
{
236 int func_attr
; /* calling convention, exports, ... */
239 /* -------------------------------------------------- */
240 /* gr: wrappers for casting sym->r for other purposes */
248 #define FUNC_CALL(r) (((func_attr_t*)&(r))->func_call)
249 #define FUNC_EXPORT(r) (((func_attr_t*)&(r))->func_export)
250 #define FUNC_ARGS(r) (((func_attr_t*)&(r))->func_args)
251 #define INLINE_DEF(r) (*(int **)&(r))
252 /* -------------------------------------------------- */
254 #define SYM_STRUCT 0x40000000 /* struct/union/enum symbol space */
255 #define SYM_FIELD 0x20000000 /* struct/union field symbol space */
256 #define SYM_FIRST_ANOM 0x10000000 /* first anonymous sym */
258 /* stored in 'Sym.c' field */
259 #define FUNC_NEW 1 /* ansi function prototype */
260 #define FUNC_OLD 2 /* old function prototype */
261 #define FUNC_ELLIPSIS 3 /* ansi function prototype with ... */
263 /* stored in 'Sym.r' field */
264 #define FUNC_CDECL 0 /* standard c call */
265 #define FUNC_STDCALL 1 /* pascal c call */
266 #define FUNC_FASTCALL1 2 /* first param in %eax */
267 #define FUNC_FASTCALL2 3 /* first parameters in %eax, %edx */
268 #define FUNC_FASTCALL3 4 /* first parameter in %eax, %edx, %ecx */
269 #define FUNC_FASTCALLW 5 /* first parameter in %ecx, %edx */
271 /* field 'Sym.t' for macros */
272 #define MACRO_OBJ 0 /* object like macro */
273 #define MACRO_FUNC 1 /* function like macro */
275 /* field 'Sym.r' for C labels */
276 #define LABEL_DEFINED 0 /* label is defined */
277 #define LABEL_FORWARD 1 /* label is forward defined */
278 #define LABEL_DECLARED 2 /* label is declared but never used */
280 /* type_decl() types */
281 #define TYPE_ABSTRACT 1 /* type without variable */
282 #define TYPE_DIRECT 2 /* type with variable */
284 #define IO_BUF_SIZE 8192
286 typedef struct BufferedFile
{
290 int line_num
; /* current line number - here to simplify code */
291 int ifndef_macro
; /* #ifndef macro / #endif search */
292 int ifndef_macro_saved
; /* saved ifndef_macro */
293 int *ifdef_stack_ptr
; /* ifdef_stack value at the start of the file */
294 char inc_type
; /* type of include */
295 char inc_filename
[512]; /* filename specified by the user */
296 char filename
[1024]; /* current filename - here to simplify code */
297 unsigned char buffer
[IO_BUF_SIZE
+ 1]; /* extra size for CH_EOB char */
300 #define CH_EOB '\\' /* end of buffer or '\0' char in file */
301 #define CH_EOF (-1) /* end of file */
303 /* parsing state (used to save parser state to reparse part of the
304 source several times) */
305 typedef struct ParseState
{
312 /* used to record tokens */
313 typedef struct TokenString
{
320 /* include file cache, used to find files faster and also to eliminate
321 inclusion if the include file is protected by #ifndef ... #endif */
322 typedef struct CachedInclude
{
324 int hash_next
; /* -1 if none */
325 char type
; /* '"' or '>' to give include type */
326 char filename
[1]; /* path specified in #include */
329 #define CACHED_INCLUDES_HASH_SIZE 512
332 static struct BufferedFile
*file
;
335 static CString tokcstr
; /* current parsed string, if any */
336 /* additional informations about token */
337 static int tok_flags
;
338 #define TOK_FLAG_BOL 0x0001 /* beginning of line before */
339 #define TOK_FLAG_BOF 0x0002 /* beginning of file before */
340 #define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */
341 #define TOK_FLAG_EOF 0x0008 /* end of file */
343 static int *macro_ptr
, *macro_ptr_allocated
;
344 static int *unget_saved_macro_ptr
;
345 static int unget_saved_buffer
[TOK_MAX_SIZE
+ 1];
346 static int unget_buffer_enabled
;
347 static int parse_flags
;
348 #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
349 #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
350 #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
351 token. line feed is also
353 #define PARSE_FLAG_ASM_COMMENTS 0x0008 /* '#' can be used for line comment */
355 static Section
*text_section
, *data_section
, *bss_section
; /* predefined sections */
356 static Section
*cur_text_section
; /* current section where function code is
358 #ifdef CONFIG_TCC_ASM
359 static Section
*last_text_section
; /* to handle .previous asm directive */
361 /* bound check related sections */
362 static Section
*bounds_section
; /* contains global data bound description */
363 static Section
*lbounds_section
; /* contains local data bound description */
364 /* symbol sections */
365 static Section
*symtab_section
, *strtab_section
;
368 static Section
*stab_section
, *stabstr_section
;
370 /* loc : local variable index
371 ind : output code index
373 anon_sym: anonymous symbol index
375 static int rsym
, anon_sym
, ind
, loc
;
376 /* expression generation modifiers */
377 static int const_wanted
; /* true if constant wanted */
378 static int nocode_wanted
; /* true if no code generation wanted for an expression */
379 static int global_expr
; /* true if compound literals must be allocated
380 globally (used during initializers parsing */
381 static CType func_vt
; /* current function return type (used by return
384 static int last_line_num
, last_ind
, func_ind
; /* debug last line number and pc */
385 static int tok_ident
;
386 static TokenSym
**table_ident
;
387 static TokenSym
*hash_ident
[TOK_HASH_SIZE
];
388 static char token_buf
[STRING_MAX_SIZE
+ 1];
389 static char *funcname
;
390 static Sym
*global_stack
, *local_stack
;
391 static Sym
*define_stack
;
392 static Sym
*global_label_stack
, *local_label_stack
;
393 /* symbol allocator */
394 #define SYM_POOL_NB (8192 / sizeof(Sym))
395 static Sym
*sym_free_first
;
396 static void **sym_pools
;
397 static int nb_sym_pools
;
399 static SValue vstack
[VSTACK_SIZE
], *vtop
;
400 /* some predefined types */
401 static CType char_pointer_type
, func_old_type
, int_type
;
402 /* true if isid(c) || isnum(c) */
403 static unsigned char isidnum_table
[256-CH_EOF
];
405 /* display some information during compilation */
406 static int verbose
= 0;
408 /* compile with debug symbol (and use them if error during execution) */
409 static int do_debug
= 0;
411 /* compile with built-in memory and bounds checker */
412 static int do_bounds_check
= 0;
414 /* display benchmark infos */
416 static int do_bench
= 0;
418 static int total_lines
;
419 static int total_bytes
;
421 /* use GNU C extensions */
422 static int gnu_ext
= 1;
424 /* use Tiny C extensions */
425 static int tcc_ext
= 1;
427 /* max number of callers shown if error */
428 static int num_callers
= 6;
429 static const char **rt_bound_error_msg
;
431 /* XXX: get rid of this ASAP */
432 static struct TCCState
*tcc_state
;
434 /* give the path of the tcc libraries */
435 static const char *tcc_lib_path
= CONFIG_TCCDIR
;
440 BufferedFile
**include_stack_ptr
;
441 int *ifdef_stack_ptr
;
443 /* include file handling */
444 char **include_paths
;
445 int nb_include_paths
;
446 char **sysinclude_paths
;
447 int nb_sysinclude_paths
;
448 CachedInclude
**cached_includes
;
449 int nb_cached_includes
;
451 char **library_paths
;
452 int nb_library_paths
;
454 /* array of all loaded dlls (including those referenced by loaded
456 DLLReference
**loaded_dlls
;
461 int nb_sections
; /* number of sections, including first dummy section */
466 unsigned long *got_offsets
;
468 /* give the correspondance from symtab indexes to dynsym indexes */
469 int *symtab_to_dynsym
;
471 /* temporary dynamic symbol sections (for dll loading) */
472 Section
*dynsymtab_section
;
473 /* exported dynamic symbol section */
476 int nostdinc
; /* if true, no standard headers are added */
477 int nostdlib
; /* if true, no standard libraries are added */
479 int nocommon
; /* if true, do not use common symbols for .bss data */
481 /* if true, static linking is performed */
484 /* soname as specified on the command line (-soname) */
487 /* if true, all symbols are exported */
490 /* if true, only link in referenced objects from archive */
493 /* address of text section */
494 unsigned long text_addr
;
497 /* output format, see TCC_OUTPUT_FORMAT_xxx */
500 /* C language options */
501 int char_is_unsigned
;
502 int leading_underscore
;
504 /* warning switches */
505 int warn_write_strings
;
506 int warn_unsupported
;
509 int warn_implicit_function_declaration
;
513 void (*error_func
)(void *opaque
, const char *msg
);
514 int error_set_jmp_enabled
;
515 jmp_buf error_jmp_buf
;
518 /* tiny assembler state */
521 /* see include_stack_ptr */
522 BufferedFile
*include_stack
[INCLUDE_STACK_SIZE
];
524 /* see ifdef_stack_ptr */
525 int ifdef_stack
[IFDEF_STACK_SIZE
];
527 /* see cached_includes */
528 int cached_includes_hash
[CACHED_INCLUDES_HASH_SIZE
];
531 int pack_stack
[PACK_STACK_SIZE
];
534 /* output file for preprocessing */
537 #ifdef TCC_TARGET_X86_64
538 /* buffer to store jump tables */
544 /* The current value can be: */
545 #define VT_VALMASK 0x00ff
546 #define VT_CONST 0x00f0 /* constant in vc
547 (must be first non register value) */
548 #define VT_LLOCAL 0x00f1 /* lvalue, offset on stack */
549 #define VT_LOCAL 0x00f2 /* offset on stack */
550 #define VT_CMP 0x00f3 /* the value is stored in processor flags (in vc) */
551 #define VT_JMP 0x00f4 /* value is the consequence of jmp true (even) */
552 #define VT_JMPI 0x00f5 /* value is the consequence of jmp false (odd) */
553 #define VT_LVAL 0x0100 /* var is an lvalue */
554 #define VT_SYM 0x0200 /* a symbol value is added */
555 #define VT_MUSTCAST 0x0400 /* value must be casted to be correct (used for
556 char/short stored in integer registers) */
557 #define VT_MUSTBOUND 0x0800 /* bound checking must be done before
558 dereferencing value */
559 #define VT_BOUNDED 0x8000 /* value is bounded. The address of the
560 bounding function call point is in vc */
561 #define VT_LVAL_BYTE 0x1000 /* lvalue is a byte */
562 #define VT_LVAL_SHORT 0x2000 /* lvalue is a short */
563 #define VT_LVAL_UNSIGNED 0x4000 /* lvalue is unsigned */
564 #define VT_LVAL_TYPE (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
567 #define VT_INT 0 /* integer type */
568 #define VT_BYTE 1 /* signed byte type */
569 #define VT_SHORT 2 /* short type */
570 #define VT_VOID 3 /* void type */
571 #define VT_PTR 4 /* pointer */
572 #define VT_ENUM 5 /* enum definition */
573 #define VT_FUNC 6 /* function type */
574 #define VT_STRUCT 7 /* struct/union definition */
575 #define VT_FLOAT 8 /* IEEE float */
576 #define VT_DOUBLE 9 /* IEEE double */
577 #define VT_LDOUBLE 10 /* IEEE long double */
578 #define VT_BOOL 11 /* ISOC99 boolean type */
579 #define VT_LLONG 12 /* 64 bit integer */
580 #define VT_LONG 13 /* long integer (NEVER USED as type, only
582 #define VT_BTYPE 0x000f /* mask for basic type */
583 #define VT_UNSIGNED 0x0010 /* unsigned type */
584 #define VT_ARRAY 0x0020 /* array type (also has VT_PTR) */
585 #define VT_BITFIELD 0x0040 /* bitfield modifier */
586 #define VT_CONSTANT 0x0800 /* const modifier */
587 #define VT_VOLATILE 0x1000 /* volatile modifier */
588 #define VT_SIGNED 0x2000 /* signed type */
591 #define VT_EXTERN 0x00000080 /* extern definition */
592 #define VT_STATIC 0x00000100 /* static variable */
593 #define VT_TYPEDEF 0x00000200 /* typedef definition */
594 #define VT_INLINE 0x00000400 /* inline definition */
596 #define VT_STRUCT_SHIFT 16 /* shift for bitfield shift values */
598 /* type mask (except storage) */
599 #define VT_STORAGE (VT_EXTERN | VT_STATIC | VT_TYPEDEF | VT_INLINE)
600 #define VT_TYPE (~(VT_STORAGE))
604 /* warning: the following compare tokens depend on i386 asm code */
611 #define TOK_Nset 0x98
612 #define TOK_Nclear 0x99
618 #define TOK_LAND 0xa0
622 #define TOK_MID 0xa3 /* inc/dec, to void constant */
624 #define TOK_UDIV 0xb0 /* unsigned division */
625 #define TOK_UMOD 0xb1 /* unsigned modulo */
626 #define TOK_PDIV 0xb2 /* fast division with undefined rounding for pointers */
627 #define TOK_CINT 0xb3 /* number in tokc */
628 #define TOK_CCHAR 0xb4 /* char constant in tokc */
629 #define TOK_STR 0xb5 /* pointer to string in tokc */
630 #define TOK_TWOSHARPS 0xb6 /* ## preprocessing token */
631 #define TOK_LCHAR 0xb7
632 #define TOK_LSTR 0xb8
633 #define TOK_CFLOAT 0xb9 /* float constant */
634 #define TOK_LINENUM 0xba /* line number info */
635 #define TOK_CDOUBLE 0xc0 /* double constant */
636 #define TOK_CLDOUBLE 0xc1 /* long double constant */
637 #define TOK_UMULL 0xc2 /* unsigned 32x32 -> 64 mul */
638 #define TOK_ADDC1 0xc3 /* add with carry generation */
639 #define TOK_ADDC2 0xc4 /* add with carry use */
640 #define TOK_SUBC1 0xc5 /* add with carry generation */
641 #define TOK_SUBC2 0xc6 /* add with carry use */
642 #define TOK_CUINT 0xc8 /* unsigned int constant */
643 #define TOK_CLLONG 0xc9 /* long long constant */
644 #define TOK_CULLONG 0xca /* unsigned long long constant */
645 #define TOK_ARROW 0xcb
646 #define TOK_DOTS 0xcc /* three dots */
647 #define TOK_SHR 0xcd /* unsigned shift right */
648 #define TOK_PPNUM 0xce /* preprocessor number */
650 #define TOK_SHL 0x01 /* shift left */
651 #define TOK_SAR 0x02 /* signed shift right */
653 /* assignement operators : normal operator or 0x80 */
654 #define TOK_A_MOD 0xa5
655 #define TOK_A_AND 0xa6
656 #define TOK_A_MUL 0xaa
657 #define TOK_A_ADD 0xab
658 #define TOK_A_SUB 0xad
659 #define TOK_A_DIV 0xaf
660 #define TOK_A_XOR 0xde
661 #define TOK_A_OR 0xfc
662 #define TOK_A_SHL 0x81
663 #define TOK_A_SAR 0x82
666 #define offsetof(type, field) ((size_t) &((type *)0)->field)
670 #define countof(tab) (sizeof(tab) / sizeof((tab)[0]))
673 /* WARNING: the content of this string encodes token numbers */
674 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";
676 #define TOK_EOF (-1) /* end of file */
677 #define TOK_LINEFEED 10 /* line feed */
679 /* all identificators and strings have token above that */
680 #define TOK_IDENT 256
682 /* only used for i386 asm opcodes definitions */
683 #define DEF_ASM(x) DEF(TOK_ASM_ ## x, #x)
686 DEF(TOK_ASM_ ## x ## b, #x "b") \
687 DEF(TOK_ASM_ ## x ## w, #x "w") \
688 DEF(TOK_ASM_ ## x ## l, #x "l") \
689 DEF(TOK_ASM_ ## x, #x)
692 DEF(TOK_ASM_ ## x ## w, #x "w") \
693 DEF(TOK_ASM_ ## x ## l, #x "l") \
694 DEF(TOK_ASM_ ## x, #x)
697 DEF(TOK_ASM_ ## f ## x ## s, "f" #x "s") \
698 DEF(TOK_ASM_ ## fi ## x ## l, "fi" #x "l") \
699 DEF(TOK_ASM_ ## f ## x ## l, "f" #x "l") \
700 DEF(TOK_ASM_ ## fi ## x ## s, "fi" #x "s")
703 DEF(TOK_ASM_ ## f ## x, "f" #x ) \
704 DEF(TOK_ASM_ ## f ## x ## p, "f" #x "p") \
707 #define DEF_ASMTEST(x) \
739 #define TOK_ASM_int TOK_INT
742 TOK_LAST
= TOK_IDENT
- 1,
743 #define DEF(id, str) id,
748 static const char tcc_keywords
[] =
749 #define DEF(id, str) str "\0"
754 #define TOK_UIDENT TOK_DEFINE
757 #define snprintf _snprintf
758 #define vsnprintf _vsnprintf
760 #define strtold (long double)strtod
761 #define strtof (float)strtod
762 #define strtoll (long long)strtol
764 #elif defined(TCC_UCLIBC) || defined(__FreeBSD__) || defined(__DragonFly__) \
765 || defined(__OpenBSD__)
766 /* currently incorrect */
767 long double strtold(const char *nptr
, char **endptr
)
769 return (long double)strtod(nptr
, endptr
);
771 float strtof(const char *nptr
, char **endptr
)
773 return (float)strtod(nptr
, endptr
);
776 /* XXX: need to define this to use them in non ISOC99 context */
777 extern float strtof (const char *__nptr
, char **__endptr
);
778 extern long double strtold (const char *__nptr
, char **__endptr
);
781 static char *pstrcpy(char *buf
, int buf_size
, const char *s
);
782 static char *pstrcat(char *buf
, int buf_size
, const char *s
);
783 static char *tcc_basename(const char *name
);
784 static char *tcc_fileextension (const char *p
);
786 static void next(void);
787 static void next_nomacro(void);
788 static void parse_expr_type(CType
*type
);
789 static void expr_type(CType
*type
);
790 static void unary_type(CType
*type
);
791 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
792 int case_reg
, int is_expr
);
793 static int expr_const(void);
794 static void expr_eq(void);
795 static void gexpr(void);
796 static void gen_inline_functions(void);
797 static void decl(int l
);
798 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
799 int first
, int size_only
);
800 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
801 int has_init
, int v
, int scope
);
803 void gv2(int rc1
, int rc2
);
804 void move_reg(int r
, int s
);
805 void save_regs(int n
);
806 void save_reg(int r
);
811 int get_reg_ex(int rc
,int rc2
);
814 struct macro_level
*prev
;
818 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
819 const int *macro_str
, struct macro_level
**can_read_stream
);
821 void force_charshort_cast(int t
);
822 static void gen_cast(CType
*type
);
824 static Sym
*sym_find(int v
);
825 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
);
828 static int type_size(CType
*type
, int *a
);
829 static inline CType
*pointed_type(CType
*type
);
830 static int pointed_size(CType
*type
);
831 static int lvalue_type(int t
);
832 static int parse_btype(CType
*type
, AttributeDef
*ad
);
833 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
);
834 static int compare_types(CType
*type1
, CType
*type2
, int unqualified
);
835 static int is_compatible_types(CType
*type1
, CType
*type2
);
836 static int is_compatible_parameter_types(CType
*type1
, CType
*type2
);
838 int ieee_finite(double d
);
839 void error(const char *fmt
, ...);
843 void lexpand_nr(void);
844 static void vpush_global_sym(CType
*type
, int v
);
845 void vset(CType
*type
, int r
, int v
);
846 void type_to_str(char *buf
, int buf_size
,
847 CType
*type
, const char *varstr
);
848 char *get_tok_str(int v
, CValue
*cv
);
849 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
850 unsigned long offset
, unsigned long size
);
851 static Sym
*external_global_sym(int v
, CType
*type
, int r
);
853 /* section generation */
854 static void section_realloc(Section
*sec
, unsigned long new_size
);
855 static void *section_ptr_add(Section
*sec
, unsigned long size
);
856 static void put_extern_sym(Sym
*sym
, Section
*section
,
857 unsigned long value
, unsigned long size
);
858 static void greloc(Section
*s
, Sym
*sym
, unsigned long addr
, int type
);
859 static int put_elf_str(Section
*s
, const char *sym
);
860 static int put_elf_sym(Section
*s
,
861 unsigned long value
, unsigned long size
,
862 int info
, int other
, int shndx
, const char *name
);
863 static int add_elf_sym(Section
*s
, unsigned long value
, unsigned long size
,
864 int info
, int other
, int sh_num
, const char *name
);
865 static void put_elf_reloc(Section
*symtab
, Section
*s
, unsigned long offset
,
866 int type
, int symbol
);
867 static void put_stabs(const char *str
, int type
, int other
, int desc
,
868 unsigned long value
);
869 static void put_stabs_r(const char *str
, int type
, int other
, int desc
,
870 unsigned long value
, Section
*sec
, int sym_index
);
871 static void put_stabn(int type
, int other
, int desc
, int value
);
872 static void put_stabd(int type
, int other
, int desc
);
873 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
);
875 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
876 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
877 #define AFF_PREPROCESS 0x0004 /* preprocess file */
878 static int tcc_add_file_internal(TCCState
*s
, const char *filename
, int flags
);
881 int tcc_output_coff(TCCState
*s1
, FILE *f
);
884 void *resolve_sym(TCCState
*s1
, const char *sym
, int type
);
885 int pe_load_def_file(struct TCCState
*s1
, int fd
);
886 int pe_test_res_file(void *v
, int size
);
887 int pe_load_res_file(struct TCCState
*s1
, int fd
);
888 void pe_add_runtime(struct TCCState
*s1
);
889 void pe_guess_outfile(char *objfilename
, int output_type
);
890 int pe_output_file(struct TCCState
*s1
, const char *filename
);
894 #ifdef CONFIG_TCC_ASM
896 typedef struct ExprValue
{
901 #define MAX_ASM_OPERANDS 30
903 typedef struct ASMOperand
{
904 int id
; /* GCC 3 optionnal identifier (0 if number only supported */
906 char asm_str
[16]; /* computed asm string for operand */
907 SValue
*vt
; /* C value of the expression */
908 int ref_index
; /* if >= 0, gives reference to a output constraint */
909 int input_index
; /* if >= 0, gives reference to an input constraint */
910 int priority
; /* priority, used to assign registers */
911 int reg
; /* if >= 0, register number used for this operand */
912 int is_llong
; /* true if double register value */
913 int is_memory
; /* true if memory operand */
914 int is_rw
; /* for '+' modifier */
917 static void asm_expr(TCCState
*s1
, ExprValue
*pe
);
918 static int asm_int_expr(TCCState
*s1
);
919 static int find_constraint(ASMOperand
*operands
, int nb_operands
,
920 const char *name
, const char **pp
);
922 static int tcc_assemble(TCCState
*s1
, int do_preprocess
);
926 static void asm_instr(void);
927 static void asm_global_instr(void);
929 /* true if float/double/long double type */
930 static inline int is_float(int t
)
934 return bt
== VT_LDOUBLE
|| bt
== VT_DOUBLE
|| bt
== VT_FLOAT
;
937 #ifdef TCC_TARGET_I386
938 #include "i386-gen.c"
941 #ifdef TCC_TARGET_ARM
945 #ifdef TCC_TARGET_C67
949 #ifdef TCC_TARGET_X86_64
950 #include "x86_64-gen.c"
953 #ifdef CONFIG_TCC_STATIC
955 #define RTLD_LAZY 0x001
956 #define RTLD_NOW 0x002
957 #define RTLD_GLOBAL 0x100
958 #define RTLD_DEFAULT NULL
960 /* dummy function for profiling */
961 void *dlopen(const char *filename
, int flag
)
966 const char *dlerror(void)
971 typedef struct TCCSyms
{
976 #define TCCSYM(a) { #a, &a, },
978 /* add the symbol you want here if no dynamic linking is done */
979 static TCCSyms tcc_syms
[] = {
980 #if !defined(CONFIG_TCCBOOT)
989 void *resolve_sym(TCCState
*s1
, const char *symbol
, int type
)
993 while (p
->str
!= NULL
) {
994 if (!strcmp(p
->str
, symbol
))
1001 #elif !defined(_WIN32)
1005 void *resolve_sym(TCCState
*s1
, const char *sym
, int type
)
1007 return dlsym(RTLD_DEFAULT
, sym
);
1012 /********************************************************/
1014 /* we use our own 'finite' function to avoid potential problems with
1015 non standard math libs */
1016 /* XXX: endianness dependent */
1017 int ieee_finite(double d
)
1020 return ((unsigned)((p
[1] | 0x800fffff) + 1)) >> 31;
1023 /* copy a string and truncate it. */
1024 static char *pstrcpy(char *buf
, int buf_size
, const char *s
)
1031 q_end
= buf
+ buf_size
- 1;
1043 /* strcat and truncate. */
1044 static char *pstrcat(char *buf
, int buf_size
, const char *s
)
1049 pstrcpy(buf
+ len
, buf_size
- len
, s
);
1054 static int strstart(const char *str
, const char *val
, const char **ptr
)
1059 while (*q
!= '\0') {
1071 /* extract the basename of a file */
1072 static char *tcc_basename(const char *name
)
1074 char *p
= strchr(name
, 0);
1085 static char *tcc_fileextension (const char *name
)
1087 char *b
= tcc_basename(name
);
1088 char *e
= strrchr(b
, '.');
1089 return e
? e
: strchr(b
, 0);
1093 char *normalize_slashes(char *path
)
1096 for (p
= path
; *p
; ++p
)
1102 char *w32_tcc_lib_path(void)
1104 /* on win32, we suppose the lib and includes are at the location
1106 char path
[1024], *p
;
1107 GetModuleFileNameA(NULL
, path
, sizeof path
);
1108 p
= tcc_basename(normalize_slashes(strlwr(path
)));
1109 if (p
- 5 > path
&& 0 == strncmp(p
- 5, "/bin/", 5))
1114 return strdup(path
);
1118 void set_pages_executable(void *ptr
, unsigned long length
)
1121 unsigned long old_protect
;
1122 VirtualProtect(ptr
, length
, PAGE_EXECUTE_READWRITE
, &old_protect
);
1124 unsigned long start
, end
;
1125 start
= (unsigned long)ptr
& ~(PAGESIZE
- 1);
1126 end
= (unsigned long)ptr
+ length
;
1127 end
= (end
+ PAGESIZE
- 1) & ~(PAGESIZE
- 1);
1128 mprotect((void *)start
, end
- start
, PROT_READ
| PROT_WRITE
| PROT_EXEC
);
1132 /* memory management */
1136 unsigned malloc_usable_size(void*);
1139 static inline void tcc_free(void *ptr
)
1142 mem_cur_size
-= malloc_usable_size(ptr
);
1147 static void *tcc_malloc(unsigned long size
)
1152 error("memory full");
1154 mem_cur_size
+= malloc_usable_size(ptr
);
1155 if (mem_cur_size
> mem_max_size
)
1156 mem_max_size
= mem_cur_size
;
1161 static void *tcc_mallocz(unsigned long size
)
1164 ptr
= tcc_malloc(size
);
1165 memset(ptr
, 0, size
);
1169 static inline void *tcc_realloc(void *ptr
, unsigned long size
)
1173 mem_cur_size
-= malloc_usable_size(ptr
);
1175 ptr1
= realloc(ptr
, size
);
1177 /* NOTE: count not correct if alloc error, but not critical */
1178 mem_cur_size
+= malloc_usable_size(ptr1
);
1179 if (mem_cur_size
> mem_max_size
)
1180 mem_max_size
= mem_cur_size
;
1185 static char *tcc_strdup(const char *str
)
1188 ptr
= tcc_malloc(strlen(str
) + 1);
1193 #define free(p) use_tcc_free(p)
1194 #define malloc(s) use_tcc_malloc(s)
1195 #define realloc(p, s) use_tcc_realloc(p, s)
1197 static void dynarray_add(void ***ptab
, int *nb_ptr
, void *data
)
1204 /* every power of two we double array size */
1205 if ((nb
& (nb
- 1)) == 0) {
1210 pp
= tcc_realloc(pp
, nb_alloc
* sizeof(void *));
1212 error("memory full");
1219 static void dynarray_reset(void *pp
, int *n
)
1222 for (p
= *(void***)pp
; *n
; ++p
, --*n
)
1225 tcc_free(*(void**)pp
);
1229 /* symbol allocator */
1230 static Sym
*__sym_malloc(void)
1232 Sym
*sym_pool
, *sym
, *last_sym
;
1235 sym_pool
= tcc_malloc(SYM_POOL_NB
* sizeof(Sym
));
1236 dynarray_add(&sym_pools
, &nb_sym_pools
, sym_pool
);
1238 last_sym
= sym_free_first
;
1240 for(i
= 0; i
< SYM_POOL_NB
; i
++) {
1241 sym
->next
= last_sym
;
1245 sym_free_first
= last_sym
;
1249 static inline Sym
*sym_malloc(void)
1252 sym
= sym_free_first
;
1254 sym
= __sym_malloc();
1255 sym_free_first
= sym
->next
;
1259 static inline void sym_free(Sym
*sym
)
1261 sym
->next
= sym_free_first
;
1262 sym_free_first
= sym
;
1265 Section
*new_section(TCCState
*s1
, const char *name
, int sh_type
, int sh_flags
)
1269 sec
= tcc_mallocz(sizeof(Section
) + strlen(name
));
1270 strcpy(sec
->name
, name
);
1271 sec
->sh_type
= sh_type
;
1272 sec
->sh_flags
= sh_flags
;
1280 sec
->sh_addralign
= 4;
1283 sec
->sh_addralign
= 1;
1286 sec
->sh_addralign
= 32; /* default conservative alignment */
1290 /* only add section if not private */
1291 if (!(sh_flags
& SHF_PRIVATE
)) {
1292 sec
->sh_num
= s1
->nb_sections
;
1293 dynarray_add((void ***)&s1
->sections
, &s1
->nb_sections
, sec
);
1298 static void free_section(Section
*s
)
1300 if (s
->link
&& (s
->link
->sh_flags
& SHF_PRIVATE
))
1301 free_section(s
->link
);
1302 if (s
->hash
&& (s
->hash
->sh_flags
& SHF_PRIVATE
))
1303 s
->hash
->link
= NULL
, free_section(s
->hash
);
1308 /* realloc section and set its content to zero */
1309 static void section_realloc(Section
*sec
, unsigned long new_size
)
1312 unsigned char *data
;
1314 size
= sec
->data_allocated
;
1317 while (size
< new_size
)
1319 data
= tcc_realloc(sec
->data
, size
);
1321 error("memory full");
1322 memset(data
+ sec
->data_allocated
, 0, size
- sec
->data_allocated
);
1324 sec
->data_allocated
= size
;
1327 /* reserve at least 'size' bytes in section 'sec' from
1328 sec->data_offset. */
1329 static void *section_ptr_add(Section
*sec
, unsigned long size
)
1331 unsigned long offset
, offset1
;
1333 offset
= sec
->data_offset
;
1334 offset1
= offset
+ size
;
1335 if (offset1
> sec
->data_allocated
)
1336 section_realloc(sec
, offset1
);
1337 sec
->data_offset
= offset1
;
1338 return sec
->data
+ offset
;
1341 /* return a reference to a section, and create it if it does not
1343 Section
*find_section(TCCState
*s1
, const char *name
)
1347 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1348 sec
= s1
->sections
[i
];
1349 if (!strcmp(name
, sec
->name
))
1352 /* sections are created as PROGBITS */
1353 return new_section(s1
, name
, SHT_PROGBITS
, SHF_ALLOC
);
1356 #define SECTION_ABS ((void *)1)
1358 /* update sym->c so that it points to an external symbol in section
1359 'section' with value 'value' */
1360 static void put_extern_sym2(Sym
*sym
, Section
*section
,
1361 unsigned long value
, unsigned long size
,
1362 int can_add_underscore
)
1364 int sym_type
, sym_bind
, sh_num
, info
, other
, attr
;
1369 if (section
== NULL
)
1371 else if (section
== SECTION_ABS
)
1374 sh_num
= section
->sh_num
;
1378 if ((sym
->type
.t
& VT_BTYPE
) == VT_FUNC
) {
1379 sym_type
= STT_FUNC
;
1380 #ifdef TCC_TARGET_PE
1382 attr
= sym
->type
.ref
->r
;
1383 if (FUNC_EXPORT(attr
))
1385 if (FUNC_CALL(attr
) == FUNC_STDCALL
)
1389 sym_type
= STT_OBJECT
;
1392 if (sym
->type
.t
& VT_STATIC
)
1393 sym_bind
= STB_LOCAL
;
1395 sym_bind
= STB_GLOBAL
;
1398 name
= get_tok_str(sym
->v
, NULL
);
1399 #ifdef CONFIG_TCC_BCHECK
1400 if (do_bounds_check
) {
1403 /* XXX: avoid doing that for statics ? */
1404 /* if bound checking is activated, we change some function
1405 names by adding the "__bound" prefix */
1408 /* XXX: we rely only on malloc hooks */
1421 strcpy(buf
, "__bound_");
1429 #ifdef TCC_TARGET_PE
1430 if ((other
& 2) && can_add_underscore
) {
1431 sprintf(buf1
, "_%s@%d", name
, FUNC_ARGS(attr
));
1435 if (tcc_state
->leading_underscore
&& can_add_underscore
) {
1437 pstrcpy(buf1
+ 1, sizeof(buf1
) - 1, name
);
1440 info
= ELFW(ST_INFO
)(sym_bind
, sym_type
);
1441 sym
->c
= add_elf_sym(symtab_section
, value
, size
, info
, other
, sh_num
, name
);
1443 esym
= &((ElfW(Sym
) *)symtab_section
->data
)[sym
->c
];
1444 esym
->st_value
= value
;
1445 esym
->st_size
= size
;
1446 esym
->st_shndx
= sh_num
;
1447 esym
->st_other
|= other
;
1451 static void put_extern_sym(Sym
*sym
, Section
*section
,
1452 unsigned long value
, unsigned long size
)
1454 put_extern_sym2(sym
, section
, value
, size
, 1);
1457 /* add a new relocation entry to symbol 'sym' in section 's' */
1458 static void greloc(Section
*s
, Sym
*sym
, unsigned long offset
, int type
)
1461 put_extern_sym(sym
, NULL
, 0, 0);
1462 /* now we can add ELF relocation info */
1463 put_elf_reloc(symtab_section
, s
, offset
, type
, sym
->c
);
1466 static inline int isid(int c
)
1468 return (c
>= 'a' && c
<= 'z') ||
1469 (c
>= 'A' && c
<= 'Z') ||
1473 static inline int isnum(int c
)
1475 return c
>= '0' && c
<= '9';
1478 static inline int isoct(int c
)
1480 return c
>= '0' && c
<= '7';
1483 static inline int toup(int c
)
1485 if (c
>= 'a' && c
<= 'z')
1486 return c
- 'a' + 'A';
1491 static void strcat_vprintf(char *buf
, int buf_size
, const char *fmt
, va_list ap
)
1495 vsnprintf(buf
+ len
, buf_size
- len
, fmt
, ap
);
1498 static void strcat_printf(char *buf
, int buf_size
, const char *fmt
, ...)
1502 strcat_vprintf(buf
, buf_size
, fmt
, ap
);
1506 void error1(TCCState
*s1
, int is_warning
, const char *fmt
, va_list ap
)
1513 for(f
= s1
->include_stack
; f
< s1
->include_stack_ptr
; f
++)
1514 strcat_printf(buf
, sizeof(buf
), "In file included from %s:%d:\n",
1515 (*f
)->filename
, (*f
)->line_num
);
1516 if (file
->line_num
> 0) {
1517 strcat_printf(buf
, sizeof(buf
),
1518 "%s:%d: ", file
->filename
, file
->line_num
);
1520 strcat_printf(buf
, sizeof(buf
),
1521 "%s: ", file
->filename
);
1524 strcat_printf(buf
, sizeof(buf
),
1528 strcat_printf(buf
, sizeof(buf
), "warning: ");
1529 strcat_vprintf(buf
, sizeof(buf
), fmt
, ap
);
1531 if (!s1
->error_func
) {
1532 /* default case: stderr */
1533 fprintf(stderr
, "%s\n", buf
);
1535 s1
->error_func(s1
->error_opaque
, buf
);
1537 if (!is_warning
|| s1
->warn_error
)
1542 void tcc_set_error_func(TCCState
*s
, void *error_opaque
,
1543 void (*error_func
)(void *opaque
, const char *msg
))
1545 s
->error_opaque
= error_opaque
;
1546 s
->error_func
= error_func
;
1550 /* error without aborting current compilation */
1551 void error_noabort(const char *fmt
, ...)
1553 TCCState
*s1
= tcc_state
;
1557 error1(s1
, 0, fmt
, ap
);
1561 void error(const char *fmt
, ...)
1563 TCCState
*s1
= tcc_state
;
1567 error1(s1
, 0, fmt
, ap
);
1569 /* better than nothing: in some cases, we accept to handle errors */
1570 if (s1
->error_set_jmp_enabled
) {
1571 longjmp(s1
->error_jmp_buf
, 1);
1573 /* XXX: eliminate this someday */
1578 void expect(const char *msg
)
1580 error("%s expected", msg
);
1583 void warning(const char *fmt
, ...)
1585 TCCState
*s1
= tcc_state
;
1592 error1(s1
, 1, fmt
, ap
);
1599 error("'%c' expected", c
);
1603 static void test_lvalue(void)
1605 if (!(vtop
->r
& VT_LVAL
))
1609 /* allocate a new token */
1610 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
1612 TokenSym
*ts
, **ptable
;
1615 if (tok_ident
>= SYM_FIRST_ANOM
)
1616 error("memory full");
1618 /* expand token table if needed */
1619 i
= tok_ident
- TOK_IDENT
;
1620 if ((i
% TOK_ALLOC_INCR
) == 0) {
1621 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
1623 error("memory full");
1624 table_ident
= ptable
;
1627 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
1628 table_ident
[i
] = ts
;
1629 ts
->tok
= tok_ident
++;
1630 ts
->sym_define
= NULL
;
1631 ts
->sym_label
= NULL
;
1632 ts
->sym_struct
= NULL
;
1633 ts
->sym_identifier
= NULL
;
1635 ts
->hash_next
= NULL
;
1636 memcpy(ts
->str
, str
, len
);
1637 ts
->str
[len
] = '\0';
1642 #define TOK_HASH_INIT 1
1643 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
1645 /* find a token and add it if not found */
1646 static TokenSym
*tok_alloc(const char *str
, int len
)
1648 TokenSym
*ts
, **pts
;
1654 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
1655 h
&= (TOK_HASH_SIZE
- 1);
1657 pts
= &hash_ident
[h
];
1662 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
1664 pts
= &(ts
->hash_next
);
1666 return tok_alloc_new(pts
, str
, len
);
1669 /* CString handling */
1671 static void cstr_realloc(CString
*cstr
, int new_size
)
1676 size
= cstr
->size_allocated
;
1678 size
= 8; /* no need to allocate a too small first string */
1679 while (size
< new_size
)
1681 data
= tcc_realloc(cstr
->data_allocated
, size
);
1683 error("memory full");
1684 cstr
->data_allocated
= data
;
1685 cstr
->size_allocated
= size
;
1690 static inline void cstr_ccat(CString
*cstr
, int ch
)
1693 size
= cstr
->size
+ 1;
1694 if (size
> cstr
->size_allocated
)
1695 cstr_realloc(cstr
, size
);
1696 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
1700 static void cstr_cat(CString
*cstr
, const char *str
)
1712 /* add a wide char */
1713 static void cstr_wccat(CString
*cstr
, int ch
)
1716 size
= cstr
->size
+ sizeof(nwchar_t
);
1717 if (size
> cstr
->size_allocated
)
1718 cstr_realloc(cstr
, size
);
1719 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
1723 static void cstr_new(CString
*cstr
)
1725 memset(cstr
, 0, sizeof(CString
));
1728 /* free string and reset it to NULL */
1729 static void cstr_free(CString
*cstr
)
1731 tcc_free(cstr
->data_allocated
);
1735 #define cstr_reset(cstr) cstr_free(cstr)
1737 /* XXX: unicode ? */
1738 static void add_char(CString
*cstr
, int c
)
1740 if (c
== '\'' || c
== '\"' || c
== '\\') {
1741 /* XXX: could be more precise if char or string */
1742 cstr_ccat(cstr
, '\\');
1744 if (c
>= 32 && c
<= 126) {
1747 cstr_ccat(cstr
, '\\');
1749 cstr_ccat(cstr
, 'n');
1751 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
1752 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
1753 cstr_ccat(cstr
, '0' + (c
& 7));
1758 /* XXX: buffer overflow */
1759 /* XXX: float tokens */
1760 char *get_tok_str(int v
, CValue
*cv
)
1762 static char buf
[STRING_MAX_SIZE
+ 1];
1763 static CString cstr_buf
;
1769 /* NOTE: to go faster, we give a fixed buffer for small strings */
1770 cstr_reset(&cstr_buf
);
1771 cstr_buf
.data
= buf
;
1772 cstr_buf
.size_allocated
= sizeof(buf
);
1778 /* XXX: not quite exact, but only useful for testing */
1779 sprintf(p
, "%u", cv
->ui
);
1783 /* XXX: not quite exact, but only useful for testing */
1784 sprintf(p
, "%Lu", cv
->ull
);
1787 cstr_ccat(&cstr_buf
, 'L');
1789 cstr_ccat(&cstr_buf
, '\'');
1790 add_char(&cstr_buf
, cv
->i
);
1791 cstr_ccat(&cstr_buf
, '\'');
1792 cstr_ccat(&cstr_buf
, '\0');
1796 len
= cstr
->size
- 1;
1798 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1799 cstr_ccat(&cstr_buf
, '\0');
1802 cstr_ccat(&cstr_buf
, 'L');
1805 cstr_ccat(&cstr_buf
, '\"');
1807 len
= cstr
->size
- 1;
1809 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1811 len
= (cstr
->size
/ sizeof(nwchar_t
)) - 1;
1813 add_char(&cstr_buf
, ((nwchar_t
*)cstr
->data
)[i
]);
1815 cstr_ccat(&cstr_buf
, '\"');
1816 cstr_ccat(&cstr_buf
, '\0');
1825 return strcpy(p
, "...");
1827 return strcpy(p
, "<<=");
1829 return strcpy(p
, ">>=");
1831 if (v
< TOK_IDENT
) {
1832 /* search in two bytes table */
1846 } else if (v
< tok_ident
) {
1847 return table_ident
[v
- TOK_IDENT
]->str
;
1848 } else if (v
>= SYM_FIRST_ANOM
) {
1849 /* special name for anonymous symbol */
1850 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
1852 /* should never happen */
1857 return cstr_buf
.data
;
1860 /* push, without hashing */
1861 static Sym
*sym_push2(Sym
**ps
, int v
, int t
, long c
)
1875 /* find a symbol and return its associated structure. 's' is the top
1876 of the symbol stack */
1877 static Sym
*sym_find2(Sym
*s
, int v
)
1887 /* structure lookup */
1888 static inline Sym
*struct_find(int v
)
1891 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1893 return table_ident
[v
]->sym_struct
;
1896 /* find an identifier */
1897 static inline Sym
*sym_find(int v
)
1900 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1902 return table_ident
[v
]->sym_identifier
;
1905 /* push a given symbol on the symbol stack */
1906 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
)
1915 s
= sym_push2(ps
, v
, type
->t
, c
);
1916 s
->type
.ref
= type
->ref
;
1918 /* don't record fields or anonymous symbols */
1920 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1921 /* record symbol in token array */
1922 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1924 ps
= &ts
->sym_struct
;
1926 ps
= &ts
->sym_identifier
;
1933 /* push a global identifier */
1934 static Sym
*global_identifier_push(int v
, int t
, int c
)
1937 s
= sym_push2(&global_stack
, v
, t
, c
);
1938 /* don't record anonymous symbol */
1939 if (v
< SYM_FIRST_ANOM
) {
1940 ps
= &table_ident
[v
- TOK_IDENT
]->sym_identifier
;
1941 /* modify the top most local identifier, so that
1942 sym_identifier will point to 's' when popped */
1944 ps
= &(*ps
)->prev_tok
;
1951 /* pop symbols until top reaches 'b' */
1952 static void sym_pop(Sym
**ptop
, Sym
*b
)
1962 /* remove symbol in token array */
1964 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1965 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1967 ps
= &ts
->sym_struct
;
1969 ps
= &ts
->sym_identifier
;
1980 BufferedFile
*tcc_open(TCCState
*s1
, const char *filename
)
1985 if (strcmp(filename
, "-") == 0)
1986 fd
= 0, filename
= "stdin";
1988 fd
= open(filename
, O_RDONLY
| O_BINARY
);
1989 if ((verbose
== 2 && fd
>= 0) || verbose
== 3)
1990 printf("%s %*s%s\n", fd
< 0 ? "nf":"->",
1991 (s1
->include_stack_ptr
- s1
->include_stack
), "", filename
);
1994 bf
= tcc_malloc(sizeof(BufferedFile
));
1996 bf
->buf_ptr
= bf
->buffer
;
1997 bf
->buf_end
= bf
->buffer
;
1998 bf
->buffer
[0] = CH_EOB
; /* put eob symbol */
1999 pstrcpy(bf
->filename
, sizeof(bf
->filename
), filename
);
2001 normalize_slashes(bf
->filename
);
2004 bf
->ifndef_macro
= 0;
2005 bf
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
2006 // printf("opening '%s'\n", filename);
2010 void tcc_close(BufferedFile
*bf
)
2012 total_lines
+= bf
->line_num
;
2017 /* fill input buffer and peek next char */
2018 static int tcc_peekc_slow(BufferedFile
*bf
)
2021 /* only tries to read if really end of buffer */
2022 if (bf
->buf_ptr
>= bf
->buf_end
) {
2024 #if defined(PARSE_DEBUG)
2029 len
= read(bf
->fd
, bf
->buffer
, len
);
2036 bf
->buf_ptr
= bf
->buffer
;
2037 bf
->buf_end
= bf
->buffer
+ len
;
2038 *bf
->buf_end
= CH_EOB
;
2040 if (bf
->buf_ptr
< bf
->buf_end
) {
2041 return bf
->buf_ptr
[0];
2043 bf
->buf_ptr
= bf
->buf_end
;
2048 /* return the current character, handling end of block if necessary
2050 static int handle_eob(void)
2052 return tcc_peekc_slow(file
);
2055 /* read next char from current input file and handle end of input buffer */
2056 static inline void inp(void)
2058 ch
= *(++(file
->buf_ptr
));
2059 /* end of buffer/file handling */
2064 /* handle '\[\r]\n' */
2065 static int handle_stray_noerror(void)
2067 while (ch
== '\\') {
2072 } else if (ch
== '\r') {
2086 static void handle_stray(void)
2088 if (handle_stray_noerror())
2089 error("stray '\\' in program");
2092 /* skip the stray and handle the \\n case. Output an error if
2093 incorrect char after the stray */
2094 static int handle_stray1(uint8_t *p
)
2098 if (p
>= file
->buf_end
) {
2115 /* handle just the EOB case, but not stray */
2116 #define PEEKC_EOB(c, p)\
2127 /* handle the complicated stray case */
2128 #define PEEKC(c, p)\
2133 c = handle_stray1(p);\
2138 /* input with '\[\r]\n' handling. Note that this function cannot
2139 handle other characters after '\', so you cannot call it inside
2140 strings or comments */
2141 static void minp(void)
2149 /* single line C++ comments */
2150 static uint8_t *parse_line_comment(uint8_t *p
)
2158 if (c
== '\n' || c
== CH_EOF
) {
2160 } else if (c
== '\\') {
2169 } else if (c
== '\r') {
2187 static uint8_t *parse_comment(uint8_t *p
)
2193 /* fast skip loop */
2196 if (c
== '\n' || c
== '*' || c
== '\\')
2200 if (c
== '\n' || c
== '*' || c
== '\\')
2204 /* now we can handle all the cases */
2208 } else if (c
== '*') {
2214 } else if (c
== '/') {
2215 goto end_of_comment
;
2216 } else if (c
== '\\') {
2221 /* skip '\[\r]\n', otherwise just skip the stray */
2227 } else if (c
== '\r') {
2244 /* stray, eob or eof */
2249 error("unexpected end of file in comment");
2250 } else if (c
== '\\') {
2262 /* space exlcuding newline */
2263 static inline int is_space(int ch
)
2265 return ch
== ' ' || ch
== '\t' || ch
== '\v' || ch
== '\f' || ch
== '\r';
2268 static inline void skip_spaces(void)
2270 while (is_space(ch
))
2274 /* parse a string without interpreting escapes */
2275 static uint8_t *parse_pp_string(uint8_t *p
,
2276 int sep
, CString
*str
)
2284 } else if (c
== '\\') {
2289 unterminated_string
:
2290 /* XXX: indicate line number of start of string */
2291 error("missing terminating %c character", sep
);
2292 } else if (c
== '\\') {
2293 /* escape : just skip \[\r]\n */
2298 } else if (c
== '\r') {
2301 expect("'\n' after '\r'");
2304 } else if (c
== CH_EOF
) {
2305 goto unterminated_string
;
2308 cstr_ccat(str
, '\\');
2314 } else if (c
== '\n') {
2317 } else if (c
== '\r') {
2321 cstr_ccat(str
, '\r');
2337 /* skip block of text until #else, #elif or #endif. skip also pairs of
2339 void preprocess_skip(void)
2341 int a
, start_of_line
, c
, in_warn_or_error
;
2348 in_warn_or_error
= 0;
2369 } else if (c
== '\\') {
2370 ch
= file
->buf_ptr
[0];
2371 handle_stray_noerror();
2378 if (in_warn_or_error
)
2380 p
= parse_pp_string(p
, c
, NULL
);
2384 if (in_warn_or_error
)
2391 p
= parse_comment(p
);
2392 } else if (ch
== '/') {
2393 p
= parse_line_comment(p
);
2398 if (start_of_line
) {
2403 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
2405 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
2407 else if (tok
== TOK_ENDIF
)
2409 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
2410 in_warn_or_error
= 1;
2424 /* ParseState handling */
2426 /* XXX: currently, no include file info is stored. Thus, we cannot display
2427 accurate messages if the function or data definition spans multiple
2430 /* save current parse state in 's' */
2431 void save_parse_state(ParseState
*s
)
2433 s
->line_num
= file
->line_num
;
2434 s
->macro_ptr
= macro_ptr
;
2439 /* restore parse state from 's' */
2440 void restore_parse_state(ParseState
*s
)
2442 file
->line_num
= s
->line_num
;
2443 macro_ptr
= s
->macro_ptr
;
2448 /* return the number of additional 'ints' necessary to store the
2450 static inline int tok_ext_size(int t
)
2464 error("unsupported token");
2471 return LDOUBLE_SIZE
/ 4;
2477 /* token string handling */
2479 static inline void tok_str_new(TokenString
*s
)
2483 s
->allocated_len
= 0;
2484 s
->last_line_num
= -1;
2487 static void tok_str_free(int *str
)
2492 static int *tok_str_realloc(TokenString
*s
)
2496 if (s
->allocated_len
== 0) {
2499 len
= s
->allocated_len
* 2;
2501 str
= tcc_realloc(s
->str
, len
* sizeof(int));
2503 error("memory full");
2504 s
->allocated_len
= len
;
2509 static void tok_str_add(TokenString
*s
, int t
)
2515 if (len
>= s
->allocated_len
)
2516 str
= tok_str_realloc(s
);
2521 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
2528 /* allocate space for worst case */
2529 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
2530 str
= tok_str_realloc(s
);
2539 str
[len
++] = cv
->tab
[0];
2548 nb_words
= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
2549 while ((len
+ nb_words
) > s
->allocated_len
)
2550 str
= tok_str_realloc(s
);
2551 cstr
= (CString
*)(str
+ len
);
2553 cstr
->size
= cv
->cstr
->size
;
2554 cstr
->data_allocated
= NULL
;
2555 cstr
->size_allocated
= cstr
->size
;
2556 memcpy((char *)cstr
+ sizeof(CString
),
2557 cv
->cstr
->data
, cstr
->size
);
2564 #if LDOUBLE_SIZE == 8
2567 str
[len
++] = cv
->tab
[0];
2568 str
[len
++] = cv
->tab
[1];
2570 #if LDOUBLE_SIZE == 12
2572 str
[len
++] = cv
->tab
[0];
2573 str
[len
++] = cv
->tab
[1];
2574 str
[len
++] = cv
->tab
[2];
2575 #elif LDOUBLE_SIZE == 16
2577 str
[len
++] = cv
->tab
[0];
2578 str
[len
++] = cv
->tab
[1];
2579 str
[len
++] = cv
->tab
[2];
2580 str
[len
++] = cv
->tab
[3];
2581 #elif LDOUBLE_SIZE != 8
2582 #error add long double size support
2591 /* add the current parse token in token string 's' */
2592 static void tok_str_add_tok(TokenString
*s
)
2596 /* save line number info */
2597 if (file
->line_num
!= s
->last_line_num
) {
2598 s
->last_line_num
= file
->line_num
;
2599 cval
.i
= s
->last_line_num
;
2600 tok_str_add2(s
, TOK_LINENUM
, &cval
);
2602 tok_str_add2(s
, tok
, &tokc
);
2605 #if LDOUBLE_SIZE == 16
2606 #define LDOUBLE_GET(p, cv) \
2611 #elif LDOUBLE_SIZE == 12
2612 #define LDOUBLE_GET(p, cv) \
2616 #elif LDOUBLE_SIZE == 8
2617 #define LDOUBLE_GET(p, cv) \
2621 #error add long double size support
2625 /* get a token from an integer array and increment pointer
2626 accordingly. we code it as a macro to avoid pointer aliasing. */
2627 #define TOK_GET(t, p, cv) \
2642 cv.cstr = (CString *)p; \
2643 cv.cstr->data = (char *)p + sizeof(CString);\
2644 p += (sizeof(CString) + cv.cstr->size + 3) >> 2;\
2653 case TOK_CLDOUBLE: \
2654 LDOUBLE_GET(p, cv); \
2655 p += LDOUBLE_SIZE / 4; \
2662 /* defines handling */
2663 static inline void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
2667 s
= sym_push2(&define_stack
, v
, macro_type
, (long)str
);
2668 s
->next
= first_arg
;
2669 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
2672 /* undefined a define symbol. Its name is just set to zero */
2673 static void define_undef(Sym
*s
)
2677 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2678 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2682 static inline Sym
*define_find(int v
)
2685 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2687 return table_ident
[v
]->sym_define
;
2690 /* free define stack until top reaches 'b' */
2691 static void free_defines(Sym
*b
)
2699 /* do not free args or predefined defines */
2701 tok_str_free((int *)top
->c
);
2703 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2704 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2712 static Sym
*label_find(int v
)
2715 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2717 return table_ident
[v
]->sym_label
;
2720 static Sym
*label_push(Sym
**ptop
, int v
, int flags
)
2723 s
= sym_push2(ptop
, v
, 0, 0);
2725 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
2726 if (ptop
== &global_label_stack
) {
2727 /* modify the top most local identifier, so that
2728 sym_identifier will point to 's' when popped */
2730 ps
= &(*ps
)->prev_tok
;
2737 /* pop labels until element last is reached. Look if any labels are
2738 undefined. Define symbols if '&&label' was used. */
2739 static void label_pop(Sym
**ptop
, Sym
*slast
)
2742 for(s
= *ptop
; s
!= slast
; s
= s1
) {
2744 if (s
->r
== LABEL_DECLARED
) {
2745 warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
2746 } else if (s
->r
== LABEL_FORWARD
) {
2747 error("label '%s' used but not defined",
2748 get_tok_str(s
->v
, NULL
));
2751 /* define corresponding symbol. A size of
2753 put_extern_sym(s
, cur_text_section
, (long)s
->next
, 1);
2757 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
2763 /* eval an expression for #if/#elif */
2764 static int expr_preprocess(void)
2770 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2771 next(); /* do macro subst */
2772 if (tok
== TOK_DEFINED
) {
2777 c
= define_find(tok
) != 0;
2782 } else if (tok
>= TOK_IDENT
) {
2783 /* if undefined macro */
2787 tok_str_add_tok(&str
);
2789 tok_str_add(&str
, -1); /* simulate end of file */
2790 tok_str_add(&str
, 0);
2791 /* now evaluate C constant expression */
2792 macro_ptr
= str
.str
;
2796 tok_str_free(str
.str
);
2800 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
2801 static void tok_print(int *str
)
2807 TOK_GET(t
, str
, cval
);
2810 printf(" %s", get_tok_str(t
, &cval
));
2816 /* parse after #define */
2817 static void parse_define(void)
2819 Sym
*s
, *first
, **ps
;
2820 int v
, t
, varg
, is_vaargs
, c
;
2825 error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
2826 /* XXX: should check if same macro (ANSI) */
2829 /* '(' must be just after macro definition for MACRO_FUNC */
2830 c
= file
->buf_ptr
[0];
2832 c
= handle_stray1(file
->buf_ptr
);
2837 while (tok
!= ')') {
2841 if (varg
== TOK_DOTS
) {
2842 varg
= TOK___VA_ARGS__
;
2844 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
2848 if (varg
< TOK_IDENT
)
2849 error("badly punctuated parameter list");
2850 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
2861 /* EOF testing necessary for '-D' handling */
2862 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2863 tok_str_add2(&str
, tok
, &tokc
);
2866 tok_str_add(&str
, 0);
2868 printf("define %s %d: ", get_tok_str(v
, NULL
), t
);
2871 define_push(v
, t
, str
.str
, first
);
2874 static inline int hash_cached_include(int type
, const char *filename
)
2876 const unsigned char *s
;
2880 h
= TOK_HASH_FUNC(h
, type
);
2883 h
= TOK_HASH_FUNC(h
, *s
);
2886 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
2890 /* XXX: use a token or a hash table to accelerate matching ? */
2891 static CachedInclude
*search_cached_include(TCCState
*s1
,
2892 int type
, const char *filename
)
2896 h
= hash_cached_include(type
, filename
);
2897 i
= s1
->cached_includes_hash
[h
];
2901 e
= s1
->cached_includes
[i
- 1];
2902 if (e
->type
== type
&& !strcmp(e
->filename
, filename
))
2909 static inline void add_cached_include(TCCState
*s1
, int type
,
2910 const char *filename
, int ifndef_macro
)
2915 if (search_cached_include(s1
, type
, filename
))
2918 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
2920 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
2924 strcpy(e
->filename
, filename
);
2925 e
->ifndef_macro
= ifndef_macro
;
2926 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
2927 /* add in hash table */
2928 h
= hash_cached_include(type
, filename
);
2929 e
->hash_next
= s1
->cached_includes_hash
[h
];
2930 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
2933 static void pragma_parse(TCCState
*s1
)
2938 if (tok
== TOK_pack
) {
2941 #pragma pack(1) // set
2942 #pragma pack() // reset to default
2943 #pragma pack(push,1) // push & set
2944 #pragma pack(pop) // restore previous
2948 if (tok
== TOK_ASM_pop
) {
2950 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
2952 error("out of pack stack");
2954 s1
->pack_stack_ptr
--;
2958 if (tok
== TOK_ASM_push
) {
2960 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
2962 s1
->pack_stack_ptr
++;
2965 if (tok
!= TOK_CINT
) {
2967 error("invalid pack pragma");
2970 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
2974 *s1
->pack_stack_ptr
= val
;
2980 /* is_bof is true if first non space token at beginning of file */
2981 static void preprocess(int is_bof
)
2983 TCCState
*s1
= tcc_state
;
2984 int size
, i
, c
, n
, saved_parse_flags
;
2991 saved_parse_flags
= parse_flags
;
2992 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
|
2993 PARSE_FLAG_LINEFEED
;
3003 s
= define_find(tok
);
3004 /* undefine symbol by putting an invalid name */
3009 case TOK_INCLUDE_NEXT
:
3010 ch
= file
->buf_ptr
[0];
3011 /* XXX: incorrect if comments : use next_nomacro with a special mode */
3016 } else if (ch
== '\"') {
3021 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
3022 if ((q
- buf
) < sizeof(buf
) - 1)
3025 if (handle_stray_noerror() == 0)
3033 /* eat all spaces and comments after include */
3034 /* XXX: slightly incorrect */
3035 while (ch1
!= '\n' && ch1
!= CH_EOF
)
3039 /* computed #include : either we have only strings or
3040 we have anything enclosed in '<>' */
3043 if (tok
== TOK_STR
) {
3044 while (tok
!= TOK_LINEFEED
) {
3045 if (tok
!= TOK_STR
) {
3047 error("'#include' expects \"FILENAME\" or <FILENAME>");
3049 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
3055 while (tok
!= TOK_LINEFEED
) {
3056 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
3060 /* check syntax and remove '<>' */
3061 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
3062 goto include_syntax
;
3063 memmove(buf
, buf
+ 1, len
- 2);
3064 buf
[len
- 2] = '\0';
3069 e
= search_cached_include(s1
, c
, buf
);
3070 if (e
&& define_find(e
->ifndef_macro
)) {
3071 /* no need to parse the include because the 'ifndef macro'
3074 printf("%s: skipping %s\n", file
->filename
, buf
);
3077 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
3078 error("#include recursion too deep");
3079 /* push current file in stack */
3080 /* XXX: fix current line init */
3081 *s1
->include_stack_ptr
++ = file
;
3083 /* first search in current dir if "header.h" */
3084 size
= tcc_basename(file
->filename
) - file
->filename
;
3085 if (size
> sizeof(buf1
) - 1)
3086 size
= sizeof(buf1
) - 1;
3087 memcpy(buf1
, file
->filename
, size
);
3089 pstrcat(buf1
, sizeof(buf1
), buf
);
3090 f
= tcc_open(s1
, buf1
);
3092 if (tok
== TOK_INCLUDE_NEXT
)
3098 /* now search in all the include paths */
3099 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
3100 for(i
= 0; i
< n
; i
++) {
3102 if (i
< s1
->nb_include_paths
)
3103 path
= s1
->include_paths
[i
];
3105 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
3106 pstrcpy(buf1
, sizeof(buf1
), path
);
3107 pstrcat(buf1
, sizeof(buf1
), "/");
3108 pstrcat(buf1
, sizeof(buf1
), buf
);
3109 f
= tcc_open(s1
, buf1
);
3111 if (tok
== TOK_INCLUDE_NEXT
)
3117 --s1
->include_stack_ptr
;
3118 error("include file '%s' not found", buf
);
3122 printf("%s: including %s\n", file
->filename
, buf1
);
3125 pstrcpy(f
->inc_filename
, sizeof(f
->inc_filename
), buf
);
3127 /* add include file debug info */
3129 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
3131 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
3132 ch
= file
->buf_ptr
[0];
3140 c
= expr_preprocess();
3146 if (tok
< TOK_IDENT
)
3147 error("invalid argument for '#if%sdef'", c
? "n" : "");
3151 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
3153 file
->ifndef_macro
= tok
;
3156 c
= (define_find(tok
) != 0) ^ c
;
3158 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
3159 error("memory full");
3160 *s1
->ifdef_stack_ptr
++ = c
;
3163 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
3164 error("#else without matching #if");
3165 if (s1
->ifdef_stack_ptr
[-1] & 2)
3166 error("#else after #else");
3167 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
3170 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
3171 error("#elif without matching #if");
3172 c
= s1
->ifdef_stack_ptr
[-1];
3174 error("#elif after #else");
3175 /* last #if/#elif expression was true: we skip */
3178 c
= expr_preprocess();
3179 s1
->ifdef_stack_ptr
[-1] = c
;
3189 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
3190 error("#endif without matching #if");
3191 s1
->ifdef_stack_ptr
--;
3192 /* '#ifndef macro' was at the start of file. Now we check if
3193 an '#endif' is exactly at the end of file */
3194 if (file
->ifndef_macro
&&
3195 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
3196 file
->ifndef_macro_saved
= file
->ifndef_macro
;
3197 /* need to set to zero to avoid false matches if another
3198 #ifndef at middle of file */
3199 file
->ifndef_macro
= 0;
3200 while (tok
!= TOK_LINEFEED
)
3202 tok_flags
|= TOK_FLAG_ENDIF
;
3208 if (tok
!= TOK_CINT
)
3210 file
->line_num
= tokc
.i
- 1; /* the line number will be incremented after */
3212 if (tok
!= TOK_LINEFEED
) {
3215 pstrcpy(file
->filename
, sizeof(file
->filename
),
3216 (char *)tokc
.cstr
->data
);
3222 ch
= file
->buf_ptr
[0];
3225 while (ch
!= '\n' && ch
!= CH_EOF
) {
3226 if ((q
- buf
) < sizeof(buf
) - 1)
3229 if (handle_stray_noerror() == 0)
3236 error("#error %s", buf
);
3238 warning("#warning %s", buf
);
3244 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_CINT
) {
3245 /* '!' is ignored to allow C scripts. numbers are ignored
3246 to emulate cpp behaviour */
3248 if (!(saved_parse_flags
& PARSE_FLAG_ASM_COMMENTS
))
3249 warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
3253 /* ignore other preprocess commands or #! for C scripts */
3254 while (tok
!= TOK_LINEFEED
)
3257 parse_flags
= saved_parse_flags
;
3260 /* evaluate escape codes in a string. */
3261 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
3276 case '0': case '1': case '2': case '3':
3277 case '4': case '5': case '6': case '7':
3278 /* at most three octal digits */
3283 n
= n
* 8 + c
- '0';
3287 n
= n
* 8 + c
- '0';
3292 goto add_char_nonext
;
3300 if (c
>= 'a' && c
<= 'f')
3302 else if (c
>= 'A' && c
<= 'F')
3312 goto add_char_nonext
;
3336 goto invalid_escape
;
3346 if (c
>= '!' && c
<= '~')
3347 warning("unknown escape sequence: \'\\%c\'", c
);
3349 warning("unknown escape sequence: \'\\x%x\'", c
);
3356 cstr_ccat(outstr
, c
);
3358 cstr_wccat(outstr
, c
);
3360 /* add a trailing '\0' */
3362 cstr_ccat(outstr
, '\0');
3364 cstr_wccat(outstr
, '\0');
3367 /* we use 64 bit numbers */
3370 /* bn = (bn << shift) | or_val */
3371 void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
3375 for(i
=0;i
<BN_SIZE
;i
++) {
3377 bn
[i
] = (v
<< shift
) | or_val
;
3378 or_val
= v
>> (32 - shift
);
3382 void bn_zero(unsigned int *bn
)
3385 for(i
=0;i
<BN_SIZE
;i
++) {
3390 /* parse number in null terminated string 'p' and return it in the
3392 void parse_number(const char *p
)
3394 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
3396 unsigned int bn
[BN_SIZE
];
3407 goto float_frac_parse
;
3408 } else if (t
== '0') {
3409 if (ch
== 'x' || ch
== 'X') {
3413 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
3419 /* parse all digits. cannot check octal numbers at this stage
3420 because of floating point constants */
3422 if (ch
>= 'a' && ch
<= 'f')
3424 else if (ch
>= 'A' && ch
<= 'F')
3432 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
3434 error("number too long");
3440 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
3441 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
3443 /* NOTE: strtox should support that for hexa numbers, but
3444 non ISOC99 libcs do not support it, so we prefer to do
3446 /* hexadecimal or binary floats */
3447 /* XXX: handle overflows */
3459 } else if (t
>= 'a') {
3461 } else if (t
>= 'A') {
3466 bn_lshift(bn
, shift
, t
);
3473 if (t
>= 'a' && t
<= 'f') {
3475 } else if (t
>= 'A' && t
<= 'F') {
3477 } else if (t
>= '0' && t
<= '9') {
3483 error("invalid digit");
3484 bn_lshift(bn
, shift
, t
);
3489 if (ch
!= 'p' && ch
!= 'P')
3496 } else if (ch
== '-') {
3500 if (ch
< '0' || ch
> '9')
3501 expect("exponent digits");
3502 while (ch
>= '0' && ch
<= '9') {
3503 exp_val
= exp_val
* 10 + ch
- '0';
3506 exp_val
= exp_val
* s
;
3508 /* now we can generate the number */
3509 /* XXX: should patch directly float number */
3510 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
3511 d
= ldexp(d
, exp_val
- frac_bits
);
3516 /* float : should handle overflow */
3518 } else if (t
== 'L') {
3521 /* XXX: not large enough */
3522 tokc
.ld
= (long double)d
;
3528 /* decimal floats */
3530 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3535 while (ch
>= '0' && ch
<= '9') {
3536 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3542 if (ch
== 'e' || ch
== 'E') {
3543 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3547 if (ch
== '-' || ch
== '+') {
3548 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3553 if (ch
< '0' || ch
> '9')
3554 expect("exponent digits");
3555 while (ch
>= '0' && ch
<= '9') {
3556 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3568 tokc
.f
= strtof(token_buf
, NULL
);
3569 } else if (t
== 'L') {
3572 tokc
.ld
= strtold(token_buf
, NULL
);
3575 tokc
.d
= strtod(token_buf
, NULL
);
3579 unsigned long long n
, n1
;
3582 /* integer number */
3585 if (b
== 10 && *q
== '0') {
3592 /* no need for checks except for base 10 / 8 errors */
3595 } else if (t
>= 'a') {
3597 } else if (t
>= 'A') {
3602 error("invalid digit");
3606 /* detect overflow */
3607 /* XXX: this test is not reliable */
3609 error("integer constant overflow");
3612 /* XXX: not exactly ANSI compliant */
3613 if ((n
& 0xffffffff00000000LL
) != 0) {
3618 } else if (n
> 0x7fffffff) {
3629 error("three 'l's in integer constant");
3632 if (tok
== TOK_CINT
)
3634 else if (tok
== TOK_CUINT
)
3638 } else if (t
== 'U') {
3640 error("two 'u's in integer constant");
3642 if (tok
== TOK_CINT
)
3644 else if (tok
== TOK_CLLONG
)
3651 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
3659 #define PARSE2(c1, tok1, c2, tok2) \
3670 /* return next token without macro substitution */
3671 static inline void next_nomacro1(void)
3691 /* first look if it is in fact an end of buffer */
3692 if (p
>= file
->buf_end
) {
3696 if (p
>= file
->buf_end
)
3709 TCCState
*s1
= tcc_state
;
3710 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
3711 && !(tok_flags
& TOK_FLAG_EOF
)) {
3712 tok_flags
|= TOK_FLAG_EOF
;
3714 goto keep_tok_flags
;
3715 } else if (s1
->include_stack_ptr
== s1
->include_stack
||
3716 !(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3717 /* no include left : end of file. */
3720 tok_flags
&= ~TOK_FLAG_EOF
;
3721 /* pop include file */
3723 /* test if previous '#endif' was after a #ifdef at
3725 if (tok_flags
& TOK_FLAG_ENDIF
) {
3727 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
3729 add_cached_include(s1
, file
->inc_type
, file
->inc_filename
,
3730 file
->ifndef_macro_saved
);
3733 /* add end of include file debug info */
3735 put_stabd(N_EINCL
, 0, 0);
3737 /* pop include stack */
3739 s1
->include_stack_ptr
--;
3740 file
= *s1
->include_stack_ptr
;
3749 tok_flags
|= TOK_FLAG_BOL
;
3751 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
3754 goto keep_tok_flags
;
3759 if ((tok_flags
& TOK_FLAG_BOL
) &&
3760 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3762 preprocess(tok_flags
& TOK_FLAG_BOF
);
3768 tok
= TOK_TWOSHARPS
;
3770 if (parse_flags
& PARSE_FLAG_ASM_COMMENTS
) {
3771 p
= parse_line_comment(p
- 1);
3780 case 'a': case 'b': case 'c': case 'd':
3781 case 'e': case 'f': case 'g': case 'h':
3782 case 'i': case 'j': case 'k': case 'l':
3783 case 'm': case 'n': case 'o': case 'p':
3784 case 'q': case 'r': case 's': case 't':
3785 case 'u': case 'v': case 'w': case 'x':
3787 case 'A': case 'B': case 'C': case 'D':
3788 case 'E': case 'F': case 'G': case 'H':
3789 case 'I': case 'J': case 'K':
3790 case 'M': case 'N': case 'O': case 'P':
3791 case 'Q': case 'R': case 'S': case 'T':
3792 case 'U': case 'V': case 'W': case 'X':
3798 h
= TOK_HASH_FUNC(h
, c
);
3802 if (!isidnum_table
[c
-CH_EOF
])
3804 h
= TOK_HASH_FUNC(h
, c
);
3811 /* fast case : no stray found, so we have the full token
3812 and we have already hashed it */
3814 h
&= (TOK_HASH_SIZE
- 1);
3815 pts
= &hash_ident
[h
];
3820 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
3822 pts
= &(ts
->hash_next
);
3824 ts
= tok_alloc_new(pts
, p1
, len
);
3828 cstr_reset(&tokcstr
);
3831 cstr_ccat(&tokcstr
, *p1
);
3837 while (isidnum_table
[c
-CH_EOF
]) {
3838 cstr_ccat(&tokcstr
, c
);
3841 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
3847 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
3849 goto parse_ident_fast
;
3852 if (c
== '\'' || c
== '\"') {
3856 cstr_reset(&tokcstr
);
3857 cstr_ccat(&tokcstr
, 'L');
3858 goto parse_ident_slow
;
3862 case '0': case '1': case '2': case '3':
3863 case '4': case '5': case '6': case '7':
3866 cstr_reset(&tokcstr
);
3867 /* after the first digit, accept digits, alpha, '.' or sign if
3868 prefixed by 'eEpP' */
3872 cstr_ccat(&tokcstr
, c
);
3874 if (!(isnum(c
) || isid(c
) || c
== '.' ||
3875 ((c
== '+' || c
== '-') &&
3876 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
3879 /* We add a trailing '\0' to ease parsing */
3880 cstr_ccat(&tokcstr
, '\0');
3881 tokc
.cstr
= &tokcstr
;
3885 /* special dot handling because it can also start a number */
3888 cstr_reset(&tokcstr
);
3889 cstr_ccat(&tokcstr
, '.');
3891 } else if (c
== '.') {
3911 /* parse the string */
3913 p
= parse_pp_string(p
, sep
, &str
);
3914 cstr_ccat(&str
, '\0');
3916 /* eval the escape (should be done as TOK_PPNUM) */
3917 cstr_reset(&tokcstr
);
3918 parse_escape_string(&tokcstr
, str
.data
, is_long
);
3923 /* XXX: make it portable */
3927 char_size
= sizeof(nwchar_t
);
3928 if (tokcstr
.size
<= char_size
)
3929 error("empty character constant");
3930 if (tokcstr
.size
> 2 * char_size
)
3931 warning("multi-character character constant");
3933 tokc
.i
= *(int8_t *)tokcstr
.data
;
3936 tokc
.i
= *(nwchar_t
*)tokcstr
.data
;
3940 tokc
.cstr
= &tokcstr
;
3954 } else if (c
== '<') {
3972 } else if (c
== '>') {
3990 } else if (c
== '=') {
4003 } else if (c
== '=') {
4016 } else if (c
== '=') {
4029 } else if (c
== '=') {
4032 } else if (c
== '>') {
4040 PARSE2('!', '!', '=', TOK_NE
)
4041 PARSE2('=', '=', '=', TOK_EQ
)
4042 PARSE2('*', '*', '=', TOK_A_MUL
)
4043 PARSE2('%', '%', '=', TOK_A_MOD
)
4044 PARSE2('^', '^', '=', TOK_A_XOR
)
4046 /* comments or operator */
4050 p
= parse_comment(p
);
4052 } else if (c
== '/') {
4053 p
= parse_line_comment(p
);
4055 } else if (c
== '=') {
4075 case '$': /* only used in assembler */
4076 case '@': /* dito */
4081 error("unrecognized character \\x%02x", c
);
4087 #if defined(PARSE_DEBUG)
4088 printf("token = %s\n", get_tok_str(tok
, &tokc
));
4092 /* return next token without macro substitution. Can read input from
4094 static void next_nomacro(void)
4100 TOK_GET(tok
, macro_ptr
, tokc
);
4101 if (tok
== TOK_LINENUM
) {
4102 file
->line_num
= tokc
.i
;
4111 /* substitute args in macro_str and return allocated string */
4112 static int *macro_arg_subst(Sym
**nested_list
, int *macro_str
, Sym
*args
)
4114 int *st
, last_tok
, t
, notfirst
;
4123 TOK_GET(t
, macro_str
, cval
);
4128 TOK_GET(t
, macro_str
, cval
);
4131 s
= sym_find2(args
, t
);
4138 cstr_ccat(&cstr
, ' ');
4139 TOK_GET(t
, st
, cval
);
4140 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
4145 cstr_ccat(&cstr
, '\0');
4147 printf("stringize: %s\n", (char *)cstr
.data
);
4151 tok_str_add2(&str
, TOK_STR
, &cval
);
4154 tok_str_add2(&str
, t
, &cval
);
4156 } else if (t
>= TOK_IDENT
) {
4157 s
= sym_find2(args
, t
);
4160 /* if '##' is present before or after, no arg substitution */
4161 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
4162 /* special case for var arg macros : ## eats the
4163 ',' if empty VA_ARGS variable. */
4164 /* XXX: test of the ',' is not 100%
4165 reliable. should fix it to avoid security
4167 if (gnu_ext
&& s
->type
.t
&&
4168 last_tok
== TOK_TWOSHARPS
&&
4169 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
4171 /* suppress ',' '##' */
4174 /* suppress '##' and add variable */
4182 TOK_GET(t1
, st
, cval
);
4185 tok_str_add2(&str
, t1
, &cval
);
4189 /* NOTE: the stream cannot be read when macro
4190 substituing an argument */
4191 macro_subst(&str
, nested_list
, st
, NULL
);
4194 tok_str_add(&str
, t
);
4197 tok_str_add2(&str
, t
, &cval
);
4201 tok_str_add(&str
, 0);
4205 static char const ab_month_name
[12][4] =
4207 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
4208 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
4211 /* do macro substitution of current token with macro 's' and add
4212 result to (tok_str,tok_len). 'nested_list' is the list of all
4213 macros we got inside to avoid recursing. Return non zero if no
4214 substitution needs to be done */
4215 static int macro_subst_tok(TokenString
*tok_str
,
4216 Sym
**nested_list
, Sym
*s
, struct macro_level
**can_read_stream
)
4218 Sym
*args
, *sa
, *sa1
;
4219 int mstr_allocated
, parlevel
, *mstr
, t
, t1
;
4226 /* if symbol is a macro, prepare substitution */
4227 /* special macros */
4228 if (tok
== TOK___LINE__
) {
4229 snprintf(buf
, sizeof(buf
), "%d", file
->line_num
);
4233 } else if (tok
== TOK___FILE__
) {
4234 cstrval
= file
->filename
;
4236 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
4241 tm
= localtime(&ti
);
4242 if (tok
== TOK___DATE__
) {
4243 snprintf(buf
, sizeof(buf
), "%s %2d %d",
4244 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
4246 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
4247 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
4254 cstr_cat(&cstr
, cstrval
);
4255 cstr_ccat(&cstr
, '\0');
4257 tok_str_add2(tok_str
, t1
, &cval
);
4262 if (s
->type
.t
== MACRO_FUNC
) {
4263 /* NOTE: we do not use next_nomacro to avoid eating the
4264 next token. XXX: find better solution */
4268 if (t
== 0 && can_read_stream
) {
4269 /* end of macro stream: we must look at the token
4270 after in the file */
4271 struct macro_level
*ml
= *can_read_stream
;
4277 *can_read_stream
= ml
-> prev
;
4282 /* XXX: incorrect with comments */
4283 ch
= file
->buf_ptr
[0];
4284 while (is_space(ch
) || ch
== '\n')
4288 if (t
!= '(') /* no macro subst */
4291 /* argument macro */
4296 /* NOTE: empty args are allowed, except if no args */
4298 /* handle '()' case */
4299 if (!args
&& !sa
&& tok
== ')')
4302 error("macro '%s' used with too many args",
4303 get_tok_str(s
->v
, 0));
4306 /* NOTE: non zero sa->t indicates VA_ARGS */
4307 while ((parlevel
> 0 ||
4309 (tok
!= ',' || sa
->type
.t
))) &&
4313 else if (tok
== ')')
4315 if (tok
!= TOK_LINEFEED
)
4316 tok_str_add2(&str
, tok
, &tokc
);
4319 tok_str_add(&str
, 0);
4320 sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, (long)str
.str
);
4323 /* special case for gcc var args: add an empty
4324 var arg argument if it is omitted */
4325 if (sa
&& sa
->type
.t
&& gnu_ext
)
4335 error("macro '%s' used with too few args",
4336 get_tok_str(s
->v
, 0));
4339 /* now subst each arg */
4340 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
4345 tok_str_free((int *)sa
->c
);
4351 sym_push2(nested_list
, s
->v
, 0, 0);
4352 macro_subst(tok_str
, nested_list
, mstr
, can_read_stream
);
4353 /* pop nested defined symbol */
4355 *nested_list
= sa1
->prev
;
4363 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
4364 return the resulting string (which must be freed). */
4365 static inline int *macro_twosharps(const int *macro_str
)
4368 const int *macro_ptr1
, *start_macro_ptr
, *ptr
, *saved_macro_ptr
;
4370 const char *p1
, *p2
;
4372 TokenString macro_str1
;
4375 start_macro_ptr
= macro_str
;
4376 /* we search the first '##' */
4378 macro_ptr1
= macro_str
;
4379 TOK_GET(t
, macro_str
, cval
);
4380 /* nothing more to do if end of string */
4383 if (*macro_str
== TOK_TWOSHARPS
)
4387 /* we saw '##', so we need more processing to handle it */
4389 tok_str_new(¯o_str1
);
4393 /* add all tokens seen so far */
4394 for(ptr
= start_macro_ptr
; ptr
< macro_ptr1
;) {
4395 TOK_GET(t
, ptr
, cval
);
4396 tok_str_add2(¯o_str1
, t
, &cval
);
4398 saved_macro_ptr
= macro_ptr
;
4399 /* XXX: get rid of the use of macro_ptr here */
4400 macro_ptr
= (int *)macro_str
;
4402 while (*macro_ptr
== TOK_TWOSHARPS
) {
4404 macro_ptr1
= macro_ptr
;
4407 TOK_GET(t
, macro_ptr
, cval
);
4408 /* We concatenate the two tokens if we have an
4409 identifier or a preprocessing number */
4411 p1
= get_tok_str(tok
, &tokc
);
4412 cstr_cat(&cstr
, p1
);
4413 p2
= get_tok_str(t
, &cval
);
4414 cstr_cat(&cstr
, p2
);
4415 cstr_ccat(&cstr
, '\0');
4417 if ((tok
>= TOK_IDENT
|| tok
== TOK_PPNUM
) &&
4418 (t
>= TOK_IDENT
|| t
== TOK_PPNUM
)) {
4419 if (tok
== TOK_PPNUM
) {
4420 /* if number, then create a number token */
4421 /* NOTE: no need to allocate because
4422 tok_str_add2() does it */
4423 cstr_reset(&tokcstr
);
4426 tokc
.cstr
= &tokcstr
;
4428 /* if identifier, we must do a test to
4429 validate we have a correct identifier */
4430 if (t
== TOK_PPNUM
) {
4440 if (!isnum(c
) && !isid(c
))
4444 ts
= tok_alloc(cstr
.data
, strlen(cstr
.data
));
4445 tok
= ts
->tok
; /* modify current token */
4448 const char *str
= cstr
.data
;
4449 const unsigned char *q
;
4451 /* we look for a valid token */
4452 /* XXX: do more extensive checks */
4453 if (!strcmp(str
, ">>=")) {
4455 } else if (!strcmp(str
, "<<=")) {
4457 } else if (strlen(str
) == 2) {
4458 /* search in two bytes table */
4463 if (q
[0] == str
[0] && q
[1] == str
[1])
4470 /* NOTE: because get_tok_str use a static buffer,
4473 p1
= get_tok_str(tok
, &tokc
);
4474 cstr_cat(&cstr
, p1
);
4475 cstr_ccat(&cstr
, '\0');
4476 p2
= get_tok_str(t
, &cval
);
4477 warning("pasting \"%s\" and \"%s\" does not give a valid preprocessing token", cstr
.data
, p2
);
4478 /* cannot merge tokens: just add them separately */
4479 tok_str_add2(¯o_str1
, tok
, &tokc
);
4480 /* XXX: free associated memory ? */
4487 tok_str_add2(¯o_str1
, tok
, &tokc
);
4492 macro_ptr
= (int *)saved_macro_ptr
;
4494 tok_str_add(¯o_str1
, 0);
4495 return macro_str1
.str
;
4499 /* do macro substitution of macro_str and add result to
4500 (tok_str,tok_len). 'nested_list' is the list of all macros we got
4501 inside to avoid recursing. */
4502 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
4503 const int *macro_str
, struct macro_level
** can_read_stream
)
4510 struct macro_level ml
;
4512 /* first scan for '##' operator handling */
4514 macro_str1
= macro_twosharps(ptr
);
4518 /* NOTE: ptr == NULL can only happen if tokens are read from
4519 file stream due to a macro function call */
4522 TOK_GET(t
, ptr
, cval
);
4527 /* if nested substitution, do nothing */
4528 if (sym_find2(*nested_list
, t
))
4531 if (can_read_stream
)
4532 ml
.prev
= *can_read_stream
, *can_read_stream
= &ml
;
4533 macro_ptr
= (int *)ptr
;
4535 ret
= macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
4536 ptr
= (int *)macro_ptr
;
4538 if (can_read_stream
&& *can_read_stream
== &ml
)
4539 *can_read_stream
= ml
.prev
;
4544 tok_str_add2(tok_str
, t
, &cval
);
4548 tok_str_free(macro_str1
);
4551 /* return next token with macro substitution */
4552 static void next(void)
4554 Sym
*nested_list
, *s
;
4556 struct macro_level
*ml
;
4561 /* if not reading from macro substituted string, then try
4562 to substitute macros */
4563 if (tok
>= TOK_IDENT
&&
4564 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
4565 s
= define_find(tok
);
4567 /* we have a macro: we try to substitute */
4571 if (macro_subst_tok(&str
, &nested_list
, s
, &ml
) == 0) {
4572 /* substitution done, NOTE: maybe empty */
4573 tok_str_add(&str
, 0);
4574 macro_ptr
= str
.str
;
4575 macro_ptr_allocated
= str
.str
;
4582 /* end of macro or end of unget buffer */
4583 if (unget_buffer_enabled
) {
4584 macro_ptr
= unget_saved_macro_ptr
;
4585 unget_buffer_enabled
= 0;
4587 /* end of macro string: free it */
4588 tok_str_free(macro_ptr_allocated
);
4595 /* convert preprocessor tokens into C tokens */
4596 if (tok
== TOK_PPNUM
&&
4597 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
4598 parse_number((char *)tokc
.cstr
->data
);
4602 /* push back current token and set current token to 'last_tok'. Only
4603 identifier case handled for labels. */
4604 static inline void unget_tok(int last_tok
)
4608 unget_saved_macro_ptr
= macro_ptr
;
4609 unget_buffer_enabled
= 1;
4610 q
= unget_saved_buffer
;
4613 n
= tok_ext_size(tok
) - 1;
4616 *q
= 0; /* end of token string */
4621 void swap(int *p
, int *q
)
4629 void vsetc(CType
*type
, int r
, CValue
*vc
)
4633 if (vtop
>= vstack
+ (VSTACK_SIZE
- 1))
4634 error("memory full");
4635 /* cannot let cpu flags if other instruction are generated. Also
4636 avoid leaving VT_JMP anywhere except on the top of the stack
4637 because it would complicate the code generator. */
4638 if (vtop
>= vstack
) {
4639 v
= vtop
->r
& VT_VALMASK
;
4640 if (v
== VT_CMP
|| (v
& ~1) == VT_JMP
)
4646 vtop
->r2
= VT_CONST
;
4650 /* push integer constant */
4655 vsetc(&int_type
, VT_CONST
, &cval
);
4658 /* Return a static symbol pointing to a section */
4659 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
4660 unsigned long offset
, unsigned long size
)
4666 sym
= global_identifier_push(v
, type
->t
| VT_STATIC
, 0);
4667 sym
->type
.ref
= type
->ref
;
4668 sym
->r
= VT_CONST
| VT_SYM
;
4669 put_extern_sym(sym
, sec
, offset
, size
);
4673 /* push a reference to a section offset by adding a dummy symbol */
4674 static void vpush_ref(CType
*type
, Section
*sec
, unsigned long offset
, unsigned long size
)
4679 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4680 vtop
->sym
= get_sym_ref(type
, sec
, offset
, size
);
4683 /* define a new external reference to a symbol 'v' of type 'u' */
4684 static Sym
*external_global_sym(int v
, CType
*type
, int r
)
4690 /* push forward reference */
4691 s
= global_identifier_push(v
, type
->t
| VT_EXTERN
, 0);
4692 s
->type
.ref
= type
->ref
;
4693 s
->r
= r
| VT_CONST
| VT_SYM
;
4698 /* define a new external reference to a symbol 'v' of type 'u' */
4699 static Sym
*external_sym(int v
, CType
*type
, int r
)
4705 /* push forward reference */
4706 s
= sym_push(v
, type
, r
| VT_CONST
| VT_SYM
, 0);
4707 s
->type
.t
|= VT_EXTERN
;
4709 if (!is_compatible_types(&s
->type
, type
))
4710 error("incompatible types for redefinition of '%s'",
4711 get_tok_str(v
, NULL
));
4716 /* push a reference to global symbol v */
4717 static void vpush_global_sym(CType
*type
, int v
)
4722 sym
= external_global_sym(v
, type
, 0);
4724 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4728 void vset(CType
*type
, int r
, int v
)
4733 vsetc(type
, r
, &cval
);
4736 void vseti(int r
, int v
)
4752 void vpushv(SValue
*v
)
4754 if (vtop
>= vstack
+ (VSTACK_SIZE
- 1))
4755 error("memory full");
4765 /* save r to the memory stack, and mark it as being free */
4766 void save_reg(int r
)
4768 int l
, saved
, size
, align
;
4772 /* modify all stack values */
4775 for(p
=vstack
;p
<=vtop
;p
++) {
4776 if ((p
->r
& VT_VALMASK
) == r
||
4777 ((p
->type
.t
& VT_BTYPE
) == VT_LLONG
&& (p
->r2
& VT_VALMASK
) == r
)) {
4778 /* must save value on stack if not already done */
4780 /* NOTE: must reload 'r' because r might be equal to r2 */
4781 r
= p
->r
& VT_VALMASK
;
4782 /* store register in the stack */
4784 #ifndef TCC_TARGET_X86_64
4785 if ((p
->r
& VT_LVAL
) ||
4786 (!is_float(type
->t
) && (type
->t
& VT_BTYPE
) != VT_LLONG
))
4790 type
= &char_pointer_type
;
4792 size
= type_size(type
, &align
);
4793 loc
= (loc
- size
) & -align
;
4794 sv
.type
.t
= type
->t
;
4795 sv
.r
= VT_LOCAL
| VT_LVAL
;
4798 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
4799 /* x86 specific: need to pop fp register ST0 if saved */
4800 if (r
== TREG_ST0
) {
4801 o(0xd9dd); /* fstp %st(1) */
4804 #ifndef TCC_TARGET_X86_64
4805 /* special long long case */
4806 if ((type
->t
& VT_BTYPE
) == VT_LLONG
) {
4814 /* mark that stack entry as being saved on the stack */
4815 if (p
->r
& VT_LVAL
) {
4816 /* also clear the bounded flag because the
4817 relocation address of the function was stored in
4819 p
->r
= (p
->r
& ~(VT_VALMASK
| VT_BOUNDED
)) | VT_LLOCAL
;
4821 p
->r
= lvalue_type(p
->type
.t
) | VT_LOCAL
;
4829 /* find a register of class 'rc2' with at most one reference on stack.
4830 * If none, call get_reg(rc) */
4831 int get_reg_ex(int rc
, int rc2
)
4836 for(r
=0;r
<NB_REGS
;r
++) {
4837 if (reg_classes
[r
] & rc2
) {
4840 for(p
= vstack
; p
<= vtop
; p
++) {
4841 if ((p
->r
& VT_VALMASK
) == r
||
4842 (p
->r2
& VT_VALMASK
) == r
)
4852 /* find a free register of class 'rc'. If none, save one register */
4858 /* find a free register */
4859 for(r
=0;r
<NB_REGS
;r
++) {
4860 if (reg_classes
[r
] & rc
) {
4861 for(p
=vstack
;p
<=vtop
;p
++) {
4862 if ((p
->r
& VT_VALMASK
) == r
||
4863 (p
->r2
& VT_VALMASK
) == r
)
4871 /* no register left : free the first one on the stack (VERY
4872 IMPORTANT to start from the bottom to ensure that we don't
4873 spill registers used in gen_opi()) */
4874 for(p
=vstack
;p
<=vtop
;p
++) {
4875 r
= p
->r
& VT_VALMASK
;
4876 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
))
4878 /* also look at second register (if long long) */
4879 r
= p
->r2
& VT_VALMASK
;
4880 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
)) {
4886 /* Should never comes here */
4890 /* save registers up to (vtop - n) stack entry */
4891 void save_regs(int n
)
4896 for(p
= vstack
;p
<= p1
; p
++) {
4897 r
= p
->r
& VT_VALMASK
;
4904 /* move register 's' to 'r', and flush previous value of r to memory
4906 void move_reg(int r
, int s
)
4919 /* get address of vtop (vtop MUST BE an lvalue) */
4922 vtop
->r
&= ~VT_LVAL
;
4923 /* tricky: if saved lvalue, then we can go back to lvalue */
4924 if ((vtop
->r
& VT_VALMASK
) == VT_LLOCAL
)
4925 vtop
->r
= (vtop
->r
& ~(VT_VALMASK
| VT_LVAL_TYPE
)) | VT_LOCAL
| VT_LVAL
;
4928 #ifdef CONFIG_TCC_BCHECK
4929 /* generate lvalue bound code */
4935 vtop
->r
&= ~VT_MUSTBOUND
;
4936 /* if lvalue, then use checking code before dereferencing */
4937 if (vtop
->r
& VT_LVAL
) {
4938 /* if not VT_BOUNDED value, then make one */
4939 if (!(vtop
->r
& VT_BOUNDED
)) {
4940 lval_type
= vtop
->r
& (VT_LVAL_TYPE
| VT_LVAL
);
4941 /* must save type because we must set it to int to get pointer */
4943 vtop
->type
.t
= VT_INT
;
4946 gen_bounded_ptr_add();
4947 vtop
->r
|= lval_type
;
4950 /* then check for dereferencing */
4951 gen_bounded_ptr_deref();
4956 /* store vtop a register belonging to class 'rc'. lvalues are
4957 converted to values. Cannot be used if cannot be converted to
4958 register value (such as structures). */
4961 int r
, rc2
, bit_pos
, bit_size
, size
, align
, i
;
4963 /* NOTE: get_reg can modify vstack[] */
4964 if (vtop
->type
.t
& VT_BITFIELD
) {
4966 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
4967 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
4968 /* remove bit field info to avoid loops */
4969 vtop
->type
.t
&= ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
4970 /* cast to int to propagate signedness in following ops */
4972 if((vtop
->type
.t
& VT_UNSIGNED
) ||
4973 (vtop
->type
.t
& VT_BTYPE
) == VT_BOOL
)
4974 type
.t
|= VT_UNSIGNED
;
4976 /* generate shifts */
4977 vpushi(32 - (bit_pos
+ bit_size
));
4979 vpushi(32 - bit_size
);
4980 /* NOTE: transformed to SHR if unsigned */
4984 if (is_float(vtop
->type
.t
) &&
4985 (vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4988 unsigned long offset
;
4989 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
4993 /* XXX: unify with initializers handling ? */
4994 /* CPUs usually cannot use float constants, so we store them
4995 generically in data segment */
4996 size
= type_size(&vtop
->type
, &align
);
4997 offset
= (data_section
->data_offset
+ align
- 1) & -align
;
4998 data_section
->data_offset
= offset
;
4999 /* XXX: not portable yet */
5000 #if defined(__i386__) || defined(__x86_64__)
5001 /* Zero pad x87 tenbyte long doubles */
5002 if (size
== LDOUBLE_SIZE
)
5003 vtop
->c
.tab
[2] &= 0xffff;
5005 ptr
= section_ptr_add(data_section
, size
);
5007 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
5011 ptr
[i
] = vtop
->c
.tab
[size
-1-i
];
5015 ptr
[i
] = vtop
->c
.tab
[i
];
5016 sym
= get_sym_ref(&vtop
->type
, data_section
, offset
, size
<< 2);
5017 vtop
->r
|= VT_LVAL
| VT_SYM
;
5021 #ifdef CONFIG_TCC_BCHECK
5022 if (vtop
->r
& VT_MUSTBOUND
)
5026 r
= vtop
->r
& VT_VALMASK
;
5030 /* need to reload if:
5032 - lvalue (need to dereference pointer)
5033 - already a register, but not in the right class */
5034 if (r
>= VT_CONST
||
5035 (vtop
->r
& VT_LVAL
) ||
5036 !(reg_classes
[r
] & rc
) ||
5037 ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
&&
5038 !(reg_classes
[vtop
->r2
] & rc2
))) {
5040 #ifndef TCC_TARGET_X86_64
5041 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
) {
5043 unsigned long long ll
;
5044 /* two register type load : expand to two words
5046 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
5049 vtop
->c
.ui
= ll
; /* first word */
5051 vtop
->r
= r
; /* save register value */
5052 vpushi(ll
>> 32); /* second word */
5053 } else if (r
>= VT_CONST
|| /* XXX: test to VT_CONST incorrect ? */
5054 (vtop
->r
& VT_LVAL
)) {
5055 /* We do not want to modifier the long long
5056 pointer here, so the safest (and less
5057 efficient) is to save all the other registers
5058 in the stack. XXX: totally inefficient. */
5060 /* load from memory */
5063 vtop
[-1].r
= r
; /* save register value */
5064 /* increment pointer to get second word */
5065 vtop
->type
.t
= VT_INT
;
5071 /* move registers */
5074 vtop
[-1].r
= r
; /* save register value */
5075 vtop
->r
= vtop
[-1].r2
;
5077 /* allocate second register */
5081 /* write second register */
5085 if ((vtop
->r
& VT_LVAL
) && !is_float(vtop
->type
.t
)) {
5087 /* lvalue of scalar type : need to use lvalue type
5088 because of possible cast */
5091 /* compute memory access type */
5092 if (vtop
->r
& VT_LVAL_BYTE
)
5094 else if (vtop
->r
& VT_LVAL_SHORT
)
5096 if (vtop
->r
& VT_LVAL_UNSIGNED
)
5100 /* restore wanted type */
5103 /* one register type load */
5108 #ifdef TCC_TARGET_C67
5109 /* uses register pairs for doubles */
5110 if ((vtop
->type
.t
& VT_BTYPE
) == VT_DOUBLE
)
5117 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
5118 void gv2(int rc1
, int rc2
)
5122 /* generate more generic register first. But VT_JMP or VT_CMP
5123 values must be generated first in all cases to avoid possible
5125 v
= vtop
[0].r
& VT_VALMASK
;
5126 if (v
!= VT_CMP
&& (v
& ~1) != VT_JMP
&& rc1
<= rc2
) {
5131 /* test if reload is needed for first register */
5132 if ((vtop
[-1].r
& VT_VALMASK
) >= VT_CONST
) {
5142 /* test if reload is needed for first register */
5143 if ((vtop
[0].r
& VT_VALMASK
) >= VT_CONST
) {
5149 /* expand long long on stack in two int registers */
5154 u
= vtop
->type
.t
& VT_UNSIGNED
;
5157 vtop
[0].r
= vtop
[-1].r2
;
5158 vtop
[0].r2
= VT_CONST
;
5159 vtop
[-1].r2
= VT_CONST
;
5160 vtop
[0].type
.t
= VT_INT
| u
;
5161 vtop
[-1].type
.t
= VT_INT
| u
;
5164 #ifdef TCC_TARGET_ARM
5165 /* expand long long on stack */
5166 void lexpand_nr(void)
5170 u
= vtop
->type
.t
& VT_UNSIGNED
;
5172 vtop
->r2
= VT_CONST
;
5173 vtop
->type
.t
= VT_INT
| u
;
5174 v
=vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
);
5175 if (v
== VT_CONST
) {
5176 vtop
[-1].c
.ui
= vtop
->c
.ull
;
5177 vtop
->c
.ui
= vtop
->c
.ull
>> 32;
5179 } else if (v
== (VT_LVAL
|VT_CONST
) || v
== (VT_LVAL
|VT_LOCAL
)) {
5181 vtop
->r
= vtop
[-1].r
;
5182 } else if (v
> VT_CONST
) {
5186 vtop
->r
= vtop
[-1].r2
;
5187 vtop
[-1].r2
= VT_CONST
;
5188 vtop
[-1].type
.t
= VT_INT
| u
;
5192 /* build a long long from two ints */
5195 gv2(RC_INT
, RC_INT
);
5196 vtop
[-1].r2
= vtop
[0].r
;
5197 vtop
[-1].type
.t
= t
;
5201 /* rotate n first stack elements to the bottom
5202 I1 ... In -> I2 ... In I1 [top is right]
5210 for(i
=-n
+1;i
!=0;i
++)
5211 vtop
[i
] = vtop
[i
+1];
5215 /* rotate n first stack elements to the top
5216 I1 ... In -> In I1 ... I(n-1) [top is right]
5224 for(i
= 0;i
< n
- 1; i
++)
5225 vtop
[-i
] = vtop
[-i
- 1];
5229 #ifdef TCC_TARGET_ARM
5230 /* like vrott but in other direction
5231 In ... I1 -> I(n-1) ... I1 In [top is right]
5239 for(i
= n
- 1; i
> 0; i
--)
5240 vtop
[-i
] = vtop
[-i
+ 1];
5245 /* pop stack value */
5249 v
= vtop
->r
& VT_VALMASK
;
5250 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
5251 /* for x86, we need to pop the FP stack */
5252 if (v
== TREG_ST0
&& !nocode_wanted
) {
5253 o(0xd9dd); /* fstp %st(1) */
5256 if (v
== VT_JMP
|| v
== VT_JMPI
) {
5257 /* need to put correct jump if && or || without test */
5263 /* convert stack entry to register and duplicate its value in another
5271 if ((t
& VT_BTYPE
) == VT_LLONG
) {
5278 /* stack: H L L1 H1 */
5286 /* duplicate value */
5291 #ifdef TCC_TARGET_X86_64
5292 if ((t
& VT_BTYPE
) == VT_LDOUBLE
) {
5302 load(r1
, &sv
); /* move r to r1 */
5304 /* duplicates value */
5309 #ifndef TCC_TARGET_X86_64
5310 /* generate CPU independent (unsigned) long long operations */
5311 void gen_opl(int op
)
5313 int t
, a
, b
, op1
, c
, i
;
5315 unsigned short reg_iret
= REG_IRET
;
5316 unsigned short reg_lret
= REG_LRET
;
5322 func
= TOK___divdi3
;
5325 func
= TOK___udivdi3
;
5328 func
= TOK___moddi3
;
5331 func
= TOK___umoddi3
;
5338 /* call generic long long function */
5339 vpush_global_sym(&func_old_type
, func
);
5344 vtop
->r2
= reg_lret
;
5357 /* stack: L1 H1 L2 H2 */
5362 vtop
[-2] = vtop
[-3];
5365 /* stack: H1 H2 L1 L2 */
5371 /* stack: H1 H2 L1 L2 ML MH */
5374 /* stack: ML MH H1 H2 L1 L2 */
5378 /* stack: ML MH H1 L2 H2 L1 */
5383 /* stack: ML MH M1 M2 */
5386 } else if (op
== '+' || op
== '-') {
5387 /* XXX: add non carry method too (for MIPS or alpha) */
5393 /* stack: H1 H2 (L1 op L2) */
5396 gen_op(op1
+ 1); /* TOK_xxxC2 */
5399 /* stack: H1 H2 (L1 op L2) */
5402 /* stack: (L1 op L2) H1 H2 */
5404 /* stack: (L1 op L2) (H1 op H2) */
5412 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) {
5413 t
= vtop
[-1].type
.t
;
5417 /* stack: L H shift */
5419 /* constant: simpler */
5420 /* NOTE: all comments are for SHL. the other cases are
5421 done by swaping words */
5432 if (op
!= TOK_SAR
) {
5465 /* XXX: should provide a faster fallback on x86 ? */
5468 func
= TOK___ashrdi3
;
5471 func
= TOK___lshrdi3
;
5474 func
= TOK___ashldi3
;
5480 /* compare operations */
5486 /* stack: L1 H1 L2 H2 */
5488 vtop
[-1] = vtop
[-2];
5490 /* stack: L1 L2 H1 H2 */
5493 /* when values are equal, we need to compare low words. since
5494 the jump is inverted, we invert the test too. */
5497 else if (op1
== TOK_GT
)
5499 else if (op1
== TOK_ULT
)
5501 else if (op1
== TOK_UGT
)
5506 if (op1
!= TOK_NE
) {
5510 /* generate non equal test */
5511 /* XXX: NOT PORTABLE yet */
5515 #if defined(TCC_TARGET_I386)
5516 b
= psym(0x850f, 0);
5517 #elif defined(TCC_TARGET_ARM)
5519 o(0x1A000000 | encbranch(ind
, 0, 1));
5520 #elif defined(TCC_TARGET_C67)
5521 error("not implemented");
5523 #error not supported
5527 /* compare low. Always unsigned */
5531 else if (op1
== TOK_LE
)
5533 else if (op1
== TOK_GT
)
5535 else if (op1
== TOK_GE
)
5546 /* handle integer constant optimizations and various machine
5548 void gen_opic(int op
)
5550 int c1
, c2
, t1
, t2
, n
;
5553 typedef unsigned long long U
;
5557 t1
= v1
->type
.t
& VT_BTYPE
;
5558 t2
= v2
->type
.t
& VT_BTYPE
;
5562 else if (v1
->type
.t
& VT_UNSIGNED
)
5569 else if (v2
->type
.t
& VT_UNSIGNED
)
5574 /* currently, we cannot do computations with forward symbols */
5575 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5576 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5579 case '+': l1
+= l2
; break;
5580 case '-': l1
-= l2
; break;
5581 case '&': l1
&= l2
; break;
5582 case '^': l1
^= l2
; break;
5583 case '|': l1
|= l2
; break;
5584 case '*': l1
*= l2
; break;
5591 /* if division by zero, generate explicit division */
5594 error("division by zero in constant");
5598 default: l1
/= l2
; break;
5599 case '%': l1
%= l2
; break;
5600 case TOK_UDIV
: l1
= (U
)l1
/ l2
; break;
5601 case TOK_UMOD
: l1
= (U
)l1
% l2
; break;
5604 case TOK_SHL
: l1
<<= l2
; break;
5605 case TOK_SHR
: l1
= (U
)l1
>> l2
; break;
5606 case TOK_SAR
: l1
>>= l2
; break;
5608 case TOK_ULT
: l1
= (U
)l1
< (U
)l2
; break;
5609 case TOK_UGE
: l1
= (U
)l1
>= (U
)l2
; break;
5610 case TOK_EQ
: l1
= l1
== l2
; break;
5611 case TOK_NE
: l1
= l1
!= l2
; break;
5612 case TOK_ULE
: l1
= (U
)l1
<= (U
)l2
; break;
5613 case TOK_UGT
: l1
= (U
)l1
> (U
)l2
; break;
5614 case TOK_LT
: l1
= l1
< l2
; break;
5615 case TOK_GE
: l1
= l1
>= l2
; break;
5616 case TOK_LE
: l1
= l1
<= l2
; break;
5617 case TOK_GT
: l1
= l1
> l2
; break;
5619 case TOK_LAND
: l1
= l1
&& l2
; break;
5620 case TOK_LOR
: l1
= l1
|| l2
; break;
5627 /* if commutative ops, put c2 as constant */
5628 if (c1
&& (op
== '+' || op
== '&' || op
== '^' ||
5629 op
== '|' || op
== '*')) {
5631 c2
= c1
; //c = c1, c1 = c2, c2 = c;
5632 l2
= l1
; //l = l1, l1 = l2, l2 = l;
5634 /* Filter out NOP operations like x*1, x-0, x&-1... */
5635 if (c2
&& (((op
== '*' || op
== '/' || op
== TOK_UDIV
||
5638 ((op
== '+' || op
== '-' || op
== '|' || op
== '^' ||
5639 op
== TOK_SHL
|| op
== TOK_SHR
|| op
== TOK_SAR
) &&
5645 } else if (c2
&& (op
== '*' || op
== TOK_PDIV
|| op
== TOK_UDIV
)) {
5646 /* try to use shifts instead of muls or divs */
5647 if (l2
> 0 && (l2
& (l2
- 1)) == 0) {
5656 else if (op
== TOK_PDIV
)
5662 } else if (c2
&& (op
== '+' || op
== '-') &&
5663 ((vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) ==
5664 (VT_CONST
| VT_SYM
) ||
5665 (vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
)) == VT_LOCAL
)) {
5666 /* symbol + constant case */
5673 if (!nocode_wanted
) {
5674 /* call low level op generator */
5675 if (t1
== VT_LLONG
|| t2
== VT_LLONG
)
5686 /* generate a floating point operation with constant propagation */
5687 void gen_opif(int op
)
5695 /* currently, we cannot do computations with forward symbols */
5696 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5697 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5699 if (v1
->type
.t
== VT_FLOAT
) {
5702 } else if (v1
->type
.t
== VT_DOUBLE
) {
5710 /* NOTE: we only do constant propagation if finite number (not
5711 NaN or infinity) (ANSI spec) */
5712 if (!ieee_finite(f1
) || !ieee_finite(f2
))
5716 case '+': f1
+= f2
; break;
5717 case '-': f1
-= f2
; break;
5718 case '*': f1
*= f2
; break;
5722 error("division by zero in constant");
5727 /* XXX: also handles tests ? */
5731 /* XXX: overflow test ? */
5732 if (v1
->type
.t
== VT_FLOAT
) {
5734 } else if (v1
->type
.t
== VT_DOUBLE
) {
5742 if (!nocode_wanted
) {
5750 static int pointed_size(CType
*type
)
5753 return type_size(pointed_type(type
), &align
);
5756 static inline int is_null_pointer(SValue
*p
)
5758 if ((p
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
5760 return ((p
->type
.t
& VT_BTYPE
) == VT_INT
&& p
->c
.i
== 0) ||
5761 ((p
->type
.t
& VT_BTYPE
) == VT_LLONG
&& p
->c
.ll
== 0);
5764 static inline int is_integer_btype(int bt
)
5766 return (bt
== VT_BYTE
|| bt
== VT_SHORT
||
5767 bt
== VT_INT
|| bt
== VT_LLONG
);
5770 /* check types for comparison or substraction of pointers */
5771 static void check_comparison_pointer_types(SValue
*p1
, SValue
*p2
, int op
)
5773 CType
*type1
, *type2
, tmp_type1
, tmp_type2
;
5776 /* null pointers are accepted for all comparisons as gcc */
5777 if (is_null_pointer(p1
) || is_null_pointer(p2
))
5781 bt1
= type1
->t
& VT_BTYPE
;
5782 bt2
= type2
->t
& VT_BTYPE
;
5783 /* accept comparison between pointer and integer with a warning */
5784 if ((is_integer_btype(bt1
) || is_integer_btype(bt2
)) && op
!= '-') {
5785 if (op
!= TOK_LOR
&& op
!= TOK_LAND
)
5786 warning("comparison between pointer and integer");
5790 /* both must be pointers or implicit function pointers */
5791 if (bt1
== VT_PTR
) {
5792 type1
= pointed_type(type1
);
5793 } else if (bt1
!= VT_FUNC
)
5794 goto invalid_operands
;
5796 if (bt2
== VT_PTR
) {
5797 type2
= pointed_type(type2
);
5798 } else if (bt2
!= VT_FUNC
) {
5800 error("invalid operands to binary %s", get_tok_str(op
, NULL
));
5802 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
5803 (type2
->t
& VT_BTYPE
) == VT_VOID
)
5807 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5808 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5809 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
5810 /* gcc-like error if '-' is used */
5812 goto invalid_operands
;
5814 warning("comparison of distinct pointer types lacks a cast");
5818 /* generic gen_op: handles types problems */
5821 int u
, t1
, t2
, bt1
, bt2
, t
;
5824 t1
= vtop
[-1].type
.t
;
5825 t2
= vtop
[0].type
.t
;
5826 bt1
= t1
& VT_BTYPE
;
5827 bt2
= t2
& VT_BTYPE
;
5829 if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
5830 /* at least one operand is a pointer */
5831 /* relationnal op: must be both pointers */
5832 if (op
>= TOK_ULT
&& op
<= TOK_LOR
) {
5833 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5834 /* pointers are handled are unsigned */
5835 #ifdef TCC_TARGET_X86_64
5836 t
= VT_LLONG
| VT_UNSIGNED
;
5838 t
= VT_INT
| VT_UNSIGNED
;
5842 /* if both pointers, then it must be the '-' op */
5843 if (bt1
== VT_PTR
&& bt2
== VT_PTR
) {
5845 error("cannot use pointers here");
5846 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5847 /* XXX: check that types are compatible */
5848 u
= pointed_size(&vtop
[-1].type
);
5850 /* set to integer type */
5851 #ifdef TCC_TARGET_X86_64
5852 vtop
->type
.t
= VT_LLONG
;
5854 vtop
->type
.t
= VT_INT
;
5859 /* exactly one pointer : must be '+' or '-'. */
5860 if (op
!= '-' && op
!= '+')
5861 error("cannot use pointers here");
5862 /* Put pointer as first operand */
5863 if (bt2
== VT_PTR
) {
5867 type1
= vtop
[-1].type
;
5868 #ifdef TCC_TARGET_X86_64
5873 cval
.ull
= pointed_size(&vtop
[-1].type
);
5874 vsetc(&ctype
, VT_CONST
, &cval
);
5877 /* XXX: cast to int ? (long long case) */
5878 vpushi(pointed_size(&vtop
[-1].type
));
5881 #ifdef CONFIG_TCC_BCHECK
5882 /* if evaluating constant expression, no code should be
5883 generated, so no bound check */
5884 if (do_bounds_check
&& !const_wanted
) {
5885 /* if bounded pointers, we generate a special code to
5892 gen_bounded_ptr_add();
5898 /* put again type if gen_opic() swaped operands */
5901 } else if (is_float(bt1
) || is_float(bt2
)) {
5902 /* compute bigger type and do implicit casts */
5903 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
5905 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
5910 /* floats can only be used for a few operations */
5911 if (op
!= '+' && op
!= '-' && op
!= '*' && op
!= '/' &&
5912 (op
< TOK_ULT
|| op
> TOK_GT
))
5913 error("invalid operands for binary operation");
5915 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
5916 /* cast to biggest op */
5918 /* convert to unsigned if it does not fit in a long long */
5919 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
5920 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
5924 /* integer operations */
5926 /* convert to unsigned if it does not fit in an integer */
5927 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
5928 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
5931 /* XXX: currently, some unsigned operations are explicit, so
5932 we modify them here */
5933 if (t
& VT_UNSIGNED
) {
5940 else if (op
== TOK_LT
)
5942 else if (op
== TOK_GT
)
5944 else if (op
== TOK_LE
)
5946 else if (op
== TOK_GE
)
5953 /* special case for shifts and long long: we keep the shift as
5955 if (op
== TOK_SHR
|| op
== TOK_SAR
|| op
== TOK_SHL
)
5962 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5963 /* relationnal op: the result is an int */
5964 vtop
->type
.t
= VT_INT
;
5971 #ifndef TCC_TARGET_ARM
5972 /* generic itof for unsigned long long case */
5973 void gen_cvt_itof1(int t
)
5975 if ((vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
)) ==
5976 (VT_LLONG
| VT_UNSIGNED
)) {
5979 vpush_global_sym(&func_old_type
, TOK___floatundisf
);
5980 #if LDOUBLE_SIZE != 8
5981 else if (t
== VT_LDOUBLE
)
5982 vpush_global_sym(&func_old_type
, TOK___floatundixf
);
5985 vpush_global_sym(&func_old_type
, TOK___floatundidf
);
5996 /* generic ftoi for unsigned long long case */
5997 void gen_cvt_ftoi1(int t
)
6001 if (t
== (VT_LLONG
| VT_UNSIGNED
)) {
6002 /* not handled natively */
6003 st
= vtop
->type
.t
& VT_BTYPE
;
6005 vpush_global_sym(&func_old_type
, TOK___fixunssfdi
);
6006 #if LDOUBLE_SIZE != 8
6007 else if (st
== VT_LDOUBLE
)
6008 vpush_global_sym(&func_old_type
, TOK___fixunsxfdi
);
6011 vpush_global_sym(&func_old_type
, TOK___fixunsdfdi
);
6016 vtop
->r2
= REG_LRET
;
6022 /* force char or short cast */
6023 void force_charshort_cast(int t
)
6027 /* XXX: add optimization if lvalue : just change type and offset */
6032 if (t
& VT_UNSIGNED
) {
6033 vpushi((1 << bits
) - 1);
6039 /* result must be signed or the SAR is converted to an SHL
6040 This was not the case when "t" was a signed short
6041 and the last value on the stack was an unsigned int */
6042 vtop
->type
.t
&= ~VT_UNSIGNED
;
6048 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
6049 static void gen_cast(CType
*type
)
6051 int sbt
, dbt
, sf
, df
, c
, p
;
6053 /* special delayed cast for char/short */
6054 /* XXX: in some cases (multiple cascaded casts), it may still
6056 if (vtop
->r
& VT_MUSTCAST
) {
6057 vtop
->r
&= ~VT_MUSTCAST
;
6058 force_charshort_cast(vtop
->type
.t
);
6061 /* bitfields first get cast to ints */
6062 if (vtop
->type
.t
& VT_BITFIELD
) {
6066 dbt
= type
->t
& (VT_BTYPE
| VT_UNSIGNED
);
6067 sbt
= vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
);
6072 c
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
6073 p
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == (VT_CONST
| VT_SYM
);
6075 /* constant case: we can do it now */
6076 /* XXX: in ISOC, cannot do it if error in convert */
6077 if (sbt
== VT_FLOAT
)
6078 vtop
->c
.ld
= vtop
->c
.f
;
6079 else if (sbt
== VT_DOUBLE
)
6080 vtop
->c
.ld
= vtop
->c
.d
;
6083 if ((sbt
& VT_BTYPE
) == VT_LLONG
) {
6084 if (sbt
& VT_UNSIGNED
)
6085 vtop
->c
.ld
= vtop
->c
.ull
;
6087 vtop
->c
.ld
= vtop
->c
.ll
;
6089 if (sbt
& VT_UNSIGNED
)
6090 vtop
->c
.ld
= vtop
->c
.ui
;
6092 vtop
->c
.ld
= vtop
->c
.i
;
6095 if (dbt
== VT_FLOAT
)
6096 vtop
->c
.f
= (float)vtop
->c
.ld
;
6097 else if (dbt
== VT_DOUBLE
)
6098 vtop
->c
.d
= (double)vtop
->c
.ld
;
6099 } else if (sf
&& dbt
== (VT_LLONG
|VT_UNSIGNED
)) {
6100 vtop
->c
.ull
= (unsigned long long)vtop
->c
.ld
;
6101 } else if (sf
&& dbt
== VT_BOOL
) {
6102 vtop
->c
.i
= (vtop
->c
.ld
!= 0);
6105 vtop
->c
.ll
= (long long)vtop
->c
.ld
;
6106 else if (sbt
== (VT_LLONG
|VT_UNSIGNED
))
6107 vtop
->c
.ll
= vtop
->c
.ull
;
6108 else if (sbt
& VT_UNSIGNED
)
6109 vtop
->c
.ll
= vtop
->c
.ui
;
6110 else if (sbt
!= VT_LLONG
)
6111 vtop
->c
.ll
= vtop
->c
.i
;
6113 if (dbt
== (VT_LLONG
|VT_UNSIGNED
))
6114 vtop
->c
.ull
= vtop
->c
.ll
;
6115 else if (dbt
== VT_BOOL
)
6116 vtop
->c
.i
= (vtop
->c
.ll
!= 0);
6117 else if (dbt
!= VT_LLONG
) {
6119 if ((dbt
& VT_BTYPE
) == VT_BYTE
)
6121 else if ((dbt
& VT_BTYPE
) == VT_SHORT
)
6124 if(dbt
& VT_UNSIGNED
)
6125 vtop
->c
.ui
= ((unsigned int)vtop
->c
.ll
<< s
) >> s
;
6127 vtop
->c
.i
= ((int)vtop
->c
.ll
<< s
) >> s
;
6130 } else if (p
&& dbt
== VT_BOOL
) {
6133 } else if (!nocode_wanted
) {
6134 /* non constant case: generate code */
6136 /* convert from fp to fp */
6139 /* convert int to fp */
6142 /* convert fp to int */
6143 if (dbt
== VT_BOOL
) {
6147 /* we handle char/short/etc... with generic code */
6148 if (dbt
!= (VT_INT
| VT_UNSIGNED
) &&
6149 dbt
!= (VT_LLONG
| VT_UNSIGNED
) &&
6153 if (dbt
== VT_INT
&& (type
->t
& (VT_BTYPE
| VT_UNSIGNED
)) != dbt
) {
6154 /* additional cast for char/short... */
6159 } else if ((dbt
& VT_BTYPE
) == VT_LLONG
) {
6160 if ((sbt
& VT_BTYPE
) != VT_LLONG
) {
6161 /* scalar to long long */
6162 #ifndef TCC_TARGET_X86_64
6163 /* machine independent conversion */
6165 /* generate high word */
6166 if (sbt
== (VT_INT
| VT_UNSIGNED
)) {
6174 /* patch second register */
6175 vtop
[-1].r2
= vtop
->r
;
6179 if (sbt
!= (VT_INT
| VT_UNSIGNED
)) {
6180 /* x86_64 specific: movslq */
6182 o(0xc0 + (REG_VALUE(r
) << 3) + REG_VALUE(r
));
6186 } else if (dbt
== VT_BOOL
) {
6187 /* scalar to bool */
6190 } else if ((dbt
& VT_BTYPE
) == VT_BYTE
||
6191 (dbt
& VT_BTYPE
) == VT_SHORT
) {
6192 if (sbt
== VT_PTR
) {
6193 vtop
->type
.t
= VT_INT
;
6194 warning("nonportable conversion from pointer to char/short");
6196 force_charshort_cast(dbt
);
6197 } else if ((dbt
& VT_BTYPE
) == VT_INT
) {
6199 if (sbt
== VT_LLONG
) {
6200 /* from long long: just take low order word */
6204 /* if lvalue and single word type, nothing to do because
6205 the lvalue already contains the real type size (see
6206 VT_LVAL_xxx constants) */
6209 } else if ((dbt
& VT_BTYPE
) == VT_PTR
&& !(vtop
->r
& VT_LVAL
)) {
6210 /* if we are casting between pointer types,
6211 we must update the VT_LVAL_xxx size */
6212 vtop
->r
= (vtop
->r
& ~VT_LVAL_TYPE
)
6213 | (lvalue_type(type
->ref
->type
.t
) & VT_LVAL_TYPE
);
6218 /* return type size. Put alignment at 'a' */
6219 static int type_size(CType
*type
, int *a
)
6224 bt
= type
->t
& VT_BTYPE
;
6225 if (bt
== VT_STRUCT
) {
6230 } else if (bt
== VT_PTR
) {
6231 if (type
->t
& VT_ARRAY
) {
6233 return type_size(&s
->type
, a
) * s
->c
;
6238 } else if (bt
== VT_LDOUBLE
) {
6240 return LDOUBLE_SIZE
;
6241 } else if (bt
== VT_DOUBLE
|| bt
== VT_LLONG
) {
6242 #ifdef TCC_TARGET_I386
6244 #elif defined(TCC_TARGET_ARM)
6254 } else if (bt
== VT_INT
|| bt
== VT_ENUM
|| bt
== VT_FLOAT
) {
6257 } else if (bt
== VT_SHORT
) {
6261 /* char, void, function, _Bool */
6267 /* return the pointed type of t */
6268 static inline CType
*pointed_type(CType
*type
)
6270 return &type
->ref
->type
;
6273 /* modify type so that its it is a pointer to type. */
6274 static void mk_pointer(CType
*type
)
6277 s
= sym_push(SYM_FIELD
, type
, 0, -1);
6278 type
->t
= VT_PTR
| (type
->t
& ~VT_TYPE
);
6282 /* compare function types. OLD functions match any new functions */
6283 static int is_compatible_func(CType
*type1
, CType
*type2
)
6289 if (!is_compatible_types(&s1
->type
, &s2
->type
))
6291 /* check func_call */
6292 if (FUNC_CALL(s1
->r
) != FUNC_CALL(s2
->r
))
6294 /* XXX: not complete */
6295 if (s1
->c
== FUNC_OLD
|| s2
->c
== FUNC_OLD
)
6299 while (s1
!= NULL
) {
6302 if (!is_compatible_parameter_types(&s1
->type
, &s2
->type
))
6312 /* return true if type1 and type2 are the same. If unqualified is
6313 true, qualifiers on the types are ignored.
6315 - enums are not checked as gcc __builtin_types_compatible_p ()
6317 static int compare_types(CType
*type1
, CType
*type2
, int unqualified
)
6321 t1
= type1
->t
& VT_TYPE
;
6322 t2
= type2
->t
& VT_TYPE
;
6324 /* strip qualifiers before comparing */
6325 t1
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6326 t2
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6328 /* XXX: bitfields ? */
6331 /* test more complicated cases */
6332 bt1
= t1
& VT_BTYPE
;
6333 if (bt1
== VT_PTR
) {
6334 type1
= pointed_type(type1
);
6335 type2
= pointed_type(type2
);
6336 return is_compatible_types(type1
, type2
);
6337 } else if (bt1
== VT_STRUCT
) {
6338 return (type1
->ref
== type2
->ref
);
6339 } else if (bt1
== VT_FUNC
) {
6340 return is_compatible_func(type1
, type2
);
6346 /* return true if type1 and type2 are exactly the same (including
6349 static int is_compatible_types(CType
*type1
, CType
*type2
)
6351 return compare_types(type1
,type2
,0);
6354 /* return true if type1 and type2 are the same (ignoring qualifiers).
6356 static int is_compatible_parameter_types(CType
*type1
, CType
*type2
)
6358 return compare_types(type1
,type2
,1);
6361 /* print a type. If 'varstr' is not NULL, then the variable is also
6362 printed in the type */
6364 /* XXX: add array and function pointers */
6365 void type_to_str(char *buf
, int buf_size
,
6366 CType
*type
, const char *varstr
)
6373 t
= type
->t
& VT_TYPE
;
6376 if (t
& VT_CONSTANT
)
6377 pstrcat(buf
, buf_size
, "const ");
6378 if (t
& VT_VOLATILE
)
6379 pstrcat(buf
, buf_size
, "volatile ");
6380 if (t
& VT_UNSIGNED
)
6381 pstrcat(buf
, buf_size
, "unsigned ");
6411 tstr
= "long double";
6413 pstrcat(buf
, buf_size
, tstr
);
6417 if (bt
== VT_STRUCT
)
6421 pstrcat(buf
, buf_size
, tstr
);
6422 v
= type
->ref
->v
& ~SYM_STRUCT
;
6423 if (v
>= SYM_FIRST_ANOM
)
6424 pstrcat(buf
, buf_size
, "<anonymous>");
6426 pstrcat(buf
, buf_size
, get_tok_str(v
, NULL
));
6430 type_to_str(buf
, buf_size
, &s
->type
, varstr
);
6431 pstrcat(buf
, buf_size
, "(");
6433 while (sa
!= NULL
) {
6434 type_to_str(buf1
, sizeof(buf1
), &sa
->type
, NULL
);
6435 pstrcat(buf
, buf_size
, buf1
);
6438 pstrcat(buf
, buf_size
, ", ");
6440 pstrcat(buf
, buf_size
, ")");
6444 pstrcpy(buf1
, sizeof(buf1
), "*");
6446 pstrcat(buf1
, sizeof(buf1
), varstr
);
6447 type_to_str(buf
, buf_size
, &s
->type
, buf1
);
6451 pstrcat(buf
, buf_size
, " ");
6452 pstrcat(buf
, buf_size
, varstr
);
6457 /* verify type compatibility to store vtop in 'dt' type, and generate
6459 static void gen_assign_cast(CType
*dt
)
6461 CType
*st
, *type1
, *type2
, tmp_type1
, tmp_type2
;
6462 char buf1
[256], buf2
[256];
6465 st
= &vtop
->type
; /* source type */
6466 dbt
= dt
->t
& VT_BTYPE
;
6467 sbt
= st
->t
& VT_BTYPE
;
6468 if (dt
->t
& VT_CONSTANT
)
6469 warning("assignment of read-only location");
6472 /* special cases for pointers */
6473 /* '0' can also be a pointer */
6474 if (is_null_pointer(vtop
))
6476 /* accept implicit pointer to integer cast with warning */
6477 if (is_integer_btype(sbt
)) {
6478 warning("assignment makes pointer from integer without a cast");
6481 type1
= pointed_type(dt
);
6482 /* a function is implicitely a function pointer */
6483 if (sbt
== VT_FUNC
) {
6484 if ((type1
->t
& VT_BTYPE
) != VT_VOID
&&
6485 !is_compatible_types(pointed_type(dt
), st
))
6492 type2
= pointed_type(st
);
6493 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
6494 (type2
->t
& VT_BTYPE
) == VT_VOID
) {
6495 /* void * can match anything */
6497 /* exact type match, except for unsigned */
6500 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
6501 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
6502 if (!is_compatible_types(&tmp_type1
, &tmp_type2
))
6503 warning("assignment from incompatible pointer type");
6505 /* check const and volatile */
6506 if ((!(type1
->t
& VT_CONSTANT
) && (type2
->t
& VT_CONSTANT
)) ||
6507 (!(type1
->t
& VT_VOLATILE
) && (type2
->t
& VT_VOLATILE
)))
6508 warning("assignment discards qualifiers from pointer target type");
6514 if (sbt
== VT_PTR
|| sbt
== VT_FUNC
) {
6515 warning("assignment makes integer from pointer without a cast");
6517 /* XXX: more tests */
6522 tmp_type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6523 tmp_type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6524 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
6526 type_to_str(buf1
, sizeof(buf1
), st
, NULL
);
6527 type_to_str(buf2
, sizeof(buf2
), dt
, NULL
);
6528 error("cannot cast '%s' to '%s'", buf1
, buf2
);
6536 /* store vtop in lvalue pushed on stack */
6539 int sbt
, dbt
, ft
, r
, t
, size
, align
, bit_size
, bit_pos
, rc
, delayed_cast
;
6541 ft
= vtop
[-1].type
.t
;
6542 sbt
= vtop
->type
.t
& VT_BTYPE
;
6543 dbt
= ft
& VT_BTYPE
;
6544 if (((sbt
== VT_INT
|| sbt
== VT_SHORT
) && dbt
== VT_BYTE
) ||
6545 (sbt
== VT_INT
&& dbt
== VT_SHORT
)) {
6546 /* optimize char/short casts */
6547 delayed_cast
= VT_MUSTCAST
;
6548 vtop
->type
.t
= ft
& (VT_TYPE
& ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
)));
6549 /* XXX: factorize */
6550 if (ft
& VT_CONSTANT
)
6551 warning("assignment of read-only location");
6554 if (!(ft
& VT_BITFIELD
))
6555 gen_assign_cast(&vtop
[-1].type
);
6558 if (sbt
== VT_STRUCT
) {
6559 /* if structure, only generate pointer */
6560 /* structure assignment : generate memcpy */
6561 /* XXX: optimize if small size */
6562 if (!nocode_wanted
) {
6563 size
= type_size(&vtop
->type
, &align
);
6567 vpush_global_sym(&func_old_type
, TOK_memcpy8
);
6568 else if(!(align
& 3))
6569 vpush_global_sym(&func_old_type
, TOK_memcpy4
);
6572 vpush_global_sym(&func_old_type
, TOK_memcpy
);
6576 vtop
->type
.t
= VT_INT
;
6580 vtop
->type
.t
= VT_INT
;
6592 /* leave source on stack */
6593 } else if (ft
& VT_BITFIELD
) {
6594 /* bitfield store handling */
6595 bit_pos
= (ft
>> VT_STRUCT_SHIFT
) & 0x3f;
6596 bit_size
= (ft
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
6597 /* remove bit field info to avoid loops */
6598 vtop
[-1].type
.t
= ft
& ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
6600 /* duplicate source into other register */
6605 if((ft
& VT_BTYPE
) == VT_BOOL
) {
6606 gen_cast(&vtop
[-1].type
);
6607 vtop
[-1].type
.t
= (vtop
[-1].type
.t
& ~VT_BTYPE
) | (VT_BYTE
| VT_UNSIGNED
);
6610 /* duplicate destination */
6612 vtop
[-1] = vtop
[-2];
6614 /* mask and shift source */
6615 if((ft
& VT_BTYPE
) != VT_BOOL
) {
6616 vpushi((1 << bit_size
) - 1);
6621 /* load destination, mask and or with source */
6623 vpushi(~(((1 << bit_size
) - 1) << bit_pos
));
6629 /* pop off shifted source from "duplicate source..." above */
6633 #ifdef CONFIG_TCC_BCHECK
6634 /* bound check case */
6635 if (vtop
[-1].r
& VT_MUSTBOUND
) {
6641 if (!nocode_wanted
) {
6645 #ifdef TCC_TARGET_X86_64
6646 if ((ft
& VT_BTYPE
) == VT_LDOUBLE
) {
6651 r
= gv(rc
); /* generate value */
6652 /* if lvalue was saved on stack, must read it */
6653 if ((vtop
[-1].r
& VT_VALMASK
) == VT_LLOCAL
) {
6655 t
= get_reg(RC_INT
);
6656 #ifdef TCC_TARGET_X86_64
6661 sv
.r
= VT_LOCAL
| VT_LVAL
;
6662 sv
.c
.ul
= vtop
[-1].c
.ul
;
6664 vtop
[-1].r
= t
| VT_LVAL
;
6667 #ifndef TCC_TARGET_X86_64
6668 /* two word case handling : store second register at word + 4 */
6669 if ((ft
& VT_BTYPE
) == VT_LLONG
) {
6671 /* convert to int to increment easily */
6672 vtop
->type
.t
= VT_INT
;
6678 /* XXX: it works because r2 is spilled last ! */
6679 store(vtop
->r2
, vtop
- 1);
6684 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
6685 vtop
->r
|= delayed_cast
;
6689 /* post defines POST/PRE add. c is the token ++ or -- */
6690 void inc(int post
, int c
)
6693 vdup(); /* save lvalue */
6695 gv_dup(); /* duplicate value */
6700 vpushi(c
- TOK_MID
);
6702 vstore(); /* store value */
6704 vpop(); /* if post op, return saved value */
6707 /* Parse GNUC __attribute__ extension. Currently, the following
6708 extensions are recognized:
6709 - aligned(n) : set data/function alignment.
6710 - packed : force data alignment to 1
6711 - section(x) : generate data/code in this section.
6712 - unused : currently ignored, but may be used someday.
6713 - regparm(n) : pass function parameters in registers (i386 only)
6715 static void parse_attribute(AttributeDef
*ad
)
6719 while (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
) {
6723 while (tok
!= ')') {
6724 if (tok
< TOK_IDENT
)
6725 expect("attribute name");
6733 expect("section name");
6734 ad
->section
= find_section(tcc_state
, (char *)tokc
.cstr
->data
);
6743 if (n
<= 0 || (n
& (n
- 1)) != 0)
6744 error("alignment must be a positive power of two");
6757 /* currently, no need to handle it because tcc does not
6758 track unused objects */
6762 /* currently, no need to handle it because tcc does not
6763 track unused objects */
6768 FUNC_CALL(ad
->func_attr
) = FUNC_CDECL
;
6773 FUNC_CALL(ad
->func_attr
) = FUNC_STDCALL
;
6775 #ifdef TCC_TARGET_I386
6785 FUNC_CALL(ad
->func_attr
) = FUNC_FASTCALL1
+ n
- 1;
6791 FUNC_CALL(ad
->func_attr
) = FUNC_FASTCALLW
;
6795 FUNC_EXPORT(ad
->func_attr
) = 1;
6798 if (tcc_state
->warn_unsupported
)
6799 warning("'%s' attribute ignored", get_tok_str(t
, NULL
));
6800 /* skip parameters */
6802 int parenthesis
= 0;
6806 else if (tok
== ')')
6809 } while (parenthesis
&& tok
!= -1);
6822 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
6823 static void struct_decl(CType
*type
, int u
)
6825 int a
, v
, size
, align
, maxalign
, c
, offset
;
6826 int bit_size
, bit_pos
, bsize
, bt
, lbit_pos
, prevbt
;
6827 Sym
*s
, *ss
, *ass
, **ps
;
6831 a
= tok
; /* save decl type */
6836 /* struct already defined ? return it */
6838 expect("struct/union/enum name");
6842 error("invalid type");
6849 /* we put an undefined size for struct/union */
6850 s
= sym_push(v
| SYM_STRUCT
, &type1
, 0, -1);
6851 s
->r
= 0; /* default alignment is zero as gcc */
6852 /* put struct/union/enum name in type */
6860 error("struct/union/enum already defined");
6861 /* cannot be empty */
6863 /* non empty enums are not allowed */
6864 if (a
== TOK_ENUM
) {
6868 expect("identifier");
6874 /* enum symbols have static storage */
6875 ss
= sym_push(v
, &int_type
, VT_CONST
, c
);
6876 ss
->type
.t
|= VT_STATIC
;
6881 /* NOTE: we accept a trailing comma */
6892 while (tok
!= '}') {
6893 parse_btype(&btype
, &ad
);
6899 type_decl(&type1
, &ad
, &v
, TYPE_DIRECT
| TYPE_ABSTRACT
);
6900 if (v
== 0 && (type1
.t
& VT_BTYPE
) != VT_STRUCT
)
6901 expect("identifier");
6902 if ((type1
.t
& VT_BTYPE
) == VT_FUNC
||
6903 (type1
.t
& (VT_TYPEDEF
| VT_STATIC
| VT_EXTERN
| VT_INLINE
)))
6904 error("invalid type for '%s'",
6905 get_tok_str(v
, NULL
));
6909 bit_size
= expr_const();
6910 /* XXX: handle v = 0 case for messages */
6912 error("negative width in bit-field '%s'",
6913 get_tok_str(v
, NULL
));
6914 if (v
&& bit_size
== 0)
6915 error("zero width for bit-field '%s'",
6916 get_tok_str(v
, NULL
));
6918 size
= type_size(&type1
, &align
);
6920 if (align
< ad
.aligned
)
6922 } else if (ad
.packed
) {
6924 } else if (*tcc_state
->pack_stack_ptr
) {
6925 if (align
> *tcc_state
->pack_stack_ptr
)
6926 align
= *tcc_state
->pack_stack_ptr
;
6929 if (bit_size
>= 0) {
6930 bt
= type1
.t
& VT_BTYPE
;
6936 error("bitfields must have scalar type");
6938 if (bit_size
> bsize
) {
6939 error("width of '%s' exceeds its type",
6940 get_tok_str(v
, NULL
));
6941 } else if (bit_size
== bsize
) {
6942 /* no need for bit fields */
6944 } else if (bit_size
== 0) {
6945 /* XXX: what to do if only padding in a
6947 /* zero size: means to pad */
6950 /* we do not have enough room ?
6951 did the type change?
6953 if ((bit_pos
+ bit_size
) > bsize
||
6954 bt
!= prevbt
|| a
== TOK_UNION
)
6957 /* XXX: handle LSB first */
6958 type1
.t
|= VT_BITFIELD
|
6959 (bit_pos
<< VT_STRUCT_SHIFT
) |
6960 (bit_size
<< (VT_STRUCT_SHIFT
+ 6));
6961 bit_pos
+= bit_size
;
6967 if (v
!= 0 || (type1
.t
& VT_BTYPE
) == VT_STRUCT
) {
6968 /* add new memory data only if starting
6970 if (lbit_pos
== 0) {
6971 if (a
== TOK_STRUCT
) {
6972 c
= (c
+ align
- 1) & -align
;
6981 if (align
> maxalign
)
6985 printf("add field %s offset=%d",
6986 get_tok_str(v
, NULL
), offset
);
6987 if (type1
.t
& VT_BITFIELD
) {
6988 printf(" pos=%d size=%d",
6989 (type1
.t
>> VT_STRUCT_SHIFT
) & 0x3f,
6990 (type1
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f);
6995 if (v
== 0 && (type1
.t
& VT_BTYPE
) == VT_STRUCT
) {
6997 while ((ass
= ass
->next
) != NULL
) {
6998 ss
= sym_push(ass
->v
, &ass
->type
, 0, offset
+ ass
->c
);
7003 ss
= sym_push(v
| SYM_FIELD
, &type1
, 0, offset
);
7007 if (tok
== ';' || tok
== TOK_EOF
)
7014 /* store size and alignment */
7015 s
->c
= (c
+ maxalign
- 1) & -maxalign
;
7021 /* return 0 if no type declaration. otherwise, return the basic type
7024 static int parse_btype(CType
*type
, AttributeDef
*ad
)
7026 int t
, u
, type_found
, typespec_found
, typedef_found
;
7030 memset(ad
, 0, sizeof(AttributeDef
));
7038 /* currently, we really ignore extension */
7048 if ((t
& VT_BTYPE
) != 0)
7049 error("too many basic types");
7065 if ((t
& VT_BTYPE
) == VT_DOUBLE
) {
7066 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
7067 } else if ((t
& VT_BTYPE
) == VT_LONG
) {
7068 t
= (t
& ~VT_BTYPE
) | VT_LLONG
;
7082 if ((t
& VT_BTYPE
) == VT_LONG
) {
7083 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
7090 struct_decl(&type1
, VT_ENUM
);
7093 type
->ref
= type1
.ref
;
7097 struct_decl(&type1
, VT_STRUCT
);
7100 /* type modifiers */
7153 /* GNUC attribute */
7154 case TOK_ATTRIBUTE1
:
7155 case TOK_ATTRIBUTE2
:
7156 parse_attribute(ad
);
7163 parse_expr_type(&type1
);
7166 if (typespec_found
|| typedef_found
)
7169 if (!s
|| !(s
->type
.t
& VT_TYPEDEF
))
7172 t
|= (s
->type
.t
& ~VT_TYPEDEF
);
7173 type
->ref
= s
->type
.ref
;
7181 if ((t
& (VT_SIGNED
|VT_UNSIGNED
)) == (VT_SIGNED
|VT_UNSIGNED
))
7182 error("signed and unsigned modifier");
7183 if (tcc_state
->char_is_unsigned
) {
7184 if ((t
& (VT_SIGNED
|VT_UNSIGNED
|VT_BTYPE
)) == VT_BYTE
)
7189 /* long is never used as type */
7190 if ((t
& VT_BTYPE
) == VT_LONG
)
7191 #ifndef TCC_TARGET_X86_64
7192 t
= (t
& ~VT_BTYPE
) | VT_INT
;
7194 t
= (t
& ~VT_BTYPE
) | VT_LLONG
;
7200 /* convert a function parameter type (array to pointer and function to
7201 function pointer) */
7202 static inline void convert_parameter_type(CType
*pt
)
7204 /* remove const and volatile qualifiers (XXX: const could be used
7205 to indicate a const function parameter */
7206 pt
->t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7207 /* array must be transformed to pointer according to ANSI C */
7209 if ((pt
->t
& VT_BTYPE
) == VT_FUNC
) {
7214 static void post_type(CType
*type
, AttributeDef
*ad
)
7216 int n
, l
, t1
, arg_size
, align
;
7217 Sym
**plast
, *s
, *first
;
7222 /* function declaration */
7230 /* read param name and compute offset */
7231 if (l
!= FUNC_OLD
) {
7232 if (!parse_btype(&pt
, &ad1
)) {
7234 error("invalid type");
7241 if ((pt
.t
& VT_BTYPE
) == VT_VOID
&& tok
== ')')
7243 type_decl(&pt
, &ad1
, &n
, TYPE_DIRECT
| TYPE_ABSTRACT
);
7244 if ((pt
.t
& VT_BTYPE
) == VT_VOID
)
7245 error("parameter declared as void");
7246 arg_size
+= (type_size(&pt
, &align
) + 3) & ~3;
7251 expect("identifier");
7255 convert_parameter_type(&pt
);
7256 s
= sym_push(n
| SYM_FIELD
, &pt
, 0, 0);
7262 if (l
== FUNC_NEW
&& tok
== TOK_DOTS
) {
7269 /* if no parameters, then old type prototype */
7273 t1
= type
->t
& VT_STORAGE
;
7274 /* NOTE: const is ignored in returned type as it has a special
7275 meaning in gcc / C++ */
7276 type
->t
&= ~(VT_STORAGE
| VT_CONSTANT
);
7277 post_type(type
, ad
);
7278 /* we push a anonymous symbol which will contain the function prototype */
7279 FUNC_ARGS(ad
->func_attr
) = arg_size
;
7280 s
= sym_push(SYM_FIELD
, type
, ad
->func_attr
, l
);
7282 type
->t
= t1
| VT_FUNC
;
7284 } else if (tok
== '[') {
7285 /* array definition */
7291 error("invalid array size");
7294 /* parse next post type */
7295 t1
= type
->t
& VT_STORAGE
;
7296 type
->t
&= ~VT_STORAGE
;
7297 post_type(type
, ad
);
7299 /* we push a anonymous symbol which will contain the array
7301 s
= sym_push(SYM_FIELD
, type
, 0, n
);
7302 type
->t
= t1
| VT_ARRAY
| VT_PTR
;
7307 /* Parse a type declaration (except basic type), and return the type
7308 in 'type'. 'td' is a bitmask indicating which kind of type decl is
7309 expected. 'type' should contain the basic type. 'ad' is the
7310 attribute definition of the basic type. It can be modified by
7313 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
)
7316 CType type1
, *type2
;
7319 while (tok
== '*') {
7327 qualifiers
|= VT_CONSTANT
;
7332 qualifiers
|= VT_VOLATILE
;
7340 type
->t
|= qualifiers
;
7343 /* XXX: clarify attribute handling */
7344 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
7345 parse_attribute(ad
);
7347 /* recursive type */
7348 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
7349 type1
.t
= 0; /* XXX: same as int */
7352 /* XXX: this is not correct to modify 'ad' at this point, but
7353 the syntax is not clear */
7354 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
7355 parse_attribute(ad
);
7356 type_decl(&type1
, ad
, v
, td
);
7359 /* type identifier */
7360 if (tok
>= TOK_IDENT
&& (td
& TYPE_DIRECT
)) {
7364 if (!(td
& TYPE_ABSTRACT
))
7365 expect("identifier");
7369 post_type(type
, ad
);
7370 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
7371 parse_attribute(ad
);
7374 /* append type at the end of type1 */
7387 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
7388 static int lvalue_type(int t
)
7393 if (bt
== VT_BYTE
|| bt
== VT_BOOL
)
7395 else if (bt
== VT_SHORT
)
7399 if (t
& VT_UNSIGNED
)
7400 r
|= VT_LVAL_UNSIGNED
;
7404 /* indirection with full error checking and bound check */
7405 static void indir(void)
7407 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
) {
7408 if ((vtop
->type
.t
& VT_BTYPE
) == VT_FUNC
)
7412 if ((vtop
->r
& VT_LVAL
) && !nocode_wanted
)
7414 vtop
->type
= *pointed_type(&vtop
->type
);
7415 /* Arrays and functions are never lvalues */
7416 if (!(vtop
->type
.t
& VT_ARRAY
)
7417 && (vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
) {
7418 vtop
->r
|= lvalue_type(vtop
->type
.t
);
7419 /* if bound checking, the referenced pointer must be checked */
7420 if (do_bounds_check
)
7421 vtop
->r
|= VT_MUSTBOUND
;
7425 /* pass a parameter to a function and do type checking and casting */
7426 static void gfunc_param_typed(Sym
*func
, Sym
*arg
)
7431 func_type
= func
->c
;
7432 if (func_type
== FUNC_OLD
||
7433 (func_type
== FUNC_ELLIPSIS
&& arg
== NULL
)) {
7434 /* default casting : only need to convert float to double */
7435 if ((vtop
->type
.t
& VT_BTYPE
) == VT_FLOAT
) {
7439 } else if (arg
== NULL
) {
7440 error("too many arguments to function");
7443 type
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
7444 gen_assign_cast(&type
);
7448 /* parse an expression of the form '(type)' or '(expr)' and return its
7450 static void parse_expr_type(CType
*type
)
7456 if (parse_btype(type
, &ad
)) {
7457 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
7464 static void parse_type(CType
*type
)
7469 if (!parse_btype(type
, &ad
)) {
7472 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
7475 static void vpush_tokc(int t
)
7479 vsetc(&type
, VT_CONST
, &tokc
);
7482 static void unary(void)
7484 int n
, t
, align
, size
, r
;
7489 /* XXX: GCC 2.95.3 does not generate a table although it should be
7503 vpush_tokc(VT_INT
| VT_UNSIGNED
);
7507 vpush_tokc(VT_LLONG
);
7511 vpush_tokc(VT_LLONG
| VT_UNSIGNED
);
7515 vpush_tokc(VT_FLOAT
);
7519 vpush_tokc(VT_DOUBLE
);
7523 vpush_tokc(VT_LDOUBLE
);
7526 case TOK___FUNCTION__
:
7528 goto tok_identifier
;
7534 /* special function name identifier */
7535 len
= strlen(funcname
) + 1;
7536 /* generate char[len] type */
7541 vpush_ref(&type
, data_section
, data_section
->data_offset
, len
);
7542 ptr
= section_ptr_add(data_section
, len
);
7543 memcpy(ptr
, funcname
, len
);
7548 #ifdef TCC_TARGET_PE
7549 t
= VT_SHORT
| VT_UNSIGNED
;
7555 /* string parsing */
7558 if (tcc_state
->warn_write_strings
)
7563 memset(&ad
, 0, sizeof(AttributeDef
));
7564 decl_initializer_alloc(&type
, &ad
, VT_CONST
, 2, 0, 0);
7569 if (parse_btype(&type
, &ad
)) {
7570 type_decl(&type
, &ad
, &n
, TYPE_ABSTRACT
);
7572 /* check ISOC99 compound literal */
7574 /* data is allocated locally by default */
7579 /* all except arrays are lvalues */
7580 if (!(type
.t
& VT_ARRAY
))
7581 r
|= lvalue_type(type
.t
);
7582 memset(&ad
, 0, sizeof(AttributeDef
));
7583 decl_initializer_alloc(&type
, &ad
, r
, 1, 0, 0);
7588 } else if (tok
== '{') {
7589 /* save all registers */
7591 /* statement expression : we do not accept break/continue
7592 inside as GCC does */
7593 block(NULL
, NULL
, NULL
, NULL
, 0, 1);
7608 /* functions names must be treated as function pointers,
7609 except for unary '&' and sizeof. Since we consider that
7610 functions are not lvalues, we only have to handle it
7611 there and in function calls. */
7612 /* arrays can also be used although they are not lvalues */
7613 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
&&
7614 !(vtop
->type
.t
& VT_ARRAY
) && !(vtop
->type
.t
& VT_LLOCAL
))
7616 mk_pointer(&vtop
->type
);
7622 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) {
7624 boolean
.t
= VT_BOOL
;
7626 vtop
->c
.i
= !vtop
->c
.i
;
7627 } else if ((vtop
->r
& VT_VALMASK
) == VT_CMP
)
7628 vtop
->c
.i
= vtop
->c
.i
^ 1;
7631 vseti(VT_JMP
, gtst(1, 0));
7642 /* in order to force cast, we add zero */
7644 if ((vtop
->type
.t
& VT_BTYPE
) == VT_PTR
)
7645 error("pointer not accepted for unary plus");
7655 parse_expr_type(&type
);
7659 size
= type_size(&type
, &align
);
7660 if (t
== TOK_SIZEOF
) {
7662 error("sizeof applied to an incomplete type");
7667 vtop
->type
.t
|= VT_UNSIGNED
;
7670 case TOK_builtin_types_compatible_p
:
7679 type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7680 type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7681 vpushi(is_compatible_types(&type1
, &type2
));
7684 case TOK_builtin_constant_p
:
7686 int saved_nocode_wanted
, res
;
7689 saved_nocode_wanted
= nocode_wanted
;
7692 res
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
7694 nocode_wanted
= saved_nocode_wanted
;
7699 case TOK_builtin_frame_address
:
7704 if (tok
!= TOK_CINT
) {
7705 error("__builtin_frame_address only takes integers");
7708 error("TCC only supports __builtin_frame_address(0)");
7714 vset(&type
, VT_LOCAL
, 0);
7732 goto tok_identifier
;
7734 /* allow to take the address of a label */
7735 if (tok
< TOK_UIDENT
)
7736 expect("label identifier");
7737 s
= label_find(tok
);
7739 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
7741 if (s
->r
== LABEL_DECLARED
)
7742 s
->r
= LABEL_FORWARD
;
7745 s
->type
.t
= VT_VOID
;
7746 mk_pointer(&s
->type
);
7747 s
->type
.t
|= VT_STATIC
;
7749 vset(&s
->type
, VT_CONST
| VT_SYM
, 0);
7758 expect("identifier");
7762 error("'%s' undeclared", get_tok_str(t
, NULL
));
7763 /* for simple function calls, we tolerate undeclared
7764 external reference to int() function */
7765 if (tcc_state
->warn_implicit_function_declaration
)
7766 warning("implicit declaration of function '%s'",
7767 get_tok_str(t
, NULL
));
7768 s
= external_global_sym(t
, &func_old_type
, 0);
7770 if ((s
->type
.t
& (VT_STATIC
| VT_INLINE
| VT_BTYPE
)) ==
7771 (VT_STATIC
| VT_INLINE
| VT_FUNC
)) {
7772 /* if referencing an inline function, then we generate a
7773 symbol to it if not already done. It will have the
7774 effect to generate code for it at the end of the
7775 compilation unit. Inline function as always
7776 generated in the text section. */
7778 put_extern_sym(s
, text_section
, 0, 0);
7779 r
= VT_SYM
| VT_CONST
;
7783 vset(&s
->type
, r
, s
->c
);
7784 /* if forward reference, we must point to s */
7785 if (vtop
->r
& VT_SYM
) {
7792 /* post operations */
7794 if (tok
== TOK_INC
|| tok
== TOK_DEC
) {
7797 } else if (tok
== '.' || tok
== TOK_ARROW
) {
7799 if (tok
== TOK_ARROW
)
7804 /* expect pointer on structure */
7805 if ((vtop
->type
.t
& VT_BTYPE
) != VT_STRUCT
)
7806 expect("struct or union");
7810 while ((s
= s
->next
) != NULL
) {
7815 error("field not found: %s", get_tok_str(tok
& ~SYM_FIELD
, NULL
));
7816 /* add field offset to pointer */
7817 vtop
->type
= char_pointer_type
; /* change type to 'char *' */
7820 /* change type to field type, and set to lvalue */
7821 vtop
->type
= s
->type
;
7822 /* an array is never an lvalue */
7823 if (!(vtop
->type
.t
& VT_ARRAY
)) {
7824 vtop
->r
|= lvalue_type(vtop
->type
.t
);
7825 /* if bound checking, the referenced pointer must be checked */
7826 if (do_bounds_check
)
7827 vtop
->r
|= VT_MUSTBOUND
;
7830 } else if (tok
== '[') {
7836 } else if (tok
== '(') {
7842 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
) {
7843 /* pointer test (no array accepted) */
7844 if ((vtop
->type
.t
& (VT_BTYPE
| VT_ARRAY
)) == VT_PTR
) {
7845 vtop
->type
= *pointed_type(&vtop
->type
);
7846 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
)
7850 expect("function pointer");
7853 vtop
->r
&= ~VT_LVAL
; /* no lvalue */
7855 /* get return type */
7858 sa
= s
->next
; /* first parameter */
7861 /* compute first implicit argument if a structure is returned */
7862 if ((s
->type
.t
& VT_BTYPE
) == VT_STRUCT
) {
7863 /* get some space for the returned structure */
7864 size
= type_size(&s
->type
, &align
);
7865 loc
= (loc
- size
) & -align
;
7867 ret
.r
= VT_LOCAL
| VT_LVAL
;
7868 /* pass it as 'int' to avoid structure arg passing
7870 vseti(VT_LOCAL
, loc
);
7875 /* return in register */
7876 if (is_float(ret
.type
.t
)) {
7879 if ((ret
.type
.t
& VT_BTYPE
) == VT_LLONG
)
7888 gfunc_param_typed(s
, sa
);
7898 error("too few arguments to function");
7900 if (!nocode_wanted
) {
7901 gfunc_call(nb_args
);
7903 vtop
-= (nb_args
+ 1);
7906 vsetc(&ret
.type
, ret
.r
, &ret
.c
);
7914 static void uneq(void)
7920 (tok
>= TOK_A_MOD
&& tok
<= TOK_A_DIV
) ||
7921 tok
== TOK_A_XOR
|| tok
== TOK_A_OR
||
7922 tok
== TOK_A_SHL
|| tok
== TOK_A_SAR
) {
7937 static void expr_prod(void)
7942 while (tok
== '*' || tok
== '/' || tok
== '%') {
7950 static void expr_sum(void)
7955 while (tok
== '+' || tok
== '-') {
7963 static void expr_shift(void)
7968 while (tok
== TOK_SHL
|| tok
== TOK_SAR
) {
7976 static void expr_cmp(void)
7981 while ((tok
>= TOK_ULE
&& tok
<= TOK_GT
) ||
7982 tok
== TOK_ULT
|| tok
== TOK_UGE
) {
7990 static void expr_cmpeq(void)
7995 while (tok
== TOK_EQ
|| tok
== TOK_NE
) {
8003 static void expr_and(void)
8006 while (tok
== '&') {
8013 static void expr_xor(void)
8016 while (tok
== '^') {
8023 static void expr_or(void)
8026 while (tok
== '|') {
8033 /* XXX: fix this mess */
8034 static void expr_land_const(void)
8037 while (tok
== TOK_LAND
) {
8044 /* XXX: fix this mess */
8045 static void expr_lor_const(void)
8048 while (tok
== TOK_LOR
) {
8055 /* only used if non constant */
8056 static void expr_land(void)
8061 if (tok
== TOK_LAND
) {
8066 if (tok
!= TOK_LAND
) {
8076 static void expr_lor(void)
8081 if (tok
== TOK_LOR
) {
8086 if (tok
!= TOK_LOR
) {
8096 /* XXX: better constant handling */
8097 static void expr_eq(void)
8099 int tt
, u
, r1
, r2
, rc
, t1
, t2
, bt1
, bt2
;
8101 CType type
, type1
, type2
;
8108 boolean
.t
= VT_BOOL
;
8114 if (tok
!= ':' || !gnu_ext
) {
8129 if (vtop
!= vstack
) {
8130 /* needed to avoid having different registers saved in
8132 if (is_float(vtop
->type
.t
)) {
8134 #ifdef TCC_TARGET_X86_64
8135 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LDOUBLE
) {
8145 if (tok
== ':' && gnu_ext
) {
8153 sv
= *vtop
; /* save value to handle it later */
8154 vtop
--; /* no vpop so that FP stack is not flushed */
8162 bt1
= t1
& VT_BTYPE
;
8164 bt2
= t2
& VT_BTYPE
;
8165 /* cast operands to correct type according to ISOC rules */
8166 if (is_float(bt1
) || is_float(bt2
)) {
8167 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
8168 type
.t
= VT_LDOUBLE
;
8169 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
8174 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
8175 /* cast to biggest op */
8177 /* convert to unsigned if it does not fit in a long long */
8178 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
8179 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
8180 type
.t
|= VT_UNSIGNED
;
8181 } else if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
8182 /* XXX: test pointer compatibility */
8184 } else if (bt1
== VT_FUNC
|| bt2
== VT_FUNC
) {
8185 /* XXX: test function pointer compatibility */
8187 } else if (bt1
== VT_STRUCT
|| bt2
== VT_STRUCT
) {
8188 /* XXX: test structure compatibility */
8190 } else if (bt1
== VT_VOID
|| bt2
== VT_VOID
) {
8191 /* NOTE: as an extension, we accept void on only one side */
8194 /* integer operations */
8196 /* convert to unsigned if it does not fit in an integer */
8197 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
8198 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
8199 type
.t
|= VT_UNSIGNED
;
8202 /* now we convert second operand */
8204 if (VT_STRUCT
== (vtop
->type
.t
& VT_BTYPE
))
8207 if (is_float(type
.t
)) {
8209 #ifdef TCC_TARGET_X86_64
8210 if ((type
.t
& VT_BTYPE
) == VT_LDOUBLE
) {
8214 } else if ((type
.t
& VT_BTYPE
) == VT_LLONG
) {
8215 /* for long longs, we use fixed registers to avoid having
8216 to handle a complicated move */
8221 /* this is horrible, but we must also convert first
8225 /* put again first value and cast it */
8228 if (VT_STRUCT
== (vtop
->type
.t
& VT_BTYPE
))
8238 static void gexpr(void)
8249 /* parse an expression and return its type without any side effect. */
8250 static void expr_type(CType
*type
)
8252 int saved_nocode_wanted
;
8254 saved_nocode_wanted
= nocode_wanted
;
8259 nocode_wanted
= saved_nocode_wanted
;
8262 /* parse a unary expression and return its type without any side
8264 static void unary_type(CType
*type
)
8276 /* parse a constant expression and return value in vtop. */
8277 static void expr_const1(void)
8286 /* parse an integer constant and return its value. */
8287 static int expr_const(void)
8291 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
8292 expect("constant expression");
8298 /* return the label token if current token is a label, otherwise
8300 static int is_label(void)
8304 /* fast test first */
8305 if (tok
< TOK_UIDENT
)
8307 /* no need to save tokc because tok is an identifier */
8314 unget_tok(last_tok
);
8319 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
8320 int case_reg
, int is_expr
)
8325 /* generate line number info */
8327 (last_line_num
!= file
->line_num
|| last_ind
!= ind
)) {
8328 put_stabn(N_SLINE
, 0, file
->line_num
, ind
- func_ind
);
8330 last_line_num
= file
->line_num
;
8334 /* default return value is (void) */
8336 vtop
->type
.t
= VT_VOID
;
8339 if (tok
== TOK_IF
) {
8346 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
8348 if (c
== TOK_ELSE
) {
8352 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
8353 gsym(d
); /* patch else jmp */
8356 } else if (tok
== TOK_WHILE
) {
8364 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
8368 } else if (tok
== '{') {
8372 /* record local declaration stack position */
8374 llabel
= local_label_stack
;
8375 /* handle local labels declarations */
8376 if (tok
== TOK_LABEL
) {
8379 if (tok
< TOK_UIDENT
)
8380 expect("label identifier");
8381 label_push(&local_label_stack
, tok
, LABEL_DECLARED
);
8391 while (tok
!= '}') {
8396 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
8399 /* pop locally defined labels */
8400 label_pop(&local_label_stack
, llabel
);
8401 /* pop locally defined symbols */
8403 /* XXX: this solution makes only valgrind happy...
8404 triggered by gcc.c-torture/execute/20000917-1.c */
8406 switch(vtop
->type
.t
& VT_BTYPE
) {
8411 for(p
=vtop
->type
.ref
;p
;p
=p
->prev
)
8413 error("unsupported expression type");
8416 sym_pop(&local_stack
, s
);
8418 } else if (tok
== TOK_RETURN
) {
8422 gen_assign_cast(&func_vt
);
8423 if ((func_vt
.t
& VT_BTYPE
) == VT_STRUCT
) {
8425 /* if returning structure, must copy it to implicit
8426 first pointer arg location */
8429 size
= type_size(&func_vt
,&align
);
8432 if((vtop
->r
!= (VT_LOCAL
| VT_LVAL
) || (vtop
->c
.i
& 3))
8436 loc
= (loc
- size
) & -4;
8439 vset(&type
, VT_LOCAL
| VT_LVAL
, addr
);
8442 vset(&int_type
, VT_LOCAL
| VT_LVAL
, addr
);
8444 vtop
->type
= int_type
;
8450 vset(&type
, VT_LOCAL
| VT_LVAL
, func_vc
);
8453 /* copy structure value to pointer */
8458 } else if (is_float(func_vt
.t
)) {
8463 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
8466 rsym
= gjmp(rsym
); /* jmp */
8467 } else if (tok
== TOK_BREAK
) {
8470 error("cannot break");
8471 *bsym
= gjmp(*bsym
);
8474 } else if (tok
== TOK_CONTINUE
) {
8477 error("cannot continue");
8478 *csym
= gjmp(*csym
);
8481 } else if (tok
== TOK_FOR
) {
8508 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
8513 if (tok
== TOK_DO
) {
8518 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
8529 if (tok
== TOK_SWITCH
) {
8533 /* XXX: other types than integer */
8534 case_reg
= gv(RC_INT
);
8538 b
= gjmp(0); /* jump to first case */
8540 block(&a
, csym
, &b
, &c
, case_reg
, 0);
8541 /* if no default, jmp after switch */
8549 if (tok
== TOK_CASE
) {
8556 if (gnu_ext
&& tok
== TOK_DOTS
) {
8560 warning("empty case range");
8562 /* since a case is like a label, we must skip it with a jmp */
8569 *case_sym
= gtst(1, 0);
8572 *case_sym
= gtst(1, 0);
8576 *case_sym
= gtst(1, *case_sym
);
8581 goto block_after_label
;
8583 if (tok
== TOK_DEFAULT
) {
8589 error("too many 'default'");
8592 goto block_after_label
;
8594 if (tok
== TOK_GOTO
) {
8596 if (tok
== '*' && gnu_ext
) {
8600 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
8603 } else if (tok
>= TOK_UIDENT
) {
8604 s
= label_find(tok
);
8605 /* put forward definition if needed */
8607 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
8609 if (s
->r
== LABEL_DECLARED
)
8610 s
->r
= LABEL_FORWARD
;
8612 /* label already defined */
8613 if (s
->r
& LABEL_FORWARD
)
8614 s
->next
= (void *)gjmp((long)s
->next
);
8616 gjmp_addr((long)s
->next
);
8619 expect("label identifier");
8622 } else if (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
) {
8630 if (s
->r
== LABEL_DEFINED
)
8631 error("duplicate label '%s'", get_tok_str(s
->v
, NULL
));
8632 gsym((long)s
->next
);
8633 s
->r
= LABEL_DEFINED
;
8635 s
= label_push(&global_label_stack
, b
, LABEL_DEFINED
);
8637 s
->next
= (void *)ind
;
8638 /* we accept this, but it is a mistake */
8641 warning("deprecated use of label at end of compound statement");
8645 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
8648 /* expression case */
8663 /* t is the array or struct type. c is the array or struct
8664 address. cur_index/cur_field is the pointer to the current
8665 value. 'size_only' is true if only size info is needed (only used
8667 static void decl_designator(CType
*type
, Section
*sec
, unsigned long c
,
8668 int *cur_index
, Sym
**cur_field
,
8672 int notfirst
, index
, index_last
, align
, l
, nb_elems
, elem_size
;
8678 if (gnu_ext
&& (l
= is_label()) != 0)
8680 while (tok
== '[' || tok
== '.') {
8682 if (!(type
->t
& VT_ARRAY
))
8683 expect("array type");
8686 index
= expr_const();
8687 if (index
< 0 || (s
->c
>= 0 && index
>= s
->c
))
8688 expect("invalid index");
8689 if (tok
== TOK_DOTS
&& gnu_ext
) {
8691 index_last
= expr_const();
8692 if (index_last
< 0 ||
8693 (s
->c
>= 0 && index_last
>= s
->c
) ||
8695 expect("invalid index");
8701 *cur_index
= index_last
;
8702 type
= pointed_type(type
);
8703 elem_size
= type_size(type
, &align
);
8704 c
+= index
* elem_size
;
8705 /* NOTE: we only support ranges for last designator */
8706 nb_elems
= index_last
- index
+ 1;
8707 if (nb_elems
!= 1) {
8716 if ((type
->t
& VT_BTYPE
) != VT_STRUCT
)
8717 expect("struct/union type");
8730 /* XXX: fix this mess by using explicit storage field */
8732 type1
.t
|= (type
->t
& ~VT_TYPE
);
8746 if (type
->t
& VT_ARRAY
) {
8748 type
= pointed_type(type
);
8749 c
+= index
* type_size(type
, &align
);
8753 error("too many field init");
8754 /* XXX: fix this mess by using explicit storage field */
8756 type1
.t
|= (type
->t
& ~VT_TYPE
);
8761 decl_initializer(type
, sec
, c
, 0, size_only
);
8763 /* XXX: make it more general */
8764 if (!size_only
&& nb_elems
> 1) {
8765 unsigned long c_end
;
8770 error("range init not supported yet for dynamic storage");
8771 c_end
= c
+ nb_elems
* elem_size
;
8772 if (c_end
> sec
->data_allocated
)
8773 section_realloc(sec
, c_end
);
8774 src
= sec
->data
+ c
;
8776 for(i
= 1; i
< nb_elems
; i
++) {
8778 memcpy(dst
, src
, elem_size
);
8784 #define EXPR_CONST 1
8787 /* store a value or an expression directly in global data or in local array */
8788 static void init_putv(CType
*type
, Section
*sec
, unsigned long c
,
8789 int v
, int expr_type
)
8791 int saved_global_expr
, bt
, bit_pos
, bit_size
;
8793 unsigned long long bit_mask
;
8801 /* compound literals must be allocated globally in this case */
8802 saved_global_expr
= global_expr
;
8805 global_expr
= saved_global_expr
;
8806 /* NOTE: symbols are accepted */
8807 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) != VT_CONST
)
8808 error("initializer element is not constant");
8816 dtype
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
8819 /* XXX: not portable */
8820 /* XXX: generate error if incorrect relocation */
8821 gen_assign_cast(&dtype
);
8822 bt
= type
->t
& VT_BTYPE
;
8823 /* we'll write at most 12 bytes */
8824 if (c
+ 12 > sec
->data_allocated
) {
8825 section_realloc(sec
, c
+ 12);
8827 ptr
= sec
->data
+ c
;
8828 /* XXX: make code faster ? */
8829 if (!(type
->t
& VT_BITFIELD
)) {
8834 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
8835 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
8836 bit_mask
= (1LL << bit_size
) - 1;
8838 if ((vtop
->r
& VT_SYM
) &&
8844 (bt
== VT_INT
&& bit_size
!= 32)))
8845 error("initializer element is not computable at load time");
8848 vtop
->c
.i
= (vtop
->c
.i
!= 0);
8850 *(char *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8853 *(short *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8856 *(double *)ptr
= vtop
->c
.d
;
8859 *(long double *)ptr
= vtop
->c
.ld
;
8862 *(long long *)ptr
|= (vtop
->c
.ll
& bit_mask
) << bit_pos
;
8865 if (vtop
->r
& VT_SYM
) {
8866 greloc(sec
, vtop
->sym
, c
, R_DATA_32
);
8868 *(int *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8873 vset(&dtype
, VT_LOCAL
|VT_LVAL
, c
);
8880 /* put zeros for variable based init */
8881 static void init_putz(CType
*t
, Section
*sec
, unsigned long c
, int size
)
8884 /* nothing to do because globals are already set to zero */
8886 vpush_global_sym(&func_old_type
, TOK_memset
);
8894 /* 't' contains the type and storage info. 'c' is the offset of the
8895 object in section 'sec'. If 'sec' is NULL, it means stack based
8896 allocation. 'first' is true if array '{' must be read (multi
8897 dimension implicit array init handling). 'size_only' is true if
8898 size only evaluation is wanted (only for arrays). */
8899 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
8900 int first
, int size_only
)
8902 int index
, array_length
, n
, no_oblock
, nb
, parlevel
, i
;
8903 int size1
, align1
, expr_type
;
8907 if (type
->t
& VT_ARRAY
) {
8911 t1
= pointed_type(type
);
8912 size1
= type_size(t1
, &align1
);
8915 if ((first
&& tok
!= TOK_LSTR
&& tok
!= TOK_STR
) ||
8921 /* only parse strings here if correct type (otherwise: handle
8922 them as ((w)char *) expressions */
8923 if ((tok
== TOK_LSTR
&&
8924 #ifdef TCC_TARGET_PE
8925 (t1
->t
& VT_BTYPE
) == VT_SHORT
&& (t1
->t
& VT_UNSIGNED
)
8927 (t1
->t
& VT_BTYPE
) == VT_INT
8929 ) || (tok
== TOK_STR
&& (t1
->t
& VT_BTYPE
) == VT_BYTE
)) {
8930 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
8935 /* compute maximum number of chars wanted */
8937 cstr_len
= cstr
->size
;
8939 cstr_len
= cstr
->size
/ sizeof(nwchar_t
);
8942 if (n
>= 0 && nb
> (n
- array_length
))
8943 nb
= n
- array_length
;
8946 warning("initializer-string for array is too long");
8947 /* in order to go faster for common case (char
8948 string in global variable, we handle it
8950 if (sec
&& tok
== TOK_STR
&& size1
== 1) {
8951 memcpy(sec
->data
+ c
+ array_length
, cstr
->data
, nb
);
8955 ch
= ((unsigned char *)cstr
->data
)[i
];
8957 ch
= ((nwchar_t
*)cstr
->data
)[i
];
8958 init_putv(t1
, sec
, c
+ (array_length
+ i
) * size1
,
8966 /* only add trailing zero if enough storage (no
8967 warning in this case since it is standard) */
8968 if (n
< 0 || array_length
< n
) {
8970 init_putv(t1
, sec
, c
+ (array_length
* size1
), 0, EXPR_VAL
);
8976 while (tok
!= '}') {
8977 decl_designator(type
, sec
, c
, &index
, NULL
, size_only
);
8978 if (n
>= 0 && index
>= n
)
8979 error("index too large");
8980 /* must put zero in holes (note that doing it that way
8981 ensures that it even works with designators) */
8982 if (!size_only
&& array_length
< index
) {
8983 init_putz(t1
, sec
, c
+ array_length
* size1
,
8984 (index
- array_length
) * size1
);
8987 if (index
> array_length
)
8988 array_length
= index
;
8989 /* special test for multi dimensional arrays (may not
8990 be strictly correct if designators are used at the
8992 if (index
>= n
&& no_oblock
)
9001 /* put zeros at the end */
9002 if (!size_only
&& n
>= 0 && array_length
< n
) {
9003 init_putz(t1
, sec
, c
+ array_length
* size1
,
9004 (n
- array_length
) * size1
);
9006 /* patch type size if needed */
9008 s
->c
= array_length
;
9009 } else if ((type
->t
& VT_BTYPE
) == VT_STRUCT
&&
9010 (sec
|| !first
|| tok
== '{')) {
9013 /* NOTE: the previous test is a specific case for automatic
9014 struct/union init */
9015 /* XXX: union needs only one init */
9017 /* XXX: this test is incorrect for local initializers
9018 beginning with ( without {. It would be much more difficult
9019 to do it correctly (ideally, the expression parser should
9020 be used in all cases) */
9026 while (tok
== '(') {
9030 if (!parse_btype(&type1
, &ad1
))
9032 type_decl(&type1
, &ad1
, &n
, TYPE_ABSTRACT
);
9034 if (!is_assignable_types(type
, &type1
))
9035 error("invalid type for cast");
9040 if (first
|| tok
== '{') {
9049 while (tok
!= '}') {
9050 decl_designator(type
, sec
, c
, NULL
, &f
, size_only
);
9052 if (!size_only
&& array_length
< index
) {
9053 init_putz(type
, sec
, c
+ array_length
,
9054 index
- array_length
);
9056 index
= index
+ type_size(&f
->type
, &align1
);
9057 if (index
> array_length
)
9058 array_length
= index
;
9060 if (no_oblock
&& f
== NULL
)
9066 /* put zeros at the end */
9067 if (!size_only
&& array_length
< n
) {
9068 init_putz(type
, sec
, c
+ array_length
,
9077 } else if (tok
== '{') {
9079 decl_initializer(type
, sec
, c
, first
, size_only
);
9081 } else if (size_only
) {
9082 /* just skip expression */
9084 while ((parlevel
> 0 || (tok
!= '}' && tok
!= ',')) &&
9088 else if (tok
== ')')
9093 /* currently, we always use constant expression for globals
9094 (may change for scripting case) */
9095 expr_type
= EXPR_CONST
;
9097 expr_type
= EXPR_ANY
;
9098 init_putv(type
, sec
, c
, 0, expr_type
);
9102 /* parse an initializer for type 't' if 'has_init' is non zero, and
9103 allocate space in local or global data space ('r' is either
9104 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
9105 variable 'v' of scope 'scope' is declared before initializers are
9106 parsed. If 'v' is zero, then a reference to the new object is put
9107 in the value stack. If 'has_init' is 2, a special parsing is done
9108 to handle string constants. */
9109 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
9110 int has_init
, int v
, int scope
)
9112 int size
, align
, addr
, data_offset
;
9114 ParseState saved_parse_state
;
9115 TokenString init_str
;
9118 size
= type_size(type
, &align
);
9119 /* If unknown size, we must evaluate it before
9120 evaluating initializers because
9121 initializers can generate global data too
9122 (e.g. string pointers or ISOC99 compound
9123 literals). It also simplifies local
9124 initializers handling */
9125 tok_str_new(&init_str
);
9128 error("unknown type size");
9129 /* get all init string */
9130 if (has_init
== 2) {
9131 /* only get strings */
9132 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
9133 tok_str_add_tok(&init_str
);
9138 while (level
> 0 || (tok
!= ',' && tok
!= ';')) {
9140 error("unexpected end of file in initializer");
9141 tok_str_add_tok(&init_str
);
9144 else if (tok
== '}') {
9152 tok_str_add(&init_str
, -1);
9153 tok_str_add(&init_str
, 0);
9156 save_parse_state(&saved_parse_state
);
9158 macro_ptr
= init_str
.str
;
9160 decl_initializer(type
, NULL
, 0, 1, 1);
9161 /* prepare second initializer parsing */
9162 macro_ptr
= init_str
.str
;
9165 /* if still unknown size, error */
9166 size
= type_size(type
, &align
);
9168 error("unknown type size");
9170 /* take into account specified alignment if bigger */
9172 if (ad
->aligned
> align
)
9173 align
= ad
->aligned
;
9174 } else if (ad
->packed
) {
9177 if ((r
& VT_VALMASK
) == VT_LOCAL
) {
9179 if (do_bounds_check
&& (type
->t
& VT_ARRAY
))
9181 loc
= (loc
- size
) & -align
;
9183 /* handles bounds */
9184 /* XXX: currently, since we do only one pass, we cannot track
9185 '&' operators, so we add only arrays */
9186 if (do_bounds_check
&& (type
->t
& VT_ARRAY
)) {
9187 unsigned long *bounds_ptr
;
9188 /* add padding between regions */
9190 /* then add local bound info */
9191 bounds_ptr
= section_ptr_add(lbounds_section
, 2 * sizeof(unsigned long));
9192 bounds_ptr
[0] = addr
;
9193 bounds_ptr
[1] = size
;
9196 /* local variable */
9197 sym_push(v
, type
, r
, addr
);
9199 /* push local reference */
9200 vset(type
, r
, addr
);
9206 if (v
&& scope
== VT_CONST
) {
9207 /* see if the symbol was already defined */
9210 if (!is_compatible_types(&sym
->type
, type
))
9211 error("incompatible types for redefinition of '%s'",
9212 get_tok_str(v
, NULL
));
9213 if (sym
->type
.t
& VT_EXTERN
) {
9214 /* if the variable is extern, it was not allocated */
9215 sym
->type
.t
&= ~VT_EXTERN
;
9216 /* set array size if it was ommited in extern
9218 if ((sym
->type
.t
& VT_ARRAY
) &&
9219 sym
->type
.ref
->c
< 0 &&
9221 sym
->type
.ref
->c
= type
->ref
->c
;
9223 /* we accept several definitions of the same
9224 global variable. this is tricky, because we
9225 must play with the SHN_COMMON type of the symbol */
9226 /* XXX: should check if the variable was already
9227 initialized. It is incorrect to initialized it
9229 /* no init data, we won't add more to the symbol */
9236 /* allocate symbol in corresponding section */
9241 else if (tcc_state
->nocommon
)
9245 data_offset
= sec
->data_offset
;
9246 data_offset
= (data_offset
+ align
- 1) & -align
;
9248 /* very important to increment global pointer at this time
9249 because initializers themselves can create new initializers */
9250 data_offset
+= size
;
9251 /* add padding if bound check */
9252 if (do_bounds_check
)
9254 sec
->data_offset
= data_offset
;
9255 /* allocate section space to put the data */
9256 if (sec
->sh_type
!= SHT_NOBITS
&&
9257 data_offset
> sec
->data_allocated
)
9258 section_realloc(sec
, data_offset
);
9259 /* align section if needed */
9260 if (align
> sec
->sh_addralign
)
9261 sec
->sh_addralign
= align
;
9263 addr
= 0; /* avoid warning */
9267 if (scope
!= VT_CONST
|| !sym
) {
9268 sym
= sym_push(v
, type
, r
| VT_SYM
, 0);
9270 /* update symbol definition */
9272 put_extern_sym(sym
, sec
, addr
, size
);
9275 /* put a common area */
9276 put_extern_sym(sym
, NULL
, align
, size
);
9277 /* XXX: find a nicer way */
9278 esym
= &((ElfW(Sym
) *)symtab_section
->data
)[sym
->c
];
9279 esym
->st_shndx
= SHN_COMMON
;
9284 /* push global reference */
9285 sym
= get_sym_ref(type
, sec
, addr
, size
);
9287 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
9291 /* handles bounds now because the symbol must be defined
9292 before for the relocation */
9293 if (do_bounds_check
) {
9294 unsigned long *bounds_ptr
;
9296 greloc(bounds_section
, sym
, bounds_section
->data_offset
, R_DATA_32
);
9297 /* then add global bound info */
9298 bounds_ptr
= section_ptr_add(bounds_section
, 2 * sizeof(long));
9299 bounds_ptr
[0] = 0; /* relocated */
9300 bounds_ptr
[1] = size
;
9304 decl_initializer(type
, sec
, addr
, 1, 0);
9305 /* restore parse state if needed */
9307 tok_str_free(init_str
.str
);
9308 restore_parse_state(&saved_parse_state
);
9314 void put_func_debug(Sym
*sym
)
9319 /* XXX: we put here a dummy type */
9320 snprintf(buf
, sizeof(buf
), "%s:%c1",
9321 funcname
, sym
->type
.t
& VT_STATIC
? 'f' : 'F');
9322 put_stabs_r(buf
, N_FUN
, 0, file
->line_num
, 0,
9323 cur_text_section
, sym
->c
);
9324 /* //gr gdb wants a line at the function */
9325 put_stabn(N_SLINE
, 0, file
->line_num
, 0);
9330 /* parse an old style function declaration list */
9331 /* XXX: check multiple parameter */
9332 static void func_decl_list(Sym
*func_sym
)
9339 /* parse each declaration */
9340 while (tok
!= '{' && tok
!= ';' && tok
!= ',' && tok
!= TOK_EOF
) {
9341 if (!parse_btype(&btype
, &ad
))
9342 expect("declaration list");
9343 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
9344 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
9346 /* we accept no variable after */
9350 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
9351 /* find parameter in function parameter list */
9354 if ((s
->v
& ~SYM_FIELD
) == v
)
9358 error("declaration for parameter '%s' but no such parameter",
9359 get_tok_str(v
, NULL
));
9361 /* check that no storage specifier except 'register' was given */
9362 if (type
.t
& VT_STORAGE
)
9363 error("storage class specified for '%s'", get_tok_str(v
, NULL
));
9364 convert_parameter_type(&type
);
9365 /* we can add the type (NOTE: it could be local to the function) */
9367 /* accept other parameters */
9378 /* parse a function defined by symbol 'sym' and generate its code in
9379 'cur_text_section' */
9380 static void gen_function(Sym
*sym
)
9382 int saved_nocode_wanted
= nocode_wanted
;
9384 ind
= cur_text_section
->data_offset
;
9385 /* NOTE: we patch the symbol size later */
9386 put_extern_sym(sym
, cur_text_section
, ind
, 0);
9387 funcname
= get_tok_str(sym
->v
, NULL
);
9389 /* put debug symbol */
9391 put_func_debug(sym
);
9392 /* push a dummy symbol to enable local sym storage */
9393 sym_push2(&local_stack
, SYM_FIELD
, 0, 0);
9394 gfunc_prolog(&sym
->type
);
9396 block(NULL
, NULL
, NULL
, NULL
, 0, 0);
9399 cur_text_section
->data_offset
= ind
;
9400 label_pop(&global_label_stack
, NULL
);
9401 sym_pop(&local_stack
, NULL
); /* reset local stack */
9402 /* end of function */
9403 /* patch symbol size */
9404 ((ElfW(Sym
) *)symtab_section
->data
)[sym
->c
].st_size
=
9407 put_stabn(N_FUN
, 0, 0, ind
- func_ind
);
9409 /* It's better to crash than to generate wrong code */
9410 cur_text_section
= NULL
;
9411 funcname
= ""; /* for safety */
9412 func_vt
.t
= VT_VOID
; /* for safety */
9413 ind
= 0; /* for safety */
9414 nocode_wanted
= saved_nocode_wanted
;
9417 static void gen_inline_functions(void)
9421 int *str
, inline_generated
;
9423 /* iterate while inline function are referenced */
9425 inline_generated
= 0;
9426 for(sym
= global_stack
; sym
!= NULL
; sym
= sym
->prev
) {
9428 if (((type
->t
& VT_BTYPE
) == VT_FUNC
) &&
9429 (type
->t
& (VT_STATIC
| VT_INLINE
)) ==
9430 (VT_STATIC
| VT_INLINE
) &&
9432 /* the function was used: generate its code and
9433 convert it to a normal function */
9434 str
= INLINE_DEF(sym
->r
);
9435 sym
->r
= VT_SYM
| VT_CONST
;
9436 sym
->type
.t
&= ~VT_INLINE
;
9440 cur_text_section
= text_section
;
9442 macro_ptr
= NULL
; /* fail safe */
9445 inline_generated
= 1;
9448 if (!inline_generated
)
9452 /* free all remaining inline function tokens */
9453 for(sym
= global_stack
; sym
!= NULL
; sym
= sym
->prev
) {
9455 if (((type
->t
& VT_BTYPE
) == VT_FUNC
) &&
9456 (type
->t
& (VT_STATIC
| VT_INLINE
)) ==
9457 (VT_STATIC
| VT_INLINE
)) {
9458 //gr printf("sym %d %s\n", sym->r, get_tok_str(sym->v, NULL));
9459 if (sym
->r
== (VT_SYM
| VT_CONST
)) //gr beware!
9461 str
= INLINE_DEF(sym
->r
);
9463 sym
->r
= 0; /* fail safe */
9468 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
9469 static void decl(int l
)
9477 if (!parse_btype(&btype
, &ad
)) {
9478 /* skip redundant ';' */
9479 /* XXX: find more elegant solution */
9484 if (l
== VT_CONST
&&
9485 (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
)) {
9486 /* global asm block */
9490 /* special test for old K&R protos without explicit int
9491 type. Only accepted when defining global data */
9492 if (l
== VT_LOCAL
|| tok
< TOK_DEFINE
)
9496 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
9497 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
9499 /* we accept no variable after */
9503 while (1) { /* iterate thru each declaration */
9505 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
9509 type_to_str(buf
, sizeof(buf
), t
, get_tok_str(v
, NULL
));
9510 printf("type = '%s'\n", buf
);
9513 if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
9514 /* if old style function prototype, we accept a
9517 if (sym
->c
== FUNC_OLD
)
9518 func_decl_list(sym
);
9523 error("cannot use local functions");
9524 if ((type
.t
& VT_BTYPE
) != VT_FUNC
)
9525 expect("function definition");
9527 /* reject abstract declarators in function definition */
9529 while ((sym
= sym
->next
) != NULL
)
9530 if (!(sym
->v
& ~SYM_FIELD
))
9531 expect("identifier");
9533 /* XXX: cannot do better now: convert extern line to static inline */
9534 if ((type
.t
& (VT_EXTERN
| VT_INLINE
)) == (VT_EXTERN
| VT_INLINE
))
9535 type
.t
= (type
.t
& ~VT_EXTERN
) | VT_STATIC
;
9539 if ((sym
->type
.t
& VT_BTYPE
) != VT_FUNC
)
9541 /* specific case: if not func_call defined, we put
9542 the one of the prototype */
9543 /* XXX: should have default value */
9544 r
= sym
->type
.ref
->r
;
9545 if (FUNC_CALL(r
) != FUNC_CDECL
9546 && FUNC_CALL(type
.ref
->r
) == FUNC_CDECL
)
9547 FUNC_CALL(type
.ref
->r
) = FUNC_CALL(r
);
9549 FUNC_EXPORT(type
.ref
->r
) = 1;
9551 if (!is_compatible_types(&sym
->type
, &type
)) {
9553 error("incompatible types for redefinition of '%s'",
9554 get_tok_str(v
, NULL
));
9556 /* if symbol is already defined, then put complete type */
9559 /* put function symbol */
9560 sym
= global_identifier_push(v
, type
.t
, 0);
9561 sym
->type
.ref
= type
.ref
;
9564 /* static inline functions are just recorded as a kind
9565 of macro. Their code will be emitted at the end of
9566 the compilation unit only if they are used */
9567 if ((type
.t
& (VT_INLINE
| VT_STATIC
)) ==
9568 (VT_INLINE
| VT_STATIC
)) {
9569 TokenString func_str
;
9572 tok_str_new(&func_str
);
9578 error("unexpected end of file");
9579 tok_str_add_tok(&func_str
);
9584 } else if (t
== '}') {
9586 if (block_level
== 0)
9590 tok_str_add(&func_str
, -1);
9591 tok_str_add(&func_str
, 0);
9592 INLINE_DEF(sym
->r
) = func_str
.str
;
9594 /* compute text section */
9595 cur_text_section
= ad
.section
;
9596 if (!cur_text_section
)
9597 cur_text_section
= text_section
;
9598 sym
->r
= VT_SYM
| VT_CONST
;
9603 if (btype
.t
& VT_TYPEDEF
) {
9604 /* save typedefed type */
9605 /* XXX: test storage specifiers ? */
9606 sym
= sym_push(v
, &type
, 0, 0);
9607 sym
->type
.t
|= VT_TYPEDEF
;
9608 } else if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
9609 /* external function definition */
9610 /* specific case for func_call attribute */
9612 type
.ref
->r
= ad
.func_attr
;
9613 external_sym(v
, &type
, 0);
9615 /* not lvalue if array */
9617 if (!(type
.t
& VT_ARRAY
))
9618 r
|= lvalue_type(type
.t
);
9619 has_init
= (tok
== '=');
9620 if ((btype
.t
& VT_EXTERN
) ||
9621 ((type
.t
& VT_ARRAY
) && (type
.t
& VT_STATIC
) &&
9622 !has_init
&& l
== VT_CONST
&& type
.ref
->c
< 0)) {
9623 /* external variable */
9624 /* NOTE: as GCC, uninitialized global static
9625 arrays of null size are considered as
9627 external_sym(v
, &type
, r
);
9629 type
.t
|= (btype
.t
& VT_STATIC
); /* Retain "static". */
9630 if (type
.t
& VT_STATIC
)
9636 decl_initializer_alloc(&type
, &ad
, r
,
9650 /* better than nothing, but needs extension to handle '-E' option
9652 static void preprocess_init(TCCState
*s1
)
9654 s1
->include_stack_ptr
= s1
->include_stack
;
9655 /* XXX: move that before to avoid having to initialize
9656 file->ifdef_stack_ptr ? */
9657 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
9658 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
9660 /* XXX: not ANSI compliant: bound checking says error */
9662 s1
->pack_stack
[0] = 0;
9663 s1
->pack_stack_ptr
= s1
->pack_stack
;
9666 /* compile the C file opened in 'file'. Return non zero if errors. */
9667 static int tcc_compile(TCCState
*s1
)
9671 volatile int section_sym
;
9674 printf("%s: **** new file\n", file
->filename
);
9676 preprocess_init(s1
);
9678 cur_text_section
= NULL
;
9680 anon_sym
= SYM_FIRST_ANOM
;
9682 /* file info: full path + filename */
9683 section_sym
= 0; /* avoid warning */
9685 section_sym
= put_elf_sym(symtab_section
, 0, 0,
9686 ELFW(ST_INFO
)(STB_LOCAL
, STT_SECTION
), 0,
9687 text_section
->sh_num
, NULL
);
9688 getcwd(buf
, sizeof(buf
));
9690 normalize_slashes(buf
);
9692 pstrcat(buf
, sizeof(buf
), "/");
9693 put_stabs_r(buf
, N_SO
, 0, 0,
9694 text_section
->data_offset
, text_section
, section_sym
);
9695 put_stabs_r(file
->filename
, N_SO
, 0, 0,
9696 text_section
->data_offset
, text_section
, section_sym
);
9698 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
9699 symbols can be safely used */
9700 put_elf_sym(symtab_section
, 0, 0,
9701 ELFW(ST_INFO
)(STB_LOCAL
, STT_FILE
), 0,
9702 SHN_ABS
, file
->filename
);
9704 /* define some often used types */
9705 int_type
.t
= VT_INT
;
9707 char_pointer_type
.t
= VT_BYTE
;
9708 mk_pointer(&char_pointer_type
);
9710 func_old_type
.t
= VT_FUNC
;
9711 func_old_type
.ref
= sym_push(SYM_FIELD
, &int_type
, FUNC_CDECL
, FUNC_OLD
);
9713 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
9714 float_type
.t
= VT_FLOAT
;
9715 double_type
.t
= VT_DOUBLE
;
9717 func_float_type
.t
= VT_FUNC
;
9718 func_float_type
.ref
= sym_push(SYM_FIELD
, &float_type
, FUNC_CDECL
, FUNC_OLD
);
9719 func_double_type
.t
= VT_FUNC
;
9720 func_double_type
.ref
= sym_push(SYM_FIELD
, &double_type
, FUNC_CDECL
, FUNC_OLD
);
9724 /* define 'void *alloca(unsigned int)' builtin function */
9729 sym
= sym_push(p
, mk_pointer(VT_VOID
), FUNC_CDECL
, FUNC_NEW
);
9730 s1
= sym_push(SYM_FIELD
, VT_UNSIGNED
| VT_INT
, 0, 0);
9733 sym_push(TOK_alloca
, VT_FUNC
| (p
<< VT_STRUCT_SHIFT
), VT_CONST
, 0);
9737 define_start
= define_stack
;
9740 if (setjmp(s1
->error_jmp_buf
) == 0) {
9742 s1
->error_set_jmp_enabled
= 1;
9744 ch
= file
->buf_ptr
[0];
9745 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
9746 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
;
9750 expect("declaration");
9752 /* end of translation unit info */
9754 put_stabs_r(NULL
, N_SO
, 0, 0,
9755 text_section
->data_offset
, text_section
, section_sym
);
9758 s1
->error_set_jmp_enabled
= 0;
9760 /* reset define stack, but leave -Dsymbols (may be incorrect if
9761 they are undefined) */
9762 free_defines(define_start
);
9764 gen_inline_functions();
9766 sym_pop(&global_stack
, NULL
);
9767 sym_pop(&local_stack
, NULL
);
9769 return s1
->nb_errors
!= 0 ? -1 : 0;
9772 /* Preprocess the current file */
9773 /* XXX: add line and file infos, add options to preserve spaces */
9774 static int tcc_preprocess(TCCState
*s1
)
9777 BufferedFile
*file_ref
;
9778 int token_seen
, line_ref
;
9780 preprocess_init(s1
);
9781 define_start
= define_stack
;
9782 ch
= file
->buf_ptr
[0];
9784 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
9785 parse_flags
= PARSE_FLAG_ASM_COMMENTS
| PARSE_FLAG_PREPROCESS
|
9786 PARSE_FLAG_LINEFEED
;
9794 if (tok
== TOK_EOF
) {
9796 } else if (tok
== TOK_LINEFEED
) {
9801 } else if (token_seen
) {
9802 fputc(' ', s1
->outfile
);
9804 int d
= file
->line_num
- line_ref
;
9805 if (file
!= file_ref
|| d
< 0 || d
>= 8)
9806 fprintf(s1
->outfile
, "# %d \"%s\"\n", file
->line_num
, file
->filename
);
9809 fputs("\n", s1
->outfile
), --d
;
9810 line_ref
= (file_ref
= file
)->line_num
;
9813 fputs(get_tok_str(tok
, &tokc
), s1
->outfile
);
9815 free_defines(define_start
);
9820 int tcc_compile_string(TCCState
*s
, const char *str
)
9822 BufferedFile bf1
, *bf
= &bf1
;
9826 /* init file structure */
9828 /* XXX: avoid copying */
9830 buf
= tcc_malloc(len
+ 1);
9833 memcpy(buf
, str
, len
);
9836 bf
->buf_end
= buf
+ len
;
9837 pstrcpy(bf
->filename
, sizeof(bf
->filename
), "<string>");
9840 ret
= tcc_compile(s
);
9844 /* currently, no need to close */
9849 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
9850 void tcc_define_symbol(TCCState
*s1
, const char *sym
, const char *value
)
9852 BufferedFile bf1
, *bf
= &bf1
;
9854 pstrcpy(bf
->buffer
, IO_BUF_SIZE
, sym
);
9855 pstrcat(bf
->buffer
, IO_BUF_SIZE
, " ");
9859 pstrcat(bf
->buffer
, IO_BUF_SIZE
, value
);
9861 /* init file structure */
9863 bf
->buf_ptr
= bf
->buffer
;
9864 bf
->buf_end
= bf
->buffer
+ strlen(bf
->buffer
);
9865 *bf
->buf_end
= CH_EOB
;
9866 bf
->filename
[0] = '\0';
9870 s1
->include_stack_ptr
= s1
->include_stack
;
9872 /* parse with define parser */
9873 ch
= file
->buf_ptr
[0];
9879 /* undefine a preprocessor symbol */
9880 void tcc_undefine_symbol(TCCState
*s1
, const char *sym
)
9884 ts
= tok_alloc(sym
, strlen(sym
));
9885 s
= define_find(ts
->tok
);
9886 /* undefine symbol by putting an invalid name */
9891 #ifdef CONFIG_TCC_ASM
9893 #ifdef TCC_TARGET_I386
9894 #include "i386-asm.c"
9899 static void asm_instr(void)
9901 error("inline asm() not supported");
9903 static void asm_global_instr(void)
9905 error("inline asm() not supported");
9911 #ifdef TCC_TARGET_COFF
9912 #include "tcccoff.c"
9915 #ifdef TCC_TARGET_PE
9919 /* print the position in the source file of PC value 'pc' by reading
9920 the stabs debug information */
9921 static void rt_printline(unsigned long wanted_pc
)
9923 Stab_Sym
*sym
, *sym_end
;
9924 char func_name
[128], last_func_name
[128];
9925 unsigned long func_addr
, last_pc
, pc
;
9926 const char *incl_files
[INCLUDE_STACK_SIZE
];
9927 int incl_index
, len
, last_line_num
, i
;
9928 const char *str
, *p
;
9930 fprintf(stderr
, "0x%08lx:", wanted_pc
);
9932 func_name
[0] = '\0';
9935 last_func_name
[0] = '\0';
9936 last_pc
= 0xffffffff;
9938 sym
= (Stab_Sym
*)stab_section
->data
+ 1;
9939 sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
9940 while (sym
< sym_end
) {
9941 switch(sym
->n_type
) {
9942 /* function start or end */
9944 if (sym
->n_strx
== 0) {
9945 /* we test if between last line and end of function */
9946 pc
= sym
->n_value
+ func_addr
;
9947 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
9949 func_name
[0] = '\0';
9952 str
= stabstr_section
->data
+ sym
->n_strx
;
9953 p
= strchr(str
, ':');
9955 pstrcpy(func_name
, sizeof(func_name
), str
);
9958 if (len
> sizeof(func_name
) - 1)
9959 len
= sizeof(func_name
) - 1;
9960 memcpy(func_name
, str
, len
);
9961 func_name
[len
] = '\0';
9963 func_addr
= sym
->n_value
;
9966 /* line number info */
9968 pc
= sym
->n_value
+ func_addr
;
9969 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
9972 last_line_num
= sym
->n_desc
;
9974 strcpy(last_func_name
, func_name
);
9978 str
= stabstr_section
->data
+ sym
->n_strx
;
9980 if (incl_index
< INCLUDE_STACK_SIZE
) {
9981 incl_files
[incl_index
++] = str
;
9989 if (sym
->n_strx
== 0) {
9990 incl_index
= 0; /* end of translation unit */
9992 str
= stabstr_section
->data
+ sym
->n_strx
;
9993 /* do not add path */
9995 if (len
> 0 && str
[len
- 1] != '/')
10003 /* second pass: we try symtab symbols (no line number info) */
10006 ElfW(Sym
) *sym
, *sym_end
;
10009 sym_end
= (ElfW(Sym
) *)(symtab_section
->data
+ symtab_section
->data_offset
);
10010 for(sym
= (ElfW(Sym
) *)symtab_section
->data
+ 1;
10013 type
= ELFW(ST_TYPE
)(sym
->st_info
);
10014 if (type
== STT_FUNC
) {
10015 if (wanted_pc
>= sym
->st_value
&&
10016 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
10017 pstrcpy(last_func_name
, sizeof(last_func_name
),
10018 strtab_section
->data
+ sym
->st_name
);
10024 /* did not find any info: */
10025 fprintf(stderr
, " ???\n");
10028 if (last_func_name
[0] != '\0') {
10029 fprintf(stderr
, " %s()", last_func_name
);
10031 if (incl_index
> 0) {
10032 fprintf(stderr
, " (%s:%d",
10033 incl_files
[incl_index
- 1], last_line_num
);
10034 for(i
= incl_index
- 2; i
>= 0; i
--)
10035 fprintf(stderr
, ", included from %s", incl_files
[i
]);
10036 fprintf(stderr
, ")");
10038 fprintf(stderr
, "\n");
10041 #if !defined(_WIN32) && !defined(CONFIG_TCCBOOT)
10045 /* fix for glibc 2.1 */
10047 #define REG_EIP EIP
10048 #define REG_EBP EBP
10051 /* return the PC at frame level 'level'. Return non zero if not found */
10052 static int rt_get_caller_pc(unsigned long *paddr
,
10053 ucontext_t
*uc
, int level
)
10059 #if defined(__FreeBSD__)
10060 *paddr
= uc
->uc_mcontext
.mc_eip
;
10061 #elif defined(__dietlibc__)
10062 *paddr
= uc
->uc_mcontext
.eip
;
10064 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
10068 #if defined(__FreeBSD__)
10069 fp
= uc
->uc_mcontext
.mc_ebp
;
10070 #elif defined(__dietlibc__)
10071 fp
= uc
->uc_mcontext
.ebp
;
10073 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
10075 for(i
=1;i
<level
;i
++) {
10076 /* XXX: check address validity with program info */
10077 if (fp
<= 0x1000 || fp
>= 0xc0000000)
10079 fp
= ((unsigned long *)fp
)[0];
10081 *paddr
= ((unsigned long *)fp
)[1];
10085 #elif defined(__x86_64__)
10086 /* return the PC at frame level 'level'. Return non zero if not found */
10087 static int rt_get_caller_pc(unsigned long *paddr
,
10088 ucontext_t
*uc
, int level
)
10094 /* XXX: only support linux */
10095 *paddr
= uc
->uc_mcontext
.gregs
[REG_RIP
];
10098 fp
= uc
->uc_mcontext
.gregs
[REG_RBP
];
10099 for(i
=1;i
<level
;i
++) {
10100 /* XXX: check address validity with program info */
10101 if (fp
<= 0x1000 || fp
>= 0xc0000000)
10103 fp
= ((unsigned long *)fp
)[0];
10105 *paddr
= ((unsigned long *)fp
)[1];
10111 #warning add arch specific rt_get_caller_pc()
10113 static int rt_get_caller_pc(unsigned long *paddr
,
10114 ucontext_t
*uc
, int level
)
10120 /* emit a run time error at position 'pc' */
10121 void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
10128 fprintf(stderr
, "Runtime error: ");
10129 vfprintf(stderr
, fmt
, ap
);
10130 fprintf(stderr
, "\n");
10131 for(i
=0;i
<num_callers
;i
++) {
10132 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
10135 fprintf(stderr
, "at ");
10137 fprintf(stderr
, "by ");
10144 /* signal handler for fatal errors */
10145 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
10147 ucontext_t
*uc
= puc
;
10151 switch(siginf
->si_code
) {
10154 rt_error(uc
, "division by zero");
10157 rt_error(uc
, "floating point exception");
10163 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
10164 rt_error(uc
, *rt_bound_error_msg
);
10166 rt_error(uc
, "dereferencing invalid pointer");
10169 rt_error(uc
, "illegal instruction");
10172 rt_error(uc
, "abort() called");
10175 rt_error(uc
, "caught signal %d", signum
);
10182 /* do all relocations (needed before using tcc_get_symbol()) */
10183 int tcc_relocate(TCCState
*s1
)
10190 #ifdef TCC_TARGET_PE
10191 pe_add_runtime(s1
);
10193 tcc_add_runtime(s1
);
10196 relocate_common_syms();
10198 tcc_add_linker_symbols(s1
);
10199 #ifndef TCC_TARGET_PE
10200 build_got_entries(s1
);
10202 /* compute relocation address : section are relocated in place. We
10203 also alloc the bss space */
10204 for(i
= 1; i
< s1
->nb_sections
; i
++) {
10205 s
= s1
->sections
[i
];
10206 if (s
->sh_flags
& SHF_ALLOC
) {
10207 if (s
->sh_type
== SHT_NOBITS
)
10208 s
->data
= tcc_mallocz(s
->data_offset
);
10209 s
->sh_addr
= (unsigned long)s
->data
;
10213 relocate_syms(s1
, 1);
10215 if (s1
->nb_errors
!= 0)
10218 /* relocate each section */
10219 for(i
= 1; i
< s1
->nb_sections
; i
++) {
10220 s
= s1
->sections
[i
];
10222 relocate_section(s1
, s
);
10225 /* mark executable sections as executable in memory */
10226 for(i
= 1; i
< s1
->nb_sections
; i
++) {
10227 s
= s1
->sections
[i
];
10228 if ((s
->sh_flags
& (SHF_ALLOC
| SHF_EXECINSTR
)) ==
10229 (SHF_ALLOC
| SHF_EXECINSTR
))
10230 set_pages_executable(s
->data
, s
->data_offset
);
10235 /* launch the compiled program with the given arguments */
10236 int tcc_run(TCCState
*s1
, int argc
, char **argv
)
10238 int (*prog_main
)(int, char **);
10240 if (tcc_relocate(s1
) < 0)
10243 prog_main
= tcc_get_symbol_err(s1
, "main");
10246 #if defined(_WIN32) || defined(CONFIG_TCCBOOT)
10247 error("debug mode currently not available for Windows");
10249 struct sigaction sigact
;
10250 /* install TCC signal handlers to print debug info on fatal
10252 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
10253 sigact
.sa_sigaction
= sig_error
;
10254 sigemptyset(&sigact
.sa_mask
);
10255 sigaction(SIGFPE
, &sigact
, NULL
);
10256 sigaction(SIGILL
, &sigact
, NULL
);
10257 sigaction(SIGSEGV
, &sigact
, NULL
);
10258 sigaction(SIGBUS
, &sigact
, NULL
);
10259 sigaction(SIGABRT
, &sigact
, NULL
);
10263 #ifdef CONFIG_TCC_BCHECK
10264 if (do_bounds_check
) {
10265 void (*bound_init
)(void);
10267 /* set error function */
10268 rt_bound_error_msg
= (void *)tcc_get_symbol_err(s1
,
10269 "__bound_error_msg");
10271 /* XXX: use .init section so that it also work in binary ? */
10272 bound_init
= (void *)tcc_get_symbol_err(s1
, "__bound_init");
10276 return (*prog_main
)(argc
, argv
);
10279 void tcc_memstats(void)
10282 printf("memory in use: %d\n", mem_cur_size
);
10286 static void tcc_cleanup(void)
10290 if (NULL
== tcc_state
)
10294 /* free -D defines */
10295 free_defines(NULL
);
10298 n
= tok_ident
- TOK_IDENT
;
10299 for(i
= 0; i
< n
; i
++)
10300 tcc_free(table_ident
[i
]);
10301 tcc_free(table_ident
);
10303 /* free sym_pools */
10304 dynarray_reset(&sym_pools
, &nb_sym_pools
);
10305 /* string buffer */
10306 cstr_free(&tokcstr
);
10307 /* reset symbol stack */
10308 sym_free_first
= NULL
;
10309 /* cleanup from error/setjmp */
10313 TCCState
*tcc_new(void)
10322 s
= tcc_mallocz(sizeof(TCCState
));
10326 s
->output_type
= TCC_OUTPUT_MEMORY
;
10328 /* init isid table */
10329 for(i
=CH_EOF
;i
<256;i
++)
10330 isidnum_table
[i
-CH_EOF
] = isid(i
) || isnum(i
);
10332 /* add all tokens */
10333 table_ident
= NULL
;
10334 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
10336 tok_ident
= TOK_IDENT
;
10345 ts
= tok_alloc(p
, r
- p
- 1);
10349 /* we add dummy defines for some special macros to speed up tests
10350 and to have working defined() */
10351 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
10352 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
10353 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
10354 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
10356 /* standard defines */
10357 tcc_define_symbol(s
, "__STDC__", NULL
);
10358 tcc_define_symbol(s
, "__STDC_VERSION__", "199901L");
10359 #if defined(TCC_TARGET_I386)
10360 tcc_define_symbol(s
, "__i386__", NULL
);
10362 #if defined(TCC_TARGET_X86_64)
10363 tcc_define_symbol(s
, "__x86_64__", NULL
);
10365 #if defined(TCC_TARGET_ARM)
10366 tcc_define_symbol(s
, "__ARM_ARCH_4__", NULL
);
10367 tcc_define_symbol(s
, "__arm_elf__", NULL
);
10368 tcc_define_symbol(s
, "__arm_elf", NULL
);
10369 tcc_define_symbol(s
, "arm_elf", NULL
);
10370 tcc_define_symbol(s
, "__arm__", NULL
);
10371 tcc_define_symbol(s
, "__arm", NULL
);
10372 tcc_define_symbol(s
, "arm", NULL
);
10373 tcc_define_symbol(s
, "__APCS_32__", NULL
);
10375 #ifdef TCC_TARGET_PE
10376 tcc_define_symbol(s
, "_WIN32", NULL
);
10378 tcc_define_symbol(s
, "__unix__", NULL
);
10379 tcc_define_symbol(s
, "__unix", NULL
);
10380 #if defined(__linux)
10381 tcc_define_symbol(s
, "__linux__", NULL
);
10382 tcc_define_symbol(s
, "__linux", NULL
);
10385 /* tiny C specific defines */
10386 tcc_define_symbol(s
, "__TINYC__", NULL
);
10388 /* tiny C & gcc defines */
10389 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned int");
10390 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "int");
10391 #ifdef TCC_TARGET_PE
10392 tcc_define_symbol(s
, "__WCHAR_TYPE__", "unsigned short");
10394 tcc_define_symbol(s
, "__WCHAR_TYPE__", "int");
10397 #ifndef TCC_TARGET_PE
10398 /* default library paths */
10399 tcc_add_library_path(s
, CONFIG_SYSROOT
"/usr/local/lib");
10400 tcc_add_library_path(s
, CONFIG_SYSROOT
"/usr/lib");
10401 tcc_add_library_path(s
, CONFIG_SYSROOT
"/lib");
10404 /* no section zero */
10405 dynarray_add((void ***)&s
->sections
, &s
->nb_sections
, NULL
);
10407 /* create standard sections */
10408 text_section
= new_section(s
, ".text", SHT_PROGBITS
, SHF_ALLOC
| SHF_EXECINSTR
);
10409 data_section
= new_section(s
, ".data", SHT_PROGBITS
, SHF_ALLOC
| SHF_WRITE
);
10410 bss_section
= new_section(s
, ".bss", SHT_NOBITS
, SHF_ALLOC
| SHF_WRITE
);
10412 /* symbols are always generated for linking stage */
10413 symtab_section
= new_symtab(s
, ".symtab", SHT_SYMTAB
, 0,
10415 ".hashtab", SHF_PRIVATE
);
10416 strtab_section
= symtab_section
->link
;
10418 /* private symbol table for dynamic symbols */
10419 s
->dynsymtab_section
= new_symtab(s
, ".dynsymtab", SHT_SYMTAB
, SHF_PRIVATE
,
10421 ".dynhashtab", SHF_PRIVATE
);
10422 s
->alacarte_link
= 1;
10424 #ifdef CHAR_IS_UNSIGNED
10425 s
->char_is_unsigned
= 1;
10427 #if defined(TCC_TARGET_PE) && 0
10428 /* XXX: currently the PE linker is not ready to support that */
10429 s
->leading_underscore
= 1;
10432 #ifdef TCC_TARGET_X86_64
10433 s
->jmp_table
= NULL
;
10438 void tcc_delete(TCCState
*s1
)
10444 /* free all sections */
10445 free_section(s1
->dynsymtab_section
);
10447 for(i
= 1; i
< s1
->nb_sections
; i
++)
10448 free_section(s1
->sections
[i
]);
10449 tcc_free(s1
->sections
);
10451 /* free any loaded DLLs */
10452 for ( i
= 0; i
< s1
->nb_loaded_dlls
; i
++)
10454 DLLReference
*ref
= s1
->loaded_dlls
[i
];
10456 dlclose(ref
->handle
);
10459 /* free loaded dlls array */
10460 dynarray_reset(&s1
->loaded_dlls
, &s1
->nb_loaded_dlls
);
10462 /* free library paths */
10463 dynarray_reset(&s1
->library_paths
, &s1
->nb_library_paths
);
10465 /* free include paths */
10466 dynarray_reset(&s1
->cached_includes
, &s1
->nb_cached_includes
);
10467 dynarray_reset(&s1
->include_paths
, &s1
->nb_include_paths
);
10468 dynarray_reset(&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
);
10470 #ifdef TCC_TARGET_X86_64
10471 tcc_free(s1
->jmp_table
);
10476 int tcc_add_include_path(TCCState
*s1
, const char *pathname
)
10480 pathname1
= tcc_strdup(pathname
);
10481 dynarray_add((void ***)&s1
->include_paths
, &s1
->nb_include_paths
, pathname1
);
10485 int tcc_add_sysinclude_path(TCCState
*s1
, const char *pathname
)
10489 pathname1
= tcc_strdup(pathname
);
10490 dynarray_add((void ***)&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
, pathname1
);
10494 static int tcc_add_file_internal(TCCState
*s1
, const char *filename
, int flags
)
10499 BufferedFile
*saved_file
;
10501 /* find source file type with extension */
10502 ext
= tcc_fileextension(filename
);
10506 /* open the file */
10508 file
= tcc_open(s1
, filename
);
10510 if (flags
& AFF_PRINT_ERROR
) {
10511 error_noabort("file '%s' not found", filename
);
10517 if (flags
& AFF_PREPROCESS
) {
10518 ret
= tcc_preprocess(s1
);
10519 } else if (!ext
[0] || !strcmp(ext
, "c")) {
10520 /* C file assumed */
10521 ret
= tcc_compile(s1
);
10523 #ifdef CONFIG_TCC_ASM
10524 if (!strcmp(ext
, "S")) {
10525 /* preprocessed assembler */
10526 ret
= tcc_assemble(s1
, 1);
10527 } else if (!strcmp(ext
, "s")) {
10528 /* non preprocessed assembler */
10529 ret
= tcc_assemble(s1
, 0);
10532 #ifdef TCC_TARGET_PE
10533 if (!strcmp(ext
, "def")) {
10534 ret
= pe_load_def_file(s1
, file
->fd
);
10539 /* assume executable format: auto guess file type */
10540 ret
= read(fd
, &ehdr
, sizeof(ehdr
));
10541 lseek(fd
, 0, SEEK_SET
);
10543 error_noabort("could not read header");
10545 } else if (ret
!= sizeof(ehdr
)) {
10546 goto try_load_script
;
10549 if (ehdr
.e_ident
[0] == ELFMAG0
&&
10550 ehdr
.e_ident
[1] == ELFMAG1
&&
10551 ehdr
.e_ident
[2] == ELFMAG2
&&
10552 ehdr
.e_ident
[3] == ELFMAG3
) {
10553 file
->line_num
= 0; /* do not display line number if error */
10554 if (ehdr
.e_type
== ET_REL
) {
10555 ret
= tcc_load_object_file(s1
, fd
, 0);
10556 } else if (ehdr
.e_type
== ET_DYN
) {
10557 if (s1
->output_type
== TCC_OUTPUT_MEMORY
) {
10558 #ifdef TCC_TARGET_PE
10562 h
= dlopen(filename
, RTLD_GLOBAL
| RTLD_LAZY
);
10569 ret
= tcc_load_dll(s1
, fd
, filename
,
10570 (flags
& AFF_REFERENCED_DLL
) != 0);
10573 error_noabort("unrecognized ELF file");
10576 } else if (memcmp((char *)&ehdr
, ARMAG
, 8) == 0) {
10577 file
->line_num
= 0; /* do not display line number if error */
10578 ret
= tcc_load_archive(s1
, fd
);
10580 #ifdef TCC_TARGET_COFF
10581 if (*(uint16_t *)(&ehdr
) == COFF_C67_MAGIC
) {
10582 ret
= tcc_load_coff(s1
, fd
);
10585 #ifdef TCC_TARGET_PE
10586 if (pe_test_res_file(&ehdr
, ret
)) {
10587 ret
= pe_load_res_file(s1
, fd
);
10591 /* as GNU ld, consider it is an ld script if not recognized */
10593 ret
= tcc_load_ldscript(s1
);
10595 error_noabort("unrecognized file type");
10610 int tcc_add_file(TCCState
*s
, const char *filename
)
10612 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
);
10615 int tcc_add_library_path(TCCState
*s
, const char *pathname
)
10619 pathname1
= tcc_strdup(pathname
);
10620 dynarray_add((void ***)&s
->library_paths
, &s
->nb_library_paths
, pathname1
);
10624 /* find and load a dll. Return non zero if not found */
10625 /* XXX: add '-rpath' option support ? */
10626 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
)
10631 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
10632 snprintf(buf
, sizeof(buf
), "%s/%s",
10633 s
->library_paths
[i
], filename
);
10634 if (tcc_add_file_internal(s
, buf
, flags
) == 0)
10640 /* the library name is the same as the argument of the '-l' option */
10641 int tcc_add_library(TCCState
*s
, const char *libraryname
)
10646 /* first we look for the dynamic library if not static linking */
10647 if (!s
->static_link
) {
10648 #ifdef TCC_TARGET_PE
10649 snprintf(buf
, sizeof(buf
), "%s.def", libraryname
);
10651 snprintf(buf
, sizeof(buf
), "lib%s.so", libraryname
);
10653 if (tcc_add_dll(s
, buf
, 0) == 0)
10657 /* then we look for the static library */
10658 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
10659 snprintf(buf
, sizeof(buf
), "%s/lib%s.a",
10660 s
->library_paths
[i
], libraryname
);
10661 if (tcc_add_file_internal(s
, buf
, 0) == 0)
10667 int tcc_add_symbol(TCCState
*s
, const char *name
, unsigned long val
)
10669 add_elf_sym(symtab_section
, val
, 0,
10670 ELFW(ST_INFO
)(STB_GLOBAL
, STT_NOTYPE
), 0,
10675 int tcc_set_output_type(TCCState
*s
, int output_type
)
10679 s
->output_type
= output_type
;
10681 if (!s
->nostdinc
) {
10682 /* default include paths */
10683 /* XXX: reverse order needed if -isystem support */
10684 #ifndef TCC_TARGET_PE
10685 tcc_add_sysinclude_path(s
, CONFIG_SYSROOT
"/usr/local/include");
10686 tcc_add_sysinclude_path(s
, CONFIG_SYSROOT
"/usr/include");
10688 snprintf(buf
, sizeof(buf
), "%s/include", tcc_lib_path
);
10689 tcc_add_sysinclude_path(s
, buf
);
10690 #ifdef TCC_TARGET_PE
10691 snprintf(buf
, sizeof(buf
), "%s/include/winapi", tcc_lib_path
);
10692 tcc_add_sysinclude_path(s
, buf
);
10696 /* if bound checking, then add corresponding sections */
10697 #ifdef CONFIG_TCC_BCHECK
10698 if (do_bounds_check
) {
10699 /* define symbol */
10700 tcc_define_symbol(s
, "__BOUNDS_CHECKING_ON", NULL
);
10701 /* create bounds sections */
10702 bounds_section
= new_section(s
, ".bounds",
10703 SHT_PROGBITS
, SHF_ALLOC
);
10704 lbounds_section
= new_section(s
, ".lbounds",
10705 SHT_PROGBITS
, SHF_ALLOC
);
10709 if (s
->char_is_unsigned
) {
10710 tcc_define_symbol(s
, "__CHAR_UNSIGNED__", NULL
);
10713 /* add debug sections */
10716 stab_section
= new_section(s
, ".stab", SHT_PROGBITS
, 0);
10717 stab_section
->sh_entsize
= sizeof(Stab_Sym
);
10718 stabstr_section
= new_section(s
, ".stabstr", SHT_STRTAB
, 0);
10719 put_elf_str(stabstr_section
, "");
10720 stab_section
->link
= stabstr_section
;
10721 /* put first entry */
10722 put_stabs("", 0, 0, 0, 0);
10725 /* add libc crt1/crti objects */
10726 #ifndef TCC_TARGET_PE
10727 if ((output_type
== TCC_OUTPUT_EXE
|| output_type
== TCC_OUTPUT_DLL
) &&
10729 if (output_type
!= TCC_OUTPUT_DLL
)
10730 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crt1.o");
10731 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crti.o");
10735 #ifdef TCC_TARGET_PE
10736 snprintf(buf
, sizeof(buf
), "%s/lib", tcc_lib_path
);
10737 tcc_add_library_path(s
, buf
);
10743 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
10744 #define FD_INVERT 0x0002 /* invert value before storing */
10746 typedef struct FlagDef
{
10752 static const FlagDef warning_defs
[] = {
10753 { offsetof(TCCState
, warn_unsupported
), 0, "unsupported" },
10754 { offsetof(TCCState
, warn_write_strings
), 0, "write-strings" },
10755 { offsetof(TCCState
, warn_error
), 0, "error" },
10756 { offsetof(TCCState
, warn_implicit_function_declaration
), WD_ALL
,
10757 "implicit-function-declaration" },
10760 static int set_flag(TCCState
*s
, const FlagDef
*flags
, int nb_flags
,
10761 const char *name
, int value
)
10768 if (r
[0] == 'n' && r
[1] == 'o' && r
[2] == '-') {
10772 for(i
= 0, p
= flags
; i
< nb_flags
; i
++, p
++) {
10773 if (!strcmp(r
, p
->name
))
10778 if (p
->flags
& FD_INVERT
)
10780 *(int *)((uint8_t *)s
+ p
->offset
) = value
;
10785 /* set/reset a warning */
10786 int tcc_set_warning(TCCState
*s
, const char *warning_name
, int value
)
10791 if (!strcmp(warning_name
, "all")) {
10792 for(i
= 0, p
= warning_defs
; i
< countof(warning_defs
); i
++, p
++) {
10793 if (p
->flags
& WD_ALL
)
10794 *(int *)((uint8_t *)s
+ p
->offset
) = 1;
10798 return set_flag(s
, warning_defs
, countof(warning_defs
),
10799 warning_name
, value
);
10803 static const FlagDef flag_defs
[] = {
10804 { offsetof(TCCState
, char_is_unsigned
), 0, "unsigned-char" },
10805 { offsetof(TCCState
, char_is_unsigned
), FD_INVERT
, "signed-char" },
10806 { offsetof(TCCState
, nocommon
), FD_INVERT
, "common" },
10807 { offsetof(TCCState
, leading_underscore
), 0, "leading-underscore" },
10810 /* set/reset a flag */
10811 int tcc_set_flag(TCCState
*s
, const char *flag_name
, int value
)
10813 return set_flag(s
, flag_defs
, countof(flag_defs
),
10817 #if !defined(LIBTCC)
10819 static int64_t getclock_us(void)
10824 return (tb
.time
* 1000LL + tb
.millitm
) * 1000LL;
10827 gettimeofday(&tv
, NULL
);
10828 return tv
.tv_sec
* 1000000LL + tv
.tv_usec
;
10834 printf("tcc version " TCC_VERSION
" - Tiny C Compiler - Copyright (C) 2001-2006 Fabrice Bellard\n"
10835 "usage: tcc [-v] [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"
10836 " [-Wwarn] [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-soname name]\n"
10837 " [-static] [infile1 infile2...] [-run infile args...]\n"
10839 "General options:\n"
10840 " -v display current version, increase verbosity\n"
10841 " -c compile only - generate an object file\n"
10842 " -o outfile set output filename\n"
10843 " -Bdir set tcc internal library path\n"
10844 " -bench output compilation statistics\n"
10845 " -run run compiled source\n"
10846 " -fflag set or reset (with 'no-' prefix) 'flag' (see man page)\n"
10847 " -Wwarning set or reset (with 'no-' prefix) 'warning' (see man page)\n"
10848 " -w disable all warnings\n"
10849 "Preprocessor options:\n"
10850 " -E preprocess only\n"
10851 " -Idir add include path 'dir'\n"
10852 " -Dsym[=val] define 'sym' with value 'val'\n"
10853 " -Usym undefine 'sym'\n"
10854 "Linker options:\n"
10855 " -Ldir add library path 'dir'\n"
10856 " -llib link with dynamic or static library 'lib'\n"
10857 " -shared generate a shared library\n"
10858 " -soname set name for shared library to be used at runtime\n"
10859 " -static static linking\n"
10860 " -rdynamic export all global symbols to dynamic linker\n"
10861 " -r generate (relocatable) object file\n"
10862 "Debugger options:\n"
10863 " -g generate runtime debug info\n"
10864 #ifdef CONFIG_TCC_BCHECK
10865 " -b compile with built-in memory and bounds checker (implies -g)\n"
10867 " -bt N show N callers in stack traces\n"
10871 #define TCC_OPTION_HAS_ARG 0x0001
10872 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
10874 typedef struct TCCOption
{
10903 TCC_OPTION_nostdinc
,
10904 TCC_OPTION_nostdlib
,
10905 TCC_OPTION_print_search_dirs
,
10906 TCC_OPTION_rdynamic
,
10914 static const TCCOption tcc_options
[] = {
10915 { "h", TCC_OPTION_HELP
, 0 },
10916 { "?", TCC_OPTION_HELP
, 0 },
10917 { "I", TCC_OPTION_I
, TCC_OPTION_HAS_ARG
},
10918 { "D", TCC_OPTION_D
, TCC_OPTION_HAS_ARG
},
10919 { "U", TCC_OPTION_U
, TCC_OPTION_HAS_ARG
},
10920 { "L", TCC_OPTION_L
, TCC_OPTION_HAS_ARG
},
10921 { "B", TCC_OPTION_B
, TCC_OPTION_HAS_ARG
},
10922 { "l", TCC_OPTION_l
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10923 { "bench", TCC_OPTION_bench
, 0 },
10924 { "bt", TCC_OPTION_bt
, TCC_OPTION_HAS_ARG
},
10925 #ifdef CONFIG_TCC_BCHECK
10926 { "b", TCC_OPTION_b
, 0 },
10928 { "g", TCC_OPTION_g
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10929 { "c", TCC_OPTION_c
, 0 },
10930 { "static", TCC_OPTION_static
, 0 },
10931 { "shared", TCC_OPTION_shared
, 0 },
10932 { "soname", TCC_OPTION_soname
, TCC_OPTION_HAS_ARG
},
10933 { "o", TCC_OPTION_o
, TCC_OPTION_HAS_ARG
},
10934 { "run", TCC_OPTION_run
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10935 { "rdynamic", TCC_OPTION_rdynamic
, 0 },
10936 { "r", TCC_OPTION_r
, 0 },
10937 { "Wl,", TCC_OPTION_Wl
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10938 { "W", TCC_OPTION_W
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10939 { "O", TCC_OPTION_O
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10940 { "m", TCC_OPTION_m
, TCC_OPTION_HAS_ARG
},
10941 { "f", TCC_OPTION_f
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10942 { "nostdinc", TCC_OPTION_nostdinc
, 0 },
10943 { "nostdlib", TCC_OPTION_nostdlib
, 0 },
10944 { "print-search-dirs", TCC_OPTION_print_search_dirs
, 0 },
10945 { "v", TCC_OPTION_v
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10946 { "w", TCC_OPTION_w
, 0 },
10947 { "pipe", TCC_OPTION_pipe
, 0},
10948 { "E", TCC_OPTION_E
, 0},
10952 /* convert 'str' into an array of space separated strings */
10953 static int expand_args(char ***pargv
, const char *str
)
10962 while (is_space(*str
))
10967 while (*str
!= '\0' && !is_space(*str
))
10970 arg
= tcc_malloc(len
+ 1);
10971 memcpy(arg
, s1
, len
);
10973 dynarray_add((void ***)&argv
, &argc
, arg
);
10979 static char **files
;
10980 static int nb_files
, nb_libraries
;
10981 static int multiple_files
;
10982 static int print_search_dirs
;
10983 static int output_type
;
10984 static int reloc_output
;
10985 static const char *outfile
;
10987 int parse_args(TCCState
*s
, int argc
, char **argv
)
10990 const TCCOption
*popt
;
10991 const char *optarg
, *p1
, *r1
;
10995 while (optind
< argc
) {
10997 r
= argv
[optind
++];
10998 if (r
[0] != '-' || r
[1] == '\0') {
10999 /* add a new file */
11000 dynarray_add((void ***)&files
, &nb_files
, r
);
11001 if (!multiple_files
) {
11003 /* argv[0] will be this file */
11007 /* find option in table (match only the first chars */
11008 popt
= tcc_options
;
11012 error("invalid option -- '%s'", r
);
11025 if (popt
->flags
& TCC_OPTION_HAS_ARG
) {
11026 if (*r1
!= '\0' || (popt
->flags
& TCC_OPTION_NOSEP
)) {
11029 if (optind
>= argc
)
11030 error("argument to '%s' is missing", r
);
11031 optarg
= argv
[optind
++];
11039 switch(popt
->index
) {
11040 case TCC_OPTION_HELP
:
11044 if (tcc_add_include_path(s
, optarg
) < 0)
11045 error("too many include paths");
11050 sym
= (char *)optarg
;
11051 value
= strchr(sym
, '=');
11056 tcc_define_symbol(s
, sym
, value
);
11060 tcc_undefine_symbol(s
, optarg
);
11063 tcc_add_library_path(s
, optarg
);
11066 /* set tcc utilities path (mainly for tcc development) */
11067 tcc_lib_path
= optarg
;
11070 dynarray_add((void ***)&files
, &nb_files
, r
);
11073 case TCC_OPTION_bench
:
11076 case TCC_OPTION_bt
:
11077 num_callers
= atoi(optarg
);
11079 #ifdef CONFIG_TCC_BCHECK
11081 do_bounds_check
= 1;
11089 multiple_files
= 1;
11090 output_type
= TCC_OUTPUT_OBJ
;
11092 case TCC_OPTION_static
:
11093 s
->static_link
= 1;
11095 case TCC_OPTION_shared
:
11096 output_type
= TCC_OUTPUT_DLL
;
11098 case TCC_OPTION_soname
:
11099 s
->soname
= optarg
;
11102 multiple_files
= 1;
11106 /* generate a .o merging several output files */
11108 output_type
= TCC_OUTPUT_OBJ
;
11110 case TCC_OPTION_nostdinc
:
11113 case TCC_OPTION_nostdlib
:
11116 case TCC_OPTION_print_search_dirs
:
11117 print_search_dirs
= 1;
11119 case TCC_OPTION_run
:
11123 argc1
= expand_args(&argv1
, optarg
);
11125 parse_args(s
, argc1
, argv1
);
11127 multiple_files
= 0;
11128 output_type
= TCC_OUTPUT_MEMORY
;
11133 if (0 == verbose
++)
11134 printf("tcc version %s\n", TCC_VERSION
);
11135 } while (*optarg
++ == 'v');
11138 if (tcc_set_flag(s
, optarg
, 1) < 0 && s
->warn_unsupported
)
11139 goto unsupported_option
;
11142 if (tcc_set_warning(s
, optarg
, 1) < 0 &&
11143 s
->warn_unsupported
)
11144 goto unsupported_option
;
11149 case TCC_OPTION_rdynamic
:
11152 case TCC_OPTION_Wl
:
11155 if (strstart(optarg
, "-Ttext,", &p
)) {
11156 s
->text_addr
= strtoul(p
, NULL
, 16);
11157 s
->has_text_addr
= 1;
11158 } else if (strstart(optarg
, "--oformat,", &p
)) {
11159 if (strstart(p
, "elf32-", NULL
)) {
11160 s
->output_format
= TCC_OUTPUT_FORMAT_ELF
;
11161 } else if (!strcmp(p
, "binary")) {
11162 s
->output_format
= TCC_OUTPUT_FORMAT_BINARY
;
11164 #ifdef TCC_TARGET_COFF
11165 if (!strcmp(p
, "coff")) {
11166 s
->output_format
= TCC_OUTPUT_FORMAT_COFF
;
11170 error("target %s not found", p
);
11173 error("unsupported linker option '%s'", optarg
);
11178 output_type
= TCC_OUTPUT_PREPROCESS
;
11181 if (s
->warn_unsupported
) {
11182 unsupported_option
:
11183 warning("unsupported option '%s'", r
);
11192 int main(int argc
, char **argv
)
11196 int nb_objfiles
, ret
, optind
;
11197 char objfilename
[1024];
11198 int64_t start_time
= 0;
11201 tcc_lib_path
= w32_tcc_lib_path();
11205 output_type
= TCC_OUTPUT_EXE
;
11207 multiple_files
= 1;
11212 print_search_dirs
= 0;
11215 optind
= parse_args(s
, argc
- 1, argv
+ 1);
11216 if (print_search_dirs
) {
11217 /* enough for Linux kernel */
11218 printf("install: %s/\n", tcc_lib_path
);
11221 if (optind
== 0 || nb_files
== 0) {
11222 if (optind
&& verbose
)
11228 nb_objfiles
= nb_files
- nb_libraries
;
11230 /* if outfile provided without other options, we output an
11232 if (outfile
&& output_type
== TCC_OUTPUT_MEMORY
)
11233 output_type
= TCC_OUTPUT_EXE
;
11235 /* check -c consistency : only single file handled. XXX: checks file type */
11236 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
11237 /* accepts only a single input file */
11238 if (nb_objfiles
!= 1)
11239 error("cannot specify multiple files with -c");
11240 if (nb_libraries
!= 0)
11241 error("cannot specify libraries with -c");
11245 if (output_type
== TCC_OUTPUT_PREPROCESS
) {
11247 s
->outfile
= stdout
;
11249 s
->outfile
= fopen(outfile
, "w");
11251 error("could not open '%s", outfile
);
11253 } else if (output_type
!= TCC_OUTPUT_MEMORY
) {
11255 /* compute default outfile name */
11258 strcmp(files
[0], "-") == 0 ? "a" : tcc_basename(files
[0]);
11259 pstrcpy(objfilename
, sizeof(objfilename
), name
);
11260 ext
= tcc_fileextension(objfilename
);
11261 #ifdef TCC_TARGET_PE
11262 if (output_type
== TCC_OUTPUT_DLL
)
11263 strcpy(ext
, ".dll");
11265 if (output_type
== TCC_OUTPUT_EXE
)
11266 strcpy(ext
, ".exe");
11269 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
&& *ext
)
11272 pstrcpy(objfilename
, sizeof(objfilename
), "a.out");
11273 outfile
= objfilename
;
11278 start_time
= getclock_us();
11281 tcc_set_output_type(s
, output_type
);
11283 /* compile or add each files or library */
11284 for(i
= 0; i
< nb_files
&& ret
== 0; i
++) {
11285 const char *filename
;
11287 filename
= files
[i
];
11288 if (output_type
== TCC_OUTPUT_PREPROCESS
) {
11289 if (tcc_add_file_internal(s
, filename
,
11290 AFF_PRINT_ERROR
| AFF_PREPROCESS
) < 0)
11292 } else if (filename
[0] == '-' && filename
[1]) {
11293 if (tcc_add_library(s
, filename
+ 2) < 0)
11294 error("cannot find %s", filename
);
11297 printf("-> %s\n", filename
);
11298 if (tcc_add_file(s
, filename
) < 0)
11303 /* free all files */
11311 total_time
= (double)(getclock_us() - start_time
) / 1000000.0;
11312 if (total_time
< 0.001)
11313 total_time
= 0.001;
11314 if (total_bytes
< 1)
11316 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
11317 tok_ident
- TOK_IDENT
, total_lines
, total_bytes
,
11318 total_time
, (int)(total_lines
/ total_time
),
11319 total_bytes
/ total_time
/ 1000000.0);
11322 if (s
->output_type
== TCC_OUTPUT_PREPROCESS
) {
11324 fclose(s
->outfile
);
11325 } else if (s
->output_type
== TCC_OUTPUT_MEMORY
) {
11326 ret
= tcc_run(s
, argc
- optind
, argv
+ optind
);
11328 ret
= tcc_output_file(s
, outfile
) ? 1 : 0;
11330 /* XXX: cannot do it with bound checking because of the malloc hooks */
11331 if (!do_bounds_check
)
11336 printf("memory: %d bytes, max = %d bytes\n", mem_cur_size
, mem_max_size
);