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