Make sizeof() be of type size_t
[tinycc.git] / tccgen.c
blob36a1879f8b154a64175a1fa8037b8ea060df3dbe
1 /*
2 * TCC - Tiny C Compiler
3 *
4 * Copyright (c) 2001-2004 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #include "tcc.h"
23 /********************************************************/
24 /* global variables */
26 /* loc : local variable index
27 ind : output code index
28 rsym: return symbol
29 anon_sym: anonymous symbol index
31 ST_DATA int rsym, anon_sym, ind, loc;
33 ST_DATA Section *text_section, *data_section, *bss_section; /* predefined sections */
34 ST_DATA Section *cur_text_section; /* current section where function code is generated */
35 #ifdef CONFIG_TCC_ASM
36 ST_DATA Section *last_text_section; /* to handle .previous asm directive */
37 #endif
38 #ifdef CONFIG_TCC_BCHECK
39 /* bound check related sections */
40 ST_DATA Section *bounds_section; /* contains global data bound description */
41 ST_DATA Section *lbounds_section; /* contains local data bound description */
42 #endif
43 /* symbol sections */
44 ST_DATA Section *symtab_section, *strtab_section;
45 /* debug sections */
46 ST_DATA Section *stab_section, *stabstr_section;
47 ST_DATA Sym *sym_free_first;
48 ST_DATA void **sym_pools;
49 ST_DATA int nb_sym_pools;
51 ST_DATA Sym *global_stack;
52 ST_DATA Sym *local_stack;
53 ST_DATA Sym *define_stack;
54 ST_DATA Sym *global_label_stack;
55 ST_DATA Sym *local_label_stack;
57 ST_DATA SValue vstack[VSTACK_SIZE], *vtop;
59 ST_DATA int const_wanted; /* true if constant wanted */
60 ST_DATA int nocode_wanted; /* true if no code generation wanted for an expression */
61 ST_DATA int global_expr; /* true if compound literals must be allocated globally (used during initializers parsing */
62 ST_DATA CType func_vt; /* current function return type (used by return instruction) */
63 ST_DATA int func_vc;
64 ST_DATA int last_line_num, last_ind, func_ind; /* debug last line number and pc */
65 ST_DATA char *funcname;
67 ST_DATA CType char_pointer_type, func_old_type, int_type, size_type;
69 /* ------------------------------------------------------------------------- */
70 static void gen_cast(CType *type);
71 static inline CType *pointed_type(CType *type);
72 static int is_compatible_types(CType *type1, CType *type2);
73 static int parse_btype(CType *type, AttributeDef *ad);
74 static void type_decl(CType *type, AttributeDef *ad, int *v, int td);
75 static void parse_expr_type(CType *type);
76 static void decl_initializer(CType *type, Section *sec, unsigned long c, int first, int size_only);
77 static void block(int *bsym, int *csym, int *case_sym, int *def_sym, int case_reg, int is_expr);
78 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r, int has_init, int v, char *asm_label, int scope);
79 static int decl0(int l, int is_for_loop_init);
80 static void expr_eq(void);
81 static void unary_type(CType *type);
82 static void vla_runtime_type_size(CType *type, int *a);
83 static int is_compatible_parameter_types(CType *type1, CType *type2);
84 static void expr_type(CType *type);
86 ST_INLN int is_float(int t)
88 int bt;
89 bt = t & VT_BTYPE;
90 return bt == VT_LDOUBLE || bt == VT_DOUBLE || bt == VT_FLOAT;
93 /* we use our own 'finite' function to avoid potential problems with
94 non standard math libs */
95 /* XXX: endianness dependent */
96 ST_FUNC int ieee_finite(double d)
98 int *p = (int *)&d;
99 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
102 ST_FUNC void test_lvalue(void)
104 if (!(vtop->r & VT_LVAL))
105 expect("lvalue");
108 /* ------------------------------------------------------------------------- */
109 /* symbol allocator */
110 static Sym *__sym_malloc(void)
112 Sym *sym_pool, *sym, *last_sym;
113 int i;
115 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
116 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
118 last_sym = sym_free_first;
119 sym = sym_pool;
120 for(i = 0; i < SYM_POOL_NB; i++) {
121 sym->next = last_sym;
122 last_sym = sym;
123 sym++;
125 sym_free_first = last_sym;
126 return last_sym;
129 static inline Sym *sym_malloc(void)
131 Sym *sym;
132 sym = sym_free_first;
133 if (!sym)
134 sym = __sym_malloc();
135 sym_free_first = sym->next;
136 return sym;
139 ST_INLN void sym_free(Sym *sym)
141 sym->next = sym_free_first;
142 tcc_free(sym->asm_label);
143 sym_free_first = sym;
146 /* push, without hashing */
147 ST_FUNC Sym *sym_push2(Sym **ps, int v, int t, long c)
149 Sym *s;
150 s = sym_malloc();
151 s->asm_label = NULL;
152 s->v = v;
153 s->type.t = t;
154 s->type.ref = NULL;
155 #ifdef _WIN64
156 s->d = NULL;
157 #endif
158 s->c = c;
159 s->next = NULL;
160 /* add in stack */
161 s->prev = *ps;
162 *ps = s;
163 return s;
166 /* find a symbol and return its associated structure. 's' is the top
167 of the symbol stack */
168 ST_FUNC Sym *sym_find2(Sym *s, int v)
170 while (s) {
171 if (s->v == v)
172 return s;
173 s = s->prev;
175 return NULL;
178 /* structure lookup */
179 ST_INLN Sym *struct_find(int v)
181 v -= TOK_IDENT;
182 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
183 return NULL;
184 return table_ident[v]->sym_struct;
187 /* find an identifier */
188 ST_INLN Sym *sym_find(int v)
190 v -= TOK_IDENT;
191 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
192 return NULL;
193 return table_ident[v]->sym_identifier;
196 /* push a given symbol on the symbol stack */
197 ST_FUNC Sym *sym_push(int v, CType *type, int r, int c)
199 Sym *s, **ps;
200 TokenSym *ts;
202 if (local_stack)
203 ps = &local_stack;
204 else
205 ps = &global_stack;
206 s = sym_push2(ps, v, type->t, c);
207 s->type.ref = type->ref;
208 s->r = r;
209 /* don't record fields or anonymous symbols */
210 /* XXX: simplify */
211 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
212 /* record symbol in token array */
213 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
214 if (v & SYM_STRUCT)
215 ps = &ts->sym_struct;
216 else
217 ps = &ts->sym_identifier;
218 s->prev_tok = *ps;
219 *ps = s;
221 return s;
224 /* push a global identifier */
225 ST_FUNC Sym *global_identifier_push(int v, int t, int c)
227 Sym *s, **ps;
228 s = sym_push2(&global_stack, v, t, c);
229 /* don't record anonymous symbol */
230 if (v < SYM_FIRST_ANOM) {
231 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
232 /* modify the top most local identifier, so that
233 sym_identifier will point to 's' when popped */
234 while (*ps != NULL)
235 ps = &(*ps)->prev_tok;
236 s->prev_tok = NULL;
237 *ps = s;
239 return s;
242 /* pop symbols until top reaches 'b' */
243 ST_FUNC void sym_pop(Sym **ptop, Sym *b)
245 Sym *s, *ss, **ps;
246 TokenSym *ts;
247 int v;
249 s = *ptop;
250 while(s != b) {
251 ss = s->prev;
252 v = s->v;
253 /* remove symbol in token array */
254 /* XXX: simplify */
255 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
256 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
257 if (v & SYM_STRUCT)
258 ps = &ts->sym_struct;
259 else
260 ps = &ts->sym_identifier;
261 *ps = s->prev_tok;
263 sym_free(s);
264 s = ss;
266 *ptop = b;
269 static void weaken_symbol(Sym *sym)
271 sym->type.t |= VT_WEAK;
272 if (sym->c > 0) {
273 int esym_type;
274 ElfW(Sym) *esym;
276 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
277 esym_type = ELFW(ST_TYPE)(esym->st_info);
278 esym->st_info = ELFW(ST_INFO)(STB_WEAK, esym_type);
282 /* ------------------------------------------------------------------------- */
284 ST_FUNC void swap(int *p, int *q)
286 int t;
287 t = *p;
288 *p = *q;
289 *q = t;
292 static void vsetc(CType *type, int r, CValue *vc)
294 int v;
296 if (vtop >= vstack + (VSTACK_SIZE - 1))
297 tcc_error("memory full");
298 /* cannot let cpu flags if other instruction are generated. Also
299 avoid leaving VT_JMP anywhere except on the top of the stack
300 because it would complicate the code generator. */
301 if (vtop >= vstack) {
302 v = vtop->r & VT_VALMASK;
303 if (v == VT_CMP || (v & ~1) == VT_JMP)
304 gv(RC_INT);
306 vtop++;
307 vtop->type = *type;
308 vtop->r = r;
309 vtop->r2 = VT_CONST;
310 vtop->c = *vc;
313 /* push constant of type "type" with useless value */
314 void vpush(CType *type)
316 CValue cval;
317 vsetc(type, VT_CONST, &cval);
320 /* push integer constant */
321 ST_FUNC void vpushi(int v)
323 CValue cval;
324 cval.i = v;
325 vsetc(&int_type, VT_CONST, &cval);
328 /* push a pointer sized constant */
329 static void vpushs(long long v)
331 CValue cval;
332 if (PTR_SIZE == 4)
333 cval.i = (int)v;
334 else
335 cval.ull = v;
336 vsetc(&size_type, VT_CONST, &cval);
339 /* push long long constant */
340 static void vpushll(long long v)
342 CValue cval;
343 CType ctype;
344 ctype.t = VT_LLONG;
345 ctype.ref = 0;
346 cval.ull = v;
347 vsetc(&ctype, VT_CONST, &cval);
350 /* push arbitrary 64bit constant */
351 void vpush64(int ty, unsigned long long v)
353 CValue cval;
354 CType ctype;
355 ctype.t = ty;
356 cval.ull = v;
357 vsetc(&ctype, VT_CONST, &cval);
360 /* Return a static symbol pointing to a section */
361 ST_FUNC Sym *get_sym_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
363 int v;
364 Sym *sym;
366 v = anon_sym++;
367 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
368 sym->type.ref = type->ref;
369 sym->r = VT_CONST | VT_SYM;
370 put_extern_sym(sym, sec, offset, size);
371 return sym;
374 /* push a reference to a section offset by adding a dummy symbol */
375 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
377 CValue cval;
379 cval.ul = 0;
380 vsetc(type, VT_CONST | VT_SYM, &cval);
381 vtop->sym = get_sym_ref(type, sec, offset, size);
384 /* define a new external reference to a symbol 'v' of type 'u' */
385 ST_FUNC Sym *external_global_sym(int v, CType *type, int r)
387 Sym *s;
389 s = sym_find(v);
390 if (!s) {
391 /* push forward reference */
392 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
393 s->type.ref = type->ref;
394 s->r = r | VT_CONST | VT_SYM;
396 return s;
399 /* define a new external reference to a symbol 'v' with alternate asm
400 name 'asm_label' of type 'u'. 'asm_label' is equal to NULL if there
401 is no alternate name (most cases) */
402 static Sym *external_sym(int v, CType *type, int r, char *asm_label)
404 Sym *s;
406 s = sym_find(v);
407 if (!s) {
408 /* push forward reference */
409 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
410 s->asm_label = asm_label;
411 s->type.t |= VT_EXTERN;
412 } else if (s->type.ref == func_old_type.ref) {
413 s->type.ref = type->ref;
414 s->r = r | VT_CONST | VT_SYM;
415 s->type.t |= VT_EXTERN;
416 } else if (!is_compatible_types(&s->type, type)) {
417 tcc_error("incompatible types for redefinition of '%s'",
418 get_tok_str(v, NULL));
420 return s;
423 /* push a reference to global symbol v */
424 ST_FUNC void vpush_global_sym(CType *type, int v)
426 Sym *sym;
427 CValue cval;
429 sym = external_global_sym(v, type, 0);
430 cval.ul = 0;
431 vsetc(type, VT_CONST | VT_SYM, &cval);
432 vtop->sym = sym;
435 ST_FUNC void vset(CType *type, int r, int v)
437 CValue cval;
439 cval.i = v;
440 vsetc(type, r, &cval);
443 static void vseti(int r, int v)
445 CType type;
446 type.t = VT_INT;
447 type.ref = 0;
448 vset(&type, r, v);
451 ST_FUNC void vswap(void)
453 SValue tmp;
455 tmp = vtop[0];
456 vtop[0] = vtop[-1];
457 vtop[-1] = tmp;
460 ST_FUNC void vpushv(SValue *v)
462 if (vtop >= vstack + (VSTACK_SIZE - 1))
463 tcc_error("memory full");
464 vtop++;
465 *vtop = *v;
468 static void vdup(void)
470 vpushv(vtop);
473 /* save r to the memory stack, and mark it as being free */
474 ST_FUNC void save_reg(int r)
476 int l, saved, size, align;
477 SValue *p, sv;
478 CType *type;
480 /* modify all stack values */
481 saved = 0;
482 l = 0;
483 for(p=vstack;p<=vtop;p++) {
484 if ((p->r & VT_VALMASK) == r ||
485 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
486 /* must save value on stack if not already done */
487 if (!saved) {
488 /* NOTE: must reload 'r' because r might be equal to r2 */
489 r = p->r & VT_VALMASK;
490 /* store register in the stack */
491 type = &p->type;
492 if ((p->r & VT_LVAL) ||
493 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
494 #ifdef TCC_TARGET_X86_64
495 type = &char_pointer_type;
496 #else
497 type = &int_type;
498 #endif
499 size = type_size(type, &align);
500 loc = (loc - size) & -align;
501 sv.type.t = type->t;
502 sv.r = VT_LOCAL | VT_LVAL;
503 sv.c.ul = loc;
504 store(r, &sv);
505 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
506 /* x86 specific: need to pop fp register ST0 if saved */
507 if (r == TREG_ST0) {
508 o(0xd8dd); /* fstp %st(0) */
510 #endif
511 #ifndef TCC_TARGET_X86_64
512 /* special long long case */
513 if ((type->t & VT_BTYPE) == VT_LLONG) {
514 sv.c.ul += 4;
515 store(p->r2, &sv);
517 #endif
518 l = loc;
519 saved = 1;
521 /* mark that stack entry as being saved on the stack */
522 if (p->r & VT_LVAL) {
523 /* also clear the bounded flag because the
524 relocation address of the function was stored in
525 p->c.ul */
526 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
527 } else {
528 p->r = lvalue_type(p->type.t) | VT_LOCAL;
530 p->r2 = VT_CONST;
531 p->c.ul = l;
536 #ifdef TCC_TARGET_ARM
537 /* find a register of class 'rc2' with at most one reference on stack.
538 * If none, call get_reg(rc) */
539 ST_FUNC int get_reg_ex(int rc, int rc2)
541 int r;
542 SValue *p;
544 for(r=0;r<NB_REGS;r++) {
545 if (reg_classes[r] & rc2) {
546 int n;
547 n=0;
548 for(p = vstack; p <= vtop; p++) {
549 if ((p->r & VT_VALMASK) == r ||
550 (p->r2 & VT_VALMASK) == r)
551 n++;
553 if (n <= 1)
554 return r;
557 return get_reg(rc);
559 #endif
561 /* find a free register of class 'rc'. If none, save one register */
562 ST_FUNC int get_reg(int rc)
564 int r;
565 SValue *p;
567 /* find a free register */
568 for(r=0;r<NB_REGS;r++) {
569 if (reg_classes[r] & rc) {
570 for(p=vstack;p<=vtop;p++) {
571 if ((p->r & VT_VALMASK) == r ||
572 (p->r2 & VT_VALMASK) == r)
573 goto notfound;
575 return r;
577 notfound: ;
580 /* no register left : free the first one on the stack (VERY
581 IMPORTANT to start from the bottom to ensure that we don't
582 spill registers used in gen_opi()) */
583 for(p=vstack;p<=vtop;p++) {
584 r = p->r & VT_VALMASK;
585 if (r < VT_CONST && (reg_classes[r] & rc))
586 goto save_found;
587 /* also look at second register (if long long) */
588 r = p->r2 & VT_VALMASK;
589 if (r < VT_CONST && (reg_classes[r] & rc)) {
590 save_found:
591 save_reg(r);
592 return r;
595 /* Should never comes here */
596 return -1;
599 /* save registers up to (vtop - n) stack entry */
600 ST_FUNC void save_regs(int n)
602 int r;
603 SValue *p, *p1;
604 p1 = vtop - n;
605 for(p = vstack;p <= p1; p++) {
606 r = p->r & VT_VALMASK;
607 if (r < VT_CONST) {
608 save_reg(r);
613 /* move register 's' to 'r', and flush previous value of r to memory
614 if needed */
615 static void move_reg(int r, int s)
617 SValue sv;
619 if (r != s) {
620 save_reg(r);
621 sv.type.t = VT_INT;
622 sv.r = s;
623 sv.c.ul = 0;
624 load(r, &sv);
628 /* get address of vtop (vtop MUST BE an lvalue) */
629 static void gaddrof(void)
631 if (vtop->r & VT_REF)
632 gv(RC_INT);
633 vtop->r &= ~VT_LVAL;
634 /* tricky: if saved lvalue, then we can go back to lvalue */
635 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
636 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
641 #ifdef CONFIG_TCC_BCHECK
642 /* generate lvalue bound code */
643 static void gbound(void)
645 int lval_type;
646 CType type1;
648 vtop->r &= ~VT_MUSTBOUND;
649 /* if lvalue, then use checking code before dereferencing */
650 if (vtop->r & VT_LVAL) {
651 /* if not VT_BOUNDED value, then make one */
652 if (!(vtop->r & VT_BOUNDED)) {
653 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
654 /* must save type because we must set it to int to get pointer */
655 type1 = vtop->type;
656 vtop->type.t = VT_INT;
657 gaddrof();
658 vpushi(0);
659 gen_bounded_ptr_add();
660 vtop->r |= lval_type;
661 vtop->type = type1;
663 /* then check for dereferencing */
664 gen_bounded_ptr_deref();
667 #endif
669 /* store vtop a register belonging to class 'rc'. lvalues are
670 converted to values. Cannot be used if cannot be converted to
671 register value (such as structures). */
672 ST_FUNC int gv(int rc)
674 int r, bit_pos, bit_size, size, align, i;
675 #ifndef TCC_TARGET_X86_64
676 int rc2;
677 #endif
679 /* NOTE: get_reg can modify vstack[] */
680 if (vtop->type.t & VT_BITFIELD) {
681 CType type;
682 int bits = 32;
683 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
684 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
685 /* remove bit field info to avoid loops */
686 vtop->type.t &= ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
687 /* cast to int to propagate signedness in following ops */
688 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
689 type.t = VT_LLONG;
690 bits = 64;
691 } else
692 type.t = VT_INT;
693 if((vtop->type.t & VT_UNSIGNED) ||
694 (vtop->type.t & VT_BTYPE) == VT_BOOL)
695 type.t |= VT_UNSIGNED;
696 gen_cast(&type);
697 /* generate shifts */
698 vpushi(bits - (bit_pos + bit_size));
699 gen_op(TOK_SHL);
700 vpushi(bits - bit_size);
701 /* NOTE: transformed to SHR if unsigned */
702 gen_op(TOK_SAR);
703 r = gv(rc);
704 } else {
705 if (is_float(vtop->type.t) &&
706 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
707 Sym *sym;
708 int *ptr;
709 unsigned long offset;
710 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
711 CValue check;
712 #endif
714 /* XXX: unify with initializers handling ? */
715 /* CPUs usually cannot use float constants, so we store them
716 generically in data segment */
717 size = type_size(&vtop->type, &align);
718 offset = (data_section->data_offset + align - 1) & -align;
719 data_section->data_offset = offset;
720 /* XXX: not portable yet */
721 #if defined(__i386__) || defined(__x86_64__)
722 /* Zero pad x87 tenbyte long doubles */
723 if (size == LDOUBLE_SIZE) {
724 vtop->c.tab[2] &= 0xffff;
725 #if LDOUBLE_SIZE == 16
726 vtop->c.tab[3] = 0;
727 #endif
729 #endif
730 ptr = section_ptr_add(data_section, size);
731 size = size >> 2;
732 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
733 check.d = 1;
734 if(check.tab[0])
735 for(i=0;i<size;i++)
736 ptr[i] = vtop->c.tab[size-1-i];
737 else
738 #endif
739 for(i=0;i<size;i++)
740 ptr[i] = vtop->c.tab[i];
741 sym = get_sym_ref(&vtop->type, data_section, offset, size << 2);
742 vtop->r |= VT_LVAL | VT_SYM;
743 vtop->sym = sym;
744 vtop->c.ul = 0;
746 #ifdef CONFIG_TCC_BCHECK
747 if (vtop->r & VT_MUSTBOUND)
748 gbound();
749 #endif
751 r = vtop->r & VT_VALMASK;
752 #ifndef TCC_TARGET_X86_64
753 rc2 = RC_INT;
754 if (rc == RC_IRET)
755 rc2 = RC_LRET;
756 #endif
757 /* need to reload if:
758 - constant
759 - lvalue (need to dereference pointer)
760 - already a register, but not in the right class */
761 if (r >= VT_CONST
762 || (vtop->r & VT_LVAL)
763 || !(reg_classes[r] & rc)
764 #ifndef TCC_TARGET_X86_64
765 || ((vtop->type.t & VT_BTYPE) == VT_LLONG && !(reg_classes[vtop->r2] & rc2))
766 #endif
769 r = get_reg(rc);
770 #ifndef TCC_TARGET_X86_64
771 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
772 int r2;
773 unsigned long long ll;
774 /* two register type load : expand to two words
775 temporarily */
776 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
777 /* load constant */
778 ll = vtop->c.ull;
779 vtop->c.ui = ll; /* first word */
780 load(r, vtop);
781 vtop->r = r; /* save register value */
782 vpushi(ll >> 32); /* second word */
783 } else if (r >= VT_CONST || /* XXX: test to VT_CONST incorrect ? */
784 (vtop->r & VT_LVAL)) {
785 /* We do not want to modifier the long long
786 pointer here, so the safest (and less
787 efficient) is to save all the other registers
788 in the stack. XXX: totally inefficient. */
789 save_regs(1);
790 /* load from memory */
791 load(r, vtop);
792 vdup();
793 vtop[-1].r = r; /* save register value */
794 /* increment pointer to get second word */
795 vtop->type.t = VT_INT;
796 gaddrof();
797 vpushi(4);
798 gen_op('+');
799 vtop->r |= VT_LVAL;
800 } else {
801 /* move registers */
802 load(r, vtop);
803 vdup();
804 vtop[-1].r = r; /* save register value */
805 vtop->r = vtop[-1].r2;
807 /* allocate second register */
808 r2 = get_reg(rc2);
809 load(r2, vtop);
810 vpop();
811 /* write second register */
812 vtop->r2 = r2;
813 } else
814 #endif
815 if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
816 int t1, t;
817 /* lvalue of scalar type : need to use lvalue type
818 because of possible cast */
819 t = vtop->type.t;
820 t1 = t;
821 /* compute memory access type */
822 if (vtop->r & VT_LVAL_BYTE)
823 t = VT_BYTE;
824 else if (vtop->r & VT_LVAL_SHORT)
825 t = VT_SHORT;
826 if (vtop->r & VT_LVAL_UNSIGNED)
827 t |= VT_UNSIGNED;
828 vtop->type.t = t;
829 load(r, vtop);
830 /* restore wanted type */
831 vtop->type.t = t1;
832 } else {
833 /* one register type load */
834 load(r, vtop);
837 vtop->r = r;
838 #ifdef TCC_TARGET_C67
839 /* uses register pairs for doubles */
840 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
841 vtop->r2 = r+1;
842 #endif
844 return r;
847 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
848 ST_FUNC void gv2(int rc1, int rc2)
850 int v;
852 /* generate more generic register first. But VT_JMP or VT_CMP
853 values must be generated first in all cases to avoid possible
854 reload errors */
855 v = vtop[0].r & VT_VALMASK;
856 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
857 vswap();
858 gv(rc1);
859 vswap();
860 gv(rc2);
861 /* test if reload is needed for first register */
862 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
863 vswap();
864 gv(rc1);
865 vswap();
867 } else {
868 gv(rc2);
869 vswap();
870 gv(rc1);
871 vswap();
872 /* test if reload is needed for first register */
873 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
874 gv(rc2);
879 /* wrapper around RC_FRET to return a register by type */
880 static int rc_fret(int t)
882 #ifdef TCC_TARGET_X86_64
883 if (t == VT_LDOUBLE) {
884 return RC_ST0;
886 #endif
887 return RC_FRET;
890 /* wrapper around REG_FRET to return a register by type */
891 static int reg_fret(int t)
893 #ifdef TCC_TARGET_X86_64
894 if (t == VT_LDOUBLE) {
895 return TREG_ST0;
897 #endif
898 return REG_FRET;
901 /* expand long long on stack in two int registers */
902 static void lexpand(void)
904 int u;
906 u = vtop->type.t & VT_UNSIGNED;
907 gv(RC_INT);
908 vdup();
909 vtop[0].r = vtop[-1].r2;
910 vtop[0].r2 = VT_CONST;
911 vtop[-1].r2 = VT_CONST;
912 vtop[0].type.t = VT_INT | u;
913 vtop[-1].type.t = VT_INT | u;
916 #ifdef TCC_TARGET_ARM
917 /* expand long long on stack */
918 ST_FUNC void lexpand_nr(void)
920 int u,v;
922 u = vtop->type.t & VT_UNSIGNED;
923 vdup();
924 vtop->r2 = VT_CONST;
925 vtop->type.t = VT_INT | u;
926 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
927 if (v == VT_CONST) {
928 vtop[-1].c.ui = vtop->c.ull;
929 vtop->c.ui = vtop->c.ull >> 32;
930 vtop->r = VT_CONST;
931 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
932 vtop->c.ui += 4;
933 vtop->r = vtop[-1].r;
934 } else if (v > VT_CONST) {
935 vtop--;
936 lexpand();
937 } else
938 vtop->r = vtop[-1].r2;
939 vtop[-1].r2 = VT_CONST;
940 vtop[-1].type.t = VT_INT | u;
942 #endif
944 /* build a long long from two ints */
945 static void lbuild(int t)
947 gv2(RC_INT, RC_INT);
948 vtop[-1].r2 = vtop[0].r;
949 vtop[-1].type.t = t;
950 vpop();
953 /* rotate n first stack elements to the bottom
954 I1 ... In -> I2 ... In I1 [top is right]
956 static void vrotb(int n)
958 int i;
959 SValue tmp;
961 tmp = vtop[-n + 1];
962 for(i=-n+1;i!=0;i++)
963 vtop[i] = vtop[i+1];
964 vtop[0] = tmp;
967 /* rotate n first stack elements to the top
968 I1 ... In -> In I1 ... I(n-1) [top is right]
970 ST_FUNC void vrott(int n)
972 int i;
973 SValue tmp;
975 tmp = vtop[0];
976 for(i = 0;i < n - 1; i++)
977 vtop[-i] = vtop[-i - 1];
978 vtop[-n + 1] = tmp;
981 /* pop stack value */
982 ST_FUNC void vpop(void)
984 int v;
985 v = vtop->r & VT_VALMASK;
986 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
987 /* for x86, we need to pop the FP stack */
988 if (v == TREG_ST0 && !nocode_wanted) {
989 o(0xd8dd); /* fstp %st(0) */
990 } else
991 #endif
992 if (v == VT_JMP || v == VT_JMPI) {
993 /* need to put correct jump if && or || without test */
994 gsym(vtop->c.ul);
996 vtop--;
999 /* convert stack entry to register and duplicate its value in another
1000 register */
1001 static void gv_dup(void)
1003 int rc, t, r, r1;
1004 SValue sv;
1006 t = vtop->type.t;
1007 if ((t & VT_BTYPE) == VT_LLONG) {
1008 lexpand();
1009 gv_dup();
1010 vswap();
1011 vrotb(3);
1012 gv_dup();
1013 vrotb(4);
1014 /* stack: H L L1 H1 */
1015 lbuild(t);
1016 vrotb(3);
1017 vrotb(3);
1018 vswap();
1019 lbuild(t);
1020 vswap();
1021 } else {
1022 /* duplicate value */
1023 rc = RC_INT;
1024 sv.type.t = VT_INT;
1025 if (is_float(t)) {
1026 rc = RC_FLOAT;
1027 #ifdef TCC_TARGET_X86_64
1028 if ((t & VT_BTYPE) == VT_LDOUBLE) {
1029 rc = RC_ST0;
1031 #endif
1032 sv.type.t = t;
1034 r = gv(rc);
1035 r1 = get_reg(rc);
1036 sv.r = r;
1037 sv.c.ul = 0;
1038 load(r1, &sv); /* move r to r1 */
1039 vdup();
1040 /* duplicates value */
1041 if (r != r1)
1042 vtop->r = r1;
1046 #ifndef TCC_TARGET_X86_64
1047 /* generate CPU independent (unsigned) long long operations */
1048 static void gen_opl(int op)
1050 int t, a, b, op1, c, i;
1051 int func;
1052 unsigned short reg_iret = REG_IRET;
1053 unsigned short reg_lret = REG_LRET;
1054 SValue tmp;
1056 switch(op) {
1057 case '/':
1058 case TOK_PDIV:
1059 func = TOK___divdi3;
1060 goto gen_func;
1061 case TOK_UDIV:
1062 func = TOK___udivdi3;
1063 goto gen_func;
1064 case '%':
1065 func = TOK___moddi3;
1066 goto gen_mod_func;
1067 case TOK_UMOD:
1068 func = TOK___umoddi3;
1069 gen_mod_func:
1070 #ifdef TCC_ARM_EABI
1071 reg_iret = TREG_R2;
1072 reg_lret = TREG_R3;
1073 #endif
1074 gen_func:
1075 /* call generic long long function */
1076 vpush_global_sym(&func_old_type, func);
1077 vrott(3);
1078 gfunc_call(2);
1079 vpushi(0);
1080 vtop->r = reg_iret;
1081 vtop->r2 = reg_lret;
1082 break;
1083 case '^':
1084 case '&':
1085 case '|':
1086 case '*':
1087 case '+':
1088 case '-':
1089 t = vtop->type.t;
1090 vswap();
1091 lexpand();
1092 vrotb(3);
1093 lexpand();
1094 /* stack: L1 H1 L2 H2 */
1095 tmp = vtop[0];
1096 vtop[0] = vtop[-3];
1097 vtop[-3] = tmp;
1098 tmp = vtop[-2];
1099 vtop[-2] = vtop[-3];
1100 vtop[-3] = tmp;
1101 vswap();
1102 /* stack: H1 H2 L1 L2 */
1103 if (op == '*') {
1104 vpushv(vtop - 1);
1105 vpushv(vtop - 1);
1106 gen_op(TOK_UMULL);
1107 lexpand();
1108 /* stack: H1 H2 L1 L2 ML MH */
1109 for(i=0;i<4;i++)
1110 vrotb(6);
1111 /* stack: ML MH H1 H2 L1 L2 */
1112 tmp = vtop[0];
1113 vtop[0] = vtop[-2];
1114 vtop[-2] = tmp;
1115 /* stack: ML MH H1 L2 H2 L1 */
1116 gen_op('*');
1117 vrotb(3);
1118 vrotb(3);
1119 gen_op('*');
1120 /* stack: ML MH M1 M2 */
1121 gen_op('+');
1122 gen_op('+');
1123 } else if (op == '+' || op == '-') {
1124 /* XXX: add non carry method too (for MIPS or alpha) */
1125 if (op == '+')
1126 op1 = TOK_ADDC1;
1127 else
1128 op1 = TOK_SUBC1;
1129 gen_op(op1);
1130 /* stack: H1 H2 (L1 op L2) */
1131 vrotb(3);
1132 vrotb(3);
1133 gen_op(op1 + 1); /* TOK_xxxC2 */
1134 } else {
1135 gen_op(op);
1136 /* stack: H1 H2 (L1 op L2) */
1137 vrotb(3);
1138 vrotb(3);
1139 /* stack: (L1 op L2) H1 H2 */
1140 gen_op(op);
1141 /* stack: (L1 op L2) (H1 op H2) */
1143 /* stack: L H */
1144 lbuild(t);
1145 break;
1146 case TOK_SAR:
1147 case TOK_SHR:
1148 case TOK_SHL:
1149 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1150 t = vtop[-1].type.t;
1151 vswap();
1152 lexpand();
1153 vrotb(3);
1154 /* stack: L H shift */
1155 c = (int)vtop->c.i;
1156 /* constant: simpler */
1157 /* NOTE: all comments are for SHL. the other cases are
1158 done by swaping words */
1159 vpop();
1160 if (op != TOK_SHL)
1161 vswap();
1162 if (c >= 32) {
1163 /* stack: L H */
1164 vpop();
1165 if (c > 32) {
1166 vpushi(c - 32);
1167 gen_op(op);
1169 if (op != TOK_SAR) {
1170 vpushi(0);
1171 } else {
1172 gv_dup();
1173 vpushi(31);
1174 gen_op(TOK_SAR);
1176 vswap();
1177 } else {
1178 vswap();
1179 gv_dup();
1180 /* stack: H L L */
1181 vpushi(c);
1182 gen_op(op);
1183 vswap();
1184 vpushi(32 - c);
1185 if (op == TOK_SHL)
1186 gen_op(TOK_SHR);
1187 else
1188 gen_op(TOK_SHL);
1189 vrotb(3);
1190 /* stack: L L H */
1191 vpushi(c);
1192 if (op == TOK_SHL)
1193 gen_op(TOK_SHL);
1194 else
1195 gen_op(TOK_SHR);
1196 gen_op('|');
1198 if (op != TOK_SHL)
1199 vswap();
1200 lbuild(t);
1201 } else {
1202 /* XXX: should provide a faster fallback on x86 ? */
1203 switch(op) {
1204 case TOK_SAR:
1205 func = TOK___ashrdi3;
1206 goto gen_func;
1207 case TOK_SHR:
1208 func = TOK___lshrdi3;
1209 goto gen_func;
1210 case TOK_SHL:
1211 func = TOK___ashldi3;
1212 goto gen_func;
1215 break;
1216 default:
1217 /* compare operations */
1218 t = vtop->type.t;
1219 vswap();
1220 lexpand();
1221 vrotb(3);
1222 lexpand();
1223 /* stack: L1 H1 L2 H2 */
1224 tmp = vtop[-1];
1225 vtop[-1] = vtop[-2];
1226 vtop[-2] = tmp;
1227 /* stack: L1 L2 H1 H2 */
1228 /* compare high */
1229 op1 = op;
1230 /* when values are equal, we need to compare low words. since
1231 the jump is inverted, we invert the test too. */
1232 if (op1 == TOK_LT)
1233 op1 = TOK_LE;
1234 else if (op1 == TOK_GT)
1235 op1 = TOK_GE;
1236 else if (op1 == TOK_ULT)
1237 op1 = TOK_ULE;
1238 else if (op1 == TOK_UGT)
1239 op1 = TOK_UGE;
1240 a = 0;
1241 b = 0;
1242 gen_op(op1);
1243 if (op1 != TOK_NE) {
1244 a = gtst(1, 0);
1246 if (op != TOK_EQ) {
1247 /* generate non equal test */
1248 /* XXX: NOT PORTABLE yet */
1249 if (a == 0) {
1250 b = gtst(0, 0);
1251 } else {
1252 #if defined(TCC_TARGET_I386)
1253 b = psym(0x850f, 0);
1254 #elif defined(TCC_TARGET_ARM)
1255 b = ind;
1256 o(0x1A000000 | encbranch(ind, 0, 1));
1257 #elif defined(TCC_TARGET_C67)
1258 tcc_error("not implemented");
1259 #else
1260 #error not supported
1261 #endif
1264 /* compare low. Always unsigned */
1265 op1 = op;
1266 if (op1 == TOK_LT)
1267 op1 = TOK_ULT;
1268 else if (op1 == TOK_LE)
1269 op1 = TOK_ULE;
1270 else if (op1 == TOK_GT)
1271 op1 = TOK_UGT;
1272 else if (op1 == TOK_GE)
1273 op1 = TOK_UGE;
1274 gen_op(op1);
1275 a = gtst(1, a);
1276 gsym(b);
1277 vseti(VT_JMPI, a);
1278 break;
1281 #endif
1283 /* handle integer constant optimizations and various machine
1284 independent opt */
1285 static void gen_opic(int op)
1287 int c1, c2, t1, t2, n;
1288 SValue *v1, *v2;
1289 long long l1, l2;
1290 typedef unsigned long long U;
1292 v1 = vtop - 1;
1293 v2 = vtop;
1294 t1 = v1->type.t & VT_BTYPE;
1295 t2 = v2->type.t & VT_BTYPE;
1297 if (t1 == VT_LLONG)
1298 l1 = v1->c.ll;
1299 else if (v1->type.t & VT_UNSIGNED)
1300 l1 = v1->c.ui;
1301 else
1302 l1 = v1->c.i;
1304 if (t2 == VT_LLONG)
1305 l2 = v2->c.ll;
1306 else if (v2->type.t & VT_UNSIGNED)
1307 l2 = v2->c.ui;
1308 else
1309 l2 = v2->c.i;
1311 /* currently, we cannot do computations with forward symbols */
1312 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1313 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1314 if (c1 && c2) {
1315 switch(op) {
1316 case '+': l1 += l2; break;
1317 case '-': l1 -= l2; break;
1318 case '&': l1 &= l2; break;
1319 case '^': l1 ^= l2; break;
1320 case '|': l1 |= l2; break;
1321 case '*': l1 *= l2; break;
1323 case TOK_PDIV:
1324 case '/':
1325 case '%':
1326 case TOK_UDIV:
1327 case TOK_UMOD:
1328 /* if division by zero, generate explicit division */
1329 if (l2 == 0) {
1330 if (const_wanted)
1331 tcc_error("division by zero in constant");
1332 goto general_case;
1334 switch(op) {
1335 default: l1 /= l2; break;
1336 case '%': l1 %= l2; break;
1337 case TOK_UDIV: l1 = (U)l1 / l2; break;
1338 case TOK_UMOD: l1 = (U)l1 % l2; break;
1340 break;
1341 case TOK_SHL: l1 <<= l2; break;
1342 case TOK_SHR: l1 = (U)l1 >> l2; break;
1343 case TOK_SAR: l1 >>= l2; break;
1344 /* tests */
1345 case TOK_ULT: l1 = (U)l1 < (U)l2; break;
1346 case TOK_UGE: l1 = (U)l1 >= (U)l2; break;
1347 case TOK_EQ: l1 = l1 == l2; break;
1348 case TOK_NE: l1 = l1 != l2; break;
1349 case TOK_ULE: l1 = (U)l1 <= (U)l2; break;
1350 case TOK_UGT: l1 = (U)l1 > (U)l2; break;
1351 case TOK_LT: l1 = l1 < l2; break;
1352 case TOK_GE: l1 = l1 >= l2; break;
1353 case TOK_LE: l1 = l1 <= l2; break;
1354 case TOK_GT: l1 = l1 > l2; break;
1355 /* logical */
1356 case TOK_LAND: l1 = l1 && l2; break;
1357 case TOK_LOR: l1 = l1 || l2; break;
1358 default:
1359 goto general_case;
1361 v1->c.ll = l1;
1362 vtop--;
1363 } else {
1364 /* if commutative ops, put c2 as constant */
1365 if (c1 && (op == '+' || op == '&' || op == '^' ||
1366 op == '|' || op == '*')) {
1367 vswap();
1368 c2 = c1; //c = c1, c1 = c2, c2 = c;
1369 l2 = l1; //l = l1, l1 = l2, l2 = l;
1371 /* Filter out NOP operations like x*1, x-0, x&-1... */
1372 if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
1373 op == TOK_PDIV) &&
1374 l2 == 1) ||
1375 ((op == '+' || op == '-' || op == '|' || op == '^' ||
1376 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
1377 l2 == 0) ||
1378 (op == '&' &&
1379 l2 == -1))) {
1380 /* nothing to do */
1381 vtop--;
1382 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
1383 /* try to use shifts instead of muls or divs */
1384 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
1385 n = -1;
1386 while (l2) {
1387 l2 >>= 1;
1388 n++;
1390 vtop->c.ll = n;
1391 if (op == '*')
1392 op = TOK_SHL;
1393 else if (op == TOK_PDIV)
1394 op = TOK_SAR;
1395 else
1396 op = TOK_SHR;
1398 goto general_case;
1399 } else if (c2 && (op == '+' || op == '-') &&
1400 (((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM))
1401 || (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
1402 /* symbol + constant case */
1403 if (op == '-')
1404 l2 = -l2;
1405 vtop--;
1406 vtop->c.ll += l2;
1407 } else {
1408 general_case:
1409 if (!nocode_wanted) {
1410 /* call low level op generator */
1411 if (t1 == VT_LLONG || t2 == VT_LLONG)
1412 gen_opl(op);
1413 else
1414 gen_opi(op);
1415 } else {
1416 vtop--;
1422 /* generate a floating point operation with constant propagation */
1423 static void gen_opif(int op)
1425 int c1, c2;
1426 SValue *v1, *v2;
1427 long double f1, f2;
1429 v1 = vtop - 1;
1430 v2 = vtop;
1431 /* currently, we cannot do computations with forward symbols */
1432 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1433 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1434 if (c1 && c2) {
1435 if (v1->type.t == VT_FLOAT) {
1436 f1 = v1->c.f;
1437 f2 = v2->c.f;
1438 } else if (v1->type.t == VT_DOUBLE) {
1439 f1 = v1->c.d;
1440 f2 = v2->c.d;
1441 } else {
1442 f1 = v1->c.ld;
1443 f2 = v2->c.ld;
1446 /* NOTE: we only do constant propagation if finite number (not
1447 NaN or infinity) (ANSI spec) */
1448 if (!ieee_finite(f1) || !ieee_finite(f2))
1449 goto general_case;
1451 switch(op) {
1452 case '+': f1 += f2; break;
1453 case '-': f1 -= f2; break;
1454 case '*': f1 *= f2; break;
1455 case '/':
1456 if (f2 == 0.0) {
1457 if (const_wanted)
1458 tcc_error("division by zero in constant");
1459 goto general_case;
1461 f1 /= f2;
1462 break;
1463 /* XXX: also handles tests ? */
1464 default:
1465 goto general_case;
1467 /* XXX: overflow test ? */
1468 if (v1->type.t == VT_FLOAT) {
1469 v1->c.f = f1;
1470 } else if (v1->type.t == VT_DOUBLE) {
1471 v1->c.d = f1;
1472 } else {
1473 v1->c.ld = f1;
1475 vtop--;
1476 } else {
1477 general_case:
1478 if (!nocode_wanted) {
1479 gen_opf(op);
1480 } else {
1481 vtop--;
1486 static int pointed_size(CType *type)
1488 int align;
1489 return type_size(pointed_type(type), &align);
1492 static void vla_runtime_pointed_size(CType *type)
1494 int align;
1495 vla_runtime_type_size(pointed_type(type), &align);
1498 static inline int is_null_pointer(SValue *p)
1500 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
1501 return 0;
1502 return ((p->type.t & VT_BTYPE) == VT_INT && p->c.i == 0) ||
1503 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.ll == 0) ||
1504 ((p->type.t & VT_BTYPE) == VT_PTR && p->c.ptr == 0);
1507 static inline int is_integer_btype(int bt)
1509 return (bt == VT_BYTE || bt == VT_SHORT ||
1510 bt == VT_INT || bt == VT_LLONG);
1513 /* check types for comparison or substraction of pointers */
1514 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
1516 CType *type1, *type2, tmp_type1, tmp_type2;
1517 int bt1, bt2;
1519 /* null pointers are accepted for all comparisons as gcc */
1520 if (is_null_pointer(p1) || is_null_pointer(p2))
1521 return;
1522 type1 = &p1->type;
1523 type2 = &p2->type;
1524 bt1 = type1->t & VT_BTYPE;
1525 bt2 = type2->t & VT_BTYPE;
1526 /* accept comparison between pointer and integer with a warning */
1527 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
1528 if (op != TOK_LOR && op != TOK_LAND )
1529 tcc_warning("comparison between pointer and integer");
1530 return;
1533 /* both must be pointers or implicit function pointers */
1534 if (bt1 == VT_PTR) {
1535 type1 = pointed_type(type1);
1536 } else if (bt1 != VT_FUNC)
1537 goto invalid_operands;
1539 if (bt2 == VT_PTR) {
1540 type2 = pointed_type(type2);
1541 } else if (bt2 != VT_FUNC) {
1542 invalid_operands:
1543 tcc_error("invalid operands to binary %s", get_tok_str(op, NULL));
1545 if ((type1->t & VT_BTYPE) == VT_VOID ||
1546 (type2->t & VT_BTYPE) == VT_VOID)
1547 return;
1548 tmp_type1 = *type1;
1549 tmp_type2 = *type2;
1550 tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1551 tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1552 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
1553 /* gcc-like error if '-' is used */
1554 if (op == '-')
1555 goto invalid_operands;
1556 else
1557 tcc_warning("comparison of distinct pointer types lacks a cast");
1561 /* generic gen_op: handles types problems */
1562 ST_FUNC void gen_op(int op)
1564 int u, t1, t2, bt1, bt2, t;
1565 CType type1;
1567 t1 = vtop[-1].type.t;
1568 t2 = vtop[0].type.t;
1569 bt1 = t1 & VT_BTYPE;
1570 bt2 = t2 & VT_BTYPE;
1572 if (bt1 == VT_PTR || bt2 == VT_PTR) {
1573 /* at least one operand is a pointer */
1574 /* relationnal op: must be both pointers */
1575 if (op >= TOK_ULT && op <= TOK_LOR) {
1576 check_comparison_pointer_types(vtop - 1, vtop, op);
1577 /* pointers are handled are unsigned */
1578 #ifdef TCC_TARGET_X86_64
1579 t = VT_LLONG | VT_UNSIGNED;
1580 #else
1581 t = VT_INT | VT_UNSIGNED;
1582 #endif
1583 goto std_op;
1585 /* if both pointers, then it must be the '-' op */
1586 if (bt1 == VT_PTR && bt2 == VT_PTR) {
1587 if (op != '-')
1588 tcc_error("cannot use pointers here");
1589 check_comparison_pointer_types(vtop - 1, vtop, op);
1590 /* XXX: check that types are compatible */
1591 if (vtop[-1].type.t & VT_VLA) {
1592 vla_runtime_pointed_size(&vtop[-1].type);
1593 } else {
1594 vpushi(pointed_size(&vtop[-1].type));
1596 vrott(3);
1597 gen_opic(op);
1598 /* set to integer type */
1599 #ifdef TCC_TARGET_X86_64
1600 vtop->type.t = VT_LLONG;
1601 #else
1602 vtop->type.t = VT_INT;
1603 #endif
1604 vswap();
1605 gen_op(TOK_PDIV);
1606 } else {
1607 /* exactly one pointer : must be '+' or '-'. */
1608 if (op != '-' && op != '+')
1609 tcc_error("cannot use pointers here");
1610 /* Put pointer as first operand */
1611 if (bt2 == VT_PTR) {
1612 vswap();
1613 swap(&t1, &t2);
1615 type1 = vtop[-1].type;
1616 type1.t &= ~VT_ARRAY;
1617 if (vtop[-1].type.t & VT_VLA)
1618 vla_runtime_pointed_size(&vtop[-1].type);
1619 else {
1620 u = pointed_size(&vtop[-1].type);
1621 if (u < 0)
1622 tcc_error("unknown array element size");
1623 #ifdef TCC_TARGET_X86_64
1624 vpushll(u);
1625 #else
1626 /* XXX: cast to int ? (long long case) */
1627 vpushi(u);
1628 #endif
1630 gen_op('*');
1631 #ifdef CONFIG_TCC_BCHECK
1632 /* if evaluating constant expression, no code should be
1633 generated, so no bound check */
1634 if (tcc_state->do_bounds_check && !const_wanted) {
1635 /* if bounded pointers, we generate a special code to
1636 test bounds */
1637 if (op == '-') {
1638 vpushi(0);
1639 vswap();
1640 gen_op('-');
1642 gen_bounded_ptr_add();
1643 } else
1644 #endif
1646 gen_opic(op);
1648 /* put again type if gen_opic() swaped operands */
1649 vtop->type = type1;
1651 } else if (is_float(bt1) || is_float(bt2)) {
1652 /* compute bigger type and do implicit casts */
1653 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
1654 t = VT_LDOUBLE;
1655 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
1656 t = VT_DOUBLE;
1657 } else {
1658 t = VT_FLOAT;
1660 /* floats can only be used for a few operations */
1661 if (op != '+' && op != '-' && op != '*' && op != '/' &&
1662 (op < TOK_ULT || op > TOK_GT))
1663 tcc_error("invalid operands for binary operation");
1664 goto std_op;
1665 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
1666 /* cast to biggest op */
1667 t = VT_LLONG;
1668 /* convert to unsigned if it does not fit in a long long */
1669 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
1670 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
1671 t |= VT_UNSIGNED;
1672 goto std_op;
1673 } else {
1674 /* integer operations */
1675 t = VT_INT;
1676 /* convert to unsigned if it does not fit in an integer */
1677 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
1678 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
1679 t |= VT_UNSIGNED;
1680 std_op:
1681 /* XXX: currently, some unsigned operations are explicit, so
1682 we modify them here */
1683 if (t & VT_UNSIGNED) {
1684 if (op == TOK_SAR)
1685 op = TOK_SHR;
1686 else if (op == '/')
1687 op = TOK_UDIV;
1688 else if (op == '%')
1689 op = TOK_UMOD;
1690 else if (op == TOK_LT)
1691 op = TOK_ULT;
1692 else if (op == TOK_GT)
1693 op = TOK_UGT;
1694 else if (op == TOK_LE)
1695 op = TOK_ULE;
1696 else if (op == TOK_GE)
1697 op = TOK_UGE;
1699 vswap();
1700 type1.t = t;
1701 gen_cast(&type1);
1702 vswap();
1703 /* special case for shifts and long long: we keep the shift as
1704 an integer */
1705 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
1706 type1.t = VT_INT;
1707 gen_cast(&type1);
1708 if (is_float(t))
1709 gen_opif(op);
1710 else
1711 gen_opic(op);
1712 if (op >= TOK_ULT && op <= TOK_GT) {
1713 /* relationnal op: the result is an int */
1714 vtop->type.t = VT_INT;
1715 } else {
1716 vtop->type.t = t;
1721 #ifndef TCC_TARGET_ARM
1722 /* generic itof for unsigned long long case */
1723 static void gen_cvt_itof1(int t)
1725 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
1726 (VT_LLONG | VT_UNSIGNED)) {
1728 if (t == VT_FLOAT)
1729 vpush_global_sym(&func_old_type, TOK___floatundisf);
1730 #if LDOUBLE_SIZE != 8
1731 else if (t == VT_LDOUBLE)
1732 vpush_global_sym(&func_old_type, TOK___floatundixf);
1733 #endif
1734 else
1735 vpush_global_sym(&func_old_type, TOK___floatundidf);
1736 vrott(2);
1737 gfunc_call(1);
1738 vpushi(0);
1739 vtop->r = reg_fret(t);
1740 } else {
1741 gen_cvt_itof(t);
1744 #endif
1746 /* generic ftoi for unsigned long long case */
1747 static void gen_cvt_ftoi1(int t)
1749 int st;
1751 if (t == (VT_LLONG | VT_UNSIGNED)) {
1752 /* not handled natively */
1753 st = vtop->type.t & VT_BTYPE;
1754 if (st == VT_FLOAT)
1755 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
1756 #if LDOUBLE_SIZE != 8
1757 else if (st == VT_LDOUBLE)
1758 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
1759 #endif
1760 else
1761 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
1762 vrott(2);
1763 gfunc_call(1);
1764 vpushi(0);
1765 vtop->r = REG_IRET;
1766 vtop->r2 = REG_LRET;
1767 } else {
1768 gen_cvt_ftoi(t);
1772 /* force char or short cast */
1773 static void force_charshort_cast(int t)
1775 int bits, dbt;
1776 dbt = t & VT_BTYPE;
1777 /* XXX: add optimization if lvalue : just change type and offset */
1778 if (dbt == VT_BYTE)
1779 bits = 8;
1780 else
1781 bits = 16;
1782 if (t & VT_UNSIGNED) {
1783 vpushi((1 << bits) - 1);
1784 gen_op('&');
1785 } else {
1786 bits = 32 - bits;
1787 vpushi(bits);
1788 gen_op(TOK_SHL);
1789 /* result must be signed or the SAR is converted to an SHL
1790 This was not the case when "t" was a signed short
1791 and the last value on the stack was an unsigned int */
1792 vtop->type.t &= ~VT_UNSIGNED;
1793 vpushi(bits);
1794 gen_op(TOK_SAR);
1798 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
1799 static void gen_cast(CType *type)
1801 int sbt, dbt, sf, df, c, p;
1803 /* special delayed cast for char/short */
1804 /* XXX: in some cases (multiple cascaded casts), it may still
1805 be incorrect */
1806 if (vtop->r & VT_MUSTCAST) {
1807 vtop->r &= ~VT_MUSTCAST;
1808 force_charshort_cast(vtop->type.t);
1811 /* bitfields first get cast to ints */
1812 if (vtop->type.t & VT_BITFIELD) {
1813 gv(RC_INT);
1816 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
1817 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
1819 if (sbt != dbt) {
1820 sf = is_float(sbt);
1821 df = is_float(dbt);
1822 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1823 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
1824 if (c) {
1825 /* constant case: we can do it now */
1826 /* XXX: in ISOC, cannot do it if error in convert */
1827 if (sbt == VT_FLOAT)
1828 vtop->c.ld = vtop->c.f;
1829 else if (sbt == VT_DOUBLE)
1830 vtop->c.ld = vtop->c.d;
1832 if (df) {
1833 if ((sbt & VT_BTYPE) == VT_LLONG) {
1834 if (sbt & VT_UNSIGNED)
1835 vtop->c.ld = vtop->c.ull;
1836 else
1837 vtop->c.ld = vtop->c.ll;
1838 } else if(!sf) {
1839 if (sbt & VT_UNSIGNED)
1840 vtop->c.ld = vtop->c.ui;
1841 else
1842 vtop->c.ld = vtop->c.i;
1845 if (dbt == VT_FLOAT)
1846 vtop->c.f = (float)vtop->c.ld;
1847 else if (dbt == VT_DOUBLE)
1848 vtop->c.d = (double)vtop->c.ld;
1849 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
1850 vtop->c.ull = (unsigned long long)vtop->c.ld;
1851 } else if (sf && dbt == VT_BOOL) {
1852 vtop->c.i = (vtop->c.ld != 0);
1853 } else {
1854 if(sf)
1855 vtop->c.ll = (long long)vtop->c.ld;
1856 else if (sbt == (VT_LLONG|VT_UNSIGNED))
1857 vtop->c.ll = vtop->c.ull;
1858 else if (sbt & VT_UNSIGNED)
1859 vtop->c.ll = vtop->c.ui;
1860 #ifdef TCC_TARGET_X86_64
1861 else if (sbt == VT_PTR)
1863 #endif
1864 else if (sbt != VT_LLONG)
1865 vtop->c.ll = vtop->c.i;
1867 if (dbt == (VT_LLONG|VT_UNSIGNED))
1868 vtop->c.ull = vtop->c.ll;
1869 else if (dbt == VT_BOOL)
1870 vtop->c.i = (vtop->c.ll != 0);
1871 else if (dbt != VT_LLONG) {
1872 int s = 0;
1873 if ((dbt & VT_BTYPE) == VT_BYTE)
1874 s = 24;
1875 else if ((dbt & VT_BTYPE) == VT_SHORT)
1876 s = 16;
1878 if(dbt & VT_UNSIGNED)
1879 vtop->c.ui = ((unsigned int)vtop->c.ll << s) >> s;
1880 else
1881 vtop->c.i = ((int)vtop->c.ll << s) >> s;
1884 } else if (p && dbt == VT_BOOL) {
1885 vtop->r = VT_CONST;
1886 vtop->c.i = 1;
1887 } else if (!nocode_wanted) {
1888 /* non constant case: generate code */
1889 if (sf && df) {
1890 /* convert from fp to fp */
1891 gen_cvt_ftof(dbt);
1892 } else if (df) {
1893 /* convert int to fp */
1894 gen_cvt_itof1(dbt);
1895 } else if (sf) {
1896 /* convert fp to int */
1897 if (dbt == VT_BOOL) {
1898 vpushi(0);
1899 gen_op(TOK_NE);
1900 } else {
1901 /* we handle char/short/etc... with generic code */
1902 if (dbt != (VT_INT | VT_UNSIGNED) &&
1903 dbt != (VT_LLONG | VT_UNSIGNED) &&
1904 dbt != VT_LLONG)
1905 dbt = VT_INT;
1906 gen_cvt_ftoi1(dbt);
1907 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
1908 /* additional cast for char/short... */
1909 vtop->type.t = dbt;
1910 gen_cast(type);
1913 #ifndef TCC_TARGET_X86_64
1914 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
1915 if ((sbt & VT_BTYPE) != VT_LLONG) {
1916 /* scalar to long long */
1917 /* machine independent conversion */
1918 gv(RC_INT);
1919 /* generate high word */
1920 if (sbt == (VT_INT | VT_UNSIGNED)) {
1921 vpushi(0);
1922 gv(RC_INT);
1923 } else {
1924 if (sbt == VT_PTR) {
1925 /* cast from pointer to int before we apply
1926 shift operation, which pointers don't support*/
1927 gen_cast(&int_type);
1929 gv_dup();
1930 vpushi(31);
1931 gen_op(TOK_SAR);
1933 /* patch second register */
1934 vtop[-1].r2 = vtop->r;
1935 vpop();
1937 #else
1938 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
1939 (dbt & VT_BTYPE) == VT_PTR ||
1940 (dbt & VT_BTYPE) == VT_FUNC) {
1941 if ((sbt & VT_BTYPE) != VT_LLONG &&
1942 (sbt & VT_BTYPE) != VT_PTR &&
1943 (sbt & VT_BTYPE) != VT_FUNC) {
1944 /* need to convert from 32bit to 64bit */
1945 int r = gv(RC_INT);
1946 if (sbt != (VT_INT | VT_UNSIGNED)) {
1947 /* x86_64 specific: movslq */
1948 o(0x6348);
1949 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
1952 #endif
1953 } else if (dbt == VT_BOOL) {
1954 /* scalar to bool */
1955 vpushi(0);
1956 gen_op(TOK_NE);
1957 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
1958 (dbt & VT_BTYPE) == VT_SHORT) {
1959 if (sbt == VT_PTR) {
1960 vtop->type.t = VT_INT;
1961 tcc_warning("nonportable conversion from pointer to char/short");
1963 force_charshort_cast(dbt);
1964 } else if ((dbt & VT_BTYPE) == VT_INT) {
1965 /* scalar to int */
1966 if (sbt == VT_LLONG) {
1967 /* from long long: just take low order word */
1968 lexpand();
1969 vpop();
1971 /* if lvalue and single word type, nothing to do because
1972 the lvalue already contains the real type size (see
1973 VT_LVAL_xxx constants) */
1976 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
1977 /* if we are casting between pointer types,
1978 we must update the VT_LVAL_xxx size */
1979 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
1980 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
1982 vtop->type = *type;
1985 /* return type size as known at compile time. Put alignment at 'a' */
1986 ST_FUNC int type_size(CType *type, int *a)
1988 Sym *s;
1989 int bt;
1991 bt = type->t & VT_BTYPE;
1992 if (bt == VT_STRUCT) {
1993 /* struct/union */
1994 s = type->ref;
1995 *a = s->r;
1996 return s->c;
1997 } else if (bt == VT_PTR) {
1998 if (type->t & VT_ARRAY) {
1999 int ts;
2001 s = type->ref;
2002 ts = type_size(&s->type, a);
2004 if (ts < 0 && s->c < 0)
2005 ts = -ts;
2007 return ts * s->c;
2008 } else {
2009 *a = PTR_SIZE;
2010 return PTR_SIZE;
2012 } else if (bt == VT_LDOUBLE) {
2013 *a = LDOUBLE_ALIGN;
2014 return LDOUBLE_SIZE;
2015 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
2016 #ifdef TCC_TARGET_I386
2017 #ifdef TCC_TARGET_PE
2018 *a = 8;
2019 #else
2020 *a = 4;
2021 #endif
2022 #elif defined(TCC_TARGET_ARM)
2023 #ifdef TCC_ARM_EABI
2024 *a = 8;
2025 #else
2026 *a = 4;
2027 #endif
2028 #else
2029 *a = 8;
2030 #endif
2031 return 8;
2032 } else if (bt == VT_INT || bt == VT_ENUM || bt == VT_FLOAT) {
2033 *a = 4;
2034 return 4;
2035 } else if (bt == VT_SHORT) {
2036 *a = 2;
2037 return 2;
2038 } else {
2039 /* char, void, function, _Bool */
2040 *a = 1;
2041 return 1;
2045 /* push type size as known at runtime time on top of value stack. Put
2046 alignment at 'a' */
2047 ST_FUNC void vla_runtime_type_size(CType *type, int *a)
2049 if (type->t & VT_VLA) {
2050 vset(&int_type, VT_LOCAL|VT_LVAL, type->ref->c);
2051 } else {
2052 vpushi(type_size(type, a));
2056 /* return the pointed type of t */
2057 static inline CType *pointed_type(CType *type)
2059 return &type->ref->type;
2062 /* modify type so that its it is a pointer to type. */
2063 ST_FUNC void mk_pointer(CType *type)
2065 Sym *s;
2066 s = sym_push(SYM_FIELD, type, 0, -1);
2067 type->t = VT_PTR | (type->t & ~VT_TYPE);
2068 type->ref = s;
2071 /* compare function types. OLD functions match any new functions */
2072 static int is_compatible_func(CType *type1, CType *type2)
2074 Sym *s1, *s2;
2076 s1 = type1->ref;
2077 s2 = type2->ref;
2078 if (!is_compatible_types(&s1->type, &s2->type))
2079 return 0;
2080 /* check func_call */
2081 if (FUNC_CALL(s1->r) != FUNC_CALL(s2->r))
2082 return 0;
2083 /* XXX: not complete */
2084 if (s1->c == FUNC_OLD || s2->c == FUNC_OLD)
2085 return 1;
2086 if (s1->c != s2->c)
2087 return 0;
2088 while (s1 != NULL) {
2089 if (s2 == NULL)
2090 return 0;
2091 if (!is_compatible_parameter_types(&s1->type, &s2->type))
2092 return 0;
2093 s1 = s1->next;
2094 s2 = s2->next;
2096 if (s2)
2097 return 0;
2098 return 1;
2101 /* return true if type1 and type2 are the same. If unqualified is
2102 true, qualifiers on the types are ignored.
2104 - enums are not checked as gcc __builtin_types_compatible_p ()
2106 static int compare_types(CType *type1, CType *type2, int unqualified)
2108 int bt1, t1, t2;
2110 t1 = type1->t & VT_TYPE;
2111 t2 = type2->t & VT_TYPE;
2112 if (unqualified) {
2113 /* strip qualifiers before comparing */
2114 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
2115 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
2117 /* XXX: bitfields ? */
2118 if (t1 != t2)
2119 return 0;
2120 /* test more complicated cases */
2121 bt1 = t1 & VT_BTYPE;
2122 if (bt1 == VT_PTR) {
2123 type1 = pointed_type(type1);
2124 type2 = pointed_type(type2);
2125 return is_compatible_types(type1, type2);
2126 } else if (bt1 == VT_STRUCT) {
2127 return (type1->ref == type2->ref);
2128 } else if (bt1 == VT_FUNC) {
2129 return is_compatible_func(type1, type2);
2130 } else {
2131 return 1;
2135 /* return true if type1 and type2 are exactly the same (including
2136 qualifiers).
2138 static int is_compatible_types(CType *type1, CType *type2)
2140 return compare_types(type1,type2,0);
2143 /* return true if type1 and type2 are the same (ignoring qualifiers).
2145 static int is_compatible_parameter_types(CType *type1, CType *type2)
2147 return compare_types(type1,type2,1);
2150 /* print a type. If 'varstr' is not NULL, then the variable is also
2151 printed in the type */
2152 /* XXX: union */
2153 /* XXX: add array and function pointers */
2154 static void type_to_str(char *buf, int buf_size,
2155 CType *type, const char *varstr)
2157 int bt, v, t;
2158 Sym *s, *sa;
2159 char buf1[256];
2160 const char *tstr;
2162 t = type->t & VT_TYPE;
2163 bt = t & VT_BTYPE;
2164 buf[0] = '\0';
2165 if (t & VT_CONSTANT)
2166 pstrcat(buf, buf_size, "const ");
2167 if (t & VT_VOLATILE)
2168 pstrcat(buf, buf_size, "volatile ");
2169 if (t & VT_UNSIGNED)
2170 pstrcat(buf, buf_size, "unsigned ");
2171 switch(bt) {
2172 case VT_VOID:
2173 tstr = "void";
2174 goto add_tstr;
2175 case VT_BOOL:
2176 tstr = "_Bool";
2177 goto add_tstr;
2178 case VT_BYTE:
2179 tstr = "char";
2180 goto add_tstr;
2181 case VT_SHORT:
2182 tstr = "short";
2183 goto add_tstr;
2184 case VT_INT:
2185 tstr = "int";
2186 goto add_tstr;
2187 case VT_LONG:
2188 tstr = "long";
2189 goto add_tstr;
2190 case VT_LLONG:
2191 tstr = "long long";
2192 goto add_tstr;
2193 case VT_FLOAT:
2194 tstr = "float";
2195 goto add_tstr;
2196 case VT_DOUBLE:
2197 tstr = "double";
2198 goto add_tstr;
2199 case VT_LDOUBLE:
2200 tstr = "long double";
2201 add_tstr:
2202 pstrcat(buf, buf_size, tstr);
2203 break;
2204 case VT_ENUM:
2205 case VT_STRUCT:
2206 if (bt == VT_STRUCT)
2207 tstr = "struct ";
2208 else
2209 tstr = "enum ";
2210 pstrcat(buf, buf_size, tstr);
2211 v = type->ref->v & ~SYM_STRUCT;
2212 if (v >= SYM_FIRST_ANOM)
2213 pstrcat(buf, buf_size, "<anonymous>");
2214 else
2215 pstrcat(buf, buf_size, get_tok_str(v, NULL));
2216 break;
2217 case VT_FUNC:
2218 s = type->ref;
2219 type_to_str(buf, buf_size, &s->type, varstr);
2220 pstrcat(buf, buf_size, "(");
2221 sa = s->next;
2222 while (sa != NULL) {
2223 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
2224 pstrcat(buf, buf_size, buf1);
2225 sa = sa->next;
2226 if (sa)
2227 pstrcat(buf, buf_size, ", ");
2229 pstrcat(buf, buf_size, ")");
2230 goto no_var;
2231 case VT_PTR:
2232 s = type->ref;
2233 pstrcpy(buf1, sizeof(buf1), "*");
2234 if (varstr)
2235 pstrcat(buf1, sizeof(buf1), varstr);
2236 type_to_str(buf, buf_size, &s->type, buf1);
2237 goto no_var;
2239 if (varstr) {
2240 pstrcat(buf, buf_size, " ");
2241 pstrcat(buf, buf_size, varstr);
2243 no_var: ;
2246 /* verify type compatibility to store vtop in 'dt' type, and generate
2247 casts if needed. */
2248 static void gen_assign_cast(CType *dt)
2250 CType *st, *type1, *type2, tmp_type1, tmp_type2;
2251 char buf1[256], buf2[256];
2252 int dbt, sbt;
2254 st = &vtop->type; /* source type */
2255 dbt = dt->t & VT_BTYPE;
2256 sbt = st->t & VT_BTYPE;
2257 if (sbt == VT_VOID)
2258 tcc_error("Cannot assign void value");
2259 if (dt->t & VT_CONSTANT)
2260 tcc_warning("assignment of read-only location");
2261 switch(dbt) {
2262 case VT_PTR:
2263 /* special cases for pointers */
2264 /* '0' can also be a pointer */
2265 if (is_null_pointer(vtop))
2266 goto type_ok;
2267 /* accept implicit pointer to integer cast with warning */
2268 if (is_integer_btype(sbt)) {
2269 tcc_warning("assignment makes pointer from integer without a cast");
2270 goto type_ok;
2272 type1 = pointed_type(dt);
2273 /* a function is implicitely a function pointer */
2274 if (sbt == VT_FUNC) {
2275 if ((type1->t & VT_BTYPE) != VT_VOID &&
2276 !is_compatible_types(pointed_type(dt), st))
2277 tcc_warning("assignment from incompatible pointer type");
2278 goto type_ok;
2280 if (sbt != VT_PTR)
2281 goto error;
2282 type2 = pointed_type(st);
2283 if ((type1->t & VT_BTYPE) == VT_VOID ||
2284 (type2->t & VT_BTYPE) == VT_VOID) {
2285 /* void * can match anything */
2286 } else {
2287 /* exact type match, except for unsigned */
2288 tmp_type1 = *type1;
2289 tmp_type2 = *type2;
2290 tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
2291 tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
2292 if (!is_compatible_types(&tmp_type1, &tmp_type2))
2293 tcc_warning("assignment from incompatible pointer type");
2295 /* check const and volatile */
2296 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
2297 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
2298 tcc_warning("assignment discards qualifiers from pointer target type");
2299 break;
2300 case VT_BYTE:
2301 case VT_SHORT:
2302 case VT_INT:
2303 case VT_LLONG:
2304 if (sbt == VT_PTR || sbt == VT_FUNC) {
2305 tcc_warning("assignment makes integer from pointer without a cast");
2307 /* XXX: more tests */
2308 break;
2309 case VT_STRUCT:
2310 tmp_type1 = *dt;
2311 tmp_type2 = *st;
2312 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2313 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2314 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2315 error:
2316 type_to_str(buf1, sizeof(buf1), st, NULL);
2317 type_to_str(buf2, sizeof(buf2), dt, NULL);
2318 tcc_error("cannot cast '%s' to '%s'", buf1, buf2);
2320 break;
2322 type_ok:
2323 gen_cast(dt);
2326 /* store vtop in lvalue pushed on stack */
2327 ST_FUNC void vstore(void)
2329 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
2331 ft = vtop[-1].type.t;
2332 sbt = vtop->type.t & VT_BTYPE;
2333 dbt = ft & VT_BTYPE;
2334 if ((((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
2335 (sbt == VT_INT && dbt == VT_SHORT))
2336 && !(vtop->type.t & VT_BITFIELD)) {
2337 /* optimize char/short casts */
2338 delayed_cast = VT_MUSTCAST;
2339 vtop->type.t = ft & (VT_TYPE & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT)));
2340 /* XXX: factorize */
2341 if (ft & VT_CONSTANT)
2342 tcc_warning("assignment of read-only location");
2343 } else {
2344 delayed_cast = 0;
2345 if (!(ft & VT_BITFIELD))
2346 gen_assign_cast(&vtop[-1].type);
2349 if (sbt == VT_STRUCT) {
2350 /* if structure, only generate pointer */
2351 /* structure assignment : generate memcpy */
2352 /* XXX: optimize if small size */
2353 if (!nocode_wanted) {
2354 size = type_size(&vtop->type, &align);
2356 /* destination */
2357 vswap();
2358 vtop->type.t = VT_PTR;
2359 gaddrof();
2361 /* address of memcpy() */
2362 #ifdef TCC_ARM_EABI
2363 if(!(align & 7))
2364 vpush_global_sym(&func_old_type, TOK_memcpy8);
2365 else if(!(align & 3))
2366 vpush_global_sym(&func_old_type, TOK_memcpy4);
2367 else
2368 #endif
2369 vpush_global_sym(&func_old_type, TOK_memcpy);
2371 vswap();
2372 /* source */
2373 vpushv(vtop - 2);
2374 vtop->type.t = VT_PTR;
2375 gaddrof();
2376 /* type size */
2377 vpushi(size);
2378 gfunc_call(3);
2379 } else {
2380 vswap();
2381 vpop();
2383 /* leave source on stack */
2384 } else if (ft & VT_BITFIELD) {
2385 /* bitfield store handling */
2386 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
2387 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
2388 /* remove bit field info to avoid loops */
2389 vtop[-1].type.t = ft & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
2391 /* duplicate source into other register */
2392 gv_dup();
2393 vswap();
2394 vrott(3);
2396 if((ft & VT_BTYPE) == VT_BOOL) {
2397 gen_cast(&vtop[-1].type);
2398 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
2401 /* duplicate destination */
2402 vdup();
2403 vtop[-1] = vtop[-2];
2405 /* mask and shift source */
2406 if((ft & VT_BTYPE) != VT_BOOL) {
2407 if((ft & VT_BTYPE) == VT_LLONG) {
2408 vpushll((1ULL << bit_size) - 1ULL);
2409 } else {
2410 vpushi((1 << bit_size) - 1);
2412 gen_op('&');
2414 vpushi(bit_pos);
2415 gen_op(TOK_SHL);
2416 /* load destination, mask and or with source */
2417 vswap();
2418 if((ft & VT_BTYPE) == VT_LLONG) {
2419 vpushll(~(((1ULL << bit_size) - 1ULL) << bit_pos));
2420 } else {
2421 vpushi(~(((1 << bit_size) - 1) << bit_pos));
2423 gen_op('&');
2424 gen_op('|');
2425 /* store result */
2426 vstore();
2428 /* pop off shifted source from "duplicate source..." above */
2429 vpop();
2431 } else {
2432 #ifdef CONFIG_TCC_BCHECK
2433 /* bound check case */
2434 if (vtop[-1].r & VT_MUSTBOUND) {
2435 vswap();
2436 gbound();
2437 vswap();
2439 #endif
2440 if (!nocode_wanted) {
2441 rc = RC_INT;
2442 if (is_float(ft)) {
2443 rc = RC_FLOAT;
2444 #ifdef TCC_TARGET_X86_64
2445 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
2446 rc = RC_ST0;
2448 #endif
2450 r = gv(rc); /* generate value */
2451 /* if lvalue was saved on stack, must read it */
2452 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
2453 SValue sv;
2454 t = get_reg(RC_INT);
2455 #ifdef TCC_TARGET_X86_64
2456 sv.type.t = VT_PTR;
2457 #else
2458 sv.type.t = VT_INT;
2459 #endif
2460 sv.r = VT_LOCAL | VT_LVAL;
2461 sv.c.ul = vtop[-1].c.ul;
2462 load(t, &sv);
2463 vtop[-1].r = t | VT_LVAL;
2465 store(r, vtop - 1);
2466 #ifndef TCC_TARGET_X86_64
2467 /* two word case handling : store second register at word + 4 */
2468 if ((ft & VT_BTYPE) == VT_LLONG) {
2469 vswap();
2470 /* convert to int to increment easily */
2471 vtop->type.t = VT_INT;
2472 gaddrof();
2473 vpushi(4);
2474 gen_op('+');
2475 vtop->r |= VT_LVAL;
2476 vswap();
2477 /* XXX: it works because r2 is spilled last ! */
2478 store(vtop->r2, vtop - 1);
2480 #endif
2482 vswap();
2483 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
2484 vtop->r |= delayed_cast;
2488 /* post defines POST/PRE add. c is the token ++ or -- */
2489 ST_FUNC void inc(int post, int c)
2491 test_lvalue();
2492 vdup(); /* save lvalue */
2493 if (post) {
2494 gv_dup(); /* duplicate value */
2495 vrotb(3);
2496 vrotb(3);
2498 /* add constant */
2499 vpushi(c - TOK_MID);
2500 gen_op('+');
2501 vstore(); /* store value */
2502 if (post)
2503 vpop(); /* if post op, return saved value */
2506 /* Parse GNUC __attribute__ extension. Currently, the following
2507 extensions are recognized:
2508 - aligned(n) : set data/function alignment.
2509 - packed : force data alignment to 1
2510 - section(x) : generate data/code in this section.
2511 - unused : currently ignored, but may be used someday.
2512 - regparm(n) : pass function parameters in registers (i386 only)
2514 static void parse_attribute(AttributeDef *ad)
2516 int t, n;
2518 while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
2519 next();
2520 skip('(');
2521 skip('(');
2522 while (tok != ')') {
2523 if (tok < TOK_IDENT)
2524 expect("attribute name");
2525 t = tok;
2526 next();
2527 switch(t) {
2528 case TOK_SECTION1:
2529 case TOK_SECTION2:
2530 skip('(');
2531 if (tok != TOK_STR)
2532 expect("section name");
2533 ad->section = find_section(tcc_state, (char *)tokc.cstr->data);
2534 next();
2535 skip(')');
2536 break;
2537 case TOK_ALIAS1:
2538 case TOK_ALIAS2:
2539 skip('(');
2540 if (tok != TOK_STR)
2541 expect("alias(\"target\")");
2542 ad->alias_target = /* save string as token, for later */
2543 tok_alloc((char*)tokc.cstr->data, tokc.cstr->size-1)->tok;
2544 next();
2545 skip(')');
2546 break;
2547 case TOK_ALIGNED1:
2548 case TOK_ALIGNED2:
2549 if (tok == '(') {
2550 next();
2551 n = expr_const();
2552 if (n <= 0 || (n & (n - 1)) != 0)
2553 tcc_error("alignment must be a positive power of two");
2554 skip(')');
2555 } else {
2556 n = MAX_ALIGN;
2558 ad->aligned = n;
2559 break;
2560 case TOK_PACKED1:
2561 case TOK_PACKED2:
2562 ad->packed = 1;
2563 break;
2564 case TOK_WEAK1:
2565 case TOK_WEAK2:
2566 ad->weak = 1;
2567 break;
2568 case TOK_UNUSED1:
2569 case TOK_UNUSED2:
2570 /* currently, no need to handle it because tcc does not
2571 track unused objects */
2572 break;
2573 case TOK_NORETURN1:
2574 case TOK_NORETURN2:
2575 /* currently, no need to handle it because tcc does not
2576 track unused objects */
2577 break;
2578 case TOK_CDECL1:
2579 case TOK_CDECL2:
2580 case TOK_CDECL3:
2581 ad->func_call = FUNC_CDECL;
2582 break;
2583 case TOK_STDCALL1:
2584 case TOK_STDCALL2:
2585 case TOK_STDCALL3:
2586 ad->func_call = FUNC_STDCALL;
2587 break;
2588 #ifdef TCC_TARGET_I386
2589 case TOK_REGPARM1:
2590 case TOK_REGPARM2:
2591 skip('(');
2592 n = expr_const();
2593 if (n > 3)
2594 n = 3;
2595 else if (n < 0)
2596 n = 0;
2597 if (n > 0)
2598 ad->func_call = FUNC_FASTCALL1 + n - 1;
2599 skip(')');
2600 break;
2601 case TOK_FASTCALL1:
2602 case TOK_FASTCALL2:
2603 case TOK_FASTCALL3:
2604 ad->func_call = FUNC_FASTCALLW;
2605 break;
2606 #endif
2607 case TOK_MODE:
2608 skip('(');
2609 switch(tok) {
2610 case TOK_MODE_DI:
2611 ad->mode = VT_LLONG + 1;
2612 break;
2613 case TOK_MODE_HI:
2614 ad->mode = VT_SHORT + 1;
2615 break;
2616 case TOK_MODE_SI:
2617 ad->mode = VT_INT + 1;
2618 break;
2619 default:
2620 tcc_warning("__mode__(%s) not supported\n", get_tok_str(tok, NULL));
2621 break;
2623 next();
2624 skip(')');
2625 break;
2626 case TOK_DLLEXPORT:
2627 ad->func_export = 1;
2628 break;
2629 case TOK_DLLIMPORT:
2630 ad->func_import = 1;
2631 break;
2632 default:
2633 if (tcc_state->warn_unsupported)
2634 tcc_warning("'%s' attribute ignored", get_tok_str(t, NULL));
2635 /* skip parameters */
2636 if (tok == '(') {
2637 int parenthesis = 0;
2638 do {
2639 if (tok == '(')
2640 parenthesis++;
2641 else if (tok == ')')
2642 parenthesis--;
2643 next();
2644 } while (parenthesis && tok != -1);
2646 break;
2648 if (tok != ',')
2649 break;
2650 next();
2652 skip(')');
2653 skip(')');
2657 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
2658 static void struct_decl(CType *type, int u)
2660 int a, v, size, align, maxalign, c, offset;
2661 int bit_size, bit_pos, bsize, bt, lbit_pos, prevbt;
2662 Sym *s, *ss, *ass, **ps;
2663 AttributeDef ad;
2664 CType type1, btype;
2666 a = tok; /* save decl type */
2667 next();
2668 if (tok != '{') {
2669 v = tok;
2670 next();
2671 /* struct already defined ? return it */
2672 if (v < TOK_IDENT)
2673 expect("struct/union/enum name");
2674 s = struct_find(v);
2675 if (s) {
2676 if (s->type.t != a)
2677 tcc_error("invalid type");
2678 goto do_decl;
2680 } else {
2681 v = anon_sym++;
2683 type1.t = a;
2684 /* we put an undefined size for struct/union */
2685 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
2686 s->r = 0; /* default alignment is zero as gcc */
2687 /* put struct/union/enum name in type */
2688 do_decl:
2689 type->t = u;
2690 type->ref = s;
2692 if (tok == '{') {
2693 next();
2694 if (s->c != -1)
2695 tcc_error("struct/union/enum already defined");
2696 /* cannot be empty */
2697 c = 0;
2698 /* non empty enums are not allowed */
2699 if (a == TOK_ENUM) {
2700 for(;;) {
2701 v = tok;
2702 if (v < TOK_UIDENT)
2703 expect("identifier");
2704 next();
2705 if (tok == '=') {
2706 next();
2707 c = expr_const();
2709 /* enum symbols have static storage */
2710 ss = sym_push(v, &int_type, VT_CONST, c);
2711 ss->type.t |= VT_STATIC;
2712 if (tok != ',')
2713 break;
2714 next();
2715 c++;
2716 /* NOTE: we accept a trailing comma */
2717 if (tok == '}')
2718 break;
2720 skip('}');
2721 } else {
2722 maxalign = 1;
2723 ps = &s->next;
2724 prevbt = VT_INT;
2725 bit_pos = 0;
2726 offset = 0;
2727 while (tok != '}') {
2728 parse_btype(&btype, &ad);
2729 while (1) {
2730 bit_size = -1;
2731 v = 0;
2732 type1 = btype;
2733 if (tok != ':') {
2734 type_decl(&type1, &ad, &v, TYPE_DIRECT | TYPE_ABSTRACT);
2735 if (v == 0 && (type1.t & VT_BTYPE) != VT_STRUCT)
2736 expect("identifier");
2737 if ((type1.t & VT_BTYPE) == VT_FUNC ||
2738 (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
2739 tcc_error("invalid type for '%s'",
2740 get_tok_str(v, NULL));
2742 if (tok == ':') {
2743 next();
2744 bit_size = expr_const();
2745 /* XXX: handle v = 0 case for messages */
2746 if (bit_size < 0)
2747 tcc_error("negative width in bit-field '%s'",
2748 get_tok_str(v, NULL));
2749 if (v && bit_size == 0)
2750 tcc_error("zero width for bit-field '%s'",
2751 get_tok_str(v, NULL));
2753 size = type_size(&type1, &align);
2754 if (ad.aligned) {
2755 if (align < ad.aligned)
2756 align = ad.aligned;
2757 } else if (ad.packed) {
2758 align = 1;
2759 } else if (*tcc_state->pack_stack_ptr) {
2760 if (align > *tcc_state->pack_stack_ptr)
2761 align = *tcc_state->pack_stack_ptr;
2763 lbit_pos = 0;
2764 if (bit_size >= 0) {
2765 bt = type1.t & VT_BTYPE;
2766 if (bt != VT_INT &&
2767 bt != VT_BYTE &&
2768 bt != VT_SHORT &&
2769 bt != VT_BOOL &&
2770 bt != VT_ENUM &&
2771 bt != VT_LLONG)
2772 tcc_error("bitfields must have scalar type");
2773 bsize = size * 8;
2774 if (bit_size > bsize) {
2775 tcc_error("width of '%s' exceeds its type",
2776 get_tok_str(v, NULL));
2777 } else if (bit_size == bsize) {
2778 /* no need for bit fields */
2779 bit_pos = 0;
2780 } else if (bit_size == 0) {
2781 /* XXX: what to do if only padding in a
2782 structure ? */
2783 /* zero size: means to pad */
2784 bit_pos = 0;
2785 } else {
2786 /* we do not have enough room ?
2787 did the type change?
2788 is it a union? */
2789 if ((bit_pos + bit_size) > bsize ||
2790 bt != prevbt || a == TOK_UNION)
2791 bit_pos = 0;
2792 lbit_pos = bit_pos;
2793 /* XXX: handle LSB first */
2794 type1.t |= VT_BITFIELD |
2795 (bit_pos << VT_STRUCT_SHIFT) |
2796 (bit_size << (VT_STRUCT_SHIFT + 6));
2797 bit_pos += bit_size;
2799 prevbt = bt;
2800 } else {
2801 bit_pos = 0;
2803 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
2804 /* add new memory data only if starting
2805 bit field */
2806 if (lbit_pos == 0) {
2807 if (a == TOK_STRUCT) {
2808 c = (c + align - 1) & -align;
2809 offset = c;
2810 if (size > 0)
2811 c += size;
2812 } else {
2813 offset = 0;
2814 if (size > c)
2815 c = size;
2817 if (align > maxalign)
2818 maxalign = align;
2820 #if 0
2821 printf("add field %s offset=%d",
2822 get_tok_str(v, NULL), offset);
2823 if (type1.t & VT_BITFIELD) {
2824 printf(" pos=%d size=%d",
2825 (type1.t >> VT_STRUCT_SHIFT) & 0x3f,
2826 (type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
2828 printf("\n");
2829 #endif
2831 if (v == 0 && (type1.t & VT_BTYPE) == VT_STRUCT) {
2832 ass = type1.ref;
2833 while ((ass = ass->next) != NULL) {
2834 ss = sym_push(ass->v, &ass->type, 0, offset + ass->c);
2835 *ps = ss;
2836 ps = &ss->next;
2838 } else if (v) {
2839 ss = sym_push(v | SYM_FIELD, &type1, 0, offset);
2840 *ps = ss;
2841 ps = &ss->next;
2843 if (tok == ';' || tok == TOK_EOF)
2844 break;
2845 skip(',');
2847 skip(';');
2849 skip('}');
2850 /* store size and alignment */
2851 s->c = (c + maxalign - 1) & -maxalign;
2852 s->r = maxalign;
2857 /* return 0 if no type declaration. otherwise, return the basic type
2858 and skip it.
2860 static int parse_btype(CType *type, AttributeDef *ad)
2862 int t, u, type_found, typespec_found, typedef_found;
2863 Sym *s;
2864 CType type1;
2866 memset(ad, 0, sizeof(AttributeDef));
2867 type_found = 0;
2868 typespec_found = 0;
2869 typedef_found = 0;
2870 t = 0;
2871 while(1) {
2872 switch(tok) {
2873 case TOK_EXTENSION:
2874 /* currently, we really ignore extension */
2875 next();
2876 continue;
2878 /* basic types */
2879 case TOK_CHAR:
2880 u = VT_BYTE;
2881 basic_type:
2882 next();
2883 basic_type1:
2884 if ((t & VT_BTYPE) != 0)
2885 tcc_error("too many basic types");
2886 t |= u;
2887 typespec_found = 1;
2888 break;
2889 case TOK_VOID:
2890 u = VT_VOID;
2891 goto basic_type;
2892 case TOK_SHORT:
2893 u = VT_SHORT;
2894 goto basic_type;
2895 case TOK_INT:
2896 next();
2897 typespec_found = 1;
2898 break;
2899 case TOK_LONG:
2900 next();
2901 if ((t & VT_BTYPE) == VT_DOUBLE) {
2902 #ifndef TCC_TARGET_PE
2903 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
2904 #endif
2905 } else if ((t & VT_BTYPE) == VT_LONG) {
2906 t = (t & ~VT_BTYPE) | VT_LLONG;
2907 } else {
2908 u = VT_LONG;
2909 goto basic_type1;
2911 break;
2912 case TOK_BOOL:
2913 u = VT_BOOL;
2914 goto basic_type;
2915 case TOK_FLOAT:
2916 u = VT_FLOAT;
2917 goto basic_type;
2918 case TOK_DOUBLE:
2919 next();
2920 if ((t & VT_BTYPE) == VT_LONG) {
2921 #ifdef TCC_TARGET_PE
2922 t = (t & ~VT_BTYPE) | VT_DOUBLE;
2923 #else
2924 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
2925 #endif
2926 } else {
2927 u = VT_DOUBLE;
2928 goto basic_type1;
2930 break;
2931 case TOK_ENUM:
2932 struct_decl(&type1, VT_ENUM);
2933 basic_type2:
2934 u = type1.t;
2935 type->ref = type1.ref;
2936 goto basic_type1;
2937 case TOK_STRUCT:
2938 case TOK_UNION:
2939 struct_decl(&type1, VT_STRUCT);
2940 goto basic_type2;
2942 /* type modifiers */
2943 case TOK_CONST1:
2944 case TOK_CONST2:
2945 case TOK_CONST3:
2946 t |= VT_CONSTANT;
2947 next();
2948 break;
2949 case TOK_VOLATILE1:
2950 case TOK_VOLATILE2:
2951 case TOK_VOLATILE3:
2952 t |= VT_VOLATILE;
2953 next();
2954 break;
2955 case TOK_SIGNED1:
2956 case TOK_SIGNED2:
2957 case TOK_SIGNED3:
2958 typespec_found = 1;
2959 t |= VT_SIGNED;
2960 next();
2961 break;
2962 case TOK_REGISTER:
2963 case TOK_AUTO:
2964 case TOK_RESTRICT1:
2965 case TOK_RESTRICT2:
2966 case TOK_RESTRICT3:
2967 next();
2968 break;
2969 case TOK_UNSIGNED:
2970 t |= VT_UNSIGNED;
2971 next();
2972 typespec_found = 1;
2973 break;
2975 /* storage */
2976 case TOK_EXTERN:
2977 t |= VT_EXTERN;
2978 next();
2979 break;
2980 case TOK_STATIC:
2981 t |= VT_STATIC;
2982 next();
2983 break;
2984 case TOK_TYPEDEF:
2985 t |= VT_TYPEDEF;
2986 next();
2987 break;
2988 case TOK_INLINE1:
2989 case TOK_INLINE2:
2990 case TOK_INLINE3:
2991 t |= VT_INLINE;
2992 next();
2993 break;
2995 /* GNUC attribute */
2996 case TOK_ATTRIBUTE1:
2997 case TOK_ATTRIBUTE2:
2998 parse_attribute(ad);
2999 if (ad->mode) {
3000 u = ad->mode -1;
3001 t = (t & ~VT_BTYPE) | u;
3003 break;
3004 /* GNUC typeof */
3005 case TOK_TYPEOF1:
3006 case TOK_TYPEOF2:
3007 case TOK_TYPEOF3:
3008 next();
3009 parse_expr_type(&type1);
3010 /* remove all storage modifiers except typedef */
3011 type1.t &= ~(VT_STORAGE&~VT_TYPEDEF);
3012 goto basic_type2;
3013 default:
3014 if (typespec_found || typedef_found)
3015 goto the_end;
3016 s = sym_find(tok);
3017 if (!s || !(s->type.t & VT_TYPEDEF))
3018 goto the_end;
3019 typedef_found = 1;
3020 t |= (s->type.t & ~VT_TYPEDEF);
3021 type->ref = s->type.ref;
3022 if (s->r) {
3023 /* get attributes from typedef */
3024 if (0 == ad->aligned)
3025 ad->aligned = FUNC_ALIGN(s->r);
3026 if (0 == ad->func_call)
3027 ad->func_call = FUNC_CALL(s->r);
3028 ad->packed |= FUNC_PACKED(s->r);
3030 next();
3031 typespec_found = 1;
3032 break;
3034 type_found = 1;
3036 the_end:
3037 if ((t & (VT_SIGNED|VT_UNSIGNED)) == (VT_SIGNED|VT_UNSIGNED))
3038 tcc_error("signed and unsigned modifier");
3039 if (tcc_state->char_is_unsigned) {
3040 if ((t & (VT_SIGNED|VT_UNSIGNED|VT_BTYPE)) == VT_BYTE)
3041 t |= VT_UNSIGNED;
3043 t &= ~VT_SIGNED;
3045 /* long is never used as type */
3046 if ((t & VT_BTYPE) == VT_LONG)
3047 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
3048 t = (t & ~VT_BTYPE) | VT_INT;
3049 #else
3050 t = (t & ~VT_BTYPE) | VT_LLONG;
3051 #endif
3052 type->t = t;
3053 return type_found;
3056 /* convert a function parameter type (array to pointer and function to
3057 function pointer) */
3058 static inline void convert_parameter_type(CType *pt)
3060 /* remove const and volatile qualifiers (XXX: const could be used
3061 to indicate a const function parameter */
3062 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
3063 /* array must be transformed to pointer according to ANSI C */
3064 pt->t &= ~VT_ARRAY;
3065 if ((pt->t & VT_BTYPE) == VT_FUNC) {
3066 mk_pointer(pt);
3070 ST_FUNC void parse_asm_str(CString *astr)
3072 skip('(');
3073 /* read the string */
3074 if (tok != TOK_STR)
3075 expect("string constant");
3076 cstr_new(astr);
3077 while (tok == TOK_STR) {
3078 /* XXX: add \0 handling too ? */
3079 cstr_cat(astr, tokc.cstr->data);
3080 next();
3082 cstr_ccat(astr, '\0');
3085 /* Parse an asm label and return the label
3086 * Don't forget to free the CString in the caller! */
3087 static void asm_label_instr(CString *astr)
3089 next();
3090 parse_asm_str(astr);
3091 skip(')');
3092 #ifdef ASM_DEBUG
3093 printf("asm_alias: \"%s\"\n", (char *)astr->data);
3094 #endif
3097 static void post_type(CType *type, AttributeDef *ad)
3099 int n, l, t1, arg_size, align;
3100 Sym **plast, *s, *first;
3101 AttributeDef ad1;
3102 CType pt;
3104 if (tok == '(') {
3105 /* function declaration */
3106 next();
3107 l = 0;
3108 first = NULL;
3109 plast = &first;
3110 arg_size = 0;
3111 if (tok != ')') {
3112 for(;;) {
3113 /* read param name and compute offset */
3114 if (l != FUNC_OLD) {
3115 if (!parse_btype(&pt, &ad1)) {
3116 if (l) {
3117 tcc_error("invalid type");
3118 } else {
3119 l = FUNC_OLD;
3120 goto old_proto;
3123 l = FUNC_NEW;
3124 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
3125 break;
3126 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
3127 if ((pt.t & VT_BTYPE) == VT_VOID)
3128 tcc_error("parameter declared as void");
3129 arg_size += (type_size(&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
3130 } else {
3131 old_proto:
3132 n = tok;
3133 if (n < TOK_UIDENT)
3134 expect("identifier");
3135 pt.t = VT_INT;
3136 next();
3138 convert_parameter_type(&pt);
3139 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
3140 *plast = s;
3141 plast = &s->next;
3142 if (tok == ')')
3143 break;
3144 skip(',');
3145 if (l == FUNC_NEW && tok == TOK_DOTS) {
3146 l = FUNC_ELLIPSIS;
3147 next();
3148 break;
3152 /* if no parameters, then old type prototype */
3153 if (l == 0)
3154 l = FUNC_OLD;
3155 skip(')');
3156 /* NOTE: const is ignored in returned type as it has a special
3157 meaning in gcc / C++ */
3158 type->t &= ~VT_CONSTANT;
3159 /* some ancient pre-K&R C allows a function to return an array
3160 and the array brackets to be put after the arguments, such
3161 that "int c()[]" means something like "int[] c()" */
3162 if (tok == '[') {
3163 next();
3164 skip(']'); /* only handle simple "[]" */
3165 type->t |= VT_PTR;
3167 /* we push a anonymous symbol which will contain the function prototype */
3168 ad->func_args = arg_size;
3169 s = sym_push(SYM_FIELD, type, INT_ATTR(ad), l);
3170 s->next = first;
3171 type->t = VT_FUNC;
3172 type->ref = s;
3173 } else if (tok == '[') {
3174 /* array definition */
3175 next();
3176 if (tok == TOK_RESTRICT1)
3177 next();
3178 n = -1;
3179 t1 = 0;
3180 if (tok != ']') {
3181 if (!local_stack || nocode_wanted)
3182 vpushi(expr_const());
3183 else gexpr();
3184 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3185 n = vtop->c.i;
3186 if (n < 0)
3187 tcc_error("invalid array size");
3188 } else {
3189 if (!is_integer_btype(vtop->type.t & VT_BTYPE))
3190 tcc_error("size of variable length array should be an integer");
3191 t1 = VT_VLA;
3194 skip(']');
3195 /* parse next post type */
3196 post_type(type, ad);
3197 t1 |= type->t & VT_VLA;
3199 if (t1 & VT_VLA) {
3200 loc -= type_size(&int_type, &align);
3201 loc &= -align;
3202 n = loc;
3204 vla_runtime_type_size(type, &align);
3205 gen_op('*');
3206 vset(&int_type, VT_LOCAL|VT_LVAL, loc);
3207 vswap();
3208 vstore();
3210 if (n != -1)
3211 vpop();
3213 /* we push an anonymous symbol which will contain the array
3214 element type */
3215 s = sym_push(SYM_FIELD, type, 0, n);
3216 type->t = (t1 ? VT_VLA : VT_ARRAY) | VT_PTR;
3217 type->ref = s;
3221 /* Parse a type declaration (except basic type), and return the type
3222 in 'type'. 'td' is a bitmask indicating which kind of type decl is
3223 expected. 'type' should contain the basic type. 'ad' is the
3224 attribute definition of the basic type. It can be modified by
3225 type_decl().
3227 static void type_decl(CType *type, AttributeDef *ad, int *v, int td)
3229 Sym *s;
3230 CType type1, *type2;
3231 int qualifiers, storage;
3233 while (tok == '*') {
3234 qualifiers = 0;
3235 redo:
3236 next();
3237 switch(tok) {
3238 case TOK_CONST1:
3239 case TOK_CONST2:
3240 case TOK_CONST3:
3241 qualifiers |= VT_CONSTANT;
3242 goto redo;
3243 case TOK_VOLATILE1:
3244 case TOK_VOLATILE2:
3245 case TOK_VOLATILE3:
3246 qualifiers |= VT_VOLATILE;
3247 goto redo;
3248 case TOK_RESTRICT1:
3249 case TOK_RESTRICT2:
3250 case TOK_RESTRICT3:
3251 goto redo;
3253 mk_pointer(type);
3254 type->t |= qualifiers;
3257 /* XXX: clarify attribute handling */
3258 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3259 parse_attribute(ad);
3261 /* recursive type */
3262 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
3263 type1.t = 0; /* XXX: same as int */
3264 if (tok == '(') {
3265 next();
3266 /* XXX: this is not correct to modify 'ad' at this point, but
3267 the syntax is not clear */
3268 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3269 parse_attribute(ad);
3270 type_decl(&type1, ad, v, td);
3271 skip(')');
3272 } else {
3273 /* type identifier */
3274 if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
3275 *v = tok;
3276 next();
3277 } else {
3278 if (!(td & TYPE_ABSTRACT))
3279 expect("identifier");
3280 *v = 0;
3283 storage = type->t & VT_STORAGE;
3284 type->t &= ~VT_STORAGE;
3285 post_type(type, ad);
3286 type->t |= storage;
3287 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3288 parse_attribute(ad);
3290 if (!type1.t)
3291 return;
3292 /* append type at the end of type1 */
3293 type2 = &type1;
3294 for(;;) {
3295 s = type2->ref;
3296 type2 = &s->type;
3297 if (!type2->t) {
3298 *type2 = *type;
3299 break;
3302 *type = type1;
3305 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
3306 ST_FUNC int lvalue_type(int t)
3308 int bt, r;
3309 r = VT_LVAL;
3310 bt = t & VT_BTYPE;
3311 if (bt == VT_BYTE || bt == VT_BOOL)
3312 r |= VT_LVAL_BYTE;
3313 else if (bt == VT_SHORT)
3314 r |= VT_LVAL_SHORT;
3315 else
3316 return r;
3317 if (t & VT_UNSIGNED)
3318 r |= VT_LVAL_UNSIGNED;
3319 return r;
3322 /* indirection with full error checking and bound check */
3323 ST_FUNC void indir(void)
3325 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
3326 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
3327 return;
3328 expect("pointer");
3330 if ((vtop->r & VT_LVAL) && !nocode_wanted)
3331 gv(RC_INT);
3332 vtop->type = *pointed_type(&vtop->type);
3333 /* Arrays and functions are never lvalues */
3334 if (!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_VLA)
3335 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
3336 vtop->r |= lvalue_type(vtop->type.t);
3337 /* if bound checking, the referenced pointer must be checked */
3338 #ifdef CONFIG_TCC_BCHECK
3339 if (tcc_state->do_bounds_check)
3340 vtop->r |= VT_MUSTBOUND;
3341 #endif
3345 /* pass a parameter to a function and do type checking and casting */
3346 static void gfunc_param_typed(Sym *func, Sym *arg)
3348 int func_type;
3349 CType type;
3351 func_type = func->c;
3352 if (func_type == FUNC_OLD ||
3353 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
3354 /* default casting : only need to convert float to double */
3355 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
3356 type.t = VT_DOUBLE;
3357 gen_cast(&type);
3359 } else if (arg == NULL) {
3360 tcc_error("too many arguments to function");
3361 } else {
3362 type = arg->type;
3363 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
3364 gen_assign_cast(&type);
3368 /* parse an expression of the form '(type)' or '(expr)' and return its
3369 type */
3370 static void parse_expr_type(CType *type)
3372 int n;
3373 AttributeDef ad;
3375 skip('(');
3376 if (parse_btype(type, &ad)) {
3377 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3378 } else {
3379 expr_type(type);
3381 skip(')');
3384 static void parse_type(CType *type)
3386 AttributeDef ad;
3387 int n;
3389 if (!parse_btype(type, &ad)) {
3390 expect("type");
3392 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3395 static void vpush_tokc(int t)
3397 CType type;
3398 type.t = t;
3399 type.ref = 0;
3400 vsetc(&type, VT_CONST, &tokc);
3403 ST_FUNC void unary(void)
3405 int n, t, align, size, r, sizeof_caller;
3406 CType type;
3407 Sym *s;
3408 AttributeDef ad;
3409 static int in_sizeof = 0;
3411 sizeof_caller = in_sizeof;
3412 in_sizeof = 0;
3413 /* XXX: GCC 2.95.3 does not generate a table although it should be
3414 better here */
3415 tok_next:
3416 switch(tok) {
3417 case TOK_EXTENSION:
3418 next();
3419 goto tok_next;
3420 case TOK_CINT:
3421 case TOK_CCHAR:
3422 case TOK_LCHAR:
3423 vpushi(tokc.i);
3424 next();
3425 break;
3426 case TOK_CUINT:
3427 vpush_tokc(VT_INT | VT_UNSIGNED);
3428 next();
3429 break;
3430 case TOK_CLLONG:
3431 vpush_tokc(VT_LLONG);
3432 next();
3433 break;
3434 case TOK_CULLONG:
3435 vpush_tokc(VT_LLONG | VT_UNSIGNED);
3436 next();
3437 break;
3438 case TOK_CFLOAT:
3439 vpush_tokc(VT_FLOAT);
3440 next();
3441 break;
3442 case TOK_CDOUBLE:
3443 vpush_tokc(VT_DOUBLE);
3444 next();
3445 break;
3446 case TOK_CLDOUBLE:
3447 vpush_tokc(VT_LDOUBLE);
3448 next();
3449 break;
3450 case TOK___FUNCTION__:
3451 if (!gnu_ext)
3452 goto tok_identifier;
3453 /* fall thru */
3454 case TOK___FUNC__:
3456 void *ptr;
3457 int len;
3458 /* special function name identifier */
3459 len = strlen(funcname) + 1;
3460 /* generate char[len] type */
3461 type.t = VT_BYTE;
3462 mk_pointer(&type);
3463 type.t |= VT_ARRAY;
3464 type.ref->c = len;
3465 vpush_ref(&type, data_section, data_section->data_offset, len);
3466 ptr = section_ptr_add(data_section, len);
3467 memcpy(ptr, funcname, len);
3468 next();
3470 break;
3471 case TOK_LSTR:
3472 #ifdef TCC_TARGET_PE
3473 t = VT_SHORT | VT_UNSIGNED;
3474 #else
3475 t = VT_INT;
3476 #endif
3477 goto str_init;
3478 case TOK_STR:
3479 /* string parsing */
3480 t = VT_BYTE;
3481 str_init:
3482 if (tcc_state->warn_write_strings)
3483 t |= VT_CONSTANT;
3484 type.t = t;
3485 mk_pointer(&type);
3486 type.t |= VT_ARRAY;
3487 memset(&ad, 0, sizeof(AttributeDef));
3488 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, NULL, 0);
3489 break;
3490 case '(':
3491 next();
3492 /* cast ? */
3493 if (parse_btype(&type, &ad)) {
3494 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
3495 skip(')');
3496 /* check ISOC99 compound literal */
3497 if (tok == '{') {
3498 /* data is allocated locally by default */
3499 if (global_expr)
3500 r = VT_CONST;
3501 else
3502 r = VT_LOCAL;
3503 /* all except arrays are lvalues */
3504 if (!(type.t & VT_ARRAY))
3505 r |= lvalue_type(type.t);
3506 memset(&ad, 0, sizeof(AttributeDef));
3507 decl_initializer_alloc(&type, &ad, r, 1, 0, NULL, 0);
3508 } else {
3509 if (sizeof_caller) {
3510 vpush(&type);
3511 return;
3513 unary();
3514 gen_cast(&type);
3516 } else if (tok == '{') {
3517 /* save all registers */
3518 save_regs(0);
3519 /* statement expression : we do not accept break/continue
3520 inside as GCC does */
3521 block(NULL, NULL, NULL, NULL, 0, 1);
3522 skip(')');
3523 } else {
3524 gexpr();
3525 skip(')');
3527 break;
3528 case '*':
3529 next();
3530 unary();
3531 indir();
3532 break;
3533 case '&':
3534 next();
3535 unary();
3536 /* functions names must be treated as function pointers,
3537 except for unary '&' and sizeof. Since we consider that
3538 functions are not lvalues, we only have to handle it
3539 there and in function calls. */
3540 /* arrays can also be used although they are not lvalues */
3541 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
3542 !(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
3543 test_lvalue();
3544 mk_pointer(&vtop->type);
3545 gaddrof();
3546 break;
3547 case '!':
3548 next();
3549 unary();
3550 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3551 CType boolean;
3552 boolean.t = VT_BOOL;
3553 gen_cast(&boolean);
3554 vtop->c.i = !vtop->c.i;
3555 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
3556 vtop->c.i = vtop->c.i ^ 1;
3557 else {
3558 save_regs(1);
3559 vseti(VT_JMP, gtst(1, 0));
3561 break;
3562 case '~':
3563 next();
3564 unary();
3565 vpushi(-1);
3566 gen_op('^');
3567 break;
3568 case '+':
3569 next();
3570 /* in order to force cast, we add zero */
3571 unary();
3572 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
3573 tcc_error("pointer not accepted for unary plus");
3574 vpushi(0);
3575 gen_op('+');
3576 break;
3577 case TOK_SIZEOF:
3578 case TOK_ALIGNOF1:
3579 case TOK_ALIGNOF2:
3580 t = tok;
3581 next();
3582 in_sizeof++;
3583 unary_type(&type); // Perform a in_sizeof = 0;
3584 size = type_size(&type, &align);
3585 if (t == TOK_SIZEOF) {
3586 if (!(type.t & VT_VLA)) {
3587 if (size < 0)
3588 tcc_error("sizeof applied to an incomplete type");
3589 vpushs(size);
3590 } else {
3591 vla_runtime_type_size(&type, &align);
3593 } else {
3594 vpushs(align);
3596 vtop->type.t |= VT_UNSIGNED;
3597 break;
3599 case TOK_builtin_types_compatible_p:
3601 CType type1, type2;
3602 next();
3603 skip('(');
3604 parse_type(&type1);
3605 skip(',');
3606 parse_type(&type2);
3607 skip(')');
3608 type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
3609 type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
3610 vpushi(is_compatible_types(&type1, &type2));
3612 break;
3613 case TOK_builtin_constant_p:
3615 int saved_nocode_wanted, res;
3616 next();
3617 skip('(');
3618 saved_nocode_wanted = nocode_wanted;
3619 nocode_wanted = 1;
3620 gexpr();
3621 res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
3622 vpop();
3623 nocode_wanted = saved_nocode_wanted;
3624 skip(')');
3625 vpushi(res);
3627 break;
3628 case TOK_builtin_frame_address:
3630 CType type;
3631 next();
3632 skip('(');
3633 if (tok != TOK_CINT) {
3634 tcc_error("__builtin_frame_address only takes integers");
3636 if (tokc.i != 0) {
3637 tcc_error("TCC only supports __builtin_frame_address(0)");
3639 next();
3640 skip(')');
3641 type.t = VT_VOID;
3642 mk_pointer(&type);
3643 vset(&type, VT_LOCAL, 0);
3645 break;
3646 #ifdef TCC_TARGET_X86_64
3647 case TOK_builtin_va_arg_types:
3649 /* This definition must be synced with stdarg.h */
3650 enum __va_arg_type {
3651 __va_gen_reg, __va_float_reg, __va_stack
3653 CType type;
3654 int bt;
3655 next();
3656 skip('(');
3657 parse_type(&type);
3658 skip(')');
3659 bt = type.t & VT_BTYPE;
3660 if (bt == VT_STRUCT || bt == VT_LDOUBLE) {
3661 vpushi(__va_stack);
3662 } else if (bt == VT_FLOAT || bt == VT_DOUBLE) {
3663 vpushi(__va_float_reg);
3664 } else {
3665 vpushi(__va_gen_reg);
3668 break;
3669 #endif
3670 case TOK_INC:
3671 case TOK_DEC:
3672 t = tok;
3673 next();
3674 unary();
3675 inc(0, t);
3676 break;
3677 case '-':
3678 next();
3679 vpushi(0);
3680 unary();
3681 gen_op('-');
3682 break;
3683 case TOK_LAND:
3684 if (!gnu_ext)
3685 goto tok_identifier;
3686 next();
3687 /* allow to take the address of a label */
3688 if (tok < TOK_UIDENT)
3689 expect("label identifier");
3690 s = label_find(tok);
3691 if (!s) {
3692 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
3693 } else {
3694 if (s->r == LABEL_DECLARED)
3695 s->r = LABEL_FORWARD;
3697 if (!s->type.t) {
3698 s->type.t = VT_VOID;
3699 mk_pointer(&s->type);
3700 s->type.t |= VT_STATIC;
3702 vset(&s->type, VT_CONST | VT_SYM, 0);
3703 vtop->sym = s;
3704 next();
3705 break;
3707 // special qnan , snan and infinity values
3708 case TOK___NAN__:
3709 vpush64(VT_DOUBLE, 0x7ff8000000000000ULL);
3710 next();
3711 break;
3712 case TOK___SNAN__:
3713 vpush64(VT_DOUBLE, 0x7ff0000000000001ULL);
3714 next();
3715 break;
3716 case TOK___INF__:
3717 vpush64(VT_DOUBLE, 0x7ff0000000000000ULL);
3718 next();
3719 break;
3721 default:
3722 tok_identifier:
3723 t = tok;
3724 next();
3725 if (t < TOK_UIDENT)
3726 expect("identifier");
3727 s = sym_find(t);
3728 if (!s) {
3729 if (tok != '(')
3730 tcc_error("'%s' undeclared", get_tok_str(t, NULL));
3731 /* for simple function calls, we tolerate undeclared
3732 external reference to int() function */
3733 if (tcc_state->warn_implicit_function_declaration)
3734 tcc_warning("implicit declaration of function '%s'",
3735 get_tok_str(t, NULL));
3736 s = external_global_sym(t, &func_old_type, 0);
3738 if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
3739 (VT_STATIC | VT_INLINE | VT_FUNC)) {
3740 /* if referencing an inline function, then we generate a
3741 symbol to it if not already done. It will have the
3742 effect to generate code for it at the end of the
3743 compilation unit. Inline function as always
3744 generated in the text section. */
3745 if (!s->c)
3746 put_extern_sym(s, text_section, 0, 0);
3747 r = VT_SYM | VT_CONST;
3748 } else {
3749 r = s->r;
3751 vset(&s->type, r, s->c);
3752 /* if forward reference, we must point to s */
3753 if (vtop->r & VT_SYM) {
3754 vtop->sym = s;
3755 vtop->c.ul = 0;
3757 break;
3760 /* post operations */
3761 while (1) {
3762 if (tok == TOK_INC || tok == TOK_DEC) {
3763 inc(1, tok);
3764 next();
3765 } else if (tok == '.' || tok == TOK_ARROW) {
3766 int qualifiers;
3767 /* field */
3768 if (tok == TOK_ARROW)
3769 indir();
3770 qualifiers = vtop->type.t & (VT_CONSTANT | VT_VOLATILE);
3771 test_lvalue();
3772 gaddrof();
3773 next();
3774 /* expect pointer on structure */
3775 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
3776 expect("struct or union");
3777 s = vtop->type.ref;
3778 /* find field */
3779 tok |= SYM_FIELD;
3780 while ((s = s->next) != NULL) {
3781 if (s->v == tok)
3782 break;
3784 if (!s)
3785 tcc_error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, NULL));
3786 /* add field offset to pointer */
3787 vtop->type = char_pointer_type; /* change type to 'char *' */
3788 vpushi(s->c);
3789 gen_op('+');
3790 /* change type to field type, and set to lvalue */
3791 vtop->type = s->type;
3792 vtop->type.t |= qualifiers;
3793 /* an array is never an lvalue */
3794 if (!(vtop->type.t & VT_ARRAY)) {
3795 vtop->r |= lvalue_type(vtop->type.t);
3796 #ifdef CONFIG_TCC_BCHECK
3797 /* if bound checking, the referenced pointer must be checked */
3798 if (tcc_state->do_bounds_check)
3799 vtop->r |= VT_MUSTBOUND;
3800 #endif
3802 next();
3803 } else if (tok == '[') {
3804 next();
3805 gexpr();
3806 gen_op('+');
3807 indir();
3808 skip(']');
3809 } else if (tok == '(') {
3810 SValue ret;
3811 Sym *sa;
3812 int nb_args;
3814 /* function call */
3815 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
3816 /* pointer test (no array accepted) */
3817 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
3818 vtop->type = *pointed_type(&vtop->type);
3819 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
3820 goto error_func;
3821 } else {
3822 error_func:
3823 expect("function pointer");
3825 } else {
3826 vtop->r &= ~VT_LVAL; /* no lvalue */
3828 /* get return type */
3829 s = vtop->type.ref;
3830 next();
3831 sa = s->next; /* first parameter */
3832 nb_args = 0;
3833 ret.r2 = VT_CONST;
3834 /* compute first implicit argument if a structure is returned */
3835 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
3836 /* get some space for the returned structure */
3837 size = type_size(&s->type, &align);
3838 loc = (loc - size) & -align;
3839 ret.type = s->type;
3840 ret.r = VT_LOCAL | VT_LVAL;
3841 /* pass it as 'int' to avoid structure arg passing
3842 problems */
3843 vseti(VT_LOCAL, loc);
3844 ret.c = vtop->c;
3845 nb_args++;
3846 } else {
3847 ret.type = s->type;
3848 /* return in register */
3849 if (is_float(ret.type.t)) {
3850 ret.r = reg_fret(ret.type.t);
3851 } else {
3852 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
3853 ret.r2 = REG_LRET;
3854 ret.r = REG_IRET;
3856 ret.c.i = 0;
3858 if (tok != ')') {
3859 for(;;) {
3860 expr_eq();
3861 gfunc_param_typed(s, sa);
3862 nb_args++;
3863 if (sa)
3864 sa = sa->next;
3865 if (tok == ')')
3866 break;
3867 skip(',');
3870 if (sa)
3871 tcc_error("too few arguments to function");
3872 skip(')');
3873 if (!nocode_wanted) {
3874 gfunc_call(nb_args);
3875 } else {
3876 vtop -= (nb_args + 1);
3878 /* return value */
3879 vsetc(&ret.type, ret.r, &ret.c);
3880 vtop->r2 = ret.r2;
3881 } else {
3882 break;
3887 ST_FUNC void expr_prod(void)
3889 int t;
3891 unary();
3892 while (tok == '*' || tok == '/' || tok == '%') {
3893 t = tok;
3894 next();
3895 unary();
3896 gen_op(t);
3900 ST_FUNC void expr_sum(void)
3902 int t;
3904 expr_prod();
3905 while (tok == '+' || tok == '-') {
3906 t = tok;
3907 next();
3908 expr_prod();
3909 gen_op(t);
3913 static void expr_shift(void)
3915 int t;
3917 expr_sum();
3918 while (tok == TOK_SHL || tok == TOK_SAR) {
3919 t = tok;
3920 next();
3921 expr_sum();
3922 gen_op(t);
3926 static void expr_cmp(void)
3928 int t;
3930 expr_shift();
3931 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
3932 tok == TOK_ULT || tok == TOK_UGE) {
3933 t = tok;
3934 next();
3935 expr_shift();
3936 gen_op(t);
3940 static void expr_cmpeq(void)
3942 int t;
3944 expr_cmp();
3945 while (tok == TOK_EQ || tok == TOK_NE) {
3946 t = tok;
3947 next();
3948 expr_cmp();
3949 gen_op(t);
3953 static void expr_and(void)
3955 expr_cmpeq();
3956 while (tok == '&') {
3957 next();
3958 expr_cmpeq();
3959 gen_op('&');
3963 static void expr_xor(void)
3965 expr_and();
3966 while (tok == '^') {
3967 next();
3968 expr_and();
3969 gen_op('^');
3973 static void expr_or(void)
3975 expr_xor();
3976 while (tok == '|') {
3977 next();
3978 expr_xor();
3979 gen_op('|');
3983 /* XXX: fix this mess */
3984 static void expr_land_const(void)
3986 expr_or();
3987 while (tok == TOK_LAND) {
3988 next();
3989 expr_or();
3990 gen_op(TOK_LAND);
3994 /* XXX: fix this mess */
3995 static void expr_lor_const(void)
3997 expr_land_const();
3998 while (tok == TOK_LOR) {
3999 next();
4000 expr_land_const();
4001 gen_op(TOK_LOR);
4005 /* only used if non constant */
4006 static void expr_land(void)
4008 int t;
4010 expr_or();
4011 if (tok == TOK_LAND) {
4012 t = 0;
4013 save_regs(1);
4014 for(;;) {
4015 t = gtst(1, t);
4016 if (tok != TOK_LAND) {
4017 vseti(VT_JMPI, t);
4018 break;
4020 next();
4021 expr_or();
4026 static void expr_lor(void)
4028 int t;
4030 expr_land();
4031 if (tok == TOK_LOR) {
4032 t = 0;
4033 save_regs(1);
4034 for(;;) {
4035 t = gtst(0, t);
4036 if (tok != TOK_LOR) {
4037 vseti(VT_JMP, t);
4038 break;
4040 next();
4041 expr_land();
4046 /* XXX: better constant handling */
4047 static void expr_cond(void)
4049 int tt, u, r1, r2, rc, t1, t2, bt1, bt2;
4050 SValue sv;
4051 CType type, type1, type2;
4053 if (const_wanted) {
4054 expr_lor_const();
4055 if (tok == '?') {
4056 CType boolean;
4057 int c;
4058 boolean.t = VT_BOOL;
4059 vdup();
4060 gen_cast(&boolean);
4061 c = vtop->c.i;
4062 vpop();
4063 next();
4064 if (tok != ':' || !gnu_ext) {
4065 vpop();
4066 gexpr();
4068 if (!c)
4069 vpop();
4070 skip(':');
4071 expr_cond();
4072 if (c)
4073 vpop();
4075 } else {
4076 expr_lor();
4077 if (tok == '?') {
4078 next();
4079 if (vtop != vstack) {
4080 /* needed to avoid having different registers saved in
4081 each branch */
4082 if (is_float(vtop->type.t)) {
4083 rc = RC_FLOAT;
4084 #ifdef TCC_TARGET_X86_64
4085 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
4086 rc = RC_ST0;
4088 #endif
4090 else
4091 rc = RC_INT;
4092 gv(rc);
4093 save_regs(1);
4095 if (tok == ':' && gnu_ext) {
4096 gv_dup();
4097 tt = gtst(1, 0);
4098 } else {
4099 tt = gtst(1, 0);
4100 gexpr();
4102 type1 = vtop->type;
4103 sv = *vtop; /* save value to handle it later */
4104 vtop--; /* no vpop so that FP stack is not flushed */
4105 skip(':');
4106 u = gjmp(0);
4107 gsym(tt);
4108 expr_cond();
4109 type2 = vtop->type;
4111 t1 = type1.t;
4112 bt1 = t1 & VT_BTYPE;
4113 t2 = type2.t;
4114 bt2 = t2 & VT_BTYPE;
4115 /* cast operands to correct type according to ISOC rules */
4116 if (is_float(bt1) || is_float(bt2)) {
4117 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
4118 type.t = VT_LDOUBLE;
4119 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
4120 type.t = VT_DOUBLE;
4121 } else {
4122 type.t = VT_FLOAT;
4124 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
4125 /* cast to biggest op */
4126 type.t = VT_LLONG;
4127 /* convert to unsigned if it does not fit in a long long */
4128 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
4129 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
4130 type.t |= VT_UNSIGNED;
4131 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
4132 /* If one is a null ptr constant the result type
4133 is the other. */
4134 if (is_null_pointer (vtop))
4135 type = type1;
4136 else if (is_null_pointer (&sv))
4137 type = type2;
4138 /* XXX: test pointer compatibility, C99 has more elaborate
4139 rules here. */
4140 else
4141 type = type1;
4142 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
4143 /* XXX: test function pointer compatibility */
4144 type = bt1 == VT_FUNC ? type1 : type2;
4145 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
4146 /* XXX: test structure compatibility */
4147 type = bt1 == VT_STRUCT ? type1 : type2;
4148 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
4149 /* NOTE: as an extension, we accept void on only one side */
4150 type.t = VT_VOID;
4151 } else {
4152 /* integer operations */
4153 type.t = VT_INT;
4154 /* convert to unsigned if it does not fit in an integer */
4155 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
4156 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
4157 type.t |= VT_UNSIGNED;
4160 /* now we convert second operand */
4161 gen_cast(&type);
4162 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4163 gaddrof();
4164 rc = RC_INT;
4165 if (is_float(type.t)) {
4166 rc = RC_FLOAT;
4167 #ifdef TCC_TARGET_X86_64
4168 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
4169 rc = RC_ST0;
4171 #endif
4172 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
4173 /* for long longs, we use fixed registers to avoid having
4174 to handle a complicated move */
4175 rc = RC_IRET;
4178 r2 = gv(rc);
4179 /* this is horrible, but we must also convert first
4180 operand */
4181 tt = gjmp(0);
4182 gsym(u);
4183 /* put again first value and cast it */
4184 *vtop = sv;
4185 gen_cast(&type);
4186 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4187 gaddrof();
4188 r1 = gv(rc);
4189 move_reg(r2, r1);
4190 vtop->r = r2;
4191 gsym(tt);
4196 static void expr_eq(void)
4198 int t;
4200 expr_cond();
4201 if (tok == '=' ||
4202 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
4203 tok == TOK_A_XOR || tok == TOK_A_OR ||
4204 tok == TOK_A_SHL || tok == TOK_A_SAR) {
4205 test_lvalue();
4206 t = tok;
4207 next();
4208 if (t == '=') {
4209 expr_eq();
4210 } else {
4211 vdup();
4212 expr_eq();
4213 gen_op(t & 0x7f);
4215 vstore();
4219 ST_FUNC void gexpr(void)
4221 while (1) {
4222 expr_eq();
4223 if (tok != ',')
4224 break;
4225 vpop();
4226 next();
4230 /* parse an expression and return its type without any side effect. */
4231 static void expr_type(CType *type)
4233 int saved_nocode_wanted;
4235 saved_nocode_wanted = nocode_wanted;
4236 nocode_wanted = 1;
4237 gexpr();
4238 *type = vtop->type;
4239 vpop();
4240 nocode_wanted = saved_nocode_wanted;
4243 /* parse a unary expression and return its type without any side
4244 effect. */
4245 static void unary_type(CType *type)
4247 int a;
4249 a = nocode_wanted;
4250 nocode_wanted = 1;
4251 unary();
4252 *type = vtop->type;
4253 vpop();
4254 nocode_wanted = a;
4257 /* parse a constant expression and return value in vtop. */
4258 static void expr_const1(void)
4260 int a;
4261 a = const_wanted;
4262 const_wanted = 1;
4263 expr_cond();
4264 const_wanted = a;
4267 /* parse an integer constant and return its value. */
4268 ST_FUNC int expr_const(void)
4270 int c;
4271 expr_const1();
4272 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
4273 expect("constant expression");
4274 c = vtop->c.i;
4275 vpop();
4276 return c;
4279 /* return the label token if current token is a label, otherwise
4280 return zero */
4281 static int is_label(void)
4283 int last_tok;
4285 /* fast test first */
4286 if (tok < TOK_UIDENT)
4287 return 0;
4288 /* no need to save tokc because tok is an identifier */
4289 last_tok = tok;
4290 next();
4291 if (tok == ':') {
4292 next();
4293 return last_tok;
4294 } else {
4295 unget_tok(last_tok);
4296 return 0;
4300 static void label_or_decl(int l)
4302 int last_tok;
4304 /* fast test first */
4305 if (tok >= TOK_UIDENT)
4307 /* no need to save tokc because tok is an identifier */
4308 last_tok = tok;
4309 next();
4310 if (tok == ':') {
4311 unget_tok(last_tok);
4312 return;
4314 unget_tok(last_tok);
4316 decl(l);
4319 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
4320 int case_reg, int is_expr)
4322 int a, b, c, d;
4323 Sym *s;
4325 /* generate line number info */
4326 if (tcc_state->do_debug &&
4327 (last_line_num != file->line_num || last_ind != ind)) {
4328 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
4329 last_ind = ind;
4330 last_line_num = file->line_num;
4333 if (is_expr) {
4334 /* default return value is (void) */
4335 vpushi(0);
4336 vtop->type.t = VT_VOID;
4339 if (tok == TOK_IF) {
4340 /* if test */
4341 next();
4342 skip('(');
4343 gexpr();
4344 skip(')');
4345 a = gtst(1, 0);
4346 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4347 c = tok;
4348 if (c == TOK_ELSE) {
4349 next();
4350 d = gjmp(0);
4351 gsym(a);
4352 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4353 gsym(d); /* patch else jmp */
4354 } else
4355 gsym(a);
4356 } else if (tok == TOK_WHILE) {
4357 next();
4358 d = ind;
4359 skip('(');
4360 gexpr();
4361 skip(')');
4362 a = gtst(1, 0);
4363 b = 0;
4364 block(&a, &b, case_sym, def_sym, case_reg, 0);
4365 gjmp_addr(d);
4366 gsym(a);
4367 gsym_addr(b, d);
4368 } else if (tok == '{') {
4369 Sym *llabel;
4371 next();
4372 /* record local declaration stack position */
4373 s = local_stack;
4374 llabel = local_label_stack;
4375 /* handle local labels declarations */
4376 if (tok == TOK_LABEL) {
4377 next();
4378 for(;;) {
4379 if (tok < TOK_UIDENT)
4380 expect("label identifier");
4381 label_push(&local_label_stack, tok, LABEL_DECLARED);
4382 next();
4383 if (tok == ',') {
4384 next();
4385 } else {
4386 skip(';');
4387 break;
4391 while (tok != '}') {
4392 label_or_decl(VT_LOCAL);
4393 if (tok != '}') {
4394 if (is_expr)
4395 vpop();
4396 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
4399 /* pop locally defined labels */
4400 label_pop(&local_label_stack, llabel);
4401 if(is_expr) {
4402 /* XXX: this solution makes only valgrind happy...
4403 triggered by gcc.c-torture/execute/20000917-1.c */
4404 Sym *p;
4405 switch(vtop->type.t & VT_BTYPE) {
4406 case VT_PTR:
4407 case VT_STRUCT:
4408 case VT_ENUM:
4409 case VT_FUNC:
4410 for(p=vtop->type.ref;p;p=p->prev)
4411 if(p->prev==s)
4412 tcc_error("unsupported expression type");
4415 /* pop locally defined symbols */
4416 sym_pop(&local_stack, s);
4417 next();
4418 } else if (tok == TOK_RETURN) {
4419 next();
4420 if (tok != ';') {
4421 gexpr();
4422 gen_assign_cast(&func_vt);
4423 if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
4424 CType type;
4425 /* if returning structure, must copy it to implicit
4426 first pointer arg location */
4427 #ifdef TCC_ARM_EABI
4428 int align, size;
4429 size = type_size(&func_vt,&align);
4430 if(size <= 4)
4432 if((vtop->r != (VT_LOCAL | VT_LVAL) || (vtop->c.i & 3))
4433 && (align & 3))
4435 int addr;
4436 loc = (loc - size) & -4;
4437 addr = loc;
4438 type = func_vt;
4439 vset(&type, VT_LOCAL | VT_LVAL, addr);
4440 vswap();
4441 vstore();
4442 vset(&int_type, VT_LOCAL | VT_LVAL, addr);
4444 vtop->type = int_type;
4445 gv(RC_IRET);
4446 } else {
4447 #endif
4448 type = func_vt;
4449 mk_pointer(&type);
4450 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
4451 indir();
4452 vswap();
4453 /* copy structure value to pointer */
4454 vstore();
4455 #ifdef TCC_ARM_EABI
4457 #endif
4458 } else if (is_float(func_vt.t)) {
4459 gv(rc_fret(func_vt.t));
4460 } else {
4461 gv(RC_IRET);
4463 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
4465 skip(';');
4466 rsym = gjmp(rsym); /* jmp */
4467 } else if (tok == TOK_BREAK) {
4468 /* compute jump */
4469 if (!bsym)
4470 tcc_error("cannot break");
4471 *bsym = gjmp(*bsym);
4472 next();
4473 skip(';');
4474 } else if (tok == TOK_CONTINUE) {
4475 /* compute jump */
4476 if (!csym)
4477 tcc_error("cannot continue");
4478 *csym = gjmp(*csym);
4479 next();
4480 skip(';');
4481 } else if (tok == TOK_FOR) {
4482 int e;
4483 next();
4484 skip('(');
4485 s = local_stack;
4486 if (tok != ';') {
4487 /* c99 for-loop init decl? */
4488 if (!decl0(VT_LOCAL, 1)) {
4489 /* no, regular for-loop init expr */
4490 gexpr();
4491 vpop();
4494 skip(';');
4495 d = ind;
4496 c = ind;
4497 a = 0;
4498 b = 0;
4499 if (tok != ';') {
4500 gexpr();
4501 a = gtst(1, 0);
4503 skip(';');
4504 if (tok != ')') {
4505 e = gjmp(0);
4506 c = ind;
4507 gexpr();
4508 vpop();
4509 gjmp_addr(d);
4510 gsym(e);
4512 skip(')');
4513 block(&a, &b, case_sym, def_sym, case_reg, 0);
4514 gjmp_addr(c);
4515 gsym(a);
4516 gsym_addr(b, c);
4517 sym_pop(&local_stack, s);
4518 } else
4519 if (tok == TOK_DO) {
4520 next();
4521 a = 0;
4522 b = 0;
4523 d = ind;
4524 block(&a, &b, case_sym, def_sym, case_reg, 0);
4525 skip(TOK_WHILE);
4526 skip('(');
4527 gsym(b);
4528 gexpr();
4529 c = gtst(0, 0);
4530 gsym_addr(c, d);
4531 skip(')');
4532 gsym(a);
4533 skip(';');
4534 } else
4535 if (tok == TOK_SWITCH) {
4536 next();
4537 skip('(');
4538 gexpr();
4539 /* XXX: other types than integer */
4540 case_reg = gv(RC_INT);
4541 vpop();
4542 skip(')');
4543 a = 0;
4544 b = gjmp(0); /* jump to first case */
4545 c = 0;
4546 block(&a, csym, &b, &c, case_reg, 0);
4547 /* if no default, jmp after switch */
4548 if (c == 0)
4549 c = ind;
4550 /* default label */
4551 gsym_addr(b, c);
4552 /* break label */
4553 gsym(a);
4554 } else
4555 if (tok == TOK_CASE) {
4556 int v1, v2;
4557 if (!case_sym)
4558 expect("switch");
4559 next();
4560 v1 = expr_const();
4561 v2 = v1;
4562 if (gnu_ext && tok == TOK_DOTS) {
4563 next();
4564 v2 = expr_const();
4565 if (v2 < v1)
4566 tcc_warning("empty case range");
4568 /* since a case is like a label, we must skip it with a jmp */
4569 b = gjmp(0);
4570 gsym(*case_sym);
4571 vseti(case_reg, 0);
4572 vpushi(v1);
4573 if (v1 == v2) {
4574 gen_op(TOK_EQ);
4575 *case_sym = gtst(1, 0);
4576 } else {
4577 gen_op(TOK_GE);
4578 *case_sym = gtst(1, 0);
4579 vseti(case_reg, 0);
4580 vpushi(v2);
4581 gen_op(TOK_LE);
4582 *case_sym = gtst(1, *case_sym);
4584 gsym(b);
4585 skip(':');
4586 is_expr = 0;
4587 goto block_after_label;
4588 } else
4589 if (tok == TOK_DEFAULT) {
4590 next();
4591 skip(':');
4592 if (!def_sym)
4593 expect("switch");
4594 if (*def_sym)
4595 tcc_error("too many 'default'");
4596 *def_sym = ind;
4597 is_expr = 0;
4598 goto block_after_label;
4599 } else
4600 if (tok == TOK_GOTO) {
4601 next();
4602 if (tok == '*' && gnu_ext) {
4603 /* computed goto */
4604 next();
4605 gexpr();
4606 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
4607 expect("pointer");
4608 ggoto();
4609 } else if (tok >= TOK_UIDENT) {
4610 s = label_find(tok);
4611 /* put forward definition if needed */
4612 if (!s) {
4613 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
4614 } else {
4615 if (s->r == LABEL_DECLARED)
4616 s->r = LABEL_FORWARD;
4618 /* label already defined */
4619 if (s->r & LABEL_FORWARD)
4620 s->jnext = gjmp(s->jnext);
4621 else
4622 gjmp_addr(s->jnext);
4623 next();
4624 } else {
4625 expect("label identifier");
4627 skip(';');
4628 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
4629 asm_instr();
4630 } else {
4631 b = is_label();
4632 if (b) {
4633 /* label case */
4634 s = label_find(b);
4635 if (s) {
4636 if (s->r == LABEL_DEFINED)
4637 tcc_error("duplicate label '%s'", get_tok_str(s->v, NULL));
4638 gsym(s->jnext);
4639 s->r = LABEL_DEFINED;
4640 } else {
4641 s = label_push(&global_label_stack, b, LABEL_DEFINED);
4643 s->jnext = ind;
4644 /* we accept this, but it is a mistake */
4645 block_after_label:
4646 if (tok == '}') {
4647 tcc_warning("deprecated use of label at end of compound statement");
4648 } else {
4649 if (is_expr)
4650 vpop();
4651 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
4653 } else {
4654 /* expression case */
4655 if (tok != ';') {
4656 if (is_expr) {
4657 vpop();
4658 gexpr();
4659 } else {
4660 gexpr();
4661 vpop();
4664 skip(';');
4669 /* t is the array or struct type. c is the array or struct
4670 address. cur_index/cur_field is the pointer to the current
4671 value. 'size_only' is true if only size info is needed (only used
4672 in arrays) */
4673 static void decl_designator(CType *type, Section *sec, unsigned long c,
4674 int *cur_index, Sym **cur_field,
4675 int size_only)
4677 Sym *s, *f;
4678 int notfirst, index, index_last, align, l, nb_elems, elem_size;
4679 CType type1;
4681 notfirst = 0;
4682 elem_size = 0;
4683 nb_elems = 1;
4684 if (gnu_ext && (l = is_label()) != 0)
4685 goto struct_field;
4686 while (tok == '[' || tok == '.') {
4687 if (tok == '[') {
4688 if (!(type->t & VT_ARRAY))
4689 expect("array type");
4690 s = type->ref;
4691 next();
4692 index = expr_const();
4693 if (index < 0 || (s->c >= 0 && index >= s->c))
4694 expect("invalid index");
4695 if (tok == TOK_DOTS && gnu_ext) {
4696 next();
4697 index_last = expr_const();
4698 if (index_last < 0 ||
4699 (s->c >= 0 && index_last >= s->c) ||
4700 index_last < index)
4701 expect("invalid index");
4702 } else {
4703 index_last = index;
4705 skip(']');
4706 if (!notfirst)
4707 *cur_index = index_last;
4708 type = pointed_type(type);
4709 elem_size = type_size(type, &align);
4710 c += index * elem_size;
4711 /* NOTE: we only support ranges for last designator */
4712 nb_elems = index_last - index + 1;
4713 if (nb_elems != 1) {
4714 notfirst = 1;
4715 break;
4717 } else {
4718 next();
4719 l = tok;
4720 next();
4721 struct_field:
4722 if ((type->t & VT_BTYPE) != VT_STRUCT)
4723 expect("struct/union type");
4724 s = type->ref;
4725 l |= SYM_FIELD;
4726 f = s->next;
4727 while (f) {
4728 if (f->v == l)
4729 break;
4730 f = f->next;
4732 if (!f)
4733 expect("field");
4734 if (!notfirst)
4735 *cur_field = f;
4736 /* XXX: fix this mess by using explicit storage field */
4737 type1 = f->type;
4738 type1.t |= (type->t & ~VT_TYPE);
4739 type = &type1;
4740 c += f->c;
4742 notfirst = 1;
4744 if (notfirst) {
4745 if (tok == '=') {
4746 next();
4747 } else {
4748 if (!gnu_ext)
4749 expect("=");
4751 } else {
4752 if (type->t & VT_ARRAY) {
4753 index = *cur_index;
4754 type = pointed_type(type);
4755 c += index * type_size(type, &align);
4756 } else {
4757 f = *cur_field;
4758 if (!f)
4759 tcc_error("too many field init");
4760 /* XXX: fix this mess by using explicit storage field */
4761 type1 = f->type;
4762 type1.t |= (type->t & ~VT_TYPE);
4763 type = &type1;
4764 c += f->c;
4767 decl_initializer(type, sec, c, 0, size_only);
4769 /* XXX: make it more general */
4770 if (!size_only && nb_elems > 1) {
4771 unsigned long c_end;
4772 uint8_t *src, *dst;
4773 int i;
4775 if (!sec)
4776 tcc_error("range init not supported yet for dynamic storage");
4777 c_end = c + nb_elems * elem_size;
4778 if (c_end > sec->data_allocated)
4779 section_realloc(sec, c_end);
4780 src = sec->data + c;
4781 dst = src;
4782 for(i = 1; i < nb_elems; i++) {
4783 dst += elem_size;
4784 memcpy(dst, src, elem_size);
4789 #define EXPR_VAL 0
4790 #define EXPR_CONST 1
4791 #define EXPR_ANY 2
4793 /* store a value or an expression directly in global data or in local array */
4794 static void init_putv(CType *type, Section *sec, unsigned long c,
4795 int v, int expr_type)
4797 int saved_global_expr, bt, bit_pos, bit_size;
4798 void *ptr;
4799 unsigned long long bit_mask;
4800 CType dtype;
4802 switch(expr_type) {
4803 case EXPR_VAL:
4804 vpushi(v);
4805 break;
4806 case EXPR_CONST:
4807 /* compound literals must be allocated globally in this case */
4808 saved_global_expr = global_expr;
4809 global_expr = 1;
4810 expr_const1();
4811 global_expr = saved_global_expr;
4812 /* NOTE: symbols are accepted */
4813 if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
4814 tcc_error("initializer element is not constant");
4815 break;
4816 case EXPR_ANY:
4817 expr_eq();
4818 break;
4821 dtype = *type;
4822 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
4824 if (sec) {
4825 /* XXX: not portable */
4826 /* XXX: generate error if incorrect relocation */
4827 gen_assign_cast(&dtype);
4828 bt = type->t & VT_BTYPE;
4829 /* we'll write at most 12 bytes */
4830 if (c + 12 > sec->data_allocated) {
4831 section_realloc(sec, c + 12);
4833 ptr = sec->data + c;
4834 /* XXX: make code faster ? */
4835 if (!(type->t & VT_BITFIELD)) {
4836 bit_pos = 0;
4837 bit_size = 32;
4838 bit_mask = -1LL;
4839 } else {
4840 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
4841 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
4842 bit_mask = (1LL << bit_size) - 1;
4844 if ((vtop->r & VT_SYM) &&
4845 (bt == VT_BYTE ||
4846 bt == VT_SHORT ||
4847 bt == VT_DOUBLE ||
4848 bt == VT_LDOUBLE ||
4849 bt == VT_LLONG ||
4850 (bt == VT_INT && bit_size != 32)))
4851 tcc_error("initializer element is not computable at load time");
4852 switch(bt) {
4853 case VT_BOOL:
4854 vtop->c.i = (vtop->c.i != 0);
4855 case VT_BYTE:
4856 *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
4857 break;
4858 case VT_SHORT:
4859 *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
4860 break;
4861 case VT_DOUBLE:
4862 *(double *)ptr = vtop->c.d;
4863 break;
4864 case VT_LDOUBLE:
4865 *(long double *)ptr = vtop->c.ld;
4866 break;
4867 case VT_LLONG:
4868 *(long long *)ptr |= (vtop->c.ll & bit_mask) << bit_pos;
4869 break;
4870 default:
4871 if (vtop->r & VT_SYM) {
4872 greloc(sec, vtop->sym, c, R_DATA_PTR);
4874 *(int *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
4875 break;
4877 vtop--;
4878 } else {
4879 vset(&dtype, VT_LOCAL|VT_LVAL, c);
4880 vswap();
4881 vstore();
4882 vpop();
4886 /* put zeros for variable based init */
4887 static void init_putz(CType *t, Section *sec, unsigned long c, int size)
4889 if (sec) {
4890 /* nothing to do because globals are already set to zero */
4891 } else {
4892 vpush_global_sym(&func_old_type, TOK_memset);
4893 vseti(VT_LOCAL, c);
4894 vpushi(0);
4895 vpushi(size);
4896 gfunc_call(3);
4900 /* 't' contains the type and storage info. 'c' is the offset of the
4901 object in section 'sec'. If 'sec' is NULL, it means stack based
4902 allocation. 'first' is true if array '{' must be read (multi
4903 dimension implicit array init handling). 'size_only' is true if
4904 size only evaluation is wanted (only for arrays). */
4905 static void decl_initializer(CType *type, Section *sec, unsigned long c,
4906 int first, int size_only)
4908 int index, array_length, n, no_oblock, nb, parlevel, parlevel1, i;
4909 int size1, align1, expr_type;
4910 Sym *s, *f;
4911 CType *t1;
4913 if (type->t & VT_VLA) {
4914 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
4915 int a;
4916 CValue retcval;
4918 vpush_global_sym(&func_old_type, TOK_alloca);
4919 vla_runtime_type_size(type, &a);
4920 gfunc_call(1);
4922 /* return value */
4923 retcval.i = 0;
4924 vsetc(type, REG_IRET, &retcval);
4925 vset(type, VT_LOCAL|VT_LVAL, c);
4926 vswap();
4927 vstore();
4928 vpop();
4929 #else
4930 tcc_error("variable length arrays unsupported for this target");
4931 #endif
4932 } else if (type->t & VT_ARRAY) {
4933 s = type->ref;
4934 n = s->c;
4935 array_length = 0;
4936 t1 = pointed_type(type);
4937 size1 = type_size(t1, &align1);
4939 no_oblock = 1;
4940 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
4941 tok == '{') {
4942 if (tok != '{')
4943 tcc_error("character array initializer must be a literal,"
4944 " optionally enclosed in braces");
4945 skip('{');
4946 no_oblock = 0;
4949 /* only parse strings here if correct type (otherwise: handle
4950 them as ((w)char *) expressions */
4951 if ((tok == TOK_LSTR &&
4952 #ifdef TCC_TARGET_PE
4953 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
4954 #else
4955 (t1->t & VT_BTYPE) == VT_INT
4956 #endif
4957 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
4958 while (tok == TOK_STR || tok == TOK_LSTR) {
4959 int cstr_len, ch;
4960 CString *cstr;
4962 cstr = tokc.cstr;
4963 /* compute maximum number of chars wanted */
4964 if (tok == TOK_STR)
4965 cstr_len = cstr->size;
4966 else
4967 cstr_len = cstr->size / sizeof(nwchar_t);
4968 cstr_len--;
4969 nb = cstr_len;
4970 if (n >= 0 && nb > (n - array_length))
4971 nb = n - array_length;
4972 if (!size_only) {
4973 if (cstr_len > nb)
4974 tcc_warning("initializer-string for array is too long");
4975 /* in order to go faster for common case (char
4976 string in global variable, we handle it
4977 specifically */
4978 if (sec && tok == TOK_STR && size1 == 1) {
4979 memcpy(sec->data + c + array_length, cstr->data, nb);
4980 } else {
4981 for(i=0;i<nb;i++) {
4982 if (tok == TOK_STR)
4983 ch = ((unsigned char *)cstr->data)[i];
4984 else
4985 ch = ((nwchar_t *)cstr->data)[i];
4986 init_putv(t1, sec, c + (array_length + i) * size1,
4987 ch, EXPR_VAL);
4991 array_length += nb;
4992 next();
4994 /* only add trailing zero if enough storage (no
4995 warning in this case since it is standard) */
4996 if (n < 0 || array_length < n) {
4997 if (!size_only) {
4998 init_putv(t1, sec, c + (array_length * size1), 0, EXPR_VAL);
5000 array_length++;
5002 } else {
5003 index = 0;
5004 while (tok != '}') {
5005 decl_designator(type, sec, c, &index, NULL, size_only);
5006 if (n >= 0 && index >= n)
5007 tcc_error("index too large");
5008 /* must put zero in holes (note that doing it that way
5009 ensures that it even works with designators) */
5010 if (!size_only && array_length < index) {
5011 init_putz(t1, sec, c + array_length * size1,
5012 (index - array_length) * size1);
5014 index++;
5015 if (index > array_length)
5016 array_length = index;
5017 /* special test for multi dimensional arrays (may not
5018 be strictly correct if designators are used at the
5019 same time) */
5020 if (index >= n && no_oblock)
5021 break;
5022 if (tok == '}')
5023 break;
5024 skip(',');
5027 if (!no_oblock)
5028 skip('}');
5029 /* put zeros at the end */
5030 if (!size_only && n >= 0 && array_length < n) {
5031 init_putz(t1, sec, c + array_length * size1,
5032 (n - array_length) * size1);
5034 /* patch type size if needed */
5035 if (n < 0)
5036 s->c = array_length;
5037 } else if ((type->t & VT_BTYPE) == VT_STRUCT &&
5038 (sec || !first || tok == '{')) {
5039 int par_count;
5041 /* NOTE: the previous test is a specific case for automatic
5042 struct/union init */
5043 /* XXX: union needs only one init */
5045 /* XXX: this test is incorrect for local initializers
5046 beginning with ( without {. It would be much more difficult
5047 to do it correctly (ideally, the expression parser should
5048 be used in all cases) */
5049 par_count = 0;
5050 if (tok == '(') {
5051 AttributeDef ad1;
5052 CType type1;
5053 next();
5054 while (tok == '(') {
5055 par_count++;
5056 next();
5058 if (!parse_btype(&type1, &ad1))
5059 expect("cast");
5060 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
5061 #if 0
5062 if (!is_assignable_types(type, &type1))
5063 tcc_error("invalid type for cast");
5064 #endif
5065 skip(')');
5067 no_oblock = 1;
5068 if (first || tok == '{') {
5069 skip('{');
5070 no_oblock = 0;
5072 s = type->ref;
5073 f = s->next;
5074 array_length = 0;
5075 index = 0;
5076 n = s->c;
5077 while (tok != '}') {
5078 decl_designator(type, sec, c, NULL, &f, size_only);
5079 index = f->c;
5080 if (!size_only && array_length < index) {
5081 init_putz(type, sec, c + array_length,
5082 index - array_length);
5084 index = index + type_size(&f->type, &align1);
5085 if (index > array_length)
5086 array_length = index;
5088 /* gr: skip fields from same union - ugly. */
5089 while (f->next) {
5090 ///printf("index: %2d %08x -- %2d %08x\n", f->c, f->type.t, f->next->c, f->next->type.t);
5091 /* test for same offset */
5092 if (f->next->c != f->c)
5093 break;
5094 /* if yes, test for bitfield shift */
5095 if ((f->type.t & VT_BITFIELD) && (f->next->type.t & VT_BITFIELD)) {
5096 int bit_pos_1 = (f->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5097 int bit_pos_2 = (f->next->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5098 //printf("bitfield %d %d\n", bit_pos_1, bit_pos_2);
5099 if (bit_pos_1 != bit_pos_2)
5100 break;
5102 f = f->next;
5105 f = f->next;
5106 if (no_oblock && f == NULL)
5107 break;
5108 if (tok == '}')
5109 break;
5110 skip(',');
5112 /* put zeros at the end */
5113 if (!size_only && array_length < n) {
5114 init_putz(type, sec, c + array_length,
5115 n - array_length);
5117 if (!no_oblock)
5118 skip('}');
5119 while (par_count) {
5120 skip(')');
5121 par_count--;
5123 } else if (tok == '{') {
5124 next();
5125 decl_initializer(type, sec, c, first, size_only);
5126 skip('}');
5127 } else if (size_only) {
5128 /* just skip expression */
5129 parlevel = parlevel1 = 0;
5130 while ((parlevel > 0 || parlevel1 > 0 ||
5131 (tok != '}' && tok != ',')) && tok != -1) {
5132 if (tok == '(')
5133 parlevel++;
5134 else if (tok == ')')
5135 parlevel--;
5136 else if (tok == '{')
5137 parlevel1++;
5138 else if (tok == '}')
5139 parlevel1--;
5140 next();
5142 } else {
5143 /* currently, we always use constant expression for globals
5144 (may change for scripting case) */
5145 expr_type = EXPR_CONST;
5146 if (!sec)
5147 expr_type = EXPR_ANY;
5148 init_putv(type, sec, c, 0, expr_type);
5152 /* parse an initializer for type 't' if 'has_init' is non zero, and
5153 allocate space in local or global data space ('r' is either
5154 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
5155 variable 'v' with an associated name represented by 'asm_label' of
5156 scope 'scope' is declared before initializers are parsed. If 'v' is
5157 zero, then a reference to the new object is put in the value stack.
5158 If 'has_init' is 2, a special parsing is done to handle string
5159 constants. */
5160 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
5161 int has_init, int v, char *asm_label,
5162 int scope)
5164 int size, align, addr, data_offset;
5165 int level;
5166 ParseState saved_parse_state = {0};
5167 TokenString init_str;
5168 Section *sec;
5169 Sym *flexible_array;
5171 flexible_array = NULL;
5172 if ((type->t & VT_BTYPE) == VT_STRUCT) {
5173 Sym *field;
5174 field = type->ref;
5175 while (field && field->next)
5176 field = field->next;
5177 if (field->type.t & VT_ARRAY && field->type.ref->c < 0)
5178 flexible_array = field;
5181 size = type_size(type, &align);
5182 /* If unknown size, we must evaluate it before
5183 evaluating initializers because
5184 initializers can generate global data too
5185 (e.g. string pointers or ISOC99 compound
5186 literals). It also simplifies local
5187 initializers handling */
5188 tok_str_new(&init_str);
5189 if (size < 0 || (flexible_array && has_init)) {
5190 if (!has_init)
5191 tcc_error("unknown type size");
5192 /* get all init string */
5193 if (has_init == 2) {
5194 /* only get strings */
5195 while (tok == TOK_STR || tok == TOK_LSTR) {
5196 tok_str_add_tok(&init_str);
5197 next();
5199 } else {
5200 level = 0;
5201 while (level > 0 || (tok != ',' && tok != ';')) {
5202 if (tok < 0)
5203 tcc_error("unexpected end of file in initializer");
5204 tok_str_add_tok(&init_str);
5205 if (tok == '{')
5206 level++;
5207 else if (tok == '}') {
5208 level--;
5209 if (level <= 0) {
5210 next();
5211 break;
5214 next();
5217 tok_str_add(&init_str, -1);
5218 tok_str_add(&init_str, 0);
5220 /* compute size */
5221 save_parse_state(&saved_parse_state);
5223 macro_ptr = init_str.str;
5224 next();
5225 decl_initializer(type, NULL, 0, 1, 1);
5226 /* prepare second initializer parsing */
5227 macro_ptr = init_str.str;
5228 next();
5230 /* if still unknown size, error */
5231 size = type_size(type, &align);
5232 if (size < 0)
5233 tcc_error("unknown type size");
5235 if (flexible_array)
5236 size += flexible_array->type.ref->c * pointed_size(&flexible_array->type);
5237 /* take into account specified alignment if bigger */
5238 if (ad->aligned) {
5239 if (ad->aligned > align)
5240 align = ad->aligned;
5241 } else if (ad->packed) {
5242 align = 1;
5244 if ((r & VT_VALMASK) == VT_LOCAL) {
5245 sec = NULL;
5246 #ifdef CONFIG_TCC_BCHECK
5247 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5248 loc--;
5250 #endif
5251 loc = (loc - size) & -align;
5252 addr = loc;
5253 #ifdef CONFIG_TCC_BCHECK
5254 /* handles bounds */
5255 /* XXX: currently, since we do only one pass, we cannot track
5256 '&' operators, so we add only arrays */
5257 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5258 unsigned long *bounds_ptr;
5259 /* add padding between regions */
5260 loc--;
5261 /* then add local bound info */
5262 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(unsigned long));
5263 bounds_ptr[0] = addr;
5264 bounds_ptr[1] = size;
5266 #endif
5267 if (v) {
5268 /* local variable */
5269 sym_push(v, type, r, addr);
5270 } else {
5271 /* push local reference */
5272 vset(type, r, addr);
5274 } else {
5275 Sym *sym;
5277 sym = NULL;
5278 if (v && scope == VT_CONST) {
5279 /* see if the symbol was already defined */
5280 sym = sym_find(v);
5281 if (sym) {
5282 if (!is_compatible_types(&sym->type, type))
5283 tcc_error("incompatible types for redefinition of '%s'",
5284 get_tok_str(v, NULL));
5285 if (sym->type.t & VT_EXTERN) {
5286 /* if the variable is extern, it was not allocated */
5287 sym->type.t &= ~VT_EXTERN;
5288 /* set array size if it was ommited in extern
5289 declaration */
5290 if ((sym->type.t & VT_ARRAY) &&
5291 sym->type.ref->c < 0 &&
5292 type->ref->c >= 0)
5293 sym->type.ref->c = type->ref->c;
5294 } else {
5295 /* we accept several definitions of the same
5296 global variable. this is tricky, because we
5297 must play with the SHN_COMMON type of the symbol */
5298 /* XXX: should check if the variable was already
5299 initialized. It is incorrect to initialized it
5300 twice */
5301 /* no init data, we won't add more to the symbol */
5302 if (!has_init)
5303 goto no_alloc;
5308 /* allocate symbol in corresponding section */
5309 sec = ad->section;
5310 if (!sec) {
5311 if (has_init)
5312 sec = data_section;
5313 else if (tcc_state->nocommon)
5314 sec = bss_section;
5316 if (sec) {
5317 data_offset = sec->data_offset;
5318 data_offset = (data_offset + align - 1) & -align;
5319 addr = data_offset;
5320 /* very important to increment global pointer at this time
5321 because initializers themselves can create new initializers */
5322 data_offset += size;
5323 #ifdef CONFIG_TCC_BCHECK
5324 /* add padding if bound check */
5325 if (tcc_state->do_bounds_check)
5326 data_offset++;
5327 #endif
5328 sec->data_offset = data_offset;
5329 /* allocate section space to put the data */
5330 if (sec->sh_type != SHT_NOBITS &&
5331 data_offset > sec->data_allocated)
5332 section_realloc(sec, data_offset);
5333 /* align section if needed */
5334 if (align > sec->sh_addralign)
5335 sec->sh_addralign = align;
5336 } else {
5337 addr = 0; /* avoid warning */
5340 if (v) {
5341 if (scope != VT_CONST || !sym) {
5342 sym = sym_push(v, type, r | VT_SYM, 0);
5343 sym->asm_label = asm_label;
5345 /* update symbol definition */
5346 if (sec) {
5347 put_extern_sym(sym, sec, addr, size);
5348 } else {
5349 ElfW(Sym) *esym;
5350 /* put a common area */
5351 put_extern_sym(sym, NULL, align, size);
5352 /* XXX: find a nicer way */
5353 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
5354 esym->st_shndx = SHN_COMMON;
5356 } else {
5357 CValue cval;
5359 /* push global reference */
5360 sym = get_sym_ref(type, sec, addr, size);
5361 cval.ul = 0;
5362 vsetc(type, VT_CONST | VT_SYM, &cval);
5363 vtop->sym = sym;
5365 /* patch symbol weakness */
5366 if (type->t & VT_WEAK)
5367 weaken_symbol(sym);
5368 #ifdef CONFIG_TCC_BCHECK
5369 /* handles bounds now because the symbol must be defined
5370 before for the relocation */
5371 if (tcc_state->do_bounds_check) {
5372 unsigned long *bounds_ptr;
5374 greloc(bounds_section, sym, bounds_section->data_offset, R_DATA_PTR);
5375 /* then add global bound info */
5376 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(long));
5377 bounds_ptr[0] = 0; /* relocated */
5378 bounds_ptr[1] = size;
5380 #endif
5382 if (has_init || (type->t & VT_VLA)) {
5383 decl_initializer(type, sec, addr, 1, 0);
5384 /* restore parse state if needed */
5385 if (init_str.str) {
5386 tok_str_free(init_str.str);
5387 restore_parse_state(&saved_parse_state);
5389 /* patch flexible array member size back to -1, */
5390 /* for possible subsequent similar declarations */
5391 if (flexible_array)
5392 flexible_array->type.ref->c = -1;
5394 no_alloc: ;
5397 static void put_func_debug(Sym *sym)
5399 char buf[512];
5401 /* stabs info */
5402 /* XXX: we put here a dummy type */
5403 snprintf(buf, sizeof(buf), "%s:%c1",
5404 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
5405 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
5406 cur_text_section, sym->c);
5407 /* //gr gdb wants a line at the function */
5408 put_stabn(N_SLINE, 0, file->line_num, 0);
5409 last_ind = 0;
5410 last_line_num = 0;
5413 /* parse an old style function declaration list */
5414 /* XXX: check multiple parameter */
5415 static void func_decl_list(Sym *func_sym)
5417 AttributeDef ad;
5418 int v;
5419 Sym *s;
5420 CType btype, type;
5422 /* parse each declaration */
5423 while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF &&
5424 tok != TOK_ASM1 && tok != TOK_ASM2 && tok != TOK_ASM3) {
5425 if (!parse_btype(&btype, &ad))
5426 expect("declaration list");
5427 if (((btype.t & VT_BTYPE) == VT_ENUM ||
5428 (btype.t & VT_BTYPE) == VT_STRUCT) &&
5429 tok == ';') {
5430 /* we accept no variable after */
5431 } else {
5432 for(;;) {
5433 type = btype;
5434 type_decl(&type, &ad, &v, TYPE_DIRECT);
5435 /* find parameter in function parameter list */
5436 s = func_sym->next;
5437 while (s != NULL) {
5438 if ((s->v & ~SYM_FIELD) == v)
5439 goto found;
5440 s = s->next;
5442 tcc_error("declaration for parameter '%s' but no such parameter",
5443 get_tok_str(v, NULL));
5444 found:
5445 /* check that no storage specifier except 'register' was given */
5446 if (type.t & VT_STORAGE)
5447 tcc_error("storage class specified for '%s'", get_tok_str(v, NULL));
5448 convert_parameter_type(&type);
5449 /* we can add the type (NOTE: it could be local to the function) */
5450 s->type = type;
5451 /* accept other parameters */
5452 if (tok == ',')
5453 next();
5454 else
5455 break;
5458 skip(';');
5462 /* parse a function defined by symbol 'sym' and generate its code in
5463 'cur_text_section' */
5464 static void gen_function(Sym *sym)
5466 int saved_nocode_wanted = nocode_wanted;
5467 nocode_wanted = 0;
5468 ind = cur_text_section->data_offset;
5469 /* NOTE: we patch the symbol size later */
5470 put_extern_sym(sym, cur_text_section, ind, 0);
5471 funcname = get_tok_str(sym->v, NULL);
5472 func_ind = ind;
5473 /* put debug symbol */
5474 if (tcc_state->do_debug)
5475 put_func_debug(sym);
5476 /* push a dummy symbol to enable local sym storage */
5477 sym_push2(&local_stack, SYM_FIELD, 0, 0);
5478 gfunc_prolog(&sym->type);
5479 rsym = 0;
5480 block(NULL, NULL, NULL, NULL, 0, 0);
5481 gsym(rsym);
5482 gfunc_epilog();
5483 cur_text_section->data_offset = ind;
5484 label_pop(&global_label_stack, NULL);
5485 sym_pop(&local_stack, NULL); /* reset local stack */
5486 /* end of function */
5487 /* patch symbol size */
5488 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
5489 ind - func_ind;
5490 /* patch symbol weakness (this definition overrules any prototype) */
5491 if (sym->type.t & VT_WEAK)
5492 weaken_symbol(sym);
5493 if (tcc_state->do_debug) {
5494 put_stabn(N_FUN, 0, 0, ind - func_ind);
5496 /* It's better to crash than to generate wrong code */
5497 cur_text_section = NULL;
5498 funcname = ""; /* for safety */
5499 func_vt.t = VT_VOID; /* for safety */
5500 ind = 0; /* for safety */
5501 nocode_wanted = saved_nocode_wanted;
5504 ST_FUNC void gen_inline_functions(void)
5506 Sym *sym;
5507 int *str, inline_generated, i;
5508 struct InlineFunc *fn;
5510 /* iterate while inline function are referenced */
5511 for(;;) {
5512 inline_generated = 0;
5513 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
5514 fn = tcc_state->inline_fns[i];
5515 sym = fn->sym;
5516 if (sym && sym->c) {
5517 /* the function was used: generate its code and
5518 convert it to a normal function */
5519 str = fn->token_str;
5520 fn->sym = NULL;
5521 if (file)
5522 strcpy(file->filename, fn->filename);
5523 sym->r = VT_SYM | VT_CONST;
5524 sym->type.t &= ~VT_INLINE;
5526 macro_ptr = str;
5527 next();
5528 cur_text_section = text_section;
5529 gen_function(sym);
5530 macro_ptr = NULL; /* fail safe */
5532 inline_generated = 1;
5535 if (!inline_generated)
5536 break;
5538 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
5539 fn = tcc_state->inline_fns[i];
5540 str = fn->token_str;
5541 tok_str_free(str);
5543 dynarray_reset(&tcc_state->inline_fns, &tcc_state->nb_inline_fns);
5546 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
5547 static int decl0(int l, int is_for_loop_init)
5549 int v, has_init, r;
5550 CType type, btype;
5551 Sym *sym;
5552 AttributeDef ad;
5554 while (1) {
5555 if (!parse_btype(&btype, &ad)) {
5556 if (is_for_loop_init)
5557 return 0;
5558 /* skip redundant ';' */
5559 /* XXX: find more elegant solution */
5560 if (tok == ';') {
5561 next();
5562 continue;
5564 if (l == VT_CONST &&
5565 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
5566 /* global asm block */
5567 asm_global_instr();
5568 continue;
5570 /* special test for old K&R protos without explicit int
5571 type. Only accepted when defining global data */
5572 if (l == VT_LOCAL || tok < TOK_DEFINE)
5573 break;
5574 btype.t = VT_INT;
5576 if (((btype.t & VT_BTYPE) == VT_ENUM ||
5577 (btype.t & VT_BTYPE) == VT_STRUCT) &&
5578 tok == ';') {
5579 /* we accept no variable after */
5580 next();
5581 continue;
5583 while (1) { /* iterate thru each declaration */
5584 char *asm_label; // associated asm label
5585 type = btype;
5586 type_decl(&type, &ad, &v, TYPE_DIRECT);
5587 #if 0
5589 char buf[500];
5590 type_to_str(buf, sizeof(buf), t, get_tok_str(v, NULL));
5591 printf("type = '%s'\n", buf);
5593 #endif
5594 if ((type.t & VT_BTYPE) == VT_FUNC) {
5595 if ((type.t & VT_STATIC) && (l == VT_LOCAL)) {
5596 tcc_error("function without file scope cannot be static");
5598 /* if old style function prototype, we accept a
5599 declaration list */
5600 sym = type.ref;
5601 if (sym->c == FUNC_OLD)
5602 func_decl_list(sym);
5605 asm_label = NULL;
5606 if (gnu_ext && (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
5607 CString astr;
5609 asm_label_instr(&astr);
5610 asm_label = tcc_strdup(astr.data);
5611 cstr_free(&astr);
5613 /* parse one last attribute list, after asm label */
5614 parse_attribute(&ad);
5617 if (ad.weak)
5618 type.t |= VT_WEAK;
5619 #ifdef TCC_TARGET_PE
5620 if (ad.func_import)
5621 type.t |= VT_IMPORT;
5622 if (ad.func_export)
5623 type.t |= VT_EXPORT;
5624 #endif
5625 if (tok == '{') {
5626 if (l == VT_LOCAL)
5627 tcc_error("cannot use local functions");
5628 if ((type.t & VT_BTYPE) != VT_FUNC)
5629 expect("function definition");
5631 /* reject abstract declarators in function definition */
5632 sym = type.ref;
5633 while ((sym = sym->next) != NULL)
5634 if (!(sym->v & ~SYM_FIELD))
5635 expect("identifier");
5637 /* XXX: cannot do better now: convert extern line to static inline */
5638 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
5639 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
5641 sym = sym_find(v);
5642 if (sym) {
5643 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
5644 goto func_error1;
5646 r = sym->type.ref->r;
5647 /* use func_call from prototype if not defined */
5648 if (FUNC_CALL(r) != FUNC_CDECL
5649 && FUNC_CALL(type.ref->r) == FUNC_CDECL)
5650 FUNC_CALL(type.ref->r) = FUNC_CALL(r);
5652 /* use export from prototype */
5653 if (FUNC_EXPORT(r))
5654 FUNC_EXPORT(type.ref->r) = 1;
5656 /* use static from prototype */
5657 if (sym->type.t & VT_STATIC)
5658 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
5660 if (!is_compatible_types(&sym->type, &type)) {
5661 func_error1:
5662 tcc_error("incompatible types for redefinition of '%s'",
5663 get_tok_str(v, NULL));
5665 /* if symbol is already defined, then put complete type */
5666 sym->type = type;
5667 } else {
5668 /* put function symbol */
5669 sym = global_identifier_push(v, type.t, 0);
5670 sym->type.ref = type.ref;
5673 /* static inline functions are just recorded as a kind
5674 of macro. Their code will be emitted at the end of
5675 the compilation unit only if they are used */
5676 if ((type.t & (VT_INLINE | VT_STATIC)) ==
5677 (VT_INLINE | VT_STATIC)) {
5678 TokenString func_str;
5679 int block_level;
5680 struct InlineFunc *fn;
5681 const char *filename;
5683 tok_str_new(&func_str);
5685 block_level = 0;
5686 for(;;) {
5687 int t;
5688 if (tok == TOK_EOF)
5689 tcc_error("unexpected end of file");
5690 tok_str_add_tok(&func_str);
5691 t = tok;
5692 next();
5693 if (t == '{') {
5694 block_level++;
5695 } else if (t == '}') {
5696 block_level--;
5697 if (block_level == 0)
5698 break;
5701 tok_str_add(&func_str, -1);
5702 tok_str_add(&func_str, 0);
5703 filename = file ? file->filename : "";
5704 fn = tcc_malloc(sizeof *fn + strlen(filename));
5705 strcpy(fn->filename, filename);
5706 fn->sym = sym;
5707 fn->token_str = func_str.str;
5708 dynarray_add((void ***)&tcc_state->inline_fns, &tcc_state->nb_inline_fns, fn);
5710 } else {
5711 /* compute text section */
5712 cur_text_section = ad.section;
5713 if (!cur_text_section)
5714 cur_text_section = text_section;
5715 sym->r = VT_SYM | VT_CONST;
5716 gen_function(sym);
5718 break;
5719 } else {
5720 if (btype.t & VT_TYPEDEF) {
5721 /* save typedefed type */
5722 /* XXX: test storage specifiers ? */
5723 sym = sym_push(v, &type, INT_ATTR(&ad), 0);
5724 sym->type.t |= VT_TYPEDEF;
5725 } else {
5726 r = 0;
5727 if ((type.t & VT_BTYPE) == VT_FUNC) {
5728 /* external function definition */
5729 /* specific case for func_call attribute */
5730 type.ref->r = INT_ATTR(&ad);
5731 } else if (!(type.t & VT_ARRAY)) {
5732 /* not lvalue if array */
5733 r |= lvalue_type(type.t);
5735 has_init = (tok == '=');
5736 if (has_init && (type.t & VT_VLA))
5737 tcc_error("Variable length array cannot be initialized");
5738 if ((btype.t & VT_EXTERN) || ((type.t & VT_BTYPE) == VT_FUNC) ||
5739 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
5740 !has_init && l == VT_CONST && type.ref->c < 0)) {
5741 /* external variable or function */
5742 /* NOTE: as GCC, uninitialized global static
5743 arrays of null size are considered as
5744 extern */
5745 sym = external_sym(v, &type, r, asm_label);
5747 if (type.t & VT_WEAK)
5748 weaken_symbol(sym);
5750 if (ad.alias_target) {
5751 Section tsec;
5752 Elf32_Sym *esym;
5753 Sym *alias_target;
5755 alias_target = sym_find(ad.alias_target);
5756 if (!alias_target || !alias_target->c)
5757 tcc_error("unsupported forward __alias__ attribute");
5758 esym = &((Elf32_Sym *)symtab_section->data)[alias_target->c];
5759 tsec.sh_num = esym->st_shndx;
5760 put_extern_sym2(sym, &tsec, esym->st_value, esym->st_size, 0);
5762 } else {
5763 type.t |= (btype.t & VT_STATIC); /* Retain "static". */
5764 if (type.t & VT_STATIC)
5765 r |= VT_CONST;
5766 else
5767 r |= l;
5768 if (has_init)
5769 next();
5770 decl_initializer_alloc(&type, &ad, r, has_init, v, asm_label, l);
5773 if (tok != ',') {
5774 if (is_for_loop_init)
5775 return 1;
5776 skip(';');
5777 break;
5779 next();
5781 ad.aligned = 0;
5784 return 0;
5787 ST_FUNC void decl(int l)
5789 decl0(l, 0);