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.
33 #include <sys/timeb.h>
37 #include <sys/ucontext.h>
41 #ifndef CONFIG_TCC_STATIC
49 /* preprocessor debug */
51 /* include file debug */
59 /* target selection */
60 //#define TCC_TARGET_I386 /* i386 code generator */
62 /* default target is I386 */
63 #if !defined(TCC_TARGET_I386)
64 #define TCC_TARGET_I386
67 #if !defined(WIN32) && !defined(TCC_UCLIBC)
68 #define CONFIG_TCC_BCHECK /* enable bound checking code */
71 /* define it to include assembler support */
72 #define CONFIG_TCC_ASM
74 #ifndef CONFIG_TCC_PREFIX
75 #define CONFIG_TCC_PREFIX "/usr/local"
78 /* path to find crt1.o, crti.o and crtn.o. Only needed when generating
79 executables or dlls */
80 #define CONFIG_TCC_CRT_PREFIX "/usr/lib"
82 #define INCLUDE_STACK_SIZE 32
83 #define IFDEF_STACK_SIZE 64
84 #define VSTACK_SIZE 64
85 #define STRING_MAX_SIZE 1024
87 #define TOK_HASH_SIZE 2048 /* must be a power of two */
88 #define TOK_ALLOC_INCR 512 /* must be a power of two */
89 #define TOK_STR_ALLOC_INCR_BITS 6
90 #define TOK_STR_ALLOC_INCR (1 << TOK_STR_ALLOC_INCR_BITS)
91 #define TOK_MAX_SIZE 4 /* token max size in int unit when stored in string */
93 /* token symbol management */
94 typedef struct TokenSym
{
95 struct TokenSym
*hash_next
;
96 struct Sym
*sym_define
; /* direct pointer to define */
97 struct Sym
*sym_label
; /* direct pointer to label */
98 struct Sym
*sym_struct
; /* direct pointer to structure */
99 struct Sym
*sym_identifier
; /* direct pointer to identifier */
100 int tok
; /* token number */
105 typedef struct CString
{
106 int size
; /* size in bytes */
107 void *data
; /* either 'char *' or 'int *' */
109 void *data_allocated
; /* if non NULL, data has been malloced */
112 /* type definition */
113 typedef struct CType
{
119 typedef union CValue
{
125 unsigned int ul
; /* address (should be unsigned long on 64 bit cpu) */
127 unsigned long long ull
;
128 struct CString
*cstr
;
134 typedef struct SValue
{
135 CType type
; /* type */
136 unsigned short r
; /* register + flags */
137 unsigned short r2
; /* second register, used for 'long long'
138 type. If not used, set to VT_CONST */
139 CValue c
; /* constant, if VT_CONST */
140 struct Sym
*sym
; /* symbol, if (VT_SYM | VT_CONST) */
143 /* symbol management */
145 int v
; /* symbol token */
146 int r
; /* associated register */
147 int c
; /* associated number */
148 CType type
; /* associated type */
149 struct Sym
*next
; /* next related symbol */
150 struct Sym
*prev
; /* prev symbol in stack */
151 struct Sym
*prev_tok
; /* previous symbol for this token */
154 /* section definition */
155 /* XXX: use directly ELF structure for parameters ? */
156 /* special flag to indicate that the section should not be linked to
158 #define SHF_PRIVATE 0x80000000
160 typedef struct Section
{
161 unsigned long data_offset
; /* current data offset */
162 unsigned char *data
; /* section data */
163 unsigned long data_allocated
; /* used for realloc() handling */
164 int sh_name
; /* elf section name (only used during output) */
165 int sh_num
; /* elf section number */
166 int sh_type
; /* elf section type */
167 int sh_flags
; /* elf section flags */
168 int sh_info
; /* elf section info */
169 int sh_addralign
; /* elf section alignment */
170 int sh_entsize
; /* elf entry size */
171 unsigned long sh_size
; /* section size (only used during output) */
172 unsigned long sh_addr
; /* address at which the section is relocated */
173 unsigned long sh_offset
; /* address at which the section is relocated */
174 int nb_hashed_syms
; /* used to resize the hash table */
175 struct Section
*link
; /* link to another section */
176 struct Section
*reloc
; /* corresponding section for relocation, if any */
177 struct Section
*hash
; /* hash table for symbols */
178 struct Section
*next
;
179 char name
[64]; /* section name */
182 typedef struct DLLReference
{
187 /* GNUC attribute definition */
188 typedef struct AttributeDef
{
191 unsigned char func_call
; /* FUNC_CDECL or FUNC_STDCALL */
194 #define SYM_STRUCT 0x40000000 /* struct/union/enum symbol space */
195 #define SYM_FIELD 0x20000000 /* struct/union field symbol space */
196 #define SYM_FIRST_ANOM (1 << (31 - VT_STRUCT_SHIFT)) /* first anonymous sym */
198 /* stored in 'Sym.c' field */
199 #define FUNC_NEW 1 /* ansi function prototype */
200 #define FUNC_OLD 2 /* old function prototype */
201 #define FUNC_ELLIPSIS 3 /* ansi function prototype with ... */
203 /* stored in 'Sym.r' field */
204 #define FUNC_CDECL 0 /* standard c call */
205 #define FUNC_STDCALL 1 /* pascal c call */
207 /* field 'Sym.t' for macros */
208 #define MACRO_OBJ 0 /* object like macro */
209 #define MACRO_FUNC 1 /* function like macro */
211 /* field 'Sym.r' for C labels */
212 #define LABEL_DEFINED 0 /* label is defined */
213 #define LABEL_FORWARD 1 /* label is forward defined */
214 #define LABEL_DECLARED 2 /* label is declared but never used */
216 /* type_decl() types */
217 #define TYPE_ABSTRACT 1 /* type without variable */
218 #define TYPE_DIRECT 2 /* type with variable */
220 #define IO_BUF_SIZE 8192
222 typedef struct BufferedFile
{
226 int line_num
; /* current line number - here to simply code */
227 int ifndef_macro
; /* #ifndef macro / #endif search */
228 int ifndef_macro_saved
; /* saved ifndef_macro */
229 int *ifdef_stack_ptr
; /* ifdef_stack value at the start of the file */
230 char inc_type
; /* type of include */
231 char inc_filename
[512]; /* filename specified by the user */
232 char filename
[1024]; /* current filename - here to simplify code */
233 unsigned char buffer
[IO_BUF_SIZE
+ 1]; /* extra size for CH_EOB char */
236 #define CH_EOB '\\' /* end of buffer or '\0' char in file */
237 #define CH_EOF (-1) /* end of file */
239 /* parsing state (used to save parser state to reparse part of the
240 source several times) */
241 typedef struct ParseState
{
248 /* used to record tokens */
249 typedef struct TokenString
{
256 /* include file cache, used to find files faster and also to eliminate
257 inclusion if the include file is protected by #ifndef ... #endif */
258 typedef struct CachedInclude
{
260 char type
; /* '"' or '>' to give include type */
261 char filename
[1]; /* path specified in #include */
265 static struct BufferedFile
*file
;
268 static CString tokcstr
; /* current parsed string, if any */
269 /* additionnal informations about token */
270 static int tok_flags
;
271 #define TOK_FLAG_BOL 0x0001 /* beginning of line before */
272 #define TOK_FLAG_BOF 0x0002 /* beginning of file before */
273 #define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */
275 static int *macro_ptr
, *macro_ptr_allocated
;
276 static int *unget_saved_macro_ptr
;
277 static int unget_saved_buffer
[TOK_MAX_SIZE
+ 1];
278 static int unget_buffer_enabled
;
279 static int parse_flags
;
280 #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
281 #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
282 #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
283 token. line feed is also
286 static Section
*text_section
, *data_section
, *bss_section
; /* predefined sections */
287 static Section
*cur_text_section
; /* current section where function code is
289 /* bound check related sections */
290 static Section
*bounds_section
; /* contains global data bound description */
291 static Section
*lbounds_section
; /* contains local data bound description */
292 /* symbol sections */
293 static Section
*symtab_section
, *strtab_section
;
296 static Section
*stab_section
, *stabstr_section
;
298 /* loc : local variable index
299 ind : output code index
301 anon_sym: anonymous symbol index
303 static int rsym
, anon_sym
, ind
, loc
;
304 /* expression generation modifiers */
305 static int const_wanted
; /* true if constant wanted */
306 static int nocode_wanted
; /* true if no code generation wanted for an expression */
307 static int global_expr
; /* true if compound literals must be allocated
308 globally (used during initializers parsing */
309 static CType func_vt
; /* current function return type (used by return
312 static int last_line_num
, last_ind
, func_ind
; /* debug last line number and pc */
313 static int tok_ident
;
314 static TokenSym
**table_ident
;
315 static TokenSym
*hash_ident
[TOK_HASH_SIZE
];
316 static char token_buf
[STRING_MAX_SIZE
+ 1];
317 static char *funcname
;
318 static Sym
*global_stack
, *local_stack
;
319 static Sym
*define_stack
;
320 static Sym
*global_label_stack
, *local_label_stack
;
322 static SValue vstack
[VSTACK_SIZE
], *vtop
;
323 /* some predefined types */
324 static CType char_pointer_type
, func_old_type
, int_type
;
325 /* true if isid(c) || isnum(c) */
326 static unsigned char isidnum_table
[256];
328 /* compile with debug symbol (and use them if error during execution) */
329 static int do_debug
= 0;
331 /* compile with built-in memory and bounds checker */
332 static int do_bounds_check
= 0;
334 /* display benchmark infos */
335 static int do_bench
= 0;
336 static int total_lines
;
337 static int total_bytes
;
339 /* use GNU C extensions */
340 static int gnu_ext
= 1;
342 /* use Tiny C extensions */
343 static int tcc_ext
= 1;
345 /* max number of callers shown if error */
346 static int num_callers
= 6;
347 static const char **rt_bound_error_msg
;
349 /* XXX: suppress that ASAP */
350 static struct TCCState
*tcc_state
;
352 /* give the path of the tcc libraries */
353 static const char *tcc_lib_path
= CONFIG_TCC_PREFIX
"/lib/tcc";
358 BufferedFile
**include_stack_ptr
;
359 int *ifdef_stack_ptr
;
361 /* include file handling */
362 char **include_paths
;
363 int nb_include_paths
;
364 char **sysinclude_paths
;
365 int nb_sysinclude_paths
;
366 CachedInclude
**cached_includes
;
367 int nb_cached_includes
;
369 char **library_paths
;
370 int nb_library_paths
;
372 /* array of all loaded dlls (including those referenced by loaded
374 DLLReference
**loaded_dlls
;
379 int nb_sections
; /* number of sections, including first dummy section */
384 unsigned long *got_offsets
;
386 /* give the correspondance from symtab indexes to dynsym indexes */
387 int *symtab_to_dynsym
;
389 /* temporary dynamic symbol sections (for dll loading) */
390 Section
*dynsymtab_section
;
391 /* exported dynamic symbol section */
394 /* if true, no standard headers are added */
397 /* if true, static linking is performed */
402 void (*error_func
)(void *opaque
, const char *msg
);
403 int error_set_jmp_enabled
;
404 jmp_buf error_jmp_buf
;
407 /* tiny assembler state */
410 /* see include_stack_ptr */
411 BufferedFile
*include_stack
[INCLUDE_STACK_SIZE
];
413 /* see ifdef_stack_ptr */
414 int ifdef_stack
[IFDEF_STACK_SIZE
];
417 /* The current value can be: */
418 #define VT_VALMASK 0x00ff
419 #define VT_CONST 0x00f0 /* constant in vc
420 (must be first non register value) */
421 #define VT_LLOCAL 0x00f1 /* lvalue, offset on stack */
422 #define VT_LOCAL 0x00f2 /* offset on stack */
423 #define VT_CMP 0x00f3 /* the value is stored in processor flags (in vc) */
424 #define VT_JMP 0x00f4 /* value is the consequence of jmp true (even) */
425 #define VT_JMPI 0x00f5 /* value is the consequence of jmp false (odd) */
426 #define VT_LVAL 0x0100 /* var is an lvalue */
427 #define VT_SYM 0x0200 /* a symbol value is added */
428 #define VT_MUSTCAST 0x0400 /* value must be casted to be correct (used for
429 char/short stored in integer registers) */
430 #define VT_MUSTBOUND 0x0800 /* bound checking must be done before
431 dereferencing value */
432 #define VT_BOUNDED 0x8000 /* value is bounded. The address of the
433 bounding function call point is in vc */
434 #define VT_LVAL_BYTE 0x1000 /* lvalue is a byte */
435 #define VT_LVAL_SHORT 0x2000 /* lvalue is a short */
436 #define VT_LVAL_UNSIGNED 0x4000 /* lvalue is unsigned */
437 #define VT_LVAL_TYPE (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
440 #define VT_STRUCT_SHIFT 12 /* structure/enum name shift (20 bits left) */
442 #define VT_INT 0 /* integer type */
443 #define VT_BYTE 1 /* signed byte type */
444 #define VT_SHORT 2 /* short type */
445 #define VT_VOID 3 /* void type */
446 #define VT_PTR 4 /* pointer */
447 #define VT_ENUM 5 /* enum definition */
448 #define VT_FUNC 6 /* function type */
449 #define VT_STRUCT 7 /* struct/union definition */
450 #define VT_FLOAT 8 /* IEEE float */
451 #define VT_DOUBLE 9 /* IEEE double */
452 #define VT_LDOUBLE 10 /* IEEE long double */
453 #define VT_BOOL 11 /* ISOC99 boolean type */
454 #define VT_LLONG 12 /* 64 bit integer */
455 #define VT_LONG 13 /* long integer (NEVER USED as type, only
457 #define VT_BTYPE 0x000f /* mask for basic type */
458 #define VT_UNSIGNED 0x0010 /* unsigned type */
459 #define VT_ARRAY 0x0020 /* array type (also has VT_PTR) */
460 #define VT_BITFIELD 0x0040 /* bitfield modifier */
463 #define VT_EXTERN 0x00000080 /* extern definition */
464 #define VT_STATIC 0x00000100 /* static variable */
465 #define VT_TYPEDEF 0x00000200 /* typedef definition */
466 #define VT_INLINE 0x00000400 /* inline definition */
468 /* type mask (except storage) */
469 #define VT_STORAGE (VT_EXTERN | VT_STATIC | VT_TYPEDEF | VT_INLINE)
470 #define VT_TYPE (~(VT_STORAGE))
474 /* warning: the following compare tokens depend on i386 asm code */
486 #define TOK_LAND 0xa0
490 #define TOK_MID 0xa3 /* inc/dec, to void constant */
492 #define TOK_UDIV 0xb0 /* unsigned division */
493 #define TOK_UMOD 0xb1 /* unsigned modulo */
494 #define TOK_PDIV 0xb2 /* fast division with undefined rounding for pointers */
495 #define TOK_CINT 0xb3 /* number in tokc */
496 #define TOK_CCHAR 0xb4 /* char constant in tokc */
497 #define TOK_STR 0xb5 /* pointer to string in tokc */
498 #define TOK_TWOSHARPS 0xb6 /* ## preprocessing token */
499 #define TOK_LCHAR 0xb7
500 #define TOK_LSTR 0xb8
501 #define TOK_CFLOAT 0xb9 /* float constant */
502 #define TOK_LINENUM 0xba /* line number info */
503 #define TOK_CDOUBLE 0xc0 /* double constant */
504 #define TOK_CLDOUBLE 0xc1 /* long double constant */
505 #define TOK_UMULL 0xc2 /* unsigned 32x32 -> 64 mul */
506 #define TOK_ADDC1 0xc3 /* add with carry generation */
507 #define TOK_ADDC2 0xc4 /* add with carry use */
508 #define TOK_SUBC1 0xc5 /* add with carry generation */
509 #define TOK_SUBC2 0xc6 /* add with carry use */
510 #define TOK_CUINT 0xc8 /* unsigned int constant */
511 #define TOK_CLLONG 0xc9 /* long long constant */
512 #define TOK_CULLONG 0xca /* unsigned long long constant */
513 #define TOK_ARROW 0xcb
514 #define TOK_DOTS 0xcc /* three dots */
515 #define TOK_SHR 0xcd /* unsigned shift right */
516 #define TOK_PPNUM 0xce /* preprocessor number */
518 #define TOK_SHL 0x01 /* shift left */
519 #define TOK_SAR 0x02 /* signed shift right */
521 /* assignement operators : normal operator or 0x80 */
522 #define TOK_A_MOD 0xa5
523 #define TOK_A_AND 0xa6
524 #define TOK_A_MUL 0xaa
525 #define TOK_A_ADD 0xab
526 #define TOK_A_SUB 0xad
527 #define TOK_A_DIV 0xaf
528 #define TOK_A_XOR 0xde
529 #define TOK_A_OR 0xfc
530 #define TOK_A_SHL 0x81
531 #define TOK_A_SAR 0x82
533 /* WARNING: the content of this string encodes token numbers */
534 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";
536 #define TOK_EOF (-1) /* end of file */
537 #define TOK_LINEFEED 10 /* line feed */
539 /* all identificators and strings have token above that */
540 #define TOK_IDENT 256
542 /* only used for i386 asm opcodes definitions */
543 #define DEF_ASM(x) DEF(TOK_ASM_ ## x, #x)
546 DEF(TOK_ASM_ ## x ## b, #x "b") \
547 DEF(TOK_ASM_ ## x ## w, #x "w") \
548 DEF(TOK_ASM_ ## x ## l, #x "l") \
549 DEF(TOK_ASM_ ## x, #x)
552 DEF(TOK_ASM_ ## x ## w, #x "w") \
553 DEF(TOK_ASM_ ## x ## l, #x "l") \
554 DEF(TOK_ASM_ ## x, #x)
557 DEF(TOK_ASM_ ## f ## x ## s, "f" #x "s") \
558 DEF(TOK_ASM_ ## fi ## x ## l, "fi" #x "l") \
559 DEF(TOK_ASM_ ## f ## x ## l, "f" #x "l") \
560 DEF(TOK_ASM_ ## fi ## x ## s, "fi" #x "s")
563 DEF(TOK_ASM_ ## f ## x, "f" #x ) \
564 DEF(TOK_ASM_ ## f ## x ## p, "f" #x "p") \
567 #define DEF_ASMTEST(x) \
599 #define TOK_ASM_int TOK_INT
602 TOK_LAST
= TOK_IDENT
- 1,
603 #define DEF(id, str) id,
608 static const char tcc_keywords
[] =
609 #define DEF(id, str) str "\0"
614 #define TOK_UIDENT TOK_DEFINE
617 #define snprintf _snprintf
618 #define vsnprintf _vsnprintf
621 #if defined(WIN32) || defined(TCC_UCLIBC) || defined(__FreeBSD__)
622 /* currently incorrect */
623 long double strtold(const char *nptr
, char **endptr
)
625 return (long double)strtod(nptr
, endptr
);
627 float strtof(const char *nptr
, char **endptr
)
629 return (float)strtod(nptr
, endptr
);
632 /* XXX: need to define this to use them in non ISOC99 context */
633 extern float strtof (const char *__nptr
, char **__endptr
);
634 extern long double strtold (const char *__nptr
, char **__endptr
);
637 static char *pstrcpy(char *buf
, int buf_size
, const char *s
);
638 static char *pstrcat(char *buf
, int buf_size
, const char *s
);
640 static void next(void);
641 static void next_nomacro(void);
642 static void parse_expr_type(CType
*type
);
643 static void expr_type(CType
*type
);
644 static void unary_type(CType
*type
);
645 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
646 int case_reg
, int is_expr
);
647 static int expr_const(void);
648 static void expr_eq(void);
649 static void gexpr(void);
650 static void decl(int l
);
651 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
652 int first
, int size_only
);
653 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
654 int has_init
, int v
, int scope
);
656 void gv2(int rc1
, int rc2
);
657 void move_reg(int r
, int s
);
658 void save_regs(int n
);
659 void save_reg(int r
);
665 static void macro_subst(TokenString
*tok_str
,
666 Sym
**nested_list
, const int *macro_str
);
667 int save_reg_forced(int r
);
669 void force_charshort_cast(int t
);
670 static void gen_cast(CType
*type
);
672 static Sym
*sym_find(int v
);
673 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
);
676 static int type_size(CType
*type
, int *a
);
677 static inline CType
*pointed_type(CType
*type
);
678 static int pointed_size(CType
*type
);
679 static int lvalue_type(int t
);
680 static int is_compatible_types(CType
*type1
, CType
*type2
);
681 static int parse_btype(CType
*type
, AttributeDef
*ad
);
682 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
);
684 void error(const char *fmt
, ...);
686 void vset(CType
*type
, int r
, int v
);
687 void type_to_str(char *buf
, int buf_size
,
688 CType
*type
, const char *varstr
);
689 char *get_tok_str(int v
, CValue
*cv
);
690 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
691 unsigned long offset
, unsigned long size
);
692 static Sym
*external_global_sym(int v
, CType
*type
, int r
);
694 /* section generation */
695 static void section_realloc(Section
*sec
, unsigned long new_size
);
696 static void *section_ptr_add(Section
*sec
, unsigned long size
);
697 static void put_extern_sym(Sym
*sym
, Section
*section
,
698 unsigned long value
, unsigned long size
);
699 static void greloc(Section
*s
, Sym
*sym
, unsigned long addr
, int type
);
700 static int put_elf_str(Section
*s
, const char *sym
);
701 static int put_elf_sym(Section
*s
,
702 unsigned long value
, unsigned long size
,
703 int info
, int other
, int shndx
, const char *name
);
704 static int add_elf_sym(Section
*s
, unsigned long value
, unsigned long size
,
705 int info
, int sh_num
, const char *name
);
706 static void put_elf_reloc(Section
*symtab
, Section
*s
, unsigned long offset
,
707 int type
, int symbol
);
708 static void put_stabs(const char *str
, int type
, int other
, int desc
,
709 unsigned long value
);
710 static void put_stabs_r(const char *str
, int type
, int other
, int desc
,
711 unsigned long value
, Section
*sec
, int sym_index
);
712 static void put_stabn(int type
, int other
, int desc
, int value
);
713 static void put_stabd(int type
, int other
, int desc
);
714 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
);
716 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
717 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
718 static int tcc_add_file_internal(TCCState
*s
, const char *filename
, int flags
);
722 #ifdef CONFIG_TCC_ASM
724 typedef struct ExprValue
{
729 #define MAX_ASM_OPERANDS 30
731 typedef struct ASMOperand
{
732 int id
; /* GCC 3 optionnal identifier (0 if number only supported */
734 char asm_str
[16]; /* computed asm string for operand */
735 SValue
*vt
; /* C value of the expression */
736 int ref_index
; /* if >= 0, gives reference to a output constraint */
737 int priority
; /* priority, used to assign registers */
738 int reg
; /* if >= 0, register number used for this operand */
741 static void asm_expr(TCCState
*s1
, ExprValue
*pe
);
742 static int asm_int_expr(TCCState
*s1
);
743 static int find_constraint(ASMOperand
*operands
, int nb_operands
,
744 const char *name
, const char **pp
);
746 static int tcc_assemble(TCCState
*s1
, int do_preprocess
);
750 static void asm_instr(void);
752 /* true if float/double/long double type */
753 static inline int is_float(int t
)
757 return bt
== VT_LDOUBLE
|| bt
== VT_DOUBLE
|| bt
== VT_FLOAT
;
760 #ifdef TCC_TARGET_I386
761 #include "i386-gen.c"
764 #ifdef CONFIG_TCC_STATIC
766 #define RTLD_LAZY 0x001
767 #define RTLD_NOW 0x002
768 #define RTLD_GLOBAL 0x100
769 #define RTLD_DEFAULT NULL
771 /* dummy function for profiling */
772 void *dlopen(const char *filename
, int flag
)
777 const char *dlerror(void)
782 typedef struct TCCSyms
{
787 #define TCCSYM(a) { #a, &a, },
789 /* add the symbol you want here if no dynamic linking is done */
790 static TCCSyms tcc_syms
[] = {
798 void *dlsym(void *handle
, const char *symbol
)
802 while (p
->str
!= NULL
) {
803 if (!strcmp(p
->str
, symbol
))
812 /********************************************************/
814 /* we use our own 'finite' function to avoid potential problems with
815 non standard math libs */
816 /* XXX: endianness dependant */
817 int ieee_finite(double d
)
820 return ((unsigned)((p
[1] | 0x800fffff) + 1)) >> 31;
823 /* copy a string and truncate it. */
824 static char *pstrcpy(char *buf
, int buf_size
, const char *s
)
831 q_end
= buf
+ buf_size
- 1;
843 /* strcat and truncate. */
844 static char *pstrcat(char *buf
, int buf_size
, const char *s
)
849 pstrcpy(buf
+ len
, buf_size
- len
, s
);
853 /* memory management */
859 static inline void tcc_free(void *ptr
)
862 mem_cur_size
-= malloc_usable_size(ptr
);
867 static void *tcc_malloc(unsigned long size
)
872 error("memory full");
874 mem_cur_size
+= malloc_usable_size(ptr
);
875 if (mem_cur_size
> mem_max_size
)
876 mem_max_size
= mem_cur_size
;
881 static void *tcc_mallocz(unsigned long size
)
884 ptr
= tcc_malloc(size
);
885 memset(ptr
, 0, size
);
889 static inline void *tcc_realloc(void *ptr
, unsigned long size
)
893 mem_cur_size
-= malloc_usable_size(ptr
);
895 ptr1
= realloc(ptr
, size
);
897 /* NOTE: count not correct if alloc error, but not critical */
898 mem_cur_size
+= malloc_usable_size(ptr1
);
899 if (mem_cur_size
> mem_max_size
)
900 mem_max_size
= mem_cur_size
;
905 static char *tcc_strdup(const char *str
)
908 ptr
= tcc_malloc(strlen(str
) + 1);
913 #define free(p) use_tcc_free(p)
914 #define malloc(s) use_tcc_malloc(s)
915 #define realloc(p, s) use_tcc_realloc(p, s)
917 static void dynarray_add(void ***ptab
, int *nb_ptr
, void *data
)
924 /* every power of two we double array size */
925 if ((nb
& (nb
- 1)) == 0) {
930 pp
= tcc_realloc(pp
, nb_alloc
* sizeof(void *));
932 error("memory full");
939 Section
*new_section(TCCState
*s1
, const char *name
, int sh_type
, int sh_flags
)
943 sec
= tcc_mallocz(sizeof(Section
));
944 pstrcpy(sec
->name
, sizeof(sec
->name
), name
);
945 sec
->sh_type
= sh_type
;
946 sec
->sh_flags
= sh_flags
;
953 sec
->sh_addralign
= 4;
956 sec
->sh_addralign
= 1;
959 sec
->sh_addralign
= 32; /* default conservative alignment */
963 /* only add section if not private */
964 if (!(sh_flags
& SHF_PRIVATE
)) {
965 sec
->sh_num
= s1
->nb_sections
;
966 dynarray_add((void ***)&s1
->sections
, &s1
->nb_sections
, sec
);
971 static void free_section(Section
*s
)
977 /* realloc section and set its content to zero */
978 static void section_realloc(Section
*sec
, unsigned long new_size
)
983 size
= sec
->data_allocated
;
986 while (size
< new_size
)
988 data
= tcc_realloc(sec
->data
, size
);
990 error("memory full");
991 memset(data
+ sec
->data_allocated
, 0, size
- sec
->data_allocated
);
993 sec
->data_allocated
= size
;
996 /* reserve at least 'size' bytes in section 'sec' from
998 static void *section_ptr_add(Section
*sec
, unsigned long size
)
1000 unsigned long offset
, offset1
;
1002 offset
= sec
->data_offset
;
1003 offset1
= offset
+ size
;
1004 if (offset1
> sec
->data_allocated
)
1005 section_realloc(sec
, offset1
);
1006 sec
->data_offset
= offset1
;
1007 return sec
->data
+ offset
;
1010 /* return a reference to a section, and create it if it does not
1012 Section
*find_section(TCCState
*s1
, const char *name
)
1016 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1017 sec
= s1
->sections
[i
];
1018 if (!strcmp(name
, sec
->name
))
1021 /* sections are created as PROGBITS */
1022 return new_section(s1
, name
, SHT_PROGBITS
, SHF_ALLOC
);
1025 /* update sym->c so that it points to an external symbol in section
1026 'section' with value 'value' */
1027 static void put_extern_sym(Sym
*sym
, Section
*section
,
1028 unsigned long value
, unsigned long size
)
1030 int sym_type
, sym_bind
, sh_num
, info
;
1035 sh_num
= section
->sh_num
;
1039 if ((sym
->type
.t
& VT_BTYPE
) == VT_FUNC
)
1040 sym_type
= STT_FUNC
;
1042 sym_type
= STT_OBJECT
;
1043 if (sym
->type
.t
& VT_STATIC
)
1044 sym_bind
= STB_LOCAL
;
1046 sym_bind
= STB_GLOBAL
;
1048 name
= get_tok_str(sym
->v
, NULL
);
1049 #ifdef CONFIG_TCC_BCHECK
1050 if (do_bounds_check
) {
1053 /* XXX: avoid doing that for statics ? */
1054 /* if bound checking is activated, we change some function
1055 names by adding the "__bound" prefix */
1058 /* XXX: we rely only on malloc hooks */
1070 strcpy(buf
, "__bound_");
1077 info
= ELF32_ST_INFO(sym_bind
, sym_type
);
1078 sym
->c
= add_elf_sym(symtab_section
, value
, size
, info
, sh_num
, name
);
1080 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
1081 esym
->st_value
= value
;
1082 esym
->st_size
= size
;
1083 esym
->st_shndx
= sh_num
;
1087 /* add a new relocation entry to symbol 'sym' in section 's' */
1088 static void greloc(Section
*s
, Sym
*sym
, unsigned long offset
, int type
)
1091 put_extern_sym(sym
, NULL
, 0, 0);
1092 /* now we can add ELF relocation info */
1093 put_elf_reloc(symtab_section
, s
, offset
, type
, sym
->c
);
1096 static inline int isid(int c
)
1098 return (c
>= 'a' && c
<= 'z') ||
1099 (c
>= 'A' && c
<= 'Z') ||
1103 static inline int isnum(int c
)
1105 return c
>= '0' && c
<= '9';
1108 static inline int isoct(int c
)
1110 return c
>= '0' && c
<= '7';
1113 static inline int toup(int c
)
1115 if (c
>= 'a' && c
<= 'z')
1116 return c
- 'a' + 'A';
1121 static void strcat_vprintf(char *buf
, int buf_size
, const char *fmt
, va_list ap
)
1125 vsnprintf(buf
+ len
, buf_size
- len
, fmt
, ap
);
1128 static void strcat_printf(char *buf
, int buf_size
, const char *fmt
, ...)
1132 strcat_vprintf(buf
, buf_size
, fmt
, ap
);
1136 void error1(TCCState
*s1
, int is_warning
, const char *fmt
, va_list ap
)
1143 for(f
= s1
->include_stack
; f
< s1
->include_stack_ptr
; f
++)
1144 strcat_printf(buf
, sizeof(buf
), "In file included from %s:%d:\n",
1145 (*f
)->filename
, (*f
)->line_num
);
1146 if (file
->line_num
> 0) {
1147 strcat_printf(buf
, sizeof(buf
),
1148 "%s:%d: ", file
->filename
, file
->line_num
);
1150 strcat_printf(buf
, sizeof(buf
),
1151 "%s: ", file
->filename
);
1154 strcat_printf(buf
, sizeof(buf
),
1158 strcat_printf(buf
, sizeof(buf
), "warning: ");
1159 strcat_vprintf(buf
, sizeof(buf
), fmt
, ap
);
1161 if (!s1
->error_func
) {
1162 /* default case: stderr */
1163 fprintf(stderr
, "%s\n", buf
);
1165 s1
->error_func(s1
->error_opaque
, buf
);
1172 void tcc_set_error_func(TCCState
*s
, void *error_opaque
,
1173 void (*error_func
)(void *opaque
, const char *msg
))
1175 s
->error_opaque
= error_opaque
;
1176 s
->error_func
= error_func
;
1180 /* error without aborting current compilation */
1181 void error_noabort(const char *fmt
, ...)
1183 TCCState
*s1
= tcc_state
;
1187 error1(s1
, 0, fmt
, ap
);
1191 void error(const char *fmt
, ...)
1193 TCCState
*s1
= tcc_state
;
1197 error1(s1
, 0, fmt
, ap
);
1199 /* better than nothing: in some cases, we accept to handle errors */
1200 if (s1
->error_set_jmp_enabled
) {
1201 longjmp(s1
->error_jmp_buf
, 1);
1203 /* XXX: suppress it someday */
1208 void expect(const char *msg
)
1210 error("%s expected", msg
);
1213 void warning(const char *fmt
, ...)
1215 TCCState
*s1
= tcc_state
;
1219 error1(s1
, 1, fmt
, ap
);
1226 error("'%c' expected", c
);
1230 static void test_lvalue(void)
1232 if (!(vtop
->r
& VT_LVAL
))
1236 /* allocate a new token */
1237 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
1239 TokenSym
*ts
, **ptable
;
1242 if (tok_ident
>= SYM_FIRST_ANOM
)
1243 error("memory full");
1245 /* expand token table if needed */
1246 i
= tok_ident
- TOK_IDENT
;
1247 if ((i
% TOK_ALLOC_INCR
) == 0) {
1248 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
1250 error("memory full");
1251 table_ident
= ptable
;
1254 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
1255 table_ident
[i
] = ts
;
1256 ts
->tok
= tok_ident
++;
1257 ts
->sym_define
= NULL
;
1258 ts
->sym_label
= NULL
;
1259 ts
->sym_struct
= NULL
;
1260 ts
->sym_identifier
= NULL
;
1262 ts
->hash_next
= NULL
;
1263 memcpy(ts
->str
, str
, len
);
1264 ts
->str
[len
] = '\0';
1269 #define TOK_HASH_INIT 1
1270 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
1272 /* find a token and add it if not found */
1273 static TokenSym
*tok_alloc(const char *str
, int len
)
1275 TokenSym
*ts
, **pts
;
1281 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
1282 h
&= (TOK_HASH_SIZE
- 1);
1284 pts
= &hash_ident
[h
];
1289 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
1291 pts
= &(ts
->hash_next
);
1293 return tok_alloc_new(pts
, str
, len
);
1296 /* CString handling */
1298 static void cstr_realloc(CString
*cstr
, int new_size
)
1303 size
= cstr
->size_allocated
;
1305 size
= 8; /* no need to allocate a too small first string */
1306 while (size
< new_size
)
1308 data
= tcc_realloc(cstr
->data_allocated
, size
);
1310 error("memory full");
1311 cstr
->data_allocated
= data
;
1312 cstr
->size_allocated
= size
;
1317 static void cstr_ccat(CString
*cstr
, int ch
)
1320 size
= cstr
->size
+ 1;
1321 if (size
> cstr
->size_allocated
)
1322 cstr_realloc(cstr
, size
);
1323 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
1327 static void cstr_cat(CString
*cstr
, const char *str
)
1339 /* add a wide char */
1340 static void cstr_wccat(CString
*cstr
, int ch
)
1343 size
= cstr
->size
+ sizeof(int);
1344 if (size
> cstr
->size_allocated
)
1345 cstr_realloc(cstr
, size
);
1346 *(int *)(((unsigned char *)cstr
->data
) + size
- sizeof(int)) = ch
;
1350 static void cstr_new(CString
*cstr
)
1352 memset(cstr
, 0, sizeof(CString
));
1355 /* free string and reset it to NULL */
1356 static void cstr_free(CString
*cstr
)
1358 tcc_free(cstr
->data_allocated
);
1362 #define cstr_reset(cstr) cstr_free(cstr)
1364 static CString
*cstr_dup(CString
*cstr1
)
1369 cstr
= tcc_malloc(sizeof(CString
));
1372 cstr
->size_allocated
= size
;
1373 cstr
->data_allocated
= tcc_malloc(size
);
1374 cstr
->data
= cstr
->data_allocated
;
1375 memcpy(cstr
->data_allocated
, cstr1
->data_allocated
, size
);
1379 /* XXX: unicode ? */
1380 static void add_char(CString
*cstr
, int c
)
1382 if (c
== '\'' || c
== '\"' || c
== '\\') {
1383 /* XXX: could be more precise if char or string */
1384 cstr_ccat(cstr
, '\\');
1386 if (c
>= 32 && c
<= 126) {
1389 cstr_ccat(cstr
, '\\');
1391 cstr_ccat(cstr
, 'n');
1393 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
1394 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
1395 cstr_ccat(cstr
, '0' + (c
& 7));
1400 /* XXX: buffer overflow */
1401 /* XXX: float tokens */
1402 char *get_tok_str(int v
, CValue
*cv
)
1404 static char buf
[STRING_MAX_SIZE
+ 1];
1405 static CString cstr_buf
;
1411 /* NOTE: to go faster, we give a fixed buffer for small strings */
1412 cstr_reset(&cstr_buf
);
1413 cstr_buf
.data
= buf
;
1414 cstr_buf
.size_allocated
= sizeof(buf
);
1420 /* XXX: not quite exact, but only useful for testing */
1421 sprintf(p
, "%u", cv
->ui
);
1425 /* XXX: not quite exact, but only useful for testing */
1426 sprintf(p
, "%Lu", cv
->ull
);
1430 cstr_ccat(&cstr_buf
, '\'');
1431 add_char(&cstr_buf
, cv
->i
);
1432 cstr_ccat(&cstr_buf
, '\'');
1433 cstr_ccat(&cstr_buf
, '\0');
1437 len
= cstr
->size
- 1;
1439 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1440 cstr_ccat(&cstr_buf
, '\0');
1445 cstr_ccat(&cstr_buf
, '\"');
1447 len
= cstr
->size
- 1;
1449 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1451 len
= (cstr
->size
/ sizeof(int)) - 1;
1453 add_char(&cstr_buf
, ((int *)cstr
->data
)[i
]);
1455 cstr_ccat(&cstr_buf
, '\"');
1456 cstr_ccat(&cstr_buf
, '\0');
1465 return strcpy(p
, "<<=");
1467 return strcpy(p
, ">>=");
1469 if (v
< TOK_IDENT
) {
1470 /* search in two bytes table */
1484 } else if (v
< tok_ident
) {
1485 return table_ident
[v
- TOK_IDENT
]->str
;
1486 } else if (v
>= SYM_FIRST_ANOM
) {
1487 /* special name for anonymous symbol */
1488 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
1490 /* should never happen */
1495 return cstr_buf
.data
;
1498 /* push, without hashing */
1499 static Sym
*sym_push2(Sym
**ps
, int v
, int t
, int c
)
1502 s
= tcc_malloc(sizeof(Sym
));
1513 /* find a symbol and return its associated structure. 's' is the top
1514 of the symbol stack */
1515 static Sym
*sym_find2(Sym
*s
, int v
)
1525 /* structure lookup */
1526 static Sym
*struct_find(int v
)
1529 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1531 return table_ident
[v
]->sym_struct
;
1534 /* find an identifier */
1535 static inline Sym
*sym_find(int v
)
1538 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1540 return table_ident
[v
]->sym_identifier
;
1543 /* push a given symbol on the symbol stack */
1544 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
)
1553 s
= sym_push2(ps
, v
, type
->t
, c
);
1554 s
->type
.ref
= type
->ref
;
1556 /* don't record fields or anonymous symbols */
1558 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1559 /* record symbol in token array */
1560 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1562 ps
= &ts
->sym_struct
;
1564 ps
= &ts
->sym_identifier
;
1571 /* push a global identifier */
1572 static Sym
*global_identifier_push(int v
, int t
, int c
)
1575 s
= sym_push2(&global_stack
, v
, t
, c
);
1576 /* don't record anonymous symbol */
1577 if (v
< SYM_FIRST_ANOM
) {
1578 ps
= &table_ident
[v
- TOK_IDENT
]->sym_identifier
;
1579 /* modify the top most local identifier, so that
1580 sym_identifier will point to 's' when popped */
1582 ps
= &(*ps
)->prev_tok
;
1589 /* pop symbols until top reaches 'b' */
1590 static void sym_pop(Sym
**ptop
, Sym
*b
)
1600 /* remove symbol in token array */
1602 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1603 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1605 ps
= &ts
->sym_struct
;
1607 ps
= &ts
->sym_identifier
;
1618 BufferedFile
*tcc_open(TCCState
*s1
, const char *filename
)
1623 fd
= open(filename
, O_RDONLY
);
1626 bf
= tcc_malloc(sizeof(BufferedFile
));
1632 bf
->buf_ptr
= bf
->buffer
;
1633 bf
->buf_end
= bf
->buffer
;
1634 bf
->buffer
[0] = CH_EOB
; /* put eob symbol */
1635 pstrcpy(bf
->filename
, sizeof(bf
->filename
), filename
);
1637 bf
->ifndef_macro
= 0;
1638 bf
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
1639 // printf("opening '%s'\n", filename);
1643 void tcc_close(BufferedFile
*bf
)
1645 total_lines
+= bf
->line_num
;
1650 /* fill input buffer and peek next char */
1651 static int tcc_peekc_slow(BufferedFile
*bf
)
1654 /* only tries to read if really end of buffer */
1655 if (bf
->buf_ptr
>= bf
->buf_end
) {
1657 #if defined(PARSE_DEBUG)
1662 len
= read(bf
->fd
, bf
->buffer
, len
);
1669 bf
->buf_ptr
= bf
->buffer
;
1670 bf
->buf_end
= bf
->buffer
+ len
;
1671 *bf
->buf_end
= CH_EOB
;
1673 if (bf
->buf_ptr
< bf
->buf_end
) {
1674 return bf
->buf_ptr
[0];
1676 bf
->buf_ptr
= bf
->buf_end
;
1681 /* return the current character, handling end of block if necessary
1683 static int handle_eob(void)
1685 return tcc_peekc_slow(file
);
1688 /* read next char from current input file and handle end of input buffer */
1689 static inline void inp(void)
1691 ch
= *(++(file
->buf_ptr
));
1692 /* end of buffer/file handling */
1697 /* handle '\[\r]\n' */
1698 static void handle_stray(void)
1700 while (ch
== '\\') {
1705 } else if (ch
== '\r') {
1713 error("stray '\\' in program");
1718 /* skip the stray and handle the \\n case. Output an error if
1719 incorrect char after the stray */
1720 static int handle_stray1(uint8_t *p
)
1724 if (p
>= file
->buf_end
) {
1741 /* handle the complicated stray case */
1742 #define PEEKC(c, p)\
1747 c = handle_stray1(p);\
1752 /* input with '\[\r]\n' handling. Note that this function cannot
1753 handle other characters after '\', so you cannot call it inside
1754 strings or comments */
1755 static void minp(void)
1763 static void parse_line_comment(void)
1765 /* single line C++ comments */
1766 /* XXX: accept '\\\n' ? */
1768 while (ch
!= '\n' && ch
!= CH_EOF
)
1772 static void parse_comment(void)
1781 /* fast skip loop */
1784 if (c
== '\n' || c
== '*' || c
== '\\')
1788 if (c
== '\n' || c
== '*' || c
== '\\')
1792 /* now we can handle all the cases */
1796 } else if (c
== '*') {
1802 } else if (c
== '/') {
1803 goto end_of_comment
;
1804 } else if (c
== '\\') {
1808 /* skip '\\n', but if '\' followed but another
1809 char, behave asif a stray was parsed */
1810 ch
= file
->buf_ptr
[0];
1811 while (ch
== '\\') {
1816 } else if (ch
== '\r') {
1834 /* stray, eob or eof */
1839 error("unexpected end of file in comment");
1840 } else if (c
== '\\') {
1853 /* space exlcuding newline */
1854 static inline int is_space(int ch
)
1856 return ch
== ' ' || ch
== '\t' || ch
== '\v' || ch
== '\f' || ch
== '\r';
1859 static inline void skip_spaces(void)
1861 while (is_space(ch
))
1865 /* skip block of text until #else, #elif or #endif. skip also pairs of
1867 void preprocess_skip(void)
1869 int a
, start_of_line
, sep
, c
;
1896 } else if (c
== '\\') {
1897 /* XXX: incorrect: should not give an error */
1898 ch
= file
->buf_ptr
[0];
1912 } else if (c
== '\\') {
1917 /* XXX: better error message */
1918 error("unterminated string");
1919 } else if (c
== '\\') {
1920 /* ignore next char */
1930 else if (c
!= CH_EOF
)
1933 } else if (c
== '\n') {
1949 } else if (ch
== '/') {
1950 parse_line_comment();
1957 if (start_of_line
) {
1962 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
1964 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
1966 else if (tok
== TOK_ENDIF
)
1980 /* ParseState handling */
1982 /* XXX: currently, no include file info is stored. Thus, we cannot display
1983 accurate messages if the function or data definition spans multiple
1986 /* save current parse state in 's' */
1987 void save_parse_state(ParseState
*s
)
1989 s
->line_num
= file
->line_num
;
1990 s
->macro_ptr
= macro_ptr
;
1995 /* restore parse state from 's' */
1996 void restore_parse_state(ParseState
*s
)
1998 file
->line_num
= s
->line_num
;
1999 macro_ptr
= s
->macro_ptr
;
2004 /* return the number of additionnal 'ints' necessary to store the
2006 static inline int tok_ext_size(int t
)
2025 return LDOUBLE_SIZE
/ 4;
2031 /* token string handling */
2033 static inline void tok_str_new(TokenString
*s
)
2037 s
->allocated_len
= 0;
2038 s
->last_line_num
= -1;
2041 static void tok_str_free(int *str
)
2050 /* NOTE: we test zero separately so that GCC can generate a
2051 table for the following switch */
2066 /* XXX: use a macro to be portable on 64 bit ? */
2067 cstr
= (CString
*)p
[1];
2078 p
+= 1 + (LDOUBLE_SIZE
/ 4);
2088 static int *tok_str_realloc(TokenString
*s
)
2092 len
= s
->allocated_len
+ TOK_STR_ALLOC_INCR
;
2093 str
= tcc_realloc(s
->str
, len
* sizeof(int));
2095 error("memory full");
2096 s
->allocated_len
= len
;
2101 static void tok_str_add(TokenString
*s
, int t
)
2107 if (len
>= s
->allocated_len
)
2108 str
= tok_str_realloc(s
);
2113 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
2120 /* allocate space for worst case */
2121 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
2122 str
= tok_str_realloc(s
);
2131 str
[len
++] = cv
->tab
[0];
2136 str
[len
++] = (int)cstr_dup(cv
->cstr
);
2141 str
[len
++] = cv
->tab
[0];
2142 str
[len
++] = cv
->tab
[1];
2145 #if LDOUBLE_SIZE == 12
2146 str
[len
++] = cv
->tab
[0];
2147 str
[len
++] = cv
->tab
[1];
2148 str
[len
++] = cv
->tab
[2];
2150 #error add long double size support
2159 /* add the current parse token in token string 's' */
2160 static void tok_str_add_tok(TokenString
*s
)
2164 /* save line number info */
2165 if (file
->line_num
!= s
->last_line_num
) {
2166 s
->last_line_num
= file
->line_num
;
2167 cval
.i
= s
->last_line_num
;
2168 tok_str_add2(s
, TOK_LINENUM
, &cval
);
2170 tok_str_add2(s
, tok
, &tokc
);
2173 #if LDOUBLE_SIZE == 12
2174 #define LDOUBLE_GET(p, cv) \
2179 #error add long double size support
2183 /* get a token from an integer array and increment pointer
2184 accordingly. we code it as a macro to avoid pointer aliasing. */
2185 #define TOK_GET(t, p, cv) \
2207 case TOK_CLDOUBLE: \
2208 LDOUBLE_GET(p, cv); \
2209 p += LDOUBLE_SIZE / 4; \
2216 /* defines handling */
2217 static inline void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
2221 s
= sym_push2(&define_stack
, v
, macro_type
, (int)str
);
2222 s
->next
= first_arg
;
2223 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
2226 /* undefined a define symbol. Its name is just set to zero */
2227 static void define_undef(Sym
*s
)
2231 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2232 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2236 static inline Sym
*define_find(int v
)
2239 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2241 return table_ident
[v
]->sym_define
;
2244 /* free define stack until top reaches 'b' */
2245 static void free_defines(Sym
*b
)
2253 /* do not free args or predefined defines */
2255 tok_str_free((int *)top
->c
);
2257 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2258 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2266 static Sym
*label_find(int v
)
2269 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2271 return table_ident
[v
]->sym_label
;
2274 static Sym
*label_push(Sym
**ptop
, int v
, int flags
)
2277 s
= sym_push2(ptop
, v
, 0, 0);
2279 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
2280 if (ptop
== &global_label_stack
) {
2281 /* modify the top most local identifier, so that
2282 sym_identifier will point to 's' when popped */
2284 ps
= &(*ps
)->prev_tok
;
2291 /* pop labels until element last is reached. Look if any labels are
2292 undefined. Define symbols if '&&label' was used. */
2293 static void label_pop(Sym
**ptop
, Sym
*slast
)
2296 for(s
= *ptop
; s
!= slast
; s
= s1
) {
2298 if (s
->r
== LABEL_DECLARED
) {
2299 warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
2300 } else if (s
->r
== LABEL_FORWARD
) {
2301 error("label '%s' used but not defined",
2302 get_tok_str(s
->v
, NULL
));
2305 /* define corresponding symbol. A size of
2307 put_extern_sym(s
, cur_text_section
, (long)s
->next
, 1);
2311 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
2317 /* eval an expression for #if/#elif */
2318 static int expr_preprocess(void)
2324 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2325 next(); /* do macro subst */
2326 if (tok
== TOK_DEFINED
) {
2331 c
= define_find(tok
) != 0;
2336 } else if (tok
>= TOK_IDENT
) {
2337 /* if undefined macro */
2341 tok_str_add_tok(&str
);
2343 tok_str_add(&str
, -1); /* simulate end of file */
2344 tok_str_add(&str
, 0);
2345 /* now evaluate C constant expression */
2346 macro_ptr
= str
.str
;
2350 tok_str_free(str
.str
);
2354 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
2355 static void tok_print(int *str
)
2361 TOK_GET(t
, str
, cval
);
2364 printf(" %s", get_tok_str(t
, &cval
));
2370 /* parse after #define */
2371 static void parse_define(void)
2373 Sym
*s
, *first
, **ps
;
2374 int v
, t
, varg
, is_vaargs
, c
;
2379 error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
2380 /* XXX: should check if same macro (ANSI) */
2383 /* '(' must be just after macro definition for MACRO_FUNC */
2384 c
= file
->buf_ptr
[0];
2386 c
= handle_stray1(file
->buf_ptr
);
2391 while (tok
!= ')') {
2395 if (varg
== TOK_DOTS
) {
2396 varg
= TOK___VA_ARGS__
;
2398 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
2402 if (varg
< TOK_IDENT
)
2403 error("badly punctuated parameter list");
2404 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
2415 /* EOF testing necessary for '-D' handling */
2416 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2417 tok_str_add2(&str
, tok
, &tokc
);
2420 tok_str_add(&str
, 0);
2422 printf("define %s %d: ", get_tok_str(v
, NULL
), t
);
2425 define_push(v
, t
, str
.str
, first
);
2428 /* XXX: use a token or a hash table to accelerate matching ? */
2429 static CachedInclude
*search_cached_include(TCCState
*s1
,
2430 int type
, const char *filename
)
2435 for(i
= 0;i
< s1
->nb_cached_includes
; i
++) {
2436 e
= s1
->cached_includes
[i
];
2437 if (e
->type
== type
&& !strcmp(e
->filename
, filename
))
2443 static inline void add_cached_include(TCCState
*s1
, int type
,
2444 const char *filename
, int ifndef_macro
)
2448 if (search_cached_include(s1
, type
, filename
))
2451 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
2453 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
2457 strcpy(e
->filename
, filename
);
2458 e
->ifndef_macro
= ifndef_macro
;
2459 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
2462 /* is_bof is true if first non space token at beginning of file */
2463 static void preprocess(int is_bof
)
2465 TCCState
*s1
= tcc_state
;
2466 int size
, i
, c
, n
, saved_parse_flags
;
2467 char buf
[1024], *q
, *p
;
2473 saved_parse_flags
= parse_flags
;
2474 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
|
2475 PARSE_FLAG_LINEFEED
;
2485 s
= define_find(tok
);
2486 /* undefine symbol by putting an invalid name */
2491 ch
= file
->buf_ptr
[0];
2492 /* XXX: incorrect if comments : use next_nomacro with a special mode */
2497 } else if (ch
== '\"') {
2500 /* XXX: better stray handling */
2503 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
2504 if ((q
- buf
) < sizeof(buf
) - 1)
2511 /* eat all spaces and comments after include */
2512 /* XXX: slightly incorrect */
2513 while (ch1
!= '\n' && ch1
!= CH_EOF
)
2517 /* computed #include : either we have only strings or
2518 we have anything enclosed in '<>' */
2521 if (tok
== TOK_STR
) {
2522 while (tok
!= TOK_LINEFEED
) {
2523 if (tok
!= TOK_STR
) {
2525 error("'#include' expects \"FILENAME\" or <FILENAME>");
2527 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
2533 while (tok
!= TOK_LINEFEED
) {
2534 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
2538 /* check syntax and remove '<>' */
2539 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
2540 goto include_syntax
;
2541 memmove(buf
, buf
+ 1, len
- 2);
2542 buf
[len
- 2] = '\0';
2547 e
= search_cached_include(s1
, c
, buf
);
2548 if (e
&& define_find(e
->ifndef_macro
)) {
2549 /* no need to parse the include because the 'ifndef macro'
2552 printf("%s: skipping %s\n", file
->filename
, buf
);
2556 /* first search in current dir if "header.h" */
2558 p
= strrchr(file
->filename
, '/');
2560 size
= p
+ 1 - file
->filename
;
2561 if (size
> sizeof(buf1
) - 1)
2562 size
= sizeof(buf1
) - 1;
2563 memcpy(buf1
, file
->filename
, size
);
2565 pstrcat(buf1
, sizeof(buf1
), buf
);
2566 f
= tcc_open(s1
, buf1
);
2570 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
2571 error("#include recursion too deep");
2572 /* now search in all the include paths */
2573 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
2574 for(i
= 0; i
< n
; i
++) {
2576 if (i
< s1
->nb_include_paths
)
2577 path
= s1
->include_paths
[i
];
2579 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
2580 pstrcpy(buf1
, sizeof(buf1
), path
);
2581 pstrcat(buf1
, sizeof(buf1
), "/");
2582 pstrcat(buf1
, sizeof(buf1
), buf
);
2583 f
= tcc_open(s1
, buf1
);
2587 error("include file '%s' not found", buf
);
2591 printf("%s: including %s\n", file
->filename
, buf1
);
2594 pstrcpy(f
->inc_filename
, sizeof(f
->inc_filename
), buf
);
2595 /* push current file in stack */
2596 /* XXX: fix current line init */
2597 *s1
->include_stack_ptr
++ = file
;
2599 /* add include file debug info */
2601 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
2603 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
2604 ch
= file
->buf_ptr
[0];
2612 c
= expr_preprocess();
2618 if (tok
< TOK_IDENT
)
2619 error("invalid argument for '#if%sdef'", c
? "n" : "");
2623 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
2625 file
->ifndef_macro
= tok
;
2628 c
= (define_find(tok
) != 0) ^ c
;
2630 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
2631 error("memory full");
2632 *s1
->ifdef_stack_ptr
++ = c
;
2635 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
2636 error("#else without matching #if");
2637 if (s1
->ifdef_stack_ptr
[-1] & 2)
2638 error("#else after #else");
2639 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
2642 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
2643 error("#elif without matching #if");
2644 c
= s1
->ifdef_stack_ptr
[-1];
2646 error("#elif after #else");
2647 /* last #if/#elif expression was true: we skip */
2650 c
= expr_preprocess();
2651 s1
->ifdef_stack_ptr
[-1] = c
;
2661 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
2662 error("#endif without matching #if");
2663 s1
->ifdef_stack_ptr
--;
2664 /* '#ifndef macro' was at the start of file. Now we check if
2665 an '#endif' is exactly at the end of file */
2666 if (file
->ifndef_macro
&&
2667 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
2668 file
->ifndef_macro_saved
= file
->ifndef_macro
;
2669 /* need to set to zero to avoid false matches if another
2670 #ifndef at middle of file */
2671 file
->ifndef_macro
= 0;
2672 while (tok
!= TOK_LINEFEED
)
2674 tok_flags
|= TOK_FLAG_ENDIF
;
2680 if (tok
!= TOK_CINT
)
2682 file
->line_num
= tokc
.i
- 1; /* the line number will be incremented after */
2684 if (tok
!= TOK_LINEFEED
) {
2687 pstrcpy(file
->filename
, sizeof(file
->filename
),
2688 (char *)tokc
.cstr
->data
);
2694 ch
= file
->buf_ptr
[0];
2697 while (ch
!= '\n' && ch
!= CH_EOF
) {
2698 if ((q
- buf
) < sizeof(buf
) - 1)
2704 error("#error %s", buf
);
2706 warning("#warning %s", buf
);
2712 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_CINT
) {
2713 /* '!' is ignored to allow C scripts. numbers are ignored
2714 to emulate cpp behaviour */
2716 error("invalid preprocessing directive #%s", get_tok_str(tok
, &tokc
));
2720 /* ignore other preprocess commands or #! for C scripts */
2721 while (tok
!= TOK_LINEFEED
)
2724 parse_flags
= saved_parse_flags
;
2727 /* read a number in base b */
2728 static int getn(int b
)
2733 if (ch
>= 'a' && ch
<= 'f')
2735 else if (ch
>= 'A' && ch
<= 'F')
2741 if (t
< 0 || t
>= b
)
2749 /* read a character for string or char constant and eval escape codes */
2750 static int getq(void)
2759 case '0': case '1': case '2': case '3':
2760 case '4': case '5': case '6': case '7':
2761 /* at most three octal digits */
2765 c
= c
* 8 + ch
- '0';
2768 c
= c
* 8 + ch
- '0';
2799 goto invalid_escape
;
2814 goto invalid_escape
;
2819 error("invalid escaped char");
2822 } else if (c
== '\r' && ch
== '\n') {
2829 /* we use 64 bit numbers */
2832 /* bn = (bn << shift) | or_val */
2833 void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
2837 for(i
=0;i
<BN_SIZE
;i
++) {
2839 bn
[i
] = (v
<< shift
) | or_val
;
2840 or_val
= v
>> (32 - shift
);
2844 void bn_zero(unsigned int *bn
)
2847 for(i
=0;i
<BN_SIZE
;i
++) {
2852 /* parse number in null terminated string 'p' and return it in the
2854 void parse_number(const char *p
)
2856 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
2858 unsigned int bn
[BN_SIZE
];
2869 goto float_frac_parse
;
2870 } else if (t
== '0') {
2871 if (ch
== 'x' || ch
== 'X') {
2875 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
2881 /* parse all digits. cannot check octal numbers at this stage
2882 because of floating point constants */
2884 if (ch
>= 'a' && ch
<= 'f')
2886 else if (ch
>= 'A' && ch
<= 'F')
2894 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
2896 error("number too long");
2902 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
2903 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
2905 /* NOTE: strtox should support that for hexa numbers, but
2906 non ISOC99 libcs do not support it, so we prefer to do
2908 /* hexadecimal or binary floats */
2909 /* XXX: handle overflows */
2921 } else if (t
>= 'a') {
2923 } else if (t
>= 'A') {
2928 bn_lshift(bn
, shift
, t
);
2935 if (t
>= 'a' && t
<= 'f') {
2937 } else if (t
>= 'A' && t
<= 'F') {
2939 } else if (t
>= '0' && t
<= '9') {
2945 error("invalid digit");
2946 bn_lshift(bn
, shift
, t
);
2951 if (ch
!= 'p' && ch
!= 'P')
2958 } else if (ch
== '-') {
2962 if (ch
< '0' || ch
> '9')
2963 expect("exponent digits");
2964 while (ch
>= '0' && ch
<= '9') {
2965 exp_val
= exp_val
* 10 + ch
- '0';
2968 exp_val
= exp_val
* s
;
2970 /* now we can generate the number */
2971 /* XXX: should patch directly float number */
2972 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
2973 d
= ldexp(d
, exp_val
- frac_bits
);
2978 /* float : should handle overflow */
2980 } else if (t
== 'L') {
2983 /* XXX: not large enough */
2984 tokc
.ld
= (long double)d
;
2990 /* decimal floats */
2992 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2997 while (ch
>= '0' && ch
<= '9') {
2998 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3004 if (ch
== 'e' || ch
== 'E') {
3005 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3009 if (ch
== '-' || ch
== '+') {
3010 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3015 if (ch
< '0' || ch
> '9')
3016 expect("exponent digits");
3017 while (ch
>= '0' && ch
<= '9') {
3018 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3030 tokc
.f
= strtof(token_buf
, NULL
);
3031 } else if (t
== 'L') {
3034 tokc
.ld
= strtold(token_buf
, NULL
);
3037 tokc
.d
= strtod(token_buf
, NULL
);
3041 unsigned long long n
, n1
;
3044 /* integer number */
3047 if (b
== 10 && *q
== '0') {
3054 /* no need for checks except for base 10 / 8 errors */
3057 } else if (t
>= 'a') {
3059 } else if (t
>= 'A') {
3064 error("invalid digit");
3068 /* detect overflow */
3069 /* XXX: this test is not reliable */
3071 error("integer constant overflow");
3074 /* XXX: not exactly ANSI compliant */
3075 if ((n
& 0xffffffff00000000LL
) != 0) {
3080 } else if (n
> 0x7fffffff) {
3091 error("three 'l's in integer constant");
3094 if (tok
== TOK_CINT
)
3096 else if (tok
== TOK_CUINT
)
3100 } else if (t
== 'U') {
3102 error("two 'u's in integer constant");
3104 if (tok
== TOK_CINT
)
3106 else if (tok
== TOK_CLLONG
)
3113 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
3121 #define PARSE2(c1, tok1, c2, tok2) \
3132 /* return next token without macro substitution */
3133 static inline void next_nomacro1(void)
3153 /* first look if it is in fact an end of buffer */
3154 if (p
>= file
->buf_end
) {
3158 if (p
>= file
->buf_end
)
3171 TCCState
*s1
= tcc_state
;
3172 if (parse_flags
& PARSE_FLAG_LINEFEED
) {
3174 } else if (s1
->include_stack_ptr
== s1
->include_stack
||
3175 !(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3176 /* no include left : end of file. */
3179 /* pop include file */
3181 /* test if previous '#endif' was after a #ifdef at
3183 if (tok_flags
& TOK_FLAG_ENDIF
) {
3185 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
3187 add_cached_include(s1
, file
->inc_type
, file
->inc_filename
,
3188 file
->ifndef_macro_saved
);
3191 /* add end of include file debug info */
3193 put_stabd(N_EINCL
, 0, 0);
3195 /* pop include stack */
3197 s1
->include_stack_ptr
--;
3198 file
= *s1
->include_stack_ptr
;
3206 if (parse_flags
& PARSE_FLAG_LINEFEED
) {
3210 tok_flags
|= TOK_FLAG_BOL
;
3219 if ((tok_flags
& TOK_FLAG_BOL
) &&
3220 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3222 preprocess(tok_flags
& TOK_FLAG_BOF
);
3228 tok
= TOK_TWOSHARPS
;
3235 case 'a': case 'b': case 'c': case 'd':
3236 case 'e': case 'f': case 'g': case 'h':
3237 case 'i': case 'j': case 'k': case 'l':
3238 case 'm': case 'n': case 'o': case 'p':
3239 case 'q': case 'r': case 's': case 't':
3240 case 'u': case 'v': case 'w': case 'x':
3242 case 'A': case 'B': case 'C': case 'D':
3243 case 'E': case 'F': case 'G': case 'H':
3244 case 'I': case 'J': case 'K':
3245 case 'M': case 'N': case 'O': case 'P':
3246 case 'Q': case 'R': case 'S': case 'T':
3247 case 'U': case 'V': case 'W': case 'X':
3253 h
= TOK_HASH_FUNC(h
, c
);
3257 if (!isidnum_table
[c
])
3259 h
= TOK_HASH_FUNC(h
, c
);
3266 /* fast case : no stray found, so we have the full token
3267 and we have already hashed it */
3269 h
&= (TOK_HASH_SIZE
- 1);
3270 pts
= &hash_ident
[h
];
3275 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
3277 pts
= &(ts
->hash_next
);
3279 ts
= tok_alloc_new(pts
, p1
, len
);
3283 cstr_reset(&tokcstr
);
3286 cstr_ccat(&tokcstr
, *p1
);
3292 while (isidnum_table
[c
]) {
3293 cstr_ccat(&tokcstr
, c
);
3296 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
3302 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
3304 goto parse_ident_fast
;
3310 } else if (c
== '\"') {
3314 cstr_reset(&tokcstr
);
3315 cstr_ccat(&tokcstr
, 'L');
3316 goto parse_ident_slow
;
3320 case '0': case '1': case '2': case '3':
3321 case '4': case '5': case '6': case '7':
3324 cstr_reset(&tokcstr
);
3325 /* after the first digit, accept digits, alpha, '.' or sign if
3326 prefixed by 'eEpP' */
3330 cstr_ccat(&tokcstr
, c
);
3332 if (!(isnum(c
) || isid(c
) || c
== '.' ||
3333 ((c
== '+' || c
== '-') &&
3334 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
3337 /* We add a trailing '\0' to ease parsing */
3338 cstr_ccat(&tokcstr
, '\0');
3339 tokc
.cstr
= &tokcstr
;
3343 /* special dot handling because it can also start a number */
3346 cstr_reset(&tokcstr
);
3347 cstr_ccat(&tokcstr
, '.');
3349 } else if (c
== '.') {
3365 /* this cast is needed if >= 128 */
3366 if (tok
== TOK_CCHAR
)
3370 error("unterminated character constant");
3379 cstr_reset(&tokcstr
);
3380 while (ch
!= '\"') {
3383 error("unterminated string");
3385 cstr_ccat(&tokcstr
, b
);
3387 cstr_wccat(&tokcstr
, b
);
3390 cstr_ccat(&tokcstr
, '\0');
3392 cstr_wccat(&tokcstr
, '\0');
3393 tokc
.cstr
= &tokcstr
;
3403 } else if (c
== '<') {
3421 } else if (c
== '>') {
3439 } else if (c
== '=') {
3452 } else if (c
== '=') {
3465 } else if (c
== '=') {
3478 } else if (c
== '=') {
3481 } else if (c
== '>') {
3489 PARSE2('!', '!', '=', TOK_NE
)
3490 PARSE2('=', '=', '=', TOK_EQ
)
3491 PARSE2('*', '*', '=', TOK_A_MUL
)
3492 PARSE2('%', '%', '=', TOK_A_MOD
)
3493 PARSE2('^', '^', '=', TOK_A_XOR
)
3495 /* comments or operator */
3503 } else if (c
== '/') {
3505 parse_line_comment();
3508 } else if (c
== '=') {
3528 case '$': /* only used in assembler */
3533 error("unrecognized character \\x%02x", c
);
3538 #if defined(PARSE_DEBUG)
3539 printf("token = %s\n", get_tok_str(tok
, &tokc
));
3543 /* return next token without macro substitution. Can read input from
3545 static void next_nomacro(void)
3551 TOK_GET(tok
, macro_ptr
, tokc
);
3552 if (tok
== TOK_LINENUM
) {
3553 file
->line_num
= tokc
.i
;
3562 /* substitute args in macro_str and return allocated string */
3563 static int *macro_arg_subst(Sym
**nested_list
, int *macro_str
, Sym
*args
)
3565 int *st
, last_tok
, t
, notfirst
;
3574 TOK_GET(t
, macro_str
, cval
);
3579 TOK_GET(t
, macro_str
, cval
);
3582 s
= sym_find2(args
, t
);
3589 cstr_ccat(&cstr
, ' ');
3590 TOK_GET(t
, st
, cval
);
3591 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
3594 cstr_ccat(&cstr
, '\0');
3596 printf("stringize: %s\n", (char *)cstr
.data
);
3600 tok_str_add2(&str
, TOK_STR
, &cval
);
3603 tok_str_add2(&str
, t
, &cval
);
3605 } else if (t
>= TOK_IDENT
) {
3606 s
= sym_find2(args
, t
);
3609 /* if '##' is present before or after, no arg substitution */
3610 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
3611 /* special case for var arg macros : ## eats the
3612 ',' if empty VA_ARGS variable. */
3613 /* XXX: test of the ',' is not 100%
3614 reliable. should fix it to avoid security
3616 if (gnu_ext
&& s
->type
.t
&&
3617 last_tok
== TOK_TWOSHARPS
&&
3618 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
3620 /* suppress ',' '##' */
3623 /* suppress '##' and add variable */
3631 TOK_GET(t1
, st
, cval
);
3634 tok_str_add2(&str
, t1
, &cval
);
3638 macro_subst(&str
, nested_list
, st
);
3641 tok_str_add(&str
, t
);
3644 tok_str_add2(&str
, t
, &cval
);
3648 tok_str_add(&str
, 0);
3652 /* do macro substitution of current token with macro 's' and add
3653 result to (tok_str,tok_len). 'nested_list' is the list of all
3654 macros we got inside to avoid recursing. Return non zero if no
3655 substitution needs to be done */
3656 static int macro_subst_tok(TokenString
*tok_str
,
3657 Sym
**nested_list
, Sym
*s
)
3659 Sym
*args
, *sa
, *sa1
;
3660 int mstr_allocated
, parlevel
, *mstr
, t
;
3666 /* if symbol is a macro, prepare substitution */
3668 /* special macros */
3669 if (tok
== TOK___LINE__
) {
3670 cval
.i
= file
->line_num
;
3671 tok_str_add2(tok_str
, TOK_CINT
, &cval
);
3672 } else if (tok
== TOK___FILE__
) {
3673 cstrval
= file
->filename
;
3675 tok_str_add2(tok_str
, TOK_STR
, &cval
);
3676 } else if (tok
== TOK___DATE__
) {
3677 cstrval
= "Jan 1 2002";
3679 } else if (tok
== TOK___TIME__
) {
3680 cstrval
= "00:00:00";
3683 cstr_cat(&cstr
, cstrval
);
3684 cstr_ccat(&cstr
, '\0');
3686 tok_str_add2(tok_str
, TOK_STR
, &cval
);
3691 if (s
->type
.t
== MACRO_FUNC
) {
3692 /* NOTE: we do not use next_nomacro to avoid eating the
3693 next token. XXX: find better solution */
3697 /* XXX: incorrect with comments */
3698 ch
= file
->buf_ptr
[0];
3699 while (is_space(ch
) || ch
== '\n')
3703 if (t
!= '(') /* no macro subst */
3706 /* argument macro */
3711 /* NOTE: empty args are allowed, except if no args */
3713 /* handle '()' case */
3714 if (!args
&& tok
== ')')
3717 error("macro '%s' used with too many args",
3718 get_tok_str(s
->v
, 0));
3721 /* NOTE: non zero sa->t indicates VA_ARGS */
3722 while ((parlevel
> 0 ||
3724 (tok
!= ',' || sa
->type
.t
))) &&
3728 else if (tok
== ')')
3730 tok_str_add2(&str
, tok
, &tokc
);
3733 tok_str_add(&str
, 0);
3734 sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, (int)str
.str
);
3737 /* special case for gcc var args: add an empty
3738 var arg argument if it is omitted */
3739 if (sa
&& sa
->type
.t
&& gnu_ext
)
3749 error("macro '%s' used with too few args",
3750 get_tok_str(s
->v
, 0));
3753 /* now subst each arg */
3754 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3759 tok_str_free((int *)sa
->c
);
3765 sym_push2(nested_list
, s
->v
, 0, 0);
3766 macro_subst(tok_str
, nested_list
, mstr
);
3767 /* pop nested defined symbol */
3769 *nested_list
= sa1
->prev
;
3777 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3778 return the resulting string (which must be freed). */
3779 static inline int *macro_twosharps(const int *macro_str
)
3782 const int *macro_ptr1
, *start_macro_ptr
, *ptr
, *saved_macro_ptr
;
3784 const char *p1
, *p2
;
3786 TokenString macro_str1
;
3789 start_macro_ptr
= macro_str
;
3790 /* we search the first '##' */
3792 macro_ptr1
= macro_str
;
3793 TOK_GET(t
, macro_str
, cval
);
3794 /* nothing more to do if end of string */
3797 if (*macro_str
== TOK_TWOSHARPS
)
3801 /* we saw '##', so we need more processing to handle it */
3803 tok_str_new(¯o_str1
);
3807 /* add all tokens seen so far */
3808 for(ptr
= start_macro_ptr
; ptr
< macro_ptr1
;) {
3809 TOK_GET(t
, ptr
, cval
);
3810 tok_str_add2(¯o_str1
, t
, &cval
);
3812 saved_macro_ptr
= macro_ptr
;
3813 /* XXX: suppress the use of macro_ptr here */
3814 macro_ptr
= (int *)macro_str
;
3816 while (*macro_ptr
== TOK_TWOSHARPS
) {
3818 macro_ptr1
= macro_ptr
;
3821 TOK_GET(t
, macro_ptr
, cval
);
3822 /* We concatenate the two tokens if we have an
3823 identifier or a preprocessing number */
3825 p1
= get_tok_str(tok
, &tokc
);
3826 cstr_cat(&cstr
, p1
);
3827 p2
= get_tok_str(t
, &cval
);
3828 cstr_cat(&cstr
, p2
);
3829 cstr_ccat(&cstr
, '\0');
3831 if ((tok
>= TOK_IDENT
|| tok
== TOK_PPNUM
) &&
3832 (t
>= TOK_IDENT
|| t
== TOK_PPNUM
)) {
3833 if (tok
== TOK_PPNUM
) {
3834 /* if number, then create a number token */
3835 /* NOTE: no need to allocate because
3836 tok_str_add2() does it */
3839 /* if identifier, we must do a test to
3840 validate we have a correct identifier */
3841 if (t
== TOK_PPNUM
) {
3851 if (!isnum(c
) && !isid(c
))
3855 ts
= tok_alloc(cstr
.data
, strlen(cstr
.data
));
3856 tok
= ts
->tok
; /* modify current token */
3859 const char *str
= cstr
.data
;
3860 const unsigned char *q
;
3862 /* we look for a valid token */
3863 /* XXX: do more extensive checks */
3864 if (!strcmp(str
, ">>=")) {
3866 } else if (!strcmp(str
, "<<=")) {
3868 } else if (strlen(str
) == 2) {
3869 /* search in two bytes table */
3874 if (q
[0] == str
[0] && q
[1] == str
[1])
3881 /* NOTE: because get_tok_str use a static buffer,
3884 p1
= get_tok_str(tok
, &tokc
);
3885 cstr_cat(&cstr
, p1
);
3886 cstr_ccat(&cstr
, '\0');
3887 p2
= get_tok_str(t
, &cval
);
3888 warning("pasting \"%s\" and \"%s\" does not give a valid preprocessing token", cstr
.data
, p2
);
3889 /* cannot merge tokens: just add them separately */
3890 tok_str_add2(¯o_str1
, tok
, &tokc
);
3891 /* XXX: free associated memory ? */
3898 tok_str_add2(¯o_str1
, tok
, &tokc
);
3903 macro_ptr
= (int *)saved_macro_ptr
;
3905 tok_str_add(¯o_str1
, 0);
3906 return macro_str1
.str
;
3910 /* do macro substitution of macro_str and add result to
3911 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3912 inside to avoid recursing. */
3913 static void macro_subst(TokenString
*tok_str
,
3914 Sym
**nested_list
, const int *macro_str
)
3917 int *saved_macro_ptr
, *macro_str1
;
3922 /* first scan for '##' operator handling */
3924 macro_str1
= macro_twosharps(ptr
);
3928 TOK_GET(t
, ptr
, cval
);
3933 /* if nested substitution, do nothing */
3934 if (sym_find2(*nested_list
, t
))
3936 saved_macro_ptr
= macro_ptr
;
3937 macro_ptr
= (int *)ptr
;
3939 ret
= macro_subst_tok(tok_str
, nested_list
, s
);
3940 ptr
= (int *)macro_ptr
;
3941 macro_ptr
= saved_macro_ptr
;
3946 tok_str_add2(tok_str
, t
, &cval
);
3950 tok_str_free(macro_str1
);
3953 /* return next token with macro substitution */
3954 static void next(void)
3956 Sym
*nested_list
, *s
;
3962 /* if not reading from macro substituted string, then try
3963 to substitute macros */
3964 if (tok
>= TOK_IDENT
&&
3965 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3966 s
= define_find(tok
);
3968 /* we have a macro: we try to substitute */
3971 if (macro_subst_tok(&str
, &nested_list
, s
) == 0) {
3972 /* substitution done, NOTE: maybe empty */
3973 tok_str_add(&str
, 0);
3974 macro_ptr
= str
.str
;
3975 macro_ptr_allocated
= str
.str
;
3982 /* end of macro or end of unget buffer */
3983 if (unget_buffer_enabled
) {
3984 macro_ptr
= unget_saved_macro_ptr
;
3985 unget_buffer_enabled
= 0;
3987 /* end of macro string: free it */
3988 tok_str_free(macro_ptr_allocated
);
3995 /* convert preprocessor tokens into C tokens */
3996 if (tok
== TOK_PPNUM
&&
3997 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
3998 parse_number((char *)tokc
.cstr
->data
);
4002 /* push back current token and set current token to 'last_tok'. Only
4003 identifier case handled for labels. */
4004 static inline void unget_tok(int last_tok
)
4008 unget_saved_macro_ptr
= macro_ptr
;
4009 unget_buffer_enabled
= 1;
4010 q
= unget_saved_buffer
;
4013 n
= tok_ext_size(tok
) - 1;
4016 *q
= 0; /* end of token string */
4021 void swap(int *p
, int *q
)
4029 void vsetc(CType
*type
, int r
, CValue
*vc
)
4033 if (vtop
>= vstack
+ VSTACK_SIZE
)
4034 error("memory full");
4035 /* cannot let cpu flags if other instruction are generated. Also
4036 avoid leaving VT_JMP anywhere except on the top of the stack
4037 because it would complicate the code generator. */
4038 if (vtop
>= vstack
) {
4039 v
= vtop
->r
& VT_VALMASK
;
4040 if (v
== VT_CMP
|| (v
& ~1) == VT_JMP
)
4046 vtop
->r2
= VT_CONST
;
4050 /* push integer constant */
4055 vsetc(&int_type
, VT_CONST
, &cval
);
4058 /* Return a static symbol pointing to a section */
4059 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
4060 unsigned long offset
, unsigned long size
)
4066 sym
= global_identifier_push(v
, type
->t
| VT_STATIC
, 0);
4067 sym
->type
.ref
= type
->ref
;
4068 sym
->r
= VT_CONST
| VT_SYM
;
4069 put_extern_sym(sym
, sec
, offset
, size
);
4073 /* push a reference to a section offset by adding a dummy symbol */
4074 static void vpush_ref(CType
*type
, Section
*sec
, unsigned long offset
, unsigned long size
)
4079 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4080 vtop
->sym
= get_sym_ref(type
, sec
, offset
, size
);
4083 /* define a new external reference to a symbol 'v' of type 'u' */
4084 static Sym
*external_global_sym(int v
, CType
*type
, int r
)
4090 /* push forward reference */
4091 s
= global_identifier_push(v
, type
->t
| VT_EXTERN
, 0);
4092 s
->type
.ref
= type
->ref
;
4093 s
->r
= r
| VT_CONST
| VT_SYM
;
4098 /* define a new external reference to a symbol 'v' of type 'u' */
4099 static Sym
*external_sym(int v
, CType
*type
, int r
)
4105 /* push forward reference */
4106 s
= sym_push(v
, type
, r
| VT_CONST
| VT_SYM
, 0);
4107 s
->type
.t
|= VT_EXTERN
;
4109 if (!is_compatible_types(&s
->type
, type
))
4110 error("incompatible types for redefinition of '%s'",
4111 get_tok_str(v
, NULL
));
4116 /* push a reference to global symbol v */
4117 static void vpush_global_sym(CType
*type
, int v
)
4122 sym
= external_global_sym(v
, type
, 0);
4124 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4128 void vset(CType
*type
, int r
, int v
)
4133 vsetc(type
, r
, &cval
);
4136 void vseti(int r
, int v
)
4152 void vpushv(SValue
*v
)
4154 if (vtop
>= vstack
+ VSTACK_SIZE
)
4155 error("memory full");
4165 /* save r to the memory stack, and mark it as being free */
4166 void save_reg(int r
)
4168 int l
, saved
, size
, align
;
4172 /* modify all stack values */
4175 for(p
=vstack
;p
<=vtop
;p
++) {
4176 if ((p
->r
& VT_VALMASK
) == r
||
4177 (p
->r2
& VT_VALMASK
) == r
) {
4178 /* must save value on stack if not already done */
4180 /* NOTE: must reload 'r' because r might be equal to r2 */
4181 r
= p
->r
& VT_VALMASK
;
4182 /* store register in the stack */
4184 if ((p
->r
& VT_LVAL
) ||
4185 (!is_float(type
->t
) && (type
->t
& VT_BTYPE
) != VT_LLONG
))
4187 size
= type_size(type
, &align
);
4188 loc
= (loc
- size
) & -align
;
4189 sv
.type
.t
= type
->t
;
4190 sv
.r
= VT_LOCAL
| VT_LVAL
;
4193 #ifdef TCC_TARGET_I386
4194 /* x86 specific: need to pop fp register ST0 if saved */
4195 if (r
== TREG_ST0
) {
4196 o(0xd9dd); /* fstp %st(1) */
4199 /* special long long case */
4200 if ((type
->t
& VT_BTYPE
) == VT_LLONG
) {
4207 /* mark that stack entry as being saved on the stack */
4208 if (p
->r
& VT_LVAL
) {
4209 /* also suppress the bounded flag because the
4210 relocation address of the function was stored in
4212 p
->r
= (p
->r
& ~(VT_VALMASK
| VT_BOUNDED
)) | VT_LLOCAL
;
4214 p
->r
= lvalue_type(p
->type
.t
) | VT_LOCAL
;
4222 /* find a free register of class 'rc'. If none, save one register */
4228 /* find a free register */
4229 for(r
=0;r
<NB_REGS
;r
++) {
4230 if (reg_classes
[r
] & rc
) {
4231 for(p
=vstack
;p
<=vtop
;p
++) {
4232 if ((p
->r
& VT_VALMASK
) == r
||
4233 (p
->r2
& VT_VALMASK
) == r
)
4241 /* no register left : free the first one on the stack (VERY
4242 IMPORTANT to start from the bottom to ensure that we don't
4243 spill registers used in gen_opi()) */
4244 for(p
=vstack
;p
<=vtop
;p
++) {
4245 r
= p
->r
& VT_VALMASK
;
4246 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
))
4248 /* also look at second register (if long long) */
4249 r
= p
->r2
& VT_VALMASK
;
4250 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
)) {
4256 /* Should never comes here */
4260 /* save registers up to (vtop - n) stack entry */
4261 void save_regs(int n
)
4266 for(p
= vstack
;p
<= p1
; p
++) {
4267 r
= p
->r
& VT_VALMASK
;
4274 /* move register 's' to 'r', and flush previous value of r to memory
4276 void move_reg(int r
, int s
)
4289 /* get address of vtop (vtop MUST BE an lvalue) */
4292 vtop
->r
&= ~VT_LVAL
;
4293 /* tricky: if saved lvalue, then we can go back to lvalue */
4294 if ((vtop
->r
& VT_VALMASK
) == VT_LLOCAL
)
4295 vtop
->r
= (vtop
->r
& ~(VT_VALMASK
| VT_LVAL_TYPE
)) | VT_LOCAL
| VT_LVAL
;
4298 #ifdef CONFIG_TCC_BCHECK
4299 /* generate lvalue bound code */
4305 vtop
->r
&= ~VT_MUSTBOUND
;
4306 /* if lvalue, then use checking code before dereferencing */
4307 if (vtop
->r
& VT_LVAL
) {
4308 /* if not VT_BOUNDED value, then make one */
4309 if (!(vtop
->r
& VT_BOUNDED
)) {
4310 lval_type
= vtop
->r
& (VT_LVAL_TYPE
| VT_LVAL
);
4311 /* must save type because we must set it to int to get pointer */
4313 vtop
->type
.t
= VT_INT
;
4316 gen_bounded_ptr_add();
4317 vtop
->r
|= lval_type
;
4320 /* then check for dereferencing */
4321 gen_bounded_ptr_deref();
4326 /* store vtop a register belonging to class 'rc'. lvalues are
4327 converted to values. Cannot be used if cannot be converted to
4328 register value (such as structures). */
4331 int r
, r2
, rc2
, bit_pos
, bit_size
, size
, align
, i
;
4332 unsigned long long ll
;
4334 /* NOTE: get_reg can modify vstack[] */
4335 if (vtop
->type
.t
& VT_BITFIELD
) {
4336 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
4337 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
4338 /* remove bit field info to avoid loops */
4339 vtop
->type
.t
&= ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
4340 /* generate shifts */
4341 vpushi(32 - (bit_pos
+ bit_size
));
4343 vpushi(32 - bit_size
);
4344 /* NOTE: transformed to SHR if unsigned */
4348 if (is_float(vtop
->type
.t
) &&
4349 (vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4352 unsigned long offset
;
4354 /* XXX: unify with initializers handling ? */
4355 /* CPUs usually cannot use float constants, so we store them
4356 generically in data segment */
4357 size
= type_size(&vtop
->type
, &align
);
4358 offset
= (data_section
->data_offset
+ align
- 1) & -align
;
4359 data_section
->data_offset
= offset
;
4360 /* XXX: not portable yet */
4361 ptr
= section_ptr_add(data_section
, size
);
4364 ptr
[i
] = vtop
->c
.tab
[i
];
4365 sym
= get_sym_ref(&vtop
->type
, data_section
, offset
, size
<< 2);
4366 vtop
->r
|= VT_LVAL
| VT_SYM
;
4370 #ifdef CONFIG_TCC_BCHECK
4371 if (vtop
->r
& VT_MUSTBOUND
)
4375 r
= vtop
->r
& VT_VALMASK
;
4376 /* need to reload if:
4378 - lvalue (need to dereference pointer)
4379 - already a register, but not in the right class */
4380 if (r
>= VT_CONST
||
4381 (vtop
->r
& VT_LVAL
) ||
4382 !(reg_classes
[r
] & rc
) ||
4383 ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
&&
4384 !(reg_classes
[vtop
->r2
] & rc
))) {
4386 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
) {
4387 /* two register type load : expand to two words
4389 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4392 vtop
->c
.ui
= ll
; /* first word */
4394 vtop
->r
= r
; /* save register value */
4395 vpushi(ll
>> 32); /* second word */
4396 } else if (r
>= VT_CONST
||
4397 (vtop
->r
& VT_LVAL
)) {
4398 /* load from memory */
4401 vtop
[-1].r
= r
; /* save register value */
4402 /* increment pointer to get second word */
4403 vtop
->type
.t
= VT_INT
;
4409 /* move registers */
4412 vtop
[-1].r
= r
; /* save register value */
4413 vtop
->r
= vtop
[-1].r2
;
4415 /* allocate second register */
4422 /* write second register */
4424 } else if ((vtop
->r
& VT_LVAL
) && !is_float(vtop
->type
.t
)) {
4426 /* lvalue of scalar type : need to use lvalue type
4427 because of possible cast */
4430 /* compute memory access type */
4431 if (vtop
->r
& VT_LVAL_BYTE
)
4433 else if (vtop
->r
& VT_LVAL_SHORT
)
4435 if (vtop
->r
& VT_LVAL_UNSIGNED
)
4439 /* restore wanted type */
4442 /* one register type load */
4451 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
4452 void gv2(int rc1
, int rc2
)
4456 /* generate more generic register first. But VT_JMP or VT_CMP
4457 values must be generated first in all cases to avoid possible
4459 v
= vtop
[0].r
& VT_VALMASK
;
4460 if (v
!= VT_CMP
&& (v
& ~1) != VT_JMP
&& rc1
<= rc2
) {
4465 /* test if reload is needed for first register */
4466 if ((vtop
[-1].r
& VT_VALMASK
) >= VT_CONST
) {
4476 /* test if reload is needed for first register */
4477 if ((vtop
[0].r
& VT_VALMASK
) >= VT_CONST
) {
4483 /* expand long long on stack in two int registers */
4488 u
= vtop
->type
.t
& VT_UNSIGNED
;
4491 vtop
[0].r
= vtop
[-1].r2
;
4492 vtop
[0].r2
= VT_CONST
;
4493 vtop
[-1].r2
= VT_CONST
;
4494 vtop
[0].type
.t
= VT_INT
| u
;
4495 vtop
[-1].type
.t
= VT_INT
| u
;
4498 /* build a long long from two ints */
4501 gv2(RC_INT
, RC_INT
);
4502 vtop
[-1].r2
= vtop
[0].r
;
4503 vtop
[-1].type
.t
= t
;
4507 /* rotate n first stack elements to the bottom */
4514 for(i
=-n
+1;i
!=0;i
++)
4515 vtop
[i
] = vtop
[i
+1];
4519 /* pop stack value */
4523 v
= vtop
->r
& VT_VALMASK
;
4524 #ifdef TCC_TARGET_I386
4525 /* for x86, we need to pop the FP stack */
4526 if (v
== TREG_ST0
&& !nocode_wanted
) {
4527 o(0xd9dd); /* fstp %st(1) */
4530 if (v
== VT_JMP
|| v
== VT_JMPI
) {
4531 /* need to put correct jump if && or || without test */
4537 /* convert stack entry to register and duplicate its value in another
4545 if ((t
& VT_BTYPE
) == VT_LLONG
) {
4552 /* stack: H L L1 H1 */
4560 /* duplicate value */
4571 load(r1
, &sv
); /* move r to r1 */
4573 /* duplicates value */
4578 /* generate CPU independent (unsigned) long long operations */
4579 void gen_opl(int op
)
4581 int t
, a
, b
, op1
, c
, i
;
4589 func
= TOK___divdi3
;
4592 func
= TOK___udivdi3
;
4595 func
= TOK___moddi3
;
4598 func
= TOK___umoddi3
;
4600 /* call generic long long function */
4601 gfunc_start(&gf
, FUNC_CDECL
);
4604 vpush_global_sym(&func_old_type
, func
);
4608 vtop
->r2
= REG_LRET
;
4621 /* stack: L1 H1 L2 H2 */
4626 vtop
[-2] = vtop
[-3];
4629 /* stack: H1 H2 L1 L2 */
4635 /* stack: H1 H2 L1 L2 ML MH */
4638 /* stack: ML MH H1 H2 L1 L2 */
4642 /* stack: ML MH H1 L2 H2 L1 */
4647 /* stack: ML MH M1 M2 */
4650 } else if (op
== '+' || op
== '-') {
4651 /* XXX: add non carry method too (for MIPS or alpha) */
4657 /* stack: H1 H2 (L1 op L2) */
4660 gen_op(op1
+ 1); /* TOK_xxxC2 */
4663 /* stack: H1 H2 (L1 op L2) */
4666 /* stack: (L1 op L2) H1 H2 */
4668 /* stack: (L1 op L2) (H1 op H2) */
4676 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) {
4677 t
= vtop
[-1].type
.t
;
4681 /* stack: L H shift */
4683 /* constant: simpler */
4684 /* NOTE: all comments are for SHL. the other cases are
4685 done by swaping words */
4696 if (op
!= TOK_SAR
) {
4729 /* XXX: should provide a faster fallback on x86 ? */
4732 func
= TOK___sardi3
;
4735 func
= TOK___shrdi3
;
4738 func
= TOK___shldi3
;
4744 /* compare operations */
4750 /* stack: L1 H1 L2 H2 */
4752 vtop
[-1] = vtop
[-2];
4754 /* stack: L1 L2 H1 H2 */
4757 /* when values are equal, we need to compare low words. since
4758 the jump is inverted, we invert the test too. */
4761 else if (op1
== TOK_GT
)
4763 else if (op1
== TOK_ULT
)
4765 else if (op1
== TOK_UGT
)
4770 if (op1
!= TOK_NE
) {
4774 /* generate non equal test */
4775 /* XXX: NOT PORTABLE yet */
4779 #ifdef TCC_TARGET_I386
4780 b
= psym(0x850f, 0);
4782 error("not implemented");
4786 /* compare low. Always unsigned */
4790 else if (op1
== TOK_LE
)
4792 else if (op1
== TOK_GT
)
4794 else if (op1
== TOK_GE
)
4804 /* handle integer constant optimizations and various machine
4806 void gen_opic(int op
)
4813 /* currently, we cannot do computations with forward symbols */
4814 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
4815 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
4819 case '+': v1
->c
.i
+= fc
; break;
4820 case '-': v1
->c
.i
-= fc
; break;
4821 case '&': v1
->c
.i
&= fc
; break;
4822 case '^': v1
->c
.i
^= fc
; break;
4823 case '|': v1
->c
.i
|= fc
; break;
4824 case '*': v1
->c
.i
*= fc
; break;
4831 /* if division by zero, generate explicit division */
4834 error("division by zero in constant");
4838 default: v1
->c
.i
/= fc
; break;
4839 case '%': v1
->c
.i
%= fc
; break;
4840 case TOK_UDIV
: v1
->c
.i
= (unsigned)v1
->c
.i
/ fc
; break;
4841 case TOK_UMOD
: v1
->c
.i
= (unsigned)v1
->c
.i
% fc
; break;
4844 case TOK_SHL
: v1
->c
.i
<<= fc
; break;
4845 case TOK_SHR
: v1
->c
.i
= (unsigned)v1
->c
.i
>> fc
; break;
4846 case TOK_SAR
: v1
->c
.i
>>= fc
; break;
4848 case TOK_ULT
: v1
->c
.i
= (unsigned)v1
->c
.i
< (unsigned)fc
; break;
4849 case TOK_UGE
: v1
->c
.i
= (unsigned)v1
->c
.i
>= (unsigned)fc
; break;
4850 case TOK_EQ
: v1
->c
.i
= v1
->c
.i
== fc
; break;
4851 case TOK_NE
: v1
->c
.i
= v1
->c
.i
!= fc
; break;
4852 case TOK_ULE
: v1
->c
.i
= (unsigned)v1
->c
.i
<= (unsigned)fc
; break;
4853 case TOK_UGT
: v1
->c
.i
= (unsigned)v1
->c
.i
> (unsigned)fc
; break;
4854 case TOK_LT
: v1
->c
.i
= v1
->c
.i
< fc
; break;
4855 case TOK_GE
: v1
->c
.i
= v1
->c
.i
>= fc
; break;
4856 case TOK_LE
: v1
->c
.i
= v1
->c
.i
<= fc
; break;
4857 case TOK_GT
: v1
->c
.i
= v1
->c
.i
> fc
; break;
4859 case TOK_LAND
: v1
->c
.i
= v1
->c
.i
&& fc
; break;
4860 case TOK_LOR
: v1
->c
.i
= v1
->c
.i
|| fc
; break;
4866 /* if commutative ops, put c2 as constant */
4867 if (c1
&& (op
== '+' || op
== '&' || op
== '^' ||
4868 op
== '|' || op
== '*')) {
4873 if (c2
&& (((op
== '*' || op
== '/' || op
== TOK_UDIV
||
4876 ((op
== '+' || op
== '-' || op
== '|' || op
== '^' ||
4877 op
== TOK_SHL
|| op
== TOK_SHR
|| op
== TOK_SAR
) &&
4883 } else if (c2
&& (op
== '*' || op
== TOK_PDIV
|| op
== TOK_UDIV
)) {
4884 /* try to use shifts instead of muls or divs */
4885 if (fc
> 0 && (fc
& (fc
- 1)) == 0) {
4894 else if (op
== TOK_PDIV
)
4900 } else if (c2
&& (op
== '+' || op
== '-') &&
4901 (vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) ==
4902 (VT_CONST
| VT_SYM
)) {
4903 /* symbol + constant case */
4910 if (!nocode_wanted
) {
4911 /* call low level op generator */
4920 /* generate a floating point operation with constant propagation */
4921 void gen_opif(int op
)
4929 /* currently, we cannot do computations with forward symbols */
4930 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
4931 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
4933 if (v1
->type
.t
== VT_FLOAT
) {
4936 } else if (v1
->type
.t
== VT_DOUBLE
) {
4944 /* NOTE: we only do constant propagation if finite number (not
4945 NaN or infinity) (ANSI spec) */
4946 if (!ieee_finite(f1
) || !ieee_finite(f2
))
4950 case '+': f1
+= f2
; break;
4951 case '-': f1
-= f2
; break;
4952 case '*': f1
*= f2
; break;
4956 error("division by zero in constant");
4961 /* XXX: also handles tests ? */
4965 /* XXX: overflow test ? */
4966 if (v1
->type
.t
== VT_FLOAT
) {
4968 } else if (v1
->type
.t
== VT_DOUBLE
) {
4976 if (!nocode_wanted
) {
4984 static int pointed_size(CType
*type
)
4987 return type_size(pointed_type(type
), &align
);
4991 void check_pointer_types(SValue
*p1
, SValue
*p2
)
4993 char buf1
[256], buf2
[256];
4997 if (!is_compatible_types(t1
, t2
)) {
4998 type_to_str(buf1
, sizeof(buf1
), t1
, NULL
);
4999 type_to_str(buf2
, sizeof(buf2
), t2
, NULL
);
5000 error("incompatible pointers '%s' and '%s'", buf1
, buf2
);
5005 /* generic gen_op: handles types problems */
5008 int u
, t1
, t2
, bt1
, bt2
, t
;
5011 t1
= vtop
[-1].type
.t
;
5012 t2
= vtop
[0].type
.t
;
5013 bt1
= t1
& VT_BTYPE
;
5014 bt2
= t2
& VT_BTYPE
;
5016 if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
5017 /* at least one operand is a pointer */
5018 /* relationnal op: must be both pointers */
5019 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5020 // check_pointer_types(vtop, vtop - 1);
5021 /* pointers are handled are unsigned */
5022 t
= VT_INT
| VT_UNSIGNED
;
5025 /* if both pointers, then it must be the '-' op */
5026 if (bt1
== VT_PTR
&& bt2
== VT_PTR
) {
5028 error("cannot use pointers here");
5029 // check_pointer_types(vtop - 1, vtop);
5030 /* XXX: check that types are compatible */
5031 u
= pointed_size(&vtop
[-1].type
);
5033 /* set to integer type */
5034 vtop
->type
.t
= VT_INT
;
5038 /* exactly one pointer : must be '+' or '-'. */
5039 if (op
!= '-' && op
!= '+')
5040 error("cannot use pointers here");
5041 /* Put pointer as first operand */
5042 if (bt2
== VT_PTR
) {
5046 type1
= vtop
[-1].type
;
5047 /* XXX: cast to int ? (long long case) */
5048 vpushi(pointed_size(&vtop
[-1].type
));
5050 #ifdef CONFIG_TCC_BCHECK
5051 /* if evaluating constant expression, no code should be
5052 generated, so no bound check */
5053 if (do_bounds_check
&& !const_wanted
) {
5054 /* if bounded pointers, we generate a special code to
5061 gen_bounded_ptr_add();
5067 /* put again type if gen_opic() swaped operands */
5070 } else if (is_float(bt1
) || is_float(bt2
)) {
5071 /* compute bigger type and do implicit casts */
5072 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
5074 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
5079 /* floats can only be used for a few operations */
5080 if (op
!= '+' && op
!= '-' && op
!= '*' && op
!= '/' &&
5081 (op
< TOK_ULT
|| op
> TOK_GT
))
5082 error("invalid operands for binary operation");
5084 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
5085 /* cast to biggest op */
5087 /* convert to unsigned if it does not fit in a long long */
5088 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
5089 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
5093 /* integer operations */
5095 /* convert to unsigned if it does not fit in an integer */
5096 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
5097 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
5100 /* XXX: currently, some unsigned operations are explicit, so
5101 we modify them here */
5102 if (t
& VT_UNSIGNED
) {
5109 else if (op
== TOK_LT
)
5111 else if (op
== TOK_GT
)
5113 else if (op
== TOK_LE
)
5115 else if (op
== TOK_GE
)
5122 /* special case for shifts and long long: we keep the shift as
5124 if (op
== TOK_SHR
|| op
== TOK_SAR
|| op
== TOK_SHL
)
5129 else if ((t
& VT_BTYPE
) == VT_LLONG
)
5133 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5134 /* relationnal op: the result is an int */
5135 vtop
->type
.t
= VT_INT
;
5142 /* generic itof for unsigned long long case */
5143 void gen_cvt_itof1(int t
)
5147 if ((vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
)) ==
5148 (VT_LLONG
| VT_UNSIGNED
)) {
5150 gfunc_start(&gf
, FUNC_CDECL
);
5153 vpush_global_sym(&func_old_type
, TOK___ulltof
);
5154 else if (t
== VT_DOUBLE
)
5155 vpush_global_sym(&func_old_type
, TOK___ulltod
);
5157 vpush_global_sym(&func_old_type
, TOK___ulltold
);
5166 /* generic ftoi for unsigned long long case */
5167 void gen_cvt_ftoi1(int t
)
5172 if (t
== (VT_LLONG
| VT_UNSIGNED
)) {
5173 /* not handled natively */
5174 gfunc_start(&gf
, FUNC_CDECL
);
5175 st
= vtop
->type
.t
& VT_BTYPE
;
5178 vpush_global_sym(&func_old_type
, TOK___fixunssfdi
);
5179 else if (st
== VT_DOUBLE
)
5180 vpush_global_sym(&func_old_type
, TOK___fixunsdfdi
);
5182 vpush_global_sym(&func_old_type
, TOK___fixunsxfdi
);
5186 vtop
->r2
= REG_LRET
;
5192 /* force char or short cast */
5193 void force_charshort_cast(int t
)
5197 /* XXX: add optimization if lvalue : just change type and offset */
5202 if (t
& VT_UNSIGNED
) {
5203 vpushi((1 << bits
) - 1);
5214 /* cast 'vtop' to 'type' */
5215 static void gen_cast(CType
*type
)
5217 int sbt
, dbt
, sf
, df
, c
;
5219 /* special delayed cast for char/short */
5220 /* XXX: in some cases (multiple cascaded casts), it may still
5222 if (vtop
->r
& VT_MUSTCAST
) {
5223 vtop
->r
&= ~VT_MUSTCAST
;
5224 force_charshort_cast(vtop
->type
.t
);
5227 dbt
= type
->t
& (VT_BTYPE
| VT_UNSIGNED
);
5228 sbt
= vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
);
5230 if (sbt
!= dbt
&& !nocode_wanted
) {
5233 c
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5235 /* convert from fp to fp */
5237 /* constant case: we can do it now */
5238 /* XXX: in ISOC, cannot do it if error in convert */
5239 if (dbt
== VT_FLOAT
&& sbt
== VT_DOUBLE
)
5240 vtop
->c
.f
= (float)vtop
->c
.d
;
5241 else if (dbt
== VT_FLOAT
&& sbt
== VT_LDOUBLE
)
5242 vtop
->c
.f
= (float)vtop
->c
.ld
;
5243 else if (dbt
== VT_DOUBLE
&& sbt
== VT_FLOAT
)
5244 vtop
->c
.d
= (double)vtop
->c
.f
;
5245 else if (dbt
== VT_DOUBLE
&& sbt
== VT_LDOUBLE
)
5246 vtop
->c
.d
= (double)vtop
->c
.ld
;
5247 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_FLOAT
)
5248 vtop
->c
.ld
= (long double)vtop
->c
.f
;
5249 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_DOUBLE
)
5250 vtop
->c
.ld
= (long double)vtop
->c
.d
;
5252 /* non constant case: generate code */
5256 /* convert int to fp */
5259 case VT_LLONG
| VT_UNSIGNED
:
5261 /* XXX: add const cases for long long */
5263 case VT_INT
| VT_UNSIGNED
:
5265 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.ui
; break;
5266 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.ui
; break;
5267 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.ui
; break;
5272 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.i
; break;
5273 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.i
; break;
5274 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.i
; break;
5283 /* convert fp to int */
5284 /* we handle char/short/etc... with generic code */
5285 if (dbt
!= (VT_INT
| VT_UNSIGNED
) &&
5286 dbt
!= (VT_LLONG
| VT_UNSIGNED
) &&
5291 case VT_LLONG
| VT_UNSIGNED
:
5293 /* XXX: add const cases for long long */
5295 case VT_INT
| VT_UNSIGNED
:
5297 case VT_FLOAT
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5298 case VT_DOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5299 case VT_LDOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5305 case VT_FLOAT
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5306 case VT_DOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5307 case VT_LDOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5315 if (dbt
== VT_INT
&& (type
->t
& (VT_BTYPE
| VT_UNSIGNED
)) != dbt
) {
5316 /* additionnal cast for char/short/bool... */
5320 } else if ((dbt
& VT_BTYPE
) == VT_LLONG
) {
5321 if ((sbt
& VT_BTYPE
) != VT_LLONG
) {
5322 /* scalar to long long */
5324 if (sbt
== (VT_INT
| VT_UNSIGNED
))
5325 vtop
->c
.ll
= vtop
->c
.ui
;
5327 vtop
->c
.ll
= vtop
->c
.i
;
5329 /* machine independant conversion */
5331 /* generate high word */
5332 if (sbt
== (VT_INT
| VT_UNSIGNED
)) {
5340 /* patch second register */
5341 vtop
[-1].r2
= vtop
->r
;
5345 } else if (dbt
== VT_BOOL
) {
5346 /* scalar to bool */
5349 } else if ((dbt
& VT_BTYPE
) == VT_BYTE
||
5350 (dbt
& VT_BTYPE
) == VT_SHORT
) {
5351 force_charshort_cast(dbt
);
5352 } else if ((dbt
& VT_BTYPE
) == VT_INT
) {
5354 if (sbt
== VT_LLONG
) {
5355 /* from long long: just take low order word */
5359 /* if lvalue and single word type, nothing to do because
5360 the lvalue already contains the real type size (see
5361 VT_LVAL_xxx constants) */
5367 /* return type size. Put alignment at 'a' */
5368 static int type_size(CType
*type
, int *a
)
5373 bt
= type
->t
& VT_BTYPE
;
5374 if (bt
== VT_STRUCT
) {
5379 } else if (bt
== VT_PTR
) {
5380 if (type
->t
& VT_ARRAY
) {
5382 return type_size(&s
->type
, a
) * s
->c
;
5387 } else if (bt
== VT_LDOUBLE
) {
5389 return LDOUBLE_SIZE
;
5390 } else if (bt
== VT_DOUBLE
|| bt
== VT_LLONG
) {
5391 *a
= 4; /* XXX: i386 specific */
5393 } else if (bt
== VT_INT
|| bt
== VT_ENUM
|| bt
== VT_FLOAT
) {
5396 } else if (bt
== VT_SHORT
) {
5400 /* char, void, function, _Bool */
5406 /* return the pointed type of t */
5407 static inline CType
*pointed_type(CType
*type
)
5409 return &type
->ref
->type
;
5412 /* modify type so that its it is a pointer to type. */
5413 static void mk_pointer(CType
*type
)
5416 s
= sym_push(SYM_FIELD
, type
, 0, -1);
5417 type
->t
= VT_PTR
| (type
->t
& ~VT_TYPE
);
5421 static int is_compatible_types(CType
*type1
, CType
*type2
)
5424 int bt1
, bt2
, t1
, t2
;
5426 t1
= type1
->t
& VT_TYPE
;
5427 t2
= type2
->t
& VT_TYPE
;
5428 bt1
= t1
& VT_BTYPE
;
5429 bt2
= t2
& VT_BTYPE
;
5430 if (bt1
== VT_PTR
) {
5431 type1
= pointed_type(type1
);
5432 /* if function, then convert implicitely to function pointer */
5433 if (bt2
!= VT_FUNC
) {
5436 type2
= pointed_type(type2
);
5438 /* void matches everything */
5439 /* XXX: not fully compliant */
5440 if ((type1
->t
& VT_TYPE
) == VT_VOID
|| (type2
->t
& VT_TYPE
) == VT_VOID
)
5442 return is_compatible_types(type1
, type2
);
5443 } else if (bt1
== VT_STRUCT
|| bt2
== VT_STRUCT
) {
5444 return (type1
->ref
== type2
->ref
);
5445 } else if (bt1
== VT_FUNC
) {
5450 if (!is_compatible_types(&s1
->type
, &s2
->type
))
5452 /* XXX: not complete */
5453 if (s1
->c
== FUNC_OLD
|| s2
->c
== FUNC_OLD
)
5457 while (s1
!= NULL
) {
5460 if (!is_compatible_types(&s1
->type
, &s2
->type
))
5469 /* XXX: not complete */
5474 /* print a type. If 'varstr' is not NULL, then the variable is also
5475 printed in the type */
5477 /* XXX: add array and function pointers */
5478 void type_to_str(char *buf
, int buf_size
,
5479 CType
*type
, const char *varstr
)
5486 t
= type
->t
& VT_TYPE
;
5489 if (t
& VT_UNSIGNED
)
5490 pstrcat(buf
, buf_size
, "unsigned ");
5520 tstr
= "long double";
5522 pstrcat(buf
, buf_size
, tstr
);
5526 if (bt
== VT_STRUCT
)
5530 pstrcat(buf
, buf_size
, tstr
);
5531 v
= type
->ref
->v
& ~SYM_STRUCT
;
5532 if (v
>= SYM_FIRST_ANOM
)
5533 pstrcat(buf
, buf_size
, "<anonymous>");
5535 pstrcat(buf
, buf_size
, get_tok_str(v
, NULL
));
5539 type_to_str(buf
, buf_size
, &s
->type
, varstr
);
5540 pstrcat(buf
, buf_size
, "(");
5542 while (sa
!= NULL
) {
5543 type_to_str(buf1
, sizeof(buf1
), &sa
->type
, NULL
);
5544 pstrcat(buf
, buf_size
, buf1
);
5547 pstrcat(buf
, buf_size
, ", ");
5549 pstrcat(buf
, buf_size
, ")");
5553 pstrcpy(buf1
, sizeof(buf1
), "*");
5555 pstrcat(buf1
, sizeof(buf1
), varstr
);
5556 type_to_str(buf
, buf_size
, &s
->type
, buf1
);
5560 pstrcat(buf
, buf_size
, " ");
5561 pstrcat(buf
, buf_size
, varstr
);
5566 /* verify type compatibility to store vtop in 'dt' type, and generate
5568 static void gen_assign_cast(CType
*dt
)
5571 char buf1
[256], buf2
[256];
5574 st
= &vtop
->type
; /* source type */
5575 dbt
= dt
->t
& VT_BTYPE
;
5576 sbt
= st
->t
& VT_BTYPE
;
5577 if (dbt
== VT_PTR
) {
5578 /* special cases for pointers */
5579 /* a function is implicitely a function pointer */
5580 if (sbt
== VT_FUNC
) {
5581 if (!is_compatible_types(pointed_type(dt
), st
))
5586 /* '0' can also be a pointer */
5587 if (sbt
== VT_INT
&&
5588 ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) &&
5591 /* accept implicit pointer to integer cast with warning */
5592 if (sbt
== VT_BYTE
|| sbt
== VT_SHORT
||
5593 sbt
== VT_INT
|| sbt
== VT_LLONG
) {
5594 warning("assignment makes pointer from integer without a cast");
5597 } else if (dbt
== VT_BYTE
|| dbt
== VT_SHORT
||
5598 dbt
== VT_INT
|| dbt
== VT_LLONG
) {
5599 if (sbt
== VT_PTR
|| sbt
== VT_FUNC
) {
5600 warning("assignment makes integer from pointer without a cast");
5604 if (!is_compatible_types(dt
, st
)) {
5606 type_to_str(buf1
, sizeof(buf1
), st
, NULL
);
5607 type_to_str(buf2
, sizeof(buf2
), dt
, NULL
);
5608 error("cannot cast '%s' to '%s'", buf1
, buf2
);
5614 /* store vtop in lvalue pushed on stack */
5617 int sbt
, dbt
, ft
, r
, t
, size
, align
, bit_size
, bit_pos
, rc
, delayed_cast
;
5620 ft
= vtop
[-1].type
.t
;
5621 sbt
= vtop
->type
.t
& VT_BTYPE
;
5622 dbt
= ft
& VT_BTYPE
;
5623 if (((sbt
== VT_INT
|| sbt
== VT_SHORT
) && dbt
== VT_BYTE
) ||
5624 (sbt
== VT_INT
&& dbt
== VT_SHORT
)) {
5625 /* optimize char/short casts */
5626 delayed_cast
= VT_MUSTCAST
;
5627 vtop
->type
.t
= ft
& VT_TYPE
;
5630 gen_assign_cast(&vtop
[-1].type
);
5633 if (sbt
== VT_STRUCT
) {
5634 /* if structure, only generate pointer */
5635 /* structure assignment : generate memcpy */
5636 /* XXX: optimize if small size */
5637 if (!nocode_wanted
) {
5639 gfunc_start(&gf
, FUNC_CDECL
);
5641 size
= type_size(&vtop
->type
, &align
);
5645 vtop
->type
.t
= VT_INT
;
5650 vtop
->type
.t
= VT_INT
;
5655 vpush_global_sym(&func_old_type
, TOK_memcpy
);
5661 /* leave source on stack */
5662 } else if (ft
& VT_BITFIELD
) {
5663 /* bitfield store handling */
5664 bit_pos
= (ft
>> VT_STRUCT_SHIFT
) & 0x3f;
5665 bit_size
= (ft
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
5666 /* remove bit field info to avoid loops */
5667 vtop
[-1].type
.t
= ft
& ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
5669 /* duplicate destination */
5671 vtop
[-1] = vtop
[-2];
5673 /* mask and shift source */
5674 vpushi((1 << bit_size
) - 1);
5678 /* load destination, mask and or with source */
5680 vpushi(~(((1 << bit_size
) - 1) << bit_pos
));
5686 #ifdef CONFIG_TCC_BCHECK
5687 /* bound check case */
5688 if (vtop
[-1].r
& VT_MUSTBOUND
) {
5694 if (!nocode_wanted
) {
5698 r
= gv(rc
); /* generate value */
5699 /* if lvalue was saved on stack, must read it */
5700 if ((vtop
[-1].r
& VT_VALMASK
) == VT_LLOCAL
) {
5702 t
= get_reg(RC_INT
);
5704 sv
.r
= VT_LOCAL
| VT_LVAL
;
5705 sv
.c
.ul
= vtop
[-1].c
.ul
;
5707 vtop
[-1].r
= t
| VT_LVAL
;
5710 /* two word case handling : store second register at word + 4 */
5711 if ((ft
& VT_BTYPE
) == VT_LLONG
) {
5713 /* convert to int to increment easily */
5714 vtop
->type
.t
= VT_INT
;
5720 /* XXX: it works because r2 is spilled last ! */
5721 store(vtop
->r2
, vtop
- 1);
5725 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
5726 vtop
->r
|= delayed_cast
;
5730 /* post defines POST/PRE add. c is the token ++ or -- */
5731 void inc(int post
, int c
)
5734 vdup(); /* save lvalue */
5736 gv_dup(); /* duplicate value */
5741 vpushi(c
- TOK_MID
);
5743 vstore(); /* store value */
5745 vpop(); /* if post op, return saved value */
5748 /* Parse GNUC __attribute__ extension. Currently, the following
5749 extensions are recognized:
5750 - aligned(n) : set data/function alignment.
5751 - section(x) : generate data/code in this section.
5752 - unused : currently ignored, but may be used someday.
5754 static void parse_attribute(AttributeDef
*ad
)
5758 while (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
) {
5762 while (tok
!= ')') {
5763 if (tok
< TOK_IDENT
)
5764 expect("attribute name");
5772 expect("section name");
5773 ad
->section
= find_section(tcc_state
, (char *)tokc
.cstr
->data
);
5782 if (n
<= 0 || (n
& (n
- 1)) != 0)
5783 error("alignment must be a positive power of two");
5792 /* currently, no need to handle it because tcc does not
5793 track unused objects */
5797 /* currently, no need to handle it because tcc does not
5798 track unused objects */
5803 ad
->func_call
= FUNC_CDECL
;
5808 ad
->func_call
= FUNC_STDCALL
;
5811 // warning("'%s' attribute ignored", get_tok_str(t, NULL));
5812 /* skip parameters */
5813 /* XXX: skip parenthesis too */
5816 while (tok
!= ')' && tok
!= -1)
5831 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
5832 static void struct_decl(CType
*type
, int u
)
5834 int a
, v
, size
, align
, maxalign
, c
, offset
;
5835 int bit_size
, bit_pos
, bsize
, bt
, lbit_pos
;
5840 a
= tok
; /* save decl type */
5845 /* struct already defined ? return it */
5846 /* XXX: check consistency */
5850 error("invalid type");
5857 s
= sym_push(v
| SYM_STRUCT
, &type1
, 0, 0);
5858 /* put struct/union/enum name in type */
5866 error("struct/union/enum already defined");
5867 /* cannot be empty */
5869 /* non empty enums are not allowed */
5870 if (a
== TOK_ENUM
) {
5874 expect("identifier");
5880 /* enum symbols have static storage */
5881 ss
= sym_push(v
, &int_type
, VT_CONST
, c
);
5882 ss
->type
.t
|= VT_STATIC
;
5887 /* NOTE: we accept a trailing comma */
5897 while (tok
!= '}') {
5898 parse_btype(&btype
, &ad
);
5904 type_decl(&type1
, &ad
, &v
, TYPE_DIRECT
);
5905 if ((type1
.t
& VT_BTYPE
) == VT_FUNC
||
5906 (type1
.t
& (VT_TYPEDEF
| VT_STATIC
| VT_EXTERN
| VT_INLINE
)))
5907 error("invalid type for '%s'",
5908 get_tok_str(v
, NULL
));
5912 bit_size
= expr_const();
5913 /* XXX: handle v = 0 case for messages */
5915 error("negative width in bit-field '%s'",
5916 get_tok_str(v
, NULL
));
5917 if (v
&& bit_size
== 0)
5918 error("zero width for bit-field '%s'",
5919 get_tok_str(v
, NULL
));
5921 size
= type_size(&type1
, &align
);
5923 if (bit_size
>= 0) {
5924 bt
= type1
.t
& VT_BTYPE
;
5929 error("bitfields must have scalar type");
5931 if (bit_size
> bsize
) {
5932 error("width of '%s' exceeds its type",
5933 get_tok_str(v
, NULL
));
5934 } else if (bit_size
== bsize
) {
5935 /* no need for bit fields */
5937 } else if (bit_size
== 0) {
5938 /* XXX: what to do if only padding in a
5940 /* zero size: means to pad */
5944 /* we do not have enough room ? */
5945 if ((bit_pos
+ bit_size
) > bsize
)
5948 /* XXX: handle LSB first */
5949 type1
.t
|= VT_BITFIELD
|
5950 (bit_pos
<< VT_STRUCT_SHIFT
) |
5951 (bit_size
<< (VT_STRUCT_SHIFT
+ 6));
5952 bit_pos
+= bit_size
;
5958 /* add new memory data only if starting
5960 if (lbit_pos
== 0) {
5961 if (a
== TOK_STRUCT
) {
5962 c
= (c
+ align
- 1) & -align
;
5970 if (align
> maxalign
)
5974 printf("add field %s offset=%d",
5975 get_tok_str(v
, NULL
), offset
);
5976 if (type1
.t
& VT_BITFIELD
) {
5977 printf(" pos=%d size=%d",
5978 (type1
.t
>> VT_STRUCT_SHIFT
) & 0x3f,
5979 (type1
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f);
5983 ss
= sym_push(v
| SYM_FIELD
, &type1
, 0, offset
);
5987 if (tok
== ';' || tok
== TOK_EOF
)
5994 /* store size and alignment */
5995 s
->c
= (c
+ maxalign
- 1) & -maxalign
;
6001 /* return 0 if no type declaration. otherwise, return the basic type
6004 static int parse_btype(CType
*type
, AttributeDef
*ad
)
6006 int t
, u
, type_found
;
6010 memset(ad
, 0, sizeof(AttributeDef
));
6016 /* currently, we really ignore extension */
6026 if ((t
& VT_BTYPE
) != 0)
6027 error("too many basic types");
6041 if ((t
& VT_BTYPE
) == VT_DOUBLE
) {
6042 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6043 } else if ((t
& VT_BTYPE
) == VT_LONG
) {
6044 t
= (t
& ~VT_BTYPE
) | VT_LLONG
;
6058 if ((t
& VT_BTYPE
) == VT_LONG
) {
6059 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6066 struct_decl(&type1
, VT_ENUM
);
6069 type
->ref
= type1
.ref
;
6073 struct_decl(&type1
, VT_STRUCT
);
6076 /* type modifiers */
6118 /* GNUC attribute */
6119 case TOK_ATTRIBUTE1
:
6120 case TOK_ATTRIBUTE2
:
6121 parse_attribute(ad
);
6128 parse_expr_type(&type1
);
6132 if (!s
|| !(s
->type
.t
& VT_TYPEDEF
))
6134 t
|= (s
->type
.t
& ~VT_TYPEDEF
);
6135 type
->ref
= s
->type
.ref
;
6142 /* long is never used as type */
6143 if ((t
& VT_BTYPE
) == VT_LONG
)
6144 t
= (t
& ~VT_BTYPE
) | VT_INT
;
6149 static void post_type(CType
*type
, AttributeDef
*ad
)
6152 Sym
**plast
, *s
, *first
;
6157 /* function declaration */
6162 while (tok
!= ')') {
6163 /* read param name and compute offset */
6164 if (l
!= FUNC_OLD
) {
6165 if (!parse_btype(&pt
, &ad1
)) {
6167 error("invalid type");
6174 if ((pt
.t
& VT_BTYPE
) == VT_VOID
&& tok
== ')')
6176 type_decl(&pt
, &ad1
, &n
, TYPE_DIRECT
| TYPE_ABSTRACT
);
6177 if ((pt
.t
& VT_BTYPE
) == VT_VOID
)
6178 error("parameter declared as void");
6185 /* array must be transformed to pointer according to ANSI C */
6187 s
= sym_push(n
| SYM_FIELD
, &pt
, 0, 0);
6192 if (l
== FUNC_NEW
&& tok
== TOK_DOTS
) {
6199 /* if no parameters, then old type prototype */
6203 t1
= type
->t
& VT_STORAGE
;
6204 type
->t
&= ~VT_STORAGE
;
6205 post_type(type
, ad
);
6206 /* we push a anonymous symbol which will contain the function prototype */
6207 s
= sym_push(SYM_FIELD
, type
, ad
->func_call
, l
);
6209 type
->t
= t1
| VT_FUNC
;
6211 } else if (tok
== '[') {
6212 /* array definition */
6218 error("invalid array size");
6221 /* parse next post type */
6222 t1
= type
->t
& VT_STORAGE
;
6223 type
->t
&= ~VT_STORAGE
;
6224 post_type(type
, ad
);
6226 /* we push a anonymous symbol which will contain the array
6228 s
= sym_push(SYM_FIELD
, type
, 0, n
);
6229 type
->t
= t1
| VT_ARRAY
| VT_PTR
;
6234 /* Parse a type declaration (except basic type), and return the type
6235 in 'type'. 'td' is a bitmask indicating which kind of type decl is
6236 expected. 'type' should contain the basic type. 'ad' is the
6237 attribute definition of the basic type. It can be modified by
6240 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
)
6243 CType type1
, *type2
;
6245 while (tok
== '*') {
6264 /* XXX: clarify attribute handling */
6265 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6266 parse_attribute(ad
);
6268 /* recursive type */
6269 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
6270 type1
.t
= 0; /* XXX: same as int */
6273 /* XXX: this is not correct to modify 'ad' at this point, but
6274 the syntax is not clear */
6275 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6276 parse_attribute(ad
);
6277 type_decl(&type1
, ad
, v
, td
);
6280 /* type identifier */
6281 if (tok
>= TOK_IDENT
&& (td
& TYPE_DIRECT
)) {
6285 if (!(td
& TYPE_ABSTRACT
))
6286 expect("identifier");
6290 post_type(type
, ad
);
6291 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6292 parse_attribute(ad
);
6295 /* append type at the end of type1 */
6308 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
6309 static int lvalue_type(int t
)
6316 else if (bt
== VT_SHORT
)
6320 if (t
& VT_UNSIGNED
)
6321 r
|= VT_LVAL_UNSIGNED
;
6325 /* indirection with full error checking and bound check */
6326 static void indir(void)
6328 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
6330 if ((vtop
->r
& VT_LVAL
) && !nocode_wanted
)
6332 vtop
->type
= *pointed_type(&vtop
->type
);
6333 /* an array is never an lvalue */
6334 if (!(vtop
->type
.t
& VT_ARRAY
)) {
6335 vtop
->r
|= lvalue_type(vtop
->type
.t
);
6336 /* if bound checking, the referenced pointer must be checked */
6337 if (do_bounds_check
)
6338 vtop
->r
|= VT_MUSTBOUND
;
6342 /* pass a parameter to a function and do type checking and casting */
6343 void gfunc_param_typed(GFuncContext
*gf
, Sym
*func
, Sym
*arg
)
6348 func_type
= func
->c
;
6349 if (func_type
== FUNC_OLD
||
6350 (func_type
== FUNC_ELLIPSIS
&& arg
== NULL
)) {
6351 /* default casting : only need to convert float to double */
6352 if ((vtop
->type
.t
& VT_BTYPE
) == VT_FLOAT
) {
6356 } else if (arg
== NULL
) {
6357 error("too many arguments to function");
6359 gen_assign_cast(&arg
->type
);
6361 if (!nocode_wanted
) {
6368 /* parse an expression of the form '(type)' or '(expr)' and return its
6370 static void parse_expr_type(CType
*type
)
6376 if (parse_btype(type
, &ad
)) {
6377 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
6384 static void vpush_tokc(int t
)
6388 vsetc(&type
, VT_CONST
, &tokc
);
6391 static void unary(void)
6393 int n
, t
, align
, size
, r
;
6399 /* XXX: GCC 2.95.3 does not generate a table although it should be
6413 vpush_tokc(VT_INT
| VT_UNSIGNED
);
6417 vpush_tokc(VT_LLONG
);
6421 vpush_tokc(VT_LLONG
| VT_UNSIGNED
);
6425 vpush_tokc(VT_FLOAT
);
6429 vpush_tokc(VT_DOUBLE
);
6433 vpush_tokc(VT_LDOUBLE
);
6436 case TOK___FUNCTION__
:
6438 goto tok_identifier
;
6444 /* special function name identifier */
6445 len
= strlen(funcname
) + 1;
6446 /* generate char[len] type */
6451 vpush_ref(&type
, data_section
, data_section
->data_offset
, len
);
6452 ptr
= section_ptr_add(data_section
, len
);
6453 memcpy(ptr
, funcname
, len
);
6461 /* string parsing */
6467 memset(&ad
, 0, sizeof(AttributeDef
));
6468 decl_initializer_alloc(&type
, &ad
, VT_CONST
, 2, 0, 0);
6473 if (parse_btype(&type
, &ad
)) {
6474 type_decl(&type
, &ad
, &n
, TYPE_ABSTRACT
);
6476 /* check ISOC99 compound literal */
6478 /* data is allocated locally by default */
6483 /* all except arrays are lvalues */
6484 if (!(type
.t
& VT_ARRAY
))
6485 r
|= lvalue_type(type
.t
);
6486 memset(&ad
, 0, sizeof(AttributeDef
));
6487 decl_initializer_alloc(&type
, &ad
, r
, 1, 0, 0);
6492 } else if (tok
== '{') {
6493 /* save all registers */
6495 /* statement expression : we do not accept break/continue
6496 inside as GCC does */
6497 block(NULL
, NULL
, NULL
, NULL
, 0, 1);
6512 /* functions names must be treated as function pointers,
6513 except for unary '&' and sizeof. Since we consider that
6514 functions are not lvalues, we only have to handle it
6515 there and in function calls. */
6516 /* arrays can also be used although they are not lvalues */
6517 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
&&
6518 !(vtop
->type
.t
& VT_ARRAY
))
6520 mk_pointer(&vtop
->type
);
6526 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
)
6527 vtop
->c
.i
= !vtop
->c
.i
;
6528 else if ((vtop
->r
& VT_VALMASK
) == VT_CMP
)
6529 vtop
->c
.i
= vtop
->c
.i
^ 1;
6531 vseti(VT_JMP
, gtst(1, 0));
6541 /* in order to force cast, we add zero */
6543 if ((vtop
->type
.t
& VT_BTYPE
) == VT_PTR
)
6544 error("pointer not accepted for unary plus");
6554 parse_expr_type(&type
);
6558 size
= type_size(&type
, &align
);
6559 if (t
== TOK_SIZEOF
)
6580 goto tok_identifier
;
6582 /* allow to take the address of a label */
6583 if (tok
< TOK_UIDENT
)
6584 expect("label identifier");
6585 s
= label_find(tok
);
6587 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
6589 if (s
->r
== LABEL_DECLARED
)
6590 s
->r
= LABEL_FORWARD
;
6593 s
->type
.t
= VT_VOID
;
6594 mk_pointer(&s
->type
);
6595 s
->type
.t
|= VT_STATIC
;
6597 vset(&s
->type
, VT_CONST
| VT_SYM
, 0);
6606 expect("identifier");
6610 error("'%s' undeclared", get_tok_str(t
, NULL
));
6611 /* for simple function calls, we tolerate undeclared
6612 external reference to int() function */
6613 s
= external_global_sym(t
, &func_old_type
, 0);
6615 vset(&s
->type
, s
->r
, s
->c
);
6616 /* if forward reference, we must point to s */
6617 if (vtop
->r
& VT_SYM
) {
6624 /* post operations */
6626 if (tok
== TOK_INC
|| tok
== TOK_DEC
) {
6629 } else if (tok
== '.' || tok
== TOK_ARROW
) {
6631 if (tok
== TOK_ARROW
)
6636 /* expect pointer on structure */
6637 if ((vtop
->type
.t
& VT_BTYPE
) != VT_STRUCT
)
6638 expect("struct or union");
6642 while ((s
= s
->next
) != NULL
) {
6647 error("field not found");
6648 /* add field offset to pointer */
6649 vtop
->type
= char_pointer_type
; /* change type to 'char *' */
6652 /* change type to field type, and set to lvalue */
6653 vtop
->type
= s
->type
;
6654 /* an array is never an lvalue */
6655 if (!(vtop
->type
.t
& VT_ARRAY
)) {
6656 vtop
->r
|= lvalue_type(vtop
->type
.t
);
6657 /* if bound checking, the referenced pointer must be checked */
6658 if (do_bounds_check
)
6659 vtop
->r
|= VT_MUSTBOUND
;
6662 } else if (tok
== '[') {
6668 } else if (tok
== '(') {
6673 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
) {
6674 /* pointer test (no array accepted) */
6675 if ((vtop
->type
.t
& (VT_BTYPE
| VT_ARRAY
)) == VT_PTR
) {
6676 vtop
->type
= *pointed_type(&vtop
->type
);
6677 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
)
6681 expect("function pointer");
6684 vtop
->r
&= ~VT_LVAL
; /* no lvalue */
6686 /* get return type */
6688 if (!nocode_wanted
) {
6689 save_regs(0); /* save used temporary registers */
6690 gfunc_start(&gf
, s
->r
);
6693 sa
= s
->next
; /* first parameter */
6694 #ifdef INVERT_FUNC_PARAMS
6698 ParseState saved_parse_state
;
6701 /* read each argument and store it on a stack */
6707 while ((parlevel
> 0 || (tok
!= ')' && tok
!= ',')) &&
6711 else if (tok
== ')')
6713 tok_str_add_tok(&str
);
6716 tok_str_add(&str
, -1); /* end of file added */
6717 tok_str_add(&str
, 0);
6718 s1
= sym_push2(&args
, 0, 0, (int)str
.str
);
6719 s1
->next
= sa
; /* add reference to argument */
6728 /* now generate code in reverse order by reading the stack */
6729 save_parse_state(&saved_parse_state
);
6731 macro_ptr
= (int *)args
->c
;
6735 expect("',' or ')'");
6736 gfunc_param_typed(&gf
, s
, args
->next
);
6738 tok_str_free((int *)args
->c
);
6742 restore_parse_state(&saved_parse_state
);
6745 /* compute first implicit argument if a structure is returned */
6746 if ((s
->type
.t
& VT_BTYPE
) == VT_STRUCT
) {
6747 /* get some space for the returned structure */
6748 size
= type_size(&s
->type
, &align
);
6749 loc
= (loc
- size
) & -align
;
6751 ret
.r
= VT_LOCAL
| VT_LVAL
;
6752 /* pass it as 'int' to avoid structure arg passing
6754 vseti(VT_LOCAL
, loc
);
6763 /* return in register */
6764 if (is_float(ret
.type
.t
)) {
6767 if ((ret
.type
.t
& VT_BTYPE
) == VT_LLONG
)
6773 #ifndef INVERT_FUNC_PARAMS
6777 gfunc_param_typed(&gf
, s
, sa
);
6787 error("too few arguments to function");
6794 vsetc(&ret
.type
, ret
.r
, &ret
.c
);
6802 static void uneq(void)
6808 (tok
>= TOK_A_MOD
&& tok
<= TOK_A_DIV
) ||
6809 tok
== TOK_A_XOR
|| tok
== TOK_A_OR
||
6810 tok
== TOK_A_SHL
|| tok
== TOK_A_SAR
) {
6825 static void expr_prod(void)
6830 while (tok
== '*' || tok
== '/' || tok
== '%') {
6838 static void expr_sum(void)
6843 while (tok
== '+' || tok
== '-') {
6851 static void expr_shift(void)
6856 while (tok
== TOK_SHL
|| tok
== TOK_SAR
) {
6864 static void expr_cmp(void)
6869 while ((tok
>= TOK_ULE
&& tok
<= TOK_GT
) ||
6870 tok
== TOK_ULT
|| tok
== TOK_UGE
) {
6878 static void expr_cmpeq(void)
6883 while (tok
== TOK_EQ
|| tok
== TOK_NE
) {
6891 static void expr_and(void)
6894 while (tok
== '&') {
6901 static void expr_xor(void)
6904 while (tok
== '^') {
6911 static void expr_or(void)
6914 while (tok
== '|') {
6921 /* XXX: suppress this mess */
6922 static void expr_land_const(void)
6925 while (tok
== TOK_LAND
) {
6932 /* XXX: suppress this mess */
6933 static void expr_lor_const(void)
6936 while (tok
== TOK_LOR
) {
6943 /* only used if non constant */
6944 static void expr_land(void)
6949 if (tok
== TOK_LAND
) {
6953 if (tok
!= TOK_LAND
) {
6963 static void expr_lor(void)
6968 if (tok
== TOK_LOR
) {
6972 if (tok
!= TOK_LOR
) {
6982 /* XXX: better constant handling */
6983 static void expr_eq(void)
6985 int tt
, u
, r1
, r2
, rc
, t1
, t2
, bt1
, bt2
;
6987 CType type
, type1
, type2
;
6996 if (tok
== ':' && gnu_ext
) {
7012 if (vtop
!= vstack
) {
7013 /* needed to avoid having different registers saved in
7015 if (is_float(vtop
->type
.t
))
7022 if (tok
== ':' && gnu_ext
) {
7030 sv
= *vtop
; /* save value to handle it later */
7031 vtop
--; /* no vpop so that FP stack is not flushed */
7039 bt1
= t1
& VT_BTYPE
;
7041 bt2
= t2
& VT_BTYPE
;
7042 /* cast operands to correct type according to ISOC rules */
7043 if (is_float(bt1
) || is_float(bt2
)) {
7044 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
7045 type
.t
= VT_LDOUBLE
;
7046 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
7051 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
7052 /* cast to biggest op */
7054 /* convert to unsigned if it does not fit in a long long */
7055 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
7056 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
7057 type
.t
|= VT_UNSIGNED
;
7058 } else if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
7059 /* XXX: test pointer compatibility */
7061 } else if (bt1
== VT_STRUCT
|| bt2
== VT_STRUCT
) {
7062 /* XXX: test structure compatibility */
7064 } else if (bt1
== VT_VOID
|| bt2
== VT_VOID
) {
7065 /* NOTE: as an extension, we accept void on only one side */
7068 /* integer operations */
7070 /* convert to unsigned if it does not fit in an integer */
7071 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
7072 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
7073 type
.t
|= VT_UNSIGNED
;
7076 /* now we convert second operand */
7079 if (is_float(type
.t
)) {
7081 } else if ((type
.t
& VT_BTYPE
) == VT_LLONG
) {
7082 /* for long longs, we use fixed registers to avoid having
7083 to handle a complicated move */
7088 /* this is horrible, but we must also convert first
7092 /* put again first value and cast it */
7103 static void gexpr(void)
7114 /* parse an expression and return its type without any side effect. */
7115 static void expr_type(CType
*type
)
7127 /* parse a unary expression and return its type without any side
7129 static void unary_type(CType
*type
)
7141 /* parse a constant expression and return value in vtop. */
7142 static void expr_const1(void)
7151 /* parse an integer constant and return its value. */
7152 static int expr_const(void)
7156 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
7157 expect("constant expression");
7163 /* return the label token if current token is a label, otherwise
7165 static int is_label(void)
7169 /* fast test first */
7170 if (tok
< TOK_UIDENT
)
7172 /* no need to save tokc because tok is an identifier */
7179 unget_tok(last_tok
);
7184 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
7185 int case_reg
, int is_expr
)
7190 /* generate line number info */
7192 (last_line_num
!= file
->line_num
|| last_ind
!= ind
)) {
7193 put_stabn(N_SLINE
, 0, file
->line_num
, ind
- func_ind
);
7195 last_line_num
= file
->line_num
;
7199 /* default return value is (void) */
7201 vtop
->type
.t
= VT_VOID
;
7204 if (tok
== TOK_IF
) {
7211 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7213 if (c
== TOK_ELSE
) {
7217 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7218 gsym(d
); /* patch else jmp */
7221 } else if (tok
== TOK_WHILE
) {
7229 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7233 } else if (tok
== '{') {
7237 /* record local declaration stack position */
7239 llabel
= local_label_stack
;
7240 /* handle local labels declarations */
7241 if (tok
== TOK_LABEL
) {
7244 if (tok
< TOK_UIDENT
)
7245 expect("label identifier");
7246 label_push(&local_label_stack
, tok
, LABEL_DECLARED
);
7256 while (tok
!= '}') {
7261 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
7264 /* pop locally defined labels */
7265 label_pop(&local_label_stack
, llabel
);
7266 /* pop locally defined symbols */
7267 sym_pop(&local_stack
, s
);
7269 } else if (tok
== TOK_RETURN
) {
7273 gen_assign_cast(&func_vt
);
7274 if ((func_vt
.t
& VT_BTYPE
) == VT_STRUCT
) {
7276 /* if returning structure, must copy it to implicit
7277 first pointer arg location */
7280 vset(&type
, VT_LOCAL
| VT_LVAL
, func_vc
);
7283 /* copy structure value to pointer */
7285 } else if (is_float(func_vt
.t
)) {
7290 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
7293 rsym
= gjmp(rsym
); /* jmp */
7294 } else if (tok
== TOK_BREAK
) {
7297 error("cannot break");
7298 *bsym
= gjmp(*bsym
);
7301 } else if (tok
== TOK_CONTINUE
) {
7304 error("cannot continue");
7305 *csym
= gjmp(*csym
);
7308 } else if (tok
== TOK_FOR
) {
7335 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7340 if (tok
== TOK_DO
) {
7345 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7356 if (tok
== TOK_SWITCH
) {
7360 /* XXX: other types than integer */
7361 case_reg
= gv(RC_INT
);
7365 b
= gjmp(0); /* jump to first case */
7367 block(&a
, csym
, &b
, &c
, case_reg
, 0);
7368 /* if no default, jmp after switch */
7376 if (tok
== TOK_CASE
) {
7383 if (gnu_ext
&& tok
== TOK_DOTS
) {
7387 warning("empty case range");
7389 /* since a case is like a label, we must skip it with a jmp */
7396 *case_sym
= gtst(1, 0);
7399 *case_sym
= gtst(1, 0);
7403 *case_sym
= gtst(1, *case_sym
);
7407 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7409 if (tok
== TOK_DEFAULT
) {
7415 error("too many 'default'");
7417 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7419 if (tok
== TOK_GOTO
) {
7421 if (tok
== '*' && gnu_ext
) {
7425 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
7428 } else if (tok
>= TOK_UIDENT
) {
7429 s
= label_find(tok
);
7430 /* put forward definition if needed */
7432 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
7434 if (s
->r
== LABEL_DECLARED
)
7435 s
->r
= LABEL_FORWARD
;
7437 /* label already defined */
7438 if (s
->r
& LABEL_FORWARD
)
7439 s
->next
= (void *)gjmp((long)s
->next
);
7441 gjmp_addr((long)s
->next
);
7444 expect("label identifier");
7447 } else if (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
) {
7455 if (s
->r
== LABEL_DEFINED
)
7456 error("duplicate label '%s'", get_tok_str(s
->v
, NULL
));
7457 gsym((long)s
->next
);
7458 s
->r
= LABEL_DEFINED
;
7460 s
= label_push(&global_label_stack
, b
, LABEL_DEFINED
);
7462 s
->next
= (void *)ind
;
7463 /* we accept this, but it is a mistake */
7465 warning("deprecated use of label at end of compound statement");
7469 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
7472 /* expression case */
7487 /* t is the array or struct type. c is the array or struct
7488 address. cur_index/cur_field is the pointer to the current
7489 value. 'size_only' is true if only size info is needed (only used
7491 static void decl_designator(CType
*type
, Section
*sec
, unsigned long c
,
7492 int *cur_index
, Sym
**cur_field
,
7496 int notfirst
, index
, index_last
, align
, l
, nb_elems
, elem_size
;
7502 if (gnu_ext
&& (l
= is_label()) != 0)
7504 while (tok
== '[' || tok
== '.') {
7506 if (!(type
->t
& VT_ARRAY
))
7507 expect("array type");
7510 index
= expr_const();
7511 if (index
< 0 || (s
->c
>= 0 && index
>= s
->c
))
7512 expect("invalid index");
7513 if (tok
== TOK_DOTS
&& gnu_ext
) {
7515 index_last
= expr_const();
7516 if (index_last
< 0 ||
7517 (s
->c
>= 0 && index_last
>= s
->c
) ||
7519 expect("invalid index");
7525 *cur_index
= index_last
;
7526 type
= pointed_type(type
);
7527 elem_size
= type_size(type
, &align
);
7528 c
+= index
* elem_size
;
7529 /* NOTE: we only support ranges for last designator */
7530 nb_elems
= index_last
- index
+ 1;
7531 if (nb_elems
!= 1) {
7540 if ((type
->t
& VT_BTYPE
) != VT_STRUCT
)
7541 expect("struct/union type");
7554 /* XXX: suppress this mess by using explicit storage field */
7556 type1
.t
|= (type
->t
& ~VT_TYPE
);
7570 if (type
->t
& VT_ARRAY
) {
7572 type
= pointed_type(type
);
7573 c
+= index
* type_size(type
, &align
);
7577 error("too many field init");
7578 /* XXX: suppress this mess by using explicit storage field */
7580 type1
.t
|= (type
->t
& ~VT_TYPE
);
7585 decl_initializer(type
, sec
, c
, 0, size_only
);
7587 /* XXX: make it more general */
7588 if (!size_only
&& nb_elems
> 1) {
7589 unsigned long c_end
;
7594 error("range init not supported yet for dynamic storage");
7595 c_end
= c
+ nb_elems
* elem_size
;
7596 if (c_end
> sec
->data_allocated
)
7597 section_realloc(sec
, c_end
);
7598 src
= sec
->data
+ c
;
7600 for(i
= 1; i
< nb_elems
; i
++) {
7602 memcpy(dst
, src
, elem_size
);
7608 #define EXPR_CONST 1
7611 /* store a value or an expression directly in global data or in local array */
7612 static void init_putv(CType
*type
, Section
*sec
, unsigned long c
,
7613 int v
, int expr_type
)
7615 int saved_global_expr
, bt
, bit_pos
, bit_size
;
7617 unsigned long long bit_mask
;
7624 /* compound literals must be allocated globally in this case */
7625 saved_global_expr
= global_expr
;
7628 global_expr
= saved_global_expr
;
7629 /* NOTE: symbols are accepted */
7630 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) != VT_CONST
)
7631 error("initializer element is not constant");
7639 /* XXX: not portable */
7640 /* XXX: generate error if incorrect relocation */
7641 gen_assign_cast(type
);
7642 bt
= type
->t
& VT_BTYPE
;
7643 ptr
= sec
->data
+ c
;
7644 /* XXX: make code faster ? */
7645 if (!(type
->t
& VT_BITFIELD
)) {
7650 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
7651 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
7652 bit_mask
= (1LL << bit_size
) - 1;
7654 if ((vtop
->r
& VT_SYM
) &&
7660 (bt
== VT_INT
&& bit_size
!= 32)))
7661 error("initializer element is not computable at load time");
7664 *(char *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
7667 *(short *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
7670 *(double *)ptr
= vtop
->c
.d
;
7673 *(long double *)ptr
= vtop
->c
.ld
;
7676 *(long long *)ptr
|= (vtop
->c
.ll
& bit_mask
) << bit_pos
;
7679 if (vtop
->r
& VT_SYM
) {
7680 greloc(sec
, vtop
->sym
, c
, R_DATA_32
);
7682 *(int *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
7687 vset(type
, VT_LOCAL
, c
);
7694 /* put zeros for variable based init */
7695 static void init_putz(CType
*t
, Section
*sec
, unsigned long c
, int size
)
7700 /* nothing to do because globals are already set to zero */
7702 gfunc_start(&gf
, FUNC_CDECL
);
7709 vpush_global_sym(&func_old_type
, TOK_memset
);
7714 /* 't' contains the type and storage info. 'c' is the offset of the
7715 object in section 'sec'. If 'sec' is NULL, it means stack based
7716 allocation. 'first' is true if array '{' must be read (multi
7717 dimension implicit array init handling). 'size_only' is true if
7718 size only evaluation is wanted (only for arrays). */
7719 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
7720 int first
, int size_only
)
7722 int index
, array_length
, n
, no_oblock
, nb
, parlevel
, i
;
7723 int size1
, align1
, expr_type
;
7727 if (type
->t
& VT_ARRAY
) {
7731 t1
= pointed_type(type
);
7732 size1
= type_size(t1
, &align1
);
7735 if ((first
&& tok
!= TOK_LSTR
&& tok
!= TOK_STR
) ||
7741 /* only parse strings here if correct type (otherwise: handle
7742 them as ((w)char *) expressions */
7743 if ((tok
== TOK_LSTR
&&
7744 (t1
->t
& VT_BTYPE
) == VT_INT
) ||
7746 (t1
->t
& VT_BTYPE
) == VT_BYTE
)) {
7747 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
7752 /* compute maximum number of chars wanted */
7754 cstr_len
= cstr
->size
;
7756 cstr_len
= cstr
->size
/ sizeof(int);
7759 if (n
>= 0 && nb
> (n
- array_length
))
7760 nb
= n
- array_length
;
7763 warning("initializer-string for array is too long");
7764 /* in order to go faster for common case (char
7765 string in global variable, we handle it
7767 if (sec
&& tok
== TOK_STR
&& size1
== 1) {
7768 memcpy(sec
->data
+ c
+ array_length
, cstr
->data
, nb
);
7772 ch
= ((unsigned char *)cstr
->data
)[i
];
7774 ch
= ((int *)cstr
->data
)[i
];
7775 init_putv(t1
, sec
, c
+ (array_length
+ i
) * size1
,
7783 /* only add trailing zero if enough storage (no
7784 warning in this case since it is standard) */
7785 if (n
< 0 || array_length
< n
) {
7787 init_putv(t1
, sec
, c
+ (array_length
* size1
), 0, EXPR_VAL
);
7793 while (tok
!= '}') {
7794 decl_designator(type
, sec
, c
, &index
, NULL
, size_only
);
7795 if (n
>= 0 && index
>= n
)
7796 error("index too large");
7797 /* must put zero in holes (note that doing it that way
7798 ensures that it even works with designators) */
7799 if (!size_only
&& array_length
< index
) {
7800 init_putz(t1
, sec
, c
+ array_length
* size1
,
7801 (index
- array_length
) * size1
);
7804 if (index
> array_length
)
7805 array_length
= index
;
7806 /* special test for multi dimensional arrays (may not
7807 be strictly correct if designators are used at the
7809 if (index
>= n
&& no_oblock
)
7818 /* put zeros at the end */
7819 if (!size_only
&& n
>= 0 && array_length
< n
) {
7820 init_putz(t1
, sec
, c
+ array_length
* size1
,
7821 (n
- array_length
) * size1
);
7823 /* patch type size if needed */
7825 s
->c
= array_length
;
7826 } else if ((type
->t
& VT_BTYPE
) == VT_STRUCT
&&
7827 (sec
|| !first
|| tok
== '{')) {
7830 /* NOTE: the previous test is a specific case for automatic
7831 struct/union init */
7832 /* XXX: union needs only one init */
7834 /* XXX: this test is incorrect for local initializers
7835 beginning with ( without {. It would be much more difficult
7836 to do it correctly (ideally, the expression parser should
7837 be used in all cases) */
7843 while (tok
== '(') {
7847 if (!parse_btype(&type1
, &ad1
))
7849 type_decl(&type1
, &ad1
, &n
, TYPE_ABSTRACT
);
7850 if (!is_compatible_types(type
, &type1
))
7851 error("invalid type for cast");
7855 if (first
|| tok
== '{') {
7864 while (tok
!= '}') {
7865 decl_designator(type
, sec
, c
, NULL
, &f
, size_only
);
7867 if (!size_only
&& array_length
< index
) {
7868 init_putz(type
, sec
, c
+ array_length
,
7869 index
- array_length
);
7871 index
= index
+ type_size(&f
->type
, &align1
);
7872 if (index
> array_length
)
7873 array_length
= index
;
7875 if (no_oblock
&& f
== NULL
)
7881 /* put zeros at the end */
7882 if (!size_only
&& array_length
< n
) {
7883 init_putz(type
, sec
, c
+ array_length
,
7892 } else if (tok
== '{') {
7894 decl_initializer(type
, sec
, c
, first
, size_only
);
7896 } else if (size_only
) {
7897 /* just skip expression */
7899 while ((parlevel
> 0 || (tok
!= '}' && tok
!= ',')) &&
7903 else if (tok
== ')')
7908 /* currently, we always use constant expression for globals
7909 (may change for scripting case) */
7910 expr_type
= EXPR_CONST
;
7912 expr_type
= EXPR_ANY
;
7913 init_putv(type
, sec
, c
, 0, expr_type
);
7917 /* parse an initializer for type 't' if 'has_init' is non zero, and
7918 allocate space in local or global data space ('r' is either
7919 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
7920 variable 'v' of scope 'scope' is declared before initializers are
7921 parsed. If 'v' is zero, then a reference to the new object is put
7922 in the value stack. If 'has_init' is 2, a special parsing is done
7923 to handle string constants. */
7924 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
7925 int has_init
, int v
, int scope
)
7927 int size
, align
, addr
, data_offset
;
7929 ParseState saved_parse_state
;
7930 TokenString init_str
;
7933 size
= type_size(type
, &align
);
7934 /* If unknown size, we must evaluate it before
7935 evaluating initializers because
7936 initializers can generate global data too
7937 (e.g. string pointers or ISOC99 compound
7938 literals). It also simplifies local
7939 initializers handling */
7940 tok_str_new(&init_str
);
7943 error("unknown type size");
7944 /* get all init string */
7945 if (has_init
== 2) {
7946 /* only get strings */
7947 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
7948 tok_str_add_tok(&init_str
);
7953 while (level
> 0 || (tok
!= ',' && tok
!= ';')) {
7955 error("unexpected end of file in initializer");
7956 tok_str_add_tok(&init_str
);
7959 else if (tok
== '}') {
7967 tok_str_add(&init_str
, -1);
7968 tok_str_add(&init_str
, 0);
7971 save_parse_state(&saved_parse_state
);
7973 macro_ptr
= init_str
.str
;
7975 decl_initializer(type
, NULL
, 0, 1, 1);
7976 /* prepare second initializer parsing */
7977 macro_ptr
= init_str
.str
;
7980 /* if still unknown size, error */
7981 size
= type_size(type
, &align
);
7983 error("unknown type size");
7985 /* take into account specified alignment if bigger */
7986 if (ad
->aligned
> align
)
7987 align
= ad
->aligned
;
7988 if ((r
& VT_VALMASK
) == VT_LOCAL
) {
7990 if (do_bounds_check
&& (type
->t
& VT_ARRAY
))
7992 loc
= (loc
- size
) & -align
;
7994 /* handles bounds */
7995 /* XXX: currently, since we do only one pass, we cannot track
7996 '&' operators, so we add only arrays */
7997 if (do_bounds_check
&& (type
->t
& VT_ARRAY
)) {
7998 unsigned long *bounds_ptr
;
7999 /* add padding between regions */
8001 /* then add local bound info */
8002 bounds_ptr
= section_ptr_add(lbounds_section
, 2 * sizeof(unsigned long));
8003 bounds_ptr
[0] = addr
;
8004 bounds_ptr
[1] = size
;
8007 /* local variable */
8008 sym_push(v
, type
, r
, addr
);
8010 /* push local reference */
8011 vset(type
, r
, addr
);
8017 if (v
&& scope
== VT_CONST
) {
8018 /* see if the symbol was already defined */
8021 if (!is_compatible_types(&sym
->type
, type
))
8022 error("incompatible types for redefinition of '%s'",
8023 get_tok_str(v
, NULL
));
8024 if (sym
->type
.t
& VT_EXTERN
) {
8025 /* if the variable is extern, it was not allocated */
8026 sym
->type
.t
&= ~VT_EXTERN
;
8028 /* we accept several definitions of the same
8029 global variable. this is tricky, because we
8030 must play with the SHN_COMMON type of the symbol */
8031 /* XXX: should check if the variable was already
8032 initialized. It is incorrect to initialized it
8034 /* no init data, we won't add more to the symbol */
8041 /* allocate symbol in corresponding section */
8048 data_offset
= sec
->data_offset
;
8049 data_offset
= (data_offset
+ align
- 1) & -align
;
8051 /* very important to increment global pointer at this time
8052 because initializers themselves can create new initializers */
8053 data_offset
+= size
;
8054 /* add padding if bound check */
8055 if (do_bounds_check
)
8057 sec
->data_offset
= data_offset
;
8058 /* allocate section space to put the data */
8059 if (sec
->sh_type
!= SHT_NOBITS
&&
8060 data_offset
> sec
->data_allocated
)
8061 section_realloc(sec
, data_offset
);
8063 addr
= 0; /* avoid warning */
8067 if (scope
== VT_CONST
) {
8072 sym
= sym_push(v
, type
, r
| VT_SYM
, 0);
8074 /* update symbol definition */
8076 put_extern_sym(sym
, sec
, addr
, size
);
8079 /* put a common area */
8080 put_extern_sym(sym
, NULL
, align
, size
);
8081 /* XXX: find a nicer way */
8082 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
8083 esym
->st_shndx
= SHN_COMMON
;
8088 /* push global reference */
8089 sym
= get_sym_ref(type
, sec
, addr
, size
);
8091 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
8095 /* handles bounds now because the symbol must be defined
8096 before for the relocation */
8097 if (do_bounds_check
) {
8098 unsigned long *bounds_ptr
;
8100 greloc(bounds_section
, sym
, bounds_section
->data_offset
, R_DATA_32
);
8101 /* then add global bound info */
8102 bounds_ptr
= section_ptr_add(bounds_section
, 2 * sizeof(long));
8103 bounds_ptr
[0] = 0; /* relocated */
8104 bounds_ptr
[1] = size
;
8108 decl_initializer(type
, sec
, addr
, 1, 0);
8109 /* restore parse state if needed */
8111 tok_str_free(init_str
.str
);
8112 restore_parse_state(&saved_parse_state
);
8118 void put_func_debug(Sym
*sym
)
8123 /* XXX: we put here a dummy type */
8124 snprintf(buf
, sizeof(buf
), "%s:%c1",
8125 funcname
, sym
->type
.t
& VT_STATIC
? 'f' : 'F');
8126 put_stabs_r(buf
, N_FUN
, 0, file
->line_num
, 0,
8127 cur_text_section
, sym
->c
);
8132 /* not finished : try to put some local vars in registers */
8133 //#define CONFIG_REG_VARS
8135 #ifdef CONFIG_REG_VARS
8136 void add_var_ref(int t
)
8138 printf("%s:%d: &%s\n",
8139 file
->filename
, file
->line_num
,
8140 get_tok_str(t
, NULL
));
8143 /* first pass on a function with heuristic to extract variable usage
8144 and pointer references to local variables for register allocation */
8145 void analyse_function(void)
8152 /* any symbol coming after '&' is considered as being a
8153 variable whose reference is taken. It is highly unaccurate
8154 but it is difficult to do better without a complete parse */
8157 /* if '& number', then no need to examine next tokens */
8158 if (tok
== TOK_CINT
||
8160 tok
== TOK_CLLONG
||
8161 tok
== TOK_CULLONG
) {
8163 } else if (tok
>= TOK_UIDENT
) {
8164 /* if '& ident [' or '& ident ->', then ident address
8168 if (tok
!= '[' && tok
!= TOK_ARROW
)
8172 while (tok
!= '}' && tok
!= ';' &&
8173 !((tok
== ',' || tok
== ')') && level
== 0)) {
8174 if (tok
>= TOK_UIDENT
) {
8176 } else if (tok
== '(') {
8178 } else if (tok
== ')') {
8191 /* parse an old style function declaration list */
8192 /* XXX: check multiple parameter */
8193 static void func_decl_list(Sym
*func_sym
)
8200 /* parse each declaration */
8201 while (tok
!= '{' && tok
!= ';' && tok
!= ',' && tok
!= TOK_EOF
) {
8202 if (!parse_btype(&btype
, &ad
))
8203 expect("declaration list");
8204 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
8205 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
8207 /* we accept no variable after */
8211 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
8212 /* find parameter in function parameter list */
8215 if ((s
->v
& ~SYM_FIELD
) == v
)
8219 error("declaration for parameter '%s' but no such parameter",
8220 get_tok_str(v
, NULL
));
8222 /* check that no storage specifier except 'register' was given */
8223 if (type
.t
& VT_STORAGE
)
8224 error("storage class specified for '%s'", get_tok_str(v
, NULL
));
8225 /* array must be transformed to pointer according to ANSI C */
8226 type
.t
&= ~VT_ARRAY
;
8227 /* we can add the type (NOTE: it could be local to the function) */
8229 /* accept other parameters */
8240 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
8241 static void decl(int l
)
8249 if (!parse_btype(&btype
, &ad
)) {
8250 /* skip redundant ';' */
8251 /* XXX: find more elegant solution */
8256 /* special test for old K&R protos without explicit int
8257 type. Only accepted when defining global data */
8258 if (l
== VT_LOCAL
|| tok
< TOK_DEFINE
)
8262 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
8263 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
8265 /* we accept no variable after */
8269 while (1) { /* iterate thru each declaration */
8271 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
8275 type_to_str(buf
, sizeof(buf
), t
, get_tok_str(v
, NULL
));
8276 printf("type = '%s'\n", buf
);
8279 if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
8280 /* if old style function prototype, we accept a
8283 if (sym
->c
== FUNC_OLD
)
8284 func_decl_list(sym
);
8288 #ifdef CONFIG_REG_VARS
8289 TokenString func_str
;
8290 ParseState saved_parse_state
;
8295 error("cannot use local functions");
8296 if (!(type
.t
& VT_FUNC
))
8297 expect("function definition");
8298 /* XXX: cannot do better now: convert extern line to static inline */
8299 if ((type
.t
& (VT_EXTERN
| VT_INLINE
)) == (VT_EXTERN
| VT_INLINE
))
8300 type
.t
= (type
.t
& ~VT_EXTERN
) | VT_STATIC
;
8302 #ifdef CONFIG_REG_VARS
8303 /* parse all function code and record it */
8305 tok_str_new(&func_str
);
8311 error("unexpected end of file");
8312 tok_str_add_tok(&func_str
);
8317 } else if (t
== '}') {
8319 if (block_level
== 0)
8323 tok_str_add(&func_str
, -1);
8324 tok_str_add(&func_str
, 0);
8326 save_parse_state(&saved_parse_state
);
8328 macro_ptr
= func_str
.str
;
8333 /* compute text section */
8334 cur_text_section
= ad
.section
;
8335 if (!cur_text_section
)
8336 cur_text_section
= text_section
;
8337 ind
= cur_text_section
->data_offset
;
8338 funcname
= get_tok_str(v
, NULL
);
8341 /* if symbol is already defined, then put complete type */
8344 /* put function symbol */
8345 sym
= global_identifier_push(v
, type
.t
, 0);
8346 sym
->type
.ref
= type
.ref
;
8348 /* NOTE: we patch the symbol size later */
8349 put_extern_sym(sym
, cur_text_section
, ind
, 0);
8351 sym
->r
= VT_SYM
| VT_CONST
;
8352 /* put debug symbol */
8354 put_func_debug(sym
);
8355 /* push a dummy symbol to enable local sym storage */
8356 sym_push2(&local_stack
, SYM_FIELD
, 0, 0);
8357 gfunc_prolog(&type
);
8360 #ifdef CONFIG_REG_VARS
8361 macro_ptr
= func_str
.str
;
8364 block(NULL
, NULL
, NULL
, NULL
, 0, 0);
8367 cur_text_section
->data_offset
= ind
;
8368 label_pop(&global_label_stack
, NULL
);
8369 sym_pop(&local_stack
, NULL
); /* reset local stack */
8370 /* end of function */
8371 /* patch symbol size */
8372 ((Elf32_Sym
*)symtab_section
->data
)[sym
->c
].st_size
=
8375 put_stabn(N_FUN
, 0, 0, ind
- func_ind
);
8377 funcname
= ""; /* for safety */
8378 func_vt
.t
= VT_VOID
; /* for safety */
8379 ind
= 0; /* for safety */
8381 #ifdef CONFIG_REG_VARS
8382 tok_str_free(func_str
.str
);
8383 restore_parse_state(&saved_parse_state
);
8387 if (btype
.t
& VT_TYPEDEF
) {
8388 /* save typedefed type */
8389 /* XXX: test storage specifiers ? */
8390 sym
= sym_push(v
, &type
, 0, 0);
8391 sym
->type
.t
|= VT_TYPEDEF
;
8392 } else if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
8393 /* external function definition */
8394 external_sym(v
, &type
, 0);
8396 /* not lvalue if array */
8398 if (!(type
.t
& VT_ARRAY
))
8399 r
|= lvalue_type(type
.t
);
8400 has_init
= (tok
== '=');
8401 if ((btype
.t
& VT_EXTERN
) ||
8402 ((type
.t
& VT_ARRAY
) && (type
.t
& VT_STATIC
) &&
8403 !has_init
&& l
== VT_CONST
&& type
.ref
->c
< 0)) {
8404 /* external variable */
8405 /* NOTE: as GCC, uninitialized global static
8406 arrays of null size are considered as
8408 external_sym(v
, &type
, r
);
8410 if (type
.t
& VT_STATIC
)
8416 decl_initializer_alloc(&type
, &ad
, r
,
8430 /* better than nothing, but needs extension to handle '-E' option
8432 static void preprocess_init(TCCState
*s1
)
8434 s1
->include_stack_ptr
= s1
->include_stack
;
8435 /* XXX: move that before to avoid having to initialize
8436 file->ifdef_stack_ptr ? */
8437 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
8438 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
8440 /* XXX: not ANSI compliant: bound checking says error */
8444 /* compile the C file opened in 'file'. Return non zero if errors. */
8445 static int tcc_compile(TCCState
*s1
)
8449 volatile int section_sym
;
8452 printf("%s: **** new file\n", file
->filename
);
8454 preprocess_init(s1
);
8457 anon_sym
= SYM_FIRST_ANOM
;
8459 /* file info: full path + filename */
8460 section_sym
= 0; /* avoid warning */
8462 section_sym
= put_elf_sym(symtab_section
, 0, 0,
8463 ELF32_ST_INFO(STB_LOCAL
, STT_SECTION
), 0,
8464 text_section
->sh_num
, NULL
);
8465 getcwd(buf
, sizeof(buf
));
8466 pstrcat(buf
, sizeof(buf
), "/");
8467 put_stabs_r(buf
, N_SO
, 0, 0,
8468 text_section
->data_offset
, text_section
, section_sym
);
8469 put_stabs_r(file
->filename
, N_SO
, 0, 0,
8470 text_section
->data_offset
, text_section
, section_sym
);
8472 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
8473 symbols can be safely used */
8474 put_elf_sym(symtab_section
, 0, 0,
8475 ELF32_ST_INFO(STB_LOCAL
, STT_FILE
), 0,
8476 SHN_ABS
, file
->filename
);
8478 /* define some often used types */
8479 int_type
.t
= VT_INT
;
8481 char_pointer_type
.t
= VT_BYTE
;
8482 mk_pointer(&char_pointer_type
);
8484 func_old_type
.t
= VT_FUNC
;
8485 func_old_type
.ref
= sym_push(SYM_FIELD
, &int_type
, FUNC_CDECL
, FUNC_OLD
);
8488 /* define 'void *alloca(unsigned int)' builtin function */
8493 sym
= sym_push(p
, mk_pointer(VT_VOID
), FUNC_CDECL
, FUNC_NEW
);
8494 s1
= sym_push(SYM_FIELD
, VT_UNSIGNED
| VT_INT
, 0, 0);
8497 sym_push(TOK_alloca
, VT_FUNC
| (p
<< VT_STRUCT_SHIFT
), VT_CONST
, 0);
8501 define_start
= define_stack
;
8503 if (setjmp(s1
->error_jmp_buf
) == 0) {
8505 s1
->error_set_jmp_enabled
= 1;
8507 ch
= file
->buf_ptr
[0];
8508 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
8509 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
;
8513 expect("declaration");
8515 /* end of translation unit info */
8517 put_stabs_r(NULL
, N_SO
, 0, 0,
8518 text_section
->data_offset
, text_section
, section_sym
);
8521 s1
->error_set_jmp_enabled
= 0;
8523 /* reset define stack, but leave -Dsymbols (may be incorrect if
8524 they are undefined) */
8525 free_defines(define_start
);
8527 sym_pop(&global_stack
, NULL
);
8529 return s1
->nb_errors
!= 0 ? -1 : 0;
8533 int tcc_compile_string(TCCState
*s
, const char *str
)
8535 BufferedFile bf1
, *bf
= &bf1
;
8539 /* init file structure */
8541 /* XXX: avoid copying */
8543 buf
= tcc_malloc(len
+ 1);
8546 memcpy(buf
, str
, len
);
8549 bf
->buf_end
= buf
+ len
;
8550 pstrcpy(bf
->filename
, sizeof(bf
->filename
), "<string>");
8554 ret
= tcc_compile(s
);
8558 /* currently, no need to close */
8563 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
8564 void tcc_define_symbol(TCCState
*s1
, const char *sym
, const char *value
)
8566 BufferedFile bf1
, *bf
= &bf1
;
8568 pstrcpy(bf
->buffer
, IO_BUF_SIZE
, sym
);
8569 pstrcat(bf
->buffer
, IO_BUF_SIZE
, " ");
8573 pstrcat(bf
->buffer
, IO_BUF_SIZE
, value
);
8575 /* init file structure */
8577 bf
->buf_ptr
= bf
->buffer
;
8578 bf
->buf_end
= bf
->buffer
+ strlen(bf
->buffer
);
8579 *bf
->buf_end
= CH_EOB
;
8580 bf
->filename
[0] = '\0';
8584 s1
->include_stack_ptr
= s1
->include_stack
;
8586 /* parse with define parser */
8587 ch
= file
->buf_ptr
[0];
8593 /* undefine a preprocessor symbol */
8594 void tcc_undefine_symbol(TCCState
*s1
, const char *sym
)
8598 ts
= tok_alloc(sym
, strlen(sym
));
8599 s
= define_find(ts
->tok
);
8600 /* undefine symbol by putting an invalid name */
8605 #ifdef CONFIG_TCC_ASM
8607 #include "i386-asm.c"
8611 static void asm_instr(void)
8613 error("inline asm() not supported");
8619 /* print the position in the source file of PC value 'pc' by reading
8620 the stabs debug information */
8621 static void rt_printline(unsigned long wanted_pc
)
8623 Stab_Sym
*sym
, *sym_end
;
8624 char func_name
[128], last_func_name
[128];
8625 unsigned long func_addr
, last_pc
, pc
;
8626 const char *incl_files
[INCLUDE_STACK_SIZE
];
8627 int incl_index
, len
, last_line_num
, i
;
8628 const char *str
, *p
;
8630 fprintf(stderr
, "0x%08lx:", wanted_pc
);
8632 func_name
[0] = '\0';
8635 last_func_name
[0] = '\0';
8636 last_pc
= 0xffffffff;
8638 sym
= (Stab_Sym
*)stab_section
->data
+ 1;
8639 sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
8640 while (sym
< sym_end
) {
8641 switch(sym
->n_type
) {
8642 /* function start or end */
8644 if (sym
->n_strx
== 0) {
8645 /* we test if between last line and end of function */
8646 pc
= sym
->n_value
+ func_addr
;
8647 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
8649 func_name
[0] = '\0';
8652 str
= stabstr_section
->data
+ sym
->n_strx
;
8653 p
= strchr(str
, ':');
8655 pstrcpy(func_name
, sizeof(func_name
), str
);
8658 if (len
> sizeof(func_name
) - 1)
8659 len
= sizeof(func_name
) - 1;
8660 memcpy(func_name
, str
, len
);
8661 func_name
[len
] = '\0';
8663 func_addr
= sym
->n_value
;
8666 /* line number info */
8668 pc
= sym
->n_value
+ func_addr
;
8669 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
8672 last_line_num
= sym
->n_desc
;
8674 strcpy(last_func_name
, func_name
);
8678 str
= stabstr_section
->data
+ sym
->n_strx
;
8680 if (incl_index
< INCLUDE_STACK_SIZE
) {
8681 incl_files
[incl_index
++] = str
;
8689 if (sym
->n_strx
== 0) {
8690 incl_index
= 0; /* end of translation unit */
8692 str
= stabstr_section
->data
+ sym
->n_strx
;
8693 /* do not add path */
8695 if (len
> 0 && str
[len
- 1] != '/')
8703 /* second pass: we try symtab symbols (no line number info) */
8706 Elf32_Sym
*sym
, *sym_end
;
8709 sym_end
= (Elf32_Sym
*)(symtab_section
->data
+ symtab_section
->data_offset
);
8710 for(sym
= (Elf32_Sym
*)symtab_section
->data
+ 1;
8713 type
= ELF32_ST_TYPE(sym
->st_info
);
8714 if (type
== STT_FUNC
) {
8715 if (wanted_pc
>= sym
->st_value
&&
8716 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
8717 pstrcpy(last_func_name
, sizeof(last_func_name
),
8718 strtab_section
->data
+ sym
->st_name
);
8724 /* did not find any info: */
8725 fprintf(stderr
, " ???\n");
8728 if (last_func_name
[0] != '\0') {
8729 fprintf(stderr
, " %s()", last_func_name
);
8731 if (incl_index
> 0) {
8732 fprintf(stderr
, " (%s:%d",
8733 incl_files
[incl_index
- 1], last_line_num
);
8734 for(i
= incl_index
- 2; i
>= 0; i
--)
8735 fprintf(stderr
, ", included from %s", incl_files
[i
]);
8736 fprintf(stderr
, ")");
8738 fprintf(stderr
, "\n");
8745 /* fix for glibc 2.1 */
8751 /* return the PC at frame level 'level'. Return non zero if not found */
8752 static int rt_get_caller_pc(unsigned long *paddr
,
8753 ucontext_t
*uc
, int level
)
8760 *paddr
= uc
->uc_mcontext
.mc_eip
;
8762 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
8767 fp
= uc
->uc_mcontext
.mc_ebp
;
8769 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
8771 for(i
=1;i
<level
;i
++) {
8772 /* XXX: check address validity with program info */
8773 if (fp
<= 0x1000 || fp
>= 0xc0000000)
8775 fp
= ((unsigned long *)fp
)[0];
8777 *paddr
= ((unsigned long *)fp
)[1];
8782 #error add arch specific rt_get_caller_pc()
8785 /* emit a run time error at position 'pc' */
8786 void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
8793 fprintf(stderr
, "Runtime error: ");
8794 vfprintf(stderr
, fmt
, ap
);
8795 fprintf(stderr
, "\n");
8796 for(i
=0;i
<num_callers
;i
++) {
8797 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
8800 fprintf(stderr
, "at ");
8802 fprintf(stderr
, "by ");
8809 /* signal handler for fatal errors */
8810 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
8812 ucontext_t
*uc
= puc
;
8816 switch(siginf
->si_code
) {
8819 rt_error(uc
, "division by zero");
8822 rt_error(uc
, "floating point exception");
8828 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
8829 rt_error(uc
, *rt_bound_error_msg
);
8831 rt_error(uc
, "dereferencing invalid pointer");
8834 rt_error(uc
, "illegal instruction");
8837 rt_error(uc
, "abort() called");
8840 rt_error(uc
, "caught signal %d", signum
);
8847 /* do all relocations (needed before using tcc_get_symbol()) */
8848 int tcc_relocate(TCCState
*s1
)
8855 tcc_add_runtime(s1
);
8857 relocate_common_syms();
8859 /* compute relocation address : section are relocated in place. We
8860 also alloc the bss space */
8861 for(i
= 1; i
< s1
->nb_sections
; i
++) {
8862 s
= s1
->sections
[i
];
8863 if (s
->sh_flags
& SHF_ALLOC
) {
8864 if (s
->sh_type
== SHT_NOBITS
)
8865 s
->data
= tcc_mallocz(s
->data_offset
);
8866 s
->sh_addr
= (unsigned long)s
->data
;
8870 relocate_syms(s1
, 1);
8872 if (s1
->nb_errors
!= 0)
8875 /* relocate each section */
8876 for(i
= 1; i
< s1
->nb_sections
; i
++) {
8877 s
= s1
->sections
[i
];
8879 relocate_section(s1
, s
);
8884 /* launch the compiled program with the given arguments */
8885 int tcc_run(TCCState
*s1
, int argc
, char **argv
)
8887 int (*prog_main
)(int, char **);
8889 if (tcc_relocate(s1
) < 0)
8892 prog_main
= tcc_get_symbol(s1
, "main");
8896 error("debug mode currently not available for Windows");
8898 struct sigaction sigact
;
8899 /* install TCC signal handlers to print debug info on fatal
8901 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
8902 sigact
.sa_sigaction
= sig_error
;
8903 sigemptyset(&sigact
.sa_mask
);
8904 sigaction(SIGFPE
, &sigact
, NULL
);
8905 sigaction(SIGILL
, &sigact
, NULL
);
8906 sigaction(SIGSEGV
, &sigact
, NULL
);
8907 sigaction(SIGBUS
, &sigact
, NULL
);
8908 sigaction(SIGABRT
, &sigact
, NULL
);
8912 #ifdef CONFIG_TCC_BCHECK
8913 if (do_bounds_check
) {
8914 void (*bound_init
)(void);
8916 /* set error function */
8917 rt_bound_error_msg
= (void *)tcc_get_symbol(s1
, "__bound_error_msg");
8919 /* XXX: use .init section so that it also work in binary ? */
8920 bound_init
= (void *)tcc_get_symbol(s1
, "__bound_init");
8924 return (*prog_main
)(argc
, argv
);
8927 TCCState
*tcc_new(void)
8934 s
= tcc_mallocz(sizeof(TCCState
));
8938 s
->output_type
= TCC_OUTPUT_MEMORY
;
8940 /* init isid table */
8942 isidnum_table
[i
] = isid(i
) || isnum(i
);
8944 /* add all tokens */
8946 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
8948 tok_ident
= TOK_IDENT
;
8957 ts
= tok_alloc(p
, r
- p
- 1);
8961 /* we add dummy defines for some special macros to speed up tests
8962 and to have working defined() */
8963 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
8964 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
8965 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
8966 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
8968 /* standard defines */
8969 tcc_define_symbol(s
, "__STDC__", NULL
);
8970 #if defined(TCC_TARGET_I386)
8971 tcc_define_symbol(s
, "__i386__", NULL
);
8974 tcc_define_symbol(s
, "__linux__", NULL
);
8975 tcc_define_symbol(s
, "linux", NULL
);
8977 /* tiny C specific defines */
8978 tcc_define_symbol(s
, "__TINYC__", NULL
);
8980 /* tiny C & gcc defines */
8981 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned int");
8982 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "int");
8983 tcc_define_symbol(s
, "__WCHAR_TYPE__", "int");
8985 /* default library paths */
8986 tcc_add_library_path(s
, "/usr/local/lib");
8987 tcc_add_library_path(s
, "/usr/lib");
8988 tcc_add_library_path(s
, "/lib");
8990 /* no section zero */
8991 dynarray_add((void ***)&s
->sections
, &s
->nb_sections
, NULL
);
8993 /* create standard sections */
8994 text_section
= new_section(s
, ".text", SHT_PROGBITS
, SHF_ALLOC
| SHF_EXECINSTR
);
8995 data_section
= new_section(s
, ".data", SHT_PROGBITS
, SHF_ALLOC
| SHF_WRITE
);
8996 bss_section
= new_section(s
, ".bss", SHT_NOBITS
, SHF_ALLOC
| SHF_WRITE
);
8998 /* symbols are always generated for linking stage */
8999 symtab_section
= new_symtab(s
, ".symtab", SHT_SYMTAB
, 0,
9001 ".hashtab", SHF_PRIVATE
);
9002 strtab_section
= symtab_section
->link
;
9004 /* private symbol table for dynamic symbols */
9005 s
->dynsymtab_section
= new_symtab(s
, ".dynsymtab", SHT_SYMTAB
, SHF_PRIVATE
,
9007 ".dynhashtab", SHF_PRIVATE
);
9011 void tcc_delete(TCCState
*s1
)
9015 /* free -D defines */
9019 n
= tok_ident
- TOK_IDENT
;
9020 for(i
= 0; i
< n
; i
++)
9021 tcc_free(table_ident
[i
]);
9022 tcc_free(table_ident
);
9024 /* free all sections */
9026 free_section(symtab_section
->hash
);
9028 free_section(s1
->dynsymtab_section
->hash
);
9029 free_section(s1
->dynsymtab_section
->link
);
9030 free_section(s1
->dynsymtab_section
);
9032 for(i
= 1; i
< s1
->nb_sections
; i
++)
9033 free_section(s1
->sections
[i
]);
9034 tcc_free(s1
->sections
);
9036 /* free loaded dlls array */
9037 for(i
= 0; i
< s1
->nb_loaded_dlls
; i
++)
9038 tcc_free(s1
->loaded_dlls
[i
]);
9039 tcc_free(s1
->loaded_dlls
);
9042 for(i
= 0; i
< s1
->nb_library_paths
; i
++)
9043 tcc_free(s1
->library_paths
[i
]);
9044 tcc_free(s1
->library_paths
);
9046 /* cached includes */
9047 for(i
= 0; i
< s1
->nb_cached_includes
; i
++)
9048 tcc_free(s1
->cached_includes
[i
]);
9049 tcc_free(s1
->cached_includes
);
9051 for(i
= 0; i
< s1
->nb_include_paths
; i
++)
9052 tcc_free(s1
->include_paths
[i
]);
9053 tcc_free(s1
->include_paths
);
9055 for(i
= 0; i
< s1
->nb_sysinclude_paths
; i
++)
9056 tcc_free(s1
->sysinclude_paths
[i
]);
9057 tcc_free(s1
->sysinclude_paths
);
9062 int tcc_add_include_path(TCCState
*s1
, const char *pathname
)
9066 pathname1
= tcc_strdup(pathname
);
9067 dynarray_add((void ***)&s1
->include_paths
, &s1
->nb_include_paths
, pathname1
);
9071 int tcc_add_sysinclude_path(TCCState
*s1
, const char *pathname
)
9075 pathname1
= tcc_strdup(pathname
);
9076 dynarray_add((void ***)&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
, pathname1
);
9080 static int tcc_add_file_internal(TCCState
*s1
, const char *filename
, int flags
)
9082 const char *ext
, *filename1
;
9085 BufferedFile
*saved_file
;
9087 /* find source file type with extension */
9088 filename1
= strrchr(filename
, '/');
9092 filename1
= filename
;
9093 ext
= strrchr(filename1
, '.');
9099 file
= tcc_open(s1
, filename
);
9101 if (flags
& AFF_PRINT_ERROR
) {
9102 error_noabort("file '%s' not found", filename
);
9108 if (!ext
|| !strcmp(ext
, "c")) {
9109 /* C file assumed */
9110 ret
= tcc_compile(s1
);
9112 #ifdef CONFIG_TCC_ASM
9113 if (!strcmp(ext
, "S")) {
9114 /* preprocessed assembler */
9115 ret
= tcc_assemble(s1
, 1);
9116 } else if (!strcmp(ext
, "s")) {
9117 /* non preprocessed assembler */
9118 ret
= tcc_assemble(s1
, 0);
9123 /* assume executable format: auto guess file type */
9124 if (read(fd
, &ehdr
, sizeof(ehdr
)) != sizeof(ehdr
)) {
9125 error_noabort("could not read header");
9128 lseek(fd
, 0, SEEK_SET
);
9130 if (ehdr
.e_ident
[0] == ELFMAG0
&&
9131 ehdr
.e_ident
[1] == ELFMAG1
&&
9132 ehdr
.e_ident
[2] == ELFMAG2
&&
9133 ehdr
.e_ident
[3] == ELFMAG3
) {
9134 file
->line_num
= 0; /* do not display line number if error */
9135 if (ehdr
.e_type
== ET_REL
) {
9136 ret
= tcc_load_object_file(s1
, fd
, 0);
9137 } else if (ehdr
.e_type
== ET_DYN
) {
9138 ret
= tcc_load_dll(s1
, fd
, filename
,
9139 (flags
& AFF_REFERENCED_DLL
) != 0);
9141 error_noabort("unrecognized ELF file");
9144 } else if (memcmp((char *)&ehdr
, ARMAG
, 8) == 0) {
9145 file
->line_num
= 0; /* do not display line number if error */
9146 ret
= tcc_load_archive(s1
, fd
);
9148 /* as GNU ld, consider it is an ld script if not recognized */
9149 ret
= tcc_load_ldscript(s1
);
9151 error_noabort("unrecognized file type");
9166 int tcc_add_file(TCCState
*s
, const char *filename
)
9168 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
);
9171 int tcc_add_library_path(TCCState
*s
, const char *pathname
)
9175 pathname1
= tcc_strdup(pathname
);
9176 dynarray_add((void ***)&s
->library_paths
, &s
->nb_library_paths
, pathname1
);
9180 /* find and load a dll. Return non zero if not found */
9181 /* XXX: add '-rpath' option support ? */
9182 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
)
9187 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
9188 snprintf(buf
, sizeof(buf
), "%s/%s",
9189 s
->library_paths
[i
], filename
);
9190 if (tcc_add_file_internal(s
, buf
, flags
) == 0)
9196 /* the library name is the same as the argument of the '-l' option */
9197 int tcc_add_library(TCCState
*s
, const char *libraryname
)
9203 /* first we look for the dynamic library if not static linking */
9204 if (!s
->static_link
) {
9205 snprintf(buf
, sizeof(buf
), "lib%s.so", libraryname
);
9206 /* if we output to memory, then we simply we dlopen(). */
9207 if (s
->output_type
== TCC_OUTPUT_MEMORY
) {
9208 /* Since the libc is already loaded, we don't need to load it again */
9209 if (!strcmp(libraryname
, "c"))
9211 h
= dlopen(buf
, RTLD_GLOBAL
| RTLD_LAZY
);
9215 if (tcc_add_dll(s
, buf
, 0) == 0)
9220 /* then we look for the static library */
9221 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
9222 snprintf(buf
, sizeof(buf
), "%s/lib%s.a",
9223 s
->library_paths
[i
], libraryname
);
9224 if (tcc_add_file_internal(s
, buf
, 0) == 0)
9230 int tcc_add_symbol(TCCState
*s
, const char *name
, unsigned long val
)
9232 add_elf_sym(symtab_section
, val
, 0,
9233 ELF32_ST_INFO(STB_GLOBAL
, STT_NOTYPE
),
9238 int tcc_set_output_type(TCCState
*s
, int output_type
)
9242 s
->output_type
= output_type
;
9245 /* default include paths */
9246 /* XXX: reverse order needed if -isystem support */
9247 tcc_add_sysinclude_path(s
, "/usr/local/include");
9248 tcc_add_sysinclude_path(s
, "/usr/include");
9249 snprintf(buf
, sizeof(buf
), "%s/include", tcc_lib_path
);
9250 tcc_add_sysinclude_path(s
, buf
);
9253 /* if bound checking, then add corresponding sections */
9254 #ifdef CONFIG_TCC_BCHECK
9255 if (do_bounds_check
) {
9257 tcc_define_symbol(s
, "__BOUNDS_CHECKING_ON", NULL
);
9258 /* create bounds sections */
9259 bounds_section
= new_section(s
, ".bounds",
9260 SHT_PROGBITS
, SHF_ALLOC
);
9261 lbounds_section
= new_section(s
, ".lbounds",
9262 SHT_PROGBITS
, SHF_ALLOC
);
9266 /* add debug sections */
9269 stab_section
= new_section(s
, ".stab", SHT_PROGBITS
, 0);
9270 stab_section
->sh_entsize
= sizeof(Stab_Sym
);
9271 stabstr_section
= new_section(s
, ".stabstr", SHT_STRTAB
, 0);
9272 put_elf_str(stabstr_section
, "");
9273 stab_section
->link
= stabstr_section
;
9274 /* put first entry */
9275 put_stabs("", 0, 0, 0, 0);
9278 /* add libc crt1/crti objects */
9279 if (output_type
== TCC_OUTPUT_EXE
||
9280 output_type
== TCC_OUTPUT_DLL
) {
9281 if (output_type
!= TCC_OUTPUT_DLL
)
9282 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crt1.o");
9283 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crti.o");
9288 #if !defined(LIBTCC)
9290 static int64_t getclock_us(void)
9295 return (tb
.time
* 1000LL + tb
.millitm
) * 1000LL;
9298 gettimeofday(&tv
, NULL
);
9299 return tv
.tv_sec
* 1000000LL + tv
.tv_usec
;
9305 printf("tcc version 0.9.16 - Tiny C Compiler - Copyright (C) 2001, 2002 Fabrice Bellard\n"
9306 "usage: tcc [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"
9307 " [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-static]\n"
9308 " [--] infile1 [infile2... --] [infile_args...]\n"
9310 "General options:\n"
9311 " -c compile only - generate an object file\n"
9312 " -o outfile set output filename\n"
9313 " -- allows multiples input files if no -o option given. Also\n"
9314 " separate input files from runtime arguments\n"
9315 " -Bdir set tcc internal library path\n"
9316 " -bench output compilation statistics\n"
9317 "Preprocessor options:\n"
9318 " -Idir add include path 'dir'\n"
9319 " -Dsym[=val] define 'sym' with value 'val'\n"
9320 " -Usym undefine 'sym'\n"
9322 " -Ldir add library path 'dir'\n"
9323 " -llib link with dynamic or static library 'lib'\n"
9324 " -shared generate a shared library\n"
9325 " -static static linking\n"
9326 " -r relocatable output\n"
9327 "Debugger options:\n"
9328 " -g generate runtime debug info\n"
9329 #ifdef CONFIG_TCC_BCHECK
9330 " -b compile with built-in memory and bounds checker (implies -g)\n"
9332 " -bt N show N callers in stack traces\n"
9336 #define TCC_OPTION_HAS_ARG 0x0001
9337 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
9339 typedef struct TCCOption
{
9367 TCC_OPTION_nostdinc
,
9368 TCC_OPTION_print_search_dirs
,
9369 TCC_OPTION_rdynamic
,
9372 static const TCCOption tcc_options
[] = {
9373 { "h", TCC_OPTION_HELP
, 0 },
9374 { "?", TCC_OPTION_HELP
, 0 },
9375 { "-", TCC_OPTION_MARKER
, 0 },
9376 { "I", TCC_OPTION_I
, TCC_OPTION_HAS_ARG
},
9377 { "D", TCC_OPTION_D
, TCC_OPTION_HAS_ARG
},
9378 { "U", TCC_OPTION_U
, TCC_OPTION_HAS_ARG
},
9379 { "L", TCC_OPTION_L
, TCC_OPTION_HAS_ARG
},
9380 { "B", TCC_OPTION_B
, TCC_OPTION_HAS_ARG
},
9381 { "l", TCC_OPTION_l
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9382 { "bench", TCC_OPTION_bench
, 0 },
9383 { "bt", TCC_OPTION_bt
, TCC_OPTION_HAS_ARG
},
9384 #ifdef CONFIG_TCC_BCHECK
9385 { "b", TCC_OPTION_b
, 0 },
9387 { "g", TCC_OPTION_g
, 0 },
9388 { "c", TCC_OPTION_c
, 0 },
9389 { "static", TCC_OPTION_static
, 0 },
9390 { "shared", TCC_OPTION_shared
, 0 },
9391 { "o", TCC_OPTION_o
, TCC_OPTION_HAS_ARG
},
9392 { "rdynamic", TCC_OPTION_rdynamic
, 0 }, /* currently ignored */
9393 { "r", TCC_OPTION_r
, 0 },
9394 { "W", TCC_OPTION_W
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9395 { "O", TCC_OPTION_O
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9396 { "m", TCC_OPTION_m
, TCC_OPTION_HAS_ARG
},
9397 { "f", TCC_OPTION_f
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9398 { "nostdinc", TCC_OPTION_nostdinc
, 0 },
9399 { "print-search-dirs", TCC_OPTION_print_search_dirs
, 0 },
9403 int main(int argc
, char **argv
)
9406 int optind
, output_type
, multiple_files
, i
, reloc_output
;
9409 int nb_files
, nb_libraries
, nb_objfiles
, dminus
, ret
;
9410 char objfilename
[1024];
9411 int64_t start_time
= 0;
9412 const TCCOption
*popt
;
9413 const char *optarg
, *p1
, *r1
, *outfile
;
9414 int print_search_dirs
;
9417 output_type
= TCC_OUTPUT_MEMORY
;
9427 print_search_dirs
= 0;
9429 if (optind
>= argc
) {
9430 if (nb_files
== 0 && !print_search_dirs
)
9437 /* add a new file */
9438 dynarray_add((void ***)&files
, &nb_files
, r
);
9439 if (!multiple_files
) {
9441 /* argv[0] will be this file */
9445 /* find option in table (match only the first chars */
9450 error("invalid option -- '%s'", r
);
9463 if (popt
->flags
& TCC_OPTION_HAS_ARG
) {
9464 if (*r1
!= '\0' || (popt
->flags
& TCC_OPTION_NOSEP
)) {
9468 error("argument to '%s' is missing", r
);
9469 optarg
= argv
[optind
++];
9477 switch(popt
->index
) {
9478 case TCC_OPTION_HELP
:
9482 case TCC_OPTION_MARKER
:
9483 /* '--' enables multiple files input and also ends several
9485 if (dminus
&& multiple_files
) {
9486 optind
--; /* argv[0] will be '--' */
9492 if (tcc_add_include_path(s
, optarg
) < 0)
9493 error("too many include paths");
9498 sym
= (char *)optarg
;
9499 value
= strchr(sym
, '=');
9504 tcc_define_symbol(s
, sym
, value
);
9508 tcc_undefine_symbol(s
, optarg
);
9511 tcc_add_library_path(s
, optarg
);
9514 /* set tcc utilities path (mainly for tcc development) */
9515 tcc_lib_path
= optarg
;
9518 dynarray_add((void ***)&files
, &nb_files
, r
);
9521 case TCC_OPTION_bench
:
9525 num_callers
= atoi(optarg
);
9527 #ifdef CONFIG_TCC_BCHECK
9529 do_bounds_check
= 1;
9538 output_type
= TCC_OUTPUT_OBJ
;
9540 case TCC_OPTION_static
:
9543 case TCC_OPTION_shared
:
9544 output_type
= TCC_OUTPUT_DLL
;
9551 /* generate a .o merging several output files */
9553 output_type
= TCC_OUTPUT_OBJ
;
9555 case TCC_OPTION_nostdinc
:
9558 case TCC_OPTION_print_search_dirs
:
9559 print_search_dirs
= 1;
9567 if (print_search_dirs
) {
9568 /* enough for Linux kernel */
9569 printf("install: %s/\n", tcc_lib_path
);
9573 nb_objfiles
= nb_files
- nb_libraries
;
9575 /* if outfile provided without other options, we output an
9577 if (outfile
&& output_type
== TCC_OUTPUT_MEMORY
)
9578 output_type
= TCC_OUTPUT_EXE
;
9580 /* check -c consistency : only single file handled. XXX: checks file type */
9581 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
9582 /* accepts only a single input file */
9583 if (nb_objfiles
!= 1)
9584 error("cannot specify multiple files with -c");
9585 if (nb_libraries
!= 0)
9586 error("cannot specify libraries with -c");
9589 /* compute default outfile name */
9590 if (output_type
!= TCC_OUTPUT_MEMORY
&& !outfile
) {
9591 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
9593 /* add .o extension */
9594 pstrcpy(objfilename
, sizeof(objfilename
) - 1, files
[0]);
9595 ext
= strrchr(objfilename
, '.');
9597 goto default_outfile
;
9598 strcpy(ext
+ 1, "o");
9601 pstrcpy(objfilename
, sizeof(objfilename
), "a.out");
9603 outfile
= objfilename
;
9607 start_time
= getclock_us();
9610 tcc_set_output_type(s
, output_type
);
9612 /* compile or add each files or library */
9613 for(i
= 0;i
< nb_files
; i
++) {
9614 const char *filename
;
9616 filename
= files
[i
];
9617 if (filename
[0] == '-') {
9618 if (tcc_add_library(s
, filename
+ 2) < 0)
9619 error("cannot find %s", filename
);
9621 if (tcc_add_file(s
, filename
) < 0) {
9628 /* free all files */
9633 total_time
= (double)(getclock_us() - start_time
) / 1000000.0;
9634 if (total_time
< 0.001)
9636 if (total_bytes
< 1)
9638 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
9639 tok_ident
- TOK_IDENT
, total_lines
, total_bytes
,
9640 total_time
, (int)(total_lines
/ total_time
),
9641 total_bytes
/ total_time
/ 1000000.0);
9644 if (s
->output_type
!= TCC_OUTPUT_MEMORY
) {
9645 tcc_output_file(s
, outfile
);
9648 ret
= tcc_run(s
, argc
- optind
, argv
+ optind
);
9651 /* XXX: cannot do it with bound checking because of the malloc hooks */
9652 if (!do_bounds_check
)
9657 printf("memory: %d bytes, max = %d bytes\n", mem_cur_size
, mem_max_size
);