tcc on i386 are still having problems at work.Thank Roy report again. Struck on sever...
[tinycc.git] / tccgen.c
blobc2481b0cbd2d648829d5b5c56adb7a557314de1e
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, ex_rc;
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;
73 ST_DATA int pop_stack;
75 ST_DATA CType char_pointer_type, func_old_type, int_type, size_type;
77 /* ------------------------------------------------------------------------- */
78 static void gen_cast(CType *type);
79 static inline CType *pointed_type(CType *type);
80 static int is_compatible_types(CType *type1, CType *type2);
81 static int parse_btype(CType *type, AttributeDef *ad);
82 static void type_decl(CType *type, AttributeDef *ad, int *v, int td);
83 static void parse_expr_type(CType *type);
84 static void decl_initializer(CType *type, Section *sec, unsigned long c, int first, int size_only);
85 static void block(int *bsym, int *csym, int *case_sym, int *def_sym, int case_reg, int is_expr);
86 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r, int has_init, int v, char *asm_label, int scope);
87 static int decl0(int l, int is_for_loop_init);
88 static void expr_eq(void);
89 static void unary_type(CType *type);
90 static void vla_runtime_type_size(CType *type, int *a);
91 static void vla_sp_save(void);
92 static int is_compatible_parameter_types(CType *type1, CType *type2);
93 static void expr_type(CType *type);
94 ST_FUNC void vpush64(int ty, unsigned long long v);
95 ST_FUNC void vpush(CType *type);
96 ST_FUNC int gtst(int inv, int t);
97 ST_FUNC int is_btype_size(int bt);
99 ST_INLN int is_float(int t)
101 int bt;
102 bt = t & VT_BTYPE;
103 return bt == VT_LDOUBLE || bt == VT_DOUBLE || bt == VT_FLOAT || bt == VT_QFLOAT;
106 /* we use our own 'finite' function to avoid potential problems with
107 non standard math libs */
108 /* XXX: endianness dependent */
109 ST_FUNC int ieee_finite(double d)
111 int p[4];
112 memcpy(p, &d, sizeof(double));
113 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
116 ST_FUNC void test_lvalue(void)
118 if (!(vtop->r & VT_LVAL))
119 expect("lvalue");
122 /* ------------------------------------------------------------------------- */
123 /* symbol allocator */
124 static Sym *__sym_malloc(void)
126 Sym *sym_pool, *sym, *last_sym;
127 int i;
129 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
130 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
132 last_sym = sym_free_first;
133 sym = sym_pool;
134 for(i = 0; i < SYM_POOL_NB; i++) {
135 sym->next = last_sym;
136 last_sym = sym;
137 sym++;
139 sym_free_first = last_sym;
140 return last_sym;
143 static inline Sym *sym_malloc(void)
145 Sym *sym;
146 sym = sym_free_first;
147 if (!sym)
148 sym = __sym_malloc();
149 sym_free_first = sym->next;
150 return sym;
153 ST_INLN void sym_free(Sym *sym)
155 sym->next = sym_free_first;
156 tcc_free(sym->asm_label);
157 sym_free_first = sym;
160 /* push, without hashing */
161 ST_FUNC Sym *sym_push2(Sym **ps, int v, int t, long c)
163 Sym *s;
164 if (ps == &local_stack) {
165 for (s = *ps; s && s != scope_stack_bottom; s = s->prev)
166 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM && s->v == v)
167 tcc_error("incompatible types for redefinition of '%s'",
168 get_tok_str(v, NULL));
170 s = sym_malloc();
171 s->asm_label = NULL;
172 s->v = v;
173 s->type.t = t;
174 s->type.ref = NULL;
175 #ifdef _WIN64
176 s->d = NULL;
177 #endif
178 s->c = c;
179 s->next = NULL;
180 /* add in stack */
181 s->prev = *ps;
182 *ps = s;
183 return s;
186 /* find a symbol and return its associated structure. 's' is the top
187 of the symbol stack */
188 ST_FUNC Sym *sym_find2(Sym *s, int v)
190 while (s) {
191 if (s->v == v)
192 return s;
193 else if (s->v == -1)
194 return NULL;
195 s = s->prev;
197 return NULL;
200 /* structure lookup */
201 ST_INLN Sym *struct_find(int v)
203 v -= TOK_IDENT;
204 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
205 return NULL;
206 return table_ident[v]->sym_struct;
209 /* find an identifier */
210 ST_INLN Sym *sym_find(int v)
212 v -= TOK_IDENT;
213 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
214 return NULL;
215 return table_ident[v]->sym_identifier;
218 /* push a given symbol on the symbol stack */
219 ST_FUNC Sym *sym_push(int v, CType *type, int r, int c)
221 Sym *s, **ps;
222 TokenSym *ts;
224 if (local_stack)
225 ps = &local_stack;
226 else
227 ps = &global_stack;
228 s = sym_push2(ps, v, type->t, c);
229 s->type.ref = type->ref;
230 s->r = r;
231 /* don't record fields or anonymous symbols */
232 /* XXX: simplify */
233 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
234 /* record symbol in token array */
235 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
236 if (v & SYM_STRUCT)
237 ps = &ts->sym_struct;
238 else
239 ps = &ts->sym_identifier;
240 s->prev_tok = *ps;
241 *ps = s;
243 return s;
246 /* push a global identifier */
247 ST_FUNC Sym *global_identifier_push(int v, int t, int c)
249 Sym *s, **ps;
250 s = sym_push2(&global_stack, v, t, c);
251 /* don't record anonymous symbol */
252 if (v < SYM_FIRST_ANOM) {
253 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
254 /* modify the top most local identifier, so that
255 sym_identifier will point to 's' when popped */
256 while (*ps != NULL)
257 ps = &(*ps)->prev_tok;
258 s->prev_tok = NULL;
259 *ps = s;
261 return s;
264 /* pop symbols until top reaches 'b' */
265 ST_FUNC void sym_pop(Sym **ptop, Sym *b)
267 Sym *s, *ss, **ps;
268 TokenSym *ts;
269 int v;
271 s = *ptop;
272 while(s != b) {
273 ss = s->prev;
274 v = s->v;
275 /* remove symbol in token array */
276 /* XXX: simplify */
277 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
278 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
279 if (v & SYM_STRUCT)
280 ps = &ts->sym_struct;
281 else
282 ps = &ts->sym_identifier;
283 *ps = s->prev_tok;
285 sym_free(s);
286 s = ss;
288 *ptop = b;
291 static void weaken_symbol(Sym *sym)
293 sym->type.t |= VT_WEAK;
294 if (sym->c > 0) {
295 int esym_type;
296 ElfW(Sym) *esym;
298 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
299 esym_type = ELFW(ST_TYPE)(esym->st_info);
300 esym->st_info = ELFW(ST_INFO)(STB_WEAK, esym_type);
304 static void apply_visibility(Sym *sym, CType *type)
306 int vis = sym->type.t & VT_VIS_MASK;
307 int vis2 = type->t & VT_VIS_MASK;
308 if (vis == (STV_DEFAULT << VT_VIS_SHIFT))
309 vis = vis2;
310 else if (vis2 == (STV_DEFAULT << VT_VIS_SHIFT))
312 else
313 vis = (vis < vis2) ? vis : vis2;
314 sym->type.t &= ~VT_VIS_MASK;
315 sym->type.t |= vis;
317 if (sym->c > 0) {
318 ElfW(Sym) *esym;
320 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
321 vis >>= VT_VIS_SHIFT;
322 esym->st_other = (esym->st_other & ~ELFW(ST_VISIBILITY)(-1)) | vis;
326 /* ------------------------------------------------------------------------- */
328 ST_FUNC void swap(int *p, int *q)
330 int t;
331 t = *p;
332 *p = *q;
333 *q = t;
336 static void vsetc(CType *type, int r, CValue *vc)
338 int v;
340 if (vtop >= vstack + (VSTACK_SIZE - 1))
341 tcc_error("memory full (vstack)");
342 /* cannot let cpu flags if other instruction are generated. Also
343 avoid leaving VT_JMP anywhere except on the top of the stack
344 because it would complicate the code generator. */
345 if (vtop >= vstack) {
346 v = vtop->r & VT_VALMASK;
347 if (v == VT_CMP || (v & ~1) == VT_JMP)
348 gv(RC_INT);
350 vtop++;
351 vtop->type = *type;
352 vtop->r = r;
353 vtop->r2 = VT_CONST;
354 vtop->c = *vc;
357 /* push constant of type "type" with useless value */
358 ST_FUNC void vpush(CType *type)
360 CValue cval;
361 vsetc(type, VT_CONST, &cval);
364 /* push integer constant */
365 ST_FUNC void vpushi(int v)
367 CValue cval;
368 cval.i = v;
369 vsetc(&int_type, VT_CONST, &cval);
372 /* push a pointer sized constant */
373 ST_FUNC void vpushs(addr_t v)
375 CValue cval;
376 cval.ptr_offset = v;
377 vsetc(&size_type, VT_CONST, &cval);
380 /* push arbitrary 64bit constant */
381 ST_FUNC void vpush64(int ty, unsigned long long v)
383 CValue cval;
384 CType ctype;
385 ctype.t = ty;
386 ctype.ref = NULL;
387 cval.ull = v;
388 vsetc(&ctype, VT_CONST, &cval);
391 /* push long long constant */
392 static inline void vpushll(long long v)
394 vpush64(VT_LLONG, v);
397 /* push a symbol value of TYPE */
398 static inline void vpushsym(CType *type, Sym *sym)
400 CValue cval;
401 cval.ptr_offset = 0;
402 vsetc(type, VT_CONST | VT_SYM, &cval);
403 vtop->sym = sym;
406 /* Return a static symbol pointing to a section */
407 ST_FUNC Sym *get_sym_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
409 int v;
410 Sym *sym;
412 v = anon_sym++;
413 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
414 sym->type.ref = type->ref;
415 sym->r = VT_CONST | VT_SYM;
416 put_extern_sym(sym, sec, offset, size);
417 return sym;
420 /* push a reference to a section offset by adding a dummy symbol */
421 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
423 vpushsym(type, get_sym_ref(type, sec, offset, size));
426 /* define a new external reference to a symbol 'v' of type 'u' */
427 ST_FUNC Sym *external_global_sym(int v, CType *type, int r)
429 Sym *s;
431 s = sym_find(v);
432 if (!s) {
433 /* push forward reference */
434 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
435 s->type.ref = type->ref;
436 s->r = r | VT_CONST | VT_SYM;
438 return s;
441 /* define a new external reference to a symbol 'v' with alternate asm
442 name 'asm_label' of type 'u'. 'asm_label' is equal to NULL if there
443 is no alternate name (most cases) */
444 static Sym *external_sym(int v, CType *type, int r, char *asm_label)
446 Sym *s;
448 s = sym_find(v);
449 if (!s) {
450 /* push forward reference */
451 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
452 s->asm_label = asm_label;
453 s->type.t |= VT_EXTERN;
454 } else if (s->type.ref == func_old_type.ref) {
455 s->type.ref = type->ref;
456 s->r = r | VT_CONST | VT_SYM;
457 s->type.t |= VT_EXTERN;
458 } else if (!is_compatible_types(&s->type, type)) {
459 tcc_error("incompatible types for redefinition of '%s'",
460 get_tok_str(v, NULL));
462 /* Merge some storage attributes. */
463 if (type->t & VT_WEAK)
464 weaken_symbol(s);
466 if (type->t & VT_VIS_MASK)
467 apply_visibility(s, type);
469 return s;
472 /* push a reference to global symbol v */
473 ST_FUNC void vpush_global_sym(CType *type, int v)
475 vpushsym(type, external_global_sym(v, type, 0));
478 ST_FUNC void vset(CType *type, int r, int v)
480 CValue cval;
482 cval.i = v;
483 vsetc(type, r, &cval);
486 static void vseti(int r, int v)
488 CType type;
489 type.t = VT_INT;
490 type.ref = 0;
491 vset(&type, r, v);
494 ST_FUNC void vswap(void)
496 SValue tmp;
497 /* cannot let cpu flags if other instruction are generated. Also
498 avoid leaving VT_JMP anywhere except on the top of the stack
499 because it would complicate the code generator. */
500 if (vtop >= vstack) {
501 int v = vtop->r & VT_VALMASK;
502 if (v == VT_CMP || (v & ~1) == VT_JMP)
503 gv(RC_INT);
505 tmp = vtop[0];
506 vtop[0] = vtop[-1];
507 vtop[-1] = tmp;
509 /* XXX: +2% overall speed possible with optimized memswap
511 * memswap(&vtop[0], &vtop[1], sizeof *vtop);
515 ST_FUNC void vpushv(SValue *v)
517 if (vtop >= vstack + (VSTACK_SIZE - 1))
518 tcc_error("memory full (vstack)");
519 vtop++;
520 *vtop = *v;
523 ST_FUNC void vdup(void)
525 vpushv(vtop);
528 static int align_size(int size)
530 #ifdef TCC_TARGET_X86_64
531 if(size > 4)
532 return 8;
533 else
534 #endif
535 if(size > 2)
536 return 4;
537 else if(size > 1)
538 return 2;
539 else
540 return 1;
543 int loc_stack(int size, int is_sub){
544 int l, align;
545 align = align_size(size);
546 size = (size + align - 1) & - align;
547 if(is_sub){
548 pop_stack -= size;
549 if(pop_stack >= 0)
550 l = loc + pop_stack;
551 else{
552 loc += pop_stack;
553 l = loc &= -align;
554 pop_stack = 0;
556 }else{
557 pop_stack += size;
558 l = loc + pop_stack;
560 return l;
563 /* save r to the memory stack, and mark it as being free */
564 ST_FUNC void save_reg(int r)
566 int l, saved, size, align;
567 SValue *p, sv;
568 CType *type;
570 /* modify all stack values */
571 l = saved = 0;
572 for(p = vstack; p <= vtop; p++) {
573 #ifdef TCC_TARGET_X86_64
574 if ((p->r & VT_VALMASK) == r ||
575 ((((p->type.t & VT_BTYPE) == VT_QLONG) || ((p->type.t & VT_BTYPE) == VT_QFLOAT)) &&
576 ((p->r2 & VT_VALMASK) == r)))
577 #else
578 if ((p->r & VT_VALMASK) == r || ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r))
579 #endif
581 /* must save value on stack if not already done */
582 if (!saved) {
583 /* NOTE: must reload 'r' because r might be equal to r2 */
584 r = p->r & VT_VALMASK;
585 /* store register in the stack */
586 type = &p->type;
587 if((type->t & VT_BTYPE) == VT_STRUCT){
588 int ret_align;
589 SValue ret;
590 gfunc_sret(type, func_var, &ret.type, &ret_align);
591 type = &ret.type;
593 if ((p->r & VT_LVAL) || ((type->t & VT_BTYPE) == VT_FUNC))
594 #ifdef TCC_TARGET_X86_64
595 type = &char_pointer_type;
596 #else
597 type = &int_type;
598 #endif
599 size = type_size(type, &align);
600 l = loc_stack(size, 1);
601 sv.r = VT_LOCAL | VT_LVAL;
602 sv.c.ul = l;
603 #ifdef TCC_TARGET_X86_64
604 if (((type->t & VT_BTYPE) == VT_QLONG) || ((type->t & VT_BTYPE) == VT_QFLOAT))
605 #else
606 if ((type->t & VT_BTYPE) == VT_LLONG)
607 #endif
609 #ifdef TCC_TARGET_X86_64
610 int load_size = 8, load_type = ((type->t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
611 #else
612 int load_size = 4, load_type = VT_INT;
613 #endif
614 sv.type.t = load_type;
615 store(r, &sv);
616 sv.c.ul += load_size;
617 store(p->r2, &sv);
618 }else{
619 sv.type.t = type->t;
620 store(r, &sv);
622 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
623 /* x86 specific: need to pop fp register ST0 if saved */
624 if (r == TREG_ST0) {
625 o(0xd8dd); /* fstp %st(0) */
627 #endif
628 saved = 1;
630 /* mark that stack entry as being saved on the stack */
631 if (p->r & VT_LVAL) {
632 /* also clear the bounded flag because the
633 relocation address of the function was stored in
634 p->c.ul */
635 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
636 } else {
637 p->r = lvalue_type(p->type.t) | VT_LOCAL | VT_TMP;
639 p->r2 = VT_CONST;
640 p->c.ul = l;
645 #ifdef TCC_TARGET_ARM
646 /* find a register of class 'rc2' with at most one reference on stack.
647 * If none, call get_reg(rc) */
648 ST_FUNC int get_reg_ex(int rc, int rc2)
650 int r;
651 SValue *p;
653 for(r=0;r<NB_REGS;r++) {
654 if (reg_classes[r] & rc2) {
655 int n;
656 n=0;
657 for(p = vstack; p <= vtop; p++) {
658 if ((p->r & VT_VALMASK) == r ||
659 (p->r2 & VT_VALMASK) == r)
660 n++;
662 if (n <= 1)
663 return r;
666 return get_reg(rc);
668 #endif
670 static int for_reg(int rc)
672 int r;
673 SValue *p;
674 if(rc){
675 for(r = 0; r < NB_REGS; r++) {
676 if (reg_classes[r] & rc) {
677 for(p = vstack; p <= vtop; p++) {
678 if ((p->r & VT_VALMASK) == r || (p->r2 & VT_VALMASK) == r)
679 goto notfound;
681 goto found;
683 notfound:;
686 r = -1;
687 found:
688 return r;
691 /* find a free register of class 'rc'. If none, save one register */
692 int get_reg(int rc)
694 int r;
695 SValue *p;
697 /* find a free register */
698 r = for_reg(rc);
699 if (r != -1)
700 return r;
701 /* no register left : free the first one on the stack (VERY
702 IMPORTANT to start from the bottom to ensure that we don't
703 spill registers used in gen_opi()) */
704 for(p = vstack; p <= vtop; p++) {
705 /* look at second register (if long long) */
706 if(p->r & VT_TMP)
707 continue;
708 r = p->r2 & VT_VALMASK;
709 if (r < VT_CONST && (reg_classes[r] & rc))
710 goto save_found;
711 r = p->r & VT_VALMASK;
712 if (r < VT_CONST && (reg_classes[r] & rc)) {
713 save_found:
714 save_reg(r);
715 return r;
718 /* Should never comes here */
719 assert(0);
720 return -1;
723 /* save registers up to (vtop - n) stack entry */
724 ST_FUNC void save_regs(int n)
726 int r;
727 SValue *p, *p1;
728 p1 = vtop - n;
729 for(p = vstack;p <= p1; p++) {
730 r = p->r & VT_VALMASK;
731 if (r < VT_CONST) {
732 save_reg(r);
737 /* move register 's' (of type 't') to 'r', and flush previous value of r to memory
738 if needed */
739 static void move_reg(int r, int s, int t)
741 SValue sv;
743 if (r != s) {
744 save_reg(r);
745 sv.type.t = t;
746 sv.type.ref = NULL;
747 sv.r = s;
748 sv.c.ul = 0;
749 load(r, &sv);
753 /* get address of vtop (vtop MUST BE an lvalue) */
754 ST_FUNC void gaddrof(void)
756 if (vtop->r & VT_REF)
757 gv(RC_INT);
758 vtop->r &= ~VT_LVAL;
759 /* tricky: if saved lvalue, then we can go back to lvalue */
760 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
761 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL| VT_TMP;
764 #ifdef CONFIG_TCC_BCHECK
765 /* generate lvalue bound code */
766 static void gbound(void)
768 int lval_type;
769 CType type1;
771 vtop->r &= ~VT_MUSTBOUND;
772 /* if lvalue, then use checking code before dereferencing */
773 if (vtop->r & VT_LVAL) {
774 /* if not VT_BOUNDED value, then make one */
775 if (!(vtop->r & VT_BOUNDED)) {
776 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
777 /* must save type because we must set it to int to get pointer */
778 type1 = vtop->type;
779 vtop->type.t = VT_INT;
780 gaddrof();
781 vpushi(0);
782 gen_bounded_ptr_add();
783 vtop->r |= lval_type;
784 vtop->type = type1;
786 /* then check for dereferencing */
787 gen_bounded_ptr_deref();
790 #endif
792 /* store vtop a register belonging to class 'rc'. lvalues are
793 converted to values. Cannot be used if cannot be converted to
794 register value (such as structures). */
795 ST_FUNC int gv(int rc)
797 int r, bit_pos, bit_size, size, align, i, ft, sbt;
798 int rc2;
800 ft = vtop->type.t;
801 sbt = ft & VT_BTYPE;
802 /* NOTE: get_reg can modify vstack[] */
803 if (ft & VT_BITFIELD) {
804 CType type;
805 int bits;
806 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
807 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
808 /* remove bit field info to avoid loops */
809 ft = vtop->type.t &= ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
810 /* cast to int to propagate signedness in following ops */
811 if (sbt == VT_LLONG) {
812 type.t = VT_LLONG;
813 bits = 64;
814 } else{
815 type.t = VT_INT;
816 bits = 32;
818 if((ft & VT_UNSIGNED) || sbt == VT_BOOL)
819 type.t |= VT_UNSIGNED;
820 gen_cast(&type);
821 /* generate shifts */
822 vpushi(bits - (bit_pos + bit_size));
823 gen_op(TOK_SHL);
824 vpushi(bits - bit_size);
825 /* NOTE: transformed to SHR if unsigned */
826 gen_op(TOK_SAR);
827 r = gv(rc);
828 } else {
829 if (is_float(vtop->type.t) &&
830 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
831 Sym *sym;
832 int *ptr;
833 unsigned long offset;
834 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
835 CValue check;
836 #endif
838 /* XXX: unify with initializers handling ? */
839 /* CPUs usually cannot use float constants, so we store them
840 generically in data segment */
841 size = type_size(&vtop->type, &align);
842 offset = (data_section->data_offset + align - 1) & -align;
843 data_section->data_offset = offset;
844 /* XXX: not portable yet */
845 #if defined(__i386__) || defined(__x86_64__)
846 /* Zero pad x87 tenbyte long doubles */
847 if (size == LDOUBLE_SIZE) {
848 vtop->c.tab[2] &= 0xffff;
849 #if LDOUBLE_SIZE == 16
850 vtop->c.tab[3] = 0;
851 #endif
853 #endif
854 ptr = section_ptr_add(data_section, size);
855 size = size >> 2;
856 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
857 check.d = 1;
858 if(check.tab[0])
859 for(i=0;i<size;i++)
860 ptr[i] = vtop->c.tab[size-1-i];
861 else
862 #endif
863 for(i=0;i<size;i++)
864 ptr[i] = vtop->c.tab[i];
865 sym = get_sym_ref(&vtop->type, data_section, offset, size << 2);
866 vtop->r |= VT_LVAL | VT_SYM;
867 vtop->sym = sym;
868 vtop->c.ptr_offset = 0;
870 #ifdef CONFIG_TCC_BCHECK
871 if (vtop->r & VT_MUSTBOUND)
872 gbound();
873 #endif
875 r = vtop->r & VT_VALMASK;
876 if(rc & ~RC_MASK)
877 rc2 = ex_rc;
878 else
879 rc2 = (rc & RC_FLOAT) ? RC_FLOAT : RC_INT;
881 /* need to reload if:
882 - constant
883 - lvalue (need to dereference pointer)
884 - already a register, but not in the right class */
885 if (r >= VT_CONST || (vtop->r & VT_LVAL) || !(reg_classes[r] & rc)
886 #ifdef TCC_TARGET_X86_64
887 || (sbt == VT_QLONG && !(reg_classes[vtop->r2] & rc2))
888 || (sbt == VT_QFLOAT && !(reg_classes[vtop->r2] & rc2))
889 #else
890 || (sbt == VT_LLONG && !(reg_classes[vtop->r2] & rc2))
891 #endif
892 || vtop->c.i)
894 r = get_reg(rc);
895 #ifdef TCC_TARGET_X86_64
896 if ((sbt == VT_QLONG) || (sbt == VT_QFLOAT))
897 #else
898 if (sbt == VT_LLONG)
899 #endif
901 #ifdef TCC_TARGET_X86_64
902 int load_size = 8, load_type = (sbt == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
903 #else
904 int load_size = 4, load_type = VT_INT;
905 unsigned long long ll;
906 #endif
907 int r2;
908 /* two register type load : expand to two words
909 temporarily */
910 #ifndef TCC_TARGET_X86_64
911 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
912 /* load constant */
913 ll = vtop->c.ull;
914 vtop->c.ui = ll; /* first word */
915 load(r, vtop);
916 vtop->r = r; /* save register value */
917 vpushi(ll >> 32); /* second word */
918 } else
919 #endif
920 /* XXX: test to VT_CONST incorrect ? */
921 if (r >= VT_CONST || (vtop->r & VT_LVAL)) {
922 /* We do not want to modifier the long long
923 pointer here, so the safest (and less
924 efficient) is to save all the other registers
925 in the regs. use VT_TMP XXX: totally inefficient. */
926 /* load from memory */
927 vtop->type.t = load_type;
928 load(r, vtop);
929 vdup();
930 vtop[-1].r = r | VT_TMP; /* lock register value */
931 /* increment pointer to get second word */
932 vtop->type = char_pointer_type;
933 gaddrof();
934 vpushi(load_size);
935 gen_op('+');
936 vtop->r |= VT_LVAL;
937 vtop->type.t = load_type;
938 } else {
939 /* move registers */
940 load(r, vtop);
941 vdup();
942 vtop[-1].r = r | VT_TMP; /* lock register value */
943 vtop->r = vtop[-1].r2;
945 /* Allocate second register. Here we rely on the fact that
946 get_reg() tries first to free r2 of an SValue. */
947 r2 = get_reg(rc2);
948 load(r2, vtop);
949 vtop--;
950 /* write second register */
951 vtop->r2 = r2;
952 vtop->r &= ~VT_TMP;
953 vtop->type.t = ft;
954 } else if ((vtop->r & VT_LVAL) && !is_float(ft)) {
955 int t;
956 /* lvalue of scalar type : need to use lvalue type
957 because of possible cast */
958 t = ft;
959 /* compute memory access type */
960 if (vtop->r & VT_REF)
961 #ifdef TCC_TARGET_X86_64
962 t = VT_PTR;
963 #else
964 t = VT_INT;
965 #endif
966 else if (vtop->r & VT_LVAL_BYTE)
967 t = VT_BYTE;
968 else if (vtop->r & VT_LVAL_SHORT)
969 t = VT_SHORT;
970 if (vtop->r & VT_LVAL_UNSIGNED)
971 t |= VT_UNSIGNED;
972 vtop->type.t = t;
973 load(r, vtop);
974 /* restore wanted type */
975 vtop->type.t = ft;
976 } else {
977 /* one register type load */
978 load(r, vtop);
980 vtop->r = r;
981 vtop->c.ptr_offset = 0;
983 #ifdef TCC_TARGET_C67
984 /* uses register pairs for doubles */
985 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
986 vtop->r2 = r+1;
987 #endif
989 return r;
992 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
993 ST_FUNC void gv2(int rc1, int rc2)
995 /* generate more generic register first. But VT_JMP or VT_CMP
996 values must be generated first in all cases to avoid possible
997 reload errors */
998 if (rc1 <= rc2) {
999 vswap();
1000 gv(rc1);
1001 vswap();
1002 gv(rc2);
1003 /* test if reload is needed for first register */
1004 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
1005 vswap();
1006 gv(rc1);
1007 vswap();
1009 } else {
1010 gv(rc2);
1011 vswap();
1012 gv(rc1);
1013 vswap();
1014 /* test if reload is needed for first register */
1015 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
1016 gv(rc2);
1021 /* wrapper around RC_FRET to return a register by type */
1022 static int rc_fret(int t)
1024 #ifdef TCC_TARGET_X86_64
1025 if (t == VT_LDOUBLE) {
1026 return RC_ST0;
1028 ex_rc = RC_QRET;
1029 #endif
1030 return RC_FRET;
1033 /* wrapper around REG_FRET to return a register by type */
1034 static int reg_fret(int t)
1036 #ifdef TCC_TARGET_X86_64
1037 if (t == VT_LDOUBLE) {
1038 return TREG_ST0;
1040 #endif
1041 return REG_FRET;
1044 /* expand long long on stack in two int registers */
1045 static void lexpand(void)
1047 int u;
1049 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
1050 gv(RC_INT);
1051 vdup();
1052 vtop[0].r = vtop[-1].r2;
1053 vtop[0].r2 = VT_CONST;
1054 vtop[-1].r2 = VT_CONST;
1055 vtop[0].type.t = VT_INT | u;
1056 vtop[-1].type.t = VT_INT | u;
1059 #ifdef TCC_TARGET_ARM
1060 /* expand long long on stack */
1061 ST_FUNC void lexpand_nr(void)
1063 int u,v;
1065 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
1066 vdup();
1067 vtop->r2 = VT_CONST;
1068 vtop->type.t = VT_INT | u;
1069 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
1070 if (v == VT_CONST) {
1071 vtop[-1].c.ui = vtop->c.ull;
1072 vtop->c.ui = vtop->c.ull >> 32;
1073 vtop->r = VT_CONST;
1074 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
1075 vtop->c.ui += 4;
1076 vtop->r = vtop[-1].r;
1077 } else if (v > VT_CONST) {
1078 vtop--;
1079 lexpand();
1080 } else
1081 vtop->r = vtop[-1].r2;
1082 vtop[-1].r2 = VT_CONST;
1083 vtop[-1].type.t = VT_INT | u;
1085 #endif
1087 #ifndef TCC_TARGET_X86_64
1088 /* build a long long from two ints */
1089 static void lbuild(int t)
1091 gv2(RC_INT, RC_INT);
1092 vtop[-1].r2 = vtop[0].r;
1093 vtop[-1].type.t = t;
1094 vpop();
1096 #endif
1098 /* rotate n first stack elements to the bottom
1099 I1 ... In -> I2 ... In I1 [top is right]
1101 ST_FUNC void vrotb(int n)
1103 int i;
1104 SValue tmp;
1106 tmp = vtop[-n + 1];
1107 for(i=-n+1;i!=0;i++)
1108 vtop[i] = vtop[i+1];
1109 vtop[0] = tmp;
1112 /* rotate the n elements before entry e towards the top
1113 I1 ... In ... -> In I1 ... I(n-1) ... [top is right]
1115 ST_FUNC void vrote(SValue *e, int n)
1117 int i;
1118 SValue tmp;
1120 tmp = *e;
1121 for(i = 0;i < n - 1; i++)
1122 e[-i] = e[-i - 1];
1123 e[-n + 1] = tmp;
1126 /* rotate n first stack elements to the top
1127 I1 ... In -> In I1 ... I(n-1) [top is right]
1129 ST_FUNC void vrott(int n)
1131 vrote(vtop, n);
1134 /* pop stack value */
1135 ST_FUNC void vpop(void)
1137 int v, fr;
1138 fr = vtop->r;
1139 v = fr & VT_VALMASK;
1140 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1141 /* for x86, we need to pop the FP stack */
1142 if (v == TREG_ST0 && !nocode_wanted) {
1143 o(0xd8dd); /* fstp %st(0) */
1144 } else
1145 #endif
1146 if (v == VT_JMP || v == VT_JMPI) {
1147 /* need to put correct jump if && or || without test */
1148 gsym(vtop->c.ul);
1150 if(fr & VT_TMP){
1151 int size, align;
1152 SValue ret;
1153 if((vtop->type.t & VT_BTYPE) == VT_FUNC)
1154 size = 8;
1155 else{
1156 gfunc_sret(&vtop->type, func_var, &ret.type, &align);
1157 size = type_size(&ret.type, &align);
1159 loc_stack(size, 0);
1161 vtop--;
1164 /* convert stack entry to register and duplicate its value in another
1165 register */
1166 static void gv_dup(void)
1168 int rc, t, r, r1;
1169 SValue sv;
1170 t = vtop->type.t;
1171 #ifndef TCC_TARGET_X86_64
1172 if ((t & VT_BTYPE) == VT_LLONG) {
1173 lexpand();
1174 gv_dup();
1175 vswap();
1176 vrotb(3);
1177 gv_dup();
1178 vrotb(4);
1179 /* stack: H L L1 H1 */
1180 lbuild(t);
1181 vrott(3);
1182 vswap();
1183 lbuild(t);
1184 vswap();
1185 } else
1186 #endif
1188 /* duplicate value */
1189 if (is_float(t)) {
1190 rc = RC_FLOAT;
1191 #ifdef TCC_TARGET_X86_64
1192 if ((t & VT_BTYPE) == VT_LDOUBLE) {
1193 rc = RC_ST0;
1195 #endif
1196 }else
1197 rc = RC_INT;
1198 sv.type.t = t;
1199 r = gv(rc);
1200 r1 = get_reg(rc);
1201 sv.r = r;
1202 sv.c.ul = 0;
1203 load(r1, &sv); /* move r to r1 */
1204 vdup();
1205 /* duplicates value */
1206 if (r != r1)
1207 vtop->r = r1;
1210 #ifndef TCC_TARGET_X86_64
1211 /* generate CPU independent (unsigned) long long operations */
1212 static void gen_opl(int op)
1214 int t, a, b, op1, c, i;
1215 int func;
1216 unsigned short reg_iret = REG_IRET;
1217 unsigned short reg_lret = REG_LRET;
1218 SValue tmp;
1220 switch(op) {
1221 case '/':
1222 case TOK_PDIV:
1223 func = TOK___divdi3;
1224 goto gen_func;
1225 case TOK_UDIV:
1226 func = TOK___udivdi3;
1227 goto gen_func;
1228 case '%':
1229 func = TOK___moddi3;
1230 goto gen_mod_func;
1231 case TOK_UMOD:
1232 func = TOK___umoddi3;
1233 gen_mod_func:
1234 #ifdef TCC_ARM_EABI
1235 reg_iret = TREG_R2;
1236 reg_lret = TREG_R3;
1237 #endif
1238 gen_func:
1239 /* call generic long long function */
1240 vpush_global_sym(&func_old_type, func);
1241 vrott(3);
1242 gfunc_call(2);
1243 vpushi(0);
1244 vtop->r = reg_iret;
1245 vtop->r2 = reg_lret;
1246 break;
1247 case '^':
1248 case '&':
1249 case '|':
1250 case '*':
1251 case '+':
1252 case '-':
1253 t = vtop->type.t;
1254 vswap();
1255 lexpand();
1256 vrotb(3);
1257 lexpand();
1258 /* stack: L1 H1 L2 H2 */
1259 tmp = vtop[0];
1260 vtop[0] = vtop[-3];
1261 vtop[-3] = tmp;
1262 tmp = vtop[-2];
1263 vtop[-2] = vtop[-3];
1264 vtop[-3] = tmp;
1265 vswap();
1266 /* stack: H1 H2 L1 L2 */
1267 if (op == '*') {
1268 vpushv(vtop - 1);
1269 vpushv(vtop - 1);
1270 gen_op(TOK_UMULL);
1271 lexpand();
1272 /* stack: H1 H2 L1 L2 ML MH */
1273 for(i=0;i<4;i++)
1274 vrotb(6);
1275 /* stack: ML MH H1 H2 L1 L2 */
1276 tmp = vtop[0];
1277 vtop[0] = vtop[-2];
1278 vtop[-2] = tmp;
1279 /* stack: ML MH H1 L2 H2 L1 */
1280 gen_op('*');
1281 vrotb(3);
1282 vrotb(3);
1283 gen_op('*');
1284 /* stack: ML MH M1 M2 */
1285 gen_op('+');
1286 gen_op('+');
1287 } else if (op == '+' || op == '-') {
1288 /* XXX: add non carry method too (for MIPS or alpha) */
1289 if (op == '+')
1290 op1 = TOK_ADDC1;
1291 else
1292 op1 = TOK_SUBC1;
1293 gen_op(op1);
1294 /* stack: H1 H2 (L1 op L2) */
1295 vrotb(3);
1296 vrotb(3);
1297 gen_op(op1 + 1); /* TOK_xxxC2 */
1298 } else {
1299 gen_op(op);
1300 /* stack: H1 H2 (L1 op L2) */
1301 vrotb(3);
1302 vrotb(3);
1303 /* stack: (L1 op L2) H1 H2 */
1304 gen_op(op);
1305 /* stack: (L1 op L2) (H1 op H2) */
1307 /* stack: L H */
1308 lbuild(t);
1309 break;
1310 case TOK_SAR:
1311 case TOK_SHR:
1312 case TOK_SHL:
1313 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1314 t = vtop[-1].type.t;
1315 vswap();
1316 lexpand();
1317 vrotb(3);
1318 /* stack: L H shift */
1319 c = (int)vtop->c.i;
1320 /* constant: simpler */
1321 /* NOTE: all comments are for SHL. the other cases are
1322 done by swaping words */
1323 vpop();
1324 if (op != TOK_SHL)
1325 vswap();
1326 if (c >= 32) {
1327 /* stack: L H */
1328 vpop();
1329 if (c > 32) {
1330 vpushi(c - 32);
1331 gen_op(op);
1333 if (op != TOK_SAR) {
1334 vpushi(0);
1335 } else {
1336 gv_dup();
1337 vpushi(31);
1338 gen_op(TOK_SAR);
1340 vswap();
1341 } else {
1342 vswap();
1343 gv_dup();
1344 /* stack: H L L */
1345 vpushi(c);
1346 gen_op(op);
1347 vswap();
1348 vpushi(32 - c);
1349 if (op == TOK_SHL)
1350 gen_op(TOK_SHR);
1351 else
1352 gen_op(TOK_SHL);
1353 vrotb(3);
1354 /* stack: L L H */
1355 vpushi(c);
1356 if (op == TOK_SHL)
1357 gen_op(TOK_SHL);
1358 else
1359 gen_op(TOK_SHR);
1360 gen_op('|');
1362 if (op != TOK_SHL)
1363 vswap();
1364 lbuild(t);
1365 } else {
1366 /* XXX: should provide a faster fallback on x86 ? */
1367 switch(op) {
1368 case TOK_SAR:
1369 func = TOK___ashrdi3;
1370 goto gen_func;
1371 case TOK_SHR:
1372 func = TOK___lshrdi3;
1373 goto gen_func;
1374 case TOK_SHL:
1375 func = TOK___ashldi3;
1376 goto gen_func;
1379 break;
1380 default:
1381 /* compare operations */
1382 t = vtop->type.t;
1383 vswap();
1384 lexpand();
1385 vrotb(3);
1386 lexpand();
1387 /* stack: L1 H1 L2 H2 */
1388 tmp = vtop[-1];
1389 vtop[-1] = vtop[-2];
1390 vtop[-2] = tmp;
1391 /* stack: L1 L2 H1 H2 */
1392 /* compare high */
1393 op1 = op;
1394 /* when values are equal, we need to compare low words. since
1395 the jump is inverted, we invert the test too. */
1396 if (op1 == TOK_LT)
1397 op1 = TOK_LE;
1398 else if (op1 == TOK_GT)
1399 op1 = TOK_GE;
1400 else if (op1 == TOK_ULT)
1401 op1 = TOK_ULE;
1402 else if (op1 == TOK_UGT)
1403 op1 = TOK_UGE;
1404 a = 0;
1405 b = 0;
1406 gen_op(op1);
1407 if (op1 != TOK_NE) {
1408 a = gtst(1, 0);
1410 if (op != TOK_EQ) {
1411 /* generate non equal test */
1412 /* XXX: NOT PORTABLE yet */
1413 if (a == 0) {
1414 b = gtst(0, 0);
1415 } else {
1416 #if defined(TCC_TARGET_I386)
1417 b = psym(0x850f, 0);
1418 #elif defined(TCC_TARGET_ARM)
1419 b = ind;
1420 o(0x1A000000 | encbranch(ind, 0, 1));
1421 #elif defined(TCC_TARGET_C67)
1422 tcc_error("not implemented");
1423 #else
1424 #error not supported
1425 #endif
1428 /* compare low. Always unsigned */
1429 op1 = op;
1430 if (op1 == TOK_LT)
1431 op1 = TOK_ULT;
1432 else if (op1 == TOK_LE)
1433 op1 = TOK_ULE;
1434 else if (op1 == TOK_GT)
1435 op1 = TOK_UGT;
1436 else if (op1 == TOK_GE)
1437 op1 = TOK_UGE;
1438 gen_op(op1);
1439 a = gtst(1, a);
1440 gsym(b);
1441 vseti(VT_JMPI, a);
1442 break;
1445 #endif
1447 /* handle integer constant optimizations and various machine
1448 independent opt */
1449 static void gen_opic(int op)
1451 int c1, c2, t1, t2, n;
1452 SValue *v1, *v2;
1453 long long l1, l2;
1454 typedef unsigned long long U;
1456 v1 = vtop - 1;
1457 v2 = vtop;
1458 t1 = v1->type.t & VT_BTYPE;
1459 t2 = v2->type.t & VT_BTYPE;
1461 if (t1 == VT_LLONG)
1462 l1 = v1->c.ll;
1463 else if (v1->type.t & VT_UNSIGNED)
1464 l1 = v1->c.ui;
1465 else
1466 l1 = v1->c.i;
1468 if (t2 == VT_LLONG)
1469 l2 = v2->c.ll;
1470 else if (v2->type.t & VT_UNSIGNED)
1471 l2 = v2->c.ui;
1472 else
1473 l2 = v2->c.i;
1475 /* currently, we cannot do computations with forward symbols */
1476 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1477 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1478 if (c1 && c2) {
1479 switch(op) {
1480 case '+': l1 += l2; break;
1481 case '-': l1 -= l2; break;
1482 case '&': l1 &= l2; break;
1483 case '^': l1 ^= l2; break;
1484 case '|': l1 |= l2; break;
1485 case '*': l1 *= l2; break;
1487 case TOK_PDIV:
1488 case '/':
1489 case '%':
1490 case TOK_UDIV:
1491 case TOK_UMOD:
1492 /* if division by zero, generate explicit division */
1493 if (l2 == 0) {
1494 if (const_wanted)
1495 tcc_error("division by zero in constant");
1496 goto general_case;
1498 switch(op) {
1499 default: l1 /= l2; break;
1500 case '%': l1 %= l2; break;
1501 case TOK_UDIV: l1 = (U)l1 / l2; break;
1502 case TOK_UMOD: l1 = (U)l1 % l2; break;
1504 break;
1505 case TOK_SHL: l1 <<= l2; break;
1506 case TOK_SHR: l1 = (U)l1 >> l2; break;
1507 case TOK_SAR: l1 >>= l2; break;
1508 /* tests */
1509 case TOK_ULT: l1 = (U)l1 < (U)l2; break;
1510 case TOK_UGE: l1 = (U)l1 >= (U)l2; break;
1511 case TOK_EQ: l1 = l1 == l2; break;
1512 case TOK_NE: l1 = l1 != l2; break;
1513 case TOK_ULE: l1 = (U)l1 <= (U)l2; break;
1514 case TOK_UGT: l1 = (U)l1 > (U)l2; break;
1515 case TOK_LT: l1 = l1 < l2; break;
1516 case TOK_GE: l1 = l1 >= l2; break;
1517 case TOK_LE: l1 = l1 <= l2; break;
1518 case TOK_GT: l1 = l1 > l2; break;
1519 /* logical */
1520 case TOK_LAND: l1 = l1 && l2; break;
1521 case TOK_LOR: l1 = l1 || l2; break;
1522 default:
1523 goto general_case;
1525 v1->c.ll = l1;
1526 vtop--;
1527 } else {
1528 /* if commutative ops, put c2 as constant */
1529 if (c1 && (op == '+' || op == '&' || op == '^' ||
1530 op == '|' || op == '*')) {
1531 vswap();
1532 c2 = c1; //c = c1, c1 = c2, c2 = c;
1533 l2 = l1; //l = l1, l1 = l2, l2 = l;
1535 /* Filter out NOP operations like x*1, x-0, x&-1... */
1536 if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
1537 op == TOK_PDIV) &&
1538 l2 == 1) ||
1539 ((op == '+' || op == '-' || op == '|' || op == '^' ||
1540 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
1541 l2 == 0) ||
1542 (op == '&' &&
1543 l2 == -1))) {
1544 /* nothing to do */
1545 vtop--;
1546 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
1547 /* try to use shifts instead of muls or divs */
1548 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
1549 n = -1;
1550 while (l2) {
1551 l2 >>= 1;
1552 n++;
1554 vtop->c.ll = n;
1555 if (op == '*')
1556 op = TOK_SHL;
1557 else if (op == TOK_PDIV)
1558 op = TOK_SAR;
1559 else
1560 op = TOK_SHR;
1562 goto general_case;
1563 } else if (c2 && (op == '+' || op == '-') &&
1564 (((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM))
1565 || (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
1566 /* symbol + constant case */
1567 if (op == '-')
1568 l2 = -l2;
1569 vtop--;
1570 vtop->c.ll += l2;
1571 } else {
1572 general_case:
1573 if (!nocode_wanted) {
1574 /* call low level op generator */
1575 if (t1 == VT_LLONG || t2 == VT_LLONG)
1576 gen_opl(op);
1577 else
1578 gen_opi(op);
1579 } else {
1580 vtop--;
1586 /* generate a floating point operation with constant propagation */
1587 static void gen_opif(int op)
1589 int c1, c2;
1590 SValue *v1, *v2;
1591 long double f1, f2;
1593 v1 = vtop - 1;
1594 v2 = vtop;
1595 /* currently, we cannot do computations with forward symbols */
1596 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1597 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1598 if (c1 && c2) {
1599 if (v1->type.t == VT_FLOAT) {
1600 f1 = v1->c.f;
1601 f2 = v2->c.f;
1602 } else if (v1->type.t == VT_DOUBLE) {
1603 f1 = v1->c.d;
1604 f2 = v2->c.d;
1605 } else {
1606 f1 = v1->c.ld;
1607 f2 = v2->c.ld;
1610 /* NOTE: we only do constant propagation if finite number (not
1611 NaN or infinity) (ANSI spec) */
1612 if (!ieee_finite(f1) || !ieee_finite(f2))
1613 goto general_case;
1615 switch(op) {
1616 case '+': f1 += f2; break;
1617 case '-': f1 -= f2; break;
1618 case '*': f1 *= f2; break;
1619 case '/':
1620 if (f2 == 0.0) {
1621 if (const_wanted)
1622 tcc_error("division by zero in constant");
1623 goto general_case;
1625 f1 /= f2;
1626 break;
1627 /* XXX: also handles tests ? */
1628 default:
1629 goto general_case;
1631 /* XXX: overflow test ? */
1632 if (v1->type.t == VT_FLOAT) {
1633 v1->c.f = f1;
1634 } else if (v1->type.t == VT_DOUBLE) {
1635 v1->c.d = f1;
1636 } else {
1637 v1->c.ld = f1;
1639 vtop--;
1640 } else {
1641 general_case:
1642 if (!nocode_wanted) {
1643 gen_opf(op);
1644 } else {
1645 vtop--;
1650 static int pointed_size(CType *type)
1652 int align;
1653 return type_size(pointed_type(type), &align);
1656 static void vla_runtime_pointed_size(CType *type)
1658 int align;
1659 vla_runtime_type_size(pointed_type(type), &align);
1662 static inline int is_null_pointer(SValue *p)
1664 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
1665 return 0;
1666 return ((p->type.t & VT_BTYPE) == VT_INT && p->c.i == 0) ||
1667 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.ll == 0) ||
1668 ((p->type.t & VT_BTYPE) == VT_PTR && p->c.ptr_offset == 0);
1671 static inline int is_integer_btype(int bt)
1673 return (bt == VT_BYTE || bt == VT_SHORT ||
1674 bt == VT_INT || bt == VT_LLONG);
1677 /* check types for comparison or subtraction of pointers */
1678 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
1680 CType *type1, *type2, tmp_type1, tmp_type2;
1681 int bt1, bt2;
1683 /* null pointers are accepted for all comparisons as gcc */
1684 if (is_null_pointer(p1) || is_null_pointer(p2))
1685 return;
1686 type1 = &p1->type;
1687 type2 = &p2->type;
1688 bt1 = type1->t & VT_BTYPE;
1689 bt2 = type2->t & VT_BTYPE;
1690 /* accept comparison between pointer and integer with a warning */
1691 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
1692 if (op != TOK_LOR && op != TOK_LAND )
1693 tcc_warning("comparison between pointer and integer");
1694 return;
1697 /* both must be pointers or implicit function pointers */
1698 if (bt1 == VT_PTR) {
1699 type1 = pointed_type(type1);
1700 } else if (bt1 != VT_FUNC)
1701 goto invalid_operands;
1703 if (bt2 == VT_PTR) {
1704 type2 = pointed_type(type2);
1705 } else if (bt2 != VT_FUNC) {
1706 invalid_operands:
1707 tcc_error("invalid operands to binary %s", get_tok_str(op, NULL));
1709 if ((type1->t & VT_BTYPE) == VT_VOID ||
1710 (type2->t & VT_BTYPE) == VT_VOID)
1711 return;
1712 tmp_type1 = *type1;
1713 tmp_type2 = *type2;
1714 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1715 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1716 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
1717 /* gcc-like error if '-' is used */
1718 if (op == '-')
1719 goto invalid_operands;
1720 else
1721 tcc_warning("comparison of distinct pointer types lacks a cast");
1725 /* generic gen_op: handles types problems */
1726 ST_FUNC void gen_op(int op)
1728 int u, t1, t2, bt1, bt2, t;
1729 CType type1;
1731 t1 = vtop[-1].type.t;
1732 t2 = vtop[0].type.t;
1733 bt1 = t1 & VT_BTYPE;
1734 bt2 = t2 & VT_BTYPE;
1736 if (bt1 == VT_PTR || bt2 == VT_PTR) {
1737 /* at least one operand is a pointer */
1738 /* relationnal op: must be both pointers */
1739 if (op >= TOK_ULT && op <= TOK_LOR) {
1740 check_comparison_pointer_types(vtop - 1, vtop, op);
1741 /* pointers are handled are unsigned */
1742 #ifdef TCC_TARGET_X86_64
1743 t = VT_LLONG | VT_UNSIGNED;
1744 #else
1745 t = VT_INT | VT_UNSIGNED;
1746 #endif
1747 goto std_op;
1749 /* if both pointers, then it must be the '-' op */
1750 if (bt1 == VT_PTR && bt2 == VT_PTR) {
1751 if (op != '-')
1752 tcc_error("cannot use pointers here");
1753 check_comparison_pointer_types(vtop - 1, vtop, op);
1754 /* XXX: check that types are compatible */
1755 if (vtop[-1].type.t & VT_VLA) {
1756 vla_runtime_pointed_size(&vtop[-1].type);
1757 } else {
1758 vpushi(pointed_size(&vtop[-1].type));
1760 vrott(3);
1761 gen_opic(op);
1762 /* set to integer type */
1763 #ifdef TCC_TARGET_X86_64
1764 vtop->type.t = VT_LLONG;
1765 #else
1766 vtop->type.t = VT_INT;
1767 #endif
1768 vswap();
1769 gen_op(TOK_PDIV);
1770 } else {
1771 /* exactly one pointer : must be '+' or '-'. */
1772 if (op != '-' && op != '+')
1773 tcc_error("cannot use pointers here");
1774 /* Put pointer as first operand */
1775 if (bt2 == VT_PTR) {
1776 vswap();
1777 swap(&t1, &t2);
1779 type1 = vtop[-1].type;
1780 type1.t &= ~VT_ARRAY;
1781 if (vtop[-1].type.t & VT_VLA)
1782 vla_runtime_pointed_size(&vtop[-1].type);
1783 else {
1784 u = pointed_size(&vtop[-1].type);
1785 if (u < 0)
1786 tcc_error("unknown array element size");
1787 #ifdef TCC_TARGET_X86_64
1788 vpushll(u);
1789 #else
1790 /* XXX: cast to int ? (long long case) */
1791 vpushi(u);
1792 #endif
1794 gen_op('*');
1795 #ifdef CONFIG_TCC_BCHECK
1796 /* if evaluating constant expression, no code should be
1797 generated, so no bound check */
1798 if (tcc_state->do_bounds_check && !const_wanted) {
1799 /* if bounded pointers, we generate a special code to
1800 test bounds */
1801 if (op == '-') {
1802 vpushi(0);
1803 vswap();
1804 gen_op('-');
1806 gen_bounded_ptr_add();
1807 } else
1808 #endif
1810 gen_opic(op);
1812 /* put again type if gen_opic() swaped operands */
1813 vtop->type = type1;
1815 } else if (is_float(bt1) || is_float(bt2)) {
1816 /* compute bigger type and do implicit casts */
1817 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
1818 t = VT_LDOUBLE;
1819 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
1820 t = VT_DOUBLE;
1821 } else {
1822 t = VT_FLOAT;
1824 /* floats can only be used for a few operations */
1825 if (op != '+' && op != '-' && op != '*' && op != '/' &&
1826 (op < TOK_ULT || op > TOK_GT))
1827 tcc_error("invalid operands for binary operation");
1828 goto std_op;
1829 } else if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL) {
1830 t = bt1 == VT_LLONG ? VT_LLONG : VT_INT;
1831 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (t | VT_UNSIGNED))
1832 t |= VT_UNSIGNED;
1833 goto std_op;
1834 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
1835 /* cast to biggest op */
1836 t = VT_LLONG;
1837 /* convert to unsigned if it does not fit in a long long */
1838 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
1839 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
1840 t |= VT_UNSIGNED;
1841 goto std_op;
1842 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
1843 tcc_error("comparison of struct");
1844 } else {
1845 /* integer operations */
1846 t = VT_INT;
1847 /* convert to unsigned if it does not fit in an integer */
1848 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
1849 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
1850 t |= VT_UNSIGNED;
1851 std_op:
1852 /* XXX: currently, some unsigned operations are explicit, so
1853 we modify them here */
1854 if (t & VT_UNSIGNED) {
1855 if (op == TOK_SAR)
1856 op = TOK_SHR;
1857 else if (op == '/')
1858 op = TOK_UDIV;
1859 else if (op == '%')
1860 op = TOK_UMOD;
1861 else if (op == TOK_LT)
1862 op = TOK_ULT;
1863 else if (op == TOK_GT)
1864 op = TOK_UGT;
1865 else if (op == TOK_LE)
1866 op = TOK_ULE;
1867 else if (op == TOK_GE)
1868 op = TOK_UGE;
1870 vswap();
1871 type1.t = t;
1872 gen_cast(&type1);
1873 vswap();
1874 /* special case for shifts and long long: we keep the shift as
1875 an integer */
1876 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
1877 type1.t = VT_INT;
1878 gen_cast(&type1);
1879 if (is_float(t))
1880 gen_opif(op);
1881 else
1882 gen_opic(op);
1883 if (op >= TOK_ULT && op <= TOK_GT) {
1884 /* relationnal op: the result is an int */
1885 vtop->type.t = VT_INT;
1886 } else {
1887 vtop->type.t = t;
1892 #ifndef TCC_TARGET_ARM
1893 /* generic itof for unsigned long long case */
1894 static void gen_cvt_itof1(int t)
1896 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
1897 (VT_LLONG | VT_UNSIGNED)) {
1899 if (t == VT_FLOAT)
1900 vpush_global_sym(&func_old_type, TOK___floatundisf);
1901 #if LDOUBLE_SIZE != 8
1902 else if (t == VT_LDOUBLE)
1903 vpush_global_sym(&func_old_type, TOK___floatundixf);
1904 #endif
1905 else
1906 vpush_global_sym(&func_old_type, TOK___floatundidf);
1907 vrott(2);
1908 gfunc_call(1);
1909 vpushi(0);
1910 vtop->r = reg_fret(t);
1911 } else {
1912 gen_cvt_itof(t);
1915 #endif
1917 /* generic ftoi for unsigned long long case */
1918 static void gen_cvt_ftoi1(int t)
1920 int st;
1922 if (t == (VT_LLONG | VT_UNSIGNED)) {
1923 /* not handled natively */
1924 st = vtop->type.t & VT_BTYPE;
1925 if (st == VT_FLOAT)
1926 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
1927 #if LDOUBLE_SIZE != 8
1928 else if (st == VT_LDOUBLE)
1929 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
1930 #endif
1931 else
1932 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
1933 vrott(2);
1934 gfunc_call(1);
1935 vpushi(0);
1936 vtop->r = REG_IRET;
1937 vtop->r2 = REG_LRET;
1938 } else {
1939 gen_cvt_ftoi(t);
1943 /* force char or short cast */
1944 static void force_charshort_cast(int t)
1946 int bits, dbt;
1947 dbt = t & VT_BTYPE;
1948 /* XXX: add optimization if lvalue : just change type and offset */
1949 if (dbt == VT_BYTE)
1950 bits = 8;
1951 else
1952 bits = 16;
1953 if (t & VT_UNSIGNED) {
1954 vpushi((1 << bits) - 1);
1955 gen_op('&');
1956 } else {
1957 bits = 32 - bits;
1958 vpushi(bits);
1959 gen_op(TOK_SHL);
1960 /* result must be signed or the SAR is converted to an SHL
1961 This was not the case when "t" was a signed short
1962 and the last value on the stack was an unsigned int */
1963 vtop->type.t &= ~VT_UNSIGNED;
1964 vpushi(bits);
1965 gen_op(TOK_SAR);
1969 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
1970 static void gen_cast(CType *type)
1972 int sbt, dbt, sf, df, c, p;
1974 /* special delayed cast for char/short */
1975 /* XXX: in some cases (multiple cascaded casts), it may still
1976 be incorrect */
1977 if (vtop->r & VT_MUSTCAST) {
1978 vtop->r &= ~VT_MUSTCAST;
1979 force_charshort_cast(vtop->type.t);
1982 /* bitfields first get cast to ints */
1983 if (vtop->type.t & VT_BITFIELD) {
1984 gv(RC_INT);
1987 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
1988 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
1990 if (sbt != dbt) {
1991 sf = is_float(sbt);
1992 df = is_float(dbt);
1993 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1994 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
1995 if (c) {
1996 /* constant case: we can do it now */
1997 /* XXX: in ISOC, cannot do it if error in convert */
1998 if (sbt == VT_FLOAT)
1999 vtop->c.ld = vtop->c.f;
2000 else if (sbt == VT_DOUBLE)
2001 vtop->c.ld = vtop->c.d;
2003 if (df) {
2004 if ((sbt & VT_BTYPE) == VT_LLONG) {
2005 if (sbt & VT_UNSIGNED)
2006 vtop->c.ld = vtop->c.ull;
2007 else
2008 vtop->c.ld = vtop->c.ll;
2009 } else if(!sf) {
2010 if (sbt & VT_UNSIGNED)
2011 vtop->c.ld = vtop->c.ui;
2012 else
2013 vtop->c.ld = vtop->c.i;
2016 if (dbt == VT_FLOAT)
2017 vtop->c.f = (float)vtop->c.ld;
2018 else if (dbt == VT_DOUBLE)
2019 vtop->c.d = (double)vtop->c.ld;
2020 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
2021 vtop->c.ull = (unsigned long long)vtop->c.ld;
2022 } else if (sf && dbt == VT_BOOL) {
2023 vtop->c.i = (vtop->c.ld != 0);
2024 } else {
2025 if(sf)
2026 vtop->c.ll = (long long)vtop->c.ld;
2027 else if (sbt == (VT_LLONG|VT_UNSIGNED))
2028 vtop->c.ll = vtop->c.ull;
2029 else if (sbt & VT_UNSIGNED)
2030 vtop->c.ll = vtop->c.ui;
2031 #ifdef TCC_TARGET_X86_64
2032 else if (sbt == VT_PTR)
2034 #endif
2035 else if (sbt != VT_LLONG)
2036 vtop->c.ll = vtop->c.i;
2038 if (dbt == (VT_LLONG|VT_UNSIGNED))
2039 vtop->c.ull = vtop->c.ll;
2040 else if (dbt == VT_BOOL)
2041 vtop->c.i = (vtop->c.ll != 0);
2042 #ifdef TCC_TARGET_X86_64
2043 else if (dbt == VT_PTR)
2045 #endif
2046 else if (dbt != VT_LLONG) {
2047 int s = 0;
2048 if ((dbt & VT_BTYPE) == VT_BYTE)
2049 s = 24;
2050 else if ((dbt & VT_BTYPE) == VT_SHORT)
2051 s = 16;
2052 if(dbt & VT_UNSIGNED)
2053 vtop->c.ui = ((unsigned int)vtop->c.ll << s) >> s;
2054 else
2055 vtop->c.i = ((int)vtop->c.ll << s) >> s;
2058 } else if (p && dbt == VT_BOOL) {
2059 vtop->r = VT_CONST;
2060 vtop->c.i = 1;
2061 } else if (!nocode_wanted) {
2062 /* non constant case: generate code */
2063 if (sf && df) {
2064 /* convert from fp to fp */
2065 gen_cvt_ftof(dbt);
2066 } else if (df) {
2067 /* convert int to fp */
2068 gen_cvt_itof1(dbt);
2069 } else if (sf) {
2070 /* convert fp to int */
2071 if (dbt == VT_BOOL) {
2072 vpushi(0);
2073 gen_op(TOK_NE);
2074 } else {
2075 /* we handle char/short/etc... with generic code */
2076 if (dbt != (VT_INT | VT_UNSIGNED) &&
2077 dbt != (VT_LLONG | VT_UNSIGNED) &&
2078 dbt != VT_LLONG)
2079 dbt = VT_INT;
2080 gen_cvt_ftoi1(dbt);
2081 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
2082 /* additional cast for char/short... */
2083 vtop->type.t = dbt;
2084 gen_cast(type);
2087 #ifndef TCC_TARGET_X86_64
2088 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
2089 if ((sbt & VT_BTYPE) != VT_LLONG) {
2090 /* scalar to long long */
2091 /* machine independent conversion */
2092 gv(RC_INT);
2093 /* generate high word */
2094 if (sbt == (VT_INT | VT_UNSIGNED)) {
2095 vpushi(0);
2096 gv(RC_INT);
2097 } else {
2098 if (sbt == VT_PTR) {
2099 /* cast from pointer to int before we apply
2100 shift operation, which pointers don't support*/
2101 gen_cast(&int_type);
2103 gv_dup();
2104 vpushi(31);
2105 gen_op(TOK_SAR);
2107 /* patch second register */
2108 vtop[-1].r2 = vtop->r;
2109 vpop();
2111 #else
2112 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
2113 (dbt & VT_BTYPE) == VT_PTR ||
2114 (dbt & VT_BTYPE) == VT_FUNC) {
2115 if ((sbt & VT_BTYPE) != VT_LLONG &&
2116 (sbt & VT_BTYPE) != VT_PTR &&
2117 (sbt & VT_BTYPE) != VT_FUNC) {
2118 /* need to convert from 32bit to 64bit */
2119 int r = gv(RC_INT);
2120 if (sbt != (VT_INT | VT_UNSIGNED)) {
2121 /* x86_64 specific: movslq */
2122 o(0x6348);
2123 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
2126 #endif
2127 } else if (dbt == VT_BOOL) {
2128 /* scalar to bool */
2129 vpushi(0);
2130 gen_op(TOK_NE);
2131 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
2132 (dbt & VT_BTYPE) == VT_SHORT) {
2133 if (sbt == VT_PTR) {
2134 vtop->type.t = VT_INT;
2135 tcc_warning("nonportable conversion from pointer to char/short");
2137 force_charshort_cast(dbt);
2138 } else if ((dbt & VT_BTYPE) == VT_INT) {
2139 /* scalar to int */
2140 if (sbt == VT_LLONG) {
2141 /* from long long: just take low order word */
2142 lexpand();
2143 vpop();
2145 /* if lvalue and single word type, nothing to do because
2146 the lvalue already contains the real type size (see
2147 VT_LVAL_xxx constants) */
2150 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
2151 /* if we are casting between pointer types,
2152 we must update the VT_LVAL_xxx size */
2153 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
2154 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
2156 vtop->type = *type;
2159 /* return type size as known at compile time. Put alignment at 'a' */
2160 ST_FUNC int type_size(CType *type, int *a)
2162 Sym *s;
2163 int bt;
2164 size_t size;
2166 bt = type->t & VT_BTYPE;
2167 if (bt == VT_STRUCT) {
2168 assert(!(type->t & VT_VLS));
2169 /* struct/union */
2170 s = type->ref;
2171 *a = s->r;
2172 size = s->c;
2173 } else if (bt == VT_PTR) {
2174 if (type->t & VT_ARRAY) {
2175 int ts;
2176 s = type->ref;
2177 ts = type_size(&s->type, a);
2178 if (ts < 0 && s->c < 0)
2179 ts = -ts;
2180 size = (size_t)ts * s->c;
2181 } else {
2182 *a = PTR_SIZE;
2183 size = PTR_SIZE;
2185 } else if (bt == VT_LDOUBLE) {
2186 *a = LDOUBLE_ALIGN;
2187 size = LDOUBLE_SIZE;
2188 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
2189 #ifdef TCC_TARGET_I386
2190 #ifdef TCC_TARGET_PE
2191 *a = 8;
2192 #else
2193 *a = 4;
2194 #endif
2195 #elif defined(TCC_TARGET_ARM)
2196 #ifdef TCC_ARM_EABI
2197 *a = 8;
2198 #else
2199 *a = 4;
2200 #endif
2201 #else
2202 *a = 8;
2203 #endif
2204 size = 8;
2205 } else if (bt == VT_INT || bt == VT_ENUM || bt == VT_FLOAT) {
2206 *a = 4;
2207 size = 4;
2208 } else if (bt == VT_SHORT) {
2209 *a = 2;
2210 size = 2;
2211 } else if (bt == VT_QLONG || bt == VT_QFLOAT) {
2212 *a = 8;
2213 size = 16;
2214 } else {
2215 /* char, void, function, _Bool */
2216 *a = 1;
2217 size = 1;
2219 assert(size == (int)size);
2220 return (int)size;
2223 /* push type size as known at runtime time on top of value stack. Put
2224 alignment at 'a' */
2225 ST_FUNC void vla_runtime_type_size(CType *type, int *a)
2227 if (type->t & VT_VLA) {
2228 vset(&int_type, VT_LOCAL|VT_LVAL, type->ref->c);
2229 } else {
2230 vpushi(type_size(type, a));
2234 static void vla_sp_save(void) {
2235 if (!(vla_flags & VLA_SP_LOC_SET)) {
2236 *vla_sp_loc = loc_stack(PTR_SIZE, 1);
2237 vla_flags |= VLA_SP_LOC_SET;
2239 if (!(vla_flags & VLA_SP_SAVED)) {
2240 gen_vla_sp_save(*vla_sp_loc);
2241 vla_flags |= VLA_SP_SAVED;
2245 /* return the pointed type of t */
2246 static inline CType *pointed_type(CType *type)
2248 return &type->ref->type;
2251 /* modify type so that its it is a pointer to type. */
2252 ST_FUNC void mk_pointer(CType *type)
2254 Sym *s;
2255 s = sym_push(SYM_FIELD, type, 0, -1);
2256 type->t = VT_PTR | (type->t & ~VT_TYPE);
2257 type->ref = s;
2260 /* compare function types. OLD functions match any new functions */
2261 static int is_compatible_func(CType *type1, CType *type2)
2263 Sym *s1, *s2;
2265 s1 = type1->ref;
2266 s2 = type2->ref;
2267 if (!is_compatible_types(&s1->type, &s2->type))
2268 return 0;
2269 /* check func_call */
2270 if (s1->a.func_call != s2->a.func_call)
2271 return 0;
2272 /* XXX: not complete */
2273 if (s1->c == FUNC_OLD || s2->c == FUNC_OLD)
2274 return 1;
2275 if (s1->c != s2->c)
2276 return 0;
2277 while (s1 != NULL) {
2278 if (s2 == NULL)
2279 return 0;
2280 if (!is_compatible_parameter_types(&s1->type, &s2->type))
2281 return 0;
2282 s1 = s1->next;
2283 s2 = s2->next;
2285 if (s2)
2286 return 0;
2287 return 1;
2290 /* return true if type1 and type2 are the same. If unqualified is
2291 true, qualifiers on the types are ignored.
2293 - enums are not checked as gcc __builtin_types_compatible_p ()
2295 static int compare_types(CType *type1, CType *type2, int unqualified)
2297 int bt1, t1, t2;
2299 t1 = type1->t & VT_TYPE;
2300 t2 = type2->t & VT_TYPE;
2301 if (unqualified) {
2302 /* strip qualifiers before comparing */
2303 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
2304 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
2306 /* Default Vs explicit signedness only matters for char */
2307 if ((t1 & VT_BTYPE) != VT_BYTE) {
2308 t1 &= ~VT_DEFSIGN;
2309 t2 &= ~VT_DEFSIGN;
2311 /* XXX: bitfields ? */
2312 if (t1 != t2)
2313 return 0;
2314 /* test more complicated cases */
2315 bt1 = t1 & VT_BTYPE;
2316 if (bt1 == VT_PTR) {
2317 type1 = pointed_type(type1);
2318 type2 = pointed_type(type2);
2319 return is_compatible_types(type1, type2);
2320 } else if (bt1 == VT_STRUCT) {
2321 return (type1->ref == type2->ref);
2322 } else if (bt1 == VT_FUNC) {
2323 return is_compatible_func(type1, type2);
2324 } else {
2325 return 1;
2329 /* return true if type1 and type2 are exactly the same (including
2330 qualifiers).
2332 static int is_compatible_types(CType *type1, CType *type2)
2334 return compare_types(type1,type2,0);
2337 /* return true if type1 and type2 are the same (ignoring qualifiers).
2339 static int is_compatible_parameter_types(CType *type1, CType *type2)
2341 return compare_types(type1,type2,1);
2344 /* print a type. If 'varstr' is not NULL, then the variable is also
2345 printed in the type */
2346 /* XXX: union */
2347 /* XXX: add array and function pointers */
2348 static void type_to_str(char *buf, int buf_size,
2349 CType *type, const char *varstr)
2351 int bt, v, t;
2352 Sym *s, *sa;
2353 char buf1[256];
2354 const char *tstr;
2356 t = type->t & VT_TYPE;
2357 bt = t & VT_BTYPE;
2358 buf[0] = '\0';
2359 if (t & VT_CONSTANT)
2360 pstrcat(buf, buf_size, "const ");
2361 if (t & VT_VOLATILE)
2362 pstrcat(buf, buf_size, "volatile ");
2363 if ((t & (VT_DEFSIGN | VT_UNSIGNED)) == (VT_DEFSIGN | VT_UNSIGNED))
2364 pstrcat(buf, buf_size, "unsigned ");
2365 else if (t & VT_DEFSIGN)
2366 pstrcat(buf, buf_size, "signed ");
2367 switch(bt) {
2368 case VT_VOID:
2369 tstr = "void";
2370 goto add_tstr;
2371 case VT_BOOL:
2372 tstr = "_Bool";
2373 goto add_tstr;
2374 case VT_BYTE:
2375 tstr = "char";
2376 goto add_tstr;
2377 case VT_SHORT:
2378 tstr = "short";
2379 goto add_tstr;
2380 case VT_INT:
2381 tstr = "int";
2382 goto add_tstr;
2383 case VT_LONG:
2384 tstr = "long";
2385 goto add_tstr;
2386 case VT_LLONG:
2387 tstr = "long long";
2388 goto add_tstr;
2389 case VT_FLOAT:
2390 tstr = "float";
2391 goto add_tstr;
2392 case VT_DOUBLE:
2393 tstr = "double";
2394 goto add_tstr;
2395 case VT_LDOUBLE:
2396 tstr = "long double";
2397 add_tstr:
2398 pstrcat(buf, buf_size, tstr);
2399 break;
2400 case VT_ENUM:
2401 case VT_STRUCT:
2402 if (bt == VT_STRUCT)
2403 tstr = "struct ";
2404 else
2405 tstr = "enum ";
2406 pstrcat(buf, buf_size, tstr);
2407 v = type->ref->v & ~SYM_STRUCT;
2408 if (v >= SYM_FIRST_ANOM)
2409 pstrcat(buf, buf_size, "<anonymous>");
2410 else
2411 pstrcat(buf, buf_size, get_tok_str(v, NULL));
2412 break;
2413 case VT_FUNC:
2414 s = type->ref;
2415 type_to_str(buf, buf_size, &s->type, varstr);
2416 pstrcat(buf, buf_size, "(");
2417 sa = s->next;
2418 while (sa != NULL) {
2419 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
2420 pstrcat(buf, buf_size, buf1);
2421 sa = sa->next;
2422 if (sa)
2423 pstrcat(buf, buf_size, ", ");
2425 pstrcat(buf, buf_size, ")");
2426 goto no_var;
2427 case VT_PTR:
2428 s = type->ref;
2429 pstrcpy(buf1, sizeof(buf1), "*");
2430 if (varstr)
2431 pstrcat(buf1, sizeof(buf1), varstr);
2432 type_to_str(buf, buf_size, &s->type, buf1);
2433 goto no_var;
2435 if (varstr) {
2436 pstrcat(buf, buf_size, " ");
2437 pstrcat(buf, buf_size, varstr);
2439 no_var: ;
2442 /* verify type compatibility to store vtop in 'dt' type, and generate
2443 casts if needed. */
2444 static void gen_assign_cast(CType *dt)
2446 CType *st, *type1, *type2, tmp_type1, tmp_type2;
2447 char buf1[256], buf2[256];
2448 int dbt, sbt;
2450 st = &vtop->type; /* source type */
2451 dbt = dt->t & VT_BTYPE;
2452 sbt = st->t & VT_BTYPE;
2453 if (sbt == VT_VOID || dbt == VT_VOID)
2454 tcc_error("cannot cast from/to void");
2455 if (dt->t & VT_CONSTANT)
2456 tcc_warning("assignment of read-only location");
2457 switch(dbt) {
2458 case VT_PTR:
2459 /* special cases for pointers */
2460 /* '0' can also be a pointer */
2461 if (is_null_pointer(vtop))
2462 goto type_ok;
2463 /* accept implicit pointer to integer cast with warning */
2464 if (is_integer_btype(sbt)) {
2465 tcc_warning("assignment makes pointer from integer without a cast");
2466 goto type_ok;
2468 type1 = pointed_type(dt);
2469 /* a function is implicitely a function pointer */
2470 if (sbt == VT_FUNC) {
2471 if ((type1->t & VT_BTYPE) != VT_VOID &&
2472 !is_compatible_types(pointed_type(dt), st))
2473 tcc_warning("assignment from incompatible pointer type");
2474 goto type_ok;
2476 if (sbt != VT_PTR)
2477 goto error;
2478 type2 = pointed_type(st);
2479 if ((type1->t & VT_BTYPE) == VT_VOID ||
2480 (type2->t & VT_BTYPE) == VT_VOID) {
2481 /* void * can match anything */
2482 } else {
2483 /* exact type match, except for unsigned */
2484 tmp_type1 = *type1;
2485 tmp_type2 = *type2;
2486 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT |
2487 VT_VOLATILE);
2488 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT |
2489 VT_VOLATILE);
2490 if (!is_compatible_types(&tmp_type1, &tmp_type2))
2491 tcc_warning("assignment from incompatible pointer type");
2493 /* check const and volatile */
2494 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
2495 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
2496 tcc_warning("assignment discards qualifiers from pointer target type");
2497 break;
2498 case VT_BYTE:
2499 case VT_SHORT:
2500 case VT_INT:
2501 case VT_LLONG:
2502 if (sbt == VT_PTR || sbt == VT_FUNC) {
2503 tcc_warning("assignment makes integer from pointer without a cast");
2505 if (sbt == VT_STRUCT)
2506 goto error;
2507 /* XXX: more tests */
2508 break;
2509 case VT_STRUCT:
2510 tmp_type1 = *dt;
2511 tmp_type2 = *st;
2512 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2513 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2514 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2515 error:
2516 type_to_str(buf1, sizeof(buf1), st, NULL);
2517 type_to_str(buf2, sizeof(buf2), dt, NULL);
2518 tcc_error("cannot cast '%s' to '%s'", buf1, buf2);
2520 break;
2522 type_ok:
2523 gen_cast(dt);
2526 static void vstore_im(){
2527 int rc, ft, sbt, dbt, t, r;
2528 ft = vtop[-1].type.t;
2529 sbt = vtop->type.t & VT_BTYPE;
2530 dbt = ft & VT_BTYPE;
2531 if (is_float(ft)) {
2532 rc = RC_FLOAT;
2533 #ifdef TCC_TARGET_X86_64
2534 if (dbt == VT_LDOUBLE) {
2535 rc = RC_ST0;
2537 #endif
2538 }else
2539 rc = RC_INT;
2540 r = gv(rc); /* generate value */
2541 /* if lvalue was saved on stack, must read it */
2542 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
2543 SValue sv;
2544 t = get_reg(RC_INT);
2545 #ifdef TCC_TARGET_X86_64
2546 sv.type.t = VT_PTR;
2547 #else
2548 sv.type.t = VT_INT;
2549 #endif
2550 sv.r = VT_LOCAL | VT_LVAL | VT_TMP;
2551 sv.c.ul = vtop[-1].c.ul;
2552 load(t, &sv);
2553 vtop[-1].r = t | VT_LVAL;
2554 vtop[-1].c.ul = 0;
2556 /* two word case handling : store second register at word + 4 */
2557 #ifdef TCC_TARGET_X86_64
2558 if ((dbt == VT_QLONG) || (dbt == VT_QFLOAT))
2559 #else
2560 if (dbt == VT_LLONG)
2561 #endif
2563 #ifdef TCC_TARGET_X86_64
2564 int load_size = 8, load_type = (sbt == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
2565 #else
2566 int load_size = 4, load_type = VT_INT;
2567 #endif
2568 vtop[-1].type.t = load_type;
2569 store(r, vtop - 1);
2570 vswap();
2571 /* convert to int to increment easily */
2572 vtop->type = char_pointer_type;
2573 gaddrof();
2574 vpushi(load_size);
2575 gen_op('+');
2576 vtop->r |= VT_LVAL;
2577 vswap();
2578 vtop[-1].type.t = load_type;
2579 /* XXX: it works because r2 is spilled last ! */
2580 store(vtop->r2, vtop - 1);
2581 vtop->type.t = ft;
2582 vtop[-1].type.t = ft;
2583 } else {
2584 store(r, vtop - 1);
2588 /* store vtop in lvalue pushed on stack */
2589 ST_FUNC void vstore(void)
2591 int sbt, dbt, ft, size, align, bit_size, bit_pos, delayed_cast;
2593 ft = vtop[-1].type.t;
2594 sbt = vtop->type.t & VT_BTYPE;
2595 dbt = ft & VT_BTYPE;
2596 if ((((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
2597 (sbt == VT_INT && dbt == VT_SHORT)) && !(vtop->type.t & VT_BITFIELD)) {
2598 /* optimize char/short casts */
2599 delayed_cast = VT_MUSTCAST;
2600 vtop->type.t = ft & (VT_TYPE & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT)));
2601 /* XXX: factorize */
2602 if (ft & VT_CONSTANT)
2603 tcc_warning("assignment of read-only location");
2604 } else {
2605 delayed_cast = 0;
2606 if (!(ft & VT_BITFIELD))
2607 gen_assign_cast(&vtop[-1].type);
2610 if (sbt == VT_STRUCT) {
2611 /* if structure, only generate pointer */
2612 /* structure assignment : generate memcpy */
2613 /* XXX: optimize if small size */
2614 if (!nocode_wanted) {
2615 SValue ret;
2616 int ret_nregs, ret_align;
2617 ret_nregs = gfunc_sret(&vtop->type, func_var, &ret.type, &ret_align);
2618 if(ret_nregs){
2619 vswap();
2620 vpushv(vtop - 1);
2621 vtop[0].type = ret.type;
2622 vtop[-1].type = ret.type;
2623 vstore_im();
2624 vtop -=2;
2625 }else{
2626 size = type_size(&vtop->type, &align);
2627 /* destination */
2628 vswap();
2629 vtop->type.t = VT_PTR;
2630 gaddrof();
2632 /* address of memcpy() */
2633 #ifdef TCC_ARM_EABI
2634 if(!(align & 7))
2635 vpush_global_sym(&func_old_type, TOK_memcpy8);
2636 else if(!(align & 3))
2637 vpush_global_sym(&func_old_type, TOK_memcpy4);
2638 else
2639 #endif
2640 vpush_global_sym(&func_old_type, TOK_memcpy);
2642 vswap();
2643 /* source */
2644 vpushv(vtop - 2);
2645 vtop->type.t = VT_PTR;
2646 gaddrof();
2647 /* type size */
2648 vpushi(size);
2649 gfunc_call(3);
2651 } else {
2652 vswap();
2653 vpop();
2655 /* leave source on stack */
2656 } else if (ft & VT_BITFIELD) {
2657 /* bitfield store handling */
2658 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
2659 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
2660 /* remove bit field info to avoid loops */
2661 vtop[-1].type.t = ft & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
2662 /* duplicate source into other register */
2663 if(dbt == VT_BOOL) {
2664 gen_cast(&vtop[-1].type);
2665 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
2668 /* duplicate destination */
2669 vdup();
2670 vtop[-1] = vtop[-2];
2672 /* mask and shift source */
2673 if(dbt != VT_BOOL) {
2674 if(dbt == VT_LLONG) {
2675 vpushll((1ULL << bit_size) - 1ULL);
2676 } else {
2677 vpushi((1 << bit_size) - 1);
2679 gen_op('&');
2681 vpushi(bit_pos);
2682 gen_op(TOK_SHL);
2683 /* load destination, mask and or with source */
2684 vswap();
2685 if(dbt == VT_LLONG) {
2686 vpushll(~(((1ULL << bit_size) - 1ULL) << bit_pos));
2687 } else {
2688 vpushi(~(((1 << bit_size) - 1) << bit_pos));
2690 gen_op('&');
2691 gen_op('|');
2692 /* store result */
2693 vstore();
2694 } else {
2695 #ifdef CONFIG_TCC_BCHECK
2696 /* bound check case */
2697 if (vtop[-1].r & VT_MUSTBOUND) {
2698 vswap();
2699 gbound();
2700 vswap();
2702 #endif
2703 if (!nocode_wanted) {
2704 vstore_im();
2706 vswap();
2707 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
2708 vtop->r |= delayed_cast;
2712 /* post defines POST/PRE add. c is the token ++ or -- */
2713 ST_FUNC void inc(int post, int c)
2715 test_lvalue();
2716 vdup(); /* save lvalue */
2717 if (post) {
2718 gv_dup(); /* duplicate value */
2719 vrotb(3);
2720 vrotb(3);
2722 /* add constant */
2723 vpushi(c - TOK_MID);
2724 gen_op('+');
2725 vstore(); /* store value */
2726 if (post)
2727 vpop(); /* if post op, return saved value */
2730 /* Parse GNUC __attribute__ extension. Currently, the following
2731 extensions are recognized:
2732 - aligned(n) : set data/function alignment.
2733 - packed : force data alignment to 1
2734 - section(x) : generate data/code in this section.
2735 - unused : currently ignored, but may be used someday.
2736 - regparm(n) : pass function parameters in registers (i386 only)
2738 static void parse_attribute(AttributeDef *ad)
2740 int t, n;
2742 while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
2743 next();
2744 skip('(');
2745 skip('(');
2746 while (tok != ')') {
2747 if (tok < TOK_IDENT)
2748 expect("attribute name");
2749 t = tok;
2750 next();
2751 switch(t) {
2752 case TOK_SECTION1:
2753 case TOK_SECTION2:
2754 skip('(');
2755 if (tok != TOK_STR)
2756 expect("section name");
2757 ad->section = find_section(tcc_state, (char *)tokc.cstr->data);
2758 next();
2759 skip(')');
2760 break;
2761 case TOK_ALIAS1:
2762 case TOK_ALIAS2:
2763 skip('(');
2764 if (tok != TOK_STR)
2765 expect("alias(\"target\")");
2766 ad->alias_target = /* save string as token, for later */
2767 tok_alloc((char*)tokc.cstr->data, tokc.cstr->size-1)->tok;
2768 next();
2769 skip(')');
2770 break;
2771 case TOK_VISIBILITY1:
2772 case TOK_VISIBILITY2:
2773 skip('(');
2774 if (tok != TOK_STR)
2775 expect("visibility(\"default|hidden|internal|protected\")");
2776 if (!strcmp (tokc.cstr->data, "default"))
2777 ad->a.visibility = STV_DEFAULT;
2778 else if (!strcmp (tokc.cstr->data, "hidden"))
2779 ad->a.visibility = STV_HIDDEN;
2780 else if (!strcmp (tokc.cstr->data, "internal"))
2781 ad->a.visibility = STV_INTERNAL;
2782 else if (!strcmp (tokc.cstr->data, "protected"))
2783 ad->a.visibility = STV_PROTECTED;
2784 else
2785 expect("visibility(\"default|hidden|internal|protected\")");
2786 next();
2787 skip(')');
2788 break;
2789 case TOK_ALIGNED1:
2790 case TOK_ALIGNED2:
2791 if (tok == '(') {
2792 next();
2793 n = expr_const();
2794 if (n <= 0 || (n & (n - 1)) != 0)
2795 tcc_error("alignment must be a positive power of two");
2796 skip(')');
2797 } else {
2798 n = MAX_ALIGN;
2800 ad->a.aligned = n;
2801 break;
2802 case TOK_PACKED1:
2803 case TOK_PACKED2:
2804 ad->a.packed = 1;
2805 break;
2806 case TOK_WEAK1:
2807 case TOK_WEAK2:
2808 ad->a.weak = 1;
2809 break;
2810 case TOK_UNUSED1:
2811 case TOK_UNUSED2:
2812 /* currently, no need to handle it because tcc does not
2813 track unused objects */
2814 break;
2815 case TOK_NORETURN1:
2816 case TOK_NORETURN2:
2817 /* currently, no need to handle it because tcc does not
2818 track unused objects */
2819 break;
2820 case TOK_CDECL1:
2821 case TOK_CDECL2:
2822 case TOK_CDECL3:
2823 ad->a.func_call = FUNC_CDECL;
2824 break;
2825 case TOK_STDCALL1:
2826 case TOK_STDCALL2:
2827 case TOK_STDCALL3:
2828 ad->a.func_call = FUNC_STDCALL;
2829 break;
2830 #ifdef TCC_TARGET_I386
2831 case TOK_REGPARM1:
2832 case TOK_REGPARM2:
2833 skip('(');
2834 n = expr_const();
2835 if (n > 3)
2836 n = 3;
2837 else if (n < 0)
2838 n = 0;
2839 if (n > 0)
2840 ad->a.func_call = FUNC_FASTCALL1 + n - 1;
2841 skip(')');
2842 break;
2843 case TOK_FASTCALL1:
2844 case TOK_FASTCALL2:
2845 case TOK_FASTCALL3:
2846 ad->a.func_call = FUNC_FASTCALLW;
2847 break;
2848 #endif
2849 case TOK_MODE:
2850 skip('(');
2851 switch(tok) {
2852 case TOK_MODE_DI:
2853 ad->a.mode = VT_LLONG + 1;
2854 break;
2855 case TOK_MODE_HI:
2856 ad->a.mode = VT_SHORT + 1;
2857 break;
2858 case TOK_MODE_SI:
2859 ad->a.mode = VT_INT + 1;
2860 break;
2861 default:
2862 tcc_warning("__mode__(%s) not supported\n", get_tok_str(tok, NULL));
2863 break;
2865 next();
2866 skip(')');
2867 break;
2868 case TOK_DLLEXPORT:
2869 ad->a.func_export = 1;
2870 break;
2871 case TOK_DLLIMPORT:
2872 ad->a.func_import = 1;
2873 break;
2874 default:
2875 if (tcc_state->warn_unsupported)
2876 tcc_warning("'%s' attribute ignored", get_tok_str(t, NULL));
2877 /* skip parameters */
2878 if (tok == '(') {
2879 int parenthesis = 0;
2880 do {
2881 if (tok == '(')
2882 parenthesis++;
2883 else if (tok == ')')
2884 parenthesis--;
2885 next();
2886 } while (parenthesis && tok != -1);
2888 break;
2890 if (tok != ',')
2891 break;
2892 next();
2894 skip(')');
2895 skip(')');
2899 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
2900 static void struct_decl(CType *type, int u, int tdef)
2902 int a, v, size, align, maxalign, c, offset, flexible;
2903 int bit_size, bit_pos, bsize, bt, lbit_pos, prevbt;
2904 Sym *s, *ss, *ass, **ps;
2905 AttributeDef ad;
2906 CType type1, btype;
2908 a = tok; /* save decl type */
2909 next();
2910 if (tok != '{') {
2911 v = tok;
2912 next();
2913 /* struct already defined ? return it */
2914 if (v < TOK_IDENT)
2915 expect("struct/union/enum name");
2916 s = struct_find(v);
2917 if (s) {
2918 if (s->type.t != a)
2919 tcc_error("invalid type");
2920 goto do_decl;
2921 } else if (tok >= TOK_IDENT && !tdef)
2922 tcc_error("unknown struct/union/enum");
2923 } else {
2924 v = anon_sym++;
2926 type1.t = a;
2927 type1.ref = NULL;
2928 /* we put an undefined size for struct/union */
2929 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
2930 s->r = 0; /* default alignment is zero as gcc */
2931 /* put struct/union/enum name in type */
2932 do_decl:
2933 type->t = u;
2934 type->ref = s;
2936 if (tok == '{') {
2937 next();
2938 if (s->c != -1)
2939 tcc_error("struct/union/enum already defined");
2940 /* cannot be empty */
2941 c = 0;
2942 /* non empty enums are not allowed */
2943 if (a == TOK_ENUM) {
2944 for(;;) {
2945 v = tok;
2946 if (v < TOK_UIDENT)
2947 expect("identifier");
2948 ss = sym_find(v);
2949 if (ss && !local_stack)
2950 tcc_error("redefinition of enumerator '%s'",
2951 get_tok_str(v, NULL));
2952 next();
2953 if (tok == '=') {
2954 next();
2955 c = expr_const();
2957 /* enum symbols have static storage */
2958 ss = sym_push(v, &int_type, VT_CONST, c);
2959 ss->type.t |= VT_STATIC;
2960 if (tok != ',')
2961 break;
2962 next();
2963 c++;
2964 /* NOTE: we accept a trailing comma */
2965 if (tok == '}')
2966 break;
2968 s->c = type_size(&int_type, &align);
2969 skip('}');
2970 } else {
2971 maxalign = 1;
2972 ps = &s->next;
2973 prevbt = VT_INT;
2974 bit_pos = 0;
2975 offset = 0;
2976 flexible = 0;
2977 while (tok != '}') {
2978 parse_btype(&btype, &ad);
2979 while (1) {
2980 if (flexible)
2981 tcc_error("flexible array member '%s' not at the end of struct",
2982 get_tok_str(v, NULL));
2983 bit_size = -1;
2984 v = 0;
2985 type1 = btype;
2986 if (tok != ':') {
2987 type_decl(&type1, &ad, &v, TYPE_DIRECT | TYPE_ABSTRACT);
2988 if (v == 0 && (type1.t & VT_BTYPE) != VT_STRUCT)
2989 expect("identifier");
2990 if (type_size(&type1, &align) < 0) {
2991 if ((a == TOK_STRUCT) && (type1.t & VT_ARRAY) && c)
2992 flexible = 1;
2993 else
2994 tcc_error("field '%s' has incomplete type",
2995 get_tok_str(v, NULL));
2997 if ((type1.t & VT_BTYPE) == VT_FUNC ||
2998 (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
2999 tcc_error("invalid type for '%s'",
3000 get_tok_str(v, NULL));
3002 if (tok == ':') {
3003 next();
3004 bit_size = expr_const();
3005 /* XXX: handle v = 0 case for messages */
3006 if (bit_size < 0)
3007 tcc_error("negative width in bit-field '%s'",
3008 get_tok_str(v, NULL));
3009 if (v && bit_size == 0)
3010 tcc_error("zero width for bit-field '%s'",
3011 get_tok_str(v, NULL));
3013 size = type_size(&type1, &align);
3014 if (ad.a.aligned) {
3015 if (align < ad.a.aligned)
3016 align = ad.a.aligned;
3017 } else if (ad.a.packed) {
3018 align = 1;
3019 } else if (*tcc_state->pack_stack_ptr) {
3020 if (align > *tcc_state->pack_stack_ptr)
3021 align = *tcc_state->pack_stack_ptr;
3023 lbit_pos = 0;
3024 if (bit_size >= 0) {
3025 bt = type1.t & VT_BTYPE;
3026 if (bt != VT_INT &&
3027 bt != VT_BYTE &&
3028 bt != VT_SHORT &&
3029 bt != VT_BOOL &&
3030 bt != VT_ENUM &&
3031 bt != VT_LLONG)
3032 tcc_error("bitfields must have scalar type");
3033 bsize = size * 8;
3034 if (bit_size > bsize) {
3035 tcc_error("width of '%s' exceeds its type",
3036 get_tok_str(v, NULL));
3037 } else if (bit_size == bsize) {
3038 /* no need for bit fields */
3039 bit_pos = 0;
3040 } else if (bit_size == 0) {
3041 /* XXX: what to do if only padding in a
3042 structure ? */
3043 /* zero size: means to pad */
3044 bit_pos = 0;
3045 } else {
3046 /* we do not have enough room ?
3047 did the type change?
3048 is it a union? */
3049 if ((bit_pos + bit_size) > bsize ||
3050 bt != prevbt || a == TOK_UNION)
3051 bit_pos = 0;
3052 lbit_pos = bit_pos;
3053 /* XXX: handle LSB first */
3054 type1.t |= VT_BITFIELD |
3055 (bit_pos << VT_STRUCT_SHIFT) |
3056 (bit_size << (VT_STRUCT_SHIFT + 6));
3057 bit_pos += bit_size;
3059 prevbt = bt;
3060 } else {
3061 bit_pos = 0;
3063 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
3064 /* add new memory data only if starting
3065 bit field */
3066 if (lbit_pos == 0) {
3067 if (a == TOK_STRUCT) {
3068 c = (c + align - 1) & -align;
3069 offset = c;
3070 if (size > 0)
3071 c += size;
3072 } else {
3073 offset = 0;
3074 if (size > c)
3075 c = size;
3077 if (align > maxalign)
3078 maxalign = align;
3080 #if 0
3081 printf("add field %s offset=%d",
3082 get_tok_str(v, NULL), offset);
3083 if (type1.t & VT_BITFIELD) {
3084 printf(" pos=%d size=%d",
3085 (type1.t >> VT_STRUCT_SHIFT) & 0x3f,
3086 (type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
3088 printf("\n");
3089 #endif
3091 if (v == 0 && (type1.t & VT_BTYPE) == VT_STRUCT) {
3092 ass = type1.ref;
3093 while ((ass = ass->next) != NULL) {
3094 ss = sym_push(ass->v, &ass->type, 0, offset + ass->c);
3095 *ps = ss;
3096 ps = &ss->next;
3098 } else if (v) {
3099 ss = sym_push(v | SYM_FIELD, &type1, 0, offset);
3100 *ps = ss;
3101 ps = &ss->next;
3103 if (tok == ';' || tok == TOK_EOF)
3104 break;
3105 skip(',');
3107 skip(';');
3109 skip('}');
3110 /* store size and alignment */
3111 s->c = (c + maxalign - 1) & -maxalign;
3112 s->r = maxalign;
3117 /* return 1 if basic type is a type size (short, long, long long) */
3118 ST_FUNC int is_btype_size(int bt)
3120 return bt == VT_SHORT || bt == VT_LONG || bt == VT_LLONG;
3123 /* return 0 if no type declaration. otherwise, return the basic type
3124 and skip it.
3126 static int parse_btype(CType *type, AttributeDef *ad)
3128 int t, u, bt_size, complete, type_found, typespec_found;
3129 Sym *s;
3130 CType type1;
3132 memset(ad, 0, sizeof(AttributeDef));
3133 complete = 0;
3134 type_found = 0;
3135 typespec_found = 0;
3136 t = 0;
3137 while(1) {
3138 switch(tok) {
3139 case TOK_EXTENSION:
3140 /* currently, we really ignore extension */
3141 next();
3142 continue;
3144 /* basic types */
3145 case TOK_CHAR:
3146 u = VT_BYTE;
3147 basic_type:
3148 next();
3149 basic_type1:
3150 if (complete)
3151 tcc_error("too many basic types");
3152 t |= u;
3153 bt_size = is_btype_size (u & VT_BTYPE);
3154 if (u == VT_INT || (!bt_size && !(t & VT_TYPEDEF)))
3155 complete = 1;
3156 typespec_found = 1;
3157 break;
3158 case TOK_VOID:
3159 u = VT_VOID;
3160 goto basic_type;
3161 case TOK_SHORT:
3162 u = VT_SHORT;
3163 goto basic_type;
3164 case TOK_INT:
3165 u = VT_INT;
3166 goto basic_type;
3167 case TOK_LONG:
3168 next();
3169 if ((t & VT_BTYPE) == VT_DOUBLE) {
3170 #ifndef TCC_TARGET_PE
3171 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3172 #endif
3173 } else if ((t & VT_BTYPE) == VT_LONG) {
3174 t = (t & ~VT_BTYPE) | VT_LLONG;
3175 } else {
3176 u = VT_LONG;
3177 goto basic_type1;
3179 break;
3180 case TOK_BOOL:
3181 u = VT_BOOL;
3182 goto basic_type;
3183 case TOK_FLOAT:
3184 u = VT_FLOAT;
3185 goto basic_type;
3186 case TOK_DOUBLE:
3187 next();
3188 if ((t & VT_BTYPE) == VT_LONG) {
3189 #ifdef TCC_TARGET_PE
3190 t = (t & ~VT_BTYPE) | VT_DOUBLE;
3191 #else
3192 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3193 #endif
3194 } else {
3195 u = VT_DOUBLE;
3196 goto basic_type1;
3198 break;
3199 case TOK_ENUM:
3200 struct_decl(&type1, VT_ENUM, t & VT_TYPEDEF);
3201 basic_type2:
3202 u = type1.t;
3203 type->ref = type1.ref;
3204 goto basic_type1;
3205 case TOK_STRUCT:
3206 case TOK_UNION:
3207 struct_decl(&type1, VT_STRUCT, t & VT_TYPEDEF);
3208 goto basic_type2;
3210 /* type modifiers */
3211 case TOK_CONST1:
3212 case TOK_CONST2:
3213 case TOK_CONST3:
3214 t |= VT_CONSTANT;
3215 next();
3216 break;
3217 case TOK_VOLATILE1:
3218 case TOK_VOLATILE2:
3219 case TOK_VOLATILE3:
3220 t |= VT_VOLATILE;
3221 next();
3222 break;
3223 case TOK_SIGNED1:
3224 case TOK_SIGNED2:
3225 case TOK_SIGNED3:
3226 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == (VT_DEFSIGN|VT_UNSIGNED))
3227 tcc_error("signed and unsigned modifier");
3228 typespec_found = 1;
3229 t |= VT_DEFSIGN;
3230 next();
3231 break;
3232 case TOK_REGISTER:
3233 case TOK_AUTO:
3234 case TOK_RESTRICT1:
3235 case TOK_RESTRICT2:
3236 case TOK_RESTRICT3:
3237 next();
3238 break;
3239 case TOK_UNSIGNED:
3240 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == VT_DEFSIGN)
3241 tcc_error("signed and unsigned modifier");
3242 t |= VT_DEFSIGN | VT_UNSIGNED;
3243 next();
3244 typespec_found = 1;
3245 break;
3247 /* storage */
3248 case TOK_EXTERN:
3249 t |= VT_EXTERN;
3250 next();
3251 break;
3252 case TOK_STATIC:
3253 t |= VT_STATIC;
3254 next();
3255 break;
3256 case TOK_TYPEDEF:
3257 t |= VT_TYPEDEF;
3258 next();
3259 break;
3260 case TOK_INLINE1:
3261 case TOK_INLINE2:
3262 case TOK_INLINE3:
3263 t |= VT_INLINE;
3264 next();
3265 break;
3267 /* GNUC attribute */
3268 case TOK_ATTRIBUTE1:
3269 case TOK_ATTRIBUTE2:
3270 parse_attribute(ad);
3271 if (ad->a.mode) {
3272 u = ad->a.mode -1;
3273 t = (t & ~VT_BTYPE) | u;
3275 break;
3276 /* GNUC typeof */
3277 case TOK_TYPEOF1:
3278 case TOK_TYPEOF2:
3279 case TOK_TYPEOF3:
3280 next();
3281 parse_expr_type(&type1);
3282 /* remove all storage modifiers except typedef */
3283 type1.t &= ~(VT_STORAGE&~VT_TYPEDEF);
3284 goto basic_type2;
3285 default:
3286 if (typespec_found)
3287 goto the_end;
3288 s = sym_find(tok);
3289 if (!s || !(s->type.t & VT_TYPEDEF))
3290 goto the_end;
3291 t |= (s->type.t & ~VT_TYPEDEF);
3292 type->ref = s->type.ref;
3293 if (s->r) {
3294 /* get attributes from typedef */
3295 if (0 == ad->a.aligned)
3296 ad->a.aligned = s->a.aligned;
3297 if (0 == ad->a.func_call)
3298 ad->a.func_call = s->a.func_call;
3299 ad->a.packed |= s->a.packed;
3301 next();
3302 typespec_found = 1;
3303 break;
3305 type_found = 1;
3307 the_end:
3308 if (tcc_state->char_is_unsigned) {
3309 if ((t & (VT_DEFSIGN|VT_BTYPE)) == VT_BYTE)
3310 t |= VT_UNSIGNED;
3313 /* long is never used as type */
3314 if ((t & VT_BTYPE) == VT_LONG)
3315 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
3316 t = (t & ~VT_BTYPE) | VT_INT;
3317 #else
3318 t = (t & ~VT_BTYPE) | VT_LLONG;
3319 #endif
3320 type->t = t;
3321 return type_found;
3324 /* convert a function parameter type (array to pointer and function to
3325 function pointer) */
3326 static inline void convert_parameter_type(CType *pt)
3328 /* remove const and volatile qualifiers (XXX: const could be used
3329 to indicate a const function parameter */
3330 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
3331 /* array must be transformed to pointer according to ANSI C */
3332 pt->t &= ~VT_ARRAY;
3333 if ((pt->t & VT_BTYPE) == VT_FUNC) {
3334 mk_pointer(pt);
3338 ST_FUNC void parse_asm_str(CString *astr)
3340 skip('(');
3341 /* read the string */
3342 if (tok != TOK_STR)
3343 expect("string constant");
3344 cstr_new(astr);
3345 while (tok == TOK_STR) {
3346 /* XXX: add \0 handling too ? */
3347 cstr_cat(astr, tokc.cstr->data);
3348 next();
3350 cstr_ccat(astr, '\0');
3353 /* Parse an asm label and return the label
3354 * Don't forget to free the CString in the caller! */
3355 static void asm_label_instr(CString *astr)
3357 next();
3358 parse_asm_str(astr);
3359 skip(')');
3360 #ifdef ASM_DEBUG
3361 printf("asm_alias: \"%s\"\n", (char *)astr->data);
3362 #endif
3365 static void post_type(CType *type, AttributeDef *ad)
3367 int n, l, t1, arg_size, size, align;
3368 Sym **plast, *s, *first;
3369 AttributeDef ad1;
3370 CType pt;
3372 if (tok == '(') {
3373 /* function declaration */
3374 next();
3375 l = 0;
3376 first = NULL;
3377 plast = &first;
3378 arg_size = 0;
3379 if (tok != ')') {
3380 for(;;) {
3381 /* read param name and compute offset */
3382 if (l != FUNC_OLD) {
3383 if (!parse_btype(&pt, &ad1)) {
3384 if (l) {
3385 tcc_error("invalid type");
3386 } else {
3387 l = FUNC_OLD;
3388 goto old_proto;
3391 l = FUNC_NEW;
3392 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
3393 break;
3394 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
3395 if ((pt.t & VT_BTYPE) == VT_VOID)
3396 tcc_error("parameter declared as void");
3397 arg_size += (type_size(&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
3398 } else {
3399 old_proto:
3400 n = tok;
3401 if (n < TOK_UIDENT)
3402 expect("identifier");
3403 pt.t = VT_INT;
3404 next();
3406 convert_parameter_type(&pt);
3407 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
3408 *plast = s;
3409 plast = &s->next;
3410 if (tok == ')')
3411 break;
3412 skip(',');
3413 if (l == FUNC_NEW && tok == TOK_DOTS) {
3414 l = FUNC_ELLIPSIS;
3415 next();
3416 break;
3420 /* if no parameters, then old type prototype */
3421 if (l == 0)
3422 l = FUNC_OLD;
3423 skip(')');
3424 /* NOTE: const is ignored in returned type as it has a special
3425 meaning in gcc / C++ */
3426 type->t &= ~VT_CONSTANT;
3427 /* some ancient pre-K&R C allows a function to return an array
3428 and the array brackets to be put after the arguments, such
3429 that "int c()[]" means something like "int[] c()" */
3430 if (tok == '[') {
3431 next();
3432 skip(']'); /* only handle simple "[]" */
3433 type->t |= VT_PTR;
3435 /* we push a anonymous symbol which will contain the function prototype */
3436 ad->a.func_args = arg_size;
3437 s = sym_push(SYM_FIELD, type, 0, l);
3438 s->a = ad->a;
3439 s->next = first;
3440 type->t = VT_FUNC;
3441 type->ref = s;
3442 } else if (tok == '[') {
3443 /* array definition */
3444 next();
3445 if (tok == TOK_RESTRICT1)
3446 next();
3447 n = -1;
3448 t1 = 0;
3449 if (tok != ']') {
3450 if (!local_stack || nocode_wanted)
3451 vpushi(expr_const());
3452 else gexpr();
3453 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3454 n = vtop->c.i;
3455 if (n < 0)
3456 tcc_error("invalid array size");
3457 } else {
3458 if (!is_integer_btype(vtop->type.t & VT_BTYPE))
3459 tcc_error("size of variable length array should be an integer");
3460 t1 = VT_VLA;
3463 skip(']');
3464 /* parse next post type */
3465 post_type(type, ad);
3466 if (type->t == VT_FUNC)
3467 tcc_error("declaration of an array of functions");
3468 t1 |= type->t & VT_VLA;
3470 if (t1 & VT_VLA) {
3471 size = type_size(&int_type, &align);
3472 n = loc_stack(size, 1);
3474 vla_runtime_type_size(type, &align);
3475 gen_op('*');
3476 vset(&int_type, VT_LOCAL|VT_LVAL, n);
3477 vswap();
3478 vstore();
3480 if (n != -1)
3481 vpop();
3483 /* we push an anonymous symbol which will contain the array
3484 element type */
3485 s = sym_push(SYM_FIELD, type, 0, n);
3486 type->t = (t1 ? VT_VLA : VT_ARRAY) | VT_PTR;
3487 type->ref = s;
3491 /* Parse a type declaration (except basic type), and return the type
3492 in 'type'. 'td' is a bitmask indicating which kind of type decl is
3493 expected. 'type' should contain the basic type. 'ad' is the
3494 attribute definition of the basic type. It can be modified by
3495 type_decl().
3497 static void type_decl(CType *type, AttributeDef *ad, int *v, int td)
3499 Sym *s;
3500 CType type1, *type2;
3501 int qualifiers, storage;
3503 while (tok == '*') {
3504 qualifiers = 0;
3505 redo:
3506 next();
3507 switch(tok) {
3508 case TOK_CONST1:
3509 case TOK_CONST2:
3510 case TOK_CONST3:
3511 qualifiers |= VT_CONSTANT;
3512 goto redo;
3513 case TOK_VOLATILE1:
3514 case TOK_VOLATILE2:
3515 case TOK_VOLATILE3:
3516 qualifiers |= VT_VOLATILE;
3517 goto redo;
3518 case TOK_RESTRICT1:
3519 case TOK_RESTRICT2:
3520 case TOK_RESTRICT3:
3521 goto redo;
3523 mk_pointer(type);
3524 type->t |= qualifiers;
3527 /* XXX: clarify attribute handling */
3528 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3529 parse_attribute(ad);
3531 /* recursive type */
3532 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
3533 type1.t = 0; /* XXX: same as int */
3534 if (tok == '(') {
3535 next();
3536 /* XXX: this is not correct to modify 'ad' at this point, but
3537 the syntax is not clear */
3538 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3539 parse_attribute(ad);
3540 type_decl(&type1, ad, v, td);
3541 skip(')');
3542 } else {
3543 /* type identifier */
3544 if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
3545 *v = tok;
3546 next();
3547 } else {
3548 if (!(td & TYPE_ABSTRACT))
3549 expect("identifier");
3550 *v = 0;
3553 storage = type->t & VT_STORAGE;
3554 type->t &= ~VT_STORAGE;
3555 if (storage & VT_STATIC) {
3556 int saved_nocode_wanted = nocode_wanted;
3557 nocode_wanted = 1;
3558 post_type(type, ad);
3559 nocode_wanted = saved_nocode_wanted;
3560 } else
3561 post_type(type, ad);
3562 type->t |= storage;
3563 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3564 parse_attribute(ad);
3566 if (!type1.t)
3567 return;
3568 /* append type at the end of type1 */
3569 type2 = &type1;
3570 for(;;) {
3571 s = type2->ref;
3572 type2 = &s->type;
3573 if (!type2->t) {
3574 *type2 = *type;
3575 break;
3578 *type = type1;
3581 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
3582 ST_FUNC int lvalue_type(int t)
3584 int bt, r;
3585 r = VT_LVAL;
3586 bt = t & VT_BTYPE;
3587 if (bt == VT_BYTE || bt == VT_BOOL)
3588 r |= VT_LVAL_BYTE;
3589 else if (bt == VT_SHORT)
3590 r |= VT_LVAL_SHORT;
3591 else
3592 return r;
3593 if (t & VT_UNSIGNED)
3594 r |= VT_LVAL_UNSIGNED;
3595 return r;
3598 /* indirection with full error checking and bound check */
3599 ST_FUNC void indir(void)
3601 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
3602 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
3603 return;
3604 expect("pointer");
3606 if ((vtop->r & VT_LVAL) && !nocode_wanted)
3607 gv(RC_INT);
3608 vtop->type = *pointed_type(&vtop->type);
3609 /* Arrays and functions are never lvalues */
3610 if (!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_VLA)
3611 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
3612 vtop->r |= lvalue_type(vtop->type.t);
3613 /* if bound checking, the referenced pointer must be checked */
3614 #ifdef CONFIG_TCC_BCHECK
3615 if (tcc_state->do_bounds_check)
3616 vtop->r |= VT_MUSTBOUND;
3617 #endif
3621 /* pass a parameter to a function and do type checking and casting */
3622 static void gfunc_param_typed(Sym *func, Sym *arg)
3624 int func_type;
3625 CType type;
3627 func_type = func->c;
3628 if (func_type == FUNC_OLD ||
3629 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
3630 /* default casting : only need to convert float to double */
3631 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
3632 type.t = VT_DOUBLE;
3633 gen_cast(&type);
3634 } else if (vtop->type.t & VT_BITFIELD) {
3635 type.t = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
3636 gen_cast(&type);
3638 } else if (arg == NULL) {
3639 tcc_error("too many arguments to function");
3640 } else {
3641 type = arg->type;
3642 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
3643 gen_assign_cast(&type);
3647 /* parse an expression of the form '(type)' or '(expr)' and return its
3648 type */
3649 static void parse_expr_type(CType *type)
3651 int n;
3652 AttributeDef ad;
3654 skip('(');
3655 if (parse_btype(type, &ad)) {
3656 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3657 } else {
3658 expr_type(type);
3660 skip(')');
3663 static void parse_type(CType *type)
3665 AttributeDef ad;
3666 int n;
3668 if (!parse_btype(type, &ad)) {
3669 expect("type");
3671 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3674 static void vpush_tokc(int t)
3676 CType type;
3677 type.t = t;
3678 type.ref = 0;
3679 vsetc(&type, VT_CONST, &tokc);
3682 ST_FUNC void unary(void)
3684 int n, t, align, size, r, sizeof_caller;
3685 CType type;
3686 Sym *s;
3687 AttributeDef ad;
3688 static int in_sizeof = 0;
3690 sizeof_caller = in_sizeof;
3691 in_sizeof = 0;
3692 /* XXX: GCC 2.95.3 does not generate a table although it should be
3693 better here */
3694 tok_next:
3695 switch(tok) {
3696 case TOK_EXTENSION:
3697 next();
3698 goto tok_next;
3699 case TOK_CINT:
3700 case TOK_CCHAR:
3701 case TOK_LCHAR:
3702 vpushi(tokc.i);
3703 next();
3704 break;
3705 case TOK_CUINT:
3706 vpush_tokc(VT_INT | VT_UNSIGNED);
3707 next();
3708 break;
3709 case TOK_CLLONG:
3710 vpush_tokc(VT_LLONG);
3711 next();
3712 break;
3713 case TOK_CULLONG:
3714 vpush_tokc(VT_LLONG | VT_UNSIGNED);
3715 next();
3716 break;
3717 case TOK_CFLOAT:
3718 vpush_tokc(VT_FLOAT);
3719 next();
3720 break;
3721 case TOK_CDOUBLE:
3722 vpush_tokc(VT_DOUBLE);
3723 next();
3724 break;
3725 case TOK_CLDOUBLE:
3726 vpush_tokc(VT_LDOUBLE);
3727 next();
3728 break;
3729 case TOK___FUNCTION__:
3730 if (!gnu_ext)
3731 goto tok_identifier;
3732 /* fall thru */
3733 case TOK___FUNC__:
3735 void *ptr;
3736 int len;
3737 /* special function name identifier */
3738 len = strlen(funcname) + 1;
3739 /* generate char[len] type */
3740 type.t = VT_BYTE;
3741 mk_pointer(&type);
3742 type.t |= VT_ARRAY;
3743 type.ref->c = len;
3744 vpush_ref(&type, data_section, data_section->data_offset, len);
3745 ptr = section_ptr_add(data_section, len);
3746 memcpy(ptr, funcname, len);
3747 next();
3749 break;
3750 case TOK_LSTR:
3751 #ifdef TCC_TARGET_PE
3752 t = VT_SHORT | VT_UNSIGNED;
3753 #else
3754 t = VT_INT;
3755 #endif
3756 goto str_init;
3757 case TOK_STR:
3758 /* string parsing */
3759 t = VT_BYTE;
3760 str_init:
3761 if (tcc_state->warn_write_strings)
3762 t |= VT_CONSTANT;
3763 type.t = t;
3764 mk_pointer(&type);
3765 type.t |= VT_ARRAY;
3766 memset(&ad, 0, sizeof(AttributeDef));
3767 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, NULL, 0);
3768 break;
3769 case '(':
3770 next();
3771 /* cast ? */
3772 if (parse_btype(&type, &ad)) {
3773 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
3774 skip(')');
3775 /* check ISOC99 compound literal */
3776 if (tok == '{') {
3777 /* data is allocated locally by default */
3778 if (global_expr)
3779 r = VT_CONST;
3780 else
3781 r = VT_LOCAL;
3782 /* all except arrays are lvalues */
3783 if (!(type.t & VT_ARRAY))
3784 r |= lvalue_type(type.t);
3785 memset(&ad, 0, sizeof(AttributeDef));
3786 decl_initializer_alloc(&type, &ad, r, 1, 0, NULL, 0);
3787 } else {
3788 if (sizeof_caller) {
3789 vpush(&type);
3790 return;
3792 unary();
3793 gen_cast(&type);
3795 } else if (tok == '{') {
3796 /* save all registers */
3797 save_regs(0);
3798 /* statement expression : we do not accept break/continue
3799 inside as GCC does */
3800 block(NULL, NULL, NULL, NULL, 0, 1);
3801 skip(')');
3802 } else {
3803 gexpr();
3804 skip(')');
3806 break;
3807 case '*':
3808 next();
3809 unary();
3810 indir();
3811 break;
3812 case '&':
3813 next();
3814 unary();
3815 /* functions names must be treated as function pointers,
3816 except for unary '&' and sizeof. Since we consider that
3817 functions are not lvalues, we only have to handle it
3818 there and in function calls. */
3819 /* arrays can also be used although they are not lvalues */
3820 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
3821 !(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
3822 test_lvalue();
3823 mk_pointer(&vtop->type);
3824 gaddrof();
3825 break;
3826 case '!':
3827 next();
3828 unary();
3829 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3830 CType boolean;
3831 boolean.t = VT_BOOL;
3832 gen_cast(&boolean);
3833 vtop->c.i = !vtop->c.i;
3834 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
3835 vtop->c.i = vtop->c.i ^ 1;
3836 else {
3837 save_regs(1);
3838 vseti(VT_JMP, gtst(1, 0));
3840 break;
3841 case '~':
3842 next();
3843 unary();
3844 vpushi(-1);
3845 gen_op('^');
3846 break;
3847 case '+':
3848 next();
3849 unary();
3850 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
3851 tcc_error("pointer not accepted for unary plus");
3852 /* In order to force cast, we add zero, except for floating point
3853 where we really need an noop (otherwise -0.0 will be transformed
3854 into +0.0). */
3855 if (!is_float(vtop->type.t)) {
3856 vpushi(0);
3857 gen_op('+');
3859 break;
3860 case TOK_SIZEOF:
3861 case TOK_ALIGNOF1:
3862 case TOK_ALIGNOF2:
3863 t = tok;
3864 next();
3865 in_sizeof++;
3866 unary_type(&type); // Perform a in_sizeof = 0;
3867 size = type_size(&type, &align);
3868 if (t == TOK_SIZEOF) {
3869 if (!(type.t & VT_VLA)) {
3870 if (size < 0)
3871 tcc_error("sizeof applied to an incomplete type");
3872 vpushs(size);
3873 } else {
3874 vla_runtime_type_size(&type, &align);
3876 } else {
3877 vpushs(align);
3879 vtop->type.t |= VT_UNSIGNED;
3880 break;
3882 case TOK_builtin_types_compatible_p:
3884 CType type1, type2;
3885 next();
3886 skip('(');
3887 parse_type(&type1);
3888 skip(',');
3889 parse_type(&type2);
3890 skip(')');
3891 type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
3892 type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
3893 vpushi(is_compatible_types(&type1, &type2));
3895 break;
3896 case TOK_builtin_constant_p:
3898 int saved_nocode_wanted, res;
3899 next();
3900 skip('(');
3901 saved_nocode_wanted = nocode_wanted;
3902 nocode_wanted = 1;
3903 gexpr();
3904 res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
3905 vpop();
3906 nocode_wanted = saved_nocode_wanted;
3907 skip(')');
3908 vpushi(res);
3910 break;
3911 case TOK_builtin_frame_address:
3913 int level;
3914 CType type;
3915 next();
3916 skip('(');
3917 if (tok != TOK_CINT || tokc.i < 0) {
3918 tcc_error("__builtin_frame_address only takes positive integers");
3920 level = tokc.i;
3921 next();
3922 skip(')');
3923 type.t = VT_VOID;
3924 mk_pointer(&type);
3925 vset(&type, VT_LOCAL, 0); /* local frame */
3926 while (level--) {
3927 mk_pointer(&vtop->type);
3928 indir(); /* -> parent frame */
3931 break;
3932 #ifdef TCC_TARGET_X86_64
3933 #ifdef TCC_TARGET_PE
3934 case TOK_builtin_va_start:
3936 next();
3937 skip('(');
3938 expr_eq();
3939 skip(',');
3940 expr_eq();
3941 skip(')');
3942 if ((vtop->r & VT_VALMASK) != VT_LOCAL)
3943 tcc_error("__builtin_va_start expects a local variable");
3944 vtop->r &= ~(VT_LVAL | VT_REF);
3945 vtop->type = char_pointer_type;
3946 vstore();
3948 break;
3949 #else
3950 case TOK_builtin_va_arg_types:
3952 CType type;
3953 next();
3954 skip('(');
3955 parse_type(&type);
3956 skip(')');
3957 vpushi(classify_x86_64_va_arg(&type));
3959 break;
3960 #endif
3961 #endif
3962 case TOK_INC:
3963 case TOK_DEC:
3964 t = tok;
3965 next();
3966 unary();
3967 inc(0, t);
3968 break;
3969 case '-':
3970 next();
3971 unary();
3972 t = vtop->type.t & VT_BTYPE;
3973 if (is_float(t)) {
3974 /* In IEEE negate(x) isn't subtract(0,x), but rather
3975 subtract(-0, x). */
3976 vpush(&vtop->type);
3977 if (t == VT_FLOAT)
3978 vtop->c.f = -0.0f;
3979 else if (t == VT_DOUBLE)
3980 vtop->c.d = -0.0;
3981 else
3982 vtop->c.ld = -0.0;
3983 } else
3984 vpushi(0);
3985 vswap();
3986 gen_op('-');
3987 break;
3988 case TOK_LAND:
3989 if (!gnu_ext)
3990 goto tok_identifier;
3991 next();
3992 /* allow to take the address of a label */
3993 if (tok < TOK_UIDENT)
3994 expect("label identifier");
3995 s = label_find(tok);
3996 if (!s) {
3997 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
3998 } else {
3999 if (s->r == LABEL_DECLARED)
4000 s->r = LABEL_FORWARD;
4002 if (!s->type.t) {
4003 s->type.t = VT_VOID;
4004 mk_pointer(&s->type);
4005 s->type.t |= VT_STATIC;
4007 vpushsym(&s->type, s);
4008 next();
4009 break;
4011 // special qnan , snan and infinity values
4012 case TOK___NAN__:
4013 vpush64(VT_DOUBLE, 0x7ff8000000000000ULL);
4014 next();
4015 break;
4016 case TOK___SNAN__:
4017 vpush64(VT_DOUBLE, 0x7ff0000000000001ULL);
4018 next();
4019 break;
4020 case TOK___INF__:
4021 vpush64(VT_DOUBLE, 0x7ff0000000000000ULL);
4022 next();
4023 break;
4025 default:
4026 tok_identifier:
4027 t = tok;
4028 next();
4029 if (t < TOK_UIDENT)
4030 expect("identifier");
4031 s = sym_find(t);
4032 if (!s) {
4033 const char *name = get_tok_str(t, NULL);
4034 if (tok != '(')
4035 tcc_error("'%s' undeclared", name);
4036 /* for simple function calls, we tolerate undeclared
4037 external reference to int() function */
4038 if (tcc_state->warn_implicit_function_declaration
4039 #ifdef TCC_TARGET_PE
4040 /* people must be warned about using undeclared WINAPI functions
4041 (which usually start with uppercase letter) */
4042 || (name[0] >= 'A' && name[0] <= 'Z')
4043 #endif
4045 tcc_warning("implicit declaration of function '%s'", name);
4046 s = external_global_sym(t, &func_old_type, 0);
4048 if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
4049 (VT_STATIC | VT_INLINE | VT_FUNC)) {
4050 /* if referencing an inline function, then we generate a
4051 symbol to it if not already done. It will have the
4052 effect to generate code for it at the end of the
4053 compilation unit. Inline function as always
4054 generated in the text section. */
4055 if (!s->c)
4056 put_extern_sym(s, text_section, 0, 0);
4057 r = VT_SYM | VT_CONST;
4058 } else {
4059 r = s->r;
4061 vset(&s->type, r, s->c);
4062 /* if forward reference, we must point to s */
4063 if (vtop->r & VT_SYM) {
4064 vtop->sym = s;
4065 vtop->c.ptr_offset = 0;
4067 break;
4070 /* post operations */
4071 while (1) {
4072 SValue ret;
4073 int ret_nregs, ret_align;
4074 if (tok == TOK_INC || tok == TOK_DEC) {
4075 inc(1, tok);
4076 next();
4077 } else if (tok == '.' || tok == TOK_ARROW) {
4078 int qualifiers, add, is_lval;
4079 /* field */
4080 qualifiers = vtop->type.t & (VT_CONSTANT | VT_VOLATILE);
4081 add = 0;
4082 if (tok == TOK_ARROW)
4083 indir();
4085 type = vtop->type;
4086 is_lval = (vtop->r & (VT_VALMASK | VT_LVAL)) >= VT_CONST;
4087 if(is_lval){
4088 test_lvalue();
4089 gaddrof();
4090 vtop->type = char_pointer_type; /* change type to 'char *' */
4091 }else
4092 gfunc_sret(&vtop->type, func_var, &ret.type, &ret_align);
4094 next();
4095 /* expect pointer on structure */
4096 if ((type.t & VT_BTYPE) != VT_STRUCT)
4097 expect("struct or union");
4098 s = type.ref;
4099 /* find field */
4100 tok |= SYM_FIELD;
4101 while ((s = s->next) != NULL) {
4102 if (s->v == tok)
4103 break;
4105 if (!s)
4106 tcc_error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, NULL));
4107 /* add bit */
4108 add += s->c;
4109 /* change type to field type, and set to lvalue */
4110 type = s->type;
4111 next();
4112 }while(tok == '.');
4114 type.t |= qualifiers;
4115 if (is_lval){
4116 p_lval:
4117 vpushi(add);
4118 gen_op('+');
4119 /* an array is never an lvalue */
4120 if (!(type.t & VT_ARRAY)) {
4121 vtop->r |= lvalue_type(type.t);
4122 #ifdef CONFIG_TCC_BCHECK
4123 /* if bound checking, the referenced pointer must be checked */
4124 if (tcc_state->do_bounds_check)
4125 vtop->r |= VT_MUSTBOUND;
4126 #endif
4128 }else{
4129 gfunc_sret(&vtop->type, func_var, &ret.type, &ret_align);
4130 if(is_float(ret.type.t) || (type.t & VT_ARRAY)){
4131 #ifdef TCC_TARGET_X86_64
4132 if((ret.type.t & VT_BTYPE) != VT_LDOUBLE)
4133 #endif
4135 save_reg(vtop->r);
4136 vtop->r &= ~VT_TMP;
4137 gaddrof();
4138 vtop->type = char_pointer_type; /* change type to 'char *' */
4139 goto p_lval;
4141 }else{
4142 #ifdef TCC_TARGET_X86_64
4143 int load_size = 8;
4144 #else
4145 int load_size = 4;
4146 #endif
4147 if(add & load_size){
4148 add -= load_size;
4149 vtop->r = vtop->r2;
4150 vtop->r2 = VT_CONST;
4152 if(add){
4153 vtop->type.t = VT_LLONG;
4154 vpushi(add*8);
4155 gen_op(TOK_SAR);
4159 vtop->type = type;
4160 } else if (tok == '[') {
4161 next();
4162 gexpr();
4163 gen_op('+');
4164 indir();
4165 skip(']');
4166 } else if (tok == '(') {
4167 Sym *sa;
4168 int nb_args, variadic, addr;
4170 /* function call */
4171 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
4172 /* pointer test (no array accepted) */
4173 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
4174 vtop->type = *pointed_type(&vtop->type);
4175 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
4176 goto error_func;
4177 } else {
4178 error_func:
4179 expect("function pointer");
4181 } else {
4182 vtop->r &= ~VT_LVAL; /* no lvalue */
4184 /* get return type */
4185 s = vtop->type.ref;
4186 sa = s->next; /* first parameter */
4187 nb_args = 0;
4188 ret.r2 = VT_CONST;
4189 /* compute first implicit argument if a structure is returned */
4190 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
4191 variadic = (s->c == FUNC_ELLIPSIS);
4192 ret_nregs = gfunc_sret(&s->type, variadic, &ret.type,
4193 &ret_align);
4194 if (!ret_nregs) {
4195 /* get some space for the returned structure */
4196 size = type_size(&s->type, &align);
4197 addr = loc_stack(size, 1);
4198 ret.type = s->type;
4199 ret.r = VT_LOCAL | VT_LVAL;
4200 /* pass it as 'int' to avoid structure arg passing
4201 problems */
4202 vseti(VT_LOCAL, addr);
4203 ret.c = vtop->c;
4204 nb_args++;
4206 } else {
4207 ret_nregs = 1;
4208 ret.type = s->type;
4211 if (ret_nregs) {
4212 /* return in register */
4213 if (is_float(ret.type.t)) {
4214 ret.r = reg_fret(ret.type.t);
4215 #ifdef TCC_TARGET_X86_64
4216 if ((ret.type.t & VT_BTYPE) == VT_QFLOAT)
4217 ret.r2 = REG_QRET;
4218 #endif
4219 } else {
4220 #ifdef TCC_TARGET_X86_64
4221 if ((ret.type.t & VT_BTYPE) == VT_QLONG)
4222 #else
4223 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
4224 #endif
4225 ret.r2 = REG_LRET;
4226 ret.r = REG_IRET;
4228 ret.c.i = 0;
4230 next();
4231 if (tok != ')') {
4232 for(;;) {
4233 expr_eq();
4234 gfunc_param_typed(s, sa);
4235 nb_args++;
4236 if (sa)
4237 sa = sa->next;
4238 if (tok == ')')
4239 break;
4240 skip(',');
4243 if (sa)
4244 tcc_error("too few arguments to function");
4245 skip(')');
4246 if (!nocode_wanted) {
4247 gfunc_call(nb_args);
4248 } else {
4249 vtop -= (nb_args + 1);
4252 /* return value */
4253 for (r = ret.r + ret_nregs + !ret_nregs; r-- > ret.r;) {
4254 vsetc(&ret.type, r, &ret.c);
4255 vtop->r2 = ret.r2; /* Loop only happens when r2 is VT_CONST */
4258 /* handle packed struct return */
4259 if (((s->type.t & VT_BTYPE) == VT_STRUCT) && ret_nregs)
4260 vtop->type = s->type;
4261 } else {
4262 break;
4267 ST_FUNC void expr_prod(void)
4269 int t;
4271 unary();
4272 while (tok == '*' || tok == '/' || tok == '%') {
4273 t = tok;
4274 next();
4275 unary();
4276 gen_op(t);
4280 ST_FUNC void expr_sum(void)
4282 int t;
4284 expr_prod();
4285 while (tok == '+' || tok == '-') {
4286 t = tok;
4287 next();
4288 expr_prod();
4289 gen_op(t);
4293 static void expr_shift(void)
4295 int t;
4297 expr_sum();
4298 while (tok == TOK_SHL || tok == TOK_SAR) {
4299 t = tok;
4300 next();
4301 expr_sum();
4302 gen_op(t);
4306 static void expr_cmp(void)
4308 int t;
4310 expr_shift();
4311 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
4312 tok == TOK_ULT || tok == TOK_UGE) {
4313 t = tok;
4314 next();
4315 expr_shift();
4316 gen_op(t);
4320 static void expr_cmpeq(void)
4322 int t;
4324 expr_cmp();
4325 while (tok == TOK_EQ || tok == TOK_NE) {
4326 t = tok;
4327 next();
4328 expr_cmp();
4329 gen_op(t);
4333 static void expr_and(void)
4335 expr_cmpeq();
4336 while (tok == '&') {
4337 next();
4338 expr_cmpeq();
4339 gen_op('&');
4343 static void expr_xor(void)
4345 expr_and();
4346 while (tok == '^') {
4347 next();
4348 expr_and();
4349 gen_op('^');
4353 static void expr_or(void)
4355 expr_xor();
4356 while (tok == '|') {
4357 next();
4358 expr_xor();
4359 gen_op('|');
4363 /* XXX: fix this mess */
4364 static void expr_land_const(void)
4366 expr_or();
4367 while (tok == TOK_LAND) {
4368 next();
4369 expr_or();
4370 gen_op(TOK_LAND);
4374 /* XXX: fix this mess */
4375 static void expr_lor_const(void)
4377 expr_land_const();
4378 while (tok == TOK_LOR) {
4379 next();
4380 expr_land_const();
4381 gen_op(TOK_LOR);
4385 /* only used if non constant */
4386 static void expr_land(void)
4388 int t;
4390 expr_or();
4391 if (tok == TOK_LAND) {
4392 t = 0;
4393 save_regs(1);
4394 for(;;) {
4395 t = gtst(1, t);
4396 if (tok != TOK_LAND) {
4397 vseti(VT_JMPI, t);
4398 break;
4400 next();
4401 expr_or();
4406 static void expr_lor(void)
4408 int t;
4410 expr_land();
4411 if (tok == TOK_LOR) {
4412 t = 0;
4413 save_regs(1);
4414 for(;;) {
4415 t = gtst(0, t);
4416 if (tok != TOK_LOR) {
4417 vseti(VT_JMP, t);
4418 break;
4420 next();
4421 expr_land();
4426 /* XXX: better constant handling */
4427 static void expr_cond(void)
4429 int tt, u, r, rc, t1, t2, bt1, bt2, ret_nregs, ret_align;
4430 SValue sv, ret;
4431 CType type, type1, type2;
4433 if (const_wanted) {
4434 expr_lor_const();
4435 if (tok == '?') {
4436 CType boolean;
4437 int c;
4438 boolean.t = VT_BOOL;
4439 vdup();
4440 gen_cast(&boolean);
4441 c = vtop->c.i;
4442 vpop();
4443 next();
4444 if (tok != ':' || !gnu_ext) {
4445 vpop();
4446 gexpr();
4448 if (!c)
4449 vpop();
4450 skip(':');
4451 expr_cond();
4452 if (c)
4453 vpop();
4455 } else {
4456 expr_lor();
4457 if (tok == '?') {
4458 next();
4459 if (vtop != vstack) {
4460 /* needed to avoid having different registers saved in
4461 each branch */
4462 if (is_float(vtop->type.t)) {
4463 rc = RC_FLOAT;
4464 #ifdef TCC_TARGET_X86_64
4465 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
4466 rc = RC_ST0;
4468 #endif
4470 else
4471 rc = RC_INT;
4472 save_regs(1);
4474 if (tok == ':' && gnu_ext) {
4475 gv_dup();
4476 tt = gtst(1, 0);
4477 } else {
4478 tt = gtst(1, 0);
4479 gexpr();
4481 type1 = vtop->type;
4482 sv = *vtop; /* save value to handle it later */
4483 vtop--; /* no vpop so that FP stack is not flushed */
4484 skip(':');
4485 u = gjmp(0);
4486 gsym(tt);
4487 expr_cond();
4488 type2 = vtop->type;
4490 t1 = type1.t;
4491 bt1 = t1 & VT_BTYPE;
4492 t2 = type2.t;
4493 bt2 = t2 & VT_BTYPE;
4494 /* cast operands to correct type according to ISOC rules */
4495 if (is_float(bt1) || is_float(bt2)) {
4496 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
4497 type.t = VT_LDOUBLE;
4498 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
4499 type.t = VT_DOUBLE;
4500 } else {
4501 type.t = VT_FLOAT;
4503 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
4504 /* cast to biggest op */
4505 type.t = VT_LLONG;
4506 /* convert to unsigned if it does not fit in a long long */
4507 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
4508 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
4509 type.t |= VT_UNSIGNED;
4510 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
4511 /* If one is a null ptr constant the result type is the other. */
4512 if (is_null_pointer (vtop))
4513 type = type1;
4514 else if (is_null_pointer (&sv))
4515 type = type2;
4516 /* XXX: test pointer compatibility, C99 has more elaborate rules here. */
4517 else
4518 type = type1;
4519 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
4520 /* XXX: test function pointer compatibility */
4521 type = bt1 == VT_FUNC ? type1 : type2;
4522 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
4523 /* XXX: test structure compatibility */
4524 type = bt1 == VT_STRUCT ? type1 : type2;
4525 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
4526 /* NOTE: as an extension, we accept void on only one side */
4527 type.t = VT_VOID;
4528 } else {
4529 /* integer operations */
4530 type.t = VT_INT;
4531 /* convert to unsigned if it does not fit in an integer */
4532 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
4533 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
4534 type.t |= VT_UNSIGNED;
4537 /* now we convert second operand */
4538 gen_cast(&type);
4539 ret_nregs = 0;
4540 if (VT_STRUCT == (type.t & VT_BTYPE)){
4541 ret_nregs = gfunc_sret(&type, func_var, &ret.type, &ret_align);
4542 if(ret_nregs)
4543 vtop->type = ret.type;
4544 else
4545 gaddrof();
4548 if (is_float(vtop->type.t)) {
4549 rc = RC_FLOAT;
4550 #ifdef TCC_TARGET_X86_64
4551 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
4552 rc = RC_ST0;
4554 #endif
4555 } else
4556 rc = RC_INT;
4557 r = gv(rc);
4558 rc = reg_classes[r] & ~RC_MASK;
4559 #ifdef TCC_TARGET_X86_64
4560 if (((vtop->type.t & VT_BTYPE) == VT_QLONG) || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT))
4561 #else
4562 if ((vtop->type.t & VT_BTYPE) == VT_LLONG)
4563 #endif
4564 ex_rc = reg_classes[vtop->r2] & ~RC_MASK;
4565 /* this is horrible, but we must also convert first
4566 operand */
4567 tt = gjmp(0);
4568 gsym(u);
4569 /* put again first value and cast it */
4570 *vtop = sv;
4571 gen_cast(&type);
4572 if (VT_STRUCT == (type.t & VT_BTYPE)){
4573 if(ret_nregs)
4574 vtop->type = ret.type;
4575 else
4576 gaddrof();
4578 gv(rc);
4579 gsym(tt);
4581 if (VT_STRUCT == (type.t & VT_BTYPE)){
4582 if(ret_nregs)
4583 vtop->type = type;
4584 else
4585 vtop->r |= VT_LVAL;
4591 static void expr_eq(void)
4593 int t;
4595 expr_cond();
4596 if (tok == '=' ||
4597 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
4598 tok == TOK_A_XOR || tok == TOK_A_OR ||
4599 tok == TOK_A_SHL || tok == TOK_A_SAR) {
4600 test_lvalue();
4601 t = tok;
4602 next();
4603 if (t == '=') {
4604 expr_eq();
4605 } else {
4606 vdup();
4607 expr_eq();
4608 gen_op(t & 0x7f);
4610 vstore();
4614 ST_FUNC void gexpr(void)
4616 while (1) {
4617 expr_eq();
4618 if (tok != ',')
4619 break;
4620 vpop();
4621 next();
4625 /* parse an expression and return its type without any side effect. */
4626 static void expr_type(CType *type)
4628 int saved_nocode_wanted;
4630 saved_nocode_wanted = nocode_wanted;
4631 nocode_wanted = 1;
4632 gexpr();
4633 *type = vtop->type;
4634 vpop();
4635 nocode_wanted = saved_nocode_wanted;
4638 /* parse a unary expression and return its type without any side
4639 effect. */
4640 static void unary_type(CType *type)
4642 int a;
4644 a = nocode_wanted;
4645 nocode_wanted = 1;
4646 unary();
4647 *type = vtop->type;
4648 vpop();
4649 nocode_wanted = a;
4652 /* parse a constant expression and return value in vtop. */
4653 static void expr_const1(void)
4655 int a;
4656 a = const_wanted;
4657 const_wanted = 1;
4658 expr_cond();
4659 const_wanted = a;
4662 /* parse an integer constant and return its value. */
4663 ST_FUNC int expr_const(void)
4665 int c;
4666 expr_const1();
4667 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
4668 expect("constant expression");
4669 c = vtop->c.i;
4670 vpop();
4671 return c;
4674 /* return the label token if current token is a label, otherwise
4675 return zero */
4676 static int is_label(void)
4678 int last_tok;
4680 /* fast test first */
4681 if (tok < TOK_UIDENT)
4682 return 0;
4683 /* no need to save tokc because tok is an identifier */
4684 last_tok = tok;
4685 next();
4686 if (tok == ':') {
4687 next();
4688 return last_tok;
4689 } else {
4690 unget_tok(last_tok);
4691 return 0;
4695 static void label_or_decl(int l)
4697 int last_tok;
4699 /* fast test first */
4700 if (tok >= TOK_UIDENT)
4702 /* no need to save tokc because tok is an identifier */
4703 last_tok = tok;
4704 next();
4705 if (tok == ':') {
4706 unget_tok(last_tok);
4707 return;
4709 unget_tok(last_tok);
4711 decl(l);
4714 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
4715 int case_reg, int is_expr)
4717 int a, b, c, d;
4718 Sym *s, *frame_bottom;
4720 /* generate line number info */
4721 if (tcc_state->do_debug &&
4722 (last_line_num != file->line_num || last_ind != ind)) {
4723 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
4724 last_ind = ind;
4725 last_line_num = file->line_num;
4728 if (is_expr) {
4729 /* default return value is (void) */
4730 vpushi(0);
4731 vtop->type.t = VT_VOID;
4734 if (tok == TOK_IF) {
4735 /* if test */
4736 next();
4737 skip('(');
4738 gexpr();
4739 skip(')');
4740 a = gtst(1, 0);
4741 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4742 c = tok;
4743 if (c == TOK_ELSE) {
4744 next();
4745 d = gjmp(0);
4746 gsym(a);
4747 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4748 gsym(d); /* patch else jmp */
4749 } else
4750 gsym(a);
4751 } else if (tok == TOK_WHILE) {
4752 next();
4753 d = ind;
4754 skip('(');
4755 gexpr();
4756 skip(')');
4757 a = gtst(1, 0);
4758 b = 0;
4759 block(&a, &b, case_sym, def_sym, case_reg, 0);
4760 gjmp_addr(d);
4761 gsym(a);
4762 gsym_addr(b, d);
4763 } else if (tok == '{') {
4764 Sym *llabel;
4765 int block_vla_sp_loc, *saved_vla_sp_loc, saved_vla_flags;
4767 next();
4768 /* record local declaration stack position */
4769 s = local_stack;
4770 frame_bottom = sym_push2(&local_stack, SYM_FIELD, 0, 0);
4771 frame_bottom->next = scope_stack_bottom;
4772 scope_stack_bottom = frame_bottom;
4773 llabel = local_label_stack;
4775 /* save VLA state */
4776 block_vla_sp_loc = *(saved_vla_sp_loc = vla_sp_loc);
4777 if (saved_vla_sp_loc != &vla_sp_root_loc)
4778 vla_sp_loc = &block_vla_sp_loc;
4780 saved_vla_flags = vla_flags;
4781 vla_flags |= VLA_NEED_NEW_FRAME;
4783 /* handle local labels declarations */
4784 if (tok == TOK_LABEL) {
4785 next();
4786 for(;;) {
4787 if (tok < TOK_UIDENT)
4788 expect("label identifier");
4789 label_push(&local_label_stack, tok, LABEL_DECLARED);
4790 next();
4791 if (tok == ',') {
4792 next();
4793 } else {
4794 skip(';');
4795 break;
4799 while (tok != '}') {
4800 label_or_decl(VT_LOCAL);
4801 if (tok != '}') {
4802 if (is_expr)
4803 vpop();
4804 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
4807 /* pop locally defined labels */
4808 label_pop(&local_label_stack, llabel);
4809 if(is_expr) {
4810 /* XXX: this solution makes only valgrind happy...
4811 triggered by gcc.c-torture/execute/20000917-1.c */
4812 Sym *p;
4813 switch(vtop->type.t & VT_BTYPE) {
4814 case VT_PTR:
4815 case VT_STRUCT:
4816 case VT_ENUM:
4817 case VT_FUNC:
4818 for(p=vtop->type.ref;p;p=p->prev)
4819 if(p->prev==s)
4820 tcc_error("unsupported expression type");
4823 /* pop locally defined symbols */
4824 scope_stack_bottom = scope_stack_bottom->next;
4825 sym_pop(&local_stack, s);
4827 /* Pop VLA frames and restore stack pointer if required */
4828 if (saved_vla_sp_loc != &vla_sp_root_loc)
4829 *saved_vla_sp_loc = block_vla_sp_loc;
4830 if (vla_sp_loc != (saved_vla_sp_loc == &vla_sp_root_loc ? &vla_sp_root_loc : &block_vla_sp_loc)) {
4831 vla_sp_loc = saved_vla_sp_loc;
4832 gen_vla_sp_restore(*vla_sp_loc);
4834 vla_flags = (vla_flags & ~VLA_SCOPE_FLAGS) | (saved_vla_flags & VLA_SCOPE_FLAGS);
4836 next();
4837 } else if (tok == TOK_RETURN) {
4838 next();
4839 if (tok != ';') {
4840 gexpr();
4841 gen_assign_cast(&func_vt);
4842 if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
4843 CType type, ret_type;
4844 int ret_align, ret_nregs;
4845 ret_nregs = gfunc_sret(&func_vt, func_var, &ret_type,
4846 &ret_align);
4847 if (0 == ret_nregs) {
4848 /* if returning structure, must copy it to implicit
4849 first pointer arg location */
4850 type = func_vt;
4851 mk_pointer(&type);
4852 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
4853 indir();
4854 vswap();
4855 /* copy structure value to pointer */
4856 vstore();
4857 } else {
4858 /* returning structure packed into registers */
4859 int rc;
4860 vtop->type = ret_type;
4861 if (is_float(ret_type.t))
4862 rc = rc_fret(ret_type.t);
4863 else{
4864 rc = RC_IRET;
4865 ex_rc = RC_LRET;
4868 for (;;) {
4869 gv(rc);
4870 if (--ret_nregs == 0)
4871 break;
4872 /* We assume that when a structure is returned in multiple
4873 registers, their classes are consecutive values of the
4874 suite s(n) = 2^n */
4875 rc <<= 1;
4876 /* XXX: compatible with arm only: ret_align == register_size */
4877 vtop->c.i += ret_align;
4878 vtop->r = VT_LOCAL | VT_LVAL;
4881 } else if (is_float(func_vt.t)) {
4882 gv(rc_fret(func_vt.t));
4883 } else {
4884 gv(RC_IRET);
4886 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
4888 skip(';');
4889 rsym = gjmp(rsym); /* jmp */
4890 } else if (tok == TOK_BREAK) {
4891 /* compute jump */
4892 if (!bsym)
4893 tcc_error("cannot break");
4894 *bsym = gjmp(*bsym);
4895 next();
4896 skip(';');
4897 } else if (tok == TOK_CONTINUE) {
4898 /* compute jump */
4899 if (!csym)
4900 tcc_error("cannot continue");
4901 *csym = gjmp(*csym);
4902 next();
4903 skip(';');
4904 } else if (tok == TOK_FOR) {
4905 int e;
4906 next();
4907 skip('(');
4908 s = local_stack;
4909 frame_bottom = sym_push2(&local_stack, SYM_FIELD, 0, 0);
4910 frame_bottom->next = scope_stack_bottom;
4911 scope_stack_bottom = frame_bottom;
4912 if (tok != ';') {
4913 /* c99 for-loop init decl? */
4914 if (!decl0(VT_LOCAL, 1)) {
4915 /* no, regular for-loop init expr */
4916 gexpr();
4917 vpop();
4920 skip(';');
4921 d = ind;
4922 c = ind;
4923 a = 0;
4924 b = 0;
4925 if (tok != ';') {
4926 gexpr();
4927 a = gtst(1, 0);
4929 skip(';');
4930 if (tok != ')') {
4931 e = gjmp(0);
4932 c = ind;
4933 gexpr();
4934 vpop();
4935 gjmp_addr(d);
4936 gsym(e);
4938 skip(')');
4939 block(&a, &b, case_sym, def_sym, case_reg, 0);
4940 gjmp_addr(c);
4941 gsym(a);
4942 gsym_addr(b, c);
4943 scope_stack_bottom = scope_stack_bottom->next;
4944 sym_pop(&local_stack, s);
4945 } else
4946 if (tok == TOK_DO) {
4947 next();
4948 a = 0;
4949 b = 0;
4950 d = ind;
4951 block(&a, &b, case_sym, def_sym, case_reg, 0);
4952 skip(TOK_WHILE);
4953 skip('(');
4954 gsym(b);
4955 gexpr();
4956 c = gtst(0, 0);
4957 gsym_addr(c, d);
4958 skip(')');
4959 gsym(a);
4960 skip(';');
4961 } else
4962 if (tok == TOK_SWITCH) {
4963 next();
4964 skip('(');
4965 gexpr();
4966 /* XXX: other types than integer */
4967 case_reg = gv(RC_INT);
4968 vpop();
4969 skip(')');
4970 a = 0;
4971 b = gjmp(0); /* jump to first case */
4972 c = 0;
4973 block(&a, csym, &b, &c, case_reg, 0);
4974 /* if no default, jmp after switch */
4975 if (c == 0)
4976 c = ind;
4977 /* default label */
4978 gsym_addr(b, c);
4979 /* break label */
4980 gsym(a);
4981 } else
4982 if (tok == TOK_CASE) {
4983 int v1, v2;
4984 if (!case_sym)
4985 expect("switch");
4986 next();
4987 v1 = expr_const();
4988 v2 = v1;
4989 if (gnu_ext && tok == TOK_DOTS) {
4990 next();
4991 v2 = expr_const();
4992 if (v2 < v1)
4993 tcc_warning("empty case range");
4995 /* since a case is like a label, we must skip it with a jmp */
4996 b = gjmp(0);
4997 gsym(*case_sym);
4998 vseti(case_reg, 0);
4999 vpushi(v1);
5000 if (v1 == v2) {
5001 gen_op(TOK_EQ);
5002 *case_sym = gtst(1, 0);
5003 } else {
5004 gen_op(TOK_GE);
5005 *case_sym = gtst(1, 0);
5006 vseti(case_reg, 0);
5007 vpushi(v2);
5008 gen_op(TOK_LE);
5009 *case_sym = gtst(1, *case_sym);
5011 gsym(b);
5012 skip(':');
5013 is_expr = 0;
5014 goto block_after_label;
5015 } else
5016 if (tok == TOK_DEFAULT) {
5017 next();
5018 skip(':');
5019 if (!def_sym)
5020 expect("switch");
5021 if (*def_sym)
5022 tcc_error("too many 'default'");
5023 *def_sym = ind;
5024 is_expr = 0;
5025 goto block_after_label;
5026 } else
5027 if (tok == TOK_GOTO) {
5028 next();
5029 if (tok == '*' && gnu_ext) {
5030 /* computed goto */
5031 next();
5032 gexpr();
5033 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
5034 expect("pointer");
5035 ggoto();
5036 } else if (tok >= TOK_UIDENT) {
5037 s = label_find(tok);
5038 /* put forward definition if needed */
5039 if (!s) {
5040 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
5041 } else {
5042 if (s->r == LABEL_DECLARED)
5043 s->r = LABEL_FORWARD;
5045 /* label already defined */
5046 if (vla_flags & VLA_IN_SCOPE) {
5047 /* If VLAs are in use, save the current stack pointer and
5048 reset the stack pointer to what it was at function entry
5049 (label will restore stack pointer in inner scopes) */
5050 vla_sp_save();
5051 gen_vla_sp_restore(vla_sp_root_loc);
5053 if (s->r & LABEL_FORWARD)
5054 s->jnext = gjmp(s->jnext);
5055 else
5056 gjmp_addr(s->jnext);
5057 next();
5058 } else {
5059 expect("label identifier");
5061 skip(';');
5062 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
5063 asm_instr();
5064 } else {
5065 b = is_label();
5066 if (b) {
5067 /* label case */
5068 if (vla_flags & VLA_IN_SCOPE) {
5069 /* save/restore stack pointer across label
5070 this is a no-op when combined with the load immediately
5071 after the label unless we arrive via goto */
5072 vla_sp_save();
5074 s = label_find(b);
5075 if (s) {
5076 if (s->r == LABEL_DEFINED)
5077 tcc_error("duplicate label '%s'", get_tok_str(s->v, NULL));
5078 gsym(s->jnext);
5079 s->r = LABEL_DEFINED;
5080 } else {
5081 s = label_push(&global_label_stack, b, LABEL_DEFINED);
5083 s->jnext = ind;
5084 if (vla_flags & VLA_IN_SCOPE) {
5085 gen_vla_sp_restore(*vla_sp_loc);
5086 vla_flags |= VLA_NEED_NEW_FRAME;
5088 /* we accept this, but it is a mistake */
5089 block_after_label:
5090 if (tok == '}') {
5091 tcc_warning("deprecated use of label at end of compound statement");
5092 } else {
5093 if (is_expr)
5094 vpop();
5095 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
5097 } else {
5098 /* expression case */
5099 if (tok != ';') {
5100 if (is_expr) {
5101 vpop();
5102 gexpr();
5103 } else {
5104 gexpr();
5105 vpop();
5108 skip(';');
5113 /* t is the array or struct type. c is the array or struct
5114 address. cur_index/cur_field is the pointer to the current
5115 value. 'size_only' is true if only size info is needed (only used
5116 in arrays) */
5117 static void decl_designator(CType *type, Section *sec, unsigned long c,
5118 int *cur_index, Sym **cur_field,
5119 int size_only)
5121 Sym *s, *f;
5122 int notfirst, index, index_last, align, l, nb_elems, elem_size;
5123 CType type1;
5125 notfirst = 0;
5126 elem_size = 0;
5127 nb_elems = 1;
5128 if (gnu_ext && (l = is_label()) != 0)
5129 goto struct_field;
5130 while (tok == '[' || tok == '.') {
5131 if (tok == '[') {
5132 if (!(type->t & VT_ARRAY))
5133 expect("array type");
5134 s = type->ref;
5135 next();
5136 index = expr_const();
5137 if (index < 0 || (s->c >= 0 && index >= s->c))
5138 expect("invalid index");
5139 if (tok == TOK_DOTS && gnu_ext) {
5140 next();
5141 index_last = expr_const();
5142 if (index_last < 0 ||
5143 (s->c >= 0 && index_last >= s->c) ||
5144 index_last < index)
5145 expect("invalid index");
5146 } else {
5147 index_last = index;
5149 skip(']');
5150 if (!notfirst)
5151 *cur_index = index_last;
5152 type = pointed_type(type);
5153 elem_size = type_size(type, &align);
5154 c += index * elem_size;
5155 /* NOTE: we only support ranges for last designator */
5156 nb_elems = index_last - index + 1;
5157 if (nb_elems != 1) {
5158 notfirst = 1;
5159 break;
5161 } else {
5162 next();
5163 l = tok;
5164 next();
5165 struct_field:
5166 if ((type->t & VT_BTYPE) != VT_STRUCT)
5167 expect("struct/union type");
5168 s = type->ref;
5169 l |= SYM_FIELD;
5170 f = s->next;
5171 while (f) {
5172 if (f->v == l)
5173 break;
5174 f = f->next;
5176 if (!f)
5177 expect("field");
5178 if (!notfirst)
5179 *cur_field = f;
5180 /* XXX: fix this mess by using explicit storage field */
5181 type1 = f->type;
5182 type1.t |= (type->t & ~VT_TYPE);
5183 type = &type1;
5184 c += f->c;
5186 notfirst = 1;
5188 if (notfirst) {
5189 if (tok == '=') {
5190 next();
5191 } else {
5192 if (!gnu_ext)
5193 expect("=");
5195 } else {
5196 if (type->t & VT_ARRAY) {
5197 index = *cur_index;
5198 type = pointed_type(type);
5199 c += index * type_size(type, &align);
5200 } else {
5201 f = *cur_field;
5202 if (!f)
5203 tcc_error("too many field init");
5204 /* XXX: fix this mess by using explicit storage field */
5205 type1 = f->type;
5206 type1.t |= (type->t & ~VT_TYPE);
5207 type = &type1;
5208 c += f->c;
5211 decl_initializer(type, sec, c, 0, size_only);
5213 /* XXX: make it more general */
5214 if (!size_only && nb_elems > 1) {
5215 unsigned long c_end;
5216 uint8_t *src, *dst;
5217 int i;
5219 if (!sec)
5220 tcc_error("range init not supported yet for dynamic storage");
5221 c_end = c + nb_elems * elem_size;
5222 if (c_end > sec->data_allocated)
5223 section_realloc(sec, c_end);
5224 src = sec->data + c;
5225 dst = src;
5226 for(i = 1; i < nb_elems; i++) {
5227 dst += elem_size;
5228 memcpy(dst, src, elem_size);
5233 #define EXPR_VAL 0
5234 #define EXPR_CONST 1
5235 #define EXPR_ANY 2
5237 /* store a value or an expression directly in global data or in local array */
5238 static void init_putv(CType *type, Section *sec, unsigned long c,
5239 int v, int expr_type)
5241 int saved_global_expr, bt, bit_pos, bit_size;
5242 void *ptr;
5243 unsigned long long bit_mask;
5244 CType dtype;
5246 switch(expr_type) {
5247 case EXPR_VAL:
5248 vpushi(v);
5249 break;
5250 case EXPR_CONST:
5251 /* compound literals must be allocated globally in this case */
5252 saved_global_expr = global_expr;
5253 global_expr = 1;
5254 expr_const1();
5255 global_expr = saved_global_expr;
5256 /* NOTE: symbols are accepted */
5257 if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
5258 tcc_error("initializer element is not constant");
5259 break;
5260 case EXPR_ANY:
5261 expr_eq();
5262 break;
5265 dtype = *type;
5266 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
5268 if (sec) {
5269 /* XXX: not portable */
5270 /* XXX: generate error if incorrect relocation */
5271 gen_assign_cast(&dtype);
5272 bt = type->t & VT_BTYPE;
5273 /* we'll write at most 12 bytes */
5274 if (c + 12 > sec->data_allocated) {
5275 section_realloc(sec, c + 12);
5277 ptr = sec->data + c;
5278 /* XXX: make code faster ? */
5279 if (!(type->t & VT_BITFIELD)) {
5280 bit_pos = 0;
5281 bit_size = 32;
5282 bit_mask = -1LL;
5283 } else {
5284 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5285 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
5286 bit_mask = (1LL << bit_size) - 1;
5288 if ((vtop->r & VT_SYM) &&
5289 (bt == VT_BYTE ||
5290 bt == VT_SHORT ||
5291 bt == VT_DOUBLE ||
5292 bt == VT_LDOUBLE ||
5293 bt == VT_LLONG ||
5294 (bt == VT_INT && bit_size != 32)))
5295 tcc_error("initializer element is not computable at load time");
5296 switch(bt) {
5297 case VT_BOOL:
5298 vtop->c.i = (vtop->c.i != 0);
5299 case VT_BYTE:
5300 *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5301 break;
5302 case VT_SHORT:
5303 *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5304 break;
5305 case VT_DOUBLE:
5306 *(double *)ptr = vtop->c.d;
5307 break;
5308 case VT_LDOUBLE:
5309 *(long double *)ptr = vtop->c.ld;
5310 break;
5311 case VT_LLONG:
5312 *(long long *)ptr |= (vtop->c.ll & bit_mask) << bit_pos;
5313 break;
5314 case VT_PTR:
5315 if (vtop->r & VT_SYM) {
5316 greloc(sec, vtop->sym, c, R_DATA_PTR);
5318 *(addr_t *)ptr |= (vtop->c.ptr_offset & bit_mask) << bit_pos;
5319 break;
5320 default:
5321 if (vtop->r & VT_SYM) {
5322 greloc(sec, vtop->sym, c, R_DATA_PTR);
5324 *(int *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5325 break;
5327 vtop--;
5328 } else {
5329 vset(&dtype, VT_LOCAL|VT_LVAL, c);
5330 vswap();
5331 vstore();
5332 vpop();
5336 /* put zeros for variable based init */
5337 static void init_putz(CType *t, Section *sec, unsigned long c, int size)
5339 if (sec) {
5340 /* nothing to do because globals are already set to zero */
5341 } else {
5342 vpush_global_sym(&func_old_type, TOK_memset);
5343 vseti(VT_LOCAL, c);
5344 #ifdef TCC_TARGET_ARM
5345 vpushs(size);
5346 vpushi(0);
5347 #else
5348 vpushi(0);
5349 vpushs(size);
5350 #endif
5351 gfunc_call(3);
5355 /* 't' contains the type and storage info. 'c' is the offset of the
5356 object in section 'sec'. If 'sec' is NULL, it means stack based
5357 allocation. 'first' is true if array '{' must be read (multi
5358 dimension implicit array init handling). 'size_only' is true if
5359 size only evaluation is wanted (only for arrays). */
5360 static void decl_initializer(CType *type, Section *sec, unsigned long c,
5361 int first, int size_only)
5363 int index, array_length, n, no_oblock, nb, parlevel, parlevel1, i;
5364 int size1, align1, expr_type;
5365 Sym *s, *f;
5366 CType *t1;
5368 if (type->t & VT_VLA) {
5369 int a;
5371 /* save current stack pointer */
5372 if (vla_flags & VLA_NEED_NEW_FRAME) {
5373 vla_sp_save();
5374 vla_flags = VLA_IN_SCOPE;
5375 vla_sp_loc = &vla_sp_loc_tmp;
5378 vla_runtime_type_size(type, &a);
5379 gen_vla_alloc(type, a);
5380 vset(type, VT_LOCAL|VT_LVAL, c);
5381 vswap();
5382 vstore();
5383 vpop();
5384 } else if (type->t & VT_ARRAY) {
5385 s = type->ref;
5386 n = s->c;
5387 array_length = 0;
5388 t1 = pointed_type(type);
5389 size1 = type_size(t1, &align1);
5391 no_oblock = 1;
5392 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
5393 tok == '{') {
5394 if (tok != '{')
5395 tcc_error("character array initializer must be a literal,"
5396 " optionally enclosed in braces");
5397 skip('{');
5398 no_oblock = 0;
5401 /* only parse strings here if correct type (otherwise: handle
5402 them as ((w)char *) expressions */
5403 if ((tok == TOK_LSTR &&
5404 #ifdef TCC_TARGET_PE
5405 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
5406 #else
5407 (t1->t & VT_BTYPE) == VT_INT
5408 #endif
5409 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
5410 while (tok == TOK_STR || tok == TOK_LSTR) {
5411 int cstr_len, ch;
5412 CString *cstr;
5414 cstr = tokc.cstr;
5415 /* compute maximum number of chars wanted */
5416 if (tok == TOK_STR)
5417 cstr_len = cstr->size;
5418 else
5419 cstr_len = cstr->size / sizeof(nwchar_t);
5420 cstr_len--;
5421 nb = cstr_len;
5422 if (n >= 0 && nb > (n - array_length))
5423 nb = n - array_length;
5424 if (!size_only) {
5425 if (cstr_len > nb)
5426 tcc_warning("initializer-string for array is too long");
5427 /* in order to go faster for common case (char
5428 string in global variable, we handle it
5429 specifically */
5430 if (sec && tok == TOK_STR && size1 == 1) {
5431 memcpy(sec->data + c + array_length, cstr->data, nb);
5432 } else {
5433 for(i=0;i<nb;i++) {
5434 if (tok == TOK_STR)
5435 ch = ((unsigned char *)cstr->data)[i];
5436 else
5437 ch = ((nwchar_t *)cstr->data)[i];
5438 init_putv(t1, sec, c + (array_length + i) * size1,
5439 ch, EXPR_VAL);
5443 array_length += nb;
5444 next();
5446 /* only add trailing zero if enough storage (no
5447 warning in this case since it is standard) */
5448 if (n < 0 || array_length < n) {
5449 if (!size_only) {
5450 init_putv(t1, sec, c + (array_length * size1), 0, EXPR_VAL);
5452 array_length++;
5454 } else {
5455 index = 0;
5456 while (tok != '}') {
5457 decl_designator(type, sec, c, &index, NULL, size_only);
5458 if (n >= 0 && index >= n)
5459 tcc_error("index too large");
5460 /* must put zero in holes (note that doing it that way
5461 ensures that it even works with designators) */
5462 if (!size_only && array_length < index) {
5463 init_putz(t1, sec, c + array_length * size1,
5464 (index - array_length) * size1);
5466 index++;
5467 if (index > array_length)
5468 array_length = index;
5469 /* special test for multi dimensional arrays (may not
5470 be strictly correct if designators are used at the
5471 same time) */
5472 if (index >= n && no_oblock)
5473 break;
5474 if (tok == '}')
5475 break;
5476 skip(',');
5479 if (!no_oblock)
5480 skip('}');
5481 /* put zeros at the end */
5482 if (!size_only && n >= 0 && array_length < n) {
5483 init_putz(t1, sec, c + array_length * size1,
5484 (n - array_length) * size1);
5486 /* patch type size if needed */
5487 if (n < 0)
5488 s->c = array_length;
5489 } else if ((type->t & VT_BTYPE) == VT_STRUCT &&
5490 (sec || !first || tok == '{')) {
5491 int par_count;
5493 /* NOTE: the previous test is a specific case for automatic
5494 struct/union init */
5495 /* XXX: union needs only one init */
5497 /* XXX: this test is incorrect for local initializers
5498 beginning with ( without {. It would be much more difficult
5499 to do it correctly (ideally, the expression parser should
5500 be used in all cases) */
5501 par_count = 0;
5502 if (tok == '(') {
5503 AttributeDef ad1;
5504 CType type1;
5505 next();
5506 while (tok == '(') {
5507 par_count++;
5508 next();
5510 if (!parse_btype(&type1, &ad1))
5511 expect("cast");
5512 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
5513 #if 0
5514 if (!is_assignable_types(type, &type1))
5515 tcc_error("invalid type for cast");
5516 #endif
5517 skip(')');
5519 no_oblock = 1;
5520 if (first || tok == '{') {
5521 skip('{');
5522 no_oblock = 0;
5524 s = type->ref;
5525 f = s->next;
5526 array_length = 0;
5527 index = 0;
5528 n = s->c;
5529 while (tok != '}') {
5530 decl_designator(type, sec, c, NULL, &f, size_only);
5531 index = f->c;
5532 if (!size_only && array_length < index) {
5533 init_putz(type, sec, c + array_length,
5534 index - array_length);
5536 index = index + type_size(&f->type, &align1);
5537 if (index > array_length)
5538 array_length = index;
5540 /* gr: skip fields from same union - ugly. */
5541 while (f->next) {
5542 ///printf("index: %2d %08x -- %2d %08x\n", f->c, f->type.t, f->next->c, f->next->type.t);
5543 /* test for same offset */
5544 if (f->next->c != f->c)
5545 break;
5546 /* if yes, test for bitfield shift */
5547 if ((f->type.t & VT_BITFIELD) && (f->next->type.t & VT_BITFIELD)) {
5548 int bit_pos_1 = (f->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5549 int bit_pos_2 = (f->next->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5550 //printf("bitfield %d %d\n", bit_pos_1, bit_pos_2);
5551 if (bit_pos_1 != bit_pos_2)
5552 break;
5554 f = f->next;
5557 f = f->next;
5558 if (no_oblock && f == NULL)
5559 break;
5560 if (tok == '}')
5561 break;
5562 skip(',');
5564 /* put zeros at the end */
5565 if (!size_only && array_length < n) {
5566 init_putz(type, sec, c + array_length,
5567 n - array_length);
5569 if (!no_oblock)
5570 skip('}');
5571 while (par_count) {
5572 skip(')');
5573 par_count--;
5575 } else if (tok == '{') {
5576 next();
5577 decl_initializer(type, sec, c, first, size_only);
5578 skip('}');
5579 } else if (size_only) {
5580 /* just skip expression */
5581 parlevel = parlevel1 = 0;
5582 while ((parlevel > 0 || parlevel1 > 0 ||
5583 (tok != '}' && tok != ',')) && tok != -1) {
5584 if (tok == '(')
5585 parlevel++;
5586 else if (tok == ')')
5587 parlevel--;
5588 else if (tok == '{')
5589 parlevel1++;
5590 else if (tok == '}')
5591 parlevel1--;
5592 next();
5594 } else {
5595 /* currently, we always use constant expression for globals
5596 (may change for scripting case) */
5597 expr_type = EXPR_CONST;
5598 if (!sec)
5599 expr_type = EXPR_ANY;
5600 init_putv(type, sec, c, 0, expr_type);
5604 /* parse an initializer for type 't' if 'has_init' is non zero, and
5605 allocate space in local or global data space ('r' is either
5606 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
5607 variable 'v' with an associated name represented by 'asm_label' of
5608 scope 'scope' is declared before initializers are parsed. If 'v' is
5609 zero, then a reference to the new object is put in the value stack.
5610 If 'has_init' is 2, a special parsing is done to handle string
5611 constants. */
5612 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
5613 int has_init, int v, char *asm_label,
5614 int scope)
5616 int size, align, addr, data_offset;
5617 int level;
5618 ParseState saved_parse_state = {0};
5619 TokenString init_str;
5620 Section *sec;
5621 Sym *flexible_array;
5623 flexible_array = NULL;
5624 if ((type->t & VT_BTYPE) == VT_STRUCT) {
5625 Sym *field = type->ref->next;
5626 if (field) {
5627 while (field->next)
5628 field = field->next;
5629 if (field->type.t & VT_ARRAY && field->type.ref->c < 0)
5630 flexible_array = field;
5634 size = type_size(type, &align);
5635 /* If unknown size, we must evaluate it before
5636 evaluating initializers because
5637 initializers can generate global data too
5638 (e.g. string pointers or ISOC99 compound
5639 literals). It also simplifies local
5640 initializers handling */
5641 tok_str_new(&init_str);
5642 if (size < 0 || (flexible_array && has_init)) {
5643 if (!has_init)
5644 tcc_error("unknown type size");
5645 /* get all init string */
5646 if (has_init == 2) {
5647 /* only get strings */
5648 while (tok == TOK_STR || tok == TOK_LSTR) {
5649 tok_str_add_tok(&init_str);
5650 next();
5652 } else {
5653 level = 0;
5654 while (level > 0 || (tok != ',' && tok != ';')) {
5655 if (tok < 0)
5656 tcc_error("unexpected end of file in initializer");
5657 tok_str_add_tok(&init_str);
5658 if (tok == '{')
5659 level++;
5660 else if (tok == '}') {
5661 level--;
5662 if (level <= 0) {
5663 next();
5664 break;
5667 next();
5670 tok_str_add(&init_str, -1);
5671 tok_str_add(&init_str, 0);
5673 /* compute size */
5674 save_parse_state(&saved_parse_state);
5676 macro_ptr = init_str.str;
5677 next();
5678 decl_initializer(type, NULL, 0, 1, 1);
5679 /* prepare second initializer parsing */
5680 macro_ptr = init_str.str;
5681 next();
5683 /* if still unknown size, error */
5684 size = type_size(type, &align);
5685 if (size < 0)
5686 tcc_error("unknown type size");
5688 if (flexible_array)
5689 size += flexible_array->type.ref->c * pointed_size(&flexible_array->type);
5690 /* take into account specified alignment if bigger */
5691 if (ad->a.aligned) {
5692 if (ad->a.aligned > align)
5693 align = ad->a.aligned;
5694 } else if (ad->a.packed) {
5695 align = 1;
5697 if ((r & VT_VALMASK) == VT_LOCAL) {
5698 sec = NULL;
5699 #ifdef CONFIG_TCC_BCHECK
5700 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5701 loc_stack(1, 1);
5703 #endif
5704 addr = loc_stack(size, 1);
5705 #ifdef CONFIG_TCC_BCHECK
5706 /* handles bounds */
5707 /* XXX: currently, since we do only one pass, we cannot track
5708 '&' operators, so we add only arrays */
5709 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5710 unsigned long *bounds_ptr;
5711 /* add padding between regions */
5712 loc_stack(1, 1);
5713 /* then add local bound info */
5714 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(unsigned long));
5715 bounds_ptr[0] = addr;
5716 bounds_ptr[1] = size;
5718 #endif
5719 if (v) {
5720 /* local variable */
5721 sym_push(v, type, r, addr);
5722 } else {
5723 /* push local reference */
5724 vset(type, r, addr);
5726 } else {
5727 Sym *sym;
5729 sym = NULL;
5730 if (v && scope == VT_CONST) {
5731 /* see if the symbol was already defined */
5732 sym = sym_find(v);
5733 if (sym) {
5734 if (!is_compatible_types(&sym->type, type))
5735 tcc_error("incompatible types for redefinition of '%s'",
5736 get_tok_str(v, NULL));
5737 if (sym->type.t & VT_EXTERN) {
5738 /* if the variable is extern, it was not allocated */
5739 sym->type.t &= ~VT_EXTERN;
5740 /* set array size if it was omitted in extern
5741 declaration */
5742 if ((sym->type.t & VT_ARRAY) &&
5743 sym->type.ref->c < 0 &&
5744 type->ref->c >= 0)
5745 sym->type.ref->c = type->ref->c;
5746 } else {
5747 /* we accept several definitions of the same
5748 global variable. this is tricky, because we
5749 must play with the SHN_COMMON type of the symbol */
5750 /* XXX: should check if the variable was already
5751 initialized. It is incorrect to initialized it
5752 twice */
5753 /* no init data, we won't add more to the symbol */
5754 if (!has_init)
5755 goto no_alloc;
5760 /* allocate symbol in corresponding section */
5761 sec = ad->section;
5762 if (!sec) {
5763 if (has_init)
5764 sec = data_section;
5765 else if (tcc_state->nocommon)
5766 sec = bss_section;
5768 if (sec) {
5769 data_offset = sec->data_offset;
5770 data_offset = (data_offset + align - 1) & -align;
5771 addr = data_offset;
5772 /* very important to increment global pointer at this time
5773 because initializers themselves can create new initializers */
5774 data_offset += size;
5775 #ifdef CONFIG_TCC_BCHECK
5776 /* add padding if bound check */
5777 if (tcc_state->do_bounds_check)
5778 data_offset++;
5779 #endif
5780 sec->data_offset = data_offset;
5781 /* allocate section space to put the data */
5782 if (sec->sh_type != SHT_NOBITS &&
5783 data_offset > sec->data_allocated)
5784 section_realloc(sec, data_offset);
5785 /* align section if needed */
5786 if (align > sec->sh_addralign)
5787 sec->sh_addralign = align;
5788 } else {
5789 addr = 0; /* avoid warning */
5792 if (v) {
5793 if (scope != VT_CONST || !sym) {
5794 sym = sym_push(v, type, r | VT_SYM, 0);
5795 sym->asm_label = asm_label;
5797 /* update symbol definition */
5798 if (sec) {
5799 put_extern_sym(sym, sec, addr, size);
5800 } else {
5801 ElfW(Sym) *esym;
5802 /* put a common area */
5803 put_extern_sym(sym, NULL, align, size);
5804 /* XXX: find a nicer way */
5805 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
5806 esym->st_shndx = SHN_COMMON;
5808 } else {
5809 /* push global reference */
5810 sym = get_sym_ref(type, sec, addr, size);
5811 vpushsym(type, sym);
5813 /* patch symbol weakness */
5814 if (type->t & VT_WEAK)
5815 weaken_symbol(sym);
5816 apply_visibility(sym, type);
5817 #ifdef CONFIG_TCC_BCHECK
5818 /* handles bounds now because the symbol must be defined
5819 before for the relocation */
5820 if (tcc_state->do_bounds_check) {
5821 unsigned long *bounds_ptr;
5823 greloc(bounds_section, sym, bounds_section->data_offset, R_DATA_PTR);
5824 /* then add global bound info */
5825 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(long));
5826 bounds_ptr[0] = 0; /* relocated */
5827 bounds_ptr[1] = size;
5829 #endif
5831 if (has_init || (type->t & VT_VLA)) {
5832 decl_initializer(type, sec, addr, 1, 0);
5833 /* restore parse state if needed */
5834 if (init_str.str) {
5835 tok_str_free(init_str.str);
5836 restore_parse_state(&saved_parse_state);
5838 /* patch flexible array member size back to -1, */
5839 /* for possible subsequent similar declarations */
5840 if (flexible_array)
5841 flexible_array->type.ref->c = -1;
5843 no_alloc: ;
5846 static void put_func_debug(Sym *sym)
5848 char buf[512];
5850 /* stabs info */
5851 /* XXX: we put here a dummy type */
5852 snprintf(buf, sizeof(buf), "%s:%c1",
5853 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
5854 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
5855 cur_text_section, sym->c);
5856 /* //gr gdb wants a line at the function */
5857 put_stabn(N_SLINE, 0, file->line_num, 0);
5858 last_ind = 0;
5859 last_line_num = 0;
5862 /* parse an old style function declaration list */
5863 /* XXX: check multiple parameter */
5864 static void func_decl_list(Sym *func_sym)
5866 AttributeDef ad;
5867 int v;
5868 Sym *s;
5869 CType btype, type;
5871 /* parse each declaration */
5872 while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF &&
5873 tok != TOK_ASM1 && tok != TOK_ASM2 && tok != TOK_ASM3) {
5874 if (!parse_btype(&btype, &ad))
5875 expect("declaration list");
5876 if (((btype.t & VT_BTYPE) == VT_ENUM ||
5877 (btype.t & VT_BTYPE) == VT_STRUCT) &&
5878 tok == ';') {
5879 /* we accept no variable after */
5880 } else {
5881 for(;;) {
5882 type = btype;
5883 type_decl(&type, &ad, &v, TYPE_DIRECT);
5884 /* find parameter in function parameter list */
5885 s = func_sym->next;
5886 while (s != NULL) {
5887 if ((s->v & ~SYM_FIELD) == v)
5888 goto found;
5889 s = s->next;
5891 tcc_error("declaration for parameter '%s' but no such parameter",
5892 get_tok_str(v, NULL));
5893 found:
5894 /* check that no storage specifier except 'register' was given */
5895 if (type.t & VT_STORAGE)
5896 tcc_error("storage class specified for '%s'", get_tok_str(v, NULL));
5897 convert_parameter_type(&type);
5898 /* we can add the type (NOTE: it could be local to the function) */
5899 s->type = type;
5900 /* accept other parameters */
5901 if (tok == ',')
5902 next();
5903 else
5904 break;
5907 skip(';');
5911 /* parse a function defined by symbol 'sym' and generate its code in
5912 'cur_text_section' */
5913 static void gen_function(Sym *sym)
5915 int saved_nocode_wanted = nocode_wanted;
5916 nocode_wanted = 0;
5917 ind = cur_text_section->data_offset;
5918 /* NOTE: we patch the symbol size later */
5919 put_extern_sym(sym, cur_text_section, ind, 0);
5920 funcname = get_tok_str(sym->v, NULL);
5921 func_ind = ind;
5922 /* Initialize VLA state */
5923 vla_sp_loc = &vla_sp_root_loc;
5924 vla_flags = VLA_NEED_NEW_FRAME;
5925 /* put debug symbol */
5926 if (tcc_state->do_debug)
5927 put_func_debug(sym);
5928 /* push a dummy symbol to enable local sym storage */
5929 sym_push2(&local_stack, SYM_FIELD, 0, 0);
5930 gfunc_prolog(&sym->type);
5931 #ifdef CONFIG_TCC_BCHECK
5932 if (tcc_state->do_bounds_check
5933 && !strcmp(get_tok_str(sym->v, NULL), "main")) {
5934 int i;
5936 sym = local_stack;
5937 for (i = 0, sym = local_stack; i < 2; i++, sym = sym->prev) {
5938 if (sym->v & SYM_FIELD || sym->prev->v & SYM_FIELD)
5939 break;
5940 vpush_global_sym(&func_old_type, TOK___bound_main_arg);
5941 vset(&sym->type, sym->r, sym->c);
5942 gfunc_call(1);
5945 #endif
5946 rsym = 0;
5947 block(NULL, NULL, NULL, NULL, 0, 0);
5948 gsym(rsym);
5949 gfunc_epilog();
5950 cur_text_section->data_offset = ind;
5951 label_pop(&global_label_stack, NULL);
5952 /* reset local stack */
5953 scope_stack_bottom = NULL;
5954 sym_pop(&local_stack, NULL);
5955 /* end of function */
5956 /* patch symbol size */
5957 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
5958 ind - func_ind;
5959 /* patch symbol weakness (this definition overrules any prototype) */
5960 if (sym->type.t & VT_WEAK)
5961 weaken_symbol(sym);
5962 apply_visibility(sym, &sym->type);
5963 if (tcc_state->do_debug) {
5964 put_stabn(N_FUN, 0, 0, ind - func_ind);
5966 /* It's better to crash than to generate wrong code */
5967 cur_text_section = NULL;
5968 funcname = ""; /* for safety */
5969 func_vt.t = VT_VOID; /* for safety */
5970 func_var = 0; /* for safety */
5971 ind = 0; /* for safety */
5972 nocode_wanted = saved_nocode_wanted;
5975 ST_FUNC void gen_inline_functions(void)
5977 Sym *sym;
5978 int *str, inline_generated, i;
5979 struct InlineFunc *fn;
5981 /* iterate while inline function are referenced */
5982 for(;;) {
5983 inline_generated = 0;
5984 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
5985 fn = tcc_state->inline_fns[i];
5986 sym = fn->sym;
5987 if (sym && sym->c) {
5988 /* the function was used: generate its code and
5989 convert it to a normal function */
5990 str = fn->token_str;
5991 fn->sym = NULL;
5992 if (file)
5993 pstrcpy(file->filename, sizeof file->filename, fn->filename);
5994 sym->r = VT_SYM | VT_CONST;
5995 sym->type.t &= ~VT_INLINE;
5997 macro_ptr = str;
5998 next();
5999 cur_text_section = text_section;
6000 gen_function(sym);
6001 macro_ptr = NULL; /* fail safe */
6003 inline_generated = 1;
6006 if (!inline_generated)
6007 break;
6009 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
6010 fn = tcc_state->inline_fns[i];
6011 str = fn->token_str;
6012 tok_str_free(str);
6014 dynarray_reset(&tcc_state->inline_fns, &tcc_state->nb_inline_fns);
6017 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
6018 static int decl0(int l, int is_for_loop_init)
6020 int v, has_init, r;
6021 CType type, btype;
6022 Sym *sym;
6023 AttributeDef ad;
6025 while (1) {
6026 if (!parse_btype(&btype, &ad)) {
6027 if (is_for_loop_init)
6028 return 0;
6029 /* skip redundant ';' */
6030 /* XXX: find more elegant solution */
6031 if (tok == ';') {
6032 next();
6033 continue;
6035 if (l == VT_CONST &&
6036 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
6037 /* global asm block */
6038 asm_global_instr();
6039 continue;
6041 /* special test for old K&R protos without explicit int
6042 type. Only accepted when defining global data */
6043 if (l == VT_LOCAL || tok < TOK_DEFINE)
6044 break;
6045 btype.t = VT_INT;
6047 if (((btype.t & VT_BTYPE) == VT_ENUM ||
6048 (btype.t & VT_BTYPE) == VT_STRUCT) &&
6049 tok == ';') {
6050 /* we accept no variable after */
6051 next();
6052 continue;
6054 while (1) { /* iterate thru each declaration */
6055 char *asm_label; // associated asm label
6056 type = btype;
6057 type_decl(&type, &ad, &v, TYPE_DIRECT);
6058 #if 0
6060 char buf[500];
6061 type_to_str(buf, sizeof(buf), t, get_tok_str(v, NULL));
6062 printf("type = '%s'\n", buf);
6064 #endif
6065 if ((type.t & VT_BTYPE) == VT_FUNC) {
6066 if ((type.t & VT_STATIC) && (l == VT_LOCAL)) {
6067 tcc_error("function without file scope cannot be static");
6069 /* if old style function prototype, we accept a
6070 declaration list */
6071 sym = type.ref;
6072 if (sym->c == FUNC_OLD)
6073 func_decl_list(sym);
6076 asm_label = NULL;
6077 if (gnu_ext && (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
6078 CString astr;
6080 asm_label_instr(&astr);
6081 asm_label = tcc_strdup(astr.data);
6082 cstr_free(&astr);
6084 /* parse one last attribute list, after asm label */
6085 parse_attribute(&ad);
6088 if (ad.a.weak)
6089 type.t |= VT_WEAK;
6090 #ifdef TCC_TARGET_PE
6091 if (ad.a.func_import)
6092 type.t |= VT_IMPORT;
6093 if (ad.a.func_export)
6094 type.t |= VT_EXPORT;
6095 #endif
6096 type.t |= ad.a.visibility << VT_VIS_SHIFT;
6098 if (tok == '{') {
6099 if (l == VT_LOCAL)
6100 tcc_error("cannot use local functions");
6101 if ((type.t & VT_BTYPE) != VT_FUNC)
6102 expect("function definition");
6104 /* reject abstract declarators in function definition */
6105 sym = type.ref;
6106 while ((sym = sym->next) != NULL)
6107 if (!(sym->v & ~SYM_FIELD))
6108 expect("identifier");
6110 /* XXX: cannot do better now: convert extern line to static inline */
6111 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
6112 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
6114 sym = sym_find(v);
6115 if (sym) {
6116 Sym *ref;
6117 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
6118 goto func_error1;
6120 ref = sym->type.ref;
6121 if (0 == ref->a.func_proto)
6122 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
6124 /* use func_call from prototype if not defined */
6125 if (ref->a.func_call != FUNC_CDECL
6126 && type.ref->a.func_call == FUNC_CDECL)
6127 type.ref->a.func_call = ref->a.func_call;
6129 /* use export from prototype */
6130 if (ref->a.func_export)
6131 type.ref->a.func_export = 1;
6133 /* use static from prototype */
6134 if (sym->type.t & VT_STATIC)
6135 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
6137 /* If the definition has no visibility use the
6138 one from prototype. */
6139 if (! (type.t & VT_VIS_MASK))
6140 type.t |= sym->type.t & VT_VIS_MASK;
6142 if (!is_compatible_types(&sym->type, &type)) {
6143 func_error1:
6144 tcc_error("incompatible types for redefinition of '%s'",
6145 get_tok_str(v, NULL));
6147 type.ref->a.func_proto = 0;
6148 /* if symbol is already defined, then put complete type */
6149 sym->type = type;
6150 } else {
6151 /* put function symbol */
6152 sym = global_identifier_push(v, type.t, 0);
6153 sym->type.ref = type.ref;
6156 /* static inline functions are just recorded as a kind
6157 of macro. Their code will be emitted at the end of
6158 the compilation unit only if they are used */
6159 if ((type.t & (VT_INLINE | VT_STATIC)) ==
6160 (VT_INLINE | VT_STATIC)) {
6161 TokenString func_str;
6162 int block_level;
6163 struct InlineFunc *fn;
6164 const char *filename;
6166 tok_str_new(&func_str);
6168 block_level = 0;
6169 for(;;) {
6170 int t;
6171 if (tok == TOK_EOF)
6172 tcc_error("unexpected end of file");
6173 tok_str_add_tok(&func_str);
6174 t = tok;
6175 next();
6176 if (t == '{') {
6177 block_level++;
6178 } else if (t == '}') {
6179 block_level--;
6180 if (block_level == 0)
6181 break;
6184 tok_str_add(&func_str, -1);
6185 tok_str_add(&func_str, 0);
6186 filename = file ? file->filename : "";
6187 fn = tcc_malloc(sizeof *fn + strlen(filename));
6188 strcpy(fn->filename, filename);
6189 fn->sym = sym;
6190 fn->token_str = func_str.str;
6191 dynarray_add((void ***)&tcc_state->inline_fns, &tcc_state->nb_inline_fns, fn);
6193 } else {
6194 /* compute text section */
6195 cur_text_section = ad.section;
6196 if (!cur_text_section)
6197 cur_text_section = text_section;
6198 sym->r = VT_SYM | VT_CONST;
6199 gen_function(sym);
6201 break;
6202 } else {
6203 if (btype.t & VT_TYPEDEF) {
6204 /* save typedefed type */
6205 /* XXX: test storage specifiers ? */
6206 sym = sym_push(v, &type, 0, 0);
6207 sym->a = ad.a;
6208 sym->type.t |= VT_TYPEDEF;
6209 } else {
6210 r = 0;
6211 if ((type.t & VT_BTYPE) == VT_FUNC) {
6212 /* external function definition */
6213 /* specific case for func_call attribute */
6214 ad.a.func_proto = 1;
6215 type.ref->a = ad.a;
6216 } else if (!(type.t & VT_ARRAY)) {
6217 /* not lvalue if array */
6218 r |= lvalue_type(type.t);
6220 has_init = (tok == '=');
6221 if (has_init && (type.t & VT_VLA))
6222 tcc_error("Variable length array cannot be initialized");
6223 if ((btype.t & VT_EXTERN) || ((type.t & VT_BTYPE) == VT_FUNC) ||
6224 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
6225 !has_init && l == VT_CONST && type.ref->c < 0)) {
6226 /* external variable or function */
6227 /* NOTE: as GCC, uninitialized global static
6228 arrays of null size are considered as
6229 extern */
6230 sym = external_sym(v, &type, r, asm_label);
6232 if (ad.alias_target) {
6233 Section tsec;
6234 Elf32_Sym *esym;
6235 Sym *alias_target;
6237 alias_target = sym_find(ad.alias_target);
6238 if (!alias_target || !alias_target->c)
6239 tcc_error("unsupported forward __alias__ attribute");
6240 esym = &((Elf32_Sym *)symtab_section->data)[alias_target->c];
6241 tsec.sh_num = esym->st_shndx;
6242 put_extern_sym2(sym, &tsec, esym->st_value, esym->st_size, 0);
6244 } else {
6245 type.t |= (btype.t & VT_STATIC); /* Retain "static". */
6246 if (type.t & VT_STATIC)
6247 r |= VT_CONST;
6248 else
6249 r |= l;
6250 if (has_init)
6251 next();
6252 decl_initializer_alloc(&type, &ad, r, has_init, v, asm_label, l);
6255 if (tok != ',') {
6256 if (is_for_loop_init)
6257 return 1;
6258 skip(';');
6259 break;
6261 next();
6263 ad.a.aligned = 0;
6266 return 0;
6269 ST_FUNC void decl(int l)
6271 decl0(l, 0);