2 * TCC - Tiny C Compiler
4 * Copyright (c) 2001, 2002 Fabrice Bellard
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
36 #include <sys/timeb.h>
40 #include <sys/ucontext.h>
44 #ifndef CONFIG_TCC_STATIC
52 /* preprocessor debug */
54 /* include file debug */
62 /* target selection */
63 //#define TCC_TARGET_I386 /* i386 code generator */
65 /* default target is I386 */
66 #if !defined(TCC_TARGET_I386)
67 #define TCC_TARGET_I386
70 #if !defined(WIN32) && !defined(TCC_UCLIBC)
71 #define CONFIG_TCC_BCHECK /* enable bound checking code */
74 /* define it to include assembler support */
75 #define CONFIG_TCC_ASM
77 /* path to find crt1.o, crti.o and crtn.o. Only needed when generating
78 executables or dlls */
79 #define CONFIG_TCC_CRT_PREFIX "/usr/lib"
81 #define INCLUDE_STACK_SIZE 32
82 #define IFDEF_STACK_SIZE 64
83 #define VSTACK_SIZE 64
84 #define STRING_MAX_SIZE 1024
86 #define TOK_HASH_SIZE 2048 /* must be a power of two */
87 #define TOK_ALLOC_INCR 512 /* must be a power of two */
88 #define TOK_STR_ALLOC_INCR_BITS 6
89 #define TOK_STR_ALLOC_INCR (1 << TOK_STR_ALLOC_INCR_BITS)
90 #define TOK_MAX_SIZE 4 /* token max size in int unit when stored in string */
92 /* token symbol management */
93 typedef struct TokenSym
{
94 struct TokenSym
*hash_next
;
95 struct Sym
*sym_define
; /* direct pointer to define */
96 struct Sym
*sym_label
; /* direct pointer to label */
97 struct Sym
*sym_struct
; /* direct pointer to structure */
98 struct Sym
*sym_identifier
; /* direct pointer to identifier */
99 int tok
; /* token number */
104 typedef struct CString
{
105 int size
; /* size in bytes */
106 void *data
; /* either 'char *' or 'int *' */
108 void *data_allocated
; /* if non NULL, data has been malloced */
111 /* type definition */
112 typedef struct CType
{
118 typedef union CValue
{
124 unsigned int ul
; /* address (should be unsigned long on 64 bit cpu) */
126 unsigned long long ull
;
127 struct CString
*cstr
;
133 typedef struct SValue
{
134 CType type
; /* type */
135 unsigned short r
; /* register + flags */
136 unsigned short r2
; /* second register, used for 'long long'
137 type. If not used, set to VT_CONST */
138 CValue c
; /* constant, if VT_CONST */
139 struct Sym
*sym
; /* symbol, if (VT_SYM | VT_CONST) */
142 /* symbol management */
144 int v
; /* symbol token */
145 int r
; /* associated register */
146 int c
; /* associated number */
147 CType type
; /* associated type */
148 struct Sym
*next
; /* next related symbol */
149 struct Sym
*prev
; /* prev symbol in stack */
150 struct Sym
*prev_tok
; /* previous symbol for this token */
153 /* section definition */
154 /* XXX: use directly ELF structure for parameters ? */
155 /* special flag to indicate that the section should not be linked to
157 #define SHF_PRIVATE 0x80000000
159 typedef struct Section
{
160 unsigned long data_offset
; /* current data offset */
161 unsigned char *data
; /* section data */
162 unsigned long data_allocated
; /* used for realloc() handling */
163 int sh_name
; /* elf section name (only used during output) */
164 int sh_num
; /* elf section number */
165 int sh_type
; /* elf section type */
166 int sh_flags
; /* elf section flags */
167 int sh_info
; /* elf section info */
168 int sh_addralign
; /* elf section alignment */
169 int sh_entsize
; /* elf entry size */
170 unsigned long sh_size
; /* section size (only used during output) */
171 unsigned long sh_addr
; /* address at which the section is relocated */
172 unsigned long sh_offset
; /* address at which the section is relocated */
173 int nb_hashed_syms
; /* used to resize the hash table */
174 struct Section
*link
; /* link to another section */
175 struct Section
*reloc
; /* corresponding section for relocation, if any */
176 struct Section
*hash
; /* hash table for symbols */
177 struct Section
*next
;
178 char name
[64]; /* section name */
181 typedef struct DLLReference
{
186 /* GNUC attribute definition */
187 typedef struct AttributeDef
{
190 unsigned char func_call
; /* FUNC_CDECL or FUNC_STDCALL */
193 #define SYM_STRUCT 0x40000000 /* struct/union/enum symbol space */
194 #define SYM_FIELD 0x20000000 /* struct/union field symbol space */
195 #define SYM_FIRST_ANOM (1 << (31 - VT_STRUCT_SHIFT)) /* first anonymous sym */
197 /* stored in 'Sym.c' field */
198 #define FUNC_NEW 1 /* ansi function prototype */
199 #define FUNC_OLD 2 /* old function prototype */
200 #define FUNC_ELLIPSIS 3 /* ansi function prototype with ... */
202 /* stored in 'Sym.r' field */
203 #define FUNC_CDECL 0 /* standard c call */
204 #define FUNC_STDCALL 1 /* pascal c call */
206 /* field 'Sym.t' for macros */
207 #define MACRO_OBJ 0 /* object like macro */
208 #define MACRO_FUNC 1 /* function like macro */
210 /* field 'Sym.r' for C labels */
211 #define LABEL_DEFINED 0 /* label is defined */
212 #define LABEL_FORWARD 1 /* label is forward defined */
213 #define LABEL_DECLARED 2 /* label is declared but never used */
215 /* type_decl() types */
216 #define TYPE_ABSTRACT 1 /* type without variable */
217 #define TYPE_DIRECT 2 /* type with variable */
219 #define IO_BUF_SIZE 8192
221 typedef struct BufferedFile
{
225 int line_num
; /* current line number - here to simplify code */
226 int ifndef_macro
; /* #ifndef macro / #endif search */
227 int ifndef_macro_saved
; /* saved ifndef_macro */
228 int *ifdef_stack_ptr
; /* ifdef_stack value at the start of the file */
229 char inc_type
; /* type of include */
230 char inc_filename
[512]; /* filename specified by the user */
231 char filename
[1024]; /* current filename - here to simplify code */
232 unsigned char buffer
[IO_BUF_SIZE
+ 1]; /* extra size for CH_EOB char */
235 #define CH_EOB '\\' /* end of buffer or '\0' char in file */
236 #define CH_EOF (-1) /* end of file */
238 /* parsing state (used to save parser state to reparse part of the
239 source several times) */
240 typedef struct ParseState
{
247 /* used to record tokens */
248 typedef struct TokenString
{
255 /* include file cache, used to find files faster and also to eliminate
256 inclusion if the include file is protected by #ifndef ... #endif */
257 typedef struct CachedInclude
{
259 char type
; /* '"' or '>' to give include type */
260 char filename
[1]; /* path specified in #include */
264 static struct BufferedFile
*file
;
267 static CString tokcstr
; /* current parsed string, if any */
268 /* additional informations about token */
269 static int tok_flags
;
270 #define TOK_FLAG_BOL 0x0001 /* beginning of line before */
271 #define TOK_FLAG_BOF 0x0002 /* beginning of file before */
272 #define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */
274 static int *macro_ptr
, *macro_ptr_allocated
;
275 static int *unget_saved_macro_ptr
;
276 static int unget_saved_buffer
[TOK_MAX_SIZE
+ 1];
277 static int unget_buffer_enabled
;
278 static int parse_flags
;
279 #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
280 #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
281 #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
282 token. line feed is also
285 static Section
*text_section
, *data_section
, *bss_section
; /* predefined sections */
286 static Section
*cur_text_section
; /* current section where function code is
288 /* bound check related sections */
289 static Section
*bounds_section
; /* contains global data bound description */
290 static Section
*lbounds_section
; /* contains local data bound description */
291 /* symbol sections */
292 static Section
*symtab_section
, *strtab_section
;
295 static Section
*stab_section
, *stabstr_section
;
297 /* loc : local variable index
298 ind : output code index
300 anon_sym: anonymous symbol index
302 static int rsym
, anon_sym
, ind
, loc
;
303 /* expression generation modifiers */
304 static int const_wanted
; /* true if constant wanted */
305 static int nocode_wanted
; /* true if no code generation wanted for an expression */
306 static int global_expr
; /* true if compound literals must be allocated
307 globally (used during initializers parsing */
308 static CType func_vt
; /* current function return type (used by return
311 static int last_line_num
, last_ind
, func_ind
; /* debug last line number and pc */
312 static int tok_ident
;
313 static TokenSym
**table_ident
;
314 static TokenSym
*hash_ident
[TOK_HASH_SIZE
];
315 static char token_buf
[STRING_MAX_SIZE
+ 1];
316 static char *funcname
;
317 static Sym
*global_stack
, *local_stack
;
318 static Sym
*define_stack
;
319 static Sym
*global_label_stack
, *local_label_stack
;
321 static SValue vstack
[VSTACK_SIZE
], *vtop
;
322 /* some predefined types */
323 static CType char_pointer_type
, func_old_type
, int_type
;
324 /* true if isid(c) || isnum(c) */
325 static unsigned char isidnum_table
[256];
327 /* compile with debug symbol (and use them if error during execution) */
328 static int do_debug
= 0;
330 /* compile with built-in memory and bounds checker */
331 static int do_bounds_check
= 0;
333 /* display benchmark infos */
335 static int do_bench
= 0;
337 static int total_lines
;
338 static int total_bytes
;
340 /* use GNU C extensions */
341 static int gnu_ext
= 1;
343 /* use Tiny C extensions */
344 static int tcc_ext
= 1;
346 /* max number of callers shown if error */
347 static int num_callers
= 6;
348 static const char **rt_bound_error_msg
;
350 /* XXX: get rid of this ASAP */
351 static struct TCCState
*tcc_state
;
353 /* give the path of the tcc libraries */
354 static const char *tcc_lib_path
= CONFIG_TCC_LIBDIR
"/tcc";
359 BufferedFile
**include_stack_ptr
;
360 int *ifdef_stack_ptr
;
362 /* include file handling */
363 char **include_paths
;
364 int nb_include_paths
;
365 char **sysinclude_paths
;
366 int nb_sysinclude_paths
;
367 CachedInclude
**cached_includes
;
368 int nb_cached_includes
;
370 char **library_paths
;
371 int nb_library_paths
;
373 /* array of all loaded dlls (including those referenced by loaded
375 DLLReference
**loaded_dlls
;
380 int nb_sections
; /* number of sections, including first dummy section */
385 unsigned long *got_offsets
;
387 /* give the correspondance from symtab indexes to dynsym indexes */
388 int *symtab_to_dynsym
;
390 /* temporary dynamic symbol sections (for dll loading) */
391 Section
*dynsymtab_section
;
392 /* exported dynamic symbol section */
395 /* if true, no standard headers are added */
398 /* if true, static linking is performed */
403 void (*error_func
)(void *opaque
, const char *msg
);
404 int error_set_jmp_enabled
;
405 jmp_buf error_jmp_buf
;
408 /* tiny assembler state */
411 /* see include_stack_ptr */
412 BufferedFile
*include_stack
[INCLUDE_STACK_SIZE
];
414 /* see ifdef_stack_ptr */
415 int ifdef_stack
[IFDEF_STACK_SIZE
];
418 /* The current value can be: */
419 #define VT_VALMASK 0x00ff
420 #define VT_CONST 0x00f0 /* constant in vc
421 (must be first non register value) */
422 #define VT_LLOCAL 0x00f1 /* lvalue, offset on stack */
423 #define VT_LOCAL 0x00f2 /* offset on stack */
424 #define VT_CMP 0x00f3 /* the value is stored in processor flags (in vc) */
425 #define VT_JMP 0x00f4 /* value is the consequence of jmp true (even) */
426 #define VT_JMPI 0x00f5 /* value is the consequence of jmp false (odd) */
427 #define VT_LVAL 0x0100 /* var is an lvalue */
428 #define VT_SYM 0x0200 /* a symbol value is added */
429 #define VT_MUSTCAST 0x0400 /* value must be casted to be correct (used for
430 char/short stored in integer registers) */
431 #define VT_MUSTBOUND 0x0800 /* bound checking must be done before
432 dereferencing value */
433 #define VT_BOUNDED 0x8000 /* value is bounded. The address of the
434 bounding function call point is in vc */
435 #define VT_LVAL_BYTE 0x1000 /* lvalue is a byte */
436 #define VT_LVAL_SHORT 0x2000 /* lvalue is a short */
437 #define VT_LVAL_UNSIGNED 0x4000 /* lvalue is unsigned */
438 #define VT_LVAL_TYPE (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
441 #define VT_STRUCT_SHIFT 12 /* structure/enum name shift (20 bits left) */
443 #define VT_INT 0 /* integer type */
444 #define VT_BYTE 1 /* signed byte type */
445 #define VT_SHORT 2 /* short type */
446 #define VT_VOID 3 /* void type */
447 #define VT_PTR 4 /* pointer */
448 #define VT_ENUM 5 /* enum definition */
449 #define VT_FUNC 6 /* function type */
450 #define VT_STRUCT 7 /* struct/union definition */
451 #define VT_FLOAT 8 /* IEEE float */
452 #define VT_DOUBLE 9 /* IEEE double */
453 #define VT_LDOUBLE 10 /* IEEE long double */
454 #define VT_BOOL 11 /* ISOC99 boolean type */
455 #define VT_LLONG 12 /* 64 bit integer */
456 #define VT_LONG 13 /* long integer (NEVER USED as type, only
458 #define VT_BTYPE 0x000f /* mask for basic type */
459 #define VT_UNSIGNED 0x0010 /* unsigned type */
460 #define VT_ARRAY 0x0020 /* array type (also has VT_PTR) */
461 #define VT_BITFIELD 0x0040 /* bitfield modifier */
464 #define VT_EXTERN 0x00000080 /* extern definition */
465 #define VT_STATIC 0x00000100 /* static variable */
466 #define VT_TYPEDEF 0x00000200 /* typedef definition */
467 #define VT_INLINE 0x00000400 /* inline definition */
469 /* type mask (except storage) */
470 #define VT_STORAGE (VT_EXTERN | VT_STATIC | VT_TYPEDEF | VT_INLINE)
471 #define VT_TYPE (~(VT_STORAGE))
475 /* warning: the following compare tokens depend on i386 asm code */
487 #define TOK_LAND 0xa0
491 #define TOK_MID 0xa3 /* inc/dec, to void constant */
493 #define TOK_UDIV 0xb0 /* unsigned division */
494 #define TOK_UMOD 0xb1 /* unsigned modulo */
495 #define TOK_PDIV 0xb2 /* fast division with undefined rounding for pointers */
496 #define TOK_CINT 0xb3 /* number in tokc */
497 #define TOK_CCHAR 0xb4 /* char constant in tokc */
498 #define TOK_STR 0xb5 /* pointer to string in tokc */
499 #define TOK_TWOSHARPS 0xb6 /* ## preprocessing token */
500 #define TOK_LCHAR 0xb7
501 #define TOK_LSTR 0xb8
502 #define TOK_CFLOAT 0xb9 /* float constant */
503 #define TOK_LINENUM 0xba /* line number info */
504 #define TOK_CDOUBLE 0xc0 /* double constant */
505 #define TOK_CLDOUBLE 0xc1 /* long double constant */
506 #define TOK_UMULL 0xc2 /* unsigned 32x32 -> 64 mul */
507 #define TOK_ADDC1 0xc3 /* add with carry generation */
508 #define TOK_ADDC2 0xc4 /* add with carry use */
509 #define TOK_SUBC1 0xc5 /* add with carry generation */
510 #define TOK_SUBC2 0xc6 /* add with carry use */
511 #define TOK_CUINT 0xc8 /* unsigned int constant */
512 #define TOK_CLLONG 0xc9 /* long long constant */
513 #define TOK_CULLONG 0xca /* unsigned long long constant */
514 #define TOK_ARROW 0xcb
515 #define TOK_DOTS 0xcc /* three dots */
516 #define TOK_SHR 0xcd /* unsigned shift right */
517 #define TOK_PPNUM 0xce /* preprocessor number */
519 #define TOK_SHL 0x01 /* shift left */
520 #define TOK_SAR 0x02 /* signed shift right */
522 /* assignement operators : normal operator or 0x80 */
523 #define TOK_A_MOD 0xa5
524 #define TOK_A_AND 0xa6
525 #define TOK_A_MUL 0xaa
526 #define TOK_A_ADD 0xab
527 #define TOK_A_SUB 0xad
528 #define TOK_A_DIV 0xaf
529 #define TOK_A_XOR 0xde
530 #define TOK_A_OR 0xfc
531 #define TOK_A_SHL 0x81
532 #define TOK_A_SAR 0x82
534 /* WARNING: the content of this string encodes token numbers */
535 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";
537 #define TOK_EOF (-1) /* end of file */
538 #define TOK_LINEFEED 10 /* line feed */
540 /* all identificators and strings have token above that */
541 #define TOK_IDENT 256
543 /* only used for i386 asm opcodes definitions */
544 #define DEF_ASM(x) DEF(TOK_ASM_ ## x, #x)
547 DEF(TOK_ASM_ ## x ## b, #x "b") \
548 DEF(TOK_ASM_ ## x ## w, #x "w") \
549 DEF(TOK_ASM_ ## x ## l, #x "l") \
550 DEF(TOK_ASM_ ## x, #x)
553 DEF(TOK_ASM_ ## x ## w, #x "w") \
554 DEF(TOK_ASM_ ## x ## l, #x "l") \
555 DEF(TOK_ASM_ ## x, #x)
558 DEF(TOK_ASM_ ## f ## x ## s, "f" #x "s") \
559 DEF(TOK_ASM_ ## fi ## x ## l, "fi" #x "l") \
560 DEF(TOK_ASM_ ## f ## x ## l, "f" #x "l") \
561 DEF(TOK_ASM_ ## fi ## x ## s, "fi" #x "s")
564 DEF(TOK_ASM_ ## f ## x, "f" #x ) \
565 DEF(TOK_ASM_ ## f ## x ## p, "f" #x "p") \
568 #define DEF_ASMTEST(x) \
600 #define TOK_ASM_int TOK_INT
603 TOK_LAST
= TOK_IDENT
- 1,
604 #define DEF(id, str) id,
609 static const char tcc_keywords
[] =
610 #define DEF(id, str) str "\0"
615 #define TOK_UIDENT TOK_DEFINE
618 #define snprintf _snprintf
619 #define vsnprintf _vsnprintf
622 #if defined(WIN32) || defined(TCC_UCLIBC) || defined(__FreeBSD__)
623 /* currently incorrect */
624 long double strtold(const char *nptr
, char **endptr
)
626 return (long double)strtod(nptr
, endptr
);
628 float strtof(const char *nptr
, char **endptr
)
630 return (float)strtod(nptr
, endptr
);
633 /* XXX: need to define this to use them in non ISOC99 context */
634 extern float strtof (const char *__nptr
, char **__endptr
);
635 extern long double strtold (const char *__nptr
, char **__endptr
);
638 static char *pstrcpy(char *buf
, int buf_size
, const char *s
);
639 static char *pstrcat(char *buf
, int buf_size
, const char *s
);
641 static void next(void);
642 static void next_nomacro(void);
643 static void parse_expr_type(CType
*type
);
644 static void expr_type(CType
*type
);
645 static void unary_type(CType
*type
);
646 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
647 int case_reg
, int is_expr
);
648 static int expr_const(void);
649 static void expr_eq(void);
650 static void gexpr(void);
651 static void decl(int l
);
652 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
653 int first
, int size_only
);
654 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
655 int has_init
, int v
, int scope
);
657 void gv2(int rc1
, int rc2
);
658 void move_reg(int r
, int s
);
659 void save_regs(int n
);
660 void save_reg(int r
);
666 static void macro_subst(TokenString
*tok_str
,
667 Sym
**nested_list
, const int *macro_str
);
668 int save_reg_forced(int r
);
670 void force_charshort_cast(int t
);
671 static void gen_cast(CType
*type
);
673 static Sym
*sym_find(int v
);
674 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
);
677 static int type_size(CType
*type
, int *a
);
678 static inline CType
*pointed_type(CType
*type
);
679 static int pointed_size(CType
*type
);
680 static int lvalue_type(int t
);
681 static int is_compatible_types(CType
*type1
, CType
*type2
);
682 static int parse_btype(CType
*type
, AttributeDef
*ad
);
683 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
);
685 void error(const char *fmt
, ...);
687 void vset(CType
*type
, int r
, int v
);
688 void type_to_str(char *buf
, int buf_size
,
689 CType
*type
, const char *varstr
);
690 char *get_tok_str(int v
, CValue
*cv
);
691 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
692 unsigned long offset
, unsigned long size
);
693 static Sym
*external_global_sym(int v
, CType
*type
, int r
);
695 /* section generation */
696 static void section_realloc(Section
*sec
, unsigned long new_size
);
697 static void *section_ptr_add(Section
*sec
, unsigned long size
);
698 static void put_extern_sym(Sym
*sym
, Section
*section
,
699 unsigned long value
, unsigned long size
);
700 static void greloc(Section
*s
, Sym
*sym
, unsigned long addr
, int type
);
701 static int put_elf_str(Section
*s
, const char *sym
);
702 static int put_elf_sym(Section
*s
,
703 unsigned long value
, unsigned long size
,
704 int info
, int other
, int shndx
, const char *name
);
705 static int add_elf_sym(Section
*s
, unsigned long value
, unsigned long size
,
706 int info
, int sh_num
, const char *name
);
707 static void put_elf_reloc(Section
*symtab
, Section
*s
, unsigned long offset
,
708 int type
, int symbol
);
709 static void put_stabs(const char *str
, int type
, int other
, int desc
,
710 unsigned long value
);
711 static void put_stabs_r(const char *str
, int type
, int other
, int desc
,
712 unsigned long value
, Section
*sec
, int sym_index
);
713 static void put_stabn(int type
, int other
, int desc
, int value
);
714 static void put_stabd(int type
, int other
, int desc
);
715 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
);
717 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
718 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
719 static int tcc_add_file_internal(TCCState
*s
, const char *filename
, int flags
);
723 #ifdef CONFIG_TCC_ASM
725 typedef struct ExprValue
{
730 #define MAX_ASM_OPERANDS 30
732 typedef struct ASMOperand
{
733 int id
; /* GCC 3 optionnal identifier (0 if number only supported */
735 char asm_str
[16]; /* computed asm string for operand */
736 SValue
*vt
; /* C value of the expression */
737 int ref_index
; /* if >= 0, gives reference to a output constraint */
738 int priority
; /* priority, used to assign registers */
739 int reg
; /* if >= 0, register number used for this operand */
742 static void asm_expr(TCCState
*s1
, ExprValue
*pe
);
743 static int asm_int_expr(TCCState
*s1
);
744 static int find_constraint(ASMOperand
*operands
, int nb_operands
,
745 const char *name
, const char **pp
);
747 static int tcc_assemble(TCCState
*s1
, int do_preprocess
);
751 static void asm_instr(void);
753 /* true if float/double/long double type */
754 static inline int is_float(int t
)
758 return bt
== VT_LDOUBLE
|| bt
== VT_DOUBLE
|| bt
== VT_FLOAT
;
761 #ifdef TCC_TARGET_I386
762 #include "i386-gen.c"
765 #ifdef CONFIG_TCC_STATIC
767 #define RTLD_LAZY 0x001
768 #define RTLD_NOW 0x002
769 #define RTLD_GLOBAL 0x100
770 #define RTLD_DEFAULT NULL
772 /* dummy function for profiling */
773 void *dlopen(const char *filename
, int flag
)
778 const char *dlerror(void)
783 typedef struct TCCSyms
{
788 #define TCCSYM(a) { #a, &a, },
790 /* add the symbol you want here if no dynamic linking is done */
791 static TCCSyms tcc_syms
[] = {
799 void *dlsym(void *handle
, const char *symbol
)
803 while (p
->str
!= NULL
) {
804 if (!strcmp(p
->str
, symbol
))
813 /********************************************************/
815 /* we use our own 'finite' function to avoid potential problems with
816 non standard math libs */
817 /* XXX: endianness dependent */
818 int ieee_finite(double d
)
821 return ((unsigned)((p
[1] | 0x800fffff) + 1)) >> 31;
824 /* copy a string and truncate it. */
825 static char *pstrcpy(char *buf
, int buf_size
, const char *s
)
832 q_end
= buf
+ buf_size
- 1;
844 /* strcat and truncate. */
845 static char *pstrcat(char *buf
, int buf_size
, const char *s
)
850 pstrcpy(buf
+ len
, buf_size
- len
, s
);
854 /* memory management */
860 static inline void tcc_free(void *ptr
)
863 mem_cur_size
-= malloc_usable_size(ptr
);
868 static void *tcc_malloc(unsigned long size
)
873 error("memory full");
875 mem_cur_size
+= malloc_usable_size(ptr
);
876 if (mem_cur_size
> mem_max_size
)
877 mem_max_size
= mem_cur_size
;
882 static void *tcc_mallocz(unsigned long size
)
885 ptr
= tcc_malloc(size
);
886 memset(ptr
, 0, size
);
890 static inline void *tcc_realloc(void *ptr
, unsigned long size
)
894 mem_cur_size
-= malloc_usable_size(ptr
);
896 ptr1
= realloc(ptr
, size
);
898 /* NOTE: count not correct if alloc error, but not critical */
899 mem_cur_size
+= malloc_usable_size(ptr1
);
900 if (mem_cur_size
> mem_max_size
)
901 mem_max_size
= mem_cur_size
;
906 static char *tcc_strdup(const char *str
)
909 ptr
= tcc_malloc(strlen(str
) + 1);
914 #define free(p) use_tcc_free(p)
915 #define malloc(s) use_tcc_malloc(s)
916 #define realloc(p, s) use_tcc_realloc(p, s)
918 static void dynarray_add(void ***ptab
, int *nb_ptr
, void *data
)
925 /* every power of two we double array size */
926 if ((nb
& (nb
- 1)) == 0) {
931 pp
= tcc_realloc(pp
, nb_alloc
* sizeof(void *));
933 error("memory full");
940 Section
*new_section(TCCState
*s1
, const char *name
, int sh_type
, int sh_flags
)
944 sec
= tcc_mallocz(sizeof(Section
));
945 pstrcpy(sec
->name
, sizeof(sec
->name
), name
);
946 sec
->sh_type
= sh_type
;
947 sec
->sh_flags
= sh_flags
;
954 sec
->sh_addralign
= 4;
957 sec
->sh_addralign
= 1;
960 sec
->sh_addralign
= 32; /* default conservative alignment */
964 /* only add section if not private */
965 if (!(sh_flags
& SHF_PRIVATE
)) {
966 sec
->sh_num
= s1
->nb_sections
;
967 dynarray_add((void ***)&s1
->sections
, &s1
->nb_sections
, sec
);
972 static void free_section(Section
*s
)
978 /* realloc section and set its content to zero */
979 static void section_realloc(Section
*sec
, unsigned long new_size
)
984 size
= sec
->data_allocated
;
987 while (size
< new_size
)
989 data
= tcc_realloc(sec
->data
, size
);
991 error("memory full");
992 memset(data
+ sec
->data_allocated
, 0, size
- sec
->data_allocated
);
994 sec
->data_allocated
= size
;
997 /* reserve at least 'size' bytes in section 'sec' from
999 static void *section_ptr_add(Section
*sec
, unsigned long size
)
1001 unsigned long offset
, offset1
;
1003 offset
= sec
->data_offset
;
1004 offset1
= offset
+ size
;
1005 if (offset1
> sec
->data_allocated
)
1006 section_realloc(sec
, offset1
);
1007 sec
->data_offset
= offset1
;
1008 return sec
->data
+ offset
;
1011 /* return a reference to a section, and create it if it does not
1013 Section
*find_section(TCCState
*s1
, const char *name
)
1017 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1018 sec
= s1
->sections
[i
];
1019 if (!strcmp(name
, sec
->name
))
1022 /* sections are created as PROGBITS */
1023 return new_section(s1
, name
, SHT_PROGBITS
, SHF_ALLOC
);
1026 /* update sym->c so that it points to an external symbol in section
1027 'section' with value 'value' */
1028 static void put_extern_sym(Sym
*sym
, Section
*section
,
1029 unsigned long value
, unsigned long size
)
1031 int sym_type
, sym_bind
, sh_num
, info
;
1036 sh_num
= section
->sh_num
;
1040 if ((sym
->type
.t
& VT_BTYPE
) == VT_FUNC
)
1041 sym_type
= STT_FUNC
;
1043 sym_type
= STT_OBJECT
;
1044 if (sym
->type
.t
& VT_STATIC
)
1045 sym_bind
= STB_LOCAL
;
1047 sym_bind
= STB_GLOBAL
;
1049 name
= get_tok_str(sym
->v
, NULL
);
1050 #ifdef CONFIG_TCC_BCHECK
1051 if (do_bounds_check
) {
1054 /* XXX: avoid doing that for statics ? */
1055 /* if bound checking is activated, we change some function
1056 names by adding the "__bound" prefix */
1059 /* XXX: we rely only on malloc hooks */
1071 strcpy(buf
, "__bound_");
1078 info
= ELF32_ST_INFO(sym_bind
, sym_type
);
1079 sym
->c
= add_elf_sym(symtab_section
, value
, size
, info
, sh_num
, name
);
1081 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
1082 esym
->st_value
= value
;
1083 esym
->st_size
= size
;
1084 esym
->st_shndx
= sh_num
;
1088 /* add a new relocation entry to symbol 'sym' in section 's' */
1089 static void greloc(Section
*s
, Sym
*sym
, unsigned long offset
, int type
)
1092 put_extern_sym(sym
, NULL
, 0, 0);
1093 /* now we can add ELF relocation info */
1094 put_elf_reloc(symtab_section
, s
, offset
, type
, sym
->c
);
1097 static inline int isid(int c
)
1099 return (c
>= 'a' && c
<= 'z') ||
1100 (c
>= 'A' && c
<= 'Z') ||
1104 static inline int isnum(int c
)
1106 return c
>= '0' && c
<= '9';
1109 static inline int isoct(int c
)
1111 return c
>= '0' && c
<= '7';
1114 static inline int toup(int c
)
1116 if (c
>= 'a' && c
<= 'z')
1117 return c
- 'a' + 'A';
1122 static void strcat_vprintf(char *buf
, int buf_size
, const char *fmt
, va_list ap
)
1126 vsnprintf(buf
+ len
, buf_size
- len
, fmt
, ap
);
1129 static void strcat_printf(char *buf
, int buf_size
, const char *fmt
, ...)
1133 strcat_vprintf(buf
, buf_size
, fmt
, ap
);
1137 void error1(TCCState
*s1
, int is_warning
, const char *fmt
, va_list ap
)
1144 for(f
= s1
->include_stack
; f
< s1
->include_stack_ptr
; f
++)
1145 strcat_printf(buf
, sizeof(buf
), "In file included from %s:%d:\n",
1146 (*f
)->filename
, (*f
)->line_num
);
1147 if (file
->line_num
> 0) {
1148 strcat_printf(buf
, sizeof(buf
),
1149 "%s:%d: ", file
->filename
, file
->line_num
);
1151 strcat_printf(buf
, sizeof(buf
),
1152 "%s: ", file
->filename
);
1155 strcat_printf(buf
, sizeof(buf
),
1159 strcat_printf(buf
, sizeof(buf
), "warning: ");
1160 strcat_vprintf(buf
, sizeof(buf
), fmt
, ap
);
1162 if (!s1
->error_func
) {
1163 /* default case: stderr */
1164 fprintf(stderr
, "%s\n", buf
);
1166 s1
->error_func(s1
->error_opaque
, buf
);
1173 void tcc_set_error_func(TCCState
*s
, void *error_opaque
,
1174 void (*error_func
)(void *opaque
, const char *msg
))
1176 s
->error_opaque
= error_opaque
;
1177 s
->error_func
= error_func
;
1181 /* error without aborting current compilation */
1182 void error_noabort(const char *fmt
, ...)
1184 TCCState
*s1
= tcc_state
;
1188 error1(s1
, 0, fmt
, ap
);
1192 void error(const char *fmt
, ...)
1194 TCCState
*s1
= tcc_state
;
1198 error1(s1
, 0, fmt
, ap
);
1200 /* better than nothing: in some cases, we accept to handle errors */
1201 if (s1
->error_set_jmp_enabled
) {
1202 longjmp(s1
->error_jmp_buf
, 1);
1204 /* XXX: eliminate this someday */
1209 void expect(const char *msg
)
1211 error("%s expected", msg
);
1214 void warning(const char *fmt
, ...)
1216 TCCState
*s1
= tcc_state
;
1220 error1(s1
, 1, fmt
, ap
);
1227 error("'%c' expected", c
);
1231 static void test_lvalue(void)
1233 if (!(vtop
->r
& VT_LVAL
))
1237 /* allocate a new token */
1238 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
1240 TokenSym
*ts
, **ptable
;
1243 if (tok_ident
>= SYM_FIRST_ANOM
)
1244 error("memory full");
1246 /* expand token table if needed */
1247 i
= tok_ident
- TOK_IDENT
;
1248 if ((i
% TOK_ALLOC_INCR
) == 0) {
1249 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
1251 error("memory full");
1252 table_ident
= ptable
;
1255 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
1256 table_ident
[i
] = ts
;
1257 ts
->tok
= tok_ident
++;
1258 ts
->sym_define
= NULL
;
1259 ts
->sym_label
= NULL
;
1260 ts
->sym_struct
= NULL
;
1261 ts
->sym_identifier
= NULL
;
1263 ts
->hash_next
= NULL
;
1264 memcpy(ts
->str
, str
, len
);
1265 ts
->str
[len
] = '\0';
1270 #define TOK_HASH_INIT 1
1271 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
1273 /* find a token and add it if not found */
1274 static TokenSym
*tok_alloc(const char *str
, int len
)
1276 TokenSym
*ts
, **pts
;
1282 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
1283 h
&= (TOK_HASH_SIZE
- 1);
1285 pts
= &hash_ident
[h
];
1290 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
1292 pts
= &(ts
->hash_next
);
1294 return tok_alloc_new(pts
, str
, len
);
1297 /* CString handling */
1299 static void cstr_realloc(CString
*cstr
, int new_size
)
1304 size
= cstr
->size_allocated
;
1306 size
= 8; /* no need to allocate a too small first string */
1307 while (size
< new_size
)
1309 data
= tcc_realloc(cstr
->data_allocated
, size
);
1311 error("memory full");
1312 cstr
->data_allocated
= data
;
1313 cstr
->size_allocated
= size
;
1318 static void cstr_ccat(CString
*cstr
, int ch
)
1321 size
= cstr
->size
+ 1;
1322 if (size
> cstr
->size_allocated
)
1323 cstr_realloc(cstr
, size
);
1324 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
1328 static void cstr_cat(CString
*cstr
, const char *str
)
1340 /* add a wide char */
1341 static void cstr_wccat(CString
*cstr
, int ch
)
1344 size
= cstr
->size
+ sizeof(int);
1345 if (size
> cstr
->size_allocated
)
1346 cstr_realloc(cstr
, size
);
1347 *(int *)(((unsigned char *)cstr
->data
) + size
- sizeof(int)) = ch
;
1351 static void cstr_new(CString
*cstr
)
1353 memset(cstr
, 0, sizeof(CString
));
1356 /* free string and reset it to NULL */
1357 static void cstr_free(CString
*cstr
)
1359 tcc_free(cstr
->data_allocated
);
1363 #define cstr_reset(cstr) cstr_free(cstr)
1365 static CString
*cstr_dup(CString
*cstr1
)
1370 cstr
= tcc_malloc(sizeof(CString
));
1373 cstr
->size_allocated
= size
;
1374 cstr
->data_allocated
= tcc_malloc(size
);
1375 cstr
->data
= cstr
->data_allocated
;
1376 memcpy(cstr
->data_allocated
, cstr1
->data_allocated
, size
);
1380 /* XXX: unicode ? */
1381 static void add_char(CString
*cstr
, int c
)
1383 if (c
== '\'' || c
== '\"' || c
== '\\') {
1384 /* XXX: could be more precise if char or string */
1385 cstr_ccat(cstr
, '\\');
1387 if (c
>= 32 && c
<= 126) {
1390 cstr_ccat(cstr
, '\\');
1392 cstr_ccat(cstr
, 'n');
1394 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
1395 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
1396 cstr_ccat(cstr
, '0' + (c
& 7));
1401 /* XXX: buffer overflow */
1402 /* XXX: float tokens */
1403 char *get_tok_str(int v
, CValue
*cv
)
1405 static char buf
[STRING_MAX_SIZE
+ 1];
1406 static CString cstr_buf
;
1412 /* NOTE: to go faster, we give a fixed buffer for small strings */
1413 cstr_reset(&cstr_buf
);
1414 cstr_buf
.data
= buf
;
1415 cstr_buf
.size_allocated
= sizeof(buf
);
1421 /* XXX: not quite exact, but only useful for testing */
1422 sprintf(p
, "%u", cv
->ui
);
1426 /* XXX: not quite exact, but only useful for testing */
1427 sprintf(p
, "%Lu", cv
->ull
);
1431 cstr_ccat(&cstr_buf
, '\'');
1432 add_char(&cstr_buf
, cv
->i
);
1433 cstr_ccat(&cstr_buf
, '\'');
1434 cstr_ccat(&cstr_buf
, '\0');
1438 len
= cstr
->size
- 1;
1440 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1441 cstr_ccat(&cstr_buf
, '\0');
1446 cstr_ccat(&cstr_buf
, '\"');
1448 len
= cstr
->size
- 1;
1450 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1452 len
= (cstr
->size
/ sizeof(int)) - 1;
1454 add_char(&cstr_buf
, ((int *)cstr
->data
)[i
]);
1456 cstr_ccat(&cstr_buf
, '\"');
1457 cstr_ccat(&cstr_buf
, '\0');
1466 return strcpy(p
, "<<=");
1468 return strcpy(p
, ">>=");
1470 if (v
< TOK_IDENT
) {
1471 /* search in two bytes table */
1485 } else if (v
< tok_ident
) {
1486 return table_ident
[v
- TOK_IDENT
]->str
;
1487 } else if (v
>= SYM_FIRST_ANOM
) {
1488 /* special name for anonymous symbol */
1489 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
1491 /* should never happen */
1496 return cstr_buf
.data
;
1499 /* push, without hashing */
1500 static Sym
*sym_push2(Sym
**ps
, int v
, int t
, int c
)
1503 s
= tcc_malloc(sizeof(Sym
));
1514 /* find a symbol and return its associated structure. 's' is the top
1515 of the symbol stack */
1516 static Sym
*sym_find2(Sym
*s
, int v
)
1526 /* structure lookup */
1527 static inline Sym
*struct_find(int v
)
1530 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1532 return table_ident
[v
]->sym_struct
;
1535 /* find an identifier */
1536 static inline Sym
*sym_find(int v
)
1539 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1541 return table_ident
[v
]->sym_identifier
;
1544 /* push a given symbol on the symbol stack */
1545 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
)
1554 s
= sym_push2(ps
, v
, type
->t
, c
);
1555 s
->type
.ref
= type
->ref
;
1557 /* don't record fields or anonymous symbols */
1559 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1560 /* record symbol in token array */
1561 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1563 ps
= &ts
->sym_struct
;
1565 ps
= &ts
->sym_identifier
;
1572 /* push a global identifier */
1573 static Sym
*global_identifier_push(int v
, int t
, int c
)
1576 s
= sym_push2(&global_stack
, v
, t
, c
);
1577 /* don't record anonymous symbol */
1578 if (v
< SYM_FIRST_ANOM
) {
1579 ps
= &table_ident
[v
- TOK_IDENT
]->sym_identifier
;
1580 /* modify the top most local identifier, so that
1581 sym_identifier will point to 's' when popped */
1583 ps
= &(*ps
)->prev_tok
;
1590 /* pop symbols until top reaches 'b' */
1591 static void sym_pop(Sym
**ptop
, Sym
*b
)
1601 /* remove symbol in token array */
1603 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1604 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1606 ps
= &ts
->sym_struct
;
1608 ps
= &ts
->sym_identifier
;
1619 BufferedFile
*tcc_open(TCCState
*s1
, const char *filename
)
1624 fd
= open(filename
, O_RDONLY
);
1627 bf
= tcc_malloc(sizeof(BufferedFile
));
1633 bf
->buf_ptr
= bf
->buffer
;
1634 bf
->buf_end
= bf
->buffer
;
1635 bf
->buffer
[0] = CH_EOB
; /* put eob symbol */
1636 pstrcpy(bf
->filename
, sizeof(bf
->filename
), filename
);
1638 bf
->ifndef_macro
= 0;
1639 bf
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
1640 // printf("opening '%s'\n", filename);
1644 void tcc_close(BufferedFile
*bf
)
1646 total_lines
+= bf
->line_num
;
1651 /* fill input buffer and peek next char */
1652 static int tcc_peekc_slow(BufferedFile
*bf
)
1655 /* only tries to read if really end of buffer */
1656 if (bf
->buf_ptr
>= bf
->buf_end
) {
1658 #if defined(PARSE_DEBUG)
1663 len
= read(bf
->fd
, bf
->buffer
, len
);
1670 bf
->buf_ptr
= bf
->buffer
;
1671 bf
->buf_end
= bf
->buffer
+ len
;
1672 *bf
->buf_end
= CH_EOB
;
1674 if (bf
->buf_ptr
< bf
->buf_end
) {
1675 return bf
->buf_ptr
[0];
1677 bf
->buf_ptr
= bf
->buf_end
;
1682 /* return the current character, handling end of block if necessary
1684 static int handle_eob(void)
1686 return tcc_peekc_slow(file
);
1689 /* read next char from current input file and handle end of input buffer */
1690 static inline void inp(void)
1692 ch
= *(++(file
->buf_ptr
));
1693 /* end of buffer/file handling */
1698 /* handle '\[\r]\n' */
1699 static void handle_stray(void)
1701 while (ch
== '\\') {
1706 } else if (ch
== '\r') {
1714 error("stray '\\' in program");
1719 /* skip the stray and handle the \\n case. Output an error if
1720 incorrect char after the stray */
1721 static int handle_stray1(uint8_t *p
)
1725 if (p
>= file
->buf_end
) {
1742 /* handle just the EOB case, but not stray */
1743 #define PEEKC_EOB(c, p)\
1754 /* handle the complicated stray case */
1755 #define PEEKC(c, p)\
1760 c = handle_stray1(p);\
1765 /* input with '\[\r]\n' handling. Note that this function cannot
1766 handle other characters after '\', so you cannot call it inside
1767 strings or comments */
1768 static void minp(void)
1776 /* single line C++ comments */
1777 static uint8_t *parse_line_comment(uint8_t *p
)
1784 if (c
== '\n' || c
== CH_EOF
) {
1786 } else if (c
== '\\') {
1791 } else if (c
== '\r') {
1806 static uint8_t *parse_comment(uint8_t *p
)
1812 /* fast skip loop */
1815 if (c
== '\n' || c
== '*' || c
== '\\')
1819 if (c
== '\n' || c
== '*' || c
== '\\')
1823 /* now we can handle all the cases */
1827 } else if (c
== '*') {
1833 } else if (c
== '/') {
1834 goto end_of_comment
;
1835 } else if (c
== '\\') {
1840 /* skip '\[\r]\n', otherwise just skip the stray */
1846 } else if (c
== '\r') {
1863 /* stray, eob or eof */
1868 error("unexpected end of file in comment");
1869 } else if (c
== '\\') {
1881 /* space exlcuding newline */
1882 static inline int is_space(int ch
)
1884 return ch
== ' ' || ch
== '\t' || ch
== '\v' || ch
== '\f' || ch
== '\r';
1887 static inline void skip_spaces(void)
1889 while (is_space(ch
))
1893 /* parse a string without interpreting escapes */
1894 static uint8_t *parse_pp_string(uint8_t *p
,
1895 int sep
, CString
*str
)
1903 } else if (c
== '\\') {
1908 unterminated_string
:
1909 /* XXX: indicate line number of start of string */
1910 error("missing terminating %c character", sep
);
1911 } else if (c
== '\\') {
1912 /* escape : just skip \[\r]\n */
1917 } else if (c
== '\r') {
1920 expect("'\n' after '\r'");
1923 } else if (c
== CH_EOF
) {
1924 goto unterminated_string
;
1927 cstr_ccat(str
, '\\');
1933 } else if (c
== '\n') {
1936 } else if (c
== '\r') {
1939 cstr_ccat(str
, '\r');
1955 /* skip block of text until #else, #elif or #endif. skip also pairs of
1957 void preprocess_skip(void)
1959 int a
, start_of_line
, c
;
1986 } else if (c
== '\\') {
1987 /* XXX: incorrect: should not give an error */
1988 ch
= file
->buf_ptr
[0];
1996 p
= parse_pp_string(p
, c
, NULL
);
2005 p
= parse_comment(p
);
2006 } else if (ch
== '/') {
2007 p
= parse_line_comment(p
);
2013 if (start_of_line
) {
2018 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
2020 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
2022 else if (tok
== TOK_ENDIF
)
2036 /* ParseState handling */
2038 /* XXX: currently, no include file info is stored. Thus, we cannot display
2039 accurate messages if the function or data definition spans multiple
2042 /* save current parse state in 's' */
2043 void save_parse_state(ParseState
*s
)
2045 s
->line_num
= file
->line_num
;
2046 s
->macro_ptr
= macro_ptr
;
2051 /* restore parse state from 's' */
2052 void restore_parse_state(ParseState
*s
)
2054 file
->line_num
= s
->line_num
;
2055 macro_ptr
= s
->macro_ptr
;
2060 /* return the number of additional 'ints' necessary to store the
2062 static inline int tok_ext_size(int t
)
2081 return LDOUBLE_SIZE
/ 4;
2087 /* token string handling */
2089 static inline void tok_str_new(TokenString
*s
)
2093 s
->allocated_len
= 0;
2094 s
->last_line_num
= -1;
2097 static void tok_str_free(int *str
)
2106 /* NOTE: we test zero separately so that GCC can generate a
2107 table for the following switch */
2122 /* XXX: use a macro to be portable on 64 bit ? */
2123 cstr
= (CString
*)p
[1];
2134 p
+= 1 + (LDOUBLE_SIZE
/ 4);
2144 static int *tok_str_realloc(TokenString
*s
)
2148 len
= s
->allocated_len
+ TOK_STR_ALLOC_INCR
;
2149 str
= tcc_realloc(s
->str
, len
* sizeof(int));
2151 error("memory full");
2152 s
->allocated_len
= len
;
2157 static void tok_str_add(TokenString
*s
, int t
)
2163 if (len
>= s
->allocated_len
)
2164 str
= tok_str_realloc(s
);
2169 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
2176 /* allocate space for worst case */
2177 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
2178 str
= tok_str_realloc(s
);
2187 str
[len
++] = cv
->tab
[0];
2192 str
[len
++] = (int)cstr_dup(cv
->cstr
);
2197 str
[len
++] = cv
->tab
[0];
2198 str
[len
++] = cv
->tab
[1];
2201 #if LDOUBLE_SIZE == 12
2202 str
[len
++] = cv
->tab
[0];
2203 str
[len
++] = cv
->tab
[1];
2204 str
[len
++] = cv
->tab
[2];
2206 #error add long double size support
2215 /* add the current parse token in token string 's' */
2216 static void tok_str_add_tok(TokenString
*s
)
2220 /* save line number info */
2221 if (file
->line_num
!= s
->last_line_num
) {
2222 s
->last_line_num
= file
->line_num
;
2223 cval
.i
= s
->last_line_num
;
2224 tok_str_add2(s
, TOK_LINENUM
, &cval
);
2226 tok_str_add2(s
, tok
, &tokc
);
2229 #if LDOUBLE_SIZE == 12
2230 #define LDOUBLE_GET(p, cv) \
2235 #error add long double size support
2239 /* get a token from an integer array and increment pointer
2240 accordingly. we code it as a macro to avoid pointer aliasing. */
2241 #define TOK_GET(t, p, cv) \
2263 case TOK_CLDOUBLE: \
2264 LDOUBLE_GET(p, cv); \
2265 p += LDOUBLE_SIZE / 4; \
2272 /* defines handling */
2273 static inline void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
2277 s
= sym_push2(&define_stack
, v
, macro_type
, (int)str
);
2278 s
->next
= first_arg
;
2279 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
2282 /* undefined a define symbol. Its name is just set to zero */
2283 static void define_undef(Sym
*s
)
2287 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2288 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2292 static inline Sym
*define_find(int v
)
2295 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2297 return table_ident
[v
]->sym_define
;
2300 /* free define stack until top reaches 'b' */
2301 static void free_defines(Sym
*b
)
2309 /* do not free args or predefined defines */
2311 tok_str_free((int *)top
->c
);
2313 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2314 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2322 static Sym
*label_find(int v
)
2325 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2327 return table_ident
[v
]->sym_label
;
2330 static Sym
*label_push(Sym
**ptop
, int v
, int flags
)
2333 s
= sym_push2(ptop
, v
, 0, 0);
2335 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
2336 if (ptop
== &global_label_stack
) {
2337 /* modify the top most local identifier, so that
2338 sym_identifier will point to 's' when popped */
2340 ps
= &(*ps
)->prev_tok
;
2347 /* pop labels until element last is reached. Look if any labels are
2348 undefined. Define symbols if '&&label' was used. */
2349 static void label_pop(Sym
**ptop
, Sym
*slast
)
2352 for(s
= *ptop
; s
!= slast
; s
= s1
) {
2354 if (s
->r
== LABEL_DECLARED
) {
2355 warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
2356 } else if (s
->r
== LABEL_FORWARD
) {
2357 error("label '%s' used but not defined",
2358 get_tok_str(s
->v
, NULL
));
2361 /* define corresponding symbol. A size of
2363 put_extern_sym(s
, cur_text_section
, (long)s
->next
, 1);
2367 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
2373 /* eval an expression for #if/#elif */
2374 static int expr_preprocess(void)
2380 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2381 next(); /* do macro subst */
2382 if (tok
== TOK_DEFINED
) {
2387 c
= define_find(tok
) != 0;
2392 } else if (tok
>= TOK_IDENT
) {
2393 /* if undefined macro */
2397 tok_str_add_tok(&str
);
2399 tok_str_add(&str
, -1); /* simulate end of file */
2400 tok_str_add(&str
, 0);
2401 /* now evaluate C constant expression */
2402 macro_ptr
= str
.str
;
2406 tok_str_free(str
.str
);
2410 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
2411 static void tok_print(int *str
)
2417 TOK_GET(t
, str
, cval
);
2420 printf(" %s", get_tok_str(t
, &cval
));
2426 /* parse after #define */
2427 static void parse_define(void)
2429 Sym
*s
, *first
, **ps
;
2430 int v
, t
, varg
, is_vaargs
, c
;
2435 error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
2436 /* XXX: should check if same macro (ANSI) */
2439 /* '(' must be just after macro definition for MACRO_FUNC */
2440 c
= file
->buf_ptr
[0];
2442 c
= handle_stray1(file
->buf_ptr
);
2447 while (tok
!= ')') {
2451 if (varg
== TOK_DOTS
) {
2452 varg
= TOK___VA_ARGS__
;
2454 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
2458 if (varg
< TOK_IDENT
)
2459 error("badly punctuated parameter list");
2460 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
2471 /* EOF testing necessary for '-D' handling */
2472 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2473 tok_str_add2(&str
, tok
, &tokc
);
2476 tok_str_add(&str
, 0);
2478 printf("define %s %d: ", get_tok_str(v
, NULL
), t
);
2481 define_push(v
, t
, str
.str
, first
);
2484 /* XXX: use a token or a hash table to accelerate matching ? */
2485 static CachedInclude
*search_cached_include(TCCState
*s1
,
2486 int type
, const char *filename
)
2491 for(i
= 0;i
< s1
->nb_cached_includes
; i
++) {
2492 e
= s1
->cached_includes
[i
];
2493 if (e
->type
== type
&& !strcmp(e
->filename
, filename
))
2499 static inline void add_cached_include(TCCState
*s1
, int type
,
2500 const char *filename
, int ifndef_macro
)
2504 if (search_cached_include(s1
, type
, filename
))
2507 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
2509 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
2513 strcpy(e
->filename
, filename
);
2514 e
->ifndef_macro
= ifndef_macro
;
2515 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
2518 /* is_bof is true if first non space token at beginning of file */
2519 static void preprocess(int is_bof
)
2521 TCCState
*s1
= tcc_state
;
2522 int size
, i
, c
, n
, saved_parse_flags
;
2523 char buf
[1024], *q
, *p
;
2529 saved_parse_flags
= parse_flags
;
2530 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
|
2531 PARSE_FLAG_LINEFEED
;
2541 s
= define_find(tok
);
2542 /* undefine symbol by putting an invalid name */
2547 ch
= file
->buf_ptr
[0];
2548 /* XXX: incorrect if comments : use next_nomacro with a special mode */
2553 } else if (ch
== '\"') {
2556 /* XXX: better stray handling */
2559 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
2560 if ((q
- buf
) < sizeof(buf
) - 1)
2567 /* eat all spaces and comments after include */
2568 /* XXX: slightly incorrect */
2569 while (ch1
!= '\n' && ch1
!= CH_EOF
)
2573 /* computed #include : either we have only strings or
2574 we have anything enclosed in '<>' */
2577 if (tok
== TOK_STR
) {
2578 while (tok
!= TOK_LINEFEED
) {
2579 if (tok
!= TOK_STR
) {
2581 error("'#include' expects \"FILENAME\" or <FILENAME>");
2583 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
2589 while (tok
!= TOK_LINEFEED
) {
2590 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
2594 /* check syntax and remove '<>' */
2595 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
2596 goto include_syntax
;
2597 memmove(buf
, buf
+ 1, len
- 2);
2598 buf
[len
- 2] = '\0';
2603 e
= search_cached_include(s1
, c
, buf
);
2604 if (e
&& define_find(e
->ifndef_macro
)) {
2605 /* no need to parse the include because the 'ifndef macro'
2608 printf("%s: skipping %s\n", file
->filename
, buf
);
2612 /* first search in current dir if "header.h" */
2614 p
= strrchr(file
->filename
, '/');
2616 size
= p
+ 1 - file
->filename
;
2617 if (size
> sizeof(buf1
) - 1)
2618 size
= sizeof(buf1
) - 1;
2619 memcpy(buf1
, file
->filename
, size
);
2621 pstrcat(buf1
, sizeof(buf1
), buf
);
2622 f
= tcc_open(s1
, buf1
);
2626 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
2627 error("#include recursion too deep");
2628 /* now search in all the include paths */
2629 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
2630 for(i
= 0; i
< n
; i
++) {
2632 if (i
< s1
->nb_include_paths
)
2633 path
= s1
->include_paths
[i
];
2635 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
2636 pstrcpy(buf1
, sizeof(buf1
), path
);
2637 pstrcat(buf1
, sizeof(buf1
), "/");
2638 pstrcat(buf1
, sizeof(buf1
), buf
);
2639 f
= tcc_open(s1
, buf1
);
2643 error("include file '%s' not found", buf
);
2647 printf("%s: including %s\n", file
->filename
, buf1
);
2650 pstrcpy(f
->inc_filename
, sizeof(f
->inc_filename
), buf
);
2651 /* push current file in stack */
2652 /* XXX: fix current line init */
2653 *s1
->include_stack_ptr
++ = file
;
2655 /* add include file debug info */
2657 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
2659 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
2660 ch
= file
->buf_ptr
[0];
2668 c
= expr_preprocess();
2674 if (tok
< TOK_IDENT
)
2675 error("invalid argument for '#if%sdef'", c
? "n" : "");
2679 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
2681 file
->ifndef_macro
= tok
;
2684 c
= (define_find(tok
) != 0) ^ c
;
2686 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
2687 error("memory full");
2688 *s1
->ifdef_stack_ptr
++ = c
;
2691 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
2692 error("#else without matching #if");
2693 if (s1
->ifdef_stack_ptr
[-1] & 2)
2694 error("#else after #else");
2695 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
2698 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
2699 error("#elif without matching #if");
2700 c
= s1
->ifdef_stack_ptr
[-1];
2702 error("#elif after #else");
2703 /* last #if/#elif expression was true: we skip */
2706 c
= expr_preprocess();
2707 s1
->ifdef_stack_ptr
[-1] = c
;
2717 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
2718 error("#endif without matching #if");
2719 s1
->ifdef_stack_ptr
--;
2720 /* '#ifndef macro' was at the start of file. Now we check if
2721 an '#endif' is exactly at the end of file */
2722 if (file
->ifndef_macro
&&
2723 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
2724 file
->ifndef_macro_saved
= file
->ifndef_macro
;
2725 /* need to set to zero to avoid false matches if another
2726 #ifndef at middle of file */
2727 file
->ifndef_macro
= 0;
2728 while (tok
!= TOK_LINEFEED
)
2730 tok_flags
|= TOK_FLAG_ENDIF
;
2736 if (tok
!= TOK_CINT
)
2738 file
->line_num
= tokc
.i
- 1; /* the line number will be incremented after */
2740 if (tok
!= TOK_LINEFEED
) {
2743 pstrcpy(file
->filename
, sizeof(file
->filename
),
2744 (char *)tokc
.cstr
->data
);
2750 ch
= file
->buf_ptr
[0];
2753 while (ch
!= '\n' && ch
!= CH_EOF
) {
2754 if ((q
- buf
) < sizeof(buf
) - 1)
2760 error("#error %s", buf
);
2762 warning("#warning %s", buf
);
2768 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_CINT
) {
2769 /* '!' is ignored to allow C scripts. numbers are ignored
2770 to emulate cpp behaviour */
2772 error("invalid preprocessing directive #%s", get_tok_str(tok
, &tokc
));
2776 /* ignore other preprocess commands or #! for C scripts */
2777 while (tok
!= TOK_LINEFEED
)
2780 parse_flags
= saved_parse_flags
;
2783 /* evaluate escape codes in a string. */
2784 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
2799 case '0': case '1': case '2': case '3':
2800 case '4': case '5': case '6': case '7':
2801 /* at most three octal digits */
2806 n
= n
* 8 + c
- '0';
2810 n
= n
* 8 + c
- '0';
2815 goto add_char_nonext
;
2821 if (c
>= 'a' && c
<= 'f')
2823 else if (c
>= 'A' && c
<= 'F')
2833 goto add_char_nonext
;
2857 goto invalid_escape
;
2867 error("invalid escaped char");
2873 cstr_ccat(outstr
, c
);
2875 cstr_wccat(outstr
, c
);
2877 /* add a trailing '\0' */
2879 cstr_ccat(outstr
, '\0');
2881 cstr_wccat(outstr
, '\0');
2884 /* we use 64 bit numbers */
2887 /* bn = (bn << shift) | or_val */
2888 void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
2892 for(i
=0;i
<BN_SIZE
;i
++) {
2894 bn
[i
] = (v
<< shift
) | or_val
;
2895 or_val
= v
>> (32 - shift
);
2899 void bn_zero(unsigned int *bn
)
2902 for(i
=0;i
<BN_SIZE
;i
++) {
2907 /* parse number in null terminated string 'p' and return it in the
2909 void parse_number(const char *p
)
2911 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
2913 unsigned int bn
[BN_SIZE
];
2924 goto float_frac_parse
;
2925 } else if (t
== '0') {
2926 if (ch
== 'x' || ch
== 'X') {
2930 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
2936 /* parse all digits. cannot check octal numbers at this stage
2937 because of floating point constants */
2939 if (ch
>= 'a' && ch
<= 'f')
2941 else if (ch
>= 'A' && ch
<= 'F')
2949 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
2951 error("number too long");
2957 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
2958 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
2960 /* NOTE: strtox should support that for hexa numbers, but
2961 non ISOC99 libcs do not support it, so we prefer to do
2963 /* hexadecimal or binary floats */
2964 /* XXX: handle overflows */
2976 } else if (t
>= 'a') {
2978 } else if (t
>= 'A') {
2983 bn_lshift(bn
, shift
, t
);
2990 if (t
>= 'a' && t
<= 'f') {
2992 } else if (t
>= 'A' && t
<= 'F') {
2994 } else if (t
>= '0' && t
<= '9') {
3000 error("invalid digit");
3001 bn_lshift(bn
, shift
, t
);
3006 if (ch
!= 'p' && ch
!= 'P')
3013 } else if (ch
== '-') {
3017 if (ch
< '0' || ch
> '9')
3018 expect("exponent digits");
3019 while (ch
>= '0' && ch
<= '9') {
3020 exp_val
= exp_val
* 10 + ch
- '0';
3023 exp_val
= exp_val
* s
;
3025 /* now we can generate the number */
3026 /* XXX: should patch directly float number */
3027 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
3028 d
= ldexp(d
, exp_val
- frac_bits
);
3033 /* float : should handle overflow */
3035 } else if (t
== 'L') {
3038 /* XXX: not large enough */
3039 tokc
.ld
= (long double)d
;
3045 /* decimal floats */
3047 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3052 while (ch
>= '0' && ch
<= '9') {
3053 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3059 if (ch
== 'e' || ch
== 'E') {
3060 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3064 if (ch
== '-' || ch
== '+') {
3065 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3070 if (ch
< '0' || ch
> '9')
3071 expect("exponent digits");
3072 while (ch
>= '0' && ch
<= '9') {
3073 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3085 tokc
.f
= strtof(token_buf
, NULL
);
3086 } else if (t
== 'L') {
3089 tokc
.ld
= strtold(token_buf
, NULL
);
3092 tokc
.d
= strtod(token_buf
, NULL
);
3096 unsigned long long n
, n1
;
3099 /* integer number */
3102 if (b
== 10 && *q
== '0') {
3109 /* no need for checks except for base 10 / 8 errors */
3112 } else if (t
>= 'a') {
3114 } else if (t
>= 'A') {
3119 error("invalid digit");
3123 /* detect overflow */
3124 /* XXX: this test is not reliable */
3126 error("integer constant overflow");
3129 /* XXX: not exactly ANSI compliant */
3130 if ((n
& 0xffffffff00000000LL
) != 0) {
3135 } else if (n
> 0x7fffffff) {
3146 error("three 'l's in integer constant");
3149 if (tok
== TOK_CINT
)
3151 else if (tok
== TOK_CUINT
)
3155 } else if (t
== 'U') {
3157 error("two 'u's in integer constant");
3159 if (tok
== TOK_CINT
)
3161 else if (tok
== TOK_CLLONG
)
3168 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
3176 #define PARSE2(c1, tok1, c2, tok2) \
3187 /* return next token without macro substitution */
3188 static inline void next_nomacro1(void)
3208 /* first look if it is in fact an end of buffer */
3209 if (p
>= file
->buf_end
) {
3213 if (p
>= file
->buf_end
)
3226 TCCState
*s1
= tcc_state
;
3227 if (parse_flags
& PARSE_FLAG_LINEFEED
) {
3229 } else if (s1
->include_stack_ptr
== s1
->include_stack
||
3230 !(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3231 /* no include left : end of file. */
3234 /* pop include file */
3236 /* test if previous '#endif' was after a #ifdef at
3238 if (tok_flags
& TOK_FLAG_ENDIF
) {
3240 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
3242 add_cached_include(s1
, file
->inc_type
, file
->inc_filename
,
3243 file
->ifndef_macro_saved
);
3246 /* add end of include file debug info */
3248 put_stabd(N_EINCL
, 0, 0);
3250 /* pop include stack */
3252 s1
->include_stack_ptr
--;
3253 file
= *s1
->include_stack_ptr
;
3261 if (parse_flags
& PARSE_FLAG_LINEFEED
) {
3265 tok_flags
|= TOK_FLAG_BOL
;
3274 if ((tok_flags
& TOK_FLAG_BOL
) &&
3275 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3277 preprocess(tok_flags
& TOK_FLAG_BOF
);
3283 tok
= TOK_TWOSHARPS
;
3290 case 'a': case 'b': case 'c': case 'd':
3291 case 'e': case 'f': case 'g': case 'h':
3292 case 'i': case 'j': case 'k': case 'l':
3293 case 'm': case 'n': case 'o': case 'p':
3294 case 'q': case 'r': case 's': case 't':
3295 case 'u': case 'v': case 'w': case 'x':
3297 case 'A': case 'B': case 'C': case 'D':
3298 case 'E': case 'F': case 'G': case 'H':
3299 case 'I': case 'J': case 'K':
3300 case 'M': case 'N': case 'O': case 'P':
3301 case 'Q': case 'R': case 'S': case 'T':
3302 case 'U': case 'V': case 'W': case 'X':
3308 h
= TOK_HASH_FUNC(h
, c
);
3312 if (!isidnum_table
[c
])
3314 h
= TOK_HASH_FUNC(h
, c
);
3321 /* fast case : no stray found, so we have the full token
3322 and we have already hashed it */
3324 h
&= (TOK_HASH_SIZE
- 1);
3325 pts
= &hash_ident
[h
];
3330 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
3332 pts
= &(ts
->hash_next
);
3334 ts
= tok_alloc_new(pts
, p1
, len
);
3338 cstr_reset(&tokcstr
);
3341 cstr_ccat(&tokcstr
, *p1
);
3347 while (isidnum_table
[c
]) {
3348 cstr_ccat(&tokcstr
, c
);
3351 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
3357 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
3359 goto parse_ident_fast
;
3362 if (c
== '\'' || c
== '\"') {
3366 cstr_reset(&tokcstr
);
3367 cstr_ccat(&tokcstr
, 'L');
3368 goto parse_ident_slow
;
3372 case '0': case '1': case '2': case '3':
3373 case '4': case '5': case '6': case '7':
3376 cstr_reset(&tokcstr
);
3377 /* after the first digit, accept digits, alpha, '.' or sign if
3378 prefixed by 'eEpP' */
3382 cstr_ccat(&tokcstr
, c
);
3384 if (!(isnum(c
) || isid(c
) || c
== '.' ||
3385 ((c
== '+' || c
== '-') &&
3386 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
3389 /* We add a trailing '\0' to ease parsing */
3390 cstr_ccat(&tokcstr
, '\0');
3391 tokc
.cstr
= &tokcstr
;
3395 /* special dot handling because it can also start a number */
3398 cstr_reset(&tokcstr
);
3399 cstr_ccat(&tokcstr
, '.');
3401 } else if (c
== '.') {
3421 /* parse the string */
3423 p
= parse_pp_string(p
, sep
, &str
);
3424 cstr_ccat(&str
, '\0');
3426 /* eval the escape (should be done as TOK_PPNUM) */
3427 cstr_reset(&tokcstr
);
3428 parse_escape_string(&tokcstr
, str
.data
, is_long
);
3433 /* XXX: make it portable */
3437 char_size
= sizeof(int);
3438 if (tokcstr
.size
<= char_size
)
3439 error("empty character constant");
3440 if (tokcstr
.size
> 2 * char_size
)
3441 warning("multi-character character constant");
3443 tokc
.i
= *(int8_t *)tokcstr
.data
;
3446 tokc
.i
= *(int *)tokcstr
.data
;
3450 tokc
.cstr
= &tokcstr
;
3464 } else if (c
== '<') {
3482 } else if (c
== '>') {
3500 } else if (c
== '=') {
3513 } else if (c
== '=') {
3526 } else if (c
== '=') {
3539 } else if (c
== '=') {
3542 } else if (c
== '>') {
3550 PARSE2('!', '!', '=', TOK_NE
)
3551 PARSE2('=', '=', '=', TOK_EQ
)
3552 PARSE2('*', '*', '=', TOK_A_MUL
)
3553 PARSE2('%', '%', '=', TOK_A_MOD
)
3554 PARSE2('^', '^', '=', TOK_A_XOR
)
3556 /* comments or operator */
3560 p
= parse_comment(p
);
3562 } else if (c
== '/') {
3563 p
= parse_line_comment(p
);
3565 } else if (c
== '=') {
3585 case '$': /* only used in assembler */
3590 error("unrecognized character \\x%02x", c
);
3595 #if defined(PARSE_DEBUG)
3596 printf("token = %s\n", get_tok_str(tok
, &tokc
));
3600 /* return next token without macro substitution. Can read input from
3602 static void next_nomacro(void)
3608 TOK_GET(tok
, macro_ptr
, tokc
);
3609 if (tok
== TOK_LINENUM
) {
3610 file
->line_num
= tokc
.i
;
3619 /* substitute args in macro_str and return allocated string */
3620 static int *macro_arg_subst(Sym
**nested_list
, int *macro_str
, Sym
*args
)
3622 int *st
, last_tok
, t
, notfirst
;
3631 TOK_GET(t
, macro_str
, cval
);
3636 TOK_GET(t
, macro_str
, cval
);
3639 s
= sym_find2(args
, t
);
3646 cstr_ccat(&cstr
, ' ');
3647 TOK_GET(t
, st
, cval
);
3648 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
3651 cstr_ccat(&cstr
, '\0');
3653 printf("stringize: %s\n", (char *)cstr
.data
);
3657 tok_str_add2(&str
, TOK_STR
, &cval
);
3660 tok_str_add2(&str
, t
, &cval
);
3662 } else if (t
>= TOK_IDENT
) {
3663 s
= sym_find2(args
, t
);
3666 /* if '##' is present before or after, no arg substitution */
3667 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
3668 /* special case for var arg macros : ## eats the
3669 ',' if empty VA_ARGS variable. */
3670 /* XXX: test of the ',' is not 100%
3671 reliable. should fix it to avoid security
3673 if (gnu_ext
&& s
->type
.t
&&
3674 last_tok
== TOK_TWOSHARPS
&&
3675 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
3677 /* suppress ',' '##' */
3680 /* suppress '##' and add variable */
3688 TOK_GET(t1
, st
, cval
);
3691 tok_str_add2(&str
, t1
, &cval
);
3695 macro_subst(&str
, nested_list
, st
);
3698 tok_str_add(&str
, t
);
3701 tok_str_add2(&str
, t
, &cval
);
3705 tok_str_add(&str
, 0);
3709 static char const ab_month_name
[12][4] =
3711 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3712 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3715 /* do macro substitution of current token with macro 's' and add
3716 result to (tok_str,tok_len). 'nested_list' is the list of all
3717 macros we got inside to avoid recursing. Return non zero if no
3718 substitution needs to be done */
3719 static int macro_subst_tok(TokenString
*tok_str
,
3720 Sym
**nested_list
, Sym
*s
)
3722 Sym
*args
, *sa
, *sa1
;
3723 int mstr_allocated
, parlevel
, *mstr
, t
;
3729 /* if symbol is a macro, prepare substitution */
3731 /* special macros */
3732 if (tok
== TOK___LINE__
) {
3733 cval
.i
= file
->line_num
;
3734 tok_str_add2(tok_str
, TOK_CINT
, &cval
);
3735 } else if (tok
== TOK___FILE__
) {
3736 cstrval
= file
->filename
;
3738 tok_str_add2(tok_str
, TOK_STR
, &cval
);
3739 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
3745 tm
= localtime(&ti
);
3746 if (tok
== TOK___DATE__
) {
3747 snprintf(buf
, sizeof(buf
), "%s %2d %d",
3748 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
3750 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
3751 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
3756 cstr_cat(&cstr
, cstrval
);
3757 cstr_ccat(&cstr
, '\0');
3759 tok_str_add2(tok_str
, TOK_STR
, &cval
);
3764 if (s
->type
.t
== MACRO_FUNC
) {
3765 /* NOTE: we do not use next_nomacro to avoid eating the
3766 next token. XXX: find better solution */
3770 /* end of macro stream: we must look at the token
3771 after in the file */
3777 /* XXX: incorrect with comments */
3778 ch
= file
->buf_ptr
[0];
3779 while (is_space(ch
) || ch
== '\n')
3783 if (t
!= '(') /* no macro subst */
3786 /* argument macro */
3791 /* NOTE: empty args are allowed, except if no args */
3793 /* handle '()' case */
3794 if (!args
&& tok
== ')')
3797 error("macro '%s' used with too many args",
3798 get_tok_str(s
->v
, 0));
3801 /* NOTE: non zero sa->t indicates VA_ARGS */
3802 while ((parlevel
> 0 ||
3804 (tok
!= ',' || sa
->type
.t
))) &&
3808 else if (tok
== ')')
3810 tok_str_add2(&str
, tok
, &tokc
);
3813 tok_str_add(&str
, 0);
3814 sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, (int)str
.str
);
3817 /* special case for gcc var args: add an empty
3818 var arg argument if it is omitted */
3819 if (sa
&& sa
->type
.t
&& gnu_ext
)
3829 error("macro '%s' used with too few args",
3830 get_tok_str(s
->v
, 0));
3833 /* now subst each arg */
3834 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3839 tok_str_free((int *)sa
->c
);
3845 sym_push2(nested_list
, s
->v
, 0, 0);
3846 macro_subst(tok_str
, nested_list
, mstr
);
3847 /* pop nested defined symbol */
3849 *nested_list
= sa1
->prev
;
3857 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3858 return the resulting string (which must be freed). */
3859 static inline int *macro_twosharps(const int *macro_str
)
3862 const int *macro_ptr1
, *start_macro_ptr
, *ptr
, *saved_macro_ptr
;
3864 const char *p1
, *p2
;
3866 TokenString macro_str1
;
3869 start_macro_ptr
= macro_str
;
3870 /* we search the first '##' */
3872 macro_ptr1
= macro_str
;
3873 TOK_GET(t
, macro_str
, cval
);
3874 /* nothing more to do if end of string */
3877 if (*macro_str
== TOK_TWOSHARPS
)
3881 /* we saw '##', so we need more processing to handle it */
3883 tok_str_new(¯o_str1
);
3887 /* add all tokens seen so far */
3888 for(ptr
= start_macro_ptr
; ptr
< macro_ptr1
;) {
3889 TOK_GET(t
, ptr
, cval
);
3890 tok_str_add2(¯o_str1
, t
, &cval
);
3892 saved_macro_ptr
= macro_ptr
;
3893 /* XXX: get rid of the use of macro_ptr here */
3894 macro_ptr
= (int *)macro_str
;
3896 while (*macro_ptr
== TOK_TWOSHARPS
) {
3898 macro_ptr1
= macro_ptr
;
3901 TOK_GET(t
, macro_ptr
, cval
);
3902 /* We concatenate the two tokens if we have an
3903 identifier or a preprocessing number */
3905 p1
= get_tok_str(tok
, &tokc
);
3906 cstr_cat(&cstr
, p1
);
3907 p2
= get_tok_str(t
, &cval
);
3908 cstr_cat(&cstr
, p2
);
3909 cstr_ccat(&cstr
, '\0');
3911 if ((tok
>= TOK_IDENT
|| tok
== TOK_PPNUM
) &&
3912 (t
>= TOK_IDENT
|| t
== TOK_PPNUM
)) {
3913 if (tok
== TOK_PPNUM
) {
3914 /* if number, then create a number token */
3915 /* NOTE: no need to allocate because
3916 tok_str_add2() does it */
3919 /* if identifier, we must do a test to
3920 validate we have a correct identifier */
3921 if (t
== TOK_PPNUM
) {
3931 if (!isnum(c
) && !isid(c
))
3935 ts
= tok_alloc(cstr
.data
, strlen(cstr
.data
));
3936 tok
= ts
->tok
; /* modify current token */
3939 const char *str
= cstr
.data
;
3940 const unsigned char *q
;
3942 /* we look for a valid token */
3943 /* XXX: do more extensive checks */
3944 if (!strcmp(str
, ">>=")) {
3946 } else if (!strcmp(str
, "<<=")) {
3948 } else if (strlen(str
) == 2) {
3949 /* search in two bytes table */
3954 if (q
[0] == str
[0] && q
[1] == str
[1])
3961 /* NOTE: because get_tok_str use a static buffer,
3964 p1
= get_tok_str(tok
, &tokc
);
3965 cstr_cat(&cstr
, p1
);
3966 cstr_ccat(&cstr
, '\0');
3967 p2
= get_tok_str(t
, &cval
);
3968 warning("pasting \"%s\" and \"%s\" does not give a valid preprocessing token", cstr
.data
, p2
);
3969 /* cannot merge tokens: just add them separately */
3970 tok_str_add2(¯o_str1
, tok
, &tokc
);
3971 /* XXX: free associated memory ? */
3978 tok_str_add2(¯o_str1
, tok
, &tokc
);
3983 macro_ptr
= (int *)saved_macro_ptr
;
3985 tok_str_add(¯o_str1
, 0);
3986 return macro_str1
.str
;
3990 /* do macro substitution of macro_str and add result to
3991 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3992 inside to avoid recursing. */
3993 static void macro_subst(TokenString
*tok_str
,
3994 Sym
**nested_list
, const int *macro_str
)
3997 int *saved_macro_ptr
, *macro_str1
;
4002 /* first scan for '##' operator handling */
4004 macro_str1
= macro_twosharps(ptr
);
4008 /* NOTE: ptr == NULL can only happen if tokens are read from
4009 file stream due to a macro function call */
4012 TOK_GET(t
, ptr
, cval
);
4017 /* if nested substitution, do nothing */
4018 if (sym_find2(*nested_list
, t
))
4020 saved_macro_ptr
= macro_ptr
;
4021 macro_ptr
= (int *)ptr
;
4023 ret
= macro_subst_tok(tok_str
, nested_list
, s
);
4024 ptr
= (int *)macro_ptr
;
4025 macro_ptr
= saved_macro_ptr
;
4030 tok_str_add2(tok_str
, t
, &cval
);
4034 tok_str_free(macro_str1
);
4037 /* return next token with macro substitution */
4038 static void next(void)
4040 Sym
*nested_list
, *s
;
4046 /* if not reading from macro substituted string, then try
4047 to substitute macros */
4048 if (tok
>= TOK_IDENT
&&
4049 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
4050 s
= define_find(tok
);
4052 /* we have a macro: we try to substitute */
4055 if (macro_subst_tok(&str
, &nested_list
, s
) == 0) {
4056 /* substitution done, NOTE: maybe empty */
4057 tok_str_add(&str
, 0);
4058 macro_ptr
= str
.str
;
4059 macro_ptr_allocated
= str
.str
;
4066 /* end of macro or end of unget buffer */
4067 if (unget_buffer_enabled
) {
4068 macro_ptr
= unget_saved_macro_ptr
;
4069 unget_buffer_enabled
= 0;
4071 /* end of macro string: free it */
4072 tok_str_free(macro_ptr_allocated
);
4079 /* convert preprocessor tokens into C tokens */
4080 if (tok
== TOK_PPNUM
&&
4081 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
4082 parse_number((char *)tokc
.cstr
->data
);
4086 /* push back current token and set current token to 'last_tok'. Only
4087 identifier case handled for labels. */
4088 static inline void unget_tok(int last_tok
)
4092 unget_saved_macro_ptr
= macro_ptr
;
4093 unget_buffer_enabled
= 1;
4094 q
= unget_saved_buffer
;
4097 n
= tok_ext_size(tok
) - 1;
4100 *q
= 0; /* end of token string */
4105 void swap(int *p
, int *q
)
4113 void vsetc(CType
*type
, int r
, CValue
*vc
)
4117 if (vtop
>= vstack
+ VSTACK_SIZE
)
4118 error("memory full");
4119 /* cannot let cpu flags if other instruction are generated. Also
4120 avoid leaving VT_JMP anywhere except on the top of the stack
4121 because it would complicate the code generator. */
4122 if (vtop
>= vstack
) {
4123 v
= vtop
->r
& VT_VALMASK
;
4124 if (v
== VT_CMP
|| (v
& ~1) == VT_JMP
)
4130 vtop
->r2
= VT_CONST
;
4134 /* push integer constant */
4139 vsetc(&int_type
, VT_CONST
, &cval
);
4142 /* Return a static symbol pointing to a section */
4143 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
4144 unsigned long offset
, unsigned long size
)
4150 sym
= global_identifier_push(v
, type
->t
| VT_STATIC
, 0);
4151 sym
->type
.ref
= type
->ref
;
4152 sym
->r
= VT_CONST
| VT_SYM
;
4153 put_extern_sym(sym
, sec
, offset
, size
);
4157 /* push a reference to a section offset by adding a dummy symbol */
4158 static void vpush_ref(CType
*type
, Section
*sec
, unsigned long offset
, unsigned long size
)
4163 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4164 vtop
->sym
= get_sym_ref(type
, sec
, offset
, size
);
4167 /* define a new external reference to a symbol 'v' of type 'u' */
4168 static Sym
*external_global_sym(int v
, CType
*type
, int r
)
4174 /* push forward reference */
4175 s
= global_identifier_push(v
, type
->t
| VT_EXTERN
, 0);
4176 s
->type
.ref
= type
->ref
;
4177 s
->r
= r
| VT_CONST
| VT_SYM
;
4182 /* define a new external reference to a symbol 'v' of type 'u' */
4183 static Sym
*external_sym(int v
, CType
*type
, int r
)
4189 /* push forward reference */
4190 s
= sym_push(v
, type
, r
| VT_CONST
| VT_SYM
, 0);
4191 s
->type
.t
|= VT_EXTERN
;
4193 if (!is_compatible_types(&s
->type
, type
))
4194 error("incompatible types for redefinition of '%s'",
4195 get_tok_str(v
, NULL
));
4200 /* push a reference to global symbol v */
4201 static void vpush_global_sym(CType
*type
, int v
)
4206 sym
= external_global_sym(v
, type
, 0);
4208 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4212 void vset(CType
*type
, int r
, int v
)
4217 vsetc(type
, r
, &cval
);
4220 void vseti(int r
, int v
)
4236 void vpushv(SValue
*v
)
4238 if (vtop
>= vstack
+ VSTACK_SIZE
)
4239 error("memory full");
4249 /* save r to the memory stack, and mark it as being free */
4250 void save_reg(int r
)
4252 int l
, saved
, size
, align
;
4256 /* modify all stack values */
4259 for(p
=vstack
;p
<=vtop
;p
++) {
4260 if ((p
->r
& VT_VALMASK
) == r
||
4261 (p
->r2
& VT_VALMASK
) == r
) {
4262 /* must save value on stack if not already done */
4264 /* NOTE: must reload 'r' because r might be equal to r2 */
4265 r
= p
->r
& VT_VALMASK
;
4266 /* store register in the stack */
4268 if ((p
->r
& VT_LVAL
) ||
4269 (!is_float(type
->t
) && (type
->t
& VT_BTYPE
) != VT_LLONG
))
4271 size
= type_size(type
, &align
);
4272 loc
= (loc
- size
) & -align
;
4273 sv
.type
.t
= type
->t
;
4274 sv
.r
= VT_LOCAL
| VT_LVAL
;
4277 #ifdef TCC_TARGET_I386
4278 /* x86 specific: need to pop fp register ST0 if saved */
4279 if (r
== TREG_ST0
) {
4280 o(0xd9dd); /* fstp %st(1) */
4283 /* special long long case */
4284 if ((type
->t
& VT_BTYPE
) == VT_LLONG
) {
4291 /* mark that stack entry as being saved on the stack */
4292 if (p
->r
& VT_LVAL
) {
4293 /* also clear the bounded flag because the
4294 relocation address of the function was stored in
4296 p
->r
= (p
->r
& ~(VT_VALMASK
| VT_BOUNDED
)) | VT_LLOCAL
;
4298 p
->r
= lvalue_type(p
->type
.t
) | VT_LOCAL
;
4306 /* find a free register of class 'rc'. If none, save one register */
4312 /* find a free register */
4313 for(r
=0;r
<NB_REGS
;r
++) {
4314 if (reg_classes
[r
] & rc
) {
4315 for(p
=vstack
;p
<=vtop
;p
++) {
4316 if ((p
->r
& VT_VALMASK
) == r
||
4317 (p
->r2
& VT_VALMASK
) == r
)
4325 /* no register left : free the first one on the stack (VERY
4326 IMPORTANT to start from the bottom to ensure that we don't
4327 spill registers used in gen_opi()) */
4328 for(p
=vstack
;p
<=vtop
;p
++) {
4329 r
= p
->r
& VT_VALMASK
;
4330 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
))
4332 /* also look at second register (if long long) */
4333 r
= p
->r2
& VT_VALMASK
;
4334 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
)) {
4340 /* Should never comes here */
4344 /* save registers up to (vtop - n) stack entry */
4345 void save_regs(int n
)
4350 for(p
= vstack
;p
<= p1
; p
++) {
4351 r
= p
->r
& VT_VALMASK
;
4358 /* move register 's' to 'r', and flush previous value of r to memory
4360 void move_reg(int r
, int s
)
4373 /* get address of vtop (vtop MUST BE an lvalue) */
4376 vtop
->r
&= ~VT_LVAL
;
4377 /* tricky: if saved lvalue, then we can go back to lvalue */
4378 if ((vtop
->r
& VT_VALMASK
) == VT_LLOCAL
)
4379 vtop
->r
= (vtop
->r
& ~(VT_VALMASK
| VT_LVAL_TYPE
)) | VT_LOCAL
| VT_LVAL
;
4382 #ifdef CONFIG_TCC_BCHECK
4383 /* generate lvalue bound code */
4389 vtop
->r
&= ~VT_MUSTBOUND
;
4390 /* if lvalue, then use checking code before dereferencing */
4391 if (vtop
->r
& VT_LVAL
) {
4392 /* if not VT_BOUNDED value, then make one */
4393 if (!(vtop
->r
& VT_BOUNDED
)) {
4394 lval_type
= vtop
->r
& (VT_LVAL_TYPE
| VT_LVAL
);
4395 /* must save type because we must set it to int to get pointer */
4397 vtop
->type
.t
= VT_INT
;
4400 gen_bounded_ptr_add();
4401 vtop
->r
|= lval_type
;
4404 /* then check for dereferencing */
4405 gen_bounded_ptr_deref();
4410 /* store vtop a register belonging to class 'rc'. lvalues are
4411 converted to values. Cannot be used if cannot be converted to
4412 register value (such as structures). */
4415 int r
, r2
, rc2
, bit_pos
, bit_size
, size
, align
, i
;
4416 unsigned long long ll
;
4418 /* NOTE: get_reg can modify vstack[] */
4419 if (vtop
->type
.t
& VT_BITFIELD
) {
4420 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
4421 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
4422 /* remove bit field info to avoid loops */
4423 vtop
->type
.t
&= ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
4424 /* generate shifts */
4425 vpushi(32 - (bit_pos
+ bit_size
));
4427 vpushi(32 - bit_size
);
4428 /* NOTE: transformed to SHR if unsigned */
4432 if (is_float(vtop
->type
.t
) &&
4433 (vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4436 unsigned long offset
;
4438 /* XXX: unify with initializers handling ? */
4439 /* CPUs usually cannot use float constants, so we store them
4440 generically in data segment */
4441 size
= type_size(&vtop
->type
, &align
);
4442 offset
= (data_section
->data_offset
+ align
- 1) & -align
;
4443 data_section
->data_offset
= offset
;
4444 /* XXX: not portable yet */
4445 ptr
= section_ptr_add(data_section
, size
);
4448 ptr
[i
] = vtop
->c
.tab
[i
];
4449 sym
= get_sym_ref(&vtop
->type
, data_section
, offset
, size
<< 2);
4450 vtop
->r
|= VT_LVAL
| VT_SYM
;
4454 #ifdef CONFIG_TCC_BCHECK
4455 if (vtop
->r
& VT_MUSTBOUND
)
4459 r
= vtop
->r
& VT_VALMASK
;
4460 /* need to reload if:
4462 - lvalue (need to dereference pointer)
4463 - already a register, but not in the right class */
4464 if (r
>= VT_CONST
||
4465 (vtop
->r
& VT_LVAL
) ||
4466 !(reg_classes
[r
] & rc
) ||
4467 ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
&&
4468 !(reg_classes
[vtop
->r2
] & rc
))) {
4470 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
) {
4471 /* two register type load : expand to two words
4473 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4476 vtop
->c
.ui
= ll
; /* first word */
4478 vtop
->r
= r
; /* save register value */
4479 vpushi(ll
>> 32); /* second word */
4480 } else if (r
>= VT_CONST
||
4481 (vtop
->r
& VT_LVAL
)) {
4482 /* load from memory */
4485 vtop
[-1].r
= r
; /* save register value */
4486 /* increment pointer to get second word */
4487 vtop
->type
.t
= VT_INT
;
4493 /* move registers */
4496 vtop
[-1].r
= r
; /* save register value */
4497 vtop
->r
= vtop
[-1].r2
;
4499 /* allocate second register */
4506 /* write second register */
4508 } else if ((vtop
->r
& VT_LVAL
) && !is_float(vtop
->type
.t
)) {
4510 /* lvalue of scalar type : need to use lvalue type
4511 because of possible cast */
4514 /* compute memory access type */
4515 if (vtop
->r
& VT_LVAL_BYTE
)
4517 else if (vtop
->r
& VT_LVAL_SHORT
)
4519 if (vtop
->r
& VT_LVAL_UNSIGNED
)
4523 /* restore wanted type */
4526 /* one register type load */
4535 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
4536 void gv2(int rc1
, int rc2
)
4540 /* generate more generic register first. But VT_JMP or VT_CMP
4541 values must be generated first in all cases to avoid possible
4543 v
= vtop
[0].r
& VT_VALMASK
;
4544 if (v
!= VT_CMP
&& (v
& ~1) != VT_JMP
&& rc1
<= rc2
) {
4549 /* test if reload is needed for first register */
4550 if ((vtop
[-1].r
& VT_VALMASK
) >= VT_CONST
) {
4560 /* test if reload is needed for first register */
4561 if ((vtop
[0].r
& VT_VALMASK
) >= VT_CONST
) {
4567 /* expand long long on stack in two int registers */
4572 u
= vtop
->type
.t
& VT_UNSIGNED
;
4575 vtop
[0].r
= vtop
[-1].r2
;
4576 vtop
[0].r2
= VT_CONST
;
4577 vtop
[-1].r2
= VT_CONST
;
4578 vtop
[0].type
.t
= VT_INT
| u
;
4579 vtop
[-1].type
.t
= VT_INT
| u
;
4582 /* build a long long from two ints */
4585 gv2(RC_INT
, RC_INT
);
4586 vtop
[-1].r2
= vtop
[0].r
;
4587 vtop
[-1].type
.t
= t
;
4591 /* rotate n first stack elements to the bottom */
4598 for(i
=-n
+1;i
!=0;i
++)
4599 vtop
[i
] = vtop
[i
+1];
4603 /* pop stack value */
4607 v
= vtop
->r
& VT_VALMASK
;
4608 #ifdef TCC_TARGET_I386
4609 /* for x86, we need to pop the FP stack */
4610 if (v
== TREG_ST0
&& !nocode_wanted
) {
4611 o(0xd9dd); /* fstp %st(1) */
4614 if (v
== VT_JMP
|| v
== VT_JMPI
) {
4615 /* need to put correct jump if && or || without test */
4621 /* convert stack entry to register and duplicate its value in another
4629 if ((t
& VT_BTYPE
) == VT_LLONG
) {
4636 /* stack: H L L1 H1 */
4644 /* duplicate value */
4655 load(r1
, &sv
); /* move r to r1 */
4657 /* duplicates value */
4662 /* generate CPU independent (unsigned) long long operations */
4663 void gen_opl(int op
)
4665 int t
, a
, b
, op1
, c
, i
;
4673 func
= TOK___divdi3
;
4676 func
= TOK___udivdi3
;
4679 func
= TOK___moddi3
;
4682 func
= TOK___umoddi3
;
4684 /* call generic long long function */
4685 gfunc_start(&gf
, FUNC_CDECL
);
4688 vpush_global_sym(&func_old_type
, func
);
4692 vtop
->r2
= REG_LRET
;
4705 /* stack: L1 H1 L2 H2 */
4710 vtop
[-2] = vtop
[-3];
4713 /* stack: H1 H2 L1 L2 */
4719 /* stack: H1 H2 L1 L2 ML MH */
4722 /* stack: ML MH H1 H2 L1 L2 */
4726 /* stack: ML MH H1 L2 H2 L1 */
4731 /* stack: ML MH M1 M2 */
4734 } else if (op
== '+' || op
== '-') {
4735 /* XXX: add non carry method too (for MIPS or alpha) */
4741 /* stack: H1 H2 (L1 op L2) */
4744 gen_op(op1
+ 1); /* TOK_xxxC2 */
4747 /* stack: H1 H2 (L1 op L2) */
4750 /* stack: (L1 op L2) H1 H2 */
4752 /* stack: (L1 op L2) (H1 op H2) */
4760 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) {
4761 t
= vtop
[-1].type
.t
;
4765 /* stack: L H shift */
4767 /* constant: simpler */
4768 /* NOTE: all comments are for SHL. the other cases are
4769 done by swaping words */
4780 if (op
!= TOK_SAR
) {
4813 /* XXX: should provide a faster fallback on x86 ? */
4816 func
= TOK___sardi3
;
4819 func
= TOK___shrdi3
;
4822 func
= TOK___shldi3
;
4828 /* compare operations */
4834 /* stack: L1 H1 L2 H2 */
4836 vtop
[-1] = vtop
[-2];
4838 /* stack: L1 L2 H1 H2 */
4841 /* when values are equal, we need to compare low words. since
4842 the jump is inverted, we invert the test too. */
4845 else if (op1
== TOK_GT
)
4847 else if (op1
== TOK_ULT
)
4849 else if (op1
== TOK_UGT
)
4854 if (op1
!= TOK_NE
) {
4858 /* generate non equal test */
4859 /* XXX: NOT PORTABLE yet */
4863 #ifdef TCC_TARGET_I386
4864 b
= psym(0x850f, 0);
4866 error("not implemented");
4870 /* compare low. Always unsigned */
4874 else if (op1
== TOK_LE
)
4876 else if (op1
== TOK_GT
)
4878 else if (op1
== TOK_GE
)
4888 /* handle integer constant optimizations and various machine
4890 void gen_opic(int op
)
4897 /* currently, we cannot do computations with forward symbols */
4898 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
4899 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
4903 case '+': v1
->c
.i
+= fc
; break;
4904 case '-': v1
->c
.i
-= fc
; break;
4905 case '&': v1
->c
.i
&= fc
; break;
4906 case '^': v1
->c
.i
^= fc
; break;
4907 case '|': v1
->c
.i
|= fc
; break;
4908 case '*': v1
->c
.i
*= fc
; break;
4915 /* if division by zero, generate explicit division */
4918 error("division by zero in constant");
4922 default: v1
->c
.i
/= fc
; break;
4923 case '%': v1
->c
.i
%= fc
; break;
4924 case TOK_UDIV
: v1
->c
.i
= (unsigned)v1
->c
.i
/ fc
; break;
4925 case TOK_UMOD
: v1
->c
.i
= (unsigned)v1
->c
.i
% fc
; break;
4928 case TOK_SHL
: v1
->c
.i
<<= fc
; break;
4929 case TOK_SHR
: v1
->c
.i
= (unsigned)v1
->c
.i
>> fc
; break;
4930 case TOK_SAR
: v1
->c
.i
>>= fc
; break;
4932 case TOK_ULT
: v1
->c
.i
= (unsigned)v1
->c
.i
< (unsigned)fc
; break;
4933 case TOK_UGE
: v1
->c
.i
= (unsigned)v1
->c
.i
>= (unsigned)fc
; break;
4934 case TOK_EQ
: v1
->c
.i
= v1
->c
.i
== fc
; break;
4935 case TOK_NE
: v1
->c
.i
= v1
->c
.i
!= fc
; break;
4936 case TOK_ULE
: v1
->c
.i
= (unsigned)v1
->c
.i
<= (unsigned)fc
; break;
4937 case TOK_UGT
: v1
->c
.i
= (unsigned)v1
->c
.i
> (unsigned)fc
; break;
4938 case TOK_LT
: v1
->c
.i
= v1
->c
.i
< fc
; break;
4939 case TOK_GE
: v1
->c
.i
= v1
->c
.i
>= fc
; break;
4940 case TOK_LE
: v1
->c
.i
= v1
->c
.i
<= fc
; break;
4941 case TOK_GT
: v1
->c
.i
= v1
->c
.i
> fc
; break;
4943 case TOK_LAND
: v1
->c
.i
= v1
->c
.i
&& fc
; break;
4944 case TOK_LOR
: v1
->c
.i
= v1
->c
.i
|| fc
; break;
4950 /* if commutative ops, put c2 as constant */
4951 if (c1
&& (op
== '+' || op
== '&' || op
== '^' ||
4952 op
== '|' || op
== '*')) {
4957 if (c2
&& (((op
== '*' || op
== '/' || op
== TOK_UDIV
||
4960 ((op
== '+' || op
== '-' || op
== '|' || op
== '^' ||
4961 op
== TOK_SHL
|| op
== TOK_SHR
|| op
== TOK_SAR
) &&
4967 } else if (c2
&& (op
== '*' || op
== TOK_PDIV
|| op
== TOK_UDIV
)) {
4968 /* try to use shifts instead of muls or divs */
4969 if (fc
> 0 && (fc
& (fc
- 1)) == 0) {
4978 else if (op
== TOK_PDIV
)
4984 } else if (c2
&& (op
== '+' || op
== '-') &&
4985 (vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) ==
4986 (VT_CONST
| VT_SYM
)) {
4987 /* symbol + constant case */
4994 if (!nocode_wanted
) {
4995 /* call low level op generator */
5004 /* generate a floating point operation with constant propagation */
5005 void gen_opif(int op
)
5013 /* currently, we cannot do computations with forward symbols */
5014 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5015 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5017 if (v1
->type
.t
== VT_FLOAT
) {
5020 } else if (v1
->type
.t
== VT_DOUBLE
) {
5028 /* NOTE: we only do constant propagation if finite number (not
5029 NaN or infinity) (ANSI spec) */
5030 if (!ieee_finite(f1
) || !ieee_finite(f2
))
5034 case '+': f1
+= f2
; break;
5035 case '-': f1
-= f2
; break;
5036 case '*': f1
*= f2
; break;
5040 error("division by zero in constant");
5045 /* XXX: also handles tests ? */
5049 /* XXX: overflow test ? */
5050 if (v1
->type
.t
== VT_FLOAT
) {
5052 } else if (v1
->type
.t
== VT_DOUBLE
) {
5060 if (!nocode_wanted
) {
5068 static int pointed_size(CType
*type
)
5071 return type_size(pointed_type(type
), &align
);
5075 void check_pointer_types(SValue
*p1
, SValue
*p2
)
5077 char buf1
[256], buf2
[256];
5081 if (!is_compatible_types(t1
, t2
)) {
5082 type_to_str(buf1
, sizeof(buf1
), t1
, NULL
);
5083 type_to_str(buf2
, sizeof(buf2
), t2
, NULL
);
5084 error("incompatible pointers '%s' and '%s'", buf1
, buf2
);
5089 /* generic gen_op: handles types problems */
5092 int u
, t1
, t2
, bt1
, bt2
, t
;
5095 t1
= vtop
[-1].type
.t
;
5096 t2
= vtop
[0].type
.t
;
5097 bt1
= t1
& VT_BTYPE
;
5098 bt2
= t2
& VT_BTYPE
;
5100 if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
5101 /* at least one operand is a pointer */
5102 /* relationnal op: must be both pointers */
5103 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5104 // check_pointer_types(vtop, vtop - 1);
5105 /* pointers are handled are unsigned */
5106 t
= VT_INT
| VT_UNSIGNED
;
5109 /* if both pointers, then it must be the '-' op */
5110 if (bt1
== VT_PTR
&& bt2
== VT_PTR
) {
5112 error("cannot use pointers here");
5113 // check_pointer_types(vtop - 1, vtop);
5114 /* XXX: check that types are compatible */
5115 u
= pointed_size(&vtop
[-1].type
);
5117 /* set to integer type */
5118 vtop
->type
.t
= VT_INT
;
5122 /* exactly one pointer : must be '+' or '-'. */
5123 if (op
!= '-' && op
!= '+')
5124 error("cannot use pointers here");
5125 /* Put pointer as first operand */
5126 if (bt2
== VT_PTR
) {
5130 type1
= vtop
[-1].type
;
5131 /* XXX: cast to int ? (long long case) */
5132 vpushi(pointed_size(&vtop
[-1].type
));
5134 #ifdef CONFIG_TCC_BCHECK
5135 /* if evaluating constant expression, no code should be
5136 generated, so no bound check */
5137 if (do_bounds_check
&& !const_wanted
) {
5138 /* if bounded pointers, we generate a special code to
5145 gen_bounded_ptr_add();
5151 /* put again type if gen_opic() swaped operands */
5154 } else if (is_float(bt1
) || is_float(bt2
)) {
5155 /* compute bigger type and do implicit casts */
5156 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
5158 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
5163 /* floats can only be used for a few operations */
5164 if (op
!= '+' && op
!= '-' && op
!= '*' && op
!= '/' &&
5165 (op
< TOK_ULT
|| op
> TOK_GT
))
5166 error("invalid operands for binary operation");
5168 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
5169 /* cast to biggest op */
5171 /* convert to unsigned if it does not fit in a long long */
5172 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
5173 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
5177 /* integer operations */
5179 /* convert to unsigned if it does not fit in an integer */
5180 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
5181 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
5184 /* XXX: currently, some unsigned operations are explicit, so
5185 we modify them here */
5186 if (t
& VT_UNSIGNED
) {
5193 else if (op
== TOK_LT
)
5195 else if (op
== TOK_GT
)
5197 else if (op
== TOK_LE
)
5199 else if (op
== TOK_GE
)
5206 /* special case for shifts and long long: we keep the shift as
5208 if (op
== TOK_SHR
|| op
== TOK_SAR
|| op
== TOK_SHL
)
5213 else if ((t
& VT_BTYPE
) == VT_LLONG
)
5217 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5218 /* relationnal op: the result is an int */
5219 vtop
->type
.t
= VT_INT
;
5226 /* generic itof for unsigned long long case */
5227 void gen_cvt_itof1(int t
)
5231 if ((vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
)) ==
5232 (VT_LLONG
| VT_UNSIGNED
)) {
5234 gfunc_start(&gf
, FUNC_CDECL
);
5237 vpush_global_sym(&func_old_type
, TOK___ulltof
);
5238 else if (t
== VT_DOUBLE
)
5239 vpush_global_sym(&func_old_type
, TOK___ulltod
);
5241 vpush_global_sym(&func_old_type
, TOK___ulltold
);
5250 /* generic ftoi for unsigned long long case */
5251 void gen_cvt_ftoi1(int t
)
5256 if (t
== (VT_LLONG
| VT_UNSIGNED
)) {
5257 /* not handled natively */
5258 gfunc_start(&gf
, FUNC_CDECL
);
5259 st
= vtop
->type
.t
& VT_BTYPE
;
5262 vpush_global_sym(&func_old_type
, TOK___fixunssfdi
);
5263 else if (st
== VT_DOUBLE
)
5264 vpush_global_sym(&func_old_type
, TOK___fixunsdfdi
);
5266 vpush_global_sym(&func_old_type
, TOK___fixunsxfdi
);
5270 vtop
->r2
= REG_LRET
;
5276 /* force char or short cast */
5277 void force_charshort_cast(int t
)
5281 /* XXX: add optimization if lvalue : just change type and offset */
5286 if (t
& VT_UNSIGNED
) {
5287 vpushi((1 << bits
) - 1);
5298 /* cast 'vtop' to 'type' */
5299 static void gen_cast(CType
*type
)
5301 int sbt
, dbt
, sf
, df
, c
;
5303 /* special delayed cast for char/short */
5304 /* XXX: in some cases (multiple cascaded casts), it may still
5306 if (vtop
->r
& VT_MUSTCAST
) {
5307 vtop
->r
&= ~VT_MUSTCAST
;
5308 force_charshort_cast(vtop
->type
.t
);
5311 dbt
= type
->t
& (VT_BTYPE
| VT_UNSIGNED
);
5312 sbt
= vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
);
5314 if (sbt
!= dbt
&& !nocode_wanted
) {
5317 c
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5319 /* convert from fp to fp */
5321 /* constant case: we can do it now */
5322 /* XXX: in ISOC, cannot do it if error in convert */
5323 if (dbt
== VT_FLOAT
&& sbt
== VT_DOUBLE
)
5324 vtop
->c
.f
= (float)vtop
->c
.d
;
5325 else if (dbt
== VT_FLOAT
&& sbt
== VT_LDOUBLE
)
5326 vtop
->c
.f
= (float)vtop
->c
.ld
;
5327 else if (dbt
== VT_DOUBLE
&& sbt
== VT_FLOAT
)
5328 vtop
->c
.d
= (double)vtop
->c
.f
;
5329 else if (dbt
== VT_DOUBLE
&& sbt
== VT_LDOUBLE
)
5330 vtop
->c
.d
= (double)vtop
->c
.ld
;
5331 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_FLOAT
)
5332 vtop
->c
.ld
= (long double)vtop
->c
.f
;
5333 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_DOUBLE
)
5334 vtop
->c
.ld
= (long double)vtop
->c
.d
;
5336 /* non constant case: generate code */
5340 /* convert int to fp */
5343 case VT_LLONG
| VT_UNSIGNED
:
5345 /* XXX: add const cases for long long */
5347 case VT_INT
| VT_UNSIGNED
:
5349 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.ui
; break;
5350 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.ui
; break;
5351 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.ui
; break;
5356 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.i
; break;
5357 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.i
; break;
5358 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.i
; break;
5367 /* convert fp to int */
5368 /* we handle char/short/etc... with generic code */
5369 if (dbt
!= (VT_INT
| VT_UNSIGNED
) &&
5370 dbt
!= (VT_LLONG
| VT_UNSIGNED
) &&
5375 case VT_LLONG
| VT_UNSIGNED
:
5377 /* XXX: add const cases for long long */
5379 case VT_INT
| VT_UNSIGNED
:
5381 case VT_FLOAT
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5382 case VT_DOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5383 case VT_LDOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5389 case VT_FLOAT
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5390 case VT_DOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5391 case VT_LDOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5399 if (dbt
== VT_INT
&& (type
->t
& (VT_BTYPE
| VT_UNSIGNED
)) != dbt
) {
5400 /* additional cast for char/short/bool... */
5404 } else if ((dbt
& VT_BTYPE
) == VT_LLONG
) {
5405 if ((sbt
& VT_BTYPE
) != VT_LLONG
) {
5406 /* scalar to long long */
5408 if (sbt
== (VT_INT
| VT_UNSIGNED
))
5409 vtop
->c
.ll
= vtop
->c
.ui
;
5411 vtop
->c
.ll
= vtop
->c
.i
;
5413 /* machine independent conversion */
5415 /* generate high word */
5416 if (sbt
== (VT_INT
| VT_UNSIGNED
)) {
5424 /* patch second register */
5425 vtop
[-1].r2
= vtop
->r
;
5429 } else if (dbt
== VT_BOOL
) {
5430 /* scalar to bool */
5433 } else if ((dbt
& VT_BTYPE
) == VT_BYTE
||
5434 (dbt
& VT_BTYPE
) == VT_SHORT
) {
5435 force_charshort_cast(dbt
);
5436 } else if ((dbt
& VT_BTYPE
) == VT_INT
) {
5438 if (sbt
== VT_LLONG
) {
5439 /* from long long: just take low order word */
5443 /* if lvalue and single word type, nothing to do because
5444 the lvalue already contains the real type size (see
5445 VT_LVAL_xxx constants) */
5451 /* return type size. Put alignment at 'a' */
5452 static int type_size(CType
*type
, int *a
)
5457 bt
= type
->t
& VT_BTYPE
;
5458 if (bt
== VT_STRUCT
) {
5463 } else if (bt
== VT_PTR
) {
5464 if (type
->t
& VT_ARRAY
) {
5466 return type_size(&s
->type
, a
) * s
->c
;
5471 } else if (bt
== VT_LDOUBLE
) {
5473 return LDOUBLE_SIZE
;
5474 } else if (bt
== VT_DOUBLE
|| bt
== VT_LLONG
) {
5475 *a
= 4; /* XXX: i386 specific */
5477 } else if (bt
== VT_INT
|| bt
== VT_ENUM
|| bt
== VT_FLOAT
) {
5480 } else if (bt
== VT_SHORT
) {
5484 /* char, void, function, _Bool */
5490 /* return the pointed type of t */
5491 static inline CType
*pointed_type(CType
*type
)
5493 return &type
->ref
->type
;
5496 /* modify type so that its it is a pointer to type. */
5497 static void mk_pointer(CType
*type
)
5500 s
= sym_push(SYM_FIELD
, type
, 0, -1);
5501 type
->t
= VT_PTR
| (type
->t
& ~VT_TYPE
);
5505 static int is_compatible_types(CType
*type1
, CType
*type2
)
5508 int bt1
, bt2
, t1
, t2
;
5510 t1
= type1
->t
& VT_TYPE
;
5511 t2
= type2
->t
& VT_TYPE
;
5512 bt1
= t1
& VT_BTYPE
;
5513 bt2
= t2
& VT_BTYPE
;
5514 if (bt1
== VT_PTR
) {
5515 type1
= pointed_type(type1
);
5516 /* if function, then convert implicitely to function pointer */
5517 if (bt2
!= VT_FUNC
) {
5520 type2
= pointed_type(type2
);
5522 /* void matches everything */
5523 /* XXX: not fully compliant */
5524 if ((type1
->t
& VT_TYPE
) == VT_VOID
|| (type2
->t
& VT_TYPE
) == VT_VOID
)
5526 return is_compatible_types(type1
, type2
);
5527 } else if (bt1
== VT_STRUCT
|| bt2
== VT_STRUCT
) {
5528 return (type1
->ref
== type2
->ref
);
5529 } else if (bt1
== VT_FUNC
) {
5534 if (!is_compatible_types(&s1
->type
, &s2
->type
))
5536 /* XXX: not complete */
5537 if (s1
->c
== FUNC_OLD
|| s2
->c
== FUNC_OLD
)
5541 while (s1
!= NULL
) {
5544 if (!is_compatible_types(&s1
->type
, &s2
->type
))
5553 /* XXX: not complete */
5558 /* print a type. If 'varstr' is not NULL, then the variable is also
5559 printed in the type */
5561 /* XXX: add array and function pointers */
5562 void type_to_str(char *buf
, int buf_size
,
5563 CType
*type
, const char *varstr
)
5570 t
= type
->t
& VT_TYPE
;
5573 if (t
& VT_UNSIGNED
)
5574 pstrcat(buf
, buf_size
, "unsigned ");
5604 tstr
= "long double";
5606 pstrcat(buf
, buf_size
, tstr
);
5610 if (bt
== VT_STRUCT
)
5614 pstrcat(buf
, buf_size
, tstr
);
5615 v
= type
->ref
->v
& ~SYM_STRUCT
;
5616 if (v
>= SYM_FIRST_ANOM
)
5617 pstrcat(buf
, buf_size
, "<anonymous>");
5619 pstrcat(buf
, buf_size
, get_tok_str(v
, NULL
));
5623 type_to_str(buf
, buf_size
, &s
->type
, varstr
);
5624 pstrcat(buf
, buf_size
, "(");
5626 while (sa
!= NULL
) {
5627 type_to_str(buf1
, sizeof(buf1
), &sa
->type
, NULL
);
5628 pstrcat(buf
, buf_size
, buf1
);
5631 pstrcat(buf
, buf_size
, ", ");
5633 pstrcat(buf
, buf_size
, ")");
5637 pstrcpy(buf1
, sizeof(buf1
), "*");
5639 pstrcat(buf1
, sizeof(buf1
), varstr
);
5640 type_to_str(buf
, buf_size
, &s
->type
, buf1
);
5644 pstrcat(buf
, buf_size
, " ");
5645 pstrcat(buf
, buf_size
, varstr
);
5650 /* verify type compatibility to store vtop in 'dt' type, and generate
5652 static void gen_assign_cast(CType
*dt
)
5655 char buf1
[256], buf2
[256];
5658 st
= &vtop
->type
; /* source type */
5659 dbt
= dt
->t
& VT_BTYPE
;
5660 sbt
= st
->t
& VT_BTYPE
;
5661 if (dbt
== VT_PTR
) {
5662 /* special cases for pointers */
5663 /* a function is implicitely a function pointer */
5664 if (sbt
== VT_FUNC
) {
5665 if (!is_compatible_types(pointed_type(dt
), st
))
5670 /* '0' can also be a pointer */
5671 if (sbt
== VT_INT
&&
5672 ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) &&
5675 /* accept implicit pointer to integer cast with warning */
5676 if (sbt
== VT_BYTE
|| sbt
== VT_SHORT
||
5677 sbt
== VT_INT
|| sbt
== VT_LLONG
) {
5678 warning("assignment makes pointer from integer without a cast");
5681 } else if (dbt
== VT_BYTE
|| dbt
== VT_SHORT
||
5682 dbt
== VT_INT
|| dbt
== VT_LLONG
) {
5683 if (sbt
== VT_PTR
|| sbt
== VT_FUNC
) {
5684 warning("assignment makes integer from pointer without a cast");
5688 if (!is_compatible_types(dt
, st
)) {
5690 type_to_str(buf1
, sizeof(buf1
), st
, NULL
);
5691 type_to_str(buf2
, sizeof(buf2
), dt
, NULL
);
5692 error("cannot cast '%s' to '%s'", buf1
, buf2
);
5698 /* store vtop in lvalue pushed on stack */
5701 int sbt
, dbt
, ft
, r
, t
, size
, align
, bit_size
, bit_pos
, rc
, delayed_cast
;
5704 ft
= vtop
[-1].type
.t
;
5705 sbt
= vtop
->type
.t
& VT_BTYPE
;
5706 dbt
= ft
& VT_BTYPE
;
5707 if (((sbt
== VT_INT
|| sbt
== VT_SHORT
) && dbt
== VT_BYTE
) ||
5708 (sbt
== VT_INT
&& dbt
== VT_SHORT
)) {
5709 /* optimize char/short casts */
5710 delayed_cast
= VT_MUSTCAST
;
5711 vtop
->type
.t
= ft
& VT_TYPE
;
5714 gen_assign_cast(&vtop
[-1].type
);
5717 if (sbt
== VT_STRUCT
) {
5718 /* if structure, only generate pointer */
5719 /* structure assignment : generate memcpy */
5720 /* XXX: optimize if small size */
5721 if (!nocode_wanted
) {
5723 gfunc_start(&gf
, FUNC_CDECL
);
5725 size
= type_size(&vtop
->type
, &align
);
5729 vtop
->type
.t
= VT_INT
;
5734 vtop
->type
.t
= VT_INT
;
5739 vpush_global_sym(&func_old_type
, TOK_memcpy
);
5745 /* leave source on stack */
5746 } else if (ft
& VT_BITFIELD
) {
5747 /* bitfield store handling */
5748 bit_pos
= (ft
>> VT_STRUCT_SHIFT
) & 0x3f;
5749 bit_size
= (ft
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
5750 /* remove bit field info to avoid loops */
5751 vtop
[-1].type
.t
= ft
& ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
5753 /* duplicate destination */
5755 vtop
[-1] = vtop
[-2];
5757 /* mask and shift source */
5758 vpushi((1 << bit_size
) - 1);
5762 /* load destination, mask and or with source */
5764 vpushi(~(((1 << bit_size
) - 1) << bit_pos
));
5770 #ifdef CONFIG_TCC_BCHECK
5771 /* bound check case */
5772 if (vtop
[-1].r
& VT_MUSTBOUND
) {
5778 if (!nocode_wanted
) {
5782 r
= gv(rc
); /* generate value */
5783 /* if lvalue was saved on stack, must read it */
5784 if ((vtop
[-1].r
& VT_VALMASK
) == VT_LLOCAL
) {
5786 t
= get_reg(RC_INT
);
5788 sv
.r
= VT_LOCAL
| VT_LVAL
;
5789 sv
.c
.ul
= vtop
[-1].c
.ul
;
5791 vtop
[-1].r
= t
| VT_LVAL
;
5794 /* two word case handling : store second register at word + 4 */
5795 if ((ft
& VT_BTYPE
) == VT_LLONG
) {
5797 /* convert to int to increment easily */
5798 vtop
->type
.t
= VT_INT
;
5804 /* XXX: it works because r2 is spilled last ! */
5805 store(vtop
->r2
, vtop
- 1);
5809 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
5810 vtop
->r
|= delayed_cast
;
5814 /* post defines POST/PRE add. c is the token ++ or -- */
5815 void inc(int post
, int c
)
5818 vdup(); /* save lvalue */
5820 gv_dup(); /* duplicate value */
5825 vpushi(c
- TOK_MID
);
5827 vstore(); /* store value */
5829 vpop(); /* if post op, return saved value */
5832 /* Parse GNUC __attribute__ extension. Currently, the following
5833 extensions are recognized:
5834 - aligned(n) : set data/function alignment.
5835 - section(x) : generate data/code in this section.
5836 - unused : currently ignored, but may be used someday.
5838 static void parse_attribute(AttributeDef
*ad
)
5842 while (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
) {
5846 while (tok
!= ')') {
5847 if (tok
< TOK_IDENT
)
5848 expect("attribute name");
5856 expect("section name");
5857 ad
->section
= find_section(tcc_state
, (char *)tokc
.cstr
->data
);
5866 if (n
<= 0 || (n
& (n
- 1)) != 0)
5867 error("alignment must be a positive power of two");
5876 /* currently, no need to handle it because tcc does not
5877 track unused objects */
5881 /* currently, no need to handle it because tcc does not
5882 track unused objects */
5887 ad
->func_call
= FUNC_CDECL
;
5892 ad
->func_call
= FUNC_STDCALL
;
5895 // warning("'%s' attribute ignored", get_tok_str(t, NULL));
5896 /* skip parameters */
5897 /* XXX: skip parenthesis too */
5900 while (tok
!= ')' && tok
!= -1)
5915 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
5916 static void struct_decl(CType
*type
, int u
)
5918 int a
, v
, size
, align
, maxalign
, c
, offset
;
5919 int bit_size
, bit_pos
, bsize
, bt
, lbit_pos
;
5924 a
= tok
; /* save decl type */
5929 /* struct already defined ? return it */
5931 expect("struct/union/enum name");
5935 error("invalid type");
5942 s
= sym_push(v
| SYM_STRUCT
, &type1
, 0, 0);
5943 /* put struct/union/enum name in type */
5951 error("struct/union/enum already defined");
5952 /* cannot be empty */
5954 /* non empty enums are not allowed */
5955 if (a
== TOK_ENUM
) {
5959 expect("identifier");
5965 /* enum symbols have static storage */
5966 ss
= sym_push(v
, &int_type
, VT_CONST
, c
);
5967 ss
->type
.t
|= VT_STATIC
;
5972 /* NOTE: we accept a trailing comma */
5982 while (tok
!= '}') {
5983 parse_btype(&btype
, &ad
);
5989 type_decl(&type1
, &ad
, &v
, TYPE_DIRECT
);
5990 if ((type1
.t
& VT_BTYPE
) == VT_FUNC
||
5991 (type1
.t
& (VT_TYPEDEF
| VT_STATIC
| VT_EXTERN
| VT_INLINE
)))
5992 error("invalid type for '%s'",
5993 get_tok_str(v
, NULL
));
5997 bit_size
= expr_const();
5998 /* XXX: handle v = 0 case for messages */
6000 error("negative width in bit-field '%s'",
6001 get_tok_str(v
, NULL
));
6002 if (v
&& bit_size
== 0)
6003 error("zero width for bit-field '%s'",
6004 get_tok_str(v
, NULL
));
6006 size
= type_size(&type1
, &align
);
6008 if (bit_size
>= 0) {
6009 bt
= type1
.t
& VT_BTYPE
;
6014 error("bitfields must have scalar type");
6016 if (bit_size
> bsize
) {
6017 error("width of '%s' exceeds its type",
6018 get_tok_str(v
, NULL
));
6019 } else if (bit_size
== bsize
) {
6020 /* no need for bit fields */
6022 } else if (bit_size
== 0) {
6023 /* XXX: what to do if only padding in a
6025 /* zero size: means to pad */
6029 /* we do not have enough room ? */
6030 if ((bit_pos
+ bit_size
) > bsize
)
6033 /* XXX: handle LSB first */
6034 type1
.t
|= VT_BITFIELD
|
6035 (bit_pos
<< VT_STRUCT_SHIFT
) |
6036 (bit_size
<< (VT_STRUCT_SHIFT
+ 6));
6037 bit_pos
+= bit_size
;
6043 /* add new memory data only if starting
6045 if (lbit_pos
== 0) {
6046 if (a
== TOK_STRUCT
) {
6047 c
= (c
+ align
- 1) & -align
;
6055 if (align
> maxalign
)
6059 printf("add field %s offset=%d",
6060 get_tok_str(v
, NULL
), offset
);
6061 if (type1
.t
& VT_BITFIELD
) {
6062 printf(" pos=%d size=%d",
6063 (type1
.t
>> VT_STRUCT_SHIFT
) & 0x3f,
6064 (type1
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f);
6068 ss
= sym_push(v
| SYM_FIELD
, &type1
, 0, offset
);
6072 if (tok
== ';' || tok
== TOK_EOF
)
6079 /* store size and alignment */
6080 s
->c
= (c
+ maxalign
- 1) & -maxalign
;
6086 /* return 0 if no type declaration. otherwise, return the basic type
6089 static int parse_btype(CType
*type
, AttributeDef
*ad
)
6091 int t
, u
, type_found
;
6095 memset(ad
, 0, sizeof(AttributeDef
));
6101 /* currently, we really ignore extension */
6111 if ((t
& VT_BTYPE
) != 0)
6112 error("too many basic types");
6126 if ((t
& VT_BTYPE
) == VT_DOUBLE
) {
6127 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6128 } else if ((t
& VT_BTYPE
) == VT_LONG
) {
6129 t
= (t
& ~VT_BTYPE
) | VT_LLONG
;
6143 if ((t
& VT_BTYPE
) == VT_LONG
) {
6144 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6151 struct_decl(&type1
, VT_ENUM
);
6154 type
->ref
= type1
.ref
;
6158 struct_decl(&type1
, VT_STRUCT
);
6161 /* type modifiers */
6203 /* GNUC attribute */
6204 case TOK_ATTRIBUTE1
:
6205 case TOK_ATTRIBUTE2
:
6206 parse_attribute(ad
);
6213 parse_expr_type(&type1
);
6217 if (!s
|| !(s
->type
.t
& VT_TYPEDEF
))
6219 t
|= (s
->type
.t
& ~VT_TYPEDEF
);
6220 type
->ref
= s
->type
.ref
;
6227 /* long is never used as type */
6228 if ((t
& VT_BTYPE
) == VT_LONG
)
6229 t
= (t
& ~VT_BTYPE
) | VT_INT
;
6234 /* convert a function parameter type (array to pointer and function to
6235 function pointer) */
6236 static inline void convert_parameter_type(CType
*pt
)
6238 /* array must be transformed to pointer according to ANSI C */
6240 if ((pt
->t
& VT_BTYPE
) == VT_FUNC
) {
6245 static void post_type(CType
*type
, AttributeDef
*ad
)
6248 Sym
**plast
, *s
, *first
;
6253 /* function declaration */
6258 while (tok
!= ')') {
6259 /* read param name and compute offset */
6260 if (l
!= FUNC_OLD
) {
6261 if (!parse_btype(&pt
, &ad1
)) {
6263 error("invalid type");
6270 if ((pt
.t
& VT_BTYPE
) == VT_VOID
&& tok
== ')')
6272 type_decl(&pt
, &ad1
, &n
, TYPE_DIRECT
| TYPE_ABSTRACT
);
6273 if ((pt
.t
& VT_BTYPE
) == VT_VOID
)
6274 error("parameter declared as void");
6281 convert_parameter_type(&pt
);
6282 s
= sym_push(n
| SYM_FIELD
, &pt
, 0, 0);
6287 if (l
== FUNC_NEW
&& tok
== TOK_DOTS
) {
6294 /* if no parameters, then old type prototype */
6298 t1
= type
->t
& VT_STORAGE
;
6299 type
->t
&= ~VT_STORAGE
;
6300 post_type(type
, ad
);
6301 /* we push a anonymous symbol which will contain the function prototype */
6302 s
= sym_push(SYM_FIELD
, type
, ad
->func_call
, l
);
6304 type
->t
= t1
| VT_FUNC
;
6306 } else if (tok
== '[') {
6307 /* array definition */
6313 error("invalid array size");
6316 /* parse next post type */
6317 t1
= type
->t
& VT_STORAGE
;
6318 type
->t
&= ~VT_STORAGE
;
6319 post_type(type
, ad
);
6321 /* we push a anonymous symbol which will contain the array
6323 s
= sym_push(SYM_FIELD
, type
, 0, n
);
6324 type
->t
= t1
| VT_ARRAY
| VT_PTR
;
6329 /* Parse a type declaration (except basic type), and return the type
6330 in 'type'. 'td' is a bitmask indicating which kind of type decl is
6331 expected. 'type' should contain the basic type. 'ad' is the
6332 attribute definition of the basic type. It can be modified by
6335 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
)
6338 CType type1
, *type2
;
6340 while (tok
== '*') {
6359 /* XXX: clarify attribute handling */
6360 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6361 parse_attribute(ad
);
6363 /* recursive type */
6364 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
6365 type1
.t
= 0; /* XXX: same as int */
6368 /* XXX: this is not correct to modify 'ad' at this point, but
6369 the syntax is not clear */
6370 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6371 parse_attribute(ad
);
6372 type_decl(&type1
, ad
, v
, td
);
6375 /* type identifier */
6376 if (tok
>= TOK_IDENT
&& (td
& TYPE_DIRECT
)) {
6380 if (!(td
& TYPE_ABSTRACT
))
6381 expect("identifier");
6385 post_type(type
, ad
);
6386 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6387 parse_attribute(ad
);
6390 /* append type at the end of type1 */
6403 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
6404 static int lvalue_type(int t
)
6409 if (bt
== VT_BYTE
|| bt
== VT_BOOL
)
6411 else if (bt
== VT_SHORT
)
6415 if (t
& VT_UNSIGNED
)
6416 r
|= VT_LVAL_UNSIGNED
;
6420 /* indirection with full error checking and bound check */
6421 static void indir(void)
6423 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
6425 if ((vtop
->r
& VT_LVAL
) && !nocode_wanted
)
6427 vtop
->type
= *pointed_type(&vtop
->type
);
6428 /* an array is never an lvalue */
6429 if (!(vtop
->type
.t
& VT_ARRAY
)) {
6430 vtop
->r
|= lvalue_type(vtop
->type
.t
);
6431 /* if bound checking, the referenced pointer must be checked */
6432 if (do_bounds_check
)
6433 vtop
->r
|= VT_MUSTBOUND
;
6437 /* pass a parameter to a function and do type checking and casting */
6438 void gfunc_param_typed(GFuncContext
*gf
, Sym
*func
, Sym
*arg
)
6443 func_type
= func
->c
;
6444 if (func_type
== FUNC_OLD
||
6445 (func_type
== FUNC_ELLIPSIS
&& arg
== NULL
)) {
6446 /* default casting : only need to convert float to double */
6447 if ((vtop
->type
.t
& VT_BTYPE
) == VT_FLOAT
) {
6451 } else if (arg
== NULL
) {
6452 error("too many arguments to function");
6454 gen_assign_cast(&arg
->type
);
6456 if (!nocode_wanted
) {
6463 /* parse an expression of the form '(type)' or '(expr)' and return its
6465 static void parse_expr_type(CType
*type
)
6471 if (parse_btype(type
, &ad
)) {
6472 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
6479 static void vpush_tokc(int t
)
6483 vsetc(&type
, VT_CONST
, &tokc
);
6486 static void unary(void)
6488 int n
, t
, align
, size
, r
;
6494 /* XXX: GCC 2.95.3 does not generate a table although it should be
6508 vpush_tokc(VT_INT
| VT_UNSIGNED
);
6512 vpush_tokc(VT_LLONG
);
6516 vpush_tokc(VT_LLONG
| VT_UNSIGNED
);
6520 vpush_tokc(VT_FLOAT
);
6524 vpush_tokc(VT_DOUBLE
);
6528 vpush_tokc(VT_LDOUBLE
);
6531 case TOK___FUNCTION__
:
6533 goto tok_identifier
;
6539 /* special function name identifier */
6540 len
= strlen(funcname
) + 1;
6541 /* generate char[len] type */
6546 vpush_ref(&type
, data_section
, data_section
->data_offset
, len
);
6547 ptr
= section_ptr_add(data_section
, len
);
6548 memcpy(ptr
, funcname
, len
);
6556 /* string parsing */
6562 memset(&ad
, 0, sizeof(AttributeDef
));
6563 decl_initializer_alloc(&type
, &ad
, VT_CONST
, 2, 0, 0);
6568 if (parse_btype(&type
, &ad
)) {
6569 type_decl(&type
, &ad
, &n
, TYPE_ABSTRACT
);
6571 /* check ISOC99 compound literal */
6573 /* data is allocated locally by default */
6578 /* all except arrays are lvalues */
6579 if (!(type
.t
& VT_ARRAY
))
6580 r
|= lvalue_type(type
.t
);
6581 memset(&ad
, 0, sizeof(AttributeDef
));
6582 decl_initializer_alloc(&type
, &ad
, r
, 1, 0, 0);
6587 } else if (tok
== '{') {
6588 /* save all registers */
6590 /* statement expression : we do not accept break/continue
6591 inside as GCC does */
6592 block(NULL
, NULL
, NULL
, NULL
, 0, 1);
6607 /* functions names must be treated as function pointers,
6608 except for unary '&' and sizeof. Since we consider that
6609 functions are not lvalues, we only have to handle it
6610 there and in function calls. */
6611 /* arrays can also be used although they are not lvalues */
6612 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
&&
6613 !(vtop
->type
.t
& VT_ARRAY
))
6615 mk_pointer(&vtop
->type
);
6621 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
)
6622 vtop
->c
.i
= !vtop
->c
.i
;
6623 else if ((vtop
->r
& VT_VALMASK
) == VT_CMP
)
6624 vtop
->c
.i
= vtop
->c
.i
^ 1;
6626 vseti(VT_JMP
, gtst(1, 0));
6636 /* in order to force cast, we add zero */
6638 if ((vtop
->type
.t
& VT_BTYPE
) == VT_PTR
)
6639 error("pointer not accepted for unary plus");
6649 parse_expr_type(&type
);
6653 size
= type_size(&type
, &align
);
6654 if (t
== TOK_SIZEOF
)
6675 goto tok_identifier
;
6677 /* allow to take the address of a label */
6678 if (tok
< TOK_UIDENT
)
6679 expect("label identifier");
6680 s
= label_find(tok
);
6682 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
6684 if (s
->r
== LABEL_DECLARED
)
6685 s
->r
= LABEL_FORWARD
;
6688 s
->type
.t
= VT_VOID
;
6689 mk_pointer(&s
->type
);
6690 s
->type
.t
|= VT_STATIC
;
6692 vset(&s
->type
, VT_CONST
| VT_SYM
, 0);
6701 expect("identifier");
6705 error("'%s' undeclared", get_tok_str(t
, NULL
));
6706 /* for simple function calls, we tolerate undeclared
6707 external reference to int() function */
6708 s
= external_global_sym(t
, &func_old_type
, 0);
6710 vset(&s
->type
, s
->r
, s
->c
);
6711 /* if forward reference, we must point to s */
6712 if (vtop
->r
& VT_SYM
) {
6719 /* post operations */
6721 if (tok
== TOK_INC
|| tok
== TOK_DEC
) {
6724 } else if (tok
== '.' || tok
== TOK_ARROW
) {
6726 if (tok
== TOK_ARROW
)
6731 /* expect pointer on structure */
6732 if ((vtop
->type
.t
& VT_BTYPE
) != VT_STRUCT
)
6733 expect("struct or union");
6737 while ((s
= s
->next
) != NULL
) {
6742 error("field not found");
6743 /* add field offset to pointer */
6744 vtop
->type
= char_pointer_type
; /* change type to 'char *' */
6747 /* change type to field type, and set to lvalue */
6748 vtop
->type
= s
->type
;
6749 /* an array is never an lvalue */
6750 if (!(vtop
->type
.t
& VT_ARRAY
)) {
6751 vtop
->r
|= lvalue_type(vtop
->type
.t
);
6752 /* if bound checking, the referenced pointer must be checked */
6753 if (do_bounds_check
)
6754 vtop
->r
|= VT_MUSTBOUND
;
6757 } else if (tok
== '[') {
6763 } else if (tok
== '(') {
6768 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
) {
6769 /* pointer test (no array accepted) */
6770 if ((vtop
->type
.t
& (VT_BTYPE
| VT_ARRAY
)) == VT_PTR
) {
6771 vtop
->type
= *pointed_type(&vtop
->type
);
6772 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
)
6776 expect("function pointer");
6779 vtop
->r
&= ~VT_LVAL
; /* no lvalue */
6781 /* get return type */
6783 if (!nocode_wanted
) {
6784 save_regs(0); /* save used temporary registers */
6785 gfunc_start(&gf
, s
->r
);
6788 sa
= s
->next
; /* first parameter */
6789 #ifdef INVERT_FUNC_PARAMS
6793 ParseState saved_parse_state
;
6796 /* read each argument and store it on a stack */
6802 while ((parlevel
> 0 || (tok
!= ')' && tok
!= ',')) &&
6806 else if (tok
== ')')
6808 tok_str_add_tok(&str
);
6811 tok_str_add(&str
, -1); /* end of file added */
6812 tok_str_add(&str
, 0);
6813 s1
= sym_push2(&args
, 0, 0, (int)str
.str
);
6814 s1
->next
= sa
; /* add reference to argument */
6823 /* now generate code in reverse order by reading the stack */
6824 save_parse_state(&saved_parse_state
);
6826 macro_ptr
= (int *)args
->c
;
6830 expect("',' or ')'");
6831 gfunc_param_typed(&gf
, s
, args
->next
);
6833 tok_str_free((int *)args
->c
);
6837 restore_parse_state(&saved_parse_state
);
6840 /* compute first implicit argument if a structure is returned */
6841 if ((s
->type
.t
& VT_BTYPE
) == VT_STRUCT
) {
6842 /* get some space for the returned structure */
6843 size
= type_size(&s
->type
, &align
);
6844 loc
= (loc
- size
) & -align
;
6846 ret
.r
= VT_LOCAL
| VT_LVAL
;
6847 /* pass it as 'int' to avoid structure arg passing
6849 vseti(VT_LOCAL
, loc
);
6858 /* return in register */
6859 if (is_float(ret
.type
.t
)) {
6862 if ((ret
.type
.t
& VT_BTYPE
) == VT_LLONG
)
6868 #ifndef INVERT_FUNC_PARAMS
6872 gfunc_param_typed(&gf
, s
, sa
);
6882 error("too few arguments to function");
6889 vsetc(&ret
.type
, ret
.r
, &ret
.c
);
6897 static void uneq(void)
6903 (tok
>= TOK_A_MOD
&& tok
<= TOK_A_DIV
) ||
6904 tok
== TOK_A_XOR
|| tok
== TOK_A_OR
||
6905 tok
== TOK_A_SHL
|| tok
== TOK_A_SAR
) {
6920 static void expr_prod(void)
6925 while (tok
== '*' || tok
== '/' || tok
== '%') {
6933 static void expr_sum(void)
6938 while (tok
== '+' || tok
== '-') {
6946 static void expr_shift(void)
6951 while (tok
== TOK_SHL
|| tok
== TOK_SAR
) {
6959 static void expr_cmp(void)
6964 while ((tok
>= TOK_ULE
&& tok
<= TOK_GT
) ||
6965 tok
== TOK_ULT
|| tok
== TOK_UGE
) {
6973 static void expr_cmpeq(void)
6978 while (tok
== TOK_EQ
|| tok
== TOK_NE
) {
6986 static void expr_and(void)
6989 while (tok
== '&') {
6996 static void expr_xor(void)
6999 while (tok
== '^') {
7006 static void expr_or(void)
7009 while (tok
== '|') {
7016 /* XXX: fix this mess */
7017 static void expr_land_const(void)
7020 while (tok
== TOK_LAND
) {
7027 /* XXX: fix this mess */
7028 static void expr_lor_const(void)
7031 while (tok
== TOK_LOR
) {
7038 /* only used if non constant */
7039 static void expr_land(void)
7044 if (tok
== TOK_LAND
) {
7048 if (tok
!= TOK_LAND
) {
7058 static void expr_lor(void)
7063 if (tok
== TOK_LOR
) {
7067 if (tok
!= TOK_LOR
) {
7077 /* XXX: better constant handling */
7078 static void expr_eq(void)
7080 int tt
, u
, r1
, r2
, rc
, t1
, t2
, bt1
, bt2
;
7082 CType type
, type1
, type2
;
7091 if (tok
== ':' && gnu_ext
) {
7107 if (vtop
!= vstack
) {
7108 /* needed to avoid having different registers saved in
7110 if (is_float(vtop
->type
.t
))
7117 if (tok
== ':' && gnu_ext
) {
7125 sv
= *vtop
; /* save value to handle it later */
7126 vtop
--; /* no vpop so that FP stack is not flushed */
7134 bt1
= t1
& VT_BTYPE
;
7136 bt2
= t2
& VT_BTYPE
;
7137 /* cast operands to correct type according to ISOC rules */
7138 if (is_float(bt1
) || is_float(bt2
)) {
7139 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
7140 type
.t
= VT_LDOUBLE
;
7141 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
7146 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
7147 /* cast to biggest op */
7149 /* convert to unsigned if it does not fit in a long long */
7150 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
7151 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
7152 type
.t
|= VT_UNSIGNED
;
7153 } else if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
7154 /* XXX: test pointer compatibility */
7156 } else if (bt1
== VT_STRUCT
|| bt2
== VT_STRUCT
) {
7157 /* XXX: test structure compatibility */
7159 } else if (bt1
== VT_VOID
|| bt2
== VT_VOID
) {
7160 /* NOTE: as an extension, we accept void on only one side */
7163 /* integer operations */
7165 /* convert to unsigned if it does not fit in an integer */
7166 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
7167 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
7168 type
.t
|= VT_UNSIGNED
;
7171 /* now we convert second operand */
7174 if (is_float(type
.t
)) {
7176 } else if ((type
.t
& VT_BTYPE
) == VT_LLONG
) {
7177 /* for long longs, we use fixed registers to avoid having
7178 to handle a complicated move */
7183 /* this is horrible, but we must also convert first
7187 /* put again first value and cast it */
7198 static void gexpr(void)
7209 /* parse an expression and return its type without any side effect. */
7210 static void expr_type(CType
*type
)
7222 /* parse a unary expression and return its type without any side
7224 static void unary_type(CType
*type
)
7236 /* parse a constant expression and return value in vtop. */
7237 static void expr_const1(void)
7246 /* parse an integer constant and return its value. */
7247 static int expr_const(void)
7251 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
7252 expect("constant expression");
7258 /* return the label token if current token is a label, otherwise
7260 static int is_label(void)
7264 /* fast test first */
7265 if (tok
< TOK_UIDENT
)
7267 /* no need to save tokc because tok is an identifier */
7274 unget_tok(last_tok
);
7279 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
7280 int case_reg
, int is_expr
)
7285 /* generate line number info */
7287 (last_line_num
!= file
->line_num
|| last_ind
!= ind
)) {
7288 put_stabn(N_SLINE
, 0, file
->line_num
, ind
- func_ind
);
7290 last_line_num
= file
->line_num
;
7294 /* default return value is (void) */
7296 vtop
->type
.t
= VT_VOID
;
7299 if (tok
== TOK_IF
) {
7306 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7308 if (c
== TOK_ELSE
) {
7312 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7313 gsym(d
); /* patch else jmp */
7316 } else if (tok
== TOK_WHILE
) {
7324 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7328 } else if (tok
== '{') {
7332 /* record local declaration stack position */
7334 llabel
= local_label_stack
;
7335 /* handle local labels declarations */
7336 if (tok
== TOK_LABEL
) {
7339 if (tok
< TOK_UIDENT
)
7340 expect("label identifier");
7341 label_push(&local_label_stack
, tok
, LABEL_DECLARED
);
7351 while (tok
!= '}') {
7356 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
7359 /* pop locally defined labels */
7360 label_pop(&local_label_stack
, llabel
);
7361 /* pop locally defined symbols */
7362 sym_pop(&local_stack
, s
);
7364 } else if (tok
== TOK_RETURN
) {
7368 gen_assign_cast(&func_vt
);
7369 if ((func_vt
.t
& VT_BTYPE
) == VT_STRUCT
) {
7371 /* if returning structure, must copy it to implicit
7372 first pointer arg location */
7375 vset(&type
, VT_LOCAL
| VT_LVAL
, func_vc
);
7378 /* copy structure value to pointer */
7380 } else if (is_float(func_vt
.t
)) {
7385 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
7388 rsym
= gjmp(rsym
); /* jmp */
7389 } else if (tok
== TOK_BREAK
) {
7392 error("cannot break");
7393 *bsym
= gjmp(*bsym
);
7396 } else if (tok
== TOK_CONTINUE
) {
7399 error("cannot continue");
7400 *csym
= gjmp(*csym
);
7403 } else if (tok
== TOK_FOR
) {
7430 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7435 if (tok
== TOK_DO
) {
7440 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7451 if (tok
== TOK_SWITCH
) {
7455 /* XXX: other types than integer */
7456 case_reg
= gv(RC_INT
);
7460 b
= gjmp(0); /* jump to first case */
7462 block(&a
, csym
, &b
, &c
, case_reg
, 0);
7463 /* if no default, jmp after switch */
7471 if (tok
== TOK_CASE
) {
7478 if (gnu_ext
&& tok
== TOK_DOTS
) {
7482 warning("empty case range");
7484 /* since a case is like a label, we must skip it with a jmp */
7491 *case_sym
= gtst(1, 0);
7494 *case_sym
= gtst(1, 0);
7498 *case_sym
= gtst(1, *case_sym
);
7502 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7504 if (tok
== TOK_DEFAULT
) {
7510 error("too many 'default'");
7512 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7514 if (tok
== TOK_GOTO
) {
7516 if (tok
== '*' && gnu_ext
) {
7520 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
7523 } else if (tok
>= TOK_UIDENT
) {
7524 s
= label_find(tok
);
7525 /* put forward definition if needed */
7527 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
7529 if (s
->r
== LABEL_DECLARED
)
7530 s
->r
= LABEL_FORWARD
;
7532 /* label already defined */
7533 if (s
->r
& LABEL_FORWARD
)
7534 s
->next
= (void *)gjmp((long)s
->next
);
7536 gjmp_addr((long)s
->next
);
7539 expect("label identifier");
7542 } else if (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
) {
7550 if (s
->r
== LABEL_DEFINED
)
7551 error("duplicate label '%s'", get_tok_str(s
->v
, NULL
));
7552 gsym((long)s
->next
);
7553 s
->r
= LABEL_DEFINED
;
7555 s
= label_push(&global_label_stack
, b
, LABEL_DEFINED
);
7557 s
->next
= (void *)ind
;
7558 /* we accept this, but it is a mistake */
7560 warning("deprecated use of label at end of compound statement");
7564 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
7567 /* expression case */
7582 /* t is the array or struct type. c is the array or struct
7583 address. cur_index/cur_field is the pointer to the current
7584 value. 'size_only' is true if only size info is needed (only used
7586 static void decl_designator(CType
*type
, Section
*sec
, unsigned long c
,
7587 int *cur_index
, Sym
**cur_field
,
7591 int notfirst
, index
, index_last
, align
, l
, nb_elems
, elem_size
;
7597 if (gnu_ext
&& (l
= is_label()) != 0)
7599 while (tok
== '[' || tok
== '.') {
7601 if (!(type
->t
& VT_ARRAY
))
7602 expect("array type");
7605 index
= expr_const();
7606 if (index
< 0 || (s
->c
>= 0 && index
>= s
->c
))
7607 expect("invalid index");
7608 if (tok
== TOK_DOTS
&& gnu_ext
) {
7610 index_last
= expr_const();
7611 if (index_last
< 0 ||
7612 (s
->c
>= 0 && index_last
>= s
->c
) ||
7614 expect("invalid index");
7620 *cur_index
= index_last
;
7621 type
= pointed_type(type
);
7622 elem_size
= type_size(type
, &align
);
7623 c
+= index
* elem_size
;
7624 /* NOTE: we only support ranges for last designator */
7625 nb_elems
= index_last
- index
+ 1;
7626 if (nb_elems
!= 1) {
7635 if ((type
->t
& VT_BTYPE
) != VT_STRUCT
)
7636 expect("struct/union type");
7649 /* XXX: fix this mess by using explicit storage field */
7651 type1
.t
|= (type
->t
& ~VT_TYPE
);
7665 if (type
->t
& VT_ARRAY
) {
7667 type
= pointed_type(type
);
7668 c
+= index
* type_size(type
, &align
);
7672 error("too many field init");
7673 /* XXX: fix this mess by using explicit storage field */
7675 type1
.t
|= (type
->t
& ~VT_TYPE
);
7680 decl_initializer(type
, sec
, c
, 0, size_only
);
7682 /* XXX: make it more general */
7683 if (!size_only
&& nb_elems
> 1) {
7684 unsigned long c_end
;
7689 error("range init not supported yet for dynamic storage");
7690 c_end
= c
+ nb_elems
* elem_size
;
7691 if (c_end
> sec
->data_allocated
)
7692 section_realloc(sec
, c_end
);
7693 src
= sec
->data
+ c
;
7695 for(i
= 1; i
< nb_elems
; i
++) {
7697 memcpy(dst
, src
, elem_size
);
7703 #define EXPR_CONST 1
7706 /* store a value or an expression directly in global data or in local array */
7707 static void init_putv(CType
*type
, Section
*sec
, unsigned long c
,
7708 int v
, int expr_type
)
7710 int saved_global_expr
, bt
, bit_pos
, bit_size
;
7712 unsigned long long bit_mask
;
7719 /* compound literals must be allocated globally in this case */
7720 saved_global_expr
= global_expr
;
7723 global_expr
= saved_global_expr
;
7724 /* NOTE: symbols are accepted */
7725 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) != VT_CONST
)
7726 error("initializer element is not constant");
7734 /* XXX: not portable */
7735 /* XXX: generate error if incorrect relocation */
7736 gen_assign_cast(type
);
7737 bt
= type
->t
& VT_BTYPE
;
7738 ptr
= sec
->data
+ c
;
7739 /* XXX: make code faster ? */
7740 if (!(type
->t
& VT_BITFIELD
)) {
7745 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
7746 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
7747 bit_mask
= (1LL << bit_size
) - 1;
7749 if ((vtop
->r
& VT_SYM
) &&
7755 (bt
== VT_INT
&& bit_size
!= 32)))
7756 error("initializer element is not computable at load time");
7759 *(char *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
7762 *(short *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
7765 *(double *)ptr
= vtop
->c
.d
;
7768 *(long double *)ptr
= vtop
->c
.ld
;
7771 *(long long *)ptr
|= (vtop
->c
.ll
& bit_mask
) << bit_pos
;
7774 if (vtop
->r
& VT_SYM
) {
7775 greloc(sec
, vtop
->sym
, c
, R_DATA_32
);
7777 *(int *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
7782 vset(type
, VT_LOCAL
, c
);
7789 /* put zeros for variable based init */
7790 static void init_putz(CType
*t
, Section
*sec
, unsigned long c
, int size
)
7795 /* nothing to do because globals are already set to zero */
7797 gfunc_start(&gf
, FUNC_CDECL
);
7804 vpush_global_sym(&func_old_type
, TOK_memset
);
7809 /* 't' contains the type and storage info. 'c' is the offset of the
7810 object in section 'sec'. If 'sec' is NULL, it means stack based
7811 allocation. 'first' is true if array '{' must be read (multi
7812 dimension implicit array init handling). 'size_only' is true if
7813 size only evaluation is wanted (only for arrays). */
7814 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
7815 int first
, int size_only
)
7817 int index
, array_length
, n
, no_oblock
, nb
, parlevel
, i
;
7818 int size1
, align1
, expr_type
;
7822 if (type
->t
& VT_ARRAY
) {
7826 t1
= pointed_type(type
);
7827 size1
= type_size(t1
, &align1
);
7830 if ((first
&& tok
!= TOK_LSTR
&& tok
!= TOK_STR
) ||
7836 /* only parse strings here if correct type (otherwise: handle
7837 them as ((w)char *) expressions */
7838 if ((tok
== TOK_LSTR
&&
7839 (t1
->t
& VT_BTYPE
) == VT_INT
) ||
7841 (t1
->t
& VT_BTYPE
) == VT_BYTE
)) {
7842 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
7847 /* compute maximum number of chars wanted */
7849 cstr_len
= cstr
->size
;
7851 cstr_len
= cstr
->size
/ sizeof(int);
7854 if (n
>= 0 && nb
> (n
- array_length
))
7855 nb
= n
- array_length
;
7858 warning("initializer-string for array is too long");
7859 /* in order to go faster for common case (char
7860 string in global variable, we handle it
7862 if (sec
&& tok
== TOK_STR
&& size1
== 1) {
7863 memcpy(sec
->data
+ c
+ array_length
, cstr
->data
, nb
);
7867 ch
= ((unsigned char *)cstr
->data
)[i
];
7869 ch
= ((int *)cstr
->data
)[i
];
7870 init_putv(t1
, sec
, c
+ (array_length
+ i
) * size1
,
7878 /* only add trailing zero if enough storage (no
7879 warning in this case since it is standard) */
7880 if (n
< 0 || array_length
< n
) {
7882 init_putv(t1
, sec
, c
+ (array_length
* size1
), 0, EXPR_VAL
);
7888 while (tok
!= '}') {
7889 decl_designator(type
, sec
, c
, &index
, NULL
, size_only
);
7890 if (n
>= 0 && index
>= n
)
7891 error("index too large");
7892 /* must put zero in holes (note that doing it that way
7893 ensures that it even works with designators) */
7894 if (!size_only
&& array_length
< index
) {
7895 init_putz(t1
, sec
, c
+ array_length
* size1
,
7896 (index
- array_length
) * size1
);
7899 if (index
> array_length
)
7900 array_length
= index
;
7901 /* special test for multi dimensional arrays (may not
7902 be strictly correct if designators are used at the
7904 if (index
>= n
&& no_oblock
)
7913 /* put zeros at the end */
7914 if (!size_only
&& n
>= 0 && array_length
< n
) {
7915 init_putz(t1
, sec
, c
+ array_length
* size1
,
7916 (n
- array_length
) * size1
);
7918 /* patch type size if needed */
7920 s
->c
= array_length
;
7921 } else if ((type
->t
& VT_BTYPE
) == VT_STRUCT
&&
7922 (sec
|| !first
|| tok
== '{')) {
7925 /* NOTE: the previous test is a specific case for automatic
7926 struct/union init */
7927 /* XXX: union needs only one init */
7929 /* XXX: this test is incorrect for local initializers
7930 beginning with ( without {. It would be much more difficult
7931 to do it correctly (ideally, the expression parser should
7932 be used in all cases) */
7938 while (tok
== '(') {
7942 if (!parse_btype(&type1
, &ad1
))
7944 type_decl(&type1
, &ad1
, &n
, TYPE_ABSTRACT
);
7945 if (!is_compatible_types(type
, &type1
))
7946 error("invalid type for cast");
7950 if (first
|| tok
== '{') {
7959 while (tok
!= '}') {
7960 decl_designator(type
, sec
, c
, NULL
, &f
, size_only
);
7962 if (!size_only
&& array_length
< index
) {
7963 init_putz(type
, sec
, c
+ array_length
,
7964 index
- array_length
);
7966 index
= index
+ type_size(&f
->type
, &align1
);
7967 if (index
> array_length
)
7968 array_length
= index
;
7970 if (no_oblock
&& f
== NULL
)
7976 /* put zeros at the end */
7977 if (!size_only
&& array_length
< n
) {
7978 init_putz(type
, sec
, c
+ array_length
,
7987 } else if (tok
== '{') {
7989 decl_initializer(type
, sec
, c
, first
, size_only
);
7991 } else if (size_only
) {
7992 /* just skip expression */
7994 while ((parlevel
> 0 || (tok
!= '}' && tok
!= ',')) &&
7998 else if (tok
== ')')
8003 /* currently, we always use constant expression for globals
8004 (may change for scripting case) */
8005 expr_type
= EXPR_CONST
;
8007 expr_type
= EXPR_ANY
;
8008 init_putv(type
, sec
, c
, 0, expr_type
);
8012 /* parse an initializer for type 't' if 'has_init' is non zero, and
8013 allocate space in local or global data space ('r' is either
8014 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
8015 variable 'v' of scope 'scope' is declared before initializers are
8016 parsed. If 'v' is zero, then a reference to the new object is put
8017 in the value stack. If 'has_init' is 2, a special parsing is done
8018 to handle string constants. */
8019 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
8020 int has_init
, int v
, int scope
)
8022 int size
, align
, addr
, data_offset
;
8024 ParseState saved_parse_state
;
8025 TokenString init_str
;
8028 size
= type_size(type
, &align
);
8029 /* If unknown size, we must evaluate it before
8030 evaluating initializers because
8031 initializers can generate global data too
8032 (e.g. string pointers or ISOC99 compound
8033 literals). It also simplifies local
8034 initializers handling */
8035 tok_str_new(&init_str
);
8038 error("unknown type size");
8039 /* get all init string */
8040 if (has_init
== 2) {
8041 /* only get strings */
8042 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
8043 tok_str_add_tok(&init_str
);
8048 while (level
> 0 || (tok
!= ',' && tok
!= ';')) {
8050 error("unexpected end of file in initializer");
8051 tok_str_add_tok(&init_str
);
8054 else if (tok
== '}') {
8062 tok_str_add(&init_str
, -1);
8063 tok_str_add(&init_str
, 0);
8066 save_parse_state(&saved_parse_state
);
8068 macro_ptr
= init_str
.str
;
8070 decl_initializer(type
, NULL
, 0, 1, 1);
8071 /* prepare second initializer parsing */
8072 macro_ptr
= init_str
.str
;
8075 /* if still unknown size, error */
8076 size
= type_size(type
, &align
);
8078 error("unknown type size");
8080 /* take into account specified alignment if bigger */
8081 if (ad
->aligned
> align
)
8082 align
= ad
->aligned
;
8083 if ((r
& VT_VALMASK
) == VT_LOCAL
) {
8085 if (do_bounds_check
&& (type
->t
& VT_ARRAY
))
8087 loc
= (loc
- size
) & -align
;
8089 /* handles bounds */
8090 /* XXX: currently, since we do only one pass, we cannot track
8091 '&' operators, so we add only arrays */
8092 if (do_bounds_check
&& (type
->t
& VT_ARRAY
)) {
8093 unsigned long *bounds_ptr
;
8094 /* add padding between regions */
8096 /* then add local bound info */
8097 bounds_ptr
= section_ptr_add(lbounds_section
, 2 * sizeof(unsigned long));
8098 bounds_ptr
[0] = addr
;
8099 bounds_ptr
[1] = size
;
8102 /* local variable */
8103 sym_push(v
, type
, r
, addr
);
8105 /* push local reference */
8106 vset(type
, r
, addr
);
8112 if (v
&& scope
== VT_CONST
) {
8113 /* see if the symbol was already defined */
8116 if (!is_compatible_types(&sym
->type
, type
))
8117 error("incompatible types for redefinition of '%s'",
8118 get_tok_str(v
, NULL
));
8119 if (sym
->type
.t
& VT_EXTERN
) {
8120 /* if the variable is extern, it was not allocated */
8121 sym
->type
.t
&= ~VT_EXTERN
;
8123 /* we accept several definitions of the same
8124 global variable. this is tricky, because we
8125 must play with the SHN_COMMON type of the symbol */
8126 /* XXX: should check if the variable was already
8127 initialized. It is incorrect to initialized it
8129 /* no init data, we won't add more to the symbol */
8136 /* allocate symbol in corresponding section */
8143 data_offset
= sec
->data_offset
;
8144 data_offset
= (data_offset
+ align
- 1) & -align
;
8146 /* very important to increment global pointer at this time
8147 because initializers themselves can create new initializers */
8148 data_offset
+= size
;
8149 /* add padding if bound check */
8150 if (do_bounds_check
)
8152 sec
->data_offset
= data_offset
;
8153 /* allocate section space to put the data */
8154 if (sec
->sh_type
!= SHT_NOBITS
&&
8155 data_offset
> sec
->data_allocated
)
8156 section_realloc(sec
, data_offset
);
8158 addr
= 0; /* avoid warning */
8162 if (scope
== VT_CONST
) {
8167 sym
= sym_push(v
, type
, r
| VT_SYM
, 0);
8169 /* update symbol definition */
8171 put_extern_sym(sym
, sec
, addr
, size
);
8174 /* put a common area */
8175 put_extern_sym(sym
, NULL
, align
, size
);
8176 /* XXX: find a nicer way */
8177 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
8178 esym
->st_shndx
= SHN_COMMON
;
8183 /* push global reference */
8184 sym
= get_sym_ref(type
, sec
, addr
, size
);
8186 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
8190 /* handles bounds now because the symbol must be defined
8191 before for the relocation */
8192 if (do_bounds_check
) {
8193 unsigned long *bounds_ptr
;
8195 greloc(bounds_section
, sym
, bounds_section
->data_offset
, R_DATA_32
);
8196 /* then add global bound info */
8197 bounds_ptr
= section_ptr_add(bounds_section
, 2 * sizeof(long));
8198 bounds_ptr
[0] = 0; /* relocated */
8199 bounds_ptr
[1] = size
;
8203 decl_initializer(type
, sec
, addr
, 1, 0);
8204 /* restore parse state if needed */
8206 tok_str_free(init_str
.str
);
8207 restore_parse_state(&saved_parse_state
);
8213 void put_func_debug(Sym
*sym
)
8218 /* XXX: we put here a dummy type */
8219 snprintf(buf
, sizeof(buf
), "%s:%c1",
8220 funcname
, sym
->type
.t
& VT_STATIC
? 'f' : 'F');
8221 put_stabs_r(buf
, N_FUN
, 0, file
->line_num
, 0,
8222 cur_text_section
, sym
->c
);
8227 /* not finished : try to put some local vars in registers */
8228 //#define CONFIG_REG_VARS
8230 #ifdef CONFIG_REG_VARS
8231 void add_var_ref(int t
)
8233 printf("%s:%d: &%s\n",
8234 file
->filename
, file
->line_num
,
8235 get_tok_str(t
, NULL
));
8238 /* first pass on a function with heuristic to extract variable usage
8239 and pointer references to local variables for register allocation */
8240 void analyse_function(void)
8247 /* any symbol coming after '&' is considered as being a
8248 variable whose reference is taken. It is highly unaccurate
8249 but it is difficult to do better without a complete parse */
8252 /* if '& number', then no need to examine next tokens */
8253 if (tok
== TOK_CINT
||
8255 tok
== TOK_CLLONG
||
8256 tok
== TOK_CULLONG
) {
8258 } else if (tok
>= TOK_UIDENT
) {
8259 /* if '& ident [' or '& ident ->', then ident address
8263 if (tok
!= '[' && tok
!= TOK_ARROW
)
8267 while (tok
!= '}' && tok
!= ';' &&
8268 !((tok
== ',' || tok
== ')') && level
== 0)) {
8269 if (tok
>= TOK_UIDENT
) {
8271 } else if (tok
== '(') {
8273 } else if (tok
== ')') {
8286 /* parse an old style function declaration list */
8287 /* XXX: check multiple parameter */
8288 static void func_decl_list(Sym
*func_sym
)
8295 /* parse each declaration */
8296 while (tok
!= '{' && tok
!= ';' && tok
!= ',' && tok
!= TOK_EOF
) {
8297 if (!parse_btype(&btype
, &ad
))
8298 expect("declaration list");
8299 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
8300 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
8302 /* we accept no variable after */
8306 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
8307 /* find parameter in function parameter list */
8310 if ((s
->v
& ~SYM_FIELD
) == v
)
8314 error("declaration for parameter '%s' but no such parameter",
8315 get_tok_str(v
, NULL
));
8317 /* check that no storage specifier except 'register' was given */
8318 if (type
.t
& VT_STORAGE
)
8319 error("storage class specified for '%s'", get_tok_str(v
, NULL
));
8320 convert_parameter_type(&type
);
8321 /* we can add the type (NOTE: it could be local to the function) */
8323 /* accept other parameters */
8334 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
8335 static void decl(int l
)
8343 if (!parse_btype(&btype
, &ad
)) {
8344 /* skip redundant ';' */
8345 /* XXX: find more elegant solution */
8350 /* special test for old K&R protos without explicit int
8351 type. Only accepted when defining global data */
8352 if (l
== VT_LOCAL
|| tok
< TOK_DEFINE
)
8356 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
8357 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
8359 /* we accept no variable after */
8363 while (1) { /* iterate thru each declaration */
8365 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
8369 type_to_str(buf
, sizeof(buf
), t
, get_tok_str(v
, NULL
));
8370 printf("type = '%s'\n", buf
);
8373 if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
8374 /* if old style function prototype, we accept a
8377 if (sym
->c
== FUNC_OLD
)
8378 func_decl_list(sym
);
8382 #ifdef CONFIG_REG_VARS
8383 TokenString func_str
;
8384 ParseState saved_parse_state
;
8389 error("cannot use local functions");
8390 if (!(type
.t
& VT_FUNC
))
8391 expect("function definition");
8392 /* XXX: cannot do better now: convert extern line to static inline */
8393 if ((type
.t
& (VT_EXTERN
| VT_INLINE
)) == (VT_EXTERN
| VT_INLINE
))
8394 type
.t
= (type
.t
& ~VT_EXTERN
) | VT_STATIC
;
8396 #ifdef CONFIG_REG_VARS
8397 /* parse all function code and record it */
8399 tok_str_new(&func_str
);
8405 error("unexpected end of file");
8406 tok_str_add_tok(&func_str
);
8411 } else if (t
== '}') {
8413 if (block_level
== 0)
8417 tok_str_add(&func_str
, -1);
8418 tok_str_add(&func_str
, 0);
8420 save_parse_state(&saved_parse_state
);
8422 macro_ptr
= func_str
.str
;
8427 /* compute text section */
8428 cur_text_section
= ad
.section
;
8429 if (!cur_text_section
)
8430 cur_text_section
= text_section
;
8431 ind
= cur_text_section
->data_offset
;
8432 funcname
= get_tok_str(v
, NULL
);
8435 /* if symbol is already defined, then put complete type */
8438 /* put function symbol */
8439 sym
= global_identifier_push(v
, type
.t
, 0);
8440 sym
->type
.ref
= type
.ref
;
8442 /* NOTE: we patch the symbol size later */
8443 put_extern_sym(sym
, cur_text_section
, ind
, 0);
8445 sym
->r
= VT_SYM
| VT_CONST
;
8446 /* put debug symbol */
8448 put_func_debug(sym
);
8449 /* push a dummy symbol to enable local sym storage */
8450 sym_push2(&local_stack
, SYM_FIELD
, 0, 0);
8451 gfunc_prolog(&type
);
8454 #ifdef CONFIG_REG_VARS
8455 macro_ptr
= func_str
.str
;
8458 block(NULL
, NULL
, NULL
, NULL
, 0, 0);
8461 cur_text_section
->data_offset
= ind
;
8462 label_pop(&global_label_stack
, NULL
);
8463 sym_pop(&local_stack
, NULL
); /* reset local stack */
8464 /* end of function */
8465 /* patch symbol size */
8466 ((Elf32_Sym
*)symtab_section
->data
)[sym
->c
].st_size
=
8469 put_stabn(N_FUN
, 0, 0, ind
- func_ind
);
8471 funcname
= ""; /* for safety */
8472 func_vt
.t
= VT_VOID
; /* for safety */
8473 ind
= 0; /* for safety */
8475 #ifdef CONFIG_REG_VARS
8476 tok_str_free(func_str
.str
);
8477 restore_parse_state(&saved_parse_state
);
8481 if (btype
.t
& VT_TYPEDEF
) {
8482 /* save typedefed type */
8483 /* XXX: test storage specifiers ? */
8484 sym
= sym_push(v
, &type
, 0, 0);
8485 sym
->type
.t
|= VT_TYPEDEF
;
8486 } else if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
8487 /* external function definition */
8488 external_sym(v
, &type
, 0);
8490 /* not lvalue if array */
8492 if (!(type
.t
& VT_ARRAY
))
8493 r
|= lvalue_type(type
.t
);
8494 has_init
= (tok
== '=');
8495 if ((btype
.t
& VT_EXTERN
) ||
8496 ((type
.t
& VT_ARRAY
) && (type
.t
& VT_STATIC
) &&
8497 !has_init
&& l
== VT_CONST
&& type
.ref
->c
< 0)) {
8498 /* external variable */
8499 /* NOTE: as GCC, uninitialized global static
8500 arrays of null size are considered as
8502 external_sym(v
, &type
, r
);
8504 if (type
.t
& VT_STATIC
)
8510 decl_initializer_alloc(&type
, &ad
, r
,
8524 /* better than nothing, but needs extension to handle '-E' option
8526 static void preprocess_init(TCCState
*s1
)
8528 s1
->include_stack_ptr
= s1
->include_stack
;
8529 /* XXX: move that before to avoid having to initialize
8530 file->ifdef_stack_ptr ? */
8531 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
8532 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
8534 /* XXX: not ANSI compliant: bound checking says error */
8538 /* compile the C file opened in 'file'. Return non zero if errors. */
8539 static int tcc_compile(TCCState
*s1
)
8543 volatile int section_sym
;
8546 printf("%s: **** new file\n", file
->filename
);
8548 preprocess_init(s1
);
8551 anon_sym
= SYM_FIRST_ANOM
;
8553 /* file info: full path + filename */
8554 section_sym
= 0; /* avoid warning */
8556 section_sym
= put_elf_sym(symtab_section
, 0, 0,
8557 ELF32_ST_INFO(STB_LOCAL
, STT_SECTION
), 0,
8558 text_section
->sh_num
, NULL
);
8559 getcwd(buf
, sizeof(buf
));
8560 pstrcat(buf
, sizeof(buf
), "/");
8561 put_stabs_r(buf
, N_SO
, 0, 0,
8562 text_section
->data_offset
, text_section
, section_sym
);
8563 put_stabs_r(file
->filename
, N_SO
, 0, 0,
8564 text_section
->data_offset
, text_section
, section_sym
);
8566 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
8567 symbols can be safely used */
8568 put_elf_sym(symtab_section
, 0, 0,
8569 ELF32_ST_INFO(STB_LOCAL
, STT_FILE
), 0,
8570 SHN_ABS
, file
->filename
);
8572 /* define some often used types */
8573 int_type
.t
= VT_INT
;
8575 char_pointer_type
.t
= VT_BYTE
;
8576 mk_pointer(&char_pointer_type
);
8578 func_old_type
.t
= VT_FUNC
;
8579 func_old_type
.ref
= sym_push(SYM_FIELD
, &int_type
, FUNC_CDECL
, FUNC_OLD
);
8582 /* define 'void *alloca(unsigned int)' builtin function */
8587 sym
= sym_push(p
, mk_pointer(VT_VOID
), FUNC_CDECL
, FUNC_NEW
);
8588 s1
= sym_push(SYM_FIELD
, VT_UNSIGNED
| VT_INT
, 0, 0);
8591 sym_push(TOK_alloca
, VT_FUNC
| (p
<< VT_STRUCT_SHIFT
), VT_CONST
, 0);
8595 define_start
= define_stack
;
8597 if (setjmp(s1
->error_jmp_buf
) == 0) {
8599 s1
->error_set_jmp_enabled
= 1;
8601 ch
= file
->buf_ptr
[0];
8602 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
8603 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
;
8607 expect("declaration");
8609 /* end of translation unit info */
8611 put_stabs_r(NULL
, N_SO
, 0, 0,
8612 text_section
->data_offset
, text_section
, section_sym
);
8615 s1
->error_set_jmp_enabled
= 0;
8617 /* reset define stack, but leave -Dsymbols (may be incorrect if
8618 they are undefined) */
8619 free_defines(define_start
);
8621 sym_pop(&global_stack
, NULL
);
8623 return s1
->nb_errors
!= 0 ? -1 : 0;
8627 int tcc_compile_string(TCCState
*s
, const char *str
)
8629 BufferedFile bf1
, *bf
= &bf1
;
8633 /* init file structure */
8635 /* XXX: avoid copying */
8637 buf
= tcc_malloc(len
+ 1);
8640 memcpy(buf
, str
, len
);
8643 bf
->buf_end
= buf
+ len
;
8644 pstrcpy(bf
->filename
, sizeof(bf
->filename
), "<string>");
8648 ret
= tcc_compile(s
);
8652 /* currently, no need to close */
8657 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
8658 void tcc_define_symbol(TCCState
*s1
, const char *sym
, const char *value
)
8660 BufferedFile bf1
, *bf
= &bf1
;
8662 pstrcpy(bf
->buffer
, IO_BUF_SIZE
, sym
);
8663 pstrcat(bf
->buffer
, IO_BUF_SIZE
, " ");
8667 pstrcat(bf
->buffer
, IO_BUF_SIZE
, value
);
8669 /* init file structure */
8671 bf
->buf_ptr
= bf
->buffer
;
8672 bf
->buf_end
= bf
->buffer
+ strlen(bf
->buffer
);
8673 *bf
->buf_end
= CH_EOB
;
8674 bf
->filename
[0] = '\0';
8678 s1
->include_stack_ptr
= s1
->include_stack
;
8680 /* parse with define parser */
8681 ch
= file
->buf_ptr
[0];
8687 /* undefine a preprocessor symbol */
8688 void tcc_undefine_symbol(TCCState
*s1
, const char *sym
)
8692 ts
= tok_alloc(sym
, strlen(sym
));
8693 s
= define_find(ts
->tok
);
8694 /* undefine symbol by putting an invalid name */
8699 #ifdef CONFIG_TCC_ASM
8701 #include "i386-asm.c"
8705 static void asm_instr(void)
8707 error("inline asm() not supported");
8713 /* print the position in the source file of PC value 'pc' by reading
8714 the stabs debug information */
8715 static void rt_printline(unsigned long wanted_pc
)
8717 Stab_Sym
*sym
, *sym_end
;
8718 char func_name
[128], last_func_name
[128];
8719 unsigned long func_addr
, last_pc
, pc
;
8720 const char *incl_files
[INCLUDE_STACK_SIZE
];
8721 int incl_index
, len
, last_line_num
, i
;
8722 const char *str
, *p
;
8724 fprintf(stderr
, "0x%08lx:", wanted_pc
);
8726 func_name
[0] = '\0';
8729 last_func_name
[0] = '\0';
8730 last_pc
= 0xffffffff;
8732 sym
= (Stab_Sym
*)stab_section
->data
+ 1;
8733 sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
8734 while (sym
< sym_end
) {
8735 switch(sym
->n_type
) {
8736 /* function start or end */
8738 if (sym
->n_strx
== 0) {
8739 /* we test if between last line and end of function */
8740 pc
= sym
->n_value
+ func_addr
;
8741 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
8743 func_name
[0] = '\0';
8746 str
= stabstr_section
->data
+ sym
->n_strx
;
8747 p
= strchr(str
, ':');
8749 pstrcpy(func_name
, sizeof(func_name
), str
);
8752 if (len
> sizeof(func_name
) - 1)
8753 len
= sizeof(func_name
) - 1;
8754 memcpy(func_name
, str
, len
);
8755 func_name
[len
] = '\0';
8757 func_addr
= sym
->n_value
;
8760 /* line number info */
8762 pc
= sym
->n_value
+ func_addr
;
8763 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
8766 last_line_num
= sym
->n_desc
;
8768 strcpy(last_func_name
, func_name
);
8772 str
= stabstr_section
->data
+ sym
->n_strx
;
8774 if (incl_index
< INCLUDE_STACK_SIZE
) {
8775 incl_files
[incl_index
++] = str
;
8783 if (sym
->n_strx
== 0) {
8784 incl_index
= 0; /* end of translation unit */
8786 str
= stabstr_section
->data
+ sym
->n_strx
;
8787 /* do not add path */
8789 if (len
> 0 && str
[len
- 1] != '/')
8797 /* second pass: we try symtab symbols (no line number info) */
8800 Elf32_Sym
*sym
, *sym_end
;
8803 sym_end
= (Elf32_Sym
*)(symtab_section
->data
+ symtab_section
->data_offset
);
8804 for(sym
= (Elf32_Sym
*)symtab_section
->data
+ 1;
8807 type
= ELF32_ST_TYPE(sym
->st_info
);
8808 if (type
== STT_FUNC
) {
8809 if (wanted_pc
>= sym
->st_value
&&
8810 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
8811 pstrcpy(last_func_name
, sizeof(last_func_name
),
8812 strtab_section
->data
+ sym
->st_name
);
8818 /* did not find any info: */
8819 fprintf(stderr
, " ???\n");
8822 if (last_func_name
[0] != '\0') {
8823 fprintf(stderr
, " %s()", last_func_name
);
8825 if (incl_index
> 0) {
8826 fprintf(stderr
, " (%s:%d",
8827 incl_files
[incl_index
- 1], last_line_num
);
8828 for(i
= incl_index
- 2; i
>= 0; i
--)
8829 fprintf(stderr
, ", included from %s", incl_files
[i
]);
8830 fprintf(stderr
, ")");
8832 fprintf(stderr
, "\n");
8839 /* fix for glibc 2.1 */
8845 /* return the PC at frame level 'level'. Return non zero if not found */
8846 static int rt_get_caller_pc(unsigned long *paddr
,
8847 ucontext_t
*uc
, int level
)
8854 *paddr
= uc
->uc_mcontext
.mc_eip
;
8856 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
8861 fp
= uc
->uc_mcontext
.mc_ebp
;
8863 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
8865 for(i
=1;i
<level
;i
++) {
8866 /* XXX: check address validity with program info */
8867 if (fp
<= 0x1000 || fp
>= 0xc0000000)
8869 fp
= ((unsigned long *)fp
)[0];
8871 *paddr
= ((unsigned long *)fp
)[1];
8876 #error add arch specific rt_get_caller_pc()
8879 /* emit a run time error at position 'pc' */
8880 void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
8887 fprintf(stderr
, "Runtime error: ");
8888 vfprintf(stderr
, fmt
, ap
);
8889 fprintf(stderr
, "\n");
8890 for(i
=0;i
<num_callers
;i
++) {
8891 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
8894 fprintf(stderr
, "at ");
8896 fprintf(stderr
, "by ");
8903 /* signal handler for fatal errors */
8904 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
8906 ucontext_t
*uc
= puc
;
8910 switch(siginf
->si_code
) {
8913 rt_error(uc
, "division by zero");
8916 rt_error(uc
, "floating point exception");
8922 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
8923 rt_error(uc
, *rt_bound_error_msg
);
8925 rt_error(uc
, "dereferencing invalid pointer");
8928 rt_error(uc
, "illegal instruction");
8931 rt_error(uc
, "abort() called");
8934 rt_error(uc
, "caught signal %d", signum
);
8941 /* do all relocations (needed before using tcc_get_symbol()) */
8942 int tcc_relocate(TCCState
*s1
)
8949 tcc_add_runtime(s1
);
8951 relocate_common_syms();
8953 /* compute relocation address : section are relocated in place. We
8954 also alloc the bss space */
8955 for(i
= 1; i
< s1
->nb_sections
; i
++) {
8956 s
= s1
->sections
[i
];
8957 if (s
->sh_flags
& SHF_ALLOC
) {
8958 if (s
->sh_type
== SHT_NOBITS
)
8959 s
->data
= tcc_mallocz(s
->data_offset
);
8960 s
->sh_addr
= (unsigned long)s
->data
;
8964 relocate_syms(s1
, 1);
8966 if (s1
->nb_errors
!= 0)
8969 /* relocate each section */
8970 for(i
= 1; i
< s1
->nb_sections
; i
++) {
8971 s
= s1
->sections
[i
];
8973 relocate_section(s1
, s
);
8978 /* launch the compiled program with the given arguments */
8979 int tcc_run(TCCState
*s1
, int argc
, char **argv
)
8981 int (*prog_main
)(int, char **);
8983 if (tcc_relocate(s1
) < 0)
8986 prog_main
= tcc_get_symbol(s1
, "main");
8990 error("debug mode currently not available for Windows");
8992 struct sigaction sigact
;
8993 /* install TCC signal handlers to print debug info on fatal
8995 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
8996 sigact
.sa_sigaction
= sig_error
;
8997 sigemptyset(&sigact
.sa_mask
);
8998 sigaction(SIGFPE
, &sigact
, NULL
);
8999 sigaction(SIGILL
, &sigact
, NULL
);
9000 sigaction(SIGSEGV
, &sigact
, NULL
);
9001 sigaction(SIGBUS
, &sigact
, NULL
);
9002 sigaction(SIGABRT
, &sigact
, NULL
);
9006 #ifdef CONFIG_TCC_BCHECK
9007 if (do_bounds_check
) {
9008 void (*bound_init
)(void);
9010 /* set error function */
9011 rt_bound_error_msg
= (void *)tcc_get_symbol(s1
, "__bound_error_msg");
9013 /* XXX: use .init section so that it also work in binary ? */
9014 bound_init
= (void *)tcc_get_symbol(s1
, "__bound_init");
9018 return (*prog_main
)(argc
, argv
);
9021 TCCState
*tcc_new(void)
9028 s
= tcc_mallocz(sizeof(TCCState
));
9032 s
->output_type
= TCC_OUTPUT_MEMORY
;
9034 /* init isid table */
9036 isidnum_table
[i
] = isid(i
) || isnum(i
);
9038 /* add all tokens */
9040 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
9042 tok_ident
= TOK_IDENT
;
9051 ts
= tok_alloc(p
, r
- p
- 1);
9055 /* we add dummy defines for some special macros to speed up tests
9056 and to have working defined() */
9057 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
9058 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
9059 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
9060 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
9062 /* standard defines */
9063 tcc_define_symbol(s
, "__STDC__", NULL
);
9064 #if defined(TCC_TARGET_I386)
9065 tcc_define_symbol(s
, "__i386__", NULL
);
9068 tcc_define_symbol(s
, "__linux__", NULL
);
9069 tcc_define_symbol(s
, "linux", NULL
);
9071 /* tiny C specific defines */
9072 tcc_define_symbol(s
, "__TINYC__", NULL
);
9074 /* tiny C & gcc defines */
9075 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned int");
9076 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "int");
9077 tcc_define_symbol(s
, "__WCHAR_TYPE__", "int");
9079 /* default library paths */
9080 tcc_add_library_path(s
, "/usr/local/lib");
9081 tcc_add_library_path(s
, "/usr/lib");
9082 tcc_add_library_path(s
, "/lib");
9084 /* no section zero */
9085 dynarray_add((void ***)&s
->sections
, &s
->nb_sections
, NULL
);
9087 /* create standard sections */
9088 text_section
= new_section(s
, ".text", SHT_PROGBITS
, SHF_ALLOC
| SHF_EXECINSTR
);
9089 data_section
= new_section(s
, ".data", SHT_PROGBITS
, SHF_ALLOC
| SHF_WRITE
);
9090 bss_section
= new_section(s
, ".bss", SHT_NOBITS
, SHF_ALLOC
| SHF_WRITE
);
9092 /* symbols are always generated for linking stage */
9093 symtab_section
= new_symtab(s
, ".symtab", SHT_SYMTAB
, 0,
9095 ".hashtab", SHF_PRIVATE
);
9096 strtab_section
= symtab_section
->link
;
9098 /* private symbol table for dynamic symbols */
9099 s
->dynsymtab_section
= new_symtab(s
, ".dynsymtab", SHT_SYMTAB
, SHF_PRIVATE
,
9101 ".dynhashtab", SHF_PRIVATE
);
9105 void tcc_delete(TCCState
*s1
)
9109 /* free -D defines */
9113 n
= tok_ident
- TOK_IDENT
;
9114 for(i
= 0; i
< n
; i
++)
9115 tcc_free(table_ident
[i
]);
9116 tcc_free(table_ident
);
9118 /* free all sections */
9120 free_section(symtab_section
->hash
);
9122 free_section(s1
->dynsymtab_section
->hash
);
9123 free_section(s1
->dynsymtab_section
->link
);
9124 free_section(s1
->dynsymtab_section
);
9126 for(i
= 1; i
< s1
->nb_sections
; i
++)
9127 free_section(s1
->sections
[i
]);
9128 tcc_free(s1
->sections
);
9130 /* free loaded dlls array */
9131 for(i
= 0; i
< s1
->nb_loaded_dlls
; i
++)
9132 tcc_free(s1
->loaded_dlls
[i
]);
9133 tcc_free(s1
->loaded_dlls
);
9136 for(i
= 0; i
< s1
->nb_library_paths
; i
++)
9137 tcc_free(s1
->library_paths
[i
]);
9138 tcc_free(s1
->library_paths
);
9140 /* cached includes */
9141 for(i
= 0; i
< s1
->nb_cached_includes
; i
++)
9142 tcc_free(s1
->cached_includes
[i
]);
9143 tcc_free(s1
->cached_includes
);
9145 for(i
= 0; i
< s1
->nb_include_paths
; i
++)
9146 tcc_free(s1
->include_paths
[i
]);
9147 tcc_free(s1
->include_paths
);
9149 for(i
= 0; i
< s1
->nb_sysinclude_paths
; i
++)
9150 tcc_free(s1
->sysinclude_paths
[i
]);
9151 tcc_free(s1
->sysinclude_paths
);
9156 int tcc_add_include_path(TCCState
*s1
, const char *pathname
)
9160 pathname1
= tcc_strdup(pathname
);
9161 dynarray_add((void ***)&s1
->include_paths
, &s1
->nb_include_paths
, pathname1
);
9165 int tcc_add_sysinclude_path(TCCState
*s1
, const char *pathname
)
9169 pathname1
= tcc_strdup(pathname
);
9170 dynarray_add((void ***)&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
, pathname1
);
9174 static int tcc_add_file_internal(TCCState
*s1
, const char *filename
, int flags
)
9176 const char *ext
, *filename1
;
9179 BufferedFile
*saved_file
;
9181 /* find source file type with extension */
9182 filename1
= strrchr(filename
, '/');
9186 filename1
= filename
;
9187 ext
= strrchr(filename1
, '.');
9193 file
= tcc_open(s1
, filename
);
9195 if (flags
& AFF_PRINT_ERROR
) {
9196 error_noabort("file '%s' not found", filename
);
9202 if (!ext
|| !strcmp(ext
, "c")) {
9203 /* C file assumed */
9204 ret
= tcc_compile(s1
);
9206 #ifdef CONFIG_TCC_ASM
9207 if (!strcmp(ext
, "S")) {
9208 /* preprocessed assembler */
9209 ret
= tcc_assemble(s1
, 1);
9210 } else if (!strcmp(ext
, "s")) {
9211 /* non preprocessed assembler */
9212 ret
= tcc_assemble(s1
, 0);
9217 /* assume executable format: auto guess file type */
9218 if (read(fd
, &ehdr
, sizeof(ehdr
)) != sizeof(ehdr
)) {
9219 error_noabort("could not read header");
9222 lseek(fd
, 0, SEEK_SET
);
9224 if (ehdr
.e_ident
[0] == ELFMAG0
&&
9225 ehdr
.e_ident
[1] == ELFMAG1
&&
9226 ehdr
.e_ident
[2] == ELFMAG2
&&
9227 ehdr
.e_ident
[3] == ELFMAG3
) {
9228 file
->line_num
= 0; /* do not display line number if error */
9229 if (ehdr
.e_type
== ET_REL
) {
9230 ret
= tcc_load_object_file(s1
, fd
, 0);
9231 } else if (ehdr
.e_type
== ET_DYN
) {
9232 ret
= tcc_load_dll(s1
, fd
, filename
,
9233 (flags
& AFF_REFERENCED_DLL
) != 0);
9235 error_noabort("unrecognized ELF file");
9238 } else if (memcmp((char *)&ehdr
, ARMAG
, 8) == 0) {
9239 file
->line_num
= 0; /* do not display line number if error */
9240 ret
= tcc_load_archive(s1
, fd
);
9242 /* as GNU ld, consider it is an ld script if not recognized */
9243 ret
= tcc_load_ldscript(s1
);
9245 error_noabort("unrecognized file type");
9260 int tcc_add_file(TCCState
*s
, const char *filename
)
9262 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
);
9265 int tcc_add_library_path(TCCState
*s
, const char *pathname
)
9269 pathname1
= tcc_strdup(pathname
);
9270 dynarray_add((void ***)&s
->library_paths
, &s
->nb_library_paths
, pathname1
);
9274 /* find and load a dll. Return non zero if not found */
9275 /* XXX: add '-rpath' option support ? */
9276 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
)
9281 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
9282 snprintf(buf
, sizeof(buf
), "%s/%s",
9283 s
->library_paths
[i
], filename
);
9284 if (tcc_add_file_internal(s
, buf
, flags
) == 0)
9290 /* the library name is the same as the argument of the '-l' option */
9291 int tcc_add_library(TCCState
*s
, const char *libraryname
)
9297 /* first we look for the dynamic library if not static linking */
9298 if (!s
->static_link
) {
9299 snprintf(buf
, sizeof(buf
), "lib%s.so", libraryname
);
9300 /* if we output to memory, then we simply we dlopen(). */
9301 if (s
->output_type
== TCC_OUTPUT_MEMORY
) {
9302 /* Since the libc is already loaded, we don't need to load it again */
9303 if (!strcmp(libraryname
, "c"))
9305 h
= dlopen(buf
, RTLD_GLOBAL
| RTLD_LAZY
);
9309 if (tcc_add_dll(s
, buf
, 0) == 0)
9314 /* then we look for the static library */
9315 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
9316 snprintf(buf
, sizeof(buf
), "%s/lib%s.a",
9317 s
->library_paths
[i
], libraryname
);
9318 if (tcc_add_file_internal(s
, buf
, 0) == 0)
9324 int tcc_add_symbol(TCCState
*s
, const char *name
, unsigned long val
)
9326 add_elf_sym(symtab_section
, val
, 0,
9327 ELF32_ST_INFO(STB_GLOBAL
, STT_NOTYPE
),
9332 int tcc_set_output_type(TCCState
*s
, int output_type
)
9336 s
->output_type
= output_type
;
9339 /* default include paths */
9340 /* XXX: reverse order needed if -isystem support */
9341 tcc_add_sysinclude_path(s
, "/usr/local/include");
9342 tcc_add_sysinclude_path(s
, "/usr/include");
9343 snprintf(buf
, sizeof(buf
), "%s/include", tcc_lib_path
);
9344 tcc_add_sysinclude_path(s
, buf
);
9347 /* if bound checking, then add corresponding sections */
9348 #ifdef CONFIG_TCC_BCHECK
9349 if (do_bounds_check
) {
9351 tcc_define_symbol(s
, "__BOUNDS_CHECKING_ON", NULL
);
9352 /* create bounds sections */
9353 bounds_section
= new_section(s
, ".bounds",
9354 SHT_PROGBITS
, SHF_ALLOC
);
9355 lbounds_section
= new_section(s
, ".lbounds",
9356 SHT_PROGBITS
, SHF_ALLOC
);
9360 /* add debug sections */
9363 stab_section
= new_section(s
, ".stab", SHT_PROGBITS
, 0);
9364 stab_section
->sh_entsize
= sizeof(Stab_Sym
);
9365 stabstr_section
= new_section(s
, ".stabstr", SHT_STRTAB
, 0);
9366 put_elf_str(stabstr_section
, "");
9367 stab_section
->link
= stabstr_section
;
9368 /* put first entry */
9369 put_stabs("", 0, 0, 0, 0);
9372 /* add libc crt1/crti objects */
9373 if (output_type
== TCC_OUTPUT_EXE
||
9374 output_type
== TCC_OUTPUT_DLL
) {
9375 if (output_type
!= TCC_OUTPUT_DLL
)
9376 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crt1.o");
9377 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crti.o");
9382 #if !defined(LIBTCC)
9384 static int64_t getclock_us(void)
9389 return (tb
.time
* 1000LL + tb
.millitm
) * 1000LL;
9392 gettimeofday(&tv
, NULL
);
9393 return tv
.tv_sec
* 1000000LL + tv
.tv_usec
;
9399 printf("tcc version " TCC_VERSION
" - Tiny C Compiler - Copyright (C) 2001, 2002 Fabrice Bellard\n"
9400 "usage: tcc [-v] [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"
9401 " [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-static]\n"
9402 " [infile1 infile2...] [-run infile args...]\n"
9404 "General options:\n"
9405 " -v display current version\n"
9406 " -c compile only - generate an object file\n"
9407 " -o outfile set output filename\n"
9408 " -Bdir set tcc internal library path\n"
9409 " -bench output compilation statistics\n"
9410 " -run run compiled source\n"
9411 "Preprocessor options:\n"
9412 " -Idir add include path 'dir'\n"
9413 " -Dsym[=val] define 'sym' with value 'val'\n"
9414 " -Usym undefine 'sym'\n"
9416 " -Ldir add library path 'dir'\n"
9417 " -llib link with dynamic or static library 'lib'\n"
9418 " -shared generate a shared library\n"
9419 " -static static linking\n"
9420 " -r relocatable output\n"
9421 "Debugger options:\n"
9422 " -g generate runtime debug info\n"
9423 #ifdef CONFIG_TCC_BCHECK
9424 " -b compile with built-in memory and bounds checker (implies -g)\n"
9426 " -bt N show N callers in stack traces\n"
9430 #define TCC_OPTION_HAS_ARG 0x0001
9431 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
9433 typedef struct TCCOption
{
9460 TCC_OPTION_nostdinc
,
9461 TCC_OPTION_print_search_dirs
,
9462 TCC_OPTION_rdynamic
,
9467 static const TCCOption tcc_options
[] = {
9468 { "h", TCC_OPTION_HELP
, 0 },
9469 { "?", TCC_OPTION_HELP
, 0 },
9470 { "I", TCC_OPTION_I
, TCC_OPTION_HAS_ARG
},
9471 { "D", TCC_OPTION_D
, TCC_OPTION_HAS_ARG
},
9472 { "U", TCC_OPTION_U
, TCC_OPTION_HAS_ARG
},
9473 { "L", TCC_OPTION_L
, TCC_OPTION_HAS_ARG
},
9474 { "B", TCC_OPTION_B
, TCC_OPTION_HAS_ARG
},
9475 { "l", TCC_OPTION_l
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9476 { "bench", TCC_OPTION_bench
, 0 },
9477 { "bt", TCC_OPTION_bt
, TCC_OPTION_HAS_ARG
},
9478 #ifdef CONFIG_TCC_BCHECK
9479 { "b", TCC_OPTION_b
, 0 },
9481 { "g", TCC_OPTION_g
, 0 },
9482 { "c", TCC_OPTION_c
, 0 },
9483 { "static", TCC_OPTION_static
, 0 },
9484 { "shared", TCC_OPTION_shared
, 0 },
9485 { "o", TCC_OPTION_o
, TCC_OPTION_HAS_ARG
},
9486 { "run", TCC_OPTION_run
, 0 },
9487 { "rdynamic", TCC_OPTION_rdynamic
, 0 }, /* currently ignored */
9488 { "r", TCC_OPTION_r
, 0 },
9489 { "W", TCC_OPTION_W
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9490 { "O", TCC_OPTION_O
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9491 { "m", TCC_OPTION_m
, TCC_OPTION_HAS_ARG
},
9492 { "f", TCC_OPTION_f
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9493 { "nostdinc", TCC_OPTION_nostdinc
, 0 },
9494 { "print-search-dirs", TCC_OPTION_print_search_dirs
, 0 },
9495 { "v", TCC_OPTION_v
, 0 },
9499 int main(int argc
, char **argv
)
9502 int optind
, output_type
, multiple_files
, i
, reloc_output
;
9505 int nb_files
, nb_libraries
, nb_objfiles
, dminus
, ret
;
9506 char objfilename
[1024];
9507 int64_t start_time
= 0;
9508 const TCCOption
*popt
;
9509 const char *optarg
, *p1
, *r1
, *outfile
;
9510 int print_search_dirs
;
9513 output_type
= TCC_OUTPUT_EXE
;
9523 print_search_dirs
= 0;
9525 if (optind
>= argc
) {
9526 if (nb_files
== 0 && !print_search_dirs
)
9533 /* add a new file */
9534 dynarray_add((void ***)&files
, &nb_files
, r
);
9535 if (!multiple_files
) {
9537 /* argv[0] will be this file */
9541 /* find option in table (match only the first chars */
9546 error("invalid option -- '%s'", r
);
9559 if (popt
->flags
& TCC_OPTION_HAS_ARG
) {
9560 if (*r1
!= '\0' || (popt
->flags
& TCC_OPTION_NOSEP
)) {
9564 error("argument to '%s' is missing", r
);
9565 optarg
= argv
[optind
++];
9573 switch(popt
->index
) {
9574 case TCC_OPTION_HELP
:
9579 if (tcc_add_include_path(s
, optarg
) < 0)
9580 error("too many include paths");
9585 sym
= (char *)optarg
;
9586 value
= strchr(sym
, '=');
9591 tcc_define_symbol(s
, sym
, value
);
9595 tcc_undefine_symbol(s
, optarg
);
9598 tcc_add_library_path(s
, optarg
);
9601 /* set tcc utilities path (mainly for tcc development) */
9602 tcc_lib_path
= optarg
;
9605 dynarray_add((void ***)&files
, &nb_files
, r
);
9608 case TCC_OPTION_bench
:
9612 num_callers
= atoi(optarg
);
9614 #ifdef CONFIG_TCC_BCHECK
9616 do_bounds_check
= 1;
9625 output_type
= TCC_OUTPUT_OBJ
;
9627 case TCC_OPTION_static
:
9630 case TCC_OPTION_shared
:
9631 output_type
= TCC_OUTPUT_DLL
;
9638 /* generate a .o merging several output files */
9640 output_type
= TCC_OUTPUT_OBJ
;
9642 case TCC_OPTION_nostdinc
:
9645 case TCC_OPTION_print_search_dirs
:
9646 print_search_dirs
= 1;
9648 case TCC_OPTION_run
:
9650 output_type
= TCC_OUTPUT_MEMORY
;
9653 printf("tcc version %s\n", TCC_VERSION
);
9660 if (print_search_dirs
) {
9661 /* enough for Linux kernel */
9662 printf("install: %s/\n", tcc_lib_path
);
9666 nb_objfiles
= nb_files
- nb_libraries
;
9668 /* if outfile provided without other options, we output an
9670 if (outfile
&& output_type
== TCC_OUTPUT_MEMORY
)
9671 output_type
= TCC_OUTPUT_EXE
;
9673 /* check -c consistency : only single file handled. XXX: checks file type */
9674 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
9675 /* accepts only a single input file */
9676 if (nb_objfiles
!= 1)
9677 error("cannot specify multiple files with -c");
9678 if (nb_libraries
!= 0)
9679 error("cannot specify libraries with -c");
9682 /* compute default outfile name */
9683 if (output_type
!= TCC_OUTPUT_MEMORY
&& !outfile
) {
9684 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
9686 /* add .o extension */
9687 pstrcpy(objfilename
, sizeof(objfilename
) - 1, files
[0]);
9688 ext
= strrchr(objfilename
, '.');
9690 goto default_outfile
;
9691 strcpy(ext
+ 1, "o");
9694 pstrcpy(objfilename
, sizeof(objfilename
), "a.out");
9696 outfile
= objfilename
;
9700 start_time
= getclock_us();
9703 tcc_set_output_type(s
, output_type
);
9705 /* compile or add each files or library */
9706 for(i
= 0;i
< nb_files
; i
++) {
9707 const char *filename
;
9709 filename
= files
[i
];
9710 if (filename
[0] == '-') {
9711 if (tcc_add_library(s
, filename
+ 2) < 0)
9712 error("cannot find %s", filename
);
9714 if (tcc_add_file(s
, filename
) < 0) {
9721 /* free all files */
9726 total_time
= (double)(getclock_us() - start_time
) / 1000000.0;
9727 if (total_time
< 0.001)
9729 if (total_bytes
< 1)
9731 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
9732 tok_ident
- TOK_IDENT
, total_lines
, total_bytes
,
9733 total_time
, (int)(total_lines
/ total_time
),
9734 total_bytes
/ total_time
/ 1000000.0);
9737 if (s
->output_type
!= TCC_OUTPUT_MEMORY
) {
9738 tcc_output_file(s
, outfile
);
9741 ret
= tcc_run(s
, argc
- optind
, argv
+ optind
);
9744 /* XXX: cannot do it with bound checking because of the malloc hooks */
9745 if (!do_bounds_check
)
9750 printf("memory: %d bytes, max = %d bytes\n", mem_cur_size
, mem_max_size
);