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
42 #include <sys/timeb.h>
47 #include <sys/ucontext.h>
51 #endif /* !CONFIG_TCCBOOT */
68 /* preprocessor debug */
70 /* include file debug */
78 /* target selection */
79 //#define TCC_TARGET_I386 /* i386 code generator */
80 //#define TCC_TARGET_ARM /* ARMv4 code generator */
81 //#define TCC_TARGET_C67 /* TMS320C67xx code generator */
83 /* default target is I386 */
84 #if !defined(TCC_TARGET_I386) && !defined(TCC_TARGET_ARM) && \
85 !defined(TCC_TARGET_C67)
86 #define TCC_TARGET_I386
89 #if !defined(_WIN32) && !defined(TCC_UCLIBC) && !defined(TCC_TARGET_ARM) && \
90 !defined(TCC_TARGET_C67)
91 #define CONFIG_TCC_BCHECK /* enable bound checking code */
94 #if defined(_WIN32) && !defined(TCC_TARGET_PE)
95 #define CONFIG_TCC_STATIC
98 /* define it to include assembler support */
99 #if !defined(TCC_TARGET_ARM) && !defined(TCC_TARGET_C67)
100 #define CONFIG_TCC_ASM
103 /* object format selection */
104 #if defined(TCC_TARGET_C67)
105 #define TCC_TARGET_COFF
114 /* path to find crt1.o, crti.o and crtn.o. Only needed when generating
115 executables or dlls */
116 #define CONFIG_TCC_CRT_PREFIX CONFIG_SYSROOT "/usr/lib"
118 #define INCLUDE_STACK_SIZE 32
119 #define IFDEF_STACK_SIZE 64
120 #define VSTACK_SIZE 256
121 #define STRING_MAX_SIZE 1024
122 #define PACK_STACK_SIZE 8
124 #define TOK_HASH_SIZE 8192 /* must be a power of two */
125 #define TOK_ALLOC_INCR 512 /* must be a power of two */
126 #define TOK_MAX_SIZE 4 /* token max size in int unit when stored in string */
128 /* token symbol management */
129 typedef struct TokenSym
{
130 struct TokenSym
*hash_next
;
131 struct Sym
*sym_define
; /* direct pointer to define */
132 struct Sym
*sym_label
; /* direct pointer to label */
133 struct Sym
*sym_struct
; /* direct pointer to structure */
134 struct Sym
*sym_identifier
; /* direct pointer to identifier */
135 int tok
; /* token number */
141 typedef unsigned short nwchar_t
;
143 typedef int nwchar_t
;
146 typedef struct CString
{
147 int size
; /* size in bytes */
148 void *data
; /* either 'char *' or 'nwchar_t *' */
150 void *data_allocated
; /* if non NULL, data has been malloced */
153 /* type definition */
154 typedef struct CType
{
160 typedef union CValue
{
166 unsigned int ul
; /* address (should be unsigned long on 64 bit cpu) */
168 unsigned long long ull
;
169 struct CString
*cstr
;
175 typedef struct SValue
{
176 CType type
; /* type */
177 unsigned short r
; /* register + flags */
178 unsigned short r2
; /* second register, used for 'long long'
179 type. If not used, set to VT_CONST */
180 CValue c
; /* constant, if VT_CONST */
181 struct Sym
*sym
; /* symbol, if (VT_SYM | VT_CONST) */
184 /* symbol management */
186 int v
; /* symbol token */
187 int r
; /* associated register */
188 int c
; /* associated number */
189 CType type
; /* associated type */
190 struct Sym
*next
; /* next related symbol */
191 struct Sym
*prev
; /* prev symbol in stack */
192 struct Sym
*prev_tok
; /* previous symbol for this token */
195 /* section definition */
196 /* XXX: use directly ELF structure for parameters ? */
197 /* special flag to indicate that the section should not be linked to
199 #define SHF_PRIVATE 0x80000000
201 typedef struct Section
{
202 unsigned long data_offset
; /* current data offset */
203 unsigned char *data
; /* section data */
204 unsigned long data_allocated
; /* used for realloc() handling */
205 int sh_name
; /* elf section name (only used during output) */
206 int sh_num
; /* elf section number */
207 int sh_type
; /* elf section type */
208 int sh_flags
; /* elf section flags */
209 int sh_info
; /* elf section info */
210 int sh_addralign
; /* elf section alignment */
211 int sh_entsize
; /* elf entry size */
212 unsigned long sh_size
; /* section size (only used during output) */
213 unsigned long sh_addr
; /* address at which the section is relocated */
214 unsigned long sh_offset
; /* file offset */
215 int nb_hashed_syms
; /* used to resize the hash table */
216 struct Section
*link
; /* link to another section */
217 struct Section
*reloc
; /* corresponding section for relocation, if any */
218 struct Section
*hash
; /* hash table for symbols */
219 struct Section
*next
;
220 char name
[1]; /* section name */
223 typedef struct DLLReference
{
229 /* GNUC attribute definition */
230 typedef struct AttributeDef
{
234 int func_attr
; /* calling convention, exports, ... */
237 /* -------------------------------------------------- */
238 /* gr: wrappers for casting sym->r for other purposes */
246 #define FUNC_CALL(r) (((func_attr_t*)&(r))->func_call)
247 #define FUNC_EXPORT(r) (((func_attr_t*)&(r))->func_export)
248 #define FUNC_ARGS(r) (((func_attr_t*)&(r))->func_args)
249 #define INLINE_DEF(r) (*(int **)&(r))
250 /* -------------------------------------------------- */
252 #define SYM_STRUCT 0x40000000 /* struct/union/enum symbol space */
253 #define SYM_FIELD 0x20000000 /* struct/union field symbol space */
254 #define SYM_FIRST_ANOM 0x10000000 /* first anonymous sym */
256 /* stored in 'Sym.c' field */
257 #define FUNC_NEW 1 /* ansi function prototype */
258 #define FUNC_OLD 2 /* old function prototype */
259 #define FUNC_ELLIPSIS 3 /* ansi function prototype with ... */
261 /* stored in 'Sym.r' field */
262 #define FUNC_CDECL 0 /* standard c call */
263 #define FUNC_STDCALL 1 /* pascal c call */
264 #define FUNC_FASTCALL1 2 /* first param in %eax */
265 #define FUNC_FASTCALL2 3 /* first parameters in %eax, %edx */
266 #define FUNC_FASTCALL3 4 /* first parameter in %eax, %edx, %ecx */
267 #define FUNC_FASTCALLW 5 /* first parameter in %ecx, %edx */
269 /* field 'Sym.t' for macros */
270 #define MACRO_OBJ 0 /* object like macro */
271 #define MACRO_FUNC 1 /* function like macro */
273 /* field 'Sym.r' for C labels */
274 #define LABEL_DEFINED 0 /* label is defined */
275 #define LABEL_FORWARD 1 /* label is forward defined */
276 #define LABEL_DECLARED 2 /* label is declared but never used */
278 /* type_decl() types */
279 #define TYPE_ABSTRACT 1 /* type without variable */
280 #define TYPE_DIRECT 2 /* type with variable */
282 #define IO_BUF_SIZE 8192
284 typedef struct BufferedFile
{
288 int line_num
; /* current line number - here to simplify code */
289 int ifndef_macro
; /* #ifndef macro / #endif search */
290 int ifndef_macro_saved
; /* saved ifndef_macro */
291 int *ifdef_stack_ptr
; /* ifdef_stack value at the start of the file */
292 char inc_type
; /* type of include */
293 char inc_filename
[512]; /* filename specified by the user */
294 char filename
[1024]; /* current filename - here to simplify code */
295 unsigned char buffer
[IO_BUF_SIZE
+ 1]; /* extra size for CH_EOB char */
298 #define CH_EOB '\\' /* end of buffer or '\0' char in file */
299 #define CH_EOF (-1) /* end of file */
301 /* parsing state (used to save parser state to reparse part of the
302 source several times) */
303 typedef struct ParseState
{
310 /* used to record tokens */
311 typedef struct TokenString
{
318 /* include file cache, used to find files faster and also to eliminate
319 inclusion if the include file is protected by #ifndef ... #endif */
320 typedef struct CachedInclude
{
322 int hash_next
; /* -1 if none */
323 char type
; /* '"' or '>' to give include type */
324 char filename
[1]; /* path specified in #include */
327 #define CACHED_INCLUDES_HASH_SIZE 512
330 static struct BufferedFile
*file
;
333 static CString tokcstr
; /* current parsed string, if any */
334 /* additional informations about token */
335 static int tok_flags
;
336 #define TOK_FLAG_BOL 0x0001 /* beginning of line before */
337 #define TOK_FLAG_BOF 0x0002 /* beginning of file before */
338 #define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */
339 #define TOK_FLAG_EOF 0x0008 /* end of file */
341 static int *macro_ptr
, *macro_ptr_allocated
;
342 static int *unget_saved_macro_ptr
;
343 static int unget_saved_buffer
[TOK_MAX_SIZE
+ 1];
344 static int unget_buffer_enabled
;
345 static int parse_flags
;
346 #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
347 #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
348 #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
349 token. line feed is also
351 #define PARSE_FLAG_ASM_COMMENTS 0x0008 /* '#' can be used for line comment */
353 static Section
*text_section
, *data_section
, *bss_section
; /* predefined sections */
354 static Section
*cur_text_section
; /* current section where function code is
356 #ifdef CONFIG_TCC_ASM
357 static Section
*last_text_section
; /* to handle .previous asm directive */
359 /* bound check related sections */
360 static Section
*bounds_section
; /* contains global data bound description */
361 static Section
*lbounds_section
; /* contains local data bound description */
362 /* symbol sections */
363 static Section
*symtab_section
, *strtab_section
;
366 static Section
*stab_section
, *stabstr_section
;
368 /* loc : local variable index
369 ind : output code index
371 anon_sym: anonymous symbol index
373 static int rsym
, anon_sym
, ind
, loc
;
374 /* expression generation modifiers */
375 static int const_wanted
; /* true if constant wanted */
376 static int nocode_wanted
; /* true if no code generation wanted for an expression */
377 static int global_expr
; /* true if compound literals must be allocated
378 globally (used during initializers parsing */
379 static CType func_vt
; /* current function return type (used by return
382 static int last_line_num
, last_ind
, func_ind
; /* debug last line number and pc */
383 static int tok_ident
;
384 static TokenSym
**table_ident
;
385 static TokenSym
*hash_ident
[TOK_HASH_SIZE
];
386 static char token_buf
[STRING_MAX_SIZE
+ 1];
387 static char *funcname
;
388 static Sym
*global_stack
, *local_stack
;
389 static Sym
*define_stack
;
390 static Sym
*global_label_stack
, *local_label_stack
;
391 /* symbol allocator */
392 #define SYM_POOL_NB (8192 / sizeof(Sym))
393 static Sym
*sym_free_first
;
394 static void **sym_pools
;
395 static int nb_sym_pools
;
397 static SValue vstack
[VSTACK_SIZE
], *vtop
;
398 /* some predefined types */
399 static CType char_pointer_type
, func_old_type
, int_type
;
400 /* true if isid(c) || isnum(c) */
401 static unsigned char isidnum_table
[256-CH_EOF
];
403 /* display some information during compilation */
404 static int verbose
= 0;
406 /* compile with debug symbol (and use them if error during execution) */
407 static int do_debug
= 0;
409 /* compile with built-in memory and bounds checker */
410 static int do_bounds_check
= 0;
412 /* display benchmark infos */
414 static int do_bench
= 0;
416 static int total_lines
;
417 static int total_bytes
;
419 /* use GNU C extensions */
420 static int gnu_ext
= 1;
422 /* use Tiny C extensions */
423 static int tcc_ext
= 1;
425 /* max number of callers shown if error */
426 static int num_callers
= 6;
427 static const char **rt_bound_error_msg
;
429 /* XXX: get rid of this ASAP */
430 static struct TCCState
*tcc_state
;
432 /* give the path of the tcc libraries */
433 static const char *tcc_lib_path
= CONFIG_TCCDIR
;
438 BufferedFile
**include_stack_ptr
;
439 int *ifdef_stack_ptr
;
441 /* include file handling */
442 char **include_paths
;
443 int nb_include_paths
;
444 char **sysinclude_paths
;
445 int nb_sysinclude_paths
;
446 CachedInclude
**cached_includes
;
447 int nb_cached_includes
;
449 char **library_paths
;
450 int nb_library_paths
;
452 /* array of all loaded dlls (including those referenced by loaded
454 DLLReference
**loaded_dlls
;
459 int nb_sections
; /* number of sections, including first dummy section */
464 unsigned long *got_offsets
;
466 /* give the correspondance from symtab indexes to dynsym indexes */
467 int *symtab_to_dynsym
;
469 /* temporary dynamic symbol sections (for dll loading) */
470 Section
*dynsymtab_section
;
471 /* exported dynamic symbol section */
474 int nostdinc
; /* if true, no standard headers are added */
475 int nostdlib
; /* if true, no standard libraries are added */
477 int nocommon
; /* if true, do not use common symbols for .bss data */
479 /* if true, static linking is performed */
482 /* soname as specified on the command line (-soname) */
485 /* if true, all symbols are exported */
488 /* if true, only link in referenced objects from archive */
491 /* address of text section */
492 unsigned long text_addr
;
495 /* output format, see TCC_OUTPUT_FORMAT_xxx */
498 /* C language options */
499 int char_is_unsigned
;
500 int leading_underscore
;
502 /* warning switches */
503 int warn_write_strings
;
504 int warn_unsupported
;
507 int warn_implicit_function_declaration
;
511 void (*error_func
)(void *opaque
, const char *msg
);
512 int error_set_jmp_enabled
;
513 jmp_buf error_jmp_buf
;
516 /* tiny assembler state */
519 /* see include_stack_ptr */
520 BufferedFile
*include_stack
[INCLUDE_STACK_SIZE
];
522 /* see ifdef_stack_ptr */
523 int ifdef_stack
[IFDEF_STACK_SIZE
];
525 /* see cached_includes */
526 int cached_includes_hash
[CACHED_INCLUDES_HASH_SIZE
];
529 int pack_stack
[PACK_STACK_SIZE
];
532 /* output file for preprocessing */
536 /* The current value can be: */
537 #define VT_VALMASK 0x00ff
538 #define VT_CONST 0x00f0 /* constant in vc
539 (must be first non register value) */
540 #define VT_LLOCAL 0x00f1 /* lvalue, offset on stack */
541 #define VT_LOCAL 0x00f2 /* offset on stack */
542 #define VT_CMP 0x00f3 /* the value is stored in processor flags (in vc) */
543 #define VT_JMP 0x00f4 /* value is the consequence of jmp true (even) */
544 #define VT_JMPI 0x00f5 /* value is the consequence of jmp false (odd) */
545 #define VT_LVAL 0x0100 /* var is an lvalue */
546 #define VT_SYM 0x0200 /* a symbol value is added */
547 #define VT_MUSTCAST 0x0400 /* value must be casted to be correct (used for
548 char/short stored in integer registers) */
549 #define VT_MUSTBOUND 0x0800 /* bound checking must be done before
550 dereferencing value */
551 #define VT_BOUNDED 0x8000 /* value is bounded. The address of the
552 bounding function call point is in vc */
553 #define VT_LVAL_BYTE 0x1000 /* lvalue is a byte */
554 #define VT_LVAL_SHORT 0x2000 /* lvalue is a short */
555 #define VT_LVAL_UNSIGNED 0x4000 /* lvalue is unsigned */
556 #define VT_LVAL_TYPE (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
559 #define VT_INT 0 /* integer type */
560 #define VT_BYTE 1 /* signed byte type */
561 #define VT_SHORT 2 /* short type */
562 #define VT_VOID 3 /* void type */
563 #define VT_PTR 4 /* pointer */
564 #define VT_ENUM 5 /* enum definition */
565 #define VT_FUNC 6 /* function type */
566 #define VT_STRUCT 7 /* struct/union definition */
567 #define VT_FLOAT 8 /* IEEE float */
568 #define VT_DOUBLE 9 /* IEEE double */
569 #define VT_LDOUBLE 10 /* IEEE long double */
570 #define VT_BOOL 11 /* ISOC99 boolean type */
571 #define VT_LLONG 12 /* 64 bit integer */
572 #define VT_LONG 13 /* long integer (NEVER USED as type, only
574 #define VT_BTYPE 0x000f /* mask for basic type */
575 #define VT_UNSIGNED 0x0010 /* unsigned type */
576 #define VT_ARRAY 0x0020 /* array type (also has VT_PTR) */
577 #define VT_BITFIELD 0x0040 /* bitfield modifier */
578 #define VT_CONSTANT 0x0800 /* const modifier */
579 #define VT_VOLATILE 0x1000 /* volatile modifier */
580 #define VT_SIGNED 0x2000 /* signed type */
583 #define VT_EXTERN 0x00000080 /* extern definition */
584 #define VT_STATIC 0x00000100 /* static variable */
585 #define VT_TYPEDEF 0x00000200 /* typedef definition */
586 #define VT_INLINE 0x00000400 /* inline definition */
588 #define VT_STRUCT_SHIFT 16 /* shift for bitfield shift values */
590 /* type mask (except storage) */
591 #define VT_STORAGE (VT_EXTERN | VT_STATIC | VT_TYPEDEF | VT_INLINE)
592 #define VT_TYPE (~(VT_STORAGE))
596 /* warning: the following compare tokens depend on i386 asm code */
603 #define TOK_Nset 0x98
604 #define TOK_Nclear 0x99
610 #define TOK_LAND 0xa0
614 #define TOK_MID 0xa3 /* inc/dec, to void constant */
616 #define TOK_UDIV 0xb0 /* unsigned division */
617 #define TOK_UMOD 0xb1 /* unsigned modulo */
618 #define TOK_PDIV 0xb2 /* fast division with undefined rounding for pointers */
619 #define TOK_CINT 0xb3 /* number in tokc */
620 #define TOK_CCHAR 0xb4 /* char constant in tokc */
621 #define TOK_STR 0xb5 /* pointer to string in tokc */
622 #define TOK_TWOSHARPS 0xb6 /* ## preprocessing token */
623 #define TOK_LCHAR 0xb7
624 #define TOK_LSTR 0xb8
625 #define TOK_CFLOAT 0xb9 /* float constant */
626 #define TOK_LINENUM 0xba /* line number info */
627 #define TOK_CDOUBLE 0xc0 /* double constant */
628 #define TOK_CLDOUBLE 0xc1 /* long double constant */
629 #define TOK_UMULL 0xc2 /* unsigned 32x32 -> 64 mul */
630 #define TOK_ADDC1 0xc3 /* add with carry generation */
631 #define TOK_ADDC2 0xc4 /* add with carry use */
632 #define TOK_SUBC1 0xc5 /* add with carry generation */
633 #define TOK_SUBC2 0xc6 /* add with carry use */
634 #define TOK_CUINT 0xc8 /* unsigned int constant */
635 #define TOK_CLLONG 0xc9 /* long long constant */
636 #define TOK_CULLONG 0xca /* unsigned long long constant */
637 #define TOK_ARROW 0xcb
638 #define TOK_DOTS 0xcc /* three dots */
639 #define TOK_SHR 0xcd /* unsigned shift right */
640 #define TOK_PPNUM 0xce /* preprocessor number */
642 #define TOK_SHL 0x01 /* shift left */
643 #define TOK_SAR 0x02 /* signed shift right */
645 /* assignement operators : normal operator or 0x80 */
646 #define TOK_A_MOD 0xa5
647 #define TOK_A_AND 0xa6
648 #define TOK_A_MUL 0xaa
649 #define TOK_A_ADD 0xab
650 #define TOK_A_SUB 0xad
651 #define TOK_A_DIV 0xaf
652 #define TOK_A_XOR 0xde
653 #define TOK_A_OR 0xfc
654 #define TOK_A_SHL 0x81
655 #define TOK_A_SAR 0x82
658 #define offsetof(type, field) ((size_t) &((type *)0)->field)
662 #define countof(tab) (sizeof(tab) / sizeof((tab)[0]))
665 /* WARNING: the content of this string encodes token numbers */
666 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";
668 #define TOK_EOF (-1) /* end of file */
669 #define TOK_LINEFEED 10 /* line feed */
671 /* all identificators and strings have token above that */
672 #define TOK_IDENT 256
674 /* only used for i386 asm opcodes definitions */
675 #define DEF_ASM(x) DEF(TOK_ASM_ ## x, #x)
678 DEF(TOK_ASM_ ## x ## b, #x "b") \
679 DEF(TOK_ASM_ ## x ## w, #x "w") \
680 DEF(TOK_ASM_ ## x ## l, #x "l") \
681 DEF(TOK_ASM_ ## x, #x)
684 DEF(TOK_ASM_ ## x ## w, #x "w") \
685 DEF(TOK_ASM_ ## x ## l, #x "l") \
686 DEF(TOK_ASM_ ## x, #x)
689 DEF(TOK_ASM_ ## f ## x ## s, "f" #x "s") \
690 DEF(TOK_ASM_ ## fi ## x ## l, "fi" #x "l") \
691 DEF(TOK_ASM_ ## f ## x ## l, "f" #x "l") \
692 DEF(TOK_ASM_ ## fi ## x ## s, "fi" #x "s")
695 DEF(TOK_ASM_ ## f ## x, "f" #x ) \
696 DEF(TOK_ASM_ ## f ## x ## p, "f" #x "p") \
699 #define DEF_ASMTEST(x) \
731 #define TOK_ASM_int TOK_INT
734 TOK_LAST
= TOK_IDENT
- 1,
735 #define DEF(id, str) id,
740 static const char tcc_keywords
[] =
741 #define DEF(id, str) str "\0"
746 #define TOK_UIDENT TOK_DEFINE
749 #define snprintf _snprintf
750 #define vsnprintf _vsnprintf
752 #define strtold (long double)strtod
753 #define strtof (float)strtod
754 #define strtoll (long long)strtol
756 #elif defined(TCC_UCLIBC) || defined(__FreeBSD__) || defined(__DragonFly__) \
757 || defined(__OpenBSD__)
758 /* currently incorrect */
759 long double strtold(const char *nptr
, char **endptr
)
761 return (long double)strtod(nptr
, endptr
);
763 float strtof(const char *nptr
, char **endptr
)
765 return (float)strtod(nptr
, endptr
);
768 /* XXX: need to define this to use them in non ISOC99 context */
769 extern float strtof (const char *__nptr
, char **__endptr
);
770 extern long double strtold (const char *__nptr
, char **__endptr
);
773 static char *pstrcpy(char *buf
, int buf_size
, const char *s
);
774 static char *pstrcat(char *buf
, int buf_size
, const char *s
);
775 static char *tcc_basename(const char *name
);
776 static char *tcc_fileextension (const char *p
);
778 static void next(void);
779 static void next_nomacro(void);
780 static void parse_expr_type(CType
*type
);
781 static void expr_type(CType
*type
);
782 static void unary_type(CType
*type
);
783 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
784 int case_reg
, int is_expr
);
785 static int expr_const(void);
786 static void expr_eq(void);
787 static void gexpr(void);
788 static void gen_inline_functions(void);
789 static void decl(int l
);
790 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
791 int first
, int size_only
);
792 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
793 int has_init
, int v
, int scope
);
795 void gv2(int rc1
, int rc2
);
796 void move_reg(int r
, int s
);
797 void save_regs(int n
);
798 void save_reg(int r
);
803 int get_reg_ex(int rc
,int rc2
);
806 struct macro_level
*prev
;
810 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
811 const int *macro_str
, struct macro_level
**can_read_stream
);
813 void force_charshort_cast(int t
);
814 static void gen_cast(CType
*type
);
816 static Sym
*sym_find(int v
);
817 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
);
820 static int type_size(CType
*type
, int *a
);
821 static inline CType
*pointed_type(CType
*type
);
822 static int pointed_size(CType
*type
);
823 static int lvalue_type(int t
);
824 static int parse_btype(CType
*type
, AttributeDef
*ad
);
825 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
);
826 static int compare_types(CType
*type1
, CType
*type2
, int unqualified
);
827 static int is_compatible_types(CType
*type1
, CType
*type2
);
828 static int is_compatible_parameter_types(CType
*type1
, CType
*type2
);
830 int ieee_finite(double d
);
831 void error(const char *fmt
, ...);
835 void lexpand_nr(void);
836 static void vpush_global_sym(CType
*type
, int v
);
837 void vset(CType
*type
, int r
, int v
);
838 void type_to_str(char *buf
, int buf_size
,
839 CType
*type
, const char *varstr
);
840 char *get_tok_str(int v
, CValue
*cv
);
841 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
842 unsigned long offset
, unsigned long size
);
843 static Sym
*external_global_sym(int v
, CType
*type
, int r
);
845 /* section generation */
846 static void section_realloc(Section
*sec
, unsigned long new_size
);
847 static void *section_ptr_add(Section
*sec
, unsigned long size
);
848 static void put_extern_sym(Sym
*sym
, Section
*section
,
849 unsigned long value
, unsigned long size
);
850 static void greloc(Section
*s
, Sym
*sym
, unsigned long addr
, int type
);
851 static int put_elf_str(Section
*s
, const char *sym
);
852 static int put_elf_sym(Section
*s
,
853 unsigned long value
, unsigned long size
,
854 int info
, int other
, int shndx
, const char *name
);
855 static int add_elf_sym(Section
*s
, unsigned long value
, unsigned long size
,
856 int info
, int other
, int sh_num
, const char *name
);
857 static void put_elf_reloc(Section
*symtab
, Section
*s
, unsigned long offset
,
858 int type
, int symbol
);
859 static void put_stabs(const char *str
, int type
, int other
, int desc
,
860 unsigned long value
);
861 static void put_stabs_r(const char *str
, int type
, int other
, int desc
,
862 unsigned long value
, Section
*sec
, int sym_index
);
863 static void put_stabn(int type
, int other
, int desc
, int value
);
864 static void put_stabd(int type
, int other
, int desc
);
865 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
);
867 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
868 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
869 #define AFF_PREPROCESS 0x0004 /* preprocess file */
870 static int tcc_add_file_internal(TCCState
*s
, const char *filename
, int flags
);
873 int tcc_output_coff(TCCState
*s1
, FILE *f
);
876 void *resolve_sym(TCCState
*s1
, const char *sym
, int type
);
877 int pe_load_def_file(struct TCCState
*s1
, int fd
);
878 int pe_test_res_file(void *v
, int size
);
879 int pe_load_res_file(struct TCCState
*s1
, int fd
);
880 void pe_add_runtime(struct TCCState
*s1
);
881 void pe_guess_outfile(char *objfilename
, int output_type
);
882 int pe_output_file(struct TCCState
*s1
, const char *filename
);
886 #ifdef CONFIG_TCC_ASM
888 typedef struct ExprValue
{
893 #define MAX_ASM_OPERANDS 30
895 typedef struct ASMOperand
{
896 int id
; /* GCC 3 optionnal identifier (0 if number only supported */
898 char asm_str
[16]; /* computed asm string for operand */
899 SValue
*vt
; /* C value of the expression */
900 int ref_index
; /* if >= 0, gives reference to a output constraint */
901 int input_index
; /* if >= 0, gives reference to an input constraint */
902 int priority
; /* priority, used to assign registers */
903 int reg
; /* if >= 0, register number used for this operand */
904 int is_llong
; /* true if double register value */
905 int is_memory
; /* true if memory operand */
906 int is_rw
; /* for '+' modifier */
909 static void asm_expr(TCCState
*s1
, ExprValue
*pe
);
910 static int asm_int_expr(TCCState
*s1
);
911 static int find_constraint(ASMOperand
*operands
, int nb_operands
,
912 const char *name
, const char **pp
);
914 static int tcc_assemble(TCCState
*s1
, int do_preprocess
);
918 static void asm_instr(void);
919 static void asm_global_instr(void);
921 /* true if float/double/long double type */
922 static inline int is_float(int t
)
926 return bt
== VT_LDOUBLE
|| bt
== VT_DOUBLE
|| bt
== VT_FLOAT
;
929 #ifdef TCC_TARGET_I386
930 #include "i386-gen.c"
933 #ifdef TCC_TARGET_ARM
937 #ifdef TCC_TARGET_C67
941 #ifdef CONFIG_TCC_STATIC
943 #define RTLD_LAZY 0x001
944 #define RTLD_NOW 0x002
945 #define RTLD_GLOBAL 0x100
946 #define RTLD_DEFAULT NULL
948 /* dummy function for profiling */
949 void *dlopen(const char *filename
, int flag
)
954 const char *dlerror(void)
959 typedef struct TCCSyms
{
964 #define TCCSYM(a) { #a, &a, },
966 /* add the symbol you want here if no dynamic linking is done */
967 static TCCSyms tcc_syms
[] = {
968 #if !defined(CONFIG_TCCBOOT)
977 void *resolve_sym(TCCState
*s1
, const char *symbol
, int type
)
981 while (p
->str
!= NULL
) {
982 if (!strcmp(p
->str
, symbol
))
989 #elif !defined(_WIN32)
993 void *resolve_sym(TCCState
*s1
, const char *sym
, int type
)
995 return dlsym(RTLD_DEFAULT
, sym
);
1000 /********************************************************/
1002 /* we use our own 'finite' function to avoid potential problems with
1003 non standard math libs */
1004 /* XXX: endianness dependent */
1005 int ieee_finite(double d
)
1008 return ((unsigned)((p
[1] | 0x800fffff) + 1)) >> 31;
1011 /* copy a string and truncate it. */
1012 static char *pstrcpy(char *buf
, int buf_size
, const char *s
)
1019 q_end
= buf
+ buf_size
- 1;
1031 /* strcat and truncate. */
1032 static char *pstrcat(char *buf
, int buf_size
, const char *s
)
1037 pstrcpy(buf
+ len
, buf_size
- len
, s
);
1042 static int strstart(const char *str
, const char *val
, const char **ptr
)
1047 while (*q
!= '\0') {
1059 /* extract the basename of a file */
1060 static char *tcc_basename(const char *name
)
1062 char *p
= strchr(name
, 0);
1073 static char *tcc_fileextension (const char *name
)
1075 char *b
= tcc_basename(name
);
1076 char *e
= strrchr(b
, '.');
1077 return e
? e
: strchr(b
, 0);
1081 char *normalize_slashes(char *path
)
1084 for (p
= path
; *p
; ++p
)
1090 char *w32_tcc_lib_path(void)
1092 /* on win32, we suppose the lib and includes are at the location
1094 char path
[1024], *p
;
1095 GetModuleFileNameA(NULL
, path
, sizeof path
);
1096 p
= tcc_basename(normalize_slashes(strlwr(path
)));
1097 if (p
- 5 > path
&& 0 == strncmp(p
- 5, "/bin/", 5))
1102 return strdup(path
);
1106 void set_pages_executable(void *ptr
, unsigned long length
)
1109 unsigned long old_protect
;
1110 VirtualProtect(ptr
, length
, PAGE_EXECUTE_READWRITE
, &old_protect
);
1112 unsigned long start
, end
;
1113 start
= (unsigned long)ptr
& ~(PAGESIZE
- 1);
1114 end
= (unsigned long)ptr
+ length
;
1115 end
= (end
+ PAGESIZE
- 1) & ~(PAGESIZE
- 1);
1116 mprotect((void *)start
, end
- start
, PROT_READ
| PROT_WRITE
| PROT_EXEC
);
1120 /* memory management */
1124 unsigned malloc_usable_size(void*);
1127 static inline void tcc_free(void *ptr
)
1130 mem_cur_size
-= malloc_usable_size(ptr
);
1135 static void *tcc_malloc(unsigned long size
)
1140 error("memory full");
1142 mem_cur_size
+= malloc_usable_size(ptr
);
1143 if (mem_cur_size
> mem_max_size
)
1144 mem_max_size
= mem_cur_size
;
1149 static void *tcc_mallocz(unsigned long size
)
1152 ptr
= tcc_malloc(size
);
1153 memset(ptr
, 0, size
);
1157 static inline void *tcc_realloc(void *ptr
, unsigned long size
)
1161 mem_cur_size
-= malloc_usable_size(ptr
);
1163 ptr1
= realloc(ptr
, size
);
1165 /* NOTE: count not correct if alloc error, but not critical */
1166 mem_cur_size
+= malloc_usable_size(ptr1
);
1167 if (mem_cur_size
> mem_max_size
)
1168 mem_max_size
= mem_cur_size
;
1173 static char *tcc_strdup(const char *str
)
1176 ptr
= tcc_malloc(strlen(str
) + 1);
1181 #define free(p) use_tcc_free(p)
1182 #define malloc(s) use_tcc_malloc(s)
1183 #define realloc(p, s) use_tcc_realloc(p, s)
1185 static void dynarray_add(void ***ptab
, int *nb_ptr
, void *data
)
1192 /* every power of two we double array size */
1193 if ((nb
& (nb
- 1)) == 0) {
1198 pp
= tcc_realloc(pp
, nb_alloc
* sizeof(void *));
1200 error("memory full");
1207 static void dynarray_reset(void *pp
, int *n
)
1210 for (p
= *(void***)pp
; *n
; ++p
, --*n
)
1213 tcc_free(*(void**)pp
);
1217 /* symbol allocator */
1218 static Sym
*__sym_malloc(void)
1220 Sym
*sym_pool
, *sym
, *last_sym
;
1223 sym_pool
= tcc_malloc(SYM_POOL_NB
* sizeof(Sym
));
1224 dynarray_add(&sym_pools
, &nb_sym_pools
, sym_pool
);
1226 last_sym
= sym_free_first
;
1228 for(i
= 0; i
< SYM_POOL_NB
; i
++) {
1229 sym
->next
= last_sym
;
1233 sym_free_first
= last_sym
;
1237 static inline Sym
*sym_malloc(void)
1240 sym
= sym_free_first
;
1242 sym
= __sym_malloc();
1243 sym_free_first
= sym
->next
;
1247 static inline void sym_free(Sym
*sym
)
1249 sym
->next
= sym_free_first
;
1250 sym_free_first
= sym
;
1253 Section
*new_section(TCCState
*s1
, const char *name
, int sh_type
, int sh_flags
)
1257 sec
= tcc_mallocz(sizeof(Section
) + strlen(name
));
1258 strcpy(sec
->name
, name
);
1259 sec
->sh_type
= sh_type
;
1260 sec
->sh_flags
= sh_flags
;
1267 sec
->sh_addralign
= 4;
1270 sec
->sh_addralign
= 1;
1273 sec
->sh_addralign
= 32; /* default conservative alignment */
1277 /* only add section if not private */
1278 if (!(sh_flags
& SHF_PRIVATE
)) {
1279 sec
->sh_num
= s1
->nb_sections
;
1280 dynarray_add((void ***)&s1
->sections
, &s1
->nb_sections
, sec
);
1285 static void free_section(Section
*s
)
1287 if (s
->link
&& (s
->link
->sh_flags
& SHF_PRIVATE
))
1288 free_section(s
->link
);
1289 if (s
->hash
&& (s
->hash
->sh_flags
& SHF_PRIVATE
))
1290 s
->hash
->link
= NULL
, free_section(s
->hash
);
1295 /* realloc section and set its content to zero */
1296 static void section_realloc(Section
*sec
, unsigned long new_size
)
1299 unsigned char *data
;
1301 size
= sec
->data_allocated
;
1304 while (size
< new_size
)
1306 data
= tcc_realloc(sec
->data
, size
);
1308 error("memory full");
1309 memset(data
+ sec
->data_allocated
, 0, size
- sec
->data_allocated
);
1311 sec
->data_allocated
= size
;
1314 /* reserve at least 'size' bytes in section 'sec' from
1315 sec->data_offset. */
1316 static void *section_ptr_add(Section
*sec
, unsigned long size
)
1318 unsigned long offset
, offset1
;
1320 offset
= sec
->data_offset
;
1321 offset1
= offset
+ size
;
1322 if (offset1
> sec
->data_allocated
)
1323 section_realloc(sec
, offset1
);
1324 sec
->data_offset
= offset1
;
1325 return sec
->data
+ offset
;
1328 /* return a reference to a section, and create it if it does not
1330 Section
*find_section(TCCState
*s1
, const char *name
)
1334 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1335 sec
= s1
->sections
[i
];
1336 if (!strcmp(name
, sec
->name
))
1339 /* sections are created as PROGBITS */
1340 return new_section(s1
, name
, SHT_PROGBITS
, SHF_ALLOC
);
1343 #define SECTION_ABS ((void *)1)
1345 /* update sym->c so that it points to an external symbol in section
1346 'section' with value 'value' */
1347 static void put_extern_sym2(Sym
*sym
, Section
*section
,
1348 unsigned long value
, unsigned long size
,
1349 int can_add_underscore
)
1351 int sym_type
, sym_bind
, sh_num
, info
, other
, attr
;
1356 if (section
== NULL
)
1358 else if (section
== SECTION_ABS
)
1361 sh_num
= section
->sh_num
;
1365 if ((sym
->type
.t
& VT_BTYPE
) == VT_FUNC
) {
1366 sym_type
= STT_FUNC
;
1367 #ifdef TCC_TARGET_PE
1369 attr
= sym
->type
.ref
->r
;
1370 if (FUNC_EXPORT(attr
))
1372 if (FUNC_CALL(attr
) == FUNC_STDCALL
)
1376 sym_type
= STT_OBJECT
;
1379 if (sym
->type
.t
& VT_STATIC
)
1380 sym_bind
= STB_LOCAL
;
1382 sym_bind
= STB_GLOBAL
;
1385 name
= get_tok_str(sym
->v
, NULL
);
1386 #ifdef CONFIG_TCC_BCHECK
1387 if (do_bounds_check
) {
1390 /* XXX: avoid doing that for statics ? */
1391 /* if bound checking is activated, we change some function
1392 names by adding the "__bound" prefix */
1395 /* XXX: we rely only on malloc hooks */
1408 strcpy(buf
, "__bound_");
1416 #ifdef TCC_TARGET_PE
1417 if ((other
& 2) && can_add_underscore
) {
1418 sprintf(buf1
, "_%s@%d", name
, FUNC_ARGS(attr
));
1422 if (tcc_state
->leading_underscore
&& can_add_underscore
) {
1424 pstrcpy(buf1
+ 1, sizeof(buf1
) - 1, name
);
1427 info
= ELF32_ST_INFO(sym_bind
, sym_type
);
1428 sym
->c
= add_elf_sym(symtab_section
, value
, size
, info
, other
, sh_num
, name
);
1430 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
1431 esym
->st_value
= value
;
1432 esym
->st_size
= size
;
1433 esym
->st_shndx
= sh_num
;
1434 esym
->st_other
|= other
;
1438 static void put_extern_sym(Sym
*sym
, Section
*section
,
1439 unsigned long value
, unsigned long size
)
1441 put_extern_sym2(sym
, section
, value
, size
, 1);
1444 /* add a new relocation entry to symbol 'sym' in section 's' */
1445 static void greloc(Section
*s
, Sym
*sym
, unsigned long offset
, int type
)
1448 put_extern_sym(sym
, NULL
, 0, 0);
1449 /* now we can add ELF relocation info */
1450 put_elf_reloc(symtab_section
, s
, offset
, type
, sym
->c
);
1453 static inline int isid(int c
)
1455 return (c
>= 'a' && c
<= 'z') ||
1456 (c
>= 'A' && c
<= 'Z') ||
1460 static inline int isnum(int c
)
1462 return c
>= '0' && c
<= '9';
1465 static inline int isoct(int c
)
1467 return c
>= '0' && c
<= '7';
1470 static inline int toup(int c
)
1472 if (c
>= 'a' && c
<= 'z')
1473 return c
- 'a' + 'A';
1478 static void strcat_vprintf(char *buf
, int buf_size
, const char *fmt
, va_list ap
)
1482 vsnprintf(buf
+ len
, buf_size
- len
, fmt
, ap
);
1485 static void strcat_printf(char *buf
, int buf_size
, const char *fmt
, ...)
1489 strcat_vprintf(buf
, buf_size
, fmt
, ap
);
1493 void error1(TCCState
*s1
, int is_warning
, const char *fmt
, va_list ap
)
1500 for(f
= s1
->include_stack
; f
< s1
->include_stack_ptr
; f
++)
1501 strcat_printf(buf
, sizeof(buf
), "In file included from %s:%d:\n",
1502 (*f
)->filename
, (*f
)->line_num
);
1503 if (file
->line_num
> 0) {
1504 strcat_printf(buf
, sizeof(buf
),
1505 "%s:%d: ", file
->filename
, file
->line_num
);
1507 strcat_printf(buf
, sizeof(buf
),
1508 "%s: ", file
->filename
);
1511 strcat_printf(buf
, sizeof(buf
),
1515 strcat_printf(buf
, sizeof(buf
), "warning: ");
1516 strcat_vprintf(buf
, sizeof(buf
), fmt
, ap
);
1518 if (!s1
->error_func
) {
1519 /* default case: stderr */
1520 fprintf(stderr
, "%s\n", buf
);
1522 s1
->error_func(s1
->error_opaque
, buf
);
1524 if (!is_warning
|| s1
->warn_error
)
1529 void tcc_set_error_func(TCCState
*s
, void *error_opaque
,
1530 void (*error_func
)(void *opaque
, const char *msg
))
1532 s
->error_opaque
= error_opaque
;
1533 s
->error_func
= error_func
;
1537 /* error without aborting current compilation */
1538 void error_noabort(const char *fmt
, ...)
1540 TCCState
*s1
= tcc_state
;
1544 error1(s1
, 0, fmt
, ap
);
1548 void error(const char *fmt
, ...)
1550 TCCState
*s1
= tcc_state
;
1554 error1(s1
, 0, fmt
, ap
);
1556 /* better than nothing: in some cases, we accept to handle errors */
1557 if (s1
->error_set_jmp_enabled
) {
1558 longjmp(s1
->error_jmp_buf
, 1);
1560 /* XXX: eliminate this someday */
1565 void expect(const char *msg
)
1567 error("%s expected", msg
);
1570 void warning(const char *fmt
, ...)
1572 TCCState
*s1
= tcc_state
;
1579 error1(s1
, 1, fmt
, ap
);
1586 error("'%c' expected", c
);
1590 static void test_lvalue(void)
1592 if (!(vtop
->r
& VT_LVAL
))
1596 /* allocate a new token */
1597 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
1599 TokenSym
*ts
, **ptable
;
1602 if (tok_ident
>= SYM_FIRST_ANOM
)
1603 error("memory full");
1605 /* expand token table if needed */
1606 i
= tok_ident
- TOK_IDENT
;
1607 if ((i
% TOK_ALLOC_INCR
) == 0) {
1608 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
1610 error("memory full");
1611 table_ident
= ptable
;
1614 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
1615 table_ident
[i
] = ts
;
1616 ts
->tok
= tok_ident
++;
1617 ts
->sym_define
= NULL
;
1618 ts
->sym_label
= NULL
;
1619 ts
->sym_struct
= NULL
;
1620 ts
->sym_identifier
= NULL
;
1622 ts
->hash_next
= NULL
;
1623 memcpy(ts
->str
, str
, len
);
1624 ts
->str
[len
] = '\0';
1629 #define TOK_HASH_INIT 1
1630 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
1632 /* find a token and add it if not found */
1633 static TokenSym
*tok_alloc(const char *str
, int len
)
1635 TokenSym
*ts
, **pts
;
1641 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
1642 h
&= (TOK_HASH_SIZE
- 1);
1644 pts
= &hash_ident
[h
];
1649 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
1651 pts
= &(ts
->hash_next
);
1653 return tok_alloc_new(pts
, str
, len
);
1656 /* CString handling */
1658 static void cstr_realloc(CString
*cstr
, int new_size
)
1663 size
= cstr
->size_allocated
;
1665 size
= 8; /* no need to allocate a too small first string */
1666 while (size
< new_size
)
1668 data
= tcc_realloc(cstr
->data_allocated
, size
);
1670 error("memory full");
1671 cstr
->data_allocated
= data
;
1672 cstr
->size_allocated
= size
;
1677 static inline void cstr_ccat(CString
*cstr
, int ch
)
1680 size
= cstr
->size
+ 1;
1681 if (size
> cstr
->size_allocated
)
1682 cstr_realloc(cstr
, size
);
1683 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
1687 static void cstr_cat(CString
*cstr
, const char *str
)
1699 /* add a wide char */
1700 static void cstr_wccat(CString
*cstr
, int ch
)
1703 size
= cstr
->size
+ sizeof(nwchar_t
);
1704 if (size
> cstr
->size_allocated
)
1705 cstr_realloc(cstr
, size
);
1706 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
1710 static void cstr_new(CString
*cstr
)
1712 memset(cstr
, 0, sizeof(CString
));
1715 /* free string and reset it to NULL */
1716 static void cstr_free(CString
*cstr
)
1718 tcc_free(cstr
->data_allocated
);
1722 #define cstr_reset(cstr) cstr_free(cstr)
1724 /* XXX: unicode ? */
1725 static void add_char(CString
*cstr
, int c
)
1727 if (c
== '\'' || c
== '\"' || c
== '\\') {
1728 /* XXX: could be more precise if char or string */
1729 cstr_ccat(cstr
, '\\');
1731 if (c
>= 32 && c
<= 126) {
1734 cstr_ccat(cstr
, '\\');
1736 cstr_ccat(cstr
, 'n');
1738 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
1739 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
1740 cstr_ccat(cstr
, '0' + (c
& 7));
1745 /* XXX: buffer overflow */
1746 /* XXX: float tokens */
1747 char *get_tok_str(int v
, CValue
*cv
)
1749 static char buf
[STRING_MAX_SIZE
+ 1];
1750 static CString cstr_buf
;
1756 /* NOTE: to go faster, we give a fixed buffer for small strings */
1757 cstr_reset(&cstr_buf
);
1758 cstr_buf
.data
= buf
;
1759 cstr_buf
.size_allocated
= sizeof(buf
);
1765 /* XXX: not quite exact, but only useful for testing */
1766 sprintf(p
, "%u", cv
->ui
);
1770 /* XXX: not quite exact, but only useful for testing */
1771 sprintf(p
, "%Lu", cv
->ull
);
1775 cstr_ccat(&cstr_buf
, '\'');
1776 add_char(&cstr_buf
, cv
->i
);
1777 cstr_ccat(&cstr_buf
, '\'');
1778 cstr_ccat(&cstr_buf
, '\0');
1782 len
= cstr
->size
- 1;
1784 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1785 cstr_ccat(&cstr_buf
, '\0');
1790 cstr_ccat(&cstr_buf
, '\"');
1792 len
= cstr
->size
- 1;
1794 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1796 len
= (cstr
->size
/ sizeof(nwchar_t
)) - 1;
1798 add_char(&cstr_buf
, ((nwchar_t
*)cstr
->data
)[i
]);
1800 cstr_ccat(&cstr_buf
, '\"');
1801 cstr_ccat(&cstr_buf
, '\0');
1810 return strcpy(p
, "...");
1812 return strcpy(p
, "<<=");
1814 return strcpy(p
, ">>=");
1816 if (v
< TOK_IDENT
) {
1817 /* search in two bytes table */
1831 } else if (v
< tok_ident
) {
1832 return table_ident
[v
- TOK_IDENT
]->str
;
1833 } else if (v
>= SYM_FIRST_ANOM
) {
1834 /* special name for anonymous symbol */
1835 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
1837 /* should never happen */
1842 return cstr_buf
.data
;
1845 /* push, without hashing */
1846 static Sym
*sym_push2(Sym
**ps
, int v
, int t
, int c
)
1860 /* find a symbol and return its associated structure. 's' is the top
1861 of the symbol stack */
1862 static Sym
*sym_find2(Sym
*s
, int v
)
1872 /* structure lookup */
1873 static inline Sym
*struct_find(int v
)
1876 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1878 return table_ident
[v
]->sym_struct
;
1881 /* find an identifier */
1882 static inline Sym
*sym_find(int v
)
1885 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1887 return table_ident
[v
]->sym_identifier
;
1890 /* push a given symbol on the symbol stack */
1891 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
)
1900 s
= sym_push2(ps
, v
, type
->t
, c
);
1901 s
->type
.ref
= type
->ref
;
1903 /* don't record fields or anonymous symbols */
1905 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1906 /* record symbol in token array */
1907 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1909 ps
= &ts
->sym_struct
;
1911 ps
= &ts
->sym_identifier
;
1918 /* push a global identifier */
1919 static Sym
*global_identifier_push(int v
, int t
, int c
)
1922 s
= sym_push2(&global_stack
, v
, t
, c
);
1923 /* don't record anonymous symbol */
1924 if (v
< SYM_FIRST_ANOM
) {
1925 ps
= &table_ident
[v
- TOK_IDENT
]->sym_identifier
;
1926 /* modify the top most local identifier, so that
1927 sym_identifier will point to 's' when popped */
1929 ps
= &(*ps
)->prev_tok
;
1936 /* pop symbols until top reaches 'b' */
1937 static void sym_pop(Sym
**ptop
, Sym
*b
)
1947 /* remove symbol in token array */
1949 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1950 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1952 ps
= &ts
->sym_struct
;
1954 ps
= &ts
->sym_identifier
;
1965 BufferedFile
*tcc_open(TCCState
*s1
, const char *filename
)
1970 if (strcmp(filename
, "-") == 0)
1971 fd
= 0, filename
= "stdin";
1973 fd
= open(filename
, O_RDONLY
| O_BINARY
);
1974 if ((verbose
== 2 && fd
>= 0) || verbose
== 3)
1975 printf("%s %*s%s\n", fd
< 0 ? "nf":"->",
1976 (s1
->include_stack_ptr
- s1
->include_stack
), "", filename
);
1979 bf
= tcc_malloc(sizeof(BufferedFile
));
1981 bf
->buf_ptr
= bf
->buffer
;
1982 bf
->buf_end
= bf
->buffer
;
1983 bf
->buffer
[0] = CH_EOB
; /* put eob symbol */
1984 pstrcpy(bf
->filename
, sizeof(bf
->filename
), filename
);
1986 normalize_slashes(bf
->filename
);
1989 bf
->ifndef_macro
= 0;
1990 bf
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
1991 // printf("opening '%s'\n", filename);
1995 void tcc_close(BufferedFile
*bf
)
1997 total_lines
+= bf
->line_num
;
2002 /* fill input buffer and peek next char */
2003 static int tcc_peekc_slow(BufferedFile
*bf
)
2006 /* only tries to read if really end of buffer */
2007 if (bf
->buf_ptr
>= bf
->buf_end
) {
2009 #if defined(PARSE_DEBUG)
2014 len
= read(bf
->fd
, bf
->buffer
, len
);
2021 bf
->buf_ptr
= bf
->buffer
;
2022 bf
->buf_end
= bf
->buffer
+ len
;
2023 *bf
->buf_end
= CH_EOB
;
2025 if (bf
->buf_ptr
< bf
->buf_end
) {
2026 return bf
->buf_ptr
[0];
2028 bf
->buf_ptr
= bf
->buf_end
;
2033 /* return the current character, handling end of block if necessary
2035 static int handle_eob(void)
2037 return tcc_peekc_slow(file
);
2040 /* read next char from current input file and handle end of input buffer */
2041 static inline void inp(void)
2043 ch
= *(++(file
->buf_ptr
));
2044 /* end of buffer/file handling */
2049 /* handle '\[\r]\n' */
2050 static int handle_stray_noerror(void)
2052 while (ch
== '\\') {
2057 } else if (ch
== '\r') {
2071 static void handle_stray(void)
2073 if (handle_stray_noerror())
2074 error("stray '\\' in program");
2077 /* skip the stray and handle the \\n case. Output an error if
2078 incorrect char after the stray */
2079 static int handle_stray1(uint8_t *p
)
2083 if (p
>= file
->buf_end
) {
2100 /* handle just the EOB case, but not stray */
2101 #define PEEKC_EOB(c, p)\
2112 /* handle the complicated stray case */
2113 #define PEEKC(c, p)\
2118 c = handle_stray1(p);\
2123 /* input with '\[\r]\n' handling. Note that this function cannot
2124 handle other characters after '\', so you cannot call it inside
2125 strings or comments */
2126 static void minp(void)
2134 /* single line C++ comments */
2135 static uint8_t *parse_line_comment(uint8_t *p
)
2143 if (c
== '\n' || c
== CH_EOF
) {
2145 } else if (c
== '\\') {
2154 } else if (c
== '\r') {
2172 static uint8_t *parse_comment(uint8_t *p
)
2178 /* fast skip loop */
2181 if (c
== '\n' || c
== '*' || c
== '\\')
2185 if (c
== '\n' || c
== '*' || c
== '\\')
2189 /* now we can handle all the cases */
2193 } else if (c
== '*') {
2199 } else if (c
== '/') {
2200 goto end_of_comment
;
2201 } else if (c
== '\\') {
2206 /* skip '\[\r]\n', otherwise just skip the stray */
2212 } else if (c
== '\r') {
2229 /* stray, eob or eof */
2234 error("unexpected end of file in comment");
2235 } else if (c
== '\\') {
2247 /* space exlcuding newline */
2248 static inline int is_space(int ch
)
2250 return ch
== ' ' || ch
== '\t' || ch
== '\v' || ch
== '\f' || ch
== '\r';
2253 static inline void skip_spaces(void)
2255 while (is_space(ch
))
2259 /* parse a string without interpreting escapes */
2260 static uint8_t *parse_pp_string(uint8_t *p
,
2261 int sep
, CString
*str
)
2269 } else if (c
== '\\') {
2274 unterminated_string
:
2275 /* XXX: indicate line number of start of string */
2276 error("missing terminating %c character", sep
);
2277 } else if (c
== '\\') {
2278 /* escape : just skip \[\r]\n */
2283 } else if (c
== '\r') {
2286 expect("'\n' after '\r'");
2289 } else if (c
== CH_EOF
) {
2290 goto unterminated_string
;
2293 cstr_ccat(str
, '\\');
2299 } else if (c
== '\n') {
2302 } else if (c
== '\r') {
2306 cstr_ccat(str
, '\r');
2322 /* skip block of text until #else, #elif or #endif. skip also pairs of
2324 void preprocess_skip(void)
2326 int a
, start_of_line
, c
, in_warn_or_error
;
2333 in_warn_or_error
= 0;
2354 } else if (c
== '\\') {
2355 ch
= file
->buf_ptr
[0];
2356 handle_stray_noerror();
2363 if (in_warn_or_error
)
2365 p
= parse_pp_string(p
, c
, NULL
);
2369 if (in_warn_or_error
)
2376 p
= parse_comment(p
);
2377 } else if (ch
== '/') {
2378 p
= parse_line_comment(p
);
2383 if (start_of_line
) {
2388 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
2390 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
2392 else if (tok
== TOK_ENDIF
)
2394 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
2395 in_warn_or_error
= 1;
2409 /* ParseState handling */
2411 /* XXX: currently, no include file info is stored. Thus, we cannot display
2412 accurate messages if the function or data definition spans multiple
2415 /* save current parse state in 's' */
2416 void save_parse_state(ParseState
*s
)
2418 s
->line_num
= file
->line_num
;
2419 s
->macro_ptr
= macro_ptr
;
2424 /* restore parse state from 's' */
2425 void restore_parse_state(ParseState
*s
)
2427 file
->line_num
= s
->line_num
;
2428 macro_ptr
= s
->macro_ptr
;
2433 /* return the number of additional 'ints' necessary to store the
2435 static inline int tok_ext_size(int t
)
2449 error("unsupported token");
2456 return LDOUBLE_SIZE
/ 4;
2462 /* token string handling */
2464 static inline void tok_str_new(TokenString
*s
)
2468 s
->allocated_len
= 0;
2469 s
->last_line_num
= -1;
2472 static void tok_str_free(int *str
)
2477 static int *tok_str_realloc(TokenString
*s
)
2481 if (s
->allocated_len
== 0) {
2484 len
= s
->allocated_len
* 2;
2486 str
= tcc_realloc(s
->str
, len
* sizeof(int));
2488 error("memory full");
2489 s
->allocated_len
= len
;
2494 static void tok_str_add(TokenString
*s
, int t
)
2500 if (len
>= s
->allocated_len
)
2501 str
= tok_str_realloc(s
);
2506 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
2513 /* allocate space for worst case */
2514 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
2515 str
= tok_str_realloc(s
);
2524 str
[len
++] = cv
->tab
[0];
2533 nb_words
= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
2534 while ((len
+ nb_words
) > s
->allocated_len
)
2535 str
= tok_str_realloc(s
);
2536 cstr
= (CString
*)(str
+ len
);
2538 cstr
->size
= cv
->cstr
->size
;
2539 cstr
->data_allocated
= NULL
;
2540 cstr
->size_allocated
= cstr
->size
;
2541 memcpy((char *)cstr
+ sizeof(CString
),
2542 cv
->cstr
->data
, cstr
->size
);
2549 #if LDOUBLE_SIZE == 8
2552 str
[len
++] = cv
->tab
[0];
2553 str
[len
++] = cv
->tab
[1];
2555 #if LDOUBLE_SIZE == 12
2557 str
[len
++] = cv
->tab
[0];
2558 str
[len
++] = cv
->tab
[1];
2559 str
[len
++] = cv
->tab
[2];
2560 #elif LDOUBLE_SIZE != 8
2561 #error add long double size support
2570 /* add the current parse token in token string 's' */
2571 static void tok_str_add_tok(TokenString
*s
)
2575 /* save line number info */
2576 if (file
->line_num
!= s
->last_line_num
) {
2577 s
->last_line_num
= file
->line_num
;
2578 cval
.i
= s
->last_line_num
;
2579 tok_str_add2(s
, TOK_LINENUM
, &cval
);
2581 tok_str_add2(s
, tok
, &tokc
);
2584 #if LDOUBLE_SIZE == 12
2585 #define LDOUBLE_GET(p, cv) \
2589 #elif LDOUBLE_SIZE == 8
2590 #define LDOUBLE_GET(p, cv) \
2594 #error add long double size support
2598 /* get a token from an integer array and increment pointer
2599 accordingly. we code it as a macro to avoid pointer aliasing. */
2600 #define TOK_GET(t, p, cv) \
2615 cv.cstr = (CString *)p; \
2616 cv.cstr->data = (char *)p + sizeof(CString);\
2617 p += (sizeof(CString) + cv.cstr->size + 3) >> 2;\
2626 case TOK_CLDOUBLE: \
2627 LDOUBLE_GET(p, cv); \
2628 p += LDOUBLE_SIZE / 4; \
2635 /* defines handling */
2636 static inline void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
2640 s
= sym_push2(&define_stack
, v
, macro_type
, (int)str
);
2641 s
->next
= first_arg
;
2642 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
2645 /* undefined a define symbol. Its name is just set to zero */
2646 static void define_undef(Sym
*s
)
2650 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2651 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2655 static inline Sym
*define_find(int v
)
2658 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2660 return table_ident
[v
]->sym_define
;
2663 /* free define stack until top reaches 'b' */
2664 static void free_defines(Sym
*b
)
2672 /* do not free args or predefined defines */
2674 tok_str_free((int *)top
->c
);
2676 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2677 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2685 static Sym
*label_find(int v
)
2688 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2690 return table_ident
[v
]->sym_label
;
2693 static Sym
*label_push(Sym
**ptop
, int v
, int flags
)
2696 s
= sym_push2(ptop
, v
, 0, 0);
2698 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
2699 if (ptop
== &global_label_stack
) {
2700 /* modify the top most local identifier, so that
2701 sym_identifier will point to 's' when popped */
2703 ps
= &(*ps
)->prev_tok
;
2710 /* pop labels until element last is reached. Look if any labels are
2711 undefined. Define symbols if '&&label' was used. */
2712 static void label_pop(Sym
**ptop
, Sym
*slast
)
2715 for(s
= *ptop
; s
!= slast
; s
= s1
) {
2717 if (s
->r
== LABEL_DECLARED
) {
2718 warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
2719 } else if (s
->r
== LABEL_FORWARD
) {
2720 error("label '%s' used but not defined",
2721 get_tok_str(s
->v
, NULL
));
2724 /* define corresponding symbol. A size of
2726 put_extern_sym(s
, cur_text_section
, (long)s
->next
, 1);
2730 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
2736 /* eval an expression for #if/#elif */
2737 static int expr_preprocess(void)
2743 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2744 next(); /* do macro subst */
2745 if (tok
== TOK_DEFINED
) {
2750 c
= define_find(tok
) != 0;
2755 } else if (tok
>= TOK_IDENT
) {
2756 /* if undefined macro */
2760 tok_str_add_tok(&str
);
2762 tok_str_add(&str
, -1); /* simulate end of file */
2763 tok_str_add(&str
, 0);
2764 /* now evaluate C constant expression */
2765 macro_ptr
= str
.str
;
2769 tok_str_free(str
.str
);
2773 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
2774 static void tok_print(int *str
)
2780 TOK_GET(t
, str
, cval
);
2783 printf(" %s", get_tok_str(t
, &cval
));
2789 /* parse after #define */
2790 static void parse_define(void)
2792 Sym
*s
, *first
, **ps
;
2793 int v
, t
, varg
, is_vaargs
, c
;
2798 error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
2799 /* XXX: should check if same macro (ANSI) */
2802 /* '(' must be just after macro definition for MACRO_FUNC */
2803 c
= file
->buf_ptr
[0];
2805 c
= handle_stray1(file
->buf_ptr
);
2810 while (tok
!= ')') {
2814 if (varg
== TOK_DOTS
) {
2815 varg
= TOK___VA_ARGS__
;
2817 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
2821 if (varg
< TOK_IDENT
)
2822 error("badly punctuated parameter list");
2823 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
2834 /* EOF testing necessary for '-D' handling */
2835 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2836 tok_str_add2(&str
, tok
, &tokc
);
2839 tok_str_add(&str
, 0);
2841 printf("define %s %d: ", get_tok_str(v
, NULL
), t
);
2844 define_push(v
, t
, str
.str
, first
);
2847 static inline int hash_cached_include(int type
, const char *filename
)
2849 const unsigned char *s
;
2853 h
= TOK_HASH_FUNC(h
, type
);
2856 h
= TOK_HASH_FUNC(h
, *s
);
2859 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
2863 /* XXX: use a token or a hash table to accelerate matching ? */
2864 static CachedInclude
*search_cached_include(TCCState
*s1
,
2865 int type
, const char *filename
)
2869 h
= hash_cached_include(type
, filename
);
2870 i
= s1
->cached_includes_hash
[h
];
2874 e
= s1
->cached_includes
[i
- 1];
2875 if (e
->type
== type
&& !strcmp(e
->filename
, filename
))
2882 static inline void add_cached_include(TCCState
*s1
, int type
,
2883 const char *filename
, int ifndef_macro
)
2888 if (search_cached_include(s1
, type
, filename
))
2891 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
2893 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
2897 strcpy(e
->filename
, filename
);
2898 e
->ifndef_macro
= ifndef_macro
;
2899 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
2900 /* add in hash table */
2901 h
= hash_cached_include(type
, filename
);
2902 e
->hash_next
= s1
->cached_includes_hash
[h
];
2903 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
2906 static void pragma_parse(TCCState
*s1
)
2911 if (tok
== TOK_pack
) {
2914 #pragma pack(1) // set
2915 #pragma pack() // reset to default
2916 #pragma pack(push,1) // push & set
2917 #pragma pack(pop) // restore previous
2921 if (tok
== TOK_ASM_pop
) {
2923 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
2925 error("out of pack stack");
2927 s1
->pack_stack_ptr
--;
2931 if (tok
== TOK_ASM_push
) {
2933 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
2935 s1
->pack_stack_ptr
++;
2938 if (tok
!= TOK_CINT
) {
2940 error("invalid pack pragma");
2943 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
2947 *s1
->pack_stack_ptr
= val
;
2953 /* is_bof is true if first non space token at beginning of file */
2954 static void preprocess(int is_bof
)
2956 TCCState
*s1
= tcc_state
;
2957 int size
, i
, c
, n
, saved_parse_flags
;
2964 saved_parse_flags
= parse_flags
;
2965 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
|
2966 PARSE_FLAG_LINEFEED
;
2976 s
= define_find(tok
);
2977 /* undefine symbol by putting an invalid name */
2982 case TOK_INCLUDE_NEXT
:
2983 ch
= file
->buf_ptr
[0];
2984 /* XXX: incorrect if comments : use next_nomacro with a special mode */
2989 } else if (ch
== '\"') {
2994 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
2995 if ((q
- buf
) < sizeof(buf
) - 1)
2998 if (handle_stray_noerror() == 0)
3006 /* eat all spaces and comments after include */
3007 /* XXX: slightly incorrect */
3008 while (ch1
!= '\n' && ch1
!= CH_EOF
)
3012 /* computed #include : either we have only strings or
3013 we have anything enclosed in '<>' */
3016 if (tok
== TOK_STR
) {
3017 while (tok
!= TOK_LINEFEED
) {
3018 if (tok
!= TOK_STR
) {
3020 error("'#include' expects \"FILENAME\" or <FILENAME>");
3022 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
3028 while (tok
!= TOK_LINEFEED
) {
3029 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
3033 /* check syntax and remove '<>' */
3034 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
3035 goto include_syntax
;
3036 memmove(buf
, buf
+ 1, len
- 2);
3037 buf
[len
- 2] = '\0';
3042 e
= search_cached_include(s1
, c
, buf
);
3043 if (e
&& define_find(e
->ifndef_macro
)) {
3044 /* no need to parse the include because the 'ifndef macro'
3047 printf("%s: skipping %s\n", file
->filename
, buf
);
3050 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
3051 error("#include recursion too deep");
3052 /* push current file in stack */
3053 /* XXX: fix current line init */
3054 *s1
->include_stack_ptr
++ = file
;
3056 /* first search in current dir if "header.h" */
3057 size
= tcc_basename(file
->filename
) - file
->filename
;
3058 if (size
> sizeof(buf1
) - 1)
3059 size
= sizeof(buf1
) - 1;
3060 memcpy(buf1
, file
->filename
, size
);
3062 pstrcat(buf1
, sizeof(buf1
), buf
);
3063 f
= tcc_open(s1
, buf1
);
3065 if (tok
== TOK_INCLUDE_NEXT
)
3071 /* now search in all the include paths */
3072 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
3073 for(i
= 0; i
< n
; i
++) {
3075 if (i
< s1
->nb_include_paths
)
3076 path
= s1
->include_paths
[i
];
3078 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
3079 pstrcpy(buf1
, sizeof(buf1
), path
);
3080 pstrcat(buf1
, sizeof(buf1
), "/");
3081 pstrcat(buf1
, sizeof(buf1
), buf
);
3082 f
= tcc_open(s1
, buf1
);
3084 if (tok
== TOK_INCLUDE_NEXT
)
3090 --s1
->include_stack_ptr
;
3091 error("include file '%s' not found", buf
);
3095 printf("%s: including %s\n", file
->filename
, buf1
);
3098 pstrcpy(f
->inc_filename
, sizeof(f
->inc_filename
), buf
);
3100 /* add include file debug info */
3102 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
3104 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
3105 ch
= file
->buf_ptr
[0];
3113 c
= expr_preprocess();
3119 if (tok
< TOK_IDENT
)
3120 error("invalid argument for '#if%sdef'", c
? "n" : "");
3124 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
3126 file
->ifndef_macro
= tok
;
3129 c
= (define_find(tok
) != 0) ^ c
;
3131 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
3132 error("memory full");
3133 *s1
->ifdef_stack_ptr
++ = c
;
3136 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
3137 error("#else without matching #if");
3138 if (s1
->ifdef_stack_ptr
[-1] & 2)
3139 error("#else after #else");
3140 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
3143 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
3144 error("#elif without matching #if");
3145 c
= s1
->ifdef_stack_ptr
[-1];
3147 error("#elif after #else");
3148 /* last #if/#elif expression was true: we skip */
3151 c
= expr_preprocess();
3152 s1
->ifdef_stack_ptr
[-1] = c
;
3162 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
3163 error("#endif without matching #if");
3164 s1
->ifdef_stack_ptr
--;
3165 /* '#ifndef macro' was at the start of file. Now we check if
3166 an '#endif' is exactly at the end of file */
3167 if (file
->ifndef_macro
&&
3168 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
3169 file
->ifndef_macro_saved
= file
->ifndef_macro
;
3170 /* need to set to zero to avoid false matches if another
3171 #ifndef at middle of file */
3172 file
->ifndef_macro
= 0;
3173 while (tok
!= TOK_LINEFEED
)
3175 tok_flags
|= TOK_FLAG_ENDIF
;
3181 if (tok
!= TOK_CINT
)
3183 file
->line_num
= tokc
.i
- 1; /* the line number will be incremented after */
3185 if (tok
!= TOK_LINEFEED
) {
3188 pstrcpy(file
->filename
, sizeof(file
->filename
),
3189 (char *)tokc
.cstr
->data
);
3195 ch
= file
->buf_ptr
[0];
3198 while (ch
!= '\n' && ch
!= CH_EOF
) {
3199 if ((q
- buf
) < sizeof(buf
) - 1)
3202 if (handle_stray_noerror() == 0)
3209 error("#error %s", buf
);
3211 warning("#warning %s", buf
);
3217 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_CINT
) {
3218 /* '!' is ignored to allow C scripts. numbers are ignored
3219 to emulate cpp behaviour */
3221 if (!(saved_parse_flags
& PARSE_FLAG_ASM_COMMENTS
))
3222 warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
3226 /* ignore other preprocess commands or #! for C scripts */
3227 while (tok
!= TOK_LINEFEED
)
3230 parse_flags
= saved_parse_flags
;
3233 /* evaluate escape codes in a string. */
3234 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
3249 case '0': case '1': case '2': case '3':
3250 case '4': case '5': case '6': case '7':
3251 /* at most three octal digits */
3256 n
= n
* 8 + c
- '0';
3260 n
= n
* 8 + c
- '0';
3265 goto add_char_nonext
;
3273 if (c
>= 'a' && c
<= 'f')
3275 else if (c
>= 'A' && c
<= 'F')
3285 goto add_char_nonext
;
3309 goto invalid_escape
;
3319 if (c
>= '!' && c
<= '~')
3320 warning("unknown escape sequence: \'\\%c\'", c
);
3322 warning("unknown escape sequence: \'\\x%x\'", c
);
3329 cstr_ccat(outstr
, c
);
3331 cstr_wccat(outstr
, c
);
3333 /* add a trailing '\0' */
3335 cstr_ccat(outstr
, '\0');
3337 cstr_wccat(outstr
, '\0');
3340 /* we use 64 bit numbers */
3343 /* bn = (bn << shift) | or_val */
3344 void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
3348 for(i
=0;i
<BN_SIZE
;i
++) {
3350 bn
[i
] = (v
<< shift
) | or_val
;
3351 or_val
= v
>> (32 - shift
);
3355 void bn_zero(unsigned int *bn
)
3358 for(i
=0;i
<BN_SIZE
;i
++) {
3363 /* parse number in null terminated string 'p' and return it in the
3365 void parse_number(const char *p
)
3367 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
3369 unsigned int bn
[BN_SIZE
];
3380 goto float_frac_parse
;
3381 } else if (t
== '0') {
3382 if (ch
== 'x' || ch
== 'X') {
3386 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
3392 /* parse all digits. cannot check octal numbers at this stage
3393 because of floating point constants */
3395 if (ch
>= 'a' && ch
<= 'f')
3397 else if (ch
>= 'A' && ch
<= 'F')
3405 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
3407 error("number too long");
3413 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
3414 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
3416 /* NOTE: strtox should support that for hexa numbers, but
3417 non ISOC99 libcs do not support it, so we prefer to do
3419 /* hexadecimal or binary floats */
3420 /* XXX: handle overflows */
3432 } else if (t
>= 'a') {
3434 } else if (t
>= 'A') {
3439 bn_lshift(bn
, shift
, t
);
3446 if (t
>= 'a' && t
<= 'f') {
3448 } else if (t
>= 'A' && t
<= 'F') {
3450 } else if (t
>= '0' && t
<= '9') {
3456 error("invalid digit");
3457 bn_lshift(bn
, shift
, t
);
3462 if (ch
!= 'p' && ch
!= 'P')
3469 } else if (ch
== '-') {
3473 if (ch
< '0' || ch
> '9')
3474 expect("exponent digits");
3475 while (ch
>= '0' && ch
<= '9') {
3476 exp_val
= exp_val
* 10 + ch
- '0';
3479 exp_val
= exp_val
* s
;
3481 /* now we can generate the number */
3482 /* XXX: should patch directly float number */
3483 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
3484 d
= ldexp(d
, exp_val
- frac_bits
);
3489 /* float : should handle overflow */
3491 } else if (t
== 'L') {
3494 /* XXX: not large enough */
3495 tokc
.ld
= (long double)d
;
3501 /* decimal floats */
3503 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3508 while (ch
>= '0' && ch
<= '9') {
3509 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3515 if (ch
== 'e' || ch
== 'E') {
3516 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3520 if (ch
== '-' || ch
== '+') {
3521 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3526 if (ch
< '0' || ch
> '9')
3527 expect("exponent digits");
3528 while (ch
>= '0' && ch
<= '9') {
3529 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3541 tokc
.f
= strtof(token_buf
, NULL
);
3542 } else if (t
== 'L') {
3545 tokc
.ld
= strtold(token_buf
, NULL
);
3548 tokc
.d
= strtod(token_buf
, NULL
);
3552 unsigned long long n
, n1
;
3555 /* integer number */
3558 if (b
== 10 && *q
== '0') {
3565 /* no need for checks except for base 10 / 8 errors */
3568 } else if (t
>= 'a') {
3570 } else if (t
>= 'A') {
3575 error("invalid digit");
3579 /* detect overflow */
3580 /* XXX: this test is not reliable */
3582 error("integer constant overflow");
3585 /* XXX: not exactly ANSI compliant */
3586 if ((n
& 0xffffffff00000000LL
) != 0) {
3591 } else if (n
> 0x7fffffff) {
3602 error("three 'l's in integer constant");
3605 if (tok
== TOK_CINT
)
3607 else if (tok
== TOK_CUINT
)
3611 } else if (t
== 'U') {
3613 error("two 'u's in integer constant");
3615 if (tok
== TOK_CINT
)
3617 else if (tok
== TOK_CLLONG
)
3624 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
3632 #define PARSE2(c1, tok1, c2, tok2) \
3643 /* return next token without macro substitution */
3644 static inline void next_nomacro1(void)
3664 /* first look if it is in fact an end of buffer */
3665 if (p
>= file
->buf_end
) {
3669 if (p
>= file
->buf_end
)
3682 TCCState
*s1
= tcc_state
;
3683 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
3684 && !(tok_flags
& TOK_FLAG_EOF
)) {
3685 tok_flags
|= TOK_FLAG_EOF
;
3687 goto keep_tok_flags
;
3688 } else if (s1
->include_stack_ptr
== s1
->include_stack
||
3689 !(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3690 /* no include left : end of file. */
3693 tok_flags
&= ~TOK_FLAG_EOF
;
3694 /* pop include file */
3696 /* test if previous '#endif' was after a #ifdef at
3698 if (tok_flags
& TOK_FLAG_ENDIF
) {
3700 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
3702 add_cached_include(s1
, file
->inc_type
, file
->inc_filename
,
3703 file
->ifndef_macro_saved
);
3706 /* add end of include file debug info */
3708 put_stabd(N_EINCL
, 0, 0);
3710 /* pop include stack */
3712 s1
->include_stack_ptr
--;
3713 file
= *s1
->include_stack_ptr
;
3722 tok_flags
|= TOK_FLAG_BOL
;
3724 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
3727 goto keep_tok_flags
;
3732 if ((tok_flags
& TOK_FLAG_BOL
) &&
3733 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3735 preprocess(tok_flags
& TOK_FLAG_BOF
);
3741 tok
= TOK_TWOSHARPS
;
3743 if (parse_flags
& PARSE_FLAG_ASM_COMMENTS
) {
3744 p
= parse_line_comment(p
- 1);
3753 case 'a': case 'b': case 'c': case 'd':
3754 case 'e': case 'f': case 'g': case 'h':
3755 case 'i': case 'j': case 'k': case 'l':
3756 case 'm': case 'n': case 'o': case 'p':
3757 case 'q': case 'r': case 's': case 't':
3758 case 'u': case 'v': case 'w': case 'x':
3760 case 'A': case 'B': case 'C': case 'D':
3761 case 'E': case 'F': case 'G': case 'H':
3762 case 'I': case 'J': case 'K':
3763 case 'M': case 'N': case 'O': case 'P':
3764 case 'Q': case 'R': case 'S': case 'T':
3765 case 'U': case 'V': case 'W': case 'X':
3771 h
= TOK_HASH_FUNC(h
, c
);
3775 if (!isidnum_table
[c
-CH_EOF
])
3777 h
= TOK_HASH_FUNC(h
, c
);
3784 /* fast case : no stray found, so we have the full token
3785 and we have already hashed it */
3787 h
&= (TOK_HASH_SIZE
- 1);
3788 pts
= &hash_ident
[h
];
3793 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
3795 pts
= &(ts
->hash_next
);
3797 ts
= tok_alloc_new(pts
, p1
, len
);
3801 cstr_reset(&tokcstr
);
3804 cstr_ccat(&tokcstr
, *p1
);
3810 while (isidnum_table
[c
-CH_EOF
]) {
3811 cstr_ccat(&tokcstr
, c
);
3814 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
3820 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
3822 goto parse_ident_fast
;
3825 if (c
== '\'' || c
== '\"') {
3829 cstr_reset(&tokcstr
);
3830 cstr_ccat(&tokcstr
, 'L');
3831 goto parse_ident_slow
;
3835 case '0': case '1': case '2': case '3':
3836 case '4': case '5': case '6': case '7':
3839 cstr_reset(&tokcstr
);
3840 /* after the first digit, accept digits, alpha, '.' or sign if
3841 prefixed by 'eEpP' */
3845 cstr_ccat(&tokcstr
, c
);
3847 if (!(isnum(c
) || isid(c
) || c
== '.' ||
3848 ((c
== '+' || c
== '-') &&
3849 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
3852 /* We add a trailing '\0' to ease parsing */
3853 cstr_ccat(&tokcstr
, '\0');
3854 tokc
.cstr
= &tokcstr
;
3858 /* special dot handling because it can also start a number */
3861 cstr_reset(&tokcstr
);
3862 cstr_ccat(&tokcstr
, '.');
3864 } else if (c
== '.') {
3884 /* parse the string */
3886 p
= parse_pp_string(p
, sep
, &str
);
3887 cstr_ccat(&str
, '\0');
3889 /* eval the escape (should be done as TOK_PPNUM) */
3890 cstr_reset(&tokcstr
);
3891 parse_escape_string(&tokcstr
, str
.data
, is_long
);
3896 /* XXX: make it portable */
3900 char_size
= sizeof(nwchar_t
);
3901 if (tokcstr
.size
<= char_size
)
3902 error("empty character constant");
3903 if (tokcstr
.size
> 2 * char_size
)
3904 warning("multi-character character constant");
3906 tokc
.i
= *(int8_t *)tokcstr
.data
;
3909 tokc
.i
= *(nwchar_t
*)tokcstr
.data
;
3913 tokc
.cstr
= &tokcstr
;
3927 } else if (c
== '<') {
3945 } else if (c
== '>') {
3963 } else if (c
== '=') {
3976 } else if (c
== '=') {
3989 } else if (c
== '=') {
4002 } else if (c
== '=') {
4005 } else if (c
== '>') {
4013 PARSE2('!', '!', '=', TOK_NE
)
4014 PARSE2('=', '=', '=', TOK_EQ
)
4015 PARSE2('*', '*', '=', TOK_A_MUL
)
4016 PARSE2('%', '%', '=', TOK_A_MOD
)
4017 PARSE2('^', '^', '=', TOK_A_XOR
)
4019 /* comments or operator */
4023 p
= parse_comment(p
);
4025 } else if (c
== '/') {
4026 p
= parse_line_comment(p
);
4028 } else if (c
== '=') {
4048 case '$': /* only used in assembler */
4049 case '@': /* dito */
4054 error("unrecognized character \\x%02x", c
);
4060 #if defined(PARSE_DEBUG)
4061 printf("token = %s\n", get_tok_str(tok
, &tokc
));
4065 /* return next token without macro substitution. Can read input from
4067 static void next_nomacro(void)
4073 TOK_GET(tok
, macro_ptr
, tokc
);
4074 if (tok
== TOK_LINENUM
) {
4075 file
->line_num
= tokc
.i
;
4084 /* substitute args in macro_str and return allocated string */
4085 static int *macro_arg_subst(Sym
**nested_list
, int *macro_str
, Sym
*args
)
4087 int *st
, last_tok
, t
, notfirst
;
4096 TOK_GET(t
, macro_str
, cval
);
4101 TOK_GET(t
, macro_str
, cval
);
4104 s
= sym_find2(args
, t
);
4111 cstr_ccat(&cstr
, ' ');
4112 TOK_GET(t
, st
, cval
);
4113 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
4118 cstr_ccat(&cstr
, '\0');
4120 printf("stringize: %s\n", (char *)cstr
.data
);
4124 tok_str_add2(&str
, TOK_STR
, &cval
);
4127 tok_str_add2(&str
, t
, &cval
);
4129 } else if (t
>= TOK_IDENT
) {
4130 s
= sym_find2(args
, t
);
4133 /* if '##' is present before or after, no arg substitution */
4134 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
4135 /* special case for var arg macros : ## eats the
4136 ',' if empty VA_ARGS variable. */
4137 /* XXX: test of the ',' is not 100%
4138 reliable. should fix it to avoid security
4140 if (gnu_ext
&& s
->type
.t
&&
4141 last_tok
== TOK_TWOSHARPS
&&
4142 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
4144 /* suppress ',' '##' */
4147 /* suppress '##' and add variable */
4155 TOK_GET(t1
, st
, cval
);
4158 tok_str_add2(&str
, t1
, &cval
);
4162 /* NOTE: the stream cannot be read when macro
4163 substituing an argument */
4164 macro_subst(&str
, nested_list
, st
, NULL
);
4167 tok_str_add(&str
, t
);
4170 tok_str_add2(&str
, t
, &cval
);
4174 tok_str_add(&str
, 0);
4178 static char const ab_month_name
[12][4] =
4180 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
4181 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
4184 /* do macro substitution of current token with macro 's' and add
4185 result to (tok_str,tok_len). 'nested_list' is the list of all
4186 macros we got inside to avoid recursing. Return non zero if no
4187 substitution needs to be done */
4188 static int macro_subst_tok(TokenString
*tok_str
,
4189 Sym
**nested_list
, Sym
*s
, struct macro_level
**can_read_stream
)
4191 Sym
*args
, *sa
, *sa1
;
4192 int mstr_allocated
, parlevel
, *mstr
, t
, t1
;
4199 /* if symbol is a macro, prepare substitution */
4200 /* special macros */
4201 if (tok
== TOK___LINE__
) {
4202 snprintf(buf
, sizeof(buf
), "%d", file
->line_num
);
4206 } else if (tok
== TOK___FILE__
) {
4207 cstrval
= file
->filename
;
4209 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
4214 tm
= localtime(&ti
);
4215 if (tok
== TOK___DATE__
) {
4216 snprintf(buf
, sizeof(buf
), "%s %2d %d",
4217 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
4219 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
4220 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
4227 cstr_cat(&cstr
, cstrval
);
4228 cstr_ccat(&cstr
, '\0');
4230 tok_str_add2(tok_str
, t1
, &cval
);
4235 if (s
->type
.t
== MACRO_FUNC
) {
4236 /* NOTE: we do not use next_nomacro to avoid eating the
4237 next token. XXX: find better solution */
4241 if (t
== 0 && can_read_stream
) {
4242 /* end of macro stream: we must look at the token
4243 after in the file */
4244 struct macro_level
*ml
= *can_read_stream
;
4250 *can_read_stream
= ml
-> prev
;
4255 /* XXX: incorrect with comments */
4256 ch
= file
->buf_ptr
[0];
4257 while (is_space(ch
) || ch
== '\n')
4261 if (t
!= '(') /* no macro subst */
4264 /* argument macro */
4269 /* NOTE: empty args are allowed, except if no args */
4271 /* handle '()' case */
4272 if (!args
&& !sa
&& tok
== ')')
4275 error("macro '%s' used with too many args",
4276 get_tok_str(s
->v
, 0));
4279 /* NOTE: non zero sa->t indicates VA_ARGS */
4280 while ((parlevel
> 0 ||
4282 (tok
!= ',' || sa
->type
.t
))) &&
4286 else if (tok
== ')')
4288 if (tok
!= TOK_LINEFEED
)
4289 tok_str_add2(&str
, tok
, &tokc
);
4292 tok_str_add(&str
, 0);
4293 sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, (int)str
.str
);
4296 /* special case for gcc var args: add an empty
4297 var arg argument if it is omitted */
4298 if (sa
&& sa
->type
.t
&& gnu_ext
)
4308 error("macro '%s' used with too few args",
4309 get_tok_str(s
->v
, 0));
4312 /* now subst each arg */
4313 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
4318 tok_str_free((int *)sa
->c
);
4324 sym_push2(nested_list
, s
->v
, 0, 0);
4325 macro_subst(tok_str
, nested_list
, mstr
, can_read_stream
);
4326 /* pop nested defined symbol */
4328 *nested_list
= sa1
->prev
;
4336 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
4337 return the resulting string (which must be freed). */
4338 static inline int *macro_twosharps(const int *macro_str
)
4341 const int *macro_ptr1
, *start_macro_ptr
, *ptr
, *saved_macro_ptr
;
4343 const char *p1
, *p2
;
4345 TokenString macro_str1
;
4348 start_macro_ptr
= macro_str
;
4349 /* we search the first '##' */
4351 macro_ptr1
= macro_str
;
4352 TOK_GET(t
, macro_str
, cval
);
4353 /* nothing more to do if end of string */
4356 if (*macro_str
== TOK_TWOSHARPS
)
4360 /* we saw '##', so we need more processing to handle it */
4362 tok_str_new(¯o_str1
);
4366 /* add all tokens seen so far */
4367 for(ptr
= start_macro_ptr
; ptr
< macro_ptr1
;) {
4368 TOK_GET(t
, ptr
, cval
);
4369 tok_str_add2(¯o_str1
, t
, &cval
);
4371 saved_macro_ptr
= macro_ptr
;
4372 /* XXX: get rid of the use of macro_ptr here */
4373 macro_ptr
= (int *)macro_str
;
4375 while (*macro_ptr
== TOK_TWOSHARPS
) {
4377 macro_ptr1
= macro_ptr
;
4380 TOK_GET(t
, macro_ptr
, cval
);
4381 /* We concatenate the two tokens if we have an
4382 identifier or a preprocessing number */
4384 p1
= get_tok_str(tok
, &tokc
);
4385 cstr_cat(&cstr
, p1
);
4386 p2
= get_tok_str(t
, &cval
);
4387 cstr_cat(&cstr
, p2
);
4388 cstr_ccat(&cstr
, '\0');
4390 if ((tok
>= TOK_IDENT
|| tok
== TOK_PPNUM
) &&
4391 (t
>= TOK_IDENT
|| t
== TOK_PPNUM
)) {
4392 if (tok
== TOK_PPNUM
) {
4393 /* if number, then create a number token */
4394 /* NOTE: no need to allocate because
4395 tok_str_add2() does it */
4396 cstr_reset(&tokcstr
);
4399 tokc
.cstr
= &tokcstr
;
4401 /* if identifier, we must do a test to
4402 validate we have a correct identifier */
4403 if (t
== TOK_PPNUM
) {
4413 if (!isnum(c
) && !isid(c
))
4417 ts
= tok_alloc(cstr
.data
, strlen(cstr
.data
));
4418 tok
= ts
->tok
; /* modify current token */
4421 const char *str
= cstr
.data
;
4422 const unsigned char *q
;
4424 /* we look for a valid token */
4425 /* XXX: do more extensive checks */
4426 if (!strcmp(str
, ">>=")) {
4428 } else if (!strcmp(str
, "<<=")) {
4430 } else if (strlen(str
) == 2) {
4431 /* search in two bytes table */
4436 if (q
[0] == str
[0] && q
[1] == str
[1])
4443 /* NOTE: because get_tok_str use a static buffer,
4446 p1
= get_tok_str(tok
, &tokc
);
4447 cstr_cat(&cstr
, p1
);
4448 cstr_ccat(&cstr
, '\0');
4449 p2
= get_tok_str(t
, &cval
);
4450 warning("pasting \"%s\" and \"%s\" does not give a valid preprocessing token", cstr
.data
, p2
);
4451 /* cannot merge tokens: just add them separately */
4452 tok_str_add2(¯o_str1
, tok
, &tokc
);
4453 /* XXX: free associated memory ? */
4460 tok_str_add2(¯o_str1
, tok
, &tokc
);
4465 macro_ptr
= (int *)saved_macro_ptr
;
4467 tok_str_add(¯o_str1
, 0);
4468 return macro_str1
.str
;
4472 /* do macro substitution of macro_str and add result to
4473 (tok_str,tok_len). 'nested_list' is the list of all macros we got
4474 inside to avoid recursing. */
4475 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
4476 const int *macro_str
, struct macro_level
** can_read_stream
)
4483 struct macro_level ml
;
4485 /* first scan for '##' operator handling */
4487 macro_str1
= macro_twosharps(ptr
);
4491 /* NOTE: ptr == NULL can only happen if tokens are read from
4492 file stream due to a macro function call */
4495 TOK_GET(t
, ptr
, cval
);
4500 /* if nested substitution, do nothing */
4501 if (sym_find2(*nested_list
, t
))
4504 if (can_read_stream
)
4505 ml
.prev
= *can_read_stream
, *can_read_stream
= &ml
;
4506 macro_ptr
= (int *)ptr
;
4508 ret
= macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
4509 ptr
= (int *)macro_ptr
;
4511 if (can_read_stream
&& *can_read_stream
== &ml
)
4512 *can_read_stream
= ml
.prev
;
4517 tok_str_add2(tok_str
, t
, &cval
);
4521 tok_str_free(macro_str1
);
4524 /* return next token with macro substitution */
4525 static void next(void)
4527 Sym
*nested_list
, *s
;
4529 struct macro_level
*ml
;
4534 /* if not reading from macro substituted string, then try
4535 to substitute macros */
4536 if (tok
>= TOK_IDENT
&&
4537 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
4538 s
= define_find(tok
);
4540 /* we have a macro: we try to substitute */
4544 if (macro_subst_tok(&str
, &nested_list
, s
, &ml
) == 0) {
4545 /* substitution done, NOTE: maybe empty */
4546 tok_str_add(&str
, 0);
4547 macro_ptr
= str
.str
;
4548 macro_ptr_allocated
= str
.str
;
4555 /* end of macro or end of unget buffer */
4556 if (unget_buffer_enabled
) {
4557 macro_ptr
= unget_saved_macro_ptr
;
4558 unget_buffer_enabled
= 0;
4560 /* end of macro string: free it */
4561 tok_str_free(macro_ptr_allocated
);
4568 /* convert preprocessor tokens into C tokens */
4569 if (tok
== TOK_PPNUM
&&
4570 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
4571 parse_number((char *)tokc
.cstr
->data
);
4575 /* push back current token and set current token to 'last_tok'. Only
4576 identifier case handled for labels. */
4577 static inline void unget_tok(int last_tok
)
4581 unget_saved_macro_ptr
= macro_ptr
;
4582 unget_buffer_enabled
= 1;
4583 q
= unget_saved_buffer
;
4586 n
= tok_ext_size(tok
) - 1;
4589 *q
= 0; /* end of token string */
4594 void swap(int *p
, int *q
)
4602 void vsetc(CType
*type
, int r
, CValue
*vc
)
4606 if (vtop
>= vstack
+ (VSTACK_SIZE
- 1))
4607 error("memory full");
4608 /* cannot let cpu flags if other instruction are generated. Also
4609 avoid leaving VT_JMP anywhere except on the top of the stack
4610 because it would complicate the code generator. */
4611 if (vtop
>= vstack
) {
4612 v
= vtop
->r
& VT_VALMASK
;
4613 if (v
== VT_CMP
|| (v
& ~1) == VT_JMP
)
4619 vtop
->r2
= VT_CONST
;
4623 /* push integer constant */
4628 vsetc(&int_type
, VT_CONST
, &cval
);
4631 /* Return a static symbol pointing to a section */
4632 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
4633 unsigned long offset
, unsigned long size
)
4639 sym
= global_identifier_push(v
, type
->t
| VT_STATIC
, 0);
4640 sym
->type
.ref
= type
->ref
;
4641 sym
->r
= VT_CONST
| VT_SYM
;
4642 put_extern_sym(sym
, sec
, offset
, size
);
4646 /* push a reference to a section offset by adding a dummy symbol */
4647 static void vpush_ref(CType
*type
, Section
*sec
, unsigned long offset
, unsigned long size
)
4652 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4653 vtop
->sym
= get_sym_ref(type
, sec
, offset
, size
);
4656 /* define a new external reference to a symbol 'v' of type 'u' */
4657 static Sym
*external_global_sym(int v
, CType
*type
, int r
)
4663 /* push forward reference */
4664 s
= global_identifier_push(v
, type
->t
| VT_EXTERN
, 0);
4665 s
->type
.ref
= type
->ref
;
4666 s
->r
= r
| VT_CONST
| VT_SYM
;
4671 /* define a new external reference to a symbol 'v' of type 'u' */
4672 static Sym
*external_sym(int v
, CType
*type
, int r
)
4678 /* push forward reference */
4679 s
= sym_push(v
, type
, r
| VT_CONST
| VT_SYM
, 0);
4680 s
->type
.t
|= VT_EXTERN
;
4682 if (!is_compatible_types(&s
->type
, type
))
4683 error("incompatible types for redefinition of '%s'",
4684 get_tok_str(v
, NULL
));
4689 /* push a reference to global symbol v */
4690 static void vpush_global_sym(CType
*type
, int v
)
4695 sym
= external_global_sym(v
, type
, 0);
4697 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4701 void vset(CType
*type
, int r
, int v
)
4706 vsetc(type
, r
, &cval
);
4709 void vseti(int r
, int v
)
4725 void vpushv(SValue
*v
)
4727 if (vtop
>= vstack
+ (VSTACK_SIZE
- 1))
4728 error("memory full");
4738 /* save r to the memory stack, and mark it as being free */
4739 void save_reg(int r
)
4741 int l
, saved
, size
, align
;
4745 /* modify all stack values */
4748 for(p
=vstack
;p
<=vtop
;p
++) {
4749 if ((p
->r
& VT_VALMASK
) == r
||
4750 ((p
->type
.t
& VT_BTYPE
) == VT_LLONG
&& (p
->r2
& VT_VALMASK
) == r
)) {
4751 /* must save value on stack if not already done */
4753 /* NOTE: must reload 'r' because r might be equal to r2 */
4754 r
= p
->r
& VT_VALMASK
;
4755 /* store register in the stack */
4757 if ((p
->r
& VT_LVAL
) ||
4758 (!is_float(type
->t
) && (type
->t
& VT_BTYPE
) != VT_LLONG
))
4760 size
= type_size(type
, &align
);
4761 loc
= (loc
- size
) & -align
;
4762 sv
.type
.t
= type
->t
;
4763 sv
.r
= VT_LOCAL
| VT_LVAL
;
4766 #ifdef TCC_TARGET_I386
4767 /* x86 specific: need to pop fp register ST0 if saved */
4768 if (r
== TREG_ST0
) {
4769 o(0xd9dd); /* fstp %st(1) */
4772 /* special long long case */
4773 if ((type
->t
& VT_BTYPE
) == VT_LLONG
) {
4780 /* mark that stack entry as being saved on the stack */
4781 if (p
->r
& VT_LVAL
) {
4782 /* also clear the bounded flag because the
4783 relocation address of the function was stored in
4785 p
->r
= (p
->r
& ~(VT_VALMASK
| VT_BOUNDED
)) | VT_LLOCAL
;
4787 p
->r
= lvalue_type(p
->type
.t
) | VT_LOCAL
;
4795 /* find a register of class 'rc2' with at most one reference on stack.
4796 * If none, call get_reg(rc) */
4797 int get_reg_ex(int rc
, int rc2
)
4802 for(r
=0;r
<NB_REGS
;r
++) {
4803 if (reg_classes
[r
] & rc2
) {
4806 for(p
= vstack
; p
<= vtop
; p
++) {
4807 if ((p
->r
& VT_VALMASK
) == r
||
4808 (p
->r2
& VT_VALMASK
) == r
)
4818 /* find a free register of class 'rc'. If none, save one register */
4824 /* find a free register */
4825 for(r
=0;r
<NB_REGS
;r
++) {
4826 if (reg_classes
[r
] & rc
) {
4827 for(p
=vstack
;p
<=vtop
;p
++) {
4828 if ((p
->r
& VT_VALMASK
) == r
||
4829 (p
->r2
& VT_VALMASK
) == r
)
4837 /* no register left : free the first one on the stack (VERY
4838 IMPORTANT to start from the bottom to ensure that we don't
4839 spill registers used in gen_opi()) */
4840 for(p
=vstack
;p
<=vtop
;p
++) {
4841 r
= p
->r
& VT_VALMASK
;
4842 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
))
4844 /* also look at second register (if long long) */
4845 r
= p
->r2
& VT_VALMASK
;
4846 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
)) {
4852 /* Should never comes here */
4856 /* save registers up to (vtop - n) stack entry */
4857 void save_regs(int n
)
4862 for(p
= vstack
;p
<= p1
; p
++) {
4863 r
= p
->r
& VT_VALMASK
;
4870 /* move register 's' to 'r', and flush previous value of r to memory
4872 void move_reg(int r
, int s
)
4885 /* get address of vtop (vtop MUST BE an lvalue) */
4888 vtop
->r
&= ~VT_LVAL
;
4889 /* tricky: if saved lvalue, then we can go back to lvalue */
4890 if ((vtop
->r
& VT_VALMASK
) == VT_LLOCAL
)
4891 vtop
->r
= (vtop
->r
& ~(VT_VALMASK
| VT_LVAL_TYPE
)) | VT_LOCAL
| VT_LVAL
;
4894 #ifdef CONFIG_TCC_BCHECK
4895 /* generate lvalue bound code */
4901 vtop
->r
&= ~VT_MUSTBOUND
;
4902 /* if lvalue, then use checking code before dereferencing */
4903 if (vtop
->r
& VT_LVAL
) {
4904 /* if not VT_BOUNDED value, then make one */
4905 if (!(vtop
->r
& VT_BOUNDED
)) {
4906 lval_type
= vtop
->r
& (VT_LVAL_TYPE
| VT_LVAL
);
4907 /* must save type because we must set it to int to get pointer */
4909 vtop
->type
.t
= VT_INT
;
4912 gen_bounded_ptr_add();
4913 vtop
->r
|= lval_type
;
4916 /* then check for dereferencing */
4917 gen_bounded_ptr_deref();
4922 /* store vtop a register belonging to class 'rc'. lvalues are
4923 converted to values. Cannot be used if cannot be converted to
4924 register value (such as structures). */
4927 int r
, r2
, rc2
, bit_pos
, bit_size
, size
, align
, i
;
4928 unsigned long long ll
;
4930 /* NOTE: get_reg can modify vstack[] */
4931 if (vtop
->type
.t
& VT_BITFIELD
) {
4933 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
4934 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
4935 /* remove bit field info to avoid loops */
4936 vtop
->type
.t
&= ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
4937 /* cast to int to propagate signedness in following ops */
4939 if((vtop
->type
.t
& VT_UNSIGNED
) ||
4940 (vtop
->type
.t
& VT_BTYPE
) == VT_BOOL
)
4941 type
.t
|= VT_UNSIGNED
;
4943 /* generate shifts */
4944 vpushi(32 - (bit_pos
+ bit_size
));
4946 vpushi(32 - bit_size
);
4947 /* NOTE: transformed to SHR if unsigned */
4951 if (is_float(vtop
->type
.t
) &&
4952 (vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4955 unsigned long offset
;
4956 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
4960 /* XXX: unify with initializers handling ? */
4961 /* CPUs usually cannot use float constants, so we store them
4962 generically in data segment */
4963 size
= type_size(&vtop
->type
, &align
);
4964 offset
= (data_section
->data_offset
+ align
- 1) & -align
;
4965 data_section
->data_offset
= offset
;
4966 /* XXX: not portable yet */
4968 /* Zero pad x87 tenbyte long doubles */
4970 vtop
->c
.tab
[2] &= 0xffff;
4972 ptr
= section_ptr_add(data_section
, size
);
4974 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
4978 ptr
[i
] = vtop
->c
.tab
[size
-1-i
];
4982 ptr
[i
] = vtop
->c
.tab
[i
];
4983 sym
= get_sym_ref(&vtop
->type
, data_section
, offset
, size
<< 2);
4984 vtop
->r
|= VT_LVAL
| VT_SYM
;
4988 #ifdef CONFIG_TCC_BCHECK
4989 if (vtop
->r
& VT_MUSTBOUND
)
4993 r
= vtop
->r
& VT_VALMASK
;
4997 /* need to reload if:
4999 - lvalue (need to dereference pointer)
5000 - already a register, but not in the right class */
5001 if (r
>= VT_CONST
||
5002 (vtop
->r
& VT_LVAL
) ||
5003 !(reg_classes
[r
] & rc
) ||
5004 ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
&&
5005 !(reg_classes
[vtop
->r2
] & rc2
))) {
5007 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
) {
5008 /* two register type load : expand to two words
5010 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
5013 vtop
->c
.ui
= ll
; /* first word */
5015 vtop
->r
= r
; /* save register value */
5016 vpushi(ll
>> 32); /* second word */
5017 } else if (r
>= VT_CONST
|| /* XXX: test to VT_CONST incorrect ? */
5018 (vtop
->r
& VT_LVAL
)) {
5019 /* We do not want to modifier the long long
5020 pointer here, so the safest (and less
5021 efficient) is to save all the other registers
5022 in the stack. XXX: totally inefficient. */
5024 /* load from memory */
5027 vtop
[-1].r
= r
; /* save register value */
5028 /* increment pointer to get second word */
5029 vtop
->type
.t
= VT_INT
;
5035 /* move registers */
5038 vtop
[-1].r
= r
; /* save register value */
5039 vtop
->r
= vtop
[-1].r2
;
5041 /* allocate second register */
5045 /* write second register */
5047 } else if ((vtop
->r
& VT_LVAL
) && !is_float(vtop
->type
.t
)) {
5049 /* lvalue of scalar type : need to use lvalue type
5050 because of possible cast */
5053 /* compute memory access type */
5054 if (vtop
->r
& VT_LVAL_BYTE
)
5056 else if (vtop
->r
& VT_LVAL_SHORT
)
5058 if (vtop
->r
& VT_LVAL_UNSIGNED
)
5062 /* restore wanted type */
5065 /* one register type load */
5070 #ifdef TCC_TARGET_C67
5071 /* uses register pairs for doubles */
5072 if ((vtop
->type
.t
& VT_BTYPE
) == VT_DOUBLE
)
5079 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
5080 void gv2(int rc1
, int rc2
)
5084 /* generate more generic register first. But VT_JMP or VT_CMP
5085 values must be generated first in all cases to avoid possible
5087 v
= vtop
[0].r
& VT_VALMASK
;
5088 if (v
!= VT_CMP
&& (v
& ~1) != VT_JMP
&& rc1
<= rc2
) {
5093 /* test if reload is needed for first register */
5094 if ((vtop
[-1].r
& VT_VALMASK
) >= VT_CONST
) {
5104 /* test if reload is needed for first register */
5105 if ((vtop
[0].r
& VT_VALMASK
) >= VT_CONST
) {
5111 /* expand long long on stack in two int registers */
5116 u
= vtop
->type
.t
& VT_UNSIGNED
;
5119 vtop
[0].r
= vtop
[-1].r2
;
5120 vtop
[0].r2
= VT_CONST
;
5121 vtop
[-1].r2
= VT_CONST
;
5122 vtop
[0].type
.t
= VT_INT
| u
;
5123 vtop
[-1].type
.t
= VT_INT
| u
;
5126 #ifdef TCC_TARGET_ARM
5127 /* expand long long on stack */
5128 void lexpand_nr(void)
5132 u
= vtop
->type
.t
& VT_UNSIGNED
;
5134 vtop
->r2
= VT_CONST
;
5135 vtop
->type
.t
= VT_INT
| u
;
5136 v
=vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
);
5137 if (v
== VT_CONST
) {
5138 vtop
[-1].c
.ui
= vtop
->c
.ull
;
5139 vtop
->c
.ui
= vtop
->c
.ull
>> 32;
5141 } else if (v
== (VT_LVAL
|VT_CONST
) || v
== (VT_LVAL
|VT_LOCAL
)) {
5143 vtop
->r
= vtop
[-1].r
;
5144 } else if (v
> VT_CONST
) {
5148 vtop
->r
= vtop
[-1].r2
;
5149 vtop
[-1].r2
= VT_CONST
;
5150 vtop
[-1].type
.t
= VT_INT
| u
;
5154 /* build a long long from two ints */
5157 gv2(RC_INT
, RC_INT
);
5158 vtop
[-1].r2
= vtop
[0].r
;
5159 vtop
[-1].type
.t
= t
;
5163 /* rotate n first stack elements to the bottom
5164 I1 ... In -> I2 ... In I1 [top is right]
5172 for(i
=-n
+1;i
!=0;i
++)
5173 vtop
[i
] = vtop
[i
+1];
5177 /* rotate n first stack elements to the top
5178 I1 ... In -> In I1 ... I(n-1) [top is right]
5186 for(i
= 0;i
< n
- 1; i
++)
5187 vtop
[-i
] = vtop
[-i
- 1];
5191 #ifdef TCC_TARGET_ARM
5192 /* like vrott but in other direction
5193 In ... I1 -> I(n-1) ... I1 In [top is right]
5201 for(i
= n
- 1; i
> 0; i
--)
5202 vtop
[-i
] = vtop
[-i
+ 1];
5207 /* pop stack value */
5211 v
= vtop
->r
& VT_VALMASK
;
5212 #ifdef TCC_TARGET_I386
5213 /* for x86, we need to pop the FP stack */
5214 if (v
== TREG_ST0
&& !nocode_wanted
) {
5215 o(0xd9dd); /* fstp %st(1) */
5218 if (v
== VT_JMP
|| v
== VT_JMPI
) {
5219 /* need to put correct jump if && or || without test */
5225 /* convert stack entry to register and duplicate its value in another
5233 if ((t
& VT_BTYPE
) == VT_LLONG
) {
5240 /* stack: H L L1 H1 */
5248 /* duplicate value */
5259 load(r1
, &sv
); /* move r to r1 */
5261 /* duplicates value */
5266 /* generate CPU independent (unsigned) long long operations */
5267 void gen_opl(int op
)
5269 int t
, a
, b
, op1
, c
, i
;
5271 unsigned short reg_iret
= REG_IRET
;
5272 unsigned short reg_lret
= REG_LRET
;
5278 func
= TOK___divdi3
;
5281 func
= TOK___udivdi3
;
5284 func
= TOK___moddi3
;
5287 func
= TOK___umoddi3
;
5294 /* call generic long long function */
5295 vpush_global_sym(&func_old_type
, func
);
5300 vtop
->r2
= reg_lret
;
5313 /* stack: L1 H1 L2 H2 */
5318 vtop
[-2] = vtop
[-3];
5321 /* stack: H1 H2 L1 L2 */
5327 /* stack: H1 H2 L1 L2 ML MH */
5330 /* stack: ML MH H1 H2 L1 L2 */
5334 /* stack: ML MH H1 L2 H2 L1 */
5339 /* stack: ML MH M1 M2 */
5342 } else if (op
== '+' || op
== '-') {
5343 /* XXX: add non carry method too (for MIPS or alpha) */
5349 /* stack: H1 H2 (L1 op L2) */
5352 gen_op(op1
+ 1); /* TOK_xxxC2 */
5355 /* stack: H1 H2 (L1 op L2) */
5358 /* stack: (L1 op L2) H1 H2 */
5360 /* stack: (L1 op L2) (H1 op H2) */
5368 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) {
5369 t
= vtop
[-1].type
.t
;
5373 /* stack: L H shift */
5375 /* constant: simpler */
5376 /* NOTE: all comments are for SHL. the other cases are
5377 done by swaping words */
5388 if (op
!= TOK_SAR
) {
5421 /* XXX: should provide a faster fallback on x86 ? */
5424 func
= TOK___ashrdi3
;
5427 func
= TOK___lshrdi3
;
5430 func
= TOK___ashldi3
;
5436 /* compare operations */
5442 /* stack: L1 H1 L2 H2 */
5444 vtop
[-1] = vtop
[-2];
5446 /* stack: L1 L2 H1 H2 */
5449 /* when values are equal, we need to compare low words. since
5450 the jump is inverted, we invert the test too. */
5453 else if (op1
== TOK_GT
)
5455 else if (op1
== TOK_ULT
)
5457 else if (op1
== TOK_UGT
)
5462 if (op1
!= TOK_NE
) {
5466 /* generate non equal test */
5467 /* XXX: NOT PORTABLE yet */
5471 #if defined(TCC_TARGET_I386)
5472 b
= psym(0x850f, 0);
5473 #elif defined(TCC_TARGET_ARM)
5475 o(0x1A000000 | encbranch(ind
, 0, 1));
5476 #elif defined(TCC_TARGET_C67)
5477 error("not implemented");
5479 #error not supported
5483 /* compare low. Always unsigned */
5487 else if (op1
== TOK_LE
)
5489 else if (op1
== TOK_GT
)
5491 else if (op1
== TOK_GE
)
5501 /* handle integer constant optimizations and various machine
5503 void gen_opic(int op
)
5505 int c1
, c2
, t1
, t2
, n
;
5508 typedef unsigned long long U
;
5512 t1
= v1
->type
.t
& VT_BTYPE
;
5513 t2
= v2
->type
.t
& VT_BTYPE
;
5514 l1
= (t1
== VT_LLONG
) ? v1
->c
.ll
: v1
->c
.i
;
5515 l2
= (t2
== VT_LLONG
) ? v2
->c
.ll
: v2
->c
.i
;
5517 /* currently, we cannot do computations with forward symbols */
5518 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5519 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5522 case '+': l1
+= l2
; break;
5523 case '-': l1
-= l2
; break;
5524 case '&': l1
&= l2
; break;
5525 case '^': l1
^= l2
; break;
5526 case '|': l1
|= l2
; break;
5527 case '*': l1
*= l2
; break;
5534 /* if division by zero, generate explicit division */
5537 error("division by zero in constant");
5541 default: l1
/= l2
; break;
5542 case '%': l1
%= l2
; break;
5543 case TOK_UDIV
: l1
= (U
)l1
/ l2
; break;
5544 case TOK_UMOD
: l1
= (U
)l1
% l2
; break;
5547 case TOK_SHL
: l1
<<= l2
; break;
5548 case TOK_SHR
: l1
= (U
)l1
>> l2
; break;
5549 case TOK_SAR
: l1
>>= l2
; break;
5551 case TOK_ULT
: l1
= (U
)l1
< (U
)l2
; break;
5552 case TOK_UGE
: l1
= (U
)l1
>= (U
)l2
; break;
5553 case TOK_EQ
: l1
= l1
== l2
; break;
5554 case TOK_NE
: l1
= l1
!= l2
; break;
5555 case TOK_ULE
: l1
= (U
)l1
<= (U
)l2
; break;
5556 case TOK_UGT
: l1
= (U
)l1
> (U
)l2
; break;
5557 case TOK_LT
: l1
= l1
< l2
; break;
5558 case TOK_GE
: l1
= l1
>= l2
; break;
5559 case TOK_LE
: l1
= l1
<= l2
; break;
5560 case TOK_GT
: l1
= l1
> l2
; break;
5562 case TOK_LAND
: l1
= l1
&& l2
; break;
5563 case TOK_LOR
: l1
= l1
|| l2
; break;
5570 /* if commutative ops, put c2 as constant */
5571 if (c1
&& (op
== '+' || op
== '&' || op
== '^' ||
5572 op
== '|' || op
== '*')) {
5574 c2
= c1
; //c = c1, c1 = c2, c2 = c;
5575 l2
= l1
; //l = l1, l1 = l2, l2 = l;
5577 /* Filter out NOP operations like x*1, x-0, x&-1... */
5578 if (c2
&& (((op
== '*' || op
== '/' || op
== TOK_UDIV
||
5581 ((op
== '+' || op
== '-' || op
== '|' || op
== '^' ||
5582 op
== TOK_SHL
|| op
== TOK_SHR
|| op
== TOK_SAR
) &&
5588 } else if (c2
&& (op
== '*' || op
== TOK_PDIV
|| op
== TOK_UDIV
)) {
5589 /* try to use shifts instead of muls or divs */
5590 if (l2
> 0 && (l2
& (l2
- 1)) == 0) {
5599 else if (op
== TOK_PDIV
)
5605 } else if (c2
&& (op
== '+' || op
== '-') &&
5606 ((vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) ==
5607 (VT_CONST
| VT_SYM
) ||
5608 (vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
)) == VT_LOCAL
)) {
5609 /* symbol + constant case */
5616 if (!nocode_wanted
) {
5617 /* call low level op generator */
5618 if (t1
== VT_LLONG
|| t2
== VT_LLONG
)
5629 /* generate a floating point operation with constant propagation */
5630 void gen_opif(int op
)
5638 /* currently, we cannot do computations with forward symbols */
5639 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5640 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5642 if (v1
->type
.t
== VT_FLOAT
) {
5645 } else if (v1
->type
.t
== VT_DOUBLE
) {
5653 /* NOTE: we only do constant propagation if finite number (not
5654 NaN or infinity) (ANSI spec) */
5655 if (!ieee_finite(f1
) || !ieee_finite(f2
))
5659 case '+': f1
+= f2
; break;
5660 case '-': f1
-= f2
; break;
5661 case '*': f1
*= f2
; break;
5665 error("division by zero in constant");
5670 /* XXX: also handles tests ? */
5674 /* XXX: overflow test ? */
5675 if (v1
->type
.t
== VT_FLOAT
) {
5677 } else if (v1
->type
.t
== VT_DOUBLE
) {
5685 if (!nocode_wanted
) {
5693 static int pointed_size(CType
*type
)
5696 return type_size(pointed_type(type
), &align
);
5699 static inline int is_null_pointer(SValue
*p
)
5701 if ((p
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
5703 return ((p
->type
.t
& VT_BTYPE
) == VT_INT
&& p
->c
.i
== 0) ||
5704 ((p
->type
.t
& VT_BTYPE
) == VT_LLONG
&& p
->c
.ll
== 0);
5707 static inline int is_integer_btype(int bt
)
5709 return (bt
== VT_BYTE
|| bt
== VT_SHORT
||
5710 bt
== VT_INT
|| bt
== VT_LLONG
);
5713 /* check types for comparison or substraction of pointers */
5714 static void check_comparison_pointer_types(SValue
*p1
, SValue
*p2
, int op
)
5716 CType
*type1
, *type2
, tmp_type1
, tmp_type2
;
5719 /* null pointers are accepted for all comparisons as gcc */
5720 if (is_null_pointer(p1
) || is_null_pointer(p2
))
5724 bt1
= type1
->t
& VT_BTYPE
;
5725 bt2
= type2
->t
& VT_BTYPE
;
5726 /* accept comparison between pointer and integer with a warning */
5727 if ((is_integer_btype(bt1
) || is_integer_btype(bt2
)) && op
!= '-') {
5728 if (op
!= TOK_LOR
&& op
!= TOK_LAND
)
5729 warning("comparison between pointer and integer");
5733 /* both must be pointers or implicit function pointers */
5734 if (bt1
== VT_PTR
) {
5735 type1
= pointed_type(type1
);
5736 } else if (bt1
!= VT_FUNC
)
5737 goto invalid_operands
;
5739 if (bt2
== VT_PTR
) {
5740 type2
= pointed_type(type2
);
5741 } else if (bt2
!= VT_FUNC
) {
5743 error("invalid operands to binary %s", get_tok_str(op
, NULL
));
5745 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
5746 (type2
->t
& VT_BTYPE
) == VT_VOID
)
5750 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5751 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5752 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
5753 /* gcc-like error if '-' is used */
5755 goto invalid_operands
;
5757 warning("comparison of distinct pointer types lacks a cast");
5761 /* generic gen_op: handles types problems */
5764 int u
, t1
, t2
, bt1
, bt2
, t
;
5767 t1
= vtop
[-1].type
.t
;
5768 t2
= vtop
[0].type
.t
;
5769 bt1
= t1
& VT_BTYPE
;
5770 bt2
= t2
& VT_BTYPE
;
5772 if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
5773 /* at least one operand is a pointer */
5774 /* relationnal op: must be both pointers */
5775 if (op
>= TOK_ULT
&& op
<= TOK_LOR
) {
5776 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5777 /* pointers are handled are unsigned */
5778 t
= VT_INT
| VT_UNSIGNED
;
5781 /* if both pointers, then it must be the '-' op */
5782 if (bt1
== VT_PTR
&& bt2
== VT_PTR
) {
5784 error("cannot use pointers here");
5785 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5786 /* XXX: check that types are compatible */
5787 u
= pointed_size(&vtop
[-1].type
);
5789 /* set to integer type */
5790 vtop
->type
.t
= VT_INT
;
5794 /* exactly one pointer : must be '+' or '-'. */
5795 if (op
!= '-' && op
!= '+')
5796 error("cannot use pointers here");
5797 /* Put pointer as first operand */
5798 if (bt2
== VT_PTR
) {
5802 type1
= vtop
[-1].type
;
5803 /* XXX: cast to int ? (long long case) */
5804 vpushi(pointed_size(&vtop
[-1].type
));
5806 #ifdef CONFIG_TCC_BCHECK
5807 /* if evaluating constant expression, no code should be
5808 generated, so no bound check */
5809 if (do_bounds_check
&& !const_wanted
) {
5810 /* if bounded pointers, we generate a special code to
5817 gen_bounded_ptr_add();
5823 /* put again type if gen_opic() swaped operands */
5826 } else if (is_float(bt1
) || is_float(bt2
)) {
5827 /* compute bigger type and do implicit casts */
5828 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
5830 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
5835 /* floats can only be used for a few operations */
5836 if (op
!= '+' && op
!= '-' && op
!= '*' && op
!= '/' &&
5837 (op
< TOK_ULT
|| op
> TOK_GT
))
5838 error("invalid operands for binary operation");
5840 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
5841 /* cast to biggest op */
5843 /* convert to unsigned if it does not fit in a long long */
5844 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
5845 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
5849 /* integer operations */
5851 /* convert to unsigned if it does not fit in an integer */
5852 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
5853 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
5856 /* XXX: currently, some unsigned operations are explicit, so
5857 we modify them here */
5858 if (t
& VT_UNSIGNED
) {
5865 else if (op
== TOK_LT
)
5867 else if (op
== TOK_GT
)
5869 else if (op
== TOK_LE
)
5871 else if (op
== TOK_GE
)
5878 /* special case for shifts and long long: we keep the shift as
5880 if (op
== TOK_SHR
|| op
== TOK_SAR
|| op
== TOK_SHL
)
5887 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5888 /* relationnal op: the result is an int */
5889 vtop
->type
.t
= VT_INT
;
5896 #ifndef TCC_TARGET_ARM
5897 /* generic itof for unsigned long long case */
5898 void gen_cvt_itof1(int t
)
5900 if ((vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
)) ==
5901 (VT_LLONG
| VT_UNSIGNED
)) {
5904 vpush_global_sym(&func_old_type
, TOK___floatundisf
);
5905 #if LDOUBLE_SIZE != 8
5906 else if (t
== VT_LDOUBLE
)
5907 vpush_global_sym(&func_old_type
, TOK___floatundixf
);
5910 vpush_global_sym(&func_old_type
, TOK___floatundidf
);
5921 /* generic ftoi for unsigned long long case */
5922 void gen_cvt_ftoi1(int t
)
5926 if (t
== (VT_LLONG
| VT_UNSIGNED
)) {
5927 /* not handled natively */
5928 st
= vtop
->type
.t
& VT_BTYPE
;
5930 vpush_global_sym(&func_old_type
, TOK___fixunssfdi
);
5931 #if LDOUBLE_SIZE != 8
5932 else if (st
== VT_LDOUBLE
)
5933 vpush_global_sym(&func_old_type
, TOK___fixunsxfdi
);
5936 vpush_global_sym(&func_old_type
, TOK___fixunsdfdi
);
5941 vtop
->r2
= REG_LRET
;
5947 /* force char or short cast */
5948 void force_charshort_cast(int t
)
5952 /* XXX: add optimization if lvalue : just change type and offset */
5957 if (t
& VT_UNSIGNED
) {
5958 vpushi((1 << bits
) - 1);
5964 /* result must be signed or the SAR is converted to an SHL
5965 This was not the case when "t" was a signed short
5966 and the last value on the stack was an unsigned int */
5967 vtop
->type
.t
&= ~VT_UNSIGNED
;
5973 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
5974 static void gen_cast(CType
*type
)
5976 int sbt
, dbt
, sf
, df
, c
;
5978 /* special delayed cast for char/short */
5979 /* XXX: in some cases (multiple cascaded casts), it may still
5981 if (vtop
->r
& VT_MUSTCAST
) {
5982 vtop
->r
&= ~VT_MUSTCAST
;
5983 force_charshort_cast(vtop
->type
.t
);
5986 /* bitfields first get cast to ints */
5987 if (vtop
->type
.t
& VT_BITFIELD
) {
5991 dbt
= type
->t
& (VT_BTYPE
| VT_UNSIGNED
);
5992 sbt
= vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
);
5997 c
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5999 /* constant case: we can do it now */
6000 /* XXX: in ISOC, cannot do it if error in convert */
6001 if (sbt
== VT_FLOAT
)
6002 vtop
->c
.ld
= vtop
->c
.f
;
6003 else if (sbt
== VT_DOUBLE
)
6004 vtop
->c
.ld
= vtop
->c
.d
;
6007 if ((sbt
& VT_BTYPE
) == VT_LLONG
) {
6008 if (sbt
& VT_UNSIGNED
)
6009 vtop
->c
.ld
= vtop
->c
.ull
;
6011 vtop
->c
.ld
= vtop
->c
.ll
;
6013 if (sbt
& VT_UNSIGNED
)
6014 vtop
->c
.ld
= vtop
->c
.ui
;
6016 vtop
->c
.ld
= vtop
->c
.i
;
6019 if (dbt
== VT_FLOAT
)
6020 vtop
->c
.f
= (float)vtop
->c
.ld
;
6021 else if (dbt
== VT_DOUBLE
)
6022 vtop
->c
.d
= (double)vtop
->c
.ld
;
6023 } else if (sf
&& dbt
== (VT_LLONG
|VT_UNSIGNED
)) {
6024 vtop
->c
.ull
= (unsigned long long)vtop
->c
.ld
;
6025 } else if (sf
&& dbt
== VT_BOOL
) {
6026 vtop
->c
.i
= (vtop
->c
.ld
!= 0);
6029 vtop
->c
.ll
= (long long)vtop
->c
.ld
;
6030 else if (sbt
== (VT_LLONG
|VT_UNSIGNED
))
6031 vtop
->c
.ll
= vtop
->c
.ull
;
6032 else if (sbt
& VT_UNSIGNED
)
6033 vtop
->c
.ll
= vtop
->c
.ui
;
6034 else if (sbt
!= VT_LLONG
)
6035 vtop
->c
.ll
= vtop
->c
.i
;
6037 if (dbt
== (VT_LLONG
|VT_UNSIGNED
))
6038 vtop
->c
.ull
= vtop
->c
.ll
;
6039 else if (dbt
== VT_BOOL
)
6040 vtop
->c
.i
= (vtop
->c
.ll
!= 0);
6041 else if (dbt
!= VT_LLONG
) {
6043 if ((dbt
& VT_BTYPE
) == VT_BYTE
)
6045 else if ((dbt
& VT_BTYPE
) == VT_SHORT
)
6048 if(dbt
& VT_UNSIGNED
)
6049 vtop
->c
.ui
= ((unsigned int)vtop
->c
.ll
<< s
) >> s
;
6051 vtop
->c
.i
= ((int)vtop
->c
.ll
<< s
) >> s
;
6054 } else if (!nocode_wanted
) {
6055 /* non constant case: generate code */
6057 /* convert from fp to fp */
6060 /* convert int to fp */
6063 /* convert fp to int */
6064 if (dbt
== VT_BOOL
) {
6068 /* we handle char/short/etc... with generic code */
6069 if (dbt
!= (VT_INT
| VT_UNSIGNED
) &&
6070 dbt
!= (VT_LLONG
| VT_UNSIGNED
) &&
6074 if (dbt
== VT_INT
&& (type
->t
& (VT_BTYPE
| VT_UNSIGNED
)) != dbt
) {
6075 /* additional cast for char/short... */
6080 } else if ((dbt
& VT_BTYPE
) == VT_LLONG
) {
6081 if ((sbt
& VT_BTYPE
) != VT_LLONG
) {
6082 /* scalar to long long */
6083 /* machine independent conversion */
6085 /* generate high word */
6086 if (sbt
== (VT_INT
| VT_UNSIGNED
)) {
6094 /* patch second register */
6095 vtop
[-1].r2
= vtop
->r
;
6098 } else if (dbt
== VT_BOOL
) {
6099 /* scalar to bool */
6102 } else if ((dbt
& VT_BTYPE
) == VT_BYTE
||
6103 (dbt
& VT_BTYPE
) == VT_SHORT
) {
6104 if (sbt
== VT_PTR
) {
6105 vtop
->type
.t
= VT_INT
;
6106 warning("nonportable conversion from pointer to char/short");
6108 force_charshort_cast(dbt
);
6109 } else if ((dbt
& VT_BTYPE
) == VT_INT
) {
6111 if (sbt
== VT_LLONG
) {
6112 /* from long long: just take low order word */
6116 /* if lvalue and single word type, nothing to do because
6117 the lvalue already contains the real type size (see
6118 VT_LVAL_xxx constants) */
6121 expect("constant expression");
6122 } else if ((dbt
& VT_BTYPE
) == VT_PTR
&& !(vtop
->r
& VT_LVAL
)) {
6123 /* if we are casting between pointer types,
6124 we must update the VT_LVAL_xxx size */
6125 vtop
->r
= (vtop
->r
& ~VT_LVAL_TYPE
)
6126 | (lvalue_type(type
->ref
->type
.t
) & VT_LVAL_TYPE
);
6131 /* return type size. Put alignment at 'a' */
6132 static int type_size(CType
*type
, int *a
)
6137 bt
= type
->t
& VT_BTYPE
;
6138 if (bt
== VT_STRUCT
) {
6143 } else if (bt
== VT_PTR
) {
6144 if (type
->t
& VT_ARRAY
) {
6146 return type_size(&s
->type
, a
) * s
->c
;
6151 } else if (bt
== VT_LDOUBLE
) {
6153 return LDOUBLE_SIZE
;
6154 } else if (bt
== VT_DOUBLE
|| bt
== VT_LLONG
) {
6155 #ifdef TCC_TARGET_I386
6157 #elif defined(TCC_TARGET_ARM)
6167 } else if (bt
== VT_INT
|| bt
== VT_ENUM
|| bt
== VT_FLOAT
) {
6170 } else if (bt
== VT_SHORT
) {
6174 /* char, void, function, _Bool */
6180 /* return the pointed type of t */
6181 static inline CType
*pointed_type(CType
*type
)
6183 return &type
->ref
->type
;
6186 /* modify type so that its it is a pointer to type. */
6187 static void mk_pointer(CType
*type
)
6190 s
= sym_push(SYM_FIELD
, type
, 0, -1);
6191 type
->t
= VT_PTR
| (type
->t
& ~VT_TYPE
);
6195 /* compare function types. OLD functions match any new functions */
6196 static int is_compatible_func(CType
*type1
, CType
*type2
)
6202 if (!is_compatible_types(&s1
->type
, &s2
->type
))
6204 /* check func_call */
6205 if (FUNC_CALL(s1
->r
) != FUNC_CALL(s2
->r
))
6207 /* XXX: not complete */
6208 if (s1
->c
== FUNC_OLD
|| s2
->c
== FUNC_OLD
)
6212 while (s1
!= NULL
) {
6215 if (!is_compatible_parameter_types(&s1
->type
, &s2
->type
))
6225 /* return true if type1 and type2 are the same. If unqualified is
6226 true, qualifiers on the types are ignored.
6228 - enums are not checked as gcc __builtin_types_compatible_p ()
6230 static int compare_types(CType
*type1
, CType
*type2
, int unqualified
)
6234 t1
= type1
->t
& VT_TYPE
;
6235 t2
= type2
->t
& VT_TYPE
;
6237 /* strip qualifiers before comparing */
6238 t1
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6239 t2
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6241 /* XXX: bitfields ? */
6244 /* test more complicated cases */
6245 bt1
= t1
& VT_BTYPE
;
6246 if (bt1
== VT_PTR
) {
6247 type1
= pointed_type(type1
);
6248 type2
= pointed_type(type2
);
6249 return is_compatible_types(type1
, type2
);
6250 } else if (bt1
== VT_STRUCT
) {
6251 return (type1
->ref
== type2
->ref
);
6252 } else if (bt1
== VT_FUNC
) {
6253 return is_compatible_func(type1
, type2
);
6259 /* return true if type1 and type2 are exactly the same (including
6262 static int is_compatible_types(CType
*type1
, CType
*type2
)
6264 return compare_types(type1
,type2
,0);
6267 /* return true if type1 and type2 are the same (ignoring qualifiers).
6269 static int is_compatible_parameter_types(CType
*type1
, CType
*type2
)
6271 return compare_types(type1
,type2
,1);
6274 /* print a type. If 'varstr' is not NULL, then the variable is also
6275 printed in the type */
6277 /* XXX: add array and function pointers */
6278 void type_to_str(char *buf
, int buf_size
,
6279 CType
*type
, const char *varstr
)
6286 t
= type
->t
& VT_TYPE
;
6289 if (t
& VT_CONSTANT
)
6290 pstrcat(buf
, buf_size
, "const ");
6291 if (t
& VT_VOLATILE
)
6292 pstrcat(buf
, buf_size
, "volatile ");
6293 if (t
& VT_UNSIGNED
)
6294 pstrcat(buf
, buf_size
, "unsigned ");
6324 tstr
= "long double";
6326 pstrcat(buf
, buf_size
, tstr
);
6330 if (bt
== VT_STRUCT
)
6334 pstrcat(buf
, buf_size
, tstr
);
6335 v
= type
->ref
->v
& ~SYM_STRUCT
;
6336 if (v
>= SYM_FIRST_ANOM
)
6337 pstrcat(buf
, buf_size
, "<anonymous>");
6339 pstrcat(buf
, buf_size
, get_tok_str(v
, NULL
));
6343 type_to_str(buf
, buf_size
, &s
->type
, varstr
);
6344 pstrcat(buf
, buf_size
, "(");
6346 while (sa
!= NULL
) {
6347 type_to_str(buf1
, sizeof(buf1
), &sa
->type
, NULL
);
6348 pstrcat(buf
, buf_size
, buf1
);
6351 pstrcat(buf
, buf_size
, ", ");
6353 pstrcat(buf
, buf_size
, ")");
6357 pstrcpy(buf1
, sizeof(buf1
), "*");
6359 pstrcat(buf1
, sizeof(buf1
), varstr
);
6360 type_to_str(buf
, buf_size
, &s
->type
, buf1
);
6364 pstrcat(buf
, buf_size
, " ");
6365 pstrcat(buf
, buf_size
, varstr
);
6370 /* verify type compatibility to store vtop in 'dt' type, and generate
6372 static void gen_assign_cast(CType
*dt
)
6374 CType
*st
, *type1
, *type2
, tmp_type1
, tmp_type2
;
6375 char buf1
[256], buf2
[256];
6378 st
= &vtop
->type
; /* source type */
6379 dbt
= dt
->t
& VT_BTYPE
;
6380 sbt
= st
->t
& VT_BTYPE
;
6381 if (dt
->t
& VT_CONSTANT
)
6382 warning("assignment of read-only location");
6385 /* special cases for pointers */
6386 /* '0' can also be a pointer */
6387 if (is_null_pointer(vtop
))
6389 /* accept implicit pointer to integer cast with warning */
6390 if (is_integer_btype(sbt
)) {
6391 warning("assignment makes pointer from integer without a cast");
6394 type1
= pointed_type(dt
);
6395 /* a function is implicitely a function pointer */
6396 if (sbt
== VT_FUNC
) {
6397 if ((type1
->t
& VT_BTYPE
) != VT_VOID
&&
6398 !is_compatible_types(pointed_type(dt
), st
))
6405 type2
= pointed_type(st
);
6406 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
6407 (type2
->t
& VT_BTYPE
) == VT_VOID
) {
6408 /* void * can match anything */
6410 /* exact type match, except for unsigned */
6413 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
6414 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
6415 if (!is_compatible_types(&tmp_type1
, &tmp_type2
))
6416 warning("assignment from incompatible pointer type");
6418 /* check const and volatile */
6419 if ((!(type1
->t
& VT_CONSTANT
) && (type2
->t
& VT_CONSTANT
)) ||
6420 (!(type1
->t
& VT_VOLATILE
) && (type2
->t
& VT_VOLATILE
)))
6421 warning("assignment discards qualifiers from pointer target type");
6427 if (sbt
== VT_PTR
|| sbt
== VT_FUNC
) {
6428 warning("assignment makes integer from pointer without a cast");
6430 /* XXX: more tests */
6435 tmp_type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6436 tmp_type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6437 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
6439 type_to_str(buf1
, sizeof(buf1
), st
, NULL
);
6440 type_to_str(buf2
, sizeof(buf2
), dt
, NULL
);
6441 error("cannot cast '%s' to '%s'", buf1
, buf2
);
6449 /* store vtop in lvalue pushed on stack */
6452 int sbt
, dbt
, ft
, r
, t
, size
, align
, bit_size
, bit_pos
, rc
, delayed_cast
;
6454 ft
= vtop
[-1].type
.t
;
6455 sbt
= vtop
->type
.t
& VT_BTYPE
;
6456 dbt
= ft
& VT_BTYPE
;
6457 if (((sbt
== VT_INT
|| sbt
== VT_SHORT
) && dbt
== VT_BYTE
) ||
6458 (sbt
== VT_INT
&& dbt
== VT_SHORT
)) {
6459 /* optimize char/short casts */
6460 delayed_cast
= VT_MUSTCAST
;
6461 vtop
->type
.t
= ft
& (VT_TYPE
& ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
)));
6462 /* XXX: factorize */
6463 if (ft
& VT_CONSTANT
)
6464 warning("assignment of read-only location");
6467 if (!(ft
& VT_BITFIELD
))
6468 gen_assign_cast(&vtop
[-1].type
);
6471 if (sbt
== VT_STRUCT
) {
6472 /* if structure, only generate pointer */
6473 /* structure assignment : generate memcpy */
6474 /* XXX: optimize if small size */
6475 if (!nocode_wanted
) {
6476 size
= type_size(&vtop
->type
, &align
);
6480 vpush_global_sym(&func_old_type
, TOK_memcpy8
);
6481 else if(!(align
& 3))
6482 vpush_global_sym(&func_old_type
, TOK_memcpy4
);
6485 vpush_global_sym(&func_old_type
, TOK_memcpy
);
6489 vtop
->type
.t
= VT_INT
;
6493 vtop
->type
.t
= VT_INT
;
6505 /* leave source on stack */
6506 } else if (ft
& VT_BITFIELD
) {
6507 /* bitfield store handling */
6508 bit_pos
= (ft
>> VT_STRUCT_SHIFT
) & 0x3f;
6509 bit_size
= (ft
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
6510 /* remove bit field info to avoid loops */
6511 vtop
[-1].type
.t
= ft
& ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
6513 /* duplicate source into other register */
6518 if((ft
& VT_BTYPE
) == VT_BOOL
) {
6519 gen_cast(&vtop
[-1].type
);
6520 vtop
[-1].type
.t
= (vtop
[-1].type
.t
& ~VT_BTYPE
) | (VT_BYTE
| VT_UNSIGNED
);
6523 /* duplicate destination */
6525 vtop
[-1] = vtop
[-2];
6527 /* mask and shift source */
6528 if((ft
& VT_BTYPE
) != VT_BOOL
) {
6529 vpushi((1 << bit_size
) - 1);
6534 /* load destination, mask and or with source */
6536 vpushi(~(((1 << bit_size
) - 1) << bit_pos
));
6542 /* pop off shifted source from "duplicate source..." above */
6546 #ifdef CONFIG_TCC_BCHECK
6547 /* bound check case */
6548 if (vtop
[-1].r
& VT_MUSTBOUND
) {
6554 if (!nocode_wanted
) {
6558 r
= gv(rc
); /* generate value */
6559 /* if lvalue was saved on stack, must read it */
6560 if ((vtop
[-1].r
& VT_VALMASK
) == VT_LLOCAL
) {
6562 t
= get_reg(RC_INT
);
6564 sv
.r
= VT_LOCAL
| VT_LVAL
;
6565 sv
.c
.ul
= vtop
[-1].c
.ul
;
6567 vtop
[-1].r
= t
| VT_LVAL
;
6570 /* two word case handling : store second register at word + 4 */
6571 if ((ft
& VT_BTYPE
) == VT_LLONG
) {
6573 /* convert to int to increment easily */
6574 vtop
->type
.t
= VT_INT
;
6580 /* XXX: it works because r2 is spilled last ! */
6581 store(vtop
->r2
, vtop
- 1);
6585 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
6586 vtop
->r
|= delayed_cast
;
6590 /* post defines POST/PRE add. c is the token ++ or -- */
6591 void inc(int post
, int c
)
6594 vdup(); /* save lvalue */
6596 gv_dup(); /* duplicate value */
6601 vpushi(c
- TOK_MID
);
6603 vstore(); /* store value */
6605 vpop(); /* if post op, return saved value */
6608 /* Parse GNUC __attribute__ extension. Currently, the following
6609 extensions are recognized:
6610 - aligned(n) : set data/function alignment.
6611 - packed : force data alignment to 1
6612 - section(x) : generate data/code in this section.
6613 - unused : currently ignored, but may be used someday.
6614 - regparm(n) : pass function parameters in registers (i386 only)
6616 static void parse_attribute(AttributeDef
*ad
)
6620 while (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
) {
6624 while (tok
!= ')') {
6625 if (tok
< TOK_IDENT
)
6626 expect("attribute name");
6634 expect("section name");
6635 ad
->section
= find_section(tcc_state
, (char *)tokc
.cstr
->data
);
6644 if (n
<= 0 || (n
& (n
- 1)) != 0)
6645 error("alignment must be a positive power of two");
6658 /* currently, no need to handle it because tcc does not
6659 track unused objects */
6663 /* currently, no need to handle it because tcc does not
6664 track unused objects */
6669 FUNC_CALL(ad
->func_attr
) = FUNC_CDECL
;
6674 FUNC_CALL(ad
->func_attr
) = FUNC_STDCALL
;
6676 #ifdef TCC_TARGET_I386
6686 FUNC_CALL(ad
->func_attr
) = FUNC_FASTCALL1
+ n
- 1;
6692 FUNC_CALL(ad
->func_attr
) = FUNC_FASTCALLW
;
6696 FUNC_EXPORT(ad
->func_attr
) = 1;
6699 if (tcc_state
->warn_unsupported
)
6700 warning("'%s' attribute ignored", get_tok_str(t
, NULL
));
6701 /* skip parameters */
6703 int parenthesis
= 0;
6707 else if (tok
== ')')
6710 } while (parenthesis
&& tok
!= -1);
6723 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
6724 static void struct_decl(CType
*type
, int u
)
6726 int a
, v
, size
, align
, maxalign
, c
, offset
;
6727 int bit_size
, bit_pos
, bsize
, bt
, lbit_pos
, prevbt
;
6728 Sym
*s
, *ss
, *ass
, **ps
;
6732 a
= tok
; /* save decl type */
6737 /* struct already defined ? return it */
6739 expect("struct/union/enum name");
6743 error("invalid type");
6750 /* we put an undefined size for struct/union */
6751 s
= sym_push(v
| SYM_STRUCT
, &type1
, 0, -1);
6752 s
->r
= 0; /* default alignment is zero as gcc */
6753 /* put struct/union/enum name in type */
6761 error("struct/union/enum already defined");
6762 /* cannot be empty */
6764 /* non empty enums are not allowed */
6765 if (a
== TOK_ENUM
) {
6769 expect("identifier");
6775 /* enum symbols have static storage */
6776 ss
= sym_push(v
, &int_type
, VT_CONST
, c
);
6777 ss
->type
.t
|= VT_STATIC
;
6782 /* NOTE: we accept a trailing comma */
6793 while (tok
!= '}') {
6794 parse_btype(&btype
, &ad
);
6800 type_decl(&type1
, &ad
, &v
, TYPE_DIRECT
| TYPE_ABSTRACT
);
6801 if (v
== 0 && (type1
.t
& VT_BTYPE
) != VT_STRUCT
)
6802 expect("identifier");
6803 if ((type1
.t
& VT_BTYPE
) == VT_FUNC
||
6804 (type1
.t
& (VT_TYPEDEF
| VT_STATIC
| VT_EXTERN
| VT_INLINE
)))
6805 error("invalid type for '%s'",
6806 get_tok_str(v
, NULL
));
6810 bit_size
= expr_const();
6811 /* XXX: handle v = 0 case for messages */
6813 error("negative width in bit-field '%s'",
6814 get_tok_str(v
, NULL
));
6815 if (v
&& bit_size
== 0)
6816 error("zero width for bit-field '%s'",
6817 get_tok_str(v
, NULL
));
6819 size
= type_size(&type1
, &align
);
6821 if (align
< ad
.aligned
)
6823 } else if (ad
.packed
) {
6825 } else if (*tcc_state
->pack_stack_ptr
) {
6826 if (align
> *tcc_state
->pack_stack_ptr
)
6827 align
= *tcc_state
->pack_stack_ptr
;
6830 if (bit_size
>= 0) {
6831 bt
= type1
.t
& VT_BTYPE
;
6837 error("bitfields must have scalar type");
6839 if (bit_size
> bsize
) {
6840 error("width of '%s' exceeds its type",
6841 get_tok_str(v
, NULL
));
6842 } else if (bit_size
== bsize
) {
6843 /* no need for bit fields */
6845 } else if (bit_size
== 0) {
6846 /* XXX: what to do if only padding in a
6848 /* zero size: means to pad */
6851 /* we do not have enough room ?
6852 did the type change?
6854 if ((bit_pos
+ bit_size
) > bsize
||
6855 bt
!= prevbt
|| a
== TOK_UNION
)
6858 /* XXX: handle LSB first */
6859 type1
.t
|= VT_BITFIELD
|
6860 (bit_pos
<< VT_STRUCT_SHIFT
) |
6861 (bit_size
<< (VT_STRUCT_SHIFT
+ 6));
6862 bit_pos
+= bit_size
;
6868 if (v
!= 0 || (type1
.t
& VT_BTYPE
) == VT_STRUCT
) {
6869 /* add new memory data only if starting
6871 if (lbit_pos
== 0) {
6872 if (a
== TOK_STRUCT
) {
6873 c
= (c
+ align
- 1) & -align
;
6882 if (align
> maxalign
)
6886 printf("add field %s offset=%d",
6887 get_tok_str(v
, NULL
), offset
);
6888 if (type1
.t
& VT_BITFIELD
) {
6889 printf(" pos=%d size=%d",
6890 (type1
.t
>> VT_STRUCT_SHIFT
) & 0x3f,
6891 (type1
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f);
6896 if (v
== 0 && (type1
.t
& VT_BTYPE
) == VT_STRUCT
) {
6898 while ((ass
= ass
->next
) != NULL
) {
6899 ss
= sym_push(ass
->v
, &ass
->type
, 0, offset
+ ass
->c
);
6904 ss
= sym_push(v
| SYM_FIELD
, &type1
, 0, offset
);
6908 if (tok
== ';' || tok
== TOK_EOF
)
6915 /* store size and alignment */
6916 s
->c
= (c
+ maxalign
- 1) & -maxalign
;
6922 /* return 0 if no type declaration. otherwise, return the basic type
6925 static int parse_btype(CType
*type
, AttributeDef
*ad
)
6927 int t
, u
, type_found
, typespec_found
, typedef_found
;
6931 memset(ad
, 0, sizeof(AttributeDef
));
6939 /* currently, we really ignore extension */
6949 if ((t
& VT_BTYPE
) != 0)
6950 error("too many basic types");
6966 if ((t
& VT_BTYPE
) == VT_DOUBLE
) {
6967 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6968 } else if ((t
& VT_BTYPE
) == VT_LONG
) {
6969 t
= (t
& ~VT_BTYPE
) | VT_LLONG
;
6983 if ((t
& VT_BTYPE
) == VT_LONG
) {
6984 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6991 struct_decl(&type1
, VT_ENUM
);
6994 type
->ref
= type1
.ref
;
6998 struct_decl(&type1
, VT_STRUCT
);
7001 /* type modifiers */
7054 /* GNUC attribute */
7055 case TOK_ATTRIBUTE1
:
7056 case TOK_ATTRIBUTE2
:
7057 parse_attribute(ad
);
7064 parse_expr_type(&type1
);
7067 if (typespec_found
|| typedef_found
)
7070 if (!s
|| !(s
->type
.t
& VT_TYPEDEF
))
7073 t
|= (s
->type
.t
& ~VT_TYPEDEF
);
7074 type
->ref
= s
->type
.ref
;
7082 if ((t
& (VT_SIGNED
|VT_UNSIGNED
)) == (VT_SIGNED
|VT_UNSIGNED
))
7083 error("signed and unsigned modifier");
7084 if (tcc_state
->char_is_unsigned
) {
7085 if ((t
& (VT_SIGNED
|VT_UNSIGNED
|VT_BTYPE
)) == VT_BYTE
)
7090 /* long is never used as type */
7091 if ((t
& VT_BTYPE
) == VT_LONG
)
7092 t
= (t
& ~VT_BTYPE
) | VT_INT
;
7097 /* convert a function parameter type (array to pointer and function to
7098 function pointer) */
7099 static inline void convert_parameter_type(CType
*pt
)
7101 /* remove const and volatile qualifiers (XXX: const could be used
7102 to indicate a const function parameter */
7103 pt
->t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7104 /* array must be transformed to pointer according to ANSI C */
7106 if ((pt
->t
& VT_BTYPE
) == VT_FUNC
) {
7111 static void post_type(CType
*type
, AttributeDef
*ad
)
7113 int n
, l
, t1
, arg_size
, align
;
7114 Sym
**plast
, *s
, *first
;
7119 /* function declaration */
7127 /* read param name and compute offset */
7128 if (l
!= FUNC_OLD
) {
7129 if (!parse_btype(&pt
, &ad1
)) {
7131 error("invalid type");
7138 if ((pt
.t
& VT_BTYPE
) == VT_VOID
&& tok
== ')')
7140 type_decl(&pt
, &ad1
, &n
, TYPE_DIRECT
| TYPE_ABSTRACT
);
7141 if ((pt
.t
& VT_BTYPE
) == VT_VOID
)
7142 error("parameter declared as void");
7143 arg_size
+= (type_size(&pt
, &align
) + 3) & ~3;
7148 expect("identifier");
7152 convert_parameter_type(&pt
);
7153 s
= sym_push(n
| SYM_FIELD
, &pt
, 0, 0);
7159 if (l
== FUNC_NEW
&& tok
== TOK_DOTS
) {
7166 /* if no parameters, then old type prototype */
7170 t1
= type
->t
& VT_STORAGE
;
7171 /* NOTE: const is ignored in returned type as it has a special
7172 meaning in gcc / C++ */
7173 type
->t
&= ~(VT_STORAGE
| VT_CONSTANT
);
7174 post_type(type
, ad
);
7175 /* we push a anonymous symbol which will contain the function prototype */
7176 FUNC_ARGS(ad
->func_attr
) = arg_size
;
7177 s
= sym_push(SYM_FIELD
, type
, ad
->func_attr
, l
);
7179 type
->t
= t1
| VT_FUNC
;
7181 } else if (tok
== '[') {
7182 /* array definition */
7188 error("invalid array size");
7191 /* parse next post type */
7192 t1
= type
->t
& VT_STORAGE
;
7193 type
->t
&= ~VT_STORAGE
;
7194 post_type(type
, ad
);
7196 /* we push a anonymous symbol which will contain the array
7198 s
= sym_push(SYM_FIELD
, type
, 0, n
);
7199 type
->t
= t1
| VT_ARRAY
| VT_PTR
;
7204 /* Parse a type declaration (except basic type), and return the type
7205 in 'type'. 'td' is a bitmask indicating which kind of type decl is
7206 expected. 'type' should contain the basic type. 'ad' is the
7207 attribute definition of the basic type. It can be modified by
7210 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
)
7213 CType type1
, *type2
;
7216 while (tok
== '*') {
7224 qualifiers
|= VT_CONSTANT
;
7229 qualifiers
|= VT_VOLATILE
;
7237 type
->t
|= qualifiers
;
7240 /* XXX: clarify attribute handling */
7241 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
7242 parse_attribute(ad
);
7244 /* recursive type */
7245 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
7246 type1
.t
= 0; /* XXX: same as int */
7249 /* XXX: this is not correct to modify 'ad' at this point, but
7250 the syntax is not clear */
7251 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
7252 parse_attribute(ad
);
7253 type_decl(&type1
, ad
, v
, td
);
7256 /* type identifier */
7257 if (tok
>= TOK_IDENT
&& (td
& TYPE_DIRECT
)) {
7261 if (!(td
& TYPE_ABSTRACT
))
7262 expect("identifier");
7266 post_type(type
, ad
);
7267 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
7268 parse_attribute(ad
);
7271 /* append type at the end of type1 */
7284 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
7285 static int lvalue_type(int t
)
7290 if (bt
== VT_BYTE
|| bt
== VT_BOOL
)
7292 else if (bt
== VT_SHORT
)
7296 if (t
& VT_UNSIGNED
)
7297 r
|= VT_LVAL_UNSIGNED
;
7301 /* indirection with full error checking and bound check */
7302 static void indir(void)
7304 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
) {
7305 if ((vtop
->type
.t
& VT_BTYPE
) == VT_FUNC
)
7309 if ((vtop
->r
& VT_LVAL
) && !nocode_wanted
)
7311 vtop
->type
= *pointed_type(&vtop
->type
);
7312 /* Arrays and functions are never lvalues */
7313 if (!(vtop
->type
.t
& VT_ARRAY
)
7314 && (vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
) {
7315 vtop
->r
|= lvalue_type(vtop
->type
.t
);
7316 /* if bound checking, the referenced pointer must be checked */
7317 if (do_bounds_check
)
7318 vtop
->r
|= VT_MUSTBOUND
;
7322 /* pass a parameter to a function and do type checking and casting */
7323 static void gfunc_param_typed(Sym
*func
, Sym
*arg
)
7328 func_type
= func
->c
;
7329 if (func_type
== FUNC_OLD
||
7330 (func_type
== FUNC_ELLIPSIS
&& arg
== NULL
)) {
7331 /* default casting : only need to convert float to double */
7332 if ((vtop
->type
.t
& VT_BTYPE
) == VT_FLOAT
) {
7336 } else if (arg
== NULL
) {
7337 error("too many arguments to function");
7340 type
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
7341 gen_assign_cast(&type
);
7345 /* parse an expression of the form '(type)' or '(expr)' and return its
7347 static void parse_expr_type(CType
*type
)
7353 if (parse_btype(type
, &ad
)) {
7354 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
7361 static void parse_type(CType
*type
)
7366 if (!parse_btype(type
, &ad
)) {
7369 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
7372 static void vpush_tokc(int t
)
7376 vsetc(&type
, VT_CONST
, &tokc
);
7379 static void unary(void)
7381 int n
, t
, align
, size
, r
;
7386 /* XXX: GCC 2.95.3 does not generate a table although it should be
7400 vpush_tokc(VT_INT
| VT_UNSIGNED
);
7404 vpush_tokc(VT_LLONG
);
7408 vpush_tokc(VT_LLONG
| VT_UNSIGNED
);
7412 vpush_tokc(VT_FLOAT
);
7416 vpush_tokc(VT_DOUBLE
);
7420 vpush_tokc(VT_LDOUBLE
);
7423 case TOK___FUNCTION__
:
7425 goto tok_identifier
;
7431 /* special function name identifier */
7432 len
= strlen(funcname
) + 1;
7433 /* generate char[len] type */
7438 vpush_ref(&type
, data_section
, data_section
->data_offset
, len
);
7439 ptr
= section_ptr_add(data_section
, len
);
7440 memcpy(ptr
, funcname
, len
);
7445 #ifdef TCC_TARGET_PE
7446 t
= VT_SHORT
| VT_UNSIGNED
;
7452 /* string parsing */
7455 if (tcc_state
->warn_write_strings
)
7460 memset(&ad
, 0, sizeof(AttributeDef
));
7461 decl_initializer_alloc(&type
, &ad
, VT_CONST
, 2, 0, 0);
7466 if (parse_btype(&type
, &ad
)) {
7467 type_decl(&type
, &ad
, &n
, TYPE_ABSTRACT
);
7469 /* check ISOC99 compound literal */
7471 /* data is allocated locally by default */
7476 /* all except arrays are lvalues */
7477 if (!(type
.t
& VT_ARRAY
))
7478 r
|= lvalue_type(type
.t
);
7479 memset(&ad
, 0, sizeof(AttributeDef
));
7480 decl_initializer_alloc(&type
, &ad
, r
, 1, 0, 0);
7485 } else if (tok
== '{') {
7486 /* save all registers */
7488 /* statement expression : we do not accept break/continue
7489 inside as GCC does */
7490 block(NULL
, NULL
, NULL
, NULL
, 0, 1);
7505 /* functions names must be treated as function pointers,
7506 except for unary '&' and sizeof. Since we consider that
7507 functions are not lvalues, we only have to handle it
7508 there and in function calls. */
7509 /* arrays can also be used although they are not lvalues */
7510 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
&&
7511 !(vtop
->type
.t
& VT_ARRAY
) && !(vtop
->type
.t
& VT_LLOCAL
))
7513 mk_pointer(&vtop
->type
);
7519 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) {
7521 boolean
.t
= VT_BOOL
;
7523 vtop
->c
.i
= !vtop
->c
.i
;
7524 } else if ((vtop
->r
& VT_VALMASK
) == VT_CMP
)
7525 vtop
->c
.i
= vtop
->c
.i
^ 1;
7528 vseti(VT_JMP
, gtst(1, 0));
7539 /* in order to force cast, we add zero */
7541 if ((vtop
->type
.t
& VT_BTYPE
) == VT_PTR
)
7542 error("pointer not accepted for unary plus");
7552 parse_expr_type(&type
);
7556 size
= type_size(&type
, &align
);
7557 if (t
== TOK_SIZEOF
) {
7559 error("sizeof applied to an incomplete type");
7564 vtop
->type
.t
|= VT_UNSIGNED
;
7567 case TOK_builtin_types_compatible_p
:
7576 type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7577 type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7578 vpushi(is_compatible_types(&type1
, &type2
));
7581 case TOK_builtin_constant_p
:
7583 int saved_nocode_wanted
, res
;
7586 saved_nocode_wanted
= nocode_wanted
;
7589 res
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
7591 nocode_wanted
= saved_nocode_wanted
;
7611 goto tok_identifier
;
7613 /* allow to take the address of a label */
7614 if (tok
< TOK_UIDENT
)
7615 expect("label identifier");
7616 s
= label_find(tok
);
7618 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
7620 if (s
->r
== LABEL_DECLARED
)
7621 s
->r
= LABEL_FORWARD
;
7624 s
->type
.t
= VT_VOID
;
7625 mk_pointer(&s
->type
);
7626 s
->type
.t
|= VT_STATIC
;
7628 vset(&s
->type
, VT_CONST
| VT_SYM
, 0);
7637 expect("identifier");
7641 error("'%s' undeclared", get_tok_str(t
, NULL
));
7642 /* for simple function calls, we tolerate undeclared
7643 external reference to int() function */
7644 if (tcc_state
->warn_implicit_function_declaration
)
7645 warning("implicit declaration of function '%s'",
7646 get_tok_str(t
, NULL
));
7647 s
= external_global_sym(t
, &func_old_type
, 0);
7649 if ((s
->type
.t
& (VT_STATIC
| VT_INLINE
| VT_BTYPE
)) ==
7650 (VT_STATIC
| VT_INLINE
| VT_FUNC
)) {
7651 /* if referencing an inline function, then we generate a
7652 symbol to it if not already done. It will have the
7653 effect to generate code for it at the end of the
7654 compilation unit. Inline function as always
7655 generated in the text section. */
7657 put_extern_sym(s
, text_section
, 0, 0);
7658 r
= VT_SYM
| VT_CONST
;
7662 vset(&s
->type
, r
, s
->c
);
7663 /* if forward reference, we must point to s */
7664 if (vtop
->r
& VT_SYM
) {
7671 /* post operations */
7673 if (tok
== TOK_INC
|| tok
== TOK_DEC
) {
7676 } else if (tok
== '.' || tok
== TOK_ARROW
) {
7678 if (tok
== TOK_ARROW
)
7683 /* expect pointer on structure */
7684 if ((vtop
->type
.t
& VT_BTYPE
) != VT_STRUCT
)
7685 expect("struct or union");
7689 while ((s
= s
->next
) != NULL
) {
7694 error("field not found: %s", get_tok_str(tok
& ~SYM_FIELD
, NULL
));
7695 /* add field offset to pointer */
7696 vtop
->type
= char_pointer_type
; /* change type to 'char *' */
7699 /* change type to field type, and set to lvalue */
7700 vtop
->type
= s
->type
;
7701 /* an array is never an lvalue */
7702 if (!(vtop
->type
.t
& VT_ARRAY
)) {
7703 vtop
->r
|= lvalue_type(vtop
->type
.t
);
7704 /* if bound checking, the referenced pointer must be checked */
7705 if (do_bounds_check
)
7706 vtop
->r
|= VT_MUSTBOUND
;
7709 } else if (tok
== '[') {
7715 } else if (tok
== '(') {
7721 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
) {
7722 /* pointer test (no array accepted) */
7723 if ((vtop
->type
.t
& (VT_BTYPE
| VT_ARRAY
)) == VT_PTR
) {
7724 vtop
->type
= *pointed_type(&vtop
->type
);
7725 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
)
7729 expect("function pointer");
7732 vtop
->r
&= ~VT_LVAL
; /* no lvalue */
7734 /* get return type */
7737 sa
= s
->next
; /* first parameter */
7740 /* compute first implicit argument if a structure is returned */
7741 if ((s
->type
.t
& VT_BTYPE
) == VT_STRUCT
) {
7742 /* get some space for the returned structure */
7743 size
= type_size(&s
->type
, &align
);
7744 loc
= (loc
- size
) & -align
;
7746 ret
.r
= VT_LOCAL
| VT_LVAL
;
7747 /* pass it as 'int' to avoid structure arg passing
7749 vseti(VT_LOCAL
, loc
);
7754 /* return in register */
7755 if (is_float(ret
.type
.t
)) {
7758 if ((ret
.type
.t
& VT_BTYPE
) == VT_LLONG
)
7767 gfunc_param_typed(s
, sa
);
7777 error("too few arguments to function");
7779 if (!nocode_wanted
) {
7780 gfunc_call(nb_args
);
7782 vtop
-= (nb_args
+ 1);
7785 vsetc(&ret
.type
, ret
.r
, &ret
.c
);
7793 static void uneq(void)
7799 (tok
>= TOK_A_MOD
&& tok
<= TOK_A_DIV
) ||
7800 tok
== TOK_A_XOR
|| tok
== TOK_A_OR
||
7801 tok
== TOK_A_SHL
|| tok
== TOK_A_SAR
) {
7816 static void expr_prod(void)
7821 while (tok
== '*' || tok
== '/' || tok
== '%') {
7829 static void expr_sum(void)
7834 while (tok
== '+' || tok
== '-') {
7842 static void expr_shift(void)
7847 while (tok
== TOK_SHL
|| tok
== TOK_SAR
) {
7855 static void expr_cmp(void)
7860 while ((tok
>= TOK_ULE
&& tok
<= TOK_GT
) ||
7861 tok
== TOK_ULT
|| tok
== TOK_UGE
) {
7869 static void expr_cmpeq(void)
7874 while (tok
== TOK_EQ
|| tok
== TOK_NE
) {
7882 static void expr_and(void)
7885 while (tok
== '&') {
7892 static void expr_xor(void)
7895 while (tok
== '^') {
7902 static void expr_or(void)
7905 while (tok
== '|') {
7912 /* XXX: fix this mess */
7913 static void expr_land_const(void)
7916 while (tok
== TOK_LAND
) {
7923 /* XXX: fix this mess */
7924 static void expr_lor_const(void)
7927 while (tok
== TOK_LOR
) {
7934 /* only used if non constant */
7935 static void expr_land(void)
7940 if (tok
== TOK_LAND
) {
7945 if (tok
!= TOK_LAND
) {
7955 static void expr_lor(void)
7960 if (tok
== TOK_LOR
) {
7965 if (tok
!= TOK_LOR
) {
7975 /* XXX: better constant handling */
7976 static void expr_eq(void)
7978 int tt
, u
, r1
, r2
, rc
, t1
, t2
, bt1
, bt2
;
7980 CType type
, type1
, type2
;
7989 if (tok
== ':' && gnu_ext
) {
8005 if (vtop
!= vstack
) {
8006 /* needed to avoid having different registers saved in
8008 if (is_float(vtop
->type
.t
))
8015 if (tok
== ':' && gnu_ext
) {
8023 sv
= *vtop
; /* save value to handle it later */
8024 vtop
--; /* no vpop so that FP stack is not flushed */
8032 bt1
= t1
& VT_BTYPE
;
8034 bt2
= t2
& VT_BTYPE
;
8035 /* cast operands to correct type according to ISOC rules */
8036 if (is_float(bt1
) || is_float(bt2
)) {
8037 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
8038 type
.t
= VT_LDOUBLE
;
8039 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
8044 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
8045 /* cast to biggest op */
8047 /* convert to unsigned if it does not fit in a long long */
8048 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
8049 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
8050 type
.t
|= VT_UNSIGNED
;
8051 } else if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
8052 /* XXX: test pointer compatibility */
8054 } else if (bt1
== VT_FUNC
|| bt2
== VT_FUNC
) {
8055 /* XXX: test function pointer compatibility */
8057 } else if (bt1
== VT_STRUCT
|| bt2
== VT_STRUCT
) {
8058 /* XXX: test structure compatibility */
8060 } else if (bt1
== VT_VOID
|| bt2
== VT_VOID
) {
8061 /* NOTE: as an extension, we accept void on only one side */
8064 /* integer operations */
8066 /* convert to unsigned if it does not fit in an integer */
8067 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
8068 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
8069 type
.t
|= VT_UNSIGNED
;
8072 /* now we convert second operand */
8074 if (VT_STRUCT
== (vtop
->type
.t
& VT_BTYPE
))
8077 if (is_float(type
.t
)) {
8079 } else if ((type
.t
& VT_BTYPE
) == VT_LLONG
) {
8080 /* for long longs, we use fixed registers to avoid having
8081 to handle a complicated move */
8086 /* this is horrible, but we must also convert first
8090 /* put again first value and cast it */
8093 if (VT_STRUCT
== (vtop
->type
.t
& VT_BTYPE
))
8103 static void gexpr(void)
8114 /* parse an expression and return its type without any side effect. */
8115 static void expr_type(CType
*type
)
8117 int saved_nocode_wanted
;
8119 saved_nocode_wanted
= nocode_wanted
;
8124 nocode_wanted
= saved_nocode_wanted
;
8127 /* parse a unary expression and return its type without any side
8129 static void unary_type(CType
*type
)
8141 /* parse a constant expression and return value in vtop. */
8142 static void expr_const1(void)
8151 /* parse an integer constant and return its value. */
8152 static int expr_const(void)
8156 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
8157 expect("constant expression");
8163 /* return the label token if current token is a label, otherwise
8165 static int is_label(void)
8169 /* fast test first */
8170 if (tok
< TOK_UIDENT
)
8172 /* no need to save tokc because tok is an identifier */
8179 unget_tok(last_tok
);
8184 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
8185 int case_reg
, int is_expr
)
8190 /* generate line number info */
8192 (last_line_num
!= file
->line_num
|| last_ind
!= ind
)) {
8193 put_stabn(N_SLINE
, 0, file
->line_num
, ind
- func_ind
);
8195 last_line_num
= file
->line_num
;
8199 /* default return value is (void) */
8201 vtop
->type
.t
= VT_VOID
;
8204 if (tok
== TOK_IF
) {
8211 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
8213 if (c
== TOK_ELSE
) {
8217 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
8218 gsym(d
); /* patch else jmp */
8221 } else if (tok
== TOK_WHILE
) {
8229 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
8233 } else if (tok
== '{') {
8237 /* record local declaration stack position */
8239 llabel
= local_label_stack
;
8240 /* handle local labels declarations */
8241 if (tok
== TOK_LABEL
) {
8244 if (tok
< TOK_UIDENT
)
8245 expect("label identifier");
8246 label_push(&local_label_stack
, tok
, LABEL_DECLARED
);
8256 while (tok
!= '}') {
8261 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
8264 /* pop locally defined labels */
8265 label_pop(&local_label_stack
, llabel
);
8266 /* pop locally defined symbols */
8268 /* XXX: this solution makes only valgrind happy...
8269 triggered by gcc.c-torture/execute/20000917-1.c */
8271 switch(vtop
->type
.t
& VT_BTYPE
) {
8276 for(p
=vtop
->type
.ref
;p
;p
=p
->prev
)
8278 error("unsupported expression type");
8281 sym_pop(&local_stack
, s
);
8283 } else if (tok
== TOK_RETURN
) {
8287 gen_assign_cast(&func_vt
);
8288 if ((func_vt
.t
& VT_BTYPE
) == VT_STRUCT
) {
8290 /* if returning structure, must copy it to implicit
8291 first pointer arg location */
8294 size
= type_size(&func_vt
,&align
);
8297 if((vtop
->r
!= (VT_LOCAL
| VT_LVAL
) || (vtop
->c
.i
& 3))
8301 loc
= (loc
- size
) & -4;
8304 vset(&type
, VT_LOCAL
| VT_LVAL
, addr
);
8307 vset(&int_type
, VT_LOCAL
| VT_LVAL
, addr
);
8309 vtop
->type
= int_type
;
8315 vset(&type
, VT_LOCAL
| VT_LVAL
, func_vc
);
8318 /* copy structure value to pointer */
8323 } else if (is_float(func_vt
.t
)) {
8328 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
8331 rsym
= gjmp(rsym
); /* jmp */
8332 } else if (tok
== TOK_BREAK
) {
8335 error("cannot break");
8336 *bsym
= gjmp(*bsym
);
8339 } else if (tok
== TOK_CONTINUE
) {
8342 error("cannot continue");
8343 *csym
= gjmp(*csym
);
8346 } else if (tok
== TOK_FOR
) {
8373 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
8378 if (tok
== TOK_DO
) {
8383 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
8394 if (tok
== TOK_SWITCH
) {
8398 /* XXX: other types than integer */
8399 case_reg
= gv(RC_INT
);
8403 b
= gjmp(0); /* jump to first case */
8405 block(&a
, csym
, &b
, &c
, case_reg
, 0);
8406 /* if no default, jmp after switch */
8414 if (tok
== TOK_CASE
) {
8421 if (gnu_ext
&& tok
== TOK_DOTS
) {
8425 warning("empty case range");
8427 /* since a case is like a label, we must skip it with a jmp */
8434 *case_sym
= gtst(1, 0);
8437 *case_sym
= gtst(1, 0);
8441 *case_sym
= gtst(1, *case_sym
);
8446 goto block_after_label
;
8448 if (tok
== TOK_DEFAULT
) {
8454 error("too many 'default'");
8457 goto block_after_label
;
8459 if (tok
== TOK_GOTO
) {
8461 if (tok
== '*' && gnu_ext
) {
8465 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
8468 } else if (tok
>= TOK_UIDENT
) {
8469 s
= label_find(tok
);
8470 /* put forward definition if needed */
8472 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
8474 if (s
->r
== LABEL_DECLARED
)
8475 s
->r
= LABEL_FORWARD
;
8477 /* label already defined */
8478 if (s
->r
& LABEL_FORWARD
)
8479 s
->next
= (void *)gjmp((long)s
->next
);
8481 gjmp_addr((long)s
->next
);
8484 expect("label identifier");
8487 } else if (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
) {
8495 if (s
->r
== LABEL_DEFINED
)
8496 error("duplicate label '%s'", get_tok_str(s
->v
, NULL
));
8497 gsym((long)s
->next
);
8498 s
->r
= LABEL_DEFINED
;
8500 s
= label_push(&global_label_stack
, b
, LABEL_DEFINED
);
8502 s
->next
= (void *)ind
;
8503 /* we accept this, but it is a mistake */
8506 warning("deprecated use of label at end of compound statement");
8510 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
8513 /* expression case */
8528 /* t is the array or struct type. c is the array or struct
8529 address. cur_index/cur_field is the pointer to the current
8530 value. 'size_only' is true if only size info is needed (only used
8532 static void decl_designator(CType
*type
, Section
*sec
, unsigned long c
,
8533 int *cur_index
, Sym
**cur_field
,
8537 int notfirst
, index
, index_last
, align
, l
, nb_elems
, elem_size
;
8543 if (gnu_ext
&& (l
= is_label()) != 0)
8545 while (tok
== '[' || tok
== '.') {
8547 if (!(type
->t
& VT_ARRAY
))
8548 expect("array type");
8551 index
= expr_const();
8552 if (index
< 0 || (s
->c
>= 0 && index
>= s
->c
))
8553 expect("invalid index");
8554 if (tok
== TOK_DOTS
&& gnu_ext
) {
8556 index_last
= expr_const();
8557 if (index_last
< 0 ||
8558 (s
->c
>= 0 && index_last
>= s
->c
) ||
8560 expect("invalid index");
8566 *cur_index
= index_last
;
8567 type
= pointed_type(type
);
8568 elem_size
= type_size(type
, &align
);
8569 c
+= index
* elem_size
;
8570 /* NOTE: we only support ranges for last designator */
8571 nb_elems
= index_last
- index
+ 1;
8572 if (nb_elems
!= 1) {
8581 if ((type
->t
& VT_BTYPE
) != VT_STRUCT
)
8582 expect("struct/union type");
8595 /* XXX: fix this mess by using explicit storage field */
8597 type1
.t
|= (type
->t
& ~VT_TYPE
);
8611 if (type
->t
& VT_ARRAY
) {
8613 type
= pointed_type(type
);
8614 c
+= index
* type_size(type
, &align
);
8618 error("too many field init");
8619 /* XXX: fix this mess by using explicit storage field */
8621 type1
.t
|= (type
->t
& ~VT_TYPE
);
8626 decl_initializer(type
, sec
, c
, 0, size_only
);
8628 /* XXX: make it more general */
8629 if (!size_only
&& nb_elems
> 1) {
8630 unsigned long c_end
;
8635 error("range init not supported yet for dynamic storage");
8636 c_end
= c
+ nb_elems
* elem_size
;
8637 if (c_end
> sec
->data_allocated
)
8638 section_realloc(sec
, c_end
);
8639 src
= sec
->data
+ c
;
8641 for(i
= 1; i
< nb_elems
; i
++) {
8643 memcpy(dst
, src
, elem_size
);
8649 #define EXPR_CONST 1
8652 /* store a value or an expression directly in global data or in local array */
8653 static void init_putv(CType
*type
, Section
*sec
, unsigned long c
,
8654 int v
, int expr_type
)
8656 int saved_global_expr
, bt
, bit_pos
, bit_size
;
8658 unsigned long long bit_mask
;
8666 /* compound literals must be allocated globally in this case */
8667 saved_global_expr
= global_expr
;
8670 global_expr
= saved_global_expr
;
8671 /* NOTE: symbols are accepted */
8672 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) != VT_CONST
)
8673 error("initializer element is not constant");
8681 dtype
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
8684 /* XXX: not portable */
8685 /* XXX: generate error if incorrect relocation */
8686 gen_assign_cast(&dtype
);
8687 bt
= type
->t
& VT_BTYPE
;
8688 ptr
= sec
->data
+ c
;
8689 /* XXX: make code faster ? */
8690 if (!(type
->t
& VT_BITFIELD
)) {
8695 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
8696 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
8697 bit_mask
= (1LL << bit_size
) - 1;
8699 if ((vtop
->r
& VT_SYM
) &&
8705 (bt
== VT_INT
&& bit_size
!= 32)))
8706 error("initializer element is not computable at load time");
8709 vtop
->c
.i
= (vtop
->c
.i
!= 0);
8711 *(char *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8714 *(short *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8717 *(double *)ptr
= vtop
->c
.d
;
8720 *(long double *)ptr
= vtop
->c
.ld
;
8723 *(long long *)ptr
|= (vtop
->c
.ll
& bit_mask
) << bit_pos
;
8726 if (vtop
->r
& VT_SYM
) {
8727 greloc(sec
, vtop
->sym
, c
, R_DATA_32
);
8729 *(int *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8734 vset(&dtype
, VT_LOCAL
|VT_LVAL
, c
);
8741 /* put zeros for variable based init */
8742 static void init_putz(CType
*t
, Section
*sec
, unsigned long c
, int size
)
8745 /* nothing to do because globals are already set to zero */
8747 vpush_global_sym(&func_old_type
, TOK_memset
);
8755 /* 't' contains the type and storage info. 'c' is the offset of the
8756 object in section 'sec'. If 'sec' is NULL, it means stack based
8757 allocation. 'first' is true if array '{' must be read (multi
8758 dimension implicit array init handling). 'size_only' is true if
8759 size only evaluation is wanted (only for arrays). */
8760 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
8761 int first
, int size_only
)
8763 int index
, array_length
, n
, no_oblock
, nb
, parlevel
, i
;
8764 int size1
, align1
, expr_type
;
8768 if (type
->t
& VT_ARRAY
) {
8772 t1
= pointed_type(type
);
8773 size1
= type_size(t1
, &align1
);
8776 if ((first
&& tok
!= TOK_LSTR
&& tok
!= TOK_STR
) ||
8782 /* only parse strings here if correct type (otherwise: handle
8783 them as ((w)char *) expressions */
8784 if ((tok
== TOK_LSTR
&&
8785 #ifdef TCC_TARGET_PE
8786 (t1
->t
& VT_BTYPE
) == VT_SHORT
&& (t1
->t
& VT_UNSIGNED
)
8788 (t1
->t
& VT_BTYPE
) == VT_INT
8790 ) || (tok
== TOK_STR
&& (t1
->t
& VT_BTYPE
) == VT_BYTE
)) {
8791 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
8796 /* compute maximum number of chars wanted */
8798 cstr_len
= cstr
->size
;
8800 cstr_len
= cstr
->size
/ sizeof(nwchar_t
);
8803 if (n
>= 0 && nb
> (n
- array_length
))
8804 nb
= n
- array_length
;
8807 warning("initializer-string for array is too long");
8808 /* in order to go faster for common case (char
8809 string in global variable, we handle it
8811 if (sec
&& tok
== TOK_STR
&& size1
== 1) {
8812 memcpy(sec
->data
+ c
+ array_length
, cstr
->data
, nb
);
8816 ch
= ((unsigned char *)cstr
->data
)[i
];
8818 ch
= ((nwchar_t
*)cstr
->data
)[i
];
8819 init_putv(t1
, sec
, c
+ (array_length
+ i
) * size1
,
8827 /* only add trailing zero if enough storage (no
8828 warning in this case since it is standard) */
8829 if (n
< 0 || array_length
< n
) {
8831 init_putv(t1
, sec
, c
+ (array_length
* size1
), 0, EXPR_VAL
);
8837 while (tok
!= '}') {
8838 decl_designator(type
, sec
, c
, &index
, NULL
, size_only
);
8839 if (n
>= 0 && index
>= n
)
8840 error("index too large");
8841 /* must put zero in holes (note that doing it that way
8842 ensures that it even works with designators) */
8843 if (!size_only
&& array_length
< index
) {
8844 init_putz(t1
, sec
, c
+ array_length
* size1
,
8845 (index
- array_length
) * size1
);
8848 if (index
> array_length
)
8849 array_length
= index
;
8850 /* special test for multi dimensional arrays (may not
8851 be strictly correct if designators are used at the
8853 if (index
>= n
&& no_oblock
)
8862 /* put zeros at the end */
8863 if (!size_only
&& n
>= 0 && array_length
< n
) {
8864 init_putz(t1
, sec
, c
+ array_length
* size1
,
8865 (n
- array_length
) * size1
);
8867 /* patch type size if needed */
8869 s
->c
= array_length
;
8870 } else if ((type
->t
& VT_BTYPE
) == VT_STRUCT
&&
8871 (sec
|| !first
|| tok
== '{')) {
8874 /* NOTE: the previous test is a specific case for automatic
8875 struct/union init */
8876 /* XXX: union needs only one init */
8878 /* XXX: this test is incorrect for local initializers
8879 beginning with ( without {. It would be much more difficult
8880 to do it correctly (ideally, the expression parser should
8881 be used in all cases) */
8887 while (tok
== '(') {
8891 if (!parse_btype(&type1
, &ad1
))
8893 type_decl(&type1
, &ad1
, &n
, TYPE_ABSTRACT
);
8895 if (!is_assignable_types(type
, &type1
))
8896 error("invalid type for cast");
8901 if (first
|| tok
== '{') {
8910 while (tok
!= '}') {
8911 decl_designator(type
, sec
, c
, NULL
, &f
, size_only
);
8913 if (!size_only
&& array_length
< index
) {
8914 init_putz(type
, sec
, c
+ array_length
,
8915 index
- array_length
);
8917 index
= index
+ type_size(&f
->type
, &align1
);
8918 if (index
> array_length
)
8919 array_length
= index
;
8921 if (no_oblock
&& f
== NULL
)
8927 /* put zeros at the end */
8928 if (!size_only
&& array_length
< n
) {
8929 init_putz(type
, sec
, c
+ array_length
,
8938 } else if (tok
== '{') {
8940 decl_initializer(type
, sec
, c
, first
, size_only
);
8942 } else if (size_only
) {
8943 /* just skip expression */
8945 while ((parlevel
> 0 || (tok
!= '}' && tok
!= ',')) &&
8949 else if (tok
== ')')
8954 /* currently, we always use constant expression for globals
8955 (may change for scripting case) */
8956 expr_type
= EXPR_CONST
;
8958 expr_type
= EXPR_ANY
;
8959 init_putv(type
, sec
, c
, 0, expr_type
);
8963 /* parse an initializer for type 't' if 'has_init' is non zero, and
8964 allocate space in local or global data space ('r' is either
8965 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
8966 variable 'v' of scope 'scope' is declared before initializers are
8967 parsed. If 'v' is zero, then a reference to the new object is put
8968 in the value stack. If 'has_init' is 2, a special parsing is done
8969 to handle string constants. */
8970 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
8971 int has_init
, int v
, int scope
)
8973 int size
, align
, addr
, data_offset
;
8975 ParseState saved_parse_state
;
8976 TokenString init_str
;
8979 size
= type_size(type
, &align
);
8980 /* If unknown size, we must evaluate it before
8981 evaluating initializers because
8982 initializers can generate global data too
8983 (e.g. string pointers or ISOC99 compound
8984 literals). It also simplifies local
8985 initializers handling */
8986 tok_str_new(&init_str
);
8989 error("unknown type size");
8990 /* get all init string */
8991 if (has_init
== 2) {
8992 /* only get strings */
8993 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
8994 tok_str_add_tok(&init_str
);
8999 while (level
> 0 || (tok
!= ',' && tok
!= ';')) {
9001 error("unexpected end of file in initializer");
9002 tok_str_add_tok(&init_str
);
9005 else if (tok
== '}') {
9013 tok_str_add(&init_str
, -1);
9014 tok_str_add(&init_str
, 0);
9017 save_parse_state(&saved_parse_state
);
9019 macro_ptr
= init_str
.str
;
9021 decl_initializer(type
, NULL
, 0, 1, 1);
9022 /* prepare second initializer parsing */
9023 macro_ptr
= init_str
.str
;
9026 /* if still unknown size, error */
9027 size
= type_size(type
, &align
);
9029 error("unknown type size");
9031 /* take into account specified alignment if bigger */
9033 if (ad
->aligned
> align
)
9034 align
= ad
->aligned
;
9035 } else if (ad
->packed
) {
9038 if ((r
& VT_VALMASK
) == VT_LOCAL
) {
9040 if (do_bounds_check
&& (type
->t
& VT_ARRAY
))
9042 loc
= (loc
- size
) & -align
;
9044 /* handles bounds */
9045 /* XXX: currently, since we do only one pass, we cannot track
9046 '&' operators, so we add only arrays */
9047 if (do_bounds_check
&& (type
->t
& VT_ARRAY
)) {
9048 unsigned long *bounds_ptr
;
9049 /* add padding between regions */
9051 /* then add local bound info */
9052 bounds_ptr
= section_ptr_add(lbounds_section
, 2 * sizeof(unsigned long));
9053 bounds_ptr
[0] = addr
;
9054 bounds_ptr
[1] = size
;
9057 /* local variable */
9058 sym_push(v
, type
, r
, addr
);
9060 /* push local reference */
9061 vset(type
, r
, addr
);
9067 if (v
&& scope
== VT_CONST
) {
9068 /* see if the symbol was already defined */
9071 if (!is_compatible_types(&sym
->type
, type
))
9072 error("incompatible types for redefinition of '%s'",
9073 get_tok_str(v
, NULL
));
9074 if (sym
->type
.t
& VT_EXTERN
) {
9075 /* if the variable is extern, it was not allocated */
9076 sym
->type
.t
&= ~VT_EXTERN
;
9077 /* set array size if it was ommited in extern
9079 if ((sym
->type
.t
& VT_ARRAY
) &&
9080 sym
->type
.ref
->c
< 0 &&
9082 sym
->type
.ref
->c
= type
->ref
->c
;
9084 /* we accept several definitions of the same
9085 global variable. this is tricky, because we
9086 must play with the SHN_COMMON type of the symbol */
9087 /* XXX: should check if the variable was already
9088 initialized. It is incorrect to initialized it
9090 /* no init data, we won't add more to the symbol */
9097 /* allocate symbol in corresponding section */
9102 else if (tcc_state
->nocommon
)
9106 data_offset
= sec
->data_offset
;
9107 data_offset
= (data_offset
+ align
- 1) & -align
;
9109 /* very important to increment global pointer at this time
9110 because initializers themselves can create new initializers */
9111 data_offset
+= size
;
9112 /* add padding if bound check */
9113 if (do_bounds_check
)
9115 sec
->data_offset
= data_offset
;
9116 /* allocate section space to put the data */
9117 if (sec
->sh_type
!= SHT_NOBITS
&&
9118 data_offset
> sec
->data_allocated
)
9119 section_realloc(sec
, data_offset
);
9120 /* align section if needed */
9121 if (align
> sec
->sh_addralign
)
9122 sec
->sh_addralign
= align
;
9124 addr
= 0; /* avoid warning */
9128 if (scope
!= VT_CONST
|| !sym
) {
9129 sym
= sym_push(v
, type
, r
| VT_SYM
, 0);
9131 /* update symbol definition */
9133 put_extern_sym(sym
, sec
, addr
, size
);
9136 /* put a common area */
9137 put_extern_sym(sym
, NULL
, align
, size
);
9138 /* XXX: find a nicer way */
9139 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
9140 esym
->st_shndx
= SHN_COMMON
;
9145 /* push global reference */
9146 sym
= get_sym_ref(type
, sec
, addr
, size
);
9148 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
9152 /* handles bounds now because the symbol must be defined
9153 before for the relocation */
9154 if (do_bounds_check
) {
9155 unsigned long *bounds_ptr
;
9157 greloc(bounds_section
, sym
, bounds_section
->data_offset
, R_DATA_32
);
9158 /* then add global bound info */
9159 bounds_ptr
= section_ptr_add(bounds_section
, 2 * sizeof(long));
9160 bounds_ptr
[0] = 0; /* relocated */
9161 bounds_ptr
[1] = size
;
9165 decl_initializer(type
, sec
, addr
, 1, 0);
9166 /* restore parse state if needed */
9168 tok_str_free(init_str
.str
);
9169 restore_parse_state(&saved_parse_state
);
9175 void put_func_debug(Sym
*sym
)
9180 /* XXX: we put here a dummy type */
9181 snprintf(buf
, sizeof(buf
), "%s:%c1",
9182 funcname
, sym
->type
.t
& VT_STATIC
? 'f' : 'F');
9183 put_stabs_r(buf
, N_FUN
, 0, file
->line_num
, 0,
9184 cur_text_section
, sym
->c
);
9185 /* //gr gdb wants a line at the function */
9186 put_stabn(N_SLINE
, 0, file
->line_num
, 0);
9191 /* parse an old style function declaration list */
9192 /* XXX: check multiple parameter */
9193 static void func_decl_list(Sym
*func_sym
)
9200 /* parse each declaration */
9201 while (tok
!= '{' && tok
!= ';' && tok
!= ',' && tok
!= TOK_EOF
) {
9202 if (!parse_btype(&btype
, &ad
))
9203 expect("declaration list");
9204 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
9205 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
9207 /* we accept no variable after */
9211 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
9212 /* find parameter in function parameter list */
9215 if ((s
->v
& ~SYM_FIELD
) == v
)
9219 error("declaration for parameter '%s' but no such parameter",
9220 get_tok_str(v
, NULL
));
9222 /* check that no storage specifier except 'register' was given */
9223 if (type
.t
& VT_STORAGE
)
9224 error("storage class specified for '%s'", get_tok_str(v
, NULL
));
9225 convert_parameter_type(&type
);
9226 /* we can add the type (NOTE: it could be local to the function) */
9228 /* accept other parameters */
9239 /* parse a function defined by symbol 'sym' and generate its code in
9240 'cur_text_section' */
9241 static void gen_function(Sym
*sym
)
9243 int saved_nocode_wanted
= nocode_wanted
;
9245 ind
= cur_text_section
->data_offset
;
9246 /* NOTE: we patch the symbol size later */
9247 put_extern_sym(sym
, cur_text_section
, ind
, 0);
9248 funcname
= get_tok_str(sym
->v
, NULL
);
9250 /* put debug symbol */
9252 put_func_debug(sym
);
9253 /* push a dummy symbol to enable local sym storage */
9254 sym_push2(&local_stack
, SYM_FIELD
, 0, 0);
9255 gfunc_prolog(&sym
->type
);
9257 block(NULL
, NULL
, NULL
, NULL
, 0, 0);
9260 cur_text_section
->data_offset
= ind
;
9261 label_pop(&global_label_stack
, NULL
);
9262 sym_pop(&local_stack
, NULL
); /* reset local stack */
9263 /* end of function */
9264 /* patch symbol size */
9265 ((Elf32_Sym
*)symtab_section
->data
)[sym
->c
].st_size
=
9268 put_stabn(N_FUN
, 0, 0, ind
- func_ind
);
9270 /* It's better to crash than to generate wrong code */
9271 cur_text_section
= NULL
;
9272 funcname
= ""; /* for safety */
9273 func_vt
.t
= VT_VOID
; /* for safety */
9274 ind
= 0; /* for safety */
9275 nocode_wanted
= saved_nocode_wanted
;
9278 static void gen_inline_functions(void)
9282 int *str
, inline_generated
;
9284 /* iterate while inline function are referenced */
9286 inline_generated
= 0;
9287 for(sym
= global_stack
; sym
!= NULL
; sym
= sym
->prev
) {
9289 if (((type
->t
& VT_BTYPE
) == VT_FUNC
) &&
9290 (type
->t
& (VT_STATIC
| VT_INLINE
)) ==
9291 (VT_STATIC
| VT_INLINE
) &&
9293 /* the function was used: generate its code and
9294 convert it to a normal function */
9295 str
= INLINE_DEF(sym
->r
);
9296 sym
->r
= VT_SYM
| VT_CONST
;
9297 sym
->type
.t
&= ~VT_INLINE
;
9301 cur_text_section
= text_section
;
9303 macro_ptr
= NULL
; /* fail safe */
9306 inline_generated
= 1;
9309 if (!inline_generated
)
9313 /* free all remaining inline function tokens */
9314 for(sym
= global_stack
; sym
!= NULL
; sym
= sym
->prev
) {
9316 if (((type
->t
& VT_BTYPE
) == VT_FUNC
) &&
9317 (type
->t
& (VT_STATIC
| VT_INLINE
)) ==
9318 (VT_STATIC
| VT_INLINE
)) {
9319 //gr printf("sym %d %s\n", sym->r, get_tok_str(sym->v, NULL));
9320 if (sym
->r
== (VT_SYM
| VT_CONST
)) //gr beware!
9322 str
= INLINE_DEF(sym
->r
);
9324 sym
->r
= 0; /* fail safe */
9329 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
9330 static void decl(int l
)
9338 if (!parse_btype(&btype
, &ad
)) {
9339 /* skip redundant ';' */
9340 /* XXX: find more elegant solution */
9345 if (l
== VT_CONST
&&
9346 (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
)) {
9347 /* global asm block */
9351 /* special test for old K&R protos without explicit int
9352 type. Only accepted when defining global data */
9353 if (l
== VT_LOCAL
|| tok
< TOK_DEFINE
)
9357 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
9358 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
9360 /* we accept no variable after */
9364 while (1) { /* iterate thru each declaration */
9366 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
9370 type_to_str(buf
, sizeof(buf
), t
, get_tok_str(v
, NULL
));
9371 printf("type = '%s'\n", buf
);
9374 if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
9375 /* if old style function prototype, we accept a
9378 if (sym
->c
== FUNC_OLD
)
9379 func_decl_list(sym
);
9384 error("cannot use local functions");
9385 if ((type
.t
& VT_BTYPE
) != VT_FUNC
)
9386 expect("function definition");
9388 /* reject abstract declarators in function definition */
9390 while ((sym
= sym
->next
) != NULL
)
9391 if (!(sym
->v
& ~SYM_FIELD
))
9392 expect("identifier");
9394 /* XXX: cannot do better now: convert extern line to static inline */
9395 if ((type
.t
& (VT_EXTERN
| VT_INLINE
)) == (VT_EXTERN
| VT_INLINE
))
9396 type
.t
= (type
.t
& ~VT_EXTERN
) | VT_STATIC
;
9400 if ((sym
->type
.t
& VT_BTYPE
) != VT_FUNC
)
9402 /* specific case: if not func_call defined, we put
9403 the one of the prototype */
9404 /* XXX: should have default value */
9405 r
= sym
->type
.ref
->r
;
9406 if (FUNC_CALL(r
) != FUNC_CDECL
9407 && FUNC_CALL(type
.ref
->r
) == FUNC_CDECL
)
9408 FUNC_CALL(type
.ref
->r
) = FUNC_CALL(r
);
9410 FUNC_EXPORT(type
.ref
->r
) = 1;
9412 if (!is_compatible_types(&sym
->type
, &type
)) {
9414 error("incompatible types for redefinition of '%s'",
9415 get_tok_str(v
, NULL
));
9417 /* if symbol is already defined, then put complete type */
9420 /* put function symbol */
9421 sym
= global_identifier_push(v
, type
.t
, 0);
9422 sym
->type
.ref
= type
.ref
;
9425 /* static inline functions are just recorded as a kind
9426 of macro. Their code will be emitted at the end of
9427 the compilation unit only if they are used */
9428 if ((type
.t
& (VT_INLINE
| VT_STATIC
)) ==
9429 (VT_INLINE
| VT_STATIC
)) {
9430 TokenString func_str
;
9433 tok_str_new(&func_str
);
9439 error("unexpected end of file");
9440 tok_str_add_tok(&func_str
);
9445 } else if (t
== '}') {
9447 if (block_level
== 0)
9451 tok_str_add(&func_str
, -1);
9452 tok_str_add(&func_str
, 0);
9453 INLINE_DEF(sym
->r
) = func_str
.str
;
9455 /* compute text section */
9456 cur_text_section
= ad
.section
;
9457 if (!cur_text_section
)
9458 cur_text_section
= text_section
;
9459 sym
->r
= VT_SYM
| VT_CONST
;
9464 if (btype
.t
& VT_TYPEDEF
) {
9465 /* save typedefed type */
9466 /* XXX: test storage specifiers ? */
9467 sym
= sym_push(v
, &type
, 0, 0);
9468 sym
->type
.t
|= VT_TYPEDEF
;
9469 } else if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
9470 /* external function definition */
9471 /* specific case for func_call attribute */
9473 type
.ref
->r
= ad
.func_attr
;
9474 external_sym(v
, &type
, 0);
9476 /* not lvalue if array */
9478 if (!(type
.t
& VT_ARRAY
))
9479 r
|= lvalue_type(type
.t
);
9480 has_init
= (tok
== '=');
9481 if ((btype
.t
& VT_EXTERN
) ||
9482 ((type
.t
& VT_ARRAY
) && (type
.t
& VT_STATIC
) &&
9483 !has_init
&& l
== VT_CONST
&& type
.ref
->c
< 0)) {
9484 /* external variable */
9485 /* NOTE: as GCC, uninitialized global static
9486 arrays of null size are considered as
9488 external_sym(v
, &type
, r
);
9490 type
.t
|= (btype
.t
& VT_STATIC
); /* Retain "static". */
9491 if (type
.t
& VT_STATIC
)
9497 decl_initializer_alloc(&type
, &ad
, r
,
9511 /* better than nothing, but needs extension to handle '-E' option
9513 static void preprocess_init(TCCState
*s1
)
9515 s1
->include_stack_ptr
= s1
->include_stack
;
9516 /* XXX: move that before to avoid having to initialize
9517 file->ifdef_stack_ptr ? */
9518 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
9519 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
9521 /* XXX: not ANSI compliant: bound checking says error */
9523 s1
->pack_stack
[0] = 0;
9524 s1
->pack_stack_ptr
= s1
->pack_stack
;
9527 /* compile the C file opened in 'file'. Return non zero if errors. */
9528 static int tcc_compile(TCCState
*s1
)
9532 volatile int section_sym
;
9535 printf("%s: **** new file\n", file
->filename
);
9537 preprocess_init(s1
);
9539 cur_text_section
= NULL
;
9541 anon_sym
= SYM_FIRST_ANOM
;
9543 /* file info: full path + filename */
9544 section_sym
= 0; /* avoid warning */
9546 section_sym
= put_elf_sym(symtab_section
, 0, 0,
9547 ELF32_ST_INFO(STB_LOCAL
, STT_SECTION
), 0,
9548 text_section
->sh_num
, NULL
);
9549 getcwd(buf
, sizeof(buf
));
9551 normalize_slashes(buf
);
9553 pstrcat(buf
, sizeof(buf
), "/");
9554 put_stabs_r(buf
, N_SO
, 0, 0,
9555 text_section
->data_offset
, text_section
, section_sym
);
9556 put_stabs_r(file
->filename
, N_SO
, 0, 0,
9557 text_section
->data_offset
, text_section
, section_sym
);
9559 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
9560 symbols can be safely used */
9561 put_elf_sym(symtab_section
, 0, 0,
9562 ELF32_ST_INFO(STB_LOCAL
, STT_FILE
), 0,
9563 SHN_ABS
, file
->filename
);
9565 /* define some often used types */
9566 int_type
.t
= VT_INT
;
9568 char_pointer_type
.t
= VT_BYTE
;
9569 mk_pointer(&char_pointer_type
);
9571 func_old_type
.t
= VT_FUNC
;
9572 func_old_type
.ref
= sym_push(SYM_FIELD
, &int_type
, FUNC_CDECL
, FUNC_OLD
);
9574 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
9575 float_type
.t
= VT_FLOAT
;
9576 double_type
.t
= VT_DOUBLE
;
9578 func_float_type
.t
= VT_FUNC
;
9579 func_float_type
.ref
= sym_push(SYM_FIELD
, &float_type
, FUNC_CDECL
, FUNC_OLD
);
9580 func_double_type
.t
= VT_FUNC
;
9581 func_double_type
.ref
= sym_push(SYM_FIELD
, &double_type
, FUNC_CDECL
, FUNC_OLD
);
9585 /* define 'void *alloca(unsigned int)' builtin function */
9590 sym
= sym_push(p
, mk_pointer(VT_VOID
), FUNC_CDECL
, FUNC_NEW
);
9591 s1
= sym_push(SYM_FIELD
, VT_UNSIGNED
| VT_INT
, 0, 0);
9594 sym_push(TOK_alloca
, VT_FUNC
| (p
<< VT_STRUCT_SHIFT
), VT_CONST
, 0);
9598 define_start
= define_stack
;
9601 if (setjmp(s1
->error_jmp_buf
) == 0) {
9603 s1
->error_set_jmp_enabled
= 1;
9605 ch
= file
->buf_ptr
[0];
9606 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
9607 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
;
9611 expect("declaration");
9613 /* end of translation unit info */
9615 put_stabs_r(NULL
, N_SO
, 0, 0,
9616 text_section
->data_offset
, text_section
, section_sym
);
9619 s1
->error_set_jmp_enabled
= 0;
9621 /* reset define stack, but leave -Dsymbols (may be incorrect if
9622 they are undefined) */
9623 free_defines(define_start
);
9625 gen_inline_functions();
9627 sym_pop(&global_stack
, NULL
);
9628 sym_pop(&local_stack
, NULL
);
9630 return s1
->nb_errors
!= 0 ? -1 : 0;
9633 /* Preprocess the current file */
9634 /* XXX: add line and file infos, add options to preserve spaces */
9635 static int tcc_preprocess(TCCState
*s1
)
9640 preprocess_init(s1
);
9642 define_start
= define_stack
;
9644 ch
= file
->buf_ptr
[0];
9645 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
9646 parse_flags
= PARSE_FLAG_ASM_COMMENTS
| PARSE_FLAG_PREPROCESS
|
9647 PARSE_FLAG_LINEFEED
;
9651 if (tok
== TOK_EOF
) {
9653 } else if (tok
== TOK_LINEFEED
) {
9657 fputc(' ', s1
->outfile
);
9660 fputs(get_tok_str(tok
, &tokc
), s1
->outfile
);
9663 free_defines(define_start
);
9668 int tcc_compile_string(TCCState
*s
, const char *str
)
9670 BufferedFile bf1
, *bf
= &bf1
;
9674 /* init file structure */
9676 /* XXX: avoid copying */
9678 buf
= tcc_malloc(len
+ 1);
9681 memcpy(buf
, str
, len
);
9684 bf
->buf_end
= buf
+ len
;
9685 pstrcpy(bf
->filename
, sizeof(bf
->filename
), "<string>");
9688 ret
= tcc_compile(s
);
9692 /* currently, no need to close */
9697 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
9698 void tcc_define_symbol(TCCState
*s1
, const char *sym
, const char *value
)
9700 BufferedFile bf1
, *bf
= &bf1
;
9702 pstrcpy(bf
->buffer
, IO_BUF_SIZE
, sym
);
9703 pstrcat(bf
->buffer
, IO_BUF_SIZE
, " ");
9707 pstrcat(bf
->buffer
, IO_BUF_SIZE
, value
);
9709 /* init file structure */
9711 bf
->buf_ptr
= bf
->buffer
;
9712 bf
->buf_end
= bf
->buffer
+ strlen(bf
->buffer
);
9713 *bf
->buf_end
= CH_EOB
;
9714 bf
->filename
[0] = '\0';
9718 s1
->include_stack_ptr
= s1
->include_stack
;
9720 /* parse with define parser */
9721 ch
= file
->buf_ptr
[0];
9727 /* undefine a preprocessor symbol */
9728 void tcc_undefine_symbol(TCCState
*s1
, const char *sym
)
9732 ts
= tok_alloc(sym
, strlen(sym
));
9733 s
= define_find(ts
->tok
);
9734 /* undefine symbol by putting an invalid name */
9739 #ifdef CONFIG_TCC_ASM
9741 #ifdef TCC_TARGET_I386
9742 #include "i386-asm.c"
9747 static void asm_instr(void)
9749 error("inline asm() not supported");
9751 static void asm_global_instr(void)
9753 error("inline asm() not supported");
9759 #ifdef TCC_TARGET_COFF
9760 #include "tcccoff.c"
9763 #ifdef TCC_TARGET_PE
9767 /* print the position in the source file of PC value 'pc' by reading
9768 the stabs debug information */
9769 static void rt_printline(unsigned long wanted_pc
)
9771 Stab_Sym
*sym
, *sym_end
;
9772 char func_name
[128], last_func_name
[128];
9773 unsigned long func_addr
, last_pc
, pc
;
9774 const char *incl_files
[INCLUDE_STACK_SIZE
];
9775 int incl_index
, len
, last_line_num
, i
;
9776 const char *str
, *p
;
9778 fprintf(stderr
, "0x%08lx:", wanted_pc
);
9780 func_name
[0] = '\0';
9783 last_func_name
[0] = '\0';
9784 last_pc
= 0xffffffff;
9786 sym
= (Stab_Sym
*)stab_section
->data
+ 1;
9787 sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
9788 while (sym
< sym_end
) {
9789 switch(sym
->n_type
) {
9790 /* function start or end */
9792 if (sym
->n_strx
== 0) {
9793 /* we test if between last line and end of function */
9794 pc
= sym
->n_value
+ func_addr
;
9795 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
9797 func_name
[0] = '\0';
9800 str
= stabstr_section
->data
+ sym
->n_strx
;
9801 p
= strchr(str
, ':');
9803 pstrcpy(func_name
, sizeof(func_name
), str
);
9806 if (len
> sizeof(func_name
) - 1)
9807 len
= sizeof(func_name
) - 1;
9808 memcpy(func_name
, str
, len
);
9809 func_name
[len
] = '\0';
9811 func_addr
= sym
->n_value
;
9814 /* line number info */
9816 pc
= sym
->n_value
+ func_addr
;
9817 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
9820 last_line_num
= sym
->n_desc
;
9822 strcpy(last_func_name
, func_name
);
9826 str
= stabstr_section
->data
+ sym
->n_strx
;
9828 if (incl_index
< INCLUDE_STACK_SIZE
) {
9829 incl_files
[incl_index
++] = str
;
9837 if (sym
->n_strx
== 0) {
9838 incl_index
= 0; /* end of translation unit */
9840 str
= stabstr_section
->data
+ sym
->n_strx
;
9841 /* do not add path */
9843 if (len
> 0 && str
[len
- 1] != '/')
9851 /* second pass: we try symtab symbols (no line number info) */
9854 Elf32_Sym
*sym
, *sym_end
;
9857 sym_end
= (Elf32_Sym
*)(symtab_section
->data
+ symtab_section
->data_offset
);
9858 for(sym
= (Elf32_Sym
*)symtab_section
->data
+ 1;
9861 type
= ELF32_ST_TYPE(sym
->st_info
);
9862 if (type
== STT_FUNC
) {
9863 if (wanted_pc
>= sym
->st_value
&&
9864 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
9865 pstrcpy(last_func_name
, sizeof(last_func_name
),
9866 strtab_section
->data
+ sym
->st_name
);
9872 /* did not find any info: */
9873 fprintf(stderr
, " ???\n");
9876 if (last_func_name
[0] != '\0') {
9877 fprintf(stderr
, " %s()", last_func_name
);
9879 if (incl_index
> 0) {
9880 fprintf(stderr
, " (%s:%d",
9881 incl_files
[incl_index
- 1], last_line_num
);
9882 for(i
= incl_index
- 2; i
>= 0; i
--)
9883 fprintf(stderr
, ", included from %s", incl_files
[i
]);
9884 fprintf(stderr
, ")");
9886 fprintf(stderr
, "\n");
9889 #if !defined(_WIN32) && !defined(CONFIG_TCCBOOT)
9893 /* fix for glibc 2.1 */
9899 /* return the PC at frame level 'level'. Return non zero if not found */
9900 static int rt_get_caller_pc(unsigned long *paddr
,
9901 ucontext_t
*uc
, int level
)
9907 #if defined(__FreeBSD__)
9908 *paddr
= uc
->uc_mcontext
.mc_eip
;
9909 #elif defined(__dietlibc__)
9910 *paddr
= uc
->uc_mcontext
.eip
;
9912 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
9916 #if defined(__FreeBSD__)
9917 fp
= uc
->uc_mcontext
.mc_ebp
;
9918 #elif defined(__dietlibc__)
9919 fp
= uc
->uc_mcontext
.ebp
;
9921 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
9923 for(i
=1;i
<level
;i
++) {
9924 /* XXX: check address validity with program info */
9925 if (fp
<= 0x1000 || fp
>= 0xc0000000)
9927 fp
= ((unsigned long *)fp
)[0];
9929 *paddr
= ((unsigned long *)fp
)[1];
9935 #warning add arch specific rt_get_caller_pc()
9937 static int rt_get_caller_pc(unsigned long *paddr
,
9938 ucontext_t
*uc
, int level
)
9944 /* emit a run time error at position 'pc' */
9945 void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
9952 fprintf(stderr
, "Runtime error: ");
9953 vfprintf(stderr
, fmt
, ap
);
9954 fprintf(stderr
, "\n");
9955 for(i
=0;i
<num_callers
;i
++) {
9956 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
9959 fprintf(stderr
, "at ");
9961 fprintf(stderr
, "by ");
9968 /* signal handler for fatal errors */
9969 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
9971 ucontext_t
*uc
= puc
;
9975 switch(siginf
->si_code
) {
9978 rt_error(uc
, "division by zero");
9981 rt_error(uc
, "floating point exception");
9987 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
9988 rt_error(uc
, *rt_bound_error_msg
);
9990 rt_error(uc
, "dereferencing invalid pointer");
9993 rt_error(uc
, "illegal instruction");
9996 rt_error(uc
, "abort() called");
9999 rt_error(uc
, "caught signal %d", signum
);
10006 /* do all relocations (needed before using tcc_get_symbol()) */
10007 int tcc_relocate(TCCState
*s1
)
10014 #ifdef TCC_TARGET_PE
10015 pe_add_runtime(s1
);
10017 tcc_add_runtime(s1
);
10020 relocate_common_syms();
10022 tcc_add_linker_symbols(s1
);
10023 #ifndef TCC_TARGET_PE
10024 build_got_entries(s1
);
10026 /* compute relocation address : section are relocated in place. We
10027 also alloc the bss space */
10028 for(i
= 1; i
< s1
->nb_sections
; i
++) {
10029 s
= s1
->sections
[i
];
10030 if (s
->sh_flags
& SHF_ALLOC
) {
10031 if (s
->sh_type
== SHT_NOBITS
)
10032 s
->data
= tcc_mallocz(s
->data_offset
);
10033 s
->sh_addr
= (unsigned long)s
->data
;
10037 relocate_syms(s1
, 1);
10039 if (s1
->nb_errors
!= 0)
10042 /* relocate each section */
10043 for(i
= 1; i
< s1
->nb_sections
; i
++) {
10044 s
= s1
->sections
[i
];
10046 relocate_section(s1
, s
);
10049 /* mark executable sections as executable in memory */
10050 for(i
= 1; i
< s1
->nb_sections
; i
++) {
10051 s
= s1
->sections
[i
];
10052 if ((s
->sh_flags
& (SHF_ALLOC
| SHF_EXECINSTR
)) ==
10053 (SHF_ALLOC
| SHF_EXECINSTR
))
10054 set_pages_executable(s
->data
, s
->data_offset
);
10059 /* launch the compiled program with the given arguments */
10060 int tcc_run(TCCState
*s1
, int argc
, char **argv
)
10062 int (*prog_main
)(int, char **);
10064 if (tcc_relocate(s1
) < 0)
10067 prog_main
= tcc_get_symbol_err(s1
, "main");
10070 #if defined(_WIN32) || defined(CONFIG_TCCBOOT)
10071 error("debug mode currently not available for Windows");
10073 struct sigaction sigact
;
10074 /* install TCC signal handlers to print debug info on fatal
10076 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
10077 sigact
.sa_sigaction
= sig_error
;
10078 sigemptyset(&sigact
.sa_mask
);
10079 sigaction(SIGFPE
, &sigact
, NULL
);
10080 sigaction(SIGILL
, &sigact
, NULL
);
10081 sigaction(SIGSEGV
, &sigact
, NULL
);
10082 sigaction(SIGBUS
, &sigact
, NULL
);
10083 sigaction(SIGABRT
, &sigact
, NULL
);
10087 #ifdef CONFIG_TCC_BCHECK
10088 if (do_bounds_check
) {
10089 void (*bound_init
)(void);
10091 /* set error function */
10092 rt_bound_error_msg
= (void *)tcc_get_symbol_err(s1
,
10093 "__bound_error_msg");
10095 /* XXX: use .init section so that it also work in binary ? */
10096 bound_init
= (void *)tcc_get_symbol_err(s1
, "__bound_init");
10100 return (*prog_main
)(argc
, argv
);
10103 void tcc_memstats(void)
10106 printf("memory in use: %d\n", mem_cur_size
);
10110 static void tcc_cleanup(void)
10114 if (NULL
== tcc_state
)
10118 /* free -D defines */
10119 free_defines(NULL
);
10122 n
= tok_ident
- TOK_IDENT
;
10123 for(i
= 0; i
< n
; i
++)
10124 tcc_free(table_ident
[i
]);
10125 tcc_free(table_ident
);
10127 /* free sym_pools */
10128 dynarray_reset(&sym_pools
, &nb_sym_pools
);
10129 /* string buffer */
10130 cstr_free(&tokcstr
);
10131 /* reset symbol stack */
10132 sym_free_first
= NULL
;
10133 /* cleanup from error/setjmp */
10137 TCCState
*tcc_new(void)
10146 s
= tcc_mallocz(sizeof(TCCState
));
10150 s
->output_type
= TCC_OUTPUT_MEMORY
;
10152 /* init isid table */
10153 for(i
=CH_EOF
;i
<256;i
++)
10154 isidnum_table
[i
-CH_EOF
] = isid(i
) || isnum(i
);
10156 /* add all tokens */
10157 table_ident
= NULL
;
10158 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
10160 tok_ident
= TOK_IDENT
;
10169 ts
= tok_alloc(p
, r
- p
- 1);
10173 /* we add dummy defines for some special macros to speed up tests
10174 and to have working defined() */
10175 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
10176 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
10177 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
10178 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
10180 /* standard defines */
10181 tcc_define_symbol(s
, "__STDC__", NULL
);
10182 tcc_define_symbol(s
, "__STDC_VERSION__", "199901L");
10183 #if defined(TCC_TARGET_I386)
10184 tcc_define_symbol(s
, "__i386__", NULL
);
10186 #if defined(TCC_TARGET_ARM)
10187 tcc_define_symbol(s
, "__ARM_ARCH_4__", NULL
);
10188 tcc_define_symbol(s
, "__arm_elf__", NULL
);
10189 tcc_define_symbol(s
, "__arm_elf", NULL
);
10190 tcc_define_symbol(s
, "arm_elf", NULL
);
10191 tcc_define_symbol(s
, "__arm__", NULL
);
10192 tcc_define_symbol(s
, "__arm", NULL
);
10193 tcc_define_symbol(s
, "arm", NULL
);
10194 tcc_define_symbol(s
, "__APCS_32__", NULL
);
10196 #ifdef TCC_TARGET_PE
10197 tcc_define_symbol(s
, "_WIN32", NULL
);
10199 tcc_define_symbol(s
, "__unix__", NULL
);
10200 tcc_define_symbol(s
, "__unix", NULL
);
10201 #if defined(__linux)
10202 tcc_define_symbol(s
, "__linux__", NULL
);
10203 tcc_define_symbol(s
, "__linux", NULL
);
10206 /* tiny C specific defines */
10207 tcc_define_symbol(s
, "__TINYC__", NULL
);
10209 /* tiny C & gcc defines */
10210 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned int");
10211 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "int");
10212 #ifdef TCC_TARGET_PE
10213 tcc_define_symbol(s
, "__WCHAR_TYPE__", "unsigned short");
10215 tcc_define_symbol(s
, "__WCHAR_TYPE__", "int");
10218 #ifndef TCC_TARGET_PE
10219 /* default library paths */
10220 tcc_add_library_path(s
, CONFIG_SYSROOT
"/usr/local/lib");
10221 tcc_add_library_path(s
, CONFIG_SYSROOT
"/usr/lib");
10222 tcc_add_library_path(s
, CONFIG_SYSROOT
"/lib");
10225 /* no section zero */
10226 dynarray_add((void ***)&s
->sections
, &s
->nb_sections
, NULL
);
10228 /* create standard sections */
10229 text_section
= new_section(s
, ".text", SHT_PROGBITS
, SHF_ALLOC
| SHF_EXECINSTR
);
10230 data_section
= new_section(s
, ".data", SHT_PROGBITS
, SHF_ALLOC
| SHF_WRITE
);
10231 bss_section
= new_section(s
, ".bss", SHT_NOBITS
, SHF_ALLOC
| SHF_WRITE
);
10233 /* symbols are always generated for linking stage */
10234 symtab_section
= new_symtab(s
, ".symtab", SHT_SYMTAB
, 0,
10236 ".hashtab", SHF_PRIVATE
);
10237 strtab_section
= symtab_section
->link
;
10239 /* private symbol table for dynamic symbols */
10240 s
->dynsymtab_section
= new_symtab(s
, ".dynsymtab", SHT_SYMTAB
, SHF_PRIVATE
,
10242 ".dynhashtab", SHF_PRIVATE
);
10243 s
->alacarte_link
= 1;
10245 #ifdef CHAR_IS_UNSIGNED
10246 s
->char_is_unsigned
= 1;
10248 #if defined(TCC_TARGET_PE) && 0
10249 /* XXX: currently the PE linker is not ready to support that */
10250 s
->leading_underscore
= 1;
10255 void tcc_delete(TCCState
*s1
)
10261 /* free all sections */
10262 free_section(s1
->dynsymtab_section
);
10264 for(i
= 1; i
< s1
->nb_sections
; i
++)
10265 free_section(s1
->sections
[i
]);
10266 tcc_free(s1
->sections
);
10268 /* free any loaded DLLs */
10269 for ( i
= 0; i
< s1
->nb_loaded_dlls
; i
++)
10271 DLLReference
*ref
= s1
->loaded_dlls
[i
];
10273 dlclose(ref
->handle
);
10276 /* free loaded dlls array */
10277 dynarray_reset(&s1
->loaded_dlls
, &s1
->nb_loaded_dlls
);
10279 /* free library paths */
10280 dynarray_reset(&s1
->library_paths
, &s1
->nb_library_paths
);
10282 /* free include paths */
10283 dynarray_reset(&s1
->cached_includes
, &s1
->nb_cached_includes
);
10284 dynarray_reset(&s1
->include_paths
, &s1
->nb_include_paths
);
10285 dynarray_reset(&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
);
10290 int tcc_add_include_path(TCCState
*s1
, const char *pathname
)
10294 pathname1
= tcc_strdup(pathname
);
10295 dynarray_add((void ***)&s1
->include_paths
, &s1
->nb_include_paths
, pathname1
);
10299 int tcc_add_sysinclude_path(TCCState
*s1
, const char *pathname
)
10303 pathname1
= tcc_strdup(pathname
);
10304 dynarray_add((void ***)&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
, pathname1
);
10308 static int tcc_add_file_internal(TCCState
*s1
, const char *filename
, int flags
)
10313 BufferedFile
*saved_file
;
10315 /* find source file type with extension */
10316 ext
= tcc_fileextension(filename
);
10320 /* open the file */
10322 file
= tcc_open(s1
, filename
);
10324 if (flags
& AFF_PRINT_ERROR
) {
10325 error_noabort("file '%s' not found", filename
);
10331 if (flags
& AFF_PREPROCESS
) {
10332 ret
= tcc_preprocess(s1
);
10333 } else if (!ext
[0] || !strcmp(ext
, "c")) {
10334 /* C file assumed */
10335 ret
= tcc_compile(s1
);
10337 #ifdef CONFIG_TCC_ASM
10338 if (!strcmp(ext
, "S")) {
10339 /* preprocessed assembler */
10340 ret
= tcc_assemble(s1
, 1);
10341 } else if (!strcmp(ext
, "s")) {
10342 /* non preprocessed assembler */
10343 ret
= tcc_assemble(s1
, 0);
10346 #ifdef TCC_TARGET_PE
10347 if (!strcmp(ext
, "def")) {
10348 ret
= pe_load_def_file(s1
, file
->fd
);
10353 /* assume executable format: auto guess file type */
10354 ret
= read(fd
, &ehdr
, sizeof(ehdr
));
10355 lseek(fd
, 0, SEEK_SET
);
10357 error_noabort("could not read header");
10359 } else if (ret
!= sizeof(ehdr
)) {
10360 goto try_load_script
;
10363 if (ehdr
.e_ident
[0] == ELFMAG0
&&
10364 ehdr
.e_ident
[1] == ELFMAG1
&&
10365 ehdr
.e_ident
[2] == ELFMAG2
&&
10366 ehdr
.e_ident
[3] == ELFMAG3
) {
10367 file
->line_num
= 0; /* do not display line number if error */
10368 if (ehdr
.e_type
== ET_REL
) {
10369 ret
= tcc_load_object_file(s1
, fd
, 0);
10370 } else if (ehdr
.e_type
== ET_DYN
) {
10371 if (s1
->output_type
== TCC_OUTPUT_MEMORY
) {
10372 #ifdef TCC_TARGET_PE
10376 h
= dlopen(filename
, RTLD_GLOBAL
| RTLD_LAZY
);
10383 ret
= tcc_load_dll(s1
, fd
, filename
,
10384 (flags
& AFF_REFERENCED_DLL
) != 0);
10387 error_noabort("unrecognized ELF file");
10390 } else if (memcmp((char *)&ehdr
, ARMAG
, 8) == 0) {
10391 file
->line_num
= 0; /* do not display line number if error */
10392 ret
= tcc_load_archive(s1
, fd
);
10394 #ifdef TCC_TARGET_COFF
10395 if (*(uint16_t *)(&ehdr
) == COFF_C67_MAGIC
) {
10396 ret
= tcc_load_coff(s1
, fd
);
10399 #ifdef TCC_TARGET_PE
10400 if (pe_test_res_file(&ehdr
, ret
)) {
10401 ret
= pe_load_res_file(s1
, fd
);
10405 /* as GNU ld, consider it is an ld script if not recognized */
10407 ret
= tcc_load_ldscript(s1
);
10409 error_noabort("unrecognized file type");
10424 int tcc_add_file(TCCState
*s
, const char *filename
)
10426 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
);
10429 int tcc_add_library_path(TCCState
*s
, const char *pathname
)
10433 pathname1
= tcc_strdup(pathname
);
10434 dynarray_add((void ***)&s
->library_paths
, &s
->nb_library_paths
, pathname1
);
10438 /* find and load a dll. Return non zero if not found */
10439 /* XXX: add '-rpath' option support ? */
10440 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
)
10445 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
10446 snprintf(buf
, sizeof(buf
), "%s/%s",
10447 s
->library_paths
[i
], filename
);
10448 if (tcc_add_file_internal(s
, buf
, flags
) == 0)
10454 /* the library name is the same as the argument of the '-l' option */
10455 int tcc_add_library(TCCState
*s
, const char *libraryname
)
10460 /* first we look for the dynamic library if not static linking */
10461 if (!s
->static_link
) {
10462 #ifdef TCC_TARGET_PE
10463 snprintf(buf
, sizeof(buf
), "%s.def", libraryname
);
10465 snprintf(buf
, sizeof(buf
), "lib%s.so", libraryname
);
10467 if (tcc_add_dll(s
, buf
, 0) == 0)
10471 /* then we look for the static library */
10472 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
10473 snprintf(buf
, sizeof(buf
), "%s/lib%s.a",
10474 s
->library_paths
[i
], libraryname
);
10475 if (tcc_add_file_internal(s
, buf
, 0) == 0)
10481 int tcc_add_symbol(TCCState
*s
, const char *name
, unsigned long val
)
10483 add_elf_sym(symtab_section
, val
, 0,
10484 ELF32_ST_INFO(STB_GLOBAL
, STT_NOTYPE
), 0,
10489 int tcc_set_output_type(TCCState
*s
, int output_type
)
10493 s
->output_type
= output_type
;
10495 if (!s
->nostdinc
) {
10496 /* default include paths */
10497 /* XXX: reverse order needed if -isystem support */
10498 #ifndef TCC_TARGET_PE
10499 tcc_add_sysinclude_path(s
, CONFIG_SYSROOT
"/usr/local/include");
10500 tcc_add_sysinclude_path(s
, CONFIG_SYSROOT
"/usr/include");
10502 snprintf(buf
, sizeof(buf
), "%s/include", tcc_lib_path
);
10503 tcc_add_sysinclude_path(s
, buf
);
10504 #ifdef TCC_TARGET_PE
10505 snprintf(buf
, sizeof(buf
), "%s/include/winapi", tcc_lib_path
);
10506 tcc_add_sysinclude_path(s
, buf
);
10510 /* if bound checking, then add corresponding sections */
10511 #ifdef CONFIG_TCC_BCHECK
10512 if (do_bounds_check
) {
10513 /* define symbol */
10514 tcc_define_symbol(s
, "__BOUNDS_CHECKING_ON", NULL
);
10515 /* create bounds sections */
10516 bounds_section
= new_section(s
, ".bounds",
10517 SHT_PROGBITS
, SHF_ALLOC
);
10518 lbounds_section
= new_section(s
, ".lbounds",
10519 SHT_PROGBITS
, SHF_ALLOC
);
10523 if (s
->char_is_unsigned
) {
10524 tcc_define_symbol(s
, "__CHAR_UNSIGNED__", NULL
);
10527 /* add debug sections */
10530 stab_section
= new_section(s
, ".stab", SHT_PROGBITS
, 0);
10531 stab_section
->sh_entsize
= sizeof(Stab_Sym
);
10532 stabstr_section
= new_section(s
, ".stabstr", SHT_STRTAB
, 0);
10533 put_elf_str(stabstr_section
, "");
10534 stab_section
->link
= stabstr_section
;
10535 /* put first entry */
10536 put_stabs("", 0, 0, 0, 0);
10539 /* add libc crt1/crti objects */
10540 #ifndef TCC_TARGET_PE
10541 if ((output_type
== TCC_OUTPUT_EXE
|| output_type
== TCC_OUTPUT_DLL
) &&
10543 if (output_type
!= TCC_OUTPUT_DLL
)
10544 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crt1.o");
10545 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crti.o");
10549 #ifdef TCC_TARGET_PE
10550 snprintf(buf
, sizeof(buf
), "%s/lib", tcc_lib_path
);
10551 tcc_add_library_path(s
, buf
);
10557 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
10558 #define FD_INVERT 0x0002 /* invert value before storing */
10560 typedef struct FlagDef
{
10566 static const FlagDef warning_defs
[] = {
10567 { offsetof(TCCState
, warn_unsupported
), 0, "unsupported" },
10568 { offsetof(TCCState
, warn_write_strings
), 0, "write-strings" },
10569 { offsetof(TCCState
, warn_error
), 0, "error" },
10570 { offsetof(TCCState
, warn_implicit_function_declaration
), WD_ALL
,
10571 "implicit-function-declaration" },
10574 static int set_flag(TCCState
*s
, const FlagDef
*flags
, int nb_flags
,
10575 const char *name
, int value
)
10582 if (r
[0] == 'n' && r
[1] == 'o' && r
[2] == '-') {
10586 for(i
= 0, p
= flags
; i
< nb_flags
; i
++, p
++) {
10587 if (!strcmp(r
, p
->name
))
10592 if (p
->flags
& FD_INVERT
)
10594 *(int *)((uint8_t *)s
+ p
->offset
) = value
;
10599 /* set/reset a warning */
10600 int tcc_set_warning(TCCState
*s
, const char *warning_name
, int value
)
10605 if (!strcmp(warning_name
, "all")) {
10606 for(i
= 0, p
= warning_defs
; i
< countof(warning_defs
); i
++, p
++) {
10607 if (p
->flags
& WD_ALL
)
10608 *(int *)((uint8_t *)s
+ p
->offset
) = 1;
10612 return set_flag(s
, warning_defs
, countof(warning_defs
),
10613 warning_name
, value
);
10617 static const FlagDef flag_defs
[] = {
10618 { offsetof(TCCState
, char_is_unsigned
), 0, "unsigned-char" },
10619 { offsetof(TCCState
, char_is_unsigned
), FD_INVERT
, "signed-char" },
10620 { offsetof(TCCState
, nocommon
), FD_INVERT
, "common" },
10621 { offsetof(TCCState
, leading_underscore
), 0, "leading-underscore" },
10624 /* set/reset a flag */
10625 int tcc_set_flag(TCCState
*s
, const char *flag_name
, int value
)
10627 return set_flag(s
, flag_defs
, countof(flag_defs
),
10631 #if !defined(LIBTCC)
10633 static int64_t getclock_us(void)
10638 return (tb
.time
* 1000LL + tb
.millitm
) * 1000LL;
10641 gettimeofday(&tv
, NULL
);
10642 return tv
.tv_sec
* 1000000LL + tv
.tv_usec
;
10648 printf("tcc version " TCC_VERSION
" - Tiny C Compiler - Copyright (C) 2001-2006 Fabrice Bellard\n"
10649 "usage: tcc [-v] [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"
10650 " [-Wwarn] [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-soname name]\n"
10651 " [-static] [infile1 infile2...] [-run infile args...]\n"
10653 "General options:\n"
10654 " -v display current version, increase verbosity\n"
10655 " -c compile only - generate an object file\n"
10656 " -o outfile set output filename\n"
10657 " -Bdir set tcc internal library path\n"
10658 " -bench output compilation statistics\n"
10659 " -run run compiled source\n"
10660 " -fflag set or reset (with 'no-' prefix) 'flag' (see man page)\n"
10661 " -Wwarning set or reset (with 'no-' prefix) 'warning' (see man page)\n"
10662 " -w disable all warnings\n"
10663 "Preprocessor options:\n"
10664 " -E preprocess only\n"
10665 " -Idir add include path 'dir'\n"
10666 " -Dsym[=val] define 'sym' with value 'val'\n"
10667 " -Usym undefine 'sym'\n"
10668 "Linker options:\n"
10669 " -Ldir add library path 'dir'\n"
10670 " -llib link with dynamic or static library 'lib'\n"
10671 " -shared generate a shared library\n"
10672 " -soname set name for shared library to be used at runtime\n"
10673 " -static static linking\n"
10674 " -rdynamic export all global symbols to dynamic linker\n"
10675 " -r generate (relocatable) object file\n"
10676 "Debugger options:\n"
10677 " -g generate runtime debug info\n"
10678 #ifdef CONFIG_TCC_BCHECK
10679 " -b compile with built-in memory and bounds checker (implies -g)\n"
10681 " -bt N show N callers in stack traces\n"
10685 #define TCC_OPTION_HAS_ARG 0x0001
10686 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
10688 typedef struct TCCOption
{
10717 TCC_OPTION_nostdinc
,
10718 TCC_OPTION_nostdlib
,
10719 TCC_OPTION_print_search_dirs
,
10720 TCC_OPTION_rdynamic
,
10728 static const TCCOption tcc_options
[] = {
10729 { "h", TCC_OPTION_HELP
, 0 },
10730 { "?", TCC_OPTION_HELP
, 0 },
10731 { "I", TCC_OPTION_I
, TCC_OPTION_HAS_ARG
},
10732 { "D", TCC_OPTION_D
, TCC_OPTION_HAS_ARG
},
10733 { "U", TCC_OPTION_U
, TCC_OPTION_HAS_ARG
},
10734 { "L", TCC_OPTION_L
, TCC_OPTION_HAS_ARG
},
10735 { "B", TCC_OPTION_B
, TCC_OPTION_HAS_ARG
},
10736 { "l", TCC_OPTION_l
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10737 { "bench", TCC_OPTION_bench
, 0 },
10738 { "bt", TCC_OPTION_bt
, TCC_OPTION_HAS_ARG
},
10739 #ifdef CONFIG_TCC_BCHECK
10740 { "b", TCC_OPTION_b
, 0 },
10742 { "g", TCC_OPTION_g
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10743 { "c", TCC_OPTION_c
, 0 },
10744 { "static", TCC_OPTION_static
, 0 },
10745 { "shared", TCC_OPTION_shared
, 0 },
10746 { "soname", TCC_OPTION_soname
, TCC_OPTION_HAS_ARG
},
10747 { "o", TCC_OPTION_o
, TCC_OPTION_HAS_ARG
},
10748 { "run", TCC_OPTION_run
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10749 { "rdynamic", TCC_OPTION_rdynamic
, 0 },
10750 { "r", TCC_OPTION_r
, 0 },
10751 { "Wl,", TCC_OPTION_Wl
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10752 { "W", TCC_OPTION_W
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10753 { "O", TCC_OPTION_O
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10754 { "m", TCC_OPTION_m
, TCC_OPTION_HAS_ARG
},
10755 { "f", TCC_OPTION_f
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10756 { "nostdinc", TCC_OPTION_nostdinc
, 0 },
10757 { "nostdlib", TCC_OPTION_nostdlib
, 0 },
10758 { "print-search-dirs", TCC_OPTION_print_search_dirs
, 0 },
10759 { "v", TCC_OPTION_v
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10760 { "w", TCC_OPTION_w
, 0 },
10761 { "pipe", TCC_OPTION_pipe
, 0},
10762 { "E", TCC_OPTION_E
, 0},
10766 /* convert 'str' into an array of space separated strings */
10767 static int expand_args(char ***pargv
, const char *str
)
10776 while (is_space(*str
))
10781 while (*str
!= '\0' && !is_space(*str
))
10784 arg
= tcc_malloc(len
+ 1);
10785 memcpy(arg
, s1
, len
);
10787 dynarray_add((void ***)&argv
, &argc
, arg
);
10793 static char **files
;
10794 static int nb_files
, nb_libraries
;
10795 static int multiple_files
;
10796 static int print_search_dirs
;
10797 static int output_type
;
10798 static int reloc_output
;
10799 static const char *outfile
;
10801 int parse_args(TCCState
*s
, int argc
, char **argv
)
10804 const TCCOption
*popt
;
10805 const char *optarg
, *p1
, *r1
;
10809 while (optind
< argc
) {
10811 r
= argv
[optind
++];
10812 if (r
[0] != '-' || r
[1] == '\0') {
10813 /* add a new file */
10814 dynarray_add((void ***)&files
, &nb_files
, r
);
10815 if (!multiple_files
) {
10817 /* argv[0] will be this file */
10821 /* find option in table (match only the first chars */
10822 popt
= tcc_options
;
10826 error("invalid option -- '%s'", r
);
10839 if (popt
->flags
& TCC_OPTION_HAS_ARG
) {
10840 if (*r1
!= '\0' || (popt
->flags
& TCC_OPTION_NOSEP
)) {
10843 if (optind
>= argc
)
10844 error("argument to '%s' is missing", r
);
10845 optarg
= argv
[optind
++];
10853 switch(popt
->index
) {
10854 case TCC_OPTION_HELP
:
10858 if (tcc_add_include_path(s
, optarg
) < 0)
10859 error("too many include paths");
10864 sym
= (char *)optarg
;
10865 value
= strchr(sym
, '=');
10870 tcc_define_symbol(s
, sym
, value
);
10874 tcc_undefine_symbol(s
, optarg
);
10877 tcc_add_library_path(s
, optarg
);
10880 /* set tcc utilities path (mainly for tcc development) */
10881 tcc_lib_path
= optarg
;
10884 dynarray_add((void ***)&files
, &nb_files
, r
);
10887 case TCC_OPTION_bench
:
10890 case TCC_OPTION_bt
:
10891 num_callers
= atoi(optarg
);
10893 #ifdef CONFIG_TCC_BCHECK
10895 do_bounds_check
= 1;
10903 multiple_files
= 1;
10904 output_type
= TCC_OUTPUT_OBJ
;
10906 case TCC_OPTION_static
:
10907 s
->static_link
= 1;
10909 case TCC_OPTION_shared
:
10910 output_type
= TCC_OUTPUT_DLL
;
10912 case TCC_OPTION_soname
:
10913 s
->soname
= optarg
;
10916 multiple_files
= 1;
10920 /* generate a .o merging several output files */
10922 output_type
= TCC_OUTPUT_OBJ
;
10924 case TCC_OPTION_nostdinc
:
10927 case TCC_OPTION_nostdlib
:
10930 case TCC_OPTION_print_search_dirs
:
10931 print_search_dirs
= 1;
10933 case TCC_OPTION_run
:
10937 argc1
= expand_args(&argv1
, optarg
);
10939 parse_args(s
, argc1
, argv1
);
10941 multiple_files
= 0;
10942 output_type
= TCC_OUTPUT_MEMORY
;
10947 if (0 == verbose
++)
10948 printf("tcc version %s\n", TCC_VERSION
);
10949 } while (*optarg
++ == 'v');
10952 if (tcc_set_flag(s
, optarg
, 1) < 0 && s
->warn_unsupported
)
10953 goto unsupported_option
;
10956 if (tcc_set_warning(s
, optarg
, 1) < 0 &&
10957 s
->warn_unsupported
)
10958 goto unsupported_option
;
10963 case TCC_OPTION_rdynamic
:
10966 case TCC_OPTION_Wl
:
10969 if (strstart(optarg
, "-Ttext,", &p
)) {
10970 s
->text_addr
= strtoul(p
, NULL
, 16);
10971 s
->has_text_addr
= 1;
10972 } else if (strstart(optarg
, "--oformat,", &p
)) {
10973 if (strstart(p
, "elf32-", NULL
)) {
10974 s
->output_format
= TCC_OUTPUT_FORMAT_ELF
;
10975 } else if (!strcmp(p
, "binary")) {
10976 s
->output_format
= TCC_OUTPUT_FORMAT_BINARY
;
10978 #ifdef TCC_TARGET_COFF
10979 if (!strcmp(p
, "coff")) {
10980 s
->output_format
= TCC_OUTPUT_FORMAT_COFF
;
10984 error("target %s not found", p
);
10987 error("unsupported linker option '%s'", optarg
);
10992 output_type
= TCC_OUTPUT_PREPROCESS
;
10995 if (s
->warn_unsupported
) {
10996 unsupported_option
:
10997 warning("unsupported option '%s'", r
);
11006 int main(int argc
, char **argv
)
11010 int nb_objfiles
, ret
, optind
;
11011 char objfilename
[1024];
11012 int64_t start_time
= 0;
11015 tcc_lib_path
= w32_tcc_lib_path();
11019 output_type
= TCC_OUTPUT_EXE
;
11021 multiple_files
= 1;
11026 print_search_dirs
= 0;
11029 optind
= parse_args(s
, argc
- 1, argv
+ 1);
11030 if (print_search_dirs
) {
11031 /* enough for Linux kernel */
11032 printf("install: %s/\n", tcc_lib_path
);
11035 if (optind
== 0 || nb_files
== 0) {
11036 if (optind
&& verbose
)
11042 nb_objfiles
= nb_files
- nb_libraries
;
11044 /* if outfile provided without other options, we output an
11046 if (outfile
&& output_type
== TCC_OUTPUT_MEMORY
)
11047 output_type
= TCC_OUTPUT_EXE
;
11049 /* check -c consistency : only single file handled. XXX: checks file type */
11050 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
11051 /* accepts only a single input file */
11052 if (nb_objfiles
!= 1)
11053 error("cannot specify multiple files with -c");
11054 if (nb_libraries
!= 0)
11055 error("cannot specify libraries with -c");
11059 if (output_type
== TCC_OUTPUT_PREPROCESS
) {
11061 s
->outfile
= stdout
;
11063 s
->outfile
= fopen(outfile
, "w");
11065 error("could not open '%s", outfile
);
11067 } else if (output_type
!= TCC_OUTPUT_MEMORY
) {
11069 /* compute default outfile name */
11072 strcmp(files
[0], "-") == 0 ? "a" : tcc_basename(files
[0]);
11073 pstrcpy(objfilename
, sizeof(objfilename
), name
);
11074 ext
= tcc_fileextension(objfilename
);
11075 #ifdef TCC_TARGET_PE
11076 if (output_type
== TCC_OUTPUT_DLL
)
11077 strcpy(ext
, ".dll");
11079 if (output_type
== TCC_OUTPUT_EXE
)
11080 strcpy(ext
, ".exe");
11083 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
&& *ext
)
11086 pstrcpy(objfilename
, sizeof(objfilename
), "a.out");
11087 outfile
= objfilename
;
11092 start_time
= getclock_us();
11095 tcc_set_output_type(s
, output_type
);
11097 /* compile or add each files or library */
11098 for(i
= 0; i
< nb_files
&& ret
== 0; i
++) {
11099 const char *filename
;
11101 filename
= files
[i
];
11102 if (output_type
== TCC_OUTPUT_PREPROCESS
) {
11103 if (tcc_add_file_internal(s
, filename
,
11104 AFF_PRINT_ERROR
| AFF_PREPROCESS
) < 0)
11106 } else if (filename
[0] == '-' && filename
[1]) {
11107 if (tcc_add_library(s
, filename
+ 2) < 0)
11108 error("cannot find %s", filename
);
11111 printf("-> %s\n", filename
);
11112 if (tcc_add_file(s
, filename
) < 0)
11117 /* free all files */
11125 total_time
= (double)(getclock_us() - start_time
) / 1000000.0;
11126 if (total_time
< 0.001)
11127 total_time
= 0.001;
11128 if (total_bytes
< 1)
11130 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
11131 tok_ident
- TOK_IDENT
, total_lines
, total_bytes
,
11132 total_time
, (int)(total_lines
/ total_time
),
11133 total_bytes
/ total_time
/ 1000000.0);
11136 if (s
->output_type
== TCC_OUTPUT_PREPROCESS
) {
11138 fclose(s
->outfile
);
11139 } else if (s
->output_type
== TCC_OUTPUT_MEMORY
) {
11140 ret
= tcc_run(s
, argc
- optind
, argv
+ optind
);
11142 ret
= tcc_output_file(s
, outfile
) ? 1 : 0;
11144 /* XXX: cannot do it with bound checking because of the malloc hooks */
11145 if (!do_bounds_check
)
11150 printf("memory: %d bytes, max = %d bytes\n", mem_cur_size
, mem_max_size
);