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 "/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
{
228 /* GNUC attribute definition */
229 typedef struct AttributeDef
{
233 int func_attr
; /* calling convention, exports, ... */
236 /* -------------------------------------------------- */
237 /* gr: wrappers for casting sym->r for other purposes */
245 #define FUNC_CALL(r) (((func_attr_t*)&(r))->func_call)
246 #define FUNC_EXPORT(r) (((func_attr_t*)&(r))->func_export)
247 #define FUNC_ARGS(r) (((func_attr_t*)&(r))->func_args)
248 #define INLINE_DEF(r) (*(int **)&(r))
249 /* -------------------------------------------------- */
251 #define SYM_STRUCT 0x40000000 /* struct/union/enum symbol space */
252 #define SYM_FIELD 0x20000000 /* struct/union field symbol space */
253 #define SYM_FIRST_ANOM 0x10000000 /* first anonymous sym */
255 /* stored in 'Sym.c' field */
256 #define FUNC_NEW 1 /* ansi function prototype */
257 #define FUNC_OLD 2 /* old function prototype */
258 #define FUNC_ELLIPSIS 3 /* ansi function prototype with ... */
260 /* stored in 'Sym.r' field */
261 #define FUNC_CDECL 0 /* standard c call */
262 #define FUNC_STDCALL 1 /* pascal c call */
263 #define FUNC_FASTCALL1 2 /* first param in %eax */
264 #define FUNC_FASTCALL2 3 /* first parameters in %eax, %edx */
265 #define FUNC_FASTCALL3 4 /* first parameter in %eax, %edx, %ecx */
266 #define FUNC_FASTCALLW 5 /* first parameter in %ecx, %edx */
268 /* field 'Sym.t' for macros */
269 #define MACRO_OBJ 0 /* object like macro */
270 #define MACRO_FUNC 1 /* function like macro */
272 /* field 'Sym.r' for C labels */
273 #define LABEL_DEFINED 0 /* label is defined */
274 #define LABEL_FORWARD 1 /* label is forward defined */
275 #define LABEL_DECLARED 2 /* label is declared but never used */
277 /* type_decl() types */
278 #define TYPE_ABSTRACT 1 /* type without variable */
279 #define TYPE_DIRECT 2 /* type with variable */
281 #define IO_BUF_SIZE 8192
283 typedef struct BufferedFile
{
287 int line_num
; /* current line number - here to simplify code */
288 int ifndef_macro
; /* #ifndef macro / #endif search */
289 int ifndef_macro_saved
; /* saved ifndef_macro */
290 int *ifdef_stack_ptr
; /* ifdef_stack value at the start of the file */
291 char inc_type
; /* type of include */
292 char inc_filename
[512]; /* filename specified by the user */
293 char filename
[1024]; /* current filename - here to simplify code */
294 unsigned char buffer
[IO_BUF_SIZE
+ 1]; /* extra size for CH_EOB char */
297 #define CH_EOB '\\' /* end of buffer or '\0' char in file */
298 #define CH_EOF (-1) /* end of file */
300 /* parsing state (used to save parser state to reparse part of the
301 source several times) */
302 typedef struct ParseState
{
309 /* used to record tokens */
310 typedef struct TokenString
{
317 /* include file cache, used to find files faster and also to eliminate
318 inclusion if the include file is protected by #ifndef ... #endif */
319 typedef struct CachedInclude
{
321 int hash_next
; /* -1 if none */
322 char type
; /* '"' or '>' to give include type */
323 char filename
[1]; /* path specified in #include */
326 #define CACHED_INCLUDES_HASH_SIZE 512
329 static struct BufferedFile
*file
;
332 static CString tokcstr
; /* current parsed string, if any */
333 /* additional informations about token */
334 static int tok_flags
;
335 #define TOK_FLAG_BOL 0x0001 /* beginning of line before */
336 #define TOK_FLAG_BOF 0x0002 /* beginning of file before */
337 #define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */
338 #define TOK_FLAG_EOF 0x0008 /* end of file */
340 static int *macro_ptr
, *macro_ptr_allocated
;
341 static int *unget_saved_macro_ptr
;
342 static int unget_saved_buffer
[TOK_MAX_SIZE
+ 1];
343 static int unget_buffer_enabled
;
344 static int parse_flags
;
345 #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
346 #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
347 #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
348 token. line feed is also
350 #define PARSE_FLAG_ASM_COMMENTS 0x0008 /* '#' can be used for line comment */
352 static Section
*text_section
, *data_section
, *bss_section
; /* predefined sections */
353 static Section
*cur_text_section
; /* current section where function code is
355 #ifdef CONFIG_TCC_ASM
356 static Section
*last_text_section
; /* to handle .previous asm directive */
358 /* bound check related sections */
359 static Section
*bounds_section
; /* contains global data bound description */
360 static Section
*lbounds_section
; /* contains local data bound description */
361 /* symbol sections */
362 static Section
*symtab_section
, *strtab_section
;
365 static Section
*stab_section
, *stabstr_section
;
367 /* loc : local variable index
368 ind : output code index
370 anon_sym: anonymous symbol index
372 static int rsym
, anon_sym
, ind
, loc
;
373 /* expression generation modifiers */
374 static int const_wanted
; /* true if constant wanted */
375 static int nocode_wanted
; /* true if no code generation wanted for an expression */
376 static int global_expr
; /* true if compound literals must be allocated
377 globally (used during initializers parsing */
378 static CType func_vt
; /* current function return type (used by return
381 static int last_line_num
, last_ind
, func_ind
; /* debug last line number and pc */
382 static int tok_ident
;
383 static TokenSym
**table_ident
;
384 static TokenSym
*hash_ident
[TOK_HASH_SIZE
];
385 static char token_buf
[STRING_MAX_SIZE
+ 1];
386 static char *funcname
;
387 static Sym
*global_stack
, *local_stack
;
388 static Sym
*define_stack
;
389 static Sym
*global_label_stack
, *local_label_stack
;
390 /* symbol allocator */
391 #define SYM_POOL_NB (8192 / sizeof(Sym))
392 static Sym
*sym_free_first
;
394 static SValue vstack
[VSTACK_SIZE
], *vtop
;
395 /* some predefined types */
396 static CType char_pointer_type
, func_old_type
, int_type
;
397 /* true if isid(c) || isnum(c) */
398 static unsigned char isidnum_table
[256];
400 /* display some information during compilation */
401 static int verbose
= 0;
403 /* compile with debug symbol (and use them if error during execution) */
404 static int do_debug
= 0;
406 /* compile with built-in memory and bounds checker */
407 static int do_bounds_check
= 0;
409 /* display benchmark infos */
411 static int do_bench
= 0;
413 static int total_lines
;
414 static int total_bytes
;
416 /* use GNU C extensions */
417 static int gnu_ext
= 1;
419 /* use Tiny C extensions */
420 static int tcc_ext
= 1;
422 /* max number of callers shown if error */
423 static int num_callers
= 6;
424 static const char **rt_bound_error_msg
;
426 /* XXX: get rid of this ASAP */
427 static struct TCCState
*tcc_state
;
429 /* give the path of the tcc libraries */
430 static const char *tcc_lib_path
= CONFIG_TCCDIR
;
435 BufferedFile
**include_stack_ptr
;
436 int *ifdef_stack_ptr
;
438 /* include file handling */
439 char **include_paths
;
440 int nb_include_paths
;
441 char **sysinclude_paths
;
442 int nb_sysinclude_paths
;
443 CachedInclude
**cached_includes
;
444 int nb_cached_includes
;
446 char **library_paths
;
447 int nb_library_paths
;
449 /* array of all loaded dlls (including those referenced by loaded
451 DLLReference
**loaded_dlls
;
456 int nb_sections
; /* number of sections, including first dummy section */
461 unsigned long *got_offsets
;
463 /* give the correspondance from symtab indexes to dynsym indexes */
464 int *symtab_to_dynsym
;
466 /* temporary dynamic symbol sections (for dll loading) */
467 Section
*dynsymtab_section
;
468 /* exported dynamic symbol section */
471 int nostdinc
; /* if true, no standard headers are added */
472 int nostdlib
; /* if true, no standard libraries are added */
474 int nocommon
; /* if true, do not use common symbols for .bss data */
476 /* if true, static linking is performed */
479 /* soname as specified on the command line (-soname) */
482 /* if true, all symbols are exported */
485 /* if true, only link in referenced objects from archive */
488 /* address of text section */
489 unsigned long text_addr
;
492 /* output format, see TCC_OUTPUT_FORMAT_xxx */
495 /* C language options */
496 int char_is_unsigned
;
497 int leading_underscore
;
499 /* warning switches */
500 int warn_write_strings
;
501 int warn_unsupported
;
504 int warn_implicit_function_declaration
;
508 void (*error_func
)(void *opaque
, const char *msg
);
509 int error_set_jmp_enabled
;
510 jmp_buf error_jmp_buf
;
513 /* tiny assembler state */
516 /* see include_stack_ptr */
517 BufferedFile
*include_stack
[INCLUDE_STACK_SIZE
];
519 /* see ifdef_stack_ptr */
520 int ifdef_stack
[IFDEF_STACK_SIZE
];
522 /* see cached_includes */
523 int cached_includes_hash
[CACHED_INCLUDES_HASH_SIZE
];
526 int pack_stack
[PACK_STACK_SIZE
];
529 /* output file for preprocessing */
533 /* The current value can be: */
534 #define VT_VALMASK 0x00ff
535 #define VT_CONST 0x00f0 /* constant in vc
536 (must be first non register value) */
537 #define VT_LLOCAL 0x00f1 /* lvalue, offset on stack */
538 #define VT_LOCAL 0x00f2 /* offset on stack */
539 #define VT_CMP 0x00f3 /* the value is stored in processor flags (in vc) */
540 #define VT_JMP 0x00f4 /* value is the consequence of jmp true (even) */
541 #define VT_JMPI 0x00f5 /* value is the consequence of jmp false (odd) */
542 #define VT_LVAL 0x0100 /* var is an lvalue */
543 #define VT_SYM 0x0200 /* a symbol value is added */
544 #define VT_MUSTCAST 0x0400 /* value must be casted to be correct (used for
545 char/short stored in integer registers) */
546 #define VT_MUSTBOUND 0x0800 /* bound checking must be done before
547 dereferencing value */
548 #define VT_BOUNDED 0x8000 /* value is bounded. The address of the
549 bounding function call point is in vc */
550 #define VT_LVAL_BYTE 0x1000 /* lvalue is a byte */
551 #define VT_LVAL_SHORT 0x2000 /* lvalue is a short */
552 #define VT_LVAL_UNSIGNED 0x4000 /* lvalue is unsigned */
553 #define VT_LVAL_TYPE (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
556 #define VT_INT 0 /* integer type */
557 #define VT_BYTE 1 /* signed byte type */
558 #define VT_SHORT 2 /* short type */
559 #define VT_VOID 3 /* void type */
560 #define VT_PTR 4 /* pointer */
561 #define VT_ENUM 5 /* enum definition */
562 #define VT_FUNC 6 /* function type */
563 #define VT_STRUCT 7 /* struct/union definition */
564 #define VT_FLOAT 8 /* IEEE float */
565 #define VT_DOUBLE 9 /* IEEE double */
566 #define VT_LDOUBLE 10 /* IEEE long double */
567 #define VT_BOOL 11 /* ISOC99 boolean type */
568 #define VT_LLONG 12 /* 64 bit integer */
569 #define VT_LONG 13 /* long integer (NEVER USED as type, only
571 #define VT_BTYPE 0x000f /* mask for basic type */
572 #define VT_UNSIGNED 0x0010 /* unsigned type */
573 #define VT_ARRAY 0x0020 /* array type (also has VT_PTR) */
574 #define VT_BITFIELD 0x0040 /* bitfield modifier */
575 #define VT_CONSTANT 0x0800 /* const modifier */
576 #define VT_VOLATILE 0x1000 /* volatile modifier */
577 #define VT_SIGNED 0x2000 /* signed type */
580 #define VT_EXTERN 0x00000080 /* extern definition */
581 #define VT_STATIC 0x00000100 /* static variable */
582 #define VT_TYPEDEF 0x00000200 /* typedef definition */
583 #define VT_INLINE 0x00000400 /* inline definition */
585 #define VT_STRUCT_SHIFT 16 /* shift for bitfield shift values */
587 /* type mask (except storage) */
588 #define VT_STORAGE (VT_EXTERN | VT_STATIC | VT_TYPEDEF | VT_INLINE)
589 #define VT_TYPE (~(VT_STORAGE))
593 /* warning: the following compare tokens depend on i386 asm code */
600 #define TOK_Nset 0x98
601 #define TOK_Nclear 0x99
607 #define TOK_LAND 0xa0
611 #define TOK_MID 0xa3 /* inc/dec, to void constant */
613 #define TOK_UDIV 0xb0 /* unsigned division */
614 #define TOK_UMOD 0xb1 /* unsigned modulo */
615 #define TOK_PDIV 0xb2 /* fast division with undefined rounding for pointers */
616 #define TOK_CINT 0xb3 /* number in tokc */
617 #define TOK_CCHAR 0xb4 /* char constant in tokc */
618 #define TOK_STR 0xb5 /* pointer to string in tokc */
619 #define TOK_TWOSHARPS 0xb6 /* ## preprocessing token */
620 #define TOK_LCHAR 0xb7
621 #define TOK_LSTR 0xb8
622 #define TOK_CFLOAT 0xb9 /* float constant */
623 #define TOK_LINENUM 0xba /* line number info */
624 #define TOK_CDOUBLE 0xc0 /* double constant */
625 #define TOK_CLDOUBLE 0xc1 /* long double constant */
626 #define TOK_UMULL 0xc2 /* unsigned 32x32 -> 64 mul */
627 #define TOK_ADDC1 0xc3 /* add with carry generation */
628 #define TOK_ADDC2 0xc4 /* add with carry use */
629 #define TOK_SUBC1 0xc5 /* add with carry generation */
630 #define TOK_SUBC2 0xc6 /* add with carry use */
631 #define TOK_CUINT 0xc8 /* unsigned int constant */
632 #define TOK_CLLONG 0xc9 /* long long constant */
633 #define TOK_CULLONG 0xca /* unsigned long long constant */
634 #define TOK_ARROW 0xcb
635 #define TOK_DOTS 0xcc /* three dots */
636 #define TOK_SHR 0xcd /* unsigned shift right */
637 #define TOK_PPNUM 0xce /* preprocessor number */
639 #define TOK_SHL 0x01 /* shift left */
640 #define TOK_SAR 0x02 /* signed shift right */
642 /* assignement operators : normal operator or 0x80 */
643 #define TOK_A_MOD 0xa5
644 #define TOK_A_AND 0xa6
645 #define TOK_A_MUL 0xaa
646 #define TOK_A_ADD 0xab
647 #define TOK_A_SUB 0xad
648 #define TOK_A_DIV 0xaf
649 #define TOK_A_XOR 0xde
650 #define TOK_A_OR 0xfc
651 #define TOK_A_SHL 0x81
652 #define TOK_A_SAR 0x82
655 #define offsetof(type, field) ((size_t) &((type *)0)->field)
659 #define countof(tab) (sizeof(tab) / sizeof((tab)[0]))
662 /* WARNING: the content of this string encodes token numbers */
663 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";
665 #define TOK_EOF (-1) /* end of file */
666 #define TOK_LINEFEED 10 /* line feed */
668 /* all identificators and strings have token above that */
669 #define TOK_IDENT 256
671 /* only used for i386 asm opcodes definitions */
672 #define DEF_ASM(x) DEF(TOK_ASM_ ## x, #x)
675 DEF(TOK_ASM_ ## x ## b, #x "b") \
676 DEF(TOK_ASM_ ## x ## w, #x "w") \
677 DEF(TOK_ASM_ ## x ## l, #x "l") \
678 DEF(TOK_ASM_ ## x, #x)
681 DEF(TOK_ASM_ ## x ## w, #x "w") \
682 DEF(TOK_ASM_ ## x ## l, #x "l") \
683 DEF(TOK_ASM_ ## x, #x)
686 DEF(TOK_ASM_ ## f ## x ## s, "f" #x "s") \
687 DEF(TOK_ASM_ ## fi ## x ## l, "fi" #x "l") \
688 DEF(TOK_ASM_ ## f ## x ## l, "f" #x "l") \
689 DEF(TOK_ASM_ ## fi ## x ## s, "fi" #x "s")
692 DEF(TOK_ASM_ ## f ## x, "f" #x ) \
693 DEF(TOK_ASM_ ## f ## x ## p, "f" #x "p") \
696 #define DEF_ASMTEST(x) \
728 #define TOK_ASM_int TOK_INT
731 TOK_LAST
= TOK_IDENT
- 1,
732 #define DEF(id, str) id,
737 static const char tcc_keywords
[] =
738 #define DEF(id, str) str "\0"
743 #define TOK_UIDENT TOK_DEFINE
746 #define snprintf _snprintf
747 #define vsnprintf _vsnprintf
749 #define strtold (long double)strtod
750 #define strtof (float)strtod
751 #define strtoll (long long)strtol
753 #elif defined(TCC_UCLIBC) || defined(__FreeBSD__) || defined(__DragonFly__) \
754 || defined(__OpenBSD__)
755 /* currently incorrect */
756 long double strtold(const char *nptr
, char **endptr
)
758 return (long double)strtod(nptr
, endptr
);
760 float strtof(const char *nptr
, char **endptr
)
762 return (float)strtod(nptr
, endptr
);
765 /* XXX: need to define this to use them in non ISOC99 context */
766 extern float strtof (const char *__nptr
, char **__endptr
);
767 extern long double strtold (const char *__nptr
, char **__endptr
);
770 static char *pstrcpy(char *buf
, int buf_size
, const char *s
);
771 static char *pstrcat(char *buf
, int buf_size
, const char *s
);
772 static char *tcc_basename(const char *name
);
773 static char *tcc_fileextension (const char *p
);
775 static void next(void);
776 static void next_nomacro(void);
777 static void parse_expr_type(CType
*type
);
778 static void expr_type(CType
*type
);
779 static void unary_type(CType
*type
);
780 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
781 int case_reg
, int is_expr
);
782 static int expr_const(void);
783 static void expr_eq(void);
784 static void gexpr(void);
785 static void gen_inline_functions(void);
786 static void decl(int l
);
787 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
788 int first
, int size_only
);
789 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
790 int has_init
, int v
, int scope
);
792 void gv2(int rc1
, int rc2
);
793 void move_reg(int r
, int s
);
794 void save_regs(int n
);
795 void save_reg(int r
);
800 int get_reg_ex(int rc
,int rc2
);
803 struct macro_level
*prev
;
807 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
808 const int *macro_str
, struct macro_level
**can_read_stream
);
810 void force_charshort_cast(int t
);
811 static void gen_cast(CType
*type
);
813 static Sym
*sym_find(int v
);
814 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
);
817 static int type_size(CType
*type
, int *a
);
818 static inline CType
*pointed_type(CType
*type
);
819 static int pointed_size(CType
*type
);
820 static int lvalue_type(int t
);
821 static int parse_btype(CType
*type
, AttributeDef
*ad
);
822 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
);
823 static int compare_types(CType
*type1
, CType
*type2
, int unqualified
);
824 static int is_compatible_types(CType
*type1
, CType
*type2
);
825 static int is_compatible_parameter_types(CType
*type1
, CType
*type2
);
827 int ieee_finite(double d
);
828 void error(const char *fmt
, ...);
832 void lexpand_nr(void);
833 static void vpush_global_sym(CType
*type
, int v
);
834 void vset(CType
*type
, int r
, int v
);
835 void type_to_str(char *buf
, int buf_size
,
836 CType
*type
, const char *varstr
);
837 char *get_tok_str(int v
, CValue
*cv
);
838 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
839 unsigned long offset
, unsigned long size
);
840 static Sym
*external_global_sym(int v
, CType
*type
, int r
);
842 /* section generation */
843 static void section_realloc(Section
*sec
, unsigned long new_size
);
844 static void *section_ptr_add(Section
*sec
, unsigned long size
);
845 static void put_extern_sym(Sym
*sym
, Section
*section
,
846 unsigned long value
, unsigned long size
);
847 static void greloc(Section
*s
, Sym
*sym
, unsigned long addr
, int type
);
848 static int put_elf_str(Section
*s
, const char *sym
);
849 static int put_elf_sym(Section
*s
,
850 unsigned long value
, unsigned long size
,
851 int info
, int other
, int shndx
, const char *name
);
852 static int add_elf_sym(Section
*s
, unsigned long value
, unsigned long size
,
853 int info
, int other
, int sh_num
, const char *name
);
854 static void put_elf_reloc(Section
*symtab
, Section
*s
, unsigned long offset
,
855 int type
, int symbol
);
856 static void put_stabs(const char *str
, int type
, int other
, int desc
,
857 unsigned long value
);
858 static void put_stabs_r(const char *str
, int type
, int other
, int desc
,
859 unsigned long value
, Section
*sec
, int sym_index
);
860 static void put_stabn(int type
, int other
, int desc
, int value
);
861 static void put_stabd(int type
, int other
, int desc
);
862 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
);
864 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
865 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
866 #define AFF_PREPROCESS 0x0004 /* preprocess file */
867 static int tcc_add_file_internal(TCCState
*s
, const char *filename
, int flags
);
870 int tcc_output_coff(TCCState
*s1
, FILE *f
);
873 void *resolve_sym(TCCState
*s1
, const char *sym
, int type
);
874 int pe_load_def_file(struct TCCState
*s1
, int fd
);
875 int pe_test_res_file(void *v
, int size
);
876 int pe_load_res_file(struct TCCState
*s1
, int fd
);
877 void pe_add_runtime(struct TCCState
*s1
);
878 void pe_guess_outfile(char *objfilename
, int output_type
);
879 int pe_output_file(struct TCCState
*s1
, const char *filename
);
883 #ifdef CONFIG_TCC_ASM
885 typedef struct ExprValue
{
890 #define MAX_ASM_OPERANDS 30
892 typedef struct ASMOperand
{
893 int id
; /* GCC 3 optionnal identifier (0 if number only supported */
895 char asm_str
[16]; /* computed asm string for operand */
896 SValue
*vt
; /* C value of the expression */
897 int ref_index
; /* if >= 0, gives reference to a output constraint */
898 int input_index
; /* if >= 0, gives reference to an input constraint */
899 int priority
; /* priority, used to assign registers */
900 int reg
; /* if >= 0, register number used for this operand */
901 int is_llong
; /* true if double register value */
902 int is_memory
; /* true if memory operand */
903 int is_rw
; /* for '+' modifier */
906 static void asm_expr(TCCState
*s1
, ExprValue
*pe
);
907 static int asm_int_expr(TCCState
*s1
);
908 static int find_constraint(ASMOperand
*operands
, int nb_operands
,
909 const char *name
, const char **pp
);
911 static int tcc_assemble(TCCState
*s1
, int do_preprocess
);
915 static void asm_instr(void);
916 static void asm_global_instr(void);
918 /* true if float/double/long double type */
919 static inline int is_float(int t
)
923 return bt
== VT_LDOUBLE
|| bt
== VT_DOUBLE
|| bt
== VT_FLOAT
;
926 #ifdef TCC_TARGET_I386
927 #include "i386-gen.c"
930 #ifdef TCC_TARGET_ARM
934 #ifdef TCC_TARGET_C67
938 #ifdef CONFIG_TCC_STATIC
940 #define RTLD_LAZY 0x001
941 #define RTLD_NOW 0x002
942 #define RTLD_GLOBAL 0x100
943 #define RTLD_DEFAULT NULL
945 /* dummy function for profiling */
946 void *dlopen(const char *filename
, int flag
)
951 const char *dlerror(void)
956 typedef struct TCCSyms
{
961 #define TCCSYM(a) { #a, &a, },
963 /* add the symbol you want here if no dynamic linking is done */
964 static TCCSyms tcc_syms
[] = {
965 #if !defined(CONFIG_TCCBOOT)
974 void *resolve_sym(TCCState
*s1
, const char *symbol
, int type
)
978 while (p
->str
!= NULL
) {
979 if (!strcmp(p
->str
, symbol
))
986 #elif !defined(_WIN32)
990 void *resolve_sym(TCCState
*s1
, const char *sym
, int type
)
992 return dlsym(RTLD_DEFAULT
, sym
);
997 /********************************************************/
999 /* we use our own 'finite' function to avoid potential problems with
1000 non standard math libs */
1001 /* XXX: endianness dependent */
1002 int ieee_finite(double d
)
1005 return ((unsigned)((p
[1] | 0x800fffff) + 1)) >> 31;
1008 /* copy a string and truncate it. */
1009 static char *pstrcpy(char *buf
, int buf_size
, const char *s
)
1016 q_end
= buf
+ buf_size
- 1;
1028 /* strcat and truncate. */
1029 static char *pstrcat(char *buf
, int buf_size
, const char *s
)
1034 pstrcpy(buf
+ len
, buf_size
- len
, s
);
1038 static int strstart(const char *str
, const char *val
, const char **ptr
)
1043 while (*q
!= '\0') {
1054 /* extract the basename of a file */
1055 static char *tcc_basename(const char *name
)
1057 char *p
= strchr(name
, 0);
1068 static char *tcc_fileextension (const char *name
)
1070 char *b
= tcc_basename(name
);
1071 char *e
= strrchr(b
, '.');
1072 return e
? e
: strchr(b
, 0);
1076 char *normalize_slashes(char *path
)
1079 for (p
= path
; *p
; ++p
)
1085 char *w32_tcc_lib_path(void)
1087 /* on win32, we suppose the lib and includes are at the location
1089 char path
[1024], *p
;
1090 GetModuleFileNameA(NULL
, path
, sizeof path
);
1091 p
= tcc_basename(normalize_slashes(strlwr(path
)));
1092 if (p
- 5 > path
&& 0 == strncmp(p
- 5, "/bin/", 5))
1097 return strdup(path
);
1101 void set_pages_executable(void *ptr
, unsigned long length
)
1104 unsigned long old_protect
;
1105 VirtualProtect(ptr
, length
, PAGE_EXECUTE_READWRITE
, &old_protect
);
1107 unsigned long start
, end
;
1108 start
= (unsigned long)ptr
& ~(PAGESIZE
- 1);
1109 end
= (unsigned long)ptr
+ length
;
1110 end
= (end
+ PAGESIZE
- 1) & ~(PAGESIZE
- 1);
1111 mprotect((void *)start
, end
- start
, PROT_READ
| PROT_WRITE
| PROT_EXEC
);
1115 /* memory management */
1121 static inline void tcc_free(void *ptr
)
1124 mem_cur_size
-= malloc_usable_size(ptr
);
1129 static void *tcc_malloc(unsigned long size
)
1134 error("memory full");
1136 mem_cur_size
+= malloc_usable_size(ptr
);
1137 if (mem_cur_size
> mem_max_size
)
1138 mem_max_size
= mem_cur_size
;
1143 static void *tcc_mallocz(unsigned long size
)
1146 ptr
= tcc_malloc(size
);
1147 memset(ptr
, 0, size
);
1151 static inline void *tcc_realloc(void *ptr
, unsigned long size
)
1155 mem_cur_size
-= malloc_usable_size(ptr
);
1157 ptr1
= realloc(ptr
, size
);
1159 /* NOTE: count not correct if alloc error, but not critical */
1160 mem_cur_size
+= malloc_usable_size(ptr1
);
1161 if (mem_cur_size
> mem_max_size
)
1162 mem_max_size
= mem_cur_size
;
1167 static char *tcc_strdup(const char *str
)
1170 ptr
= tcc_malloc(strlen(str
) + 1);
1175 #define free(p) use_tcc_free(p)
1176 #define malloc(s) use_tcc_malloc(s)
1177 #define realloc(p, s) use_tcc_realloc(p, s)
1179 static void dynarray_add(void ***ptab
, int *nb_ptr
, void *data
)
1186 /* every power of two we double array size */
1187 if ((nb
& (nb
- 1)) == 0) {
1192 pp
= tcc_realloc(pp
, nb_alloc
* sizeof(void *));
1194 error("memory full");
1201 static void dynarray_reset(void *pp
, int *n
)
1204 for (p
= *(void***)pp
; *n
; ++p
, --*n
)
1207 tcc_free(*(void**)pp
);
1211 /* symbol allocator */
1212 static Sym
*__sym_malloc(void)
1214 Sym
*sym_pool
, *sym
, *last_sym
;
1217 sym_pool
= tcc_malloc(SYM_POOL_NB
* sizeof(Sym
));
1219 last_sym
= sym_free_first
;
1221 for(i
= 0; i
< SYM_POOL_NB
; i
++) {
1222 sym
->next
= last_sym
;
1226 sym_free_first
= last_sym
;
1230 static inline Sym
*sym_malloc(void)
1233 sym
= sym_free_first
;
1235 sym
= __sym_malloc();
1236 sym_free_first
= sym
->next
;
1240 static inline void sym_free(Sym
*sym
)
1242 sym
->next
= sym_free_first
;
1243 sym_free_first
= sym
;
1246 Section
*new_section(TCCState
*s1
, const char *name
, int sh_type
, int sh_flags
)
1250 sec
= tcc_mallocz(sizeof(Section
) + strlen(name
));
1251 strcpy(sec
->name
, name
);
1252 sec
->sh_type
= sh_type
;
1253 sec
->sh_flags
= sh_flags
;
1260 sec
->sh_addralign
= 4;
1263 sec
->sh_addralign
= 1;
1266 sec
->sh_addralign
= 32; /* default conservative alignment */
1270 /* only add section if not private */
1271 if (!(sh_flags
& SHF_PRIVATE
)) {
1272 sec
->sh_num
= s1
->nb_sections
;
1273 dynarray_add((void ***)&s1
->sections
, &s1
->nb_sections
, sec
);
1278 static void free_section(Section
*s
)
1284 /* realloc section and set its content to zero */
1285 static void section_realloc(Section
*sec
, unsigned long new_size
)
1288 unsigned char *data
;
1290 size
= sec
->data_allocated
;
1293 while (size
< new_size
)
1295 data
= tcc_realloc(sec
->data
, size
);
1297 error("memory full");
1298 memset(data
+ sec
->data_allocated
, 0, size
- sec
->data_allocated
);
1300 sec
->data_allocated
= size
;
1303 /* reserve at least 'size' bytes in section 'sec' from
1304 sec->data_offset. */
1305 static void *section_ptr_add(Section
*sec
, unsigned long size
)
1307 unsigned long offset
, offset1
;
1309 offset
= sec
->data_offset
;
1310 offset1
= offset
+ size
;
1311 if (offset1
> sec
->data_allocated
)
1312 section_realloc(sec
, offset1
);
1313 sec
->data_offset
= offset1
;
1314 return sec
->data
+ offset
;
1317 /* return a reference to a section, and create it if it does not
1319 Section
*find_section(TCCState
*s1
, const char *name
)
1323 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1324 sec
= s1
->sections
[i
];
1325 if (!strcmp(name
, sec
->name
))
1328 /* sections are created as PROGBITS */
1329 return new_section(s1
, name
, SHT_PROGBITS
, SHF_ALLOC
);
1332 #define SECTION_ABS ((void *)1)
1334 /* update sym->c so that it points to an external symbol in section
1335 'section' with value 'value' */
1336 static void put_extern_sym2(Sym
*sym
, Section
*section
,
1337 unsigned long value
, unsigned long size
,
1338 int can_add_underscore
)
1340 int sym_type
, sym_bind
, sh_num
, info
, other
, attr
;
1345 if (section
== NULL
)
1347 else if (section
== SECTION_ABS
)
1350 sh_num
= section
->sh_num
;
1354 if ((sym
->type
.t
& VT_BTYPE
) == VT_FUNC
) {
1355 sym_type
= STT_FUNC
;
1356 #ifdef TCC_TARGET_PE
1358 attr
= sym
->type
.ref
->r
;
1359 if (FUNC_EXPORT(attr
))
1361 if (FUNC_CALL(attr
) == FUNC_STDCALL
)
1365 sym_type
= STT_OBJECT
;
1368 if (sym
->type
.t
& VT_STATIC
)
1369 sym_bind
= STB_LOCAL
;
1371 sym_bind
= STB_GLOBAL
;
1374 name
= get_tok_str(sym
->v
, NULL
);
1375 #ifdef CONFIG_TCC_BCHECK
1376 if (do_bounds_check
) {
1379 /* XXX: avoid doing that for statics ? */
1380 /* if bound checking is activated, we change some function
1381 names by adding the "__bound" prefix */
1384 /* XXX: we rely only on malloc hooks */
1397 strcpy(buf
, "__bound_");
1405 #ifdef TCC_TARGET_PE
1406 if ((other
& 2) && can_add_underscore
) {
1407 sprintf(buf1
, "_%s@%d", name
, FUNC_ARGS(attr
));
1411 if (tcc_state
->leading_underscore
&& can_add_underscore
) {
1413 pstrcpy(buf1
+ 1, sizeof(buf1
) - 1, name
);
1416 info
= ELF32_ST_INFO(sym_bind
, sym_type
);
1417 sym
->c
= add_elf_sym(symtab_section
, value
, size
, info
, other
, sh_num
, name
);
1419 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
1420 esym
->st_value
= value
;
1421 esym
->st_size
= size
;
1422 esym
->st_shndx
= sh_num
;
1423 esym
->st_other
|= other
;
1427 static void put_extern_sym(Sym
*sym
, Section
*section
,
1428 unsigned long value
, unsigned long size
)
1430 put_extern_sym2(sym
, section
, value
, size
, 1);
1433 /* add a new relocation entry to symbol 'sym' in section 's' */
1434 static void greloc(Section
*s
, Sym
*sym
, unsigned long offset
, int type
)
1437 put_extern_sym(sym
, NULL
, 0, 0);
1438 /* now we can add ELF relocation info */
1439 put_elf_reloc(symtab_section
, s
, offset
, type
, sym
->c
);
1442 static inline int isid(int c
)
1444 return (c
>= 'a' && c
<= 'z') ||
1445 (c
>= 'A' && c
<= 'Z') ||
1449 static inline int isnum(int c
)
1451 return c
>= '0' && c
<= '9';
1454 static inline int isoct(int c
)
1456 return c
>= '0' && c
<= '7';
1459 static inline int toup(int c
)
1461 if (c
>= 'a' && c
<= 'z')
1462 return c
- 'a' + 'A';
1467 static void strcat_vprintf(char *buf
, int buf_size
, const char *fmt
, va_list ap
)
1471 vsnprintf(buf
+ len
, buf_size
- len
, fmt
, ap
);
1474 static void strcat_printf(char *buf
, int buf_size
, const char *fmt
, ...)
1478 strcat_vprintf(buf
, buf_size
, fmt
, ap
);
1482 void error1(TCCState
*s1
, int is_warning
, const char *fmt
, va_list ap
)
1489 for(f
= s1
->include_stack
; f
< s1
->include_stack_ptr
; f
++)
1490 strcat_printf(buf
, sizeof(buf
), "In file included from %s:%d:\n",
1491 (*f
)->filename
, (*f
)->line_num
);
1492 if (file
->line_num
> 0) {
1493 strcat_printf(buf
, sizeof(buf
),
1494 "%s:%d: ", file
->filename
, file
->line_num
);
1496 strcat_printf(buf
, sizeof(buf
),
1497 "%s: ", file
->filename
);
1500 strcat_printf(buf
, sizeof(buf
),
1504 strcat_printf(buf
, sizeof(buf
), "warning: ");
1505 strcat_vprintf(buf
, sizeof(buf
), fmt
, ap
);
1507 if (!s1
->error_func
) {
1508 /* default case: stderr */
1509 fprintf(stderr
, "%s\n", buf
);
1511 s1
->error_func(s1
->error_opaque
, buf
);
1513 if (!is_warning
|| s1
->warn_error
)
1518 void tcc_set_error_func(TCCState
*s
, void *error_opaque
,
1519 void (*error_func
)(void *opaque
, const char *msg
))
1521 s
->error_opaque
= error_opaque
;
1522 s
->error_func
= error_func
;
1526 /* error without aborting current compilation */
1527 void error_noabort(const char *fmt
, ...)
1529 TCCState
*s1
= tcc_state
;
1533 error1(s1
, 0, fmt
, ap
);
1537 void error(const char *fmt
, ...)
1539 TCCState
*s1
= tcc_state
;
1543 error1(s1
, 0, fmt
, ap
);
1545 /* better than nothing: in some cases, we accept to handle errors */
1546 if (s1
->error_set_jmp_enabled
) {
1547 longjmp(s1
->error_jmp_buf
, 1);
1549 /* XXX: eliminate this someday */
1554 void expect(const char *msg
)
1556 error("%s expected", msg
);
1559 void warning(const char *fmt
, ...)
1561 TCCState
*s1
= tcc_state
;
1568 error1(s1
, 1, fmt
, ap
);
1575 error("'%c' expected", c
);
1579 static void test_lvalue(void)
1581 if (!(vtop
->r
& VT_LVAL
))
1585 /* allocate a new token */
1586 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
1588 TokenSym
*ts
, **ptable
;
1591 if (tok_ident
>= SYM_FIRST_ANOM
)
1592 error("memory full");
1594 /* expand token table if needed */
1595 i
= tok_ident
- TOK_IDENT
;
1596 if ((i
% TOK_ALLOC_INCR
) == 0) {
1597 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
1599 error("memory full");
1600 table_ident
= ptable
;
1603 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
1604 table_ident
[i
] = ts
;
1605 ts
->tok
= tok_ident
++;
1606 ts
->sym_define
= NULL
;
1607 ts
->sym_label
= NULL
;
1608 ts
->sym_struct
= NULL
;
1609 ts
->sym_identifier
= NULL
;
1611 ts
->hash_next
= NULL
;
1612 memcpy(ts
->str
, str
, len
);
1613 ts
->str
[len
] = '\0';
1618 #define TOK_HASH_INIT 1
1619 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
1621 /* find a token and add it if not found */
1622 static TokenSym
*tok_alloc(const char *str
, int len
)
1624 TokenSym
*ts
, **pts
;
1630 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
1631 h
&= (TOK_HASH_SIZE
- 1);
1633 pts
= &hash_ident
[h
];
1638 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
1640 pts
= &(ts
->hash_next
);
1642 return tok_alloc_new(pts
, str
, len
);
1645 /* CString handling */
1647 static void cstr_realloc(CString
*cstr
, int new_size
)
1652 size
= cstr
->size_allocated
;
1654 size
= 8; /* no need to allocate a too small first string */
1655 while (size
< new_size
)
1657 data
= tcc_realloc(cstr
->data_allocated
, size
);
1659 error("memory full");
1660 cstr
->data_allocated
= data
;
1661 cstr
->size_allocated
= size
;
1666 static inline void cstr_ccat(CString
*cstr
, int ch
)
1669 size
= cstr
->size
+ 1;
1670 if (size
> cstr
->size_allocated
)
1671 cstr_realloc(cstr
, size
);
1672 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
1676 static void cstr_cat(CString
*cstr
, const char *str
)
1688 /* add a wide char */
1689 static void cstr_wccat(CString
*cstr
, int ch
)
1692 size
= cstr
->size
+ sizeof(nwchar_t
);
1693 if (size
> cstr
->size_allocated
)
1694 cstr_realloc(cstr
, size
);
1695 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
1699 static void cstr_new(CString
*cstr
)
1701 memset(cstr
, 0, sizeof(CString
));
1704 /* free string and reset it to NULL */
1705 static void cstr_free(CString
*cstr
)
1707 tcc_free(cstr
->data_allocated
);
1711 #define cstr_reset(cstr) cstr_free(cstr)
1713 /* XXX: unicode ? */
1714 static void add_char(CString
*cstr
, int c
)
1716 if (c
== '\'' || c
== '\"' || c
== '\\') {
1717 /* XXX: could be more precise if char or string */
1718 cstr_ccat(cstr
, '\\');
1720 if (c
>= 32 && c
<= 126) {
1723 cstr_ccat(cstr
, '\\');
1725 cstr_ccat(cstr
, 'n');
1727 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
1728 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
1729 cstr_ccat(cstr
, '0' + (c
& 7));
1734 /* XXX: buffer overflow */
1735 /* XXX: float tokens */
1736 char *get_tok_str(int v
, CValue
*cv
)
1738 static char buf
[STRING_MAX_SIZE
+ 1];
1739 static CString cstr_buf
;
1745 /* NOTE: to go faster, we give a fixed buffer for small strings */
1746 cstr_reset(&cstr_buf
);
1747 cstr_buf
.data
= buf
;
1748 cstr_buf
.size_allocated
= sizeof(buf
);
1754 /* XXX: not quite exact, but only useful for testing */
1755 sprintf(p
, "%u", cv
->ui
);
1759 /* XXX: not quite exact, but only useful for testing */
1760 sprintf(p
, "%Lu", cv
->ull
);
1764 cstr_ccat(&cstr_buf
, '\'');
1765 add_char(&cstr_buf
, cv
->i
);
1766 cstr_ccat(&cstr_buf
, '\'');
1767 cstr_ccat(&cstr_buf
, '\0');
1771 len
= cstr
->size
- 1;
1773 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1774 cstr_ccat(&cstr_buf
, '\0');
1779 cstr_ccat(&cstr_buf
, '\"');
1781 len
= cstr
->size
- 1;
1783 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1785 len
= (cstr
->size
/ sizeof(nwchar_t
)) - 1;
1787 add_char(&cstr_buf
, ((nwchar_t
*)cstr
->data
)[i
]);
1789 cstr_ccat(&cstr_buf
, '\"');
1790 cstr_ccat(&cstr_buf
, '\0');
1799 return strcpy(p
, "...");
1801 return strcpy(p
, "<<=");
1803 return strcpy(p
, ">>=");
1805 if (v
< TOK_IDENT
) {
1806 /* search in two bytes table */
1820 } else if (v
< tok_ident
) {
1821 return table_ident
[v
- TOK_IDENT
]->str
;
1822 } else if (v
>= SYM_FIRST_ANOM
) {
1823 /* special name for anonymous symbol */
1824 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
1826 /* should never happen */
1831 return cstr_buf
.data
;
1834 /* push, without hashing */
1835 static Sym
*sym_push2(Sym
**ps
, int v
, int t
, int c
)
1849 /* find a symbol and return its associated structure. 's' is the top
1850 of the symbol stack */
1851 static Sym
*sym_find2(Sym
*s
, int v
)
1861 /* structure lookup */
1862 static inline Sym
*struct_find(int v
)
1865 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1867 return table_ident
[v
]->sym_struct
;
1870 /* find an identifier */
1871 static inline Sym
*sym_find(int v
)
1874 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1876 return table_ident
[v
]->sym_identifier
;
1879 /* push a given symbol on the symbol stack */
1880 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
)
1889 s
= sym_push2(ps
, v
, type
->t
, c
);
1890 s
->type
.ref
= type
->ref
;
1892 /* don't record fields or anonymous symbols */
1894 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1895 /* record symbol in token array */
1896 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1898 ps
= &ts
->sym_struct
;
1900 ps
= &ts
->sym_identifier
;
1907 /* push a global identifier */
1908 static Sym
*global_identifier_push(int v
, int t
, int c
)
1911 s
= sym_push2(&global_stack
, v
, t
, c
);
1912 /* don't record anonymous symbol */
1913 if (v
< SYM_FIRST_ANOM
) {
1914 ps
= &table_ident
[v
- TOK_IDENT
]->sym_identifier
;
1915 /* modify the top most local identifier, so that
1916 sym_identifier will point to 's' when popped */
1918 ps
= &(*ps
)->prev_tok
;
1925 /* pop symbols until top reaches 'b' */
1926 static void sym_pop(Sym
**ptop
, Sym
*b
)
1936 /* remove symbol in token array */
1938 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1939 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1941 ps
= &ts
->sym_struct
;
1943 ps
= &ts
->sym_identifier
;
1954 BufferedFile
*tcc_open(TCCState
*s1
, const char *filename
)
1959 if (strcmp(filename
, "-") == 0)
1960 fd
= 0, filename
= "stdin";
1962 fd
= open(filename
, O_RDONLY
| O_BINARY
);
1965 bf
= tcc_malloc(sizeof(BufferedFile
));
1967 bf
->buf_ptr
= bf
->buffer
;
1968 bf
->buf_end
= bf
->buffer
;
1969 bf
->buffer
[0] = CH_EOB
; /* put eob symbol */
1970 pstrcpy(bf
->filename
, sizeof(bf
->filename
), filename
);
1972 normalize_slashes(bf
->filename
);
1975 bf
->ifndef_macro
= 0;
1976 bf
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
1977 // printf("opening '%s'\n", filename);
1981 void tcc_close(BufferedFile
*bf
)
1983 total_lines
+= bf
->line_num
;
1988 /* fill input buffer and peek next char */
1989 static int tcc_peekc_slow(BufferedFile
*bf
)
1992 /* only tries to read if really end of buffer */
1993 if (bf
->buf_ptr
>= bf
->buf_end
) {
1995 #if defined(PARSE_DEBUG)
2000 len
= read(bf
->fd
, bf
->buffer
, len
);
2007 bf
->buf_ptr
= bf
->buffer
;
2008 bf
->buf_end
= bf
->buffer
+ len
;
2009 *bf
->buf_end
= CH_EOB
;
2011 if (bf
->buf_ptr
< bf
->buf_end
) {
2012 return bf
->buf_ptr
[0];
2014 bf
->buf_ptr
= bf
->buf_end
;
2019 /* return the current character, handling end of block if necessary
2021 static int handle_eob(void)
2023 return tcc_peekc_slow(file
);
2026 /* read next char from current input file and handle end of input buffer */
2027 static inline void inp(void)
2029 ch
= *(++(file
->buf_ptr
));
2030 /* end of buffer/file handling */
2035 /* handle '\[\r]\n' */
2036 static int handle_stray_noerror(void)
2038 while (ch
== '\\') {
2043 } else if (ch
== '\r') {
2057 static void handle_stray(void)
2059 if (handle_stray_noerror())
2060 error("stray '\\' in program");
2063 /* skip the stray and handle the \\n case. Output an error if
2064 incorrect char after the stray */
2065 static int handle_stray1(uint8_t *p
)
2069 if (p
>= file
->buf_end
) {
2086 /* handle just the EOB case, but not stray */
2087 #define PEEKC_EOB(c, p)\
2098 /* handle the complicated stray case */
2099 #define PEEKC(c, p)\
2104 c = handle_stray1(p);\
2109 /* input with '\[\r]\n' handling. Note that this function cannot
2110 handle other characters after '\', so you cannot call it inside
2111 strings or comments */
2112 static void minp(void)
2120 /* single line C++ comments */
2121 static uint8_t *parse_line_comment(uint8_t *p
)
2129 if (c
== '\n' || c
== CH_EOF
) {
2131 } else if (c
== '\\') {
2140 } else if (c
== '\r') {
2158 static uint8_t *parse_comment(uint8_t *p
)
2164 /* fast skip loop */
2167 if (c
== '\n' || c
== '*' || c
== '\\')
2171 if (c
== '\n' || c
== '*' || c
== '\\')
2175 /* now we can handle all the cases */
2179 } else if (c
== '*') {
2185 } else if (c
== '/') {
2186 goto end_of_comment
;
2187 } else if (c
== '\\') {
2192 /* skip '\[\r]\n', otherwise just skip the stray */
2198 } else if (c
== '\r') {
2215 /* stray, eob or eof */
2220 error("unexpected end of file in comment");
2221 } else if (c
== '\\') {
2233 /* space exlcuding newline */
2234 static inline int is_space(int ch
)
2236 return ch
== ' ' || ch
== '\t' || ch
== '\v' || ch
== '\f' || ch
== '\r';
2239 static inline void skip_spaces(void)
2241 while (is_space(ch
))
2245 /* parse a string without interpreting escapes */
2246 static uint8_t *parse_pp_string(uint8_t *p
,
2247 int sep
, CString
*str
)
2255 } else if (c
== '\\') {
2260 unterminated_string
:
2261 /* XXX: indicate line number of start of string */
2262 error("missing terminating %c character", sep
);
2263 } else if (c
== '\\') {
2264 /* escape : just skip \[\r]\n */
2269 } else if (c
== '\r') {
2272 expect("'\n' after '\r'");
2275 } else if (c
== CH_EOF
) {
2276 goto unterminated_string
;
2279 cstr_ccat(str
, '\\');
2285 } else if (c
== '\n') {
2288 } else if (c
== '\r') {
2292 cstr_ccat(str
, '\r');
2308 /* skip block of text until #else, #elif or #endif. skip also pairs of
2310 void preprocess_skip(void)
2312 int a
, start_of_line
, c
, in_warn_or_error
;
2319 in_warn_or_error
= 0;
2340 } else if (c
== '\\') {
2341 ch
= file
->buf_ptr
[0];
2342 handle_stray_noerror();
2349 if (in_warn_or_error
)
2351 p
= parse_pp_string(p
, c
, NULL
);
2355 if (in_warn_or_error
)
2362 p
= parse_comment(p
);
2363 } else if (ch
== '/') {
2364 p
= parse_line_comment(p
);
2369 if (start_of_line
) {
2374 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
2376 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
2378 else if (tok
== TOK_ENDIF
)
2380 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
2381 in_warn_or_error
= 1;
2395 /* ParseState handling */
2397 /* XXX: currently, no include file info is stored. Thus, we cannot display
2398 accurate messages if the function or data definition spans multiple
2401 /* save current parse state in 's' */
2402 void save_parse_state(ParseState
*s
)
2404 s
->line_num
= file
->line_num
;
2405 s
->macro_ptr
= macro_ptr
;
2410 /* restore parse state from 's' */
2411 void restore_parse_state(ParseState
*s
)
2413 file
->line_num
= s
->line_num
;
2414 macro_ptr
= s
->macro_ptr
;
2419 /* return the number of additional 'ints' necessary to store the
2421 static inline int tok_ext_size(int t
)
2435 error("unsupported token");
2442 return LDOUBLE_SIZE
/ 4;
2448 /* token string handling */
2450 static inline void tok_str_new(TokenString
*s
)
2454 s
->allocated_len
= 0;
2455 s
->last_line_num
= -1;
2458 static void tok_str_free(int *str
)
2463 static int *tok_str_realloc(TokenString
*s
)
2467 if (s
->allocated_len
== 0) {
2470 len
= s
->allocated_len
* 2;
2472 str
= tcc_realloc(s
->str
, len
* sizeof(int));
2474 error("memory full");
2475 s
->allocated_len
= len
;
2480 static void tok_str_add(TokenString
*s
, int t
)
2486 if (len
>= s
->allocated_len
)
2487 str
= tok_str_realloc(s
);
2492 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
2499 /* allocate space for worst case */
2500 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
2501 str
= tok_str_realloc(s
);
2510 str
[len
++] = cv
->tab
[0];
2519 nb_words
= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
2520 while ((len
+ nb_words
) > s
->allocated_len
)
2521 str
= tok_str_realloc(s
);
2522 cstr
= (CString
*)(str
+ len
);
2524 cstr
->size
= cv
->cstr
->size
;
2525 cstr
->data_allocated
= NULL
;
2526 cstr
->size_allocated
= cstr
->size
;
2527 memcpy((char *)cstr
+ sizeof(CString
),
2528 cv
->cstr
->data
, cstr
->size
);
2535 #if LDOUBLE_SIZE == 8
2538 str
[len
++] = cv
->tab
[0];
2539 str
[len
++] = cv
->tab
[1];
2541 #if LDOUBLE_SIZE == 12
2543 str
[len
++] = cv
->tab
[0];
2544 str
[len
++] = cv
->tab
[1];
2545 str
[len
++] = cv
->tab
[2];
2546 #elif LDOUBLE_SIZE != 8
2547 #error add long double size support
2556 /* add the current parse token in token string 's' */
2557 static void tok_str_add_tok(TokenString
*s
)
2561 /* save line number info */
2562 if (file
->line_num
!= s
->last_line_num
) {
2563 s
->last_line_num
= file
->line_num
;
2564 cval
.i
= s
->last_line_num
;
2565 tok_str_add2(s
, TOK_LINENUM
, &cval
);
2567 tok_str_add2(s
, tok
, &tokc
);
2570 #if LDOUBLE_SIZE == 12
2571 #define LDOUBLE_GET(p, cv) \
2575 #elif LDOUBLE_SIZE == 8
2576 #define LDOUBLE_GET(p, cv) \
2580 #error add long double size support
2584 /* get a token from an integer array and increment pointer
2585 accordingly. we code it as a macro to avoid pointer aliasing. */
2586 #define TOK_GET(t, p, cv) \
2601 cv.cstr = (CString *)p; \
2602 cv.cstr->data = (char *)p + sizeof(CString);\
2603 p += (sizeof(CString) + cv.cstr->size + 3) >> 2;\
2612 case TOK_CLDOUBLE: \
2613 LDOUBLE_GET(p, cv); \
2614 p += LDOUBLE_SIZE / 4; \
2621 /* defines handling */
2622 static inline void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
2626 s
= sym_push2(&define_stack
, v
, macro_type
, (int)str
);
2627 s
->next
= first_arg
;
2628 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
2631 /* undefined a define symbol. Its name is just set to zero */
2632 static void define_undef(Sym
*s
)
2636 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2637 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2641 static inline Sym
*define_find(int v
)
2644 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2646 return table_ident
[v
]->sym_define
;
2649 /* free define stack until top reaches 'b' */
2650 static void free_defines(Sym
*b
)
2658 /* do not free args or predefined defines */
2660 tok_str_free((int *)top
->c
);
2662 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2663 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2671 static Sym
*label_find(int v
)
2674 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2676 return table_ident
[v
]->sym_label
;
2679 static Sym
*label_push(Sym
**ptop
, int v
, int flags
)
2682 s
= sym_push2(ptop
, v
, 0, 0);
2684 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
2685 if (ptop
== &global_label_stack
) {
2686 /* modify the top most local identifier, so that
2687 sym_identifier will point to 's' when popped */
2689 ps
= &(*ps
)->prev_tok
;
2696 /* pop labels until element last is reached. Look if any labels are
2697 undefined. Define symbols if '&&label' was used. */
2698 static void label_pop(Sym
**ptop
, Sym
*slast
)
2701 for(s
= *ptop
; s
!= slast
; s
= s1
) {
2703 if (s
->r
== LABEL_DECLARED
) {
2704 warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
2705 } else if (s
->r
== LABEL_FORWARD
) {
2706 error("label '%s' used but not defined",
2707 get_tok_str(s
->v
, NULL
));
2710 /* define corresponding symbol. A size of
2712 put_extern_sym(s
, cur_text_section
, (long)s
->next
, 1);
2716 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
2722 /* eval an expression for #if/#elif */
2723 static int expr_preprocess(void)
2729 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2730 next(); /* do macro subst */
2731 if (tok
== TOK_DEFINED
) {
2736 c
= define_find(tok
) != 0;
2741 } else if (tok
>= TOK_IDENT
) {
2742 /* if undefined macro */
2746 tok_str_add_tok(&str
);
2748 tok_str_add(&str
, -1); /* simulate end of file */
2749 tok_str_add(&str
, 0);
2750 /* now evaluate C constant expression */
2751 macro_ptr
= str
.str
;
2755 tok_str_free(str
.str
);
2759 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
2760 static void tok_print(int *str
)
2766 TOK_GET(t
, str
, cval
);
2769 printf(" %s", get_tok_str(t
, &cval
));
2775 /* parse after #define */
2776 static void parse_define(void)
2778 Sym
*s
, *first
, **ps
;
2779 int v
, t
, varg
, is_vaargs
, c
;
2784 error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
2785 /* XXX: should check if same macro (ANSI) */
2788 /* '(' must be just after macro definition for MACRO_FUNC */
2789 c
= file
->buf_ptr
[0];
2791 c
= handle_stray1(file
->buf_ptr
);
2796 while (tok
!= ')') {
2800 if (varg
== TOK_DOTS
) {
2801 varg
= TOK___VA_ARGS__
;
2803 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
2807 if (varg
< TOK_IDENT
)
2808 error("badly punctuated parameter list");
2809 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
2820 /* EOF testing necessary for '-D' handling */
2821 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2822 tok_str_add2(&str
, tok
, &tokc
);
2825 tok_str_add(&str
, 0);
2827 printf("define %s %d: ", get_tok_str(v
, NULL
), t
);
2830 define_push(v
, t
, str
.str
, first
);
2833 static inline int hash_cached_include(int type
, const char *filename
)
2835 const unsigned char *s
;
2839 h
= TOK_HASH_FUNC(h
, type
);
2842 h
= TOK_HASH_FUNC(h
, *s
);
2845 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
2849 /* XXX: use a token or a hash table to accelerate matching ? */
2850 static CachedInclude
*search_cached_include(TCCState
*s1
,
2851 int type
, const char *filename
)
2855 h
= hash_cached_include(type
, filename
);
2856 i
= s1
->cached_includes_hash
[h
];
2860 e
= s1
->cached_includes
[i
- 1];
2861 if (e
->type
== type
&& !strcmp(e
->filename
, filename
))
2868 static inline void add_cached_include(TCCState
*s1
, int type
,
2869 const char *filename
, int ifndef_macro
)
2874 if (search_cached_include(s1
, type
, filename
))
2877 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
2879 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
2883 strcpy(e
->filename
, filename
);
2884 e
->ifndef_macro
= ifndef_macro
;
2885 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
2886 /* add in hash table */
2887 h
= hash_cached_include(type
, filename
);
2888 e
->hash_next
= s1
->cached_includes_hash
[h
];
2889 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
2892 static void pragma_parse(TCCState
*s1
)
2897 if (tok
== TOK_pack
) {
2900 #pragma pack(1) // set
2901 #pragma pack() // reset to default
2902 #pragma pack(push,1) // push & set
2903 #pragma pack(pop) // restore previous
2907 if (tok
== TOK_ASM_pop
) {
2909 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
2911 error("out of pack stack");
2913 s1
->pack_stack_ptr
--;
2917 if (tok
== TOK_ASM_push
) {
2919 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
2921 s1
->pack_stack_ptr
++;
2924 if (tok
!= TOK_CINT
) {
2926 error("invalid pack pragma");
2929 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
2933 *s1
->pack_stack_ptr
= val
;
2939 /* is_bof is true if first non space token at beginning of file */
2940 static void preprocess(int is_bof
)
2942 TCCState
*s1
= tcc_state
;
2943 int size
, i
, c
, n
, saved_parse_flags
;
2950 saved_parse_flags
= parse_flags
;
2951 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
|
2952 PARSE_FLAG_LINEFEED
;
2962 s
= define_find(tok
);
2963 /* undefine symbol by putting an invalid name */
2968 case TOK_INCLUDE_NEXT
:
2969 ch
= file
->buf_ptr
[0];
2970 /* XXX: incorrect if comments : use next_nomacro with a special mode */
2975 } else if (ch
== '\"') {
2980 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
2981 if ((q
- buf
) < sizeof(buf
) - 1)
2984 if (handle_stray_noerror() == 0)
2992 /* eat all spaces and comments after include */
2993 /* XXX: slightly incorrect */
2994 while (ch1
!= '\n' && ch1
!= CH_EOF
)
2998 /* computed #include : either we have only strings or
2999 we have anything enclosed in '<>' */
3002 if (tok
== TOK_STR
) {
3003 while (tok
!= TOK_LINEFEED
) {
3004 if (tok
!= TOK_STR
) {
3006 error("'#include' expects \"FILENAME\" or <FILENAME>");
3008 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
3014 while (tok
!= TOK_LINEFEED
) {
3015 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
3019 /* check syntax and remove '<>' */
3020 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
3021 goto include_syntax
;
3022 memmove(buf
, buf
+ 1, len
- 2);
3023 buf
[len
- 2] = '\0';
3028 e
= search_cached_include(s1
, c
, buf
);
3029 if (e
&& define_find(e
->ifndef_macro
)) {
3030 /* no need to parse the include because the 'ifndef macro'
3033 printf("%s: skipping %s\n", file
->filename
, buf
);
3037 /* first search in current dir if "header.h" */
3038 size
= tcc_basename(file
->filename
) - file
->filename
;
3039 if (size
> sizeof(buf1
) - 1)
3040 size
= sizeof(buf1
) - 1;
3041 memcpy(buf1
, file
->filename
, size
);
3043 pstrcat(buf1
, sizeof(buf1
), buf
);
3044 f
= tcc_open(s1
, buf1
);
3046 if (tok
== TOK_INCLUDE_NEXT
)
3052 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
3053 error("#include recursion too deep");
3054 /* now search in all the include paths */
3055 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
3056 for(i
= 0; i
< n
; i
++) {
3058 if (i
< s1
->nb_include_paths
)
3059 path
= s1
->include_paths
[i
];
3061 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
3062 pstrcpy(buf1
, sizeof(buf1
), path
);
3063 pstrcat(buf1
, sizeof(buf1
), "/");
3064 pstrcat(buf1
, sizeof(buf1
), buf
);
3065 f
= tcc_open(s1
, buf1
);
3067 if (tok
== TOK_INCLUDE_NEXT
)
3073 error("include file '%s' not found", buf
);
3077 printf("%s: including %s\n", file
->filename
, buf1
);
3080 pstrcpy(f
->inc_filename
, sizeof(f
->inc_filename
), buf
);
3081 /* push current file in stack */
3082 /* XXX: fix current line init */
3083 *s1
->include_stack_ptr
++ = file
;
3085 /* add include file debug info */
3087 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
3089 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
3090 ch
= file
->buf_ptr
[0];
3098 c
= expr_preprocess();
3104 if (tok
< TOK_IDENT
)
3105 error("invalid argument for '#if%sdef'", c
? "n" : "");
3109 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
3111 file
->ifndef_macro
= tok
;
3114 c
= (define_find(tok
) != 0) ^ c
;
3116 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
3117 error("memory full");
3118 *s1
->ifdef_stack_ptr
++ = c
;
3121 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
3122 error("#else without matching #if");
3123 if (s1
->ifdef_stack_ptr
[-1] & 2)
3124 error("#else after #else");
3125 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
3128 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
3129 error("#elif without matching #if");
3130 c
= s1
->ifdef_stack_ptr
[-1];
3132 error("#elif after #else");
3133 /* last #if/#elif expression was true: we skip */
3136 c
= expr_preprocess();
3137 s1
->ifdef_stack_ptr
[-1] = c
;
3147 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
3148 error("#endif without matching #if");
3149 s1
->ifdef_stack_ptr
--;
3150 /* '#ifndef macro' was at the start of file. Now we check if
3151 an '#endif' is exactly at the end of file */
3152 if (file
->ifndef_macro
&&
3153 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
3154 file
->ifndef_macro_saved
= file
->ifndef_macro
;
3155 /* need to set to zero to avoid false matches if another
3156 #ifndef at middle of file */
3157 file
->ifndef_macro
= 0;
3158 while (tok
!= TOK_LINEFEED
)
3160 tok_flags
|= TOK_FLAG_ENDIF
;
3166 if (tok
!= TOK_CINT
)
3168 file
->line_num
= tokc
.i
- 1; /* the line number will be incremented after */
3170 if (tok
!= TOK_LINEFEED
) {
3173 pstrcpy(file
->filename
, sizeof(file
->filename
),
3174 (char *)tokc
.cstr
->data
);
3180 ch
= file
->buf_ptr
[0];
3183 while (ch
!= '\n' && ch
!= CH_EOF
) {
3184 if ((q
- buf
) < sizeof(buf
) - 1)
3187 if (handle_stray_noerror() == 0)
3194 error("#error %s", buf
);
3196 warning("#warning %s", buf
);
3202 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_CINT
) {
3203 /* '!' is ignored to allow C scripts. numbers are ignored
3204 to emulate cpp behaviour */
3206 if (!(saved_parse_flags
& PARSE_FLAG_ASM_COMMENTS
))
3207 warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
3211 /* ignore other preprocess commands or #! for C scripts */
3212 while (tok
!= TOK_LINEFEED
)
3215 parse_flags
= saved_parse_flags
;
3218 /* evaluate escape codes in a string. */
3219 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
3234 case '0': case '1': case '2': case '3':
3235 case '4': case '5': case '6': case '7':
3236 /* at most three octal digits */
3241 n
= n
* 8 + c
- '0';
3245 n
= n
* 8 + c
- '0';
3250 goto add_char_nonext
;
3258 if (c
>= 'a' && c
<= 'f')
3260 else if (c
>= 'A' && c
<= 'F')
3270 goto add_char_nonext
;
3294 goto invalid_escape
;
3304 if (c
>= '!' && c
<= '~')
3305 warning("unknown escape sequence: \'\\%c\'", c
);
3307 warning("unknown escape sequence: \'\\x%x\'", c
);
3314 cstr_ccat(outstr
, c
);
3316 cstr_wccat(outstr
, c
);
3318 /* add a trailing '\0' */
3320 cstr_ccat(outstr
, '\0');
3322 cstr_wccat(outstr
, '\0');
3325 /* we use 64 bit numbers */
3328 /* bn = (bn << shift) | or_val */
3329 void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
3333 for(i
=0;i
<BN_SIZE
;i
++) {
3335 bn
[i
] = (v
<< shift
) | or_val
;
3336 or_val
= v
>> (32 - shift
);
3340 void bn_zero(unsigned int *bn
)
3343 for(i
=0;i
<BN_SIZE
;i
++) {
3348 /* parse number in null terminated string 'p' and return it in the
3350 void parse_number(const char *p
)
3352 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
3354 unsigned int bn
[BN_SIZE
];
3365 goto float_frac_parse
;
3366 } else if (t
== '0') {
3367 if (ch
== 'x' || ch
== 'X') {
3371 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
3377 /* parse all digits. cannot check octal numbers at this stage
3378 because of floating point constants */
3380 if (ch
>= 'a' && ch
<= 'f')
3382 else if (ch
>= 'A' && ch
<= 'F')
3390 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
3392 error("number too long");
3398 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
3399 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
3401 /* NOTE: strtox should support that for hexa numbers, but
3402 non ISOC99 libcs do not support it, so we prefer to do
3404 /* hexadecimal or binary floats */
3405 /* XXX: handle overflows */
3417 } else if (t
>= 'a') {
3419 } else if (t
>= 'A') {
3424 bn_lshift(bn
, shift
, t
);
3431 if (t
>= 'a' && t
<= 'f') {
3433 } else if (t
>= 'A' && t
<= 'F') {
3435 } else if (t
>= '0' && t
<= '9') {
3441 error("invalid digit");
3442 bn_lshift(bn
, shift
, t
);
3447 if (ch
!= 'p' && ch
!= 'P')
3454 } else if (ch
== '-') {
3458 if (ch
< '0' || ch
> '9')
3459 expect("exponent digits");
3460 while (ch
>= '0' && ch
<= '9') {
3461 exp_val
= exp_val
* 10 + ch
- '0';
3464 exp_val
= exp_val
* s
;
3466 /* now we can generate the number */
3467 /* XXX: should patch directly float number */
3468 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
3469 d
= ldexp(d
, exp_val
- frac_bits
);
3474 /* float : should handle overflow */
3476 } else if (t
== 'L') {
3479 /* XXX: not large enough */
3480 tokc
.ld
= (long double)d
;
3486 /* decimal floats */
3488 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3493 while (ch
>= '0' && ch
<= '9') {
3494 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3500 if (ch
== 'e' || ch
== 'E') {
3501 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3505 if (ch
== '-' || ch
== '+') {
3506 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3511 if (ch
< '0' || ch
> '9')
3512 expect("exponent digits");
3513 while (ch
>= '0' && ch
<= '9') {
3514 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3526 tokc
.f
= strtof(token_buf
, NULL
);
3527 } else if (t
== 'L') {
3530 tokc
.ld
= strtold(token_buf
, NULL
);
3533 tokc
.d
= strtod(token_buf
, NULL
);
3537 unsigned long long n
, n1
;
3540 /* integer number */
3543 if (b
== 10 && *q
== '0') {
3550 /* no need for checks except for base 10 / 8 errors */
3553 } else if (t
>= 'a') {
3555 } else if (t
>= 'A') {
3560 error("invalid digit");
3564 /* detect overflow */
3565 /* XXX: this test is not reliable */
3567 error("integer constant overflow");
3570 /* XXX: not exactly ANSI compliant */
3571 if ((n
& 0xffffffff00000000LL
) != 0) {
3576 } else if (n
> 0x7fffffff) {
3587 error("three 'l's in integer constant");
3590 if (tok
== TOK_CINT
)
3592 else if (tok
== TOK_CUINT
)
3596 } else if (t
== 'U') {
3598 error("two 'u's in integer constant");
3600 if (tok
== TOK_CINT
)
3602 else if (tok
== TOK_CLLONG
)
3609 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
3617 #define PARSE2(c1, tok1, c2, tok2) \
3628 /* return next token without macro substitution */
3629 static inline void next_nomacro1(void)
3649 /* first look if it is in fact an end of buffer */
3650 if (p
>= file
->buf_end
) {
3654 if (p
>= file
->buf_end
)
3667 TCCState
*s1
= tcc_state
;
3668 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
3669 && !(tok_flags
& TOK_FLAG_EOF
)) {
3670 tok_flags
|= TOK_FLAG_EOF
;
3672 goto keep_tok_flags
;
3673 } else if (s1
->include_stack_ptr
== s1
->include_stack
||
3674 !(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3675 /* no include left : end of file. */
3678 tok_flags
&= ~TOK_FLAG_EOF
;
3679 /* pop include file */
3681 /* test if previous '#endif' was after a #ifdef at
3683 if (tok_flags
& TOK_FLAG_ENDIF
) {
3685 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
3687 add_cached_include(s1
, file
->inc_type
, file
->inc_filename
,
3688 file
->ifndef_macro_saved
);
3691 /* add end of include file debug info */
3693 put_stabd(N_EINCL
, 0, 0);
3695 /* pop include stack */
3697 s1
->include_stack_ptr
--;
3698 file
= *s1
->include_stack_ptr
;
3707 tok_flags
|= TOK_FLAG_BOL
;
3709 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
3712 goto keep_tok_flags
;
3717 if ((tok_flags
& TOK_FLAG_BOL
) &&
3718 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3720 preprocess(tok_flags
& TOK_FLAG_BOF
);
3726 tok
= TOK_TWOSHARPS
;
3728 if (parse_flags
& PARSE_FLAG_ASM_COMMENTS
) {
3729 p
= parse_line_comment(p
- 1);
3738 case 'a': case 'b': case 'c': case 'd':
3739 case 'e': case 'f': case 'g': case 'h':
3740 case 'i': case 'j': case 'k': case 'l':
3741 case 'm': case 'n': case 'o': case 'p':
3742 case 'q': case 'r': case 's': case 't':
3743 case 'u': case 'v': case 'w': case 'x':
3745 case 'A': case 'B': case 'C': case 'D':
3746 case 'E': case 'F': case 'G': case 'H':
3747 case 'I': case 'J': case 'K':
3748 case 'M': case 'N': case 'O': case 'P':
3749 case 'Q': case 'R': case 'S': case 'T':
3750 case 'U': case 'V': case 'W': case 'X':
3756 h
= TOK_HASH_FUNC(h
, c
);
3760 if (!isidnum_table
[c
])
3762 h
= TOK_HASH_FUNC(h
, c
);
3769 /* fast case : no stray found, so we have the full token
3770 and we have already hashed it */
3772 h
&= (TOK_HASH_SIZE
- 1);
3773 pts
= &hash_ident
[h
];
3778 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
3780 pts
= &(ts
->hash_next
);
3782 ts
= tok_alloc_new(pts
, p1
, len
);
3786 cstr_reset(&tokcstr
);
3789 cstr_ccat(&tokcstr
, *p1
);
3795 while (isidnum_table
[c
]) {
3796 cstr_ccat(&tokcstr
, c
);
3799 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
3805 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
3807 goto parse_ident_fast
;
3810 if (c
== '\'' || c
== '\"') {
3814 cstr_reset(&tokcstr
);
3815 cstr_ccat(&tokcstr
, 'L');
3816 goto parse_ident_slow
;
3820 case '0': case '1': case '2': case '3':
3821 case '4': case '5': case '6': case '7':
3824 cstr_reset(&tokcstr
);
3825 /* after the first digit, accept digits, alpha, '.' or sign if
3826 prefixed by 'eEpP' */
3830 cstr_ccat(&tokcstr
, c
);
3832 if (!(isnum(c
) || isid(c
) || c
== '.' ||
3833 ((c
== '+' || c
== '-') &&
3834 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
3837 /* We add a trailing '\0' to ease parsing */
3838 cstr_ccat(&tokcstr
, '\0');
3839 tokc
.cstr
= &tokcstr
;
3843 /* special dot handling because it can also start a number */
3846 cstr_reset(&tokcstr
);
3847 cstr_ccat(&tokcstr
, '.');
3849 } else if (c
== '.') {
3869 /* parse the string */
3871 p
= parse_pp_string(p
, sep
, &str
);
3872 cstr_ccat(&str
, '\0');
3874 /* eval the escape (should be done as TOK_PPNUM) */
3875 cstr_reset(&tokcstr
);
3876 parse_escape_string(&tokcstr
, str
.data
, is_long
);
3881 /* XXX: make it portable */
3885 char_size
= sizeof(nwchar_t
);
3886 if (tokcstr
.size
<= char_size
)
3887 error("empty character constant");
3888 if (tokcstr
.size
> 2 * char_size
)
3889 warning("multi-character character constant");
3891 tokc
.i
= *(int8_t *)tokcstr
.data
;
3894 tokc
.i
= *(nwchar_t
*)tokcstr
.data
;
3898 tokc
.cstr
= &tokcstr
;
3912 } else if (c
== '<') {
3930 } else if (c
== '>') {
3948 } else if (c
== '=') {
3961 } else if (c
== '=') {
3974 } else if (c
== '=') {
3987 } else if (c
== '=') {
3990 } else if (c
== '>') {
3998 PARSE2('!', '!', '=', TOK_NE
)
3999 PARSE2('=', '=', '=', TOK_EQ
)
4000 PARSE2('*', '*', '=', TOK_A_MUL
)
4001 PARSE2('%', '%', '=', TOK_A_MOD
)
4002 PARSE2('^', '^', '=', TOK_A_XOR
)
4004 /* comments or operator */
4008 p
= parse_comment(p
);
4010 } else if (c
== '/') {
4011 p
= parse_line_comment(p
);
4013 } else if (c
== '=') {
4033 case '$': /* only used in assembler */
4034 case '@': /* dito */
4039 error("unrecognized character \\x%02x", c
);
4045 #if defined(PARSE_DEBUG)
4046 printf("token = %s\n", get_tok_str(tok
, &tokc
));
4050 /* return next token without macro substitution. Can read input from
4052 static void next_nomacro(void)
4058 TOK_GET(tok
, macro_ptr
, tokc
);
4059 if (tok
== TOK_LINENUM
) {
4060 file
->line_num
= tokc
.i
;
4069 /* substitute args in macro_str and return allocated string */
4070 static int *macro_arg_subst(Sym
**nested_list
, int *macro_str
, Sym
*args
)
4072 int *st
, last_tok
, t
, notfirst
;
4081 TOK_GET(t
, macro_str
, cval
);
4086 TOK_GET(t
, macro_str
, cval
);
4089 s
= sym_find2(args
, t
);
4096 cstr_ccat(&cstr
, ' ');
4097 TOK_GET(t
, st
, cval
);
4098 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
4103 cstr_ccat(&cstr
, '\0');
4105 printf("stringize: %s\n", (char *)cstr
.data
);
4109 tok_str_add2(&str
, TOK_STR
, &cval
);
4112 tok_str_add2(&str
, t
, &cval
);
4114 } else if (t
>= TOK_IDENT
) {
4115 s
= sym_find2(args
, t
);
4118 /* if '##' is present before or after, no arg substitution */
4119 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
4120 /* special case for var arg macros : ## eats the
4121 ',' if empty VA_ARGS variable. */
4122 /* XXX: test of the ',' is not 100%
4123 reliable. should fix it to avoid security
4125 if (gnu_ext
&& s
->type
.t
&&
4126 last_tok
== TOK_TWOSHARPS
&&
4127 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
4129 /* suppress ',' '##' */
4132 /* suppress '##' and add variable */
4140 TOK_GET(t1
, st
, cval
);
4143 tok_str_add2(&str
, t1
, &cval
);
4147 /* NOTE: the stream cannot be read when macro
4148 substituing an argument */
4149 macro_subst(&str
, nested_list
, st
, NULL
);
4152 tok_str_add(&str
, t
);
4155 tok_str_add2(&str
, t
, &cval
);
4159 tok_str_add(&str
, 0);
4163 static char const ab_month_name
[12][4] =
4165 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
4166 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
4169 /* do macro substitution of current token with macro 's' and add
4170 result to (tok_str,tok_len). 'nested_list' is the list of all
4171 macros we got inside to avoid recursing. Return non zero if no
4172 substitution needs to be done */
4173 static int macro_subst_tok(TokenString
*tok_str
,
4174 Sym
**nested_list
, Sym
*s
, struct macro_level
**can_read_stream
)
4176 Sym
*args
, *sa
, *sa1
;
4177 int mstr_allocated
, parlevel
, *mstr
, t
, t1
;
4184 /* if symbol is a macro, prepare substitution */
4185 /* special macros */
4186 if (tok
== TOK___LINE__
) {
4187 snprintf(buf
, sizeof(buf
), "%d", file
->line_num
);
4191 } else if (tok
== TOK___FILE__
) {
4192 cstrval
= file
->filename
;
4194 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
4199 tm
= localtime(&ti
);
4200 if (tok
== TOK___DATE__
) {
4201 snprintf(buf
, sizeof(buf
), "%s %2d %d",
4202 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
4204 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
4205 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
4212 cstr_cat(&cstr
, cstrval
);
4213 cstr_ccat(&cstr
, '\0');
4215 tok_str_add2(tok_str
, t1
, &cval
);
4220 if (s
->type
.t
== MACRO_FUNC
) {
4221 /* NOTE: we do not use next_nomacro to avoid eating the
4222 next token. XXX: find better solution */
4226 if (t
== 0 && can_read_stream
) {
4227 /* end of macro stream: we must look at the token
4228 after in the file */
4229 struct macro_level
*ml
= *can_read_stream
;
4235 *can_read_stream
= ml
-> prev
;
4240 /* XXX: incorrect with comments */
4241 ch
= file
->buf_ptr
[0];
4242 while (is_space(ch
) || ch
== '\n')
4246 if (t
!= '(') /* no macro subst */
4249 /* argument macro */
4254 /* NOTE: empty args are allowed, except if no args */
4256 /* handle '()' case */
4257 if (!args
&& !sa
&& tok
== ')')
4260 error("macro '%s' used with too many args",
4261 get_tok_str(s
->v
, 0));
4264 /* NOTE: non zero sa->t indicates VA_ARGS */
4265 while ((parlevel
> 0 ||
4267 (tok
!= ',' || sa
->type
.t
))) &&
4271 else if (tok
== ')')
4273 if (tok
!= TOK_LINEFEED
)
4274 tok_str_add2(&str
, tok
, &tokc
);
4277 tok_str_add(&str
, 0);
4278 sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, (int)str
.str
);
4281 /* special case for gcc var args: add an empty
4282 var arg argument if it is omitted */
4283 if (sa
&& sa
->type
.t
&& gnu_ext
)
4293 error("macro '%s' used with too few args",
4294 get_tok_str(s
->v
, 0));
4297 /* now subst each arg */
4298 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
4303 tok_str_free((int *)sa
->c
);
4309 sym_push2(nested_list
, s
->v
, 0, 0);
4310 macro_subst(tok_str
, nested_list
, mstr
, can_read_stream
);
4311 /* pop nested defined symbol */
4313 *nested_list
= sa1
->prev
;
4321 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
4322 return the resulting string (which must be freed). */
4323 static inline int *macro_twosharps(const int *macro_str
)
4326 const int *macro_ptr1
, *start_macro_ptr
, *ptr
, *saved_macro_ptr
;
4328 const char *p1
, *p2
;
4330 TokenString macro_str1
;
4333 start_macro_ptr
= macro_str
;
4334 /* we search the first '##' */
4336 macro_ptr1
= macro_str
;
4337 TOK_GET(t
, macro_str
, cval
);
4338 /* nothing more to do if end of string */
4341 if (*macro_str
== TOK_TWOSHARPS
)
4345 /* we saw '##', so we need more processing to handle it */
4347 tok_str_new(¯o_str1
);
4351 /* add all tokens seen so far */
4352 for(ptr
= start_macro_ptr
; ptr
< macro_ptr1
;) {
4353 TOK_GET(t
, ptr
, cval
);
4354 tok_str_add2(¯o_str1
, t
, &cval
);
4356 saved_macro_ptr
= macro_ptr
;
4357 /* XXX: get rid of the use of macro_ptr here */
4358 macro_ptr
= (int *)macro_str
;
4360 while (*macro_ptr
== TOK_TWOSHARPS
) {
4362 macro_ptr1
= macro_ptr
;
4365 TOK_GET(t
, macro_ptr
, cval
);
4366 /* We concatenate the two tokens if we have an
4367 identifier or a preprocessing number */
4369 p1
= get_tok_str(tok
, &tokc
);
4370 cstr_cat(&cstr
, p1
);
4371 p2
= get_tok_str(t
, &cval
);
4372 cstr_cat(&cstr
, p2
);
4373 cstr_ccat(&cstr
, '\0');
4375 if ((tok
>= TOK_IDENT
|| tok
== TOK_PPNUM
) &&
4376 (t
>= TOK_IDENT
|| t
== TOK_PPNUM
)) {
4377 if (tok
== TOK_PPNUM
) {
4378 /* if number, then create a number token */
4379 /* NOTE: no need to allocate because
4380 tok_str_add2() does it */
4381 cstr_reset(&tokcstr
);
4384 tokc
.cstr
= &tokcstr
;
4386 /* if identifier, we must do a test to
4387 validate we have a correct identifier */
4388 if (t
== TOK_PPNUM
) {
4398 if (!isnum(c
) && !isid(c
))
4402 ts
= tok_alloc(cstr
.data
, strlen(cstr
.data
));
4403 tok
= ts
->tok
; /* modify current token */
4406 const char *str
= cstr
.data
;
4407 const unsigned char *q
;
4409 /* we look for a valid token */
4410 /* XXX: do more extensive checks */
4411 if (!strcmp(str
, ">>=")) {
4413 } else if (!strcmp(str
, "<<=")) {
4415 } else if (strlen(str
) == 2) {
4416 /* search in two bytes table */
4421 if (q
[0] == str
[0] && q
[1] == str
[1])
4428 /* NOTE: because get_tok_str use a static buffer,
4431 p1
= get_tok_str(tok
, &tokc
);
4432 cstr_cat(&cstr
, p1
);
4433 cstr_ccat(&cstr
, '\0');
4434 p2
= get_tok_str(t
, &cval
);
4435 warning("pasting \"%s\" and \"%s\" does not give a valid preprocessing token", cstr
.data
, p2
);
4436 /* cannot merge tokens: just add them separately */
4437 tok_str_add2(¯o_str1
, tok
, &tokc
);
4438 /* XXX: free associated memory ? */
4445 tok_str_add2(¯o_str1
, tok
, &tokc
);
4450 macro_ptr
= (int *)saved_macro_ptr
;
4452 tok_str_add(¯o_str1
, 0);
4453 return macro_str1
.str
;
4457 /* do macro substitution of macro_str and add result to
4458 (tok_str,tok_len). 'nested_list' is the list of all macros we got
4459 inside to avoid recursing. */
4460 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
4461 const int *macro_str
, struct macro_level
** can_read_stream
)
4468 struct macro_level ml
;
4470 /* first scan for '##' operator handling */
4472 macro_str1
= macro_twosharps(ptr
);
4476 /* NOTE: ptr == NULL can only happen if tokens are read from
4477 file stream due to a macro function call */
4480 TOK_GET(t
, ptr
, cval
);
4485 /* if nested substitution, do nothing */
4486 if (sym_find2(*nested_list
, t
))
4489 if (can_read_stream
)
4490 ml
.prev
= *can_read_stream
, *can_read_stream
= &ml
;
4491 macro_ptr
= (int *)ptr
;
4493 ret
= macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
4494 ptr
= (int *)macro_ptr
;
4496 if (can_read_stream
&& *can_read_stream
== &ml
)
4497 *can_read_stream
= ml
.prev
;
4502 tok_str_add2(tok_str
, t
, &cval
);
4506 tok_str_free(macro_str1
);
4509 /* return next token with macro substitution */
4510 static void next(void)
4512 Sym
*nested_list
, *s
;
4514 struct macro_level
*ml
;
4519 /* if not reading from macro substituted string, then try
4520 to substitute macros */
4521 if (tok
>= TOK_IDENT
&&
4522 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
4523 s
= define_find(tok
);
4525 /* we have a macro: we try to substitute */
4529 if (macro_subst_tok(&str
, &nested_list
, s
, &ml
) == 0) {
4530 /* substitution done, NOTE: maybe empty */
4531 tok_str_add(&str
, 0);
4532 macro_ptr
= str
.str
;
4533 macro_ptr_allocated
= str
.str
;
4540 /* end of macro or end of unget buffer */
4541 if (unget_buffer_enabled
) {
4542 macro_ptr
= unget_saved_macro_ptr
;
4543 unget_buffer_enabled
= 0;
4545 /* end of macro string: free it */
4546 tok_str_free(macro_ptr_allocated
);
4553 /* convert preprocessor tokens into C tokens */
4554 if (tok
== TOK_PPNUM
&&
4555 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
4556 parse_number((char *)tokc
.cstr
->data
);
4560 /* push back current token and set current token to 'last_tok'. Only
4561 identifier case handled for labels. */
4562 static inline void unget_tok(int last_tok
)
4566 unget_saved_macro_ptr
= macro_ptr
;
4567 unget_buffer_enabled
= 1;
4568 q
= unget_saved_buffer
;
4571 n
= tok_ext_size(tok
) - 1;
4574 *q
= 0; /* end of token string */
4579 void swap(int *p
, int *q
)
4587 void vsetc(CType
*type
, int r
, CValue
*vc
)
4591 if (vtop
>= vstack
+ (VSTACK_SIZE
- 1))
4592 error("memory full");
4593 /* cannot let cpu flags if other instruction are generated. Also
4594 avoid leaving VT_JMP anywhere except on the top of the stack
4595 because it would complicate the code generator. */
4596 if (vtop
>= vstack
) {
4597 v
= vtop
->r
& VT_VALMASK
;
4598 if (v
== VT_CMP
|| (v
& ~1) == VT_JMP
)
4604 vtop
->r2
= VT_CONST
;
4608 /* push integer constant */
4613 vsetc(&int_type
, VT_CONST
, &cval
);
4616 /* Return a static symbol pointing to a section */
4617 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
4618 unsigned long offset
, unsigned long size
)
4624 sym
= global_identifier_push(v
, type
->t
| VT_STATIC
, 0);
4625 sym
->type
.ref
= type
->ref
;
4626 sym
->r
= VT_CONST
| VT_SYM
;
4627 put_extern_sym(sym
, sec
, offset
, size
);
4631 /* push a reference to a section offset by adding a dummy symbol */
4632 static void vpush_ref(CType
*type
, Section
*sec
, unsigned long offset
, unsigned long size
)
4637 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4638 vtop
->sym
= get_sym_ref(type
, sec
, offset
, size
);
4641 /* define a new external reference to a symbol 'v' of type 'u' */
4642 static Sym
*external_global_sym(int v
, CType
*type
, int r
)
4648 /* push forward reference */
4649 s
= global_identifier_push(v
, type
->t
| VT_EXTERN
, 0);
4650 s
->type
.ref
= type
->ref
;
4651 s
->r
= r
| VT_CONST
| VT_SYM
;
4656 /* define a new external reference to a symbol 'v' of type 'u' */
4657 static Sym
*external_sym(int v
, CType
*type
, int r
)
4663 /* push forward reference */
4664 s
= sym_push(v
, type
, r
| VT_CONST
| VT_SYM
, 0);
4665 s
->type
.t
|= VT_EXTERN
;
4667 if (!is_compatible_types(&s
->type
, type
))
4668 error("incompatible types for redefinition of '%s'",
4669 get_tok_str(v
, NULL
));
4674 /* push a reference to global symbol v */
4675 static void vpush_global_sym(CType
*type
, int v
)
4680 sym
= external_global_sym(v
, type
, 0);
4682 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4686 void vset(CType
*type
, int r
, int v
)
4691 vsetc(type
, r
, &cval
);
4694 void vseti(int r
, int v
)
4710 void vpushv(SValue
*v
)
4712 if (vtop
>= vstack
+ (VSTACK_SIZE
- 1))
4713 error("memory full");
4723 /* save r to the memory stack, and mark it as being free */
4724 void save_reg(int r
)
4726 int l
, saved
, size
, align
;
4730 /* modify all stack values */
4733 for(p
=vstack
;p
<=vtop
;p
++) {
4734 if ((p
->r
& VT_VALMASK
) == r
||
4735 ((p
->type
.t
& VT_BTYPE
) == VT_LLONG
&& (p
->r2
& VT_VALMASK
) == r
)) {
4736 /* must save value on stack if not already done */
4738 /* NOTE: must reload 'r' because r might be equal to r2 */
4739 r
= p
->r
& VT_VALMASK
;
4740 /* store register in the stack */
4742 if ((p
->r
& VT_LVAL
) ||
4743 (!is_float(type
->t
) && (type
->t
& VT_BTYPE
) != VT_LLONG
))
4745 size
= type_size(type
, &align
);
4746 loc
= (loc
- size
) & -align
;
4747 sv
.type
.t
= type
->t
;
4748 sv
.r
= VT_LOCAL
| VT_LVAL
;
4751 #ifdef TCC_TARGET_I386
4752 /* x86 specific: need to pop fp register ST0 if saved */
4753 if (r
== TREG_ST0
) {
4754 o(0xd9dd); /* fstp %st(1) */
4757 /* special long long case */
4758 if ((type
->t
& VT_BTYPE
) == VT_LLONG
) {
4765 /* mark that stack entry as being saved on the stack */
4766 if (p
->r
& VT_LVAL
) {
4767 /* also clear the bounded flag because the
4768 relocation address of the function was stored in
4770 p
->r
= (p
->r
& ~(VT_VALMASK
| VT_BOUNDED
)) | VT_LLOCAL
;
4772 p
->r
= lvalue_type(p
->type
.t
) | VT_LOCAL
;
4780 /* find a register of class 'rc2' with at most one reference on stack.
4781 * If none, call get_reg(rc) */
4782 int get_reg_ex(int rc
, int rc2
)
4787 for(r
=0;r
<NB_REGS
;r
++) {
4788 if (reg_classes
[r
] & rc2
) {
4791 for(p
= vstack
; p
<= vtop
; p
++) {
4792 if ((p
->r
& VT_VALMASK
) == r
||
4793 (p
->r2
& VT_VALMASK
) == r
)
4803 /* find a free register of class 'rc'. If none, save one register */
4809 /* find a free register */
4810 for(r
=0;r
<NB_REGS
;r
++) {
4811 if (reg_classes
[r
] & rc
) {
4812 for(p
=vstack
;p
<=vtop
;p
++) {
4813 if ((p
->r
& VT_VALMASK
) == r
||
4814 (p
->r2
& VT_VALMASK
) == r
)
4822 /* no register left : free the first one on the stack (VERY
4823 IMPORTANT to start from the bottom to ensure that we don't
4824 spill registers used in gen_opi()) */
4825 for(p
=vstack
;p
<=vtop
;p
++) {
4826 r
= p
->r
& VT_VALMASK
;
4827 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
))
4829 /* also look at second register (if long long) */
4830 r
= p
->r2
& VT_VALMASK
;
4831 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
)) {
4837 /* Should never comes here */
4841 /* save registers up to (vtop - n) stack entry */
4842 void save_regs(int n
)
4847 for(p
= vstack
;p
<= p1
; p
++) {
4848 r
= p
->r
& VT_VALMASK
;
4855 /* move register 's' to 'r', and flush previous value of r to memory
4857 void move_reg(int r
, int s
)
4870 /* get address of vtop (vtop MUST BE an lvalue) */
4873 vtop
->r
&= ~VT_LVAL
;
4874 /* tricky: if saved lvalue, then we can go back to lvalue */
4875 if ((vtop
->r
& VT_VALMASK
) == VT_LLOCAL
)
4876 vtop
->r
= (vtop
->r
& ~(VT_VALMASK
| VT_LVAL_TYPE
)) | VT_LOCAL
| VT_LVAL
;
4879 #ifdef CONFIG_TCC_BCHECK
4880 /* generate lvalue bound code */
4886 vtop
->r
&= ~VT_MUSTBOUND
;
4887 /* if lvalue, then use checking code before dereferencing */
4888 if (vtop
->r
& VT_LVAL
) {
4889 /* if not VT_BOUNDED value, then make one */
4890 if (!(vtop
->r
& VT_BOUNDED
)) {
4891 lval_type
= vtop
->r
& (VT_LVAL_TYPE
| VT_LVAL
);
4892 /* must save type because we must set it to int to get pointer */
4894 vtop
->type
.t
= VT_INT
;
4897 gen_bounded_ptr_add();
4898 vtop
->r
|= lval_type
;
4901 /* then check for dereferencing */
4902 gen_bounded_ptr_deref();
4907 /* store vtop a register belonging to class 'rc'. lvalues are
4908 converted to values. Cannot be used if cannot be converted to
4909 register value (such as structures). */
4912 int r
, r2
, rc2
, bit_pos
, bit_size
, size
, align
, i
;
4913 unsigned long long ll
;
4915 /* NOTE: get_reg can modify vstack[] */
4916 if (vtop
->type
.t
& VT_BITFIELD
) {
4917 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
4918 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
4919 /* remove bit field info to avoid loops */
4920 vtop
->type
.t
&= ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
4921 /* generate shifts */
4922 vpushi(32 - (bit_pos
+ bit_size
));
4924 vpushi(32 - bit_size
);
4925 /* NOTE: transformed to SHR if unsigned */
4929 if (is_float(vtop
->type
.t
) &&
4930 (vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4933 unsigned long offset
;
4934 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
4938 /* XXX: unify with initializers handling ? */
4939 /* CPUs usually cannot use float constants, so we store them
4940 generically in data segment */
4941 size
= type_size(&vtop
->type
, &align
);
4942 offset
= (data_section
->data_offset
+ align
- 1) & -align
;
4943 data_section
->data_offset
= offset
;
4944 /* XXX: not portable yet */
4946 /* Zero pad x87 tenbyte long doubles */
4948 vtop
->c
.tab
[2] &= 0xffff;
4950 ptr
= section_ptr_add(data_section
, size
);
4952 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
4956 ptr
[i
] = vtop
->c
.tab
[size
-1-i
];
4960 ptr
[i
] = vtop
->c
.tab
[i
];
4961 sym
= get_sym_ref(&vtop
->type
, data_section
, offset
, size
<< 2);
4962 vtop
->r
|= VT_LVAL
| VT_SYM
;
4966 #ifdef CONFIG_TCC_BCHECK
4967 if (vtop
->r
& VT_MUSTBOUND
)
4971 r
= vtop
->r
& VT_VALMASK
;
4972 /* need to reload if:
4974 - lvalue (need to dereference pointer)
4975 - already a register, but not in the right class */
4976 if (r
>= VT_CONST
||
4977 (vtop
->r
& VT_LVAL
) ||
4978 !(reg_classes
[r
] & rc
) ||
4979 ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
&&
4980 !(reg_classes
[vtop
->r2
] & rc
))) {
4982 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
) {
4983 /* two register type load : expand to two words
4985 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4988 vtop
->c
.ui
= ll
; /* first word */
4990 vtop
->r
= r
; /* save register value */
4991 vpushi(ll
>> 32); /* second word */
4992 } else if (r
>= VT_CONST
|| /* XXX: test to VT_CONST incorrect ? */
4993 (vtop
->r
& VT_LVAL
)) {
4994 /* We do not want to modifier the long long
4995 pointer here, so the safest (and less
4996 efficient) is to save all the other registers
4997 in the stack. XXX: totally inefficient. */
4999 /* load from memory */
5002 vtop
[-1].r
= r
; /* save register value */
5003 /* increment pointer to get second word */
5004 vtop
->type
.t
= VT_INT
;
5010 /* move registers */
5013 vtop
[-1].r
= r
; /* save register value */
5014 vtop
->r
= vtop
[-1].r2
;
5016 /* allocate second register */
5023 /* write second register */
5025 } else if ((vtop
->r
& VT_LVAL
) && !is_float(vtop
->type
.t
)) {
5027 /* lvalue of scalar type : need to use lvalue type
5028 because of possible cast */
5031 /* compute memory access type */
5032 if (vtop
->r
& VT_LVAL_BYTE
)
5034 else if (vtop
->r
& VT_LVAL_SHORT
)
5036 if (vtop
->r
& VT_LVAL_UNSIGNED
)
5040 /* restore wanted type */
5043 /* one register type load */
5048 #ifdef TCC_TARGET_C67
5049 /* uses register pairs for doubles */
5050 if ((vtop
->type
.t
& VT_BTYPE
) == VT_DOUBLE
)
5057 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
5058 void gv2(int rc1
, int rc2
)
5062 /* generate more generic register first. But VT_JMP or VT_CMP
5063 values must be generated first in all cases to avoid possible
5065 v
= vtop
[0].r
& VT_VALMASK
;
5066 if (v
!= VT_CMP
&& (v
& ~1) != VT_JMP
&& rc1
<= rc2
) {
5071 /* test if reload is needed for first register */
5072 if ((vtop
[-1].r
& VT_VALMASK
) >= VT_CONST
) {
5082 /* test if reload is needed for first register */
5083 if ((vtop
[0].r
& VT_VALMASK
) >= VT_CONST
) {
5089 /* expand long long on stack in two int registers */
5094 u
= vtop
->type
.t
& VT_UNSIGNED
;
5097 vtop
[0].r
= vtop
[-1].r2
;
5098 vtop
[0].r2
= VT_CONST
;
5099 vtop
[-1].r2
= VT_CONST
;
5100 vtop
[0].type
.t
= VT_INT
| u
;
5101 vtop
[-1].type
.t
= VT_INT
| u
;
5104 #ifdef TCC_TARGET_ARM
5105 /* expand long long on stack */
5106 void lexpand_nr(void)
5110 u
= vtop
->type
.t
& VT_UNSIGNED
;
5112 vtop
->r2
= VT_CONST
;
5113 vtop
->type
.t
= VT_INT
| u
;
5114 v
=vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
);
5115 if (v
== VT_CONST
) {
5116 vtop
[-1].c
.ui
= vtop
->c
.ull
;
5117 vtop
->c
.ui
= vtop
->c
.ull
>> 32;
5119 } else if (v
== (VT_LVAL
|VT_CONST
) || v
== (VT_LVAL
|VT_LOCAL
)) {
5121 vtop
->r
= vtop
[-1].r
;
5122 } else if (v
> VT_CONST
) {
5126 vtop
->r
= vtop
[-1].r2
;
5127 vtop
[-1].r2
= VT_CONST
;
5128 vtop
[-1].type
.t
= VT_INT
| u
;
5132 /* build a long long from two ints */
5135 gv2(RC_INT
, RC_INT
);
5136 vtop
[-1].r2
= vtop
[0].r
;
5137 vtop
[-1].type
.t
= t
;
5141 /* rotate n first stack elements to the bottom
5142 I1 ... In -> I2 ... In I1 [top is right]
5150 for(i
=-n
+1;i
!=0;i
++)
5151 vtop
[i
] = vtop
[i
+1];
5155 /* rotate n first stack elements to the top
5156 I1 ... In -> In I1 ... I(n-1) [top is right]
5164 for(i
= 0;i
< n
- 1; i
++)
5165 vtop
[-i
] = vtop
[-i
- 1];
5169 #ifdef TCC_TARGET_ARM
5170 /* like vrott but in other direction
5171 In ... I1 -> I(n-1) ... I1 In [top is right]
5179 for(i
= n
- 1; i
> 0; i
--)
5180 vtop
[-i
] = vtop
[-i
+ 1];
5185 /* pop stack value */
5189 v
= vtop
->r
& VT_VALMASK
;
5190 #ifdef TCC_TARGET_I386
5191 /* for x86, we need to pop the FP stack */
5192 if (v
== TREG_ST0
&& !nocode_wanted
) {
5193 o(0xd9dd); /* fstp %st(1) */
5196 if (v
== VT_JMP
|| v
== VT_JMPI
) {
5197 /* need to put correct jump if && or || without test */
5203 /* convert stack entry to register and duplicate its value in another
5211 if ((t
& VT_BTYPE
) == VT_LLONG
) {
5218 /* stack: H L L1 H1 */
5226 /* duplicate value */
5237 load(r1
, &sv
); /* move r to r1 */
5239 /* duplicates value */
5244 /* generate CPU independent (unsigned) long long operations */
5245 void gen_opl(int op
)
5247 int t
, a
, b
, op1
, c
, i
;
5254 func
= TOK___divdi3
;
5257 func
= TOK___udivdi3
;
5260 func
= TOK___moddi3
;
5263 func
= TOK___umoddi3
;
5265 /* call generic long long function */
5266 vpush_global_sym(&func_old_type
, func
);
5271 vtop
->r2
= REG_LRET
;
5284 /* stack: L1 H1 L2 H2 */
5289 vtop
[-2] = vtop
[-3];
5292 /* stack: H1 H2 L1 L2 */
5298 /* stack: H1 H2 L1 L2 ML MH */
5301 /* stack: ML MH H1 H2 L1 L2 */
5305 /* stack: ML MH H1 L2 H2 L1 */
5310 /* stack: ML MH M1 M2 */
5313 } else if (op
== '+' || op
== '-') {
5314 /* XXX: add non carry method too (for MIPS or alpha) */
5320 /* stack: H1 H2 (L1 op L2) */
5323 gen_op(op1
+ 1); /* TOK_xxxC2 */
5326 /* stack: H1 H2 (L1 op L2) */
5329 /* stack: (L1 op L2) H1 H2 */
5331 /* stack: (L1 op L2) (H1 op H2) */
5339 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) {
5340 t
= vtop
[-1].type
.t
;
5344 /* stack: L H shift */
5346 /* constant: simpler */
5347 /* NOTE: all comments are for SHL. the other cases are
5348 done by swaping words */
5359 if (op
!= TOK_SAR
) {
5392 /* XXX: should provide a faster fallback on x86 ? */
5395 func
= TOK___sardi3
;
5398 func
= TOK___shrdi3
;
5401 func
= TOK___shldi3
;
5407 /* compare operations */
5413 /* stack: L1 H1 L2 H2 */
5415 vtop
[-1] = vtop
[-2];
5417 /* stack: L1 L2 H1 H2 */
5420 /* when values are equal, we need to compare low words. since
5421 the jump is inverted, we invert the test too. */
5424 else if (op1
== TOK_GT
)
5426 else if (op1
== TOK_ULT
)
5428 else if (op1
== TOK_UGT
)
5433 if (op1
!= TOK_NE
) {
5437 /* generate non equal test */
5438 /* XXX: NOT PORTABLE yet */
5442 #if defined(TCC_TARGET_I386)
5443 b
= psym(0x850f, 0);
5444 #elif defined(TCC_TARGET_ARM)
5446 o(0x1A000000 | encbranch(ind
, 0, 1));
5447 #elif defined(TCC_TARGET_C67)
5448 error("not implemented");
5450 #error not supported
5454 /* compare low. Always unsigned */
5458 else if (op1
== TOK_LE
)
5460 else if (op1
== TOK_GT
)
5462 else if (op1
== TOK_GE
)
5472 /* handle integer constant optimizations and various machine
5474 void gen_opic(int op
)
5476 int c1
, c2
, t1
, t2
, n
;
5479 typedef unsigned long long U
;
5483 t1
= v1
->type
.t
& VT_BTYPE
;
5484 t2
= v2
->type
.t
& VT_BTYPE
;
5485 l1
= (t1
== VT_LLONG
) ? v1
->c
.ll
: v1
->c
.i
;
5486 l2
= (t2
== VT_LLONG
) ? v2
->c
.ll
: v2
->c
.i
;
5488 /* currently, we cannot do computations with forward symbols */
5489 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5490 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5493 case '+': l1
+= l2
; break;
5494 case '-': l1
-= l2
; break;
5495 case '&': l1
&= l2
; break;
5496 case '^': l1
^= l2
; break;
5497 case '|': l1
|= l2
; break;
5498 case '*': l1
*= l2
; break;
5505 /* if division by zero, generate explicit division */
5508 error("division by zero in constant");
5512 default: l1
/= l2
; break;
5513 case '%': l1
%= l2
; break;
5514 case TOK_UDIV
: l1
= (U
)l1
/ l2
; break;
5515 case TOK_UMOD
: l1
= (U
)l1
% l2
; break;
5518 case TOK_SHL
: l1
<<= l2
; break;
5519 case TOK_SHR
: l1
= (U
)l1
>> l2
; break;
5520 case TOK_SAR
: l1
>>= l2
; break;
5522 case TOK_ULT
: l1
= (U
)l1
< (U
)l2
; break;
5523 case TOK_UGE
: l1
= (U
)l1
>= (U
)l2
; break;
5524 case TOK_EQ
: l1
= l1
== l2
; break;
5525 case TOK_NE
: l1
= l1
!= l2
; break;
5526 case TOK_ULE
: l1
= (U
)l1
<= (U
)l2
; break;
5527 case TOK_UGT
: l1
= (U
)l1
> (U
)l2
; break;
5528 case TOK_LT
: l1
= l1
< l2
; break;
5529 case TOK_GE
: l1
= l1
>= l2
; break;
5530 case TOK_LE
: l1
= l1
<= l2
; break;
5531 case TOK_GT
: l1
= l1
> l2
; break;
5533 case TOK_LAND
: l1
= l1
&& l2
; break;
5534 case TOK_LOR
: l1
= l1
|| l2
; break;
5541 /* if commutative ops, put c2 as constant */
5542 if (c1
&& (op
== '+' || op
== '&' || op
== '^' ||
5543 op
== '|' || op
== '*')) {
5545 c2
= c1
; //c = c1, c1 = c2, c2 = c;
5546 l2
= l1
; //l = l1, l1 = l2, l2 = l;
5548 /* Filter out NOP operations like x*1, x-0, x&-1... */
5549 if (c2
&& (((op
== '*' || op
== '/' || op
== TOK_UDIV
||
5552 ((op
== '+' || op
== '-' || op
== '|' || op
== '^' ||
5553 op
== TOK_SHL
|| op
== TOK_SHR
|| op
== TOK_SAR
) &&
5559 } else if (c2
&& (op
== '*' || op
== TOK_PDIV
|| op
== TOK_UDIV
)) {
5560 /* try to use shifts instead of muls or divs */
5561 if (l2
> 0 && (l2
& (l2
- 1)) == 0) {
5570 else if (op
== TOK_PDIV
)
5576 } else if (c2
&& (op
== '+' || op
== '-') &&
5577 (vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) ==
5578 (VT_CONST
| VT_SYM
)) {
5579 /* symbol + constant case */
5586 if (!nocode_wanted
) {
5587 /* call low level op generator */
5588 if (t1
== VT_LLONG
|| t2
== VT_LLONG
)
5599 /* generate a floating point operation with constant propagation */
5600 void gen_opif(int op
)
5608 /* currently, we cannot do computations with forward symbols */
5609 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5610 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5612 if (v1
->type
.t
== VT_FLOAT
) {
5615 } else if (v1
->type
.t
== VT_DOUBLE
) {
5623 /* NOTE: we only do constant propagation if finite number (not
5624 NaN or infinity) (ANSI spec) */
5625 if (!ieee_finite(f1
) || !ieee_finite(f2
))
5629 case '+': f1
+= f2
; break;
5630 case '-': f1
-= f2
; break;
5631 case '*': f1
*= f2
; break;
5635 error("division by zero in constant");
5640 /* XXX: also handles tests ? */
5644 /* XXX: overflow test ? */
5645 if (v1
->type
.t
== VT_FLOAT
) {
5647 } else if (v1
->type
.t
== VT_DOUBLE
) {
5655 if (!nocode_wanted
) {
5663 static int pointed_size(CType
*type
)
5666 return type_size(pointed_type(type
), &align
);
5669 static inline int is_null_pointer(SValue
*p
)
5671 if ((p
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
5673 return ((p
->type
.t
& VT_BTYPE
) == VT_INT
&& p
->c
.i
== 0) ||
5674 ((p
->type
.t
& VT_BTYPE
) == VT_LLONG
&& p
->c
.ll
== 0);
5677 static inline int is_integer_btype(int bt
)
5679 return (bt
== VT_BYTE
|| bt
== VT_SHORT
||
5680 bt
== VT_INT
|| bt
== VT_LLONG
);
5683 /* check types for comparison or substraction of pointers */
5684 static void check_comparison_pointer_types(SValue
*p1
, SValue
*p2
, int op
)
5686 CType
*type1
, *type2
, tmp_type1
, tmp_type2
;
5689 /* null pointers are accepted for all comparisons as gcc */
5690 if (is_null_pointer(p1
) || is_null_pointer(p2
))
5694 bt1
= type1
->t
& VT_BTYPE
;
5695 bt2
= type2
->t
& VT_BTYPE
;
5696 /* accept comparison between pointer and integer with a warning */
5697 if ((is_integer_btype(bt1
) || is_integer_btype(bt2
)) && op
!= '-') {
5698 if (op
!= TOK_LOR
&& op
!= TOK_LAND
)
5699 warning("comparison between pointer and integer");
5703 /* both must be pointers or implicit function pointers */
5704 if (bt1
== VT_PTR
) {
5705 type1
= pointed_type(type1
);
5706 } else if (bt1
!= VT_FUNC
)
5707 goto invalid_operands
;
5709 if (bt2
== VT_PTR
) {
5710 type2
= pointed_type(type2
);
5711 } else if (bt2
!= VT_FUNC
) {
5713 error("invalid operands to binary %s", get_tok_str(op
, NULL
));
5715 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
5716 (type2
->t
& VT_BTYPE
) == VT_VOID
)
5720 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5721 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5722 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
5723 /* gcc-like error if '-' is used */
5725 goto invalid_operands
;
5727 warning("comparison of distinct pointer types lacks a cast");
5731 /* generic gen_op: handles types problems */
5734 int u
, t1
, t2
, bt1
, bt2
, t
;
5737 t1
= vtop
[-1].type
.t
;
5738 t2
= vtop
[0].type
.t
;
5739 bt1
= t1
& VT_BTYPE
;
5740 bt2
= t2
& VT_BTYPE
;
5742 if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
5743 /* at least one operand is a pointer */
5744 /* relationnal op: must be both pointers */
5745 if (op
>= TOK_ULT
&& op
<= TOK_LOR
) {
5746 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5747 /* pointers are handled are unsigned */
5748 t
= VT_INT
| VT_UNSIGNED
;
5751 /* if both pointers, then it must be the '-' op */
5752 if (bt1
== VT_PTR
&& bt2
== VT_PTR
) {
5754 error("cannot use pointers here");
5755 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5756 /* XXX: check that types are compatible */
5757 u
= pointed_size(&vtop
[-1].type
);
5759 /* set to integer type */
5760 vtop
->type
.t
= VT_INT
;
5764 /* exactly one pointer : must be '+' or '-'. */
5765 if (op
!= '-' && op
!= '+')
5766 error("cannot use pointers here");
5767 /* Put pointer as first operand */
5768 if (bt2
== VT_PTR
) {
5772 type1
= vtop
[-1].type
;
5773 /* XXX: cast to int ? (long long case) */
5774 vpushi(pointed_size(&vtop
[-1].type
));
5776 #ifdef CONFIG_TCC_BCHECK
5777 /* if evaluating constant expression, no code should be
5778 generated, so no bound check */
5779 if (do_bounds_check
&& !const_wanted
) {
5780 /* if bounded pointers, we generate a special code to
5787 gen_bounded_ptr_add();
5793 /* put again type if gen_opic() swaped operands */
5796 } else if (is_float(bt1
) || is_float(bt2
)) {
5797 /* compute bigger type and do implicit casts */
5798 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
5800 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
5805 /* floats can only be used for a few operations */
5806 if (op
!= '+' && op
!= '-' && op
!= '*' && op
!= '/' &&
5807 (op
< TOK_ULT
|| op
> TOK_GT
))
5808 error("invalid operands for binary operation");
5810 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
5811 /* cast to biggest op */
5813 /* convert to unsigned if it does not fit in a long long */
5814 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
5815 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
5819 /* integer operations */
5821 /* convert to unsigned if it does not fit in an integer */
5822 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
5823 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
5826 /* XXX: currently, some unsigned operations are explicit, so
5827 we modify them here */
5828 if (t
& VT_UNSIGNED
) {
5835 else if (op
== TOK_LT
)
5837 else if (op
== TOK_GT
)
5839 else if (op
== TOK_LE
)
5841 else if (op
== TOK_GE
)
5848 /* special case for shifts and long long: we keep the shift as
5850 if (op
== TOK_SHR
|| op
== TOK_SAR
|| op
== TOK_SHL
)
5857 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5858 /* relationnal op: the result is an int */
5859 vtop
->type
.t
= VT_INT
;
5866 /* generic itof for unsigned long long case */
5867 void gen_cvt_itof1(int t
)
5869 if ((vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
)) ==
5870 (VT_LLONG
| VT_UNSIGNED
)) {
5873 vpush_global_sym(&func_old_type
, TOK___ulltof
);
5874 else if (t
== VT_DOUBLE
)
5875 vpush_global_sym(&func_old_type
, TOK___ulltod
);
5877 vpush_global_sym(&func_old_type
, TOK___ulltold
);
5887 /* generic ftoi for unsigned long long case */
5888 void gen_cvt_ftoi1(int t
)
5892 if (t
== (VT_LLONG
| VT_UNSIGNED
)) {
5893 /* not handled natively */
5894 st
= vtop
->type
.t
& VT_BTYPE
;
5896 vpush_global_sym(&func_old_type
, TOK___fixunssfdi
);
5897 else if (st
== VT_DOUBLE
)
5898 vpush_global_sym(&func_old_type
, TOK___fixunsdfdi
);
5900 vpush_global_sym(&func_old_type
, TOK___fixunsxfdi
);
5905 vtop
->r2
= REG_LRET
;
5911 /* force char or short cast */
5912 void force_charshort_cast(int t
)
5916 /* XXX: add optimization if lvalue : just change type and offset */
5921 if (t
& VT_UNSIGNED
) {
5922 vpushi((1 << bits
) - 1);
5928 /* result must be signed or the SAR is converted to an SHL
5929 This was not the case when "t" was a signed short
5930 and the last value on the stack was an unsigned int */
5931 vtop
->type
.t
&= ~VT_UNSIGNED
;
5937 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
5938 static void gen_cast(CType
*type
)
5940 int sbt
, dbt
, sf
, df
, c
;
5942 /* special delayed cast for char/short */
5943 /* XXX: in some cases (multiple cascaded casts), it may still
5945 if (vtop
->r
& VT_MUSTCAST
) {
5946 vtop
->r
&= ~VT_MUSTCAST
;
5947 force_charshort_cast(vtop
->type
.t
);
5950 /* bitfields first get cast to ints */
5951 if (vtop
->type
.t
& VT_BITFIELD
) {
5955 dbt
= type
->t
& (VT_BTYPE
| VT_UNSIGNED
);
5956 sbt
= vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
);
5958 if (sbt
!= dbt
&& !nocode_wanted
) {
5961 c
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5963 /* convert from fp to fp */
5965 /* constant case: we can do it now */
5966 /* XXX: in ISOC, cannot do it if error in convert */
5967 if (dbt
== VT_FLOAT
&& sbt
== VT_DOUBLE
)
5968 vtop
->c
.f
= (float)vtop
->c
.d
;
5969 else if (dbt
== VT_FLOAT
&& sbt
== VT_LDOUBLE
)
5970 vtop
->c
.f
= (float)vtop
->c
.ld
;
5971 else if (dbt
== VT_DOUBLE
&& sbt
== VT_FLOAT
)
5972 vtop
->c
.d
= (double)vtop
->c
.f
;
5973 else if (dbt
== VT_DOUBLE
&& sbt
== VT_LDOUBLE
)
5974 vtop
->c
.d
= (double)vtop
->c
.ld
;
5975 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_FLOAT
)
5976 vtop
->c
.ld
= (long double)vtop
->c
.f
;
5977 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_DOUBLE
)
5978 vtop
->c
.ld
= (long double)vtop
->c
.d
;
5980 /* non constant case: generate code */
5984 /* convert int to fp */
5987 case VT_LLONG
| VT_UNSIGNED
:
5989 /* XXX: add const cases for long long */
5991 case VT_INT
| VT_UNSIGNED
:
5993 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.ui
; break;
5994 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.ui
; break;
5995 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.ui
; break;
6000 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.i
; break;
6001 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.i
; break;
6002 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.i
; break;
6008 #if !defined(TCC_TARGET_ARM)
6015 /* convert fp to int */
6016 if (dbt
== VT_BOOL
) {
6020 /* we handle char/short/etc... with generic code */
6021 if (dbt
!= (VT_INT
| VT_UNSIGNED
) &&
6022 dbt
!= (VT_LLONG
| VT_UNSIGNED
) &&
6027 case VT_LLONG
| VT_UNSIGNED
:
6029 /* XXX: add const cases for long long */
6031 case VT_INT
| VT_UNSIGNED
:
6033 case VT_FLOAT
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
6034 case VT_DOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
6035 case VT_LDOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
6041 case VT_FLOAT
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
6042 case VT_DOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
6043 case VT_LDOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
6051 if (dbt
== VT_INT
&& (type
->t
& (VT_BTYPE
| VT_UNSIGNED
)) != dbt
) {
6052 /* additional cast for char/short... */
6057 } else if ((dbt
& VT_BTYPE
) == VT_LLONG
) {
6058 if ((sbt
& VT_BTYPE
) != VT_LLONG
) {
6059 /* scalar to long long */
6061 if (sbt
== (VT_INT
| VT_UNSIGNED
))
6062 vtop
->c
.ll
= vtop
->c
.ui
;
6064 vtop
->c
.ll
= vtop
->c
.i
;
6066 /* machine independent conversion */
6068 /* generate high word */
6069 if (sbt
== (VT_INT
| VT_UNSIGNED
)) {
6077 /* patch second register */
6078 vtop
[-1].r2
= vtop
->r
;
6082 } else if (dbt
== VT_BOOL
) {
6083 /* scalar to bool */
6086 } else if ((dbt
& VT_BTYPE
) == VT_BYTE
||
6087 (dbt
& VT_BTYPE
) == VT_SHORT
) {
6088 if (sbt
== VT_PTR
) {
6089 vtop
->type
.t
= VT_INT
;
6090 warning("nonportable conversion from pointer to char/short");
6092 force_charshort_cast(dbt
);
6093 } else if ((dbt
& VT_BTYPE
) == VT_INT
) {
6095 if (sbt
== VT_LLONG
) {
6096 /* from long long: just take low order word */
6100 /* if lvalue and single word type, nothing to do because
6101 the lvalue already contains the real type size (see
6102 VT_LVAL_xxx constants) */
6104 } else if ((dbt
& VT_BTYPE
) == VT_PTR
&& !(vtop
->r
& VT_LVAL
)) {
6105 /* if we are casting between pointer types,
6106 we must update the VT_LVAL_xxx size */
6107 vtop
->r
= (vtop
->r
& ~VT_LVAL_TYPE
)
6108 | (lvalue_type(type
->ref
->type
.t
) & VT_LVAL_TYPE
);
6113 /* return type size. Put alignment at 'a' */
6114 static int type_size(CType
*type
, int *a
)
6119 bt
= type
->t
& VT_BTYPE
;
6120 if (bt
== VT_STRUCT
) {
6125 } else if (bt
== VT_PTR
) {
6126 if (type
->t
& VT_ARRAY
) {
6128 return type_size(&s
->type
, a
) * s
->c
;
6133 } else if (bt
== VT_LDOUBLE
) {
6135 return LDOUBLE_SIZE
;
6136 } else if (bt
== VT_DOUBLE
|| bt
== VT_LLONG
) {
6137 #ifdef TCC_TARGET_I386
6139 #elif defined(TCC_TARGET_ARM)
6149 } else if (bt
== VT_INT
|| bt
== VT_ENUM
|| bt
== VT_FLOAT
) {
6152 } else if (bt
== VT_SHORT
) {
6156 /* char, void, function, _Bool */
6162 /* return the pointed type of t */
6163 static inline CType
*pointed_type(CType
*type
)
6165 return &type
->ref
->type
;
6168 /* modify type so that its it is a pointer to type. */
6169 static void mk_pointer(CType
*type
)
6172 s
= sym_push(SYM_FIELD
, type
, 0, -1);
6173 type
->t
= VT_PTR
| (type
->t
& ~VT_TYPE
);
6177 /* compare function types. OLD functions match any new functions */
6178 static int is_compatible_func(CType
*type1
, CType
*type2
)
6184 if (!is_compatible_types(&s1
->type
, &s2
->type
))
6186 /* check func_call */
6187 if (FUNC_CALL(s1
->r
) != FUNC_CALL(s2
->r
))
6189 /* XXX: not complete */
6190 if (s1
->c
== FUNC_OLD
|| s2
->c
== FUNC_OLD
)
6194 while (s1
!= NULL
) {
6197 if (!is_compatible_parameter_types(&s1
->type
, &s2
->type
))
6207 /* return true if type1 and type2 are the same. If unqualified is
6208 true, qualifiers on the types are ignored.
6210 - enums are not checked as gcc __builtin_types_compatible_p ()
6212 static int compare_types(CType
*type1
, CType
*type2
, int unqualified
)
6216 t1
= type1
->t
& VT_TYPE
;
6217 t2
= type2
->t
& VT_TYPE
;
6219 /* strip qualifiers before comparing */
6220 t1
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6221 t2
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6223 /* XXX: bitfields ? */
6226 /* test more complicated cases */
6227 bt1
= t1
& VT_BTYPE
;
6228 if (bt1
== VT_PTR
) {
6229 type1
= pointed_type(type1
);
6230 type2
= pointed_type(type2
);
6231 return is_compatible_types(type1
, type2
);
6232 } else if (bt1
== VT_STRUCT
) {
6233 return (type1
->ref
== type2
->ref
);
6234 } else if (bt1
== VT_FUNC
) {
6235 return is_compatible_func(type1
, type2
);
6241 /* return true if type1 and type2 are exactly the same (including
6244 static int is_compatible_types(CType
*type1
, CType
*type2
)
6246 return compare_types(type1
,type2
,0);
6249 /* return true if type1 and type2 are the same (ignoring qualifiers).
6251 static int is_compatible_parameter_types(CType
*type1
, CType
*type2
)
6253 return compare_types(type1
,type2
,1);
6256 /* print a type. If 'varstr' is not NULL, then the variable is also
6257 printed in the type */
6259 /* XXX: add array and function pointers */
6260 void type_to_str(char *buf
, int buf_size
,
6261 CType
*type
, const char *varstr
)
6268 t
= type
->t
& VT_TYPE
;
6271 if (t
& VT_CONSTANT
)
6272 pstrcat(buf
, buf_size
, "const ");
6273 if (t
& VT_VOLATILE
)
6274 pstrcat(buf
, buf_size
, "volatile ");
6275 if (t
& VT_UNSIGNED
)
6276 pstrcat(buf
, buf_size
, "unsigned ");
6306 tstr
= "long double";
6308 pstrcat(buf
, buf_size
, tstr
);
6312 if (bt
== VT_STRUCT
)
6316 pstrcat(buf
, buf_size
, tstr
);
6317 v
= type
->ref
->v
& ~SYM_STRUCT
;
6318 if (v
>= SYM_FIRST_ANOM
)
6319 pstrcat(buf
, buf_size
, "<anonymous>");
6321 pstrcat(buf
, buf_size
, get_tok_str(v
, NULL
));
6325 type_to_str(buf
, buf_size
, &s
->type
, varstr
);
6326 pstrcat(buf
, buf_size
, "(");
6328 while (sa
!= NULL
) {
6329 type_to_str(buf1
, sizeof(buf1
), &sa
->type
, NULL
);
6330 pstrcat(buf
, buf_size
, buf1
);
6333 pstrcat(buf
, buf_size
, ", ");
6335 pstrcat(buf
, buf_size
, ")");
6339 pstrcpy(buf1
, sizeof(buf1
), "*");
6341 pstrcat(buf1
, sizeof(buf1
), varstr
);
6342 type_to_str(buf
, buf_size
, &s
->type
, buf1
);
6346 pstrcat(buf
, buf_size
, " ");
6347 pstrcat(buf
, buf_size
, varstr
);
6352 /* verify type compatibility to store vtop in 'dt' type, and generate
6354 static void gen_assign_cast(CType
*dt
)
6356 CType
*st
, *type1
, *type2
, tmp_type1
, tmp_type2
;
6357 char buf1
[256], buf2
[256];
6360 st
= &vtop
->type
; /* source type */
6361 dbt
= dt
->t
& VT_BTYPE
;
6362 sbt
= st
->t
& VT_BTYPE
;
6363 if (dt
->t
& VT_CONSTANT
)
6364 warning("assignment of read-only location");
6367 /* special cases for pointers */
6368 /* '0' can also be a pointer */
6369 if (is_null_pointer(vtop
))
6371 /* accept implicit pointer to integer cast with warning */
6372 if (is_integer_btype(sbt
)) {
6373 warning("assignment makes pointer from integer without a cast");
6376 type1
= pointed_type(dt
);
6377 /* a function is implicitely a function pointer */
6378 if (sbt
== VT_FUNC
) {
6379 if ((type1
->t
& VT_BTYPE
) != VT_VOID
&&
6380 !is_compatible_types(pointed_type(dt
), st
))
6387 type2
= pointed_type(st
);
6388 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
6389 (type2
->t
& VT_BTYPE
) == VT_VOID
) {
6390 /* void * can match anything */
6392 /* exact type match, except for unsigned */
6395 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
6396 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
6397 if (!is_compatible_types(&tmp_type1
, &tmp_type2
))
6398 warning("assignment from incompatible pointer type");
6400 /* check const and volatile */
6401 if ((!(type1
->t
& VT_CONSTANT
) && (type2
->t
& VT_CONSTANT
)) ||
6402 (!(type1
->t
& VT_VOLATILE
) && (type2
->t
& VT_VOLATILE
)))
6403 warning("assignment discards qualifiers from pointer target type");
6409 if (sbt
== VT_PTR
|| sbt
== VT_FUNC
) {
6410 warning("assignment makes integer from pointer without a cast");
6412 /* XXX: more tests */
6417 tmp_type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6418 tmp_type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6419 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
6421 type_to_str(buf1
, sizeof(buf1
), st
, NULL
);
6422 type_to_str(buf2
, sizeof(buf2
), dt
, NULL
);
6423 error("cannot cast '%s' to '%s'", buf1
, buf2
);
6431 /* store vtop in lvalue pushed on stack */
6434 int sbt
, dbt
, ft
, r
, t
, size
, align
, bit_size
, bit_pos
, rc
, delayed_cast
;
6436 ft
= vtop
[-1].type
.t
;
6437 sbt
= vtop
->type
.t
& VT_BTYPE
;
6438 dbt
= ft
& VT_BTYPE
;
6439 if (((sbt
== VT_INT
|| sbt
== VT_SHORT
) && dbt
== VT_BYTE
) ||
6440 (sbt
== VT_INT
&& dbt
== VT_SHORT
)) {
6441 /* optimize char/short casts */
6442 delayed_cast
= VT_MUSTCAST
;
6443 vtop
->type
.t
= ft
& VT_TYPE
;
6444 /* XXX: factorize */
6445 if (ft
& VT_CONSTANT
)
6446 warning("assignment of read-only location");
6449 if (!(ft
& VT_BITFIELD
))
6450 gen_assign_cast(&vtop
[-1].type
);
6453 if (sbt
== VT_STRUCT
) {
6454 /* if structure, only generate pointer */
6455 /* structure assignment : generate memcpy */
6456 /* XXX: optimize if small size */
6457 if (!nocode_wanted
) {
6458 size
= type_size(&vtop
->type
, &align
);
6462 vpush_global_sym(&func_old_type
, TOK_memcpy8
);
6463 else if(!(align
& 3))
6464 vpush_global_sym(&func_old_type
, TOK_memcpy4
);
6467 vpush_global_sym(&func_old_type
, TOK_memcpy
);
6471 vtop
->type
.t
= VT_INT
;
6475 vtop
->type
.t
= VT_INT
;
6487 /* leave source on stack */
6488 } else if (ft
& VT_BITFIELD
) {
6489 /* bitfield store handling */
6490 bit_pos
= (ft
>> VT_STRUCT_SHIFT
) & 0x3f;
6491 bit_size
= (ft
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
6492 /* remove bit field info to avoid loops */
6493 vtop
[-1].type
.t
= ft
& ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
6495 /* duplicate source into other register */
6500 /* duplicate destination */
6502 vtop
[-1] = vtop
[-2];
6504 /* mask and shift source */
6505 vpushi((1 << bit_size
) - 1);
6509 /* load destination, mask and or with source */
6511 vpushi(~(((1 << bit_size
) - 1) << bit_pos
));
6517 /* pop off shifted source from "duplicate source..." above */
6521 #ifdef CONFIG_TCC_BCHECK
6522 /* bound check case */
6523 if (vtop
[-1].r
& VT_MUSTBOUND
) {
6529 if (!nocode_wanted
) {
6533 r
= gv(rc
); /* generate value */
6534 /* if lvalue was saved on stack, must read it */
6535 if ((vtop
[-1].r
& VT_VALMASK
) == VT_LLOCAL
) {
6537 t
= get_reg(RC_INT
);
6539 sv
.r
= VT_LOCAL
| VT_LVAL
;
6540 sv
.c
.ul
= vtop
[-1].c
.ul
;
6542 vtop
[-1].r
= t
| VT_LVAL
;
6545 /* two word case handling : store second register at word + 4 */
6546 if ((ft
& VT_BTYPE
) == VT_LLONG
) {
6548 /* convert to int to increment easily */
6549 vtop
->type
.t
= VT_INT
;
6555 /* XXX: it works because r2 is spilled last ! */
6556 store(vtop
->r2
, vtop
- 1);
6560 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
6561 vtop
->r
|= delayed_cast
;
6565 /* post defines POST/PRE add. c is the token ++ or -- */
6566 void inc(int post
, int c
)
6569 vdup(); /* save lvalue */
6571 gv_dup(); /* duplicate value */
6576 vpushi(c
- TOK_MID
);
6578 vstore(); /* store value */
6580 vpop(); /* if post op, return saved value */
6583 /* Parse GNUC __attribute__ extension. Currently, the following
6584 extensions are recognized:
6585 - aligned(n) : set data/function alignment.
6586 - packed : force data alignment to 1
6587 - section(x) : generate data/code in this section.
6588 - unused : currently ignored, but may be used someday.
6589 - regparm(n) : pass function parameters in registers (i386 only)
6591 static void parse_attribute(AttributeDef
*ad
)
6595 while (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
) {
6599 while (tok
!= ')') {
6600 if (tok
< TOK_IDENT
)
6601 expect("attribute name");
6609 expect("section name");
6610 ad
->section
= find_section(tcc_state
, (char *)tokc
.cstr
->data
);
6619 if (n
<= 0 || (n
& (n
- 1)) != 0)
6620 error("alignment must be a positive power of two");
6633 /* currently, no need to handle it because tcc does not
6634 track unused objects */
6638 /* currently, no need to handle it because tcc does not
6639 track unused objects */
6644 FUNC_CALL(ad
->func_attr
) = FUNC_CDECL
;
6649 FUNC_CALL(ad
->func_attr
) = FUNC_STDCALL
;
6651 #ifdef TCC_TARGET_I386
6661 FUNC_CALL(ad
->func_attr
) = FUNC_FASTCALL1
+ n
- 1;
6667 FUNC_CALL(ad
->func_attr
) = FUNC_FASTCALLW
;
6671 FUNC_EXPORT(ad
->func_attr
) = 1;
6674 if (tcc_state
->warn_unsupported
)
6675 warning("'%s' attribute ignored", get_tok_str(t
, NULL
));
6676 /* skip parameters */
6678 int parenthesis
= 0;
6682 else if (tok
== ')')
6685 } while (parenthesis
&& tok
!= -1);
6698 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
6699 static void struct_decl(CType
*type
, int u
)
6701 int a
, v
, size
, align
, maxalign
, c
, offset
;
6702 int bit_size
, bit_pos
, bsize
, bt
, lbit_pos
;
6703 Sym
*s
, *ss
, *ass
, **ps
;
6707 a
= tok
; /* save decl type */
6712 /* struct already defined ? return it */
6714 expect("struct/union/enum name");
6718 error("invalid type");
6725 /* we put an undefined size for struct/union */
6726 s
= sym_push(v
| SYM_STRUCT
, &type1
, 0, -1);
6727 s
->r
= 0; /* default alignment is zero as gcc */
6728 /* put struct/union/enum name in type */
6736 error("struct/union/enum already defined");
6737 /* cannot be empty */
6739 /* non empty enums are not allowed */
6740 if (a
== TOK_ENUM
) {
6744 expect("identifier");
6750 /* enum symbols have static storage */
6751 ss
= sym_push(v
, &int_type
, VT_CONST
, c
);
6752 ss
->type
.t
|= VT_STATIC
;
6757 /* NOTE: we accept a trailing comma */
6767 while (tok
!= '}') {
6768 parse_btype(&btype
, &ad
);
6774 type_decl(&type1
, &ad
, &v
, TYPE_DIRECT
| TYPE_ABSTRACT
);
6775 if (v
== 0 && (type1
.t
& VT_BTYPE
) != VT_STRUCT
)
6776 expect("identifier");
6777 if ((type1
.t
& VT_BTYPE
) == VT_FUNC
||
6778 (type1
.t
& (VT_TYPEDEF
| VT_STATIC
| VT_EXTERN
| VT_INLINE
)))
6779 error("invalid type for '%s'",
6780 get_tok_str(v
, NULL
));
6784 bit_size
= expr_const();
6785 /* XXX: handle v = 0 case for messages */
6787 error("negative width in bit-field '%s'",
6788 get_tok_str(v
, NULL
));
6789 if (v
&& bit_size
== 0)
6790 error("zero width for bit-field '%s'",
6791 get_tok_str(v
, NULL
));
6793 size
= type_size(&type1
, &align
);
6795 if (align
< ad
.aligned
)
6797 } else if (ad
.packed
) {
6799 } else if (*tcc_state
->pack_stack_ptr
) {
6800 if (align
> *tcc_state
->pack_stack_ptr
)
6801 align
= *tcc_state
->pack_stack_ptr
;
6804 if (bit_size
>= 0) {
6805 bt
= type1
.t
& VT_BTYPE
;
6811 error("bitfields must have scalar type");
6813 if (bit_size
> bsize
) {
6814 error("width of '%s' exceeds its type",
6815 get_tok_str(v
, NULL
));
6816 } else if (bit_size
== bsize
) {
6817 /* no need for bit fields */
6819 } else if (bit_size
== 0) {
6820 /* XXX: what to do if only padding in a
6822 /* zero size: means to pad */
6826 /* we do not have enough room ? */
6827 if ((bit_pos
+ bit_size
) > bsize
)
6830 /* XXX: handle LSB first */
6831 type1
.t
|= VT_BITFIELD
|
6832 (bit_pos
<< VT_STRUCT_SHIFT
) |
6833 (bit_size
<< (VT_STRUCT_SHIFT
+ 6));
6834 bit_pos
+= bit_size
;
6839 if (v
!= 0 || (type1
.t
& VT_BTYPE
) == VT_STRUCT
) {
6840 /* add new memory data only if starting
6842 if (lbit_pos
== 0) {
6843 if (a
== TOK_STRUCT
) {
6844 c
= (c
+ align
- 1) & -align
;
6853 if (align
> maxalign
)
6857 printf("add field %s offset=%d",
6858 get_tok_str(v
, NULL
), offset
);
6859 if (type1
.t
& VT_BITFIELD
) {
6860 printf(" pos=%d size=%d",
6861 (type1
.t
>> VT_STRUCT_SHIFT
) & 0x3f,
6862 (type1
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f);
6867 if (v
== 0 && (type1
.t
& VT_BTYPE
) == VT_STRUCT
) {
6869 while ((ass
= ass
->next
) != NULL
) {
6870 ss
= sym_push(ass
->v
, &ass
->type
, 0, offset
+ ass
->c
);
6875 ss
= sym_push(v
| SYM_FIELD
, &type1
, 0, offset
);
6879 if (tok
== ';' || tok
== TOK_EOF
)
6886 /* store size and alignment */
6887 s
->c
= (c
+ maxalign
- 1) & -maxalign
;
6893 /* return 0 if no type declaration. otherwise, return the basic type
6896 static int parse_btype(CType
*type
, AttributeDef
*ad
)
6898 int t
, u
, type_found
, typespec_found
, typedef_found
;
6902 memset(ad
, 0, sizeof(AttributeDef
));
6910 /* currently, we really ignore extension */
6920 if ((t
& VT_BTYPE
) != 0)
6921 error("too many basic types");
6937 if ((t
& VT_BTYPE
) == VT_DOUBLE
) {
6938 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6939 } else if ((t
& VT_BTYPE
) == VT_LONG
) {
6940 t
= (t
& ~VT_BTYPE
) | VT_LLONG
;
6954 if ((t
& VT_BTYPE
) == VT_LONG
) {
6955 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6962 struct_decl(&type1
, VT_ENUM
);
6965 type
->ref
= type1
.ref
;
6969 struct_decl(&type1
, VT_STRUCT
);
6972 /* type modifiers */
7025 /* GNUC attribute */
7026 case TOK_ATTRIBUTE1
:
7027 case TOK_ATTRIBUTE2
:
7028 parse_attribute(ad
);
7035 parse_expr_type(&type1
);
7038 if (typespec_found
|| typedef_found
)
7041 if (!s
|| !(s
->type
.t
& VT_TYPEDEF
))
7044 t
|= (s
->type
.t
& ~VT_TYPEDEF
);
7045 type
->ref
= s
->type
.ref
;
7053 if ((t
& (VT_SIGNED
|VT_UNSIGNED
)) == (VT_SIGNED
|VT_UNSIGNED
))
7054 error("signed and unsigned modifier");
7055 if (tcc_state
->char_is_unsigned
) {
7056 if ((t
& (VT_SIGNED
|VT_UNSIGNED
|VT_BTYPE
)) == VT_BYTE
)
7061 /* long is never used as type */
7062 if ((t
& VT_BTYPE
) == VT_LONG
)
7063 t
= (t
& ~VT_BTYPE
) | VT_INT
;
7068 /* convert a function parameter type (array to pointer and function to
7069 function pointer) */
7070 static inline void convert_parameter_type(CType
*pt
)
7072 /* remove const and volatile qualifiers (XXX: const could be used
7073 to indicate a const function parameter */
7074 pt
->t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7075 /* array must be transformed to pointer according to ANSI C */
7077 if ((pt
->t
& VT_BTYPE
) == VT_FUNC
) {
7082 static void post_type(CType
*type
, AttributeDef
*ad
)
7084 int n
, l
, t1
, arg_size
, align
;
7085 Sym
**plast
, *s
, *first
;
7090 /* function declaration */
7098 /* read param name and compute offset */
7099 if (l
!= FUNC_OLD
) {
7100 if (!parse_btype(&pt
, &ad1
)) {
7102 error("invalid type");
7109 if ((pt
.t
& VT_BTYPE
) == VT_VOID
&& tok
== ')')
7111 type_decl(&pt
, &ad1
, &n
, TYPE_DIRECT
| TYPE_ABSTRACT
);
7112 if ((pt
.t
& VT_BTYPE
) == VT_VOID
)
7113 error("parameter declared as void");
7114 arg_size
+= (type_size(&pt
, &align
) + 3) & ~3;
7119 expect("identifier");
7123 convert_parameter_type(&pt
);
7124 s
= sym_push(n
| SYM_FIELD
, &pt
, 0, 0);
7130 if (l
== FUNC_NEW
&& tok
== TOK_DOTS
) {
7137 /* if no parameters, then old type prototype */
7141 t1
= type
->t
& VT_STORAGE
;
7142 /* NOTE: const is ignored in returned type as it has a special
7143 meaning in gcc / C++ */
7144 type
->t
&= ~(VT_STORAGE
| VT_CONSTANT
);
7145 post_type(type
, ad
);
7146 /* we push a anonymous symbol which will contain the function prototype */
7147 FUNC_ARGS(ad
->func_attr
) = arg_size
;
7148 s
= sym_push(SYM_FIELD
, type
, ad
->func_attr
, l
);
7150 type
->t
= t1
| VT_FUNC
;
7152 } else if (tok
== '[') {
7153 /* array definition */
7159 error("invalid array size");
7162 /* parse next post type */
7163 t1
= type
->t
& VT_STORAGE
;
7164 type
->t
&= ~VT_STORAGE
;
7165 post_type(type
, ad
);
7167 /* we push a anonymous symbol which will contain the array
7169 s
= sym_push(SYM_FIELD
, type
, 0, n
);
7170 type
->t
= t1
| VT_ARRAY
| VT_PTR
;
7175 /* Parse a type declaration (except basic type), and return the type
7176 in 'type'. 'td' is a bitmask indicating which kind of type decl is
7177 expected. 'type' should contain the basic type. 'ad' is the
7178 attribute definition of the basic type. It can be modified by
7181 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
)
7184 CType type1
, *type2
;
7187 while (tok
== '*') {
7195 qualifiers
|= VT_CONSTANT
;
7200 qualifiers
|= VT_VOLATILE
;
7208 type
->t
|= qualifiers
;
7211 /* XXX: clarify attribute handling */
7212 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
7213 parse_attribute(ad
);
7215 /* recursive type */
7216 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
7217 type1
.t
= 0; /* XXX: same as int */
7220 /* XXX: this is not correct to modify 'ad' at this point, but
7221 the syntax is not clear */
7222 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
7223 parse_attribute(ad
);
7224 type_decl(&type1
, ad
, v
, td
);
7227 /* type identifier */
7228 if (tok
>= TOK_IDENT
&& (td
& TYPE_DIRECT
)) {
7232 if (!(td
& TYPE_ABSTRACT
))
7233 expect("identifier");
7237 post_type(type
, ad
);
7238 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
7239 parse_attribute(ad
);
7242 /* append type at the end of type1 */
7255 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
7256 static int lvalue_type(int t
)
7261 if (bt
== VT_BYTE
|| bt
== VT_BOOL
)
7263 else if (bt
== VT_SHORT
)
7267 if (t
& VT_UNSIGNED
)
7268 r
|= VT_LVAL_UNSIGNED
;
7272 /* indirection with full error checking and bound check */
7273 static void indir(void)
7275 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
) {
7276 if ((vtop
->type
.t
& VT_BTYPE
) == VT_FUNC
)
7280 if ((vtop
->r
& VT_LVAL
) && !nocode_wanted
)
7282 vtop
->type
= *pointed_type(&vtop
->type
);
7283 /* Arrays and functions are never lvalues */
7284 if (!(vtop
->type
.t
& VT_ARRAY
)
7285 && (vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
) {
7286 vtop
->r
|= lvalue_type(vtop
->type
.t
);
7287 /* if bound checking, the referenced pointer must be checked */
7288 if (do_bounds_check
)
7289 vtop
->r
|= VT_MUSTBOUND
;
7293 /* pass a parameter to a function and do type checking and casting */
7294 static void gfunc_param_typed(Sym
*func
, Sym
*arg
)
7299 func_type
= func
->c
;
7300 if (func_type
== FUNC_OLD
||
7301 (func_type
== FUNC_ELLIPSIS
&& arg
== NULL
)) {
7302 /* default casting : only need to convert float to double */
7303 if ((vtop
->type
.t
& VT_BTYPE
) == VT_FLOAT
) {
7307 } else if (arg
== NULL
) {
7308 error("too many arguments to function");
7311 type
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
7312 gen_assign_cast(&type
);
7316 /* parse an expression of the form '(type)' or '(expr)' and return its
7318 static void parse_expr_type(CType
*type
)
7324 if (parse_btype(type
, &ad
)) {
7325 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
7332 static void parse_type(CType
*type
)
7337 if (!parse_btype(type
, &ad
)) {
7340 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
7343 static void vpush_tokc(int t
)
7347 vsetc(&type
, VT_CONST
, &tokc
);
7350 static void unary(void)
7352 int n
, t
, align
, size
, r
;
7357 /* XXX: GCC 2.95.3 does not generate a table although it should be
7371 vpush_tokc(VT_INT
| VT_UNSIGNED
);
7375 vpush_tokc(VT_LLONG
);
7379 vpush_tokc(VT_LLONG
| VT_UNSIGNED
);
7383 vpush_tokc(VT_FLOAT
);
7387 vpush_tokc(VT_DOUBLE
);
7391 vpush_tokc(VT_LDOUBLE
);
7394 case TOK___FUNCTION__
:
7396 goto tok_identifier
;
7402 /* special function name identifier */
7403 len
= strlen(funcname
) + 1;
7404 /* generate char[len] type */
7409 vpush_ref(&type
, data_section
, data_section
->data_offset
, len
);
7410 ptr
= section_ptr_add(data_section
, len
);
7411 memcpy(ptr
, funcname
, len
);
7416 #ifdef TCC_TARGET_PE
7417 t
= VT_SHORT
| VT_UNSIGNED
;
7423 /* string parsing */
7426 if (tcc_state
->warn_write_strings
)
7431 memset(&ad
, 0, sizeof(AttributeDef
));
7432 decl_initializer_alloc(&type
, &ad
, VT_CONST
, 2, 0, 0);
7437 if (parse_btype(&type
, &ad
)) {
7438 type_decl(&type
, &ad
, &n
, TYPE_ABSTRACT
);
7440 /* check ISOC99 compound literal */
7442 /* data is allocated locally by default */
7447 /* all except arrays are lvalues */
7448 if (!(type
.t
& VT_ARRAY
))
7449 r
|= lvalue_type(type
.t
);
7450 memset(&ad
, 0, sizeof(AttributeDef
));
7451 decl_initializer_alloc(&type
, &ad
, r
, 1, 0, 0);
7456 } else if (tok
== '{') {
7457 /* save all registers */
7459 /* statement expression : we do not accept break/continue
7460 inside as GCC does */
7461 block(NULL
, NULL
, NULL
, NULL
, 0, 1);
7476 /* functions names must be treated as function pointers,
7477 except for unary '&' and sizeof. Since we consider that
7478 functions are not lvalues, we only have to handle it
7479 there and in function calls. */
7480 /* arrays can also be used although they are not lvalues */
7481 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
&&
7482 !(vtop
->type
.t
& VT_ARRAY
) && !(vtop
->type
.t
& VT_LLOCAL
))
7484 mk_pointer(&vtop
->type
);
7490 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
)
7491 vtop
->c
.i
= !vtop
->c
.i
;
7492 else if ((vtop
->r
& VT_VALMASK
) == VT_CMP
)
7493 vtop
->c
.i
= vtop
->c
.i
^ 1;
7496 vseti(VT_JMP
, gtst(1, 0));
7507 /* in order to force cast, we add zero */
7509 if ((vtop
->type
.t
& VT_BTYPE
) == VT_PTR
)
7510 error("pointer not accepted for unary plus");
7520 parse_expr_type(&type
);
7524 size
= type_size(&type
, &align
);
7525 if (t
== TOK_SIZEOF
) {
7527 error("sizeof applied to an incomplete type");
7532 vtop
->type
.t
|= VT_UNSIGNED
;
7535 case TOK_builtin_types_compatible_p
:
7544 type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7545 type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7546 vpushi(is_compatible_types(&type1
, &type2
));
7549 case TOK_builtin_constant_p
:
7551 int saved_nocode_wanted
, res
;
7554 saved_nocode_wanted
= nocode_wanted
;
7557 res
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
7559 nocode_wanted
= saved_nocode_wanted
;
7579 goto tok_identifier
;
7581 /* allow to take the address of a label */
7582 if (tok
< TOK_UIDENT
)
7583 expect("label identifier");
7584 s
= label_find(tok
);
7586 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
7588 if (s
->r
== LABEL_DECLARED
)
7589 s
->r
= LABEL_FORWARD
;
7592 s
->type
.t
= VT_VOID
;
7593 mk_pointer(&s
->type
);
7594 s
->type
.t
|= VT_STATIC
;
7596 vset(&s
->type
, VT_CONST
| VT_SYM
, 0);
7605 expect("identifier");
7609 error("'%s' undeclared", get_tok_str(t
, NULL
));
7610 /* for simple function calls, we tolerate undeclared
7611 external reference to int() function */
7612 if (tcc_state
->warn_implicit_function_declaration
)
7613 warning("implicit declaration of function '%s'",
7614 get_tok_str(t
, NULL
));
7615 s
= external_global_sym(t
, &func_old_type
, 0);
7617 if ((s
->type
.t
& (VT_STATIC
| VT_INLINE
| VT_BTYPE
)) ==
7618 (VT_STATIC
| VT_INLINE
| VT_FUNC
)) {
7619 /* if referencing an inline function, then we generate a
7620 symbol to it if not already done. It will have the
7621 effect to generate code for it at the end of the
7622 compilation unit. Inline function as always
7623 generated in the text section. */
7625 put_extern_sym(s
, text_section
, 0, 0);
7626 r
= VT_SYM
| VT_CONST
;
7630 vset(&s
->type
, r
, s
->c
);
7631 /* if forward reference, we must point to s */
7632 if (vtop
->r
& VT_SYM
) {
7639 /* post operations */
7641 if (tok
== TOK_INC
|| tok
== TOK_DEC
) {
7644 } else if (tok
== '.' || tok
== TOK_ARROW
) {
7646 if (tok
== TOK_ARROW
)
7651 /* expect pointer on structure */
7652 if ((vtop
->type
.t
& VT_BTYPE
) != VT_STRUCT
)
7653 expect("struct or union");
7657 while ((s
= s
->next
) != NULL
) {
7662 error("field not found: %s", get_tok_str(tok
& ~SYM_FIELD
, NULL
));
7663 /* add field offset to pointer */
7664 vtop
->type
= char_pointer_type
; /* change type to 'char *' */
7667 /* change type to field type, and set to lvalue */
7668 vtop
->type
= s
->type
;
7669 /* an array is never an lvalue */
7670 if (!(vtop
->type
.t
& VT_ARRAY
)) {
7671 vtop
->r
|= lvalue_type(vtop
->type
.t
);
7672 /* if bound checking, the referenced pointer must be checked */
7673 if (do_bounds_check
)
7674 vtop
->r
|= VT_MUSTBOUND
;
7677 } else if (tok
== '[') {
7683 } else if (tok
== '(') {
7689 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
) {
7690 /* pointer test (no array accepted) */
7691 if ((vtop
->type
.t
& (VT_BTYPE
| VT_ARRAY
)) == VT_PTR
) {
7692 vtop
->type
= *pointed_type(&vtop
->type
);
7693 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
)
7697 expect("function pointer");
7700 vtop
->r
&= ~VT_LVAL
; /* no lvalue */
7702 /* get return type */
7705 sa
= s
->next
; /* first parameter */
7708 /* compute first implicit argument if a structure is returned */
7709 if ((s
->type
.t
& VT_BTYPE
) == VT_STRUCT
) {
7710 /* get some space for the returned structure */
7711 size
= type_size(&s
->type
, &align
);
7712 loc
= (loc
- size
) & -align
;
7714 ret
.r
= VT_LOCAL
| VT_LVAL
;
7715 /* pass it as 'int' to avoid structure arg passing
7717 vseti(VT_LOCAL
, loc
);
7722 /* return in register */
7723 if (is_float(ret
.type
.t
)) {
7726 if ((ret
.type
.t
& VT_BTYPE
) == VT_LLONG
)
7735 gfunc_param_typed(s
, sa
);
7745 error("too few arguments to function");
7747 if (!nocode_wanted
) {
7748 gfunc_call(nb_args
);
7750 vtop
-= (nb_args
+ 1);
7753 vsetc(&ret
.type
, ret
.r
, &ret
.c
);
7761 static void uneq(void)
7767 (tok
>= TOK_A_MOD
&& tok
<= TOK_A_DIV
) ||
7768 tok
== TOK_A_XOR
|| tok
== TOK_A_OR
||
7769 tok
== TOK_A_SHL
|| tok
== TOK_A_SAR
) {
7784 static void expr_prod(void)
7789 while (tok
== '*' || tok
== '/' || tok
== '%') {
7797 static void expr_sum(void)
7802 while (tok
== '+' || tok
== '-') {
7810 static void expr_shift(void)
7815 while (tok
== TOK_SHL
|| tok
== TOK_SAR
) {
7823 static void expr_cmp(void)
7828 while ((tok
>= TOK_ULE
&& tok
<= TOK_GT
) ||
7829 tok
== TOK_ULT
|| tok
== TOK_UGE
) {
7837 static void expr_cmpeq(void)
7842 while (tok
== TOK_EQ
|| tok
== TOK_NE
) {
7850 static void expr_and(void)
7853 while (tok
== '&') {
7860 static void expr_xor(void)
7863 while (tok
== '^') {
7870 static void expr_or(void)
7873 while (tok
== '|') {
7880 /* XXX: fix this mess */
7881 static void expr_land_const(void)
7884 while (tok
== TOK_LAND
) {
7891 /* XXX: fix this mess */
7892 static void expr_lor_const(void)
7895 while (tok
== TOK_LOR
) {
7902 /* only used if non constant */
7903 static void expr_land(void)
7908 if (tok
== TOK_LAND
) {
7913 if (tok
!= TOK_LAND
) {
7923 static void expr_lor(void)
7928 if (tok
== TOK_LOR
) {
7933 if (tok
!= TOK_LOR
) {
7943 /* XXX: better constant handling */
7944 static void expr_eq(void)
7946 int tt
, u
, r1
, r2
, rc
, t1
, t2
, bt1
, bt2
;
7948 CType type
, type1
, type2
;
7957 if (tok
== ':' && gnu_ext
) {
7973 if (vtop
!= vstack
) {
7974 /* needed to avoid having different registers saved in
7976 if (is_float(vtop
->type
.t
))
7983 if (tok
== ':' && gnu_ext
) {
7991 sv
= *vtop
; /* save value to handle it later */
7992 vtop
--; /* no vpop so that FP stack is not flushed */
8000 bt1
= t1
& VT_BTYPE
;
8002 bt2
= t2
& VT_BTYPE
;
8003 /* cast operands to correct type according to ISOC rules */
8004 if (is_float(bt1
) || is_float(bt2
)) {
8005 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
8006 type
.t
= VT_LDOUBLE
;
8007 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
8012 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
8013 /* cast to biggest op */
8015 /* convert to unsigned if it does not fit in a long long */
8016 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
8017 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
8018 type
.t
|= VT_UNSIGNED
;
8019 } else if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
8020 /* XXX: test pointer compatibility */
8022 } else if (bt1
== VT_FUNC
|| bt2
== VT_FUNC
) {
8023 /* XXX: test function pointer compatibility */
8025 } else if (bt1
== VT_STRUCT
|| bt2
== VT_STRUCT
) {
8026 /* XXX: test structure compatibility */
8028 } else if (bt1
== VT_VOID
|| bt2
== VT_VOID
) {
8029 /* NOTE: as an extension, we accept void on only one side */
8032 /* integer operations */
8034 /* convert to unsigned if it does not fit in an integer */
8035 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
8036 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
8037 type
.t
|= VT_UNSIGNED
;
8040 /* now we convert second operand */
8042 if (VT_STRUCT
== (vtop
->type
.t
& VT_BTYPE
))
8045 if (is_float(type
.t
)) {
8047 } else if ((type
.t
& VT_BTYPE
) == VT_LLONG
) {
8048 /* for long longs, we use fixed registers to avoid having
8049 to handle a complicated move */
8054 /* this is horrible, but we must also convert first
8058 /* put again first value and cast it */
8061 if (VT_STRUCT
== (vtop
->type
.t
& VT_BTYPE
))
8071 static void gexpr(void)
8082 /* parse an expression and return its type without any side effect. */
8083 static void expr_type(CType
*type
)
8085 int saved_nocode_wanted
;
8087 saved_nocode_wanted
= nocode_wanted
;
8092 nocode_wanted
= saved_nocode_wanted
;
8095 /* parse a unary expression and return its type without any side
8097 static void unary_type(CType
*type
)
8109 /* parse a constant expression and return value in vtop. */
8110 static void expr_const1(void)
8119 /* parse an integer constant and return its value. */
8120 static int expr_const(void)
8124 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
8125 expect("constant expression");
8131 /* return the label token if current token is a label, otherwise
8133 static int is_label(void)
8137 /* fast test first */
8138 if (tok
< TOK_UIDENT
)
8140 /* no need to save tokc because tok is an identifier */
8147 unget_tok(last_tok
);
8152 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
8153 int case_reg
, int is_expr
)
8158 /* generate line number info */
8160 (last_line_num
!= file
->line_num
|| last_ind
!= ind
)) {
8161 put_stabn(N_SLINE
, 0, file
->line_num
, ind
- func_ind
);
8163 last_line_num
= file
->line_num
;
8167 /* default return value is (void) */
8169 vtop
->type
.t
= VT_VOID
;
8172 if (tok
== TOK_IF
) {
8179 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
8181 if (c
== TOK_ELSE
) {
8185 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
8186 gsym(d
); /* patch else jmp */
8189 } else if (tok
== TOK_WHILE
) {
8197 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
8201 } else if (tok
== '{') {
8205 /* record local declaration stack position */
8207 llabel
= local_label_stack
;
8208 /* handle local labels declarations */
8209 if (tok
== TOK_LABEL
) {
8212 if (tok
< TOK_UIDENT
)
8213 expect("label identifier");
8214 label_push(&local_label_stack
, tok
, LABEL_DECLARED
);
8224 while (tok
!= '}') {
8229 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
8232 /* pop locally defined labels */
8233 label_pop(&local_label_stack
, llabel
);
8234 /* pop locally defined symbols */
8235 sym_pop(&local_stack
, s
);
8237 } else if (tok
== TOK_RETURN
) {
8241 gen_assign_cast(&func_vt
);
8242 if ((func_vt
.t
& VT_BTYPE
) == VT_STRUCT
) {
8244 /* if returning structure, must copy it to implicit
8245 first pointer arg location */
8248 size
= type_size(&func_vt
,&align
);
8251 if((vtop
->r
!= (VT_LOCAL
| VT_LVAL
) || (vtop
->c
.i
& 3))
8255 loc
= (loc
- size
) & -4;
8258 vset(&type
, VT_LOCAL
| VT_LVAL
, addr
);
8261 vset(&int_type
, VT_LOCAL
| VT_LVAL
, addr
);
8263 vtop
->type
= int_type
;
8269 vset(&type
, VT_LOCAL
| VT_LVAL
, func_vc
);
8272 /* copy structure value to pointer */
8277 } else if (is_float(func_vt
.t
)) {
8282 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
8285 rsym
= gjmp(rsym
); /* jmp */
8286 } else if (tok
== TOK_BREAK
) {
8289 error("cannot break");
8290 *bsym
= gjmp(*bsym
);
8293 } else if (tok
== TOK_CONTINUE
) {
8296 error("cannot continue");
8297 *csym
= gjmp(*csym
);
8300 } else if (tok
== TOK_FOR
) {
8327 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
8332 if (tok
== TOK_DO
) {
8337 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
8348 if (tok
== TOK_SWITCH
) {
8352 /* XXX: other types than integer */
8353 case_reg
= gv(RC_INT
);
8357 b
= gjmp(0); /* jump to first case */
8359 block(&a
, csym
, &b
, &c
, case_reg
, 0);
8360 /* if no default, jmp after switch */
8368 if (tok
== TOK_CASE
) {
8375 if (gnu_ext
&& tok
== TOK_DOTS
) {
8379 warning("empty case range");
8381 /* since a case is like a label, we must skip it with a jmp */
8388 *case_sym
= gtst(1, 0);
8391 *case_sym
= gtst(1, 0);
8395 *case_sym
= gtst(1, *case_sym
);
8400 goto block_after_label
;
8402 if (tok
== TOK_DEFAULT
) {
8408 error("too many 'default'");
8411 goto block_after_label
;
8413 if (tok
== TOK_GOTO
) {
8415 if (tok
== '*' && gnu_ext
) {
8419 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
8422 } else if (tok
>= TOK_UIDENT
) {
8423 s
= label_find(tok
);
8424 /* put forward definition if needed */
8426 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
8428 if (s
->r
== LABEL_DECLARED
)
8429 s
->r
= LABEL_FORWARD
;
8431 /* label already defined */
8432 if (s
->r
& LABEL_FORWARD
)
8433 s
->next
= (void *)gjmp((long)s
->next
);
8435 gjmp_addr((long)s
->next
);
8438 expect("label identifier");
8441 } else if (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
) {
8449 if (s
->r
== LABEL_DEFINED
)
8450 error("duplicate label '%s'", get_tok_str(s
->v
, NULL
));
8451 gsym((long)s
->next
);
8452 s
->r
= LABEL_DEFINED
;
8454 s
= label_push(&global_label_stack
, b
, LABEL_DEFINED
);
8456 s
->next
= (void *)ind
;
8457 /* we accept this, but it is a mistake */
8460 warning("deprecated use of label at end of compound statement");
8464 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
8467 /* expression case */
8482 /* t is the array or struct type. c is the array or struct
8483 address. cur_index/cur_field is the pointer to the current
8484 value. 'size_only' is true if only size info is needed (only used
8486 static void decl_designator(CType
*type
, Section
*sec
, unsigned long c
,
8487 int *cur_index
, Sym
**cur_field
,
8491 int notfirst
, index
, index_last
, align
, l
, nb_elems
, elem_size
;
8497 if (gnu_ext
&& (l
= is_label()) != 0)
8499 while (tok
== '[' || tok
== '.') {
8501 if (!(type
->t
& VT_ARRAY
))
8502 expect("array type");
8505 index
= expr_const();
8506 if (index
< 0 || (s
->c
>= 0 && index
>= s
->c
))
8507 expect("invalid index");
8508 if (tok
== TOK_DOTS
&& gnu_ext
) {
8510 index_last
= expr_const();
8511 if (index_last
< 0 ||
8512 (s
->c
>= 0 && index_last
>= s
->c
) ||
8514 expect("invalid index");
8520 *cur_index
= index_last
;
8521 type
= pointed_type(type
);
8522 elem_size
= type_size(type
, &align
);
8523 c
+= index
* elem_size
;
8524 /* NOTE: we only support ranges for last designator */
8525 nb_elems
= index_last
- index
+ 1;
8526 if (nb_elems
!= 1) {
8535 if ((type
->t
& VT_BTYPE
) != VT_STRUCT
)
8536 expect("struct/union type");
8549 /* XXX: fix this mess by using explicit storage field */
8551 type1
.t
|= (type
->t
& ~VT_TYPE
);
8565 if (type
->t
& VT_ARRAY
) {
8567 type
= pointed_type(type
);
8568 c
+= index
* type_size(type
, &align
);
8572 error("too many field init");
8573 /* XXX: fix this mess by using explicit storage field */
8575 type1
.t
|= (type
->t
& ~VT_TYPE
);
8580 decl_initializer(type
, sec
, c
, 0, size_only
);
8582 /* XXX: make it more general */
8583 if (!size_only
&& nb_elems
> 1) {
8584 unsigned long c_end
;
8589 error("range init not supported yet for dynamic storage");
8590 c_end
= c
+ nb_elems
* elem_size
;
8591 if (c_end
> sec
->data_allocated
)
8592 section_realloc(sec
, c_end
);
8593 src
= sec
->data
+ c
;
8595 for(i
= 1; i
< nb_elems
; i
++) {
8597 memcpy(dst
, src
, elem_size
);
8603 #define EXPR_CONST 1
8606 /* store a value or an expression directly in global data or in local array */
8607 static void init_putv(CType
*type
, Section
*sec
, unsigned long c
,
8608 int v
, int expr_type
)
8610 int saved_global_expr
, bt
, bit_pos
, bit_size
;
8612 unsigned long long bit_mask
;
8620 /* compound literals must be allocated globally in this case */
8621 saved_global_expr
= global_expr
;
8624 global_expr
= saved_global_expr
;
8625 /* NOTE: symbols are accepted */
8626 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) != VT_CONST
)
8627 error("initializer element is not constant");
8635 dtype
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
8638 /* XXX: not portable */
8639 /* XXX: generate error if incorrect relocation */
8640 gen_assign_cast(&dtype
);
8641 bt
= type
->t
& VT_BTYPE
;
8642 ptr
= sec
->data
+ c
;
8643 /* XXX: make code faster ? */
8644 if (!(type
->t
& VT_BITFIELD
)) {
8649 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
8650 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
8651 bit_mask
= (1LL << bit_size
) - 1;
8653 if ((vtop
->r
& VT_SYM
) &&
8659 (bt
== VT_INT
&& bit_size
!= 32)))
8660 error("initializer element is not computable at load time");
8663 *(char *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8666 *(short *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8669 *(double *)ptr
= vtop
->c
.d
;
8672 *(long double *)ptr
= vtop
->c
.ld
;
8675 *(long long *)ptr
|= (vtop
->c
.ll
& bit_mask
) << bit_pos
;
8678 if (vtop
->r
& VT_SYM
) {
8679 greloc(sec
, vtop
->sym
, c
, R_DATA_32
);
8681 *(int *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8686 vset(&dtype
, VT_LOCAL
|VT_LVAL
, c
);
8693 /* put zeros for variable based init */
8694 static void init_putz(CType
*t
, Section
*sec
, unsigned long c
, int size
)
8697 /* nothing to do because globals are already set to zero */
8699 vpush_global_sym(&func_old_type
, TOK_memset
);
8707 /* 't' contains the type and storage info. 'c' is the offset of the
8708 object in section 'sec'. If 'sec' is NULL, it means stack based
8709 allocation. 'first' is true if array '{' must be read (multi
8710 dimension implicit array init handling). 'size_only' is true if
8711 size only evaluation is wanted (only for arrays). */
8712 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
8713 int first
, int size_only
)
8715 int index
, array_length
, n
, no_oblock
, nb
, parlevel
, i
;
8716 int size1
, align1
, expr_type
;
8720 if (type
->t
& VT_ARRAY
) {
8724 t1
= pointed_type(type
);
8725 size1
= type_size(t1
, &align1
);
8728 if ((first
&& tok
!= TOK_LSTR
&& tok
!= TOK_STR
) ||
8734 /* only parse strings here if correct type (otherwise: handle
8735 them as ((w)char *) expressions */
8736 if ((tok
== TOK_LSTR
&&
8737 #ifdef TCC_TARGET_PE
8738 (t1
->t
& VT_BTYPE
) == VT_SHORT
&& (t1
->t
& VT_UNSIGNED
)
8740 (t1
->t
& VT_BTYPE
) == VT_INT
8742 ) || (tok
== TOK_STR
&& (t1
->t
& VT_BTYPE
) == VT_BYTE
)) {
8743 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
8748 /* compute maximum number of chars wanted */
8750 cstr_len
= cstr
->size
;
8752 cstr_len
= cstr
->size
/ sizeof(nwchar_t
);
8755 if (n
>= 0 && nb
> (n
- array_length
))
8756 nb
= n
- array_length
;
8759 warning("initializer-string for array is too long");
8760 /* in order to go faster for common case (char
8761 string in global variable, we handle it
8763 if (sec
&& tok
== TOK_STR
&& size1
== 1) {
8764 memcpy(sec
->data
+ c
+ array_length
, cstr
->data
, nb
);
8768 ch
= ((unsigned char *)cstr
->data
)[i
];
8770 ch
= ((nwchar_t
*)cstr
->data
)[i
];
8771 init_putv(t1
, sec
, c
+ (array_length
+ i
) * size1
,
8779 /* only add trailing zero if enough storage (no
8780 warning in this case since it is standard) */
8781 if (n
< 0 || array_length
< n
) {
8783 init_putv(t1
, sec
, c
+ (array_length
* size1
), 0, EXPR_VAL
);
8789 while (tok
!= '}') {
8790 decl_designator(type
, sec
, c
, &index
, NULL
, size_only
);
8791 if (n
>= 0 && index
>= n
)
8792 error("index too large");
8793 /* must put zero in holes (note that doing it that way
8794 ensures that it even works with designators) */
8795 if (!size_only
&& array_length
< index
) {
8796 init_putz(t1
, sec
, c
+ array_length
* size1
,
8797 (index
- array_length
) * size1
);
8800 if (index
> array_length
)
8801 array_length
= index
;
8802 /* special test for multi dimensional arrays (may not
8803 be strictly correct if designators are used at the
8805 if (index
>= n
&& no_oblock
)
8814 /* put zeros at the end */
8815 if (!size_only
&& n
>= 0 && array_length
< n
) {
8816 init_putz(t1
, sec
, c
+ array_length
* size1
,
8817 (n
- array_length
) * size1
);
8819 /* patch type size if needed */
8821 s
->c
= array_length
;
8822 } else if ((type
->t
& VT_BTYPE
) == VT_STRUCT
&&
8823 (sec
|| !first
|| tok
== '{')) {
8826 /* NOTE: the previous test is a specific case for automatic
8827 struct/union init */
8828 /* XXX: union needs only one init */
8830 /* XXX: this test is incorrect for local initializers
8831 beginning with ( without {. It would be much more difficult
8832 to do it correctly (ideally, the expression parser should
8833 be used in all cases) */
8839 while (tok
== '(') {
8843 if (!parse_btype(&type1
, &ad1
))
8845 type_decl(&type1
, &ad1
, &n
, TYPE_ABSTRACT
);
8847 if (!is_assignable_types(type
, &type1
))
8848 error("invalid type for cast");
8853 if (first
|| tok
== '{') {
8862 while (tok
!= '}') {
8863 decl_designator(type
, sec
, c
, NULL
, &f
, size_only
);
8865 if (!size_only
&& array_length
< index
) {
8866 init_putz(type
, sec
, c
+ array_length
,
8867 index
- array_length
);
8869 index
= index
+ type_size(&f
->type
, &align1
);
8870 if (index
> array_length
)
8871 array_length
= index
;
8873 if (no_oblock
&& f
== NULL
)
8879 /* put zeros at the end */
8880 if (!size_only
&& array_length
< n
) {
8881 init_putz(type
, sec
, c
+ array_length
,
8890 } else if (tok
== '{') {
8892 decl_initializer(type
, sec
, c
, first
, size_only
);
8894 } else if (size_only
) {
8895 /* just skip expression */
8897 while ((parlevel
> 0 || (tok
!= '}' && tok
!= ',')) &&
8901 else if (tok
== ')')
8906 /* currently, we always use constant expression for globals
8907 (may change for scripting case) */
8908 expr_type
= EXPR_CONST
;
8910 expr_type
= EXPR_ANY
;
8911 init_putv(type
, sec
, c
, 0, expr_type
);
8915 /* parse an initializer for type 't' if 'has_init' is non zero, and
8916 allocate space in local or global data space ('r' is either
8917 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
8918 variable 'v' of scope 'scope' is declared before initializers are
8919 parsed. If 'v' is zero, then a reference to the new object is put
8920 in the value stack. If 'has_init' is 2, a special parsing is done
8921 to handle string constants. */
8922 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
8923 int has_init
, int v
, int scope
)
8925 int size
, align
, addr
, data_offset
;
8927 ParseState saved_parse_state
;
8928 TokenString init_str
;
8931 size
= type_size(type
, &align
);
8932 /* If unknown size, we must evaluate it before
8933 evaluating initializers because
8934 initializers can generate global data too
8935 (e.g. string pointers or ISOC99 compound
8936 literals). It also simplifies local
8937 initializers handling */
8938 tok_str_new(&init_str
);
8941 error("unknown type size");
8942 /* get all init string */
8943 if (has_init
== 2) {
8944 /* only get strings */
8945 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
8946 tok_str_add_tok(&init_str
);
8951 while (level
> 0 || (tok
!= ',' && tok
!= ';')) {
8953 error("unexpected end of file in initializer");
8954 tok_str_add_tok(&init_str
);
8957 else if (tok
== '}') {
8965 tok_str_add(&init_str
, -1);
8966 tok_str_add(&init_str
, 0);
8969 save_parse_state(&saved_parse_state
);
8971 macro_ptr
= init_str
.str
;
8973 decl_initializer(type
, NULL
, 0, 1, 1);
8974 /* prepare second initializer parsing */
8975 macro_ptr
= init_str
.str
;
8978 /* if still unknown size, error */
8979 size
= type_size(type
, &align
);
8981 error("unknown type size");
8983 /* take into account specified alignment if bigger */
8985 if (ad
->aligned
> align
)
8986 align
= ad
->aligned
;
8987 } else if (ad
->packed
) {
8990 if ((r
& VT_VALMASK
) == VT_LOCAL
) {
8992 if (do_bounds_check
&& (type
->t
& VT_ARRAY
))
8994 loc
= (loc
- size
) & -align
;
8996 /* handles bounds */
8997 /* XXX: currently, since we do only one pass, we cannot track
8998 '&' operators, so we add only arrays */
8999 if (do_bounds_check
&& (type
->t
& VT_ARRAY
)) {
9000 unsigned long *bounds_ptr
;
9001 /* add padding between regions */
9003 /* then add local bound info */
9004 bounds_ptr
= section_ptr_add(lbounds_section
, 2 * sizeof(unsigned long));
9005 bounds_ptr
[0] = addr
;
9006 bounds_ptr
[1] = size
;
9009 /* local variable */
9010 sym_push(v
, type
, r
, addr
);
9012 /* push local reference */
9013 vset(type
, r
, addr
);
9019 if (v
&& scope
== VT_CONST
) {
9020 /* see if the symbol was already defined */
9023 if (!is_compatible_types(&sym
->type
, type
))
9024 error("incompatible types for redefinition of '%s'",
9025 get_tok_str(v
, NULL
));
9026 if (sym
->type
.t
& VT_EXTERN
) {
9027 /* if the variable is extern, it was not allocated */
9028 sym
->type
.t
&= ~VT_EXTERN
;
9029 /* set array size if it was ommited in extern
9031 if ((sym
->type
.t
& VT_ARRAY
) &&
9032 sym
->type
.ref
->c
< 0 &&
9034 sym
->type
.ref
->c
= type
->ref
->c
;
9036 /* we accept several definitions of the same
9037 global variable. this is tricky, because we
9038 must play with the SHN_COMMON type of the symbol */
9039 /* XXX: should check if the variable was already
9040 initialized. It is incorrect to initialized it
9042 /* no init data, we won't add more to the symbol */
9049 /* allocate symbol in corresponding section */
9054 else if (tcc_state
->nocommon
)
9058 data_offset
= sec
->data_offset
;
9059 data_offset
= (data_offset
+ align
- 1) & -align
;
9061 /* very important to increment global pointer at this time
9062 because initializers themselves can create new initializers */
9063 data_offset
+= size
;
9064 /* add padding if bound check */
9065 if (do_bounds_check
)
9067 sec
->data_offset
= data_offset
;
9068 /* allocate section space to put the data */
9069 if (sec
->sh_type
!= SHT_NOBITS
&&
9070 data_offset
> sec
->data_allocated
)
9071 section_realloc(sec
, data_offset
);
9072 /* align section if needed */
9073 if (align
> sec
->sh_addralign
)
9074 sec
->sh_addralign
= align
;
9076 addr
= 0; /* avoid warning */
9080 if (scope
!= VT_CONST
|| !sym
) {
9081 sym
= sym_push(v
, type
, r
| VT_SYM
, 0);
9083 /* update symbol definition */
9085 put_extern_sym(sym
, sec
, addr
, size
);
9088 /* put a common area */
9089 put_extern_sym(sym
, NULL
, align
, size
);
9090 /* XXX: find a nicer way */
9091 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
9092 esym
->st_shndx
= SHN_COMMON
;
9097 /* push global reference */
9098 sym
= get_sym_ref(type
, sec
, addr
, size
);
9100 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
9104 /* handles bounds now because the symbol must be defined
9105 before for the relocation */
9106 if (do_bounds_check
) {
9107 unsigned long *bounds_ptr
;
9109 greloc(bounds_section
, sym
, bounds_section
->data_offset
, R_DATA_32
);
9110 /* then add global bound info */
9111 bounds_ptr
= section_ptr_add(bounds_section
, 2 * sizeof(long));
9112 bounds_ptr
[0] = 0; /* relocated */
9113 bounds_ptr
[1] = size
;
9117 decl_initializer(type
, sec
, addr
, 1, 0);
9118 /* restore parse state if needed */
9120 tok_str_free(init_str
.str
);
9121 restore_parse_state(&saved_parse_state
);
9127 void put_func_debug(Sym
*sym
)
9132 /* XXX: we put here a dummy type */
9133 snprintf(buf
, sizeof(buf
), "%s:%c1",
9134 funcname
, sym
->type
.t
& VT_STATIC
? 'f' : 'F');
9135 put_stabs_r(buf
, N_FUN
, 0, file
->line_num
, 0,
9136 cur_text_section
, sym
->c
);
9141 /* parse an old style function declaration list */
9142 /* XXX: check multiple parameter */
9143 static void func_decl_list(Sym
*func_sym
)
9150 /* parse each declaration */
9151 while (tok
!= '{' && tok
!= ';' && tok
!= ',' && tok
!= TOK_EOF
) {
9152 if (!parse_btype(&btype
, &ad
))
9153 expect("declaration list");
9154 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
9155 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
9157 /* we accept no variable after */
9161 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
9162 /* find parameter in function parameter list */
9165 if ((s
->v
& ~SYM_FIELD
) == v
)
9169 error("declaration for parameter '%s' but no such parameter",
9170 get_tok_str(v
, NULL
));
9172 /* check that no storage specifier except 'register' was given */
9173 if (type
.t
& VT_STORAGE
)
9174 error("storage class specified for '%s'", get_tok_str(v
, NULL
));
9175 convert_parameter_type(&type
);
9176 /* we can add the type (NOTE: it could be local to the function) */
9178 /* accept other parameters */
9189 /* parse a function defined by symbol 'sym' and generate its code in
9190 'cur_text_section' */
9191 static void gen_function(Sym
*sym
)
9193 int saved_nocode_wanted
= nocode_wanted
;
9195 ind
= cur_text_section
->data_offset
;
9196 /* NOTE: we patch the symbol size later */
9197 put_extern_sym(sym
, cur_text_section
, ind
, 0);
9198 funcname
= get_tok_str(sym
->v
, NULL
);
9200 /* put debug symbol */
9202 put_func_debug(sym
);
9203 /* push a dummy symbol to enable local sym storage */
9204 sym_push2(&local_stack
, SYM_FIELD
, 0, 0);
9205 gfunc_prolog(&sym
->type
);
9207 block(NULL
, NULL
, NULL
, NULL
, 0, 0);
9210 cur_text_section
->data_offset
= ind
;
9211 label_pop(&global_label_stack
, NULL
);
9212 sym_pop(&local_stack
, NULL
); /* reset local stack */
9213 /* end of function */
9214 /* patch symbol size */
9215 ((Elf32_Sym
*)symtab_section
->data
)[sym
->c
].st_size
=
9218 put_stabn(N_FUN
, 0, 0, ind
- func_ind
);
9220 funcname
= ""; /* for safety */
9221 func_vt
.t
= VT_VOID
; /* for safety */
9222 ind
= 0; /* for safety */
9223 nocode_wanted
= saved_nocode_wanted
;
9226 static void gen_inline_functions(void)
9230 int *str
, inline_generated
;
9232 /* iterate while inline function are referenced */
9234 inline_generated
= 0;
9235 for(sym
= global_stack
; sym
!= NULL
; sym
= sym
->prev
) {
9237 if (((type
->t
& VT_BTYPE
) == VT_FUNC
) &&
9238 (type
->t
& (VT_STATIC
| VT_INLINE
)) ==
9239 (VT_STATIC
| VT_INLINE
) &&
9241 /* the function was used: generate its code and
9242 convert it to a normal function */
9243 str
= INLINE_DEF(sym
->r
);
9244 sym
->r
= VT_SYM
| VT_CONST
;
9245 sym
->type
.t
&= ~VT_INLINE
;
9249 cur_text_section
= text_section
;
9251 macro_ptr
= NULL
; /* fail safe */
9254 inline_generated
= 1;
9257 if (!inline_generated
)
9261 /* free all remaining inline function tokens */
9262 for(sym
= global_stack
; sym
!= NULL
; sym
= sym
->prev
) {
9264 if (((type
->t
& VT_BTYPE
) == VT_FUNC
) &&
9265 (type
->t
& (VT_STATIC
| VT_INLINE
)) ==
9266 (VT_STATIC
| VT_INLINE
)) {
9267 //gr printf("sym %d %s\n", sym->r, get_tok_str(sym->v, NULL));
9268 if (sym
->r
== (VT_SYM
| VT_CONST
)) //gr beware!
9270 str
= INLINE_DEF(sym
->r
);
9272 sym
->r
= 0; /* fail safe */
9277 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
9278 static void decl(int l
)
9286 if (!parse_btype(&btype
, &ad
)) {
9287 /* skip redundant ';' */
9288 /* XXX: find more elegant solution */
9293 if (l
== VT_CONST
&&
9294 (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
)) {
9295 /* global asm block */
9299 /* special test for old K&R protos without explicit int
9300 type. Only accepted when defining global data */
9301 if (l
== VT_LOCAL
|| tok
< TOK_DEFINE
)
9305 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
9306 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
9308 /* we accept no variable after */
9312 while (1) { /* iterate thru each declaration */
9314 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
9318 type_to_str(buf
, sizeof(buf
), t
, get_tok_str(v
, NULL
));
9319 printf("type = '%s'\n", buf
);
9322 if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
9323 /* if old style function prototype, we accept a
9326 if (sym
->c
== FUNC_OLD
)
9327 func_decl_list(sym
);
9332 error("cannot use local functions");
9333 if ((type
.t
& VT_BTYPE
) != VT_FUNC
)
9334 expect("function definition");
9336 /* reject abstract declarators in function definition */
9338 while ((sym
= sym
->next
) != NULL
)
9339 if (!(sym
->v
& ~SYM_FIELD
))
9340 expect("identifier");
9342 /* XXX: cannot do better now: convert extern line to static inline */
9343 if ((type
.t
& (VT_EXTERN
| VT_INLINE
)) == (VT_EXTERN
| VT_INLINE
))
9344 type
.t
= (type
.t
& ~VT_EXTERN
) | VT_STATIC
;
9348 if ((sym
->type
.t
& VT_BTYPE
) != VT_FUNC
)
9350 /* specific case: if not func_call defined, we put
9351 the one of the prototype */
9352 /* XXX: should have default value */
9353 r
= sym
->type
.ref
->r
;
9354 if (FUNC_CALL(r
) != FUNC_CDECL
9355 && FUNC_CALL(type
.ref
->r
) == FUNC_CDECL
)
9356 FUNC_CALL(type
.ref
->r
) = FUNC_CALL(r
);
9358 FUNC_EXPORT(type
.ref
->r
) = 1;
9360 if (!is_compatible_types(&sym
->type
, &type
)) {
9362 error("incompatible types for redefinition of '%s'",
9363 get_tok_str(v
, NULL
));
9365 /* if symbol is already defined, then put complete type */
9368 /* put function symbol */
9369 sym
= global_identifier_push(v
, type
.t
, 0);
9370 sym
->type
.ref
= type
.ref
;
9373 /* static inline functions are just recorded as a kind
9374 of macro. Their code will be emitted at the end of
9375 the compilation unit only if they are used */
9376 if ((type
.t
& (VT_INLINE
| VT_STATIC
)) ==
9377 (VT_INLINE
| VT_STATIC
)) {
9378 TokenString func_str
;
9381 tok_str_new(&func_str
);
9387 error("unexpected end of file");
9388 tok_str_add_tok(&func_str
);
9393 } else if (t
== '}') {
9395 if (block_level
== 0)
9399 tok_str_add(&func_str
, -1);
9400 tok_str_add(&func_str
, 0);
9401 INLINE_DEF(sym
->r
) = func_str
.str
;
9403 /* compute text section */
9404 cur_text_section
= ad
.section
;
9405 if (!cur_text_section
)
9406 cur_text_section
= text_section
;
9407 sym
->r
= VT_SYM
| VT_CONST
;
9412 if (btype
.t
& VT_TYPEDEF
) {
9413 /* save typedefed type */
9414 /* XXX: test storage specifiers ? */
9415 sym
= sym_push(v
, &type
, 0, 0);
9416 sym
->type
.t
|= VT_TYPEDEF
;
9417 } else if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
9418 /* external function definition */
9419 /* specific case for func_call attribute */
9421 type
.ref
->r
= ad
.func_attr
;
9422 external_sym(v
, &type
, 0);
9424 /* not lvalue if array */
9426 if (!(type
.t
& VT_ARRAY
))
9427 r
|= lvalue_type(type
.t
);
9428 has_init
= (tok
== '=');
9429 if ((btype
.t
& VT_EXTERN
) ||
9430 ((type
.t
& VT_ARRAY
) && (type
.t
& VT_STATIC
) &&
9431 !has_init
&& l
== VT_CONST
&& type
.ref
->c
< 0)) {
9432 /* external variable */
9433 /* NOTE: as GCC, uninitialized global static
9434 arrays of null size are considered as
9436 external_sym(v
, &type
, r
);
9438 type
.t
|= (btype
.t
& VT_STATIC
); /* Retain "static". */
9439 if (type
.t
& VT_STATIC
)
9445 decl_initializer_alloc(&type
, &ad
, r
,
9459 /* better than nothing, but needs extension to handle '-E' option
9461 static void preprocess_init(TCCState
*s1
)
9463 s1
->include_stack_ptr
= s1
->include_stack
;
9464 /* XXX: move that before to avoid having to initialize
9465 file->ifdef_stack_ptr ? */
9466 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
9467 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
9469 /* XXX: not ANSI compliant: bound checking says error */
9471 s1
->pack_stack
[0] = 0;
9472 s1
->pack_stack_ptr
= s1
->pack_stack
;
9475 /* compile the C file opened in 'file'. Return non zero if errors. */
9476 static int tcc_compile(TCCState
*s1
)
9480 volatile int section_sym
;
9483 printf("%s: **** new file\n", file
->filename
);
9485 preprocess_init(s1
);
9488 anon_sym
= SYM_FIRST_ANOM
;
9490 /* file info: full path + filename */
9491 section_sym
= 0; /* avoid warning */
9493 section_sym
= put_elf_sym(symtab_section
, 0, 0,
9494 ELF32_ST_INFO(STB_LOCAL
, STT_SECTION
), 0,
9495 text_section
->sh_num
, NULL
);
9496 getcwd(buf
, sizeof(buf
));
9498 normalize_slashes(buf
);
9500 pstrcat(buf
, sizeof(buf
), "/");
9501 put_stabs_r(buf
, N_SO
, 0, 0,
9502 text_section
->data_offset
, text_section
, section_sym
);
9503 put_stabs_r(file
->filename
, N_SO
, 0, 0,
9504 text_section
->data_offset
, text_section
, section_sym
);
9506 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
9507 symbols can be safely used */
9508 put_elf_sym(symtab_section
, 0, 0,
9509 ELF32_ST_INFO(STB_LOCAL
, STT_FILE
), 0,
9510 SHN_ABS
, file
->filename
);
9512 /* define some often used types */
9513 int_type
.t
= VT_INT
;
9515 char_pointer_type
.t
= VT_BYTE
;
9516 mk_pointer(&char_pointer_type
);
9518 func_old_type
.t
= VT_FUNC
;
9519 func_old_type
.ref
= sym_push(SYM_FIELD
, &int_type
, FUNC_CDECL
, FUNC_OLD
);
9521 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
9522 float_type
.t
= VT_FLOAT
;
9523 double_type
.t
= VT_DOUBLE
;
9525 func_float_type
.t
= VT_FUNC
;
9526 func_float_type
.ref
= sym_push(SYM_FIELD
, &float_type
, FUNC_CDECL
, FUNC_OLD
);
9527 func_double_type
.t
= VT_FUNC
;
9528 func_double_type
.ref
= sym_push(SYM_FIELD
, &double_type
, FUNC_CDECL
, FUNC_OLD
);
9532 /* define 'void *alloca(unsigned int)' builtin function */
9537 sym
= sym_push(p
, mk_pointer(VT_VOID
), FUNC_CDECL
, FUNC_NEW
);
9538 s1
= sym_push(SYM_FIELD
, VT_UNSIGNED
| VT_INT
, 0, 0);
9541 sym_push(TOK_alloca
, VT_FUNC
| (p
<< VT_STRUCT_SHIFT
), VT_CONST
, 0);
9545 define_start
= define_stack
;
9548 if (setjmp(s1
->error_jmp_buf
) == 0) {
9550 s1
->error_set_jmp_enabled
= 1;
9552 ch
= file
->buf_ptr
[0];
9553 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
9554 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
;
9558 expect("declaration");
9560 /* end of translation unit info */
9562 put_stabs_r(NULL
, N_SO
, 0, 0,
9563 text_section
->data_offset
, text_section
, section_sym
);
9566 s1
->error_set_jmp_enabled
= 0;
9568 /* reset define stack, but leave -Dsymbols (may be incorrect if
9569 they are undefined) */
9570 free_defines(define_start
);
9572 gen_inline_functions();
9574 sym_pop(&global_stack
, NULL
);
9576 return s1
->nb_errors
!= 0 ? -1 : 0;
9579 /* Preprocess the current file */
9580 /* XXX: add line and file infos, add options to preserve spaces */
9581 static int tcc_preprocess(TCCState
*s1
)
9586 preprocess_init(s1
);
9588 define_start
= define_stack
;
9590 ch
= file
->buf_ptr
[0];
9591 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
9592 parse_flags
= PARSE_FLAG_ASM_COMMENTS
| PARSE_FLAG_PREPROCESS
|
9593 PARSE_FLAG_LINEFEED
;
9597 if (tok
== TOK_EOF
) {
9599 } else if (tok
== TOK_LINEFEED
) {
9603 fputc(' ', s1
->outfile
);
9606 fputs(get_tok_str(tok
, &tokc
), s1
->outfile
);
9609 free_defines(define_start
);
9614 int tcc_compile_string(TCCState
*s
, const char *str
)
9616 BufferedFile bf1
, *bf
= &bf1
;
9620 /* init file structure */
9622 /* XXX: avoid copying */
9624 buf
= tcc_malloc(len
+ 1);
9627 memcpy(buf
, str
, len
);
9630 bf
->buf_end
= buf
+ len
;
9631 pstrcpy(bf
->filename
, sizeof(bf
->filename
), "<string>");
9635 ret
= tcc_compile(s
);
9639 /* currently, no need to close */
9644 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
9645 void tcc_define_symbol(TCCState
*s1
, const char *sym
, const char *value
)
9647 BufferedFile bf1
, *bf
= &bf1
;
9649 pstrcpy(bf
->buffer
, IO_BUF_SIZE
, sym
);
9650 pstrcat(bf
->buffer
, IO_BUF_SIZE
, " ");
9654 pstrcat(bf
->buffer
, IO_BUF_SIZE
, value
);
9656 /* init file structure */
9658 bf
->buf_ptr
= bf
->buffer
;
9659 bf
->buf_end
= bf
->buffer
+ strlen(bf
->buffer
);
9660 *bf
->buf_end
= CH_EOB
;
9661 bf
->filename
[0] = '\0';
9665 s1
->include_stack_ptr
= s1
->include_stack
;
9667 /* parse with define parser */
9668 ch
= file
->buf_ptr
[0];
9674 /* undefine a preprocessor symbol */
9675 void tcc_undefine_symbol(TCCState
*s1
, const char *sym
)
9679 ts
= tok_alloc(sym
, strlen(sym
));
9680 s
= define_find(ts
->tok
);
9681 /* undefine symbol by putting an invalid name */
9686 #ifdef CONFIG_TCC_ASM
9688 #ifdef TCC_TARGET_I386
9689 #include "i386-asm.c"
9694 static void asm_instr(void)
9696 error("inline asm() not supported");
9698 static void asm_global_instr(void)
9700 error("inline asm() not supported");
9706 #ifdef TCC_TARGET_COFF
9707 #include "tcccoff.c"
9710 #ifdef TCC_TARGET_PE
9714 /* print the position in the source file of PC value 'pc' by reading
9715 the stabs debug information */
9716 static void rt_printline(unsigned long wanted_pc
)
9718 Stab_Sym
*sym
, *sym_end
;
9719 char func_name
[128], last_func_name
[128];
9720 unsigned long func_addr
, last_pc
, pc
;
9721 const char *incl_files
[INCLUDE_STACK_SIZE
];
9722 int incl_index
, len
, last_line_num
, i
;
9723 const char *str
, *p
;
9725 fprintf(stderr
, "0x%08lx:", wanted_pc
);
9727 func_name
[0] = '\0';
9730 last_func_name
[0] = '\0';
9731 last_pc
= 0xffffffff;
9733 sym
= (Stab_Sym
*)stab_section
->data
+ 1;
9734 sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
9735 while (sym
< sym_end
) {
9736 switch(sym
->n_type
) {
9737 /* function start or end */
9739 if (sym
->n_strx
== 0) {
9740 /* we test if between last line and end of function */
9741 pc
= sym
->n_value
+ func_addr
;
9742 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
9744 func_name
[0] = '\0';
9747 str
= stabstr_section
->data
+ sym
->n_strx
;
9748 p
= strchr(str
, ':');
9750 pstrcpy(func_name
, sizeof(func_name
), str
);
9753 if (len
> sizeof(func_name
) - 1)
9754 len
= sizeof(func_name
) - 1;
9755 memcpy(func_name
, str
, len
);
9756 func_name
[len
] = '\0';
9758 func_addr
= sym
->n_value
;
9761 /* line number info */
9763 pc
= sym
->n_value
+ func_addr
;
9764 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
9767 last_line_num
= sym
->n_desc
;
9769 strcpy(last_func_name
, func_name
);
9773 str
= stabstr_section
->data
+ sym
->n_strx
;
9775 if (incl_index
< INCLUDE_STACK_SIZE
) {
9776 incl_files
[incl_index
++] = str
;
9784 if (sym
->n_strx
== 0) {
9785 incl_index
= 0; /* end of translation unit */
9787 str
= stabstr_section
->data
+ sym
->n_strx
;
9788 /* do not add path */
9790 if (len
> 0 && str
[len
- 1] != '/')
9798 /* second pass: we try symtab symbols (no line number info) */
9801 Elf32_Sym
*sym
, *sym_end
;
9804 sym_end
= (Elf32_Sym
*)(symtab_section
->data
+ symtab_section
->data_offset
);
9805 for(sym
= (Elf32_Sym
*)symtab_section
->data
+ 1;
9808 type
= ELF32_ST_TYPE(sym
->st_info
);
9809 if (type
== STT_FUNC
) {
9810 if (wanted_pc
>= sym
->st_value
&&
9811 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
9812 pstrcpy(last_func_name
, sizeof(last_func_name
),
9813 strtab_section
->data
+ sym
->st_name
);
9819 /* did not find any info: */
9820 fprintf(stderr
, " ???\n");
9823 if (last_func_name
[0] != '\0') {
9824 fprintf(stderr
, " %s()", last_func_name
);
9826 if (incl_index
> 0) {
9827 fprintf(stderr
, " (%s:%d",
9828 incl_files
[incl_index
- 1], last_line_num
);
9829 for(i
= incl_index
- 2; i
>= 0; i
--)
9830 fprintf(stderr
, ", included from %s", incl_files
[i
]);
9831 fprintf(stderr
, ")");
9833 fprintf(stderr
, "\n");
9836 #if !defined(_WIN32) && !defined(CONFIG_TCCBOOT)
9840 /* fix for glibc 2.1 */
9846 /* return the PC at frame level 'level'. Return non zero if not found */
9847 static int rt_get_caller_pc(unsigned long *paddr
,
9848 ucontext_t
*uc
, int level
)
9854 #if defined(__FreeBSD__)
9855 *paddr
= uc
->uc_mcontext
.mc_eip
;
9856 #elif defined(__dietlibc__)
9857 *paddr
= uc
->uc_mcontext
.eip
;
9859 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
9863 #if defined(__FreeBSD__)
9864 fp
= uc
->uc_mcontext
.mc_ebp
;
9865 #elif defined(__dietlibc__)
9866 fp
= uc
->uc_mcontext
.ebp
;
9868 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
9870 for(i
=1;i
<level
;i
++) {
9871 /* XXX: check address validity with program info */
9872 if (fp
<= 0x1000 || fp
>= 0xc0000000)
9874 fp
= ((unsigned long *)fp
)[0];
9876 *paddr
= ((unsigned long *)fp
)[1];
9882 #warning add arch specific rt_get_caller_pc()
9884 static int rt_get_caller_pc(unsigned long *paddr
,
9885 ucontext_t
*uc
, int level
)
9891 /* emit a run time error at position 'pc' */
9892 void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
9899 fprintf(stderr
, "Runtime error: ");
9900 vfprintf(stderr
, fmt
, ap
);
9901 fprintf(stderr
, "\n");
9902 for(i
=0;i
<num_callers
;i
++) {
9903 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
9906 fprintf(stderr
, "at ");
9908 fprintf(stderr
, "by ");
9915 /* signal handler for fatal errors */
9916 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
9918 ucontext_t
*uc
= puc
;
9922 switch(siginf
->si_code
) {
9925 rt_error(uc
, "division by zero");
9928 rt_error(uc
, "floating point exception");
9934 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
9935 rt_error(uc
, *rt_bound_error_msg
);
9937 rt_error(uc
, "dereferencing invalid pointer");
9940 rt_error(uc
, "illegal instruction");
9943 rt_error(uc
, "abort() called");
9946 rt_error(uc
, "caught signal %d", signum
);
9953 /* do all relocations (needed before using tcc_get_symbol()) */
9954 int tcc_relocate(TCCState
*s1
)
9961 #ifdef TCC_TARGET_PE
9964 tcc_add_runtime(s1
);
9967 relocate_common_syms();
9969 tcc_add_linker_symbols(s1
);
9970 #ifndef TCC_TARGET_PE
9971 build_got_entries(s1
);
9973 /* compute relocation address : section are relocated in place. We
9974 also alloc the bss space */
9975 for(i
= 1; i
< s1
->nb_sections
; i
++) {
9976 s
= s1
->sections
[i
];
9977 if (s
->sh_flags
& SHF_ALLOC
) {
9978 if (s
->sh_type
== SHT_NOBITS
)
9979 s
->data
= tcc_mallocz(s
->data_offset
);
9980 s
->sh_addr
= (unsigned long)s
->data
;
9984 relocate_syms(s1
, 1);
9986 if (s1
->nb_errors
!= 0)
9989 /* relocate each section */
9990 for(i
= 1; i
< s1
->nb_sections
; i
++) {
9991 s
= s1
->sections
[i
];
9993 relocate_section(s1
, s
);
9996 /* mark executable sections as executable in memory */
9997 for(i
= 1; i
< s1
->nb_sections
; i
++) {
9998 s
= s1
->sections
[i
];
9999 if ((s
->sh_flags
& (SHF_ALLOC
| SHF_EXECINSTR
)) ==
10000 (SHF_ALLOC
| SHF_EXECINSTR
))
10001 set_pages_executable(s
->data
, s
->data_offset
);
10006 /* launch the compiled program with the given arguments */
10007 int tcc_run(TCCState
*s1
, int argc
, char **argv
)
10009 int (*prog_main
)(int, char **);
10011 if (tcc_relocate(s1
) < 0)
10014 prog_main
= tcc_get_symbol_err(s1
, "main");
10017 #if defined(_WIN32) || defined(CONFIG_TCCBOOT)
10018 error("debug mode currently not available for Windows");
10020 struct sigaction sigact
;
10021 /* install TCC signal handlers to print debug info on fatal
10023 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
10024 sigact
.sa_sigaction
= sig_error
;
10025 sigemptyset(&sigact
.sa_mask
);
10026 sigaction(SIGFPE
, &sigact
, NULL
);
10027 sigaction(SIGILL
, &sigact
, NULL
);
10028 sigaction(SIGSEGV
, &sigact
, NULL
);
10029 sigaction(SIGBUS
, &sigact
, NULL
);
10030 sigaction(SIGABRT
, &sigact
, NULL
);
10034 #ifdef CONFIG_TCC_BCHECK
10035 if (do_bounds_check
) {
10036 void (*bound_init
)(void);
10038 /* set error function */
10039 rt_bound_error_msg
= (void *)tcc_get_symbol_err(s1
,
10040 "__bound_error_msg");
10042 /* XXX: use .init section so that it also work in binary ? */
10043 bound_init
= (void *)tcc_get_symbol_err(s1
, "__bound_init");
10047 return (*prog_main
)(argc
, argv
);
10050 TCCState
*tcc_new(void)
10057 s
= tcc_mallocz(sizeof(TCCState
));
10061 s
->output_type
= TCC_OUTPUT_MEMORY
;
10063 /* init isid table */
10065 isidnum_table
[i
] = isid(i
) || isnum(i
);
10067 /* add all tokens */
10068 table_ident
= NULL
;
10069 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
10071 tok_ident
= TOK_IDENT
;
10080 ts
= tok_alloc(p
, r
- p
- 1);
10084 /* we add dummy defines for some special macros to speed up tests
10085 and to have working defined() */
10086 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
10087 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
10088 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
10089 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
10091 /* standard defines */
10092 tcc_define_symbol(s
, "__STDC__", NULL
);
10093 tcc_define_symbol(s
, "__STDC_VERSION__", "199901L");
10094 #if defined(TCC_TARGET_I386)
10095 tcc_define_symbol(s
, "__i386__", NULL
);
10097 #if defined(TCC_TARGET_ARM)
10098 tcc_define_symbol(s
, "__ARM_ARCH_4__", NULL
);
10099 tcc_define_symbol(s
, "__arm_elf__", NULL
);
10100 tcc_define_symbol(s
, "__arm_elf", NULL
);
10101 tcc_define_symbol(s
, "arm_elf", NULL
);
10102 tcc_define_symbol(s
, "__arm__", NULL
);
10103 tcc_define_symbol(s
, "__arm", NULL
);
10104 tcc_define_symbol(s
, "arm", NULL
);
10105 tcc_define_symbol(s
, "__APCS_32__", NULL
);
10107 #ifdef TCC_TARGET_PE
10108 tcc_define_symbol(s
, "_WIN32", NULL
);
10110 tcc_define_symbol(s
, "__unix__", NULL
);
10111 tcc_define_symbol(s
, "__unix", NULL
);
10112 #if defined(__linux)
10113 tcc_define_symbol(s
, "__linux__", NULL
);
10114 tcc_define_symbol(s
, "__linux", NULL
);
10117 /* tiny C specific defines */
10118 tcc_define_symbol(s
, "__TINYC__", NULL
);
10120 /* tiny C & gcc defines */
10121 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned int");
10122 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "int");
10123 #ifdef TCC_TARGET_PE
10124 tcc_define_symbol(s
, "__WCHAR_TYPE__", "unsigned short");
10126 tcc_define_symbol(s
, "__WCHAR_TYPE__", "int");
10129 #ifndef TCC_TARGET_PE
10130 /* default library paths */
10131 tcc_add_library_path(s
, "/usr/local/lib");
10132 tcc_add_library_path(s
, "/usr/lib");
10133 tcc_add_library_path(s
, "/lib");
10136 /* no section zero */
10137 dynarray_add((void ***)&s
->sections
, &s
->nb_sections
, NULL
);
10139 /* create standard sections */
10140 text_section
= new_section(s
, ".text", SHT_PROGBITS
, SHF_ALLOC
| SHF_EXECINSTR
);
10141 data_section
= new_section(s
, ".data", SHT_PROGBITS
, SHF_ALLOC
| SHF_WRITE
);
10142 bss_section
= new_section(s
, ".bss", SHT_NOBITS
, SHF_ALLOC
| SHF_WRITE
);
10144 /* symbols are always generated for linking stage */
10145 symtab_section
= new_symtab(s
, ".symtab", SHT_SYMTAB
, 0,
10147 ".hashtab", SHF_PRIVATE
);
10148 strtab_section
= symtab_section
->link
;
10150 /* private symbol table for dynamic symbols */
10151 s
->dynsymtab_section
= new_symtab(s
, ".dynsymtab", SHT_SYMTAB
, SHF_PRIVATE
,
10153 ".dynhashtab", SHF_PRIVATE
);
10154 s
->alacarte_link
= 1;
10156 #ifdef CHAR_IS_UNSIGNED
10157 s
->char_is_unsigned
= 1;
10159 #if defined(TCC_TARGET_PE) && 0
10160 /* XXX: currently the PE linker is not ready to support that */
10161 s
->leading_underscore
= 1;
10166 void tcc_delete(TCCState
*s1
)
10170 /* free -D defines */
10171 free_defines(NULL
);
10174 n
= tok_ident
- TOK_IDENT
;
10175 for(i
= 0; i
< n
; i
++)
10176 tcc_free(table_ident
[i
]);
10177 tcc_free(table_ident
);
10179 /* free all sections */
10181 free_section(symtab_section
->hash
);
10183 free_section(s1
->dynsymtab_section
->hash
);
10184 free_section(s1
->dynsymtab_section
->link
);
10185 free_section(s1
->dynsymtab_section
);
10187 for(i
= 1; i
< s1
->nb_sections
; i
++)
10188 free_section(s1
->sections
[i
]);
10189 tcc_free(s1
->sections
);
10191 /* free loaded dlls array */
10192 dynarray_reset(&s1
->loaded_dlls
, &s1
->nb_loaded_dlls
);
10194 /* free library paths */
10195 dynarray_reset(&s1
->library_paths
, &s1
->nb_library_paths
);
10197 /* free include paths */
10198 dynarray_reset(&s1
->cached_includes
, &s1
->nb_cached_includes
);
10199 dynarray_reset(&s1
->include_paths
, &s1
->nb_include_paths
);
10200 dynarray_reset(&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
);
10205 int tcc_add_include_path(TCCState
*s1
, const char *pathname
)
10209 pathname1
= tcc_strdup(pathname
);
10210 dynarray_add((void ***)&s1
->include_paths
, &s1
->nb_include_paths
, pathname1
);
10214 int tcc_add_sysinclude_path(TCCState
*s1
, const char *pathname
)
10218 pathname1
= tcc_strdup(pathname
);
10219 dynarray_add((void ***)&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
, pathname1
);
10223 static int tcc_add_file_internal(TCCState
*s1
, const char *filename
, int flags
)
10228 BufferedFile
*saved_file
;
10230 /* find source file type with extension */
10231 ext
= tcc_fileextension(filename
);
10235 /* open the file */
10237 file
= tcc_open(s1
, filename
);
10239 if (flags
& AFF_PRINT_ERROR
) {
10240 error_noabort("file '%s' not found", filename
);
10246 if (flags
& AFF_PREPROCESS
) {
10247 ret
= tcc_preprocess(s1
);
10248 } else if (!ext
[0] || !strcmp(ext
, "c")) {
10249 /* C file assumed */
10250 ret
= tcc_compile(s1
);
10252 #ifdef CONFIG_TCC_ASM
10253 if (!strcmp(ext
, "S")) {
10254 /* preprocessed assembler */
10255 ret
= tcc_assemble(s1
, 1);
10256 } else if (!strcmp(ext
, "s")) {
10257 /* non preprocessed assembler */
10258 ret
= tcc_assemble(s1
, 0);
10261 #ifdef TCC_TARGET_PE
10262 if (!strcmp(ext
, "def")) {
10263 ret
= pe_load_def_file(s1
, file
->fd
);
10268 /* assume executable format: auto guess file type */
10269 ret
= read(fd
, &ehdr
, sizeof(ehdr
));
10270 lseek(fd
, 0, SEEK_SET
);
10272 error_noabort("could not read header");
10274 } else if (ret
!= sizeof(ehdr
)) {
10275 goto try_load_script
;
10278 if (ehdr
.e_ident
[0] == ELFMAG0
&&
10279 ehdr
.e_ident
[1] == ELFMAG1
&&
10280 ehdr
.e_ident
[2] == ELFMAG2
&&
10281 ehdr
.e_ident
[3] == ELFMAG3
) {
10282 file
->line_num
= 0; /* do not display line number if error */
10283 if (ehdr
.e_type
== ET_REL
) {
10284 ret
= tcc_load_object_file(s1
, fd
, 0);
10285 } else if (ehdr
.e_type
== ET_DYN
) {
10286 if (s1
->output_type
== TCC_OUTPUT_MEMORY
) {
10287 #ifdef TCC_TARGET_PE
10291 h
= dlopen(filename
, RTLD_GLOBAL
| RTLD_LAZY
);
10298 ret
= tcc_load_dll(s1
, fd
, filename
,
10299 (flags
& AFF_REFERENCED_DLL
) != 0);
10302 error_noabort("unrecognized ELF file");
10305 } else if (memcmp((char *)&ehdr
, ARMAG
, 8) == 0) {
10306 file
->line_num
= 0; /* do not display line number if error */
10307 ret
= tcc_load_archive(s1
, fd
);
10309 #ifdef TCC_TARGET_COFF
10310 if (*(uint16_t *)(&ehdr
) == COFF_C67_MAGIC
) {
10311 ret
= tcc_load_coff(s1
, fd
);
10314 #ifdef TCC_TARGET_PE
10315 if (pe_test_res_file(&ehdr
, ret
)) {
10316 ret
= pe_load_res_file(s1
, fd
);
10320 /* as GNU ld, consider it is an ld script if not recognized */
10322 ret
= tcc_load_ldscript(s1
);
10324 error_noabort("unrecognized file type");
10339 int tcc_add_file(TCCState
*s
, const char *filename
)
10341 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
);
10344 int tcc_add_library_path(TCCState
*s
, const char *pathname
)
10348 pathname1
= tcc_strdup(pathname
);
10349 dynarray_add((void ***)&s
->library_paths
, &s
->nb_library_paths
, pathname1
);
10353 /* find and load a dll. Return non zero if not found */
10354 /* XXX: add '-rpath' option support ? */
10355 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
)
10360 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
10361 snprintf(buf
, sizeof(buf
), "%s/%s",
10362 s
->library_paths
[i
], filename
);
10363 if (tcc_add_file_internal(s
, buf
, flags
) == 0)
10369 /* the library name is the same as the argument of the '-l' option */
10370 int tcc_add_library(TCCState
*s
, const char *libraryname
)
10375 /* first we look for the dynamic library if not static linking */
10376 if (!s
->static_link
) {
10377 #ifdef TCC_TARGET_PE
10378 snprintf(buf
, sizeof(buf
), "%s.def", libraryname
);
10380 snprintf(buf
, sizeof(buf
), "lib%s.so", libraryname
);
10382 if (tcc_add_dll(s
, buf
, 0) == 0)
10386 /* then we look for the static library */
10387 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
10388 snprintf(buf
, sizeof(buf
), "%s/lib%s.a",
10389 s
->library_paths
[i
], libraryname
);
10390 if (tcc_add_file_internal(s
, buf
, 0) == 0)
10396 int tcc_add_symbol(TCCState
*s
, const char *name
, unsigned long val
)
10398 add_elf_sym(symtab_section
, val
, 0,
10399 ELF32_ST_INFO(STB_GLOBAL
, STT_NOTYPE
), 0,
10404 int tcc_set_output_type(TCCState
*s
, int output_type
)
10408 s
->output_type
= output_type
;
10410 if (!s
->nostdinc
) {
10411 /* default include paths */
10412 /* XXX: reverse order needed if -isystem support */
10413 #ifndef TCC_TARGET_PE
10414 tcc_add_sysinclude_path(s
, "/usr/local/include");
10415 tcc_add_sysinclude_path(s
, "/usr/include");
10417 snprintf(buf
, sizeof(buf
), "%s/include", tcc_lib_path
);
10418 tcc_add_sysinclude_path(s
, buf
);
10419 #ifdef TCC_TARGET_PE
10420 snprintf(buf
, sizeof(buf
), "%s/include/winapi", tcc_lib_path
);
10421 tcc_add_sysinclude_path(s
, buf
);
10425 /* if bound checking, then add corresponding sections */
10426 #ifdef CONFIG_TCC_BCHECK
10427 if (do_bounds_check
) {
10428 /* define symbol */
10429 tcc_define_symbol(s
, "__BOUNDS_CHECKING_ON", NULL
);
10430 /* create bounds sections */
10431 bounds_section
= new_section(s
, ".bounds",
10432 SHT_PROGBITS
, SHF_ALLOC
);
10433 lbounds_section
= new_section(s
, ".lbounds",
10434 SHT_PROGBITS
, SHF_ALLOC
);
10438 if (s
->char_is_unsigned
) {
10439 tcc_define_symbol(s
, "__CHAR_UNSIGNED__", NULL
);
10442 /* add debug sections */
10445 stab_section
= new_section(s
, ".stab", SHT_PROGBITS
, 0);
10446 stab_section
->sh_entsize
= sizeof(Stab_Sym
);
10447 stabstr_section
= new_section(s
, ".stabstr", SHT_STRTAB
, 0);
10448 put_elf_str(stabstr_section
, "");
10449 stab_section
->link
= stabstr_section
;
10450 /* put first entry */
10451 put_stabs("", 0, 0, 0, 0);
10454 /* add libc crt1/crti objects */
10455 #ifndef TCC_TARGET_PE
10456 if ((output_type
== TCC_OUTPUT_EXE
|| output_type
== TCC_OUTPUT_DLL
) &&
10458 if (output_type
!= TCC_OUTPUT_DLL
)
10459 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crt1.o");
10460 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crti.o");
10464 #ifdef TCC_TARGET_PE
10465 snprintf(buf
, sizeof(buf
), "%s/lib", tcc_lib_path
);
10466 tcc_add_library_path(s
, buf
);
10472 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
10473 #define FD_INVERT 0x0002 /* invert value before storing */
10475 typedef struct FlagDef
{
10481 static const FlagDef warning_defs
[] = {
10482 { offsetof(TCCState
, warn_unsupported
), 0, "unsupported" },
10483 { offsetof(TCCState
, warn_write_strings
), 0, "write-strings" },
10484 { offsetof(TCCState
, warn_error
), 0, "error" },
10485 { offsetof(TCCState
, warn_implicit_function_declaration
), WD_ALL
,
10486 "implicit-function-declaration" },
10489 static int set_flag(TCCState
*s
, const FlagDef
*flags
, int nb_flags
,
10490 const char *name
, int value
)
10497 if (r
[0] == 'n' && r
[1] == 'o' && r
[2] == '-') {
10501 for(i
= 0, p
= flags
; i
< nb_flags
; i
++, p
++) {
10502 if (!strcmp(r
, p
->name
))
10507 if (p
->flags
& FD_INVERT
)
10509 *(int *)((uint8_t *)s
+ p
->offset
) = value
;
10514 /* set/reset a warning */
10515 int tcc_set_warning(TCCState
*s
, const char *warning_name
, int value
)
10520 if (!strcmp(warning_name
, "all")) {
10521 for(i
= 0, p
= warning_defs
; i
< countof(warning_defs
); i
++, p
++) {
10522 if (p
->flags
& WD_ALL
)
10523 *(int *)((uint8_t *)s
+ p
->offset
) = 1;
10527 return set_flag(s
, warning_defs
, countof(warning_defs
),
10528 warning_name
, value
);
10532 static const FlagDef flag_defs
[] = {
10533 { offsetof(TCCState
, char_is_unsigned
), 0, "unsigned-char" },
10534 { offsetof(TCCState
, char_is_unsigned
), FD_INVERT
, "signed-char" },
10535 { offsetof(TCCState
, nocommon
), FD_INVERT
, "common" },
10536 { offsetof(TCCState
, leading_underscore
), 0, "leading-underscore" },
10539 /* set/reset a flag */
10540 int tcc_set_flag(TCCState
*s
, const char *flag_name
, int value
)
10542 return set_flag(s
, flag_defs
, countof(flag_defs
),
10546 #if !defined(LIBTCC)
10548 static int64_t getclock_us(void)
10553 return (tb
.time
* 1000LL + tb
.millitm
) * 1000LL;
10556 gettimeofday(&tv
, NULL
);
10557 return tv
.tv_sec
* 1000000LL + tv
.tv_usec
;
10563 printf("tcc version " TCC_VERSION
" - Tiny C Compiler - Copyright (C) 2001-2006 Fabrice Bellard\n"
10564 "usage: tcc [-v] [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"
10565 " [-Wwarn] [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-soname name]\n"
10566 " [-static] [infile1 infile2...] [-run infile args...]\n"
10568 "General options:\n"
10569 " -v display current version\n"
10570 " -c compile only - generate an object file\n"
10571 " -o outfile set output filename\n"
10572 " -Bdir set tcc internal library path\n"
10573 " -bench output compilation statistics\n"
10574 " -run run compiled source\n"
10575 " -fflag set or reset (with 'no-' prefix) 'flag' (see man page)\n"
10576 " -Wwarning set or reset (with 'no-' prefix) 'warning' (see man page)\n"
10577 " -w disable all warnings\n"
10578 "Preprocessor options:\n"
10579 " -E preprocess only\n"
10580 " -Idir add include path 'dir'\n"
10581 " -Dsym[=val] define 'sym' with value 'val'\n"
10582 " -Usym undefine 'sym'\n"
10583 "Linker options:\n"
10584 " -Ldir add library path 'dir'\n"
10585 " -llib link with dynamic or static library 'lib'\n"
10586 " -shared generate a shared library\n"
10587 " -soname set name for shared library to be used at runtime\n"
10588 " -static static linking\n"
10589 " -rdynamic export all global symbols to dynamic linker\n"
10590 " -r generate (relocatable) object file\n"
10591 "Debugger options:\n"
10592 " -g generate runtime debug info\n"
10593 #ifdef CONFIG_TCC_BCHECK
10594 " -b compile with built-in memory and bounds checker (implies -g)\n"
10596 " -bt N show N callers in stack traces\n"
10600 #define TCC_OPTION_HAS_ARG 0x0001
10601 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
10603 typedef struct TCCOption
{
10632 TCC_OPTION_nostdinc
,
10633 TCC_OPTION_nostdlib
,
10634 TCC_OPTION_print_search_dirs
,
10635 TCC_OPTION_rdynamic
,
10643 static const TCCOption tcc_options
[] = {
10644 { "h", TCC_OPTION_HELP
, 0 },
10645 { "?", TCC_OPTION_HELP
, 0 },
10646 { "I", TCC_OPTION_I
, TCC_OPTION_HAS_ARG
},
10647 { "D", TCC_OPTION_D
, TCC_OPTION_HAS_ARG
},
10648 { "U", TCC_OPTION_U
, TCC_OPTION_HAS_ARG
},
10649 { "L", TCC_OPTION_L
, TCC_OPTION_HAS_ARG
},
10650 { "B", TCC_OPTION_B
, TCC_OPTION_HAS_ARG
},
10651 { "l", TCC_OPTION_l
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10652 { "bench", TCC_OPTION_bench
, 0 },
10653 { "bt", TCC_OPTION_bt
, TCC_OPTION_HAS_ARG
},
10654 #ifdef CONFIG_TCC_BCHECK
10655 { "b", TCC_OPTION_b
, 0 },
10657 { "g", TCC_OPTION_g
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10658 { "c", TCC_OPTION_c
, 0 },
10659 { "static", TCC_OPTION_static
, 0 },
10660 { "shared", TCC_OPTION_shared
, 0 },
10661 { "soname", TCC_OPTION_soname
, TCC_OPTION_HAS_ARG
},
10662 { "o", TCC_OPTION_o
, TCC_OPTION_HAS_ARG
},
10663 { "run", TCC_OPTION_run
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10664 { "rdynamic", TCC_OPTION_rdynamic
, 0 },
10665 { "r", TCC_OPTION_r
, 0 },
10666 { "Wl,", TCC_OPTION_Wl
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10667 { "W", TCC_OPTION_W
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10668 { "O", TCC_OPTION_O
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10669 { "m", TCC_OPTION_m
, TCC_OPTION_HAS_ARG
},
10670 { "f", TCC_OPTION_f
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10671 { "nostdinc", TCC_OPTION_nostdinc
, 0 },
10672 { "nostdlib", TCC_OPTION_nostdlib
, 0 },
10673 { "print-search-dirs", TCC_OPTION_print_search_dirs
, 0 },
10674 { "v", TCC_OPTION_v
, 0 },
10675 { "w", TCC_OPTION_w
, 0 },
10676 { "pipe", TCC_OPTION_pipe
, 0},
10677 { "E", TCC_OPTION_E
, 0},
10681 /* convert 'str' into an array of space separated strings */
10682 static int expand_args(char ***pargv
, const char *str
)
10691 while (is_space(*str
))
10696 while (*str
!= '\0' && !is_space(*str
))
10699 arg
= tcc_malloc(len
+ 1);
10700 memcpy(arg
, s1
, len
);
10702 dynarray_add((void ***)&argv
, &argc
, arg
);
10708 static char **files
;
10709 static int nb_files
, nb_libraries
;
10710 static int multiple_files
;
10711 static int print_search_dirs
;
10712 static int output_type
;
10713 static int reloc_output
;
10714 static const char *outfile
;
10716 int parse_args(TCCState
*s
, int argc
, char **argv
)
10719 const TCCOption
*popt
;
10720 const char *optarg
, *p1
, *r1
;
10725 if (optind
>= argc
) {
10726 if (nb_files
== 0 && !print_search_dirs
)
10731 r
= argv
[optind
++];
10732 if (r
[0] != '-' || r
[1] == '\0') {
10733 /* add a new file */
10734 dynarray_add((void ***)&files
, &nb_files
, r
);
10735 if (!multiple_files
) {
10737 /* argv[0] will be this file */
10741 /* find option in table (match only the first chars */
10742 popt
= tcc_options
;
10746 error("invalid option -- '%s'", r
);
10759 if (popt
->flags
& TCC_OPTION_HAS_ARG
) {
10760 if (*r1
!= '\0' || (popt
->flags
& TCC_OPTION_NOSEP
)) {
10763 if (optind
>= argc
)
10764 error("argument to '%s' is missing", r
);
10765 optarg
= argv
[optind
++];
10773 switch(popt
->index
) {
10774 case TCC_OPTION_HELP
:
10779 if (tcc_add_include_path(s
, optarg
) < 0)
10780 error("too many include paths");
10785 sym
= (char *)optarg
;
10786 value
= strchr(sym
, '=');
10791 tcc_define_symbol(s
, sym
, value
);
10795 tcc_undefine_symbol(s
, optarg
);
10798 tcc_add_library_path(s
, optarg
);
10801 /* set tcc utilities path (mainly for tcc development) */
10802 tcc_lib_path
= optarg
;
10805 dynarray_add((void ***)&files
, &nb_files
, r
);
10808 case TCC_OPTION_bench
:
10811 case TCC_OPTION_bt
:
10812 num_callers
= atoi(optarg
);
10814 #ifdef CONFIG_TCC_BCHECK
10816 do_bounds_check
= 1;
10824 multiple_files
= 1;
10825 output_type
= TCC_OUTPUT_OBJ
;
10827 case TCC_OPTION_static
:
10828 s
->static_link
= 1;
10830 case TCC_OPTION_shared
:
10831 output_type
= TCC_OUTPUT_DLL
;
10833 case TCC_OPTION_soname
:
10834 s
->soname
= optarg
;
10837 multiple_files
= 1;
10841 /* generate a .o merging several output files */
10843 output_type
= TCC_OUTPUT_OBJ
;
10845 case TCC_OPTION_nostdinc
:
10848 case TCC_OPTION_nostdlib
:
10851 case TCC_OPTION_print_search_dirs
:
10852 print_search_dirs
= 1;
10854 case TCC_OPTION_run
:
10858 argc1
= expand_args(&argv1
, optarg
);
10860 parse_args(s
, argc1
, argv1
);
10862 multiple_files
= 0;
10863 output_type
= TCC_OUTPUT_MEMORY
;
10867 printf("tcc version %s\n", TCC_VERSION
);
10870 if (tcc_set_flag(s
, optarg
, 1) < 0 && s
->warn_unsupported
)
10871 goto unsupported_option
;
10874 if (tcc_set_warning(s
, optarg
, 1) < 0 &&
10875 s
->warn_unsupported
)
10876 goto unsupported_option
;
10881 case TCC_OPTION_rdynamic
:
10884 case TCC_OPTION_Wl
:
10887 if (strstart(optarg
, "-Ttext,", &p
)) {
10888 s
->text_addr
= strtoul(p
, NULL
, 16);
10889 s
->has_text_addr
= 1;
10890 } else if (strstart(optarg
, "--oformat,", &p
)) {
10891 if (strstart(p
, "elf32-", NULL
)) {
10892 s
->output_format
= TCC_OUTPUT_FORMAT_ELF
;
10893 } else if (!strcmp(p
, "binary")) {
10894 s
->output_format
= TCC_OUTPUT_FORMAT_BINARY
;
10896 #ifdef TCC_TARGET_COFF
10897 if (!strcmp(p
, "coff")) {
10898 s
->output_format
= TCC_OUTPUT_FORMAT_COFF
;
10902 error("target %s not found", p
);
10905 error("unsupported linker option '%s'", optarg
);
10910 output_type
= TCC_OUTPUT_PREPROCESS
;
10913 if (s
->warn_unsupported
) {
10914 unsupported_option
:
10915 warning("unsupported option '%s'", r
);
10924 int main(int argc
, char **argv
)
10928 int nb_objfiles
, ret
, optind
;
10929 char objfilename
[1024];
10930 int64_t start_time
= 0;
10933 tcc_lib_path
= w32_tcc_lib_path();
10937 output_type
= TCC_OUTPUT_EXE
;
10939 multiple_files
= 1;
10944 print_search_dirs
= 0;
10947 optind
= parse_args(s
, argc
- 1, argv
+ 1) + 1;
10949 if (print_search_dirs
) {
10950 /* enough for Linux kernel */
10951 printf("install: %s/\n", tcc_lib_path
);
10955 nb_objfiles
= nb_files
- nb_libraries
;
10957 /* if outfile provided without other options, we output an
10959 if (outfile
&& output_type
== TCC_OUTPUT_MEMORY
)
10960 output_type
= TCC_OUTPUT_EXE
;
10962 /* check -c consistency : only single file handled. XXX: checks file type */
10963 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
10964 /* accepts only a single input file */
10965 if (nb_objfiles
!= 1)
10966 error("cannot specify multiple files with -c");
10967 if (nb_libraries
!= 0)
10968 error("cannot specify libraries with -c");
10972 if (output_type
== TCC_OUTPUT_PREPROCESS
) {
10974 s
->outfile
= stdout
;
10976 s
->outfile
= fopen(outfile
, "w");
10978 error("could not open '%s", outfile
);
10980 } else if (output_type
!= TCC_OUTPUT_MEMORY
) {
10982 /* compute default outfile name */
10985 strcmp(files
[0], "-") == 0 ? "a" : tcc_basename(files
[0]);
10986 pstrcpy(objfilename
, sizeof(objfilename
), name
);
10987 ext
= tcc_fileextension(objfilename
);
10988 #ifdef TCC_TARGET_PE
10989 if (output_type
== TCC_OUTPUT_DLL
)
10990 strcpy(ext
, ".dll");
10992 if (output_type
== TCC_OUTPUT_EXE
)
10993 strcpy(ext
, ".exe");
10996 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
&& *ext
)
10999 pstrcpy(objfilename
, sizeof(objfilename
), "a.out");
11000 outfile
= objfilename
;
11005 start_time
= getclock_us();
11008 tcc_set_output_type(s
, output_type
);
11010 /* compile or add each files or library */
11011 for(i
= 0; i
< nb_files
&& ret
== 0; i
++) {
11012 const char *filename
;
11014 filename
= files
[i
];
11015 if (output_type
== TCC_OUTPUT_PREPROCESS
) {
11016 if (tcc_add_file_internal(s
, filename
,
11017 AFF_PRINT_ERROR
| AFF_PREPROCESS
) < 0)
11019 } else if (filename
[0] == '-' && filename
[1]) {
11020 if (tcc_add_library(s
, filename
+ 2) < 0)
11021 error("cannot find %s", filename
);
11023 if (tcc_add_file(s
, filename
) < 0)
11028 /* free all files */
11036 total_time
= (double)(getclock_us() - start_time
) / 1000000.0;
11037 if (total_time
< 0.001)
11038 total_time
= 0.001;
11039 if (total_bytes
< 1)
11041 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
11042 tok_ident
- TOK_IDENT
, total_lines
, total_bytes
,
11043 total_time
, (int)(total_lines
/ total_time
),
11044 total_bytes
/ total_time
/ 1000000.0);
11047 if (s
->output_type
== TCC_OUTPUT_PREPROCESS
) {
11049 fclose(s
->outfile
);
11050 } else if (s
->output_type
== TCC_OUTPUT_MEMORY
) {
11051 ret
= tcc_run(s
, argc
- optind
, argv
+ optind
);
11053 #ifdef TCC_TARGET_PE
11054 if (s
->output_type
!= TCC_OUTPUT_OBJ
) {
11055 ret
= pe_output_file(s
, outfile
);
11059 ret
= tcc_output_file(s
, outfile
) ? 1 : 0;
11062 /* XXX: cannot do it with bound checking because of the malloc hooks */
11063 if (!do_bounds_check
)
11068 printf("memory: %d bytes, max = %d bytes\n", mem_cur_size
, mem_max_size
);