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 */
549 #ifdef TCC_TARGET_X86_64
550 /* write PLT and GOT here */
551 char *runtime_plt_and_got
;
552 unsigned int runtime_plt_and_got_offset
;
556 /* The current value can be: */
557 #define VT_VALMASK 0x00ff
558 #define VT_CONST 0x00f0 /* constant in vc
559 (must be first non register value) */
560 #define VT_LLOCAL 0x00f1 /* lvalue, offset on stack */
561 #define VT_LOCAL 0x00f2 /* offset on stack */
562 #define VT_CMP 0x00f3 /* the value is stored in processor flags (in vc) */
563 #define VT_JMP 0x00f4 /* value is the consequence of jmp true (even) */
564 #define VT_JMPI 0x00f5 /* value is the consequence of jmp false (odd) */
565 #define VT_LVAL 0x0100 /* var is an lvalue */
566 #define VT_SYM 0x0200 /* a symbol value is added */
567 #define VT_MUSTCAST 0x0400 /* value must be casted to be correct (used for
568 char/short stored in integer registers) */
569 #define VT_MUSTBOUND 0x0800 /* bound checking must be done before
570 dereferencing value */
571 #define VT_BOUNDED 0x8000 /* value is bounded. The address of the
572 bounding function call point is in vc */
573 #define VT_LVAL_BYTE 0x1000 /* lvalue is a byte */
574 #define VT_LVAL_SHORT 0x2000 /* lvalue is a short */
575 #define VT_LVAL_UNSIGNED 0x4000 /* lvalue is unsigned */
576 #define VT_LVAL_TYPE (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
579 #define VT_INT 0 /* integer type */
580 #define VT_BYTE 1 /* signed byte type */
581 #define VT_SHORT 2 /* short type */
582 #define VT_VOID 3 /* void type */
583 #define VT_PTR 4 /* pointer */
584 #define VT_ENUM 5 /* enum definition */
585 #define VT_FUNC 6 /* function type */
586 #define VT_STRUCT 7 /* struct/union definition */
587 #define VT_FLOAT 8 /* IEEE float */
588 #define VT_DOUBLE 9 /* IEEE double */
589 #define VT_LDOUBLE 10 /* IEEE long double */
590 #define VT_BOOL 11 /* ISOC99 boolean type */
591 #define VT_LLONG 12 /* 64 bit integer */
592 #define VT_LONG 13 /* long integer (NEVER USED as type, only
594 #define VT_BTYPE 0x000f /* mask for basic type */
595 #define VT_UNSIGNED 0x0010 /* unsigned type */
596 #define VT_ARRAY 0x0020 /* array type (also has VT_PTR) */
597 #define VT_BITFIELD 0x0040 /* bitfield modifier */
598 #define VT_CONSTANT 0x0800 /* const modifier */
599 #define VT_VOLATILE 0x1000 /* volatile modifier */
600 #define VT_SIGNED 0x2000 /* signed type */
603 #define VT_EXTERN 0x00000080 /* extern definition */
604 #define VT_STATIC 0x00000100 /* static variable */
605 #define VT_TYPEDEF 0x00000200 /* typedef definition */
606 #define VT_INLINE 0x00000400 /* inline definition */
608 #define VT_STRUCT_SHIFT 16 /* shift for bitfield shift values */
610 /* type mask (except storage) */
611 #define VT_STORAGE (VT_EXTERN | VT_STATIC | VT_TYPEDEF | VT_INLINE)
612 #define VT_TYPE (~(VT_STORAGE))
616 /* warning: the following compare tokens depend on i386 asm code */
623 #define TOK_Nset 0x98
624 #define TOK_Nclear 0x99
630 #define TOK_LAND 0xa0
634 #define TOK_MID 0xa3 /* inc/dec, to void constant */
636 #define TOK_UDIV 0xb0 /* unsigned division */
637 #define TOK_UMOD 0xb1 /* unsigned modulo */
638 #define TOK_PDIV 0xb2 /* fast division with undefined rounding for pointers */
639 #define TOK_CINT 0xb3 /* number in tokc */
640 #define TOK_CCHAR 0xb4 /* char constant in tokc */
641 #define TOK_STR 0xb5 /* pointer to string in tokc */
642 #define TOK_TWOSHARPS 0xb6 /* ## preprocessing token */
643 #define TOK_LCHAR 0xb7
644 #define TOK_LSTR 0xb8
645 #define TOK_CFLOAT 0xb9 /* float constant */
646 #define TOK_LINENUM 0xba /* line number info */
647 #define TOK_CDOUBLE 0xc0 /* double constant */
648 #define TOK_CLDOUBLE 0xc1 /* long double constant */
649 #define TOK_UMULL 0xc2 /* unsigned 32x32 -> 64 mul */
650 #define TOK_ADDC1 0xc3 /* add with carry generation */
651 #define TOK_ADDC2 0xc4 /* add with carry use */
652 #define TOK_SUBC1 0xc5 /* add with carry generation */
653 #define TOK_SUBC2 0xc6 /* add with carry use */
654 #define TOK_CUINT 0xc8 /* unsigned int constant */
655 #define TOK_CLLONG 0xc9 /* long long constant */
656 #define TOK_CULLONG 0xca /* unsigned long long constant */
657 #define TOK_ARROW 0xcb
658 #define TOK_DOTS 0xcc /* three dots */
659 #define TOK_SHR 0xcd /* unsigned shift right */
660 #define TOK_PPNUM 0xce /* preprocessor number */
662 #define TOK_SHL 0x01 /* shift left */
663 #define TOK_SAR 0x02 /* signed shift right */
665 /* assignement operators : normal operator or 0x80 */
666 #define TOK_A_MOD 0xa5
667 #define TOK_A_AND 0xa6
668 #define TOK_A_MUL 0xaa
669 #define TOK_A_ADD 0xab
670 #define TOK_A_SUB 0xad
671 #define TOK_A_DIV 0xaf
672 #define TOK_A_XOR 0xde
673 #define TOK_A_OR 0xfc
674 #define TOK_A_SHL 0x81
675 #define TOK_A_SAR 0x82
678 #define offsetof(type, field) ((size_t) &((type *)0)->field)
682 #define countof(tab) (sizeof(tab) / sizeof((tab)[0]))
685 /* WARNING: the content of this string encodes token numbers */
686 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";
688 #define TOK_EOF (-1) /* end of file */
689 #define TOK_LINEFEED 10 /* line feed */
691 /* all identificators and strings have token above that */
692 #define TOK_IDENT 256
694 /* only used for i386 asm opcodes definitions */
695 #define DEF_ASM(x) DEF(TOK_ASM_ ## x, #x)
698 DEF(TOK_ASM_ ## x ## b, #x "b") \
699 DEF(TOK_ASM_ ## x ## w, #x "w") \
700 DEF(TOK_ASM_ ## x ## l, #x "l") \
701 DEF(TOK_ASM_ ## x, #x)
704 DEF(TOK_ASM_ ## x ## w, #x "w") \
705 DEF(TOK_ASM_ ## x ## l, #x "l") \
706 DEF(TOK_ASM_ ## x, #x)
709 DEF(TOK_ASM_ ## f ## x ## s, "f" #x "s") \
710 DEF(TOK_ASM_ ## fi ## x ## l, "fi" #x "l") \
711 DEF(TOK_ASM_ ## f ## x ## l, "f" #x "l") \
712 DEF(TOK_ASM_ ## fi ## x ## s, "fi" #x "s")
715 DEF(TOK_ASM_ ## f ## x, "f" #x ) \
716 DEF(TOK_ASM_ ## f ## x ## p, "f" #x "p") \
719 #define DEF_ASMTEST(x) \
751 #define TOK_ASM_int TOK_INT
754 TOK_LAST
= TOK_IDENT
- 1,
755 #define DEF(id, str) id,
760 static const char tcc_keywords
[] =
761 #define DEF(id, str) str "\0"
766 #define TOK_UIDENT TOK_DEFINE
769 #define snprintf _snprintf
770 #define vsnprintf _vsnprintf
772 #define strtold (long double)strtod
773 #define strtof (float)strtod
774 #define strtoll (long long)strtol
776 #elif defined(TCC_UCLIBC) || defined(__FreeBSD__) || defined(__DragonFly__) \
777 || defined(__OpenBSD__)
778 /* currently incorrect */
779 long double strtold(const char *nptr
, char **endptr
)
781 return (long double)strtod(nptr
, endptr
);
783 float strtof(const char *nptr
, char **endptr
)
785 return (float)strtod(nptr
, endptr
);
788 /* XXX: need to define this to use them in non ISOC99 context */
789 extern float strtof (const char *__nptr
, char **__endptr
);
790 extern long double strtold (const char *__nptr
, char **__endptr
);
793 static char *pstrcpy(char *buf
, int buf_size
, const char *s
);
794 static char *pstrcat(char *buf
, int buf_size
, const char *s
);
795 static char *tcc_basename(const char *name
);
796 static char *tcc_fileextension (const char *p
);
798 static void next(void);
799 static void next_nomacro(void);
800 static void parse_expr_type(CType
*type
);
801 static void expr_type(CType
*type
);
802 static void unary_type(CType
*type
);
803 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
804 int case_reg
, int is_expr
);
805 static int expr_const(void);
806 static void expr_eq(void);
807 static void gexpr(void);
808 static void gen_inline_functions(void);
809 static void decl(int l
);
810 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
811 int first
, int size_only
);
812 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
813 int has_init
, int v
, int scope
);
815 void gv2(int rc1
, int rc2
);
816 void move_reg(int r
, int s
);
817 void save_regs(int n
);
818 void save_reg(int r
);
823 int get_reg_ex(int rc
,int rc2
);
826 struct macro_level
*prev
;
830 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
831 const int *macro_str
, struct macro_level
**can_read_stream
);
833 void force_charshort_cast(int t
);
834 static void gen_cast(CType
*type
);
836 static Sym
*sym_find(int v
);
837 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
);
840 static int type_size(CType
*type
, int *a
);
841 static inline CType
*pointed_type(CType
*type
);
842 static int pointed_size(CType
*type
);
843 static int lvalue_type(int t
);
844 static int parse_btype(CType
*type
, AttributeDef
*ad
);
845 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
);
846 static int compare_types(CType
*type1
, CType
*type2
, int unqualified
);
847 static int is_compatible_types(CType
*type1
, CType
*type2
);
848 static int is_compatible_parameter_types(CType
*type1
, CType
*type2
);
850 int ieee_finite(double d
);
851 void error(const char *fmt
, ...);
853 void vpushll(long long v
);
856 void lexpand_nr(void);
857 static void vpush_global_sym(CType
*type
, int v
);
858 void vset(CType
*type
, int r
, int v
);
859 void type_to_str(char *buf
, int buf_size
,
860 CType
*type
, const char *varstr
);
861 char *get_tok_str(int v
, CValue
*cv
);
862 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
863 unsigned long offset
, unsigned long size
);
864 static Sym
*external_global_sym(int v
, CType
*type
, int r
);
866 /* section generation */
867 static void section_realloc(Section
*sec
, unsigned long new_size
);
868 static void *section_ptr_add(Section
*sec
, unsigned long size
);
869 static void put_extern_sym(Sym
*sym
, Section
*section
,
870 unsigned long value
, unsigned long size
);
871 static void greloc(Section
*s
, Sym
*sym
, unsigned long addr
, int type
);
872 static int put_elf_str(Section
*s
, const char *sym
);
873 static int put_elf_sym(Section
*s
,
874 unsigned long value
, unsigned long size
,
875 int info
, int other
, int shndx
, const char *name
);
876 static int add_elf_sym(Section
*s
, unsigned long value
, unsigned long size
,
877 int info
, int other
, int sh_num
, const char *name
);
878 static void put_elf_reloc(Section
*symtab
, Section
*s
, unsigned long offset
,
879 int type
, int symbol
);
880 static void put_stabs(const char *str
, int type
, int other
, int desc
,
881 unsigned long value
);
882 static void put_stabs_r(const char *str
, int type
, int other
, int desc
,
883 unsigned long value
, Section
*sec
, int sym_index
);
884 static void put_stabn(int type
, int other
, int desc
, int value
);
885 static void put_stabd(int type
, int other
, int desc
);
886 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
);
888 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
889 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
890 #define AFF_PREPROCESS 0x0004 /* preprocess file */
891 static int tcc_add_file_internal(TCCState
*s
, const char *filename
, int flags
);
894 int tcc_output_coff(TCCState
*s1
, FILE *f
);
897 void *resolve_sym(TCCState
*s1
, const char *sym
, int type
);
898 int pe_load_def_file(struct TCCState
*s1
, int fd
);
899 int pe_test_res_file(void *v
, int size
);
900 int pe_load_res_file(struct TCCState
*s1
, int fd
);
901 void pe_add_runtime(struct TCCState
*s1
);
902 void pe_guess_outfile(char *objfilename
, int output_type
);
903 int pe_output_file(struct TCCState
*s1
, const char *filename
);
907 #ifdef CONFIG_TCC_ASM
909 typedef struct ExprValue
{
914 #define MAX_ASM_OPERANDS 30
916 typedef struct ASMOperand
{
917 int id
; /* GCC 3 optionnal identifier (0 if number only supported */
919 char asm_str
[16]; /* computed asm string for operand */
920 SValue
*vt
; /* C value of the expression */
921 int ref_index
; /* if >= 0, gives reference to a output constraint */
922 int input_index
; /* if >= 0, gives reference to an input constraint */
923 int priority
; /* priority, used to assign registers */
924 int reg
; /* if >= 0, register number used for this operand */
925 int is_llong
; /* true if double register value */
926 int is_memory
; /* true if memory operand */
927 int is_rw
; /* for '+' modifier */
930 static void asm_expr(TCCState
*s1
, ExprValue
*pe
);
931 static int asm_int_expr(TCCState
*s1
);
932 static int find_constraint(ASMOperand
*operands
, int nb_operands
,
933 const char *name
, const char **pp
);
935 static int tcc_assemble(TCCState
*s1
, int do_preprocess
);
939 static void asm_instr(void);
940 static void asm_global_instr(void);
942 /* true if float/double/long double type */
943 static inline int is_float(int t
)
947 return bt
== VT_LDOUBLE
|| bt
== VT_DOUBLE
|| bt
== VT_FLOAT
;
950 #ifdef TCC_TARGET_I386
951 #include "i386-gen.c"
954 #ifdef TCC_TARGET_ARM
958 #ifdef TCC_TARGET_C67
962 #ifdef TCC_TARGET_X86_64
963 #include "x86_64-gen.c"
966 #ifdef CONFIG_TCC_STATIC
968 #define RTLD_LAZY 0x001
969 #define RTLD_NOW 0x002
970 #define RTLD_GLOBAL 0x100
971 #define RTLD_DEFAULT NULL
973 /* dummy function for profiling */
974 void *dlopen(const char *filename
, int flag
)
979 void dlclose(void *p
)
983 const char *dlerror(void)
988 typedef struct TCCSyms
{
993 #define TCCSYM(a) { #a, &a, },
995 /* add the symbol you want here if no dynamic linking is done */
996 static TCCSyms tcc_syms
[] = {
997 #if !defined(CONFIG_TCCBOOT)
1006 void *resolve_sym(TCCState
*s1
, const char *symbol
, int type
)
1010 while (p
->str
!= NULL
) {
1011 if (!strcmp(p
->str
, symbol
))
1018 #elif !defined(_WIN32)
1022 void *resolve_sym(TCCState
*s1
, const char *sym
, int type
)
1024 return dlsym(RTLD_DEFAULT
, sym
);
1029 /********************************************************/
1031 /* we use our own 'finite' function to avoid potential problems with
1032 non standard math libs */
1033 /* XXX: endianness dependent */
1034 int ieee_finite(double d
)
1037 return ((unsigned)((p
[1] | 0x800fffff) + 1)) >> 31;
1040 /* copy a string and truncate it. */
1041 static char *pstrcpy(char *buf
, int buf_size
, const char *s
)
1048 q_end
= buf
+ buf_size
- 1;
1060 /* strcat and truncate. */
1061 static char *pstrcat(char *buf
, int buf_size
, const char *s
)
1066 pstrcpy(buf
+ len
, buf_size
- len
, s
);
1071 static int strstart(const char *str
, const char *val
, const char **ptr
)
1076 while (*q
!= '\0') {
1089 #define IS_PATHSEP(c) (c == '/' || c == '\\')
1090 #define IS_ABSPATH(p) (IS_PATHSEP(p[0]) || (p[0] && p[1] == ':' && IS_PATHSEP(p[2])))
1091 #define PATHCMP stricmp
1093 #define IS_PATHSEP(c) (c == '/')
1094 #define IS_ABSPATH(p) IS_PATHSEP(p[0])
1095 #define PATHCMP strcmp
1098 /* extract the basename of a file */
1099 static char *tcc_basename(const char *name
)
1101 char *p
= strchr(name
, 0);
1102 while (p
> name
&& !IS_PATHSEP(p
[-1]))
1107 static char *tcc_fileextension (const char *name
)
1109 char *b
= tcc_basename(name
);
1110 char *e
= strrchr(b
, '.');
1111 return e
? e
: strchr(b
, 0);
1115 char *normalize_slashes(char *path
)
1118 for (p
= path
; *p
; ++p
)
1124 char *w32_tcc_lib_path(void)
1126 /* on win32, we suppose the lib and includes are at the location
1128 char path
[1024], *p
;
1129 GetModuleFileNameA(NULL
, path
, sizeof path
);
1130 p
= tcc_basename(normalize_slashes(strlwr(path
)));
1131 if (p
- 5 > path
&& 0 == strncmp(p
- 5, "/bin/", 5))
1136 return strdup(path
);
1140 void set_pages_executable(void *ptr
, unsigned long length
)
1143 unsigned long old_protect
;
1144 VirtualProtect(ptr
, length
, PAGE_EXECUTE_READWRITE
, &old_protect
);
1146 unsigned long start
, end
;
1147 start
= (unsigned long)ptr
& ~(PAGESIZE
- 1);
1148 end
= (unsigned long)ptr
+ length
;
1149 end
= (end
+ PAGESIZE
- 1) & ~(PAGESIZE
- 1);
1150 mprotect((void *)start
, end
- start
, PROT_READ
| PROT_WRITE
| PROT_EXEC
);
1154 /* memory management */
1158 unsigned malloc_usable_size(void*);
1161 static inline void tcc_free(void *ptr
)
1164 mem_cur_size
-= malloc_usable_size(ptr
);
1169 static void *tcc_malloc(unsigned long size
)
1174 error("memory full");
1176 mem_cur_size
+= malloc_usable_size(ptr
);
1177 if (mem_cur_size
> mem_max_size
)
1178 mem_max_size
= mem_cur_size
;
1183 static void *tcc_mallocz(unsigned long size
)
1186 ptr
= tcc_malloc(size
);
1187 memset(ptr
, 0, size
);
1191 static inline void *tcc_realloc(void *ptr
, unsigned long size
)
1195 mem_cur_size
-= malloc_usable_size(ptr
);
1197 ptr1
= realloc(ptr
, size
);
1199 /* NOTE: count not correct if alloc error, but not critical */
1200 mem_cur_size
+= malloc_usable_size(ptr1
);
1201 if (mem_cur_size
> mem_max_size
)
1202 mem_max_size
= mem_cur_size
;
1207 static char *tcc_strdup(const char *str
)
1210 ptr
= tcc_malloc(strlen(str
) + 1);
1215 #define free(p) use_tcc_free(p)
1216 #define malloc(s) use_tcc_malloc(s)
1217 #define realloc(p, s) use_tcc_realloc(p, s)
1219 static void dynarray_add(void ***ptab
, int *nb_ptr
, void *data
)
1226 /* every power of two we double array size */
1227 if ((nb
& (nb
- 1)) == 0) {
1232 pp
= tcc_realloc(pp
, nb_alloc
* sizeof(void *));
1234 error("memory full");
1241 static void dynarray_reset(void *pp
, int *n
)
1244 for (p
= *(void***)pp
; *n
; ++p
, --*n
)
1247 tcc_free(*(void**)pp
);
1251 /* symbol allocator */
1252 static Sym
*__sym_malloc(void)
1254 Sym
*sym_pool
, *sym
, *last_sym
;
1257 sym_pool
= tcc_malloc(SYM_POOL_NB
* sizeof(Sym
));
1258 dynarray_add(&sym_pools
, &nb_sym_pools
, sym_pool
);
1260 last_sym
= sym_free_first
;
1262 for(i
= 0; i
< SYM_POOL_NB
; i
++) {
1263 sym
->next
= last_sym
;
1267 sym_free_first
= last_sym
;
1271 static inline Sym
*sym_malloc(void)
1274 sym
= sym_free_first
;
1276 sym
= __sym_malloc();
1277 sym_free_first
= sym
->next
;
1281 static inline void sym_free(Sym
*sym
)
1283 sym
->next
= sym_free_first
;
1284 sym_free_first
= sym
;
1287 Section
*new_section(TCCState
*s1
, const char *name
, int sh_type
, int sh_flags
)
1291 sec
= tcc_mallocz(sizeof(Section
) + strlen(name
));
1292 strcpy(sec
->name
, name
);
1293 sec
->sh_type
= sh_type
;
1294 sec
->sh_flags
= sh_flags
;
1302 sec
->sh_addralign
= 4;
1305 sec
->sh_addralign
= 1;
1308 sec
->sh_addralign
= 32; /* default conservative alignment */
1312 if (sh_flags
& SHF_PRIVATE
) {
1313 dynarray_add((void ***)&s1
->priv_sections
, &s1
->nb_priv_sections
, sec
);
1315 sec
->sh_num
= s1
->nb_sections
;
1316 dynarray_add((void ***)&s1
->sections
, &s1
->nb_sections
, sec
);
1322 static void free_section(Section
*s
)
1327 /* realloc section and set its content to zero */
1328 static void section_realloc(Section
*sec
, unsigned long new_size
)
1331 unsigned char *data
;
1333 size
= sec
->data_allocated
;
1336 while (size
< new_size
)
1338 data
= tcc_realloc(sec
->data
, size
);
1340 error("memory full");
1341 memset(data
+ sec
->data_allocated
, 0, size
- sec
->data_allocated
);
1343 sec
->data_allocated
= size
;
1346 /* reserve at least 'size' bytes in section 'sec' from
1347 sec->data_offset. */
1348 static void *section_ptr_add(Section
*sec
, unsigned long size
)
1350 unsigned long offset
, offset1
;
1352 offset
= sec
->data_offset
;
1353 offset1
= offset
+ size
;
1354 if (offset1
> sec
->data_allocated
)
1355 section_realloc(sec
, offset1
);
1356 sec
->data_offset
= offset1
;
1357 return sec
->data
+ offset
;
1360 /* return a reference to a section, and create it if it does not
1362 Section
*find_section(TCCState
*s1
, const char *name
)
1366 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1367 sec
= s1
->sections
[i
];
1368 if (!strcmp(name
, sec
->name
))
1371 /* sections are created as PROGBITS */
1372 return new_section(s1
, name
, SHT_PROGBITS
, SHF_ALLOC
);
1375 #define SECTION_ABS ((void *)1)
1377 /* update sym->c so that it points to an external symbol in section
1378 'section' with value 'value' */
1379 static void put_extern_sym2(Sym
*sym
, Section
*section
,
1380 unsigned long value
, unsigned long size
,
1381 int can_add_underscore
)
1383 int sym_type
, sym_bind
, sh_num
, info
, other
, attr
;
1388 if (section
== NULL
)
1390 else if (section
== SECTION_ABS
)
1393 sh_num
= section
->sh_num
;
1397 if ((sym
->type
.t
& VT_BTYPE
) == VT_FUNC
) {
1398 sym_type
= STT_FUNC
;
1399 #ifdef TCC_TARGET_PE
1401 attr
= sym
->type
.ref
->r
;
1402 if (FUNC_EXPORT(attr
))
1404 if (FUNC_CALL(attr
) == FUNC_STDCALL
)
1408 sym_type
= STT_OBJECT
;
1411 if (sym
->type
.t
& VT_STATIC
)
1412 sym_bind
= STB_LOCAL
;
1414 sym_bind
= STB_GLOBAL
;
1417 name
= get_tok_str(sym
->v
, NULL
);
1418 #ifdef CONFIG_TCC_BCHECK
1419 if (do_bounds_check
) {
1422 /* XXX: avoid doing that for statics ? */
1423 /* if bound checking is activated, we change some function
1424 names by adding the "__bound" prefix */
1427 /* XXX: we rely only on malloc hooks */
1440 strcpy(buf
, "__bound_");
1448 #ifdef TCC_TARGET_PE
1449 if ((other
& 2) && can_add_underscore
) {
1450 sprintf(buf1
, "_%s@%d", name
, FUNC_ARGS(attr
));
1454 if (tcc_state
->leading_underscore
&& can_add_underscore
) {
1456 pstrcpy(buf1
+ 1, sizeof(buf1
) - 1, name
);
1459 info
= ELFW(ST_INFO
)(sym_bind
, sym_type
);
1460 sym
->c
= add_elf_sym(symtab_section
, value
, size
, info
, other
, sh_num
, name
);
1462 esym
= &((ElfW(Sym
) *)symtab_section
->data
)[sym
->c
];
1463 esym
->st_value
= value
;
1464 esym
->st_size
= size
;
1465 esym
->st_shndx
= sh_num
;
1466 esym
->st_other
|= other
;
1470 static void put_extern_sym(Sym
*sym
, Section
*section
,
1471 unsigned long value
, unsigned long size
)
1473 put_extern_sym2(sym
, section
, value
, size
, 1);
1476 /* add a new relocation entry to symbol 'sym' in section 's' */
1477 static void greloc(Section
*s
, Sym
*sym
, unsigned long offset
, int type
)
1480 put_extern_sym(sym
, NULL
, 0, 0);
1481 /* now we can add ELF relocation info */
1482 put_elf_reloc(symtab_section
, s
, offset
, type
, sym
->c
);
1485 static inline int isid(int c
)
1487 return (c
>= 'a' && c
<= 'z') ||
1488 (c
>= 'A' && c
<= 'Z') ||
1492 static inline int isnum(int c
)
1494 return c
>= '0' && c
<= '9';
1497 static inline int isoct(int c
)
1499 return c
>= '0' && c
<= '7';
1502 static inline int toup(int c
)
1504 if (c
>= 'a' && c
<= 'z')
1505 return c
- 'a' + 'A';
1510 static void strcat_vprintf(char *buf
, int buf_size
, const char *fmt
, va_list ap
)
1514 vsnprintf(buf
+ len
, buf_size
- len
, fmt
, ap
);
1517 static void strcat_printf(char *buf
, int buf_size
, const char *fmt
, ...)
1521 strcat_vprintf(buf
, buf_size
, fmt
, ap
);
1525 void error1(TCCState
*s1
, int is_warning
, const char *fmt
, va_list ap
)
1532 for(f
= s1
->include_stack
; f
< s1
->include_stack_ptr
; f
++)
1533 strcat_printf(buf
, sizeof(buf
), "In file included from %s:%d:\n",
1534 (*f
)->filename
, (*f
)->line_num
);
1535 if (file
->line_num
> 0) {
1536 strcat_printf(buf
, sizeof(buf
),
1537 "%s:%d: ", file
->filename
, file
->line_num
);
1539 strcat_printf(buf
, sizeof(buf
),
1540 "%s: ", file
->filename
);
1543 strcat_printf(buf
, sizeof(buf
),
1547 strcat_printf(buf
, sizeof(buf
), "warning: ");
1548 strcat_vprintf(buf
, sizeof(buf
), fmt
, ap
);
1550 if (!s1
->error_func
) {
1551 /* default case: stderr */
1552 fprintf(stderr
, "%s\n", buf
);
1554 s1
->error_func(s1
->error_opaque
, buf
);
1556 if (!is_warning
|| s1
->warn_error
)
1561 void tcc_set_error_func(TCCState
*s
, void *error_opaque
,
1562 void (*error_func
)(void *opaque
, const char *msg
))
1564 s
->error_opaque
= error_opaque
;
1565 s
->error_func
= error_func
;
1569 /* error without aborting current compilation */
1570 void error_noabort(const char *fmt
, ...)
1572 TCCState
*s1
= tcc_state
;
1576 error1(s1
, 0, fmt
, ap
);
1580 void error(const char *fmt
, ...)
1582 TCCState
*s1
= tcc_state
;
1586 error1(s1
, 0, fmt
, ap
);
1588 /* better than nothing: in some cases, we accept to handle errors */
1589 if (s1
->error_set_jmp_enabled
) {
1590 longjmp(s1
->error_jmp_buf
, 1);
1592 /* XXX: eliminate this someday */
1597 void expect(const char *msg
)
1599 error("%s expected", msg
);
1602 void warning(const char *fmt
, ...)
1604 TCCState
*s1
= tcc_state
;
1611 error1(s1
, 1, fmt
, ap
);
1618 error("'%c' expected", c
);
1622 static void test_lvalue(void)
1624 if (!(vtop
->r
& VT_LVAL
))
1628 /* allocate a new token */
1629 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
1631 TokenSym
*ts
, **ptable
;
1634 if (tok_ident
>= SYM_FIRST_ANOM
)
1635 error("memory full");
1637 /* expand token table if needed */
1638 i
= tok_ident
- TOK_IDENT
;
1639 if ((i
% TOK_ALLOC_INCR
) == 0) {
1640 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
1642 error("memory full");
1643 table_ident
= ptable
;
1646 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
1647 table_ident
[i
] = ts
;
1648 ts
->tok
= tok_ident
++;
1649 ts
->sym_define
= NULL
;
1650 ts
->sym_label
= NULL
;
1651 ts
->sym_struct
= NULL
;
1652 ts
->sym_identifier
= NULL
;
1654 ts
->hash_next
= NULL
;
1655 memcpy(ts
->str
, str
, len
);
1656 ts
->str
[len
] = '\0';
1661 #define TOK_HASH_INIT 1
1662 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
1664 /* find a token and add it if not found */
1665 static TokenSym
*tok_alloc(const char *str
, int len
)
1667 TokenSym
*ts
, **pts
;
1673 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
1674 h
&= (TOK_HASH_SIZE
- 1);
1676 pts
= &hash_ident
[h
];
1681 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
1683 pts
= &(ts
->hash_next
);
1685 return tok_alloc_new(pts
, str
, len
);
1688 /* CString handling */
1690 static void cstr_realloc(CString
*cstr
, int new_size
)
1695 size
= cstr
->size_allocated
;
1697 size
= 8; /* no need to allocate a too small first string */
1698 while (size
< new_size
)
1700 data
= tcc_realloc(cstr
->data_allocated
, size
);
1702 error("memory full");
1703 cstr
->data_allocated
= data
;
1704 cstr
->size_allocated
= size
;
1709 static inline void cstr_ccat(CString
*cstr
, int ch
)
1712 size
= cstr
->size
+ 1;
1713 if (size
> cstr
->size_allocated
)
1714 cstr_realloc(cstr
, size
);
1715 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
1719 static void cstr_cat(CString
*cstr
, const char *str
)
1731 /* add a wide char */
1732 static void cstr_wccat(CString
*cstr
, int ch
)
1735 size
= cstr
->size
+ sizeof(nwchar_t
);
1736 if (size
> cstr
->size_allocated
)
1737 cstr_realloc(cstr
, size
);
1738 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
1742 static void cstr_new(CString
*cstr
)
1744 memset(cstr
, 0, sizeof(CString
));
1747 /* free string and reset it to NULL */
1748 static void cstr_free(CString
*cstr
)
1750 tcc_free(cstr
->data_allocated
);
1754 #define cstr_reset(cstr) cstr_free(cstr)
1756 /* XXX: unicode ? */
1757 static void add_char(CString
*cstr
, int c
)
1759 if (c
== '\'' || c
== '\"' || c
== '\\') {
1760 /* XXX: could be more precise if char or string */
1761 cstr_ccat(cstr
, '\\');
1763 if (c
>= 32 && c
<= 126) {
1766 cstr_ccat(cstr
, '\\');
1768 cstr_ccat(cstr
, 'n');
1770 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
1771 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
1772 cstr_ccat(cstr
, '0' + (c
& 7));
1777 /* XXX: buffer overflow */
1778 /* XXX: float tokens */
1779 char *get_tok_str(int v
, CValue
*cv
)
1781 static char buf
[STRING_MAX_SIZE
+ 1];
1782 static CString cstr_buf
;
1788 /* NOTE: to go faster, we give a fixed buffer for small strings */
1789 cstr_reset(&cstr_buf
);
1790 cstr_buf
.data
= buf
;
1791 cstr_buf
.size_allocated
= sizeof(buf
);
1797 /* XXX: not quite exact, but only useful for testing */
1798 sprintf(p
, "%u", cv
->ui
);
1802 /* XXX: not quite exact, but only useful for testing */
1803 sprintf(p
, "%Lu", cv
->ull
);
1806 cstr_ccat(&cstr_buf
, 'L');
1808 cstr_ccat(&cstr_buf
, '\'');
1809 add_char(&cstr_buf
, cv
->i
);
1810 cstr_ccat(&cstr_buf
, '\'');
1811 cstr_ccat(&cstr_buf
, '\0');
1815 len
= cstr
->size
- 1;
1817 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1818 cstr_ccat(&cstr_buf
, '\0');
1821 cstr_ccat(&cstr_buf
, 'L');
1824 cstr_ccat(&cstr_buf
, '\"');
1826 len
= cstr
->size
- 1;
1828 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1830 len
= (cstr
->size
/ sizeof(nwchar_t
)) - 1;
1832 add_char(&cstr_buf
, ((nwchar_t
*)cstr
->data
)[i
]);
1834 cstr_ccat(&cstr_buf
, '\"');
1835 cstr_ccat(&cstr_buf
, '\0');
1844 return strcpy(p
, "...");
1846 return strcpy(p
, "<<=");
1848 return strcpy(p
, ">>=");
1850 if (v
< TOK_IDENT
) {
1851 /* search in two bytes table */
1865 } else if (v
< tok_ident
) {
1866 return table_ident
[v
- TOK_IDENT
]->str
;
1867 } else if (v
>= SYM_FIRST_ANOM
) {
1868 /* special name for anonymous symbol */
1869 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
1871 /* should never happen */
1876 return cstr_buf
.data
;
1879 /* push, without hashing */
1880 static Sym
*sym_push2(Sym
**ps
, int v
, int t
, long c
)
1894 /* find a symbol and return its associated structure. 's' is the top
1895 of the symbol stack */
1896 static Sym
*sym_find2(Sym
*s
, int v
)
1906 /* structure lookup */
1907 static inline Sym
*struct_find(int v
)
1910 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1912 return table_ident
[v
]->sym_struct
;
1915 /* find an identifier */
1916 static inline Sym
*sym_find(int v
)
1919 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1921 return table_ident
[v
]->sym_identifier
;
1924 /* push a given symbol on the symbol stack */
1925 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
)
1934 s
= sym_push2(ps
, v
, type
->t
, c
);
1935 s
->type
.ref
= type
->ref
;
1937 /* don't record fields or anonymous symbols */
1939 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1940 /* record symbol in token array */
1941 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1943 ps
= &ts
->sym_struct
;
1945 ps
= &ts
->sym_identifier
;
1952 /* push a global identifier */
1953 static Sym
*global_identifier_push(int v
, int t
, int c
)
1956 s
= sym_push2(&global_stack
, v
, t
, c
);
1957 /* don't record anonymous symbol */
1958 if (v
< SYM_FIRST_ANOM
) {
1959 ps
= &table_ident
[v
- TOK_IDENT
]->sym_identifier
;
1960 /* modify the top most local identifier, so that
1961 sym_identifier will point to 's' when popped */
1963 ps
= &(*ps
)->prev_tok
;
1970 /* pop symbols until top reaches 'b' */
1971 static void sym_pop(Sym
**ptop
, Sym
*b
)
1981 /* remove symbol in token array */
1983 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1984 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1986 ps
= &ts
->sym_struct
;
1988 ps
= &ts
->sym_identifier
;
1999 BufferedFile
*tcc_open(TCCState
*s1
, const char *filename
)
2004 if (strcmp(filename
, "-") == 0)
2005 fd
= 0, filename
= "stdin";
2007 fd
= open(filename
, O_RDONLY
| O_BINARY
);
2008 if ((verbose
== 2 && fd
>= 0) || verbose
== 3)
2009 printf("%s %*s%s\n", fd
< 0 ? "nf":"->",
2010 (s1
->include_stack_ptr
- s1
->include_stack
), "", filename
);
2013 bf
= tcc_malloc(sizeof(BufferedFile
));
2015 bf
->buf_ptr
= bf
->buffer
;
2016 bf
->buf_end
= bf
->buffer
;
2017 bf
->buffer
[0] = CH_EOB
; /* put eob symbol */
2018 pstrcpy(bf
->filename
, sizeof(bf
->filename
), filename
);
2020 normalize_slashes(bf
->filename
);
2023 bf
->ifndef_macro
= 0;
2024 bf
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
2025 // printf("opening '%s'\n", filename);
2029 void tcc_close(BufferedFile
*bf
)
2031 total_lines
+= bf
->line_num
;
2036 /* fill input buffer and peek next char */
2037 static int tcc_peekc_slow(BufferedFile
*bf
)
2040 /* only tries to read if really end of buffer */
2041 if (bf
->buf_ptr
>= bf
->buf_end
) {
2043 #if defined(PARSE_DEBUG)
2048 len
= read(bf
->fd
, bf
->buffer
, len
);
2055 bf
->buf_ptr
= bf
->buffer
;
2056 bf
->buf_end
= bf
->buffer
+ len
;
2057 *bf
->buf_end
= CH_EOB
;
2059 if (bf
->buf_ptr
< bf
->buf_end
) {
2060 return bf
->buf_ptr
[0];
2062 bf
->buf_ptr
= bf
->buf_end
;
2067 /* return the current character, handling end of block if necessary
2069 static int handle_eob(void)
2071 return tcc_peekc_slow(file
);
2074 /* read next char from current input file and handle end of input buffer */
2075 static inline void inp(void)
2077 ch
= *(++(file
->buf_ptr
));
2078 /* end of buffer/file handling */
2083 /* handle '\[\r]\n' */
2084 static int handle_stray_noerror(void)
2086 while (ch
== '\\') {
2091 } else if (ch
== '\r') {
2105 static void handle_stray(void)
2107 if (handle_stray_noerror())
2108 error("stray '\\' in program");
2111 /* skip the stray and handle the \\n case. Output an error if
2112 incorrect char after the stray */
2113 static int handle_stray1(uint8_t *p
)
2117 if (p
>= file
->buf_end
) {
2134 /* handle just the EOB case, but not stray */
2135 #define PEEKC_EOB(c, p)\
2146 /* handle the complicated stray case */
2147 #define PEEKC(c, p)\
2152 c = handle_stray1(p);\
2157 /* input with '\[\r]\n' handling. Note that this function cannot
2158 handle other characters after '\', so you cannot call it inside
2159 strings or comments */
2160 static void minp(void)
2168 /* single line C++ comments */
2169 static uint8_t *parse_line_comment(uint8_t *p
)
2177 if (c
== '\n' || c
== CH_EOF
) {
2179 } else if (c
== '\\') {
2188 } else if (c
== '\r') {
2206 static uint8_t *parse_comment(uint8_t *p
)
2212 /* fast skip loop */
2215 if (c
== '\n' || c
== '*' || c
== '\\')
2219 if (c
== '\n' || c
== '*' || c
== '\\')
2223 /* now we can handle all the cases */
2227 } else if (c
== '*') {
2233 } else if (c
== '/') {
2234 goto end_of_comment
;
2235 } else if (c
== '\\') {
2240 /* skip '\[\r]\n', otherwise just skip the stray */
2246 } else if (c
== '\r') {
2263 /* stray, eob or eof */
2268 error("unexpected end of file in comment");
2269 } else if (c
== '\\') {
2281 /* space exlcuding newline */
2282 static inline int is_space(int ch
)
2284 return ch
== ' ' || ch
== '\t' || ch
== '\v' || ch
== '\f' || ch
== '\r';
2287 static inline void skip_spaces(void)
2289 while (is_space(ch
))
2293 /* parse a string without interpreting escapes */
2294 static uint8_t *parse_pp_string(uint8_t *p
,
2295 int sep
, CString
*str
)
2303 } else if (c
== '\\') {
2308 unterminated_string
:
2309 /* XXX: indicate line number of start of string */
2310 error("missing terminating %c character", sep
);
2311 } else if (c
== '\\') {
2312 /* escape : just skip \[\r]\n */
2317 } else if (c
== '\r') {
2320 expect("'\n' after '\r'");
2323 } else if (c
== CH_EOF
) {
2324 goto unterminated_string
;
2327 cstr_ccat(str
, '\\');
2333 } else if (c
== '\n') {
2336 } else if (c
== '\r') {
2340 cstr_ccat(str
, '\r');
2356 /* skip block of text until #else, #elif or #endif. skip also pairs of
2358 void preprocess_skip(void)
2360 int a
, start_of_line
, c
, in_warn_or_error
;
2367 in_warn_or_error
= 0;
2388 } else if (c
== '\\') {
2389 ch
= file
->buf_ptr
[0];
2390 handle_stray_noerror();
2397 if (in_warn_or_error
)
2399 p
= parse_pp_string(p
, c
, NULL
);
2403 if (in_warn_or_error
)
2410 p
= parse_comment(p
);
2411 } else if (ch
== '/') {
2412 p
= parse_line_comment(p
);
2417 if (start_of_line
) {
2422 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
2424 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
2426 else if (tok
== TOK_ENDIF
)
2428 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
2429 in_warn_or_error
= 1;
2443 /* ParseState handling */
2445 /* XXX: currently, no include file info is stored. Thus, we cannot display
2446 accurate messages if the function or data definition spans multiple
2449 /* save current parse state in 's' */
2450 void save_parse_state(ParseState
*s
)
2452 s
->line_num
= file
->line_num
;
2453 s
->macro_ptr
= macro_ptr
;
2458 /* restore parse state from 's' */
2459 void restore_parse_state(ParseState
*s
)
2461 file
->line_num
= s
->line_num
;
2462 macro_ptr
= s
->macro_ptr
;
2467 /* return the number of additional 'ints' necessary to store the
2469 static inline int tok_ext_size(int t
)
2483 error("unsupported token");
2490 return LDOUBLE_SIZE
/ 4;
2496 /* token string handling */
2498 static inline void tok_str_new(TokenString
*s
)
2502 s
->allocated_len
= 0;
2503 s
->last_line_num
= -1;
2506 static void tok_str_free(int *str
)
2511 static int *tok_str_realloc(TokenString
*s
)
2515 if (s
->allocated_len
== 0) {
2518 len
= s
->allocated_len
* 2;
2520 str
= tcc_realloc(s
->str
, len
* sizeof(int));
2522 error("memory full");
2523 s
->allocated_len
= len
;
2528 static void tok_str_add(TokenString
*s
, int t
)
2534 if (len
>= s
->allocated_len
)
2535 str
= tok_str_realloc(s
);
2540 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
2547 /* allocate space for worst case */
2548 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
2549 str
= tok_str_realloc(s
);
2558 str
[len
++] = cv
->tab
[0];
2567 nb_words
= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
2568 while ((len
+ nb_words
) > s
->allocated_len
)
2569 str
= tok_str_realloc(s
);
2570 cstr
= (CString
*)(str
+ len
);
2572 cstr
->size
= cv
->cstr
->size
;
2573 cstr
->data_allocated
= NULL
;
2574 cstr
->size_allocated
= cstr
->size
;
2575 memcpy((char *)cstr
+ sizeof(CString
),
2576 cv
->cstr
->data
, cstr
->size
);
2583 #if LDOUBLE_SIZE == 8
2586 str
[len
++] = cv
->tab
[0];
2587 str
[len
++] = cv
->tab
[1];
2589 #if LDOUBLE_SIZE == 12
2591 str
[len
++] = cv
->tab
[0];
2592 str
[len
++] = cv
->tab
[1];
2593 str
[len
++] = cv
->tab
[2];
2594 #elif LDOUBLE_SIZE == 16
2596 str
[len
++] = cv
->tab
[0];
2597 str
[len
++] = cv
->tab
[1];
2598 str
[len
++] = cv
->tab
[2];
2599 str
[len
++] = cv
->tab
[3];
2600 #elif LDOUBLE_SIZE != 8
2601 #error add long double size support
2610 /* add the current parse token in token string 's' */
2611 static void tok_str_add_tok(TokenString
*s
)
2615 /* save line number info */
2616 if (file
->line_num
!= s
->last_line_num
) {
2617 s
->last_line_num
= file
->line_num
;
2618 cval
.i
= s
->last_line_num
;
2619 tok_str_add2(s
, TOK_LINENUM
, &cval
);
2621 tok_str_add2(s
, tok
, &tokc
);
2624 #if LDOUBLE_SIZE == 16
2625 #define LDOUBLE_GET(p, cv) \
2630 #elif LDOUBLE_SIZE == 12
2631 #define LDOUBLE_GET(p, cv) \
2635 #elif LDOUBLE_SIZE == 8
2636 #define LDOUBLE_GET(p, cv) \
2640 #error add long double size support
2644 /* get a token from an integer array and increment pointer
2645 accordingly. we code it as a macro to avoid pointer aliasing. */
2646 #define TOK_GET(t, p, cv) \
2661 cv.cstr = (CString *)p; \
2662 cv.cstr->data = (char *)p + sizeof(CString);\
2663 p += (sizeof(CString) + cv.cstr->size + 3) >> 2;\
2672 case TOK_CLDOUBLE: \
2673 LDOUBLE_GET(p, cv); \
2674 p += LDOUBLE_SIZE / 4; \
2681 /* defines handling */
2682 static inline void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
2686 s
= sym_push2(&define_stack
, v
, macro_type
, (long)str
);
2687 s
->next
= first_arg
;
2688 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
2691 /* undefined a define symbol. Its name is just set to zero */
2692 static void define_undef(Sym
*s
)
2696 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2697 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2701 static inline Sym
*define_find(int v
)
2704 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2706 return table_ident
[v
]->sym_define
;
2709 /* free define stack until top reaches 'b' */
2710 static void free_defines(Sym
*b
)
2718 /* do not free args or predefined defines */
2720 tok_str_free((int *)top
->c
);
2722 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2723 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2731 static Sym
*label_find(int v
)
2734 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2736 return table_ident
[v
]->sym_label
;
2739 static Sym
*label_push(Sym
**ptop
, int v
, int flags
)
2742 s
= sym_push2(ptop
, v
, 0, 0);
2744 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
2745 if (ptop
== &global_label_stack
) {
2746 /* modify the top most local identifier, so that
2747 sym_identifier will point to 's' when popped */
2749 ps
= &(*ps
)->prev_tok
;
2756 /* pop labels until element last is reached. Look if any labels are
2757 undefined. Define symbols if '&&label' was used. */
2758 static void label_pop(Sym
**ptop
, Sym
*slast
)
2761 for(s
= *ptop
; s
!= slast
; s
= s1
) {
2763 if (s
->r
== LABEL_DECLARED
) {
2764 warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
2765 } else if (s
->r
== LABEL_FORWARD
) {
2766 error("label '%s' used but not defined",
2767 get_tok_str(s
->v
, NULL
));
2770 /* define corresponding symbol. A size of
2772 put_extern_sym(s
, cur_text_section
, (long)s
->next
, 1);
2776 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
2782 /* eval an expression for #if/#elif */
2783 static int expr_preprocess(void)
2789 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2790 next(); /* do macro subst */
2791 if (tok
== TOK_DEFINED
) {
2796 c
= define_find(tok
) != 0;
2801 } else if (tok
>= TOK_IDENT
) {
2802 /* if undefined macro */
2806 tok_str_add_tok(&str
);
2808 tok_str_add(&str
, -1); /* simulate end of file */
2809 tok_str_add(&str
, 0);
2810 /* now evaluate C constant expression */
2811 macro_ptr
= str
.str
;
2815 tok_str_free(str
.str
);
2819 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
2820 static void tok_print(int *str
)
2826 TOK_GET(t
, str
, cval
);
2829 printf(" %s", get_tok_str(t
, &cval
));
2835 /* parse after #define */
2836 static void parse_define(void)
2838 Sym
*s
, *first
, **ps
;
2839 int v
, t
, varg
, is_vaargs
, c
;
2844 error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
2845 /* XXX: should check if same macro (ANSI) */
2848 /* '(' must be just after macro definition for MACRO_FUNC */
2849 c
= file
->buf_ptr
[0];
2851 c
= handle_stray1(file
->buf_ptr
);
2856 while (tok
!= ')') {
2860 if (varg
== TOK_DOTS
) {
2861 varg
= TOK___VA_ARGS__
;
2863 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
2867 if (varg
< TOK_IDENT
)
2868 error("badly punctuated parameter list");
2869 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
2880 /* EOF testing necessary for '-D' handling */
2881 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2882 tok_str_add2(&str
, tok
, &tokc
);
2885 tok_str_add(&str
, 0);
2887 printf("define %s %d: ", get_tok_str(v
, NULL
), t
);
2890 define_push(v
, t
, str
.str
, first
);
2893 static inline int hash_cached_include(int type
, const char *filename
)
2895 const unsigned char *s
;
2899 h
= TOK_HASH_FUNC(h
, type
);
2902 h
= TOK_HASH_FUNC(h
, *s
);
2905 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
2909 /* XXX: use a token or a hash table to accelerate matching ? */
2910 static CachedInclude
*search_cached_include(TCCState
*s1
,
2911 int type
, const char *filename
)
2915 h
= hash_cached_include(type
, filename
);
2916 i
= s1
->cached_includes_hash
[h
];
2920 e
= s1
->cached_includes
[i
- 1];
2921 if (e
->type
== type
&& !PATHCMP(e
->filename
, filename
))
2928 static inline void add_cached_include(TCCState
*s1
, int type
,
2929 const char *filename
, int ifndef_macro
)
2934 if (search_cached_include(s1
, type
, filename
))
2937 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
2939 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
2943 strcpy(e
->filename
, filename
);
2944 e
->ifndef_macro
= ifndef_macro
;
2945 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
2946 /* add in hash table */
2947 h
= hash_cached_include(type
, filename
);
2948 e
->hash_next
= s1
->cached_includes_hash
[h
];
2949 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
2952 static void pragma_parse(TCCState
*s1
)
2957 if (tok
== TOK_pack
) {
2960 #pragma pack(1) // set
2961 #pragma pack() // reset to default
2962 #pragma pack(push,1) // push & set
2963 #pragma pack(pop) // restore previous
2967 if (tok
== TOK_ASM_pop
) {
2969 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
2971 error("out of pack stack");
2973 s1
->pack_stack_ptr
--;
2977 if (tok
== TOK_ASM_push
) {
2979 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
2981 s1
->pack_stack_ptr
++;
2984 if (tok
!= TOK_CINT
) {
2986 error("invalid pack pragma");
2989 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
2993 *s1
->pack_stack_ptr
= val
;
2999 /* is_bof is true if first non space token at beginning of file */
3000 static void preprocess(int is_bof
)
3002 TCCState
*s1
= tcc_state
;
3003 int size
, i
, c
, n
, saved_parse_flags
;
3010 saved_parse_flags
= parse_flags
;
3011 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
|
3012 PARSE_FLAG_LINEFEED
;
3022 s
= define_find(tok
);
3023 /* undefine symbol by putting an invalid name */
3028 case TOK_INCLUDE_NEXT
:
3029 ch
= file
->buf_ptr
[0];
3030 /* XXX: incorrect if comments : use next_nomacro with a special mode */
3035 } else if (ch
== '\"') {
3040 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
3041 if ((q
- buf
) < sizeof(buf
) - 1)
3044 if (handle_stray_noerror() == 0)
3052 /* eat all spaces and comments after include */
3053 /* XXX: slightly incorrect */
3054 while (ch1
!= '\n' && ch1
!= CH_EOF
)
3058 /* computed #include : either we have only strings or
3059 we have anything enclosed in '<>' */
3062 if (tok
== TOK_STR
) {
3063 while (tok
!= TOK_LINEFEED
) {
3064 if (tok
!= TOK_STR
) {
3066 error("'#include' expects \"FILENAME\" or <FILENAME>");
3068 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
3074 while (tok
!= TOK_LINEFEED
) {
3075 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
3079 /* check syntax and remove '<>' */
3080 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
3081 goto include_syntax
;
3082 memmove(buf
, buf
+ 1, len
- 2);
3083 buf
[len
- 2] = '\0';
3088 e
= search_cached_include(s1
, c
, buf
);
3089 if (e
&& define_find(e
->ifndef_macro
)) {
3090 /* no need to parse the include because the 'ifndef macro'
3093 printf("%s: skipping %s\n", file
->filename
, buf
);
3096 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
3097 error("#include recursion too deep");
3098 /* push current file in stack */
3099 /* XXX: fix current line init */
3100 *s1
->include_stack_ptr
++ = file
;
3102 /* check absolute include path */
3103 if (IS_ABSPATH(buf
)) {
3104 f
= tcc_open(s1
, buf
);
3109 /* first search in current dir if "header.h" */
3110 size
= tcc_basename(file
->filename
) - file
->filename
;
3111 if (size
> sizeof(buf1
) - 1)
3112 size
= sizeof(buf1
) - 1;
3113 memcpy(buf1
, file
->filename
, size
);
3115 pstrcat(buf1
, sizeof(buf1
), buf
);
3116 f
= tcc_open(s1
, buf1
);
3118 if (tok
== TOK_INCLUDE_NEXT
)
3124 /* now search in all the include paths */
3125 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
3126 for(i
= 0; i
< n
; i
++) {
3128 if (i
< s1
->nb_include_paths
)
3129 path
= s1
->include_paths
[i
];
3131 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
3132 pstrcpy(buf1
, sizeof(buf1
), path
);
3133 pstrcat(buf1
, sizeof(buf1
), "/");
3134 pstrcat(buf1
, sizeof(buf1
), buf
);
3135 f
= tcc_open(s1
, buf1
);
3137 if (tok
== TOK_INCLUDE_NEXT
)
3143 --s1
->include_stack_ptr
;
3144 error("include file '%s' not found", buf
);
3148 printf("%s: including %s\n", file
->filename
, buf1
);
3151 pstrcpy(f
->inc_filename
, sizeof(f
->inc_filename
), buf
);
3153 /* add include file debug info */
3155 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
3157 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
3158 ch
= file
->buf_ptr
[0];
3166 c
= expr_preprocess();
3172 if (tok
< TOK_IDENT
)
3173 error("invalid argument for '#if%sdef'", c
? "n" : "");
3177 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
3179 file
->ifndef_macro
= tok
;
3182 c
= (define_find(tok
) != 0) ^ c
;
3184 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
3185 error("memory full");
3186 *s1
->ifdef_stack_ptr
++ = c
;
3189 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
3190 error("#else without matching #if");
3191 if (s1
->ifdef_stack_ptr
[-1] & 2)
3192 error("#else after #else");
3193 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
3196 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
3197 error("#elif without matching #if");
3198 c
= s1
->ifdef_stack_ptr
[-1];
3200 error("#elif after #else");
3201 /* last #if/#elif expression was true: we skip */
3204 c
= expr_preprocess();
3205 s1
->ifdef_stack_ptr
[-1] = c
;
3215 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
3216 error("#endif without matching #if");
3217 s1
->ifdef_stack_ptr
--;
3218 /* '#ifndef macro' was at the start of file. Now we check if
3219 an '#endif' is exactly at the end of file */
3220 if (file
->ifndef_macro
&&
3221 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
3222 file
->ifndef_macro_saved
= file
->ifndef_macro
;
3223 /* need to set to zero to avoid false matches if another
3224 #ifndef at middle of file */
3225 file
->ifndef_macro
= 0;
3226 while (tok
!= TOK_LINEFEED
)
3228 tok_flags
|= TOK_FLAG_ENDIF
;
3234 if (tok
!= TOK_CINT
)
3236 file
->line_num
= tokc
.i
- 1; /* the line number will be incremented after */
3238 if (tok
!= TOK_LINEFEED
) {
3241 pstrcpy(file
->filename
, sizeof(file
->filename
),
3242 (char *)tokc
.cstr
->data
);
3248 ch
= file
->buf_ptr
[0];
3251 while (ch
!= '\n' && ch
!= CH_EOF
) {
3252 if ((q
- buf
) < sizeof(buf
) - 1)
3255 if (handle_stray_noerror() == 0)
3262 error("#error %s", buf
);
3264 warning("#warning %s", buf
);
3270 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_CINT
) {
3271 /* '!' is ignored to allow C scripts. numbers are ignored
3272 to emulate cpp behaviour */
3274 if (!(saved_parse_flags
& PARSE_FLAG_ASM_COMMENTS
))
3275 warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
3279 /* ignore other preprocess commands or #! for C scripts */
3280 while (tok
!= TOK_LINEFEED
)
3283 parse_flags
= saved_parse_flags
;
3286 /* evaluate escape codes in a string. */
3287 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
3302 case '0': case '1': case '2': case '3':
3303 case '4': case '5': case '6': case '7':
3304 /* at most three octal digits */
3309 n
= n
* 8 + c
- '0';
3313 n
= n
* 8 + c
- '0';
3318 goto add_char_nonext
;
3326 if (c
>= 'a' && c
<= 'f')
3328 else if (c
>= 'A' && c
<= 'F')
3338 goto add_char_nonext
;
3362 goto invalid_escape
;
3372 if (c
>= '!' && c
<= '~')
3373 warning("unknown escape sequence: \'\\%c\'", c
);
3375 warning("unknown escape sequence: \'\\x%x\'", c
);
3382 cstr_ccat(outstr
, c
);
3384 cstr_wccat(outstr
, c
);
3386 /* add a trailing '\0' */
3388 cstr_ccat(outstr
, '\0');
3390 cstr_wccat(outstr
, '\0');
3393 /* we use 64 bit numbers */
3396 /* bn = (bn << shift) | or_val */
3397 void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
3401 for(i
=0;i
<BN_SIZE
;i
++) {
3403 bn
[i
] = (v
<< shift
) | or_val
;
3404 or_val
= v
>> (32 - shift
);
3408 void bn_zero(unsigned int *bn
)
3411 for(i
=0;i
<BN_SIZE
;i
++) {
3416 /* parse number in null terminated string 'p' and return it in the
3418 void parse_number(const char *p
)
3420 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
3422 unsigned int bn
[BN_SIZE
];
3433 goto float_frac_parse
;
3434 } else if (t
== '0') {
3435 if (ch
== 'x' || ch
== 'X') {
3439 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
3445 /* parse all digits. cannot check octal numbers at this stage
3446 because of floating point constants */
3448 if (ch
>= 'a' && ch
<= 'f')
3450 else if (ch
>= 'A' && ch
<= 'F')
3458 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
3460 error("number too long");
3466 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
3467 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
3469 /* NOTE: strtox should support that for hexa numbers, but
3470 non ISOC99 libcs do not support it, so we prefer to do
3472 /* hexadecimal or binary floats */
3473 /* XXX: handle overflows */
3485 } else if (t
>= 'a') {
3487 } else if (t
>= 'A') {
3492 bn_lshift(bn
, shift
, t
);
3499 if (t
>= 'a' && t
<= 'f') {
3501 } else if (t
>= 'A' && t
<= 'F') {
3503 } else if (t
>= '0' && t
<= '9') {
3509 error("invalid digit");
3510 bn_lshift(bn
, shift
, t
);
3515 if (ch
!= 'p' && ch
!= 'P')
3522 } else if (ch
== '-') {
3526 if (ch
< '0' || ch
> '9')
3527 expect("exponent digits");
3528 while (ch
>= '0' && ch
<= '9') {
3529 exp_val
= exp_val
* 10 + ch
- '0';
3532 exp_val
= exp_val
* s
;
3534 /* now we can generate the number */
3535 /* XXX: should patch directly float number */
3536 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
3537 d
= ldexp(d
, exp_val
- frac_bits
);
3542 /* float : should handle overflow */
3544 } else if (t
== 'L') {
3547 /* XXX: not large enough */
3548 tokc
.ld
= (long double)d
;
3554 /* decimal floats */
3556 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3561 while (ch
>= '0' && ch
<= '9') {
3562 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3568 if (ch
== 'e' || ch
== 'E') {
3569 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3573 if (ch
== '-' || ch
== '+') {
3574 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3579 if (ch
< '0' || ch
> '9')
3580 expect("exponent digits");
3581 while (ch
>= '0' && ch
<= '9') {
3582 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3594 tokc
.f
= strtof(token_buf
, NULL
);
3595 } else if (t
== 'L') {
3598 tokc
.ld
= strtold(token_buf
, NULL
);
3601 tokc
.d
= strtod(token_buf
, NULL
);
3605 unsigned long long n
, n1
;
3608 /* integer number */
3611 if (b
== 10 && *q
== '0') {
3618 /* no need for checks except for base 10 / 8 errors */
3621 } else if (t
>= 'a') {
3623 } else if (t
>= 'A') {
3628 error("invalid digit");
3632 /* detect overflow */
3633 /* XXX: this test is not reliable */
3635 error("integer constant overflow");
3638 /* XXX: not exactly ANSI compliant */
3639 if ((n
& 0xffffffff00000000LL
) != 0) {
3644 } else if (n
> 0x7fffffff) {
3655 error("three 'l's in integer constant");
3658 if (tok
== TOK_CINT
)
3660 else if (tok
== TOK_CUINT
)
3664 } else if (t
== 'U') {
3666 error("two 'u's in integer constant");
3668 if (tok
== TOK_CINT
)
3670 else if (tok
== TOK_CLLONG
)
3677 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
3683 error("invalid number\n");
3687 #define PARSE2(c1, tok1, c2, tok2) \
3698 /* return next token without macro substitution */
3699 static inline void next_nomacro1(void)
3706 cstr_reset(&tok_spaces
);
3716 cstr_ccat(&tok_spaces
, c
);
3721 /* first look if it is in fact an end of buffer */
3722 if (p
>= file
->buf_end
) {
3726 if (p
>= file
->buf_end
)
3739 TCCState
*s1
= tcc_state
;
3740 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
3741 && !(tok_flags
& TOK_FLAG_EOF
)) {
3742 tok_flags
|= TOK_FLAG_EOF
;
3744 goto keep_tok_flags
;
3745 } else if (s1
->include_stack_ptr
== s1
->include_stack
||
3746 !(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3747 /* no include left : end of file. */
3750 tok_flags
&= ~TOK_FLAG_EOF
;
3751 /* pop include file */
3753 /* test if previous '#endif' was after a #ifdef at
3755 if (tok_flags
& TOK_FLAG_ENDIF
) {
3757 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
3759 add_cached_include(s1
, file
->inc_type
, file
->inc_filename
,
3760 file
->ifndef_macro_saved
);
3763 /* add end of include file debug info */
3765 put_stabd(N_EINCL
, 0, 0);
3767 /* pop include stack */
3769 s1
->include_stack_ptr
--;
3770 file
= *s1
->include_stack_ptr
;
3779 tok_flags
|= TOK_FLAG_BOL
;
3781 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
3784 goto keep_tok_flags
;
3789 if ((tok_flags
& TOK_FLAG_BOL
) &&
3790 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3792 preprocess(tok_flags
& TOK_FLAG_BOF
);
3798 tok
= TOK_TWOSHARPS
;
3800 if (parse_flags
& PARSE_FLAG_ASM_COMMENTS
) {
3801 p
= parse_line_comment(p
- 1);
3810 case 'a': case 'b': case 'c': case 'd':
3811 case 'e': case 'f': case 'g': case 'h':
3812 case 'i': case 'j': case 'k': case 'l':
3813 case 'm': case 'n': case 'o': case 'p':
3814 case 'q': case 'r': case 's': case 't':
3815 case 'u': case 'v': case 'w': case 'x':
3817 case 'A': case 'B': case 'C': case 'D':
3818 case 'E': case 'F': case 'G': case 'H':
3819 case 'I': case 'J': case 'K':
3820 case 'M': case 'N': case 'O': case 'P':
3821 case 'Q': case 'R': case 'S': case 'T':
3822 case 'U': case 'V': case 'W': case 'X':
3828 h
= TOK_HASH_FUNC(h
, c
);
3832 if (!isidnum_table
[c
-CH_EOF
])
3834 h
= TOK_HASH_FUNC(h
, c
);
3841 /* fast case : no stray found, so we have the full token
3842 and we have already hashed it */
3844 h
&= (TOK_HASH_SIZE
- 1);
3845 pts
= &hash_ident
[h
];
3850 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
3852 pts
= &(ts
->hash_next
);
3854 ts
= tok_alloc_new(pts
, p1
, len
);
3858 cstr_reset(&tokcstr
);
3861 cstr_ccat(&tokcstr
, *p1
);
3867 while (isidnum_table
[c
-CH_EOF
]) {
3868 cstr_ccat(&tokcstr
, c
);
3871 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
3877 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
3879 goto parse_ident_fast
;
3882 if (c
== '\'' || c
== '\"') {
3886 cstr_reset(&tokcstr
);
3887 cstr_ccat(&tokcstr
, 'L');
3888 goto parse_ident_slow
;
3892 case '0': case '1': case '2': case '3':
3893 case '4': case '5': case '6': case '7':
3896 cstr_reset(&tokcstr
);
3897 /* after the first digit, accept digits, alpha, '.' or sign if
3898 prefixed by 'eEpP' */
3902 cstr_ccat(&tokcstr
, c
);
3904 if (!(isnum(c
) || isid(c
) || c
== '.' ||
3905 ((c
== '+' || c
== '-') &&
3906 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
3909 /* We add a trailing '\0' to ease parsing */
3910 cstr_ccat(&tokcstr
, '\0');
3911 tokc
.cstr
= &tokcstr
;
3915 /* special dot handling because it can also start a number */
3918 cstr_reset(&tokcstr
);
3919 cstr_ccat(&tokcstr
, '.');
3921 } else if (c
== '.') {
3941 /* parse the string */
3943 p
= parse_pp_string(p
, sep
, &str
);
3944 cstr_ccat(&str
, '\0');
3946 /* eval the escape (should be done as TOK_PPNUM) */
3947 cstr_reset(&tokcstr
);
3948 parse_escape_string(&tokcstr
, str
.data
, is_long
);
3953 /* XXX: make it portable */
3957 char_size
= sizeof(nwchar_t
);
3958 if (tokcstr
.size
<= char_size
)
3959 error("empty character constant");
3960 if (tokcstr
.size
> 2 * char_size
)
3961 warning("multi-character character constant");
3963 tokc
.i
= *(int8_t *)tokcstr
.data
;
3966 tokc
.i
= *(nwchar_t
*)tokcstr
.data
;
3970 tokc
.cstr
= &tokcstr
;
3984 } else if (c
== '<') {
4002 } else if (c
== '>') {
4020 } else if (c
== '=') {
4033 } else if (c
== '=') {
4046 } else if (c
== '=') {
4059 } else if (c
== '=') {
4062 } else if (c
== '>') {
4070 PARSE2('!', '!', '=', TOK_NE
)
4071 PARSE2('=', '=', '=', TOK_EQ
)
4072 PARSE2('*', '*', '=', TOK_A_MUL
)
4073 PARSE2('%', '%', '=', TOK_A_MOD
)
4074 PARSE2('^', '^', '=', TOK_A_XOR
)
4076 /* comments or operator */
4080 p
= parse_comment(p
);
4082 } else if (c
== '/') {
4083 p
= parse_line_comment(p
);
4085 } else if (c
== '=') {
4105 case '$': /* only used in assembler */
4106 case '@': /* dito */
4111 error("unrecognized character \\x%02x", c
);
4117 #if defined(PARSE_DEBUG)
4118 printf("token = %s\n", get_tok_str(tok
, &tokc
));
4122 /* return next token without macro substitution. Can read input from
4124 static void next_nomacro(void)
4130 TOK_GET(tok
, macro_ptr
, tokc
);
4131 if (tok
== TOK_LINENUM
) {
4132 file
->line_num
= tokc
.i
;
4141 /* substitute args in macro_str and return allocated string */
4142 static int *macro_arg_subst(Sym
**nested_list
, int *macro_str
, Sym
*args
)
4144 int *st
, last_tok
, t
, notfirst
;
4153 TOK_GET(t
, macro_str
, cval
);
4158 TOK_GET(t
, macro_str
, cval
);
4161 s
= sym_find2(args
, t
);
4168 cstr_ccat(&cstr
, ' ');
4169 TOK_GET(t
, st
, cval
);
4170 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
4175 cstr_ccat(&cstr
, '\0');
4177 printf("stringize: %s\n", (char *)cstr
.data
);
4181 tok_str_add2(&str
, TOK_STR
, &cval
);
4184 tok_str_add2(&str
, t
, &cval
);
4186 } else if (t
>= TOK_IDENT
) {
4187 s
= sym_find2(args
, t
);
4190 /* if '##' is present before or after, no arg substitution */
4191 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
4192 /* special case for var arg macros : ## eats the
4193 ',' if empty VA_ARGS variable. */
4194 /* XXX: test of the ',' is not 100%
4195 reliable. should fix it to avoid security
4197 if (gnu_ext
&& s
->type
.t
&&
4198 last_tok
== TOK_TWOSHARPS
&&
4199 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
4201 /* suppress ',' '##' */
4204 /* suppress '##' and add variable */
4212 TOK_GET(t1
, st
, cval
);
4215 tok_str_add2(&str
, t1
, &cval
);
4219 /* NOTE: the stream cannot be read when macro
4220 substituing an argument */
4221 macro_subst(&str
, nested_list
, st
, NULL
);
4224 tok_str_add(&str
, t
);
4227 tok_str_add2(&str
, t
, &cval
);
4231 tok_str_add(&str
, 0);
4235 static char const ab_month_name
[12][4] =
4237 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
4238 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
4241 /* do macro substitution of current token with macro 's' and add
4242 result to (tok_str,tok_len). 'nested_list' is the list of all
4243 macros we got inside to avoid recursing. Return non zero if no
4244 substitution needs to be done */
4245 static int macro_subst_tok(TokenString
*tok_str
,
4246 Sym
**nested_list
, Sym
*s
, struct macro_level
**can_read_stream
)
4248 Sym
*args
, *sa
, *sa1
;
4249 int mstr_allocated
, parlevel
, *mstr
, t
, t1
;
4256 /* if symbol is a macro, prepare substitution */
4257 /* special macros */
4258 if (tok
== TOK___LINE__
) {
4259 snprintf(buf
, sizeof(buf
), "%d", file
->line_num
);
4263 } else if (tok
== TOK___FILE__
) {
4264 cstrval
= file
->filename
;
4266 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
4271 tm
= localtime(&ti
);
4272 if (tok
== TOK___DATE__
) {
4273 snprintf(buf
, sizeof(buf
), "%s %2d %d",
4274 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
4276 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
4277 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
4284 cstr_cat(&cstr
, cstrval
);
4285 cstr_ccat(&cstr
, '\0');
4287 tok_str_add2(tok_str
, t1
, &cval
);
4292 if (s
->type
.t
== MACRO_FUNC
) {
4293 /* NOTE: we do not use next_nomacro to avoid eating the
4294 next token. XXX: find better solution */
4298 if (t
== 0 && can_read_stream
) {
4299 /* end of macro stream: we must look at the token
4300 after in the file */
4301 struct macro_level
*ml
= *can_read_stream
;
4307 *can_read_stream
= ml
-> prev
;
4312 /* XXX: incorrect with comments */
4313 ch
= file
->buf_ptr
[0];
4314 while (is_space(ch
) || ch
== '\n')
4318 if (t
!= '(') /* no macro subst */
4321 /* argument macro */
4326 /* NOTE: empty args are allowed, except if no args */
4328 /* handle '()' case */
4329 if (!args
&& !sa
&& tok
== ')')
4332 error("macro '%s' used with too many args",
4333 get_tok_str(s
->v
, 0));
4336 /* NOTE: non zero sa->t indicates VA_ARGS */
4337 while ((parlevel
> 0 ||
4339 (tok
!= ',' || sa
->type
.t
))) &&
4343 else if (tok
== ')')
4345 if (tok
!= TOK_LINEFEED
)
4346 tok_str_add2(&str
, tok
, &tokc
);
4349 tok_str_add(&str
, 0);
4350 sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, (long)str
.str
);
4353 /* special case for gcc var args: add an empty
4354 var arg argument if it is omitted */
4355 if (sa
&& sa
->type
.t
&& gnu_ext
)
4365 error("macro '%s' used with too few args",
4366 get_tok_str(s
->v
, 0));
4369 /* now subst each arg */
4370 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
4375 tok_str_free((int *)sa
->c
);
4381 sym_push2(nested_list
, s
->v
, 0, 0);
4382 macro_subst(tok_str
, nested_list
, mstr
, can_read_stream
);
4383 /* pop nested defined symbol */
4385 *nested_list
= sa1
->prev
;
4393 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
4394 return the resulting string (which must be freed). */
4395 static inline int *macro_twosharps(const int *macro_str
)
4398 const int *macro_ptr1
, *start_macro_ptr
, *ptr
, *saved_macro_ptr
;
4400 const char *p1
, *p2
;
4402 TokenString macro_str1
;
4405 start_macro_ptr
= macro_str
;
4406 /* we search the first '##' */
4408 macro_ptr1
= macro_str
;
4409 TOK_GET(t
, macro_str
, cval
);
4410 /* nothing more to do if end of string */
4413 if (*macro_str
== TOK_TWOSHARPS
)
4417 /* we saw '##', so we need more processing to handle it */
4419 tok_str_new(¯o_str1
);
4423 /* add all tokens seen so far */
4424 for(ptr
= start_macro_ptr
; ptr
< macro_ptr1
;) {
4425 TOK_GET(t
, ptr
, cval
);
4426 tok_str_add2(¯o_str1
, t
, &cval
);
4428 saved_macro_ptr
= macro_ptr
;
4429 /* XXX: get rid of the use of macro_ptr here */
4430 macro_ptr
= (int *)macro_str
;
4432 while (*macro_ptr
== TOK_TWOSHARPS
) {
4434 macro_ptr1
= macro_ptr
;
4437 TOK_GET(t
, macro_ptr
, cval
);
4438 /* We concatenate the two tokens if we have an
4439 identifier or a preprocessing number */
4441 p1
= get_tok_str(tok
, &tokc
);
4442 cstr_cat(&cstr
, p1
);
4443 p2
= get_tok_str(t
, &cval
);
4444 cstr_cat(&cstr
, p2
);
4445 cstr_ccat(&cstr
, '\0');
4447 if ((tok
>= TOK_IDENT
|| tok
== TOK_PPNUM
) &&
4448 (t
>= TOK_IDENT
|| t
== TOK_PPNUM
)) {
4449 if (tok
== TOK_PPNUM
) {
4450 /* if number, then create a number token */
4451 /* NOTE: no need to allocate because
4452 tok_str_add2() does it */
4453 cstr_reset(&tokcstr
);
4456 tokc
.cstr
= &tokcstr
;
4458 /* if identifier, we must do a test to
4459 validate we have a correct identifier */
4460 if (t
== TOK_PPNUM
) {
4470 if (!isnum(c
) && !isid(c
))
4474 ts
= tok_alloc(cstr
.data
, strlen(cstr
.data
));
4475 tok
= ts
->tok
; /* modify current token */
4478 const char *str
= cstr
.data
;
4479 const unsigned char *q
;
4481 /* we look for a valid token */
4482 /* XXX: do more extensive checks */
4483 if (!strcmp(str
, ">>=")) {
4485 } else if (!strcmp(str
, "<<=")) {
4487 } else if (strlen(str
) == 2) {
4488 /* search in two bytes table */
4493 if (q
[0] == str
[0] && q
[1] == str
[1])
4500 /* NOTE: because get_tok_str use a static buffer,
4503 p1
= get_tok_str(tok
, &tokc
);
4504 cstr_cat(&cstr
, p1
);
4505 cstr_ccat(&cstr
, '\0');
4506 p2
= get_tok_str(t
, &cval
);
4507 warning("pasting \"%s\" and \"%s\" does not give a valid preprocessing token", cstr
.data
, p2
);
4508 /* cannot merge tokens: just add them separately */
4509 tok_str_add2(¯o_str1
, tok
, &tokc
);
4510 /* XXX: free associated memory ? */
4517 tok_str_add2(¯o_str1
, tok
, &tokc
);
4522 macro_ptr
= (int *)saved_macro_ptr
;
4524 tok_str_add(¯o_str1
, 0);
4525 return macro_str1
.str
;
4529 /* do macro substitution of macro_str and add result to
4530 (tok_str,tok_len). 'nested_list' is the list of all macros we got
4531 inside to avoid recursing. */
4532 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
4533 const int *macro_str
, struct macro_level
** can_read_stream
)
4540 struct macro_level ml
;
4542 /* first scan for '##' operator handling */
4544 macro_str1
= macro_twosharps(ptr
);
4548 /* NOTE: ptr == NULL can only happen if tokens are read from
4549 file stream due to a macro function call */
4552 TOK_GET(t
, ptr
, cval
);
4557 /* if nested substitution, do nothing */
4558 if (sym_find2(*nested_list
, t
))
4561 if (can_read_stream
)
4562 ml
.prev
= *can_read_stream
, *can_read_stream
= &ml
;
4563 macro_ptr
= (int *)ptr
;
4565 ret
= macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
4566 ptr
= (int *)macro_ptr
;
4568 if (can_read_stream
&& *can_read_stream
== &ml
)
4569 *can_read_stream
= ml
.prev
;
4574 tok_str_add2(tok_str
, t
, &cval
);
4578 tok_str_free(macro_str1
);
4581 /* return next token with macro substitution */
4582 static void next(void)
4584 Sym
*nested_list
, *s
;
4586 struct macro_level
*ml
;
4591 /* if not reading from macro substituted string, then try
4592 to substitute macros */
4593 if (tok
>= TOK_IDENT
&&
4594 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
4595 s
= define_find(tok
);
4597 /* we have a macro: we try to substitute */
4601 if (macro_subst_tok(&str
, &nested_list
, s
, &ml
) == 0) {
4602 /* substitution done, NOTE: maybe empty */
4603 tok_str_add(&str
, 0);
4604 macro_ptr
= str
.str
;
4605 macro_ptr_allocated
= str
.str
;
4612 /* end of macro or end of unget buffer */
4613 if (unget_buffer_enabled
) {
4614 macro_ptr
= unget_saved_macro_ptr
;
4615 unget_buffer_enabled
= 0;
4617 /* end of macro string: free it */
4618 tok_str_free(macro_ptr_allocated
);
4625 /* convert preprocessor tokens into C tokens */
4626 if (tok
== TOK_PPNUM
&&
4627 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
4628 parse_number((char *)tokc
.cstr
->data
);
4632 /* push back current token and set current token to 'last_tok'. Only
4633 identifier case handled for labels. */
4634 static inline void unget_tok(int last_tok
)
4638 unget_saved_macro_ptr
= macro_ptr
;
4639 unget_buffer_enabled
= 1;
4640 q
= unget_saved_buffer
;
4643 n
= tok_ext_size(tok
) - 1;
4646 *q
= 0; /* end of token string */
4651 void swap(int *p
, int *q
)
4659 void vsetc(CType
*type
, int r
, CValue
*vc
)
4663 if (vtop
>= vstack
+ (VSTACK_SIZE
- 1))
4664 error("memory full");
4665 /* cannot let cpu flags if other instruction are generated. Also
4666 avoid leaving VT_JMP anywhere except on the top of the stack
4667 because it would complicate the code generator. */
4668 if (vtop
>= vstack
) {
4669 v
= vtop
->r
& VT_VALMASK
;
4670 if (v
== VT_CMP
|| (v
& ~1) == VT_JMP
)
4676 vtop
->r2
= VT_CONST
;
4680 /* push integer constant */
4685 vsetc(&int_type
, VT_CONST
, &cval
);
4688 /* push long long constant */
4689 void vpushll(long long v
)
4695 vsetc(&ctype
, VT_CONST
, &cval
);
4698 /* Return a static symbol pointing to a section */
4699 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
4700 unsigned long offset
, unsigned long size
)
4706 sym
= global_identifier_push(v
, type
->t
| VT_STATIC
, 0);
4707 sym
->type
.ref
= type
->ref
;
4708 sym
->r
= VT_CONST
| VT_SYM
;
4709 put_extern_sym(sym
, sec
, offset
, size
);
4713 /* push a reference to a section offset by adding a dummy symbol */
4714 static void vpush_ref(CType
*type
, Section
*sec
, unsigned long offset
, unsigned long size
)
4719 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4720 vtop
->sym
= get_sym_ref(type
, sec
, offset
, size
);
4723 /* define a new external reference to a symbol 'v' of type 'u' */
4724 static Sym
*external_global_sym(int v
, CType
*type
, int r
)
4730 /* push forward reference */
4731 s
= global_identifier_push(v
, type
->t
| VT_EXTERN
, 0);
4732 s
->type
.ref
= type
->ref
;
4733 s
->r
= r
| VT_CONST
| VT_SYM
;
4738 /* define a new external reference to a symbol 'v' of type 'u' */
4739 static Sym
*external_sym(int v
, CType
*type
, int r
)
4745 /* push forward reference */
4746 s
= sym_push(v
, type
, r
| VT_CONST
| VT_SYM
, 0);
4747 s
->type
.t
|= VT_EXTERN
;
4749 if (!is_compatible_types(&s
->type
, type
))
4750 error("incompatible types for redefinition of '%s'",
4751 get_tok_str(v
, NULL
));
4756 /* push a reference to global symbol v */
4757 static void vpush_global_sym(CType
*type
, int v
)
4762 sym
= external_global_sym(v
, type
, 0);
4764 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4768 void vset(CType
*type
, int r
, int v
)
4773 vsetc(type
, r
, &cval
);
4776 void vseti(int r
, int v
)
4792 void vpushv(SValue
*v
)
4794 if (vtop
>= vstack
+ (VSTACK_SIZE
- 1))
4795 error("memory full");
4805 /* save r to the memory stack, and mark it as being free */
4806 void save_reg(int r
)
4808 int l
, saved
, size
, align
;
4812 /* modify all stack values */
4815 for(p
=vstack
;p
<=vtop
;p
++) {
4816 if ((p
->r
& VT_VALMASK
) == r
||
4817 ((p
->type
.t
& VT_BTYPE
) == VT_LLONG
&& (p
->r2
& VT_VALMASK
) == r
)) {
4818 /* must save value on stack if not already done */
4820 /* NOTE: must reload 'r' because r might be equal to r2 */
4821 r
= p
->r
& VT_VALMASK
;
4822 /* store register in the stack */
4824 if ((p
->r
& VT_LVAL
) ||
4825 (!is_float(type
->t
) && (type
->t
& VT_BTYPE
) != VT_LLONG
))
4826 #ifdef TCC_TARGET_X86_64
4827 type
= &char_pointer_type
;
4831 size
= type_size(type
, &align
);
4832 loc
= (loc
- size
) & -align
;
4833 sv
.type
.t
= type
->t
;
4834 sv
.r
= VT_LOCAL
| VT_LVAL
;
4837 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
4838 /* x86 specific: need to pop fp register ST0 if saved */
4839 if (r
== TREG_ST0
) {
4840 o(0xd9dd); /* fstp %st(1) */
4843 #ifndef TCC_TARGET_X86_64
4844 /* special long long case */
4845 if ((type
->t
& VT_BTYPE
) == VT_LLONG
) {
4853 /* mark that stack entry as being saved on the stack */
4854 if (p
->r
& VT_LVAL
) {
4855 /* also clear the bounded flag because the
4856 relocation address of the function was stored in
4858 p
->r
= (p
->r
& ~(VT_VALMASK
| VT_BOUNDED
)) | VT_LLOCAL
;
4860 p
->r
= lvalue_type(p
->type
.t
) | VT_LOCAL
;
4868 /* find a register of class 'rc2' with at most one reference on stack.
4869 * If none, call get_reg(rc) */
4870 int get_reg_ex(int rc
, int rc2
)
4875 for(r
=0;r
<NB_REGS
;r
++) {
4876 if (reg_classes
[r
] & rc2
) {
4879 for(p
= vstack
; p
<= vtop
; p
++) {
4880 if ((p
->r
& VT_VALMASK
) == r
||
4881 (p
->r2
& VT_VALMASK
) == r
)
4891 /* find a free register of class 'rc'. If none, save one register */
4897 /* find a free register */
4898 for(r
=0;r
<NB_REGS
;r
++) {
4899 if (reg_classes
[r
] & rc
) {
4900 for(p
=vstack
;p
<=vtop
;p
++) {
4901 if ((p
->r
& VT_VALMASK
) == r
||
4902 (p
->r2
& VT_VALMASK
) == r
)
4910 /* no register left : free the first one on the stack (VERY
4911 IMPORTANT to start from the bottom to ensure that we don't
4912 spill registers used in gen_opi()) */
4913 for(p
=vstack
;p
<=vtop
;p
++) {
4914 r
= p
->r
& VT_VALMASK
;
4915 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
))
4917 /* also look at second register (if long long) */
4918 r
= p
->r2
& VT_VALMASK
;
4919 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
)) {
4925 /* Should never comes here */
4929 /* save registers up to (vtop - n) stack entry */
4930 void save_regs(int n
)
4935 for(p
= vstack
;p
<= p1
; p
++) {
4936 r
= p
->r
& VT_VALMASK
;
4943 /* move register 's' to 'r', and flush previous value of r to memory
4945 void move_reg(int r
, int s
)
4958 /* get address of vtop (vtop MUST BE an lvalue) */
4961 vtop
->r
&= ~VT_LVAL
;
4962 /* tricky: if saved lvalue, then we can go back to lvalue */
4963 if ((vtop
->r
& VT_VALMASK
) == VT_LLOCAL
)
4964 vtop
->r
= (vtop
->r
& ~(VT_VALMASK
| VT_LVAL_TYPE
)) | VT_LOCAL
| VT_LVAL
;
4967 #ifdef CONFIG_TCC_BCHECK
4968 /* generate lvalue bound code */
4974 vtop
->r
&= ~VT_MUSTBOUND
;
4975 /* if lvalue, then use checking code before dereferencing */
4976 if (vtop
->r
& VT_LVAL
) {
4977 /* if not VT_BOUNDED value, then make one */
4978 if (!(vtop
->r
& VT_BOUNDED
)) {
4979 lval_type
= vtop
->r
& (VT_LVAL_TYPE
| VT_LVAL
);
4980 /* must save type because we must set it to int to get pointer */
4982 vtop
->type
.t
= VT_INT
;
4985 gen_bounded_ptr_add();
4986 vtop
->r
|= lval_type
;
4989 /* then check for dereferencing */
4990 gen_bounded_ptr_deref();
4995 /* store vtop a register belonging to class 'rc'. lvalues are
4996 converted to values. Cannot be used if cannot be converted to
4997 register value (such as structures). */
5000 int r
, rc2
, bit_pos
, bit_size
, size
, align
, i
;
5002 /* NOTE: get_reg can modify vstack[] */
5003 if (vtop
->type
.t
& VT_BITFIELD
) {
5006 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
5007 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
5008 /* remove bit field info to avoid loops */
5009 vtop
->type
.t
&= ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
5010 /* cast to int to propagate signedness in following ops */
5011 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
) {
5016 if((vtop
->type
.t
& VT_UNSIGNED
) ||
5017 (vtop
->type
.t
& VT_BTYPE
) == VT_BOOL
)
5018 type
.t
|= VT_UNSIGNED
;
5020 /* generate shifts */
5021 vpushi(bits
- (bit_pos
+ bit_size
));
5023 vpushi(bits
- bit_size
);
5024 /* NOTE: transformed to SHR if unsigned */
5028 if (is_float(vtop
->type
.t
) &&
5029 (vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
5032 unsigned long offset
;
5033 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
5037 /* XXX: unify with initializers handling ? */
5038 /* CPUs usually cannot use float constants, so we store them
5039 generically in data segment */
5040 size
= type_size(&vtop
->type
, &align
);
5041 offset
= (data_section
->data_offset
+ align
- 1) & -align
;
5042 data_section
->data_offset
= offset
;
5043 /* XXX: not portable yet */
5044 #if defined(__i386__) || defined(__x86_64__)
5045 /* Zero pad x87 tenbyte long doubles */
5046 if (size
== LDOUBLE_SIZE
)
5047 vtop
->c
.tab
[2] &= 0xffff;
5049 ptr
= section_ptr_add(data_section
, size
);
5051 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
5055 ptr
[i
] = vtop
->c
.tab
[size
-1-i
];
5059 ptr
[i
] = vtop
->c
.tab
[i
];
5060 sym
= get_sym_ref(&vtop
->type
, data_section
, offset
, size
<< 2);
5061 vtop
->r
|= VT_LVAL
| VT_SYM
;
5065 #ifdef CONFIG_TCC_BCHECK
5066 if (vtop
->r
& VT_MUSTBOUND
)
5070 r
= vtop
->r
& VT_VALMASK
;
5074 /* need to reload if:
5076 - lvalue (need to dereference pointer)
5077 - already a register, but not in the right class */
5078 if (r
>= VT_CONST
||
5079 (vtop
->r
& VT_LVAL
) ||
5080 !(reg_classes
[r
] & rc
) ||
5081 ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
&&
5082 !(reg_classes
[vtop
->r2
] & rc2
))) {
5084 #ifndef TCC_TARGET_X86_64
5085 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
) {
5087 unsigned long long ll
;
5088 /* two register type load : expand to two words
5090 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
5093 vtop
->c
.ui
= ll
; /* first word */
5095 vtop
->r
= r
; /* save register value */
5096 vpushi(ll
>> 32); /* second word */
5097 } else if (r
>= VT_CONST
|| /* XXX: test to VT_CONST incorrect ? */
5098 (vtop
->r
& VT_LVAL
)) {
5099 /* We do not want to modifier the long long
5100 pointer here, so the safest (and less
5101 efficient) is to save all the other registers
5102 in the stack. XXX: totally inefficient. */
5104 /* load from memory */
5107 vtop
[-1].r
= r
; /* save register value */
5108 /* increment pointer to get second word */
5109 vtop
->type
.t
= VT_INT
;
5115 /* move registers */
5118 vtop
[-1].r
= r
; /* save register value */
5119 vtop
->r
= vtop
[-1].r2
;
5121 /* allocate second register */
5125 /* write second register */
5129 if ((vtop
->r
& VT_LVAL
) && !is_float(vtop
->type
.t
)) {
5131 /* lvalue of scalar type : need to use lvalue type
5132 because of possible cast */
5135 /* compute memory access type */
5136 if (vtop
->r
& VT_LVAL_BYTE
)
5138 else if (vtop
->r
& VT_LVAL_SHORT
)
5140 if (vtop
->r
& VT_LVAL_UNSIGNED
)
5144 /* restore wanted type */
5147 /* one register type load */
5152 #ifdef TCC_TARGET_C67
5153 /* uses register pairs for doubles */
5154 if ((vtop
->type
.t
& VT_BTYPE
) == VT_DOUBLE
)
5161 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
5162 void gv2(int rc1
, int rc2
)
5166 /* generate more generic register first. But VT_JMP or VT_CMP
5167 values must be generated first in all cases to avoid possible
5169 v
= vtop
[0].r
& VT_VALMASK
;
5170 if (v
!= VT_CMP
&& (v
& ~1) != VT_JMP
&& rc1
<= rc2
) {
5175 /* test if reload is needed for first register */
5176 if ((vtop
[-1].r
& VT_VALMASK
) >= VT_CONST
) {
5186 /* test if reload is needed for first register */
5187 if ((vtop
[0].r
& VT_VALMASK
) >= VT_CONST
) {
5193 /* wrapper around RC_FRET to return a register by type */
5196 #ifdef TCC_TARGET_X86_64
5197 if (t
== VT_LDOUBLE
) {
5204 /* wrapper around REG_FRET to return a register by type */
5207 #ifdef TCC_TARGET_X86_64
5208 if (t
== VT_LDOUBLE
) {
5215 /* expand long long on stack in two int registers */
5220 u
= vtop
->type
.t
& VT_UNSIGNED
;
5223 vtop
[0].r
= vtop
[-1].r2
;
5224 vtop
[0].r2
= VT_CONST
;
5225 vtop
[-1].r2
= VT_CONST
;
5226 vtop
[0].type
.t
= VT_INT
| u
;
5227 vtop
[-1].type
.t
= VT_INT
| u
;
5230 #ifdef TCC_TARGET_ARM
5231 /* expand long long on stack */
5232 void lexpand_nr(void)
5236 u
= vtop
->type
.t
& VT_UNSIGNED
;
5238 vtop
->r2
= VT_CONST
;
5239 vtop
->type
.t
= VT_INT
| u
;
5240 v
=vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
);
5241 if (v
== VT_CONST
) {
5242 vtop
[-1].c
.ui
= vtop
->c
.ull
;
5243 vtop
->c
.ui
= vtop
->c
.ull
>> 32;
5245 } else if (v
== (VT_LVAL
|VT_CONST
) || v
== (VT_LVAL
|VT_LOCAL
)) {
5247 vtop
->r
= vtop
[-1].r
;
5248 } else if (v
> VT_CONST
) {
5252 vtop
->r
= vtop
[-1].r2
;
5253 vtop
[-1].r2
= VT_CONST
;
5254 vtop
[-1].type
.t
= VT_INT
| u
;
5258 /* build a long long from two ints */
5261 gv2(RC_INT
, RC_INT
);
5262 vtop
[-1].r2
= vtop
[0].r
;
5263 vtop
[-1].type
.t
= t
;
5267 /* rotate n first stack elements to the bottom
5268 I1 ... In -> I2 ... In I1 [top is right]
5276 for(i
=-n
+1;i
!=0;i
++)
5277 vtop
[i
] = vtop
[i
+1];
5281 /* rotate n first stack elements to the top
5282 I1 ... In -> In I1 ... I(n-1) [top is right]
5290 for(i
= 0;i
< n
- 1; i
++)
5291 vtop
[-i
] = vtop
[-i
- 1];
5295 #ifdef TCC_TARGET_ARM
5296 /* like vrott but in other direction
5297 In ... I1 -> I(n-1) ... I1 In [top is right]
5305 for(i
= n
- 1; i
> 0; i
--)
5306 vtop
[-i
] = vtop
[-i
+ 1];
5311 /* pop stack value */
5315 v
= vtop
->r
& VT_VALMASK
;
5316 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
5317 /* for x86, we need to pop the FP stack */
5318 if (v
== TREG_ST0
&& !nocode_wanted
) {
5319 o(0xd9dd); /* fstp %st(1) */
5322 if (v
== VT_JMP
|| v
== VT_JMPI
) {
5323 /* need to put correct jump if && or || without test */
5329 /* convert stack entry to register and duplicate its value in another
5337 if ((t
& VT_BTYPE
) == VT_LLONG
) {
5344 /* stack: H L L1 H1 */
5352 /* duplicate value */
5357 #ifdef TCC_TARGET_X86_64
5358 if ((t
& VT_BTYPE
) == VT_LDOUBLE
) {
5368 load(r1
, &sv
); /* move r to r1 */
5370 /* duplicates value */
5375 #ifndef TCC_TARGET_X86_64
5376 /* generate CPU independent (unsigned) long long operations */
5377 void gen_opl(int op
)
5379 int t
, a
, b
, op1
, c
, i
;
5381 unsigned short reg_iret
= REG_IRET
;
5382 unsigned short reg_lret
= REG_LRET
;
5388 func
= TOK___divdi3
;
5391 func
= TOK___udivdi3
;
5394 func
= TOK___moddi3
;
5397 func
= TOK___umoddi3
;
5404 /* call generic long long function */
5405 vpush_global_sym(&func_old_type
, func
);
5410 vtop
->r2
= reg_lret
;
5423 /* stack: L1 H1 L2 H2 */
5428 vtop
[-2] = vtop
[-3];
5431 /* stack: H1 H2 L1 L2 */
5437 /* stack: H1 H2 L1 L2 ML MH */
5440 /* stack: ML MH H1 H2 L1 L2 */
5444 /* stack: ML MH H1 L2 H2 L1 */
5449 /* stack: ML MH M1 M2 */
5452 } else if (op
== '+' || op
== '-') {
5453 /* XXX: add non carry method too (for MIPS or alpha) */
5459 /* stack: H1 H2 (L1 op L2) */
5462 gen_op(op1
+ 1); /* TOK_xxxC2 */
5465 /* stack: H1 H2 (L1 op L2) */
5468 /* stack: (L1 op L2) H1 H2 */
5470 /* stack: (L1 op L2) (H1 op H2) */
5478 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) {
5479 t
= vtop
[-1].type
.t
;
5483 /* stack: L H shift */
5485 /* constant: simpler */
5486 /* NOTE: all comments are for SHL. the other cases are
5487 done by swaping words */
5498 if (op
!= TOK_SAR
) {
5531 /* XXX: should provide a faster fallback on x86 ? */
5534 func
= TOK___ashrdi3
;
5537 func
= TOK___lshrdi3
;
5540 func
= TOK___ashldi3
;
5546 /* compare operations */
5552 /* stack: L1 H1 L2 H2 */
5554 vtop
[-1] = vtop
[-2];
5556 /* stack: L1 L2 H1 H2 */
5559 /* when values are equal, we need to compare low words. since
5560 the jump is inverted, we invert the test too. */
5563 else if (op1
== TOK_GT
)
5565 else if (op1
== TOK_ULT
)
5567 else if (op1
== TOK_UGT
)
5572 if (op1
!= TOK_NE
) {
5576 /* generate non equal test */
5577 /* XXX: NOT PORTABLE yet */
5581 #if defined(TCC_TARGET_I386)
5582 b
= psym(0x850f, 0);
5583 #elif defined(TCC_TARGET_ARM)
5585 o(0x1A000000 | encbranch(ind
, 0, 1));
5586 #elif defined(TCC_TARGET_C67)
5587 error("not implemented");
5589 #error not supported
5593 /* compare low. Always unsigned */
5597 else if (op1
== TOK_LE
)
5599 else if (op1
== TOK_GT
)
5601 else if (op1
== TOK_GE
)
5612 /* handle integer constant optimizations and various machine
5614 void gen_opic(int op
)
5616 int c1
, c2
, t1
, t2
, n
;
5619 typedef unsigned long long U
;
5623 t1
= v1
->type
.t
& VT_BTYPE
;
5624 t2
= v2
->type
.t
& VT_BTYPE
;
5628 else if (v1
->type
.t
& VT_UNSIGNED
)
5635 else if (v2
->type
.t
& VT_UNSIGNED
)
5640 /* currently, we cannot do computations with forward symbols */
5641 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5642 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5645 case '+': l1
+= l2
; break;
5646 case '-': l1
-= l2
; break;
5647 case '&': l1
&= l2
; break;
5648 case '^': l1
^= l2
; break;
5649 case '|': l1
|= l2
; break;
5650 case '*': l1
*= l2
; break;
5657 /* if division by zero, generate explicit division */
5660 error("division by zero in constant");
5664 default: l1
/= l2
; break;
5665 case '%': l1
%= l2
; break;
5666 case TOK_UDIV
: l1
= (U
)l1
/ l2
; break;
5667 case TOK_UMOD
: l1
= (U
)l1
% l2
; break;
5670 case TOK_SHL
: l1
<<= l2
; break;
5671 case TOK_SHR
: l1
= (U
)l1
>> l2
; break;
5672 case TOK_SAR
: l1
>>= l2
; break;
5674 case TOK_ULT
: l1
= (U
)l1
< (U
)l2
; break;
5675 case TOK_UGE
: l1
= (U
)l1
>= (U
)l2
; break;
5676 case TOK_EQ
: l1
= l1
== l2
; break;
5677 case TOK_NE
: l1
= l1
!= l2
; break;
5678 case TOK_ULE
: l1
= (U
)l1
<= (U
)l2
; break;
5679 case TOK_UGT
: l1
= (U
)l1
> (U
)l2
; break;
5680 case TOK_LT
: l1
= l1
< l2
; break;
5681 case TOK_GE
: l1
= l1
>= l2
; break;
5682 case TOK_LE
: l1
= l1
<= l2
; break;
5683 case TOK_GT
: l1
= l1
> l2
; break;
5685 case TOK_LAND
: l1
= l1
&& l2
; break;
5686 case TOK_LOR
: l1
= l1
|| l2
; break;
5693 /* if commutative ops, put c2 as constant */
5694 if (c1
&& (op
== '+' || op
== '&' || op
== '^' ||
5695 op
== '|' || op
== '*')) {
5697 c2
= c1
; //c = c1, c1 = c2, c2 = c;
5698 l2
= l1
; //l = l1, l1 = l2, l2 = l;
5700 /* Filter out NOP operations like x*1, x-0, x&-1... */
5701 if (c2
&& (((op
== '*' || op
== '/' || op
== TOK_UDIV
||
5704 ((op
== '+' || op
== '-' || op
== '|' || op
== '^' ||
5705 op
== TOK_SHL
|| op
== TOK_SHR
|| op
== TOK_SAR
) &&
5711 } else if (c2
&& (op
== '*' || op
== TOK_PDIV
|| op
== TOK_UDIV
)) {
5712 /* try to use shifts instead of muls or divs */
5713 if (l2
> 0 && (l2
& (l2
- 1)) == 0) {
5722 else if (op
== TOK_PDIV
)
5728 } else if (c2
&& (op
== '+' || op
== '-') &&
5729 ((vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) ==
5730 (VT_CONST
| VT_SYM
) ||
5731 (vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
)) == VT_LOCAL
)) {
5732 /* symbol + constant case */
5739 if (!nocode_wanted
) {
5740 /* call low level op generator */
5741 if (t1
== VT_LLONG
|| t2
== VT_LLONG
)
5752 /* generate a floating point operation with constant propagation */
5753 void gen_opif(int op
)
5761 /* currently, we cannot do computations with forward symbols */
5762 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5763 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5765 if (v1
->type
.t
== VT_FLOAT
) {
5768 } else if (v1
->type
.t
== VT_DOUBLE
) {
5776 /* NOTE: we only do constant propagation if finite number (not
5777 NaN or infinity) (ANSI spec) */
5778 if (!ieee_finite(f1
) || !ieee_finite(f2
))
5782 case '+': f1
+= f2
; break;
5783 case '-': f1
-= f2
; break;
5784 case '*': f1
*= f2
; break;
5788 error("division by zero in constant");
5793 /* XXX: also handles tests ? */
5797 /* XXX: overflow test ? */
5798 if (v1
->type
.t
== VT_FLOAT
) {
5800 } else if (v1
->type
.t
== VT_DOUBLE
) {
5808 if (!nocode_wanted
) {
5816 static int pointed_size(CType
*type
)
5819 return type_size(pointed_type(type
), &align
);
5822 static inline int is_null_pointer(SValue
*p
)
5824 if ((p
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
5826 return ((p
->type
.t
& VT_BTYPE
) == VT_INT
&& p
->c
.i
== 0) ||
5827 ((p
->type
.t
& VT_BTYPE
) == VT_LLONG
&& p
->c
.ll
== 0);
5830 static inline int is_integer_btype(int bt
)
5832 return (bt
== VT_BYTE
|| bt
== VT_SHORT
||
5833 bt
== VT_INT
|| bt
== VT_LLONG
);
5836 /* check types for comparison or substraction of pointers */
5837 static void check_comparison_pointer_types(SValue
*p1
, SValue
*p2
, int op
)
5839 CType
*type1
, *type2
, tmp_type1
, tmp_type2
;
5842 /* null pointers are accepted for all comparisons as gcc */
5843 if (is_null_pointer(p1
) || is_null_pointer(p2
))
5847 bt1
= type1
->t
& VT_BTYPE
;
5848 bt2
= type2
->t
& VT_BTYPE
;
5849 /* accept comparison between pointer and integer with a warning */
5850 if ((is_integer_btype(bt1
) || is_integer_btype(bt2
)) && op
!= '-') {
5851 if (op
!= TOK_LOR
&& op
!= TOK_LAND
)
5852 warning("comparison between pointer and integer");
5856 /* both must be pointers or implicit function pointers */
5857 if (bt1
== VT_PTR
) {
5858 type1
= pointed_type(type1
);
5859 } else if (bt1
!= VT_FUNC
)
5860 goto invalid_operands
;
5862 if (bt2
== VT_PTR
) {
5863 type2
= pointed_type(type2
);
5864 } else if (bt2
!= VT_FUNC
) {
5866 error("invalid operands to binary %s", get_tok_str(op
, NULL
));
5868 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
5869 (type2
->t
& VT_BTYPE
) == VT_VOID
)
5873 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5874 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5875 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
5876 /* gcc-like error if '-' is used */
5878 goto invalid_operands
;
5880 warning("comparison of distinct pointer types lacks a cast");
5884 /* generic gen_op: handles types problems */
5887 int u
, t1
, t2
, bt1
, bt2
, t
;
5890 t1
= vtop
[-1].type
.t
;
5891 t2
= vtop
[0].type
.t
;
5892 bt1
= t1
& VT_BTYPE
;
5893 bt2
= t2
& VT_BTYPE
;
5895 if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
5896 /* at least one operand is a pointer */
5897 /* relationnal op: must be both pointers */
5898 if (op
>= TOK_ULT
&& op
<= TOK_LOR
) {
5899 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5900 /* pointers are handled are unsigned */
5901 #ifdef TCC_TARGET_X86_64
5902 t
= VT_LLONG
| VT_UNSIGNED
;
5904 t
= VT_INT
| VT_UNSIGNED
;
5908 /* if both pointers, then it must be the '-' op */
5909 if (bt1
== VT_PTR
&& bt2
== VT_PTR
) {
5911 error("cannot use pointers here");
5912 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5913 /* XXX: check that types are compatible */
5914 u
= pointed_size(&vtop
[-1].type
);
5916 /* set to integer type */
5917 #ifdef TCC_TARGET_X86_64
5918 vtop
->type
.t
= VT_LLONG
;
5920 vtop
->type
.t
= VT_INT
;
5925 /* exactly one pointer : must be '+' or '-'. */
5926 if (op
!= '-' && op
!= '+')
5927 error("cannot use pointers here");
5928 /* Put pointer as first operand */
5929 if (bt2
== VT_PTR
) {
5933 type1
= vtop
[-1].type
;
5934 #ifdef TCC_TARGET_X86_64
5935 vpushll(pointed_size(&vtop
[-1].type
));
5937 /* XXX: cast to int ? (long long case) */
5938 vpushi(pointed_size(&vtop
[-1].type
));
5941 #ifdef CONFIG_TCC_BCHECK
5942 /* if evaluating constant expression, no code should be
5943 generated, so no bound check */
5944 if (do_bounds_check
&& !const_wanted
) {
5945 /* if bounded pointers, we generate a special code to
5952 gen_bounded_ptr_add();
5958 /* put again type if gen_opic() swaped operands */
5961 } else if (is_float(bt1
) || is_float(bt2
)) {
5962 /* compute bigger type and do implicit casts */
5963 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
5965 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
5970 /* floats can only be used for a few operations */
5971 if (op
!= '+' && op
!= '-' && op
!= '*' && op
!= '/' &&
5972 (op
< TOK_ULT
|| op
> TOK_GT
))
5973 error("invalid operands for binary operation");
5975 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
5976 /* cast to biggest op */
5978 /* convert to unsigned if it does not fit in a long long */
5979 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
5980 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
5984 /* integer operations */
5986 /* convert to unsigned if it does not fit in an integer */
5987 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
5988 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
5991 /* XXX: currently, some unsigned operations are explicit, so
5992 we modify them here */
5993 if (t
& VT_UNSIGNED
) {
6000 else if (op
== TOK_LT
)
6002 else if (op
== TOK_GT
)
6004 else if (op
== TOK_LE
)
6006 else if (op
== TOK_GE
)
6013 /* special case for shifts and long long: we keep the shift as
6015 if (op
== TOK_SHR
|| op
== TOK_SAR
|| op
== TOK_SHL
)
6022 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
6023 /* relationnal op: the result is an int */
6024 vtop
->type
.t
= VT_INT
;
6031 #ifndef TCC_TARGET_ARM
6032 /* generic itof for unsigned long long case */
6033 void gen_cvt_itof1(int t
)
6035 if ((vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
)) ==
6036 (VT_LLONG
| VT_UNSIGNED
)) {
6039 vpush_global_sym(&func_old_type
, TOK___floatundisf
);
6040 #if LDOUBLE_SIZE != 8
6041 else if (t
== VT_LDOUBLE
)
6042 vpush_global_sym(&func_old_type
, TOK___floatundixf
);
6045 vpush_global_sym(&func_old_type
, TOK___floatundidf
);
6049 vtop
->r
= reg_fret(t
);
6056 /* generic ftoi for unsigned long long case */
6057 void gen_cvt_ftoi1(int t
)
6061 if (t
== (VT_LLONG
| VT_UNSIGNED
)) {
6062 /* not handled natively */
6063 st
= vtop
->type
.t
& VT_BTYPE
;
6065 vpush_global_sym(&func_old_type
, TOK___fixunssfdi
);
6066 #if LDOUBLE_SIZE != 8
6067 else if (st
== VT_LDOUBLE
)
6068 vpush_global_sym(&func_old_type
, TOK___fixunsxfdi
);
6071 vpush_global_sym(&func_old_type
, TOK___fixunsdfdi
);
6076 vtop
->r2
= REG_LRET
;
6082 /* force char or short cast */
6083 void force_charshort_cast(int t
)
6087 /* XXX: add optimization if lvalue : just change type and offset */
6092 if (t
& VT_UNSIGNED
) {
6093 vpushi((1 << bits
) - 1);
6099 /* result must be signed or the SAR is converted to an SHL
6100 This was not the case when "t" was a signed short
6101 and the last value on the stack was an unsigned int */
6102 vtop
->type
.t
&= ~VT_UNSIGNED
;
6108 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
6109 static void gen_cast(CType
*type
)
6111 int sbt
, dbt
, sf
, df
, c
, p
;
6113 /* special delayed cast for char/short */
6114 /* XXX: in some cases (multiple cascaded casts), it may still
6116 if (vtop
->r
& VT_MUSTCAST
) {
6117 vtop
->r
&= ~VT_MUSTCAST
;
6118 force_charshort_cast(vtop
->type
.t
);
6121 /* bitfields first get cast to ints */
6122 if (vtop
->type
.t
& VT_BITFIELD
) {
6126 dbt
= type
->t
& (VT_BTYPE
| VT_UNSIGNED
);
6127 sbt
= vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
);
6132 c
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
6133 p
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == (VT_CONST
| VT_SYM
);
6135 /* constant case: we can do it now */
6136 /* XXX: in ISOC, cannot do it if error in convert */
6137 if (sbt
== VT_FLOAT
)
6138 vtop
->c
.ld
= vtop
->c
.f
;
6139 else if (sbt
== VT_DOUBLE
)
6140 vtop
->c
.ld
= vtop
->c
.d
;
6143 if ((sbt
& VT_BTYPE
) == VT_LLONG
) {
6144 if (sbt
& VT_UNSIGNED
)
6145 vtop
->c
.ld
= vtop
->c
.ull
;
6147 vtop
->c
.ld
= vtop
->c
.ll
;
6149 if (sbt
& VT_UNSIGNED
)
6150 vtop
->c
.ld
= vtop
->c
.ui
;
6152 vtop
->c
.ld
= vtop
->c
.i
;
6155 if (dbt
== VT_FLOAT
)
6156 vtop
->c
.f
= (float)vtop
->c
.ld
;
6157 else if (dbt
== VT_DOUBLE
)
6158 vtop
->c
.d
= (double)vtop
->c
.ld
;
6159 } else if (sf
&& dbt
== (VT_LLONG
|VT_UNSIGNED
)) {
6160 vtop
->c
.ull
= (unsigned long long)vtop
->c
.ld
;
6161 } else if (sf
&& dbt
== VT_BOOL
) {
6162 vtop
->c
.i
= (vtop
->c
.ld
!= 0);
6165 vtop
->c
.ll
= (long long)vtop
->c
.ld
;
6166 else if (sbt
== (VT_LLONG
|VT_UNSIGNED
))
6167 vtop
->c
.ll
= vtop
->c
.ull
;
6168 else if (sbt
& VT_UNSIGNED
)
6169 vtop
->c
.ll
= vtop
->c
.ui
;
6170 else if (sbt
!= VT_LLONG
)
6171 vtop
->c
.ll
= vtop
->c
.i
;
6173 if (dbt
== (VT_LLONG
|VT_UNSIGNED
))
6174 vtop
->c
.ull
= vtop
->c
.ll
;
6175 else if (dbt
== VT_BOOL
)
6176 vtop
->c
.i
= (vtop
->c
.ll
!= 0);
6177 else if (dbt
!= VT_LLONG
) {
6179 if ((dbt
& VT_BTYPE
) == VT_BYTE
)
6181 else if ((dbt
& VT_BTYPE
) == VT_SHORT
)
6184 if(dbt
& VT_UNSIGNED
)
6185 vtop
->c
.ui
= ((unsigned int)vtop
->c
.ll
<< s
) >> s
;
6187 vtop
->c
.i
= ((int)vtop
->c
.ll
<< s
) >> s
;
6190 } else if (p
&& dbt
== VT_BOOL
) {
6193 } else if (!nocode_wanted
) {
6194 /* non constant case: generate code */
6196 /* convert from fp to fp */
6199 /* convert int to fp */
6202 /* convert fp to int */
6203 if (dbt
== VT_BOOL
) {
6207 /* we handle char/short/etc... with generic code */
6208 if (dbt
!= (VT_INT
| VT_UNSIGNED
) &&
6209 dbt
!= (VT_LLONG
| VT_UNSIGNED
) &&
6213 if (dbt
== VT_INT
&& (type
->t
& (VT_BTYPE
| VT_UNSIGNED
)) != dbt
) {
6214 /* additional cast for char/short... */
6219 #ifndef TCC_TARGET_X86_64
6220 } else if ((dbt
& VT_BTYPE
) == VT_LLONG
) {
6221 if ((sbt
& VT_BTYPE
) != VT_LLONG
) {
6222 /* scalar to long long */
6223 /* machine independent conversion */
6225 /* generate high word */
6226 if (sbt
== (VT_INT
| VT_UNSIGNED
)) {
6230 if (sbt
== VT_PTR
) {
6231 /* cast from pointer to int before we apply
6232 shift operation, which pointers don't support*/
6233 gen_cast(&int_type
);
6239 /* patch second register */
6240 vtop
[-1].r2
= vtop
->r
;
6244 } else if ((dbt
& VT_BTYPE
) == VT_LLONG
||
6245 (dbt
& VT_BTYPE
) == VT_PTR
) {
6246 /* XXX: not sure if this is perfect... need more tests */
6247 if ((sbt
& VT_BTYPE
) != VT_LLONG
) {
6249 if (sbt
!= (VT_INT
| VT_UNSIGNED
) &&
6250 sbt
!= VT_PTR
&& sbt
!= VT_FUNC
) {
6251 /* x86_64 specific: movslq */
6253 o(0xc0 + (REG_VALUE(r
) << 3) + REG_VALUE(r
));
6257 } else if (dbt
== VT_BOOL
) {
6258 /* scalar to bool */
6261 } else if ((dbt
& VT_BTYPE
) == VT_BYTE
||
6262 (dbt
& VT_BTYPE
) == VT_SHORT
) {
6263 if (sbt
== VT_PTR
) {
6264 vtop
->type
.t
= VT_INT
;
6265 warning("nonportable conversion from pointer to char/short");
6267 force_charshort_cast(dbt
);
6268 } else if ((dbt
& VT_BTYPE
) == VT_INT
) {
6270 if (sbt
== VT_LLONG
) {
6271 /* from long long: just take low order word */
6275 /* if lvalue and single word type, nothing to do because
6276 the lvalue already contains the real type size (see
6277 VT_LVAL_xxx constants) */
6280 } else if ((dbt
& VT_BTYPE
) == VT_PTR
&& !(vtop
->r
& VT_LVAL
)) {
6281 /* if we are casting between pointer types,
6282 we must update the VT_LVAL_xxx size */
6283 vtop
->r
= (vtop
->r
& ~VT_LVAL_TYPE
)
6284 | (lvalue_type(type
->ref
->type
.t
) & VT_LVAL_TYPE
);
6289 /* return type size. Put alignment at 'a' */
6290 static int type_size(CType
*type
, int *a
)
6295 bt
= type
->t
& VT_BTYPE
;
6296 if (bt
== VT_STRUCT
) {
6301 } else if (bt
== VT_PTR
) {
6302 if (type
->t
& VT_ARRAY
) {
6306 ts
= type_size(&s
->type
, a
);
6308 if (ts
< 0 && s
->c
< 0)
6316 } else if (bt
== VT_LDOUBLE
) {
6318 return LDOUBLE_SIZE
;
6319 } else if (bt
== VT_DOUBLE
|| bt
== VT_LLONG
) {
6320 #ifdef TCC_TARGET_I386
6321 #ifdef TCC_TARGET_PE
6326 #elif defined(TCC_TARGET_ARM)
6336 } else if (bt
== VT_INT
|| bt
== VT_ENUM
|| bt
== VT_FLOAT
) {
6339 } else if (bt
== VT_SHORT
) {
6343 /* char, void, function, _Bool */
6349 /* return the pointed type of t */
6350 static inline CType
*pointed_type(CType
*type
)
6352 return &type
->ref
->type
;
6355 /* modify type so that its it is a pointer to type. */
6356 static void mk_pointer(CType
*type
)
6359 s
= sym_push(SYM_FIELD
, type
, 0, -1);
6360 type
->t
= VT_PTR
| (type
->t
& ~VT_TYPE
);
6364 /* compare function types. OLD functions match any new functions */
6365 static int is_compatible_func(CType
*type1
, CType
*type2
)
6371 if (!is_compatible_types(&s1
->type
, &s2
->type
))
6373 /* check func_call */
6374 if (FUNC_CALL(s1
->r
) != FUNC_CALL(s2
->r
))
6376 /* XXX: not complete */
6377 if (s1
->c
== FUNC_OLD
|| s2
->c
== FUNC_OLD
)
6381 while (s1
!= NULL
) {
6384 if (!is_compatible_parameter_types(&s1
->type
, &s2
->type
))
6394 /* return true if type1 and type2 are the same. If unqualified is
6395 true, qualifiers on the types are ignored.
6397 - enums are not checked as gcc __builtin_types_compatible_p ()
6399 static int compare_types(CType
*type1
, CType
*type2
, int unqualified
)
6403 t1
= type1
->t
& VT_TYPE
;
6404 t2
= type2
->t
& VT_TYPE
;
6406 /* strip qualifiers before comparing */
6407 t1
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6408 t2
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6410 /* XXX: bitfields ? */
6413 /* test more complicated cases */
6414 bt1
= t1
& VT_BTYPE
;
6415 if (bt1
== VT_PTR
) {
6416 type1
= pointed_type(type1
);
6417 type2
= pointed_type(type2
);
6418 return is_compatible_types(type1
, type2
);
6419 } else if (bt1
== VT_STRUCT
) {
6420 return (type1
->ref
== type2
->ref
);
6421 } else if (bt1
== VT_FUNC
) {
6422 return is_compatible_func(type1
, type2
);
6428 /* return true if type1 and type2 are exactly the same (including
6431 static int is_compatible_types(CType
*type1
, CType
*type2
)
6433 return compare_types(type1
,type2
,0);
6436 /* return true if type1 and type2 are the same (ignoring qualifiers).
6438 static int is_compatible_parameter_types(CType
*type1
, CType
*type2
)
6440 return compare_types(type1
,type2
,1);
6443 /* print a type. If 'varstr' is not NULL, then the variable is also
6444 printed in the type */
6446 /* XXX: add array and function pointers */
6447 void type_to_str(char *buf
, int buf_size
,
6448 CType
*type
, const char *varstr
)
6455 t
= type
->t
& VT_TYPE
;
6458 if (t
& VT_CONSTANT
)
6459 pstrcat(buf
, buf_size
, "const ");
6460 if (t
& VT_VOLATILE
)
6461 pstrcat(buf
, buf_size
, "volatile ");
6462 if (t
& VT_UNSIGNED
)
6463 pstrcat(buf
, buf_size
, "unsigned ");
6493 tstr
= "long double";
6495 pstrcat(buf
, buf_size
, tstr
);
6499 if (bt
== VT_STRUCT
)
6503 pstrcat(buf
, buf_size
, tstr
);
6504 v
= type
->ref
->v
& ~SYM_STRUCT
;
6505 if (v
>= SYM_FIRST_ANOM
)
6506 pstrcat(buf
, buf_size
, "<anonymous>");
6508 pstrcat(buf
, buf_size
, get_tok_str(v
, NULL
));
6512 type_to_str(buf
, buf_size
, &s
->type
, varstr
);
6513 pstrcat(buf
, buf_size
, "(");
6515 while (sa
!= NULL
) {
6516 type_to_str(buf1
, sizeof(buf1
), &sa
->type
, NULL
);
6517 pstrcat(buf
, buf_size
, buf1
);
6520 pstrcat(buf
, buf_size
, ", ");
6522 pstrcat(buf
, buf_size
, ")");
6526 pstrcpy(buf1
, sizeof(buf1
), "*");
6528 pstrcat(buf1
, sizeof(buf1
), varstr
);
6529 type_to_str(buf
, buf_size
, &s
->type
, buf1
);
6533 pstrcat(buf
, buf_size
, " ");
6534 pstrcat(buf
, buf_size
, varstr
);
6539 /* verify type compatibility to store vtop in 'dt' type, and generate
6541 static void gen_assign_cast(CType
*dt
)
6543 CType
*st
, *type1
, *type2
, tmp_type1
, tmp_type2
;
6544 char buf1
[256], buf2
[256];
6547 st
= &vtop
->type
; /* source type */
6548 dbt
= dt
->t
& VT_BTYPE
;
6549 sbt
= st
->t
& VT_BTYPE
;
6550 if (dt
->t
& VT_CONSTANT
)
6551 warning("assignment of read-only location");
6554 /* special cases for pointers */
6555 /* '0' can also be a pointer */
6556 if (is_null_pointer(vtop
))
6558 /* accept implicit pointer to integer cast with warning */
6559 if (is_integer_btype(sbt
)) {
6560 warning("assignment makes pointer from integer without a cast");
6563 type1
= pointed_type(dt
);
6564 /* a function is implicitely a function pointer */
6565 if (sbt
== VT_FUNC
) {
6566 if ((type1
->t
& VT_BTYPE
) != VT_VOID
&&
6567 !is_compatible_types(pointed_type(dt
), st
))
6574 type2
= pointed_type(st
);
6575 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
6576 (type2
->t
& VT_BTYPE
) == VT_VOID
) {
6577 /* void * can match anything */
6579 /* exact type match, except for unsigned */
6582 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
6583 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
6584 if (!is_compatible_types(&tmp_type1
, &tmp_type2
))
6585 warning("assignment from incompatible pointer type");
6587 /* check const and volatile */
6588 if ((!(type1
->t
& VT_CONSTANT
) && (type2
->t
& VT_CONSTANT
)) ||
6589 (!(type1
->t
& VT_VOLATILE
) && (type2
->t
& VT_VOLATILE
)))
6590 warning("assignment discards qualifiers from pointer target type");
6596 if (sbt
== VT_PTR
|| sbt
== VT_FUNC
) {
6597 warning("assignment makes integer from pointer without a cast");
6599 /* XXX: more tests */
6604 tmp_type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6605 tmp_type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6606 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
6608 type_to_str(buf1
, sizeof(buf1
), st
, NULL
);
6609 type_to_str(buf2
, sizeof(buf2
), dt
, NULL
);
6610 error("cannot cast '%s' to '%s'", buf1
, buf2
);
6618 /* store vtop in lvalue pushed on stack */
6621 int sbt
, dbt
, ft
, r
, t
, size
, align
, bit_size
, bit_pos
, rc
, delayed_cast
;
6623 ft
= vtop
[-1].type
.t
;
6624 sbt
= vtop
->type
.t
& VT_BTYPE
;
6625 dbt
= ft
& VT_BTYPE
;
6626 if (((sbt
== VT_INT
|| sbt
== VT_SHORT
) && dbt
== VT_BYTE
) ||
6627 (sbt
== VT_INT
&& dbt
== VT_SHORT
)) {
6628 /* optimize char/short casts */
6629 delayed_cast
= VT_MUSTCAST
;
6630 vtop
->type
.t
= ft
& (VT_TYPE
& ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
)));
6631 /* XXX: factorize */
6632 if (ft
& VT_CONSTANT
)
6633 warning("assignment of read-only location");
6636 if (!(ft
& VT_BITFIELD
))
6637 gen_assign_cast(&vtop
[-1].type
);
6640 if (sbt
== VT_STRUCT
) {
6641 /* if structure, only generate pointer */
6642 /* structure assignment : generate memcpy */
6643 /* XXX: optimize if small size */
6644 if (!nocode_wanted
) {
6645 size
= type_size(&vtop
->type
, &align
);
6649 vpush_global_sym(&func_old_type
, TOK_memcpy8
);
6650 else if(!(align
& 3))
6651 vpush_global_sym(&func_old_type
, TOK_memcpy4
);
6654 vpush_global_sym(&func_old_type
, TOK_memcpy
);
6658 vtop
->type
.t
= VT_PTR
;
6662 vtop
->type
.t
= VT_PTR
;
6674 /* leave source on stack */
6675 } else if (ft
& VT_BITFIELD
) {
6676 /* bitfield store handling */
6677 bit_pos
= (ft
>> VT_STRUCT_SHIFT
) & 0x3f;
6678 bit_size
= (ft
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
6679 /* remove bit field info to avoid loops */
6680 vtop
[-1].type
.t
= ft
& ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
6682 /* duplicate source into other register */
6687 if((ft
& VT_BTYPE
) == VT_BOOL
) {
6688 gen_cast(&vtop
[-1].type
);
6689 vtop
[-1].type
.t
= (vtop
[-1].type
.t
& ~VT_BTYPE
) | (VT_BYTE
| VT_UNSIGNED
);
6692 /* duplicate destination */
6694 vtop
[-1] = vtop
[-2];
6696 /* mask and shift source */
6697 if((ft
& VT_BTYPE
) != VT_BOOL
) {
6698 if((ft
& VT_BTYPE
) == VT_LLONG
) {
6699 vpushll((1ULL << bit_size
) - 1ULL);
6701 vpushi((1 << bit_size
) - 1);
6707 /* load destination, mask and or with source */
6709 if((ft
& VT_BTYPE
) == VT_LLONG
) {
6710 vpushll(~(((1ULL << bit_size
) - 1ULL) << bit_pos
));
6712 vpushi(~(((1 << bit_size
) - 1) << bit_pos
));
6719 /* pop off shifted source from "duplicate source..." above */
6723 #ifdef CONFIG_TCC_BCHECK
6724 /* bound check case */
6725 if (vtop
[-1].r
& VT_MUSTBOUND
) {
6731 if (!nocode_wanted
) {
6735 #ifdef TCC_TARGET_X86_64
6736 if ((ft
& VT_BTYPE
) == VT_LDOUBLE
) {
6741 r
= gv(rc
); /* generate value */
6742 /* if lvalue was saved on stack, must read it */
6743 if ((vtop
[-1].r
& VT_VALMASK
) == VT_LLOCAL
) {
6745 t
= get_reg(RC_INT
);
6746 #ifdef TCC_TARGET_X86_64
6751 sv
.r
= VT_LOCAL
| VT_LVAL
;
6752 sv
.c
.ul
= vtop
[-1].c
.ul
;
6754 vtop
[-1].r
= t
| VT_LVAL
;
6757 #ifndef TCC_TARGET_X86_64
6758 /* two word case handling : store second register at word + 4 */
6759 if ((ft
& VT_BTYPE
) == VT_LLONG
) {
6761 /* convert to int to increment easily */
6762 vtop
->type
.t
= VT_INT
;
6768 /* XXX: it works because r2 is spilled last ! */
6769 store(vtop
->r2
, vtop
- 1);
6774 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
6775 vtop
->r
|= delayed_cast
;
6779 /* post defines POST/PRE add. c is the token ++ or -- */
6780 void inc(int post
, int c
)
6783 vdup(); /* save lvalue */
6785 gv_dup(); /* duplicate value */
6790 vpushi(c
- TOK_MID
);
6792 vstore(); /* store value */
6794 vpop(); /* if post op, return saved value */
6797 /* Parse GNUC __attribute__ extension. Currently, the following
6798 extensions are recognized:
6799 - aligned(n) : set data/function alignment.
6800 - packed : force data alignment to 1
6801 - section(x) : generate data/code in this section.
6802 - unused : currently ignored, but may be used someday.
6803 - regparm(n) : pass function parameters in registers (i386 only)
6805 static void parse_attribute(AttributeDef
*ad
)
6809 while (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
) {
6813 while (tok
!= ')') {
6814 if (tok
< TOK_IDENT
)
6815 expect("attribute name");
6823 expect("section name");
6824 ad
->section
= find_section(tcc_state
, (char *)tokc
.cstr
->data
);
6833 if (n
<= 0 || (n
& (n
- 1)) != 0)
6834 error("alignment must be a positive power of two");
6847 /* currently, no need to handle it because tcc does not
6848 track unused objects */
6852 /* currently, no need to handle it because tcc does not
6853 track unused objects */
6858 FUNC_CALL(ad
->func_attr
) = FUNC_CDECL
;
6863 FUNC_CALL(ad
->func_attr
) = FUNC_STDCALL
;
6865 #ifdef TCC_TARGET_I386
6875 FUNC_CALL(ad
->func_attr
) = FUNC_FASTCALL1
+ n
- 1;
6881 FUNC_CALL(ad
->func_attr
) = FUNC_FASTCALLW
;
6885 FUNC_EXPORT(ad
->func_attr
) = 1;
6888 if (tcc_state
->warn_unsupported
)
6889 warning("'%s' attribute ignored", get_tok_str(t
, NULL
));
6890 /* skip parameters */
6892 int parenthesis
= 0;
6896 else if (tok
== ')')
6899 } while (parenthesis
&& tok
!= -1);
6912 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
6913 static void struct_decl(CType
*type
, int u
)
6915 int a
, v
, size
, align
, maxalign
, c
, offset
;
6916 int bit_size
, bit_pos
, bsize
, bt
, lbit_pos
, prevbt
;
6917 Sym
*s
, *ss
, *ass
, **ps
;
6921 a
= tok
; /* save decl type */
6926 /* struct already defined ? return it */
6928 expect("struct/union/enum name");
6932 error("invalid type");
6939 /* we put an undefined size for struct/union */
6940 s
= sym_push(v
| SYM_STRUCT
, &type1
, 0, -1);
6941 s
->r
= 0; /* default alignment is zero as gcc */
6942 /* put struct/union/enum name in type */
6950 error("struct/union/enum already defined");
6951 /* cannot be empty */
6953 /* non empty enums are not allowed */
6954 if (a
== TOK_ENUM
) {
6958 expect("identifier");
6964 /* enum symbols have static storage */
6965 ss
= sym_push(v
, &int_type
, VT_CONST
, c
);
6966 ss
->type
.t
|= VT_STATIC
;
6971 /* NOTE: we accept a trailing comma */
6982 while (tok
!= '}') {
6983 parse_btype(&btype
, &ad
);
6989 type_decl(&type1
, &ad
, &v
, TYPE_DIRECT
| TYPE_ABSTRACT
);
6990 if (v
== 0 && (type1
.t
& VT_BTYPE
) != VT_STRUCT
)
6991 expect("identifier");
6992 if ((type1
.t
& VT_BTYPE
) == VT_FUNC
||
6993 (type1
.t
& (VT_TYPEDEF
| VT_STATIC
| VT_EXTERN
| VT_INLINE
)))
6994 error("invalid type for '%s'",
6995 get_tok_str(v
, NULL
));
6999 bit_size
= expr_const();
7000 /* XXX: handle v = 0 case for messages */
7002 error("negative width in bit-field '%s'",
7003 get_tok_str(v
, NULL
));
7004 if (v
&& bit_size
== 0)
7005 error("zero width for bit-field '%s'",
7006 get_tok_str(v
, NULL
));
7008 size
= type_size(&type1
, &align
);
7010 if (align
< ad
.aligned
)
7012 } else if (ad
.packed
) {
7014 } else if (*tcc_state
->pack_stack_ptr
) {
7015 if (align
> *tcc_state
->pack_stack_ptr
)
7016 align
= *tcc_state
->pack_stack_ptr
;
7019 if (bit_size
>= 0) {
7020 bt
= type1
.t
& VT_BTYPE
;
7027 error("bitfields must have scalar type");
7029 if (bit_size
> bsize
) {
7030 error("width of '%s' exceeds its type",
7031 get_tok_str(v
, NULL
));
7032 } else if (bit_size
== bsize
) {
7033 /* no need for bit fields */
7035 } else if (bit_size
== 0) {
7036 /* XXX: what to do if only padding in a
7038 /* zero size: means to pad */
7041 /* we do not have enough room ?
7042 did the type change?
7044 if ((bit_pos
+ bit_size
) > bsize
||
7045 bt
!= prevbt
|| a
== TOK_UNION
)
7048 /* XXX: handle LSB first */
7049 type1
.t
|= VT_BITFIELD
|
7050 (bit_pos
<< VT_STRUCT_SHIFT
) |
7051 (bit_size
<< (VT_STRUCT_SHIFT
+ 6));
7052 bit_pos
+= bit_size
;
7058 if (v
!= 0 || (type1
.t
& VT_BTYPE
) == VT_STRUCT
) {
7059 /* add new memory data only if starting
7061 if (lbit_pos
== 0) {
7062 if (a
== TOK_STRUCT
) {
7063 c
= (c
+ align
- 1) & -align
;
7072 if (align
> maxalign
)
7076 printf("add field %s offset=%d",
7077 get_tok_str(v
, NULL
), offset
);
7078 if (type1
.t
& VT_BITFIELD
) {
7079 printf(" pos=%d size=%d",
7080 (type1
.t
>> VT_STRUCT_SHIFT
) & 0x3f,
7081 (type1
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f);
7086 if (v
== 0 && (type1
.t
& VT_BTYPE
) == VT_STRUCT
) {
7088 while ((ass
= ass
->next
) != NULL
) {
7089 ss
= sym_push(ass
->v
, &ass
->type
, 0, offset
+ ass
->c
);
7094 ss
= sym_push(v
| SYM_FIELD
, &type1
, 0, offset
);
7098 if (tok
== ';' || tok
== TOK_EOF
)
7105 /* store size and alignment */
7106 s
->c
= (c
+ maxalign
- 1) & -maxalign
;
7112 /* return 0 if no type declaration. otherwise, return the basic type
7115 static int parse_btype(CType
*type
, AttributeDef
*ad
)
7117 int t
, u
, type_found
, typespec_found
, typedef_found
;
7121 memset(ad
, 0, sizeof(AttributeDef
));
7129 /* currently, we really ignore extension */
7139 if ((t
& VT_BTYPE
) != 0)
7140 error("too many basic types");
7156 if ((t
& VT_BTYPE
) == VT_DOUBLE
) {
7157 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
7158 } else if ((t
& VT_BTYPE
) == VT_LONG
) {
7159 t
= (t
& ~VT_BTYPE
) | VT_LLONG
;
7173 if ((t
& VT_BTYPE
) == VT_LONG
) {
7174 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
7181 struct_decl(&type1
, VT_ENUM
);
7184 type
->ref
= type1
.ref
;
7188 struct_decl(&type1
, VT_STRUCT
);
7191 /* type modifiers */
7244 /* GNUC attribute */
7245 case TOK_ATTRIBUTE1
:
7246 case TOK_ATTRIBUTE2
:
7247 parse_attribute(ad
);
7254 parse_expr_type(&type1
);
7257 if (typespec_found
|| typedef_found
)
7260 if (!s
|| !(s
->type
.t
& VT_TYPEDEF
))
7263 t
|= (s
->type
.t
& ~VT_TYPEDEF
);
7264 type
->ref
= s
->type
.ref
;
7272 if ((t
& (VT_SIGNED
|VT_UNSIGNED
)) == (VT_SIGNED
|VT_UNSIGNED
))
7273 error("signed and unsigned modifier");
7274 if (tcc_state
->char_is_unsigned
) {
7275 if ((t
& (VT_SIGNED
|VT_UNSIGNED
|VT_BTYPE
)) == VT_BYTE
)
7280 /* long is never used as type */
7281 if ((t
& VT_BTYPE
) == VT_LONG
)
7282 #ifndef TCC_TARGET_X86_64
7283 t
= (t
& ~VT_BTYPE
) | VT_INT
;
7285 t
= (t
& ~VT_BTYPE
) | VT_LLONG
;
7291 /* convert a function parameter type (array to pointer and function to
7292 function pointer) */
7293 static inline void convert_parameter_type(CType
*pt
)
7295 /* remove const and volatile qualifiers (XXX: const could be used
7296 to indicate a const function parameter */
7297 pt
->t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7298 /* array must be transformed to pointer according to ANSI C */
7300 if ((pt
->t
& VT_BTYPE
) == VT_FUNC
) {
7305 static void post_type(CType
*type
, AttributeDef
*ad
)
7307 int n
, l
, t1
, arg_size
, align
;
7308 Sym
**plast
, *s
, *first
;
7313 /* function declaration */
7321 /* read param name and compute offset */
7322 if (l
!= FUNC_OLD
) {
7323 if (!parse_btype(&pt
, &ad1
)) {
7325 error("invalid type");
7332 if ((pt
.t
& VT_BTYPE
) == VT_VOID
&& tok
== ')')
7334 type_decl(&pt
, &ad1
, &n
, TYPE_DIRECT
| TYPE_ABSTRACT
);
7335 if ((pt
.t
& VT_BTYPE
) == VT_VOID
)
7336 error("parameter declared as void");
7337 arg_size
+= (type_size(&pt
, &align
) + 3) & ~3;
7342 expect("identifier");
7346 convert_parameter_type(&pt
);
7347 s
= sym_push(n
| SYM_FIELD
, &pt
, 0, 0);
7353 if (l
== FUNC_NEW
&& tok
== TOK_DOTS
) {
7360 /* if no parameters, then old type prototype */
7364 t1
= type
->t
& VT_STORAGE
;
7365 /* NOTE: const is ignored in returned type as it has a special
7366 meaning in gcc / C++ */
7367 type
->t
&= ~(VT_STORAGE
| VT_CONSTANT
);
7368 post_type(type
, ad
);
7369 /* we push a anonymous symbol which will contain the function prototype */
7370 FUNC_ARGS(ad
->func_attr
) = arg_size
;
7371 s
= sym_push(SYM_FIELD
, type
, ad
->func_attr
, l
);
7373 type
->t
= t1
| VT_FUNC
;
7375 } else if (tok
== '[') {
7376 /* array definition */
7378 if (tok
== TOK_RESTRICT1
)
7384 error("invalid array size");
7387 /* parse next post type */
7388 t1
= type
->t
& VT_STORAGE
;
7389 type
->t
&= ~VT_STORAGE
;
7390 post_type(type
, ad
);
7392 /* we push a anonymous symbol which will contain the array
7394 s
= sym_push(SYM_FIELD
, type
, 0, n
);
7395 type
->t
= t1
| VT_ARRAY
| VT_PTR
;
7400 /* Parse a type declaration (except basic type), and return the type
7401 in 'type'. 'td' is a bitmask indicating which kind of type decl is
7402 expected. 'type' should contain the basic type. 'ad' is the
7403 attribute definition of the basic type. It can be modified by
7406 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
)
7409 CType type1
, *type2
;
7412 while (tok
== '*') {
7420 qualifiers
|= VT_CONSTANT
;
7425 qualifiers
|= VT_VOLATILE
;
7433 type
->t
|= qualifiers
;
7436 /* XXX: clarify attribute handling */
7437 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
7438 parse_attribute(ad
);
7440 /* recursive type */
7441 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
7442 type1
.t
= 0; /* XXX: same as int */
7445 /* XXX: this is not correct to modify 'ad' at this point, but
7446 the syntax is not clear */
7447 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
7448 parse_attribute(ad
);
7449 type_decl(&type1
, ad
, v
, td
);
7452 /* type identifier */
7453 if (tok
>= TOK_IDENT
&& (td
& TYPE_DIRECT
)) {
7457 if (!(td
& TYPE_ABSTRACT
))
7458 expect("identifier");
7462 post_type(type
, ad
);
7463 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
7464 parse_attribute(ad
);
7467 /* append type at the end of type1 */
7480 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
7481 static int lvalue_type(int t
)
7486 if (bt
== VT_BYTE
|| bt
== VT_BOOL
)
7488 else if (bt
== VT_SHORT
)
7492 if (t
& VT_UNSIGNED
)
7493 r
|= VT_LVAL_UNSIGNED
;
7497 /* indirection with full error checking and bound check */
7498 static void indir(void)
7500 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
) {
7501 if ((vtop
->type
.t
& VT_BTYPE
) == VT_FUNC
)
7505 if ((vtop
->r
& VT_LVAL
) && !nocode_wanted
)
7507 vtop
->type
= *pointed_type(&vtop
->type
);
7508 /* Arrays and functions are never lvalues */
7509 if (!(vtop
->type
.t
& VT_ARRAY
)
7510 && (vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
) {
7511 vtop
->r
|= lvalue_type(vtop
->type
.t
);
7512 /* if bound checking, the referenced pointer must be checked */
7513 if (do_bounds_check
)
7514 vtop
->r
|= VT_MUSTBOUND
;
7518 /* pass a parameter to a function and do type checking and casting */
7519 static void gfunc_param_typed(Sym
*func
, Sym
*arg
)
7524 func_type
= func
->c
;
7525 if (func_type
== FUNC_OLD
||
7526 (func_type
== FUNC_ELLIPSIS
&& arg
== NULL
)) {
7527 /* default casting : only need to convert float to double */
7528 if ((vtop
->type
.t
& VT_BTYPE
) == VT_FLOAT
) {
7532 } else if (arg
== NULL
) {
7533 error("too many arguments to function");
7536 type
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
7537 gen_assign_cast(&type
);
7541 /* parse an expression of the form '(type)' or '(expr)' and return its
7543 static void parse_expr_type(CType
*type
)
7549 if (parse_btype(type
, &ad
)) {
7550 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
7557 static void parse_type(CType
*type
)
7562 if (!parse_btype(type
, &ad
)) {
7565 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
7568 static void vpush_tokc(int t
)
7572 vsetc(&type
, VT_CONST
, &tokc
);
7575 static void unary(void)
7577 int n
, t
, align
, size
, r
;
7582 /* XXX: GCC 2.95.3 does not generate a table although it should be
7596 vpush_tokc(VT_INT
| VT_UNSIGNED
);
7600 vpush_tokc(VT_LLONG
);
7604 vpush_tokc(VT_LLONG
| VT_UNSIGNED
);
7608 vpush_tokc(VT_FLOAT
);
7612 vpush_tokc(VT_DOUBLE
);
7616 vpush_tokc(VT_LDOUBLE
);
7619 case TOK___FUNCTION__
:
7621 goto tok_identifier
;
7627 /* special function name identifier */
7628 len
= strlen(funcname
) + 1;
7629 /* generate char[len] type */
7634 vpush_ref(&type
, data_section
, data_section
->data_offset
, len
);
7635 ptr
= section_ptr_add(data_section
, len
);
7636 memcpy(ptr
, funcname
, len
);
7641 #ifdef TCC_TARGET_PE
7642 t
= VT_SHORT
| VT_UNSIGNED
;
7648 /* string parsing */
7651 if (tcc_state
->warn_write_strings
)
7656 memset(&ad
, 0, sizeof(AttributeDef
));
7657 decl_initializer_alloc(&type
, &ad
, VT_CONST
, 2, 0, 0);
7662 if (parse_btype(&type
, &ad
)) {
7663 type_decl(&type
, &ad
, &n
, TYPE_ABSTRACT
);
7665 /* check ISOC99 compound literal */
7667 /* data is allocated locally by default */
7672 /* all except arrays are lvalues */
7673 if (!(type
.t
& VT_ARRAY
))
7674 r
|= lvalue_type(type
.t
);
7675 memset(&ad
, 0, sizeof(AttributeDef
));
7676 decl_initializer_alloc(&type
, &ad
, r
, 1, 0, 0);
7681 } else if (tok
== '{') {
7682 /* save all registers */
7684 /* statement expression : we do not accept break/continue
7685 inside as GCC does */
7686 block(NULL
, NULL
, NULL
, NULL
, 0, 1);
7701 /* functions names must be treated as function pointers,
7702 except for unary '&' and sizeof. Since we consider that
7703 functions are not lvalues, we only have to handle it
7704 there and in function calls. */
7705 /* arrays can also be used although they are not lvalues */
7706 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
&&
7707 !(vtop
->type
.t
& VT_ARRAY
) && !(vtop
->type
.t
& VT_LLOCAL
))
7709 mk_pointer(&vtop
->type
);
7715 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) {
7717 boolean
.t
= VT_BOOL
;
7719 vtop
->c
.i
= !vtop
->c
.i
;
7720 } else if ((vtop
->r
& VT_VALMASK
) == VT_CMP
)
7721 vtop
->c
.i
= vtop
->c
.i
^ 1;
7724 vseti(VT_JMP
, gtst(1, 0));
7735 /* in order to force cast, we add zero */
7737 if ((vtop
->type
.t
& VT_BTYPE
) == VT_PTR
)
7738 error("pointer not accepted for unary plus");
7748 parse_expr_type(&type
);
7752 size
= type_size(&type
, &align
);
7753 if (t
== TOK_SIZEOF
) {
7755 error("sizeof applied to an incomplete type");
7760 vtop
->type
.t
|= VT_UNSIGNED
;
7763 case TOK_builtin_types_compatible_p
:
7772 type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7773 type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7774 vpushi(is_compatible_types(&type1
, &type2
));
7777 case TOK_builtin_constant_p
:
7779 int saved_nocode_wanted
, res
;
7782 saved_nocode_wanted
= nocode_wanted
;
7785 res
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
7787 nocode_wanted
= saved_nocode_wanted
;
7792 case TOK_builtin_frame_address
:
7797 if (tok
!= TOK_CINT
) {
7798 error("__builtin_frame_address only takes integers");
7801 error("TCC only supports __builtin_frame_address(0)");
7807 vset(&type
, VT_LOCAL
, 0);
7810 #ifdef TCC_TARGET_X86_64
7811 case TOK_builtin_malloc
:
7813 goto tok_identifier
;
7814 case TOK_builtin_free
:
7816 goto tok_identifier
;
7833 goto tok_identifier
;
7835 /* allow to take the address of a label */
7836 if (tok
< TOK_UIDENT
)
7837 expect("label identifier");
7838 s
= label_find(tok
);
7840 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
7842 if (s
->r
== LABEL_DECLARED
)
7843 s
->r
= LABEL_FORWARD
;
7846 s
->type
.t
= VT_VOID
;
7847 mk_pointer(&s
->type
);
7848 s
->type
.t
|= VT_STATIC
;
7850 vset(&s
->type
, VT_CONST
| VT_SYM
, 0);
7859 expect("identifier");
7863 error("'%s' undeclared", get_tok_str(t
, NULL
));
7864 /* for simple function calls, we tolerate undeclared
7865 external reference to int() function */
7866 if (tcc_state
->warn_implicit_function_declaration
)
7867 warning("implicit declaration of function '%s'",
7868 get_tok_str(t
, NULL
));
7869 s
= external_global_sym(t
, &func_old_type
, 0);
7871 if ((s
->type
.t
& (VT_STATIC
| VT_INLINE
| VT_BTYPE
)) ==
7872 (VT_STATIC
| VT_INLINE
| VT_FUNC
)) {
7873 /* if referencing an inline function, then we generate a
7874 symbol to it if not already done. It will have the
7875 effect to generate code for it at the end of the
7876 compilation unit. Inline function as always
7877 generated in the text section. */
7879 put_extern_sym(s
, text_section
, 0, 0);
7880 r
= VT_SYM
| VT_CONST
;
7884 vset(&s
->type
, r
, s
->c
);
7885 /* if forward reference, we must point to s */
7886 if (vtop
->r
& VT_SYM
) {
7893 /* post operations */
7895 if (tok
== TOK_INC
|| tok
== TOK_DEC
) {
7898 } else if (tok
== '.' || tok
== TOK_ARROW
) {
7900 if (tok
== TOK_ARROW
)
7905 /* expect pointer on structure */
7906 if ((vtop
->type
.t
& VT_BTYPE
) != VT_STRUCT
)
7907 expect("struct or union");
7911 while ((s
= s
->next
) != NULL
) {
7916 error("field not found: %s", get_tok_str(tok
& ~SYM_FIELD
, NULL
));
7917 /* add field offset to pointer */
7918 vtop
->type
= char_pointer_type
; /* change type to 'char *' */
7921 /* change type to field type, and set to lvalue */
7922 vtop
->type
= s
->type
;
7923 /* an array is never an lvalue */
7924 if (!(vtop
->type
.t
& VT_ARRAY
)) {
7925 vtop
->r
|= lvalue_type(vtop
->type
.t
);
7926 /* if bound checking, the referenced pointer must be checked */
7927 if (do_bounds_check
)
7928 vtop
->r
|= VT_MUSTBOUND
;
7931 } else if (tok
== '[') {
7937 } else if (tok
== '(') {
7943 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
) {
7944 /* pointer test (no array accepted) */
7945 if ((vtop
->type
.t
& (VT_BTYPE
| VT_ARRAY
)) == VT_PTR
) {
7946 vtop
->type
= *pointed_type(&vtop
->type
);
7947 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
)
7951 expect("function pointer");
7954 vtop
->r
&= ~VT_LVAL
; /* no lvalue */
7956 /* get return type */
7959 sa
= s
->next
; /* first parameter */
7962 /* compute first implicit argument if a structure is returned */
7963 if ((s
->type
.t
& VT_BTYPE
) == VT_STRUCT
) {
7964 /* get some space for the returned structure */
7965 size
= type_size(&s
->type
, &align
);
7966 loc
= (loc
- size
) & -align
;
7968 ret
.r
= VT_LOCAL
| VT_LVAL
;
7969 /* pass it as 'int' to avoid structure arg passing
7971 vseti(VT_LOCAL
, loc
);
7976 /* return in register */
7977 if (is_float(ret
.type
.t
)) {
7978 ret
.r
= reg_fret(ret
.type
.t
);
7980 if ((ret
.type
.t
& VT_BTYPE
) == VT_LLONG
)
7989 gfunc_param_typed(s
, sa
);
7999 error("too few arguments to function");
8001 if (!nocode_wanted
) {
8002 gfunc_call(nb_args
);
8004 vtop
-= (nb_args
+ 1);
8007 vsetc(&ret
.type
, ret
.r
, &ret
.c
);
8015 static void uneq(void)
8021 (tok
>= TOK_A_MOD
&& tok
<= TOK_A_DIV
) ||
8022 tok
== TOK_A_XOR
|| tok
== TOK_A_OR
||
8023 tok
== TOK_A_SHL
|| tok
== TOK_A_SAR
) {
8038 static void expr_prod(void)
8043 while (tok
== '*' || tok
== '/' || tok
== '%') {
8051 static void expr_sum(void)
8056 while (tok
== '+' || tok
== '-') {
8064 static void expr_shift(void)
8069 while (tok
== TOK_SHL
|| tok
== TOK_SAR
) {
8077 static void expr_cmp(void)
8082 while ((tok
>= TOK_ULE
&& tok
<= TOK_GT
) ||
8083 tok
== TOK_ULT
|| tok
== TOK_UGE
) {
8091 static void expr_cmpeq(void)
8096 while (tok
== TOK_EQ
|| tok
== TOK_NE
) {
8104 static void expr_and(void)
8107 while (tok
== '&') {
8114 static void expr_xor(void)
8117 while (tok
== '^') {
8124 static void expr_or(void)
8127 while (tok
== '|') {
8134 /* XXX: fix this mess */
8135 static void expr_land_const(void)
8138 while (tok
== TOK_LAND
) {
8145 /* XXX: fix this mess */
8146 static void expr_lor_const(void)
8149 while (tok
== TOK_LOR
) {
8156 /* only used if non constant */
8157 static void expr_land(void)
8162 if (tok
== TOK_LAND
) {
8167 if (tok
!= TOK_LAND
) {
8177 static void expr_lor(void)
8182 if (tok
== TOK_LOR
) {
8187 if (tok
!= TOK_LOR
) {
8197 /* XXX: better constant handling */
8198 static void expr_eq(void)
8200 int tt
, u
, r1
, r2
, rc
, t1
, t2
, bt1
, bt2
;
8202 CType type
, type1
, type2
;
8209 boolean
.t
= VT_BOOL
;
8215 if (tok
!= ':' || !gnu_ext
) {
8230 if (vtop
!= vstack
) {
8231 /* needed to avoid having different registers saved in
8233 if (is_float(vtop
->type
.t
)) {
8235 #ifdef TCC_TARGET_X86_64
8236 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LDOUBLE
) {
8246 if (tok
== ':' && gnu_ext
) {
8254 sv
= *vtop
; /* save value to handle it later */
8255 vtop
--; /* no vpop so that FP stack is not flushed */
8263 bt1
= t1
& VT_BTYPE
;
8265 bt2
= t2
& VT_BTYPE
;
8266 /* cast operands to correct type according to ISOC rules */
8267 if (is_float(bt1
) || is_float(bt2
)) {
8268 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
8269 type
.t
= VT_LDOUBLE
;
8270 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
8275 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
8276 /* cast to biggest op */
8278 /* convert to unsigned if it does not fit in a long long */
8279 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
8280 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
8281 type
.t
|= VT_UNSIGNED
;
8282 } else if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
8283 /* XXX: test pointer compatibility */
8285 } else if (bt1
== VT_FUNC
|| bt2
== VT_FUNC
) {
8286 /* XXX: test function pointer compatibility */
8288 } else if (bt1
== VT_STRUCT
|| bt2
== VT_STRUCT
) {
8289 /* XXX: test structure compatibility */
8291 } else if (bt1
== VT_VOID
|| bt2
== VT_VOID
) {
8292 /* NOTE: as an extension, we accept void on only one side */
8295 /* integer operations */
8297 /* convert to unsigned if it does not fit in an integer */
8298 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
8299 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
8300 type
.t
|= VT_UNSIGNED
;
8303 /* now we convert second operand */
8305 if (VT_STRUCT
== (vtop
->type
.t
& VT_BTYPE
))
8308 if (is_float(type
.t
)) {
8310 #ifdef TCC_TARGET_X86_64
8311 if ((type
.t
& VT_BTYPE
) == VT_LDOUBLE
) {
8315 } else if ((type
.t
& VT_BTYPE
) == VT_LLONG
) {
8316 /* for long longs, we use fixed registers to avoid having
8317 to handle a complicated move */
8322 /* this is horrible, but we must also convert first
8326 /* put again first value and cast it */
8329 if (VT_STRUCT
== (vtop
->type
.t
& VT_BTYPE
))
8339 static void gexpr(void)
8350 /* parse an expression and return its type without any side effect. */
8351 static void expr_type(CType
*type
)
8353 int saved_nocode_wanted
;
8355 saved_nocode_wanted
= nocode_wanted
;
8360 nocode_wanted
= saved_nocode_wanted
;
8363 /* parse a unary expression and return its type without any side
8365 static void unary_type(CType
*type
)
8377 /* parse a constant expression and return value in vtop. */
8378 static void expr_const1(void)
8387 /* parse an integer constant and return its value. */
8388 static int expr_const(void)
8392 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
8393 expect("constant expression");
8399 /* return the label token if current token is a label, otherwise
8401 static int is_label(void)
8405 /* fast test first */
8406 if (tok
< TOK_UIDENT
)
8408 /* no need to save tokc because tok is an identifier */
8415 unget_tok(last_tok
);
8420 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
8421 int case_reg
, int is_expr
)
8426 /* generate line number info */
8428 (last_line_num
!= file
->line_num
|| last_ind
!= ind
)) {
8429 put_stabn(N_SLINE
, 0, file
->line_num
, ind
- func_ind
);
8431 last_line_num
= file
->line_num
;
8435 /* default return value is (void) */
8437 vtop
->type
.t
= VT_VOID
;
8440 if (tok
== TOK_IF
) {
8447 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
8449 if (c
== TOK_ELSE
) {
8453 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
8454 gsym(d
); /* patch else jmp */
8457 } else if (tok
== TOK_WHILE
) {
8465 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
8469 } else if (tok
== '{') {
8473 /* record local declaration stack position */
8475 llabel
= local_label_stack
;
8476 /* handle local labels declarations */
8477 if (tok
== TOK_LABEL
) {
8480 if (tok
< TOK_UIDENT
)
8481 expect("label identifier");
8482 label_push(&local_label_stack
, tok
, LABEL_DECLARED
);
8492 while (tok
!= '}') {
8497 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
8500 /* pop locally defined labels */
8501 label_pop(&local_label_stack
, llabel
);
8502 /* pop locally defined symbols */
8504 /* XXX: this solution makes only valgrind happy...
8505 triggered by gcc.c-torture/execute/20000917-1.c */
8507 switch(vtop
->type
.t
& VT_BTYPE
) {
8512 for(p
=vtop
->type
.ref
;p
;p
=p
->prev
)
8514 error("unsupported expression type");
8517 sym_pop(&local_stack
, s
);
8519 } else if (tok
== TOK_RETURN
) {
8523 gen_assign_cast(&func_vt
);
8524 if ((func_vt
.t
& VT_BTYPE
) == VT_STRUCT
) {
8526 /* if returning structure, must copy it to implicit
8527 first pointer arg location */
8530 size
= type_size(&func_vt
,&align
);
8533 if((vtop
->r
!= (VT_LOCAL
| VT_LVAL
) || (vtop
->c
.i
& 3))
8537 loc
= (loc
- size
) & -4;
8540 vset(&type
, VT_LOCAL
| VT_LVAL
, addr
);
8543 vset(&int_type
, VT_LOCAL
| VT_LVAL
, addr
);
8545 vtop
->type
= int_type
;
8551 vset(&type
, VT_LOCAL
| VT_LVAL
, func_vc
);
8554 /* copy structure value to pointer */
8559 } else if (is_float(func_vt
.t
)) {
8560 gv(rc_fret(func_vt
.t
));
8564 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
8567 rsym
= gjmp(rsym
); /* jmp */
8568 } else if (tok
== TOK_BREAK
) {
8571 error("cannot break");
8572 *bsym
= gjmp(*bsym
);
8575 } else if (tok
== TOK_CONTINUE
) {
8578 error("cannot continue");
8579 *csym
= gjmp(*csym
);
8582 } else if (tok
== TOK_FOR
) {
8609 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
8614 if (tok
== TOK_DO
) {
8619 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
8630 if (tok
== TOK_SWITCH
) {
8634 /* XXX: other types than integer */
8635 case_reg
= gv(RC_INT
);
8639 b
= gjmp(0); /* jump to first case */
8641 block(&a
, csym
, &b
, &c
, case_reg
, 0);
8642 /* if no default, jmp after switch */
8650 if (tok
== TOK_CASE
) {
8657 if (gnu_ext
&& tok
== TOK_DOTS
) {
8661 warning("empty case range");
8663 /* since a case is like a label, we must skip it with a jmp */
8670 *case_sym
= gtst(1, 0);
8673 *case_sym
= gtst(1, 0);
8677 *case_sym
= gtst(1, *case_sym
);
8682 goto block_after_label
;
8684 if (tok
== TOK_DEFAULT
) {
8690 error("too many 'default'");
8693 goto block_after_label
;
8695 if (tok
== TOK_GOTO
) {
8697 if (tok
== '*' && gnu_ext
) {
8701 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
8704 } else if (tok
>= TOK_UIDENT
) {
8705 s
= label_find(tok
);
8706 /* put forward definition if needed */
8708 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
8710 if (s
->r
== LABEL_DECLARED
)
8711 s
->r
= LABEL_FORWARD
;
8713 /* label already defined */
8714 if (s
->r
& LABEL_FORWARD
)
8715 s
->next
= (void *)gjmp((long)s
->next
);
8717 gjmp_addr((long)s
->next
);
8720 expect("label identifier");
8723 } else if (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
) {
8731 if (s
->r
== LABEL_DEFINED
)
8732 error("duplicate label '%s'", get_tok_str(s
->v
, NULL
));
8733 gsym((long)s
->next
);
8734 s
->r
= LABEL_DEFINED
;
8736 s
= label_push(&global_label_stack
, b
, LABEL_DEFINED
);
8738 s
->next
= (void *)ind
;
8739 /* we accept this, but it is a mistake */
8742 warning("deprecated use of label at end of compound statement");
8746 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
8749 /* expression case */
8764 /* t is the array or struct type. c is the array or struct
8765 address. cur_index/cur_field is the pointer to the current
8766 value. 'size_only' is true if only size info is needed (only used
8768 static void decl_designator(CType
*type
, Section
*sec
, unsigned long c
,
8769 int *cur_index
, Sym
**cur_field
,
8773 int notfirst
, index
, index_last
, align
, l
, nb_elems
, elem_size
;
8779 if (gnu_ext
&& (l
= is_label()) != 0)
8781 while (tok
== '[' || tok
== '.') {
8783 if (!(type
->t
& VT_ARRAY
))
8784 expect("array type");
8787 index
= expr_const();
8788 if (index
< 0 || (s
->c
>= 0 && index
>= s
->c
))
8789 expect("invalid index");
8790 if (tok
== TOK_DOTS
&& gnu_ext
) {
8792 index_last
= expr_const();
8793 if (index_last
< 0 ||
8794 (s
->c
>= 0 && index_last
>= s
->c
) ||
8796 expect("invalid index");
8802 *cur_index
= index_last
;
8803 type
= pointed_type(type
);
8804 elem_size
= type_size(type
, &align
);
8805 c
+= index
* elem_size
;
8806 /* NOTE: we only support ranges for last designator */
8807 nb_elems
= index_last
- index
+ 1;
8808 if (nb_elems
!= 1) {
8817 if ((type
->t
& VT_BTYPE
) != VT_STRUCT
)
8818 expect("struct/union type");
8831 /* XXX: fix this mess by using explicit storage field */
8833 type1
.t
|= (type
->t
& ~VT_TYPE
);
8847 if (type
->t
& VT_ARRAY
) {
8849 type
= pointed_type(type
);
8850 c
+= index
* type_size(type
, &align
);
8854 error("too many field init");
8855 /* XXX: fix this mess by using explicit storage field */
8857 type1
.t
|= (type
->t
& ~VT_TYPE
);
8862 decl_initializer(type
, sec
, c
, 0, size_only
);
8864 /* XXX: make it more general */
8865 if (!size_only
&& nb_elems
> 1) {
8866 unsigned long c_end
;
8871 error("range init not supported yet for dynamic storage");
8872 c_end
= c
+ nb_elems
* elem_size
;
8873 if (c_end
> sec
->data_allocated
)
8874 section_realloc(sec
, c_end
);
8875 src
= sec
->data
+ c
;
8877 for(i
= 1; i
< nb_elems
; i
++) {
8879 memcpy(dst
, src
, elem_size
);
8885 #define EXPR_CONST 1
8888 /* store a value or an expression directly in global data or in local array */
8889 static void init_putv(CType
*type
, Section
*sec
, unsigned long c
,
8890 int v
, int expr_type
)
8892 int saved_global_expr
, bt
, bit_pos
, bit_size
;
8894 unsigned long long bit_mask
;
8902 /* compound literals must be allocated globally in this case */
8903 saved_global_expr
= global_expr
;
8906 global_expr
= saved_global_expr
;
8907 /* NOTE: symbols are accepted */
8908 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) != VT_CONST
)
8909 error("initializer element is not constant");
8917 dtype
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
8920 /* XXX: not portable */
8921 /* XXX: generate error if incorrect relocation */
8922 gen_assign_cast(&dtype
);
8923 bt
= type
->t
& VT_BTYPE
;
8924 /* we'll write at most 12 bytes */
8925 if (c
+ 12 > sec
->data_allocated
) {
8926 section_realloc(sec
, c
+ 12);
8928 ptr
= sec
->data
+ c
;
8929 /* XXX: make code faster ? */
8930 if (!(type
->t
& VT_BITFIELD
)) {
8935 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
8936 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
8937 bit_mask
= (1LL << bit_size
) - 1;
8939 if ((vtop
->r
& VT_SYM
) &&
8945 (bt
== VT_INT
&& bit_size
!= 32)))
8946 error("initializer element is not computable at load time");
8949 vtop
->c
.i
= (vtop
->c
.i
!= 0);
8951 *(char *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8954 *(short *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8957 *(double *)ptr
= vtop
->c
.d
;
8960 *(long double *)ptr
= vtop
->c
.ld
;
8963 *(long long *)ptr
|= (vtop
->c
.ll
& bit_mask
) << bit_pos
;
8966 if (vtop
->r
& VT_SYM
) {
8967 greloc(sec
, vtop
->sym
, c
, R_DATA_32
);
8969 *(int *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8974 vset(&dtype
, VT_LOCAL
|VT_LVAL
, c
);
8981 /* put zeros for variable based init */
8982 static void init_putz(CType
*t
, Section
*sec
, unsigned long c
, int size
)
8985 /* nothing to do because globals are already set to zero */
8987 vpush_global_sym(&func_old_type
, TOK_memset
);
8995 /* 't' contains the type and storage info. 'c' is the offset of the
8996 object in section 'sec'. If 'sec' is NULL, it means stack based
8997 allocation. 'first' is true if array '{' must be read (multi
8998 dimension implicit array init handling). 'size_only' is true if
8999 size only evaluation is wanted (only for arrays). */
9000 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
9001 int first
, int size_only
)
9003 int index
, array_length
, n
, no_oblock
, nb
, parlevel
, i
;
9004 int size1
, align1
, expr_type
;
9008 if (type
->t
& VT_ARRAY
) {
9012 t1
= pointed_type(type
);
9013 size1
= type_size(t1
, &align1
);
9016 if ((first
&& tok
!= TOK_LSTR
&& tok
!= TOK_STR
) ||
9022 /* only parse strings here if correct type (otherwise: handle
9023 them as ((w)char *) expressions */
9024 if ((tok
== TOK_LSTR
&&
9025 #ifdef TCC_TARGET_PE
9026 (t1
->t
& VT_BTYPE
) == VT_SHORT
&& (t1
->t
& VT_UNSIGNED
)
9028 (t1
->t
& VT_BTYPE
) == VT_INT
9030 ) || (tok
== TOK_STR
&& (t1
->t
& VT_BTYPE
) == VT_BYTE
)) {
9031 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
9036 /* compute maximum number of chars wanted */
9038 cstr_len
= cstr
->size
;
9040 cstr_len
= cstr
->size
/ sizeof(nwchar_t
);
9043 if (n
>= 0 && nb
> (n
- array_length
))
9044 nb
= n
- array_length
;
9047 warning("initializer-string for array is too long");
9048 /* in order to go faster for common case (char
9049 string in global variable, we handle it
9051 if (sec
&& tok
== TOK_STR
&& size1
== 1) {
9052 memcpy(sec
->data
+ c
+ array_length
, cstr
->data
, nb
);
9056 ch
= ((unsigned char *)cstr
->data
)[i
];
9058 ch
= ((nwchar_t
*)cstr
->data
)[i
];
9059 init_putv(t1
, sec
, c
+ (array_length
+ i
) * size1
,
9067 /* only add trailing zero if enough storage (no
9068 warning in this case since it is standard) */
9069 if (n
< 0 || array_length
< n
) {
9071 init_putv(t1
, sec
, c
+ (array_length
* size1
), 0, EXPR_VAL
);
9077 while (tok
!= '}') {
9078 decl_designator(type
, sec
, c
, &index
, NULL
, size_only
);
9079 if (n
>= 0 && index
>= n
)
9080 error("index too large");
9081 /* must put zero in holes (note that doing it that way
9082 ensures that it even works with designators) */
9083 if (!size_only
&& array_length
< index
) {
9084 init_putz(t1
, sec
, c
+ array_length
* size1
,
9085 (index
- array_length
) * size1
);
9088 if (index
> array_length
)
9089 array_length
= index
;
9090 /* special test for multi dimensional arrays (may not
9091 be strictly correct if designators are used at the
9093 if (index
>= n
&& no_oblock
)
9102 /* put zeros at the end */
9103 if (!size_only
&& n
>= 0 && array_length
< n
) {
9104 init_putz(t1
, sec
, c
+ array_length
* size1
,
9105 (n
- array_length
) * size1
);
9107 /* patch type size if needed */
9109 s
->c
= array_length
;
9110 } else if ((type
->t
& VT_BTYPE
) == VT_STRUCT
&&
9111 (sec
|| !first
|| tok
== '{')) {
9114 /* NOTE: the previous test is a specific case for automatic
9115 struct/union init */
9116 /* XXX: union needs only one init */
9118 /* XXX: this test is incorrect for local initializers
9119 beginning with ( without {. It would be much more difficult
9120 to do it correctly (ideally, the expression parser should
9121 be used in all cases) */
9127 while (tok
== '(') {
9131 if (!parse_btype(&type1
, &ad1
))
9133 type_decl(&type1
, &ad1
, &n
, TYPE_ABSTRACT
);
9135 if (!is_assignable_types(type
, &type1
))
9136 error("invalid type for cast");
9141 if (first
|| tok
== '{') {
9150 while (tok
!= '}') {
9151 decl_designator(type
, sec
, c
, NULL
, &f
, size_only
);
9153 if (!size_only
&& array_length
< index
) {
9154 init_putz(type
, sec
, c
+ array_length
,
9155 index
- array_length
);
9157 index
= index
+ type_size(&f
->type
, &align1
);
9158 if (index
> array_length
)
9159 array_length
= index
;
9161 if (no_oblock
&& f
== NULL
)
9167 /* put zeros at the end */
9168 if (!size_only
&& array_length
< n
) {
9169 init_putz(type
, sec
, c
+ array_length
,
9178 } else if (tok
== '{') {
9180 decl_initializer(type
, sec
, c
, first
, size_only
);
9182 } else if (size_only
) {
9183 /* just skip expression */
9185 while ((parlevel
> 0 || (tok
!= '}' && tok
!= ',')) &&
9189 else if (tok
== ')')
9194 /* currently, we always use constant expression for globals
9195 (may change for scripting case) */
9196 expr_type
= EXPR_CONST
;
9198 expr_type
= EXPR_ANY
;
9199 init_putv(type
, sec
, c
, 0, expr_type
);
9203 /* parse an initializer for type 't' if 'has_init' is non zero, and
9204 allocate space in local or global data space ('r' is either
9205 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
9206 variable 'v' of scope 'scope' is declared before initializers are
9207 parsed. If 'v' is zero, then a reference to the new object is put
9208 in the value stack. If 'has_init' is 2, a special parsing is done
9209 to handle string constants. */
9210 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
9211 int has_init
, int v
, int scope
)
9213 int size
, align
, addr
, data_offset
;
9215 ParseState saved_parse_state
= {0};
9216 TokenString init_str
;
9219 size
= type_size(type
, &align
);
9220 /* If unknown size, we must evaluate it before
9221 evaluating initializers because
9222 initializers can generate global data too
9223 (e.g. string pointers or ISOC99 compound
9224 literals). It also simplifies local
9225 initializers handling */
9226 tok_str_new(&init_str
);
9229 error("unknown type size");
9230 /* get all init string */
9231 if (has_init
== 2) {
9232 /* only get strings */
9233 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
9234 tok_str_add_tok(&init_str
);
9239 while (level
> 0 || (tok
!= ',' && tok
!= ';')) {
9241 error("unexpected end of file in initializer");
9242 tok_str_add_tok(&init_str
);
9245 else if (tok
== '}') {
9255 tok_str_add(&init_str
, -1);
9256 tok_str_add(&init_str
, 0);
9259 save_parse_state(&saved_parse_state
);
9261 macro_ptr
= init_str
.str
;
9263 decl_initializer(type
, NULL
, 0, 1, 1);
9264 /* prepare second initializer parsing */
9265 macro_ptr
= init_str
.str
;
9268 /* if still unknown size, error */
9269 size
= type_size(type
, &align
);
9271 error("unknown type size");
9273 /* take into account specified alignment if bigger */
9275 if (ad
->aligned
> align
)
9276 align
= ad
->aligned
;
9277 } else if (ad
->packed
) {
9280 if ((r
& VT_VALMASK
) == VT_LOCAL
) {
9282 if (do_bounds_check
&& (type
->t
& VT_ARRAY
))
9284 loc
= (loc
- size
) & -align
;
9286 /* handles bounds */
9287 /* XXX: currently, since we do only one pass, we cannot track
9288 '&' operators, so we add only arrays */
9289 if (do_bounds_check
&& (type
->t
& VT_ARRAY
)) {
9290 unsigned long *bounds_ptr
;
9291 /* add padding between regions */
9293 /* then add local bound info */
9294 bounds_ptr
= section_ptr_add(lbounds_section
, 2 * sizeof(unsigned long));
9295 bounds_ptr
[0] = addr
;
9296 bounds_ptr
[1] = size
;
9299 /* local variable */
9300 sym_push(v
, type
, r
, addr
);
9302 /* push local reference */
9303 vset(type
, r
, addr
);
9309 if (v
&& scope
== VT_CONST
) {
9310 /* see if the symbol was already defined */
9313 if (!is_compatible_types(&sym
->type
, type
))
9314 error("incompatible types for redefinition of '%s'",
9315 get_tok_str(v
, NULL
));
9316 if (sym
->type
.t
& VT_EXTERN
) {
9317 /* if the variable is extern, it was not allocated */
9318 sym
->type
.t
&= ~VT_EXTERN
;
9319 /* set array size if it was ommited in extern
9321 if ((sym
->type
.t
& VT_ARRAY
) &&
9322 sym
->type
.ref
->c
< 0 &&
9324 sym
->type
.ref
->c
= type
->ref
->c
;
9326 /* we accept several definitions of the same
9327 global variable. this is tricky, because we
9328 must play with the SHN_COMMON type of the symbol */
9329 /* XXX: should check if the variable was already
9330 initialized. It is incorrect to initialized it
9332 /* no init data, we won't add more to the symbol */
9339 /* allocate symbol in corresponding section */
9344 else if (tcc_state
->nocommon
)
9348 data_offset
= sec
->data_offset
;
9349 data_offset
= (data_offset
+ align
- 1) & -align
;
9351 /* very important to increment global pointer at this time
9352 because initializers themselves can create new initializers */
9353 data_offset
+= size
;
9354 /* add padding if bound check */
9355 if (do_bounds_check
)
9357 sec
->data_offset
= data_offset
;
9358 /* allocate section space to put the data */
9359 if (sec
->sh_type
!= SHT_NOBITS
&&
9360 data_offset
> sec
->data_allocated
)
9361 section_realloc(sec
, data_offset
);
9362 /* align section if needed */
9363 if (align
> sec
->sh_addralign
)
9364 sec
->sh_addralign
= align
;
9366 addr
= 0; /* avoid warning */
9370 if (scope
!= VT_CONST
|| !sym
) {
9371 sym
= sym_push(v
, type
, r
| VT_SYM
, 0);
9373 /* update symbol definition */
9375 put_extern_sym(sym
, sec
, addr
, size
);
9378 /* put a common area */
9379 put_extern_sym(sym
, NULL
, align
, size
);
9380 /* XXX: find a nicer way */
9381 esym
= &((ElfW(Sym
) *)symtab_section
->data
)[sym
->c
];
9382 esym
->st_shndx
= SHN_COMMON
;
9387 /* push global reference */
9388 sym
= get_sym_ref(type
, sec
, addr
, size
);
9390 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
9394 /* handles bounds now because the symbol must be defined
9395 before for the relocation */
9396 if (do_bounds_check
) {
9397 unsigned long *bounds_ptr
;
9399 greloc(bounds_section
, sym
, bounds_section
->data_offset
, R_DATA_32
);
9400 /* then add global bound info */
9401 bounds_ptr
= section_ptr_add(bounds_section
, 2 * sizeof(long));
9402 bounds_ptr
[0] = 0; /* relocated */
9403 bounds_ptr
[1] = size
;
9407 decl_initializer(type
, sec
, addr
, 1, 0);
9408 /* restore parse state if needed */
9410 tok_str_free(init_str
.str
);
9411 restore_parse_state(&saved_parse_state
);
9417 void put_func_debug(Sym
*sym
)
9422 /* XXX: we put here a dummy type */
9423 snprintf(buf
, sizeof(buf
), "%s:%c1",
9424 funcname
, sym
->type
.t
& VT_STATIC
? 'f' : 'F');
9425 put_stabs_r(buf
, N_FUN
, 0, file
->line_num
, 0,
9426 cur_text_section
, sym
->c
);
9427 /* //gr gdb wants a line at the function */
9428 put_stabn(N_SLINE
, 0, file
->line_num
, 0);
9433 /* parse an old style function declaration list */
9434 /* XXX: check multiple parameter */
9435 static void func_decl_list(Sym
*func_sym
)
9442 /* parse each declaration */
9443 while (tok
!= '{' && tok
!= ';' && tok
!= ',' && tok
!= TOK_EOF
) {
9444 if (!parse_btype(&btype
, &ad
))
9445 expect("declaration list");
9446 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
9447 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
9449 /* we accept no variable after */
9453 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
9454 /* find parameter in function parameter list */
9457 if ((s
->v
& ~SYM_FIELD
) == v
)
9461 error("declaration for parameter '%s' but no such parameter",
9462 get_tok_str(v
, NULL
));
9464 /* check that no storage specifier except 'register' was given */
9465 if (type
.t
& VT_STORAGE
)
9466 error("storage class specified for '%s'", get_tok_str(v
, NULL
));
9467 convert_parameter_type(&type
);
9468 /* we can add the type (NOTE: it could be local to the function) */
9470 /* accept other parameters */
9481 /* parse a function defined by symbol 'sym' and generate its code in
9482 'cur_text_section' */
9483 static void gen_function(Sym
*sym
)
9485 int saved_nocode_wanted
= nocode_wanted
;
9487 ind
= cur_text_section
->data_offset
;
9488 /* NOTE: we patch the symbol size later */
9489 put_extern_sym(sym
, cur_text_section
, ind
, 0);
9490 funcname
= get_tok_str(sym
->v
, NULL
);
9492 /* put debug symbol */
9494 put_func_debug(sym
);
9495 /* push a dummy symbol to enable local sym storage */
9496 sym_push2(&local_stack
, SYM_FIELD
, 0, 0);
9497 gfunc_prolog(&sym
->type
);
9499 block(NULL
, NULL
, NULL
, NULL
, 0, 0);
9502 cur_text_section
->data_offset
= ind
;
9503 label_pop(&global_label_stack
, NULL
);
9504 sym_pop(&local_stack
, NULL
); /* reset local stack */
9505 /* end of function */
9506 /* patch symbol size */
9507 ((ElfW(Sym
) *)symtab_section
->data
)[sym
->c
].st_size
=
9510 put_stabn(N_FUN
, 0, 0, ind
- func_ind
);
9512 /* It's better to crash than to generate wrong code */
9513 cur_text_section
= NULL
;
9514 funcname
= ""; /* for safety */
9515 func_vt
.t
= VT_VOID
; /* for safety */
9516 ind
= 0; /* for safety */
9517 nocode_wanted
= saved_nocode_wanted
;
9520 static void gen_inline_functions(void)
9524 int *str
, inline_generated
;
9526 /* iterate while inline function are referenced */
9528 inline_generated
= 0;
9529 for(sym
= global_stack
; sym
!= NULL
; sym
= sym
->prev
) {
9531 if (((type
->t
& VT_BTYPE
) == VT_FUNC
) &&
9532 (type
->t
& (VT_STATIC
| VT_INLINE
)) ==
9533 (VT_STATIC
| VT_INLINE
) &&
9535 /* the function was used: generate its code and
9536 convert it to a normal function */
9537 str
= INLINE_DEF(sym
->r
);
9538 sym
->r
= VT_SYM
| VT_CONST
;
9539 sym
->type
.t
&= ~VT_INLINE
;
9543 cur_text_section
= text_section
;
9545 macro_ptr
= NULL
; /* fail safe */
9548 inline_generated
= 1;
9551 if (!inline_generated
)
9555 /* free all remaining inline function tokens */
9556 for(sym
= global_stack
; sym
!= NULL
; sym
= sym
->prev
) {
9558 if (((type
->t
& VT_BTYPE
) == VT_FUNC
) &&
9559 (type
->t
& (VT_STATIC
| VT_INLINE
)) ==
9560 (VT_STATIC
| VT_INLINE
)) {
9561 //gr printf("sym %d %s\n", sym->r, get_tok_str(sym->v, NULL));
9562 if (sym
->r
== (VT_SYM
| VT_CONST
)) //gr beware!
9564 str
= INLINE_DEF(sym
->r
);
9566 sym
->r
= 0; /* fail safe */
9571 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
9572 static void decl(int l
)
9580 if (!parse_btype(&btype
, &ad
)) {
9581 /* skip redundant ';' */
9582 /* XXX: find more elegant solution */
9587 if (l
== VT_CONST
&&
9588 (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
)) {
9589 /* global asm block */
9593 /* special test for old K&R protos without explicit int
9594 type. Only accepted when defining global data */
9595 if (l
== VT_LOCAL
|| tok
< TOK_DEFINE
)
9599 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
9600 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
9602 /* we accept no variable after */
9606 while (1) { /* iterate thru each declaration */
9608 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
9612 type_to_str(buf
, sizeof(buf
), t
, get_tok_str(v
, NULL
));
9613 printf("type = '%s'\n", buf
);
9616 if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
9617 /* if old style function prototype, we accept a
9620 if (sym
->c
== FUNC_OLD
)
9621 func_decl_list(sym
);
9626 error("cannot use local functions");
9627 if ((type
.t
& VT_BTYPE
) != VT_FUNC
)
9628 expect("function definition");
9630 /* reject abstract declarators in function definition */
9632 while ((sym
= sym
->next
) != NULL
)
9633 if (!(sym
->v
& ~SYM_FIELD
))
9634 expect("identifier");
9636 /* XXX: cannot do better now: convert extern line to static inline */
9637 if ((type
.t
& (VT_EXTERN
| VT_INLINE
)) == (VT_EXTERN
| VT_INLINE
))
9638 type
.t
= (type
.t
& ~VT_EXTERN
) | VT_STATIC
;
9642 if ((sym
->type
.t
& VT_BTYPE
) != VT_FUNC
)
9644 /* specific case: if not func_call defined, we put
9645 the one of the prototype */
9646 /* XXX: should have default value */
9647 r
= sym
->type
.ref
->r
;
9648 if (FUNC_CALL(r
) != FUNC_CDECL
9649 && FUNC_CALL(type
.ref
->r
) == FUNC_CDECL
)
9650 FUNC_CALL(type
.ref
->r
) = FUNC_CALL(r
);
9652 FUNC_EXPORT(type
.ref
->r
) = 1;
9654 if (!is_compatible_types(&sym
->type
, &type
)) {
9656 error("incompatible types for redefinition of '%s'",
9657 get_tok_str(v
, NULL
));
9659 /* if symbol is already defined, then put complete type */
9662 /* put function symbol */
9663 sym
= global_identifier_push(v
, type
.t
, 0);
9664 sym
->type
.ref
= type
.ref
;
9667 /* static inline functions are just recorded as a kind
9668 of macro. Their code will be emitted at the end of
9669 the compilation unit only if they are used */
9670 if ((type
.t
& (VT_INLINE
| VT_STATIC
)) ==
9671 (VT_INLINE
| VT_STATIC
)) {
9672 TokenString func_str
;
9675 tok_str_new(&func_str
);
9681 error("unexpected end of file");
9682 tok_str_add_tok(&func_str
);
9687 } else if (t
== '}') {
9689 if (block_level
== 0)
9693 tok_str_add(&func_str
, -1);
9694 tok_str_add(&func_str
, 0);
9695 INLINE_DEF(sym
->r
) = func_str
.str
;
9697 /* compute text section */
9698 cur_text_section
= ad
.section
;
9699 if (!cur_text_section
)
9700 cur_text_section
= text_section
;
9701 sym
->r
= VT_SYM
| VT_CONST
;
9706 if (btype
.t
& VT_TYPEDEF
) {
9707 /* save typedefed type */
9708 /* XXX: test storage specifiers ? */
9709 sym
= sym_push(v
, &type
, 0, 0);
9710 sym
->type
.t
|= VT_TYPEDEF
;
9711 } else if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
9712 /* external function definition */
9713 /* specific case for func_call attribute */
9715 type
.ref
->r
= ad
.func_attr
;
9716 external_sym(v
, &type
, 0);
9718 /* not lvalue if array */
9720 if (!(type
.t
& VT_ARRAY
))
9721 r
|= lvalue_type(type
.t
);
9722 has_init
= (tok
== '=');
9723 if ((btype
.t
& VT_EXTERN
) ||
9724 ((type
.t
& VT_ARRAY
) && (type
.t
& VT_STATIC
) &&
9725 !has_init
&& l
== VT_CONST
&& type
.ref
->c
< 0)) {
9726 /* external variable */
9727 /* NOTE: as GCC, uninitialized global static
9728 arrays of null size are considered as
9730 external_sym(v
, &type
, r
);
9732 type
.t
|= (btype
.t
& VT_STATIC
); /* Retain "static". */
9733 if (type
.t
& VT_STATIC
)
9739 decl_initializer_alloc(&type
, &ad
, r
,
9753 /* better than nothing, but needs extension to handle '-E' option
9755 static void preprocess_init(TCCState
*s1
)
9757 s1
->include_stack_ptr
= s1
->include_stack
;
9758 /* XXX: move that before to avoid having to initialize
9759 file->ifdef_stack_ptr ? */
9760 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
9761 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
9763 /* XXX: not ANSI compliant: bound checking says error */
9765 s1
->pack_stack
[0] = 0;
9766 s1
->pack_stack_ptr
= s1
->pack_stack
;
9769 /* compile the C file opened in 'file'. Return non zero if errors. */
9770 static int tcc_compile(TCCState
*s1
)
9774 volatile int section_sym
;
9777 printf("%s: **** new file\n", file
->filename
);
9779 preprocess_init(s1
);
9781 cur_text_section
= NULL
;
9783 anon_sym
= SYM_FIRST_ANOM
;
9785 /* file info: full path + filename */
9786 section_sym
= 0; /* avoid warning */
9788 section_sym
= put_elf_sym(symtab_section
, 0, 0,
9789 ELFW(ST_INFO
)(STB_LOCAL
, STT_SECTION
), 0,
9790 text_section
->sh_num
, NULL
);
9791 getcwd(buf
, sizeof(buf
));
9793 normalize_slashes(buf
);
9795 pstrcat(buf
, sizeof(buf
), "/");
9796 put_stabs_r(buf
, N_SO
, 0, 0,
9797 text_section
->data_offset
, text_section
, section_sym
);
9798 put_stabs_r(file
->filename
, N_SO
, 0, 0,
9799 text_section
->data_offset
, text_section
, section_sym
);
9801 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
9802 symbols can be safely used */
9803 put_elf_sym(symtab_section
, 0, 0,
9804 ELFW(ST_INFO
)(STB_LOCAL
, STT_FILE
), 0,
9805 SHN_ABS
, file
->filename
);
9807 /* define some often used types */
9808 int_type
.t
= VT_INT
;
9810 char_pointer_type
.t
= VT_BYTE
;
9811 mk_pointer(&char_pointer_type
);
9813 func_old_type
.t
= VT_FUNC
;
9814 func_old_type
.ref
= sym_push(SYM_FIELD
, &int_type
, FUNC_CDECL
, FUNC_OLD
);
9816 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
9817 float_type
.t
= VT_FLOAT
;
9818 double_type
.t
= VT_DOUBLE
;
9820 func_float_type
.t
= VT_FUNC
;
9821 func_float_type
.ref
= sym_push(SYM_FIELD
, &float_type
, FUNC_CDECL
, FUNC_OLD
);
9822 func_double_type
.t
= VT_FUNC
;
9823 func_double_type
.ref
= sym_push(SYM_FIELD
, &double_type
, FUNC_CDECL
, FUNC_OLD
);
9827 /* define 'void *alloca(unsigned int)' builtin function */
9832 sym
= sym_push(p
, mk_pointer(VT_VOID
), FUNC_CDECL
, FUNC_NEW
);
9833 s1
= sym_push(SYM_FIELD
, VT_UNSIGNED
| VT_INT
, 0, 0);
9836 sym_push(TOK_alloca
, VT_FUNC
| (p
<< VT_STRUCT_SHIFT
), VT_CONST
, 0);
9840 define_start
= define_stack
;
9843 if (setjmp(s1
->error_jmp_buf
) == 0) {
9845 s1
->error_set_jmp_enabled
= 1;
9847 ch
= file
->buf_ptr
[0];
9848 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
9849 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
;
9853 expect("declaration");
9855 /* end of translation unit info */
9857 put_stabs_r(NULL
, N_SO
, 0, 0,
9858 text_section
->data_offset
, text_section
, section_sym
);
9861 s1
->error_set_jmp_enabled
= 0;
9863 /* reset define stack, but leave -Dsymbols (may be incorrect if
9864 they are undefined) */
9865 free_defines(define_start
);
9867 gen_inline_functions();
9869 sym_pop(&global_stack
, NULL
);
9870 sym_pop(&local_stack
, NULL
);
9872 return s1
->nb_errors
!= 0 ? -1 : 0;
9875 /* Preprocess the current file */
9876 /* XXX: add line and file infos,
9877 * XXX: add options to preserve spaces (partly done, only spaces in macro are
9880 static int tcc_preprocess(TCCState
*s1
)
9883 BufferedFile
*file_ref
;
9884 int token_seen
, line_ref
;
9886 preprocess_init(s1
);
9887 define_start
= define_stack
;
9888 ch
= file
->buf_ptr
[0];
9890 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
9891 parse_flags
= PARSE_FLAG_ASM_COMMENTS
| PARSE_FLAG_PREPROCESS
|
9892 PARSE_FLAG_LINEFEED
;
9900 if (tok
== TOK_EOF
) {
9902 } else if (tok
== TOK_LINEFEED
) {
9907 } else if (token_seen
) {
9908 fwrite(tok_spaces
.data
, tok_spaces
.size
, 1, s1
->outfile
);
9910 int d
= file
->line_num
- line_ref
;
9911 if (file
!= file_ref
|| d
< 0 || d
>= 8)
9912 fprintf(s1
->outfile
, "# %d \"%s\"\n", file
->line_num
, file
->filename
);
9915 fputs("\n", s1
->outfile
), --d
;
9916 line_ref
= (file_ref
= file
)->line_num
;
9919 fputs(get_tok_str(tok
, &tokc
), s1
->outfile
);
9921 free_defines(define_start
);
9926 int tcc_compile_string(TCCState
*s
, const char *str
)
9928 BufferedFile bf1
, *bf
= &bf1
;
9932 /* init file structure */
9934 /* XXX: avoid copying */
9936 buf
= tcc_malloc(len
+ 1);
9939 memcpy(buf
, str
, len
);
9942 bf
->buf_end
= buf
+ len
;
9943 pstrcpy(bf
->filename
, sizeof(bf
->filename
), "<string>");
9946 ret
= tcc_compile(s
);
9950 /* currently, no need to close */
9955 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
9956 void tcc_define_symbol(TCCState
*s1
, const char *sym
, const char *value
)
9958 BufferedFile bf1
, *bf
= &bf1
;
9960 pstrcpy(bf
->buffer
, IO_BUF_SIZE
, sym
);
9961 pstrcat(bf
->buffer
, IO_BUF_SIZE
, " ");
9965 pstrcat(bf
->buffer
, IO_BUF_SIZE
, value
);
9967 /* init file structure */
9969 bf
->buf_ptr
= bf
->buffer
;
9970 bf
->buf_end
= bf
->buffer
+ strlen(bf
->buffer
);
9971 *bf
->buf_end
= CH_EOB
;
9972 bf
->filename
[0] = '\0';
9976 s1
->include_stack_ptr
= s1
->include_stack
;
9978 /* parse with define parser */
9979 ch
= file
->buf_ptr
[0];
9985 /* undefine a preprocessor symbol */
9986 void tcc_undefine_symbol(TCCState
*s1
, const char *sym
)
9990 ts
= tok_alloc(sym
, strlen(sym
));
9991 s
= define_find(ts
->tok
);
9992 /* undefine symbol by putting an invalid name */
9997 #ifdef CONFIG_TCC_ASM
9999 #ifdef TCC_TARGET_I386
10000 #include "i386-asm.c"
10002 #include "tccasm.c"
10005 static void asm_instr(void)
10007 error("inline asm() not supported");
10009 static void asm_global_instr(void)
10011 error("inline asm() not supported");
10015 #include "tccelf.c"
10017 #ifdef TCC_TARGET_COFF
10018 #include "tcccoff.c"
10021 #ifdef TCC_TARGET_PE
10025 /* print the position in the source file of PC value 'pc' by reading
10026 the stabs debug information */
10027 static void rt_printline(unsigned long wanted_pc
)
10029 Stab_Sym
*sym
, *sym_end
;
10030 char func_name
[128], last_func_name
[128];
10031 unsigned long func_addr
, last_pc
, pc
;
10032 const char *incl_files
[INCLUDE_STACK_SIZE
];
10033 int incl_index
, len
, last_line_num
, i
;
10034 const char *str
, *p
;
10036 fprintf(stderr
, "0x%08lx:", wanted_pc
);
10038 func_name
[0] = '\0';
10041 last_func_name
[0] = '\0';
10042 last_pc
= 0xffffffff;
10044 sym
= (Stab_Sym
*)stab_section
->data
+ 1;
10045 sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
10046 while (sym
< sym_end
) {
10047 switch(sym
->n_type
) {
10048 /* function start or end */
10050 if (sym
->n_strx
== 0) {
10051 /* we test if between last line and end of function */
10052 pc
= sym
->n_value
+ func_addr
;
10053 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
10055 func_name
[0] = '\0';
10058 str
= stabstr_section
->data
+ sym
->n_strx
;
10059 p
= strchr(str
, ':');
10061 pstrcpy(func_name
, sizeof(func_name
), str
);
10064 if (len
> sizeof(func_name
) - 1)
10065 len
= sizeof(func_name
) - 1;
10066 memcpy(func_name
, str
, len
);
10067 func_name
[len
] = '\0';
10069 func_addr
= sym
->n_value
;
10072 /* line number info */
10074 pc
= sym
->n_value
+ func_addr
;
10075 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
10078 last_line_num
= sym
->n_desc
;
10080 strcpy(last_func_name
, func_name
);
10082 /* include files */
10084 str
= stabstr_section
->data
+ sym
->n_strx
;
10086 if (incl_index
< INCLUDE_STACK_SIZE
) {
10087 incl_files
[incl_index
++] = str
;
10091 if (incl_index
> 1)
10095 if (sym
->n_strx
== 0) {
10096 incl_index
= 0; /* end of translation unit */
10098 str
= stabstr_section
->data
+ sym
->n_strx
;
10099 /* do not add path */
10101 if (len
> 0 && str
[len
- 1] != '/')
10109 /* second pass: we try symtab symbols (no line number info) */
10112 ElfW(Sym
) *sym
, *sym_end
;
10115 sym_end
= (ElfW(Sym
) *)(symtab_section
->data
+ symtab_section
->data_offset
);
10116 for(sym
= (ElfW(Sym
) *)symtab_section
->data
+ 1;
10119 type
= ELFW(ST_TYPE
)(sym
->st_info
);
10120 if (type
== STT_FUNC
) {
10121 if (wanted_pc
>= sym
->st_value
&&
10122 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
10123 pstrcpy(last_func_name
, sizeof(last_func_name
),
10124 strtab_section
->data
+ sym
->st_name
);
10130 /* did not find any info: */
10131 fprintf(stderr
, " ???\n");
10134 if (last_func_name
[0] != '\0') {
10135 fprintf(stderr
, " %s()", last_func_name
);
10137 if (incl_index
> 0) {
10138 fprintf(stderr
, " (%s:%d",
10139 incl_files
[incl_index
- 1], last_line_num
);
10140 for(i
= incl_index
- 2; i
>= 0; i
--)
10141 fprintf(stderr
, ", included from %s", incl_files
[i
]);
10142 fprintf(stderr
, ")");
10144 fprintf(stderr
, "\n");
10147 #if !defined(_WIN32) && !defined(CONFIG_TCCBOOT)
10151 /* fix for glibc 2.1 */
10153 #define REG_EIP EIP
10154 #define REG_EBP EBP
10157 /* return the PC at frame level 'level'. Return non zero if not found */
10158 static int rt_get_caller_pc(unsigned long *paddr
,
10159 ucontext_t
*uc
, int level
)
10165 #if defined(__FreeBSD__)
10166 *paddr
= uc
->uc_mcontext
.mc_eip
;
10167 #elif defined(__dietlibc__)
10168 *paddr
= uc
->uc_mcontext
.eip
;
10170 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
10174 #if defined(__FreeBSD__)
10175 fp
= uc
->uc_mcontext
.mc_ebp
;
10176 #elif defined(__dietlibc__)
10177 fp
= uc
->uc_mcontext
.ebp
;
10179 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
10181 for(i
=1;i
<level
;i
++) {
10182 /* XXX: check address validity with program info */
10183 if (fp
<= 0x1000 || fp
>= 0xc0000000)
10185 fp
= ((unsigned long *)fp
)[0];
10187 *paddr
= ((unsigned long *)fp
)[1];
10191 #elif defined(__x86_64__)
10192 /* return the PC at frame level 'level'. Return non zero if not found */
10193 static int rt_get_caller_pc(unsigned long *paddr
,
10194 ucontext_t
*uc
, int level
)
10200 /* XXX: only support linux */
10201 *paddr
= uc
->uc_mcontext
.gregs
[REG_RIP
];
10204 fp
= uc
->uc_mcontext
.gregs
[REG_RBP
];
10205 for(i
=1;i
<level
;i
++) {
10206 /* XXX: check address validity with program info */
10209 fp
= ((unsigned long *)fp
)[0];
10211 *paddr
= ((unsigned long *)fp
)[1];
10217 #warning add arch specific rt_get_caller_pc()
10219 static int rt_get_caller_pc(unsigned long *paddr
,
10220 ucontext_t
*uc
, int level
)
10226 /* emit a run time error at position 'pc' */
10227 void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
10234 fprintf(stderr
, "Runtime error: ");
10235 vfprintf(stderr
, fmt
, ap
);
10236 fprintf(stderr
, "\n");
10237 for(i
=0;i
<num_callers
;i
++) {
10238 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
10241 fprintf(stderr
, "at ");
10243 fprintf(stderr
, "by ");
10250 /* signal handler for fatal errors */
10251 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
10253 ucontext_t
*uc
= puc
;
10257 switch(siginf
->si_code
) {
10260 rt_error(uc
, "division by zero");
10263 rt_error(uc
, "floating point exception");
10269 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
10270 rt_error(uc
, *rt_bound_error_msg
);
10272 rt_error(uc
, "dereferencing invalid pointer");
10275 rt_error(uc
, "illegal instruction");
10278 rt_error(uc
, "abort() called");
10281 rt_error(uc
, "caught signal %d", signum
);
10288 /* copy code into memory passed in by the caller and do all relocations
10289 (needed before using tcc_get_symbol()).
10290 returns -1 on error and required size if ptr is NULL */
10291 int tcc_relocate(TCCState
*s1
, void *ptr
)
10294 unsigned long offset
, length
, mem
;
10299 if (0 == s1
->runtime_added
) {
10300 #ifdef TCC_TARGET_PE
10301 pe_add_runtime(s1
);
10302 relocate_common_syms();
10303 tcc_add_linker_symbols(s1
);
10305 tcc_add_runtime(s1
);
10306 relocate_common_syms();
10307 tcc_add_linker_symbols(s1
);
10308 build_got_entries(s1
);
10310 s1
->runtime_added
= 1;
10314 mem
= (unsigned long)ptr
;
10315 for(i
= 1; i
< s1
->nb_sections
; i
++) {
10316 s
= s1
->sections
[i
];
10317 if (0 == (s
->sh_flags
& SHF_ALLOC
))
10319 length
= s
->data_offset
;
10322 } else if (1 == mem
) {
10323 /* section are relocated in place.
10324 We also alloc the bss space */
10325 if (s
->sh_type
== SHT_NOBITS
)
10326 s
->data
= tcc_malloc(length
);
10327 s
->sh_addr
= (unsigned long)s
->data
;
10329 /* sections are relocated to new memory */
10330 s
->sh_addr
= (mem
+ offset
+ 15) & ~15;
10332 offset
= (offset
+ length
+ 15) & ~15;
10335 #ifdef TCC_TARGET_X86_64
10336 s1
->runtime_plt_and_got_offset
= 0;
10337 s1
->runtime_plt_and_got
= (char *)(mem
+ offset
);
10338 /* double the size of the buffer for got and plt entries
10339 XXX: calculate exact size for them? */
10344 return offset
+ 15;
10346 /* relocate symbols */
10347 relocate_syms(s1
, 1);
10351 /* relocate each section */
10352 for(i
= 1; i
< s1
->nb_sections
; i
++) {
10353 s
= s1
->sections
[i
];
10355 relocate_section(s1
, s
);
10358 for(i
= 1; i
< s1
->nb_sections
; i
++) {
10359 s
= s1
->sections
[i
];
10360 if (0 == (s
->sh_flags
& SHF_ALLOC
))
10362 length
= s
->data_offset
;
10363 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
10364 ptr
= (void*)s
->sh_addr
;
10365 if (NULL
== s
->data
|| s
->sh_type
== SHT_NOBITS
)
10366 memset(ptr
, 0, length
);
10367 else if (ptr
!= s
->data
)
10368 memcpy(ptr
, s
->data
, length
);
10369 /* mark executable sections as executable in memory */
10370 if (s
->sh_flags
& SHF_EXECINSTR
)
10371 set_pages_executable(ptr
, length
);
10373 #ifdef TCC_TARGET_X86_64
10374 set_pages_executable(s1
->runtime_plt_and_got
,
10375 s1
->runtime_plt_and_got_offset
);
10380 /* launch the compiled program with the given arguments */
10381 int tcc_run(TCCState
*s1
, int argc
, char **argv
)
10383 int (*prog_main
)(int, char **);
10387 ret
= tcc_relocate(s1
, NULL
);
10390 ptr
= tcc_malloc(ret
);
10391 tcc_relocate(s1
, ptr
);
10393 prog_main
= tcc_get_symbol_err(s1
, "main");
10396 #if defined(_WIN32) || defined(CONFIG_TCCBOOT)
10397 error("debug mode currently not available for Windows");
10399 struct sigaction sigact
;
10400 /* install TCC signal handlers to print debug info on fatal
10402 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
10403 sigact
.sa_sigaction
= sig_error
;
10404 sigemptyset(&sigact
.sa_mask
);
10405 sigaction(SIGFPE
, &sigact
, NULL
);
10406 sigaction(SIGILL
, &sigact
, NULL
);
10407 sigaction(SIGSEGV
, &sigact
, NULL
);
10408 sigaction(SIGBUS
, &sigact
, NULL
);
10409 sigaction(SIGABRT
, &sigact
, NULL
);
10413 #ifdef CONFIG_TCC_BCHECK
10414 if (do_bounds_check
) {
10415 void (*bound_init
)(void);
10417 /* set error function */
10418 rt_bound_error_msg
= tcc_get_symbol_err(s1
, "__bound_error_msg");
10420 /* XXX: use .init section so that it also work in binary ? */
10421 bound_init
= (void *)tcc_get_symbol_err(s1
, "__bound_init");
10425 ret
= (*prog_main
)(argc
, argv
);
10430 void tcc_memstats(void)
10433 printf("memory in use: %d\n", mem_cur_size
);
10437 static void tcc_cleanup(void)
10441 if (NULL
== tcc_state
)
10445 /* free -D defines */
10446 free_defines(NULL
);
10449 n
= tok_ident
- TOK_IDENT
;
10450 for(i
= 0; i
< n
; i
++)
10451 tcc_free(table_ident
[i
]);
10452 tcc_free(table_ident
);
10454 /* free sym_pools */
10455 dynarray_reset(&sym_pools
, &nb_sym_pools
);
10456 /* string buffer */
10457 cstr_free(&tokcstr
);
10458 cstr_free(&tok_spaces
);
10459 /* reset symbol stack */
10460 sym_free_first
= NULL
;
10461 /* cleanup from error/setjmp */
10465 TCCState
*tcc_new(void)
10474 s
= tcc_mallocz(sizeof(TCCState
));
10478 s
->output_type
= TCC_OUTPUT_MEMORY
;
10480 /* init isid table */
10481 for(i
=CH_EOF
;i
<256;i
++)
10482 isidnum_table
[i
-CH_EOF
] = isid(i
) || isnum(i
);
10484 /* add all tokens */
10485 table_ident
= NULL
;
10486 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
10488 tok_ident
= TOK_IDENT
;
10497 ts
= tok_alloc(p
, r
- p
- 1);
10501 /* we add dummy defines for some special macros to speed up tests
10502 and to have working defined() */
10503 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
10504 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
10505 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
10506 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
10508 /* standard defines */
10509 tcc_define_symbol(s
, "__STDC__", NULL
);
10510 tcc_define_symbol(s
, "__STDC_VERSION__", "199901L");
10511 #if defined(TCC_TARGET_I386)
10512 tcc_define_symbol(s
, "__i386__", NULL
);
10514 #if defined(TCC_TARGET_X86_64)
10515 tcc_define_symbol(s
, "__x86_64__", NULL
);
10517 #if defined(TCC_TARGET_ARM)
10518 tcc_define_symbol(s
, "__ARM_ARCH_4__", NULL
);
10519 tcc_define_symbol(s
, "__arm_elf__", NULL
);
10520 tcc_define_symbol(s
, "__arm_elf", NULL
);
10521 tcc_define_symbol(s
, "arm_elf", NULL
);
10522 tcc_define_symbol(s
, "__arm__", NULL
);
10523 tcc_define_symbol(s
, "__arm", NULL
);
10524 tcc_define_symbol(s
, "arm", NULL
);
10525 tcc_define_symbol(s
, "__APCS_32__", NULL
);
10527 #ifdef TCC_TARGET_PE
10528 tcc_define_symbol(s
, "_WIN32", NULL
);
10530 tcc_define_symbol(s
, "__unix__", NULL
);
10531 tcc_define_symbol(s
, "__unix", NULL
);
10532 #if defined(__linux)
10533 tcc_define_symbol(s
, "__linux__", NULL
);
10534 tcc_define_symbol(s
, "__linux", NULL
);
10537 /* tiny C specific defines */
10538 tcc_define_symbol(s
, "__TINYC__", NULL
);
10540 /* tiny C & gcc defines */
10541 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned int");
10542 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "int");
10543 #ifdef TCC_TARGET_PE
10544 tcc_define_symbol(s
, "__WCHAR_TYPE__", "unsigned short");
10546 tcc_define_symbol(s
, "__WCHAR_TYPE__", "int");
10549 #ifndef TCC_TARGET_PE
10550 /* default library paths */
10551 tcc_add_library_path(s
, CONFIG_SYSROOT
"/usr/local/lib");
10552 tcc_add_library_path(s
, CONFIG_SYSROOT
"/usr/lib");
10553 tcc_add_library_path(s
, CONFIG_SYSROOT
"/lib");
10556 /* no section zero */
10557 dynarray_add((void ***)&s
->sections
, &s
->nb_sections
, NULL
);
10559 /* create standard sections */
10560 text_section
= new_section(s
, ".text", SHT_PROGBITS
, SHF_ALLOC
| SHF_EXECINSTR
);
10561 data_section
= new_section(s
, ".data", SHT_PROGBITS
, SHF_ALLOC
| SHF_WRITE
);
10562 bss_section
= new_section(s
, ".bss", SHT_NOBITS
, SHF_ALLOC
| SHF_WRITE
);
10564 /* symbols are always generated for linking stage */
10565 symtab_section
= new_symtab(s
, ".symtab", SHT_SYMTAB
, 0,
10567 ".hashtab", SHF_PRIVATE
);
10568 strtab_section
= symtab_section
->link
;
10570 /* private symbol table for dynamic symbols */
10571 s
->dynsymtab_section
= new_symtab(s
, ".dynsymtab", SHT_SYMTAB
, SHF_PRIVATE
,
10573 ".dynhashtab", SHF_PRIVATE
);
10574 s
->alacarte_link
= 1;
10576 #ifdef CHAR_IS_UNSIGNED
10577 s
->char_is_unsigned
= 1;
10579 #if defined(TCC_TARGET_PE) && 0
10580 /* XXX: currently the PE linker is not ready to support that */
10581 s
->leading_underscore
= 1;
10586 void tcc_delete(TCCState
*s1
)
10592 /* free all sections */
10593 for(i
= 1; i
< s1
->nb_sections
; i
++)
10594 free_section(s1
->sections
[i
]);
10595 dynarray_reset(&s1
->sections
, &s1
->nb_sections
);
10597 for(i
= 0; i
< s1
->nb_priv_sections
; i
++)
10598 free_section(s1
->priv_sections
[i
]);
10599 dynarray_reset(&s1
->priv_sections
, &s1
->nb_priv_sections
);
10601 /* free any loaded DLLs */
10602 for ( i
= 0; i
< s1
->nb_loaded_dlls
; i
++) {
10603 DLLReference
*ref
= s1
->loaded_dlls
[i
];
10605 dlclose(ref
->handle
);
10608 /* free loaded dlls array */
10609 dynarray_reset(&s1
->loaded_dlls
, &s1
->nb_loaded_dlls
);
10611 /* free library paths */
10612 dynarray_reset(&s1
->library_paths
, &s1
->nb_library_paths
);
10614 /* free include paths */
10615 dynarray_reset(&s1
->cached_includes
, &s1
->nb_cached_includes
);
10616 dynarray_reset(&s1
->include_paths
, &s1
->nb_include_paths
);
10617 dynarray_reset(&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
);
10622 int tcc_add_include_path(TCCState
*s1
, const char *pathname
)
10626 pathname1
= tcc_strdup(pathname
);
10627 dynarray_add((void ***)&s1
->include_paths
, &s1
->nb_include_paths
, pathname1
);
10631 int tcc_add_sysinclude_path(TCCState
*s1
, const char *pathname
)
10635 pathname1
= tcc_strdup(pathname
);
10636 dynarray_add((void ***)&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
, pathname1
);
10640 static int tcc_add_file_internal(TCCState
*s1
, const char *filename
, int flags
)
10645 BufferedFile
*saved_file
;
10647 /* find source file type with extension */
10648 ext
= tcc_fileextension(filename
);
10652 /* open the file */
10654 file
= tcc_open(s1
, filename
);
10656 if (flags
& AFF_PRINT_ERROR
) {
10657 error_noabort("file '%s' not found", filename
);
10663 if (flags
& AFF_PREPROCESS
) {
10664 ret
= tcc_preprocess(s1
);
10665 } else if (!ext
[0] || !PATHCMP(ext
, "c")) {
10666 /* C file assumed */
10667 ret
= tcc_compile(s1
);
10669 #ifdef CONFIG_TCC_ASM
10670 if (!strcmp(ext
, "S")) {
10671 /* preprocessed assembler */
10672 ret
= tcc_assemble(s1
, 1);
10673 } else if (!strcmp(ext
, "s")) {
10674 /* non preprocessed assembler */
10675 ret
= tcc_assemble(s1
, 0);
10678 #ifdef TCC_TARGET_PE
10679 if (!PATHCMP(ext
, "def")) {
10680 ret
= pe_load_def_file(s1
, file
->fd
);
10685 /* assume executable format: auto guess file type */
10686 ret
= read(fd
, &ehdr
, sizeof(ehdr
));
10687 lseek(fd
, 0, SEEK_SET
);
10689 error_noabort("could not read header");
10691 } else if (ret
!= sizeof(ehdr
)) {
10692 goto try_load_script
;
10695 if (ehdr
.e_ident
[0] == ELFMAG0
&&
10696 ehdr
.e_ident
[1] == ELFMAG1
&&
10697 ehdr
.e_ident
[2] == ELFMAG2
&&
10698 ehdr
.e_ident
[3] == ELFMAG3
) {
10699 file
->line_num
= 0; /* do not display line number if error */
10700 if (ehdr
.e_type
== ET_REL
) {
10701 ret
= tcc_load_object_file(s1
, fd
, 0);
10702 } else if (ehdr
.e_type
== ET_DYN
) {
10703 if (s1
->output_type
== TCC_OUTPUT_MEMORY
) {
10704 #ifdef TCC_TARGET_PE
10708 h
= dlopen(filename
, RTLD_GLOBAL
| RTLD_LAZY
);
10715 ret
= tcc_load_dll(s1
, fd
, filename
,
10716 (flags
& AFF_REFERENCED_DLL
) != 0);
10719 error_noabort("unrecognized ELF file");
10722 } else if (memcmp((char *)&ehdr
, ARMAG
, 8) == 0) {
10723 file
->line_num
= 0; /* do not display line number if error */
10724 ret
= tcc_load_archive(s1
, fd
);
10726 #ifdef TCC_TARGET_COFF
10727 if (*(uint16_t *)(&ehdr
) == COFF_C67_MAGIC
) {
10728 ret
= tcc_load_coff(s1
, fd
);
10731 #ifdef TCC_TARGET_PE
10732 if (pe_test_res_file(&ehdr
, ret
)) {
10733 ret
= pe_load_res_file(s1
, fd
);
10737 /* as GNU ld, consider it is an ld script if not recognized */
10739 ret
= tcc_load_ldscript(s1
);
10741 error_noabort("unrecognized file type");
10756 int tcc_add_file(TCCState
*s
, const char *filename
)
10758 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
);
10761 int tcc_add_library_path(TCCState
*s
, const char *pathname
)
10765 pathname1
= tcc_strdup(pathname
);
10766 dynarray_add((void ***)&s
->library_paths
, &s
->nb_library_paths
, pathname1
);
10770 /* find and load a dll. Return non zero if not found */
10771 /* XXX: add '-rpath' option support ? */
10772 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
)
10777 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
10778 snprintf(buf
, sizeof(buf
), "%s/%s",
10779 s
->library_paths
[i
], filename
);
10780 if (tcc_add_file_internal(s
, buf
, flags
) == 0)
10786 /* the library name is the same as the argument of the '-l' option */
10787 int tcc_add_library(TCCState
*s
, const char *libraryname
)
10792 /* first we look for the dynamic library if not static linking */
10793 if (!s
->static_link
) {
10794 #ifdef TCC_TARGET_PE
10795 snprintf(buf
, sizeof(buf
), "%s.def", libraryname
);
10797 snprintf(buf
, sizeof(buf
), "lib%s.so", libraryname
);
10799 if (tcc_add_dll(s
, buf
, 0) == 0)
10803 /* then we look for the static library */
10804 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
10805 snprintf(buf
, sizeof(buf
), "%s/lib%s.a",
10806 s
->library_paths
[i
], libraryname
);
10807 if (tcc_add_file_internal(s
, buf
, 0) == 0)
10813 int tcc_add_symbol(TCCState
*s
, const char *name
, void *val
)
10815 add_elf_sym(symtab_section
, (unsigned long)val
, 0,
10816 ELFW(ST_INFO
)(STB_GLOBAL
, STT_NOTYPE
), 0,
10821 int tcc_set_output_type(TCCState
*s
, int output_type
)
10825 s
->output_type
= output_type
;
10827 if (!s
->nostdinc
) {
10828 /* default include paths */
10829 /* XXX: reverse order needed if -isystem support */
10830 #ifndef TCC_TARGET_PE
10831 tcc_add_sysinclude_path(s
, CONFIG_SYSROOT
"/usr/local/include");
10832 tcc_add_sysinclude_path(s
, CONFIG_SYSROOT
"/usr/include");
10834 snprintf(buf
, sizeof(buf
), "%s/include", tcc_lib_path
);
10835 tcc_add_sysinclude_path(s
, buf
);
10836 #ifdef TCC_TARGET_PE
10837 snprintf(buf
, sizeof(buf
), "%s/include/winapi", tcc_lib_path
);
10838 tcc_add_sysinclude_path(s
, buf
);
10842 /* if bound checking, then add corresponding sections */
10843 #ifdef CONFIG_TCC_BCHECK
10844 if (do_bounds_check
) {
10845 /* define symbol */
10846 tcc_define_symbol(s
, "__BOUNDS_CHECKING_ON", NULL
);
10847 /* create bounds sections */
10848 bounds_section
= new_section(s
, ".bounds",
10849 SHT_PROGBITS
, SHF_ALLOC
);
10850 lbounds_section
= new_section(s
, ".lbounds",
10851 SHT_PROGBITS
, SHF_ALLOC
);
10855 if (s
->char_is_unsigned
) {
10856 tcc_define_symbol(s
, "__CHAR_UNSIGNED__", NULL
);
10859 /* add debug sections */
10862 stab_section
= new_section(s
, ".stab", SHT_PROGBITS
, 0);
10863 stab_section
->sh_entsize
= sizeof(Stab_Sym
);
10864 stabstr_section
= new_section(s
, ".stabstr", SHT_STRTAB
, 0);
10865 put_elf_str(stabstr_section
, "");
10866 stab_section
->link
= stabstr_section
;
10867 /* put first entry */
10868 put_stabs("", 0, 0, 0, 0);
10871 /* add libc crt1/crti objects */
10872 #ifndef TCC_TARGET_PE
10873 if ((output_type
== TCC_OUTPUT_EXE
|| output_type
== TCC_OUTPUT_DLL
) &&
10875 if (output_type
!= TCC_OUTPUT_DLL
)
10876 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crt1.o");
10877 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crti.o");
10881 #ifdef TCC_TARGET_PE
10882 snprintf(buf
, sizeof(buf
), "%s/lib", tcc_lib_path
);
10883 tcc_add_library_path(s
, buf
);
10889 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
10890 #define FD_INVERT 0x0002 /* invert value before storing */
10892 typedef struct FlagDef
{
10898 static const FlagDef warning_defs
[] = {
10899 { offsetof(TCCState
, warn_unsupported
), 0, "unsupported" },
10900 { offsetof(TCCState
, warn_write_strings
), 0, "write-strings" },
10901 { offsetof(TCCState
, warn_error
), 0, "error" },
10902 { offsetof(TCCState
, warn_implicit_function_declaration
), WD_ALL
,
10903 "implicit-function-declaration" },
10906 static int set_flag(TCCState
*s
, const FlagDef
*flags
, int nb_flags
,
10907 const char *name
, int value
)
10914 if (r
[0] == 'n' && r
[1] == 'o' && r
[2] == '-') {
10918 for(i
= 0, p
= flags
; i
< nb_flags
; i
++, p
++) {
10919 if (!strcmp(r
, p
->name
))
10924 if (p
->flags
& FD_INVERT
)
10926 *(int *)((uint8_t *)s
+ p
->offset
) = value
;
10931 /* set/reset a warning */
10932 int tcc_set_warning(TCCState
*s
, const char *warning_name
, int value
)
10937 if (!strcmp(warning_name
, "all")) {
10938 for(i
= 0, p
= warning_defs
; i
< countof(warning_defs
); i
++, p
++) {
10939 if (p
->flags
& WD_ALL
)
10940 *(int *)((uint8_t *)s
+ p
->offset
) = 1;
10944 return set_flag(s
, warning_defs
, countof(warning_defs
),
10945 warning_name
, value
);
10949 static const FlagDef flag_defs
[] = {
10950 { offsetof(TCCState
, char_is_unsigned
), 0, "unsigned-char" },
10951 { offsetof(TCCState
, char_is_unsigned
), FD_INVERT
, "signed-char" },
10952 { offsetof(TCCState
, nocommon
), FD_INVERT
, "common" },
10953 { offsetof(TCCState
, leading_underscore
), 0, "leading-underscore" },
10956 /* set/reset a flag */
10957 int tcc_set_flag(TCCState
*s
, const char *flag_name
, int value
)
10959 return set_flag(s
, flag_defs
, countof(flag_defs
),
10963 #if !defined(LIBTCC)
10965 static int64_t getclock_us(void)
10970 return (tb
.time
* 1000LL + tb
.millitm
) * 1000LL;
10973 gettimeofday(&tv
, NULL
);
10974 return tv
.tv_sec
* 1000000LL + tv
.tv_usec
;
10980 printf("tcc version " TCC_VERSION
" - Tiny C Compiler - Copyright (C) 2001-2006 Fabrice Bellard\n"
10981 "usage: tcc [-v] [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"
10982 " [-Wwarn] [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-soname name]\n"
10983 " [-static] [infile1 infile2...] [-run infile args...]\n"
10985 "General options:\n"
10986 " -v display current version, increase verbosity\n"
10987 " -c compile only - generate an object file\n"
10988 " -o outfile set output filename\n"
10989 " -Bdir set tcc internal library path\n"
10990 " -bench output compilation statistics\n"
10991 " -run run compiled source\n"
10992 " -fflag set or reset (with 'no-' prefix) 'flag' (see man page)\n"
10993 " -Wwarning set or reset (with 'no-' prefix) 'warning' (see man page)\n"
10994 " -w disable all warnings\n"
10995 "Preprocessor options:\n"
10996 " -E preprocess only\n"
10997 " -Idir add include path 'dir'\n"
10998 " -Dsym[=val] define 'sym' with value 'val'\n"
10999 " -Usym undefine 'sym'\n"
11000 "Linker options:\n"
11001 " -Ldir add library path 'dir'\n"
11002 " -llib link with dynamic or static library 'lib'\n"
11003 " -shared generate a shared library\n"
11004 " -soname set name for shared library to be used at runtime\n"
11005 " -static static linking\n"
11006 " -rdynamic export all global symbols to dynamic linker\n"
11007 " -r generate (relocatable) object file\n"
11008 "Debugger options:\n"
11009 " -g generate runtime debug info\n"
11010 #ifdef CONFIG_TCC_BCHECK
11011 " -b compile with built-in memory and bounds checker (implies -g)\n"
11013 " -bt N show N callers in stack traces\n"
11017 #define TCC_OPTION_HAS_ARG 0x0001
11018 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
11020 typedef struct TCCOption
{
11049 TCC_OPTION_nostdinc
,
11050 TCC_OPTION_nostdlib
,
11051 TCC_OPTION_print_search_dirs
,
11052 TCC_OPTION_rdynamic
,
11060 static const TCCOption tcc_options
[] = {
11061 { "h", TCC_OPTION_HELP
, 0 },
11062 { "?", TCC_OPTION_HELP
, 0 },
11063 { "I", TCC_OPTION_I
, TCC_OPTION_HAS_ARG
},
11064 { "D", TCC_OPTION_D
, TCC_OPTION_HAS_ARG
},
11065 { "U", TCC_OPTION_U
, TCC_OPTION_HAS_ARG
},
11066 { "L", TCC_OPTION_L
, TCC_OPTION_HAS_ARG
},
11067 { "B", TCC_OPTION_B
, TCC_OPTION_HAS_ARG
},
11068 { "l", TCC_OPTION_l
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11069 { "bench", TCC_OPTION_bench
, 0 },
11070 { "bt", TCC_OPTION_bt
, TCC_OPTION_HAS_ARG
},
11071 #ifdef CONFIG_TCC_BCHECK
11072 { "b", TCC_OPTION_b
, 0 },
11074 { "g", TCC_OPTION_g
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11075 { "c", TCC_OPTION_c
, 0 },
11076 { "static", TCC_OPTION_static
, 0 },
11077 { "shared", TCC_OPTION_shared
, 0 },
11078 { "soname", TCC_OPTION_soname
, TCC_OPTION_HAS_ARG
},
11079 { "o", TCC_OPTION_o
, TCC_OPTION_HAS_ARG
},
11080 { "run", TCC_OPTION_run
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11081 { "rdynamic", TCC_OPTION_rdynamic
, 0 },
11082 { "r", TCC_OPTION_r
, 0 },
11083 { "Wl,", TCC_OPTION_Wl
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11084 { "W", TCC_OPTION_W
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11085 { "O", TCC_OPTION_O
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11086 { "m", TCC_OPTION_m
, TCC_OPTION_HAS_ARG
},
11087 { "f", TCC_OPTION_f
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11088 { "nostdinc", TCC_OPTION_nostdinc
, 0 },
11089 { "nostdlib", TCC_OPTION_nostdlib
, 0 },
11090 { "print-search-dirs", TCC_OPTION_print_search_dirs
, 0 },
11091 { "v", TCC_OPTION_v
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11092 { "w", TCC_OPTION_w
, 0 },
11093 { "pipe", TCC_OPTION_pipe
, 0},
11094 { "E", TCC_OPTION_E
, 0},
11098 /* convert 'str' into an array of space separated strings */
11099 static int expand_args(char ***pargv
, const char *str
)
11108 while (is_space(*str
))
11113 while (*str
!= '\0' && !is_space(*str
))
11116 arg
= tcc_malloc(len
+ 1);
11117 memcpy(arg
, s1
, len
);
11119 dynarray_add((void ***)&argv
, &argc
, arg
);
11125 static char **files
;
11126 static int nb_files
, nb_libraries
;
11127 static int multiple_files
;
11128 static int print_search_dirs
;
11129 static int output_type
;
11130 static int reloc_output
;
11131 static const char *outfile
;
11133 int parse_args(TCCState
*s
, int argc
, char **argv
)
11136 const TCCOption
*popt
;
11137 const char *optarg
, *p1
, *r1
;
11141 while (optind
< argc
) {
11143 r
= argv
[optind
++];
11144 if (r
[0] != '-' || r
[1] == '\0') {
11145 /* add a new file */
11146 dynarray_add((void ***)&files
, &nb_files
, r
);
11147 if (!multiple_files
) {
11149 /* argv[0] will be this file */
11153 /* find option in table (match only the first chars */
11154 popt
= tcc_options
;
11158 error("invalid option -- '%s'", r
);
11171 if (popt
->flags
& TCC_OPTION_HAS_ARG
) {
11172 if (*r1
!= '\0' || (popt
->flags
& TCC_OPTION_NOSEP
)) {
11175 if (optind
>= argc
)
11176 error("argument to '%s' is missing", r
);
11177 optarg
= argv
[optind
++];
11185 switch(popt
->index
) {
11186 case TCC_OPTION_HELP
:
11190 if (tcc_add_include_path(s
, optarg
) < 0)
11191 error("too many include paths");
11196 sym
= (char *)optarg
;
11197 value
= strchr(sym
, '=');
11202 tcc_define_symbol(s
, sym
, value
);
11206 tcc_undefine_symbol(s
, optarg
);
11209 tcc_add_library_path(s
, optarg
);
11212 /* set tcc utilities path (mainly for tcc development) */
11213 tcc_lib_path
= optarg
;
11216 dynarray_add((void ***)&files
, &nb_files
, r
);
11219 case TCC_OPTION_bench
:
11222 case TCC_OPTION_bt
:
11223 num_callers
= atoi(optarg
);
11225 #ifdef CONFIG_TCC_BCHECK
11227 do_bounds_check
= 1;
11235 multiple_files
= 1;
11236 output_type
= TCC_OUTPUT_OBJ
;
11238 case TCC_OPTION_static
:
11239 s
->static_link
= 1;
11241 case TCC_OPTION_shared
:
11242 output_type
= TCC_OUTPUT_DLL
;
11244 case TCC_OPTION_soname
:
11245 s
->soname
= optarg
;
11248 multiple_files
= 1;
11252 /* generate a .o merging several output files */
11254 output_type
= TCC_OUTPUT_OBJ
;
11256 case TCC_OPTION_nostdinc
:
11259 case TCC_OPTION_nostdlib
:
11262 case TCC_OPTION_print_search_dirs
:
11263 print_search_dirs
= 1;
11265 case TCC_OPTION_run
:
11269 argc1
= expand_args(&argv1
, optarg
);
11271 parse_args(s
, argc1
, argv1
);
11273 multiple_files
= 0;
11274 output_type
= TCC_OUTPUT_MEMORY
;
11279 if (0 == verbose
++)
11280 printf("tcc version %s\n", TCC_VERSION
);
11281 } while (*optarg
++ == 'v');
11284 if (tcc_set_flag(s
, optarg
, 1) < 0 && s
->warn_unsupported
)
11285 goto unsupported_option
;
11288 if (tcc_set_warning(s
, optarg
, 1) < 0 &&
11289 s
->warn_unsupported
)
11290 goto unsupported_option
;
11295 case TCC_OPTION_rdynamic
:
11298 case TCC_OPTION_Wl
:
11301 if (strstart(optarg
, "-Ttext,", &p
)) {
11302 s
->text_addr
= strtoul(p
, NULL
, 16);
11303 s
->has_text_addr
= 1;
11304 } else if (strstart(optarg
, "--oformat,", &p
)) {
11305 if (strstart(p
, "elf32-", NULL
)) {
11306 s
->output_format
= TCC_OUTPUT_FORMAT_ELF
;
11307 } else if (!strcmp(p
, "binary")) {
11308 s
->output_format
= TCC_OUTPUT_FORMAT_BINARY
;
11310 #ifdef TCC_TARGET_COFF
11311 if (!strcmp(p
, "coff")) {
11312 s
->output_format
= TCC_OUTPUT_FORMAT_COFF
;
11316 error("target %s not found", p
);
11319 error("unsupported linker option '%s'", optarg
);
11324 output_type
= TCC_OUTPUT_PREPROCESS
;
11327 if (s
->warn_unsupported
) {
11328 unsupported_option
:
11329 warning("unsupported option '%s'", r
);
11338 int main(int argc
, char **argv
)
11342 int nb_objfiles
, ret
, optind
;
11343 char objfilename
[1024];
11344 int64_t start_time
= 0;
11347 tcc_lib_path
= w32_tcc_lib_path();
11351 output_type
= TCC_OUTPUT_EXE
;
11353 multiple_files
= 1;
11358 print_search_dirs
= 0;
11361 optind
= parse_args(s
, argc
- 1, argv
+ 1);
11362 if (print_search_dirs
) {
11363 /* enough for Linux kernel */
11364 printf("install: %s/\n", tcc_lib_path
);
11367 if (optind
== 0 || nb_files
== 0) {
11368 if (optind
&& verbose
)
11374 nb_objfiles
= nb_files
- nb_libraries
;
11376 /* if outfile provided without other options, we output an
11378 if (outfile
&& output_type
== TCC_OUTPUT_MEMORY
)
11379 output_type
= TCC_OUTPUT_EXE
;
11381 /* check -c consistency : only single file handled. XXX: checks file type */
11382 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
11383 /* accepts only a single input file */
11384 if (nb_objfiles
!= 1)
11385 error("cannot specify multiple files with -c");
11386 if (nb_libraries
!= 0)
11387 error("cannot specify libraries with -c");
11391 if (output_type
== TCC_OUTPUT_PREPROCESS
) {
11393 s
->outfile
= stdout
;
11395 s
->outfile
= fopen(outfile
, "w");
11397 error("could not open '%s", outfile
);
11399 } else if (output_type
!= TCC_OUTPUT_MEMORY
) {
11401 /* compute default outfile name */
11404 strcmp(files
[0], "-") == 0 ? "a" : tcc_basename(files
[0]);
11405 pstrcpy(objfilename
, sizeof(objfilename
), name
);
11406 ext
= tcc_fileextension(objfilename
);
11407 #ifdef TCC_TARGET_PE
11408 if (output_type
== TCC_OUTPUT_DLL
)
11409 strcpy(ext
, ".dll");
11411 if (output_type
== TCC_OUTPUT_EXE
)
11412 strcpy(ext
, ".exe");
11415 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
&& *ext
)
11418 pstrcpy(objfilename
, sizeof(objfilename
), "a.out");
11419 outfile
= objfilename
;
11424 start_time
= getclock_us();
11427 tcc_set_output_type(s
, output_type
);
11429 /* compile or add each files or library */
11430 for(i
= 0; i
< nb_files
&& ret
== 0; i
++) {
11431 const char *filename
;
11433 filename
= files
[i
];
11434 if (output_type
== TCC_OUTPUT_PREPROCESS
) {
11435 if (tcc_add_file_internal(s
, filename
,
11436 AFF_PRINT_ERROR
| AFF_PREPROCESS
) < 0)
11438 } else if (filename
[0] == '-' && filename
[1]) {
11439 if (tcc_add_library(s
, filename
+ 2) < 0)
11440 error("cannot find %s", filename
);
11443 printf("-> %s\n", filename
);
11444 if (tcc_add_file(s
, filename
) < 0)
11449 /* free all files */
11457 total_time
= (double)(getclock_us() - start_time
) / 1000000.0;
11458 if (total_time
< 0.001)
11459 total_time
= 0.001;
11460 if (total_bytes
< 1)
11462 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
11463 tok_ident
- TOK_IDENT
, total_lines
, total_bytes
,
11464 total_time
, (int)(total_lines
/ total_time
),
11465 total_bytes
/ total_time
/ 1000000.0);
11468 if (s
->output_type
== TCC_OUTPUT_PREPROCESS
) {
11470 fclose(s
->outfile
);
11471 } else if (s
->output_type
== TCC_OUTPUT_MEMORY
) {
11472 ret
= tcc_run(s
, argc
- optind
, argv
+ optind
);
11474 ret
= tcc_output_file(s
, outfile
) ? 1 : 0;
11476 /* XXX: cannot do it with bound checking because of the malloc hooks */
11477 if (!do_bounds_check
)
11482 printf("memory: %d bytes, max = %d bytes\n", mem_cur_size
, mem_max_size
);