2 * TCC - Tiny C Compiler
4 * Copyright (c) 2001-2004 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26 #define CONFIG_TCC_STATIC
43 #include <sys/timeb.h>
45 #define inline __inline
52 #include <sys/ucontext.h>
56 #endif /* !CONFIG_TCCBOOT */
73 /* preprocessor debug */
75 /* include file debug */
83 /* target selection */
84 //#define TCC_TARGET_I386 /* i386 code generator */
85 //#define TCC_TARGET_ARM /* ARMv4 code generator */
86 //#define TCC_TARGET_C67 /* TMS320C67xx code generator */
87 //#define TCC_TARGET_X86_64 /* x86-64 code generator */
89 /* default target is I386 */
90 #if !defined(TCC_TARGET_I386) && !defined(TCC_TARGET_ARM) && \
91 !defined(TCC_TARGET_C67) && !defined(TCC_TARGET_X86_64)
92 #define TCC_TARGET_I386
95 #if !defined(_WIN32) && !defined(TCC_UCLIBC) && !defined(TCC_TARGET_ARM) && \
96 !defined(TCC_TARGET_C67) && !defined(TCC_TARGET_X86_64)
97 #define CONFIG_TCC_BCHECK /* enable bound checking code */
100 #if defined(_WIN32) && !defined(TCC_TARGET_PE)
101 #define CONFIG_TCC_STATIC
104 /* define it to include assembler support */
105 #if !defined(TCC_TARGET_ARM) && !defined(TCC_TARGET_C67) && \
106 !defined(TCC_TARGET_X86_64)
107 #define CONFIG_TCC_ASM
110 /* object format selection */
111 #if defined(TCC_TARGET_C67)
112 #define TCC_TARGET_COFF
121 /* path to find crt1.o, crti.o and crtn.o. Only needed when generating
122 executables or dlls */
123 #define CONFIG_TCC_CRT_PREFIX CONFIG_SYSROOT "/usr/lib"
125 #define INCLUDE_STACK_SIZE 32
126 #define IFDEF_STACK_SIZE 64
127 #define VSTACK_SIZE 256
128 #define STRING_MAX_SIZE 1024
129 #define PACK_STACK_SIZE 8
131 #define TOK_HASH_SIZE 8192 /* must be a power of two */
132 #define TOK_ALLOC_INCR 512 /* must be a power of two */
133 #define TOK_MAX_SIZE 4 /* token max size in int unit when stored in string */
135 /* token symbol management */
136 typedef struct TokenSym
{
137 struct TokenSym
*hash_next
;
138 struct Sym
*sym_define
; /* direct pointer to define */
139 struct Sym
*sym_label
; /* direct pointer to label */
140 struct Sym
*sym_struct
; /* direct pointer to structure */
141 struct Sym
*sym_identifier
; /* direct pointer to identifier */
142 int tok
; /* token number */
148 typedef unsigned short nwchar_t
;
150 typedef int nwchar_t
;
153 typedef struct CString
{
154 int size
; /* size in bytes */
155 void *data
; /* either 'char *' or 'nwchar_t *' */
157 void *data_allocated
; /* if non NULL, data has been malloced */
160 /* type definition */
161 typedef struct CType
{
167 typedef union CValue
{
173 unsigned int ul
; /* address (should be unsigned long on 64 bit cpu) */
175 unsigned long long ull
;
176 struct CString
*cstr
;
182 typedef struct SValue
{
183 CType type
; /* type */
184 unsigned short r
; /* register + flags */
185 unsigned short r2
; /* second register, used for 'long long'
186 type. If not used, set to VT_CONST */
187 CValue c
; /* constant, if VT_CONST */
188 struct Sym
*sym
; /* symbol, if (VT_SYM | VT_CONST) */
191 /* symbol management */
193 int v
; /* symbol token */
194 long r
; /* associated register */
195 long c
; /* associated number */
196 CType type
; /* associated type */
197 struct Sym
*next
; /* next related symbol */
198 struct Sym
*prev
; /* prev symbol in stack */
199 struct Sym
*prev_tok
; /* previous symbol for this token */
202 /* section definition */
203 /* XXX: use directly ELF structure for parameters ? */
204 /* special flag to indicate that the section should not be linked to
206 #define SHF_PRIVATE 0x80000000
208 typedef struct Section
{
209 unsigned long data_offset
; /* current data offset */
210 unsigned char *data
; /* section data */
211 unsigned long data_allocated
; /* used for realloc() handling */
212 int sh_name
; /* elf section name (only used during output) */
213 int sh_num
; /* elf section number */
214 int sh_type
; /* elf section type */
215 int sh_flags
; /* elf section flags */
216 int sh_info
; /* elf section info */
217 int sh_addralign
; /* elf section alignment */
218 int sh_entsize
; /* elf entry size */
219 unsigned long sh_size
; /* section size (only used during output) */
220 unsigned long sh_addr
; /* address at which the section is relocated */
221 unsigned long sh_offset
; /* file offset */
222 int nb_hashed_syms
; /* used to resize the hash table */
223 struct Section
*link
; /* link to another section */
224 struct Section
*reloc
; /* corresponding section for relocation, if any */
225 struct Section
*hash
; /* hash table for symbols */
226 struct Section
*next
;
227 char name
[1]; /* section name */
230 typedef struct DLLReference
{
236 /* GNUC attribute definition */
237 typedef struct AttributeDef
{
241 int func_attr
; /* calling convention, exports, ... */
244 /* -------------------------------------------------- */
245 /* gr: wrappers for casting sym->r for other purposes */
253 #define FUNC_CALL(r) (((func_attr_t*)&(r))->func_call)
254 #define FUNC_EXPORT(r) (((func_attr_t*)&(r))->func_export)
255 #define FUNC_ARGS(r) (((func_attr_t*)&(r))->func_args)
256 #define INLINE_DEF(r) (*(int **)&(r))
257 /* -------------------------------------------------- */
259 #define SYM_STRUCT 0x40000000 /* struct/union/enum symbol space */
260 #define SYM_FIELD 0x20000000 /* struct/union field symbol space */
261 #define SYM_FIRST_ANOM 0x10000000 /* first anonymous sym */
263 /* stored in 'Sym.c' field */
264 #define FUNC_NEW 1 /* ansi function prototype */
265 #define FUNC_OLD 2 /* old function prototype */
266 #define FUNC_ELLIPSIS 3 /* ansi function prototype with ... */
268 /* stored in 'Sym.r' field */
269 #define FUNC_CDECL 0 /* standard c call */
270 #define FUNC_STDCALL 1 /* pascal c call */
271 #define FUNC_FASTCALL1 2 /* first param in %eax */
272 #define FUNC_FASTCALL2 3 /* first parameters in %eax, %edx */
273 #define FUNC_FASTCALL3 4 /* first parameter in %eax, %edx, %ecx */
274 #define FUNC_FASTCALLW 5 /* first parameter in %ecx, %edx */
276 /* field 'Sym.t' for macros */
277 #define MACRO_OBJ 0 /* object like macro */
278 #define MACRO_FUNC 1 /* function like macro */
280 /* field 'Sym.r' for C labels */
281 #define LABEL_DEFINED 0 /* label is defined */
282 #define LABEL_FORWARD 1 /* label is forward defined */
283 #define LABEL_DECLARED 2 /* label is declared but never used */
285 /* type_decl() types */
286 #define TYPE_ABSTRACT 1 /* type without variable */
287 #define TYPE_DIRECT 2 /* type with variable */
289 #define IO_BUF_SIZE 8192
291 typedef struct BufferedFile
{
295 int line_num
; /* current line number - here to simplify code */
296 int ifndef_macro
; /* #ifndef macro / #endif search */
297 int ifndef_macro_saved
; /* saved ifndef_macro */
298 int *ifdef_stack_ptr
; /* ifdef_stack value at the start of the file */
299 char inc_type
; /* type of include */
300 char inc_filename
[512]; /* filename specified by the user */
301 char filename
[1024]; /* current filename - here to simplify code */
302 unsigned char buffer
[IO_BUF_SIZE
+ 1]; /* extra size for CH_EOB char */
305 #define CH_EOB '\\' /* end of buffer or '\0' char in file */
306 #define CH_EOF (-1) /* end of file */
308 /* parsing state (used to save parser state to reparse part of the
309 source several times) */
310 typedef struct ParseState
{
317 /* used to record tokens */
318 typedef struct TokenString
{
325 /* include file cache, used to find files faster and also to eliminate
326 inclusion if the include file is protected by #ifndef ... #endif */
327 typedef struct CachedInclude
{
329 int hash_next
; /* -1 if none */
330 char type
; /* '"' or '>' to give include type */
331 char filename
[1]; /* path specified in #include */
334 #define CACHED_INCLUDES_HASH_SIZE 512
337 static struct BufferedFile
*file
;
339 static CString tok_spaces
; /* spaces before current token */
341 static CString tokcstr
; /* current parsed string, if any */
342 /* additional informations about token */
343 static int tok_flags
;
344 #define TOK_FLAG_BOL 0x0001 /* beginning of line before */
345 #define TOK_FLAG_BOF 0x0002 /* beginning of file before */
346 #define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */
347 #define TOK_FLAG_EOF 0x0008 /* end of file */
349 static int *macro_ptr
, *macro_ptr_allocated
;
350 static int *unget_saved_macro_ptr
;
351 static int unget_saved_buffer
[TOK_MAX_SIZE
+ 1];
352 static int unget_buffer_enabled
;
353 static int parse_flags
;
354 #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
355 #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
356 #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
357 token. line feed is also
359 #define PARSE_FLAG_ASM_COMMENTS 0x0008 /* '#' can be used for line comment */
361 static Section
*text_section
, *data_section
, *bss_section
; /* predefined sections */
362 static Section
*cur_text_section
; /* current section where function code is
364 #ifdef CONFIG_TCC_ASM
365 static Section
*last_text_section
; /* to handle .previous asm directive */
367 /* bound check related sections */
368 static Section
*bounds_section
; /* contains global data bound description */
369 static Section
*lbounds_section
; /* contains local data bound description */
370 /* symbol sections */
371 static Section
*symtab_section
, *strtab_section
;
374 static Section
*stab_section
, *stabstr_section
;
376 /* loc : local variable index
377 ind : output code index
379 anon_sym: anonymous symbol index
381 static int rsym
, anon_sym
, ind
, loc
;
382 /* expression generation modifiers */
383 static int const_wanted
; /* true if constant wanted */
384 static int nocode_wanted
; /* true if no code generation wanted for an expression */
385 static int global_expr
; /* true if compound literals must be allocated
386 globally (used during initializers parsing */
387 static CType func_vt
; /* current function return type (used by return
390 static int last_line_num
, last_ind
, func_ind
; /* debug last line number and pc */
391 static int tok_ident
;
392 static TokenSym
**table_ident
;
393 static TokenSym
*hash_ident
[TOK_HASH_SIZE
];
394 static char token_buf
[STRING_MAX_SIZE
+ 1];
395 static char *funcname
;
396 static Sym
*global_stack
, *local_stack
;
397 static Sym
*define_stack
;
398 static Sym
*global_label_stack
, *local_label_stack
;
399 /* symbol allocator */
400 #define SYM_POOL_NB (8192 / sizeof(Sym))
401 static Sym
*sym_free_first
;
402 static void **sym_pools
;
403 static int nb_sym_pools
;
405 static SValue vstack
[VSTACK_SIZE
], *vtop
;
406 /* some predefined types */
407 static CType char_pointer_type
, func_old_type
, int_type
;
408 /* true if isid(c) || isnum(c) */
409 static unsigned char isidnum_table
[256-CH_EOF
];
411 /* display some information during compilation */
412 static int verbose
= 0;
414 /* compile with debug symbol (and use them if error during execution) */
415 static int do_debug
= 0;
417 /* compile with built-in memory and bounds checker */
418 static int do_bounds_check
= 0;
420 /* display benchmark infos */
422 static int do_bench
= 0;
424 static int total_lines
;
425 static int total_bytes
;
427 /* use GNU C extensions */
428 static int gnu_ext
= 1;
430 /* use Tiny C extensions */
431 static int tcc_ext
= 1;
433 /* max number of callers shown if error */
434 static int num_callers
= 6;
435 static const char **rt_bound_error_msg
;
437 /* XXX: get rid of this ASAP */
438 static struct TCCState
*tcc_state
;
440 /* give the path of the tcc libraries */
441 static const char *tcc_lib_path
= CONFIG_TCCDIR
;
446 BufferedFile
**include_stack_ptr
;
447 int *ifdef_stack_ptr
;
449 /* include file handling */
450 char **include_paths
;
451 int nb_include_paths
;
452 char **sysinclude_paths
;
453 int nb_sysinclude_paths
;
454 CachedInclude
**cached_includes
;
455 int nb_cached_includes
;
457 char **library_paths
;
458 int nb_library_paths
;
460 /* array of all loaded dlls (including those referenced by loaded
462 DLLReference
**loaded_dlls
;
467 int nb_sections
; /* number of sections, including first dummy section */
469 Section
**priv_sections
;
470 int nb_priv_sections
; /* number of private sections */
475 unsigned long *got_offsets
;
477 /* give the correspondance from symtab indexes to dynsym indexes */
478 int *symtab_to_dynsym
;
480 /* temporary dynamic symbol sections (for dll loading) */
481 Section
*dynsymtab_section
;
482 /* exported dynamic symbol section */
485 int nostdinc
; /* if true, no standard headers are added */
486 int nostdlib
; /* if true, no standard libraries are added */
488 int nocommon
; /* if true, do not use common symbols for .bss data */
490 /* if true, static linking is performed */
493 /* soname as specified on the command line (-soname) */
496 /* if true, all symbols are exported */
499 /* if true, only link in referenced objects from archive */
502 /* address of text section */
503 unsigned long text_addr
;
506 /* output format, see TCC_OUTPUT_FORMAT_xxx */
509 /* C language options */
510 int char_is_unsigned
;
511 int leading_underscore
;
513 /* warning switches */
514 int warn_write_strings
;
515 int warn_unsupported
;
518 int warn_implicit_function_declaration
;
522 void (*error_func
)(void *opaque
, const char *msg
);
523 int error_set_jmp_enabled
;
524 jmp_buf error_jmp_buf
;
527 /* tiny assembler state */
530 /* see include_stack_ptr */
531 BufferedFile
*include_stack
[INCLUDE_STACK_SIZE
];
533 /* see ifdef_stack_ptr */
534 int ifdef_stack
[IFDEF_STACK_SIZE
];
536 /* see cached_includes */
537 int cached_includes_hash
[CACHED_INCLUDES_HASH_SIZE
];
540 int pack_stack
[PACK_STACK_SIZE
];
543 /* output file for preprocessing */
546 /* for tcc_relocate */
550 /* The current value can be: */
551 #define VT_VALMASK 0x00ff
552 #define VT_CONST 0x00f0 /* constant in vc
553 (must be first non register value) */
554 #define VT_LLOCAL 0x00f1 /* lvalue, offset on stack */
555 #define VT_LOCAL 0x00f2 /* offset on stack */
556 #define VT_CMP 0x00f3 /* the value is stored in processor flags (in vc) */
557 #define VT_JMP 0x00f4 /* value is the consequence of jmp true (even) */
558 #define VT_JMPI 0x00f5 /* value is the consequence of jmp false (odd) */
559 #define VT_LVAL 0x0100 /* var is an lvalue */
560 #define VT_SYM 0x0200 /* a symbol value is added */
561 #define VT_MUSTCAST 0x0400 /* value must be casted to be correct (used for
562 char/short stored in integer registers) */
563 #define VT_MUSTBOUND 0x0800 /* bound checking must be done before
564 dereferencing value */
565 #define VT_BOUNDED 0x8000 /* value is bounded. The address of the
566 bounding function call point is in vc */
567 #define VT_LVAL_BYTE 0x1000 /* lvalue is a byte */
568 #define VT_LVAL_SHORT 0x2000 /* lvalue is a short */
569 #define VT_LVAL_UNSIGNED 0x4000 /* lvalue is unsigned */
570 #define VT_LVAL_TYPE (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
573 #define VT_INT 0 /* integer type */
574 #define VT_BYTE 1 /* signed byte type */
575 #define VT_SHORT 2 /* short type */
576 #define VT_VOID 3 /* void type */
577 #define VT_PTR 4 /* pointer */
578 #define VT_ENUM 5 /* enum definition */
579 #define VT_FUNC 6 /* function type */
580 #define VT_STRUCT 7 /* struct/union definition */
581 #define VT_FLOAT 8 /* IEEE float */
582 #define VT_DOUBLE 9 /* IEEE double */
583 #define VT_LDOUBLE 10 /* IEEE long double */
584 #define VT_BOOL 11 /* ISOC99 boolean type */
585 #define VT_LLONG 12 /* 64 bit integer */
586 #define VT_LONG 13 /* long integer (NEVER USED as type, only
588 #define VT_BTYPE 0x000f /* mask for basic type */
589 #define VT_UNSIGNED 0x0010 /* unsigned type */
590 #define VT_ARRAY 0x0020 /* array type (also has VT_PTR) */
591 #define VT_BITFIELD 0x0040 /* bitfield modifier */
592 #define VT_CONSTANT 0x0800 /* const modifier */
593 #define VT_VOLATILE 0x1000 /* volatile modifier */
594 #define VT_SIGNED 0x2000 /* signed type */
597 #define VT_EXTERN 0x00000080 /* extern definition */
598 #define VT_STATIC 0x00000100 /* static variable */
599 #define VT_TYPEDEF 0x00000200 /* typedef definition */
600 #define VT_INLINE 0x00000400 /* inline definition */
602 #define VT_STRUCT_SHIFT 16 /* shift for bitfield shift values */
604 /* type mask (except storage) */
605 #define VT_STORAGE (VT_EXTERN | VT_STATIC | VT_TYPEDEF | VT_INLINE)
606 #define VT_TYPE (~(VT_STORAGE))
610 /* warning: the following compare tokens depend on i386 asm code */
617 #define TOK_Nset 0x98
618 #define TOK_Nclear 0x99
624 #define TOK_LAND 0xa0
628 #define TOK_MID 0xa3 /* inc/dec, to void constant */
630 #define TOK_UDIV 0xb0 /* unsigned division */
631 #define TOK_UMOD 0xb1 /* unsigned modulo */
632 #define TOK_PDIV 0xb2 /* fast division with undefined rounding for pointers */
633 #define TOK_CINT 0xb3 /* number in tokc */
634 #define TOK_CCHAR 0xb4 /* char constant in tokc */
635 #define TOK_STR 0xb5 /* pointer to string in tokc */
636 #define TOK_TWOSHARPS 0xb6 /* ## preprocessing token */
637 #define TOK_LCHAR 0xb7
638 #define TOK_LSTR 0xb8
639 #define TOK_CFLOAT 0xb9 /* float constant */
640 #define TOK_LINENUM 0xba /* line number info */
641 #define TOK_CDOUBLE 0xc0 /* double constant */
642 #define TOK_CLDOUBLE 0xc1 /* long double constant */
643 #define TOK_UMULL 0xc2 /* unsigned 32x32 -> 64 mul */
644 #define TOK_ADDC1 0xc3 /* add with carry generation */
645 #define TOK_ADDC2 0xc4 /* add with carry use */
646 #define TOK_SUBC1 0xc5 /* add with carry generation */
647 #define TOK_SUBC2 0xc6 /* add with carry use */
648 #define TOK_CUINT 0xc8 /* unsigned int constant */
649 #define TOK_CLLONG 0xc9 /* long long constant */
650 #define TOK_CULLONG 0xca /* unsigned long long constant */
651 #define TOK_ARROW 0xcb
652 #define TOK_DOTS 0xcc /* three dots */
653 #define TOK_SHR 0xcd /* unsigned shift right */
654 #define TOK_PPNUM 0xce /* preprocessor number */
656 #define TOK_SHL 0x01 /* shift left */
657 #define TOK_SAR 0x02 /* signed shift right */
659 /* assignement operators : normal operator or 0x80 */
660 #define TOK_A_MOD 0xa5
661 #define TOK_A_AND 0xa6
662 #define TOK_A_MUL 0xaa
663 #define TOK_A_ADD 0xab
664 #define TOK_A_SUB 0xad
665 #define TOK_A_DIV 0xaf
666 #define TOK_A_XOR 0xde
667 #define TOK_A_OR 0xfc
668 #define TOK_A_SHL 0x81
669 #define TOK_A_SAR 0x82
672 #define offsetof(type, field) ((size_t) &((type *)0)->field)
676 #define countof(tab) (sizeof(tab) / sizeof((tab)[0]))
679 /* WARNING: the content of this string encodes token numbers */
680 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";
682 #define TOK_EOF (-1) /* end of file */
683 #define TOK_LINEFEED 10 /* line feed */
685 /* all identificators and strings have token above that */
686 #define TOK_IDENT 256
688 /* only used for i386 asm opcodes definitions */
689 #define DEF_ASM(x) DEF(TOK_ASM_ ## x, #x)
692 DEF(TOK_ASM_ ## x ## b, #x "b") \
693 DEF(TOK_ASM_ ## x ## w, #x "w") \
694 DEF(TOK_ASM_ ## x ## l, #x "l") \
695 DEF(TOK_ASM_ ## x, #x)
698 DEF(TOK_ASM_ ## x ## w, #x "w") \
699 DEF(TOK_ASM_ ## x ## l, #x "l") \
700 DEF(TOK_ASM_ ## x, #x)
703 DEF(TOK_ASM_ ## f ## x ## s, "f" #x "s") \
704 DEF(TOK_ASM_ ## fi ## x ## l, "fi" #x "l") \
705 DEF(TOK_ASM_ ## f ## x ## l, "f" #x "l") \
706 DEF(TOK_ASM_ ## fi ## x ## s, "fi" #x "s")
709 DEF(TOK_ASM_ ## f ## x, "f" #x ) \
710 DEF(TOK_ASM_ ## f ## x ## p, "f" #x "p") \
713 #define DEF_ASMTEST(x) \
745 #define TOK_ASM_int TOK_INT
748 TOK_LAST
= TOK_IDENT
- 1,
749 #define DEF(id, str) id,
754 static const char tcc_keywords
[] =
755 #define DEF(id, str) str "\0"
760 #define TOK_UIDENT TOK_DEFINE
763 #define snprintf _snprintf
764 #define vsnprintf _vsnprintf
766 #define strtold (long double)strtod
767 #define strtof (float)strtod
768 #define strtoll (long long)strtol
770 #elif defined(TCC_UCLIBC) || defined(__FreeBSD__) || defined(__DragonFly__) \
771 || defined(__OpenBSD__)
772 /* currently incorrect */
773 long double strtold(const char *nptr
, char **endptr
)
775 return (long double)strtod(nptr
, endptr
);
777 float strtof(const char *nptr
, char **endptr
)
779 return (float)strtod(nptr
, endptr
);
782 /* XXX: need to define this to use them in non ISOC99 context */
783 extern float strtof (const char *__nptr
, char **__endptr
);
784 extern long double strtold (const char *__nptr
, char **__endptr
);
787 static char *pstrcpy(char *buf
, int buf_size
, const char *s
);
788 static char *pstrcat(char *buf
, int buf_size
, const char *s
);
789 static char *tcc_basename(const char *name
);
790 static char *tcc_fileextension (const char *p
);
792 static void next(void);
793 static void next_nomacro(void);
794 static void parse_expr_type(CType
*type
);
795 static void expr_type(CType
*type
);
796 static void unary_type(CType
*type
);
797 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
798 int case_reg
, int is_expr
);
799 static int expr_const(void);
800 static void expr_eq(void);
801 static void gexpr(void);
802 static void gen_inline_functions(void);
803 static void decl(int l
);
804 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
805 int first
, int size_only
);
806 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
807 int has_init
, int v
, int scope
);
809 void gv2(int rc1
, int rc2
);
810 void move_reg(int r
, int s
);
811 void save_regs(int n
);
812 void save_reg(int r
);
817 int get_reg_ex(int rc
,int rc2
);
820 struct macro_level
*prev
;
824 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
825 const int *macro_str
, struct macro_level
**can_read_stream
);
827 void force_charshort_cast(int t
);
828 static void gen_cast(CType
*type
);
830 static Sym
*sym_find(int v
);
831 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
);
834 static int type_size(CType
*type
, int *a
);
835 static inline CType
*pointed_type(CType
*type
);
836 static int pointed_size(CType
*type
);
837 static int lvalue_type(int t
);
838 static int parse_btype(CType
*type
, AttributeDef
*ad
);
839 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
);
840 static int compare_types(CType
*type1
, CType
*type2
, int unqualified
);
841 static int is_compatible_types(CType
*type1
, CType
*type2
);
842 static int is_compatible_parameter_types(CType
*type1
, CType
*type2
);
844 int ieee_finite(double d
);
845 void error(const char *fmt
, ...);
847 void vpushll(long long v
);
850 void lexpand_nr(void);
851 static void vpush_global_sym(CType
*type
, int v
);
852 void vset(CType
*type
, int r
, int v
);
853 void type_to_str(char *buf
, int buf_size
,
854 CType
*type
, const char *varstr
);
855 char *get_tok_str(int v
, CValue
*cv
);
856 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
857 unsigned long offset
, unsigned long size
);
858 static Sym
*external_global_sym(int v
, CType
*type
, int r
);
860 /* section generation */
861 static void section_realloc(Section
*sec
, unsigned long new_size
);
862 static void *section_ptr_add(Section
*sec
, unsigned long size
);
863 static void put_extern_sym(Sym
*sym
, Section
*section
,
864 unsigned long value
, unsigned long size
);
865 static void greloc(Section
*s
, Sym
*sym
, unsigned long addr
, int type
);
866 static int put_elf_str(Section
*s
, const char *sym
);
867 static int put_elf_sym(Section
*s
,
868 unsigned long value
, unsigned long size
,
869 int info
, int other
, int shndx
, const char *name
);
870 static int add_elf_sym(Section
*s
, unsigned long value
, unsigned long size
,
871 int info
, int other
, int sh_num
, const char *name
);
872 static void put_elf_reloc(Section
*symtab
, Section
*s
, unsigned long offset
,
873 int type
, int symbol
);
874 static void put_stabs(const char *str
, int type
, int other
, int desc
,
875 unsigned long value
);
876 static void put_stabs_r(const char *str
, int type
, int other
, int desc
,
877 unsigned long value
, Section
*sec
, int sym_index
);
878 static void put_stabn(int type
, int other
, int desc
, int value
);
879 static void put_stabd(int type
, int other
, int desc
);
880 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
);
882 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
883 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
884 #define AFF_PREPROCESS 0x0004 /* preprocess file */
885 static int tcc_add_file_internal(TCCState
*s
, const char *filename
, int flags
);
888 int tcc_output_coff(TCCState
*s1
, FILE *f
);
891 void *resolve_sym(TCCState
*s1
, const char *sym
, int type
);
892 int pe_load_def_file(struct TCCState
*s1
, int fd
);
893 int pe_test_res_file(void *v
, int size
);
894 int pe_load_res_file(struct TCCState
*s1
, int fd
);
895 void pe_add_runtime(struct TCCState
*s1
);
896 void pe_guess_outfile(char *objfilename
, int output_type
);
897 int pe_output_file(struct TCCState
*s1
, const char *filename
);
901 #ifdef CONFIG_TCC_ASM
903 typedef struct ExprValue
{
908 #define MAX_ASM_OPERANDS 30
910 typedef struct ASMOperand
{
911 int id
; /* GCC 3 optionnal identifier (0 if number only supported */
913 char asm_str
[16]; /* computed asm string for operand */
914 SValue
*vt
; /* C value of the expression */
915 int ref_index
; /* if >= 0, gives reference to a output constraint */
916 int input_index
; /* if >= 0, gives reference to an input constraint */
917 int priority
; /* priority, used to assign registers */
918 int reg
; /* if >= 0, register number used for this operand */
919 int is_llong
; /* true if double register value */
920 int is_memory
; /* true if memory operand */
921 int is_rw
; /* for '+' modifier */
924 static void asm_expr(TCCState
*s1
, ExprValue
*pe
);
925 static int asm_int_expr(TCCState
*s1
);
926 static int find_constraint(ASMOperand
*operands
, int nb_operands
,
927 const char *name
, const char **pp
);
929 static int tcc_assemble(TCCState
*s1
, int do_preprocess
);
933 static void asm_instr(void);
934 static void asm_global_instr(void);
936 /* true if float/double/long double type */
937 static inline int is_float(int t
)
941 return bt
== VT_LDOUBLE
|| bt
== VT_DOUBLE
|| bt
== VT_FLOAT
;
944 #ifdef TCC_TARGET_I386
945 #include "i386-gen.c"
948 #ifdef TCC_TARGET_ARM
952 #ifdef TCC_TARGET_C67
956 #ifdef TCC_TARGET_X86_64
957 #include "x86_64-gen.c"
960 #ifdef CONFIG_TCC_STATIC
962 #define RTLD_LAZY 0x001
963 #define RTLD_NOW 0x002
964 #define RTLD_GLOBAL 0x100
965 #define RTLD_DEFAULT NULL
967 /* dummy function for profiling */
968 void *dlopen(const char *filename
, int flag
)
973 const char *dlerror(void)
978 typedef struct TCCSyms
{
983 #define TCCSYM(a) { #a, &a, },
985 /* add the symbol you want here if no dynamic linking is done */
986 static TCCSyms tcc_syms
[] = {
987 #if !defined(CONFIG_TCCBOOT)
996 void *resolve_sym(TCCState
*s1
, const char *symbol
, int type
)
1000 while (p
->str
!= NULL
) {
1001 if (!strcmp(p
->str
, symbol
))
1008 #elif !defined(_WIN32)
1012 void *resolve_sym(TCCState
*s1
, const char *sym
, int type
)
1014 return dlsym(RTLD_DEFAULT
, sym
);
1019 /********************************************************/
1021 /* we use our own 'finite' function to avoid potential problems with
1022 non standard math libs */
1023 /* XXX: endianness dependent */
1024 int ieee_finite(double d
)
1027 return ((unsigned)((p
[1] | 0x800fffff) + 1)) >> 31;
1030 /* copy a string and truncate it. */
1031 static char *pstrcpy(char *buf
, int buf_size
, const char *s
)
1038 q_end
= buf
+ buf_size
- 1;
1050 /* strcat and truncate. */
1051 static char *pstrcat(char *buf
, int buf_size
, const char *s
)
1056 pstrcpy(buf
+ len
, buf_size
- len
, s
);
1061 static int strstart(const char *str
, const char *val
, const char **ptr
)
1066 while (*q
!= '\0') {
1079 #define IS_PATHSEP(c) (c == '/' || c == '\\')
1080 #define IS_ABSPATH(p) (IS_PATHSEP(p[0]) || (p[0] && p[1] == ':' && IS_PATHSEP(p[2])))
1081 #define PATHCMP stricmp
1083 #define IS_PATHSEP(c) (c == '/')
1084 #define IS_ABSPATH(p) IS_PATHSEP(p[0])
1085 #define PATHCMP strcmp
1088 /* extract the basename of a file */
1089 static char *tcc_basename(const char *name
)
1091 char *p
= strchr(name
, 0);
1092 while (p
> name
&& !IS_PATHSEP(p
[-1]))
1097 static char *tcc_fileextension (const char *name
)
1099 char *b
= tcc_basename(name
);
1100 char *e
= strrchr(b
, '.');
1101 return e
? e
: strchr(b
, 0);
1105 char *normalize_slashes(char *path
)
1108 for (p
= path
; *p
; ++p
)
1114 char *w32_tcc_lib_path(void)
1116 /* on win32, we suppose the lib and includes are at the location
1118 char path
[1024], *p
;
1119 GetModuleFileNameA(NULL
, path
, sizeof path
);
1120 p
= tcc_basename(normalize_slashes(strlwr(path
)));
1121 if (p
- 5 > path
&& 0 == strncmp(p
- 5, "/bin/", 5))
1126 return strdup(path
);
1130 void set_pages_executable(void *ptr
, unsigned long length
)
1133 unsigned long old_protect
;
1134 VirtualProtect(ptr
, length
, PAGE_EXECUTE_READWRITE
, &old_protect
);
1136 unsigned long start
, end
;
1137 start
= (unsigned long)ptr
& ~(PAGESIZE
- 1);
1138 end
= (unsigned long)ptr
+ length
;
1139 end
= (end
+ PAGESIZE
- 1) & ~(PAGESIZE
- 1);
1140 mprotect((void *)start
, end
- start
, PROT_READ
| PROT_WRITE
| PROT_EXEC
);
1144 /* memory management */
1148 unsigned malloc_usable_size(void*);
1151 static inline void tcc_free(void *ptr
)
1154 mem_cur_size
-= malloc_usable_size(ptr
);
1159 static void *tcc_malloc(unsigned long size
)
1164 error("memory full");
1166 mem_cur_size
+= malloc_usable_size(ptr
);
1167 if (mem_cur_size
> mem_max_size
)
1168 mem_max_size
= mem_cur_size
;
1173 static void *tcc_mallocz(unsigned long size
)
1176 ptr
= tcc_malloc(size
);
1177 memset(ptr
, 0, size
);
1181 static inline void *tcc_realloc(void *ptr
, unsigned long size
)
1185 mem_cur_size
-= malloc_usable_size(ptr
);
1187 ptr1
= realloc(ptr
, size
);
1189 /* NOTE: count not correct if alloc error, but not critical */
1190 mem_cur_size
+= malloc_usable_size(ptr1
);
1191 if (mem_cur_size
> mem_max_size
)
1192 mem_max_size
= mem_cur_size
;
1197 static char *tcc_strdup(const char *str
)
1200 ptr
= tcc_malloc(strlen(str
) + 1);
1205 #define free(p) use_tcc_free(p)
1206 #define malloc(s) use_tcc_malloc(s)
1207 #define realloc(p, s) use_tcc_realloc(p, s)
1209 static void dynarray_add(void ***ptab
, int *nb_ptr
, void *data
)
1216 /* every power of two we double array size */
1217 if ((nb
& (nb
- 1)) == 0) {
1222 pp
= tcc_realloc(pp
, nb_alloc
* sizeof(void *));
1224 error("memory full");
1231 static void dynarray_reset(void *pp
, int *n
)
1234 for (p
= *(void***)pp
; *n
; ++p
, --*n
)
1237 tcc_free(*(void**)pp
);
1241 /* symbol allocator */
1242 static Sym
*__sym_malloc(void)
1244 Sym
*sym_pool
, *sym
, *last_sym
;
1247 sym_pool
= tcc_malloc(SYM_POOL_NB
* sizeof(Sym
));
1248 dynarray_add(&sym_pools
, &nb_sym_pools
, sym_pool
);
1250 last_sym
= sym_free_first
;
1252 for(i
= 0; i
< SYM_POOL_NB
; i
++) {
1253 sym
->next
= last_sym
;
1257 sym_free_first
= last_sym
;
1261 static inline Sym
*sym_malloc(void)
1264 sym
= sym_free_first
;
1266 sym
= __sym_malloc();
1267 sym_free_first
= sym
->next
;
1271 static inline void sym_free(Sym
*sym
)
1273 sym
->next
= sym_free_first
;
1274 sym_free_first
= sym
;
1277 Section
*new_section(TCCState
*s1
, const char *name
, int sh_type
, int sh_flags
)
1281 sec
= tcc_mallocz(sizeof(Section
) + strlen(name
));
1282 strcpy(sec
->name
, name
);
1283 sec
->sh_type
= sh_type
;
1284 sec
->sh_flags
= sh_flags
;
1292 sec
->sh_addralign
= 4;
1295 sec
->sh_addralign
= 1;
1298 sec
->sh_addralign
= 32; /* default conservative alignment */
1302 if (sh_flags
& SHF_PRIVATE
) {
1303 dynarray_add((void ***)&s1
->priv_sections
, &s1
->nb_priv_sections
, sec
);
1305 sec
->sh_num
= s1
->nb_sections
;
1306 dynarray_add((void ***)&s1
->sections
, &s1
->nb_sections
, sec
);
1312 static void free_section(Section
*s
)
1314 #ifdef TCC_TARGET_X86_64
1315 /* after tcc_relocate(), some sections share the data buffer.
1316 let's check if the data is allocated not to free the shared buffers */
1317 if (s
->data_allocated
)
1322 /* realloc section and set its content to zero */
1323 static void section_realloc(Section
*sec
, unsigned long new_size
)
1326 unsigned char *data
;
1328 size
= sec
->data_allocated
;
1331 while (size
< new_size
)
1333 data
= tcc_realloc(sec
->data
, size
);
1335 error("memory full");
1336 memset(data
+ sec
->data_allocated
, 0, size
- sec
->data_allocated
);
1338 sec
->data_allocated
= size
;
1341 /* reserve at least 'size' bytes in section 'sec' from
1342 sec->data_offset. */
1343 static void *section_ptr_add(Section
*sec
, unsigned long size
)
1345 unsigned long offset
, offset1
;
1347 offset
= sec
->data_offset
;
1348 offset1
= offset
+ size
;
1349 if (offset1
> sec
->data_allocated
)
1350 section_realloc(sec
, offset1
);
1351 sec
->data_offset
= offset1
;
1352 return sec
->data
+ offset
;
1355 /* return a reference to a section, and create it if it does not
1357 Section
*find_section(TCCState
*s1
, const char *name
)
1361 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1362 sec
= s1
->sections
[i
];
1363 if (!strcmp(name
, sec
->name
))
1366 /* sections are created as PROGBITS */
1367 return new_section(s1
, name
, SHT_PROGBITS
, SHF_ALLOC
);
1370 #define SECTION_ABS ((void *)1)
1372 /* update sym->c so that it points to an external symbol in section
1373 'section' with value 'value' */
1374 static void put_extern_sym2(Sym
*sym
, Section
*section
,
1375 unsigned long value
, unsigned long size
,
1376 int can_add_underscore
)
1378 int sym_type
, sym_bind
, sh_num
, info
, other
, attr
;
1383 if (section
== NULL
)
1385 else if (section
== SECTION_ABS
)
1388 sh_num
= section
->sh_num
;
1392 if ((sym
->type
.t
& VT_BTYPE
) == VT_FUNC
) {
1393 sym_type
= STT_FUNC
;
1394 #ifdef TCC_TARGET_PE
1396 attr
= sym
->type
.ref
->r
;
1397 if (FUNC_EXPORT(attr
))
1399 if (FUNC_CALL(attr
) == FUNC_STDCALL
)
1403 sym_type
= STT_OBJECT
;
1406 if (sym
->type
.t
& VT_STATIC
)
1407 sym_bind
= STB_LOCAL
;
1409 sym_bind
= STB_GLOBAL
;
1412 name
= get_tok_str(sym
->v
, NULL
);
1413 #ifdef CONFIG_TCC_BCHECK
1414 if (do_bounds_check
) {
1417 /* XXX: avoid doing that for statics ? */
1418 /* if bound checking is activated, we change some function
1419 names by adding the "__bound" prefix */
1422 /* XXX: we rely only on malloc hooks */
1435 strcpy(buf
, "__bound_");
1443 #ifdef TCC_TARGET_PE
1444 if ((other
& 2) && can_add_underscore
) {
1445 sprintf(buf1
, "_%s@%d", name
, FUNC_ARGS(attr
));
1449 if (tcc_state
->leading_underscore
&& can_add_underscore
) {
1451 pstrcpy(buf1
+ 1, sizeof(buf1
) - 1, name
);
1454 info
= ELFW(ST_INFO
)(sym_bind
, sym_type
);
1455 sym
->c
= add_elf_sym(symtab_section
, value
, size
, info
, other
, sh_num
, name
);
1457 esym
= &((ElfW(Sym
) *)symtab_section
->data
)[sym
->c
];
1458 esym
->st_value
= value
;
1459 esym
->st_size
= size
;
1460 esym
->st_shndx
= sh_num
;
1461 esym
->st_other
|= other
;
1465 static void put_extern_sym(Sym
*sym
, Section
*section
,
1466 unsigned long value
, unsigned long size
)
1468 put_extern_sym2(sym
, section
, value
, size
, 1);
1471 /* add a new relocation entry to symbol 'sym' in section 's' */
1472 static void greloc(Section
*s
, Sym
*sym
, unsigned long offset
, int type
)
1475 put_extern_sym(sym
, NULL
, 0, 0);
1476 /* now we can add ELF relocation info */
1477 put_elf_reloc(symtab_section
, s
, offset
, type
, sym
->c
);
1480 static inline int isid(int c
)
1482 return (c
>= 'a' && c
<= 'z') ||
1483 (c
>= 'A' && c
<= 'Z') ||
1487 static inline int isnum(int c
)
1489 return c
>= '0' && c
<= '9';
1492 static inline int isoct(int c
)
1494 return c
>= '0' && c
<= '7';
1497 static inline int toup(int c
)
1499 if (c
>= 'a' && c
<= 'z')
1500 return c
- 'a' + 'A';
1505 static void strcat_vprintf(char *buf
, int buf_size
, const char *fmt
, va_list ap
)
1509 vsnprintf(buf
+ len
, buf_size
- len
, fmt
, ap
);
1512 static void strcat_printf(char *buf
, int buf_size
, const char *fmt
, ...)
1516 strcat_vprintf(buf
, buf_size
, fmt
, ap
);
1520 void error1(TCCState
*s1
, int is_warning
, const char *fmt
, va_list ap
)
1527 for(f
= s1
->include_stack
; f
< s1
->include_stack_ptr
; f
++)
1528 strcat_printf(buf
, sizeof(buf
), "In file included from %s:%d:\n",
1529 (*f
)->filename
, (*f
)->line_num
);
1530 if (file
->line_num
> 0) {
1531 strcat_printf(buf
, sizeof(buf
),
1532 "%s:%d: ", file
->filename
, file
->line_num
);
1534 strcat_printf(buf
, sizeof(buf
),
1535 "%s: ", file
->filename
);
1538 strcat_printf(buf
, sizeof(buf
),
1542 strcat_printf(buf
, sizeof(buf
), "warning: ");
1543 strcat_vprintf(buf
, sizeof(buf
), fmt
, ap
);
1545 if (!s1
->error_func
) {
1546 /* default case: stderr */
1547 fprintf(stderr
, "%s\n", buf
);
1549 s1
->error_func(s1
->error_opaque
, buf
);
1551 if (!is_warning
|| s1
->warn_error
)
1556 void tcc_set_error_func(TCCState
*s
, void *error_opaque
,
1557 void (*error_func
)(void *opaque
, const char *msg
))
1559 s
->error_opaque
= error_opaque
;
1560 s
->error_func
= error_func
;
1564 /* error without aborting current compilation */
1565 void error_noabort(const char *fmt
, ...)
1567 TCCState
*s1
= tcc_state
;
1571 error1(s1
, 0, fmt
, ap
);
1575 void error(const char *fmt
, ...)
1577 TCCState
*s1
= tcc_state
;
1581 error1(s1
, 0, fmt
, ap
);
1583 /* better than nothing: in some cases, we accept to handle errors */
1584 if (s1
->error_set_jmp_enabled
) {
1585 longjmp(s1
->error_jmp_buf
, 1);
1587 /* XXX: eliminate this someday */
1592 void expect(const char *msg
)
1594 error("%s expected", msg
);
1597 void warning(const char *fmt
, ...)
1599 TCCState
*s1
= tcc_state
;
1606 error1(s1
, 1, fmt
, ap
);
1613 error("'%c' expected", c
);
1617 static void test_lvalue(void)
1619 if (!(vtop
->r
& VT_LVAL
))
1623 /* allocate a new token */
1624 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
1626 TokenSym
*ts
, **ptable
;
1629 if (tok_ident
>= SYM_FIRST_ANOM
)
1630 error("memory full");
1632 /* expand token table if needed */
1633 i
= tok_ident
- TOK_IDENT
;
1634 if ((i
% TOK_ALLOC_INCR
) == 0) {
1635 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
1637 error("memory full");
1638 table_ident
= ptable
;
1641 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
1642 table_ident
[i
] = ts
;
1643 ts
->tok
= tok_ident
++;
1644 ts
->sym_define
= NULL
;
1645 ts
->sym_label
= NULL
;
1646 ts
->sym_struct
= NULL
;
1647 ts
->sym_identifier
= NULL
;
1649 ts
->hash_next
= NULL
;
1650 memcpy(ts
->str
, str
, len
);
1651 ts
->str
[len
] = '\0';
1656 #define TOK_HASH_INIT 1
1657 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
1659 /* find a token and add it if not found */
1660 static TokenSym
*tok_alloc(const char *str
, int len
)
1662 TokenSym
*ts
, **pts
;
1668 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
1669 h
&= (TOK_HASH_SIZE
- 1);
1671 pts
= &hash_ident
[h
];
1676 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
1678 pts
= &(ts
->hash_next
);
1680 return tok_alloc_new(pts
, str
, len
);
1683 /* CString handling */
1685 static void cstr_realloc(CString
*cstr
, int new_size
)
1690 size
= cstr
->size_allocated
;
1692 size
= 8; /* no need to allocate a too small first string */
1693 while (size
< new_size
)
1695 data
= tcc_realloc(cstr
->data_allocated
, size
);
1697 error("memory full");
1698 cstr
->data_allocated
= data
;
1699 cstr
->size_allocated
= size
;
1704 static inline void cstr_ccat(CString
*cstr
, int ch
)
1707 size
= cstr
->size
+ 1;
1708 if (size
> cstr
->size_allocated
)
1709 cstr_realloc(cstr
, size
);
1710 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
1714 static void cstr_cat(CString
*cstr
, const char *str
)
1726 /* add a wide char */
1727 static void cstr_wccat(CString
*cstr
, int ch
)
1730 size
= cstr
->size
+ sizeof(nwchar_t
);
1731 if (size
> cstr
->size_allocated
)
1732 cstr_realloc(cstr
, size
);
1733 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
1737 static void cstr_new(CString
*cstr
)
1739 memset(cstr
, 0, sizeof(CString
));
1742 /* free string and reset it to NULL */
1743 static void cstr_free(CString
*cstr
)
1745 tcc_free(cstr
->data_allocated
);
1749 #define cstr_reset(cstr) cstr_free(cstr)
1751 /* XXX: unicode ? */
1752 static void add_char(CString
*cstr
, int c
)
1754 if (c
== '\'' || c
== '\"' || c
== '\\') {
1755 /* XXX: could be more precise if char or string */
1756 cstr_ccat(cstr
, '\\');
1758 if (c
>= 32 && c
<= 126) {
1761 cstr_ccat(cstr
, '\\');
1763 cstr_ccat(cstr
, 'n');
1765 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
1766 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
1767 cstr_ccat(cstr
, '0' + (c
& 7));
1772 /* XXX: buffer overflow */
1773 /* XXX: float tokens */
1774 char *get_tok_str(int v
, CValue
*cv
)
1776 static char buf
[STRING_MAX_SIZE
+ 1];
1777 static CString cstr_buf
;
1783 /* NOTE: to go faster, we give a fixed buffer for small strings */
1784 cstr_reset(&cstr_buf
);
1785 cstr_buf
.data
= buf
;
1786 cstr_buf
.size_allocated
= sizeof(buf
);
1792 /* XXX: not quite exact, but only useful for testing */
1793 sprintf(p
, "%u", cv
->ui
);
1797 /* XXX: not quite exact, but only useful for testing */
1798 sprintf(p
, "%Lu", cv
->ull
);
1801 cstr_ccat(&cstr_buf
, 'L');
1803 cstr_ccat(&cstr_buf
, '\'');
1804 add_char(&cstr_buf
, cv
->i
);
1805 cstr_ccat(&cstr_buf
, '\'');
1806 cstr_ccat(&cstr_buf
, '\0');
1810 len
= cstr
->size
- 1;
1812 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1813 cstr_ccat(&cstr_buf
, '\0');
1816 cstr_ccat(&cstr_buf
, 'L');
1819 cstr_ccat(&cstr_buf
, '\"');
1821 len
= cstr
->size
- 1;
1823 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1825 len
= (cstr
->size
/ sizeof(nwchar_t
)) - 1;
1827 add_char(&cstr_buf
, ((nwchar_t
*)cstr
->data
)[i
]);
1829 cstr_ccat(&cstr_buf
, '\"');
1830 cstr_ccat(&cstr_buf
, '\0');
1839 return strcpy(p
, "...");
1841 return strcpy(p
, "<<=");
1843 return strcpy(p
, ">>=");
1845 if (v
< TOK_IDENT
) {
1846 /* search in two bytes table */
1860 } else if (v
< tok_ident
) {
1861 return table_ident
[v
- TOK_IDENT
]->str
;
1862 } else if (v
>= SYM_FIRST_ANOM
) {
1863 /* special name for anonymous symbol */
1864 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
1866 /* should never happen */
1871 return cstr_buf
.data
;
1874 /* push, without hashing */
1875 static Sym
*sym_push2(Sym
**ps
, int v
, int t
, long c
)
1889 /* find a symbol and return its associated structure. 's' is the top
1890 of the symbol stack */
1891 static Sym
*sym_find2(Sym
*s
, int v
)
1901 /* structure lookup */
1902 static inline Sym
*struct_find(int v
)
1905 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1907 return table_ident
[v
]->sym_struct
;
1910 /* find an identifier */
1911 static inline Sym
*sym_find(int v
)
1914 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1916 return table_ident
[v
]->sym_identifier
;
1919 /* push a given symbol on the symbol stack */
1920 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
)
1929 s
= sym_push2(ps
, v
, type
->t
, c
);
1930 s
->type
.ref
= type
->ref
;
1932 /* don't record fields or anonymous symbols */
1934 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1935 /* record symbol in token array */
1936 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1938 ps
= &ts
->sym_struct
;
1940 ps
= &ts
->sym_identifier
;
1947 /* push a global identifier */
1948 static Sym
*global_identifier_push(int v
, int t
, int c
)
1951 s
= sym_push2(&global_stack
, v
, t
, c
);
1952 /* don't record anonymous symbol */
1953 if (v
< SYM_FIRST_ANOM
) {
1954 ps
= &table_ident
[v
- TOK_IDENT
]->sym_identifier
;
1955 /* modify the top most local identifier, so that
1956 sym_identifier will point to 's' when popped */
1958 ps
= &(*ps
)->prev_tok
;
1965 /* pop symbols until top reaches 'b' */
1966 static void sym_pop(Sym
**ptop
, Sym
*b
)
1976 /* remove symbol in token array */
1978 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1979 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1981 ps
= &ts
->sym_struct
;
1983 ps
= &ts
->sym_identifier
;
1994 BufferedFile
*tcc_open(TCCState
*s1
, const char *filename
)
1999 if (strcmp(filename
, "-") == 0)
2000 fd
= 0, filename
= "stdin";
2002 fd
= open(filename
, O_RDONLY
| O_BINARY
);
2003 if ((verbose
== 2 && fd
>= 0) || verbose
== 3)
2004 printf("%s %*s%s\n", fd
< 0 ? "nf":"->",
2005 (s1
->include_stack_ptr
- s1
->include_stack
), "", filename
);
2008 bf
= tcc_malloc(sizeof(BufferedFile
));
2010 bf
->buf_ptr
= bf
->buffer
;
2011 bf
->buf_end
= bf
->buffer
;
2012 bf
->buffer
[0] = CH_EOB
; /* put eob symbol */
2013 pstrcpy(bf
->filename
, sizeof(bf
->filename
), filename
);
2015 normalize_slashes(bf
->filename
);
2018 bf
->ifndef_macro
= 0;
2019 bf
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
2020 // printf("opening '%s'\n", filename);
2024 void tcc_close(BufferedFile
*bf
)
2026 total_lines
+= bf
->line_num
;
2031 /* fill input buffer and peek next char */
2032 static int tcc_peekc_slow(BufferedFile
*bf
)
2035 /* only tries to read if really end of buffer */
2036 if (bf
->buf_ptr
>= bf
->buf_end
) {
2038 #if defined(PARSE_DEBUG)
2043 len
= read(bf
->fd
, bf
->buffer
, len
);
2050 bf
->buf_ptr
= bf
->buffer
;
2051 bf
->buf_end
= bf
->buffer
+ len
;
2052 *bf
->buf_end
= CH_EOB
;
2054 if (bf
->buf_ptr
< bf
->buf_end
) {
2055 return bf
->buf_ptr
[0];
2057 bf
->buf_ptr
= bf
->buf_end
;
2062 /* return the current character, handling end of block if necessary
2064 static int handle_eob(void)
2066 return tcc_peekc_slow(file
);
2069 /* read next char from current input file and handle end of input buffer */
2070 static inline void inp(void)
2072 ch
= *(++(file
->buf_ptr
));
2073 /* end of buffer/file handling */
2078 /* handle '\[\r]\n' */
2079 static int handle_stray_noerror(void)
2081 while (ch
== '\\') {
2086 } else if (ch
== '\r') {
2100 static void handle_stray(void)
2102 if (handle_stray_noerror())
2103 error("stray '\\' in program");
2106 /* skip the stray and handle the \\n case. Output an error if
2107 incorrect char after the stray */
2108 static int handle_stray1(uint8_t *p
)
2112 if (p
>= file
->buf_end
) {
2129 /* handle just the EOB case, but not stray */
2130 #define PEEKC_EOB(c, p)\
2141 /* handle the complicated stray case */
2142 #define PEEKC(c, p)\
2147 c = handle_stray1(p);\
2152 /* input with '\[\r]\n' handling. Note that this function cannot
2153 handle other characters after '\', so you cannot call it inside
2154 strings or comments */
2155 static void minp(void)
2163 /* single line C++ comments */
2164 static uint8_t *parse_line_comment(uint8_t *p
)
2172 if (c
== '\n' || c
== CH_EOF
) {
2174 } else if (c
== '\\') {
2183 } else if (c
== '\r') {
2201 static uint8_t *parse_comment(uint8_t *p
)
2207 /* fast skip loop */
2210 if (c
== '\n' || c
== '*' || c
== '\\')
2214 if (c
== '\n' || c
== '*' || c
== '\\')
2218 /* now we can handle all the cases */
2222 } else if (c
== '*') {
2228 } else if (c
== '/') {
2229 goto end_of_comment
;
2230 } else if (c
== '\\') {
2235 /* skip '\[\r]\n', otherwise just skip the stray */
2241 } else if (c
== '\r') {
2258 /* stray, eob or eof */
2263 error("unexpected end of file in comment");
2264 } else if (c
== '\\') {
2276 /* space exlcuding newline */
2277 static inline int is_space(int ch
)
2279 return ch
== ' ' || ch
== '\t' || ch
== '\v' || ch
== '\f' || ch
== '\r';
2282 static inline void skip_spaces(void)
2284 while (is_space(ch
))
2288 /* parse a string without interpreting escapes */
2289 static uint8_t *parse_pp_string(uint8_t *p
,
2290 int sep
, CString
*str
)
2298 } else if (c
== '\\') {
2303 unterminated_string
:
2304 /* XXX: indicate line number of start of string */
2305 error("missing terminating %c character", sep
);
2306 } else if (c
== '\\') {
2307 /* escape : just skip \[\r]\n */
2312 } else if (c
== '\r') {
2315 expect("'\n' after '\r'");
2318 } else if (c
== CH_EOF
) {
2319 goto unterminated_string
;
2322 cstr_ccat(str
, '\\');
2328 } else if (c
== '\n') {
2331 } else if (c
== '\r') {
2335 cstr_ccat(str
, '\r');
2351 /* skip block of text until #else, #elif or #endif. skip also pairs of
2353 void preprocess_skip(void)
2355 int a
, start_of_line
, c
, in_warn_or_error
;
2362 in_warn_or_error
= 0;
2383 } else if (c
== '\\') {
2384 ch
= file
->buf_ptr
[0];
2385 handle_stray_noerror();
2392 if (in_warn_or_error
)
2394 p
= parse_pp_string(p
, c
, NULL
);
2398 if (in_warn_or_error
)
2405 p
= parse_comment(p
);
2406 } else if (ch
== '/') {
2407 p
= parse_line_comment(p
);
2412 if (start_of_line
) {
2417 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
2419 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
2421 else if (tok
== TOK_ENDIF
)
2423 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
2424 in_warn_or_error
= 1;
2438 /* ParseState handling */
2440 /* XXX: currently, no include file info is stored. Thus, we cannot display
2441 accurate messages if the function or data definition spans multiple
2444 /* save current parse state in 's' */
2445 void save_parse_state(ParseState
*s
)
2447 s
->line_num
= file
->line_num
;
2448 s
->macro_ptr
= macro_ptr
;
2453 /* restore parse state from 's' */
2454 void restore_parse_state(ParseState
*s
)
2456 file
->line_num
= s
->line_num
;
2457 macro_ptr
= s
->macro_ptr
;
2462 /* return the number of additional 'ints' necessary to store the
2464 static inline int tok_ext_size(int t
)
2478 error("unsupported token");
2485 return LDOUBLE_SIZE
/ 4;
2491 /* token string handling */
2493 static inline void tok_str_new(TokenString
*s
)
2497 s
->allocated_len
= 0;
2498 s
->last_line_num
= -1;
2501 static void tok_str_free(int *str
)
2506 static int *tok_str_realloc(TokenString
*s
)
2510 if (s
->allocated_len
== 0) {
2513 len
= s
->allocated_len
* 2;
2515 str
= tcc_realloc(s
->str
, len
* sizeof(int));
2517 error("memory full");
2518 s
->allocated_len
= len
;
2523 static void tok_str_add(TokenString
*s
, int t
)
2529 if (len
>= s
->allocated_len
)
2530 str
= tok_str_realloc(s
);
2535 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
2542 /* allocate space for worst case */
2543 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
2544 str
= tok_str_realloc(s
);
2553 str
[len
++] = cv
->tab
[0];
2562 nb_words
= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
2563 while ((len
+ nb_words
) > s
->allocated_len
)
2564 str
= tok_str_realloc(s
);
2565 cstr
= (CString
*)(str
+ len
);
2567 cstr
->size
= cv
->cstr
->size
;
2568 cstr
->data_allocated
= NULL
;
2569 cstr
->size_allocated
= cstr
->size
;
2570 memcpy((char *)cstr
+ sizeof(CString
),
2571 cv
->cstr
->data
, cstr
->size
);
2578 #if LDOUBLE_SIZE == 8
2581 str
[len
++] = cv
->tab
[0];
2582 str
[len
++] = cv
->tab
[1];
2584 #if LDOUBLE_SIZE == 12
2586 str
[len
++] = cv
->tab
[0];
2587 str
[len
++] = cv
->tab
[1];
2588 str
[len
++] = cv
->tab
[2];
2589 #elif LDOUBLE_SIZE == 16
2591 str
[len
++] = cv
->tab
[0];
2592 str
[len
++] = cv
->tab
[1];
2593 str
[len
++] = cv
->tab
[2];
2594 str
[len
++] = cv
->tab
[3];
2595 #elif LDOUBLE_SIZE != 8
2596 #error add long double size support
2605 /* add the current parse token in token string 's' */
2606 static void tok_str_add_tok(TokenString
*s
)
2610 /* save line number info */
2611 if (file
->line_num
!= s
->last_line_num
) {
2612 s
->last_line_num
= file
->line_num
;
2613 cval
.i
= s
->last_line_num
;
2614 tok_str_add2(s
, TOK_LINENUM
, &cval
);
2616 tok_str_add2(s
, tok
, &tokc
);
2619 #if LDOUBLE_SIZE == 16
2620 #define LDOUBLE_GET(p, cv) \
2625 #elif LDOUBLE_SIZE == 12
2626 #define LDOUBLE_GET(p, cv) \
2630 #elif LDOUBLE_SIZE == 8
2631 #define LDOUBLE_GET(p, cv) \
2635 #error add long double size support
2639 /* get a token from an integer array and increment pointer
2640 accordingly. we code it as a macro to avoid pointer aliasing. */
2641 #define TOK_GET(t, p, cv) \
2656 cv.cstr = (CString *)p; \
2657 cv.cstr->data = (char *)p + sizeof(CString);\
2658 p += (sizeof(CString) + cv.cstr->size + 3) >> 2;\
2667 case TOK_CLDOUBLE: \
2668 LDOUBLE_GET(p, cv); \
2669 p += LDOUBLE_SIZE / 4; \
2676 /* defines handling */
2677 static inline void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
2681 s
= sym_push2(&define_stack
, v
, macro_type
, (long)str
);
2682 s
->next
= first_arg
;
2683 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
2686 /* undefined a define symbol. Its name is just set to zero */
2687 static void define_undef(Sym
*s
)
2691 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2692 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2696 static inline Sym
*define_find(int v
)
2699 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2701 return table_ident
[v
]->sym_define
;
2704 /* free define stack until top reaches 'b' */
2705 static void free_defines(Sym
*b
)
2713 /* do not free args or predefined defines */
2715 tok_str_free((int *)top
->c
);
2717 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2718 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2726 static Sym
*label_find(int v
)
2729 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2731 return table_ident
[v
]->sym_label
;
2734 static Sym
*label_push(Sym
**ptop
, int v
, int flags
)
2737 s
= sym_push2(ptop
, v
, 0, 0);
2739 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
2740 if (ptop
== &global_label_stack
) {
2741 /* modify the top most local identifier, so that
2742 sym_identifier will point to 's' when popped */
2744 ps
= &(*ps
)->prev_tok
;
2751 /* pop labels until element last is reached. Look if any labels are
2752 undefined. Define symbols if '&&label' was used. */
2753 static void label_pop(Sym
**ptop
, Sym
*slast
)
2756 for(s
= *ptop
; s
!= slast
; s
= s1
) {
2758 if (s
->r
== LABEL_DECLARED
) {
2759 warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
2760 } else if (s
->r
== LABEL_FORWARD
) {
2761 error("label '%s' used but not defined",
2762 get_tok_str(s
->v
, NULL
));
2765 /* define corresponding symbol. A size of
2767 put_extern_sym(s
, cur_text_section
, (long)s
->next
, 1);
2771 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
2777 /* eval an expression for #if/#elif */
2778 static int expr_preprocess(void)
2784 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2785 next(); /* do macro subst */
2786 if (tok
== TOK_DEFINED
) {
2791 c
= define_find(tok
) != 0;
2796 } else if (tok
>= TOK_IDENT
) {
2797 /* if undefined macro */
2801 tok_str_add_tok(&str
);
2803 tok_str_add(&str
, -1); /* simulate end of file */
2804 tok_str_add(&str
, 0);
2805 /* now evaluate C constant expression */
2806 macro_ptr
= str
.str
;
2810 tok_str_free(str
.str
);
2814 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
2815 static void tok_print(int *str
)
2821 TOK_GET(t
, str
, cval
);
2824 printf(" %s", get_tok_str(t
, &cval
));
2830 /* parse after #define */
2831 static void parse_define(void)
2833 Sym
*s
, *first
, **ps
;
2834 int v
, t
, varg
, is_vaargs
, c
;
2839 error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
2840 /* XXX: should check if same macro (ANSI) */
2843 /* '(' must be just after macro definition for MACRO_FUNC */
2844 c
= file
->buf_ptr
[0];
2846 c
= handle_stray1(file
->buf_ptr
);
2851 while (tok
!= ')') {
2855 if (varg
== TOK_DOTS
) {
2856 varg
= TOK___VA_ARGS__
;
2858 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
2862 if (varg
< TOK_IDENT
)
2863 error("badly punctuated parameter list");
2864 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
2875 /* EOF testing necessary for '-D' handling */
2876 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2877 tok_str_add2(&str
, tok
, &tokc
);
2880 tok_str_add(&str
, 0);
2882 printf("define %s %d: ", get_tok_str(v
, NULL
), t
);
2885 define_push(v
, t
, str
.str
, first
);
2888 static inline int hash_cached_include(int type
, const char *filename
)
2890 const unsigned char *s
;
2894 h
= TOK_HASH_FUNC(h
, type
);
2897 h
= TOK_HASH_FUNC(h
, *s
);
2900 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
2904 /* XXX: use a token or a hash table to accelerate matching ? */
2905 static CachedInclude
*search_cached_include(TCCState
*s1
,
2906 int type
, const char *filename
)
2910 h
= hash_cached_include(type
, filename
);
2911 i
= s1
->cached_includes_hash
[h
];
2915 e
= s1
->cached_includes
[i
- 1];
2916 if (e
->type
== type
&& !PATHCMP(e
->filename
, filename
))
2923 static inline void add_cached_include(TCCState
*s1
, int type
,
2924 const char *filename
, int ifndef_macro
)
2929 if (search_cached_include(s1
, type
, filename
))
2932 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
2934 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
2938 strcpy(e
->filename
, filename
);
2939 e
->ifndef_macro
= ifndef_macro
;
2940 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
2941 /* add in hash table */
2942 h
= hash_cached_include(type
, filename
);
2943 e
->hash_next
= s1
->cached_includes_hash
[h
];
2944 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
2947 static void pragma_parse(TCCState
*s1
)
2952 if (tok
== TOK_pack
) {
2955 #pragma pack(1) // set
2956 #pragma pack() // reset to default
2957 #pragma pack(push,1) // push & set
2958 #pragma pack(pop) // restore previous
2962 if (tok
== TOK_ASM_pop
) {
2964 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
2966 error("out of pack stack");
2968 s1
->pack_stack_ptr
--;
2972 if (tok
== TOK_ASM_push
) {
2974 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
2976 s1
->pack_stack_ptr
++;
2979 if (tok
!= TOK_CINT
) {
2981 error("invalid pack pragma");
2984 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
2988 *s1
->pack_stack_ptr
= val
;
2994 /* is_bof is true if first non space token at beginning of file */
2995 static void preprocess(int is_bof
)
2997 TCCState
*s1
= tcc_state
;
2998 int size
, i
, c
, n
, saved_parse_flags
;
3005 saved_parse_flags
= parse_flags
;
3006 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
|
3007 PARSE_FLAG_LINEFEED
;
3017 s
= define_find(tok
);
3018 /* undefine symbol by putting an invalid name */
3023 case TOK_INCLUDE_NEXT
:
3024 ch
= file
->buf_ptr
[0];
3025 /* XXX: incorrect if comments : use next_nomacro with a special mode */
3030 } else if (ch
== '\"') {
3035 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
3036 if ((q
- buf
) < sizeof(buf
) - 1)
3039 if (handle_stray_noerror() == 0)
3047 /* eat all spaces and comments after include */
3048 /* XXX: slightly incorrect */
3049 while (ch1
!= '\n' && ch1
!= CH_EOF
)
3053 /* computed #include : either we have only strings or
3054 we have anything enclosed in '<>' */
3057 if (tok
== TOK_STR
) {
3058 while (tok
!= TOK_LINEFEED
) {
3059 if (tok
!= TOK_STR
) {
3061 error("'#include' expects \"FILENAME\" or <FILENAME>");
3063 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
3069 while (tok
!= TOK_LINEFEED
) {
3070 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
3074 /* check syntax and remove '<>' */
3075 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
3076 goto include_syntax
;
3077 memmove(buf
, buf
+ 1, len
- 2);
3078 buf
[len
- 2] = '\0';
3083 e
= search_cached_include(s1
, c
, buf
);
3084 if (e
&& define_find(e
->ifndef_macro
)) {
3085 /* no need to parse the include because the 'ifndef macro'
3088 printf("%s: skipping %s\n", file
->filename
, buf
);
3091 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
3092 error("#include recursion too deep");
3093 /* push current file in stack */
3094 /* XXX: fix current line init */
3095 *s1
->include_stack_ptr
++ = file
;
3097 /* check absolute include path */
3098 if (IS_ABSPATH(buf
)) {
3099 f
= tcc_open(s1
, buf
);
3104 /* first search in current dir if "header.h" */
3105 size
= tcc_basename(file
->filename
) - file
->filename
;
3106 if (size
> sizeof(buf1
) - 1)
3107 size
= sizeof(buf1
) - 1;
3108 memcpy(buf1
, file
->filename
, size
);
3110 pstrcat(buf1
, sizeof(buf1
), buf
);
3111 f
= tcc_open(s1
, buf1
);
3113 if (tok
== TOK_INCLUDE_NEXT
)
3119 /* now search in all the include paths */
3120 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
3121 for(i
= 0; i
< n
; i
++) {
3123 if (i
< s1
->nb_include_paths
)
3124 path
= s1
->include_paths
[i
];
3126 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
3127 pstrcpy(buf1
, sizeof(buf1
), path
);
3128 pstrcat(buf1
, sizeof(buf1
), "/");
3129 pstrcat(buf1
, sizeof(buf1
), buf
);
3130 f
= tcc_open(s1
, buf1
);
3132 if (tok
== TOK_INCLUDE_NEXT
)
3138 --s1
->include_stack_ptr
;
3139 error("include file '%s' not found", buf
);
3143 printf("%s: including %s\n", file
->filename
, buf1
);
3146 pstrcpy(f
->inc_filename
, sizeof(f
->inc_filename
), buf
);
3148 /* add include file debug info */
3150 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
3152 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
3153 ch
= file
->buf_ptr
[0];
3161 c
= expr_preprocess();
3167 if (tok
< TOK_IDENT
)
3168 error("invalid argument for '#if%sdef'", c
? "n" : "");
3172 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
3174 file
->ifndef_macro
= tok
;
3177 c
= (define_find(tok
) != 0) ^ c
;
3179 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
3180 error("memory full");
3181 *s1
->ifdef_stack_ptr
++ = c
;
3184 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
3185 error("#else without matching #if");
3186 if (s1
->ifdef_stack_ptr
[-1] & 2)
3187 error("#else after #else");
3188 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
3191 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
3192 error("#elif without matching #if");
3193 c
= s1
->ifdef_stack_ptr
[-1];
3195 error("#elif after #else");
3196 /* last #if/#elif expression was true: we skip */
3199 c
= expr_preprocess();
3200 s1
->ifdef_stack_ptr
[-1] = c
;
3210 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
3211 error("#endif without matching #if");
3212 s1
->ifdef_stack_ptr
--;
3213 /* '#ifndef macro' was at the start of file. Now we check if
3214 an '#endif' is exactly at the end of file */
3215 if (file
->ifndef_macro
&&
3216 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
3217 file
->ifndef_macro_saved
= file
->ifndef_macro
;
3218 /* need to set to zero to avoid false matches if another
3219 #ifndef at middle of file */
3220 file
->ifndef_macro
= 0;
3221 while (tok
!= TOK_LINEFEED
)
3223 tok_flags
|= TOK_FLAG_ENDIF
;
3229 if (tok
!= TOK_CINT
)
3231 file
->line_num
= tokc
.i
- 1; /* the line number will be incremented after */
3233 if (tok
!= TOK_LINEFEED
) {
3236 pstrcpy(file
->filename
, sizeof(file
->filename
),
3237 (char *)tokc
.cstr
->data
);
3243 ch
= file
->buf_ptr
[0];
3246 while (ch
!= '\n' && ch
!= CH_EOF
) {
3247 if ((q
- buf
) < sizeof(buf
) - 1)
3250 if (handle_stray_noerror() == 0)
3257 error("#error %s", buf
);
3259 warning("#warning %s", buf
);
3265 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_CINT
) {
3266 /* '!' is ignored to allow C scripts. numbers are ignored
3267 to emulate cpp behaviour */
3269 if (!(saved_parse_flags
& PARSE_FLAG_ASM_COMMENTS
))
3270 warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
3274 /* ignore other preprocess commands or #! for C scripts */
3275 while (tok
!= TOK_LINEFEED
)
3278 parse_flags
= saved_parse_flags
;
3281 /* evaluate escape codes in a string. */
3282 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
3297 case '0': case '1': case '2': case '3':
3298 case '4': case '5': case '6': case '7':
3299 /* at most three octal digits */
3304 n
= n
* 8 + c
- '0';
3308 n
= n
* 8 + c
- '0';
3313 goto add_char_nonext
;
3321 if (c
>= 'a' && c
<= 'f')
3323 else if (c
>= 'A' && c
<= 'F')
3333 goto add_char_nonext
;
3357 goto invalid_escape
;
3367 if (c
>= '!' && c
<= '~')
3368 warning("unknown escape sequence: \'\\%c\'", c
);
3370 warning("unknown escape sequence: \'\\x%x\'", c
);
3377 cstr_ccat(outstr
, c
);
3379 cstr_wccat(outstr
, c
);
3381 /* add a trailing '\0' */
3383 cstr_ccat(outstr
, '\0');
3385 cstr_wccat(outstr
, '\0');
3388 /* we use 64 bit numbers */
3391 /* bn = (bn << shift) | or_val */
3392 void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
3396 for(i
=0;i
<BN_SIZE
;i
++) {
3398 bn
[i
] = (v
<< shift
) | or_val
;
3399 or_val
= v
>> (32 - shift
);
3403 void bn_zero(unsigned int *bn
)
3406 for(i
=0;i
<BN_SIZE
;i
++) {
3411 /* parse number in null terminated string 'p' and return it in the
3413 void parse_number(const char *p
)
3415 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
3417 unsigned int bn
[BN_SIZE
];
3428 goto float_frac_parse
;
3429 } else if (t
== '0') {
3430 if (ch
== 'x' || ch
== 'X') {
3434 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
3440 /* parse all digits. cannot check octal numbers at this stage
3441 because of floating point constants */
3443 if (ch
>= 'a' && ch
<= 'f')
3445 else if (ch
>= 'A' && ch
<= 'F')
3453 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
3455 error("number too long");
3461 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
3462 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
3464 /* NOTE: strtox should support that for hexa numbers, but
3465 non ISOC99 libcs do not support it, so we prefer to do
3467 /* hexadecimal or binary floats */
3468 /* XXX: handle overflows */
3480 } else if (t
>= 'a') {
3482 } else if (t
>= 'A') {
3487 bn_lshift(bn
, shift
, t
);
3494 if (t
>= 'a' && t
<= 'f') {
3496 } else if (t
>= 'A' && t
<= 'F') {
3498 } else if (t
>= '0' && t
<= '9') {
3504 error("invalid digit");
3505 bn_lshift(bn
, shift
, t
);
3510 if (ch
!= 'p' && ch
!= 'P')
3517 } else if (ch
== '-') {
3521 if (ch
< '0' || ch
> '9')
3522 expect("exponent digits");
3523 while (ch
>= '0' && ch
<= '9') {
3524 exp_val
= exp_val
* 10 + ch
- '0';
3527 exp_val
= exp_val
* s
;
3529 /* now we can generate the number */
3530 /* XXX: should patch directly float number */
3531 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
3532 d
= ldexp(d
, exp_val
- frac_bits
);
3537 /* float : should handle overflow */
3539 } else if (t
== 'L') {
3542 /* XXX: not large enough */
3543 tokc
.ld
= (long double)d
;
3549 /* decimal floats */
3551 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3556 while (ch
>= '0' && ch
<= '9') {
3557 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3563 if (ch
== 'e' || ch
== 'E') {
3564 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3568 if (ch
== '-' || ch
== '+') {
3569 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3574 if (ch
< '0' || ch
> '9')
3575 expect("exponent digits");
3576 while (ch
>= '0' && ch
<= '9') {
3577 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3589 tokc
.f
= strtof(token_buf
, NULL
);
3590 } else if (t
== 'L') {
3593 tokc
.ld
= strtold(token_buf
, NULL
);
3596 tokc
.d
= strtod(token_buf
, NULL
);
3600 unsigned long long n
, n1
;
3603 /* integer number */
3606 if (b
== 10 && *q
== '0') {
3613 /* no need for checks except for base 10 / 8 errors */
3616 } else if (t
>= 'a') {
3618 } else if (t
>= 'A') {
3623 error("invalid digit");
3627 /* detect overflow */
3628 /* XXX: this test is not reliable */
3630 error("integer constant overflow");
3633 /* XXX: not exactly ANSI compliant */
3634 if ((n
& 0xffffffff00000000LL
) != 0) {
3639 } else if (n
> 0x7fffffff) {
3650 error("three 'l's in integer constant");
3653 if (tok
== TOK_CINT
)
3655 else if (tok
== TOK_CUINT
)
3659 } else if (t
== 'U') {
3661 error("two 'u's in integer constant");
3663 if (tok
== TOK_CINT
)
3665 else if (tok
== TOK_CLLONG
)
3672 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
3678 error("invalid number\n");
3682 #define PARSE2(c1, tok1, c2, tok2) \
3693 /* return next token without macro substitution */
3694 static inline void next_nomacro1(void)
3701 cstr_reset(&tok_spaces
);
3711 cstr_ccat(&tok_spaces
, c
);
3716 /* first look if it is in fact an end of buffer */
3717 if (p
>= file
->buf_end
) {
3721 if (p
>= file
->buf_end
)
3734 TCCState
*s1
= tcc_state
;
3735 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
3736 && !(tok_flags
& TOK_FLAG_EOF
)) {
3737 tok_flags
|= TOK_FLAG_EOF
;
3739 goto keep_tok_flags
;
3740 } else if (s1
->include_stack_ptr
== s1
->include_stack
||
3741 !(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3742 /* no include left : end of file. */
3745 tok_flags
&= ~TOK_FLAG_EOF
;
3746 /* pop include file */
3748 /* test if previous '#endif' was after a #ifdef at
3750 if (tok_flags
& TOK_FLAG_ENDIF
) {
3752 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
3754 add_cached_include(s1
, file
->inc_type
, file
->inc_filename
,
3755 file
->ifndef_macro_saved
);
3758 /* add end of include file debug info */
3760 put_stabd(N_EINCL
, 0, 0);
3762 /* pop include stack */
3764 s1
->include_stack_ptr
--;
3765 file
= *s1
->include_stack_ptr
;
3774 tok_flags
|= TOK_FLAG_BOL
;
3776 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
3779 goto keep_tok_flags
;
3784 if ((tok_flags
& TOK_FLAG_BOL
) &&
3785 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3787 preprocess(tok_flags
& TOK_FLAG_BOF
);
3793 tok
= TOK_TWOSHARPS
;
3795 if (parse_flags
& PARSE_FLAG_ASM_COMMENTS
) {
3796 p
= parse_line_comment(p
- 1);
3805 case 'a': case 'b': case 'c': case 'd':
3806 case 'e': case 'f': case 'g': case 'h':
3807 case 'i': case 'j': case 'k': case 'l':
3808 case 'm': case 'n': case 'o': case 'p':
3809 case 'q': case 'r': case 's': case 't':
3810 case 'u': case 'v': case 'w': case 'x':
3812 case 'A': case 'B': case 'C': case 'D':
3813 case 'E': case 'F': case 'G': case 'H':
3814 case 'I': case 'J': case 'K':
3815 case 'M': case 'N': case 'O': case 'P':
3816 case 'Q': case 'R': case 'S': case 'T':
3817 case 'U': case 'V': case 'W': case 'X':
3823 h
= TOK_HASH_FUNC(h
, c
);
3827 if (!isidnum_table
[c
-CH_EOF
])
3829 h
= TOK_HASH_FUNC(h
, c
);
3836 /* fast case : no stray found, so we have the full token
3837 and we have already hashed it */
3839 h
&= (TOK_HASH_SIZE
- 1);
3840 pts
= &hash_ident
[h
];
3845 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
3847 pts
= &(ts
->hash_next
);
3849 ts
= tok_alloc_new(pts
, p1
, len
);
3853 cstr_reset(&tokcstr
);
3856 cstr_ccat(&tokcstr
, *p1
);
3862 while (isidnum_table
[c
-CH_EOF
]) {
3863 cstr_ccat(&tokcstr
, c
);
3866 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
3872 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
3874 goto parse_ident_fast
;
3877 if (c
== '\'' || c
== '\"') {
3881 cstr_reset(&tokcstr
);
3882 cstr_ccat(&tokcstr
, 'L');
3883 goto parse_ident_slow
;
3887 case '0': case '1': case '2': case '3':
3888 case '4': case '5': case '6': case '7':
3891 cstr_reset(&tokcstr
);
3892 /* after the first digit, accept digits, alpha, '.' or sign if
3893 prefixed by 'eEpP' */
3897 cstr_ccat(&tokcstr
, c
);
3899 if (!(isnum(c
) || isid(c
) || c
== '.' ||
3900 ((c
== '+' || c
== '-') &&
3901 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
3904 /* We add a trailing '\0' to ease parsing */
3905 cstr_ccat(&tokcstr
, '\0');
3906 tokc
.cstr
= &tokcstr
;
3910 /* special dot handling because it can also start a number */
3913 cstr_reset(&tokcstr
);
3914 cstr_ccat(&tokcstr
, '.');
3916 } else if (c
== '.') {
3936 /* parse the string */
3938 p
= parse_pp_string(p
, sep
, &str
);
3939 cstr_ccat(&str
, '\0');
3941 /* eval the escape (should be done as TOK_PPNUM) */
3942 cstr_reset(&tokcstr
);
3943 parse_escape_string(&tokcstr
, str
.data
, is_long
);
3948 /* XXX: make it portable */
3952 char_size
= sizeof(nwchar_t
);
3953 if (tokcstr
.size
<= char_size
)
3954 error("empty character constant");
3955 if (tokcstr
.size
> 2 * char_size
)
3956 warning("multi-character character constant");
3958 tokc
.i
= *(int8_t *)tokcstr
.data
;
3961 tokc
.i
= *(nwchar_t
*)tokcstr
.data
;
3965 tokc
.cstr
= &tokcstr
;
3979 } else if (c
== '<') {
3997 } else if (c
== '>') {
4015 } else if (c
== '=') {
4028 } else if (c
== '=') {
4041 } else if (c
== '=') {
4054 } else if (c
== '=') {
4057 } else if (c
== '>') {
4065 PARSE2('!', '!', '=', TOK_NE
)
4066 PARSE2('=', '=', '=', TOK_EQ
)
4067 PARSE2('*', '*', '=', TOK_A_MUL
)
4068 PARSE2('%', '%', '=', TOK_A_MOD
)
4069 PARSE2('^', '^', '=', TOK_A_XOR
)
4071 /* comments or operator */
4075 p
= parse_comment(p
);
4077 } else if (c
== '/') {
4078 p
= parse_line_comment(p
);
4080 } else if (c
== '=') {
4100 case '$': /* only used in assembler */
4101 case '@': /* dito */
4106 error("unrecognized character \\x%02x", c
);
4112 #if defined(PARSE_DEBUG)
4113 printf("token = %s\n", get_tok_str(tok
, &tokc
));
4117 /* return next token without macro substitution. Can read input from
4119 static void next_nomacro(void)
4125 TOK_GET(tok
, macro_ptr
, tokc
);
4126 if (tok
== TOK_LINENUM
) {
4127 file
->line_num
= tokc
.i
;
4136 /* substitute args in macro_str and return allocated string */
4137 static int *macro_arg_subst(Sym
**nested_list
, int *macro_str
, Sym
*args
)
4139 int *st
, last_tok
, t
, notfirst
;
4148 TOK_GET(t
, macro_str
, cval
);
4153 TOK_GET(t
, macro_str
, cval
);
4156 s
= sym_find2(args
, t
);
4163 cstr_ccat(&cstr
, ' ');
4164 TOK_GET(t
, st
, cval
);
4165 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
4170 cstr_ccat(&cstr
, '\0');
4172 printf("stringize: %s\n", (char *)cstr
.data
);
4176 tok_str_add2(&str
, TOK_STR
, &cval
);
4179 tok_str_add2(&str
, t
, &cval
);
4181 } else if (t
>= TOK_IDENT
) {
4182 s
= sym_find2(args
, t
);
4185 /* if '##' is present before or after, no arg substitution */
4186 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
4187 /* special case for var arg macros : ## eats the
4188 ',' if empty VA_ARGS variable. */
4189 /* XXX: test of the ',' is not 100%
4190 reliable. should fix it to avoid security
4192 if (gnu_ext
&& s
->type
.t
&&
4193 last_tok
== TOK_TWOSHARPS
&&
4194 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
4196 /* suppress ',' '##' */
4199 /* suppress '##' and add variable */
4207 TOK_GET(t1
, st
, cval
);
4210 tok_str_add2(&str
, t1
, &cval
);
4214 /* NOTE: the stream cannot be read when macro
4215 substituing an argument */
4216 macro_subst(&str
, nested_list
, st
, NULL
);
4219 tok_str_add(&str
, t
);
4222 tok_str_add2(&str
, t
, &cval
);
4226 tok_str_add(&str
, 0);
4230 static char const ab_month_name
[12][4] =
4232 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
4233 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
4236 /* do macro substitution of current token with macro 's' and add
4237 result to (tok_str,tok_len). 'nested_list' is the list of all
4238 macros we got inside to avoid recursing. Return non zero if no
4239 substitution needs to be done */
4240 static int macro_subst_tok(TokenString
*tok_str
,
4241 Sym
**nested_list
, Sym
*s
, struct macro_level
**can_read_stream
)
4243 Sym
*args
, *sa
, *sa1
;
4244 int mstr_allocated
, parlevel
, *mstr
, t
, t1
;
4251 /* if symbol is a macro, prepare substitution */
4252 /* special macros */
4253 if (tok
== TOK___LINE__
) {
4254 snprintf(buf
, sizeof(buf
), "%d", file
->line_num
);
4258 } else if (tok
== TOK___FILE__
) {
4259 cstrval
= file
->filename
;
4261 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
4266 tm
= localtime(&ti
);
4267 if (tok
== TOK___DATE__
) {
4268 snprintf(buf
, sizeof(buf
), "%s %2d %d",
4269 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
4271 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
4272 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
4279 cstr_cat(&cstr
, cstrval
);
4280 cstr_ccat(&cstr
, '\0');
4282 tok_str_add2(tok_str
, t1
, &cval
);
4287 if (s
->type
.t
== MACRO_FUNC
) {
4288 /* NOTE: we do not use next_nomacro to avoid eating the
4289 next token. XXX: find better solution */
4293 if (t
== 0 && can_read_stream
) {
4294 /* end of macro stream: we must look at the token
4295 after in the file */
4296 struct macro_level
*ml
= *can_read_stream
;
4302 *can_read_stream
= ml
-> prev
;
4307 /* XXX: incorrect with comments */
4308 ch
= file
->buf_ptr
[0];
4309 while (is_space(ch
) || ch
== '\n')
4313 if (t
!= '(') /* no macro subst */
4316 /* argument macro */
4321 /* NOTE: empty args are allowed, except if no args */
4323 /* handle '()' case */
4324 if (!args
&& !sa
&& tok
== ')')
4327 error("macro '%s' used with too many args",
4328 get_tok_str(s
->v
, 0));
4331 /* NOTE: non zero sa->t indicates VA_ARGS */
4332 while ((parlevel
> 0 ||
4334 (tok
!= ',' || sa
->type
.t
))) &&
4338 else if (tok
== ')')
4340 if (tok
!= TOK_LINEFEED
)
4341 tok_str_add2(&str
, tok
, &tokc
);
4344 tok_str_add(&str
, 0);
4345 sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, (long)str
.str
);
4348 /* special case for gcc var args: add an empty
4349 var arg argument if it is omitted */
4350 if (sa
&& sa
->type
.t
&& gnu_ext
)
4360 error("macro '%s' used with too few args",
4361 get_tok_str(s
->v
, 0));
4364 /* now subst each arg */
4365 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
4370 tok_str_free((int *)sa
->c
);
4376 sym_push2(nested_list
, s
->v
, 0, 0);
4377 macro_subst(tok_str
, nested_list
, mstr
, can_read_stream
);
4378 /* pop nested defined symbol */
4380 *nested_list
= sa1
->prev
;
4388 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
4389 return the resulting string (which must be freed). */
4390 static inline int *macro_twosharps(const int *macro_str
)
4393 const int *macro_ptr1
, *start_macro_ptr
, *ptr
, *saved_macro_ptr
;
4395 const char *p1
, *p2
;
4397 TokenString macro_str1
;
4400 start_macro_ptr
= macro_str
;
4401 /* we search the first '##' */
4403 macro_ptr1
= macro_str
;
4404 TOK_GET(t
, macro_str
, cval
);
4405 /* nothing more to do if end of string */
4408 if (*macro_str
== TOK_TWOSHARPS
)
4412 /* we saw '##', so we need more processing to handle it */
4414 tok_str_new(¯o_str1
);
4418 /* add all tokens seen so far */
4419 for(ptr
= start_macro_ptr
; ptr
< macro_ptr1
;) {
4420 TOK_GET(t
, ptr
, cval
);
4421 tok_str_add2(¯o_str1
, t
, &cval
);
4423 saved_macro_ptr
= macro_ptr
;
4424 /* XXX: get rid of the use of macro_ptr here */
4425 macro_ptr
= (int *)macro_str
;
4427 while (*macro_ptr
== TOK_TWOSHARPS
) {
4429 macro_ptr1
= macro_ptr
;
4432 TOK_GET(t
, macro_ptr
, cval
);
4433 /* We concatenate the two tokens if we have an
4434 identifier or a preprocessing number */
4436 p1
= get_tok_str(tok
, &tokc
);
4437 cstr_cat(&cstr
, p1
);
4438 p2
= get_tok_str(t
, &cval
);
4439 cstr_cat(&cstr
, p2
);
4440 cstr_ccat(&cstr
, '\0');
4442 if ((tok
>= TOK_IDENT
|| tok
== TOK_PPNUM
) &&
4443 (t
>= TOK_IDENT
|| t
== TOK_PPNUM
)) {
4444 if (tok
== TOK_PPNUM
) {
4445 /* if number, then create a number token */
4446 /* NOTE: no need to allocate because
4447 tok_str_add2() does it */
4448 cstr_reset(&tokcstr
);
4451 tokc
.cstr
= &tokcstr
;
4453 /* if identifier, we must do a test to
4454 validate we have a correct identifier */
4455 if (t
== TOK_PPNUM
) {
4465 if (!isnum(c
) && !isid(c
))
4469 ts
= tok_alloc(cstr
.data
, strlen(cstr
.data
));
4470 tok
= ts
->tok
; /* modify current token */
4473 const char *str
= cstr
.data
;
4474 const unsigned char *q
;
4476 /* we look for a valid token */
4477 /* XXX: do more extensive checks */
4478 if (!strcmp(str
, ">>=")) {
4480 } else if (!strcmp(str
, "<<=")) {
4482 } else if (strlen(str
) == 2) {
4483 /* search in two bytes table */
4488 if (q
[0] == str
[0] && q
[1] == str
[1])
4495 /* NOTE: because get_tok_str use a static buffer,
4498 p1
= get_tok_str(tok
, &tokc
);
4499 cstr_cat(&cstr
, p1
);
4500 cstr_ccat(&cstr
, '\0');
4501 p2
= get_tok_str(t
, &cval
);
4502 warning("pasting \"%s\" and \"%s\" does not give a valid preprocessing token", cstr
.data
, p2
);
4503 /* cannot merge tokens: just add them separately */
4504 tok_str_add2(¯o_str1
, tok
, &tokc
);
4505 /* XXX: free associated memory ? */
4512 tok_str_add2(¯o_str1
, tok
, &tokc
);
4517 macro_ptr
= (int *)saved_macro_ptr
;
4519 tok_str_add(¯o_str1
, 0);
4520 return macro_str1
.str
;
4524 /* do macro substitution of macro_str and add result to
4525 (tok_str,tok_len). 'nested_list' is the list of all macros we got
4526 inside to avoid recursing. */
4527 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
4528 const int *macro_str
, struct macro_level
** can_read_stream
)
4535 struct macro_level ml
;
4537 /* first scan for '##' operator handling */
4539 macro_str1
= macro_twosharps(ptr
);
4543 /* NOTE: ptr == NULL can only happen if tokens are read from
4544 file stream due to a macro function call */
4547 TOK_GET(t
, ptr
, cval
);
4552 /* if nested substitution, do nothing */
4553 if (sym_find2(*nested_list
, t
))
4556 if (can_read_stream
)
4557 ml
.prev
= *can_read_stream
, *can_read_stream
= &ml
;
4558 macro_ptr
= (int *)ptr
;
4560 ret
= macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
4561 ptr
= (int *)macro_ptr
;
4563 if (can_read_stream
&& *can_read_stream
== &ml
)
4564 *can_read_stream
= ml
.prev
;
4569 tok_str_add2(tok_str
, t
, &cval
);
4573 tok_str_free(macro_str1
);
4576 /* return next token with macro substitution */
4577 static void next(void)
4579 Sym
*nested_list
, *s
;
4581 struct macro_level
*ml
;
4586 /* if not reading from macro substituted string, then try
4587 to substitute macros */
4588 if (tok
>= TOK_IDENT
&&
4589 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
4590 s
= define_find(tok
);
4592 /* we have a macro: we try to substitute */
4596 if (macro_subst_tok(&str
, &nested_list
, s
, &ml
) == 0) {
4597 /* substitution done, NOTE: maybe empty */
4598 tok_str_add(&str
, 0);
4599 macro_ptr
= str
.str
;
4600 macro_ptr_allocated
= str
.str
;
4607 /* end of macro or end of unget buffer */
4608 if (unget_buffer_enabled
) {
4609 macro_ptr
= unget_saved_macro_ptr
;
4610 unget_buffer_enabled
= 0;
4612 /* end of macro string: free it */
4613 tok_str_free(macro_ptr_allocated
);
4620 /* convert preprocessor tokens into C tokens */
4621 if (tok
== TOK_PPNUM
&&
4622 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
4623 parse_number((char *)tokc
.cstr
->data
);
4627 /* push back current token and set current token to 'last_tok'. Only
4628 identifier case handled for labels. */
4629 static inline void unget_tok(int last_tok
)
4633 unget_saved_macro_ptr
= macro_ptr
;
4634 unget_buffer_enabled
= 1;
4635 q
= unget_saved_buffer
;
4638 n
= tok_ext_size(tok
) - 1;
4641 *q
= 0; /* end of token string */
4646 void swap(int *p
, int *q
)
4654 void vsetc(CType
*type
, int r
, CValue
*vc
)
4658 if (vtop
>= vstack
+ (VSTACK_SIZE
- 1))
4659 error("memory full");
4660 /* cannot let cpu flags if other instruction are generated. Also
4661 avoid leaving VT_JMP anywhere except on the top of the stack
4662 because it would complicate the code generator. */
4663 if (vtop
>= vstack
) {
4664 v
= vtop
->r
& VT_VALMASK
;
4665 if (v
== VT_CMP
|| (v
& ~1) == VT_JMP
)
4671 vtop
->r2
= VT_CONST
;
4675 /* push integer constant */
4680 vsetc(&int_type
, VT_CONST
, &cval
);
4683 /* push long long constant */
4684 void vpushll(long long v
)
4690 vsetc(&ctype
, VT_CONST
, &cval
);
4693 /* Return a static symbol pointing to a section */
4694 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
4695 unsigned long offset
, unsigned long size
)
4701 sym
= global_identifier_push(v
, type
->t
| VT_STATIC
, 0);
4702 sym
->type
.ref
= type
->ref
;
4703 sym
->r
= VT_CONST
| VT_SYM
;
4704 put_extern_sym(sym
, sec
, offset
, size
);
4708 /* push a reference to a section offset by adding a dummy symbol */
4709 static void vpush_ref(CType
*type
, Section
*sec
, unsigned long offset
, unsigned long size
)
4714 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4715 vtop
->sym
= get_sym_ref(type
, sec
, offset
, size
);
4718 /* define a new external reference to a symbol 'v' of type 'u' */
4719 static Sym
*external_global_sym(int v
, CType
*type
, int r
)
4725 /* push forward reference */
4726 s
= global_identifier_push(v
, type
->t
| VT_EXTERN
, 0);
4727 s
->type
.ref
= type
->ref
;
4728 s
->r
= r
| VT_CONST
| VT_SYM
;
4733 /* define a new external reference to a symbol 'v' of type 'u' */
4734 static Sym
*external_sym(int v
, CType
*type
, int r
)
4740 /* push forward reference */
4741 s
= sym_push(v
, type
, r
| VT_CONST
| VT_SYM
, 0);
4742 s
->type
.t
|= VT_EXTERN
;
4744 if (!is_compatible_types(&s
->type
, type
))
4745 error("incompatible types for redefinition of '%s'",
4746 get_tok_str(v
, NULL
));
4751 /* push a reference to global symbol v */
4752 static void vpush_global_sym(CType
*type
, int v
)
4757 sym
= external_global_sym(v
, type
, 0);
4759 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4763 void vset(CType
*type
, int r
, int v
)
4768 vsetc(type
, r
, &cval
);
4771 void vseti(int r
, int v
)
4787 void vpushv(SValue
*v
)
4789 if (vtop
>= vstack
+ (VSTACK_SIZE
- 1))
4790 error("memory full");
4800 /* save r to the memory stack, and mark it as being free */
4801 void save_reg(int r
)
4803 int l
, saved
, size
, align
;
4807 /* modify all stack values */
4810 for(p
=vstack
;p
<=vtop
;p
++) {
4811 if ((p
->r
& VT_VALMASK
) == r
||
4812 ((p
->type
.t
& VT_BTYPE
) == VT_LLONG
&& (p
->r2
& VT_VALMASK
) == r
)) {
4813 /* must save value on stack if not already done */
4815 /* NOTE: must reload 'r' because r might be equal to r2 */
4816 r
= p
->r
& VT_VALMASK
;
4817 /* store register in the stack */
4819 if ((p
->r
& VT_LVAL
) ||
4820 (!is_float(type
->t
) && (type
->t
& VT_BTYPE
) != VT_LLONG
))
4821 #ifdef TCC_TARGET_X86_64
4822 type
= &char_pointer_type
;
4826 size
= type_size(type
, &align
);
4827 loc
= (loc
- size
) & -align
;
4828 sv
.type
.t
= type
->t
;
4829 sv
.r
= VT_LOCAL
| VT_LVAL
;
4832 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
4833 /* x86 specific: need to pop fp register ST0 if saved */
4834 if (r
== TREG_ST0
) {
4835 o(0xd9dd); /* fstp %st(1) */
4838 #ifndef TCC_TARGET_X86_64
4839 /* special long long case */
4840 if ((type
->t
& VT_BTYPE
) == VT_LLONG
) {
4848 /* mark that stack entry as being saved on the stack */
4849 if (p
->r
& VT_LVAL
) {
4850 /* also clear the bounded flag because the
4851 relocation address of the function was stored in
4853 p
->r
= (p
->r
& ~(VT_VALMASK
| VT_BOUNDED
)) | VT_LLOCAL
;
4855 p
->r
= lvalue_type(p
->type
.t
) | VT_LOCAL
;
4863 /* find a register of class 'rc2' with at most one reference on stack.
4864 * If none, call get_reg(rc) */
4865 int get_reg_ex(int rc
, int rc2
)
4870 for(r
=0;r
<NB_REGS
;r
++) {
4871 if (reg_classes
[r
] & rc2
) {
4874 for(p
= vstack
; p
<= vtop
; p
++) {
4875 if ((p
->r
& VT_VALMASK
) == r
||
4876 (p
->r2
& VT_VALMASK
) == r
)
4886 /* find a free register of class 'rc'. If none, save one register */
4892 /* find a free register */
4893 for(r
=0;r
<NB_REGS
;r
++) {
4894 if (reg_classes
[r
] & rc
) {
4895 for(p
=vstack
;p
<=vtop
;p
++) {
4896 if ((p
->r
& VT_VALMASK
) == r
||
4897 (p
->r2
& VT_VALMASK
) == r
)
4905 /* no register left : free the first one on the stack (VERY
4906 IMPORTANT to start from the bottom to ensure that we don't
4907 spill registers used in gen_opi()) */
4908 for(p
=vstack
;p
<=vtop
;p
++) {
4909 r
= p
->r
& VT_VALMASK
;
4910 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
))
4912 /* also look at second register (if long long) */
4913 r
= p
->r2
& VT_VALMASK
;
4914 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
)) {
4920 /* Should never comes here */
4924 /* save registers up to (vtop - n) stack entry */
4925 void save_regs(int n
)
4930 for(p
= vstack
;p
<= p1
; p
++) {
4931 r
= p
->r
& VT_VALMASK
;
4938 /* move register 's' to 'r', and flush previous value of r to memory
4940 void move_reg(int r
, int s
)
4953 /* get address of vtop (vtop MUST BE an lvalue) */
4956 vtop
->r
&= ~VT_LVAL
;
4957 /* tricky: if saved lvalue, then we can go back to lvalue */
4958 if ((vtop
->r
& VT_VALMASK
) == VT_LLOCAL
)
4959 vtop
->r
= (vtop
->r
& ~(VT_VALMASK
| VT_LVAL_TYPE
)) | VT_LOCAL
| VT_LVAL
;
4962 #ifdef CONFIG_TCC_BCHECK
4963 /* generate lvalue bound code */
4969 vtop
->r
&= ~VT_MUSTBOUND
;
4970 /* if lvalue, then use checking code before dereferencing */
4971 if (vtop
->r
& VT_LVAL
) {
4972 /* if not VT_BOUNDED value, then make one */
4973 if (!(vtop
->r
& VT_BOUNDED
)) {
4974 lval_type
= vtop
->r
& (VT_LVAL_TYPE
| VT_LVAL
);
4975 /* must save type because we must set it to int to get pointer */
4977 vtop
->type
.t
= VT_INT
;
4980 gen_bounded_ptr_add();
4981 vtop
->r
|= lval_type
;
4984 /* then check for dereferencing */
4985 gen_bounded_ptr_deref();
4990 /* store vtop a register belonging to class 'rc'. lvalues are
4991 converted to values. Cannot be used if cannot be converted to
4992 register value (such as structures). */
4995 int r
, rc2
, bit_pos
, bit_size
, size
, align
, i
;
4997 /* NOTE: get_reg can modify vstack[] */
4998 if (vtop
->type
.t
& VT_BITFIELD
) {
5001 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
5002 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
5003 /* remove bit field info to avoid loops */
5004 vtop
->type
.t
&= ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
5005 /* cast to int to propagate signedness in following ops */
5006 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
) {
5011 if((vtop
->type
.t
& VT_UNSIGNED
) ||
5012 (vtop
->type
.t
& VT_BTYPE
) == VT_BOOL
)
5013 type
.t
|= VT_UNSIGNED
;
5015 /* generate shifts */
5016 vpushi(bits
- (bit_pos
+ bit_size
));
5018 vpushi(bits
- bit_size
);
5019 /* NOTE: transformed to SHR if unsigned */
5023 if (is_float(vtop
->type
.t
) &&
5024 (vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
5027 unsigned long offset
;
5028 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
5032 /* XXX: unify with initializers handling ? */
5033 /* CPUs usually cannot use float constants, so we store them
5034 generically in data segment */
5035 size
= type_size(&vtop
->type
, &align
);
5036 offset
= (data_section
->data_offset
+ align
- 1) & -align
;
5037 data_section
->data_offset
= offset
;
5038 /* XXX: not portable yet */
5039 #if defined(__i386__) || defined(__x86_64__)
5040 /* Zero pad x87 tenbyte long doubles */
5041 if (size
== LDOUBLE_SIZE
)
5042 vtop
->c
.tab
[2] &= 0xffff;
5044 ptr
= section_ptr_add(data_section
, size
);
5046 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
5050 ptr
[i
] = vtop
->c
.tab
[size
-1-i
];
5054 ptr
[i
] = vtop
->c
.tab
[i
];
5055 sym
= get_sym_ref(&vtop
->type
, data_section
, offset
, size
<< 2);
5056 vtop
->r
|= VT_LVAL
| VT_SYM
;
5060 #ifdef CONFIG_TCC_BCHECK
5061 if (vtop
->r
& VT_MUSTBOUND
)
5065 r
= vtop
->r
& VT_VALMASK
;
5069 /* need to reload if:
5071 - lvalue (need to dereference pointer)
5072 - already a register, but not in the right class */
5073 if (r
>= VT_CONST
||
5074 (vtop
->r
& VT_LVAL
) ||
5075 !(reg_classes
[r
] & rc
) ||
5076 ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
&&
5077 !(reg_classes
[vtop
->r2
] & rc2
))) {
5079 #ifndef TCC_TARGET_X86_64
5080 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
) {
5082 unsigned long long ll
;
5083 /* two register type load : expand to two words
5085 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
5088 vtop
->c
.ui
= ll
; /* first word */
5090 vtop
->r
= r
; /* save register value */
5091 vpushi(ll
>> 32); /* second word */
5092 } else if (r
>= VT_CONST
|| /* XXX: test to VT_CONST incorrect ? */
5093 (vtop
->r
& VT_LVAL
)) {
5094 /* We do not want to modifier the long long
5095 pointer here, so the safest (and less
5096 efficient) is to save all the other registers
5097 in the stack. XXX: totally inefficient. */
5099 /* load from memory */
5102 vtop
[-1].r
= r
; /* save register value */
5103 /* increment pointer to get second word */
5104 vtop
->type
.t
= VT_INT
;
5110 /* move registers */
5113 vtop
[-1].r
= r
; /* save register value */
5114 vtop
->r
= vtop
[-1].r2
;
5116 /* allocate second register */
5120 /* write second register */
5124 if ((vtop
->r
& VT_LVAL
) && !is_float(vtop
->type
.t
)) {
5126 /* lvalue of scalar type : need to use lvalue type
5127 because of possible cast */
5130 /* compute memory access type */
5131 if (vtop
->r
& VT_LVAL_BYTE
)
5133 else if (vtop
->r
& VT_LVAL_SHORT
)
5135 if (vtop
->r
& VT_LVAL_UNSIGNED
)
5139 /* restore wanted type */
5142 /* one register type load */
5147 #ifdef TCC_TARGET_C67
5148 /* uses register pairs for doubles */
5149 if ((vtop
->type
.t
& VT_BTYPE
) == VT_DOUBLE
)
5156 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
5157 void gv2(int rc1
, int rc2
)
5161 /* generate more generic register first. But VT_JMP or VT_CMP
5162 values must be generated first in all cases to avoid possible
5164 v
= vtop
[0].r
& VT_VALMASK
;
5165 if (v
!= VT_CMP
&& (v
& ~1) != VT_JMP
&& rc1
<= rc2
) {
5170 /* test if reload is needed for first register */
5171 if ((vtop
[-1].r
& VT_VALMASK
) >= VT_CONST
) {
5181 /* test if reload is needed for first register */
5182 if ((vtop
[0].r
& VT_VALMASK
) >= VT_CONST
) {
5188 /* wrapper around RC_FRET to return a register by type */
5191 #ifdef TCC_TARGET_X86_64
5192 if (t
== VT_LDOUBLE
) {
5199 /* wrapper around REG_FRET to return a register by type */
5202 #ifdef TCC_TARGET_X86_64
5203 if (t
== VT_LDOUBLE
) {
5210 /* expand long long on stack in two int registers */
5215 u
= vtop
->type
.t
& VT_UNSIGNED
;
5218 vtop
[0].r
= vtop
[-1].r2
;
5219 vtop
[0].r2
= VT_CONST
;
5220 vtop
[-1].r2
= VT_CONST
;
5221 vtop
[0].type
.t
= VT_INT
| u
;
5222 vtop
[-1].type
.t
= VT_INT
| u
;
5225 #ifdef TCC_TARGET_ARM
5226 /* expand long long on stack */
5227 void lexpand_nr(void)
5231 u
= vtop
->type
.t
& VT_UNSIGNED
;
5233 vtop
->r2
= VT_CONST
;
5234 vtop
->type
.t
= VT_INT
| u
;
5235 v
=vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
);
5236 if (v
== VT_CONST
) {
5237 vtop
[-1].c
.ui
= vtop
->c
.ull
;
5238 vtop
->c
.ui
= vtop
->c
.ull
>> 32;
5240 } else if (v
== (VT_LVAL
|VT_CONST
) || v
== (VT_LVAL
|VT_LOCAL
)) {
5242 vtop
->r
= vtop
[-1].r
;
5243 } else if (v
> VT_CONST
) {
5247 vtop
->r
= vtop
[-1].r2
;
5248 vtop
[-1].r2
= VT_CONST
;
5249 vtop
[-1].type
.t
= VT_INT
| u
;
5253 /* build a long long from two ints */
5256 gv2(RC_INT
, RC_INT
);
5257 vtop
[-1].r2
= vtop
[0].r
;
5258 vtop
[-1].type
.t
= t
;
5262 /* rotate n first stack elements to the bottom
5263 I1 ... In -> I2 ... In I1 [top is right]
5271 for(i
=-n
+1;i
!=0;i
++)
5272 vtop
[i
] = vtop
[i
+1];
5276 /* rotate n first stack elements to the top
5277 I1 ... In -> In I1 ... I(n-1) [top is right]
5285 for(i
= 0;i
< n
- 1; i
++)
5286 vtop
[-i
] = vtop
[-i
- 1];
5290 #ifdef TCC_TARGET_ARM
5291 /* like vrott but in other direction
5292 In ... I1 -> I(n-1) ... I1 In [top is right]
5300 for(i
= n
- 1; i
> 0; i
--)
5301 vtop
[-i
] = vtop
[-i
+ 1];
5306 /* pop stack value */
5310 v
= vtop
->r
& VT_VALMASK
;
5311 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
5312 /* for x86, we need to pop the FP stack */
5313 if (v
== TREG_ST0
&& !nocode_wanted
) {
5314 o(0xd9dd); /* fstp %st(1) */
5317 if (v
== VT_JMP
|| v
== VT_JMPI
) {
5318 /* need to put correct jump if && or || without test */
5324 /* convert stack entry to register and duplicate its value in another
5332 if ((t
& VT_BTYPE
) == VT_LLONG
) {
5339 /* stack: H L L1 H1 */
5347 /* duplicate value */
5352 #ifdef TCC_TARGET_X86_64
5353 if ((t
& VT_BTYPE
) == VT_LDOUBLE
) {
5363 load(r1
, &sv
); /* move r to r1 */
5365 /* duplicates value */
5370 #ifndef TCC_TARGET_X86_64
5371 /* generate CPU independent (unsigned) long long operations */
5372 void gen_opl(int op
)
5374 int t
, a
, b
, op1
, c
, i
;
5376 unsigned short reg_iret
= REG_IRET
;
5377 unsigned short reg_lret
= REG_LRET
;
5383 func
= TOK___divdi3
;
5386 func
= TOK___udivdi3
;
5389 func
= TOK___moddi3
;
5392 func
= TOK___umoddi3
;
5399 /* call generic long long function */
5400 vpush_global_sym(&func_old_type
, func
);
5405 vtop
->r2
= reg_lret
;
5418 /* stack: L1 H1 L2 H2 */
5423 vtop
[-2] = vtop
[-3];
5426 /* stack: H1 H2 L1 L2 */
5432 /* stack: H1 H2 L1 L2 ML MH */
5435 /* stack: ML MH H1 H2 L1 L2 */
5439 /* stack: ML MH H1 L2 H2 L1 */
5444 /* stack: ML MH M1 M2 */
5447 } else if (op
== '+' || op
== '-') {
5448 /* XXX: add non carry method too (for MIPS or alpha) */
5454 /* stack: H1 H2 (L1 op L2) */
5457 gen_op(op1
+ 1); /* TOK_xxxC2 */
5460 /* stack: H1 H2 (L1 op L2) */
5463 /* stack: (L1 op L2) H1 H2 */
5465 /* stack: (L1 op L2) (H1 op H2) */
5473 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) {
5474 t
= vtop
[-1].type
.t
;
5478 /* stack: L H shift */
5480 /* constant: simpler */
5481 /* NOTE: all comments are for SHL. the other cases are
5482 done by swaping words */
5493 if (op
!= TOK_SAR
) {
5526 /* XXX: should provide a faster fallback on x86 ? */
5529 func
= TOK___ashrdi3
;
5532 func
= TOK___lshrdi3
;
5535 func
= TOK___ashldi3
;
5541 /* compare operations */
5547 /* stack: L1 H1 L2 H2 */
5549 vtop
[-1] = vtop
[-2];
5551 /* stack: L1 L2 H1 H2 */
5554 /* when values are equal, we need to compare low words. since
5555 the jump is inverted, we invert the test too. */
5558 else if (op1
== TOK_GT
)
5560 else if (op1
== TOK_ULT
)
5562 else if (op1
== TOK_UGT
)
5567 if (op1
!= TOK_NE
) {
5571 /* generate non equal test */
5572 /* XXX: NOT PORTABLE yet */
5576 #if defined(TCC_TARGET_I386)
5577 b
= psym(0x850f, 0);
5578 #elif defined(TCC_TARGET_ARM)
5580 o(0x1A000000 | encbranch(ind
, 0, 1));
5581 #elif defined(TCC_TARGET_C67)
5582 error("not implemented");
5584 #error not supported
5588 /* compare low. Always unsigned */
5592 else if (op1
== TOK_LE
)
5594 else if (op1
== TOK_GT
)
5596 else if (op1
== TOK_GE
)
5607 /* handle integer constant optimizations and various machine
5609 void gen_opic(int op
)
5611 int c1
, c2
, t1
, t2
, n
;
5614 typedef unsigned long long U
;
5618 t1
= v1
->type
.t
& VT_BTYPE
;
5619 t2
= v2
->type
.t
& VT_BTYPE
;
5623 else if (v1
->type
.t
& VT_UNSIGNED
)
5630 else if (v2
->type
.t
& VT_UNSIGNED
)
5635 /* currently, we cannot do computations with forward symbols */
5636 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5637 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5640 case '+': l1
+= l2
; break;
5641 case '-': l1
-= l2
; break;
5642 case '&': l1
&= l2
; break;
5643 case '^': l1
^= l2
; break;
5644 case '|': l1
|= l2
; break;
5645 case '*': l1
*= l2
; break;
5652 /* if division by zero, generate explicit division */
5655 error("division by zero in constant");
5659 default: l1
/= l2
; break;
5660 case '%': l1
%= l2
; break;
5661 case TOK_UDIV
: l1
= (U
)l1
/ l2
; break;
5662 case TOK_UMOD
: l1
= (U
)l1
% l2
; break;
5665 case TOK_SHL
: l1
<<= l2
; break;
5666 case TOK_SHR
: l1
= (U
)l1
>> l2
; break;
5667 case TOK_SAR
: l1
>>= l2
; break;
5669 case TOK_ULT
: l1
= (U
)l1
< (U
)l2
; break;
5670 case TOK_UGE
: l1
= (U
)l1
>= (U
)l2
; break;
5671 case TOK_EQ
: l1
= l1
== l2
; break;
5672 case TOK_NE
: l1
= l1
!= l2
; break;
5673 case TOK_ULE
: l1
= (U
)l1
<= (U
)l2
; break;
5674 case TOK_UGT
: l1
= (U
)l1
> (U
)l2
; break;
5675 case TOK_LT
: l1
= l1
< l2
; break;
5676 case TOK_GE
: l1
= l1
>= l2
; break;
5677 case TOK_LE
: l1
= l1
<= l2
; break;
5678 case TOK_GT
: l1
= l1
> l2
; break;
5680 case TOK_LAND
: l1
= l1
&& l2
; break;
5681 case TOK_LOR
: l1
= l1
|| l2
; break;
5688 /* if commutative ops, put c2 as constant */
5689 if (c1
&& (op
== '+' || op
== '&' || op
== '^' ||
5690 op
== '|' || op
== '*')) {
5692 c2
= c1
; //c = c1, c1 = c2, c2 = c;
5693 l2
= l1
; //l = l1, l1 = l2, l2 = l;
5695 /* Filter out NOP operations like x*1, x-0, x&-1... */
5696 if (c2
&& (((op
== '*' || op
== '/' || op
== TOK_UDIV
||
5699 ((op
== '+' || op
== '-' || op
== '|' || op
== '^' ||
5700 op
== TOK_SHL
|| op
== TOK_SHR
|| op
== TOK_SAR
) &&
5706 } else if (c2
&& (op
== '*' || op
== TOK_PDIV
|| op
== TOK_UDIV
)) {
5707 /* try to use shifts instead of muls or divs */
5708 if (l2
> 0 && (l2
& (l2
- 1)) == 0) {
5717 else if (op
== TOK_PDIV
)
5723 } else if (c2
&& (op
== '+' || op
== '-') &&
5724 ((vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) ==
5725 (VT_CONST
| VT_SYM
) ||
5726 (vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
)) == VT_LOCAL
)) {
5727 /* symbol + constant case */
5734 if (!nocode_wanted
) {
5735 /* call low level op generator */
5736 if (t1
== VT_LLONG
|| t2
== VT_LLONG
)
5747 /* generate a floating point operation with constant propagation */
5748 void gen_opif(int op
)
5756 /* currently, we cannot do computations with forward symbols */
5757 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5758 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5760 if (v1
->type
.t
== VT_FLOAT
) {
5763 } else if (v1
->type
.t
== VT_DOUBLE
) {
5771 /* NOTE: we only do constant propagation if finite number (not
5772 NaN or infinity) (ANSI spec) */
5773 if (!ieee_finite(f1
) || !ieee_finite(f2
))
5777 case '+': f1
+= f2
; break;
5778 case '-': f1
-= f2
; break;
5779 case '*': f1
*= f2
; break;
5783 error("division by zero in constant");
5788 /* XXX: also handles tests ? */
5792 /* XXX: overflow test ? */
5793 if (v1
->type
.t
== VT_FLOAT
) {
5795 } else if (v1
->type
.t
== VT_DOUBLE
) {
5803 if (!nocode_wanted
) {
5811 static int pointed_size(CType
*type
)
5814 return type_size(pointed_type(type
), &align
);
5817 static inline int is_null_pointer(SValue
*p
)
5819 if ((p
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
5821 return ((p
->type
.t
& VT_BTYPE
) == VT_INT
&& p
->c
.i
== 0) ||
5822 ((p
->type
.t
& VT_BTYPE
) == VT_LLONG
&& p
->c
.ll
== 0);
5825 static inline int is_integer_btype(int bt
)
5827 return (bt
== VT_BYTE
|| bt
== VT_SHORT
||
5828 bt
== VT_INT
|| bt
== VT_LLONG
);
5831 /* check types for comparison or substraction of pointers */
5832 static void check_comparison_pointer_types(SValue
*p1
, SValue
*p2
, int op
)
5834 CType
*type1
, *type2
, tmp_type1
, tmp_type2
;
5837 /* null pointers are accepted for all comparisons as gcc */
5838 if (is_null_pointer(p1
) || is_null_pointer(p2
))
5842 bt1
= type1
->t
& VT_BTYPE
;
5843 bt2
= type2
->t
& VT_BTYPE
;
5844 /* accept comparison between pointer and integer with a warning */
5845 if ((is_integer_btype(bt1
) || is_integer_btype(bt2
)) && op
!= '-') {
5846 if (op
!= TOK_LOR
&& op
!= TOK_LAND
)
5847 warning("comparison between pointer and integer");
5851 /* both must be pointers or implicit function pointers */
5852 if (bt1
== VT_PTR
) {
5853 type1
= pointed_type(type1
);
5854 } else if (bt1
!= VT_FUNC
)
5855 goto invalid_operands
;
5857 if (bt2
== VT_PTR
) {
5858 type2
= pointed_type(type2
);
5859 } else if (bt2
!= VT_FUNC
) {
5861 error("invalid operands to binary %s", get_tok_str(op
, NULL
));
5863 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
5864 (type2
->t
& VT_BTYPE
) == VT_VOID
)
5868 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5869 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5870 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
5871 /* gcc-like error if '-' is used */
5873 goto invalid_operands
;
5875 warning("comparison of distinct pointer types lacks a cast");
5879 /* generic gen_op: handles types problems */
5882 int u
, t1
, t2
, bt1
, bt2
, t
;
5885 t1
= vtop
[-1].type
.t
;
5886 t2
= vtop
[0].type
.t
;
5887 bt1
= t1
& VT_BTYPE
;
5888 bt2
= t2
& VT_BTYPE
;
5890 if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
5891 /* at least one operand is a pointer */
5892 /* relationnal op: must be both pointers */
5893 if (op
>= TOK_ULT
&& op
<= TOK_LOR
) {
5894 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5895 /* pointers are handled are unsigned */
5896 #ifdef TCC_TARGET_X86_64
5897 t
= VT_LLONG
| VT_UNSIGNED
;
5899 t
= VT_INT
| VT_UNSIGNED
;
5903 /* if both pointers, then it must be the '-' op */
5904 if (bt1
== VT_PTR
&& bt2
== VT_PTR
) {
5906 error("cannot use pointers here");
5907 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5908 /* XXX: check that types are compatible */
5909 u
= pointed_size(&vtop
[-1].type
);
5911 /* set to integer type */
5912 #ifdef TCC_TARGET_X86_64
5913 vtop
->type
.t
= VT_LLONG
;
5915 vtop
->type
.t
= VT_INT
;
5920 /* exactly one pointer : must be '+' or '-'. */
5921 if (op
!= '-' && op
!= '+')
5922 error("cannot use pointers here");
5923 /* Put pointer as first operand */
5924 if (bt2
== VT_PTR
) {
5928 type1
= vtop
[-1].type
;
5929 #ifdef TCC_TARGET_X86_64
5930 vpushll(pointed_size(&vtop
[-1].type
));
5932 /* XXX: cast to int ? (long long case) */
5933 vpushi(pointed_size(&vtop
[-1].type
));
5936 #ifdef CONFIG_TCC_BCHECK
5937 /* if evaluating constant expression, no code should be
5938 generated, so no bound check */
5939 if (do_bounds_check
&& !const_wanted
) {
5940 /* if bounded pointers, we generate a special code to
5947 gen_bounded_ptr_add();
5953 /* put again type if gen_opic() swaped operands */
5956 } else if (is_float(bt1
) || is_float(bt2
)) {
5957 /* compute bigger type and do implicit casts */
5958 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
5960 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
5965 /* floats can only be used for a few operations */
5966 if (op
!= '+' && op
!= '-' && op
!= '*' && op
!= '/' &&
5967 (op
< TOK_ULT
|| op
> TOK_GT
))
5968 error("invalid operands for binary operation");
5970 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
5971 /* cast to biggest op */
5973 /* convert to unsigned if it does not fit in a long long */
5974 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
5975 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
5979 /* integer operations */
5981 /* convert to unsigned if it does not fit in an integer */
5982 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
5983 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
5986 /* XXX: currently, some unsigned operations are explicit, so
5987 we modify them here */
5988 if (t
& VT_UNSIGNED
) {
5995 else if (op
== TOK_LT
)
5997 else if (op
== TOK_GT
)
5999 else if (op
== TOK_LE
)
6001 else if (op
== TOK_GE
)
6008 /* special case for shifts and long long: we keep the shift as
6010 if (op
== TOK_SHR
|| op
== TOK_SAR
|| op
== TOK_SHL
)
6017 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
6018 /* relationnal op: the result is an int */
6019 vtop
->type
.t
= VT_INT
;
6026 #ifndef TCC_TARGET_ARM
6027 /* generic itof for unsigned long long case */
6028 void gen_cvt_itof1(int t
)
6030 if ((vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
)) ==
6031 (VT_LLONG
| VT_UNSIGNED
)) {
6034 vpush_global_sym(&func_old_type
, TOK___floatundisf
);
6035 #if LDOUBLE_SIZE != 8
6036 else if (t
== VT_LDOUBLE
)
6037 vpush_global_sym(&func_old_type
, TOK___floatundixf
);
6040 vpush_global_sym(&func_old_type
, TOK___floatundidf
);
6044 vtop
->r
= reg_fret(t
);
6051 /* generic ftoi for unsigned long long case */
6052 void gen_cvt_ftoi1(int t
)
6056 if (t
== (VT_LLONG
| VT_UNSIGNED
)) {
6057 /* not handled natively */
6058 st
= vtop
->type
.t
& VT_BTYPE
;
6060 vpush_global_sym(&func_old_type
, TOK___fixunssfdi
);
6061 #if LDOUBLE_SIZE != 8
6062 else if (st
== VT_LDOUBLE
)
6063 vpush_global_sym(&func_old_type
, TOK___fixunsxfdi
);
6066 vpush_global_sym(&func_old_type
, TOK___fixunsdfdi
);
6071 vtop
->r2
= REG_LRET
;
6077 /* force char or short cast */
6078 void force_charshort_cast(int t
)
6082 /* XXX: add optimization if lvalue : just change type and offset */
6087 if (t
& VT_UNSIGNED
) {
6088 vpushi((1 << bits
) - 1);
6094 /* result must be signed or the SAR is converted to an SHL
6095 This was not the case when "t" was a signed short
6096 and the last value on the stack was an unsigned int */
6097 vtop
->type
.t
&= ~VT_UNSIGNED
;
6103 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
6104 static void gen_cast(CType
*type
)
6106 int sbt
, dbt
, sf
, df
, c
, p
;
6108 /* special delayed cast for char/short */
6109 /* XXX: in some cases (multiple cascaded casts), it may still
6111 if (vtop
->r
& VT_MUSTCAST
) {
6112 vtop
->r
&= ~VT_MUSTCAST
;
6113 force_charshort_cast(vtop
->type
.t
);
6116 /* bitfields first get cast to ints */
6117 if (vtop
->type
.t
& VT_BITFIELD
) {
6121 dbt
= type
->t
& (VT_BTYPE
| VT_UNSIGNED
);
6122 sbt
= vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
);
6127 c
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
6128 p
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == (VT_CONST
| VT_SYM
);
6130 /* constant case: we can do it now */
6131 /* XXX: in ISOC, cannot do it if error in convert */
6132 if (sbt
== VT_FLOAT
)
6133 vtop
->c
.ld
= vtop
->c
.f
;
6134 else if (sbt
== VT_DOUBLE
)
6135 vtop
->c
.ld
= vtop
->c
.d
;
6138 if ((sbt
& VT_BTYPE
) == VT_LLONG
) {
6139 if (sbt
& VT_UNSIGNED
)
6140 vtop
->c
.ld
= vtop
->c
.ull
;
6142 vtop
->c
.ld
= vtop
->c
.ll
;
6144 if (sbt
& VT_UNSIGNED
)
6145 vtop
->c
.ld
= vtop
->c
.ui
;
6147 vtop
->c
.ld
= vtop
->c
.i
;
6150 if (dbt
== VT_FLOAT
)
6151 vtop
->c
.f
= (float)vtop
->c
.ld
;
6152 else if (dbt
== VT_DOUBLE
)
6153 vtop
->c
.d
= (double)vtop
->c
.ld
;
6154 } else if (sf
&& dbt
== (VT_LLONG
|VT_UNSIGNED
)) {
6155 vtop
->c
.ull
= (unsigned long long)vtop
->c
.ld
;
6156 } else if (sf
&& dbt
== VT_BOOL
) {
6157 vtop
->c
.i
= (vtop
->c
.ld
!= 0);
6160 vtop
->c
.ll
= (long long)vtop
->c
.ld
;
6161 else if (sbt
== (VT_LLONG
|VT_UNSIGNED
))
6162 vtop
->c
.ll
= vtop
->c
.ull
;
6163 else if (sbt
& VT_UNSIGNED
)
6164 vtop
->c
.ll
= vtop
->c
.ui
;
6165 else if (sbt
!= VT_LLONG
)
6166 vtop
->c
.ll
= vtop
->c
.i
;
6168 if (dbt
== (VT_LLONG
|VT_UNSIGNED
))
6169 vtop
->c
.ull
= vtop
->c
.ll
;
6170 else if (dbt
== VT_BOOL
)
6171 vtop
->c
.i
= (vtop
->c
.ll
!= 0);
6172 else if (dbt
!= VT_LLONG
) {
6174 if ((dbt
& VT_BTYPE
) == VT_BYTE
)
6176 else if ((dbt
& VT_BTYPE
) == VT_SHORT
)
6179 if(dbt
& VT_UNSIGNED
)
6180 vtop
->c
.ui
= ((unsigned int)vtop
->c
.ll
<< s
) >> s
;
6182 vtop
->c
.i
= ((int)vtop
->c
.ll
<< s
) >> s
;
6185 } else if (p
&& dbt
== VT_BOOL
) {
6188 } else if (!nocode_wanted
) {
6189 /* non constant case: generate code */
6191 /* convert from fp to fp */
6194 /* convert int to fp */
6197 /* convert fp to int */
6198 if (dbt
== VT_BOOL
) {
6202 /* we handle char/short/etc... with generic code */
6203 if (dbt
!= (VT_INT
| VT_UNSIGNED
) &&
6204 dbt
!= (VT_LLONG
| VT_UNSIGNED
) &&
6208 if (dbt
== VT_INT
&& (type
->t
& (VT_BTYPE
| VT_UNSIGNED
)) != dbt
) {
6209 /* additional cast for char/short... */
6214 #ifndef TCC_TARGET_X86_64
6215 } else if ((dbt
& VT_BTYPE
) == VT_LLONG
) {
6216 if ((sbt
& VT_BTYPE
) != VT_LLONG
) {
6217 /* scalar to long long */
6218 /* machine independent conversion */
6220 /* generate high word */
6221 if (sbt
== (VT_INT
| VT_UNSIGNED
)) {
6225 if (sbt
== VT_PTR
) {
6226 /* cast from pointer to int before we apply
6227 shift operation, which pointers don't support*/
6228 gen_cast(&int_type
);
6234 /* patch second register */
6235 vtop
[-1].r2
= vtop
->r
;
6239 } else if ((dbt
& VT_BTYPE
) == VT_LLONG
||
6240 (dbt
& VT_BTYPE
) == VT_PTR
) {
6241 /* XXX: not sure if this is perfect... need more tests */
6242 if ((sbt
& VT_BTYPE
) != VT_LLONG
) {
6244 if (sbt
!= (VT_INT
| VT_UNSIGNED
) &&
6245 sbt
!= VT_PTR
&& sbt
!= VT_FUNC
) {
6246 /* x86_64 specific: movslq */
6248 o(0xc0 + (REG_VALUE(r
) << 3) + REG_VALUE(r
));
6252 } else if (dbt
== VT_BOOL
) {
6253 /* scalar to bool */
6256 } else if ((dbt
& VT_BTYPE
) == VT_BYTE
||
6257 (dbt
& VT_BTYPE
) == VT_SHORT
) {
6258 if (sbt
== VT_PTR
) {
6259 vtop
->type
.t
= VT_INT
;
6260 warning("nonportable conversion from pointer to char/short");
6262 force_charshort_cast(dbt
);
6263 } else if ((dbt
& VT_BTYPE
) == VT_INT
) {
6265 if (sbt
== VT_LLONG
) {
6266 /* from long long: just take low order word */
6270 /* if lvalue and single word type, nothing to do because
6271 the lvalue already contains the real type size (see
6272 VT_LVAL_xxx constants) */
6275 } else if ((dbt
& VT_BTYPE
) == VT_PTR
&& !(vtop
->r
& VT_LVAL
)) {
6276 /* if we are casting between pointer types,
6277 we must update the VT_LVAL_xxx size */
6278 vtop
->r
= (vtop
->r
& ~VT_LVAL_TYPE
)
6279 | (lvalue_type(type
->ref
->type
.t
) & VT_LVAL_TYPE
);
6284 /* return type size. Put alignment at 'a' */
6285 static int type_size(CType
*type
, int *a
)
6290 bt
= type
->t
& VT_BTYPE
;
6291 if (bt
== VT_STRUCT
) {
6296 } else if (bt
== VT_PTR
) {
6297 if (type
->t
& VT_ARRAY
) {
6301 ts
= type_size(&s
->type
, a
);
6303 if (ts
< 0 && s
->c
< 0)
6311 } else if (bt
== VT_LDOUBLE
) {
6313 return LDOUBLE_SIZE
;
6314 } else if (bt
== VT_DOUBLE
|| bt
== VT_LLONG
) {
6315 #ifdef TCC_TARGET_I386
6316 #ifdef TCC_TARGET_PE
6321 #elif defined(TCC_TARGET_ARM)
6331 } else if (bt
== VT_INT
|| bt
== VT_ENUM
|| bt
== VT_FLOAT
) {
6334 } else if (bt
== VT_SHORT
) {
6338 /* char, void, function, _Bool */
6344 /* return the pointed type of t */
6345 static inline CType
*pointed_type(CType
*type
)
6347 return &type
->ref
->type
;
6350 /* modify type so that its it is a pointer to type. */
6351 static void mk_pointer(CType
*type
)
6354 s
= sym_push(SYM_FIELD
, type
, 0, -1);
6355 type
->t
= VT_PTR
| (type
->t
& ~VT_TYPE
);
6359 /* compare function types. OLD functions match any new functions */
6360 static int is_compatible_func(CType
*type1
, CType
*type2
)
6366 if (!is_compatible_types(&s1
->type
, &s2
->type
))
6368 /* check func_call */
6369 if (FUNC_CALL(s1
->r
) != FUNC_CALL(s2
->r
))
6371 /* XXX: not complete */
6372 if (s1
->c
== FUNC_OLD
|| s2
->c
== FUNC_OLD
)
6376 while (s1
!= NULL
) {
6379 if (!is_compatible_parameter_types(&s1
->type
, &s2
->type
))
6389 /* return true if type1 and type2 are the same. If unqualified is
6390 true, qualifiers on the types are ignored.
6392 - enums are not checked as gcc __builtin_types_compatible_p ()
6394 static int compare_types(CType
*type1
, CType
*type2
, int unqualified
)
6398 t1
= type1
->t
& VT_TYPE
;
6399 t2
= type2
->t
& VT_TYPE
;
6401 /* strip qualifiers before comparing */
6402 t1
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6403 t2
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6405 /* XXX: bitfields ? */
6408 /* test more complicated cases */
6409 bt1
= t1
& VT_BTYPE
;
6410 if (bt1
== VT_PTR
) {
6411 type1
= pointed_type(type1
);
6412 type2
= pointed_type(type2
);
6413 return is_compatible_types(type1
, type2
);
6414 } else if (bt1
== VT_STRUCT
) {
6415 return (type1
->ref
== type2
->ref
);
6416 } else if (bt1
== VT_FUNC
) {
6417 return is_compatible_func(type1
, type2
);
6423 /* return true if type1 and type2 are exactly the same (including
6426 static int is_compatible_types(CType
*type1
, CType
*type2
)
6428 return compare_types(type1
,type2
,0);
6431 /* return true if type1 and type2 are the same (ignoring qualifiers).
6433 static int is_compatible_parameter_types(CType
*type1
, CType
*type2
)
6435 return compare_types(type1
,type2
,1);
6438 /* print a type. If 'varstr' is not NULL, then the variable is also
6439 printed in the type */
6441 /* XXX: add array and function pointers */
6442 void type_to_str(char *buf
, int buf_size
,
6443 CType
*type
, const char *varstr
)
6450 t
= type
->t
& VT_TYPE
;
6453 if (t
& VT_CONSTANT
)
6454 pstrcat(buf
, buf_size
, "const ");
6455 if (t
& VT_VOLATILE
)
6456 pstrcat(buf
, buf_size
, "volatile ");
6457 if (t
& VT_UNSIGNED
)
6458 pstrcat(buf
, buf_size
, "unsigned ");
6488 tstr
= "long double";
6490 pstrcat(buf
, buf_size
, tstr
);
6494 if (bt
== VT_STRUCT
)
6498 pstrcat(buf
, buf_size
, tstr
);
6499 v
= type
->ref
->v
& ~SYM_STRUCT
;
6500 if (v
>= SYM_FIRST_ANOM
)
6501 pstrcat(buf
, buf_size
, "<anonymous>");
6503 pstrcat(buf
, buf_size
, get_tok_str(v
, NULL
));
6507 type_to_str(buf
, buf_size
, &s
->type
, varstr
);
6508 pstrcat(buf
, buf_size
, "(");
6510 while (sa
!= NULL
) {
6511 type_to_str(buf1
, sizeof(buf1
), &sa
->type
, NULL
);
6512 pstrcat(buf
, buf_size
, buf1
);
6515 pstrcat(buf
, buf_size
, ", ");
6517 pstrcat(buf
, buf_size
, ")");
6521 pstrcpy(buf1
, sizeof(buf1
), "*");
6523 pstrcat(buf1
, sizeof(buf1
), varstr
);
6524 type_to_str(buf
, buf_size
, &s
->type
, buf1
);
6528 pstrcat(buf
, buf_size
, " ");
6529 pstrcat(buf
, buf_size
, varstr
);
6534 /* verify type compatibility to store vtop in 'dt' type, and generate
6536 static void gen_assign_cast(CType
*dt
)
6538 CType
*st
, *type1
, *type2
, tmp_type1
, tmp_type2
;
6539 char buf1
[256], buf2
[256];
6542 st
= &vtop
->type
; /* source type */
6543 dbt
= dt
->t
& VT_BTYPE
;
6544 sbt
= st
->t
& VT_BTYPE
;
6545 if (dt
->t
& VT_CONSTANT
)
6546 warning("assignment of read-only location");
6549 /* special cases for pointers */
6550 /* '0' can also be a pointer */
6551 if (is_null_pointer(vtop
))
6553 /* accept implicit pointer to integer cast with warning */
6554 if (is_integer_btype(sbt
)) {
6555 warning("assignment makes pointer from integer without a cast");
6558 type1
= pointed_type(dt
);
6559 /* a function is implicitely a function pointer */
6560 if (sbt
== VT_FUNC
) {
6561 if ((type1
->t
& VT_BTYPE
) != VT_VOID
&&
6562 !is_compatible_types(pointed_type(dt
), st
))
6569 type2
= pointed_type(st
);
6570 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
6571 (type2
->t
& VT_BTYPE
) == VT_VOID
) {
6572 /* void * can match anything */
6574 /* exact type match, except for unsigned */
6577 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
6578 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
6579 if (!is_compatible_types(&tmp_type1
, &tmp_type2
))
6580 warning("assignment from incompatible pointer type");
6582 /* check const and volatile */
6583 if ((!(type1
->t
& VT_CONSTANT
) && (type2
->t
& VT_CONSTANT
)) ||
6584 (!(type1
->t
& VT_VOLATILE
) && (type2
->t
& VT_VOLATILE
)))
6585 warning("assignment discards qualifiers from pointer target type");
6591 if (sbt
== VT_PTR
|| sbt
== VT_FUNC
) {
6592 warning("assignment makes integer from pointer without a cast");
6594 /* XXX: more tests */
6599 tmp_type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6600 tmp_type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6601 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
6603 type_to_str(buf1
, sizeof(buf1
), st
, NULL
);
6604 type_to_str(buf2
, sizeof(buf2
), dt
, NULL
);
6605 error("cannot cast '%s' to '%s'", buf1
, buf2
);
6613 /* store vtop in lvalue pushed on stack */
6616 int sbt
, dbt
, ft
, r
, t
, size
, align
, bit_size
, bit_pos
, rc
, delayed_cast
;
6618 ft
= vtop
[-1].type
.t
;
6619 sbt
= vtop
->type
.t
& VT_BTYPE
;
6620 dbt
= ft
& VT_BTYPE
;
6621 if (((sbt
== VT_INT
|| sbt
== VT_SHORT
) && dbt
== VT_BYTE
) ||
6622 (sbt
== VT_INT
&& dbt
== VT_SHORT
)) {
6623 /* optimize char/short casts */
6624 delayed_cast
= VT_MUSTCAST
;
6625 vtop
->type
.t
= ft
& (VT_TYPE
& ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
)));
6626 /* XXX: factorize */
6627 if (ft
& VT_CONSTANT
)
6628 warning("assignment of read-only location");
6631 if (!(ft
& VT_BITFIELD
))
6632 gen_assign_cast(&vtop
[-1].type
);
6635 if (sbt
== VT_STRUCT
) {
6636 /* if structure, only generate pointer */
6637 /* structure assignment : generate memcpy */
6638 /* XXX: optimize if small size */
6639 if (!nocode_wanted
) {
6640 size
= type_size(&vtop
->type
, &align
);
6644 vpush_global_sym(&func_old_type
, TOK_memcpy8
);
6645 else if(!(align
& 3))
6646 vpush_global_sym(&func_old_type
, TOK_memcpy4
);
6649 vpush_global_sym(&func_old_type
, TOK_memcpy
);
6653 vtop
->type
.t
= VT_PTR
;
6657 vtop
->type
.t
= VT_PTR
;
6669 /* leave source on stack */
6670 } else if (ft
& VT_BITFIELD
) {
6671 /* bitfield store handling */
6672 bit_pos
= (ft
>> VT_STRUCT_SHIFT
) & 0x3f;
6673 bit_size
= (ft
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
6674 /* remove bit field info to avoid loops */
6675 vtop
[-1].type
.t
= ft
& ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
6677 /* duplicate source into other register */
6682 if((ft
& VT_BTYPE
) == VT_BOOL
) {
6683 gen_cast(&vtop
[-1].type
);
6684 vtop
[-1].type
.t
= (vtop
[-1].type
.t
& ~VT_BTYPE
) | (VT_BYTE
| VT_UNSIGNED
);
6687 /* duplicate destination */
6689 vtop
[-1] = vtop
[-2];
6691 /* mask and shift source */
6692 if((ft
& VT_BTYPE
) != VT_BOOL
) {
6693 if((ft
& VT_BTYPE
) == VT_LLONG
) {
6694 vpushll((1ULL << bit_size
) - 1ULL);
6696 vpushi((1 << bit_size
) - 1);
6702 /* load destination, mask and or with source */
6704 if((ft
& VT_BTYPE
) == VT_LLONG
) {
6705 vpushll(~(((1ULL << bit_size
) - 1ULL) << bit_pos
));
6707 vpushi(~(((1 << bit_size
) - 1) << bit_pos
));
6714 /* pop off shifted source from "duplicate source..." above */
6718 #ifdef CONFIG_TCC_BCHECK
6719 /* bound check case */
6720 if (vtop
[-1].r
& VT_MUSTBOUND
) {
6726 if (!nocode_wanted
) {
6730 #ifdef TCC_TARGET_X86_64
6731 if ((ft
& VT_BTYPE
) == VT_LDOUBLE
) {
6736 r
= gv(rc
); /* generate value */
6737 /* if lvalue was saved on stack, must read it */
6738 if ((vtop
[-1].r
& VT_VALMASK
) == VT_LLOCAL
) {
6740 t
= get_reg(RC_INT
);
6741 #ifdef TCC_TARGET_X86_64
6746 sv
.r
= VT_LOCAL
| VT_LVAL
;
6747 sv
.c
.ul
= vtop
[-1].c
.ul
;
6749 vtop
[-1].r
= t
| VT_LVAL
;
6752 #ifndef TCC_TARGET_X86_64
6753 /* two word case handling : store second register at word + 4 */
6754 if ((ft
& VT_BTYPE
) == VT_LLONG
) {
6756 /* convert to int to increment easily */
6757 vtop
->type
.t
= VT_INT
;
6763 /* XXX: it works because r2 is spilled last ! */
6764 store(vtop
->r2
, vtop
- 1);
6769 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
6770 vtop
->r
|= delayed_cast
;
6774 /* post defines POST/PRE add. c is the token ++ or -- */
6775 void inc(int post
, int c
)
6778 vdup(); /* save lvalue */
6780 gv_dup(); /* duplicate value */
6785 vpushi(c
- TOK_MID
);
6787 vstore(); /* store value */
6789 vpop(); /* if post op, return saved value */
6792 /* Parse GNUC __attribute__ extension. Currently, the following
6793 extensions are recognized:
6794 - aligned(n) : set data/function alignment.
6795 - packed : force data alignment to 1
6796 - section(x) : generate data/code in this section.
6797 - unused : currently ignored, but may be used someday.
6798 - regparm(n) : pass function parameters in registers (i386 only)
6800 static void parse_attribute(AttributeDef
*ad
)
6804 while (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
) {
6808 while (tok
!= ')') {
6809 if (tok
< TOK_IDENT
)
6810 expect("attribute name");
6818 expect("section name");
6819 ad
->section
= find_section(tcc_state
, (char *)tokc
.cstr
->data
);
6828 if (n
<= 0 || (n
& (n
- 1)) != 0)
6829 error("alignment must be a positive power of two");
6842 /* currently, no need to handle it because tcc does not
6843 track unused objects */
6847 /* currently, no need to handle it because tcc does not
6848 track unused objects */
6853 FUNC_CALL(ad
->func_attr
) = FUNC_CDECL
;
6858 FUNC_CALL(ad
->func_attr
) = FUNC_STDCALL
;
6860 #ifdef TCC_TARGET_I386
6870 FUNC_CALL(ad
->func_attr
) = FUNC_FASTCALL1
+ n
- 1;
6876 FUNC_CALL(ad
->func_attr
) = FUNC_FASTCALLW
;
6880 FUNC_EXPORT(ad
->func_attr
) = 1;
6883 if (tcc_state
->warn_unsupported
)
6884 warning("'%s' attribute ignored", get_tok_str(t
, NULL
));
6885 /* skip parameters */
6887 int parenthesis
= 0;
6891 else if (tok
== ')')
6894 } while (parenthesis
&& tok
!= -1);
6907 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
6908 static void struct_decl(CType
*type
, int u
)
6910 int a
, v
, size
, align
, maxalign
, c
, offset
;
6911 int bit_size
, bit_pos
, bsize
, bt
, lbit_pos
, prevbt
;
6912 Sym
*s
, *ss
, *ass
, **ps
;
6916 a
= tok
; /* save decl type */
6921 /* struct already defined ? return it */
6923 expect("struct/union/enum name");
6927 error("invalid type");
6934 /* we put an undefined size for struct/union */
6935 s
= sym_push(v
| SYM_STRUCT
, &type1
, 0, -1);
6936 s
->r
= 0; /* default alignment is zero as gcc */
6937 /* put struct/union/enum name in type */
6945 error("struct/union/enum already defined");
6946 /* cannot be empty */
6948 /* non empty enums are not allowed */
6949 if (a
== TOK_ENUM
) {
6953 expect("identifier");
6959 /* enum symbols have static storage */
6960 ss
= sym_push(v
, &int_type
, VT_CONST
, c
);
6961 ss
->type
.t
|= VT_STATIC
;
6966 /* NOTE: we accept a trailing comma */
6977 while (tok
!= '}') {
6978 parse_btype(&btype
, &ad
);
6984 type_decl(&type1
, &ad
, &v
, TYPE_DIRECT
| TYPE_ABSTRACT
);
6985 if (v
== 0 && (type1
.t
& VT_BTYPE
) != VT_STRUCT
)
6986 expect("identifier");
6987 if ((type1
.t
& VT_BTYPE
) == VT_FUNC
||
6988 (type1
.t
& (VT_TYPEDEF
| VT_STATIC
| VT_EXTERN
| VT_INLINE
)))
6989 error("invalid type for '%s'",
6990 get_tok_str(v
, NULL
));
6994 bit_size
= expr_const();
6995 /* XXX: handle v = 0 case for messages */
6997 error("negative width in bit-field '%s'",
6998 get_tok_str(v
, NULL
));
6999 if (v
&& bit_size
== 0)
7000 error("zero width for bit-field '%s'",
7001 get_tok_str(v
, NULL
));
7003 size
= type_size(&type1
, &align
);
7005 if (align
< ad
.aligned
)
7007 } else if (ad
.packed
) {
7009 } else if (*tcc_state
->pack_stack_ptr
) {
7010 if (align
> *tcc_state
->pack_stack_ptr
)
7011 align
= *tcc_state
->pack_stack_ptr
;
7014 if (bit_size
>= 0) {
7015 bt
= type1
.t
& VT_BTYPE
;
7022 error("bitfields must have scalar type");
7024 if (bit_size
> bsize
) {
7025 error("width of '%s' exceeds its type",
7026 get_tok_str(v
, NULL
));
7027 } else if (bit_size
== bsize
) {
7028 /* no need for bit fields */
7030 } else if (bit_size
== 0) {
7031 /* XXX: what to do if only padding in a
7033 /* zero size: means to pad */
7036 /* we do not have enough room ?
7037 did the type change?
7039 if ((bit_pos
+ bit_size
) > bsize
||
7040 bt
!= prevbt
|| a
== TOK_UNION
)
7043 /* XXX: handle LSB first */
7044 type1
.t
|= VT_BITFIELD
|
7045 (bit_pos
<< VT_STRUCT_SHIFT
) |
7046 (bit_size
<< (VT_STRUCT_SHIFT
+ 6));
7047 bit_pos
+= bit_size
;
7053 if (v
!= 0 || (type1
.t
& VT_BTYPE
) == VT_STRUCT
) {
7054 /* add new memory data only if starting
7056 if (lbit_pos
== 0) {
7057 if (a
== TOK_STRUCT
) {
7058 c
= (c
+ align
- 1) & -align
;
7067 if (align
> maxalign
)
7071 printf("add field %s offset=%d",
7072 get_tok_str(v
, NULL
), offset
);
7073 if (type1
.t
& VT_BITFIELD
) {
7074 printf(" pos=%d size=%d",
7075 (type1
.t
>> VT_STRUCT_SHIFT
) & 0x3f,
7076 (type1
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f);
7081 if (v
== 0 && (type1
.t
& VT_BTYPE
) == VT_STRUCT
) {
7083 while ((ass
= ass
->next
) != NULL
) {
7084 ss
= sym_push(ass
->v
, &ass
->type
, 0, offset
+ ass
->c
);
7089 ss
= sym_push(v
| SYM_FIELD
, &type1
, 0, offset
);
7093 if (tok
== ';' || tok
== TOK_EOF
)
7100 /* store size and alignment */
7101 s
->c
= (c
+ maxalign
- 1) & -maxalign
;
7107 /* return 0 if no type declaration. otherwise, return the basic type
7110 static int parse_btype(CType
*type
, AttributeDef
*ad
)
7112 int t
, u
, type_found
, typespec_found
, typedef_found
;
7116 memset(ad
, 0, sizeof(AttributeDef
));
7124 /* currently, we really ignore extension */
7134 if ((t
& VT_BTYPE
) != 0)
7135 error("too many basic types");
7151 if ((t
& VT_BTYPE
) == VT_DOUBLE
) {
7152 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
7153 } else if ((t
& VT_BTYPE
) == VT_LONG
) {
7154 t
= (t
& ~VT_BTYPE
) | VT_LLONG
;
7168 if ((t
& VT_BTYPE
) == VT_LONG
) {
7169 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
7176 struct_decl(&type1
, VT_ENUM
);
7179 type
->ref
= type1
.ref
;
7183 struct_decl(&type1
, VT_STRUCT
);
7186 /* type modifiers */
7239 /* GNUC attribute */
7240 case TOK_ATTRIBUTE1
:
7241 case TOK_ATTRIBUTE2
:
7242 parse_attribute(ad
);
7249 parse_expr_type(&type1
);
7252 if (typespec_found
|| typedef_found
)
7255 if (!s
|| !(s
->type
.t
& VT_TYPEDEF
))
7258 t
|= (s
->type
.t
& ~VT_TYPEDEF
);
7259 type
->ref
= s
->type
.ref
;
7267 if ((t
& (VT_SIGNED
|VT_UNSIGNED
)) == (VT_SIGNED
|VT_UNSIGNED
))
7268 error("signed and unsigned modifier");
7269 if (tcc_state
->char_is_unsigned
) {
7270 if ((t
& (VT_SIGNED
|VT_UNSIGNED
|VT_BTYPE
)) == VT_BYTE
)
7275 /* long is never used as type */
7276 if ((t
& VT_BTYPE
) == VT_LONG
)
7277 #ifndef TCC_TARGET_X86_64
7278 t
= (t
& ~VT_BTYPE
) | VT_INT
;
7280 t
= (t
& ~VT_BTYPE
) | VT_LLONG
;
7286 /* convert a function parameter type (array to pointer and function to
7287 function pointer) */
7288 static inline void convert_parameter_type(CType
*pt
)
7290 /* remove const and volatile qualifiers (XXX: const could be used
7291 to indicate a const function parameter */
7292 pt
->t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7293 /* array must be transformed to pointer according to ANSI C */
7295 if ((pt
->t
& VT_BTYPE
) == VT_FUNC
) {
7300 static void post_type(CType
*type
, AttributeDef
*ad
)
7302 int n
, l
, t1
, arg_size
, align
;
7303 Sym
**plast
, *s
, *first
;
7308 /* function declaration */
7316 /* read param name and compute offset */
7317 if (l
!= FUNC_OLD
) {
7318 if (!parse_btype(&pt
, &ad1
)) {
7320 error("invalid type");
7327 if ((pt
.t
& VT_BTYPE
) == VT_VOID
&& tok
== ')')
7329 type_decl(&pt
, &ad1
, &n
, TYPE_DIRECT
| TYPE_ABSTRACT
);
7330 if ((pt
.t
& VT_BTYPE
) == VT_VOID
)
7331 error("parameter declared as void");
7332 arg_size
+= (type_size(&pt
, &align
) + 3) & ~3;
7337 expect("identifier");
7341 convert_parameter_type(&pt
);
7342 s
= sym_push(n
| SYM_FIELD
, &pt
, 0, 0);
7348 if (l
== FUNC_NEW
&& tok
== TOK_DOTS
) {
7355 /* if no parameters, then old type prototype */
7359 t1
= type
->t
& VT_STORAGE
;
7360 /* NOTE: const is ignored in returned type as it has a special
7361 meaning in gcc / C++ */
7362 type
->t
&= ~(VT_STORAGE
| VT_CONSTANT
);
7363 post_type(type
, ad
);
7364 /* we push a anonymous symbol which will contain the function prototype */
7365 FUNC_ARGS(ad
->func_attr
) = arg_size
;
7366 s
= sym_push(SYM_FIELD
, type
, ad
->func_attr
, l
);
7368 type
->t
= t1
| VT_FUNC
;
7370 } else if (tok
== '[') {
7371 /* array definition */
7373 if (tok
== TOK_RESTRICT1
)
7379 error("invalid array size");
7382 /* parse next post type */
7383 t1
= type
->t
& VT_STORAGE
;
7384 type
->t
&= ~VT_STORAGE
;
7385 post_type(type
, ad
);
7387 /* we push a anonymous symbol which will contain the array
7389 s
= sym_push(SYM_FIELD
, type
, 0, n
);
7390 type
->t
= t1
| VT_ARRAY
| VT_PTR
;
7395 /* Parse a type declaration (except basic type), and return the type
7396 in 'type'. 'td' is a bitmask indicating which kind of type decl is
7397 expected. 'type' should contain the basic type. 'ad' is the
7398 attribute definition of the basic type. It can be modified by
7401 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
)
7404 CType type1
, *type2
;
7407 while (tok
== '*') {
7415 qualifiers
|= VT_CONSTANT
;
7420 qualifiers
|= VT_VOLATILE
;
7428 type
->t
|= qualifiers
;
7431 /* XXX: clarify attribute handling */
7432 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
7433 parse_attribute(ad
);
7435 /* recursive type */
7436 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
7437 type1
.t
= 0; /* XXX: same as int */
7440 /* XXX: this is not correct to modify 'ad' at this point, but
7441 the syntax is not clear */
7442 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
7443 parse_attribute(ad
);
7444 type_decl(&type1
, ad
, v
, td
);
7447 /* type identifier */
7448 if (tok
>= TOK_IDENT
&& (td
& TYPE_DIRECT
)) {
7452 if (!(td
& TYPE_ABSTRACT
))
7453 expect("identifier");
7457 post_type(type
, ad
);
7458 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
7459 parse_attribute(ad
);
7462 /* append type at the end of type1 */
7475 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
7476 static int lvalue_type(int t
)
7481 if (bt
== VT_BYTE
|| bt
== VT_BOOL
)
7483 else if (bt
== VT_SHORT
)
7487 if (t
& VT_UNSIGNED
)
7488 r
|= VT_LVAL_UNSIGNED
;
7492 /* indirection with full error checking and bound check */
7493 static void indir(void)
7495 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
) {
7496 if ((vtop
->type
.t
& VT_BTYPE
) == VT_FUNC
)
7500 if ((vtop
->r
& VT_LVAL
) && !nocode_wanted
)
7502 vtop
->type
= *pointed_type(&vtop
->type
);
7503 /* Arrays and functions are never lvalues */
7504 if (!(vtop
->type
.t
& VT_ARRAY
)
7505 && (vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
) {
7506 vtop
->r
|= lvalue_type(vtop
->type
.t
);
7507 /* if bound checking, the referenced pointer must be checked */
7508 if (do_bounds_check
)
7509 vtop
->r
|= VT_MUSTBOUND
;
7513 /* pass a parameter to a function and do type checking and casting */
7514 static void gfunc_param_typed(Sym
*func
, Sym
*arg
)
7519 func_type
= func
->c
;
7520 if (func_type
== FUNC_OLD
||
7521 (func_type
== FUNC_ELLIPSIS
&& arg
== NULL
)) {
7522 /* default casting : only need to convert float to double */
7523 if ((vtop
->type
.t
& VT_BTYPE
) == VT_FLOAT
) {
7527 } else if (arg
== NULL
) {
7528 error("too many arguments to function");
7531 type
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
7532 gen_assign_cast(&type
);
7536 /* parse an expression of the form '(type)' or '(expr)' and return its
7538 static void parse_expr_type(CType
*type
)
7544 if (parse_btype(type
, &ad
)) {
7545 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
7552 static void parse_type(CType
*type
)
7557 if (!parse_btype(type
, &ad
)) {
7560 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
7563 static void vpush_tokc(int t
)
7567 vsetc(&type
, VT_CONST
, &tokc
);
7570 static void unary(void)
7572 int n
, t
, align
, size
, r
;
7577 /* XXX: GCC 2.95.3 does not generate a table although it should be
7591 vpush_tokc(VT_INT
| VT_UNSIGNED
);
7595 vpush_tokc(VT_LLONG
);
7599 vpush_tokc(VT_LLONG
| VT_UNSIGNED
);
7603 vpush_tokc(VT_FLOAT
);
7607 vpush_tokc(VT_DOUBLE
);
7611 vpush_tokc(VT_LDOUBLE
);
7614 case TOK___FUNCTION__
:
7616 goto tok_identifier
;
7622 /* special function name identifier */
7623 len
= strlen(funcname
) + 1;
7624 /* generate char[len] type */
7629 vpush_ref(&type
, data_section
, data_section
->data_offset
, len
);
7630 ptr
= section_ptr_add(data_section
, len
);
7631 memcpy(ptr
, funcname
, len
);
7636 #ifdef TCC_TARGET_PE
7637 t
= VT_SHORT
| VT_UNSIGNED
;
7643 /* string parsing */
7646 if (tcc_state
->warn_write_strings
)
7651 memset(&ad
, 0, sizeof(AttributeDef
));
7652 decl_initializer_alloc(&type
, &ad
, VT_CONST
, 2, 0, 0);
7657 if (parse_btype(&type
, &ad
)) {
7658 type_decl(&type
, &ad
, &n
, TYPE_ABSTRACT
);
7660 /* check ISOC99 compound literal */
7662 /* data is allocated locally by default */
7667 /* all except arrays are lvalues */
7668 if (!(type
.t
& VT_ARRAY
))
7669 r
|= lvalue_type(type
.t
);
7670 memset(&ad
, 0, sizeof(AttributeDef
));
7671 decl_initializer_alloc(&type
, &ad
, r
, 1, 0, 0);
7676 } else if (tok
== '{') {
7677 /* save all registers */
7679 /* statement expression : we do not accept break/continue
7680 inside as GCC does */
7681 block(NULL
, NULL
, NULL
, NULL
, 0, 1);
7696 /* functions names must be treated as function pointers,
7697 except for unary '&' and sizeof. Since we consider that
7698 functions are not lvalues, we only have to handle it
7699 there and in function calls. */
7700 /* arrays can also be used although they are not lvalues */
7701 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
&&
7702 !(vtop
->type
.t
& VT_ARRAY
) && !(vtop
->type
.t
& VT_LLOCAL
))
7704 mk_pointer(&vtop
->type
);
7710 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) {
7712 boolean
.t
= VT_BOOL
;
7714 vtop
->c
.i
= !vtop
->c
.i
;
7715 } else if ((vtop
->r
& VT_VALMASK
) == VT_CMP
)
7716 vtop
->c
.i
= vtop
->c
.i
^ 1;
7719 vseti(VT_JMP
, gtst(1, 0));
7730 /* in order to force cast, we add zero */
7732 if ((vtop
->type
.t
& VT_BTYPE
) == VT_PTR
)
7733 error("pointer not accepted for unary plus");
7743 parse_expr_type(&type
);
7747 size
= type_size(&type
, &align
);
7748 if (t
== TOK_SIZEOF
) {
7750 error("sizeof applied to an incomplete type");
7755 vtop
->type
.t
|= VT_UNSIGNED
;
7758 case TOK_builtin_types_compatible_p
:
7767 type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7768 type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7769 vpushi(is_compatible_types(&type1
, &type2
));
7772 case TOK_builtin_constant_p
:
7774 int saved_nocode_wanted
, res
;
7777 saved_nocode_wanted
= nocode_wanted
;
7780 res
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
7782 nocode_wanted
= saved_nocode_wanted
;
7787 case TOK_builtin_frame_address
:
7792 if (tok
!= TOK_CINT
) {
7793 error("__builtin_frame_address only takes integers");
7796 error("TCC only supports __builtin_frame_address(0)");
7802 vset(&type
, VT_LOCAL
, 0);
7805 #ifdef TCC_TARGET_X86_64
7806 case TOK_builtin_malloc
:
7808 goto tok_identifier
;
7809 case TOK_builtin_free
:
7811 goto tok_identifier
;
7828 goto tok_identifier
;
7830 /* allow to take the address of a label */
7831 if (tok
< TOK_UIDENT
)
7832 expect("label identifier");
7833 s
= label_find(tok
);
7835 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
7837 if (s
->r
== LABEL_DECLARED
)
7838 s
->r
= LABEL_FORWARD
;
7841 s
->type
.t
= VT_VOID
;
7842 mk_pointer(&s
->type
);
7843 s
->type
.t
|= VT_STATIC
;
7845 vset(&s
->type
, VT_CONST
| VT_SYM
, 0);
7854 expect("identifier");
7858 error("'%s' undeclared", get_tok_str(t
, NULL
));
7859 /* for simple function calls, we tolerate undeclared
7860 external reference to int() function */
7861 if (tcc_state
->warn_implicit_function_declaration
)
7862 warning("implicit declaration of function '%s'",
7863 get_tok_str(t
, NULL
));
7864 s
= external_global_sym(t
, &func_old_type
, 0);
7866 if ((s
->type
.t
& (VT_STATIC
| VT_INLINE
| VT_BTYPE
)) ==
7867 (VT_STATIC
| VT_INLINE
| VT_FUNC
)) {
7868 /* if referencing an inline function, then we generate a
7869 symbol to it if not already done. It will have the
7870 effect to generate code for it at the end of the
7871 compilation unit. Inline function as always
7872 generated in the text section. */
7874 put_extern_sym(s
, text_section
, 0, 0);
7875 r
= VT_SYM
| VT_CONST
;
7879 vset(&s
->type
, r
, s
->c
);
7880 /* if forward reference, we must point to s */
7881 if (vtop
->r
& VT_SYM
) {
7888 /* post operations */
7890 if (tok
== TOK_INC
|| tok
== TOK_DEC
) {
7893 } else if (tok
== '.' || tok
== TOK_ARROW
) {
7895 if (tok
== TOK_ARROW
)
7900 /* expect pointer on structure */
7901 if ((vtop
->type
.t
& VT_BTYPE
) != VT_STRUCT
)
7902 expect("struct or union");
7906 while ((s
= s
->next
) != NULL
) {
7911 error("field not found: %s", get_tok_str(tok
& ~SYM_FIELD
, NULL
));
7912 /* add field offset to pointer */
7913 vtop
->type
= char_pointer_type
; /* change type to 'char *' */
7916 /* change type to field type, and set to lvalue */
7917 vtop
->type
= s
->type
;
7918 /* an array is never an lvalue */
7919 if (!(vtop
->type
.t
& VT_ARRAY
)) {
7920 vtop
->r
|= lvalue_type(vtop
->type
.t
);
7921 /* if bound checking, the referenced pointer must be checked */
7922 if (do_bounds_check
)
7923 vtop
->r
|= VT_MUSTBOUND
;
7926 } else if (tok
== '[') {
7932 } else if (tok
== '(') {
7938 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
) {
7939 /* pointer test (no array accepted) */
7940 if ((vtop
->type
.t
& (VT_BTYPE
| VT_ARRAY
)) == VT_PTR
) {
7941 vtop
->type
= *pointed_type(&vtop
->type
);
7942 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
)
7946 expect("function pointer");
7949 vtop
->r
&= ~VT_LVAL
; /* no lvalue */
7951 /* get return type */
7954 sa
= s
->next
; /* first parameter */
7957 /* compute first implicit argument if a structure is returned */
7958 if ((s
->type
.t
& VT_BTYPE
) == VT_STRUCT
) {
7959 /* get some space for the returned structure */
7960 size
= type_size(&s
->type
, &align
);
7961 loc
= (loc
- size
) & -align
;
7963 ret
.r
= VT_LOCAL
| VT_LVAL
;
7964 /* pass it as 'int' to avoid structure arg passing
7966 vseti(VT_LOCAL
, loc
);
7971 /* return in register */
7972 if (is_float(ret
.type
.t
)) {
7973 ret
.r
= reg_fret(ret
.type
.t
);
7975 if ((ret
.type
.t
& VT_BTYPE
) == VT_LLONG
)
7984 gfunc_param_typed(s
, sa
);
7994 error("too few arguments to function");
7996 if (!nocode_wanted
) {
7997 gfunc_call(nb_args
);
7999 vtop
-= (nb_args
+ 1);
8002 vsetc(&ret
.type
, ret
.r
, &ret
.c
);
8010 static void uneq(void)
8016 (tok
>= TOK_A_MOD
&& tok
<= TOK_A_DIV
) ||
8017 tok
== TOK_A_XOR
|| tok
== TOK_A_OR
||
8018 tok
== TOK_A_SHL
|| tok
== TOK_A_SAR
) {
8033 static void expr_prod(void)
8038 while (tok
== '*' || tok
== '/' || tok
== '%') {
8046 static void expr_sum(void)
8051 while (tok
== '+' || tok
== '-') {
8059 static void expr_shift(void)
8064 while (tok
== TOK_SHL
|| tok
== TOK_SAR
) {
8072 static void expr_cmp(void)
8077 while ((tok
>= TOK_ULE
&& tok
<= TOK_GT
) ||
8078 tok
== TOK_ULT
|| tok
== TOK_UGE
) {
8086 static void expr_cmpeq(void)
8091 while (tok
== TOK_EQ
|| tok
== TOK_NE
) {
8099 static void expr_and(void)
8102 while (tok
== '&') {
8109 static void expr_xor(void)
8112 while (tok
== '^') {
8119 static void expr_or(void)
8122 while (tok
== '|') {
8129 /* XXX: fix this mess */
8130 static void expr_land_const(void)
8133 while (tok
== TOK_LAND
) {
8140 /* XXX: fix this mess */
8141 static void expr_lor_const(void)
8144 while (tok
== TOK_LOR
) {
8151 /* only used if non constant */
8152 static void expr_land(void)
8157 if (tok
== TOK_LAND
) {
8162 if (tok
!= TOK_LAND
) {
8172 static void expr_lor(void)
8177 if (tok
== TOK_LOR
) {
8182 if (tok
!= TOK_LOR
) {
8192 /* XXX: better constant handling */
8193 static void expr_eq(void)
8195 int tt
, u
, r1
, r2
, rc
, t1
, t2
, bt1
, bt2
;
8197 CType type
, type1
, type2
;
8204 boolean
.t
= VT_BOOL
;
8210 if (tok
!= ':' || !gnu_ext
) {
8225 if (vtop
!= vstack
) {
8226 /* needed to avoid having different registers saved in
8228 if (is_float(vtop
->type
.t
)) {
8230 #ifdef TCC_TARGET_X86_64
8231 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LDOUBLE
) {
8241 if (tok
== ':' && gnu_ext
) {
8249 sv
= *vtop
; /* save value to handle it later */
8250 vtop
--; /* no vpop so that FP stack is not flushed */
8258 bt1
= t1
& VT_BTYPE
;
8260 bt2
= t2
& VT_BTYPE
;
8261 /* cast operands to correct type according to ISOC rules */
8262 if (is_float(bt1
) || is_float(bt2
)) {
8263 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
8264 type
.t
= VT_LDOUBLE
;
8265 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
8270 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
8271 /* cast to biggest op */
8273 /* convert to unsigned if it does not fit in a long long */
8274 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
8275 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
8276 type
.t
|= VT_UNSIGNED
;
8277 } else if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
8278 /* XXX: test pointer compatibility */
8280 } else if (bt1
== VT_FUNC
|| bt2
== VT_FUNC
) {
8281 /* XXX: test function pointer compatibility */
8283 } else if (bt1
== VT_STRUCT
|| bt2
== VT_STRUCT
) {
8284 /* XXX: test structure compatibility */
8286 } else if (bt1
== VT_VOID
|| bt2
== VT_VOID
) {
8287 /* NOTE: as an extension, we accept void on only one side */
8290 /* integer operations */
8292 /* convert to unsigned if it does not fit in an integer */
8293 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
8294 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
8295 type
.t
|= VT_UNSIGNED
;
8298 /* now we convert second operand */
8300 if (VT_STRUCT
== (vtop
->type
.t
& VT_BTYPE
))
8303 if (is_float(type
.t
)) {
8305 #ifdef TCC_TARGET_X86_64
8306 if ((type
.t
& VT_BTYPE
) == VT_LDOUBLE
) {
8310 } else if ((type
.t
& VT_BTYPE
) == VT_LLONG
) {
8311 /* for long longs, we use fixed registers to avoid having
8312 to handle a complicated move */
8317 /* this is horrible, but we must also convert first
8321 /* put again first value and cast it */
8324 if (VT_STRUCT
== (vtop
->type
.t
& VT_BTYPE
))
8334 static void gexpr(void)
8345 /* parse an expression and return its type without any side effect. */
8346 static void expr_type(CType
*type
)
8348 int saved_nocode_wanted
;
8350 saved_nocode_wanted
= nocode_wanted
;
8355 nocode_wanted
= saved_nocode_wanted
;
8358 /* parse a unary expression and return its type without any side
8360 static void unary_type(CType
*type
)
8372 /* parse a constant expression and return value in vtop. */
8373 static void expr_const1(void)
8382 /* parse an integer constant and return its value. */
8383 static int expr_const(void)
8387 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
8388 expect("constant expression");
8394 /* return the label token if current token is a label, otherwise
8396 static int is_label(void)
8400 /* fast test first */
8401 if (tok
< TOK_UIDENT
)
8403 /* no need to save tokc because tok is an identifier */
8410 unget_tok(last_tok
);
8415 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
8416 int case_reg
, int is_expr
)
8421 /* generate line number info */
8423 (last_line_num
!= file
->line_num
|| last_ind
!= ind
)) {
8424 put_stabn(N_SLINE
, 0, file
->line_num
, ind
- func_ind
);
8426 last_line_num
= file
->line_num
;
8430 /* default return value is (void) */
8432 vtop
->type
.t
= VT_VOID
;
8435 if (tok
== TOK_IF
) {
8442 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
8444 if (c
== TOK_ELSE
) {
8448 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
8449 gsym(d
); /* patch else jmp */
8452 } else if (tok
== TOK_WHILE
) {
8460 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
8464 } else if (tok
== '{') {
8468 /* record local declaration stack position */
8470 llabel
= local_label_stack
;
8471 /* handle local labels declarations */
8472 if (tok
== TOK_LABEL
) {
8475 if (tok
< TOK_UIDENT
)
8476 expect("label identifier");
8477 label_push(&local_label_stack
, tok
, LABEL_DECLARED
);
8487 while (tok
!= '}') {
8492 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
8495 /* pop locally defined labels */
8496 label_pop(&local_label_stack
, llabel
);
8497 /* pop locally defined symbols */
8499 /* XXX: this solution makes only valgrind happy...
8500 triggered by gcc.c-torture/execute/20000917-1.c */
8502 switch(vtop
->type
.t
& VT_BTYPE
) {
8507 for(p
=vtop
->type
.ref
;p
;p
=p
->prev
)
8509 error("unsupported expression type");
8512 sym_pop(&local_stack
, s
);
8514 } else if (tok
== TOK_RETURN
) {
8518 gen_assign_cast(&func_vt
);
8519 if ((func_vt
.t
& VT_BTYPE
) == VT_STRUCT
) {
8521 /* if returning structure, must copy it to implicit
8522 first pointer arg location */
8525 size
= type_size(&func_vt
,&align
);
8528 if((vtop
->r
!= (VT_LOCAL
| VT_LVAL
) || (vtop
->c
.i
& 3))
8532 loc
= (loc
- size
) & -4;
8535 vset(&type
, VT_LOCAL
| VT_LVAL
, addr
);
8538 vset(&int_type
, VT_LOCAL
| VT_LVAL
, addr
);
8540 vtop
->type
= int_type
;
8546 vset(&type
, VT_LOCAL
| VT_LVAL
, func_vc
);
8549 /* copy structure value to pointer */
8554 } else if (is_float(func_vt
.t
)) {
8555 gv(rc_fret(func_vt
.t
));
8559 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
8562 rsym
= gjmp(rsym
); /* jmp */
8563 } else if (tok
== TOK_BREAK
) {
8566 error("cannot break");
8567 *bsym
= gjmp(*bsym
);
8570 } else if (tok
== TOK_CONTINUE
) {
8573 error("cannot continue");
8574 *csym
= gjmp(*csym
);
8577 } else if (tok
== TOK_FOR
) {
8604 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
8609 if (tok
== TOK_DO
) {
8614 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
8625 if (tok
== TOK_SWITCH
) {
8629 /* XXX: other types than integer */
8630 case_reg
= gv(RC_INT
);
8634 b
= gjmp(0); /* jump to first case */
8636 block(&a
, csym
, &b
, &c
, case_reg
, 0);
8637 /* if no default, jmp after switch */
8645 if (tok
== TOK_CASE
) {
8652 if (gnu_ext
&& tok
== TOK_DOTS
) {
8656 warning("empty case range");
8658 /* since a case is like a label, we must skip it with a jmp */
8665 *case_sym
= gtst(1, 0);
8668 *case_sym
= gtst(1, 0);
8672 *case_sym
= gtst(1, *case_sym
);
8677 goto block_after_label
;
8679 if (tok
== TOK_DEFAULT
) {
8685 error("too many 'default'");
8688 goto block_after_label
;
8690 if (tok
== TOK_GOTO
) {
8692 if (tok
== '*' && gnu_ext
) {
8696 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
8699 } else if (tok
>= TOK_UIDENT
) {
8700 s
= label_find(tok
);
8701 /* put forward definition if needed */
8703 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
8705 if (s
->r
== LABEL_DECLARED
)
8706 s
->r
= LABEL_FORWARD
;
8708 /* label already defined */
8709 if (s
->r
& LABEL_FORWARD
)
8710 s
->next
= (void *)gjmp((long)s
->next
);
8712 gjmp_addr((long)s
->next
);
8715 expect("label identifier");
8718 } else if (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
) {
8726 if (s
->r
== LABEL_DEFINED
)
8727 error("duplicate label '%s'", get_tok_str(s
->v
, NULL
));
8728 gsym((long)s
->next
);
8729 s
->r
= LABEL_DEFINED
;
8731 s
= label_push(&global_label_stack
, b
, LABEL_DEFINED
);
8733 s
->next
= (void *)ind
;
8734 /* we accept this, but it is a mistake */
8737 warning("deprecated use of label at end of compound statement");
8741 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
8744 /* expression case */
8759 /* t is the array or struct type. c is the array or struct
8760 address. cur_index/cur_field is the pointer to the current
8761 value. 'size_only' is true if only size info is needed (only used
8763 static void decl_designator(CType
*type
, Section
*sec
, unsigned long c
,
8764 int *cur_index
, Sym
**cur_field
,
8768 int notfirst
, index
, index_last
, align
, l
, nb_elems
, elem_size
;
8774 if (gnu_ext
&& (l
= is_label()) != 0)
8776 while (tok
== '[' || tok
== '.') {
8778 if (!(type
->t
& VT_ARRAY
))
8779 expect("array type");
8782 index
= expr_const();
8783 if (index
< 0 || (s
->c
>= 0 && index
>= s
->c
))
8784 expect("invalid index");
8785 if (tok
== TOK_DOTS
&& gnu_ext
) {
8787 index_last
= expr_const();
8788 if (index_last
< 0 ||
8789 (s
->c
>= 0 && index_last
>= s
->c
) ||
8791 expect("invalid index");
8797 *cur_index
= index_last
;
8798 type
= pointed_type(type
);
8799 elem_size
= type_size(type
, &align
);
8800 c
+= index
* elem_size
;
8801 /* NOTE: we only support ranges for last designator */
8802 nb_elems
= index_last
- index
+ 1;
8803 if (nb_elems
!= 1) {
8812 if ((type
->t
& VT_BTYPE
) != VT_STRUCT
)
8813 expect("struct/union type");
8826 /* XXX: fix this mess by using explicit storage field */
8828 type1
.t
|= (type
->t
& ~VT_TYPE
);
8842 if (type
->t
& VT_ARRAY
) {
8844 type
= pointed_type(type
);
8845 c
+= index
* type_size(type
, &align
);
8849 error("too many field init");
8850 /* XXX: fix this mess by using explicit storage field */
8852 type1
.t
|= (type
->t
& ~VT_TYPE
);
8857 decl_initializer(type
, sec
, c
, 0, size_only
);
8859 /* XXX: make it more general */
8860 if (!size_only
&& nb_elems
> 1) {
8861 unsigned long c_end
;
8866 error("range init not supported yet for dynamic storage");
8867 c_end
= c
+ nb_elems
* elem_size
;
8868 if (c_end
> sec
->data_allocated
)
8869 section_realloc(sec
, c_end
);
8870 src
= sec
->data
+ c
;
8872 for(i
= 1; i
< nb_elems
; i
++) {
8874 memcpy(dst
, src
, elem_size
);
8880 #define EXPR_CONST 1
8883 /* store a value or an expression directly in global data or in local array */
8884 static void init_putv(CType
*type
, Section
*sec
, unsigned long c
,
8885 int v
, int expr_type
)
8887 int saved_global_expr
, bt
, bit_pos
, bit_size
;
8889 unsigned long long bit_mask
;
8897 /* compound literals must be allocated globally in this case */
8898 saved_global_expr
= global_expr
;
8901 global_expr
= saved_global_expr
;
8902 /* NOTE: symbols are accepted */
8903 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) != VT_CONST
)
8904 error("initializer element is not constant");
8912 dtype
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
8915 /* XXX: not portable */
8916 /* XXX: generate error if incorrect relocation */
8917 gen_assign_cast(&dtype
);
8918 bt
= type
->t
& VT_BTYPE
;
8919 /* we'll write at most 12 bytes */
8920 if (c
+ 12 > sec
->data_allocated
) {
8921 section_realloc(sec
, c
+ 12);
8923 ptr
= sec
->data
+ c
;
8924 /* XXX: make code faster ? */
8925 if (!(type
->t
& VT_BITFIELD
)) {
8930 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
8931 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
8932 bit_mask
= (1LL << bit_size
) - 1;
8934 if ((vtop
->r
& VT_SYM
) &&
8940 (bt
== VT_INT
&& bit_size
!= 32)))
8941 error("initializer element is not computable at load time");
8944 vtop
->c
.i
= (vtop
->c
.i
!= 0);
8946 *(char *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8949 *(short *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8952 *(double *)ptr
= vtop
->c
.d
;
8955 *(long double *)ptr
= vtop
->c
.ld
;
8958 *(long long *)ptr
|= (vtop
->c
.ll
& bit_mask
) << bit_pos
;
8961 if (vtop
->r
& VT_SYM
) {
8962 greloc(sec
, vtop
->sym
, c
, R_DATA_32
);
8964 *(int *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8969 vset(&dtype
, VT_LOCAL
|VT_LVAL
, c
);
8976 /* put zeros for variable based init */
8977 static void init_putz(CType
*t
, Section
*sec
, unsigned long c
, int size
)
8980 /* nothing to do because globals are already set to zero */
8982 vpush_global_sym(&func_old_type
, TOK_memset
);
8990 /* 't' contains the type and storage info. 'c' is the offset of the
8991 object in section 'sec'. If 'sec' is NULL, it means stack based
8992 allocation. 'first' is true if array '{' must be read (multi
8993 dimension implicit array init handling). 'size_only' is true if
8994 size only evaluation is wanted (only for arrays). */
8995 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
8996 int first
, int size_only
)
8998 int index
, array_length
, n
, no_oblock
, nb
, parlevel
, i
;
8999 int size1
, align1
, expr_type
;
9003 if (type
->t
& VT_ARRAY
) {
9007 t1
= pointed_type(type
);
9008 size1
= type_size(t1
, &align1
);
9011 if ((first
&& tok
!= TOK_LSTR
&& tok
!= TOK_STR
) ||
9017 /* only parse strings here if correct type (otherwise: handle
9018 them as ((w)char *) expressions */
9019 if ((tok
== TOK_LSTR
&&
9020 #ifdef TCC_TARGET_PE
9021 (t1
->t
& VT_BTYPE
) == VT_SHORT
&& (t1
->t
& VT_UNSIGNED
)
9023 (t1
->t
& VT_BTYPE
) == VT_INT
9025 ) || (tok
== TOK_STR
&& (t1
->t
& VT_BTYPE
) == VT_BYTE
)) {
9026 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
9031 /* compute maximum number of chars wanted */
9033 cstr_len
= cstr
->size
;
9035 cstr_len
= cstr
->size
/ sizeof(nwchar_t
);
9038 if (n
>= 0 && nb
> (n
- array_length
))
9039 nb
= n
- array_length
;
9042 warning("initializer-string for array is too long");
9043 /* in order to go faster for common case (char
9044 string in global variable, we handle it
9046 if (sec
&& tok
== TOK_STR
&& size1
== 1) {
9047 memcpy(sec
->data
+ c
+ array_length
, cstr
->data
, nb
);
9051 ch
= ((unsigned char *)cstr
->data
)[i
];
9053 ch
= ((nwchar_t
*)cstr
->data
)[i
];
9054 init_putv(t1
, sec
, c
+ (array_length
+ i
) * size1
,
9062 /* only add trailing zero if enough storage (no
9063 warning in this case since it is standard) */
9064 if (n
< 0 || array_length
< n
) {
9066 init_putv(t1
, sec
, c
+ (array_length
* size1
), 0, EXPR_VAL
);
9072 while (tok
!= '}') {
9073 decl_designator(type
, sec
, c
, &index
, NULL
, size_only
);
9074 if (n
>= 0 && index
>= n
)
9075 error("index too large");
9076 /* must put zero in holes (note that doing it that way
9077 ensures that it even works with designators) */
9078 if (!size_only
&& array_length
< index
) {
9079 init_putz(t1
, sec
, c
+ array_length
* size1
,
9080 (index
- array_length
) * size1
);
9083 if (index
> array_length
)
9084 array_length
= index
;
9085 /* special test for multi dimensional arrays (may not
9086 be strictly correct if designators are used at the
9088 if (index
>= n
&& no_oblock
)
9097 /* put zeros at the end */
9098 if (!size_only
&& n
>= 0 && array_length
< n
) {
9099 init_putz(t1
, sec
, c
+ array_length
* size1
,
9100 (n
- array_length
) * size1
);
9102 /* patch type size if needed */
9104 s
->c
= array_length
;
9105 } else if ((type
->t
& VT_BTYPE
) == VT_STRUCT
&&
9106 (sec
|| !first
|| tok
== '{')) {
9109 /* NOTE: the previous test is a specific case for automatic
9110 struct/union init */
9111 /* XXX: union needs only one init */
9113 /* XXX: this test is incorrect for local initializers
9114 beginning with ( without {. It would be much more difficult
9115 to do it correctly (ideally, the expression parser should
9116 be used in all cases) */
9122 while (tok
== '(') {
9126 if (!parse_btype(&type1
, &ad1
))
9128 type_decl(&type1
, &ad1
, &n
, TYPE_ABSTRACT
);
9130 if (!is_assignable_types(type
, &type1
))
9131 error("invalid type for cast");
9136 if (first
|| tok
== '{') {
9145 while (tok
!= '}') {
9146 decl_designator(type
, sec
, c
, NULL
, &f
, size_only
);
9148 if (!size_only
&& array_length
< index
) {
9149 init_putz(type
, sec
, c
+ array_length
,
9150 index
- array_length
);
9152 index
= index
+ type_size(&f
->type
, &align1
);
9153 if (index
> array_length
)
9154 array_length
= index
;
9156 if (no_oblock
&& f
== NULL
)
9162 /* put zeros at the end */
9163 if (!size_only
&& array_length
< n
) {
9164 init_putz(type
, sec
, c
+ array_length
,
9173 } else if (tok
== '{') {
9175 decl_initializer(type
, sec
, c
, first
, size_only
);
9177 } else if (size_only
) {
9178 /* just skip expression */
9180 while ((parlevel
> 0 || (tok
!= '}' && tok
!= ',')) &&
9184 else if (tok
== ')')
9189 /* currently, we always use constant expression for globals
9190 (may change for scripting case) */
9191 expr_type
= EXPR_CONST
;
9193 expr_type
= EXPR_ANY
;
9194 init_putv(type
, sec
, c
, 0, expr_type
);
9198 /* parse an initializer for type 't' if 'has_init' is non zero, and
9199 allocate space in local or global data space ('r' is either
9200 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
9201 variable 'v' of scope 'scope' is declared before initializers are
9202 parsed. If 'v' is zero, then a reference to the new object is put
9203 in the value stack. If 'has_init' is 2, a special parsing is done
9204 to handle string constants. */
9205 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
9206 int has_init
, int v
, int scope
)
9208 int size
, align
, addr
, data_offset
;
9210 ParseState saved_parse_state
;
9211 TokenString init_str
;
9214 size
= type_size(type
, &align
);
9215 /* If unknown size, we must evaluate it before
9216 evaluating initializers because
9217 initializers can generate global data too
9218 (e.g. string pointers or ISOC99 compound
9219 literals). It also simplifies local
9220 initializers handling */
9221 tok_str_new(&init_str
);
9224 error("unknown type size");
9225 /* get all init string */
9226 if (has_init
== 2) {
9227 /* only get strings */
9228 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
9229 tok_str_add_tok(&init_str
);
9234 while (level
> 0 || (tok
!= ',' && tok
!= ';')) {
9236 error("unexpected end of file in initializer");
9237 tok_str_add_tok(&init_str
);
9240 else if (tok
== '}') {
9250 tok_str_add(&init_str
, -1);
9251 tok_str_add(&init_str
, 0);
9254 save_parse_state(&saved_parse_state
);
9256 macro_ptr
= init_str
.str
;
9258 decl_initializer(type
, NULL
, 0, 1, 1);
9259 /* prepare second initializer parsing */
9260 macro_ptr
= init_str
.str
;
9263 /* if still unknown size, error */
9264 size
= type_size(type
, &align
);
9266 error("unknown type size");
9268 /* take into account specified alignment if bigger */
9270 if (ad
->aligned
> align
)
9271 align
= ad
->aligned
;
9272 } else if (ad
->packed
) {
9275 if ((r
& VT_VALMASK
) == VT_LOCAL
) {
9277 if (do_bounds_check
&& (type
->t
& VT_ARRAY
))
9279 loc
= (loc
- size
) & -align
;
9281 /* handles bounds */
9282 /* XXX: currently, since we do only one pass, we cannot track
9283 '&' operators, so we add only arrays */
9284 if (do_bounds_check
&& (type
->t
& VT_ARRAY
)) {
9285 unsigned long *bounds_ptr
;
9286 /* add padding between regions */
9288 /* then add local bound info */
9289 bounds_ptr
= section_ptr_add(lbounds_section
, 2 * sizeof(unsigned long));
9290 bounds_ptr
[0] = addr
;
9291 bounds_ptr
[1] = size
;
9294 /* local variable */
9295 sym_push(v
, type
, r
, addr
);
9297 /* push local reference */
9298 vset(type
, r
, addr
);
9304 if (v
&& scope
== VT_CONST
) {
9305 /* see if the symbol was already defined */
9308 if (!is_compatible_types(&sym
->type
, type
))
9309 error("incompatible types for redefinition of '%s'",
9310 get_tok_str(v
, NULL
));
9311 if (sym
->type
.t
& VT_EXTERN
) {
9312 /* if the variable is extern, it was not allocated */
9313 sym
->type
.t
&= ~VT_EXTERN
;
9314 /* set array size if it was ommited in extern
9316 if ((sym
->type
.t
& VT_ARRAY
) &&
9317 sym
->type
.ref
->c
< 0 &&
9319 sym
->type
.ref
->c
= type
->ref
->c
;
9321 /* we accept several definitions of the same
9322 global variable. this is tricky, because we
9323 must play with the SHN_COMMON type of the symbol */
9324 /* XXX: should check if the variable was already
9325 initialized. It is incorrect to initialized it
9327 /* no init data, we won't add more to the symbol */
9334 /* allocate symbol in corresponding section */
9339 else if (tcc_state
->nocommon
)
9343 data_offset
= sec
->data_offset
;
9344 data_offset
= (data_offset
+ align
- 1) & -align
;
9346 /* very important to increment global pointer at this time
9347 because initializers themselves can create new initializers */
9348 data_offset
+= size
;
9349 /* add padding if bound check */
9350 if (do_bounds_check
)
9352 sec
->data_offset
= data_offset
;
9353 /* allocate section space to put the data */
9354 if (sec
->sh_type
!= SHT_NOBITS
&&
9355 data_offset
> sec
->data_allocated
)
9356 section_realloc(sec
, data_offset
);
9357 /* align section if needed */
9358 if (align
> sec
->sh_addralign
)
9359 sec
->sh_addralign
= align
;
9361 addr
= 0; /* avoid warning */
9365 if (scope
!= VT_CONST
|| !sym
) {
9366 sym
= sym_push(v
, type
, r
| VT_SYM
, 0);
9368 /* update symbol definition */
9370 put_extern_sym(sym
, sec
, addr
, size
);
9373 /* put a common area */
9374 put_extern_sym(sym
, NULL
, align
, size
);
9375 /* XXX: find a nicer way */
9376 esym
= &((ElfW(Sym
) *)symtab_section
->data
)[sym
->c
];
9377 esym
->st_shndx
= SHN_COMMON
;
9382 /* push global reference */
9383 sym
= get_sym_ref(type
, sec
, addr
, size
);
9385 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
9389 /* handles bounds now because the symbol must be defined
9390 before for the relocation */
9391 if (do_bounds_check
) {
9392 unsigned long *bounds_ptr
;
9394 greloc(bounds_section
, sym
, bounds_section
->data_offset
, R_DATA_32
);
9395 /* then add global bound info */
9396 bounds_ptr
= section_ptr_add(bounds_section
, 2 * sizeof(long));
9397 bounds_ptr
[0] = 0; /* relocated */
9398 bounds_ptr
[1] = size
;
9402 decl_initializer(type
, sec
, addr
, 1, 0);
9403 /* restore parse state if needed */
9405 tok_str_free(init_str
.str
);
9406 restore_parse_state(&saved_parse_state
);
9412 void put_func_debug(Sym
*sym
)
9417 /* XXX: we put here a dummy type */
9418 snprintf(buf
, sizeof(buf
), "%s:%c1",
9419 funcname
, sym
->type
.t
& VT_STATIC
? 'f' : 'F');
9420 put_stabs_r(buf
, N_FUN
, 0, file
->line_num
, 0,
9421 cur_text_section
, sym
->c
);
9422 /* //gr gdb wants a line at the function */
9423 put_stabn(N_SLINE
, 0, file
->line_num
, 0);
9428 /* parse an old style function declaration list */
9429 /* XXX: check multiple parameter */
9430 static void func_decl_list(Sym
*func_sym
)
9437 /* parse each declaration */
9438 while (tok
!= '{' && tok
!= ';' && tok
!= ',' && tok
!= TOK_EOF
) {
9439 if (!parse_btype(&btype
, &ad
))
9440 expect("declaration list");
9441 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
9442 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
9444 /* we accept no variable after */
9448 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
9449 /* find parameter in function parameter list */
9452 if ((s
->v
& ~SYM_FIELD
) == v
)
9456 error("declaration for parameter '%s' but no such parameter",
9457 get_tok_str(v
, NULL
));
9459 /* check that no storage specifier except 'register' was given */
9460 if (type
.t
& VT_STORAGE
)
9461 error("storage class specified for '%s'", get_tok_str(v
, NULL
));
9462 convert_parameter_type(&type
);
9463 /* we can add the type (NOTE: it could be local to the function) */
9465 /* accept other parameters */
9476 /* parse a function defined by symbol 'sym' and generate its code in
9477 'cur_text_section' */
9478 static void gen_function(Sym
*sym
)
9480 int saved_nocode_wanted
= nocode_wanted
;
9482 ind
= cur_text_section
->data_offset
;
9483 /* NOTE: we patch the symbol size later */
9484 put_extern_sym(sym
, cur_text_section
, ind
, 0);
9485 funcname
= get_tok_str(sym
->v
, NULL
);
9487 /* put debug symbol */
9489 put_func_debug(sym
);
9490 /* push a dummy symbol to enable local sym storage */
9491 sym_push2(&local_stack
, SYM_FIELD
, 0, 0);
9492 gfunc_prolog(&sym
->type
);
9494 block(NULL
, NULL
, NULL
, NULL
, 0, 0);
9497 cur_text_section
->data_offset
= ind
;
9498 label_pop(&global_label_stack
, NULL
);
9499 sym_pop(&local_stack
, NULL
); /* reset local stack */
9500 /* end of function */
9501 /* patch symbol size */
9502 ((ElfW(Sym
) *)symtab_section
->data
)[sym
->c
].st_size
=
9505 put_stabn(N_FUN
, 0, 0, ind
- func_ind
);
9507 /* It's better to crash than to generate wrong code */
9508 cur_text_section
= NULL
;
9509 funcname
= ""; /* for safety */
9510 func_vt
.t
= VT_VOID
; /* for safety */
9511 ind
= 0; /* for safety */
9512 nocode_wanted
= saved_nocode_wanted
;
9515 static void gen_inline_functions(void)
9519 int *str
, inline_generated
;
9521 /* iterate while inline function are referenced */
9523 inline_generated
= 0;
9524 for(sym
= global_stack
; sym
!= NULL
; sym
= sym
->prev
) {
9526 if (((type
->t
& VT_BTYPE
) == VT_FUNC
) &&
9527 (type
->t
& (VT_STATIC
| VT_INLINE
)) ==
9528 (VT_STATIC
| VT_INLINE
) &&
9530 /* the function was used: generate its code and
9531 convert it to a normal function */
9532 str
= INLINE_DEF(sym
->r
);
9533 sym
->r
= VT_SYM
| VT_CONST
;
9534 sym
->type
.t
&= ~VT_INLINE
;
9538 cur_text_section
= text_section
;
9540 macro_ptr
= NULL
; /* fail safe */
9543 inline_generated
= 1;
9546 if (!inline_generated
)
9550 /* free all remaining inline function tokens */
9551 for(sym
= global_stack
; sym
!= NULL
; sym
= sym
->prev
) {
9553 if (((type
->t
& VT_BTYPE
) == VT_FUNC
) &&
9554 (type
->t
& (VT_STATIC
| VT_INLINE
)) ==
9555 (VT_STATIC
| VT_INLINE
)) {
9556 //gr printf("sym %d %s\n", sym->r, get_tok_str(sym->v, NULL));
9557 if (sym
->r
== (VT_SYM
| VT_CONST
)) //gr beware!
9559 str
= INLINE_DEF(sym
->r
);
9561 sym
->r
= 0; /* fail safe */
9566 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
9567 static void decl(int l
)
9575 if (!parse_btype(&btype
, &ad
)) {
9576 /* skip redundant ';' */
9577 /* XXX: find more elegant solution */
9582 if (l
== VT_CONST
&&
9583 (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
)) {
9584 /* global asm block */
9588 /* special test for old K&R protos without explicit int
9589 type. Only accepted when defining global data */
9590 if (l
== VT_LOCAL
|| tok
< TOK_DEFINE
)
9594 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
9595 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
9597 /* we accept no variable after */
9601 while (1) { /* iterate thru each declaration */
9603 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
9607 type_to_str(buf
, sizeof(buf
), t
, get_tok_str(v
, NULL
));
9608 printf("type = '%s'\n", buf
);
9611 if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
9612 /* if old style function prototype, we accept a
9615 if (sym
->c
== FUNC_OLD
)
9616 func_decl_list(sym
);
9621 error("cannot use local functions");
9622 if ((type
.t
& VT_BTYPE
) != VT_FUNC
)
9623 expect("function definition");
9625 /* reject abstract declarators in function definition */
9627 while ((sym
= sym
->next
) != NULL
)
9628 if (!(sym
->v
& ~SYM_FIELD
))
9629 expect("identifier");
9631 /* XXX: cannot do better now: convert extern line to static inline */
9632 if ((type
.t
& (VT_EXTERN
| VT_INLINE
)) == (VT_EXTERN
| VT_INLINE
))
9633 type
.t
= (type
.t
& ~VT_EXTERN
) | VT_STATIC
;
9637 if ((sym
->type
.t
& VT_BTYPE
) != VT_FUNC
)
9639 /* specific case: if not func_call defined, we put
9640 the one of the prototype */
9641 /* XXX: should have default value */
9642 r
= sym
->type
.ref
->r
;
9643 if (FUNC_CALL(r
) != FUNC_CDECL
9644 && FUNC_CALL(type
.ref
->r
) == FUNC_CDECL
)
9645 FUNC_CALL(type
.ref
->r
) = FUNC_CALL(r
);
9647 FUNC_EXPORT(type
.ref
->r
) = 1;
9649 if (!is_compatible_types(&sym
->type
, &type
)) {
9651 error("incompatible types for redefinition of '%s'",
9652 get_tok_str(v
, NULL
));
9654 /* if symbol is already defined, then put complete type */
9657 /* put function symbol */
9658 sym
= global_identifier_push(v
, type
.t
, 0);
9659 sym
->type
.ref
= type
.ref
;
9662 /* static inline functions are just recorded as a kind
9663 of macro. Their code will be emitted at the end of
9664 the compilation unit only if they are used */
9665 if ((type
.t
& (VT_INLINE
| VT_STATIC
)) ==
9666 (VT_INLINE
| VT_STATIC
)) {
9667 TokenString func_str
;
9670 tok_str_new(&func_str
);
9676 error("unexpected end of file");
9677 tok_str_add_tok(&func_str
);
9682 } else if (t
== '}') {
9684 if (block_level
== 0)
9688 tok_str_add(&func_str
, -1);
9689 tok_str_add(&func_str
, 0);
9690 INLINE_DEF(sym
->r
) = func_str
.str
;
9692 /* compute text section */
9693 cur_text_section
= ad
.section
;
9694 if (!cur_text_section
)
9695 cur_text_section
= text_section
;
9696 sym
->r
= VT_SYM
| VT_CONST
;
9701 if (btype
.t
& VT_TYPEDEF
) {
9702 /* save typedefed type */
9703 /* XXX: test storage specifiers ? */
9704 sym
= sym_push(v
, &type
, 0, 0);
9705 sym
->type
.t
|= VT_TYPEDEF
;
9706 } else if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
9707 /* external function definition */
9708 /* specific case for func_call attribute */
9710 type
.ref
->r
= ad
.func_attr
;
9711 external_sym(v
, &type
, 0);
9713 /* not lvalue if array */
9715 if (!(type
.t
& VT_ARRAY
))
9716 r
|= lvalue_type(type
.t
);
9717 has_init
= (tok
== '=');
9718 if ((btype
.t
& VT_EXTERN
) ||
9719 ((type
.t
& VT_ARRAY
) && (type
.t
& VT_STATIC
) &&
9720 !has_init
&& l
== VT_CONST
&& type
.ref
->c
< 0)) {
9721 /* external variable */
9722 /* NOTE: as GCC, uninitialized global static
9723 arrays of null size are considered as
9725 external_sym(v
, &type
, r
);
9727 type
.t
|= (btype
.t
& VT_STATIC
); /* Retain "static". */
9728 if (type
.t
& VT_STATIC
)
9734 decl_initializer_alloc(&type
, &ad
, r
,
9748 /* better than nothing, but needs extension to handle '-E' option
9750 static void preprocess_init(TCCState
*s1
)
9752 s1
->include_stack_ptr
= s1
->include_stack
;
9753 /* XXX: move that before to avoid having to initialize
9754 file->ifdef_stack_ptr ? */
9755 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
9756 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
9758 /* XXX: not ANSI compliant: bound checking says error */
9760 s1
->pack_stack
[0] = 0;
9761 s1
->pack_stack_ptr
= s1
->pack_stack
;
9764 /* compile the C file opened in 'file'. Return non zero if errors. */
9765 static int tcc_compile(TCCState
*s1
)
9769 volatile int section_sym
;
9772 printf("%s: **** new file\n", file
->filename
);
9774 preprocess_init(s1
);
9776 cur_text_section
= NULL
;
9778 anon_sym
= SYM_FIRST_ANOM
;
9780 /* file info: full path + filename */
9781 section_sym
= 0; /* avoid warning */
9783 section_sym
= put_elf_sym(symtab_section
, 0, 0,
9784 ELFW(ST_INFO
)(STB_LOCAL
, STT_SECTION
), 0,
9785 text_section
->sh_num
, NULL
);
9786 getcwd(buf
, sizeof(buf
));
9788 normalize_slashes(buf
);
9790 pstrcat(buf
, sizeof(buf
), "/");
9791 put_stabs_r(buf
, N_SO
, 0, 0,
9792 text_section
->data_offset
, text_section
, section_sym
);
9793 put_stabs_r(file
->filename
, N_SO
, 0, 0,
9794 text_section
->data_offset
, text_section
, section_sym
);
9796 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
9797 symbols can be safely used */
9798 put_elf_sym(symtab_section
, 0, 0,
9799 ELFW(ST_INFO
)(STB_LOCAL
, STT_FILE
), 0,
9800 SHN_ABS
, file
->filename
);
9802 /* define some often used types */
9803 int_type
.t
= VT_INT
;
9805 char_pointer_type
.t
= VT_BYTE
;
9806 mk_pointer(&char_pointer_type
);
9808 func_old_type
.t
= VT_FUNC
;
9809 func_old_type
.ref
= sym_push(SYM_FIELD
, &int_type
, FUNC_CDECL
, FUNC_OLD
);
9811 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
9812 float_type
.t
= VT_FLOAT
;
9813 double_type
.t
= VT_DOUBLE
;
9815 func_float_type
.t
= VT_FUNC
;
9816 func_float_type
.ref
= sym_push(SYM_FIELD
, &float_type
, FUNC_CDECL
, FUNC_OLD
);
9817 func_double_type
.t
= VT_FUNC
;
9818 func_double_type
.ref
= sym_push(SYM_FIELD
, &double_type
, FUNC_CDECL
, FUNC_OLD
);
9822 /* define 'void *alloca(unsigned int)' builtin function */
9827 sym
= sym_push(p
, mk_pointer(VT_VOID
), FUNC_CDECL
, FUNC_NEW
);
9828 s1
= sym_push(SYM_FIELD
, VT_UNSIGNED
| VT_INT
, 0, 0);
9831 sym_push(TOK_alloca
, VT_FUNC
| (p
<< VT_STRUCT_SHIFT
), VT_CONST
, 0);
9835 define_start
= define_stack
;
9838 if (setjmp(s1
->error_jmp_buf
) == 0) {
9840 s1
->error_set_jmp_enabled
= 1;
9842 ch
= file
->buf_ptr
[0];
9843 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
9844 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
;
9848 expect("declaration");
9850 /* end of translation unit info */
9852 put_stabs_r(NULL
, N_SO
, 0, 0,
9853 text_section
->data_offset
, text_section
, section_sym
);
9856 s1
->error_set_jmp_enabled
= 0;
9858 /* reset define stack, but leave -Dsymbols (may be incorrect if
9859 they are undefined) */
9860 free_defines(define_start
);
9862 gen_inline_functions();
9864 sym_pop(&global_stack
, NULL
);
9865 sym_pop(&local_stack
, NULL
);
9867 return s1
->nb_errors
!= 0 ? -1 : 0;
9870 /* Preprocess the current file */
9871 /* XXX: add line and file infos,
9872 * XXX: add options to preserve spaces (partly done, only spaces in macro are
9875 static int tcc_preprocess(TCCState
*s1
)
9878 BufferedFile
*file_ref
;
9879 int token_seen
, line_ref
;
9881 preprocess_init(s1
);
9882 define_start
= define_stack
;
9883 ch
= file
->buf_ptr
[0];
9885 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
9886 parse_flags
= PARSE_FLAG_ASM_COMMENTS
| PARSE_FLAG_PREPROCESS
|
9887 PARSE_FLAG_LINEFEED
;
9895 if (tok
== TOK_EOF
) {
9897 } else if (tok
== TOK_LINEFEED
) {
9902 } else if (token_seen
) {
9903 fwrite(tok_spaces
.data
, tok_spaces
.size
, 1, s1
->outfile
);
9905 int d
= file
->line_num
- line_ref
;
9906 if (file
!= file_ref
|| d
< 0 || d
>= 8)
9907 fprintf(s1
->outfile
, "# %d \"%s\"\n", file
->line_num
, file
->filename
);
9910 fputs("\n", s1
->outfile
), --d
;
9911 line_ref
= (file_ref
= file
)->line_num
;
9914 fputs(get_tok_str(tok
, &tokc
), s1
->outfile
);
9916 free_defines(define_start
);
9921 int tcc_compile_string(TCCState
*s
, const char *str
)
9923 BufferedFile bf1
, *bf
= &bf1
;
9927 /* init file structure */
9929 /* XXX: avoid copying */
9931 buf
= tcc_malloc(len
+ 1);
9934 memcpy(buf
, str
, len
);
9937 bf
->buf_end
= buf
+ len
;
9938 pstrcpy(bf
->filename
, sizeof(bf
->filename
), "<string>");
9941 ret
= tcc_compile(s
);
9945 /* currently, no need to close */
9950 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
9951 void tcc_define_symbol(TCCState
*s1
, const char *sym
, const char *value
)
9953 BufferedFile bf1
, *bf
= &bf1
;
9955 pstrcpy(bf
->buffer
, IO_BUF_SIZE
, sym
);
9956 pstrcat(bf
->buffer
, IO_BUF_SIZE
, " ");
9960 pstrcat(bf
->buffer
, IO_BUF_SIZE
, value
);
9962 /* init file structure */
9964 bf
->buf_ptr
= bf
->buffer
;
9965 bf
->buf_end
= bf
->buffer
+ strlen(bf
->buffer
);
9966 *bf
->buf_end
= CH_EOB
;
9967 bf
->filename
[0] = '\0';
9971 s1
->include_stack_ptr
= s1
->include_stack
;
9973 /* parse with define parser */
9974 ch
= file
->buf_ptr
[0];
9980 /* undefine a preprocessor symbol */
9981 void tcc_undefine_symbol(TCCState
*s1
, const char *sym
)
9985 ts
= tok_alloc(sym
, strlen(sym
));
9986 s
= define_find(ts
->tok
);
9987 /* undefine symbol by putting an invalid name */
9992 #ifdef CONFIG_TCC_ASM
9994 #ifdef TCC_TARGET_I386
9995 #include "i386-asm.c"
10000 static void asm_instr(void)
10002 error("inline asm() not supported");
10004 static void asm_global_instr(void)
10006 error("inline asm() not supported");
10010 #include "tccelf.c"
10012 #ifdef TCC_TARGET_COFF
10013 #include "tcccoff.c"
10016 #ifdef TCC_TARGET_PE
10020 /* print the position in the source file of PC value 'pc' by reading
10021 the stabs debug information */
10022 static void rt_printline(unsigned long wanted_pc
)
10024 Stab_Sym
*sym
, *sym_end
;
10025 char func_name
[128], last_func_name
[128];
10026 unsigned long func_addr
, last_pc
, pc
;
10027 const char *incl_files
[INCLUDE_STACK_SIZE
];
10028 int incl_index
, len
, last_line_num
, i
;
10029 const char *str
, *p
;
10031 fprintf(stderr
, "0x%08lx:", wanted_pc
);
10033 func_name
[0] = '\0';
10036 last_func_name
[0] = '\0';
10037 last_pc
= 0xffffffff;
10039 sym
= (Stab_Sym
*)stab_section
->data
+ 1;
10040 sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
10041 while (sym
< sym_end
) {
10042 switch(sym
->n_type
) {
10043 /* function start or end */
10045 if (sym
->n_strx
== 0) {
10046 /* we test if between last line and end of function */
10047 pc
= sym
->n_value
+ func_addr
;
10048 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
10050 func_name
[0] = '\0';
10053 str
= stabstr_section
->data
+ sym
->n_strx
;
10054 p
= strchr(str
, ':');
10056 pstrcpy(func_name
, sizeof(func_name
), str
);
10059 if (len
> sizeof(func_name
) - 1)
10060 len
= sizeof(func_name
) - 1;
10061 memcpy(func_name
, str
, len
);
10062 func_name
[len
] = '\0';
10064 func_addr
= sym
->n_value
;
10067 /* line number info */
10069 pc
= sym
->n_value
+ func_addr
;
10070 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
10073 last_line_num
= sym
->n_desc
;
10075 strcpy(last_func_name
, func_name
);
10077 /* include files */
10079 str
= stabstr_section
->data
+ sym
->n_strx
;
10081 if (incl_index
< INCLUDE_STACK_SIZE
) {
10082 incl_files
[incl_index
++] = str
;
10086 if (incl_index
> 1)
10090 if (sym
->n_strx
== 0) {
10091 incl_index
= 0; /* end of translation unit */
10093 str
= stabstr_section
->data
+ sym
->n_strx
;
10094 /* do not add path */
10096 if (len
> 0 && str
[len
- 1] != '/')
10104 /* second pass: we try symtab symbols (no line number info) */
10107 ElfW(Sym
) *sym
, *sym_end
;
10110 sym_end
= (ElfW(Sym
) *)(symtab_section
->data
+ symtab_section
->data_offset
);
10111 for(sym
= (ElfW(Sym
) *)symtab_section
->data
+ 1;
10114 type
= ELFW(ST_TYPE
)(sym
->st_info
);
10115 if (type
== STT_FUNC
) {
10116 if (wanted_pc
>= sym
->st_value
&&
10117 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
10118 pstrcpy(last_func_name
, sizeof(last_func_name
),
10119 strtab_section
->data
+ sym
->st_name
);
10125 /* did not find any info: */
10126 fprintf(stderr
, " ???\n");
10129 if (last_func_name
[0] != '\0') {
10130 fprintf(stderr
, " %s()", last_func_name
);
10132 if (incl_index
> 0) {
10133 fprintf(stderr
, " (%s:%d",
10134 incl_files
[incl_index
- 1], last_line_num
);
10135 for(i
= incl_index
- 2; i
>= 0; i
--)
10136 fprintf(stderr
, ", included from %s", incl_files
[i
]);
10137 fprintf(stderr
, ")");
10139 fprintf(stderr
, "\n");
10142 #if !defined(_WIN32) && !defined(CONFIG_TCCBOOT)
10146 /* fix for glibc 2.1 */
10148 #define REG_EIP EIP
10149 #define REG_EBP EBP
10152 /* return the PC at frame level 'level'. Return non zero if not found */
10153 static int rt_get_caller_pc(unsigned long *paddr
,
10154 ucontext_t
*uc
, int level
)
10160 #if defined(__FreeBSD__)
10161 *paddr
= uc
->uc_mcontext
.mc_eip
;
10162 #elif defined(__dietlibc__)
10163 *paddr
= uc
->uc_mcontext
.eip
;
10165 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
10169 #if defined(__FreeBSD__)
10170 fp
= uc
->uc_mcontext
.mc_ebp
;
10171 #elif defined(__dietlibc__)
10172 fp
= uc
->uc_mcontext
.ebp
;
10174 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
10176 for(i
=1;i
<level
;i
++) {
10177 /* XXX: check address validity with program info */
10178 if (fp
<= 0x1000 || fp
>= 0xc0000000)
10180 fp
= ((unsigned long *)fp
)[0];
10182 *paddr
= ((unsigned long *)fp
)[1];
10186 #elif defined(__x86_64__)
10187 /* return the PC at frame level 'level'. Return non zero if not found */
10188 static int rt_get_caller_pc(unsigned long *paddr
,
10189 ucontext_t
*uc
, int level
)
10195 /* XXX: only support linux */
10196 *paddr
= uc
->uc_mcontext
.gregs
[REG_RIP
];
10199 fp
= uc
->uc_mcontext
.gregs
[REG_RBP
];
10200 for(i
=1;i
<level
;i
++) {
10201 /* XXX: check address validity with program info */
10204 fp
= ((unsigned long *)fp
)[0];
10206 *paddr
= ((unsigned long *)fp
)[1];
10212 #warning add arch specific rt_get_caller_pc()
10214 static int rt_get_caller_pc(unsigned long *paddr
,
10215 ucontext_t
*uc
, int level
)
10221 /* emit a run time error at position 'pc' */
10222 void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
10229 fprintf(stderr
, "Runtime error: ");
10230 vfprintf(stderr
, fmt
, ap
);
10231 fprintf(stderr
, "\n");
10232 for(i
=0;i
<num_callers
;i
++) {
10233 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
10236 fprintf(stderr
, "at ");
10238 fprintf(stderr
, "by ");
10245 /* signal handler for fatal errors */
10246 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
10248 ucontext_t
*uc
= puc
;
10252 switch(siginf
->si_code
) {
10255 rt_error(uc
, "division by zero");
10258 rt_error(uc
, "floating point exception");
10264 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
10265 rt_error(uc
, *rt_bound_error_msg
);
10267 rt_error(uc
, "dereferencing invalid pointer");
10270 rt_error(uc
, "illegal instruction");
10273 rt_error(uc
, "abort() called");
10276 rt_error(uc
, "caught signal %d", signum
);
10283 /* copy code into memory passed in by the caller and do all relocations
10284 (needed before using tcc_get_symbol()).
10285 returns -1 on error and required size if ptr is NULL */
10286 int tcc_relocate(TCCState
*s1
, void *ptr
)
10289 unsigned long offset
, length
, mem
;
10294 if (0 == s1
->runtime_added
) {
10295 #ifdef TCC_TARGET_PE
10296 pe_add_runtime(s1
);
10297 relocate_common_syms();
10298 tcc_add_linker_symbols(s1
);
10300 tcc_add_runtime(s1
);
10301 relocate_common_syms();
10302 tcc_add_linker_symbols(s1
);
10303 build_got_entries(s1
);
10305 s1
->runtime_added
= 1;
10309 mem
= (unsigned long)ptr
;
10310 for(i
= 1; i
< s1
->nb_sections
; i
++) {
10311 s
= s1
->sections
[i
];
10312 if (0 == (s
->sh_flags
& SHF_ALLOC
))
10314 length
= s
->data_offset
;
10317 } else if (1 == mem
) {
10318 /* section are relocated in place.
10319 We also alloc the bss space */
10320 if (s
->sh_type
== SHT_NOBITS
)
10321 s
->data
= tcc_malloc(length
);
10322 s
->sh_addr
= (unsigned long)s
->data
;
10324 /* sections are relocated to new memory */
10325 s
->sh_addr
= (mem
+ offset
+ 15) & ~15;
10327 offset
= (offset
+ length
+ 15) & ~15;
10330 /* relocate symbols */
10331 relocate_syms(s1
, 1);
10336 return offset
+ 15;
10338 /* relocate each section */
10339 for(i
= 1; i
< s1
->nb_sections
; i
++) {
10340 s
= s1
->sections
[i
];
10342 relocate_section(s1
, s
);
10345 for(i
= 1; i
< s1
->nb_sections
; i
++) {
10346 s
= s1
->sections
[i
];
10347 if (0 == (s
->sh_flags
& SHF_ALLOC
))
10349 length
= s
->data_offset
;
10350 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
10351 ptr
= (void*)s
->sh_addr
;
10352 if (NULL
== s
->data
|| s
->sh_type
== SHT_NOBITS
)
10353 memset(ptr
, 0, length
);
10354 else if (ptr
!= s
->data
)
10355 memcpy(ptr
, s
->data
, length
);
10356 /* mark executable sections as executable in memory */
10357 if (s
->sh_flags
& SHF_EXECINSTR
)
10358 set_pages_executable(ptr
, length
);
10363 /* launch the compiled program with the given arguments */
10364 int tcc_run(TCCState
*s1
, int argc
, char **argv
)
10366 int (*prog_main
)(int, char **);
10370 ret
= tcc_relocate(s1
, NULL
);
10373 ptr
= tcc_malloc(ret
);
10374 tcc_relocate(s1
, ptr
);
10376 prog_main
= tcc_get_symbol_err(s1
, "main");
10379 #if defined(_WIN32) || defined(CONFIG_TCCBOOT)
10380 error("debug mode currently not available for Windows");
10382 struct sigaction sigact
;
10383 /* install TCC signal handlers to print debug info on fatal
10385 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
10386 sigact
.sa_sigaction
= sig_error
;
10387 sigemptyset(&sigact
.sa_mask
);
10388 sigaction(SIGFPE
, &sigact
, NULL
);
10389 sigaction(SIGILL
, &sigact
, NULL
);
10390 sigaction(SIGSEGV
, &sigact
, NULL
);
10391 sigaction(SIGBUS
, &sigact
, NULL
);
10392 sigaction(SIGABRT
, &sigact
, NULL
);
10396 #ifdef CONFIG_TCC_BCHECK
10397 if (do_bounds_check
) {
10398 void (*bound_init
)(void);
10400 /* set error function */
10401 rt_bound_error_msg
= (void *)tcc_get_symbol_err(s1
,
10402 "__bound_error_msg");
10404 /* XXX: use .init section so that it also work in binary ? */
10405 bound_init
= (void *)tcc_get_symbol_err(s1
, "__bound_init");
10409 ret
= (*prog_main
)(argc
, argv
);
10414 void tcc_memstats(void)
10417 printf("memory in use: %d\n", mem_cur_size
);
10421 static void tcc_cleanup(void)
10425 if (NULL
== tcc_state
)
10429 /* free -D defines */
10430 free_defines(NULL
);
10433 n
= tok_ident
- TOK_IDENT
;
10434 for(i
= 0; i
< n
; i
++)
10435 tcc_free(table_ident
[i
]);
10436 tcc_free(table_ident
);
10438 /* free sym_pools */
10439 dynarray_reset(&sym_pools
, &nb_sym_pools
);
10440 /* string buffer */
10441 cstr_free(&tokcstr
);
10442 /* reset symbol stack */
10443 sym_free_first
= NULL
;
10444 /* cleanup from error/setjmp */
10448 TCCState
*tcc_new(void)
10457 s
= tcc_mallocz(sizeof(TCCState
));
10461 s
->output_type
= TCC_OUTPUT_MEMORY
;
10463 /* init isid table */
10464 for(i
=CH_EOF
;i
<256;i
++)
10465 isidnum_table
[i
-CH_EOF
] = isid(i
) || isnum(i
);
10467 /* add all tokens */
10468 table_ident
= NULL
;
10469 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
10471 tok_ident
= TOK_IDENT
;
10480 ts
= tok_alloc(p
, r
- p
- 1);
10484 /* we add dummy defines for some special macros to speed up tests
10485 and to have working defined() */
10486 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
10487 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
10488 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
10489 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
10491 /* standard defines */
10492 tcc_define_symbol(s
, "__STDC__", NULL
);
10493 tcc_define_symbol(s
, "__STDC_VERSION__", "199901L");
10494 #if defined(TCC_TARGET_I386)
10495 tcc_define_symbol(s
, "__i386__", NULL
);
10497 #if defined(TCC_TARGET_X86_64)
10498 tcc_define_symbol(s
, "__x86_64__", NULL
);
10500 #if defined(TCC_TARGET_ARM)
10501 tcc_define_symbol(s
, "__ARM_ARCH_4__", NULL
);
10502 tcc_define_symbol(s
, "__arm_elf__", NULL
);
10503 tcc_define_symbol(s
, "__arm_elf", NULL
);
10504 tcc_define_symbol(s
, "arm_elf", NULL
);
10505 tcc_define_symbol(s
, "__arm__", NULL
);
10506 tcc_define_symbol(s
, "__arm", NULL
);
10507 tcc_define_symbol(s
, "arm", NULL
);
10508 tcc_define_symbol(s
, "__APCS_32__", NULL
);
10510 #ifdef TCC_TARGET_PE
10511 tcc_define_symbol(s
, "_WIN32", NULL
);
10513 tcc_define_symbol(s
, "__unix__", NULL
);
10514 tcc_define_symbol(s
, "__unix", NULL
);
10515 #if defined(__linux)
10516 tcc_define_symbol(s
, "__linux__", NULL
);
10517 tcc_define_symbol(s
, "__linux", NULL
);
10520 /* tiny C specific defines */
10521 tcc_define_symbol(s
, "__TINYC__", NULL
);
10523 /* tiny C & gcc defines */
10524 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned int");
10525 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "int");
10526 #ifdef TCC_TARGET_PE
10527 tcc_define_symbol(s
, "__WCHAR_TYPE__", "unsigned short");
10529 tcc_define_symbol(s
, "__WCHAR_TYPE__", "int");
10532 #ifndef TCC_TARGET_PE
10533 /* default library paths */
10534 tcc_add_library_path(s
, CONFIG_SYSROOT
"/usr/local/lib");
10535 tcc_add_library_path(s
, CONFIG_SYSROOT
"/usr/lib");
10536 tcc_add_library_path(s
, CONFIG_SYSROOT
"/lib");
10539 /* no section zero */
10540 dynarray_add((void ***)&s
->sections
, &s
->nb_sections
, NULL
);
10542 /* create standard sections */
10543 text_section
= new_section(s
, ".text", SHT_PROGBITS
, SHF_ALLOC
| SHF_EXECINSTR
);
10544 data_section
= new_section(s
, ".data", SHT_PROGBITS
, SHF_ALLOC
| SHF_WRITE
);
10545 bss_section
= new_section(s
, ".bss", SHT_NOBITS
, SHF_ALLOC
| SHF_WRITE
);
10547 /* symbols are always generated for linking stage */
10548 symtab_section
= new_symtab(s
, ".symtab", SHT_SYMTAB
, 0,
10550 ".hashtab", SHF_PRIVATE
);
10551 strtab_section
= symtab_section
->link
;
10553 /* private symbol table for dynamic symbols */
10554 s
->dynsymtab_section
= new_symtab(s
, ".dynsymtab", SHT_SYMTAB
, SHF_PRIVATE
,
10556 ".dynhashtab", SHF_PRIVATE
);
10557 s
->alacarte_link
= 1;
10559 #ifdef CHAR_IS_UNSIGNED
10560 s
->char_is_unsigned
= 1;
10562 #if defined(TCC_TARGET_PE) && 0
10563 /* XXX: currently the PE linker is not ready to support that */
10564 s
->leading_underscore
= 1;
10569 void tcc_delete(TCCState
*s1
)
10575 /* free all sections */
10576 for(i
= 1; i
< s1
->nb_sections
; i
++)
10577 free_section(s1
->sections
[i
]);
10578 dynarray_reset(&s1
->sections
, &s1
->nb_sections
);
10580 for(i
= 0; i
< s1
->nb_priv_sections
; i
++)
10581 free_section(s1
->priv_sections
[i
]);
10582 dynarray_reset(&s1
->priv_sections
, &s1
->nb_priv_sections
);
10584 /* free any loaded DLLs */
10585 for ( i
= 0; i
< s1
->nb_loaded_dlls
; i
++) {
10586 DLLReference
*ref
= s1
->loaded_dlls
[i
];
10588 dlclose(ref
->handle
);
10591 /* free loaded dlls array */
10592 dynarray_reset(&s1
->loaded_dlls
, &s1
->nb_loaded_dlls
);
10594 /* free library paths */
10595 dynarray_reset(&s1
->library_paths
, &s1
->nb_library_paths
);
10597 /* free include paths */
10598 dynarray_reset(&s1
->cached_includes
, &s1
->nb_cached_includes
);
10599 dynarray_reset(&s1
->include_paths
, &s1
->nb_include_paths
);
10600 dynarray_reset(&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
);
10605 int tcc_add_include_path(TCCState
*s1
, const char *pathname
)
10609 pathname1
= tcc_strdup(pathname
);
10610 dynarray_add((void ***)&s1
->include_paths
, &s1
->nb_include_paths
, pathname1
);
10614 int tcc_add_sysinclude_path(TCCState
*s1
, const char *pathname
)
10618 pathname1
= tcc_strdup(pathname
);
10619 dynarray_add((void ***)&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
, pathname1
);
10623 static int tcc_add_file_internal(TCCState
*s1
, const char *filename
, int flags
)
10628 BufferedFile
*saved_file
;
10630 /* find source file type with extension */
10631 ext
= tcc_fileextension(filename
);
10635 /* open the file */
10637 file
= tcc_open(s1
, filename
);
10639 if (flags
& AFF_PRINT_ERROR
) {
10640 error_noabort("file '%s' not found", filename
);
10646 if (flags
& AFF_PREPROCESS
) {
10647 ret
= tcc_preprocess(s1
);
10648 } else if (!ext
[0] || !PATHCMP(ext
, "c")) {
10649 /* C file assumed */
10650 ret
= tcc_compile(s1
);
10652 #ifdef CONFIG_TCC_ASM
10653 if (!strcmp(ext
, "S")) {
10654 /* preprocessed assembler */
10655 ret
= tcc_assemble(s1
, 1);
10656 } else if (!strcmp(ext
, "s")) {
10657 /* non preprocessed assembler */
10658 ret
= tcc_assemble(s1
, 0);
10661 #ifdef TCC_TARGET_PE
10662 if (!PATHCMP(ext
, "def")) {
10663 ret
= pe_load_def_file(s1
, file
->fd
);
10668 /* assume executable format: auto guess file type */
10669 ret
= read(fd
, &ehdr
, sizeof(ehdr
));
10670 lseek(fd
, 0, SEEK_SET
);
10672 error_noabort("could not read header");
10674 } else if (ret
!= sizeof(ehdr
)) {
10675 goto try_load_script
;
10678 if (ehdr
.e_ident
[0] == ELFMAG0
&&
10679 ehdr
.e_ident
[1] == ELFMAG1
&&
10680 ehdr
.e_ident
[2] == ELFMAG2
&&
10681 ehdr
.e_ident
[3] == ELFMAG3
) {
10682 file
->line_num
= 0; /* do not display line number if error */
10683 if (ehdr
.e_type
== ET_REL
) {
10684 ret
= tcc_load_object_file(s1
, fd
, 0);
10685 } else if (ehdr
.e_type
== ET_DYN
) {
10686 if (s1
->output_type
== TCC_OUTPUT_MEMORY
) {
10687 #ifdef TCC_TARGET_PE
10691 h
= dlopen(filename
, RTLD_GLOBAL
| RTLD_LAZY
);
10698 ret
= tcc_load_dll(s1
, fd
, filename
,
10699 (flags
& AFF_REFERENCED_DLL
) != 0);
10702 error_noabort("unrecognized ELF file");
10705 } else if (memcmp((char *)&ehdr
, ARMAG
, 8) == 0) {
10706 file
->line_num
= 0; /* do not display line number if error */
10707 ret
= tcc_load_archive(s1
, fd
);
10709 #ifdef TCC_TARGET_COFF
10710 if (*(uint16_t *)(&ehdr
) == COFF_C67_MAGIC
) {
10711 ret
= tcc_load_coff(s1
, fd
);
10714 #ifdef TCC_TARGET_PE
10715 if (pe_test_res_file(&ehdr
, ret
)) {
10716 ret
= pe_load_res_file(s1
, fd
);
10720 /* as GNU ld, consider it is an ld script if not recognized */
10722 ret
= tcc_load_ldscript(s1
);
10724 error_noabort("unrecognized file type");
10739 int tcc_add_file(TCCState
*s
, const char *filename
)
10741 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
);
10744 int tcc_add_library_path(TCCState
*s
, const char *pathname
)
10748 pathname1
= tcc_strdup(pathname
);
10749 dynarray_add((void ***)&s
->library_paths
, &s
->nb_library_paths
, pathname1
);
10753 /* find and load a dll. Return non zero if not found */
10754 /* XXX: add '-rpath' option support ? */
10755 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
)
10760 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
10761 snprintf(buf
, sizeof(buf
), "%s/%s",
10762 s
->library_paths
[i
], filename
);
10763 if (tcc_add_file_internal(s
, buf
, flags
) == 0)
10769 /* the library name is the same as the argument of the '-l' option */
10770 int tcc_add_library(TCCState
*s
, const char *libraryname
)
10775 /* first we look for the dynamic library if not static linking */
10776 if (!s
->static_link
) {
10777 #ifdef TCC_TARGET_PE
10778 snprintf(buf
, sizeof(buf
), "%s.def", libraryname
);
10780 snprintf(buf
, sizeof(buf
), "lib%s.so", libraryname
);
10782 if (tcc_add_dll(s
, buf
, 0) == 0)
10786 /* then we look for the static library */
10787 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
10788 snprintf(buf
, sizeof(buf
), "%s/lib%s.a",
10789 s
->library_paths
[i
], libraryname
);
10790 if (tcc_add_file_internal(s
, buf
, 0) == 0)
10796 int tcc_add_symbol(TCCState
*s
, const char *name
, unsigned long val
)
10798 add_elf_sym(symtab_section
, val
, 0,
10799 ELFW(ST_INFO
)(STB_GLOBAL
, STT_NOTYPE
), 0,
10804 int tcc_set_output_type(TCCState
*s
, int output_type
)
10808 s
->output_type
= output_type
;
10810 if (!s
->nostdinc
) {
10811 /* default include paths */
10812 /* XXX: reverse order needed if -isystem support */
10813 #ifndef TCC_TARGET_PE
10814 tcc_add_sysinclude_path(s
, CONFIG_SYSROOT
"/usr/local/include");
10815 tcc_add_sysinclude_path(s
, CONFIG_SYSROOT
"/usr/include");
10817 snprintf(buf
, sizeof(buf
), "%s/include", tcc_lib_path
);
10818 tcc_add_sysinclude_path(s
, buf
);
10819 #ifdef TCC_TARGET_PE
10820 snprintf(buf
, sizeof(buf
), "%s/include/winapi", tcc_lib_path
);
10821 tcc_add_sysinclude_path(s
, buf
);
10825 /* if bound checking, then add corresponding sections */
10826 #ifdef CONFIG_TCC_BCHECK
10827 if (do_bounds_check
) {
10828 /* define symbol */
10829 tcc_define_symbol(s
, "__BOUNDS_CHECKING_ON", NULL
);
10830 /* create bounds sections */
10831 bounds_section
= new_section(s
, ".bounds",
10832 SHT_PROGBITS
, SHF_ALLOC
);
10833 lbounds_section
= new_section(s
, ".lbounds",
10834 SHT_PROGBITS
, SHF_ALLOC
);
10838 if (s
->char_is_unsigned
) {
10839 tcc_define_symbol(s
, "__CHAR_UNSIGNED__", NULL
);
10842 /* add debug sections */
10845 stab_section
= new_section(s
, ".stab", SHT_PROGBITS
, 0);
10846 stab_section
->sh_entsize
= sizeof(Stab_Sym
);
10847 stabstr_section
= new_section(s
, ".stabstr", SHT_STRTAB
, 0);
10848 put_elf_str(stabstr_section
, "");
10849 stab_section
->link
= stabstr_section
;
10850 /* put first entry */
10851 put_stabs("", 0, 0, 0, 0);
10854 /* add libc crt1/crti objects */
10855 #ifndef TCC_TARGET_PE
10856 if ((output_type
== TCC_OUTPUT_EXE
|| output_type
== TCC_OUTPUT_DLL
) &&
10858 if (output_type
!= TCC_OUTPUT_DLL
)
10859 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crt1.o");
10860 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crti.o");
10864 #ifdef TCC_TARGET_PE
10865 snprintf(buf
, sizeof(buf
), "%s/lib", tcc_lib_path
);
10866 tcc_add_library_path(s
, buf
);
10872 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
10873 #define FD_INVERT 0x0002 /* invert value before storing */
10875 typedef struct FlagDef
{
10881 static const FlagDef warning_defs
[] = {
10882 { offsetof(TCCState
, warn_unsupported
), 0, "unsupported" },
10883 { offsetof(TCCState
, warn_write_strings
), 0, "write-strings" },
10884 { offsetof(TCCState
, warn_error
), 0, "error" },
10885 { offsetof(TCCState
, warn_implicit_function_declaration
), WD_ALL
,
10886 "implicit-function-declaration" },
10889 static int set_flag(TCCState
*s
, const FlagDef
*flags
, int nb_flags
,
10890 const char *name
, int value
)
10897 if (r
[0] == 'n' && r
[1] == 'o' && r
[2] == '-') {
10901 for(i
= 0, p
= flags
; i
< nb_flags
; i
++, p
++) {
10902 if (!strcmp(r
, p
->name
))
10907 if (p
->flags
& FD_INVERT
)
10909 *(int *)((uint8_t *)s
+ p
->offset
) = value
;
10914 /* set/reset a warning */
10915 int tcc_set_warning(TCCState
*s
, const char *warning_name
, int value
)
10920 if (!strcmp(warning_name
, "all")) {
10921 for(i
= 0, p
= warning_defs
; i
< countof(warning_defs
); i
++, p
++) {
10922 if (p
->flags
& WD_ALL
)
10923 *(int *)((uint8_t *)s
+ p
->offset
) = 1;
10927 return set_flag(s
, warning_defs
, countof(warning_defs
),
10928 warning_name
, value
);
10932 static const FlagDef flag_defs
[] = {
10933 { offsetof(TCCState
, char_is_unsigned
), 0, "unsigned-char" },
10934 { offsetof(TCCState
, char_is_unsigned
), FD_INVERT
, "signed-char" },
10935 { offsetof(TCCState
, nocommon
), FD_INVERT
, "common" },
10936 { offsetof(TCCState
, leading_underscore
), 0, "leading-underscore" },
10939 /* set/reset a flag */
10940 int tcc_set_flag(TCCState
*s
, const char *flag_name
, int value
)
10942 return set_flag(s
, flag_defs
, countof(flag_defs
),
10946 #if !defined(LIBTCC)
10948 static int64_t getclock_us(void)
10953 return (tb
.time
* 1000LL + tb
.millitm
) * 1000LL;
10956 gettimeofday(&tv
, NULL
);
10957 return tv
.tv_sec
* 1000000LL + tv
.tv_usec
;
10963 printf("tcc version " TCC_VERSION
" - Tiny C Compiler - Copyright (C) 2001-2006 Fabrice Bellard\n"
10964 "usage: tcc [-v] [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"
10965 " [-Wwarn] [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-soname name]\n"
10966 " [-static] [infile1 infile2...] [-run infile args...]\n"
10968 "General options:\n"
10969 " -v display current version, increase verbosity\n"
10970 " -c compile only - generate an object file\n"
10971 " -o outfile set output filename\n"
10972 " -Bdir set tcc internal library path\n"
10973 " -bench output compilation statistics\n"
10974 " -run run compiled source\n"
10975 " -fflag set or reset (with 'no-' prefix) 'flag' (see man page)\n"
10976 " -Wwarning set or reset (with 'no-' prefix) 'warning' (see man page)\n"
10977 " -w disable all warnings\n"
10978 "Preprocessor options:\n"
10979 " -E preprocess only\n"
10980 " -Idir add include path 'dir'\n"
10981 " -Dsym[=val] define 'sym' with value 'val'\n"
10982 " -Usym undefine 'sym'\n"
10983 "Linker options:\n"
10984 " -Ldir add library path 'dir'\n"
10985 " -llib link with dynamic or static library 'lib'\n"
10986 " -shared generate a shared library\n"
10987 " -soname set name for shared library to be used at runtime\n"
10988 " -static static linking\n"
10989 " -rdynamic export all global symbols to dynamic linker\n"
10990 " -r generate (relocatable) object file\n"
10991 "Debugger options:\n"
10992 " -g generate runtime debug info\n"
10993 #ifdef CONFIG_TCC_BCHECK
10994 " -b compile with built-in memory and bounds checker (implies -g)\n"
10996 " -bt N show N callers in stack traces\n"
11000 #define TCC_OPTION_HAS_ARG 0x0001
11001 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
11003 typedef struct TCCOption
{
11032 TCC_OPTION_nostdinc
,
11033 TCC_OPTION_nostdlib
,
11034 TCC_OPTION_print_search_dirs
,
11035 TCC_OPTION_rdynamic
,
11043 static const TCCOption tcc_options
[] = {
11044 { "h", TCC_OPTION_HELP
, 0 },
11045 { "?", TCC_OPTION_HELP
, 0 },
11046 { "I", TCC_OPTION_I
, TCC_OPTION_HAS_ARG
},
11047 { "D", TCC_OPTION_D
, TCC_OPTION_HAS_ARG
},
11048 { "U", TCC_OPTION_U
, TCC_OPTION_HAS_ARG
},
11049 { "L", TCC_OPTION_L
, TCC_OPTION_HAS_ARG
},
11050 { "B", TCC_OPTION_B
, TCC_OPTION_HAS_ARG
},
11051 { "l", TCC_OPTION_l
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11052 { "bench", TCC_OPTION_bench
, 0 },
11053 { "bt", TCC_OPTION_bt
, TCC_OPTION_HAS_ARG
},
11054 #ifdef CONFIG_TCC_BCHECK
11055 { "b", TCC_OPTION_b
, 0 },
11057 { "g", TCC_OPTION_g
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11058 { "c", TCC_OPTION_c
, 0 },
11059 { "static", TCC_OPTION_static
, 0 },
11060 { "shared", TCC_OPTION_shared
, 0 },
11061 { "soname", TCC_OPTION_soname
, TCC_OPTION_HAS_ARG
},
11062 { "o", TCC_OPTION_o
, TCC_OPTION_HAS_ARG
},
11063 { "run", TCC_OPTION_run
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11064 { "rdynamic", TCC_OPTION_rdynamic
, 0 },
11065 { "r", TCC_OPTION_r
, 0 },
11066 { "Wl,", TCC_OPTION_Wl
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11067 { "W", TCC_OPTION_W
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11068 { "O", TCC_OPTION_O
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11069 { "m", TCC_OPTION_m
, TCC_OPTION_HAS_ARG
},
11070 { "f", TCC_OPTION_f
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11071 { "nostdinc", TCC_OPTION_nostdinc
, 0 },
11072 { "nostdlib", TCC_OPTION_nostdlib
, 0 },
11073 { "print-search-dirs", TCC_OPTION_print_search_dirs
, 0 },
11074 { "v", TCC_OPTION_v
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11075 { "w", TCC_OPTION_w
, 0 },
11076 { "pipe", TCC_OPTION_pipe
, 0},
11077 { "E", TCC_OPTION_E
, 0},
11081 /* convert 'str' into an array of space separated strings */
11082 static int expand_args(char ***pargv
, const char *str
)
11091 while (is_space(*str
))
11096 while (*str
!= '\0' && !is_space(*str
))
11099 arg
= tcc_malloc(len
+ 1);
11100 memcpy(arg
, s1
, len
);
11102 dynarray_add((void ***)&argv
, &argc
, arg
);
11108 static char **files
;
11109 static int nb_files
, nb_libraries
;
11110 static int multiple_files
;
11111 static int print_search_dirs
;
11112 static int output_type
;
11113 static int reloc_output
;
11114 static const char *outfile
;
11116 int parse_args(TCCState
*s
, int argc
, char **argv
)
11119 const TCCOption
*popt
;
11120 const char *optarg
, *p1
, *r1
;
11124 while (optind
< argc
) {
11126 r
= argv
[optind
++];
11127 if (r
[0] != '-' || r
[1] == '\0') {
11128 /* add a new file */
11129 dynarray_add((void ***)&files
, &nb_files
, r
);
11130 if (!multiple_files
) {
11132 /* argv[0] will be this file */
11136 /* find option in table (match only the first chars */
11137 popt
= tcc_options
;
11141 error("invalid option -- '%s'", r
);
11154 if (popt
->flags
& TCC_OPTION_HAS_ARG
) {
11155 if (*r1
!= '\0' || (popt
->flags
& TCC_OPTION_NOSEP
)) {
11158 if (optind
>= argc
)
11159 error("argument to '%s' is missing", r
);
11160 optarg
= argv
[optind
++];
11168 switch(popt
->index
) {
11169 case TCC_OPTION_HELP
:
11173 if (tcc_add_include_path(s
, optarg
) < 0)
11174 error("too many include paths");
11179 sym
= (char *)optarg
;
11180 value
= strchr(sym
, '=');
11185 tcc_define_symbol(s
, sym
, value
);
11189 tcc_undefine_symbol(s
, optarg
);
11192 tcc_add_library_path(s
, optarg
);
11195 /* set tcc utilities path (mainly for tcc development) */
11196 tcc_lib_path
= optarg
;
11199 dynarray_add((void ***)&files
, &nb_files
, r
);
11202 case TCC_OPTION_bench
:
11205 case TCC_OPTION_bt
:
11206 num_callers
= atoi(optarg
);
11208 #ifdef CONFIG_TCC_BCHECK
11210 do_bounds_check
= 1;
11218 multiple_files
= 1;
11219 output_type
= TCC_OUTPUT_OBJ
;
11221 case TCC_OPTION_static
:
11222 s
->static_link
= 1;
11224 case TCC_OPTION_shared
:
11225 output_type
= TCC_OUTPUT_DLL
;
11227 case TCC_OPTION_soname
:
11228 s
->soname
= optarg
;
11231 multiple_files
= 1;
11235 /* generate a .o merging several output files */
11237 output_type
= TCC_OUTPUT_OBJ
;
11239 case TCC_OPTION_nostdinc
:
11242 case TCC_OPTION_nostdlib
:
11245 case TCC_OPTION_print_search_dirs
:
11246 print_search_dirs
= 1;
11248 case TCC_OPTION_run
:
11252 argc1
= expand_args(&argv1
, optarg
);
11254 parse_args(s
, argc1
, argv1
);
11256 multiple_files
= 0;
11257 output_type
= TCC_OUTPUT_MEMORY
;
11262 if (0 == verbose
++)
11263 printf("tcc version %s\n", TCC_VERSION
);
11264 } while (*optarg
++ == 'v');
11267 if (tcc_set_flag(s
, optarg
, 1) < 0 && s
->warn_unsupported
)
11268 goto unsupported_option
;
11271 if (tcc_set_warning(s
, optarg
, 1) < 0 &&
11272 s
->warn_unsupported
)
11273 goto unsupported_option
;
11278 case TCC_OPTION_rdynamic
:
11281 case TCC_OPTION_Wl
:
11284 if (strstart(optarg
, "-Ttext,", &p
)) {
11285 s
->text_addr
= strtoul(p
, NULL
, 16);
11286 s
->has_text_addr
= 1;
11287 } else if (strstart(optarg
, "--oformat,", &p
)) {
11288 if (strstart(p
, "elf32-", NULL
)) {
11289 s
->output_format
= TCC_OUTPUT_FORMAT_ELF
;
11290 } else if (!strcmp(p
, "binary")) {
11291 s
->output_format
= TCC_OUTPUT_FORMAT_BINARY
;
11293 #ifdef TCC_TARGET_COFF
11294 if (!strcmp(p
, "coff")) {
11295 s
->output_format
= TCC_OUTPUT_FORMAT_COFF
;
11299 error("target %s not found", p
);
11302 error("unsupported linker option '%s'", optarg
);
11307 output_type
= TCC_OUTPUT_PREPROCESS
;
11310 if (s
->warn_unsupported
) {
11311 unsupported_option
:
11312 warning("unsupported option '%s'", r
);
11321 int main(int argc
, char **argv
)
11325 int nb_objfiles
, ret
, optind
;
11326 char objfilename
[1024];
11327 int64_t start_time
= 0;
11330 tcc_lib_path
= w32_tcc_lib_path();
11334 output_type
= TCC_OUTPUT_EXE
;
11336 multiple_files
= 1;
11341 print_search_dirs
= 0;
11344 optind
= parse_args(s
, argc
- 1, argv
+ 1);
11345 if (print_search_dirs
) {
11346 /* enough for Linux kernel */
11347 printf("install: %s/\n", tcc_lib_path
);
11350 if (optind
== 0 || nb_files
== 0) {
11351 if (optind
&& verbose
)
11357 nb_objfiles
= nb_files
- nb_libraries
;
11359 /* if outfile provided without other options, we output an
11361 if (outfile
&& output_type
== TCC_OUTPUT_MEMORY
)
11362 output_type
= TCC_OUTPUT_EXE
;
11364 /* check -c consistency : only single file handled. XXX: checks file type */
11365 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
11366 /* accepts only a single input file */
11367 if (nb_objfiles
!= 1)
11368 error("cannot specify multiple files with -c");
11369 if (nb_libraries
!= 0)
11370 error("cannot specify libraries with -c");
11374 if (output_type
== TCC_OUTPUT_PREPROCESS
) {
11376 s
->outfile
= stdout
;
11378 s
->outfile
= fopen(outfile
, "w");
11380 error("could not open '%s", outfile
);
11382 } else if (output_type
!= TCC_OUTPUT_MEMORY
) {
11384 /* compute default outfile name */
11387 strcmp(files
[0], "-") == 0 ? "a" : tcc_basename(files
[0]);
11388 pstrcpy(objfilename
, sizeof(objfilename
), name
);
11389 ext
= tcc_fileextension(objfilename
);
11390 #ifdef TCC_TARGET_PE
11391 if (output_type
== TCC_OUTPUT_DLL
)
11392 strcpy(ext
, ".dll");
11394 if (output_type
== TCC_OUTPUT_EXE
)
11395 strcpy(ext
, ".exe");
11398 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
&& *ext
)
11401 pstrcpy(objfilename
, sizeof(objfilename
), "a.out");
11402 outfile
= objfilename
;
11407 start_time
= getclock_us();
11410 tcc_set_output_type(s
, output_type
);
11412 /* compile or add each files or library */
11413 for(i
= 0; i
< nb_files
&& ret
== 0; i
++) {
11414 const char *filename
;
11416 filename
= files
[i
];
11417 if (output_type
== TCC_OUTPUT_PREPROCESS
) {
11418 if (tcc_add_file_internal(s
, filename
,
11419 AFF_PRINT_ERROR
| AFF_PREPROCESS
) < 0)
11421 } else if (filename
[0] == '-' && filename
[1]) {
11422 if (tcc_add_library(s
, filename
+ 2) < 0)
11423 error("cannot find %s", filename
);
11426 printf("-> %s\n", filename
);
11427 if (tcc_add_file(s
, filename
) < 0)
11432 /* free all files */
11440 total_time
= (double)(getclock_us() - start_time
) / 1000000.0;
11441 if (total_time
< 0.001)
11442 total_time
= 0.001;
11443 if (total_bytes
< 1)
11445 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
11446 tok_ident
- TOK_IDENT
, total_lines
, total_bytes
,
11447 total_time
, (int)(total_lines
/ total_time
),
11448 total_bytes
/ total_time
/ 1000000.0);
11451 if (s
->output_type
== TCC_OUTPUT_PREPROCESS
) {
11453 fclose(s
->outfile
);
11454 } else if (s
->output_type
== TCC_OUTPUT_MEMORY
) {
11455 ret
= tcc_run(s
, argc
- optind
, argv
+ optind
);
11457 ret
= tcc_output_file(s
, outfile
) ? 1 : 0;
11459 /* XXX: cannot do it with bound checking because of the malloc hooks */
11460 if (!do_bounds_check
)
11465 printf("memory: %d bytes, max = %d bytes\n", mem_cur_size
, mem_max_size
);