#pragma comment(option,"-..."), bitfields test, etc...
[tinycc.git] / tccgen.c
blob3cc61089626cbb4c1ac2416eba1c16d49a31b5c1
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"
23 /********************************************************/
24 /* global variables */
26 /* loc : local variable index
27 ind : output code index
28 rsym: return symbol
29 anon_sym: anonymous symbol index
31 ST_DATA int rsym, anon_sym, ind, loc;
33 ST_DATA Sym *sym_free_first;
34 ST_DATA void **sym_pools;
35 ST_DATA int nb_sym_pools;
37 ST_DATA Sym *global_stack;
38 ST_DATA Sym *local_stack;
39 ST_DATA Sym *define_stack;
40 ST_DATA Sym *global_label_stack;
41 ST_DATA Sym *local_label_stack;
42 static int local_scope;
43 static int in_sizeof;
44 static int section_sym;
46 ST_DATA int vlas_in_scope; /* number of VLAs that are currently in scope */
47 ST_DATA int vla_sp_root_loc; /* vla_sp_loc for SP before any VLAs were pushed */
48 ST_DATA int vla_sp_loc; /* Pointer to variable holding location to store stack pointer on the stack when modifying stack pointer */
50 ST_DATA SValue __vstack[1+VSTACK_SIZE], *vtop, *pvtop;
52 ST_DATA int const_wanted; /* true if constant wanted */
53 ST_DATA int nocode_wanted; /* true if no code generation wanted for an expression */
54 ST_DATA int global_expr; /* true if compound literals must be allocated globally (used during initializers parsing */
55 ST_DATA CType func_vt; /* current function return type (used by return instruction) */
56 ST_DATA int func_var; /* true if current function is variadic (used by return instruction) */
57 ST_DATA int func_vc;
58 ST_DATA int last_line_num, last_ind, func_ind; /* debug last line number and pc */
59 ST_DATA const char *funcname;
60 ST_DATA int g_debug;
62 ST_DATA CType char_pointer_type, func_old_type, int_type, size_type;
64 ST_DATA struct switch_t {
65 struct case_t {
66 int64_t v1, v2;
67 int sym;
68 } **p; int n; /* list of case ranges */
69 int def_sym; /* default symbol */
70 } *cur_switch; /* current switch */
72 /* ------------------------------------------------------------------------- */
74 static void gen_cast(CType *type);
75 static void gen_cast_s(int t);
76 static inline CType *pointed_type(CType *type);
77 static int is_compatible_types(CType *type1, CType *type2);
78 static int parse_btype(CType *type, AttributeDef *ad);
79 static CType *type_decl(CType *type, AttributeDef *ad, int *v, int td);
80 static void parse_expr_type(CType *type);
81 static void init_putv(CType *type, Section *sec, unsigned long c);
82 static void decl_initializer(CType *type, Section *sec, unsigned long c, int first, int size_only);
83 static void block(int *bsym, int *csym, int is_expr);
84 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r, int has_init, int v, int scope);
85 static int decl0(int l, int is_for_loop_init, Sym *);
86 static void expr_eq(void);
87 static void vla_runtime_type_size(CType *type, int *a);
88 static void vla_sp_restore(void);
89 static void vla_sp_restore_root(void);
90 static int is_compatible_unqualified_types(CType *type1, CType *type2);
91 static inline int64_t expr_const64(void);
92 ST_FUNC void vpush64(int ty, unsigned long long v);
93 ST_FUNC void vpush(CType *type);
94 ST_FUNC int gvtst(int inv, int t);
95 static void gen_inline_functions(TCCState *s);
96 static void skip_or_save_block(TokenString **str);
97 static void gv_dup(void);
99 ST_INLN int is_float(int t)
101 int bt;
102 bt = t & VT_BTYPE;
103 return bt == VT_LDOUBLE || bt == VT_DOUBLE || bt == VT_FLOAT || bt == VT_QFLOAT;
106 /* we use our own 'finite' function to avoid potential problems with
107 non standard math libs */
108 /* XXX: endianness dependent */
109 ST_FUNC int ieee_finite(double d)
111 int p[4];
112 memcpy(p, &d, sizeof(double));
113 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
116 ST_FUNC void test_lvalue(void)
118 if (!(vtop->r & VT_LVAL))
119 expect("lvalue");
122 ST_FUNC void check_vstack(void)
124 if (pvtop != vtop)
125 tcc_error("internal compiler error: vstack leak (%d)", vtop - pvtop);
128 /* ------------------------------------------------------------------------- */
129 /* vstack debugging aid */
131 #if 0
132 void pv (const char *lbl, int a, int b)
134 int i;
135 for (i = a; i < a + b; ++i) {
136 SValue *p = &vtop[-i];
137 printf("%s vtop[-%d] : type.t:%04x r:%04x r2:%04x c.i:%d\n",
138 lbl, i, p->type.t, p->r, p->r2, (int)p->c.i);
141 #endif
143 /* ------------------------------------------------------------------------- */
144 /* start of translation unit info */
145 ST_FUNC void tcc_debug_start(TCCState *s1)
147 if (s1->do_debug) {
148 char buf[512];
150 /* file info: full path + filename */
151 section_sym = put_elf_sym(symtab_section, 0, 0,
152 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
153 text_section->sh_num, NULL);
154 getcwd(buf, sizeof(buf));
155 #ifdef _WIN32
156 normalize_slashes(buf);
157 #endif
158 pstrcat(buf, sizeof(buf), "/");
159 put_stabs_r(buf, N_SO, 0, 0,
160 text_section->data_offset, text_section, section_sym);
161 put_stabs_r(file->filename, N_SO, 0, 0,
162 text_section->data_offset, text_section, section_sym);
163 last_ind = 0;
164 last_line_num = 0;
167 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
168 symbols can be safely used */
169 put_elf_sym(symtab_section, 0, 0,
170 ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
171 SHN_ABS, file->filename);
174 /* put end of translation unit info */
175 ST_FUNC void tcc_debug_end(TCCState *s1)
177 if (!s1->do_debug)
178 return;
179 put_stabs_r(NULL, N_SO, 0, 0,
180 text_section->data_offset, text_section, section_sym);
184 /* generate line number info */
185 ST_FUNC void tcc_debug_line(TCCState *s1)
187 if (!s1->do_debug)
188 return;
189 if ((last_line_num != file->line_num || last_ind != ind)) {
190 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
191 last_ind = ind;
192 last_line_num = file->line_num;
196 /* put function symbol */
197 ST_FUNC void tcc_debug_funcstart(TCCState *s1, Sym *sym)
199 char buf[512];
201 if (!s1->do_debug)
202 return;
204 /* stabs info */
205 /* XXX: we put here a dummy type */
206 snprintf(buf, sizeof(buf), "%s:%c1",
207 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
208 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
209 cur_text_section, sym->c);
210 /* //gr gdb wants a line at the function */
211 put_stabn(N_SLINE, 0, file->line_num, 0);
213 last_ind = 0;
214 last_line_num = 0;
217 /* put function size */
218 ST_FUNC void tcc_debug_funcend(TCCState *s1, int size)
220 if (!s1->do_debug)
221 return;
222 put_stabn(N_FUN, 0, 0, size);
225 /* ------------------------------------------------------------------------- */
226 ST_FUNC void tccgen_start(TCCState *s1)
228 cur_text_section = NULL;
229 funcname = "";
230 anon_sym = SYM_FIRST_ANOM;
231 section_sym = 0;
232 const_wanted = 0;
233 nocode_wanted = 1;
235 /* define some often used types */
236 int_type.t = VT_INT;
237 char_pointer_type.t = VT_BYTE;
238 mk_pointer(&char_pointer_type);
239 #if PTR_SIZE == 4
240 size_type.t = VT_INT;
241 #else
242 size_type.t = VT_LLONG;
243 #endif
244 func_old_type.t = VT_FUNC;
245 func_old_type.ref = sym_push(SYM_FIELD, &int_type, 0, 0);
246 func_old_type.ref->f.func_call = FUNC_CDECL;
247 func_old_type.ref->f.func_type = FUNC_OLD;
249 tcc_debug_start(s1);
251 #ifdef TCC_TARGET_ARM
252 arm_init(s1);
253 #endif
256 ST_FUNC void tccgen_end(TCCState *s1)
258 gen_inline_functions(s1);
259 check_vstack();
260 /* end of translation unit info */
261 tcc_debug_end(s1);
264 /* ------------------------------------------------------------------------- */
265 /* apply storage attributes to Elf symbol */
267 static void update_storage(Sym *sym)
269 ElfW(Sym) *esym;
270 if (0 == sym->c)
271 return;
272 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
273 if (sym->a.visibility)
274 esym->st_other = (esym->st_other & ~ELFW(ST_VISIBILITY)(-1))
275 | sym->a.visibility;
276 if (sym->a.weak)
277 esym->st_info = ELFW(ST_INFO)(STB_WEAK, ELFW(ST_TYPE)(esym->st_info));
278 #ifdef TCC_TARGET_PE
279 if (sym->a.dllimport)
280 esym->st_other |= ST_PE_IMPORT;
281 if (sym->a.dllexport)
282 esym->st_other |= ST_PE_EXPORT;
283 #endif
284 #if 0
285 printf("storage %s: vis=%d weak=%d exp=%d imp=%d\n",
286 get_tok_str(sym->v, NULL),
287 sym->a.visibility,
288 sym->a.weak,
289 sym->a.dllexport,
290 sym->a.dllimport
292 #endif
295 /* ------------------------------------------------------------------------- */
296 /* update sym->c so that it points to an external symbol in section
297 'section' with value 'value' */
299 ST_FUNC void put_extern_sym2(Sym *sym, Section *section,
300 addr_t value, unsigned long size,
301 int can_add_underscore)
303 int sym_type, sym_bind, sh_num, info, other, t;
304 ElfW(Sym) *esym;
305 const char *name;
306 char buf1[256];
307 #ifdef CONFIG_TCC_BCHECK
308 char buf[32];
309 #endif
311 if (section == NULL)
312 sh_num = SHN_UNDEF;
313 else if (section == SECTION_ABS)
314 sh_num = SHN_ABS;
315 else
316 sh_num = section->sh_num;
318 if (!sym->c) {
319 name = get_tok_str(sym->v, NULL);
320 #ifdef CONFIG_TCC_BCHECK
321 if (tcc_state->do_bounds_check) {
322 /* XXX: avoid doing that for statics ? */
323 /* if bound checking is activated, we change some function
324 names by adding the "__bound" prefix */
325 switch(sym->v) {
326 #ifdef TCC_TARGET_PE
327 /* XXX: we rely only on malloc hooks */
328 case TOK_malloc:
329 case TOK_free:
330 case TOK_realloc:
331 case TOK_memalign:
332 case TOK_calloc:
333 #endif
334 case TOK_memcpy:
335 case TOK_memmove:
336 case TOK_memset:
337 case TOK_strlen:
338 case TOK_strcpy:
339 case TOK_alloca:
340 strcpy(buf, "__bound_");
341 strcat(buf, name);
342 name = buf;
343 break;
346 #endif
347 t = sym->type.t;
348 if ((t & VT_BTYPE) == VT_FUNC) {
349 sym_type = STT_FUNC;
350 } else if ((t & VT_BTYPE) == VT_VOID) {
351 sym_type = STT_NOTYPE;
352 } else {
353 sym_type = STT_OBJECT;
355 if (t & VT_STATIC)
356 sym_bind = STB_LOCAL;
357 else
358 sym_bind = STB_GLOBAL;
359 other = 0;
360 #ifdef TCC_TARGET_PE
361 if (sym_type == STT_FUNC && sym->type.ref) {
362 Sym *ref = sym->type.ref;
363 if (ref->f.func_call == FUNC_STDCALL && can_add_underscore) {
364 sprintf(buf1, "_%s@%d", name, ref->f.func_args * PTR_SIZE);
365 name = buf1;
366 other |= ST_PE_STDCALL;
367 can_add_underscore = 0;
370 #endif
371 if (tcc_state->leading_underscore && can_add_underscore) {
372 buf1[0] = '_';
373 pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
374 name = buf1;
376 if (sym->asm_label)
377 name = get_tok_str(sym->asm_label, NULL);
378 info = ELFW(ST_INFO)(sym_bind, sym_type);
379 sym->c = set_elf_sym(symtab_section, value, size, info, other, sh_num, name);
380 } else {
381 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
382 esym->st_value = value;
383 esym->st_size = size;
384 esym->st_shndx = sh_num;
386 update_storage(sym);
389 ST_FUNC void put_extern_sym(Sym *sym, Section *section,
390 addr_t value, unsigned long size)
392 put_extern_sym2(sym, section, value, size, 1);
395 /* add a new relocation entry to symbol 'sym' in section 's' */
396 ST_FUNC void greloca(Section *s, Sym *sym, unsigned long offset, int type,
397 addr_t addend)
399 int c = 0;
401 if (nocode_wanted && s == cur_text_section)
402 return;
404 if (sym) {
405 if (0 == sym->c)
406 put_extern_sym(sym, NULL, 0, 0);
407 c = sym->c;
410 /* now we can add ELF relocation info */
411 put_elf_reloca(symtab_section, s, offset, type, c, addend);
414 #if PTR_SIZE == 4
415 ST_FUNC void greloc(Section *s, Sym *sym, unsigned long offset, int type)
417 greloca(s, sym, offset, type, 0);
419 #endif
421 /* ------------------------------------------------------------------------- */
422 /* symbol allocator */
423 static Sym *__sym_malloc(void)
425 Sym *sym_pool, *sym, *last_sym;
426 int i;
428 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
429 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
431 last_sym = sym_free_first;
432 sym = sym_pool;
433 for(i = 0; i < SYM_POOL_NB; i++) {
434 sym->next = last_sym;
435 last_sym = sym;
436 sym++;
438 sym_free_first = last_sym;
439 return last_sym;
442 static inline Sym *sym_malloc(void)
444 Sym *sym;
445 #ifndef SYM_DEBUG
446 sym = sym_free_first;
447 if (!sym)
448 sym = __sym_malloc();
449 sym_free_first = sym->next;
450 return sym;
451 #else
452 sym = tcc_malloc(sizeof(Sym));
453 return sym;
454 #endif
457 ST_INLN void sym_free(Sym *sym)
459 #ifndef SYM_DEBUG
460 sym->next = sym_free_first;
461 sym_free_first = sym;
462 #else
463 tcc_free(sym);
464 #endif
467 /* push, without hashing */
468 ST_FUNC Sym *sym_push2(Sym **ps, int v, int t, int c)
470 Sym *s;
472 s = sym_malloc();
473 memset(s, 0, sizeof *s);
474 s->v = v;
475 s->type.t = t;
476 s->c = c;
477 /* add in stack */
478 s->prev = *ps;
479 *ps = s;
480 return s;
483 /* find a symbol and return its associated structure. 's' is the top
484 of the symbol stack */
485 ST_FUNC Sym *sym_find2(Sym *s, int v)
487 while (s) {
488 if (s->v == v)
489 return s;
490 else if (s->v == -1)
491 return NULL;
492 s = s->prev;
494 return NULL;
497 /* structure lookup */
498 ST_INLN Sym *struct_find(int v)
500 v -= TOK_IDENT;
501 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
502 return NULL;
503 return table_ident[v]->sym_struct;
506 /* find an identifier */
507 ST_INLN Sym *sym_find(int v)
509 v -= TOK_IDENT;
510 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
511 return NULL;
512 return table_ident[v]->sym_identifier;
515 /* push a given symbol on the symbol stack */
516 ST_FUNC Sym *sym_push(int v, CType *type, int r, int c)
518 Sym *s, **ps;
519 TokenSym *ts;
521 if (local_stack)
522 ps = &local_stack;
523 else
524 ps = &global_stack;
525 s = sym_push2(ps, v, type->t, c);
526 s->type.ref = type->ref;
527 s->r = r;
528 /* don't record fields or anonymous symbols */
529 /* XXX: simplify */
530 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
531 /* record symbol in token array */
532 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
533 if (v & SYM_STRUCT)
534 ps = &ts->sym_struct;
535 else
536 ps = &ts->sym_identifier;
537 s->prev_tok = *ps;
538 *ps = s;
539 s->sym_scope = local_scope;
540 if (s->prev_tok && s->prev_tok->sym_scope == s->sym_scope)
541 tcc_error("redeclaration of '%s'",
542 get_tok_str(v & ~SYM_STRUCT, NULL));
544 return s;
547 /* push a global identifier */
548 ST_FUNC Sym *global_identifier_push(int v, int t, int c)
550 Sym *s, **ps;
551 s = sym_push2(&global_stack, v, t, c);
552 /* don't record anonymous symbol */
553 if (v < SYM_FIRST_ANOM) {
554 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
555 /* modify the top most local identifier, so that
556 sym_identifier will point to 's' when popped */
557 while (*ps != NULL)
558 ps = &(*ps)->prev_tok;
559 s->prev_tok = NULL;
560 *ps = s;
562 return s;
565 /* pop symbols until top reaches 'b'. If KEEP is non-zero don't really
566 pop them yet from the list, but do remove them from the token array. */
567 ST_FUNC void sym_pop(Sym **ptop, Sym *b, int keep)
569 Sym *s, *ss, **ps;
570 TokenSym *ts;
571 int v;
573 s = *ptop;
574 while(s != b) {
575 ss = s->prev;
576 v = s->v;
577 /* remove symbol in token array */
578 /* XXX: simplify */
579 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
580 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
581 if (v & SYM_STRUCT)
582 ps = &ts->sym_struct;
583 else
584 ps = &ts->sym_identifier;
585 *ps = s->prev_tok;
587 if (!keep)
588 sym_free(s);
589 s = ss;
591 if (!keep)
592 *ptop = b;
595 /* ------------------------------------------------------------------------- */
597 static void vsetc(CType *type, int r, CValue *vc)
599 int v;
601 if (vtop >= vstack + (VSTACK_SIZE - 1))
602 tcc_error("memory full (vstack)");
603 /* cannot let cpu flags if other instruction are generated. Also
604 avoid leaving VT_JMP anywhere except on the top of the stack
605 because it would complicate the code generator.
607 Don't do this when nocode_wanted. vtop might come from
608 !nocode_wanted regions (see 88_codeopt.c) and transforming
609 it to a register without actually generating code is wrong
610 as their value might still be used for real. All values
611 we push under nocode_wanted will eventually be popped
612 again, so that the VT_CMP/VT_JMP value will be in vtop
613 when code is unsuppressed again.
615 Same logic below in vswap(); */
616 if (vtop >= vstack && !nocode_wanted) {
617 v = vtop->r & VT_VALMASK;
618 if (v == VT_CMP || (v & ~1) == VT_JMP)
619 gv(RC_INT);
622 vtop++;
623 vtop->type = *type;
624 vtop->r = r;
625 vtop->r2 = VT_CONST;
626 vtop->c = *vc;
627 vtop->sym = NULL;
630 ST_FUNC void vswap(void)
632 SValue tmp;
633 /* cannot vswap cpu flags. See comment at vsetc() above */
634 if (vtop >= vstack && !nocode_wanted) {
635 int v = vtop->r & VT_VALMASK;
636 if (v == VT_CMP || (v & ~1) == VT_JMP)
637 gv(RC_INT);
639 tmp = vtop[0];
640 vtop[0] = vtop[-1];
641 vtop[-1] = tmp;
644 /* pop stack value */
645 ST_FUNC void vpop(void)
647 int v;
648 v = vtop->r & VT_VALMASK;
649 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
650 /* for x86, we need to pop the FP stack */
651 if (v == TREG_ST0) {
652 o(0xd8dd); /* fstp %st(0) */
653 } else
654 #endif
655 if (v == VT_JMP || v == VT_JMPI) {
656 /* need to put correct jump if && or || without test */
657 gsym(vtop->c.i);
659 vtop--;
662 /* push constant of type "type" with useless value */
663 ST_FUNC void vpush(CType *type)
665 vset(type, VT_CONST, 0);
668 /* push integer constant */
669 ST_FUNC void vpushi(int v)
671 CValue cval;
672 cval.i = v;
673 vsetc(&int_type, VT_CONST, &cval);
676 /* push a pointer sized constant */
677 static void vpushs(addr_t v)
679 CValue cval;
680 cval.i = v;
681 vsetc(&size_type, VT_CONST, &cval);
684 /* push arbitrary 64bit constant */
685 ST_FUNC void vpush64(int ty, unsigned long long v)
687 CValue cval;
688 CType ctype;
689 ctype.t = ty;
690 ctype.ref = NULL;
691 cval.i = v;
692 vsetc(&ctype, VT_CONST, &cval);
695 /* push long long constant */
696 static inline void vpushll(long long v)
698 vpush64(VT_LLONG, v);
701 ST_FUNC void vset(CType *type, int r, int v)
703 CValue cval;
705 cval.i = v;
706 vsetc(type, r, &cval);
709 static void vseti(int r, int v)
711 CType type;
712 type.t = VT_INT;
713 type.ref = NULL;
714 vset(&type, r, v);
717 ST_FUNC void vpushv(SValue *v)
719 if (vtop >= vstack + (VSTACK_SIZE - 1))
720 tcc_error("memory full (vstack)");
721 vtop++;
722 *vtop = *v;
725 static void vdup(void)
727 vpushv(vtop);
730 /* rotate n first stack elements to the bottom
731 I1 ... In -> I2 ... In I1 [top is right]
733 ST_FUNC void vrotb(int n)
735 int i;
736 SValue tmp;
738 tmp = vtop[-n + 1];
739 for(i=-n+1;i!=0;i++)
740 vtop[i] = vtop[i+1];
741 vtop[0] = tmp;
744 /* rotate the n elements before entry e towards the top
745 I1 ... In ... -> In I1 ... I(n-1) ... [top is right]
747 ST_FUNC void vrote(SValue *e, int n)
749 int i;
750 SValue tmp;
752 tmp = *e;
753 for(i = 0;i < n - 1; i++)
754 e[-i] = e[-i - 1];
755 e[-n + 1] = tmp;
758 /* rotate n first stack elements to the top
759 I1 ... In -> In I1 ... I(n-1) [top is right]
761 ST_FUNC void vrott(int n)
763 vrote(vtop, n);
766 /* push a symbol value of TYPE */
767 static inline void vpushsym(CType *type, Sym *sym)
769 CValue cval;
770 cval.i = 0;
771 vsetc(type, VT_CONST | VT_SYM, &cval);
772 vtop->sym = sym;
775 /* Return a static symbol pointing to a section */
776 ST_FUNC Sym *get_sym_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
778 int v;
779 Sym *sym;
781 v = anon_sym++;
782 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
783 sym->type.ref = type->ref;
784 sym->r = VT_CONST | VT_SYM;
785 put_extern_sym(sym, sec, offset, size);
786 return sym;
789 /* push a reference to a section offset by adding a dummy symbol */
790 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
792 vpushsym(type, get_sym_ref(type, sec, offset, size));
795 /* define a new external reference to a symbol 'v' of type 'u' */
796 ST_FUNC Sym *external_global_sym(int v, CType *type, int r)
798 Sym *s;
800 s = sym_find(v);
801 if (!s) {
802 /* push forward reference */
803 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
804 s->type.ref = type->ref;
805 s->r = r | VT_CONST | VT_SYM;
807 return s;
810 /* Merge some storage attributes. */
811 static void patch_storage(Sym *sym, AttributeDef *ad, CType *type)
813 if (type && !is_compatible_types(&sym->type, type))
814 tcc_error("incompatible types for redefinition of '%s'",
815 get_tok_str(sym->v, NULL));
816 #ifdef TCC_TARGET_PE
817 if (sym->a.dllimport != ad->a.dllimport)
818 tcc_error("incompatible dll linkage for redefinition of '%s'",
819 get_tok_str(sym->v, NULL));
820 #endif
821 sym->a.dllexport |= ad->a.dllexport;
822 sym->a.weak |= ad->a.weak;
823 if (ad->a.visibility) {
824 int vis = sym->a.visibility;
825 int vis2 = ad->a.visibility;
826 if (vis == STV_DEFAULT)
827 vis = vis2;
828 else if (vis2 != STV_DEFAULT)
829 vis = (vis < vis2) ? vis : vis2;
830 sym->a.visibility = vis;
832 if (ad->a.aligned)
833 sym->a.aligned = ad->a.aligned;
834 if (ad->asm_label)
835 sym->asm_label = ad->asm_label;
836 update_storage(sym);
839 /* define a new external reference to a symbol 'v' */
840 static Sym *external_sym(int v, CType *type, int r, AttributeDef *ad)
842 Sym *s;
843 s = sym_find(v);
844 if (!s) {
845 /* push forward reference */
846 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
847 s->type.t |= VT_EXTERN;
848 s->a = ad->a;
849 s->sym_scope = 0;
850 } else {
851 if (s->type.ref == func_old_type.ref) {
852 s->type.ref = type->ref;
853 s->r = r | VT_CONST | VT_SYM;
854 s->type.t |= VT_EXTERN;
856 patch_storage(s, ad, type);
858 return s;
861 /* push a reference to global symbol v */
862 ST_FUNC void vpush_global_sym(CType *type, int v)
864 vpushsym(type, external_global_sym(v, type, 0));
867 /* save registers up to (vtop - n) stack entry */
868 ST_FUNC void save_regs(int n)
870 SValue *p, *p1;
871 for(p = vstack, p1 = vtop - n; p <= p1; p++)
872 save_reg(p->r);
875 /* save r to the memory stack, and mark it as being free */
876 ST_FUNC void save_reg(int r)
878 save_reg_upstack(r, 0);
881 /* save r to the memory stack, and mark it as being free,
882 if seen up to (vtop - n) stack entry */
883 ST_FUNC void save_reg_upstack(int r, int n)
885 int l, saved, size, align;
886 SValue *p, *p1, sv;
887 CType *type;
889 if ((r &= VT_VALMASK) >= VT_CONST)
890 return;
891 if (nocode_wanted)
892 return;
894 /* modify all stack values */
895 saved = 0;
896 l = 0;
897 for(p = vstack, p1 = vtop - n; p <= p1; p++) {
898 if ((p->r & VT_VALMASK) == r ||
899 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
900 /* must save value on stack if not already done */
901 if (!saved) {
902 /* NOTE: must reload 'r' because r might be equal to r2 */
903 r = p->r & VT_VALMASK;
904 /* store register in the stack */
905 type = &p->type;
906 if ((p->r & VT_LVAL) ||
907 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
908 #if PTR_SIZE == 8
909 type = &char_pointer_type;
910 #else
911 type = &int_type;
912 #endif
913 size = type_size(type, &align);
914 loc = (loc - size) & -align;
915 sv.type.t = type->t;
916 sv.r = VT_LOCAL | VT_LVAL;
917 sv.c.i = loc;
918 store(r, &sv);
919 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
920 /* x86 specific: need to pop fp register ST0 if saved */
921 if (r == TREG_ST0) {
922 o(0xd8dd); /* fstp %st(0) */
924 #endif
925 #if PTR_SIZE == 4
926 /* special long long case */
927 if ((type->t & VT_BTYPE) == VT_LLONG) {
928 sv.c.i += 4;
929 store(p->r2, &sv);
931 #endif
932 l = loc;
933 saved = 1;
935 /* mark that stack entry as being saved on the stack */
936 if (p->r & VT_LVAL) {
937 /* also clear the bounded flag because the
938 relocation address of the function was stored in
939 p->c.i */
940 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
941 } else {
942 p->r = lvalue_type(p->type.t) | VT_LOCAL;
944 p->r2 = VT_CONST;
945 p->c.i = l;
950 #ifdef TCC_TARGET_ARM
951 /* find a register of class 'rc2' with at most one reference on stack.
952 * If none, call get_reg(rc) */
953 ST_FUNC int get_reg_ex(int rc, int rc2)
955 int r;
956 SValue *p;
958 for(r=0;r<NB_REGS;r++) {
959 if (reg_classes[r] & rc2) {
960 int n;
961 n=0;
962 for(p = vstack; p <= vtop; p++) {
963 if ((p->r & VT_VALMASK) == r ||
964 (p->r2 & VT_VALMASK) == r)
965 n++;
967 if (n <= 1)
968 return r;
971 return get_reg(rc);
973 #endif
975 /* find a free register of class 'rc'. If none, save one register */
976 ST_FUNC int get_reg(int rc)
978 int r;
979 SValue *p;
981 /* find a free register */
982 for(r=0;r<NB_REGS;r++) {
983 if (reg_classes[r] & rc) {
984 if (nocode_wanted)
985 return r;
986 for(p=vstack;p<=vtop;p++) {
987 if ((p->r & VT_VALMASK) == r ||
988 (p->r2 & VT_VALMASK) == r)
989 goto notfound;
991 return r;
993 notfound: ;
996 /* no register left : free the first one on the stack (VERY
997 IMPORTANT to start from the bottom to ensure that we don't
998 spill registers used in gen_opi()) */
999 for(p=vstack;p<=vtop;p++) {
1000 /* look at second register (if long long) */
1001 r = p->r2 & VT_VALMASK;
1002 if (r < VT_CONST && (reg_classes[r] & rc))
1003 goto save_found;
1004 r = p->r & VT_VALMASK;
1005 if (r < VT_CONST && (reg_classes[r] & rc)) {
1006 save_found:
1007 save_reg(r);
1008 return r;
1011 /* Should never comes here */
1012 return -1;
1015 /* move register 's' (of type 't') to 'r', and flush previous value of r to memory
1016 if needed */
1017 static void move_reg(int r, int s, int t)
1019 SValue sv;
1021 if (r != s) {
1022 save_reg(r);
1023 sv.type.t = t;
1024 sv.type.ref = NULL;
1025 sv.r = s;
1026 sv.c.i = 0;
1027 load(r, &sv);
1031 /* get address of vtop (vtop MUST BE an lvalue) */
1032 ST_FUNC void gaddrof(void)
1034 vtop->r &= ~VT_LVAL;
1035 /* tricky: if saved lvalue, then we can go back to lvalue */
1036 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
1037 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
1042 #ifdef CONFIG_TCC_BCHECK
1043 /* generate lvalue bound code */
1044 static void gbound(void)
1046 int lval_type;
1047 CType type1;
1049 vtop->r &= ~VT_MUSTBOUND;
1050 /* if lvalue, then use checking code before dereferencing */
1051 if (vtop->r & VT_LVAL) {
1052 /* if not VT_BOUNDED value, then make one */
1053 if (!(vtop->r & VT_BOUNDED)) {
1054 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
1055 /* must save type because we must set it to int to get pointer */
1056 type1 = vtop->type;
1057 vtop->type.t = VT_PTR;
1058 gaddrof();
1059 vpushi(0);
1060 gen_bounded_ptr_add();
1061 vtop->r |= lval_type;
1062 vtop->type = type1;
1064 /* then check for dereferencing */
1065 gen_bounded_ptr_deref();
1068 #endif
1070 static void incr_bf_adr(int o)
1072 vtop->type = char_pointer_type;
1073 gaddrof();
1074 vpushi(o);
1075 gen_op('+');
1076 vtop->type.t = (vtop->type.t & ~(VT_BTYPE|VT_DEFSIGN))
1077 | (VT_BYTE|VT_UNSIGNED);
1078 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
1079 | (VT_LVAL_BYTE|VT_LVAL_UNSIGNED|VT_LVAL);
1082 /* single-byte load mode for packed or otherwise unaligned bitfields */
1083 static void load_packed_bf(CType *type, int bit_pos, int bit_size)
1085 int n, o, bits;
1086 save_reg_upstack(vtop->r, 1);
1087 vpush64(type->t & VT_BTYPE, 0); // B X
1088 bits = 0, o = bit_pos >> 3, bit_pos &= 7;
1089 do {
1090 vswap(); // X B
1091 incr_bf_adr(o);
1092 vdup(); // X B B
1093 n = 8 - bit_pos;
1094 if (n > bit_size)
1095 n = bit_size;
1096 if (bit_pos)
1097 vpushi(bit_pos), gen_op(TOK_SHR), bit_pos = 0; // X B Y
1098 if (n < 8)
1099 vpushi((1 << n) - 1), gen_op('&');
1100 gen_cast(type);
1101 if (bits)
1102 vpushi(bits), gen_op(TOK_SHL);
1103 vrotb(3); // B Y X
1104 gen_op('|'); // B X
1105 bits += n, bit_size -= n, o = 1;
1106 } while (bit_size);
1107 vswap(), vpop();
1108 if (!(type->t & VT_UNSIGNED)) {
1109 n = ((type->t & VT_BTYPE) == VT_LLONG ? 64 : 32) - bits;
1110 vpushi(n), gen_op(TOK_SHL);
1111 vpushi(n), gen_op(TOK_SAR);
1115 /* single-byte store mode for packed or otherwise unaligned bitfields */
1116 static void store_packed_bf(int bit_pos, int bit_size)
1118 int bits, n, o, m, c;
1120 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1121 vswap(); // X B
1122 save_reg_upstack(vtop->r, 1);
1123 bits = 0, o = bit_pos >> 3, bit_pos &= 7;
1124 do {
1125 incr_bf_adr(o); // X B
1126 vswap(); //B X
1127 c ? vdup() : gv_dup(); // B V X
1128 vrott(3); // X B V
1129 if (bits)
1130 vpushi(bits), gen_op(TOK_SHR);
1131 if (bit_pos)
1132 vpushi(bit_pos), gen_op(TOK_SHL);
1133 n = 8 - bit_pos;
1134 if (n > bit_size)
1135 n = bit_size;
1136 if (n < 8) {
1137 m = ((1 << n) - 1) << bit_pos;
1138 vpushi(m), gen_op('&'); // X B V1
1139 vpushv(vtop-1); // X B V1 B
1140 vpushi(m & 0x80 ? ~m & 0x7f : ~m);
1141 gen_op('&'); // X B V1 B1
1142 gen_op('|'); // X B V2
1144 vdup(), vtop[-1] = vtop[-2]; // X B B V2
1145 vstore(), vpop(); // X B
1146 bits += n, bit_size -= n, bit_pos = 0, o = 1;
1147 } while (bit_size);
1148 vpop(), vpop();
1151 static int adjust_bf(SValue *sv, int bit_pos, int bit_size)
1153 int t;
1154 if (0 == sv->type.ref)
1155 return 0;
1156 t = sv->type.ref->auxtype;
1157 if (t != -1 && t != VT_STRUCT) {
1158 sv->type.t = (sv->type.t & ~VT_BTYPE) | t;
1159 sv->r = (sv->r & ~VT_LVAL_TYPE) | lvalue_type(sv->type.t);
1161 return t;
1164 /* store vtop a register belonging to class 'rc'. lvalues are
1165 converted to values. Cannot be used if cannot be converted to
1166 register value (such as structures). */
1167 ST_FUNC int gv(int rc)
1169 int r, bit_pos, bit_size, size, align, rc2;
1171 /* NOTE: get_reg can modify vstack[] */
1172 if (vtop->type.t & VT_BITFIELD) {
1173 CType type;
1175 bit_pos = BIT_POS(vtop->type.t);
1176 bit_size = BIT_SIZE(vtop->type.t);
1177 /* remove bit field info to avoid loops */
1178 vtop->type.t &= ~VT_STRUCT_MASK;
1180 type.ref = NULL;
1181 type.t = vtop->type.t & VT_UNSIGNED;
1182 if ((vtop->type.t & VT_BTYPE) == VT_BOOL)
1183 type.t |= VT_UNSIGNED;
1185 r = adjust_bf(vtop, bit_pos, bit_size);
1187 if ((vtop->type.t & VT_BTYPE) == VT_LLONG)
1188 type.t |= VT_LLONG;
1189 else
1190 type.t |= VT_INT;
1192 if (r == VT_STRUCT) {
1193 load_packed_bf(&type, bit_pos, bit_size);
1194 } else {
1195 int bits = (type.t & VT_BTYPE) == VT_LLONG ? 64 : 32;
1196 /* cast to int to propagate signedness in following ops */
1197 gen_cast(&type);
1198 /* generate shifts */
1199 vpushi(bits - (bit_pos + bit_size));
1200 gen_op(TOK_SHL);
1201 vpushi(bits - bit_size);
1202 /* NOTE: transformed to SHR if unsigned */
1203 gen_op(TOK_SAR);
1205 r = gv(rc);
1206 } else {
1207 if (is_float(vtop->type.t) &&
1208 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
1209 unsigned long offset;
1210 /* CPUs usually cannot use float constants, so we store them
1211 generically in data segment */
1212 size = type_size(&vtop->type, &align);
1213 offset = section_add(data_section, size, align);
1214 vpush_ref(&vtop->type, data_section, offset, size);
1215 vswap();
1216 init_putv(&vtop->type, data_section, offset);
1217 vtop->r |= VT_LVAL;
1219 #ifdef CONFIG_TCC_BCHECK
1220 if (vtop->r & VT_MUSTBOUND)
1221 gbound();
1222 #endif
1224 r = vtop->r & VT_VALMASK;
1225 rc2 = (rc & RC_FLOAT) ? RC_FLOAT : RC_INT;
1226 #ifndef TCC_TARGET_ARM64
1227 if (rc == RC_IRET)
1228 rc2 = RC_LRET;
1229 #ifdef TCC_TARGET_X86_64
1230 else if (rc == RC_FRET)
1231 rc2 = RC_QRET;
1232 #endif
1233 #endif
1234 /* need to reload if:
1235 - constant
1236 - lvalue (need to dereference pointer)
1237 - already a register, but not in the right class */
1238 if (r >= VT_CONST
1239 || (vtop->r & VT_LVAL)
1240 || !(reg_classes[r] & rc)
1241 #if PTR_SIZE == 8
1242 || ((vtop->type.t & VT_BTYPE) == VT_QLONG && !(reg_classes[vtop->r2] & rc2))
1243 || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT && !(reg_classes[vtop->r2] & rc2))
1244 #else
1245 || ((vtop->type.t & VT_BTYPE) == VT_LLONG && !(reg_classes[vtop->r2] & rc2))
1246 #endif
1249 r = get_reg(rc);
1250 #if PTR_SIZE == 8
1251 if (((vtop->type.t & VT_BTYPE) == VT_QLONG) || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT)) {
1252 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
1253 #else
1254 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
1255 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
1256 unsigned long long ll;
1257 #endif
1258 int r2, original_type;
1259 original_type = vtop->type.t;
1260 /* two register type load : expand to two words
1261 temporarily */
1262 #if PTR_SIZE == 4
1263 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
1264 /* load constant */
1265 ll = vtop->c.i;
1266 vtop->c.i = ll; /* first word */
1267 load(r, vtop);
1268 vtop->r = r; /* save register value */
1269 vpushi(ll >> 32); /* second word */
1270 } else
1271 #endif
1272 if (vtop->r & VT_LVAL) {
1273 /* We do not want to modifier the long long
1274 pointer here, so the safest (and less
1275 efficient) is to save all the other registers
1276 in the stack. XXX: totally inefficient. */
1277 #if 0
1278 save_regs(1);
1279 #else
1280 /* lvalue_save: save only if used further down the stack */
1281 save_reg_upstack(vtop->r, 1);
1282 #endif
1283 /* load from memory */
1284 vtop->type.t = load_type;
1285 load(r, vtop);
1286 vdup();
1287 vtop[-1].r = r; /* save register value */
1288 /* increment pointer to get second word */
1289 vtop->type.t = addr_type;
1290 gaddrof();
1291 vpushi(load_size);
1292 gen_op('+');
1293 vtop->r |= VT_LVAL;
1294 vtop->type.t = load_type;
1295 } else {
1296 /* move registers */
1297 load(r, vtop);
1298 vdup();
1299 vtop[-1].r = r; /* save register value */
1300 vtop->r = vtop[-1].r2;
1302 /* Allocate second register. Here we rely on the fact that
1303 get_reg() tries first to free r2 of an SValue. */
1304 r2 = get_reg(rc2);
1305 load(r2, vtop);
1306 vpop();
1307 /* write second register */
1308 vtop->r2 = r2;
1309 vtop->type.t = original_type;
1310 } else if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
1311 int t1, t;
1312 /* lvalue of scalar type : need to use lvalue type
1313 because of possible cast */
1314 t = vtop->type.t;
1315 t1 = t;
1316 /* compute memory access type */
1317 if (vtop->r & VT_LVAL_BYTE)
1318 t = VT_BYTE;
1319 else if (vtop->r & VT_LVAL_SHORT)
1320 t = VT_SHORT;
1321 if (vtop->r & VT_LVAL_UNSIGNED)
1322 t |= VT_UNSIGNED;
1323 vtop->type.t = t;
1324 load(r, vtop);
1325 /* restore wanted type */
1326 vtop->type.t = t1;
1327 } else {
1328 /* one register type load */
1329 load(r, vtop);
1332 vtop->r = r;
1333 #ifdef TCC_TARGET_C67
1334 /* uses register pairs for doubles */
1335 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
1336 vtop->r2 = r+1;
1337 #endif
1339 return r;
1342 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
1343 ST_FUNC void gv2(int rc1, int rc2)
1345 int v;
1347 /* generate more generic register first. But VT_JMP or VT_CMP
1348 values must be generated first in all cases to avoid possible
1349 reload errors */
1350 v = vtop[0].r & VT_VALMASK;
1351 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
1352 vswap();
1353 gv(rc1);
1354 vswap();
1355 gv(rc2);
1356 /* test if reload is needed for first register */
1357 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
1358 vswap();
1359 gv(rc1);
1360 vswap();
1362 } else {
1363 gv(rc2);
1364 vswap();
1365 gv(rc1);
1366 vswap();
1367 /* test if reload is needed for first register */
1368 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
1369 gv(rc2);
1374 #ifndef TCC_TARGET_ARM64
1375 /* wrapper around RC_FRET to return a register by type */
1376 static int rc_fret(int t)
1378 #ifdef TCC_TARGET_X86_64
1379 if (t == VT_LDOUBLE) {
1380 return RC_ST0;
1382 #endif
1383 return RC_FRET;
1385 #endif
1387 /* wrapper around REG_FRET to return a register by type */
1388 static int reg_fret(int t)
1390 #ifdef TCC_TARGET_X86_64
1391 if (t == VT_LDOUBLE) {
1392 return TREG_ST0;
1394 #endif
1395 return REG_FRET;
1398 #if PTR_SIZE == 4
1399 /* expand 64bit on stack in two ints */
1400 static void lexpand(void)
1402 int u, v;
1403 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
1404 v = vtop->r & (VT_VALMASK | VT_LVAL);
1405 if (v == VT_CONST) {
1406 vdup();
1407 vtop[0].c.i >>= 32;
1408 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
1409 vdup();
1410 vtop[0].c.i += 4;
1411 } else {
1412 gv(RC_INT);
1413 vdup();
1414 vtop[0].r = vtop[-1].r2;
1415 vtop[0].r2 = vtop[-1].r2 = VT_CONST;
1417 vtop[0].type.t = vtop[-1].type.t = VT_INT | u;
1419 #endif
1421 #ifdef TCC_TARGET_ARM
1422 /* expand long long on stack */
1423 ST_FUNC void lexpand_nr(void)
1425 int u,v;
1427 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
1428 vdup();
1429 vtop->r2 = VT_CONST;
1430 vtop->type.t = VT_INT | u;
1431 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
1432 if (v == VT_CONST) {
1433 vtop[-1].c.i = vtop->c.i;
1434 vtop->c.i = vtop->c.i >> 32;
1435 vtop->r = VT_CONST;
1436 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
1437 vtop->c.i += 4;
1438 vtop->r = vtop[-1].r;
1439 } else if (v > VT_CONST) {
1440 vtop--;
1441 lexpand();
1442 } else
1443 vtop->r = vtop[-1].r2;
1444 vtop[-1].r2 = VT_CONST;
1445 vtop[-1].type.t = VT_INT | u;
1447 #endif
1449 #if PTR_SIZE == 4
1450 /* build a long long from two ints */
1451 static void lbuild(int t)
1453 gv2(RC_INT, RC_INT);
1454 vtop[-1].r2 = vtop[0].r;
1455 vtop[-1].type.t = t;
1456 vpop();
1458 #endif
1460 /* convert stack entry to register and duplicate its value in another
1461 register */
1462 static void gv_dup(void)
1464 int rc, t, r, r1;
1465 SValue sv;
1467 t = vtop->type.t;
1468 #if PTR_SIZE == 4
1469 if ((t & VT_BTYPE) == VT_LLONG) {
1470 if (t & VT_BITFIELD) {
1471 gv(RC_INT);
1472 t = vtop->type.t;
1474 lexpand();
1475 gv_dup();
1476 vswap();
1477 vrotb(3);
1478 gv_dup();
1479 vrotb(4);
1480 /* stack: H L L1 H1 */
1481 lbuild(t);
1482 vrotb(3);
1483 vrotb(3);
1484 vswap();
1485 lbuild(t);
1486 vswap();
1487 } else
1488 #endif
1490 /* duplicate value */
1491 rc = RC_INT;
1492 sv.type.t = VT_INT;
1493 if (is_float(t)) {
1494 rc = RC_FLOAT;
1495 #ifdef TCC_TARGET_X86_64
1496 if ((t & VT_BTYPE) == VT_LDOUBLE) {
1497 rc = RC_ST0;
1499 #endif
1500 sv.type.t = t;
1502 r = gv(rc);
1503 r1 = get_reg(rc);
1504 sv.r = r;
1505 sv.c.i = 0;
1506 load(r1, &sv); /* move r to r1 */
1507 vdup();
1508 /* duplicates value */
1509 if (r != r1)
1510 vtop->r = r1;
1514 /* Generate value test
1516 * Generate a test for any value (jump, comparison and integers) */
1517 ST_FUNC int gvtst(int inv, int t)
1519 int v = vtop->r & VT_VALMASK;
1520 if (v != VT_CMP && v != VT_JMP && v != VT_JMPI) {
1521 vpushi(0);
1522 gen_op(TOK_NE);
1524 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1525 /* constant jmp optimization */
1526 if ((vtop->c.i != 0) != inv)
1527 t = gjmp(t);
1528 vtop--;
1529 return t;
1531 return gtst(inv, t);
1534 #if PTR_SIZE == 4
1535 /* generate CPU independent (unsigned) long long operations */
1536 static void gen_opl(int op)
1538 int t, a, b, op1, c, i;
1539 int func;
1540 unsigned short reg_iret = REG_IRET;
1541 unsigned short reg_lret = REG_LRET;
1542 SValue tmp;
1544 switch(op) {
1545 case '/':
1546 case TOK_PDIV:
1547 func = TOK___divdi3;
1548 goto gen_func;
1549 case TOK_UDIV:
1550 func = TOK___udivdi3;
1551 goto gen_func;
1552 case '%':
1553 func = TOK___moddi3;
1554 goto gen_mod_func;
1555 case TOK_UMOD:
1556 func = TOK___umoddi3;
1557 gen_mod_func:
1558 #ifdef TCC_ARM_EABI
1559 reg_iret = TREG_R2;
1560 reg_lret = TREG_R3;
1561 #endif
1562 gen_func:
1563 /* call generic long long function */
1564 vpush_global_sym(&func_old_type, func);
1565 vrott(3);
1566 gfunc_call(2);
1567 vpushi(0);
1568 vtop->r = reg_iret;
1569 vtop->r2 = reg_lret;
1570 break;
1571 case '^':
1572 case '&':
1573 case '|':
1574 case '*':
1575 case '+':
1576 case '-':
1577 //pv("gen_opl A",0,2);
1578 t = vtop->type.t;
1579 vswap();
1580 lexpand();
1581 vrotb(3);
1582 lexpand();
1583 /* stack: L1 H1 L2 H2 */
1584 tmp = vtop[0];
1585 vtop[0] = vtop[-3];
1586 vtop[-3] = tmp;
1587 tmp = vtop[-2];
1588 vtop[-2] = vtop[-3];
1589 vtop[-3] = tmp;
1590 vswap();
1591 /* stack: H1 H2 L1 L2 */
1592 //pv("gen_opl B",0,4);
1593 if (op == '*') {
1594 vpushv(vtop - 1);
1595 vpushv(vtop - 1);
1596 gen_op(TOK_UMULL);
1597 lexpand();
1598 /* stack: H1 H2 L1 L2 ML MH */
1599 for(i=0;i<4;i++)
1600 vrotb(6);
1601 /* stack: ML MH H1 H2 L1 L2 */
1602 tmp = vtop[0];
1603 vtop[0] = vtop[-2];
1604 vtop[-2] = tmp;
1605 /* stack: ML MH H1 L2 H2 L1 */
1606 gen_op('*');
1607 vrotb(3);
1608 vrotb(3);
1609 gen_op('*');
1610 /* stack: ML MH M1 M2 */
1611 gen_op('+');
1612 gen_op('+');
1613 } else if (op == '+' || op == '-') {
1614 /* XXX: add non carry method too (for MIPS or alpha) */
1615 if (op == '+')
1616 op1 = TOK_ADDC1;
1617 else
1618 op1 = TOK_SUBC1;
1619 gen_op(op1);
1620 /* stack: H1 H2 (L1 op L2) */
1621 vrotb(3);
1622 vrotb(3);
1623 gen_op(op1 + 1); /* TOK_xxxC2 */
1624 } else {
1625 gen_op(op);
1626 /* stack: H1 H2 (L1 op L2) */
1627 vrotb(3);
1628 vrotb(3);
1629 /* stack: (L1 op L2) H1 H2 */
1630 gen_op(op);
1631 /* stack: (L1 op L2) (H1 op H2) */
1633 /* stack: L H */
1634 lbuild(t);
1635 break;
1636 case TOK_SAR:
1637 case TOK_SHR:
1638 case TOK_SHL:
1639 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1640 t = vtop[-1].type.t;
1641 vswap();
1642 lexpand();
1643 vrotb(3);
1644 /* stack: L H shift */
1645 c = (int)vtop->c.i;
1646 /* constant: simpler */
1647 /* NOTE: all comments are for SHL. the other cases are
1648 done by swapping words */
1649 vpop();
1650 if (op != TOK_SHL)
1651 vswap();
1652 if (c >= 32) {
1653 /* stack: L H */
1654 vpop();
1655 if (c > 32) {
1656 vpushi(c - 32);
1657 gen_op(op);
1659 if (op != TOK_SAR) {
1660 vpushi(0);
1661 } else {
1662 gv_dup();
1663 vpushi(31);
1664 gen_op(TOK_SAR);
1666 vswap();
1667 } else {
1668 vswap();
1669 gv_dup();
1670 /* stack: H L L */
1671 vpushi(c);
1672 gen_op(op);
1673 vswap();
1674 vpushi(32 - c);
1675 if (op == TOK_SHL)
1676 gen_op(TOK_SHR);
1677 else
1678 gen_op(TOK_SHL);
1679 vrotb(3);
1680 /* stack: L L H */
1681 vpushi(c);
1682 if (op == TOK_SHL)
1683 gen_op(TOK_SHL);
1684 else
1685 gen_op(TOK_SHR);
1686 gen_op('|');
1688 if (op != TOK_SHL)
1689 vswap();
1690 lbuild(t);
1691 } else {
1692 /* XXX: should provide a faster fallback on x86 ? */
1693 switch(op) {
1694 case TOK_SAR:
1695 func = TOK___ashrdi3;
1696 goto gen_func;
1697 case TOK_SHR:
1698 func = TOK___lshrdi3;
1699 goto gen_func;
1700 case TOK_SHL:
1701 func = TOK___ashldi3;
1702 goto gen_func;
1705 break;
1706 default:
1707 /* compare operations */
1708 t = vtop->type.t;
1709 vswap();
1710 lexpand();
1711 vrotb(3);
1712 lexpand();
1713 /* stack: L1 H1 L2 H2 */
1714 tmp = vtop[-1];
1715 vtop[-1] = vtop[-2];
1716 vtop[-2] = tmp;
1717 /* stack: L1 L2 H1 H2 */
1718 /* compare high */
1719 op1 = op;
1720 /* when values are equal, we need to compare low words. since
1721 the jump is inverted, we invert the test too. */
1722 if (op1 == TOK_LT)
1723 op1 = TOK_LE;
1724 else if (op1 == TOK_GT)
1725 op1 = TOK_GE;
1726 else if (op1 == TOK_ULT)
1727 op1 = TOK_ULE;
1728 else if (op1 == TOK_UGT)
1729 op1 = TOK_UGE;
1730 a = 0;
1731 b = 0;
1732 gen_op(op1);
1733 if (op == TOK_NE) {
1734 b = gvtst(0, 0);
1735 } else {
1736 a = gvtst(1, 0);
1737 if (op != TOK_EQ) {
1738 /* generate non equal test */
1739 vpushi(TOK_NE);
1740 vtop->r = VT_CMP;
1741 b = gvtst(0, 0);
1744 /* compare low. Always unsigned */
1745 op1 = op;
1746 if (op1 == TOK_LT)
1747 op1 = TOK_ULT;
1748 else if (op1 == TOK_LE)
1749 op1 = TOK_ULE;
1750 else if (op1 == TOK_GT)
1751 op1 = TOK_UGT;
1752 else if (op1 == TOK_GE)
1753 op1 = TOK_UGE;
1754 gen_op(op1);
1755 a = gvtst(1, a);
1756 gsym(b);
1757 vseti(VT_JMPI, a);
1758 break;
1761 #endif
1763 static uint64_t gen_opic_sdiv(uint64_t a, uint64_t b)
1765 uint64_t x = (a >> 63 ? -a : a) / (b >> 63 ? -b : b);
1766 return (a ^ b) >> 63 ? -x : x;
1769 static int gen_opic_lt(uint64_t a, uint64_t b)
1771 return (a ^ (uint64_t)1 << 63) < (b ^ (uint64_t)1 << 63);
1774 /* handle integer constant optimizations and various machine
1775 independent opt */
1776 static void gen_opic(int op)
1778 SValue *v1 = vtop - 1;
1779 SValue *v2 = vtop;
1780 int t1 = v1->type.t & VT_BTYPE;
1781 int t2 = v2->type.t & VT_BTYPE;
1782 int c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1783 int c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1784 uint64_t l1 = c1 ? v1->c.i : 0;
1785 uint64_t l2 = c2 ? v2->c.i : 0;
1786 int shm = (t1 == VT_LLONG) ? 63 : 31;
1788 if (t1 != VT_LLONG && (PTR_SIZE != 8 || t1 != VT_PTR))
1789 l1 = ((uint32_t)l1 |
1790 (v1->type.t & VT_UNSIGNED ? 0 : -(l1 & 0x80000000)));
1791 if (t2 != VT_LLONG && (PTR_SIZE != 8 || t2 != VT_PTR))
1792 l2 = ((uint32_t)l2 |
1793 (v2->type.t & VT_UNSIGNED ? 0 : -(l2 & 0x80000000)));
1795 if (c1 && c2) {
1796 switch(op) {
1797 case '+': l1 += l2; break;
1798 case '-': l1 -= l2; break;
1799 case '&': l1 &= l2; break;
1800 case '^': l1 ^= l2; break;
1801 case '|': l1 |= l2; break;
1802 case '*': l1 *= l2; break;
1804 case TOK_PDIV:
1805 case '/':
1806 case '%':
1807 case TOK_UDIV:
1808 case TOK_UMOD:
1809 /* if division by zero, generate explicit division */
1810 if (l2 == 0) {
1811 if (const_wanted)
1812 tcc_error("division by zero in constant");
1813 goto general_case;
1815 switch(op) {
1816 default: l1 = gen_opic_sdiv(l1, l2); break;
1817 case '%': l1 = l1 - l2 * gen_opic_sdiv(l1, l2); break;
1818 case TOK_UDIV: l1 = l1 / l2; break;
1819 case TOK_UMOD: l1 = l1 % l2; break;
1821 break;
1822 case TOK_SHL: l1 <<= (l2 & shm); break;
1823 case TOK_SHR: l1 >>= (l2 & shm); break;
1824 case TOK_SAR:
1825 l1 = (l1 >> 63) ? ~(~l1 >> (l2 & shm)) : l1 >> (l2 & shm);
1826 break;
1827 /* tests */
1828 case TOK_ULT: l1 = l1 < l2; break;
1829 case TOK_UGE: l1 = l1 >= l2; break;
1830 case TOK_EQ: l1 = l1 == l2; break;
1831 case TOK_NE: l1 = l1 != l2; break;
1832 case TOK_ULE: l1 = l1 <= l2; break;
1833 case TOK_UGT: l1 = l1 > l2; break;
1834 case TOK_LT: l1 = gen_opic_lt(l1, l2); break;
1835 case TOK_GE: l1 = !gen_opic_lt(l1, l2); break;
1836 case TOK_LE: l1 = !gen_opic_lt(l2, l1); break;
1837 case TOK_GT: l1 = gen_opic_lt(l2, l1); break;
1838 /* logical */
1839 case TOK_LAND: l1 = l1 && l2; break;
1840 case TOK_LOR: l1 = l1 || l2; break;
1841 default:
1842 goto general_case;
1844 if (t1 != VT_LLONG && (PTR_SIZE != 8 || t1 != VT_PTR))
1845 l1 = ((uint32_t)l1 |
1846 (v1->type.t & VT_UNSIGNED ? 0 : -(l1 & 0x80000000)));
1847 v1->c.i = l1;
1848 vtop--;
1849 } else {
1850 /* if commutative ops, put c2 as constant */
1851 if (c1 && (op == '+' || op == '&' || op == '^' ||
1852 op == '|' || op == '*')) {
1853 vswap();
1854 c2 = c1; //c = c1, c1 = c2, c2 = c;
1855 l2 = l1; //l = l1, l1 = l2, l2 = l;
1857 if (!const_wanted &&
1858 c1 && ((l1 == 0 &&
1859 (op == TOK_SHL || op == TOK_SHR || op == TOK_SAR)) ||
1860 (l1 == -1 && op == TOK_SAR))) {
1861 /* treat (0 << x), (0 >> x) and (-1 >> x) as constant */
1862 vtop--;
1863 } else if (!const_wanted &&
1864 c2 && ((l2 == 0 && (op == '&' || op == '*')) ||
1865 (op == '|' &&
1866 (l2 == -1 || (l2 == 0xFFFFFFFF && t2 != VT_LLONG))) ||
1867 (l2 == 1 && (op == '%' || op == TOK_UMOD)))) {
1868 /* treat (x & 0), (x * 0), (x | -1) and (x % 1) as constant */
1869 if (l2 == 1)
1870 vtop->c.i = 0;
1871 vswap();
1872 vtop--;
1873 } else if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
1874 op == TOK_PDIV) &&
1875 l2 == 1) ||
1876 ((op == '+' || op == '-' || op == '|' || op == '^' ||
1877 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
1878 l2 == 0) ||
1879 (op == '&' &&
1880 (l2 == -1 || (l2 == 0xFFFFFFFF && t2 != VT_LLONG))))) {
1881 /* filter out NOP operations like x*1, x-0, x&-1... */
1882 vtop--;
1883 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
1884 /* try to use shifts instead of muls or divs */
1885 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
1886 int n = -1;
1887 while (l2) {
1888 l2 >>= 1;
1889 n++;
1891 vtop->c.i = n;
1892 if (op == '*')
1893 op = TOK_SHL;
1894 else if (op == TOK_PDIV)
1895 op = TOK_SAR;
1896 else
1897 op = TOK_SHR;
1899 goto general_case;
1900 } else if (c2 && (op == '+' || op == '-') &&
1901 (((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM))
1902 || (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
1903 /* symbol + constant case */
1904 if (op == '-')
1905 l2 = -l2;
1906 l2 += vtop[-1].c.i;
1907 /* The backends can't always deal with addends to symbols
1908 larger than +-1<<31. Don't construct such. */
1909 if ((int)l2 != l2)
1910 goto general_case;
1911 vtop--;
1912 vtop->c.i = l2;
1913 } else {
1914 general_case:
1915 /* call low level op generator */
1916 if (t1 == VT_LLONG || t2 == VT_LLONG ||
1917 (PTR_SIZE == 8 && (t1 == VT_PTR || t2 == VT_PTR)))
1918 gen_opl(op);
1919 else
1920 gen_opi(op);
1925 /* generate a floating point operation with constant propagation */
1926 static void gen_opif(int op)
1928 int c1, c2;
1929 SValue *v1, *v2;
1930 #if defined _MSC_VER && defined _AMD64_
1931 /* avoid bad optimization with f1 -= f2 for f1:-0.0, f2:0.0 */
1932 volatile
1933 #endif
1934 long double f1, f2;
1936 v1 = vtop - 1;
1937 v2 = vtop;
1938 /* currently, we cannot do computations with forward symbols */
1939 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1940 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1941 if (c1 && c2) {
1942 if (v1->type.t == VT_FLOAT) {
1943 f1 = v1->c.f;
1944 f2 = v2->c.f;
1945 } else if (v1->type.t == VT_DOUBLE) {
1946 f1 = v1->c.d;
1947 f2 = v2->c.d;
1948 } else {
1949 f1 = v1->c.ld;
1950 f2 = v2->c.ld;
1953 /* NOTE: we only do constant propagation if finite number (not
1954 NaN or infinity) (ANSI spec) */
1955 if (!ieee_finite(f1) || !ieee_finite(f2))
1956 goto general_case;
1958 switch(op) {
1959 case '+': f1 += f2; break;
1960 case '-': f1 -= f2; break;
1961 case '*': f1 *= f2; break;
1962 case '/':
1963 if (f2 == 0.0) {
1964 if (const_wanted)
1965 tcc_error("division by zero in constant");
1966 goto general_case;
1968 f1 /= f2;
1969 break;
1970 /* XXX: also handles tests ? */
1971 default:
1972 goto general_case;
1974 /* XXX: overflow test ? */
1975 if (v1->type.t == VT_FLOAT) {
1976 v1->c.f = f1;
1977 } else if (v1->type.t == VT_DOUBLE) {
1978 v1->c.d = f1;
1979 } else {
1980 v1->c.ld = f1;
1982 vtop--;
1983 } else {
1984 general_case:
1985 gen_opf(op);
1989 static int pointed_size(CType *type)
1991 int align;
1992 return type_size(pointed_type(type), &align);
1995 static void vla_runtime_pointed_size(CType *type)
1997 int align;
1998 vla_runtime_type_size(pointed_type(type), &align);
2001 static inline int is_null_pointer(SValue *p)
2003 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
2004 return 0;
2005 return ((p->type.t & VT_BTYPE) == VT_INT && (uint32_t)p->c.i == 0) ||
2006 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.i == 0) ||
2007 ((p->type.t & VT_BTYPE) == VT_PTR &&
2008 (PTR_SIZE == 4 ? (uint32_t)p->c.i == 0 : p->c.i == 0));
2011 static inline int is_integer_btype(int bt)
2013 return (bt == VT_BYTE || bt == VT_SHORT ||
2014 bt == VT_INT || bt == VT_LLONG);
2017 /* check types for comparison or subtraction of pointers */
2018 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
2020 CType *type1, *type2, tmp_type1, tmp_type2;
2021 int bt1, bt2;
2023 /* null pointers are accepted for all comparisons as gcc */
2024 if (is_null_pointer(p1) || is_null_pointer(p2))
2025 return;
2026 type1 = &p1->type;
2027 type2 = &p2->type;
2028 bt1 = type1->t & VT_BTYPE;
2029 bt2 = type2->t & VT_BTYPE;
2030 /* accept comparison between pointer and integer with a warning */
2031 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
2032 if (op != TOK_LOR && op != TOK_LAND )
2033 tcc_warning("comparison between pointer and integer");
2034 return;
2037 /* both must be pointers or implicit function pointers */
2038 if (bt1 == VT_PTR) {
2039 type1 = pointed_type(type1);
2040 } else if (bt1 != VT_FUNC)
2041 goto invalid_operands;
2043 if (bt2 == VT_PTR) {
2044 type2 = pointed_type(type2);
2045 } else if (bt2 != VT_FUNC) {
2046 invalid_operands:
2047 tcc_error("invalid operands to binary %s", get_tok_str(op, NULL));
2049 if ((type1->t & VT_BTYPE) == VT_VOID ||
2050 (type2->t & VT_BTYPE) == VT_VOID)
2051 return;
2052 tmp_type1 = *type1;
2053 tmp_type2 = *type2;
2054 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
2055 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
2056 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2057 /* gcc-like error if '-' is used */
2058 if (op == '-')
2059 goto invalid_operands;
2060 else
2061 tcc_warning("comparison of distinct pointer types lacks a cast");
2065 /* generic gen_op: handles types problems */
2066 ST_FUNC void gen_op(int op)
2068 int u, t1, t2, bt1, bt2, t;
2069 CType type1;
2071 redo:
2072 t1 = vtop[-1].type.t;
2073 t2 = vtop[0].type.t;
2074 bt1 = t1 & VT_BTYPE;
2075 bt2 = t2 & VT_BTYPE;
2077 if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
2078 tcc_error("operation on a struct");
2079 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
2080 if (bt2 == VT_FUNC) {
2081 mk_pointer(&vtop->type);
2082 gaddrof();
2084 if (bt1 == VT_FUNC) {
2085 vswap();
2086 mk_pointer(&vtop->type);
2087 gaddrof();
2088 vswap();
2090 goto redo;
2091 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
2092 /* at least one operand is a pointer */
2093 /* relational op: must be both pointers */
2094 if (op >= TOK_ULT && op <= TOK_LOR) {
2095 check_comparison_pointer_types(vtop - 1, vtop, op);
2096 /* pointers are handled are unsigned */
2097 #if PTR_SIZE == 8
2098 t = VT_LLONG | VT_UNSIGNED;
2099 #else
2100 t = VT_INT | VT_UNSIGNED;
2101 #endif
2102 goto std_op;
2104 /* if both pointers, then it must be the '-' op */
2105 if (bt1 == VT_PTR && bt2 == VT_PTR) {
2106 if (op != '-')
2107 tcc_error("cannot use pointers here");
2108 check_comparison_pointer_types(vtop - 1, vtop, op);
2109 /* XXX: check that types are compatible */
2110 if (vtop[-1].type.t & VT_VLA) {
2111 vla_runtime_pointed_size(&vtop[-1].type);
2112 } else {
2113 vpushi(pointed_size(&vtop[-1].type));
2115 vrott(3);
2116 gen_opic(op);
2117 /* set to integer type */
2118 #if PTR_SIZE == 8
2119 vtop->type.t = VT_LLONG;
2120 #else
2121 vtop->type.t = VT_INT;
2122 #endif
2123 vswap();
2124 gen_op(TOK_PDIV);
2125 } else {
2126 /* exactly one pointer : must be '+' or '-'. */
2127 if (op != '-' && op != '+')
2128 tcc_error("cannot use pointers here");
2129 /* Put pointer as first operand */
2130 if (bt2 == VT_PTR) {
2131 vswap();
2132 t = t1, t1 = t2, t2 = t;
2134 #if PTR_SIZE == 4
2135 if ((vtop[0].type.t & VT_BTYPE) == VT_LLONG)
2136 /* XXX: truncate here because gen_opl can't handle ptr + long long */
2137 gen_cast_s(VT_INT);
2138 #endif
2139 type1 = vtop[-1].type;
2140 type1.t &= ~VT_ARRAY;
2141 if (vtop[-1].type.t & VT_VLA)
2142 vla_runtime_pointed_size(&vtop[-1].type);
2143 else {
2144 u = pointed_size(&vtop[-1].type);
2145 if (u < 0)
2146 tcc_error("unknown array element size");
2147 #if PTR_SIZE == 8
2148 vpushll(u);
2149 #else
2150 /* XXX: cast to int ? (long long case) */
2151 vpushi(u);
2152 #endif
2154 gen_op('*');
2155 #if 0
2156 /* #ifdef CONFIG_TCC_BCHECK
2157 The main reason to removing this code:
2158 #include <stdio.h>
2159 int main ()
2161 int v[10];
2162 int i = 10;
2163 int j = 9;
2164 fprintf(stderr, "v+i-j = %p\n", v+i-j);
2165 fprintf(stderr, "v+(i-j) = %p\n", v+(i-j));
2167 When this code is on. then the output looks like
2168 v+i-j = 0xfffffffe
2169 v+(i-j) = 0xbff84000
2171 /* if evaluating constant expression, no code should be
2172 generated, so no bound check */
2173 if (tcc_state->do_bounds_check && !const_wanted) {
2174 /* if bounded pointers, we generate a special code to
2175 test bounds */
2176 if (op == '-') {
2177 vpushi(0);
2178 vswap();
2179 gen_op('-');
2181 gen_bounded_ptr_add();
2182 } else
2183 #endif
2185 gen_opic(op);
2187 /* put again type if gen_opic() swaped operands */
2188 vtop->type = type1;
2190 } else if (is_float(bt1) || is_float(bt2)) {
2191 /* compute bigger type and do implicit casts */
2192 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
2193 t = VT_LDOUBLE;
2194 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
2195 t = VT_DOUBLE;
2196 } else {
2197 t = VT_FLOAT;
2199 /* floats can only be used for a few operations */
2200 if (op != '+' && op != '-' && op != '*' && op != '/' &&
2201 (op < TOK_ULT || op > TOK_GT))
2202 tcc_error("invalid operands for binary operation");
2203 goto std_op;
2204 } else if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL) {
2205 t = bt1 == VT_LLONG ? VT_LLONG : VT_INT;
2206 if ((t1 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (t | VT_UNSIGNED))
2207 t |= VT_UNSIGNED;
2208 goto std_op;
2209 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
2210 /* cast to biggest op */
2211 t = VT_LLONG;
2212 /* convert to unsigned if it does not fit in a long long */
2213 if ((t1 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_LLONG | VT_UNSIGNED) ||
2214 (t2 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_LLONG | VT_UNSIGNED))
2215 t |= VT_UNSIGNED;
2216 goto std_op;
2217 } else {
2218 /* integer operations */
2219 t = VT_INT;
2220 /* convert to unsigned if it does not fit in an integer */
2221 if ((t1 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_INT | VT_UNSIGNED) ||
2222 (t2 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_INT | VT_UNSIGNED))
2223 t |= VT_UNSIGNED;
2224 std_op:
2225 /* XXX: currently, some unsigned operations are explicit, so
2226 we modify them here */
2227 if (t & VT_UNSIGNED) {
2228 if (op == TOK_SAR)
2229 op = TOK_SHR;
2230 else if (op == '/')
2231 op = TOK_UDIV;
2232 else if (op == '%')
2233 op = TOK_UMOD;
2234 else if (op == TOK_LT)
2235 op = TOK_ULT;
2236 else if (op == TOK_GT)
2237 op = TOK_UGT;
2238 else if (op == TOK_LE)
2239 op = TOK_ULE;
2240 else if (op == TOK_GE)
2241 op = TOK_UGE;
2243 vswap();
2244 type1.t = t;
2245 type1.ref = NULL;
2246 gen_cast(&type1);
2247 vswap();
2248 /* special case for shifts and long long: we keep the shift as
2249 an integer */
2250 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
2251 type1.t = VT_INT;
2252 gen_cast(&type1);
2253 if (is_float(t))
2254 gen_opif(op);
2255 else
2256 gen_opic(op);
2257 if (op >= TOK_ULT && op <= TOK_GT) {
2258 /* relational op: the result is an int */
2259 vtop->type.t = VT_INT;
2260 } else {
2261 vtop->type.t = t;
2264 // Make sure that we have converted to an rvalue:
2265 if (vtop->r & VT_LVAL)
2266 gv(is_float(vtop->type.t & VT_BTYPE) ? RC_FLOAT : RC_INT);
2269 #ifndef TCC_TARGET_ARM
2270 /* generic itof for unsigned long long case */
2271 static void gen_cvt_itof1(int t)
2273 #ifdef TCC_TARGET_ARM64
2274 gen_cvt_itof(t);
2275 #else
2276 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
2277 (VT_LLONG | VT_UNSIGNED)) {
2279 if (t == VT_FLOAT)
2280 vpush_global_sym(&func_old_type, TOK___floatundisf);
2281 #if LDOUBLE_SIZE != 8
2282 else if (t == VT_LDOUBLE)
2283 vpush_global_sym(&func_old_type, TOK___floatundixf);
2284 #endif
2285 else
2286 vpush_global_sym(&func_old_type, TOK___floatundidf);
2287 vrott(2);
2288 gfunc_call(1);
2289 vpushi(0);
2290 vtop->r = reg_fret(t);
2291 } else {
2292 gen_cvt_itof(t);
2294 #endif
2296 #endif
2298 /* generic ftoi for unsigned long long case */
2299 static void gen_cvt_ftoi1(int t)
2301 #ifdef TCC_TARGET_ARM64
2302 gen_cvt_ftoi(t);
2303 #else
2304 int st;
2306 if (t == (VT_LLONG | VT_UNSIGNED)) {
2307 /* not handled natively */
2308 st = vtop->type.t & VT_BTYPE;
2309 if (st == VT_FLOAT)
2310 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
2311 #if LDOUBLE_SIZE != 8
2312 else if (st == VT_LDOUBLE)
2313 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
2314 #endif
2315 else
2316 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
2317 vrott(2);
2318 gfunc_call(1);
2319 vpushi(0);
2320 vtop->r = REG_IRET;
2321 vtop->r2 = REG_LRET;
2322 } else {
2323 gen_cvt_ftoi(t);
2325 #endif
2328 /* force char or short cast */
2329 static void force_charshort_cast(int t)
2331 int bits, dbt;
2332 dbt = t & VT_BTYPE;
2333 /* XXX: add optimization if lvalue : just change type and offset */
2334 if (dbt == VT_BYTE)
2335 bits = 8;
2336 else
2337 bits = 16;
2338 if (t & VT_UNSIGNED) {
2339 vpushi((1 << bits) - 1);
2340 gen_op('&');
2341 } else {
2342 if ((vtop->type.t & VT_BTYPE) == VT_LLONG)
2343 bits = 64 - bits;
2344 else
2345 bits = 32 - bits;
2346 vpushi(bits);
2347 gen_op(TOK_SHL);
2348 /* result must be signed or the SAR is converted to an SHL
2349 This was not the case when "t" was a signed short
2350 and the last value on the stack was an unsigned int */
2351 vtop->type.t &= ~VT_UNSIGNED;
2352 vpushi(bits);
2353 gen_op(TOK_SAR);
2357 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
2358 static void gen_cast_s(int t)
2360 CType type;
2361 type.t = t;
2362 type.ref = NULL;
2363 gen_cast(&type);
2366 static void gen_cast(CType *type)
2368 int sbt, dbt, sf, df, c, p;
2370 /* special delayed cast for char/short */
2371 /* XXX: in some cases (multiple cascaded casts), it may still
2372 be incorrect */
2373 if (vtop->r & VT_MUSTCAST) {
2374 vtop->r &= ~VT_MUSTCAST;
2375 force_charshort_cast(vtop->type.t);
2378 /* bitfields first get cast to ints */
2379 if (vtop->type.t & VT_BITFIELD) {
2380 gv(RC_INT);
2383 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
2384 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
2386 if (sbt != dbt) {
2387 sf = is_float(sbt);
2388 df = is_float(dbt);
2389 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
2390 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
2391 if (c) {
2392 /* constant case: we can do it now */
2393 /* XXX: in ISOC, cannot do it if error in convert */
2394 if (sbt == VT_FLOAT)
2395 vtop->c.ld = vtop->c.f;
2396 else if (sbt == VT_DOUBLE)
2397 vtop->c.ld = vtop->c.d;
2399 if (df) {
2400 if ((sbt & VT_BTYPE) == VT_LLONG) {
2401 if ((sbt & VT_UNSIGNED) || !(vtop->c.i >> 63))
2402 vtop->c.ld = vtop->c.i;
2403 else
2404 vtop->c.ld = -(long double)-vtop->c.i;
2405 } else if(!sf) {
2406 if ((sbt & VT_UNSIGNED) || !(vtop->c.i >> 31))
2407 vtop->c.ld = (uint32_t)vtop->c.i;
2408 else
2409 vtop->c.ld = -(long double)-(uint32_t)vtop->c.i;
2412 if (dbt == VT_FLOAT)
2413 vtop->c.f = (float)vtop->c.ld;
2414 else if (dbt == VT_DOUBLE)
2415 vtop->c.d = (double)vtop->c.ld;
2416 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
2417 vtop->c.i = vtop->c.ld;
2418 } else if (sf && dbt == VT_BOOL) {
2419 vtop->c.i = (vtop->c.ld != 0);
2420 } else {
2421 if(sf)
2422 vtop->c.i = vtop->c.ld;
2423 else if (sbt == (VT_LLONG|VT_UNSIGNED))
2425 else if (sbt & VT_UNSIGNED)
2426 vtop->c.i = (uint32_t)vtop->c.i;
2427 #if PTR_SIZE == 8
2428 else if (sbt == VT_PTR)
2430 #endif
2431 else if (sbt != VT_LLONG)
2432 vtop->c.i = ((uint32_t)vtop->c.i |
2433 -(vtop->c.i & 0x80000000));
2435 if (dbt == (VT_LLONG|VT_UNSIGNED))
2437 else if (dbt == VT_BOOL)
2438 vtop->c.i = (vtop->c.i != 0);
2439 #if PTR_SIZE == 8
2440 else if (dbt == VT_PTR)
2442 #endif
2443 else if (dbt != VT_LLONG) {
2444 uint32_t m = ((dbt & VT_BTYPE) == VT_BYTE ? 0xff :
2445 (dbt & VT_BTYPE) == VT_SHORT ? 0xffff :
2446 0xffffffff);
2447 vtop->c.i &= m;
2448 if (!(dbt & VT_UNSIGNED))
2449 vtop->c.i |= -(vtop->c.i & ((m >> 1) + 1));
2452 } else if (p && dbt == VT_BOOL) {
2453 vtop->r = VT_CONST;
2454 vtop->c.i = 1;
2455 } else {
2456 /* non constant case: generate code */
2457 if (sf && df) {
2458 /* convert from fp to fp */
2459 gen_cvt_ftof(dbt);
2460 } else if (df) {
2461 /* convert int to fp */
2462 gen_cvt_itof1(dbt);
2463 } else if (sf) {
2464 /* convert fp to int */
2465 if (dbt == VT_BOOL) {
2466 vpushi(0);
2467 gen_op(TOK_NE);
2468 } else {
2469 /* we handle char/short/etc... with generic code */
2470 if (dbt != (VT_INT | VT_UNSIGNED) &&
2471 dbt != (VT_LLONG | VT_UNSIGNED) &&
2472 dbt != VT_LLONG)
2473 dbt = VT_INT;
2474 gen_cvt_ftoi1(dbt);
2475 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
2476 /* additional cast for char/short... */
2477 vtop->type.t = dbt;
2478 gen_cast(type);
2481 #if PTR_SIZE == 4
2482 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
2483 if ((sbt & VT_BTYPE) != VT_LLONG) {
2484 /* scalar to long long */
2485 /* machine independent conversion */
2486 gv(RC_INT);
2487 /* generate high word */
2488 if (sbt == (VT_INT | VT_UNSIGNED)) {
2489 vpushi(0);
2490 gv(RC_INT);
2491 } else {
2492 if (sbt == VT_PTR) {
2493 /* cast from pointer to int before we apply
2494 shift operation, which pointers don't support*/
2495 gen_cast_s(VT_INT);
2497 gv_dup();
2498 vpushi(31);
2499 gen_op(TOK_SAR);
2501 /* patch second register */
2502 vtop[-1].r2 = vtop->r;
2503 vpop();
2505 #else
2506 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
2507 (dbt & VT_BTYPE) == VT_PTR ||
2508 (dbt & VT_BTYPE) == VT_FUNC) {
2509 if ((sbt & VT_BTYPE) != VT_LLONG &&
2510 (sbt & VT_BTYPE) != VT_PTR &&
2511 (sbt & VT_BTYPE) != VT_FUNC) {
2512 /* need to convert from 32bit to 64bit */
2513 gv(RC_INT);
2514 if (sbt != (VT_INT | VT_UNSIGNED)) {
2515 #if defined(TCC_TARGET_ARM64)
2516 gen_cvt_sxtw();
2517 #elif defined(TCC_TARGET_X86_64)
2518 int r = gv(RC_INT);
2519 /* x86_64 specific: movslq */
2520 o(0x6348);
2521 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
2522 #else
2523 #error
2524 #endif
2527 #endif
2528 } else if (dbt == VT_BOOL) {
2529 /* scalar to bool */
2530 vpushi(0);
2531 gen_op(TOK_NE);
2532 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
2533 (dbt & VT_BTYPE) == VT_SHORT) {
2534 if (sbt == VT_PTR) {
2535 vtop->type.t = VT_INT;
2536 tcc_warning("nonportable conversion from pointer to char/short");
2538 force_charshort_cast(dbt);
2539 #if PTR_SIZE == 4
2540 } else if ((dbt & VT_BTYPE) == VT_INT) {
2541 /* scalar to int */
2542 if ((sbt & VT_BTYPE) == VT_LLONG) {
2543 /* from long long: just take low order word */
2544 lexpand();
2545 vpop();
2547 /* if lvalue and single word type, nothing to do because
2548 the lvalue already contains the real type size (see
2549 VT_LVAL_xxx constants) */
2550 #endif
2553 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
2554 /* if we are casting between pointer types,
2555 we must update the VT_LVAL_xxx size */
2556 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
2557 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
2559 vtop->type = *type;
2562 /* return type size as known at compile time. Put alignment at 'a' */
2563 ST_FUNC int type_size(CType *type, int *a)
2565 Sym *s;
2566 int bt;
2568 bt = type->t & VT_BTYPE;
2569 if (bt == VT_STRUCT) {
2570 /* struct/union */
2571 s = type->ref;
2572 *a = s->r;
2573 return s->c;
2574 } else if (bt == VT_PTR) {
2575 if (type->t & VT_ARRAY) {
2576 int ts;
2578 s = type->ref;
2579 ts = type_size(&s->type, a);
2581 if (ts < 0 && s->c < 0)
2582 ts = -ts;
2584 return ts * s->c;
2585 } else {
2586 *a = PTR_SIZE;
2587 return PTR_SIZE;
2589 } else if (IS_ENUM(type->t) && type->ref->c == -1) {
2590 return -1; /* incomplete enum */
2591 } else if (bt == VT_LDOUBLE) {
2592 *a = LDOUBLE_ALIGN;
2593 return LDOUBLE_SIZE;
2594 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
2595 #ifdef TCC_TARGET_I386
2596 #ifdef TCC_TARGET_PE
2597 *a = 8;
2598 #else
2599 *a = 4;
2600 #endif
2601 #elif defined(TCC_TARGET_ARM)
2602 #ifdef TCC_ARM_EABI
2603 *a = 8;
2604 #else
2605 *a = 4;
2606 #endif
2607 #else
2608 *a = 8;
2609 #endif
2610 return 8;
2611 } else if (bt == VT_INT || bt == VT_FLOAT) {
2612 *a = 4;
2613 return 4;
2614 } else if (bt == VT_SHORT) {
2615 *a = 2;
2616 return 2;
2617 } else if (bt == VT_QLONG || bt == VT_QFLOAT) {
2618 *a = 8;
2619 return 16;
2620 } else {
2621 /* char, void, function, _Bool */
2622 *a = 1;
2623 return 1;
2627 /* push type size as known at runtime time on top of value stack. Put
2628 alignment at 'a' */
2629 ST_FUNC void vla_runtime_type_size(CType *type, int *a)
2631 if (type->t & VT_VLA) {
2632 type_size(&type->ref->type, a);
2633 vset(&int_type, VT_LOCAL|VT_LVAL, type->ref->c);
2634 } else {
2635 vpushi(type_size(type, a));
2639 static void vla_sp_restore(void) {
2640 if (vlas_in_scope) {
2641 gen_vla_sp_restore(vla_sp_loc);
2645 static void vla_sp_restore_root(void) {
2646 if (vlas_in_scope) {
2647 gen_vla_sp_restore(vla_sp_root_loc);
2651 /* return the pointed type of t */
2652 static inline CType *pointed_type(CType *type)
2654 return &type->ref->type;
2657 /* modify type so that its it is a pointer to type. */
2658 ST_FUNC void mk_pointer(CType *type)
2660 Sym *s;
2661 s = sym_push(SYM_FIELD, type, 0, -1);
2662 type->t = VT_PTR | (type->t & VT_STORAGE);
2663 type->ref = s;
2666 /* compare function types. OLD functions match any new functions */
2667 static int is_compatible_func(CType *type1, CType *type2)
2669 Sym *s1, *s2;
2671 s1 = type1->ref;
2672 s2 = type2->ref;
2673 if (!is_compatible_types(&s1->type, &s2->type))
2674 return 0;
2675 /* check func_call */
2676 if (s1->f.func_call != s2->f.func_call)
2677 return 0;
2678 /* XXX: not complete */
2679 if (s1->f.func_type == FUNC_OLD || s2->f.func_type == FUNC_OLD)
2680 return 1;
2681 if (s1->f.func_type != s2->f.func_type)
2682 return 0;
2683 while (s1 != NULL) {
2684 if (s2 == NULL)
2685 return 0;
2686 if (!is_compatible_unqualified_types(&s1->type, &s2->type))
2687 return 0;
2688 s1 = s1->next;
2689 s2 = s2->next;
2691 if (s2)
2692 return 0;
2693 return 1;
2696 /* return true if type1 and type2 are the same. If unqualified is
2697 true, qualifiers on the types are ignored.
2699 - enums are not checked as gcc __builtin_types_compatible_p ()
2701 static int compare_types(CType *type1, CType *type2, int unqualified)
2703 int bt1, t1, t2;
2705 t1 = type1->t & VT_TYPE;
2706 t2 = type2->t & VT_TYPE;
2707 if (unqualified) {
2708 /* strip qualifiers before comparing */
2709 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
2710 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
2712 /* Default Vs explicit signedness only matters for char */
2713 if ((t1 & VT_BTYPE) != VT_BYTE) {
2714 t1 &= ~VT_DEFSIGN;
2715 t2 &= ~VT_DEFSIGN;
2718 /* XXX: bitfields ? */
2719 if (t1 != t2)
2720 return 0;
2721 /* test more complicated cases */
2722 bt1 = t1 & VT_BTYPE;
2723 if (bt1 == VT_PTR) {
2724 type1 = pointed_type(type1);
2725 type2 = pointed_type(type2);
2726 return is_compatible_types(type1, type2);
2727 } else if (bt1 == VT_STRUCT) {
2728 return (type1->ref == type2->ref);
2729 } else if (bt1 == VT_FUNC) {
2730 return is_compatible_func(type1, type2);
2731 } else {
2732 return 1;
2736 /* return true if type1 and type2 are exactly the same (including
2737 qualifiers).
2739 static int is_compatible_types(CType *type1, CType *type2)
2741 return compare_types(type1,type2,0);
2744 /* return true if type1 and type2 are the same (ignoring qualifiers).
2746 static int is_compatible_unqualified_types(CType *type1, CType *type2)
2748 return compare_types(type1,type2,1);
2751 /* print a type. If 'varstr' is not NULL, then the variable is also
2752 printed in the type */
2753 /* XXX: union */
2754 /* XXX: add array and function pointers */
2755 static void type_to_str(char *buf, int buf_size,
2756 CType *type, const char *varstr)
2758 int bt, v, t;
2759 Sym *s, *sa;
2760 char buf1[256];
2761 const char *tstr;
2763 t = type->t;
2764 bt = t & VT_BTYPE;
2765 buf[0] = '\0';
2766 if (t & VT_CONSTANT)
2767 pstrcat(buf, buf_size, "const ");
2768 if (t & VT_VOLATILE)
2769 pstrcat(buf, buf_size, "volatile ");
2770 if ((t & (VT_DEFSIGN | VT_UNSIGNED)) == (VT_DEFSIGN | VT_UNSIGNED))
2771 pstrcat(buf, buf_size, "unsigned ");
2772 else if (t & VT_DEFSIGN)
2773 pstrcat(buf, buf_size, "signed ");
2774 if (t & VT_EXTERN)
2775 pstrcat(buf, buf_size, "extern ");
2776 if (t & VT_STATIC)
2777 pstrcat(buf, buf_size, "static ");
2778 if (t & VT_TYPEDEF)
2779 pstrcat(buf, buf_size, "typedef ");
2780 if (t & VT_INLINE)
2781 pstrcat(buf, buf_size, "inline ");
2782 buf_size -= strlen(buf);
2783 buf += strlen(buf);
2784 if (IS_ENUM(t)) {
2785 tstr = "enum ";
2786 goto tstruct;
2788 switch(bt) {
2789 case VT_VOID:
2790 tstr = "void";
2791 goto add_tstr;
2792 case VT_BOOL:
2793 tstr = "_Bool";
2794 goto add_tstr;
2795 case VT_BYTE:
2796 tstr = "char";
2797 goto add_tstr;
2798 case VT_SHORT:
2799 tstr = "short";
2800 goto add_tstr;
2801 case VT_INT:
2802 tstr = "int";
2803 goto add_tstr;
2804 case VT_LONG:
2805 tstr = "long";
2806 goto add_tstr;
2807 case VT_LLONG:
2808 tstr = "long long";
2809 goto add_tstr;
2810 case VT_FLOAT:
2811 tstr = "float";
2812 goto add_tstr;
2813 case VT_DOUBLE:
2814 tstr = "double";
2815 goto add_tstr;
2816 case VT_LDOUBLE:
2817 tstr = "long double";
2818 add_tstr:
2819 pstrcat(buf, buf_size, tstr);
2820 break;
2821 case VT_STRUCT:
2822 tstr = "struct ";
2823 if (IS_UNION(t))
2824 tstr = "union ";
2825 tstruct:
2826 pstrcat(buf, buf_size, tstr);
2827 v = type->ref->v & ~SYM_STRUCT;
2828 if (v >= SYM_FIRST_ANOM)
2829 pstrcat(buf, buf_size, "<anonymous>");
2830 else
2831 pstrcat(buf, buf_size, get_tok_str(v, NULL));
2832 break;
2833 case VT_FUNC:
2834 s = type->ref;
2835 type_to_str(buf, buf_size, &s->type, varstr);
2836 pstrcat(buf, buf_size, "(");
2837 sa = s->next;
2838 while (sa != NULL) {
2839 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
2840 pstrcat(buf, buf_size, buf1);
2841 sa = sa->next;
2842 if (sa)
2843 pstrcat(buf, buf_size, ", ");
2845 pstrcat(buf, buf_size, ")");
2846 goto no_var;
2847 case VT_PTR:
2848 s = type->ref;
2849 if (t & VT_ARRAY) {
2850 snprintf(buf1, sizeof(buf1), "%s[%d]", varstr ? varstr : "", s->c);
2851 type_to_str(buf, buf_size, &s->type, buf1);
2852 goto no_var;
2854 pstrcpy(buf1, sizeof(buf1), "*");
2855 if (t & VT_CONSTANT)
2856 pstrcat(buf1, buf_size, "const ");
2857 if (t & VT_VOLATILE)
2858 pstrcat(buf1, buf_size, "volatile ");
2859 if (varstr)
2860 pstrcat(buf1, sizeof(buf1), varstr);
2861 type_to_str(buf, buf_size, &s->type, buf1);
2862 goto no_var;
2864 if (varstr) {
2865 pstrcat(buf, buf_size, " ");
2866 pstrcat(buf, buf_size, varstr);
2868 no_var: ;
2871 /* verify type compatibility to store vtop in 'dt' type, and generate
2872 casts if needed. */
2873 static void gen_assign_cast(CType *dt)
2875 CType *st, *type1, *type2, tmp_type1, tmp_type2;
2876 char buf1[256], buf2[256];
2877 int dbt, sbt;
2879 st = &vtop->type; /* source type */
2880 dbt = dt->t & VT_BTYPE;
2881 sbt = st->t & VT_BTYPE;
2882 if (sbt == VT_VOID || dbt == VT_VOID) {
2883 if (sbt == VT_VOID && dbt == VT_VOID)
2884 ; /*
2885 It is Ok if both are void
2886 A test program:
2887 void func1() {}
2888 void func2() {
2889 return func1();
2891 gcc accepts this program
2893 else
2894 tcc_error("cannot cast from/to void");
2896 if (dt->t & VT_CONSTANT)
2897 tcc_warning("assignment of read-only location");
2898 switch(dbt) {
2899 case VT_PTR:
2900 /* special cases for pointers */
2901 /* '0' can also be a pointer */
2902 if (is_null_pointer(vtop))
2903 goto type_ok;
2904 /* accept implicit pointer to integer cast with warning */
2905 if (is_integer_btype(sbt)) {
2906 tcc_warning("assignment makes pointer from integer without a cast");
2907 goto type_ok;
2909 type1 = pointed_type(dt);
2910 /* a function is implicitly a function pointer */
2911 if (sbt == VT_FUNC) {
2912 if ((type1->t & VT_BTYPE) != VT_VOID &&
2913 !is_compatible_types(pointed_type(dt), st))
2914 tcc_warning("assignment from incompatible pointer type");
2915 goto type_ok;
2917 if (sbt != VT_PTR)
2918 goto error;
2919 type2 = pointed_type(st);
2920 if ((type1->t & VT_BTYPE) == VT_VOID ||
2921 (type2->t & VT_BTYPE) == VT_VOID) {
2922 /* void * can match anything */
2923 } else {
2924 //printf("types %08x %08x\n", type1->t, type2->t);
2925 /* exact type match, except for qualifiers */
2926 if (!is_compatible_unqualified_types(type1, type2)) {
2927 /* Like GCC don't warn by default for merely changes
2928 in pointer target signedness. Do warn for different
2929 base types, though, in particular for unsigned enums
2930 and signed int targets. */
2931 if ((type1->t & VT_BTYPE) != (type2->t & VT_BTYPE)
2932 || IS_ENUM(type1->t) || IS_ENUM(type2->t)
2934 tcc_warning("assignment from incompatible pointer type");
2937 /* check const and volatile */
2938 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
2939 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
2940 tcc_warning("assignment discards qualifiers from pointer target type");
2941 break;
2942 case VT_BYTE:
2943 case VT_SHORT:
2944 case VT_INT:
2945 case VT_LLONG:
2946 if (sbt == VT_PTR || sbt == VT_FUNC) {
2947 tcc_warning("assignment makes integer from pointer without a cast");
2948 } else if (sbt == VT_STRUCT) {
2949 goto case_VT_STRUCT;
2951 /* XXX: more tests */
2952 break;
2953 case VT_STRUCT:
2954 case_VT_STRUCT:
2955 tmp_type1 = *dt;
2956 tmp_type2 = *st;
2957 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2958 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2959 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2960 error:
2961 type_to_str(buf1, sizeof(buf1), st, NULL);
2962 type_to_str(buf2, sizeof(buf2), dt, NULL);
2963 tcc_error("cannot cast '%s' to '%s'", buf1, buf2);
2965 break;
2967 type_ok:
2968 gen_cast(dt);
2971 /* store vtop in lvalue pushed on stack */
2972 ST_FUNC void vstore(void)
2974 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
2976 ft = vtop[-1].type.t;
2977 sbt = vtop->type.t & VT_BTYPE;
2978 dbt = ft & VT_BTYPE;
2979 if ((((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
2980 (sbt == VT_INT && dbt == VT_SHORT))
2981 && !(vtop->type.t & VT_BITFIELD)) {
2982 /* optimize char/short casts */
2983 delayed_cast = VT_MUSTCAST;
2984 vtop->type.t = ft & VT_TYPE;
2985 /* XXX: factorize */
2986 if (ft & VT_CONSTANT)
2987 tcc_warning("assignment of read-only location");
2988 } else {
2989 delayed_cast = 0;
2990 if (!(ft & VT_BITFIELD))
2991 gen_assign_cast(&vtop[-1].type);
2994 if (sbt == VT_STRUCT) {
2995 /* if structure, only generate pointer */
2996 /* structure assignment : generate memcpy */
2997 /* XXX: optimize if small size */
2998 size = type_size(&vtop->type, &align);
3000 /* destination */
3001 vswap();
3002 vtop->type.t = VT_PTR;
3003 gaddrof();
3005 /* address of memcpy() */
3006 #ifdef TCC_ARM_EABI
3007 if(!(align & 7))
3008 vpush_global_sym(&func_old_type, TOK_memcpy8);
3009 else if(!(align & 3))
3010 vpush_global_sym(&func_old_type, TOK_memcpy4);
3011 else
3012 #endif
3013 /* Use memmove, rather than memcpy, as dest and src may be same: */
3014 vpush_global_sym(&func_old_type, TOK_memmove);
3016 vswap();
3017 /* source */
3018 vpushv(vtop - 2);
3019 vtop->type.t = VT_PTR;
3020 gaddrof();
3021 /* type size */
3022 vpushi(size);
3023 gfunc_call(3);
3025 /* leave source on stack */
3026 } else if (ft & VT_BITFIELD) {
3027 /* bitfield store handling */
3029 /* save lvalue as expression result (example: s.b = s.a = n;) */
3030 vdup(), vtop[-1] = vtop[-2];
3032 bit_pos = BIT_POS(ft);
3033 bit_size = BIT_SIZE(ft);
3034 /* remove bit field info to avoid loops */
3035 vtop[-1].type.t = ft & ~VT_STRUCT_MASK;
3037 if ((ft & VT_BTYPE) == VT_BOOL) {
3038 gen_cast(&vtop[-1].type);
3039 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
3042 r = adjust_bf(vtop - 1, bit_pos, bit_size);
3043 if (r == VT_STRUCT) {
3044 gen_cast_s((ft & VT_BTYPE) == VT_LLONG ? VT_LLONG : VT_INT);
3045 store_packed_bf(bit_pos, bit_size);
3046 } else {
3047 unsigned long long mask = (1ULL << bit_size) - 1;
3048 if ((ft & VT_BTYPE) != VT_BOOL) {
3049 /* mask source */
3050 if ((vtop[-1].type.t & VT_BTYPE) == VT_LLONG)
3051 vpushll(mask);
3052 else
3053 vpushi((unsigned)mask);
3054 gen_op('&');
3056 /* shift source */
3057 vpushi(bit_pos);
3058 gen_op(TOK_SHL);
3059 vswap();
3060 /* duplicate destination */
3061 vdup();
3062 vrott(3);
3063 /* load destination, mask and or with source */
3064 if ((vtop->type.t & VT_BTYPE) == VT_LLONG)
3065 vpushll(~(mask << bit_pos));
3066 else
3067 vpushi(~((unsigned)mask << bit_pos));
3068 gen_op('&');
3069 gen_op('|');
3070 /* store result */
3071 vstore();
3072 /* ... and discard */
3073 vpop();
3075 } else {
3076 #ifdef CONFIG_TCC_BCHECK
3077 /* bound check case */
3078 if (vtop[-1].r & VT_MUSTBOUND) {
3079 vswap();
3080 gbound();
3081 vswap();
3083 #endif
3084 rc = RC_INT;
3085 if (is_float(ft)) {
3086 rc = RC_FLOAT;
3087 #ifdef TCC_TARGET_X86_64
3088 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
3089 rc = RC_ST0;
3090 } else if ((ft & VT_BTYPE) == VT_QFLOAT) {
3091 rc = RC_FRET;
3093 #endif
3095 r = gv(rc); /* generate value */
3096 /* if lvalue was saved on stack, must read it */
3097 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
3098 SValue sv;
3099 t = get_reg(RC_INT);
3100 #if PTR_SIZE == 8
3101 sv.type.t = VT_PTR;
3102 #else
3103 sv.type.t = VT_INT;
3104 #endif
3105 sv.r = VT_LOCAL | VT_LVAL;
3106 sv.c.i = vtop[-1].c.i;
3107 load(t, &sv);
3108 vtop[-1].r = t | VT_LVAL;
3110 /* two word case handling : store second register at word + 4 (or +8 for x86-64) */
3111 #if PTR_SIZE == 8
3112 if (((ft & VT_BTYPE) == VT_QLONG) || ((ft & VT_BTYPE) == VT_QFLOAT)) {
3113 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
3114 #else
3115 if ((ft & VT_BTYPE) == VT_LLONG) {
3116 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
3117 #endif
3118 vtop[-1].type.t = load_type;
3119 store(r, vtop - 1);
3120 vswap();
3121 /* convert to int to increment easily */
3122 vtop->type.t = addr_type;
3123 gaddrof();
3124 vpushi(load_size);
3125 gen_op('+');
3126 vtop->r |= VT_LVAL;
3127 vswap();
3128 vtop[-1].type.t = load_type;
3129 /* XXX: it works because r2 is spilled last ! */
3130 store(vtop->r2, vtop - 1);
3131 } else {
3132 store(r, vtop - 1);
3135 vswap();
3136 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
3137 vtop->r |= delayed_cast;
3141 /* post defines POST/PRE add. c is the token ++ or -- */
3142 ST_FUNC void inc(int post, int c)
3144 test_lvalue();
3145 vdup(); /* save lvalue */
3146 if (post) {
3147 gv_dup(); /* duplicate value */
3148 vrotb(3);
3149 vrotb(3);
3151 /* add constant */
3152 vpushi(c - TOK_MID);
3153 gen_op('+');
3154 vstore(); /* store value */
3155 if (post)
3156 vpop(); /* if post op, return saved value */
3159 ST_FUNC void parse_mult_str (CString *astr, const char *msg)
3161 /* read the string */
3162 if (tok != TOK_STR)
3163 expect(msg);
3164 cstr_new(astr);
3165 while (tok == TOK_STR) {
3166 /* XXX: add \0 handling too ? */
3167 cstr_cat(astr, tokc.str.data, -1);
3168 next();
3170 cstr_ccat(astr, '\0');
3173 /* If I is >= 1 and a power of two, returns log2(i)+1.
3174 If I is 0 returns 0. */
3175 static int exact_log2p1(int i)
3177 int ret;
3178 if (!i)
3179 return 0;
3180 for (ret = 1; i >= 1 << 8; ret += 8)
3181 i >>= 8;
3182 if (i >= 1 << 4)
3183 ret += 4, i >>= 4;
3184 if (i >= 1 << 2)
3185 ret += 2, i >>= 2;
3186 if (i >= 1 << 1)
3187 ret++;
3188 return ret;
3191 /* Parse __attribute__((...)) GNUC extension. */
3192 static void parse_attribute(AttributeDef *ad)
3194 int t, n;
3195 CString astr;
3197 redo:
3198 if (tok != TOK_ATTRIBUTE1 && tok != TOK_ATTRIBUTE2)
3199 return;
3200 next();
3201 skip('(');
3202 skip('(');
3203 while (tok != ')') {
3204 if (tok < TOK_IDENT)
3205 expect("attribute name");
3206 t = tok;
3207 next();
3208 switch(t) {
3209 case TOK_SECTION1:
3210 case TOK_SECTION2:
3211 skip('(');
3212 parse_mult_str(&astr, "section name");
3213 ad->section = find_section(tcc_state, (char *)astr.data);
3214 skip(')');
3215 cstr_free(&astr);
3216 break;
3217 case TOK_ALIAS1:
3218 case TOK_ALIAS2:
3219 skip('(');
3220 parse_mult_str(&astr, "alias(\"target\")");
3221 ad->alias_target = /* save string as token, for later */
3222 tok_alloc((char*)astr.data, astr.size-1)->tok;
3223 skip(')');
3224 cstr_free(&astr);
3225 break;
3226 case TOK_VISIBILITY1:
3227 case TOK_VISIBILITY2:
3228 skip('(');
3229 parse_mult_str(&astr,
3230 "visibility(\"default|hidden|internal|protected\")");
3231 if (!strcmp (astr.data, "default"))
3232 ad->a.visibility = STV_DEFAULT;
3233 else if (!strcmp (astr.data, "hidden"))
3234 ad->a.visibility = STV_HIDDEN;
3235 else if (!strcmp (astr.data, "internal"))
3236 ad->a.visibility = STV_INTERNAL;
3237 else if (!strcmp (astr.data, "protected"))
3238 ad->a.visibility = STV_PROTECTED;
3239 else
3240 expect("visibility(\"default|hidden|internal|protected\")");
3241 skip(')');
3242 cstr_free(&astr);
3243 break;
3244 case TOK_ALIGNED1:
3245 case TOK_ALIGNED2:
3246 if (tok == '(') {
3247 next();
3248 n = expr_const();
3249 if (n <= 0 || (n & (n - 1)) != 0)
3250 tcc_error("alignment must be a positive power of two");
3251 skip(')');
3252 } else {
3253 n = MAX_ALIGN;
3255 ad->a.aligned = exact_log2p1(n);
3256 if (n != 1 << (ad->a.aligned - 1))
3257 tcc_error("alignment of %d is larger than implemented", n);
3258 break;
3259 case TOK_PACKED1:
3260 case TOK_PACKED2:
3261 ad->a.packed = 1;
3262 break;
3263 case TOK_WEAK1:
3264 case TOK_WEAK2:
3265 ad->a.weak = 1;
3266 break;
3267 case TOK_UNUSED1:
3268 case TOK_UNUSED2:
3269 /* currently, no need to handle it because tcc does not
3270 track unused objects */
3271 break;
3272 case TOK_NORETURN1:
3273 case TOK_NORETURN2:
3274 /* currently, no need to handle it because tcc does not
3275 track unused objects */
3276 break;
3277 case TOK_CDECL1:
3278 case TOK_CDECL2:
3279 case TOK_CDECL3:
3280 ad->f.func_call = FUNC_CDECL;
3281 break;
3282 case TOK_STDCALL1:
3283 case TOK_STDCALL2:
3284 case TOK_STDCALL3:
3285 ad->f.func_call = FUNC_STDCALL;
3286 break;
3287 #ifdef TCC_TARGET_I386
3288 case TOK_REGPARM1:
3289 case TOK_REGPARM2:
3290 skip('(');
3291 n = expr_const();
3292 if (n > 3)
3293 n = 3;
3294 else if (n < 0)
3295 n = 0;
3296 if (n > 0)
3297 ad->f.func_call = FUNC_FASTCALL1 + n - 1;
3298 skip(')');
3299 break;
3300 case TOK_FASTCALL1:
3301 case TOK_FASTCALL2:
3302 case TOK_FASTCALL3:
3303 ad->f.func_call = FUNC_FASTCALLW;
3304 break;
3305 #endif
3306 case TOK_MODE:
3307 skip('(');
3308 switch(tok) {
3309 case TOK_MODE_DI:
3310 ad->attr_mode = VT_LLONG + 1;
3311 break;
3312 case TOK_MODE_QI:
3313 ad->attr_mode = VT_BYTE + 1;
3314 break;
3315 case TOK_MODE_HI:
3316 ad->attr_mode = VT_SHORT + 1;
3317 break;
3318 case TOK_MODE_SI:
3319 case TOK_MODE_word:
3320 ad->attr_mode = VT_INT + 1;
3321 break;
3322 default:
3323 tcc_warning("__mode__(%s) not supported\n", get_tok_str(tok, NULL));
3324 break;
3326 next();
3327 skip(')');
3328 break;
3329 case TOK_DLLEXPORT:
3330 ad->a.dllexport = 1;
3331 break;
3332 case TOK_DLLIMPORT:
3333 ad->a.dllimport = 1;
3334 break;
3335 default:
3336 if (tcc_state->warn_unsupported)
3337 tcc_warning("'%s' attribute ignored", get_tok_str(t, NULL));
3338 /* skip parameters */
3339 if (tok == '(') {
3340 int parenthesis = 0;
3341 do {
3342 if (tok == '(')
3343 parenthesis++;
3344 else if (tok == ')')
3345 parenthesis--;
3346 next();
3347 } while (parenthesis && tok != -1);
3349 break;
3351 if (tok != ',')
3352 break;
3353 next();
3355 skip(')');
3356 skip(')');
3357 goto redo;
3360 static Sym * find_field (CType *type, int v)
3362 Sym *s = type->ref;
3363 v |= SYM_FIELD;
3364 while ((s = s->next) != NULL) {
3365 if ((s->v & SYM_FIELD) &&
3366 (s->type.t & VT_BTYPE) == VT_STRUCT &&
3367 (s->v & ~SYM_FIELD) >= SYM_FIRST_ANOM) {
3368 Sym *ret = find_field (&s->type, v);
3369 if (ret)
3370 return ret;
3372 if (s->v == v)
3373 break;
3375 return s;
3378 static void struct_add_offset (Sym *s, int offset)
3380 while ((s = s->next) != NULL) {
3381 if ((s->v & SYM_FIELD) &&
3382 (s->type.t & VT_BTYPE) == VT_STRUCT &&
3383 (s->v & ~SYM_FIELD) >= SYM_FIRST_ANOM) {
3384 struct_add_offset(s->type.ref, offset);
3385 } else
3386 s->c += offset;
3390 static void struct_layout(CType *type, AttributeDef *ad)
3392 int size, align, maxalign, offset, c, bit_pos, bit_size;
3393 int packed, a, bt, prevbt, prev_bit_size;
3394 int pcc = !tcc_state->ms_bitfields;
3395 int pragma_pack = *tcc_state->pack_stack_ptr;
3396 Sym *f;
3398 maxalign = 1;
3399 offset = 0;
3400 c = 0;
3401 bit_pos = 0;
3402 prevbt = VT_STRUCT; /* make it never match */
3403 prev_bit_size = 0;
3405 //#define BF_DEBUG
3407 for (f = type->ref->next; f; f = f->next) {
3408 if (f->type.t & VT_BITFIELD) {
3409 bit_size = BIT_SIZE(f->type.t);
3410 /* in pcc mode, long long bitfields have type int if they fit */
3411 if (pcc && (f->type.t & VT_BTYPE) == VT_LLONG && bit_size <= 32)
3412 f->type.t = (f->type.t & ~VT_BTYPE) | VT_INT;
3413 } else
3414 bit_size = -1;
3415 size = type_size(&f->type, &align);
3416 a = f->a.aligned ? 1 << (f->a.aligned - 1) : 0;
3417 packed = 0;
3419 if (pcc && bit_size == 0) {
3420 /* in pcc mode, packing does not affect zero-width bitfields */
3422 } else {
3423 /* in pcc mode, attribute packed overrides if set. */
3424 if (pcc && (f->a.packed || ad->a.packed))
3425 align = packed = 1;
3427 /* pragma pack overrides align if lesser and packs bitfields always */
3428 if (pragma_pack) {
3429 packed = 1;
3430 if (pragma_pack < align)
3431 align = pragma_pack;
3432 /* in pcc mode pragma pack also overrides individual align */
3433 if (pcc && pragma_pack < a)
3434 a = 0;
3437 /* some individual align was specified */
3438 if (a)
3439 align = a;
3441 if (type->ref->type.t == VT_UNION) {
3442 if (pcc && bit_size >= 0)
3443 size = (bit_size + 7) >> 3;
3444 offset = 0;
3445 if (size > c)
3446 c = size;
3448 } else if (bit_size < 0) {
3449 if (pcc)
3450 c += (bit_pos + 7) >> 3;
3451 c = (c + align - 1) & -align;
3452 offset = c;
3453 if (size > 0)
3454 c += size;
3455 bit_pos = 0;
3456 prevbt = VT_STRUCT;
3457 prev_bit_size = 0;
3459 } else {
3460 /* A bit-field. Layout is more complicated. There are two
3461 options: PCC (GCC) compatible and MS compatible */
3462 if (pcc) {
3463 /* In PCC layout a bit-field is placed adjacent to the
3464 preceding bit-fields, except if:
3465 - it has zero-width
3466 - an individual alignment was given
3467 - it would overflow its base type container and
3468 there is no packing */
3469 if (bit_size == 0) {
3470 new_field:
3471 c = (c + ((bit_pos + 7) >> 3) + align - 1) & -align;
3472 bit_pos = 0;
3473 } else if (f->a.aligned) {
3474 goto new_field;
3475 } else if (!packed) {
3476 int a8 = align * 8;
3477 int ofs = ((c * 8 + bit_pos) % a8 + bit_size + a8 - 1) / a8;
3478 if (ofs > size / align)
3479 goto new_field;
3482 while (bit_pos >= align * 8)
3483 c += align, bit_pos -= align * 8;
3484 offset = c;
3486 /* In PCC layout named bit-fields influence the alignment
3487 of the containing struct using the base types alignment,
3488 except for packed fields (which here have correct align). */
3489 if (f->v & SYM_FIRST_ANOM)
3490 align = 1;
3491 } else {
3492 bt = f->type.t & VT_BTYPE;
3493 if ((bit_pos + bit_size > size * 8)
3494 || (bit_size > 0) == (bt != prevbt)
3496 c = (c + align - 1) & -align;
3497 offset = c;
3498 bit_pos = 0;
3499 /* In MS bitfield mode a bit-field run always uses
3500 at least as many bits as the underlying type.
3501 To start a new run it's also required that this
3502 or the last bit-field had non-zero width. */
3503 if (bit_size || prev_bit_size)
3504 c += size;
3506 /* In MS layout the records alignment is normally
3507 influenced by the field, except for a zero-width
3508 field at the start of a run (but by further zero-width
3509 fields it is again). */
3510 if (bit_size == 0 && prevbt != bt)
3511 align = 1;
3512 prevbt = bt;
3513 prev_bit_size = bit_size;
3516 f->type.t = (f->type.t & ~(0x3f << VT_STRUCT_SHIFT))
3517 | (bit_pos << VT_STRUCT_SHIFT);
3518 bit_pos += bit_size;
3520 if (align > maxalign)
3521 maxalign = align;
3523 #ifdef BF_DEBUG
3524 printf("set field %s offset %-2d size %-2d align %-2d",
3525 get_tok_str(f->v & ~SYM_FIELD, NULL), offset, size, align);
3526 if (f->type.t & VT_BITFIELD) {
3527 printf(" pos %-2d bits %-2d",
3528 BIT_POS(f->type.t),
3529 BIT_SIZE(f->type.t)
3532 printf("\n");
3533 #endif
3535 if (f->v & SYM_FIRST_ANOM && (f->type.t & VT_BTYPE) == VT_STRUCT) {
3536 Sym *ass;
3537 /* An anonymous struct/union. Adjust member offsets
3538 to reflect the real offset of our containing struct.
3539 Also set the offset of this anon member inside
3540 the outer struct to be zero. Via this it
3541 works when accessing the field offset directly
3542 (from base object), as well as when recursing
3543 members in initializer handling. */
3544 int v2 = f->type.ref->v;
3545 if (!(v2 & SYM_FIELD) &&
3546 (v2 & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
3547 Sym **pps;
3548 /* This happens only with MS extensions. The
3549 anon member has a named struct type, so it
3550 potentially is shared with other references.
3551 We need to unshare members so we can modify
3552 them. */
3553 ass = f->type.ref;
3554 f->type.ref = sym_push(anon_sym++ | SYM_FIELD,
3555 &f->type.ref->type, 0,
3556 f->type.ref->c);
3557 pps = &f->type.ref->next;
3558 while ((ass = ass->next) != NULL) {
3559 *pps = sym_push(ass->v, &ass->type, 0, ass->c);
3560 pps = &((*pps)->next);
3562 *pps = NULL;
3564 struct_add_offset(f->type.ref, offset);
3565 f->c = 0;
3566 } else {
3567 f->c = offset;
3570 f->r = 0;
3573 if (pcc)
3574 c += (bit_pos + 7) >> 3;
3576 /* store size and alignment */
3577 a = bt = ad->a.aligned ? 1 << (ad->a.aligned - 1) : 1;
3578 if (a < maxalign)
3579 a = maxalign;
3580 type->ref->r = a;
3581 if (pragma_pack && pragma_pack < maxalign) {
3582 /* can happen if individual align for some member was given. In
3583 this case MSVC ignores maxalign when aligning the size */
3584 a = pragma_pack;
3585 if (a < bt)
3586 a = bt;
3588 c = (c + a - 1) & -a;
3589 type->ref->c = c;
3591 #ifdef BF_DEBUG
3592 printf("struct size %-2d align %-2d\n\n", c, a), fflush(stdout);
3593 #endif
3595 /* check whether we can access bitfields by their type */
3596 for (f = type->ref->next; f; f = f->next) {
3597 int s, px, cx, c0;
3598 CType t;
3600 if (0 == (f->type.t & VT_BITFIELD))
3601 continue;
3602 f->type.ref = f;
3603 f->auxtype = -1;
3604 bit_size = BIT_SIZE(f->type.t);
3605 if (bit_size == 0)
3606 continue;
3607 bit_pos = BIT_POS(f->type.t);
3608 size = type_size(&f->type, &align);
3609 if (bit_pos + bit_size <= size * 8 && f->c + size <= c)
3610 continue;
3612 /* try to access the field using a differnt type */
3613 c0 = -1, s = align = 1;
3614 for (;;) {
3615 px = f->c * 8 + bit_pos;
3616 cx = (px >> 3) & -align;
3617 px = px - (cx << 3);
3618 if (c0 == cx)
3619 break;
3620 s = (px + bit_size + 7) >> 3;
3621 if (s > 4) {
3622 t.t = VT_LLONG;
3623 } else if (s > 2) {
3624 t.t = VT_INT;
3625 } else if (s > 1) {
3626 t.t = VT_SHORT;
3627 } else {
3628 t.t = VT_BYTE;
3630 s = type_size(&t, &align);
3631 c0 = cx;
3634 if (px + bit_size <= s * 8 && cx + s <= c) {
3635 /* update offset and bit position */
3636 f->c = cx;
3637 bit_pos = px;
3638 f->type.t = (f->type.t & ~(0x3f << VT_STRUCT_SHIFT))
3639 | (bit_pos << VT_STRUCT_SHIFT);
3640 if (s != size)
3641 f->auxtype = t.t;
3642 #ifdef BF_DEBUG
3643 printf("FIX field %s offset %-2d size %-2d align %-2d "
3644 "pos %-2d bits %-2d\n",
3645 get_tok_str(f->v & ~SYM_FIELD, NULL),
3646 cx, s, align, px, bit_size);
3647 #endif
3648 } else {
3649 /* fall back to load/store single-byte wise */
3650 f->auxtype = VT_STRUCT;
3651 #ifdef BF_DEBUG
3652 printf("FIX field %s : load byte-wise\n",
3653 get_tok_str(f->v & ~SYM_FIELD, NULL));
3654 #endif
3659 /* enum/struct/union declaration. u is VT_ENUM/VT_STRUCT/VT_UNION */
3660 static void struct_decl(CType *type, int u)
3662 int v, c, size, align, flexible;
3663 int bit_size, bsize, bt;
3664 Sym *s, *ss, **ps;
3665 AttributeDef ad, ad1;
3666 CType type1, btype;
3668 memset(&ad, 0, sizeof ad);
3669 next();
3670 parse_attribute(&ad);
3671 if (tok != '{') {
3672 v = tok;
3673 next();
3674 /* struct already defined ? return it */
3675 if (v < TOK_IDENT)
3676 expect("struct/union/enum name");
3677 s = struct_find(v);
3678 if (s && (s->sym_scope == local_scope || tok != '{')) {
3679 if (u == s->type.t)
3680 goto do_decl;
3681 if (u == VT_ENUM && IS_ENUM(s->type.t))
3682 goto do_decl;
3683 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
3685 } else {
3686 v = anon_sym++;
3688 /* Record the original enum/struct/union token. */
3689 type1.t = u == VT_ENUM ? u | VT_INT | VT_UNSIGNED : u;
3690 type1.ref = NULL;
3691 /* we put an undefined size for struct/union */
3692 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
3693 s->r = 0; /* default alignment is zero as gcc */
3694 do_decl:
3695 type->t = s->type.t;
3696 type->ref = s;
3698 if (tok == '{') {
3699 next();
3700 if (s->c != -1)
3701 tcc_error("struct/union/enum already defined");
3702 /* cannot be empty */
3703 /* non empty enums are not allowed */
3704 ps = &s->next;
3705 if (u == VT_ENUM) {
3706 long long ll = 0, pl = 0, nl = 0;
3707 CType t;
3708 t.ref = s;
3709 /* enum symbols have static storage */
3710 t.t = VT_INT|VT_STATIC|VT_ENUM_VAL;
3711 for(;;) {
3712 v = tok;
3713 if (v < TOK_UIDENT)
3714 expect("identifier");
3715 ss = sym_find(v);
3716 if (ss && !local_stack)
3717 tcc_error("redefinition of enumerator '%s'",
3718 get_tok_str(v, NULL));
3719 next();
3720 if (tok == '=') {
3721 next();
3722 ll = expr_const64();
3724 ss = sym_push(v, &t, VT_CONST, 0);
3725 ss->enum_val = ll;
3726 *ps = ss, ps = &ss->next;
3727 if (ll < nl)
3728 nl = ll;
3729 if (ll > pl)
3730 pl = ll;
3731 if (tok != ',')
3732 break;
3733 next();
3734 ll++;
3735 /* NOTE: we accept a trailing comma */
3736 if (tok == '}')
3737 break;
3739 skip('}');
3740 /* set integral type of the enum */
3741 t.t = VT_INT;
3742 if (nl >= 0) {
3743 if (pl != (unsigned)pl)
3744 t.t = VT_LLONG;
3745 t.t |= VT_UNSIGNED;
3746 } else if (pl != (int)pl || nl != (int)nl)
3747 t.t = VT_LLONG;
3748 s->type.t = type->t = t.t | VT_ENUM;
3749 s->c = 0;
3750 /* set type for enum members */
3751 for (ss = s->next; ss; ss = ss->next) {
3752 ll = ss->enum_val;
3753 if (ll == (int)ll) /* default is int if it fits */
3754 continue;
3755 if (t.t & VT_UNSIGNED) {
3756 ss->type.t |= VT_UNSIGNED;
3757 if (ll == (unsigned)ll)
3758 continue;
3760 ss->type.t = (ss->type.t & ~VT_BTYPE) | VT_LLONG;
3762 } else {
3763 c = 0;
3764 flexible = 0;
3765 while (tok != '}') {
3766 if (!parse_btype(&btype, &ad1)) {
3767 skip(';');
3768 continue;
3770 while (1) {
3771 if (flexible)
3772 tcc_error("flexible array member '%s' not at the end of struct",
3773 get_tok_str(v, NULL));
3774 bit_size = -1;
3775 v = 0;
3776 type1 = btype;
3777 if (tok != ':') {
3778 if (tok != ';')
3779 type_decl(&type1, &ad1, &v, TYPE_DIRECT);
3780 if (v == 0) {
3781 if ((type1.t & VT_BTYPE) != VT_STRUCT)
3782 expect("identifier");
3783 else {
3784 int v = btype.ref->v;
3785 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
3786 if (tcc_state->ms_extensions == 0)
3787 expect("identifier");
3791 if (type_size(&type1, &align) < 0) {
3792 if ((u == VT_STRUCT) && (type1.t & VT_ARRAY) && c)
3793 flexible = 1;
3794 else
3795 tcc_error("field '%s' has incomplete type",
3796 get_tok_str(v, NULL));
3798 if ((type1.t & VT_BTYPE) == VT_FUNC ||
3799 (type1.t & VT_STORAGE))
3800 tcc_error("invalid type for '%s'",
3801 get_tok_str(v, NULL));
3803 if (tok == ':') {
3804 next();
3805 bit_size = expr_const();
3806 /* XXX: handle v = 0 case for messages */
3807 if (bit_size < 0)
3808 tcc_error("negative width in bit-field '%s'",
3809 get_tok_str(v, NULL));
3810 if (v && bit_size == 0)
3811 tcc_error("zero width for bit-field '%s'",
3812 get_tok_str(v, NULL));
3813 parse_attribute(&ad1);
3815 size = type_size(&type1, &align);
3816 if (bit_size >= 0) {
3817 bt = type1.t & VT_BTYPE;
3818 if (bt != VT_INT &&
3819 bt != VT_BYTE &&
3820 bt != VT_SHORT &&
3821 bt != VT_BOOL &&
3822 bt != VT_LLONG)
3823 tcc_error("bitfields must have scalar type");
3824 bsize = size * 8;
3825 if (bit_size > bsize) {
3826 tcc_error("width of '%s' exceeds its type",
3827 get_tok_str(v, NULL));
3828 } else if (bit_size == bsize
3829 && !ad.a.packed && !ad1.a.packed) {
3830 /* no need for bit fields */
3832 } else if (bit_size == 64) {
3833 tcc_error("field width 64 not implemented");
3834 } else {
3835 type1.t = (type1.t & ~VT_STRUCT_MASK)
3836 | VT_BITFIELD
3837 | (bit_size << (VT_STRUCT_SHIFT + 6));
3840 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
3841 /* Remember we've seen a real field to check
3842 for placement of flexible array member. */
3843 c = 1;
3845 /* If member is a struct or bit-field, enforce
3846 placing into the struct (as anonymous). */
3847 if (v == 0 &&
3848 ((type1.t & VT_BTYPE) == VT_STRUCT ||
3849 bit_size >= 0)) {
3850 v = anon_sym++;
3852 if (v) {
3853 ss = sym_push(v | SYM_FIELD, &type1, 0, 0);
3854 ss->a = ad1.a;
3855 *ps = ss;
3856 ps = &ss->next;
3858 if (tok == ';' || tok == TOK_EOF)
3859 break;
3860 skip(',');
3862 skip(';');
3864 skip('}');
3865 parse_attribute(&ad);
3866 struct_layout(type, &ad);
3871 static void sym_to_attr(AttributeDef *ad, Sym *s)
3873 if (s->a.aligned && 0 == ad->a.aligned)
3874 ad->a.aligned = s->a.aligned;
3875 if (s->f.func_call && 0 == ad->f.func_call)
3876 ad->f.func_call = s->f.func_call;
3877 if (s->f.func_type && 0 == ad->f.func_type)
3878 ad->f.func_type = s->f.func_type;
3879 if (s->a.packed)
3880 ad->a.packed = 1;
3883 /* Add type qualifiers to a type. If the type is an array then the qualifiers
3884 are added to the element type, copied because it could be a typedef. */
3885 static void parse_btype_qualify(CType *type, int qualifiers)
3887 while (type->t & VT_ARRAY) {
3888 type->ref = sym_push(SYM_FIELD, &type->ref->type, 0, type->ref->c);
3889 type = &type->ref->type;
3891 type->t |= qualifiers;
3894 /* return 0 if no type declaration. otherwise, return the basic type
3895 and skip it.
3897 static int parse_btype(CType *type, AttributeDef *ad)
3899 int t, u, bt, st, type_found, typespec_found, g;
3900 Sym *s;
3901 CType type1;
3903 memset(ad, 0, sizeof(AttributeDef));
3904 type_found = 0;
3905 typespec_found = 0;
3906 t = VT_INT;
3907 bt = st = -1;
3908 type->ref = NULL;
3910 while(1) {
3911 switch(tok) {
3912 case TOK_EXTENSION:
3913 /* currently, we really ignore extension */
3914 next();
3915 continue;
3917 /* basic types */
3918 case TOK_CHAR:
3919 u = VT_BYTE;
3920 basic_type:
3921 next();
3922 basic_type1:
3923 if (u == VT_SHORT || u == VT_LONG) {
3924 if (st != -1 || (bt != -1 && bt != VT_INT))
3925 tmbt: tcc_error("too many basic types");
3926 st = u;
3927 } else {
3928 if (bt != -1 || (st != -1 && u != VT_INT))
3929 goto tmbt;
3930 bt = u;
3932 if (u != VT_INT)
3933 t = (t & ~VT_BTYPE) | u;
3934 typespec_found = 1;
3935 break;
3936 case TOK_VOID:
3937 u = VT_VOID;
3938 goto basic_type;
3939 case TOK_SHORT:
3940 u = VT_SHORT;
3941 goto basic_type;
3942 case TOK_INT:
3943 u = VT_INT;
3944 goto basic_type;
3945 case TOK_LONG:
3946 if ((t & VT_BTYPE) == VT_DOUBLE) {
3947 #ifndef TCC_TARGET_PE
3948 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3949 #endif
3950 } else if ((t & VT_BTYPE) == VT_LONG) {
3951 t = (t & ~VT_BTYPE) | VT_LLONG;
3952 } else {
3953 u = VT_LONG;
3954 goto basic_type;
3956 next();
3957 break;
3958 #ifdef TCC_TARGET_ARM64
3959 case TOK_UINT128:
3960 /* GCC's __uint128_t appears in some Linux header files. Make it a
3961 synonym for long double to get the size and alignment right. */
3962 u = VT_LDOUBLE;
3963 goto basic_type;
3964 #endif
3965 case TOK_BOOL:
3966 u = VT_BOOL;
3967 goto basic_type;
3968 case TOK_FLOAT:
3969 u = VT_FLOAT;
3970 goto basic_type;
3971 case TOK_DOUBLE:
3972 if ((t & VT_BTYPE) == VT_LONG) {
3973 #ifdef TCC_TARGET_PE
3974 t = (t & ~VT_BTYPE) | VT_DOUBLE;
3975 #else
3976 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3977 #endif
3978 } else {
3979 u = VT_DOUBLE;
3980 goto basic_type;
3982 next();
3983 break;
3984 case TOK_ENUM:
3985 struct_decl(&type1, VT_ENUM);
3986 basic_type2:
3987 u = type1.t;
3988 type->ref = type1.ref;
3989 goto basic_type1;
3990 case TOK_STRUCT:
3991 struct_decl(&type1, VT_STRUCT);
3992 goto basic_type2;
3993 case TOK_UNION:
3994 struct_decl(&type1, VT_UNION);
3995 goto basic_type2;
3997 /* type modifiers */
3998 case TOK_CONST1:
3999 case TOK_CONST2:
4000 case TOK_CONST3:
4001 type->t = t;
4002 parse_btype_qualify(type, VT_CONSTANT);
4003 t = type->t;
4004 next();
4005 break;
4006 case TOK_VOLATILE1:
4007 case TOK_VOLATILE2:
4008 case TOK_VOLATILE3:
4009 type->t = t;
4010 parse_btype_qualify(type, VT_VOLATILE);
4011 t = type->t;
4012 next();
4013 break;
4014 case TOK_SIGNED1:
4015 case TOK_SIGNED2:
4016 case TOK_SIGNED3:
4017 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == (VT_DEFSIGN|VT_UNSIGNED))
4018 tcc_error("signed and unsigned modifier");
4019 t |= VT_DEFSIGN;
4020 next();
4021 typespec_found = 1;
4022 break;
4023 case TOK_REGISTER:
4024 case TOK_AUTO:
4025 case TOK_RESTRICT1:
4026 case TOK_RESTRICT2:
4027 case TOK_RESTRICT3:
4028 next();
4029 break;
4030 case TOK_UNSIGNED:
4031 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == VT_DEFSIGN)
4032 tcc_error("signed and unsigned modifier");
4033 t |= VT_DEFSIGN | VT_UNSIGNED;
4034 next();
4035 typespec_found = 1;
4036 break;
4038 /* storage */
4039 case TOK_EXTERN:
4040 g = VT_EXTERN;
4041 goto storage;
4042 case TOK_STATIC:
4043 g = VT_STATIC;
4044 goto storage;
4045 case TOK_TYPEDEF:
4046 g = VT_TYPEDEF;
4047 goto storage;
4048 storage:
4049 if (t & (VT_EXTERN|VT_STATIC|VT_TYPEDEF) & ~g)
4050 tcc_error("multiple storage classes");
4051 t |= g;
4052 next();
4053 break;
4054 case TOK_INLINE1:
4055 case TOK_INLINE2:
4056 case TOK_INLINE3:
4057 t |= VT_INLINE;
4058 next();
4059 break;
4061 /* GNUC attribute */
4062 case TOK_ATTRIBUTE1:
4063 case TOK_ATTRIBUTE2:
4064 parse_attribute(ad);
4065 if (ad->attr_mode) {
4066 u = ad->attr_mode -1;
4067 t = (t & ~VT_BTYPE) | u;
4069 break;
4070 /* GNUC typeof */
4071 case TOK_TYPEOF1:
4072 case TOK_TYPEOF2:
4073 case TOK_TYPEOF3:
4074 next();
4075 parse_expr_type(&type1);
4076 /* remove all storage modifiers except typedef */
4077 type1.t &= ~(VT_STORAGE&~VT_TYPEDEF);
4078 if (type1.ref)
4079 sym_to_attr(ad, type1.ref);
4080 goto basic_type2;
4081 default:
4082 if (typespec_found)
4083 goto the_end;
4084 s = sym_find(tok);
4085 if (!s || !(s->type.t & VT_TYPEDEF))
4086 goto the_end;
4087 t &= ~VT_BTYPE;
4088 u = t & ~(VT_CONSTANT | VT_VOLATILE), t ^= u;
4089 type->t = (s->type.t & ~VT_TYPEDEF) | u;
4090 type->ref = s->type.ref;
4091 if (t)
4092 parse_btype_qualify(type, t);
4093 t = type->t;
4094 /* get attributes from typedef */
4095 sym_to_attr(ad, s);
4096 next();
4097 typespec_found = 1;
4098 st = bt = -2;
4099 break;
4101 type_found = 1;
4103 the_end:
4104 if (tcc_state->char_is_unsigned) {
4105 if ((t & (VT_DEFSIGN|VT_BTYPE)) == VT_BYTE)
4106 t |= VT_UNSIGNED;
4109 /* long is never used as type */
4110 if ((t & VT_BTYPE) == VT_LONG)
4111 #if PTR_SIZE == 8 && !defined TCC_TARGET_PE
4112 t = (t & ~VT_BTYPE) | VT_LLONG;
4113 #else
4114 t = (t & ~VT_BTYPE) | VT_INT;
4115 #endif
4116 type->t = t;
4117 return type_found;
4120 /* convert a function parameter type (array to pointer and function to
4121 function pointer) */
4122 static inline void convert_parameter_type(CType *pt)
4124 /* remove const and volatile qualifiers (XXX: const could be used
4125 to indicate a const function parameter */
4126 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
4127 /* array must be transformed to pointer according to ANSI C */
4128 pt->t &= ~VT_ARRAY;
4129 if ((pt->t & VT_BTYPE) == VT_FUNC) {
4130 mk_pointer(pt);
4134 ST_FUNC void parse_asm_str(CString *astr)
4136 skip('(');
4137 parse_mult_str(astr, "string constant");
4140 /* Parse an asm label and return the token */
4141 static int asm_label_instr(void)
4143 int v;
4144 CString astr;
4146 next();
4147 parse_asm_str(&astr);
4148 skip(')');
4149 #ifdef ASM_DEBUG
4150 printf("asm_alias: \"%s\"\n", (char *)astr.data);
4151 #endif
4152 v = tok_alloc(astr.data, astr.size - 1)->tok;
4153 cstr_free(&astr);
4154 return v;
4157 static int post_type(CType *type, AttributeDef *ad, int storage, int td)
4159 int n, l, t1, arg_size, align;
4160 Sym **plast, *s, *first;
4161 AttributeDef ad1;
4162 CType pt;
4164 if (tok == '(') {
4165 /* function type, or recursive declarator (return if so) */
4166 next();
4167 if (td && !(td & TYPE_ABSTRACT))
4168 return 0;
4169 if (tok == ')')
4170 l = 0;
4171 else if (parse_btype(&pt, &ad1))
4172 l = FUNC_NEW;
4173 else if (td)
4174 return 0;
4175 else
4176 l = FUNC_OLD;
4177 first = NULL;
4178 plast = &first;
4179 arg_size = 0;
4180 if (l) {
4181 for(;;) {
4182 /* read param name and compute offset */
4183 if (l != FUNC_OLD) {
4184 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
4185 break;
4186 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
4187 if ((pt.t & VT_BTYPE) == VT_VOID)
4188 tcc_error("parameter declared as void");
4189 arg_size += (type_size(&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
4190 } else {
4191 n = tok;
4192 if (n < TOK_UIDENT)
4193 expect("identifier");
4194 pt.t = VT_VOID; /* invalid type */
4195 next();
4197 convert_parameter_type(&pt);
4198 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
4199 *plast = s;
4200 plast = &s->next;
4201 if (tok == ')')
4202 break;
4203 skip(',');
4204 if (l == FUNC_NEW && tok == TOK_DOTS) {
4205 l = FUNC_ELLIPSIS;
4206 next();
4207 break;
4209 if (l == FUNC_NEW && !parse_btype(&pt, &ad1))
4210 tcc_error("invalid type");
4212 } else
4213 /* if no parameters, then old type prototype */
4214 l = FUNC_OLD;
4215 skip(')');
4216 /* NOTE: const is ignored in returned type as it has a special
4217 meaning in gcc / C++ */
4218 type->t &= ~VT_CONSTANT;
4219 /* some ancient pre-K&R C allows a function to return an array
4220 and the array brackets to be put after the arguments, such
4221 that "int c()[]" means something like "int[] c()" */
4222 if (tok == '[') {
4223 next();
4224 skip(']'); /* only handle simple "[]" */
4225 mk_pointer(type);
4227 /* we push a anonymous symbol which will contain the function prototype */
4228 ad->f.func_args = arg_size;
4229 ad->f.func_type = l;
4230 s = sym_push(SYM_FIELD, type, 0, 0);
4231 s->a = ad->a;
4232 s->f = ad->f;
4233 s->next = first;
4234 type->t = VT_FUNC;
4235 type->ref = s;
4236 } else if (tok == '[') {
4237 int saved_nocode_wanted = nocode_wanted;
4238 /* array definition */
4239 next();
4240 if (tok == TOK_RESTRICT1)
4241 next();
4242 n = -1;
4243 t1 = 0;
4244 if (tok != ']') {
4245 if (!local_stack || (storage & VT_STATIC))
4246 vpushi(expr_const());
4247 else {
4248 /* VLAs (which can only happen with local_stack && !VT_STATIC)
4249 length must always be evaluated, even under nocode_wanted,
4250 so that its size slot is initialized (e.g. under sizeof
4251 or typeof). */
4252 nocode_wanted = 0;
4253 gexpr();
4255 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4256 n = vtop->c.i;
4257 if (n < 0)
4258 tcc_error("invalid array size");
4259 } else {
4260 if (!is_integer_btype(vtop->type.t & VT_BTYPE))
4261 tcc_error("size of variable length array should be an integer");
4262 t1 = VT_VLA;
4265 skip(']');
4266 /* parse next post type */
4267 post_type(type, ad, storage, 0);
4268 if (type->t == VT_FUNC)
4269 tcc_error("declaration of an array of functions");
4270 t1 |= type->t & VT_VLA;
4272 if (t1 & VT_VLA) {
4273 loc -= type_size(&int_type, &align);
4274 loc &= -align;
4275 n = loc;
4277 vla_runtime_type_size(type, &align);
4278 gen_op('*');
4279 vset(&int_type, VT_LOCAL|VT_LVAL, n);
4280 vswap();
4281 vstore();
4283 if (n != -1)
4284 vpop();
4285 nocode_wanted = saved_nocode_wanted;
4287 /* we push an anonymous symbol which will contain the array
4288 element type */
4289 s = sym_push(SYM_FIELD, type, 0, n);
4290 type->t = (t1 ? VT_VLA : VT_ARRAY) | VT_PTR;
4291 type->ref = s;
4293 return 1;
4296 /* Parse a type declarator (except basic type), and return the type
4297 in 'type'. 'td' is a bitmask indicating which kind of type decl is
4298 expected. 'type' should contain the basic type. 'ad' is the
4299 attribute definition of the basic type. It can be modified by
4300 type_decl(). If this (possibly abstract) declarator is a pointer chain
4301 it returns the innermost pointed to type (equals *type, but is a different
4302 pointer), otherwise returns type itself, that's used for recursive calls. */
4303 static CType *type_decl(CType *type, AttributeDef *ad, int *v, int td)
4305 CType *post, *ret;
4306 int qualifiers, storage;
4308 /* recursive type, remove storage bits first, apply them later again */
4309 storage = type->t & VT_STORAGE;
4310 type->t &= ~VT_STORAGE;
4311 post = ret = type;
4313 while (tok == '*') {
4314 qualifiers = 0;
4315 redo:
4316 next();
4317 switch(tok) {
4318 case TOK_CONST1:
4319 case TOK_CONST2:
4320 case TOK_CONST3:
4321 qualifiers |= VT_CONSTANT;
4322 goto redo;
4323 case TOK_VOLATILE1:
4324 case TOK_VOLATILE2:
4325 case TOK_VOLATILE3:
4326 qualifiers |= VT_VOLATILE;
4327 goto redo;
4328 case TOK_RESTRICT1:
4329 case TOK_RESTRICT2:
4330 case TOK_RESTRICT3:
4331 goto redo;
4332 /* XXX: clarify attribute handling */
4333 case TOK_ATTRIBUTE1:
4334 case TOK_ATTRIBUTE2:
4335 parse_attribute(ad);
4336 break;
4338 mk_pointer(type);
4339 type->t |= qualifiers;
4340 if (ret == type)
4341 /* innermost pointed to type is the one for the first derivation */
4342 ret = pointed_type(type);
4345 if (tok == '(') {
4346 /* This is possibly a parameter type list for abstract declarators
4347 ('int ()'), use post_type for testing this. */
4348 if (!post_type(type, ad, 0, td)) {
4349 /* It's not, so it's a nested declarator, and the post operations
4350 apply to the innermost pointed to type (if any). */
4351 /* XXX: this is not correct to modify 'ad' at this point, but
4352 the syntax is not clear */
4353 parse_attribute(ad);
4354 post = type_decl(type, ad, v, td);
4355 skip(')');
4357 } else if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
4358 /* type identifier */
4359 *v = tok;
4360 next();
4361 } else {
4362 if (!(td & TYPE_ABSTRACT))
4363 expect("identifier");
4364 *v = 0;
4366 post_type(post, ad, storage, 0);
4367 parse_attribute(ad);
4368 type->t |= storage;
4369 return ret;
4372 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
4373 ST_FUNC int lvalue_type(int t)
4375 int bt, r;
4376 r = VT_LVAL;
4377 bt = t & VT_BTYPE;
4378 if (bt == VT_BYTE || bt == VT_BOOL)
4379 r |= VT_LVAL_BYTE;
4380 else if (bt == VT_SHORT)
4381 r |= VT_LVAL_SHORT;
4382 else
4383 return r;
4384 if (t & VT_UNSIGNED)
4385 r |= VT_LVAL_UNSIGNED;
4386 return r;
4389 /* indirection with full error checking and bound check */
4390 ST_FUNC void indir(void)
4392 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
4393 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
4394 return;
4395 expect("pointer");
4397 if (vtop->r & VT_LVAL)
4398 gv(RC_INT);
4399 vtop->type = *pointed_type(&vtop->type);
4400 /* Arrays and functions are never lvalues */
4401 if (!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_VLA)
4402 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
4403 vtop->r |= lvalue_type(vtop->type.t);
4404 /* if bound checking, the referenced pointer must be checked */
4405 #ifdef CONFIG_TCC_BCHECK
4406 if (tcc_state->do_bounds_check)
4407 vtop->r |= VT_MUSTBOUND;
4408 #endif
4412 /* pass a parameter to a function and do type checking and casting */
4413 static void gfunc_param_typed(Sym *func, Sym *arg)
4415 int func_type;
4416 CType type;
4418 func_type = func->f.func_type;
4419 if (func_type == FUNC_OLD ||
4420 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
4421 /* default casting : only need to convert float to double */
4422 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
4423 gen_cast_s(VT_DOUBLE);
4424 } else if (vtop->type.t & VT_BITFIELD) {
4425 type.t = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
4426 type.ref = vtop->type.ref;
4427 gen_cast(&type);
4429 } else if (arg == NULL) {
4430 tcc_error("too many arguments to function");
4431 } else {
4432 type = arg->type;
4433 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
4434 gen_assign_cast(&type);
4438 /* parse an expression and return its type without any side effect.
4439 If UNRY we parse an unary expression, otherwise a full one. */
4440 static void expr_type(CType *type, int unry)
4442 nocode_wanted++;
4443 if (unry)
4444 unary();
4445 else
4446 gexpr();
4447 *type = vtop->type;
4448 vpop();
4449 nocode_wanted--;
4452 /* parse an expression of the form '(type)' or '(expr)' and return its
4453 type */
4454 static void parse_expr_type(CType *type)
4456 int n;
4457 AttributeDef ad;
4459 skip('(');
4460 if (parse_btype(type, &ad)) {
4461 type_decl(type, &ad, &n, TYPE_ABSTRACT);
4462 } else {
4463 expr_type(type, 0);
4465 skip(')');
4468 static void parse_type(CType *type)
4470 AttributeDef ad;
4471 int n;
4473 if (!parse_btype(type, &ad)) {
4474 expect("type");
4476 type_decl(type, &ad, &n, TYPE_ABSTRACT);
4479 static void parse_builtin_params(int nc, const char *args)
4481 char c, sep = '(';
4482 CType t;
4483 if (nc)
4484 nocode_wanted++;
4485 next();
4486 while ((c = *args++)) {
4487 skip(sep);
4488 sep = ',';
4489 switch (c) {
4490 case 'e': expr_eq(); continue;
4491 case 't': parse_type(&t); vpush(&t); continue;
4492 default: tcc_error("internal error"); break;
4495 skip(')');
4496 if (nc)
4497 nocode_wanted--;
4500 ST_FUNC void unary(void)
4502 int n, t, align, size, r, sizeof_caller;
4503 CType type;
4504 Sym *s;
4505 AttributeDef ad;
4507 sizeof_caller = in_sizeof;
4508 in_sizeof = 0;
4509 type.ref = NULL;
4510 /* XXX: GCC 2.95.3 does not generate a table although it should be
4511 better here */
4512 tok_next:
4513 switch(tok) {
4514 case TOK_EXTENSION:
4515 next();
4516 goto tok_next;
4517 case TOK_CINT:
4518 case TOK_CCHAR:
4519 case TOK_LCHAR:
4520 t = VT_INT;
4521 push_tokc:
4522 type.t = t;
4523 vsetc(&type, VT_CONST, &tokc);
4524 next();
4525 break;
4526 case TOK_CUINT:
4527 t = VT_INT | VT_UNSIGNED;
4528 goto push_tokc;
4529 case TOK_CLLONG:
4530 t = VT_LLONG;
4531 goto push_tokc;
4532 case TOK_CULLONG:
4533 t = VT_LLONG | VT_UNSIGNED;
4534 goto push_tokc;
4535 case TOK_CFLOAT:
4536 t = VT_FLOAT;
4537 goto push_tokc;
4538 case TOK_CDOUBLE:
4539 t = VT_DOUBLE;
4540 goto push_tokc;
4541 case TOK_CLDOUBLE:
4542 t = VT_LDOUBLE;
4543 goto push_tokc;
4545 case TOK___FUNCTION__:
4546 if (!gnu_ext)
4547 goto tok_identifier;
4548 /* fall thru */
4549 case TOK___FUNC__:
4551 void *ptr;
4552 int len;
4553 /* special function name identifier */
4554 len = strlen(funcname) + 1;
4555 /* generate char[len] type */
4556 type.t = VT_BYTE;
4557 mk_pointer(&type);
4558 type.t |= VT_ARRAY;
4559 type.ref->c = len;
4560 vpush_ref(&type, data_section, data_section->data_offset, len);
4561 ptr = section_ptr_add(data_section, len);
4562 memcpy(ptr, funcname, len);
4563 next();
4565 break;
4566 case TOK_LSTR:
4567 #ifdef TCC_TARGET_PE
4568 t = VT_SHORT | VT_UNSIGNED;
4569 #else
4570 t = VT_INT;
4571 #endif
4572 goto str_init;
4573 case TOK_STR:
4574 /* string parsing */
4575 t = VT_BYTE;
4576 if (tcc_state->char_is_unsigned)
4577 t = VT_BYTE | VT_UNSIGNED;
4578 str_init:
4579 if (tcc_state->warn_write_strings)
4580 t |= VT_CONSTANT;
4581 type.t = t;
4582 mk_pointer(&type);
4583 type.t |= VT_ARRAY;
4584 memset(&ad, 0, sizeof(AttributeDef));
4585 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, 0);
4586 break;
4587 case '(':
4588 next();
4589 /* cast ? */
4590 if (parse_btype(&type, &ad)) {
4591 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
4592 skip(')');
4593 /* check ISOC99 compound literal */
4594 if (tok == '{') {
4595 /* data is allocated locally by default */
4596 if (global_expr)
4597 r = VT_CONST;
4598 else
4599 r = VT_LOCAL;
4600 /* all except arrays are lvalues */
4601 if (!(type.t & VT_ARRAY))
4602 r |= lvalue_type(type.t);
4603 memset(&ad, 0, sizeof(AttributeDef));
4604 decl_initializer_alloc(&type, &ad, r, 1, 0, 0);
4605 } else {
4606 if (sizeof_caller) {
4607 vpush(&type);
4608 return;
4610 unary();
4611 gen_cast(&type);
4613 } else if (tok == '{') {
4614 int saved_nocode_wanted = nocode_wanted;
4615 if (const_wanted)
4616 tcc_error("expected constant");
4617 /* save all registers */
4618 save_regs(0);
4619 /* statement expression : we do not accept break/continue
4620 inside as GCC does. We do retain the nocode_wanted state,
4621 as statement expressions can't ever be entered from the
4622 outside, so any reactivation of code emission (from labels
4623 or loop heads) can be disabled again after the end of it. */
4624 block(NULL, NULL, 1);
4625 nocode_wanted = saved_nocode_wanted;
4626 skip(')');
4627 } else {
4628 gexpr();
4629 skip(')');
4631 break;
4632 case '*':
4633 next();
4634 unary();
4635 indir();
4636 break;
4637 case '&':
4638 next();
4639 unary();
4640 /* functions names must be treated as function pointers,
4641 except for unary '&' and sizeof. Since we consider that
4642 functions are not lvalues, we only have to handle it
4643 there and in function calls. */
4644 /* arrays can also be used although they are not lvalues */
4645 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
4646 !(vtop->type.t & VT_ARRAY))
4647 test_lvalue();
4648 mk_pointer(&vtop->type);
4649 gaddrof();
4650 break;
4651 case '!':
4652 next();
4653 unary();
4654 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4655 gen_cast_s(VT_BOOL);
4656 vtop->c.i = !vtop->c.i;
4657 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
4658 vtop->c.i ^= 1;
4659 else {
4660 save_regs(1);
4661 vseti(VT_JMP, gvtst(1, 0));
4663 break;
4664 case '~':
4665 next();
4666 unary();
4667 vpushi(-1);
4668 gen_op('^');
4669 break;
4670 case '+':
4671 next();
4672 unary();
4673 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
4674 tcc_error("pointer not accepted for unary plus");
4675 /* In order to force cast, we add zero, except for floating point
4676 where we really need an noop (otherwise -0.0 will be transformed
4677 into +0.0). */
4678 if (!is_float(vtop->type.t)) {
4679 vpushi(0);
4680 gen_op('+');
4682 break;
4683 case TOK_SIZEOF:
4684 case TOK_ALIGNOF1:
4685 case TOK_ALIGNOF2:
4686 t = tok;
4687 next();
4688 in_sizeof++;
4689 expr_type(&type, 1); // Perform a in_sizeof = 0;
4690 s = vtop[1].sym; /* hack: accessing previous vtop */
4691 size = type_size(&type, &align);
4692 if (s && s->a.aligned)
4693 align = 1 << (s->a.aligned - 1);
4694 if (t == TOK_SIZEOF) {
4695 if (!(type.t & VT_VLA)) {
4696 if (size < 0)
4697 tcc_error("sizeof applied to an incomplete type");
4698 vpushs(size);
4699 } else {
4700 vla_runtime_type_size(&type, &align);
4702 } else {
4703 vpushs(align);
4705 vtop->type.t |= VT_UNSIGNED;
4706 break;
4708 case TOK_builtin_expect:
4709 /* __builtin_expect is a no-op for now */
4710 parse_builtin_params(0, "ee");
4711 vpop();
4712 break;
4713 case TOK_builtin_types_compatible_p:
4714 parse_builtin_params(0, "tt");
4715 vtop[-1].type.t &= ~(VT_CONSTANT | VT_VOLATILE);
4716 vtop[0].type.t &= ~(VT_CONSTANT | VT_VOLATILE);
4717 n = is_compatible_types(&vtop[-1].type, &vtop[0].type);
4718 vtop -= 2;
4719 vpushi(n);
4720 break;
4721 case TOK_builtin_choose_expr:
4723 int64_t c;
4724 next();
4725 skip('(');
4726 c = expr_const64();
4727 skip(',');
4728 if (!c) {
4729 nocode_wanted++;
4731 expr_eq();
4732 if (!c) {
4733 vpop();
4734 nocode_wanted--;
4736 skip(',');
4737 if (c) {
4738 nocode_wanted++;
4740 expr_eq();
4741 if (c) {
4742 vpop();
4743 nocode_wanted--;
4745 skip(')');
4747 break;
4748 case TOK_builtin_constant_p:
4749 parse_builtin_params(1, "e");
4750 n = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
4751 vtop--;
4752 vpushi(n);
4753 break;
4754 case TOK_builtin_frame_address:
4755 case TOK_builtin_return_address:
4757 int tok1 = tok;
4758 int level;
4759 next();
4760 skip('(');
4761 if (tok != TOK_CINT) {
4762 tcc_error("%s only takes positive integers",
4763 tok1 == TOK_builtin_return_address ?
4764 "__builtin_return_address" :
4765 "__builtin_frame_address");
4767 level = (uint32_t)tokc.i;
4768 next();
4769 skip(')');
4770 type.t = VT_VOID;
4771 mk_pointer(&type);
4772 vset(&type, VT_LOCAL, 0); /* local frame */
4773 while (level--) {
4774 mk_pointer(&vtop->type);
4775 indir(); /* -> parent frame */
4777 if (tok1 == TOK_builtin_return_address) {
4778 // assume return address is just above frame pointer on stack
4779 vpushi(PTR_SIZE);
4780 gen_op('+');
4781 mk_pointer(&vtop->type);
4782 indir();
4785 break;
4786 #ifdef TCC_TARGET_X86_64
4787 #ifdef TCC_TARGET_PE
4788 case TOK_builtin_va_start:
4789 parse_builtin_params(0, "ee");
4790 r = vtop->r & VT_VALMASK;
4791 if (r == VT_LLOCAL)
4792 r = VT_LOCAL;
4793 if (r != VT_LOCAL)
4794 tcc_error("__builtin_va_start expects a local variable");
4795 vtop->r = r;
4796 vtop->type = char_pointer_type;
4797 vtop->c.i += 8;
4798 vstore();
4799 break;
4800 #else
4801 case TOK_builtin_va_arg_types:
4802 parse_builtin_params(0, "t");
4803 vpushi(classify_x86_64_va_arg(&vtop->type));
4804 vswap();
4805 vpop();
4806 break;
4807 #endif
4808 #endif
4810 #ifdef TCC_TARGET_ARM64
4811 case TOK___va_start: {
4812 parse_builtin_params(0, "ee");
4813 //xx check types
4814 gen_va_start();
4815 vpushi(0);
4816 vtop->type.t = VT_VOID;
4817 break;
4819 case TOK___va_arg: {
4820 parse_builtin_params(0, "et");
4821 type = vtop->type;
4822 vpop();
4823 //xx check types
4824 gen_va_arg(&type);
4825 vtop->type = type;
4826 break;
4828 case TOK___arm64_clear_cache: {
4829 parse_builtin_params(0, "ee");
4830 gen_clear_cache();
4831 vpushi(0);
4832 vtop->type.t = VT_VOID;
4833 break;
4835 #endif
4836 /* pre operations */
4837 case TOK_INC:
4838 case TOK_DEC:
4839 t = tok;
4840 next();
4841 unary();
4842 inc(0, t);
4843 break;
4844 case '-':
4845 next();
4846 unary();
4847 t = vtop->type.t & VT_BTYPE;
4848 if (is_float(t)) {
4849 /* In IEEE negate(x) isn't subtract(0,x), but rather
4850 subtract(-0, x). */
4851 vpush(&vtop->type);
4852 if (t == VT_FLOAT)
4853 vtop->c.f = -1.0 * 0.0;
4854 else if (t == VT_DOUBLE)
4855 vtop->c.d = -1.0 * 0.0;
4856 else
4857 vtop->c.ld = -1.0 * 0.0;
4858 } else
4859 vpushi(0);
4860 vswap();
4861 gen_op('-');
4862 break;
4863 case TOK_LAND:
4864 if (!gnu_ext)
4865 goto tok_identifier;
4866 next();
4867 /* allow to take the address of a label */
4868 if (tok < TOK_UIDENT)
4869 expect("label identifier");
4870 s = label_find(tok);
4871 if (!s) {
4872 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
4873 } else {
4874 if (s->r == LABEL_DECLARED)
4875 s->r = LABEL_FORWARD;
4877 if (!s->type.t) {
4878 s->type.t = VT_VOID;
4879 mk_pointer(&s->type);
4880 s->type.t |= VT_STATIC;
4882 vpushsym(&s->type, s);
4883 next();
4884 break;
4886 case TOK_GENERIC:
4888 CType controlling_type;
4889 int has_default = 0;
4890 int has_match = 0;
4891 CType cur_type;
4892 AttributeDef ad_tmp;
4893 int learn = 0;
4894 TokenString *str = NULL;
4895 ParseState saved_parse_state;
4897 next();
4898 skip('(');
4899 expr_type(&controlling_type, 1);
4900 if (controlling_type.t & VT_ARRAY)
4901 controlling_type.t = VT_PTR;
4902 controlling_type.t &= ~VT_CONSTANT;
4903 for (;;) {
4904 learn = 0;
4905 skip(',');
4906 if (tok == TOK_DEFAULT) {
4907 if (has_default)
4908 tcc_error("too many 'default'");
4909 if (!has_match) {
4910 has_default = 1;
4911 learn = 1;
4913 next();
4914 } else {
4915 int itmp;
4917 parse_btype(&cur_type, &ad_tmp);
4918 type_decl(&cur_type, &ad_tmp, &itmp, TYPE_ABSTRACT);
4919 if (compare_types(&controlling_type, &cur_type, 0)) {
4920 if (has_match) {
4921 // tcc_error("type march twice");
4923 if (str)
4924 tok_str_free(str);
4925 has_match = 1;
4926 learn = 1;
4929 skip(':');
4930 if (learn) {
4931 skip_or_save_block(&str);
4932 } else {
4933 skip_or_save_block(NULL);
4935 if (tok == ',')
4936 continue;
4937 else if (tok == ')')
4938 break;
4940 if (!has_match && !has_default) {
4941 char buf[256];
4943 type_to_str(buf, 256, &controlling_type, NULL);
4944 tcc_error("_Generic sellector of type '%s' is not compatible with any assosiation",
4945 buf);
4947 skip(')');
4948 save_parse_state(&saved_parse_state);
4949 begin_macro(str, 1);
4950 next();
4951 expr_eq();
4952 end_macro();
4953 restore_parse_state(&saved_parse_state);
4954 break;
4956 // special qnan , snan and infinity values
4957 case TOK___NAN__:
4958 vpush64(VT_DOUBLE, 0x7ff8000000000000ULL);
4959 next();
4960 break;
4961 case TOK___SNAN__:
4962 vpush64(VT_DOUBLE, 0x7ff0000000000001ULL);
4963 next();
4964 break;
4965 case TOK___INF__:
4966 vpush64(VT_DOUBLE, 0x7ff0000000000000ULL);
4967 next();
4968 break;
4970 default:
4971 tok_identifier:
4972 t = tok;
4973 next();
4974 if (t < TOK_UIDENT)
4975 expect("identifier");
4976 s = sym_find(t);
4977 if (!s) {
4978 const char *name = get_tok_str(t, NULL);
4979 if (tok != '(')
4980 tcc_error("'%s' undeclared", name);
4981 /* for simple function calls, we tolerate undeclared
4982 external reference to int() function */
4983 if (tcc_state->warn_implicit_function_declaration
4984 #ifdef TCC_TARGET_PE
4985 /* people must be warned about using undeclared WINAPI functions
4986 (which usually start with uppercase letter) */
4987 || (name[0] >= 'A' && name[0] <= 'Z')
4988 #endif
4990 tcc_warning("implicit declaration of function '%s'", name);
4991 s = external_global_sym(t, &func_old_type, 0);
4994 r = s->r;
4995 /* A symbol that has a register is a local register variable,
4996 which starts out as VT_LOCAL value. */
4997 if ((r & VT_VALMASK) < VT_CONST)
4998 r = (r & ~VT_VALMASK) | VT_LOCAL;
5000 vset(&s->type, r, s->c);
5001 /* Point to s as backpointer (even without r&VT_SYM).
5002 Will be used by at least the x86 inline asm parser for
5003 regvars. */
5004 vtop->sym = s;
5006 if (r & VT_SYM) {
5007 vtop->c.i = 0;
5008 } else if (r == VT_CONST && IS_ENUM_VAL(s->type.t)) {
5009 vtop->c.i = s->enum_val;
5011 break;
5014 /* post operations */
5015 while (1) {
5016 if (tok == TOK_INC || tok == TOK_DEC) {
5017 inc(1, tok);
5018 next();
5019 } else if (tok == '.' || tok == TOK_ARROW || tok == TOK_CDOUBLE) {
5020 int qualifiers;
5021 /* field */
5022 if (tok == TOK_ARROW)
5023 indir();
5024 qualifiers = vtop->type.t & (VT_CONSTANT | VT_VOLATILE);
5025 test_lvalue();
5026 gaddrof();
5027 /* expect pointer on structure */
5028 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
5029 expect("struct or union");
5030 if (tok == TOK_CDOUBLE)
5031 expect("field name");
5032 next();
5033 if (tok == TOK_CINT || tok == TOK_CUINT)
5034 expect("field name");
5035 s = find_field(&vtop->type, tok);
5036 if (!s)
5037 tcc_error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, &tokc));
5038 /* add field offset to pointer */
5039 vtop->type = char_pointer_type; /* change type to 'char *' */
5040 vpushi(s->c);
5041 gen_op('+');
5042 /* change type to field type, and set to lvalue */
5043 vtop->type = s->type;
5044 vtop->type.t |= qualifiers;
5045 /* an array is never an lvalue */
5046 if (!(vtop->type.t & VT_ARRAY)) {
5047 vtop->r |= lvalue_type(vtop->type.t);
5048 #ifdef CONFIG_TCC_BCHECK
5049 /* if bound checking, the referenced pointer must be checked */
5050 if (tcc_state->do_bounds_check && (vtop->r & VT_VALMASK) != VT_LOCAL)
5051 vtop->r |= VT_MUSTBOUND;
5052 #endif
5054 next();
5055 } else if (tok == '[') {
5056 next();
5057 gexpr();
5058 gen_op('+');
5059 indir();
5060 skip(']');
5061 } else if (tok == '(') {
5062 SValue ret;
5063 Sym *sa;
5064 int nb_args, ret_nregs, ret_align, regsize, variadic;
5066 /* function call */
5067 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
5068 /* pointer test (no array accepted) */
5069 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
5070 vtop->type = *pointed_type(&vtop->type);
5071 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
5072 goto error_func;
5073 } else {
5074 error_func:
5075 expect("function pointer");
5077 } else {
5078 vtop->r &= ~VT_LVAL; /* no lvalue */
5080 /* get return type */
5081 s = vtop->type.ref;
5082 next();
5083 sa = s->next; /* first parameter */
5084 nb_args = regsize = 0;
5085 ret.r2 = VT_CONST;
5086 /* compute first implicit argument if a structure is returned */
5087 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
5088 variadic = (s->f.func_type == FUNC_ELLIPSIS);
5089 ret_nregs = gfunc_sret(&s->type, variadic, &ret.type,
5090 &ret_align, &regsize);
5091 if (!ret_nregs) {
5092 /* get some space for the returned structure */
5093 size = type_size(&s->type, &align);
5094 #ifdef TCC_TARGET_ARM64
5095 /* On arm64, a small struct is return in registers.
5096 It is much easier to write it to memory if we know
5097 that we are allowed to write some extra bytes, so
5098 round the allocated space up to a power of 2: */
5099 if (size < 16)
5100 while (size & (size - 1))
5101 size = (size | (size - 1)) + 1;
5102 #endif
5103 loc = (loc - size) & -align;
5104 ret.type = s->type;
5105 ret.r = VT_LOCAL | VT_LVAL;
5106 /* pass it as 'int' to avoid structure arg passing
5107 problems */
5108 vseti(VT_LOCAL, loc);
5109 ret.c = vtop->c;
5110 nb_args++;
5112 } else {
5113 ret_nregs = 1;
5114 ret.type = s->type;
5117 if (ret_nregs) {
5118 /* return in register */
5119 if (is_float(ret.type.t)) {
5120 ret.r = reg_fret(ret.type.t);
5121 #ifdef TCC_TARGET_X86_64
5122 if ((ret.type.t & VT_BTYPE) == VT_QFLOAT)
5123 ret.r2 = REG_QRET;
5124 #endif
5125 } else {
5126 #ifndef TCC_TARGET_ARM64
5127 #ifdef TCC_TARGET_X86_64
5128 if ((ret.type.t & VT_BTYPE) == VT_QLONG)
5129 #else
5130 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
5131 #endif
5132 ret.r2 = REG_LRET;
5133 #endif
5134 ret.r = REG_IRET;
5136 ret.c.i = 0;
5138 if (tok != ')') {
5139 for(;;) {
5140 expr_eq();
5141 gfunc_param_typed(s, sa);
5142 nb_args++;
5143 if (sa)
5144 sa = sa->next;
5145 if (tok == ')')
5146 break;
5147 skip(',');
5150 if (sa)
5151 tcc_error("too few arguments to function");
5152 skip(')');
5153 gfunc_call(nb_args);
5155 /* return value */
5156 for (r = ret.r + ret_nregs + !ret_nregs; r-- > ret.r;) {
5157 vsetc(&ret.type, r, &ret.c);
5158 vtop->r2 = ret.r2; /* Loop only happens when r2 is VT_CONST */
5161 /* handle packed struct return */
5162 if (((s->type.t & VT_BTYPE) == VT_STRUCT) && ret_nregs) {
5163 int addr, offset;
5165 size = type_size(&s->type, &align);
5166 /* We're writing whole regs often, make sure there's enough
5167 space. Assume register size is power of 2. */
5168 if (regsize > align)
5169 align = regsize;
5170 loc = (loc - size) & -align;
5171 addr = loc;
5172 offset = 0;
5173 for (;;) {
5174 vset(&ret.type, VT_LOCAL | VT_LVAL, addr + offset);
5175 vswap();
5176 vstore();
5177 vtop--;
5178 if (--ret_nregs == 0)
5179 break;
5180 offset += regsize;
5182 vset(&s->type, VT_LOCAL | VT_LVAL, addr);
5184 } else {
5185 break;
5190 ST_FUNC void expr_prod(void)
5192 int t;
5194 unary();
5195 while (tok == '*' || tok == '/' || tok == '%') {
5196 t = tok;
5197 next();
5198 unary();
5199 gen_op(t);
5203 ST_FUNC void expr_sum(void)
5205 int t;
5207 expr_prod();
5208 while (tok == '+' || tok == '-') {
5209 t = tok;
5210 next();
5211 expr_prod();
5212 gen_op(t);
5216 static void expr_shift(void)
5218 int t;
5220 expr_sum();
5221 while (tok == TOK_SHL || tok == TOK_SAR) {
5222 t = tok;
5223 next();
5224 expr_sum();
5225 gen_op(t);
5229 static void expr_cmp(void)
5231 int t;
5233 expr_shift();
5234 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
5235 tok == TOK_ULT || tok == TOK_UGE) {
5236 t = tok;
5237 next();
5238 expr_shift();
5239 gen_op(t);
5243 static void expr_cmpeq(void)
5245 int t;
5247 expr_cmp();
5248 while (tok == TOK_EQ || tok == TOK_NE) {
5249 t = tok;
5250 next();
5251 expr_cmp();
5252 gen_op(t);
5256 static void expr_and(void)
5258 expr_cmpeq();
5259 while (tok == '&') {
5260 next();
5261 expr_cmpeq();
5262 gen_op('&');
5266 static void expr_xor(void)
5268 expr_and();
5269 while (tok == '^') {
5270 next();
5271 expr_and();
5272 gen_op('^');
5276 static void expr_or(void)
5278 expr_xor();
5279 while (tok == '|') {
5280 next();
5281 expr_xor();
5282 gen_op('|');
5286 static void expr_land(void)
5288 expr_or();
5289 if (tok == TOK_LAND) {
5290 int t = 0;
5291 for(;;) {
5292 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
5293 gen_cast_s(VT_BOOL);
5294 if (vtop->c.i) {
5295 vpop();
5296 } else {
5297 nocode_wanted++;
5298 while (tok == TOK_LAND) {
5299 next();
5300 expr_or();
5301 vpop();
5303 nocode_wanted--;
5304 if (t)
5305 gsym(t);
5306 gen_cast_s(VT_INT);
5307 break;
5309 } else {
5310 if (!t)
5311 save_regs(1);
5312 t = gvtst(1, t);
5314 if (tok != TOK_LAND) {
5315 if (t)
5316 vseti(VT_JMPI, t);
5317 else
5318 vpushi(1);
5319 break;
5321 next();
5322 expr_or();
5327 static void expr_lor(void)
5329 expr_land();
5330 if (tok == TOK_LOR) {
5331 int t = 0;
5332 for(;;) {
5333 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
5334 gen_cast_s(VT_BOOL);
5335 if (!vtop->c.i) {
5336 vpop();
5337 } else {
5338 nocode_wanted++;
5339 while (tok == TOK_LOR) {
5340 next();
5341 expr_land();
5342 vpop();
5344 nocode_wanted--;
5345 if (t)
5346 gsym(t);
5347 gen_cast_s(VT_INT);
5348 break;
5350 } else {
5351 if (!t)
5352 save_regs(1);
5353 t = gvtst(0, t);
5355 if (tok != TOK_LOR) {
5356 if (t)
5357 vseti(VT_JMP, t);
5358 else
5359 vpushi(0);
5360 break;
5362 next();
5363 expr_land();
5368 /* Assuming vtop is a value used in a conditional context
5369 (i.e. compared with zero) return 0 if it's false, 1 if
5370 true and -1 if it can't be statically determined. */
5371 static int condition_3way(void)
5373 int c = -1;
5374 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST &&
5375 (!(vtop->r & VT_SYM) || !vtop->sym->a.weak)) {
5376 vdup();
5377 gen_cast_s(VT_BOOL);
5378 c = vtop->c.i;
5379 vpop();
5381 return c;
5384 static void expr_cond(void)
5386 int tt, u, r1, r2, rc, t1, t2, bt1, bt2, islv, c, g;
5387 SValue sv;
5388 CType type, type1, type2;
5390 expr_lor();
5391 if (tok == '?') {
5392 next();
5393 c = condition_3way();
5394 g = (tok == ':' && gnu_ext);
5395 if (c < 0) {
5396 /* needed to avoid having different registers saved in
5397 each branch */
5398 if (is_float(vtop->type.t)) {
5399 rc = RC_FLOAT;
5400 #ifdef TCC_TARGET_X86_64
5401 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
5402 rc = RC_ST0;
5404 #endif
5405 } else
5406 rc = RC_INT;
5407 gv(rc);
5408 save_regs(1);
5409 if (g)
5410 gv_dup();
5411 tt = gvtst(1, 0);
5413 } else {
5414 if (!g)
5415 vpop();
5416 tt = 0;
5419 if (1) {
5420 if (c == 0)
5421 nocode_wanted++;
5422 if (!g)
5423 gexpr();
5425 type1 = vtop->type;
5426 sv = *vtop; /* save value to handle it later */
5427 vtop--; /* no vpop so that FP stack is not flushed */
5428 skip(':');
5430 u = 0;
5431 if (c < 0)
5432 u = gjmp(0);
5433 gsym(tt);
5435 if (c == 0)
5436 nocode_wanted--;
5437 if (c == 1)
5438 nocode_wanted++;
5439 expr_cond();
5440 if (c == 1)
5441 nocode_wanted--;
5443 type2 = vtop->type;
5444 t1 = type1.t;
5445 bt1 = t1 & VT_BTYPE;
5446 t2 = type2.t;
5447 bt2 = t2 & VT_BTYPE;
5448 type.ref = NULL;
5450 /* cast operands to correct type according to ISOC rules */
5451 if (is_float(bt1) || is_float(bt2)) {
5452 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
5453 type.t = VT_LDOUBLE;
5455 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
5456 type.t = VT_DOUBLE;
5457 } else {
5458 type.t = VT_FLOAT;
5460 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
5461 /* cast to biggest op */
5462 type.t = VT_LLONG;
5463 /* convert to unsigned if it does not fit in a long long */
5464 if ((t1 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_LLONG | VT_UNSIGNED) ||
5465 (t2 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_LLONG | VT_UNSIGNED))
5466 type.t |= VT_UNSIGNED;
5467 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
5468 /* If one is a null ptr constant the result type
5469 is the other. */
5470 if (is_null_pointer (vtop))
5471 type = type1;
5472 else if (is_null_pointer (&sv))
5473 type = type2;
5474 /* XXX: test pointer compatibility, C99 has more elaborate
5475 rules here. */
5476 else
5477 type = type1;
5478 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
5479 /* XXX: test function pointer compatibility */
5480 type = bt1 == VT_FUNC ? type1 : type2;
5481 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
5482 /* XXX: test structure compatibility */
5483 type = bt1 == VT_STRUCT ? type1 : type2;
5484 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
5485 /* NOTE: as an extension, we accept void on only one side */
5486 type.t = VT_VOID;
5487 } else {
5488 /* integer operations */
5489 type.t = VT_INT;
5490 /* convert to unsigned if it does not fit in an integer */
5491 if ((t1 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_INT | VT_UNSIGNED) ||
5492 (t2 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_INT | VT_UNSIGNED))
5493 type.t |= VT_UNSIGNED;
5495 /* keep structs lvalue by transforming `(expr ? a : b)` to `*(expr ? &a : &b)` so
5496 that `(expr ? a : b).mem` does not error with "lvalue expected" */
5497 islv = (vtop->r & VT_LVAL) && (sv.r & VT_LVAL) && VT_STRUCT == (type.t & VT_BTYPE);
5498 islv &= c < 0;
5500 /* now we convert second operand */
5501 if (c != 1) {
5502 gen_cast(&type);
5503 if (islv) {
5504 mk_pointer(&vtop->type);
5505 gaddrof();
5506 } else if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
5507 gaddrof();
5510 rc = RC_INT;
5511 if (is_float(type.t)) {
5512 rc = RC_FLOAT;
5513 #ifdef TCC_TARGET_X86_64
5514 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
5515 rc = RC_ST0;
5517 #endif
5518 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
5519 /* for long longs, we use fixed registers to avoid having
5520 to handle a complicated move */
5521 rc = RC_IRET;
5524 tt = r2 = 0;
5525 if (c < 0) {
5526 r2 = gv(rc);
5527 tt = gjmp(0);
5529 gsym(u);
5531 /* this is horrible, but we must also convert first
5532 operand */
5533 if (c != 0) {
5534 *vtop = sv;
5535 gen_cast(&type);
5536 if (islv) {
5537 mk_pointer(&vtop->type);
5538 gaddrof();
5539 } else if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
5540 gaddrof();
5543 if (c < 0) {
5544 r1 = gv(rc);
5545 move_reg(r2, r1, type.t);
5546 vtop->r = r2;
5547 gsym(tt);
5548 if (islv)
5549 indir();
5555 static void expr_eq(void)
5557 int t;
5559 expr_cond();
5560 if (tok == '=' ||
5561 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
5562 tok == TOK_A_XOR || tok == TOK_A_OR ||
5563 tok == TOK_A_SHL || tok == TOK_A_SAR) {
5564 test_lvalue();
5565 t = tok;
5566 next();
5567 if (t == '=') {
5568 expr_eq();
5569 } else {
5570 vdup();
5571 expr_eq();
5572 gen_op(t & 0x7f);
5574 vstore();
5578 ST_FUNC void gexpr(void)
5580 while (1) {
5581 expr_eq();
5582 if (tok != ',')
5583 break;
5584 vpop();
5585 next();
5589 /* parse a constant expression and return value in vtop. */
5590 static void expr_const1(void)
5592 const_wanted++;
5593 expr_cond();
5594 const_wanted--;
5597 /* parse an integer constant and return its value. */
5598 static inline int64_t expr_const64(void)
5600 int64_t c;
5601 expr_const1();
5602 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
5603 expect("constant expression");
5604 c = vtop->c.i;
5605 vpop();
5606 return c;
5609 /* parse an integer constant and return its value.
5610 Complain if it doesn't fit 32bit (signed or unsigned). */
5611 ST_FUNC int expr_const(void)
5613 int c;
5614 int64_t wc = expr_const64();
5615 c = wc;
5616 if (c != wc && (unsigned)c != wc)
5617 tcc_error("constant exceeds 32 bit");
5618 return c;
5621 /* return the label token if current token is a label, otherwise
5622 return zero */
5623 static int is_label(void)
5625 int last_tok;
5627 /* fast test first */
5628 if (tok < TOK_UIDENT)
5629 return 0;
5630 /* no need to save tokc because tok is an identifier */
5631 last_tok = tok;
5632 next();
5633 if (tok == ':') {
5634 return last_tok;
5635 } else {
5636 unget_tok(last_tok);
5637 return 0;
5641 #ifndef TCC_TARGET_ARM64
5642 static void gfunc_return(CType *func_type)
5644 if ((func_type->t & VT_BTYPE) == VT_STRUCT) {
5645 CType type, ret_type;
5646 int ret_align, ret_nregs, regsize;
5647 ret_nregs = gfunc_sret(func_type, func_var, &ret_type,
5648 &ret_align, &regsize);
5649 if (0 == ret_nregs) {
5650 /* if returning structure, must copy it to implicit
5651 first pointer arg location */
5652 type = *func_type;
5653 mk_pointer(&type);
5654 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
5655 indir();
5656 vswap();
5657 /* copy structure value to pointer */
5658 vstore();
5659 } else {
5660 /* returning structure packed into registers */
5661 int r, size, addr, align;
5662 size = type_size(func_type,&align);
5663 if ((vtop->r != (VT_LOCAL | VT_LVAL) ||
5664 (vtop->c.i & (ret_align-1)))
5665 && (align & (ret_align-1))) {
5666 loc = (loc - size) & -ret_align;
5667 addr = loc;
5668 type = *func_type;
5669 vset(&type, VT_LOCAL | VT_LVAL, addr);
5670 vswap();
5671 vstore();
5672 vpop();
5673 vset(&ret_type, VT_LOCAL | VT_LVAL, addr);
5675 vtop->type = ret_type;
5676 if (is_float(ret_type.t))
5677 r = rc_fret(ret_type.t);
5678 else
5679 r = RC_IRET;
5681 if (ret_nregs == 1)
5682 gv(r);
5683 else {
5684 for (;;) {
5685 vdup();
5686 gv(r);
5687 vpop();
5688 if (--ret_nregs == 0)
5689 break;
5690 /* We assume that when a structure is returned in multiple
5691 registers, their classes are consecutive values of the
5692 suite s(n) = 2^n */
5693 r <<= 1;
5694 vtop->c.i += regsize;
5698 } else if (is_float(func_type->t)) {
5699 gv(rc_fret(func_type->t));
5700 } else {
5701 gv(RC_IRET);
5703 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
5705 #endif
5707 static int case_cmp(const void *pa, const void *pb)
5709 int64_t a = (*(struct case_t**) pa)->v1;
5710 int64_t b = (*(struct case_t**) pb)->v1;
5711 return a < b ? -1 : a > b;
5714 static void gcase(struct case_t **base, int len, int *bsym)
5716 struct case_t *p;
5717 int e;
5718 int ll = (vtop->type.t & VT_BTYPE) == VT_LLONG;
5719 gv(RC_INT);
5720 while (len > 4) {
5721 /* binary search */
5722 p = base[len/2];
5723 vdup();
5724 if (ll)
5725 vpushll(p->v2);
5726 else
5727 vpushi(p->v2);
5728 gen_op(TOK_LE);
5729 e = gtst(1, 0);
5730 vdup();
5731 if (ll)
5732 vpushll(p->v1);
5733 else
5734 vpushi(p->v1);
5735 gen_op(TOK_GE);
5736 gtst_addr(0, p->sym); /* v1 <= x <= v2 */
5737 /* x < v1 */
5738 gcase(base, len/2, bsym);
5739 if (cur_switch->def_sym)
5740 gjmp_addr(cur_switch->def_sym);
5741 else
5742 *bsym = gjmp(*bsym);
5743 /* x > v2 */
5744 gsym(e);
5745 e = len/2 + 1;
5746 base += e; len -= e;
5748 /* linear scan */
5749 while (len--) {
5750 p = *base++;
5751 vdup();
5752 if (ll)
5753 vpushll(p->v2);
5754 else
5755 vpushi(p->v2);
5756 if (p->v1 == p->v2) {
5757 gen_op(TOK_EQ);
5758 gtst_addr(0, p->sym);
5759 } else {
5760 gen_op(TOK_LE);
5761 e = gtst(1, 0);
5762 vdup();
5763 if (ll)
5764 vpushll(p->v1);
5765 else
5766 vpushi(p->v1);
5767 gen_op(TOK_GE);
5768 gtst_addr(0, p->sym);
5769 gsym(e);
5774 static void block(int *bsym, int *csym, int is_expr)
5776 int a, b, c, d, cond;
5777 Sym *s;
5779 /* generate line number info */
5780 if (tcc_state->do_debug)
5781 tcc_debug_line(tcc_state);
5783 if (is_expr) {
5784 /* default return value is (void) */
5785 vpushi(0);
5786 vtop->type.t = VT_VOID;
5789 if (tok == TOK_IF) {
5790 /* if test */
5791 int saved_nocode_wanted = nocode_wanted;
5792 next();
5793 skip('(');
5794 gexpr();
5795 skip(')');
5796 cond = condition_3way();
5797 if (cond == 1)
5798 a = 0, vpop();
5799 else
5800 a = gvtst(1, 0);
5801 if (cond == 0)
5802 nocode_wanted |= 0x20000000;
5803 block(bsym, csym, 0);
5804 if (cond != 1)
5805 nocode_wanted = saved_nocode_wanted;
5806 c = tok;
5807 if (c == TOK_ELSE) {
5808 next();
5809 d = gjmp(0);
5810 gsym(a);
5811 if (cond == 1)
5812 nocode_wanted |= 0x20000000;
5813 block(bsym, csym, 0);
5814 gsym(d); /* patch else jmp */
5815 if (cond != 0)
5816 nocode_wanted = saved_nocode_wanted;
5817 } else
5818 gsym(a);
5819 } else if (tok == TOK_WHILE) {
5820 int saved_nocode_wanted;
5821 nocode_wanted &= ~0x20000000;
5822 next();
5823 d = ind;
5824 vla_sp_restore();
5825 skip('(');
5826 gexpr();
5827 skip(')');
5828 a = gvtst(1, 0);
5829 b = 0;
5830 ++local_scope;
5831 saved_nocode_wanted = nocode_wanted;
5832 block(&a, &b, 0);
5833 nocode_wanted = saved_nocode_wanted;
5834 --local_scope;
5835 gjmp_addr(d);
5836 gsym(a);
5837 gsym_addr(b, d);
5838 } else if (tok == '{') {
5839 Sym *llabel;
5840 int block_vla_sp_loc = vla_sp_loc, saved_vlas_in_scope = vlas_in_scope;
5842 next();
5843 /* record local declaration stack position */
5844 s = local_stack;
5845 llabel = local_label_stack;
5846 ++local_scope;
5848 /* handle local labels declarations */
5849 if (tok == TOK_LABEL) {
5850 next();
5851 for(;;) {
5852 if (tok < TOK_UIDENT)
5853 expect("label identifier");
5854 label_push(&local_label_stack, tok, LABEL_DECLARED);
5855 next();
5856 if (tok == ',') {
5857 next();
5858 } else {
5859 skip(';');
5860 break;
5864 while (tok != '}') {
5865 if ((a = is_label()))
5866 unget_tok(a);
5867 else
5868 decl(VT_LOCAL);
5869 if (tok != '}') {
5870 if (is_expr)
5871 vpop();
5872 block(bsym, csym, is_expr);
5875 /* pop locally defined labels */
5876 label_pop(&local_label_stack, llabel, is_expr);
5877 /* pop locally defined symbols */
5878 --local_scope;
5879 /* In the is_expr case (a statement expression is finished here),
5880 vtop might refer to symbols on the local_stack. Either via the
5881 type or via vtop->sym. We can't pop those nor any that in turn
5882 might be referred to. To make it easier we don't roll back
5883 any symbols in that case; some upper level call to block() will
5884 do that. We do have to remove such symbols from the lookup
5885 tables, though. sym_pop will do that. */
5886 sym_pop(&local_stack, s, is_expr);
5888 /* Pop VLA frames and restore stack pointer if required */
5889 if (vlas_in_scope > saved_vlas_in_scope) {
5890 vla_sp_loc = saved_vlas_in_scope ? block_vla_sp_loc : vla_sp_root_loc;
5891 vla_sp_restore();
5893 vlas_in_scope = saved_vlas_in_scope;
5895 next();
5896 } else if (tok == TOK_RETURN) {
5897 next();
5898 if (tok != ';') {
5899 gexpr();
5900 gen_assign_cast(&func_vt);
5901 gfunc_return(&func_vt);
5903 skip(';');
5904 /* jump unless last stmt in top-level block */
5905 if (tok != '}' || local_scope != 1)
5906 rsym = gjmp(rsym);
5907 nocode_wanted |= 0x20000000;
5908 } else if (tok == TOK_BREAK) {
5909 /* compute jump */
5910 if (!bsym)
5911 tcc_error("cannot break");
5912 *bsym = gjmp(*bsym);
5913 next();
5914 skip(';');
5915 nocode_wanted |= 0x20000000;
5916 } else if (tok == TOK_CONTINUE) {
5917 /* compute jump */
5918 if (!csym)
5919 tcc_error("cannot continue");
5920 vla_sp_restore_root();
5921 *csym = gjmp(*csym);
5922 next();
5923 skip(';');
5924 } else if (tok == TOK_FOR) {
5925 int e;
5926 int saved_nocode_wanted;
5927 nocode_wanted &= ~0x20000000;
5928 next();
5929 skip('(');
5930 s = local_stack;
5931 ++local_scope;
5932 if (tok != ';') {
5933 /* c99 for-loop init decl? */
5934 if (!decl0(VT_LOCAL, 1, NULL)) {
5935 /* no, regular for-loop init expr */
5936 gexpr();
5937 vpop();
5940 skip(';');
5941 d = ind;
5942 c = ind;
5943 vla_sp_restore();
5944 a = 0;
5945 b = 0;
5946 if (tok != ';') {
5947 gexpr();
5948 a = gvtst(1, 0);
5950 skip(';');
5951 if (tok != ')') {
5952 e = gjmp(0);
5953 c = ind;
5954 vla_sp_restore();
5955 gexpr();
5956 vpop();
5957 gjmp_addr(d);
5958 gsym(e);
5960 skip(')');
5961 saved_nocode_wanted = nocode_wanted;
5962 block(&a, &b, 0);
5963 nocode_wanted = saved_nocode_wanted;
5964 gjmp_addr(c);
5965 gsym(a);
5966 gsym_addr(b, c);
5967 --local_scope;
5968 sym_pop(&local_stack, s, 0);
5970 } else
5971 if (tok == TOK_DO) {
5972 int saved_nocode_wanted;
5973 nocode_wanted &= ~0x20000000;
5974 next();
5975 a = 0;
5976 b = 0;
5977 d = ind;
5978 vla_sp_restore();
5979 saved_nocode_wanted = nocode_wanted;
5980 block(&a, &b, 0);
5981 skip(TOK_WHILE);
5982 skip('(');
5983 gsym(b);
5984 gexpr();
5985 c = gvtst(0, 0);
5986 gsym_addr(c, d);
5987 nocode_wanted = saved_nocode_wanted;
5988 skip(')');
5989 gsym(a);
5990 skip(';');
5991 } else
5992 if (tok == TOK_SWITCH) {
5993 struct switch_t *saved, sw;
5994 int saved_nocode_wanted = nocode_wanted;
5995 SValue switchval;
5996 next();
5997 skip('(');
5998 gexpr();
5999 skip(')');
6000 switchval = *vtop--;
6001 a = 0;
6002 b = gjmp(0); /* jump to first case */
6003 sw.p = NULL; sw.n = 0; sw.def_sym = 0;
6004 saved = cur_switch;
6005 cur_switch = &sw;
6006 block(&a, csym, 0);
6007 nocode_wanted = saved_nocode_wanted;
6008 a = gjmp(a); /* add implicit break */
6009 /* case lookup */
6010 gsym(b);
6011 qsort(sw.p, sw.n, sizeof(void*), case_cmp);
6012 for (b = 1; b < sw.n; b++)
6013 if (sw.p[b - 1]->v2 >= sw.p[b]->v1)
6014 tcc_error("duplicate case value");
6015 /* Our switch table sorting is signed, so the compared
6016 value needs to be as well when it's 64bit. */
6017 if ((switchval.type.t & VT_BTYPE) == VT_LLONG)
6018 switchval.type.t &= ~VT_UNSIGNED;
6019 vpushv(&switchval);
6020 gcase(sw.p, sw.n, &a);
6021 vpop();
6022 if (sw.def_sym)
6023 gjmp_addr(sw.def_sym);
6024 dynarray_reset(&sw.p, &sw.n);
6025 cur_switch = saved;
6026 /* break label */
6027 gsym(a);
6028 } else
6029 if (tok == TOK_CASE) {
6030 struct case_t *cr = tcc_malloc(sizeof(struct case_t));
6031 if (!cur_switch)
6032 expect("switch");
6033 nocode_wanted &= ~0x20000000;
6034 next();
6035 cr->v1 = cr->v2 = expr_const64();
6036 if (gnu_ext && tok == TOK_DOTS) {
6037 next();
6038 cr->v2 = expr_const64();
6039 if (cr->v2 < cr->v1)
6040 tcc_warning("empty case range");
6042 cr->sym = ind;
6043 dynarray_add(&cur_switch->p, &cur_switch->n, cr);
6044 skip(':');
6045 is_expr = 0;
6046 goto block_after_label;
6047 } else
6048 if (tok == TOK_DEFAULT) {
6049 next();
6050 skip(':');
6051 if (!cur_switch)
6052 expect("switch");
6053 if (cur_switch->def_sym)
6054 tcc_error("too many 'default'");
6055 cur_switch->def_sym = ind;
6056 is_expr = 0;
6057 goto block_after_label;
6058 } else
6059 if (tok == TOK_GOTO) {
6060 next();
6061 if (tok == '*' && gnu_ext) {
6062 /* computed goto */
6063 next();
6064 gexpr();
6065 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
6066 expect("pointer");
6067 ggoto();
6068 } else if (tok >= TOK_UIDENT) {
6069 s = label_find(tok);
6070 /* put forward definition if needed */
6071 if (!s) {
6072 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
6073 } else {
6074 if (s->r == LABEL_DECLARED)
6075 s->r = LABEL_FORWARD;
6077 vla_sp_restore_root();
6078 if (s->r & LABEL_FORWARD)
6079 s->jnext = gjmp(s->jnext);
6080 else
6081 gjmp_addr(s->jnext);
6082 next();
6083 } else {
6084 expect("label identifier");
6086 skip(';');
6087 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
6088 asm_instr();
6089 } else {
6090 b = is_label();
6091 if (b) {
6092 /* label case */
6093 next();
6094 s = label_find(b);
6095 if (s) {
6096 if (s->r == LABEL_DEFINED)
6097 tcc_error("duplicate label '%s'", get_tok_str(s->v, NULL));
6098 gsym(s->jnext);
6099 s->r = LABEL_DEFINED;
6100 } else {
6101 s = label_push(&global_label_stack, b, LABEL_DEFINED);
6103 s->jnext = ind;
6104 vla_sp_restore();
6105 /* we accept this, but it is a mistake */
6106 block_after_label:
6107 nocode_wanted &= ~0x20000000;
6108 if (tok == '}') {
6109 tcc_warning("deprecated use of label at end of compound statement");
6110 } else {
6111 if (is_expr)
6112 vpop();
6113 block(bsym, csym, is_expr);
6115 } else {
6116 /* expression case */
6117 if (tok != ';') {
6118 if (is_expr) {
6119 vpop();
6120 gexpr();
6121 } else {
6122 gexpr();
6123 vpop();
6126 skip(';');
6131 /* This skips over a stream of tokens containing balanced {} and ()
6132 pairs, stopping at outer ',' ';' and '}' (or matching '}' if we started
6133 with a '{'). If STR then allocates and stores the skipped tokens
6134 in *STR. This doesn't check if () and {} are nested correctly,
6135 i.e. "({)}" is accepted. */
6136 static void skip_or_save_block(TokenString **str)
6138 int braces = tok == '{';
6139 int level = 0;
6140 if (str)
6141 *str = tok_str_alloc();
6143 while ((level > 0 || (tok != '}' && tok != ',' && tok != ';' && tok != ')'))) {
6144 int t;
6145 if (tok == TOK_EOF) {
6146 if (str || level > 0)
6147 tcc_error("unexpected end of file");
6148 else
6149 break;
6151 if (str)
6152 tok_str_add_tok(*str);
6153 t = tok;
6154 next();
6155 if (t == '{' || t == '(') {
6156 level++;
6157 } else if (t == '}' || t == ')') {
6158 level--;
6159 if (level == 0 && braces && t == '}')
6160 break;
6163 if (str) {
6164 tok_str_add(*str, -1);
6165 tok_str_add(*str, 0);
6169 #define EXPR_CONST 1
6170 #define EXPR_ANY 2
6172 static void parse_init_elem(int expr_type)
6174 int saved_global_expr;
6175 switch(expr_type) {
6176 case EXPR_CONST:
6177 /* compound literals must be allocated globally in this case */
6178 saved_global_expr = global_expr;
6179 global_expr = 1;
6180 expr_const1();
6181 global_expr = saved_global_expr;
6182 /* NOTE: symbols are accepted, as well as lvalue for anon symbols
6183 (compound literals). */
6184 if (((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST
6185 && ((vtop->r & (VT_SYM|VT_LVAL)) != (VT_SYM|VT_LVAL)
6186 || vtop->sym->v < SYM_FIRST_ANOM))
6187 #ifdef TCC_TARGET_PE
6188 || ((vtop->r & VT_SYM) && vtop->sym->a.dllimport)
6189 #endif
6191 tcc_error("initializer element is not constant");
6192 break;
6193 case EXPR_ANY:
6194 expr_eq();
6195 break;
6199 /* put zeros for variable based init */
6200 static void init_putz(Section *sec, unsigned long c, int size)
6202 if (sec) {
6203 /* nothing to do because globals are already set to zero */
6204 } else {
6205 vpush_global_sym(&func_old_type, TOK_memset);
6206 vseti(VT_LOCAL, c);
6207 #ifdef TCC_TARGET_ARM
6208 vpushs(size);
6209 vpushi(0);
6210 #else
6211 vpushi(0);
6212 vpushs(size);
6213 #endif
6214 gfunc_call(3);
6218 /* t is the array or struct type. c is the array or struct
6219 address. cur_field is the pointer to the current
6220 field, for arrays the 'c' member contains the current start
6221 index. 'size_only' is true if only size info is needed (only used
6222 in arrays). al contains the already initialized length of the
6223 current container (starting at c). This returns the new length of that. */
6224 static int decl_designator(CType *type, Section *sec, unsigned long c,
6225 Sym **cur_field, int size_only, int al)
6227 Sym *s, *f;
6228 int index, index_last, align, l, nb_elems, elem_size;
6229 unsigned long corig = c;
6231 elem_size = 0;
6232 nb_elems = 1;
6233 if (gnu_ext && (l = is_label()) != 0)
6234 goto struct_field;
6235 /* NOTE: we only support ranges for last designator */
6236 while (nb_elems == 1 && (tok == '[' || tok == '.')) {
6237 if (tok == '[') {
6238 if (!(type->t & VT_ARRAY))
6239 expect("array type");
6240 next();
6241 index = index_last = expr_const();
6242 if (tok == TOK_DOTS && gnu_ext) {
6243 next();
6244 index_last = expr_const();
6246 skip(']');
6247 s = type->ref;
6248 if (index < 0 || (s->c >= 0 && index_last >= s->c) ||
6249 index_last < index)
6250 tcc_error("invalid index");
6251 if (cur_field)
6252 (*cur_field)->c = index_last;
6253 type = pointed_type(type);
6254 elem_size = type_size(type, &align);
6255 c += index * elem_size;
6256 nb_elems = index_last - index + 1;
6257 } else {
6258 next();
6259 l = tok;
6260 struct_field:
6261 next();
6262 if ((type->t & VT_BTYPE) != VT_STRUCT)
6263 expect("struct/union type");
6264 f = find_field(type, l);
6265 if (!f)
6266 expect("field");
6267 if (cur_field)
6268 *cur_field = f;
6269 type = &f->type;
6270 c += f->c;
6272 cur_field = NULL;
6274 if (!cur_field) {
6275 if (tok == '=') {
6276 next();
6277 } else if (!gnu_ext) {
6278 expect("=");
6280 } else {
6281 if (type->t & VT_ARRAY) {
6282 index = (*cur_field)->c;
6283 if (type->ref->c >= 0 && index >= type->ref->c)
6284 tcc_error("index too large");
6285 type = pointed_type(type);
6286 c += index * type_size(type, &align);
6287 } else {
6288 f = *cur_field;
6289 while (f && (f->v & SYM_FIRST_ANOM) && (f->type.t & VT_BITFIELD))
6290 *cur_field = f = f->next;
6291 if (!f)
6292 tcc_error("too many field init");
6293 type = &f->type;
6294 c += f->c;
6297 /* must put zero in holes (note that doing it that way
6298 ensures that it even works with designators) */
6299 if (!size_only && c - corig > al)
6300 init_putz(sec, corig + al, c - corig - al);
6301 decl_initializer(type, sec, c, 0, size_only);
6303 /* XXX: make it more general */
6304 if (!size_only && nb_elems > 1) {
6305 unsigned long c_end;
6306 uint8_t *src, *dst;
6307 int i;
6309 if (!sec) {
6310 vset(type, VT_LOCAL|VT_LVAL, c);
6311 for (i = 1; i < nb_elems; i++) {
6312 vset(type, VT_LOCAL|VT_LVAL, c + elem_size * i);
6313 vswap();
6314 vstore();
6316 vpop();
6317 } else {
6318 c_end = c + nb_elems * elem_size;
6319 if (c_end > sec->data_allocated)
6320 section_realloc(sec, c_end);
6321 src = sec->data + c;
6322 dst = src;
6323 for(i = 1; i < nb_elems; i++) {
6324 dst += elem_size;
6325 memcpy(dst, src, elem_size);
6329 c += nb_elems * type_size(type, &align);
6330 if (c - corig > al)
6331 al = c - corig;
6332 return al;
6335 /* store a value or an expression directly in global data or in local array */
6336 static void init_putv(CType *type, Section *sec, unsigned long c)
6338 int bt;
6339 void *ptr;
6340 CType dtype;
6342 dtype = *type;
6343 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
6345 if (sec) {
6346 int size, align;
6347 /* XXX: not portable */
6348 /* XXX: generate error if incorrect relocation */
6349 gen_assign_cast(&dtype);
6350 bt = type->t & VT_BTYPE;
6351 size = type_size(type, &align);
6352 section_reserve(sec, c + size);
6353 ptr = sec->data + c;
6354 /* XXX: make code faster ? */
6355 if ((vtop->r & (VT_SYM|VT_CONST)) == (VT_SYM|VT_CONST) &&
6356 vtop->sym->v >= SYM_FIRST_ANOM &&
6357 /* XXX This rejects compound literals like
6358 '(void *){ptr}'. The problem is that '&sym' is
6359 represented the same way, which would be ruled out
6360 by the SYM_FIRST_ANOM check above, but also '"string"'
6361 in 'char *p = "string"' is represented the same
6362 with the type being VT_PTR and the symbol being an
6363 anonymous one. That is, there's no difference in vtop
6364 between '(void *){x}' and '&(void *){x}'. Ignore
6365 pointer typed entities here. Hopefully no real code
6366 will every use compound literals with scalar type. */
6367 (vtop->type.t & VT_BTYPE) != VT_PTR) {
6368 /* These come from compound literals, memcpy stuff over. */
6369 Section *ssec;
6370 ElfW(Sym) *esym;
6371 ElfW_Rel *rel;
6372 esym = &((ElfW(Sym) *)symtab_section->data)[vtop->sym->c];
6373 ssec = tcc_state->sections[esym->st_shndx];
6374 memmove (ptr, ssec->data + esym->st_value, size);
6375 if (ssec->reloc) {
6376 /* We need to copy over all memory contents, and that
6377 includes relocations. Use the fact that relocs are
6378 created it order, so look from the end of relocs
6379 until we hit one before the copied region. */
6380 int num_relocs = ssec->reloc->data_offset / sizeof(*rel);
6381 rel = (ElfW_Rel*)(ssec->reloc->data + ssec->reloc->data_offset);
6382 while (num_relocs--) {
6383 rel--;
6384 if (rel->r_offset >= esym->st_value + size)
6385 continue;
6386 if (rel->r_offset < esym->st_value)
6387 break;
6388 /* Note: if the same fields are initialized multiple
6389 times (possible with designators) then we possibly
6390 add multiple relocations for the same offset here.
6391 That would lead to wrong code, the last reloc needs
6392 to win. We clean this up later after the whole
6393 initializer is parsed. */
6394 put_elf_reloca(symtab_section, sec,
6395 c + rel->r_offset - esym->st_value,
6396 ELFW(R_TYPE)(rel->r_info),
6397 ELFW(R_SYM)(rel->r_info),
6398 #if PTR_SIZE == 8
6399 rel->r_addend
6400 #else
6402 #endif
6406 } else {
6407 if ((vtop->r & VT_SYM) &&
6408 (bt == VT_BYTE ||
6409 bt == VT_SHORT ||
6410 bt == VT_DOUBLE ||
6411 bt == VT_LDOUBLE ||
6412 #if PTR_SIZE == 8
6413 bt == VT_INT ||
6414 #else
6415 bt == VT_LLONG ||
6416 #endif
6417 (type->t & VT_BITFIELD)
6419 tcc_error("initializer element is not computable at load time");
6421 if (type->t & VT_BITFIELD) {
6422 int bit_pos, bit_size, bits, n;
6423 unsigned char *p, v, m;
6424 bit_pos = BIT_POS(vtop->type.t);
6425 bit_size = BIT_SIZE(vtop->type.t);
6426 p = (unsigned char*)ptr + (bit_pos >> 3);
6427 bit_pos &= 7, bits = 0;
6428 while (bit_size) {
6429 n = 8 - bit_pos;
6430 if (n > bit_size)
6431 n = bit_size;
6432 v = vtop->c.i >> bits << bit_pos;
6433 m = ((1 << n) - 1) << bit_pos;
6434 *p = (*p & ~m) | (v & m);
6435 bits += n, bit_size -= n, bit_pos = 0, ++p;
6437 } else
6438 switch(bt) {
6439 /* XXX: when cross-compiling we assume that each type has the
6440 same representation on host and target, which is likely to
6441 be wrong in the case of long double */
6442 case VT_BOOL:
6443 vtop->c.i = vtop->c.i != 0;
6444 case VT_BYTE:
6445 *(char *)ptr |= vtop->c.i;
6446 break;
6447 case VT_SHORT:
6448 *(short *)ptr |= vtop->c.i;
6449 break;
6450 case VT_FLOAT:
6451 *(float*)ptr = vtop->c.f;
6452 break;
6453 case VT_DOUBLE:
6454 *(double *)ptr = vtop->c.d;
6455 break;
6456 case VT_LDOUBLE:
6457 if (sizeof(long double) == LDOUBLE_SIZE)
6458 *(long double *)ptr = vtop->c.ld;
6459 else if (sizeof(double) == LDOUBLE_SIZE)
6460 *(double *)ptr = (double)vtop->c.ld;
6461 #if (defined __i386__ || defined __x86_64__) && (defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64)
6462 else if (sizeof (long double) >= 10)
6463 memcpy(memset(ptr, 0, LDOUBLE_SIZE), &vtop->c.ld, 10);
6464 #ifdef __TINYC__
6465 else if (sizeof (long double) == sizeof (double))
6466 __asm__("fldl %1\nfstpt %0\n" : "=m"
6467 (memset(ptr, 0, LDOUBLE_SIZE), ptr) : "m" (vtop->c.ld));
6468 #endif
6469 #endif
6470 else
6471 tcc_error("can't cross compile long double constants");
6472 break;
6473 #if PTR_SIZE != 8
6474 case VT_LLONG:
6475 *(long long *)ptr |= vtop->c.i;
6476 break;
6477 #else
6478 case VT_LLONG:
6479 #endif
6480 case VT_PTR:
6482 addr_t val = vtop->c.i;
6483 #if PTR_SIZE == 8
6484 if (vtop->r & VT_SYM)
6485 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
6486 else
6487 *(addr_t *)ptr |= val;
6488 #else
6489 if (vtop->r & VT_SYM)
6490 greloc(sec, vtop->sym, c, R_DATA_PTR);
6491 *(addr_t *)ptr |= val;
6492 #endif
6493 break;
6495 default:
6497 int val = vtop->c.i;
6498 #if PTR_SIZE == 8
6499 if (vtop->r & VT_SYM)
6500 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
6501 else
6502 *(int *)ptr |= val;
6503 #else
6504 if (vtop->r & VT_SYM)
6505 greloc(sec, vtop->sym, c, R_DATA_PTR);
6506 *(int *)ptr |= val;
6507 #endif
6508 break;
6512 vtop--;
6513 } else {
6514 vset(&dtype, VT_LOCAL|VT_LVAL, c);
6515 vswap();
6516 vstore();
6517 vpop();
6521 /* 't' contains the type and storage info. 'c' is the offset of the
6522 object in section 'sec'. If 'sec' is NULL, it means stack based
6523 allocation. 'first' is true if array '{' must be read (multi
6524 dimension implicit array init handling). 'size_only' is true if
6525 size only evaluation is wanted (only for arrays). */
6526 static void decl_initializer(CType *type, Section *sec, unsigned long c,
6527 int first, int size_only)
6529 int len, n, no_oblock, nb, i;
6530 int size1, align1;
6531 int have_elem;
6532 Sym *s, *f;
6533 Sym indexsym;
6534 CType *t1;
6536 /* If we currently are at an '}' or ',' we have read an initializer
6537 element in one of our callers, and not yet consumed it. */
6538 have_elem = tok == '}' || tok == ',';
6539 if (!have_elem && tok != '{' &&
6540 /* In case of strings we have special handling for arrays, so
6541 don't consume them as initializer value (which would commit them
6542 to some anonymous symbol). */
6543 tok != TOK_LSTR && tok != TOK_STR &&
6544 !size_only) {
6545 parse_init_elem(!sec ? EXPR_ANY : EXPR_CONST);
6546 have_elem = 1;
6549 if (have_elem &&
6550 !(type->t & VT_ARRAY) &&
6551 /* Use i_c_parameter_t, to strip toplevel qualifiers.
6552 The source type might have VT_CONSTANT set, which is
6553 of course assignable to non-const elements. */
6554 is_compatible_unqualified_types(type, &vtop->type)) {
6555 init_putv(type, sec, c);
6556 } else if (type->t & VT_ARRAY) {
6557 s = type->ref;
6558 n = s->c;
6559 t1 = pointed_type(type);
6560 size1 = type_size(t1, &align1);
6562 no_oblock = 1;
6563 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
6564 tok == '{') {
6565 if (tok != '{')
6566 tcc_error("character array initializer must be a literal,"
6567 " optionally enclosed in braces");
6568 skip('{');
6569 no_oblock = 0;
6572 /* only parse strings here if correct type (otherwise: handle
6573 them as ((w)char *) expressions */
6574 if ((tok == TOK_LSTR &&
6575 #ifdef TCC_TARGET_PE
6576 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
6577 #else
6578 (t1->t & VT_BTYPE) == VT_INT
6579 #endif
6580 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
6581 len = 0;
6582 while (tok == TOK_STR || tok == TOK_LSTR) {
6583 int cstr_len, ch;
6585 /* compute maximum number of chars wanted */
6586 if (tok == TOK_STR)
6587 cstr_len = tokc.str.size;
6588 else
6589 cstr_len = tokc.str.size / sizeof(nwchar_t);
6590 cstr_len--;
6591 nb = cstr_len;
6592 if (n >= 0 && nb > (n - len))
6593 nb = n - len;
6594 if (!size_only) {
6595 if (cstr_len > nb)
6596 tcc_warning("initializer-string for array is too long");
6597 /* in order to go faster for common case (char
6598 string in global variable, we handle it
6599 specifically */
6600 if (sec && tok == TOK_STR && size1 == 1) {
6601 memcpy(sec->data + c + len, tokc.str.data, nb);
6602 } else {
6603 for(i=0;i<nb;i++) {
6604 if (tok == TOK_STR)
6605 ch = ((unsigned char *)tokc.str.data)[i];
6606 else
6607 ch = ((nwchar_t *)tokc.str.data)[i];
6608 vpushi(ch);
6609 init_putv(t1, sec, c + (len + i) * size1);
6613 len += nb;
6614 next();
6616 /* only add trailing zero if enough storage (no
6617 warning in this case since it is standard) */
6618 if (n < 0 || len < n) {
6619 if (!size_only) {
6620 vpushi(0);
6621 init_putv(t1, sec, c + (len * size1));
6623 len++;
6625 len *= size1;
6626 } else {
6627 indexsym.c = 0;
6628 f = &indexsym;
6630 do_init_list:
6631 len = 0;
6632 while (tok != '}' || have_elem) {
6633 len = decl_designator(type, sec, c, &f, size_only, len);
6634 have_elem = 0;
6635 if (type->t & VT_ARRAY) {
6636 ++indexsym.c;
6637 /* special test for multi dimensional arrays (may not
6638 be strictly correct if designators are used at the
6639 same time) */
6640 if (no_oblock && len >= n*size1)
6641 break;
6642 } else {
6643 if (s->type.t == VT_UNION)
6644 f = NULL;
6645 else
6646 f = f->next;
6647 if (no_oblock && f == NULL)
6648 break;
6651 if (tok == '}')
6652 break;
6653 skip(',');
6656 /* put zeros at the end */
6657 if (!size_only && len < n*size1)
6658 init_putz(sec, c + len, n*size1 - len);
6659 if (!no_oblock)
6660 skip('}');
6661 /* patch type size if needed, which happens only for array types */
6662 if (n < 0)
6663 s->c = size1 == 1 ? len : ((len + size1 - 1)/size1);
6664 } else if ((type->t & VT_BTYPE) == VT_STRUCT) {
6665 size1 = 1;
6666 no_oblock = 1;
6667 if (first || tok == '{') {
6668 skip('{');
6669 no_oblock = 0;
6671 s = type->ref;
6672 f = s->next;
6673 n = s->c;
6674 goto do_init_list;
6675 } else if (tok == '{') {
6676 next();
6677 decl_initializer(type, sec, c, first, size_only);
6678 skip('}');
6679 } else if (size_only) {
6680 /* If we supported only ISO C we wouldn't have to accept calling
6681 this on anything than an array size_only==1 (and even then
6682 only on the outermost level, so no recursion would be needed),
6683 because initializing a flex array member isn't supported.
6684 But GNU C supports it, so we need to recurse even into
6685 subfields of structs and arrays when size_only is set. */
6686 /* just skip expression */
6687 skip_or_save_block(NULL);
6688 } else {
6689 if (!have_elem) {
6690 /* This should happen only when we haven't parsed
6691 the init element above for fear of committing a
6692 string constant to memory too early. */
6693 if (tok != TOK_STR && tok != TOK_LSTR)
6694 expect("string constant");
6695 parse_init_elem(!sec ? EXPR_ANY : EXPR_CONST);
6697 init_putv(type, sec, c);
6701 /* parse an initializer for type 't' if 'has_init' is non zero, and
6702 allocate space in local or global data space ('r' is either
6703 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
6704 variable 'v' of scope 'scope' is declared before initializers
6705 are parsed. If 'v' is zero, then a reference to the new object
6706 is put in the value stack. If 'has_init' is 2, a special parsing
6707 is done to handle string constants. */
6708 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
6709 int has_init, int v, int scope)
6711 int size, align, addr;
6712 ParseState saved_parse_state = {0};
6713 TokenString *init_str = NULL;
6714 Section *sec;
6715 Sym *flexible_array;
6716 Sym *sym = NULL;
6718 flexible_array = NULL;
6719 if ((type->t & VT_BTYPE) == VT_STRUCT) {
6720 Sym *field = type->ref->next;
6721 if (field) {
6722 while (field->next)
6723 field = field->next;
6724 if (field->type.t & VT_ARRAY && field->type.ref->c < 0)
6725 flexible_array = field;
6729 size = type_size(type, &align);
6730 /* If unknown size, we must evaluate it before
6731 evaluating initializers because
6732 initializers can generate global data too
6733 (e.g. string pointers or ISOC99 compound
6734 literals). It also simplifies local
6735 initializers handling */
6736 if (size < 0 || (flexible_array && has_init)) {
6737 if (!has_init)
6738 tcc_error("unknown type size");
6739 /* get all init string */
6740 if (has_init == 2) {
6741 init_str = tok_str_alloc();
6742 /* only get strings */
6743 while (tok == TOK_STR || tok == TOK_LSTR) {
6744 tok_str_add_tok(init_str);
6745 next();
6747 tok_str_add(init_str, -1);
6748 tok_str_add(init_str, 0);
6749 } else {
6750 skip_or_save_block(&init_str);
6753 /* compute size */
6754 save_parse_state(&saved_parse_state);
6756 begin_macro(init_str, 1);
6757 next();
6758 decl_initializer(type, NULL, 0, 1, 1);
6759 /* prepare second initializer parsing */
6760 macro_ptr = init_str->str;
6761 next();
6763 /* if still unknown size, error */
6764 size = type_size(type, &align);
6765 if (size < 0)
6766 tcc_error("unknown type size");
6768 /* If there's a flex member and it was used in the initializer
6769 adjust size. */
6770 if (flexible_array &&
6771 flexible_array->type.ref->c > 0)
6772 size += flexible_array->type.ref->c
6773 * pointed_size(&flexible_array->type);
6774 /* take into account specified alignment if bigger */
6775 if (ad->a.aligned) {
6776 int speca = 1 << (ad->a.aligned - 1);
6777 if (speca > align)
6778 align = speca;
6779 } else if (ad->a.packed) {
6780 align = 1;
6782 if ((r & VT_VALMASK) == VT_LOCAL) {
6783 sec = NULL;
6784 #ifdef CONFIG_TCC_BCHECK
6785 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
6786 loc--;
6788 #endif
6789 loc = (loc - size) & -align;
6790 addr = loc;
6791 #ifdef CONFIG_TCC_BCHECK
6792 /* handles bounds */
6793 /* XXX: currently, since we do only one pass, we cannot track
6794 '&' operators, so we add only arrays */
6795 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
6796 addr_t *bounds_ptr;
6797 /* add padding between regions */
6798 loc--;
6799 /* then add local bound info */
6800 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(addr_t));
6801 bounds_ptr[0] = addr;
6802 bounds_ptr[1] = size;
6804 #endif
6805 if (v) {
6806 /* local variable */
6807 #ifdef CONFIG_TCC_ASM
6808 if (ad->asm_label) {
6809 int reg = asm_parse_regvar(ad->asm_label);
6810 if (reg >= 0)
6811 r = (r & ~VT_VALMASK) | reg;
6813 #endif
6814 sym = sym_push(v, type, r, addr);
6815 sym->a = ad->a;
6816 } else {
6817 /* push local reference */
6818 vset(type, r, addr);
6820 } else {
6821 if (v && scope == VT_CONST) {
6822 /* see if the symbol was already defined */
6823 sym = sym_find(v);
6824 if (sym) {
6825 patch_storage(sym, ad, type);
6826 if (sym->type.t & VT_EXTERN) {
6827 /* if the variable is extern, it was not allocated */
6828 sym->type.t &= ~VT_EXTERN;
6829 /* set array size if it was omitted in extern
6830 declaration */
6831 if ((sym->type.t & VT_ARRAY) &&
6832 sym->type.ref->c < 0 &&
6833 type->ref->c >= 0)
6834 sym->type.ref->c = type->ref->c;
6835 } else if (!has_init) {
6836 /* we accept several definitions of the same
6837 global variable. this is tricky, because we
6838 must play with the SHN_COMMON type of the symbol */
6839 /* no init data, we won't add more to the symbol */
6840 goto no_alloc;
6841 } else if (sym->c) {
6842 ElfW(Sym) *esym;
6843 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
6844 if (esym->st_shndx == data_section->sh_num)
6845 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
6850 /* allocate symbol in corresponding section */
6851 sec = ad->section;
6852 if (!sec) {
6853 if (has_init)
6854 sec = data_section;
6855 else if (tcc_state->nocommon)
6856 sec = bss_section;
6859 if (sec) {
6860 addr = section_add(sec, size, align);
6861 #ifdef CONFIG_TCC_BCHECK
6862 /* add padding if bound check */
6863 if (tcc_state->do_bounds_check)
6864 section_add(sec, 1, 1);
6865 #endif
6866 } else {
6867 addr = align; /* SHN_COMMON is special, symbol value is align */
6868 sec = common_section;
6871 if (v) {
6872 if (!sym) {
6873 sym = sym_push(v, type, r | VT_SYM, 0);
6874 patch_storage(sym, ad, NULL);
6876 /* Local statics have a scope until now (for
6877 warnings), remove it here. */
6878 sym->sym_scope = 0;
6879 /* update symbol definition */
6880 put_extern_sym(sym, sec, addr, size);
6881 } else {
6882 /* push global reference */
6883 sym = get_sym_ref(type, sec, addr, size);
6884 vpushsym(type, sym);
6885 vtop->r |= r;
6888 #ifdef CONFIG_TCC_BCHECK
6889 /* handles bounds now because the symbol must be defined
6890 before for the relocation */
6891 if (tcc_state->do_bounds_check) {
6892 addr_t *bounds_ptr;
6894 greloca(bounds_section, sym, bounds_section->data_offset, R_DATA_PTR, 0);
6895 /* then add global bound info */
6896 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(addr_t));
6897 bounds_ptr[0] = 0; /* relocated */
6898 bounds_ptr[1] = size;
6900 #endif
6903 if (type->t & VT_VLA) {
6904 int a;
6906 /* save current stack pointer */
6907 if (vlas_in_scope == 0) {
6908 if (vla_sp_root_loc == -1)
6909 vla_sp_root_loc = (loc -= PTR_SIZE);
6910 gen_vla_sp_save(vla_sp_root_loc);
6913 vla_runtime_type_size(type, &a);
6914 gen_vla_alloc(type, a);
6915 gen_vla_sp_save(addr);
6916 vla_sp_loc = addr;
6917 vlas_in_scope++;
6919 } else if (has_init) {
6920 size_t oldreloc_offset = 0;
6921 if (sec && sec->reloc)
6922 oldreloc_offset = sec->reloc->data_offset;
6923 decl_initializer(type, sec, addr, 1, 0);
6924 if (sec && sec->reloc)
6925 squeeze_multi_relocs(sec, oldreloc_offset);
6926 /* patch flexible array member size back to -1, */
6927 /* for possible subsequent similar declarations */
6928 if (flexible_array)
6929 flexible_array->type.ref->c = -1;
6932 no_alloc:
6933 /* restore parse state if needed */
6934 if (init_str) {
6935 end_macro();
6936 restore_parse_state(&saved_parse_state);
6940 /* parse a function defined by symbol 'sym' and generate its code in
6941 'cur_text_section' */
6942 static void gen_function(Sym *sym)
6944 nocode_wanted = 0;
6945 ind = cur_text_section->data_offset;
6946 /* NOTE: we patch the symbol size later */
6947 put_extern_sym(sym, cur_text_section, ind, 0);
6948 funcname = get_tok_str(sym->v, NULL);
6949 func_ind = ind;
6950 /* Initialize VLA state */
6951 vla_sp_loc = -1;
6952 vla_sp_root_loc = -1;
6953 /* put debug symbol */
6954 tcc_debug_funcstart(tcc_state, sym);
6955 /* push a dummy symbol to enable local sym storage */
6956 sym_push2(&local_stack, SYM_FIELD, 0, 0);
6957 local_scope = 1; /* for function parameters */
6958 gfunc_prolog(&sym->type);
6959 local_scope = 0;
6960 rsym = 0;
6961 block(NULL, NULL, 0);
6962 nocode_wanted = 0;
6963 gsym(rsym);
6964 gfunc_epilog();
6965 cur_text_section->data_offset = ind;
6966 label_pop(&global_label_stack, NULL, 0);
6967 /* reset local stack */
6968 local_scope = 0;
6969 sym_pop(&local_stack, NULL, 0);
6970 /* end of function */
6971 /* patch symbol size */
6972 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
6973 ind - func_ind;
6974 tcc_debug_funcend(tcc_state, ind - func_ind);
6975 /* It's better to crash than to generate wrong code */
6976 cur_text_section = NULL;
6977 funcname = ""; /* for safety */
6978 func_vt.t = VT_VOID; /* for safety */
6979 func_var = 0; /* for safety */
6980 ind = 0; /* for safety */
6981 nocode_wanted = 1;
6982 check_vstack();
6985 static void gen_inline_functions(TCCState *s)
6987 Sym *sym;
6988 int inline_generated, i, ln;
6989 struct InlineFunc *fn;
6991 ln = file->line_num;
6992 /* iterate while inline function are referenced */
6993 do {
6994 inline_generated = 0;
6995 for (i = 0; i < s->nb_inline_fns; ++i) {
6996 fn = s->inline_fns[i];
6997 sym = fn->sym;
6998 if (sym && sym->c) {
6999 /* the function was used: generate its code and
7000 convert it to a normal function */
7001 fn->sym = NULL;
7002 if (file)
7003 pstrcpy(file->filename, sizeof file->filename, fn->filename);
7004 sym->type.t &= ~VT_INLINE;
7006 begin_macro(fn->func_str, 1);
7007 next();
7008 cur_text_section = text_section;
7009 gen_function(sym);
7010 end_macro();
7012 inline_generated = 1;
7015 } while (inline_generated);
7016 file->line_num = ln;
7019 ST_FUNC void free_inline_functions(TCCState *s)
7021 int i;
7022 /* free tokens of unused inline functions */
7023 for (i = 0; i < s->nb_inline_fns; ++i) {
7024 struct InlineFunc *fn = s->inline_fns[i];
7025 if (fn->sym)
7026 tok_str_free(fn->func_str);
7028 dynarray_reset(&s->inline_fns, &s->nb_inline_fns);
7031 /* 'l' is VT_LOCAL or VT_CONST to define default storage type, or VT_CMP
7032 if parsing old style parameter decl list (and FUNC_SYM is set then) */
7033 static int decl0(int l, int is_for_loop_init, Sym *func_sym)
7035 int v, has_init, r;
7036 CType type, btype;
7037 Sym *sym;
7038 AttributeDef ad;
7040 while (1) {
7041 if (!parse_btype(&btype, &ad)) {
7042 if (is_for_loop_init)
7043 return 0;
7044 /* skip redundant ';' if not in old parameter decl scope */
7045 if (tok == ';' && l != VT_CMP) {
7046 next();
7047 continue;
7049 if (l == VT_CONST &&
7050 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
7051 /* global asm block */
7052 asm_global_instr();
7053 continue;
7055 /* special test for old K&R protos without explicit int
7056 type. Only accepted when defining global data */
7057 if (l != VT_CONST || tok < TOK_UIDENT)
7058 break;
7059 btype.t = VT_INT;
7061 if (tok == ';') {
7062 if ((btype.t & VT_BTYPE) == VT_STRUCT) {
7063 int v = btype.ref->v;
7064 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) >= SYM_FIRST_ANOM)
7065 tcc_warning("unnamed struct/union that defines no instances");
7066 next();
7067 continue;
7069 if (IS_ENUM(btype.t)) {
7070 next();
7071 continue;
7074 while (1) { /* iterate thru each declaration */
7075 type = btype;
7076 /* If the base type itself was an array type of unspecified
7077 size (like in 'typedef int arr[]; arr x = {1};') then
7078 we will overwrite the unknown size by the real one for
7079 this decl. We need to unshare the ref symbol holding
7080 that size. */
7081 if ((type.t & VT_ARRAY) && type.ref->c < 0) {
7082 type.ref = sym_push(SYM_FIELD, &type.ref->type, 0, type.ref->c);
7084 type_decl(&type, &ad, &v, TYPE_DIRECT);
7085 #if 0
7087 char buf[500];
7088 type_to_str(buf, sizeof(buf), &type, get_tok_str(v, NULL));
7089 printf("type = '%s'\n", buf);
7091 #endif
7092 if ((type.t & VT_BTYPE) == VT_FUNC) {
7093 if ((type.t & VT_STATIC) && (l == VT_LOCAL)) {
7094 tcc_error("function without file scope cannot be static");
7096 /* if old style function prototype, we accept a
7097 declaration list */
7098 sym = type.ref;
7099 if (sym->f.func_type == FUNC_OLD && l == VT_CONST)
7100 decl0(VT_CMP, 0, sym);
7103 if (gnu_ext && (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
7104 ad.asm_label = asm_label_instr();
7105 /* parse one last attribute list, after asm label */
7106 parse_attribute(&ad);
7107 if (tok == '{')
7108 expect(";");
7111 #ifdef TCC_TARGET_PE
7112 if (ad.a.dllimport || ad.a.dllexport) {
7113 if (type.t & (VT_STATIC|VT_TYPEDEF))
7114 tcc_error("cannot have dll linkage with static or typedef");
7115 if (ad.a.dllimport) {
7116 if ((type.t & VT_BTYPE) == VT_FUNC)
7117 ad.a.dllimport = 0;
7118 else
7119 type.t |= VT_EXTERN;
7122 #endif
7123 if (tok == '{') {
7124 if (l != VT_CONST)
7125 tcc_error("cannot use local functions");
7126 if ((type.t & VT_BTYPE) != VT_FUNC)
7127 expect("function definition");
7129 /* reject abstract declarators in function definition
7130 make old style params without decl have int type */
7131 sym = type.ref;
7132 while ((sym = sym->next) != NULL) {
7133 if (!(sym->v & ~SYM_FIELD))
7134 expect("identifier");
7135 if (sym->type.t == VT_VOID)
7136 sym->type = int_type;
7139 /* XXX: cannot do better now: convert extern line to static inline */
7140 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
7141 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
7143 sym = sym_find(v);
7144 if (sym) {
7145 Sym *ref;
7146 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
7147 goto func_error1;
7149 ref = sym->type.ref;
7151 /* use func_call from prototype if not defined */
7152 if (ref->f.func_call != FUNC_CDECL
7153 && type.ref->f.func_call == FUNC_CDECL)
7154 type.ref->f.func_call = ref->f.func_call;
7156 /* use static from prototype */
7157 if (sym->type.t & VT_STATIC)
7158 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
7160 /* If the definition has no visibility use the
7161 one from prototype. */
7162 if (!type.ref->a.visibility)
7163 type.ref->a.visibility = ref->a.visibility;
7164 /* apply other storage attributes from prototype */
7165 type.ref->a.dllexport |= ref->a.dllexport;
7166 type.ref->a.weak |= ref->a.weak;
7168 if (!is_compatible_types(&sym->type, &type)) {
7169 func_error1:
7170 tcc_error("incompatible types for redefinition of '%s'",
7171 get_tok_str(v, NULL));
7173 if (ref->f.func_body)
7174 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
7175 /* if symbol is already defined, then put complete type */
7176 sym->type = type;
7178 } else {
7179 /* put function symbol */
7180 sym = global_identifier_push(v, type.t, 0);
7181 sym->type.ref = type.ref;
7184 sym->type.ref->f.func_body = 1;
7185 sym->r = VT_SYM | VT_CONST;
7186 patch_storage(sym, &ad, NULL);
7188 /* static inline functions are just recorded as a kind
7189 of macro. Their code will be emitted at the end of
7190 the compilation unit only if they are used */
7191 if ((type.t & (VT_INLINE | VT_STATIC)) ==
7192 (VT_INLINE | VT_STATIC)) {
7193 struct InlineFunc *fn;
7194 const char *filename;
7196 filename = file ? file->filename : "";
7197 fn = tcc_malloc(sizeof *fn + strlen(filename));
7198 strcpy(fn->filename, filename);
7199 fn->sym = sym;
7200 skip_or_save_block(&fn->func_str);
7201 dynarray_add(&tcc_state->inline_fns,
7202 &tcc_state->nb_inline_fns, fn);
7203 } else {
7204 /* compute text section */
7205 cur_text_section = ad.section;
7206 if (!cur_text_section)
7207 cur_text_section = text_section;
7208 gen_function(sym);
7210 break;
7211 } else {
7212 if (l == VT_CMP) {
7213 /* find parameter in function parameter list */
7214 for (sym = func_sym->next; sym; sym = sym->next)
7215 if ((sym->v & ~SYM_FIELD) == v)
7216 goto found;
7217 tcc_error("declaration for parameter '%s' but no such parameter",
7218 get_tok_str(v, NULL));
7219 found:
7220 if (type.t & VT_STORAGE) /* 'register' is okay */
7221 tcc_error("storage class specified for '%s'",
7222 get_tok_str(v, NULL));
7223 if (sym->type.t != VT_VOID)
7224 tcc_error("redefinition of parameter '%s'",
7225 get_tok_str(v, NULL));
7226 convert_parameter_type(&type);
7227 sym->type = type;
7228 } else if (type.t & VT_TYPEDEF) {
7229 /* save typedefed type */
7230 /* XXX: test storage specifiers ? */
7231 sym = sym_find(v);
7232 if (sym && sym->sym_scope == local_scope) {
7233 if (!is_compatible_types(&sym->type, &type)
7234 || !(sym->type.t & VT_TYPEDEF))
7235 tcc_error("incompatible redefinition of '%s'",
7236 get_tok_str(v, NULL));
7237 sym->type = type;
7238 } else {
7239 sym = sym_push(v, &type, 0, 0);
7241 sym->a = ad.a;
7242 sym->f = ad.f;
7243 } else {
7244 r = 0;
7245 if ((type.t & VT_BTYPE) == VT_FUNC) {
7246 /* external function definition */
7247 /* specific case for func_call attribute */
7248 type.ref->f = ad.f;
7249 } else if (!(type.t & VT_ARRAY)) {
7250 /* not lvalue if array */
7251 r |= lvalue_type(type.t);
7253 has_init = (tok == '=');
7254 if (has_init && (type.t & VT_VLA))
7255 tcc_error("variable length array cannot be initialized");
7256 if (((type.t & VT_EXTERN) && (!has_init || l != VT_CONST)) ||
7257 ((type.t & VT_BTYPE) == VT_FUNC) ||
7258 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
7259 !has_init && l == VT_CONST && type.ref->c < 0)) {
7260 /* external variable or function */
7261 /* NOTE: as GCC, uninitialized global static
7262 arrays of null size are considered as
7263 extern */
7264 sym = external_sym(v, &type, r, &ad);
7265 if (ad.alias_target) {
7266 Section tsec;
7267 ElfW(Sym) *esym;
7268 Sym *alias_target;
7269 alias_target = sym_find(ad.alias_target);
7270 if (!alias_target || !alias_target->c)
7271 tcc_error("unsupported forward __alias__ attribute");
7272 esym = &((ElfW(Sym) *)symtab_section->data)[alias_target->c];
7273 tsec.sh_num = esym->st_shndx;
7274 /* Local statics have a scope until now (for
7275 warnings), remove it here. */
7276 sym->sym_scope = 0;
7277 put_extern_sym2(sym, &tsec, esym->st_value, esym->st_size, 0);
7279 } else {
7280 if (type.t & VT_STATIC)
7281 r |= VT_CONST;
7282 else
7283 r |= l;
7284 if (has_init)
7285 next();
7286 decl_initializer_alloc(&type, &ad, r, has_init, v, l);
7289 if (tok != ',') {
7290 if (is_for_loop_init)
7291 return 1;
7292 skip(';');
7293 break;
7295 next();
7297 ad.a.aligned = 0;
7300 return 0;
7303 ST_FUNC void decl(int l)
7305 decl0(l, 0, NULL);
7308 /* ------------------------------------------------------------------------- */