x86-64 ABI fixes.
[tinycc.git] / tccgen.c
blob83ee171ad5dbae27f8778f6d1371450725884006
1 /*
2 * TCC - Tiny C Compiler
3 *
4 * Copyright (c) 2001-2004 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #include "tcc.h"
23 /********************************************************/
24 /* global variables */
26 /* loc : local variable index
27 ind : output code index
28 rsym: return symbol
29 anon_sym: anonymous symbol index
31 ST_DATA int rsym, anon_sym, ind, loc;
33 ST_DATA Section *text_section, *data_section, *bss_section; /* predefined sections */
34 ST_DATA Section *cur_text_section; /* current section where function code is generated */
35 #ifdef CONFIG_TCC_ASM
36 ST_DATA Section *last_text_section; /* to handle .previous asm directive */
37 #endif
38 #ifdef CONFIG_TCC_BCHECK
39 /* bound check related sections */
40 ST_DATA Section *bounds_section; /* contains global data bound description */
41 ST_DATA Section *lbounds_section; /* contains local data bound description */
42 #endif
43 /* symbol sections */
44 ST_DATA Section *symtab_section, *strtab_section;
45 /* debug sections */
46 ST_DATA Section *stab_section, *stabstr_section;
47 ST_DATA Sym *sym_free_first;
48 ST_DATA void **sym_pools;
49 ST_DATA int nb_sym_pools;
51 ST_DATA Sym *global_stack;
52 ST_DATA Sym *local_stack;
53 ST_DATA Sym *scope_stack_bottom;
54 ST_DATA Sym *define_stack;
55 ST_DATA Sym *global_label_stack;
56 ST_DATA Sym *local_label_stack;
58 ST_DATA SValue __vstack[1+VSTACK_SIZE], *vtop;
60 ST_DATA int const_wanted; /* true if constant wanted */
61 ST_DATA int nocode_wanted; /* true if no code generation wanted for an expression */
62 ST_DATA int global_expr; /* true if compound literals must be allocated globally (used during initializers parsing */
63 ST_DATA CType func_vt; /* current function return type (used by return instruction) */
64 ST_DATA int func_vc;
65 ST_DATA int last_line_num, last_ind, func_ind; /* debug last line number and pc */
66 ST_DATA char *funcname;
68 ST_DATA CType char_pointer_type, func_old_type, int_type, size_type;
70 /* ------------------------------------------------------------------------- */
71 static void gen_cast(CType *type);
72 static inline CType *pointed_type(CType *type);
73 static int is_compatible_types(CType *type1, CType *type2);
74 static int parse_btype(CType *type, AttributeDef *ad);
75 static void type_decl(CType *type, AttributeDef *ad, int *v, int td);
76 static void parse_expr_type(CType *type);
77 static void decl_initializer(CType *type, Section *sec, unsigned long c, int first, int size_only);
78 static void block(int *bsym, int *csym, int *case_sym, int *def_sym, int case_reg, int is_expr);
79 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r, int has_init, int v, char *asm_label, int scope);
80 static int decl0(int l, int is_for_loop_init);
81 static void expr_eq(void);
82 static void unary_type(CType *type);
83 static void vla_runtime_type_size(CType *type, int *a);
84 static int is_compatible_parameter_types(CType *type1, CType *type2);
85 static void expr_type(CType *type);
87 ST_INLN int is_float(int t)
89 int bt;
90 bt = t & VT_BTYPE;
91 return bt == VT_LDOUBLE || bt == VT_DOUBLE || bt == VT_FLOAT;
94 /* we use our own 'finite' function to avoid potential problems with
95 non standard math libs */
96 /* XXX: endianness dependent */
97 ST_FUNC int ieee_finite(double d)
99 int *p = (int *)&d;
100 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
103 ST_FUNC void test_lvalue(void)
105 if (!(vtop->r & VT_LVAL))
106 expect("lvalue");
109 /* ------------------------------------------------------------------------- */
110 /* symbol allocator */
111 static Sym *__sym_malloc(void)
113 Sym *sym_pool, *sym, *last_sym;
114 int i;
116 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
117 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
119 last_sym = sym_free_first;
120 sym = sym_pool;
121 for(i = 0; i < SYM_POOL_NB; i++) {
122 sym->next = last_sym;
123 last_sym = sym;
124 sym++;
126 sym_free_first = last_sym;
127 return last_sym;
130 static inline Sym *sym_malloc(void)
132 Sym *sym;
133 sym = sym_free_first;
134 if (!sym)
135 sym = __sym_malloc();
136 sym_free_first = sym->next;
137 return sym;
140 ST_INLN void sym_free(Sym *sym)
142 sym->next = sym_free_first;
143 tcc_free(sym->asm_label);
144 sym_free_first = sym;
147 /* push, without hashing */
148 ST_FUNC Sym *sym_push2(Sym **ps, int v, int t, long c)
150 Sym *s;
151 if (ps == &local_stack) {
152 for (s = *ps; s && s != scope_stack_bottom; s = s->prev)
153 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM && s->v == v)
154 tcc_error("incompatible types for redefinition of '%s'",
155 get_tok_str(v, NULL));
157 s = *ps;
158 s = sym_malloc();
159 s->asm_label = NULL;
160 s->v = v;
161 s->type.t = t;
162 s->type.ref = NULL;
163 #ifdef _WIN64
164 s->d = NULL;
165 #endif
166 s->c = c;
167 s->next = NULL;
168 /* add in stack */
169 s->prev = *ps;
170 *ps = s;
171 return s;
174 /* find a symbol and return its associated structure. 's' is the top
175 of the symbol stack */
176 ST_FUNC Sym *sym_find2(Sym *s, int v)
178 while (s) {
179 if (s->v == v)
180 return s;
181 s = s->prev;
183 return NULL;
186 /* structure lookup */
187 ST_INLN Sym *struct_find(int v)
189 v -= TOK_IDENT;
190 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
191 return NULL;
192 return table_ident[v]->sym_struct;
195 /* find an identifier */
196 ST_INLN Sym *sym_find(int v)
198 v -= TOK_IDENT;
199 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
200 return NULL;
201 return table_ident[v]->sym_identifier;
204 /* push a given symbol on the symbol stack */
205 ST_FUNC Sym *sym_push(int v, CType *type, int r, int c)
207 Sym *s, **ps;
208 TokenSym *ts;
210 if (local_stack)
211 ps = &local_stack;
212 else
213 ps = &global_stack;
214 s = sym_push2(ps, v, type->t, c);
215 s->type.ref = type->ref;
216 s->r = r;
217 /* don't record fields or anonymous symbols */
218 /* XXX: simplify */
219 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
220 /* record symbol in token array */
221 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
222 if (v & SYM_STRUCT)
223 ps = &ts->sym_struct;
224 else
225 ps = &ts->sym_identifier;
226 s->prev_tok = *ps;
227 *ps = s;
229 return s;
232 /* push a global identifier */
233 ST_FUNC Sym *global_identifier_push(int v, int t, int c)
235 Sym *s, **ps;
236 s = sym_push2(&global_stack, v, t, c);
237 /* don't record anonymous symbol */
238 if (v < SYM_FIRST_ANOM) {
239 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
240 /* modify the top most local identifier, so that
241 sym_identifier will point to 's' when popped */
242 while (*ps != NULL)
243 ps = &(*ps)->prev_tok;
244 s->prev_tok = NULL;
245 *ps = s;
247 return s;
250 /* pop symbols until top reaches 'b' */
251 ST_FUNC void sym_pop(Sym **ptop, Sym *b)
253 Sym *s, *ss, **ps;
254 TokenSym *ts;
255 int v;
257 s = *ptop;
258 while(s != b) {
259 ss = s->prev;
260 v = s->v;
261 /* remove symbol in token array */
262 /* XXX: simplify */
263 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
264 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
265 if (v & SYM_STRUCT)
266 ps = &ts->sym_struct;
267 else
268 ps = &ts->sym_identifier;
269 *ps = s->prev_tok;
271 sym_free(s);
272 s = ss;
274 *ptop = b;
277 static void weaken_symbol(Sym *sym)
279 sym->type.t |= VT_WEAK;
280 if (sym->c > 0) {
281 int esym_type;
282 ElfW(Sym) *esym;
284 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
285 esym_type = ELFW(ST_TYPE)(esym->st_info);
286 esym->st_info = ELFW(ST_INFO)(STB_WEAK, esym_type);
290 /* ------------------------------------------------------------------------- */
292 ST_FUNC void swap(int *p, int *q)
294 int t;
295 t = *p;
296 *p = *q;
297 *q = t;
300 static void vsetc(CType *type, int r, CValue *vc)
302 int v;
304 if (vtop >= vstack + (VSTACK_SIZE - 1))
305 tcc_error("memory full");
306 /* cannot let cpu flags if other instruction are generated. Also
307 avoid leaving VT_JMP anywhere except on the top of the stack
308 because it would complicate the code generator. */
309 if (vtop >= vstack) {
310 v = vtop->r & VT_VALMASK;
311 if (v == VT_CMP || (v & ~1) == VT_JMP)
312 gv(RC_INT);
314 vtop++;
315 vtop->type = *type;
316 vtop->r = r;
317 vtop->r2 = VT_CONST;
318 vtop->c = *vc;
321 /* push constant of type "type" with useless value */
322 void vpush(CType *type)
324 CValue cval;
325 vsetc(type, VT_CONST, &cval);
328 /* push integer constant */
329 ST_FUNC void vpushi(int v)
331 CValue cval;
332 cval.i = v;
333 vsetc(&int_type, VT_CONST, &cval);
336 /* push a pointer sized constant */
337 static void vpushs(long long v)
339 CValue cval;
340 if (PTR_SIZE == 4)
341 cval.i = (int)v;
342 else
343 cval.ull = v;
344 vsetc(&size_type, VT_CONST, &cval);
347 /* push arbitrary 64bit constant */
348 void vpush64(int ty, unsigned long long v)
350 CValue cval;
351 CType ctype;
352 ctype.t = ty;
353 ctype.ref = NULL;
354 cval.ull = v;
355 vsetc(&ctype, VT_CONST, &cval);
358 /* push long long constant */
359 static inline void vpushll(long long v)
361 vpush64(VT_LLONG, v);
364 /* Return a static symbol pointing to a section */
365 ST_FUNC Sym *get_sym_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
367 int v;
368 Sym *sym;
370 v = anon_sym++;
371 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
372 sym->type.ref = type->ref;
373 sym->r = VT_CONST | VT_SYM;
374 put_extern_sym(sym, sec, offset, size);
375 return sym;
378 /* push a reference to a section offset by adding a dummy symbol */
379 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
381 CValue cval;
383 cval.ul = 0;
384 vsetc(type, VT_CONST | VT_SYM, &cval);
385 vtop->sym = get_sym_ref(type, sec, offset, size);
388 /* define a new external reference to a symbol 'v' of type 'u' */
389 ST_FUNC Sym *external_global_sym(int v, CType *type, int r)
391 Sym *s;
393 s = sym_find(v);
394 if (!s) {
395 /* push forward reference */
396 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
397 s->type.ref = type->ref;
398 s->r = r | VT_CONST | VT_SYM;
400 return s;
403 /* define a new external reference to a symbol 'v' with alternate asm
404 name 'asm_label' of type 'u'. 'asm_label' is equal to NULL if there
405 is no alternate name (most cases) */
406 static Sym *external_sym(int v, CType *type, int r, char *asm_label)
408 Sym *s;
410 s = sym_find(v);
411 if (!s) {
412 /* push forward reference */
413 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
414 s->asm_label = asm_label;
415 s->type.t |= VT_EXTERN;
416 } else if (s->type.ref == func_old_type.ref) {
417 s->type.ref = type->ref;
418 s->r = r | VT_CONST | VT_SYM;
419 s->type.t |= VT_EXTERN;
420 } else if (!is_compatible_types(&s->type, type)) {
421 tcc_error("incompatible types for redefinition of '%s'",
422 get_tok_str(v, NULL));
424 return s;
427 /* push a reference to global symbol v */
428 ST_FUNC void vpush_global_sym(CType *type, int v)
430 Sym *sym;
431 CValue cval;
433 sym = external_global_sym(v, type, 0);
434 cval.ul = 0;
435 vsetc(type, VT_CONST | VT_SYM, &cval);
436 vtop->sym = sym;
439 ST_FUNC void vset(CType *type, int r, int v)
441 CValue cval;
443 cval.i = v;
444 vsetc(type, r, &cval);
447 static void vseti(int r, int v)
449 CType type;
450 type.t = VT_INT;
451 type.ref = 0;
452 vset(&type, r, v);
455 ST_FUNC void vswap(void)
457 SValue tmp;
458 /* cannot let cpu flags if other instruction are generated. Also
459 avoid leaving VT_JMP anywhere except on the top of the stack
460 because it would complicate the code generator. */
461 if (vtop >= vstack) {
462 int v = vtop->r & VT_VALMASK;
463 if (v == VT_CMP || (v & ~1) == VT_JMP)
464 gv(RC_INT);
466 tmp = vtop[0];
467 vtop[0] = vtop[-1];
468 vtop[-1] = tmp;
470 /* XXX: +2% overall speed possible with optimized memswap
472 * memswap(&vtop[0], &vtop[1], sizeof *vtop);
476 ST_FUNC void vpushv(SValue *v)
478 if (vtop >= vstack + (VSTACK_SIZE - 1))
479 tcc_error("memory full");
480 vtop++;
481 *vtop = *v;
484 static void vdup(void)
486 vpushv(vtop);
489 /* save r to the memory stack, and mark it as being free */
490 ST_FUNC void save_reg(int r)
492 int l, saved, size, align;
493 SValue *p, sv;
494 CType *type;
496 /* modify all stack values */
497 saved = 0;
498 l = 0;
499 for(p=vstack;p<=vtop;p++) {
500 if ((p->r & VT_VALMASK) == r ||
501 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
502 /* must save value on stack if not already done */
503 if (!saved) {
504 /* NOTE: must reload 'r' because r might be equal to r2 */
505 r = p->r & VT_VALMASK;
506 /* store register in the stack */
507 type = &p->type;
508 if ((p->r & VT_LVAL) ||
509 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
510 #ifdef TCC_TARGET_X86_64
511 type = &char_pointer_type;
512 #else
513 type = &int_type;
514 #endif
515 size = type_size(type, &align);
516 loc = (loc - size) & -align;
517 sv.type.t = type->t;
518 sv.r = VT_LOCAL | VT_LVAL;
519 sv.c.ul = loc;
520 store(r, &sv);
521 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
522 /* x86 specific: need to pop fp register ST0 if saved */
523 if (r == TREG_ST0) {
524 o(0xd8dd); /* fstp %st(0) */
526 #endif
527 #ifndef TCC_TARGET_X86_64
528 /* special long long case */
529 if ((type->t & VT_BTYPE) == VT_LLONG) {
530 sv.c.ul += 4;
531 store(p->r2, &sv);
533 #endif
534 l = loc;
535 saved = 1;
537 /* mark that stack entry as being saved on the stack */
538 if (p->r & VT_LVAL) {
539 /* also clear the bounded flag because the
540 relocation address of the function was stored in
541 p->c.ul */
542 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
543 } else {
544 p->r = lvalue_type(p->type.t) | VT_LOCAL;
546 p->r2 = VT_CONST;
547 p->c.ul = l;
552 #ifdef TCC_TARGET_ARM
553 /* find a register of class 'rc2' with at most one reference on stack.
554 * If none, call get_reg(rc) */
555 ST_FUNC int get_reg_ex(int rc, int rc2)
557 int r;
558 SValue *p;
560 for(r=0;r<NB_REGS;r++) {
561 if (reg_classes[r] & rc2) {
562 int n;
563 n=0;
564 for(p = vstack; p <= vtop; p++) {
565 if ((p->r & VT_VALMASK) == r ||
566 (p->r2 & VT_VALMASK) == r)
567 n++;
569 if (n <= 1)
570 return r;
573 return get_reg(rc);
575 #endif
577 /* find a free register of class 'rc'. If none, save one register */
578 ST_FUNC int get_reg(int rc)
580 int r;
581 SValue *p;
583 /* find a free register */
584 for(r=0;r<NB_REGS;r++) {
585 if (reg_classes[r] & rc) {
586 for(p=vstack;p<=vtop;p++) {
587 if ((p->r & VT_VALMASK) == r ||
588 (p->r2 & VT_VALMASK) == r)
589 goto notfound;
591 return r;
593 notfound: ;
596 /* no register left : free the first one on the stack (VERY
597 IMPORTANT to start from the bottom to ensure that we don't
598 spill registers used in gen_opi()) */
599 for(p=vstack;p<=vtop;p++) {
600 /* look at second register (if long long) */
601 r = p->r2 & VT_VALMASK;
602 if (r < VT_CONST && (reg_classes[r] & rc))
603 goto save_found;
604 r = p->r & VT_VALMASK;
605 if (r < VT_CONST && (reg_classes[r] & rc)) {
606 save_found:
607 save_reg(r);
608 return r;
611 /* Should never comes here */
612 return -1;
615 /* save registers up to (vtop - n) stack entry */
616 ST_FUNC void save_regs(int n)
618 int r;
619 SValue *p, *p1;
620 p1 = vtop - n;
621 for(p = vstack;p <= p1; p++) {
622 r = p->r & VT_VALMASK;
623 if (r < VT_CONST) {
624 save_reg(r);
629 /* move register 's' to 'r', and flush previous value of r to memory
630 if needed */
631 static void move_reg(int r, int s)
633 SValue sv;
635 if (r != s) {
636 save_reg(r);
637 sv.type.t = VT_INT;
638 sv.r = s;
639 sv.c.ul = 0;
640 load(r, &sv);
644 /* get address of vtop (vtop MUST BE an lvalue) */
645 static void gaddrof(void)
647 if (vtop->r & VT_REF)
648 gv(RC_INT);
649 vtop->r &= ~VT_LVAL;
650 /* tricky: if saved lvalue, then we can go back to lvalue */
651 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
652 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
657 #ifdef CONFIG_TCC_BCHECK
658 /* generate lvalue bound code */
659 static void gbound(void)
661 int lval_type;
662 CType type1;
664 vtop->r &= ~VT_MUSTBOUND;
665 /* if lvalue, then use checking code before dereferencing */
666 if (vtop->r & VT_LVAL) {
667 /* if not VT_BOUNDED value, then make one */
668 if (!(vtop->r & VT_BOUNDED)) {
669 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
670 /* must save type because we must set it to int to get pointer */
671 type1 = vtop->type;
672 vtop->type.t = VT_INT;
673 gaddrof();
674 vpushi(0);
675 gen_bounded_ptr_add();
676 vtop->r |= lval_type;
677 vtop->type = type1;
679 /* then check for dereferencing */
680 gen_bounded_ptr_deref();
683 #endif
685 /* store vtop a register belonging to class 'rc'. lvalues are
686 converted to values. Cannot be used if cannot be converted to
687 register value (such as structures). */
688 ST_FUNC int gv(int rc)
690 int r, bit_pos, bit_size, size, align, i;
691 #ifndef TCC_TARGET_X86_64
692 int rc2;
693 #endif
695 /* NOTE: get_reg can modify vstack[] */
696 if (vtop->type.t & VT_BITFIELD) {
697 CType type;
698 int bits = 32;
699 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
700 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
701 /* remove bit field info to avoid loops */
702 vtop->type.t &= ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
703 /* cast to int to propagate signedness in following ops */
704 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
705 type.t = VT_LLONG;
706 bits = 64;
707 } else
708 type.t = VT_INT;
709 if((vtop->type.t & VT_UNSIGNED) ||
710 (vtop->type.t & VT_BTYPE) == VT_BOOL)
711 type.t |= VT_UNSIGNED;
712 gen_cast(&type);
713 /* generate shifts */
714 vpushi(bits - (bit_pos + bit_size));
715 gen_op(TOK_SHL);
716 vpushi(bits - bit_size);
717 /* NOTE: transformed to SHR if unsigned */
718 gen_op(TOK_SAR);
719 r = gv(rc);
720 } else {
721 if (is_float(vtop->type.t) &&
722 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
723 Sym *sym;
724 int *ptr;
725 unsigned long offset;
726 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
727 CValue check;
728 #endif
730 /* XXX: unify with initializers handling ? */
731 /* CPUs usually cannot use float constants, so we store them
732 generically in data segment */
733 size = type_size(&vtop->type, &align);
734 offset = (data_section->data_offset + align - 1) & -align;
735 data_section->data_offset = offset;
736 /* XXX: not portable yet */
737 #if defined(__i386__) || defined(__x86_64__)
738 /* Zero pad x87 tenbyte long doubles */
739 if (size == LDOUBLE_SIZE) {
740 vtop->c.tab[2] &= 0xffff;
741 #if LDOUBLE_SIZE == 16
742 vtop->c.tab[3] = 0;
743 #endif
745 #endif
746 ptr = section_ptr_add(data_section, size);
747 size = size >> 2;
748 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
749 check.d = 1;
750 if(check.tab[0])
751 for(i=0;i<size;i++)
752 ptr[i] = vtop->c.tab[size-1-i];
753 else
754 #endif
755 for(i=0;i<size;i++)
756 ptr[i] = vtop->c.tab[i];
757 sym = get_sym_ref(&vtop->type, data_section, offset, size << 2);
758 vtop->r |= VT_LVAL | VT_SYM;
759 vtop->sym = sym;
760 vtop->c.ul = 0;
762 #ifdef CONFIG_TCC_BCHECK
763 if (vtop->r & VT_MUSTBOUND)
764 gbound();
765 #endif
767 r = vtop->r & VT_VALMASK;
768 #ifndef TCC_TARGET_X86_64
769 rc2 = RC_INT;
770 if (rc == RC_IRET)
771 rc2 = RC_LRET;
772 #endif
773 /* need to reload if:
774 - constant
775 - lvalue (need to dereference pointer)
776 - already a register, but not in the right class */
777 if (r >= VT_CONST
778 || (vtop->r & VT_LVAL)
779 || !(reg_classes[r] & rc)
780 #ifndef TCC_TARGET_X86_64
781 || ((vtop->type.t & VT_BTYPE) == VT_LLONG && !(reg_classes[vtop->r2] & rc2))
782 #endif
785 r = get_reg(rc);
786 #ifndef TCC_TARGET_X86_64
787 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
788 int r2;
789 unsigned long long ll;
790 /* two register type load : expand to two words
791 temporarily */
792 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
793 /* load constant */
794 ll = vtop->c.ull;
795 vtop->c.ui = ll; /* first word */
796 load(r, vtop);
797 vtop->r = r; /* save register value */
798 vpushi(ll >> 32); /* second word */
799 } else if (r >= VT_CONST || /* XXX: test to VT_CONST incorrect ? */
800 (vtop->r & VT_LVAL)) {
801 /* We do not want to modifier the long long
802 pointer here, so the safest (and less
803 efficient) is to save all the other registers
804 in the stack. XXX: totally inefficient. */
805 save_regs(1);
806 /* load from memory */
807 load(r, vtop);
808 vdup();
809 vtop[-1].r = r; /* save register value */
810 /* increment pointer to get second word */
811 vtop->type.t = VT_INT;
812 gaddrof();
813 vpushi(4);
814 gen_op('+');
815 vtop->r |= VT_LVAL;
816 } else {
817 /* move registers */
818 load(r, vtop);
819 vdup();
820 vtop[-1].r = r; /* save register value */
821 vtop->r = vtop[-1].r2;
823 /* Allocate second register. Here we rely on the fact that
824 get_reg() tries first to free r2 of an SValue. */
825 r2 = get_reg(rc2);
826 load(r2, vtop);
827 vpop();
828 /* write second register */
829 vtop->r2 = r2;
830 } else
831 #endif
832 if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
833 int t1, t;
834 /* lvalue of scalar type : need to use lvalue type
835 because of possible cast */
836 t = vtop->type.t;
837 t1 = t;
838 /* compute memory access type */
839 if (vtop->r & VT_LVAL_BYTE)
840 t = VT_BYTE;
841 else if (vtop->r & VT_LVAL_SHORT)
842 t = VT_SHORT;
843 if (vtop->r & VT_LVAL_UNSIGNED)
844 t |= VT_UNSIGNED;
845 vtop->type.t = t;
846 load(r, vtop);
847 /* restore wanted type */
848 vtop->type.t = t1;
849 } else {
850 /* one register type load */
851 load(r, vtop);
854 vtop->r = r;
855 #ifdef TCC_TARGET_C67
856 /* uses register pairs for doubles */
857 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
858 vtop->r2 = r+1;
859 #endif
861 return r;
864 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
865 ST_FUNC void gv2(int rc1, int rc2)
867 int v;
869 /* generate more generic register first. But VT_JMP or VT_CMP
870 values must be generated first in all cases to avoid possible
871 reload errors */
872 v = vtop[0].r & VT_VALMASK;
873 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
874 vswap();
875 gv(rc1);
876 vswap();
877 gv(rc2);
878 /* test if reload is needed for first register */
879 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
880 vswap();
881 gv(rc1);
882 vswap();
884 } else {
885 gv(rc2);
886 vswap();
887 gv(rc1);
888 vswap();
889 /* test if reload is needed for first register */
890 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
891 gv(rc2);
896 /* wrapper around RC_FRET to return a register by type */
897 static int rc_fret(int t)
899 #ifdef TCC_TARGET_X86_64
900 if (t == VT_LDOUBLE) {
901 return RC_ST0;
903 #endif
904 return RC_FRET;
907 /* wrapper around REG_FRET to return a register by type */
908 static int reg_fret(int t)
910 #ifdef TCC_TARGET_X86_64
911 if (t == VT_LDOUBLE) {
912 return TREG_ST0;
914 #endif
915 return REG_FRET;
918 /* expand long long on stack in two int registers */
919 static void lexpand(void)
921 int u;
923 u = vtop->type.t & VT_UNSIGNED;
924 gv(RC_INT);
925 vdup();
926 vtop[0].r = vtop[-1].r2;
927 vtop[0].r2 = VT_CONST;
928 vtop[-1].r2 = VT_CONST;
929 vtop[0].type.t = VT_INT | u;
930 vtop[-1].type.t = VT_INT | u;
933 #ifdef TCC_TARGET_ARM
934 /* expand long long on stack */
935 ST_FUNC void lexpand_nr(void)
937 int u,v;
939 u = vtop->type.t & VT_UNSIGNED;
940 vdup();
941 vtop->r2 = VT_CONST;
942 vtop->type.t = VT_INT | u;
943 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
944 if (v == VT_CONST) {
945 vtop[-1].c.ui = vtop->c.ull;
946 vtop->c.ui = vtop->c.ull >> 32;
947 vtop->r = VT_CONST;
948 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
949 vtop->c.ui += 4;
950 vtop->r = vtop[-1].r;
951 } else if (v > VT_CONST) {
952 vtop--;
953 lexpand();
954 } else
955 vtop->r = vtop[-1].r2;
956 vtop[-1].r2 = VT_CONST;
957 vtop[-1].type.t = VT_INT | u;
959 #endif
961 /* build a long long from two ints */
962 static void lbuild(int t)
964 gv2(RC_INT, RC_INT);
965 vtop[-1].r2 = vtop[0].r;
966 vtop[-1].type.t = t;
967 vpop();
970 /* rotate n first stack elements to the bottom
971 I1 ... In -> I2 ... In I1 [top is right]
973 ST_FUNC void vrotb(int n)
975 int i;
976 SValue tmp;
978 tmp = vtop[-n + 1];
979 for(i=-n+1;i!=0;i++)
980 vtop[i] = vtop[i+1];
981 vtop[0] = tmp;
984 /* rotate the n elements before entry e towards the top
985 I1 ... In ... -> In I1 ... I(n-1) ... [top is right]
987 ST_FUNC void vrote(SValue *e, int n)
989 int i;
990 SValue tmp;
992 tmp = *e;
993 for(i = 0;i < n - 1; i++)
994 e[-i] = e[-i - 1];
995 e[-n + 1] = tmp;
998 /* rotate n first stack elements to the top
999 I1 ... In -> In I1 ... I(n-1) [top is right]
1001 ST_FUNC void vrott(int n)
1003 vrote(vtop, n);
1006 /* pop stack value */
1007 ST_FUNC void vpop(void)
1009 int v;
1010 v = vtop->r & VT_VALMASK;
1011 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1012 /* for x86, we need to pop the FP stack */
1013 if (v == TREG_ST0 && !nocode_wanted) {
1014 o(0xd8dd); /* fstp %st(0) */
1015 } else
1016 #endif
1017 if (v == VT_JMP || v == VT_JMPI) {
1018 /* need to put correct jump if && or || without test */
1019 gsym(vtop->c.ul);
1021 vtop--;
1024 /* convert stack entry to register and duplicate its value in another
1025 register */
1026 static void gv_dup(void)
1028 int rc, t, r, r1;
1029 SValue sv;
1031 t = vtop->type.t;
1032 if ((t & VT_BTYPE) == VT_LLONG) {
1033 lexpand();
1034 gv_dup();
1035 vswap();
1036 vrotb(3);
1037 gv_dup();
1038 vrotb(4);
1039 /* stack: H L L1 H1 */
1040 lbuild(t);
1041 vrotb(3);
1042 vrotb(3);
1043 vswap();
1044 lbuild(t);
1045 vswap();
1046 } else {
1047 /* duplicate value */
1048 rc = RC_INT;
1049 sv.type.t = VT_INT;
1050 if (is_float(t)) {
1051 rc = RC_FLOAT;
1052 #ifdef TCC_TARGET_X86_64
1053 if ((t & VT_BTYPE) == VT_LDOUBLE) {
1054 rc = RC_ST0;
1056 #endif
1057 sv.type.t = t;
1059 r = gv(rc);
1060 r1 = get_reg(rc);
1061 sv.r = r;
1062 sv.c.ul = 0;
1063 load(r1, &sv); /* move r to r1 */
1064 vdup();
1065 /* duplicates value */
1066 if (r != r1)
1067 vtop->r = r1;
1071 #ifndef TCC_TARGET_X86_64
1072 /* generate CPU independent (unsigned) long long operations */
1073 static void gen_opl(int op)
1075 int t, a, b, op1, c, i;
1076 int func;
1077 unsigned short reg_iret = REG_IRET;
1078 unsigned short reg_lret = REG_LRET;
1079 SValue tmp;
1081 switch(op) {
1082 case '/':
1083 case TOK_PDIV:
1084 func = TOK___divdi3;
1085 goto gen_func;
1086 case TOK_UDIV:
1087 func = TOK___udivdi3;
1088 goto gen_func;
1089 case '%':
1090 func = TOK___moddi3;
1091 goto gen_mod_func;
1092 case TOK_UMOD:
1093 func = TOK___umoddi3;
1094 gen_mod_func:
1095 #ifdef TCC_ARM_EABI
1096 reg_iret = TREG_R2;
1097 reg_lret = TREG_R3;
1098 #endif
1099 gen_func:
1100 /* call generic long long function */
1101 vpush_global_sym(&func_old_type, func);
1102 vrott(3);
1103 gfunc_call(2);
1104 vpushi(0);
1105 vtop->r = reg_iret;
1106 vtop->r2 = reg_lret;
1107 break;
1108 case '^':
1109 case '&':
1110 case '|':
1111 case '*':
1112 case '+':
1113 case '-':
1114 t = vtop->type.t;
1115 vswap();
1116 lexpand();
1117 vrotb(3);
1118 lexpand();
1119 /* stack: L1 H1 L2 H2 */
1120 tmp = vtop[0];
1121 vtop[0] = vtop[-3];
1122 vtop[-3] = tmp;
1123 tmp = vtop[-2];
1124 vtop[-2] = vtop[-3];
1125 vtop[-3] = tmp;
1126 vswap();
1127 /* stack: H1 H2 L1 L2 */
1128 if (op == '*') {
1129 vpushv(vtop - 1);
1130 vpushv(vtop - 1);
1131 gen_op(TOK_UMULL);
1132 lexpand();
1133 /* stack: H1 H2 L1 L2 ML MH */
1134 for(i=0;i<4;i++)
1135 vrotb(6);
1136 /* stack: ML MH H1 H2 L1 L2 */
1137 tmp = vtop[0];
1138 vtop[0] = vtop[-2];
1139 vtop[-2] = tmp;
1140 /* stack: ML MH H1 L2 H2 L1 */
1141 gen_op('*');
1142 vrotb(3);
1143 vrotb(3);
1144 gen_op('*');
1145 /* stack: ML MH M1 M2 */
1146 gen_op('+');
1147 gen_op('+');
1148 } else if (op == '+' || op == '-') {
1149 /* XXX: add non carry method too (for MIPS or alpha) */
1150 if (op == '+')
1151 op1 = TOK_ADDC1;
1152 else
1153 op1 = TOK_SUBC1;
1154 gen_op(op1);
1155 /* stack: H1 H2 (L1 op L2) */
1156 vrotb(3);
1157 vrotb(3);
1158 gen_op(op1 + 1); /* TOK_xxxC2 */
1159 } else {
1160 gen_op(op);
1161 /* stack: H1 H2 (L1 op L2) */
1162 vrotb(3);
1163 vrotb(3);
1164 /* stack: (L1 op L2) H1 H2 */
1165 gen_op(op);
1166 /* stack: (L1 op L2) (H1 op H2) */
1168 /* stack: L H */
1169 lbuild(t);
1170 break;
1171 case TOK_SAR:
1172 case TOK_SHR:
1173 case TOK_SHL:
1174 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1175 t = vtop[-1].type.t;
1176 vswap();
1177 lexpand();
1178 vrotb(3);
1179 /* stack: L H shift */
1180 c = (int)vtop->c.i;
1181 /* constant: simpler */
1182 /* NOTE: all comments are for SHL. the other cases are
1183 done by swaping words */
1184 vpop();
1185 if (op != TOK_SHL)
1186 vswap();
1187 if (c >= 32) {
1188 /* stack: L H */
1189 vpop();
1190 if (c > 32) {
1191 vpushi(c - 32);
1192 gen_op(op);
1194 if (op != TOK_SAR) {
1195 vpushi(0);
1196 } else {
1197 gv_dup();
1198 vpushi(31);
1199 gen_op(TOK_SAR);
1201 vswap();
1202 } else {
1203 vswap();
1204 gv_dup();
1205 /* stack: H L L */
1206 vpushi(c);
1207 gen_op(op);
1208 vswap();
1209 vpushi(32 - c);
1210 if (op == TOK_SHL)
1211 gen_op(TOK_SHR);
1212 else
1213 gen_op(TOK_SHL);
1214 vrotb(3);
1215 /* stack: L L H */
1216 vpushi(c);
1217 if (op == TOK_SHL)
1218 gen_op(TOK_SHL);
1219 else
1220 gen_op(TOK_SHR);
1221 gen_op('|');
1223 if (op != TOK_SHL)
1224 vswap();
1225 lbuild(t);
1226 } else {
1227 /* XXX: should provide a faster fallback on x86 ? */
1228 switch(op) {
1229 case TOK_SAR:
1230 func = TOK___ashrdi3;
1231 goto gen_func;
1232 case TOK_SHR:
1233 func = TOK___lshrdi3;
1234 goto gen_func;
1235 case TOK_SHL:
1236 func = TOK___ashldi3;
1237 goto gen_func;
1240 break;
1241 default:
1242 /* compare operations */
1243 t = vtop->type.t;
1244 vswap();
1245 lexpand();
1246 vrotb(3);
1247 lexpand();
1248 /* stack: L1 H1 L2 H2 */
1249 tmp = vtop[-1];
1250 vtop[-1] = vtop[-2];
1251 vtop[-2] = tmp;
1252 /* stack: L1 L2 H1 H2 */
1253 /* compare high */
1254 op1 = op;
1255 /* when values are equal, we need to compare low words. since
1256 the jump is inverted, we invert the test too. */
1257 if (op1 == TOK_LT)
1258 op1 = TOK_LE;
1259 else if (op1 == TOK_GT)
1260 op1 = TOK_GE;
1261 else if (op1 == TOK_ULT)
1262 op1 = TOK_ULE;
1263 else if (op1 == TOK_UGT)
1264 op1 = TOK_UGE;
1265 a = 0;
1266 b = 0;
1267 gen_op(op1);
1268 if (op1 != TOK_NE) {
1269 a = gtst(1, 0);
1271 if (op != TOK_EQ) {
1272 /* generate non equal test */
1273 /* XXX: NOT PORTABLE yet */
1274 if (a == 0) {
1275 b = gtst(0, 0);
1276 } else {
1277 #if defined(TCC_TARGET_I386)
1278 b = psym(0x850f, 0);
1279 #elif defined(TCC_TARGET_ARM)
1280 b = ind;
1281 o(0x1A000000 | encbranch(ind, 0, 1));
1282 #elif defined(TCC_TARGET_C67)
1283 tcc_error("not implemented");
1284 #else
1285 #error not supported
1286 #endif
1289 /* compare low. Always unsigned */
1290 op1 = op;
1291 if (op1 == TOK_LT)
1292 op1 = TOK_ULT;
1293 else if (op1 == TOK_LE)
1294 op1 = TOK_ULE;
1295 else if (op1 == TOK_GT)
1296 op1 = TOK_UGT;
1297 else if (op1 == TOK_GE)
1298 op1 = TOK_UGE;
1299 gen_op(op1);
1300 a = gtst(1, a);
1301 gsym(b);
1302 vseti(VT_JMPI, a);
1303 break;
1306 #endif
1308 /* handle integer constant optimizations and various machine
1309 independent opt */
1310 static void gen_opic(int op)
1312 int c1, c2, t1, t2, n;
1313 SValue *v1, *v2;
1314 long long l1, l2;
1315 typedef unsigned long long U;
1317 v1 = vtop - 1;
1318 v2 = vtop;
1319 t1 = v1->type.t & VT_BTYPE;
1320 t2 = v2->type.t & VT_BTYPE;
1322 if (t1 == VT_LLONG)
1323 l1 = v1->c.ll;
1324 else if (v1->type.t & VT_UNSIGNED)
1325 l1 = v1->c.ui;
1326 else
1327 l1 = v1->c.i;
1329 if (t2 == VT_LLONG)
1330 l2 = v2->c.ll;
1331 else if (v2->type.t & VT_UNSIGNED)
1332 l2 = v2->c.ui;
1333 else
1334 l2 = v2->c.i;
1336 /* currently, we cannot do computations with forward symbols */
1337 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1338 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1339 if (c1 && c2) {
1340 switch(op) {
1341 case '+': l1 += l2; break;
1342 case '-': l1 -= l2; break;
1343 case '&': l1 &= l2; break;
1344 case '^': l1 ^= l2; break;
1345 case '|': l1 |= l2; break;
1346 case '*': l1 *= l2; break;
1348 case TOK_PDIV:
1349 case '/':
1350 case '%':
1351 case TOK_UDIV:
1352 case TOK_UMOD:
1353 /* if division by zero, generate explicit division */
1354 if (l2 == 0) {
1355 if (const_wanted)
1356 tcc_error("division by zero in constant");
1357 goto general_case;
1359 switch(op) {
1360 default: l1 /= l2; break;
1361 case '%': l1 %= l2; break;
1362 case TOK_UDIV: l1 = (U)l1 / l2; break;
1363 case TOK_UMOD: l1 = (U)l1 % l2; break;
1365 break;
1366 case TOK_SHL: l1 <<= l2; break;
1367 case TOK_SHR: l1 = (U)l1 >> l2; break;
1368 case TOK_SAR: l1 >>= l2; break;
1369 /* tests */
1370 case TOK_ULT: l1 = (U)l1 < (U)l2; break;
1371 case TOK_UGE: l1 = (U)l1 >= (U)l2; break;
1372 case TOK_EQ: l1 = l1 == l2; break;
1373 case TOK_NE: l1 = l1 != l2; break;
1374 case TOK_ULE: l1 = (U)l1 <= (U)l2; break;
1375 case TOK_UGT: l1 = (U)l1 > (U)l2; break;
1376 case TOK_LT: l1 = l1 < l2; break;
1377 case TOK_GE: l1 = l1 >= l2; break;
1378 case TOK_LE: l1 = l1 <= l2; break;
1379 case TOK_GT: l1 = l1 > l2; break;
1380 /* logical */
1381 case TOK_LAND: l1 = l1 && l2; break;
1382 case TOK_LOR: l1 = l1 || l2; break;
1383 default:
1384 goto general_case;
1386 v1->c.ll = l1;
1387 vtop--;
1388 } else {
1389 /* if commutative ops, put c2 as constant */
1390 if (c1 && (op == '+' || op == '&' || op == '^' ||
1391 op == '|' || op == '*')) {
1392 vswap();
1393 c2 = c1; //c = c1, c1 = c2, c2 = c;
1394 l2 = l1; //l = l1, l1 = l2, l2 = l;
1396 /* Filter out NOP operations like x*1, x-0, x&-1... */
1397 if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
1398 op == TOK_PDIV) &&
1399 l2 == 1) ||
1400 ((op == '+' || op == '-' || op == '|' || op == '^' ||
1401 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
1402 l2 == 0) ||
1403 (op == '&' &&
1404 l2 == -1))) {
1405 /* nothing to do */
1406 vtop--;
1407 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
1408 /* try to use shifts instead of muls or divs */
1409 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
1410 n = -1;
1411 while (l2) {
1412 l2 >>= 1;
1413 n++;
1415 vtop->c.ll = n;
1416 if (op == '*')
1417 op = TOK_SHL;
1418 else if (op == TOK_PDIV)
1419 op = TOK_SAR;
1420 else
1421 op = TOK_SHR;
1423 goto general_case;
1424 } else if (c2 && (op == '+' || op == '-') &&
1425 (((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM))
1426 || (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
1427 /* symbol + constant case */
1428 if (op == '-')
1429 l2 = -l2;
1430 vtop--;
1431 vtop->c.ll += l2;
1432 } else {
1433 general_case:
1434 if (!nocode_wanted) {
1435 /* call low level op generator */
1436 if (t1 == VT_LLONG || t2 == VT_LLONG)
1437 gen_opl(op);
1438 else
1439 gen_opi(op);
1440 } else {
1441 vtop--;
1447 /* generate a floating point operation with constant propagation */
1448 static void gen_opif(int op)
1450 int c1, c2;
1451 SValue *v1, *v2;
1452 long double f1, f2;
1454 v1 = vtop - 1;
1455 v2 = vtop;
1456 /* currently, we cannot do computations with forward symbols */
1457 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1458 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1459 if (c1 && c2) {
1460 if (v1->type.t == VT_FLOAT) {
1461 f1 = v1->c.f;
1462 f2 = v2->c.f;
1463 } else if (v1->type.t == VT_DOUBLE) {
1464 f1 = v1->c.d;
1465 f2 = v2->c.d;
1466 } else {
1467 f1 = v1->c.ld;
1468 f2 = v2->c.ld;
1471 /* NOTE: we only do constant propagation if finite number (not
1472 NaN or infinity) (ANSI spec) */
1473 if (!ieee_finite(f1) || !ieee_finite(f2))
1474 goto general_case;
1476 switch(op) {
1477 case '+': f1 += f2; break;
1478 case '-': f1 -= f2; break;
1479 case '*': f1 *= f2; break;
1480 case '/':
1481 if (f2 == 0.0) {
1482 if (const_wanted)
1483 tcc_error("division by zero in constant");
1484 goto general_case;
1486 f1 /= f2;
1487 break;
1488 /* XXX: also handles tests ? */
1489 default:
1490 goto general_case;
1492 /* XXX: overflow test ? */
1493 if (v1->type.t == VT_FLOAT) {
1494 v1->c.f = f1;
1495 } else if (v1->type.t == VT_DOUBLE) {
1496 v1->c.d = f1;
1497 } else {
1498 v1->c.ld = f1;
1500 vtop--;
1501 } else {
1502 general_case:
1503 if (!nocode_wanted) {
1504 gen_opf(op);
1505 } else {
1506 vtop--;
1511 static int pointed_size(CType *type)
1513 int align;
1514 return type_size(pointed_type(type), &align);
1517 static void vla_runtime_pointed_size(CType *type)
1519 int align;
1520 vla_runtime_type_size(pointed_type(type), &align);
1523 static inline int is_null_pointer(SValue *p)
1525 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
1526 return 0;
1527 return ((p->type.t & VT_BTYPE) == VT_INT && p->c.i == 0) ||
1528 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.ll == 0) ||
1529 ((p->type.t & VT_BTYPE) == VT_PTR && p->c.ptr == 0);
1532 static inline int is_integer_btype(int bt)
1534 return (bt == VT_BYTE || bt == VT_SHORT ||
1535 bt == VT_INT || bt == VT_LLONG);
1538 /* check types for comparison or substraction of pointers */
1539 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
1541 CType *type1, *type2, tmp_type1, tmp_type2;
1542 int bt1, bt2;
1544 /* null pointers are accepted for all comparisons as gcc */
1545 if (is_null_pointer(p1) || is_null_pointer(p2))
1546 return;
1547 type1 = &p1->type;
1548 type2 = &p2->type;
1549 bt1 = type1->t & VT_BTYPE;
1550 bt2 = type2->t & VT_BTYPE;
1551 /* accept comparison between pointer and integer with a warning */
1552 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
1553 if (op != TOK_LOR && op != TOK_LAND )
1554 tcc_warning("comparison between pointer and integer");
1555 return;
1558 /* both must be pointers or implicit function pointers */
1559 if (bt1 == VT_PTR) {
1560 type1 = pointed_type(type1);
1561 } else if (bt1 != VT_FUNC)
1562 goto invalid_operands;
1564 if (bt2 == VT_PTR) {
1565 type2 = pointed_type(type2);
1566 } else if (bt2 != VT_FUNC) {
1567 invalid_operands:
1568 tcc_error("invalid operands to binary %s", get_tok_str(op, NULL));
1570 if ((type1->t & VT_BTYPE) == VT_VOID ||
1571 (type2->t & VT_BTYPE) == VT_VOID)
1572 return;
1573 tmp_type1 = *type1;
1574 tmp_type2 = *type2;
1575 tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1576 tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1577 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
1578 /* gcc-like error if '-' is used */
1579 if (op == '-')
1580 goto invalid_operands;
1581 else
1582 tcc_warning("comparison of distinct pointer types lacks a cast");
1586 /* generic gen_op: handles types problems */
1587 ST_FUNC void gen_op(int op)
1589 int u, t1, t2, bt1, bt2, t;
1590 CType type1;
1592 t1 = vtop[-1].type.t;
1593 t2 = vtop[0].type.t;
1594 bt1 = t1 & VT_BTYPE;
1595 bt2 = t2 & VT_BTYPE;
1597 if (bt1 == VT_PTR || bt2 == VT_PTR) {
1598 /* at least one operand is a pointer */
1599 /* relationnal op: must be both pointers */
1600 if (op >= TOK_ULT && op <= TOK_LOR) {
1601 check_comparison_pointer_types(vtop - 1, vtop, op);
1602 /* pointers are handled are unsigned */
1603 #ifdef TCC_TARGET_X86_64
1604 t = VT_LLONG | VT_UNSIGNED;
1605 #else
1606 t = VT_INT | VT_UNSIGNED;
1607 #endif
1608 goto std_op;
1610 /* if both pointers, then it must be the '-' op */
1611 if (bt1 == VT_PTR && bt2 == VT_PTR) {
1612 if (op != '-')
1613 tcc_error("cannot use pointers here");
1614 check_comparison_pointer_types(vtop - 1, vtop, op);
1615 /* XXX: check that types are compatible */
1616 if (vtop[-1].type.t & VT_VLA) {
1617 vla_runtime_pointed_size(&vtop[-1].type);
1618 } else {
1619 vpushi(pointed_size(&vtop[-1].type));
1621 vrott(3);
1622 gen_opic(op);
1623 /* set to integer type */
1624 #ifdef TCC_TARGET_X86_64
1625 vtop->type.t = VT_LLONG;
1626 #else
1627 vtop->type.t = VT_INT;
1628 #endif
1629 vswap();
1630 gen_op(TOK_PDIV);
1631 } else {
1632 /* exactly one pointer : must be '+' or '-'. */
1633 if (op != '-' && op != '+')
1634 tcc_error("cannot use pointers here");
1635 /* Put pointer as first operand */
1636 if (bt2 == VT_PTR) {
1637 vswap();
1638 swap(&t1, &t2);
1640 type1 = vtop[-1].type;
1641 type1.t &= ~VT_ARRAY;
1642 if (vtop[-1].type.t & VT_VLA)
1643 vla_runtime_pointed_size(&vtop[-1].type);
1644 else {
1645 u = pointed_size(&vtop[-1].type);
1646 if (u < 0)
1647 tcc_error("unknown array element size");
1648 #ifdef TCC_TARGET_X86_64
1649 vpushll(u);
1650 #else
1651 /* XXX: cast to int ? (long long case) */
1652 vpushi(u);
1653 #endif
1655 gen_op('*');
1656 #ifdef CONFIG_TCC_BCHECK
1657 /* if evaluating constant expression, no code should be
1658 generated, so no bound check */
1659 if (tcc_state->do_bounds_check && !const_wanted) {
1660 /* if bounded pointers, we generate a special code to
1661 test bounds */
1662 if (op == '-') {
1663 vpushi(0);
1664 vswap();
1665 gen_op('-');
1667 gen_bounded_ptr_add();
1668 } else
1669 #endif
1671 gen_opic(op);
1673 /* put again type if gen_opic() swaped operands */
1674 vtop->type = type1;
1676 } else if (is_float(bt1) || is_float(bt2)) {
1677 /* compute bigger type and do implicit casts */
1678 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
1679 t = VT_LDOUBLE;
1680 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
1681 t = VT_DOUBLE;
1682 } else {
1683 t = VT_FLOAT;
1685 /* floats can only be used for a few operations */
1686 if (op != '+' && op != '-' && op != '*' && op != '/' &&
1687 (op < TOK_ULT || op > TOK_GT))
1688 tcc_error("invalid operands for binary operation");
1689 goto std_op;
1690 } else if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL) {
1691 t = bt1 == VT_LLONG ? VT_LLONG : VT_INT;
1692 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (t | VT_UNSIGNED))
1693 t |= VT_UNSIGNED;
1694 goto std_op;
1695 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
1696 /* cast to biggest op */
1697 t = VT_LLONG;
1698 /* convert to unsigned if it does not fit in a long long */
1699 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
1700 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
1701 t |= VT_UNSIGNED;
1702 goto std_op;
1703 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
1704 tcc_error("comparison of struct");
1705 } else {
1706 /* integer operations */
1707 t = VT_INT;
1708 /* convert to unsigned if it does not fit in an integer */
1709 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
1710 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
1711 t |= VT_UNSIGNED;
1712 std_op:
1713 /* XXX: currently, some unsigned operations are explicit, so
1714 we modify them here */
1715 if (t & VT_UNSIGNED) {
1716 if (op == TOK_SAR)
1717 op = TOK_SHR;
1718 else if (op == '/')
1719 op = TOK_UDIV;
1720 else if (op == '%')
1721 op = TOK_UMOD;
1722 else if (op == TOK_LT)
1723 op = TOK_ULT;
1724 else if (op == TOK_GT)
1725 op = TOK_UGT;
1726 else if (op == TOK_LE)
1727 op = TOK_ULE;
1728 else if (op == TOK_GE)
1729 op = TOK_UGE;
1731 vswap();
1732 type1.t = t;
1733 gen_cast(&type1);
1734 vswap();
1735 /* special case for shifts and long long: we keep the shift as
1736 an integer */
1737 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
1738 type1.t = VT_INT;
1739 gen_cast(&type1);
1740 if (is_float(t))
1741 gen_opif(op);
1742 else
1743 gen_opic(op);
1744 if (op >= TOK_ULT && op <= TOK_GT) {
1745 /* relationnal op: the result is an int */
1746 vtop->type.t = VT_INT;
1747 } else {
1748 vtop->type.t = t;
1753 #ifndef TCC_TARGET_ARM
1754 /* generic itof for unsigned long long case */
1755 static void gen_cvt_itof1(int t)
1757 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
1758 (VT_LLONG | VT_UNSIGNED)) {
1760 if (t == VT_FLOAT)
1761 vpush_global_sym(&func_old_type, TOK___floatundisf);
1762 #if LDOUBLE_SIZE != 8
1763 else if (t == VT_LDOUBLE)
1764 vpush_global_sym(&func_old_type, TOK___floatundixf);
1765 #endif
1766 else
1767 vpush_global_sym(&func_old_type, TOK___floatundidf);
1768 vrott(2);
1769 gfunc_call(1);
1770 vpushi(0);
1771 vtop->r = reg_fret(t);
1772 } else {
1773 gen_cvt_itof(t);
1776 #endif
1778 /* generic ftoi for unsigned long long case */
1779 static void gen_cvt_ftoi1(int t)
1781 int st;
1783 if (t == (VT_LLONG | VT_UNSIGNED)) {
1784 /* not handled natively */
1785 st = vtop->type.t & VT_BTYPE;
1786 if (st == VT_FLOAT)
1787 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
1788 #if LDOUBLE_SIZE != 8
1789 else if (st == VT_LDOUBLE)
1790 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
1791 #endif
1792 else
1793 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
1794 vrott(2);
1795 gfunc_call(1);
1796 vpushi(0);
1797 vtop->r = REG_IRET;
1798 vtop->r2 = REG_LRET;
1799 } else {
1800 gen_cvt_ftoi(t);
1804 /* force char or short cast */
1805 static void force_charshort_cast(int t)
1807 int bits, dbt;
1808 dbt = t & VT_BTYPE;
1809 /* XXX: add optimization if lvalue : just change type and offset */
1810 if (dbt == VT_BYTE)
1811 bits = 8;
1812 else
1813 bits = 16;
1814 if (t & VT_UNSIGNED) {
1815 vpushi((1 << bits) - 1);
1816 gen_op('&');
1817 } else {
1818 bits = 32 - bits;
1819 vpushi(bits);
1820 gen_op(TOK_SHL);
1821 /* result must be signed or the SAR is converted to an SHL
1822 This was not the case when "t" was a signed short
1823 and the last value on the stack was an unsigned int */
1824 vtop->type.t &= ~VT_UNSIGNED;
1825 vpushi(bits);
1826 gen_op(TOK_SAR);
1830 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
1831 static void gen_cast(CType *type)
1833 int sbt, dbt, sf, df, c, p;
1835 /* special delayed cast for char/short */
1836 /* XXX: in some cases (multiple cascaded casts), it may still
1837 be incorrect */
1838 if (vtop->r & VT_MUSTCAST) {
1839 vtop->r &= ~VT_MUSTCAST;
1840 force_charshort_cast(vtop->type.t);
1843 /* bitfields first get cast to ints */
1844 if (vtop->type.t & VT_BITFIELD) {
1845 gv(RC_INT);
1848 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
1849 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
1851 if (sbt != dbt) {
1852 sf = is_float(sbt);
1853 df = is_float(dbt);
1854 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1855 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
1856 if (c) {
1857 /* constant case: we can do it now */
1858 /* XXX: in ISOC, cannot do it if error in convert */
1859 if (sbt == VT_FLOAT)
1860 vtop->c.ld = vtop->c.f;
1861 else if (sbt == VT_DOUBLE)
1862 vtop->c.ld = vtop->c.d;
1864 if (df) {
1865 if ((sbt & VT_BTYPE) == VT_LLONG) {
1866 if (sbt & VT_UNSIGNED)
1867 vtop->c.ld = vtop->c.ull;
1868 else
1869 vtop->c.ld = vtop->c.ll;
1870 } else if(!sf) {
1871 if (sbt & VT_UNSIGNED)
1872 vtop->c.ld = vtop->c.ui;
1873 else
1874 vtop->c.ld = vtop->c.i;
1877 if (dbt == VT_FLOAT)
1878 vtop->c.f = (float)vtop->c.ld;
1879 else if (dbt == VT_DOUBLE)
1880 vtop->c.d = (double)vtop->c.ld;
1881 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
1882 vtop->c.ull = (unsigned long long)vtop->c.ld;
1883 } else if (sf && dbt == VT_BOOL) {
1884 vtop->c.i = (vtop->c.ld != 0);
1885 } else {
1886 if(sf)
1887 vtop->c.ll = (long long)vtop->c.ld;
1888 else if (sbt == (VT_LLONG|VT_UNSIGNED))
1889 vtop->c.ll = vtop->c.ull;
1890 else if (sbt & VT_UNSIGNED)
1891 vtop->c.ll = vtop->c.ui;
1892 #ifdef TCC_TARGET_X86_64
1893 else if (sbt == VT_PTR)
1895 #endif
1896 else if (sbt != VT_LLONG)
1897 vtop->c.ll = vtop->c.i;
1899 if (dbt == (VT_LLONG|VT_UNSIGNED))
1900 vtop->c.ull = vtop->c.ll;
1901 else if (dbt == VT_BOOL)
1902 vtop->c.i = (vtop->c.ll != 0);
1903 else if (dbt != VT_LLONG) {
1904 int s = 0;
1905 if ((dbt & VT_BTYPE) == VT_BYTE)
1906 s = 24;
1907 else if ((dbt & VT_BTYPE) == VT_SHORT)
1908 s = 16;
1910 if(dbt & VT_UNSIGNED)
1911 vtop->c.ui = ((unsigned int)vtop->c.ll << s) >> s;
1912 else
1913 vtop->c.i = ((int)vtop->c.ll << s) >> s;
1916 } else if (p && dbt == VT_BOOL) {
1917 vtop->r = VT_CONST;
1918 vtop->c.i = 1;
1919 } else if (!nocode_wanted) {
1920 /* non constant case: generate code */
1921 if (sf && df) {
1922 /* convert from fp to fp */
1923 gen_cvt_ftof(dbt);
1924 } else if (df) {
1925 /* convert int to fp */
1926 gen_cvt_itof1(dbt);
1927 } else if (sf) {
1928 /* convert fp to int */
1929 if (dbt == VT_BOOL) {
1930 vpushi(0);
1931 gen_op(TOK_NE);
1932 } else {
1933 /* we handle char/short/etc... with generic code */
1934 if (dbt != (VT_INT | VT_UNSIGNED) &&
1935 dbt != (VT_LLONG | VT_UNSIGNED) &&
1936 dbt != VT_LLONG)
1937 dbt = VT_INT;
1938 gen_cvt_ftoi1(dbt);
1939 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
1940 /* additional cast for char/short... */
1941 vtop->type.t = dbt;
1942 gen_cast(type);
1945 #ifndef TCC_TARGET_X86_64
1946 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
1947 if ((sbt & VT_BTYPE) != VT_LLONG) {
1948 /* scalar to long long */
1949 /* machine independent conversion */
1950 gv(RC_INT);
1951 /* generate high word */
1952 if (sbt == (VT_INT | VT_UNSIGNED)) {
1953 vpushi(0);
1954 gv(RC_INT);
1955 } else {
1956 if (sbt == VT_PTR) {
1957 /* cast from pointer to int before we apply
1958 shift operation, which pointers don't support*/
1959 gen_cast(&int_type);
1961 gv_dup();
1962 vpushi(31);
1963 gen_op(TOK_SAR);
1965 /* patch second register */
1966 vtop[-1].r2 = vtop->r;
1967 vpop();
1969 #else
1970 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
1971 (dbt & VT_BTYPE) == VT_PTR ||
1972 (dbt & VT_BTYPE) == VT_FUNC) {
1973 if ((sbt & VT_BTYPE) != VT_LLONG &&
1974 (sbt & VT_BTYPE) != VT_PTR &&
1975 (sbt & VT_BTYPE) != VT_FUNC) {
1976 /* need to convert from 32bit to 64bit */
1977 int r = gv(RC_INT);
1978 if (sbt != (VT_INT | VT_UNSIGNED)) {
1979 /* x86_64 specific: movslq */
1980 o(0x6348);
1981 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
1984 #endif
1985 } else if (dbt == VT_BOOL) {
1986 /* scalar to bool */
1987 vpushi(0);
1988 gen_op(TOK_NE);
1989 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
1990 (dbt & VT_BTYPE) == VT_SHORT) {
1991 if (sbt == VT_PTR) {
1992 vtop->type.t = VT_INT;
1993 tcc_warning("nonportable conversion from pointer to char/short");
1995 force_charshort_cast(dbt);
1996 } else if ((dbt & VT_BTYPE) == VT_INT) {
1997 /* scalar to int */
1998 if (sbt == VT_LLONG) {
1999 /* from long long: just take low order word */
2000 lexpand();
2001 vpop();
2003 /* if lvalue and single word type, nothing to do because
2004 the lvalue already contains the real type size (see
2005 VT_LVAL_xxx constants) */
2008 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
2009 /* if we are casting between pointer types,
2010 we must update the VT_LVAL_xxx size */
2011 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
2012 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
2014 vtop->type = *type;
2017 /* return type size as known at compile time. Put alignment at 'a' */
2018 ST_FUNC int type_size(CType *type, int *a)
2020 Sym *s;
2021 int bt;
2023 bt = type->t & VT_BTYPE;
2024 if (bt == VT_STRUCT) {
2025 /* struct/union */
2026 s = type->ref;
2027 *a = s->r;
2028 return s->c;
2029 } else if (bt == VT_PTR) {
2030 if (type->t & VT_ARRAY) {
2031 int ts;
2033 s = type->ref;
2034 ts = type_size(&s->type, a);
2036 if (ts < 0 && s->c < 0)
2037 ts = -ts;
2039 return ts * s->c;
2040 } else {
2041 *a = PTR_SIZE;
2042 return PTR_SIZE;
2044 } else if (bt == VT_LDOUBLE) {
2045 *a = LDOUBLE_ALIGN;
2046 return LDOUBLE_SIZE;
2047 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
2048 #ifdef TCC_TARGET_I386
2049 #ifdef TCC_TARGET_PE
2050 *a = 8;
2051 #else
2052 *a = 4;
2053 #endif
2054 #elif defined(TCC_TARGET_ARM)
2055 #ifdef TCC_ARM_EABI
2056 *a = 8;
2057 #else
2058 *a = 4;
2059 #endif
2060 #else
2061 *a = 8;
2062 #endif
2063 return 8;
2064 } else if (bt == VT_INT || bt == VT_ENUM || bt == VT_FLOAT) {
2065 *a = 4;
2066 return 4;
2067 } else if (bt == VT_SHORT) {
2068 *a = 2;
2069 return 2;
2070 } else {
2071 /* char, void, function, _Bool */
2072 *a = 1;
2073 return 1;
2077 /* push type size as known at runtime time on top of value stack. Put
2078 alignment at 'a' */
2079 ST_FUNC void vla_runtime_type_size(CType *type, int *a)
2081 if (type->t & VT_VLA) {
2082 vset(&int_type, VT_LOCAL|VT_LVAL, type->ref->c);
2083 } else {
2084 vpushi(type_size(type, a));
2088 /* return the pointed type of t */
2089 static inline CType *pointed_type(CType *type)
2091 return &type->ref->type;
2094 /* modify type so that its it is a pointer to type. */
2095 ST_FUNC void mk_pointer(CType *type)
2097 Sym *s;
2098 s = sym_push(SYM_FIELD, type, 0, -1);
2099 type->t = VT_PTR | (type->t & ~VT_TYPE);
2100 type->ref = s;
2103 /* compare function types. OLD functions match any new functions */
2104 static int is_compatible_func(CType *type1, CType *type2)
2106 Sym *s1, *s2;
2108 s1 = type1->ref;
2109 s2 = type2->ref;
2110 if (!is_compatible_types(&s1->type, &s2->type))
2111 return 0;
2112 /* check func_call */
2113 if (FUNC_CALL(s1->r) != FUNC_CALL(s2->r))
2114 return 0;
2115 /* XXX: not complete */
2116 if (s1->c == FUNC_OLD || s2->c == FUNC_OLD)
2117 return 1;
2118 if (s1->c != s2->c)
2119 return 0;
2120 while (s1 != NULL) {
2121 if (s2 == NULL)
2122 return 0;
2123 if (!is_compatible_parameter_types(&s1->type, &s2->type))
2124 return 0;
2125 s1 = s1->next;
2126 s2 = s2->next;
2128 if (s2)
2129 return 0;
2130 return 1;
2133 /* return true if type1 and type2 are the same. If unqualified is
2134 true, qualifiers on the types are ignored.
2136 - enums are not checked as gcc __builtin_types_compatible_p ()
2138 static int compare_types(CType *type1, CType *type2, int unqualified)
2140 int bt1, t1, t2;
2142 t1 = type1->t & VT_TYPE;
2143 t2 = type2->t & VT_TYPE;
2144 if (unqualified) {
2145 /* strip qualifiers before comparing */
2146 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
2147 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
2149 /* XXX: bitfields ? */
2150 if (t1 != t2)
2151 return 0;
2152 /* test more complicated cases */
2153 bt1 = t1 & VT_BTYPE;
2154 if (bt1 == VT_PTR) {
2155 type1 = pointed_type(type1);
2156 type2 = pointed_type(type2);
2157 return is_compatible_types(type1, type2);
2158 } else if (bt1 == VT_STRUCT) {
2159 return (type1->ref == type2->ref);
2160 } else if (bt1 == VT_FUNC) {
2161 return is_compatible_func(type1, type2);
2162 } else {
2163 return 1;
2167 /* return true if type1 and type2 are exactly the same (including
2168 qualifiers).
2170 static int is_compatible_types(CType *type1, CType *type2)
2172 return compare_types(type1,type2,0);
2175 /* return true if type1 and type2 are the same (ignoring qualifiers).
2177 static int is_compatible_parameter_types(CType *type1, CType *type2)
2179 return compare_types(type1,type2,1);
2182 /* print a type. If 'varstr' is not NULL, then the variable is also
2183 printed in the type */
2184 /* XXX: union */
2185 /* XXX: add array and function pointers */
2186 static void type_to_str(char *buf, int buf_size,
2187 CType *type, const char *varstr)
2189 int bt, v, t;
2190 Sym *s, *sa;
2191 char buf1[256];
2192 const char *tstr;
2194 t = type->t & VT_TYPE;
2195 bt = t & VT_BTYPE;
2196 buf[0] = '\0';
2197 if (t & VT_CONSTANT)
2198 pstrcat(buf, buf_size, "const ");
2199 if (t & VT_VOLATILE)
2200 pstrcat(buf, buf_size, "volatile ");
2201 if (t & VT_UNSIGNED)
2202 pstrcat(buf, buf_size, "unsigned ");
2203 switch(bt) {
2204 case VT_VOID:
2205 tstr = "void";
2206 goto add_tstr;
2207 case VT_BOOL:
2208 tstr = "_Bool";
2209 goto add_tstr;
2210 case VT_BYTE:
2211 tstr = "char";
2212 goto add_tstr;
2213 case VT_SHORT:
2214 tstr = "short";
2215 goto add_tstr;
2216 case VT_INT:
2217 tstr = "int";
2218 goto add_tstr;
2219 case VT_LONG:
2220 tstr = "long";
2221 goto add_tstr;
2222 case VT_LLONG:
2223 tstr = "long long";
2224 goto add_tstr;
2225 case VT_FLOAT:
2226 tstr = "float";
2227 goto add_tstr;
2228 case VT_DOUBLE:
2229 tstr = "double";
2230 goto add_tstr;
2231 case VT_LDOUBLE:
2232 tstr = "long double";
2233 add_tstr:
2234 pstrcat(buf, buf_size, tstr);
2235 break;
2236 case VT_ENUM:
2237 case VT_STRUCT:
2238 if (bt == VT_STRUCT)
2239 tstr = "struct ";
2240 else
2241 tstr = "enum ";
2242 pstrcat(buf, buf_size, tstr);
2243 v = type->ref->v & ~SYM_STRUCT;
2244 if (v >= SYM_FIRST_ANOM)
2245 pstrcat(buf, buf_size, "<anonymous>");
2246 else
2247 pstrcat(buf, buf_size, get_tok_str(v, NULL));
2248 break;
2249 case VT_FUNC:
2250 s = type->ref;
2251 type_to_str(buf, buf_size, &s->type, varstr);
2252 pstrcat(buf, buf_size, "(");
2253 sa = s->next;
2254 while (sa != NULL) {
2255 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
2256 pstrcat(buf, buf_size, buf1);
2257 sa = sa->next;
2258 if (sa)
2259 pstrcat(buf, buf_size, ", ");
2261 pstrcat(buf, buf_size, ")");
2262 goto no_var;
2263 case VT_PTR:
2264 s = type->ref;
2265 pstrcpy(buf1, sizeof(buf1), "*");
2266 if (varstr)
2267 pstrcat(buf1, sizeof(buf1), varstr);
2268 type_to_str(buf, buf_size, &s->type, buf1);
2269 goto no_var;
2271 if (varstr) {
2272 pstrcat(buf, buf_size, " ");
2273 pstrcat(buf, buf_size, varstr);
2275 no_var: ;
2278 /* verify type compatibility to store vtop in 'dt' type, and generate
2279 casts if needed. */
2280 static void gen_assign_cast(CType *dt)
2282 CType *st, *type1, *type2, tmp_type1, tmp_type2;
2283 char buf1[256], buf2[256];
2284 int dbt, sbt;
2286 st = &vtop->type; /* source type */
2287 dbt = dt->t & VT_BTYPE;
2288 sbt = st->t & VT_BTYPE;
2289 if (sbt == VT_VOID)
2290 tcc_error("Cannot assign void value");
2291 if (dt->t & VT_CONSTANT)
2292 tcc_warning("assignment of read-only location");
2293 switch(dbt) {
2294 case VT_PTR:
2295 /* special cases for pointers */
2296 /* '0' can also be a pointer */
2297 if (is_null_pointer(vtop))
2298 goto type_ok;
2299 /* accept implicit pointer to integer cast with warning */
2300 if (is_integer_btype(sbt)) {
2301 tcc_warning("assignment makes pointer from integer without a cast");
2302 goto type_ok;
2304 type1 = pointed_type(dt);
2305 /* a function is implicitely a function pointer */
2306 if (sbt == VT_FUNC) {
2307 if ((type1->t & VT_BTYPE) != VT_VOID &&
2308 !is_compatible_types(pointed_type(dt), st))
2309 tcc_warning("assignment from incompatible pointer type");
2310 goto type_ok;
2312 if (sbt != VT_PTR)
2313 goto error;
2314 type2 = pointed_type(st);
2315 if ((type1->t & VT_BTYPE) == VT_VOID ||
2316 (type2->t & VT_BTYPE) == VT_VOID) {
2317 /* void * can match anything */
2318 } else {
2319 /* exact type match, except for unsigned */
2320 tmp_type1 = *type1;
2321 tmp_type2 = *type2;
2322 tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
2323 tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
2324 if (!is_compatible_types(&tmp_type1, &tmp_type2))
2325 tcc_warning("assignment from incompatible pointer type");
2327 /* check const and volatile */
2328 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
2329 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
2330 tcc_warning("assignment discards qualifiers from pointer target type");
2331 break;
2332 case VT_BYTE:
2333 case VT_SHORT:
2334 case VT_INT:
2335 case VT_LLONG:
2336 if (sbt == VT_PTR || sbt == VT_FUNC) {
2337 tcc_warning("assignment makes integer from pointer without a cast");
2339 /* XXX: more tests */
2340 break;
2341 case VT_STRUCT:
2342 tmp_type1 = *dt;
2343 tmp_type2 = *st;
2344 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2345 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2346 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2347 error:
2348 type_to_str(buf1, sizeof(buf1), st, NULL);
2349 type_to_str(buf2, sizeof(buf2), dt, NULL);
2350 tcc_error("cannot cast '%s' to '%s'", buf1, buf2);
2352 break;
2354 type_ok:
2355 gen_cast(dt);
2358 /* store vtop in lvalue pushed on stack */
2359 ST_FUNC void vstore(void)
2361 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
2363 ft = vtop[-1].type.t;
2364 sbt = vtop->type.t & VT_BTYPE;
2365 dbt = ft & VT_BTYPE;
2366 if ((((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
2367 (sbt == VT_INT && dbt == VT_SHORT))
2368 && !(vtop->type.t & VT_BITFIELD)) {
2369 /* optimize char/short casts */
2370 delayed_cast = VT_MUSTCAST;
2371 vtop->type.t = ft & (VT_TYPE & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT)));
2372 /* XXX: factorize */
2373 if (ft & VT_CONSTANT)
2374 tcc_warning("assignment of read-only location");
2375 } else {
2376 delayed_cast = 0;
2377 if (!(ft & VT_BITFIELD))
2378 gen_assign_cast(&vtop[-1].type);
2381 if (sbt == VT_STRUCT) {
2382 /* if structure, only generate pointer */
2383 /* structure assignment : generate memcpy */
2384 /* XXX: optimize if small size */
2385 if (!nocode_wanted) {
2386 size = type_size(&vtop->type, &align);
2388 /* destination */
2389 vswap();
2390 vtop->type.t = VT_PTR;
2391 gaddrof();
2393 /* address of memcpy() */
2394 #ifdef TCC_ARM_EABI
2395 if(!(align & 7))
2396 vpush_global_sym(&func_old_type, TOK_memcpy8);
2397 else if(!(align & 3))
2398 vpush_global_sym(&func_old_type, TOK_memcpy4);
2399 else
2400 #endif
2401 vpush_global_sym(&func_old_type, TOK_memcpy);
2403 vswap();
2404 /* source */
2405 vpushv(vtop - 2);
2406 vtop->type.t = VT_PTR;
2407 gaddrof();
2408 /* type size */
2409 vpushi(size);
2410 gfunc_call(3);
2411 } else {
2412 vswap();
2413 vpop();
2415 /* leave source on stack */
2416 } else if (ft & VT_BITFIELD) {
2417 /* bitfield store handling */
2418 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
2419 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
2420 /* remove bit field info to avoid loops */
2421 vtop[-1].type.t = ft & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
2423 /* duplicate source into other register */
2424 gv_dup();
2425 vswap();
2426 vrott(3);
2428 if((ft & VT_BTYPE) == VT_BOOL) {
2429 gen_cast(&vtop[-1].type);
2430 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
2433 /* duplicate destination */
2434 vdup();
2435 vtop[-1] = vtop[-2];
2437 /* mask and shift source */
2438 if((ft & VT_BTYPE) != VT_BOOL) {
2439 if((ft & VT_BTYPE) == VT_LLONG) {
2440 vpushll((1ULL << bit_size) - 1ULL);
2441 } else {
2442 vpushi((1 << bit_size) - 1);
2444 gen_op('&');
2446 vpushi(bit_pos);
2447 gen_op(TOK_SHL);
2448 /* load destination, mask and or with source */
2449 vswap();
2450 if((ft & VT_BTYPE) == VT_LLONG) {
2451 vpushll(~(((1ULL << bit_size) - 1ULL) << bit_pos));
2452 } else {
2453 vpushi(~(((1 << bit_size) - 1) << bit_pos));
2455 gen_op('&');
2456 gen_op('|');
2457 /* store result */
2458 vstore();
2460 /* pop off shifted source from "duplicate source..." above */
2461 vpop();
2463 } else {
2464 #ifdef CONFIG_TCC_BCHECK
2465 /* bound check case */
2466 if (vtop[-1].r & VT_MUSTBOUND) {
2467 vswap();
2468 gbound();
2469 vswap();
2471 #endif
2472 if (!nocode_wanted) {
2473 rc = RC_INT;
2474 if (is_float(ft)) {
2475 rc = RC_FLOAT;
2476 #ifdef TCC_TARGET_X86_64
2477 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
2478 rc = RC_ST0;
2480 #endif
2482 r = gv(rc); /* generate value */
2483 /* if lvalue was saved on stack, must read it */
2484 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
2485 SValue sv;
2486 t = get_reg(RC_INT);
2487 #ifdef TCC_TARGET_X86_64
2488 sv.type.t = VT_PTR;
2489 #else
2490 sv.type.t = VT_INT;
2491 #endif
2492 sv.r = VT_LOCAL | VT_LVAL;
2493 sv.c.ul = vtop[-1].c.ul;
2494 load(t, &sv);
2495 vtop[-1].r = t | VT_LVAL;
2497 store(r, vtop - 1);
2498 /* two word case handling : store second register at word + 4 (or +8 for x86-64) */
2499 #ifdef TCC_TARGET_X86_64
2500 if ((ft & VT_BTYPE) == VT_QLONG) {
2501 #else
2502 if ((ft & VT_BTYPE) == VT_LLONG) {
2503 #endif
2504 vswap();
2505 /* convert to int to increment easily */
2506 #ifdef TCC_TARGET_X86_64
2507 vtop->type.t = VT_LLONG;
2508 gaddrof();
2509 vpushi(8);
2510 #else
2511 vtop->type.t = VT_INT;
2512 gaddrof();
2513 vpushi(4);
2514 #endif
2515 gen_op('+');
2516 vtop->r |= VT_LVAL;
2517 vswap();
2518 /* XXX: it works because r2 is spilled last ! */
2519 store(vtop->r2, vtop - 1);
2522 vswap();
2523 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
2524 vtop->r |= delayed_cast;
2528 /* post defines POST/PRE add. c is the token ++ or -- */
2529 ST_FUNC void inc(int post, int c)
2531 test_lvalue();
2532 vdup(); /* save lvalue */
2533 if (post) {
2534 gv_dup(); /* duplicate value */
2535 vrotb(3);
2536 vrotb(3);
2538 /* add constant */
2539 vpushi(c - TOK_MID);
2540 gen_op('+');
2541 vstore(); /* store value */
2542 if (post)
2543 vpop(); /* if post op, return saved value */
2546 /* Parse GNUC __attribute__ extension. Currently, the following
2547 extensions are recognized:
2548 - aligned(n) : set data/function alignment.
2549 - packed : force data alignment to 1
2550 - section(x) : generate data/code in this section.
2551 - unused : currently ignored, but may be used someday.
2552 - regparm(n) : pass function parameters in registers (i386 only)
2554 static void parse_attribute(AttributeDef *ad)
2556 int t, n;
2558 while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
2559 next();
2560 skip('(');
2561 skip('(');
2562 while (tok != ')') {
2563 if (tok < TOK_IDENT)
2564 expect("attribute name");
2565 t = tok;
2566 next();
2567 switch(t) {
2568 case TOK_SECTION1:
2569 case TOK_SECTION2:
2570 skip('(');
2571 if (tok != TOK_STR)
2572 expect("section name");
2573 ad->section = find_section(tcc_state, (char *)tokc.cstr->data);
2574 next();
2575 skip(')');
2576 break;
2577 case TOK_ALIAS1:
2578 case TOK_ALIAS2:
2579 skip('(');
2580 if (tok != TOK_STR)
2581 expect("alias(\"target\")");
2582 ad->alias_target = /* save string as token, for later */
2583 tok_alloc((char*)tokc.cstr->data, tokc.cstr->size-1)->tok;
2584 next();
2585 skip(')');
2586 break;
2587 case TOK_ALIGNED1:
2588 case TOK_ALIGNED2:
2589 if (tok == '(') {
2590 next();
2591 n = expr_const();
2592 if (n <= 0 || (n & (n - 1)) != 0)
2593 tcc_error("alignment must be a positive power of two");
2594 skip(')');
2595 } else {
2596 n = MAX_ALIGN;
2598 ad->aligned = n;
2599 break;
2600 case TOK_PACKED1:
2601 case TOK_PACKED2:
2602 ad->packed = 1;
2603 break;
2604 case TOK_WEAK1:
2605 case TOK_WEAK2:
2606 ad->weak = 1;
2607 break;
2608 case TOK_UNUSED1:
2609 case TOK_UNUSED2:
2610 /* currently, no need to handle it because tcc does not
2611 track unused objects */
2612 break;
2613 case TOK_NORETURN1:
2614 case TOK_NORETURN2:
2615 /* currently, no need to handle it because tcc does not
2616 track unused objects */
2617 break;
2618 case TOK_CDECL1:
2619 case TOK_CDECL2:
2620 case TOK_CDECL3:
2621 ad->func_call = FUNC_CDECL;
2622 break;
2623 case TOK_STDCALL1:
2624 case TOK_STDCALL2:
2625 case TOK_STDCALL3:
2626 ad->func_call = FUNC_STDCALL;
2627 break;
2628 #ifdef TCC_TARGET_I386
2629 case TOK_REGPARM1:
2630 case TOK_REGPARM2:
2631 skip('(');
2632 n = expr_const();
2633 if (n > 3)
2634 n = 3;
2635 else if (n < 0)
2636 n = 0;
2637 if (n > 0)
2638 ad->func_call = FUNC_FASTCALL1 + n - 1;
2639 skip(')');
2640 break;
2641 case TOK_FASTCALL1:
2642 case TOK_FASTCALL2:
2643 case TOK_FASTCALL3:
2644 ad->func_call = FUNC_FASTCALLW;
2645 break;
2646 #endif
2647 case TOK_MODE:
2648 skip('(');
2649 switch(tok) {
2650 case TOK_MODE_DI:
2651 ad->mode = VT_LLONG + 1;
2652 break;
2653 case TOK_MODE_HI:
2654 ad->mode = VT_SHORT + 1;
2655 break;
2656 case TOK_MODE_SI:
2657 ad->mode = VT_INT + 1;
2658 break;
2659 default:
2660 tcc_warning("__mode__(%s) not supported\n", get_tok_str(tok, NULL));
2661 break;
2663 next();
2664 skip(')');
2665 break;
2666 case TOK_DLLEXPORT:
2667 ad->func_export = 1;
2668 break;
2669 case TOK_DLLIMPORT:
2670 ad->func_import = 1;
2671 break;
2672 default:
2673 if (tcc_state->warn_unsupported)
2674 tcc_warning("'%s' attribute ignored", get_tok_str(t, NULL));
2675 /* skip parameters */
2676 if (tok == '(') {
2677 int parenthesis = 0;
2678 do {
2679 if (tok == '(')
2680 parenthesis++;
2681 else if (tok == ')')
2682 parenthesis--;
2683 next();
2684 } while (parenthesis && tok != -1);
2686 break;
2688 if (tok != ',')
2689 break;
2690 next();
2692 skip(')');
2693 skip(')');
2697 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
2698 static void struct_decl(CType *type, int u)
2700 int a, v, size, align, maxalign, c, offset;
2701 int bit_size, bit_pos, bsize, bt, lbit_pos, prevbt;
2702 Sym *s, *ss, *ass, **ps;
2703 AttributeDef ad;
2704 CType type1, btype;
2706 a = tok; /* save decl type */
2707 next();
2708 if (tok != '{') {
2709 v = tok;
2710 next();
2711 /* struct already defined ? return it */
2712 if (v < TOK_IDENT)
2713 expect("struct/union/enum name");
2714 s = struct_find(v);
2715 if (s) {
2716 if (s->type.t != a)
2717 tcc_error("invalid type");
2718 goto do_decl;
2720 } else {
2721 v = anon_sym++;
2723 type1.t = a;
2724 /* we put an undefined size for struct/union */
2725 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
2726 s->r = 0; /* default alignment is zero as gcc */
2727 /* put struct/union/enum name in type */
2728 do_decl:
2729 type->t = u;
2730 type->ref = s;
2732 if (tok == '{') {
2733 next();
2734 if (s->c != -1)
2735 tcc_error("struct/union/enum already defined");
2736 /* cannot be empty */
2737 c = 0;
2738 /* non empty enums are not allowed */
2739 if (a == TOK_ENUM) {
2740 for(;;) {
2741 v = tok;
2742 if (v < TOK_UIDENT)
2743 expect("identifier");
2744 next();
2745 if (tok == '=') {
2746 next();
2747 c = expr_const();
2749 /* enum symbols have static storage */
2750 ss = sym_push(v, &int_type, VT_CONST, c);
2751 ss->type.t |= VT_STATIC;
2752 if (tok != ',')
2753 break;
2754 next();
2755 c++;
2756 /* NOTE: we accept a trailing comma */
2757 if (tok == '}')
2758 break;
2760 skip('}');
2761 } else {
2762 maxalign = 1;
2763 ps = &s->next;
2764 prevbt = VT_INT;
2765 bit_pos = 0;
2766 offset = 0;
2767 while (tok != '}') {
2768 parse_btype(&btype, &ad);
2769 while (1) {
2770 bit_size = -1;
2771 v = 0;
2772 type1 = btype;
2773 if (tok != ':') {
2774 type_decl(&type1, &ad, &v, TYPE_DIRECT | TYPE_ABSTRACT);
2775 if (v == 0 && (type1.t & VT_BTYPE) != VT_STRUCT)
2776 expect("identifier");
2777 if ((type1.t & VT_BTYPE) == VT_FUNC ||
2778 (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
2779 tcc_error("invalid type for '%s'",
2780 get_tok_str(v, NULL));
2782 if (tok == ':') {
2783 next();
2784 bit_size = expr_const();
2785 /* XXX: handle v = 0 case for messages */
2786 if (bit_size < 0)
2787 tcc_error("negative width in bit-field '%s'",
2788 get_tok_str(v, NULL));
2789 if (v && bit_size == 0)
2790 tcc_error("zero width for bit-field '%s'",
2791 get_tok_str(v, NULL));
2793 size = type_size(&type1, &align);
2794 if (ad.aligned) {
2795 if (align < ad.aligned)
2796 align = ad.aligned;
2797 } else if (ad.packed) {
2798 align = 1;
2799 } else if (*tcc_state->pack_stack_ptr) {
2800 if (align > *tcc_state->pack_stack_ptr)
2801 align = *tcc_state->pack_stack_ptr;
2803 lbit_pos = 0;
2804 if (bit_size >= 0) {
2805 bt = type1.t & VT_BTYPE;
2806 if (bt != VT_INT &&
2807 bt != VT_BYTE &&
2808 bt != VT_SHORT &&
2809 bt != VT_BOOL &&
2810 bt != VT_ENUM &&
2811 bt != VT_LLONG)
2812 tcc_error("bitfields must have scalar type");
2813 bsize = size * 8;
2814 if (bit_size > bsize) {
2815 tcc_error("width of '%s' exceeds its type",
2816 get_tok_str(v, NULL));
2817 } else if (bit_size == bsize) {
2818 /* no need for bit fields */
2819 bit_pos = 0;
2820 } else if (bit_size == 0) {
2821 /* XXX: what to do if only padding in a
2822 structure ? */
2823 /* zero size: means to pad */
2824 bit_pos = 0;
2825 } else {
2826 /* we do not have enough room ?
2827 did the type change?
2828 is it a union? */
2829 if ((bit_pos + bit_size) > bsize ||
2830 bt != prevbt || a == TOK_UNION)
2831 bit_pos = 0;
2832 lbit_pos = bit_pos;
2833 /* XXX: handle LSB first */
2834 type1.t |= VT_BITFIELD |
2835 (bit_pos << VT_STRUCT_SHIFT) |
2836 (bit_size << (VT_STRUCT_SHIFT + 6));
2837 bit_pos += bit_size;
2839 prevbt = bt;
2840 } else {
2841 bit_pos = 0;
2843 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
2844 /* add new memory data only if starting
2845 bit field */
2846 if (lbit_pos == 0) {
2847 if (a == TOK_STRUCT) {
2848 c = (c + align - 1) & -align;
2849 offset = c;
2850 if (size > 0)
2851 c += size;
2852 } else {
2853 offset = 0;
2854 if (size > c)
2855 c = size;
2857 if (align > maxalign)
2858 maxalign = align;
2860 #if 0
2861 printf("add field %s offset=%d",
2862 get_tok_str(v, NULL), offset);
2863 if (type1.t & VT_BITFIELD) {
2864 printf(" pos=%d size=%d",
2865 (type1.t >> VT_STRUCT_SHIFT) & 0x3f,
2866 (type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
2868 printf("\n");
2869 #endif
2871 if (v == 0 && (type1.t & VT_BTYPE) == VT_STRUCT) {
2872 ass = type1.ref;
2873 while ((ass = ass->next) != NULL) {
2874 ss = sym_push(ass->v, &ass->type, 0, offset + ass->c);
2875 *ps = ss;
2876 ps = &ss->next;
2878 } else if (v) {
2879 ss = sym_push(v | SYM_FIELD, &type1, 0, offset);
2880 *ps = ss;
2881 ps = &ss->next;
2883 if (tok == ';' || tok == TOK_EOF)
2884 break;
2885 skip(',');
2887 skip(';');
2889 skip('}');
2890 /* store size and alignment */
2891 s->c = (c + maxalign - 1) & -maxalign;
2892 s->r = maxalign;
2897 /* return 0 if no type declaration. otherwise, return the basic type
2898 and skip it.
2900 static int parse_btype(CType *type, AttributeDef *ad)
2902 int t, u, type_found, typespec_found, typedef_found;
2903 Sym *s;
2904 CType type1;
2906 memset(ad, 0, sizeof(AttributeDef));
2907 type_found = 0;
2908 typespec_found = 0;
2909 typedef_found = 0;
2910 t = 0;
2911 while(1) {
2912 switch(tok) {
2913 case TOK_EXTENSION:
2914 /* currently, we really ignore extension */
2915 next();
2916 continue;
2918 /* basic types */
2919 case TOK_CHAR:
2920 u = VT_BYTE;
2921 basic_type:
2922 next();
2923 basic_type1:
2924 if ((t & VT_BTYPE) != 0)
2925 tcc_error("too many basic types");
2926 t |= u;
2927 typespec_found = 1;
2928 break;
2929 case TOK_VOID:
2930 u = VT_VOID;
2931 goto basic_type;
2932 case TOK_SHORT:
2933 u = VT_SHORT;
2934 goto basic_type;
2935 case TOK_INT:
2936 next();
2937 typespec_found = 1;
2938 break;
2939 case TOK_LONG:
2940 next();
2941 if ((t & VT_BTYPE) == VT_DOUBLE) {
2942 #ifndef TCC_TARGET_PE
2943 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
2944 #endif
2945 } else if ((t & VT_BTYPE) == VT_LONG) {
2946 t = (t & ~VT_BTYPE) | VT_LLONG;
2947 } else {
2948 u = VT_LONG;
2949 goto basic_type1;
2951 break;
2952 case TOK_BOOL:
2953 u = VT_BOOL;
2954 goto basic_type;
2955 case TOK_FLOAT:
2956 u = VT_FLOAT;
2957 goto basic_type;
2958 case TOK_DOUBLE:
2959 next();
2960 if ((t & VT_BTYPE) == VT_LONG) {
2961 #ifdef TCC_TARGET_PE
2962 t = (t & ~VT_BTYPE) | VT_DOUBLE;
2963 #else
2964 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
2965 #endif
2966 } else {
2967 u = VT_DOUBLE;
2968 goto basic_type1;
2970 break;
2971 case TOK_ENUM:
2972 struct_decl(&type1, VT_ENUM);
2973 basic_type2:
2974 u = type1.t;
2975 type->ref = type1.ref;
2976 goto basic_type1;
2977 case TOK_STRUCT:
2978 case TOK_UNION:
2979 struct_decl(&type1, VT_STRUCT);
2980 goto basic_type2;
2982 /* type modifiers */
2983 case TOK_CONST1:
2984 case TOK_CONST2:
2985 case TOK_CONST3:
2986 t |= VT_CONSTANT;
2987 next();
2988 break;
2989 case TOK_VOLATILE1:
2990 case TOK_VOLATILE2:
2991 case TOK_VOLATILE3:
2992 t |= VT_VOLATILE;
2993 next();
2994 break;
2995 case TOK_SIGNED1:
2996 case TOK_SIGNED2:
2997 case TOK_SIGNED3:
2998 typespec_found = 1;
2999 t |= VT_SIGNED;
3000 next();
3001 break;
3002 case TOK_REGISTER:
3003 case TOK_AUTO:
3004 case TOK_RESTRICT1:
3005 case TOK_RESTRICT2:
3006 case TOK_RESTRICT3:
3007 next();
3008 break;
3009 case TOK_UNSIGNED:
3010 t |= VT_UNSIGNED;
3011 next();
3012 typespec_found = 1;
3013 break;
3015 /* storage */
3016 case TOK_EXTERN:
3017 t |= VT_EXTERN;
3018 next();
3019 break;
3020 case TOK_STATIC:
3021 t |= VT_STATIC;
3022 next();
3023 break;
3024 case TOK_TYPEDEF:
3025 t |= VT_TYPEDEF;
3026 next();
3027 break;
3028 case TOK_INLINE1:
3029 case TOK_INLINE2:
3030 case TOK_INLINE3:
3031 t |= VT_INLINE;
3032 next();
3033 break;
3035 /* GNUC attribute */
3036 case TOK_ATTRIBUTE1:
3037 case TOK_ATTRIBUTE2:
3038 parse_attribute(ad);
3039 if (ad->mode) {
3040 u = ad->mode -1;
3041 t = (t & ~VT_BTYPE) | u;
3043 break;
3044 /* GNUC typeof */
3045 case TOK_TYPEOF1:
3046 case TOK_TYPEOF2:
3047 case TOK_TYPEOF3:
3048 next();
3049 parse_expr_type(&type1);
3050 /* remove all storage modifiers except typedef */
3051 type1.t &= ~(VT_STORAGE&~VT_TYPEDEF);
3052 goto basic_type2;
3053 default:
3054 if (typespec_found || typedef_found)
3055 goto the_end;
3056 s = sym_find(tok);
3057 if (!s || !(s->type.t & VT_TYPEDEF))
3058 goto the_end;
3059 typedef_found = 1;
3060 t |= (s->type.t & ~VT_TYPEDEF);
3061 type->ref = s->type.ref;
3062 if (s->r) {
3063 /* get attributes from typedef */
3064 if (0 == ad->aligned)
3065 ad->aligned = FUNC_ALIGN(s->r);
3066 if (0 == ad->func_call)
3067 ad->func_call = FUNC_CALL(s->r);
3068 ad->packed |= FUNC_PACKED(s->r);
3070 next();
3071 typespec_found = 1;
3072 break;
3074 type_found = 1;
3076 the_end:
3077 if ((t & (VT_SIGNED|VT_UNSIGNED)) == (VT_SIGNED|VT_UNSIGNED))
3078 tcc_error("signed and unsigned modifier");
3079 if (tcc_state->char_is_unsigned) {
3080 if ((t & (VT_SIGNED|VT_UNSIGNED|VT_BTYPE)) == VT_BYTE)
3081 t |= VT_UNSIGNED;
3083 t &= ~VT_SIGNED;
3085 /* long is never used as type */
3086 if ((t & VT_BTYPE) == VT_LONG)
3087 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
3088 t = (t & ~VT_BTYPE) | VT_INT;
3089 #else
3090 t = (t & ~VT_BTYPE) | VT_LLONG;
3091 #endif
3092 type->t = t;
3093 return type_found;
3096 /* convert a function parameter type (array to pointer and function to
3097 function pointer) */
3098 static inline void convert_parameter_type(CType *pt)
3100 /* remove const and volatile qualifiers (XXX: const could be used
3101 to indicate a const function parameter */
3102 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
3103 /* array must be transformed to pointer according to ANSI C */
3104 pt->t &= ~VT_ARRAY;
3105 if ((pt->t & VT_BTYPE) == VT_FUNC) {
3106 mk_pointer(pt);
3110 ST_FUNC void parse_asm_str(CString *astr)
3112 skip('(');
3113 /* read the string */
3114 if (tok != TOK_STR)
3115 expect("string constant");
3116 cstr_new(astr);
3117 while (tok == TOK_STR) {
3118 /* XXX: add \0 handling too ? */
3119 cstr_cat(astr, tokc.cstr->data);
3120 next();
3122 cstr_ccat(astr, '\0');
3125 /* Parse an asm label and return the label
3126 * Don't forget to free the CString in the caller! */
3127 static void asm_label_instr(CString *astr)
3129 next();
3130 parse_asm_str(astr);
3131 skip(')');
3132 #ifdef ASM_DEBUG
3133 printf("asm_alias: \"%s\"\n", (char *)astr->data);
3134 #endif
3137 static void post_type(CType *type, AttributeDef *ad)
3139 int n, l, t1, arg_size, align;
3140 Sym **plast, *s, *first;
3141 AttributeDef ad1;
3142 CType pt;
3144 if (tok == '(') {
3145 /* function declaration */
3146 next();
3147 l = 0;
3148 first = NULL;
3149 plast = &first;
3150 arg_size = 0;
3151 if (tok != ')') {
3152 for(;;) {
3153 /* read param name and compute offset */
3154 if (l != FUNC_OLD) {
3155 if (!parse_btype(&pt, &ad1)) {
3156 if (l) {
3157 tcc_error("invalid type");
3158 } else {
3159 l = FUNC_OLD;
3160 goto old_proto;
3163 l = FUNC_NEW;
3164 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
3165 break;
3166 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
3167 if ((pt.t & VT_BTYPE) == VT_VOID)
3168 tcc_error("parameter declared as void");
3169 arg_size += (type_size(&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
3170 } else {
3171 old_proto:
3172 n = tok;
3173 if (n < TOK_UIDENT)
3174 expect("identifier");
3175 pt.t = VT_INT;
3176 next();
3178 convert_parameter_type(&pt);
3179 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
3180 *plast = s;
3181 plast = &s->next;
3182 if (tok == ')')
3183 break;
3184 skip(',');
3185 if (l == FUNC_NEW && tok == TOK_DOTS) {
3186 l = FUNC_ELLIPSIS;
3187 next();
3188 break;
3192 /* if no parameters, then old type prototype */
3193 if (l == 0)
3194 l = FUNC_OLD;
3195 skip(')');
3196 /* NOTE: const is ignored in returned type as it has a special
3197 meaning in gcc / C++ */
3198 type->t &= ~VT_CONSTANT;
3199 /* some ancient pre-K&R C allows a function to return an array
3200 and the array brackets to be put after the arguments, such
3201 that "int c()[]" means something like "int[] c()" */
3202 if (tok == '[') {
3203 next();
3204 skip(']'); /* only handle simple "[]" */
3205 type->t |= VT_PTR;
3207 /* we push a anonymous symbol which will contain the function prototype */
3208 ad->func_args = arg_size;
3209 s = sym_push(SYM_FIELD, type, INT_ATTR(ad), l);
3210 s->next = first;
3211 type->t = VT_FUNC;
3212 type->ref = s;
3213 } else if (tok == '[') {
3214 /* array definition */
3215 next();
3216 if (tok == TOK_RESTRICT1)
3217 next();
3218 n = -1;
3219 t1 = 0;
3220 if (tok != ']') {
3221 if (!local_stack || nocode_wanted)
3222 vpushi(expr_const());
3223 else gexpr();
3224 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3225 n = vtop->c.i;
3226 if (n < 0)
3227 tcc_error("invalid array size");
3228 } else {
3229 if (!is_integer_btype(vtop->type.t & VT_BTYPE))
3230 tcc_error("size of variable length array should be an integer");
3231 t1 = VT_VLA;
3234 skip(']');
3235 /* parse next post type */
3236 post_type(type, ad);
3237 t1 |= type->t & VT_VLA;
3239 if (t1 & VT_VLA) {
3240 loc -= type_size(&int_type, &align);
3241 loc &= -align;
3242 n = loc;
3244 vla_runtime_type_size(type, &align);
3245 gen_op('*');
3246 vset(&int_type, VT_LOCAL|VT_LVAL, loc);
3247 vswap();
3248 vstore();
3250 if (n != -1)
3251 vpop();
3253 /* we push an anonymous symbol which will contain the array
3254 element type */
3255 s = sym_push(SYM_FIELD, type, 0, n);
3256 type->t = (t1 ? VT_VLA : VT_ARRAY) | VT_PTR;
3257 type->ref = s;
3261 /* Parse a type declaration (except basic type), and return the type
3262 in 'type'. 'td' is a bitmask indicating which kind of type decl is
3263 expected. 'type' should contain the basic type. 'ad' is the
3264 attribute definition of the basic type. It can be modified by
3265 type_decl().
3267 static void type_decl(CType *type, AttributeDef *ad, int *v, int td)
3269 Sym *s;
3270 CType type1, *type2;
3271 int qualifiers, storage;
3273 while (tok == '*') {
3274 qualifiers = 0;
3275 redo:
3276 next();
3277 switch(tok) {
3278 case TOK_CONST1:
3279 case TOK_CONST2:
3280 case TOK_CONST3:
3281 qualifiers |= VT_CONSTANT;
3282 goto redo;
3283 case TOK_VOLATILE1:
3284 case TOK_VOLATILE2:
3285 case TOK_VOLATILE3:
3286 qualifiers |= VT_VOLATILE;
3287 goto redo;
3288 case TOK_RESTRICT1:
3289 case TOK_RESTRICT2:
3290 case TOK_RESTRICT3:
3291 goto redo;
3293 mk_pointer(type);
3294 type->t |= qualifiers;
3297 /* XXX: clarify attribute handling */
3298 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3299 parse_attribute(ad);
3301 /* recursive type */
3302 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
3303 type1.t = 0; /* XXX: same as int */
3304 if (tok == '(') {
3305 next();
3306 /* XXX: this is not correct to modify 'ad' at this point, but
3307 the syntax is not clear */
3308 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3309 parse_attribute(ad);
3310 type_decl(&type1, ad, v, td);
3311 skip(')');
3312 } else {
3313 /* type identifier */
3314 if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
3315 *v = tok;
3316 next();
3317 } else {
3318 if (!(td & TYPE_ABSTRACT))
3319 expect("identifier");
3320 *v = 0;
3323 storage = type->t & VT_STORAGE;
3324 type->t &= ~VT_STORAGE;
3325 if (storage & VT_STATIC) {
3326 int saved_nocode_wanted = nocode_wanted;
3327 nocode_wanted = 1;
3328 post_type(type, ad);
3329 nocode_wanted = saved_nocode_wanted;
3330 } else
3331 post_type(type, ad);
3332 type->t |= storage;
3333 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3334 parse_attribute(ad);
3336 if (!type1.t)
3337 return;
3338 /* append type at the end of type1 */
3339 type2 = &type1;
3340 for(;;) {
3341 s = type2->ref;
3342 type2 = &s->type;
3343 if (!type2->t) {
3344 *type2 = *type;
3345 break;
3348 *type = type1;
3351 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
3352 ST_FUNC int lvalue_type(int t)
3354 int bt, r;
3355 r = VT_LVAL;
3356 bt = t & VT_BTYPE;
3357 if (bt == VT_BYTE || bt == VT_BOOL)
3358 r |= VT_LVAL_BYTE;
3359 else if (bt == VT_SHORT)
3360 r |= VT_LVAL_SHORT;
3361 else
3362 return r;
3363 if (t & VT_UNSIGNED)
3364 r |= VT_LVAL_UNSIGNED;
3365 return r;
3368 /* indirection with full error checking and bound check */
3369 ST_FUNC void indir(void)
3371 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
3372 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
3373 return;
3374 expect("pointer");
3376 if ((vtop->r & VT_LVAL) && !nocode_wanted)
3377 gv(RC_INT);
3378 vtop->type = *pointed_type(&vtop->type);
3379 /* Arrays and functions are never lvalues */
3380 if (!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_VLA)
3381 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
3382 vtop->r |= lvalue_type(vtop->type.t);
3383 /* if bound checking, the referenced pointer must be checked */
3384 #ifdef CONFIG_TCC_BCHECK
3385 if (tcc_state->do_bounds_check)
3386 vtop->r |= VT_MUSTBOUND;
3387 #endif
3391 /* pass a parameter to a function and do type checking and casting */
3392 static void gfunc_param_typed(Sym *func, Sym *arg)
3394 int func_type;
3395 CType type;
3397 func_type = func->c;
3398 if (func_type == FUNC_OLD ||
3399 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
3400 /* default casting : only need to convert float to double */
3401 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
3402 type.t = VT_DOUBLE;
3403 gen_cast(&type);
3405 } else if (arg == NULL) {
3406 tcc_error("too many arguments to function");
3407 } else {
3408 type = arg->type;
3409 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
3410 gen_assign_cast(&type);
3414 /* parse an expression of the form '(type)' or '(expr)' and return its
3415 type */
3416 static void parse_expr_type(CType *type)
3418 int n;
3419 AttributeDef ad;
3421 skip('(');
3422 if (parse_btype(type, &ad)) {
3423 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3424 } else {
3425 expr_type(type);
3427 skip(')');
3430 static void parse_type(CType *type)
3432 AttributeDef ad;
3433 int n;
3435 if (!parse_btype(type, &ad)) {
3436 expect("type");
3438 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3441 static void vpush_tokc(int t)
3443 CType type;
3444 type.t = t;
3445 type.ref = 0;
3446 vsetc(&type, VT_CONST, &tokc);
3449 ST_FUNC void unary(void)
3451 int n, t, align, size, r, sizeof_caller;
3452 CType type;
3453 Sym *s;
3454 AttributeDef ad;
3455 static int in_sizeof = 0;
3457 sizeof_caller = in_sizeof;
3458 in_sizeof = 0;
3459 /* XXX: GCC 2.95.3 does not generate a table although it should be
3460 better here */
3461 tok_next:
3462 switch(tok) {
3463 case TOK_EXTENSION:
3464 next();
3465 goto tok_next;
3466 case TOK_CINT:
3467 case TOK_CCHAR:
3468 case TOK_LCHAR:
3469 vpushi(tokc.i);
3470 next();
3471 break;
3472 case TOK_CUINT:
3473 vpush_tokc(VT_INT | VT_UNSIGNED);
3474 next();
3475 break;
3476 case TOK_CLLONG:
3477 vpush_tokc(VT_LLONG);
3478 next();
3479 break;
3480 case TOK_CULLONG:
3481 vpush_tokc(VT_LLONG | VT_UNSIGNED);
3482 next();
3483 break;
3484 case TOK_CFLOAT:
3485 vpush_tokc(VT_FLOAT);
3486 next();
3487 break;
3488 case TOK_CDOUBLE:
3489 vpush_tokc(VT_DOUBLE);
3490 next();
3491 break;
3492 case TOK_CLDOUBLE:
3493 vpush_tokc(VT_LDOUBLE);
3494 next();
3495 break;
3496 case TOK___FUNCTION__:
3497 if (!gnu_ext)
3498 goto tok_identifier;
3499 /* fall thru */
3500 case TOK___FUNC__:
3502 void *ptr;
3503 int len;
3504 /* special function name identifier */
3505 len = strlen(funcname) + 1;
3506 /* generate char[len] type */
3507 type.t = VT_BYTE;
3508 mk_pointer(&type);
3509 type.t |= VT_ARRAY;
3510 type.ref->c = len;
3511 vpush_ref(&type, data_section, data_section->data_offset, len);
3512 ptr = section_ptr_add(data_section, len);
3513 memcpy(ptr, funcname, len);
3514 next();
3516 break;
3517 case TOK_LSTR:
3518 #ifdef TCC_TARGET_PE
3519 t = VT_SHORT | VT_UNSIGNED;
3520 #else
3521 t = VT_INT;
3522 #endif
3523 goto str_init;
3524 case TOK_STR:
3525 /* string parsing */
3526 t = VT_BYTE;
3527 str_init:
3528 if (tcc_state->warn_write_strings)
3529 t |= VT_CONSTANT;
3530 type.t = t;
3531 mk_pointer(&type);
3532 type.t |= VT_ARRAY;
3533 memset(&ad, 0, sizeof(AttributeDef));
3534 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, NULL, 0);
3535 break;
3536 case '(':
3537 next();
3538 /* cast ? */
3539 if (parse_btype(&type, &ad)) {
3540 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
3541 skip(')');
3542 /* check ISOC99 compound literal */
3543 if (tok == '{') {
3544 /* data is allocated locally by default */
3545 if (global_expr)
3546 r = VT_CONST;
3547 else
3548 r = VT_LOCAL;
3549 /* all except arrays are lvalues */
3550 if (!(type.t & VT_ARRAY))
3551 r |= lvalue_type(type.t);
3552 memset(&ad, 0, sizeof(AttributeDef));
3553 decl_initializer_alloc(&type, &ad, r, 1, 0, NULL, 0);
3554 } else {
3555 if (sizeof_caller) {
3556 vpush(&type);
3557 return;
3559 unary();
3560 gen_cast(&type);
3562 } else if (tok == '{') {
3563 /* save all registers */
3564 save_regs(0);
3565 /* statement expression : we do not accept break/continue
3566 inside as GCC does */
3567 block(NULL, NULL, NULL, NULL, 0, 1);
3568 skip(')');
3569 } else {
3570 gexpr();
3571 skip(')');
3573 break;
3574 case '*':
3575 next();
3576 unary();
3577 indir();
3578 break;
3579 case '&':
3580 next();
3581 unary();
3582 /* functions names must be treated as function pointers,
3583 except for unary '&' and sizeof. Since we consider that
3584 functions are not lvalues, we only have to handle it
3585 there and in function calls. */
3586 /* arrays can also be used although they are not lvalues */
3587 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
3588 !(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
3589 test_lvalue();
3590 mk_pointer(&vtop->type);
3591 gaddrof();
3592 break;
3593 case '!':
3594 next();
3595 unary();
3596 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3597 CType boolean;
3598 boolean.t = VT_BOOL;
3599 gen_cast(&boolean);
3600 vtop->c.i = !vtop->c.i;
3601 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
3602 vtop->c.i = vtop->c.i ^ 1;
3603 else {
3604 save_regs(1);
3605 vseti(VT_JMP, gtst(1, 0));
3607 break;
3608 case '~':
3609 next();
3610 unary();
3611 vpushi(-1);
3612 gen_op('^');
3613 break;
3614 case '+':
3615 next();
3616 /* in order to force cast, we add zero */
3617 unary();
3618 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
3619 tcc_error("pointer not accepted for unary plus");
3620 vpushi(0);
3621 gen_op('+');
3622 break;
3623 case TOK_SIZEOF:
3624 case TOK_ALIGNOF1:
3625 case TOK_ALIGNOF2:
3626 t = tok;
3627 next();
3628 in_sizeof++;
3629 unary_type(&type); // Perform a in_sizeof = 0;
3630 size = type_size(&type, &align);
3631 if (t == TOK_SIZEOF) {
3632 if (!(type.t & VT_VLA)) {
3633 if (size < 0)
3634 tcc_error("sizeof applied to an incomplete type");
3635 vpushs(size);
3636 } else {
3637 vla_runtime_type_size(&type, &align);
3639 } else {
3640 vpushs(align);
3642 vtop->type.t |= VT_UNSIGNED;
3643 break;
3645 case TOK_builtin_types_compatible_p:
3647 CType type1, type2;
3648 next();
3649 skip('(');
3650 parse_type(&type1);
3651 skip(',');
3652 parse_type(&type2);
3653 skip(')');
3654 type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
3655 type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
3656 vpushi(is_compatible_types(&type1, &type2));
3658 break;
3659 case TOK_builtin_constant_p:
3661 int saved_nocode_wanted, res;
3662 next();
3663 skip('(');
3664 saved_nocode_wanted = nocode_wanted;
3665 nocode_wanted = 1;
3666 gexpr();
3667 res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
3668 vpop();
3669 nocode_wanted = saved_nocode_wanted;
3670 skip(')');
3671 vpushi(res);
3673 break;
3674 case TOK_builtin_frame_address:
3676 int level;
3677 CType type;
3678 next();
3679 skip('(');
3680 if (tok != TOK_CINT || tokc.i < 0) {
3681 tcc_error("__builtin_frame_address only takes positive integers");
3683 level = tokc.i;
3684 next();
3685 skip(')');
3686 type.t = VT_VOID;
3687 mk_pointer(&type);
3688 vset(&type, VT_LOCAL, 0); /* local frame */
3689 while (level--) {
3690 mk_pointer(&vtop->type);
3691 indir(); /* -> parent frame */
3694 break;
3695 #ifdef TCC_TARGET_X86_64
3696 case TOK_builtin_va_arg_types:
3698 /* This definition must be synced with stdarg.h */
3699 enum __va_arg_type {
3700 __va_gen_reg, __va_float_reg, __va_stack
3702 CType type;
3703 int bt;
3704 next();
3705 skip('(');
3706 parse_type(&type);
3707 skip(')');
3708 bt = type.t & VT_BTYPE;
3709 if (bt == VT_STRUCT || bt == VT_LDOUBLE) {
3710 vpushi(__va_stack);
3711 } else if (bt == VT_FLOAT || bt == VT_DOUBLE) {
3712 vpushi(__va_float_reg);
3713 } else {
3714 vpushi(__va_gen_reg);
3717 break;
3718 #endif
3719 case TOK_INC:
3720 case TOK_DEC:
3721 t = tok;
3722 next();
3723 unary();
3724 inc(0, t);
3725 break;
3726 case '-':
3727 next();
3728 vpushi(0);
3729 unary();
3730 gen_op('-');
3731 break;
3732 case TOK_LAND:
3733 if (!gnu_ext)
3734 goto tok_identifier;
3735 next();
3736 /* allow to take the address of a label */
3737 if (tok < TOK_UIDENT)
3738 expect("label identifier");
3739 s = label_find(tok);
3740 if (!s) {
3741 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
3742 } else {
3743 if (s->r == LABEL_DECLARED)
3744 s->r = LABEL_FORWARD;
3746 if (!s->type.t) {
3747 s->type.t = VT_VOID;
3748 mk_pointer(&s->type);
3749 s->type.t |= VT_STATIC;
3751 vset(&s->type, VT_CONST | VT_SYM, 0);
3752 vtop->sym = s;
3753 next();
3754 break;
3756 // special qnan , snan and infinity values
3757 case TOK___NAN__:
3758 vpush64(VT_DOUBLE, 0x7ff8000000000000ULL);
3759 next();
3760 break;
3761 case TOK___SNAN__:
3762 vpush64(VT_DOUBLE, 0x7ff0000000000001ULL);
3763 next();
3764 break;
3765 case TOK___INF__:
3766 vpush64(VT_DOUBLE, 0x7ff0000000000000ULL);
3767 next();
3768 break;
3770 default:
3771 tok_identifier:
3772 t = tok;
3773 next();
3774 if (t < TOK_UIDENT)
3775 expect("identifier");
3776 s = sym_find(t);
3777 if (!s) {
3778 if (tok != '(')
3779 tcc_error("'%s' undeclared", get_tok_str(t, NULL));
3780 /* for simple function calls, we tolerate undeclared
3781 external reference to int() function */
3782 if (tcc_state->warn_implicit_function_declaration)
3783 tcc_warning("implicit declaration of function '%s'",
3784 get_tok_str(t, NULL));
3785 s = external_global_sym(t, &func_old_type, 0);
3787 if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
3788 (VT_STATIC | VT_INLINE | VT_FUNC)) {
3789 /* if referencing an inline function, then we generate a
3790 symbol to it if not already done. It will have the
3791 effect to generate code for it at the end of the
3792 compilation unit. Inline function as always
3793 generated in the text section. */
3794 if (!s->c)
3795 put_extern_sym(s, text_section, 0, 0);
3796 r = VT_SYM | VT_CONST;
3797 } else {
3798 r = s->r;
3800 vset(&s->type, r, s->c);
3801 /* if forward reference, we must point to s */
3802 if (vtop->r & VT_SYM) {
3803 vtop->sym = s;
3804 vtop->c.ul = 0;
3806 break;
3809 /* post operations */
3810 while (1) {
3811 if (tok == TOK_INC || tok == TOK_DEC) {
3812 inc(1, tok);
3813 next();
3814 } else if (tok == '.' || tok == TOK_ARROW) {
3815 int qualifiers;
3816 /* field */
3817 if (tok == TOK_ARROW)
3818 indir();
3819 qualifiers = vtop->type.t & (VT_CONSTANT | VT_VOLATILE);
3820 test_lvalue();
3821 gaddrof();
3822 next();
3823 /* expect pointer on structure */
3824 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
3825 expect("struct or union");
3826 s = vtop->type.ref;
3827 /* find field */
3828 tok |= SYM_FIELD;
3829 while ((s = s->next) != NULL) {
3830 if (s->v == tok)
3831 break;
3833 if (!s)
3834 tcc_error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, NULL));
3835 /* add field offset to pointer */
3836 vtop->type = char_pointer_type; /* change type to 'char *' */
3837 vpushi(s->c);
3838 gen_op('+');
3839 /* change type to field type, and set to lvalue */
3840 vtop->type = s->type;
3841 vtop->type.t |= qualifiers;
3842 /* an array is never an lvalue */
3843 if (!(vtop->type.t & VT_ARRAY)) {
3844 vtop->r |= lvalue_type(vtop->type.t);
3845 #ifdef CONFIG_TCC_BCHECK
3846 /* if bound checking, the referenced pointer must be checked */
3847 if (tcc_state->do_bounds_check)
3848 vtop->r |= VT_MUSTBOUND;
3849 #endif
3851 next();
3852 } else if (tok == '[') {
3853 next();
3854 gexpr();
3855 gen_op('+');
3856 indir();
3857 skip(']');
3858 } else if (tok == '(') {
3859 SValue ret;
3860 Sym *sa;
3861 int nb_args, sret;
3863 /* function call */
3864 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
3865 /* pointer test (no array accepted) */
3866 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
3867 vtop->type = *pointed_type(&vtop->type);
3868 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
3869 goto error_func;
3870 } else {
3871 error_func:
3872 expect("function pointer");
3874 } else {
3875 vtop->r &= ~VT_LVAL; /* no lvalue */
3877 /* get return type */
3878 s = vtop->type.ref;
3879 next();
3880 sa = s->next; /* first parameter */
3881 nb_args = 0;
3882 ret.r2 = VT_CONST;
3883 /* compute first implicit argument if a structure is returned */
3884 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
3885 int ret_align;
3886 sret = gfunc_sret(&s->type, &ret.type, &ret_align);
3887 if (sret) {
3888 /* get some space for the returned structure */
3889 size = type_size(&s->type, &align);
3890 loc = (loc - size) & -align;
3891 ret.type = s->type;
3892 ret.r = VT_LOCAL | VT_LVAL;
3893 /* pass it as 'int' to avoid structure arg passing
3894 problems */
3895 vseti(VT_LOCAL, loc);
3896 ret.c = vtop->c;
3897 nb_args++;
3899 } else {
3900 sret = 0;
3901 ret.type = s->type;
3904 if (!sret) {
3905 /* return in register */
3906 if (is_float(ret.type.t)) {
3907 ret.r = reg_fret(ret.type.t);
3908 } else {
3909 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
3910 ret.r2 = REG_LRET;
3911 ret.r = REG_IRET;
3913 ret.c.i = 0;
3915 if (tok != ')') {
3916 for(;;) {
3917 expr_eq();
3918 gfunc_param_typed(s, sa);
3919 nb_args++;
3920 if (sa)
3921 sa = sa->next;
3922 if (tok == ')')
3923 break;
3924 skip(',');
3927 if (sa)
3928 tcc_error("too few arguments to function");
3929 skip(')');
3930 if (!nocode_wanted) {
3931 gfunc_call(nb_args);
3932 } else {
3933 vtop -= (nb_args + 1);
3935 /* return value */
3936 vsetc(&ret.type, ret.r, &ret.c);
3937 vtop->r2 = ret.r2;
3938 /* handle packed struct return */
3939 if (((s->type.t & VT_BTYPE) == VT_STRUCT) && !sret) {
3940 size = type_size(&s->type, &align);
3941 loc = (loc - size) & -align;
3942 int addr = loc;
3943 vset(&ret.type, VT_LOCAL | VT_LVAL, addr);
3944 vswap();
3945 vstore();
3946 vtop--;
3947 vset(&s->type, VT_LOCAL | VT_LVAL, addr);
3949 } else {
3950 break;
3955 ST_FUNC void expr_prod(void)
3957 int t;
3959 unary();
3960 while (tok == '*' || tok == '/' || tok == '%') {
3961 t = tok;
3962 next();
3963 unary();
3964 gen_op(t);
3968 ST_FUNC void expr_sum(void)
3970 int t;
3972 expr_prod();
3973 while (tok == '+' || tok == '-') {
3974 t = tok;
3975 next();
3976 expr_prod();
3977 gen_op(t);
3981 static void expr_shift(void)
3983 int t;
3985 expr_sum();
3986 while (tok == TOK_SHL || tok == TOK_SAR) {
3987 t = tok;
3988 next();
3989 expr_sum();
3990 gen_op(t);
3994 static void expr_cmp(void)
3996 int t;
3998 expr_shift();
3999 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
4000 tok == TOK_ULT || tok == TOK_UGE) {
4001 t = tok;
4002 next();
4003 expr_shift();
4004 gen_op(t);
4008 static void expr_cmpeq(void)
4010 int t;
4012 expr_cmp();
4013 while (tok == TOK_EQ || tok == TOK_NE) {
4014 t = tok;
4015 next();
4016 expr_cmp();
4017 gen_op(t);
4021 static void expr_and(void)
4023 expr_cmpeq();
4024 while (tok == '&') {
4025 next();
4026 expr_cmpeq();
4027 gen_op('&');
4031 static void expr_xor(void)
4033 expr_and();
4034 while (tok == '^') {
4035 next();
4036 expr_and();
4037 gen_op('^');
4041 static void expr_or(void)
4043 expr_xor();
4044 while (tok == '|') {
4045 next();
4046 expr_xor();
4047 gen_op('|');
4051 /* XXX: fix this mess */
4052 static void expr_land_const(void)
4054 expr_or();
4055 while (tok == TOK_LAND) {
4056 next();
4057 expr_or();
4058 gen_op(TOK_LAND);
4062 /* XXX: fix this mess */
4063 static void expr_lor_const(void)
4065 expr_land_const();
4066 while (tok == TOK_LOR) {
4067 next();
4068 expr_land_const();
4069 gen_op(TOK_LOR);
4073 /* only used if non constant */
4074 static void expr_land(void)
4076 int t;
4078 expr_or();
4079 if (tok == TOK_LAND) {
4080 t = 0;
4081 save_regs(1);
4082 for(;;) {
4083 t = gtst(1, t);
4084 if (tok != TOK_LAND) {
4085 vseti(VT_JMPI, t);
4086 break;
4088 next();
4089 expr_or();
4094 static void expr_lor(void)
4096 int t;
4098 expr_land();
4099 if (tok == TOK_LOR) {
4100 t = 0;
4101 save_regs(1);
4102 for(;;) {
4103 t = gtst(0, t);
4104 if (tok != TOK_LOR) {
4105 vseti(VT_JMP, t);
4106 break;
4108 next();
4109 expr_land();
4114 /* XXX: better constant handling */
4115 static void expr_cond(void)
4117 int tt, u, r1, r2, rc, t1, t2, bt1, bt2;
4118 SValue sv;
4119 CType type, type1, type2;
4121 if (const_wanted) {
4122 expr_lor_const();
4123 if (tok == '?') {
4124 CType boolean;
4125 int c;
4126 boolean.t = VT_BOOL;
4127 vdup();
4128 gen_cast(&boolean);
4129 c = vtop->c.i;
4130 vpop();
4131 next();
4132 if (tok != ':' || !gnu_ext) {
4133 vpop();
4134 gexpr();
4136 if (!c)
4137 vpop();
4138 skip(':');
4139 expr_cond();
4140 if (c)
4141 vpop();
4143 } else {
4144 expr_lor();
4145 if (tok == '?') {
4146 next();
4147 if (vtop != vstack) {
4148 /* needed to avoid having different registers saved in
4149 each branch */
4150 if (is_float(vtop->type.t)) {
4151 rc = RC_FLOAT;
4152 #ifdef TCC_TARGET_X86_64
4153 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
4154 rc = RC_ST0;
4156 #endif
4158 else
4159 rc = RC_INT;
4160 gv(rc);
4161 save_regs(1);
4163 if (tok == ':' && gnu_ext) {
4164 gv_dup();
4165 tt = gtst(1, 0);
4166 } else {
4167 tt = gtst(1, 0);
4168 gexpr();
4170 type1 = vtop->type;
4171 sv = *vtop; /* save value to handle it later */
4172 vtop--; /* no vpop so that FP stack is not flushed */
4173 skip(':');
4174 u = gjmp(0);
4175 gsym(tt);
4176 expr_cond();
4177 type2 = vtop->type;
4179 t1 = type1.t;
4180 bt1 = t1 & VT_BTYPE;
4181 t2 = type2.t;
4182 bt2 = t2 & VT_BTYPE;
4183 /* cast operands to correct type according to ISOC rules */
4184 if (is_float(bt1) || is_float(bt2)) {
4185 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
4186 type.t = VT_LDOUBLE;
4187 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
4188 type.t = VT_DOUBLE;
4189 } else {
4190 type.t = VT_FLOAT;
4192 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
4193 /* cast to biggest op */
4194 type.t = VT_LLONG;
4195 /* convert to unsigned if it does not fit in a long long */
4196 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
4197 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
4198 type.t |= VT_UNSIGNED;
4199 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
4200 /* If one is a null ptr constant the result type
4201 is the other. */
4202 if (is_null_pointer (vtop))
4203 type = type1;
4204 else if (is_null_pointer (&sv))
4205 type = type2;
4206 /* XXX: test pointer compatibility, C99 has more elaborate
4207 rules here. */
4208 else
4209 type = type1;
4210 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
4211 /* XXX: test function pointer compatibility */
4212 type = bt1 == VT_FUNC ? type1 : type2;
4213 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
4214 /* XXX: test structure compatibility */
4215 type = bt1 == VT_STRUCT ? type1 : type2;
4216 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
4217 /* NOTE: as an extension, we accept void on only one side */
4218 type.t = VT_VOID;
4219 } else {
4220 /* integer operations */
4221 type.t = VT_INT;
4222 /* convert to unsigned if it does not fit in an integer */
4223 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
4224 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
4225 type.t |= VT_UNSIGNED;
4228 /* now we convert second operand */
4229 gen_cast(&type);
4230 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4231 gaddrof();
4232 rc = RC_INT;
4233 if (is_float(type.t)) {
4234 rc = RC_FLOAT;
4235 #ifdef TCC_TARGET_X86_64
4236 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
4237 rc = RC_ST0;
4239 #endif
4240 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
4241 /* for long longs, we use fixed registers to avoid having
4242 to handle a complicated move */
4243 rc = RC_IRET;
4246 r2 = gv(rc);
4247 /* this is horrible, but we must also convert first
4248 operand */
4249 tt = gjmp(0);
4250 gsym(u);
4251 /* put again first value and cast it */
4252 *vtop = sv;
4253 gen_cast(&type);
4254 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4255 gaddrof();
4256 r1 = gv(rc);
4257 move_reg(r2, r1);
4258 vtop->r = r2;
4259 gsym(tt);
4264 static void expr_eq(void)
4266 int t;
4268 expr_cond();
4269 if (tok == '=' ||
4270 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
4271 tok == TOK_A_XOR || tok == TOK_A_OR ||
4272 tok == TOK_A_SHL || tok == TOK_A_SAR) {
4273 test_lvalue();
4274 t = tok;
4275 next();
4276 if (t == '=') {
4277 expr_eq();
4278 } else {
4279 vdup();
4280 expr_eq();
4281 gen_op(t & 0x7f);
4283 vstore();
4287 ST_FUNC void gexpr(void)
4289 while (1) {
4290 expr_eq();
4291 if (tok != ',')
4292 break;
4293 vpop();
4294 next();
4298 /* parse an expression and return its type without any side effect. */
4299 static void expr_type(CType *type)
4301 int saved_nocode_wanted;
4303 saved_nocode_wanted = nocode_wanted;
4304 nocode_wanted = 1;
4305 gexpr();
4306 *type = vtop->type;
4307 vpop();
4308 nocode_wanted = saved_nocode_wanted;
4311 /* parse a unary expression and return its type without any side
4312 effect. */
4313 static void unary_type(CType *type)
4315 int a;
4317 a = nocode_wanted;
4318 nocode_wanted = 1;
4319 unary();
4320 *type = vtop->type;
4321 vpop();
4322 nocode_wanted = a;
4325 /* parse a constant expression and return value in vtop. */
4326 static void expr_const1(void)
4328 int a;
4329 a = const_wanted;
4330 const_wanted = 1;
4331 expr_cond();
4332 const_wanted = a;
4335 /* parse an integer constant and return its value. */
4336 ST_FUNC int expr_const(void)
4338 int c;
4339 expr_const1();
4340 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
4341 expect("constant expression");
4342 c = vtop->c.i;
4343 vpop();
4344 return c;
4347 /* return the label token if current token is a label, otherwise
4348 return zero */
4349 static int is_label(void)
4351 int last_tok;
4353 /* fast test first */
4354 if (tok < TOK_UIDENT)
4355 return 0;
4356 /* no need to save tokc because tok is an identifier */
4357 last_tok = tok;
4358 next();
4359 if (tok == ':') {
4360 next();
4361 return last_tok;
4362 } else {
4363 unget_tok(last_tok);
4364 return 0;
4368 static void label_or_decl(int l)
4370 int last_tok;
4372 /* fast test first */
4373 if (tok >= TOK_UIDENT)
4375 /* no need to save tokc because tok is an identifier */
4376 last_tok = tok;
4377 next();
4378 if (tok == ':') {
4379 unget_tok(last_tok);
4380 return;
4382 unget_tok(last_tok);
4384 decl(l);
4387 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
4388 int case_reg, int is_expr)
4390 int a, b, c, d;
4391 Sym *s, *frame_bottom;
4393 /* generate line number info */
4394 if (tcc_state->do_debug &&
4395 (last_line_num != file->line_num || last_ind != ind)) {
4396 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
4397 last_ind = ind;
4398 last_line_num = file->line_num;
4401 if (is_expr) {
4402 /* default return value is (void) */
4403 vpushi(0);
4404 vtop->type.t = VT_VOID;
4407 if (tok == TOK_IF) {
4408 /* if test */
4409 next();
4410 skip('(');
4411 gexpr();
4412 skip(')');
4413 a = gtst(1, 0);
4414 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4415 c = tok;
4416 if (c == TOK_ELSE) {
4417 next();
4418 d = gjmp(0);
4419 gsym(a);
4420 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4421 gsym(d); /* patch else jmp */
4422 } else
4423 gsym(a);
4424 } else if (tok == TOK_WHILE) {
4425 next();
4426 d = ind;
4427 skip('(');
4428 gexpr();
4429 skip(')');
4430 a = gtst(1, 0);
4431 b = 0;
4432 block(&a, &b, case_sym, def_sym, case_reg, 0);
4433 gjmp_addr(d);
4434 gsym(a);
4435 gsym_addr(b, d);
4436 } else if (tok == '{') {
4437 Sym *llabel;
4439 next();
4440 /* record local declaration stack position */
4441 s = local_stack;
4442 frame_bottom = sym_push2(&local_stack, SYM_FIELD, 0, 0);
4443 frame_bottom->next = scope_stack_bottom;
4444 scope_stack_bottom = frame_bottom;
4445 llabel = local_label_stack;
4446 /* handle local labels declarations */
4447 if (tok == TOK_LABEL) {
4448 next();
4449 for(;;) {
4450 if (tok < TOK_UIDENT)
4451 expect("label identifier");
4452 label_push(&local_label_stack, tok, LABEL_DECLARED);
4453 next();
4454 if (tok == ',') {
4455 next();
4456 } else {
4457 skip(';');
4458 break;
4462 while (tok != '}') {
4463 label_or_decl(VT_LOCAL);
4464 if (tok != '}') {
4465 if (is_expr)
4466 vpop();
4467 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
4470 /* pop locally defined labels */
4471 label_pop(&local_label_stack, llabel);
4472 if(is_expr) {
4473 /* XXX: this solution makes only valgrind happy...
4474 triggered by gcc.c-torture/execute/20000917-1.c */
4475 Sym *p;
4476 switch(vtop->type.t & VT_BTYPE) {
4477 case VT_PTR:
4478 case VT_STRUCT:
4479 case VT_ENUM:
4480 case VT_FUNC:
4481 for(p=vtop->type.ref;p;p=p->prev)
4482 if(p->prev==s)
4483 tcc_error("unsupported expression type");
4486 /* pop locally defined symbols */
4487 scope_stack_bottom = scope_stack_bottom->next;
4488 sym_pop(&local_stack, s);
4489 next();
4490 } else if (tok == TOK_RETURN) {
4491 next();
4492 if (tok != ';') {
4493 gexpr();
4494 gen_assign_cast(&func_vt);
4495 if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
4496 CType type, ret_type;
4497 int ret_align;
4498 if (gfunc_sret(&func_vt, &ret_type, &ret_align)) {
4499 /* if returning structure, must copy it to implicit
4500 first pointer arg location */
4501 type = func_vt;
4502 mk_pointer(&type);
4503 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
4504 indir();
4505 vswap();
4506 /* copy structure value to pointer */
4507 vstore();
4508 } else {
4509 /* returning structure packed into registers */
4510 int size, addr, align;
4511 size = type_size(&func_vt,&align);
4512 if ((vtop->r != (VT_LOCAL | VT_LVAL) || (vtop->c.i & (ret_align-1)))
4513 && (align & (ret_align-1))) {
4514 loc = (loc - size) & -align;
4515 addr = loc;
4516 type = func_vt;
4517 vset(&type, VT_LOCAL | VT_LVAL, addr);
4518 vswap();
4519 vstore();
4520 vset(&ret_type, VT_LOCAL | VT_LVAL, addr);
4522 vtop->type = ret_type;
4523 if (is_float(ret_type.t))
4524 gv(rc_fret(ret_type.t));
4525 else
4526 gv(RC_IRET);
4528 } else if (is_float(func_vt.t)) {
4529 gv(rc_fret(func_vt.t));
4530 } else {
4531 gv(RC_IRET);
4533 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
4535 skip(';');
4536 rsym = gjmp(rsym); /* jmp */
4537 } else if (tok == TOK_BREAK) {
4538 /* compute jump */
4539 if (!bsym)
4540 tcc_error("cannot break");
4541 *bsym = gjmp(*bsym);
4542 next();
4543 skip(';');
4544 } else if (tok == TOK_CONTINUE) {
4545 /* compute jump */
4546 if (!csym)
4547 tcc_error("cannot continue");
4548 *csym = gjmp(*csym);
4549 next();
4550 skip(';');
4551 } else if (tok == TOK_FOR) {
4552 int e;
4553 next();
4554 skip('(');
4555 s = local_stack;
4556 frame_bottom = sym_push2(&local_stack, SYM_FIELD, 0, 0);
4557 frame_bottom->next = scope_stack_bottom;
4558 scope_stack_bottom = frame_bottom;
4559 if (tok != ';') {
4560 /* c99 for-loop init decl? */
4561 if (!decl0(VT_LOCAL, 1)) {
4562 /* no, regular for-loop init expr */
4563 gexpr();
4564 vpop();
4567 skip(';');
4568 d = ind;
4569 c = ind;
4570 a = 0;
4571 b = 0;
4572 if (tok != ';') {
4573 gexpr();
4574 a = gtst(1, 0);
4576 skip(';');
4577 if (tok != ')') {
4578 e = gjmp(0);
4579 c = ind;
4580 gexpr();
4581 vpop();
4582 gjmp_addr(d);
4583 gsym(e);
4585 skip(')');
4586 block(&a, &b, case_sym, def_sym, case_reg, 0);
4587 gjmp_addr(c);
4588 gsym(a);
4589 gsym_addr(b, c);
4590 scope_stack_bottom = scope_stack_bottom->next;
4591 sym_pop(&local_stack, s);
4592 } else
4593 if (tok == TOK_DO) {
4594 next();
4595 a = 0;
4596 b = 0;
4597 d = ind;
4598 block(&a, &b, case_sym, def_sym, case_reg, 0);
4599 skip(TOK_WHILE);
4600 skip('(');
4601 gsym(b);
4602 gexpr();
4603 c = gtst(0, 0);
4604 gsym_addr(c, d);
4605 skip(')');
4606 gsym(a);
4607 skip(';');
4608 } else
4609 if (tok == TOK_SWITCH) {
4610 next();
4611 skip('(');
4612 gexpr();
4613 /* XXX: other types than integer */
4614 case_reg = gv(RC_INT);
4615 vpop();
4616 skip(')');
4617 a = 0;
4618 b = gjmp(0); /* jump to first case */
4619 c = 0;
4620 block(&a, csym, &b, &c, case_reg, 0);
4621 /* if no default, jmp after switch */
4622 if (c == 0)
4623 c = ind;
4624 /* default label */
4625 gsym_addr(b, c);
4626 /* break label */
4627 gsym(a);
4628 } else
4629 if (tok == TOK_CASE) {
4630 int v1, v2;
4631 if (!case_sym)
4632 expect("switch");
4633 next();
4634 v1 = expr_const();
4635 v2 = v1;
4636 if (gnu_ext && tok == TOK_DOTS) {
4637 next();
4638 v2 = expr_const();
4639 if (v2 < v1)
4640 tcc_warning("empty case range");
4642 /* since a case is like a label, we must skip it with a jmp */
4643 b = gjmp(0);
4644 gsym(*case_sym);
4645 vseti(case_reg, 0);
4646 vpushi(v1);
4647 if (v1 == v2) {
4648 gen_op(TOK_EQ);
4649 *case_sym = gtst(1, 0);
4650 } else {
4651 gen_op(TOK_GE);
4652 *case_sym = gtst(1, 0);
4653 vseti(case_reg, 0);
4654 vpushi(v2);
4655 gen_op(TOK_LE);
4656 *case_sym = gtst(1, *case_sym);
4658 gsym(b);
4659 skip(':');
4660 is_expr = 0;
4661 goto block_after_label;
4662 } else
4663 if (tok == TOK_DEFAULT) {
4664 next();
4665 skip(':');
4666 if (!def_sym)
4667 expect("switch");
4668 if (*def_sym)
4669 tcc_error("too many 'default'");
4670 *def_sym = ind;
4671 is_expr = 0;
4672 goto block_after_label;
4673 } else
4674 if (tok == TOK_GOTO) {
4675 next();
4676 if (tok == '*' && gnu_ext) {
4677 /* computed goto */
4678 next();
4679 gexpr();
4680 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
4681 expect("pointer");
4682 ggoto();
4683 } else if (tok >= TOK_UIDENT) {
4684 s = label_find(tok);
4685 /* put forward definition if needed */
4686 if (!s) {
4687 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
4688 } else {
4689 if (s->r == LABEL_DECLARED)
4690 s->r = LABEL_FORWARD;
4692 /* label already defined */
4693 if (s->r & LABEL_FORWARD)
4694 s->jnext = gjmp(s->jnext);
4695 else
4696 gjmp_addr(s->jnext);
4697 next();
4698 } else {
4699 expect("label identifier");
4701 skip(';');
4702 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
4703 asm_instr();
4704 } else {
4705 b = is_label();
4706 if (b) {
4707 /* label case */
4708 s = label_find(b);
4709 if (s) {
4710 if (s->r == LABEL_DEFINED)
4711 tcc_error("duplicate label '%s'", get_tok_str(s->v, NULL));
4712 gsym(s->jnext);
4713 s->r = LABEL_DEFINED;
4714 } else {
4715 s = label_push(&global_label_stack, b, LABEL_DEFINED);
4717 s->jnext = ind;
4718 /* we accept this, but it is a mistake */
4719 block_after_label:
4720 if (tok == '}') {
4721 tcc_warning("deprecated use of label at end of compound statement");
4722 } else {
4723 if (is_expr)
4724 vpop();
4725 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
4727 } else {
4728 /* expression case */
4729 if (tok != ';') {
4730 if (is_expr) {
4731 vpop();
4732 gexpr();
4733 } else {
4734 gexpr();
4735 vpop();
4738 skip(';');
4743 /* t is the array or struct type. c is the array or struct
4744 address. cur_index/cur_field is the pointer to the current
4745 value. 'size_only' is true if only size info is needed (only used
4746 in arrays) */
4747 static void decl_designator(CType *type, Section *sec, unsigned long c,
4748 int *cur_index, Sym **cur_field,
4749 int size_only)
4751 Sym *s, *f;
4752 int notfirst, index, index_last, align, l, nb_elems, elem_size;
4753 CType type1;
4755 notfirst = 0;
4756 elem_size = 0;
4757 nb_elems = 1;
4758 if (gnu_ext && (l = is_label()) != 0)
4759 goto struct_field;
4760 while (tok == '[' || tok == '.') {
4761 if (tok == '[') {
4762 if (!(type->t & VT_ARRAY))
4763 expect("array type");
4764 s = type->ref;
4765 next();
4766 index = expr_const();
4767 if (index < 0 || (s->c >= 0 && index >= s->c))
4768 expect("invalid index");
4769 if (tok == TOK_DOTS && gnu_ext) {
4770 next();
4771 index_last = expr_const();
4772 if (index_last < 0 ||
4773 (s->c >= 0 && index_last >= s->c) ||
4774 index_last < index)
4775 expect("invalid index");
4776 } else {
4777 index_last = index;
4779 skip(']');
4780 if (!notfirst)
4781 *cur_index = index_last;
4782 type = pointed_type(type);
4783 elem_size = type_size(type, &align);
4784 c += index * elem_size;
4785 /* NOTE: we only support ranges for last designator */
4786 nb_elems = index_last - index + 1;
4787 if (nb_elems != 1) {
4788 notfirst = 1;
4789 break;
4791 } else {
4792 next();
4793 l = tok;
4794 next();
4795 struct_field:
4796 if ((type->t & VT_BTYPE) != VT_STRUCT)
4797 expect("struct/union type");
4798 s = type->ref;
4799 l |= SYM_FIELD;
4800 f = s->next;
4801 while (f) {
4802 if (f->v == l)
4803 break;
4804 f = f->next;
4806 if (!f)
4807 expect("field");
4808 if (!notfirst)
4809 *cur_field = f;
4810 /* XXX: fix this mess by using explicit storage field */
4811 type1 = f->type;
4812 type1.t |= (type->t & ~VT_TYPE);
4813 type = &type1;
4814 c += f->c;
4816 notfirst = 1;
4818 if (notfirst) {
4819 if (tok == '=') {
4820 next();
4821 } else {
4822 if (!gnu_ext)
4823 expect("=");
4825 } else {
4826 if (type->t & VT_ARRAY) {
4827 index = *cur_index;
4828 type = pointed_type(type);
4829 c += index * type_size(type, &align);
4830 } else {
4831 f = *cur_field;
4832 if (!f)
4833 tcc_error("too many field init");
4834 /* XXX: fix this mess by using explicit storage field */
4835 type1 = f->type;
4836 type1.t |= (type->t & ~VT_TYPE);
4837 type = &type1;
4838 c += f->c;
4841 decl_initializer(type, sec, c, 0, size_only);
4843 /* XXX: make it more general */
4844 if (!size_only && nb_elems > 1) {
4845 unsigned long c_end;
4846 uint8_t *src, *dst;
4847 int i;
4849 if (!sec)
4850 tcc_error("range init not supported yet for dynamic storage");
4851 c_end = c + nb_elems * elem_size;
4852 if (c_end > sec->data_allocated)
4853 section_realloc(sec, c_end);
4854 src = sec->data + c;
4855 dst = src;
4856 for(i = 1; i < nb_elems; i++) {
4857 dst += elem_size;
4858 memcpy(dst, src, elem_size);
4863 #define EXPR_VAL 0
4864 #define EXPR_CONST 1
4865 #define EXPR_ANY 2
4867 /* store a value or an expression directly in global data or in local array */
4868 static void init_putv(CType *type, Section *sec, unsigned long c,
4869 int v, int expr_type)
4871 int saved_global_expr, bt, bit_pos, bit_size;
4872 void *ptr;
4873 unsigned long long bit_mask;
4874 CType dtype;
4876 switch(expr_type) {
4877 case EXPR_VAL:
4878 vpushi(v);
4879 break;
4880 case EXPR_CONST:
4881 /* compound literals must be allocated globally in this case */
4882 saved_global_expr = global_expr;
4883 global_expr = 1;
4884 expr_const1();
4885 global_expr = saved_global_expr;
4886 /* NOTE: symbols are accepted */
4887 if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
4888 tcc_error("initializer element is not constant");
4889 break;
4890 case EXPR_ANY:
4891 expr_eq();
4892 break;
4895 dtype = *type;
4896 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
4898 if (sec) {
4899 /* XXX: not portable */
4900 /* XXX: generate error if incorrect relocation */
4901 gen_assign_cast(&dtype);
4902 bt = type->t & VT_BTYPE;
4903 /* we'll write at most 12 bytes */
4904 if (c + 12 > sec->data_allocated) {
4905 section_realloc(sec, c + 12);
4907 ptr = sec->data + c;
4908 /* XXX: make code faster ? */
4909 if (!(type->t & VT_BITFIELD)) {
4910 bit_pos = 0;
4911 bit_size = 32;
4912 bit_mask = -1LL;
4913 } else {
4914 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
4915 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
4916 bit_mask = (1LL << bit_size) - 1;
4918 if ((vtop->r & VT_SYM) &&
4919 (bt == VT_BYTE ||
4920 bt == VT_SHORT ||
4921 bt == VT_DOUBLE ||
4922 bt == VT_LDOUBLE ||
4923 bt == VT_LLONG ||
4924 (bt == VT_INT && bit_size != 32)))
4925 tcc_error("initializer element is not computable at load time");
4926 switch(bt) {
4927 case VT_BOOL:
4928 vtop->c.i = (vtop->c.i != 0);
4929 case VT_BYTE:
4930 *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
4931 break;
4932 case VT_SHORT:
4933 *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
4934 break;
4935 case VT_DOUBLE:
4936 *(double *)ptr = vtop->c.d;
4937 break;
4938 case VT_LDOUBLE:
4939 *(long double *)ptr = vtop->c.ld;
4940 break;
4941 case VT_LLONG:
4942 *(long long *)ptr |= (vtop->c.ll & bit_mask) << bit_pos;
4943 break;
4944 default:
4945 if (vtop->r & VT_SYM) {
4946 greloc(sec, vtop->sym, c, R_DATA_PTR);
4948 *(int *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
4949 break;
4951 vtop--;
4952 } else {
4953 vset(&dtype, VT_LOCAL|VT_LVAL, c);
4954 vswap();
4955 vstore();
4956 vpop();
4960 /* put zeros for variable based init */
4961 static void init_putz(CType *t, Section *sec, unsigned long c, int size)
4963 if (sec) {
4964 /* nothing to do because globals are already set to zero */
4965 } else {
4966 vpush_global_sym(&func_old_type, TOK_memset);
4967 vseti(VT_LOCAL, c);
4968 vpushi(0);
4969 vpushi(size);
4970 gfunc_call(3);
4974 /* 't' contains the type and storage info. 'c' is the offset of the
4975 object in section 'sec'. If 'sec' is NULL, it means stack based
4976 allocation. 'first' is true if array '{' must be read (multi
4977 dimension implicit array init handling). 'size_only' is true if
4978 size only evaluation is wanted (only for arrays). */
4979 static void decl_initializer(CType *type, Section *sec, unsigned long c,
4980 int first, int size_only)
4982 int index, array_length, n, no_oblock, nb, parlevel, parlevel1, i;
4983 int size1, align1, expr_type;
4984 Sym *s, *f;
4985 CType *t1;
4987 if (type->t & VT_VLA) {
4988 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
4989 int a;
4990 CValue retcval;
4992 vpush_global_sym(&func_old_type, TOK_alloca);
4993 vla_runtime_type_size(type, &a);
4994 gfunc_call(1);
4996 /* return value */
4997 retcval.i = 0;
4998 vsetc(type, REG_IRET, &retcval);
4999 vset(type, VT_LOCAL|VT_LVAL, c);
5000 vswap();
5001 vstore();
5002 vpop();
5003 #else
5004 tcc_error("variable length arrays unsupported for this target");
5005 #endif
5006 } else if (type->t & VT_ARRAY) {
5007 s = type->ref;
5008 n = s->c;
5009 array_length = 0;
5010 t1 = pointed_type(type);
5011 size1 = type_size(t1, &align1);
5013 no_oblock = 1;
5014 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
5015 tok == '{') {
5016 if (tok != '{')
5017 tcc_error("character array initializer must be a literal,"
5018 " optionally enclosed in braces");
5019 skip('{');
5020 no_oblock = 0;
5023 /* only parse strings here if correct type (otherwise: handle
5024 them as ((w)char *) expressions */
5025 if ((tok == TOK_LSTR &&
5026 #ifdef TCC_TARGET_PE
5027 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
5028 #else
5029 (t1->t & VT_BTYPE) == VT_INT
5030 #endif
5031 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
5032 while (tok == TOK_STR || tok == TOK_LSTR) {
5033 int cstr_len, ch;
5034 CString *cstr;
5036 cstr = tokc.cstr;
5037 /* compute maximum number of chars wanted */
5038 if (tok == TOK_STR)
5039 cstr_len = cstr->size;
5040 else
5041 cstr_len = cstr->size / sizeof(nwchar_t);
5042 cstr_len--;
5043 nb = cstr_len;
5044 if (n >= 0 && nb > (n - array_length))
5045 nb = n - array_length;
5046 if (!size_only) {
5047 if (cstr_len > nb)
5048 tcc_warning("initializer-string for array is too long");
5049 /* in order to go faster for common case (char
5050 string in global variable, we handle it
5051 specifically */
5052 if (sec && tok == TOK_STR && size1 == 1) {
5053 memcpy(sec->data + c + array_length, cstr->data, nb);
5054 } else {
5055 for(i=0;i<nb;i++) {
5056 if (tok == TOK_STR)
5057 ch = ((unsigned char *)cstr->data)[i];
5058 else
5059 ch = ((nwchar_t *)cstr->data)[i];
5060 init_putv(t1, sec, c + (array_length + i) * size1,
5061 ch, EXPR_VAL);
5065 array_length += nb;
5066 next();
5068 /* only add trailing zero if enough storage (no
5069 warning in this case since it is standard) */
5070 if (n < 0 || array_length < n) {
5071 if (!size_only) {
5072 init_putv(t1, sec, c + (array_length * size1), 0, EXPR_VAL);
5074 array_length++;
5076 } else {
5077 index = 0;
5078 while (tok != '}') {
5079 decl_designator(type, sec, c, &index, NULL, size_only);
5080 if (n >= 0 && index >= n)
5081 tcc_error("index too large");
5082 /* must put zero in holes (note that doing it that way
5083 ensures that it even works with designators) */
5084 if (!size_only && array_length < index) {
5085 init_putz(t1, sec, c + array_length * size1,
5086 (index - array_length) * size1);
5088 index++;
5089 if (index > array_length)
5090 array_length = index;
5091 /* special test for multi dimensional arrays (may not
5092 be strictly correct if designators are used at the
5093 same time) */
5094 if (index >= n && no_oblock)
5095 break;
5096 if (tok == '}')
5097 break;
5098 skip(',');
5101 if (!no_oblock)
5102 skip('}');
5103 /* put zeros at the end */
5104 if (!size_only && n >= 0 && array_length < n) {
5105 init_putz(t1, sec, c + array_length * size1,
5106 (n - array_length) * size1);
5108 /* patch type size if needed */
5109 if (n < 0)
5110 s->c = array_length;
5111 } else if ((type->t & VT_BTYPE) == VT_STRUCT &&
5112 (sec || !first || tok == '{')) {
5113 int par_count;
5115 /* NOTE: the previous test is a specific case for automatic
5116 struct/union init */
5117 /* XXX: union needs only one init */
5119 /* XXX: this test is incorrect for local initializers
5120 beginning with ( without {. It would be much more difficult
5121 to do it correctly (ideally, the expression parser should
5122 be used in all cases) */
5123 par_count = 0;
5124 if (tok == '(') {
5125 AttributeDef ad1;
5126 CType type1;
5127 next();
5128 while (tok == '(') {
5129 par_count++;
5130 next();
5132 if (!parse_btype(&type1, &ad1))
5133 expect("cast");
5134 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
5135 #if 0
5136 if (!is_assignable_types(type, &type1))
5137 tcc_error("invalid type for cast");
5138 #endif
5139 skip(')');
5141 no_oblock = 1;
5142 if (first || tok == '{') {
5143 skip('{');
5144 no_oblock = 0;
5146 s = type->ref;
5147 f = s->next;
5148 array_length = 0;
5149 index = 0;
5150 n = s->c;
5151 while (tok != '}') {
5152 decl_designator(type, sec, c, NULL, &f, size_only);
5153 index = f->c;
5154 if (!size_only && array_length < index) {
5155 init_putz(type, sec, c + array_length,
5156 index - array_length);
5158 index = index + type_size(&f->type, &align1);
5159 if (index > array_length)
5160 array_length = index;
5162 /* gr: skip fields from same union - ugly. */
5163 while (f->next) {
5164 ///printf("index: %2d %08x -- %2d %08x\n", f->c, f->type.t, f->next->c, f->next->type.t);
5165 /* test for same offset */
5166 if (f->next->c != f->c)
5167 break;
5168 /* if yes, test for bitfield shift */
5169 if ((f->type.t & VT_BITFIELD) && (f->next->type.t & VT_BITFIELD)) {
5170 int bit_pos_1 = (f->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5171 int bit_pos_2 = (f->next->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5172 //printf("bitfield %d %d\n", bit_pos_1, bit_pos_2);
5173 if (bit_pos_1 != bit_pos_2)
5174 break;
5176 f = f->next;
5179 f = f->next;
5180 if (no_oblock && f == NULL)
5181 break;
5182 if (tok == '}')
5183 break;
5184 skip(',');
5186 /* put zeros at the end */
5187 if (!size_only && array_length < n) {
5188 init_putz(type, sec, c + array_length,
5189 n - array_length);
5191 if (!no_oblock)
5192 skip('}');
5193 while (par_count) {
5194 skip(')');
5195 par_count--;
5197 } else if (tok == '{') {
5198 next();
5199 decl_initializer(type, sec, c, first, size_only);
5200 skip('}');
5201 } else if (size_only) {
5202 /* just skip expression */
5203 parlevel = parlevel1 = 0;
5204 while ((parlevel > 0 || parlevel1 > 0 ||
5205 (tok != '}' && tok != ',')) && tok != -1) {
5206 if (tok == '(')
5207 parlevel++;
5208 else if (tok == ')')
5209 parlevel--;
5210 else if (tok == '{')
5211 parlevel1++;
5212 else if (tok == '}')
5213 parlevel1--;
5214 next();
5216 } else {
5217 /* currently, we always use constant expression for globals
5218 (may change for scripting case) */
5219 expr_type = EXPR_CONST;
5220 if (!sec)
5221 expr_type = EXPR_ANY;
5222 init_putv(type, sec, c, 0, expr_type);
5226 /* parse an initializer for type 't' if 'has_init' is non zero, and
5227 allocate space in local or global data space ('r' is either
5228 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
5229 variable 'v' with an associated name represented by 'asm_label' of
5230 scope 'scope' is declared before initializers are parsed. If 'v' is
5231 zero, then a reference to the new object is put in the value stack.
5232 If 'has_init' is 2, a special parsing is done to handle string
5233 constants. */
5234 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
5235 int has_init, int v, char *asm_label,
5236 int scope)
5238 int size, align, addr, data_offset;
5239 int level;
5240 ParseState saved_parse_state = {0};
5241 TokenString init_str;
5242 Section *sec;
5243 Sym *flexible_array;
5245 flexible_array = NULL;
5246 if ((type->t & VT_BTYPE) == VT_STRUCT) {
5247 Sym *field;
5248 field = type->ref;
5249 while (field && field->next)
5250 field = field->next;
5251 if (field->type.t & VT_ARRAY && field->type.ref->c < 0)
5252 flexible_array = field;
5255 size = type_size(type, &align);
5256 /* If unknown size, we must evaluate it before
5257 evaluating initializers because
5258 initializers can generate global data too
5259 (e.g. string pointers or ISOC99 compound
5260 literals). It also simplifies local
5261 initializers handling */
5262 tok_str_new(&init_str);
5263 if (size < 0 || (flexible_array && has_init)) {
5264 if (!has_init)
5265 tcc_error("unknown type size");
5266 /* get all init string */
5267 if (has_init == 2) {
5268 /* only get strings */
5269 while (tok == TOK_STR || tok == TOK_LSTR) {
5270 tok_str_add_tok(&init_str);
5271 next();
5273 } else {
5274 level = 0;
5275 while (level > 0 || (tok != ',' && tok != ';')) {
5276 if (tok < 0)
5277 tcc_error("unexpected end of file in initializer");
5278 tok_str_add_tok(&init_str);
5279 if (tok == '{')
5280 level++;
5281 else if (tok == '}') {
5282 level--;
5283 if (level <= 0) {
5284 next();
5285 break;
5288 next();
5291 tok_str_add(&init_str, -1);
5292 tok_str_add(&init_str, 0);
5294 /* compute size */
5295 save_parse_state(&saved_parse_state);
5297 macro_ptr = init_str.str;
5298 next();
5299 decl_initializer(type, NULL, 0, 1, 1);
5300 /* prepare second initializer parsing */
5301 macro_ptr = init_str.str;
5302 next();
5304 /* if still unknown size, error */
5305 size = type_size(type, &align);
5306 if (size < 0)
5307 tcc_error("unknown type size");
5309 if (flexible_array)
5310 size += flexible_array->type.ref->c * pointed_size(&flexible_array->type);
5311 /* take into account specified alignment if bigger */
5312 if (ad->aligned) {
5313 if (ad->aligned > align)
5314 align = ad->aligned;
5315 } else if (ad->packed) {
5316 align = 1;
5318 if ((r & VT_VALMASK) == VT_LOCAL) {
5319 sec = NULL;
5320 #ifdef CONFIG_TCC_BCHECK
5321 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5322 loc--;
5324 #endif
5325 loc = (loc - size) & -align;
5326 addr = loc;
5327 #ifdef CONFIG_TCC_BCHECK
5328 /* handles bounds */
5329 /* XXX: currently, since we do only one pass, we cannot track
5330 '&' operators, so we add only arrays */
5331 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5332 unsigned long *bounds_ptr;
5333 /* add padding between regions */
5334 loc--;
5335 /* then add local bound info */
5336 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(unsigned long));
5337 bounds_ptr[0] = addr;
5338 bounds_ptr[1] = size;
5340 #endif
5341 if (v) {
5342 /* local variable */
5343 sym_push(v, type, r, addr);
5344 } else {
5345 /* push local reference */
5346 vset(type, r, addr);
5348 } else {
5349 Sym *sym;
5351 sym = NULL;
5352 if (v && scope == VT_CONST) {
5353 /* see if the symbol was already defined */
5354 sym = sym_find(v);
5355 if (sym) {
5356 if (!is_compatible_types(&sym->type, type))
5357 tcc_error("incompatible types for redefinition of '%s'",
5358 get_tok_str(v, NULL));
5359 if (sym->type.t & VT_EXTERN) {
5360 /* if the variable is extern, it was not allocated */
5361 sym->type.t &= ~VT_EXTERN;
5362 /* set array size if it was ommited in extern
5363 declaration */
5364 if ((sym->type.t & VT_ARRAY) &&
5365 sym->type.ref->c < 0 &&
5366 type->ref->c >= 0)
5367 sym->type.ref->c = type->ref->c;
5368 } else {
5369 /* we accept several definitions of the same
5370 global variable. this is tricky, because we
5371 must play with the SHN_COMMON type of the symbol */
5372 /* XXX: should check if the variable was already
5373 initialized. It is incorrect to initialized it
5374 twice */
5375 /* no init data, we won't add more to the symbol */
5376 if (!has_init)
5377 goto no_alloc;
5382 /* allocate symbol in corresponding section */
5383 sec = ad->section;
5384 if (!sec) {
5385 if (has_init)
5386 sec = data_section;
5387 else if (tcc_state->nocommon)
5388 sec = bss_section;
5390 if (sec) {
5391 data_offset = sec->data_offset;
5392 data_offset = (data_offset + align - 1) & -align;
5393 addr = data_offset;
5394 /* very important to increment global pointer at this time
5395 because initializers themselves can create new initializers */
5396 data_offset += size;
5397 #ifdef CONFIG_TCC_BCHECK
5398 /* add padding if bound check */
5399 if (tcc_state->do_bounds_check)
5400 data_offset++;
5401 #endif
5402 sec->data_offset = data_offset;
5403 /* allocate section space to put the data */
5404 if (sec->sh_type != SHT_NOBITS &&
5405 data_offset > sec->data_allocated)
5406 section_realloc(sec, data_offset);
5407 /* align section if needed */
5408 if (align > sec->sh_addralign)
5409 sec->sh_addralign = align;
5410 } else {
5411 addr = 0; /* avoid warning */
5414 if (v) {
5415 if (scope != VT_CONST || !sym) {
5416 sym = sym_push(v, type, r | VT_SYM, 0);
5417 sym->asm_label = asm_label;
5419 /* update symbol definition */
5420 if (sec) {
5421 put_extern_sym(sym, sec, addr, size);
5422 } else {
5423 ElfW(Sym) *esym;
5424 /* put a common area */
5425 put_extern_sym(sym, NULL, align, size);
5426 /* XXX: find a nicer way */
5427 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
5428 esym->st_shndx = SHN_COMMON;
5430 } else {
5431 CValue cval;
5433 /* push global reference */
5434 sym = get_sym_ref(type, sec, addr, size);
5435 cval.ul = 0;
5436 vsetc(type, VT_CONST | VT_SYM, &cval);
5437 vtop->sym = sym;
5439 /* patch symbol weakness */
5440 if (type->t & VT_WEAK)
5441 weaken_symbol(sym);
5442 #ifdef CONFIG_TCC_BCHECK
5443 /* handles bounds now because the symbol must be defined
5444 before for the relocation */
5445 if (tcc_state->do_bounds_check) {
5446 unsigned long *bounds_ptr;
5448 greloc(bounds_section, sym, bounds_section->data_offset, R_DATA_PTR);
5449 /* then add global bound info */
5450 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(long));
5451 bounds_ptr[0] = 0; /* relocated */
5452 bounds_ptr[1] = size;
5454 #endif
5456 if (has_init || (type->t & VT_VLA)) {
5457 decl_initializer(type, sec, addr, 1, 0);
5458 /* restore parse state if needed */
5459 if (init_str.str) {
5460 tok_str_free(init_str.str);
5461 restore_parse_state(&saved_parse_state);
5463 /* patch flexible array member size back to -1, */
5464 /* for possible subsequent similar declarations */
5465 if (flexible_array)
5466 flexible_array->type.ref->c = -1;
5468 no_alloc: ;
5471 static void put_func_debug(Sym *sym)
5473 char buf[512];
5475 /* stabs info */
5476 /* XXX: we put here a dummy type */
5477 snprintf(buf, sizeof(buf), "%s:%c1",
5478 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
5479 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
5480 cur_text_section, sym->c);
5481 /* //gr gdb wants a line at the function */
5482 put_stabn(N_SLINE, 0, file->line_num, 0);
5483 last_ind = 0;
5484 last_line_num = 0;
5487 /* parse an old style function declaration list */
5488 /* XXX: check multiple parameter */
5489 static void func_decl_list(Sym *func_sym)
5491 AttributeDef ad;
5492 int v;
5493 Sym *s;
5494 CType btype, type;
5496 /* parse each declaration */
5497 while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF &&
5498 tok != TOK_ASM1 && tok != TOK_ASM2 && tok != TOK_ASM3) {
5499 if (!parse_btype(&btype, &ad))
5500 expect("declaration list");
5501 if (((btype.t & VT_BTYPE) == VT_ENUM ||
5502 (btype.t & VT_BTYPE) == VT_STRUCT) &&
5503 tok == ';') {
5504 /* we accept no variable after */
5505 } else {
5506 for(;;) {
5507 type = btype;
5508 type_decl(&type, &ad, &v, TYPE_DIRECT);
5509 /* find parameter in function parameter list */
5510 s = func_sym->next;
5511 while (s != NULL) {
5512 if ((s->v & ~SYM_FIELD) == v)
5513 goto found;
5514 s = s->next;
5516 tcc_error("declaration for parameter '%s' but no such parameter",
5517 get_tok_str(v, NULL));
5518 found:
5519 /* check that no storage specifier except 'register' was given */
5520 if (type.t & VT_STORAGE)
5521 tcc_error("storage class specified for '%s'", get_tok_str(v, NULL));
5522 convert_parameter_type(&type);
5523 /* we can add the type (NOTE: it could be local to the function) */
5524 s->type = type;
5525 /* accept other parameters */
5526 if (tok == ',')
5527 next();
5528 else
5529 break;
5532 skip(';');
5536 /* parse a function defined by symbol 'sym' and generate its code in
5537 'cur_text_section' */
5538 static void gen_function(Sym *sym)
5540 int saved_nocode_wanted = nocode_wanted;
5541 nocode_wanted = 0;
5542 ind = cur_text_section->data_offset;
5543 /* NOTE: we patch the symbol size later */
5544 put_extern_sym(sym, cur_text_section, ind, 0);
5545 funcname = get_tok_str(sym->v, NULL);
5546 func_ind = ind;
5547 /* put debug symbol */
5548 if (tcc_state->do_debug)
5549 put_func_debug(sym);
5550 /* push a dummy symbol to enable local sym storage */
5551 sym_push2(&local_stack, SYM_FIELD, 0, 0);
5552 gfunc_prolog(&sym->type);
5553 rsym = 0;
5554 block(NULL, NULL, NULL, NULL, 0, 0);
5555 gsym(rsym);
5556 gfunc_epilog();
5557 cur_text_section->data_offset = ind;
5558 label_pop(&global_label_stack, NULL);
5559 /* reset local stack */
5560 scope_stack_bottom = NULL;
5561 sym_pop(&local_stack, NULL);
5562 /* end of function */
5563 /* patch symbol size */
5564 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
5565 ind - func_ind;
5566 /* patch symbol weakness (this definition overrules any prototype) */
5567 if (sym->type.t & VT_WEAK)
5568 weaken_symbol(sym);
5569 if (tcc_state->do_debug) {
5570 put_stabn(N_FUN, 0, 0, ind - func_ind);
5572 /* It's better to crash than to generate wrong code */
5573 cur_text_section = NULL;
5574 funcname = ""; /* for safety */
5575 func_vt.t = VT_VOID; /* for safety */
5576 ind = 0; /* for safety */
5577 nocode_wanted = saved_nocode_wanted;
5580 ST_FUNC void gen_inline_functions(void)
5582 Sym *sym;
5583 int *str, inline_generated, i;
5584 struct InlineFunc *fn;
5586 /* iterate while inline function are referenced */
5587 for(;;) {
5588 inline_generated = 0;
5589 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
5590 fn = tcc_state->inline_fns[i];
5591 sym = fn->sym;
5592 if (sym && sym->c) {
5593 /* the function was used: generate its code and
5594 convert it to a normal function */
5595 str = fn->token_str;
5596 fn->sym = NULL;
5597 if (file)
5598 pstrcpy(file->filename, sizeof file->filename, fn->filename);
5599 sym->r = VT_SYM | VT_CONST;
5600 sym->type.t &= ~VT_INLINE;
5602 macro_ptr = str;
5603 next();
5604 cur_text_section = text_section;
5605 gen_function(sym);
5606 macro_ptr = NULL; /* fail safe */
5608 inline_generated = 1;
5611 if (!inline_generated)
5612 break;
5614 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
5615 fn = tcc_state->inline_fns[i];
5616 str = fn->token_str;
5617 tok_str_free(str);
5619 dynarray_reset(&tcc_state->inline_fns, &tcc_state->nb_inline_fns);
5622 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
5623 static int decl0(int l, int is_for_loop_init)
5625 int v, has_init, r;
5626 CType type, btype;
5627 Sym *sym;
5628 AttributeDef ad;
5630 while (1) {
5631 if (!parse_btype(&btype, &ad)) {
5632 if (is_for_loop_init)
5633 return 0;
5634 /* skip redundant ';' */
5635 /* XXX: find more elegant solution */
5636 if (tok == ';') {
5637 next();
5638 continue;
5640 if (l == VT_CONST &&
5641 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
5642 /* global asm block */
5643 asm_global_instr();
5644 continue;
5646 /* special test for old K&R protos without explicit int
5647 type. Only accepted when defining global data */
5648 if (l == VT_LOCAL || tok < TOK_DEFINE)
5649 break;
5650 btype.t = VT_INT;
5652 if (((btype.t & VT_BTYPE) == VT_ENUM ||
5653 (btype.t & VT_BTYPE) == VT_STRUCT) &&
5654 tok == ';') {
5655 /* we accept no variable after */
5656 next();
5657 continue;
5659 while (1) { /* iterate thru each declaration */
5660 char *asm_label; // associated asm label
5661 type = btype;
5662 type_decl(&type, &ad, &v, TYPE_DIRECT);
5663 #if 0
5665 char buf[500];
5666 type_to_str(buf, sizeof(buf), t, get_tok_str(v, NULL));
5667 printf("type = '%s'\n", buf);
5669 #endif
5670 if ((type.t & VT_BTYPE) == VT_FUNC) {
5671 if ((type.t & VT_STATIC) && (l == VT_LOCAL)) {
5672 tcc_error("function without file scope cannot be static");
5674 /* if old style function prototype, we accept a
5675 declaration list */
5676 sym = type.ref;
5677 if (sym->c == FUNC_OLD)
5678 func_decl_list(sym);
5681 asm_label = NULL;
5682 if (gnu_ext && (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
5683 CString astr;
5685 asm_label_instr(&astr);
5686 asm_label = tcc_strdup(astr.data);
5687 cstr_free(&astr);
5689 /* parse one last attribute list, after asm label */
5690 parse_attribute(&ad);
5693 if (ad.weak)
5694 type.t |= VT_WEAK;
5695 #ifdef TCC_TARGET_PE
5696 if (ad.func_import)
5697 type.t |= VT_IMPORT;
5698 if (ad.func_export)
5699 type.t |= VT_EXPORT;
5700 #endif
5701 if (tok == '{') {
5702 if (l == VT_LOCAL)
5703 tcc_error("cannot use local functions");
5704 if ((type.t & VT_BTYPE) != VT_FUNC)
5705 expect("function definition");
5707 /* reject abstract declarators in function definition */
5708 sym = type.ref;
5709 while ((sym = sym->next) != NULL)
5710 if (!(sym->v & ~SYM_FIELD))
5711 expect("identifier");
5713 /* XXX: cannot do better now: convert extern line to static inline */
5714 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
5715 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
5717 sym = sym_find(v);
5718 if (sym) {
5719 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
5720 goto func_error1;
5722 r = sym->type.ref->r;
5723 /* use func_call from prototype if not defined */
5724 if (FUNC_CALL(r) != FUNC_CDECL
5725 && FUNC_CALL(type.ref->r) == FUNC_CDECL)
5726 FUNC_CALL(type.ref->r) = FUNC_CALL(r);
5728 /* use export from prototype */
5729 if (FUNC_EXPORT(r))
5730 FUNC_EXPORT(type.ref->r) = 1;
5732 /* use static from prototype */
5733 if (sym->type.t & VT_STATIC)
5734 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
5736 if (!is_compatible_types(&sym->type, &type)) {
5737 func_error1:
5738 tcc_error("incompatible types for redefinition of '%s'",
5739 get_tok_str(v, NULL));
5741 /* if symbol is already defined, then put complete type */
5742 sym->type = type;
5743 } else {
5744 /* put function symbol */
5745 sym = global_identifier_push(v, type.t, 0);
5746 sym->type.ref = type.ref;
5749 /* static inline functions are just recorded as a kind
5750 of macro. Their code will be emitted at the end of
5751 the compilation unit only if they are used */
5752 if ((type.t & (VT_INLINE | VT_STATIC)) ==
5753 (VT_INLINE | VT_STATIC)) {
5754 TokenString func_str;
5755 int block_level;
5756 struct InlineFunc *fn;
5757 const char *filename;
5759 tok_str_new(&func_str);
5761 block_level = 0;
5762 for(;;) {
5763 int t;
5764 if (tok == TOK_EOF)
5765 tcc_error("unexpected end of file");
5766 tok_str_add_tok(&func_str);
5767 t = tok;
5768 next();
5769 if (t == '{') {
5770 block_level++;
5771 } else if (t == '}') {
5772 block_level--;
5773 if (block_level == 0)
5774 break;
5777 tok_str_add(&func_str, -1);
5778 tok_str_add(&func_str, 0);
5779 filename = file ? file->filename : "";
5780 fn = tcc_malloc(sizeof *fn + strlen(filename));
5781 strcpy(fn->filename, filename);
5782 fn->sym = sym;
5783 fn->token_str = func_str.str;
5784 dynarray_add((void ***)&tcc_state->inline_fns, &tcc_state->nb_inline_fns, fn);
5786 } else {
5787 /* compute text section */
5788 cur_text_section = ad.section;
5789 if (!cur_text_section)
5790 cur_text_section = text_section;
5791 sym->r = VT_SYM | VT_CONST;
5792 gen_function(sym);
5794 break;
5795 } else {
5796 if (btype.t & VT_TYPEDEF) {
5797 /* save typedefed type */
5798 /* XXX: test storage specifiers ? */
5799 sym = sym_push(v, &type, INT_ATTR(&ad), 0);
5800 sym->type.t |= VT_TYPEDEF;
5801 } else {
5802 r = 0;
5803 if ((type.t & VT_BTYPE) == VT_FUNC) {
5804 /* external function definition */
5805 /* specific case for func_call attribute */
5806 type.ref->r = INT_ATTR(&ad);
5807 } else if (!(type.t & VT_ARRAY)) {
5808 /* not lvalue if array */
5809 r |= lvalue_type(type.t);
5811 has_init = (tok == '=');
5812 if (has_init && (type.t & VT_VLA))
5813 tcc_error("Variable length array cannot be initialized");
5814 if ((btype.t & VT_EXTERN) || ((type.t & VT_BTYPE) == VT_FUNC) ||
5815 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
5816 !has_init && l == VT_CONST && type.ref->c < 0)) {
5817 /* external variable or function */
5818 /* NOTE: as GCC, uninitialized global static
5819 arrays of null size are considered as
5820 extern */
5821 sym = external_sym(v, &type, r, asm_label);
5823 if (type.t & VT_WEAK)
5824 weaken_symbol(sym);
5826 if (ad.alias_target) {
5827 Section tsec;
5828 Elf32_Sym *esym;
5829 Sym *alias_target;
5831 alias_target = sym_find(ad.alias_target);
5832 if (!alias_target || !alias_target->c)
5833 tcc_error("unsupported forward __alias__ attribute");
5834 esym = &((Elf32_Sym *)symtab_section->data)[alias_target->c];
5835 tsec.sh_num = esym->st_shndx;
5836 put_extern_sym2(sym, &tsec, esym->st_value, esym->st_size, 0);
5838 } else {
5839 type.t |= (btype.t & VT_STATIC); /* Retain "static". */
5840 if (type.t & VT_STATIC)
5841 r |= VT_CONST;
5842 else
5843 r |= l;
5844 if (has_init)
5845 next();
5846 decl_initializer_alloc(&type, &ad, r, has_init, v, asm_label, l);
5849 if (tok != ',') {
5850 if (is_for_loop_init)
5851 return 1;
5852 skip(';');
5853 break;
5855 next();
5857 ad.aligned = 0;
5860 return 0;
5863 ST_FUNC void decl(int l)
5865 decl0(l, 0);