Add -std=c11 option which sets __STDC_VERSION__ to 201112L and allows to implement...
[tinycc.git] / tccgen.c
blob06af385856bc27899bcee6add2ab865eed5b8681
1 /*
2 * TCC - Tiny C Compiler
3 *
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
21 #include "tcc.h"
22 /********************************************************/
23 /* global variables */
25 /* loc : local variable index
26 ind : output code index
27 rsym: return symbol
28 anon_sym: anonymous symbol index
30 ST_DATA int rsym, anon_sym, ind, loc;
32 ST_DATA Sym *sym_free_first;
33 ST_DATA void **sym_pools;
34 ST_DATA int nb_sym_pools;
36 ST_DATA Sym *global_stack;
37 ST_DATA Sym *local_stack;
38 ST_DATA Sym *define_stack;
39 ST_DATA Sym *global_label_stack;
40 ST_DATA Sym *local_label_stack;
41 static int local_scope;
42 static int in_sizeof;
43 static int section_sym;
45 ST_DATA int vlas_in_scope; /* number of VLAs that are currently in scope */
46 ST_DATA int vla_sp_root_loc; /* vla_sp_loc for SP before any VLAs were pushed */
47 ST_DATA int vla_sp_loc; /* Pointer to variable holding location to store stack pointer on the stack when modifying stack pointer */
49 ST_DATA SValue __vstack[1+VSTACK_SIZE], *vtop, *pvtop;
51 ST_DATA int const_wanted; /* true if constant wanted */
52 ST_DATA int nocode_wanted; /* no code generation wanted */
53 #define NODATA_WANTED (nocode_wanted > 0) /* no static data output wanted either */
54 #define STATIC_DATA_WANTED (nocode_wanted & 0xC0000000) /* only static data output */
55 ST_DATA int global_expr; /* true if compound literals must be allocated globally (used during initializers parsing */
56 ST_DATA CType func_vt; /* current function return type (used by return instruction) */
57 ST_DATA int func_var; /* true if current function is variadic (used by return instruction) */
58 ST_DATA int func_vc;
59 ST_DATA int last_line_num, last_ind, func_ind; /* debug last line number and pc */
60 ST_DATA const char *funcname;
61 ST_DATA int g_debug;
63 ST_DATA CType char_pointer_type, func_old_type, int_type, size_type, ptrdiff_type;
65 ST_DATA struct switch_t {
66 struct case_t {
67 int64_t v1, v2;
68 int sym;
69 } **p; int n; /* list of case ranges */
70 int def_sym; /* default symbol */
71 } *cur_switch; /* current switch */
73 #define MAX_TEMP_LOCAL_VARIABLE_NUMBER 0x4
74 /*list of temporary local variables on the stack in current function. */
75 ST_DATA struct temp_local_variable {
76 int location; //offset on stack. Svalue.c.i
77 short size;
78 short align;
79 } arr_temp_local_vars[MAX_TEMP_LOCAL_VARIABLE_NUMBER];
80 short nb_temp_local_vars;
81 /* ------------------------------------------------------------------------- */
83 static void gen_cast(CType *type);
84 static void gen_cast_s(int t);
85 static inline CType *pointed_type(CType *type);
86 static int is_compatible_types(CType *type1, CType *type2);
87 static int parse_btype(CType *type, AttributeDef *ad);
88 static CType *type_decl(CType *type, AttributeDef *ad, int *v, int td);
89 static void parse_expr_type(CType *type);
90 static void init_putv(CType *type, Section *sec, unsigned long c);
91 static void decl_initializer(CType *type, Section *sec, unsigned long c, int first, int size_only);
92 static void block(int *bsym, int *csym, int is_expr);
93 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r, int has_init, int v, int scope);
94 static void decl(int l);
95 static int decl0(int l, int is_for_loop_init, Sym *);
96 static void expr_eq(void);
97 static void vla_runtime_type_size(CType *type, int *a);
98 static void vla_sp_restore(void);
99 static void vla_sp_restore_root(void);
100 static int is_compatible_unqualified_types(CType *type1, CType *type2);
101 static inline int64_t expr_const64(void);
102 static void vpush64(int ty, unsigned long long v);
103 static void vpush(CType *type);
104 static int gvtst(int inv, int t);
105 static void gen_inline_functions(TCCState *s);
106 static void skip_or_save_block(TokenString **str);
107 static void gv_dup(void);
108 static int get_temp_local_var(int size,int align);
109 static void clear_temp_local_var_list();
111 ST_INLN int is_float(int t)
113 int bt;
114 bt = t & VT_BTYPE;
115 return bt == VT_LDOUBLE || bt == VT_DOUBLE || bt == VT_FLOAT || bt == VT_QFLOAT;
118 /* we use our own 'finite' function to avoid potential problems with
119 non standard math libs */
120 /* XXX: endianness dependent */
121 ST_FUNC int ieee_finite(double d)
123 int p[4];
124 memcpy(p, &d, sizeof(double));
125 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
128 /* compiling intel long double natively */
129 #if (defined __i386__ || defined __x86_64__) \
130 && (defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64)
131 # define TCC_IS_NATIVE_387
132 #endif
134 ST_FUNC void test_lvalue(void)
136 if (!(vtop->r & VT_LVAL))
137 expect("lvalue");
140 ST_FUNC void check_vstack(void)
142 if (pvtop != vtop)
143 tcc_error("internal compiler error: vstack leak (%d)", vtop - pvtop);
146 /* ------------------------------------------------------------------------- */
147 /* vstack debugging aid */
149 #if 0
150 void pv (const char *lbl, int a, int b)
152 int i;
153 for (i = a; i < a + b; ++i) {
154 SValue *p = &vtop[-i];
155 printf("%s vtop[-%d] : type.t:%04x r:%04x r2:%04x c.i:%d\n",
156 lbl, i, p->type.t, p->r, p->r2, (int)p->c.i);
159 #endif
161 /* ------------------------------------------------------------------------- */
162 /* start of translation unit info */
163 ST_FUNC void tcc_debug_start(TCCState *s1)
165 if (s1->do_debug) {
166 char buf[512];
168 /* file info: full path + filename */
169 section_sym = put_elf_sym(symtab_section, 0, 0,
170 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
171 text_section->sh_num, NULL);
172 getcwd(buf, sizeof(buf));
173 #ifdef _WIN32
174 normalize_slashes(buf);
175 #endif
176 pstrcat(buf, sizeof(buf), "/");
177 put_stabs_r(buf, N_SO, 0, 0,
178 text_section->data_offset, text_section, section_sym);
179 put_stabs_r(file->filename, N_SO, 0, 0,
180 text_section->data_offset, text_section, section_sym);
181 last_ind = 0;
182 last_line_num = 0;
185 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
186 symbols can be safely used */
187 put_elf_sym(symtab_section, 0, 0,
188 ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
189 SHN_ABS, file->filename);
192 /* put end of translation unit info */
193 ST_FUNC void tcc_debug_end(TCCState *s1)
195 if (!s1->do_debug)
196 return;
197 put_stabs_r(NULL, N_SO, 0, 0,
198 text_section->data_offset, text_section, section_sym);
202 /* generate line number info */
203 ST_FUNC void tcc_debug_line(TCCState *s1)
205 if (!s1->do_debug)
206 return;
207 if ((last_line_num != file->line_num || last_ind != ind)) {
208 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
209 last_ind = ind;
210 last_line_num = file->line_num;
214 /* put function symbol */
215 ST_FUNC void tcc_debug_funcstart(TCCState *s1, Sym *sym)
217 char buf[512];
219 if (!s1->do_debug)
220 return;
222 /* stabs info */
223 /* XXX: we put here a dummy type */
224 snprintf(buf, sizeof(buf), "%s:%c1",
225 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
226 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
227 cur_text_section, sym->c);
228 /* //gr gdb wants a line at the function */
229 put_stabn(N_SLINE, 0, file->line_num, 0);
231 last_ind = 0;
232 last_line_num = 0;
235 /* put function size */
236 ST_FUNC void tcc_debug_funcend(TCCState *s1, int size)
238 if (!s1->do_debug)
239 return;
240 put_stabn(N_FUN, 0, 0, size);
243 /* ------------------------------------------------------------------------- */
244 ST_FUNC int tccgen_compile(TCCState *s1)
246 cur_text_section = NULL;
247 funcname = "";
248 anon_sym = SYM_FIRST_ANOM;
249 section_sym = 0;
250 const_wanted = 0;
251 nocode_wanted = 0x80000000;
253 /* define some often used types */
254 int_type.t = VT_INT;
255 char_pointer_type.t = VT_BYTE;
256 mk_pointer(&char_pointer_type);
257 #if PTR_SIZE == 4
258 size_type.t = VT_INT | VT_UNSIGNED;
259 ptrdiff_type.t = VT_INT;
260 #elif LONG_SIZE == 4
261 size_type.t = VT_LLONG | VT_UNSIGNED;
262 ptrdiff_type.t = VT_LLONG;
263 #else
264 size_type.t = VT_LONG | VT_LLONG | VT_UNSIGNED;
265 ptrdiff_type.t = VT_LONG | VT_LLONG;
266 #endif
267 func_old_type.t = VT_FUNC;
268 func_old_type.ref = sym_push(SYM_FIELD, &int_type, 0, 0);
269 func_old_type.ref->f.func_call = FUNC_CDECL;
270 func_old_type.ref->f.func_type = FUNC_OLD;
272 tcc_debug_start(s1);
274 #ifdef TCC_TARGET_ARM
275 arm_init(s1);
276 #endif
278 #ifdef INC_DEBUG
279 printf("%s: **** new file\n", file->filename);
280 #endif
282 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM | PARSE_FLAG_TOK_STR;
283 next();
284 decl(VT_CONST);
285 gen_inline_functions(s1);
286 check_vstack();
287 /* end of translation unit info */
288 tcc_debug_end(s1);
289 return 0;
292 /* ------------------------------------------------------------------------- */
293 ST_FUNC ElfSym *elfsym(Sym *s)
295 if (!s || !s->c)
296 return NULL;
297 return &((ElfSym *)symtab_section->data)[s->c];
300 /* apply storage attributes to Elf symbol */
301 ST_FUNC void update_storage(Sym *sym)
303 ElfSym *esym;
304 int sym_bind, old_sym_bind;
306 esym = elfsym(sym);
307 if (!esym)
308 return;
310 if (sym->a.visibility)
311 esym->st_other = (esym->st_other & ~ELFW(ST_VISIBILITY)(-1))
312 | sym->a.visibility;
314 if (sym->type.t & VT_STATIC)
315 sym_bind = STB_LOCAL;
316 else if (sym->a.weak)
317 sym_bind = STB_WEAK;
318 else
319 sym_bind = STB_GLOBAL;
320 old_sym_bind = ELFW(ST_BIND)(esym->st_info);
321 if (sym_bind != old_sym_bind) {
322 esym->st_info = ELFW(ST_INFO)(sym_bind, ELFW(ST_TYPE)(esym->st_info));
325 #ifdef TCC_TARGET_PE
326 if (sym->a.dllimport)
327 esym->st_other |= ST_PE_IMPORT;
328 if (sym->a.dllexport)
329 esym->st_other |= ST_PE_EXPORT;
330 #endif
332 #if 0
333 printf("storage %s: bind=%c vis=%d exp=%d imp=%d\n",
334 get_tok_str(sym->v, NULL),
335 sym_bind == STB_WEAK ? 'w' : sym_bind == STB_LOCAL ? 'l' : 'g',
336 sym->a.visibility,
337 sym->a.dllexport,
338 sym->a.dllimport
340 #endif
343 /* ------------------------------------------------------------------------- */
344 /* update sym->c so that it points to an external symbol in section
345 'section' with value 'value' */
347 ST_FUNC void put_extern_sym2(Sym *sym, int sh_num,
348 addr_t value, unsigned long size,
349 int can_add_underscore)
351 int sym_type, sym_bind, info, other, t;
352 ElfSym *esym;
353 const char *name;
354 char buf1[256];
355 #ifdef CONFIG_TCC_BCHECK
356 char buf[32];
357 #endif
359 if (!sym->c) {
360 name = get_tok_str(sym->v, NULL);
361 #ifdef CONFIG_TCC_BCHECK
362 if (tcc_state->do_bounds_check) {
363 /* XXX: avoid doing that for statics ? */
364 /* if bound checking is activated, we change some function
365 names by adding the "__bound" prefix */
366 switch(sym->v) {
367 #ifdef TCC_TARGET_PE
368 /* XXX: we rely only on malloc hooks */
369 case TOK_malloc:
370 case TOK_free:
371 case TOK_realloc:
372 case TOK_memalign:
373 case TOK_calloc:
374 #endif
375 case TOK_memcpy:
376 case TOK_memmove:
377 case TOK_memset:
378 case TOK_strlen:
379 case TOK_strcpy:
380 case TOK_alloca:
381 strcpy(buf, "__bound_");
382 strcat(buf, name);
383 name = buf;
384 break;
387 #endif
388 t = sym->type.t;
389 if ((t & VT_BTYPE) == VT_FUNC) {
390 sym_type = STT_FUNC;
391 } else if ((t & VT_BTYPE) == VT_VOID) {
392 sym_type = STT_NOTYPE;
393 } else {
394 sym_type = STT_OBJECT;
396 if (t & VT_STATIC)
397 sym_bind = STB_LOCAL;
398 else
399 sym_bind = STB_GLOBAL;
400 other = 0;
401 #ifdef TCC_TARGET_PE
402 if (sym_type == STT_FUNC && sym->type.ref) {
403 Sym *ref = sym->type.ref;
404 if (ref->a.nodecorate) {
405 can_add_underscore = 0;
407 if (ref->f.func_call == FUNC_STDCALL && can_add_underscore) {
408 sprintf(buf1, "_%s@%d", name, ref->f.func_args * PTR_SIZE);
409 name = buf1;
410 other |= ST_PE_STDCALL;
411 can_add_underscore = 0;
414 #endif
415 if (tcc_state->leading_underscore && can_add_underscore) {
416 buf1[0] = '_';
417 pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
418 name = buf1;
420 if (sym->asm_label)
421 name = get_tok_str(sym->asm_label, NULL);
422 info = ELFW(ST_INFO)(sym_bind, sym_type);
423 sym->c = put_elf_sym(symtab_section, value, size, info, other, sh_num, name);
424 } else {
425 esym = elfsym(sym);
426 esym->st_value = value;
427 esym->st_size = size;
428 esym->st_shndx = sh_num;
430 update_storage(sym);
433 ST_FUNC void put_extern_sym(Sym *sym, Section *section,
434 addr_t value, unsigned long size)
436 int sh_num = section ? section->sh_num : SHN_UNDEF;
437 put_extern_sym2(sym, sh_num, value, size, 1);
440 /* add a new relocation entry to symbol 'sym' in section 's' */
441 ST_FUNC void greloca(Section *s, Sym *sym, unsigned long offset, int type,
442 addr_t addend)
444 int c = 0;
446 if (nocode_wanted && s == cur_text_section)
447 return;
449 if (sym) {
450 if (0 == sym->c)
451 put_extern_sym(sym, NULL, 0, 0);
452 c = sym->c;
455 /* now we can add ELF relocation info */
456 put_elf_reloca(symtab_section, s, offset, type, c, addend);
459 #if PTR_SIZE == 4
460 ST_FUNC void greloc(Section *s, Sym *sym, unsigned long offset, int type)
462 greloca(s, sym, offset, type, 0);
464 #endif
466 /* ------------------------------------------------------------------------- */
467 /* symbol allocator */
468 static Sym *__sym_malloc(void)
470 Sym *sym_pool, *sym, *last_sym;
471 int i;
473 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
474 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
476 last_sym = sym_free_first;
477 sym = sym_pool;
478 for(i = 0; i < SYM_POOL_NB; i++) {
479 sym->next = last_sym;
480 last_sym = sym;
481 sym++;
483 sym_free_first = last_sym;
484 return last_sym;
487 static inline Sym *sym_malloc(void)
489 Sym *sym;
490 #ifndef SYM_DEBUG
491 sym = sym_free_first;
492 if (!sym)
493 sym = __sym_malloc();
494 sym_free_first = sym->next;
495 return sym;
496 #else
497 sym = tcc_malloc(sizeof(Sym));
498 return sym;
499 #endif
502 ST_INLN void sym_free(Sym *sym)
504 #ifndef SYM_DEBUG
505 sym->next = sym_free_first;
506 sym_free_first = sym;
507 #else
508 tcc_free(sym);
509 #endif
512 /* push, without hashing */
513 ST_FUNC Sym *sym_push2(Sym **ps, int v, int t, int c)
515 Sym *s;
517 s = sym_malloc();
518 memset(s, 0, sizeof *s);
519 s->v = v;
520 s->type.t = t;
521 s->c = c;
522 /* add in stack */
523 s->prev = *ps;
524 *ps = s;
525 return s;
528 /* find a symbol and return its associated structure. 's' is the top
529 of the symbol stack */
530 ST_FUNC Sym *sym_find2(Sym *s, int v)
532 while (s) {
533 if (s->v == v)
534 return s;
535 else if (s->v == -1)
536 return NULL;
537 s = s->prev;
539 return NULL;
542 /* structure lookup */
543 ST_INLN Sym *struct_find(int v)
545 v -= TOK_IDENT;
546 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
547 return NULL;
548 return table_ident[v]->sym_struct;
551 /* find an identifier */
552 ST_INLN Sym *sym_find(int v)
554 v -= TOK_IDENT;
555 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
556 return NULL;
557 return table_ident[v]->sym_identifier;
560 /* push a given symbol on the symbol stack */
561 ST_FUNC Sym *sym_push(int v, CType *type, int r, int c)
563 Sym *s, **ps;
564 TokenSym *ts;
566 if (local_stack)
567 ps = &local_stack;
568 else
569 ps = &global_stack;
570 s = sym_push2(ps, v, type->t, c);
571 s->type.ref = type->ref;
572 s->r = r;
573 /* don't record fields or anonymous symbols */
574 /* XXX: simplify */
575 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
576 /* record symbol in token array */
577 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
578 if (v & SYM_STRUCT)
579 ps = &ts->sym_struct;
580 else
581 ps = &ts->sym_identifier;
582 s->prev_tok = *ps;
583 *ps = s;
584 s->sym_scope = local_scope;
585 if (s->prev_tok && s->prev_tok->sym_scope == s->sym_scope)
586 tcc_error("redeclaration of '%s'",
587 get_tok_str(v & ~SYM_STRUCT, NULL));
589 return s;
592 /* push a global identifier */
593 ST_FUNC Sym *global_identifier_push(int v, int t, int c)
595 Sym *s, **ps;
596 s = sym_push2(&global_stack, v, t, c);
597 /* don't record anonymous symbol */
598 if (v < SYM_FIRST_ANOM) {
599 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
600 /* modify the top most local identifier, so that
601 sym_identifier will point to 's' when popped */
602 while (*ps != NULL && (*ps)->sym_scope)
603 ps = &(*ps)->prev_tok;
604 s->prev_tok = *ps;
605 *ps = s;
607 return s;
610 /* pop symbols until top reaches 'b'. If KEEP is non-zero don't really
611 pop them yet from the list, but do remove them from the token array. */
612 ST_FUNC void sym_pop(Sym **ptop, Sym *b, int keep)
614 Sym *s, *ss, **ps;
615 TokenSym *ts;
616 int v;
618 s = *ptop;
619 while(s != b) {
620 ss = s->prev;
621 v = s->v;
622 /* remove symbol in token array */
623 /* XXX: simplify */
624 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
625 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
626 if (v & SYM_STRUCT)
627 ps = &ts->sym_struct;
628 else
629 ps = &ts->sym_identifier;
630 *ps = s->prev_tok;
632 if (!keep)
633 sym_free(s);
634 s = ss;
636 if (!keep)
637 *ptop = b;
640 /* ------------------------------------------------------------------------- */
642 static void vsetc(CType *type, int r, CValue *vc)
644 int v;
646 if (vtop >= vstack + (VSTACK_SIZE - 1))
647 tcc_error("memory full (vstack)");
648 /* cannot let cpu flags if other instruction are generated. Also
649 avoid leaving VT_JMP anywhere except on the top of the stack
650 because it would complicate the code generator.
652 Don't do this when nocode_wanted. vtop might come from
653 !nocode_wanted regions (see 88_codeopt.c) and transforming
654 it to a register without actually generating code is wrong
655 as their value might still be used for real. All values
656 we push under nocode_wanted will eventually be popped
657 again, so that the VT_CMP/VT_JMP value will be in vtop
658 when code is unsuppressed again.
660 Same logic below in vswap(); */
661 if (vtop >= vstack && !nocode_wanted) {
662 v = vtop->r & VT_VALMASK;
663 if (v == VT_CMP || (v & ~1) == VT_JMP)
664 gv(RC_INT);
667 vtop++;
668 vtop->type = *type;
669 vtop->r = r;
670 vtop->r2 = VT_CONST;
671 vtop->c = *vc;
672 vtop->sym = NULL;
675 ST_FUNC void vswap(void)
677 SValue tmp;
678 /* cannot vswap cpu flags. See comment at vsetc() above */
679 if (vtop >= vstack && !nocode_wanted) {
680 int v = vtop->r & VT_VALMASK;
681 if (v == VT_CMP || (v & ~1) == VT_JMP)
682 gv(RC_INT);
684 tmp = vtop[0];
685 vtop[0] = vtop[-1];
686 vtop[-1] = tmp;
689 /* pop stack value */
690 ST_FUNC void vpop(void)
692 int v;
693 v = vtop->r & VT_VALMASK;
694 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
695 /* for x86, we need to pop the FP stack */
696 if (v == TREG_ST0) {
697 o(0xd8dd); /* fstp %st(0) */
698 } else
699 #endif
700 if (v == VT_JMP || v == VT_JMPI) {
701 /* need to put correct jump if && or || without test */
702 gsym(vtop->c.i);
704 vtop--;
707 /* push constant of type "type" with useless value */
708 ST_FUNC void vpush(CType *type)
710 vset(type, VT_CONST, 0);
713 /* push integer constant */
714 ST_FUNC void vpushi(int v)
716 CValue cval;
717 cval.i = v;
718 vsetc(&int_type, VT_CONST, &cval);
721 /* push a pointer sized constant */
722 static void vpushs(addr_t v)
724 CValue cval;
725 cval.i = v;
726 vsetc(&size_type, VT_CONST, &cval);
729 /* push arbitrary 64bit constant */
730 ST_FUNC void vpush64(int ty, unsigned long long v)
732 CValue cval;
733 CType ctype;
734 ctype.t = ty;
735 ctype.ref = NULL;
736 cval.i = v;
737 vsetc(&ctype, VT_CONST, &cval);
740 /* push long long constant */
741 static inline void vpushll(long long v)
743 vpush64(VT_LLONG, v);
746 ST_FUNC void vset(CType *type, int r, int v)
748 CValue cval;
750 cval.i = v;
751 vsetc(type, r, &cval);
754 static void vseti(int r, int v)
756 CType type;
757 type.t = VT_INT;
758 type.ref = NULL;
759 vset(&type, r, v);
762 ST_FUNC void vpushv(SValue *v)
764 if (vtop >= vstack + (VSTACK_SIZE - 1))
765 tcc_error("memory full (vstack)");
766 vtop++;
767 *vtop = *v;
770 static void vdup(void)
772 vpushv(vtop);
775 /* rotate n first stack elements to the bottom
776 I1 ... In -> I2 ... In I1 [top is right]
778 ST_FUNC void vrotb(int n)
780 int i;
781 SValue tmp;
783 tmp = vtop[-n + 1];
784 for(i=-n+1;i!=0;i++)
785 vtop[i] = vtop[i+1];
786 vtop[0] = tmp;
789 /* rotate the n elements before entry e towards the top
790 I1 ... In ... -> In I1 ... I(n-1) ... [top is right]
792 ST_FUNC void vrote(SValue *e, int n)
794 int i;
795 SValue tmp;
797 tmp = *e;
798 for(i = 0;i < n - 1; i++)
799 e[-i] = e[-i - 1];
800 e[-n + 1] = tmp;
803 /* rotate n first stack elements to the top
804 I1 ... In -> In I1 ... I(n-1) [top is right]
806 ST_FUNC void vrott(int n)
808 vrote(vtop, n);
811 /* push a symbol value of TYPE */
812 static inline void vpushsym(CType *type, Sym *sym)
814 CValue cval;
815 cval.i = 0;
816 vsetc(type, VT_CONST | VT_SYM, &cval);
817 vtop->sym = sym;
820 /* Return a static symbol pointing to a section */
821 ST_FUNC Sym *get_sym_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
823 int v;
824 Sym *sym;
826 v = anon_sym++;
827 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
828 sym->type.ref = type->ref;
829 sym->r = VT_CONST | VT_SYM;
830 put_extern_sym(sym, sec, offset, size);
831 return sym;
834 /* push a reference to a section offset by adding a dummy symbol */
835 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
837 vpushsym(type, get_sym_ref(type, sec, offset, size));
840 /* define a new external reference to a symbol 'v' of type 'u' */
841 ST_FUNC Sym *external_global_sym(int v, CType *type, int r)
843 Sym *s;
845 s = sym_find(v);
846 if (!s) {
847 /* push forward reference */
848 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
849 s->type.ref = type->ref;
850 s->r = r | VT_CONST | VT_SYM;
851 } else if (IS_ASM_SYM(s)) {
852 s->type.t = type->t | (s->type.t & VT_EXTERN);
853 s->type.ref = type->ref;
854 update_storage(s);
856 return s;
859 /* Merge symbol attributes. */
860 static void merge_symattr(struct SymAttr *sa, struct SymAttr *sa1)
862 if (sa1->aligned && !sa->aligned)
863 sa->aligned = sa1->aligned;
864 sa->packed |= sa1->packed;
865 sa->weak |= sa1->weak;
866 if (sa1->visibility != STV_DEFAULT) {
867 int vis = sa->visibility;
868 if (vis == STV_DEFAULT
869 || vis > sa1->visibility)
870 vis = sa1->visibility;
871 sa->visibility = vis;
873 sa->dllexport |= sa1->dllexport;
874 sa->nodecorate |= sa1->nodecorate;
875 sa->dllimport |= sa1->dllimport;
878 /* Merge function attributes. */
879 static void merge_funcattr(struct FuncAttr *fa, struct FuncAttr *fa1)
881 if (fa1->func_call && !fa->func_call)
882 fa->func_call = fa1->func_call;
883 if (fa1->func_type && !fa->func_type)
884 fa->func_type = fa1->func_type;
885 if (fa1->func_args && !fa->func_args)
886 fa->func_args = fa1->func_args;
889 /* Merge attributes. */
890 static void merge_attr(AttributeDef *ad, AttributeDef *ad1)
892 merge_symattr(&ad->a, &ad1->a);
893 merge_funcattr(&ad->f, &ad1->f);
895 if (ad1->section)
896 ad->section = ad1->section;
897 if (ad1->alias_target)
898 ad->alias_target = ad1->alias_target;
899 if (ad1->asm_label)
900 ad->asm_label = ad1->asm_label;
901 if (ad1->attr_mode)
902 ad->attr_mode = ad1->attr_mode;
905 /* Merge some type attributes. */
906 static void patch_type(Sym *sym, CType *type)
908 if (!(type->t & VT_EXTERN)) {
909 if (!(sym->type.t & VT_EXTERN))
910 tcc_error("redefinition of '%s'", get_tok_str(sym->v, NULL));
911 sym->type.t &= ~VT_EXTERN;
914 if (IS_ASM_SYM(sym)) {
915 /* stay static if both are static */
916 sym->type.t = type->t & (sym->type.t | ~VT_STATIC);
917 sym->type.ref = type->ref;
920 if (!is_compatible_types(&sym->type, type)) {
921 tcc_error("incompatible types for redefinition of '%s'",
922 get_tok_str(sym->v, NULL));
924 } else if ((sym->type.t & VT_BTYPE) == VT_FUNC) {
925 int static_proto = sym->type.t & VT_STATIC;
926 /* warn if static follows non-static function declaration */
927 if ((type->t & VT_STATIC) && !static_proto && !(type->t & VT_INLINE))
928 tcc_warning("static storage ignored for redefinition of '%s'",
929 get_tok_str(sym->v, NULL));
931 if (0 == (type->t & VT_EXTERN)) {
932 /* put complete type, use static from prototype */
933 sym->type.t = (type->t & ~VT_STATIC) | static_proto;
934 if (type->t & VT_INLINE)
935 sym->type.t = type->t;
936 sym->type.ref = type->ref;
939 } else {
940 if ((sym->type.t & VT_ARRAY) && type->ref->c >= 0) {
941 /* set array size if it was omitted in extern declaration */
942 if (sym->type.ref->c < 0)
943 sym->type.ref->c = type->ref->c;
944 else if (sym->type.ref->c != type->ref->c)
945 tcc_error("conflicting type for '%s'", get_tok_str(sym->v, NULL));
947 if ((type->t ^ sym->type.t) & VT_STATIC)
948 tcc_warning("storage mismatch for redefinition of '%s'",
949 get_tok_str(sym->v, NULL));
954 /* Merge some storage attributes. */
955 static void patch_storage(Sym *sym, AttributeDef *ad, CType *type)
957 if (type)
958 patch_type(sym, type);
960 #ifdef TCC_TARGET_PE
961 if (sym->a.dllimport != ad->a.dllimport)
962 tcc_error("incompatible dll linkage for redefinition of '%s'",
963 get_tok_str(sym->v, NULL));
964 #endif
965 merge_symattr(&sym->a, &ad->a);
966 if (ad->asm_label)
967 sym->asm_label = ad->asm_label;
968 update_storage(sym);
971 /* define a new external reference to a symbol 'v' */
972 static Sym *external_sym(int v, CType *type, int r, AttributeDef *ad)
974 Sym *s;
975 s = sym_find(v);
976 if (!s) {
977 /* push forward reference */
978 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
979 s->type.t |= VT_EXTERN;
980 s->a = ad->a;
981 s->sym_scope = 0;
982 } else {
983 if (s->type.ref == func_old_type.ref) {
984 s->type.ref = type->ref;
985 s->r = r | VT_CONST | VT_SYM;
986 s->type.t |= VT_EXTERN;
988 patch_storage(s, ad, type);
990 return s;
993 /* push a reference to global symbol v */
994 ST_FUNC void vpush_global_sym(CType *type, int v)
996 vpushsym(type, external_global_sym(v, type, 0));
999 /* save registers up to (vtop - n) stack entry */
1000 ST_FUNC void save_regs(int n)
1002 SValue *p, *p1;
1003 for(p = vstack, p1 = vtop - n; p <= p1; p++)
1004 save_reg(p->r);
1007 /* save r to the memory stack, and mark it as being free */
1008 ST_FUNC void save_reg(int r)
1010 save_reg_upstack(r, 0);
1013 /* save r to the memory stack, and mark it as being free,
1014 if seen up to (vtop - n) stack entry */
1015 ST_FUNC void save_reg_upstack(int r, int n)
1017 int l, saved, size, align;
1018 SValue *p, *p1, sv;
1019 CType *type;
1021 if ((r &= VT_VALMASK) >= VT_CONST)
1022 return;
1023 if (nocode_wanted)
1024 return;
1026 /* modify all stack values */
1027 saved = 0;
1028 l = 0;
1029 for(p = vstack, p1 = vtop - n; p <= p1; p++) {
1030 if ((p->r & VT_VALMASK) == r ||
1031 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
1032 /* must save value on stack if not already done */
1033 if (!saved) {
1034 /* NOTE: must reload 'r' because r might be equal to r2 */
1035 r = p->r & VT_VALMASK;
1036 /* store register in the stack */
1037 type = &p->type;
1038 if ((p->r & VT_LVAL) ||
1039 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
1040 #if PTR_SIZE == 8
1041 type = &char_pointer_type;
1042 #else
1043 type = &int_type;
1044 #endif
1045 size = type_size(type, &align);
1046 l=get_temp_local_var(size,align);
1047 sv.type.t = type->t;
1048 sv.r = VT_LOCAL | VT_LVAL;
1049 sv.c.i = l;
1050 store(r, &sv);
1051 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1052 /* x86 specific: need to pop fp register ST0 if saved */
1053 if (r == TREG_ST0) {
1054 o(0xd8dd); /* fstp %st(0) */
1056 #endif
1057 #if PTR_SIZE == 4
1058 /* special long long case */
1059 if ((type->t & VT_BTYPE) == VT_LLONG) {
1060 sv.c.i += 4;
1061 store(p->r2, &sv);
1063 #endif
1064 saved = 1;
1066 /* mark that stack entry as being saved on the stack */
1067 if (p->r & VT_LVAL) {
1068 /* also clear the bounded flag because the
1069 relocation address of the function was stored in
1070 p->c.i */
1071 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
1072 } else {
1073 p->r = lvalue_type(p->type.t) | VT_LOCAL;
1075 p->r2 = VT_CONST;
1076 p->c.i = l;
1081 #ifdef TCC_TARGET_ARM
1082 /* find a register of class 'rc2' with at most one reference on stack.
1083 * If none, call get_reg(rc) */
1084 ST_FUNC int get_reg_ex(int rc, int rc2)
1086 int r;
1087 SValue *p;
1089 for(r=0;r<NB_REGS;r++) {
1090 if (reg_classes[r] & rc2) {
1091 int n;
1092 n=0;
1093 for(p = vstack; p <= vtop; p++) {
1094 if ((p->r & VT_VALMASK) == r ||
1095 (p->r2 & VT_VALMASK) == r)
1096 n++;
1098 if (n <= 1)
1099 return r;
1102 return get_reg(rc);
1104 #endif
1106 /* find a free register of class 'rc'. If none, save one register */
1107 ST_FUNC int get_reg(int rc)
1109 int r;
1110 SValue *p;
1112 /* find a free register */
1113 for(r=0;r<NB_REGS;r++) {
1114 if (reg_classes[r] & rc) {
1115 if (nocode_wanted)
1116 return r;
1117 for(p=vstack;p<=vtop;p++) {
1118 if ((p->r & VT_VALMASK) == r ||
1119 (p->r2 & VT_VALMASK) == r)
1120 goto notfound;
1122 return r;
1124 notfound: ;
1127 /* no register left : free the first one on the stack (VERY
1128 IMPORTANT to start from the bottom to ensure that we don't
1129 spill registers used in gen_opi()) */
1130 for(p=vstack;p<=vtop;p++) {
1131 /* look at second register (if long long) */
1132 r = p->r2 & VT_VALMASK;
1133 if (r < VT_CONST && (reg_classes[r] & rc))
1134 goto save_found;
1135 r = p->r & VT_VALMASK;
1136 if (r < VT_CONST && (reg_classes[r] & rc)) {
1137 save_found:
1138 save_reg(r);
1139 return r;
1142 /* Should never comes here */
1143 return -1;
1146 /* find a free temporary local variable (return the offset on stack) match the size and align. If none, add new temporary stack variable*/
1147 static int get_temp_local_var(int size,int align){
1148 int i;
1149 struct temp_local_variable *temp_var;
1150 int found_var;
1151 SValue *p;
1152 int r;
1153 char free;
1154 char found;
1155 found=0;
1156 for(i=0;i<nb_temp_local_vars;i++){
1157 temp_var=&arr_temp_local_vars[i];
1158 if(temp_var->size<size||align!=temp_var->align){
1159 continue;
1161 /*check if temp_var is free*/
1162 free=1;
1163 for(p=vstack;p<=vtop;p++) {
1164 r=p->r&VT_VALMASK;
1165 if(r==VT_LOCAL||r==VT_LLOCAL){
1166 if(p->c.i==temp_var->location){
1167 free=0;
1168 break;
1172 if(free){
1173 found_var=temp_var->location;
1174 found=1;
1175 break;
1178 if(!found){
1179 loc = (loc - size) & -align;
1180 if(nb_temp_local_vars<MAX_TEMP_LOCAL_VARIABLE_NUMBER){
1181 temp_var=&arr_temp_local_vars[i];
1182 temp_var->location=loc;
1183 temp_var->size=size;
1184 temp_var->align=align;
1185 nb_temp_local_vars++;
1187 found_var=loc;
1189 return found_var;
1192 static void clear_temp_local_var_list(){
1193 nb_temp_local_vars=0;
1196 /* move register 's' (of type 't') to 'r', and flush previous value of r to memory
1197 if needed */
1198 static void move_reg(int r, int s, int t)
1200 SValue sv;
1202 if (r != s) {
1203 save_reg(r);
1204 sv.type.t = t;
1205 sv.type.ref = NULL;
1206 sv.r = s;
1207 sv.c.i = 0;
1208 load(r, &sv);
1212 /* get address of vtop (vtop MUST BE an lvalue) */
1213 ST_FUNC void gaddrof(void)
1215 vtop->r &= ~VT_LVAL;
1216 /* tricky: if saved lvalue, then we can go back to lvalue */
1217 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
1218 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
1223 #ifdef CONFIG_TCC_BCHECK
1224 /* generate lvalue bound code */
1225 static void gbound(void)
1227 int lval_type;
1228 CType type1;
1230 vtop->r &= ~VT_MUSTBOUND;
1231 /* if lvalue, then use checking code before dereferencing */
1232 if (vtop->r & VT_LVAL) {
1233 /* if not VT_BOUNDED value, then make one */
1234 if (!(vtop->r & VT_BOUNDED)) {
1235 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
1236 /* must save type because we must set it to int to get pointer */
1237 type1 = vtop->type;
1238 vtop->type.t = VT_PTR;
1239 gaddrof();
1240 vpushi(0);
1241 gen_bounded_ptr_add();
1242 vtop->r |= lval_type;
1243 vtop->type = type1;
1245 /* then check for dereferencing */
1246 gen_bounded_ptr_deref();
1249 #endif
1251 static void incr_bf_adr(int o)
1253 vtop->type = char_pointer_type;
1254 gaddrof();
1255 vpushi(o);
1256 gen_op('+');
1257 vtop->type.t = (vtop->type.t & ~(VT_BTYPE|VT_DEFSIGN))
1258 | (VT_BYTE|VT_UNSIGNED);
1259 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
1260 | (VT_LVAL_BYTE|VT_LVAL_UNSIGNED|VT_LVAL);
1263 /* single-byte load mode for packed or otherwise unaligned bitfields */
1264 static void load_packed_bf(CType *type, int bit_pos, int bit_size)
1266 int n, o, bits;
1267 save_reg_upstack(vtop->r, 1);
1268 vpush64(type->t & VT_BTYPE, 0); // B X
1269 bits = 0, o = bit_pos >> 3, bit_pos &= 7;
1270 do {
1271 vswap(); // X B
1272 incr_bf_adr(o);
1273 vdup(); // X B B
1274 n = 8 - bit_pos;
1275 if (n > bit_size)
1276 n = bit_size;
1277 if (bit_pos)
1278 vpushi(bit_pos), gen_op(TOK_SHR), bit_pos = 0; // X B Y
1279 if (n < 8)
1280 vpushi((1 << n) - 1), gen_op('&');
1281 gen_cast(type);
1282 if (bits)
1283 vpushi(bits), gen_op(TOK_SHL);
1284 vrotb(3); // B Y X
1285 gen_op('|'); // B X
1286 bits += n, bit_size -= n, o = 1;
1287 } while (bit_size);
1288 vswap(), vpop();
1289 if (!(type->t & VT_UNSIGNED)) {
1290 n = ((type->t & VT_BTYPE) == VT_LLONG ? 64 : 32) - bits;
1291 vpushi(n), gen_op(TOK_SHL);
1292 vpushi(n), gen_op(TOK_SAR);
1296 /* single-byte store mode for packed or otherwise unaligned bitfields */
1297 static void store_packed_bf(int bit_pos, int bit_size)
1299 int bits, n, o, m, c;
1301 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1302 vswap(); // X B
1303 save_reg_upstack(vtop->r, 1);
1304 bits = 0, o = bit_pos >> 3, bit_pos &= 7;
1305 do {
1306 incr_bf_adr(o); // X B
1307 vswap(); //B X
1308 c ? vdup() : gv_dup(); // B V X
1309 vrott(3); // X B V
1310 if (bits)
1311 vpushi(bits), gen_op(TOK_SHR);
1312 if (bit_pos)
1313 vpushi(bit_pos), gen_op(TOK_SHL);
1314 n = 8 - bit_pos;
1315 if (n > bit_size)
1316 n = bit_size;
1317 if (n < 8) {
1318 m = ((1 << n) - 1) << bit_pos;
1319 vpushi(m), gen_op('&'); // X B V1
1320 vpushv(vtop-1); // X B V1 B
1321 vpushi(m & 0x80 ? ~m & 0x7f : ~m);
1322 gen_op('&'); // X B V1 B1
1323 gen_op('|'); // X B V2
1325 vdup(), vtop[-1] = vtop[-2]; // X B B V2
1326 vstore(), vpop(); // X B
1327 bits += n, bit_size -= n, bit_pos = 0, o = 1;
1328 } while (bit_size);
1329 vpop(), vpop();
1332 static int adjust_bf(SValue *sv, int bit_pos, int bit_size)
1334 int t;
1335 if (0 == sv->type.ref)
1336 return 0;
1337 t = sv->type.ref->auxtype;
1338 if (t != -1 && t != VT_STRUCT) {
1339 sv->type.t = (sv->type.t & ~VT_BTYPE) | t;
1340 sv->r = (sv->r & ~VT_LVAL_TYPE) | lvalue_type(sv->type.t);
1342 return t;
1345 /* store vtop a register belonging to class 'rc'. lvalues are
1346 converted to values. Cannot be used if cannot be converted to
1347 register value (such as structures). */
1348 ST_FUNC int gv(int rc)
1350 int r, bit_pos, bit_size, size, align, rc2;
1352 /* NOTE: get_reg can modify vstack[] */
1353 if (vtop->type.t & VT_BITFIELD) {
1354 CType type;
1356 bit_pos = BIT_POS(vtop->type.t);
1357 bit_size = BIT_SIZE(vtop->type.t);
1358 /* remove bit field info to avoid loops */
1359 vtop->type.t &= ~VT_STRUCT_MASK;
1361 type.ref = NULL;
1362 type.t = vtop->type.t & VT_UNSIGNED;
1363 if ((vtop->type.t & VT_BTYPE) == VT_BOOL)
1364 type.t |= VT_UNSIGNED;
1366 r = adjust_bf(vtop, bit_pos, bit_size);
1368 if ((vtop->type.t & VT_BTYPE) == VT_LLONG)
1369 type.t |= VT_LLONG;
1370 else
1371 type.t |= VT_INT;
1373 if (r == VT_STRUCT) {
1374 load_packed_bf(&type, bit_pos, bit_size);
1375 } else {
1376 int bits = (type.t & VT_BTYPE) == VT_LLONG ? 64 : 32;
1377 /* cast to int to propagate signedness in following ops */
1378 gen_cast(&type);
1379 /* generate shifts */
1380 vpushi(bits - (bit_pos + bit_size));
1381 gen_op(TOK_SHL);
1382 vpushi(bits - bit_size);
1383 /* NOTE: transformed to SHR if unsigned */
1384 gen_op(TOK_SAR);
1386 r = gv(rc);
1387 } else {
1388 if (is_float(vtop->type.t) &&
1389 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
1390 unsigned long offset;
1391 /* CPUs usually cannot use float constants, so we store them
1392 generically in data segment */
1393 size = type_size(&vtop->type, &align);
1394 if (NODATA_WANTED)
1395 size = 0, align = 1;
1396 offset = section_add(data_section, size, align);
1397 vpush_ref(&vtop->type, data_section, offset, size);
1398 vswap();
1399 init_putv(&vtop->type, data_section, offset);
1400 vtop->r |= VT_LVAL;
1402 #ifdef CONFIG_TCC_BCHECK
1403 if (vtop->r & VT_MUSTBOUND)
1404 gbound();
1405 #endif
1407 r = vtop->r & VT_VALMASK;
1408 rc2 = (rc & RC_FLOAT) ? RC_FLOAT : RC_INT;
1409 #ifndef TCC_TARGET_ARM64
1410 if (rc == RC_IRET)
1411 rc2 = RC_LRET;
1412 #ifdef TCC_TARGET_X86_64
1413 else if (rc == RC_FRET)
1414 rc2 = RC_QRET;
1415 #endif
1416 #endif
1417 /* need to reload if:
1418 - constant
1419 - lvalue (need to dereference pointer)
1420 - already a register, but not in the right class */
1421 if (r >= VT_CONST
1422 || (vtop->r & VT_LVAL)
1423 || !(reg_classes[r] & rc)
1424 #if PTR_SIZE == 8
1425 || ((vtop->type.t & VT_BTYPE) == VT_QLONG && !(reg_classes[vtop->r2] & rc2))
1426 || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT && !(reg_classes[vtop->r2] & rc2))
1427 #else
1428 || ((vtop->type.t & VT_BTYPE) == VT_LLONG && !(reg_classes[vtop->r2] & rc2))
1429 #endif
1432 r = get_reg(rc);
1433 #if PTR_SIZE == 8
1434 if (((vtop->type.t & VT_BTYPE) == VT_QLONG) || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT)) {
1435 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
1436 #else
1437 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
1438 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
1439 unsigned long long ll;
1440 #endif
1441 int r2, original_type;
1442 original_type = vtop->type.t;
1443 /* two register type load : expand to two words
1444 temporarily */
1445 #if PTR_SIZE == 4
1446 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
1447 /* load constant */
1448 ll = vtop->c.i;
1449 vtop->c.i = ll; /* first word */
1450 load(r, vtop);
1451 vtop->r = r; /* save register value */
1452 vpushi(ll >> 32); /* second word */
1453 } else
1454 #endif
1455 if (vtop->r & VT_LVAL) {
1456 /* We do not want to modifier the long long
1457 pointer here, so the safest (and less
1458 efficient) is to save all the other registers
1459 in the stack. XXX: totally inefficient. */
1460 #if 0
1461 save_regs(1);
1462 #else
1463 /* lvalue_save: save only if used further down the stack */
1464 save_reg_upstack(vtop->r, 1);
1465 #endif
1466 /* load from memory */
1467 vtop->type.t = load_type;
1468 load(r, vtop);
1469 vdup();
1470 vtop[-1].r = r; /* save register value */
1471 /* increment pointer to get second word */
1472 vtop->type.t = addr_type;
1473 gaddrof();
1474 vpushi(load_size);
1475 gen_op('+');
1476 vtop->r |= VT_LVAL;
1477 vtop->type.t = load_type;
1478 } else {
1479 /* move registers */
1480 load(r, vtop);
1481 vdup();
1482 vtop[-1].r = r; /* save register value */
1483 vtop->r = vtop[-1].r2;
1485 /* Allocate second register. Here we rely on the fact that
1486 get_reg() tries first to free r2 of an SValue. */
1487 r2 = get_reg(rc2);
1488 load(r2, vtop);
1489 vpop();
1490 /* write second register */
1491 vtop->r2 = r2;
1492 vtop->type.t = original_type;
1493 } else if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
1494 int t1, t;
1495 /* lvalue of scalar type : need to use lvalue type
1496 because of possible cast */
1497 t = vtop->type.t;
1498 t1 = t;
1499 /* compute memory access type */
1500 if (vtop->r & VT_LVAL_BYTE)
1501 t = VT_BYTE;
1502 else if (vtop->r & VT_LVAL_SHORT)
1503 t = VT_SHORT;
1504 if (vtop->r & VT_LVAL_UNSIGNED)
1505 t |= VT_UNSIGNED;
1506 vtop->type.t = t;
1507 load(r, vtop);
1508 /* restore wanted type */
1509 vtop->type.t = t1;
1510 } else {
1511 /* one register type load */
1512 load(r, vtop);
1515 vtop->r = r;
1516 #ifdef TCC_TARGET_C67
1517 /* uses register pairs for doubles */
1518 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
1519 vtop->r2 = r+1;
1520 #endif
1522 return r;
1525 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
1526 ST_FUNC void gv2(int rc1, int rc2)
1528 int v;
1530 /* generate more generic register first. But VT_JMP or VT_CMP
1531 values must be generated first in all cases to avoid possible
1532 reload errors */
1533 v = vtop[0].r & VT_VALMASK;
1534 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
1535 vswap();
1536 gv(rc1);
1537 vswap();
1538 gv(rc2);
1539 /* test if reload is needed for first register */
1540 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
1541 vswap();
1542 gv(rc1);
1543 vswap();
1545 } else {
1546 gv(rc2);
1547 vswap();
1548 gv(rc1);
1549 vswap();
1550 /* test if reload is needed for first register */
1551 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
1552 gv(rc2);
1557 #ifndef TCC_TARGET_ARM64
1558 /* wrapper around RC_FRET to return a register by type */
1559 static int rc_fret(int t)
1561 #ifdef TCC_TARGET_X86_64
1562 if (t == VT_LDOUBLE) {
1563 return RC_ST0;
1565 #endif
1566 return RC_FRET;
1568 #endif
1570 /* wrapper around REG_FRET to return a register by type */
1571 static int reg_fret(int t)
1573 #ifdef TCC_TARGET_X86_64
1574 if (t == VT_LDOUBLE) {
1575 return TREG_ST0;
1577 #endif
1578 return REG_FRET;
1581 #if PTR_SIZE == 4
1582 /* expand 64bit on stack in two ints */
1583 ST_FUNC void lexpand(void)
1585 int u, v;
1586 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
1587 v = vtop->r & (VT_VALMASK | VT_LVAL);
1588 if (v == VT_CONST) {
1589 vdup();
1590 vtop[0].c.i >>= 32;
1591 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
1592 vdup();
1593 vtop[0].c.i += 4;
1594 } else {
1595 gv(RC_INT);
1596 vdup();
1597 vtop[0].r = vtop[-1].r2;
1598 vtop[0].r2 = vtop[-1].r2 = VT_CONST;
1600 vtop[0].type.t = vtop[-1].type.t = VT_INT | u;
1602 #endif
1604 #if PTR_SIZE == 4
1605 /* build a long long from two ints */
1606 static void lbuild(int t)
1608 gv2(RC_INT, RC_INT);
1609 vtop[-1].r2 = vtop[0].r;
1610 vtop[-1].type.t = t;
1611 vpop();
1613 #endif
1615 /* convert stack entry to register and duplicate its value in another
1616 register */
1617 static void gv_dup(void)
1619 int rc, t, r, r1;
1620 SValue sv;
1622 t = vtop->type.t;
1623 #if PTR_SIZE == 4
1624 if ((t & VT_BTYPE) == VT_LLONG) {
1625 if (t & VT_BITFIELD) {
1626 gv(RC_INT);
1627 t = vtop->type.t;
1629 lexpand();
1630 gv_dup();
1631 vswap();
1632 vrotb(3);
1633 gv_dup();
1634 vrotb(4);
1635 /* stack: H L L1 H1 */
1636 lbuild(t);
1637 vrotb(3);
1638 vrotb(3);
1639 vswap();
1640 lbuild(t);
1641 vswap();
1642 } else
1643 #endif
1645 /* duplicate value */
1646 rc = RC_INT;
1647 sv.type.t = VT_INT;
1648 if (is_float(t)) {
1649 rc = RC_FLOAT;
1650 #ifdef TCC_TARGET_X86_64
1651 if ((t & VT_BTYPE) == VT_LDOUBLE) {
1652 rc = RC_ST0;
1654 #endif
1655 sv.type.t = t;
1657 r = gv(rc);
1658 r1 = get_reg(rc);
1659 sv.r = r;
1660 sv.c.i = 0;
1661 load(r1, &sv); /* move r to r1 */
1662 vdup();
1663 /* duplicates value */
1664 if (r != r1)
1665 vtop->r = r1;
1669 /* Generate value test
1671 * Generate a test for any value (jump, comparison and integers) */
1672 ST_FUNC int gvtst(int inv, int t)
1674 int v = vtop->r & VT_VALMASK;
1675 if (v != VT_CMP && v != VT_JMP && v != VT_JMPI) {
1676 vpushi(0);
1677 gen_op(TOK_NE);
1679 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1680 /* constant jmp optimization */
1681 if ((vtop->c.i != 0) != inv)
1682 t = gjmp(t);
1683 vtop--;
1684 return t;
1686 return gtst(inv, t);
1689 #if PTR_SIZE == 4
1690 /* generate CPU independent (unsigned) long long operations */
1691 static void gen_opl(int op)
1693 int t, a, b, op1, c, i;
1694 int func;
1695 unsigned short reg_iret = REG_IRET;
1696 unsigned short reg_lret = REG_LRET;
1697 SValue tmp;
1699 switch(op) {
1700 case '/':
1701 case TOK_PDIV:
1702 func = TOK___divdi3;
1703 goto gen_func;
1704 case TOK_UDIV:
1705 func = TOK___udivdi3;
1706 goto gen_func;
1707 case '%':
1708 func = TOK___moddi3;
1709 goto gen_mod_func;
1710 case TOK_UMOD:
1711 func = TOK___umoddi3;
1712 gen_mod_func:
1713 #ifdef TCC_ARM_EABI
1714 reg_iret = TREG_R2;
1715 reg_lret = TREG_R3;
1716 #endif
1717 gen_func:
1718 /* call generic long long function */
1719 vpush_global_sym(&func_old_type, func);
1720 vrott(3);
1721 gfunc_call(2);
1722 vpushi(0);
1723 vtop->r = reg_iret;
1724 vtop->r2 = reg_lret;
1725 break;
1726 case '^':
1727 case '&':
1728 case '|':
1729 case '*':
1730 case '+':
1731 case '-':
1732 //pv("gen_opl A",0,2);
1733 t = vtop->type.t;
1734 vswap();
1735 lexpand();
1736 vrotb(3);
1737 lexpand();
1738 /* stack: L1 H1 L2 H2 */
1739 tmp = vtop[0];
1740 vtop[0] = vtop[-3];
1741 vtop[-3] = tmp;
1742 tmp = vtop[-2];
1743 vtop[-2] = vtop[-3];
1744 vtop[-3] = tmp;
1745 vswap();
1746 /* stack: H1 H2 L1 L2 */
1747 //pv("gen_opl B",0,4);
1748 if (op == '*') {
1749 vpushv(vtop - 1);
1750 vpushv(vtop - 1);
1751 gen_op(TOK_UMULL);
1752 lexpand();
1753 /* stack: H1 H2 L1 L2 ML MH */
1754 for(i=0;i<4;i++)
1755 vrotb(6);
1756 /* stack: ML MH H1 H2 L1 L2 */
1757 tmp = vtop[0];
1758 vtop[0] = vtop[-2];
1759 vtop[-2] = tmp;
1760 /* stack: ML MH H1 L2 H2 L1 */
1761 gen_op('*');
1762 vrotb(3);
1763 vrotb(3);
1764 gen_op('*');
1765 /* stack: ML MH M1 M2 */
1766 gen_op('+');
1767 gen_op('+');
1768 } else if (op == '+' || op == '-') {
1769 /* XXX: add non carry method too (for MIPS or alpha) */
1770 if (op == '+')
1771 op1 = TOK_ADDC1;
1772 else
1773 op1 = TOK_SUBC1;
1774 gen_op(op1);
1775 /* stack: H1 H2 (L1 op L2) */
1776 vrotb(3);
1777 vrotb(3);
1778 gen_op(op1 + 1); /* TOK_xxxC2 */
1779 } else {
1780 gen_op(op);
1781 /* stack: H1 H2 (L1 op L2) */
1782 vrotb(3);
1783 vrotb(3);
1784 /* stack: (L1 op L2) H1 H2 */
1785 gen_op(op);
1786 /* stack: (L1 op L2) (H1 op H2) */
1788 /* stack: L H */
1789 lbuild(t);
1790 break;
1791 case TOK_SAR:
1792 case TOK_SHR:
1793 case TOK_SHL:
1794 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1795 t = vtop[-1].type.t;
1796 vswap();
1797 lexpand();
1798 vrotb(3);
1799 /* stack: L H shift */
1800 c = (int)vtop->c.i;
1801 /* constant: simpler */
1802 /* NOTE: all comments are for SHL. the other cases are
1803 done by swapping words */
1804 vpop();
1805 if (op != TOK_SHL)
1806 vswap();
1807 if (c >= 32) {
1808 /* stack: L H */
1809 vpop();
1810 if (c > 32) {
1811 vpushi(c - 32);
1812 gen_op(op);
1814 if (op != TOK_SAR) {
1815 vpushi(0);
1816 } else {
1817 gv_dup();
1818 vpushi(31);
1819 gen_op(TOK_SAR);
1821 vswap();
1822 } else {
1823 vswap();
1824 gv_dup();
1825 /* stack: H L L */
1826 vpushi(c);
1827 gen_op(op);
1828 vswap();
1829 vpushi(32 - c);
1830 if (op == TOK_SHL)
1831 gen_op(TOK_SHR);
1832 else
1833 gen_op(TOK_SHL);
1834 vrotb(3);
1835 /* stack: L L H */
1836 vpushi(c);
1837 if (op == TOK_SHL)
1838 gen_op(TOK_SHL);
1839 else
1840 gen_op(TOK_SHR);
1841 gen_op('|');
1843 if (op != TOK_SHL)
1844 vswap();
1845 lbuild(t);
1846 } else {
1847 /* XXX: should provide a faster fallback on x86 ? */
1848 switch(op) {
1849 case TOK_SAR:
1850 func = TOK___ashrdi3;
1851 goto gen_func;
1852 case TOK_SHR:
1853 func = TOK___lshrdi3;
1854 goto gen_func;
1855 case TOK_SHL:
1856 func = TOK___ashldi3;
1857 goto gen_func;
1860 break;
1861 default:
1862 /* compare operations */
1863 t = vtop->type.t;
1864 vswap();
1865 lexpand();
1866 vrotb(3);
1867 lexpand();
1868 /* stack: L1 H1 L2 H2 */
1869 tmp = vtop[-1];
1870 vtop[-1] = vtop[-2];
1871 vtop[-2] = tmp;
1872 /* stack: L1 L2 H1 H2 */
1873 /* compare high */
1874 op1 = op;
1875 /* when values are equal, we need to compare low words. since
1876 the jump is inverted, we invert the test too. */
1877 if (op1 == TOK_LT)
1878 op1 = TOK_LE;
1879 else if (op1 == TOK_GT)
1880 op1 = TOK_GE;
1881 else if (op1 == TOK_ULT)
1882 op1 = TOK_ULE;
1883 else if (op1 == TOK_UGT)
1884 op1 = TOK_UGE;
1885 a = 0;
1886 b = 0;
1887 gen_op(op1);
1888 if (op == TOK_NE) {
1889 b = gvtst(0, 0);
1890 } else {
1891 a = gvtst(1, 0);
1892 if (op != TOK_EQ) {
1893 /* generate non equal test */
1894 vpushi(TOK_NE);
1895 vtop->r = VT_CMP;
1896 b = gvtst(0, 0);
1899 /* compare low. Always unsigned */
1900 op1 = op;
1901 if (op1 == TOK_LT)
1902 op1 = TOK_ULT;
1903 else if (op1 == TOK_LE)
1904 op1 = TOK_ULE;
1905 else if (op1 == TOK_GT)
1906 op1 = TOK_UGT;
1907 else if (op1 == TOK_GE)
1908 op1 = TOK_UGE;
1909 gen_op(op1);
1910 a = gvtst(1, a);
1911 gsym(b);
1912 vseti(VT_JMPI, a);
1913 break;
1916 #endif
1918 static uint64_t gen_opic_sdiv(uint64_t a, uint64_t b)
1920 uint64_t x = (a >> 63 ? -a : a) / (b >> 63 ? -b : b);
1921 return (a ^ b) >> 63 ? -x : x;
1924 static int gen_opic_lt(uint64_t a, uint64_t b)
1926 return (a ^ (uint64_t)1 << 63) < (b ^ (uint64_t)1 << 63);
1929 /* handle integer constant optimizations and various machine
1930 independent opt */
1931 static void gen_opic(int op)
1933 SValue *v1 = vtop - 1;
1934 SValue *v2 = vtop;
1935 int t1 = v1->type.t & VT_BTYPE;
1936 int t2 = v2->type.t & VT_BTYPE;
1937 int c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1938 int c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1939 uint64_t l1 = c1 ? v1->c.i : 0;
1940 uint64_t l2 = c2 ? v2->c.i : 0;
1941 int shm = (t1 == VT_LLONG) ? 63 : 31;
1943 if (t1 != VT_LLONG && (PTR_SIZE != 8 || t1 != VT_PTR))
1944 l1 = ((uint32_t)l1 |
1945 (v1->type.t & VT_UNSIGNED ? 0 : -(l1 & 0x80000000)));
1946 if (t2 != VT_LLONG && (PTR_SIZE != 8 || t2 != VT_PTR))
1947 l2 = ((uint32_t)l2 |
1948 (v2->type.t & VT_UNSIGNED ? 0 : -(l2 & 0x80000000)));
1950 if (c1 && c2) {
1951 switch(op) {
1952 case '+': l1 += l2; break;
1953 case '-': l1 -= l2; break;
1954 case '&': l1 &= l2; break;
1955 case '^': l1 ^= l2; break;
1956 case '|': l1 |= l2; break;
1957 case '*': l1 *= l2; break;
1959 case TOK_PDIV:
1960 case '/':
1961 case '%':
1962 case TOK_UDIV:
1963 case TOK_UMOD:
1964 /* if division by zero, generate explicit division */
1965 if (l2 == 0) {
1966 if (const_wanted)
1967 tcc_error("division by zero in constant");
1968 goto general_case;
1970 switch(op) {
1971 default: l1 = gen_opic_sdiv(l1, l2); break;
1972 case '%': l1 = l1 - l2 * gen_opic_sdiv(l1, l2); break;
1973 case TOK_UDIV: l1 = l1 / l2; break;
1974 case TOK_UMOD: l1 = l1 % l2; break;
1976 break;
1977 case TOK_SHL: l1 <<= (l2 & shm); break;
1978 case TOK_SHR: l1 >>= (l2 & shm); break;
1979 case TOK_SAR:
1980 l1 = (l1 >> 63) ? ~(~l1 >> (l2 & shm)) : l1 >> (l2 & shm);
1981 break;
1982 /* tests */
1983 case TOK_ULT: l1 = l1 < l2; break;
1984 case TOK_UGE: l1 = l1 >= l2; break;
1985 case TOK_EQ: l1 = l1 == l2; break;
1986 case TOK_NE: l1 = l1 != l2; break;
1987 case TOK_ULE: l1 = l1 <= l2; break;
1988 case TOK_UGT: l1 = l1 > l2; break;
1989 case TOK_LT: l1 = gen_opic_lt(l1, l2); break;
1990 case TOK_GE: l1 = !gen_opic_lt(l1, l2); break;
1991 case TOK_LE: l1 = !gen_opic_lt(l2, l1); break;
1992 case TOK_GT: l1 = gen_opic_lt(l2, l1); break;
1993 /* logical */
1994 case TOK_LAND: l1 = l1 && l2; break;
1995 case TOK_LOR: l1 = l1 || l2; break;
1996 default:
1997 goto general_case;
1999 if (t1 != VT_LLONG && (PTR_SIZE != 8 || t1 != VT_PTR))
2000 l1 = ((uint32_t)l1 |
2001 (v1->type.t & VT_UNSIGNED ? 0 : -(l1 & 0x80000000)));
2002 v1->c.i = l1;
2003 vtop--;
2004 } else {
2005 /* if commutative ops, put c2 as constant */
2006 if (c1 && (op == '+' || op == '&' || op == '^' ||
2007 op == '|' || op == '*')) {
2008 vswap();
2009 c2 = c1; //c = c1, c1 = c2, c2 = c;
2010 l2 = l1; //l = l1, l1 = l2, l2 = l;
2012 if (!const_wanted &&
2013 c1 && ((l1 == 0 &&
2014 (op == TOK_SHL || op == TOK_SHR || op == TOK_SAR)) ||
2015 (l1 == -1 && op == TOK_SAR))) {
2016 /* treat (0 << x), (0 >> x) and (-1 >> x) as constant */
2017 vtop--;
2018 } else if (!const_wanted &&
2019 c2 && ((l2 == 0 && (op == '&' || op == '*')) ||
2020 (op == '|' &&
2021 (l2 == -1 || (l2 == 0xFFFFFFFF && t2 != VT_LLONG))) ||
2022 (l2 == 1 && (op == '%' || op == TOK_UMOD)))) {
2023 /* treat (x & 0), (x * 0), (x | -1) and (x % 1) as constant */
2024 if (l2 == 1)
2025 vtop->c.i = 0;
2026 vswap();
2027 vtop--;
2028 } else if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
2029 op == TOK_PDIV) &&
2030 l2 == 1) ||
2031 ((op == '+' || op == '-' || op == '|' || op == '^' ||
2032 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
2033 l2 == 0) ||
2034 (op == '&' &&
2035 (l2 == -1 || (l2 == 0xFFFFFFFF && t2 != VT_LLONG))))) {
2036 /* filter out NOP operations like x*1, x-0, x&-1... */
2037 vtop--;
2038 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
2039 /* try to use shifts instead of muls or divs */
2040 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
2041 int n = -1;
2042 while (l2) {
2043 l2 >>= 1;
2044 n++;
2046 vtop->c.i = n;
2047 if (op == '*')
2048 op = TOK_SHL;
2049 else if (op == TOK_PDIV)
2050 op = TOK_SAR;
2051 else
2052 op = TOK_SHR;
2054 goto general_case;
2055 } else if (c2 && (op == '+' || op == '-') &&
2056 (((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM))
2057 || (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
2058 /* symbol + constant case */
2059 if (op == '-')
2060 l2 = -l2;
2061 l2 += vtop[-1].c.i;
2062 /* The backends can't always deal with addends to symbols
2063 larger than +-1<<31. Don't construct such. */
2064 if ((int)l2 != l2)
2065 goto general_case;
2066 vtop--;
2067 vtop->c.i = l2;
2068 } else {
2069 general_case:
2070 /* call low level op generator */
2071 if (t1 == VT_LLONG || t2 == VT_LLONG ||
2072 (PTR_SIZE == 8 && (t1 == VT_PTR || t2 == VT_PTR)))
2073 gen_opl(op);
2074 else
2075 gen_opi(op);
2080 /* generate a floating point operation with constant propagation */
2081 static void gen_opif(int op)
2083 int c1, c2;
2084 SValue *v1, *v2;
2085 #if defined _MSC_VER && defined _AMD64_
2086 /* avoid bad optimization with f1 -= f2 for f1:-0.0, f2:0.0 */
2087 volatile
2088 #endif
2089 long double f1, f2;
2091 v1 = vtop - 1;
2092 v2 = vtop;
2093 /* currently, we cannot do computations with forward symbols */
2094 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
2095 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
2096 if (c1 && c2) {
2097 if (v1->type.t == VT_FLOAT) {
2098 f1 = v1->c.f;
2099 f2 = v2->c.f;
2100 } else if (v1->type.t == VT_DOUBLE) {
2101 f1 = v1->c.d;
2102 f2 = v2->c.d;
2103 } else {
2104 f1 = v1->c.ld;
2105 f2 = v2->c.ld;
2108 /* NOTE: we only do constant propagation if finite number (not
2109 NaN or infinity) (ANSI spec) */
2110 if (!ieee_finite(f1) || !ieee_finite(f2))
2111 goto general_case;
2113 switch(op) {
2114 case '+': f1 += f2; break;
2115 case '-': f1 -= f2; break;
2116 case '*': f1 *= f2; break;
2117 case '/':
2118 if (f2 == 0.0) {
2119 /* If not in initializer we need to potentially generate
2120 FP exceptions at runtime, otherwise we want to fold. */
2121 if (!const_wanted)
2122 goto general_case;
2124 f1 /= f2;
2125 break;
2126 /* XXX: also handles tests ? */
2127 default:
2128 goto general_case;
2130 /* XXX: overflow test ? */
2131 if (v1->type.t == VT_FLOAT) {
2132 v1->c.f = f1;
2133 } else if (v1->type.t == VT_DOUBLE) {
2134 v1->c.d = f1;
2135 } else {
2136 v1->c.ld = f1;
2138 vtop--;
2139 } else {
2140 general_case:
2141 gen_opf(op);
2145 static int pointed_size(CType *type)
2147 int align;
2148 return type_size(pointed_type(type), &align);
2151 static void vla_runtime_pointed_size(CType *type)
2153 int align;
2154 vla_runtime_type_size(pointed_type(type), &align);
2157 static inline int is_null_pointer(SValue *p)
2159 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
2160 return 0;
2161 return ((p->type.t & VT_BTYPE) == VT_INT && (uint32_t)p->c.i == 0) ||
2162 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.i == 0) ||
2163 ((p->type.t & VT_BTYPE) == VT_PTR &&
2164 (PTR_SIZE == 4 ? (uint32_t)p->c.i == 0 : p->c.i == 0) &&
2165 ((pointed_type(&p->type)->t & VT_BTYPE) == VT_VOID) &&
2166 0 == (pointed_type(&p->type)->t & (VT_CONSTANT | VT_VOLATILE))
2169 static inline int is_integer_btype(int bt)
2171 return (bt == VT_BYTE || bt == VT_SHORT ||
2172 bt == VT_INT || bt == VT_LLONG);
2175 /* check types for comparison or subtraction of pointers */
2176 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
2178 CType *type1, *type2, tmp_type1, tmp_type2;
2179 int bt1, bt2;
2181 /* null pointers are accepted for all comparisons as gcc */
2182 if (is_null_pointer(p1) || is_null_pointer(p2))
2183 return;
2184 type1 = &p1->type;
2185 type2 = &p2->type;
2186 bt1 = type1->t & VT_BTYPE;
2187 bt2 = type2->t & VT_BTYPE;
2188 /* accept comparison between pointer and integer with a warning */
2189 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
2190 if (op != TOK_LOR && op != TOK_LAND )
2191 tcc_warning("comparison between pointer and integer");
2192 return;
2195 /* both must be pointers or implicit function pointers */
2196 if (bt1 == VT_PTR) {
2197 type1 = pointed_type(type1);
2198 } else if (bt1 != VT_FUNC)
2199 goto invalid_operands;
2201 if (bt2 == VT_PTR) {
2202 type2 = pointed_type(type2);
2203 } else if (bt2 != VT_FUNC) {
2204 invalid_operands:
2205 tcc_error("invalid operands to binary %s", get_tok_str(op, NULL));
2207 if ((type1->t & VT_BTYPE) == VT_VOID ||
2208 (type2->t & VT_BTYPE) == VT_VOID)
2209 return;
2210 tmp_type1 = *type1;
2211 tmp_type2 = *type2;
2212 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
2213 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
2214 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2215 /* gcc-like error if '-' is used */
2216 if (op == '-')
2217 goto invalid_operands;
2218 else
2219 tcc_warning("comparison of distinct pointer types lacks a cast");
2223 /* generic gen_op: handles types problems */
2224 ST_FUNC void gen_op(int op)
2226 int u, t1, t2, bt1, bt2, t;
2227 CType type1;
2229 redo:
2230 t1 = vtop[-1].type.t;
2231 t2 = vtop[0].type.t;
2232 bt1 = t1 & VT_BTYPE;
2233 bt2 = t2 & VT_BTYPE;
2235 if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
2236 tcc_error("operation on a struct");
2237 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
2238 if (bt2 == VT_FUNC) {
2239 mk_pointer(&vtop->type);
2240 gaddrof();
2242 if (bt1 == VT_FUNC) {
2243 vswap();
2244 mk_pointer(&vtop->type);
2245 gaddrof();
2246 vswap();
2248 goto redo;
2249 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
2250 /* at least one operand is a pointer */
2251 /* relational op: must be both pointers */
2252 if (op >= TOK_ULT && op <= TOK_LOR) {
2253 check_comparison_pointer_types(vtop - 1, vtop, op);
2254 /* pointers are handled are unsigned */
2255 #if PTR_SIZE == 8
2256 t = VT_LLONG | VT_UNSIGNED;
2257 #else
2258 t = VT_INT | VT_UNSIGNED;
2259 #endif
2260 goto std_op;
2262 /* if both pointers, then it must be the '-' op */
2263 if (bt1 == VT_PTR && bt2 == VT_PTR) {
2264 if (op != '-')
2265 tcc_error("cannot use pointers here");
2266 check_comparison_pointer_types(vtop - 1, vtop, op);
2267 /* XXX: check that types are compatible */
2268 if (vtop[-1].type.t & VT_VLA) {
2269 vla_runtime_pointed_size(&vtop[-1].type);
2270 } else {
2271 vpushi(pointed_size(&vtop[-1].type));
2273 vrott(3);
2274 gen_opic(op);
2275 vtop->type.t = ptrdiff_type.t;
2276 vswap();
2277 gen_op(TOK_PDIV);
2278 } else {
2279 /* exactly one pointer : must be '+' or '-'. */
2280 if (op != '-' && op != '+')
2281 tcc_error("cannot use pointers here");
2282 /* Put pointer as first operand */
2283 if (bt2 == VT_PTR) {
2284 vswap();
2285 t = t1, t1 = t2, t2 = t;
2287 #if PTR_SIZE == 4
2288 if ((vtop[0].type.t & VT_BTYPE) == VT_LLONG)
2289 /* XXX: truncate here because gen_opl can't handle ptr + long long */
2290 gen_cast_s(VT_INT);
2291 #endif
2292 type1 = vtop[-1].type;
2293 type1.t &= ~VT_ARRAY;
2294 if (vtop[-1].type.t & VT_VLA)
2295 vla_runtime_pointed_size(&vtop[-1].type);
2296 else {
2297 u = pointed_size(&vtop[-1].type);
2298 if (u < 0)
2299 tcc_error("unknown array element size");
2300 #if PTR_SIZE == 8
2301 vpushll(u);
2302 #else
2303 /* XXX: cast to int ? (long long case) */
2304 vpushi(u);
2305 #endif
2307 gen_op('*');
2308 #if 0
2309 /* #ifdef CONFIG_TCC_BCHECK
2310 The main reason to removing this code:
2311 #include <stdio.h>
2312 int main ()
2314 int v[10];
2315 int i = 10;
2316 int j = 9;
2317 fprintf(stderr, "v+i-j = %p\n", v+i-j);
2318 fprintf(stderr, "v+(i-j) = %p\n", v+(i-j));
2320 When this code is on. then the output looks like
2321 v+i-j = 0xfffffffe
2322 v+(i-j) = 0xbff84000
2324 /* if evaluating constant expression, no code should be
2325 generated, so no bound check */
2326 if (tcc_state->do_bounds_check && !const_wanted) {
2327 /* if bounded pointers, we generate a special code to
2328 test bounds */
2329 if (op == '-') {
2330 vpushi(0);
2331 vswap();
2332 gen_op('-');
2334 gen_bounded_ptr_add();
2335 } else
2336 #endif
2338 gen_opic(op);
2340 /* put again type if gen_opic() swaped operands */
2341 vtop->type = type1;
2343 } else if (is_float(bt1) || is_float(bt2)) {
2344 /* compute bigger type and do implicit casts */
2345 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
2346 t = VT_LDOUBLE;
2347 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
2348 t = VT_DOUBLE;
2349 } else {
2350 t = VT_FLOAT;
2352 /* floats can only be used for a few operations */
2353 if (op != '+' && op != '-' && op != '*' && op != '/' &&
2354 (op < TOK_ULT || op > TOK_GT))
2355 tcc_error("invalid operands for binary operation");
2356 goto std_op;
2357 } else if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL) {
2358 t = bt1 == VT_LLONG ? VT_LLONG : VT_INT;
2359 if ((t1 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (t | VT_UNSIGNED))
2360 t |= VT_UNSIGNED;
2361 t |= (VT_LONG & t1);
2362 goto std_op;
2363 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
2364 /* cast to biggest op */
2365 t = VT_LLONG | VT_LONG;
2366 if (bt1 == VT_LLONG)
2367 t &= t1;
2368 if (bt2 == VT_LLONG)
2369 t &= t2;
2370 /* convert to unsigned if it does not fit in a long long */
2371 if ((t1 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_LLONG | VT_UNSIGNED) ||
2372 (t2 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_LLONG | VT_UNSIGNED))
2373 t |= VT_UNSIGNED;
2374 goto std_op;
2375 } else {
2376 /* integer operations */
2377 t = VT_INT | (VT_LONG & (t1 | t2));
2378 /* convert to unsigned if it does not fit in an integer */
2379 if ((t1 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_INT | VT_UNSIGNED) ||
2380 (t2 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_INT | VT_UNSIGNED))
2381 t |= VT_UNSIGNED;
2382 std_op:
2383 /* XXX: currently, some unsigned operations are explicit, so
2384 we modify them here */
2385 if (t & VT_UNSIGNED) {
2386 if (op == TOK_SAR)
2387 op = TOK_SHR;
2388 else if (op == '/')
2389 op = TOK_UDIV;
2390 else if (op == '%')
2391 op = TOK_UMOD;
2392 else if (op == TOK_LT)
2393 op = TOK_ULT;
2394 else if (op == TOK_GT)
2395 op = TOK_UGT;
2396 else if (op == TOK_LE)
2397 op = TOK_ULE;
2398 else if (op == TOK_GE)
2399 op = TOK_UGE;
2401 vswap();
2402 type1.t = t;
2403 type1.ref = NULL;
2404 gen_cast(&type1);
2405 vswap();
2406 /* special case for shifts and long long: we keep the shift as
2407 an integer */
2408 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
2409 type1.t = VT_INT;
2410 gen_cast(&type1);
2411 if (is_float(t))
2412 gen_opif(op);
2413 else
2414 gen_opic(op);
2415 if (op >= TOK_ULT && op <= TOK_GT) {
2416 /* relational op: the result is an int */
2417 vtop->type.t = VT_INT;
2418 } else {
2419 vtop->type.t = t;
2422 // Make sure that we have converted to an rvalue:
2423 if (vtop->r & VT_LVAL)
2424 gv(is_float(vtop->type.t & VT_BTYPE) ? RC_FLOAT : RC_INT);
2427 #ifndef TCC_TARGET_ARM
2428 /* generic itof for unsigned long long case */
2429 static void gen_cvt_itof1(int t)
2431 #ifdef TCC_TARGET_ARM64
2432 gen_cvt_itof(t);
2433 #else
2434 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
2435 (VT_LLONG | VT_UNSIGNED)) {
2437 if (t == VT_FLOAT)
2438 vpush_global_sym(&func_old_type, TOK___floatundisf);
2439 #if LDOUBLE_SIZE != 8
2440 else if (t == VT_LDOUBLE)
2441 vpush_global_sym(&func_old_type, TOK___floatundixf);
2442 #endif
2443 else
2444 vpush_global_sym(&func_old_type, TOK___floatundidf);
2445 vrott(2);
2446 gfunc_call(1);
2447 vpushi(0);
2448 vtop->r = reg_fret(t);
2449 } else {
2450 gen_cvt_itof(t);
2452 #endif
2454 #endif
2456 /* generic ftoi for unsigned long long case */
2457 static void gen_cvt_ftoi1(int t)
2459 #ifdef TCC_TARGET_ARM64
2460 gen_cvt_ftoi(t);
2461 #else
2462 int st;
2464 if (t == (VT_LLONG | VT_UNSIGNED)) {
2465 /* not handled natively */
2466 st = vtop->type.t & VT_BTYPE;
2467 if (st == VT_FLOAT)
2468 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
2469 #if LDOUBLE_SIZE != 8
2470 else if (st == VT_LDOUBLE)
2471 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
2472 #endif
2473 else
2474 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
2475 vrott(2);
2476 gfunc_call(1);
2477 vpushi(0);
2478 vtop->r = REG_IRET;
2479 vtop->r2 = REG_LRET;
2480 } else {
2481 gen_cvt_ftoi(t);
2483 #endif
2486 /* force char or short cast */
2487 static void force_charshort_cast(int t)
2489 int bits, dbt;
2491 /* cannot cast static initializers */
2492 if (STATIC_DATA_WANTED)
2493 return;
2495 dbt = t & VT_BTYPE;
2496 /* XXX: add optimization if lvalue : just change type and offset */
2497 if (dbt == VT_BYTE)
2498 bits = 8;
2499 else
2500 bits = 16;
2501 if (t & VT_UNSIGNED) {
2502 vpushi((1 << bits) - 1);
2503 gen_op('&');
2504 } else {
2505 if ((vtop->type.t & VT_BTYPE) == VT_LLONG)
2506 bits = 64 - bits;
2507 else
2508 bits = 32 - bits;
2509 vpushi(bits);
2510 gen_op(TOK_SHL);
2511 /* result must be signed or the SAR is converted to an SHL
2512 This was not the case when "t" was a signed short
2513 and the last value on the stack was an unsigned int */
2514 vtop->type.t &= ~VT_UNSIGNED;
2515 vpushi(bits);
2516 gen_op(TOK_SAR);
2520 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
2521 static void gen_cast_s(int t)
2523 CType type;
2524 type.t = t;
2525 type.ref = NULL;
2526 gen_cast(&type);
2529 static void gen_cast(CType *type)
2531 int sbt, dbt, sf, df, c, p;
2533 /* special delayed cast for char/short */
2534 /* XXX: in some cases (multiple cascaded casts), it may still
2535 be incorrect */
2536 if (vtop->r & VT_MUSTCAST) {
2537 vtop->r &= ~VT_MUSTCAST;
2538 force_charshort_cast(vtop->type.t);
2541 /* bitfields first get cast to ints */
2542 if (vtop->type.t & VT_BITFIELD) {
2543 gv(RC_INT);
2546 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
2547 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
2549 if (sbt != dbt) {
2550 sf = is_float(sbt);
2551 df = is_float(dbt);
2552 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
2553 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
2554 #if !defined TCC_IS_NATIVE && !defined TCC_IS_NATIVE_387
2555 c &= dbt != VT_LDOUBLE;
2556 #endif
2557 if (c) {
2558 /* constant case: we can do it now */
2559 /* XXX: in ISOC, cannot do it if error in convert */
2560 if (sbt == VT_FLOAT)
2561 vtop->c.ld = vtop->c.f;
2562 else if (sbt == VT_DOUBLE)
2563 vtop->c.ld = vtop->c.d;
2565 if (df) {
2566 if ((sbt & VT_BTYPE) == VT_LLONG) {
2567 if ((sbt & VT_UNSIGNED) || !(vtop->c.i >> 63))
2568 vtop->c.ld = vtop->c.i;
2569 else
2570 vtop->c.ld = -(long double)-vtop->c.i;
2571 } else if(!sf) {
2572 if ((sbt & VT_UNSIGNED) || !(vtop->c.i >> 31))
2573 vtop->c.ld = (uint32_t)vtop->c.i;
2574 else
2575 vtop->c.ld = -(long double)-(uint32_t)vtop->c.i;
2578 if (dbt == VT_FLOAT)
2579 vtop->c.f = (float)vtop->c.ld;
2580 else if (dbt == VT_DOUBLE)
2581 vtop->c.d = (double)vtop->c.ld;
2582 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
2583 vtop->c.i = vtop->c.ld;
2584 } else if (sf && dbt == VT_BOOL) {
2585 vtop->c.i = (vtop->c.ld != 0);
2586 } else {
2587 if(sf)
2588 vtop->c.i = vtop->c.ld;
2589 else if (sbt == (VT_LLONG|VT_UNSIGNED))
2591 else if (sbt & VT_UNSIGNED)
2592 vtop->c.i = (uint32_t)vtop->c.i;
2593 #if PTR_SIZE == 8
2594 else if (sbt == VT_PTR)
2596 #endif
2597 else if (sbt != VT_LLONG)
2598 vtop->c.i = ((uint32_t)vtop->c.i |
2599 -(vtop->c.i & 0x80000000));
2601 if (dbt == (VT_LLONG|VT_UNSIGNED))
2603 else if (dbt == VT_BOOL)
2604 vtop->c.i = (vtop->c.i != 0);
2605 #if PTR_SIZE == 8
2606 else if (dbt == VT_PTR)
2608 #endif
2609 else if (dbt != VT_LLONG) {
2610 uint32_t m = ((dbt & VT_BTYPE) == VT_BYTE ? 0xff :
2611 (dbt & VT_BTYPE) == VT_SHORT ? 0xffff :
2612 0xffffffff);
2613 vtop->c.i &= m;
2614 if (!(dbt & VT_UNSIGNED))
2615 vtop->c.i |= -(vtop->c.i & ((m >> 1) + 1));
2618 } else if (p && dbt == VT_BOOL) {
2619 vtop->r = VT_CONST;
2620 vtop->c.i = 1;
2621 } else {
2622 /* non constant case: generate code */
2623 if (sf && df) {
2624 /* convert from fp to fp */
2625 gen_cvt_ftof(dbt);
2626 } else if (df) {
2627 /* convert int to fp */
2628 gen_cvt_itof1(dbt);
2629 } else if (sf) {
2630 /* convert fp to int */
2631 if (dbt == VT_BOOL) {
2632 vpushi(0);
2633 gen_op(TOK_NE);
2634 } else {
2635 /* we handle char/short/etc... with generic code */
2636 if (dbt != (VT_INT | VT_UNSIGNED) &&
2637 dbt != (VT_LLONG | VT_UNSIGNED) &&
2638 dbt != VT_LLONG)
2639 dbt = VT_INT;
2640 gen_cvt_ftoi1(dbt);
2641 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
2642 /* additional cast for char/short... */
2643 vtop->type.t = dbt;
2644 gen_cast(type);
2647 #if PTR_SIZE == 4
2648 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
2649 if ((sbt & VT_BTYPE) != VT_LLONG) {
2650 /* scalar to long long */
2651 /* machine independent conversion */
2652 gv(RC_INT);
2653 /* generate high word */
2654 if (sbt == (VT_INT | VT_UNSIGNED)) {
2655 vpushi(0);
2656 gv(RC_INT);
2657 } else {
2658 if (sbt == VT_PTR) {
2659 /* cast from pointer to int before we apply
2660 shift operation, which pointers don't support*/
2661 gen_cast_s(VT_INT);
2663 gv_dup();
2664 vpushi(31);
2665 gen_op(TOK_SAR);
2667 /* patch second register */
2668 vtop[-1].r2 = vtop->r;
2669 vpop();
2671 #else
2672 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
2673 (dbt & VT_BTYPE) == VT_PTR ||
2674 (dbt & VT_BTYPE) == VT_FUNC) {
2675 if ((sbt & VT_BTYPE) != VT_LLONG &&
2676 (sbt & VT_BTYPE) != VT_PTR &&
2677 (sbt & VT_BTYPE) != VT_FUNC) {
2678 /* need to convert from 32bit to 64bit */
2679 gv(RC_INT);
2680 if (sbt != (VT_INT | VT_UNSIGNED)) {
2681 #if defined(TCC_TARGET_ARM64)
2682 gen_cvt_sxtw();
2683 #elif defined(TCC_TARGET_X86_64)
2684 int r = gv(RC_INT);
2685 /* x86_64 specific: movslq */
2686 o(0x6348);
2687 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
2688 #else
2689 #error
2690 #endif
2693 #endif
2694 } else if (dbt == VT_BOOL) {
2695 /* scalar to bool */
2696 vpushi(0);
2697 gen_op(TOK_NE);
2698 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
2699 (dbt & VT_BTYPE) == VT_SHORT) {
2700 if (sbt == VT_PTR) {
2701 vtop->type.t = VT_INT;
2702 tcc_warning("nonportable conversion from pointer to char/short");
2704 force_charshort_cast(dbt);
2705 } else if ((dbt & VT_BTYPE) == VT_INT) {
2706 /* scalar to int */
2707 if ((sbt & VT_BTYPE) == VT_LLONG) {
2708 #if PTR_SIZE == 4
2709 /* from long long: just take low order word */
2710 lexpand();
2711 vpop();
2712 #else
2713 vpushi(0xffffffff);
2714 vtop->type.t |= VT_UNSIGNED;
2715 gen_op('&');
2716 #endif
2718 /* if lvalue and single word type, nothing to do because
2719 the lvalue already contains the real type size (see
2720 VT_LVAL_xxx constants) */
2723 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
2724 /* if we are casting between pointer types,
2725 we must update the VT_LVAL_xxx size */
2726 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
2727 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
2729 vtop->type = *type;
2730 vtop->type.t &= ~ ( VT_CONSTANT | VT_VOLATILE | VT_ARRAY );
2733 /* return type size as known at compile time. Put alignment at 'a' */
2734 ST_FUNC int type_size(CType *type, int *a)
2736 Sym *s;
2737 int bt;
2739 bt = type->t & VT_BTYPE;
2740 if (bt == VT_STRUCT) {
2741 /* struct/union */
2742 s = type->ref;
2743 *a = s->r;
2744 return s->c;
2745 } else if (bt == VT_PTR) {
2746 if (type->t & VT_ARRAY) {
2747 int ts;
2749 s = type->ref;
2750 ts = type_size(&s->type, a);
2752 if (ts < 0 && s->c < 0)
2753 ts = -ts;
2755 return ts * s->c;
2756 } else {
2757 *a = PTR_SIZE;
2758 return PTR_SIZE;
2760 } else if (IS_ENUM(type->t) && type->ref->c == -1) {
2761 return -1; /* incomplete enum */
2762 } else if (bt == VT_LDOUBLE) {
2763 *a = LDOUBLE_ALIGN;
2764 return LDOUBLE_SIZE;
2765 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
2766 #ifdef TCC_TARGET_I386
2767 #ifdef TCC_TARGET_PE
2768 *a = 8;
2769 #else
2770 *a = 4;
2771 #endif
2772 #elif defined(TCC_TARGET_ARM)
2773 #ifdef TCC_ARM_EABI
2774 *a = 8;
2775 #else
2776 *a = 4;
2777 #endif
2778 #else
2779 *a = 8;
2780 #endif
2781 return 8;
2782 } else if (bt == VT_INT || bt == VT_FLOAT) {
2783 *a = 4;
2784 return 4;
2785 } else if (bt == VT_SHORT) {
2786 *a = 2;
2787 return 2;
2788 } else if (bt == VT_QLONG || bt == VT_QFLOAT) {
2789 *a = 8;
2790 return 16;
2791 } else {
2792 /* char, void, function, _Bool */
2793 *a = 1;
2794 return 1;
2798 /* push type size as known at runtime time on top of value stack. Put
2799 alignment at 'a' */
2800 ST_FUNC void vla_runtime_type_size(CType *type, int *a)
2802 if (type->t & VT_VLA) {
2803 type_size(&type->ref->type, a);
2804 vset(&int_type, VT_LOCAL|VT_LVAL, type->ref->c);
2805 } else {
2806 vpushi(type_size(type, a));
2810 static void vla_sp_restore(void) {
2811 if (vlas_in_scope) {
2812 gen_vla_sp_restore(vla_sp_loc);
2816 static void vla_sp_restore_root(void) {
2817 if (vlas_in_scope) {
2818 gen_vla_sp_restore(vla_sp_root_loc);
2822 /* return the pointed type of t */
2823 static inline CType *pointed_type(CType *type)
2825 return &type->ref->type;
2828 /* modify type so that its it is a pointer to type. */
2829 ST_FUNC void mk_pointer(CType *type)
2831 Sym *s;
2832 s = sym_push(SYM_FIELD, type, 0, -1);
2833 type->t = VT_PTR | (type->t & VT_STORAGE);
2834 type->ref = s;
2837 /* compare function types. OLD functions match any new functions */
2838 static int is_compatible_func(CType *type1, CType *type2)
2840 Sym *s1, *s2;
2842 s1 = type1->ref;
2843 s2 = type2->ref;
2844 if (!is_compatible_types(&s1->type, &s2->type))
2845 return 0;
2846 /* check func_call */
2847 if (s1->f.func_call != s2->f.func_call)
2848 return 0;
2849 /* XXX: not complete */
2850 if (s1->f.func_type == FUNC_OLD || s2->f.func_type == FUNC_OLD)
2851 return 1;
2852 if (s1->f.func_type != s2->f.func_type)
2853 return 0;
2854 while (s1 != NULL) {
2855 if (s2 == NULL)
2856 return 0;
2857 if (!is_compatible_unqualified_types(&s1->type, &s2->type))
2858 return 0;
2859 s1 = s1->next;
2860 s2 = s2->next;
2862 if (s2)
2863 return 0;
2864 return 1;
2867 /* return true if type1 and type2 are the same. If unqualified is
2868 true, qualifiers on the types are ignored.
2870 static int compare_types(CType *type1, CType *type2, int unqualified)
2872 int bt1, t1, t2;
2874 t1 = type1->t & VT_TYPE;
2875 t2 = type2->t & VT_TYPE;
2876 if (unqualified) {
2877 /* strip qualifiers before comparing */
2878 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
2879 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
2882 /* Default Vs explicit signedness only matters for char */
2883 if ((t1 & VT_BTYPE) != VT_BYTE) {
2884 t1 &= ~VT_DEFSIGN;
2885 t2 &= ~VT_DEFSIGN;
2887 /* XXX: bitfields ? */
2888 if (t1 != t2)
2889 return 0;
2890 /* test more complicated cases */
2891 bt1 = t1 & (VT_BTYPE | VT_ARRAY);
2892 if (bt1 == VT_PTR) {
2893 type1 = pointed_type(type1);
2894 type2 = pointed_type(type2);
2895 return is_compatible_types(type1, type2);
2896 } else if (bt1 & VT_ARRAY) {
2897 return type1->ref->c < 0 || type2->ref->c < 0
2898 || type1->ref->c == type2->ref->c;
2899 } else if (bt1 == VT_STRUCT) {
2900 return (type1->ref == type2->ref);
2901 } else if (bt1 == VT_FUNC) {
2902 return is_compatible_func(type1, type2);
2903 } else if (IS_ENUM(type1->t) || IS_ENUM(type2->t)) {
2904 return type1->ref == type2->ref;
2905 } else {
2906 return 1;
2910 /* return true if type1 and type2 are exactly the same (including
2911 qualifiers).
2913 static int is_compatible_types(CType *type1, CType *type2)
2915 return compare_types(type1,type2,0);
2918 /* return true if type1 and type2 are the same (ignoring qualifiers).
2920 static int is_compatible_unqualified_types(CType *type1, CType *type2)
2922 return compare_types(type1,type2,1);
2925 /* print a type. If 'varstr' is not NULL, then the variable is also
2926 printed in the type */
2927 /* XXX: union */
2928 /* XXX: add array and function pointers */
2929 static void type_to_str(char *buf, int buf_size,
2930 CType *type, const char *varstr)
2932 int bt, v, t;
2933 Sym *s, *sa;
2934 char buf1[256];
2935 const char *tstr;
2937 t = type->t;
2938 bt = t & VT_BTYPE;
2939 buf[0] = '\0';
2941 if (t & VT_EXTERN)
2942 pstrcat(buf, buf_size, "extern ");
2943 if (t & VT_STATIC)
2944 pstrcat(buf, buf_size, "static ");
2945 if (t & VT_TYPEDEF)
2946 pstrcat(buf, buf_size, "typedef ");
2947 if (t & VT_INLINE)
2948 pstrcat(buf, buf_size, "inline ");
2949 if (t & VT_VOLATILE)
2950 pstrcat(buf, buf_size, "volatile ");
2951 if (t & VT_CONSTANT)
2952 pstrcat(buf, buf_size, "const ");
2954 if (((t & VT_DEFSIGN) && bt == VT_BYTE)
2955 || ((t & VT_UNSIGNED)
2956 && (bt == VT_SHORT || bt == VT_INT || bt == VT_LLONG)
2957 && !IS_ENUM(t)
2959 pstrcat(buf, buf_size, (t & VT_UNSIGNED) ? "unsigned " : "signed ");
2961 buf_size -= strlen(buf);
2962 buf += strlen(buf);
2964 switch(bt) {
2965 case VT_VOID:
2966 tstr = "void";
2967 goto add_tstr;
2968 case VT_BOOL:
2969 tstr = "_Bool";
2970 goto add_tstr;
2971 case VT_BYTE:
2972 tstr = "char";
2973 goto add_tstr;
2974 case VT_SHORT:
2975 tstr = "short";
2976 goto add_tstr;
2977 case VT_INT:
2978 tstr = "int";
2979 goto maybe_long;
2980 case VT_LLONG:
2981 tstr = "long long";
2982 maybe_long:
2983 if (t & VT_LONG)
2984 tstr = "long";
2985 if (!IS_ENUM(t))
2986 goto add_tstr;
2987 tstr = "enum ";
2988 goto tstruct;
2989 case VT_FLOAT:
2990 tstr = "float";
2991 goto add_tstr;
2992 case VT_DOUBLE:
2993 tstr = "double";
2994 goto add_tstr;
2995 case VT_LDOUBLE:
2996 tstr = "long double";
2997 add_tstr:
2998 pstrcat(buf, buf_size, tstr);
2999 break;
3000 case VT_STRUCT:
3001 tstr = "struct ";
3002 if (IS_UNION(t))
3003 tstr = "union ";
3004 tstruct:
3005 pstrcat(buf, buf_size, tstr);
3006 v = type->ref->v & ~SYM_STRUCT;
3007 if (v >= SYM_FIRST_ANOM)
3008 pstrcat(buf, buf_size, "<anonymous>");
3009 else
3010 pstrcat(buf, buf_size, get_tok_str(v, NULL));
3011 break;
3012 case VT_FUNC:
3013 s = type->ref;
3014 buf1[0]=0;
3015 if (varstr && '*' == *varstr) {
3016 pstrcat(buf1, sizeof(buf1), "(");
3017 pstrcat(buf1, sizeof(buf1), varstr);
3018 pstrcat(buf1, sizeof(buf1), ")");
3020 pstrcat(buf1, buf_size, "(");
3021 sa = s->next;
3022 while (sa != NULL) {
3023 char buf2[256];
3024 type_to_str(buf2, sizeof(buf2), &sa->type, NULL);
3025 pstrcat(buf1, sizeof(buf1), buf2);
3026 sa = sa->next;
3027 if (sa)
3028 pstrcat(buf1, sizeof(buf1), ", ");
3030 if (s->f.func_type == FUNC_ELLIPSIS)
3031 pstrcat(buf1, sizeof(buf1), ", ...");
3032 pstrcat(buf1, sizeof(buf1), ")");
3033 type_to_str(buf, buf_size, &s->type, buf1);
3034 goto no_var;
3035 case VT_PTR:
3036 s = type->ref;
3037 if (t & VT_ARRAY) {
3038 if (varstr && '*' == *varstr)
3039 snprintf(buf1, sizeof(buf1), "(%s)[%d]", varstr, s->c);
3040 else
3041 snprintf(buf1, sizeof(buf1), "%s[%d]", varstr ? varstr : "", s->c);
3042 type_to_str(buf, buf_size, &s->type, buf1);
3043 goto no_var;
3045 pstrcpy(buf1, sizeof(buf1), "*");
3046 if (t & VT_CONSTANT)
3047 pstrcat(buf1, buf_size, "const ");
3048 if (t & VT_VOLATILE)
3049 pstrcat(buf1, buf_size, "volatile ");
3050 if (varstr)
3051 pstrcat(buf1, sizeof(buf1), varstr);
3052 type_to_str(buf, buf_size, &s->type, buf1);
3053 goto no_var;
3055 if (varstr) {
3056 pstrcat(buf, buf_size, " ");
3057 pstrcat(buf, buf_size, varstr);
3059 no_var: ;
3062 /* verify type compatibility to store vtop in 'dt' type, and generate
3063 casts if needed. */
3064 static void gen_assign_cast(CType *dt)
3066 CType *st, *type1, *type2;
3067 char buf1[256], buf2[256];
3068 int dbt, sbt, qualwarn, lvl;
3070 st = &vtop->type; /* source type */
3071 dbt = dt->t & VT_BTYPE;
3072 sbt = st->t & VT_BTYPE;
3073 if (sbt == VT_VOID || dbt == VT_VOID) {
3074 if (sbt == VT_VOID && dbt == VT_VOID)
3075 ; /* It is Ok if both are void */
3076 else
3077 tcc_error("cannot cast from/to void");
3079 if (dt->t & VT_CONSTANT)
3080 tcc_warning("assignment of read-only location");
3081 switch(dbt) {
3082 case VT_PTR:
3083 /* special cases for pointers */
3084 /* '0' can also be a pointer */
3085 if (is_null_pointer(vtop))
3086 break;
3087 /* accept implicit pointer to integer cast with warning */
3088 if (is_integer_btype(sbt)) {
3089 tcc_warning("assignment makes pointer from integer without a cast");
3090 break;
3092 type1 = pointed_type(dt);
3093 if (sbt == VT_PTR)
3094 type2 = pointed_type(st);
3095 else if (sbt == VT_FUNC)
3096 type2 = st; /* a function is implicitly a function pointer */
3097 else
3098 goto error;
3099 if (is_compatible_types(type1, type2))
3100 break;
3101 for (qualwarn = lvl = 0;; ++lvl) {
3102 if (((type2->t & VT_CONSTANT) && !(type1->t & VT_CONSTANT)) ||
3103 ((type2->t & VT_VOLATILE) && !(type1->t & VT_VOLATILE)))
3104 qualwarn = 1;
3105 dbt = type1->t & (VT_BTYPE|VT_LONG);
3106 sbt = type2->t & (VT_BTYPE|VT_LONG);
3107 if (dbt != VT_PTR || sbt != VT_PTR)
3108 break;
3109 type1 = pointed_type(type1);
3110 type2 = pointed_type(type2);
3112 if (!is_compatible_unqualified_types(type1, type2)) {
3113 if ((dbt == VT_VOID || sbt == VT_VOID) && lvl == 0) {
3114 /* void * can match anything */
3115 } else if (dbt == sbt
3116 && is_integer_btype(sbt & VT_BTYPE)
3117 && IS_ENUM(type1->t) + IS_ENUM(type2->t)
3118 + !!((type1->t ^ type2->t) & VT_UNSIGNED) < 2) {
3119 /* Like GCC don't warn by default for merely changes
3120 in pointer target signedness. Do warn for different
3121 base types, though, in particular for unsigned enums
3122 and signed int targets. */
3123 } else {
3124 tcc_warning("assignment from incompatible pointer type");
3125 break;
3128 if (qualwarn)
3129 tcc_warning("assignment discards qualifiers from pointer target type");
3130 break;
3131 case VT_BYTE:
3132 case VT_SHORT:
3133 case VT_INT:
3134 case VT_LLONG:
3135 if (sbt == VT_PTR || sbt == VT_FUNC) {
3136 tcc_warning("assignment makes integer from pointer without a cast");
3137 } else if (sbt == VT_STRUCT) {
3138 goto case_VT_STRUCT;
3140 /* XXX: more tests */
3141 break;
3142 case VT_STRUCT:
3143 case_VT_STRUCT:
3144 if (!is_compatible_unqualified_types(dt, st)) {
3145 error:
3146 type_to_str(buf1, sizeof(buf1), st, NULL);
3147 type_to_str(buf2, sizeof(buf2), dt, NULL);
3148 tcc_error("cannot cast '%s' to '%s'", buf1, buf2);
3150 break;
3152 gen_cast(dt);
3155 /* store vtop in lvalue pushed on stack */
3156 ST_FUNC void vstore(void)
3158 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
3160 ft = vtop[-1].type.t;
3161 sbt = vtop->type.t & VT_BTYPE;
3162 dbt = ft & VT_BTYPE;
3163 if ((((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
3164 (sbt == VT_INT && dbt == VT_SHORT))
3165 && !(vtop->type.t & VT_BITFIELD)) {
3166 /* optimize char/short casts */
3167 delayed_cast = VT_MUSTCAST;
3168 vtop->type.t = ft & VT_TYPE;
3169 /* XXX: factorize */
3170 if (ft & VT_CONSTANT)
3171 tcc_warning("assignment of read-only location");
3172 } else {
3173 delayed_cast = 0;
3174 if (!(ft & VT_BITFIELD))
3175 gen_assign_cast(&vtop[-1].type);
3178 if (sbt == VT_STRUCT) {
3179 /* if structure, only generate pointer */
3180 /* structure assignment : generate memcpy */
3181 /* XXX: optimize if small size */
3182 size = type_size(&vtop->type, &align);
3184 /* destination */
3185 vswap();
3186 vtop->type.t = VT_PTR;
3187 gaddrof();
3189 /* address of memcpy() */
3190 #ifdef TCC_ARM_EABI
3191 if(!(align & 7))
3192 vpush_global_sym(&func_old_type, TOK_memcpy8);
3193 else if(!(align & 3))
3194 vpush_global_sym(&func_old_type, TOK_memcpy4);
3195 else
3196 #endif
3197 /* Use memmove, rather than memcpy, as dest and src may be same: */
3198 vpush_global_sym(&func_old_type, TOK_memmove);
3200 vswap();
3201 /* source */
3202 vpushv(vtop - 2);
3203 vtop->type.t = VT_PTR;
3204 gaddrof();
3205 /* type size */
3206 vpushi(size);
3207 gfunc_call(3);
3209 /* leave source on stack */
3210 } else if (ft & VT_BITFIELD) {
3211 /* bitfield store handling */
3213 /* save lvalue as expression result (example: s.b = s.a = n;) */
3214 vdup(), vtop[-1] = vtop[-2];
3216 bit_pos = BIT_POS(ft);
3217 bit_size = BIT_SIZE(ft);
3218 /* remove bit field info to avoid loops */
3219 vtop[-1].type.t = ft & ~VT_STRUCT_MASK;
3221 if ((ft & VT_BTYPE) == VT_BOOL) {
3222 gen_cast(&vtop[-1].type);
3223 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
3226 r = adjust_bf(vtop - 1, bit_pos, bit_size);
3227 if (r == VT_STRUCT) {
3228 gen_cast_s((ft & VT_BTYPE) == VT_LLONG ? VT_LLONG : VT_INT);
3229 store_packed_bf(bit_pos, bit_size);
3230 } else {
3231 unsigned long long mask = (1ULL << bit_size) - 1;
3232 if ((ft & VT_BTYPE) != VT_BOOL) {
3233 /* mask source */
3234 if ((vtop[-1].type.t & VT_BTYPE) == VT_LLONG)
3235 vpushll(mask);
3236 else
3237 vpushi((unsigned)mask);
3238 gen_op('&');
3240 /* shift source */
3241 vpushi(bit_pos);
3242 gen_op(TOK_SHL);
3243 vswap();
3244 /* duplicate destination */
3245 vdup();
3246 vrott(3);
3247 /* load destination, mask and or with source */
3248 if ((vtop->type.t & VT_BTYPE) == VT_LLONG)
3249 vpushll(~(mask << bit_pos));
3250 else
3251 vpushi(~((unsigned)mask << bit_pos));
3252 gen_op('&');
3253 gen_op('|');
3254 /* store result */
3255 vstore();
3256 /* ... and discard */
3257 vpop();
3259 } else if (dbt == VT_VOID) {
3260 --vtop;
3261 } else {
3262 #ifdef CONFIG_TCC_BCHECK
3263 /* bound check case */
3264 if (vtop[-1].r & VT_MUSTBOUND) {
3265 vswap();
3266 gbound();
3267 vswap();
3269 #endif
3270 rc = RC_INT;
3271 if (is_float(ft)) {
3272 rc = RC_FLOAT;
3273 #ifdef TCC_TARGET_X86_64
3274 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
3275 rc = RC_ST0;
3276 } else if ((ft & VT_BTYPE) == VT_QFLOAT) {
3277 rc = RC_FRET;
3279 #endif
3281 r = gv(rc); /* generate value */
3282 /* if lvalue was saved on stack, must read it */
3283 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
3284 SValue sv;
3285 t = get_reg(RC_INT);
3286 #if PTR_SIZE == 8
3287 sv.type.t = VT_PTR;
3288 #else
3289 sv.type.t = VT_INT;
3290 #endif
3291 sv.r = VT_LOCAL | VT_LVAL;
3292 sv.c.i = vtop[-1].c.i;
3293 load(t, &sv);
3294 vtop[-1].r = t | VT_LVAL;
3296 /* two word case handling : store second register at word + 4 (or +8 for x86-64) */
3297 #if PTR_SIZE == 8
3298 if (((ft & VT_BTYPE) == VT_QLONG) || ((ft & VT_BTYPE) == VT_QFLOAT)) {
3299 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
3300 #else
3301 if ((ft & VT_BTYPE) == VT_LLONG) {
3302 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
3303 #endif
3304 vtop[-1].type.t = load_type;
3305 store(r, vtop - 1);
3306 vswap();
3307 /* convert to int to increment easily */
3308 vtop->type.t = addr_type;
3309 gaddrof();
3310 vpushi(load_size);
3311 gen_op('+');
3312 vtop->r |= VT_LVAL;
3313 vswap();
3314 vtop[-1].type.t = load_type;
3315 /* XXX: it works because r2 is spilled last ! */
3316 store(vtop->r2, vtop - 1);
3317 } else {
3318 store(r, vtop - 1);
3321 vswap();
3322 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
3323 vtop->r |= delayed_cast;
3327 /* post defines POST/PRE add. c is the token ++ or -- */
3328 ST_FUNC void inc(int post, int c)
3330 test_lvalue();
3331 vdup(); /* save lvalue */
3332 if (post) {
3333 gv_dup(); /* duplicate value */
3334 vrotb(3);
3335 vrotb(3);
3337 /* add constant */
3338 vpushi(c - TOK_MID);
3339 gen_op('+');
3340 vstore(); /* store value */
3341 if (post)
3342 vpop(); /* if post op, return saved value */
3345 ST_FUNC void parse_mult_str (CString *astr, const char *msg)
3347 /* read the string */
3348 if (tok != TOK_STR)
3349 expect(msg);
3350 cstr_new(astr);
3351 while (tok == TOK_STR) {
3352 /* XXX: add \0 handling too ? */
3353 cstr_cat(astr, tokc.str.data, -1);
3354 next();
3356 cstr_ccat(astr, '\0');
3359 /* If I is >= 1 and a power of two, returns log2(i)+1.
3360 If I is 0 returns 0. */
3361 static int exact_log2p1(int i)
3363 int ret;
3364 if (!i)
3365 return 0;
3366 for (ret = 1; i >= 1 << 8; ret += 8)
3367 i >>= 8;
3368 if (i >= 1 << 4)
3369 ret += 4, i >>= 4;
3370 if (i >= 1 << 2)
3371 ret += 2, i >>= 2;
3372 if (i >= 1 << 1)
3373 ret++;
3374 return ret;
3377 /* Parse __attribute__((...)) GNUC extension. */
3378 static void parse_attribute(AttributeDef *ad)
3380 int t, n;
3381 CString astr;
3383 redo:
3384 if (tok != TOK_ATTRIBUTE1 && tok != TOK_ATTRIBUTE2)
3385 return;
3386 next();
3387 skip('(');
3388 skip('(');
3389 while (tok != ')') {
3390 if (tok < TOK_IDENT)
3391 expect("attribute name");
3392 t = tok;
3393 next();
3394 switch(t) {
3395 case TOK_SECTION1:
3396 case TOK_SECTION2:
3397 skip('(');
3398 parse_mult_str(&astr, "section name");
3399 ad->section = find_section(tcc_state, (char *)astr.data);
3400 skip(')');
3401 cstr_free(&astr);
3402 break;
3403 case TOK_ALIAS1:
3404 case TOK_ALIAS2:
3405 skip('(');
3406 parse_mult_str(&astr, "alias(\"target\")");
3407 ad->alias_target = /* save string as token, for later */
3408 tok_alloc((char*)astr.data, astr.size-1)->tok;
3409 skip(')');
3410 cstr_free(&astr);
3411 break;
3412 case TOK_VISIBILITY1:
3413 case TOK_VISIBILITY2:
3414 skip('(');
3415 parse_mult_str(&astr,
3416 "visibility(\"default|hidden|internal|protected\")");
3417 if (!strcmp (astr.data, "default"))
3418 ad->a.visibility = STV_DEFAULT;
3419 else if (!strcmp (astr.data, "hidden"))
3420 ad->a.visibility = STV_HIDDEN;
3421 else if (!strcmp (astr.data, "internal"))
3422 ad->a.visibility = STV_INTERNAL;
3423 else if (!strcmp (astr.data, "protected"))
3424 ad->a.visibility = STV_PROTECTED;
3425 else
3426 expect("visibility(\"default|hidden|internal|protected\")");
3427 skip(')');
3428 cstr_free(&astr);
3429 break;
3430 case TOK_ALIGNED1:
3431 case TOK_ALIGNED2:
3432 if (tok == '(') {
3433 next();
3434 n = expr_const();
3435 if (n <= 0 || (n & (n - 1)) != 0)
3436 tcc_error("alignment must be a positive power of two");
3437 skip(')');
3438 } else {
3439 n = MAX_ALIGN;
3441 ad->a.aligned = exact_log2p1(n);
3442 if (n != 1 << (ad->a.aligned - 1))
3443 tcc_error("alignment of %d is larger than implemented", n);
3444 break;
3445 case TOK_PACKED1:
3446 case TOK_PACKED2:
3447 ad->a.packed = 1;
3448 break;
3449 case TOK_WEAK1:
3450 case TOK_WEAK2:
3451 ad->a.weak = 1;
3452 break;
3453 case TOK_UNUSED1:
3454 case TOK_UNUSED2:
3455 /* currently, no need to handle it because tcc does not
3456 track unused objects */
3457 break;
3458 case TOK_NORETURN1:
3459 case TOK_NORETURN2:
3460 /* currently, no need to handle it because tcc does not
3461 track unused objects */
3462 break;
3463 case TOK_CDECL1:
3464 case TOK_CDECL2:
3465 case TOK_CDECL3:
3466 ad->f.func_call = FUNC_CDECL;
3467 break;
3468 case TOK_STDCALL1:
3469 case TOK_STDCALL2:
3470 case TOK_STDCALL3:
3471 ad->f.func_call = FUNC_STDCALL;
3472 break;
3473 #ifdef TCC_TARGET_I386
3474 case TOK_REGPARM1:
3475 case TOK_REGPARM2:
3476 skip('(');
3477 n = expr_const();
3478 if (n > 3)
3479 n = 3;
3480 else if (n < 0)
3481 n = 0;
3482 if (n > 0)
3483 ad->f.func_call = FUNC_FASTCALL1 + n - 1;
3484 skip(')');
3485 break;
3486 case TOK_FASTCALL1:
3487 case TOK_FASTCALL2:
3488 case TOK_FASTCALL3:
3489 ad->f.func_call = FUNC_FASTCALLW;
3490 break;
3491 #endif
3492 case TOK_MODE:
3493 skip('(');
3494 switch(tok) {
3495 case TOK_MODE_DI:
3496 ad->attr_mode = VT_LLONG + 1;
3497 break;
3498 case TOK_MODE_QI:
3499 ad->attr_mode = VT_BYTE + 1;
3500 break;
3501 case TOK_MODE_HI:
3502 ad->attr_mode = VT_SHORT + 1;
3503 break;
3504 case TOK_MODE_SI:
3505 case TOK_MODE_word:
3506 ad->attr_mode = VT_INT + 1;
3507 break;
3508 default:
3509 tcc_warning("__mode__(%s) not supported\n", get_tok_str(tok, NULL));
3510 break;
3512 next();
3513 skip(')');
3514 break;
3515 case TOK_DLLEXPORT:
3516 ad->a.dllexport = 1;
3517 break;
3518 case TOK_NODECORATE:
3519 ad->a.nodecorate = 1;
3520 break;
3521 case TOK_DLLIMPORT:
3522 ad->a.dllimport = 1;
3523 break;
3524 default:
3525 if (tcc_state->warn_unsupported)
3526 tcc_warning("'%s' attribute ignored", get_tok_str(t, NULL));
3527 /* skip parameters */
3528 if (tok == '(') {
3529 int parenthesis = 0;
3530 do {
3531 if (tok == '(')
3532 parenthesis++;
3533 else if (tok == ')')
3534 parenthesis--;
3535 next();
3536 } while (parenthesis && tok != -1);
3538 break;
3540 if (tok != ',')
3541 break;
3542 next();
3544 skip(')');
3545 skip(')');
3546 goto redo;
3549 static Sym * find_field (CType *type, int v)
3551 Sym *s = type->ref;
3552 v |= SYM_FIELD;
3553 while ((s = s->next) != NULL) {
3554 if ((s->v & SYM_FIELD) &&
3555 (s->type.t & VT_BTYPE) == VT_STRUCT &&
3556 (s->v & ~SYM_FIELD) >= SYM_FIRST_ANOM) {
3557 Sym *ret = find_field (&s->type, v);
3558 if (ret)
3559 return ret;
3561 if (s->v == v)
3562 break;
3564 return s;
3567 static void struct_add_offset (Sym *s, int offset)
3569 while ((s = s->next) != NULL) {
3570 if ((s->v & SYM_FIELD) &&
3571 (s->type.t & VT_BTYPE) == VT_STRUCT &&
3572 (s->v & ~SYM_FIELD) >= SYM_FIRST_ANOM) {
3573 struct_add_offset(s->type.ref, offset);
3574 } else
3575 s->c += offset;
3579 static void struct_layout(CType *type, AttributeDef *ad)
3581 int size, align, maxalign, offset, c, bit_pos, bit_size;
3582 int packed, a, bt, prevbt, prev_bit_size;
3583 int pcc = !tcc_state->ms_bitfields;
3584 int pragma_pack = *tcc_state->pack_stack_ptr;
3585 Sym *f;
3587 maxalign = 1;
3588 offset = 0;
3589 c = 0;
3590 bit_pos = 0;
3591 prevbt = VT_STRUCT; /* make it never match */
3592 prev_bit_size = 0;
3594 //#define BF_DEBUG
3596 for (f = type->ref->next; f; f = f->next) {
3597 if (f->type.t & VT_BITFIELD)
3598 bit_size = BIT_SIZE(f->type.t);
3599 else
3600 bit_size = -1;
3601 size = type_size(&f->type, &align);
3602 a = f->a.aligned ? 1 << (f->a.aligned - 1) : 0;
3603 packed = 0;
3605 if (pcc && bit_size == 0) {
3606 /* in pcc mode, packing does not affect zero-width bitfields */
3608 } else {
3609 /* in pcc mode, attribute packed overrides if set. */
3610 if (pcc && (f->a.packed || ad->a.packed))
3611 align = packed = 1;
3613 /* pragma pack overrides align if lesser and packs bitfields always */
3614 if (pragma_pack) {
3615 packed = 1;
3616 if (pragma_pack < align)
3617 align = pragma_pack;
3618 /* in pcc mode pragma pack also overrides individual align */
3619 if (pcc && pragma_pack < a)
3620 a = 0;
3623 /* some individual align was specified */
3624 if (a)
3625 align = a;
3627 if (type->ref->type.t == VT_UNION) {
3628 if (pcc && bit_size >= 0)
3629 size = (bit_size + 7) >> 3;
3630 offset = 0;
3631 if (size > c)
3632 c = size;
3634 } else if (bit_size < 0) {
3635 if (pcc)
3636 c += (bit_pos + 7) >> 3;
3637 c = (c + align - 1) & -align;
3638 offset = c;
3639 if (size > 0)
3640 c += size;
3641 bit_pos = 0;
3642 prevbt = VT_STRUCT;
3643 prev_bit_size = 0;
3645 } else {
3646 /* A bit-field. Layout is more complicated. There are two
3647 options: PCC (GCC) compatible and MS compatible */
3648 if (pcc) {
3649 /* In PCC layout a bit-field is placed adjacent to the
3650 preceding bit-fields, except if:
3651 - it has zero-width
3652 - an individual alignment was given
3653 - it would overflow its base type container and
3654 there is no packing */
3655 if (bit_size == 0) {
3656 new_field:
3657 c = (c + ((bit_pos + 7) >> 3) + align - 1) & -align;
3658 bit_pos = 0;
3659 } else if (f->a.aligned) {
3660 goto new_field;
3661 } else if (!packed) {
3662 int a8 = align * 8;
3663 int ofs = ((c * 8 + bit_pos) % a8 + bit_size + a8 - 1) / a8;
3664 if (ofs > size / align)
3665 goto new_field;
3668 /* in pcc mode, long long bitfields have type int if they fit */
3669 if (size == 8 && bit_size <= 32)
3670 f->type.t = (f->type.t & ~VT_BTYPE) | VT_INT, size = 4;
3672 while (bit_pos >= align * 8)
3673 c += align, bit_pos -= align * 8;
3674 offset = c;
3676 /* In PCC layout named bit-fields influence the alignment
3677 of the containing struct using the base types alignment,
3678 except for packed fields (which here have correct align). */
3679 if (f->v & SYM_FIRST_ANOM
3680 // && bit_size // ??? gcc on ARM/rpi does that
3682 align = 1;
3684 } else {
3685 bt = f->type.t & VT_BTYPE;
3686 if ((bit_pos + bit_size > size * 8)
3687 || (bit_size > 0) == (bt != prevbt)
3689 c = (c + align - 1) & -align;
3690 offset = c;
3691 bit_pos = 0;
3692 /* In MS bitfield mode a bit-field run always uses
3693 at least as many bits as the underlying type.
3694 To start a new run it's also required that this
3695 or the last bit-field had non-zero width. */
3696 if (bit_size || prev_bit_size)
3697 c += size;
3699 /* In MS layout the records alignment is normally
3700 influenced by the field, except for a zero-width
3701 field at the start of a run (but by further zero-width
3702 fields it is again). */
3703 if (bit_size == 0 && prevbt != bt)
3704 align = 1;
3705 prevbt = bt;
3706 prev_bit_size = bit_size;
3709 f->type.t = (f->type.t & ~(0x3f << VT_STRUCT_SHIFT))
3710 | (bit_pos << VT_STRUCT_SHIFT);
3711 bit_pos += bit_size;
3713 if (align > maxalign)
3714 maxalign = align;
3716 #ifdef BF_DEBUG
3717 printf("set field %s offset %-2d size %-2d align %-2d",
3718 get_tok_str(f->v & ~SYM_FIELD, NULL), offset, size, align);
3719 if (f->type.t & VT_BITFIELD) {
3720 printf(" pos %-2d bits %-2d",
3721 BIT_POS(f->type.t),
3722 BIT_SIZE(f->type.t)
3725 printf("\n");
3726 #endif
3728 if (f->v & SYM_FIRST_ANOM && (f->type.t & VT_BTYPE) == VT_STRUCT) {
3729 Sym *ass;
3730 /* An anonymous struct/union. Adjust member offsets
3731 to reflect the real offset of our containing struct.
3732 Also set the offset of this anon member inside
3733 the outer struct to be zero. Via this it
3734 works when accessing the field offset directly
3735 (from base object), as well as when recursing
3736 members in initializer handling. */
3737 int v2 = f->type.ref->v;
3738 if (!(v2 & SYM_FIELD) &&
3739 (v2 & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
3740 Sym **pps;
3741 /* This happens only with MS extensions. The
3742 anon member has a named struct type, so it
3743 potentially is shared with other references.
3744 We need to unshare members so we can modify
3745 them. */
3746 ass = f->type.ref;
3747 f->type.ref = sym_push(anon_sym++ | SYM_FIELD,
3748 &f->type.ref->type, 0,
3749 f->type.ref->c);
3750 pps = &f->type.ref->next;
3751 while ((ass = ass->next) != NULL) {
3752 *pps = sym_push(ass->v, &ass->type, 0, ass->c);
3753 pps = &((*pps)->next);
3755 *pps = NULL;
3757 struct_add_offset(f->type.ref, offset);
3758 f->c = 0;
3759 } else {
3760 f->c = offset;
3763 f->r = 0;
3766 if (pcc)
3767 c += (bit_pos + 7) >> 3;
3769 /* store size and alignment */
3770 a = bt = ad->a.aligned ? 1 << (ad->a.aligned - 1) : 1;
3771 if (a < maxalign)
3772 a = maxalign;
3773 type->ref->r = a;
3774 if (pragma_pack && pragma_pack < maxalign && 0 == pcc) {
3775 /* can happen if individual align for some member was given. In
3776 this case MSVC ignores maxalign when aligning the size */
3777 a = pragma_pack;
3778 if (a < bt)
3779 a = bt;
3781 c = (c + a - 1) & -a;
3782 type->ref->c = c;
3784 #ifdef BF_DEBUG
3785 printf("struct size %-2d align %-2d\n\n", c, a), fflush(stdout);
3786 #endif
3788 /* check whether we can access bitfields by their type */
3789 for (f = type->ref->next; f; f = f->next) {
3790 int s, px, cx, c0;
3791 CType t;
3793 if (0 == (f->type.t & VT_BITFIELD))
3794 continue;
3795 f->type.ref = f;
3796 f->auxtype = -1;
3797 bit_size = BIT_SIZE(f->type.t);
3798 if (bit_size == 0)
3799 continue;
3800 bit_pos = BIT_POS(f->type.t);
3801 size = type_size(&f->type, &align);
3802 if (bit_pos + bit_size <= size * 8 && f->c + size <= c)
3803 continue;
3805 /* try to access the field using a different type */
3806 c0 = -1, s = align = 1;
3807 for (;;) {
3808 px = f->c * 8 + bit_pos;
3809 cx = (px >> 3) & -align;
3810 px = px - (cx << 3);
3811 if (c0 == cx)
3812 break;
3813 s = (px + bit_size + 7) >> 3;
3814 if (s > 4) {
3815 t.t = VT_LLONG;
3816 } else if (s > 2) {
3817 t.t = VT_INT;
3818 } else if (s > 1) {
3819 t.t = VT_SHORT;
3820 } else {
3821 t.t = VT_BYTE;
3823 s = type_size(&t, &align);
3824 c0 = cx;
3827 if (px + bit_size <= s * 8 && cx + s <= c) {
3828 /* update offset and bit position */
3829 f->c = cx;
3830 bit_pos = px;
3831 f->type.t = (f->type.t & ~(0x3f << VT_STRUCT_SHIFT))
3832 | (bit_pos << VT_STRUCT_SHIFT);
3833 if (s != size)
3834 f->auxtype = t.t;
3835 #ifdef BF_DEBUG
3836 printf("FIX field %s offset %-2d size %-2d align %-2d "
3837 "pos %-2d bits %-2d\n",
3838 get_tok_str(f->v & ~SYM_FIELD, NULL),
3839 cx, s, align, px, bit_size);
3840 #endif
3841 } else {
3842 /* fall back to load/store single-byte wise */
3843 f->auxtype = VT_STRUCT;
3844 #ifdef BF_DEBUG
3845 printf("FIX field %s : load byte-wise\n",
3846 get_tok_str(f->v & ~SYM_FIELD, NULL));
3847 #endif
3852 /* enum/struct/union declaration. u is VT_ENUM/VT_STRUCT/VT_UNION */
3853 static void struct_decl(CType *type, int u)
3855 int v, c, size, align, flexible;
3856 int bit_size, bsize, bt;
3857 Sym *s, *ss, **ps;
3858 AttributeDef ad, ad1;
3859 CType type1, btype;
3861 memset(&ad, 0, sizeof ad);
3862 next();
3863 parse_attribute(&ad);
3864 if (tok != '{') {
3865 v = tok;
3866 next();
3867 /* struct already defined ? return it */
3868 if (v < TOK_IDENT)
3869 expect("struct/union/enum name");
3870 s = struct_find(v);
3871 if (s && (s->sym_scope == local_scope || tok != '{')) {
3872 if (u == s->type.t)
3873 goto do_decl;
3874 if (u == VT_ENUM && IS_ENUM(s->type.t))
3875 goto do_decl;
3876 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
3878 } else {
3879 v = anon_sym++;
3881 /* Record the original enum/struct/union token. */
3882 type1.t = u == VT_ENUM ? u | VT_INT | VT_UNSIGNED : u;
3883 type1.ref = NULL;
3884 /* we put an undefined size for struct/union */
3885 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
3886 s->r = 0; /* default alignment is zero as gcc */
3887 do_decl:
3888 type->t = s->type.t;
3889 type->ref = s;
3891 if (tok == '{') {
3892 next();
3893 if (s->c != -1)
3894 tcc_error("struct/union/enum already defined");
3895 /* cannot be empty */
3896 /* non empty enums are not allowed */
3897 ps = &s->next;
3898 if (u == VT_ENUM) {
3899 long long ll = 0, pl = 0, nl = 0;
3900 CType t;
3901 t.ref = s;
3902 /* enum symbols have static storage */
3903 t.t = VT_INT|VT_STATIC|VT_ENUM_VAL;
3904 for(;;) {
3905 v = tok;
3906 if (v < TOK_UIDENT)
3907 expect("identifier");
3908 ss = sym_find(v);
3909 if (ss && !local_stack)
3910 tcc_error("redefinition of enumerator '%s'",
3911 get_tok_str(v, NULL));
3912 next();
3913 if (tok == '=') {
3914 next();
3915 ll = expr_const64();
3917 ss = sym_push(v, &t, VT_CONST, 0);
3918 ss->enum_val = ll;
3919 *ps = ss, ps = &ss->next;
3920 if (ll < nl)
3921 nl = ll;
3922 if (ll > pl)
3923 pl = ll;
3924 if (tok != ',')
3925 break;
3926 next();
3927 ll++;
3928 /* NOTE: we accept a trailing comma */
3929 if (tok == '}')
3930 break;
3932 skip('}');
3933 /* set integral type of the enum */
3934 t.t = VT_INT;
3935 if (nl >= 0) {
3936 if (pl != (unsigned)pl)
3937 t.t = (LONG_SIZE==8 ? VT_LLONG|VT_LONG : VT_LLONG);
3938 t.t |= VT_UNSIGNED;
3939 } else if (pl != (int)pl || nl != (int)nl)
3940 t.t = (LONG_SIZE==8 ? VT_LLONG|VT_LONG : VT_LLONG);
3941 s->type.t = type->t = t.t | VT_ENUM;
3942 s->c = 0;
3943 /* set type for enum members */
3944 for (ss = s->next; ss; ss = ss->next) {
3945 ll = ss->enum_val;
3946 if (ll == (int)ll) /* default is int if it fits */
3947 continue;
3948 if (t.t & VT_UNSIGNED) {
3949 ss->type.t |= VT_UNSIGNED;
3950 if (ll == (unsigned)ll)
3951 continue;
3953 ss->type.t = (ss->type.t & ~VT_BTYPE)
3954 | (LONG_SIZE==8 ? VT_LLONG|VT_LONG : VT_LLONG);
3956 } else {
3957 c = 0;
3958 flexible = 0;
3959 while (tok != '}') {
3960 if (!parse_btype(&btype, &ad1)) {
3961 skip(';');
3962 continue;
3964 while (1) {
3965 if (flexible)
3966 tcc_error("flexible array member '%s' not at the end of struct",
3967 get_tok_str(v, NULL));
3968 bit_size = -1;
3969 v = 0;
3970 type1 = btype;
3971 if (tok != ':') {
3972 if (tok != ';')
3973 type_decl(&type1, &ad1, &v, TYPE_DIRECT);
3974 if (v == 0) {
3975 if ((type1.t & VT_BTYPE) != VT_STRUCT)
3976 expect("identifier");
3977 else {
3978 int v = btype.ref->v;
3979 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
3980 if (tcc_state->ms_extensions == 0)
3981 expect("identifier");
3985 if (type_size(&type1, &align) < 0) {
3986 if ((u == VT_STRUCT) && (type1.t & VT_ARRAY) && c)
3987 flexible = 1;
3988 else
3989 tcc_error("field '%s' has incomplete type",
3990 get_tok_str(v, NULL));
3992 if ((type1.t & VT_BTYPE) == VT_FUNC ||
3993 (type1.t & VT_BTYPE) == VT_VOID ||
3994 (type1.t & VT_STORAGE))
3995 tcc_error("invalid type for '%s'",
3996 get_tok_str(v, NULL));
3998 if (tok == ':') {
3999 next();
4000 bit_size = expr_const();
4001 /* XXX: handle v = 0 case for messages */
4002 if (bit_size < 0)
4003 tcc_error("negative width in bit-field '%s'",
4004 get_tok_str(v, NULL));
4005 if (v && bit_size == 0)
4006 tcc_error("zero width for bit-field '%s'",
4007 get_tok_str(v, NULL));
4008 parse_attribute(&ad1);
4010 size = type_size(&type1, &align);
4011 if (bit_size >= 0) {
4012 bt = type1.t & VT_BTYPE;
4013 if (bt != VT_INT &&
4014 bt != VT_BYTE &&
4015 bt != VT_SHORT &&
4016 bt != VT_BOOL &&
4017 bt != VT_LLONG)
4018 tcc_error("bitfields must have scalar type");
4019 bsize = size * 8;
4020 if (bit_size > bsize) {
4021 tcc_error("width of '%s' exceeds its type",
4022 get_tok_str(v, NULL));
4023 } else if (bit_size == bsize
4024 && !ad.a.packed && !ad1.a.packed) {
4025 /* no need for bit fields */
4027 } else if (bit_size == 64) {
4028 tcc_error("field width 64 not implemented");
4029 } else {
4030 type1.t = (type1.t & ~VT_STRUCT_MASK)
4031 | VT_BITFIELD
4032 | (bit_size << (VT_STRUCT_SHIFT + 6));
4035 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
4036 /* Remember we've seen a real field to check
4037 for placement of flexible array member. */
4038 c = 1;
4040 /* If member is a struct or bit-field, enforce
4041 placing into the struct (as anonymous). */
4042 if (v == 0 &&
4043 ((type1.t & VT_BTYPE) == VT_STRUCT ||
4044 bit_size >= 0)) {
4045 v = anon_sym++;
4047 if (v) {
4048 ss = sym_push(v | SYM_FIELD, &type1, 0, 0);
4049 ss->a = ad1.a;
4050 *ps = ss;
4051 ps = &ss->next;
4053 if (tok == ';' || tok == TOK_EOF)
4054 break;
4055 skip(',');
4057 skip(';');
4059 skip('}');
4060 parse_attribute(&ad);
4061 struct_layout(type, &ad);
4066 static void sym_to_attr(AttributeDef *ad, Sym *s)
4068 merge_symattr(&ad->a, &s->a);
4069 merge_funcattr(&ad->f, &s->f);
4072 /* Add type qualifiers to a type. If the type is an array then the qualifiers
4073 are added to the element type, copied because it could be a typedef. */
4074 static void parse_btype_qualify(CType *type, int qualifiers)
4076 while (type->t & VT_ARRAY) {
4077 type->ref = sym_push(SYM_FIELD, &type->ref->type, 0, type->ref->c);
4078 type = &type->ref->type;
4080 type->t |= qualifiers;
4083 /* return 0 if no type declaration. otherwise, return the basic type
4084 and skip it.
4086 static int parse_btype(CType *type, AttributeDef *ad)
4088 int t, u, bt, st, type_found, typespec_found, g;
4089 Sym *s;
4090 CType type1;
4092 memset(ad, 0, sizeof(AttributeDef));
4093 type_found = 0;
4094 typespec_found = 0;
4095 t = VT_INT;
4096 bt = st = -1;
4097 type->ref = NULL;
4099 while(1) {
4100 switch(tok) {
4101 case TOK_EXTENSION:
4102 /* currently, we really ignore extension */
4103 next();
4104 continue;
4106 /* basic types */
4107 case TOK_CHAR:
4108 u = VT_BYTE;
4109 basic_type:
4110 next();
4111 basic_type1:
4112 if (u == VT_SHORT || u == VT_LONG) {
4113 if (st != -1 || (bt != -1 && bt != VT_INT))
4114 tmbt: tcc_error("too many basic types");
4115 st = u;
4116 } else {
4117 if (bt != -1 || (st != -1 && u != VT_INT))
4118 goto tmbt;
4119 bt = u;
4121 if (u != VT_INT)
4122 t = (t & ~(VT_BTYPE|VT_LONG)) | u;
4123 typespec_found = 1;
4124 break;
4125 case TOK_VOID:
4126 u = VT_VOID;
4127 goto basic_type;
4128 case TOK_SHORT:
4129 u = VT_SHORT;
4130 goto basic_type;
4131 case TOK_INT:
4132 u = VT_INT;
4133 goto basic_type;
4134 case TOK_LONG:
4135 if ((t & VT_BTYPE) == VT_DOUBLE) {
4136 t = (t & ~(VT_BTYPE|VT_LONG)) | VT_LDOUBLE;
4137 } else if ((t & (VT_BTYPE|VT_LONG)) == VT_LONG) {
4138 t = (t & ~(VT_BTYPE|VT_LONG)) | VT_LLONG;
4139 } else {
4140 u = VT_LONG;
4141 goto basic_type;
4143 next();
4144 break;
4145 #ifdef TCC_TARGET_ARM64
4146 case TOK_UINT128:
4147 /* GCC's __uint128_t appears in some Linux header files. Make it a
4148 synonym for long double to get the size and alignment right. */
4149 u = VT_LDOUBLE;
4150 goto basic_type;
4151 #endif
4152 case TOK_BOOL:
4153 u = VT_BOOL;
4154 goto basic_type;
4155 case TOK_FLOAT:
4156 u = VT_FLOAT;
4157 goto basic_type;
4158 case TOK_DOUBLE:
4159 if ((t & (VT_BTYPE|VT_LONG)) == VT_LONG) {
4160 t = (t & ~(VT_BTYPE|VT_LONG)) | VT_LDOUBLE;
4161 } else {
4162 u = VT_DOUBLE;
4163 goto basic_type;
4165 next();
4166 break;
4167 case TOK_ENUM:
4168 struct_decl(&type1, VT_ENUM);
4169 basic_type2:
4170 u = type1.t;
4171 type->ref = type1.ref;
4172 goto basic_type1;
4173 case TOK_STRUCT:
4174 struct_decl(&type1, VT_STRUCT);
4175 goto basic_type2;
4176 case TOK_UNION:
4177 struct_decl(&type1, VT_UNION);
4178 goto basic_type2;
4180 /* type modifiers */
4181 case TOK_CONST1:
4182 case TOK_CONST2:
4183 case TOK_CONST3:
4184 type->t = t;
4185 parse_btype_qualify(type, VT_CONSTANT);
4186 t = type->t;
4187 next();
4188 break;
4189 case TOK_VOLATILE1:
4190 case TOK_VOLATILE2:
4191 case TOK_VOLATILE3:
4192 type->t = t;
4193 parse_btype_qualify(type, VT_VOLATILE);
4194 t = type->t;
4195 next();
4196 break;
4197 case TOK_SIGNED1:
4198 case TOK_SIGNED2:
4199 case TOK_SIGNED3:
4200 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == (VT_DEFSIGN|VT_UNSIGNED))
4201 tcc_error("signed and unsigned modifier");
4202 t |= VT_DEFSIGN;
4203 next();
4204 typespec_found = 1;
4205 break;
4206 case TOK_REGISTER:
4207 case TOK_AUTO:
4208 case TOK_RESTRICT1:
4209 case TOK_RESTRICT2:
4210 case TOK_RESTRICT3:
4211 next();
4212 break;
4213 case TOK_UNSIGNED:
4214 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == VT_DEFSIGN)
4215 tcc_error("signed and unsigned modifier");
4216 t |= VT_DEFSIGN | VT_UNSIGNED;
4217 next();
4218 typespec_found = 1;
4219 break;
4221 /* storage */
4222 case TOK_EXTERN:
4223 g = VT_EXTERN;
4224 goto storage;
4225 case TOK_STATIC:
4226 g = VT_STATIC;
4227 goto storage;
4228 case TOK_TYPEDEF:
4229 g = VT_TYPEDEF;
4230 goto storage;
4231 storage:
4232 if (t & (VT_EXTERN|VT_STATIC|VT_TYPEDEF) & ~g)
4233 tcc_error("multiple storage classes");
4234 t |= g;
4235 next();
4236 break;
4237 case TOK_INLINE1:
4238 case TOK_INLINE2:
4239 case TOK_INLINE3:
4240 t |= VT_INLINE;
4241 next();
4242 break;
4244 /* GNUC attribute */
4245 case TOK_ATTRIBUTE1:
4246 case TOK_ATTRIBUTE2:
4247 parse_attribute(ad);
4248 if (ad->attr_mode) {
4249 u = ad->attr_mode -1;
4250 t = (t & ~(VT_BTYPE|VT_LONG)) | u;
4252 continue;
4253 /* GNUC typeof */
4254 case TOK_TYPEOF1:
4255 case TOK_TYPEOF2:
4256 case TOK_TYPEOF3:
4257 next();
4258 parse_expr_type(&type1);
4259 /* remove all storage modifiers except typedef */
4260 type1.t &= ~(VT_STORAGE&~VT_TYPEDEF);
4261 if (type1.ref)
4262 sym_to_attr(ad, type1.ref);
4263 goto basic_type2;
4264 default:
4265 if (typespec_found)
4266 goto the_end;
4267 s = sym_find(tok);
4268 if (!s || !(s->type.t & VT_TYPEDEF))
4269 goto the_end;
4270 t &= ~(VT_BTYPE|VT_LONG);
4271 u = t & ~(VT_CONSTANT | VT_VOLATILE), t ^= u;
4272 type->t = (s->type.t & ~VT_TYPEDEF) | u;
4273 type->ref = s->type.ref;
4274 if (t)
4275 parse_btype_qualify(type, t);
4276 t = type->t;
4277 /* get attributes from typedef */
4278 sym_to_attr(ad, s);
4279 next();
4280 typespec_found = 1;
4281 st = bt = -2;
4282 break;
4284 type_found = 1;
4286 the_end:
4287 if (tcc_state->char_is_unsigned) {
4288 if ((t & (VT_DEFSIGN|VT_BTYPE)) == VT_BYTE)
4289 t |= VT_UNSIGNED;
4291 /* VT_LONG is used just as a modifier for VT_INT / VT_LLONG */
4292 bt = t & (VT_BTYPE|VT_LONG);
4293 if (bt == VT_LONG)
4294 t |= LONG_SIZE == 8 ? VT_LLONG : VT_INT;
4295 #ifdef TCC_TARGET_PE
4296 if (bt == VT_LDOUBLE)
4297 t = (t & ~(VT_BTYPE|VT_LONG)) | VT_DOUBLE;
4298 #endif
4299 type->t = t;
4300 return type_found;
4303 /* convert a function parameter type (array to pointer and function to
4304 function pointer) */
4305 static inline void convert_parameter_type(CType *pt)
4307 /* remove const and volatile qualifiers (XXX: const could be used
4308 to indicate a const function parameter */
4309 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
4310 /* array must be transformed to pointer according to ANSI C */
4311 pt->t &= ~VT_ARRAY;
4312 if ((pt->t & VT_BTYPE) == VT_FUNC) {
4313 mk_pointer(pt);
4317 ST_FUNC void parse_asm_str(CString *astr)
4319 skip('(');
4320 parse_mult_str(astr, "string constant");
4323 /* Parse an asm label and return the token */
4324 static int asm_label_instr(void)
4326 int v;
4327 CString astr;
4329 next();
4330 parse_asm_str(&astr);
4331 skip(')');
4332 #ifdef ASM_DEBUG
4333 printf("asm_alias: \"%s\"\n", (char *)astr.data);
4334 #endif
4335 v = tok_alloc(astr.data, astr.size - 1)->tok;
4336 cstr_free(&astr);
4337 return v;
4340 static int post_type(CType *type, AttributeDef *ad, int storage, int td)
4342 int n, l, t1, arg_size, align;
4343 Sym **plast, *s, *first;
4344 AttributeDef ad1;
4345 CType pt;
4347 if (tok == '(') {
4348 /* function type, or recursive declarator (return if so) */
4349 next();
4350 if (td && !(td & TYPE_ABSTRACT))
4351 return 0;
4352 if (tok == ')')
4353 l = 0;
4354 else if (parse_btype(&pt, &ad1))
4355 l = FUNC_NEW;
4356 else if (td) {
4357 merge_attr (ad, &ad1);
4358 return 0;
4359 } else
4360 l = FUNC_OLD;
4361 first = NULL;
4362 plast = &first;
4363 arg_size = 0;
4364 if (l) {
4365 for(;;) {
4366 /* read param name and compute offset */
4367 if (l != FUNC_OLD) {
4368 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
4369 break;
4370 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
4371 if ((pt.t & VT_BTYPE) == VT_VOID)
4372 tcc_error("parameter declared as void");
4373 } else {
4374 n = tok;
4375 if (n < TOK_UIDENT)
4376 expect("identifier");
4377 pt.t = VT_VOID; /* invalid type */
4378 next();
4380 convert_parameter_type(&pt);
4381 arg_size += (type_size(&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
4382 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
4383 *plast = s;
4384 plast = &s->next;
4385 if (tok == ')')
4386 break;
4387 skip(',');
4388 if (l == FUNC_NEW && tok == TOK_DOTS) {
4389 l = FUNC_ELLIPSIS;
4390 next();
4391 break;
4393 if (l == FUNC_NEW && !parse_btype(&pt, &ad1))
4394 tcc_error("invalid type");
4396 } else
4397 /* if no parameters, then old type prototype */
4398 l = FUNC_OLD;
4399 skip(')');
4400 /* NOTE: const is ignored in returned type as it has a special
4401 meaning in gcc / C++ */
4402 type->t &= ~VT_CONSTANT;
4403 /* some ancient pre-K&R C allows a function to return an array
4404 and the array brackets to be put after the arguments, such
4405 that "int c()[]" means something like "int[] c()" */
4406 if (tok == '[') {
4407 next();
4408 skip(']'); /* only handle simple "[]" */
4409 mk_pointer(type);
4411 /* we push a anonymous symbol which will contain the function prototype */
4412 ad->f.func_args = arg_size;
4413 ad->f.func_type = l;
4414 s = sym_push(SYM_FIELD, type, 0, 0);
4415 s->a = ad->a;
4416 s->f = ad->f;
4417 s->next = first;
4418 type->t = VT_FUNC;
4419 type->ref = s;
4420 } else if (tok == '[') {
4421 int saved_nocode_wanted = nocode_wanted;
4422 /* array definition */
4423 next();
4424 while (1) {
4425 /* XXX The optional type-quals and static should only be accepted
4426 in parameter decls. The '*' as well, and then even only
4427 in prototypes (not function defs). */
4428 switch (tok) {
4429 case TOK_RESTRICT1: case TOK_RESTRICT2: case TOK_RESTRICT3:
4430 case TOK_CONST1:
4431 case TOK_VOLATILE1:
4432 case TOK_STATIC:
4433 case '*':
4434 next();
4435 continue;
4436 default:
4437 break;
4439 break;
4441 n = -1;
4442 t1 = 0;
4443 if (tok != ']') {
4444 if (!local_stack || (storage & VT_STATIC))
4445 vpushi(expr_const());
4446 else {
4447 /* VLAs (which can only happen with local_stack && !VT_STATIC)
4448 length must always be evaluated, even under nocode_wanted,
4449 so that its size slot is initialized (e.g. under sizeof
4450 or typeof). */
4451 nocode_wanted = 0;
4452 gexpr();
4454 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4455 n = vtop->c.i;
4456 if (n < 0)
4457 tcc_error("invalid array size");
4458 } else {
4459 if (!is_integer_btype(vtop->type.t & VT_BTYPE))
4460 tcc_error("size of variable length array should be an integer");
4461 t1 = VT_VLA;
4464 skip(']');
4465 /* parse next post type */
4466 post_type(type, ad, storage, 0);
4467 if (type->t == VT_FUNC)
4468 tcc_error("declaration of an array of functions");
4469 t1 |= type->t & VT_VLA;
4471 if (t1 & VT_VLA) {
4472 loc -= type_size(&int_type, &align);
4473 loc &= -align;
4474 n = loc;
4476 vla_runtime_type_size(type, &align);
4477 gen_op('*');
4478 vset(&int_type, VT_LOCAL|VT_LVAL, n);
4479 vswap();
4480 vstore();
4482 if (n != -1)
4483 vpop();
4484 nocode_wanted = saved_nocode_wanted;
4486 /* we push an anonymous symbol which will contain the array
4487 element type */
4488 s = sym_push(SYM_FIELD, type, 0, n);
4489 type->t = (t1 ? VT_VLA : VT_ARRAY) | VT_PTR;
4490 type->ref = s;
4492 return 1;
4495 /* Parse a type declarator (except basic type), and return the type
4496 in 'type'. 'td' is a bitmask indicating which kind of type decl is
4497 expected. 'type' should contain the basic type. 'ad' is the
4498 attribute definition of the basic type. It can be modified by
4499 type_decl(). If this (possibly abstract) declarator is a pointer chain
4500 it returns the innermost pointed to type (equals *type, but is a different
4501 pointer), otherwise returns type itself, that's used for recursive calls. */
4502 static CType *type_decl(CType *type, AttributeDef *ad, int *v, int td)
4504 CType *post, *ret;
4505 int qualifiers, storage;
4507 /* recursive type, remove storage bits first, apply them later again */
4508 storage = type->t & VT_STORAGE;
4509 type->t &= ~VT_STORAGE;
4510 post = ret = type;
4512 while (tok == '*') {
4513 qualifiers = 0;
4514 redo:
4515 next();
4516 switch(tok) {
4517 case TOK_CONST1:
4518 case TOK_CONST2:
4519 case TOK_CONST3:
4520 qualifiers |= VT_CONSTANT;
4521 goto redo;
4522 case TOK_VOLATILE1:
4523 case TOK_VOLATILE2:
4524 case TOK_VOLATILE3:
4525 qualifiers |= VT_VOLATILE;
4526 goto redo;
4527 case TOK_RESTRICT1:
4528 case TOK_RESTRICT2:
4529 case TOK_RESTRICT3:
4530 goto redo;
4531 /* XXX: clarify attribute handling */
4532 case TOK_ATTRIBUTE1:
4533 case TOK_ATTRIBUTE2:
4534 parse_attribute(ad);
4535 break;
4537 mk_pointer(type);
4538 type->t |= qualifiers;
4539 if (ret == type)
4540 /* innermost pointed to type is the one for the first derivation */
4541 ret = pointed_type(type);
4544 if (tok == '(') {
4545 /* This is possibly a parameter type list for abstract declarators
4546 ('int ()'), use post_type for testing this. */
4547 if (!post_type(type, ad, 0, td)) {
4548 /* It's not, so it's a nested declarator, and the post operations
4549 apply to the innermost pointed to type (if any). */
4550 /* XXX: this is not correct to modify 'ad' at this point, but
4551 the syntax is not clear */
4552 parse_attribute(ad);
4553 post = type_decl(type, ad, v, td);
4554 skip(')');
4556 } else if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
4557 /* type identifier */
4558 *v = tok;
4559 next();
4560 } else {
4561 if (!(td & TYPE_ABSTRACT))
4562 expect("identifier");
4563 *v = 0;
4565 post_type(post, ad, storage, 0);
4566 parse_attribute(ad);
4567 type->t |= storage;
4568 return ret;
4571 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
4572 ST_FUNC int lvalue_type(int t)
4574 int bt, r;
4575 r = VT_LVAL;
4576 bt = t & VT_BTYPE;
4577 if (bt == VT_BYTE || bt == VT_BOOL)
4578 r |= VT_LVAL_BYTE;
4579 else if (bt == VT_SHORT)
4580 r |= VT_LVAL_SHORT;
4581 else
4582 return r;
4583 if (t & VT_UNSIGNED)
4584 r |= VT_LVAL_UNSIGNED;
4585 return r;
4588 /* indirection with full error checking and bound check */
4589 ST_FUNC void indir(void)
4591 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
4592 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
4593 return;
4594 expect("pointer");
4596 if (vtop->r & VT_LVAL)
4597 gv(RC_INT);
4598 vtop->type = *pointed_type(&vtop->type);
4599 /* Arrays and functions are never lvalues */
4600 if (!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_VLA)
4601 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
4602 vtop->r |= lvalue_type(vtop->type.t);
4603 /* if bound checking, the referenced pointer must be checked */
4604 #ifdef CONFIG_TCC_BCHECK
4605 if (tcc_state->do_bounds_check)
4606 vtop->r |= VT_MUSTBOUND;
4607 #endif
4611 /* pass a parameter to a function and do type checking and casting */
4612 static void gfunc_param_typed(Sym *func, Sym *arg)
4614 int func_type;
4615 CType type;
4617 func_type = func->f.func_type;
4618 if (func_type == FUNC_OLD ||
4619 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
4620 /* default casting : only need to convert float to double */
4621 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
4622 gen_cast_s(VT_DOUBLE);
4623 } else if (vtop->type.t & VT_BITFIELD) {
4624 type.t = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
4625 type.ref = vtop->type.ref;
4626 gen_cast(&type);
4628 } else if (arg == NULL) {
4629 tcc_error("too many arguments to function");
4630 } else {
4631 type = arg->type;
4632 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
4633 gen_assign_cast(&type);
4637 /* parse an expression and return its type without any side effect. */
4638 static void expr_type(CType *type, void (*expr_fn)(void))
4640 nocode_wanted++;
4641 expr_fn();
4642 *type = vtop->type;
4643 vpop();
4644 nocode_wanted--;
4647 /* parse an expression of the form '(type)' or '(expr)' and return its
4648 type */
4649 static void parse_expr_type(CType *type)
4651 int n;
4652 AttributeDef ad;
4654 skip('(');
4655 if (parse_btype(type, &ad)) {
4656 type_decl(type, &ad, &n, TYPE_ABSTRACT);
4657 } else {
4658 expr_type(type, gexpr);
4660 skip(')');
4663 static void parse_type(CType *type)
4665 AttributeDef ad;
4666 int n;
4668 if (!parse_btype(type, &ad)) {
4669 expect("type");
4671 type_decl(type, &ad, &n, TYPE_ABSTRACT);
4674 static void parse_builtin_params(int nc, const char *args)
4676 char c, sep = '(';
4677 CType t;
4678 if (nc)
4679 nocode_wanted++;
4680 next();
4681 while ((c = *args++)) {
4682 skip(sep);
4683 sep = ',';
4684 switch (c) {
4685 case 'e': expr_eq(); continue;
4686 case 't': parse_type(&t); vpush(&t); continue;
4687 default: tcc_error("internal error"); break;
4690 skip(')');
4691 if (nc)
4692 nocode_wanted--;
4695 ST_FUNC void unary(void)
4697 int n, t, align, size, r, sizeof_caller;
4698 CType type;
4699 Sym *s;
4700 AttributeDef ad;
4702 sizeof_caller = in_sizeof;
4703 in_sizeof = 0;
4704 type.ref = NULL;
4705 /* XXX: GCC 2.95.3 does not generate a table although it should be
4706 better here */
4707 tok_next:
4708 switch(tok) {
4709 case TOK_EXTENSION:
4710 next();
4711 goto tok_next;
4712 case TOK_LCHAR:
4713 #ifdef TCC_TARGET_PE
4714 t = VT_SHORT|VT_UNSIGNED;
4715 goto push_tokc;
4716 #endif
4717 case TOK_CINT:
4718 case TOK_CCHAR:
4719 t = VT_INT;
4720 push_tokc:
4721 type.t = t;
4722 vsetc(&type, VT_CONST, &tokc);
4723 next();
4724 break;
4725 case TOK_CUINT:
4726 t = VT_INT | VT_UNSIGNED;
4727 goto push_tokc;
4728 case TOK_CLLONG:
4729 t = VT_LLONG;
4730 goto push_tokc;
4731 case TOK_CULLONG:
4732 t = VT_LLONG | VT_UNSIGNED;
4733 goto push_tokc;
4734 case TOK_CFLOAT:
4735 t = VT_FLOAT;
4736 goto push_tokc;
4737 case TOK_CDOUBLE:
4738 t = VT_DOUBLE;
4739 goto push_tokc;
4740 case TOK_CLDOUBLE:
4741 t = VT_LDOUBLE;
4742 goto push_tokc;
4743 case TOK_CLONG:
4744 t = (LONG_SIZE == 8 ? VT_LLONG : VT_INT) | VT_LONG;
4745 goto push_tokc;
4746 case TOK_CULONG:
4747 t = (LONG_SIZE == 8 ? VT_LLONG : VT_INT) | VT_LONG | VT_UNSIGNED;
4748 goto push_tokc;
4749 case TOK___FUNCTION__:
4750 if (!gnu_ext)
4751 goto tok_identifier;
4752 /* fall thru */
4753 case TOK___FUNC__:
4755 void *ptr;
4756 int len;
4757 /* special function name identifier */
4758 len = strlen(funcname) + 1;
4759 /* generate char[len] type */
4760 type.t = VT_BYTE;
4761 mk_pointer(&type);
4762 type.t |= VT_ARRAY;
4763 type.ref->c = len;
4764 vpush_ref(&type, data_section, data_section->data_offset, len);
4765 if (!NODATA_WANTED) {
4766 ptr = section_ptr_add(data_section, len);
4767 memcpy(ptr, funcname, len);
4769 next();
4771 break;
4772 case TOK_LSTR:
4773 #ifdef TCC_TARGET_PE
4774 t = VT_SHORT | VT_UNSIGNED;
4775 #else
4776 t = VT_INT;
4777 #endif
4778 goto str_init;
4779 case TOK_STR:
4780 /* string parsing */
4781 t = VT_BYTE;
4782 if (tcc_state->char_is_unsigned)
4783 t = VT_BYTE | VT_UNSIGNED;
4784 str_init:
4785 if (tcc_state->warn_write_strings)
4786 t |= VT_CONSTANT;
4787 type.t = t;
4788 mk_pointer(&type);
4789 type.t |= VT_ARRAY;
4790 memset(&ad, 0, sizeof(AttributeDef));
4791 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, 0);
4792 break;
4793 case '(':
4794 next();
4795 /* cast ? */
4796 if (parse_btype(&type, &ad)) {
4797 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
4798 skip(')');
4799 /* check ISOC99 compound literal */
4800 if (tok == '{') {
4801 /* data is allocated locally by default */
4802 if (global_expr)
4803 r = VT_CONST;
4804 else
4805 r = VT_LOCAL;
4806 /* all except arrays are lvalues */
4807 if (!(type.t & VT_ARRAY))
4808 r |= lvalue_type(type.t);
4809 memset(&ad, 0, sizeof(AttributeDef));
4810 decl_initializer_alloc(&type, &ad, r, 1, 0, 0);
4811 } else {
4812 if (sizeof_caller) {
4813 vpush(&type);
4814 return;
4816 unary();
4817 gen_cast(&type);
4819 } else if (tok == '{') {
4820 int saved_nocode_wanted = nocode_wanted;
4821 if (const_wanted)
4822 tcc_error("expected constant");
4823 /* save all registers */
4824 save_regs(0);
4825 /* statement expression : we do not accept break/continue
4826 inside as GCC does. We do retain the nocode_wanted state,
4827 as statement expressions can't ever be entered from the
4828 outside, so any reactivation of code emission (from labels
4829 or loop heads) can be disabled again after the end of it. */
4830 block(NULL, NULL, 1);
4831 nocode_wanted = saved_nocode_wanted;
4832 skip(')');
4833 } else {
4834 gexpr();
4835 skip(')');
4837 break;
4838 case '*':
4839 next();
4840 unary();
4841 indir();
4842 break;
4843 case '&':
4844 next();
4845 unary();
4846 /* functions names must be treated as function pointers,
4847 except for unary '&' and sizeof. Since we consider that
4848 functions are not lvalues, we only have to handle it
4849 there and in function calls. */
4850 /* arrays can also be used although they are not lvalues */
4851 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
4852 !(vtop->type.t & VT_ARRAY))
4853 test_lvalue();
4854 mk_pointer(&vtop->type);
4855 gaddrof();
4856 break;
4857 case '!':
4858 next();
4859 unary();
4860 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4861 gen_cast_s(VT_BOOL);
4862 vtop->c.i = !vtop->c.i;
4863 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
4864 vtop->c.i ^= 1;
4865 else {
4866 save_regs(1);
4867 vseti(VT_JMP, gvtst(1, 0));
4869 break;
4870 case '~':
4871 next();
4872 unary();
4873 vpushi(-1);
4874 gen_op('^');
4875 break;
4876 case '+':
4877 next();
4878 unary();
4879 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
4880 tcc_error("pointer not accepted for unary plus");
4881 /* In order to force cast, we add zero, except for floating point
4882 where we really need an noop (otherwise -0.0 will be transformed
4883 into +0.0). */
4884 if (!is_float(vtop->type.t)) {
4885 vpushi(0);
4886 gen_op('+');
4888 break;
4889 case TOK_SIZEOF:
4890 case TOK_ALIGNOF1:
4891 case TOK_ALIGNOF2:
4892 case TOK_ALIGNOF3:
4893 t = tok;
4894 next();
4895 in_sizeof++;
4896 expr_type(&type, unary); /* Perform a in_sizeof = 0; */
4897 s = vtop[1].sym; /* hack: accessing previous vtop */
4898 size = type_size(&type, &align);
4899 if (s && s->a.aligned)
4900 align = 1 << (s->a.aligned - 1);
4901 if (t == TOK_SIZEOF) {
4902 if (!(type.t & VT_VLA)) {
4903 if (size < 0)
4904 tcc_error("sizeof applied to an incomplete type");
4905 vpushs(size);
4906 } else {
4907 vla_runtime_type_size(&type, &align);
4909 } else {
4910 vpushs(align);
4912 vtop->type.t |= VT_UNSIGNED;
4913 break;
4915 case TOK_builtin_expect:
4916 /* __builtin_expect is a no-op for now */
4917 parse_builtin_params(0, "ee");
4918 vpop();
4919 break;
4920 case TOK_builtin_types_compatible_p:
4921 parse_builtin_params(0, "tt");
4922 vtop[-1].type.t &= ~(VT_CONSTANT | VT_VOLATILE);
4923 vtop[0].type.t &= ~(VT_CONSTANT | VT_VOLATILE);
4924 n = is_compatible_types(&vtop[-1].type, &vtop[0].type);
4925 vtop -= 2;
4926 vpushi(n);
4927 break;
4928 case TOK_builtin_choose_expr:
4930 int64_t c;
4931 next();
4932 skip('(');
4933 c = expr_const64();
4934 skip(',');
4935 if (!c) {
4936 nocode_wanted++;
4938 expr_eq();
4939 if (!c) {
4940 vpop();
4941 nocode_wanted--;
4943 skip(',');
4944 if (c) {
4945 nocode_wanted++;
4947 expr_eq();
4948 if (c) {
4949 vpop();
4950 nocode_wanted--;
4952 skip(')');
4954 break;
4955 case TOK_builtin_constant_p:
4956 parse_builtin_params(1, "e");
4957 n = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
4958 vtop--;
4959 vpushi(n);
4960 break;
4961 case TOK_builtin_frame_address:
4962 case TOK_builtin_return_address:
4964 int tok1 = tok;
4965 int level;
4966 next();
4967 skip('(');
4968 if (tok != TOK_CINT) {
4969 tcc_error("%s only takes positive integers",
4970 tok1 == TOK_builtin_return_address ?
4971 "__builtin_return_address" :
4972 "__builtin_frame_address");
4974 level = (uint32_t)tokc.i;
4975 next();
4976 skip(')');
4977 type.t = VT_VOID;
4978 mk_pointer(&type);
4979 vset(&type, VT_LOCAL, 0); /* local frame */
4980 while (level--) {
4981 mk_pointer(&vtop->type);
4982 indir(); /* -> parent frame */
4984 if (tok1 == TOK_builtin_return_address) {
4985 // assume return address is just above frame pointer on stack
4986 vpushi(PTR_SIZE);
4987 gen_op('+');
4988 mk_pointer(&vtop->type);
4989 indir();
4992 break;
4993 #ifdef TCC_TARGET_X86_64
4994 #ifdef TCC_TARGET_PE
4995 case TOK_builtin_va_start:
4996 parse_builtin_params(0, "ee");
4997 r = vtop->r & VT_VALMASK;
4998 if (r == VT_LLOCAL)
4999 r = VT_LOCAL;
5000 if (r != VT_LOCAL)
5001 tcc_error("__builtin_va_start expects a local variable");
5002 vtop->r = r;
5003 vtop->type = char_pointer_type;
5004 vtop->c.i += 8;
5005 vstore();
5006 break;
5007 #else
5008 case TOK_builtin_va_arg_types:
5009 parse_builtin_params(0, "t");
5010 vpushi(classify_x86_64_va_arg(&vtop->type));
5011 vswap();
5012 vpop();
5013 break;
5014 #endif
5015 #endif
5017 #ifdef TCC_TARGET_ARM64
5018 case TOK___va_start: {
5019 parse_builtin_params(0, "ee");
5020 //xx check types
5021 gen_va_start();
5022 vpushi(0);
5023 vtop->type.t = VT_VOID;
5024 break;
5026 case TOK___va_arg: {
5027 parse_builtin_params(0, "et");
5028 type = vtop->type;
5029 vpop();
5030 //xx check types
5031 gen_va_arg(&type);
5032 vtop->type = type;
5033 break;
5035 case TOK___arm64_clear_cache: {
5036 parse_builtin_params(0, "ee");
5037 gen_clear_cache();
5038 vpushi(0);
5039 vtop->type.t = VT_VOID;
5040 break;
5042 #endif
5043 /* pre operations */
5044 case TOK_INC:
5045 case TOK_DEC:
5046 t = tok;
5047 next();
5048 unary();
5049 inc(0, t);
5050 break;
5051 case '-':
5052 next();
5053 unary();
5054 t = vtop->type.t & VT_BTYPE;
5055 if (is_float(t)) {
5056 /* In IEEE negate(x) isn't subtract(0,x), but rather
5057 subtract(-0, x). */
5058 vpush(&vtop->type);
5059 if (t == VT_FLOAT)
5060 vtop->c.f = -1.0 * 0.0;
5061 else if (t == VT_DOUBLE)
5062 vtop->c.d = -1.0 * 0.0;
5063 else
5064 vtop->c.ld = -1.0 * 0.0;
5065 } else
5066 vpushi(0);
5067 vswap();
5068 gen_op('-');
5069 break;
5070 case TOK_LAND:
5071 if (!gnu_ext)
5072 goto tok_identifier;
5073 next();
5074 /* allow to take the address of a label */
5075 if (tok < TOK_UIDENT)
5076 expect("label identifier");
5077 s = label_find(tok);
5078 if (!s) {
5079 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
5080 } else {
5081 if (s->r == LABEL_DECLARED)
5082 s->r = LABEL_FORWARD;
5084 if (!s->type.t) {
5085 s->type.t = VT_VOID;
5086 mk_pointer(&s->type);
5087 s->type.t |= VT_STATIC;
5089 vpushsym(&s->type, s);
5090 next();
5091 break;
5093 case TOK_GENERIC:
5095 CType controlling_type;
5096 int has_default = 0;
5097 int has_match = 0;
5098 int learn = 0;
5099 TokenString *str = NULL;
5100 int saved_const_wanted = const_wanted;
5102 next();
5103 skip('(');
5104 const_wanted = 0;
5105 expr_type(&controlling_type, expr_eq);
5106 controlling_type.t &= ~(VT_CONSTANT | VT_VOLATILE | VT_ARRAY);
5107 if ((controlling_type.t & VT_BTYPE) == VT_FUNC)
5108 mk_pointer(&controlling_type);
5109 const_wanted = saved_const_wanted;
5110 for (;;) {
5111 learn = 0;
5112 skip(',');
5113 if (tok == TOK_DEFAULT) {
5114 if (has_default)
5115 tcc_error("too many 'default'");
5116 has_default = 1;
5117 if (!has_match)
5118 learn = 1;
5119 next();
5120 } else {
5121 AttributeDef ad_tmp;
5122 int itmp;
5123 CType cur_type;
5124 parse_btype(&cur_type, &ad_tmp);
5125 type_decl(&cur_type, &ad_tmp, &itmp, TYPE_ABSTRACT);
5126 if (compare_types(&controlling_type, &cur_type, 0)) {
5127 if (has_match) {
5128 tcc_error("type match twice");
5130 has_match = 1;
5131 learn = 1;
5134 skip(':');
5135 if (learn) {
5136 if (str)
5137 tok_str_free(str);
5138 skip_or_save_block(&str);
5139 } else {
5140 skip_or_save_block(NULL);
5142 if (tok == ')')
5143 break;
5145 if (!str) {
5146 char buf[60];
5147 type_to_str(buf, sizeof buf, &controlling_type, NULL);
5148 tcc_error("type '%s' does not match any association", buf);
5150 begin_macro(str, 1);
5151 next();
5152 expr_eq();
5153 if (tok != TOK_EOF)
5154 expect(",");
5155 end_macro();
5156 next();
5157 break;
5159 // special qnan , snan and infinity values
5160 case TOK___NAN__:
5161 n = 0x7fc00000;
5162 special_math_val:
5163 vpushi(n);
5164 vtop->type.t = VT_FLOAT;
5165 next();
5166 break;
5167 case TOK___SNAN__:
5168 n = 0x7f800001;
5169 goto special_math_val;
5170 case TOK___INF__:
5171 n = 0x7f800000;
5172 goto special_math_val;
5174 default:
5175 tok_identifier:
5176 t = tok;
5177 next();
5178 if (t < TOK_UIDENT)
5179 expect("identifier");
5180 s = sym_find(t);
5181 if (!s || IS_ASM_SYM(s)) {
5182 const char *name = get_tok_str(t, NULL);
5183 if (tok != '(')
5184 tcc_error("'%s' undeclared", name);
5185 /* for simple function calls, we tolerate undeclared
5186 external reference to int() function */
5187 if (tcc_state->warn_implicit_function_declaration
5188 #ifdef TCC_TARGET_PE
5189 /* people must be warned about using undeclared WINAPI functions
5190 (which usually start with uppercase letter) */
5191 || (name[0] >= 'A' && name[0] <= 'Z')
5192 #endif
5194 tcc_warning("implicit declaration of function '%s'", name);
5195 s = external_global_sym(t, &func_old_type, 0);
5198 r = s->r;
5199 /* A symbol that has a register is a local register variable,
5200 which starts out as VT_LOCAL value. */
5201 if ((r & VT_VALMASK) < VT_CONST)
5202 r = (r & ~VT_VALMASK) | VT_LOCAL;
5204 vset(&s->type, r, s->c);
5205 /* Point to s as backpointer (even without r&VT_SYM).
5206 Will be used by at least the x86 inline asm parser for
5207 regvars. */
5208 vtop->sym = s;
5210 if (r & VT_SYM) {
5211 vtop->c.i = 0;
5212 } else if (r == VT_CONST && IS_ENUM_VAL(s->type.t)) {
5213 vtop->c.i = s->enum_val;
5215 break;
5218 /* post operations */
5219 while (1) {
5220 if (tok == TOK_INC || tok == TOK_DEC) {
5221 inc(1, tok);
5222 next();
5223 } else if (tok == '.' || tok == TOK_ARROW || tok == TOK_CDOUBLE) {
5224 int qualifiers;
5225 /* field */
5226 if (tok == TOK_ARROW)
5227 indir();
5228 qualifiers = vtop->type.t & (VT_CONSTANT | VT_VOLATILE);
5229 test_lvalue();
5230 gaddrof();
5231 /* expect pointer on structure */
5232 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
5233 expect("struct or union");
5234 if (tok == TOK_CDOUBLE)
5235 expect("field name");
5236 next();
5237 if (tok == TOK_CINT || tok == TOK_CUINT)
5238 expect("field name");
5239 s = find_field(&vtop->type, tok);
5240 if (!s)
5241 tcc_error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, &tokc));
5242 /* add field offset to pointer */
5243 vtop->type = char_pointer_type; /* change type to 'char *' */
5244 vpushi(s->c);
5245 gen_op('+');
5246 /* change type to field type, and set to lvalue */
5247 vtop->type = s->type;
5248 vtop->type.t |= qualifiers;
5249 /* an array is never an lvalue */
5250 if (!(vtop->type.t & VT_ARRAY)) {
5251 vtop->r |= lvalue_type(vtop->type.t);
5252 #ifdef CONFIG_TCC_BCHECK
5253 /* if bound checking, the referenced pointer must be checked */
5254 if (tcc_state->do_bounds_check && (vtop->r & VT_VALMASK) != VT_LOCAL)
5255 vtop->r |= VT_MUSTBOUND;
5256 #endif
5258 next();
5259 } else if (tok == '[') {
5260 next();
5261 gexpr();
5262 gen_op('+');
5263 indir();
5264 skip(']');
5265 } else if (tok == '(') {
5266 SValue ret;
5267 Sym *sa;
5268 int nb_args, ret_nregs, ret_align, regsize, variadic;
5270 /* function call */
5271 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
5272 /* pointer test (no array accepted) */
5273 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
5274 vtop->type = *pointed_type(&vtop->type);
5275 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
5276 goto error_func;
5277 } else {
5278 error_func:
5279 expect("function pointer");
5281 } else {
5282 vtop->r &= ~VT_LVAL; /* no lvalue */
5284 /* get return type */
5285 s = vtop->type.ref;
5286 next();
5287 sa = s->next; /* first parameter */
5288 nb_args = regsize = 0;
5289 ret.r2 = VT_CONST;
5290 /* compute first implicit argument if a structure is returned */
5291 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
5292 variadic = (s->f.func_type == FUNC_ELLIPSIS);
5293 ret_nregs = gfunc_sret(&s->type, variadic, &ret.type,
5294 &ret_align, &regsize);
5295 if (!ret_nregs) {
5296 /* get some space for the returned structure */
5297 size = type_size(&s->type, &align);
5298 #ifdef TCC_TARGET_ARM64
5299 /* On arm64, a small struct is return in registers.
5300 It is much easier to write it to memory if we know
5301 that we are allowed to write some extra bytes, so
5302 round the allocated space up to a power of 2: */
5303 if (size < 16)
5304 while (size & (size - 1))
5305 size = (size | (size - 1)) + 1;
5306 #endif
5307 loc = (loc - size) & -align;
5308 ret.type = s->type;
5309 ret.r = VT_LOCAL | VT_LVAL;
5310 /* pass it as 'int' to avoid structure arg passing
5311 problems */
5312 vseti(VT_LOCAL, loc);
5313 ret.c = vtop->c;
5314 nb_args++;
5316 } else {
5317 ret_nregs = 1;
5318 ret.type = s->type;
5321 if (ret_nregs) {
5322 /* return in register */
5323 if (is_float(ret.type.t)) {
5324 ret.r = reg_fret(ret.type.t);
5325 #ifdef TCC_TARGET_X86_64
5326 if ((ret.type.t & VT_BTYPE) == VT_QFLOAT)
5327 ret.r2 = REG_QRET;
5328 #endif
5329 } else {
5330 #ifndef TCC_TARGET_ARM64
5331 #ifdef TCC_TARGET_X86_64
5332 if ((ret.type.t & VT_BTYPE) == VT_QLONG)
5333 #else
5334 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
5335 #endif
5336 ret.r2 = REG_LRET;
5337 #endif
5338 ret.r = REG_IRET;
5340 ret.c.i = 0;
5342 if (tok != ')') {
5343 for(;;) {
5344 expr_eq();
5345 gfunc_param_typed(s, sa);
5346 nb_args++;
5347 if (sa)
5348 sa = sa->next;
5349 if (tok == ')')
5350 break;
5351 skip(',');
5354 if (sa)
5355 tcc_error("too few arguments to function");
5356 skip(')');
5357 gfunc_call(nb_args);
5359 /* return value */
5360 for (r = ret.r + ret_nregs + !ret_nregs; r-- > ret.r;) {
5361 vsetc(&ret.type, r, &ret.c);
5362 vtop->r2 = ret.r2; /* Loop only happens when r2 is VT_CONST */
5365 /* handle packed struct return */
5366 if (((s->type.t & VT_BTYPE) == VT_STRUCT) && ret_nregs) {
5367 int addr, offset;
5369 size = type_size(&s->type, &align);
5370 /* We're writing whole regs often, make sure there's enough
5371 space. Assume register size is power of 2. */
5372 if (regsize > align)
5373 align = regsize;
5374 loc = (loc - size) & -align;
5375 addr = loc;
5376 offset = 0;
5377 for (;;) {
5378 vset(&ret.type, VT_LOCAL | VT_LVAL, addr + offset);
5379 vswap();
5380 vstore();
5381 vtop--;
5382 if (--ret_nregs == 0)
5383 break;
5384 offset += regsize;
5386 vset(&s->type, VT_LOCAL | VT_LVAL, addr);
5388 } else {
5389 break;
5394 ST_FUNC void expr_prod(void)
5396 int t;
5398 unary();
5399 while (tok == '*' || tok == '/' || tok == '%') {
5400 t = tok;
5401 next();
5402 unary();
5403 gen_op(t);
5407 ST_FUNC void expr_sum(void)
5409 int t;
5411 expr_prod();
5412 while (tok == '+' || tok == '-') {
5413 t = tok;
5414 next();
5415 expr_prod();
5416 gen_op(t);
5420 static void expr_shift(void)
5422 int t;
5424 expr_sum();
5425 while (tok == TOK_SHL || tok == TOK_SAR) {
5426 t = tok;
5427 next();
5428 expr_sum();
5429 gen_op(t);
5433 static void expr_cmp(void)
5435 int t;
5437 expr_shift();
5438 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
5439 tok == TOK_ULT || tok == TOK_UGE) {
5440 t = tok;
5441 next();
5442 expr_shift();
5443 gen_op(t);
5447 static void expr_cmpeq(void)
5449 int t;
5451 expr_cmp();
5452 while (tok == TOK_EQ || tok == TOK_NE) {
5453 t = tok;
5454 next();
5455 expr_cmp();
5456 gen_op(t);
5460 static void expr_and(void)
5462 expr_cmpeq();
5463 while (tok == '&') {
5464 next();
5465 expr_cmpeq();
5466 gen_op('&');
5470 static void expr_xor(void)
5472 expr_and();
5473 while (tok == '^') {
5474 next();
5475 expr_and();
5476 gen_op('^');
5480 static void expr_or(void)
5482 expr_xor();
5483 while (tok == '|') {
5484 next();
5485 expr_xor();
5486 gen_op('|');
5490 static void expr_land(void)
5492 expr_or();
5493 if (tok == TOK_LAND) {
5494 int t = 0;
5495 for(;;) {
5496 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
5497 gen_cast_s(VT_BOOL);
5498 if (vtop->c.i) {
5499 vpop();
5500 } else {
5501 nocode_wanted++;
5502 while (tok == TOK_LAND) {
5503 next();
5504 expr_or();
5505 vpop();
5507 nocode_wanted--;
5508 if (t)
5509 gsym(t);
5510 gen_cast_s(VT_INT);
5511 break;
5513 } else {
5514 if (!t)
5515 save_regs(1);
5516 t = gvtst(1, t);
5518 if (tok != TOK_LAND) {
5519 if (t)
5520 vseti(VT_JMPI, t);
5521 else
5522 vpushi(1);
5523 break;
5525 next();
5526 expr_or();
5531 static void expr_lor(void)
5533 expr_land();
5534 if (tok == TOK_LOR) {
5535 int t = 0;
5536 for(;;) {
5537 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
5538 gen_cast_s(VT_BOOL);
5539 if (!vtop->c.i) {
5540 vpop();
5541 } else {
5542 nocode_wanted++;
5543 while (tok == TOK_LOR) {
5544 next();
5545 expr_land();
5546 vpop();
5548 nocode_wanted--;
5549 if (t)
5550 gsym(t);
5551 gen_cast_s(VT_INT);
5552 break;
5554 } else {
5555 if (!t)
5556 save_regs(1);
5557 t = gvtst(0, t);
5559 if (tok != TOK_LOR) {
5560 if (t)
5561 vseti(VT_JMP, t);
5562 else
5563 vpushi(0);
5564 break;
5566 next();
5567 expr_land();
5572 /* Assuming vtop is a value used in a conditional context
5573 (i.e. compared with zero) return 0 if it's false, 1 if
5574 true and -1 if it can't be statically determined. */
5575 static int condition_3way(void)
5577 int c = -1;
5578 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST &&
5579 (!(vtop->r & VT_SYM) || !vtop->sym->a.weak)) {
5580 vdup();
5581 gen_cast_s(VT_BOOL);
5582 c = vtop->c.i;
5583 vpop();
5585 return c;
5588 static void expr_cond(void)
5590 int tt, u, r1, r2, rc, t1, t2, bt1, bt2, islv, c, g;
5591 SValue sv;
5592 CType type, type1, type2;
5594 expr_lor();
5595 if (tok == '?') {
5596 next();
5597 c = condition_3way();
5598 g = (tok == ':' && gnu_ext);
5599 if (c < 0) {
5600 /* needed to avoid having different registers saved in
5601 each branch */
5602 if (is_float(vtop->type.t)) {
5603 rc = RC_FLOAT;
5604 #ifdef TCC_TARGET_X86_64
5605 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
5606 rc = RC_ST0;
5608 #endif
5609 } else
5610 rc = RC_INT;
5611 gv(rc);
5612 save_regs(1);
5613 if (g)
5614 gv_dup();
5615 tt = gvtst(1, 0);
5617 } else {
5618 if (!g)
5619 vpop();
5620 tt = 0;
5623 if (1) {
5624 if (c == 0)
5625 nocode_wanted++;
5626 if (!g)
5627 gexpr();
5629 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
5630 mk_pointer(&vtop->type);
5631 type1 = vtop->type;
5632 sv = *vtop; /* save value to handle it later */
5633 vtop--; /* no vpop so that FP stack is not flushed */
5634 skip(':');
5636 u = 0;
5637 if (c < 0)
5638 u = gjmp(0);
5639 gsym(tt);
5641 if (c == 0)
5642 nocode_wanted--;
5643 if (c == 1)
5644 nocode_wanted++;
5645 expr_cond();
5646 if (c == 1)
5647 nocode_wanted--;
5649 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
5650 mk_pointer(&vtop->type);
5651 type2=vtop->type;
5652 t1 = type1.t;
5653 bt1 = t1 & VT_BTYPE;
5654 t2 = type2.t;
5655 bt2 = t2 & VT_BTYPE;
5656 type.ref = NULL;
5659 /* cast operands to correct type according to ISOC rules */
5660 if (bt1 == VT_VOID || bt2 == VT_VOID) {
5661 type.t = VT_VOID; /* NOTE: as an extension, we accept void on only one side */
5662 } else if (is_float(bt1) || is_float(bt2)) {
5663 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
5664 type.t = VT_LDOUBLE;
5666 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
5667 type.t = VT_DOUBLE;
5668 } else {
5669 type.t = VT_FLOAT;
5671 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
5672 /* cast to biggest op */
5673 type.t = VT_LLONG | VT_LONG;
5674 if (bt1 == VT_LLONG)
5675 type.t &= t1;
5676 if (bt2 == VT_LLONG)
5677 type.t &= t2;
5678 /* convert to unsigned if it does not fit in a long long */
5679 if ((t1 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_LLONG | VT_UNSIGNED) ||
5680 (t2 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_LLONG | VT_UNSIGNED))
5681 type.t |= VT_UNSIGNED;
5682 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
5683 /* http://port70.net/~nsz/c/c99/n1256.html#6.5.15p6 */
5684 /* If one is a null ptr constant the result type
5685 is the other. */
5686 if (is_null_pointer (vtop)) type = type1;
5687 else if (is_null_pointer (&sv)) type = type2;
5688 else if (bt1 != bt2)
5689 tcc_error("incompatible types in conditional expressions");
5690 else {
5691 CType *pt1 = pointed_type(&type1);
5692 CType *pt2 = pointed_type(&type2);
5693 int pbt1 = pt1->t & VT_BTYPE;
5694 int pbt2 = pt2->t & VT_BTYPE;
5695 int newquals, copied = 0;
5696 /* pointers to void get preferred, otherwise the
5697 pointed to types minus qualifs should be compatible */
5698 type = (pbt1 == VT_VOID) ? type1 : type2;
5699 if (pbt1 != VT_VOID && pbt2 != VT_VOID) {
5700 if(!compare_types(pt1, pt2, 1/*unqualif*/))
5701 tcc_warning("pointer type mismatch in conditional expression\n");
5703 /* combine qualifs */
5704 newquals = ((pt1->t | pt2->t) & (VT_CONSTANT | VT_VOLATILE));
5705 if ((~pointed_type(&type)->t & (VT_CONSTANT | VT_VOLATILE))
5706 & newquals)
5708 /* copy the pointer target symbol */
5709 type.ref = sym_push(SYM_FIELD, &type.ref->type,
5710 0, type.ref->c);
5711 copied = 1;
5712 pointed_type(&type)->t |= newquals;
5714 /* pointers to incomplete arrays get converted to
5715 pointers to completed ones if possible */
5716 if (pt1->t & VT_ARRAY
5717 && pt2->t & VT_ARRAY
5718 && pointed_type(&type)->ref->c < 0
5719 && (pt1->ref->c > 0 || pt2->ref->c > 0))
5721 if (!copied)
5722 type.ref = sym_push(SYM_FIELD, &type.ref->type,
5723 0, type.ref->c);
5724 pointed_type(&type)->ref =
5725 sym_push(SYM_FIELD, &pointed_type(&type)->ref->type,
5726 0, pointed_type(&type)->ref->c);
5727 pointed_type(&type)->ref->c =
5728 0 < pt1->ref->c ? pt1->ref->c : pt2->ref->c;
5731 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
5732 /* XXX: test structure compatibility */
5733 type = bt1 == VT_STRUCT ? type1 : type2;
5734 } else {
5735 /* integer operations */
5736 type.t = VT_INT | (VT_LONG & (t1 | t2));
5737 /* convert to unsigned if it does not fit in an integer */
5738 if ((t1 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_INT | VT_UNSIGNED) ||
5739 (t2 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_INT | VT_UNSIGNED))
5740 type.t |= VT_UNSIGNED;
5742 /* keep structs lvalue by transforming `(expr ? a : b)` to `*(expr ? &a : &b)` so
5743 that `(expr ? a : b).mem` does not error with "lvalue expected" */
5744 islv = (vtop->r & VT_LVAL) && (sv.r & VT_LVAL) && VT_STRUCT == (type.t & VT_BTYPE);
5746 /* now we convert second operand */
5747 if (c != 1) {
5748 gen_cast(&type);
5749 if (islv) {
5750 mk_pointer(&vtop->type);
5751 gaddrof();
5752 } else if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
5753 gaddrof();
5756 rc = RC_INT;
5757 if (is_float(type.t)) {
5758 rc = RC_FLOAT;
5759 #ifdef TCC_TARGET_X86_64
5760 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
5761 rc = RC_ST0;
5763 #endif
5764 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
5765 /* for long longs, we use fixed registers to avoid having
5766 to handle a complicated move */
5767 rc = RC_IRET;
5770 tt = r2 = 0;
5771 if (c < 0) {
5772 r2 = gv(rc);
5773 tt = gjmp(0);
5775 gsym(u);
5777 /* this is horrible, but we must also convert first
5778 operand */
5779 if (c != 0) {
5780 *vtop = sv;
5781 gen_cast(&type);
5782 if (islv) {
5783 mk_pointer(&vtop->type);
5784 gaddrof();
5785 } else if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
5786 gaddrof();
5789 if (c < 0 || islv) {
5790 r1 = gv(rc);
5791 move_reg(r2, r1, type.t);
5792 vtop->r = r2;
5793 gsym(tt);
5794 if (islv)
5795 indir();
5801 static void expr_eq(void)
5803 int t;
5805 expr_cond();
5806 if (tok == '=' ||
5807 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
5808 tok == TOK_A_XOR || tok == TOK_A_OR ||
5809 tok == TOK_A_SHL || tok == TOK_A_SAR) {
5810 test_lvalue();
5811 t = tok;
5812 next();
5813 if (t == '=') {
5814 expr_eq();
5815 } else {
5816 vdup();
5817 expr_eq();
5818 gen_op(t & 0x7f);
5820 vstore();
5824 ST_FUNC void gexpr(void)
5826 while (1) {
5827 expr_eq();
5828 if (tok != ',')
5829 break;
5830 vpop();
5831 next();
5835 /* parse a constant expression and return value in vtop. */
5836 static void expr_const1(void)
5838 const_wanted++;
5839 nocode_wanted++;
5840 expr_cond();
5841 nocode_wanted--;
5842 const_wanted--;
5845 /* parse an integer constant and return its value. */
5846 static inline int64_t expr_const64(void)
5848 int64_t c;
5849 expr_const1();
5850 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
5851 expect("constant expression");
5852 c = vtop->c.i;
5853 vpop();
5854 return c;
5857 /* parse an integer constant and return its value.
5858 Complain if it doesn't fit 32bit (signed or unsigned). */
5859 ST_FUNC int expr_const(void)
5861 int c;
5862 int64_t wc = expr_const64();
5863 c = wc;
5864 if (c != wc && (unsigned)c != wc)
5865 tcc_error("constant exceeds 32 bit");
5866 return c;
5869 /* return the label token if current token is a label, otherwise
5870 return zero */
5871 static int is_label(void)
5873 int last_tok;
5875 /* fast test first */
5876 if (tok < TOK_UIDENT)
5877 return 0;
5878 /* no need to save tokc because tok is an identifier */
5879 last_tok = tok;
5880 next();
5881 if (tok == ':') {
5882 return last_tok;
5883 } else {
5884 unget_tok(last_tok);
5885 return 0;
5889 #ifndef TCC_TARGET_ARM64
5890 static void gfunc_return(CType *func_type)
5892 if ((func_type->t & VT_BTYPE) == VT_STRUCT) {
5893 CType type, ret_type;
5894 int ret_align, ret_nregs, regsize;
5895 ret_nregs = gfunc_sret(func_type, func_var, &ret_type,
5896 &ret_align, &regsize);
5897 if (0 == ret_nregs) {
5898 /* if returning structure, must copy it to implicit
5899 first pointer arg location */
5900 type = *func_type;
5901 mk_pointer(&type);
5902 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
5903 indir();
5904 vswap();
5905 /* copy structure value to pointer */
5906 vstore();
5907 } else {
5908 /* returning structure packed into registers */
5909 int r, size, addr, align;
5910 size = type_size(func_type,&align);
5911 if ((vtop->r != (VT_LOCAL | VT_LVAL) ||
5912 (vtop->c.i & (ret_align-1)))
5913 && (align & (ret_align-1))) {
5914 loc = (loc - size) & -ret_align;
5915 addr = loc;
5916 type = *func_type;
5917 vset(&type, VT_LOCAL | VT_LVAL, addr);
5918 vswap();
5919 vstore();
5920 vpop();
5921 vset(&ret_type, VT_LOCAL | VT_LVAL, addr);
5923 vtop->type = ret_type;
5924 if (is_float(ret_type.t))
5925 r = rc_fret(ret_type.t);
5926 else
5927 r = RC_IRET;
5929 if (ret_nregs == 1)
5930 gv(r);
5931 else {
5932 for (;;) {
5933 vdup();
5934 gv(r);
5935 vpop();
5936 if (--ret_nregs == 0)
5937 break;
5938 /* We assume that when a structure is returned in multiple
5939 registers, their classes are consecutive values of the
5940 suite s(n) = 2^n */
5941 r <<= 1;
5942 vtop->c.i += regsize;
5946 } else if (is_float(func_type->t)) {
5947 gv(rc_fret(func_type->t));
5948 } else {
5949 gv(RC_IRET);
5951 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
5953 #endif
5955 static int case_cmp(const void *pa, const void *pb)
5957 int64_t a = (*(struct case_t**) pa)->v1;
5958 int64_t b = (*(struct case_t**) pb)->v1;
5959 return a < b ? -1 : a > b;
5962 static void gcase(struct case_t **base, int len, int *bsym)
5964 struct case_t *p;
5965 int e;
5966 int ll = (vtop->type.t & VT_BTYPE) == VT_LLONG;
5967 gv(RC_INT);
5968 while (len > 4) {
5969 /* binary search */
5970 p = base[len/2];
5971 vdup();
5972 if (ll)
5973 vpushll(p->v2);
5974 else
5975 vpushi(p->v2);
5976 gen_op(TOK_LE);
5977 e = gtst(1, 0);
5978 vdup();
5979 if (ll)
5980 vpushll(p->v1);
5981 else
5982 vpushi(p->v1);
5983 gen_op(TOK_GE);
5984 gtst_addr(0, p->sym); /* v1 <= x <= v2 */
5985 /* x < v1 */
5986 gcase(base, len/2, bsym);
5987 if (cur_switch->def_sym)
5988 gjmp_addr(cur_switch->def_sym);
5989 else
5990 *bsym = gjmp(*bsym);
5991 /* x > v2 */
5992 gsym(e);
5993 e = len/2 + 1;
5994 base += e; len -= e;
5996 /* linear scan */
5997 while (len--) {
5998 p = *base++;
5999 vdup();
6000 if (ll)
6001 vpushll(p->v2);
6002 else
6003 vpushi(p->v2);
6004 if (p->v1 == p->v2) {
6005 gen_op(TOK_EQ);
6006 gtst_addr(0, p->sym);
6007 } else {
6008 gen_op(TOK_LE);
6009 e = gtst(1, 0);
6010 vdup();
6011 if (ll)
6012 vpushll(p->v1);
6013 else
6014 vpushi(p->v1);
6015 gen_op(TOK_GE);
6016 gtst_addr(0, p->sym);
6017 gsym(e);
6022 static void block(int *bsym, int *csym, int is_expr)
6024 int a, b, c, d, cond;
6025 Sym *s;
6027 /* generate line number info */
6028 if (tcc_state->do_debug)
6029 tcc_debug_line(tcc_state);
6031 if (is_expr) {
6032 /* default return value is (void) */
6033 vpushi(0);
6034 vtop->type.t = VT_VOID;
6037 if (tok == TOK_IF) {
6038 /* if test */
6039 int saved_nocode_wanted = nocode_wanted;
6040 next();
6041 skip('(');
6042 gexpr();
6043 skip(')');
6044 cond = condition_3way();
6045 if (cond == 1)
6046 a = 0, vpop();
6047 else
6048 a = gvtst(1, 0);
6049 if (cond == 0)
6050 nocode_wanted |= 0x20000000;
6051 block(bsym, csym, 0);
6052 if (cond != 1)
6053 nocode_wanted = saved_nocode_wanted;
6054 c = tok;
6055 if (c == TOK_ELSE) {
6056 next();
6057 d = gjmp(0);
6058 gsym(a);
6059 if (cond == 1)
6060 nocode_wanted |= 0x20000000;
6061 block(bsym, csym, 0);
6062 gsym(d); /* patch else jmp */
6063 if (cond != 0)
6064 nocode_wanted = saved_nocode_wanted;
6065 } else
6066 gsym(a);
6067 } else if (tok == TOK_WHILE) {
6068 int saved_nocode_wanted;
6069 nocode_wanted &= ~0x20000000;
6070 next();
6071 d = ind;
6072 vla_sp_restore();
6073 skip('(');
6074 gexpr();
6075 skip(')');
6076 a = gvtst(1, 0);
6077 b = 0;
6078 ++local_scope;
6079 saved_nocode_wanted = nocode_wanted;
6080 block(&a, &b, 0);
6081 nocode_wanted = saved_nocode_wanted;
6082 --local_scope;
6083 gjmp_addr(d);
6084 gsym(a);
6085 gsym_addr(b, d);
6086 } else if (tok == '{') {
6087 Sym *llabel;
6088 int block_vla_sp_loc = vla_sp_loc, saved_vlas_in_scope = vlas_in_scope;
6090 next();
6091 /* record local declaration stack position */
6092 s = local_stack;
6093 llabel = local_label_stack;
6094 ++local_scope;
6096 /* handle local labels declarations */
6097 while (tok == TOK_LABEL) {
6098 next();
6099 for(;;) {
6100 if (tok < TOK_UIDENT)
6101 expect("label identifier");
6102 label_push(&local_label_stack, tok, LABEL_DECLARED);
6103 next();
6104 if (tok == ',') {
6105 next();
6106 } else {
6107 skip(';');
6108 break;
6112 while (tok != '}') {
6113 if ((a = is_label()))
6114 unget_tok(a);
6115 else
6116 decl(VT_LOCAL);
6117 if (tok != '}') {
6118 if (is_expr)
6119 vpop();
6120 block(bsym, csym, is_expr);
6123 /* pop locally defined labels */
6124 label_pop(&local_label_stack, llabel, is_expr);
6125 /* pop locally defined symbols */
6126 --local_scope;
6127 /* In the is_expr case (a statement expression is finished here),
6128 vtop might refer to symbols on the local_stack. Either via the
6129 type or via vtop->sym. We can't pop those nor any that in turn
6130 might be referred to. To make it easier we don't roll back
6131 any symbols in that case; some upper level call to block() will
6132 do that. We do have to remove such symbols from the lookup
6133 tables, though. sym_pop will do that. */
6134 sym_pop(&local_stack, s, is_expr);
6136 /* Pop VLA frames and restore stack pointer if required */
6137 if (vlas_in_scope > saved_vlas_in_scope) {
6138 vla_sp_loc = saved_vlas_in_scope ? block_vla_sp_loc : vla_sp_root_loc;
6139 vla_sp_restore();
6141 vlas_in_scope = saved_vlas_in_scope;
6143 next();
6144 } else if (tok == TOK_RETURN) {
6145 next();
6146 if (tok != ';') {
6147 gexpr();
6148 gen_assign_cast(&func_vt);
6149 if ((func_vt.t & VT_BTYPE) == VT_VOID)
6150 vtop--;
6151 else
6152 gfunc_return(&func_vt);
6154 skip(';');
6155 /* jump unless last stmt in top-level block */
6156 if (tok != '}' || local_scope != 1)
6157 rsym = gjmp(rsym);
6158 nocode_wanted |= 0x20000000;
6159 } else if (tok == TOK_BREAK) {
6160 /* compute jump */
6161 if (!bsym)
6162 tcc_error("cannot break");
6163 *bsym = gjmp(*bsym);
6164 next();
6165 skip(';');
6166 nocode_wanted |= 0x20000000;
6167 } else if (tok == TOK_CONTINUE) {
6168 /* compute jump */
6169 if (!csym)
6170 tcc_error("cannot continue");
6171 vla_sp_restore_root();
6172 *csym = gjmp(*csym);
6173 next();
6174 skip(';');
6175 } else if (tok == TOK_FOR) {
6176 int e;
6177 int saved_nocode_wanted;
6178 nocode_wanted &= ~0x20000000;
6179 next();
6180 skip('(');
6181 s = local_stack;
6182 ++local_scope;
6183 if (tok != ';') {
6184 /* c99 for-loop init decl? */
6185 if (!decl0(VT_LOCAL, 1, NULL)) {
6186 /* no, regular for-loop init expr */
6187 gexpr();
6188 vpop();
6191 skip(';');
6192 d = ind;
6193 c = ind;
6194 vla_sp_restore();
6195 a = 0;
6196 b = 0;
6197 if (tok != ';') {
6198 gexpr();
6199 a = gvtst(1, 0);
6201 skip(';');
6202 if (tok != ')') {
6203 e = gjmp(0);
6204 c = ind;
6205 vla_sp_restore();
6206 gexpr();
6207 vpop();
6208 gjmp_addr(d);
6209 gsym(e);
6211 skip(')');
6212 saved_nocode_wanted = nocode_wanted;
6213 block(&a, &b, 0);
6214 nocode_wanted = saved_nocode_wanted;
6215 gjmp_addr(c);
6216 gsym(a);
6217 gsym_addr(b, c);
6218 --local_scope;
6219 sym_pop(&local_stack, s, 0);
6221 } else
6222 if (tok == TOK_DO) {
6223 int saved_nocode_wanted;
6224 nocode_wanted &= ~0x20000000;
6225 next();
6226 a = 0;
6227 b = 0;
6228 d = ind;
6229 vla_sp_restore();
6230 saved_nocode_wanted = nocode_wanted;
6231 block(&a, &b, 0);
6232 skip(TOK_WHILE);
6233 skip('(');
6234 gsym(b);
6235 if (b)
6236 nocode_wanted = saved_nocode_wanted;
6237 gexpr();
6238 c = gvtst(0, 0);
6239 gsym_addr(c, d);
6240 nocode_wanted = saved_nocode_wanted;
6241 skip(')');
6242 gsym(a);
6243 skip(';');
6244 } else
6245 if (tok == TOK_SWITCH) {
6246 struct switch_t *saved, sw;
6247 int saved_nocode_wanted = nocode_wanted;
6248 SValue switchval;
6249 next();
6250 skip('(');
6251 gexpr();
6252 skip(')');
6253 switchval = *vtop--;
6254 a = 0;
6255 b = gjmp(0); /* jump to first case */
6256 sw.p = NULL; sw.n = 0; sw.def_sym = 0;
6257 saved = cur_switch;
6258 cur_switch = &sw;
6259 block(&a, csym, 0);
6260 nocode_wanted = saved_nocode_wanted;
6261 a = gjmp(a); /* add implicit break */
6262 /* case lookup */
6263 gsym(b);
6264 qsort(sw.p, sw.n, sizeof(void*), case_cmp);
6265 for (b = 1; b < sw.n; b++)
6266 if (sw.p[b - 1]->v2 >= sw.p[b]->v1)
6267 tcc_error("duplicate case value");
6268 /* Our switch table sorting is signed, so the compared
6269 value needs to be as well when it's 64bit. */
6270 if ((switchval.type.t & VT_BTYPE) == VT_LLONG)
6271 switchval.type.t &= ~VT_UNSIGNED;
6272 vpushv(&switchval);
6273 gcase(sw.p, sw.n, &a);
6274 vpop();
6275 if (sw.def_sym)
6276 gjmp_addr(sw.def_sym);
6277 dynarray_reset(&sw.p, &sw.n);
6278 cur_switch = saved;
6279 /* break label */
6280 gsym(a);
6281 } else
6282 if (tok == TOK_CASE) {
6283 struct case_t *cr = tcc_malloc(sizeof(struct case_t));
6284 if (!cur_switch)
6285 expect("switch");
6286 nocode_wanted &= ~0x20000000;
6287 next();
6288 cr->v1 = cr->v2 = expr_const64();
6289 if (gnu_ext && tok == TOK_DOTS) {
6290 next();
6291 cr->v2 = expr_const64();
6292 if (cr->v2 < cr->v1)
6293 tcc_warning("empty case range");
6295 cr->sym = ind;
6296 dynarray_add(&cur_switch->p, &cur_switch->n, cr);
6297 skip(':');
6298 is_expr = 0;
6299 goto block_after_label;
6300 } else
6301 if (tok == TOK_DEFAULT) {
6302 next();
6303 skip(':');
6304 if (!cur_switch)
6305 expect("switch");
6306 if (cur_switch->def_sym)
6307 tcc_error("too many 'default'");
6308 cur_switch->def_sym = ind;
6309 is_expr = 0;
6310 goto block_after_label;
6311 } else
6312 if (tok == TOK_GOTO) {
6313 next();
6314 if (tok == '*' && gnu_ext) {
6315 /* computed goto */
6316 next();
6317 gexpr();
6318 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
6319 expect("pointer");
6320 ggoto();
6321 } else if (tok >= TOK_UIDENT) {
6322 s = label_find(tok);
6323 /* put forward definition if needed */
6324 if (!s) {
6325 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
6326 } else {
6327 if (s->r == LABEL_DECLARED)
6328 s->r = LABEL_FORWARD;
6330 vla_sp_restore_root();
6331 if (s->r & LABEL_FORWARD)
6332 s->jnext = gjmp(s->jnext);
6333 else
6334 gjmp_addr(s->jnext);
6335 next();
6336 } else {
6337 expect("label identifier");
6339 skip(';');
6340 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
6341 asm_instr();
6342 } else {
6343 b = is_label();
6344 if (b) {
6345 /* label case */
6346 next();
6347 s = label_find(b);
6348 if (s) {
6349 if (s->r == LABEL_DEFINED)
6350 tcc_error("duplicate label '%s'", get_tok_str(s->v, NULL));
6351 gsym(s->jnext);
6352 s->r = LABEL_DEFINED;
6353 } else {
6354 s = label_push(&global_label_stack, b, LABEL_DEFINED);
6356 s->jnext = ind;
6357 vla_sp_restore();
6358 /* we accept this, but it is a mistake */
6359 block_after_label:
6360 nocode_wanted &= ~0x20000000;
6361 if (tok == '}') {
6362 tcc_warning("deprecated use of label at end of compound statement");
6363 } else {
6364 if (is_expr)
6365 vpop();
6366 block(bsym, csym, is_expr);
6368 } else {
6369 /* expression case */
6370 if (tok != ';') {
6371 if (is_expr) {
6372 vpop();
6373 gexpr();
6374 } else {
6375 gexpr();
6376 vpop();
6379 skip(';');
6384 /* This skips over a stream of tokens containing balanced {} and ()
6385 pairs, stopping at outer ',' ';' and '}' (or matching '}' if we started
6386 with a '{'). If STR then allocates and stores the skipped tokens
6387 in *STR. This doesn't check if () and {} are nested correctly,
6388 i.e. "({)}" is accepted. */
6389 static void skip_or_save_block(TokenString **str)
6391 int braces = tok == '{';
6392 int level = 0;
6393 if (str)
6394 *str = tok_str_alloc();
6396 while ((level > 0 || (tok != '}' && tok != ',' && tok != ';' && tok != ')'))) {
6397 int t;
6398 if (tok == TOK_EOF) {
6399 if (str || level > 0)
6400 tcc_error("unexpected end of file");
6401 else
6402 break;
6404 if (str)
6405 tok_str_add_tok(*str);
6406 t = tok;
6407 next();
6408 if (t == '{' || t == '(') {
6409 level++;
6410 } else if (t == '}' || t == ')') {
6411 level--;
6412 if (level == 0 && braces && t == '}')
6413 break;
6416 if (str) {
6417 tok_str_add(*str, -1);
6418 tok_str_add(*str, 0);
6422 #define EXPR_CONST 1
6423 #define EXPR_ANY 2
6425 static void parse_init_elem(int expr_type)
6427 int saved_global_expr;
6428 switch(expr_type) {
6429 case EXPR_CONST:
6430 /* compound literals must be allocated globally in this case */
6431 saved_global_expr = global_expr;
6432 global_expr = 1;
6433 expr_const1();
6434 global_expr = saved_global_expr;
6435 /* NOTE: symbols are accepted, as well as lvalue for anon symbols
6436 (compound literals). */
6437 if (((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST
6438 && ((vtop->r & (VT_SYM|VT_LVAL)) != (VT_SYM|VT_LVAL)
6439 || vtop->sym->v < SYM_FIRST_ANOM))
6440 #ifdef TCC_TARGET_PE
6441 || ((vtop->r & VT_SYM) && vtop->sym->a.dllimport)
6442 #endif
6444 tcc_error("initializer element is not constant");
6445 break;
6446 case EXPR_ANY:
6447 expr_eq();
6448 break;
6452 /* put zeros for variable based init */
6453 static void init_putz(Section *sec, unsigned long c, int size)
6455 if (sec) {
6456 /* nothing to do because globals are already set to zero */
6457 } else {
6458 vpush_global_sym(&func_old_type, TOK_memset);
6459 vseti(VT_LOCAL, c);
6460 #ifdef TCC_TARGET_ARM
6461 vpushs(size);
6462 vpushi(0);
6463 #else
6464 vpushi(0);
6465 vpushs(size);
6466 #endif
6467 gfunc_call(3);
6471 /* t is the array or struct type. c is the array or struct
6472 address. cur_field is the pointer to the current
6473 field, for arrays the 'c' member contains the current start
6474 index. 'size_only' is true if only size info is needed (only used
6475 in arrays). al contains the already initialized length of the
6476 current container (starting at c). This returns the new length of that. */
6477 static int decl_designator(CType *type, Section *sec, unsigned long c,
6478 Sym **cur_field, int size_only, int al)
6480 Sym *s, *f;
6481 int index, index_last, align, l, nb_elems, elem_size;
6482 unsigned long corig = c;
6484 elem_size = 0;
6485 nb_elems = 1;
6486 if (gnu_ext && (l = is_label()) != 0)
6487 goto struct_field;
6488 /* NOTE: we only support ranges for last designator */
6489 while (nb_elems == 1 && (tok == '[' || tok == '.')) {
6490 if (tok == '[') {
6491 if (!(type->t & VT_ARRAY))
6492 expect("array type");
6493 next();
6494 index = index_last = expr_const();
6495 if (tok == TOK_DOTS && gnu_ext) {
6496 next();
6497 index_last = expr_const();
6499 skip(']');
6500 s = type->ref;
6501 if (index < 0 || (s->c >= 0 && index_last >= s->c) ||
6502 index_last < index)
6503 tcc_error("invalid index");
6504 if (cur_field)
6505 (*cur_field)->c = index_last;
6506 type = pointed_type(type);
6507 elem_size = type_size(type, &align);
6508 c += index * elem_size;
6509 nb_elems = index_last - index + 1;
6510 } else {
6511 next();
6512 l = tok;
6513 struct_field:
6514 next();
6515 if ((type->t & VT_BTYPE) != VT_STRUCT)
6516 expect("struct/union type");
6517 f = find_field(type, l);
6518 if (!f)
6519 expect("field");
6520 if (cur_field)
6521 *cur_field = f;
6522 type = &f->type;
6523 c += f->c;
6525 cur_field = NULL;
6527 if (!cur_field) {
6528 if (tok == '=') {
6529 next();
6530 } else if (!gnu_ext) {
6531 expect("=");
6533 } else {
6534 if (type->t & VT_ARRAY) {
6535 index = (*cur_field)->c;
6536 if (type->ref->c >= 0 && index >= type->ref->c)
6537 tcc_error("index too large");
6538 type = pointed_type(type);
6539 c += index * type_size(type, &align);
6540 } else {
6541 f = *cur_field;
6542 while (f && (f->v & SYM_FIRST_ANOM) && (f->type.t & VT_BITFIELD))
6543 *cur_field = f = f->next;
6544 if (!f)
6545 tcc_error("too many field init");
6546 type = &f->type;
6547 c += f->c;
6550 /* must put zero in holes (note that doing it that way
6551 ensures that it even works with designators) */
6552 if (!size_only && c - corig > al)
6553 init_putz(sec, corig + al, c - corig - al);
6554 decl_initializer(type, sec, c, 0, size_only);
6556 /* XXX: make it more general */
6557 if (!size_only && nb_elems > 1) {
6558 unsigned long c_end;
6559 uint8_t *src, *dst;
6560 int i;
6562 if (!sec) {
6563 vset(type, VT_LOCAL|VT_LVAL, c);
6564 for (i = 1; i < nb_elems; i++) {
6565 vset(type, VT_LOCAL|VT_LVAL, c + elem_size * i);
6566 vswap();
6567 vstore();
6569 vpop();
6570 } else if (!NODATA_WANTED) {
6571 c_end = c + nb_elems * elem_size;
6572 if (c_end > sec->data_allocated)
6573 section_realloc(sec, c_end);
6574 src = sec->data + c;
6575 dst = src;
6576 for(i = 1; i < nb_elems; i++) {
6577 dst += elem_size;
6578 memcpy(dst, src, elem_size);
6582 c += nb_elems * type_size(type, &align);
6583 if (c - corig > al)
6584 al = c - corig;
6585 return al;
6588 /* store a value or an expression directly in global data or in local array */
6589 static void init_putv(CType *type, Section *sec, unsigned long c)
6591 int bt;
6592 void *ptr;
6593 CType dtype;
6595 dtype = *type;
6596 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
6598 if (sec) {
6599 int size, align;
6600 /* XXX: not portable */
6601 /* XXX: generate error if incorrect relocation */
6602 gen_assign_cast(&dtype);
6603 bt = type->t & VT_BTYPE;
6605 if ((vtop->r & VT_SYM)
6606 && bt != VT_PTR
6607 && bt != VT_FUNC
6608 && (bt != (PTR_SIZE == 8 ? VT_LLONG : VT_INT)
6609 || (type->t & VT_BITFIELD))
6610 && !((vtop->r & VT_CONST) && vtop->sym->v >= SYM_FIRST_ANOM)
6612 tcc_error("initializer element is not computable at load time");
6614 if (NODATA_WANTED) {
6615 vtop--;
6616 return;
6619 size = type_size(type, &align);
6620 section_reserve(sec, c + size);
6621 ptr = sec->data + c;
6623 /* XXX: make code faster ? */
6624 if ((vtop->r & (VT_SYM|VT_CONST)) == (VT_SYM|VT_CONST) &&
6625 vtop->sym->v >= SYM_FIRST_ANOM &&
6626 /* XXX This rejects compound literals like
6627 '(void *){ptr}'. The problem is that '&sym' is
6628 represented the same way, which would be ruled out
6629 by the SYM_FIRST_ANOM check above, but also '"string"'
6630 in 'char *p = "string"' is represented the same
6631 with the type being VT_PTR and the symbol being an
6632 anonymous one. That is, there's no difference in vtop
6633 between '(void *){x}' and '&(void *){x}'. Ignore
6634 pointer typed entities here. Hopefully no real code
6635 will every use compound literals with scalar type. */
6636 (vtop->type.t & VT_BTYPE) != VT_PTR) {
6637 /* These come from compound literals, memcpy stuff over. */
6638 Section *ssec;
6639 ElfSym *esym;
6640 ElfW_Rel *rel;
6641 esym = elfsym(vtop->sym);
6642 ssec = tcc_state->sections[esym->st_shndx];
6643 memmove (ptr, ssec->data + esym->st_value, size);
6644 if (ssec->reloc) {
6645 /* We need to copy over all memory contents, and that
6646 includes relocations. Use the fact that relocs are
6647 created it order, so look from the end of relocs
6648 until we hit one before the copied region. */
6649 int num_relocs = ssec->reloc->data_offset / sizeof(*rel);
6650 rel = (ElfW_Rel*)(ssec->reloc->data + ssec->reloc->data_offset);
6651 while (num_relocs--) {
6652 rel--;
6653 if (rel->r_offset >= esym->st_value + size)
6654 continue;
6655 if (rel->r_offset < esym->st_value)
6656 break;
6657 /* Note: if the same fields are initialized multiple
6658 times (possible with designators) then we possibly
6659 add multiple relocations for the same offset here.
6660 That would lead to wrong code, the last reloc needs
6661 to win. We clean this up later after the whole
6662 initializer is parsed. */
6663 put_elf_reloca(symtab_section, sec,
6664 c + rel->r_offset - esym->st_value,
6665 ELFW(R_TYPE)(rel->r_info),
6666 ELFW(R_SYM)(rel->r_info),
6667 #if PTR_SIZE == 8
6668 rel->r_addend
6669 #else
6671 #endif
6675 } else {
6676 if (type->t & VT_BITFIELD) {
6677 int bit_pos, bit_size, bits, n;
6678 unsigned char *p, v, m;
6679 bit_pos = BIT_POS(vtop->type.t);
6680 bit_size = BIT_SIZE(vtop->type.t);
6681 p = (unsigned char*)ptr + (bit_pos >> 3);
6682 bit_pos &= 7, bits = 0;
6683 while (bit_size) {
6684 n = 8 - bit_pos;
6685 if (n > bit_size)
6686 n = bit_size;
6687 v = vtop->c.i >> bits << bit_pos;
6688 m = ((1 << n) - 1) << bit_pos;
6689 *p = (*p & ~m) | (v & m);
6690 bits += n, bit_size -= n, bit_pos = 0, ++p;
6692 } else
6693 switch(bt) {
6694 /* XXX: when cross-compiling we assume that each type has the
6695 same representation on host and target, which is likely to
6696 be wrong in the case of long double */
6697 case VT_BOOL:
6698 vtop->c.i = vtop->c.i != 0;
6699 case VT_BYTE:
6700 *(char *)ptr |= vtop->c.i;
6701 break;
6702 case VT_SHORT:
6703 *(short *)ptr |= vtop->c.i;
6704 break;
6705 case VT_FLOAT:
6706 *(float*)ptr = vtop->c.f;
6707 break;
6708 case VT_DOUBLE:
6709 *(double *)ptr = vtop->c.d;
6710 break;
6711 case VT_LDOUBLE:
6712 #if defined TCC_IS_NATIVE_387
6713 if (sizeof (long double) >= 10) /* zero pad ten-byte LD */
6714 memcpy(ptr, &vtop->c.ld, 10);
6715 #ifdef __TINYC__
6716 else if (sizeof (long double) == sizeof (double))
6717 __asm__("fldl %1\nfstpt %0\n" : "=m" (*ptr) : "m" (vtop->c.ld));
6718 #endif
6719 else if (vtop->c.ld == 0.0)
6721 else
6722 #endif
6723 if (sizeof(long double) == LDOUBLE_SIZE)
6724 *(long double*)ptr = vtop->c.ld;
6725 else if (sizeof(double) == LDOUBLE_SIZE)
6726 *(double *)ptr = (double)vtop->c.ld;
6727 else
6728 tcc_error("can't cross compile long double constants");
6729 break;
6730 #if PTR_SIZE != 8
6731 case VT_LLONG:
6732 *(long long *)ptr |= vtop->c.i;
6733 break;
6734 #else
6735 case VT_LLONG:
6736 #endif
6737 case VT_PTR:
6739 addr_t val = vtop->c.i;
6740 #if PTR_SIZE == 8
6741 if (vtop->r & VT_SYM)
6742 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
6743 else
6744 *(addr_t *)ptr |= val;
6745 #else
6746 if (vtop->r & VT_SYM)
6747 greloc(sec, vtop->sym, c, R_DATA_PTR);
6748 *(addr_t *)ptr |= val;
6749 #endif
6750 break;
6752 default:
6754 int val = vtop->c.i;
6755 #if PTR_SIZE == 8
6756 if (vtop->r & VT_SYM)
6757 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
6758 else
6759 *(int *)ptr |= val;
6760 #else
6761 if (vtop->r & VT_SYM)
6762 greloc(sec, vtop->sym, c, R_DATA_PTR);
6763 *(int *)ptr |= val;
6764 #endif
6765 break;
6769 vtop--;
6770 } else {
6771 vset(&dtype, VT_LOCAL|VT_LVAL, c);
6772 vswap();
6773 vstore();
6774 vpop();
6778 /* 't' contains the type and storage info. 'c' is the offset of the
6779 object in section 'sec'. If 'sec' is NULL, it means stack based
6780 allocation. 'first' is true if array '{' must be read (multi
6781 dimension implicit array init handling). 'size_only' is true if
6782 size only evaluation is wanted (only for arrays). */
6783 static void decl_initializer(CType *type, Section *sec, unsigned long c,
6784 int first, int size_only)
6786 int len, n, no_oblock, nb, i;
6787 int size1, align1;
6788 int have_elem;
6789 Sym *s, *f;
6790 Sym indexsym;
6791 CType *t1;
6793 /* If we currently are at an '}' or ',' we have read an initializer
6794 element in one of our callers, and not yet consumed it. */
6795 have_elem = tok == '}' || tok == ',';
6796 if (!have_elem && tok != '{' &&
6797 /* In case of strings we have special handling for arrays, so
6798 don't consume them as initializer value (which would commit them
6799 to some anonymous symbol). */
6800 tok != TOK_LSTR && tok != TOK_STR &&
6801 !size_only) {
6802 parse_init_elem(!sec ? EXPR_ANY : EXPR_CONST);
6803 have_elem = 1;
6806 if (have_elem &&
6807 !(type->t & VT_ARRAY) &&
6808 /* Use i_c_parameter_t, to strip toplevel qualifiers.
6809 The source type might have VT_CONSTANT set, which is
6810 of course assignable to non-const elements. */
6811 is_compatible_unqualified_types(type, &vtop->type)) {
6812 init_putv(type, sec, c);
6813 } else if (type->t & VT_ARRAY) {
6814 s = type->ref;
6815 n = s->c;
6816 t1 = pointed_type(type);
6817 size1 = type_size(t1, &align1);
6819 no_oblock = 1;
6820 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
6821 tok == '{') {
6822 if (tok != '{')
6823 tcc_error("character array initializer must be a literal,"
6824 " optionally enclosed in braces");
6825 skip('{');
6826 no_oblock = 0;
6829 /* only parse strings here if correct type (otherwise: handle
6830 them as ((w)char *) expressions */
6831 if ((tok == TOK_LSTR &&
6832 #ifdef TCC_TARGET_PE
6833 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
6834 #else
6835 (t1->t & VT_BTYPE) == VT_INT
6836 #endif
6837 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
6838 len = 0;
6839 while (tok == TOK_STR || tok == TOK_LSTR) {
6840 int cstr_len, ch;
6842 /* compute maximum number of chars wanted */
6843 if (tok == TOK_STR)
6844 cstr_len = tokc.str.size;
6845 else
6846 cstr_len = tokc.str.size / sizeof(nwchar_t);
6847 cstr_len--;
6848 nb = cstr_len;
6849 if (n >= 0 && nb > (n - len))
6850 nb = n - len;
6851 if (!size_only) {
6852 if (cstr_len > nb)
6853 tcc_warning("initializer-string for array is too long");
6854 /* in order to go faster for common case (char
6855 string in global variable, we handle it
6856 specifically */
6857 if (sec && tok == TOK_STR && size1 == 1) {
6858 if (!NODATA_WANTED)
6859 memcpy(sec->data + c + len, tokc.str.data, nb);
6860 } else {
6861 for(i=0;i<nb;i++) {
6862 if (tok == TOK_STR)
6863 ch = ((unsigned char *)tokc.str.data)[i];
6864 else
6865 ch = ((nwchar_t *)tokc.str.data)[i];
6866 vpushi(ch);
6867 init_putv(t1, sec, c + (len + i) * size1);
6871 len += nb;
6872 next();
6874 /* only add trailing zero if enough storage (no
6875 warning in this case since it is standard) */
6876 if (n < 0 || len < n) {
6877 if (!size_only) {
6878 vpushi(0);
6879 init_putv(t1, sec, c + (len * size1));
6881 len++;
6883 len *= size1;
6884 } else {
6885 indexsym.c = 0;
6886 f = &indexsym;
6888 do_init_list:
6889 len = 0;
6890 while (tok != '}' || have_elem) {
6891 len = decl_designator(type, sec, c, &f, size_only, len);
6892 have_elem = 0;
6893 if (type->t & VT_ARRAY) {
6894 ++indexsym.c;
6895 /* special test for multi dimensional arrays (may not
6896 be strictly correct if designators are used at the
6897 same time) */
6898 if (no_oblock && len >= n*size1)
6899 break;
6900 } else {
6901 if (s->type.t == VT_UNION)
6902 f = NULL;
6903 else
6904 f = f->next;
6905 if (no_oblock && f == NULL)
6906 break;
6909 if (tok == '}')
6910 break;
6911 skip(',');
6914 /* put zeros at the end */
6915 if (!size_only && len < n*size1)
6916 init_putz(sec, c + len, n*size1 - len);
6917 if (!no_oblock)
6918 skip('}');
6919 /* patch type size if needed, which happens only for array types */
6920 if (n < 0)
6921 s->c = size1 == 1 ? len : ((len + size1 - 1)/size1);
6922 } else if ((type->t & VT_BTYPE) == VT_STRUCT) {
6923 size1 = 1;
6924 no_oblock = 1;
6925 if (first || tok == '{') {
6926 skip('{');
6927 no_oblock = 0;
6929 s = type->ref;
6930 f = s->next;
6931 n = s->c;
6932 goto do_init_list;
6933 } else if (tok == '{') {
6934 next();
6935 decl_initializer(type, sec, c, first, size_only);
6936 skip('}');
6937 } else if (size_only) {
6938 /* If we supported only ISO C we wouldn't have to accept calling
6939 this on anything than an array size_only==1 (and even then
6940 only on the outermost level, so no recursion would be needed),
6941 because initializing a flex array member isn't supported.
6942 But GNU C supports it, so we need to recurse even into
6943 subfields of structs and arrays when size_only is set. */
6944 /* just skip expression */
6945 skip_or_save_block(NULL);
6946 } else {
6947 if (!have_elem) {
6948 /* This should happen only when we haven't parsed
6949 the init element above for fear of committing a
6950 string constant to memory too early. */
6951 if (tok != TOK_STR && tok != TOK_LSTR)
6952 expect("string constant");
6953 parse_init_elem(!sec ? EXPR_ANY : EXPR_CONST);
6955 init_putv(type, sec, c);
6959 /* parse an initializer for type 't' if 'has_init' is non zero, and
6960 allocate space in local or global data space ('r' is either
6961 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
6962 variable 'v' of scope 'scope' is declared before initializers
6963 are parsed. If 'v' is zero, then a reference to the new object
6964 is put in the value stack. If 'has_init' is 2, a special parsing
6965 is done to handle string constants. */
6966 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
6967 int has_init, int v, int scope)
6969 int size, align, addr;
6970 TokenString *init_str = NULL;
6972 Section *sec;
6973 Sym *flexible_array;
6974 Sym *sym = NULL;
6975 int saved_nocode_wanted = nocode_wanted;
6976 #ifdef CONFIG_TCC_BCHECK
6977 int bcheck;
6978 #endif
6980 /* Always allocate static or global variables */
6981 if (v && (r & VT_VALMASK) == VT_CONST)
6982 nocode_wanted |= 0x80000000;
6984 #ifdef CONFIG_TCC_BCHECK
6985 bcheck = tcc_state->do_bounds_check && !NODATA_WANTED;
6986 #endif
6988 flexible_array = NULL;
6989 if ((type->t & VT_BTYPE) == VT_STRUCT) {
6990 Sym *field = type->ref->next;
6991 if (field) {
6992 while (field->next)
6993 field = field->next;
6994 if (field->type.t & VT_ARRAY && field->type.ref->c < 0)
6995 flexible_array = field;
6999 size = type_size(type, &align);
7000 /* If unknown size, we must evaluate it before
7001 evaluating initializers because
7002 initializers can generate global data too
7003 (e.g. string pointers or ISOC99 compound
7004 literals). It also simplifies local
7005 initializers handling */
7006 if (size < 0 || (flexible_array && has_init)) {
7007 if (!has_init)
7008 tcc_error("unknown type size");
7009 /* get all init string */
7010 if (has_init == 2) {
7011 init_str = tok_str_alloc();
7012 /* only get strings */
7013 while (tok == TOK_STR || tok == TOK_LSTR) {
7014 tok_str_add_tok(init_str);
7015 next();
7017 tok_str_add(init_str, -1);
7018 tok_str_add(init_str, 0);
7019 } else {
7020 skip_or_save_block(&init_str);
7022 unget_tok(0);
7024 /* compute size */
7025 begin_macro(init_str, 1);
7026 next();
7027 decl_initializer(type, NULL, 0, 1, 1);
7028 /* prepare second initializer parsing */
7029 macro_ptr = init_str->str;
7030 next();
7032 /* if still unknown size, error */
7033 size = type_size(type, &align);
7034 if (size < 0)
7035 tcc_error("unknown type size");
7037 /* If there's a flex member and it was used in the initializer
7038 adjust size. */
7039 if (flexible_array &&
7040 flexible_array->type.ref->c > 0)
7041 size += flexible_array->type.ref->c
7042 * pointed_size(&flexible_array->type);
7043 /* take into account specified alignment if bigger */
7044 if (ad->a.aligned) {
7045 int speca = 1 << (ad->a.aligned - 1);
7046 if (speca > align)
7047 align = speca;
7048 } else if (ad->a.packed) {
7049 align = 1;
7052 if (!v && NODATA_WANTED)
7053 size = 0, align = 1;
7055 if ((r & VT_VALMASK) == VT_LOCAL) {
7056 sec = NULL;
7057 #ifdef CONFIG_TCC_BCHECK
7058 if (bcheck && (type->t & VT_ARRAY)) {
7059 loc--;
7061 #endif
7062 loc = (loc - size) & -align;
7063 addr = loc;
7064 #ifdef CONFIG_TCC_BCHECK
7065 /* handles bounds */
7066 /* XXX: currently, since we do only one pass, we cannot track
7067 '&' operators, so we add only arrays */
7068 if (bcheck && (type->t & VT_ARRAY)) {
7069 addr_t *bounds_ptr;
7070 /* add padding between regions */
7071 loc--;
7072 /* then add local bound info */
7073 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(addr_t));
7074 bounds_ptr[0] = addr;
7075 bounds_ptr[1] = size;
7077 #endif
7078 if (v) {
7079 /* local variable */
7080 #ifdef CONFIG_TCC_ASM
7081 if (ad->asm_label) {
7082 int reg = asm_parse_regvar(ad->asm_label);
7083 if (reg >= 0)
7084 r = (r & ~VT_VALMASK) | reg;
7086 #endif
7087 sym = sym_push(v, type, r, addr);
7088 sym->a = ad->a;
7089 } else {
7090 /* push local reference */
7091 vset(type, r, addr);
7093 } else {
7094 if (v && scope == VT_CONST) {
7095 /* see if the symbol was already defined */
7096 sym = sym_find(v);
7097 if (sym) {
7098 patch_storage(sym, ad, type);
7099 /* we accept several definitions of the same global variable. */
7100 if (!has_init && sym->c && elfsym(sym)->st_shndx != SHN_UNDEF)
7101 goto no_alloc;
7105 /* allocate symbol in corresponding section */
7106 sec = ad->section;
7107 if (!sec) {
7108 if (has_init)
7109 sec = data_section;
7110 else if (tcc_state->nocommon)
7111 sec = bss_section;
7114 if (sec) {
7115 addr = section_add(sec, size, align);
7116 #ifdef CONFIG_TCC_BCHECK
7117 /* add padding if bound check */
7118 if (bcheck)
7119 section_add(sec, 1, 1);
7120 #endif
7121 } else {
7122 addr = align; /* SHN_COMMON is special, symbol value is align */
7123 sec = common_section;
7126 if (v) {
7127 if (!sym) {
7128 sym = sym_push(v, type, r | VT_SYM, 0);
7129 patch_storage(sym, ad, NULL);
7131 /* Local statics have a scope until now (for
7132 warnings), remove it here. */
7133 sym->sym_scope = 0;
7134 /* update symbol definition */
7135 put_extern_sym(sym, sec, addr, size);
7136 } else {
7137 /* push global reference */
7138 sym = get_sym_ref(type, sec, addr, size);
7139 vpushsym(type, sym);
7140 vtop->r |= r;
7143 #ifdef CONFIG_TCC_BCHECK
7144 /* handles bounds now because the symbol must be defined
7145 before for the relocation */
7146 if (bcheck) {
7147 addr_t *bounds_ptr;
7149 greloca(bounds_section, sym, bounds_section->data_offset, R_DATA_PTR, 0);
7150 /* then add global bound info */
7151 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(addr_t));
7152 bounds_ptr[0] = 0; /* relocated */
7153 bounds_ptr[1] = size;
7155 #endif
7158 if (type->t & VT_VLA) {
7159 int a;
7161 if (NODATA_WANTED)
7162 goto no_alloc;
7164 /* save current stack pointer */
7165 if (vlas_in_scope == 0) {
7166 if (vla_sp_root_loc == -1)
7167 vla_sp_root_loc = (loc -= PTR_SIZE);
7168 gen_vla_sp_save(vla_sp_root_loc);
7171 vla_runtime_type_size(type, &a);
7172 gen_vla_alloc(type, a);
7173 #if defined TCC_TARGET_PE && defined TCC_TARGET_X86_64
7174 /* on _WIN64, because of the function args scratch area, the
7175 result of alloca differs from RSP and is returned in RAX. */
7176 gen_vla_result(addr), addr = (loc -= PTR_SIZE);
7177 #endif
7178 gen_vla_sp_save(addr);
7179 vla_sp_loc = addr;
7180 vlas_in_scope++;
7182 } else if (has_init) {
7183 size_t oldreloc_offset = 0;
7184 if (sec && sec->reloc)
7185 oldreloc_offset = sec->reloc->data_offset;
7186 decl_initializer(type, sec, addr, 1, 0);
7187 if (sec && sec->reloc)
7188 squeeze_multi_relocs(sec, oldreloc_offset);
7189 /* patch flexible array member size back to -1, */
7190 /* for possible subsequent similar declarations */
7191 if (flexible_array)
7192 flexible_array->type.ref->c = -1;
7195 no_alloc:
7196 /* restore parse state if needed */
7197 if (init_str) {
7198 end_macro();
7199 next();
7202 nocode_wanted = saved_nocode_wanted;
7205 /* parse a function defined by symbol 'sym' and generate its code in
7206 'cur_text_section' */
7207 static void gen_function(Sym *sym)
7209 nocode_wanted = 0;
7210 ind = cur_text_section->data_offset;
7211 if (sym->a.aligned) {
7212 size_t newoff = section_add(cur_text_section, 0,
7213 1 << (sym->a.aligned - 1));
7214 gen_fill_nops(newoff - ind);
7216 /* NOTE: we patch the symbol size later */
7217 put_extern_sym(sym, cur_text_section, ind, 0);
7218 funcname = get_tok_str(sym->v, NULL);
7219 func_ind = ind;
7220 /* Initialize VLA state */
7221 vla_sp_loc = -1;
7222 vla_sp_root_loc = -1;
7223 /* put debug symbol */
7224 tcc_debug_funcstart(tcc_state, sym);
7225 /* push a dummy symbol to enable local sym storage */
7226 sym_push2(&local_stack, SYM_FIELD, 0, 0);
7227 local_scope = 1; /* for function parameters */
7228 gfunc_prolog(&sym->type);
7229 local_scope = 0;
7230 rsym = 0;
7231 clear_temp_local_var_list();
7232 block(NULL, NULL, 0);
7233 if (!(nocode_wanted & 0x20000000)
7234 && ((func_vt.t & VT_BTYPE) == VT_INT)
7235 && !strcmp (funcname, "main"))
7237 nocode_wanted = 0;
7238 vpushi(0);
7239 gen_assign_cast(&func_vt);
7240 gfunc_return(&func_vt);
7242 nocode_wanted = 0;
7243 gsym(rsym);
7244 gfunc_epilog();
7245 cur_text_section->data_offset = ind;
7246 label_pop(&global_label_stack, NULL, 0);
7247 /* reset local stack */
7248 local_scope = 0;
7249 sym_pop(&local_stack, NULL, 0);
7250 /* end of function */
7251 /* patch symbol size */
7252 elfsym(sym)->st_size = ind - func_ind;
7253 tcc_debug_funcend(tcc_state, ind - func_ind);
7254 /* It's better to crash than to generate wrong code */
7255 cur_text_section = NULL;
7256 funcname = ""; /* for safety */
7257 func_vt.t = VT_VOID; /* for safety */
7258 func_var = 0; /* for safety */
7259 ind = 0; /* for safety */
7260 nocode_wanted = 0x80000000;
7261 check_vstack();
7264 static void gen_inline_functions(TCCState *s)
7266 Sym *sym;
7267 int inline_generated, i, ln;
7268 struct InlineFunc *fn;
7270 ln = file->line_num;
7271 /* iterate while inline function are referenced */
7272 do {
7273 inline_generated = 0;
7274 for (i = 0; i < s->nb_inline_fns; ++i) {
7275 fn = s->inline_fns[i];
7276 sym = fn->sym;
7277 if (sym && sym->c) {
7278 /* the function was used: generate its code and
7279 convert it to a normal function */
7280 fn->sym = NULL;
7281 if (file)
7282 pstrcpy(file->filename, sizeof file->filename, fn->filename);
7283 sym->type.t &= ~VT_INLINE;
7285 begin_macro(fn->func_str, 1);
7286 next();
7287 cur_text_section = text_section;
7288 gen_function(sym);
7289 end_macro();
7291 inline_generated = 1;
7294 } while (inline_generated);
7295 file->line_num = ln;
7298 ST_FUNC void free_inline_functions(TCCState *s)
7300 int i;
7301 /* free tokens of unused inline functions */
7302 for (i = 0; i < s->nb_inline_fns; ++i) {
7303 struct InlineFunc *fn = s->inline_fns[i];
7304 if (fn->sym)
7305 tok_str_free(fn->func_str);
7307 dynarray_reset(&s->inline_fns, &s->nb_inline_fns);
7310 /* 'l' is VT_LOCAL or VT_CONST to define default storage type, or VT_CMP
7311 if parsing old style parameter decl list (and FUNC_SYM is set then) */
7312 static int decl0(int l, int is_for_loop_init, Sym *func_sym)
7314 int v, has_init, r;
7315 CType type, btype;
7316 Sym *sym;
7317 AttributeDef ad;
7319 while (1) {
7320 if (!parse_btype(&btype, &ad)) {
7321 if (is_for_loop_init)
7322 return 0;
7323 /* skip redundant ';' if not in old parameter decl scope */
7324 if (tok == ';' && l != VT_CMP) {
7325 next();
7326 continue;
7328 if (l != VT_CONST)
7329 break;
7330 if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
7331 /* global asm block */
7332 asm_global_instr();
7333 continue;
7335 if (tok >= TOK_UIDENT) {
7336 /* special test for old K&R protos without explicit int
7337 type. Only accepted when defining global data */
7338 btype.t = VT_INT;
7339 } else {
7340 if (tok != TOK_EOF)
7341 expect("declaration");
7342 break;
7345 if (tok == ';') {
7346 if ((btype.t & VT_BTYPE) == VT_STRUCT) {
7347 int v = btype.ref->v;
7348 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) >= SYM_FIRST_ANOM)
7349 tcc_warning("unnamed struct/union that defines no instances");
7350 next();
7351 continue;
7353 if (IS_ENUM(btype.t)) {
7354 next();
7355 continue;
7358 while (1) { /* iterate thru each declaration */
7359 type = btype;
7360 /* If the base type itself was an array type of unspecified
7361 size (like in 'typedef int arr[]; arr x = {1};') then
7362 we will overwrite the unknown size by the real one for
7363 this decl. We need to unshare the ref symbol holding
7364 that size. */
7365 if ((type.t & VT_ARRAY) && type.ref->c < 0) {
7366 type.ref = sym_push(SYM_FIELD, &type.ref->type, 0, type.ref->c);
7368 type_decl(&type, &ad, &v, TYPE_DIRECT);
7369 #if 0
7371 char buf[500];
7372 type_to_str(buf, sizeof(buf), &type, get_tok_str(v, NULL));
7373 printf("type = '%s'\n", buf);
7375 #endif
7376 if ((type.t & VT_BTYPE) == VT_FUNC) {
7377 if ((type.t & VT_STATIC) && (l == VT_LOCAL)) {
7378 tcc_error("function without file scope cannot be static");
7380 /* if old style function prototype, we accept a
7381 declaration list */
7382 sym = type.ref;
7383 if (sym->f.func_type == FUNC_OLD && l == VT_CONST)
7384 decl0(VT_CMP, 0, sym);
7387 if (gnu_ext && (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
7388 ad.asm_label = asm_label_instr();
7389 /* parse one last attribute list, after asm label */
7390 parse_attribute(&ad);
7391 if (tok == '{')
7392 expect(";");
7395 #ifdef TCC_TARGET_PE
7396 if (ad.a.dllimport || ad.a.dllexport) {
7397 if (type.t & (VT_STATIC|VT_TYPEDEF))
7398 tcc_error("cannot have dll linkage with static or typedef");
7399 if (ad.a.dllimport) {
7400 if ((type.t & VT_BTYPE) == VT_FUNC)
7401 ad.a.dllimport = 0;
7402 else
7403 type.t |= VT_EXTERN;
7406 #endif
7407 if (tok == '{') {
7408 if (l != VT_CONST)
7409 tcc_error("cannot use local functions");
7410 if ((type.t & VT_BTYPE) != VT_FUNC)
7411 expect("function definition");
7413 /* reject abstract declarators in function definition
7414 make old style params without decl have int type */
7415 sym = type.ref;
7416 while ((sym = sym->next) != NULL) {
7417 if (!(sym->v & ~SYM_FIELD))
7418 expect("identifier");
7419 if (sym->type.t == VT_VOID)
7420 sym->type = int_type;
7423 /* XXX: cannot do better now: convert extern line to static inline */
7424 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
7425 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
7427 /* put function symbol */
7428 sym = external_global_sym(v, &type, 0);
7429 type.t &= ~VT_EXTERN;
7430 patch_storage(sym, &ad, &type);
7432 /* static inline functions are just recorded as a kind
7433 of macro. Their code will be emitted at the end of
7434 the compilation unit only if they are used */
7435 if ((type.t & (VT_INLINE | VT_STATIC)) ==
7436 (VT_INLINE | VT_STATIC)) {
7437 struct InlineFunc *fn;
7438 const char *filename;
7440 filename = file ? file->filename : "";
7441 fn = tcc_malloc(sizeof *fn + strlen(filename));
7442 strcpy(fn->filename, filename);
7443 fn->sym = sym;
7444 skip_or_save_block(&fn->func_str);
7445 dynarray_add(&tcc_state->inline_fns,
7446 &tcc_state->nb_inline_fns, fn);
7447 } else {
7448 /* compute text section */
7449 cur_text_section = ad.section;
7450 if (!cur_text_section)
7451 cur_text_section = text_section;
7452 gen_function(sym);
7454 break;
7455 } else {
7456 if (l == VT_CMP) {
7457 /* find parameter in function parameter list */
7458 for (sym = func_sym->next; sym; sym = sym->next)
7459 if ((sym->v & ~SYM_FIELD) == v)
7460 goto found;
7461 tcc_error("declaration for parameter '%s' but no such parameter",
7462 get_tok_str(v, NULL));
7463 found:
7464 if (type.t & VT_STORAGE) /* 'register' is okay */
7465 tcc_error("storage class specified for '%s'",
7466 get_tok_str(v, NULL));
7467 if (sym->type.t != VT_VOID)
7468 tcc_error("redefinition of parameter '%s'",
7469 get_tok_str(v, NULL));
7470 convert_parameter_type(&type);
7471 sym->type = type;
7472 } else if (type.t & VT_TYPEDEF) {
7473 /* save typedefed type */
7474 /* XXX: test storage specifiers ? */
7475 sym = sym_find(v);
7476 if (sym && sym->sym_scope == local_scope) {
7477 if (!is_compatible_types(&sym->type, &type)
7478 || !(sym->type.t & VT_TYPEDEF))
7479 tcc_error("incompatible redefinition of '%s'",
7480 get_tok_str(v, NULL));
7481 sym->type = type;
7482 } else {
7483 sym = sym_push(v, &type, 0, 0);
7485 sym->a = ad.a;
7486 sym->f = ad.f;
7487 } else if ((type.t & VT_BTYPE) == VT_VOID
7488 && !(type.t & VT_EXTERN)) {
7489 tcc_error("declaration of void object");
7490 } else {
7491 r = 0;
7492 if ((type.t & VT_BTYPE) == VT_FUNC) {
7493 /* external function definition */
7494 /* specific case for func_call attribute */
7495 type.ref->f = ad.f;
7496 } else if (!(type.t & VT_ARRAY)) {
7497 /* not lvalue if array */
7498 r |= lvalue_type(type.t);
7500 has_init = (tok == '=');
7501 if (has_init && (type.t & VT_VLA))
7502 tcc_error("variable length array cannot be initialized");
7503 if (((type.t & VT_EXTERN) && (!has_init || l != VT_CONST)) ||
7504 ((type.t & VT_BTYPE) == VT_FUNC) ||
7505 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
7506 !has_init && l == VT_CONST && type.ref->c < 0)) {
7507 /* external variable or function */
7508 /* NOTE: as GCC, uninitialized global static
7509 arrays of null size are considered as
7510 extern */
7511 type.t |= VT_EXTERN;
7512 sym = external_sym(v, &type, r, &ad);
7513 if (ad.alias_target) {
7514 ElfSym *esym;
7515 Sym *alias_target;
7516 alias_target = sym_find(ad.alias_target);
7517 esym = elfsym(alias_target);
7518 if (!esym)
7519 tcc_error("unsupported forward __alias__ attribute");
7520 /* Local statics have a scope until now (for
7521 warnings), remove it here. */
7522 sym->sym_scope = 0;
7523 put_extern_sym2(sym, esym->st_shndx, esym->st_value, esym->st_size, 0);
7525 } else {
7526 if (type.t & VT_STATIC)
7527 r |= VT_CONST;
7528 else
7529 r |= l;
7530 if (has_init)
7531 next();
7532 else if (l == VT_CONST)
7533 /* uninitialized global variables may be overridden */
7534 type.t |= VT_EXTERN;
7535 decl_initializer_alloc(&type, &ad, r, has_init, v, l);
7538 if (tok != ',') {
7539 if (is_for_loop_init)
7540 return 1;
7541 skip(';');
7542 break;
7544 next();
7546 ad.a.aligned = 0;
7549 return 0;
7552 static void decl(int l)
7554 decl0(l, 0, NULL);
7557 /* ------------------------------------------------------------------------- */