2 * TCC - Tiny C Compiler
4 * Copyright (c) 2001, 2002, 2003 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
36 #include <sys/timeb.h>
40 #include <sys/ucontext.h>
44 #ifndef CONFIG_TCC_STATIC
52 /* preprocessor debug */
54 /* include file debug */
62 /* target selection */
63 //#define TCC_TARGET_I386 /* i386 code generator */
65 /* default target is I386 */
66 #if !defined(TCC_TARGET_I386)
67 #define TCC_TARGET_I386
70 #if !defined(WIN32) && !defined(TCC_UCLIBC)
71 #define CONFIG_TCC_BCHECK /* enable bound checking code */
74 /* define it to include assembler support */
75 #define CONFIG_TCC_ASM
77 /* path to find crt1.o, crti.o and crtn.o. Only needed when generating
78 executables or dlls */
79 #define CONFIG_TCC_CRT_PREFIX "/usr/lib"
81 #define INCLUDE_STACK_SIZE 32
82 #define IFDEF_STACK_SIZE 64
83 #define VSTACK_SIZE 64
84 #define STRING_MAX_SIZE 1024
86 #define TOK_HASH_SIZE 2048 /* must be a power of two */
87 #define TOK_ALLOC_INCR 512 /* must be a power of two */
88 #define TOK_STR_ALLOC_INCR_BITS 6
89 #define TOK_STR_ALLOC_INCR (1 << TOK_STR_ALLOC_INCR_BITS)
90 #define TOK_MAX_SIZE 4 /* token max size in int unit when stored in string */
92 /* token symbol management */
93 typedef struct TokenSym
{
94 struct TokenSym
*hash_next
;
95 struct Sym
*sym_define
; /* direct pointer to define */
96 struct Sym
*sym_label
; /* direct pointer to label */
97 struct Sym
*sym_struct
; /* direct pointer to structure */
98 struct Sym
*sym_identifier
; /* direct pointer to identifier */
99 int tok
; /* token number */
104 typedef struct CString
{
105 int size
; /* size in bytes */
106 void *data
; /* either 'char *' or 'int *' */
108 void *data_allocated
; /* if non NULL, data has been malloced */
111 /* type definition */
112 typedef struct CType
{
118 typedef union CValue
{
124 unsigned int ul
; /* address (should be unsigned long on 64 bit cpu) */
126 unsigned long long ull
;
127 struct CString
*cstr
;
133 typedef struct SValue
{
134 CType type
; /* type */
135 unsigned short r
; /* register + flags */
136 unsigned short r2
; /* second register, used for 'long long'
137 type. If not used, set to VT_CONST */
138 CValue c
; /* constant, if VT_CONST */
139 struct Sym
*sym
; /* symbol, if (VT_SYM | VT_CONST) */
142 /* symbol management */
144 int v
; /* symbol token */
145 int r
; /* associated register */
146 int c
; /* associated number */
147 CType type
; /* associated type */
148 struct Sym
*next
; /* next related symbol */
149 struct Sym
*prev
; /* prev symbol in stack */
150 struct Sym
*prev_tok
; /* previous symbol for this token */
153 /* section definition */
154 /* XXX: use directly ELF structure for parameters ? */
155 /* special flag to indicate that the section should not be linked to
157 #define SHF_PRIVATE 0x80000000
159 typedef struct Section
{
160 unsigned long data_offset
; /* current data offset */
161 unsigned char *data
; /* section data */
162 unsigned long data_allocated
; /* used for realloc() handling */
163 int sh_name
; /* elf section name (only used during output) */
164 int sh_num
; /* elf section number */
165 int sh_type
; /* elf section type */
166 int sh_flags
; /* elf section flags */
167 int sh_info
; /* elf section info */
168 int sh_addralign
; /* elf section alignment */
169 int sh_entsize
; /* elf entry size */
170 unsigned long sh_size
; /* section size (only used during output) */
171 unsigned long sh_addr
; /* address at which the section is relocated */
172 unsigned long sh_offset
; /* address at which the section is relocated */
173 int nb_hashed_syms
; /* used to resize the hash table */
174 struct Section
*link
; /* link to another section */
175 struct Section
*reloc
; /* corresponding section for relocation, if any */
176 struct Section
*hash
; /* hash table for symbols */
177 struct Section
*next
;
178 char name
[64]; /* section name */
181 typedef struct DLLReference
{
186 /* GNUC attribute definition */
187 typedef struct AttributeDef
{
190 unsigned char func_call
; /* FUNC_CDECL or FUNC_STDCALL */
193 #define SYM_STRUCT 0x40000000 /* struct/union/enum symbol space */
194 #define SYM_FIELD 0x20000000 /* struct/union field symbol space */
195 #define SYM_FIRST_ANOM (1 << (31 - VT_STRUCT_SHIFT)) /* first anonymous sym */
197 /* stored in 'Sym.c' field */
198 #define FUNC_NEW 1 /* ansi function prototype */
199 #define FUNC_OLD 2 /* old function prototype */
200 #define FUNC_ELLIPSIS 3 /* ansi function prototype with ... */
202 /* stored in 'Sym.r' field */
203 #define FUNC_CDECL 0 /* standard c call */
204 #define FUNC_STDCALL 1 /* pascal c call */
206 /* field 'Sym.t' for macros */
207 #define MACRO_OBJ 0 /* object like macro */
208 #define MACRO_FUNC 1 /* function like macro */
210 /* field 'Sym.r' for C labels */
211 #define LABEL_DEFINED 0 /* label is defined */
212 #define LABEL_FORWARD 1 /* label is forward defined */
213 #define LABEL_DECLARED 2 /* label is declared but never used */
215 /* type_decl() types */
216 #define TYPE_ABSTRACT 1 /* type without variable */
217 #define TYPE_DIRECT 2 /* type with variable */
219 #define IO_BUF_SIZE 8192
221 typedef struct BufferedFile
{
225 int line_num
; /* current line number - here to simplify code */
226 int ifndef_macro
; /* #ifndef macro / #endif search */
227 int ifndef_macro_saved
; /* saved ifndef_macro */
228 int *ifdef_stack_ptr
; /* ifdef_stack value at the start of the file */
229 char inc_type
; /* type of include */
230 char inc_filename
[512]; /* filename specified by the user */
231 char filename
[1024]; /* current filename - here to simplify code */
232 unsigned char buffer
[IO_BUF_SIZE
+ 1]; /* extra size for CH_EOB char */
235 #define CH_EOB '\\' /* end of buffer or '\0' char in file */
236 #define CH_EOF (-1) /* end of file */
238 /* parsing state (used to save parser state to reparse part of the
239 source several times) */
240 typedef struct ParseState
{
247 /* used to record tokens */
248 typedef struct TokenString
{
255 /* include file cache, used to find files faster and also to eliminate
256 inclusion if the include file is protected by #ifndef ... #endif */
257 typedef struct CachedInclude
{
259 char type
; /* '"' or '>' to give include type */
260 char filename
[1]; /* path specified in #include */
264 static struct BufferedFile
*file
;
267 static CString tokcstr
; /* current parsed string, if any */
268 /* additional informations about token */
269 static int tok_flags
;
270 #define TOK_FLAG_BOL 0x0001 /* beginning of line before */
271 #define TOK_FLAG_BOF 0x0002 /* beginning of file before */
272 #define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */
274 static int *macro_ptr
, *macro_ptr_allocated
;
275 static int *unget_saved_macro_ptr
;
276 static int unget_saved_buffer
[TOK_MAX_SIZE
+ 1];
277 static int unget_buffer_enabled
;
278 static int parse_flags
;
279 #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
280 #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
281 #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
282 token. line feed is also
285 static Section
*text_section
, *data_section
, *bss_section
; /* predefined sections */
286 static Section
*cur_text_section
; /* current section where function code is
288 /* bound check related sections */
289 static Section
*bounds_section
; /* contains global data bound description */
290 static Section
*lbounds_section
; /* contains local data bound description */
291 /* symbol sections */
292 static Section
*symtab_section
, *strtab_section
;
295 static Section
*stab_section
, *stabstr_section
;
297 /* loc : local variable index
298 ind : output code index
300 anon_sym: anonymous symbol index
302 static int rsym
, anon_sym
, ind
, loc
;
303 /* expression generation modifiers */
304 static int const_wanted
; /* true if constant wanted */
305 static int nocode_wanted
; /* true if no code generation wanted for an expression */
306 static int global_expr
; /* true if compound literals must be allocated
307 globally (used during initializers parsing */
308 static CType func_vt
; /* current function return type (used by return
311 static int last_line_num
, last_ind
, func_ind
; /* debug last line number and pc */
312 static int tok_ident
;
313 static TokenSym
**table_ident
;
314 static TokenSym
*hash_ident
[TOK_HASH_SIZE
];
315 static char token_buf
[STRING_MAX_SIZE
+ 1];
316 static char *funcname
;
317 static Sym
*global_stack
, *local_stack
;
318 static Sym
*define_stack
;
319 static Sym
*global_label_stack
, *local_label_stack
;
321 static SValue vstack
[VSTACK_SIZE
], *vtop
;
322 /* some predefined types */
323 static CType char_pointer_type
, func_old_type
, int_type
;
324 /* true if isid(c) || isnum(c) */
325 static unsigned char isidnum_table
[256];
327 /* compile with debug symbol (and use them if error during execution) */
328 static int do_debug
= 0;
330 /* compile with built-in memory and bounds checker */
331 static int do_bounds_check
= 0;
333 /* display benchmark infos */
335 static int do_bench
= 0;
337 static int total_lines
;
338 static int total_bytes
;
340 /* use GNU C extensions */
341 static int gnu_ext
= 1;
343 /* use Tiny C extensions */
344 static int tcc_ext
= 1;
346 /* max number of callers shown if error */
347 static int num_callers
= 6;
348 static const char **rt_bound_error_msg
;
350 /* XXX: get rid of this ASAP */
351 static struct TCCState
*tcc_state
;
353 /* give the path of the tcc libraries */
354 static const char *tcc_lib_path
= CONFIG_TCC_LIBDIR
"/tcc";
359 BufferedFile
**include_stack_ptr
;
360 int *ifdef_stack_ptr
;
362 /* include file handling */
363 char **include_paths
;
364 int nb_include_paths
;
365 char **sysinclude_paths
;
366 int nb_sysinclude_paths
;
367 CachedInclude
**cached_includes
;
368 int nb_cached_includes
;
370 char **library_paths
;
371 int nb_library_paths
;
373 /* array of all loaded dlls (including those referenced by loaded
375 DLLReference
**loaded_dlls
;
380 int nb_sections
; /* number of sections, including first dummy section */
385 unsigned long *got_offsets
;
387 /* give the correspondance from symtab indexes to dynsym indexes */
388 int *symtab_to_dynsym
;
390 /* temporary dynamic symbol sections (for dll loading) */
391 Section
*dynsymtab_section
;
392 /* exported dynamic symbol section */
395 int nostdinc
; /* if true, no standard headers are added */
396 int nostdlib
; /* if true, no standard libraries are added */
398 /* if true, static linking is performed */
401 /* if true, all symbols are exported */
404 /* if true, only link in referenced objects from archive */
407 /* warning switches */
408 int warn_write_strings
;
409 int warn_unsupported
;
414 void (*error_func
)(void *opaque
, const char *msg
);
415 int error_set_jmp_enabled
;
416 jmp_buf error_jmp_buf
;
419 /* tiny assembler state */
422 /* see include_stack_ptr */
423 BufferedFile
*include_stack
[INCLUDE_STACK_SIZE
];
425 /* see ifdef_stack_ptr */
426 int ifdef_stack
[IFDEF_STACK_SIZE
];
429 /* The current value can be: */
430 #define VT_VALMASK 0x00ff
431 #define VT_CONST 0x00f0 /* constant in vc
432 (must be first non register value) */
433 #define VT_LLOCAL 0x00f1 /* lvalue, offset on stack */
434 #define VT_LOCAL 0x00f2 /* offset on stack */
435 #define VT_CMP 0x00f3 /* the value is stored in processor flags (in vc) */
436 #define VT_JMP 0x00f4 /* value is the consequence of jmp true (even) */
437 #define VT_JMPI 0x00f5 /* value is the consequence of jmp false (odd) */
438 #define VT_LVAL 0x0100 /* var is an lvalue */
439 #define VT_SYM 0x0200 /* a symbol value is added */
440 #define VT_MUSTCAST 0x0400 /* value must be casted to be correct (used for
441 char/short stored in integer registers) */
442 #define VT_MUSTBOUND 0x0800 /* bound checking must be done before
443 dereferencing value */
444 #define VT_BOUNDED 0x8000 /* value is bounded. The address of the
445 bounding function call point is in vc */
446 #define VT_LVAL_BYTE 0x1000 /* lvalue is a byte */
447 #define VT_LVAL_SHORT 0x2000 /* lvalue is a short */
448 #define VT_LVAL_UNSIGNED 0x4000 /* lvalue is unsigned */
449 #define VT_LVAL_TYPE (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
452 #define VT_INT 0 /* integer type */
453 #define VT_BYTE 1 /* signed byte type */
454 #define VT_SHORT 2 /* short type */
455 #define VT_VOID 3 /* void type */
456 #define VT_PTR 4 /* pointer */
457 #define VT_ENUM 5 /* enum definition */
458 #define VT_FUNC 6 /* function type */
459 #define VT_STRUCT 7 /* struct/union definition */
460 #define VT_FLOAT 8 /* IEEE float */
461 #define VT_DOUBLE 9 /* IEEE double */
462 #define VT_LDOUBLE 10 /* IEEE long double */
463 #define VT_BOOL 11 /* ISOC99 boolean type */
464 #define VT_LLONG 12 /* 64 bit integer */
465 #define VT_LONG 13 /* long integer (NEVER USED as type, only
467 #define VT_BTYPE 0x000f /* mask for basic type */
468 #define VT_UNSIGNED 0x0010 /* unsigned type */
469 #define VT_ARRAY 0x0020 /* array type (also has VT_PTR) */
470 #define VT_BITFIELD 0x0040 /* bitfield modifier */
471 #define VT_CONSTANT 0x0800 /* const modifier */
472 #define VT_VOLATILE 0x1000 /* volatile modifier */
475 #define VT_EXTERN 0x00000080 /* extern definition */
476 #define VT_STATIC 0x00000100 /* static variable */
477 #define VT_TYPEDEF 0x00000200 /* typedef definition */
478 #define VT_INLINE 0x00000400 /* inline definition */
480 #define VT_STRUCT_SHIFT 16 /* shift for bitfield shift values */
482 /* type mask (except storage) */
483 #define VT_STORAGE (VT_EXTERN | VT_STATIC | VT_TYPEDEF | VT_INLINE)
484 #define VT_TYPE (~(VT_STORAGE))
488 /* warning: the following compare tokens depend on i386 asm code */
500 #define TOK_LAND 0xa0
504 #define TOK_MID 0xa3 /* inc/dec, to void constant */
506 #define TOK_UDIV 0xb0 /* unsigned division */
507 #define TOK_UMOD 0xb1 /* unsigned modulo */
508 #define TOK_PDIV 0xb2 /* fast division with undefined rounding for pointers */
509 #define TOK_CINT 0xb3 /* number in tokc */
510 #define TOK_CCHAR 0xb4 /* char constant in tokc */
511 #define TOK_STR 0xb5 /* pointer to string in tokc */
512 #define TOK_TWOSHARPS 0xb6 /* ## preprocessing token */
513 #define TOK_LCHAR 0xb7
514 #define TOK_LSTR 0xb8
515 #define TOK_CFLOAT 0xb9 /* float constant */
516 #define TOK_LINENUM 0xba /* line number info */
517 #define TOK_CDOUBLE 0xc0 /* double constant */
518 #define TOK_CLDOUBLE 0xc1 /* long double constant */
519 #define TOK_UMULL 0xc2 /* unsigned 32x32 -> 64 mul */
520 #define TOK_ADDC1 0xc3 /* add with carry generation */
521 #define TOK_ADDC2 0xc4 /* add with carry use */
522 #define TOK_SUBC1 0xc5 /* add with carry generation */
523 #define TOK_SUBC2 0xc6 /* add with carry use */
524 #define TOK_CUINT 0xc8 /* unsigned int constant */
525 #define TOK_CLLONG 0xc9 /* long long constant */
526 #define TOK_CULLONG 0xca /* unsigned long long constant */
527 #define TOK_ARROW 0xcb
528 #define TOK_DOTS 0xcc /* three dots */
529 #define TOK_SHR 0xcd /* unsigned shift right */
530 #define TOK_PPNUM 0xce /* preprocessor number */
532 #define TOK_SHL 0x01 /* shift left */
533 #define TOK_SAR 0x02 /* signed shift right */
535 /* assignement operators : normal operator or 0x80 */
536 #define TOK_A_MOD 0xa5
537 #define TOK_A_AND 0xa6
538 #define TOK_A_MUL 0xaa
539 #define TOK_A_ADD 0xab
540 #define TOK_A_SUB 0xad
541 #define TOK_A_DIV 0xaf
542 #define TOK_A_XOR 0xde
543 #define TOK_A_OR 0xfc
544 #define TOK_A_SHL 0x81
545 #define TOK_A_SAR 0x82
548 #define offsetof(type, field) ((size_t) &((type *)0)->field)
552 #define countof(tab) (sizeof(tab) / sizeof((tab)[0]))
555 /* WARNING: the content of this string encodes token numbers */
556 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";
558 #define TOK_EOF (-1) /* end of file */
559 #define TOK_LINEFEED 10 /* line feed */
561 /* all identificators and strings have token above that */
562 #define TOK_IDENT 256
564 /* only used for i386 asm opcodes definitions */
565 #define DEF_ASM(x) DEF(TOK_ASM_ ## x, #x)
568 DEF(TOK_ASM_ ## x ## b, #x "b") \
569 DEF(TOK_ASM_ ## x ## w, #x "w") \
570 DEF(TOK_ASM_ ## x ## l, #x "l") \
571 DEF(TOK_ASM_ ## x, #x)
574 DEF(TOK_ASM_ ## x ## w, #x "w") \
575 DEF(TOK_ASM_ ## x ## l, #x "l") \
576 DEF(TOK_ASM_ ## x, #x)
579 DEF(TOK_ASM_ ## f ## x ## s, "f" #x "s") \
580 DEF(TOK_ASM_ ## fi ## x ## l, "fi" #x "l") \
581 DEF(TOK_ASM_ ## f ## x ## l, "f" #x "l") \
582 DEF(TOK_ASM_ ## fi ## x ## s, "fi" #x "s")
585 DEF(TOK_ASM_ ## f ## x, "f" #x ) \
586 DEF(TOK_ASM_ ## f ## x ## p, "f" #x "p") \
589 #define DEF_ASMTEST(x) \
621 #define TOK_ASM_int TOK_INT
624 TOK_LAST
= TOK_IDENT
- 1,
625 #define DEF(id, str) id,
630 static const char tcc_keywords
[] =
631 #define DEF(id, str) str "\0"
636 #define TOK_UIDENT TOK_DEFINE
639 #define snprintf _snprintf
640 #define vsnprintf _vsnprintf
643 #if defined(WIN32) || defined(TCC_UCLIBC) || defined(__FreeBSD__)
644 /* currently incorrect */
645 long double strtold(const char *nptr
, char **endptr
)
647 return (long double)strtod(nptr
, endptr
);
649 float strtof(const char *nptr
, char **endptr
)
651 return (float)strtod(nptr
, endptr
);
654 /* XXX: need to define this to use them in non ISOC99 context */
655 extern float strtof (const char *__nptr
, char **__endptr
);
656 extern long double strtold (const char *__nptr
, char **__endptr
);
659 static char *pstrcpy(char *buf
, int buf_size
, const char *s
);
660 static char *pstrcat(char *buf
, int buf_size
, const char *s
);
662 static void next(void);
663 static void next_nomacro(void);
664 static void parse_expr_type(CType
*type
);
665 static void expr_type(CType
*type
);
666 static void unary_type(CType
*type
);
667 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
668 int case_reg
, int is_expr
);
669 static int expr_const(void);
670 static void expr_eq(void);
671 static void gexpr(void);
672 static void decl(int l
);
673 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
674 int first
, int size_only
);
675 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
676 int has_init
, int v
, int scope
);
678 void gv2(int rc1
, int rc2
);
679 void move_reg(int r
, int s
);
680 void save_regs(int n
);
681 void save_reg(int r
);
687 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
688 const int *macro_str
, int can_read_stream
);
689 int save_reg_forced(int r
);
691 void force_charshort_cast(int t
);
692 static void gen_cast(CType
*type
);
694 static Sym
*sym_find(int v
);
695 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
);
698 static int type_size(CType
*type
, int *a
);
699 static inline CType
*pointed_type(CType
*type
);
700 static int pointed_size(CType
*type
);
701 static int lvalue_type(int t
);
702 static int parse_btype(CType
*type
, AttributeDef
*ad
);
703 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
);
704 static int is_compatible_types(CType
*type1
, CType
*type2
);
706 void error(const char *fmt
, ...);
708 void vset(CType
*type
, int r
, int v
);
709 void type_to_str(char *buf
, int buf_size
,
710 CType
*type
, const char *varstr
);
711 char *get_tok_str(int v
, CValue
*cv
);
712 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
713 unsigned long offset
, unsigned long size
);
714 static Sym
*external_global_sym(int v
, CType
*type
, int r
);
716 /* section generation */
717 static void section_realloc(Section
*sec
, unsigned long new_size
);
718 static void *section_ptr_add(Section
*sec
, unsigned long size
);
719 static void put_extern_sym(Sym
*sym
, Section
*section
,
720 unsigned long value
, unsigned long size
);
721 static void greloc(Section
*s
, Sym
*sym
, unsigned long addr
, int type
);
722 static int put_elf_str(Section
*s
, const char *sym
);
723 static int put_elf_sym(Section
*s
,
724 unsigned long value
, unsigned long size
,
725 int info
, int other
, int shndx
, const char *name
);
726 static int add_elf_sym(Section
*s
, unsigned long value
, unsigned long size
,
727 int info
, int sh_num
, const char *name
);
728 static void put_elf_reloc(Section
*symtab
, Section
*s
, unsigned long offset
,
729 int type
, int symbol
);
730 static void put_stabs(const char *str
, int type
, int other
, int desc
,
731 unsigned long value
);
732 static void put_stabs_r(const char *str
, int type
, int other
, int desc
,
733 unsigned long value
, Section
*sec
, int sym_index
);
734 static void put_stabn(int type
, int other
, int desc
, int value
);
735 static void put_stabd(int type
, int other
, int desc
);
736 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
);
738 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
739 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
740 static int tcc_add_file_internal(TCCState
*s
, const char *filename
, int flags
);
744 #ifdef CONFIG_TCC_ASM
746 typedef struct ExprValue
{
751 #define MAX_ASM_OPERANDS 30
753 typedef struct ASMOperand
{
754 int id
; /* GCC 3 optionnal identifier (0 if number only supported */
756 char asm_str
[16]; /* computed asm string for operand */
757 SValue
*vt
; /* C value of the expression */
758 int ref_index
; /* if >= 0, gives reference to a output constraint */
759 int priority
; /* priority, used to assign registers */
760 int reg
; /* if >= 0, register number used for this operand */
761 int is_llong
; /* true if double register value */
764 static void asm_expr(TCCState
*s1
, ExprValue
*pe
);
765 static int asm_int_expr(TCCState
*s1
);
766 static int find_constraint(ASMOperand
*operands
, int nb_operands
,
767 const char *name
, const char **pp
);
769 static int tcc_assemble(TCCState
*s1
, int do_preprocess
);
773 static void asm_instr(void);
775 /* true if float/double/long double type */
776 static inline int is_float(int t
)
780 return bt
== VT_LDOUBLE
|| bt
== VT_DOUBLE
|| bt
== VT_FLOAT
;
783 #ifdef TCC_TARGET_I386
784 #include "i386-gen.c"
787 #ifdef CONFIG_TCC_STATIC
789 #define RTLD_LAZY 0x001
790 #define RTLD_NOW 0x002
791 #define RTLD_GLOBAL 0x100
792 #define RTLD_DEFAULT NULL
794 /* dummy function for profiling */
795 void *dlopen(const char *filename
, int flag
)
800 const char *dlerror(void)
805 typedef struct TCCSyms
{
810 #define TCCSYM(a) { #a, &a, },
812 /* add the symbol you want here if no dynamic linking is done */
813 static TCCSyms tcc_syms
[] = {
821 void *dlsym(void *handle
, const char *symbol
)
825 while (p
->str
!= NULL
) {
826 if (!strcmp(p
->str
, symbol
))
835 /********************************************************/
837 /* we use our own 'finite' function to avoid potential problems with
838 non standard math libs */
839 /* XXX: endianness dependent */
840 int ieee_finite(double d
)
843 return ((unsigned)((p
[1] | 0x800fffff) + 1)) >> 31;
846 /* copy a string and truncate it. */
847 static char *pstrcpy(char *buf
, int buf_size
, const char *s
)
854 q_end
= buf
+ buf_size
- 1;
866 /* strcat and truncate. */
867 static char *pstrcat(char *buf
, int buf_size
, const char *s
)
872 pstrcpy(buf
+ len
, buf_size
- len
, s
);
876 /* memory management */
882 static inline void tcc_free(void *ptr
)
885 mem_cur_size
-= malloc_usable_size(ptr
);
890 static void *tcc_malloc(unsigned long size
)
895 error("memory full");
897 mem_cur_size
+= malloc_usable_size(ptr
);
898 if (mem_cur_size
> mem_max_size
)
899 mem_max_size
= mem_cur_size
;
904 static void *tcc_mallocz(unsigned long size
)
907 ptr
= tcc_malloc(size
);
908 memset(ptr
, 0, size
);
912 static inline void *tcc_realloc(void *ptr
, unsigned long size
)
916 mem_cur_size
-= malloc_usable_size(ptr
);
918 ptr1
= realloc(ptr
, size
);
920 /* NOTE: count not correct if alloc error, but not critical */
921 mem_cur_size
+= malloc_usable_size(ptr1
);
922 if (mem_cur_size
> mem_max_size
)
923 mem_max_size
= mem_cur_size
;
928 static char *tcc_strdup(const char *str
)
931 ptr
= tcc_malloc(strlen(str
) + 1);
936 #define free(p) use_tcc_free(p)
937 #define malloc(s) use_tcc_malloc(s)
938 #define realloc(p, s) use_tcc_realloc(p, s)
940 static void dynarray_add(void ***ptab
, int *nb_ptr
, void *data
)
947 /* every power of two we double array size */
948 if ((nb
& (nb
- 1)) == 0) {
953 pp
= tcc_realloc(pp
, nb_alloc
* sizeof(void *));
955 error("memory full");
962 Section
*new_section(TCCState
*s1
, const char *name
, int sh_type
, int sh_flags
)
966 sec
= tcc_mallocz(sizeof(Section
));
967 pstrcpy(sec
->name
, sizeof(sec
->name
), name
);
968 sec
->sh_type
= sh_type
;
969 sec
->sh_flags
= sh_flags
;
976 sec
->sh_addralign
= 4;
979 sec
->sh_addralign
= 1;
982 sec
->sh_addralign
= 32; /* default conservative alignment */
986 /* only add section if not private */
987 if (!(sh_flags
& SHF_PRIVATE
)) {
988 sec
->sh_num
= s1
->nb_sections
;
989 dynarray_add((void ***)&s1
->sections
, &s1
->nb_sections
, sec
);
994 static void free_section(Section
*s
)
1000 /* realloc section and set its content to zero */
1001 static void section_realloc(Section
*sec
, unsigned long new_size
)
1004 unsigned char *data
;
1006 size
= sec
->data_allocated
;
1009 while (size
< new_size
)
1011 data
= tcc_realloc(sec
->data
, size
);
1013 error("memory full");
1014 memset(data
+ sec
->data_allocated
, 0, size
- sec
->data_allocated
);
1016 sec
->data_allocated
= size
;
1019 /* reserve at least 'size' bytes in section 'sec' from
1020 sec->data_offset. */
1021 static void *section_ptr_add(Section
*sec
, unsigned long size
)
1023 unsigned long offset
, offset1
;
1025 offset
= sec
->data_offset
;
1026 offset1
= offset
+ size
;
1027 if (offset1
> sec
->data_allocated
)
1028 section_realloc(sec
, offset1
);
1029 sec
->data_offset
= offset1
;
1030 return sec
->data
+ offset
;
1033 /* return a reference to a section, and create it if it does not
1035 Section
*find_section(TCCState
*s1
, const char *name
)
1039 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1040 sec
= s1
->sections
[i
];
1041 if (!strcmp(name
, sec
->name
))
1044 /* sections are created as PROGBITS */
1045 return new_section(s1
, name
, SHT_PROGBITS
, SHF_ALLOC
);
1048 /* update sym->c so that it points to an external symbol in section
1049 'section' with value 'value' */
1050 static void put_extern_sym(Sym
*sym
, Section
*section
,
1051 unsigned long value
, unsigned long size
)
1053 int sym_type
, sym_bind
, sh_num
, info
;
1058 sh_num
= section
->sh_num
;
1062 if ((sym
->type
.t
& VT_BTYPE
) == VT_FUNC
)
1063 sym_type
= STT_FUNC
;
1065 sym_type
= STT_OBJECT
;
1066 if (sym
->type
.t
& VT_STATIC
)
1067 sym_bind
= STB_LOCAL
;
1069 sym_bind
= STB_GLOBAL
;
1071 name
= get_tok_str(sym
->v
, NULL
);
1072 #ifdef CONFIG_TCC_BCHECK
1073 if (do_bounds_check
) {
1076 /* XXX: avoid doing that for statics ? */
1077 /* if bound checking is activated, we change some function
1078 names by adding the "__bound" prefix */
1081 /* XXX: we rely only on malloc hooks */
1093 strcpy(buf
, "__bound_");
1100 info
= ELF32_ST_INFO(sym_bind
, sym_type
);
1101 sym
->c
= add_elf_sym(symtab_section
, value
, size
, info
, sh_num
, name
);
1103 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
1104 esym
->st_value
= value
;
1105 esym
->st_size
= size
;
1106 esym
->st_shndx
= sh_num
;
1110 /* add a new relocation entry to symbol 'sym' in section 's' */
1111 static void greloc(Section
*s
, Sym
*sym
, unsigned long offset
, int type
)
1114 put_extern_sym(sym
, NULL
, 0, 0);
1115 /* now we can add ELF relocation info */
1116 put_elf_reloc(symtab_section
, s
, offset
, type
, sym
->c
);
1119 static inline int isid(int c
)
1121 return (c
>= 'a' && c
<= 'z') ||
1122 (c
>= 'A' && c
<= 'Z') ||
1126 static inline int isnum(int c
)
1128 return c
>= '0' && c
<= '9';
1131 static inline int isoct(int c
)
1133 return c
>= '0' && c
<= '7';
1136 static inline int toup(int c
)
1138 if (c
>= 'a' && c
<= 'z')
1139 return c
- 'a' + 'A';
1144 static void strcat_vprintf(char *buf
, int buf_size
, const char *fmt
, va_list ap
)
1148 vsnprintf(buf
+ len
, buf_size
- len
, fmt
, ap
);
1151 static void strcat_printf(char *buf
, int buf_size
, const char *fmt
, ...)
1155 strcat_vprintf(buf
, buf_size
, fmt
, ap
);
1159 void error1(TCCState
*s1
, int is_warning
, const char *fmt
, va_list ap
)
1166 for(f
= s1
->include_stack
; f
< s1
->include_stack_ptr
; f
++)
1167 strcat_printf(buf
, sizeof(buf
), "In file included from %s:%d:\n",
1168 (*f
)->filename
, (*f
)->line_num
);
1169 if (file
->line_num
> 0) {
1170 strcat_printf(buf
, sizeof(buf
),
1171 "%s:%d: ", file
->filename
, file
->line_num
);
1173 strcat_printf(buf
, sizeof(buf
),
1174 "%s: ", file
->filename
);
1177 strcat_printf(buf
, sizeof(buf
),
1181 strcat_printf(buf
, sizeof(buf
), "warning: ");
1182 strcat_vprintf(buf
, sizeof(buf
), fmt
, ap
);
1184 if (!s1
->error_func
) {
1185 /* default case: stderr */
1186 fprintf(stderr
, "%s\n", buf
);
1188 s1
->error_func(s1
->error_opaque
, buf
);
1190 if (!is_warning
|| s1
->warn_error
)
1195 void tcc_set_error_func(TCCState
*s
, void *error_opaque
,
1196 void (*error_func
)(void *opaque
, const char *msg
))
1198 s
->error_opaque
= error_opaque
;
1199 s
->error_func
= error_func
;
1203 /* error without aborting current compilation */
1204 void error_noabort(const char *fmt
, ...)
1206 TCCState
*s1
= tcc_state
;
1210 error1(s1
, 0, fmt
, ap
);
1214 void error(const char *fmt
, ...)
1216 TCCState
*s1
= tcc_state
;
1220 error1(s1
, 0, fmt
, ap
);
1222 /* better than nothing: in some cases, we accept to handle errors */
1223 if (s1
->error_set_jmp_enabled
) {
1224 longjmp(s1
->error_jmp_buf
, 1);
1226 /* XXX: eliminate this someday */
1231 void expect(const char *msg
)
1233 error("%s expected", msg
);
1236 void warning(const char *fmt
, ...)
1238 TCCState
*s1
= tcc_state
;
1242 error1(s1
, 1, fmt
, ap
);
1249 error("'%c' expected", c
);
1253 static void test_lvalue(void)
1255 if (!(vtop
->r
& VT_LVAL
))
1259 /* allocate a new token */
1260 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
1262 TokenSym
*ts
, **ptable
;
1265 if (tok_ident
>= SYM_FIRST_ANOM
)
1266 error("memory full");
1268 /* expand token table if needed */
1269 i
= tok_ident
- TOK_IDENT
;
1270 if ((i
% TOK_ALLOC_INCR
) == 0) {
1271 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
1273 error("memory full");
1274 table_ident
= ptable
;
1277 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
1278 table_ident
[i
] = ts
;
1279 ts
->tok
= tok_ident
++;
1280 ts
->sym_define
= NULL
;
1281 ts
->sym_label
= NULL
;
1282 ts
->sym_struct
= NULL
;
1283 ts
->sym_identifier
= NULL
;
1285 ts
->hash_next
= NULL
;
1286 memcpy(ts
->str
, str
, len
);
1287 ts
->str
[len
] = '\0';
1292 #define TOK_HASH_INIT 1
1293 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
1295 /* find a token and add it if not found */
1296 static TokenSym
*tok_alloc(const char *str
, int len
)
1298 TokenSym
*ts
, **pts
;
1304 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
1305 h
&= (TOK_HASH_SIZE
- 1);
1307 pts
= &hash_ident
[h
];
1312 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
1314 pts
= &(ts
->hash_next
);
1316 return tok_alloc_new(pts
, str
, len
);
1319 /* CString handling */
1321 static void cstr_realloc(CString
*cstr
, int new_size
)
1326 size
= cstr
->size_allocated
;
1328 size
= 8; /* no need to allocate a too small first string */
1329 while (size
< new_size
)
1331 data
= tcc_realloc(cstr
->data_allocated
, size
);
1333 error("memory full");
1334 cstr
->data_allocated
= data
;
1335 cstr
->size_allocated
= size
;
1340 static void cstr_ccat(CString
*cstr
, int ch
)
1343 size
= cstr
->size
+ 1;
1344 if (size
> cstr
->size_allocated
)
1345 cstr_realloc(cstr
, size
);
1346 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
1350 static void cstr_cat(CString
*cstr
, const char *str
)
1362 /* add a wide char */
1363 static void cstr_wccat(CString
*cstr
, int ch
)
1366 size
= cstr
->size
+ sizeof(int);
1367 if (size
> cstr
->size_allocated
)
1368 cstr_realloc(cstr
, size
);
1369 *(int *)(((unsigned char *)cstr
->data
) + size
- sizeof(int)) = ch
;
1373 static void cstr_new(CString
*cstr
)
1375 memset(cstr
, 0, sizeof(CString
));
1378 /* free string and reset it to NULL */
1379 static void cstr_free(CString
*cstr
)
1381 tcc_free(cstr
->data_allocated
);
1385 #define cstr_reset(cstr) cstr_free(cstr)
1387 static CString
*cstr_dup(CString
*cstr1
)
1392 cstr
= tcc_malloc(sizeof(CString
));
1395 cstr
->size_allocated
= size
;
1396 cstr
->data_allocated
= tcc_malloc(size
);
1397 cstr
->data
= cstr
->data_allocated
;
1398 memcpy(cstr
->data_allocated
, cstr1
->data_allocated
, size
);
1402 /* XXX: unicode ? */
1403 static void add_char(CString
*cstr
, int c
)
1405 if (c
== '\'' || c
== '\"' || c
== '\\') {
1406 /* XXX: could be more precise if char or string */
1407 cstr_ccat(cstr
, '\\');
1409 if (c
>= 32 && c
<= 126) {
1412 cstr_ccat(cstr
, '\\');
1414 cstr_ccat(cstr
, 'n');
1416 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
1417 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
1418 cstr_ccat(cstr
, '0' + (c
& 7));
1423 /* XXX: buffer overflow */
1424 /* XXX: float tokens */
1425 char *get_tok_str(int v
, CValue
*cv
)
1427 static char buf
[STRING_MAX_SIZE
+ 1];
1428 static CString cstr_buf
;
1434 /* NOTE: to go faster, we give a fixed buffer for small strings */
1435 cstr_reset(&cstr_buf
);
1436 cstr_buf
.data
= buf
;
1437 cstr_buf
.size_allocated
= sizeof(buf
);
1443 /* XXX: not quite exact, but only useful for testing */
1444 sprintf(p
, "%u", cv
->ui
);
1448 /* XXX: not quite exact, but only useful for testing */
1449 sprintf(p
, "%Lu", cv
->ull
);
1453 cstr_ccat(&cstr_buf
, '\'');
1454 add_char(&cstr_buf
, cv
->i
);
1455 cstr_ccat(&cstr_buf
, '\'');
1456 cstr_ccat(&cstr_buf
, '\0');
1460 len
= cstr
->size
- 1;
1462 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1463 cstr_ccat(&cstr_buf
, '\0');
1468 cstr_ccat(&cstr_buf
, '\"');
1470 len
= cstr
->size
- 1;
1472 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1474 len
= (cstr
->size
/ sizeof(int)) - 1;
1476 add_char(&cstr_buf
, ((int *)cstr
->data
)[i
]);
1478 cstr_ccat(&cstr_buf
, '\"');
1479 cstr_ccat(&cstr_buf
, '\0');
1488 return strcpy(p
, "<<=");
1490 return strcpy(p
, ">>=");
1492 if (v
< TOK_IDENT
) {
1493 /* search in two bytes table */
1507 } else if (v
< tok_ident
) {
1508 return table_ident
[v
- TOK_IDENT
]->str
;
1509 } else if (v
>= SYM_FIRST_ANOM
) {
1510 /* special name for anonymous symbol */
1511 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
1513 /* should never happen */
1518 return cstr_buf
.data
;
1521 /* push, without hashing */
1522 static Sym
*sym_push2(Sym
**ps
, int v
, int t
, int c
)
1525 s
= tcc_malloc(sizeof(Sym
));
1536 /* find a symbol and return its associated structure. 's' is the top
1537 of the symbol stack */
1538 static Sym
*sym_find2(Sym
*s
, int v
)
1548 /* structure lookup */
1549 static inline Sym
*struct_find(int v
)
1552 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1554 return table_ident
[v
]->sym_struct
;
1557 /* find an identifier */
1558 static inline Sym
*sym_find(int v
)
1561 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1563 return table_ident
[v
]->sym_identifier
;
1566 /* push a given symbol on the symbol stack */
1567 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
)
1576 s
= sym_push2(ps
, v
, type
->t
, c
);
1577 s
->type
.ref
= type
->ref
;
1579 /* don't record fields or anonymous symbols */
1581 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1582 /* record symbol in token array */
1583 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1585 ps
= &ts
->sym_struct
;
1587 ps
= &ts
->sym_identifier
;
1594 /* push a global identifier */
1595 static Sym
*global_identifier_push(int v
, int t
, int c
)
1598 s
= sym_push2(&global_stack
, v
, t
, c
);
1599 /* don't record anonymous symbol */
1600 if (v
< SYM_FIRST_ANOM
) {
1601 ps
= &table_ident
[v
- TOK_IDENT
]->sym_identifier
;
1602 /* modify the top most local identifier, so that
1603 sym_identifier will point to 's' when popped */
1605 ps
= &(*ps
)->prev_tok
;
1612 /* pop symbols until top reaches 'b' */
1613 static void sym_pop(Sym
**ptop
, Sym
*b
)
1623 /* remove symbol in token array */
1625 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1626 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1628 ps
= &ts
->sym_struct
;
1630 ps
= &ts
->sym_identifier
;
1641 BufferedFile
*tcc_open(TCCState
*s1
, const char *filename
)
1646 fd
= open(filename
, O_RDONLY
);
1649 bf
= tcc_malloc(sizeof(BufferedFile
));
1655 bf
->buf_ptr
= bf
->buffer
;
1656 bf
->buf_end
= bf
->buffer
;
1657 bf
->buffer
[0] = CH_EOB
; /* put eob symbol */
1658 pstrcpy(bf
->filename
, sizeof(bf
->filename
), filename
);
1660 bf
->ifndef_macro
= 0;
1661 bf
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
1662 // printf("opening '%s'\n", filename);
1666 void tcc_close(BufferedFile
*bf
)
1668 total_lines
+= bf
->line_num
;
1673 /* fill input buffer and peek next char */
1674 static int tcc_peekc_slow(BufferedFile
*bf
)
1677 /* only tries to read if really end of buffer */
1678 if (bf
->buf_ptr
>= bf
->buf_end
) {
1680 #if defined(PARSE_DEBUG)
1685 len
= read(bf
->fd
, bf
->buffer
, len
);
1692 bf
->buf_ptr
= bf
->buffer
;
1693 bf
->buf_end
= bf
->buffer
+ len
;
1694 *bf
->buf_end
= CH_EOB
;
1696 if (bf
->buf_ptr
< bf
->buf_end
) {
1697 return bf
->buf_ptr
[0];
1699 bf
->buf_ptr
= bf
->buf_end
;
1704 /* return the current character, handling end of block if necessary
1706 static int handle_eob(void)
1708 return tcc_peekc_slow(file
);
1711 /* read next char from current input file and handle end of input buffer */
1712 static inline void inp(void)
1714 ch
= *(++(file
->buf_ptr
));
1715 /* end of buffer/file handling */
1720 /* handle '\[\r]\n' */
1721 static void handle_stray(void)
1723 while (ch
== '\\') {
1728 } else if (ch
== '\r') {
1736 error("stray '\\' in program");
1741 /* skip the stray and handle the \\n case. Output an error if
1742 incorrect char after the stray */
1743 static int handle_stray1(uint8_t *p
)
1747 if (p
>= file
->buf_end
) {
1764 /* handle just the EOB case, but not stray */
1765 #define PEEKC_EOB(c, p)\
1776 /* handle the complicated stray case */
1777 #define PEEKC(c, p)\
1782 c = handle_stray1(p);\
1787 /* input with '\[\r]\n' handling. Note that this function cannot
1788 handle other characters after '\', so you cannot call it inside
1789 strings or comments */
1790 static void minp(void)
1798 /* single line C++ comments */
1799 static uint8_t *parse_line_comment(uint8_t *p
)
1806 if (c
== '\n' || c
== CH_EOF
) {
1808 } else if (c
== '\\') {
1813 } else if (c
== '\r') {
1828 static uint8_t *parse_comment(uint8_t *p
)
1834 /* fast skip loop */
1837 if (c
== '\n' || c
== '*' || c
== '\\')
1841 if (c
== '\n' || c
== '*' || c
== '\\')
1845 /* now we can handle all the cases */
1849 } else if (c
== '*') {
1855 } else if (c
== '/') {
1856 goto end_of_comment
;
1857 } else if (c
== '\\') {
1862 /* skip '\[\r]\n', otherwise just skip the stray */
1868 } else if (c
== '\r') {
1885 /* stray, eob or eof */
1890 error("unexpected end of file in comment");
1891 } else if (c
== '\\') {
1903 /* space exlcuding newline */
1904 static inline int is_space(int ch
)
1906 return ch
== ' ' || ch
== '\t' || ch
== '\v' || ch
== '\f' || ch
== '\r';
1909 static inline void skip_spaces(void)
1911 while (is_space(ch
))
1915 /* parse a string without interpreting escapes */
1916 static uint8_t *parse_pp_string(uint8_t *p
,
1917 int sep
, CString
*str
)
1925 } else if (c
== '\\') {
1930 unterminated_string
:
1931 /* XXX: indicate line number of start of string */
1932 error("missing terminating %c character", sep
);
1933 } else if (c
== '\\') {
1934 /* escape : just skip \[\r]\n */
1939 } else if (c
== '\r') {
1942 expect("'\n' after '\r'");
1945 } else if (c
== CH_EOF
) {
1946 goto unterminated_string
;
1949 cstr_ccat(str
, '\\');
1955 } else if (c
== '\n') {
1958 } else if (c
== '\r') {
1961 cstr_ccat(str
, '\r');
1977 /* skip block of text until #else, #elif or #endif. skip also pairs of
1979 void preprocess_skip(void)
1981 int a
, start_of_line
, c
;
2008 } else if (c
== '\\') {
2009 /* XXX: incorrect: should not give an error */
2010 ch
= file
->buf_ptr
[0];
2018 p
= parse_pp_string(p
, c
, NULL
);
2027 p
= parse_comment(p
);
2028 } else if (ch
== '/') {
2029 p
= parse_line_comment(p
);
2035 if (start_of_line
) {
2040 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
2042 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
2044 else if (tok
== TOK_ENDIF
)
2058 /* ParseState handling */
2060 /* XXX: currently, no include file info is stored. Thus, we cannot display
2061 accurate messages if the function or data definition spans multiple
2064 /* save current parse state in 's' */
2065 void save_parse_state(ParseState
*s
)
2067 s
->line_num
= file
->line_num
;
2068 s
->macro_ptr
= macro_ptr
;
2073 /* restore parse state from 's' */
2074 void restore_parse_state(ParseState
*s
)
2076 file
->line_num
= s
->line_num
;
2077 macro_ptr
= s
->macro_ptr
;
2082 /* return the number of additional 'ints' necessary to store the
2084 static inline int tok_ext_size(int t
)
2103 return LDOUBLE_SIZE
/ 4;
2109 /* token string handling */
2111 static inline void tok_str_new(TokenString
*s
)
2115 s
->allocated_len
= 0;
2116 s
->last_line_num
= -1;
2119 static void tok_str_free(int *str
)
2128 /* NOTE: we test zero separately so that GCC can generate a
2129 table for the following switch */
2144 /* XXX: use a macro to be portable on 64 bit ? */
2145 cstr
= (CString
*)p
[1];
2156 p
+= 1 + (LDOUBLE_SIZE
/ 4);
2166 static int *tok_str_realloc(TokenString
*s
)
2170 len
= s
->allocated_len
+ TOK_STR_ALLOC_INCR
;
2171 str
= tcc_realloc(s
->str
, len
* sizeof(int));
2173 error("memory full");
2174 s
->allocated_len
= len
;
2179 static void tok_str_add(TokenString
*s
, int t
)
2185 if (len
>= s
->allocated_len
)
2186 str
= tok_str_realloc(s
);
2191 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
2198 /* allocate space for worst case */
2199 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
2200 str
= tok_str_realloc(s
);
2209 str
[len
++] = cv
->tab
[0];
2214 str
[len
++] = (int)cstr_dup(cv
->cstr
);
2219 str
[len
++] = cv
->tab
[0];
2220 str
[len
++] = cv
->tab
[1];
2223 #if LDOUBLE_SIZE == 12
2224 str
[len
++] = cv
->tab
[0];
2225 str
[len
++] = cv
->tab
[1];
2226 str
[len
++] = cv
->tab
[2];
2228 #error add long double size support
2237 /* add the current parse token in token string 's' */
2238 static void tok_str_add_tok(TokenString
*s
)
2242 /* save line number info */
2243 if (file
->line_num
!= s
->last_line_num
) {
2244 s
->last_line_num
= file
->line_num
;
2245 cval
.i
= s
->last_line_num
;
2246 tok_str_add2(s
, TOK_LINENUM
, &cval
);
2248 tok_str_add2(s
, tok
, &tokc
);
2251 #if LDOUBLE_SIZE == 12
2252 #define LDOUBLE_GET(p, cv) \
2257 #error add long double size support
2261 /* get a token from an integer array and increment pointer
2262 accordingly. we code it as a macro to avoid pointer aliasing. */
2263 #define TOK_GET(t, p, cv) \
2285 case TOK_CLDOUBLE: \
2286 LDOUBLE_GET(p, cv); \
2287 p += LDOUBLE_SIZE / 4; \
2294 /* defines handling */
2295 static inline void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
2299 s
= sym_push2(&define_stack
, v
, macro_type
, (int)str
);
2300 s
->next
= first_arg
;
2301 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
2304 /* undefined a define symbol. Its name is just set to zero */
2305 static void define_undef(Sym
*s
)
2309 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2310 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2314 static inline Sym
*define_find(int v
)
2317 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2319 return table_ident
[v
]->sym_define
;
2322 /* free define stack until top reaches 'b' */
2323 static void free_defines(Sym
*b
)
2331 /* do not free args or predefined defines */
2333 tok_str_free((int *)top
->c
);
2335 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2336 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2344 static Sym
*label_find(int v
)
2347 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2349 return table_ident
[v
]->sym_label
;
2352 static Sym
*label_push(Sym
**ptop
, int v
, int flags
)
2355 s
= sym_push2(ptop
, v
, 0, 0);
2357 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
2358 if (ptop
== &global_label_stack
) {
2359 /* modify the top most local identifier, so that
2360 sym_identifier will point to 's' when popped */
2362 ps
= &(*ps
)->prev_tok
;
2369 /* pop labels until element last is reached. Look if any labels are
2370 undefined. Define symbols if '&&label' was used. */
2371 static void label_pop(Sym
**ptop
, Sym
*slast
)
2374 for(s
= *ptop
; s
!= slast
; s
= s1
) {
2376 if (s
->r
== LABEL_DECLARED
) {
2377 warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
2378 } else if (s
->r
== LABEL_FORWARD
) {
2379 error("label '%s' used but not defined",
2380 get_tok_str(s
->v
, NULL
));
2383 /* define corresponding symbol. A size of
2385 put_extern_sym(s
, cur_text_section
, (long)s
->next
, 1);
2389 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
2395 /* eval an expression for #if/#elif */
2396 static int expr_preprocess(void)
2402 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2403 next(); /* do macro subst */
2404 if (tok
== TOK_DEFINED
) {
2409 c
= define_find(tok
) != 0;
2414 } else if (tok
>= TOK_IDENT
) {
2415 /* if undefined macro */
2419 tok_str_add_tok(&str
);
2421 tok_str_add(&str
, -1); /* simulate end of file */
2422 tok_str_add(&str
, 0);
2423 /* now evaluate C constant expression */
2424 macro_ptr
= str
.str
;
2428 tok_str_free(str
.str
);
2432 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
2433 static void tok_print(int *str
)
2439 TOK_GET(t
, str
, cval
);
2442 printf(" %s", get_tok_str(t
, &cval
));
2448 /* parse after #define */
2449 static void parse_define(void)
2451 Sym
*s
, *first
, **ps
;
2452 int v
, t
, varg
, is_vaargs
, c
;
2457 error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
2458 /* XXX: should check if same macro (ANSI) */
2461 /* '(' must be just after macro definition for MACRO_FUNC */
2462 c
= file
->buf_ptr
[0];
2464 c
= handle_stray1(file
->buf_ptr
);
2469 while (tok
!= ')') {
2473 if (varg
== TOK_DOTS
) {
2474 varg
= TOK___VA_ARGS__
;
2476 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
2480 if (varg
< TOK_IDENT
)
2481 error("badly punctuated parameter list");
2482 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
2493 /* EOF testing necessary for '-D' handling */
2494 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2495 tok_str_add2(&str
, tok
, &tokc
);
2498 tok_str_add(&str
, 0);
2500 printf("define %s %d: ", get_tok_str(v
, NULL
), t
);
2503 define_push(v
, t
, str
.str
, first
);
2506 /* XXX: use a token or a hash table to accelerate matching ? */
2507 static CachedInclude
*search_cached_include(TCCState
*s1
,
2508 int type
, const char *filename
)
2513 for(i
= 0;i
< s1
->nb_cached_includes
; i
++) {
2514 e
= s1
->cached_includes
[i
];
2515 if (e
->type
== type
&& !strcmp(e
->filename
, filename
))
2521 static inline void add_cached_include(TCCState
*s1
, int type
,
2522 const char *filename
, int ifndef_macro
)
2526 if (search_cached_include(s1
, type
, filename
))
2529 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
2531 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
2535 strcpy(e
->filename
, filename
);
2536 e
->ifndef_macro
= ifndef_macro
;
2537 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
2540 /* is_bof is true if first non space token at beginning of file */
2541 static void preprocess(int is_bof
)
2543 TCCState
*s1
= tcc_state
;
2544 int size
, i
, c
, n
, saved_parse_flags
;
2545 char buf
[1024], *q
, *p
;
2551 saved_parse_flags
= parse_flags
;
2552 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
|
2553 PARSE_FLAG_LINEFEED
;
2563 s
= define_find(tok
);
2564 /* undefine symbol by putting an invalid name */
2569 ch
= file
->buf_ptr
[0];
2570 /* XXX: incorrect if comments : use next_nomacro with a special mode */
2575 } else if (ch
== '\"') {
2578 /* XXX: better stray handling */
2581 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
2582 if ((q
- buf
) < sizeof(buf
) - 1)
2589 /* eat all spaces and comments after include */
2590 /* XXX: slightly incorrect */
2591 while (ch1
!= '\n' && ch1
!= CH_EOF
)
2595 /* computed #include : either we have only strings or
2596 we have anything enclosed in '<>' */
2599 if (tok
== TOK_STR
) {
2600 while (tok
!= TOK_LINEFEED
) {
2601 if (tok
!= TOK_STR
) {
2603 error("'#include' expects \"FILENAME\" or <FILENAME>");
2605 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
2611 while (tok
!= TOK_LINEFEED
) {
2612 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
2616 /* check syntax and remove '<>' */
2617 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
2618 goto include_syntax
;
2619 memmove(buf
, buf
+ 1, len
- 2);
2620 buf
[len
- 2] = '\0';
2625 e
= search_cached_include(s1
, c
, buf
);
2626 if (e
&& define_find(e
->ifndef_macro
)) {
2627 /* no need to parse the include because the 'ifndef macro'
2630 printf("%s: skipping %s\n", file
->filename
, buf
);
2634 /* first search in current dir if "header.h" */
2636 p
= strrchr(file
->filename
, '/');
2638 size
= p
+ 1 - file
->filename
;
2639 if (size
> sizeof(buf1
) - 1)
2640 size
= sizeof(buf1
) - 1;
2641 memcpy(buf1
, file
->filename
, size
);
2643 pstrcat(buf1
, sizeof(buf1
), buf
);
2644 f
= tcc_open(s1
, buf1
);
2648 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
2649 error("#include recursion too deep");
2650 /* now search in all the include paths */
2651 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
2652 for(i
= 0; i
< n
; i
++) {
2654 if (i
< s1
->nb_include_paths
)
2655 path
= s1
->include_paths
[i
];
2657 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
2658 pstrcpy(buf1
, sizeof(buf1
), path
);
2659 pstrcat(buf1
, sizeof(buf1
), "/");
2660 pstrcat(buf1
, sizeof(buf1
), buf
);
2661 f
= tcc_open(s1
, buf1
);
2665 error("include file '%s' not found", buf
);
2669 printf("%s: including %s\n", file
->filename
, buf1
);
2672 pstrcpy(f
->inc_filename
, sizeof(f
->inc_filename
), buf
);
2673 /* push current file in stack */
2674 /* XXX: fix current line init */
2675 *s1
->include_stack_ptr
++ = file
;
2677 /* add include file debug info */
2679 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
2681 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
2682 ch
= file
->buf_ptr
[0];
2690 c
= expr_preprocess();
2696 if (tok
< TOK_IDENT
)
2697 error("invalid argument for '#if%sdef'", c
? "n" : "");
2701 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
2703 file
->ifndef_macro
= tok
;
2706 c
= (define_find(tok
) != 0) ^ c
;
2708 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
2709 error("memory full");
2710 *s1
->ifdef_stack_ptr
++ = c
;
2713 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
2714 error("#else without matching #if");
2715 if (s1
->ifdef_stack_ptr
[-1] & 2)
2716 error("#else after #else");
2717 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
2720 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
2721 error("#elif without matching #if");
2722 c
= s1
->ifdef_stack_ptr
[-1];
2724 error("#elif after #else");
2725 /* last #if/#elif expression was true: we skip */
2728 c
= expr_preprocess();
2729 s1
->ifdef_stack_ptr
[-1] = c
;
2739 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
2740 error("#endif without matching #if");
2741 s1
->ifdef_stack_ptr
--;
2742 /* '#ifndef macro' was at the start of file. Now we check if
2743 an '#endif' is exactly at the end of file */
2744 if (file
->ifndef_macro
&&
2745 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
2746 file
->ifndef_macro_saved
= file
->ifndef_macro
;
2747 /* need to set to zero to avoid false matches if another
2748 #ifndef at middle of file */
2749 file
->ifndef_macro
= 0;
2750 while (tok
!= TOK_LINEFEED
)
2752 tok_flags
|= TOK_FLAG_ENDIF
;
2758 if (tok
!= TOK_CINT
)
2760 file
->line_num
= tokc
.i
- 1; /* the line number will be incremented after */
2762 if (tok
!= TOK_LINEFEED
) {
2765 pstrcpy(file
->filename
, sizeof(file
->filename
),
2766 (char *)tokc
.cstr
->data
);
2772 ch
= file
->buf_ptr
[0];
2775 while (ch
!= '\n' && ch
!= CH_EOF
) {
2776 if ((q
- buf
) < sizeof(buf
) - 1)
2782 error("#error %s", buf
);
2784 warning("#warning %s", buf
);
2790 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_CINT
) {
2791 /* '!' is ignored to allow C scripts. numbers are ignored
2792 to emulate cpp behaviour */
2794 error("invalid preprocessing directive #%s", get_tok_str(tok
, &tokc
));
2798 /* ignore other preprocess commands or #! for C scripts */
2799 while (tok
!= TOK_LINEFEED
)
2802 parse_flags
= saved_parse_flags
;
2805 /* evaluate escape codes in a string. */
2806 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
2821 case '0': case '1': case '2': case '3':
2822 case '4': case '5': case '6': case '7':
2823 /* at most three octal digits */
2828 n
= n
* 8 + c
- '0';
2832 n
= n
* 8 + c
- '0';
2837 goto add_char_nonext
;
2843 if (c
>= 'a' && c
<= 'f')
2845 else if (c
>= 'A' && c
<= 'F')
2855 goto add_char_nonext
;
2879 goto invalid_escape
;
2889 error("invalid escaped char");
2895 cstr_ccat(outstr
, c
);
2897 cstr_wccat(outstr
, c
);
2899 /* add a trailing '\0' */
2901 cstr_ccat(outstr
, '\0');
2903 cstr_wccat(outstr
, '\0');
2906 /* we use 64 bit numbers */
2909 /* bn = (bn << shift) | or_val */
2910 void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
2914 for(i
=0;i
<BN_SIZE
;i
++) {
2916 bn
[i
] = (v
<< shift
) | or_val
;
2917 or_val
= v
>> (32 - shift
);
2921 void bn_zero(unsigned int *bn
)
2924 for(i
=0;i
<BN_SIZE
;i
++) {
2929 /* parse number in null terminated string 'p' and return it in the
2931 void parse_number(const char *p
)
2933 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
2935 unsigned int bn
[BN_SIZE
];
2946 goto float_frac_parse
;
2947 } else if (t
== '0') {
2948 if (ch
== 'x' || ch
== 'X') {
2952 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
2958 /* parse all digits. cannot check octal numbers at this stage
2959 because of floating point constants */
2961 if (ch
>= 'a' && ch
<= 'f')
2963 else if (ch
>= 'A' && ch
<= 'F')
2971 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
2973 error("number too long");
2979 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
2980 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
2982 /* NOTE: strtox should support that for hexa numbers, but
2983 non ISOC99 libcs do not support it, so we prefer to do
2985 /* hexadecimal or binary floats */
2986 /* XXX: handle overflows */
2998 } else if (t
>= 'a') {
3000 } else if (t
>= 'A') {
3005 bn_lshift(bn
, shift
, t
);
3012 if (t
>= 'a' && t
<= 'f') {
3014 } else if (t
>= 'A' && t
<= 'F') {
3016 } else if (t
>= '0' && t
<= '9') {
3022 error("invalid digit");
3023 bn_lshift(bn
, shift
, t
);
3028 if (ch
!= 'p' && ch
!= 'P')
3035 } else if (ch
== '-') {
3039 if (ch
< '0' || ch
> '9')
3040 expect("exponent digits");
3041 while (ch
>= '0' && ch
<= '9') {
3042 exp_val
= exp_val
* 10 + ch
- '0';
3045 exp_val
= exp_val
* s
;
3047 /* now we can generate the number */
3048 /* XXX: should patch directly float number */
3049 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
3050 d
= ldexp(d
, exp_val
- frac_bits
);
3055 /* float : should handle overflow */
3057 } else if (t
== 'L') {
3060 /* XXX: not large enough */
3061 tokc
.ld
= (long double)d
;
3067 /* decimal floats */
3069 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3074 while (ch
>= '0' && ch
<= '9') {
3075 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3081 if (ch
== 'e' || ch
== 'E') {
3082 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3086 if (ch
== '-' || ch
== '+') {
3087 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3092 if (ch
< '0' || ch
> '9')
3093 expect("exponent digits");
3094 while (ch
>= '0' && ch
<= '9') {
3095 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3107 tokc
.f
= strtof(token_buf
, NULL
);
3108 } else if (t
== 'L') {
3111 tokc
.ld
= strtold(token_buf
, NULL
);
3114 tokc
.d
= strtod(token_buf
, NULL
);
3118 unsigned long long n
, n1
;
3121 /* integer number */
3124 if (b
== 10 && *q
== '0') {
3131 /* no need for checks except for base 10 / 8 errors */
3134 } else if (t
>= 'a') {
3136 } else if (t
>= 'A') {
3141 error("invalid digit");
3145 /* detect overflow */
3146 /* XXX: this test is not reliable */
3148 error("integer constant overflow");
3151 /* XXX: not exactly ANSI compliant */
3152 if ((n
& 0xffffffff00000000LL
) != 0) {
3157 } else if (n
> 0x7fffffff) {
3168 error("three 'l's in integer constant");
3171 if (tok
== TOK_CINT
)
3173 else if (tok
== TOK_CUINT
)
3177 } else if (t
== 'U') {
3179 error("two 'u's in integer constant");
3181 if (tok
== TOK_CINT
)
3183 else if (tok
== TOK_CLLONG
)
3190 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
3198 #define PARSE2(c1, tok1, c2, tok2) \
3209 /* return next token without macro substitution */
3210 static inline void next_nomacro1(void)
3230 /* first look if it is in fact an end of buffer */
3231 if (p
>= file
->buf_end
) {
3235 if (p
>= file
->buf_end
)
3248 TCCState
*s1
= tcc_state
;
3249 if (parse_flags
& PARSE_FLAG_LINEFEED
) {
3251 } else if (s1
->include_stack_ptr
== s1
->include_stack
||
3252 !(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3253 /* no include left : end of file. */
3256 /* pop include file */
3258 /* test if previous '#endif' was after a #ifdef at
3260 if (tok_flags
& TOK_FLAG_ENDIF
) {
3262 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
3264 add_cached_include(s1
, file
->inc_type
, file
->inc_filename
,
3265 file
->ifndef_macro_saved
);
3268 /* add end of include file debug info */
3270 put_stabd(N_EINCL
, 0, 0);
3272 /* pop include stack */
3274 s1
->include_stack_ptr
--;
3275 file
= *s1
->include_stack_ptr
;
3283 if (parse_flags
& PARSE_FLAG_LINEFEED
) {
3287 tok_flags
|= TOK_FLAG_BOL
;
3296 if ((tok_flags
& TOK_FLAG_BOL
) &&
3297 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3299 preprocess(tok_flags
& TOK_FLAG_BOF
);
3305 tok
= TOK_TWOSHARPS
;
3312 case 'a': case 'b': case 'c': case 'd':
3313 case 'e': case 'f': case 'g': case 'h':
3314 case 'i': case 'j': case 'k': case 'l':
3315 case 'm': case 'n': case 'o': case 'p':
3316 case 'q': case 'r': case 's': case 't':
3317 case 'u': case 'v': case 'w': case 'x':
3319 case 'A': case 'B': case 'C': case 'D':
3320 case 'E': case 'F': case 'G': case 'H':
3321 case 'I': case 'J': case 'K':
3322 case 'M': case 'N': case 'O': case 'P':
3323 case 'Q': case 'R': case 'S': case 'T':
3324 case 'U': case 'V': case 'W': case 'X':
3330 h
= TOK_HASH_FUNC(h
, c
);
3334 if (!isidnum_table
[c
])
3336 h
= TOK_HASH_FUNC(h
, c
);
3343 /* fast case : no stray found, so we have the full token
3344 and we have already hashed it */
3346 h
&= (TOK_HASH_SIZE
- 1);
3347 pts
= &hash_ident
[h
];
3352 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
3354 pts
= &(ts
->hash_next
);
3356 ts
= tok_alloc_new(pts
, p1
, len
);
3360 cstr_reset(&tokcstr
);
3363 cstr_ccat(&tokcstr
, *p1
);
3369 while (isidnum_table
[c
]) {
3370 cstr_ccat(&tokcstr
, c
);
3373 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
3379 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
3381 goto parse_ident_fast
;
3384 if (c
== '\'' || c
== '\"') {
3388 cstr_reset(&tokcstr
);
3389 cstr_ccat(&tokcstr
, 'L');
3390 goto parse_ident_slow
;
3394 case '0': case '1': case '2': case '3':
3395 case '4': case '5': case '6': case '7':
3398 cstr_reset(&tokcstr
);
3399 /* after the first digit, accept digits, alpha, '.' or sign if
3400 prefixed by 'eEpP' */
3404 cstr_ccat(&tokcstr
, c
);
3406 if (!(isnum(c
) || isid(c
) || c
== '.' ||
3407 ((c
== '+' || c
== '-') &&
3408 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
3411 /* We add a trailing '\0' to ease parsing */
3412 cstr_ccat(&tokcstr
, '\0');
3413 tokc
.cstr
= &tokcstr
;
3417 /* special dot handling because it can also start a number */
3420 cstr_reset(&tokcstr
);
3421 cstr_ccat(&tokcstr
, '.');
3423 } else if (c
== '.') {
3443 /* parse the string */
3445 p
= parse_pp_string(p
, sep
, &str
);
3446 cstr_ccat(&str
, '\0');
3448 /* eval the escape (should be done as TOK_PPNUM) */
3449 cstr_reset(&tokcstr
);
3450 parse_escape_string(&tokcstr
, str
.data
, is_long
);
3455 /* XXX: make it portable */
3459 char_size
= sizeof(int);
3460 if (tokcstr
.size
<= char_size
)
3461 error("empty character constant");
3462 if (tokcstr
.size
> 2 * char_size
)
3463 warning("multi-character character constant");
3465 tokc
.i
= *(int8_t *)tokcstr
.data
;
3468 tokc
.i
= *(int *)tokcstr
.data
;
3472 tokc
.cstr
= &tokcstr
;
3486 } else if (c
== '<') {
3504 } else if (c
== '>') {
3522 } else if (c
== '=') {
3535 } else if (c
== '=') {
3548 } else if (c
== '=') {
3561 } else if (c
== '=') {
3564 } else if (c
== '>') {
3572 PARSE2('!', '!', '=', TOK_NE
)
3573 PARSE2('=', '=', '=', TOK_EQ
)
3574 PARSE2('*', '*', '=', TOK_A_MUL
)
3575 PARSE2('%', '%', '=', TOK_A_MOD
)
3576 PARSE2('^', '^', '=', TOK_A_XOR
)
3578 /* comments or operator */
3582 p
= parse_comment(p
);
3584 } else if (c
== '/') {
3585 p
= parse_line_comment(p
);
3587 } else if (c
== '=') {
3607 case '$': /* only used in assembler */
3612 error("unrecognized character \\x%02x", c
);
3617 #if defined(PARSE_DEBUG)
3618 printf("token = %s\n", get_tok_str(tok
, &tokc
));
3622 /* return next token without macro substitution. Can read input from
3624 static void next_nomacro(void)
3630 TOK_GET(tok
, macro_ptr
, tokc
);
3631 if (tok
== TOK_LINENUM
) {
3632 file
->line_num
= tokc
.i
;
3641 /* substitute args in macro_str and return allocated string */
3642 static int *macro_arg_subst(Sym
**nested_list
, int *macro_str
, Sym
*args
)
3644 int *st
, last_tok
, t
, notfirst
;
3653 TOK_GET(t
, macro_str
, cval
);
3658 TOK_GET(t
, macro_str
, cval
);
3661 s
= sym_find2(args
, t
);
3668 cstr_ccat(&cstr
, ' ');
3669 TOK_GET(t
, st
, cval
);
3670 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
3673 cstr_ccat(&cstr
, '\0');
3675 printf("stringize: %s\n", (char *)cstr
.data
);
3679 tok_str_add2(&str
, TOK_STR
, &cval
);
3682 tok_str_add2(&str
, t
, &cval
);
3684 } else if (t
>= TOK_IDENT
) {
3685 s
= sym_find2(args
, t
);
3688 /* if '##' is present before or after, no arg substitution */
3689 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
3690 /* special case for var arg macros : ## eats the
3691 ',' if empty VA_ARGS variable. */
3692 /* XXX: test of the ',' is not 100%
3693 reliable. should fix it to avoid security
3695 if (gnu_ext
&& s
->type
.t
&&
3696 last_tok
== TOK_TWOSHARPS
&&
3697 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
3699 /* suppress ',' '##' */
3702 /* suppress '##' and add variable */
3710 TOK_GET(t1
, st
, cval
);
3713 tok_str_add2(&str
, t1
, &cval
);
3717 /* NOTE: the stream cannot be read when macro
3718 substituing an argument */
3719 macro_subst(&str
, nested_list
, st
, 0);
3722 tok_str_add(&str
, t
);
3725 tok_str_add2(&str
, t
, &cval
);
3729 tok_str_add(&str
, 0);
3733 static char const ab_month_name
[12][4] =
3735 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3736 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3739 /* do macro substitution of current token with macro 's' and add
3740 result to (tok_str,tok_len). 'nested_list' is the list of all
3741 macros we got inside to avoid recursing. Return non zero if no
3742 substitution needs to be done */
3743 static int macro_subst_tok(TokenString
*tok_str
,
3744 Sym
**nested_list
, Sym
*s
, int can_read_stream
)
3746 Sym
*args
, *sa
, *sa1
;
3747 int mstr_allocated
, parlevel
, *mstr
, t
;
3753 /* if symbol is a macro, prepare substitution */
3755 /* special macros */
3756 if (tok
== TOK___LINE__
) {
3757 cval
.i
= file
->line_num
;
3758 tok_str_add2(tok_str
, TOK_CINT
, &cval
);
3759 } else if (tok
== TOK___FILE__
) {
3760 cstrval
= file
->filename
;
3762 tok_str_add2(tok_str
, TOK_STR
, &cval
);
3763 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
3769 tm
= localtime(&ti
);
3770 if (tok
== TOK___DATE__
) {
3771 snprintf(buf
, sizeof(buf
), "%s %2d %d",
3772 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
3774 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
3775 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
3780 cstr_cat(&cstr
, cstrval
);
3781 cstr_ccat(&cstr
, '\0');
3783 tok_str_add2(tok_str
, TOK_STR
, &cval
);
3788 if (s
->type
.t
== MACRO_FUNC
) {
3789 /* NOTE: we do not use next_nomacro to avoid eating the
3790 next token. XXX: find better solution */
3793 if (t
== 0 && can_read_stream
) {
3794 /* end of macro stream: we must look at the token
3795 after in the file */
3801 /* XXX: incorrect with comments */
3802 ch
= file
->buf_ptr
[0];
3803 while (is_space(ch
) || ch
== '\n')
3807 if (t
!= '(') /* no macro subst */
3810 /* argument macro */
3815 /* NOTE: empty args are allowed, except if no args */
3817 /* handle '()' case */
3818 if (!args
&& !sa
&& tok
== ')')
3821 error("macro '%s' used with too many args",
3822 get_tok_str(s
->v
, 0));
3825 /* NOTE: non zero sa->t indicates VA_ARGS */
3826 while ((parlevel
> 0 ||
3828 (tok
!= ',' || sa
->type
.t
))) &&
3832 else if (tok
== ')')
3834 tok_str_add2(&str
, tok
, &tokc
);
3837 tok_str_add(&str
, 0);
3838 sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, (int)str
.str
);
3841 /* special case for gcc var args: add an empty
3842 var arg argument if it is omitted */
3843 if (sa
&& sa
->type
.t
&& gnu_ext
)
3853 error("macro '%s' used with too few args",
3854 get_tok_str(s
->v
, 0));
3857 /* now subst each arg */
3858 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3863 tok_str_free((int *)sa
->c
);
3869 sym_push2(nested_list
, s
->v
, 0, 0);
3870 macro_subst(tok_str
, nested_list
, mstr
, 1);
3871 /* pop nested defined symbol */
3873 *nested_list
= sa1
->prev
;
3881 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3882 return the resulting string (which must be freed). */
3883 static inline int *macro_twosharps(const int *macro_str
)
3886 const int *macro_ptr1
, *start_macro_ptr
, *ptr
, *saved_macro_ptr
;
3888 const char *p1
, *p2
;
3890 TokenString macro_str1
;
3893 start_macro_ptr
= macro_str
;
3894 /* we search the first '##' */
3896 macro_ptr1
= macro_str
;
3897 TOK_GET(t
, macro_str
, cval
);
3898 /* nothing more to do if end of string */
3901 if (*macro_str
== TOK_TWOSHARPS
)
3905 /* we saw '##', so we need more processing to handle it */
3907 tok_str_new(¯o_str1
);
3911 /* add all tokens seen so far */
3912 for(ptr
= start_macro_ptr
; ptr
< macro_ptr1
;) {
3913 TOK_GET(t
, ptr
, cval
);
3914 tok_str_add2(¯o_str1
, t
, &cval
);
3916 saved_macro_ptr
= macro_ptr
;
3917 /* XXX: get rid of the use of macro_ptr here */
3918 macro_ptr
= (int *)macro_str
;
3920 while (*macro_ptr
== TOK_TWOSHARPS
) {
3922 macro_ptr1
= macro_ptr
;
3925 TOK_GET(t
, macro_ptr
, cval
);
3926 /* We concatenate the two tokens if we have an
3927 identifier or a preprocessing number */
3929 p1
= get_tok_str(tok
, &tokc
);
3930 cstr_cat(&cstr
, p1
);
3931 p2
= get_tok_str(t
, &cval
);
3932 cstr_cat(&cstr
, p2
);
3933 cstr_ccat(&cstr
, '\0');
3935 if ((tok
>= TOK_IDENT
|| tok
== TOK_PPNUM
) &&
3936 (t
>= TOK_IDENT
|| t
== TOK_PPNUM
)) {
3937 if (tok
== TOK_PPNUM
) {
3938 /* if number, then create a number token */
3939 /* NOTE: no need to allocate because
3940 tok_str_add2() does it */
3943 /* if identifier, we must do a test to
3944 validate we have a correct identifier */
3945 if (t
== TOK_PPNUM
) {
3955 if (!isnum(c
) && !isid(c
))
3959 ts
= tok_alloc(cstr
.data
, strlen(cstr
.data
));
3960 tok
= ts
->tok
; /* modify current token */
3963 const char *str
= cstr
.data
;
3964 const unsigned char *q
;
3966 /* we look for a valid token */
3967 /* XXX: do more extensive checks */
3968 if (!strcmp(str
, ">>=")) {
3970 } else if (!strcmp(str
, "<<=")) {
3972 } else if (strlen(str
) == 2) {
3973 /* search in two bytes table */
3978 if (q
[0] == str
[0] && q
[1] == str
[1])
3985 /* NOTE: because get_tok_str use a static buffer,
3988 p1
= get_tok_str(tok
, &tokc
);
3989 cstr_cat(&cstr
, p1
);
3990 cstr_ccat(&cstr
, '\0');
3991 p2
= get_tok_str(t
, &cval
);
3992 warning("pasting \"%s\" and \"%s\" does not give a valid preprocessing token", cstr
.data
, p2
);
3993 /* cannot merge tokens: just add them separately */
3994 tok_str_add2(¯o_str1
, tok
, &tokc
);
3995 /* XXX: free associated memory ? */
4002 tok_str_add2(¯o_str1
, tok
, &tokc
);
4007 macro_ptr
= (int *)saved_macro_ptr
;
4009 tok_str_add(¯o_str1
, 0);
4010 return macro_str1
.str
;
4014 /* do macro substitution of macro_str and add result to
4015 (tok_str,tok_len). 'nested_list' is the list of all macros we got
4016 inside to avoid recursing. */
4017 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
4018 const int *macro_str
, int can_read_stream
)
4021 int *saved_macro_ptr
, *macro_str1
;
4026 /* first scan for '##' operator handling */
4028 macro_str1
= macro_twosharps(ptr
);
4032 /* NOTE: ptr == NULL can only happen if tokens are read from
4033 file stream due to a macro function call */
4036 TOK_GET(t
, ptr
, cval
);
4041 /* if nested substitution, do nothing */
4042 if (sym_find2(*nested_list
, t
))
4044 saved_macro_ptr
= macro_ptr
;
4045 macro_ptr
= (int *)ptr
;
4047 ret
= macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
4048 ptr
= (int *)macro_ptr
;
4049 macro_ptr
= saved_macro_ptr
;
4054 tok_str_add2(tok_str
, t
, &cval
);
4058 tok_str_free(macro_str1
);
4061 /* return next token with macro substitution */
4062 static void next(void)
4064 Sym
*nested_list
, *s
;
4070 /* if not reading from macro substituted string, then try
4071 to substitute macros */
4072 if (tok
>= TOK_IDENT
&&
4073 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
4074 s
= define_find(tok
);
4076 /* we have a macro: we try to substitute */
4079 if (macro_subst_tok(&str
, &nested_list
, s
, 1) == 0) {
4080 /* substitution done, NOTE: maybe empty */
4081 tok_str_add(&str
, 0);
4082 macro_ptr
= str
.str
;
4083 macro_ptr_allocated
= str
.str
;
4090 /* end of macro or end of unget buffer */
4091 if (unget_buffer_enabled
) {
4092 macro_ptr
= unget_saved_macro_ptr
;
4093 unget_buffer_enabled
= 0;
4095 /* end of macro string: free it */
4096 tok_str_free(macro_ptr_allocated
);
4103 /* convert preprocessor tokens into C tokens */
4104 if (tok
== TOK_PPNUM
&&
4105 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
4106 parse_number((char *)tokc
.cstr
->data
);
4110 /* push back current token and set current token to 'last_tok'. Only
4111 identifier case handled for labels. */
4112 static inline void unget_tok(int last_tok
)
4116 unget_saved_macro_ptr
= macro_ptr
;
4117 unget_buffer_enabled
= 1;
4118 q
= unget_saved_buffer
;
4121 n
= tok_ext_size(tok
) - 1;
4124 *q
= 0; /* end of token string */
4129 void swap(int *p
, int *q
)
4137 void vsetc(CType
*type
, int r
, CValue
*vc
)
4141 if (vtop
>= vstack
+ VSTACK_SIZE
)
4142 error("memory full");
4143 /* cannot let cpu flags if other instruction are generated. Also
4144 avoid leaving VT_JMP anywhere except on the top of the stack
4145 because it would complicate the code generator. */
4146 if (vtop
>= vstack
) {
4147 v
= vtop
->r
& VT_VALMASK
;
4148 if (v
== VT_CMP
|| (v
& ~1) == VT_JMP
)
4154 vtop
->r2
= VT_CONST
;
4158 /* push integer constant */
4163 vsetc(&int_type
, VT_CONST
, &cval
);
4166 /* Return a static symbol pointing to a section */
4167 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
4168 unsigned long offset
, unsigned long size
)
4174 sym
= global_identifier_push(v
, type
->t
| VT_STATIC
, 0);
4175 sym
->type
.ref
= type
->ref
;
4176 sym
->r
= VT_CONST
| VT_SYM
;
4177 put_extern_sym(sym
, sec
, offset
, size
);
4181 /* push a reference to a section offset by adding a dummy symbol */
4182 static void vpush_ref(CType
*type
, Section
*sec
, unsigned long offset
, unsigned long size
)
4187 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4188 vtop
->sym
= get_sym_ref(type
, sec
, offset
, size
);
4191 /* define a new external reference to a symbol 'v' of type 'u' */
4192 static Sym
*external_global_sym(int v
, CType
*type
, int r
)
4198 /* push forward reference */
4199 s
= global_identifier_push(v
, type
->t
| VT_EXTERN
, 0);
4200 s
->type
.ref
= type
->ref
;
4201 s
->r
= r
| VT_CONST
| VT_SYM
;
4206 /* define a new external reference to a symbol 'v' of type 'u' */
4207 static Sym
*external_sym(int v
, CType
*type
, int r
)
4213 /* push forward reference */
4214 s
= sym_push(v
, type
, r
| VT_CONST
| VT_SYM
, 0);
4215 s
->type
.t
|= VT_EXTERN
;
4217 if (!is_compatible_types(&s
->type
, type
))
4218 error("incompatible types for redefinition of '%s'",
4219 get_tok_str(v
, NULL
));
4224 /* push a reference to global symbol v */
4225 static void vpush_global_sym(CType
*type
, int v
)
4230 sym
= external_global_sym(v
, type
, 0);
4232 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4236 void vset(CType
*type
, int r
, int v
)
4241 vsetc(type
, r
, &cval
);
4244 void vseti(int r
, int v
)
4260 void vpushv(SValue
*v
)
4262 if (vtop
>= vstack
+ VSTACK_SIZE
)
4263 error("memory full");
4273 /* save r to the memory stack, and mark it as being free */
4274 void save_reg(int r
)
4276 int l
, saved
, size
, align
;
4280 /* modify all stack values */
4283 for(p
=vstack
;p
<=vtop
;p
++) {
4284 if ((p
->r
& VT_VALMASK
) == r
||
4285 (p
->r2
& VT_VALMASK
) == r
) {
4286 /* must save value on stack if not already done */
4288 /* NOTE: must reload 'r' because r might be equal to r2 */
4289 r
= p
->r
& VT_VALMASK
;
4290 /* store register in the stack */
4292 if ((p
->r
& VT_LVAL
) ||
4293 (!is_float(type
->t
) && (type
->t
& VT_BTYPE
) != VT_LLONG
))
4295 size
= type_size(type
, &align
);
4296 loc
= (loc
- size
) & -align
;
4297 sv
.type
.t
= type
->t
;
4298 sv
.r
= VT_LOCAL
| VT_LVAL
;
4301 #ifdef TCC_TARGET_I386
4302 /* x86 specific: need to pop fp register ST0 if saved */
4303 if (r
== TREG_ST0
) {
4304 o(0xd9dd); /* fstp %st(1) */
4307 /* special long long case */
4308 if ((type
->t
& VT_BTYPE
) == VT_LLONG
) {
4315 /* mark that stack entry as being saved on the stack */
4316 if (p
->r
& VT_LVAL
) {
4317 /* also clear the bounded flag because the
4318 relocation address of the function was stored in
4320 p
->r
= (p
->r
& ~(VT_VALMASK
| VT_BOUNDED
)) | VT_LLOCAL
;
4322 p
->r
= lvalue_type(p
->type
.t
) | VT_LOCAL
;
4330 /* find a free register of class 'rc'. If none, save one register */
4336 /* find a free register */
4337 for(r
=0;r
<NB_REGS
;r
++) {
4338 if (reg_classes
[r
] & rc
) {
4339 for(p
=vstack
;p
<=vtop
;p
++) {
4340 if ((p
->r
& VT_VALMASK
) == r
||
4341 (p
->r2
& VT_VALMASK
) == r
)
4349 /* no register left : free the first one on the stack (VERY
4350 IMPORTANT to start from the bottom to ensure that we don't
4351 spill registers used in gen_opi()) */
4352 for(p
=vstack
;p
<=vtop
;p
++) {
4353 r
= p
->r
& VT_VALMASK
;
4354 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
))
4356 /* also look at second register (if long long) */
4357 r
= p
->r2
& VT_VALMASK
;
4358 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
)) {
4364 /* Should never comes here */
4368 /* save registers up to (vtop - n) stack entry */
4369 void save_regs(int n
)
4374 for(p
= vstack
;p
<= p1
; p
++) {
4375 r
= p
->r
& VT_VALMASK
;
4382 /* move register 's' to 'r', and flush previous value of r to memory
4384 void move_reg(int r
, int s
)
4397 /* get address of vtop (vtop MUST BE an lvalue) */
4400 vtop
->r
&= ~VT_LVAL
;
4401 /* tricky: if saved lvalue, then we can go back to lvalue */
4402 if ((vtop
->r
& VT_VALMASK
) == VT_LLOCAL
)
4403 vtop
->r
= (vtop
->r
& ~(VT_VALMASK
| VT_LVAL_TYPE
)) | VT_LOCAL
| VT_LVAL
;
4406 #ifdef CONFIG_TCC_BCHECK
4407 /* generate lvalue bound code */
4413 vtop
->r
&= ~VT_MUSTBOUND
;
4414 /* if lvalue, then use checking code before dereferencing */
4415 if (vtop
->r
& VT_LVAL
) {
4416 /* if not VT_BOUNDED value, then make one */
4417 if (!(vtop
->r
& VT_BOUNDED
)) {
4418 lval_type
= vtop
->r
& (VT_LVAL_TYPE
| VT_LVAL
);
4419 /* must save type because we must set it to int to get pointer */
4421 vtop
->type
.t
= VT_INT
;
4424 gen_bounded_ptr_add();
4425 vtop
->r
|= lval_type
;
4428 /* then check for dereferencing */
4429 gen_bounded_ptr_deref();
4434 /* store vtop a register belonging to class 'rc'. lvalues are
4435 converted to values. Cannot be used if cannot be converted to
4436 register value (such as structures). */
4439 int r
, r2
, rc2
, bit_pos
, bit_size
, size
, align
, i
;
4440 unsigned long long ll
;
4442 /* NOTE: get_reg can modify vstack[] */
4443 if (vtop
->type
.t
& VT_BITFIELD
) {
4444 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
4445 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
4446 /* remove bit field info to avoid loops */
4447 vtop
->type
.t
&= ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
4448 /* generate shifts */
4449 vpushi(32 - (bit_pos
+ bit_size
));
4451 vpushi(32 - bit_size
);
4452 /* NOTE: transformed to SHR if unsigned */
4456 if (is_float(vtop
->type
.t
) &&
4457 (vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4460 unsigned long offset
;
4462 /* XXX: unify with initializers handling ? */
4463 /* CPUs usually cannot use float constants, so we store them
4464 generically in data segment */
4465 size
= type_size(&vtop
->type
, &align
);
4466 offset
= (data_section
->data_offset
+ align
- 1) & -align
;
4467 data_section
->data_offset
= offset
;
4468 /* XXX: not portable yet */
4469 ptr
= section_ptr_add(data_section
, size
);
4472 ptr
[i
] = vtop
->c
.tab
[i
];
4473 sym
= get_sym_ref(&vtop
->type
, data_section
, offset
, size
<< 2);
4474 vtop
->r
|= VT_LVAL
| VT_SYM
;
4478 #ifdef CONFIG_TCC_BCHECK
4479 if (vtop
->r
& VT_MUSTBOUND
)
4483 r
= vtop
->r
& VT_VALMASK
;
4484 /* need to reload if:
4486 - lvalue (need to dereference pointer)
4487 - already a register, but not in the right class */
4488 if (r
>= VT_CONST
||
4489 (vtop
->r
& VT_LVAL
) ||
4490 !(reg_classes
[r
] & rc
) ||
4491 ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
&&
4492 !(reg_classes
[vtop
->r2
] & rc
))) {
4494 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
) {
4495 /* two register type load : expand to two words
4497 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4500 vtop
->c
.ui
= ll
; /* first word */
4502 vtop
->r
= r
; /* save register value */
4503 vpushi(ll
>> 32); /* second word */
4504 } else if (r
>= VT_CONST
||
4505 (vtop
->r
& VT_LVAL
)) {
4506 /* load from memory */
4509 vtop
[-1].r
= r
; /* save register value */
4510 /* increment pointer to get second word */
4511 vtop
->type
.t
= VT_INT
;
4517 /* move registers */
4520 vtop
[-1].r
= r
; /* save register value */
4521 vtop
->r
= vtop
[-1].r2
;
4523 /* allocate second register */
4530 /* write second register */
4532 } else if ((vtop
->r
& VT_LVAL
) && !is_float(vtop
->type
.t
)) {
4534 /* lvalue of scalar type : need to use lvalue type
4535 because of possible cast */
4538 /* compute memory access type */
4539 if (vtop
->r
& VT_LVAL_BYTE
)
4541 else if (vtop
->r
& VT_LVAL_SHORT
)
4543 if (vtop
->r
& VT_LVAL_UNSIGNED
)
4547 /* restore wanted type */
4550 /* one register type load */
4559 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
4560 void gv2(int rc1
, int rc2
)
4564 /* generate more generic register first. But VT_JMP or VT_CMP
4565 values must be generated first in all cases to avoid possible
4567 v
= vtop
[0].r
& VT_VALMASK
;
4568 if (v
!= VT_CMP
&& (v
& ~1) != VT_JMP
&& rc1
<= rc2
) {
4573 /* test if reload is needed for first register */
4574 if ((vtop
[-1].r
& VT_VALMASK
) >= VT_CONST
) {
4584 /* test if reload is needed for first register */
4585 if ((vtop
[0].r
& VT_VALMASK
) >= VT_CONST
) {
4591 /* expand long long on stack in two int registers */
4596 u
= vtop
->type
.t
& VT_UNSIGNED
;
4599 vtop
[0].r
= vtop
[-1].r2
;
4600 vtop
[0].r2
= VT_CONST
;
4601 vtop
[-1].r2
= VT_CONST
;
4602 vtop
[0].type
.t
= VT_INT
| u
;
4603 vtop
[-1].type
.t
= VT_INT
| u
;
4606 /* build a long long from two ints */
4609 gv2(RC_INT
, RC_INT
);
4610 vtop
[-1].r2
= vtop
[0].r
;
4611 vtop
[-1].type
.t
= t
;
4615 /* rotate n first stack elements to the bottom
4616 I1 ... In -> I2 ... In I1 [top is right]
4624 for(i
=-n
+1;i
!=0;i
++)
4625 vtop
[i
] = vtop
[i
+1];
4629 /* rotate n first stack elements to the top
4630 I1 ... In -> In I1 ... I(n-1) [top is right]
4638 for(i
= 0;i
< n
- 1; i
++)
4639 vtop
[-i
] = vtop
[-i
- 1];
4643 /* pop stack value */
4647 v
= vtop
->r
& VT_VALMASK
;
4648 #ifdef TCC_TARGET_I386
4649 /* for x86, we need to pop the FP stack */
4650 if (v
== TREG_ST0
&& !nocode_wanted
) {
4651 o(0xd9dd); /* fstp %st(1) */
4654 if (v
== VT_JMP
|| v
== VT_JMPI
) {
4655 /* need to put correct jump if && or || without test */
4661 /* convert stack entry to register and duplicate its value in another
4669 if ((t
& VT_BTYPE
) == VT_LLONG
) {
4676 /* stack: H L L1 H1 */
4684 /* duplicate value */
4695 load(r1
, &sv
); /* move r to r1 */
4697 /* duplicates value */
4702 /* generate CPU independent (unsigned) long long operations */
4703 void gen_opl(int op
)
4705 int t
, a
, b
, op1
, c
, i
;
4712 func
= TOK___divdi3
;
4715 func
= TOK___udivdi3
;
4718 func
= TOK___moddi3
;
4721 func
= TOK___umoddi3
;
4723 /* call generic long long function */
4724 vpush_global_sym(&func_old_type
, func
);
4729 vtop
->r2
= REG_LRET
;
4742 /* stack: L1 H1 L2 H2 */
4747 vtop
[-2] = vtop
[-3];
4750 /* stack: H1 H2 L1 L2 */
4756 /* stack: H1 H2 L1 L2 ML MH */
4759 /* stack: ML MH H1 H2 L1 L2 */
4763 /* stack: ML MH H1 L2 H2 L1 */
4768 /* stack: ML MH M1 M2 */
4771 } else if (op
== '+' || op
== '-') {
4772 /* XXX: add non carry method too (for MIPS or alpha) */
4778 /* stack: H1 H2 (L1 op L2) */
4781 gen_op(op1
+ 1); /* TOK_xxxC2 */
4784 /* stack: H1 H2 (L1 op L2) */
4787 /* stack: (L1 op L2) H1 H2 */
4789 /* stack: (L1 op L2) (H1 op H2) */
4797 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) {
4798 t
= vtop
[-1].type
.t
;
4802 /* stack: L H shift */
4804 /* constant: simpler */
4805 /* NOTE: all comments are for SHL. the other cases are
4806 done by swaping words */
4817 if (op
!= TOK_SAR
) {
4850 /* XXX: should provide a faster fallback on x86 ? */
4853 func
= TOK___sardi3
;
4856 func
= TOK___shrdi3
;
4859 func
= TOK___shldi3
;
4865 /* compare operations */
4871 /* stack: L1 H1 L2 H2 */
4873 vtop
[-1] = vtop
[-2];
4875 /* stack: L1 L2 H1 H2 */
4878 /* when values are equal, we need to compare low words. since
4879 the jump is inverted, we invert the test too. */
4882 else if (op1
== TOK_GT
)
4884 else if (op1
== TOK_ULT
)
4886 else if (op1
== TOK_UGT
)
4891 if (op1
!= TOK_NE
) {
4895 /* generate non equal test */
4896 /* XXX: NOT PORTABLE yet */
4900 #ifdef TCC_TARGET_I386
4901 b
= psym(0x850f, 0);
4903 error("not implemented");
4907 /* compare low. Always unsigned */
4911 else if (op1
== TOK_LE
)
4913 else if (op1
== TOK_GT
)
4915 else if (op1
== TOK_GE
)
4925 /* handle integer constant optimizations and various machine
4927 void gen_opic(int op
)
4934 /* currently, we cannot do computations with forward symbols */
4935 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
4936 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
4940 case '+': v1
->c
.i
+= fc
; break;
4941 case '-': v1
->c
.i
-= fc
; break;
4942 case '&': v1
->c
.i
&= fc
; break;
4943 case '^': v1
->c
.i
^= fc
; break;
4944 case '|': v1
->c
.i
|= fc
; break;
4945 case '*': v1
->c
.i
*= fc
; break;
4952 /* if division by zero, generate explicit division */
4955 error("division by zero in constant");
4959 default: v1
->c
.i
/= fc
; break;
4960 case '%': v1
->c
.i
%= fc
; break;
4961 case TOK_UDIV
: v1
->c
.i
= (unsigned)v1
->c
.i
/ fc
; break;
4962 case TOK_UMOD
: v1
->c
.i
= (unsigned)v1
->c
.i
% fc
; break;
4965 case TOK_SHL
: v1
->c
.i
<<= fc
; break;
4966 case TOK_SHR
: v1
->c
.i
= (unsigned)v1
->c
.i
>> fc
; break;
4967 case TOK_SAR
: v1
->c
.i
>>= fc
; break;
4969 case TOK_ULT
: v1
->c
.i
= (unsigned)v1
->c
.i
< (unsigned)fc
; break;
4970 case TOK_UGE
: v1
->c
.i
= (unsigned)v1
->c
.i
>= (unsigned)fc
; break;
4971 case TOK_EQ
: v1
->c
.i
= v1
->c
.i
== fc
; break;
4972 case TOK_NE
: v1
->c
.i
= v1
->c
.i
!= fc
; break;
4973 case TOK_ULE
: v1
->c
.i
= (unsigned)v1
->c
.i
<= (unsigned)fc
; break;
4974 case TOK_UGT
: v1
->c
.i
= (unsigned)v1
->c
.i
> (unsigned)fc
; break;
4975 case TOK_LT
: v1
->c
.i
= v1
->c
.i
< fc
; break;
4976 case TOK_GE
: v1
->c
.i
= v1
->c
.i
>= fc
; break;
4977 case TOK_LE
: v1
->c
.i
= v1
->c
.i
<= fc
; break;
4978 case TOK_GT
: v1
->c
.i
= v1
->c
.i
> fc
; break;
4980 case TOK_LAND
: v1
->c
.i
= v1
->c
.i
&& fc
; break;
4981 case TOK_LOR
: v1
->c
.i
= v1
->c
.i
|| fc
; break;
4987 /* if commutative ops, put c2 as constant */
4988 if (c1
&& (op
== '+' || op
== '&' || op
== '^' ||
4989 op
== '|' || op
== '*')) {
4994 if (c2
&& (((op
== '*' || op
== '/' || op
== TOK_UDIV
||
4997 ((op
== '+' || op
== '-' || op
== '|' || op
== '^' ||
4998 op
== TOK_SHL
|| op
== TOK_SHR
|| op
== TOK_SAR
) &&
5004 } else if (c2
&& (op
== '*' || op
== TOK_PDIV
|| op
== TOK_UDIV
)) {
5005 /* try to use shifts instead of muls or divs */
5006 if (fc
> 0 && (fc
& (fc
- 1)) == 0) {
5015 else if (op
== TOK_PDIV
)
5021 } else if (c2
&& (op
== '+' || op
== '-') &&
5022 (vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) ==
5023 (VT_CONST
| VT_SYM
)) {
5024 /* symbol + constant case */
5031 if (!nocode_wanted
) {
5032 /* call low level op generator */
5041 /* generate a floating point operation with constant propagation */
5042 void gen_opif(int op
)
5050 /* currently, we cannot do computations with forward symbols */
5051 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5052 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5054 if (v1
->type
.t
== VT_FLOAT
) {
5057 } else if (v1
->type
.t
== VT_DOUBLE
) {
5065 /* NOTE: we only do constant propagation if finite number (not
5066 NaN or infinity) (ANSI spec) */
5067 if (!ieee_finite(f1
) || !ieee_finite(f2
))
5071 case '+': f1
+= f2
; break;
5072 case '-': f1
-= f2
; break;
5073 case '*': f1
*= f2
; break;
5077 error("division by zero in constant");
5082 /* XXX: also handles tests ? */
5086 /* XXX: overflow test ? */
5087 if (v1
->type
.t
== VT_FLOAT
) {
5089 } else if (v1
->type
.t
== VT_DOUBLE
) {
5097 if (!nocode_wanted
) {
5105 static int pointed_size(CType
*type
)
5108 return type_size(pointed_type(type
), &align
);
5111 static inline int is_null_pointer(SValue
*p
)
5113 if ((p
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
5115 return ((p
->type
.t
& VT_BTYPE
) == VT_INT
&& p
->c
.i
== 0) ||
5116 ((p
->type
.t
& VT_BTYPE
) == VT_LLONG
&& p
->c
.ll
== 0);
5119 static inline int is_integer_btype(int bt
)
5121 return (bt
== VT_BYTE
|| bt
== VT_SHORT
||
5122 bt
== VT_INT
|| bt
== VT_LLONG
);
5125 /* check types for comparison or substraction of pointers */
5126 static void check_comparison_pointer_types(SValue
*p1
, SValue
*p2
, int op
)
5128 CType
*type1
, *type2
, tmp_type1
, tmp_type2
;
5131 /* null pointers are accepted for all comparisons as gcc */
5132 if (is_null_pointer(p1
) || is_null_pointer(p2
))
5136 bt1
= type1
->t
& VT_BTYPE
;
5137 bt2
= type2
->t
& VT_BTYPE
;
5138 /* accept comparison between pointer and integer with a warning */
5139 if ((is_integer_btype(bt1
) || is_integer_btype(bt2
)) && op
!= '-') {
5140 warning("comparison between pointer and integer");
5144 /* both must be pointers or implicit function pointers */
5145 if (bt1
== VT_PTR
) {
5146 type1
= pointed_type(type1
);
5147 } else if (bt1
!= VT_FUNC
)
5148 goto invalid_operands
;
5150 if (bt2
== VT_PTR
) {
5151 type2
= pointed_type(type2
);
5152 } else if (bt2
!= VT_FUNC
) {
5154 error("invalid operands to binary %s", get_tok_str(op
, NULL
));
5156 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
5157 (type2
->t
& VT_BTYPE
) == VT_VOID
)
5161 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5162 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5163 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
5164 /* gcc-like error if '-' is used */
5166 goto invalid_operands
;
5168 warning("comparison of distinct pointer types lacks a cast");
5172 /* generic gen_op: handles types problems */
5175 int u
, t1
, t2
, bt1
, bt2
, t
;
5178 t1
= vtop
[-1].type
.t
;
5179 t2
= vtop
[0].type
.t
;
5180 bt1
= t1
& VT_BTYPE
;
5181 bt2
= t2
& VT_BTYPE
;
5183 if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
5184 /* at least one operand is a pointer */
5185 /* relationnal op: must be both pointers */
5186 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5187 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5188 /* pointers are handled are unsigned */
5189 t
= VT_INT
| VT_UNSIGNED
;
5192 /* if both pointers, then it must be the '-' op */
5193 if (bt1
== VT_PTR
&& bt2
== VT_PTR
) {
5195 error("cannot use pointers here");
5196 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5197 /* XXX: check that types are compatible */
5198 u
= pointed_size(&vtop
[-1].type
);
5200 /* set to integer type */
5201 vtop
->type
.t
= VT_INT
;
5205 /* exactly one pointer : must be '+' or '-'. */
5206 if (op
!= '-' && op
!= '+')
5207 error("cannot use pointers here");
5208 /* Put pointer as first operand */
5209 if (bt2
== VT_PTR
) {
5213 type1
= vtop
[-1].type
;
5214 /* XXX: cast to int ? (long long case) */
5215 vpushi(pointed_size(&vtop
[-1].type
));
5217 #ifdef CONFIG_TCC_BCHECK
5218 /* if evaluating constant expression, no code should be
5219 generated, so no bound check */
5220 if (do_bounds_check
&& !const_wanted
) {
5221 /* if bounded pointers, we generate a special code to
5228 gen_bounded_ptr_add();
5234 /* put again type if gen_opic() swaped operands */
5237 } else if (is_float(bt1
) || is_float(bt2
)) {
5238 /* compute bigger type and do implicit casts */
5239 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
5241 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
5246 /* floats can only be used for a few operations */
5247 if (op
!= '+' && op
!= '-' && op
!= '*' && op
!= '/' &&
5248 (op
< TOK_ULT
|| op
> TOK_GT
))
5249 error("invalid operands for binary operation");
5251 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
5252 /* cast to biggest op */
5254 /* convert to unsigned if it does not fit in a long long */
5255 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
5256 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
5260 /* integer operations */
5262 /* convert to unsigned if it does not fit in an integer */
5263 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
5264 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
5267 /* XXX: currently, some unsigned operations are explicit, so
5268 we modify them here */
5269 if (t
& VT_UNSIGNED
) {
5276 else if (op
== TOK_LT
)
5278 else if (op
== TOK_GT
)
5280 else if (op
== TOK_LE
)
5282 else if (op
== TOK_GE
)
5289 /* special case for shifts and long long: we keep the shift as
5291 if (op
== TOK_SHR
|| op
== TOK_SAR
|| op
== TOK_SHL
)
5296 else if ((t
& VT_BTYPE
) == VT_LLONG
)
5300 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5301 /* relationnal op: the result is an int */
5302 vtop
->type
.t
= VT_INT
;
5309 /* generic itof for unsigned long long case */
5310 void gen_cvt_itof1(int t
)
5312 if ((vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
)) ==
5313 (VT_LLONG
| VT_UNSIGNED
)) {
5316 vpush_global_sym(&func_old_type
, TOK___ulltof
);
5317 else if (t
== VT_DOUBLE
)
5318 vpush_global_sym(&func_old_type
, TOK___ulltod
);
5320 vpush_global_sym(&func_old_type
, TOK___ulltold
);
5330 /* generic ftoi for unsigned long long case */
5331 void gen_cvt_ftoi1(int t
)
5335 if (t
== (VT_LLONG
| VT_UNSIGNED
)) {
5336 /* not handled natively */
5337 st
= vtop
->type
.t
& VT_BTYPE
;
5339 vpush_global_sym(&func_old_type
, TOK___fixunssfdi
);
5340 else if (st
== VT_DOUBLE
)
5341 vpush_global_sym(&func_old_type
, TOK___fixunsdfdi
);
5343 vpush_global_sym(&func_old_type
, TOK___fixunsxfdi
);
5348 vtop
->r2
= REG_LRET
;
5354 /* force char or short cast */
5355 void force_charshort_cast(int t
)
5359 /* XXX: add optimization if lvalue : just change type and offset */
5364 if (t
& VT_UNSIGNED
) {
5365 vpushi((1 << bits
) - 1);
5376 /* cast 'vtop' to 'type' */
5377 static void gen_cast(CType
*type
)
5379 int sbt
, dbt
, sf
, df
, c
;
5381 /* special delayed cast for char/short */
5382 /* XXX: in some cases (multiple cascaded casts), it may still
5384 if (vtop
->r
& VT_MUSTCAST
) {
5385 vtop
->r
&= ~VT_MUSTCAST
;
5386 force_charshort_cast(vtop
->type
.t
);
5389 dbt
= type
->t
& (VT_BTYPE
| VT_UNSIGNED
);
5390 sbt
= vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
);
5392 if (sbt
!= dbt
&& !nocode_wanted
) {
5395 c
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5397 /* convert from fp to fp */
5399 /* constant case: we can do it now */
5400 /* XXX: in ISOC, cannot do it if error in convert */
5401 if (dbt
== VT_FLOAT
&& sbt
== VT_DOUBLE
)
5402 vtop
->c
.f
= (float)vtop
->c
.d
;
5403 else if (dbt
== VT_FLOAT
&& sbt
== VT_LDOUBLE
)
5404 vtop
->c
.f
= (float)vtop
->c
.ld
;
5405 else if (dbt
== VT_DOUBLE
&& sbt
== VT_FLOAT
)
5406 vtop
->c
.d
= (double)vtop
->c
.f
;
5407 else if (dbt
== VT_DOUBLE
&& sbt
== VT_LDOUBLE
)
5408 vtop
->c
.d
= (double)vtop
->c
.ld
;
5409 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_FLOAT
)
5410 vtop
->c
.ld
= (long double)vtop
->c
.f
;
5411 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_DOUBLE
)
5412 vtop
->c
.ld
= (long double)vtop
->c
.d
;
5414 /* non constant case: generate code */
5418 /* convert int to fp */
5421 case VT_LLONG
| VT_UNSIGNED
:
5423 /* XXX: add const cases for long long */
5425 case VT_INT
| VT_UNSIGNED
:
5427 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.ui
; break;
5428 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.ui
; break;
5429 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.ui
; break;
5434 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.i
; break;
5435 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.i
; break;
5436 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.i
; break;
5445 /* convert fp to int */
5446 /* we handle char/short/etc... with generic code */
5447 if (dbt
!= (VT_INT
| VT_UNSIGNED
) &&
5448 dbt
!= (VT_LLONG
| VT_UNSIGNED
) &&
5453 case VT_LLONG
| VT_UNSIGNED
:
5455 /* XXX: add const cases for long long */
5457 case VT_INT
| VT_UNSIGNED
:
5459 case VT_FLOAT
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5460 case VT_DOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5461 case VT_LDOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5467 case VT_FLOAT
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5468 case VT_DOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5469 case VT_LDOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5477 if (dbt
== VT_INT
&& (type
->t
& (VT_BTYPE
| VT_UNSIGNED
)) != dbt
) {
5478 /* additional cast for char/short/bool... */
5482 } else if ((dbt
& VT_BTYPE
) == VT_LLONG
) {
5483 if ((sbt
& VT_BTYPE
) != VT_LLONG
) {
5484 /* scalar to long long */
5486 if (sbt
== (VT_INT
| VT_UNSIGNED
))
5487 vtop
->c
.ll
= vtop
->c
.ui
;
5489 vtop
->c
.ll
= vtop
->c
.i
;
5491 /* machine independent conversion */
5493 /* generate high word */
5494 if (sbt
== (VT_INT
| VT_UNSIGNED
)) {
5502 /* patch second register */
5503 vtop
[-1].r2
= vtop
->r
;
5507 } else if (dbt
== VT_BOOL
) {
5508 /* scalar to bool */
5511 } else if ((dbt
& VT_BTYPE
) == VT_BYTE
||
5512 (dbt
& VT_BTYPE
) == VT_SHORT
) {
5513 force_charshort_cast(dbt
);
5514 } else if ((dbt
& VT_BTYPE
) == VT_INT
) {
5516 if (sbt
== VT_LLONG
) {
5517 /* from long long: just take low order word */
5521 /* if lvalue and single word type, nothing to do because
5522 the lvalue already contains the real type size (see
5523 VT_LVAL_xxx constants) */
5529 /* return type size. Put alignment at 'a' */
5530 static int type_size(CType
*type
, int *a
)
5535 bt
= type
->t
& VT_BTYPE
;
5536 if (bt
== VT_STRUCT
) {
5541 } else if (bt
== VT_PTR
) {
5542 if (type
->t
& VT_ARRAY
) {
5544 return type_size(&s
->type
, a
) * s
->c
;
5549 } else if (bt
== VT_LDOUBLE
) {
5551 return LDOUBLE_SIZE
;
5552 } else if (bt
== VT_DOUBLE
|| bt
== VT_LLONG
) {
5553 *a
= 4; /* XXX: i386 specific */
5555 } else if (bt
== VT_INT
|| bt
== VT_ENUM
|| bt
== VT_FLOAT
) {
5558 } else if (bt
== VT_SHORT
) {
5562 /* char, void, function, _Bool */
5568 /* return the pointed type of t */
5569 static inline CType
*pointed_type(CType
*type
)
5571 return &type
->ref
->type
;
5574 /* modify type so that its it is a pointer to type. */
5575 static void mk_pointer(CType
*type
)
5578 s
= sym_push(SYM_FIELD
, type
, 0, -1);
5579 type
->t
= VT_PTR
| (type
->t
& ~VT_TYPE
);
5583 /* compare function types. OLD functions match any new functions */
5584 static int is_compatible_func(CType
*type1
, CType
*type2
)
5590 if (!is_compatible_types(&s1
->type
, &s2
->type
))
5592 /* XXX: not complete */
5593 if (s1
->c
== FUNC_OLD
|| s2
->c
== FUNC_OLD
)
5597 while (s1
!= NULL
) {
5600 if (!is_compatible_types(&s1
->type
, &s2
->type
))
5610 /* return true if type1 and type2 are exactly the same (including
5613 - enums are not checked as gcc __builtin_types_compatible_p ()
5615 static int is_compatible_types(CType
*type1
, CType
*type2
)
5619 t1
= type1
->t
& VT_TYPE
;
5620 t2
= type2
->t
& VT_TYPE
;
5621 /* XXX: bitfields ? */
5624 /* test more complicated cases */
5625 bt1
= t1
& VT_BTYPE
;
5626 if (bt1
== VT_PTR
) {
5627 type1
= pointed_type(type1
);
5628 type2
= pointed_type(type2
);
5629 return is_compatible_types(type1
, type2
);
5630 } else if (bt1
== VT_STRUCT
) {
5631 return (type1
->ref
== type2
->ref
);
5632 } else if (bt1
== VT_FUNC
) {
5633 return is_compatible_func(type1
, type2
);
5639 /* print a type. If 'varstr' is not NULL, then the variable is also
5640 printed in the type */
5642 /* XXX: add array and function pointers */
5643 void type_to_str(char *buf
, int buf_size
,
5644 CType
*type
, const char *varstr
)
5651 t
= type
->t
& VT_TYPE
;
5654 if (t
& VT_CONSTANT
)
5655 pstrcat(buf
, buf_size
, "const ");
5656 if (t
& VT_VOLATILE
)
5657 pstrcat(buf
, buf_size
, "volatile ");
5658 if (t
& VT_UNSIGNED
)
5659 pstrcat(buf
, buf_size
, "unsigned ");
5689 tstr
= "long double";
5691 pstrcat(buf
, buf_size
, tstr
);
5695 if (bt
== VT_STRUCT
)
5699 pstrcat(buf
, buf_size
, tstr
);
5700 v
= type
->ref
->v
& ~SYM_STRUCT
;
5701 if (v
>= SYM_FIRST_ANOM
)
5702 pstrcat(buf
, buf_size
, "<anonymous>");
5704 pstrcat(buf
, buf_size
, get_tok_str(v
, NULL
));
5708 type_to_str(buf
, buf_size
, &s
->type
, varstr
);
5709 pstrcat(buf
, buf_size
, "(");
5711 while (sa
!= NULL
) {
5712 type_to_str(buf1
, sizeof(buf1
), &sa
->type
, NULL
);
5713 pstrcat(buf
, buf_size
, buf1
);
5716 pstrcat(buf
, buf_size
, ", ");
5718 pstrcat(buf
, buf_size
, ")");
5722 pstrcpy(buf1
, sizeof(buf1
), "*");
5724 pstrcat(buf1
, sizeof(buf1
), varstr
);
5725 type_to_str(buf
, buf_size
, &s
->type
, buf1
);
5729 pstrcat(buf
, buf_size
, " ");
5730 pstrcat(buf
, buf_size
, varstr
);
5735 /* verify type compatibility to store vtop in 'dt' type, and generate
5737 static void gen_assign_cast(CType
*dt
)
5739 CType
*st
, *type1
, *type2
, tmp_type1
, tmp_type2
;
5740 char buf1
[256], buf2
[256];
5743 st
= &vtop
->type
; /* source type */
5744 dbt
= dt
->t
& VT_BTYPE
;
5745 sbt
= st
->t
& VT_BTYPE
;
5746 if (dt
->t
& VT_CONSTANT
)
5747 warning("assignment of read-only location");
5750 /* special cases for pointers */
5751 /* '0' can also be a pointer */
5752 if (is_null_pointer(vtop
))
5754 /* accept implicit pointer to integer cast with warning */
5755 if (is_integer_btype(sbt
)) {
5756 warning("assignment makes pointer from integer without a cast");
5759 type1
= pointed_type(dt
);
5760 /* a function is implicitely a function pointer */
5761 if (sbt
== VT_FUNC
) {
5762 if ((type1
->t
& VT_BTYPE
) != VT_VOID
&&
5763 !is_compatible_types(pointed_type(dt
), st
))
5770 type2
= pointed_type(st
);
5771 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
5772 (type2
->t
& VT_BTYPE
) == VT_VOID
) {
5773 /* void * can match anything */
5775 /* exact type match, except for unsigned */
5778 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5779 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5780 if (!is_compatible_types(&tmp_type1
, &tmp_type2
))
5783 /* check const and volatile */
5784 if ((!(type1
->t
& VT_CONSTANT
) && (type2
->t
& VT_CONSTANT
)) ||
5785 (!(type1
->t
& VT_VOLATILE
) && (type2
->t
& VT_VOLATILE
)))
5786 warning("assignment discards qualifiers from pointer target type");
5792 if (sbt
== VT_PTR
|| sbt
== VT_FUNC
) {
5793 warning("assignment makes integer from pointer without a cast");
5795 /* XXX: more tests */
5798 if (!is_compatible_types(dt
, st
)) {
5800 type_to_str(buf1
, sizeof(buf1
), st
, NULL
);
5801 type_to_str(buf2
, sizeof(buf2
), dt
, NULL
);
5802 error("cannot cast '%s' to '%s'", buf1
, buf2
);
5810 /* store vtop in lvalue pushed on stack */
5813 int sbt
, dbt
, ft
, r
, t
, size
, align
, bit_size
, bit_pos
, rc
, delayed_cast
;
5815 ft
= vtop
[-1].type
.t
;
5816 sbt
= vtop
->type
.t
& VT_BTYPE
;
5817 dbt
= ft
& VT_BTYPE
;
5818 if (((sbt
== VT_INT
|| sbt
== VT_SHORT
) && dbt
== VT_BYTE
) ||
5819 (sbt
== VT_INT
&& dbt
== VT_SHORT
)) {
5820 /* optimize char/short casts */
5821 delayed_cast
= VT_MUSTCAST
;
5822 vtop
->type
.t
= ft
& VT_TYPE
;
5823 /* XXX: factorize */
5824 if (ft
& VT_CONSTANT
)
5825 warning("assignment of read-only location");
5828 gen_assign_cast(&vtop
[-1].type
);
5831 if (sbt
== VT_STRUCT
) {
5832 /* if structure, only generate pointer */
5833 /* structure assignment : generate memcpy */
5834 /* XXX: optimize if small size */
5835 if (!nocode_wanted
) {
5836 size
= type_size(&vtop
->type
, &align
);
5838 vpush_global_sym(&func_old_type
, TOK_memcpy
);
5842 vtop
->type
.t
= VT_INT
;
5846 vtop
->type
.t
= VT_INT
;
5858 /* leave source on stack */
5859 } else if (ft
& VT_BITFIELD
) {
5860 /* bitfield store handling */
5861 bit_pos
= (ft
>> VT_STRUCT_SHIFT
) & 0x3f;
5862 bit_size
= (ft
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
5863 /* remove bit field info to avoid loops */
5864 vtop
[-1].type
.t
= ft
& ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
5866 /* duplicate destination */
5868 vtop
[-1] = vtop
[-2];
5870 /* mask and shift source */
5871 vpushi((1 << bit_size
) - 1);
5875 /* load destination, mask and or with source */
5877 vpushi(~(((1 << bit_size
) - 1) << bit_pos
));
5883 #ifdef CONFIG_TCC_BCHECK
5884 /* bound check case */
5885 if (vtop
[-1].r
& VT_MUSTBOUND
) {
5891 if (!nocode_wanted
) {
5895 r
= gv(rc
); /* generate value */
5896 /* if lvalue was saved on stack, must read it */
5897 if ((vtop
[-1].r
& VT_VALMASK
) == VT_LLOCAL
) {
5899 t
= get_reg(RC_INT
);
5901 sv
.r
= VT_LOCAL
| VT_LVAL
;
5902 sv
.c
.ul
= vtop
[-1].c
.ul
;
5904 vtop
[-1].r
= t
| VT_LVAL
;
5907 /* two word case handling : store second register at word + 4 */
5908 if ((ft
& VT_BTYPE
) == VT_LLONG
) {
5910 /* convert to int to increment easily */
5911 vtop
->type
.t
= VT_INT
;
5917 /* XXX: it works because r2 is spilled last ! */
5918 store(vtop
->r2
, vtop
- 1);
5922 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
5923 vtop
->r
|= delayed_cast
;
5927 /* post defines POST/PRE add. c is the token ++ or -- */
5928 void inc(int post
, int c
)
5931 vdup(); /* save lvalue */
5933 gv_dup(); /* duplicate value */
5938 vpushi(c
- TOK_MID
);
5940 vstore(); /* store value */
5942 vpop(); /* if post op, return saved value */
5945 /* Parse GNUC __attribute__ extension. Currently, the following
5946 extensions are recognized:
5947 - aligned(n) : set data/function alignment.
5948 - section(x) : generate data/code in this section.
5949 - unused : currently ignored, but may be used someday.
5951 static void parse_attribute(AttributeDef
*ad
)
5955 while (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
) {
5959 while (tok
!= ')') {
5960 if (tok
< TOK_IDENT
)
5961 expect("attribute name");
5969 expect("section name");
5970 ad
->section
= find_section(tcc_state
, (char *)tokc
.cstr
->data
);
5979 if (n
<= 0 || (n
& (n
- 1)) != 0)
5980 error("alignment must be a positive power of two");
5989 /* currently, no need to handle it because tcc does not
5990 track unused objects */
5994 /* currently, no need to handle it because tcc does not
5995 track unused objects */
6000 ad
->func_call
= FUNC_CDECL
;
6005 ad
->func_call
= FUNC_STDCALL
;
6008 if (tcc_state
->warn_unsupported
)
6009 warning("'%s' attribute ignored", get_tok_str(t
, NULL
));
6010 /* skip parameters */
6011 /* XXX: skip parenthesis too */
6014 while (tok
!= ')' && tok
!= -1)
6029 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
6030 static void struct_decl(CType
*type
, int u
)
6032 int a
, v
, size
, align
, maxalign
, c
, offset
;
6033 int bit_size
, bit_pos
, bsize
, bt
, lbit_pos
;
6038 a
= tok
; /* save decl type */
6043 /* struct already defined ? return it */
6045 expect("struct/union/enum name");
6049 error("invalid type");
6056 /* we put an undefined size for struct/union */
6057 s
= sym_push(v
| SYM_STRUCT
, &type1
, 0, -1);
6058 s
->r
= 0; /* default alignment is zero as gcc */
6059 /* put struct/union/enum name in type */
6067 error("struct/union/enum already defined");
6068 /* cannot be empty */
6070 /* non empty enums are not allowed */
6071 if (a
== TOK_ENUM
) {
6075 expect("identifier");
6081 /* enum symbols have static storage */
6082 ss
= sym_push(v
, &int_type
, VT_CONST
, c
);
6083 ss
->type
.t
|= VT_STATIC
;
6088 /* NOTE: we accept a trailing comma */
6098 while (tok
!= '}') {
6099 parse_btype(&btype
, &ad
);
6105 type_decl(&type1
, &ad
, &v
, TYPE_DIRECT
);
6106 if ((type1
.t
& VT_BTYPE
) == VT_FUNC
||
6107 (type1
.t
& (VT_TYPEDEF
| VT_STATIC
| VT_EXTERN
| VT_INLINE
)))
6108 error("invalid type for '%s'",
6109 get_tok_str(v
, NULL
));
6113 bit_size
= expr_const();
6114 /* XXX: handle v = 0 case for messages */
6116 error("negative width in bit-field '%s'",
6117 get_tok_str(v
, NULL
));
6118 if (v
&& bit_size
== 0)
6119 error("zero width for bit-field '%s'",
6120 get_tok_str(v
, NULL
));
6122 size
= type_size(&type1
, &align
);
6124 if (bit_size
>= 0) {
6125 bt
= type1
.t
& VT_BTYPE
;
6130 error("bitfields must have scalar type");
6132 if (bit_size
> bsize
) {
6133 error("width of '%s' exceeds its type",
6134 get_tok_str(v
, NULL
));
6135 } else if (bit_size
== bsize
) {
6136 /* no need for bit fields */
6138 } else if (bit_size
== 0) {
6139 /* XXX: what to do if only padding in a
6141 /* zero size: means to pad */
6145 /* we do not have enough room ? */
6146 if ((bit_pos
+ bit_size
) > bsize
)
6149 /* XXX: handle LSB first */
6150 type1
.t
|= VT_BITFIELD
|
6151 (bit_pos
<< VT_STRUCT_SHIFT
) |
6152 (bit_size
<< (VT_STRUCT_SHIFT
+ 6));
6153 bit_pos
+= bit_size
;
6159 /* add new memory data only if starting
6161 if (lbit_pos
== 0) {
6162 if (a
== TOK_STRUCT
) {
6163 c
= (c
+ align
- 1) & -align
;
6171 if (align
> maxalign
)
6175 printf("add field %s offset=%d",
6176 get_tok_str(v
, NULL
), offset
);
6177 if (type1
.t
& VT_BITFIELD
) {
6178 printf(" pos=%d size=%d",
6179 (type1
.t
>> VT_STRUCT_SHIFT
) & 0x3f,
6180 (type1
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f);
6184 ss
= sym_push(v
| SYM_FIELD
, &type1
, 0, offset
);
6188 if (tok
== ';' || tok
== TOK_EOF
)
6195 /* store size and alignment */
6196 s
->c
= (c
+ maxalign
- 1) & -maxalign
;
6202 /* return 0 if no type declaration. otherwise, return the basic type
6205 static int parse_btype(CType
*type
, AttributeDef
*ad
)
6207 int t
, u
, type_found
;
6211 memset(ad
, 0, sizeof(AttributeDef
));
6217 /* currently, we really ignore extension */
6227 if ((t
& VT_BTYPE
) != 0)
6228 error("too many basic types");
6242 if ((t
& VT_BTYPE
) == VT_DOUBLE
) {
6243 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6244 } else if ((t
& VT_BTYPE
) == VT_LONG
) {
6245 t
= (t
& ~VT_BTYPE
) | VT_LLONG
;
6259 if ((t
& VT_BTYPE
) == VT_LONG
) {
6260 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6267 struct_decl(&type1
, VT_ENUM
);
6270 type
->ref
= type1
.ref
;
6274 struct_decl(&type1
, VT_STRUCT
);
6277 /* type modifiers */
6325 /* GNUC attribute */
6326 case TOK_ATTRIBUTE1
:
6327 case TOK_ATTRIBUTE2
:
6328 parse_attribute(ad
);
6335 parse_expr_type(&type1
);
6339 if (!s
|| !(s
->type
.t
& VT_TYPEDEF
))
6341 t
|= (s
->type
.t
& ~VT_TYPEDEF
);
6342 type
->ref
= s
->type
.ref
;
6349 /* long is never used as type */
6350 if ((t
& VT_BTYPE
) == VT_LONG
)
6351 t
= (t
& ~VT_BTYPE
) | VT_INT
;
6356 /* convert a function parameter type (array to pointer and function to
6357 function pointer) */
6358 static inline void convert_parameter_type(CType
*pt
)
6360 /* array must be transformed to pointer according to ANSI C */
6362 if ((pt
->t
& VT_BTYPE
) == VT_FUNC
) {
6367 static void post_type(CType
*type
, AttributeDef
*ad
)
6370 Sym
**plast
, *s
, *first
;
6375 /* function declaration */
6380 while (tok
!= ')') {
6381 /* read param name and compute offset */
6382 if (l
!= FUNC_OLD
) {
6383 if (!parse_btype(&pt
, &ad1
)) {
6385 error("invalid type");
6392 if ((pt
.t
& VT_BTYPE
) == VT_VOID
&& tok
== ')')
6394 type_decl(&pt
, &ad1
, &n
, TYPE_DIRECT
| TYPE_ABSTRACT
);
6395 if ((pt
.t
& VT_BTYPE
) == VT_VOID
)
6396 error("parameter declared as void");
6403 convert_parameter_type(&pt
);
6404 s
= sym_push(n
| SYM_FIELD
, &pt
, 0, 0);
6409 if (l
== FUNC_NEW
&& tok
== TOK_DOTS
) {
6416 /* if no parameters, then old type prototype */
6420 t1
= type
->t
& VT_STORAGE
;
6421 /* NOTE: const is ignored in returned type as it has a special
6422 meaning in gcc / C++ */
6423 type
->t
&= ~(VT_STORAGE
| VT_CONSTANT
);
6424 post_type(type
, ad
);
6425 /* we push a anonymous symbol which will contain the function prototype */
6426 s
= sym_push(SYM_FIELD
, type
, ad
->func_call
, l
);
6428 type
->t
= t1
| VT_FUNC
;
6430 } else if (tok
== '[') {
6431 /* array definition */
6437 error("invalid array size");
6440 /* parse next post type */
6441 t1
= type
->t
& VT_STORAGE
;
6442 type
->t
&= ~VT_STORAGE
;
6443 post_type(type
, ad
);
6445 /* we push a anonymous symbol which will contain the array
6447 s
= sym_push(SYM_FIELD
, type
, 0, n
);
6448 type
->t
= t1
| VT_ARRAY
| VT_PTR
;
6453 /* Parse a type declaration (except basic type), and return the type
6454 in 'type'. 'td' is a bitmask indicating which kind of type decl is
6455 expected. 'type' should contain the basic type. 'ad' is the
6456 attribute definition of the basic type. It can be modified by
6459 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
)
6462 CType type1
, *type2
;
6465 while (tok
== '*') {
6473 qualifiers
|= VT_CONSTANT
;
6478 qualifiers
|= VT_VOLATILE
;
6486 type
->t
|= qualifiers
;
6489 /* XXX: clarify attribute handling */
6490 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6491 parse_attribute(ad
);
6493 /* recursive type */
6494 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
6495 type1
.t
= 0; /* XXX: same as int */
6498 /* XXX: this is not correct to modify 'ad' at this point, but
6499 the syntax is not clear */
6500 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6501 parse_attribute(ad
);
6502 type_decl(&type1
, ad
, v
, td
);
6505 /* type identifier */
6506 if (tok
>= TOK_IDENT
&& (td
& TYPE_DIRECT
)) {
6510 if (!(td
& TYPE_ABSTRACT
))
6511 expect("identifier");
6515 post_type(type
, ad
);
6516 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6517 parse_attribute(ad
);
6520 /* append type at the end of type1 */
6533 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
6534 static int lvalue_type(int t
)
6539 if (bt
== VT_BYTE
|| bt
== VT_BOOL
)
6541 else if (bt
== VT_SHORT
)
6545 if (t
& VT_UNSIGNED
)
6546 r
|= VT_LVAL_UNSIGNED
;
6550 /* indirection with full error checking and bound check */
6551 static void indir(void)
6553 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
6555 if ((vtop
->r
& VT_LVAL
) && !nocode_wanted
)
6557 vtop
->type
= *pointed_type(&vtop
->type
);
6558 /* an array is never an lvalue */
6559 if (!(vtop
->type
.t
& VT_ARRAY
)) {
6560 vtop
->r
|= lvalue_type(vtop
->type
.t
);
6561 /* if bound checking, the referenced pointer must be checked */
6562 if (do_bounds_check
)
6563 vtop
->r
|= VT_MUSTBOUND
;
6567 /* pass a parameter to a function and do type checking and casting */
6568 static void gfunc_param_typed(Sym
*func
, Sym
*arg
)
6573 func_type
= func
->c
;
6574 if (func_type
== FUNC_OLD
||
6575 (func_type
== FUNC_ELLIPSIS
&& arg
== NULL
)) {
6576 /* default casting : only need to convert float to double */
6577 if ((vtop
->type
.t
& VT_BTYPE
) == VT_FLOAT
) {
6581 } else if (arg
== NULL
) {
6582 error("too many arguments to function");
6585 type
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
6586 gen_assign_cast(&type
);
6590 /* parse an expression of the form '(type)' or '(expr)' and return its
6592 static void parse_expr_type(CType
*type
)
6598 if (parse_btype(type
, &ad
)) {
6599 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
6606 static void parse_type(CType
*type
)
6611 if (!parse_btype(type
, &ad
)) {
6614 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
6617 static void vpush_tokc(int t
)
6621 vsetc(&type
, VT_CONST
, &tokc
);
6624 static void unary(void)
6626 int n
, t
, align
, size
, r
;
6631 /* XXX: GCC 2.95.3 does not generate a table although it should be
6645 vpush_tokc(VT_INT
| VT_UNSIGNED
);
6649 vpush_tokc(VT_LLONG
);
6653 vpush_tokc(VT_LLONG
| VT_UNSIGNED
);
6657 vpush_tokc(VT_FLOAT
);
6661 vpush_tokc(VT_DOUBLE
);
6665 vpush_tokc(VT_LDOUBLE
);
6668 case TOK___FUNCTION__
:
6670 goto tok_identifier
;
6676 /* special function name identifier */
6677 len
= strlen(funcname
) + 1;
6678 /* generate char[len] type */
6683 vpush_ref(&type
, data_section
, data_section
->data_offset
, len
);
6684 ptr
= section_ptr_add(data_section
, len
);
6685 memcpy(ptr
, funcname
, len
);
6693 /* string parsing */
6696 if (tcc_state
->warn_write_strings
)
6701 memset(&ad
, 0, sizeof(AttributeDef
));
6702 decl_initializer_alloc(&type
, &ad
, VT_CONST
, 2, 0, 0);
6707 if (parse_btype(&type
, &ad
)) {
6708 type_decl(&type
, &ad
, &n
, TYPE_ABSTRACT
);
6710 /* check ISOC99 compound literal */
6712 /* data is allocated locally by default */
6717 /* all except arrays are lvalues */
6718 if (!(type
.t
& VT_ARRAY
))
6719 r
|= lvalue_type(type
.t
);
6720 memset(&ad
, 0, sizeof(AttributeDef
));
6721 decl_initializer_alloc(&type
, &ad
, r
, 1, 0, 0);
6726 } else if (tok
== '{') {
6727 /* save all registers */
6729 /* statement expression : we do not accept break/continue
6730 inside as GCC does */
6731 block(NULL
, NULL
, NULL
, NULL
, 0, 1);
6746 /* functions names must be treated as function pointers,
6747 except for unary '&' and sizeof. Since we consider that
6748 functions are not lvalues, we only have to handle it
6749 there and in function calls. */
6750 /* arrays can also be used although they are not lvalues */
6751 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
&&
6752 !(vtop
->type
.t
& VT_ARRAY
))
6754 mk_pointer(&vtop
->type
);
6760 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
)
6761 vtop
->c
.i
= !vtop
->c
.i
;
6762 else if ((vtop
->r
& VT_VALMASK
) == VT_CMP
)
6763 vtop
->c
.i
= vtop
->c
.i
^ 1;
6765 vseti(VT_JMP
, gtst(1, 0));
6775 /* in order to force cast, we add zero */
6777 if ((vtop
->type
.t
& VT_BTYPE
) == VT_PTR
)
6778 error("pointer not accepted for unary plus");
6788 parse_expr_type(&type
);
6792 size
= type_size(&type
, &align
);
6793 if (t
== TOK_SIZEOF
) {
6795 error("sizeof applied to an incomplete type");
6802 case TOK_builtin_types_compatible_p
:
6811 type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6812 type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6813 vpushi(is_compatible_types(&type1
, &type2
));
6816 case TOK_builtin_constant_p
:
6818 int saved_nocode_wanted
, res
;
6821 saved_nocode_wanted
= nocode_wanted
;
6824 res
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
6826 nocode_wanted
= saved_nocode_wanted
;
6846 goto tok_identifier
;
6848 /* allow to take the address of a label */
6849 if (tok
< TOK_UIDENT
)
6850 expect("label identifier");
6851 s
= label_find(tok
);
6853 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
6855 if (s
->r
== LABEL_DECLARED
)
6856 s
->r
= LABEL_FORWARD
;
6859 s
->type
.t
= VT_VOID
;
6860 mk_pointer(&s
->type
);
6861 s
->type
.t
|= VT_STATIC
;
6863 vset(&s
->type
, VT_CONST
| VT_SYM
, 0);
6872 expect("identifier");
6876 error("'%s' undeclared", get_tok_str(t
, NULL
));
6877 /* for simple function calls, we tolerate undeclared
6878 external reference to int() function */
6879 s
= external_global_sym(t
, &func_old_type
, 0);
6881 vset(&s
->type
, s
->r
, s
->c
);
6882 /* if forward reference, we must point to s */
6883 if (vtop
->r
& VT_SYM
) {
6890 /* post operations */
6892 if (tok
== TOK_INC
|| tok
== TOK_DEC
) {
6895 } else if (tok
== '.' || tok
== TOK_ARROW
) {
6897 if (tok
== TOK_ARROW
)
6902 /* expect pointer on structure */
6903 if ((vtop
->type
.t
& VT_BTYPE
) != VT_STRUCT
)
6904 expect("struct or union");
6908 while ((s
= s
->next
) != NULL
) {
6913 error("field not found");
6914 /* add field offset to pointer */
6915 vtop
->type
= char_pointer_type
; /* change type to 'char *' */
6918 /* change type to field type, and set to lvalue */
6919 vtop
->type
= s
->type
;
6920 /* an array is never an lvalue */
6921 if (!(vtop
->type
.t
& VT_ARRAY
)) {
6922 vtop
->r
|= lvalue_type(vtop
->type
.t
);
6923 /* if bound checking, the referenced pointer must be checked */
6924 if (do_bounds_check
)
6925 vtop
->r
|= VT_MUSTBOUND
;
6928 } else if (tok
== '[') {
6934 } else if (tok
== '(') {
6940 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
) {
6941 /* pointer test (no array accepted) */
6942 if ((vtop
->type
.t
& (VT_BTYPE
| VT_ARRAY
)) == VT_PTR
) {
6943 vtop
->type
= *pointed_type(&vtop
->type
);
6944 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
)
6948 expect("function pointer");
6951 vtop
->r
&= ~VT_LVAL
; /* no lvalue */
6953 /* get return type */
6956 sa
= s
->next
; /* first parameter */
6958 /* compute first implicit argument if a structure is returned */
6959 if ((s
->type
.t
& VT_BTYPE
) == VT_STRUCT
) {
6960 /* get some space for the returned structure */
6961 size
= type_size(&s
->type
, &align
);
6962 loc
= (loc
- size
) & -align
;
6964 ret
.r
= VT_LOCAL
| VT_LVAL
;
6965 /* pass it as 'int' to avoid structure arg passing
6967 vseti(VT_LOCAL
, loc
);
6973 /* return in register */
6974 if (is_float(ret
.type
.t
)) {
6977 if ((ret
.type
.t
& VT_BTYPE
) == VT_LLONG
)
6986 gfunc_param_typed(s
, sa
);
6996 error("too few arguments to function");
6998 if (!nocode_wanted
) {
6999 gfunc_call(nb_args
);
7001 vtop
-= (nb_args
+ 1);
7004 vsetc(&ret
.type
, ret
.r
, &ret
.c
);
7012 static void uneq(void)
7018 (tok
>= TOK_A_MOD
&& tok
<= TOK_A_DIV
) ||
7019 tok
== TOK_A_XOR
|| tok
== TOK_A_OR
||
7020 tok
== TOK_A_SHL
|| tok
== TOK_A_SAR
) {
7035 static void expr_prod(void)
7040 while (tok
== '*' || tok
== '/' || tok
== '%') {
7048 static void expr_sum(void)
7053 while (tok
== '+' || tok
== '-') {
7061 static void expr_shift(void)
7066 while (tok
== TOK_SHL
|| tok
== TOK_SAR
) {
7074 static void expr_cmp(void)
7079 while ((tok
>= TOK_ULE
&& tok
<= TOK_GT
) ||
7080 tok
== TOK_ULT
|| tok
== TOK_UGE
) {
7088 static void expr_cmpeq(void)
7093 while (tok
== TOK_EQ
|| tok
== TOK_NE
) {
7101 static void expr_and(void)
7104 while (tok
== '&') {
7111 static void expr_xor(void)
7114 while (tok
== '^') {
7121 static void expr_or(void)
7124 while (tok
== '|') {
7131 /* XXX: fix this mess */
7132 static void expr_land_const(void)
7135 while (tok
== TOK_LAND
) {
7142 /* XXX: fix this mess */
7143 static void expr_lor_const(void)
7146 while (tok
== TOK_LOR
) {
7153 /* only used if non constant */
7154 static void expr_land(void)
7159 if (tok
== TOK_LAND
) {
7163 if (tok
!= TOK_LAND
) {
7173 static void expr_lor(void)
7178 if (tok
== TOK_LOR
) {
7182 if (tok
!= TOK_LOR
) {
7192 /* XXX: better constant handling */
7193 static void expr_eq(void)
7195 int tt
, u
, r1
, r2
, rc
, t1
, t2
, bt1
, bt2
;
7197 CType type
, type1
, type2
;
7206 if (tok
== ':' && gnu_ext
) {
7222 if (vtop
!= vstack
) {
7223 /* needed to avoid having different registers saved in
7225 if (is_float(vtop
->type
.t
))
7232 if (tok
== ':' && gnu_ext
) {
7240 sv
= *vtop
; /* save value to handle it later */
7241 vtop
--; /* no vpop so that FP stack is not flushed */
7249 bt1
= t1
& VT_BTYPE
;
7251 bt2
= t2
& VT_BTYPE
;
7252 /* cast operands to correct type according to ISOC rules */
7253 if (is_float(bt1
) || is_float(bt2
)) {
7254 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
7255 type
.t
= VT_LDOUBLE
;
7256 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
7261 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
7262 /* cast to biggest op */
7264 /* convert to unsigned if it does not fit in a long long */
7265 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
7266 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
7267 type
.t
|= VT_UNSIGNED
;
7268 } else if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
7269 /* XXX: test pointer compatibility */
7271 } else if (bt1
== VT_STRUCT
|| bt2
== VT_STRUCT
) {
7272 /* XXX: test structure compatibility */
7274 } else if (bt1
== VT_VOID
|| bt2
== VT_VOID
) {
7275 /* NOTE: as an extension, we accept void on only one side */
7278 /* integer operations */
7280 /* convert to unsigned if it does not fit in an integer */
7281 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
7282 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
7283 type
.t
|= VT_UNSIGNED
;
7286 /* now we convert second operand */
7289 if (is_float(type
.t
)) {
7291 } else if ((type
.t
& VT_BTYPE
) == VT_LLONG
) {
7292 /* for long longs, we use fixed registers to avoid having
7293 to handle a complicated move */
7298 /* this is horrible, but we must also convert first
7302 /* put again first value and cast it */
7313 static void gexpr(void)
7324 /* parse an expression and return its type without any side effect. */
7325 static void expr_type(CType
*type
)
7327 int saved_nocode_wanted
;
7329 saved_nocode_wanted
= nocode_wanted
;
7334 nocode_wanted
= saved_nocode_wanted
;
7337 /* parse a unary expression and return its type without any side
7339 static void unary_type(CType
*type
)
7351 /* parse a constant expression and return value in vtop. */
7352 static void expr_const1(void)
7361 /* parse an integer constant and return its value. */
7362 static int expr_const(void)
7366 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
7367 expect("constant expression");
7373 /* return the label token if current token is a label, otherwise
7375 static int is_label(void)
7379 /* fast test first */
7380 if (tok
< TOK_UIDENT
)
7382 /* no need to save tokc because tok is an identifier */
7389 unget_tok(last_tok
);
7394 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
7395 int case_reg
, int is_expr
)
7400 /* generate line number info */
7402 (last_line_num
!= file
->line_num
|| last_ind
!= ind
)) {
7403 put_stabn(N_SLINE
, 0, file
->line_num
, ind
- func_ind
);
7405 last_line_num
= file
->line_num
;
7409 /* default return value is (void) */
7411 vtop
->type
.t
= VT_VOID
;
7414 if (tok
== TOK_IF
) {
7421 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7423 if (c
== TOK_ELSE
) {
7427 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7428 gsym(d
); /* patch else jmp */
7431 } else if (tok
== TOK_WHILE
) {
7439 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7443 } else if (tok
== '{') {
7447 /* record local declaration stack position */
7449 llabel
= local_label_stack
;
7450 /* handle local labels declarations */
7451 if (tok
== TOK_LABEL
) {
7454 if (tok
< TOK_UIDENT
)
7455 expect("label identifier");
7456 label_push(&local_label_stack
, tok
, LABEL_DECLARED
);
7466 while (tok
!= '}') {
7471 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
7474 /* pop locally defined labels */
7475 label_pop(&local_label_stack
, llabel
);
7476 /* pop locally defined symbols */
7477 sym_pop(&local_stack
, s
);
7479 } else if (tok
== TOK_RETURN
) {
7483 gen_assign_cast(&func_vt
);
7484 if ((func_vt
.t
& VT_BTYPE
) == VT_STRUCT
) {
7486 /* if returning structure, must copy it to implicit
7487 first pointer arg location */
7490 vset(&type
, VT_LOCAL
| VT_LVAL
, func_vc
);
7493 /* copy structure value to pointer */
7495 } else if (is_float(func_vt
.t
)) {
7500 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
7503 rsym
= gjmp(rsym
); /* jmp */
7504 } else if (tok
== TOK_BREAK
) {
7507 error("cannot break");
7508 *bsym
= gjmp(*bsym
);
7511 } else if (tok
== TOK_CONTINUE
) {
7514 error("cannot continue");
7515 *csym
= gjmp(*csym
);
7518 } else if (tok
== TOK_FOR
) {
7545 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7550 if (tok
== TOK_DO
) {
7555 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7566 if (tok
== TOK_SWITCH
) {
7570 /* XXX: other types than integer */
7571 case_reg
= gv(RC_INT
);
7575 b
= gjmp(0); /* jump to first case */
7577 block(&a
, csym
, &b
, &c
, case_reg
, 0);
7578 /* if no default, jmp after switch */
7586 if (tok
== TOK_CASE
) {
7593 if (gnu_ext
&& tok
== TOK_DOTS
) {
7597 warning("empty case range");
7599 /* since a case is like a label, we must skip it with a jmp */
7606 *case_sym
= gtst(1, 0);
7609 *case_sym
= gtst(1, 0);
7613 *case_sym
= gtst(1, *case_sym
);
7618 goto block_after_label
;
7620 if (tok
== TOK_DEFAULT
) {
7626 error("too many 'default'");
7629 goto block_after_label
;
7631 if (tok
== TOK_GOTO
) {
7633 if (tok
== '*' && gnu_ext
) {
7637 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
7640 } else if (tok
>= TOK_UIDENT
) {
7641 s
= label_find(tok
);
7642 /* put forward definition if needed */
7644 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
7646 if (s
->r
== LABEL_DECLARED
)
7647 s
->r
= LABEL_FORWARD
;
7649 /* label already defined */
7650 if (s
->r
& LABEL_FORWARD
)
7651 s
->next
= (void *)gjmp((long)s
->next
);
7653 gjmp_addr((long)s
->next
);
7656 expect("label identifier");
7659 } else if (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
) {
7667 if (s
->r
== LABEL_DEFINED
)
7668 error("duplicate label '%s'", get_tok_str(s
->v
, NULL
));
7669 gsym((long)s
->next
);
7670 s
->r
= LABEL_DEFINED
;
7672 s
= label_push(&global_label_stack
, b
, LABEL_DEFINED
);
7674 s
->next
= (void *)ind
;
7675 /* we accept this, but it is a mistake */
7678 warning("deprecated use of label at end of compound statement");
7682 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
7685 /* expression case */
7700 /* t is the array or struct type. c is the array or struct
7701 address. cur_index/cur_field is the pointer to the current
7702 value. 'size_only' is true if only size info is needed (only used
7704 static void decl_designator(CType
*type
, Section
*sec
, unsigned long c
,
7705 int *cur_index
, Sym
**cur_field
,
7709 int notfirst
, index
, index_last
, align
, l
, nb_elems
, elem_size
;
7715 if (gnu_ext
&& (l
= is_label()) != 0)
7717 while (tok
== '[' || tok
== '.') {
7719 if (!(type
->t
& VT_ARRAY
))
7720 expect("array type");
7723 index
= expr_const();
7724 if (index
< 0 || (s
->c
>= 0 && index
>= s
->c
))
7725 expect("invalid index");
7726 if (tok
== TOK_DOTS
&& gnu_ext
) {
7728 index_last
= expr_const();
7729 if (index_last
< 0 ||
7730 (s
->c
>= 0 && index_last
>= s
->c
) ||
7732 expect("invalid index");
7738 *cur_index
= index_last
;
7739 type
= pointed_type(type
);
7740 elem_size
= type_size(type
, &align
);
7741 c
+= index
* elem_size
;
7742 /* NOTE: we only support ranges for last designator */
7743 nb_elems
= index_last
- index
+ 1;
7744 if (nb_elems
!= 1) {
7753 if ((type
->t
& VT_BTYPE
) != VT_STRUCT
)
7754 expect("struct/union type");
7767 /* XXX: fix this mess by using explicit storage field */
7769 type1
.t
|= (type
->t
& ~VT_TYPE
);
7783 if (type
->t
& VT_ARRAY
) {
7785 type
= pointed_type(type
);
7786 c
+= index
* type_size(type
, &align
);
7790 error("too many field init");
7791 /* XXX: fix this mess by using explicit storage field */
7793 type1
.t
|= (type
->t
& ~VT_TYPE
);
7798 decl_initializer(type
, sec
, c
, 0, size_only
);
7800 /* XXX: make it more general */
7801 if (!size_only
&& nb_elems
> 1) {
7802 unsigned long c_end
;
7807 error("range init not supported yet for dynamic storage");
7808 c_end
= c
+ nb_elems
* elem_size
;
7809 if (c_end
> sec
->data_allocated
)
7810 section_realloc(sec
, c_end
);
7811 src
= sec
->data
+ c
;
7813 for(i
= 1; i
< nb_elems
; i
++) {
7815 memcpy(dst
, src
, elem_size
);
7821 #define EXPR_CONST 1
7824 /* store a value or an expression directly in global data or in local array */
7825 static void init_putv(CType
*type
, Section
*sec
, unsigned long c
,
7826 int v
, int expr_type
)
7828 int saved_global_expr
, bt
, bit_pos
, bit_size
;
7830 unsigned long long bit_mask
;
7838 /* compound literals must be allocated globally in this case */
7839 saved_global_expr
= global_expr
;
7842 global_expr
= saved_global_expr
;
7843 /* NOTE: symbols are accepted */
7844 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) != VT_CONST
)
7845 error("initializer element is not constant");
7853 dtype
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
7856 /* XXX: not portable */
7857 /* XXX: generate error if incorrect relocation */
7858 gen_assign_cast(&dtype
);
7859 bt
= type
->t
& VT_BTYPE
;
7860 ptr
= sec
->data
+ c
;
7861 /* XXX: make code faster ? */
7862 if (!(type
->t
& VT_BITFIELD
)) {
7867 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
7868 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
7869 bit_mask
= (1LL << bit_size
) - 1;
7871 if ((vtop
->r
& VT_SYM
) &&
7877 (bt
== VT_INT
&& bit_size
!= 32)))
7878 error("initializer element is not computable at load time");
7881 *(char *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
7884 *(short *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
7887 *(double *)ptr
= vtop
->c
.d
;
7890 *(long double *)ptr
= vtop
->c
.ld
;
7893 *(long long *)ptr
|= (vtop
->c
.ll
& bit_mask
) << bit_pos
;
7896 if (vtop
->r
& VT_SYM
) {
7897 greloc(sec
, vtop
->sym
, c
, R_DATA_32
);
7899 *(int *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
7904 vset(&dtype
, VT_LOCAL
, c
);
7911 /* put zeros for variable based init */
7912 static void init_putz(CType
*t
, Section
*sec
, unsigned long c
, int size
)
7915 /* nothing to do because globals are already set to zero */
7917 vpush_global_sym(&func_old_type
, TOK_memset
);
7925 /* 't' contains the type and storage info. 'c' is the offset of the
7926 object in section 'sec'. If 'sec' is NULL, it means stack based
7927 allocation. 'first' is true if array '{' must be read (multi
7928 dimension implicit array init handling). 'size_only' is true if
7929 size only evaluation is wanted (only for arrays). */
7930 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
7931 int first
, int size_only
)
7933 int index
, array_length
, n
, no_oblock
, nb
, parlevel
, i
;
7934 int size1
, align1
, expr_type
;
7938 if (type
->t
& VT_ARRAY
) {
7942 t1
= pointed_type(type
);
7943 size1
= type_size(t1
, &align1
);
7946 if ((first
&& tok
!= TOK_LSTR
&& tok
!= TOK_STR
) ||
7952 /* only parse strings here if correct type (otherwise: handle
7953 them as ((w)char *) expressions */
7954 if ((tok
== TOK_LSTR
&&
7955 (t1
->t
& VT_BTYPE
) == VT_INT
) ||
7957 (t1
->t
& VT_BTYPE
) == VT_BYTE
)) {
7958 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
7963 /* compute maximum number of chars wanted */
7965 cstr_len
= cstr
->size
;
7967 cstr_len
= cstr
->size
/ sizeof(int);
7970 if (n
>= 0 && nb
> (n
- array_length
))
7971 nb
= n
- array_length
;
7974 warning("initializer-string for array is too long");
7975 /* in order to go faster for common case (char
7976 string in global variable, we handle it
7978 if (sec
&& tok
== TOK_STR
&& size1
== 1) {
7979 memcpy(sec
->data
+ c
+ array_length
, cstr
->data
, nb
);
7983 ch
= ((unsigned char *)cstr
->data
)[i
];
7985 ch
= ((int *)cstr
->data
)[i
];
7986 init_putv(t1
, sec
, c
+ (array_length
+ i
) * size1
,
7994 /* only add trailing zero if enough storage (no
7995 warning in this case since it is standard) */
7996 if (n
< 0 || array_length
< n
) {
7998 init_putv(t1
, sec
, c
+ (array_length
* size1
), 0, EXPR_VAL
);
8004 while (tok
!= '}') {
8005 decl_designator(type
, sec
, c
, &index
, NULL
, size_only
);
8006 if (n
>= 0 && index
>= n
)
8007 error("index too large");
8008 /* must put zero in holes (note that doing it that way
8009 ensures that it even works with designators) */
8010 if (!size_only
&& array_length
< index
) {
8011 init_putz(t1
, sec
, c
+ array_length
* size1
,
8012 (index
- array_length
) * size1
);
8015 if (index
> array_length
)
8016 array_length
= index
;
8017 /* special test for multi dimensional arrays (may not
8018 be strictly correct if designators are used at the
8020 if (index
>= n
&& no_oblock
)
8029 /* put zeros at the end */
8030 if (!size_only
&& n
>= 0 && array_length
< n
) {
8031 init_putz(t1
, sec
, c
+ array_length
* size1
,
8032 (n
- array_length
) * size1
);
8034 /* patch type size if needed */
8036 s
->c
= array_length
;
8037 } else if ((type
->t
& VT_BTYPE
) == VT_STRUCT
&&
8038 (sec
|| !first
|| tok
== '{')) {
8041 /* NOTE: the previous test is a specific case for automatic
8042 struct/union init */
8043 /* XXX: union needs only one init */
8045 /* XXX: this test is incorrect for local initializers
8046 beginning with ( without {. It would be much more difficult
8047 to do it correctly (ideally, the expression parser should
8048 be used in all cases) */
8054 while (tok
== '(') {
8058 if (!parse_btype(&type1
, &ad1
))
8060 type_decl(&type1
, &ad1
, &n
, TYPE_ABSTRACT
);
8062 if (!is_assignable_types(type
, &type1
))
8063 error("invalid type for cast");
8068 if (first
|| tok
== '{') {
8077 while (tok
!= '}') {
8078 decl_designator(type
, sec
, c
, NULL
, &f
, size_only
);
8080 if (!size_only
&& array_length
< index
) {
8081 init_putz(type
, sec
, c
+ array_length
,
8082 index
- array_length
);
8084 index
= index
+ type_size(&f
->type
, &align1
);
8085 if (index
> array_length
)
8086 array_length
= index
;
8088 if (no_oblock
&& f
== NULL
)
8094 /* put zeros at the end */
8095 if (!size_only
&& array_length
< n
) {
8096 init_putz(type
, sec
, c
+ array_length
,
8105 } else if (tok
== '{') {
8107 decl_initializer(type
, sec
, c
, first
, size_only
);
8109 } else if (size_only
) {
8110 /* just skip expression */
8112 while ((parlevel
> 0 || (tok
!= '}' && tok
!= ',')) &&
8116 else if (tok
== ')')
8121 /* currently, we always use constant expression for globals
8122 (may change for scripting case) */
8123 expr_type
= EXPR_CONST
;
8125 expr_type
= EXPR_ANY
;
8126 init_putv(type
, sec
, c
, 0, expr_type
);
8130 /* parse an initializer for type 't' if 'has_init' is non zero, and
8131 allocate space in local or global data space ('r' is either
8132 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
8133 variable 'v' of scope 'scope' is declared before initializers are
8134 parsed. If 'v' is zero, then a reference to the new object is put
8135 in the value stack. If 'has_init' is 2, a special parsing is done
8136 to handle string constants. */
8137 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
8138 int has_init
, int v
, int scope
)
8140 int size
, align
, addr
, data_offset
;
8142 ParseState saved_parse_state
;
8143 TokenString init_str
;
8146 size
= type_size(type
, &align
);
8147 /* If unknown size, we must evaluate it before
8148 evaluating initializers because
8149 initializers can generate global data too
8150 (e.g. string pointers or ISOC99 compound
8151 literals). It also simplifies local
8152 initializers handling */
8153 tok_str_new(&init_str
);
8156 error("unknown type size");
8157 /* get all init string */
8158 if (has_init
== 2) {
8159 /* only get strings */
8160 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
8161 tok_str_add_tok(&init_str
);
8166 while (level
> 0 || (tok
!= ',' && tok
!= ';')) {
8168 error("unexpected end of file in initializer");
8169 tok_str_add_tok(&init_str
);
8172 else if (tok
== '}') {
8180 tok_str_add(&init_str
, -1);
8181 tok_str_add(&init_str
, 0);
8184 save_parse_state(&saved_parse_state
);
8186 macro_ptr
= init_str
.str
;
8188 decl_initializer(type
, NULL
, 0, 1, 1);
8189 /* prepare second initializer parsing */
8190 macro_ptr
= init_str
.str
;
8193 /* if still unknown size, error */
8194 size
= type_size(type
, &align
);
8196 error("unknown type size");
8198 /* take into account specified alignment if bigger */
8199 if (ad
->aligned
> align
)
8200 align
= ad
->aligned
;
8201 if ((r
& VT_VALMASK
) == VT_LOCAL
) {
8203 if (do_bounds_check
&& (type
->t
& VT_ARRAY
))
8205 loc
= (loc
- size
) & -align
;
8207 /* handles bounds */
8208 /* XXX: currently, since we do only one pass, we cannot track
8209 '&' operators, so we add only arrays */
8210 if (do_bounds_check
&& (type
->t
& VT_ARRAY
)) {
8211 unsigned long *bounds_ptr
;
8212 /* add padding between regions */
8214 /* then add local bound info */
8215 bounds_ptr
= section_ptr_add(lbounds_section
, 2 * sizeof(unsigned long));
8216 bounds_ptr
[0] = addr
;
8217 bounds_ptr
[1] = size
;
8220 /* local variable */
8221 sym_push(v
, type
, r
, addr
);
8223 /* push local reference */
8224 vset(type
, r
, addr
);
8230 if (v
&& scope
== VT_CONST
) {
8231 /* see if the symbol was already defined */
8234 if (!is_compatible_types(&sym
->type
, type
))
8235 error("incompatible types for redefinition of '%s'",
8236 get_tok_str(v
, NULL
));
8237 if (sym
->type
.t
& VT_EXTERN
) {
8238 /* if the variable is extern, it was not allocated */
8239 sym
->type
.t
&= ~VT_EXTERN
;
8241 /* we accept several definitions of the same
8242 global variable. this is tricky, because we
8243 must play with the SHN_COMMON type of the symbol */
8244 /* XXX: should check if the variable was already
8245 initialized. It is incorrect to initialized it
8247 /* no init data, we won't add more to the symbol */
8254 /* allocate symbol in corresponding section */
8261 data_offset
= sec
->data_offset
;
8262 data_offset
= (data_offset
+ align
- 1) & -align
;
8264 /* very important to increment global pointer at this time
8265 because initializers themselves can create new initializers */
8266 data_offset
+= size
;
8267 /* add padding if bound check */
8268 if (do_bounds_check
)
8270 sec
->data_offset
= data_offset
;
8271 /* allocate section space to put the data */
8272 if (sec
->sh_type
!= SHT_NOBITS
&&
8273 data_offset
> sec
->data_allocated
)
8274 section_realloc(sec
, data_offset
);
8276 addr
= 0; /* avoid warning */
8280 if (scope
== VT_CONST
) {
8285 sym
= sym_push(v
, type
, r
| VT_SYM
, 0);
8287 /* update symbol definition */
8289 put_extern_sym(sym
, sec
, addr
, size
);
8292 /* put a common area */
8293 put_extern_sym(sym
, NULL
, align
, size
);
8294 /* XXX: find a nicer way */
8295 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
8296 esym
->st_shndx
= SHN_COMMON
;
8301 /* push global reference */
8302 sym
= get_sym_ref(type
, sec
, addr
, size
);
8304 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
8308 /* handles bounds now because the symbol must be defined
8309 before for the relocation */
8310 if (do_bounds_check
) {
8311 unsigned long *bounds_ptr
;
8313 greloc(bounds_section
, sym
, bounds_section
->data_offset
, R_DATA_32
);
8314 /* then add global bound info */
8315 bounds_ptr
= section_ptr_add(bounds_section
, 2 * sizeof(long));
8316 bounds_ptr
[0] = 0; /* relocated */
8317 bounds_ptr
[1] = size
;
8321 decl_initializer(type
, sec
, addr
, 1, 0);
8322 /* restore parse state if needed */
8324 tok_str_free(init_str
.str
);
8325 restore_parse_state(&saved_parse_state
);
8331 void put_func_debug(Sym
*sym
)
8336 /* XXX: we put here a dummy type */
8337 snprintf(buf
, sizeof(buf
), "%s:%c1",
8338 funcname
, sym
->type
.t
& VT_STATIC
? 'f' : 'F');
8339 put_stabs_r(buf
, N_FUN
, 0, file
->line_num
, 0,
8340 cur_text_section
, sym
->c
);
8345 /* not finished : try to put some local vars in registers */
8346 //#define CONFIG_REG_VARS
8348 #ifdef CONFIG_REG_VARS
8349 void add_var_ref(int t
)
8351 printf("%s:%d: &%s\n",
8352 file
->filename
, file
->line_num
,
8353 get_tok_str(t
, NULL
));
8356 /* first pass on a function with heuristic to extract variable usage
8357 and pointer references to local variables for register allocation */
8358 void analyse_function(void)
8365 /* any symbol coming after '&' is considered as being a
8366 variable whose reference is taken. It is highly unaccurate
8367 but it is difficult to do better without a complete parse */
8370 /* if '& number', then no need to examine next tokens */
8371 if (tok
== TOK_CINT
||
8373 tok
== TOK_CLLONG
||
8374 tok
== TOK_CULLONG
) {
8376 } else if (tok
>= TOK_UIDENT
) {
8377 /* if '& ident [' or '& ident ->', then ident address
8381 if (tok
!= '[' && tok
!= TOK_ARROW
)
8385 while (tok
!= '}' && tok
!= ';' &&
8386 !((tok
== ',' || tok
== ')') && level
== 0)) {
8387 if (tok
>= TOK_UIDENT
) {
8389 } else if (tok
== '(') {
8391 } else if (tok
== ')') {
8404 /* parse an old style function declaration list */
8405 /* XXX: check multiple parameter */
8406 static void func_decl_list(Sym
*func_sym
)
8413 /* parse each declaration */
8414 while (tok
!= '{' && tok
!= ';' && tok
!= ',' && tok
!= TOK_EOF
) {
8415 if (!parse_btype(&btype
, &ad
))
8416 expect("declaration list");
8417 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
8418 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
8420 /* we accept no variable after */
8424 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
8425 /* find parameter in function parameter list */
8428 if ((s
->v
& ~SYM_FIELD
) == v
)
8432 error("declaration for parameter '%s' but no such parameter",
8433 get_tok_str(v
, NULL
));
8435 /* check that no storage specifier except 'register' was given */
8436 if (type
.t
& VT_STORAGE
)
8437 error("storage class specified for '%s'", get_tok_str(v
, NULL
));
8438 convert_parameter_type(&type
);
8439 /* we can add the type (NOTE: it could be local to the function) */
8441 /* accept other parameters */
8452 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
8453 static void decl(int l
)
8461 if (!parse_btype(&btype
, &ad
)) {
8462 /* skip redundant ';' */
8463 /* XXX: find more elegant solution */
8468 /* special test for old K&R protos without explicit int
8469 type. Only accepted when defining global data */
8470 if (l
== VT_LOCAL
|| tok
< TOK_DEFINE
)
8474 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
8475 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
8477 /* we accept no variable after */
8481 while (1) { /* iterate thru each declaration */
8483 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
8487 type_to_str(buf
, sizeof(buf
), t
, get_tok_str(v
, NULL
));
8488 printf("type = '%s'\n", buf
);
8491 if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
8492 /* if old style function prototype, we accept a
8495 if (sym
->c
== FUNC_OLD
)
8496 func_decl_list(sym
);
8500 #ifdef CONFIG_REG_VARS
8501 TokenString func_str
;
8502 ParseState saved_parse_state
;
8507 error("cannot use local functions");
8508 if (!(type
.t
& VT_FUNC
))
8509 expect("function definition");
8510 /* XXX: cannot do better now: convert extern line to static inline */
8511 if ((type
.t
& (VT_EXTERN
| VT_INLINE
)) == (VT_EXTERN
| VT_INLINE
))
8512 type
.t
= (type
.t
& ~VT_EXTERN
) | VT_STATIC
;
8514 #ifdef CONFIG_REG_VARS
8515 /* parse all function code and record it */
8517 tok_str_new(&func_str
);
8523 error("unexpected end of file");
8524 tok_str_add_tok(&func_str
);
8529 } else if (t
== '}') {
8531 if (block_level
== 0)
8535 tok_str_add(&func_str
, -1);
8536 tok_str_add(&func_str
, 0);
8538 save_parse_state(&saved_parse_state
);
8540 macro_ptr
= func_str
.str
;
8545 /* compute text section */
8546 cur_text_section
= ad
.section
;
8547 if (!cur_text_section
)
8548 cur_text_section
= text_section
;
8549 ind
= cur_text_section
->data_offset
;
8550 funcname
= get_tok_str(v
, NULL
);
8553 /* if symbol is already defined, then put complete type */
8556 /* put function symbol */
8557 sym
= global_identifier_push(v
, type
.t
, 0);
8558 sym
->type
.ref
= type
.ref
;
8560 /* NOTE: we patch the symbol size later */
8561 put_extern_sym(sym
, cur_text_section
, ind
, 0);
8563 sym
->r
= VT_SYM
| VT_CONST
;
8564 /* put debug symbol */
8566 put_func_debug(sym
);
8567 /* push a dummy symbol to enable local sym storage */
8568 sym_push2(&local_stack
, SYM_FIELD
, 0, 0);
8569 gfunc_prolog(&type
);
8572 #ifdef CONFIG_REG_VARS
8573 macro_ptr
= func_str
.str
;
8576 block(NULL
, NULL
, NULL
, NULL
, 0, 0);
8579 cur_text_section
->data_offset
= ind
;
8580 label_pop(&global_label_stack
, NULL
);
8581 sym_pop(&local_stack
, NULL
); /* reset local stack */
8582 /* end of function */
8583 /* patch symbol size */
8584 ((Elf32_Sym
*)symtab_section
->data
)[sym
->c
].st_size
=
8587 put_stabn(N_FUN
, 0, 0, ind
- func_ind
);
8589 funcname
= ""; /* for safety */
8590 func_vt
.t
= VT_VOID
; /* for safety */
8591 ind
= 0; /* for safety */
8593 #ifdef CONFIG_REG_VARS
8594 tok_str_free(func_str
.str
);
8595 restore_parse_state(&saved_parse_state
);
8599 if (btype
.t
& VT_TYPEDEF
) {
8600 /* save typedefed type */
8601 /* XXX: test storage specifiers ? */
8602 sym
= sym_push(v
, &type
, 0, 0);
8603 sym
->type
.t
|= VT_TYPEDEF
;
8604 } else if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
8605 /* external function definition */
8606 external_sym(v
, &type
, 0);
8608 /* not lvalue if array */
8610 if (!(type
.t
& VT_ARRAY
))
8611 r
|= lvalue_type(type
.t
);
8612 has_init
= (tok
== '=');
8613 if ((btype
.t
& VT_EXTERN
) ||
8614 ((type
.t
& VT_ARRAY
) && (type
.t
& VT_STATIC
) &&
8615 !has_init
&& l
== VT_CONST
&& type
.ref
->c
< 0)) {
8616 /* external variable */
8617 /* NOTE: as GCC, uninitialized global static
8618 arrays of null size are considered as
8620 external_sym(v
, &type
, r
);
8622 if (type
.t
& VT_STATIC
)
8628 decl_initializer_alloc(&type
, &ad
, r
,
8642 /* better than nothing, but needs extension to handle '-E' option
8644 static void preprocess_init(TCCState
*s1
)
8646 s1
->include_stack_ptr
= s1
->include_stack
;
8647 /* XXX: move that before to avoid having to initialize
8648 file->ifdef_stack_ptr ? */
8649 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
8650 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
8652 /* XXX: not ANSI compliant: bound checking says error */
8656 /* compile the C file opened in 'file'. Return non zero if errors. */
8657 static int tcc_compile(TCCState
*s1
)
8661 volatile int section_sym
;
8664 printf("%s: **** new file\n", file
->filename
);
8666 preprocess_init(s1
);
8669 anon_sym
= SYM_FIRST_ANOM
;
8671 /* file info: full path + filename */
8672 section_sym
= 0; /* avoid warning */
8674 section_sym
= put_elf_sym(symtab_section
, 0, 0,
8675 ELF32_ST_INFO(STB_LOCAL
, STT_SECTION
), 0,
8676 text_section
->sh_num
, NULL
);
8677 getcwd(buf
, sizeof(buf
));
8678 pstrcat(buf
, sizeof(buf
), "/");
8679 put_stabs_r(buf
, N_SO
, 0, 0,
8680 text_section
->data_offset
, text_section
, section_sym
);
8681 put_stabs_r(file
->filename
, N_SO
, 0, 0,
8682 text_section
->data_offset
, text_section
, section_sym
);
8684 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
8685 symbols can be safely used */
8686 put_elf_sym(symtab_section
, 0, 0,
8687 ELF32_ST_INFO(STB_LOCAL
, STT_FILE
), 0,
8688 SHN_ABS
, file
->filename
);
8690 /* define some often used types */
8691 int_type
.t
= VT_INT
;
8693 char_pointer_type
.t
= VT_BYTE
;
8694 mk_pointer(&char_pointer_type
);
8696 func_old_type
.t
= VT_FUNC
;
8697 func_old_type
.ref
= sym_push(SYM_FIELD
, &int_type
, FUNC_CDECL
, FUNC_OLD
);
8700 /* define 'void *alloca(unsigned int)' builtin function */
8705 sym
= sym_push(p
, mk_pointer(VT_VOID
), FUNC_CDECL
, FUNC_NEW
);
8706 s1
= sym_push(SYM_FIELD
, VT_UNSIGNED
| VT_INT
, 0, 0);
8709 sym_push(TOK_alloca
, VT_FUNC
| (p
<< VT_STRUCT_SHIFT
), VT_CONST
, 0);
8713 define_start
= define_stack
;
8715 if (setjmp(s1
->error_jmp_buf
) == 0) {
8717 s1
->error_set_jmp_enabled
= 1;
8719 ch
= file
->buf_ptr
[0];
8720 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
8721 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
;
8725 expect("declaration");
8727 /* end of translation unit info */
8729 put_stabs_r(NULL
, N_SO
, 0, 0,
8730 text_section
->data_offset
, text_section
, section_sym
);
8733 s1
->error_set_jmp_enabled
= 0;
8735 /* reset define stack, but leave -Dsymbols (may be incorrect if
8736 they are undefined) */
8737 free_defines(define_start
);
8739 sym_pop(&global_stack
, NULL
);
8741 return s1
->nb_errors
!= 0 ? -1 : 0;
8745 int tcc_compile_string(TCCState
*s
, const char *str
)
8747 BufferedFile bf1
, *bf
= &bf1
;
8751 /* init file structure */
8753 /* XXX: avoid copying */
8755 buf
= tcc_malloc(len
+ 1);
8758 memcpy(buf
, str
, len
);
8761 bf
->buf_end
= buf
+ len
;
8762 pstrcpy(bf
->filename
, sizeof(bf
->filename
), "<string>");
8766 ret
= tcc_compile(s
);
8770 /* currently, no need to close */
8775 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
8776 void tcc_define_symbol(TCCState
*s1
, const char *sym
, const char *value
)
8778 BufferedFile bf1
, *bf
= &bf1
;
8780 pstrcpy(bf
->buffer
, IO_BUF_SIZE
, sym
);
8781 pstrcat(bf
->buffer
, IO_BUF_SIZE
, " ");
8785 pstrcat(bf
->buffer
, IO_BUF_SIZE
, value
);
8787 /* init file structure */
8789 bf
->buf_ptr
= bf
->buffer
;
8790 bf
->buf_end
= bf
->buffer
+ strlen(bf
->buffer
);
8791 *bf
->buf_end
= CH_EOB
;
8792 bf
->filename
[0] = '\0';
8796 s1
->include_stack_ptr
= s1
->include_stack
;
8798 /* parse with define parser */
8799 ch
= file
->buf_ptr
[0];
8805 /* undefine a preprocessor symbol */
8806 void tcc_undefine_symbol(TCCState
*s1
, const char *sym
)
8810 ts
= tok_alloc(sym
, strlen(sym
));
8811 s
= define_find(ts
->tok
);
8812 /* undefine symbol by putting an invalid name */
8817 #ifdef CONFIG_TCC_ASM
8819 #include "i386-asm.c"
8823 static void asm_instr(void)
8825 error("inline asm() not supported");
8831 /* print the position in the source file of PC value 'pc' by reading
8832 the stabs debug information */
8833 static void rt_printline(unsigned long wanted_pc
)
8835 Stab_Sym
*sym
, *sym_end
;
8836 char func_name
[128], last_func_name
[128];
8837 unsigned long func_addr
, last_pc
, pc
;
8838 const char *incl_files
[INCLUDE_STACK_SIZE
];
8839 int incl_index
, len
, last_line_num
, i
;
8840 const char *str
, *p
;
8842 fprintf(stderr
, "0x%08lx:", wanted_pc
);
8844 func_name
[0] = '\0';
8847 last_func_name
[0] = '\0';
8848 last_pc
= 0xffffffff;
8850 sym
= (Stab_Sym
*)stab_section
->data
+ 1;
8851 sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
8852 while (sym
< sym_end
) {
8853 switch(sym
->n_type
) {
8854 /* function start or end */
8856 if (sym
->n_strx
== 0) {
8857 /* we test if between last line and end of function */
8858 pc
= sym
->n_value
+ func_addr
;
8859 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
8861 func_name
[0] = '\0';
8864 str
= stabstr_section
->data
+ sym
->n_strx
;
8865 p
= strchr(str
, ':');
8867 pstrcpy(func_name
, sizeof(func_name
), str
);
8870 if (len
> sizeof(func_name
) - 1)
8871 len
= sizeof(func_name
) - 1;
8872 memcpy(func_name
, str
, len
);
8873 func_name
[len
] = '\0';
8875 func_addr
= sym
->n_value
;
8878 /* line number info */
8880 pc
= sym
->n_value
+ func_addr
;
8881 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
8884 last_line_num
= sym
->n_desc
;
8886 strcpy(last_func_name
, func_name
);
8890 str
= stabstr_section
->data
+ sym
->n_strx
;
8892 if (incl_index
< INCLUDE_STACK_SIZE
) {
8893 incl_files
[incl_index
++] = str
;
8901 if (sym
->n_strx
== 0) {
8902 incl_index
= 0; /* end of translation unit */
8904 str
= stabstr_section
->data
+ sym
->n_strx
;
8905 /* do not add path */
8907 if (len
> 0 && str
[len
- 1] != '/')
8915 /* second pass: we try symtab symbols (no line number info) */
8918 Elf32_Sym
*sym
, *sym_end
;
8921 sym_end
= (Elf32_Sym
*)(symtab_section
->data
+ symtab_section
->data_offset
);
8922 for(sym
= (Elf32_Sym
*)symtab_section
->data
+ 1;
8925 type
= ELF32_ST_TYPE(sym
->st_info
);
8926 if (type
== STT_FUNC
) {
8927 if (wanted_pc
>= sym
->st_value
&&
8928 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
8929 pstrcpy(last_func_name
, sizeof(last_func_name
),
8930 strtab_section
->data
+ sym
->st_name
);
8936 /* did not find any info: */
8937 fprintf(stderr
, " ???\n");
8940 if (last_func_name
[0] != '\0') {
8941 fprintf(stderr
, " %s()", last_func_name
);
8943 if (incl_index
> 0) {
8944 fprintf(stderr
, " (%s:%d",
8945 incl_files
[incl_index
- 1], last_line_num
);
8946 for(i
= incl_index
- 2; i
>= 0; i
--)
8947 fprintf(stderr
, ", included from %s", incl_files
[i
]);
8948 fprintf(stderr
, ")");
8950 fprintf(stderr
, "\n");
8957 /* fix for glibc 2.1 */
8963 /* return the PC at frame level 'level'. Return non zero if not found */
8964 static int rt_get_caller_pc(unsigned long *paddr
,
8965 ucontext_t
*uc
, int level
)
8972 *paddr
= uc
->uc_mcontext
.mc_eip
;
8974 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
8979 fp
= uc
->uc_mcontext
.mc_ebp
;
8981 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
8983 for(i
=1;i
<level
;i
++) {
8984 /* XXX: check address validity with program info */
8985 if (fp
<= 0x1000 || fp
>= 0xc0000000)
8987 fp
= ((unsigned long *)fp
)[0];
8989 *paddr
= ((unsigned long *)fp
)[1];
8994 #error add arch specific rt_get_caller_pc()
8997 /* emit a run time error at position 'pc' */
8998 void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
9005 fprintf(stderr
, "Runtime error: ");
9006 vfprintf(stderr
, fmt
, ap
);
9007 fprintf(stderr
, "\n");
9008 for(i
=0;i
<num_callers
;i
++) {
9009 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
9012 fprintf(stderr
, "at ");
9014 fprintf(stderr
, "by ");
9021 /* signal handler for fatal errors */
9022 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
9024 ucontext_t
*uc
= puc
;
9028 switch(siginf
->si_code
) {
9031 rt_error(uc
, "division by zero");
9034 rt_error(uc
, "floating point exception");
9040 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
9041 rt_error(uc
, *rt_bound_error_msg
);
9043 rt_error(uc
, "dereferencing invalid pointer");
9046 rt_error(uc
, "illegal instruction");
9049 rt_error(uc
, "abort() called");
9052 rt_error(uc
, "caught signal %d", signum
);
9059 /* do all relocations (needed before using tcc_get_symbol()) */
9060 int tcc_relocate(TCCState
*s1
)
9067 tcc_add_runtime(s1
);
9069 relocate_common_syms();
9071 /* compute relocation address : section are relocated in place. We
9072 also alloc the bss space */
9073 for(i
= 1; i
< s1
->nb_sections
; i
++) {
9074 s
= s1
->sections
[i
];
9075 if (s
->sh_flags
& SHF_ALLOC
) {
9076 if (s
->sh_type
== SHT_NOBITS
)
9077 s
->data
= tcc_mallocz(s
->data_offset
);
9078 s
->sh_addr
= (unsigned long)s
->data
;
9082 relocate_syms(s1
, 1);
9084 if (s1
->nb_errors
!= 0)
9087 /* relocate each section */
9088 for(i
= 1; i
< s1
->nb_sections
; i
++) {
9089 s
= s1
->sections
[i
];
9091 relocate_section(s1
, s
);
9096 /* launch the compiled program with the given arguments */
9097 int tcc_run(TCCState
*s1
, int argc
, char **argv
)
9099 int (*prog_main
)(int, char **);
9101 if (tcc_relocate(s1
) < 0)
9104 prog_main
= tcc_get_symbol(s1
, "main");
9108 error("debug mode currently not available for Windows");
9110 struct sigaction sigact
;
9111 /* install TCC signal handlers to print debug info on fatal
9113 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
9114 sigact
.sa_sigaction
= sig_error
;
9115 sigemptyset(&sigact
.sa_mask
);
9116 sigaction(SIGFPE
, &sigact
, NULL
);
9117 sigaction(SIGILL
, &sigact
, NULL
);
9118 sigaction(SIGSEGV
, &sigact
, NULL
);
9119 sigaction(SIGBUS
, &sigact
, NULL
);
9120 sigaction(SIGABRT
, &sigact
, NULL
);
9124 #ifdef CONFIG_TCC_BCHECK
9125 if (do_bounds_check
) {
9126 void (*bound_init
)(void);
9128 /* set error function */
9129 rt_bound_error_msg
= (void *)tcc_get_symbol(s1
, "__bound_error_msg");
9131 /* XXX: use .init section so that it also work in binary ? */
9132 bound_init
= (void *)tcc_get_symbol(s1
, "__bound_init");
9136 return (*prog_main
)(argc
, argv
);
9139 TCCState
*tcc_new(void)
9146 s
= tcc_mallocz(sizeof(TCCState
));
9150 s
->output_type
= TCC_OUTPUT_MEMORY
;
9152 /* init isid table */
9154 isidnum_table
[i
] = isid(i
) || isnum(i
);
9156 /* add all tokens */
9158 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
9160 tok_ident
= TOK_IDENT
;
9169 ts
= tok_alloc(p
, r
- p
- 1);
9173 /* we add dummy defines for some special macros to speed up tests
9174 and to have working defined() */
9175 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
9176 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
9177 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
9178 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
9180 /* standard defines */
9181 tcc_define_symbol(s
, "__STDC__", NULL
);
9182 #if defined(TCC_TARGET_I386)
9183 tcc_define_symbol(s
, "__i386__", NULL
);
9186 tcc_define_symbol(s
, "__linux__", NULL
);
9187 tcc_define_symbol(s
, "linux", NULL
);
9189 /* tiny C specific defines */
9190 tcc_define_symbol(s
, "__TINYC__", NULL
);
9192 /* tiny C & gcc defines */
9193 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned int");
9194 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "int");
9195 tcc_define_symbol(s
, "__WCHAR_TYPE__", "int");
9197 /* default library paths */
9198 tcc_add_library_path(s
, "/usr/local/lib");
9199 tcc_add_library_path(s
, "/usr/lib");
9200 tcc_add_library_path(s
, "/lib");
9202 /* no section zero */
9203 dynarray_add((void ***)&s
->sections
, &s
->nb_sections
, NULL
);
9205 /* create standard sections */
9206 text_section
= new_section(s
, ".text", SHT_PROGBITS
, SHF_ALLOC
| SHF_EXECINSTR
);
9207 data_section
= new_section(s
, ".data", SHT_PROGBITS
, SHF_ALLOC
| SHF_WRITE
);
9208 bss_section
= new_section(s
, ".bss", SHT_NOBITS
, SHF_ALLOC
| SHF_WRITE
);
9210 /* symbols are always generated for linking stage */
9211 symtab_section
= new_symtab(s
, ".symtab", SHT_SYMTAB
, 0,
9213 ".hashtab", SHF_PRIVATE
);
9214 strtab_section
= symtab_section
->link
;
9216 /* private symbol table for dynamic symbols */
9217 s
->dynsymtab_section
= new_symtab(s
, ".dynsymtab", SHT_SYMTAB
, SHF_PRIVATE
,
9219 ".dynhashtab", SHF_PRIVATE
);
9220 s
->alacarte_link
= 1;
9224 void tcc_delete(TCCState
*s1
)
9228 /* free -D defines */
9232 n
= tok_ident
- TOK_IDENT
;
9233 for(i
= 0; i
< n
; i
++)
9234 tcc_free(table_ident
[i
]);
9235 tcc_free(table_ident
);
9237 /* free all sections */
9239 free_section(symtab_section
->hash
);
9241 free_section(s1
->dynsymtab_section
->hash
);
9242 free_section(s1
->dynsymtab_section
->link
);
9243 free_section(s1
->dynsymtab_section
);
9245 for(i
= 1; i
< s1
->nb_sections
; i
++)
9246 free_section(s1
->sections
[i
]);
9247 tcc_free(s1
->sections
);
9249 /* free loaded dlls array */
9250 for(i
= 0; i
< s1
->nb_loaded_dlls
; i
++)
9251 tcc_free(s1
->loaded_dlls
[i
]);
9252 tcc_free(s1
->loaded_dlls
);
9255 for(i
= 0; i
< s1
->nb_library_paths
; i
++)
9256 tcc_free(s1
->library_paths
[i
]);
9257 tcc_free(s1
->library_paths
);
9259 /* cached includes */
9260 for(i
= 0; i
< s1
->nb_cached_includes
; i
++)
9261 tcc_free(s1
->cached_includes
[i
]);
9262 tcc_free(s1
->cached_includes
);
9264 for(i
= 0; i
< s1
->nb_include_paths
; i
++)
9265 tcc_free(s1
->include_paths
[i
]);
9266 tcc_free(s1
->include_paths
);
9268 for(i
= 0; i
< s1
->nb_sysinclude_paths
; i
++)
9269 tcc_free(s1
->sysinclude_paths
[i
]);
9270 tcc_free(s1
->sysinclude_paths
);
9275 int tcc_add_include_path(TCCState
*s1
, const char *pathname
)
9279 pathname1
= tcc_strdup(pathname
);
9280 dynarray_add((void ***)&s1
->include_paths
, &s1
->nb_include_paths
, pathname1
);
9284 int tcc_add_sysinclude_path(TCCState
*s1
, const char *pathname
)
9288 pathname1
= tcc_strdup(pathname
);
9289 dynarray_add((void ***)&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
, pathname1
);
9293 static int tcc_add_file_internal(TCCState
*s1
, const char *filename
, int flags
)
9295 const char *ext
, *filename1
;
9298 BufferedFile
*saved_file
;
9300 /* find source file type with extension */
9301 filename1
= strrchr(filename
, '/');
9305 filename1
= filename
;
9306 ext
= strrchr(filename1
, '.');
9312 file
= tcc_open(s1
, filename
);
9314 if (flags
& AFF_PRINT_ERROR
) {
9315 error_noabort("file '%s' not found", filename
);
9321 if (!ext
|| !strcmp(ext
, "c")) {
9322 /* C file assumed */
9323 ret
= tcc_compile(s1
);
9325 #ifdef CONFIG_TCC_ASM
9326 if (!strcmp(ext
, "S")) {
9327 /* preprocessed assembler */
9328 ret
= tcc_assemble(s1
, 1);
9329 } else if (!strcmp(ext
, "s")) {
9330 /* non preprocessed assembler */
9331 ret
= tcc_assemble(s1
, 0);
9336 /* assume executable format: auto guess file type */
9337 if (read(fd
, &ehdr
, sizeof(ehdr
)) != sizeof(ehdr
)) {
9338 error_noabort("could not read header");
9341 lseek(fd
, 0, SEEK_SET
);
9343 if (ehdr
.e_ident
[0] == ELFMAG0
&&
9344 ehdr
.e_ident
[1] == ELFMAG1
&&
9345 ehdr
.e_ident
[2] == ELFMAG2
&&
9346 ehdr
.e_ident
[3] == ELFMAG3
) {
9347 file
->line_num
= 0; /* do not display line number if error */
9348 if (ehdr
.e_type
== ET_REL
) {
9349 ret
= tcc_load_object_file(s1
, fd
, 0);
9350 } else if (ehdr
.e_type
== ET_DYN
) {
9351 ret
= tcc_load_dll(s1
, fd
, filename
,
9352 (flags
& AFF_REFERENCED_DLL
) != 0);
9354 error_noabort("unrecognized ELF file");
9357 } else if (memcmp((char *)&ehdr
, ARMAG
, 8) == 0) {
9358 file
->line_num
= 0; /* do not display line number if error */
9359 ret
= tcc_load_archive(s1
, fd
);
9361 /* as GNU ld, consider it is an ld script if not recognized */
9362 ret
= tcc_load_ldscript(s1
);
9364 error_noabort("unrecognized file type");
9379 int tcc_add_file(TCCState
*s
, const char *filename
)
9381 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
);
9384 int tcc_add_library_path(TCCState
*s
, const char *pathname
)
9388 pathname1
= tcc_strdup(pathname
);
9389 dynarray_add((void ***)&s
->library_paths
, &s
->nb_library_paths
, pathname1
);
9393 /* find and load a dll. Return non zero if not found */
9394 /* XXX: add '-rpath' option support ? */
9395 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
)
9400 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
9401 snprintf(buf
, sizeof(buf
), "%s/%s",
9402 s
->library_paths
[i
], filename
);
9403 if (tcc_add_file_internal(s
, buf
, flags
) == 0)
9409 /* the library name is the same as the argument of the '-l' option */
9410 int tcc_add_library(TCCState
*s
, const char *libraryname
)
9416 /* first we look for the dynamic library if not static linking */
9417 if (!s
->static_link
) {
9418 snprintf(buf
, sizeof(buf
), "lib%s.so", libraryname
);
9419 /* if we output to memory, then we simply we dlopen(). */
9420 if (s
->output_type
== TCC_OUTPUT_MEMORY
) {
9421 /* Since the libc is already loaded, we don't need to load it again */
9422 if (!strcmp(libraryname
, "c"))
9424 h
= dlopen(buf
, RTLD_GLOBAL
| RTLD_LAZY
);
9428 if (tcc_add_dll(s
, buf
, 0) == 0)
9433 /* then we look for the static library */
9434 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
9435 snprintf(buf
, sizeof(buf
), "%s/lib%s.a",
9436 s
->library_paths
[i
], libraryname
);
9437 if (tcc_add_file_internal(s
, buf
, 0) == 0)
9443 int tcc_add_symbol(TCCState
*s
, const char *name
, unsigned long val
)
9445 add_elf_sym(symtab_section
, val
, 0,
9446 ELF32_ST_INFO(STB_GLOBAL
, STT_NOTYPE
),
9451 int tcc_set_output_type(TCCState
*s
, int output_type
)
9455 s
->output_type
= output_type
;
9458 /* default include paths */
9459 /* XXX: reverse order needed if -isystem support */
9460 tcc_add_sysinclude_path(s
, "/usr/local/include");
9461 tcc_add_sysinclude_path(s
, "/usr/include");
9462 snprintf(buf
, sizeof(buf
), "%s/include", tcc_lib_path
);
9463 tcc_add_sysinclude_path(s
, buf
);
9466 /* if bound checking, then add corresponding sections */
9467 #ifdef CONFIG_TCC_BCHECK
9468 if (do_bounds_check
) {
9470 tcc_define_symbol(s
, "__BOUNDS_CHECKING_ON", NULL
);
9471 /* create bounds sections */
9472 bounds_section
= new_section(s
, ".bounds",
9473 SHT_PROGBITS
, SHF_ALLOC
);
9474 lbounds_section
= new_section(s
, ".lbounds",
9475 SHT_PROGBITS
, SHF_ALLOC
);
9479 /* add debug sections */
9482 stab_section
= new_section(s
, ".stab", SHT_PROGBITS
, 0);
9483 stab_section
->sh_entsize
= sizeof(Stab_Sym
);
9484 stabstr_section
= new_section(s
, ".stabstr", SHT_STRTAB
, 0);
9485 put_elf_str(stabstr_section
, "");
9486 stab_section
->link
= stabstr_section
;
9487 /* put first entry */
9488 put_stabs("", 0, 0, 0, 0);
9491 /* add libc crt1/crti objects */
9492 if ((output_type
== TCC_OUTPUT_EXE
|| output_type
== TCC_OUTPUT_DLL
) &&
9494 if (output_type
!= TCC_OUTPUT_DLL
)
9495 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crt1.o");
9496 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crti.o");
9501 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
9503 typedef struct WarningDef
{
9509 static const WarningDef warning_defs
[] = {
9510 { offsetof(TCCState
, warn_unsupported
), 0, "unsupported" },
9511 { offsetof(TCCState
, warn_write_strings
), 0, "write-strings" },
9512 { offsetof(TCCState
, warn_error
), 0, "error" },
9515 /* set/reset a warning */
9516 int tcc_set_warning(TCCState
*s
, const char *warning_name
, int value
)
9519 const WarningDef
*p
;
9520 if (!strcmp(warning_name
, "all")) {
9521 for(i
= 0, p
= warning_defs
; i
< countof(warning_defs
); i
++, p
++) {
9522 if (p
->flags
& WD_ALL
)
9523 *(int *)((uint8_t *)s
+ p
->offset
) = 1;
9526 for(i
= 0, p
= warning_defs
; i
< countof(warning_defs
); i
++, p
++) {
9527 if (!strcmp(warning_name
, p
->name
))
9532 *(int *)((uint8_t *)s
+ p
->offset
) = value
;
9538 #if !defined(LIBTCC)
9540 /* extract the basename of a file */
9541 static const char *tcc_basename(const char *name
)
9544 p
= strrchr(name
, '/');
9547 p
= strrchr(name
, '\\');
9556 static int64_t getclock_us(void)
9561 return (tb
.time
* 1000LL + tb
.millitm
) * 1000LL;
9564 gettimeofday(&tv
, NULL
);
9565 return tv
.tv_sec
* 1000000LL + tv
.tv_usec
;
9571 printf("tcc version " TCC_VERSION
" - Tiny C Compiler - Copyright (C) 2001-2003 Fabrice Bellard\n"
9572 "usage: tcc [-v] [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"
9573 " [-Wwarn] [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-static]\n"
9574 " [infile1 infile2...] [-run infile args...]\n"
9576 "General options:\n"
9577 " -v display current version\n"
9578 " -c compile only - generate an object file\n"
9579 " -o outfile set output filename\n"
9580 " -Bdir set tcc internal library path\n"
9581 " -bench output compilation statistics\n"
9582 " -run run compiled source\n"
9583 " -Wwarning set or reset (with 'no-' prefix) 'warning'\n"
9584 "Preprocessor options:\n"
9585 " -Idir add include path 'dir'\n"
9586 " -Dsym[=val] define 'sym' with value 'val'\n"
9587 " -Usym undefine 'sym'\n"
9589 " -Ldir add library path 'dir'\n"
9590 " -llib link with dynamic or static library 'lib'\n"
9591 " -shared generate a shared library\n"
9592 " -static static linking\n"
9593 " -rdynamic export all global symbols to dynamic linker\n"
9594 " -r relocatable output\n"
9595 "Debugger options:\n"
9596 " -g generate runtime debug info\n"
9597 #ifdef CONFIG_TCC_BCHECK
9598 " -b compile with built-in memory and bounds checker (implies -g)\n"
9600 " -bt N show N callers in stack traces\n"
9604 #define TCC_OPTION_HAS_ARG 0x0001
9605 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
9607 typedef struct TCCOption
{
9634 TCC_OPTION_nostdinc
,
9635 TCC_OPTION_nostdlib
,
9636 TCC_OPTION_print_search_dirs
,
9637 TCC_OPTION_rdynamic
,
9642 static const TCCOption tcc_options
[] = {
9643 { "h", TCC_OPTION_HELP
, 0 },
9644 { "?", TCC_OPTION_HELP
, 0 },
9645 { "I", TCC_OPTION_I
, TCC_OPTION_HAS_ARG
},
9646 { "D", TCC_OPTION_D
, TCC_OPTION_HAS_ARG
},
9647 { "U", TCC_OPTION_U
, TCC_OPTION_HAS_ARG
},
9648 { "L", TCC_OPTION_L
, TCC_OPTION_HAS_ARG
},
9649 { "B", TCC_OPTION_B
, TCC_OPTION_HAS_ARG
},
9650 { "l", TCC_OPTION_l
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9651 { "bench", TCC_OPTION_bench
, 0 },
9652 { "bt", TCC_OPTION_bt
, TCC_OPTION_HAS_ARG
},
9653 #ifdef CONFIG_TCC_BCHECK
9654 { "b", TCC_OPTION_b
, 0 },
9656 { "g", TCC_OPTION_g
, 0 },
9657 { "c", TCC_OPTION_c
, 0 },
9658 { "static", TCC_OPTION_static
, 0 },
9659 { "shared", TCC_OPTION_shared
, 0 },
9660 { "o", TCC_OPTION_o
, TCC_OPTION_HAS_ARG
},
9661 { "run", TCC_OPTION_run
, 0 },
9662 { "rdynamic", TCC_OPTION_rdynamic
, 0 },
9663 { "r", TCC_OPTION_r
, 0 },
9664 { "W", TCC_OPTION_W
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9665 { "O", TCC_OPTION_O
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9666 { "m", TCC_OPTION_m
, TCC_OPTION_HAS_ARG
},
9667 { "f", TCC_OPTION_f
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9668 { "nostdinc", TCC_OPTION_nostdinc
, 0 },
9669 { "nostdlib", TCC_OPTION_nostdlib
, 0 },
9670 { "print-search-dirs", TCC_OPTION_print_search_dirs
, 0 },
9671 { "v", TCC_OPTION_v
, 0 },
9675 int main(int argc
, char **argv
)
9678 int optind
, output_type
, multiple_files
, i
, reloc_output
;
9681 int nb_files
, nb_libraries
, nb_objfiles
, dminus
, ret
;
9682 char objfilename
[1024];
9683 int64_t start_time
= 0;
9684 const TCCOption
*popt
;
9685 const char *optarg
, *p1
, *r1
, *outfile
;
9686 int print_search_dirs
;
9689 output_type
= TCC_OUTPUT_EXE
;
9699 print_search_dirs
= 0;
9701 if (optind
>= argc
) {
9702 if (nb_files
== 0 && !print_search_dirs
)
9709 /* add a new file */
9710 dynarray_add((void ***)&files
, &nb_files
, r
);
9711 if (!multiple_files
) {
9713 /* argv[0] will be this file */
9717 /* find option in table (match only the first chars */
9722 error("invalid option -- '%s'", r
);
9735 if (popt
->flags
& TCC_OPTION_HAS_ARG
) {
9736 if (*r1
!= '\0' || (popt
->flags
& TCC_OPTION_NOSEP
)) {
9740 error("argument to '%s' is missing", r
);
9741 optarg
= argv
[optind
++];
9749 switch(popt
->index
) {
9750 case TCC_OPTION_HELP
:
9755 if (tcc_add_include_path(s
, optarg
) < 0)
9756 error("too many include paths");
9761 sym
= (char *)optarg
;
9762 value
= strchr(sym
, '=');
9767 tcc_define_symbol(s
, sym
, value
);
9771 tcc_undefine_symbol(s
, optarg
);
9774 tcc_add_library_path(s
, optarg
);
9777 /* set tcc utilities path (mainly for tcc development) */
9778 tcc_lib_path
= optarg
;
9781 dynarray_add((void ***)&files
, &nb_files
, r
);
9784 case TCC_OPTION_bench
:
9788 num_callers
= atoi(optarg
);
9790 #ifdef CONFIG_TCC_BCHECK
9792 do_bounds_check
= 1;
9801 output_type
= TCC_OUTPUT_OBJ
;
9803 case TCC_OPTION_static
:
9806 case TCC_OPTION_shared
:
9807 output_type
= TCC_OUTPUT_DLL
;
9814 /* generate a .o merging several output files */
9816 output_type
= TCC_OUTPUT_OBJ
;
9818 case TCC_OPTION_nostdinc
:
9821 case TCC_OPTION_nostdlib
:
9824 case TCC_OPTION_print_search_dirs
:
9825 print_search_dirs
= 1;
9827 case TCC_OPTION_run
:
9829 output_type
= TCC_OUTPUT_MEMORY
;
9832 printf("tcc version %s\n", TCC_VERSION
);
9836 const char *p
= optarg
;
9839 if (p
[0] == 'n' && p
[1] == 'o' && p
[2] == '-') {
9843 if (tcc_set_warning(s
, p
, value
) < 0 && s
->warn_unsupported
)
9844 goto unsupported_option
;
9847 case TCC_OPTION_rdynamic
:
9851 if (s
->warn_unsupported
) {
9853 warning("unsupported option '%s'", r
);
9859 if (print_search_dirs
) {
9860 /* enough for Linux kernel */
9861 printf("install: %s/\n", tcc_lib_path
);
9865 nb_objfiles
= nb_files
- nb_libraries
;
9867 /* if outfile provided without other options, we output an
9869 if (outfile
&& output_type
== TCC_OUTPUT_MEMORY
)
9870 output_type
= TCC_OUTPUT_EXE
;
9872 /* check -c consistency : only single file handled. XXX: checks file type */
9873 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
9874 /* accepts only a single input file */
9875 if (nb_objfiles
!= 1)
9876 error("cannot specify multiple files with -c");
9877 if (nb_libraries
!= 0)
9878 error("cannot specify libraries with -c");
9881 /* compute default outfile name */
9882 if (output_type
!= TCC_OUTPUT_MEMORY
&& !outfile
) {
9883 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
9886 pstrcpy(objfilename
, sizeof(objfilename
) - 1,
9887 tcc_basename(files
[0]));
9888 /* add .o extension */
9889 ext
= strrchr(objfilename
, '.');
9891 goto default_outfile
;
9892 strcpy(ext
+ 1, "o");
9895 pstrcpy(objfilename
, sizeof(objfilename
), "a.out");
9897 outfile
= objfilename
;
9901 start_time
= getclock_us();
9904 tcc_set_output_type(s
, output_type
);
9906 /* compile or add each files or library */
9907 for(i
= 0;i
< nb_files
; i
++) {
9908 const char *filename
;
9910 filename
= files
[i
];
9911 if (filename
[0] == '-') {
9912 if (tcc_add_library(s
, filename
+ 2) < 0)
9913 error("cannot find %s", filename
);
9915 if (tcc_add_file(s
, filename
) < 0) {
9922 /* free all files */
9927 total_time
= (double)(getclock_us() - start_time
) / 1000000.0;
9928 if (total_time
< 0.001)
9930 if (total_bytes
< 1)
9932 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
9933 tok_ident
- TOK_IDENT
, total_lines
, total_bytes
,
9934 total_time
, (int)(total_lines
/ total_time
),
9935 total_bytes
/ total_time
/ 1000000.0);
9938 if (s
->output_type
!= TCC_OUTPUT_MEMORY
) {
9939 tcc_output_file(s
, outfile
);
9942 ret
= tcc_run(s
, argc
- optind
, argv
+ optind
);
9945 /* XXX: cannot do it with bound checking because of the malloc hooks */
9946 if (!do_bounds_check
)
9951 printf("memory: %d bytes, max = %d bytes\n", mem_cur_size
, mem_max_size
);