fix the bug #31403: parser bug in structure
[tinycc.git] / tccgen.c
blob3b87d0a487d438351af8f0c96a98075e273c4f03
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 Section *text_section, *data_section, *bss_section; /* predefined sections */
34 ST_DATA Section *cur_text_section; /* current section where function code is generated */
35 #ifdef CONFIG_TCC_ASM
36 ST_DATA Section *last_text_section; /* to handle .previous asm directive */
37 #endif
38 #ifdef CONFIG_TCC_BCHECK
39 /* bound check related sections */
40 ST_DATA Section *bounds_section; /* contains global data bound description */
41 ST_DATA Section *lbounds_section; /* contains local data bound description */
42 #endif
43 /* symbol sections */
44 ST_DATA Section *symtab_section, *strtab_section;
45 /* debug sections */
46 ST_DATA Section *stab_section, *stabstr_section;
47 ST_DATA Sym *sym_free_first;
48 ST_DATA void **sym_pools;
49 ST_DATA int nb_sym_pools;
51 ST_DATA Sym *global_stack;
52 ST_DATA Sym *local_stack;
53 ST_DATA Sym *scope_stack_bottom;
54 ST_DATA Sym *define_stack;
55 ST_DATA Sym *global_label_stack;
56 ST_DATA Sym *local_label_stack;
58 ST_DATA int vla_sp_loc_tmp; /* vla_sp_loc is set to this when the value won't be needed later */
59 ST_DATA int vla_sp_root_loc; /* vla_sp_loc for SP before any VLAs were pushed */
60 ST_DATA int *vla_sp_loc; /* Pointer to variable holding location to store stack pointer on the stack when modifying stack pointer */
61 ST_DATA int vla_flags; /* VLA_* flags */
63 ST_DATA SValue __vstack[1+VSTACK_SIZE], *vtop;
65 ST_DATA int const_wanted; /* true if constant wanted */
66 ST_DATA int nocode_wanted; /* true if no code generation wanted for an expression */
67 ST_DATA int global_expr; /* true if compound literals must be allocated globally (used during initializers parsing */
68 ST_DATA CType func_vt; /* current function return type (used by return instruction) */
69 ST_DATA int func_var; /* true if current function is variadic (used by return instruction) */
70 ST_DATA int func_vc;
71 ST_DATA int last_line_num, last_ind, func_ind; /* debug last line number and pc */
72 ST_DATA char *funcname;
74 ST_DATA CType char_pointer_type, func_old_type, int_type, size_type;
76 /* ------------------------------------------------------------------------- */
77 static void gen_cast(CType *type);
78 static inline CType *pointed_type(CType *type);
79 static int is_compatible_types(CType *type1, CType *type2);
80 static int parse_btype(CType *type, AttributeDef *ad);
81 static void type_decl(CType *type, AttributeDef *ad, int *v, int td);
82 static void parse_expr_type(CType *type);
83 static void decl_initializer(CType *type, Section *sec, unsigned long c, int first, int size_only);
84 static void block(int *bsym, int *csym, int *case_sym, int *def_sym, int case_reg, int is_expr);
85 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r, int has_init, int v, char *asm_label, int scope);
86 static int decl0(int l, int is_for_loop_init);
87 static void expr_eq(void);
88 static void unary_type(CType *type);
89 static void vla_runtime_type_size(CType *type, int *a);
90 static void vla_sp_save(void);
91 static int is_compatible_parameter_types(CType *type1, CType *type2);
92 static void expr_type(CType *type);
93 ST_FUNC void vpush64(int ty, unsigned long long v);
94 ST_FUNC void vpush(CType *type);
95 ST_FUNC int gvtst(int inv, int t);
96 ST_FUNC int is_btype_size(int bt);
98 ST_INLN int is_float(int t)
100 int bt;
101 bt = t & VT_BTYPE;
102 return bt == VT_LDOUBLE || bt == VT_DOUBLE || bt == VT_FLOAT || bt == VT_QFLOAT;
105 /* we use our own 'finite' function to avoid potential problems with
106 non standard math libs */
107 /* XXX: endianness dependent */
108 ST_FUNC int ieee_finite(double d)
110 int p[4];
111 memcpy(p, &d, sizeof(double));
112 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
115 ST_FUNC void test_lvalue(void)
117 if (!(vtop->r & VT_LVAL))
118 expect("lvalue");
121 /* ------------------------------------------------------------------------- */
122 /* symbol allocator */
123 static Sym *__sym_malloc(void)
125 Sym *sym_pool, *sym, *last_sym;
126 int i;
128 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
129 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
131 last_sym = sym_free_first;
132 sym = sym_pool;
133 for(i = 0; i < SYM_POOL_NB; i++) {
134 sym->next = last_sym;
135 last_sym = sym;
136 sym++;
138 sym_free_first = last_sym;
139 return last_sym;
142 static inline Sym *sym_malloc(void)
144 Sym *sym;
145 sym = sym_free_first;
146 if (!sym)
147 sym = __sym_malloc();
148 sym_free_first = sym->next;
149 return sym;
152 ST_INLN void sym_free(Sym *sym)
154 sym->next = sym_free_first;
155 tcc_free(sym->asm_label);
156 sym_free_first = sym;
159 /* push, without hashing */
160 ST_FUNC Sym *sym_push2(Sym **ps, int v, int t, long c)
162 Sym *s;
163 if (ps == &local_stack) {
164 for (s = *ps; s && s != scope_stack_bottom; s = s->prev)
165 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM && s->v == v)
166 tcc_error("incompatible types for redefinition of '%s'",
167 get_tok_str(v, NULL));
169 s = sym_malloc();
170 s->asm_label = NULL;
171 s->v = v;
172 s->type.t = t;
173 s->type.ref = NULL;
174 #ifdef _WIN64
175 s->d = NULL;
176 #endif
177 s->c = c;
178 s->next = NULL;
179 /* add in stack */
180 s->prev = *ps;
181 *ps = s;
182 return s;
185 /* find a symbol and return its associated structure. 's' is the top
186 of the symbol stack */
187 ST_FUNC Sym *sym_find2(Sym *s, int v)
189 while (s) {
190 if (s->v == v)
191 return s;
192 else if (s->v == -1)
193 return NULL;
194 s = s->prev;
196 return NULL;
199 /* structure lookup */
200 ST_INLN Sym *struct_find(int v)
202 v -= TOK_IDENT;
203 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
204 return NULL;
205 return table_ident[v]->sym_struct;
208 /* find an identifier */
209 ST_INLN Sym *sym_find(int v)
211 v -= TOK_IDENT;
212 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
213 return NULL;
214 return table_ident[v]->sym_identifier;
217 /* push a given symbol on the symbol stack */
218 ST_FUNC Sym *sym_push(int v, CType *type, int r, int c)
220 Sym *s, **ps;
221 TokenSym *ts;
223 if (local_stack)
224 ps = &local_stack;
225 else
226 ps = &global_stack;
227 s = sym_push2(ps, v, type->t, c);
228 s->type.ref = type->ref;
229 s->r = r;
230 /* don't record fields or anonymous symbols */
231 /* XXX: simplify */
232 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
233 /* record symbol in token array */
234 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
235 if (v & SYM_STRUCT)
236 ps = &ts->sym_struct;
237 else
238 ps = &ts->sym_identifier;
239 s->prev_tok = *ps;
240 *ps = s;
242 return s;
245 /* push a global identifier */
246 ST_FUNC Sym *global_identifier_push(int v, int t, int c)
248 Sym *s, **ps;
249 s = sym_push2(&global_stack, v, t, c);
250 /* don't record anonymous symbol */
251 if (v < SYM_FIRST_ANOM) {
252 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
253 /* modify the top most local identifier, so that
254 sym_identifier will point to 's' when popped */
255 while (*ps != NULL)
256 ps = &(*ps)->prev_tok;
257 s->prev_tok = NULL;
258 *ps = s;
260 return s;
263 /* pop symbols until top reaches 'b' */
264 ST_FUNC void sym_pop(Sym **ptop, Sym *b)
266 Sym *s, *ss, **ps;
267 TokenSym *ts;
268 int v;
270 s = *ptop;
271 while(s != b) {
272 ss = s->prev;
273 v = s->v;
274 /* remove symbol in token array */
275 /* XXX: simplify */
276 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
277 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
278 if (v & SYM_STRUCT)
279 ps = &ts->sym_struct;
280 else
281 ps = &ts->sym_identifier;
282 *ps = s->prev_tok;
284 sym_free(s);
285 s = ss;
287 *ptop = b;
290 static void weaken_symbol(Sym *sym)
292 sym->type.t |= VT_WEAK;
293 if (sym->c > 0) {
294 int esym_type;
295 ElfW(Sym) *esym;
297 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
298 esym_type = ELFW(ST_TYPE)(esym->st_info);
299 esym->st_info = ELFW(ST_INFO)(STB_WEAK, esym_type);
303 static void apply_visibility(Sym *sym, CType *type)
305 int vis = sym->type.t & VT_VIS_MASK;
306 int vis2 = type->t & VT_VIS_MASK;
307 if (vis == (STV_DEFAULT << VT_VIS_SHIFT))
308 vis = vis2;
309 else if (vis2 == (STV_DEFAULT << VT_VIS_SHIFT))
311 else
312 vis = (vis < vis2) ? vis : vis2;
313 sym->type.t &= ~VT_VIS_MASK;
314 sym->type.t |= vis;
316 if (sym->c > 0) {
317 ElfW(Sym) *esym;
319 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
320 vis >>= VT_VIS_SHIFT;
321 esym->st_other = (esym->st_other & ~ELFW(ST_VISIBILITY)(-1)) | vis;
325 /* ------------------------------------------------------------------------- */
327 ST_FUNC void swap(int *p, int *q)
329 int t;
330 t = *p;
331 *p = *q;
332 *q = t;
335 static void vsetc(CType *type, int r, CValue *vc)
337 int v;
339 if (vtop >= vstack + (VSTACK_SIZE - 1))
340 tcc_error("memory full (vstack)");
341 /* cannot let cpu flags if other instruction are generated. Also
342 avoid leaving VT_JMP anywhere except on the top of the stack
343 because it would complicate the code generator. */
344 if (vtop >= vstack) {
345 v = vtop->r & VT_VALMASK;
346 if (v == VT_CMP || (v & ~1) == VT_JMP)
347 gv(RC_INT);
349 vtop++;
350 vtop->type = *type;
351 vtop->r = r;
352 vtop->r2 = VT_CONST;
353 vtop->c = *vc;
356 /* push constant of type "type" with useless value */
357 ST_FUNC void vpush(CType *type)
359 CValue cval;
360 vsetc(type, VT_CONST, &cval);
363 /* push integer constant */
364 ST_FUNC void vpushi(int v)
366 CValue cval;
367 cval.i = v;
368 vsetc(&int_type, VT_CONST, &cval);
371 /* push a pointer sized constant */
372 static void vpushs(addr_t v)
374 CValue cval;
375 cval.ptr_offset = v;
376 vsetc(&size_type, VT_CONST, &cval);
379 /* push arbitrary 64bit constant */
380 ST_FUNC void vpush64(int ty, unsigned long long v)
382 CValue cval;
383 CType ctype;
384 ctype.t = ty;
385 ctype.ref = NULL;
386 cval.ull = v;
387 vsetc(&ctype, VT_CONST, &cval);
390 /* push long long constant */
391 static inline void vpushll(long long v)
393 vpush64(VT_LLONG, v);
396 /* push a symbol value of TYPE */
397 static inline void vpushsym(CType *type, Sym *sym)
399 CValue cval;
400 cval.ptr_offset = 0;
401 vsetc(type, VT_CONST | VT_SYM, &cval);
402 vtop->sym = sym;
405 /* Return a static symbol pointing to a section */
406 ST_FUNC Sym *get_sym_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
408 int v;
409 Sym *sym;
411 v = anon_sym++;
412 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
413 sym->type.ref = type->ref;
414 sym->r = VT_CONST | VT_SYM;
415 put_extern_sym(sym, sec, offset, size);
416 return sym;
419 /* push a reference to a section offset by adding a dummy symbol */
420 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
422 vpushsym(type, get_sym_ref(type, sec, offset, size));
425 /* define a new external reference to a symbol 'v' of type 'u' */
426 ST_FUNC Sym *external_global_sym(int v, CType *type, int r)
428 Sym *s;
430 s = sym_find(v);
431 if (!s) {
432 /* push forward reference */
433 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
434 s->type.ref = type->ref;
435 s->r = r | VT_CONST | VT_SYM;
437 return s;
440 /* define a new external reference to a symbol 'v' with alternate asm
441 name 'asm_label' of type 'u'. 'asm_label' is equal to NULL if there
442 is no alternate name (most cases) */
443 static Sym *external_sym(int v, CType *type, int r, char *asm_label)
445 Sym *s;
447 s = sym_find(v);
448 if (!s) {
449 /* push forward reference */
450 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
451 s->asm_label = asm_label;
452 s->type.t |= VT_EXTERN;
453 } else if (s->type.ref == func_old_type.ref) {
454 s->type.ref = type->ref;
455 s->r = r | VT_CONST | VT_SYM;
456 s->type.t |= VT_EXTERN;
457 } else if (!is_compatible_types(&s->type, type)) {
458 tcc_error("incompatible types for redefinition of '%s'",
459 get_tok_str(v, NULL));
461 /* Merge some storage attributes. */
462 if (type->t & VT_WEAK)
463 weaken_symbol(s);
465 if (type->t & VT_VIS_MASK)
466 apply_visibility(s, type);
468 return s;
471 /* push a reference to global symbol v */
472 ST_FUNC void vpush_global_sym(CType *type, int v)
474 vpushsym(type, external_global_sym(v, type, 0));
477 ST_FUNC void vset(CType *type, int r, int v)
479 CValue cval;
481 cval.i = v;
482 vsetc(type, r, &cval);
485 static void vseti(int r, int v)
487 CType type;
488 type.t = VT_INT;
489 type.ref = 0;
490 vset(&type, r, v);
493 ST_FUNC void vswap(void)
495 SValue tmp;
496 /* cannot let cpu flags if other instruction are generated. Also
497 avoid leaving VT_JMP anywhere except on the top of the stack
498 because it would complicate the code generator. */
499 if (vtop >= vstack) {
500 int v = vtop->r & VT_VALMASK;
501 if (v == VT_CMP || (v & ~1) == VT_JMP)
502 gv(RC_INT);
504 tmp = vtop[0];
505 vtop[0] = vtop[-1];
506 vtop[-1] = tmp;
508 /* XXX: +2% overall speed possible with optimized memswap
510 * memswap(&vtop[0], &vtop[1], sizeof *vtop);
514 ST_FUNC void vpushv(SValue *v)
516 if (vtop >= vstack + (VSTACK_SIZE - 1))
517 tcc_error("memory full (vstack)");
518 vtop++;
519 *vtop = *v;
522 static void vdup(void)
524 vpushv(vtop);
527 /* save r to the memory stack, and mark it as being free */
528 ST_FUNC void save_reg(int r)
530 int l, saved, size, align;
531 SValue *p, sv;
532 CType *type;
534 /* modify all stack values */
535 saved = 0;
536 l = 0;
537 for(p=vstack;p<=vtop;p++) {
538 if ((p->r & VT_VALMASK) == r ||
539 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
540 /* must save value on stack if not already done */
541 if (!saved) {
542 /* NOTE: must reload 'r' because r might be equal to r2 */
543 r = p->r & VT_VALMASK;
544 /* store register in the stack */
545 type = &p->type;
546 if ((p->r & VT_LVAL) ||
547 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
548 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
549 type = &char_pointer_type;
550 #else
551 type = &int_type;
552 #endif
553 size = type_size(type, &align);
554 loc = (loc - size) & -align;
555 sv.type.t = type->t;
556 sv.r = VT_LOCAL | VT_LVAL;
557 sv.c.ul = loc;
558 store(r, &sv);
559 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
560 /* x86 specific: need to pop fp register ST0 if saved */
561 if (r == TREG_ST0) {
562 o(0xd8dd); /* fstp %st(0) */
564 #endif
565 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
566 /* special long long case */
567 if ((type->t & VT_BTYPE) == VT_LLONG) {
568 sv.c.ul += 4;
569 store(p->r2, &sv);
571 #endif
572 l = loc;
573 saved = 1;
575 /* mark that stack entry as being saved on the stack */
576 if (p->r & VT_LVAL) {
577 /* also clear the bounded flag because the
578 relocation address of the function was stored in
579 p->c.ul */
580 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
581 } else {
582 p->r = lvalue_type(p->type.t) | VT_LOCAL;
584 p->r2 = VT_CONST;
585 p->c.ul = l;
590 #ifdef TCC_TARGET_ARM
591 /* find a register of class 'rc2' with at most one reference on stack.
592 * If none, call get_reg(rc) */
593 ST_FUNC int get_reg_ex(int rc, int rc2)
595 int r;
596 SValue *p;
598 for(r=0;r<NB_REGS;r++) {
599 if (reg_classes[r] & rc2) {
600 int n;
601 n=0;
602 for(p = vstack; p <= vtop; p++) {
603 if ((p->r & VT_VALMASK) == r ||
604 (p->r2 & VT_VALMASK) == r)
605 n++;
607 if (n <= 1)
608 return r;
611 return get_reg(rc);
613 #endif
615 /* find a free register of class 'rc'. If none, save one register */
616 ST_FUNC int get_reg(int rc)
618 int r;
619 SValue *p;
621 /* find a free register */
622 for(r=0;r<NB_REGS;r++) {
623 if (reg_classes[r] & rc) {
624 for(p=vstack;p<=vtop;p++) {
625 if ((p->r & VT_VALMASK) == r ||
626 (p->r2 & VT_VALMASK) == r)
627 goto notfound;
629 return r;
631 notfound: ;
634 /* no register left : free the first one on the stack (VERY
635 IMPORTANT to start from the bottom to ensure that we don't
636 spill registers used in gen_opi()) */
637 for(p=vstack;p<=vtop;p++) {
638 /* look at second register (if long long) */
639 r = p->r2 & VT_VALMASK;
640 if (r < VT_CONST && (reg_classes[r] & rc))
641 goto save_found;
642 r = p->r & VT_VALMASK;
643 if (r < VT_CONST && (reg_classes[r] & rc)) {
644 save_found:
645 save_reg(r);
646 return r;
649 /* Should never comes here */
650 return -1;
653 /* save registers up to (vtop - n) stack entry */
654 ST_FUNC void save_regs(int n)
656 int r;
657 SValue *p, *p1;
658 p1 = vtop - n;
659 for(p = vstack;p <= p1; p++) {
660 r = p->r & VT_VALMASK;
661 if (r < VT_CONST) {
662 save_reg(r);
667 /* move register 's' (of type 't') to 'r', and flush previous value of r to memory
668 if needed */
669 static void move_reg(int r, int s, int t)
671 SValue sv;
673 if (r != s) {
674 save_reg(r);
675 sv.type.t = t;
676 sv.type.ref = NULL;
677 sv.r = s;
678 sv.c.ul = 0;
679 load(r, &sv);
683 /* get address of vtop (vtop MUST BE an lvalue) */
684 ST_FUNC void gaddrof(void)
686 if (vtop->r & VT_REF && !nocode_wanted)
687 gv(RC_INT);
688 vtop->r &= ~VT_LVAL;
689 /* tricky: if saved lvalue, then we can go back to lvalue */
690 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
691 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
696 #ifdef CONFIG_TCC_BCHECK
697 /* generate lvalue bound code */
698 static void gbound(void)
700 int lval_type;
701 CType type1;
703 vtop->r &= ~VT_MUSTBOUND;
704 /* if lvalue, then use checking code before dereferencing */
705 if (vtop->r & VT_LVAL) {
706 /* if not VT_BOUNDED value, then make one */
707 if (!(vtop->r & VT_BOUNDED)) {
708 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
709 /* must save type because we must set it to int to get pointer */
710 type1 = vtop->type;
711 vtop->type.t = VT_INT;
712 gaddrof();
713 vpushi(0);
714 gen_bounded_ptr_add();
715 vtop->r |= lval_type;
716 vtop->type = type1;
718 /* then check for dereferencing */
719 gen_bounded_ptr_deref();
722 #endif
724 /* store vtop a register belonging to class 'rc'. lvalues are
725 converted to values. Cannot be used if cannot be converted to
726 register value (such as structures). */
727 ST_FUNC int gv(int rc)
729 int r, bit_pos, bit_size, size, align, i;
730 int rc2;
732 /* NOTE: get_reg can modify vstack[] */
733 if (vtop->type.t & VT_BITFIELD) {
734 CType type;
735 int bits = 32;
736 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
737 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
738 /* remove bit field info to avoid loops */
739 vtop->type.t &= ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
740 /* cast to int to propagate signedness in following ops */
741 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
742 type.t = VT_LLONG;
743 bits = 64;
744 } else
745 type.t = VT_INT;
746 if((vtop->type.t & VT_UNSIGNED) ||
747 (vtop->type.t & VT_BTYPE) == VT_BOOL)
748 type.t |= VT_UNSIGNED;
749 gen_cast(&type);
750 /* generate shifts */
751 vpushi(bits - (bit_pos + bit_size));
752 gen_op(TOK_SHL);
753 vpushi(bits - bit_size);
754 /* NOTE: transformed to SHR if unsigned */
755 gen_op(TOK_SAR);
756 r = gv(rc);
757 } else {
758 if (is_float(vtop->type.t) &&
759 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
760 Sym *sym;
761 int *ptr;
762 unsigned long offset;
763 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
764 CValue check;
765 #endif
767 /* XXX: unify with initializers handling ? */
768 /* CPUs usually cannot use float constants, so we store them
769 generically in data segment */
770 size = type_size(&vtop->type, &align);
771 offset = (data_section->data_offset + align - 1) & -align;
772 data_section->data_offset = offset;
773 /* XXX: not portable yet */
774 #if defined(__i386__) || defined(__x86_64__)
775 /* Zero pad x87 tenbyte long doubles */
776 if (size == LDOUBLE_SIZE) {
777 vtop->c.tab[2] &= 0xffff;
778 #if LDOUBLE_SIZE == 16
779 vtop->c.tab[3] = 0;
780 #endif
782 #endif
783 ptr = section_ptr_add(data_section, size);
784 size = size >> 2;
785 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
786 check.d = 1;
787 if(check.tab[0])
788 for(i=0;i<size;i++)
789 ptr[i] = vtop->c.tab[size-1-i];
790 else
791 #endif
792 for(i=0;i<size;i++)
793 ptr[i] = vtop->c.tab[i];
794 sym = get_sym_ref(&vtop->type, data_section, offset, size << 2);
795 vtop->r |= VT_LVAL | VT_SYM;
796 vtop->sym = sym;
797 vtop->c.ptr_offset = 0;
799 #ifdef CONFIG_TCC_BCHECK
800 if (vtop->r & VT_MUSTBOUND)
801 gbound();
802 #endif
804 r = vtop->r & VT_VALMASK;
805 rc2 = (rc & RC_FLOAT) ? RC_FLOAT : RC_INT;
806 #ifndef TCC_TARGET_ARM64
807 if (rc == RC_IRET)
808 rc2 = RC_LRET;
809 #ifdef TCC_TARGET_X86_64
810 else if (rc == RC_FRET)
811 rc2 = RC_QRET;
812 #endif
813 #endif
815 /* need to reload if:
816 - constant
817 - lvalue (need to dereference pointer)
818 - already a register, but not in the right class */
819 if (r >= VT_CONST
820 || (vtop->r & VT_LVAL)
821 || !(reg_classes[r] & rc)
822 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
823 || ((vtop->type.t & VT_BTYPE) == VT_QLONG && !(reg_classes[vtop->r2] & rc2))
824 || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT && !(reg_classes[vtop->r2] & rc2))
825 #else
826 || ((vtop->type.t & VT_BTYPE) == VT_LLONG && !(reg_classes[vtop->r2] & rc2))
827 #endif
830 r = get_reg(rc);
831 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
832 if (((vtop->type.t & VT_BTYPE) == VT_QLONG) || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT)) {
833 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
834 #else
835 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
836 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
837 unsigned long long ll;
838 #endif
839 int r2, original_type;
840 original_type = vtop->type.t;
841 /* two register type load : expand to two words
842 temporarily */
843 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
844 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
845 /* load constant */
846 ll = vtop->c.ull;
847 vtop->c.ui = ll; /* first word */
848 load(r, vtop);
849 vtop->r = r; /* save register value */
850 vpushi(ll >> 32); /* second word */
851 } else
852 #endif
853 if (r >= VT_CONST || /* XXX: test to VT_CONST incorrect ? */
854 (vtop->r & VT_LVAL)) {
855 /* We do not want to modifier the long long
856 pointer here, so the safest (and less
857 efficient) is to save all the other registers
858 in the stack. XXX: totally inefficient. */
859 save_regs(1);
860 /* load from memory */
861 vtop->type.t = load_type;
862 load(r, vtop);
863 vdup();
864 vtop[-1].r = r; /* save register value */
865 /* increment pointer to get second word */
866 vtop->type.t = addr_type;
867 gaddrof();
868 vpushi(load_size);
869 gen_op('+');
870 vtop->r |= VT_LVAL;
871 vtop->type.t = load_type;
872 } else {
873 /* move registers */
874 load(r, vtop);
875 vdup();
876 vtop[-1].r = r; /* save register value */
877 vtop->r = vtop[-1].r2;
879 /* Allocate second register. Here we rely on the fact that
880 get_reg() tries first to free r2 of an SValue. */
881 r2 = get_reg(rc2);
882 load(r2, vtop);
883 vpop();
884 /* write second register */
885 vtop->r2 = r2;
886 vtop->type.t = original_type;
887 } else if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
888 int t1, t;
889 /* lvalue of scalar type : need to use lvalue type
890 because of possible cast */
891 t = vtop->type.t;
892 t1 = t;
893 /* compute memory access type */
894 if (vtop->r & VT_REF)
895 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
896 t = VT_PTR;
897 #else
898 t = VT_INT;
899 #endif
900 else if (vtop->r & VT_LVAL_BYTE)
901 t = VT_BYTE;
902 else if (vtop->r & VT_LVAL_SHORT)
903 t = VT_SHORT;
904 if (vtop->r & VT_LVAL_UNSIGNED)
905 t |= VT_UNSIGNED;
906 vtop->type.t = t;
907 load(r, vtop);
908 /* restore wanted type */
909 vtop->type.t = t1;
910 } else {
911 /* one register type load */
912 load(r, vtop);
915 vtop->r = r;
916 #ifdef TCC_TARGET_C67
917 /* uses register pairs for doubles */
918 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
919 vtop->r2 = r+1;
920 #endif
922 return r;
925 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
926 ST_FUNC void gv2(int rc1, int rc2)
928 int v;
930 /* generate more generic register first. But VT_JMP or VT_CMP
931 values must be generated first in all cases to avoid possible
932 reload errors */
933 v = vtop[0].r & VT_VALMASK;
934 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
935 vswap();
936 gv(rc1);
937 vswap();
938 gv(rc2);
939 /* test if reload is needed for first register */
940 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
941 vswap();
942 gv(rc1);
943 vswap();
945 } else {
946 gv(rc2);
947 vswap();
948 gv(rc1);
949 vswap();
950 /* test if reload is needed for first register */
951 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
952 gv(rc2);
957 #ifndef TCC_TARGET_ARM64
958 /* wrapper around RC_FRET to return a register by type */
959 static int rc_fret(int t)
961 #ifdef TCC_TARGET_X86_64
962 if (t == VT_LDOUBLE) {
963 return RC_ST0;
965 #endif
966 return RC_FRET;
968 #endif
970 /* wrapper around REG_FRET to return a register by type */
971 static int reg_fret(int t)
973 #ifdef TCC_TARGET_X86_64
974 if (t == VT_LDOUBLE) {
975 return TREG_ST0;
977 #endif
978 return REG_FRET;
981 /* expand long long on stack in two int registers */
982 static void lexpand(void)
984 int u;
986 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
987 gv(RC_INT);
988 vdup();
989 vtop[0].r = vtop[-1].r2;
990 vtop[0].r2 = VT_CONST;
991 vtop[-1].r2 = VT_CONST;
992 vtop[0].type.t = VT_INT | u;
993 vtop[-1].type.t = VT_INT | u;
996 #ifdef TCC_TARGET_ARM
997 /* expand long long on stack */
998 ST_FUNC void lexpand_nr(void)
1000 int u,v;
1002 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
1003 vdup();
1004 vtop->r2 = VT_CONST;
1005 vtop->type.t = VT_INT | u;
1006 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
1007 if (v == VT_CONST) {
1008 vtop[-1].c.ui = vtop->c.ull;
1009 vtop->c.ui = vtop->c.ull >> 32;
1010 vtop->r = VT_CONST;
1011 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
1012 vtop->c.ui += 4;
1013 vtop->r = vtop[-1].r;
1014 } else if (v > VT_CONST) {
1015 vtop--;
1016 lexpand();
1017 } else
1018 vtop->r = vtop[-1].r2;
1019 vtop[-1].r2 = VT_CONST;
1020 vtop[-1].type.t = VT_INT | u;
1022 #endif
1024 /* build a long long from two ints */
1025 static void lbuild(int t)
1027 gv2(RC_INT, RC_INT);
1028 vtop[-1].r2 = vtop[0].r;
1029 vtop[-1].type.t = t;
1030 vpop();
1033 /* rotate n first stack elements to the bottom
1034 I1 ... In -> I2 ... In I1 [top is right]
1036 ST_FUNC void vrotb(int n)
1038 int i;
1039 SValue tmp;
1041 tmp = vtop[-n + 1];
1042 for(i=-n+1;i!=0;i++)
1043 vtop[i] = vtop[i+1];
1044 vtop[0] = tmp;
1047 /* rotate the n elements before entry e towards the top
1048 I1 ... In ... -> In I1 ... I(n-1) ... [top is right]
1050 ST_FUNC void vrote(SValue *e, int n)
1052 int i;
1053 SValue tmp;
1055 tmp = *e;
1056 for(i = 0;i < n - 1; i++)
1057 e[-i] = e[-i - 1];
1058 e[-n + 1] = tmp;
1061 /* rotate n first stack elements to the top
1062 I1 ... In -> In I1 ... I(n-1) [top is right]
1064 ST_FUNC void vrott(int n)
1066 vrote(vtop, n);
1069 /* pop stack value */
1070 ST_FUNC void vpop(void)
1072 int v;
1073 v = vtop->r & VT_VALMASK;
1074 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1075 /* for x86, we need to pop the FP stack */
1076 if (v == TREG_ST0 && !nocode_wanted) {
1077 o(0xd8dd); /* fstp %st(0) */
1078 } else
1079 #endif
1080 if (v == VT_JMP || v == VT_JMPI) {
1081 /* need to put correct jump if && or || without test */
1082 gsym(vtop->c.ul);
1084 vtop--;
1087 /* convert stack entry to register and duplicate its value in another
1088 register */
1089 static void gv_dup(void)
1091 int rc, t, r, r1;
1092 SValue sv;
1094 t = vtop->type.t;
1095 if ((t & VT_BTYPE) == VT_LLONG) {
1096 lexpand();
1097 gv_dup();
1098 vswap();
1099 vrotb(3);
1100 gv_dup();
1101 vrotb(4);
1102 /* stack: H L L1 H1 */
1103 lbuild(t);
1104 vrotb(3);
1105 vrotb(3);
1106 vswap();
1107 lbuild(t);
1108 vswap();
1109 } else {
1110 /* duplicate value */
1111 rc = RC_INT;
1112 sv.type.t = VT_INT;
1113 if (is_float(t)) {
1114 rc = RC_FLOAT;
1115 #ifdef TCC_TARGET_X86_64
1116 if ((t & VT_BTYPE) == VT_LDOUBLE) {
1117 rc = RC_ST0;
1119 #endif
1120 sv.type.t = t;
1122 r = gv(rc);
1123 r1 = get_reg(rc);
1124 sv.r = r;
1125 sv.c.ul = 0;
1126 load(r1, &sv); /* move r to r1 */
1127 vdup();
1128 /* duplicates value */
1129 if (r != r1)
1130 vtop->r = r1;
1134 /* Generate value test
1136 * Generate a test for any value (jump, comparison and integers) */
1137 ST_FUNC int gvtst(int inv, int t)
1139 int v = vtop->r & VT_VALMASK;
1140 if (v != VT_CMP && v != VT_JMP && v != VT_JMPI) {
1141 vpushi(0);
1142 gen_op(TOK_NE);
1144 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1145 /* constant jmp optimization */
1146 if ((vtop->c.i != 0) != inv)
1147 t = gjmp(t);
1148 vtop--;
1149 return t;
1151 return gtst(inv, t);
1154 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
1155 /* generate CPU independent (unsigned) long long operations */
1156 static void gen_opl(int op)
1158 int t, a, b, op1, c, i;
1159 int func;
1160 unsigned short reg_iret = REG_IRET;
1161 unsigned short reg_lret = REG_LRET;
1162 SValue tmp;
1164 switch(op) {
1165 case '/':
1166 case TOK_PDIV:
1167 func = TOK___divdi3;
1168 goto gen_func;
1169 case TOK_UDIV:
1170 func = TOK___udivdi3;
1171 goto gen_func;
1172 case '%':
1173 func = TOK___moddi3;
1174 goto gen_mod_func;
1175 case TOK_UMOD:
1176 func = TOK___umoddi3;
1177 gen_mod_func:
1178 #ifdef TCC_ARM_EABI
1179 reg_iret = TREG_R2;
1180 reg_lret = TREG_R3;
1181 #endif
1182 gen_func:
1183 /* call generic long long function */
1184 vpush_global_sym(&func_old_type, func);
1185 vrott(3);
1186 gfunc_call(2);
1187 vpushi(0);
1188 vtop->r = reg_iret;
1189 vtop->r2 = reg_lret;
1190 break;
1191 case '^':
1192 case '&':
1193 case '|':
1194 case '*':
1195 case '+':
1196 case '-':
1197 t = vtop->type.t;
1198 vswap();
1199 lexpand();
1200 vrotb(3);
1201 lexpand();
1202 /* stack: L1 H1 L2 H2 */
1203 tmp = vtop[0];
1204 vtop[0] = vtop[-3];
1205 vtop[-3] = tmp;
1206 tmp = vtop[-2];
1207 vtop[-2] = vtop[-3];
1208 vtop[-3] = tmp;
1209 vswap();
1210 /* stack: H1 H2 L1 L2 */
1211 if (op == '*') {
1212 vpushv(vtop - 1);
1213 vpushv(vtop - 1);
1214 gen_op(TOK_UMULL);
1215 lexpand();
1216 /* stack: H1 H2 L1 L2 ML MH */
1217 for(i=0;i<4;i++)
1218 vrotb(6);
1219 /* stack: ML MH H1 H2 L1 L2 */
1220 tmp = vtop[0];
1221 vtop[0] = vtop[-2];
1222 vtop[-2] = tmp;
1223 /* stack: ML MH H1 L2 H2 L1 */
1224 gen_op('*');
1225 vrotb(3);
1226 vrotb(3);
1227 gen_op('*');
1228 /* stack: ML MH M1 M2 */
1229 gen_op('+');
1230 gen_op('+');
1231 } else if (op == '+' || op == '-') {
1232 /* XXX: add non carry method too (for MIPS or alpha) */
1233 if (op == '+')
1234 op1 = TOK_ADDC1;
1235 else
1236 op1 = TOK_SUBC1;
1237 gen_op(op1);
1238 /* stack: H1 H2 (L1 op L2) */
1239 vrotb(3);
1240 vrotb(3);
1241 gen_op(op1 + 1); /* TOK_xxxC2 */
1242 } else {
1243 gen_op(op);
1244 /* stack: H1 H2 (L1 op L2) */
1245 vrotb(3);
1246 vrotb(3);
1247 /* stack: (L1 op L2) H1 H2 */
1248 gen_op(op);
1249 /* stack: (L1 op L2) (H1 op H2) */
1251 /* stack: L H */
1252 lbuild(t);
1253 break;
1254 case TOK_SAR:
1255 case TOK_SHR:
1256 case TOK_SHL:
1257 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1258 t = vtop[-1].type.t;
1259 vswap();
1260 lexpand();
1261 vrotb(3);
1262 /* stack: L H shift */
1263 c = (int)vtop->c.i;
1264 /* constant: simpler */
1265 /* NOTE: all comments are for SHL. the other cases are
1266 done by swaping words */
1267 vpop();
1268 if (op != TOK_SHL)
1269 vswap();
1270 if (c >= 32) {
1271 /* stack: L H */
1272 vpop();
1273 if (c > 32) {
1274 vpushi(c - 32);
1275 gen_op(op);
1277 if (op != TOK_SAR) {
1278 vpushi(0);
1279 } else {
1280 gv_dup();
1281 vpushi(31);
1282 gen_op(TOK_SAR);
1284 vswap();
1285 } else {
1286 vswap();
1287 gv_dup();
1288 /* stack: H L L */
1289 vpushi(c);
1290 gen_op(op);
1291 vswap();
1292 vpushi(32 - c);
1293 if (op == TOK_SHL)
1294 gen_op(TOK_SHR);
1295 else
1296 gen_op(TOK_SHL);
1297 vrotb(3);
1298 /* stack: L L H */
1299 vpushi(c);
1300 if (op == TOK_SHL)
1301 gen_op(TOK_SHL);
1302 else
1303 gen_op(TOK_SHR);
1304 gen_op('|');
1306 if (op != TOK_SHL)
1307 vswap();
1308 lbuild(t);
1309 } else {
1310 /* XXX: should provide a faster fallback on x86 ? */
1311 switch(op) {
1312 case TOK_SAR:
1313 func = TOK___ashrdi3;
1314 goto gen_func;
1315 case TOK_SHR:
1316 func = TOK___lshrdi3;
1317 goto gen_func;
1318 case TOK_SHL:
1319 func = TOK___ashldi3;
1320 goto gen_func;
1323 break;
1324 default:
1325 /* compare operations */
1326 t = vtop->type.t;
1327 vswap();
1328 lexpand();
1329 vrotb(3);
1330 lexpand();
1331 /* stack: L1 H1 L2 H2 */
1332 tmp = vtop[-1];
1333 vtop[-1] = vtop[-2];
1334 vtop[-2] = tmp;
1335 /* stack: L1 L2 H1 H2 */
1336 /* compare high */
1337 op1 = op;
1338 /* when values are equal, we need to compare low words. since
1339 the jump is inverted, we invert the test too. */
1340 if (op1 == TOK_LT)
1341 op1 = TOK_LE;
1342 else if (op1 == TOK_GT)
1343 op1 = TOK_GE;
1344 else if (op1 == TOK_ULT)
1345 op1 = TOK_ULE;
1346 else if (op1 == TOK_UGT)
1347 op1 = TOK_UGE;
1348 a = 0;
1349 b = 0;
1350 gen_op(op1);
1351 if (op1 != TOK_NE) {
1352 a = gvtst(1, 0);
1354 if (op != TOK_EQ) {
1355 /* generate non equal test */
1356 /* XXX: NOT PORTABLE yet */
1357 if (a == 0) {
1358 b = gvtst(0, 0);
1359 } else {
1360 #if defined(TCC_TARGET_I386)
1361 b = psym(0x850f, 0);
1362 #elif defined(TCC_TARGET_ARM)
1363 b = ind;
1364 o(0x1A000000 | encbranch(ind, 0, 1));
1365 #elif defined(TCC_TARGET_C67) || defined(TCC_TARGET_ARM64)
1366 tcc_error("not implemented");
1367 #else
1368 #error not supported
1369 #endif
1372 /* compare low. Always unsigned */
1373 op1 = op;
1374 if (op1 == TOK_LT)
1375 op1 = TOK_ULT;
1376 else if (op1 == TOK_LE)
1377 op1 = TOK_ULE;
1378 else if (op1 == TOK_GT)
1379 op1 = TOK_UGT;
1380 else if (op1 == TOK_GE)
1381 op1 = TOK_UGE;
1382 gen_op(op1);
1383 a = gvtst(1, a);
1384 gsym(b);
1385 vseti(VT_JMPI, a);
1386 break;
1389 #endif
1391 /* handle integer constant optimizations and various machine
1392 independent opt */
1393 static void gen_opic(int op)
1395 int c1, c2, t1, t2, n;
1396 SValue *v1, *v2;
1397 long long l1, l2;
1398 typedef unsigned long long U;
1400 v1 = vtop - 1;
1401 v2 = vtop;
1402 t1 = v1->type.t & VT_BTYPE;
1403 t2 = v2->type.t & VT_BTYPE;
1405 if (t1 == VT_LLONG)
1406 l1 = v1->c.ll;
1407 else if (v1->type.t & VT_UNSIGNED)
1408 l1 = v1->c.ui;
1409 else
1410 l1 = v1->c.i;
1412 if (t2 == VT_LLONG)
1413 l2 = v2->c.ll;
1414 else if (v2->type.t & VT_UNSIGNED)
1415 l2 = v2->c.ui;
1416 else
1417 l2 = v2->c.i;
1419 /* currently, we cannot do computations with forward symbols */
1420 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1421 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1422 if (c1 && c2) {
1423 switch(op) {
1424 case '+': l1 += l2; break;
1425 case '-': l1 -= l2; break;
1426 case '&': l1 &= l2; break;
1427 case '^': l1 ^= l2; break;
1428 case '|': l1 |= l2; break;
1429 case '*': l1 *= l2; break;
1431 case TOK_PDIV:
1432 case '/':
1433 case '%':
1434 case TOK_UDIV:
1435 case TOK_UMOD:
1436 /* if division by zero, generate explicit division */
1437 if (l2 == 0) {
1438 if (const_wanted)
1439 tcc_error("division by zero in constant");
1440 goto general_case;
1442 switch(op) {
1443 default: l1 /= l2; break;
1444 case '%': l1 %= l2; break;
1445 case TOK_UDIV: l1 = (U)l1 / l2; break;
1446 case TOK_UMOD: l1 = (U)l1 % l2; break;
1448 break;
1449 case TOK_SHL: l1 <<= l2; break;
1450 case TOK_SHR: l1 = (U)l1 >> l2; break;
1451 case TOK_SAR: l1 >>= l2; break;
1452 /* tests */
1453 case TOK_ULT: l1 = (U)l1 < (U)l2; break;
1454 case TOK_UGE: l1 = (U)l1 >= (U)l2; break;
1455 case TOK_EQ: l1 = l1 == l2; break;
1456 case TOK_NE: l1 = l1 != l2; break;
1457 case TOK_ULE: l1 = (U)l1 <= (U)l2; break;
1458 case TOK_UGT: l1 = (U)l1 > (U)l2; break;
1459 case TOK_LT: l1 = l1 < l2; break;
1460 case TOK_GE: l1 = l1 >= l2; break;
1461 case TOK_LE: l1 = l1 <= l2; break;
1462 case TOK_GT: l1 = l1 > l2; break;
1463 /* logical */
1464 case TOK_LAND: l1 = l1 && l2; break;
1465 case TOK_LOR: l1 = l1 || l2; break;
1466 default:
1467 goto general_case;
1469 v1->c.ll = l1;
1470 vtop--;
1471 } else {
1472 /* if commutative ops, put c2 as constant */
1473 if (c1 && (op == '+' || op == '&' || op == '^' ||
1474 op == '|' || op == '*')) {
1475 vswap();
1476 c2 = c1; //c = c1, c1 = c2, c2 = c;
1477 l2 = l1; //l = l1, l1 = l2, l2 = l;
1479 if (!const_wanted &&
1480 c1 && ((l1 == 0 &&
1481 (op == TOK_SHL || op == TOK_SHR || op == TOK_SAR)) ||
1482 (l1 == -1 && op == TOK_SAR))) {
1483 /* treat (0 << x), (0 >> x) and (-1 >> x) as constant */
1484 vtop--;
1485 } else if (!const_wanted &&
1486 c2 && ((l2 == 0 && (op == '&' || op == '*')) ||
1487 (l2 == -1 && op == '|') ||
1488 (l2 == 0xffffffff && t2 != VT_LLONG && op == '|') ||
1489 (l2 == 1 && (op == '%' || op == TOK_UMOD)))) {
1490 /* treat (x & 0), (x * 0), (x | -1) and (x % 1) as constant */
1491 if (l2 == 1)
1492 vtop->c.ll = 0;
1493 vswap();
1494 vtop--;
1495 } else if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
1496 op == TOK_PDIV) &&
1497 l2 == 1) ||
1498 ((op == '+' || op == '-' || op == '|' || op == '^' ||
1499 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
1500 l2 == 0) ||
1501 (op == '&' &&
1502 l2 == -1))) {
1503 /* filter out NOP operations like x*1, x-0, x&-1... */
1504 vtop--;
1505 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
1506 /* try to use shifts instead of muls or divs */
1507 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
1508 n = -1;
1509 while (l2) {
1510 l2 >>= 1;
1511 n++;
1513 vtop->c.ll = n;
1514 if (op == '*')
1515 op = TOK_SHL;
1516 else if (op == TOK_PDIV)
1517 op = TOK_SAR;
1518 else
1519 op = TOK_SHR;
1521 goto general_case;
1522 } else if (c2 && (op == '+' || op == '-') &&
1523 (((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM))
1524 || (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
1525 /* symbol + constant case */
1526 if (op == '-')
1527 l2 = -l2;
1528 vtop--;
1529 vtop->c.ll += l2;
1530 } else {
1531 general_case:
1532 if (!nocode_wanted) {
1533 /* call low level op generator */
1534 if (t1 == VT_LLONG || t2 == VT_LLONG ||
1535 (PTR_SIZE == 8 && (t1 == VT_PTR || t2 == VT_PTR)))
1536 gen_opl(op);
1537 else
1538 gen_opi(op);
1539 } else {
1540 vtop--;
1546 /* generate a floating point operation with constant propagation */
1547 static void gen_opif(int op)
1549 int c1, c2;
1550 SValue *v1, *v2;
1551 long double f1, f2;
1553 v1 = vtop - 1;
1554 v2 = vtop;
1555 /* currently, we cannot do computations with forward symbols */
1556 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1557 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1558 if (c1 && c2) {
1559 if (v1->type.t == VT_FLOAT) {
1560 f1 = v1->c.f;
1561 f2 = v2->c.f;
1562 } else if (v1->type.t == VT_DOUBLE) {
1563 f1 = v1->c.d;
1564 f2 = v2->c.d;
1565 } else {
1566 f1 = v1->c.ld;
1567 f2 = v2->c.ld;
1570 /* NOTE: we only do constant propagation if finite number (not
1571 NaN or infinity) (ANSI spec) */
1572 if (!ieee_finite(f1) || !ieee_finite(f2))
1573 goto general_case;
1575 switch(op) {
1576 case '+': f1 += f2; break;
1577 case '-': f1 -= f2; break;
1578 case '*': f1 *= f2; break;
1579 case '/':
1580 if (f2 == 0.0) {
1581 if (const_wanted)
1582 tcc_error("division by zero in constant");
1583 goto general_case;
1585 f1 /= f2;
1586 break;
1587 /* XXX: also handles tests ? */
1588 default:
1589 goto general_case;
1591 /* XXX: overflow test ? */
1592 if (v1->type.t == VT_FLOAT) {
1593 v1->c.f = f1;
1594 } else if (v1->type.t == VT_DOUBLE) {
1595 v1->c.d = f1;
1596 } else {
1597 v1->c.ld = f1;
1599 vtop--;
1600 } else {
1601 general_case:
1602 if (!nocode_wanted) {
1603 gen_opf(op);
1604 } else {
1605 vtop--;
1610 static int pointed_size(CType *type)
1612 int align;
1613 return type_size(pointed_type(type), &align);
1616 static void vla_runtime_pointed_size(CType *type)
1618 int align;
1619 vla_runtime_type_size(pointed_type(type), &align);
1622 static inline int is_null_pointer(SValue *p)
1624 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
1625 return 0;
1626 return ((p->type.t & VT_BTYPE) == VT_INT && p->c.i == 0) ||
1627 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.ll == 0) ||
1628 ((p->type.t & VT_BTYPE) == VT_PTR && p->c.ptr_offset == 0);
1631 static inline int is_integer_btype(int bt)
1633 return (bt == VT_BYTE || bt == VT_SHORT ||
1634 bt == VT_INT || bt == VT_LLONG);
1637 /* check types for comparison or subtraction of pointers */
1638 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
1640 CType *type1, *type2, tmp_type1, tmp_type2;
1641 int bt1, bt2;
1643 /* null pointers are accepted for all comparisons as gcc */
1644 if (is_null_pointer(p1) || is_null_pointer(p2))
1645 return;
1646 type1 = &p1->type;
1647 type2 = &p2->type;
1648 bt1 = type1->t & VT_BTYPE;
1649 bt2 = type2->t & VT_BTYPE;
1650 /* accept comparison between pointer and integer with a warning */
1651 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
1652 if (op != TOK_LOR && op != TOK_LAND )
1653 tcc_warning("comparison between pointer and integer");
1654 return;
1657 /* both must be pointers or implicit function pointers */
1658 if (bt1 == VT_PTR) {
1659 type1 = pointed_type(type1);
1660 } else if (bt1 != VT_FUNC)
1661 goto invalid_operands;
1663 if (bt2 == VT_PTR) {
1664 type2 = pointed_type(type2);
1665 } else if (bt2 != VT_FUNC) {
1666 invalid_operands:
1667 tcc_error("invalid operands to binary %s", get_tok_str(op, NULL));
1669 if ((type1->t & VT_BTYPE) == VT_VOID ||
1670 (type2->t & VT_BTYPE) == VT_VOID)
1671 return;
1672 tmp_type1 = *type1;
1673 tmp_type2 = *type2;
1674 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1675 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1676 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
1677 /* gcc-like error if '-' is used */
1678 if (op == '-')
1679 goto invalid_operands;
1680 else
1681 tcc_warning("comparison of distinct pointer types lacks a cast");
1685 /* generic gen_op: handles types problems */
1686 ST_FUNC void gen_op(int op)
1688 int u, t1, t2, bt1, bt2, t;
1689 CType type1;
1691 t1 = vtop[-1].type.t;
1692 t2 = vtop[0].type.t;
1693 bt1 = t1 & VT_BTYPE;
1694 bt2 = t2 & VT_BTYPE;
1696 if (bt1 == VT_PTR || bt2 == VT_PTR) {
1697 /* at least one operand is a pointer */
1698 /* relationnal op: must be both pointers */
1699 if (op >= TOK_ULT && op <= TOK_LOR) {
1700 check_comparison_pointer_types(vtop - 1, vtop, op);
1701 /* pointers are handled are unsigned */
1702 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1703 t = VT_LLONG | VT_UNSIGNED;
1704 #else
1705 t = VT_INT | VT_UNSIGNED;
1706 #endif
1707 goto std_op;
1709 /* if both pointers, then it must be the '-' op */
1710 if (bt1 == VT_PTR && bt2 == VT_PTR) {
1711 if (op != '-')
1712 tcc_error("cannot use pointers here");
1713 check_comparison_pointer_types(vtop - 1, vtop, op);
1714 /* XXX: check that types are compatible */
1715 if (vtop[-1].type.t & VT_VLA) {
1716 vla_runtime_pointed_size(&vtop[-1].type);
1717 } else {
1718 vpushi(pointed_size(&vtop[-1].type));
1720 vrott(3);
1721 gen_opic(op);
1722 /* set to integer type */
1723 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1724 vtop->type.t = VT_LLONG;
1725 #else
1726 vtop->type.t = VT_INT;
1727 #endif
1728 vswap();
1729 gen_op(TOK_PDIV);
1730 } else {
1731 /* exactly one pointer : must be '+' or '-'. */
1732 if (op != '-' && op != '+')
1733 tcc_error("cannot use pointers here");
1734 /* Put pointer as first operand */
1735 if (bt2 == VT_PTR) {
1736 vswap();
1737 swap(&t1, &t2);
1739 type1 = vtop[-1].type;
1740 type1.t &= ~VT_ARRAY;
1741 if (vtop[-1].type.t & VT_VLA)
1742 vla_runtime_pointed_size(&vtop[-1].type);
1743 else {
1744 u = pointed_size(&vtop[-1].type);
1745 if (u < 0)
1746 tcc_error("unknown array element size");
1747 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1748 vpushll(u);
1749 #else
1750 /* XXX: cast to int ? (long long case) */
1751 vpushi(u);
1752 #endif
1754 gen_op('*');
1755 #ifdef CONFIG_TCC_BCHECK
1756 /* if evaluating constant expression, no code should be
1757 generated, so no bound check */
1758 if (tcc_state->do_bounds_check && !const_wanted) {
1759 /* if bounded pointers, we generate a special code to
1760 test bounds */
1761 if (op == '-') {
1762 vpushi(0);
1763 vswap();
1764 gen_op('-');
1766 gen_bounded_ptr_add();
1767 } else
1768 #endif
1770 gen_opic(op);
1772 /* put again type if gen_opic() swaped operands */
1773 vtop->type = type1;
1775 } else if (is_float(bt1) || is_float(bt2)) {
1776 /* compute bigger type and do implicit casts */
1777 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
1778 t = VT_LDOUBLE;
1779 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
1780 t = VT_DOUBLE;
1781 } else {
1782 t = VT_FLOAT;
1784 /* floats can only be used for a few operations */
1785 if (op != '+' && op != '-' && op != '*' && op != '/' &&
1786 (op < TOK_ULT || op > TOK_GT))
1787 tcc_error("invalid operands for binary operation");
1788 goto std_op;
1789 } else if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL) {
1790 t = bt1 == VT_LLONG ? VT_LLONG : VT_INT;
1791 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (t | VT_UNSIGNED))
1792 t |= VT_UNSIGNED;
1793 goto std_op;
1794 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
1795 /* cast to biggest op */
1796 t = VT_LLONG;
1797 /* convert to unsigned if it does not fit in a long long */
1798 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
1799 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
1800 t |= VT_UNSIGNED;
1801 goto std_op;
1802 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
1803 tcc_error("comparison of struct");
1804 } else {
1805 /* integer operations */
1806 t = VT_INT;
1807 /* convert to unsigned if it does not fit in an integer */
1808 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
1809 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
1810 t |= VT_UNSIGNED;
1811 std_op:
1812 /* XXX: currently, some unsigned operations are explicit, so
1813 we modify them here */
1814 if (t & VT_UNSIGNED) {
1815 if (op == TOK_SAR)
1816 op = TOK_SHR;
1817 else if (op == '/')
1818 op = TOK_UDIV;
1819 else if (op == '%')
1820 op = TOK_UMOD;
1821 else if (op == TOK_LT)
1822 op = TOK_ULT;
1823 else if (op == TOK_GT)
1824 op = TOK_UGT;
1825 else if (op == TOK_LE)
1826 op = TOK_ULE;
1827 else if (op == TOK_GE)
1828 op = TOK_UGE;
1830 vswap();
1831 type1.t = t;
1832 gen_cast(&type1);
1833 vswap();
1834 /* special case for shifts and long long: we keep the shift as
1835 an integer */
1836 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
1837 type1.t = VT_INT;
1838 gen_cast(&type1);
1839 if (is_float(t))
1840 gen_opif(op);
1841 else
1842 gen_opic(op);
1843 if (op >= TOK_ULT && op <= TOK_GT) {
1844 /* relationnal op: the result is an int */
1845 vtop->type.t = VT_INT;
1846 } else {
1847 vtop->type.t = t;
1850 // Make sure that we have converted to an rvalue:
1851 if (vtop->r & VT_LVAL && !nocode_wanted)
1852 gv(is_float(vtop->type.t & VT_BTYPE) ? RC_FLOAT : RC_INT);
1855 #ifndef TCC_TARGET_ARM
1856 /* generic itof for unsigned long long case */
1857 static void gen_cvt_itof1(int t)
1859 #ifdef TCC_TARGET_ARM64
1860 gen_cvt_itof(t);
1861 #else
1862 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
1863 (VT_LLONG | VT_UNSIGNED)) {
1865 if (t == VT_FLOAT)
1866 vpush_global_sym(&func_old_type, TOK___floatundisf);
1867 #if LDOUBLE_SIZE != 8
1868 else if (t == VT_LDOUBLE)
1869 vpush_global_sym(&func_old_type, TOK___floatundixf);
1870 #endif
1871 else
1872 vpush_global_sym(&func_old_type, TOK___floatundidf);
1873 vrott(2);
1874 gfunc_call(1);
1875 vpushi(0);
1876 vtop->r = reg_fret(t);
1877 } else {
1878 gen_cvt_itof(t);
1880 #endif
1882 #endif
1884 /* generic ftoi for unsigned long long case */
1885 static void gen_cvt_ftoi1(int t)
1887 #ifdef TCC_TARGET_ARM64
1888 gen_cvt_ftoi(t);
1889 #else
1890 int st;
1892 if (t == (VT_LLONG | VT_UNSIGNED)) {
1893 /* not handled natively */
1894 st = vtop->type.t & VT_BTYPE;
1895 if (st == VT_FLOAT)
1896 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
1897 #if LDOUBLE_SIZE != 8
1898 else if (st == VT_LDOUBLE)
1899 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
1900 #endif
1901 else
1902 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
1903 vrott(2);
1904 gfunc_call(1);
1905 vpushi(0);
1906 vtop->r = REG_IRET;
1907 vtop->r2 = REG_LRET;
1908 } else {
1909 gen_cvt_ftoi(t);
1911 #endif
1914 /* force char or short cast */
1915 static void force_charshort_cast(int t)
1917 int bits, dbt;
1918 dbt = t & VT_BTYPE;
1919 /* XXX: add optimization if lvalue : just change type and offset */
1920 if (dbt == VT_BYTE)
1921 bits = 8;
1922 else
1923 bits = 16;
1924 if (t & VT_UNSIGNED) {
1925 vpushi((1 << bits) - 1);
1926 gen_op('&');
1927 } else {
1928 bits = 32 - bits;
1929 vpushi(bits);
1930 gen_op(TOK_SHL);
1931 /* result must be signed or the SAR is converted to an SHL
1932 This was not the case when "t" was a signed short
1933 and the last value on the stack was an unsigned int */
1934 vtop->type.t &= ~VT_UNSIGNED;
1935 vpushi(bits);
1936 gen_op(TOK_SAR);
1940 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
1941 static void gen_cast(CType *type)
1943 int sbt, dbt, sf, df, c, p;
1945 /* special delayed cast for char/short */
1946 /* XXX: in some cases (multiple cascaded casts), it may still
1947 be incorrect */
1948 if (vtop->r & VT_MUSTCAST) {
1949 vtop->r &= ~VT_MUSTCAST;
1950 force_charshort_cast(vtop->type.t);
1953 /* bitfields first get cast to ints */
1954 if (vtop->type.t & VT_BITFIELD && !nocode_wanted) {
1955 gv(RC_INT);
1958 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
1959 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
1961 if (sbt != dbt) {
1962 sf = is_float(sbt);
1963 df = is_float(dbt);
1964 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1965 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
1966 if (c) {
1967 /* constant case: we can do it now */
1968 /* XXX: in ISOC, cannot do it if error in convert */
1969 if (sbt == VT_FLOAT)
1970 vtop->c.ld = vtop->c.f;
1971 else if (sbt == VT_DOUBLE)
1972 vtop->c.ld = vtop->c.d;
1974 if (df) {
1975 if ((sbt & VT_BTYPE) == VT_LLONG) {
1976 if (sbt & VT_UNSIGNED)
1977 vtop->c.ld = vtop->c.ull;
1978 else
1979 vtop->c.ld = vtop->c.ll;
1980 } else if(!sf) {
1981 if (sbt & VT_UNSIGNED)
1982 vtop->c.ld = vtop->c.ui;
1983 else
1984 vtop->c.ld = vtop->c.i;
1987 if (dbt == VT_FLOAT)
1988 vtop->c.f = (float)vtop->c.ld;
1989 else if (dbt == VT_DOUBLE)
1990 vtop->c.d = (double)vtop->c.ld;
1991 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
1992 vtop->c.ull = (unsigned long long)vtop->c.ld;
1993 } else if (sf && dbt == VT_BOOL) {
1994 vtop->c.i = (vtop->c.ld != 0);
1995 } else {
1996 if(sf)
1997 vtop->c.ll = (long long)vtop->c.ld;
1998 else if (sbt == (VT_LLONG|VT_UNSIGNED))
1999 vtop->c.ll = vtop->c.ull;
2000 else if (sbt & VT_UNSIGNED)
2001 vtop->c.ll = vtop->c.ui;
2002 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2003 else if (sbt == VT_PTR)
2005 #endif
2006 else if (sbt != VT_LLONG)
2007 vtop->c.ll = vtop->c.i;
2009 if (dbt == (VT_LLONG|VT_UNSIGNED))
2010 vtop->c.ull = vtop->c.ll;
2011 else if (dbt == VT_BOOL)
2012 vtop->c.i = (vtop->c.ll != 0);
2013 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2014 else if (dbt == VT_PTR)
2016 #endif
2017 else if (dbt != VT_LLONG) {
2018 int s = 0;
2019 if ((dbt & VT_BTYPE) == VT_BYTE)
2020 s = 24;
2021 else if ((dbt & VT_BTYPE) == VT_SHORT)
2022 s = 16;
2023 if(dbt & VT_UNSIGNED)
2024 vtop->c.ui = ((unsigned int)vtop->c.ll << s) >> s;
2025 else
2026 vtop->c.i = ((int)vtop->c.ll << s) >> s;
2029 } else if (p && dbt == VT_BOOL) {
2030 vtop->r = VT_CONST;
2031 vtop->c.i = 1;
2032 } else if (!nocode_wanted) {
2033 /* non constant case: generate code */
2034 if (sf && df) {
2035 /* convert from fp to fp */
2036 gen_cvt_ftof(dbt);
2037 } else if (df) {
2038 /* convert int to fp */
2039 gen_cvt_itof1(dbt);
2040 } else if (sf) {
2041 /* convert fp to int */
2042 if (dbt == VT_BOOL) {
2043 vpushi(0);
2044 gen_op(TOK_NE);
2045 } else {
2046 /* we handle char/short/etc... with generic code */
2047 if (dbt != (VT_INT | VT_UNSIGNED) &&
2048 dbt != (VT_LLONG | VT_UNSIGNED) &&
2049 dbt != VT_LLONG)
2050 dbt = VT_INT;
2051 gen_cvt_ftoi1(dbt);
2052 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
2053 /* additional cast for char/short... */
2054 vtop->type.t = dbt;
2055 gen_cast(type);
2058 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
2059 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
2060 if ((sbt & VT_BTYPE) != VT_LLONG && !nocode_wanted) {
2061 /* scalar to long long */
2062 /* machine independent conversion */
2063 gv(RC_INT);
2064 /* generate high word */
2065 if (sbt == (VT_INT | VT_UNSIGNED)) {
2066 vpushi(0);
2067 gv(RC_INT);
2068 } else {
2069 if (sbt == VT_PTR) {
2070 /* cast from pointer to int before we apply
2071 shift operation, which pointers don't support*/
2072 gen_cast(&int_type);
2074 gv_dup();
2075 vpushi(31);
2076 gen_op(TOK_SAR);
2078 /* patch second register */
2079 vtop[-1].r2 = vtop->r;
2080 vpop();
2082 #else
2083 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
2084 (dbt & VT_BTYPE) == VT_PTR ||
2085 (dbt & VT_BTYPE) == VT_FUNC) {
2086 if ((sbt & VT_BTYPE) != VT_LLONG &&
2087 (sbt & VT_BTYPE) != VT_PTR &&
2088 (sbt & VT_BTYPE) != VT_FUNC && !nocode_wanted) {
2089 /* need to convert from 32bit to 64bit */
2090 gv(RC_INT);
2091 if (sbt != (VT_INT | VT_UNSIGNED)) {
2092 #if defined(TCC_TARGET_ARM64)
2093 gen_cvt_sxtw();
2094 #elif defined(TCC_TARGET_X86_64)
2095 int r = gv(RC_INT);
2096 /* x86_64 specific: movslq */
2097 o(0x6348);
2098 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
2099 #else
2100 #error
2101 #endif
2104 #endif
2105 } else if (dbt == VT_BOOL) {
2106 /* scalar to bool */
2107 vpushi(0);
2108 gen_op(TOK_NE);
2109 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
2110 (dbt & VT_BTYPE) == VT_SHORT) {
2111 if (sbt == VT_PTR) {
2112 vtop->type.t = VT_INT;
2113 tcc_warning("nonportable conversion from pointer to char/short");
2115 force_charshort_cast(dbt);
2116 } else if ((dbt & VT_BTYPE) == VT_INT) {
2117 /* scalar to int */
2118 if (sbt == VT_LLONG && !nocode_wanted) {
2119 /* from long long: just take low order word */
2120 lexpand();
2121 vpop();
2123 /* if lvalue and single word type, nothing to do because
2124 the lvalue already contains the real type size (see
2125 VT_LVAL_xxx constants) */
2128 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
2129 /* if we are casting between pointer types,
2130 we must update the VT_LVAL_xxx size */
2131 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
2132 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
2134 vtop->type = *type;
2137 /* return type size as known at compile time. Put alignment at 'a' */
2138 ST_FUNC int type_size(CType *type, int *a)
2140 Sym *s;
2141 int bt;
2143 bt = type->t & VT_BTYPE;
2144 if (bt == VT_STRUCT) {
2145 /* struct/union */
2146 s = type->ref;
2147 *a = s->r;
2148 return s->c;
2149 } else if (bt == VT_PTR) {
2150 if (type->t & VT_ARRAY) {
2151 int ts;
2153 s = type->ref;
2154 ts = type_size(&s->type, a);
2156 if (ts < 0 && s->c < 0)
2157 ts = -ts;
2159 return ts * s->c;
2160 } else {
2161 *a = PTR_SIZE;
2162 return PTR_SIZE;
2164 } else if (bt == VT_LDOUBLE) {
2165 *a = LDOUBLE_ALIGN;
2166 return LDOUBLE_SIZE;
2167 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
2168 #ifdef TCC_TARGET_I386
2169 #ifdef TCC_TARGET_PE
2170 *a = 8;
2171 #else
2172 *a = 4;
2173 #endif
2174 #elif defined(TCC_TARGET_ARM)
2175 #ifdef TCC_ARM_EABI
2176 *a = 8;
2177 #else
2178 *a = 4;
2179 #endif
2180 #else
2181 *a = 8;
2182 #endif
2183 return 8;
2184 } else if (bt == VT_INT || bt == VT_ENUM || bt == VT_FLOAT) {
2185 *a = 4;
2186 return 4;
2187 } else if (bt == VT_SHORT) {
2188 *a = 2;
2189 return 2;
2190 } else if (bt == VT_QLONG || bt == VT_QFLOAT) {
2191 *a = 8;
2192 return 16;
2193 } else {
2194 /* char, void, function, _Bool */
2195 *a = 1;
2196 return 1;
2200 /* push type size as known at runtime time on top of value stack. Put
2201 alignment at 'a' */
2202 ST_FUNC void vla_runtime_type_size(CType *type, int *a)
2204 if (type->t & VT_VLA) {
2205 vset(&int_type, VT_LOCAL|VT_LVAL, type->ref->c);
2206 } else {
2207 vpushi(type_size(type, a));
2211 static void vla_sp_save(void) {
2212 if (!(vla_flags & VLA_SP_LOC_SET)) {
2213 *vla_sp_loc = (loc -= PTR_SIZE);
2214 vla_flags |= VLA_SP_LOC_SET;
2216 if (!(vla_flags & VLA_SP_SAVED)) {
2217 gen_vla_sp_save(*vla_sp_loc);
2218 vla_flags |= VLA_SP_SAVED;
2222 /* return the pointed type of t */
2223 static inline CType *pointed_type(CType *type)
2225 return &type->ref->type;
2228 /* modify type so that its it is a pointer to type. */
2229 ST_FUNC void mk_pointer(CType *type)
2231 Sym *s;
2232 s = sym_push(SYM_FIELD, type, 0, -1);
2233 type->t = VT_PTR | (type->t & ~VT_TYPE);
2234 type->ref = s;
2237 /* compare function types. OLD functions match any new functions */
2238 static int is_compatible_func(CType *type1, CType *type2)
2240 Sym *s1, *s2;
2242 s1 = type1->ref;
2243 s2 = type2->ref;
2244 if (!is_compatible_types(&s1->type, &s2->type))
2245 return 0;
2246 /* check func_call */
2247 if (s1->a.func_call != s2->a.func_call)
2248 return 0;
2249 /* XXX: not complete */
2250 if (s1->c == FUNC_OLD || s2->c == FUNC_OLD)
2251 return 1;
2252 if (s1->c != s2->c)
2253 return 0;
2254 while (s1 != NULL) {
2255 if (s2 == NULL)
2256 return 0;
2257 if (!is_compatible_parameter_types(&s1->type, &s2->type))
2258 return 0;
2259 s1 = s1->next;
2260 s2 = s2->next;
2262 if (s2)
2263 return 0;
2264 return 1;
2267 /* return true if type1 and type2 are the same. If unqualified is
2268 true, qualifiers on the types are ignored.
2270 - enums are not checked as gcc __builtin_types_compatible_p ()
2272 static int compare_types(CType *type1, CType *type2, int unqualified)
2274 int bt1, t1, t2;
2276 t1 = type1->t & VT_TYPE;
2277 t2 = type2->t & VT_TYPE;
2278 if (unqualified) {
2279 /* strip qualifiers before comparing */
2280 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
2281 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
2283 /* Default Vs explicit signedness only matters for char */
2284 if ((t1 & VT_BTYPE) != VT_BYTE) {
2285 t1 &= ~VT_DEFSIGN;
2286 t2 &= ~VT_DEFSIGN;
2288 /* XXX: bitfields ? */
2289 if (t1 != t2)
2290 return 0;
2291 /* test more complicated cases */
2292 bt1 = t1 & VT_BTYPE;
2293 if (bt1 == VT_PTR) {
2294 type1 = pointed_type(type1);
2295 type2 = pointed_type(type2);
2296 return is_compatible_types(type1, type2);
2297 } else if (bt1 == VT_STRUCT) {
2298 return (type1->ref == type2->ref);
2299 } else if (bt1 == VT_FUNC) {
2300 return is_compatible_func(type1, type2);
2301 } else {
2302 return 1;
2306 /* return true if type1 and type2 are exactly the same (including
2307 qualifiers).
2309 static int is_compatible_types(CType *type1, CType *type2)
2311 return compare_types(type1,type2,0);
2314 /* return true if type1 and type2 are the same (ignoring qualifiers).
2316 static int is_compatible_parameter_types(CType *type1, CType *type2)
2318 return compare_types(type1,type2,1);
2321 /* print a type. If 'varstr' is not NULL, then the variable is also
2322 printed in the type */
2323 /* XXX: union */
2324 /* XXX: add array and function pointers */
2325 static void type_to_str(char *buf, int buf_size,
2326 CType *type, const char *varstr)
2328 int bt, v, t;
2329 Sym *s, *sa;
2330 char buf1[256];
2331 const char *tstr;
2333 t = type->t & VT_TYPE;
2334 bt = t & VT_BTYPE;
2335 buf[0] = '\0';
2336 if (t & VT_CONSTANT)
2337 pstrcat(buf, buf_size, "const ");
2338 if (t & VT_VOLATILE)
2339 pstrcat(buf, buf_size, "volatile ");
2340 if ((t & (VT_DEFSIGN | VT_UNSIGNED)) == (VT_DEFSIGN | VT_UNSIGNED))
2341 pstrcat(buf, buf_size, "unsigned ");
2342 else if (t & VT_DEFSIGN)
2343 pstrcat(buf, buf_size, "signed ");
2344 switch(bt) {
2345 case VT_VOID:
2346 tstr = "void";
2347 goto add_tstr;
2348 case VT_BOOL:
2349 tstr = "_Bool";
2350 goto add_tstr;
2351 case VT_BYTE:
2352 tstr = "char";
2353 goto add_tstr;
2354 case VT_SHORT:
2355 tstr = "short";
2356 goto add_tstr;
2357 case VT_INT:
2358 tstr = "int";
2359 goto add_tstr;
2360 case VT_LONG:
2361 tstr = "long";
2362 goto add_tstr;
2363 case VT_LLONG:
2364 tstr = "long long";
2365 goto add_tstr;
2366 case VT_FLOAT:
2367 tstr = "float";
2368 goto add_tstr;
2369 case VT_DOUBLE:
2370 tstr = "double";
2371 goto add_tstr;
2372 case VT_LDOUBLE:
2373 tstr = "long double";
2374 add_tstr:
2375 pstrcat(buf, buf_size, tstr);
2376 break;
2377 case VT_ENUM:
2378 case VT_STRUCT:
2379 if (bt == VT_STRUCT)
2380 tstr = "struct ";
2381 else
2382 tstr = "enum ";
2383 pstrcat(buf, buf_size, tstr);
2384 v = type->ref->v & ~SYM_STRUCT;
2385 if (v >= SYM_FIRST_ANOM)
2386 pstrcat(buf, buf_size, "<anonymous>");
2387 else
2388 pstrcat(buf, buf_size, get_tok_str(v, NULL));
2389 break;
2390 case VT_FUNC:
2391 s = type->ref;
2392 type_to_str(buf, buf_size, &s->type, varstr);
2393 pstrcat(buf, buf_size, "(");
2394 sa = s->next;
2395 while (sa != NULL) {
2396 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
2397 pstrcat(buf, buf_size, buf1);
2398 sa = sa->next;
2399 if (sa)
2400 pstrcat(buf, buf_size, ", ");
2402 pstrcat(buf, buf_size, ")");
2403 goto no_var;
2404 case VT_PTR:
2405 s = type->ref;
2406 pstrcpy(buf1, sizeof(buf1), "*");
2407 if (varstr)
2408 pstrcat(buf1, sizeof(buf1), varstr);
2409 type_to_str(buf, buf_size, &s->type, buf1);
2410 goto no_var;
2412 if (varstr) {
2413 pstrcat(buf, buf_size, " ");
2414 pstrcat(buf, buf_size, varstr);
2416 no_var: ;
2419 /* verify type compatibility to store vtop in 'dt' type, and generate
2420 casts if needed. */
2421 static void gen_assign_cast(CType *dt)
2423 CType *st, *type1, *type2, tmp_type1, tmp_type2;
2424 char buf1[256], buf2[256];
2425 int dbt, sbt;
2427 st = &vtop->type; /* source type */
2428 dbt = dt->t & VT_BTYPE;
2429 sbt = st->t & VT_BTYPE;
2430 if (sbt == VT_VOID || dbt == VT_VOID) {
2431 if (sbt == VT_VOID && dbt == VT_VOID)
2432 ; /*
2433 It is Ok if both are void
2434 A test program:
2435 void func1() {}
2436 void func2() {
2437 return func1();
2439 gcc accepts this program
2441 else
2442 tcc_error("cannot cast from/to void");
2444 if (dt->t & VT_CONSTANT)
2445 tcc_warning("assignment of read-only location");
2446 switch(dbt) {
2447 case VT_PTR:
2448 /* special cases for pointers */
2449 /* '0' can also be a pointer */
2450 if (is_null_pointer(vtop))
2451 goto type_ok;
2452 /* accept implicit pointer to integer cast with warning */
2453 if (is_integer_btype(sbt)) {
2454 tcc_warning("assignment makes pointer from integer without a cast");
2455 goto type_ok;
2457 type1 = pointed_type(dt);
2458 /* a function is implicitely a function pointer */
2459 if (sbt == VT_FUNC) {
2460 if ((type1->t & VT_BTYPE) != VT_VOID &&
2461 !is_compatible_types(pointed_type(dt), st))
2462 tcc_warning("assignment from incompatible pointer type");
2463 goto type_ok;
2465 if (sbt != VT_PTR)
2466 goto error;
2467 type2 = pointed_type(st);
2468 if ((type1->t & VT_BTYPE) == VT_VOID ||
2469 (type2->t & VT_BTYPE) == VT_VOID) {
2470 /* void * can match anything */
2471 } else {
2472 /* exact type match, except for unsigned */
2473 tmp_type1 = *type1;
2474 tmp_type2 = *type2;
2475 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT |
2476 VT_VOLATILE);
2477 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT |
2478 VT_VOLATILE);
2479 if (!is_compatible_types(&tmp_type1, &tmp_type2))
2480 tcc_warning("assignment from incompatible pointer type");
2482 /* check const and volatile */
2483 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
2484 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
2485 tcc_warning("assignment discards qualifiers from pointer target type");
2486 break;
2487 case VT_BYTE:
2488 case VT_SHORT:
2489 case VT_INT:
2490 case VT_LLONG:
2491 if (sbt == VT_PTR || sbt == VT_FUNC) {
2492 tcc_warning("assignment makes integer from pointer without a cast");
2494 /* XXX: more tests */
2495 break;
2496 case VT_STRUCT:
2497 tmp_type1 = *dt;
2498 tmp_type2 = *st;
2499 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2500 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2501 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2502 error:
2503 type_to_str(buf1, sizeof(buf1), st, NULL);
2504 type_to_str(buf2, sizeof(buf2), dt, NULL);
2505 tcc_error("cannot cast '%s' to '%s'", buf1, buf2);
2507 break;
2509 type_ok:
2510 gen_cast(dt);
2513 /* store vtop in lvalue pushed on stack */
2514 ST_FUNC void vstore(void)
2516 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
2518 ft = vtop[-1].type.t;
2519 sbt = vtop->type.t & VT_BTYPE;
2520 dbt = ft & VT_BTYPE;
2521 if ((((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
2522 (sbt == VT_INT && dbt == VT_SHORT))
2523 && !(vtop->type.t & VT_BITFIELD)) {
2524 /* optimize char/short casts */
2525 delayed_cast = VT_MUSTCAST;
2526 vtop->type.t = ft & (VT_TYPE & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT)));
2527 /* XXX: factorize */
2528 if (ft & VT_CONSTANT)
2529 tcc_warning("assignment of read-only location");
2530 } else {
2531 delayed_cast = 0;
2532 if (!(ft & VT_BITFIELD))
2533 gen_assign_cast(&vtop[-1].type);
2536 if (sbt == VT_STRUCT) {
2537 /* if structure, only generate pointer */
2538 /* structure assignment : generate memcpy */
2539 /* XXX: optimize if small size */
2540 if (!nocode_wanted) {
2541 size = type_size(&vtop->type, &align);
2543 /* destination */
2544 vswap();
2545 vtop->type.t = VT_PTR;
2546 gaddrof();
2548 /* address of memcpy() */
2549 #ifdef TCC_ARM_EABI
2550 if(!(align & 7))
2551 vpush_global_sym(&func_old_type, TOK_memcpy8);
2552 else if(!(align & 3))
2553 vpush_global_sym(&func_old_type, TOK_memcpy4);
2554 else
2555 #endif
2556 vpush_global_sym(&func_old_type, TOK_memcpy);
2558 vswap();
2559 /* source */
2560 vpushv(vtop - 2);
2561 vtop->type.t = VT_PTR;
2562 gaddrof();
2563 /* type size */
2564 vpushi(size);
2565 gfunc_call(3);
2566 } else {
2567 vswap();
2568 vpop();
2570 /* leave source on stack */
2571 } else if (ft & VT_BITFIELD) {
2572 /* bitfield store handling */
2574 /* save lvalue as expression result (example: s.b = s.a = n;) */
2575 vdup(), vtop[-1] = vtop[-2];
2577 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
2578 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
2579 /* remove bit field info to avoid loops */
2580 vtop[-1].type.t = ft & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
2582 if((ft & VT_BTYPE) == VT_BOOL) {
2583 gen_cast(&vtop[-1].type);
2584 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
2587 /* duplicate destination */
2588 vdup();
2589 vtop[-1] = vtop[-2];
2591 /* mask and shift source */
2592 if((ft & VT_BTYPE) != VT_BOOL) {
2593 if((ft & VT_BTYPE) == VT_LLONG) {
2594 vpushll((1ULL << bit_size) - 1ULL);
2595 } else {
2596 vpushi((1 << bit_size) - 1);
2598 gen_op('&');
2600 vpushi(bit_pos);
2601 gen_op(TOK_SHL);
2602 /* load destination, mask and or with source */
2603 vswap();
2604 if((ft & VT_BTYPE) == VT_LLONG) {
2605 vpushll(~(((1ULL << bit_size) - 1ULL) << bit_pos));
2606 } else {
2607 vpushi(~(((1 << bit_size) - 1) << bit_pos));
2609 gen_op('&');
2610 gen_op('|');
2611 /* store result */
2612 vstore();
2613 /* ... and discard */
2614 vpop();
2616 } else {
2617 if (!nocode_wanted) {
2618 #ifdef CONFIG_TCC_BCHECK
2619 /* bound check case */
2620 if (vtop[-1].r & VT_MUSTBOUND) {
2621 vswap();
2622 gbound();
2623 vswap();
2625 #endif
2626 rc = RC_INT;
2627 if (is_float(ft)) {
2628 rc = RC_FLOAT;
2629 #ifdef TCC_TARGET_X86_64
2630 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
2631 rc = RC_ST0;
2632 } else if ((ft & VT_BTYPE) == VT_QFLOAT) {
2633 rc = RC_FRET;
2635 #endif
2637 r = gv(rc); /* generate value */
2638 /* if lvalue was saved on stack, must read it */
2639 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
2640 SValue sv;
2641 t = get_reg(RC_INT);
2642 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2643 sv.type.t = VT_PTR;
2644 #else
2645 sv.type.t = VT_INT;
2646 #endif
2647 sv.r = VT_LOCAL | VT_LVAL;
2648 sv.c.ul = vtop[-1].c.ul;
2649 load(t, &sv);
2650 vtop[-1].r = t | VT_LVAL;
2652 /* two word case handling : store second register at word + 4 (or +8 for x86-64) */
2653 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2654 if (((ft & VT_BTYPE) == VT_QLONG) || ((ft & VT_BTYPE) == VT_QFLOAT)) {
2655 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
2656 #else
2657 if ((ft & VT_BTYPE) == VT_LLONG) {
2658 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
2659 #endif
2660 vtop[-1].type.t = load_type;
2661 store(r, vtop - 1);
2662 vswap();
2663 /* convert to int to increment easily */
2664 vtop->type.t = addr_type;
2665 gaddrof();
2666 vpushi(load_size);
2667 gen_op('+');
2668 vtop->r |= VT_LVAL;
2669 vswap();
2670 vtop[-1].type.t = load_type;
2671 /* XXX: it works because r2 is spilled last ! */
2672 store(vtop->r2, vtop - 1);
2673 } else {
2674 store(r, vtop - 1);
2677 vswap();
2678 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
2679 vtop->r |= delayed_cast;
2683 /* post defines POST/PRE add. c is the token ++ or -- */
2684 ST_FUNC void inc(int post, int c)
2686 test_lvalue();
2687 vdup(); /* save lvalue */
2688 if (post) {
2689 if (!nocode_wanted)
2690 gv_dup(); /* duplicate value */
2691 else
2692 vdup(); /* duplicate value */
2693 vrotb(3);
2694 vrotb(3);
2696 /* add constant */
2697 vpushi(c - TOK_MID);
2698 gen_op('+');
2699 vstore(); /* store value */
2700 if (post)
2701 vpop(); /* if post op, return saved value */
2704 /* Parse GNUC __attribute__ extension. Currently, the following
2705 extensions are recognized:
2706 - aligned(n) : set data/function alignment.
2707 - packed : force data alignment to 1
2708 - section(x) : generate data/code in this section.
2709 - unused : currently ignored, but may be used someday.
2710 - regparm(n) : pass function parameters in registers (i386 only)
2712 static void parse_attribute(AttributeDef *ad)
2714 int t, n;
2716 while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
2717 next();
2718 skip('(');
2719 skip('(');
2720 while (tok != ')') {
2721 if (tok < TOK_IDENT)
2722 expect("attribute name");
2723 t = tok;
2724 next();
2725 switch(t) {
2726 case TOK_SECTION1:
2727 case TOK_SECTION2:
2728 skip('(');
2729 if (tok != TOK_STR)
2730 expect("section name");
2731 ad->section = find_section(tcc_state, (char *)tokc.cstr->data);
2732 next();
2733 skip(')');
2734 break;
2735 case TOK_ALIAS1:
2736 case TOK_ALIAS2:
2737 skip('(');
2738 if (tok != TOK_STR)
2739 expect("alias(\"target\")");
2740 ad->alias_target = /* save string as token, for later */
2741 tok_alloc((char*)tokc.cstr->data, tokc.cstr->size-1)->tok;
2742 next();
2743 skip(')');
2744 break;
2745 case TOK_VISIBILITY1:
2746 case TOK_VISIBILITY2:
2747 skip('(');
2748 if (tok != TOK_STR)
2749 expect("visibility(\"default|hidden|internal|protected\")");
2750 if (!strcmp (tokc.cstr->data, "default"))
2751 ad->a.visibility = STV_DEFAULT;
2752 else if (!strcmp (tokc.cstr->data, "hidden"))
2753 ad->a.visibility = STV_HIDDEN;
2754 else if (!strcmp (tokc.cstr->data, "internal"))
2755 ad->a.visibility = STV_INTERNAL;
2756 else if (!strcmp (tokc.cstr->data, "protected"))
2757 ad->a.visibility = STV_PROTECTED;
2758 else
2759 expect("visibility(\"default|hidden|internal|protected\")");
2760 next();
2761 skip(')');
2762 break;
2763 case TOK_ALIGNED1:
2764 case TOK_ALIGNED2:
2765 if (tok == '(') {
2766 next();
2767 n = expr_const();
2768 if (n <= 0 || (n & (n - 1)) != 0)
2769 tcc_error("alignment must be a positive power of two");
2770 skip(')');
2771 } else {
2772 n = MAX_ALIGN;
2774 ad->a.aligned = n;
2775 break;
2776 case TOK_PACKED1:
2777 case TOK_PACKED2:
2778 ad->a.packed = 1;
2779 break;
2780 case TOK_WEAK1:
2781 case TOK_WEAK2:
2782 ad->a.weak = 1;
2783 break;
2784 case TOK_UNUSED1:
2785 case TOK_UNUSED2:
2786 /* currently, no need to handle it because tcc does not
2787 track unused objects */
2788 break;
2789 case TOK_NORETURN1:
2790 case TOK_NORETURN2:
2791 /* currently, no need to handle it because tcc does not
2792 track unused objects */
2793 break;
2794 case TOK_CDECL1:
2795 case TOK_CDECL2:
2796 case TOK_CDECL3:
2797 ad->a.func_call = FUNC_CDECL;
2798 break;
2799 case TOK_STDCALL1:
2800 case TOK_STDCALL2:
2801 case TOK_STDCALL3:
2802 ad->a.func_call = FUNC_STDCALL;
2803 break;
2804 #ifdef TCC_TARGET_I386
2805 case TOK_REGPARM1:
2806 case TOK_REGPARM2:
2807 skip('(');
2808 n = expr_const();
2809 if (n > 3)
2810 n = 3;
2811 else if (n < 0)
2812 n = 0;
2813 if (n > 0)
2814 ad->a.func_call = FUNC_FASTCALL1 + n - 1;
2815 skip(')');
2816 break;
2817 case TOK_FASTCALL1:
2818 case TOK_FASTCALL2:
2819 case TOK_FASTCALL3:
2820 ad->a.func_call = FUNC_FASTCALLW;
2821 break;
2822 #endif
2823 case TOK_MODE:
2824 skip('(');
2825 switch(tok) {
2826 case TOK_MODE_DI:
2827 ad->a.mode = VT_LLONG + 1;
2828 break;
2829 case TOK_MODE_HI:
2830 ad->a.mode = VT_SHORT + 1;
2831 break;
2832 case TOK_MODE_SI:
2833 ad->a.mode = VT_INT + 1;
2834 break;
2835 default:
2836 tcc_warning("__mode__(%s) not supported\n", get_tok_str(tok, NULL));
2837 break;
2839 next();
2840 skip(')');
2841 break;
2842 case TOK_DLLEXPORT:
2843 ad->a.func_export = 1;
2844 break;
2845 case TOK_DLLIMPORT:
2846 ad->a.func_import = 1;
2847 break;
2848 default:
2849 if (tcc_state->warn_unsupported)
2850 tcc_warning("'%s' attribute ignored", get_tok_str(t, NULL));
2851 /* skip parameters */
2852 if (tok == '(') {
2853 int parenthesis = 0;
2854 do {
2855 if (tok == '(')
2856 parenthesis++;
2857 else if (tok == ')')
2858 parenthesis--;
2859 next();
2860 } while (parenthesis && tok != -1);
2862 break;
2864 if (tok != ',')
2865 break;
2866 next();
2868 skip(')');
2869 skip(')');
2873 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
2874 static void struct_decl(CType *type, int u, int tdef)
2876 int a, v, size, align, maxalign, c, offset, flexible;
2877 int bit_size, bit_pos, bsize, bt, lbit_pos, prevbt;
2878 Sym *s, *ss, *ass, **ps;
2879 AttributeDef ad;
2880 CType type1, btype;
2882 a = tok; /* save decl type */
2883 next();
2884 if (tok != '{') {
2885 v = tok;
2886 next();
2887 /* struct already defined ? return it */
2888 if (v < TOK_IDENT)
2889 expect("struct/union/enum name");
2890 s = struct_find(v);
2891 if (s) {
2892 if (s->type.t != a)
2893 tcc_error("invalid type");
2894 goto do_decl;
2895 } else if (tok >= TOK_IDENT && !tdef)
2896 tcc_error("unknown struct/union/enum");
2897 } else {
2898 v = anon_sym++;
2900 type1.t = a;
2901 type1.ref = NULL;
2902 /* we put an undefined size for struct/union */
2903 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
2904 s->r = 0; /* default alignment is zero as gcc */
2905 /* put struct/union/enum name in type */
2906 do_decl:
2907 type->t = u;
2908 type->ref = s;
2910 if (tok == '{') {
2911 next();
2912 if (s->c != -1)
2913 tcc_error("struct/union/enum already defined");
2914 /* cannot be empty */
2915 c = 0;
2916 /* non empty enums are not allowed */
2917 if (a == TOK_ENUM) {
2918 for(;;) {
2919 v = tok;
2920 if (v < TOK_UIDENT)
2921 expect("identifier");
2922 ss = sym_find(v);
2923 if (ss && !local_stack)
2924 tcc_error("redefinition of enumerator '%s'",
2925 get_tok_str(v, NULL));
2926 next();
2927 if (tok == '=') {
2928 next();
2929 c = expr_const();
2931 /* enum symbols have static storage */
2932 ss = sym_push(v, &int_type, VT_CONST, c);
2933 ss->type.t |= VT_STATIC;
2934 if (tok != ',')
2935 break;
2936 next();
2937 c++;
2938 /* NOTE: we accept a trailing comma */
2939 if (tok == '}')
2940 break;
2942 s->c = type_size(&int_type, &align);
2943 skip('}');
2944 } else {
2945 maxalign = 1;
2946 ps = &s->next;
2947 prevbt = VT_INT;
2948 bit_pos = 0;
2949 offset = 0;
2950 flexible = 0;
2951 while (tok != '}') {
2952 parse_btype(&btype, &ad);
2953 while (1) {
2954 if (flexible)
2955 tcc_error("flexible array member '%s' not at the end of struct",
2956 get_tok_str(v, NULL));
2957 bit_size = -1;
2958 v = 0;
2959 type1 = btype;
2960 if (tok != ':') {
2961 type_decl(&type1, &ad, &v, TYPE_DIRECT | TYPE_ABSTRACT);
2962 if (v == 0) {
2963 if ((type1.t & VT_BTYPE) != VT_STRUCT)
2964 expect("identifier");
2965 else {
2966 int v = btype.ref->v;
2967 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
2968 if (tcc_state->ms_extensions == 0)
2969 expect("identifier");
2973 if (type_size(&type1, &align) < 0) {
2974 if ((a == TOK_STRUCT) && (type1.t & VT_ARRAY) && c)
2975 flexible = 1;
2976 else
2977 tcc_error("field '%s' has incomplete type",
2978 get_tok_str(v, NULL));
2980 if ((type1.t & VT_BTYPE) == VT_FUNC ||
2981 (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
2982 tcc_error("invalid type for '%s'",
2983 get_tok_str(v, NULL));
2985 if (tok == ':') {
2986 next();
2987 bit_size = expr_const();
2988 /* XXX: handle v = 0 case for messages */
2989 if (bit_size < 0)
2990 tcc_error("negative width in bit-field '%s'",
2991 get_tok_str(v, NULL));
2992 if (v && bit_size == 0)
2993 tcc_error("zero width for bit-field '%s'",
2994 get_tok_str(v, NULL));
2996 size = type_size(&type1, &align);
2997 if (ad.a.aligned) {
2998 if (align < ad.a.aligned)
2999 align = ad.a.aligned;
3000 } else if (ad.a.packed) {
3001 align = 1;
3002 } else if (*tcc_state->pack_stack_ptr) {
3003 if (align > *tcc_state->pack_stack_ptr)
3004 align = *tcc_state->pack_stack_ptr;
3006 lbit_pos = 0;
3007 if (bit_size >= 0) {
3008 bt = type1.t & VT_BTYPE;
3009 if (bt != VT_INT &&
3010 bt != VT_BYTE &&
3011 bt != VT_SHORT &&
3012 bt != VT_BOOL &&
3013 bt != VT_ENUM &&
3014 bt != VT_LLONG)
3015 tcc_error("bitfields must have scalar type");
3016 bsize = size * 8;
3017 if (bit_size > bsize) {
3018 tcc_error("width of '%s' exceeds its type",
3019 get_tok_str(v, NULL));
3020 } else if (bit_size == bsize) {
3021 /* no need for bit fields */
3022 bit_pos = 0;
3023 } else if (bit_size == 0) {
3024 /* XXX: what to do if only padding in a
3025 structure ? */
3026 /* zero size: means to pad */
3027 bit_pos = 0;
3028 } else {
3029 /* we do not have enough room ?
3030 did the type change?
3031 is it a union? */
3032 if ((bit_pos + bit_size) > bsize ||
3033 bt != prevbt || a == TOK_UNION)
3034 bit_pos = 0;
3035 lbit_pos = bit_pos;
3036 /* XXX: handle LSB first */
3037 type1.t |= VT_BITFIELD |
3038 (bit_pos << VT_STRUCT_SHIFT) |
3039 (bit_size << (VT_STRUCT_SHIFT + 6));
3040 bit_pos += bit_size;
3042 prevbt = bt;
3043 } else {
3044 bit_pos = 0;
3046 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
3047 /* add new memory data only if starting
3048 bit field */
3049 if (lbit_pos == 0) {
3050 if (a == TOK_STRUCT) {
3051 c = (c + align - 1) & -align;
3052 offset = c;
3053 if (size > 0)
3054 c += size;
3055 } else {
3056 offset = 0;
3057 if (size > c)
3058 c = size;
3060 if (align > maxalign)
3061 maxalign = align;
3063 #if 0
3064 printf("add field %s offset=%d",
3065 get_tok_str(v, NULL), offset);
3066 if (type1.t & VT_BITFIELD) {
3067 printf(" pos=%d size=%d",
3068 (type1.t >> VT_STRUCT_SHIFT) & 0x3f,
3069 (type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
3071 printf("\n");
3072 #endif
3074 if (v == 0 && (type1.t & VT_BTYPE) == VT_STRUCT) {
3075 ass = type1.ref;
3076 while ((ass = ass->next) != NULL) {
3077 ss = sym_push(ass->v, &ass->type, 0, offset + ass->c);
3078 *ps = ss;
3079 ps = &ss->next;
3081 } else if (v) {
3082 ss = sym_push(v | SYM_FIELD, &type1, 0, offset);
3083 *ps = ss;
3084 ps = &ss->next;
3086 if (tok == ';' || tok == TOK_EOF)
3087 break;
3088 skip(',');
3090 skip(';');
3092 skip('}');
3093 /* store size and alignment */
3094 s->c = (c + maxalign - 1) & -maxalign;
3095 s->r = maxalign;
3100 /* return 1 if basic type is a type size (short, long, long long) */
3101 ST_FUNC int is_btype_size(int bt)
3103 return bt == VT_SHORT || bt == VT_LONG || bt == VT_LLONG;
3106 /* return 0 if no type declaration. otherwise, return the basic type
3107 and skip it.
3109 static int parse_btype(CType *type, AttributeDef *ad)
3111 int t, u, bt_size, complete, type_found, typespec_found;
3112 Sym *s;
3113 CType type1;
3115 memset(ad, 0, sizeof(AttributeDef));
3116 complete = 0;
3117 type_found = 0;
3118 typespec_found = 0;
3119 t = 0;
3120 while(1) {
3121 switch(tok) {
3122 case TOK_EXTENSION:
3123 /* currently, we really ignore extension */
3124 next();
3125 continue;
3127 /* basic types */
3128 case TOK_CHAR:
3129 u = VT_BYTE;
3130 basic_type:
3131 next();
3132 basic_type1:
3133 if (complete)
3134 tcc_error("too many basic types");
3135 t |= u;
3136 bt_size = is_btype_size (u & VT_BTYPE);
3137 if (u == VT_INT || (!bt_size && !(t & VT_TYPEDEF)))
3138 complete = 1;
3139 typespec_found = 1;
3140 break;
3141 case TOK_VOID:
3142 u = VT_VOID;
3143 goto basic_type;
3144 case TOK_SHORT:
3145 u = VT_SHORT;
3146 goto basic_type;
3147 case TOK_INT:
3148 u = VT_INT;
3149 goto basic_type;
3150 case TOK_LONG:
3151 next();
3152 if ((t & VT_BTYPE) == VT_DOUBLE) {
3153 #ifndef TCC_TARGET_PE
3154 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3155 #endif
3156 } else if ((t & VT_BTYPE) == VT_LONG) {
3157 t = (t & ~VT_BTYPE) | VT_LLONG;
3158 } else {
3159 u = VT_LONG;
3160 goto basic_type1;
3162 break;
3163 #ifdef TCC_TARGET_ARM64
3164 case TOK_UINT128:
3165 /* GCC's __uint128_t appears in some Linux header files. Make it a
3166 synonym for long double to get the size and alignment right. */
3167 u = VT_LDOUBLE;
3168 goto basic_type;
3169 #endif
3170 case TOK_BOOL:
3171 u = VT_BOOL;
3172 goto basic_type;
3173 case TOK_FLOAT:
3174 u = VT_FLOAT;
3175 goto basic_type;
3176 case TOK_DOUBLE:
3177 next();
3178 if ((t & VT_BTYPE) == VT_LONG) {
3179 #ifdef TCC_TARGET_PE
3180 t = (t & ~VT_BTYPE) | VT_DOUBLE;
3181 #else
3182 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3183 #endif
3184 } else {
3185 u = VT_DOUBLE;
3186 goto basic_type1;
3188 break;
3189 case TOK_ENUM:
3190 struct_decl(&type1, VT_ENUM, t & (VT_TYPEDEF | VT_EXTERN));
3191 basic_type2:
3192 u = type1.t;
3193 type->ref = type1.ref;
3194 goto basic_type1;
3195 case TOK_STRUCT:
3196 case TOK_UNION:
3197 struct_decl(&type1, VT_STRUCT, t & (VT_TYPEDEF | VT_EXTERN));
3198 goto basic_type2;
3200 /* type modifiers */
3201 case TOK_CONST1:
3202 case TOK_CONST2:
3203 case TOK_CONST3:
3204 t |= VT_CONSTANT;
3205 next();
3206 break;
3207 case TOK_VOLATILE1:
3208 case TOK_VOLATILE2:
3209 case TOK_VOLATILE3:
3210 t |= VT_VOLATILE;
3211 next();
3212 break;
3213 case TOK_SIGNED1:
3214 case TOK_SIGNED2:
3215 case TOK_SIGNED3:
3216 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == (VT_DEFSIGN|VT_UNSIGNED))
3217 tcc_error("signed and unsigned modifier");
3218 typespec_found = 1;
3219 t |= VT_DEFSIGN;
3220 next();
3221 break;
3222 case TOK_REGISTER:
3223 case TOK_AUTO:
3224 case TOK_RESTRICT1:
3225 case TOK_RESTRICT2:
3226 case TOK_RESTRICT3:
3227 next();
3228 break;
3229 case TOK_UNSIGNED:
3230 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == VT_DEFSIGN)
3231 tcc_error("signed and unsigned modifier");
3232 t |= VT_DEFSIGN | VT_UNSIGNED;
3233 next();
3234 typespec_found = 1;
3235 break;
3237 /* storage */
3238 case TOK_EXTERN:
3239 t |= VT_EXTERN;
3240 next();
3241 break;
3242 case TOK_STATIC:
3243 t |= VT_STATIC;
3244 next();
3245 break;
3246 case TOK_TYPEDEF:
3247 t |= VT_TYPEDEF;
3248 next();
3249 break;
3250 case TOK_INLINE1:
3251 case TOK_INLINE2:
3252 case TOK_INLINE3:
3253 t |= VT_INLINE;
3254 next();
3255 break;
3257 /* GNUC attribute */
3258 case TOK_ATTRIBUTE1:
3259 case TOK_ATTRIBUTE2:
3260 parse_attribute(ad);
3261 if (ad->a.mode) {
3262 u = ad->a.mode -1;
3263 t = (t & ~VT_BTYPE) | u;
3265 break;
3266 /* GNUC typeof */
3267 case TOK_TYPEOF1:
3268 case TOK_TYPEOF2:
3269 case TOK_TYPEOF3:
3270 next();
3271 parse_expr_type(&type1);
3272 /* remove all storage modifiers except typedef */
3273 type1.t &= ~(VT_STORAGE&~VT_TYPEDEF);
3274 goto basic_type2;
3275 default:
3276 if (typespec_found)
3277 goto the_end;
3278 s = sym_find(tok);
3279 if (!s || !(s->type.t & VT_TYPEDEF))
3280 goto the_end;
3281 t |= (s->type.t & ~VT_TYPEDEF);
3282 type->ref = s->type.ref;
3283 if (s->r) {
3284 /* get attributes from typedef */
3285 if (0 == ad->a.aligned)
3286 ad->a.aligned = s->a.aligned;
3287 if (0 == ad->a.func_call)
3288 ad->a.func_call = s->a.func_call;
3289 ad->a.packed |= s->a.packed;
3291 next();
3292 typespec_found = 1;
3293 break;
3295 type_found = 1;
3297 the_end:
3298 if (tcc_state->char_is_unsigned) {
3299 if ((t & (VT_DEFSIGN|VT_BTYPE)) == VT_BYTE)
3300 t |= VT_UNSIGNED;
3303 /* long is never used as type */
3304 if ((t & VT_BTYPE) == VT_LONG)
3305 #if (!defined TCC_TARGET_X86_64 && !defined TCC_TARGET_ARM64) || \
3306 defined TCC_TARGET_PE
3307 t = (t & ~VT_BTYPE) | VT_INT;
3308 #else
3309 t = (t & ~VT_BTYPE) | VT_LLONG;
3310 #endif
3311 type->t = t;
3312 return type_found;
3315 /* convert a function parameter type (array to pointer and function to
3316 function pointer) */
3317 static inline void convert_parameter_type(CType *pt)
3319 /* remove const and volatile qualifiers (XXX: const could be used
3320 to indicate a const function parameter */
3321 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
3322 /* array must be transformed to pointer according to ANSI C */
3323 pt->t &= ~VT_ARRAY;
3324 if ((pt->t & VT_BTYPE) == VT_FUNC) {
3325 mk_pointer(pt);
3329 ST_FUNC void parse_asm_str(CString *astr)
3331 skip('(');
3332 /* read the string */
3333 if (tok != TOK_STR)
3334 expect("string constant");
3335 cstr_new(astr);
3336 while (tok == TOK_STR) {
3337 /* XXX: add \0 handling too ? */
3338 cstr_cat(astr, tokc.cstr->data);
3339 next();
3341 cstr_ccat(astr, '\0');
3344 /* Parse an asm label and return the label
3345 * Don't forget to free the CString in the caller! */
3346 static void asm_label_instr(CString *astr)
3348 next();
3349 parse_asm_str(astr);
3350 skip(')');
3351 #ifdef ASM_DEBUG
3352 printf("asm_alias: \"%s\"\n", (char *)astr->data);
3353 #endif
3356 static void post_type(CType *type, AttributeDef *ad)
3358 int n, l, t1, arg_size, align;
3359 Sym **plast, *s, *first;
3360 AttributeDef ad1;
3361 CType pt;
3363 if (tok == '(') {
3364 /* function declaration */
3365 next();
3366 l = 0;
3367 first = NULL;
3368 plast = &first;
3369 arg_size = 0;
3370 if (tok != ')') {
3371 for(;;) {
3372 /* read param name and compute offset */
3373 if (l != FUNC_OLD) {
3374 if (!parse_btype(&pt, &ad1)) {
3375 if (l) {
3376 tcc_error("invalid type");
3377 } else {
3378 l = FUNC_OLD;
3379 goto old_proto;
3382 l = FUNC_NEW;
3383 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
3384 break;
3385 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
3386 if ((pt.t & VT_BTYPE) == VT_VOID)
3387 tcc_error("parameter declared as void");
3388 arg_size += (type_size(&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
3389 } else {
3390 old_proto:
3391 n = tok;
3392 if (n < TOK_UIDENT)
3393 expect("identifier");
3394 pt.t = VT_INT;
3395 next();
3397 convert_parameter_type(&pt);
3398 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
3399 *plast = s;
3400 plast = &s->next;
3401 if (tok == ')')
3402 break;
3403 skip(',');
3404 if (l == FUNC_NEW && tok == TOK_DOTS) {
3405 l = FUNC_ELLIPSIS;
3406 next();
3407 break;
3411 /* if no parameters, then old type prototype */
3412 if (l == 0)
3413 l = FUNC_OLD;
3414 skip(')');
3415 /* NOTE: const is ignored in returned type as it has a special
3416 meaning in gcc / C++ */
3417 type->t &= ~VT_CONSTANT;
3418 /* some ancient pre-K&R C allows a function to return an array
3419 and the array brackets to be put after the arguments, such
3420 that "int c()[]" means something like "int[] c()" */
3421 if (tok == '[') {
3422 next();
3423 skip(']'); /* only handle simple "[]" */
3424 type->t |= VT_PTR;
3426 /* we push a anonymous symbol which will contain the function prototype */
3427 ad->a.func_args = arg_size;
3428 s = sym_push(SYM_FIELD, type, 0, l);
3429 s->a = ad->a;
3430 s->next = first;
3431 type->t = VT_FUNC;
3432 type->ref = s;
3433 } else if (tok == '[') {
3434 /* array definition */
3435 next();
3436 if (tok == TOK_RESTRICT1)
3437 next();
3438 n = -1;
3439 t1 = 0;
3440 if (tok != ']') {
3441 if (!local_stack || nocode_wanted)
3442 vpushi(expr_const());
3443 else gexpr();
3444 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3445 n = vtop->c.i;
3446 if (n < 0)
3447 tcc_error("invalid array size");
3448 } else {
3449 if (!is_integer_btype(vtop->type.t & VT_BTYPE))
3450 tcc_error("size of variable length array should be an integer");
3451 t1 = VT_VLA;
3454 skip(']');
3455 /* parse next post type */
3456 post_type(type, ad);
3457 if (type->t == VT_FUNC)
3458 tcc_error("declaration of an array of functions");
3459 t1 |= type->t & VT_VLA;
3461 if (t1 & VT_VLA) {
3462 loc -= type_size(&int_type, &align);
3463 loc &= -align;
3464 n = loc;
3466 vla_runtime_type_size(type, &align);
3467 gen_op('*');
3468 vset(&int_type, VT_LOCAL|VT_LVAL, loc);
3469 vswap();
3470 vstore();
3472 if (n != -1)
3473 vpop();
3475 /* we push an anonymous symbol which will contain the array
3476 element type */
3477 s = sym_push(SYM_FIELD, type, 0, n);
3478 type->t = (t1 ? VT_VLA : VT_ARRAY) | VT_PTR;
3479 type->ref = s;
3483 /* Parse a type declaration (except basic type), and return the type
3484 in 'type'. 'td' is a bitmask indicating which kind of type decl is
3485 expected. 'type' should contain the basic type. 'ad' is the
3486 attribute definition of the basic type. It can be modified by
3487 type_decl().
3489 static void type_decl(CType *type, AttributeDef *ad, int *v, int td)
3491 Sym *s;
3492 CType type1, *type2;
3493 int qualifiers, storage;
3495 while (tok == '*') {
3496 qualifiers = 0;
3497 redo:
3498 next();
3499 switch(tok) {
3500 case TOK_CONST1:
3501 case TOK_CONST2:
3502 case TOK_CONST3:
3503 qualifiers |= VT_CONSTANT;
3504 goto redo;
3505 case TOK_VOLATILE1:
3506 case TOK_VOLATILE2:
3507 case TOK_VOLATILE3:
3508 qualifiers |= VT_VOLATILE;
3509 goto redo;
3510 case TOK_RESTRICT1:
3511 case TOK_RESTRICT2:
3512 case TOK_RESTRICT3:
3513 goto redo;
3515 mk_pointer(type);
3516 type->t |= qualifiers;
3519 /* XXX: clarify attribute handling */
3520 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3521 parse_attribute(ad);
3523 /* recursive type */
3524 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
3525 type1.t = 0; /* XXX: same as int */
3526 if (tok == '(') {
3527 next();
3528 /* XXX: this is not correct to modify 'ad' at this point, but
3529 the syntax is not clear */
3530 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3531 parse_attribute(ad);
3532 type_decl(&type1, ad, v, td);
3533 skip(')');
3534 } else {
3535 /* type identifier */
3536 if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
3537 *v = tok;
3538 next();
3539 } else {
3540 if (!(td & TYPE_ABSTRACT))
3541 expect("identifier");
3542 *v = 0;
3545 storage = type->t & VT_STORAGE;
3546 type->t &= ~VT_STORAGE;
3547 if (storage & VT_STATIC) {
3548 int saved_nocode_wanted = nocode_wanted;
3549 nocode_wanted = 1;
3550 post_type(type, ad);
3551 nocode_wanted = saved_nocode_wanted;
3552 } else
3553 post_type(type, ad);
3554 type->t |= storage;
3555 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3556 parse_attribute(ad);
3558 if (!type1.t)
3559 return;
3560 /* append type at the end of type1 */
3561 type2 = &type1;
3562 for(;;) {
3563 s = type2->ref;
3564 type2 = &s->type;
3565 if (!type2->t) {
3566 *type2 = *type;
3567 break;
3570 *type = type1;
3573 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
3574 ST_FUNC int lvalue_type(int t)
3576 int bt, r;
3577 r = VT_LVAL;
3578 bt = t & VT_BTYPE;
3579 if (bt == VT_BYTE || bt == VT_BOOL)
3580 r |= VT_LVAL_BYTE;
3581 else if (bt == VT_SHORT)
3582 r |= VT_LVAL_SHORT;
3583 else
3584 return r;
3585 if (t & VT_UNSIGNED)
3586 r |= VT_LVAL_UNSIGNED;
3587 return r;
3590 /* indirection with full error checking and bound check */
3591 ST_FUNC void indir(void)
3593 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
3594 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
3595 return;
3596 expect("pointer");
3598 if ((vtop->r & VT_LVAL) && !nocode_wanted)
3599 gv(RC_INT);
3600 vtop->type = *pointed_type(&vtop->type);
3601 /* Arrays and functions are never lvalues */
3602 if (!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_VLA)
3603 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
3604 vtop->r |= lvalue_type(vtop->type.t);
3605 /* if bound checking, the referenced pointer must be checked */
3606 #ifdef CONFIG_TCC_BCHECK
3607 if (tcc_state->do_bounds_check)
3608 vtop->r |= VT_MUSTBOUND;
3609 #endif
3613 /* pass a parameter to a function and do type checking and casting */
3614 static void gfunc_param_typed(Sym *func, Sym *arg)
3616 int func_type;
3617 CType type;
3619 func_type = func->c;
3620 if (func_type == FUNC_OLD ||
3621 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
3622 /* default casting : only need to convert float to double */
3623 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
3624 type.t = VT_DOUBLE;
3625 gen_cast(&type);
3626 } else if (vtop->type.t & VT_BITFIELD) {
3627 type.t = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
3628 gen_cast(&type);
3630 } else if (arg == NULL) {
3631 tcc_error("too many arguments to function");
3632 } else {
3633 type = arg->type;
3634 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
3635 gen_assign_cast(&type);
3639 /* parse an expression of the form '(type)' or '(expr)' and return its
3640 type */
3641 static void parse_expr_type(CType *type)
3643 int n;
3644 AttributeDef ad;
3646 skip('(');
3647 if (parse_btype(type, &ad)) {
3648 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3649 } else {
3650 expr_type(type);
3652 skip(')');
3655 static void parse_type(CType *type)
3657 AttributeDef ad;
3658 int n;
3660 if (!parse_btype(type, &ad)) {
3661 expect("type");
3663 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3666 static void vpush_tokc(int t)
3668 CType type;
3669 type.t = t;
3670 type.ref = 0;
3671 vsetc(&type, VT_CONST, &tokc);
3674 ST_FUNC void unary(void)
3676 int n, t, align, size, r, sizeof_caller;
3677 CType type;
3678 Sym *s;
3679 AttributeDef ad;
3680 static int in_sizeof = 0;
3682 sizeof_caller = in_sizeof;
3683 in_sizeof = 0;
3684 /* XXX: GCC 2.95.3 does not generate a table although it should be
3685 better here */
3686 tok_next:
3687 switch(tok) {
3688 case TOK_EXTENSION:
3689 next();
3690 goto tok_next;
3691 case TOK_CINT:
3692 case TOK_CCHAR:
3693 case TOK_LCHAR:
3694 vpushi(tokc.i);
3695 next();
3696 break;
3697 case TOK_CUINT:
3698 vpush_tokc(VT_INT | VT_UNSIGNED);
3699 next();
3700 break;
3701 case TOK_CLLONG:
3702 vpush_tokc(VT_LLONG);
3703 next();
3704 break;
3705 case TOK_CULLONG:
3706 vpush_tokc(VT_LLONG | VT_UNSIGNED);
3707 next();
3708 break;
3709 case TOK_CFLOAT:
3710 vpush_tokc(VT_FLOAT);
3711 next();
3712 break;
3713 case TOK_CDOUBLE:
3714 vpush_tokc(VT_DOUBLE);
3715 next();
3716 break;
3717 case TOK_CLDOUBLE:
3718 vpush_tokc(VT_LDOUBLE);
3719 next();
3720 break;
3721 case TOK___FUNCTION__:
3722 if (!gnu_ext)
3723 goto tok_identifier;
3724 /* fall thru */
3725 case TOK___FUNC__:
3727 void *ptr;
3728 int len;
3729 /* special function name identifier */
3730 len = strlen(funcname) + 1;
3731 /* generate char[len] type */
3732 type.t = VT_BYTE;
3733 mk_pointer(&type);
3734 type.t |= VT_ARRAY;
3735 type.ref->c = len;
3736 vpush_ref(&type, data_section, data_section->data_offset, len);
3737 ptr = section_ptr_add(data_section, len);
3738 memcpy(ptr, funcname, len);
3739 next();
3741 break;
3742 case TOK_LSTR:
3743 #ifdef TCC_TARGET_PE
3744 t = VT_SHORT | VT_UNSIGNED;
3745 #else
3746 t = VT_INT;
3747 #endif
3748 goto str_init;
3749 case TOK_STR:
3750 /* string parsing */
3751 t = VT_BYTE;
3752 str_init:
3753 if (tcc_state->warn_write_strings)
3754 t |= VT_CONSTANT;
3755 type.t = t;
3756 mk_pointer(&type);
3757 type.t |= VT_ARRAY;
3758 memset(&ad, 0, sizeof(AttributeDef));
3759 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, NULL, 0);
3760 break;
3761 case '(':
3762 next();
3763 /* cast ? */
3764 if (parse_btype(&type, &ad)) {
3765 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
3766 skip(')');
3767 /* check ISOC99 compound literal */
3768 if (tok == '{') {
3769 /* data is allocated locally by default */
3770 if (global_expr)
3771 r = VT_CONST;
3772 else
3773 r = VT_LOCAL;
3774 /* all except arrays are lvalues */
3775 if (!(type.t & VT_ARRAY))
3776 r |= lvalue_type(type.t);
3777 memset(&ad, 0, sizeof(AttributeDef));
3778 decl_initializer_alloc(&type, &ad, r, 1, 0, NULL, 0);
3779 } else {
3780 if (sizeof_caller) {
3781 vpush(&type);
3782 return;
3784 unary();
3785 gen_cast(&type);
3787 } else if (tok == '{') {
3789 if (nocode_wanted)
3790 tcc_error("statement expression in global scope"); */
3791 /* this check breaks compilation of the linux 2.4.26 with the meesage:
3792 linux/include/net/tcp.h:945: error: statement expression in global scope */
3794 /* save all registers */
3795 save_regs(0);
3796 /* statement expression : we do not accept break/continue
3797 inside as GCC does */
3798 block(NULL, NULL, NULL, NULL, 0, 1);
3799 skip(')');
3800 } else {
3801 gexpr();
3802 skip(')');
3804 break;
3805 case '*':
3806 next();
3807 unary();
3808 indir();
3809 break;
3810 case '&':
3811 next();
3812 unary();
3813 /* functions names must be treated as function pointers,
3814 except for unary '&' and sizeof. Since we consider that
3815 functions are not lvalues, we only have to handle it
3816 there and in function calls. */
3817 /* arrays can also be used although they are not lvalues */
3818 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
3819 !(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
3820 test_lvalue();
3821 mk_pointer(&vtop->type);
3822 gaddrof();
3823 break;
3824 case '!':
3825 next();
3826 unary();
3827 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3828 CType boolean;
3829 boolean.t = VT_BOOL;
3830 gen_cast(&boolean);
3831 vtop->c.i = !vtop->c.i;
3832 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
3833 vtop->c.i = vtop->c.i ^ 1;
3834 else if (!nocode_wanted) {
3835 save_regs(1);
3836 vseti(VT_JMP, gvtst(1, 0));
3838 else
3839 vtop--;
3840 break;
3841 case '~':
3842 next();
3843 unary();
3844 vpushi(-1);
3845 gen_op('^');
3846 break;
3847 case '+':
3848 next();
3849 unary();
3850 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
3851 tcc_error("pointer not accepted for unary plus");
3852 /* In order to force cast, we add zero, except for floating point
3853 where we really need an noop (otherwise -0.0 will be transformed
3854 into +0.0). */
3855 if (!is_float(vtop->type.t)) {
3856 vpushi(0);
3857 gen_op('+');
3859 break;
3860 case TOK_SIZEOF:
3861 case TOK_ALIGNOF1:
3862 case TOK_ALIGNOF2:
3863 t = tok;
3864 next();
3865 in_sizeof++;
3866 unary_type(&type); // Perform a in_sizeof = 0;
3867 size = type_size(&type, &align);
3868 if (t == TOK_SIZEOF) {
3869 if (!(type.t & VT_VLA)) {
3870 if (size < 0)
3871 tcc_error("sizeof applied to an incomplete type");
3872 vpushs(size);
3873 } else {
3874 vla_runtime_type_size(&type, &align);
3876 } else {
3877 vpushs(align);
3879 vtop->type.t |= VT_UNSIGNED;
3880 break;
3882 case TOK_builtin_types_compatible_p:
3884 CType type1, type2;
3885 next();
3886 skip('(');
3887 parse_type(&type1);
3888 skip(',');
3889 parse_type(&type2);
3890 skip(')');
3891 type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
3892 type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
3893 vpushi(is_compatible_types(&type1, &type2));
3895 break;
3896 case TOK_builtin_constant_p:
3898 int saved_nocode_wanted, res;
3899 next();
3900 skip('(');
3901 saved_nocode_wanted = nocode_wanted;
3902 nocode_wanted = 1;
3903 gexpr();
3904 res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
3905 vpop();
3906 nocode_wanted = saved_nocode_wanted;
3907 skip(')');
3908 vpushi(res);
3910 break;
3911 case TOK_builtin_frame_address:
3912 case TOK_builtin_return_address:
3914 int tok1 = tok;
3915 int level;
3916 CType type;
3917 next();
3918 skip('(');
3919 if (tok != TOK_CINT || tokc.i < 0) {
3920 tcc_error("%s only takes positive integers",
3921 tok1 == TOK_builtin_return_address ?
3922 "__builtin_return_address" :
3923 "__builtin_frame_address");
3925 level = tokc.i;
3926 next();
3927 skip(')');
3928 type.t = VT_VOID;
3929 mk_pointer(&type);
3930 vset(&type, VT_LOCAL, 0); /* local frame */
3931 while (level--) {
3932 mk_pointer(&vtop->type);
3933 indir(); /* -> parent frame */
3935 if (tok1 == TOK_builtin_return_address) {
3936 // assume return address is just above frame pointer on stack
3937 vpushi(PTR_SIZE);
3938 gen_op('+');
3939 mk_pointer(&vtop->type);
3940 indir();
3943 break;
3944 #ifdef TCC_TARGET_X86_64
3945 #ifdef TCC_TARGET_PE
3946 case TOK_builtin_va_start:
3948 next();
3949 skip('(');
3950 expr_eq();
3951 skip(',');
3952 expr_eq();
3953 skip(')');
3954 if ((vtop->r & VT_VALMASK) != VT_LOCAL)
3955 tcc_error("__builtin_va_start expects a local variable");
3956 vtop->r &= ~(VT_LVAL | VT_REF);
3957 vtop->type = char_pointer_type;
3958 vstore();
3960 break;
3961 #else
3962 case TOK_builtin_va_arg_types:
3964 CType type;
3965 next();
3966 skip('(');
3967 parse_type(&type);
3968 skip(')');
3969 vpushi(classify_x86_64_va_arg(&type));
3971 break;
3972 #endif
3973 #endif
3975 #ifdef TCC_TARGET_ARM64
3976 case TOK___va_start: {
3977 if (nocode_wanted)
3978 tcc_error("statement in global scope");
3979 next();
3980 skip('(');
3981 expr_eq();
3982 skip(',');
3983 expr_eq();
3984 skip(')');
3985 //xx check types
3986 gen_va_start();
3987 vpushi(0);
3988 vtop->type.t = VT_VOID;
3989 break;
3991 case TOK___va_arg: {
3992 if (nocode_wanted)
3993 tcc_error("statement in global scope");
3994 CType type;
3995 next();
3996 skip('(');
3997 expr_eq();
3998 skip(',');
3999 parse_type(&type);
4000 skip(')');
4001 //xx check types
4002 gen_va_arg(&type);
4003 vtop->type = type;
4004 break;
4006 case TOK___arm64_clear_cache: {
4007 next();
4008 skip('(');
4009 expr_eq();
4010 skip(',');
4011 expr_eq();
4012 skip(')');
4013 gen_clear_cache();
4014 vpushi(0);
4015 vtop->type.t = VT_VOID;
4016 break;
4018 #endif
4019 /* pre operations */
4020 case TOK_INC:
4021 case TOK_DEC:
4022 t = tok;
4023 next();
4024 unary();
4025 inc(0, t);
4026 break;
4027 case '-':
4028 next();
4029 unary();
4030 t = vtop->type.t & VT_BTYPE;
4031 if (is_float(t)) {
4032 /* In IEEE negate(x) isn't subtract(0,x), but rather
4033 subtract(-0, x). */
4034 vpush(&vtop->type);
4035 if (t == VT_FLOAT)
4036 vtop->c.f = -0.0f;
4037 else if (t == VT_DOUBLE)
4038 vtop->c.d = -0.0;
4039 else
4040 vtop->c.ld = -0.0;
4041 } else
4042 vpushi(0);
4043 vswap();
4044 gen_op('-');
4045 break;
4046 case TOK_LAND:
4047 if (!gnu_ext)
4048 goto tok_identifier;
4049 next();
4050 /* allow to take the address of a label */
4051 if (tok < TOK_UIDENT)
4052 expect("label identifier");
4053 s = label_find(tok);
4054 if (!s) {
4055 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
4056 } else {
4057 if (s->r == LABEL_DECLARED)
4058 s->r = LABEL_FORWARD;
4060 if (!s->type.t) {
4061 s->type.t = VT_VOID;
4062 mk_pointer(&s->type);
4063 s->type.t |= VT_STATIC;
4065 vpushsym(&s->type, s);
4066 next();
4067 break;
4069 // special qnan , snan and infinity values
4070 case TOK___NAN__:
4071 vpush64(VT_DOUBLE, 0x7ff8000000000000ULL);
4072 next();
4073 break;
4074 case TOK___SNAN__:
4075 vpush64(VT_DOUBLE, 0x7ff0000000000001ULL);
4076 next();
4077 break;
4078 case TOK___INF__:
4079 vpush64(VT_DOUBLE, 0x7ff0000000000000ULL);
4080 next();
4081 break;
4083 default:
4084 tok_identifier:
4085 t = tok;
4086 next();
4087 if (t < TOK_UIDENT)
4088 expect("identifier");
4089 s = sym_find(t);
4090 if (!s) {
4091 const char *name = get_tok_str(t, NULL);
4092 if (tok != '(')
4093 tcc_error("'%s' undeclared", name);
4094 /* for simple function calls, we tolerate undeclared
4095 external reference to int() function */
4096 if (tcc_state->warn_implicit_function_declaration
4097 #ifdef TCC_TARGET_PE
4098 /* people must be warned about using undeclared WINAPI functions
4099 (which usually start with uppercase letter) */
4100 || (name[0] >= 'A' && name[0] <= 'Z')
4101 #endif
4103 tcc_warning("implicit declaration of function '%s'", name);
4104 s = external_global_sym(t, &func_old_type, 0);
4106 if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
4107 (VT_STATIC | VT_INLINE | VT_FUNC)) {
4108 /* if referencing an inline function, then we generate a
4109 symbol to it if not already done. It will have the
4110 effect to generate code for it at the end of the
4111 compilation unit. Inline function as always
4112 generated in the text section. */
4113 if (!s->c)
4114 put_extern_sym(s, text_section, 0, 0);
4115 r = VT_SYM | VT_CONST;
4116 } else {
4117 r = s->r;
4119 vset(&s->type, r, s->c);
4120 /* if forward reference, we must point to s */
4121 if (vtop->r & VT_SYM) {
4122 vtop->sym = s;
4123 vtop->c.ptr_offset = 0;
4125 break;
4128 /* post operations */
4129 while (1) {
4130 if (tok == TOK_INC || tok == TOK_DEC) {
4131 inc(1, tok);
4132 next();
4133 } else if (tok == '.' || tok == TOK_ARROW) {
4134 int qualifiers;
4135 /* field */
4136 if (tok == TOK_ARROW)
4137 indir();
4138 qualifiers = vtop->type.t & (VT_CONSTANT | VT_VOLATILE);
4139 test_lvalue();
4140 gaddrof();
4141 next();
4142 /* expect pointer on structure */
4143 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
4144 expect("struct or union");
4145 s = vtop->type.ref;
4146 /* find field */
4147 tok |= SYM_FIELD;
4148 while ((s = s->next) != NULL) {
4149 if (s->v == tok)
4150 break;
4152 if (!s)
4153 tcc_error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, NULL));
4154 /* add field offset to pointer */
4155 vtop->type = char_pointer_type; /* change type to 'char *' */
4156 vpushi(s->c);
4157 gen_op('+');
4158 /* change type to field type, and set to lvalue */
4159 vtop->type = s->type;
4160 vtop->type.t |= qualifiers;
4161 /* an array is never an lvalue */
4162 if (!(vtop->type.t & VT_ARRAY)) {
4163 vtop->r |= lvalue_type(vtop->type.t);
4164 #ifdef CONFIG_TCC_BCHECK
4165 /* if bound checking, the referenced pointer must be checked */
4166 if (tcc_state->do_bounds_check)
4167 vtop->r |= VT_MUSTBOUND;
4168 #endif
4170 next();
4171 } else if (tok == '[') {
4172 next();
4173 gexpr();
4174 gen_op('+');
4175 indir();
4176 skip(']');
4177 } else if (tok == '(') {
4178 SValue ret;
4179 Sym *sa;
4180 int nb_args, ret_nregs, ret_align, regsize, variadic;
4182 /* function call */
4183 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
4184 /* pointer test (no array accepted) */
4185 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
4186 vtop->type = *pointed_type(&vtop->type);
4187 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
4188 goto error_func;
4189 } else {
4190 error_func:
4191 expect("function pointer");
4193 } else {
4194 vtop->r &= ~VT_LVAL; /* no lvalue */
4196 /* get return type */
4197 s = vtop->type.ref;
4198 next();
4199 sa = s->next; /* first parameter */
4200 nb_args = 0;
4201 ret.r2 = VT_CONST;
4202 /* compute first implicit argument if a structure is returned */
4203 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
4204 variadic = (s->c == FUNC_ELLIPSIS);
4205 ret_nregs = gfunc_sret(&s->type, variadic, &ret.type,
4206 &ret_align, &regsize);
4207 if (!ret_nregs) {
4208 /* get some space for the returned structure */
4209 size = type_size(&s->type, &align);
4210 #ifdef TCC_TARGET_ARM64
4211 /* On arm64, a small struct is return in registers.
4212 It is much easier to write it to memory if we know
4213 that we are allowed to write some extra bytes, so
4214 round the allocated space up to a power of 2: */
4215 if (size < 16)
4216 while (size & (size - 1))
4217 size = (size | (size - 1)) + 1;
4218 #endif
4219 loc = (loc - size) & -align;
4220 ret.type = s->type;
4221 ret.r = VT_LOCAL | VT_LVAL;
4222 /* pass it as 'int' to avoid structure arg passing
4223 problems */
4224 vseti(VT_LOCAL, loc);
4225 ret.c = vtop->c;
4226 nb_args++;
4228 } else {
4229 ret_nregs = 1;
4230 ret.type = s->type;
4233 if (ret_nregs) {
4234 /* return in register */
4235 if (is_float(ret.type.t)) {
4236 ret.r = reg_fret(ret.type.t);
4237 #ifdef TCC_TARGET_X86_64
4238 if ((ret.type.t & VT_BTYPE) == VT_QFLOAT)
4239 ret.r2 = REG_QRET;
4240 #endif
4241 } else {
4242 #ifndef TCC_TARGET_ARM64
4243 #ifdef TCC_TARGET_X86_64
4244 if ((ret.type.t & VT_BTYPE) == VT_QLONG)
4245 #else
4246 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
4247 #endif
4248 ret.r2 = REG_LRET;
4249 #endif
4250 ret.r = REG_IRET;
4252 ret.c.i = 0;
4254 if (tok != ')') {
4255 for(;;) {
4256 expr_eq();
4257 gfunc_param_typed(s, sa);
4258 nb_args++;
4259 if (sa)
4260 sa = sa->next;
4261 if (tok == ')')
4262 break;
4263 skip(',');
4266 if (sa)
4267 tcc_error("too few arguments to function");
4268 skip(')');
4269 if (!nocode_wanted) {
4270 gfunc_call(nb_args);
4271 } else {
4272 vtop -= (nb_args + 1);
4275 /* return value */
4276 for (r = ret.r + ret_nregs + !ret_nregs; r-- > ret.r;) {
4277 vsetc(&ret.type, r, &ret.c);
4278 vtop->r2 = ret.r2; /* Loop only happens when r2 is VT_CONST */
4281 /* handle packed struct return */
4282 if (((s->type.t & VT_BTYPE) == VT_STRUCT) && ret_nregs) {
4283 int addr, offset;
4285 size = type_size(&s->type, &align);
4286 /* We're writing whole regs often, make sure there's enough
4287 space. Assume register size is power of 2. */
4288 if (regsize > align)
4289 align = regsize;
4290 loc = (loc - size) & -align;
4291 addr = loc;
4292 offset = 0;
4293 for (;;) {
4294 vset(&ret.type, VT_LOCAL | VT_LVAL, addr + offset);
4295 vswap();
4296 vstore();
4297 vtop--;
4298 if (--ret_nregs == 0)
4299 break;
4300 offset += regsize;
4302 vset(&s->type, VT_LOCAL | VT_LVAL, addr);
4304 } else {
4305 break;
4310 ST_FUNC void expr_prod(void)
4312 int t;
4314 unary();
4315 while (tok == '*' || tok == '/' || tok == '%') {
4316 t = tok;
4317 next();
4318 unary();
4319 gen_op(t);
4323 ST_FUNC void expr_sum(void)
4325 int t;
4327 expr_prod();
4328 while (tok == '+' || tok == '-') {
4329 t = tok;
4330 next();
4331 expr_prod();
4332 gen_op(t);
4336 static void expr_shift(void)
4338 int t;
4340 expr_sum();
4341 while (tok == TOK_SHL || tok == TOK_SAR) {
4342 t = tok;
4343 next();
4344 expr_sum();
4345 gen_op(t);
4349 static void expr_cmp(void)
4351 int t;
4353 expr_shift();
4354 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
4355 tok == TOK_ULT || tok == TOK_UGE) {
4356 t = tok;
4357 next();
4358 expr_shift();
4359 gen_op(t);
4363 static void expr_cmpeq(void)
4365 int t;
4367 expr_cmp();
4368 while (tok == TOK_EQ || tok == TOK_NE) {
4369 t = tok;
4370 next();
4371 expr_cmp();
4372 gen_op(t);
4376 static void expr_and(void)
4378 expr_cmpeq();
4379 while (tok == '&') {
4380 next();
4381 expr_cmpeq();
4382 gen_op('&');
4386 static void expr_xor(void)
4388 expr_and();
4389 while (tok == '^') {
4390 next();
4391 expr_and();
4392 gen_op('^');
4396 static void expr_or(void)
4398 expr_xor();
4399 while (tok == '|') {
4400 next();
4401 expr_xor();
4402 gen_op('|');
4406 /* XXX: fix this mess */
4407 static void expr_land_const(void)
4409 expr_or();
4410 while (tok == TOK_LAND) {
4411 next();
4412 expr_or();
4413 gen_op(TOK_LAND);
4417 /* XXX: fix this mess */
4418 static void expr_lor_const(void)
4420 expr_land_const();
4421 while (tok == TOK_LOR) {
4422 next();
4423 expr_land_const();
4424 gen_op(TOK_LOR);
4428 /* only used if non constant */
4429 static void expr_land(void)
4431 int t;
4433 expr_or();
4434 if (tok == TOK_LAND) {
4435 t = 0;
4436 save_regs(1);
4437 for(;;) {
4438 t = gvtst(1, t);
4439 if (tok != TOK_LAND) {
4440 vseti(VT_JMPI, t);
4441 break;
4443 next();
4444 expr_or();
4449 static void expr_lor(void)
4451 int t;
4453 expr_land();
4454 if (tok == TOK_LOR) {
4455 t = 0;
4456 save_regs(1);
4457 for(;;) {
4458 t = gvtst(0, t);
4459 if (tok != TOK_LOR) {
4460 vseti(VT_JMP, t);
4461 break;
4463 next();
4464 expr_land();
4469 /* XXX: better constant handling */
4470 static void expr_cond(void)
4472 int tt, u, r1, r2, rc, t1, t2, bt1, bt2;
4473 SValue sv;
4474 CType type, type1, type2;
4476 if (const_wanted) {
4477 expr_lor_const();
4478 if (tok == '?') {
4479 CType boolean;
4480 int c;
4481 boolean.t = VT_BOOL;
4482 vdup();
4483 gen_cast(&boolean);
4484 c = vtop->c.i;
4485 vpop();
4486 next();
4487 if (tok != ':' || !gnu_ext) {
4488 vpop();
4489 gexpr();
4491 if (!c)
4492 vpop();
4493 skip(':');
4494 expr_cond();
4495 if (c)
4496 vpop();
4498 } else {
4499 expr_lor();
4500 if (tok == '?') {
4501 next();
4502 if (vtop != vstack) {
4503 /* needed to avoid having different registers saved in
4504 each branch */
4505 if (is_float(vtop->type.t)) {
4506 rc = RC_FLOAT;
4507 #ifdef TCC_TARGET_X86_64
4508 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
4509 rc = RC_ST0;
4511 #endif
4513 else
4514 rc = RC_INT;
4515 gv(rc);
4516 save_regs(1);
4518 if (tok == ':' && gnu_ext) {
4519 gv_dup();
4520 tt = gvtst(1, 0);
4521 } else {
4522 tt = gvtst(1, 0);
4523 gexpr();
4525 type1 = vtop->type;
4526 sv = *vtop; /* save value to handle it later */
4527 vtop--; /* no vpop so that FP stack is not flushed */
4528 skip(':');
4529 u = gjmp(0);
4530 gsym(tt);
4531 expr_cond();
4532 type2 = vtop->type;
4534 t1 = type1.t;
4535 bt1 = t1 & VT_BTYPE;
4536 t2 = type2.t;
4537 bt2 = t2 & VT_BTYPE;
4538 /* cast operands to correct type according to ISOC rules */
4539 if (is_float(bt1) || is_float(bt2)) {
4540 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
4541 type.t = VT_LDOUBLE;
4542 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
4543 type.t = VT_DOUBLE;
4544 } else {
4545 type.t = VT_FLOAT;
4547 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
4548 /* cast to biggest op */
4549 type.t = VT_LLONG;
4550 /* convert to unsigned if it does not fit in a long long */
4551 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
4552 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
4553 type.t |= VT_UNSIGNED;
4554 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
4555 /* If one is a null ptr constant the result type
4556 is the other. */
4557 if (is_null_pointer (vtop))
4558 type = type1;
4559 else if (is_null_pointer (&sv))
4560 type = type2;
4561 /* XXX: test pointer compatibility, C99 has more elaborate
4562 rules here. */
4563 else
4564 type = type1;
4565 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
4566 /* XXX: test function pointer compatibility */
4567 type = bt1 == VT_FUNC ? type1 : type2;
4568 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
4569 /* XXX: test structure compatibility */
4570 type = bt1 == VT_STRUCT ? type1 : type2;
4571 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
4572 /* NOTE: as an extension, we accept void on only one side */
4573 type.t = VT_VOID;
4574 } else {
4575 /* integer operations */
4576 type.t = VT_INT;
4577 /* convert to unsigned if it does not fit in an integer */
4578 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
4579 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
4580 type.t |= VT_UNSIGNED;
4583 /* now we convert second operand */
4584 gen_cast(&type);
4585 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4586 gaddrof();
4587 rc = RC_INT;
4588 if (is_float(type.t)) {
4589 rc = RC_FLOAT;
4590 #ifdef TCC_TARGET_X86_64
4591 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
4592 rc = RC_ST0;
4594 #endif
4595 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
4596 /* for long longs, we use fixed registers to avoid having
4597 to handle a complicated move */
4598 rc = RC_IRET;
4601 r2 = gv(rc);
4602 /* this is horrible, but we must also convert first
4603 operand */
4604 tt = gjmp(0);
4605 gsym(u);
4606 /* put again first value and cast it */
4607 *vtop = sv;
4608 gen_cast(&type);
4609 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4610 gaddrof();
4611 r1 = gv(rc);
4612 move_reg(r2, r1, type.t);
4613 vtop->r = r2;
4614 gsym(tt);
4619 static void expr_eq(void)
4621 int t;
4623 expr_cond();
4624 if (tok == '=' ||
4625 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
4626 tok == TOK_A_XOR || tok == TOK_A_OR ||
4627 tok == TOK_A_SHL || tok == TOK_A_SAR) {
4628 test_lvalue();
4629 t = tok;
4630 next();
4631 if (t == '=') {
4632 expr_eq();
4633 } else {
4634 vdup();
4635 expr_eq();
4636 gen_op(t & 0x7f);
4638 vstore();
4642 ST_FUNC void gexpr(void)
4644 while (1) {
4645 expr_eq();
4646 if (tok != ',')
4647 break;
4648 vpop();
4649 next();
4653 /* parse an expression and return its type without any side effect. */
4654 static void expr_type(CType *type)
4656 int saved_nocode_wanted;
4658 saved_nocode_wanted = nocode_wanted;
4659 nocode_wanted = 1;
4660 gexpr();
4661 *type = vtop->type;
4662 vpop();
4663 nocode_wanted = saved_nocode_wanted;
4666 /* parse a unary expression and return its type without any side
4667 effect. */
4668 static void unary_type(CType *type)
4670 int a;
4672 a = nocode_wanted;
4673 nocode_wanted = 1;
4674 unary();
4675 *type = vtop->type;
4676 vpop();
4677 nocode_wanted = a;
4680 /* parse a constant expression and return value in vtop. */
4681 static void expr_const1(void)
4683 int a;
4684 a = const_wanted;
4685 const_wanted = 1;
4686 expr_cond();
4687 const_wanted = a;
4690 /* parse an integer constant and return its value. */
4691 ST_FUNC int expr_const(void)
4693 int c;
4694 expr_const1();
4695 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
4696 expect("constant expression");
4697 c = vtop->c.i;
4698 vpop();
4699 return c;
4702 /* return the label token if current token is a label, otherwise
4703 return zero */
4704 static int is_label(void)
4706 int last_tok;
4708 /* fast test first */
4709 if (tok < TOK_UIDENT)
4710 return 0;
4711 /* no need to save tokc because tok is an identifier */
4712 last_tok = tok;
4713 next();
4714 if (tok == ':') {
4715 next();
4716 return last_tok;
4717 } else {
4718 unget_tok(last_tok);
4719 return 0;
4723 static void label_or_decl(int l)
4725 int last_tok;
4727 /* fast test first */
4728 if (tok >= TOK_UIDENT)
4730 /* no need to save tokc because tok is an identifier */
4731 last_tok = tok;
4732 next();
4733 if (tok == ':') {
4734 unget_tok(last_tok);
4735 return;
4737 unget_tok(last_tok);
4739 decl(l);
4742 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
4743 int case_reg, int is_expr)
4745 int a, b, c, d;
4746 Sym *s, *frame_bottom;
4748 /* generate line number info */
4749 if (tcc_state->do_debug &&
4750 (last_line_num != file->line_num || last_ind != ind)) {
4751 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
4752 last_ind = ind;
4753 last_line_num = file->line_num;
4756 if (is_expr) {
4757 /* default return value is (void) */
4758 vpushi(0);
4759 vtop->type.t = VT_VOID;
4762 if (tok == TOK_IF) {
4763 /* if test */
4764 next();
4765 skip('(');
4766 gexpr();
4767 skip(')');
4768 a = gvtst(1, 0);
4769 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4770 c = tok;
4771 if (c == TOK_ELSE) {
4772 next();
4773 d = gjmp(0);
4774 gsym(a);
4775 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4776 gsym(d); /* patch else jmp */
4777 } else
4778 gsym(a);
4779 } else if (tok == TOK_WHILE) {
4780 next();
4781 d = ind;
4782 skip('(');
4783 gexpr();
4784 skip(')');
4785 a = gvtst(1, 0);
4786 b = 0;
4787 block(&a, &b, case_sym, def_sym, case_reg, 0);
4788 gjmp_addr(d);
4789 gsym(a);
4790 gsym_addr(b, d);
4791 } else if (tok == '{') {
4792 Sym *llabel;
4793 int block_vla_sp_loc, *saved_vla_sp_loc, saved_vla_flags;
4795 next();
4796 /* record local declaration stack position */
4797 s = local_stack;
4798 frame_bottom = sym_push2(&local_stack, SYM_FIELD, 0, 0);
4799 frame_bottom->next = scope_stack_bottom;
4800 scope_stack_bottom = frame_bottom;
4801 llabel = local_label_stack;
4803 /* save VLA state */
4804 block_vla_sp_loc = *(saved_vla_sp_loc = vla_sp_loc);
4805 if (saved_vla_sp_loc != &vla_sp_root_loc)
4806 vla_sp_loc = &block_vla_sp_loc;
4808 saved_vla_flags = vla_flags;
4809 vla_flags |= VLA_NEED_NEW_FRAME;
4811 /* handle local labels declarations */
4812 if (tok == TOK_LABEL) {
4813 next();
4814 for(;;) {
4815 if (tok < TOK_UIDENT)
4816 expect("label identifier");
4817 label_push(&local_label_stack, tok, LABEL_DECLARED);
4818 next();
4819 if (tok == ',') {
4820 next();
4821 } else {
4822 skip(';');
4823 break;
4827 while (tok != '}') {
4828 label_or_decl(VT_LOCAL);
4829 if (tok != '}') {
4830 if (is_expr)
4831 vpop();
4832 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
4835 /* pop locally defined labels */
4836 label_pop(&local_label_stack, llabel);
4837 if(is_expr) {
4838 /* XXX: this solution makes only valgrind happy...
4839 triggered by gcc.c-torture/execute/20000917-1.c */
4840 Sym *p;
4841 switch(vtop->type.t & VT_BTYPE) {
4842 /* case VT_PTR: */
4843 /* this breaks a compilation of the linux kernel v2.4.26 */
4844 /* pmd_t *new = ({ __asm__ __volatile__("ud2\n") ; ((pmd_t *)1); }); */
4845 /* Look a commit a80acab: Display error on statement expressions with complex return type */
4846 /* A pointer is not a complex return type */
4847 case VT_STRUCT:
4848 case VT_ENUM:
4849 case VT_FUNC:
4850 for(p=vtop->type.ref;p;p=p->prev)
4851 if(p->prev==s)
4852 tcc_error("unsupported expression type");
4855 /* pop locally defined symbols */
4856 scope_stack_bottom = scope_stack_bottom->next;
4857 sym_pop(&local_stack, s);
4859 /* Pop VLA frames and restore stack pointer if required */
4860 if (saved_vla_sp_loc != &vla_sp_root_loc)
4861 *saved_vla_sp_loc = block_vla_sp_loc;
4862 if (vla_sp_loc != (saved_vla_sp_loc == &vla_sp_root_loc ? &vla_sp_root_loc : &block_vla_sp_loc)) {
4863 vla_sp_loc = saved_vla_sp_loc;
4864 gen_vla_sp_restore(*vla_sp_loc);
4866 vla_flags = (vla_flags & ~VLA_SCOPE_FLAGS) | (saved_vla_flags & VLA_SCOPE_FLAGS);
4868 next();
4869 } else if (tok == TOK_RETURN) {
4870 next();
4871 if (tok != ';') {
4872 gexpr();
4873 gen_assign_cast(&func_vt);
4874 #ifdef TCC_TARGET_ARM64
4875 // Perhaps it would be better to use this for all backends:
4876 greturn();
4877 #else
4878 if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
4879 CType type, ret_type;
4880 int ret_align, ret_nregs, regsize;
4881 ret_nregs = gfunc_sret(&func_vt, func_var, &ret_type,
4882 &ret_align, &regsize);
4883 if (0 == ret_nregs) {
4884 /* if returning structure, must copy it to implicit
4885 first pointer arg location */
4886 type = func_vt;
4887 mk_pointer(&type);
4888 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
4889 indir();
4890 vswap();
4891 /* copy structure value to pointer */
4892 vstore();
4893 } else {
4894 /* returning structure packed into registers */
4895 int r, size, addr, align;
4896 size = type_size(&func_vt,&align);
4897 if ((vtop->r != (VT_LOCAL | VT_LVAL) || (vtop->c.i & (ret_align-1)))
4898 && (align & (ret_align-1))) {
4899 loc = (loc - size) & -align;
4900 addr = loc;
4901 type = func_vt;
4902 vset(&type, VT_LOCAL | VT_LVAL, addr);
4903 vswap();
4904 vstore();
4905 vset(&ret_type, VT_LOCAL | VT_LVAL, addr);
4907 vtop->type = ret_type;
4908 if (is_float(ret_type.t))
4909 r = rc_fret(ret_type.t);
4910 else
4911 r = RC_IRET;
4913 for (;;) {
4914 gv(r);
4915 if (--ret_nregs == 0)
4916 break;
4917 /* We assume that when a structure is returned in multiple
4918 registers, their classes are consecutive values of the
4919 suite s(n) = 2^n */
4920 r <<= 1;
4921 vtop->c.i += regsize;
4922 vtop->r = VT_LOCAL | VT_LVAL;
4925 } else if (is_float(func_vt.t)) {
4926 gv(rc_fret(func_vt.t));
4927 } else {
4928 gv(RC_IRET);
4930 #endif
4931 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
4933 skip(';');
4934 rsym = gjmp(rsym); /* jmp */
4935 } else if (tok == TOK_BREAK) {
4936 /* compute jump */
4937 if (!bsym)
4938 tcc_error("cannot break");
4939 *bsym = gjmp(*bsym);
4940 next();
4941 skip(';');
4942 } else if (tok == TOK_CONTINUE) {
4943 /* compute jump */
4944 if (!csym)
4945 tcc_error("cannot continue");
4946 *csym = gjmp(*csym);
4947 next();
4948 skip(';');
4949 } else if (tok == TOK_FOR) {
4950 int e;
4951 next();
4952 skip('(');
4953 s = local_stack;
4954 frame_bottom = sym_push2(&local_stack, SYM_FIELD, 0, 0);
4955 frame_bottom->next = scope_stack_bottom;
4956 scope_stack_bottom = frame_bottom;
4957 if (tok != ';') {
4958 /* c99 for-loop init decl? */
4959 if (!decl0(VT_LOCAL, 1)) {
4960 /* no, regular for-loop init expr */
4961 gexpr();
4962 vpop();
4965 skip(';');
4966 d = ind;
4967 c = ind;
4968 a = 0;
4969 b = 0;
4970 if (tok != ';') {
4971 gexpr();
4972 a = gvtst(1, 0);
4974 skip(';');
4975 if (tok != ')') {
4976 e = gjmp(0);
4977 c = ind;
4978 gexpr();
4979 vpop();
4980 gjmp_addr(d);
4981 gsym(e);
4983 skip(')');
4984 block(&a, &b, case_sym, def_sym, case_reg, 0);
4985 gjmp_addr(c);
4986 gsym(a);
4987 gsym_addr(b, c);
4988 scope_stack_bottom = scope_stack_bottom->next;
4989 sym_pop(&local_stack, s);
4990 } else
4991 if (tok == TOK_DO) {
4992 next();
4993 a = 0;
4994 b = 0;
4995 d = ind;
4996 block(&a, &b, case_sym, def_sym, case_reg, 0);
4997 skip(TOK_WHILE);
4998 skip('(');
4999 gsym(b);
5000 gexpr();
5001 c = gvtst(0, 0);
5002 gsym_addr(c, d);
5003 skip(')');
5004 gsym(a);
5005 skip(';');
5006 } else
5007 if (tok == TOK_SWITCH) {
5008 next();
5009 skip('(');
5010 gexpr();
5011 /* XXX: other types than integer */
5012 case_reg = gv(RC_INT);
5013 vpop();
5014 skip(')');
5015 a = 0;
5016 b = gjmp(0); /* jump to first case */
5017 c = 0;
5018 block(&a, csym, &b, &c, case_reg, 0);
5019 /* if no default, jmp after switch */
5020 if (c == 0)
5021 c = ind;
5022 /* default label */
5023 gsym_addr(b, c);
5024 /* break label */
5025 gsym(a);
5026 } else
5027 if (tok == TOK_CASE) {
5028 int v1, v2;
5029 if (!case_sym)
5030 expect("switch");
5031 next();
5032 v1 = expr_const();
5033 v2 = v1;
5034 if (gnu_ext && tok == TOK_DOTS) {
5035 next();
5036 v2 = expr_const();
5037 if (v2 < v1)
5038 tcc_warning("empty case range");
5040 /* since a case is like a label, we must skip it with a jmp */
5041 b = gjmp(0);
5042 gsym(*case_sym);
5043 vseti(case_reg, 0);
5044 vdup();
5045 vpushi(v1);
5046 if (v1 == v2) {
5047 gen_op(TOK_EQ);
5048 *case_sym = gtst(1, 0);
5049 } else {
5050 gen_op(TOK_GE);
5051 *case_sym = gtst(1, 0);
5052 vseti(case_reg, 0);
5053 vpushi(v2);
5054 gen_op(TOK_LE);
5055 *case_sym = gtst(1, *case_sym);
5057 case_reg = gv(RC_INT);
5058 vpop();
5059 gsym(b);
5060 skip(':');
5061 is_expr = 0;
5062 goto block_after_label;
5063 } else
5064 if (tok == TOK_DEFAULT) {
5065 next();
5066 skip(':');
5067 if (!def_sym)
5068 expect("switch");
5069 if (*def_sym)
5070 tcc_error("too many 'default'");
5071 *def_sym = ind;
5072 is_expr = 0;
5073 goto block_after_label;
5074 } else
5075 if (tok == TOK_GOTO) {
5076 next();
5077 if (tok == '*' && gnu_ext) {
5078 /* computed goto */
5079 next();
5080 gexpr();
5081 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
5082 expect("pointer");
5083 ggoto();
5084 } else if (tok >= TOK_UIDENT) {
5085 s = label_find(tok);
5086 /* put forward definition if needed */
5087 if (!s) {
5088 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
5089 } else {
5090 if (s->r == LABEL_DECLARED)
5091 s->r = LABEL_FORWARD;
5093 /* label already defined */
5094 if (vla_flags & VLA_IN_SCOPE) {
5095 /* If VLAs are in use, save the current stack pointer and
5096 reset the stack pointer to what it was at function entry
5097 (label will restore stack pointer in inner scopes) */
5098 vla_sp_save();
5099 gen_vla_sp_restore(vla_sp_root_loc);
5101 if (s->r & LABEL_FORWARD)
5102 s->jnext = gjmp(s->jnext);
5103 else
5104 gjmp_addr(s->jnext);
5105 next();
5106 } else {
5107 expect("label identifier");
5109 skip(';');
5110 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
5111 asm_instr();
5112 } else {
5113 b = is_label();
5114 if (b) {
5115 /* label case */
5116 if (vla_flags & VLA_IN_SCOPE) {
5117 /* save/restore stack pointer across label
5118 this is a no-op when combined with the load immediately
5119 after the label unless we arrive via goto */
5120 vla_sp_save();
5122 s = label_find(b);
5123 if (s) {
5124 if (s->r == LABEL_DEFINED)
5125 tcc_error("duplicate label '%s'", get_tok_str(s->v, NULL));
5126 gsym(s->jnext);
5127 s->r = LABEL_DEFINED;
5128 } else {
5129 s = label_push(&global_label_stack, b, LABEL_DEFINED);
5131 s->jnext = ind;
5132 if (vla_flags & VLA_IN_SCOPE) {
5133 gen_vla_sp_restore(*vla_sp_loc);
5134 vla_flags |= VLA_NEED_NEW_FRAME;
5136 /* we accept this, but it is a mistake */
5137 block_after_label:
5138 if (tok == '}') {
5139 tcc_warning("deprecated use of label at end of compound statement");
5140 } else {
5141 if (is_expr)
5142 vpop();
5143 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
5145 } else {
5146 /* expression case */
5147 if (tok != ';') {
5148 if (is_expr) {
5149 vpop();
5150 gexpr();
5151 } else {
5152 gexpr();
5153 vpop();
5156 skip(';');
5161 /* t is the array or struct type. c is the array or struct
5162 address. cur_index/cur_field is the pointer to the current
5163 value. 'size_only' is true if only size info is needed (only used
5164 in arrays) */
5165 static void decl_designator(CType *type, Section *sec, unsigned long c,
5166 int *cur_index, Sym **cur_field,
5167 int size_only)
5169 Sym *s, *f;
5170 int notfirst, index, index_last, align, l, nb_elems, elem_size;
5171 CType type1;
5173 notfirst = 0;
5174 elem_size = 0;
5175 nb_elems = 1;
5176 if (gnu_ext && (l = is_label()) != 0)
5177 goto struct_field;
5178 while (tok == '[' || tok == '.') {
5179 if (tok == '[') {
5180 if (!(type->t & VT_ARRAY))
5181 expect("array type");
5182 s = type->ref;
5183 next();
5184 index = expr_const();
5185 if (index < 0 || (s->c >= 0 && index >= s->c))
5186 expect("invalid index");
5187 if (tok == TOK_DOTS && gnu_ext) {
5188 next();
5189 index_last = expr_const();
5190 if (index_last < 0 ||
5191 (s->c >= 0 && index_last >= s->c) ||
5192 index_last < index)
5193 expect("invalid index");
5194 } else {
5195 index_last = index;
5197 skip(']');
5198 if (!notfirst)
5199 *cur_index = index_last;
5200 type = pointed_type(type);
5201 elem_size = type_size(type, &align);
5202 c += index * elem_size;
5203 /* NOTE: we only support ranges for last designator */
5204 nb_elems = index_last - index + 1;
5205 if (nb_elems != 1) {
5206 notfirst = 1;
5207 break;
5209 } else {
5210 next();
5211 l = tok;
5212 next();
5213 struct_field:
5214 if ((type->t & VT_BTYPE) != VT_STRUCT)
5215 expect("struct/union type");
5216 s = type->ref;
5217 l |= SYM_FIELD;
5218 f = s->next;
5219 while (f) {
5220 if (f->v == l)
5221 break;
5222 f = f->next;
5224 if (!f)
5225 expect("field");
5226 if (!notfirst)
5227 *cur_field = f;
5228 /* XXX: fix this mess by using explicit storage field */
5229 type1 = f->type;
5230 type1.t |= (type->t & ~VT_TYPE);
5231 type = &type1;
5232 c += f->c;
5234 notfirst = 1;
5236 if (notfirst) {
5237 if (tok == '=') {
5238 next();
5239 } else {
5240 if (!gnu_ext)
5241 expect("=");
5243 } else {
5244 if (type->t & VT_ARRAY) {
5245 index = *cur_index;
5246 type = pointed_type(type);
5247 c += index * type_size(type, &align);
5248 } else {
5249 f = *cur_field;
5250 if (!f)
5251 tcc_error("too many field init");
5252 /* XXX: fix this mess by using explicit storage field */
5253 type1 = f->type;
5254 type1.t |= (type->t & ~VT_TYPE);
5255 type = &type1;
5256 c += f->c;
5259 decl_initializer(type, sec, c, 0, size_only);
5261 /* XXX: make it more general */
5262 if (!size_only && nb_elems > 1) {
5263 unsigned long c_end;
5264 uint8_t *src, *dst;
5265 int i;
5267 if (!sec)
5268 tcc_error("range init not supported yet for dynamic storage");
5269 c_end = c + nb_elems * elem_size;
5270 if (c_end > sec->data_allocated)
5271 section_realloc(sec, c_end);
5272 src = sec->data + c;
5273 dst = src;
5274 for(i = 1; i < nb_elems; i++) {
5275 dst += elem_size;
5276 memcpy(dst, src, elem_size);
5281 #define EXPR_VAL 0
5282 #define EXPR_CONST 1
5283 #define EXPR_ANY 2
5285 /* store a value or an expression directly in global data or in local array */
5286 static void init_putv(CType *type, Section *sec, unsigned long c,
5287 int v, int expr_type)
5289 int saved_global_expr, bt, bit_pos, bit_size;
5290 void *ptr;
5291 unsigned long long bit_mask;
5292 CType dtype;
5294 switch(expr_type) {
5295 case EXPR_VAL:
5296 vpushi(v);
5297 break;
5298 case EXPR_CONST:
5299 /* compound literals must be allocated globally in this case */
5300 saved_global_expr = global_expr;
5301 global_expr = 1;
5302 expr_const1();
5303 global_expr = saved_global_expr;
5304 /* NOTE: symbols are accepted */
5305 if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
5306 tcc_error("initializer element is not constant");
5307 break;
5308 case EXPR_ANY:
5309 expr_eq();
5310 break;
5313 dtype = *type;
5314 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
5316 if (sec) {
5317 /* XXX: not portable */
5318 /* XXX: generate error if incorrect relocation */
5319 gen_assign_cast(&dtype);
5320 bt = type->t & VT_BTYPE;
5321 /* we'll write at most 16 bytes */
5322 if (c + 16 > sec->data_allocated) {
5323 section_realloc(sec, c + 16);
5325 ptr = sec->data + c;
5326 /* XXX: make code faster ? */
5327 if (!(type->t & VT_BITFIELD)) {
5328 bit_pos = 0;
5329 bit_size = 32;
5330 bit_mask = -1LL;
5331 } else {
5332 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5333 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
5334 bit_mask = (1LL << bit_size) - 1;
5336 if ((vtop->r & VT_SYM) &&
5337 (bt == VT_BYTE ||
5338 bt == VT_SHORT ||
5339 bt == VT_DOUBLE ||
5340 bt == VT_LDOUBLE ||
5341 bt == VT_LLONG ||
5342 (bt == VT_INT && bit_size != 32)))
5343 tcc_error("initializer element is not computable at load time");
5344 switch(bt) {
5345 /* XXX: when cross-compiling we assume that each type has the
5346 same representation on host and target, which is likely to
5347 be wrong in the case of long double */
5348 case VT_BOOL:
5349 vtop->c.i = (vtop->c.i != 0);
5350 case VT_BYTE:
5351 *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5352 break;
5353 case VT_SHORT:
5354 *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5355 break;
5356 case VT_DOUBLE:
5357 *(double *)ptr = vtop->c.d;
5358 break;
5359 case VT_LDOUBLE:
5360 *(long double *)ptr = vtop->c.ld;
5361 break;
5362 case VT_LLONG:
5363 *(long long *)ptr |= (vtop->c.ll & bit_mask) << bit_pos;
5364 break;
5365 case VT_PTR: {
5366 addr_t val = (vtop->c.ptr_offset & bit_mask) << bit_pos;
5367 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
5368 if (vtop->r & VT_SYM)
5369 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
5370 else
5371 *(addr_t *)ptr |= val;
5372 #else
5373 if (vtop->r & VT_SYM)
5374 greloc(sec, vtop->sym, c, R_DATA_PTR);
5375 *(addr_t *)ptr |= val;
5376 #endif
5377 break;
5379 default: {
5380 int val = (vtop->c.i & bit_mask) << bit_pos;
5381 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
5382 if (vtop->r & VT_SYM)
5383 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
5384 else
5385 *(int *)ptr |= val;
5386 #else
5387 if (vtop->r & VT_SYM)
5388 greloc(sec, vtop->sym, c, R_DATA_PTR);
5389 *(int *)ptr |= val;
5390 #endif
5391 break;
5394 vtop--;
5395 } else {
5396 vset(&dtype, VT_LOCAL|VT_LVAL, c);
5397 vswap();
5398 vstore();
5399 vpop();
5403 /* put zeros for variable based init */
5404 static void init_putz(CType *t, Section *sec, unsigned long c, int size)
5406 if (sec) {
5407 /* nothing to do because globals are already set to zero */
5408 } else {
5409 vpush_global_sym(&func_old_type, TOK_memset);
5410 vseti(VT_LOCAL, c);
5411 #ifdef TCC_TARGET_ARM
5412 vpushs(size);
5413 vpushi(0);
5414 #else
5415 vpushi(0);
5416 vpushs(size);
5417 #endif
5418 gfunc_call(3);
5422 /* 't' contains the type and storage info. 'c' is the offset of the
5423 object in section 'sec'. If 'sec' is NULL, it means stack based
5424 allocation. 'first' is true if array '{' must be read (multi
5425 dimension implicit array init handling). 'size_only' is true if
5426 size only evaluation is wanted (only for arrays). */
5427 static void decl_initializer(CType *type, Section *sec, unsigned long c,
5428 int first, int size_only)
5430 int index, array_length, n, no_oblock, nb, parlevel, parlevel1, i;
5431 int size1, align1, expr_type;
5432 Sym *s, *f;
5433 CType *t1;
5435 if (type->t & VT_VLA) {
5436 int a;
5438 /* save current stack pointer */
5439 if (vla_flags & VLA_NEED_NEW_FRAME) {
5440 vla_sp_save();
5441 vla_flags = VLA_IN_SCOPE;
5442 vla_sp_loc = &vla_sp_loc_tmp;
5445 vla_runtime_type_size(type, &a);
5446 gen_vla_alloc(type, a);
5447 vset(type, VT_LOCAL|VT_LVAL, c);
5448 vswap();
5449 vstore();
5450 vpop();
5451 } else if (type->t & VT_ARRAY) {
5452 s = type->ref;
5453 n = s->c;
5454 array_length = 0;
5455 t1 = pointed_type(type);
5456 size1 = type_size(t1, &align1);
5458 no_oblock = 1;
5459 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
5460 tok == '{') {
5461 if (tok != '{')
5462 tcc_error("character array initializer must be a literal,"
5463 " optionally enclosed in braces");
5464 skip('{');
5465 no_oblock = 0;
5468 /* only parse strings here if correct type (otherwise: handle
5469 them as ((w)char *) expressions */
5470 if ((tok == TOK_LSTR &&
5471 #ifdef TCC_TARGET_PE
5472 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
5473 #else
5474 (t1->t & VT_BTYPE) == VT_INT
5475 #endif
5476 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
5477 while (tok == TOK_STR || tok == TOK_LSTR) {
5478 int cstr_len, ch;
5479 CString *cstr;
5481 cstr = tokc.cstr;
5482 /* compute maximum number of chars wanted */
5483 if (tok == TOK_STR)
5484 cstr_len = cstr->size;
5485 else
5486 cstr_len = cstr->size / sizeof(nwchar_t);
5487 cstr_len--;
5488 nb = cstr_len;
5489 if (n >= 0 && nb > (n - array_length))
5490 nb = n - array_length;
5491 if (!size_only) {
5492 if (cstr_len > nb)
5493 tcc_warning("initializer-string for array is too long");
5494 /* in order to go faster for common case (char
5495 string in global variable, we handle it
5496 specifically */
5497 if (sec && tok == TOK_STR && size1 == 1) {
5498 memcpy(sec->data + c + array_length, cstr->data, nb);
5499 } else {
5500 for(i=0;i<nb;i++) {
5501 if (tok == TOK_STR)
5502 ch = ((unsigned char *)cstr->data)[i];
5503 else
5504 ch = ((nwchar_t *)cstr->data)[i];
5505 init_putv(t1, sec, c + (array_length + i) * size1,
5506 ch, EXPR_VAL);
5510 array_length += nb;
5511 next();
5513 /* only add trailing zero if enough storage (no
5514 warning in this case since it is standard) */
5515 if (n < 0 || array_length < n) {
5516 if (!size_only) {
5517 init_putv(t1, sec, c + (array_length * size1), 0, EXPR_VAL);
5519 array_length++;
5521 } else {
5522 index = 0;
5523 while (tok != '}') {
5524 decl_designator(type, sec, c, &index, NULL, size_only);
5525 if (n >= 0 && index >= n)
5526 tcc_error("index too large");
5527 /* must put zero in holes (note that doing it that way
5528 ensures that it even works with designators) */
5529 if (!size_only && array_length < index) {
5530 init_putz(t1, sec, c + array_length * size1,
5531 (index - array_length) * size1);
5533 index++;
5534 if (index > array_length)
5535 array_length = index;
5536 /* special test for multi dimensional arrays (may not
5537 be strictly correct if designators are used at the
5538 same time) */
5539 if (index >= n && no_oblock)
5540 break;
5541 if (tok == '}')
5542 break;
5543 skip(',');
5546 if (!no_oblock)
5547 skip('}');
5548 /* put zeros at the end */
5549 if (!size_only && n >= 0 && array_length < n) {
5550 init_putz(t1, sec, c + array_length * size1,
5551 (n - array_length) * size1);
5553 /* patch type size if needed */
5554 if (n < 0)
5555 s->c = array_length;
5556 } else if ((type->t & VT_BTYPE) == VT_STRUCT &&
5557 (sec || !first || tok == '{')) {
5559 /* NOTE: the previous test is a specific case for automatic
5560 struct/union init */
5561 /* XXX: union needs only one init */
5563 if (tok == '(') {
5564 AttributeDef ad1;
5565 CType type1;
5566 next();
5567 if (tok != '(') {
5568 if (!parse_btype(&type1, &ad1))
5569 expect("cast");
5570 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
5571 #if 0
5572 if (!is_assignable_types(type, &type1))
5573 tcc_error("invalid type for cast");
5574 #endif
5575 skip(')');
5576 } else
5577 unget_tok(tok);
5579 no_oblock = 1;
5580 if (first || tok == '{') {
5581 skip('{');
5582 no_oblock = 0;
5584 s = type->ref;
5585 f = s->next;
5586 array_length = 0;
5587 index = 0;
5588 n = s->c;
5589 while (tok != '}') {
5590 decl_designator(type, sec, c, NULL, &f, size_only);
5591 index = f->c;
5592 if (!size_only && array_length < index) {
5593 init_putz(type, sec, c + array_length,
5594 index - array_length);
5596 index = index + type_size(&f->type, &align1);
5597 if (index > array_length)
5598 array_length = index;
5600 /* gr: skip fields from same union - ugly. */
5601 while (f->next) {
5602 int align = 0;
5603 int f_size = type_size(&f->type, &align);
5604 int f_type = (f->type.t & VT_BTYPE);
5606 ///printf("index: %2d %08x -- %2d %08x\n", f->c, f->type.t, f->next->c, f->next->type.t);
5607 /* test for same offset */
5608 if (f->next->c != f->c)
5609 break;
5610 if ((f_type == VT_STRUCT) && (f_size == 0)) {
5612 Lets assume a structure of size 0 can't be a member of the union.
5613 This allow to compile the following code from a linux kernel v2.4.26
5614 typedef struct { } rwlock_t;
5615 struct fs_struct {
5616 int count;
5617 rwlock_t lock;
5618 int umask;
5620 struct fs_struct init_fs = { { (1) }, (rwlock_t) {}, 0022, };
5621 tcc-0.9.23 can succesfully compile this version of the kernel.
5622 gcc don't have problems with this code too.
5624 break;
5626 /* if yes, test for bitfield shift */
5627 if ((f->type.t & VT_BITFIELD) && (f->next->type.t & VT_BITFIELD)) {
5628 int bit_pos_1 = (f->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5629 int bit_pos_2 = (f->next->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5630 //printf("bitfield %d %d\n", bit_pos_1, bit_pos_2);
5631 if (bit_pos_1 != bit_pos_2)
5632 break;
5634 f = f->next;
5637 f = f->next;
5638 if (no_oblock && f == NULL)
5639 break;
5640 if (tok == '}')
5641 break;
5642 skip(',');
5644 /* put zeros at the end */
5645 if (!size_only && array_length < n) {
5646 init_putz(type, sec, c + array_length,
5647 n - array_length);
5649 if (!no_oblock)
5650 skip('}');
5651 } else if (tok == '{') {
5652 next();
5653 decl_initializer(type, sec, c, first, size_only);
5654 skip('}');
5655 } else if (size_only) {
5656 /* just skip expression */
5657 parlevel = parlevel1 = 0;
5658 while ((parlevel > 0 || parlevel1 > 0 ||
5659 (tok != '}' && tok != ',')) && tok != -1) {
5660 if (tok == '(')
5661 parlevel++;
5662 else if (tok == ')') {
5663 if (parlevel == 0 && parlevel1 == 0)
5664 break;
5665 parlevel--;
5667 else if (tok == '{')
5668 parlevel1++;
5669 else if (tok == '}') {
5670 if (parlevel == 0 && parlevel1 == 0)
5671 break;
5672 parlevel1--;
5674 next();
5676 } else {
5677 /* currently, we always use constant expression for globals
5678 (may change for scripting case) */
5679 expr_type = EXPR_CONST;
5680 if (!sec)
5681 expr_type = EXPR_ANY;
5682 init_putv(type, sec, c, 0, expr_type);
5686 /* parse an initializer for type 't' if 'has_init' is non zero, and
5687 allocate space in local or global data space ('r' is either
5688 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
5689 variable 'v' with an associated name represented by 'asm_label' of
5690 scope 'scope' is declared before initializers are parsed. If 'v' is
5691 zero, then a reference to the new object is put in the value stack.
5692 If 'has_init' is 2, a special parsing is done to handle string
5693 constants. */
5694 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
5695 int has_init, int v, char *asm_label,
5696 int scope)
5698 int size, align, addr, data_offset;
5699 int level;
5700 ParseState saved_parse_state = {0};
5701 TokenString init_str;
5702 Section *sec;
5703 Sym *flexible_array;
5705 flexible_array = NULL;
5706 if ((type->t & VT_BTYPE) == VT_STRUCT) {
5707 Sym *field = type->ref->next;
5708 if (field) {
5709 while (field->next)
5710 field = field->next;
5711 if (field->type.t & VT_ARRAY && field->type.ref->c < 0)
5712 flexible_array = field;
5716 size = type_size(type, &align);
5717 /* If unknown size, we must evaluate it before
5718 evaluating initializers because
5719 initializers can generate global data too
5720 (e.g. string pointers or ISOC99 compound
5721 literals). It also simplifies local
5722 initializers handling */
5723 tok_str_new(&init_str);
5724 if (size < 0 || (flexible_array && has_init)) {
5725 if (!has_init)
5726 tcc_error("unknown type size");
5727 /* get all init string */
5728 if (has_init == 2) {
5729 /* only get strings */
5730 while (tok == TOK_STR || tok == TOK_LSTR) {
5731 tok_str_add_tok(&init_str);
5732 next();
5734 } else {
5735 level = 0;
5736 while (level > 0 || (tok != ',' && tok != ';')) {
5737 if (tok < 0)
5738 tcc_error("unexpected end of file in initializer");
5739 tok_str_add_tok(&init_str);
5740 if (tok == '{')
5741 level++;
5742 else if (tok == '}') {
5743 level--;
5744 if (level <= 0) {
5745 next();
5746 break;
5749 next();
5752 tok_str_add(&init_str, -1);
5753 tok_str_add(&init_str, 0);
5755 /* compute size */
5756 save_parse_state(&saved_parse_state);
5758 macro_ptr = init_str.str;
5759 next();
5760 decl_initializer(type, NULL, 0, 1, 1);
5761 /* prepare second initializer parsing */
5762 macro_ptr = init_str.str;
5763 next();
5765 /* if still unknown size, error */
5766 size = type_size(type, &align);
5767 if (size < 0)
5768 tcc_error("unknown type size");
5770 if (flexible_array)
5771 size += flexible_array->type.ref->c * pointed_size(&flexible_array->type);
5772 /* take into account specified alignment if bigger */
5773 if (ad->a.aligned) {
5774 if (ad->a.aligned > align)
5775 align = ad->a.aligned;
5776 } else if (ad->a.packed) {
5777 align = 1;
5779 if ((r & VT_VALMASK) == VT_LOCAL) {
5780 sec = NULL;
5781 #ifdef CONFIG_TCC_BCHECK
5782 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5783 loc--;
5785 #endif
5786 loc = (loc - size) & -align;
5787 addr = loc;
5788 #ifdef CONFIG_TCC_BCHECK
5789 /* handles bounds */
5790 /* XXX: currently, since we do only one pass, we cannot track
5791 '&' operators, so we add only arrays */
5792 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5793 addr_t *bounds_ptr;
5794 /* add padding between regions */
5795 loc--;
5796 /* then add local bound info */
5797 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(addr_t));
5798 bounds_ptr[0] = addr;
5799 bounds_ptr[1] = size;
5801 #endif
5802 if (v) {
5803 /* local variable */
5804 sym_push(v, type, r, addr);
5805 } else {
5806 /* push local reference */
5807 vset(type, r, addr);
5809 } else {
5810 Sym *sym;
5812 sym = NULL;
5813 if (v && scope == VT_CONST) {
5814 /* see if the symbol was already defined */
5815 sym = sym_find(v);
5816 if (sym) {
5817 if (!is_compatible_types(&sym->type, type))
5818 tcc_error("incompatible types for redefinition of '%s'",
5819 get_tok_str(v, NULL));
5820 if (sym->type.t & VT_EXTERN) {
5821 /* if the variable is extern, it was not allocated */
5822 sym->type.t &= ~VT_EXTERN;
5823 /* set array size if it was omitted in extern
5824 declaration */
5825 if ((sym->type.t & VT_ARRAY) &&
5826 sym->type.ref->c < 0 &&
5827 type->ref->c >= 0)
5828 sym->type.ref->c = type->ref->c;
5829 } else {
5830 /* we accept several definitions of the same
5831 global variable. this is tricky, because we
5832 must play with the SHN_COMMON type of the symbol */
5833 /* XXX: should check if the variable was already
5834 initialized. It is incorrect to initialized it
5835 twice */
5836 /* no init data, we won't add more to the symbol */
5837 if (!has_init)
5838 goto no_alloc;
5843 /* allocate symbol in corresponding section */
5844 sec = ad->section;
5845 if (!sec) {
5846 if (has_init)
5847 sec = data_section;
5848 else if (tcc_state->nocommon)
5849 sec = bss_section;
5851 if (sec) {
5852 data_offset = sec->data_offset;
5853 data_offset = (data_offset + align - 1) & -align;
5854 addr = data_offset;
5855 /* very important to increment global pointer at this time
5856 because initializers themselves can create new initializers */
5857 data_offset += size;
5858 #ifdef CONFIG_TCC_BCHECK
5859 /* add padding if bound check */
5860 if (tcc_state->do_bounds_check)
5861 data_offset++;
5862 #endif
5863 sec->data_offset = data_offset;
5864 /* allocate section space to put the data */
5865 if (sec->sh_type != SHT_NOBITS &&
5866 data_offset > sec->data_allocated)
5867 section_realloc(sec, data_offset);
5868 /* align section if needed */
5869 if (align > sec->sh_addralign)
5870 sec->sh_addralign = align;
5871 } else {
5872 addr = 0; /* avoid warning */
5875 if (v) {
5876 if (scope != VT_CONST || !sym) {
5877 sym = sym_push(v, type, r | VT_SYM, 0);
5878 sym->asm_label = asm_label;
5880 /* update symbol definition */
5881 if (sec) {
5882 put_extern_sym(sym, sec, addr, size);
5883 } else {
5884 ElfW(Sym) *esym;
5885 /* put a common area */
5886 put_extern_sym(sym, NULL, align, size);
5887 /* XXX: find a nicer way */
5888 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
5889 esym->st_shndx = SHN_COMMON;
5891 } else {
5892 /* push global reference */
5893 sym = get_sym_ref(type, sec, addr, size);
5894 vpushsym(type, sym);
5896 /* patch symbol weakness */
5897 if (type->t & VT_WEAK)
5898 weaken_symbol(sym);
5899 apply_visibility(sym, type);
5900 #ifdef CONFIG_TCC_BCHECK
5901 /* handles bounds now because the symbol must be defined
5902 before for the relocation */
5903 if (tcc_state->do_bounds_check) {
5904 addr_t *bounds_ptr;
5906 greloc(bounds_section, sym, bounds_section->data_offset, R_DATA_PTR);
5907 /* then add global bound info */
5908 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(addr_t));
5909 bounds_ptr[0] = 0; /* relocated */
5910 bounds_ptr[1] = size;
5912 #endif
5914 if (has_init || (type->t & VT_VLA)) {
5915 decl_initializer(type, sec, addr, 1, 0);
5916 /* restore parse state if needed */
5917 if (init_str.str) {
5918 tok_str_free(init_str.str);
5919 restore_parse_state(&saved_parse_state);
5921 /* patch flexible array member size back to -1, */
5922 /* for possible subsequent similar declarations */
5923 if (flexible_array)
5924 flexible_array->type.ref->c = -1;
5926 no_alloc: ;
5929 static void put_func_debug(Sym *sym)
5931 char buf[512];
5933 /* stabs info */
5934 /* XXX: we put here a dummy type */
5935 snprintf(buf, sizeof(buf), "%s:%c1",
5936 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
5937 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
5938 cur_text_section, sym->c);
5939 /* //gr gdb wants a line at the function */
5940 put_stabn(N_SLINE, 0, file->line_num, 0);
5941 last_ind = 0;
5942 last_line_num = 0;
5945 /* parse an old style function declaration list */
5946 /* XXX: check multiple parameter */
5947 static void func_decl_list(Sym *func_sym)
5949 AttributeDef ad;
5950 int v;
5951 Sym *s;
5952 CType btype, type;
5954 /* parse each declaration */
5955 while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF &&
5956 tok != TOK_ASM1 && tok != TOK_ASM2 && tok != TOK_ASM3) {
5957 if (!parse_btype(&btype, &ad))
5958 expect("declaration list");
5959 if (((btype.t & VT_BTYPE) == VT_ENUM ||
5960 (btype.t & VT_BTYPE) == VT_STRUCT) &&
5961 tok == ';') {
5962 /* we accept no variable after */
5963 } else {
5964 for(;;) {
5965 type = btype;
5966 type_decl(&type, &ad, &v, TYPE_DIRECT);
5967 /* find parameter in function parameter list */
5968 s = func_sym->next;
5969 while (s != NULL) {
5970 if ((s->v & ~SYM_FIELD) == v)
5971 goto found;
5972 s = s->next;
5974 tcc_error("declaration for parameter '%s' but no such parameter",
5975 get_tok_str(v, NULL));
5976 found:
5977 /* check that no storage specifier except 'register' was given */
5978 if (type.t & VT_STORAGE)
5979 tcc_error("storage class specified for '%s'", get_tok_str(v, NULL));
5980 convert_parameter_type(&type);
5981 /* we can add the type (NOTE: it could be local to the function) */
5982 s->type = type;
5983 /* accept other parameters */
5984 if (tok == ',')
5985 next();
5986 else
5987 break;
5990 skip(';');
5994 /* parse a function defined by symbol 'sym' and generate its code in
5995 'cur_text_section' */
5996 static void gen_function(Sym *sym)
5998 int saved_nocode_wanted = nocode_wanted;
5999 nocode_wanted = 0;
6000 ind = cur_text_section->data_offset;
6001 /* NOTE: we patch the symbol size later */
6002 put_extern_sym(sym, cur_text_section, ind, 0);
6003 funcname = get_tok_str(sym->v, NULL);
6004 func_ind = ind;
6005 /* Initialize VLA state */
6006 vla_sp_loc = &vla_sp_root_loc;
6007 vla_flags = VLA_NEED_NEW_FRAME;
6008 /* put debug symbol */
6009 if (tcc_state->do_debug)
6010 put_func_debug(sym);
6011 /* push a dummy symbol to enable local sym storage */
6012 sym_push2(&local_stack, SYM_FIELD, 0, 0);
6013 gfunc_prolog(&sym->type);
6014 #ifdef CONFIG_TCC_BCHECK
6015 if (tcc_state->do_bounds_check
6016 && !strcmp(get_tok_str(sym->v, NULL), "main")) {
6017 int i;
6019 sym = local_stack;
6020 for (i = 0, sym = local_stack; i < 2; i++, sym = sym->prev) {
6021 if (sym->v & SYM_FIELD || sym->prev->v & SYM_FIELD)
6022 break;
6023 vpush_global_sym(&func_old_type, TOK___bound_main_arg);
6024 vset(&sym->type, sym->r, sym->c);
6025 gfunc_call(1);
6028 #endif
6029 rsym = 0;
6030 block(NULL, NULL, NULL, NULL, 0, 0);
6031 gsym(rsym);
6032 gfunc_epilog();
6033 cur_text_section->data_offset = ind;
6034 label_pop(&global_label_stack, NULL);
6035 /* reset local stack */
6036 scope_stack_bottom = NULL;
6037 sym_pop(&local_stack, NULL);
6038 /* end of function */
6039 /* patch symbol size */
6040 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
6041 ind - func_ind;
6042 /* patch symbol weakness (this definition overrules any prototype) */
6043 if (sym->type.t & VT_WEAK)
6044 weaken_symbol(sym);
6045 apply_visibility(sym, &sym->type);
6046 if (tcc_state->do_debug) {
6047 put_stabn(N_FUN, 0, 0, ind - func_ind);
6049 /* It's better to crash than to generate wrong code */
6050 cur_text_section = NULL;
6051 funcname = ""; /* for safety */
6052 func_vt.t = VT_VOID; /* for safety */
6053 func_var = 0; /* for safety */
6054 ind = 0; /* for safety */
6055 nocode_wanted = saved_nocode_wanted;
6058 ST_FUNC void gen_inline_functions(void)
6060 Sym *sym;
6061 int *str, inline_generated, i;
6062 struct InlineFunc *fn;
6064 /* iterate while inline function are referenced */
6065 for(;;) {
6066 inline_generated = 0;
6067 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
6068 fn = tcc_state->inline_fns[i];
6069 sym = fn->sym;
6070 if (sym && sym->c) {
6071 /* the function was used: generate its code and
6072 convert it to a normal function */
6073 str = fn->token_str;
6074 fn->sym = NULL;
6075 if (file)
6076 pstrcpy(file->filename, sizeof file->filename, fn->filename);
6077 sym->r = VT_SYM | VT_CONST;
6078 sym->type.t &= ~VT_INLINE;
6080 macro_ptr = str;
6081 next();
6082 cur_text_section = text_section;
6083 gen_function(sym);
6084 macro_ptr = NULL; /* fail safe */
6086 inline_generated = 1;
6089 if (!inline_generated)
6090 break;
6092 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
6093 fn = tcc_state->inline_fns[i];
6094 str = fn->token_str;
6095 tok_str_free(str);
6097 dynarray_reset(&tcc_state->inline_fns, &tcc_state->nb_inline_fns);
6100 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
6101 static int decl0(int l, int is_for_loop_init)
6103 int v, has_init, r;
6104 CType type, btype;
6105 Sym *sym;
6106 AttributeDef ad;
6108 while (1) {
6109 if (!parse_btype(&btype, &ad)) {
6110 if (is_for_loop_init)
6111 return 0;
6112 /* skip redundant ';' */
6113 /* XXX: find more elegant solution */
6114 if (tok == ';') {
6115 next();
6116 continue;
6118 if (l == VT_CONST &&
6119 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
6120 /* global asm block */
6121 asm_global_instr();
6122 continue;
6124 /* special test for old K&R protos without explicit int
6125 type. Only accepted when defining global data */
6126 if (l == VT_LOCAL || tok < TOK_DEFINE)
6127 break;
6128 btype.t = VT_INT;
6130 if (((btype.t & VT_BTYPE) == VT_ENUM ||
6131 (btype.t & VT_BTYPE) == VT_STRUCT) &&
6132 tok == ';') {
6133 if ((btype.t & VT_BTYPE) == VT_STRUCT) {
6134 int v = btype.ref->v;
6135 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) >= SYM_FIRST_ANOM)
6136 tcc_warning("unnamed struct/union that defines no instances");
6138 next();
6139 continue;
6141 while (1) { /* iterate thru each declaration */
6142 char *asm_label; // associated asm label
6143 type = btype;
6144 type_decl(&type, &ad, &v, TYPE_DIRECT);
6145 #if 0
6147 char buf[500];
6148 type_to_str(buf, sizeof(buf), t, get_tok_str(v, NULL));
6149 printf("type = '%s'\n", buf);
6151 #endif
6152 if ((type.t & VT_BTYPE) == VT_FUNC) {
6153 if ((type.t & VT_STATIC) && (l == VT_LOCAL)) {
6154 tcc_error("function without file scope cannot be static");
6156 /* if old style function prototype, we accept a
6157 declaration list */
6158 sym = type.ref;
6159 if (sym->c == FUNC_OLD)
6160 func_decl_list(sym);
6163 asm_label = NULL;
6164 if (gnu_ext && (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
6165 CString astr;
6167 asm_label_instr(&astr);
6168 asm_label = tcc_strdup(astr.data);
6169 cstr_free(&astr);
6171 /* parse one last attribute list, after asm label */
6172 parse_attribute(&ad);
6175 if (ad.a.weak)
6176 type.t |= VT_WEAK;
6177 #ifdef TCC_TARGET_PE
6178 if (ad.a.func_import)
6179 type.t |= VT_IMPORT;
6180 if (ad.a.func_export)
6181 type.t |= VT_EXPORT;
6182 #endif
6183 type.t |= ad.a.visibility << VT_VIS_SHIFT;
6185 if (tok == '{') {
6186 if (l == VT_LOCAL)
6187 tcc_error("cannot use local functions");
6188 if ((type.t & VT_BTYPE) != VT_FUNC)
6189 expect("function definition");
6191 /* reject abstract declarators in function definition */
6192 sym = type.ref;
6193 while ((sym = sym->next) != NULL)
6194 if (!(sym->v & ~SYM_FIELD))
6195 expect("identifier");
6197 /* XXX: cannot do better now: convert extern line to static inline */
6198 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
6199 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
6201 sym = sym_find(v);
6202 if (sym) {
6203 Sym *ref;
6204 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
6205 goto func_error1;
6207 ref = sym->type.ref;
6208 if (0 == ref->a.func_proto)
6209 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
6211 /* use func_call from prototype if not defined */
6212 if (ref->a.func_call != FUNC_CDECL
6213 && type.ref->a.func_call == FUNC_CDECL)
6214 type.ref->a.func_call = ref->a.func_call;
6216 /* use export from prototype */
6217 if (ref->a.func_export)
6218 type.ref->a.func_export = 1;
6220 /* use static from prototype */
6221 if (sym->type.t & VT_STATIC)
6222 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
6224 /* If the definition has no visibility use the
6225 one from prototype. */
6226 if (! (type.t & VT_VIS_MASK))
6227 type.t |= sym->type.t & VT_VIS_MASK;
6229 if (!is_compatible_types(&sym->type, &type)) {
6230 func_error1:
6231 tcc_error("incompatible types for redefinition of '%s'",
6232 get_tok_str(v, NULL));
6234 type.ref->a.func_proto = 0;
6235 /* if symbol is already defined, then put complete type */
6236 sym->type = type;
6237 } else {
6238 /* put function symbol */
6239 sym = global_identifier_push(v, type.t, 0);
6240 sym->type.ref = type.ref;
6243 /* static inline functions are just recorded as a kind
6244 of macro. Their code will be emitted at the end of
6245 the compilation unit only if they are used */
6246 if ((type.t & (VT_INLINE | VT_STATIC)) ==
6247 (VT_INLINE | VT_STATIC)) {
6248 TokenString func_str;
6249 int block_level;
6250 struct InlineFunc *fn;
6251 const char *filename;
6253 tok_str_new(&func_str);
6255 block_level = 0;
6256 for(;;) {
6257 int t;
6258 if (tok == TOK_EOF)
6259 tcc_error("unexpected end of file");
6260 tok_str_add_tok(&func_str);
6261 t = tok;
6262 next();
6263 if (t == '{') {
6264 block_level++;
6265 } else if (t == '}') {
6266 block_level--;
6267 if (block_level == 0)
6268 break;
6271 tok_str_add(&func_str, -1);
6272 tok_str_add(&func_str, 0);
6273 filename = file ? file->filename : "";
6274 fn = tcc_malloc(sizeof *fn + strlen(filename));
6275 strcpy(fn->filename, filename);
6276 fn->sym = sym;
6277 fn->token_str = func_str.str;
6278 dynarray_add((void ***)&tcc_state->inline_fns, &tcc_state->nb_inline_fns, fn);
6280 } else {
6281 /* compute text section */
6282 cur_text_section = ad.section;
6283 if (!cur_text_section)
6284 cur_text_section = text_section;
6285 sym->r = VT_SYM | VT_CONST;
6286 gen_function(sym);
6288 break;
6289 } else {
6290 if (btype.t & VT_TYPEDEF) {
6291 /* save typedefed type */
6292 /* XXX: test storage specifiers ? */
6293 sym = sym_push(v, &type, 0, 0);
6294 sym->a = ad.a;
6295 sym->type.t |= VT_TYPEDEF;
6296 } else {
6297 r = 0;
6298 if ((type.t & VT_BTYPE) == VT_FUNC) {
6299 /* external function definition */
6300 /* specific case for func_call attribute */
6301 ad.a.func_proto = 1;
6302 type.ref->a = ad.a;
6303 } else if (!(type.t & VT_ARRAY)) {
6304 /* not lvalue if array */
6305 r |= lvalue_type(type.t);
6307 has_init = (tok == '=');
6308 if (has_init && (type.t & VT_VLA))
6309 tcc_error("Variable length array cannot be initialized");
6310 if ((btype.t & VT_EXTERN) || ((type.t & VT_BTYPE) == VT_FUNC) ||
6311 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
6312 !has_init && l == VT_CONST && type.ref->c < 0)) {
6313 /* external variable or function */
6314 /* NOTE: as GCC, uninitialized global static
6315 arrays of null size are considered as
6316 extern */
6317 sym = external_sym(v, &type, r, asm_label);
6319 if (ad.alias_target) {
6320 Section tsec;
6321 Elf32_Sym *esym;
6322 Sym *alias_target;
6324 alias_target = sym_find(ad.alias_target);
6325 if (!alias_target || !alias_target->c)
6326 tcc_error("unsupported forward __alias__ attribute");
6327 esym = &((Elf32_Sym *)symtab_section->data)[alias_target->c];
6328 tsec.sh_num = esym->st_shndx;
6329 put_extern_sym2(sym, &tsec, esym->st_value, esym->st_size, 0);
6331 } else {
6332 type.t |= (btype.t & VT_STATIC); /* Retain "static". */
6333 if (type.t & VT_STATIC)
6334 r |= VT_CONST;
6335 else
6336 r |= l;
6337 if (has_init)
6338 next();
6339 decl_initializer_alloc(&type, &ad, r, has_init, v, asm_label, l);
6342 if (tok != ',') {
6343 if (is_for_loop_init)
6344 return 1;
6345 skip(';');
6346 break;
6348 next();
6350 ad.a.aligned = 0;
6353 return 0;
6356 ST_FUNC void decl(int l)
6358 decl0(l, 0);