tccgen: scope levels for local symbols
[tinycc.git] / tccgen.c
blob042fb9284d2d2d887835b2490f995c22ad497752
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 *define_stack;
54 ST_DATA Sym *global_label_stack;
55 ST_DATA Sym *local_label_stack;
56 static int local_scope;
58 ST_DATA int vlas_in_scope; /* number of VLAs that are currently in scope */
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 */
62 ST_DATA SValue __vstack[1+VSTACK_SIZE], *vtop, *pvtop;
64 ST_DATA int const_wanted; /* true if constant wanted */
65 ST_DATA int nocode_wanted; /* true if no code generation wanted for an expression */
66 ST_DATA int global_expr; /* true if compound literals must be allocated globally (used during initializers parsing */
67 ST_DATA CType func_vt; /* current function return type (used by return instruction) */
68 ST_DATA int func_var; /* true if current function is variadic (used by return instruction) */
69 ST_DATA int func_vc;
70 ST_DATA int last_line_num, last_ind, func_ind; /* debug last line number and pc */
71 ST_DATA const char *funcname;
73 ST_DATA CType char_pointer_type, func_old_type, int_type, size_type;
75 /* ------------------------------------------------------------------------- */
76 static void gen_cast(CType *type);
77 static inline CType *pointed_type(CType *type);
78 static int is_compatible_types(CType *type1, CType *type2);
79 static int parse_btype(CType *type, AttributeDef *ad);
80 static void type_decl(CType *type, AttributeDef *ad, int *v, int td);
81 static void parse_expr_type(CType *type);
82 static void decl_initializer(CType *type, Section *sec, unsigned long c, int first, int size_only);
83 static void block(int *bsym, int *csym, int *case_sym, int *def_sym, int case_reg, int is_expr);
84 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r, int has_init, int v, int scope);
85 static int decl0(int l, int is_for_loop_init);
86 static void expr_eq(void);
87 static void expr_lor_const(void);
88 static void unary_type(CType *type);
89 static void vla_runtime_type_size(CType *type, int *a);
90 static void vla_sp_restore(void);
91 static void vla_sp_restore_root(void);
92 static int is_compatible_parameter_types(CType *type1, CType *type2);
93 static void expr_type(CType *type);
94 ST_FUNC void vpush64(int ty, unsigned long long v);
95 ST_FUNC void vpush(CType *type);
96 ST_FUNC int gvtst(int inv, int t);
97 ST_FUNC int is_btype_size(int bt);
99 ST_INLN int is_float(int t)
101 int bt;
102 bt = t & VT_BTYPE;
103 return bt == VT_LDOUBLE || bt == VT_DOUBLE || bt == VT_FLOAT || bt == VT_QFLOAT;
106 /* we use our own 'finite' function to avoid potential problems with
107 non standard math libs */
108 /* XXX: endianness dependent */
109 ST_FUNC int ieee_finite(double d)
111 int p[4];
112 memcpy(p, &d, sizeof(double));
113 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
116 ST_FUNC void test_lvalue(void)
118 if (!(vtop->r & VT_LVAL))
119 expect("lvalue");
122 ST_FUNC void check_vstack(void)
124 if (pvtop != vtop)
125 tcc_error("internal compiler error: vstack leak (%d)", vtop - pvtop);
128 /* ------------------------------------------------------------------------- */
129 /* symbol allocator */
130 static Sym *__sym_malloc(void)
132 Sym *sym_pool, *sym, *last_sym;
133 int i;
135 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
136 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
138 last_sym = sym_free_first;
139 sym = sym_pool;
140 for(i = 0; i < SYM_POOL_NB; i++) {
141 sym->next = last_sym;
142 last_sym = sym;
143 sym++;
145 sym_free_first = last_sym;
146 return last_sym;
149 static inline Sym *sym_malloc(void)
151 Sym *sym;
152 sym = sym_free_first;
153 if (!sym)
154 sym = __sym_malloc();
155 sym_free_first = sym->next;
156 return sym;
159 ST_INLN void sym_free(Sym *sym)
161 sym->next = sym_free_first;
162 sym_free_first = sym;
165 /* push, without hashing */
166 ST_FUNC Sym *sym_push2(Sym **ps, int v, int t, long c)
168 Sym *s;
170 s = sym_malloc();
171 s->asm_label = 0;
172 s->v = v;
173 s->type.t = t;
174 s->type.ref = NULL;
175 #ifdef _WIN64
176 s->d = NULL;
177 #endif
178 s->c = c;
179 s->next = NULL;
180 /* add in stack */
181 s->prev = *ps;
182 *ps = s;
183 return s;
186 /* find a symbol and return its associated structure. 's' is the top
187 of the symbol stack */
188 ST_FUNC Sym *sym_find2(Sym *s, int v)
190 while (s) {
191 if (s->v == v)
192 return s;
193 else if (s->v == -1)
194 return NULL;
195 s = s->prev;
197 return NULL;
200 /* structure lookup */
201 ST_INLN Sym *struct_find(int v)
203 v -= TOK_IDENT;
204 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
205 return NULL;
206 return table_ident[v]->sym_struct;
209 /* find an identifier */
210 ST_INLN Sym *sym_find(int v)
212 v -= TOK_IDENT;
213 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
214 return NULL;
215 return table_ident[v]->sym_identifier;
218 /* push a given symbol on the symbol stack */
219 ST_FUNC Sym *sym_push(int v, CType *type, int r, int c)
221 Sym *s, **ps;
222 TokenSym *ts;
224 if (local_stack)
225 ps = &local_stack;
226 else
227 ps = &global_stack;
228 s = sym_push2(ps, v, type->t, c);
229 s->type.ref = type->ref;
230 s->r = r;
231 /* don't record fields or anonymous symbols */
232 /* XXX: simplify */
233 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
234 /* record symbol in token array */
235 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
236 if (v & SYM_STRUCT)
237 ps = &ts->sym_struct;
238 else
239 ps = &ts->sym_identifier;
240 s->prev_tok = *ps;
241 *ps = s;
242 if (local_scope) {
243 s->scope = local_scope;
244 if (s->prev_tok && s->prev_tok->scope == s->scope)
245 tcc_error("redeclaration of '%s'", get_tok_str(v & ~SYM_STRUCT, NULL));
248 return s;
251 /* push a global identifier */
252 ST_FUNC Sym *global_identifier_push(int v, int t, int c)
254 Sym *s, **ps;
255 s = sym_push2(&global_stack, v, t, c);
256 /* don't record anonymous symbol */
257 if (v < SYM_FIRST_ANOM) {
258 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
259 /* modify the top most local identifier, so that
260 sym_identifier will point to 's' when popped */
261 while (*ps != NULL)
262 ps = &(*ps)->prev_tok;
263 s->prev_tok = NULL;
264 *ps = s;
266 return s;
269 /* pop symbols until top reaches 'b' */
270 ST_FUNC void sym_pop(Sym **ptop, Sym *b)
272 Sym *s, *ss, **ps;
273 TokenSym *ts;
274 int v;
276 s = *ptop;
277 while(s != b) {
278 ss = s->prev;
279 v = s->v;
280 /* remove symbol in token array */
281 /* XXX: simplify */
282 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
283 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
284 if (v & SYM_STRUCT)
285 ps = &ts->sym_struct;
286 else
287 ps = &ts->sym_identifier;
288 *ps = s->prev_tok;
290 sym_free(s);
291 s = ss;
293 *ptop = b;
296 static void weaken_symbol(Sym *sym)
298 sym->type.t |= VT_WEAK;
299 if (sym->c > 0) {
300 int esym_type;
301 ElfW(Sym) *esym;
303 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
304 esym_type = ELFW(ST_TYPE)(esym->st_info);
305 esym->st_info = ELFW(ST_INFO)(STB_WEAK, esym_type);
309 static void apply_visibility(Sym *sym, CType *type)
311 int vis = sym->type.t & VT_VIS_MASK;
312 int vis2 = type->t & VT_VIS_MASK;
313 if (vis == (STV_DEFAULT << VT_VIS_SHIFT))
314 vis = vis2;
315 else if (vis2 == (STV_DEFAULT << VT_VIS_SHIFT))
317 else
318 vis = (vis < vis2) ? vis : vis2;
319 sym->type.t &= ~VT_VIS_MASK;
320 sym->type.t |= vis;
322 if (sym->c > 0) {
323 ElfW(Sym) *esym;
325 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
326 vis >>= VT_VIS_SHIFT;
327 esym->st_other = (esym->st_other & ~ELFW(ST_VISIBILITY)(-1)) | vis;
331 /* ------------------------------------------------------------------------- */
333 ST_FUNC void swap(int *p, int *q)
335 int t;
336 t = *p;
337 *p = *q;
338 *q = t;
341 static void vsetc(CType *type, int r, CValue *vc)
343 int v;
345 if (vtop >= vstack + (VSTACK_SIZE - 1))
346 tcc_error("memory full (vstack)");
347 /* cannot let cpu flags if other instruction are generated. Also
348 avoid leaving VT_JMP anywhere except on the top of the stack
349 because it would complicate the code generator. */
350 if (vtop >= vstack) {
351 v = vtop->r & VT_VALMASK;
352 if (v == VT_CMP || (v & ~1) == VT_JMP)
353 gv(RC_INT);
355 vtop++;
356 vtop->type = *type;
357 vtop->r = r;
358 vtop->r2 = VT_CONST;
359 vtop->c = *vc;
362 /* push constant of type "type" with useless value */
363 ST_FUNC void vpush(CType *type)
365 CValue cval;
366 vsetc(type, VT_CONST, &cval);
369 /* push integer constant */
370 ST_FUNC void vpushi(int v)
372 CValue cval;
373 cval.i = v;
374 vsetc(&int_type, VT_CONST, &cval);
377 /* push a pointer sized constant */
378 static void vpushs(addr_t v)
380 CValue cval;
381 cval.i = v;
382 vsetc(&size_type, VT_CONST, &cval);
385 /* push arbitrary 64bit constant */
386 ST_FUNC void vpush64(int ty, unsigned long long v)
388 CValue cval;
389 CType ctype;
390 ctype.t = ty;
391 ctype.ref = NULL;
392 cval.i = v;
393 vsetc(&ctype, VT_CONST, &cval);
396 /* push long long constant */
397 static inline void vpushll(long long v)
399 vpush64(VT_LLONG, v);
402 /* push a symbol value of TYPE */
403 static inline void vpushsym(CType *type, Sym *sym)
405 CValue cval;
406 cval.i = 0;
407 vsetc(type, VT_CONST | VT_SYM, &cval);
408 vtop->sym = sym;
411 /* Return a static symbol pointing to a section */
412 ST_FUNC Sym *get_sym_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
414 int v;
415 Sym *sym;
417 v = anon_sym++;
418 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
419 sym->type.ref = type->ref;
420 sym->r = VT_CONST | VT_SYM;
421 put_extern_sym(sym, sec, offset, size);
422 return sym;
425 /* push a reference to a section offset by adding a dummy symbol */
426 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
428 vpushsym(type, get_sym_ref(type, sec, offset, size));
431 /* define a new external reference to a symbol 'v' of type 'u' */
432 ST_FUNC Sym *external_global_sym(int v, CType *type, int r)
434 Sym *s;
436 s = sym_find(v);
437 if (!s) {
438 /* push forward reference */
439 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
440 s->type.ref = type->ref;
441 s->r = r | VT_CONST | VT_SYM;
443 return s;
446 /* define a new external reference to a symbol 'v' */
447 static Sym *external_sym(int v, CType *type, int r)
449 Sym *s;
451 s = sym_find(v);
452 if (!s) {
453 /* push forward reference */
454 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
455 s->type.t |= VT_EXTERN;
456 } else if (s->type.ref == func_old_type.ref) {
457 s->type.ref = type->ref;
458 s->r = r | VT_CONST | VT_SYM;
459 s->type.t |= VT_EXTERN;
460 } else if (!is_compatible_types(&s->type, type)) {
461 tcc_error("incompatible types for redefinition of '%s'",
462 get_tok_str(v, NULL));
464 /* Merge some storage attributes. */
465 if (type->t & VT_WEAK)
466 weaken_symbol(s);
468 if (type->t & VT_VIS_MASK)
469 apply_visibility(s, type);
471 return s;
474 /* push a reference to global symbol v */
475 ST_FUNC void vpush_global_sym(CType *type, int v)
477 vpushsym(type, external_global_sym(v, type, 0));
480 ST_FUNC void vset(CType *type, int r, int v)
482 CValue cval;
484 cval.i = v;
485 vsetc(type, r, &cval);
488 static void vseti(int r, int v)
490 CType type;
491 type.t = VT_INT;
492 type.ref = 0;
493 vset(&type, r, v);
496 ST_FUNC void vswap(void)
498 SValue tmp;
499 /* cannot let cpu flags if other instruction are generated. Also
500 avoid leaving VT_JMP anywhere except on the top of the stack
501 because it would complicate the code generator. */
502 if (vtop >= vstack) {
503 int v = vtop->r & VT_VALMASK;
504 if (v == VT_CMP || (v & ~1) == VT_JMP)
505 gv(RC_INT);
507 tmp = vtop[0];
508 vtop[0] = vtop[-1];
509 vtop[-1] = tmp;
511 /* XXX: +2% overall speed possible with optimized memswap
513 * memswap(&vtop[0], &vtop[1], sizeof *vtop);
517 ST_FUNC void vpushv(SValue *v)
519 if (vtop >= vstack + (VSTACK_SIZE - 1))
520 tcc_error("memory full (vstack)");
521 vtop++;
522 *vtop = *v;
525 static void vdup(void)
527 vpushv(vtop);
530 /* save r to the memory stack, and mark it as being free */
531 ST_FUNC void save_reg(int r)
533 int l, saved, size, align;
534 SValue *p, sv;
535 CType *type;
537 /* modify all stack values */
538 saved = 0;
539 l = 0;
540 for(p=vstack;p<=vtop;p++) {
541 if ((p->r & VT_VALMASK) == r ||
542 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
543 /* must save value on stack if not already done */
544 if (!saved) {
545 /* NOTE: must reload 'r' because r might be equal to r2 */
546 r = p->r & VT_VALMASK;
547 /* store register in the stack */
548 type = &p->type;
549 if ((p->r & VT_LVAL) ||
550 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
551 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
552 type = &char_pointer_type;
553 #else
554 type = &int_type;
555 #endif
556 size = type_size(type, &align);
557 loc = (loc - size) & -align;
558 sv.type.t = type->t;
559 sv.r = VT_LOCAL | VT_LVAL;
560 sv.c.i = loc;
561 store(r, &sv);
562 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
563 /* x86 specific: need to pop fp register ST0 if saved */
564 if (r == TREG_ST0) {
565 o(0xd8dd); /* fstp %st(0) */
567 #endif
568 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
569 /* special long long case */
570 if ((type->t & VT_BTYPE) == VT_LLONG) {
571 sv.c.i += 4;
572 store(p->r2, &sv);
574 #endif
575 l = loc;
576 saved = 1;
578 /* mark that stack entry as being saved on the stack */
579 if (p->r & VT_LVAL) {
580 /* also clear the bounded flag because the
581 relocation address of the function was stored in
582 p->c.i */
583 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
584 } else {
585 p->r = lvalue_type(p->type.t) | VT_LOCAL;
587 p->r2 = VT_CONST;
588 p->c.i = l;
593 #ifdef TCC_TARGET_ARM
594 /* find a register of class 'rc2' with at most one reference on stack.
595 * If none, call get_reg(rc) */
596 ST_FUNC int get_reg_ex(int rc, int rc2)
598 int r;
599 SValue *p;
601 for(r=0;r<NB_REGS;r++) {
602 if (reg_classes[r] & rc2) {
603 int n;
604 n=0;
605 for(p = vstack; p <= vtop; p++) {
606 if ((p->r & VT_VALMASK) == r ||
607 (p->r2 & VT_VALMASK) == r)
608 n++;
610 if (n <= 1)
611 return r;
614 return get_reg(rc);
616 #endif
618 /* find a free register of class 'rc'. If none, save one register */
619 ST_FUNC int get_reg(int rc)
621 int r;
622 SValue *p;
624 /* find a free register */
625 for(r=0;r<NB_REGS;r++) {
626 if (reg_classes[r] & rc) {
627 for(p=vstack;p<=vtop;p++) {
628 if ((p->r & VT_VALMASK) == r ||
629 (p->r2 & VT_VALMASK) == r)
630 goto notfound;
632 return r;
634 notfound: ;
637 /* no register left : free the first one on the stack (VERY
638 IMPORTANT to start from the bottom to ensure that we don't
639 spill registers used in gen_opi()) */
640 for(p=vstack;p<=vtop;p++) {
641 /* look at second register (if long long) */
642 r = p->r2 & VT_VALMASK;
643 if (r < VT_CONST && (reg_classes[r] & rc))
644 goto save_found;
645 r = p->r & VT_VALMASK;
646 if (r < VT_CONST && (reg_classes[r] & rc)) {
647 save_found:
648 save_reg(r);
649 return r;
652 /* Should never comes here */
653 return -1;
656 /* save registers up to (vtop - n) stack entry */
657 ST_FUNC void save_regs(int n)
659 int r;
660 SValue *p, *p1;
661 p1 = vtop - n;
662 for(p = vstack;p <= p1; p++) {
663 r = p->r & VT_VALMASK;
664 if (r < VT_CONST) {
665 save_reg(r);
670 /* move register 's' (of type 't') to 'r', and flush previous value of r to memory
671 if needed */
672 static void move_reg(int r, int s, int t)
674 SValue sv;
676 if (r != s) {
677 save_reg(r);
678 sv.type.t = t;
679 sv.type.ref = NULL;
680 sv.r = s;
681 sv.c.i = 0;
682 load(r, &sv);
686 /* get address of vtop (vtop MUST BE an lvalue) */
687 ST_FUNC void gaddrof(void)
689 if (vtop->r & VT_REF && !nocode_wanted)
690 gv(RC_INT);
691 vtop->r &= ~VT_LVAL;
692 /* tricky: if saved lvalue, then we can go back to lvalue */
693 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
694 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
699 #ifdef CONFIG_TCC_BCHECK
700 /* generate lvalue bound code */
701 static void gbound(void)
703 int lval_type;
704 CType type1;
706 vtop->r &= ~VT_MUSTBOUND;
707 /* if lvalue, then use checking code before dereferencing */
708 if (vtop->r & VT_LVAL) {
709 /* if not VT_BOUNDED value, then make one */
710 if (!(vtop->r & VT_BOUNDED)) {
711 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
712 /* must save type because we must set it to int to get pointer */
713 type1 = vtop->type;
714 vtop->type.t = VT_PTR;
715 gaddrof();
716 vpushi(0);
717 gen_bounded_ptr_add();
718 vtop->r |= lval_type;
719 vtop->type = type1;
721 /* then check for dereferencing */
722 gen_bounded_ptr_deref();
725 #endif
727 /* store vtop a register belonging to class 'rc'. lvalues are
728 converted to values. Cannot be used if cannot be converted to
729 register value (such as structures). */
730 ST_FUNC int gv(int rc)
732 int r, bit_pos, bit_size, size, align, i;
733 int rc2;
735 /* NOTE: get_reg can modify vstack[] */
736 if (vtop->type.t & VT_BITFIELD) {
737 CType type;
738 int bits = 32;
739 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
740 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
741 /* remove bit field info to avoid loops */
742 vtop->type.t &= ~VT_BITFIELD & ((1 << VT_STRUCT_SHIFT) - 1);
743 /* cast to int to propagate signedness in following ops */
744 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
745 type.t = VT_LLONG;
746 bits = 64;
747 } else
748 type.t = VT_INT;
749 if((vtop->type.t & VT_UNSIGNED) ||
750 (vtop->type.t & VT_BTYPE) == VT_BOOL)
751 type.t |= VT_UNSIGNED;
752 gen_cast(&type);
753 /* generate shifts */
754 vpushi(bits - (bit_pos + bit_size));
755 gen_op(TOK_SHL);
756 vpushi(bits - bit_size);
757 /* NOTE: transformed to SHR if unsigned */
758 gen_op(TOK_SAR);
759 r = gv(rc);
760 } else {
761 if (is_float(vtop->type.t) &&
762 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
763 Sym *sym;
764 int *ptr;
765 unsigned long offset;
766 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
767 CValue check;
768 #endif
770 /* XXX: unify with initializers handling ? */
771 /* CPUs usually cannot use float constants, so we store them
772 generically in data segment */
773 size = type_size(&vtop->type, &align);
774 offset = (data_section->data_offset + align - 1) & -align;
775 data_section->data_offset = offset;
776 /* XXX: not portable yet */
777 #if defined(__i386__) || defined(__x86_64__)
778 /* Zero pad x87 tenbyte long doubles */
779 if (size == LDOUBLE_SIZE) {
780 vtop->c.tab[2] &= 0xffff;
781 #if LDOUBLE_SIZE == 16
782 vtop->c.tab[3] = 0;
783 #endif
785 #endif
786 ptr = section_ptr_add(data_section, size);
787 size = size >> 2;
788 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
789 check.d = 1;
790 if(check.tab[0])
791 for(i=0;i<size;i++)
792 ptr[i] = vtop->c.tab[size-1-i];
793 else
794 #endif
795 for(i=0;i<size;i++)
796 ptr[i] = vtop->c.tab[i];
797 sym = get_sym_ref(&vtop->type, data_section, offset, size << 2);
798 vtop->r |= VT_LVAL | VT_SYM;
799 vtop->sym = sym;
800 vtop->c.i = 0;
802 #ifdef CONFIG_TCC_BCHECK
803 if (vtop->r & VT_MUSTBOUND)
804 gbound();
805 #endif
807 r = vtop->r & VT_VALMASK;
808 rc2 = (rc & RC_FLOAT) ? RC_FLOAT : RC_INT;
809 #ifndef TCC_TARGET_ARM64
810 if (rc == RC_IRET)
811 rc2 = RC_LRET;
812 #ifdef TCC_TARGET_X86_64
813 else if (rc == RC_FRET)
814 rc2 = RC_QRET;
815 #endif
816 #endif
818 /* need to reload if:
819 - constant
820 - lvalue (need to dereference pointer)
821 - already a register, but not in the right class */
822 if (r >= VT_CONST
823 || (vtop->r & VT_LVAL)
824 || !(reg_classes[r] & rc)
825 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
826 || ((vtop->type.t & VT_BTYPE) == VT_QLONG && !(reg_classes[vtop->r2] & rc2))
827 || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT && !(reg_classes[vtop->r2] & rc2))
828 #else
829 || ((vtop->type.t & VT_BTYPE) == VT_LLONG && !(reg_classes[vtop->r2] & rc2))
830 #endif
833 r = get_reg(rc);
834 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
835 if (((vtop->type.t & VT_BTYPE) == VT_QLONG) || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT)) {
836 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
837 #else
838 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
839 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
840 unsigned long long ll;
841 #endif
842 int r2, original_type;
843 original_type = vtop->type.t;
844 /* two register type load : expand to two words
845 temporarily */
846 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
847 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
848 /* load constant */
849 ll = vtop->c.i;
850 vtop->c.i = ll; /* first word */
851 load(r, vtop);
852 vtop->r = r; /* save register value */
853 vpushi(ll >> 32); /* second word */
854 } else
855 #endif
856 if (r >= VT_CONST || /* XXX: test to VT_CONST incorrect ? */
857 (vtop->r & VT_LVAL)) {
858 /* We do not want to modifier the long long
859 pointer here, so the safest (and less
860 efficient) is to save all the other registers
861 in the stack. XXX: totally inefficient. */
862 save_regs(1);
863 /* load from memory */
864 vtop->type.t = load_type;
865 load(r, vtop);
866 vdup();
867 vtop[-1].r = r; /* save register value */
868 /* increment pointer to get second word */
869 vtop->type.t = addr_type;
870 gaddrof();
871 vpushi(load_size);
872 gen_op('+');
873 vtop->r |= VT_LVAL;
874 vtop->type.t = load_type;
875 } else {
876 /* move registers */
877 load(r, vtop);
878 vdup();
879 vtop[-1].r = r; /* save register value */
880 vtop->r = vtop[-1].r2;
882 /* Allocate second register. Here we rely on the fact that
883 get_reg() tries first to free r2 of an SValue. */
884 r2 = get_reg(rc2);
885 load(r2, vtop);
886 vpop();
887 /* write second register */
888 vtop->r2 = r2;
889 vtop->type.t = original_type;
890 } else if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
891 int t1, t;
892 /* lvalue of scalar type : need to use lvalue type
893 because of possible cast */
894 t = vtop->type.t;
895 t1 = t;
896 /* compute memory access type */
897 if (vtop->r & VT_REF)
898 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
899 t = VT_PTR;
900 #else
901 t = VT_INT;
902 #endif
903 else if (vtop->r & VT_LVAL_BYTE)
904 t = VT_BYTE;
905 else if (vtop->r & VT_LVAL_SHORT)
906 t = VT_SHORT;
907 if (vtop->r & VT_LVAL_UNSIGNED)
908 t |= VT_UNSIGNED;
909 vtop->type.t = t;
910 load(r, vtop);
911 /* restore wanted type */
912 vtop->type.t = t1;
913 } else {
914 /* one register type load */
915 load(r, vtop);
918 vtop->r = r;
919 #ifdef TCC_TARGET_C67
920 /* uses register pairs for doubles */
921 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
922 vtop->r2 = r+1;
923 #endif
925 return r;
928 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
929 ST_FUNC void gv2(int rc1, int rc2)
931 int v;
933 /* generate more generic register first. But VT_JMP or VT_CMP
934 values must be generated first in all cases to avoid possible
935 reload errors */
936 v = vtop[0].r & VT_VALMASK;
937 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
938 vswap();
939 gv(rc1);
940 vswap();
941 gv(rc2);
942 /* test if reload is needed for first register */
943 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
944 vswap();
945 gv(rc1);
946 vswap();
948 } else {
949 gv(rc2);
950 vswap();
951 gv(rc1);
952 vswap();
953 /* test if reload is needed for first register */
954 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
955 gv(rc2);
960 #ifndef TCC_TARGET_ARM64
961 /* wrapper around RC_FRET to return a register by type */
962 static int rc_fret(int t)
964 #ifdef TCC_TARGET_X86_64
965 if (t == VT_LDOUBLE) {
966 return RC_ST0;
968 #endif
969 return RC_FRET;
971 #endif
973 /* wrapper around REG_FRET to return a register by type */
974 static int reg_fret(int t)
976 #ifdef TCC_TARGET_X86_64
977 if (t == VT_LDOUBLE) {
978 return TREG_ST0;
980 #endif
981 return REG_FRET;
984 /* expand long long on stack in two int registers */
985 static void lexpand(void)
987 int u;
989 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
990 gv(RC_INT);
991 vdup();
992 vtop[0].r = vtop[-1].r2;
993 vtop[0].r2 = VT_CONST;
994 vtop[-1].r2 = VT_CONST;
995 vtop[0].type.t = VT_INT | u;
996 vtop[-1].type.t = VT_INT | u;
999 #ifdef TCC_TARGET_ARM
1000 /* expand long long on stack */
1001 ST_FUNC void lexpand_nr(void)
1003 int u,v;
1005 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
1006 vdup();
1007 vtop->r2 = VT_CONST;
1008 vtop->type.t = VT_INT | u;
1009 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
1010 if (v == VT_CONST) {
1011 vtop[-1].c.i = vtop->c.i;
1012 vtop->c.i = vtop->c.i >> 32;
1013 vtop->r = VT_CONST;
1014 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
1015 vtop->c.i += 4;
1016 vtop->r = vtop[-1].r;
1017 } else if (v > VT_CONST) {
1018 vtop--;
1019 lexpand();
1020 } else
1021 vtop->r = vtop[-1].r2;
1022 vtop[-1].r2 = VT_CONST;
1023 vtop[-1].type.t = VT_INT | u;
1025 #endif
1027 /* build a long long from two ints */
1028 static void lbuild(int t)
1030 gv2(RC_INT, RC_INT);
1031 vtop[-1].r2 = vtop[0].r;
1032 vtop[-1].type.t = t;
1033 vpop();
1036 /* rotate n first stack elements to the bottom
1037 I1 ... In -> I2 ... In I1 [top is right]
1039 ST_FUNC void vrotb(int n)
1041 int i;
1042 SValue tmp;
1044 tmp = vtop[-n + 1];
1045 for(i=-n+1;i!=0;i++)
1046 vtop[i] = vtop[i+1];
1047 vtop[0] = tmp;
1050 /* rotate the n elements before entry e towards the top
1051 I1 ... In ... -> In I1 ... I(n-1) ... [top is right]
1053 ST_FUNC void vrote(SValue *e, int n)
1055 int i;
1056 SValue tmp;
1058 tmp = *e;
1059 for(i = 0;i < n - 1; i++)
1060 e[-i] = e[-i - 1];
1061 e[-n + 1] = tmp;
1064 /* rotate n first stack elements to the top
1065 I1 ... In -> In I1 ... I(n-1) [top is right]
1067 ST_FUNC void vrott(int n)
1069 vrote(vtop, n);
1072 /* pop stack value */
1073 ST_FUNC void vpop(void)
1075 int v;
1076 v = vtop->r & VT_VALMASK;
1077 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1078 /* for x86, we need to pop the FP stack */
1079 if (v == TREG_ST0 && !nocode_wanted) {
1080 o(0xd8dd); /* fstp %st(0) */
1081 } else
1082 #endif
1083 if (v == VT_JMP || v == VT_JMPI) {
1084 /* need to put correct jump if && or || without test */
1085 gsym(vtop->c.i);
1087 vtop--;
1090 /* convert stack entry to register and duplicate its value in another
1091 register */
1092 static void gv_dup(void)
1094 int rc, t, r, r1;
1095 SValue sv;
1097 t = vtop->type.t;
1098 if ((t & VT_BTYPE) == VT_LLONG) {
1099 lexpand();
1100 gv_dup();
1101 vswap();
1102 vrotb(3);
1103 gv_dup();
1104 vrotb(4);
1105 /* stack: H L L1 H1 */
1106 lbuild(t);
1107 vrotb(3);
1108 vrotb(3);
1109 vswap();
1110 lbuild(t);
1111 vswap();
1112 } else {
1113 /* duplicate value */
1114 rc = RC_INT;
1115 sv.type.t = VT_INT;
1116 if (is_float(t)) {
1117 rc = RC_FLOAT;
1118 #ifdef TCC_TARGET_X86_64
1119 if ((t & VT_BTYPE) == VT_LDOUBLE) {
1120 rc = RC_ST0;
1122 #endif
1123 sv.type.t = t;
1125 r = gv(rc);
1126 r1 = get_reg(rc);
1127 sv.r = r;
1128 sv.c.i = 0;
1129 load(r1, &sv); /* move r to r1 */
1130 vdup();
1131 /* duplicates value */
1132 if (r != r1)
1133 vtop->r = r1;
1137 /* Generate value test
1139 * Generate a test for any value (jump, comparison and integers) */
1140 ST_FUNC int gvtst(int inv, int t)
1142 int v = vtop->r & VT_VALMASK;
1143 if (v != VT_CMP && v != VT_JMP && v != VT_JMPI) {
1144 vpushi(0);
1145 gen_op(TOK_NE);
1147 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1148 /* constant jmp optimization */
1149 if ((vtop->c.i != 0) != inv)
1150 t = gjmp(t);
1151 vtop--;
1152 return t;
1154 return gtst(inv, t);
1157 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
1158 /* generate CPU independent (unsigned) long long operations */
1159 static void gen_opl(int op)
1161 int t, a, b, op1, c, i;
1162 int func;
1163 unsigned short reg_iret = REG_IRET;
1164 unsigned short reg_lret = REG_LRET;
1165 SValue tmp;
1167 switch(op) {
1168 case '/':
1169 case TOK_PDIV:
1170 func = TOK___divdi3;
1171 goto gen_func;
1172 case TOK_UDIV:
1173 func = TOK___udivdi3;
1174 goto gen_func;
1175 case '%':
1176 func = TOK___moddi3;
1177 goto gen_mod_func;
1178 case TOK_UMOD:
1179 func = TOK___umoddi3;
1180 gen_mod_func:
1181 #ifdef TCC_ARM_EABI
1182 reg_iret = TREG_R2;
1183 reg_lret = TREG_R3;
1184 #endif
1185 gen_func:
1186 /* call generic long long function */
1187 vpush_global_sym(&func_old_type, func);
1188 vrott(3);
1189 gfunc_call(2);
1190 vpushi(0);
1191 vtop->r = reg_iret;
1192 vtop->r2 = reg_lret;
1193 break;
1194 case '^':
1195 case '&':
1196 case '|':
1197 case '*':
1198 case '+':
1199 case '-':
1200 t = vtop->type.t;
1201 vswap();
1202 lexpand();
1203 vrotb(3);
1204 lexpand();
1205 /* stack: L1 H1 L2 H2 */
1206 tmp = vtop[0];
1207 vtop[0] = vtop[-3];
1208 vtop[-3] = tmp;
1209 tmp = vtop[-2];
1210 vtop[-2] = vtop[-3];
1211 vtop[-3] = tmp;
1212 vswap();
1213 /* stack: H1 H2 L1 L2 */
1214 if (op == '*') {
1215 vpushv(vtop - 1);
1216 vpushv(vtop - 1);
1217 gen_op(TOK_UMULL);
1218 lexpand();
1219 /* stack: H1 H2 L1 L2 ML MH */
1220 for(i=0;i<4;i++)
1221 vrotb(6);
1222 /* stack: ML MH H1 H2 L1 L2 */
1223 tmp = vtop[0];
1224 vtop[0] = vtop[-2];
1225 vtop[-2] = tmp;
1226 /* stack: ML MH H1 L2 H2 L1 */
1227 gen_op('*');
1228 vrotb(3);
1229 vrotb(3);
1230 gen_op('*');
1231 /* stack: ML MH M1 M2 */
1232 gen_op('+');
1233 gen_op('+');
1234 } else if (op == '+' || op == '-') {
1235 /* XXX: add non carry method too (for MIPS or alpha) */
1236 if (op == '+')
1237 op1 = TOK_ADDC1;
1238 else
1239 op1 = TOK_SUBC1;
1240 gen_op(op1);
1241 /* stack: H1 H2 (L1 op L2) */
1242 vrotb(3);
1243 vrotb(3);
1244 gen_op(op1 + 1); /* TOK_xxxC2 */
1245 } else {
1246 gen_op(op);
1247 /* stack: H1 H2 (L1 op L2) */
1248 vrotb(3);
1249 vrotb(3);
1250 /* stack: (L1 op L2) H1 H2 */
1251 gen_op(op);
1252 /* stack: (L1 op L2) (H1 op H2) */
1254 /* stack: L H */
1255 lbuild(t);
1256 break;
1257 case TOK_SAR:
1258 case TOK_SHR:
1259 case TOK_SHL:
1260 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1261 t = vtop[-1].type.t;
1262 vswap();
1263 lexpand();
1264 vrotb(3);
1265 /* stack: L H shift */
1266 c = (int)vtop->c.i;
1267 /* constant: simpler */
1268 /* NOTE: all comments are for SHL. the other cases are
1269 done by swaping words */
1270 vpop();
1271 if (op != TOK_SHL)
1272 vswap();
1273 if (c >= 32) {
1274 /* stack: L H */
1275 vpop();
1276 if (c > 32) {
1277 vpushi(c - 32);
1278 gen_op(op);
1280 if (op != TOK_SAR) {
1281 vpushi(0);
1282 } else {
1283 gv_dup();
1284 vpushi(31);
1285 gen_op(TOK_SAR);
1287 vswap();
1288 } else {
1289 vswap();
1290 gv_dup();
1291 /* stack: H L L */
1292 vpushi(c);
1293 gen_op(op);
1294 vswap();
1295 vpushi(32 - c);
1296 if (op == TOK_SHL)
1297 gen_op(TOK_SHR);
1298 else
1299 gen_op(TOK_SHL);
1300 vrotb(3);
1301 /* stack: L L H */
1302 vpushi(c);
1303 if (op == TOK_SHL)
1304 gen_op(TOK_SHL);
1305 else
1306 gen_op(TOK_SHR);
1307 gen_op('|');
1309 if (op != TOK_SHL)
1310 vswap();
1311 lbuild(t);
1312 } else {
1313 /* XXX: should provide a faster fallback on x86 ? */
1314 switch(op) {
1315 case TOK_SAR:
1316 func = TOK___ashrdi3;
1317 goto gen_func;
1318 case TOK_SHR:
1319 func = TOK___lshrdi3;
1320 goto gen_func;
1321 case TOK_SHL:
1322 func = TOK___ashldi3;
1323 goto gen_func;
1326 break;
1327 default:
1328 /* compare operations */
1329 t = vtop->type.t;
1330 vswap();
1331 lexpand();
1332 vrotb(3);
1333 lexpand();
1334 /* stack: L1 H1 L2 H2 */
1335 tmp = vtop[-1];
1336 vtop[-1] = vtop[-2];
1337 vtop[-2] = tmp;
1338 /* stack: L1 L2 H1 H2 */
1339 /* compare high */
1340 op1 = op;
1341 /* when values are equal, we need to compare low words. since
1342 the jump is inverted, we invert the test too. */
1343 if (op1 == TOK_LT)
1344 op1 = TOK_LE;
1345 else if (op1 == TOK_GT)
1346 op1 = TOK_GE;
1347 else if (op1 == TOK_ULT)
1348 op1 = TOK_ULE;
1349 else if (op1 == TOK_UGT)
1350 op1 = TOK_UGE;
1351 a = 0;
1352 b = 0;
1353 gen_op(op1);
1354 if (op1 != TOK_NE) {
1355 a = gvtst(1, 0);
1357 if (op != TOK_EQ) {
1358 /* generate non equal test */
1359 /* XXX: NOT PORTABLE yet */
1360 if (a == 0) {
1361 b = gvtst(0, 0);
1362 } else {
1363 #if defined(TCC_TARGET_I386)
1364 b = psym(0x850f, 0);
1365 #elif defined(TCC_TARGET_ARM)
1366 b = ind;
1367 o(0x1A000000 | encbranch(ind, 0, 1));
1368 #elif defined(TCC_TARGET_C67) || defined(TCC_TARGET_ARM64)
1369 tcc_error("not implemented");
1370 #else
1371 #error not supported
1372 #endif
1375 /* compare low. Always unsigned */
1376 op1 = op;
1377 if (op1 == TOK_LT)
1378 op1 = TOK_ULT;
1379 else if (op1 == TOK_LE)
1380 op1 = TOK_ULE;
1381 else if (op1 == TOK_GT)
1382 op1 = TOK_UGT;
1383 else if (op1 == TOK_GE)
1384 op1 = TOK_UGE;
1385 gen_op(op1);
1386 a = gvtst(1, a);
1387 gsym(b);
1388 vseti(VT_JMPI, a);
1389 break;
1392 #endif
1394 static uint64_t gen_opic_sdiv(uint64_t a, uint64_t b)
1396 uint64_t x = (a >> 63 ? -a : a) / (b >> 63 ? -b : b);
1397 return (a ^ b) >> 63 ? -x : x;
1400 static int gen_opic_lt(uint64_t a, uint64_t b)
1402 return (a ^ (uint64_t)1 << 63) < (b ^ (uint64_t)1 << 63);
1405 /* handle integer constant optimizations and various machine
1406 independent opt */
1407 static void gen_opic(int op)
1409 SValue *v1 = vtop - 1;
1410 SValue *v2 = vtop;
1411 int t1 = v1->type.t & VT_BTYPE;
1412 int t2 = v2->type.t & VT_BTYPE;
1413 int c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1414 int c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1415 uint64_t l1 = c1 ? v1->c.i : 0;
1416 uint64_t l2 = c2 ? v2->c.i : 0;
1417 int shm = (t1 == VT_LLONG) ? 63 : 31;
1419 if (t1 != VT_LLONG)
1420 l1 = ((uint32_t)l1 |
1421 (v1->type.t & VT_UNSIGNED ? 0 : -(l1 & 0x80000000)));
1422 if (t2 != VT_LLONG)
1423 l2 = ((uint32_t)l2 |
1424 (v2->type.t & VT_UNSIGNED ? 0 : -(l2 & 0x80000000)));
1426 if (c1 && c2) {
1427 switch(op) {
1428 case '+': l1 += l2; break;
1429 case '-': l1 -= l2; break;
1430 case '&': l1 &= l2; break;
1431 case '^': l1 ^= l2; break;
1432 case '|': l1 |= l2; break;
1433 case '*': l1 *= l2; break;
1435 case TOK_PDIV:
1436 case '/':
1437 case '%':
1438 case TOK_UDIV:
1439 case TOK_UMOD:
1440 /* if division by zero, generate explicit division */
1441 if (l2 == 0) {
1442 if (const_wanted)
1443 tcc_error("division by zero in constant");
1444 goto general_case;
1446 switch(op) {
1447 default: l1 = gen_opic_sdiv(l1, l2); break;
1448 case '%': l1 = l1 - l2 * gen_opic_sdiv(l1, l2); break;
1449 case TOK_UDIV: l1 = l1 / l2; break;
1450 case TOK_UMOD: l1 = l1 % l2; break;
1452 break;
1453 case TOK_SHL: l1 <<= (l2 & shm); break;
1454 case TOK_SHR: l1 >>= (l2 & shm); break;
1455 case TOK_SAR:
1456 l1 = (l1 >> 63) ? ~(~l1 >> (l2 & shm)) : l1 >> (l2 & shm);
1457 break;
1458 /* tests */
1459 case TOK_ULT: l1 = l1 < l2; break;
1460 case TOK_UGE: l1 = l1 >= l2; break;
1461 case TOK_EQ: l1 = l1 == l2; break;
1462 case TOK_NE: l1 = l1 != l2; break;
1463 case TOK_ULE: l1 = l1 <= l2; break;
1464 case TOK_UGT: l1 = l1 > l2; break;
1465 case TOK_LT: l1 = gen_opic_lt(l1, l2); break;
1466 case TOK_GE: l1 = !gen_opic_lt(l1, l2); break;
1467 case TOK_LE: l1 = !gen_opic_lt(l2, l1); break;
1468 case TOK_GT: l1 = gen_opic_lt(l2, l1); break;
1469 /* logical */
1470 case TOK_LAND: l1 = l1 && l2; break;
1471 case TOK_LOR: l1 = l1 || l2; break;
1472 default:
1473 goto general_case;
1475 v1->c.i = l1;
1476 vtop--;
1477 } else {
1478 /* if commutative ops, put c2 as constant */
1479 if (c1 && (op == '+' || op == '&' || op == '^' ||
1480 op == '|' || op == '*')) {
1481 vswap();
1482 c2 = c1; //c = c1, c1 = c2, c2 = c;
1483 l2 = l1; //l = l1, l1 = l2, l2 = l;
1485 if (!const_wanted &&
1486 c1 && ((l1 == 0 &&
1487 (op == TOK_SHL || op == TOK_SHR || op == TOK_SAR)) ||
1488 (l1 == -1 && op == TOK_SAR))) {
1489 /* treat (0 << x), (0 >> x) and (-1 >> x) as constant */
1490 vtop--;
1491 } else if (!const_wanted &&
1492 c2 && ((l2 == 0 && (op == '&' || op == '*')) ||
1493 (l2 == -1 && op == '|') ||
1494 (l2 == 0xffffffff && t2 != VT_LLONG && op == '|') ||
1495 (l2 == 1 && (op == '%' || op == TOK_UMOD)))) {
1496 /* treat (x & 0), (x * 0), (x | -1) and (x % 1) as constant */
1497 if (l2 == 1)
1498 vtop->c.i = 0;
1499 vswap();
1500 vtop--;
1501 } else if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
1502 op == TOK_PDIV) &&
1503 l2 == 1) ||
1504 ((op == '+' || op == '-' || op == '|' || op == '^' ||
1505 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
1506 l2 == 0) ||
1507 (op == '&' &&
1508 l2 == -1))) {
1509 /* filter out NOP operations like x*1, x-0, x&-1... */
1510 vtop--;
1511 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
1512 /* try to use shifts instead of muls or divs */
1513 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
1514 int n = -1;
1515 while (l2) {
1516 l2 >>= 1;
1517 n++;
1519 vtop->c.i = n;
1520 if (op == '*')
1521 op = TOK_SHL;
1522 else if (op == TOK_PDIV)
1523 op = TOK_SAR;
1524 else
1525 op = TOK_SHR;
1527 goto general_case;
1528 } else if (c2 && (op == '+' || op == '-') &&
1529 (((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM))
1530 || (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
1531 /* symbol + constant case */
1532 if (op == '-')
1533 l2 = -l2;
1534 vtop--;
1535 vtop->c.i += l2;
1536 } else {
1537 general_case:
1538 if (!nocode_wanted) {
1539 /* call low level op generator */
1540 if (t1 == VT_LLONG || t2 == VT_LLONG ||
1541 (PTR_SIZE == 8 && (t1 == VT_PTR || t2 == VT_PTR)))
1542 gen_opl(op);
1543 else
1544 gen_opi(op);
1545 } else {
1546 vtop--;
1552 /* generate a floating point operation with constant propagation */
1553 static void gen_opif(int op)
1555 int c1, c2;
1556 SValue *v1, *v2;
1557 long double f1, f2;
1559 v1 = vtop - 1;
1560 v2 = vtop;
1561 /* currently, we cannot do computations with forward symbols */
1562 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1563 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1564 if (c1 && c2) {
1565 if (v1->type.t == VT_FLOAT) {
1566 f1 = v1->c.f;
1567 f2 = v2->c.f;
1568 } else if (v1->type.t == VT_DOUBLE) {
1569 f1 = v1->c.d;
1570 f2 = v2->c.d;
1571 } else {
1572 f1 = v1->c.ld;
1573 f2 = v2->c.ld;
1576 /* NOTE: we only do constant propagation if finite number (not
1577 NaN or infinity) (ANSI spec) */
1578 if (!ieee_finite(f1) || !ieee_finite(f2))
1579 goto general_case;
1581 switch(op) {
1582 case '+': f1 += f2; break;
1583 case '-': f1 -= f2; break;
1584 case '*': f1 *= f2; break;
1585 case '/':
1586 if (f2 == 0.0) {
1587 if (const_wanted)
1588 tcc_error("division by zero in constant");
1589 goto general_case;
1591 f1 /= f2;
1592 break;
1593 /* XXX: also handles tests ? */
1594 default:
1595 goto general_case;
1597 /* XXX: overflow test ? */
1598 if (v1->type.t == VT_FLOAT) {
1599 v1->c.f = f1;
1600 } else if (v1->type.t == VT_DOUBLE) {
1601 v1->c.d = f1;
1602 } else {
1603 v1->c.ld = f1;
1605 vtop--;
1606 } else {
1607 general_case:
1608 if (!nocode_wanted) {
1609 gen_opf(op);
1610 } else {
1611 vtop--;
1616 static int pointed_size(CType *type)
1618 int align;
1619 return type_size(pointed_type(type), &align);
1622 static void vla_runtime_pointed_size(CType *type)
1624 int align;
1625 vla_runtime_type_size(pointed_type(type), &align);
1628 static inline int is_null_pointer(SValue *p)
1630 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
1631 return 0;
1632 return ((p->type.t & VT_BTYPE) == VT_INT && (uint32_t)p->c.i == 0) ||
1633 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.i == 0) ||
1634 ((p->type.t & VT_BTYPE) == VT_PTR &&
1635 (PTR_SIZE == 4 ? (uint32_t)p->c.i == 0 : p->c.i == 0));
1638 static inline int is_integer_btype(int bt)
1640 return (bt == VT_BYTE || bt == VT_SHORT ||
1641 bt == VT_INT || bt == VT_LLONG);
1644 /* check types for comparison or subtraction of pointers */
1645 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
1647 CType *type1, *type2, tmp_type1, tmp_type2;
1648 int bt1, bt2;
1650 /* null pointers are accepted for all comparisons as gcc */
1651 if (is_null_pointer(p1) || is_null_pointer(p2))
1652 return;
1653 type1 = &p1->type;
1654 type2 = &p2->type;
1655 bt1 = type1->t & VT_BTYPE;
1656 bt2 = type2->t & VT_BTYPE;
1657 /* accept comparison between pointer and integer with a warning */
1658 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
1659 if (op != TOK_LOR && op != TOK_LAND )
1660 tcc_warning("comparison between pointer and integer");
1661 return;
1664 /* both must be pointers or implicit function pointers */
1665 if (bt1 == VT_PTR) {
1666 type1 = pointed_type(type1);
1667 } else if (bt1 != VT_FUNC)
1668 goto invalid_operands;
1670 if (bt2 == VT_PTR) {
1671 type2 = pointed_type(type2);
1672 } else if (bt2 != VT_FUNC) {
1673 invalid_operands:
1674 tcc_error("invalid operands to binary %s", get_tok_str(op, NULL));
1676 if ((type1->t & VT_BTYPE) == VT_VOID ||
1677 (type2->t & VT_BTYPE) == VT_VOID)
1678 return;
1679 tmp_type1 = *type1;
1680 tmp_type2 = *type2;
1681 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1682 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1683 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
1684 /* gcc-like error if '-' is used */
1685 if (op == '-')
1686 goto invalid_operands;
1687 else
1688 tcc_warning("comparison of distinct pointer types lacks a cast");
1692 /* generic gen_op: handles types problems */
1693 ST_FUNC void gen_op(int op)
1695 int u, t1, t2, bt1, bt2, t;
1696 CType type1;
1698 t1 = vtop[-1].type.t;
1699 t2 = vtop[0].type.t;
1700 bt1 = t1 & VT_BTYPE;
1701 bt2 = t2 & VT_BTYPE;
1703 if (bt1 == VT_PTR || bt2 == VT_PTR) {
1704 /* at least one operand is a pointer */
1705 /* relationnal op: must be both pointers */
1706 if (op >= TOK_ULT && op <= TOK_LOR) {
1707 check_comparison_pointer_types(vtop - 1, vtop, op);
1708 /* pointers are handled are unsigned */
1709 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1710 t = VT_LLONG | VT_UNSIGNED;
1711 #else
1712 t = VT_INT | VT_UNSIGNED;
1713 #endif
1714 goto std_op;
1716 /* if both pointers, then it must be the '-' op */
1717 if (bt1 == VT_PTR && bt2 == VT_PTR) {
1718 if (op != '-')
1719 tcc_error("cannot use pointers here");
1720 check_comparison_pointer_types(vtop - 1, vtop, op);
1721 /* XXX: check that types are compatible */
1722 if (vtop[-1].type.t & VT_VLA) {
1723 vla_runtime_pointed_size(&vtop[-1].type);
1724 } else {
1725 vpushi(pointed_size(&vtop[-1].type));
1727 vrott(3);
1728 gen_opic(op);
1729 /* set to integer type */
1730 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1731 vtop->type.t = VT_LLONG;
1732 #else
1733 vtop->type.t = VT_INT;
1734 #endif
1735 vswap();
1736 gen_op(TOK_PDIV);
1737 } else {
1738 /* exactly one pointer : must be '+' or '-'. */
1739 if (op != '-' && op != '+')
1740 tcc_error("cannot use pointers here");
1741 /* Put pointer as first operand */
1742 if (bt2 == VT_PTR) {
1743 vswap();
1744 swap(&t1, &t2);
1746 type1 = vtop[-1].type;
1747 type1.t &= ~VT_ARRAY;
1748 if (vtop[-1].type.t & VT_VLA)
1749 vla_runtime_pointed_size(&vtop[-1].type);
1750 else {
1751 u = pointed_size(&vtop[-1].type);
1752 if (u < 0)
1753 tcc_error("unknown array element size");
1754 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1755 vpushll(u);
1756 #else
1757 /* XXX: cast to int ? (long long case) */
1758 vpushi(u);
1759 #endif
1761 gen_op('*');
1762 #if 0
1763 /* #ifdef CONFIG_TCC_BCHECK
1764 The main reason to removing this code:
1765 #include <stdio.h>
1766 int main ()
1768 int v[10];
1769 int i = 10;
1770 int j = 9;
1771 fprintf(stderr, "v+i-j = %p\n", v+i-j);
1772 fprintf(stderr, "v+(i-j) = %p\n", v+(i-j));
1774 When this code is on. then the output looks like
1775 v+i-j = 0xfffffffe
1776 v+(i-j) = 0xbff84000
1778 /* if evaluating constant expression, no code should be
1779 generated, so no bound check */
1780 if (tcc_state->do_bounds_check && !const_wanted) {
1781 /* if bounded pointers, we generate a special code to
1782 test bounds */
1783 if (op == '-') {
1784 vpushi(0);
1785 vswap();
1786 gen_op('-');
1788 gen_bounded_ptr_add();
1789 } else
1790 #endif
1792 gen_opic(op);
1794 /* put again type if gen_opic() swaped operands */
1795 vtop->type = type1;
1797 } else if (is_float(bt1) || is_float(bt2)) {
1798 /* compute bigger type and do implicit casts */
1799 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
1800 t = VT_LDOUBLE;
1801 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
1802 t = VT_DOUBLE;
1803 } else {
1804 t = VT_FLOAT;
1806 /* floats can only be used for a few operations */
1807 if (op != '+' && op != '-' && op != '*' && op != '/' &&
1808 (op < TOK_ULT || op > TOK_GT))
1809 tcc_error("invalid operands for binary operation");
1810 goto std_op;
1811 } else if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL) {
1812 t = bt1 == VT_LLONG ? VT_LLONG : VT_INT;
1813 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (t | VT_UNSIGNED))
1814 t |= VT_UNSIGNED;
1815 goto std_op;
1816 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
1817 /* cast to biggest op */
1818 t = VT_LLONG;
1819 /* convert to unsigned if it does not fit in a long long */
1820 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
1821 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
1822 t |= VT_UNSIGNED;
1823 goto std_op;
1824 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
1825 tcc_error("comparison of struct");
1826 } else {
1827 /* integer operations */
1828 t = VT_INT;
1829 /* convert to unsigned if it does not fit in an integer */
1830 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
1831 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
1832 t |= VT_UNSIGNED;
1833 std_op:
1834 /* XXX: currently, some unsigned operations are explicit, so
1835 we modify them here */
1836 if (t & VT_UNSIGNED) {
1837 if (op == TOK_SAR)
1838 op = TOK_SHR;
1839 else if (op == '/')
1840 op = TOK_UDIV;
1841 else if (op == '%')
1842 op = TOK_UMOD;
1843 else if (op == TOK_LT)
1844 op = TOK_ULT;
1845 else if (op == TOK_GT)
1846 op = TOK_UGT;
1847 else if (op == TOK_LE)
1848 op = TOK_ULE;
1849 else if (op == TOK_GE)
1850 op = TOK_UGE;
1852 vswap();
1853 type1.t = t;
1854 gen_cast(&type1);
1855 vswap();
1856 /* special case for shifts and long long: we keep the shift as
1857 an integer */
1858 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
1859 type1.t = VT_INT;
1860 gen_cast(&type1);
1861 if (is_float(t))
1862 gen_opif(op);
1863 else
1864 gen_opic(op);
1865 if (op >= TOK_ULT && op <= TOK_GT) {
1866 /* relationnal op: the result is an int */
1867 vtop->type.t = VT_INT;
1868 } else {
1869 vtop->type.t = t;
1872 // Make sure that we have converted to an rvalue:
1873 if (vtop->r & VT_LVAL && !nocode_wanted)
1874 gv(is_float(vtop->type.t & VT_BTYPE) ? RC_FLOAT : RC_INT);
1877 #ifndef TCC_TARGET_ARM
1878 /* generic itof for unsigned long long case */
1879 static void gen_cvt_itof1(int t)
1881 #ifdef TCC_TARGET_ARM64
1882 gen_cvt_itof(t);
1883 #else
1884 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
1885 (VT_LLONG | VT_UNSIGNED)) {
1887 if (t == VT_FLOAT)
1888 vpush_global_sym(&func_old_type, TOK___floatundisf);
1889 #if LDOUBLE_SIZE != 8
1890 else if (t == VT_LDOUBLE)
1891 vpush_global_sym(&func_old_type, TOK___floatundixf);
1892 #endif
1893 else
1894 vpush_global_sym(&func_old_type, TOK___floatundidf);
1895 vrott(2);
1896 gfunc_call(1);
1897 vpushi(0);
1898 vtop->r = reg_fret(t);
1899 } else {
1900 gen_cvt_itof(t);
1902 #endif
1904 #endif
1906 /* generic ftoi for unsigned long long case */
1907 static void gen_cvt_ftoi1(int t)
1909 #ifdef TCC_TARGET_ARM64
1910 gen_cvt_ftoi(t);
1911 #else
1912 int st;
1914 if (t == (VT_LLONG | VT_UNSIGNED)) {
1915 /* not handled natively */
1916 st = vtop->type.t & VT_BTYPE;
1917 if (st == VT_FLOAT)
1918 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
1919 #if LDOUBLE_SIZE != 8
1920 else if (st == VT_LDOUBLE)
1921 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
1922 #endif
1923 else
1924 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
1925 vrott(2);
1926 gfunc_call(1);
1927 vpushi(0);
1928 vtop->r = REG_IRET;
1929 vtop->r2 = REG_LRET;
1930 } else {
1931 gen_cvt_ftoi(t);
1933 #endif
1936 /* force char or short cast */
1937 static void force_charshort_cast(int t)
1939 int bits, dbt;
1940 dbt = t & VT_BTYPE;
1941 /* XXX: add optimization if lvalue : just change type and offset */
1942 if (dbt == VT_BYTE)
1943 bits = 8;
1944 else
1945 bits = 16;
1946 if (t & VT_UNSIGNED) {
1947 vpushi((1 << bits) - 1);
1948 gen_op('&');
1949 } else {
1950 bits = 32 - bits;
1951 vpushi(bits);
1952 gen_op(TOK_SHL);
1953 /* result must be signed or the SAR is converted to an SHL
1954 This was not the case when "t" was a signed short
1955 and the last value on the stack was an unsigned int */
1956 vtop->type.t &= ~VT_UNSIGNED;
1957 vpushi(bits);
1958 gen_op(TOK_SAR);
1962 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
1963 static void gen_cast(CType *type)
1965 int sbt, dbt, sf, df, c, p;
1967 /* special delayed cast for char/short */
1968 /* XXX: in some cases (multiple cascaded casts), it may still
1969 be incorrect */
1970 if (vtop->r & VT_MUSTCAST) {
1971 vtop->r &= ~VT_MUSTCAST;
1972 force_charshort_cast(vtop->type.t);
1975 /* bitfields first get cast to ints */
1976 if (vtop->type.t & VT_BITFIELD && !nocode_wanted) {
1977 gv(RC_INT);
1980 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
1981 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
1983 if (sbt != dbt) {
1984 sf = is_float(sbt);
1985 df = is_float(dbt);
1986 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1987 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
1988 if (c) {
1989 /* constant case: we can do it now */
1990 /* XXX: in ISOC, cannot do it if error in convert */
1991 if (sbt == VT_FLOAT)
1992 vtop->c.ld = vtop->c.f;
1993 else if (sbt == VT_DOUBLE)
1994 vtop->c.ld = vtop->c.d;
1996 if (df) {
1997 if ((sbt & VT_BTYPE) == VT_LLONG) {
1998 if ((sbt & VT_UNSIGNED) || !(vtop->c.i >> 63))
1999 vtop->c.ld = vtop->c.i;
2000 else
2001 vtop->c.ld = -(long double)-vtop->c.i;
2002 } else if(!sf) {
2003 if ((sbt & VT_UNSIGNED) || !(vtop->c.i >> 31))
2004 vtop->c.ld = (uint32_t)vtop->c.i;
2005 else
2006 vtop->c.ld = -(long double)-(uint32_t)vtop->c.i;
2009 if (dbt == VT_FLOAT)
2010 vtop->c.f = (float)vtop->c.ld;
2011 else if (dbt == VT_DOUBLE)
2012 vtop->c.d = (double)vtop->c.ld;
2013 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
2014 vtop->c.i = vtop->c.ld;
2015 } else if (sf && dbt == VT_BOOL) {
2016 vtop->c.i = (vtop->c.ld != 0);
2017 } else {
2018 if(sf)
2019 vtop->c.i = vtop->c.ld;
2020 else if (sbt == (VT_LLONG|VT_UNSIGNED))
2022 else if (sbt & VT_UNSIGNED)
2023 vtop->c.i = (uint32_t)vtop->c.i;
2024 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2025 else if (sbt == VT_PTR)
2027 #endif
2028 else if (sbt != VT_LLONG)
2029 vtop->c.i = ((uint32_t)vtop->c.i |
2030 -(vtop->c.i & 0x80000000));
2032 if (dbt == (VT_LLONG|VT_UNSIGNED))
2034 else if (dbt == VT_BOOL)
2035 vtop->c.i = (vtop->c.i != 0);
2036 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2037 else if (dbt == VT_PTR)
2039 #endif
2040 else if (dbt != VT_LLONG) {
2041 uint32_t m = ((dbt & VT_BTYPE) == VT_BYTE ? 0xff :
2042 (dbt & VT_BTYPE) == VT_SHORT ? 0xffff :
2043 0xffffffff);
2044 vtop->c.i &= m;
2045 if (!(dbt & VT_UNSIGNED))
2046 vtop->c.i |= -(vtop->c.i & ((m >> 1) + 1));
2049 } else if (p && dbt == VT_BOOL) {
2050 vtop->r = VT_CONST;
2051 vtop->c.i = 1;
2052 } else if (!nocode_wanted) {
2053 /* non constant case: generate code */
2054 if (sf && df) {
2055 /* convert from fp to fp */
2056 gen_cvt_ftof(dbt);
2057 } else if (df) {
2058 /* convert int to fp */
2059 gen_cvt_itof1(dbt);
2060 } else if (sf) {
2061 /* convert fp to int */
2062 if (dbt == VT_BOOL) {
2063 vpushi(0);
2064 gen_op(TOK_NE);
2065 } else {
2066 /* we handle char/short/etc... with generic code */
2067 if (dbt != (VT_INT | VT_UNSIGNED) &&
2068 dbt != (VT_LLONG | VT_UNSIGNED) &&
2069 dbt != VT_LLONG)
2070 dbt = VT_INT;
2071 gen_cvt_ftoi1(dbt);
2072 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
2073 /* additional cast for char/short... */
2074 vtop->type.t = dbt;
2075 gen_cast(type);
2078 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
2079 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
2080 if ((sbt & VT_BTYPE) != VT_LLONG && !nocode_wanted) {
2081 /* scalar to long long */
2082 /* machine independent conversion */
2083 gv(RC_INT);
2084 /* generate high word */
2085 if (sbt == (VT_INT | VT_UNSIGNED)) {
2086 vpushi(0);
2087 gv(RC_INT);
2088 } else {
2089 if (sbt == VT_PTR) {
2090 /* cast from pointer to int before we apply
2091 shift operation, which pointers don't support*/
2092 gen_cast(&int_type);
2094 gv_dup();
2095 vpushi(31);
2096 gen_op(TOK_SAR);
2098 /* patch second register */
2099 vtop[-1].r2 = vtop->r;
2100 vpop();
2102 #else
2103 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
2104 (dbt & VT_BTYPE) == VT_PTR ||
2105 (dbt & VT_BTYPE) == VT_FUNC) {
2106 if ((sbt & VT_BTYPE) != VT_LLONG &&
2107 (sbt & VT_BTYPE) != VT_PTR &&
2108 (sbt & VT_BTYPE) != VT_FUNC && !nocode_wanted) {
2109 /* need to convert from 32bit to 64bit */
2110 gv(RC_INT);
2111 if (sbt != (VT_INT | VT_UNSIGNED)) {
2112 #if defined(TCC_TARGET_ARM64)
2113 gen_cvt_sxtw();
2114 #elif defined(TCC_TARGET_X86_64)
2115 int r = gv(RC_INT);
2116 /* x86_64 specific: movslq */
2117 o(0x6348);
2118 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
2119 #else
2120 #error
2121 #endif
2124 #endif
2125 } else if (dbt == VT_BOOL) {
2126 /* scalar to bool */
2127 vpushi(0);
2128 gen_op(TOK_NE);
2129 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
2130 (dbt & VT_BTYPE) == VT_SHORT) {
2131 if (sbt == VT_PTR) {
2132 vtop->type.t = VT_INT;
2133 tcc_warning("nonportable conversion from pointer to char/short");
2135 force_charshort_cast(dbt);
2136 } else if ((dbt & VT_BTYPE) == VT_INT) {
2137 /* scalar to int */
2138 if (sbt == VT_LLONG && !nocode_wanted) {
2139 /* from long long: just take low order word */
2140 lexpand();
2141 vpop();
2143 /* if lvalue and single word type, nothing to do because
2144 the lvalue already contains the real type size (see
2145 VT_LVAL_xxx constants) */
2148 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
2149 /* if we are casting between pointer types,
2150 we must update the VT_LVAL_xxx size */
2151 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
2152 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
2154 vtop->type = *type;
2157 /* return type size as known at compile time. Put alignment at 'a' */
2158 ST_FUNC int type_size(CType *type, int *a)
2160 Sym *s;
2161 int bt;
2163 bt = type->t & VT_BTYPE;
2164 if (bt == VT_STRUCT) {
2165 /* struct/union */
2166 s = type->ref;
2167 *a = s->r;
2168 return s->c;
2169 } else if (bt == VT_PTR) {
2170 if (type->t & VT_ARRAY) {
2171 int ts;
2173 s = type->ref;
2174 ts = type_size(&s->type, a);
2176 if (ts < 0 && s->c < 0)
2177 ts = -ts;
2179 return ts * s->c;
2180 } else {
2181 *a = PTR_SIZE;
2182 return PTR_SIZE;
2184 } else if (bt == VT_LDOUBLE) {
2185 *a = LDOUBLE_ALIGN;
2186 return LDOUBLE_SIZE;
2187 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
2188 #ifdef TCC_TARGET_I386
2189 #ifdef TCC_TARGET_PE
2190 *a = 8;
2191 #else
2192 *a = 4;
2193 #endif
2194 #elif defined(TCC_TARGET_ARM)
2195 #ifdef TCC_ARM_EABI
2196 *a = 8;
2197 #else
2198 *a = 4;
2199 #endif
2200 #else
2201 *a = 8;
2202 #endif
2203 return 8;
2204 } else if (bt == VT_INT || bt == VT_FLOAT) {
2205 *a = 4;
2206 return 4;
2207 } else if (bt == VT_SHORT) {
2208 *a = 2;
2209 return 2;
2210 } else if (bt == VT_QLONG || bt == VT_QFLOAT) {
2211 *a = 8;
2212 return 16;
2213 } else if (bt == VT_ENUM) {
2214 *a = 4;
2215 /* Enums might be incomplete, so don't just return '4' here. */
2216 return type->ref->c;
2217 } else {
2218 /* char, void, function, _Bool */
2219 *a = 1;
2220 return 1;
2224 /* push type size as known at runtime time on top of value stack. Put
2225 alignment at 'a' */
2226 ST_FUNC void vla_runtime_type_size(CType *type, int *a)
2228 if (type->t & VT_VLA) {
2229 vset(&int_type, VT_LOCAL|VT_LVAL, type->ref->c);
2230 } else {
2231 vpushi(type_size(type, a));
2235 static void vla_sp_restore(void) {
2236 if (vlas_in_scope) {
2237 gen_vla_sp_restore(vla_sp_loc);
2241 static void vla_sp_restore_root(void) {
2242 if (vlas_in_scope) {
2243 gen_vla_sp_restore(vla_sp_root_loc);
2247 /* return the pointed type of t */
2248 static inline CType *pointed_type(CType *type)
2250 return &type->ref->type;
2253 /* modify type so that its it is a pointer to type. */
2254 ST_FUNC void mk_pointer(CType *type)
2256 Sym *s;
2257 s = sym_push(SYM_FIELD, type, 0, -1);
2258 type->t = VT_PTR | (type->t & ~VT_TYPE);
2259 type->ref = s;
2262 /* compare function types. OLD functions match any new functions */
2263 static int is_compatible_func(CType *type1, CType *type2)
2265 Sym *s1, *s2;
2267 s1 = type1->ref;
2268 s2 = type2->ref;
2269 if (!is_compatible_types(&s1->type, &s2->type))
2270 return 0;
2271 /* check func_call */
2272 if (s1->a.func_call != s2->a.func_call)
2273 return 0;
2274 /* XXX: not complete */
2275 if (s1->c == FUNC_OLD || s2->c == FUNC_OLD)
2276 return 1;
2277 if (s1->c != s2->c)
2278 return 0;
2279 while (s1 != NULL) {
2280 if (s2 == NULL)
2281 return 0;
2282 if (!is_compatible_parameter_types(&s1->type, &s2->type))
2283 return 0;
2284 s1 = s1->next;
2285 s2 = s2->next;
2287 if (s2)
2288 return 0;
2289 return 1;
2292 /* return true if type1 and type2 are the same. If unqualified is
2293 true, qualifiers on the types are ignored.
2295 - enums are not checked as gcc __builtin_types_compatible_p ()
2297 static int compare_types(CType *type1, CType *type2, int unqualified)
2299 int bt1, t1, t2;
2301 t1 = type1->t & VT_TYPE;
2302 t2 = type2->t & VT_TYPE;
2303 if (unqualified) {
2304 /* strip qualifiers before comparing */
2305 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
2306 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
2308 /* Default Vs explicit signedness only matters for char */
2309 if ((t1 & VT_BTYPE) != VT_BYTE) {
2310 t1 &= ~VT_DEFSIGN;
2311 t2 &= ~VT_DEFSIGN;
2313 /* XXX: bitfields ? */
2314 if (t1 != t2)
2315 return 0;
2316 /* test more complicated cases */
2317 bt1 = t1 & VT_BTYPE;
2318 if (bt1 == VT_PTR) {
2319 type1 = pointed_type(type1);
2320 type2 = pointed_type(type2);
2321 return is_compatible_types(type1, type2);
2322 } else if (bt1 == VT_STRUCT) {
2323 return (type1->ref == type2->ref);
2324 } else if (bt1 == VT_FUNC) {
2325 return is_compatible_func(type1, type2);
2326 } else {
2327 return 1;
2331 /* return true if type1 and type2 are exactly the same (including
2332 qualifiers).
2334 static int is_compatible_types(CType *type1, CType *type2)
2336 return compare_types(type1,type2,0);
2339 /* return true if type1 and type2 are the same (ignoring qualifiers).
2341 static int is_compatible_parameter_types(CType *type1, CType *type2)
2343 return compare_types(type1,type2,1);
2346 /* print a type. If 'varstr' is not NULL, then the variable is also
2347 printed in the type */
2348 /* XXX: union */
2349 /* XXX: add array and function pointers */
2350 static void type_to_str(char *buf, int buf_size,
2351 CType *type, const char *varstr)
2353 int bt, v, t;
2354 Sym *s, *sa;
2355 char buf1[256];
2356 const char *tstr;
2358 t = type->t & VT_TYPE;
2359 bt = t & VT_BTYPE;
2360 buf[0] = '\0';
2361 if (t & VT_CONSTANT)
2362 pstrcat(buf, buf_size, "const ");
2363 if (t & VT_VOLATILE)
2364 pstrcat(buf, buf_size, "volatile ");
2365 if ((t & (VT_DEFSIGN | VT_UNSIGNED)) == (VT_DEFSIGN | VT_UNSIGNED))
2366 pstrcat(buf, buf_size, "unsigned ");
2367 else if (t & VT_DEFSIGN)
2368 pstrcat(buf, buf_size, "signed ");
2369 switch(bt) {
2370 case VT_VOID:
2371 tstr = "void";
2372 goto add_tstr;
2373 case VT_BOOL:
2374 tstr = "_Bool";
2375 goto add_tstr;
2376 case VT_BYTE:
2377 tstr = "char";
2378 goto add_tstr;
2379 case VT_SHORT:
2380 tstr = "short";
2381 goto add_tstr;
2382 case VT_INT:
2383 tstr = "int";
2384 goto add_tstr;
2385 case VT_LONG:
2386 tstr = "long";
2387 goto add_tstr;
2388 case VT_LLONG:
2389 tstr = "long long";
2390 goto add_tstr;
2391 case VT_FLOAT:
2392 tstr = "float";
2393 goto add_tstr;
2394 case VT_DOUBLE:
2395 tstr = "double";
2396 goto add_tstr;
2397 case VT_LDOUBLE:
2398 tstr = "long double";
2399 add_tstr:
2400 pstrcat(buf, buf_size, tstr);
2401 break;
2402 case VT_ENUM:
2403 case VT_STRUCT:
2404 if (bt == VT_STRUCT)
2405 tstr = "struct ";
2406 else
2407 tstr = "enum ";
2408 pstrcat(buf, buf_size, tstr);
2409 v = type->ref->v & ~SYM_STRUCT;
2410 if (v >= SYM_FIRST_ANOM)
2411 pstrcat(buf, buf_size, "<anonymous>");
2412 else
2413 pstrcat(buf, buf_size, get_tok_str(v, NULL));
2414 break;
2415 case VT_FUNC:
2416 s = type->ref;
2417 type_to_str(buf, buf_size, &s->type, varstr);
2418 pstrcat(buf, buf_size, "(");
2419 sa = s->next;
2420 while (sa != NULL) {
2421 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
2422 pstrcat(buf, buf_size, buf1);
2423 sa = sa->next;
2424 if (sa)
2425 pstrcat(buf, buf_size, ", ");
2427 pstrcat(buf, buf_size, ")");
2428 goto no_var;
2429 case VT_PTR:
2430 s = type->ref;
2431 if (t & VT_ARRAY) {
2432 snprintf(buf1, sizeof(buf1), "%s[%ld]", varstr ? varstr : "", s->c);
2433 type_to_str(buf, buf_size, &s->type, buf1);
2434 goto no_var;
2436 pstrcpy(buf1, sizeof(buf1), "*");
2437 if (t & VT_CONSTANT)
2438 pstrcat(buf1, buf_size, "const ");
2439 if (t & VT_VOLATILE)
2440 pstrcat(buf1, buf_size, "volatile ");
2441 if (varstr)
2442 pstrcat(buf1, sizeof(buf1), varstr);
2443 type_to_str(buf, buf_size, &s->type, buf1);
2444 goto no_var;
2446 if (varstr) {
2447 pstrcat(buf, buf_size, " ");
2448 pstrcat(buf, buf_size, varstr);
2450 no_var: ;
2453 /* verify type compatibility to store vtop in 'dt' type, and generate
2454 casts if needed. */
2455 static void gen_assign_cast(CType *dt)
2457 CType *st, *type1, *type2, tmp_type1, tmp_type2;
2458 char buf1[256], buf2[256];
2459 int dbt, sbt;
2461 st = &vtop->type; /* source type */
2462 dbt = dt->t & VT_BTYPE;
2463 sbt = st->t & VT_BTYPE;
2464 if (sbt == VT_VOID || dbt == VT_VOID) {
2465 if (sbt == VT_VOID && dbt == VT_VOID)
2466 ; /*
2467 It is Ok if both are void
2468 A test program:
2469 void func1() {}
2470 void func2() {
2471 return func1();
2473 gcc accepts this program
2475 else
2476 tcc_error("cannot cast from/to void");
2478 if (dt->t & VT_CONSTANT)
2479 tcc_warning("assignment of read-only location");
2480 switch(dbt) {
2481 case VT_PTR:
2482 /* special cases for pointers */
2483 /* '0' can also be a pointer */
2484 if (is_null_pointer(vtop))
2485 goto type_ok;
2486 /* accept implicit pointer to integer cast with warning */
2487 if (is_integer_btype(sbt)) {
2488 tcc_warning("assignment makes pointer from integer without a cast");
2489 goto type_ok;
2491 type1 = pointed_type(dt);
2492 /* a function is implicitely a function pointer */
2493 if (sbt == VT_FUNC) {
2494 if ((type1->t & VT_BTYPE) != VT_VOID &&
2495 !is_compatible_types(pointed_type(dt), st))
2496 tcc_warning("assignment from incompatible pointer type");
2497 goto type_ok;
2499 if (sbt != VT_PTR)
2500 goto error;
2501 type2 = pointed_type(st);
2502 if ((type1->t & VT_BTYPE) == VT_VOID ||
2503 (type2->t & VT_BTYPE) == VT_VOID) {
2504 /* void * can match anything */
2505 } else {
2506 /* exact type match, except for unsigned */
2507 tmp_type1 = *type1;
2508 tmp_type2 = *type2;
2509 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT |
2510 VT_VOLATILE);
2511 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT |
2512 VT_VOLATILE);
2513 if (!is_compatible_types(&tmp_type1, &tmp_type2))
2514 tcc_warning("assignment from incompatible pointer type");
2516 /* check const and volatile */
2517 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
2518 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
2519 tcc_warning("assignment discards qualifiers from pointer target type");
2520 break;
2521 case VT_BYTE:
2522 case VT_SHORT:
2523 case VT_INT:
2524 case VT_LLONG:
2525 if (sbt == VT_PTR || sbt == VT_FUNC) {
2526 tcc_warning("assignment makes integer from pointer without a cast");
2528 /* XXX: more tests */
2529 break;
2530 case VT_STRUCT:
2531 tmp_type1 = *dt;
2532 tmp_type2 = *st;
2533 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2534 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2535 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2536 error:
2537 type_to_str(buf1, sizeof(buf1), st, NULL);
2538 type_to_str(buf2, sizeof(buf2), dt, NULL);
2539 tcc_error("cannot cast '%s' to '%s'", buf1, buf2);
2541 break;
2543 type_ok:
2544 gen_cast(dt);
2547 /* store vtop in lvalue pushed on stack */
2548 ST_FUNC void vstore(void)
2550 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
2552 ft = vtop[-1].type.t;
2553 sbt = vtop->type.t & VT_BTYPE;
2554 dbt = ft & VT_BTYPE;
2555 if ((((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
2556 (sbt == VT_INT && dbt == VT_SHORT))
2557 && !(vtop->type.t & VT_BITFIELD)) {
2558 /* optimize char/short casts */
2559 delayed_cast = VT_MUSTCAST;
2560 vtop->type.t = (ft & VT_TYPE & ~VT_BITFIELD &
2561 ((1 << VT_STRUCT_SHIFT) - 1));
2562 /* XXX: factorize */
2563 if (ft & VT_CONSTANT)
2564 tcc_warning("assignment of read-only location");
2565 } else {
2566 delayed_cast = 0;
2567 if (!(ft & VT_BITFIELD))
2568 gen_assign_cast(&vtop[-1].type);
2571 if (sbt == VT_STRUCT) {
2572 /* if structure, only generate pointer */
2573 /* structure assignment : generate memcpy */
2574 /* XXX: optimize if small size */
2575 if (!nocode_wanted) {
2576 size = type_size(&vtop->type, &align);
2578 /* destination */
2579 vswap();
2580 vtop->type.t = VT_PTR;
2581 gaddrof();
2583 /* address of memcpy() */
2584 #ifdef TCC_ARM_EABI
2585 if(!(align & 7))
2586 vpush_global_sym(&func_old_type, TOK_memcpy8);
2587 else if(!(align & 3))
2588 vpush_global_sym(&func_old_type, TOK_memcpy4);
2589 else
2590 #endif
2591 /* Use memmove, rather than memcpy, as dest and src may be same: */
2592 vpush_global_sym(&func_old_type, TOK_memmove);
2594 vswap();
2595 /* source */
2596 vpushv(vtop - 2);
2597 vtop->type.t = VT_PTR;
2598 gaddrof();
2599 /* type size */
2600 vpushi(size);
2601 gfunc_call(3);
2602 } else {
2603 vswap();
2604 vpop();
2606 /* leave source on stack */
2607 } else if (ft & VT_BITFIELD) {
2608 /* bitfield store handling */
2610 /* save lvalue as expression result (example: s.b = s.a = n;) */
2611 vdup(), vtop[-1] = vtop[-2];
2613 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
2614 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
2615 /* remove bit field info to avoid loops */
2616 vtop[-1].type.t = ft & ~VT_BITFIELD & ((1 << VT_STRUCT_SHIFT) - 1);
2618 if((ft & VT_BTYPE) == VT_BOOL) {
2619 gen_cast(&vtop[-1].type);
2620 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
2623 /* duplicate destination */
2624 vdup();
2625 vtop[-1] = vtop[-2];
2627 /* mask and shift source */
2628 if((ft & VT_BTYPE) != VT_BOOL) {
2629 if((ft & VT_BTYPE) == VT_LLONG) {
2630 vpushll((1ULL << bit_size) - 1ULL);
2631 } else {
2632 vpushi((1 << bit_size) - 1);
2634 gen_op('&');
2636 vpushi(bit_pos);
2637 gen_op(TOK_SHL);
2638 /* load destination, mask and or with source */
2639 vswap();
2640 if((ft & VT_BTYPE) == VT_LLONG) {
2641 vpushll(~(((1ULL << bit_size) - 1ULL) << bit_pos));
2642 } else {
2643 vpushi(~(((1 << bit_size) - 1) << bit_pos));
2645 gen_op('&');
2646 gen_op('|');
2647 /* store result */
2648 vstore();
2649 /* ... and discard */
2650 vpop();
2652 } else {
2653 if (!nocode_wanted) {
2654 #ifdef CONFIG_TCC_BCHECK
2655 /* bound check case */
2656 if (vtop[-1].r & VT_MUSTBOUND) {
2657 vswap();
2658 gbound();
2659 vswap();
2661 #endif
2662 rc = RC_INT;
2663 if (is_float(ft)) {
2664 rc = RC_FLOAT;
2665 #ifdef TCC_TARGET_X86_64
2666 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
2667 rc = RC_ST0;
2668 } else if ((ft & VT_BTYPE) == VT_QFLOAT) {
2669 rc = RC_FRET;
2671 #endif
2673 r = gv(rc); /* generate value */
2674 /* if lvalue was saved on stack, must read it */
2675 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
2676 SValue sv;
2677 t = get_reg(RC_INT);
2678 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2679 sv.type.t = VT_PTR;
2680 #else
2681 sv.type.t = VT_INT;
2682 #endif
2683 sv.r = VT_LOCAL | VT_LVAL;
2684 sv.c.i = vtop[-1].c.i;
2685 load(t, &sv);
2686 vtop[-1].r = t | VT_LVAL;
2688 /* two word case handling : store second register at word + 4 (or +8 for x86-64) */
2689 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2690 if (((ft & VT_BTYPE) == VT_QLONG) || ((ft & VT_BTYPE) == VT_QFLOAT)) {
2691 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
2692 #else
2693 if ((ft & VT_BTYPE) == VT_LLONG) {
2694 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
2695 #endif
2696 vtop[-1].type.t = load_type;
2697 store(r, vtop - 1);
2698 vswap();
2699 /* convert to int to increment easily */
2700 vtop->type.t = addr_type;
2701 gaddrof();
2702 vpushi(load_size);
2703 gen_op('+');
2704 vtop->r |= VT_LVAL;
2705 vswap();
2706 vtop[-1].type.t = load_type;
2707 /* XXX: it works because r2 is spilled last ! */
2708 store(vtop->r2, vtop - 1);
2709 } else {
2710 store(r, vtop - 1);
2713 vswap();
2714 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
2715 vtop->r |= delayed_cast;
2719 /* post defines POST/PRE add. c is the token ++ or -- */
2720 ST_FUNC void inc(int post, int c)
2722 test_lvalue();
2723 vdup(); /* save lvalue */
2724 if (post) {
2725 if (!nocode_wanted)
2726 gv_dup(); /* duplicate value */
2727 else
2728 vdup(); /* duplicate value */
2729 vrotb(3);
2730 vrotb(3);
2732 /* add constant */
2733 vpushi(c - TOK_MID);
2734 gen_op('+');
2735 vstore(); /* store value */
2736 if (post)
2737 vpop(); /* if post op, return saved value */
2740 /* Parse GNUC __attribute__ extension. Currently, the following
2741 extensions are recognized:
2742 - aligned(n) : set data/function alignment.
2743 - packed : force data alignment to 1
2744 - section(x) : generate data/code in this section.
2745 - unused : currently ignored, but may be used someday.
2746 - regparm(n) : pass function parameters in registers (i386 only)
2748 static void parse_attribute(AttributeDef *ad)
2750 int t, n;
2752 while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
2753 next();
2754 skip('(');
2755 skip('(');
2756 while (tok != ')') {
2757 if (tok < TOK_IDENT)
2758 expect("attribute name");
2759 t = tok;
2760 next();
2761 switch(t) {
2762 case TOK_SECTION1:
2763 case TOK_SECTION2:
2764 skip('(');
2765 if (tok != TOK_STR)
2766 expect("section name");
2767 ad->section = find_section(tcc_state, (char *)tokc.str.data);
2768 next();
2769 skip(')');
2770 break;
2771 case TOK_ALIAS1:
2772 case TOK_ALIAS2:
2773 skip('(');
2774 if (tok != TOK_STR)
2775 expect("alias(\"target\")");
2776 ad->alias_target = /* save string as token, for later */
2777 tok_alloc((char*)tokc.str.data, tokc.str.size-1)->tok;
2778 next();
2779 skip(')');
2780 break;
2781 case TOK_VISIBILITY1:
2782 case TOK_VISIBILITY2:
2783 skip('(');
2784 if (tok != TOK_STR)
2785 expect("visibility(\"default|hidden|internal|protected\")");
2786 if (!strcmp (tokc.str.data, "default"))
2787 ad->a.visibility = STV_DEFAULT;
2788 else if (!strcmp (tokc.str.data, "hidden"))
2789 ad->a.visibility = STV_HIDDEN;
2790 else if (!strcmp (tokc.str.data, "internal"))
2791 ad->a.visibility = STV_INTERNAL;
2792 else if (!strcmp (tokc.str.data, "protected"))
2793 ad->a.visibility = STV_PROTECTED;
2794 else
2795 expect("visibility(\"default|hidden|internal|protected\")");
2796 next();
2797 skip(')');
2798 break;
2799 case TOK_ALIGNED1:
2800 case TOK_ALIGNED2:
2801 if (tok == '(') {
2802 next();
2803 n = expr_const();
2804 if (n <= 0 || (n & (n - 1)) != 0)
2805 tcc_error("alignment must be a positive power of two");
2806 skip(')');
2807 } else {
2808 n = MAX_ALIGN;
2810 ad->a.aligned = n;
2811 break;
2812 case TOK_PACKED1:
2813 case TOK_PACKED2:
2814 ad->a.packed = 1;
2815 break;
2816 case TOK_WEAK1:
2817 case TOK_WEAK2:
2818 ad->a.weak = 1;
2819 break;
2820 case TOK_UNUSED1:
2821 case TOK_UNUSED2:
2822 /* currently, no need to handle it because tcc does not
2823 track unused objects */
2824 break;
2825 case TOK_NORETURN1:
2826 case TOK_NORETURN2:
2827 /* currently, no need to handle it because tcc does not
2828 track unused objects */
2829 break;
2830 case TOK_CDECL1:
2831 case TOK_CDECL2:
2832 case TOK_CDECL3:
2833 ad->a.func_call = FUNC_CDECL;
2834 break;
2835 case TOK_STDCALL1:
2836 case TOK_STDCALL2:
2837 case TOK_STDCALL3:
2838 ad->a.func_call = FUNC_STDCALL;
2839 break;
2840 #ifdef TCC_TARGET_I386
2841 case TOK_REGPARM1:
2842 case TOK_REGPARM2:
2843 skip('(');
2844 n = expr_const();
2845 if (n > 3)
2846 n = 3;
2847 else if (n < 0)
2848 n = 0;
2849 if (n > 0)
2850 ad->a.func_call = FUNC_FASTCALL1 + n - 1;
2851 skip(')');
2852 break;
2853 case TOK_FASTCALL1:
2854 case TOK_FASTCALL2:
2855 case TOK_FASTCALL3:
2856 ad->a.func_call = FUNC_FASTCALLW;
2857 break;
2858 #endif
2859 case TOK_MODE:
2860 skip('(');
2861 switch(tok) {
2862 case TOK_MODE_DI:
2863 ad->a.mode = VT_LLONG + 1;
2864 break;
2865 case TOK_MODE_HI:
2866 ad->a.mode = VT_SHORT + 1;
2867 break;
2868 case TOK_MODE_SI:
2869 ad->a.mode = VT_INT + 1;
2870 break;
2871 default:
2872 tcc_warning("__mode__(%s) not supported\n", get_tok_str(tok, NULL));
2873 break;
2875 next();
2876 skip(')');
2877 break;
2878 case TOK_DLLEXPORT:
2879 ad->a.func_export = 1;
2880 break;
2881 case TOK_DLLIMPORT:
2882 ad->a.func_import = 1;
2883 break;
2884 default:
2885 if (tcc_state->warn_unsupported)
2886 tcc_warning("'%s' attribute ignored", get_tok_str(t, NULL));
2887 /* skip parameters */
2888 if (tok == '(') {
2889 int parenthesis = 0;
2890 do {
2891 if (tok == '(')
2892 parenthesis++;
2893 else if (tok == ')')
2894 parenthesis--;
2895 next();
2896 } while (parenthesis && tok != -1);
2898 break;
2900 if (tok != ',')
2901 break;
2902 next();
2904 skip(')');
2905 skip(')');
2909 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
2910 static void struct_decl(CType *type, AttributeDef *ad, int u)
2912 int a, v, size, align, maxalign, c, offset, flexible;
2913 int bit_size, bit_pos, bsize, bt, lbit_pos, prevbt;
2914 Sym *s, *ss, *ass, **ps;
2915 AttributeDef ad1;
2916 CType type1, btype;
2918 a = tok; /* save decl type */
2919 next();
2920 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
2921 parse_attribute(ad);
2922 next();
2924 if (tok != '{') {
2925 v = tok;
2926 next();
2927 /* struct already defined ? return it */
2928 if (v < TOK_IDENT)
2929 expect("struct/union/enum name");
2930 s = struct_find(v);
2931 if (s && s->type.t == a) {
2932 if (tok != '{' && tok != ';')
2933 goto do_decl; /* variable declaration: 'struct s x;' */
2934 if (s->scope == local_scope && (s->c == -1 || tok != '{'))
2935 goto do_decl; /* at least one must be incomplete type */
2937 } else {
2938 v = anon_sym++;
2940 type1.t = a;
2941 type1.ref = NULL;
2942 /* we put an undefined size for struct/union */
2943 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
2944 s->r = 0; /* default alignment is zero as gcc */
2945 /* put struct/union/enum name in type */
2946 do_decl:
2947 type->t = u;
2948 type->ref = s;
2950 if (tok == '{') {
2951 next();
2952 if (s->c != -1)
2953 tcc_error("struct/union/enum already defined");
2954 /* cannot be empty */
2955 c = 0;
2956 /* non empty enums are not allowed */
2957 if (a == TOK_ENUM) {
2958 for(;;) {
2959 v = tok;
2960 if (v < TOK_UIDENT)
2961 expect("identifier");
2962 ss = sym_find(v);
2963 if (ss && !local_stack)
2964 tcc_error("redefinition of enumerator '%s'",
2965 get_tok_str(v, NULL));
2966 next();
2967 if (tok == '=') {
2968 next();
2969 c = expr_const();
2971 /* enum symbols have static storage */
2972 ss = sym_push(v, &int_type, VT_CONST, c);
2973 ss->type.t |= VT_STATIC;
2974 if (tok != ',')
2975 break;
2976 next();
2977 c++;
2978 /* NOTE: we accept a trailing comma */
2979 if (tok == '}')
2980 break;
2982 s->c = type_size(&int_type, &align);
2983 skip('}');
2984 } else {
2985 maxalign = 1;
2986 ps = &s->next;
2987 prevbt = VT_INT;
2988 bit_pos = 0;
2989 offset = 0;
2990 flexible = 0;
2991 while (tok != '}') {
2992 parse_btype(&btype, &ad1);
2993 while (1) {
2994 if (flexible)
2995 tcc_error("flexible array member '%s' not at the end of struct",
2996 get_tok_str(v, NULL));
2997 bit_size = -1;
2998 v = 0;
2999 type1 = btype;
3000 if (tok != ':') {
3001 type_decl(&type1, &ad1, &v, TYPE_DIRECT | TYPE_ABSTRACT);
3002 if (v == 0) {
3003 if ((type1.t & VT_BTYPE) != VT_STRUCT)
3004 expect("identifier");
3005 else {
3006 int v = btype.ref->v;
3007 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
3008 if (tcc_state->ms_extensions == 0)
3009 expect("identifier");
3013 if (type_size(&type1, &align) < 0) {
3014 if ((a == TOK_STRUCT) && (type1.t & VT_ARRAY) && c)
3015 flexible = 1;
3016 else
3017 tcc_error("field '%s' has incomplete type",
3018 get_tok_str(v, NULL));
3020 if ((type1.t & VT_BTYPE) == VT_FUNC ||
3021 (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
3022 tcc_error("invalid type for '%s'",
3023 get_tok_str(v, NULL));
3025 if (tok == ':') {
3026 next();
3027 bit_size = expr_const();
3028 /* XXX: handle v = 0 case for messages */
3029 if (bit_size < 0)
3030 tcc_error("negative width in bit-field '%s'",
3031 get_tok_str(v, NULL));
3032 if (v && bit_size == 0)
3033 tcc_error("zero width for bit-field '%s'",
3034 get_tok_str(v, NULL));
3036 size = type_size(&type1, &align);
3037 if (ad1.a.aligned) {
3038 if (align < ad1.a.aligned)
3039 align = ad1.a.aligned;
3040 } else if (ad1.a.packed) {
3041 align = 1;
3042 } else if (*tcc_state->pack_stack_ptr) {
3043 if (align > *tcc_state->pack_stack_ptr)
3044 align = *tcc_state->pack_stack_ptr;
3046 lbit_pos = 0;
3047 if (bit_size >= 0) {
3048 bt = type1.t & VT_BTYPE;
3049 if (bt != VT_INT &&
3050 bt != VT_BYTE &&
3051 bt != VT_SHORT &&
3052 bt != VT_BOOL &&
3053 bt != VT_ENUM &&
3054 bt != VT_LLONG)
3055 tcc_error("bitfields must have scalar type");
3056 bsize = size * 8;
3057 if (bit_size > bsize) {
3058 tcc_error("width of '%s' exceeds its type",
3059 get_tok_str(v, NULL));
3060 } else if (bit_size == bsize) {
3061 /* no need for bit fields */
3062 bit_pos = 0;
3063 } else if (bit_size == 0) {
3064 /* XXX: what to do if only padding in a
3065 structure ? */
3066 /* zero size: means to pad */
3067 bit_pos = 0;
3068 } else {
3069 /* we do not have enough room ?
3070 did the type change?
3071 is it a union? */
3072 if ((bit_pos + bit_size) > bsize ||
3073 bt != prevbt || a == TOK_UNION)
3074 bit_pos = 0;
3075 lbit_pos = bit_pos;
3076 /* XXX: handle LSB first */
3077 type1.t |= VT_BITFIELD |
3078 (bit_pos << VT_STRUCT_SHIFT) |
3079 (bit_size << (VT_STRUCT_SHIFT + 6));
3080 bit_pos += bit_size;
3082 prevbt = bt;
3083 } else {
3084 bit_pos = 0;
3086 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
3087 /* add new memory data only if starting
3088 bit field */
3089 if (lbit_pos == 0) {
3090 if (a == TOK_STRUCT) {
3091 c = (c + align - 1) & -align;
3092 offset = c;
3093 if (size > 0)
3094 c += size;
3095 } else {
3096 offset = 0;
3097 if (size > c)
3098 c = size;
3100 if (align > maxalign)
3101 maxalign = align;
3103 #if 0
3104 printf("add field %s offset=%d",
3105 get_tok_str(v, NULL), offset);
3106 if (type1.t & VT_BITFIELD) {
3107 printf(" pos=%d size=%d",
3108 (type1.t >> VT_STRUCT_SHIFT) & 0x3f,
3109 (type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
3111 printf("\n");
3112 #endif
3114 if (v == 0 && (type1.t & VT_BTYPE) == VT_STRUCT) {
3115 ass = type1.ref;
3116 while ((ass = ass->next) != NULL) {
3117 ss = sym_push(ass->v, &ass->type, 0, offset + ass->c);
3118 *ps = ss;
3119 ps = &ss->next;
3121 } else if (v) {
3122 ss = sym_push(v | SYM_FIELD, &type1, 0, offset);
3123 *ps = ss;
3124 ps = &ss->next;
3126 if (tok == ';' || tok == TOK_EOF)
3127 break;
3128 skip(',');
3130 skip(';');
3132 skip('}');
3133 /* store size and alignment */
3134 s->c = (c + maxalign - 1) & -maxalign;
3135 s->r = maxalign;
3140 /* return 1 if basic type is a type size (short, long, long long) */
3141 ST_FUNC int is_btype_size(int bt)
3143 return bt == VT_SHORT || bt == VT_LONG || bt == VT_LLONG;
3146 /* Add type qualifiers to a type. If the type is an array then the qualifiers
3147 are added to the element type, copied because it could be a typedef. */
3148 static void parse_btype_qualify(CType *type, int qualifiers)
3150 while (type->t & VT_ARRAY) {
3151 type->ref = sym_push(SYM_FIELD, &type->ref->type, 0, type->ref->c);
3152 type = &type->ref->type;
3154 type->t |= qualifiers;
3157 /* return 0 if no type declaration. otherwise, return the basic type
3158 and skip it.
3160 static int parse_btype(CType *type, AttributeDef *ad)
3162 int t, u, bt_size, complete, type_found, typespec_found;
3163 Sym *s;
3164 CType type1;
3166 memset(ad, 0, sizeof(AttributeDef));
3167 complete = 0;
3168 type_found = 0;
3169 typespec_found = 0;
3170 t = 0;
3171 while(1) {
3172 switch(tok) {
3173 case TOK_EXTENSION:
3174 /* currently, we really ignore extension */
3175 next();
3176 continue;
3178 /* basic types */
3179 case TOK_CHAR:
3180 u = VT_BYTE;
3181 basic_type:
3182 next();
3183 basic_type1:
3184 if (complete)
3185 tcc_error("too many basic types");
3186 t |= u;
3187 bt_size = is_btype_size (u & VT_BTYPE);
3188 if (u == VT_INT || (!bt_size && !(t & VT_TYPEDEF)))
3189 complete = 1;
3190 typespec_found = 1;
3191 break;
3192 case TOK_VOID:
3193 u = VT_VOID;
3194 goto basic_type;
3195 case TOK_SHORT:
3196 u = VT_SHORT;
3197 goto basic_type;
3198 case TOK_INT:
3199 u = VT_INT;
3200 goto basic_type;
3201 case TOK_LONG:
3202 next();
3203 if ((t & VT_BTYPE) == VT_DOUBLE) {
3204 #ifndef TCC_TARGET_PE
3205 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3206 #endif
3207 } else if ((t & VT_BTYPE) == VT_LONG) {
3208 t = (t & ~VT_BTYPE) | VT_LLONG;
3209 } else {
3210 u = VT_LONG;
3211 goto basic_type1;
3213 break;
3214 #ifdef TCC_TARGET_ARM64
3215 case TOK_UINT128:
3216 /* GCC's __uint128_t appears in some Linux header files. Make it a
3217 synonym for long double to get the size and alignment right. */
3218 u = VT_LDOUBLE;
3219 goto basic_type;
3220 #endif
3221 case TOK_BOOL:
3222 u = VT_BOOL;
3223 goto basic_type;
3224 case TOK_FLOAT:
3225 u = VT_FLOAT;
3226 goto basic_type;
3227 case TOK_DOUBLE:
3228 next();
3229 if ((t & VT_BTYPE) == VT_LONG) {
3230 #ifdef TCC_TARGET_PE
3231 t = (t & ~VT_BTYPE) | VT_DOUBLE;
3232 #else
3233 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3234 #endif
3235 } else {
3236 u = VT_DOUBLE;
3237 goto basic_type1;
3239 break;
3240 case TOK_ENUM:
3241 struct_decl(&type1, ad, VT_ENUM);
3242 basic_type2:
3243 u = type1.t;
3244 type->ref = type1.ref;
3245 goto basic_type1;
3246 case TOK_STRUCT:
3247 case TOK_UNION:
3248 struct_decl(&type1, ad, VT_STRUCT);
3249 goto basic_type2;
3251 /* type modifiers */
3252 case TOK_CONST1:
3253 case TOK_CONST2:
3254 case TOK_CONST3:
3255 type->t = t;
3256 parse_btype_qualify(type, VT_CONSTANT);
3257 t = type->t;
3258 next();
3259 break;
3260 case TOK_VOLATILE1:
3261 case TOK_VOLATILE2:
3262 case TOK_VOLATILE3:
3263 type->t = t;
3264 parse_btype_qualify(type, VT_VOLATILE);
3265 t = type->t;
3266 next();
3267 break;
3268 case TOK_SIGNED1:
3269 case TOK_SIGNED2:
3270 case TOK_SIGNED3:
3271 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == (VT_DEFSIGN|VT_UNSIGNED))
3272 tcc_error("signed and unsigned modifier");
3273 typespec_found = 1;
3274 t |= VT_DEFSIGN;
3275 next();
3276 break;
3277 case TOK_REGISTER:
3278 case TOK_AUTO:
3279 case TOK_RESTRICT1:
3280 case TOK_RESTRICT2:
3281 case TOK_RESTRICT3:
3282 next();
3283 break;
3284 case TOK_UNSIGNED:
3285 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == VT_DEFSIGN)
3286 tcc_error("signed and unsigned modifier");
3287 t |= VT_DEFSIGN | VT_UNSIGNED;
3288 next();
3289 typespec_found = 1;
3290 break;
3292 /* storage */
3293 case TOK_EXTERN:
3294 t |= VT_EXTERN;
3295 next();
3296 break;
3297 case TOK_STATIC:
3298 t |= VT_STATIC;
3299 next();
3300 break;
3301 case TOK_TYPEDEF:
3302 t |= VT_TYPEDEF;
3303 next();
3304 break;
3305 case TOK_INLINE1:
3306 case TOK_INLINE2:
3307 case TOK_INLINE3:
3308 t |= VT_INLINE;
3309 next();
3310 break;
3312 /* GNUC attribute */
3313 case TOK_ATTRIBUTE1:
3314 case TOK_ATTRIBUTE2:
3315 parse_attribute(ad);
3316 if (ad->a.mode) {
3317 u = ad->a.mode -1;
3318 t = (t & ~VT_BTYPE) | u;
3320 break;
3321 /* GNUC typeof */
3322 case TOK_TYPEOF1:
3323 case TOK_TYPEOF2:
3324 case TOK_TYPEOF3:
3325 next();
3326 parse_expr_type(&type1);
3327 /* remove all storage modifiers except typedef */
3328 type1.t &= ~(VT_STORAGE&~VT_TYPEDEF);
3329 goto basic_type2;
3330 default:
3331 if (typespec_found)
3332 goto the_end;
3333 s = sym_find(tok);
3334 if (!s || !(s->type.t & VT_TYPEDEF))
3335 goto the_end;
3337 type->t = ((s->type.t & ~VT_TYPEDEF) |
3338 (t & ~(VT_CONSTANT | VT_VOLATILE)));
3339 type->ref = s->type.ref;
3340 if (t & (VT_CONSTANT | VT_VOLATILE))
3341 parse_btype_qualify(type, t & (VT_CONSTANT | VT_VOLATILE));
3342 t = type->t;
3344 if (s->r) {
3345 /* get attributes from typedef */
3346 if (0 == ad->a.aligned)
3347 ad->a.aligned = s->a.aligned;
3348 if (0 == ad->a.func_call)
3349 ad->a.func_call = s->a.func_call;
3350 ad->a.packed |= s->a.packed;
3352 next();
3353 typespec_found = 1;
3354 break;
3356 type_found = 1;
3358 the_end:
3359 if (tcc_state->char_is_unsigned) {
3360 if ((t & (VT_DEFSIGN|VT_BTYPE)) == VT_BYTE)
3361 t |= VT_UNSIGNED;
3364 /* long is never used as type */
3365 if ((t & VT_BTYPE) == VT_LONG)
3366 #if (!defined TCC_TARGET_X86_64 && !defined TCC_TARGET_ARM64) || \
3367 defined TCC_TARGET_PE
3368 t = (t & ~VT_BTYPE) | VT_INT;
3369 #else
3370 t = (t & ~VT_BTYPE) | VT_LLONG;
3371 #endif
3372 type->t = t;
3373 return type_found;
3376 /* convert a function parameter type (array to pointer and function to
3377 function pointer) */
3378 static inline void convert_parameter_type(CType *pt)
3380 /* remove const and volatile qualifiers (XXX: const could be used
3381 to indicate a const function parameter */
3382 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
3383 /* array must be transformed to pointer according to ANSI C */
3384 pt->t &= ~VT_ARRAY;
3385 if ((pt->t & VT_BTYPE) == VT_FUNC) {
3386 mk_pointer(pt);
3390 ST_FUNC void parse_asm_str(CString *astr)
3392 skip('(');
3393 /* read the string */
3394 if (tok != TOK_STR)
3395 expect("string constant");
3396 cstr_new(astr);
3397 while (tok == TOK_STR) {
3398 /* XXX: add \0 handling too ? */
3399 cstr_cat(astr, tokc.str.data, -1);
3400 next();
3402 cstr_ccat(astr, '\0');
3405 /* Parse an asm label and return the token */
3406 static int asm_label_instr(void)
3408 int v;
3409 CString astr;
3411 next();
3412 parse_asm_str(&astr);
3413 skip(')');
3414 #ifdef ASM_DEBUG
3415 printf("asm_alias: \"%s\"\n", (char *)astr.data);
3416 #endif
3417 v = tok_alloc(astr.data, astr.size - 1)->tok;
3418 cstr_free(&astr);
3419 return v;
3422 static void post_type(CType *type, AttributeDef *ad)
3424 int n, l, t1, arg_size, align;
3425 Sym **plast, *s, *first;
3426 AttributeDef ad1;
3427 CType pt;
3429 if (tok == '(') {
3430 /* function declaration */
3431 next();
3432 l = 0;
3433 first = NULL;
3434 plast = &first;
3435 arg_size = 0;
3436 if (tok != ')') {
3437 int ls = local_scope;
3438 local_scope = 1; /* for struct decl inside function params */
3439 for(;;) {
3440 /* read param name and compute offset */
3441 if (l != FUNC_OLD) {
3442 if (!parse_btype(&pt, &ad1)) {
3443 if (l) {
3444 tcc_error("invalid type");
3445 } else {
3446 l = FUNC_OLD;
3447 goto old_proto;
3450 l = FUNC_NEW;
3451 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
3452 break;
3453 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
3454 if ((pt.t & VT_BTYPE) == VT_VOID)
3455 tcc_error("parameter declared as void");
3456 arg_size += (type_size(&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
3457 } else {
3458 old_proto:
3459 n = tok;
3460 if (n < TOK_UIDENT)
3461 expect("identifier");
3462 pt.t = VT_INT;
3463 next();
3465 convert_parameter_type(&pt);
3466 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
3467 *plast = s;
3468 plast = &s->next;
3469 if (tok == ')')
3470 break;
3471 skip(',');
3472 if (l == FUNC_NEW && tok == TOK_DOTS) {
3473 l = FUNC_ELLIPSIS;
3474 next();
3475 break;
3478 local_scope = ls;
3480 /* if no parameters, then old type prototype */
3481 if (l == 0)
3482 l = FUNC_OLD;
3483 skip(')');
3484 /* NOTE: const is ignored in returned type as it has a special
3485 meaning in gcc / C++ */
3486 type->t &= ~VT_CONSTANT;
3487 /* some ancient pre-K&R C allows a function to return an array
3488 and the array brackets to be put after the arguments, such
3489 that "int c()[]" means something like "int[] c()" */
3490 if (tok == '[') {
3491 next();
3492 skip(']'); /* only handle simple "[]" */
3493 type->t |= VT_PTR;
3495 /* we push a anonymous symbol which will contain the function prototype */
3496 ad->a.func_args = arg_size;
3497 s = sym_push(SYM_FIELD, type, 0, l);
3498 s->a = ad->a;
3499 s->next = first;
3500 type->t = VT_FUNC;
3501 type->ref = s;
3502 } else if (tok == '[') {
3503 /* array definition */
3504 next();
3505 if (tok == TOK_RESTRICT1)
3506 next();
3507 n = -1;
3508 t1 = 0;
3509 if (tok != ']') {
3510 if (!local_stack || nocode_wanted)
3511 vpushi(expr_const());
3512 else gexpr();
3513 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3514 n = vtop->c.i;
3515 if (n < 0)
3516 tcc_error("invalid array size");
3517 } else {
3518 if (!is_integer_btype(vtop->type.t & VT_BTYPE))
3519 tcc_error("size of variable length array should be an integer");
3520 t1 = VT_VLA;
3523 skip(']');
3524 /* parse next post type */
3525 post_type(type, ad);
3526 if (type->t == VT_FUNC)
3527 tcc_error("declaration of an array of functions");
3528 t1 |= type->t & VT_VLA;
3530 if (t1 & VT_VLA) {
3531 loc -= type_size(&int_type, &align);
3532 loc &= -align;
3533 n = loc;
3535 vla_runtime_type_size(type, &align);
3536 gen_op('*');
3537 vset(&int_type, VT_LOCAL|VT_LVAL, n);
3538 vswap();
3539 vstore();
3541 if (n != -1)
3542 vpop();
3544 /* we push an anonymous symbol which will contain the array
3545 element type */
3546 s = sym_push(SYM_FIELD, type, 0, n);
3547 type->t = (t1 ? VT_VLA : VT_ARRAY) | VT_PTR;
3548 type->ref = s;
3552 /* Parse a type declaration (except basic type), and return the type
3553 in 'type'. 'td' is a bitmask indicating which kind of type decl is
3554 expected. 'type' should contain the basic type. 'ad' is the
3555 attribute definition of the basic type. It can be modified by
3556 type_decl().
3558 static void type_decl(CType *type, AttributeDef *ad, int *v, int td)
3560 Sym *s;
3561 CType type1, *type2;
3562 int qualifiers, storage;
3564 while (tok == '*') {
3565 qualifiers = 0;
3566 redo:
3567 next();
3568 switch(tok) {
3569 case TOK_CONST1:
3570 case TOK_CONST2:
3571 case TOK_CONST3:
3572 qualifiers |= VT_CONSTANT;
3573 goto redo;
3574 case TOK_VOLATILE1:
3575 case TOK_VOLATILE2:
3576 case TOK_VOLATILE3:
3577 qualifiers |= VT_VOLATILE;
3578 goto redo;
3579 case TOK_RESTRICT1:
3580 case TOK_RESTRICT2:
3581 case TOK_RESTRICT3:
3582 goto redo;
3584 mk_pointer(type);
3585 type->t |= qualifiers;
3588 /* XXX: clarify attribute handling */
3589 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3590 parse_attribute(ad);
3592 /* recursive type */
3593 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
3594 type1.t = 0; /* XXX: same as int */
3595 if (tok == '(') {
3596 next();
3597 /* XXX: this is not correct to modify 'ad' at this point, but
3598 the syntax is not clear */
3599 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3600 parse_attribute(ad);
3601 type_decl(&type1, ad, v, td);
3602 skip(')');
3603 } else {
3604 /* type identifier */
3605 if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
3606 *v = tok;
3607 next();
3608 } else {
3609 if (!(td & TYPE_ABSTRACT))
3610 expect("identifier");
3611 *v = 0;
3614 storage = type->t & VT_STORAGE;
3615 type->t &= ~VT_STORAGE;
3616 if (storage & VT_STATIC) {
3617 int saved_nocode_wanted = nocode_wanted;
3618 nocode_wanted = 1;
3619 post_type(type, ad);
3620 nocode_wanted = saved_nocode_wanted;
3621 } else
3622 post_type(type, ad);
3623 type->t |= storage;
3624 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3625 parse_attribute(ad);
3627 if (!type1.t)
3628 return;
3629 /* append type at the end of type1 */
3630 type2 = &type1;
3631 for(;;) {
3632 s = type2->ref;
3633 type2 = &s->type;
3634 if (!type2->t) {
3635 *type2 = *type;
3636 break;
3639 *type = type1;
3642 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
3643 ST_FUNC int lvalue_type(int t)
3645 int bt, r;
3646 r = VT_LVAL;
3647 bt = t & VT_BTYPE;
3648 if (bt == VT_BYTE || bt == VT_BOOL)
3649 r |= VT_LVAL_BYTE;
3650 else if (bt == VT_SHORT)
3651 r |= VT_LVAL_SHORT;
3652 else
3653 return r;
3654 if (t & VT_UNSIGNED)
3655 r |= VT_LVAL_UNSIGNED;
3656 return r;
3659 /* indirection with full error checking and bound check */
3660 ST_FUNC void indir(void)
3662 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
3663 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
3664 return;
3665 expect("pointer");
3667 if ((vtop->r & VT_LVAL) && !nocode_wanted)
3668 gv(RC_INT);
3669 vtop->type = *pointed_type(&vtop->type);
3670 /* Arrays and functions are never lvalues */
3671 if (!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_VLA)
3672 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
3673 vtop->r |= lvalue_type(vtop->type.t);
3674 /* if bound checking, the referenced pointer must be checked */
3675 #ifdef CONFIG_TCC_BCHECK
3676 if (tcc_state->do_bounds_check)
3677 vtop->r |= VT_MUSTBOUND;
3678 #endif
3682 /* pass a parameter to a function and do type checking and casting */
3683 static void gfunc_param_typed(Sym *func, Sym *arg)
3685 int func_type;
3686 CType type;
3688 func_type = func->c;
3689 if (func_type == FUNC_OLD ||
3690 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
3691 /* default casting : only need to convert float to double */
3692 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
3693 type.t = VT_DOUBLE;
3694 gen_cast(&type);
3695 } else if (vtop->type.t & VT_BITFIELD) {
3696 type.t = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
3697 gen_cast(&type);
3699 } else if (arg == NULL) {
3700 tcc_error("too many arguments to function");
3701 } else {
3702 type = arg->type;
3703 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
3704 gen_assign_cast(&type);
3708 /* parse an expression of the form '(type)' or '(expr)' and return its
3709 type */
3710 static void parse_expr_type(CType *type)
3712 int n;
3713 AttributeDef ad;
3715 skip('(');
3716 if (parse_btype(type, &ad)) {
3717 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3718 } else {
3719 expr_type(type);
3721 skip(')');
3724 static void parse_type(CType *type)
3726 AttributeDef ad;
3727 int n;
3729 if (!parse_btype(type, &ad)) {
3730 expect("type");
3732 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3735 static void vpush_tokc(int t)
3737 CType type;
3738 type.t = t;
3739 type.ref = 0;
3740 vsetc(&type, VT_CONST, &tokc);
3743 ST_FUNC void unary(void)
3745 int n, t, align, size, r, sizeof_caller;
3746 CType type;
3747 Sym *s;
3748 AttributeDef ad;
3749 static int in_sizeof = 0;
3751 sizeof_caller = in_sizeof;
3752 in_sizeof = 0;
3753 /* XXX: GCC 2.95.3 does not generate a table although it should be
3754 better here */
3755 tok_next:
3756 switch(tok) {
3757 case TOK_EXTENSION:
3758 next();
3759 goto tok_next;
3760 case TOK_CINT:
3761 case TOK_CCHAR:
3762 case TOK_LCHAR:
3763 vpushi(tokc.i);
3764 next();
3765 break;
3766 case TOK_CUINT:
3767 vpush_tokc(VT_INT | VT_UNSIGNED);
3768 next();
3769 break;
3770 case TOK_CLLONG:
3771 vpush_tokc(VT_LLONG);
3772 next();
3773 break;
3774 case TOK_CULLONG:
3775 vpush_tokc(VT_LLONG | VT_UNSIGNED);
3776 next();
3777 break;
3778 case TOK_CFLOAT:
3779 vpush_tokc(VT_FLOAT);
3780 next();
3781 break;
3782 case TOK_CDOUBLE:
3783 vpush_tokc(VT_DOUBLE);
3784 next();
3785 break;
3786 case TOK_CLDOUBLE:
3787 vpush_tokc(VT_LDOUBLE);
3788 next();
3789 break;
3790 case TOK___FUNCTION__:
3791 if (!gnu_ext)
3792 goto tok_identifier;
3793 /* fall thru */
3794 case TOK___FUNC__:
3796 void *ptr;
3797 int len;
3798 /* special function name identifier */
3799 len = strlen(funcname) + 1;
3800 /* generate char[len] type */
3801 type.t = VT_BYTE;
3802 mk_pointer(&type);
3803 type.t |= VT_ARRAY;
3804 type.ref->c = len;
3805 vpush_ref(&type, data_section, data_section->data_offset, len);
3806 ptr = section_ptr_add(data_section, len);
3807 memcpy(ptr, funcname, len);
3808 next();
3810 break;
3811 case TOK_LSTR:
3812 #ifdef TCC_TARGET_PE
3813 t = VT_SHORT | VT_UNSIGNED;
3814 #else
3815 t = VT_INT;
3816 #endif
3817 goto str_init;
3818 case TOK_STR:
3819 /* string parsing */
3820 t = VT_BYTE;
3821 str_init:
3822 if (tcc_state->warn_write_strings)
3823 t |= VT_CONSTANT;
3824 type.t = t;
3825 mk_pointer(&type);
3826 type.t |= VT_ARRAY;
3827 memset(&ad, 0, sizeof(AttributeDef));
3828 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, 0);
3829 break;
3830 case '(':
3831 next();
3832 /* cast ? */
3833 if (parse_btype(&type, &ad)) {
3834 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
3835 skip(')');
3836 /* check ISOC99 compound literal */
3837 if (tok == '{') {
3838 /* data is allocated locally by default */
3839 if (global_expr)
3840 r = VT_CONST;
3841 else
3842 r = VT_LOCAL;
3843 /* all except arrays are lvalues */
3844 if (!(type.t & VT_ARRAY))
3845 r |= lvalue_type(type.t);
3846 memset(&ad, 0, sizeof(AttributeDef));
3847 decl_initializer_alloc(&type, &ad, r, 1, 0, 0);
3848 } else {
3849 if (sizeof_caller) {
3850 vpush(&type);
3851 return;
3853 unary();
3854 gen_cast(&type);
3856 } else if (tok == '{') {
3857 if (const_wanted)
3858 tcc_error("expected constant");
3859 /* save all registers */
3860 if (!nocode_wanted)
3861 save_regs(0);
3862 /* statement expression : we do not accept break/continue
3863 inside as GCC does */
3864 block(NULL, NULL, NULL, NULL, 0, 1);
3865 skip(')');
3866 } else {
3867 gexpr();
3868 skip(')');
3870 break;
3871 case '*':
3872 next();
3873 unary();
3874 indir();
3875 break;
3876 case '&':
3877 next();
3878 unary();
3879 /* functions names must be treated as function pointers,
3880 except for unary '&' and sizeof. Since we consider that
3881 functions are not lvalues, we only have to handle it
3882 there and in function calls. */
3883 /* arrays can also be used although they are not lvalues */
3884 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
3885 !(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
3886 test_lvalue();
3887 mk_pointer(&vtop->type);
3888 gaddrof();
3889 break;
3890 case '!':
3891 next();
3892 unary();
3893 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3894 CType boolean;
3895 boolean.t = VT_BOOL;
3896 gen_cast(&boolean);
3897 vtop->c.i = !vtop->c.i;
3898 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
3899 vtop->c.i ^= 1;
3900 else {
3901 save_regs(1);
3902 vseti(VT_JMP, gvtst(1, 0));
3904 break;
3905 case '~':
3906 next();
3907 unary();
3908 vpushi(-1);
3909 gen_op('^');
3910 break;
3911 case '+':
3912 next();
3913 unary();
3914 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
3915 tcc_error("pointer not accepted for unary plus");
3916 /* In order to force cast, we add zero, except for floating point
3917 where we really need an noop (otherwise -0.0 will be transformed
3918 into +0.0). */
3919 if (!is_float(vtop->type.t)) {
3920 vpushi(0);
3921 gen_op('+');
3923 break;
3924 case TOK_SIZEOF:
3925 case TOK_ALIGNOF1:
3926 case TOK_ALIGNOF2:
3927 t = tok;
3928 next();
3929 in_sizeof++;
3930 unary_type(&type); // Perform a in_sizeof = 0;
3931 size = type_size(&type, &align);
3932 if (t == TOK_SIZEOF) {
3933 if (!(type.t & VT_VLA)) {
3934 if (size < 0)
3935 tcc_error("sizeof applied to an incomplete type");
3936 vpushs(size);
3937 } else {
3938 vla_runtime_type_size(&type, &align);
3940 } else {
3941 vpushs(align);
3943 vtop->type.t |= VT_UNSIGNED;
3944 break;
3946 case TOK_builtin_expect:
3948 /* __builtin_expect is a no-op for now */
3949 int saved_nocode_wanted;
3950 next();
3951 skip('(');
3952 expr_eq();
3953 skip(',');
3954 saved_nocode_wanted = nocode_wanted;
3955 nocode_wanted = 1;
3956 expr_lor_const();
3957 vpop();
3958 nocode_wanted = saved_nocode_wanted;
3959 skip(')');
3961 break;
3962 case TOK_builtin_types_compatible_p:
3964 CType type1, type2;
3965 next();
3966 skip('(');
3967 parse_type(&type1);
3968 skip(',');
3969 parse_type(&type2);
3970 skip(')');
3971 type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
3972 type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
3973 vpushi(is_compatible_types(&type1, &type2));
3975 break;
3976 case TOK_builtin_constant_p:
3978 int saved_nocode_wanted, res;
3979 next();
3980 skip('(');
3981 saved_nocode_wanted = nocode_wanted;
3982 nocode_wanted = 1;
3983 gexpr();
3984 res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
3985 vpop();
3986 nocode_wanted = saved_nocode_wanted;
3987 skip(')');
3988 vpushi(res);
3990 break;
3991 case TOK_builtin_frame_address:
3992 case TOK_builtin_return_address:
3994 int tok1 = tok;
3995 int level;
3996 CType type;
3997 next();
3998 skip('(');
3999 if (tok != TOK_CINT) {
4000 tcc_error("%s only takes positive integers",
4001 tok1 == TOK_builtin_return_address ?
4002 "__builtin_return_address" :
4003 "__builtin_frame_address");
4005 level = (uint32_t)tokc.i;
4006 next();
4007 skip(')');
4008 type.t = VT_VOID;
4009 mk_pointer(&type);
4010 vset(&type, VT_LOCAL, 0); /* local frame */
4011 while (level--) {
4012 mk_pointer(&vtop->type);
4013 indir(); /* -> parent frame */
4015 if (tok1 == TOK_builtin_return_address) {
4016 // assume return address is just above frame pointer on stack
4017 vpushi(PTR_SIZE);
4018 gen_op('+');
4019 mk_pointer(&vtop->type);
4020 indir();
4023 break;
4024 #ifdef TCC_TARGET_X86_64
4025 #ifdef TCC_TARGET_PE
4026 case TOK_builtin_va_start:
4028 next();
4029 skip('(');
4030 expr_eq();
4031 skip(',');
4032 expr_eq();
4033 skip(')');
4034 if ((vtop->r & VT_VALMASK) != VT_LOCAL)
4035 tcc_error("__builtin_va_start expects a local variable");
4036 vtop->r &= ~(VT_LVAL | VT_REF);
4037 vtop->type = char_pointer_type;
4038 vstore();
4040 break;
4041 #else
4042 case TOK_builtin_va_arg_types:
4044 CType type;
4045 next();
4046 skip('(');
4047 parse_type(&type);
4048 skip(')');
4049 vpushi(classify_x86_64_va_arg(&type));
4051 break;
4052 #endif
4053 #endif
4055 #ifdef TCC_TARGET_ARM64
4056 case TOK___va_start: {
4057 if (nocode_wanted)
4058 tcc_error("statement in global scope");
4059 next();
4060 skip('(');
4061 expr_eq();
4062 skip(',');
4063 expr_eq();
4064 skip(')');
4065 //xx check types
4066 gen_va_start();
4067 vpushi(0);
4068 vtop->type.t = VT_VOID;
4069 break;
4071 case TOK___va_arg: {
4072 CType type;
4073 if (nocode_wanted)
4074 tcc_error("statement in global scope");
4075 next();
4076 skip('(');
4077 expr_eq();
4078 skip(',');
4079 parse_type(&type);
4080 skip(')');
4081 //xx check types
4082 gen_va_arg(&type);
4083 vtop->type = type;
4084 break;
4086 case TOK___arm64_clear_cache: {
4087 next();
4088 skip('(');
4089 expr_eq();
4090 skip(',');
4091 expr_eq();
4092 skip(')');
4093 gen_clear_cache();
4094 vpushi(0);
4095 vtop->type.t = VT_VOID;
4096 break;
4098 #endif
4099 /* pre operations */
4100 case TOK_INC:
4101 case TOK_DEC:
4102 t = tok;
4103 next();
4104 unary();
4105 inc(0, t);
4106 break;
4107 case '-':
4108 next();
4109 unary();
4110 t = vtop->type.t & VT_BTYPE;
4111 if (is_float(t)) {
4112 /* In IEEE negate(x) isn't subtract(0,x), but rather
4113 subtract(-0, x). */
4114 vpush(&vtop->type);
4115 if (t == VT_FLOAT)
4116 vtop->c.f = -0.0f;
4117 else if (t == VT_DOUBLE)
4118 vtop->c.d = -0.0;
4119 else
4120 vtop->c.ld = -0.0;
4121 } else
4122 vpushi(0);
4123 vswap();
4124 gen_op('-');
4125 break;
4126 case TOK_LAND:
4127 if (!gnu_ext)
4128 goto tok_identifier;
4129 next();
4130 /* allow to take the address of a label */
4131 if (tok < TOK_UIDENT)
4132 expect("label identifier");
4133 s = label_find(tok);
4134 if (!s) {
4135 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
4136 } else {
4137 if (s->r == LABEL_DECLARED)
4138 s->r = LABEL_FORWARD;
4140 if (!s->type.t) {
4141 s->type.t = VT_VOID;
4142 mk_pointer(&s->type);
4143 s->type.t |= VT_STATIC;
4145 vpushsym(&s->type, s);
4146 next();
4147 break;
4149 // special qnan , snan and infinity values
4150 case TOK___NAN__:
4151 vpush64(VT_DOUBLE, 0x7ff8000000000000ULL);
4152 next();
4153 break;
4154 case TOK___SNAN__:
4155 vpush64(VT_DOUBLE, 0x7ff0000000000001ULL);
4156 next();
4157 break;
4158 case TOK___INF__:
4159 vpush64(VT_DOUBLE, 0x7ff0000000000000ULL);
4160 next();
4161 break;
4163 default:
4164 tok_identifier:
4165 t = tok;
4166 next();
4167 if (t < TOK_UIDENT)
4168 expect("identifier");
4169 s = sym_find(t);
4170 if (!s) {
4171 const char *name = get_tok_str(t, NULL);
4172 if (tok != '(')
4173 tcc_error("'%s' undeclared", name);
4174 /* for simple function calls, we tolerate undeclared
4175 external reference to int() function */
4176 if (tcc_state->warn_implicit_function_declaration
4177 #ifdef TCC_TARGET_PE
4178 /* people must be warned about using undeclared WINAPI functions
4179 (which usually start with uppercase letter) */
4180 || (name[0] >= 'A' && name[0] <= 'Z')
4181 #endif
4183 tcc_warning("implicit declaration of function '%s'", name);
4184 s = external_global_sym(t, &func_old_type, 0);
4186 if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
4187 (VT_STATIC | VT_INLINE | VT_FUNC)) {
4188 /* if referencing an inline function, then we generate a
4189 symbol to it if not already done. It will have the
4190 effect to generate code for it at the end of the
4191 compilation unit. Inline function as always
4192 generated in the text section. */
4193 if (!s->c)
4194 put_extern_sym(s, text_section, 0, 0);
4195 r = VT_SYM | VT_CONST;
4196 } else {
4197 r = s->r;
4199 vset(&s->type, r, s->c);
4200 /* if forward reference, we must point to s */
4201 if (vtop->r & VT_SYM) {
4202 vtop->sym = s;
4203 vtop->c.i = 0;
4205 break;
4208 /* post operations */
4209 while (1) {
4210 if (tok == TOK_INC || tok == TOK_DEC) {
4211 inc(1, tok);
4212 next();
4213 } else if (tok == '.' || tok == TOK_ARROW || tok == TOK_CDOUBLE) {
4214 int qualifiers;
4215 /* field */
4216 if (tok == TOK_ARROW)
4217 indir();
4218 qualifiers = vtop->type.t & (VT_CONSTANT | VT_VOLATILE);
4219 test_lvalue();
4220 gaddrof();
4221 /* expect pointer on structure */
4222 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
4223 expect("struct or union");
4224 if (tok == TOK_CDOUBLE)
4225 expect("field name");
4226 next();
4227 if (tok == TOK_CINT || tok == TOK_CUINT)
4228 expect("field name");
4229 s = vtop->type.ref;
4230 /* find field */
4231 tok |= SYM_FIELD;
4232 while ((s = s->next) != NULL) {
4233 if (s->v == tok)
4234 break;
4236 if (!s)
4237 tcc_error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, &tokc));
4238 /* add field offset to pointer */
4239 vtop->type = char_pointer_type; /* change type to 'char *' */
4240 vpushi(s->c);
4241 gen_op('+');
4242 /* change type to field type, and set to lvalue */
4243 vtop->type = s->type;
4244 vtop->type.t |= qualifiers;
4245 /* an array is never an lvalue */
4246 if (!(vtop->type.t & VT_ARRAY)) {
4247 vtop->r |= lvalue_type(vtop->type.t);
4248 #ifdef CONFIG_TCC_BCHECK
4249 /* if bound checking, the referenced pointer must be checked */
4250 if (tcc_state->do_bounds_check)
4251 vtop->r |= VT_MUSTBOUND;
4252 #endif
4254 next();
4255 } else if (tok == '[') {
4256 next();
4257 gexpr();
4258 gen_op('+');
4259 indir();
4260 skip(']');
4261 } else if (tok == '(') {
4262 SValue ret;
4263 Sym *sa;
4264 int nb_args, ret_nregs, ret_align, regsize, variadic;
4266 /* function call */
4267 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
4268 /* pointer test (no array accepted) */
4269 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
4270 vtop->type = *pointed_type(&vtop->type);
4271 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
4272 goto error_func;
4273 } else {
4274 error_func:
4275 expect("function pointer");
4277 } else {
4278 vtop->r &= ~VT_LVAL; /* no lvalue */
4280 /* get return type */
4281 s = vtop->type.ref;
4282 next();
4283 sa = s->next; /* first parameter */
4284 nb_args = 0;
4285 ret.r2 = VT_CONST;
4286 /* compute first implicit argument if a structure is returned */
4287 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
4288 variadic = (s->c == FUNC_ELLIPSIS);
4289 ret_nregs = gfunc_sret(&s->type, variadic, &ret.type,
4290 &ret_align, &regsize);
4291 if (!ret_nregs) {
4292 /* get some space for the returned structure */
4293 size = type_size(&s->type, &align);
4294 #ifdef TCC_TARGET_ARM64
4295 /* On arm64, a small struct is return in registers.
4296 It is much easier to write it to memory if we know
4297 that we are allowed to write some extra bytes, so
4298 round the allocated space up to a power of 2: */
4299 if (size < 16)
4300 while (size & (size - 1))
4301 size = (size | (size - 1)) + 1;
4302 #endif
4303 loc = (loc - size) & -align;
4304 ret.type = s->type;
4305 ret.r = VT_LOCAL | VT_LVAL;
4306 /* pass it as 'int' to avoid structure arg passing
4307 problems */
4308 vseti(VT_LOCAL, loc);
4309 ret.c = vtop->c;
4310 nb_args++;
4312 } else {
4313 ret_nregs = 1;
4314 ret.type = s->type;
4317 if (ret_nregs) {
4318 /* return in register */
4319 if (is_float(ret.type.t)) {
4320 ret.r = reg_fret(ret.type.t);
4321 #ifdef TCC_TARGET_X86_64
4322 if ((ret.type.t & VT_BTYPE) == VT_QFLOAT)
4323 ret.r2 = REG_QRET;
4324 #endif
4325 } else {
4326 #ifndef TCC_TARGET_ARM64
4327 #ifdef TCC_TARGET_X86_64
4328 if ((ret.type.t & VT_BTYPE) == VT_QLONG)
4329 #else
4330 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
4331 #endif
4332 ret.r2 = REG_LRET;
4333 #endif
4334 ret.r = REG_IRET;
4336 ret.c.i = 0;
4338 if (tok != ')') {
4339 for(;;) {
4340 expr_eq();
4341 gfunc_param_typed(s, sa);
4342 nb_args++;
4343 if (sa)
4344 sa = sa->next;
4345 if (tok == ')')
4346 break;
4347 skip(',');
4350 if (sa)
4351 tcc_error("too few arguments to function");
4352 skip(')');
4353 if (!nocode_wanted) {
4354 gfunc_call(nb_args);
4355 } else {
4356 vtop -= (nb_args + 1);
4359 /* return value */
4360 for (r = ret.r + ret_nregs + !ret_nregs; r-- > ret.r;) {
4361 vsetc(&ret.type, r, &ret.c);
4362 vtop->r2 = ret.r2; /* Loop only happens when r2 is VT_CONST */
4365 /* handle packed struct return */
4366 if (((s->type.t & VT_BTYPE) == VT_STRUCT) && ret_nregs) {
4367 int addr, offset;
4369 size = type_size(&s->type, &align);
4370 /* We're writing whole regs often, make sure there's enough
4371 space. Assume register size is power of 2. */
4372 if (regsize > align)
4373 align = regsize;
4374 loc = (loc - size) & -align;
4375 addr = loc;
4376 offset = 0;
4377 for (;;) {
4378 vset(&ret.type, VT_LOCAL | VT_LVAL, addr + offset);
4379 vswap();
4380 vstore();
4381 vtop--;
4382 if (--ret_nregs == 0)
4383 break;
4384 offset += regsize;
4386 vset(&s->type, VT_LOCAL | VT_LVAL, addr);
4388 } else {
4389 break;
4394 ST_FUNC void expr_prod(void)
4396 int t;
4398 unary();
4399 while (tok == '*' || tok == '/' || tok == '%') {
4400 t = tok;
4401 next();
4402 unary();
4403 gen_op(t);
4407 ST_FUNC void expr_sum(void)
4409 int t;
4411 expr_prod();
4412 while (tok == '+' || tok == '-') {
4413 t = tok;
4414 next();
4415 expr_prod();
4416 gen_op(t);
4420 static void expr_shift(void)
4422 int t;
4424 expr_sum();
4425 while (tok == TOK_SHL || tok == TOK_SAR) {
4426 t = tok;
4427 next();
4428 expr_sum();
4429 gen_op(t);
4433 static void expr_cmp(void)
4435 int t;
4437 expr_shift();
4438 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
4439 tok == TOK_ULT || tok == TOK_UGE) {
4440 t = tok;
4441 next();
4442 expr_shift();
4443 gen_op(t);
4447 static void expr_cmpeq(void)
4449 int t;
4451 expr_cmp();
4452 while (tok == TOK_EQ || tok == TOK_NE) {
4453 t = tok;
4454 next();
4455 expr_cmp();
4456 gen_op(t);
4460 static void expr_and(void)
4462 expr_cmpeq();
4463 while (tok == '&') {
4464 next();
4465 expr_cmpeq();
4466 gen_op('&');
4470 static void expr_xor(void)
4472 expr_and();
4473 while (tok == '^') {
4474 next();
4475 expr_and();
4476 gen_op('^');
4480 static void expr_or(void)
4482 expr_xor();
4483 while (tok == '|') {
4484 next();
4485 expr_xor();
4486 gen_op('|');
4490 /* XXX: fix this mess */
4491 static void expr_land_const(void)
4493 expr_or();
4494 while (tok == TOK_LAND) {
4495 next();
4496 expr_or();
4497 gen_op(TOK_LAND);
4500 static void expr_lor_const(void)
4502 expr_land_const();
4503 while (tok == TOK_LOR) {
4504 next();
4505 expr_land_const();
4506 gen_op(TOK_LOR);
4510 static void expr_land(void)
4512 expr_or();
4513 if (tok == TOK_LAND) {
4514 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4515 CType ctb, cti;
4516 ctb.t = VT_BOOL;
4517 cti.t = VT_INT;
4518 next();
4519 gen_cast(&ctb);
4520 if (vtop->c.i) {
4521 vpop();
4522 expr_land();
4523 gen_cast(&ctb);
4524 } else {
4525 int saved_nocode_wanted = nocode_wanted;
4526 nocode_wanted = 1;
4527 expr_land();
4528 vpop();
4529 nocode_wanted = saved_nocode_wanted;
4531 gen_cast(&cti);
4532 } else {
4533 int t = 0;
4534 save_regs(1);
4535 for(;;) {
4536 t = gvtst(1, t);
4537 if (tok != TOK_LAND) {
4538 vseti(VT_JMPI, t);
4539 break;
4541 next();
4542 expr_or();
4548 static void expr_lor(void)
4550 expr_land();
4551 if (tok == TOK_LOR) {
4552 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4553 CType ctb, cti;
4554 ctb.t = VT_BOOL;
4555 cti.t = VT_INT;
4556 next();
4557 gen_cast(&ctb);
4558 if (vtop->c.i) {
4559 int saved_nocode_wanted = nocode_wanted;
4560 nocode_wanted = 1;
4561 expr_lor();
4562 vpop();
4563 nocode_wanted = saved_nocode_wanted;
4564 } else {
4565 vpop();
4566 expr_lor();
4567 gen_cast(&ctb);
4569 gen_cast(&cti);
4570 } else {
4571 int t = 0;
4572 save_regs(1);
4573 for(;;) {
4574 t = gvtst(0, t);
4575 if (tok != TOK_LOR) {
4576 vseti(VT_JMP, t);
4577 break;
4579 next();
4580 expr_land();
4586 static void expr_cond(void)
4588 int tt, u, r1, r2, rc, t1, t2, bt1, bt2, islv;
4589 SValue sv;
4590 CType type, type1, type2;
4592 expr_lor();
4593 if (tok == '?') {
4594 next();
4595 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4596 int saved_nocode_wanted = nocode_wanted;
4597 CType boolean;
4598 int c;
4599 boolean.t = VT_BOOL;
4600 vdup();
4601 gen_cast(&boolean);
4602 c = vtop->c.i;
4603 vpop();
4604 if (c) {
4605 if (tok != ':' || !gnu_ext) {
4606 vpop();
4607 gexpr();
4609 skip(':');
4610 nocode_wanted = 1;
4611 expr_cond();
4612 vpop();
4613 nocode_wanted = saved_nocode_wanted;
4614 } else {
4615 vpop();
4616 if (tok != ':' || !gnu_ext) {
4617 nocode_wanted = 1;
4618 gexpr();
4619 vpop();
4620 nocode_wanted = saved_nocode_wanted;
4622 skip(':');
4623 expr_cond();
4626 else {
4627 if (vtop != vstack) {
4628 /* needed to avoid having different registers saved in
4629 each branch */
4630 if (is_float(vtop->type.t)) {
4631 rc = RC_FLOAT;
4632 #ifdef TCC_TARGET_X86_64
4633 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
4634 rc = RC_ST0;
4636 #endif
4638 else
4639 rc = RC_INT;
4640 gv(rc);
4641 save_regs(1);
4643 if (tok == ':' && gnu_ext) {
4644 gv_dup();
4645 tt = gvtst(1, 0);
4646 } else {
4647 tt = gvtst(1, 0);
4648 gexpr();
4650 type1 = vtop->type;
4651 sv = *vtop; /* save value to handle it later */
4652 vtop--; /* no vpop so that FP stack is not flushed */
4653 skip(':');
4654 u = gjmp(0);
4655 gsym(tt);
4656 expr_cond();
4657 type2 = vtop->type;
4659 t1 = type1.t;
4660 bt1 = t1 & VT_BTYPE;
4661 t2 = type2.t;
4662 bt2 = t2 & VT_BTYPE;
4663 /* cast operands to correct type according to ISOC rules */
4664 if (is_float(bt1) || is_float(bt2)) {
4665 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
4666 type.t = VT_LDOUBLE;
4667 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
4668 type.t = VT_DOUBLE;
4669 } else {
4670 type.t = VT_FLOAT;
4672 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
4673 /* cast to biggest op */
4674 type.t = VT_LLONG;
4675 /* convert to unsigned if it does not fit in a long long */
4676 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
4677 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
4678 type.t |= VT_UNSIGNED;
4679 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
4680 /* If one is a null ptr constant the result type
4681 is the other. */
4682 if (is_null_pointer (vtop))
4683 type = type1;
4684 else if (is_null_pointer (&sv))
4685 type = type2;
4686 /* XXX: test pointer compatibility, C99 has more elaborate
4687 rules here. */
4688 else
4689 type = type1;
4690 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
4691 /* XXX: test function pointer compatibility */
4692 type = bt1 == VT_FUNC ? type1 : type2;
4693 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
4694 /* XXX: test structure compatibility */
4695 type = bt1 == VT_STRUCT ? type1 : type2;
4696 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
4697 /* NOTE: as an extension, we accept void on only one side */
4698 type.t = VT_VOID;
4699 } else {
4700 /* integer operations */
4701 type.t = VT_INT;
4702 /* convert to unsigned if it does not fit in an integer */
4703 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
4704 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
4705 type.t |= VT_UNSIGNED;
4707 /* keep structs lvalue by transforming `(expr ? a : b)` to `*(expr ? &a : &b)` so
4708 that `(expr ? a : b).mem` does not error with "lvalue expected" */
4709 islv = (vtop->r & VT_LVAL) && (sv.r & VT_LVAL) && VT_STRUCT == (type.t & VT_BTYPE);
4711 /* now we convert second operand */
4712 gen_cast(&type);
4713 if (islv) {
4714 mk_pointer(&vtop->type);
4715 gaddrof();
4717 else if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4718 gaddrof();
4719 rc = RC_INT;
4720 if (is_float(type.t)) {
4721 rc = RC_FLOAT;
4722 #ifdef TCC_TARGET_X86_64
4723 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
4724 rc = RC_ST0;
4726 #endif
4727 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
4728 /* for long longs, we use fixed registers to avoid having
4729 to handle a complicated move */
4730 rc = RC_IRET;
4733 r2 = gv(rc);
4734 /* this is horrible, but we must also convert first
4735 operand */
4736 tt = gjmp(0);
4737 gsym(u);
4738 /* put again first value and cast it */
4739 *vtop = sv;
4740 gen_cast(&type);
4741 if (islv) {
4742 mk_pointer(&vtop->type);
4743 gaddrof();
4745 else if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4746 gaddrof();
4747 r1 = gv(rc);
4748 move_reg(r2, r1, type.t);
4749 vtop->r = r2;
4750 gsym(tt);
4751 if (islv)
4752 indir();
4757 static void expr_eq(void)
4759 int t;
4761 expr_cond();
4762 if (tok == '=' ||
4763 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
4764 tok == TOK_A_XOR || tok == TOK_A_OR ||
4765 tok == TOK_A_SHL || tok == TOK_A_SAR) {
4766 test_lvalue();
4767 t = tok;
4768 next();
4769 if (t == '=') {
4770 expr_eq();
4771 } else {
4772 vdup();
4773 expr_eq();
4774 gen_op(t & 0x7f);
4776 vstore();
4780 ST_FUNC void gexpr(void)
4782 while (1) {
4783 expr_eq();
4784 if (tok != ',')
4785 break;
4786 vpop();
4787 next();
4791 /* parse an expression and return its type without any side effect. */
4792 static void expr_type(CType *type)
4794 int saved_nocode_wanted;
4796 saved_nocode_wanted = nocode_wanted;
4797 nocode_wanted = 1;
4798 gexpr();
4799 *type = vtop->type;
4800 vpop();
4801 nocode_wanted = saved_nocode_wanted;
4804 /* parse a unary expression and return its type without any side
4805 effect. */
4806 static void unary_type(CType *type)
4808 int a;
4810 a = nocode_wanted;
4811 nocode_wanted = 1;
4812 unary();
4813 *type = vtop->type;
4814 vpop();
4815 nocode_wanted = a;
4818 /* parse a constant expression and return value in vtop. */
4819 static void expr_const1(void)
4821 int a;
4822 a = const_wanted;
4823 const_wanted = 1;
4824 expr_cond();
4825 const_wanted = a;
4828 /* parse an integer constant and return its value. */
4829 ST_FUNC int expr_const(void)
4831 int c;
4832 expr_const1();
4833 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
4834 expect("constant expression");
4835 c = vtop->c.i;
4836 vpop();
4837 return c;
4840 /* return the label token if current token is a label, otherwise
4841 return zero */
4842 static int is_label(void)
4844 int last_tok;
4846 /* fast test first */
4847 if (tok < TOK_UIDENT)
4848 return 0;
4849 /* no need to save tokc because tok is an identifier */
4850 last_tok = tok;
4851 next();
4852 if (tok == ':') {
4853 next();
4854 return last_tok;
4855 } else {
4856 unget_tok(last_tok);
4857 return 0;
4861 static void label_or_decl(int l)
4863 int last_tok;
4865 /* fast test first */
4866 if (tok >= TOK_UIDENT)
4868 /* no need to save tokc because tok is an identifier */
4869 last_tok = tok;
4870 next();
4871 if (tok == ':') {
4872 unget_tok(last_tok);
4873 return;
4875 unget_tok(last_tok);
4877 decl(l);
4880 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
4881 int case_reg, int is_expr)
4883 int a, b, c, d;
4884 Sym *s;
4886 /* generate line number info */
4887 if (tcc_state->do_debug &&
4888 (last_line_num != file->line_num || last_ind != ind)) {
4889 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
4890 last_ind = ind;
4891 last_line_num = file->line_num;
4894 if (is_expr) {
4895 /* default return value is (void) */
4896 vpushi(0);
4897 vtop->type.t = VT_VOID;
4900 if (tok == TOK_IF) {
4901 /* if test */
4902 next();
4903 skip('(');
4904 gexpr();
4905 skip(')');
4906 a = gvtst(1, 0);
4907 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4908 c = tok;
4909 if (c == TOK_ELSE) {
4910 next();
4911 d = gjmp(0);
4912 gsym(a);
4913 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4914 gsym(d); /* patch else jmp */
4915 } else
4916 gsym(a);
4917 } else if (tok == TOK_WHILE) {
4918 next();
4919 d = ind;
4920 vla_sp_restore();
4921 skip('(');
4922 gexpr();
4923 skip(')');
4924 a = gvtst(1, 0);
4925 b = 0;
4926 block(&a, &b, case_sym, def_sym, case_reg, 0);
4927 if(!nocode_wanted)
4928 gjmp_addr(d);
4929 gsym(a);
4930 gsym_addr(b, d);
4931 } else if (tok == '{') {
4932 Sym *llabel;
4933 int block_vla_sp_loc = vla_sp_loc, saved_vlas_in_scope = vlas_in_scope;
4935 next();
4936 /* record local declaration stack position */
4937 s = local_stack;
4938 llabel = local_label_stack;
4939 ++local_scope;
4941 /* handle local labels declarations */
4942 if (tok == TOK_LABEL) {
4943 next();
4944 for(;;) {
4945 if (tok < TOK_UIDENT)
4946 expect("label identifier");
4947 label_push(&local_label_stack, tok, LABEL_DECLARED);
4948 next();
4949 if (tok == ',') {
4950 next();
4951 } else {
4952 skip(';');
4953 break;
4957 while (tok != '}') {
4958 label_or_decl(VT_LOCAL);
4959 if (tok != '}') {
4960 if (is_expr)
4961 vpop();
4962 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
4965 /* pop locally defined labels */
4966 label_pop(&local_label_stack, llabel);
4967 if(is_expr) {
4968 /* XXX: this solution makes only valgrind happy...
4969 triggered by gcc.c-torture/execute/20000917-1.c */
4970 Sym *p;
4971 switch(vtop->type.t & VT_BTYPE) {
4972 /* case VT_PTR: */
4973 /* this breaks a compilation of the linux kernel v2.4.26 */
4974 /* pmd_t *new = ({ __asm__ __volatile__("ud2\n") ; ((pmd_t *)1); }); */
4975 /* Look a commit a80acab: Display error on statement expressions with complex return type */
4976 /* A pointer is not a complex return type */
4977 case VT_STRUCT:
4978 case VT_ENUM:
4979 case VT_FUNC:
4980 for(p=vtop->type.ref;p;p=p->prev)
4981 if(p->prev==s)
4982 tcc_error("unsupported expression type");
4985 /* pop locally defined symbols */
4986 --local_scope;
4987 sym_pop(&local_stack, s);
4989 /* Pop VLA frames and restore stack pointer if required */
4990 if (vlas_in_scope > saved_vlas_in_scope) {
4991 vla_sp_loc = saved_vlas_in_scope ? block_vla_sp_loc : vla_sp_root_loc;
4992 vla_sp_restore();
4994 vlas_in_scope = saved_vlas_in_scope;
4996 next();
4997 } else if (tok == TOK_RETURN) {
4998 next();
4999 if (tok != ';') {
5000 gexpr();
5001 gen_assign_cast(&func_vt);
5002 #ifdef TCC_TARGET_ARM64
5003 // Perhaps it would be better to use this for all backends:
5004 greturn();
5005 #else
5006 if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
5007 CType type, ret_type;
5008 int ret_align, ret_nregs, regsize;
5009 ret_nregs = gfunc_sret(&func_vt, func_var, &ret_type,
5010 &ret_align, &regsize);
5011 if (0 == ret_nregs) {
5012 /* if returning structure, must copy it to implicit
5013 first pointer arg location */
5014 type = func_vt;
5015 mk_pointer(&type);
5016 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
5017 indir();
5018 vswap();
5019 /* copy structure value to pointer */
5020 vstore();
5021 } else {
5022 /* returning structure packed into registers */
5023 int r, size, addr, align;
5024 size = type_size(&func_vt,&align);
5025 if ((vtop->r != (VT_LOCAL | VT_LVAL) ||
5026 (vtop->c.i & (ret_align-1)))
5027 && (align & (ret_align-1))) {
5028 loc = (loc - size) & -ret_align;
5029 addr = loc;
5030 type = func_vt;
5031 vset(&type, VT_LOCAL | VT_LVAL, addr);
5032 vswap();
5033 vstore();
5034 vpop();
5035 vset(&ret_type, VT_LOCAL | VT_LVAL, addr);
5037 vtop->type = ret_type;
5038 if (is_float(ret_type.t))
5039 r = rc_fret(ret_type.t);
5040 else
5041 r = RC_IRET;
5043 for (;;) {
5044 gv(r);
5045 if (--ret_nregs == 0)
5046 break;
5047 /* We assume that when a structure is returned in multiple
5048 registers, their classes are consecutive values of the
5049 suite s(n) = 2^n */
5050 r <<= 1;
5051 vtop->c.i += regsize;
5052 vtop->r = VT_LOCAL | VT_LVAL;
5055 } else if (is_float(func_vt.t)) {
5056 gv(rc_fret(func_vt.t));
5057 } else {
5058 gv(RC_IRET);
5060 #endif
5061 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
5063 skip(';');
5064 rsym = gjmp(rsym); /* jmp */
5065 } else if (tok == TOK_BREAK) {
5066 /* compute jump */
5067 if (!bsym)
5068 tcc_error("cannot break");
5069 *bsym = gjmp(*bsym);
5070 next();
5071 skip(';');
5072 } else if (tok == TOK_CONTINUE) {
5073 /* compute jump */
5074 if (!csym)
5075 tcc_error("cannot continue");
5076 vla_sp_restore_root();
5077 *csym = gjmp(*csym);
5078 next();
5079 skip(';');
5080 } else if (tok == TOK_FOR) {
5081 int e;
5082 next();
5083 skip('(');
5084 s = local_stack;
5085 ++local_scope;
5086 if (tok != ';') {
5087 /* c99 for-loop init decl? */
5088 if (!decl0(VT_LOCAL, 1)) {
5089 /* no, regular for-loop init expr */
5090 gexpr();
5091 vpop();
5094 skip(';');
5095 d = ind;
5096 c = ind;
5097 vla_sp_restore();
5098 a = 0;
5099 b = 0;
5100 if (tok != ';') {
5101 gexpr();
5102 a = gvtst(1, 0);
5104 skip(';');
5105 if (tok != ')') {
5106 e = gjmp(0);
5107 c = ind;
5108 vla_sp_restore();
5109 gexpr();
5110 vpop();
5111 gjmp_addr(d);
5112 gsym(e);
5114 skip(')');
5115 block(&a, &b, case_sym, def_sym, case_reg, 0);
5116 if(!nocode_wanted)
5117 gjmp_addr(c);
5118 gsym(a);
5119 gsym_addr(b, c);
5120 --local_scope;
5121 sym_pop(&local_stack, s);
5123 } else
5124 if (tok == TOK_DO) {
5125 next();
5126 a = 0;
5127 b = 0;
5128 d = ind;
5129 vla_sp_restore();
5130 block(&a, &b, case_sym, def_sym, case_reg, 0);
5131 skip(TOK_WHILE);
5132 skip('(');
5133 gsym(b);
5134 gexpr();
5135 c = gvtst(0, 0);
5136 gsym_addr(c, d);
5137 skip(')');
5138 gsym(a);
5139 skip(';');
5140 } else
5141 if (tok == TOK_SWITCH) {
5142 next();
5143 skip('(');
5144 gexpr();
5145 /* XXX: other types than integer */
5146 case_reg = gv(RC_INT);
5147 vpop();
5148 skip(')');
5149 a = 0;
5150 b = gjmp(0); /* jump to first case */
5151 c = 0;
5152 block(&a, csym, &b, &c, case_reg, 0);
5153 /* if no default, jmp after switch */
5154 if (c == 0)
5155 c = ind;
5156 /* default label */
5157 gsym_addr(b, c);
5158 /* break label */
5159 gsym(a);
5160 } else
5161 if (tok == TOK_CASE) {
5162 int v1, v2;
5163 if (!case_sym)
5164 expect("switch");
5165 next();
5166 v1 = expr_const();
5167 v2 = v1;
5168 if (gnu_ext && tok == TOK_DOTS) {
5169 next();
5170 v2 = expr_const();
5171 if (v2 < v1)
5172 tcc_warning("empty case range");
5174 /* since a case is like a label, we must skip it with a jmp */
5175 b = gjmp(0);
5176 gsym(*case_sym);
5177 vseti(case_reg, 0);
5178 vdup();
5179 vpushi(v1);
5180 if (v1 == v2) {
5181 gen_op(TOK_EQ);
5182 *case_sym = gtst(1, 0);
5183 } else {
5184 gen_op(TOK_GE);
5185 *case_sym = gtst(1, 0);
5186 vseti(case_reg, 0);
5187 vpushi(v2);
5188 gen_op(TOK_LE);
5189 *case_sym = gtst(1, *case_sym);
5191 case_reg = gv(RC_INT);
5192 vpop();
5193 gsym(b);
5194 skip(':');
5195 is_expr = 0;
5196 goto block_after_label;
5197 } else
5198 if (tok == TOK_DEFAULT) {
5199 next();
5200 skip(':');
5201 if (!def_sym)
5202 expect("switch");
5203 if (*def_sym)
5204 tcc_error("too many 'default'");
5205 *def_sym = ind;
5206 is_expr = 0;
5207 goto block_after_label;
5208 } else
5209 if (tok == TOK_GOTO) {
5210 next();
5211 if (tok == '*' && gnu_ext) {
5212 /* computed goto */
5213 next();
5214 gexpr();
5215 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
5216 expect("pointer");
5217 ggoto();
5218 } else if (tok >= TOK_UIDENT) {
5219 s = label_find(tok);
5220 /* put forward definition if needed */
5221 if (!s) {
5222 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
5223 } else {
5224 if (s->r == LABEL_DECLARED)
5225 s->r = LABEL_FORWARD;
5227 vla_sp_restore_root();
5228 if (s->r & LABEL_FORWARD)
5229 s->jnext = gjmp(s->jnext);
5230 else
5231 gjmp_addr(s->jnext);
5232 next();
5233 } else {
5234 expect("label identifier");
5236 skip(';');
5237 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
5238 asm_instr();
5239 } else {
5240 b = is_label();
5241 if (b) {
5242 /* label case */
5243 s = label_find(b);
5244 if (s) {
5245 if (s->r == LABEL_DEFINED)
5246 tcc_error("duplicate label '%s'", get_tok_str(s->v, NULL));
5247 gsym(s->jnext);
5248 s->r = LABEL_DEFINED;
5249 } else {
5250 s = label_push(&global_label_stack, b, LABEL_DEFINED);
5252 s->jnext = ind;
5253 vla_sp_restore();
5254 /* we accept this, but it is a mistake */
5255 block_after_label:
5256 if (tok == '}') {
5257 tcc_warning("deprecated use of label at end of compound statement");
5258 } else {
5259 if (is_expr)
5260 vpop();
5261 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
5263 } else {
5264 /* expression case */
5265 if (tok != ';') {
5266 if (is_expr) {
5267 vpop();
5268 gexpr();
5269 } else {
5270 gexpr();
5271 vpop();
5274 skip(';');
5279 /* t is the array or struct type. c is the array or struct
5280 address. cur_index/cur_field is the pointer to the current
5281 value. 'size_only' is true if only size info is needed (only used
5282 in arrays) */
5283 static void decl_designator(CType *type, Section *sec, unsigned long c,
5284 int *cur_index, Sym **cur_field,
5285 int size_only)
5287 Sym *s, *f;
5288 int notfirst, index, index_last, align, l, nb_elems, elem_size;
5289 CType type1;
5291 notfirst = 0;
5292 elem_size = 0;
5293 nb_elems = 1;
5294 if (gnu_ext && (l = is_label()) != 0)
5295 goto struct_field;
5296 while (tok == '[' || tok == '.') {
5297 if (tok == '[') {
5298 if (!(type->t & VT_ARRAY))
5299 expect("array type");
5300 s = type->ref;
5301 next();
5302 index = expr_const();
5303 if (index < 0 || (s->c >= 0 && index >= s->c))
5304 expect("invalid index");
5305 if (tok == TOK_DOTS && gnu_ext) {
5306 next();
5307 index_last = expr_const();
5308 if (index_last < 0 ||
5309 (s->c >= 0 && index_last >= s->c) ||
5310 index_last < index)
5311 expect("invalid index");
5312 } else {
5313 index_last = index;
5315 skip(']');
5316 if (!notfirst)
5317 *cur_index = index_last;
5318 type = pointed_type(type);
5319 elem_size = type_size(type, &align);
5320 c += index * elem_size;
5321 /* NOTE: we only support ranges for last designator */
5322 nb_elems = index_last - index + 1;
5323 if (nb_elems != 1) {
5324 notfirst = 1;
5325 break;
5327 } else {
5328 next();
5329 l = tok;
5330 next();
5331 struct_field:
5332 if ((type->t & VT_BTYPE) != VT_STRUCT)
5333 expect("struct/union type");
5334 s = type->ref;
5335 l |= SYM_FIELD;
5336 f = s->next;
5337 while (f) {
5338 if (f->v == l)
5339 break;
5340 f = f->next;
5342 if (!f)
5343 expect("field");
5344 if (!notfirst)
5345 *cur_field = f;
5346 /* XXX: fix this mess by using explicit storage field */
5347 type1 = f->type;
5348 type1.t |= (type->t & ~VT_TYPE);
5349 type = &type1;
5350 c += f->c;
5352 notfirst = 1;
5354 if (notfirst) {
5355 if (tok == '=') {
5356 next();
5357 } else {
5358 if (!gnu_ext)
5359 expect("=");
5361 } else {
5362 if (type->t & VT_ARRAY) {
5363 index = *cur_index;
5364 type = pointed_type(type);
5365 c += index * type_size(type, &align);
5366 } else {
5367 f = *cur_field;
5368 if (!f)
5369 tcc_error("too many field init");
5370 /* XXX: fix this mess by using explicit storage field */
5371 type1 = f->type;
5372 type1.t |= (type->t & ~VT_TYPE);
5373 type = &type1;
5374 c += f->c;
5377 decl_initializer(type, sec, c, 0, size_only);
5379 /* XXX: make it more general */
5380 if (!size_only && nb_elems > 1) {
5381 unsigned long c_end;
5382 uint8_t *src, *dst;
5383 int i;
5385 if (!sec)
5386 tcc_error("range init not supported yet for dynamic storage");
5387 c_end = c + nb_elems * elem_size;
5388 if (c_end > sec->data_allocated)
5389 section_realloc(sec, c_end);
5390 src = sec->data + c;
5391 dst = src;
5392 for(i = 1; i < nb_elems; i++) {
5393 dst += elem_size;
5394 memcpy(dst, src, elem_size);
5399 #define EXPR_VAL 0
5400 #define EXPR_CONST 1
5401 #define EXPR_ANY 2
5403 /* store a value or an expression directly in global data or in local array */
5404 static void init_putv(CType *type, Section *sec, unsigned long c,
5405 int v, int expr_type)
5407 int saved_global_expr, bt, bit_pos, bit_size;
5408 void *ptr;
5409 unsigned long long bit_mask;
5410 CType dtype;
5412 switch(expr_type) {
5413 case EXPR_VAL:
5414 vpushi(v);
5415 break;
5416 case EXPR_CONST:
5417 /* compound literals must be allocated globally in this case */
5418 saved_global_expr = global_expr;
5419 global_expr = 1;
5420 expr_const1();
5421 global_expr = saved_global_expr;
5422 /* NOTE: symbols are accepted */
5423 if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
5424 tcc_error("initializer element is not constant");
5425 break;
5426 case EXPR_ANY:
5427 expr_eq();
5428 break;
5431 dtype = *type;
5432 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
5434 if (sec) {
5435 /* XXX: not portable */
5436 /* XXX: generate error if incorrect relocation */
5437 gen_assign_cast(&dtype);
5438 bt = type->t & VT_BTYPE;
5439 /* we'll write at most 16 bytes */
5440 if (c + 16 > sec->data_allocated) {
5441 section_realloc(sec, c + 16);
5443 ptr = sec->data + c;
5444 /* XXX: make code faster ? */
5445 if (!(type->t & VT_BITFIELD)) {
5446 bit_pos = 0;
5447 bit_size = 32;
5448 bit_mask = -1LL;
5449 } else {
5450 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5451 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
5452 bit_mask = (1LL << bit_size) - 1;
5454 if ((vtop->r & VT_SYM) &&
5455 (bt == VT_BYTE ||
5456 bt == VT_SHORT ||
5457 bt == VT_DOUBLE ||
5458 bt == VT_LDOUBLE ||
5459 bt == VT_LLONG ||
5460 (bt == VT_INT && bit_size != 32)))
5461 tcc_error("initializer element is not computable at load time");
5462 switch(bt) {
5463 /* XXX: when cross-compiling we assume that each type has the
5464 same representation on host and target, which is likely to
5465 be wrong in the case of long double */
5466 case VT_BOOL:
5467 vtop->c.i = (vtop->c.i != 0);
5468 case VT_BYTE:
5469 *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5470 break;
5471 case VT_SHORT:
5472 *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5473 break;
5474 case VT_DOUBLE:
5475 *(double *)ptr = vtop->c.d;
5476 break;
5477 case VT_LDOUBLE:
5478 *(long double *)ptr = vtop->c.ld;
5479 break;
5480 case VT_LLONG:
5481 *(long long *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5482 break;
5483 case VT_PTR: {
5484 addr_t val = (vtop->c.i & bit_mask) << bit_pos;
5485 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
5486 if (vtop->r & VT_SYM)
5487 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
5488 else
5489 *(addr_t *)ptr |= val;
5490 #else
5491 if (vtop->r & VT_SYM)
5492 greloc(sec, vtop->sym, c, R_DATA_PTR);
5493 *(addr_t *)ptr |= val;
5494 #endif
5495 break;
5497 default: {
5498 int val = (vtop->c.i & bit_mask) << bit_pos;
5499 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
5500 if (vtop->r & VT_SYM)
5501 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
5502 else
5503 *(int *)ptr |= val;
5504 #else
5505 if (vtop->r & VT_SYM)
5506 greloc(sec, vtop->sym, c, R_DATA_PTR);
5507 *(int *)ptr |= val;
5508 #endif
5509 break;
5512 vtop--;
5513 } else {
5514 vset(&dtype, VT_LOCAL|VT_LVAL, c);
5515 vswap();
5516 vstore();
5517 vpop();
5521 /* put zeros for variable based init */
5522 static void init_putz(CType *t, Section *sec, unsigned long c, int size)
5524 if (sec) {
5525 /* nothing to do because globals are already set to zero */
5526 } else {
5527 vpush_global_sym(&func_old_type, TOK_memset);
5528 vseti(VT_LOCAL, c);
5529 #ifdef TCC_TARGET_ARM
5530 vpushs(size);
5531 vpushi(0);
5532 #else
5533 vpushi(0);
5534 vpushs(size);
5535 #endif
5536 gfunc_call(3);
5540 /* 't' contains the type and storage info. 'c' is the offset of the
5541 object in section 'sec'. If 'sec' is NULL, it means stack based
5542 allocation. 'first' is true if array '{' must be read (multi
5543 dimension implicit array init handling). 'size_only' is true if
5544 size only evaluation is wanted (only for arrays). */
5545 static void decl_initializer(CType *type, Section *sec, unsigned long c,
5546 int first, int size_only)
5548 int index, array_length, n, no_oblock, nb, parlevel, parlevel1, i;
5549 int size1, align1, expr_type;
5550 Sym *s, *f;
5551 CType *t1;
5553 if (type->t & VT_VLA) {
5554 int a;
5556 /* save current stack pointer */
5557 if (vlas_in_scope == 0) {
5558 if (vla_sp_root_loc == -1)
5559 vla_sp_root_loc = (loc -= PTR_SIZE);
5560 gen_vla_sp_save(vla_sp_root_loc);
5563 vla_runtime_type_size(type, &a);
5564 gen_vla_alloc(type, a);
5565 gen_vla_sp_save(c);
5566 vla_sp_loc = c;
5567 vlas_in_scope++;
5568 } else if (type->t & VT_ARRAY) {
5569 s = type->ref;
5570 n = s->c;
5571 array_length = 0;
5572 t1 = pointed_type(type);
5573 size1 = type_size(t1, &align1);
5575 no_oblock = 1;
5576 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
5577 tok == '{') {
5578 if (tok != '{')
5579 tcc_error("character array initializer must be a literal,"
5580 " optionally enclosed in braces");
5581 skip('{');
5582 no_oblock = 0;
5585 /* only parse strings here if correct type (otherwise: handle
5586 them as ((w)char *) expressions */
5587 if ((tok == TOK_LSTR &&
5588 #ifdef TCC_TARGET_PE
5589 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
5590 #else
5591 (t1->t & VT_BTYPE) == VT_INT
5592 #endif
5593 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
5594 while (tok == TOK_STR || tok == TOK_LSTR) {
5595 int cstr_len, ch;
5597 /* compute maximum number of chars wanted */
5598 if (tok == TOK_STR)
5599 cstr_len = tokc.str.size;
5600 else
5601 cstr_len = tokc.str.size / sizeof(nwchar_t);
5602 cstr_len--;
5603 nb = cstr_len;
5604 if (n >= 0 && nb > (n - array_length))
5605 nb = n - array_length;
5606 if (!size_only) {
5607 if (cstr_len > nb)
5608 tcc_warning("initializer-string for array is too long");
5609 /* in order to go faster for common case (char
5610 string in global variable, we handle it
5611 specifically */
5612 if (sec && tok == TOK_STR && size1 == 1) {
5613 memcpy(sec->data + c + array_length, tokc.str.data, nb);
5614 } else {
5615 for(i=0;i<nb;i++) {
5616 if (tok == TOK_STR)
5617 ch = ((unsigned char *)tokc.str.data)[i];
5618 else
5619 ch = ((nwchar_t *)tokc.str.data)[i];
5620 init_putv(t1, sec, c + (array_length + i) * size1,
5621 ch, EXPR_VAL);
5625 array_length += nb;
5626 next();
5628 /* only add trailing zero if enough storage (no
5629 warning in this case since it is standard) */
5630 if (n < 0 || array_length < n) {
5631 if (!size_only) {
5632 init_putv(t1, sec, c + (array_length * size1), 0, EXPR_VAL);
5634 array_length++;
5636 } else {
5637 index = 0;
5638 while (tok != '}') {
5639 decl_designator(type, sec, c, &index, NULL, size_only);
5640 if (n >= 0 && index >= n)
5641 tcc_error("index too large");
5642 /* must put zero in holes (note that doing it that way
5643 ensures that it even works with designators) */
5644 if (!size_only && array_length < index) {
5645 init_putz(t1, sec, c + array_length * size1,
5646 (index - array_length) * size1);
5648 index++;
5649 if (index > array_length)
5650 array_length = index;
5651 /* special test for multi dimensional arrays (may not
5652 be strictly correct if designators are used at the
5653 same time) */
5654 if (index >= n && no_oblock)
5655 break;
5656 if (tok == '}')
5657 break;
5658 skip(',');
5661 if (!no_oblock)
5662 skip('}');
5663 /* put zeros at the end */
5664 if (!size_only && n >= 0 && array_length < n) {
5665 init_putz(t1, sec, c + array_length * size1,
5666 (n - array_length) * size1);
5668 /* patch type size if needed */
5669 if (n < 0)
5670 s->c = array_length;
5671 } else if ((type->t & VT_BTYPE) == VT_STRUCT &&
5672 (sec || !first || tok == '{')) {
5674 /* NOTE: the previous test is a specific case for automatic
5675 struct/union init */
5676 /* XXX: union needs only one init */
5678 int par_count = 0;
5679 if (tok == '(') {
5680 AttributeDef ad1;
5681 CType type1;
5682 next();
5683 if (tcc_state->old_struct_init_code) {
5684 /* an old version of struct initialization.
5685 It have a problems. But with a new version
5686 linux 2.4.26 can't load ramdisk.
5688 while (tok == '(') {
5689 par_count++;
5690 next();
5692 if (!parse_btype(&type1, &ad1))
5693 expect("cast");
5694 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
5695 #if 0
5696 if (!is_assignable_types(type, &type1))
5697 tcc_error("invalid type for cast");
5698 #endif
5699 skip(')');
5701 else
5703 if (tok != '(') {
5704 if (!parse_btype(&type1, &ad1))
5705 expect("cast");
5706 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
5707 #if 0
5708 if (!is_assignable_types(type, &type1))
5709 tcc_error("invalid type for cast");
5710 #endif
5711 skip(')');
5712 } else
5713 unget_tok(tok);
5717 no_oblock = 1;
5718 if (first || tok == '{') {
5719 skip('{');
5720 no_oblock = 0;
5722 s = type->ref;
5723 f = s->next;
5724 array_length = 0;
5725 index = 0;
5726 n = s->c;
5727 while (tok != '}') {
5728 decl_designator(type, sec, c, NULL, &f, size_only);
5729 index = f->c;
5730 if (!size_only && array_length < index) {
5731 init_putz(type, sec, c + array_length,
5732 index - array_length);
5734 index = index + type_size(&f->type, &align1);
5735 if (index > array_length)
5736 array_length = index;
5738 /* gr: skip fields from same union - ugly. */
5739 while (f->next) {
5740 int align = 0;
5741 int f_size = type_size(&f->type, &align);
5742 int f_type = (f->type.t & VT_BTYPE);
5744 ///printf("index: %2d %08x -- %2d %08x\n", f->c, f->type.t, f->next->c, f->next->type.t);
5745 /* test for same offset */
5746 if (f->next->c != f->c)
5747 break;
5748 if ((f_type == VT_STRUCT) && (f_size == 0)) {
5750 Lets assume a structure of size 0 can't be a member of the union.
5751 This allow to compile the following code from a linux kernel v2.4.26
5752 typedef struct { } rwlock_t;
5753 struct fs_struct {
5754 int count;
5755 rwlock_t lock;
5756 int umask;
5758 struct fs_struct init_fs = { { (1) }, (rwlock_t) {}, 0022, };
5759 tcc-0.9.23 can succesfully compile this version of the kernel.
5760 gcc don't have problems with this code too.
5762 break;
5764 /* if yes, test for bitfield shift */
5765 if ((f->type.t & VT_BITFIELD) && (f->next->type.t & VT_BITFIELD)) {
5766 int bit_pos_1 = (f->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5767 int bit_pos_2 = (f->next->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5768 //printf("bitfield %d %d\n", bit_pos_1, bit_pos_2);
5769 if (bit_pos_1 != bit_pos_2)
5770 break;
5772 f = f->next;
5775 f = f->next;
5776 if (no_oblock && f == NULL)
5777 break;
5778 if (tok == '}')
5779 break;
5780 skip(',');
5782 /* put zeros at the end */
5783 if (!size_only && array_length < n) {
5784 init_putz(type, sec, c + array_length,
5785 n - array_length);
5787 if (!no_oblock)
5788 skip('}');
5789 while (par_count) {
5790 skip(')');
5791 par_count--;
5793 } else if (tok == '{') {
5794 next();
5795 decl_initializer(type, sec, c, first, size_only);
5796 skip('}');
5797 } else if (size_only) {
5798 /* just skip expression */
5799 parlevel = parlevel1 = 0;
5800 while ((parlevel > 0 || parlevel1 > 0 ||
5801 (tok != '}' && tok != ',')) && tok != -1) {
5802 if (tok == '(')
5803 parlevel++;
5804 else if (tok == ')') {
5805 if (parlevel == 0 && parlevel1 == 0)
5806 break;
5807 parlevel--;
5809 else if (tok == '{')
5810 parlevel1++;
5811 else if (tok == '}') {
5812 if (parlevel == 0 && parlevel1 == 0)
5813 break;
5814 parlevel1--;
5816 next();
5818 } else {
5819 /* currently, we always use constant expression for globals
5820 (may change for scripting case) */
5821 expr_type = EXPR_CONST;
5822 if (!sec)
5823 expr_type = EXPR_ANY;
5824 init_putv(type, sec, c, 0, expr_type);
5828 /* parse an initializer for type 't' if 'has_init' is non zero, and
5829 allocate space in local or global data space ('r' is either
5830 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
5831 variable 'v' of scope 'scope' is declared before initializers
5832 are parsed. If 'v' is zero, then a reference to the new object
5833 is put in the value stack. If 'has_init' is 2, a special parsing
5834 is done to handle string constants. */
5835 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
5836 int has_init, int v, int scope)
5838 int size, align, addr, data_offset;
5839 int level;
5840 ParseState saved_parse_state = {0};
5841 TokenString init_str;
5842 Section *sec;
5843 Sym *flexible_array;
5845 flexible_array = NULL;
5846 if ((type->t & VT_BTYPE) == VT_STRUCT) {
5847 Sym *field = type->ref->next;
5848 if (field) {
5849 while (field->next)
5850 field = field->next;
5851 if (field->type.t & VT_ARRAY && field->type.ref->c < 0)
5852 flexible_array = field;
5856 size = type_size(type, &align);
5857 /* If unknown size, we must evaluate it before
5858 evaluating initializers because
5859 initializers can generate global data too
5860 (e.g. string pointers or ISOC99 compound
5861 literals). It also simplifies local
5862 initializers handling */
5863 tok_str_new(&init_str);
5864 if (size < 0 || (flexible_array && has_init)) {
5865 if (!has_init)
5866 tcc_error("unknown type size");
5867 /* get all init string */
5868 if (has_init == 2) {
5869 /* only get strings */
5870 while (tok == TOK_STR || tok == TOK_LSTR) {
5871 tok_str_add_tok(&init_str);
5872 next();
5874 } else {
5875 level = 0;
5876 while (level > 0 || (tok != ',' && tok != ';')) {
5877 if (tok < 0)
5878 tcc_error("unexpected end of file in initializer");
5879 tok_str_add_tok(&init_str);
5880 if (tok == '{')
5881 level++;
5882 else if (tok == '}') {
5883 level--;
5884 if (level <= 0) {
5885 next();
5886 break;
5889 next();
5892 tok_str_add(&init_str, -1);
5893 tok_str_add(&init_str, 0);
5895 /* compute size */
5896 save_parse_state(&saved_parse_state);
5898 begin_macro(&init_str, 0);
5899 next();
5900 decl_initializer(type, NULL, 0, 1, 1);
5901 /* prepare second initializer parsing */
5902 macro_ptr = init_str.str;
5903 next();
5905 /* if still unknown size, error */
5906 size = type_size(type, &align);
5907 if (size < 0)
5908 tcc_error("unknown type size");
5910 /* If there's a flex member and it was used in the initializer
5911 adjust size. */
5912 if (flexible_array &&
5913 flexible_array->type.ref->c > 0)
5914 size += flexible_array->type.ref->c
5915 * pointed_size(&flexible_array->type);
5916 /* take into account specified alignment if bigger */
5917 if (ad->a.aligned) {
5918 if (ad->a.aligned > align)
5919 align = ad->a.aligned;
5920 } else if (ad->a.packed) {
5921 align = 1;
5923 if ((r & VT_VALMASK) == VT_LOCAL) {
5924 sec = NULL;
5925 #ifdef CONFIG_TCC_BCHECK
5926 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5927 loc--;
5929 #endif
5930 loc = (loc - size) & -align;
5931 addr = loc;
5932 #ifdef CONFIG_TCC_BCHECK
5933 /* handles bounds */
5934 /* XXX: currently, since we do only one pass, we cannot track
5935 '&' operators, so we add only arrays */
5936 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5937 addr_t *bounds_ptr;
5938 /* add padding between regions */
5939 loc--;
5940 /* then add local bound info */
5941 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(addr_t));
5942 bounds_ptr[0] = addr;
5943 bounds_ptr[1] = size;
5945 #endif
5946 if (v) {
5947 /* local variable */
5948 sym_push(v, type, r, addr);
5949 } else {
5950 /* push local reference */
5951 vset(type, r, addr);
5953 } else {
5954 Sym *sym;
5956 sym = NULL;
5957 if (v && scope == VT_CONST) {
5958 /* see if the symbol was already defined */
5959 sym = sym_find(v);
5960 if (sym) {
5961 if (!is_compatible_types(&sym->type, type))
5962 tcc_error("incompatible types for redefinition of '%s'",
5963 get_tok_str(v, NULL));
5964 if (sym->type.t & VT_EXTERN) {
5965 /* if the variable is extern, it was not allocated */
5966 sym->type.t &= ~VT_EXTERN;
5967 /* set array size if it was omitted in extern
5968 declaration */
5969 if ((sym->type.t & VT_ARRAY) &&
5970 sym->type.ref->c < 0 &&
5971 type->ref->c >= 0)
5972 sym->type.ref->c = type->ref->c;
5973 } else {
5974 /* we accept several definitions of the same
5975 global variable. this is tricky, because we
5976 must play with the SHN_COMMON type of the symbol */
5977 /* XXX: should check if the variable was already
5978 initialized. It is incorrect to initialized it
5979 twice */
5980 /* no init data, we won't add more to the symbol */
5981 if (!has_init)
5982 goto no_alloc;
5987 /* allocate symbol in corresponding section */
5988 sec = ad->section;
5989 if (!sec) {
5990 if (has_init)
5991 sec = data_section;
5992 else if (tcc_state->nocommon)
5993 sec = bss_section;
5995 if (sec) {
5996 data_offset = sec->data_offset;
5997 data_offset = (data_offset + align - 1) & -align;
5998 addr = data_offset;
5999 /* very important to increment global pointer at this time
6000 because initializers themselves can create new initializers */
6001 data_offset += size;
6002 #ifdef CONFIG_TCC_BCHECK
6003 /* add padding if bound check */
6004 if (tcc_state->do_bounds_check)
6005 data_offset++;
6006 #endif
6007 sec->data_offset = data_offset;
6008 /* allocate section space to put the data */
6009 if (sec->sh_type != SHT_NOBITS &&
6010 data_offset > sec->data_allocated)
6011 section_realloc(sec, data_offset);
6012 /* align section if needed */
6013 if (align > sec->sh_addralign)
6014 sec->sh_addralign = align;
6015 } else {
6016 addr = 0; /* avoid warning */
6019 if (v) {
6020 if (scope != VT_CONST || !sym) {
6021 sym = sym_push(v, type, r | VT_SYM, 0);
6022 sym->asm_label = ad->asm_label;
6024 /* update symbol definition */
6025 if (sec) {
6026 put_extern_sym(sym, sec, addr, size);
6027 } else {
6028 ElfW(Sym) *esym;
6029 /* put a common area */
6030 put_extern_sym(sym, NULL, align, size);
6031 /* XXX: find a nicer way */
6032 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
6033 esym->st_shndx = SHN_COMMON;
6035 } else {
6036 /* push global reference */
6037 sym = get_sym_ref(type, sec, addr, size);
6038 vpushsym(type, sym);
6040 /* patch symbol weakness */
6041 if (type->t & VT_WEAK)
6042 weaken_symbol(sym);
6043 apply_visibility(sym, type);
6044 #ifdef CONFIG_TCC_BCHECK
6045 /* handles bounds now because the symbol must be defined
6046 before for the relocation */
6047 if (tcc_state->do_bounds_check) {
6048 addr_t *bounds_ptr;
6050 greloc(bounds_section, sym, bounds_section->data_offset, R_DATA_PTR);
6051 /* then add global bound info */
6052 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(addr_t));
6053 bounds_ptr[0] = 0; /* relocated */
6054 bounds_ptr[1] = size;
6056 #endif
6058 if (has_init || (type->t & VT_VLA)) {
6059 decl_initializer(type, sec, addr, 1, 0);
6060 /* restore parse state if needed */
6061 if (init_str.str) {
6062 end_macro();
6063 restore_parse_state(&saved_parse_state);
6065 /* patch flexible array member size back to -1, */
6066 /* for possible subsequent similar declarations */
6067 if (flexible_array)
6068 flexible_array->type.ref->c = -1;
6070 no_alloc: ;
6073 static void put_func_debug(Sym *sym)
6075 char buf[512];
6077 /* stabs info */
6078 /* XXX: we put here a dummy type */
6079 snprintf(buf, sizeof(buf), "%s:%c1",
6080 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
6081 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
6082 cur_text_section, sym->c);
6083 /* //gr gdb wants a line at the function */
6084 put_stabn(N_SLINE, 0, file->line_num, 0);
6085 last_ind = 0;
6086 last_line_num = 0;
6089 /* parse an old style function declaration list */
6090 /* XXX: check multiple parameter */
6091 static void func_decl_list(Sym *func_sym)
6093 AttributeDef ad;
6094 int v;
6095 Sym *s;
6096 CType btype, type;
6098 /* parse each declaration */
6099 while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF &&
6100 tok != TOK_ASM1 && tok != TOK_ASM2 && tok != TOK_ASM3) {
6101 if (!parse_btype(&btype, &ad))
6102 expect("declaration list");
6103 if (((btype.t & VT_BTYPE) == VT_ENUM ||
6104 (btype.t & VT_BTYPE) == VT_STRUCT) &&
6105 tok == ';') {
6106 /* we accept no variable after */
6107 } else {
6108 for(;;) {
6109 type = btype;
6110 type_decl(&type, &ad, &v, TYPE_DIRECT);
6111 /* find parameter in function parameter list */
6112 s = func_sym->next;
6113 while (s != NULL) {
6114 if ((s->v & ~SYM_FIELD) == v)
6115 goto found;
6116 s = s->next;
6118 tcc_error("declaration for parameter '%s' but no such parameter",
6119 get_tok_str(v, NULL));
6120 found:
6121 /* check that no storage specifier except 'register' was given */
6122 if (type.t & VT_STORAGE)
6123 tcc_error("storage class specified for '%s'", get_tok_str(v, NULL));
6124 convert_parameter_type(&type);
6125 /* we can add the type (NOTE: it could be local to the function) */
6126 s->type = type;
6127 /* accept other parameters */
6128 if (tok == ',')
6129 next();
6130 else
6131 break;
6134 skip(';');
6138 /* parse a function defined by symbol 'sym' and generate its code in
6139 'cur_text_section' */
6140 static void gen_function(Sym *sym)
6142 int saved_nocode_wanted = nocode_wanted;
6144 nocode_wanted = 0;
6145 ind = cur_text_section->data_offset;
6146 /* NOTE: we patch the symbol size later */
6147 put_extern_sym(sym, cur_text_section, ind, 0);
6148 funcname = get_tok_str(sym->v, NULL);
6149 func_ind = ind;
6150 /* Initialize VLA state */
6151 vla_sp_loc = -1;
6152 vla_sp_root_loc = -1;
6153 /* put debug symbol */
6154 if (tcc_state->do_debug)
6155 put_func_debug(sym);
6157 /* push a dummy symbol to enable local sym storage */
6158 sym_push2(&local_stack, SYM_FIELD, 0, 0);
6159 local_scope = 1; /* for function parameters */
6160 gfunc_prolog(&sym->type);
6161 local_scope = 0;
6163 #ifdef CONFIG_TCC_BCHECK
6164 if (tcc_state->do_bounds_check && !strcmp(funcname, "main")) {
6165 int i;
6166 Sym *sym;
6167 for (i = 0, sym = local_stack; i < 2; i++, sym = sym->prev) {
6168 if (sym->v & SYM_FIELD || sym->prev->v & SYM_FIELD)
6169 break;
6170 vpush_global_sym(&func_old_type, TOK___bound_main_arg);
6171 vset(&sym->type, sym->r, sym->c);
6172 gfunc_call(1);
6175 #endif
6176 rsym = 0;
6177 block(NULL, NULL, NULL, NULL, 0, 0);
6178 gsym(rsym);
6179 gfunc_epilog();
6180 cur_text_section->data_offset = ind;
6181 label_pop(&global_label_stack, NULL);
6182 /* reset local stack */
6183 local_scope = 0;
6184 sym_pop(&local_stack, NULL);
6185 /* end of function */
6186 /* patch symbol size */
6187 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
6188 ind - func_ind;
6189 /* patch symbol weakness (this definition overrules any prototype) */
6190 if (sym->type.t & VT_WEAK)
6191 weaken_symbol(sym);
6192 apply_visibility(sym, &sym->type);
6193 if (tcc_state->do_debug) {
6194 put_stabn(N_FUN, 0, 0, ind - func_ind);
6196 /* It's better to crash than to generate wrong code */
6197 cur_text_section = NULL;
6198 funcname = ""; /* for safety */
6199 func_vt.t = VT_VOID; /* for safety */
6200 func_var = 0; /* for safety */
6201 ind = 0; /* for safety */
6202 nocode_wanted = saved_nocode_wanted;
6203 check_vstack();
6206 ST_FUNC void gen_inline_functions(void)
6208 Sym *sym;
6209 int inline_generated, i, ln;
6210 struct InlineFunc *fn;
6212 ln = file->line_num;
6213 /* iterate while inline function are referenced */
6214 for(;;) {
6215 inline_generated = 0;
6216 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
6217 fn = tcc_state->inline_fns[i];
6218 sym = fn->sym;
6219 if (sym && sym->c) {
6220 /* the function was used: generate its code and
6221 convert it to a normal function */
6222 fn->sym = NULL;
6223 if (file)
6224 pstrcpy(file->filename, sizeof file->filename, fn->filename);
6225 sym->r = VT_SYM | VT_CONST;
6226 sym->type.t &= ~VT_INLINE;
6228 begin_macro(&fn->func_str, 0);
6229 next();
6230 cur_text_section = text_section;
6231 gen_function(sym);
6232 end_macro();
6234 inline_generated = 1;
6237 if (!inline_generated)
6238 break;
6240 file->line_num = ln;
6241 /* free tokens of unused inline functions */
6242 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
6243 fn = tcc_state->inline_fns[i];
6244 if (fn->sym)
6245 tok_str_free(fn->func_str.str);
6247 dynarray_reset(&tcc_state->inline_fns, &tcc_state->nb_inline_fns);
6250 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
6251 static int decl0(int l, int is_for_loop_init)
6253 int v, has_init, r;
6254 CType type, btype;
6255 Sym *sym;
6256 AttributeDef ad;
6258 while (1) {
6259 if (!parse_btype(&btype, &ad)) {
6260 if (is_for_loop_init)
6261 return 0;
6262 /* skip redundant ';' */
6263 /* XXX: find more elegant solution */
6264 if (tok == ';') {
6265 next();
6266 continue;
6268 if (l == VT_CONST &&
6269 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
6270 /* global asm block */
6271 asm_global_instr();
6272 continue;
6274 /* special test for old K&R protos without explicit int
6275 type. Only accepted when defining global data */
6276 if (l == VT_LOCAL || tok < TOK_DEFINE)
6277 break;
6278 btype.t = VT_INT;
6280 if (((btype.t & VT_BTYPE) == VT_ENUM ||
6281 (btype.t & VT_BTYPE) == VT_STRUCT) &&
6282 tok == ';') {
6283 if ((btype.t & VT_BTYPE) == VT_STRUCT) {
6284 int v = btype.ref->v;
6285 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) >= SYM_FIRST_ANOM)
6286 tcc_warning("unnamed struct/union that defines no instances");
6288 next();
6289 continue;
6291 while (1) { /* iterate thru each declaration */
6292 type = btype;
6293 type_decl(&type, &ad, &v, TYPE_DIRECT);
6294 #if 0
6296 char buf[500];
6297 type_to_str(buf, sizeof(buf), t, get_tok_str(v, NULL));
6298 printf("type = '%s'\n", buf);
6300 #endif
6301 if ((type.t & VT_BTYPE) == VT_FUNC) {
6302 if ((type.t & VT_STATIC) && (l == VT_LOCAL)) {
6303 tcc_error("function without file scope cannot be static");
6305 /* if old style function prototype, we accept a
6306 declaration list */
6307 sym = type.ref;
6308 if (sym->c == FUNC_OLD)
6309 func_decl_list(sym);
6312 if (gnu_ext && (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
6313 ad.asm_label = asm_label_instr();
6314 /* parse one last attribute list, after asm label */
6315 parse_attribute(&ad);
6316 if (tok == '{')
6317 expect(";");
6320 if (ad.a.weak)
6321 type.t |= VT_WEAK;
6322 #ifdef TCC_TARGET_PE
6323 if (ad.a.func_import)
6324 type.t |= VT_IMPORT;
6325 if (ad.a.func_export)
6326 type.t |= VT_EXPORT;
6327 #endif
6328 type.t |= ad.a.visibility << VT_VIS_SHIFT;
6330 if (tok == '{') {
6331 if (l == VT_LOCAL)
6332 tcc_error("cannot use local functions");
6333 if ((type.t & VT_BTYPE) != VT_FUNC)
6334 expect("function definition");
6336 /* reject abstract declarators in function definition */
6337 sym = type.ref;
6338 while ((sym = sym->next) != NULL)
6339 if (!(sym->v & ~SYM_FIELD))
6340 expect("identifier");
6342 /* XXX: cannot do better now: convert extern line to static inline */
6343 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
6344 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
6346 sym = sym_find(v);
6347 if (sym) {
6348 Sym *ref;
6349 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
6350 goto func_error1;
6352 ref = sym->type.ref;
6353 if (0 == ref->a.func_proto)
6354 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
6356 /* use func_call from prototype if not defined */
6357 if (ref->a.func_call != FUNC_CDECL
6358 && type.ref->a.func_call == FUNC_CDECL)
6359 type.ref->a.func_call = ref->a.func_call;
6361 /* use export from prototype */
6362 if (ref->a.func_export)
6363 type.ref->a.func_export = 1;
6365 /* use static from prototype */
6366 if (sym->type.t & VT_STATIC)
6367 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
6369 /* If the definition has no visibility use the
6370 one from prototype. */
6371 if (! (type.t & VT_VIS_MASK))
6372 type.t |= sym->type.t & VT_VIS_MASK;
6374 if (!is_compatible_types(&sym->type, &type)) {
6375 func_error1:
6376 tcc_error("incompatible types for redefinition of '%s'",
6377 get_tok_str(v, NULL));
6379 type.ref->a.func_proto = 0;
6380 /* if symbol is already defined, then put complete type */
6381 sym->type = type;
6382 } else {
6383 /* put function symbol */
6384 sym = global_identifier_push(v, type.t, 0);
6385 sym->type.ref = type.ref;
6388 /* static inline functions are just recorded as a kind
6389 of macro. Their code will be emitted at the end of
6390 the compilation unit only if they are used */
6391 if ((type.t & (VT_INLINE | VT_STATIC)) ==
6392 (VT_INLINE | VT_STATIC)) {
6393 int block_level;
6394 struct InlineFunc *fn;
6395 const char *filename;
6397 filename = file ? file->filename : "";
6398 fn = tcc_malloc(sizeof *fn + strlen(filename));
6399 strcpy(fn->filename, filename);
6400 fn->sym = sym;
6401 tok_str_new(&fn->func_str);
6403 block_level = 0;
6404 for(;;) {
6405 int t;
6406 if (tok == TOK_EOF)
6407 tcc_error("unexpected end of file");
6408 tok_str_add_tok(&fn->func_str);
6409 t = tok;
6410 next();
6411 if (t == '{') {
6412 block_level++;
6413 } else if (t == '}') {
6414 block_level--;
6415 if (block_level == 0)
6416 break;
6419 tok_str_add(&fn->func_str, -1);
6420 tok_str_add(&fn->func_str, 0);
6421 dynarray_add((void ***)&tcc_state->inline_fns, &tcc_state->nb_inline_fns, fn);
6423 } else {
6424 /* compute text section */
6425 cur_text_section = ad.section;
6426 if (!cur_text_section)
6427 cur_text_section = text_section;
6428 sym->r = VT_SYM | VT_CONST;
6429 gen_function(sym);
6431 break;
6432 } else {
6433 if (btype.t & VT_TYPEDEF) {
6434 /* save typedefed type */
6435 /* XXX: test storage specifiers ? */
6436 sym = sym_push(v, &type, 0, 0);
6437 sym->a = ad.a;
6438 sym->type.t |= VT_TYPEDEF;
6439 } else {
6440 r = 0;
6441 if ((type.t & VT_BTYPE) == VT_FUNC) {
6442 /* external function definition */
6443 /* specific case for func_call attribute */
6444 ad.a.func_proto = 1;
6445 type.ref->a = ad.a;
6446 } else if (!(type.t & VT_ARRAY)) {
6447 /* not lvalue if array */
6448 r |= lvalue_type(type.t);
6450 has_init = (tok == '=');
6451 if (has_init && (type.t & VT_VLA))
6452 tcc_error("Variable length array cannot be initialized");
6453 if ((btype.t & VT_EXTERN) || ((type.t & VT_BTYPE) == VT_FUNC) ||
6454 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
6455 !has_init && l == VT_CONST && type.ref->c < 0)) {
6456 /* external variable or function */
6457 /* NOTE: as GCC, uninitialized global static
6458 arrays of null size are considered as
6459 extern */
6460 sym = external_sym(v, &type, r);
6461 sym->asm_label = ad.asm_label;
6463 if (ad.alias_target) {
6464 Section tsec;
6465 Elf32_Sym *esym;
6466 Sym *alias_target;
6468 alias_target = sym_find(ad.alias_target);
6469 if (!alias_target || !alias_target->c)
6470 tcc_error("unsupported forward __alias__ attribute");
6471 esym = &((Elf32_Sym *)symtab_section->data)[alias_target->c];
6472 tsec.sh_num = esym->st_shndx;
6473 put_extern_sym2(sym, &tsec, esym->st_value, esym->st_size, 0);
6475 } else {
6476 type.t |= (btype.t & VT_STATIC); /* Retain "static". */
6477 if (type.t & VT_STATIC)
6478 r |= VT_CONST;
6479 else
6480 r |= l;
6481 if (has_init)
6482 next();
6483 decl_initializer_alloc(&type, &ad, r, has_init, v, l);
6486 if (tok != ',') {
6487 if (is_for_loop_init)
6488 return 1;
6489 skip(';');
6490 break;
6492 next();
6494 ad.a.aligned = 0;
6497 return 0;
6500 ST_FUNC void decl(int l)
6502 decl0(l, 0);