Redo "fix line number in macro redefined message"
[tinycc.git] / tccgen.c
blob55befb16394c455550e834ce2b43de18ffcfdf2c
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 s->scope = local_scope;
243 if (s->prev_tok && s->prev_tok->scope == s->scope)
244 tcc_error("redeclaration of '%s'",
245 get_tok_str(v & ~SYM_STRUCT, NULL));
247 return s;
250 /* push a global identifier */
251 ST_FUNC Sym *global_identifier_push(int v, int t, int c)
253 Sym *s, **ps;
254 s = sym_push2(&global_stack, v, t, c);
255 /* don't record anonymous symbol */
256 if (v < SYM_FIRST_ANOM) {
257 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
258 /* modify the top most local identifier, so that
259 sym_identifier will point to 's' when popped */
260 while (*ps != NULL)
261 ps = &(*ps)->prev_tok;
262 s->prev_tok = NULL;
263 *ps = s;
265 return s;
268 /* pop symbols until top reaches 'b' */
269 ST_FUNC void sym_pop(Sym **ptop, Sym *b)
271 Sym *s, *ss, **ps;
272 TokenSym *ts;
273 int v;
275 s = *ptop;
276 while(s != b) {
277 ss = s->prev;
278 v = s->v;
279 /* remove symbol in token array */
280 /* XXX: simplify */
281 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
282 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
283 if (v & SYM_STRUCT)
284 ps = &ts->sym_struct;
285 else
286 ps = &ts->sym_identifier;
287 *ps = s->prev_tok;
289 sym_free(s);
290 s = ss;
292 *ptop = b;
295 static void weaken_symbol(Sym *sym)
297 sym->type.t |= VT_WEAK;
298 if (sym->c > 0) {
299 int esym_type;
300 ElfW(Sym) *esym;
302 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
303 esym_type = ELFW(ST_TYPE)(esym->st_info);
304 esym->st_info = ELFW(ST_INFO)(STB_WEAK, esym_type);
308 static void apply_visibility(Sym *sym, CType *type)
310 int vis = sym->type.t & VT_VIS_MASK;
311 int vis2 = type->t & VT_VIS_MASK;
312 if (vis == (STV_DEFAULT << VT_VIS_SHIFT))
313 vis = vis2;
314 else if (vis2 == (STV_DEFAULT << VT_VIS_SHIFT))
316 else
317 vis = (vis < vis2) ? vis : vis2;
318 sym->type.t &= ~VT_VIS_MASK;
319 sym->type.t |= vis;
321 if (sym->c > 0) {
322 ElfW(Sym) *esym;
324 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
325 vis >>= VT_VIS_SHIFT;
326 esym->st_other = (esym->st_other & ~ELFW(ST_VISIBILITY)(-1)) | vis;
330 /* ------------------------------------------------------------------------- */
332 ST_FUNC void swap(int *p, int *q)
334 int t;
335 t = *p;
336 *p = *q;
337 *q = t;
340 static void vsetc(CType *type, int r, CValue *vc)
342 int v;
344 if (vtop >= vstack + (VSTACK_SIZE - 1))
345 tcc_error("memory full (vstack)");
346 /* cannot let cpu flags if other instruction are generated. Also
347 avoid leaving VT_JMP anywhere except on the top of the stack
348 because it would complicate the code generator. */
349 if (vtop >= vstack) {
350 v = vtop->r & VT_VALMASK;
351 if (v == VT_CMP || (v & ~1) == VT_JMP)
352 gv(RC_INT);
354 vtop++;
355 vtop->type = *type;
356 vtop->r = r;
357 vtop->r2 = VT_CONST;
358 vtop->c = *vc;
361 /* push constant of type "type" with useless value */
362 ST_FUNC void vpush(CType *type)
364 CValue cval;
365 vsetc(type, VT_CONST, &cval);
368 /* push integer constant */
369 ST_FUNC void vpushi(int v)
371 CValue cval;
372 cval.i = v;
373 vsetc(&int_type, VT_CONST, &cval);
376 /* push a pointer sized constant */
377 static void vpushs(addr_t v)
379 CValue cval;
380 cval.i = v;
381 vsetc(&size_type, VT_CONST, &cval);
384 /* push arbitrary 64bit constant */
385 ST_FUNC void vpush64(int ty, unsigned long long v)
387 CValue cval;
388 CType ctype;
389 ctype.t = ty;
390 ctype.ref = NULL;
391 cval.i = v;
392 vsetc(&ctype, VT_CONST, &cval);
395 /* push long long constant */
396 static inline void vpushll(long long v)
398 vpush64(VT_LLONG, v);
401 /* push a symbol value of TYPE */
402 static inline void vpushsym(CType *type, Sym *sym)
404 CValue cval;
405 cval.i = 0;
406 vsetc(type, VT_CONST | VT_SYM, &cval);
407 vtop->sym = sym;
410 /* Return a static symbol pointing to a section */
411 ST_FUNC Sym *get_sym_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
413 int v;
414 Sym *sym;
416 v = anon_sym++;
417 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
418 sym->type.ref = type->ref;
419 sym->r = VT_CONST | VT_SYM;
420 put_extern_sym(sym, sec, offset, size);
421 return sym;
424 /* push a reference to a section offset by adding a dummy symbol */
425 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
427 vpushsym(type, get_sym_ref(type, sec, offset, size));
430 /* define a new external reference to a symbol 'v' of type 'u' */
431 ST_FUNC Sym *external_global_sym(int v, CType *type, int r)
433 Sym *s;
435 s = sym_find(v);
436 if (!s) {
437 /* push forward reference */
438 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
439 s->type.ref = type->ref;
440 s->r = r | VT_CONST | VT_SYM;
442 return s;
445 /* define a new external reference to a symbol 'v' */
446 static Sym *external_sym(int v, CType *type, int r)
448 Sym *s;
450 s = sym_find(v);
451 if (!s) {
452 /* push forward reference */
453 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
454 s->type.t |= VT_EXTERN;
455 } else if (s->type.ref == func_old_type.ref) {
456 s->type.ref = type->ref;
457 s->r = r | VT_CONST | VT_SYM;
458 s->type.t |= VT_EXTERN;
459 } else if (!is_compatible_types(&s->type, type)) {
460 tcc_error("incompatible types for redefinition of '%s'",
461 get_tok_str(v, NULL));
463 /* Merge some storage attributes. */
464 if (type->t & VT_WEAK)
465 weaken_symbol(s);
467 if (type->t & VT_VIS_MASK)
468 apply_visibility(s, type);
470 return s;
473 /* push a reference to global symbol v */
474 ST_FUNC void vpush_global_sym(CType *type, int v)
476 vpushsym(type, external_global_sym(v, type, 0));
479 ST_FUNC void vset(CType *type, int r, int v)
481 CValue cval;
483 cval.i = v;
484 vsetc(type, r, &cval);
487 static void vseti(int r, int v)
489 CType type;
490 type.t = VT_INT;
491 type.ref = 0;
492 vset(&type, r, v);
495 ST_FUNC void vswap(void)
497 SValue tmp;
498 /* cannot let cpu flags if other instruction are generated. Also
499 avoid leaving VT_JMP anywhere except on the top of the stack
500 because it would complicate the code generator. */
501 if (vtop >= vstack) {
502 int v = vtop->r & VT_VALMASK;
503 if (v == VT_CMP || (v & ~1) == VT_JMP)
504 gv(RC_INT);
506 tmp = vtop[0];
507 vtop[0] = vtop[-1];
508 vtop[-1] = tmp;
510 /* XXX: +2% overall speed possible with optimized memswap
512 * memswap(&vtop[0], &vtop[1], sizeof *vtop);
516 ST_FUNC void vpushv(SValue *v)
518 if (vtop >= vstack + (VSTACK_SIZE - 1))
519 tcc_error("memory full (vstack)");
520 vtop++;
521 *vtop = *v;
524 static void vdup(void)
526 vpushv(vtop);
529 /* save r to the memory stack, and mark it as being free */
530 ST_FUNC void save_reg(int r)
532 int l, saved, size, align;
533 SValue *p, sv;
534 CType *type;
536 /* modify all stack values */
537 saved = 0;
538 l = 0;
539 for(p=vstack;p<=vtop;p++) {
540 if ((p->r & VT_VALMASK) == r ||
541 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
542 /* must save value on stack if not already done */
543 if (!saved) {
544 /* NOTE: must reload 'r' because r might be equal to r2 */
545 r = p->r & VT_VALMASK;
546 /* store register in the stack */
547 type = &p->type;
548 if ((p->r & VT_LVAL) ||
549 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
550 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
551 type = &char_pointer_type;
552 #else
553 type = &int_type;
554 #endif
555 size = type_size(type, &align);
556 loc = (loc - size) & -align;
557 sv.type.t = type->t;
558 sv.r = VT_LOCAL | VT_LVAL;
559 sv.c.i = loc;
560 store(r, &sv);
561 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
562 /* x86 specific: need to pop fp register ST0 if saved */
563 if (r == TREG_ST0) {
564 o(0xd8dd); /* fstp %st(0) */
566 #endif
567 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
568 /* special long long case */
569 if ((type->t & VT_BTYPE) == VT_LLONG) {
570 sv.c.i += 4;
571 store(p->r2, &sv);
573 #endif
574 l = loc;
575 saved = 1;
577 /* mark that stack entry as being saved on the stack */
578 if (p->r & VT_LVAL) {
579 /* also clear the bounded flag because the
580 relocation address of the function was stored in
581 p->c.i */
582 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
583 } else {
584 p->r = lvalue_type(p->type.t) | VT_LOCAL;
586 p->r2 = VT_CONST;
587 p->c.i = l;
592 #ifdef TCC_TARGET_ARM
593 /* find a register of class 'rc2' with at most one reference on stack.
594 * If none, call get_reg(rc) */
595 ST_FUNC int get_reg_ex(int rc, int rc2)
597 int r;
598 SValue *p;
600 for(r=0;r<NB_REGS;r++) {
601 if (reg_classes[r] & rc2) {
602 int n;
603 n=0;
604 for(p = vstack; p <= vtop; p++) {
605 if ((p->r & VT_VALMASK) == r ||
606 (p->r2 & VT_VALMASK) == r)
607 n++;
609 if (n <= 1)
610 return r;
613 return get_reg(rc);
615 #endif
617 /* find a free register of class 'rc'. If none, save one register */
618 ST_FUNC int get_reg(int rc)
620 int r;
621 SValue *p;
623 /* find a free register */
624 for(r=0;r<NB_REGS;r++) {
625 if (reg_classes[r] & rc) {
626 for(p=vstack;p<=vtop;p++) {
627 if ((p->r & VT_VALMASK) == r ||
628 (p->r2 & VT_VALMASK) == r)
629 goto notfound;
631 return r;
633 notfound: ;
636 /* no register left : free the first one on the stack (VERY
637 IMPORTANT to start from the bottom to ensure that we don't
638 spill registers used in gen_opi()) */
639 for(p=vstack;p<=vtop;p++) {
640 /* look at second register (if long long) */
641 r = p->r2 & VT_VALMASK;
642 if (r < VT_CONST && (reg_classes[r] & rc))
643 goto save_found;
644 r = p->r & VT_VALMASK;
645 if (r < VT_CONST && (reg_classes[r] & rc)) {
646 save_found:
647 save_reg(r);
648 return r;
651 /* Should never comes here */
652 return -1;
655 /* save registers up to (vtop - n) stack entry */
656 ST_FUNC void save_regs(int n)
658 int r;
659 SValue *p, *p1;
660 p1 = vtop - n;
661 for(p = vstack;p <= p1; p++) {
662 r = p->r & VT_VALMASK;
663 if (r < VT_CONST) {
664 save_reg(r);
669 /* move register 's' (of type 't') to 'r', and flush previous value of r to memory
670 if needed */
671 static void move_reg(int r, int s, int t)
673 SValue sv;
675 if (r != s) {
676 save_reg(r);
677 sv.type.t = t;
678 sv.type.ref = NULL;
679 sv.r = s;
680 sv.c.i = 0;
681 load(r, &sv);
685 /* get address of vtop (vtop MUST BE an lvalue) */
686 ST_FUNC void gaddrof(void)
688 if (vtop->r & VT_REF && !nocode_wanted)
689 gv(RC_INT);
690 vtop->r &= ~VT_LVAL;
691 /* tricky: if saved lvalue, then we can go back to lvalue */
692 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
693 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
698 #ifdef CONFIG_TCC_BCHECK
699 /* generate lvalue bound code */
700 static void gbound(void)
702 int lval_type;
703 CType type1;
705 vtop->r &= ~VT_MUSTBOUND;
706 /* if lvalue, then use checking code before dereferencing */
707 if (vtop->r & VT_LVAL) {
708 /* if not VT_BOUNDED value, then make one */
709 if (!(vtop->r & VT_BOUNDED)) {
710 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
711 /* must save type because we must set it to int to get pointer */
712 type1 = vtop->type;
713 vtop->type.t = VT_PTR;
714 gaddrof();
715 vpushi(0);
716 gen_bounded_ptr_add();
717 vtop->r |= lval_type;
718 vtop->type = type1;
720 /* then check for dereferencing */
721 gen_bounded_ptr_deref();
724 #endif
726 /* store vtop a register belonging to class 'rc'. lvalues are
727 converted to values. Cannot be used if cannot be converted to
728 register value (such as structures). */
729 ST_FUNC int gv(int rc)
731 int r, bit_pos, bit_size, size, align, i;
732 int rc2;
734 /* NOTE: get_reg can modify vstack[] */
735 if (vtop->type.t & VT_BITFIELD) {
736 CType type;
737 int bits = 32;
738 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
739 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
740 /* remove bit field info to avoid loops */
741 vtop->type.t &= ~VT_BITFIELD & ((1 << VT_STRUCT_SHIFT) - 1);
742 /* cast to int to propagate signedness in following ops */
743 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
744 type.t = VT_LLONG;
745 bits = 64;
746 } else
747 type.t = VT_INT;
748 if((vtop->type.t & VT_UNSIGNED) ||
749 (vtop->type.t & VT_BTYPE) == VT_BOOL)
750 type.t |= VT_UNSIGNED;
751 gen_cast(&type);
752 /* generate shifts */
753 vpushi(bits - (bit_pos + bit_size));
754 gen_op(TOK_SHL);
755 vpushi(bits - bit_size);
756 /* NOTE: transformed to SHR if unsigned */
757 gen_op(TOK_SAR);
758 r = gv(rc);
759 } else {
760 if (is_float(vtop->type.t) &&
761 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
762 Sym *sym;
763 int *ptr;
764 unsigned long offset;
765 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
766 CValue check;
767 #endif
769 /* XXX: unify with initializers handling ? */
770 /* CPUs usually cannot use float constants, so we store them
771 generically in data segment */
772 size = type_size(&vtop->type, &align);
773 offset = (data_section->data_offset + align - 1) & -align;
774 data_section->data_offset = offset;
775 /* XXX: not portable yet */
776 #if defined(__i386__) || defined(__x86_64__)
777 /* Zero pad x87 tenbyte long doubles */
778 if (size == LDOUBLE_SIZE) {
779 vtop->c.tab[2] &= 0xffff;
780 #if LDOUBLE_SIZE == 16
781 vtop->c.tab[3] = 0;
782 #endif
784 #endif
785 ptr = section_ptr_add(data_section, size);
786 size = size >> 2;
787 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
788 check.d = 1;
789 if(check.tab[0])
790 for(i=0;i<size;i++)
791 ptr[i] = vtop->c.tab[size-1-i];
792 else
793 #endif
794 for(i=0;i<size;i++)
795 ptr[i] = vtop->c.tab[i];
796 sym = get_sym_ref(&vtop->type, data_section, offset, size << 2);
797 vtop->r |= VT_LVAL | VT_SYM;
798 vtop->sym = sym;
799 vtop->c.i = 0;
801 #ifdef CONFIG_TCC_BCHECK
802 if (vtop->r & VT_MUSTBOUND)
803 gbound();
804 #endif
806 r = vtop->r & VT_VALMASK;
807 rc2 = (rc & RC_FLOAT) ? RC_FLOAT : RC_INT;
808 #ifndef TCC_TARGET_ARM64
809 if (rc == RC_IRET)
810 rc2 = RC_LRET;
811 #ifdef TCC_TARGET_X86_64
812 else if (rc == RC_FRET)
813 rc2 = RC_QRET;
814 #endif
815 #endif
817 /* need to reload if:
818 - constant
819 - lvalue (need to dereference pointer)
820 - already a register, but not in the right class */
821 if (r >= VT_CONST
822 || (vtop->r & VT_LVAL)
823 || !(reg_classes[r] & rc)
824 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
825 || ((vtop->type.t & VT_BTYPE) == VT_QLONG && !(reg_classes[vtop->r2] & rc2))
826 || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT && !(reg_classes[vtop->r2] & rc2))
827 #else
828 || ((vtop->type.t & VT_BTYPE) == VT_LLONG && !(reg_classes[vtop->r2] & rc2))
829 #endif
832 r = get_reg(rc);
833 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
834 if (((vtop->type.t & VT_BTYPE) == VT_QLONG) || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT)) {
835 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
836 #else
837 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
838 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
839 unsigned long long ll;
840 #endif
841 int r2, original_type;
842 original_type = vtop->type.t;
843 /* two register type load : expand to two words
844 temporarily */
845 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
846 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
847 /* load constant */
848 ll = vtop->c.i;
849 vtop->c.i = ll; /* first word */
850 load(r, vtop);
851 vtop->r = r; /* save register value */
852 vpushi(ll >> 32); /* second word */
853 } else
854 #endif
855 if (r >= VT_CONST || /* XXX: test to VT_CONST incorrect ? */
856 (vtop->r & VT_LVAL)) {
857 /* We do not want to modifier the long long
858 pointer here, so the safest (and less
859 efficient) is to save all the other registers
860 in the stack. XXX: totally inefficient. */
861 save_regs(1);
862 /* load from memory */
863 vtop->type.t = load_type;
864 load(r, vtop);
865 vdup();
866 vtop[-1].r = r; /* save register value */
867 /* increment pointer to get second word */
868 vtop->type.t = addr_type;
869 gaddrof();
870 vpushi(load_size);
871 gen_op('+');
872 vtop->r |= VT_LVAL;
873 vtop->type.t = load_type;
874 } else {
875 /* move registers */
876 load(r, vtop);
877 vdup();
878 vtop[-1].r = r; /* save register value */
879 vtop->r = vtop[-1].r2;
881 /* Allocate second register. Here we rely on the fact that
882 get_reg() tries first to free r2 of an SValue. */
883 r2 = get_reg(rc2);
884 load(r2, vtop);
885 vpop();
886 /* write second register */
887 vtop->r2 = r2;
888 vtop->type.t = original_type;
889 } else if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
890 int t1, t;
891 /* lvalue of scalar type : need to use lvalue type
892 because of possible cast */
893 t = vtop->type.t;
894 t1 = t;
895 /* compute memory access type */
896 if (vtop->r & VT_REF)
897 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
898 t = VT_PTR;
899 #else
900 t = VT_INT;
901 #endif
902 else if (vtop->r & VT_LVAL_BYTE)
903 t = VT_BYTE;
904 else if (vtop->r & VT_LVAL_SHORT)
905 t = VT_SHORT;
906 if (vtop->r & VT_LVAL_UNSIGNED)
907 t |= VT_UNSIGNED;
908 vtop->type.t = t;
909 load(r, vtop);
910 /* restore wanted type */
911 vtop->type.t = t1;
912 } else {
913 /* one register type load */
914 load(r, vtop);
917 vtop->r = r;
918 #ifdef TCC_TARGET_C67
919 /* uses register pairs for doubles */
920 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
921 vtop->r2 = r+1;
922 #endif
924 return r;
927 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
928 ST_FUNC void gv2(int rc1, int rc2)
930 int v;
932 /* generate more generic register first. But VT_JMP or VT_CMP
933 values must be generated first in all cases to avoid possible
934 reload errors */
935 v = vtop[0].r & VT_VALMASK;
936 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
937 vswap();
938 gv(rc1);
939 vswap();
940 gv(rc2);
941 /* test if reload is needed for first register */
942 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
943 vswap();
944 gv(rc1);
945 vswap();
947 } else {
948 gv(rc2);
949 vswap();
950 gv(rc1);
951 vswap();
952 /* test if reload is needed for first register */
953 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
954 gv(rc2);
959 #ifndef TCC_TARGET_ARM64
960 /* wrapper around RC_FRET to return a register by type */
961 static int rc_fret(int t)
963 #ifdef TCC_TARGET_X86_64
964 if (t == VT_LDOUBLE) {
965 return RC_ST0;
967 #endif
968 return RC_FRET;
970 #endif
972 /* wrapper around REG_FRET to return a register by type */
973 static int reg_fret(int t)
975 #ifdef TCC_TARGET_X86_64
976 if (t == VT_LDOUBLE) {
977 return TREG_ST0;
979 #endif
980 return REG_FRET;
983 /* expand long long on stack in two int registers */
984 static void lexpand(void)
986 int u;
988 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
989 gv(RC_INT);
990 vdup();
991 vtop[0].r = vtop[-1].r2;
992 vtop[0].r2 = VT_CONST;
993 vtop[-1].r2 = VT_CONST;
994 vtop[0].type.t = VT_INT | u;
995 vtop[-1].type.t = VT_INT | u;
998 #ifdef TCC_TARGET_ARM
999 /* expand long long on stack */
1000 ST_FUNC void lexpand_nr(void)
1002 int u,v;
1004 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
1005 vdup();
1006 vtop->r2 = VT_CONST;
1007 vtop->type.t = VT_INT | u;
1008 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
1009 if (v == VT_CONST) {
1010 vtop[-1].c.i = vtop->c.i;
1011 vtop->c.i = vtop->c.i >> 32;
1012 vtop->r = VT_CONST;
1013 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
1014 vtop->c.i += 4;
1015 vtop->r = vtop[-1].r;
1016 } else if (v > VT_CONST) {
1017 vtop--;
1018 lexpand();
1019 } else
1020 vtop->r = vtop[-1].r2;
1021 vtop[-1].r2 = VT_CONST;
1022 vtop[-1].type.t = VT_INT | u;
1024 #endif
1026 /* build a long long from two ints */
1027 static void lbuild(int t)
1029 gv2(RC_INT, RC_INT);
1030 vtop[-1].r2 = vtop[0].r;
1031 vtop[-1].type.t = t;
1032 vpop();
1035 /* rotate n first stack elements to the bottom
1036 I1 ... In -> I2 ... In I1 [top is right]
1038 ST_FUNC void vrotb(int n)
1040 int i;
1041 SValue tmp;
1043 tmp = vtop[-n + 1];
1044 for(i=-n+1;i!=0;i++)
1045 vtop[i] = vtop[i+1];
1046 vtop[0] = tmp;
1049 /* rotate the n elements before entry e towards the top
1050 I1 ... In ... -> In I1 ... I(n-1) ... [top is right]
1052 ST_FUNC void vrote(SValue *e, int n)
1054 int i;
1055 SValue tmp;
1057 tmp = *e;
1058 for(i = 0;i < n - 1; i++)
1059 e[-i] = e[-i - 1];
1060 e[-n + 1] = tmp;
1063 /* rotate n first stack elements to the top
1064 I1 ... In -> In I1 ... I(n-1) [top is right]
1066 ST_FUNC void vrott(int n)
1068 vrote(vtop, n);
1071 /* pop stack value */
1072 ST_FUNC void vpop(void)
1074 int v;
1075 v = vtop->r & VT_VALMASK;
1076 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1077 /* for x86, we need to pop the FP stack */
1078 if (v == TREG_ST0 && !nocode_wanted) {
1079 o(0xd8dd); /* fstp %st(0) */
1080 } else
1081 #endif
1082 if (v == VT_JMP || v == VT_JMPI) {
1083 /* need to put correct jump if && or || without test */
1084 gsym(vtop->c.i);
1086 vtop--;
1089 /* convert stack entry to register and duplicate its value in another
1090 register */
1091 static void gv_dup(void)
1093 int rc, t, r, r1;
1094 SValue sv;
1096 t = vtop->type.t;
1097 if ((t & VT_BTYPE) == VT_LLONG) {
1098 lexpand();
1099 gv_dup();
1100 vswap();
1101 vrotb(3);
1102 gv_dup();
1103 vrotb(4);
1104 /* stack: H L L1 H1 */
1105 lbuild(t);
1106 vrotb(3);
1107 vrotb(3);
1108 vswap();
1109 lbuild(t);
1110 vswap();
1111 } else {
1112 /* duplicate value */
1113 rc = RC_INT;
1114 sv.type.t = VT_INT;
1115 if (is_float(t)) {
1116 rc = RC_FLOAT;
1117 #ifdef TCC_TARGET_X86_64
1118 if ((t & VT_BTYPE) == VT_LDOUBLE) {
1119 rc = RC_ST0;
1121 #endif
1122 sv.type.t = t;
1124 r = gv(rc);
1125 r1 = get_reg(rc);
1126 sv.r = r;
1127 sv.c.i = 0;
1128 load(r1, &sv); /* move r to r1 */
1129 vdup();
1130 /* duplicates value */
1131 if (r != r1)
1132 vtop->r = r1;
1136 /* Generate value test
1138 * Generate a test for any value (jump, comparison and integers) */
1139 ST_FUNC int gvtst(int inv, int t)
1141 int v = vtop->r & VT_VALMASK;
1142 if (v != VT_CMP && v != VT_JMP && v != VT_JMPI) {
1143 vpushi(0);
1144 gen_op(TOK_NE);
1146 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1147 /* constant jmp optimization */
1148 if ((vtop->c.i != 0) != inv)
1149 t = gjmp(t);
1150 vtop--;
1151 return t;
1153 return gtst(inv, t);
1156 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
1157 /* generate CPU independent (unsigned) long long operations */
1158 static void gen_opl(int op)
1160 int t, a, b, op1, c, i;
1161 int func;
1162 unsigned short reg_iret = REG_IRET;
1163 unsigned short reg_lret = REG_LRET;
1164 SValue tmp;
1166 switch(op) {
1167 case '/':
1168 case TOK_PDIV:
1169 func = TOK___divdi3;
1170 goto gen_func;
1171 case TOK_UDIV:
1172 func = TOK___udivdi3;
1173 goto gen_func;
1174 case '%':
1175 func = TOK___moddi3;
1176 goto gen_mod_func;
1177 case TOK_UMOD:
1178 func = TOK___umoddi3;
1179 gen_mod_func:
1180 #ifdef TCC_ARM_EABI
1181 reg_iret = TREG_R2;
1182 reg_lret = TREG_R3;
1183 #endif
1184 gen_func:
1185 /* call generic long long function */
1186 vpush_global_sym(&func_old_type, func);
1187 vrott(3);
1188 gfunc_call(2);
1189 vpushi(0);
1190 vtop->r = reg_iret;
1191 vtop->r2 = reg_lret;
1192 break;
1193 case '^':
1194 case '&':
1195 case '|':
1196 case '*':
1197 case '+':
1198 case '-':
1199 t = vtop->type.t;
1200 vswap();
1201 lexpand();
1202 vrotb(3);
1203 lexpand();
1204 /* stack: L1 H1 L2 H2 */
1205 tmp = vtop[0];
1206 vtop[0] = vtop[-3];
1207 vtop[-3] = tmp;
1208 tmp = vtop[-2];
1209 vtop[-2] = vtop[-3];
1210 vtop[-3] = tmp;
1211 vswap();
1212 /* stack: H1 H2 L1 L2 */
1213 if (op == '*') {
1214 vpushv(vtop - 1);
1215 vpushv(vtop - 1);
1216 gen_op(TOK_UMULL);
1217 lexpand();
1218 /* stack: H1 H2 L1 L2 ML MH */
1219 for(i=0;i<4;i++)
1220 vrotb(6);
1221 /* stack: ML MH H1 H2 L1 L2 */
1222 tmp = vtop[0];
1223 vtop[0] = vtop[-2];
1224 vtop[-2] = tmp;
1225 /* stack: ML MH H1 L2 H2 L1 */
1226 gen_op('*');
1227 vrotb(3);
1228 vrotb(3);
1229 gen_op('*');
1230 /* stack: ML MH M1 M2 */
1231 gen_op('+');
1232 gen_op('+');
1233 } else if (op == '+' || op == '-') {
1234 /* XXX: add non carry method too (for MIPS or alpha) */
1235 if (op == '+')
1236 op1 = TOK_ADDC1;
1237 else
1238 op1 = TOK_SUBC1;
1239 gen_op(op1);
1240 /* stack: H1 H2 (L1 op L2) */
1241 vrotb(3);
1242 vrotb(3);
1243 gen_op(op1 + 1); /* TOK_xxxC2 */
1244 } else {
1245 gen_op(op);
1246 /* stack: H1 H2 (L1 op L2) */
1247 vrotb(3);
1248 vrotb(3);
1249 /* stack: (L1 op L2) H1 H2 */
1250 gen_op(op);
1251 /* stack: (L1 op L2) (H1 op H2) */
1253 /* stack: L H */
1254 lbuild(t);
1255 break;
1256 case TOK_SAR:
1257 case TOK_SHR:
1258 case TOK_SHL:
1259 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1260 t = vtop[-1].type.t;
1261 vswap();
1262 lexpand();
1263 vrotb(3);
1264 /* stack: L H shift */
1265 c = (int)vtop->c.i;
1266 /* constant: simpler */
1267 /* NOTE: all comments are for SHL. the other cases are
1268 done by swaping words */
1269 vpop();
1270 if (op != TOK_SHL)
1271 vswap();
1272 if (c >= 32) {
1273 /* stack: L H */
1274 vpop();
1275 if (c > 32) {
1276 vpushi(c - 32);
1277 gen_op(op);
1279 if (op != TOK_SAR) {
1280 vpushi(0);
1281 } else {
1282 gv_dup();
1283 vpushi(31);
1284 gen_op(TOK_SAR);
1286 vswap();
1287 } else {
1288 vswap();
1289 gv_dup();
1290 /* stack: H L L */
1291 vpushi(c);
1292 gen_op(op);
1293 vswap();
1294 vpushi(32 - c);
1295 if (op == TOK_SHL)
1296 gen_op(TOK_SHR);
1297 else
1298 gen_op(TOK_SHL);
1299 vrotb(3);
1300 /* stack: L L H */
1301 vpushi(c);
1302 if (op == TOK_SHL)
1303 gen_op(TOK_SHL);
1304 else
1305 gen_op(TOK_SHR);
1306 gen_op('|');
1308 if (op != TOK_SHL)
1309 vswap();
1310 lbuild(t);
1311 } else {
1312 /* XXX: should provide a faster fallback on x86 ? */
1313 switch(op) {
1314 case TOK_SAR:
1315 func = TOK___ashrdi3;
1316 goto gen_func;
1317 case TOK_SHR:
1318 func = TOK___lshrdi3;
1319 goto gen_func;
1320 case TOK_SHL:
1321 func = TOK___ashldi3;
1322 goto gen_func;
1325 break;
1326 default:
1327 /* compare operations */
1328 t = vtop->type.t;
1329 vswap();
1330 lexpand();
1331 vrotb(3);
1332 lexpand();
1333 /* stack: L1 H1 L2 H2 */
1334 tmp = vtop[-1];
1335 vtop[-1] = vtop[-2];
1336 vtop[-2] = tmp;
1337 /* stack: L1 L2 H1 H2 */
1338 /* compare high */
1339 op1 = op;
1340 /* when values are equal, we need to compare low words. since
1341 the jump is inverted, we invert the test too. */
1342 if (op1 == TOK_LT)
1343 op1 = TOK_LE;
1344 else if (op1 == TOK_GT)
1345 op1 = TOK_GE;
1346 else if (op1 == TOK_ULT)
1347 op1 = TOK_ULE;
1348 else if (op1 == TOK_UGT)
1349 op1 = TOK_UGE;
1350 a = 0;
1351 b = 0;
1352 gen_op(op1);
1353 if (op1 != TOK_NE) {
1354 a = gvtst(1, 0);
1356 if (op != TOK_EQ) {
1357 /* generate non equal test */
1358 /* XXX: NOT PORTABLE yet */
1359 if (a == 0) {
1360 b = gvtst(0, 0);
1361 } else {
1362 #if defined(TCC_TARGET_I386)
1363 b = psym(0x850f, 0);
1364 #elif defined(TCC_TARGET_ARM)
1365 b = ind;
1366 o(0x1A000000 | encbranch(ind, 0, 1));
1367 #elif defined(TCC_TARGET_C67) || defined(TCC_TARGET_ARM64)
1368 tcc_error("not implemented");
1369 #else
1370 #error not supported
1371 #endif
1374 /* compare low. Always unsigned */
1375 op1 = op;
1376 if (op1 == TOK_LT)
1377 op1 = TOK_ULT;
1378 else if (op1 == TOK_LE)
1379 op1 = TOK_ULE;
1380 else if (op1 == TOK_GT)
1381 op1 = TOK_UGT;
1382 else if (op1 == TOK_GE)
1383 op1 = TOK_UGE;
1384 gen_op(op1);
1385 a = gvtst(1, a);
1386 gsym(b);
1387 vseti(VT_JMPI, a);
1388 break;
1391 #endif
1393 static uint64_t gen_opic_sdiv(uint64_t a, uint64_t b)
1395 uint64_t x = (a >> 63 ? -a : a) / (b >> 63 ? -b : b);
1396 return (a ^ b) >> 63 ? -x : x;
1399 static int gen_opic_lt(uint64_t a, uint64_t b)
1401 return (a ^ (uint64_t)1 << 63) < (b ^ (uint64_t)1 << 63);
1404 /* handle integer constant optimizations and various machine
1405 independent opt */
1406 static void gen_opic(int op)
1408 SValue *v1 = vtop - 1;
1409 SValue *v2 = vtop;
1410 int t1 = v1->type.t & VT_BTYPE;
1411 int t2 = v2->type.t & VT_BTYPE;
1412 int c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1413 int c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1414 uint64_t l1 = c1 ? v1->c.i : 0;
1415 uint64_t l2 = c2 ? v2->c.i : 0;
1416 int shm = (t1 == VT_LLONG) ? 63 : 31;
1418 if (t1 != VT_LLONG)
1419 l1 = ((uint32_t)l1 |
1420 (v1->type.t & VT_UNSIGNED ? 0 : -(l1 & 0x80000000)));
1421 if (t2 != VT_LLONG)
1422 l2 = ((uint32_t)l2 |
1423 (v2->type.t & VT_UNSIGNED ? 0 : -(l2 & 0x80000000)));
1425 if (c1 && c2) {
1426 switch(op) {
1427 case '+': l1 += l2; break;
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;
1434 case TOK_PDIV:
1435 case '/':
1436 case '%':
1437 case TOK_UDIV:
1438 case TOK_UMOD:
1439 /* if division by zero, generate explicit division */
1440 if (l2 == 0) {
1441 if (const_wanted)
1442 tcc_error("division by zero in constant");
1443 goto general_case;
1445 switch(op) {
1446 default: l1 = gen_opic_sdiv(l1, l2); break;
1447 case '%': l1 = l1 - l2 * gen_opic_sdiv(l1, l2); break;
1448 case TOK_UDIV: l1 = l1 / l2; break;
1449 case TOK_UMOD: l1 = l1 % l2; break;
1451 break;
1452 case TOK_SHL: l1 <<= (l2 & shm); break;
1453 case TOK_SHR: l1 >>= (l2 & shm); break;
1454 case TOK_SAR:
1455 l1 = (l1 >> 63) ? ~(~l1 >> (l2 & shm)) : l1 >> (l2 & shm);
1456 break;
1457 /* tests */
1458 case TOK_ULT: l1 = l1 < l2; break;
1459 case TOK_UGE: l1 = l1 >= l2; break;
1460 case TOK_EQ: l1 = l1 == l2; break;
1461 case TOK_NE: l1 = l1 != l2; break;
1462 case TOK_ULE: l1 = l1 <= l2; break;
1463 case TOK_UGT: l1 = l1 > l2; break;
1464 case TOK_LT: l1 = gen_opic_lt(l1, l2); break;
1465 case TOK_GE: l1 = !gen_opic_lt(l1, l2); break;
1466 case TOK_LE: l1 = !gen_opic_lt(l2, l1); break;
1467 case TOK_GT: l1 = gen_opic_lt(l2, l1); break;
1468 /* logical */
1469 case TOK_LAND: l1 = l1 && l2; break;
1470 case TOK_LOR: l1 = l1 || l2; break;
1471 default:
1472 goto general_case;
1474 v1->c.i = l1;
1475 vtop--;
1476 } else {
1477 /* if commutative ops, put c2 as constant */
1478 if (c1 && (op == '+' || op == '&' || op == '^' ||
1479 op == '|' || op == '*')) {
1480 vswap();
1481 c2 = c1; //c = c1, c1 = c2, c2 = c;
1482 l2 = l1; //l = l1, l1 = l2, l2 = l;
1484 if (!const_wanted &&
1485 c1 && ((l1 == 0 &&
1486 (op == TOK_SHL || op == TOK_SHR || op == TOK_SAR)) ||
1487 (l1 == -1 && op == TOK_SAR))) {
1488 /* treat (0 << x), (0 >> x) and (-1 >> x) as constant */
1489 vtop--;
1490 } else if (!const_wanted &&
1491 c2 && ((l2 == 0 && (op == '&' || op == '*')) ||
1492 (l2 == -1 && op == '|') ||
1493 (l2 == 0xffffffff && t2 != VT_LLONG && op == '|') ||
1494 (l2 == 1 && (op == '%' || op == TOK_UMOD)))) {
1495 /* treat (x & 0), (x * 0), (x | -1) and (x % 1) as constant */
1496 if (l2 == 1)
1497 vtop->c.i = 0;
1498 vswap();
1499 vtop--;
1500 } else if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
1501 op == TOK_PDIV) &&
1502 l2 == 1) ||
1503 ((op == '+' || op == '-' || op == '|' || op == '^' ||
1504 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
1505 l2 == 0) ||
1506 (op == '&' &&
1507 l2 == -1))) {
1508 /* filter out NOP operations like x*1, x-0, x&-1... */
1509 vtop--;
1510 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
1511 /* try to use shifts instead of muls or divs */
1512 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
1513 int n = -1;
1514 while (l2) {
1515 l2 >>= 1;
1516 n++;
1518 vtop->c.i = n;
1519 if (op == '*')
1520 op = TOK_SHL;
1521 else if (op == TOK_PDIV)
1522 op = TOK_SAR;
1523 else
1524 op = TOK_SHR;
1526 goto general_case;
1527 } else if (c2 && (op == '+' || op == '-') &&
1528 (((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM))
1529 || (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
1530 /* symbol + constant case */
1531 if (op == '-')
1532 l2 = -l2;
1533 vtop--;
1534 vtop->c.i += l2;
1535 } else {
1536 general_case:
1537 if (!nocode_wanted) {
1538 /* call low level op generator */
1539 if (t1 == VT_LLONG || t2 == VT_LLONG ||
1540 (PTR_SIZE == 8 && (t1 == VT_PTR || t2 == VT_PTR)))
1541 gen_opl(op);
1542 else
1543 gen_opi(op);
1544 } else {
1545 vtop--;
1551 /* generate a floating point operation with constant propagation */
1552 static void gen_opif(int op)
1554 int c1, c2;
1555 SValue *v1, *v2;
1556 long double f1, f2;
1558 v1 = vtop - 1;
1559 v2 = vtop;
1560 /* currently, we cannot do computations with forward symbols */
1561 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1562 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1563 if (c1 && c2) {
1564 if (v1->type.t == VT_FLOAT) {
1565 f1 = v1->c.f;
1566 f2 = v2->c.f;
1567 } else if (v1->type.t == VT_DOUBLE) {
1568 f1 = v1->c.d;
1569 f2 = v2->c.d;
1570 } else {
1571 f1 = v1->c.ld;
1572 f2 = v2->c.ld;
1575 /* NOTE: we only do constant propagation if finite number (not
1576 NaN or infinity) (ANSI spec) */
1577 if (!ieee_finite(f1) || !ieee_finite(f2))
1578 goto general_case;
1580 switch(op) {
1581 case '+': f1 += f2; break;
1582 case '-': f1 -= f2; break;
1583 case '*': f1 *= f2; break;
1584 case '/':
1585 if (f2 == 0.0) {
1586 if (const_wanted)
1587 tcc_error("division by zero in constant");
1588 goto general_case;
1590 f1 /= f2;
1591 break;
1592 /* XXX: also handles tests ? */
1593 default:
1594 goto general_case;
1596 /* XXX: overflow test ? */
1597 if (v1->type.t == VT_FLOAT) {
1598 v1->c.f = f1;
1599 } else if (v1->type.t == VT_DOUBLE) {
1600 v1->c.d = f1;
1601 } else {
1602 v1->c.ld = f1;
1604 vtop--;
1605 } else {
1606 general_case:
1607 if (!nocode_wanted) {
1608 gen_opf(op);
1609 } else {
1610 vtop--;
1615 static int pointed_size(CType *type)
1617 int align;
1618 return type_size(pointed_type(type), &align);
1621 static void vla_runtime_pointed_size(CType *type)
1623 int align;
1624 vla_runtime_type_size(pointed_type(type), &align);
1627 static inline int is_null_pointer(SValue *p)
1629 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
1630 return 0;
1631 return ((p->type.t & VT_BTYPE) == VT_INT && (uint32_t)p->c.i == 0) ||
1632 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.i == 0) ||
1633 ((p->type.t & VT_BTYPE) == VT_PTR &&
1634 (PTR_SIZE == 4 ? (uint32_t)p->c.i == 0 : p->c.i == 0));
1637 static inline int is_integer_btype(int bt)
1639 return (bt == VT_BYTE || bt == VT_SHORT ||
1640 bt == VT_INT || bt == VT_LLONG);
1643 /* check types for comparison or subtraction of pointers */
1644 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
1646 CType *type1, *type2, tmp_type1, tmp_type2;
1647 int bt1, bt2;
1649 /* null pointers are accepted for all comparisons as gcc */
1650 if (is_null_pointer(p1) || is_null_pointer(p2))
1651 return;
1652 type1 = &p1->type;
1653 type2 = &p2->type;
1654 bt1 = type1->t & VT_BTYPE;
1655 bt2 = type2->t & VT_BTYPE;
1656 /* accept comparison between pointer and integer with a warning */
1657 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
1658 if (op != TOK_LOR && op != TOK_LAND )
1659 tcc_warning("comparison between pointer and integer");
1660 return;
1663 /* both must be pointers or implicit function pointers */
1664 if (bt1 == VT_PTR) {
1665 type1 = pointed_type(type1);
1666 } else if (bt1 != VT_FUNC)
1667 goto invalid_operands;
1669 if (bt2 == VT_PTR) {
1670 type2 = pointed_type(type2);
1671 } else if (bt2 != VT_FUNC) {
1672 invalid_operands:
1673 tcc_error("invalid operands to binary %s", get_tok_str(op, NULL));
1675 if ((type1->t & VT_BTYPE) == VT_VOID ||
1676 (type2->t & VT_BTYPE) == VT_VOID)
1677 return;
1678 tmp_type1 = *type1;
1679 tmp_type2 = *type2;
1680 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1681 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1682 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
1683 /* gcc-like error if '-' is used */
1684 if (op == '-')
1685 goto invalid_operands;
1686 else
1687 tcc_warning("comparison of distinct pointer types lacks a cast");
1691 /* generic gen_op: handles types problems */
1692 ST_FUNC void gen_op(int op)
1694 int u, t1, t2, bt1, bt2, t;
1695 CType type1;
1697 t1 = vtop[-1].type.t;
1698 t2 = vtop[0].type.t;
1699 bt1 = t1 & VT_BTYPE;
1700 bt2 = t2 & VT_BTYPE;
1702 if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
1703 tcc_error("operation on a struct");
1704 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
1705 /* at least one operand is a pointer */
1706 /* relationnal op: must be both pointers */
1707 if (op >= TOK_ULT && op <= TOK_LOR) {
1708 check_comparison_pointer_types(vtop - 1, vtop, op);
1709 /* pointers are handled are unsigned */
1710 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1711 t = VT_LLONG | VT_UNSIGNED;
1712 #else
1713 t = VT_INT | VT_UNSIGNED;
1714 #endif
1715 goto std_op;
1717 /* if both pointers, then it must be the '-' op */
1718 if (bt1 == VT_PTR && bt2 == VT_PTR) {
1719 if (op != '-')
1720 tcc_error("cannot use pointers here");
1721 check_comparison_pointer_types(vtop - 1, vtop, op);
1722 /* XXX: check that types are compatible */
1723 if (vtop[-1].type.t & VT_VLA) {
1724 vla_runtime_pointed_size(&vtop[-1].type);
1725 } else {
1726 vpushi(pointed_size(&vtop[-1].type));
1728 vrott(3);
1729 gen_opic(op);
1730 /* set to integer type */
1731 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1732 vtop->type.t = VT_LLONG;
1733 #else
1734 vtop->type.t = VT_INT;
1735 #endif
1736 vswap();
1737 gen_op(TOK_PDIV);
1738 } else {
1739 /* exactly one pointer : must be '+' or '-'. */
1740 if (op != '-' && op != '+')
1741 tcc_error("cannot use pointers here");
1742 /* Put pointer as first operand */
1743 if (bt2 == VT_PTR) {
1744 vswap();
1745 swap(&t1, &t2);
1747 type1 = vtop[-1].type;
1748 type1.t &= ~VT_ARRAY;
1749 if (vtop[-1].type.t & VT_VLA)
1750 vla_runtime_pointed_size(&vtop[-1].type);
1751 else {
1752 u = pointed_size(&vtop[-1].type);
1753 if (u < 0)
1754 tcc_error("unknown array element size");
1755 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1756 vpushll(u);
1757 #else
1758 /* XXX: cast to int ? (long long case) */
1759 vpushi(u);
1760 #endif
1762 gen_op('*');
1763 #if 0
1764 /* #ifdef CONFIG_TCC_BCHECK
1765 The main reason to removing this code:
1766 #include <stdio.h>
1767 int main ()
1769 int v[10];
1770 int i = 10;
1771 int j = 9;
1772 fprintf(stderr, "v+i-j = %p\n", v+i-j);
1773 fprintf(stderr, "v+(i-j) = %p\n", v+(i-j));
1775 When this code is on. then the output looks like
1776 v+i-j = 0xfffffffe
1777 v+(i-j) = 0xbff84000
1779 /* if evaluating constant expression, no code should be
1780 generated, so no bound check */
1781 if (tcc_state->do_bounds_check && !const_wanted) {
1782 /* if bounded pointers, we generate a special code to
1783 test bounds */
1784 if (op == '-') {
1785 vpushi(0);
1786 vswap();
1787 gen_op('-');
1789 gen_bounded_ptr_add();
1790 } else
1791 #endif
1793 gen_opic(op);
1795 /* put again type if gen_opic() swaped operands */
1796 vtop->type = type1;
1798 } else if (is_float(bt1) || is_float(bt2)) {
1799 /* compute bigger type and do implicit casts */
1800 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
1801 t = VT_LDOUBLE;
1802 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
1803 t = VT_DOUBLE;
1804 } else {
1805 t = VT_FLOAT;
1807 /* floats can only be used for a few operations */
1808 if (op != '+' && op != '-' && op != '*' && op != '/' &&
1809 (op < TOK_ULT || op > TOK_GT))
1810 tcc_error("invalid operands for binary operation");
1811 goto std_op;
1812 } else if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL) {
1813 t = bt1 == VT_LLONG ? VT_LLONG : VT_INT;
1814 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (t | VT_UNSIGNED))
1815 t |= VT_UNSIGNED;
1816 goto std_op;
1817 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
1818 /* cast to biggest op */
1819 t = VT_LLONG;
1820 /* convert to unsigned if it does not fit in a long long */
1821 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
1822 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
1823 t |= VT_UNSIGNED;
1824 goto std_op;
1825 } else {
1826 /* integer operations */
1827 t = VT_INT;
1828 /* convert to unsigned if it does not fit in an integer */
1829 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
1830 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
1831 t |= VT_UNSIGNED;
1832 std_op:
1833 /* XXX: currently, some unsigned operations are explicit, so
1834 we modify them here */
1835 if (t & VT_UNSIGNED) {
1836 if (op == TOK_SAR)
1837 op = TOK_SHR;
1838 else if (op == '/')
1839 op = TOK_UDIV;
1840 else if (op == '%')
1841 op = TOK_UMOD;
1842 else if (op == TOK_LT)
1843 op = TOK_ULT;
1844 else if (op == TOK_GT)
1845 op = TOK_UGT;
1846 else if (op == TOK_LE)
1847 op = TOK_ULE;
1848 else if (op == TOK_GE)
1849 op = TOK_UGE;
1851 vswap();
1852 type1.t = t;
1853 gen_cast(&type1);
1854 vswap();
1855 /* special case for shifts and long long: we keep the shift as
1856 an integer */
1857 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
1858 type1.t = VT_INT;
1859 gen_cast(&type1);
1860 if (is_float(t))
1861 gen_opif(op);
1862 else
1863 gen_opic(op);
1864 if (op >= TOK_ULT && op <= TOK_GT) {
1865 /* relationnal op: the result is an int */
1866 vtop->type.t = VT_INT;
1867 } else {
1868 vtop->type.t = t;
1871 // Make sure that we have converted to an rvalue:
1872 if (vtop->r & VT_LVAL && !nocode_wanted)
1873 gv(is_float(vtop->type.t & VT_BTYPE) ? RC_FLOAT : RC_INT);
1876 #ifndef TCC_TARGET_ARM
1877 /* generic itof for unsigned long long case */
1878 static void gen_cvt_itof1(int t)
1880 #ifdef TCC_TARGET_ARM64
1881 gen_cvt_itof(t);
1882 #else
1883 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
1884 (VT_LLONG | VT_UNSIGNED)) {
1886 if (t == VT_FLOAT)
1887 vpush_global_sym(&func_old_type, TOK___floatundisf);
1888 #if LDOUBLE_SIZE != 8
1889 else if (t == VT_LDOUBLE)
1890 vpush_global_sym(&func_old_type, TOK___floatundixf);
1891 #endif
1892 else
1893 vpush_global_sym(&func_old_type, TOK___floatundidf);
1894 vrott(2);
1895 gfunc_call(1);
1896 vpushi(0);
1897 vtop->r = reg_fret(t);
1898 } else {
1899 gen_cvt_itof(t);
1901 #endif
1903 #endif
1905 /* generic ftoi for unsigned long long case */
1906 static void gen_cvt_ftoi1(int t)
1908 #ifdef TCC_TARGET_ARM64
1909 gen_cvt_ftoi(t);
1910 #else
1911 int st;
1913 if (t == (VT_LLONG | VT_UNSIGNED)) {
1914 /* not handled natively */
1915 st = vtop->type.t & VT_BTYPE;
1916 if (st == VT_FLOAT)
1917 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
1918 #if LDOUBLE_SIZE != 8
1919 else if (st == VT_LDOUBLE)
1920 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
1921 #endif
1922 else
1923 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
1924 vrott(2);
1925 gfunc_call(1);
1926 vpushi(0);
1927 vtop->r = REG_IRET;
1928 vtop->r2 = REG_LRET;
1929 } else {
1930 gen_cvt_ftoi(t);
1932 #endif
1935 /* force char or short cast */
1936 static void force_charshort_cast(int t)
1938 int bits, dbt;
1939 dbt = t & VT_BTYPE;
1940 /* XXX: add optimization if lvalue : just change type and offset */
1941 if (dbt == VT_BYTE)
1942 bits = 8;
1943 else
1944 bits = 16;
1945 if (t & VT_UNSIGNED) {
1946 vpushi((1 << bits) - 1);
1947 gen_op('&');
1948 } else {
1949 bits = 32 - bits;
1950 vpushi(bits);
1951 gen_op(TOK_SHL);
1952 /* result must be signed or the SAR is converted to an SHL
1953 This was not the case when "t" was a signed short
1954 and the last value on the stack was an unsigned int */
1955 vtop->type.t &= ~VT_UNSIGNED;
1956 vpushi(bits);
1957 gen_op(TOK_SAR);
1961 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
1962 static void gen_cast(CType *type)
1964 int sbt, dbt, sf, df, c, p;
1966 /* special delayed cast for char/short */
1967 /* XXX: in some cases (multiple cascaded casts), it may still
1968 be incorrect */
1969 if (vtop->r & VT_MUSTCAST) {
1970 vtop->r &= ~VT_MUSTCAST;
1971 force_charshort_cast(vtop->type.t);
1974 /* bitfields first get cast to ints */
1975 if (vtop->type.t & VT_BITFIELD && !nocode_wanted) {
1976 gv(RC_INT);
1979 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
1980 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
1982 if (sbt != dbt) {
1983 sf = is_float(sbt);
1984 df = is_float(dbt);
1985 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1986 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
1987 if (c) {
1988 /* constant case: we can do it now */
1989 /* XXX: in ISOC, cannot do it if error in convert */
1990 if (sbt == VT_FLOAT)
1991 vtop->c.ld = vtop->c.f;
1992 else if (sbt == VT_DOUBLE)
1993 vtop->c.ld = vtop->c.d;
1995 if (df) {
1996 if ((sbt & VT_BTYPE) == VT_LLONG) {
1997 if ((sbt & VT_UNSIGNED) || !(vtop->c.i >> 63))
1998 vtop->c.ld = vtop->c.i;
1999 else
2000 vtop->c.ld = -(long double)-vtop->c.i;
2001 } else if(!sf) {
2002 if ((sbt & VT_UNSIGNED) || !(vtop->c.i >> 31))
2003 vtop->c.ld = (uint32_t)vtop->c.i;
2004 else
2005 vtop->c.ld = -(long double)-(uint32_t)vtop->c.i;
2008 if (dbt == VT_FLOAT)
2009 vtop->c.f = (float)vtop->c.ld;
2010 else if (dbt == VT_DOUBLE)
2011 vtop->c.d = (double)vtop->c.ld;
2012 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
2013 vtop->c.i = vtop->c.ld;
2014 } else if (sf && dbt == VT_BOOL) {
2015 vtop->c.i = (vtop->c.ld != 0);
2016 } else {
2017 if(sf)
2018 vtop->c.i = vtop->c.ld;
2019 else if (sbt == (VT_LLONG|VT_UNSIGNED))
2021 else if (sbt & VT_UNSIGNED)
2022 vtop->c.i = (uint32_t)vtop->c.i;
2023 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2024 else if (sbt == VT_PTR)
2026 #endif
2027 else if (sbt != VT_LLONG)
2028 vtop->c.i = ((uint32_t)vtop->c.i |
2029 -(vtop->c.i & 0x80000000));
2031 if (dbt == (VT_LLONG|VT_UNSIGNED))
2033 else if (dbt == VT_BOOL)
2034 vtop->c.i = (vtop->c.i != 0);
2035 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2036 else if (dbt == VT_PTR)
2038 #endif
2039 else if (dbt != VT_LLONG) {
2040 uint32_t m = ((dbt & VT_BTYPE) == VT_BYTE ? 0xff :
2041 (dbt & VT_BTYPE) == VT_SHORT ? 0xffff :
2042 0xffffffff);
2043 vtop->c.i &= m;
2044 if (!(dbt & VT_UNSIGNED))
2045 vtop->c.i |= -(vtop->c.i & ((m >> 1) + 1));
2048 } else if (p && dbt == VT_BOOL) {
2049 vtop->r = VT_CONST;
2050 vtop->c.i = 1;
2051 } else if (!nocode_wanted) {
2052 /* non constant case: generate code */
2053 if (sf && df) {
2054 /* convert from fp to fp */
2055 gen_cvt_ftof(dbt);
2056 } else if (df) {
2057 /* convert int to fp */
2058 gen_cvt_itof1(dbt);
2059 } else if (sf) {
2060 /* convert fp to int */
2061 if (dbt == VT_BOOL) {
2062 vpushi(0);
2063 gen_op(TOK_NE);
2064 } else {
2065 /* we handle char/short/etc... with generic code */
2066 if (dbt != (VT_INT | VT_UNSIGNED) &&
2067 dbt != (VT_LLONG | VT_UNSIGNED) &&
2068 dbt != VT_LLONG)
2069 dbt = VT_INT;
2070 gen_cvt_ftoi1(dbt);
2071 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
2072 /* additional cast for char/short... */
2073 vtop->type.t = dbt;
2074 gen_cast(type);
2077 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
2078 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
2079 if ((sbt & VT_BTYPE) != VT_LLONG && !nocode_wanted) {
2080 /* scalar to long long */
2081 /* machine independent conversion */
2082 gv(RC_INT);
2083 /* generate high word */
2084 if (sbt == (VT_INT | VT_UNSIGNED)) {
2085 vpushi(0);
2086 gv(RC_INT);
2087 } else {
2088 if (sbt == VT_PTR) {
2089 /* cast from pointer to int before we apply
2090 shift operation, which pointers don't support*/
2091 gen_cast(&int_type);
2093 gv_dup();
2094 vpushi(31);
2095 gen_op(TOK_SAR);
2097 /* patch second register */
2098 vtop[-1].r2 = vtop->r;
2099 vpop();
2101 #else
2102 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
2103 (dbt & VT_BTYPE) == VT_PTR ||
2104 (dbt & VT_BTYPE) == VT_FUNC) {
2105 if ((sbt & VT_BTYPE) != VT_LLONG &&
2106 (sbt & VT_BTYPE) != VT_PTR &&
2107 (sbt & VT_BTYPE) != VT_FUNC && !nocode_wanted) {
2108 /* need to convert from 32bit to 64bit */
2109 gv(RC_INT);
2110 if (sbt != (VT_INT | VT_UNSIGNED)) {
2111 #if defined(TCC_TARGET_ARM64)
2112 gen_cvt_sxtw();
2113 #elif defined(TCC_TARGET_X86_64)
2114 int r = gv(RC_INT);
2115 /* x86_64 specific: movslq */
2116 o(0x6348);
2117 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
2118 #else
2119 #error
2120 #endif
2123 #endif
2124 } else if (dbt == VT_BOOL) {
2125 /* scalar to bool */
2126 vpushi(0);
2127 gen_op(TOK_NE);
2128 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
2129 (dbt & VT_BTYPE) == VT_SHORT) {
2130 if (sbt == VT_PTR) {
2131 vtop->type.t = VT_INT;
2132 tcc_warning("nonportable conversion from pointer to char/short");
2134 force_charshort_cast(dbt);
2135 } else if ((dbt & VT_BTYPE) == VT_INT) {
2136 /* scalar to int */
2137 if (sbt == VT_LLONG && !nocode_wanted) {
2138 /* from long long: just take low order word */
2139 lexpand();
2140 vpop();
2142 /* if lvalue and single word type, nothing to do because
2143 the lvalue already contains the real type size (see
2144 VT_LVAL_xxx constants) */
2147 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
2148 /* if we are casting between pointer types,
2149 we must update the VT_LVAL_xxx size */
2150 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
2151 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
2153 vtop->type = *type;
2156 /* return type size as known at compile time. Put alignment at 'a' */
2157 ST_FUNC int type_size(CType *type, int *a)
2159 Sym *s;
2160 int bt;
2162 bt = type->t & VT_BTYPE;
2163 if (bt == VT_STRUCT) {
2164 /* struct/union */
2165 s = type->ref;
2166 *a = s->r;
2167 return s->c;
2168 } else if (bt == VT_PTR) {
2169 if (type->t & VT_ARRAY) {
2170 int ts;
2172 s = type->ref;
2173 ts = type_size(&s->type, a);
2175 if (ts < 0 && s->c < 0)
2176 ts = -ts;
2178 return ts * s->c;
2179 } else {
2180 *a = PTR_SIZE;
2181 return PTR_SIZE;
2183 } else if (bt == VT_LDOUBLE) {
2184 *a = LDOUBLE_ALIGN;
2185 return LDOUBLE_SIZE;
2186 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
2187 #ifdef TCC_TARGET_I386
2188 #ifdef TCC_TARGET_PE
2189 *a = 8;
2190 #else
2191 *a = 4;
2192 #endif
2193 #elif defined(TCC_TARGET_ARM)
2194 #ifdef TCC_ARM_EABI
2195 *a = 8;
2196 #else
2197 *a = 4;
2198 #endif
2199 #else
2200 *a = 8;
2201 #endif
2202 return 8;
2203 } else if (bt == VT_INT || bt == VT_FLOAT) {
2204 *a = 4;
2205 return 4;
2206 } else if (bt == VT_SHORT) {
2207 *a = 2;
2208 return 2;
2209 } else if (bt == VT_QLONG || bt == VT_QFLOAT) {
2210 *a = 8;
2211 return 16;
2212 } else if (bt == VT_ENUM) {
2213 *a = 4;
2214 /* Enums might be incomplete, so don't just return '4' here. */
2215 return type->ref->c;
2216 } else {
2217 /* char, void, function, _Bool */
2218 *a = 1;
2219 return 1;
2223 /* push type size as known at runtime time on top of value stack. Put
2224 alignment at 'a' */
2225 ST_FUNC void vla_runtime_type_size(CType *type, int *a)
2227 if (type->t & VT_VLA) {
2228 vset(&int_type, VT_LOCAL|VT_LVAL, type->ref->c);
2229 } else {
2230 vpushi(type_size(type, a));
2234 static void vla_sp_restore(void) {
2235 if (vlas_in_scope) {
2236 gen_vla_sp_restore(vla_sp_loc);
2240 static void vla_sp_restore_root(void) {
2241 if (vlas_in_scope) {
2242 gen_vla_sp_restore(vla_sp_root_loc);
2246 /* return the pointed type of t */
2247 static inline CType *pointed_type(CType *type)
2249 return &type->ref->type;
2252 /* modify type so that its it is a pointer to type. */
2253 ST_FUNC void mk_pointer(CType *type)
2255 Sym *s;
2256 s = sym_push(SYM_FIELD, type, 0, -1);
2257 type->t = VT_PTR | (type->t & ~VT_TYPE);
2258 type->ref = s;
2261 /* compare function types. OLD functions match any new functions */
2262 static int is_compatible_func(CType *type1, CType *type2)
2264 Sym *s1, *s2;
2266 s1 = type1->ref;
2267 s2 = type2->ref;
2268 if (!is_compatible_types(&s1->type, &s2->type))
2269 return 0;
2270 /* check func_call */
2271 if (s1->a.func_call != s2->a.func_call)
2272 return 0;
2273 /* XXX: not complete */
2274 if (s1->c == FUNC_OLD || s2->c == FUNC_OLD)
2275 return 1;
2276 if (s1->c != s2->c)
2277 return 0;
2278 while (s1 != NULL) {
2279 if (s2 == NULL)
2280 return 0;
2281 if (!is_compatible_parameter_types(&s1->type, &s2->type))
2282 return 0;
2283 s1 = s1->next;
2284 s2 = s2->next;
2286 if (s2)
2287 return 0;
2288 return 1;
2291 /* return true if type1 and type2 are the same. If unqualified is
2292 true, qualifiers on the types are ignored.
2294 - enums are not checked as gcc __builtin_types_compatible_p ()
2296 static int compare_types(CType *type1, CType *type2, int unqualified)
2298 int bt1, t1, t2;
2300 t1 = type1->t & VT_TYPE;
2301 t2 = type2->t & VT_TYPE;
2302 if (unqualified) {
2303 /* strip qualifiers before comparing */
2304 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
2305 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
2307 /* Default Vs explicit signedness only matters for char */
2308 if ((t1 & VT_BTYPE) != VT_BYTE) {
2309 t1 &= ~VT_DEFSIGN;
2310 t2 &= ~VT_DEFSIGN;
2312 /* XXX: bitfields ? */
2313 if (t1 != t2)
2314 return 0;
2315 /* test more complicated cases */
2316 bt1 = t1 & VT_BTYPE;
2317 if (bt1 == VT_PTR) {
2318 type1 = pointed_type(type1);
2319 type2 = pointed_type(type2);
2320 return is_compatible_types(type1, type2);
2321 } else if (bt1 == VT_STRUCT) {
2322 return (type1->ref == type2->ref);
2323 } else if (bt1 == VT_FUNC) {
2324 return is_compatible_func(type1, type2);
2325 } else {
2326 return 1;
2330 /* return true if type1 and type2 are exactly the same (including
2331 qualifiers).
2333 static int is_compatible_types(CType *type1, CType *type2)
2335 return compare_types(type1,type2,0);
2338 /* return true if type1 and type2 are the same (ignoring qualifiers).
2340 static int is_compatible_parameter_types(CType *type1, CType *type2)
2342 return compare_types(type1,type2,1);
2345 /* print a type. If 'varstr' is not NULL, then the variable is also
2346 printed in the type */
2347 /* XXX: union */
2348 /* XXX: add array and function pointers */
2349 static void type_to_str(char *buf, int buf_size,
2350 CType *type, const char *varstr)
2352 int bt, v, t;
2353 Sym *s, *sa;
2354 char buf1[256];
2355 const char *tstr;
2357 t = type->t & VT_TYPE;
2358 bt = t & VT_BTYPE;
2359 buf[0] = '\0';
2360 if (t & VT_CONSTANT)
2361 pstrcat(buf, buf_size, "const ");
2362 if (t & VT_VOLATILE)
2363 pstrcat(buf, buf_size, "volatile ");
2364 if ((t & (VT_DEFSIGN | VT_UNSIGNED)) == (VT_DEFSIGN | VT_UNSIGNED))
2365 pstrcat(buf, buf_size, "unsigned ");
2366 else if (t & VT_DEFSIGN)
2367 pstrcat(buf, buf_size, "signed ");
2368 switch(bt) {
2369 case VT_VOID:
2370 tstr = "void";
2371 goto add_tstr;
2372 case VT_BOOL:
2373 tstr = "_Bool";
2374 goto add_tstr;
2375 case VT_BYTE:
2376 tstr = "char";
2377 goto add_tstr;
2378 case VT_SHORT:
2379 tstr = "short";
2380 goto add_tstr;
2381 case VT_INT:
2382 tstr = "int";
2383 goto add_tstr;
2384 case VT_LONG:
2385 tstr = "long";
2386 goto add_tstr;
2387 case VT_LLONG:
2388 tstr = "long long";
2389 goto add_tstr;
2390 case VT_FLOAT:
2391 tstr = "float";
2392 goto add_tstr;
2393 case VT_DOUBLE:
2394 tstr = "double";
2395 goto add_tstr;
2396 case VT_LDOUBLE:
2397 tstr = "long double";
2398 add_tstr:
2399 pstrcat(buf, buf_size, tstr);
2400 break;
2401 case VT_ENUM:
2402 case VT_STRUCT:
2403 if (bt == VT_STRUCT)
2404 tstr = "struct ";
2405 else
2406 tstr = "enum ";
2407 pstrcat(buf, buf_size, tstr);
2408 v = type->ref->v & ~SYM_STRUCT;
2409 if (v >= SYM_FIRST_ANOM)
2410 pstrcat(buf, buf_size, "<anonymous>");
2411 else
2412 pstrcat(buf, buf_size, get_tok_str(v, NULL));
2413 break;
2414 case VT_FUNC:
2415 s = type->ref;
2416 type_to_str(buf, buf_size, &s->type, varstr);
2417 pstrcat(buf, buf_size, "(");
2418 sa = s->next;
2419 while (sa != NULL) {
2420 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
2421 pstrcat(buf, buf_size, buf1);
2422 sa = sa->next;
2423 if (sa)
2424 pstrcat(buf, buf_size, ", ");
2426 pstrcat(buf, buf_size, ")");
2427 goto no_var;
2428 case VT_PTR:
2429 s = type->ref;
2430 if (t & VT_ARRAY) {
2431 snprintf(buf1, sizeof(buf1), "%s[%ld]", varstr ? varstr : "", s->c);
2432 type_to_str(buf, buf_size, &s->type, buf1);
2433 goto no_var;
2435 pstrcpy(buf1, sizeof(buf1), "*");
2436 if (t & VT_CONSTANT)
2437 pstrcat(buf1, buf_size, "const ");
2438 if (t & VT_VOLATILE)
2439 pstrcat(buf1, buf_size, "volatile ");
2440 if (varstr)
2441 pstrcat(buf1, sizeof(buf1), varstr);
2442 type_to_str(buf, buf_size, &s->type, buf1);
2443 goto no_var;
2445 if (varstr) {
2446 pstrcat(buf, buf_size, " ");
2447 pstrcat(buf, buf_size, varstr);
2449 no_var: ;
2452 /* verify type compatibility to store vtop in 'dt' type, and generate
2453 casts if needed. */
2454 static void gen_assign_cast(CType *dt)
2456 CType *st, *type1, *type2, tmp_type1, tmp_type2;
2457 char buf1[256], buf2[256];
2458 int dbt, sbt;
2460 st = &vtop->type; /* source type */
2461 dbt = dt->t & VT_BTYPE;
2462 sbt = st->t & VT_BTYPE;
2463 if (sbt == VT_VOID || dbt == VT_VOID) {
2464 if (sbt == VT_VOID && dbt == VT_VOID)
2465 ; /*
2466 It is Ok if both are void
2467 A test program:
2468 void func1() {}
2469 void func2() {
2470 return func1();
2472 gcc accepts this program
2474 else
2475 tcc_error("cannot cast from/to void");
2477 if (dt->t & VT_CONSTANT)
2478 tcc_warning("assignment of read-only location");
2479 switch(dbt) {
2480 case VT_PTR:
2481 /* special cases for pointers */
2482 /* '0' can also be a pointer */
2483 if (is_null_pointer(vtop))
2484 goto type_ok;
2485 /* accept implicit pointer to integer cast with warning */
2486 if (is_integer_btype(sbt)) {
2487 tcc_warning("assignment makes pointer from integer without a cast");
2488 goto type_ok;
2490 type1 = pointed_type(dt);
2491 /* a function is implicitely a function pointer */
2492 if (sbt == VT_FUNC) {
2493 if ((type1->t & VT_BTYPE) != VT_VOID &&
2494 !is_compatible_types(pointed_type(dt), st))
2495 tcc_warning("assignment from incompatible pointer type");
2496 goto type_ok;
2498 if (sbt != VT_PTR)
2499 goto error;
2500 type2 = pointed_type(st);
2501 if ((type1->t & VT_BTYPE) == VT_VOID ||
2502 (type2->t & VT_BTYPE) == VT_VOID) {
2503 /* void * can match anything */
2504 } else {
2505 /* exact type match, except for unsigned */
2506 tmp_type1 = *type1;
2507 tmp_type2 = *type2;
2508 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT |
2509 VT_VOLATILE);
2510 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT |
2511 VT_VOLATILE);
2512 if (!is_compatible_types(&tmp_type1, &tmp_type2))
2513 tcc_warning("assignment from incompatible pointer type");
2515 /* check const and volatile */
2516 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
2517 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
2518 tcc_warning("assignment discards qualifiers from pointer target type");
2519 break;
2520 case VT_BYTE:
2521 case VT_SHORT:
2522 case VT_INT:
2523 case VT_LLONG:
2524 if (sbt == VT_PTR || sbt == VT_FUNC) {
2525 tcc_warning("assignment makes integer from pointer without a cast");
2527 /* XXX: more tests */
2528 break;
2529 case VT_STRUCT:
2530 tmp_type1 = *dt;
2531 tmp_type2 = *st;
2532 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2533 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2534 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2535 error:
2536 type_to_str(buf1, sizeof(buf1), st, NULL);
2537 type_to_str(buf2, sizeof(buf2), dt, NULL);
2538 tcc_error("cannot cast '%s' to '%s'", buf1, buf2);
2540 break;
2542 type_ok:
2543 gen_cast(dt);
2546 /* store vtop in lvalue pushed on stack */
2547 ST_FUNC void vstore(void)
2549 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
2551 ft = vtop[-1].type.t;
2552 sbt = vtop->type.t & VT_BTYPE;
2553 dbt = ft & VT_BTYPE;
2554 if ((((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
2555 (sbt == VT_INT && dbt == VT_SHORT))
2556 && !(vtop->type.t & VT_BITFIELD)) {
2557 /* optimize char/short casts */
2558 delayed_cast = VT_MUSTCAST;
2559 vtop->type.t = (ft & VT_TYPE & ~VT_BITFIELD &
2560 ((1 << VT_STRUCT_SHIFT) - 1));
2561 /* XXX: factorize */
2562 if (ft & VT_CONSTANT)
2563 tcc_warning("assignment of read-only location");
2564 } else {
2565 delayed_cast = 0;
2566 if (!(ft & VT_BITFIELD))
2567 gen_assign_cast(&vtop[-1].type);
2570 if (sbt == VT_STRUCT) {
2571 /* if structure, only generate pointer */
2572 /* structure assignment : generate memcpy */
2573 /* XXX: optimize if small size */
2574 if (!nocode_wanted) {
2575 size = type_size(&vtop->type, &align);
2577 /* destination */
2578 vswap();
2579 vtop->type.t = VT_PTR;
2580 gaddrof();
2582 /* address of memcpy() */
2583 #ifdef TCC_ARM_EABI
2584 if(!(align & 7))
2585 vpush_global_sym(&func_old_type, TOK_memcpy8);
2586 else if(!(align & 3))
2587 vpush_global_sym(&func_old_type, TOK_memcpy4);
2588 else
2589 #endif
2590 /* Use memmove, rather than memcpy, as dest and src may be same: */
2591 vpush_global_sym(&func_old_type, TOK_memmove);
2593 vswap();
2594 /* source */
2595 vpushv(vtop - 2);
2596 vtop->type.t = VT_PTR;
2597 gaddrof();
2598 /* type size */
2599 vpushi(size);
2600 gfunc_call(3);
2601 } else {
2602 vswap();
2603 vpop();
2605 /* leave source on stack */
2606 } else if (ft & VT_BITFIELD) {
2607 /* bitfield store handling */
2609 /* save lvalue as expression result (example: s.b = s.a = n;) */
2610 vdup(), vtop[-1] = vtop[-2];
2612 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
2613 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
2614 /* remove bit field info to avoid loops */
2615 vtop[-1].type.t = ft & ~VT_BITFIELD & ((1 << VT_STRUCT_SHIFT) - 1);
2617 if((ft & VT_BTYPE) == VT_BOOL) {
2618 gen_cast(&vtop[-1].type);
2619 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
2622 /* duplicate destination */
2623 vdup();
2624 vtop[-1] = vtop[-2];
2626 /* mask and shift source */
2627 if((ft & VT_BTYPE) != VT_BOOL) {
2628 if((ft & VT_BTYPE) == VT_LLONG) {
2629 vpushll((1ULL << bit_size) - 1ULL);
2630 } else {
2631 vpushi((1 << bit_size) - 1);
2633 gen_op('&');
2635 vpushi(bit_pos);
2636 gen_op(TOK_SHL);
2637 /* load destination, mask and or with source */
2638 vswap();
2639 if((ft & VT_BTYPE) == VT_LLONG) {
2640 vpushll(~(((1ULL << bit_size) - 1ULL) << bit_pos));
2641 } else {
2642 vpushi(~(((1 << bit_size) - 1) << bit_pos));
2644 gen_op('&');
2645 gen_op('|');
2646 /* store result */
2647 vstore();
2648 /* ... and discard */
2649 vpop();
2651 } else {
2652 if (!nocode_wanted) {
2653 #ifdef CONFIG_TCC_BCHECK
2654 /* bound check case */
2655 if (vtop[-1].r & VT_MUSTBOUND) {
2656 vswap();
2657 gbound();
2658 vswap();
2660 #endif
2661 rc = RC_INT;
2662 if (is_float(ft)) {
2663 rc = RC_FLOAT;
2664 #ifdef TCC_TARGET_X86_64
2665 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
2666 rc = RC_ST0;
2667 } else if ((ft & VT_BTYPE) == VT_QFLOAT) {
2668 rc = RC_FRET;
2670 #endif
2672 r = gv(rc); /* generate value */
2673 /* if lvalue was saved on stack, must read it */
2674 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
2675 SValue sv;
2676 t = get_reg(RC_INT);
2677 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2678 sv.type.t = VT_PTR;
2679 #else
2680 sv.type.t = VT_INT;
2681 #endif
2682 sv.r = VT_LOCAL | VT_LVAL;
2683 sv.c.i = vtop[-1].c.i;
2684 load(t, &sv);
2685 vtop[-1].r = t | VT_LVAL;
2687 /* two word case handling : store second register at word + 4 (or +8 for x86-64) */
2688 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2689 if (((ft & VT_BTYPE) == VT_QLONG) || ((ft & VT_BTYPE) == VT_QFLOAT)) {
2690 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
2691 #else
2692 if ((ft & VT_BTYPE) == VT_LLONG) {
2693 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
2694 #endif
2695 vtop[-1].type.t = load_type;
2696 store(r, vtop - 1);
2697 vswap();
2698 /* convert to int to increment easily */
2699 vtop->type.t = addr_type;
2700 gaddrof();
2701 vpushi(load_size);
2702 gen_op('+');
2703 vtop->r |= VT_LVAL;
2704 vswap();
2705 vtop[-1].type.t = load_type;
2706 /* XXX: it works because r2 is spilled last ! */
2707 store(vtop->r2, vtop - 1);
2708 } else {
2709 store(r, vtop - 1);
2712 vswap();
2713 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
2714 vtop->r |= delayed_cast;
2718 /* post defines POST/PRE add. c is the token ++ or -- */
2719 ST_FUNC void inc(int post, int c)
2721 test_lvalue();
2722 vdup(); /* save lvalue */
2723 if (post) {
2724 if (!nocode_wanted)
2725 gv_dup(); /* duplicate value */
2726 else
2727 vdup(); /* duplicate value */
2728 vrotb(3);
2729 vrotb(3);
2731 /* add constant */
2732 vpushi(c - TOK_MID);
2733 gen_op('+');
2734 vstore(); /* store value */
2735 if (post)
2736 vpop(); /* if post op, return saved value */
2739 /* Parse GNUC __attribute__ extension. Currently, the following
2740 extensions are recognized:
2741 - aligned(n) : set data/function alignment.
2742 - packed : force data alignment to 1
2743 - section(x) : generate data/code in this section.
2744 - unused : currently ignored, but may be used someday.
2745 - regparm(n) : pass function parameters in registers (i386 only)
2747 static void parse_attribute(AttributeDef *ad)
2749 int t, n;
2751 while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
2752 next();
2753 skip('(');
2754 skip('(');
2755 while (tok != ')') {
2756 if (tok < TOK_IDENT)
2757 expect("attribute name");
2758 t = tok;
2759 next();
2760 switch(t) {
2761 case TOK_SECTION1:
2762 case TOK_SECTION2:
2763 skip('(');
2764 if (tok != TOK_STR)
2765 expect("section name");
2766 ad->section = find_section(tcc_state, (char *)tokc.str.data);
2767 next();
2768 skip(')');
2769 break;
2770 case TOK_ALIAS1:
2771 case TOK_ALIAS2:
2772 skip('(');
2773 if (tok != TOK_STR)
2774 expect("alias(\"target\")");
2775 ad->alias_target = /* save string as token, for later */
2776 tok_alloc((char*)tokc.str.data, tokc.str.size-1)->tok;
2777 next();
2778 skip(')');
2779 break;
2780 case TOK_VISIBILITY1:
2781 case TOK_VISIBILITY2:
2782 skip('(');
2783 if (tok != TOK_STR)
2784 expect("visibility(\"default|hidden|internal|protected\")");
2785 if (!strcmp (tokc.str.data, "default"))
2786 ad->a.visibility = STV_DEFAULT;
2787 else if (!strcmp (tokc.str.data, "hidden"))
2788 ad->a.visibility = STV_HIDDEN;
2789 else if (!strcmp (tokc.str.data, "internal"))
2790 ad->a.visibility = STV_INTERNAL;
2791 else if (!strcmp (tokc.str.data, "protected"))
2792 ad->a.visibility = STV_PROTECTED;
2793 else
2794 expect("visibility(\"default|hidden|internal|protected\")");
2795 next();
2796 skip(')');
2797 break;
2798 case TOK_ALIGNED1:
2799 case TOK_ALIGNED2:
2800 if (tok == '(') {
2801 next();
2802 n = expr_const();
2803 if (n <= 0 || (n & (n - 1)) != 0)
2804 tcc_error("alignment must be a positive power of two");
2805 skip(')');
2806 } else {
2807 n = MAX_ALIGN;
2809 ad->a.aligned = n;
2810 break;
2811 case TOK_PACKED1:
2812 case TOK_PACKED2:
2813 ad->a.packed = 1;
2814 break;
2815 case TOK_WEAK1:
2816 case TOK_WEAK2:
2817 ad->a.weak = 1;
2818 break;
2819 case TOK_UNUSED1:
2820 case TOK_UNUSED2:
2821 /* currently, no need to handle it because tcc does not
2822 track unused objects */
2823 break;
2824 case TOK_NORETURN1:
2825 case TOK_NORETURN2:
2826 /* currently, no need to handle it because tcc does not
2827 track unused objects */
2828 break;
2829 case TOK_CDECL1:
2830 case TOK_CDECL2:
2831 case TOK_CDECL3:
2832 ad->a.func_call = FUNC_CDECL;
2833 break;
2834 case TOK_STDCALL1:
2835 case TOK_STDCALL2:
2836 case TOK_STDCALL3:
2837 ad->a.func_call = FUNC_STDCALL;
2838 break;
2839 #ifdef TCC_TARGET_I386
2840 case TOK_REGPARM1:
2841 case TOK_REGPARM2:
2842 skip('(');
2843 n = expr_const();
2844 if (n > 3)
2845 n = 3;
2846 else if (n < 0)
2847 n = 0;
2848 if (n > 0)
2849 ad->a.func_call = FUNC_FASTCALL1 + n - 1;
2850 skip(')');
2851 break;
2852 case TOK_FASTCALL1:
2853 case TOK_FASTCALL2:
2854 case TOK_FASTCALL3:
2855 ad->a.func_call = FUNC_FASTCALLW;
2856 break;
2857 #endif
2858 case TOK_MODE:
2859 skip('(');
2860 switch(tok) {
2861 case TOK_MODE_DI:
2862 ad->a.mode = VT_LLONG + 1;
2863 break;
2864 case TOK_MODE_HI:
2865 ad->a.mode = VT_SHORT + 1;
2866 break;
2867 case TOK_MODE_SI:
2868 ad->a.mode = VT_INT + 1;
2869 break;
2870 default:
2871 tcc_warning("__mode__(%s) not supported\n", get_tok_str(tok, NULL));
2872 break;
2874 next();
2875 skip(')');
2876 break;
2877 case TOK_DLLEXPORT:
2878 ad->a.func_export = 1;
2879 break;
2880 case TOK_DLLIMPORT:
2881 ad->a.func_import = 1;
2882 break;
2883 default:
2884 if (tcc_state->warn_unsupported)
2885 tcc_warning("'%s' attribute ignored", get_tok_str(t, NULL));
2886 /* skip parameters */
2887 if (tok == '(') {
2888 int parenthesis = 0;
2889 do {
2890 if (tok == '(')
2891 parenthesis++;
2892 else if (tok == ')')
2893 parenthesis--;
2894 next();
2895 } while (parenthesis && tok != -1);
2897 break;
2899 if (tok != ',')
2900 break;
2901 next();
2903 skip(')');
2904 skip(')');
2908 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
2909 static void struct_decl(CType *type, AttributeDef *ad, int u)
2911 int a, v, size, align, maxalign, c, offset, flexible;
2912 int bit_size, bit_pos, bsize, bt, lbit_pos, prevbt;
2913 Sym *s, *ss, *ass, **ps;
2914 AttributeDef ad1;
2915 CType type1, btype;
2917 a = tok; /* save decl type */
2918 next();
2919 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
2920 parse_attribute(ad);
2921 next();
2923 if (tok != '{') {
2924 v = tok;
2925 next();
2926 /* struct already defined ? return it */
2927 if (v < TOK_IDENT)
2928 expect("struct/union/enum name");
2929 s = struct_find(v);
2930 if (s && (s->scope == local_scope || (tok != '{' && tok != ';'))) {
2931 if (s->type.t != a)
2932 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
2933 goto do_decl;
2935 } else {
2936 v = anon_sym++;
2938 type1.t = a;
2939 type1.ref = NULL;
2940 /* we put an undefined size for struct/union */
2941 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
2942 s->r = 0; /* default alignment is zero as gcc */
2943 /* put struct/union/enum name in type */
2944 do_decl:
2945 type->t = u;
2946 type->ref = s;
2948 if (tok == '{') {
2949 next();
2950 if (s->c != -1)
2951 tcc_error("struct/union/enum already defined");
2952 /* cannot be empty */
2953 c = 0;
2954 /* non empty enums are not allowed */
2955 if (a == TOK_ENUM) {
2956 for(;;) {
2957 v = tok;
2958 if (v < TOK_UIDENT)
2959 expect("identifier");
2960 ss = sym_find(v);
2961 if (ss && !local_stack)
2962 tcc_error("redefinition of enumerator '%s'",
2963 get_tok_str(v, NULL));
2964 next();
2965 if (tok == '=') {
2966 next();
2967 c = expr_const();
2969 /* enum symbols have static storage */
2970 ss = sym_push(v, &int_type, VT_CONST, c);
2971 ss->type.t |= VT_STATIC;
2972 if (tok != ',')
2973 break;
2974 next();
2975 c++;
2976 /* NOTE: we accept a trailing comma */
2977 if (tok == '}')
2978 break;
2980 s->c = type_size(&int_type, &align);
2981 skip('}');
2982 } else {
2983 maxalign = 1;
2984 ps = &s->next;
2985 prevbt = VT_INT;
2986 bit_pos = 0;
2987 offset = 0;
2988 flexible = 0;
2989 while (tok != '}') {
2990 parse_btype(&btype, &ad1);
2991 while (1) {
2992 if (flexible)
2993 tcc_error("flexible array member '%s' not at the end of struct",
2994 get_tok_str(v, NULL));
2995 bit_size = -1;
2996 v = 0;
2997 type1 = btype;
2998 if (tok != ':') {
2999 type_decl(&type1, &ad1, &v, TYPE_DIRECT | TYPE_ABSTRACT);
3000 if (v == 0) {
3001 if ((type1.t & VT_BTYPE) != VT_STRUCT)
3002 expect("identifier");
3003 else {
3004 int v = btype.ref->v;
3005 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
3006 if (tcc_state->ms_extensions == 0)
3007 expect("identifier");
3011 if (type_size(&type1, &align) < 0) {
3012 if ((a == TOK_STRUCT) && (type1.t & VT_ARRAY) && c)
3013 flexible = 1;
3014 else
3015 tcc_error("field '%s' has incomplete type",
3016 get_tok_str(v, NULL));
3018 if ((type1.t & VT_BTYPE) == VT_FUNC ||
3019 (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
3020 tcc_error("invalid type for '%s'",
3021 get_tok_str(v, NULL));
3023 if (tok == ':') {
3024 next();
3025 bit_size = expr_const();
3026 /* XXX: handle v = 0 case for messages */
3027 if (bit_size < 0)
3028 tcc_error("negative width in bit-field '%s'",
3029 get_tok_str(v, NULL));
3030 if (v && bit_size == 0)
3031 tcc_error("zero width for bit-field '%s'",
3032 get_tok_str(v, NULL));
3034 size = type_size(&type1, &align);
3035 if (ad1.a.aligned) {
3036 if (align < ad1.a.aligned)
3037 align = ad1.a.aligned;
3038 } else if (ad1.a.packed) {
3039 align = 1;
3040 } else if (*tcc_state->pack_stack_ptr) {
3041 if (align > *tcc_state->pack_stack_ptr)
3042 align = *tcc_state->pack_stack_ptr;
3044 lbit_pos = 0;
3045 if (bit_size >= 0) {
3046 bt = type1.t & VT_BTYPE;
3047 if (bt != VT_INT &&
3048 bt != VT_BYTE &&
3049 bt != VT_SHORT &&
3050 bt != VT_BOOL &&
3051 bt != VT_ENUM &&
3052 bt != VT_LLONG)
3053 tcc_error("bitfields must have scalar type");
3054 bsize = size * 8;
3055 if (bit_size > bsize) {
3056 tcc_error("width of '%s' exceeds its type",
3057 get_tok_str(v, NULL));
3058 } else if (bit_size == bsize) {
3059 /* no need for bit fields */
3060 bit_pos = 0;
3061 } else if (bit_size == 0) {
3062 /* XXX: what to do if only padding in a
3063 structure ? */
3064 /* zero size: means to pad */
3065 bit_pos = 0;
3066 } else {
3067 /* we do not have enough room ?
3068 did the type change?
3069 is it a union? */
3070 if ((bit_pos + bit_size) > bsize ||
3071 bt != prevbt || a == TOK_UNION)
3072 bit_pos = 0;
3073 lbit_pos = bit_pos;
3074 /* XXX: handle LSB first */
3075 type1.t |= VT_BITFIELD |
3076 (bit_pos << VT_STRUCT_SHIFT) |
3077 (bit_size << (VT_STRUCT_SHIFT + 6));
3078 bit_pos += bit_size;
3080 prevbt = bt;
3081 } else {
3082 bit_pos = 0;
3084 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
3085 /* add new memory data only if starting
3086 bit field */
3087 if (lbit_pos == 0) {
3088 if (a == TOK_STRUCT) {
3089 c = (c + align - 1) & -align;
3090 offset = c;
3091 if (size > 0)
3092 c += size;
3093 } else {
3094 offset = 0;
3095 if (size > c)
3096 c = size;
3098 if (align > maxalign)
3099 maxalign = align;
3101 #if 0
3102 printf("add field %s offset=%d",
3103 get_tok_str(v, NULL), offset);
3104 if (type1.t & VT_BITFIELD) {
3105 printf(" pos=%d size=%d",
3106 (type1.t >> VT_STRUCT_SHIFT) & 0x3f,
3107 (type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
3109 printf("\n");
3110 #endif
3112 if (v == 0 && (type1.t & VT_BTYPE) == VT_STRUCT) {
3113 ass = type1.ref;
3114 while ((ass = ass->next) != NULL) {
3115 ss = sym_push(ass->v, &ass->type, 0, offset + ass->c);
3116 *ps = ss;
3117 ps = &ss->next;
3119 } else if (v) {
3120 ss = sym_push(v | SYM_FIELD, &type1, 0, offset);
3121 *ps = ss;
3122 ps = &ss->next;
3124 if (tok == ';' || tok == TOK_EOF)
3125 break;
3126 skip(',');
3128 skip(';');
3130 skip('}');
3131 /* store size and alignment */
3132 s->c = (c + maxalign - 1) & -maxalign;
3133 s->r = maxalign;
3138 /* return 1 if basic type is a type size (short, long, long long) */
3139 ST_FUNC int is_btype_size(int bt)
3141 return bt == VT_SHORT || bt == VT_LONG || bt == VT_LLONG;
3144 /* Add type qualifiers to a type. If the type is an array then the qualifiers
3145 are added to the element type, copied because it could be a typedef. */
3146 static void parse_btype_qualify(CType *type, int qualifiers)
3148 while (type->t & VT_ARRAY) {
3149 type->ref = sym_push(SYM_FIELD, &type->ref->type, 0, type->ref->c);
3150 type = &type->ref->type;
3152 type->t |= qualifiers;
3155 /* return 0 if no type declaration. otherwise, return the basic type
3156 and skip it.
3158 static int parse_btype(CType *type, AttributeDef *ad)
3160 int t, u, bt_size, complete, type_found, typespec_found;
3161 Sym *s;
3162 CType type1;
3164 memset(ad, 0, sizeof(AttributeDef));
3165 complete = 0;
3166 type_found = 0;
3167 typespec_found = 0;
3168 t = 0;
3169 while(1) {
3170 switch(tok) {
3171 case TOK_EXTENSION:
3172 /* currently, we really ignore extension */
3173 next();
3174 continue;
3176 /* basic types */
3177 case TOK_CHAR:
3178 u = VT_BYTE;
3179 basic_type:
3180 next();
3181 basic_type1:
3182 if (complete)
3183 tcc_error("too many basic types");
3184 t |= u;
3185 bt_size = is_btype_size (u & VT_BTYPE);
3186 if (u == VT_INT || (!bt_size && !(t & VT_TYPEDEF)))
3187 complete = 1;
3188 typespec_found = 1;
3189 break;
3190 case TOK_VOID:
3191 u = VT_VOID;
3192 goto basic_type;
3193 case TOK_SHORT:
3194 u = VT_SHORT;
3195 goto basic_type;
3196 case TOK_INT:
3197 u = VT_INT;
3198 goto basic_type;
3199 case TOK_LONG:
3200 next();
3201 if ((t & VT_BTYPE) == VT_DOUBLE) {
3202 #ifndef TCC_TARGET_PE
3203 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3204 #endif
3205 } else if ((t & VT_BTYPE) == VT_LONG) {
3206 t = (t & ~VT_BTYPE) | VT_LLONG;
3207 } else {
3208 u = VT_LONG;
3209 goto basic_type1;
3211 break;
3212 #ifdef TCC_TARGET_ARM64
3213 case TOK_UINT128:
3214 /* GCC's __uint128_t appears in some Linux header files. Make it a
3215 synonym for long double to get the size and alignment right. */
3216 u = VT_LDOUBLE;
3217 goto basic_type;
3218 #endif
3219 case TOK_BOOL:
3220 u = VT_BOOL;
3221 goto basic_type;
3222 case TOK_FLOAT:
3223 u = VT_FLOAT;
3224 goto basic_type;
3225 case TOK_DOUBLE:
3226 next();
3227 if ((t & VT_BTYPE) == VT_LONG) {
3228 #ifdef TCC_TARGET_PE
3229 t = (t & ~VT_BTYPE) | VT_DOUBLE;
3230 #else
3231 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3232 #endif
3233 } else {
3234 u = VT_DOUBLE;
3235 goto basic_type1;
3237 break;
3238 case TOK_ENUM:
3239 struct_decl(&type1, ad, VT_ENUM);
3240 basic_type2:
3241 u = type1.t;
3242 type->ref = type1.ref;
3243 goto basic_type1;
3244 case TOK_STRUCT:
3245 case TOK_UNION:
3246 struct_decl(&type1, ad, VT_STRUCT);
3247 goto basic_type2;
3249 /* type modifiers */
3250 case TOK_CONST1:
3251 case TOK_CONST2:
3252 case TOK_CONST3:
3253 type->t = t;
3254 parse_btype_qualify(type, VT_CONSTANT);
3255 t = type->t;
3256 next();
3257 break;
3258 case TOK_VOLATILE1:
3259 case TOK_VOLATILE2:
3260 case TOK_VOLATILE3:
3261 type->t = t;
3262 parse_btype_qualify(type, VT_VOLATILE);
3263 t = type->t;
3264 next();
3265 break;
3266 case TOK_SIGNED1:
3267 case TOK_SIGNED2:
3268 case TOK_SIGNED3:
3269 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == (VT_DEFSIGN|VT_UNSIGNED))
3270 tcc_error("signed and unsigned modifier");
3271 typespec_found = 1;
3272 t |= VT_DEFSIGN;
3273 next();
3274 break;
3275 case TOK_REGISTER:
3276 case TOK_AUTO:
3277 case TOK_RESTRICT1:
3278 case TOK_RESTRICT2:
3279 case TOK_RESTRICT3:
3280 next();
3281 break;
3282 case TOK_UNSIGNED:
3283 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == VT_DEFSIGN)
3284 tcc_error("signed and unsigned modifier");
3285 t |= VT_DEFSIGN | VT_UNSIGNED;
3286 next();
3287 typespec_found = 1;
3288 break;
3290 /* storage */
3291 case TOK_EXTERN:
3292 t |= VT_EXTERN;
3293 next();
3294 break;
3295 case TOK_STATIC:
3296 t |= VT_STATIC;
3297 next();
3298 break;
3299 case TOK_TYPEDEF:
3300 t |= VT_TYPEDEF;
3301 next();
3302 break;
3303 case TOK_INLINE1:
3304 case TOK_INLINE2:
3305 case TOK_INLINE3:
3306 t |= VT_INLINE;
3307 next();
3308 break;
3310 /* GNUC attribute */
3311 case TOK_ATTRIBUTE1:
3312 case TOK_ATTRIBUTE2:
3313 parse_attribute(ad);
3314 if (ad->a.mode) {
3315 u = ad->a.mode -1;
3316 t = (t & ~VT_BTYPE) | u;
3318 break;
3319 /* GNUC typeof */
3320 case TOK_TYPEOF1:
3321 case TOK_TYPEOF2:
3322 case TOK_TYPEOF3:
3323 next();
3324 parse_expr_type(&type1);
3325 /* remove all storage modifiers except typedef */
3326 type1.t &= ~(VT_STORAGE&~VT_TYPEDEF);
3327 goto basic_type2;
3328 default:
3329 if (typespec_found)
3330 goto the_end;
3331 s = sym_find(tok);
3332 if (!s || !(s->type.t & VT_TYPEDEF))
3333 goto the_end;
3335 type->t = ((s->type.t & ~VT_TYPEDEF) |
3336 (t & ~(VT_CONSTANT | VT_VOLATILE)));
3337 type->ref = s->type.ref;
3338 if (t & (VT_CONSTANT | VT_VOLATILE))
3339 parse_btype_qualify(type, t & (VT_CONSTANT | VT_VOLATILE));
3340 t = type->t;
3342 if (s->r) {
3343 /* get attributes from typedef */
3344 if (0 == ad->a.aligned)
3345 ad->a.aligned = s->a.aligned;
3346 if (0 == ad->a.func_call)
3347 ad->a.func_call = s->a.func_call;
3348 ad->a.packed |= s->a.packed;
3350 next();
3351 typespec_found = 1;
3352 break;
3354 type_found = 1;
3356 the_end:
3357 if (tcc_state->char_is_unsigned) {
3358 if ((t & (VT_DEFSIGN|VT_BTYPE)) == VT_BYTE)
3359 t |= VT_UNSIGNED;
3362 /* long is never used as type */
3363 if ((t & VT_BTYPE) == VT_LONG)
3364 #if (!defined TCC_TARGET_X86_64 && !defined TCC_TARGET_ARM64) || \
3365 defined TCC_TARGET_PE
3366 t = (t & ~VT_BTYPE) | VT_INT;
3367 #else
3368 t = (t & ~VT_BTYPE) | VT_LLONG;
3369 #endif
3370 type->t = t;
3371 return type_found;
3374 /* convert a function parameter type (array to pointer and function to
3375 function pointer) */
3376 static inline void convert_parameter_type(CType *pt)
3378 /* remove const and volatile qualifiers (XXX: const could be used
3379 to indicate a const function parameter */
3380 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
3381 /* array must be transformed to pointer according to ANSI C */
3382 pt->t &= ~VT_ARRAY;
3383 if ((pt->t & VT_BTYPE) == VT_FUNC) {
3384 mk_pointer(pt);
3388 ST_FUNC void parse_asm_str(CString *astr)
3390 skip('(');
3391 /* read the string */
3392 if (tok != TOK_STR)
3393 expect("string constant");
3394 cstr_new(astr);
3395 while (tok == TOK_STR) {
3396 /* XXX: add \0 handling too ? */
3397 cstr_cat(astr, tokc.str.data, -1);
3398 next();
3400 cstr_ccat(astr, '\0');
3403 /* Parse an asm label and return the token */
3404 static int asm_label_instr(void)
3406 int v;
3407 CString astr;
3409 next();
3410 parse_asm_str(&astr);
3411 skip(')');
3412 #ifdef ASM_DEBUG
3413 printf("asm_alias: \"%s\"\n", (char *)astr.data);
3414 #endif
3415 v = tok_alloc(astr.data, astr.size - 1)->tok;
3416 cstr_free(&astr);
3417 return v;
3420 static void post_type(CType *type, AttributeDef *ad)
3422 int n, l, t1, arg_size, align;
3423 Sym **plast, *s, *first;
3424 AttributeDef ad1;
3425 CType pt;
3427 if (tok == '(') {
3428 /* function declaration */
3429 next();
3430 l = 0;
3431 first = NULL;
3432 plast = &first;
3433 arg_size = 0;
3434 if (tok != ')') {
3435 for(;;) {
3436 /* read param name and compute offset */
3437 if (l != FUNC_OLD) {
3438 if (!parse_btype(&pt, &ad1)) {
3439 if (l) {
3440 tcc_error("invalid type");
3441 } else {
3442 l = FUNC_OLD;
3443 goto old_proto;
3446 l = FUNC_NEW;
3447 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
3448 break;
3449 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
3450 if ((pt.t & VT_BTYPE) == VT_VOID)
3451 tcc_error("parameter declared as void");
3452 arg_size += (type_size(&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
3453 } else {
3454 old_proto:
3455 n = tok;
3456 if (n < TOK_UIDENT)
3457 expect("identifier");
3458 pt.t = VT_INT;
3459 next();
3461 convert_parameter_type(&pt);
3462 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
3463 *plast = s;
3464 plast = &s->next;
3465 if (tok == ')')
3466 break;
3467 skip(',');
3468 if (l == FUNC_NEW && tok == TOK_DOTS) {
3469 l = FUNC_ELLIPSIS;
3470 next();
3471 break;
3475 /* if no parameters, then old type prototype */
3476 if (l == 0)
3477 l = FUNC_OLD;
3478 skip(')');
3479 /* NOTE: const is ignored in returned type as it has a special
3480 meaning in gcc / C++ */
3481 type->t &= ~VT_CONSTANT;
3482 /* some ancient pre-K&R C allows a function to return an array
3483 and the array brackets to be put after the arguments, such
3484 that "int c()[]" means something like "int[] c()" */
3485 if (tok == '[') {
3486 next();
3487 skip(']'); /* only handle simple "[]" */
3488 type->t |= VT_PTR;
3490 /* we push a anonymous symbol which will contain the function prototype */
3491 ad->a.func_args = arg_size;
3492 s = sym_push(SYM_FIELD, type, 0, l);
3493 s->a = ad->a;
3494 s->next = first;
3495 type->t = VT_FUNC;
3496 type->ref = s;
3497 } else if (tok == '[') {
3498 /* array definition */
3499 next();
3500 if (tok == TOK_RESTRICT1)
3501 next();
3502 n = -1;
3503 t1 = 0;
3504 if (tok != ']') {
3505 if (!local_stack || nocode_wanted)
3506 vpushi(expr_const());
3507 else gexpr();
3508 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3509 n = vtop->c.i;
3510 if (n < 0)
3511 tcc_error("invalid array size");
3512 } else {
3513 if (!is_integer_btype(vtop->type.t & VT_BTYPE))
3514 tcc_error("size of variable length array should be an integer");
3515 t1 = VT_VLA;
3518 skip(']');
3519 /* parse next post type */
3520 post_type(type, ad);
3521 if (type->t == VT_FUNC)
3522 tcc_error("declaration of an array of functions");
3523 t1 |= type->t & VT_VLA;
3525 if (t1 & VT_VLA) {
3526 loc -= type_size(&int_type, &align);
3527 loc &= -align;
3528 n = loc;
3530 vla_runtime_type_size(type, &align);
3531 gen_op('*');
3532 vset(&int_type, VT_LOCAL|VT_LVAL, n);
3533 vswap();
3534 vstore();
3536 if (n != -1)
3537 vpop();
3539 /* we push an anonymous symbol which will contain the array
3540 element type */
3541 s = sym_push(SYM_FIELD, type, 0, n);
3542 type->t = (t1 ? VT_VLA : VT_ARRAY) | VT_PTR;
3543 type->ref = s;
3547 /* Parse a type declaration (except basic type), and return the type
3548 in 'type'. 'td' is a bitmask indicating which kind of type decl is
3549 expected. 'type' should contain the basic type. 'ad' is the
3550 attribute definition of the basic type. It can be modified by
3551 type_decl().
3553 static void type_decl(CType *type, AttributeDef *ad, int *v, int td)
3555 Sym *s;
3556 CType type1, *type2;
3557 int qualifiers, storage;
3559 while (tok == '*') {
3560 qualifiers = 0;
3561 redo:
3562 next();
3563 switch(tok) {
3564 case TOK_CONST1:
3565 case TOK_CONST2:
3566 case TOK_CONST3:
3567 qualifiers |= VT_CONSTANT;
3568 goto redo;
3569 case TOK_VOLATILE1:
3570 case TOK_VOLATILE2:
3571 case TOK_VOLATILE3:
3572 qualifiers |= VT_VOLATILE;
3573 goto redo;
3574 case TOK_RESTRICT1:
3575 case TOK_RESTRICT2:
3576 case TOK_RESTRICT3:
3577 goto redo;
3579 mk_pointer(type);
3580 type->t |= qualifiers;
3583 /* XXX: clarify attribute handling */
3584 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3585 parse_attribute(ad);
3587 /* recursive type */
3588 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
3589 type1.t = 0; /* XXX: same as int */
3590 if (tok == '(') {
3591 next();
3592 /* XXX: this is not correct to modify 'ad' at this point, but
3593 the syntax is not clear */
3594 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3595 parse_attribute(ad);
3596 type_decl(&type1, ad, v, td);
3597 skip(')');
3598 } else {
3599 /* type identifier */
3600 if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
3601 *v = tok;
3602 next();
3603 } else {
3604 if (!(td & TYPE_ABSTRACT))
3605 expect("identifier");
3606 *v = 0;
3609 storage = type->t & VT_STORAGE;
3610 type->t &= ~VT_STORAGE;
3611 if (storage & VT_STATIC) {
3612 int saved_nocode_wanted = nocode_wanted;
3613 nocode_wanted = 1;
3614 post_type(type, ad);
3615 nocode_wanted = saved_nocode_wanted;
3616 } else
3617 post_type(type, ad);
3618 type->t |= storage;
3619 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3620 parse_attribute(ad);
3622 if (!type1.t)
3623 return;
3624 /* append type at the end of type1 */
3625 type2 = &type1;
3626 for(;;) {
3627 s = type2->ref;
3628 type2 = &s->type;
3629 if (!type2->t) {
3630 *type2 = *type;
3631 break;
3634 *type = type1;
3637 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
3638 ST_FUNC int lvalue_type(int t)
3640 int bt, r;
3641 r = VT_LVAL;
3642 bt = t & VT_BTYPE;
3643 if (bt == VT_BYTE || bt == VT_BOOL)
3644 r |= VT_LVAL_BYTE;
3645 else if (bt == VT_SHORT)
3646 r |= VT_LVAL_SHORT;
3647 else
3648 return r;
3649 if (t & VT_UNSIGNED)
3650 r |= VT_LVAL_UNSIGNED;
3651 return r;
3654 /* indirection with full error checking and bound check */
3655 ST_FUNC void indir(void)
3657 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
3658 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
3659 return;
3660 expect("pointer");
3662 if ((vtop->r & VT_LVAL) && !nocode_wanted)
3663 gv(RC_INT);
3664 vtop->type = *pointed_type(&vtop->type);
3665 /* Arrays and functions are never lvalues */
3666 if (!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_VLA)
3667 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
3668 vtop->r |= lvalue_type(vtop->type.t);
3669 /* if bound checking, the referenced pointer must be checked */
3670 #ifdef CONFIG_TCC_BCHECK
3671 if (tcc_state->do_bounds_check)
3672 vtop->r |= VT_MUSTBOUND;
3673 #endif
3677 /* pass a parameter to a function and do type checking and casting */
3678 static void gfunc_param_typed(Sym *func, Sym *arg)
3680 int func_type;
3681 CType type;
3683 func_type = func->c;
3684 if (func_type == FUNC_OLD ||
3685 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
3686 /* default casting : only need to convert float to double */
3687 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
3688 type.t = VT_DOUBLE;
3689 gen_cast(&type);
3690 } else if (vtop->type.t & VT_BITFIELD) {
3691 type.t = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
3692 gen_cast(&type);
3694 } else if (arg == NULL) {
3695 tcc_error("too many arguments to function");
3696 } else {
3697 type = arg->type;
3698 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
3699 gen_assign_cast(&type);
3703 /* parse an expression of the form '(type)' or '(expr)' and return its
3704 type */
3705 static void parse_expr_type(CType *type)
3707 int n;
3708 AttributeDef ad;
3710 skip('(');
3711 if (parse_btype(type, &ad)) {
3712 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3713 } else {
3714 expr_type(type);
3716 skip(')');
3719 static void parse_type(CType *type)
3721 AttributeDef ad;
3722 int n;
3724 if (!parse_btype(type, &ad)) {
3725 expect("type");
3727 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3730 static void vpush_tokc(int t)
3732 CType type;
3733 type.t = t;
3734 type.ref = 0;
3735 vsetc(&type, VT_CONST, &tokc);
3738 ST_FUNC void unary(void)
3740 int n, t, align, size, r, sizeof_caller;
3741 CType type;
3742 Sym *s;
3743 AttributeDef ad;
3744 static int in_sizeof = 0;
3746 sizeof_caller = in_sizeof;
3747 in_sizeof = 0;
3748 /* XXX: GCC 2.95.3 does not generate a table although it should be
3749 better here */
3750 tok_next:
3751 switch(tok) {
3752 case TOK_EXTENSION:
3753 next();
3754 goto tok_next;
3755 case TOK_CINT:
3756 case TOK_CCHAR:
3757 case TOK_LCHAR:
3758 vpushi(tokc.i);
3759 next();
3760 break;
3761 case TOK_CUINT:
3762 vpush_tokc(VT_INT | VT_UNSIGNED);
3763 next();
3764 break;
3765 case TOK_CLLONG:
3766 vpush_tokc(VT_LLONG);
3767 next();
3768 break;
3769 case TOK_CULLONG:
3770 vpush_tokc(VT_LLONG | VT_UNSIGNED);
3771 next();
3772 break;
3773 case TOK_CFLOAT:
3774 vpush_tokc(VT_FLOAT);
3775 next();
3776 break;
3777 case TOK_CDOUBLE:
3778 vpush_tokc(VT_DOUBLE);
3779 next();
3780 break;
3781 case TOK_CLDOUBLE:
3782 vpush_tokc(VT_LDOUBLE);
3783 next();
3784 break;
3785 case TOK___FUNCTION__:
3786 if (!gnu_ext)
3787 goto tok_identifier;
3788 /* fall thru */
3789 case TOK___FUNC__:
3791 void *ptr;
3792 int len;
3793 /* special function name identifier */
3794 len = strlen(funcname) + 1;
3795 /* generate char[len] type */
3796 type.t = VT_BYTE;
3797 mk_pointer(&type);
3798 type.t |= VT_ARRAY;
3799 type.ref->c = len;
3800 vpush_ref(&type, data_section, data_section->data_offset, len);
3801 ptr = section_ptr_add(data_section, len);
3802 memcpy(ptr, funcname, len);
3803 next();
3805 break;
3806 case TOK_LSTR:
3807 #ifdef TCC_TARGET_PE
3808 t = VT_SHORT | VT_UNSIGNED;
3809 #else
3810 t = VT_INT;
3811 #endif
3812 goto str_init;
3813 case TOK_STR:
3814 /* string parsing */
3815 t = VT_BYTE;
3816 str_init:
3817 if (tcc_state->warn_write_strings)
3818 t |= VT_CONSTANT;
3819 type.t = t;
3820 mk_pointer(&type);
3821 type.t |= VT_ARRAY;
3822 memset(&ad, 0, sizeof(AttributeDef));
3823 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, 0);
3824 break;
3825 case '(':
3826 next();
3827 /* cast ? */
3828 if (parse_btype(&type, &ad)) {
3829 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
3830 skip(')');
3831 /* check ISOC99 compound literal */
3832 if (tok == '{') {
3833 /* data is allocated locally by default */
3834 if (global_expr)
3835 r = VT_CONST;
3836 else
3837 r = VT_LOCAL;
3838 /* all except arrays are lvalues */
3839 if (!(type.t & VT_ARRAY))
3840 r |= lvalue_type(type.t);
3841 memset(&ad, 0, sizeof(AttributeDef));
3842 decl_initializer_alloc(&type, &ad, r, 1, 0, 0);
3843 } else {
3844 if (sizeof_caller) {
3845 vpush(&type);
3846 return;
3848 unary();
3849 gen_cast(&type);
3851 } else if (tok == '{') {
3852 if (const_wanted)
3853 tcc_error("expected constant");
3854 /* save all registers */
3855 if (!nocode_wanted)
3856 save_regs(0);
3857 /* statement expression : we do not accept break/continue
3858 inside as GCC does */
3859 block(NULL, NULL, NULL, NULL, 0, 1);
3860 skip(')');
3861 } else {
3862 gexpr();
3863 skip(')');
3865 break;
3866 case '*':
3867 next();
3868 unary();
3869 indir();
3870 break;
3871 case '&':
3872 next();
3873 unary();
3874 /* functions names must be treated as function pointers,
3875 except for unary '&' and sizeof. Since we consider that
3876 functions are not lvalues, we only have to handle it
3877 there and in function calls. */
3878 /* arrays can also be used although they are not lvalues */
3879 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
3880 !(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
3881 test_lvalue();
3882 mk_pointer(&vtop->type);
3883 gaddrof();
3884 break;
3885 case '!':
3886 next();
3887 unary();
3888 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3889 CType boolean;
3890 boolean.t = VT_BOOL;
3891 gen_cast(&boolean);
3892 vtop->c.i = !vtop->c.i;
3893 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
3894 vtop->c.i ^= 1;
3895 else {
3896 save_regs(1);
3897 vseti(VT_JMP, gvtst(1, 0));
3899 break;
3900 case '~':
3901 next();
3902 unary();
3903 vpushi(-1);
3904 gen_op('^');
3905 break;
3906 case '+':
3907 next();
3908 unary();
3909 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
3910 tcc_error("pointer not accepted for unary plus");
3911 /* In order to force cast, we add zero, except for floating point
3912 where we really need an noop (otherwise -0.0 will be transformed
3913 into +0.0). */
3914 if (!is_float(vtop->type.t)) {
3915 vpushi(0);
3916 gen_op('+');
3918 break;
3919 case TOK_SIZEOF:
3920 case TOK_ALIGNOF1:
3921 case TOK_ALIGNOF2:
3922 t = tok;
3923 next();
3924 in_sizeof++;
3925 unary_type(&type); // Perform a in_sizeof = 0;
3926 size = type_size(&type, &align);
3927 if (t == TOK_SIZEOF) {
3928 if (!(type.t & VT_VLA)) {
3929 if (size < 0)
3930 tcc_error("sizeof applied to an incomplete type");
3931 vpushs(size);
3932 } else {
3933 vla_runtime_type_size(&type, &align);
3935 } else {
3936 vpushs(align);
3938 vtop->type.t |= VT_UNSIGNED;
3939 break;
3941 case TOK_builtin_expect:
3943 /* __builtin_expect is a no-op for now */
3944 int saved_nocode_wanted;
3945 next();
3946 skip('(');
3947 expr_eq();
3948 skip(',');
3949 saved_nocode_wanted = nocode_wanted;
3950 nocode_wanted = 1;
3951 expr_lor_const();
3952 vpop();
3953 nocode_wanted = saved_nocode_wanted;
3954 skip(')');
3956 break;
3957 case TOK_builtin_types_compatible_p:
3959 CType type1, type2;
3960 next();
3961 skip('(');
3962 parse_type(&type1);
3963 skip(',');
3964 parse_type(&type2);
3965 skip(')');
3966 type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
3967 type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
3968 vpushi(is_compatible_types(&type1, &type2));
3970 break;
3971 case TOK_builtin_constant_p:
3973 int saved_nocode_wanted, res;
3974 next();
3975 skip('(');
3976 saved_nocode_wanted = nocode_wanted;
3977 nocode_wanted = 1;
3978 gexpr();
3979 res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
3980 vpop();
3981 nocode_wanted = saved_nocode_wanted;
3982 skip(')');
3983 vpushi(res);
3985 break;
3986 case TOK_builtin_frame_address:
3987 case TOK_builtin_return_address:
3989 int tok1 = tok;
3990 int level;
3991 CType type;
3992 next();
3993 skip('(');
3994 if (tok != TOK_CINT) {
3995 tcc_error("%s only takes positive integers",
3996 tok1 == TOK_builtin_return_address ?
3997 "__builtin_return_address" :
3998 "__builtin_frame_address");
4000 level = (uint32_t)tokc.i;
4001 next();
4002 skip(')');
4003 type.t = VT_VOID;
4004 mk_pointer(&type);
4005 vset(&type, VT_LOCAL, 0); /* local frame */
4006 while (level--) {
4007 mk_pointer(&vtop->type);
4008 indir(); /* -> parent frame */
4010 if (tok1 == TOK_builtin_return_address) {
4011 // assume return address is just above frame pointer on stack
4012 vpushi(PTR_SIZE);
4013 gen_op('+');
4014 mk_pointer(&vtop->type);
4015 indir();
4018 break;
4019 #ifdef TCC_TARGET_X86_64
4020 #ifdef TCC_TARGET_PE
4021 case TOK_builtin_va_start:
4023 next();
4024 skip('(');
4025 expr_eq();
4026 skip(',');
4027 expr_eq();
4028 skip(')');
4029 if ((vtop->r & VT_VALMASK) != VT_LOCAL)
4030 tcc_error("__builtin_va_start expects a local variable");
4031 vtop->r &= ~(VT_LVAL | VT_REF);
4032 vtop->type = char_pointer_type;
4033 vstore();
4035 break;
4036 #else
4037 case TOK_builtin_va_arg_types:
4039 CType type;
4040 next();
4041 skip('(');
4042 parse_type(&type);
4043 skip(')');
4044 vpushi(classify_x86_64_va_arg(&type));
4046 break;
4047 #endif
4048 #endif
4050 #ifdef TCC_TARGET_ARM64
4051 case TOK___va_start: {
4052 if (nocode_wanted)
4053 tcc_error("statement in global scope");
4054 next();
4055 skip('(');
4056 expr_eq();
4057 skip(',');
4058 expr_eq();
4059 skip(')');
4060 //xx check types
4061 gen_va_start();
4062 vpushi(0);
4063 vtop->type.t = VT_VOID;
4064 break;
4066 case TOK___va_arg: {
4067 CType type;
4068 if (nocode_wanted)
4069 tcc_error("statement in global scope");
4070 next();
4071 skip('(');
4072 expr_eq();
4073 skip(',');
4074 parse_type(&type);
4075 skip(')');
4076 //xx check types
4077 gen_va_arg(&type);
4078 vtop->type = type;
4079 break;
4081 case TOK___arm64_clear_cache: {
4082 next();
4083 skip('(');
4084 expr_eq();
4085 skip(',');
4086 expr_eq();
4087 skip(')');
4088 gen_clear_cache();
4089 vpushi(0);
4090 vtop->type.t = VT_VOID;
4091 break;
4093 #endif
4094 /* pre operations */
4095 case TOK_INC:
4096 case TOK_DEC:
4097 t = tok;
4098 next();
4099 unary();
4100 inc(0, t);
4101 break;
4102 case '-':
4103 next();
4104 unary();
4105 t = vtop->type.t & VT_BTYPE;
4106 if (is_float(t)) {
4107 /* In IEEE negate(x) isn't subtract(0,x), but rather
4108 subtract(-0, x). */
4109 vpush(&vtop->type);
4110 if (t == VT_FLOAT)
4111 vtop->c.f = -0.0f;
4112 else if (t == VT_DOUBLE)
4113 vtop->c.d = -0.0;
4114 else
4115 vtop->c.ld = -0.0;
4116 } else
4117 vpushi(0);
4118 vswap();
4119 gen_op('-');
4120 break;
4121 case TOK_LAND:
4122 if (!gnu_ext)
4123 goto tok_identifier;
4124 next();
4125 /* allow to take the address of a label */
4126 if (tok < TOK_UIDENT)
4127 expect("label identifier");
4128 s = label_find(tok);
4129 if (!s) {
4130 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
4131 } else {
4132 if (s->r == LABEL_DECLARED)
4133 s->r = LABEL_FORWARD;
4135 if (!s->type.t) {
4136 s->type.t = VT_VOID;
4137 mk_pointer(&s->type);
4138 s->type.t |= VT_STATIC;
4140 vpushsym(&s->type, s);
4141 next();
4142 break;
4144 // special qnan , snan and infinity values
4145 case TOK___NAN__:
4146 vpush64(VT_DOUBLE, 0x7ff8000000000000ULL);
4147 next();
4148 break;
4149 case TOK___SNAN__:
4150 vpush64(VT_DOUBLE, 0x7ff0000000000001ULL);
4151 next();
4152 break;
4153 case TOK___INF__:
4154 vpush64(VT_DOUBLE, 0x7ff0000000000000ULL);
4155 next();
4156 break;
4158 default:
4159 tok_identifier:
4160 t = tok;
4161 next();
4162 if (t < TOK_UIDENT)
4163 expect("identifier");
4164 s = sym_find(t);
4165 if (!s) {
4166 const char *name = get_tok_str(t, NULL);
4167 if (tok != '(')
4168 tcc_error("'%s' undeclared", name);
4169 /* for simple function calls, we tolerate undeclared
4170 external reference to int() function */
4171 if (tcc_state->warn_implicit_function_declaration
4172 #ifdef TCC_TARGET_PE
4173 /* people must be warned about using undeclared WINAPI functions
4174 (which usually start with uppercase letter) */
4175 || (name[0] >= 'A' && name[0] <= 'Z')
4176 #endif
4178 tcc_warning("implicit declaration of function '%s'", name);
4179 s = external_global_sym(t, &func_old_type, 0);
4181 if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
4182 (VT_STATIC | VT_INLINE | VT_FUNC)) {
4183 /* if referencing an inline function, then we generate a
4184 symbol to it if not already done. It will have the
4185 effect to generate code for it at the end of the
4186 compilation unit. Inline function as always
4187 generated in the text section. */
4188 if (!s->c)
4189 put_extern_sym(s, text_section, 0, 0);
4190 r = VT_SYM | VT_CONST;
4191 } else {
4192 r = s->r;
4194 vset(&s->type, r, s->c);
4195 /* if forward reference, we must point to s */
4196 if (vtop->r & VT_SYM) {
4197 vtop->sym = s;
4198 vtop->c.i = 0;
4200 break;
4203 /* post operations */
4204 while (1) {
4205 if (tok == TOK_INC || tok == TOK_DEC) {
4206 inc(1, tok);
4207 next();
4208 } else if (tok == '.' || tok == TOK_ARROW || tok == TOK_CDOUBLE) {
4209 int qualifiers;
4210 /* field */
4211 if (tok == TOK_ARROW)
4212 indir();
4213 qualifiers = vtop->type.t & (VT_CONSTANT | VT_VOLATILE);
4214 test_lvalue();
4215 gaddrof();
4216 /* expect pointer on structure */
4217 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
4218 expect("struct or union");
4219 if (tok == TOK_CDOUBLE)
4220 expect("field name");
4221 next();
4222 if (tok == TOK_CINT || tok == TOK_CUINT)
4223 expect("field name");
4224 s = vtop->type.ref;
4225 /* find field */
4226 tok |= SYM_FIELD;
4227 while ((s = s->next) != NULL) {
4228 if (s->v == tok)
4229 break;
4231 if (!s)
4232 tcc_error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, &tokc));
4233 /* add field offset to pointer */
4234 vtop->type = char_pointer_type; /* change type to 'char *' */
4235 vpushi(s->c);
4236 gen_op('+');
4237 /* change type to field type, and set to lvalue */
4238 vtop->type = s->type;
4239 vtop->type.t |= qualifiers;
4240 /* an array is never an lvalue */
4241 if (!(vtop->type.t & VT_ARRAY)) {
4242 vtop->r |= lvalue_type(vtop->type.t);
4243 #ifdef CONFIG_TCC_BCHECK
4244 /* if bound checking, the referenced pointer must be checked */
4245 if (tcc_state->do_bounds_check)
4246 vtop->r |= VT_MUSTBOUND;
4247 #endif
4249 next();
4250 } else if (tok == '[') {
4251 next();
4252 gexpr();
4253 gen_op('+');
4254 indir();
4255 skip(']');
4256 } else if (tok == '(') {
4257 SValue ret;
4258 Sym *sa;
4259 int nb_args, ret_nregs, ret_align, regsize, variadic;
4261 /* function call */
4262 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
4263 /* pointer test (no array accepted) */
4264 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
4265 vtop->type = *pointed_type(&vtop->type);
4266 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
4267 goto error_func;
4268 } else {
4269 error_func:
4270 expect("function pointer");
4272 } else {
4273 vtop->r &= ~VT_LVAL; /* no lvalue */
4275 /* get return type */
4276 s = vtop->type.ref;
4277 next();
4278 sa = s->next; /* first parameter */
4279 nb_args = 0;
4280 ret.r2 = VT_CONST;
4281 /* compute first implicit argument if a structure is returned */
4282 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
4283 variadic = (s->c == FUNC_ELLIPSIS);
4284 ret_nregs = gfunc_sret(&s->type, variadic, &ret.type,
4285 &ret_align, &regsize);
4286 if (!ret_nregs) {
4287 /* get some space for the returned structure */
4288 size = type_size(&s->type, &align);
4289 #ifdef TCC_TARGET_ARM64
4290 /* On arm64, a small struct is return in registers.
4291 It is much easier to write it to memory if we know
4292 that we are allowed to write some extra bytes, so
4293 round the allocated space up to a power of 2: */
4294 if (size < 16)
4295 while (size & (size - 1))
4296 size = (size | (size - 1)) + 1;
4297 #endif
4298 loc = (loc - size) & -align;
4299 ret.type = s->type;
4300 ret.r = VT_LOCAL | VT_LVAL;
4301 /* pass it as 'int' to avoid structure arg passing
4302 problems */
4303 vseti(VT_LOCAL, loc);
4304 ret.c = vtop->c;
4305 nb_args++;
4307 } else {
4308 ret_nregs = 1;
4309 ret.type = s->type;
4312 if (ret_nregs) {
4313 /* return in register */
4314 if (is_float(ret.type.t)) {
4315 ret.r = reg_fret(ret.type.t);
4316 #ifdef TCC_TARGET_X86_64
4317 if ((ret.type.t & VT_BTYPE) == VT_QFLOAT)
4318 ret.r2 = REG_QRET;
4319 #endif
4320 } else {
4321 #ifndef TCC_TARGET_ARM64
4322 #ifdef TCC_TARGET_X86_64
4323 if ((ret.type.t & VT_BTYPE) == VT_QLONG)
4324 #else
4325 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
4326 #endif
4327 ret.r2 = REG_LRET;
4328 #endif
4329 ret.r = REG_IRET;
4331 ret.c.i = 0;
4333 if (tok != ')') {
4334 for(;;) {
4335 expr_eq();
4336 gfunc_param_typed(s, sa);
4337 nb_args++;
4338 if (sa)
4339 sa = sa->next;
4340 if (tok == ')')
4341 break;
4342 skip(',');
4345 if (sa)
4346 tcc_error("too few arguments to function");
4347 skip(')');
4348 if (!nocode_wanted) {
4349 gfunc_call(nb_args);
4350 } else {
4351 vtop -= (nb_args + 1);
4354 /* return value */
4355 for (r = ret.r + ret_nregs + !ret_nregs; r-- > ret.r;) {
4356 vsetc(&ret.type, r, &ret.c);
4357 vtop->r2 = ret.r2; /* Loop only happens when r2 is VT_CONST */
4360 /* handle packed struct return */
4361 if (((s->type.t & VT_BTYPE) == VT_STRUCT) && ret_nregs) {
4362 int addr, offset;
4364 size = type_size(&s->type, &align);
4365 /* We're writing whole regs often, make sure there's enough
4366 space. Assume register size is power of 2. */
4367 if (regsize > align)
4368 align = regsize;
4369 loc = (loc - size) & -align;
4370 addr = loc;
4371 offset = 0;
4372 for (;;) {
4373 vset(&ret.type, VT_LOCAL | VT_LVAL, addr + offset);
4374 vswap();
4375 vstore();
4376 vtop--;
4377 if (--ret_nregs == 0)
4378 break;
4379 offset += regsize;
4381 vset(&s->type, VT_LOCAL | VT_LVAL, addr);
4383 } else {
4384 break;
4389 ST_FUNC void expr_prod(void)
4391 int t;
4393 unary();
4394 while (tok == '*' || tok == '/' || tok == '%') {
4395 t = tok;
4396 next();
4397 unary();
4398 gen_op(t);
4402 ST_FUNC void expr_sum(void)
4404 int t;
4406 expr_prod();
4407 while (tok == '+' || tok == '-') {
4408 t = tok;
4409 next();
4410 expr_prod();
4411 gen_op(t);
4415 static void expr_shift(void)
4417 int t;
4419 expr_sum();
4420 while (tok == TOK_SHL || tok == TOK_SAR) {
4421 t = tok;
4422 next();
4423 expr_sum();
4424 gen_op(t);
4428 static void expr_cmp(void)
4430 int t;
4432 expr_shift();
4433 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
4434 tok == TOK_ULT || tok == TOK_UGE) {
4435 t = tok;
4436 next();
4437 expr_shift();
4438 gen_op(t);
4442 static void expr_cmpeq(void)
4444 int t;
4446 expr_cmp();
4447 while (tok == TOK_EQ || tok == TOK_NE) {
4448 t = tok;
4449 next();
4450 expr_cmp();
4451 gen_op(t);
4455 static void expr_and(void)
4457 expr_cmpeq();
4458 while (tok == '&') {
4459 next();
4460 expr_cmpeq();
4461 gen_op('&');
4465 static void expr_xor(void)
4467 expr_and();
4468 while (tok == '^') {
4469 next();
4470 expr_and();
4471 gen_op('^');
4475 static void expr_or(void)
4477 expr_xor();
4478 while (tok == '|') {
4479 next();
4480 expr_xor();
4481 gen_op('|');
4485 /* XXX: fix this mess */
4486 static void expr_land_const(void)
4488 expr_or();
4489 while (tok == TOK_LAND) {
4490 next();
4491 expr_or();
4492 gen_op(TOK_LAND);
4495 static void expr_lor_const(void)
4497 expr_land_const();
4498 while (tok == TOK_LOR) {
4499 next();
4500 expr_land_const();
4501 gen_op(TOK_LOR);
4505 static void expr_land(void)
4507 expr_or();
4508 if (tok == TOK_LAND) {
4509 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4510 CType ctb, cti;
4511 ctb.t = VT_BOOL;
4512 cti.t = VT_INT;
4513 next();
4514 gen_cast(&ctb);
4515 if (vtop->c.i) {
4516 vpop();
4517 expr_land();
4518 gen_cast(&ctb);
4519 } else {
4520 int saved_nocode_wanted = nocode_wanted;
4521 nocode_wanted = 1;
4522 expr_land();
4523 vpop();
4524 nocode_wanted = saved_nocode_wanted;
4526 gen_cast(&cti);
4527 } else {
4528 int t = 0;
4529 save_regs(1);
4530 for(;;) {
4531 t = gvtst(1, t);
4532 if (tok != TOK_LAND) {
4533 vseti(VT_JMPI, t);
4534 break;
4536 next();
4537 expr_or();
4543 static void expr_lor(void)
4545 expr_land();
4546 if (tok == TOK_LOR) {
4547 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4548 CType ctb, cti;
4549 ctb.t = VT_BOOL;
4550 cti.t = VT_INT;
4551 next();
4552 gen_cast(&ctb);
4553 if (vtop->c.i) {
4554 int saved_nocode_wanted = nocode_wanted;
4555 nocode_wanted = 1;
4556 expr_lor();
4557 vpop();
4558 nocode_wanted = saved_nocode_wanted;
4559 } else {
4560 vpop();
4561 expr_lor();
4562 gen_cast(&ctb);
4564 gen_cast(&cti);
4565 } else {
4566 int t = 0;
4567 save_regs(1);
4568 for(;;) {
4569 t = gvtst(0, t);
4570 if (tok != TOK_LOR) {
4571 vseti(VT_JMP, t);
4572 break;
4574 next();
4575 expr_land();
4581 static void expr_cond(void)
4583 int tt, u, r1, r2, rc, t1, t2, bt1, bt2, islv;
4584 SValue sv;
4585 CType type, type1, type2;
4587 expr_lor();
4588 if (tok == '?') {
4589 next();
4590 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4591 int saved_nocode_wanted = nocode_wanted;
4592 CType boolean;
4593 int c;
4594 boolean.t = VT_BOOL;
4595 vdup();
4596 gen_cast(&boolean);
4597 c = vtop->c.i;
4598 vpop();
4599 if (c) {
4600 if (tok != ':' || !gnu_ext) {
4601 vpop();
4602 gexpr();
4604 skip(':');
4605 nocode_wanted = 1;
4606 expr_cond();
4607 vpop();
4608 nocode_wanted = saved_nocode_wanted;
4609 } else {
4610 vpop();
4611 if (tok != ':' || !gnu_ext) {
4612 nocode_wanted = 1;
4613 gexpr();
4614 vpop();
4615 nocode_wanted = saved_nocode_wanted;
4617 skip(':');
4618 expr_cond();
4621 else {
4622 if (vtop != vstack) {
4623 /* needed to avoid having different registers saved in
4624 each branch */
4625 if (is_float(vtop->type.t)) {
4626 rc = RC_FLOAT;
4627 #ifdef TCC_TARGET_X86_64
4628 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
4629 rc = RC_ST0;
4631 #endif
4633 else
4634 rc = RC_INT;
4635 gv(rc);
4636 save_regs(1);
4638 if (tok == ':' && gnu_ext) {
4639 gv_dup();
4640 tt = gvtst(1, 0);
4641 } else {
4642 tt = gvtst(1, 0);
4643 gexpr();
4645 type1 = vtop->type;
4646 sv = *vtop; /* save value to handle it later */
4647 vtop--; /* no vpop so that FP stack is not flushed */
4648 skip(':');
4649 u = gjmp(0);
4650 gsym(tt);
4651 expr_cond();
4652 type2 = vtop->type;
4654 t1 = type1.t;
4655 bt1 = t1 & VT_BTYPE;
4656 t2 = type2.t;
4657 bt2 = t2 & VT_BTYPE;
4658 /* cast operands to correct type according to ISOC rules */
4659 if (is_float(bt1) || is_float(bt2)) {
4660 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
4661 type.t = VT_LDOUBLE;
4662 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
4663 type.t = VT_DOUBLE;
4664 } else {
4665 type.t = VT_FLOAT;
4667 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
4668 /* cast to biggest op */
4669 type.t = VT_LLONG;
4670 /* convert to unsigned if it does not fit in a long long */
4671 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
4672 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
4673 type.t |= VT_UNSIGNED;
4674 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
4675 /* If one is a null ptr constant the result type
4676 is the other. */
4677 if (is_null_pointer (vtop))
4678 type = type1;
4679 else if (is_null_pointer (&sv))
4680 type = type2;
4681 /* XXX: test pointer compatibility, C99 has more elaborate
4682 rules here. */
4683 else
4684 type = type1;
4685 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
4686 /* XXX: test function pointer compatibility */
4687 type = bt1 == VT_FUNC ? type1 : type2;
4688 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
4689 /* XXX: test structure compatibility */
4690 type = bt1 == VT_STRUCT ? type1 : type2;
4691 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
4692 /* NOTE: as an extension, we accept void on only one side */
4693 type.t = VT_VOID;
4694 } else {
4695 /* integer operations */
4696 type.t = VT_INT;
4697 /* convert to unsigned if it does not fit in an integer */
4698 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
4699 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
4700 type.t |= VT_UNSIGNED;
4702 /* keep structs lvalue by transforming `(expr ? a : b)` to `*(expr ? &a : &b)` so
4703 that `(expr ? a : b).mem` does not error with "lvalue expected" */
4704 islv = (vtop->r & VT_LVAL) && (sv.r & VT_LVAL) && VT_STRUCT == (type.t & VT_BTYPE);
4706 /* now we convert second operand */
4707 gen_cast(&type);
4708 if (islv) {
4709 mk_pointer(&vtop->type);
4710 gaddrof();
4712 else if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4713 gaddrof();
4714 rc = RC_INT;
4715 if (is_float(type.t)) {
4716 rc = RC_FLOAT;
4717 #ifdef TCC_TARGET_X86_64
4718 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
4719 rc = RC_ST0;
4721 #endif
4722 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
4723 /* for long longs, we use fixed registers to avoid having
4724 to handle a complicated move */
4725 rc = RC_IRET;
4728 r2 = gv(rc);
4729 /* this is horrible, but we must also convert first
4730 operand */
4731 tt = gjmp(0);
4732 gsym(u);
4733 /* put again first value and cast it */
4734 *vtop = sv;
4735 gen_cast(&type);
4736 if (islv) {
4737 mk_pointer(&vtop->type);
4738 gaddrof();
4740 else if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4741 gaddrof();
4742 r1 = gv(rc);
4743 move_reg(r2, r1, type.t);
4744 vtop->r = r2;
4745 gsym(tt);
4746 if (islv)
4747 indir();
4752 static void expr_eq(void)
4754 int t;
4756 expr_cond();
4757 if (tok == '=' ||
4758 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
4759 tok == TOK_A_XOR || tok == TOK_A_OR ||
4760 tok == TOK_A_SHL || tok == TOK_A_SAR) {
4761 test_lvalue();
4762 t = tok;
4763 next();
4764 if (t == '=') {
4765 expr_eq();
4766 } else {
4767 vdup();
4768 expr_eq();
4769 gen_op(t & 0x7f);
4771 vstore();
4775 ST_FUNC void gexpr(void)
4777 while (1) {
4778 expr_eq();
4779 if (tok != ',')
4780 break;
4781 vpop();
4782 next();
4786 /* parse an expression and return its type without any side effect. */
4787 static void expr_type(CType *type)
4789 int saved_nocode_wanted;
4791 saved_nocode_wanted = nocode_wanted;
4792 nocode_wanted = 1;
4793 gexpr();
4794 *type = vtop->type;
4795 vpop();
4796 nocode_wanted = saved_nocode_wanted;
4799 /* parse a unary expression and return its type without any side
4800 effect. */
4801 static void unary_type(CType *type)
4803 int a;
4805 a = nocode_wanted;
4806 nocode_wanted = 1;
4807 unary();
4808 *type = vtop->type;
4809 vpop();
4810 nocode_wanted = a;
4813 /* parse a constant expression and return value in vtop. */
4814 static void expr_const1(void)
4816 int a;
4817 a = const_wanted;
4818 const_wanted = 1;
4819 expr_cond();
4820 const_wanted = a;
4823 /* parse an integer constant and return its value. */
4824 ST_FUNC int expr_const(void)
4826 int c;
4827 expr_const1();
4828 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
4829 expect("constant expression");
4830 c = vtop->c.i;
4831 vpop();
4832 return c;
4835 /* return the label token if current token is a label, otherwise
4836 return zero */
4837 static int is_label(void)
4839 int last_tok;
4841 /* fast test first */
4842 if (tok < TOK_UIDENT)
4843 return 0;
4844 /* no need to save tokc because tok is an identifier */
4845 last_tok = tok;
4846 next();
4847 if (tok == ':') {
4848 next();
4849 return last_tok;
4850 } else {
4851 unget_tok(last_tok);
4852 return 0;
4856 static void label_or_decl(int l)
4858 int last_tok;
4860 /* fast test first */
4861 if (tok >= TOK_UIDENT)
4863 /* no need to save tokc because tok is an identifier */
4864 last_tok = tok;
4865 next();
4866 if (tok == ':') {
4867 unget_tok(last_tok);
4868 return;
4870 unget_tok(last_tok);
4872 decl(l);
4875 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
4876 int case_reg, int is_expr)
4878 int a, b, c, d;
4879 Sym *s;
4881 /* generate line number info */
4882 if (tcc_state->do_debug &&
4883 (last_line_num != file->line_num || last_ind != ind)) {
4884 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
4885 last_ind = ind;
4886 last_line_num = file->line_num;
4889 if (is_expr) {
4890 /* default return value is (void) */
4891 vpushi(0);
4892 vtop->type.t = VT_VOID;
4895 if (tok == TOK_IF) {
4896 /* if test */
4897 next();
4898 skip('(');
4899 gexpr();
4900 skip(')');
4901 a = gvtst(1, 0);
4902 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4903 c = tok;
4904 if (c == TOK_ELSE) {
4905 next();
4906 d = gjmp(0);
4907 gsym(a);
4908 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4909 gsym(d); /* patch else jmp */
4910 } else
4911 gsym(a);
4912 } else if (tok == TOK_WHILE) {
4913 next();
4914 d = ind;
4915 vla_sp_restore();
4916 skip('(');
4917 gexpr();
4918 skip(')');
4919 a = gvtst(1, 0);
4920 b = 0;
4921 block(&a, &b, case_sym, def_sym, case_reg, 0);
4922 if(!nocode_wanted)
4923 gjmp_addr(d);
4924 gsym(a);
4925 gsym_addr(b, d);
4926 } else if (tok == '{') {
4927 Sym *llabel;
4928 int block_vla_sp_loc = vla_sp_loc, saved_vlas_in_scope = vlas_in_scope;
4930 next();
4931 /* record local declaration stack position */
4932 s = local_stack;
4933 llabel = local_label_stack;
4934 ++local_scope;
4936 /* handle local labels declarations */
4937 if (tok == TOK_LABEL) {
4938 next();
4939 for(;;) {
4940 if (tok < TOK_UIDENT)
4941 expect("label identifier");
4942 label_push(&local_label_stack, tok, LABEL_DECLARED);
4943 next();
4944 if (tok == ',') {
4945 next();
4946 } else {
4947 skip(';');
4948 break;
4952 while (tok != '}') {
4953 label_or_decl(VT_LOCAL);
4954 if (tok != '}') {
4955 if (is_expr)
4956 vpop();
4957 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
4960 /* pop locally defined labels */
4961 label_pop(&local_label_stack, llabel);
4962 if(is_expr) {
4963 /* XXX: this solution makes only valgrind happy...
4964 triggered by gcc.c-torture/execute/20000917-1.c */
4965 Sym *p;
4966 switch(vtop->type.t & VT_BTYPE) {
4967 /* case VT_PTR: */
4968 /* this breaks a compilation of the linux kernel v2.4.26 */
4969 /* pmd_t *new = ({ __asm__ __volatile__("ud2\n") ; ((pmd_t *)1); }); */
4970 /* Look a commit a80acab: Display error on statement expressions with complex return type */
4971 /* A pointer is not a complex return type */
4972 case VT_STRUCT:
4973 case VT_ENUM:
4974 case VT_FUNC:
4975 for(p=vtop->type.ref;p;p=p->prev)
4976 if(p->prev==s)
4977 tcc_error("unsupported expression type");
4980 /* pop locally defined symbols */
4981 --local_scope;
4982 sym_pop(&local_stack, s);
4984 /* Pop VLA frames and restore stack pointer if required */
4985 if (vlas_in_scope > saved_vlas_in_scope) {
4986 vla_sp_loc = saved_vlas_in_scope ? block_vla_sp_loc : vla_sp_root_loc;
4987 vla_sp_restore();
4989 vlas_in_scope = saved_vlas_in_scope;
4991 next();
4992 } else if (tok == TOK_RETURN) {
4993 next();
4994 if (tok != ';') {
4995 gexpr();
4996 gen_assign_cast(&func_vt);
4997 #ifdef TCC_TARGET_ARM64
4998 // Perhaps it would be better to use this for all backends:
4999 greturn();
5000 #else
5001 if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
5002 CType type, ret_type;
5003 int ret_align, ret_nregs, regsize;
5004 ret_nregs = gfunc_sret(&func_vt, func_var, &ret_type,
5005 &ret_align, &regsize);
5006 if (0 == ret_nregs) {
5007 /* if returning structure, must copy it to implicit
5008 first pointer arg location */
5009 type = func_vt;
5010 mk_pointer(&type);
5011 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
5012 indir();
5013 vswap();
5014 /* copy structure value to pointer */
5015 vstore();
5016 } else {
5017 /* returning structure packed into registers */
5018 int r, size, addr, align;
5019 size = type_size(&func_vt,&align);
5020 if ((vtop->r != (VT_LOCAL | VT_LVAL) ||
5021 (vtop->c.i & (ret_align-1)))
5022 && (align & (ret_align-1))) {
5023 loc = (loc - size) & -ret_align;
5024 addr = loc;
5025 type = func_vt;
5026 vset(&type, VT_LOCAL | VT_LVAL, addr);
5027 vswap();
5028 vstore();
5029 vpop();
5030 vset(&ret_type, VT_LOCAL | VT_LVAL, addr);
5032 vtop->type = ret_type;
5033 if (is_float(ret_type.t))
5034 r = rc_fret(ret_type.t);
5035 else
5036 r = RC_IRET;
5038 for (;;) {
5039 gv(r);
5040 if (--ret_nregs == 0)
5041 break;
5042 /* We assume that when a structure is returned in multiple
5043 registers, their classes are consecutive values of the
5044 suite s(n) = 2^n */
5045 r <<= 1;
5046 vtop->c.i += regsize;
5047 vtop->r = VT_LOCAL | VT_LVAL;
5050 } else if (is_float(func_vt.t)) {
5051 gv(rc_fret(func_vt.t));
5052 } else {
5053 gv(RC_IRET);
5055 #endif
5056 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
5058 skip(';');
5059 rsym = gjmp(rsym); /* jmp */
5060 } else if (tok == TOK_BREAK) {
5061 /* compute jump */
5062 if (!bsym)
5063 tcc_error("cannot break");
5064 *bsym = gjmp(*bsym);
5065 next();
5066 skip(';');
5067 } else if (tok == TOK_CONTINUE) {
5068 /* compute jump */
5069 if (!csym)
5070 tcc_error("cannot continue");
5071 vla_sp_restore_root();
5072 *csym = gjmp(*csym);
5073 next();
5074 skip(';');
5075 } else if (tok == TOK_FOR) {
5076 int e;
5077 next();
5078 skip('(');
5079 s = local_stack;
5080 ++local_scope;
5081 if (tok != ';') {
5082 /* c99 for-loop init decl? */
5083 if (!decl0(VT_LOCAL, 1)) {
5084 /* no, regular for-loop init expr */
5085 gexpr();
5086 vpop();
5089 skip(';');
5090 d = ind;
5091 c = ind;
5092 vla_sp_restore();
5093 a = 0;
5094 b = 0;
5095 if (tok != ';') {
5096 gexpr();
5097 a = gvtst(1, 0);
5099 skip(';');
5100 if (tok != ')') {
5101 e = gjmp(0);
5102 c = ind;
5103 vla_sp_restore();
5104 gexpr();
5105 vpop();
5106 gjmp_addr(d);
5107 gsym(e);
5109 skip(')');
5110 block(&a, &b, case_sym, def_sym, case_reg, 0);
5111 if(!nocode_wanted)
5112 gjmp_addr(c);
5113 gsym(a);
5114 gsym_addr(b, c);
5115 --local_scope;
5116 sym_pop(&local_stack, s);
5118 } else
5119 if (tok == TOK_DO) {
5120 next();
5121 a = 0;
5122 b = 0;
5123 d = ind;
5124 vla_sp_restore();
5125 block(&a, &b, case_sym, def_sym, case_reg, 0);
5126 skip(TOK_WHILE);
5127 skip('(');
5128 gsym(b);
5129 gexpr();
5130 c = gvtst(0, 0);
5131 gsym_addr(c, d);
5132 skip(')');
5133 gsym(a);
5134 skip(';');
5135 } else
5136 if (tok == TOK_SWITCH) {
5137 next();
5138 skip('(');
5139 gexpr();
5140 /* XXX: other types than integer */
5141 case_reg = gv(RC_INT);
5142 vpop();
5143 skip(')');
5144 a = 0;
5145 b = gjmp(0); /* jump to first case */
5146 c = 0;
5147 block(&a, csym, &b, &c, case_reg, 0);
5148 /* if no default, jmp after switch */
5149 if (c == 0)
5150 c = ind;
5151 /* default label */
5152 gsym_addr(b, c);
5153 /* break label */
5154 gsym(a);
5155 } else
5156 if (tok == TOK_CASE) {
5157 int v1, v2;
5158 if (!case_sym)
5159 expect("switch");
5160 next();
5161 v1 = expr_const();
5162 v2 = v1;
5163 if (gnu_ext && tok == TOK_DOTS) {
5164 next();
5165 v2 = expr_const();
5166 if (v2 < v1)
5167 tcc_warning("empty case range");
5169 /* since a case is like a label, we must skip it with a jmp */
5170 b = gjmp(0);
5171 gsym(*case_sym);
5172 vseti(case_reg, 0);
5173 vdup();
5174 vpushi(v1);
5175 if (v1 == v2) {
5176 gen_op(TOK_EQ);
5177 *case_sym = gtst(1, 0);
5178 } else {
5179 gen_op(TOK_GE);
5180 *case_sym = gtst(1, 0);
5181 vseti(case_reg, 0);
5182 vpushi(v2);
5183 gen_op(TOK_LE);
5184 *case_sym = gtst(1, *case_sym);
5186 case_reg = gv(RC_INT);
5187 vpop();
5188 gsym(b);
5189 skip(':');
5190 is_expr = 0;
5191 goto block_after_label;
5192 } else
5193 if (tok == TOK_DEFAULT) {
5194 next();
5195 skip(':');
5196 if (!def_sym)
5197 expect("switch");
5198 if (*def_sym)
5199 tcc_error("too many 'default'");
5200 *def_sym = ind;
5201 is_expr = 0;
5202 goto block_after_label;
5203 } else
5204 if (tok == TOK_GOTO) {
5205 next();
5206 if (tok == '*' && gnu_ext) {
5207 /* computed goto */
5208 next();
5209 gexpr();
5210 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
5211 expect("pointer");
5212 ggoto();
5213 } else if (tok >= TOK_UIDENT) {
5214 s = label_find(tok);
5215 /* put forward definition if needed */
5216 if (!s) {
5217 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
5218 } else {
5219 if (s->r == LABEL_DECLARED)
5220 s->r = LABEL_FORWARD;
5222 vla_sp_restore_root();
5223 if (s->r & LABEL_FORWARD)
5224 s->jnext = gjmp(s->jnext);
5225 else
5226 gjmp_addr(s->jnext);
5227 next();
5228 } else {
5229 expect("label identifier");
5231 skip(';');
5232 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
5233 asm_instr();
5234 } else {
5235 b = is_label();
5236 if (b) {
5237 /* label case */
5238 s = label_find(b);
5239 if (s) {
5240 if (s->r == LABEL_DEFINED)
5241 tcc_error("duplicate label '%s'", get_tok_str(s->v, NULL));
5242 gsym(s->jnext);
5243 s->r = LABEL_DEFINED;
5244 } else {
5245 s = label_push(&global_label_stack, b, LABEL_DEFINED);
5247 s->jnext = ind;
5248 vla_sp_restore();
5249 /* we accept this, but it is a mistake */
5250 block_after_label:
5251 if (tok == '}') {
5252 tcc_warning("deprecated use of label at end of compound statement");
5253 } else {
5254 if (is_expr)
5255 vpop();
5256 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
5258 } else {
5259 /* expression case */
5260 if (tok != ';') {
5261 if (is_expr) {
5262 vpop();
5263 gexpr();
5264 } else {
5265 gexpr();
5266 vpop();
5269 skip(';');
5274 /* t is the array or struct type. c is the array or struct
5275 address. cur_index/cur_field is the pointer to the current
5276 value. 'size_only' is true if only size info is needed (only used
5277 in arrays) */
5278 static void decl_designator(CType *type, Section *sec, unsigned long c,
5279 int *cur_index, Sym **cur_field,
5280 int size_only)
5282 Sym *s, *f;
5283 int notfirst, index, index_last, align, l, nb_elems, elem_size;
5284 CType type1;
5286 notfirst = 0;
5287 elem_size = 0;
5288 nb_elems = 1;
5289 if (gnu_ext && (l = is_label()) != 0)
5290 goto struct_field;
5291 while (tok == '[' || tok == '.') {
5292 if (tok == '[') {
5293 if (!(type->t & VT_ARRAY))
5294 expect("array type");
5295 s = type->ref;
5296 next();
5297 index = expr_const();
5298 if (index < 0 || (s->c >= 0 && index >= s->c))
5299 expect("invalid index");
5300 if (tok == TOK_DOTS && gnu_ext) {
5301 next();
5302 index_last = expr_const();
5303 if (index_last < 0 ||
5304 (s->c >= 0 && index_last >= s->c) ||
5305 index_last < index)
5306 expect("invalid index");
5307 } else {
5308 index_last = index;
5310 skip(']');
5311 if (!notfirst)
5312 *cur_index = index_last;
5313 type = pointed_type(type);
5314 elem_size = type_size(type, &align);
5315 c += index * elem_size;
5316 /* NOTE: we only support ranges for last designator */
5317 nb_elems = index_last - index + 1;
5318 if (nb_elems != 1) {
5319 notfirst = 1;
5320 break;
5322 } else {
5323 next();
5324 l = tok;
5325 next();
5326 struct_field:
5327 if ((type->t & VT_BTYPE) != VT_STRUCT)
5328 expect("struct/union type");
5329 s = type->ref;
5330 l |= SYM_FIELD;
5331 f = s->next;
5332 while (f) {
5333 if (f->v == l)
5334 break;
5335 f = f->next;
5337 if (!f)
5338 expect("field");
5339 if (!notfirst)
5340 *cur_field = f;
5341 /* XXX: fix this mess by using explicit storage field */
5342 type1 = f->type;
5343 type1.t |= (type->t & ~VT_TYPE);
5344 type = &type1;
5345 c += f->c;
5347 notfirst = 1;
5349 if (notfirst) {
5350 if (tok == '=') {
5351 next();
5352 } else {
5353 if (!gnu_ext)
5354 expect("=");
5356 } else {
5357 if (type->t & VT_ARRAY) {
5358 index = *cur_index;
5359 type = pointed_type(type);
5360 c += index * type_size(type, &align);
5361 } else {
5362 f = *cur_field;
5363 if (!f)
5364 tcc_error("too many field init");
5365 /* XXX: fix this mess by using explicit storage field */
5366 type1 = f->type;
5367 type1.t |= (type->t & ~VT_TYPE);
5368 type = &type1;
5369 c += f->c;
5372 decl_initializer(type, sec, c, 0, size_only);
5374 /* XXX: make it more general */
5375 if (!size_only && nb_elems > 1) {
5376 unsigned long c_end;
5377 uint8_t *src, *dst;
5378 int i;
5380 if (!sec)
5381 tcc_error("range init not supported yet for dynamic storage");
5382 c_end = c + nb_elems * elem_size;
5383 if (c_end > sec->data_allocated)
5384 section_realloc(sec, c_end);
5385 src = sec->data + c;
5386 dst = src;
5387 for(i = 1; i < nb_elems; i++) {
5388 dst += elem_size;
5389 memcpy(dst, src, elem_size);
5394 #define EXPR_VAL 0
5395 #define EXPR_CONST 1
5396 #define EXPR_ANY 2
5398 /* store a value or an expression directly in global data or in local array */
5399 static void init_putv(CType *type, Section *sec, unsigned long c,
5400 int v, int expr_type)
5402 int saved_global_expr, bt, bit_pos, bit_size;
5403 void *ptr;
5404 unsigned long long bit_mask;
5405 CType dtype;
5407 switch(expr_type) {
5408 case EXPR_VAL:
5409 vpushi(v);
5410 break;
5411 case EXPR_CONST:
5412 /* compound literals must be allocated globally in this case */
5413 saved_global_expr = global_expr;
5414 global_expr = 1;
5415 expr_const1();
5416 global_expr = saved_global_expr;
5417 /* NOTE: symbols are accepted */
5418 if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
5419 tcc_error("initializer element is not constant");
5420 break;
5421 case EXPR_ANY:
5422 expr_eq();
5423 break;
5426 dtype = *type;
5427 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
5429 if (sec) {
5430 /* XXX: not portable */
5431 /* XXX: generate error if incorrect relocation */
5432 gen_assign_cast(&dtype);
5433 bt = type->t & VT_BTYPE;
5434 /* we'll write at most 16 bytes */
5435 if (c + 16 > sec->data_allocated) {
5436 section_realloc(sec, c + 16);
5438 ptr = sec->data + c;
5439 /* XXX: make code faster ? */
5440 if (!(type->t & VT_BITFIELD)) {
5441 bit_pos = 0;
5442 bit_size = 32;
5443 bit_mask = -1LL;
5444 } else {
5445 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5446 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
5447 bit_mask = (1LL << bit_size) - 1;
5449 if ((vtop->r & VT_SYM) &&
5450 (bt == VT_BYTE ||
5451 bt == VT_SHORT ||
5452 bt == VT_DOUBLE ||
5453 bt == VT_LDOUBLE ||
5454 bt == VT_LLONG ||
5455 (bt == VT_INT && bit_size != 32)))
5456 tcc_error("initializer element is not computable at load time");
5457 switch(bt) {
5458 /* XXX: when cross-compiling we assume that each type has the
5459 same representation on host and target, which is likely to
5460 be wrong in the case of long double */
5461 case VT_BOOL:
5462 vtop->c.i = (vtop->c.i != 0);
5463 case VT_BYTE:
5464 *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5465 break;
5466 case VT_SHORT:
5467 *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5468 break;
5469 case VT_DOUBLE:
5470 *(double *)ptr = vtop->c.d;
5471 break;
5472 case VT_LDOUBLE:
5473 *(long double *)ptr = vtop->c.ld;
5474 break;
5475 case VT_LLONG:
5476 *(long long *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5477 break;
5478 case VT_PTR: {
5479 addr_t val = (vtop->c.i & bit_mask) << bit_pos;
5480 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
5481 if (vtop->r & VT_SYM)
5482 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
5483 else
5484 *(addr_t *)ptr |= val;
5485 #else
5486 if (vtop->r & VT_SYM)
5487 greloc(sec, vtop->sym, c, R_DATA_PTR);
5488 *(addr_t *)ptr |= val;
5489 #endif
5490 break;
5492 default: {
5493 int val = (vtop->c.i & bit_mask) << bit_pos;
5494 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
5495 if (vtop->r & VT_SYM)
5496 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
5497 else
5498 *(int *)ptr |= val;
5499 #else
5500 if (vtop->r & VT_SYM)
5501 greloc(sec, vtop->sym, c, R_DATA_PTR);
5502 *(int *)ptr |= val;
5503 #endif
5504 break;
5507 vtop--;
5508 } else {
5509 vset(&dtype, VT_LOCAL|VT_LVAL, c);
5510 vswap();
5511 vstore();
5512 vpop();
5516 /* put zeros for variable based init */
5517 static void init_putz(CType *t, Section *sec, unsigned long c, int size)
5519 if (sec) {
5520 /* nothing to do because globals are already set to zero */
5521 } else {
5522 vpush_global_sym(&func_old_type, TOK_memset);
5523 vseti(VT_LOCAL, c);
5524 #ifdef TCC_TARGET_ARM
5525 vpushs(size);
5526 vpushi(0);
5527 #else
5528 vpushi(0);
5529 vpushs(size);
5530 #endif
5531 gfunc_call(3);
5535 /* 't' contains the type and storage info. 'c' is the offset of the
5536 object in section 'sec'. If 'sec' is NULL, it means stack based
5537 allocation. 'first' is true if array '{' must be read (multi
5538 dimension implicit array init handling). 'size_only' is true if
5539 size only evaluation is wanted (only for arrays). */
5540 static void decl_initializer(CType *type, Section *sec, unsigned long c,
5541 int first, int size_only)
5543 int index, array_length, n, no_oblock, nb, parlevel, parlevel1, i;
5544 int size1, align1, expr_type;
5545 Sym *s, *f;
5546 CType *t1;
5548 if (type->t & VT_VLA) {
5549 int a;
5551 /* save current stack pointer */
5552 if (vlas_in_scope == 0) {
5553 if (vla_sp_root_loc == -1)
5554 vla_sp_root_loc = (loc -= PTR_SIZE);
5555 gen_vla_sp_save(vla_sp_root_loc);
5558 vla_runtime_type_size(type, &a);
5559 gen_vla_alloc(type, a);
5560 gen_vla_sp_save(c);
5561 vla_sp_loc = c;
5562 vlas_in_scope++;
5563 } else if (type->t & VT_ARRAY) {
5564 s = type->ref;
5565 n = s->c;
5566 array_length = 0;
5567 t1 = pointed_type(type);
5568 size1 = type_size(t1, &align1);
5570 no_oblock = 1;
5571 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
5572 tok == '{') {
5573 if (tok != '{')
5574 tcc_error("character array initializer must be a literal,"
5575 " optionally enclosed in braces");
5576 skip('{');
5577 no_oblock = 0;
5580 /* only parse strings here if correct type (otherwise: handle
5581 them as ((w)char *) expressions */
5582 if ((tok == TOK_LSTR &&
5583 #ifdef TCC_TARGET_PE
5584 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
5585 #else
5586 (t1->t & VT_BTYPE) == VT_INT
5587 #endif
5588 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
5589 while (tok == TOK_STR || tok == TOK_LSTR) {
5590 int cstr_len, ch;
5592 /* compute maximum number of chars wanted */
5593 if (tok == TOK_STR)
5594 cstr_len = tokc.str.size;
5595 else
5596 cstr_len = tokc.str.size / sizeof(nwchar_t);
5597 cstr_len--;
5598 nb = cstr_len;
5599 if (n >= 0 && nb > (n - array_length))
5600 nb = n - array_length;
5601 if (!size_only) {
5602 if (cstr_len > nb)
5603 tcc_warning("initializer-string for array is too long");
5604 /* in order to go faster for common case (char
5605 string in global variable, we handle it
5606 specifically */
5607 if (sec && tok == TOK_STR && size1 == 1) {
5608 memcpy(sec->data + c + array_length, tokc.str.data, nb);
5609 } else {
5610 for(i=0;i<nb;i++) {
5611 if (tok == TOK_STR)
5612 ch = ((unsigned char *)tokc.str.data)[i];
5613 else
5614 ch = ((nwchar_t *)tokc.str.data)[i];
5615 init_putv(t1, sec, c + (array_length + i) * size1,
5616 ch, EXPR_VAL);
5620 array_length += nb;
5621 next();
5623 /* only add trailing zero if enough storage (no
5624 warning in this case since it is standard) */
5625 if (n < 0 || array_length < n) {
5626 if (!size_only) {
5627 init_putv(t1, sec, c + (array_length * size1), 0, EXPR_VAL);
5629 array_length++;
5631 } else {
5632 index = 0;
5633 while (tok != '}') {
5634 decl_designator(type, sec, c, &index, NULL, size_only);
5635 if (n >= 0 && index >= n)
5636 tcc_error("index too large");
5637 /* must put zero in holes (note that doing it that way
5638 ensures that it even works with designators) */
5639 if (!size_only && array_length < index) {
5640 init_putz(t1, sec, c + array_length * size1,
5641 (index - array_length) * size1);
5643 index++;
5644 if (index > array_length)
5645 array_length = index;
5646 /* special test for multi dimensional arrays (may not
5647 be strictly correct if designators are used at the
5648 same time) */
5649 if (index >= n && no_oblock)
5650 break;
5651 if (tok == '}')
5652 break;
5653 skip(',');
5656 if (!no_oblock)
5657 skip('}');
5658 /* put zeros at the end */
5659 if (!size_only && n >= 0 && array_length < n) {
5660 init_putz(t1, sec, c + array_length * size1,
5661 (n - array_length) * size1);
5663 /* patch type size if needed */
5664 if (n < 0)
5665 s->c = array_length;
5666 } else if ((type->t & VT_BTYPE) == VT_STRUCT &&
5667 (sec || !first || tok == '{')) {
5669 /* NOTE: the previous test is a specific case for automatic
5670 struct/union init */
5671 /* XXX: union needs only one init */
5673 int par_count = 0;
5674 if (tok == '(') {
5675 AttributeDef ad1;
5676 CType type1;
5677 next();
5678 if (tcc_state->old_struct_init_code) {
5679 /* an old version of struct initialization.
5680 It have a problems. But with a new version
5681 linux 2.4.26 can't load ramdisk.
5683 while (tok == '(') {
5684 par_count++;
5685 next();
5687 if (!parse_btype(&type1, &ad1))
5688 expect("cast");
5689 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
5690 #if 0
5691 if (!is_assignable_types(type, &type1))
5692 tcc_error("invalid type for cast");
5693 #endif
5694 skip(')');
5696 else
5698 if (tok != '(') {
5699 if (!parse_btype(&type1, &ad1))
5700 expect("cast");
5701 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
5702 #if 0
5703 if (!is_assignable_types(type, &type1))
5704 tcc_error("invalid type for cast");
5705 #endif
5706 skip(')');
5707 } else
5708 unget_tok(tok);
5712 no_oblock = 1;
5713 if (first || tok == '{') {
5714 skip('{');
5715 no_oblock = 0;
5717 s = type->ref;
5718 f = s->next;
5719 array_length = 0;
5720 index = 0;
5721 n = s->c;
5722 while (tok != '}') {
5723 decl_designator(type, sec, c, NULL, &f, size_only);
5724 index = f->c;
5725 if (!size_only && array_length < index) {
5726 init_putz(type, sec, c + array_length,
5727 index - array_length);
5729 index = index + type_size(&f->type, &align1);
5730 if (index > array_length)
5731 array_length = index;
5733 /* gr: skip fields from same union - ugly. */
5734 while (f->next) {
5735 int align = 0;
5736 int f_size = type_size(&f->type, &align);
5737 int f_type = (f->type.t & VT_BTYPE);
5739 ///printf("index: %2d %08x -- %2d %08x\n", f->c, f->type.t, f->next->c, f->next->type.t);
5740 /* test for same offset */
5741 if (f->next->c != f->c)
5742 break;
5743 if ((f_type == VT_STRUCT) && (f_size == 0)) {
5745 Lets assume a structure of size 0 can't be a member of the union.
5746 This allow to compile the following code from a linux kernel v2.4.26
5747 typedef struct { } rwlock_t;
5748 struct fs_struct {
5749 int count;
5750 rwlock_t lock;
5751 int umask;
5753 struct fs_struct init_fs = { { (1) }, (rwlock_t) {}, 0022, };
5754 tcc-0.9.23 can succesfully compile this version of the kernel.
5755 gcc don't have problems with this code too.
5757 break;
5759 /* if yes, test for bitfield shift */
5760 if ((f->type.t & VT_BITFIELD) && (f->next->type.t & VT_BITFIELD)) {
5761 int bit_pos_1 = (f->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5762 int bit_pos_2 = (f->next->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5763 //printf("bitfield %d %d\n", bit_pos_1, bit_pos_2);
5764 if (bit_pos_1 != bit_pos_2)
5765 break;
5767 f = f->next;
5770 f = f->next;
5771 if (no_oblock && f == NULL)
5772 break;
5773 if (tok == '}')
5774 break;
5775 skip(',');
5777 /* put zeros at the end */
5778 if (!size_only && array_length < n) {
5779 init_putz(type, sec, c + array_length,
5780 n - array_length);
5782 if (!no_oblock)
5783 skip('}');
5784 while (par_count) {
5785 skip(')');
5786 par_count--;
5788 } else if (tok == '{') {
5789 next();
5790 decl_initializer(type, sec, c, first, size_only);
5791 skip('}');
5792 } else if (size_only) {
5793 /* just skip expression */
5794 parlevel = parlevel1 = 0;
5795 while ((parlevel > 0 || parlevel1 > 0 ||
5796 (tok != '}' && tok != ',')) && tok != -1) {
5797 if (tok == '(')
5798 parlevel++;
5799 else if (tok == ')') {
5800 if (parlevel == 0 && parlevel1 == 0)
5801 break;
5802 parlevel--;
5804 else if (tok == '{')
5805 parlevel1++;
5806 else if (tok == '}') {
5807 if (parlevel == 0 && parlevel1 == 0)
5808 break;
5809 parlevel1--;
5811 next();
5813 } else {
5814 /* currently, we always use constant expression for globals
5815 (may change for scripting case) */
5816 expr_type = EXPR_CONST;
5817 if (!sec)
5818 expr_type = EXPR_ANY;
5819 init_putv(type, sec, c, 0, expr_type);
5823 /* parse an initializer for type 't' if 'has_init' is non zero, and
5824 allocate space in local or global data space ('r' is either
5825 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
5826 variable 'v' of scope 'scope' is declared before initializers
5827 are parsed. If 'v' is zero, then a reference to the new object
5828 is put in the value stack. If 'has_init' is 2, a special parsing
5829 is done to handle string constants. */
5830 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
5831 int has_init, int v, int scope)
5833 int size, align, addr, data_offset;
5834 int level;
5835 ParseState saved_parse_state = {0};
5836 TokenString init_str;
5837 Section *sec;
5838 Sym *flexible_array;
5840 flexible_array = NULL;
5841 if ((type->t & VT_BTYPE) == VT_STRUCT) {
5842 Sym *field = type->ref->next;
5843 if (field) {
5844 while (field->next)
5845 field = field->next;
5846 if (field->type.t & VT_ARRAY && field->type.ref->c < 0)
5847 flexible_array = field;
5851 size = type_size(type, &align);
5852 /* If unknown size, we must evaluate it before
5853 evaluating initializers because
5854 initializers can generate global data too
5855 (e.g. string pointers or ISOC99 compound
5856 literals). It also simplifies local
5857 initializers handling */
5858 tok_str_new(&init_str);
5859 if (size < 0 || (flexible_array && has_init)) {
5860 if (!has_init)
5861 tcc_error("unknown type size");
5862 /* get all init string */
5863 if (has_init == 2) {
5864 /* only get strings */
5865 while (tok == TOK_STR || tok == TOK_LSTR) {
5866 tok_str_add_tok(&init_str);
5867 next();
5869 } else {
5870 level = 0;
5871 while (level > 0 || (tok != ',' && tok != ';')) {
5872 if (tok < 0)
5873 tcc_error("unexpected end of file in initializer");
5874 tok_str_add_tok(&init_str);
5875 if (tok == '{')
5876 level++;
5877 else if (tok == '}') {
5878 level--;
5879 if (level <= 0) {
5880 next();
5881 break;
5884 next();
5887 tok_str_add(&init_str, -1);
5888 tok_str_add(&init_str, 0);
5890 /* compute size */
5891 save_parse_state(&saved_parse_state);
5893 begin_macro(&init_str, 0);
5894 next();
5895 decl_initializer(type, NULL, 0, 1, 1);
5896 /* prepare second initializer parsing */
5897 macro_ptr = init_str.str;
5898 next();
5900 /* if still unknown size, error */
5901 size = type_size(type, &align);
5902 if (size < 0)
5903 tcc_error("unknown type size");
5905 /* If there's a flex member and it was used in the initializer
5906 adjust size. */
5907 if (flexible_array &&
5908 flexible_array->type.ref->c > 0)
5909 size += flexible_array->type.ref->c
5910 * pointed_size(&flexible_array->type);
5911 /* take into account specified alignment if bigger */
5912 if (ad->a.aligned) {
5913 if (ad->a.aligned > align)
5914 align = ad->a.aligned;
5915 } else if (ad->a.packed) {
5916 align = 1;
5918 if ((r & VT_VALMASK) == VT_LOCAL) {
5919 sec = NULL;
5920 #ifdef CONFIG_TCC_BCHECK
5921 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5922 loc--;
5924 #endif
5925 loc = (loc - size) & -align;
5926 addr = loc;
5927 #ifdef CONFIG_TCC_BCHECK
5928 /* handles bounds */
5929 /* XXX: currently, since we do only one pass, we cannot track
5930 '&' operators, so we add only arrays */
5931 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5932 addr_t *bounds_ptr;
5933 /* add padding between regions */
5934 loc--;
5935 /* then add local bound info */
5936 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(addr_t));
5937 bounds_ptr[0] = addr;
5938 bounds_ptr[1] = size;
5940 #endif
5941 if (v) {
5942 /* local variable */
5943 sym_push(v, type, r, addr);
5944 } else {
5945 /* push local reference */
5946 vset(type, r, addr);
5948 } else {
5949 Sym *sym;
5951 sym = NULL;
5952 if (v && scope == VT_CONST) {
5953 /* see if the symbol was already defined */
5954 sym = sym_find(v);
5955 if (sym) {
5956 if (!is_compatible_types(&sym->type, type))
5957 tcc_error("incompatible types for redefinition of '%s'",
5958 get_tok_str(v, NULL));
5959 if (sym->type.t & VT_EXTERN) {
5960 /* if the variable is extern, it was not allocated */
5961 sym->type.t &= ~VT_EXTERN;
5962 /* set array size if it was omitted in extern
5963 declaration */
5964 if ((sym->type.t & VT_ARRAY) &&
5965 sym->type.ref->c < 0 &&
5966 type->ref->c >= 0)
5967 sym->type.ref->c = type->ref->c;
5968 } else {
5969 /* we accept several definitions of the same
5970 global variable. this is tricky, because we
5971 must play with the SHN_COMMON type of the symbol */
5972 /* XXX: should check if the variable was already
5973 initialized. It is incorrect to initialized it
5974 twice */
5975 /* no init data, we won't add more to the symbol */
5976 if (!has_init)
5977 goto no_alloc;
5982 /* allocate symbol in corresponding section */
5983 sec = ad->section;
5984 if (!sec) {
5985 if (has_init)
5986 sec = data_section;
5987 else if (tcc_state->nocommon)
5988 sec = bss_section;
5990 if (sec) {
5991 data_offset = sec->data_offset;
5992 data_offset = (data_offset + align - 1) & -align;
5993 addr = data_offset;
5994 /* very important to increment global pointer at this time
5995 because initializers themselves can create new initializers */
5996 data_offset += size;
5997 #ifdef CONFIG_TCC_BCHECK
5998 /* add padding if bound check */
5999 if (tcc_state->do_bounds_check)
6000 data_offset++;
6001 #endif
6002 sec->data_offset = data_offset;
6003 /* allocate section space to put the data */
6004 if (sec->sh_type != SHT_NOBITS &&
6005 data_offset > sec->data_allocated)
6006 section_realloc(sec, data_offset);
6007 /* align section if needed */
6008 if (align > sec->sh_addralign)
6009 sec->sh_addralign = align;
6010 } else {
6011 addr = 0; /* avoid warning */
6014 if (v) {
6015 if (scope != VT_CONST || !sym) {
6016 sym = sym_push(v, type, r | VT_SYM, 0);
6017 sym->asm_label = ad->asm_label;
6019 /* update symbol definition */
6020 if (sec) {
6021 put_extern_sym(sym, sec, addr, size);
6022 } else {
6023 ElfW(Sym) *esym;
6024 /* put a common area */
6025 put_extern_sym(sym, NULL, align, size);
6026 /* XXX: find a nicer way */
6027 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
6028 esym->st_shndx = SHN_COMMON;
6030 } else {
6031 /* push global reference */
6032 sym = get_sym_ref(type, sec, addr, size);
6033 vpushsym(type, sym);
6035 /* patch symbol weakness */
6036 if (type->t & VT_WEAK)
6037 weaken_symbol(sym);
6038 apply_visibility(sym, type);
6039 #ifdef CONFIG_TCC_BCHECK
6040 /* handles bounds now because the symbol must be defined
6041 before for the relocation */
6042 if (tcc_state->do_bounds_check) {
6043 addr_t *bounds_ptr;
6045 greloc(bounds_section, sym, bounds_section->data_offset, R_DATA_PTR);
6046 /* then add global bound info */
6047 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(addr_t));
6048 bounds_ptr[0] = 0; /* relocated */
6049 bounds_ptr[1] = size;
6051 #endif
6053 if (has_init || (type->t & VT_VLA)) {
6054 decl_initializer(type, sec, addr, 1, 0);
6055 /* restore parse state if needed */
6056 if (init_str.str) {
6057 end_macro();
6058 restore_parse_state(&saved_parse_state);
6060 /* patch flexible array member size back to -1, */
6061 /* for possible subsequent similar declarations */
6062 if (flexible_array)
6063 flexible_array->type.ref->c = -1;
6065 no_alloc: ;
6068 static void put_func_debug(Sym *sym)
6070 char buf[512];
6072 /* stabs info */
6073 /* XXX: we put here a dummy type */
6074 snprintf(buf, sizeof(buf), "%s:%c1",
6075 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
6076 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
6077 cur_text_section, sym->c);
6078 /* //gr gdb wants a line at the function */
6079 put_stabn(N_SLINE, 0, file->line_num, 0);
6080 last_ind = 0;
6081 last_line_num = 0;
6084 /* parse an old style function declaration list */
6085 /* XXX: check multiple parameter */
6086 static void func_decl_list(Sym *func_sym)
6088 AttributeDef ad;
6089 int v;
6090 Sym *s;
6091 CType btype, type;
6093 /* parse each declaration */
6094 while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF &&
6095 tok != TOK_ASM1 && tok != TOK_ASM2 && tok != TOK_ASM3) {
6096 if (!parse_btype(&btype, &ad))
6097 expect("declaration list");
6098 if (((btype.t & VT_BTYPE) == VT_ENUM ||
6099 (btype.t & VT_BTYPE) == VT_STRUCT) &&
6100 tok == ';') {
6101 /* we accept no variable after */
6102 } else {
6103 for(;;) {
6104 type = btype;
6105 type_decl(&type, &ad, &v, TYPE_DIRECT);
6106 /* find parameter in function parameter list */
6107 s = func_sym->next;
6108 while (s != NULL) {
6109 if ((s->v & ~SYM_FIELD) == v)
6110 goto found;
6111 s = s->next;
6113 tcc_error("declaration for parameter '%s' but no such parameter",
6114 get_tok_str(v, NULL));
6115 found:
6116 /* check that no storage specifier except 'register' was given */
6117 if (type.t & VT_STORAGE)
6118 tcc_error("storage class specified for '%s'", get_tok_str(v, NULL));
6119 convert_parameter_type(&type);
6120 /* we can add the type (NOTE: it could be local to the function) */
6121 s->type = type;
6122 /* accept other parameters */
6123 if (tok == ',')
6124 next();
6125 else
6126 break;
6129 skip(';');
6133 /* parse a function defined by symbol 'sym' and generate its code in
6134 'cur_text_section' */
6135 static void gen_function(Sym *sym)
6137 int saved_nocode_wanted = nocode_wanted;
6139 nocode_wanted = 0;
6140 ind = cur_text_section->data_offset;
6141 /* NOTE: we patch the symbol size later */
6142 put_extern_sym(sym, cur_text_section, ind, 0);
6143 funcname = get_tok_str(sym->v, NULL);
6144 func_ind = ind;
6145 /* Initialize VLA state */
6146 vla_sp_loc = -1;
6147 vla_sp_root_loc = -1;
6148 /* put debug symbol */
6149 if (tcc_state->do_debug)
6150 put_func_debug(sym);
6152 /* push a dummy symbol to enable local sym storage */
6153 sym_push2(&local_stack, SYM_FIELD, 0, 0);
6154 local_scope = 1; /* for function parameters */
6155 gfunc_prolog(&sym->type);
6156 local_scope = 0;
6158 #ifdef CONFIG_TCC_BCHECK
6159 if (tcc_state->do_bounds_check && !strcmp(funcname, "main")) {
6160 int i;
6161 Sym *sym;
6162 for (i = 0, sym = local_stack; i < 2; i++, sym = sym->prev) {
6163 if (sym->v & SYM_FIELD || sym->prev->v & SYM_FIELD)
6164 break;
6165 vpush_global_sym(&func_old_type, TOK___bound_main_arg);
6166 vset(&sym->type, sym->r, sym->c);
6167 gfunc_call(1);
6170 #endif
6171 rsym = 0;
6172 block(NULL, NULL, NULL, NULL, 0, 0);
6173 gsym(rsym);
6174 gfunc_epilog();
6175 cur_text_section->data_offset = ind;
6176 label_pop(&global_label_stack, NULL);
6177 /* reset local stack */
6178 local_scope = 0;
6179 sym_pop(&local_stack, NULL);
6180 /* end of function */
6181 /* patch symbol size */
6182 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
6183 ind - func_ind;
6184 /* patch symbol weakness (this definition overrules any prototype) */
6185 if (sym->type.t & VT_WEAK)
6186 weaken_symbol(sym);
6187 apply_visibility(sym, &sym->type);
6188 if (tcc_state->do_debug) {
6189 put_stabn(N_FUN, 0, 0, ind - func_ind);
6191 /* It's better to crash than to generate wrong code */
6192 cur_text_section = NULL;
6193 funcname = ""; /* for safety */
6194 func_vt.t = VT_VOID; /* for safety */
6195 func_var = 0; /* for safety */
6196 ind = 0; /* for safety */
6197 nocode_wanted = saved_nocode_wanted;
6198 check_vstack();
6201 ST_FUNC void gen_inline_functions(void)
6203 Sym *sym;
6204 int inline_generated, i, ln;
6205 struct InlineFunc *fn;
6207 ln = file->line_num;
6208 /* iterate while inline function are referenced */
6209 for(;;) {
6210 inline_generated = 0;
6211 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
6212 fn = tcc_state->inline_fns[i];
6213 sym = fn->sym;
6214 if (sym && sym->c) {
6215 /* the function was used: generate its code and
6216 convert it to a normal function */
6217 fn->sym = NULL;
6218 if (file)
6219 pstrcpy(file->filename, sizeof file->filename, fn->filename);
6220 sym->r = VT_SYM | VT_CONST;
6221 sym->type.t &= ~VT_INLINE;
6223 begin_macro(&fn->func_str, 0);
6224 next();
6225 cur_text_section = text_section;
6226 gen_function(sym);
6227 end_macro();
6229 inline_generated = 1;
6232 if (!inline_generated)
6233 break;
6235 file->line_num = ln;
6236 /* free tokens of unused inline functions */
6237 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
6238 fn = tcc_state->inline_fns[i];
6239 if (fn->sym)
6240 tok_str_free(fn->func_str.str);
6242 dynarray_reset(&tcc_state->inline_fns, &tcc_state->nb_inline_fns);
6245 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
6246 static int decl0(int l, int is_for_loop_init)
6248 int v, has_init, r;
6249 CType type, btype;
6250 Sym *sym;
6251 AttributeDef ad;
6253 while (1) {
6254 if (!parse_btype(&btype, &ad)) {
6255 if (is_for_loop_init)
6256 return 0;
6257 /* skip redundant ';' */
6258 /* XXX: find more elegant solution */
6259 if (tok == ';') {
6260 next();
6261 continue;
6263 if (l == VT_CONST &&
6264 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
6265 /* global asm block */
6266 asm_global_instr();
6267 continue;
6269 /* special test for old K&R protos without explicit int
6270 type. Only accepted when defining global data */
6271 if (l == VT_LOCAL || tok < TOK_DEFINE)
6272 break;
6273 btype.t = VT_INT;
6275 if (((btype.t & VT_BTYPE) == VT_ENUM ||
6276 (btype.t & VT_BTYPE) == VT_STRUCT) &&
6277 tok == ';') {
6278 if ((btype.t & VT_BTYPE) == VT_STRUCT) {
6279 int v = btype.ref->v;
6280 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) >= SYM_FIRST_ANOM)
6281 tcc_warning("unnamed struct/union that defines no instances");
6283 next();
6284 continue;
6286 while (1) { /* iterate thru each declaration */
6287 type = btype;
6288 type_decl(&type, &ad, &v, TYPE_DIRECT);
6289 #if 0
6291 char buf[500];
6292 type_to_str(buf, sizeof(buf), t, get_tok_str(v, NULL));
6293 printf("type = '%s'\n", buf);
6295 #endif
6296 if ((type.t & VT_BTYPE) == VT_FUNC) {
6297 if ((type.t & VT_STATIC) && (l == VT_LOCAL)) {
6298 tcc_error("function without file scope cannot be static");
6300 /* if old style function prototype, we accept a
6301 declaration list */
6302 sym = type.ref;
6303 if (sym->c == FUNC_OLD)
6304 func_decl_list(sym);
6307 if (gnu_ext && (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
6308 ad.asm_label = asm_label_instr();
6309 /* parse one last attribute list, after asm label */
6310 parse_attribute(&ad);
6311 if (tok == '{')
6312 expect(";");
6315 if (ad.a.weak)
6316 type.t |= VT_WEAK;
6317 #ifdef TCC_TARGET_PE
6318 if (ad.a.func_import)
6319 type.t |= VT_IMPORT;
6320 if (ad.a.func_export)
6321 type.t |= VT_EXPORT;
6322 #endif
6323 type.t |= ad.a.visibility << VT_VIS_SHIFT;
6325 if (tok == '{') {
6326 if (l == VT_LOCAL)
6327 tcc_error("cannot use local functions");
6328 if ((type.t & VT_BTYPE) != VT_FUNC)
6329 expect("function definition");
6331 /* reject abstract declarators in function definition */
6332 sym = type.ref;
6333 while ((sym = sym->next) != NULL)
6334 if (!(sym->v & ~SYM_FIELD))
6335 expect("identifier");
6337 /* XXX: cannot do better now: convert extern line to static inline */
6338 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
6339 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
6341 sym = sym_find(v);
6342 if (sym) {
6343 Sym *ref;
6344 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
6345 goto func_error1;
6347 ref = sym->type.ref;
6348 if (0 == ref->a.func_proto)
6349 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
6351 /* use func_call from prototype if not defined */
6352 if (ref->a.func_call != FUNC_CDECL
6353 && type.ref->a.func_call == FUNC_CDECL)
6354 type.ref->a.func_call = ref->a.func_call;
6356 /* use export from prototype */
6357 if (ref->a.func_export)
6358 type.ref->a.func_export = 1;
6360 /* use static from prototype */
6361 if (sym->type.t & VT_STATIC)
6362 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
6364 /* If the definition has no visibility use the
6365 one from prototype. */
6366 if (! (type.t & VT_VIS_MASK))
6367 type.t |= sym->type.t & VT_VIS_MASK;
6369 if (!is_compatible_types(&sym->type, &type)) {
6370 func_error1:
6371 tcc_error("incompatible types for redefinition of '%s'",
6372 get_tok_str(v, NULL));
6374 type.ref->a.func_proto = 0;
6375 /* if symbol is already defined, then put complete type */
6376 sym->type = type;
6377 } else {
6378 /* put function symbol */
6379 sym = global_identifier_push(v, type.t, 0);
6380 sym->type.ref = type.ref;
6383 /* static inline functions are just recorded as a kind
6384 of macro. Their code will be emitted at the end of
6385 the compilation unit only if they are used */
6386 if ((type.t & (VT_INLINE | VT_STATIC)) ==
6387 (VT_INLINE | VT_STATIC)) {
6388 int block_level;
6389 struct InlineFunc *fn;
6390 const char *filename;
6392 filename = file ? file->filename : "";
6393 fn = tcc_malloc(sizeof *fn + strlen(filename));
6394 strcpy(fn->filename, filename);
6395 fn->sym = sym;
6396 tok_str_new(&fn->func_str);
6398 block_level = 0;
6399 for(;;) {
6400 int t;
6401 if (tok == TOK_EOF)
6402 tcc_error("unexpected end of file");
6403 tok_str_add_tok(&fn->func_str);
6404 t = tok;
6405 next();
6406 if (t == '{') {
6407 block_level++;
6408 } else if (t == '}') {
6409 block_level--;
6410 if (block_level == 0)
6411 break;
6414 tok_str_add(&fn->func_str, -1);
6415 tok_str_add(&fn->func_str, 0);
6416 dynarray_add((void ***)&tcc_state->inline_fns, &tcc_state->nb_inline_fns, fn);
6418 } else {
6419 /* compute text section */
6420 cur_text_section = ad.section;
6421 if (!cur_text_section)
6422 cur_text_section = text_section;
6423 sym->r = VT_SYM | VT_CONST;
6424 gen_function(sym);
6426 break;
6427 } else {
6428 if (btype.t & VT_TYPEDEF) {
6429 /* save typedefed type */
6430 /* XXX: test storage specifiers ? */
6431 sym = sym_find(v);
6432 if (sym && sym->scope == local_scope) {
6433 if (!is_compatible_types(&sym->type, &type)
6434 || !(sym->type.t & VT_TYPEDEF))
6435 tcc_error("incompatible redefinition of '%s'",
6436 get_tok_str(v, NULL));
6437 sym->type = type;
6438 } else {
6439 sym = sym_push(v, &type, 0, 0);
6441 sym->a = ad.a;
6442 sym->type.t |= VT_TYPEDEF;
6443 } else {
6444 r = 0;
6445 if ((type.t & VT_BTYPE) == VT_FUNC) {
6446 /* external function definition */
6447 /* specific case for func_call attribute */
6448 ad.a.func_proto = 1;
6449 type.ref->a = ad.a;
6450 } else if (!(type.t & VT_ARRAY)) {
6451 /* not lvalue if array */
6452 r |= lvalue_type(type.t);
6454 has_init = (tok == '=');
6455 if (has_init && (type.t & VT_VLA))
6456 tcc_error("Variable length array cannot be initialized");
6457 if ((btype.t & VT_EXTERN) || ((type.t & VT_BTYPE) == VT_FUNC) ||
6458 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
6459 !has_init && l == VT_CONST && type.ref->c < 0)) {
6460 /* external variable or function */
6461 /* NOTE: as GCC, uninitialized global static
6462 arrays of null size are considered as
6463 extern */
6464 sym = external_sym(v, &type, r);
6465 sym->asm_label = ad.asm_label;
6467 if (ad.alias_target) {
6468 Section tsec;
6469 Elf32_Sym *esym;
6470 Sym *alias_target;
6472 alias_target = sym_find(ad.alias_target);
6473 if (!alias_target || !alias_target->c)
6474 tcc_error("unsupported forward __alias__ attribute");
6475 esym = &((Elf32_Sym *)symtab_section->data)[alias_target->c];
6476 tsec.sh_num = esym->st_shndx;
6477 put_extern_sym2(sym, &tsec, esym->st_value, esym->st_size, 0);
6479 } else {
6480 type.t |= (btype.t & VT_STATIC); /* Retain "static". */
6481 if (type.t & VT_STATIC)
6482 r |= VT_CONST;
6483 else
6484 r |= l;
6485 if (has_init)
6486 next();
6487 decl_initializer_alloc(&type, &ad, r, has_init, v, l);
6490 if (tok != ',') {
6491 if (is_for_loop_init)
6492 return 1;
6493 skip(';');
6494 break;
6496 next();
6498 ad.a.aligned = 0;
6501 return 0;
6504 ST_FUNC void decl(int l)
6506 decl0(l, 0);