Add multiarch directory for arm hardfloat variant
[tinycc.git] / tccgen.c
blob71d080947642c228c5cdbc9a693e9e3d0258ee5e
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 /* cannot let cpu flags if other instruction are generated. Also
456 avoid leaving VT_JMP anywhere except on the top of the stack
457 because it would complicate the code generator. */
458 if (vtop >= vstack) {
459 int v = vtop->r & VT_VALMASK;
460 if (v == VT_CMP || (v & ~1) == VT_JMP)
461 gv(RC_INT);
463 tmp = vtop[0];
464 vtop[0] = vtop[-1];
465 vtop[-1] = tmp;
468 ST_FUNC void vpushv(SValue *v)
470 if (vtop >= vstack + (VSTACK_SIZE - 1))
471 tcc_error("memory full");
472 vtop++;
473 *vtop = *v;
476 static void vdup(void)
478 vpushv(vtop);
481 /* save r to the memory stack, and mark it as being free */
482 ST_FUNC void save_reg(int r)
484 int l, saved, size, align;
485 SValue *p, sv;
486 CType *type;
488 /* modify all stack values */
489 saved = 0;
490 l = 0;
491 for(p=vstack;p<=vtop;p++) {
492 if ((p->r & VT_VALMASK) == r ||
493 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
494 /* must save value on stack if not already done */
495 if (!saved) {
496 /* NOTE: must reload 'r' because r might be equal to r2 */
497 r = p->r & VT_VALMASK;
498 /* store register in the stack */
499 type = &p->type;
500 if ((p->r & VT_LVAL) ||
501 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
502 #ifdef TCC_TARGET_X86_64
503 type = &char_pointer_type;
504 #else
505 type = &int_type;
506 #endif
507 size = type_size(type, &align);
508 loc = (loc - size) & -align;
509 sv.type.t = type->t;
510 sv.r = VT_LOCAL | VT_LVAL;
511 sv.c.ul = loc;
512 store(r, &sv);
513 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
514 /* x86 specific: need to pop fp register ST0 if saved */
515 if (r == TREG_ST0) {
516 o(0xd8dd); /* fstp %st(0) */
518 #endif
519 #ifndef TCC_TARGET_X86_64
520 /* special long long case */
521 if ((type->t & VT_BTYPE) == VT_LLONG) {
522 sv.c.ul += 4;
523 store(p->r2, &sv);
525 #endif
526 l = loc;
527 saved = 1;
529 /* mark that stack entry as being saved on the stack */
530 if (p->r & VT_LVAL) {
531 /* also clear the bounded flag because the
532 relocation address of the function was stored in
533 p->c.ul */
534 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
535 } else {
536 p->r = lvalue_type(p->type.t) | VT_LOCAL;
538 p->r2 = VT_CONST;
539 p->c.ul = l;
544 #ifdef TCC_TARGET_ARM
545 /* find a register of class 'rc2' with at most one reference on stack.
546 * If none, call get_reg(rc) */
547 ST_FUNC int get_reg_ex(int rc, int rc2)
549 int r;
550 SValue *p;
552 for(r=0;r<NB_REGS;r++) {
553 if (reg_classes[r] & rc2) {
554 int n;
555 n=0;
556 for(p = vstack; p <= vtop; p++) {
557 if ((p->r & VT_VALMASK) == r ||
558 (p->r2 & VT_VALMASK) == r)
559 n++;
561 if (n <= 1)
562 return r;
565 return get_reg(rc);
567 #endif
569 /* find a free register of class 'rc'. If none, save one register */
570 ST_FUNC int get_reg(int rc)
572 int r;
573 SValue *p;
575 /* find a free register */
576 for(r=0;r<NB_REGS;r++) {
577 if (reg_classes[r] & rc) {
578 for(p=vstack;p<=vtop;p++) {
579 if ((p->r & VT_VALMASK) == r ||
580 (p->r2 & VT_VALMASK) == r)
581 goto notfound;
583 return r;
585 notfound: ;
588 /* no register left : free the first one on the stack (VERY
589 IMPORTANT to start from the bottom to ensure that we don't
590 spill registers used in gen_opi()) */
591 for(p=vstack;p<=vtop;p++) {
592 /* look at second register (if long long) */
593 r = p->r2 & VT_VALMASK;
594 if (r < VT_CONST && (reg_classes[r] & rc))
595 goto save_found;
596 r = p->r & VT_VALMASK;
597 if (r < VT_CONST && (reg_classes[r] & rc)) {
598 save_found:
599 save_reg(r);
600 return r;
603 /* Should never comes here */
604 return -1;
607 /* save registers up to (vtop - n) stack entry */
608 ST_FUNC void save_regs(int n)
610 int r;
611 SValue *p, *p1;
612 p1 = vtop - n;
613 for(p = vstack;p <= p1; p++) {
614 r = p->r & VT_VALMASK;
615 if (r < VT_CONST) {
616 save_reg(r);
621 /* move register 's' to 'r', and flush previous value of r to memory
622 if needed */
623 static void move_reg(int r, int s)
625 SValue sv;
627 if (r != s) {
628 save_reg(r);
629 sv.type.t = VT_INT;
630 sv.r = s;
631 sv.c.ul = 0;
632 load(r, &sv);
636 /* get address of vtop (vtop MUST BE an lvalue) */
637 static void gaddrof(void)
639 if (vtop->r & VT_REF)
640 gv(RC_INT);
641 vtop->r &= ~VT_LVAL;
642 /* tricky: if saved lvalue, then we can go back to lvalue */
643 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
644 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
649 #ifdef CONFIG_TCC_BCHECK
650 /* generate lvalue bound code */
651 static void gbound(void)
653 int lval_type;
654 CType type1;
656 vtop->r &= ~VT_MUSTBOUND;
657 /* if lvalue, then use checking code before dereferencing */
658 if (vtop->r & VT_LVAL) {
659 /* if not VT_BOUNDED value, then make one */
660 if (!(vtop->r & VT_BOUNDED)) {
661 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
662 /* must save type because we must set it to int to get pointer */
663 type1 = vtop->type;
664 vtop->type.t = VT_INT;
665 gaddrof();
666 vpushi(0);
667 gen_bounded_ptr_add();
668 vtop->r |= lval_type;
669 vtop->type = type1;
671 /* then check for dereferencing */
672 gen_bounded_ptr_deref();
675 #endif
677 /* store vtop a register belonging to class 'rc'. lvalues are
678 converted to values. Cannot be used if cannot be converted to
679 register value (such as structures). */
680 ST_FUNC int gv(int rc)
682 int r, bit_pos, bit_size, size, align, i;
683 #ifndef TCC_TARGET_X86_64
684 int rc2;
685 #endif
687 /* NOTE: get_reg can modify vstack[] */
688 if (vtop->type.t & VT_BITFIELD) {
689 CType type;
690 int bits = 32;
691 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
692 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
693 /* remove bit field info to avoid loops */
694 vtop->type.t &= ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
695 /* cast to int to propagate signedness in following ops */
696 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
697 type.t = VT_LLONG;
698 bits = 64;
699 } else
700 type.t = VT_INT;
701 if((vtop->type.t & VT_UNSIGNED) ||
702 (vtop->type.t & VT_BTYPE) == VT_BOOL)
703 type.t |= VT_UNSIGNED;
704 gen_cast(&type);
705 /* generate shifts */
706 vpushi(bits - (bit_pos + bit_size));
707 gen_op(TOK_SHL);
708 vpushi(bits - bit_size);
709 /* NOTE: transformed to SHR if unsigned */
710 gen_op(TOK_SAR);
711 r = gv(rc);
712 } else {
713 if (is_float(vtop->type.t) &&
714 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
715 Sym *sym;
716 int *ptr;
717 unsigned long offset;
718 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
719 CValue check;
720 #endif
722 /* XXX: unify with initializers handling ? */
723 /* CPUs usually cannot use float constants, so we store them
724 generically in data segment */
725 size = type_size(&vtop->type, &align);
726 offset = (data_section->data_offset + align - 1) & -align;
727 data_section->data_offset = offset;
728 /* XXX: not portable yet */
729 #if defined(__i386__) || defined(__x86_64__)
730 /* Zero pad x87 tenbyte long doubles */
731 if (size == LDOUBLE_SIZE) {
732 vtop->c.tab[2] &= 0xffff;
733 #if LDOUBLE_SIZE == 16
734 vtop->c.tab[3] = 0;
735 #endif
737 #endif
738 ptr = section_ptr_add(data_section, size);
739 size = size >> 2;
740 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
741 check.d = 1;
742 if(check.tab[0])
743 for(i=0;i<size;i++)
744 ptr[i] = vtop->c.tab[size-1-i];
745 else
746 #endif
747 for(i=0;i<size;i++)
748 ptr[i] = vtop->c.tab[i];
749 sym = get_sym_ref(&vtop->type, data_section, offset, size << 2);
750 vtop->r |= VT_LVAL | VT_SYM;
751 vtop->sym = sym;
752 vtop->c.ul = 0;
754 #ifdef CONFIG_TCC_BCHECK
755 if (vtop->r & VT_MUSTBOUND)
756 gbound();
757 #endif
759 r = vtop->r & VT_VALMASK;
760 #ifndef TCC_TARGET_X86_64
761 rc2 = RC_INT;
762 if (rc == RC_IRET)
763 rc2 = RC_LRET;
764 #endif
765 /* need to reload if:
766 - constant
767 - lvalue (need to dereference pointer)
768 - already a register, but not in the right class */
769 if (r >= VT_CONST
770 || (vtop->r & VT_LVAL)
771 || !(reg_classes[r] & rc)
772 #ifndef TCC_TARGET_X86_64
773 || ((vtop->type.t & VT_BTYPE) == VT_LLONG && !(reg_classes[vtop->r2] & rc2))
774 #endif
777 r = get_reg(rc);
778 #ifndef TCC_TARGET_X86_64
779 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
780 int r2;
781 unsigned long long ll;
782 /* two register type load : expand to two words
783 temporarily */
784 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
785 /* load constant */
786 ll = vtop->c.ull;
787 vtop->c.ui = ll; /* first word */
788 load(r, vtop);
789 vtop->r = r; /* save register value */
790 vpushi(ll >> 32); /* second word */
791 } else if (r >= VT_CONST || /* XXX: test to VT_CONST incorrect ? */
792 (vtop->r & VT_LVAL)) {
793 /* We do not want to modifier the long long
794 pointer here, so the safest (and less
795 efficient) is to save all the other registers
796 in the stack. XXX: totally inefficient. */
797 save_regs(1);
798 /* load from memory */
799 load(r, vtop);
800 vdup();
801 vtop[-1].r = r; /* save register value */
802 /* increment pointer to get second word */
803 vtop->type.t = VT_INT;
804 gaddrof();
805 vpushi(4);
806 gen_op('+');
807 vtop->r |= VT_LVAL;
808 } else {
809 /* move registers */
810 load(r, vtop);
811 vdup();
812 vtop[-1].r = r; /* save register value */
813 vtop->r = vtop[-1].r2;
815 /* Allocate second register. Here we rely on the fact that
816 get_reg() tries first to free r2 of an SValue. */
817 r2 = get_reg(rc2);
818 load(r2, vtop);
819 vpop();
820 /* write second register */
821 vtop->r2 = r2;
822 } else
823 #endif
824 if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
825 int t1, t;
826 /* lvalue of scalar type : need to use lvalue type
827 because of possible cast */
828 t = vtop->type.t;
829 t1 = t;
830 /* compute memory access type */
831 if (vtop->r & VT_LVAL_BYTE)
832 t = VT_BYTE;
833 else if (vtop->r & VT_LVAL_SHORT)
834 t = VT_SHORT;
835 if (vtop->r & VT_LVAL_UNSIGNED)
836 t |= VT_UNSIGNED;
837 vtop->type.t = t;
838 load(r, vtop);
839 /* restore wanted type */
840 vtop->type.t = t1;
841 } else {
842 /* one register type load */
843 load(r, vtop);
846 vtop->r = r;
847 #ifdef TCC_TARGET_C67
848 /* uses register pairs for doubles */
849 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
850 vtop->r2 = r+1;
851 #endif
853 return r;
856 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
857 ST_FUNC void gv2(int rc1, int rc2)
859 int v;
861 /* generate more generic register first. But VT_JMP or VT_CMP
862 values must be generated first in all cases to avoid possible
863 reload errors */
864 v = vtop[0].r & VT_VALMASK;
865 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
866 vswap();
867 gv(rc1);
868 vswap();
869 gv(rc2);
870 /* test if reload is needed for first register */
871 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
872 vswap();
873 gv(rc1);
874 vswap();
876 } else {
877 gv(rc2);
878 vswap();
879 gv(rc1);
880 vswap();
881 /* test if reload is needed for first register */
882 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
883 gv(rc2);
888 /* wrapper around RC_FRET to return a register by type */
889 static int rc_fret(int t)
891 #ifdef TCC_TARGET_X86_64
892 if (t == VT_LDOUBLE) {
893 return RC_ST0;
895 #endif
896 return RC_FRET;
899 /* wrapper around REG_FRET to return a register by type */
900 static int reg_fret(int t)
902 #ifdef TCC_TARGET_X86_64
903 if (t == VT_LDOUBLE) {
904 return TREG_ST0;
906 #endif
907 return REG_FRET;
910 /* expand long long on stack in two int registers */
911 static void lexpand(void)
913 int u;
915 u = vtop->type.t & VT_UNSIGNED;
916 gv(RC_INT);
917 vdup();
918 vtop[0].r = vtop[-1].r2;
919 vtop[0].r2 = VT_CONST;
920 vtop[-1].r2 = VT_CONST;
921 vtop[0].type.t = VT_INT | u;
922 vtop[-1].type.t = VT_INT | u;
925 #ifdef TCC_TARGET_ARM
926 /* expand long long on stack */
927 ST_FUNC void lexpand_nr(void)
929 int u,v;
931 u = vtop->type.t & VT_UNSIGNED;
932 vdup();
933 vtop->r2 = VT_CONST;
934 vtop->type.t = VT_INT | u;
935 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
936 if (v == VT_CONST) {
937 vtop[-1].c.ui = vtop->c.ull;
938 vtop->c.ui = vtop->c.ull >> 32;
939 vtop->r = VT_CONST;
940 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
941 vtop->c.ui += 4;
942 vtop->r = vtop[-1].r;
943 } else if (v > VT_CONST) {
944 vtop--;
945 lexpand();
946 } else
947 vtop->r = vtop[-1].r2;
948 vtop[-1].r2 = VT_CONST;
949 vtop[-1].type.t = VT_INT | u;
951 #endif
953 /* build a long long from two ints */
954 static void lbuild(int t)
956 gv2(RC_INT, RC_INT);
957 vtop[-1].r2 = vtop[0].r;
958 vtop[-1].type.t = t;
959 vpop();
962 /* rotate n first stack elements to the bottom
963 I1 ... In -> I2 ... In I1 [top is right]
965 ST_FUNC void vrotb(int n)
967 int i;
968 SValue tmp;
970 tmp = vtop[-n + 1];
971 for(i=-n+1;i!=0;i++)
972 vtop[i] = vtop[i+1];
973 vtop[0] = tmp;
976 /* rotate the n elements before entry e towards the top
977 I1 ... In ... -> In I1 ... I(n-1) ... [top is right]
979 ST_FUNC void vrote(SValue *e, int n)
981 int i;
982 SValue tmp;
984 tmp = *e;
985 for(i = 0;i < n - 1; i++)
986 e[-i] = e[-i - 1];
987 e[-n + 1] = tmp;
990 /* rotate n first stack elements to the top
991 I1 ... In -> In I1 ... I(n-1) [top is right]
993 ST_FUNC void vrott(int n)
995 vrote(vtop, n);
998 /* pop stack value */
999 ST_FUNC void vpop(void)
1001 int v;
1002 v = vtop->r & VT_VALMASK;
1003 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1004 /* for x86, we need to pop the FP stack */
1005 if (v == TREG_ST0 && !nocode_wanted) {
1006 o(0xd8dd); /* fstp %st(0) */
1007 } else
1008 #endif
1009 if (v == VT_JMP || v == VT_JMPI) {
1010 /* need to put correct jump if && or || without test */
1011 gsym(vtop->c.ul);
1013 vtop--;
1016 /* convert stack entry to register and duplicate its value in another
1017 register */
1018 static void gv_dup(void)
1020 int rc, t, r, r1;
1021 SValue sv;
1023 t = vtop->type.t;
1024 if ((t & VT_BTYPE) == VT_LLONG) {
1025 lexpand();
1026 gv_dup();
1027 vswap();
1028 vrotb(3);
1029 gv_dup();
1030 vrotb(4);
1031 /* stack: H L L1 H1 */
1032 lbuild(t);
1033 vrotb(3);
1034 vrotb(3);
1035 vswap();
1036 lbuild(t);
1037 vswap();
1038 } else {
1039 /* duplicate value */
1040 rc = RC_INT;
1041 sv.type.t = VT_INT;
1042 if (is_float(t)) {
1043 rc = RC_FLOAT;
1044 #ifdef TCC_TARGET_X86_64
1045 if ((t & VT_BTYPE) == VT_LDOUBLE) {
1046 rc = RC_ST0;
1048 #endif
1049 sv.type.t = t;
1051 r = gv(rc);
1052 r1 = get_reg(rc);
1053 sv.r = r;
1054 sv.c.ul = 0;
1055 load(r1, &sv); /* move r to r1 */
1056 vdup();
1057 /* duplicates value */
1058 if (r != r1)
1059 vtop->r = r1;
1063 #ifndef TCC_TARGET_X86_64
1064 /* generate CPU independent (unsigned) long long operations */
1065 static void gen_opl(int op)
1067 int t, a, b, op1, c, i;
1068 int func;
1069 unsigned short reg_iret = REG_IRET;
1070 unsigned short reg_lret = REG_LRET;
1071 SValue tmp;
1073 switch(op) {
1074 case '/':
1075 case TOK_PDIV:
1076 func = TOK___divdi3;
1077 goto gen_func;
1078 case TOK_UDIV:
1079 func = TOK___udivdi3;
1080 goto gen_func;
1081 case '%':
1082 func = TOK___moddi3;
1083 goto gen_mod_func;
1084 case TOK_UMOD:
1085 func = TOK___umoddi3;
1086 gen_mod_func:
1087 #ifdef TCC_ARM_EABI
1088 reg_iret = TREG_R2;
1089 reg_lret = TREG_R3;
1090 #endif
1091 gen_func:
1092 /* call generic long long function */
1093 vpush_global_sym(&func_old_type, func);
1094 vrott(3);
1095 gfunc_call(2);
1096 vpushi(0);
1097 vtop->r = reg_iret;
1098 vtop->r2 = reg_lret;
1099 break;
1100 case '^':
1101 case '&':
1102 case '|':
1103 case '*':
1104 case '+':
1105 case '-':
1106 t = vtop->type.t;
1107 vswap();
1108 lexpand();
1109 vrotb(3);
1110 lexpand();
1111 /* stack: L1 H1 L2 H2 */
1112 tmp = vtop[0];
1113 vtop[0] = vtop[-3];
1114 vtop[-3] = tmp;
1115 tmp = vtop[-2];
1116 vtop[-2] = vtop[-3];
1117 vtop[-3] = tmp;
1118 vswap();
1119 /* stack: H1 H2 L1 L2 */
1120 if (op == '*') {
1121 vpushv(vtop - 1);
1122 vpushv(vtop - 1);
1123 gen_op(TOK_UMULL);
1124 lexpand();
1125 /* stack: H1 H2 L1 L2 ML MH */
1126 for(i=0;i<4;i++)
1127 vrotb(6);
1128 /* stack: ML MH H1 H2 L1 L2 */
1129 tmp = vtop[0];
1130 vtop[0] = vtop[-2];
1131 vtop[-2] = tmp;
1132 /* stack: ML MH H1 L2 H2 L1 */
1133 gen_op('*');
1134 vrotb(3);
1135 vrotb(3);
1136 gen_op('*');
1137 /* stack: ML MH M1 M2 */
1138 gen_op('+');
1139 gen_op('+');
1140 } else if (op == '+' || op == '-') {
1141 /* XXX: add non carry method too (for MIPS or alpha) */
1142 if (op == '+')
1143 op1 = TOK_ADDC1;
1144 else
1145 op1 = TOK_SUBC1;
1146 gen_op(op1);
1147 /* stack: H1 H2 (L1 op L2) */
1148 vrotb(3);
1149 vrotb(3);
1150 gen_op(op1 + 1); /* TOK_xxxC2 */
1151 } else {
1152 gen_op(op);
1153 /* stack: H1 H2 (L1 op L2) */
1154 vrotb(3);
1155 vrotb(3);
1156 /* stack: (L1 op L2) H1 H2 */
1157 gen_op(op);
1158 /* stack: (L1 op L2) (H1 op H2) */
1160 /* stack: L H */
1161 lbuild(t);
1162 break;
1163 case TOK_SAR:
1164 case TOK_SHR:
1165 case TOK_SHL:
1166 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1167 t = vtop[-1].type.t;
1168 vswap();
1169 lexpand();
1170 vrotb(3);
1171 /* stack: L H shift */
1172 c = (int)vtop->c.i;
1173 /* constant: simpler */
1174 /* NOTE: all comments are for SHL. the other cases are
1175 done by swaping words */
1176 vpop();
1177 if (op != TOK_SHL)
1178 vswap();
1179 if (c >= 32) {
1180 /* stack: L H */
1181 vpop();
1182 if (c > 32) {
1183 vpushi(c - 32);
1184 gen_op(op);
1186 if (op != TOK_SAR) {
1187 vpushi(0);
1188 } else {
1189 gv_dup();
1190 vpushi(31);
1191 gen_op(TOK_SAR);
1193 vswap();
1194 } else {
1195 vswap();
1196 gv_dup();
1197 /* stack: H L L */
1198 vpushi(c);
1199 gen_op(op);
1200 vswap();
1201 vpushi(32 - c);
1202 if (op == TOK_SHL)
1203 gen_op(TOK_SHR);
1204 else
1205 gen_op(TOK_SHL);
1206 vrotb(3);
1207 /* stack: L L H */
1208 vpushi(c);
1209 if (op == TOK_SHL)
1210 gen_op(TOK_SHL);
1211 else
1212 gen_op(TOK_SHR);
1213 gen_op('|');
1215 if (op != TOK_SHL)
1216 vswap();
1217 lbuild(t);
1218 } else {
1219 /* XXX: should provide a faster fallback on x86 ? */
1220 switch(op) {
1221 case TOK_SAR:
1222 func = TOK___ashrdi3;
1223 goto gen_func;
1224 case TOK_SHR:
1225 func = TOK___lshrdi3;
1226 goto gen_func;
1227 case TOK_SHL:
1228 func = TOK___ashldi3;
1229 goto gen_func;
1232 break;
1233 default:
1234 /* compare operations */
1235 t = vtop->type.t;
1236 vswap();
1237 lexpand();
1238 vrotb(3);
1239 lexpand();
1240 /* stack: L1 H1 L2 H2 */
1241 tmp = vtop[-1];
1242 vtop[-1] = vtop[-2];
1243 vtop[-2] = tmp;
1244 /* stack: L1 L2 H1 H2 */
1245 /* compare high */
1246 op1 = op;
1247 /* when values are equal, we need to compare low words. since
1248 the jump is inverted, we invert the test too. */
1249 if (op1 == TOK_LT)
1250 op1 = TOK_LE;
1251 else if (op1 == TOK_GT)
1252 op1 = TOK_GE;
1253 else if (op1 == TOK_ULT)
1254 op1 = TOK_ULE;
1255 else if (op1 == TOK_UGT)
1256 op1 = TOK_UGE;
1257 a = 0;
1258 b = 0;
1259 gen_op(op1);
1260 if (op1 != TOK_NE) {
1261 a = gtst(1, 0);
1263 if (op != TOK_EQ) {
1264 /* generate non equal test */
1265 /* XXX: NOT PORTABLE yet */
1266 if (a == 0) {
1267 b = gtst(0, 0);
1268 } else {
1269 #if defined(TCC_TARGET_I386)
1270 b = psym(0x850f, 0);
1271 #elif defined(TCC_TARGET_ARM)
1272 b = ind;
1273 o(0x1A000000 | encbranch(ind, 0, 1));
1274 #elif defined(TCC_TARGET_C67)
1275 tcc_error("not implemented");
1276 #else
1277 #error not supported
1278 #endif
1281 /* compare low. Always unsigned */
1282 op1 = op;
1283 if (op1 == TOK_LT)
1284 op1 = TOK_ULT;
1285 else if (op1 == TOK_LE)
1286 op1 = TOK_ULE;
1287 else if (op1 == TOK_GT)
1288 op1 = TOK_UGT;
1289 else if (op1 == TOK_GE)
1290 op1 = TOK_UGE;
1291 gen_op(op1);
1292 a = gtst(1, a);
1293 gsym(b);
1294 vseti(VT_JMPI, a);
1295 break;
1298 #endif
1300 /* handle integer constant optimizations and various machine
1301 independent opt */
1302 static void gen_opic(int op)
1304 int c1, c2, t1, t2, n;
1305 SValue *v1, *v2;
1306 long long l1, l2;
1307 typedef unsigned long long U;
1309 v1 = vtop - 1;
1310 v2 = vtop;
1311 t1 = v1->type.t & VT_BTYPE;
1312 t2 = v2->type.t & VT_BTYPE;
1314 if (t1 == VT_LLONG)
1315 l1 = v1->c.ll;
1316 else if (v1->type.t & VT_UNSIGNED)
1317 l1 = v1->c.ui;
1318 else
1319 l1 = v1->c.i;
1321 if (t2 == VT_LLONG)
1322 l2 = v2->c.ll;
1323 else if (v2->type.t & VT_UNSIGNED)
1324 l2 = v2->c.ui;
1325 else
1326 l2 = v2->c.i;
1328 /* currently, we cannot do computations with forward symbols */
1329 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1330 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1331 if (c1 && c2) {
1332 switch(op) {
1333 case '+': l1 += l2; break;
1334 case '-': l1 -= l2; break;
1335 case '&': l1 &= l2; break;
1336 case '^': l1 ^= l2; break;
1337 case '|': l1 |= l2; break;
1338 case '*': l1 *= l2; break;
1340 case TOK_PDIV:
1341 case '/':
1342 case '%':
1343 case TOK_UDIV:
1344 case TOK_UMOD:
1345 /* if division by zero, generate explicit division */
1346 if (l2 == 0) {
1347 if (const_wanted)
1348 tcc_error("division by zero in constant");
1349 goto general_case;
1351 switch(op) {
1352 default: l1 /= l2; break;
1353 case '%': l1 %= l2; break;
1354 case TOK_UDIV: l1 = (U)l1 / l2; break;
1355 case TOK_UMOD: l1 = (U)l1 % l2; break;
1357 break;
1358 case TOK_SHL: l1 <<= l2; break;
1359 case TOK_SHR: l1 = (U)l1 >> l2; break;
1360 case TOK_SAR: l1 >>= l2; break;
1361 /* tests */
1362 case TOK_ULT: l1 = (U)l1 < (U)l2; break;
1363 case TOK_UGE: l1 = (U)l1 >= (U)l2; break;
1364 case TOK_EQ: l1 = l1 == l2; break;
1365 case TOK_NE: l1 = l1 != l2; break;
1366 case TOK_ULE: l1 = (U)l1 <= (U)l2; break;
1367 case TOK_UGT: l1 = (U)l1 > (U)l2; break;
1368 case TOK_LT: l1 = l1 < l2; break;
1369 case TOK_GE: l1 = l1 >= l2; break;
1370 case TOK_LE: l1 = l1 <= l2; break;
1371 case TOK_GT: l1 = l1 > l2; break;
1372 /* logical */
1373 case TOK_LAND: l1 = l1 && l2; break;
1374 case TOK_LOR: l1 = l1 || l2; break;
1375 default:
1376 goto general_case;
1378 v1->c.ll = l1;
1379 vtop--;
1380 } else {
1381 /* if commutative ops, put c2 as constant */
1382 if (c1 && (op == '+' || op == '&' || op == '^' ||
1383 op == '|' || op == '*')) {
1384 vswap();
1385 c2 = c1; //c = c1, c1 = c2, c2 = c;
1386 l2 = l1; //l = l1, l1 = l2, l2 = l;
1388 /* Filter out NOP operations like x*1, x-0, x&-1... */
1389 if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
1390 op == TOK_PDIV) &&
1391 l2 == 1) ||
1392 ((op == '+' || op == '-' || op == '|' || op == '^' ||
1393 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
1394 l2 == 0) ||
1395 (op == '&' &&
1396 l2 == -1))) {
1397 /* nothing to do */
1398 vtop--;
1399 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
1400 /* try to use shifts instead of muls or divs */
1401 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
1402 n = -1;
1403 while (l2) {
1404 l2 >>= 1;
1405 n++;
1407 vtop->c.ll = n;
1408 if (op == '*')
1409 op = TOK_SHL;
1410 else if (op == TOK_PDIV)
1411 op = TOK_SAR;
1412 else
1413 op = TOK_SHR;
1415 goto general_case;
1416 } else if (c2 && (op == '+' || op == '-') &&
1417 (((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM))
1418 || (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
1419 /* symbol + constant case */
1420 if (op == '-')
1421 l2 = -l2;
1422 vtop--;
1423 vtop->c.ll += l2;
1424 } else {
1425 general_case:
1426 if (!nocode_wanted) {
1427 /* call low level op generator */
1428 if (t1 == VT_LLONG || t2 == VT_LLONG)
1429 gen_opl(op);
1430 else
1431 gen_opi(op);
1432 } else {
1433 vtop--;
1439 /* generate a floating point operation with constant propagation */
1440 static void gen_opif(int op)
1442 int c1, c2;
1443 SValue *v1, *v2;
1444 long double f1, f2;
1446 v1 = vtop - 1;
1447 v2 = vtop;
1448 /* currently, we cannot do computations with forward symbols */
1449 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1450 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1451 if (c1 && c2) {
1452 if (v1->type.t == VT_FLOAT) {
1453 f1 = v1->c.f;
1454 f2 = v2->c.f;
1455 } else if (v1->type.t == VT_DOUBLE) {
1456 f1 = v1->c.d;
1457 f2 = v2->c.d;
1458 } else {
1459 f1 = v1->c.ld;
1460 f2 = v2->c.ld;
1463 /* NOTE: we only do constant propagation if finite number (not
1464 NaN or infinity) (ANSI spec) */
1465 if (!ieee_finite(f1) || !ieee_finite(f2))
1466 goto general_case;
1468 switch(op) {
1469 case '+': f1 += f2; break;
1470 case '-': f1 -= f2; break;
1471 case '*': f1 *= f2; break;
1472 case '/':
1473 if (f2 == 0.0) {
1474 if (const_wanted)
1475 tcc_error("division by zero in constant");
1476 goto general_case;
1478 f1 /= f2;
1479 break;
1480 /* XXX: also handles tests ? */
1481 default:
1482 goto general_case;
1484 /* XXX: overflow test ? */
1485 if (v1->type.t == VT_FLOAT) {
1486 v1->c.f = f1;
1487 } else if (v1->type.t == VT_DOUBLE) {
1488 v1->c.d = f1;
1489 } else {
1490 v1->c.ld = f1;
1492 vtop--;
1493 } else {
1494 general_case:
1495 if (!nocode_wanted) {
1496 gen_opf(op);
1497 } else {
1498 vtop--;
1503 static int pointed_size(CType *type)
1505 int align;
1506 return type_size(pointed_type(type), &align);
1509 static void vla_runtime_pointed_size(CType *type)
1511 int align;
1512 vla_runtime_type_size(pointed_type(type), &align);
1515 static inline int is_null_pointer(SValue *p)
1517 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
1518 return 0;
1519 return ((p->type.t & VT_BTYPE) == VT_INT && p->c.i == 0) ||
1520 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.ll == 0) ||
1521 ((p->type.t & VT_BTYPE) == VT_PTR && p->c.ptr == 0);
1524 static inline int is_integer_btype(int bt)
1526 return (bt == VT_BYTE || bt == VT_SHORT ||
1527 bt == VT_INT || bt == VT_LLONG);
1530 /* check types for comparison or substraction of pointers */
1531 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
1533 CType *type1, *type2, tmp_type1, tmp_type2;
1534 int bt1, bt2;
1536 /* null pointers are accepted for all comparisons as gcc */
1537 if (is_null_pointer(p1) || is_null_pointer(p2))
1538 return;
1539 type1 = &p1->type;
1540 type2 = &p2->type;
1541 bt1 = type1->t & VT_BTYPE;
1542 bt2 = type2->t & VT_BTYPE;
1543 /* accept comparison between pointer and integer with a warning */
1544 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
1545 if (op != TOK_LOR && op != TOK_LAND )
1546 tcc_warning("comparison between pointer and integer");
1547 return;
1550 /* both must be pointers or implicit function pointers */
1551 if (bt1 == VT_PTR) {
1552 type1 = pointed_type(type1);
1553 } else if (bt1 != VT_FUNC)
1554 goto invalid_operands;
1556 if (bt2 == VT_PTR) {
1557 type2 = pointed_type(type2);
1558 } else if (bt2 != VT_FUNC) {
1559 invalid_operands:
1560 tcc_error("invalid operands to binary %s", get_tok_str(op, NULL));
1562 if ((type1->t & VT_BTYPE) == VT_VOID ||
1563 (type2->t & VT_BTYPE) == VT_VOID)
1564 return;
1565 tmp_type1 = *type1;
1566 tmp_type2 = *type2;
1567 tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1568 tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1569 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
1570 /* gcc-like error if '-' is used */
1571 if (op == '-')
1572 goto invalid_operands;
1573 else
1574 tcc_warning("comparison of distinct pointer types lacks a cast");
1578 /* generic gen_op: handles types problems */
1579 ST_FUNC void gen_op(int op)
1581 int u, t1, t2, bt1, bt2, t;
1582 CType type1;
1584 t1 = vtop[-1].type.t;
1585 t2 = vtop[0].type.t;
1586 bt1 = t1 & VT_BTYPE;
1587 bt2 = t2 & VT_BTYPE;
1589 if (bt1 == VT_PTR || bt2 == VT_PTR) {
1590 /* at least one operand is a pointer */
1591 /* relationnal op: must be both pointers */
1592 if (op >= TOK_ULT && op <= TOK_LOR) {
1593 check_comparison_pointer_types(vtop - 1, vtop, op);
1594 /* pointers are handled are unsigned */
1595 #ifdef TCC_TARGET_X86_64
1596 t = VT_LLONG | VT_UNSIGNED;
1597 #else
1598 t = VT_INT | VT_UNSIGNED;
1599 #endif
1600 goto std_op;
1602 /* if both pointers, then it must be the '-' op */
1603 if (bt1 == VT_PTR && bt2 == VT_PTR) {
1604 if (op != '-')
1605 tcc_error("cannot use pointers here");
1606 check_comparison_pointer_types(vtop - 1, vtop, op);
1607 /* XXX: check that types are compatible */
1608 if (vtop[-1].type.t & VT_VLA) {
1609 vla_runtime_pointed_size(&vtop[-1].type);
1610 } else {
1611 vpushi(pointed_size(&vtop[-1].type));
1613 vrott(3);
1614 gen_opic(op);
1615 /* set to integer type */
1616 #ifdef TCC_TARGET_X86_64
1617 vtop->type.t = VT_LLONG;
1618 #else
1619 vtop->type.t = VT_INT;
1620 #endif
1621 vswap();
1622 gen_op(TOK_PDIV);
1623 } else {
1624 /* exactly one pointer : must be '+' or '-'. */
1625 if (op != '-' && op != '+')
1626 tcc_error("cannot use pointers here");
1627 /* Put pointer as first operand */
1628 if (bt2 == VT_PTR) {
1629 vswap();
1630 swap(&t1, &t2);
1632 type1 = vtop[-1].type;
1633 type1.t &= ~VT_ARRAY;
1634 if (vtop[-1].type.t & VT_VLA)
1635 vla_runtime_pointed_size(&vtop[-1].type);
1636 else {
1637 u = pointed_size(&vtop[-1].type);
1638 if (u < 0)
1639 tcc_error("unknown array element size");
1640 #ifdef TCC_TARGET_X86_64
1641 vpushll(u);
1642 #else
1643 /* XXX: cast to int ? (long long case) */
1644 vpushi(u);
1645 #endif
1647 gen_op('*');
1648 #ifdef CONFIG_TCC_BCHECK
1649 /* if evaluating constant expression, no code should be
1650 generated, so no bound check */
1651 if (tcc_state->do_bounds_check && !const_wanted) {
1652 /* if bounded pointers, we generate a special code to
1653 test bounds */
1654 if (op == '-') {
1655 vpushi(0);
1656 vswap();
1657 gen_op('-');
1659 gen_bounded_ptr_add();
1660 } else
1661 #endif
1663 gen_opic(op);
1665 /* put again type if gen_opic() swaped operands */
1666 vtop->type = type1;
1668 } else if (is_float(bt1) || is_float(bt2)) {
1669 /* compute bigger type and do implicit casts */
1670 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
1671 t = VT_LDOUBLE;
1672 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
1673 t = VT_DOUBLE;
1674 } else {
1675 t = VT_FLOAT;
1677 /* floats can only be used for a few operations */
1678 if (op != '+' && op != '-' && op != '*' && op != '/' &&
1679 (op < TOK_ULT || op > TOK_GT))
1680 tcc_error("invalid operands for binary operation");
1681 goto std_op;
1682 } else if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL) {
1683 t = bt1 == VT_LLONG ? VT_LLONG : VT_INT;
1684 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (t | VT_UNSIGNED))
1685 t |= VT_UNSIGNED;
1686 goto std_op;
1687 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
1688 /* cast to biggest op */
1689 t = VT_LLONG;
1690 /* convert to unsigned if it does not fit in a long long */
1691 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
1692 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
1693 t |= VT_UNSIGNED;
1694 goto std_op;
1695 } else {
1696 /* integer operations */
1697 t = VT_INT;
1698 /* convert to unsigned if it does not fit in an integer */
1699 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
1700 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
1701 t |= VT_UNSIGNED;
1702 std_op:
1703 /* XXX: currently, some unsigned operations are explicit, so
1704 we modify them here */
1705 if (t & VT_UNSIGNED) {
1706 if (op == TOK_SAR)
1707 op = TOK_SHR;
1708 else if (op == '/')
1709 op = TOK_UDIV;
1710 else if (op == '%')
1711 op = TOK_UMOD;
1712 else if (op == TOK_LT)
1713 op = TOK_ULT;
1714 else if (op == TOK_GT)
1715 op = TOK_UGT;
1716 else if (op == TOK_LE)
1717 op = TOK_ULE;
1718 else if (op == TOK_GE)
1719 op = TOK_UGE;
1721 vswap();
1722 type1.t = t;
1723 gen_cast(&type1);
1724 vswap();
1725 /* special case for shifts and long long: we keep the shift as
1726 an integer */
1727 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
1728 type1.t = VT_INT;
1729 gen_cast(&type1);
1730 if (is_float(t))
1731 gen_opif(op);
1732 else
1733 gen_opic(op);
1734 if (op >= TOK_ULT && op <= TOK_GT) {
1735 /* relationnal op: the result is an int */
1736 vtop->type.t = VT_INT;
1737 } else {
1738 vtop->type.t = t;
1743 #ifndef TCC_TARGET_ARM
1744 /* generic itof for unsigned long long case */
1745 static void gen_cvt_itof1(int t)
1747 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
1748 (VT_LLONG | VT_UNSIGNED)) {
1750 if (t == VT_FLOAT)
1751 vpush_global_sym(&func_old_type, TOK___floatundisf);
1752 #if LDOUBLE_SIZE != 8
1753 else if (t == VT_LDOUBLE)
1754 vpush_global_sym(&func_old_type, TOK___floatundixf);
1755 #endif
1756 else
1757 vpush_global_sym(&func_old_type, TOK___floatundidf);
1758 vrott(2);
1759 gfunc_call(1);
1760 vpushi(0);
1761 vtop->r = reg_fret(t);
1762 } else {
1763 gen_cvt_itof(t);
1766 #endif
1768 /* generic ftoi for unsigned long long case */
1769 static void gen_cvt_ftoi1(int t)
1771 int st;
1773 if (t == (VT_LLONG | VT_UNSIGNED)) {
1774 /* not handled natively */
1775 st = vtop->type.t & VT_BTYPE;
1776 if (st == VT_FLOAT)
1777 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
1778 #if LDOUBLE_SIZE != 8
1779 else if (st == VT_LDOUBLE)
1780 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
1781 #endif
1782 else
1783 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
1784 vrott(2);
1785 gfunc_call(1);
1786 vpushi(0);
1787 vtop->r = REG_IRET;
1788 vtop->r2 = REG_LRET;
1789 } else {
1790 gen_cvt_ftoi(t);
1794 /* force char or short cast */
1795 static void force_charshort_cast(int t)
1797 int bits, dbt;
1798 dbt = t & VT_BTYPE;
1799 /* XXX: add optimization if lvalue : just change type and offset */
1800 if (dbt == VT_BYTE)
1801 bits = 8;
1802 else
1803 bits = 16;
1804 if (t & VT_UNSIGNED) {
1805 vpushi((1 << bits) - 1);
1806 gen_op('&');
1807 } else {
1808 bits = 32 - bits;
1809 vpushi(bits);
1810 gen_op(TOK_SHL);
1811 /* result must be signed or the SAR is converted to an SHL
1812 This was not the case when "t" was a signed short
1813 and the last value on the stack was an unsigned int */
1814 vtop->type.t &= ~VT_UNSIGNED;
1815 vpushi(bits);
1816 gen_op(TOK_SAR);
1820 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
1821 static void gen_cast(CType *type)
1823 int sbt, dbt, sf, df, c, p;
1825 /* special delayed cast for char/short */
1826 /* XXX: in some cases (multiple cascaded casts), it may still
1827 be incorrect */
1828 if (vtop->r & VT_MUSTCAST) {
1829 vtop->r &= ~VT_MUSTCAST;
1830 force_charshort_cast(vtop->type.t);
1833 /* bitfields first get cast to ints */
1834 if (vtop->type.t & VT_BITFIELD) {
1835 gv(RC_INT);
1838 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
1839 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
1841 if (sbt != dbt) {
1842 sf = is_float(sbt);
1843 df = is_float(dbt);
1844 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1845 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
1846 if (c) {
1847 /* constant case: we can do it now */
1848 /* XXX: in ISOC, cannot do it if error in convert */
1849 if (sbt == VT_FLOAT)
1850 vtop->c.ld = vtop->c.f;
1851 else if (sbt == VT_DOUBLE)
1852 vtop->c.ld = vtop->c.d;
1854 if (df) {
1855 if ((sbt & VT_BTYPE) == VT_LLONG) {
1856 if (sbt & VT_UNSIGNED)
1857 vtop->c.ld = vtop->c.ull;
1858 else
1859 vtop->c.ld = vtop->c.ll;
1860 } else if(!sf) {
1861 if (sbt & VT_UNSIGNED)
1862 vtop->c.ld = vtop->c.ui;
1863 else
1864 vtop->c.ld = vtop->c.i;
1867 if (dbt == VT_FLOAT)
1868 vtop->c.f = (float)vtop->c.ld;
1869 else if (dbt == VT_DOUBLE)
1870 vtop->c.d = (double)vtop->c.ld;
1871 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
1872 vtop->c.ull = (unsigned long long)vtop->c.ld;
1873 } else if (sf && dbt == VT_BOOL) {
1874 vtop->c.i = (vtop->c.ld != 0);
1875 } else {
1876 if(sf)
1877 vtop->c.ll = (long long)vtop->c.ld;
1878 else if (sbt == (VT_LLONG|VT_UNSIGNED))
1879 vtop->c.ll = vtop->c.ull;
1880 else if (sbt & VT_UNSIGNED)
1881 vtop->c.ll = vtop->c.ui;
1882 #ifdef TCC_TARGET_X86_64
1883 else if (sbt == VT_PTR)
1885 #endif
1886 else if (sbt != VT_LLONG)
1887 vtop->c.ll = vtop->c.i;
1889 if (dbt == (VT_LLONG|VT_UNSIGNED))
1890 vtop->c.ull = vtop->c.ll;
1891 else if (dbt == VT_BOOL)
1892 vtop->c.i = (vtop->c.ll != 0);
1893 else if (dbt != VT_LLONG) {
1894 int s = 0;
1895 if ((dbt & VT_BTYPE) == VT_BYTE)
1896 s = 24;
1897 else if ((dbt & VT_BTYPE) == VT_SHORT)
1898 s = 16;
1900 if(dbt & VT_UNSIGNED)
1901 vtop->c.ui = ((unsigned int)vtop->c.ll << s) >> s;
1902 else
1903 vtop->c.i = ((int)vtop->c.ll << s) >> s;
1906 } else if (p && dbt == VT_BOOL) {
1907 vtop->r = VT_CONST;
1908 vtop->c.i = 1;
1909 } else if (!nocode_wanted) {
1910 /* non constant case: generate code */
1911 if (sf && df) {
1912 /* convert from fp to fp */
1913 gen_cvt_ftof(dbt);
1914 } else if (df) {
1915 /* convert int to fp */
1916 gen_cvt_itof1(dbt);
1917 } else if (sf) {
1918 /* convert fp to int */
1919 if (dbt == VT_BOOL) {
1920 vpushi(0);
1921 gen_op(TOK_NE);
1922 } else {
1923 /* we handle char/short/etc... with generic code */
1924 if (dbt != (VT_INT | VT_UNSIGNED) &&
1925 dbt != (VT_LLONG | VT_UNSIGNED) &&
1926 dbt != VT_LLONG)
1927 dbt = VT_INT;
1928 gen_cvt_ftoi1(dbt);
1929 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
1930 /* additional cast for char/short... */
1931 vtop->type.t = dbt;
1932 gen_cast(type);
1935 #ifndef TCC_TARGET_X86_64
1936 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
1937 if ((sbt & VT_BTYPE) != VT_LLONG) {
1938 /* scalar to long long */
1939 /* machine independent conversion */
1940 gv(RC_INT);
1941 /* generate high word */
1942 if (sbt == (VT_INT | VT_UNSIGNED)) {
1943 vpushi(0);
1944 gv(RC_INT);
1945 } else {
1946 if (sbt == VT_PTR) {
1947 /* cast from pointer to int before we apply
1948 shift operation, which pointers don't support*/
1949 gen_cast(&int_type);
1951 gv_dup();
1952 vpushi(31);
1953 gen_op(TOK_SAR);
1955 /* patch second register */
1956 vtop[-1].r2 = vtop->r;
1957 vpop();
1959 #else
1960 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
1961 (dbt & VT_BTYPE) == VT_PTR ||
1962 (dbt & VT_BTYPE) == VT_FUNC) {
1963 if ((sbt & VT_BTYPE) != VT_LLONG &&
1964 (sbt & VT_BTYPE) != VT_PTR &&
1965 (sbt & VT_BTYPE) != VT_FUNC) {
1966 /* need to convert from 32bit to 64bit */
1967 int r = gv(RC_INT);
1968 if (sbt != (VT_INT | VT_UNSIGNED)) {
1969 /* x86_64 specific: movslq */
1970 o(0x6348);
1971 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
1974 #endif
1975 } else if (dbt == VT_BOOL) {
1976 /* scalar to bool */
1977 vpushi(0);
1978 gen_op(TOK_NE);
1979 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
1980 (dbt & VT_BTYPE) == VT_SHORT) {
1981 if (sbt == VT_PTR) {
1982 vtop->type.t = VT_INT;
1983 tcc_warning("nonportable conversion from pointer to char/short");
1985 force_charshort_cast(dbt);
1986 } else if ((dbt & VT_BTYPE) == VT_INT) {
1987 /* scalar to int */
1988 if (sbt == VT_LLONG) {
1989 /* from long long: just take low order word */
1990 lexpand();
1991 vpop();
1993 /* if lvalue and single word type, nothing to do because
1994 the lvalue already contains the real type size (see
1995 VT_LVAL_xxx constants) */
1998 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
1999 /* if we are casting between pointer types,
2000 we must update the VT_LVAL_xxx size */
2001 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
2002 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
2004 vtop->type = *type;
2007 /* return type size as known at compile time. Put alignment at 'a' */
2008 ST_FUNC int type_size(CType *type, int *a)
2010 Sym *s;
2011 int bt;
2013 bt = type->t & VT_BTYPE;
2014 if (bt == VT_STRUCT) {
2015 /* struct/union */
2016 s = type->ref;
2017 *a = s->r;
2018 return s->c;
2019 } else if (bt == VT_PTR) {
2020 if (type->t & VT_ARRAY) {
2021 int ts;
2023 s = type->ref;
2024 ts = type_size(&s->type, a);
2026 if (ts < 0 && s->c < 0)
2027 ts = -ts;
2029 return ts * s->c;
2030 } else {
2031 *a = PTR_SIZE;
2032 return PTR_SIZE;
2034 } else if (bt == VT_LDOUBLE) {
2035 *a = LDOUBLE_ALIGN;
2036 return LDOUBLE_SIZE;
2037 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
2038 #ifdef TCC_TARGET_I386
2039 #ifdef TCC_TARGET_PE
2040 *a = 8;
2041 #else
2042 *a = 4;
2043 #endif
2044 #elif defined(TCC_TARGET_ARM)
2045 #ifdef TCC_ARM_EABI
2046 *a = 8;
2047 #else
2048 *a = 4;
2049 #endif
2050 #else
2051 *a = 8;
2052 #endif
2053 return 8;
2054 } else if (bt == VT_INT || bt == VT_ENUM || bt == VT_FLOAT) {
2055 *a = 4;
2056 return 4;
2057 } else if (bt == VT_SHORT) {
2058 *a = 2;
2059 return 2;
2060 } else {
2061 /* char, void, function, _Bool */
2062 *a = 1;
2063 return 1;
2067 /* push type size as known at runtime time on top of value stack. Put
2068 alignment at 'a' */
2069 ST_FUNC void vla_runtime_type_size(CType *type, int *a)
2071 if (type->t & VT_VLA) {
2072 vset(&int_type, VT_LOCAL|VT_LVAL, type->ref->c);
2073 } else {
2074 vpushi(type_size(type, a));
2078 /* return the pointed type of t */
2079 static inline CType *pointed_type(CType *type)
2081 return &type->ref->type;
2084 /* modify type so that its it is a pointer to type. */
2085 ST_FUNC void mk_pointer(CType *type)
2087 Sym *s;
2088 s = sym_push(SYM_FIELD, type, 0, -1);
2089 type->t = VT_PTR | (type->t & ~VT_TYPE);
2090 type->ref = s;
2093 /* compare function types. OLD functions match any new functions */
2094 static int is_compatible_func(CType *type1, CType *type2)
2096 Sym *s1, *s2;
2098 s1 = type1->ref;
2099 s2 = type2->ref;
2100 if (!is_compatible_types(&s1->type, &s2->type))
2101 return 0;
2102 /* check func_call */
2103 if (FUNC_CALL(s1->r) != FUNC_CALL(s2->r))
2104 return 0;
2105 /* XXX: not complete */
2106 if (s1->c == FUNC_OLD || s2->c == FUNC_OLD)
2107 return 1;
2108 if (s1->c != s2->c)
2109 return 0;
2110 while (s1 != NULL) {
2111 if (s2 == NULL)
2112 return 0;
2113 if (!is_compatible_parameter_types(&s1->type, &s2->type))
2114 return 0;
2115 s1 = s1->next;
2116 s2 = s2->next;
2118 if (s2)
2119 return 0;
2120 return 1;
2123 /* return true if type1 and type2 are the same. If unqualified is
2124 true, qualifiers on the types are ignored.
2126 - enums are not checked as gcc __builtin_types_compatible_p ()
2128 static int compare_types(CType *type1, CType *type2, int unqualified)
2130 int bt1, t1, t2;
2132 t1 = type1->t & VT_TYPE;
2133 t2 = type2->t & VT_TYPE;
2134 if (unqualified) {
2135 /* strip qualifiers before comparing */
2136 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
2137 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
2139 /* XXX: bitfields ? */
2140 if (t1 != t2)
2141 return 0;
2142 /* test more complicated cases */
2143 bt1 = t1 & VT_BTYPE;
2144 if (bt1 == VT_PTR) {
2145 type1 = pointed_type(type1);
2146 type2 = pointed_type(type2);
2147 return is_compatible_types(type1, type2);
2148 } else if (bt1 == VT_STRUCT) {
2149 return (type1->ref == type2->ref);
2150 } else if (bt1 == VT_FUNC) {
2151 return is_compatible_func(type1, type2);
2152 } else {
2153 return 1;
2157 /* return true if type1 and type2 are exactly the same (including
2158 qualifiers).
2160 static int is_compatible_types(CType *type1, CType *type2)
2162 return compare_types(type1,type2,0);
2165 /* return true if type1 and type2 are the same (ignoring qualifiers).
2167 static int is_compatible_parameter_types(CType *type1, CType *type2)
2169 return compare_types(type1,type2,1);
2172 /* print a type. If 'varstr' is not NULL, then the variable is also
2173 printed in the type */
2174 /* XXX: union */
2175 /* XXX: add array and function pointers */
2176 static void type_to_str(char *buf, int buf_size,
2177 CType *type, const char *varstr)
2179 int bt, v, t;
2180 Sym *s, *sa;
2181 char buf1[256];
2182 const char *tstr;
2184 t = type->t & VT_TYPE;
2185 bt = t & VT_BTYPE;
2186 buf[0] = '\0';
2187 if (t & VT_CONSTANT)
2188 pstrcat(buf, buf_size, "const ");
2189 if (t & VT_VOLATILE)
2190 pstrcat(buf, buf_size, "volatile ");
2191 if (t & VT_UNSIGNED)
2192 pstrcat(buf, buf_size, "unsigned ");
2193 switch(bt) {
2194 case VT_VOID:
2195 tstr = "void";
2196 goto add_tstr;
2197 case VT_BOOL:
2198 tstr = "_Bool";
2199 goto add_tstr;
2200 case VT_BYTE:
2201 tstr = "char";
2202 goto add_tstr;
2203 case VT_SHORT:
2204 tstr = "short";
2205 goto add_tstr;
2206 case VT_INT:
2207 tstr = "int";
2208 goto add_tstr;
2209 case VT_LONG:
2210 tstr = "long";
2211 goto add_tstr;
2212 case VT_LLONG:
2213 tstr = "long long";
2214 goto add_tstr;
2215 case VT_FLOAT:
2216 tstr = "float";
2217 goto add_tstr;
2218 case VT_DOUBLE:
2219 tstr = "double";
2220 goto add_tstr;
2221 case VT_LDOUBLE:
2222 tstr = "long double";
2223 add_tstr:
2224 pstrcat(buf, buf_size, tstr);
2225 break;
2226 case VT_ENUM:
2227 case VT_STRUCT:
2228 if (bt == VT_STRUCT)
2229 tstr = "struct ";
2230 else
2231 tstr = "enum ";
2232 pstrcat(buf, buf_size, tstr);
2233 v = type->ref->v & ~SYM_STRUCT;
2234 if (v >= SYM_FIRST_ANOM)
2235 pstrcat(buf, buf_size, "<anonymous>");
2236 else
2237 pstrcat(buf, buf_size, get_tok_str(v, NULL));
2238 break;
2239 case VT_FUNC:
2240 s = type->ref;
2241 type_to_str(buf, buf_size, &s->type, varstr);
2242 pstrcat(buf, buf_size, "(");
2243 sa = s->next;
2244 while (sa != NULL) {
2245 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
2246 pstrcat(buf, buf_size, buf1);
2247 sa = sa->next;
2248 if (sa)
2249 pstrcat(buf, buf_size, ", ");
2251 pstrcat(buf, buf_size, ")");
2252 goto no_var;
2253 case VT_PTR:
2254 s = type->ref;
2255 pstrcpy(buf1, sizeof(buf1), "*");
2256 if (varstr)
2257 pstrcat(buf1, sizeof(buf1), varstr);
2258 type_to_str(buf, buf_size, &s->type, buf1);
2259 goto no_var;
2261 if (varstr) {
2262 pstrcat(buf, buf_size, " ");
2263 pstrcat(buf, buf_size, varstr);
2265 no_var: ;
2268 /* verify type compatibility to store vtop in 'dt' type, and generate
2269 casts if needed. */
2270 static void gen_assign_cast(CType *dt)
2272 CType *st, *type1, *type2, tmp_type1, tmp_type2;
2273 char buf1[256], buf2[256];
2274 int dbt, sbt;
2276 st = &vtop->type; /* source type */
2277 dbt = dt->t & VT_BTYPE;
2278 sbt = st->t & VT_BTYPE;
2279 if (sbt == VT_VOID)
2280 tcc_error("Cannot assign void value");
2281 if (dt->t & VT_CONSTANT)
2282 tcc_warning("assignment of read-only location");
2283 switch(dbt) {
2284 case VT_PTR:
2285 /* special cases for pointers */
2286 /* '0' can also be a pointer */
2287 if (is_null_pointer(vtop))
2288 goto type_ok;
2289 /* accept implicit pointer to integer cast with warning */
2290 if (is_integer_btype(sbt)) {
2291 tcc_warning("assignment makes pointer from integer without a cast");
2292 goto type_ok;
2294 type1 = pointed_type(dt);
2295 /* a function is implicitely a function pointer */
2296 if (sbt == VT_FUNC) {
2297 if ((type1->t & VT_BTYPE) != VT_VOID &&
2298 !is_compatible_types(pointed_type(dt), st))
2299 tcc_warning("assignment from incompatible pointer type");
2300 goto type_ok;
2302 if (sbt != VT_PTR)
2303 goto error;
2304 type2 = pointed_type(st);
2305 if ((type1->t & VT_BTYPE) == VT_VOID ||
2306 (type2->t & VT_BTYPE) == VT_VOID) {
2307 /* void * can match anything */
2308 } else {
2309 /* exact type match, except for unsigned */
2310 tmp_type1 = *type1;
2311 tmp_type2 = *type2;
2312 tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
2313 tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
2314 if (!is_compatible_types(&tmp_type1, &tmp_type2))
2315 tcc_warning("assignment from incompatible pointer type");
2317 /* check const and volatile */
2318 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
2319 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
2320 tcc_warning("assignment discards qualifiers from pointer target type");
2321 break;
2322 case VT_BYTE:
2323 case VT_SHORT:
2324 case VT_INT:
2325 case VT_LLONG:
2326 if (sbt == VT_PTR || sbt == VT_FUNC) {
2327 tcc_warning("assignment makes integer from pointer without a cast");
2329 /* XXX: more tests */
2330 break;
2331 case VT_STRUCT:
2332 tmp_type1 = *dt;
2333 tmp_type2 = *st;
2334 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2335 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2336 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2337 error:
2338 type_to_str(buf1, sizeof(buf1), st, NULL);
2339 type_to_str(buf2, sizeof(buf2), dt, NULL);
2340 tcc_error("cannot cast '%s' to '%s'", buf1, buf2);
2342 break;
2344 type_ok:
2345 gen_cast(dt);
2348 /* store vtop in lvalue pushed on stack */
2349 ST_FUNC void vstore(void)
2351 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
2353 ft = vtop[-1].type.t;
2354 sbt = vtop->type.t & VT_BTYPE;
2355 dbt = ft & VT_BTYPE;
2356 if ((((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
2357 (sbt == VT_INT && dbt == VT_SHORT))
2358 && !(vtop->type.t & VT_BITFIELD)) {
2359 /* optimize char/short casts */
2360 delayed_cast = VT_MUSTCAST;
2361 vtop->type.t = ft & (VT_TYPE & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT)));
2362 /* XXX: factorize */
2363 if (ft & VT_CONSTANT)
2364 tcc_warning("assignment of read-only location");
2365 } else {
2366 delayed_cast = 0;
2367 if (!(ft & VT_BITFIELD))
2368 gen_assign_cast(&vtop[-1].type);
2371 if (sbt == VT_STRUCT) {
2372 /* if structure, only generate pointer */
2373 /* structure assignment : generate memcpy */
2374 /* XXX: optimize if small size */
2375 if (!nocode_wanted) {
2376 size = type_size(&vtop->type, &align);
2378 /* destination */
2379 vswap();
2380 vtop->type.t = VT_PTR;
2381 gaddrof();
2383 /* address of memcpy() */
2384 #ifdef TCC_ARM_EABI
2385 if(!(align & 7))
2386 vpush_global_sym(&func_old_type, TOK_memcpy8);
2387 else if(!(align & 3))
2388 vpush_global_sym(&func_old_type, TOK_memcpy4);
2389 else
2390 #endif
2391 vpush_global_sym(&func_old_type, TOK_memcpy);
2393 vswap();
2394 /* source */
2395 vpushv(vtop - 2);
2396 vtop->type.t = VT_PTR;
2397 gaddrof();
2398 /* type size */
2399 vpushi(size);
2400 gfunc_call(3);
2401 } else {
2402 vswap();
2403 vpop();
2405 /* leave source on stack */
2406 } else if (ft & VT_BITFIELD) {
2407 /* bitfield store handling */
2408 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
2409 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
2410 /* remove bit field info to avoid loops */
2411 vtop[-1].type.t = ft & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
2413 /* duplicate source into other register */
2414 gv_dup();
2415 vswap();
2416 vrott(3);
2418 if((ft & VT_BTYPE) == VT_BOOL) {
2419 gen_cast(&vtop[-1].type);
2420 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
2423 /* duplicate destination */
2424 vdup();
2425 vtop[-1] = vtop[-2];
2427 /* mask and shift source */
2428 if((ft & VT_BTYPE) != VT_BOOL) {
2429 if((ft & VT_BTYPE) == VT_LLONG) {
2430 vpushll((1ULL << bit_size) - 1ULL);
2431 } else {
2432 vpushi((1 << bit_size) - 1);
2434 gen_op('&');
2436 vpushi(bit_pos);
2437 gen_op(TOK_SHL);
2438 /* load destination, mask and or with source */
2439 vswap();
2440 if((ft & VT_BTYPE) == VT_LLONG) {
2441 vpushll(~(((1ULL << bit_size) - 1ULL) << bit_pos));
2442 } else {
2443 vpushi(~(((1 << bit_size) - 1) << bit_pos));
2445 gen_op('&');
2446 gen_op('|');
2447 /* store result */
2448 vstore();
2450 /* pop off shifted source from "duplicate source..." above */
2451 vpop();
2453 } else {
2454 #ifdef CONFIG_TCC_BCHECK
2455 /* bound check case */
2456 if (vtop[-1].r & VT_MUSTBOUND) {
2457 vswap();
2458 gbound();
2459 vswap();
2461 #endif
2462 if (!nocode_wanted) {
2463 rc = RC_INT;
2464 if (is_float(ft)) {
2465 rc = RC_FLOAT;
2466 #ifdef TCC_TARGET_X86_64
2467 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
2468 rc = RC_ST0;
2470 #endif
2472 r = gv(rc); /* generate value */
2473 /* if lvalue was saved on stack, must read it */
2474 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
2475 SValue sv;
2476 t = get_reg(RC_INT);
2477 #ifdef TCC_TARGET_X86_64
2478 sv.type.t = VT_PTR;
2479 #else
2480 sv.type.t = VT_INT;
2481 #endif
2482 sv.r = VT_LOCAL | VT_LVAL;
2483 sv.c.ul = vtop[-1].c.ul;
2484 load(t, &sv);
2485 vtop[-1].r = t | VT_LVAL;
2487 store(r, vtop - 1);
2488 #ifndef TCC_TARGET_X86_64
2489 /* two word case handling : store second register at word + 4 */
2490 if ((ft & VT_BTYPE) == VT_LLONG) {
2491 vswap();
2492 /* convert to int to increment easily */
2493 vtop->type.t = VT_INT;
2494 gaddrof();
2495 vpushi(4);
2496 gen_op('+');
2497 vtop->r |= VT_LVAL;
2498 vswap();
2499 /* XXX: it works because r2 is spilled last ! */
2500 store(vtop->r2, vtop - 1);
2502 #endif
2504 vswap();
2505 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
2506 vtop->r |= delayed_cast;
2510 /* post defines POST/PRE add. c is the token ++ or -- */
2511 ST_FUNC void inc(int post, int c)
2513 test_lvalue();
2514 vdup(); /* save lvalue */
2515 if (post) {
2516 gv_dup(); /* duplicate value */
2517 vrotb(3);
2518 vrotb(3);
2520 /* add constant */
2521 vpushi(c - TOK_MID);
2522 gen_op('+');
2523 vstore(); /* store value */
2524 if (post)
2525 vpop(); /* if post op, return saved value */
2528 /* Parse GNUC __attribute__ extension. Currently, the following
2529 extensions are recognized:
2530 - aligned(n) : set data/function alignment.
2531 - packed : force data alignment to 1
2532 - section(x) : generate data/code in this section.
2533 - unused : currently ignored, but may be used someday.
2534 - regparm(n) : pass function parameters in registers (i386 only)
2536 static void parse_attribute(AttributeDef *ad)
2538 int t, n;
2540 while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
2541 next();
2542 skip('(');
2543 skip('(');
2544 while (tok != ')') {
2545 if (tok < TOK_IDENT)
2546 expect("attribute name");
2547 t = tok;
2548 next();
2549 switch(t) {
2550 case TOK_SECTION1:
2551 case TOK_SECTION2:
2552 skip('(');
2553 if (tok != TOK_STR)
2554 expect("section name");
2555 ad->section = find_section(tcc_state, (char *)tokc.cstr->data);
2556 next();
2557 skip(')');
2558 break;
2559 case TOK_ALIAS1:
2560 case TOK_ALIAS2:
2561 skip('(');
2562 if (tok != TOK_STR)
2563 expect("alias(\"target\")");
2564 ad->alias_target = /* save string as token, for later */
2565 tok_alloc((char*)tokc.cstr->data, tokc.cstr->size-1)->tok;
2566 next();
2567 skip(')');
2568 break;
2569 case TOK_ALIGNED1:
2570 case TOK_ALIGNED2:
2571 if (tok == '(') {
2572 next();
2573 n = expr_const();
2574 if (n <= 0 || (n & (n - 1)) != 0)
2575 tcc_error("alignment must be a positive power of two");
2576 skip(')');
2577 } else {
2578 n = MAX_ALIGN;
2580 ad->aligned = n;
2581 break;
2582 case TOK_PACKED1:
2583 case TOK_PACKED2:
2584 ad->packed = 1;
2585 break;
2586 case TOK_WEAK1:
2587 case TOK_WEAK2:
2588 ad->weak = 1;
2589 break;
2590 case TOK_UNUSED1:
2591 case TOK_UNUSED2:
2592 /* currently, no need to handle it because tcc does not
2593 track unused objects */
2594 break;
2595 case TOK_NORETURN1:
2596 case TOK_NORETURN2:
2597 /* currently, no need to handle it because tcc does not
2598 track unused objects */
2599 break;
2600 case TOK_CDECL1:
2601 case TOK_CDECL2:
2602 case TOK_CDECL3:
2603 ad->func_call = FUNC_CDECL;
2604 break;
2605 case TOK_STDCALL1:
2606 case TOK_STDCALL2:
2607 case TOK_STDCALL3:
2608 ad->func_call = FUNC_STDCALL;
2609 break;
2610 #ifdef TCC_TARGET_I386
2611 case TOK_REGPARM1:
2612 case TOK_REGPARM2:
2613 skip('(');
2614 n = expr_const();
2615 if (n > 3)
2616 n = 3;
2617 else if (n < 0)
2618 n = 0;
2619 if (n > 0)
2620 ad->func_call = FUNC_FASTCALL1 + n - 1;
2621 skip(')');
2622 break;
2623 case TOK_FASTCALL1:
2624 case TOK_FASTCALL2:
2625 case TOK_FASTCALL3:
2626 ad->func_call = FUNC_FASTCALLW;
2627 break;
2628 #endif
2629 case TOK_MODE:
2630 skip('(');
2631 switch(tok) {
2632 case TOK_MODE_DI:
2633 ad->mode = VT_LLONG + 1;
2634 break;
2635 case TOK_MODE_HI:
2636 ad->mode = VT_SHORT + 1;
2637 break;
2638 case TOK_MODE_SI:
2639 ad->mode = VT_INT + 1;
2640 break;
2641 default:
2642 tcc_warning("__mode__(%s) not supported\n", get_tok_str(tok, NULL));
2643 break;
2645 next();
2646 skip(')');
2647 break;
2648 case TOK_DLLEXPORT:
2649 ad->func_export = 1;
2650 break;
2651 case TOK_DLLIMPORT:
2652 ad->func_import = 1;
2653 break;
2654 default:
2655 if (tcc_state->warn_unsupported)
2656 tcc_warning("'%s' attribute ignored", get_tok_str(t, NULL));
2657 /* skip parameters */
2658 if (tok == '(') {
2659 int parenthesis = 0;
2660 do {
2661 if (tok == '(')
2662 parenthesis++;
2663 else if (tok == ')')
2664 parenthesis--;
2665 next();
2666 } while (parenthesis && tok != -1);
2668 break;
2670 if (tok != ',')
2671 break;
2672 next();
2674 skip(')');
2675 skip(')');
2679 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
2680 static void struct_decl(CType *type, int u)
2682 int a, v, size, align, maxalign, c, offset;
2683 int bit_size, bit_pos, bsize, bt, lbit_pos, prevbt;
2684 Sym *s, *ss, *ass, **ps;
2685 AttributeDef ad;
2686 CType type1, btype;
2688 a = tok; /* save decl type */
2689 next();
2690 if (tok != '{') {
2691 v = tok;
2692 next();
2693 /* struct already defined ? return it */
2694 if (v < TOK_IDENT)
2695 expect("struct/union/enum name");
2696 s = struct_find(v);
2697 if (s) {
2698 if (s->type.t != a)
2699 tcc_error("invalid type");
2700 goto do_decl;
2702 } else {
2703 v = anon_sym++;
2705 type1.t = a;
2706 /* we put an undefined size for struct/union */
2707 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
2708 s->r = 0; /* default alignment is zero as gcc */
2709 /* put struct/union/enum name in type */
2710 do_decl:
2711 type->t = u;
2712 type->ref = s;
2714 if (tok == '{') {
2715 next();
2716 if (s->c != -1)
2717 tcc_error("struct/union/enum already defined");
2718 /* cannot be empty */
2719 c = 0;
2720 /* non empty enums are not allowed */
2721 if (a == TOK_ENUM) {
2722 for(;;) {
2723 v = tok;
2724 if (v < TOK_UIDENT)
2725 expect("identifier");
2726 next();
2727 if (tok == '=') {
2728 next();
2729 c = expr_const();
2731 /* enum symbols have static storage */
2732 ss = sym_push(v, &int_type, VT_CONST, c);
2733 ss->type.t |= VT_STATIC;
2734 if (tok != ',')
2735 break;
2736 next();
2737 c++;
2738 /* NOTE: we accept a trailing comma */
2739 if (tok == '}')
2740 break;
2742 skip('}');
2743 } else {
2744 maxalign = 1;
2745 ps = &s->next;
2746 prevbt = VT_INT;
2747 bit_pos = 0;
2748 offset = 0;
2749 while (tok != '}') {
2750 parse_btype(&btype, &ad);
2751 while (1) {
2752 bit_size = -1;
2753 v = 0;
2754 type1 = btype;
2755 if (tok != ':') {
2756 type_decl(&type1, &ad, &v, TYPE_DIRECT | TYPE_ABSTRACT);
2757 if (v == 0 && (type1.t & VT_BTYPE) != VT_STRUCT)
2758 expect("identifier");
2759 if ((type1.t & VT_BTYPE) == VT_FUNC ||
2760 (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
2761 tcc_error("invalid type for '%s'",
2762 get_tok_str(v, NULL));
2764 if (tok == ':') {
2765 next();
2766 bit_size = expr_const();
2767 /* XXX: handle v = 0 case for messages */
2768 if (bit_size < 0)
2769 tcc_error("negative width in bit-field '%s'",
2770 get_tok_str(v, NULL));
2771 if (v && bit_size == 0)
2772 tcc_error("zero width for bit-field '%s'",
2773 get_tok_str(v, NULL));
2775 size = type_size(&type1, &align);
2776 if (ad.aligned) {
2777 if (align < ad.aligned)
2778 align = ad.aligned;
2779 } else if (ad.packed) {
2780 align = 1;
2781 } else if (*tcc_state->pack_stack_ptr) {
2782 if (align > *tcc_state->pack_stack_ptr)
2783 align = *tcc_state->pack_stack_ptr;
2785 lbit_pos = 0;
2786 if (bit_size >= 0) {
2787 bt = type1.t & VT_BTYPE;
2788 if (bt != VT_INT &&
2789 bt != VT_BYTE &&
2790 bt != VT_SHORT &&
2791 bt != VT_BOOL &&
2792 bt != VT_ENUM &&
2793 bt != VT_LLONG)
2794 tcc_error("bitfields must have scalar type");
2795 bsize = size * 8;
2796 if (bit_size > bsize) {
2797 tcc_error("width of '%s' exceeds its type",
2798 get_tok_str(v, NULL));
2799 } else if (bit_size == bsize) {
2800 /* no need for bit fields */
2801 bit_pos = 0;
2802 } else if (bit_size == 0) {
2803 /* XXX: what to do if only padding in a
2804 structure ? */
2805 /* zero size: means to pad */
2806 bit_pos = 0;
2807 } else {
2808 /* we do not have enough room ?
2809 did the type change?
2810 is it a union? */
2811 if ((bit_pos + bit_size) > bsize ||
2812 bt != prevbt || a == TOK_UNION)
2813 bit_pos = 0;
2814 lbit_pos = bit_pos;
2815 /* XXX: handle LSB first */
2816 type1.t |= VT_BITFIELD |
2817 (bit_pos << VT_STRUCT_SHIFT) |
2818 (bit_size << (VT_STRUCT_SHIFT + 6));
2819 bit_pos += bit_size;
2821 prevbt = bt;
2822 } else {
2823 bit_pos = 0;
2825 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
2826 /* add new memory data only if starting
2827 bit field */
2828 if (lbit_pos == 0) {
2829 if (a == TOK_STRUCT) {
2830 c = (c + align - 1) & -align;
2831 offset = c;
2832 if (size > 0)
2833 c += size;
2834 } else {
2835 offset = 0;
2836 if (size > c)
2837 c = size;
2839 if (align > maxalign)
2840 maxalign = align;
2842 #if 0
2843 printf("add field %s offset=%d",
2844 get_tok_str(v, NULL), offset);
2845 if (type1.t & VT_BITFIELD) {
2846 printf(" pos=%d size=%d",
2847 (type1.t >> VT_STRUCT_SHIFT) & 0x3f,
2848 (type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
2850 printf("\n");
2851 #endif
2853 if (v == 0 && (type1.t & VT_BTYPE) == VT_STRUCT) {
2854 ass = type1.ref;
2855 while ((ass = ass->next) != NULL) {
2856 ss = sym_push(ass->v, &ass->type, 0, offset + ass->c);
2857 *ps = ss;
2858 ps = &ss->next;
2860 } else if (v) {
2861 ss = sym_push(v | SYM_FIELD, &type1, 0, offset);
2862 *ps = ss;
2863 ps = &ss->next;
2865 if (tok == ';' || tok == TOK_EOF)
2866 break;
2867 skip(',');
2869 skip(';');
2871 skip('}');
2872 /* store size and alignment */
2873 s->c = (c + maxalign - 1) & -maxalign;
2874 s->r = maxalign;
2879 /* return 0 if no type declaration. otherwise, return the basic type
2880 and skip it.
2882 static int parse_btype(CType *type, AttributeDef *ad)
2884 int t, u, type_found, typespec_found, typedef_found;
2885 Sym *s;
2886 CType type1;
2888 memset(ad, 0, sizeof(AttributeDef));
2889 type_found = 0;
2890 typespec_found = 0;
2891 typedef_found = 0;
2892 t = 0;
2893 while(1) {
2894 switch(tok) {
2895 case TOK_EXTENSION:
2896 /* currently, we really ignore extension */
2897 next();
2898 continue;
2900 /* basic types */
2901 case TOK_CHAR:
2902 u = VT_BYTE;
2903 basic_type:
2904 next();
2905 basic_type1:
2906 if ((t & VT_BTYPE) != 0)
2907 tcc_error("too many basic types");
2908 t |= u;
2909 typespec_found = 1;
2910 break;
2911 case TOK_VOID:
2912 u = VT_VOID;
2913 goto basic_type;
2914 case TOK_SHORT:
2915 u = VT_SHORT;
2916 goto basic_type;
2917 case TOK_INT:
2918 next();
2919 typespec_found = 1;
2920 break;
2921 case TOK_LONG:
2922 next();
2923 if ((t & VT_BTYPE) == VT_DOUBLE) {
2924 #ifndef TCC_TARGET_PE
2925 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
2926 #endif
2927 } else if ((t & VT_BTYPE) == VT_LONG) {
2928 t = (t & ~VT_BTYPE) | VT_LLONG;
2929 } else {
2930 u = VT_LONG;
2931 goto basic_type1;
2933 break;
2934 case TOK_BOOL:
2935 u = VT_BOOL;
2936 goto basic_type;
2937 case TOK_FLOAT:
2938 u = VT_FLOAT;
2939 goto basic_type;
2940 case TOK_DOUBLE:
2941 next();
2942 if ((t & VT_BTYPE) == VT_LONG) {
2943 #ifdef TCC_TARGET_PE
2944 t = (t & ~VT_BTYPE) | VT_DOUBLE;
2945 #else
2946 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
2947 #endif
2948 } else {
2949 u = VT_DOUBLE;
2950 goto basic_type1;
2952 break;
2953 case TOK_ENUM:
2954 struct_decl(&type1, VT_ENUM);
2955 basic_type2:
2956 u = type1.t;
2957 type->ref = type1.ref;
2958 goto basic_type1;
2959 case TOK_STRUCT:
2960 case TOK_UNION:
2961 struct_decl(&type1, VT_STRUCT);
2962 goto basic_type2;
2964 /* type modifiers */
2965 case TOK_CONST1:
2966 case TOK_CONST2:
2967 case TOK_CONST3:
2968 t |= VT_CONSTANT;
2969 next();
2970 break;
2971 case TOK_VOLATILE1:
2972 case TOK_VOLATILE2:
2973 case TOK_VOLATILE3:
2974 t |= VT_VOLATILE;
2975 next();
2976 break;
2977 case TOK_SIGNED1:
2978 case TOK_SIGNED2:
2979 case TOK_SIGNED3:
2980 typespec_found = 1;
2981 t |= VT_SIGNED;
2982 next();
2983 break;
2984 case TOK_REGISTER:
2985 case TOK_AUTO:
2986 case TOK_RESTRICT1:
2987 case TOK_RESTRICT2:
2988 case TOK_RESTRICT3:
2989 next();
2990 break;
2991 case TOK_UNSIGNED:
2992 t |= VT_UNSIGNED;
2993 next();
2994 typespec_found = 1;
2995 break;
2997 /* storage */
2998 case TOK_EXTERN:
2999 t |= VT_EXTERN;
3000 next();
3001 break;
3002 case TOK_STATIC:
3003 t |= VT_STATIC;
3004 next();
3005 break;
3006 case TOK_TYPEDEF:
3007 t |= VT_TYPEDEF;
3008 next();
3009 break;
3010 case TOK_INLINE1:
3011 case TOK_INLINE2:
3012 case TOK_INLINE3:
3013 t |= VT_INLINE;
3014 next();
3015 break;
3017 /* GNUC attribute */
3018 case TOK_ATTRIBUTE1:
3019 case TOK_ATTRIBUTE2:
3020 parse_attribute(ad);
3021 if (ad->mode) {
3022 u = ad->mode -1;
3023 t = (t & ~VT_BTYPE) | u;
3025 break;
3026 /* GNUC typeof */
3027 case TOK_TYPEOF1:
3028 case TOK_TYPEOF2:
3029 case TOK_TYPEOF3:
3030 next();
3031 parse_expr_type(&type1);
3032 /* remove all storage modifiers except typedef */
3033 type1.t &= ~(VT_STORAGE&~VT_TYPEDEF);
3034 goto basic_type2;
3035 default:
3036 if (typespec_found || typedef_found)
3037 goto the_end;
3038 s = sym_find(tok);
3039 if (!s || !(s->type.t & VT_TYPEDEF))
3040 goto the_end;
3041 typedef_found = 1;
3042 t |= (s->type.t & ~VT_TYPEDEF);
3043 type->ref = s->type.ref;
3044 if (s->r) {
3045 /* get attributes from typedef */
3046 if (0 == ad->aligned)
3047 ad->aligned = FUNC_ALIGN(s->r);
3048 if (0 == ad->func_call)
3049 ad->func_call = FUNC_CALL(s->r);
3050 ad->packed |= FUNC_PACKED(s->r);
3052 next();
3053 typespec_found = 1;
3054 break;
3056 type_found = 1;
3058 the_end:
3059 if ((t & (VT_SIGNED|VT_UNSIGNED)) == (VT_SIGNED|VT_UNSIGNED))
3060 tcc_error("signed and unsigned modifier");
3061 if (tcc_state->char_is_unsigned) {
3062 if ((t & (VT_SIGNED|VT_UNSIGNED|VT_BTYPE)) == VT_BYTE)
3063 t |= VT_UNSIGNED;
3065 t &= ~VT_SIGNED;
3067 /* long is never used as type */
3068 if ((t & VT_BTYPE) == VT_LONG)
3069 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
3070 t = (t & ~VT_BTYPE) | VT_INT;
3071 #else
3072 t = (t & ~VT_BTYPE) | VT_LLONG;
3073 #endif
3074 type->t = t;
3075 return type_found;
3078 /* convert a function parameter type (array to pointer and function to
3079 function pointer) */
3080 static inline void convert_parameter_type(CType *pt)
3082 /* remove const and volatile qualifiers (XXX: const could be used
3083 to indicate a const function parameter */
3084 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
3085 /* array must be transformed to pointer according to ANSI C */
3086 pt->t &= ~VT_ARRAY;
3087 if ((pt->t & VT_BTYPE) == VT_FUNC) {
3088 mk_pointer(pt);
3092 ST_FUNC void parse_asm_str(CString *astr)
3094 skip('(');
3095 /* read the string */
3096 if (tok != TOK_STR)
3097 expect("string constant");
3098 cstr_new(astr);
3099 while (tok == TOK_STR) {
3100 /* XXX: add \0 handling too ? */
3101 cstr_cat(astr, tokc.cstr->data);
3102 next();
3104 cstr_ccat(astr, '\0');
3107 /* Parse an asm label and return the label
3108 * Don't forget to free the CString in the caller! */
3109 static void asm_label_instr(CString *astr)
3111 next();
3112 parse_asm_str(astr);
3113 skip(')');
3114 #ifdef ASM_DEBUG
3115 printf("asm_alias: \"%s\"\n", (char *)astr->data);
3116 #endif
3119 static void post_type(CType *type, AttributeDef *ad)
3121 int n, l, t1, arg_size, align;
3122 Sym **plast, *s, *first;
3123 AttributeDef ad1;
3124 CType pt;
3126 if (tok == '(') {
3127 /* function declaration */
3128 next();
3129 l = 0;
3130 first = NULL;
3131 plast = &first;
3132 arg_size = 0;
3133 if (tok != ')') {
3134 for(;;) {
3135 /* read param name and compute offset */
3136 if (l != FUNC_OLD) {
3137 if (!parse_btype(&pt, &ad1)) {
3138 if (l) {
3139 tcc_error("invalid type");
3140 } else {
3141 l = FUNC_OLD;
3142 goto old_proto;
3145 l = FUNC_NEW;
3146 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
3147 break;
3148 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
3149 if ((pt.t & VT_BTYPE) == VT_VOID)
3150 tcc_error("parameter declared as void");
3151 arg_size += (type_size(&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
3152 } else {
3153 old_proto:
3154 n = tok;
3155 if (n < TOK_UIDENT)
3156 expect("identifier");
3157 pt.t = VT_INT;
3158 next();
3160 convert_parameter_type(&pt);
3161 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
3162 *plast = s;
3163 plast = &s->next;
3164 if (tok == ')')
3165 break;
3166 skip(',');
3167 if (l == FUNC_NEW && tok == TOK_DOTS) {
3168 l = FUNC_ELLIPSIS;
3169 next();
3170 break;
3174 /* if no parameters, then old type prototype */
3175 if (l == 0)
3176 l = FUNC_OLD;
3177 skip(')');
3178 /* NOTE: const is ignored in returned type as it has a special
3179 meaning in gcc / C++ */
3180 type->t &= ~VT_CONSTANT;
3181 /* some ancient pre-K&R C allows a function to return an array
3182 and the array brackets to be put after the arguments, such
3183 that "int c()[]" means something like "int[] c()" */
3184 if (tok == '[') {
3185 next();
3186 skip(']'); /* only handle simple "[]" */
3187 type->t |= VT_PTR;
3189 /* we push a anonymous symbol which will contain the function prototype */
3190 ad->func_args = arg_size;
3191 s = sym_push(SYM_FIELD, type, INT_ATTR(ad), l);
3192 s->next = first;
3193 type->t = VT_FUNC;
3194 type->ref = s;
3195 } else if (tok == '[') {
3196 /* array definition */
3197 next();
3198 if (tok == TOK_RESTRICT1)
3199 next();
3200 n = -1;
3201 t1 = 0;
3202 if (tok != ']') {
3203 if (!local_stack || nocode_wanted)
3204 vpushi(expr_const());
3205 else gexpr();
3206 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3207 n = vtop->c.i;
3208 if (n < 0)
3209 tcc_error("invalid array size");
3210 } else {
3211 if (!is_integer_btype(vtop->type.t & VT_BTYPE))
3212 tcc_error("size of variable length array should be an integer");
3213 t1 = VT_VLA;
3216 skip(']');
3217 /* parse next post type */
3218 post_type(type, ad);
3219 t1 |= type->t & VT_VLA;
3221 if (t1 & VT_VLA) {
3222 loc -= type_size(&int_type, &align);
3223 loc &= -align;
3224 n = loc;
3226 vla_runtime_type_size(type, &align);
3227 gen_op('*');
3228 vset(&int_type, VT_LOCAL|VT_LVAL, loc);
3229 vswap();
3230 vstore();
3232 if (n != -1)
3233 vpop();
3235 /* we push an anonymous symbol which will contain the array
3236 element type */
3237 s = sym_push(SYM_FIELD, type, 0, n);
3238 type->t = (t1 ? VT_VLA : VT_ARRAY) | VT_PTR;
3239 type->ref = s;
3243 /* Parse a type declaration (except basic type), and return the type
3244 in 'type'. 'td' is a bitmask indicating which kind of type decl is
3245 expected. 'type' should contain the basic type. 'ad' is the
3246 attribute definition of the basic type. It can be modified by
3247 type_decl().
3249 static void type_decl(CType *type, AttributeDef *ad, int *v, int td)
3251 Sym *s;
3252 CType type1, *type2;
3253 int qualifiers, storage;
3255 while (tok == '*') {
3256 qualifiers = 0;
3257 redo:
3258 next();
3259 switch(tok) {
3260 case TOK_CONST1:
3261 case TOK_CONST2:
3262 case TOK_CONST3:
3263 qualifiers |= VT_CONSTANT;
3264 goto redo;
3265 case TOK_VOLATILE1:
3266 case TOK_VOLATILE2:
3267 case TOK_VOLATILE3:
3268 qualifiers |= VT_VOLATILE;
3269 goto redo;
3270 case TOK_RESTRICT1:
3271 case TOK_RESTRICT2:
3272 case TOK_RESTRICT3:
3273 goto redo;
3275 mk_pointer(type);
3276 type->t |= qualifiers;
3279 /* XXX: clarify attribute handling */
3280 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3281 parse_attribute(ad);
3283 /* recursive type */
3284 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
3285 type1.t = 0; /* XXX: same as int */
3286 if (tok == '(') {
3287 next();
3288 /* XXX: this is not correct to modify 'ad' at this point, but
3289 the syntax is not clear */
3290 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3291 parse_attribute(ad);
3292 type_decl(&type1, ad, v, td);
3293 skip(')');
3294 } else {
3295 /* type identifier */
3296 if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
3297 *v = tok;
3298 next();
3299 } else {
3300 if (!(td & TYPE_ABSTRACT))
3301 expect("identifier");
3302 *v = 0;
3305 storage = type->t & VT_STORAGE;
3306 type->t &= ~VT_STORAGE;
3307 post_type(type, ad);
3308 type->t |= storage;
3309 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3310 parse_attribute(ad);
3312 if (!type1.t)
3313 return;
3314 /* append type at the end of type1 */
3315 type2 = &type1;
3316 for(;;) {
3317 s = type2->ref;
3318 type2 = &s->type;
3319 if (!type2->t) {
3320 *type2 = *type;
3321 break;
3324 *type = type1;
3327 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
3328 ST_FUNC int lvalue_type(int t)
3330 int bt, r;
3331 r = VT_LVAL;
3332 bt = t & VT_BTYPE;
3333 if (bt == VT_BYTE || bt == VT_BOOL)
3334 r |= VT_LVAL_BYTE;
3335 else if (bt == VT_SHORT)
3336 r |= VT_LVAL_SHORT;
3337 else
3338 return r;
3339 if (t & VT_UNSIGNED)
3340 r |= VT_LVAL_UNSIGNED;
3341 return r;
3344 /* indirection with full error checking and bound check */
3345 ST_FUNC void indir(void)
3347 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
3348 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
3349 return;
3350 expect("pointer");
3352 if ((vtop->r & VT_LVAL) && !nocode_wanted)
3353 gv(RC_INT);
3354 vtop->type = *pointed_type(&vtop->type);
3355 /* Arrays and functions are never lvalues */
3356 if (!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_VLA)
3357 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
3358 vtop->r |= lvalue_type(vtop->type.t);
3359 /* if bound checking, the referenced pointer must be checked */
3360 #ifdef CONFIG_TCC_BCHECK
3361 if (tcc_state->do_bounds_check)
3362 vtop->r |= VT_MUSTBOUND;
3363 #endif
3367 /* pass a parameter to a function and do type checking and casting */
3368 static void gfunc_param_typed(Sym *func, Sym *arg)
3370 int func_type;
3371 CType type;
3373 func_type = func->c;
3374 if (func_type == FUNC_OLD ||
3375 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
3376 /* default casting : only need to convert float to double */
3377 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
3378 type.t = VT_DOUBLE;
3379 gen_cast(&type);
3381 } else if (arg == NULL) {
3382 tcc_error("too many arguments to function");
3383 } else {
3384 type = arg->type;
3385 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
3386 gen_assign_cast(&type);
3390 /* parse an expression of the form '(type)' or '(expr)' and return its
3391 type */
3392 static void parse_expr_type(CType *type)
3394 int n;
3395 AttributeDef ad;
3397 skip('(');
3398 if (parse_btype(type, &ad)) {
3399 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3400 } else {
3401 expr_type(type);
3403 skip(')');
3406 static void parse_type(CType *type)
3408 AttributeDef ad;
3409 int n;
3411 if (!parse_btype(type, &ad)) {
3412 expect("type");
3414 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3417 static void vpush_tokc(int t)
3419 CType type;
3420 type.t = t;
3421 type.ref = 0;
3422 vsetc(&type, VT_CONST, &tokc);
3425 ST_FUNC void unary(void)
3427 int n, t, align, size, r, sizeof_caller;
3428 CType type;
3429 Sym *s;
3430 AttributeDef ad;
3431 static int in_sizeof = 0;
3433 sizeof_caller = in_sizeof;
3434 in_sizeof = 0;
3435 /* XXX: GCC 2.95.3 does not generate a table although it should be
3436 better here */
3437 tok_next:
3438 switch(tok) {
3439 case TOK_EXTENSION:
3440 next();
3441 goto tok_next;
3442 case TOK_CINT:
3443 case TOK_CCHAR:
3444 case TOK_LCHAR:
3445 vpushi(tokc.i);
3446 next();
3447 break;
3448 case TOK_CUINT:
3449 vpush_tokc(VT_INT | VT_UNSIGNED);
3450 next();
3451 break;
3452 case TOK_CLLONG:
3453 vpush_tokc(VT_LLONG);
3454 next();
3455 break;
3456 case TOK_CULLONG:
3457 vpush_tokc(VT_LLONG | VT_UNSIGNED);
3458 next();
3459 break;
3460 case TOK_CFLOAT:
3461 vpush_tokc(VT_FLOAT);
3462 next();
3463 break;
3464 case TOK_CDOUBLE:
3465 vpush_tokc(VT_DOUBLE);
3466 next();
3467 break;
3468 case TOK_CLDOUBLE:
3469 vpush_tokc(VT_LDOUBLE);
3470 next();
3471 break;
3472 case TOK___FUNCTION__:
3473 if (!gnu_ext)
3474 goto tok_identifier;
3475 /* fall thru */
3476 case TOK___FUNC__:
3478 void *ptr;
3479 int len;
3480 /* special function name identifier */
3481 len = strlen(funcname) + 1;
3482 /* generate char[len] type */
3483 type.t = VT_BYTE;
3484 mk_pointer(&type);
3485 type.t |= VT_ARRAY;
3486 type.ref->c = len;
3487 vpush_ref(&type, data_section, data_section->data_offset, len);
3488 ptr = section_ptr_add(data_section, len);
3489 memcpy(ptr, funcname, len);
3490 next();
3492 break;
3493 case TOK_LSTR:
3494 #ifdef TCC_TARGET_PE
3495 t = VT_SHORT | VT_UNSIGNED;
3496 #else
3497 t = VT_INT;
3498 #endif
3499 goto str_init;
3500 case TOK_STR:
3501 /* string parsing */
3502 t = VT_BYTE;
3503 str_init:
3504 if (tcc_state->warn_write_strings)
3505 t |= VT_CONSTANT;
3506 type.t = t;
3507 mk_pointer(&type);
3508 type.t |= VT_ARRAY;
3509 memset(&ad, 0, sizeof(AttributeDef));
3510 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, NULL, 0);
3511 break;
3512 case '(':
3513 next();
3514 /* cast ? */
3515 if (parse_btype(&type, &ad)) {
3516 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
3517 skip(')');
3518 /* check ISOC99 compound literal */
3519 if (tok == '{') {
3520 /* data is allocated locally by default */
3521 if (global_expr)
3522 r = VT_CONST;
3523 else
3524 r = VT_LOCAL;
3525 /* all except arrays are lvalues */
3526 if (!(type.t & VT_ARRAY))
3527 r |= lvalue_type(type.t);
3528 memset(&ad, 0, sizeof(AttributeDef));
3529 decl_initializer_alloc(&type, &ad, r, 1, 0, NULL, 0);
3530 } else {
3531 if (sizeof_caller) {
3532 vpush(&type);
3533 return;
3535 unary();
3536 gen_cast(&type);
3538 } else if (tok == '{') {
3539 /* save all registers */
3540 save_regs(0);
3541 /* statement expression : we do not accept break/continue
3542 inside as GCC does */
3543 block(NULL, NULL, NULL, NULL, 0, 1);
3544 skip(')');
3545 } else {
3546 gexpr();
3547 skip(')');
3549 break;
3550 case '*':
3551 next();
3552 unary();
3553 indir();
3554 break;
3555 case '&':
3556 next();
3557 unary();
3558 /* functions names must be treated as function pointers,
3559 except for unary '&' and sizeof. Since we consider that
3560 functions are not lvalues, we only have to handle it
3561 there and in function calls. */
3562 /* arrays can also be used although they are not lvalues */
3563 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
3564 !(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
3565 test_lvalue();
3566 mk_pointer(&vtop->type);
3567 gaddrof();
3568 break;
3569 case '!':
3570 next();
3571 unary();
3572 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3573 CType boolean;
3574 boolean.t = VT_BOOL;
3575 gen_cast(&boolean);
3576 vtop->c.i = !vtop->c.i;
3577 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
3578 vtop->c.i = vtop->c.i ^ 1;
3579 else {
3580 save_regs(1);
3581 vseti(VT_JMP, gtst(1, 0));
3583 break;
3584 case '~':
3585 next();
3586 unary();
3587 vpushi(-1);
3588 gen_op('^');
3589 break;
3590 case '+':
3591 next();
3592 /* in order to force cast, we add zero */
3593 unary();
3594 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
3595 tcc_error("pointer not accepted for unary plus");
3596 vpushi(0);
3597 gen_op('+');
3598 break;
3599 case TOK_SIZEOF:
3600 case TOK_ALIGNOF1:
3601 case TOK_ALIGNOF2:
3602 t = tok;
3603 next();
3604 in_sizeof++;
3605 unary_type(&type); // Perform a in_sizeof = 0;
3606 size = type_size(&type, &align);
3607 if (t == TOK_SIZEOF) {
3608 if (!(type.t & VT_VLA)) {
3609 if (size < 0)
3610 tcc_error("sizeof applied to an incomplete type");
3611 vpushs(size);
3612 } else {
3613 vla_runtime_type_size(&type, &align);
3615 } else {
3616 vpushs(align);
3618 vtop->type.t |= VT_UNSIGNED;
3619 break;
3621 case TOK_builtin_types_compatible_p:
3623 CType type1, type2;
3624 next();
3625 skip('(');
3626 parse_type(&type1);
3627 skip(',');
3628 parse_type(&type2);
3629 skip(')');
3630 type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
3631 type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
3632 vpushi(is_compatible_types(&type1, &type2));
3634 break;
3635 case TOK_builtin_constant_p:
3637 int saved_nocode_wanted, res;
3638 next();
3639 skip('(');
3640 saved_nocode_wanted = nocode_wanted;
3641 nocode_wanted = 1;
3642 gexpr();
3643 res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
3644 vpop();
3645 nocode_wanted = saved_nocode_wanted;
3646 skip(')');
3647 vpushi(res);
3649 break;
3650 case TOK_builtin_frame_address:
3652 CType type;
3653 next();
3654 skip('(');
3655 if (tok != TOK_CINT) {
3656 tcc_error("__builtin_frame_address only takes integers");
3658 if (tokc.i != 0) {
3659 tcc_error("TCC only supports __builtin_frame_address(0)");
3661 next();
3662 skip(')');
3663 type.t = VT_VOID;
3664 mk_pointer(&type);
3665 vset(&type, VT_LOCAL, 0);
3667 break;
3668 #ifdef TCC_TARGET_X86_64
3669 case TOK_builtin_va_arg_types:
3671 /* This definition must be synced with stdarg.h */
3672 enum __va_arg_type {
3673 __va_gen_reg, __va_float_reg, __va_stack
3675 CType type;
3676 int bt;
3677 next();
3678 skip('(');
3679 parse_type(&type);
3680 skip(')');
3681 bt = type.t & VT_BTYPE;
3682 if (bt == VT_STRUCT || bt == VT_LDOUBLE) {
3683 vpushi(__va_stack);
3684 } else if (bt == VT_FLOAT || bt == VT_DOUBLE) {
3685 vpushi(__va_float_reg);
3686 } else {
3687 vpushi(__va_gen_reg);
3690 break;
3691 #endif
3692 case TOK_INC:
3693 case TOK_DEC:
3694 t = tok;
3695 next();
3696 unary();
3697 inc(0, t);
3698 break;
3699 case '-':
3700 next();
3701 vpushi(0);
3702 unary();
3703 gen_op('-');
3704 break;
3705 case TOK_LAND:
3706 if (!gnu_ext)
3707 goto tok_identifier;
3708 next();
3709 /* allow to take the address of a label */
3710 if (tok < TOK_UIDENT)
3711 expect("label identifier");
3712 s = label_find(tok);
3713 if (!s) {
3714 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
3715 } else {
3716 if (s->r == LABEL_DECLARED)
3717 s->r = LABEL_FORWARD;
3719 if (!s->type.t) {
3720 s->type.t = VT_VOID;
3721 mk_pointer(&s->type);
3722 s->type.t |= VT_STATIC;
3724 vset(&s->type, VT_CONST | VT_SYM, 0);
3725 vtop->sym = s;
3726 next();
3727 break;
3729 // special qnan , snan and infinity values
3730 case TOK___NAN__:
3731 vpush64(VT_DOUBLE, 0x7ff8000000000000ULL);
3732 next();
3733 break;
3734 case TOK___SNAN__:
3735 vpush64(VT_DOUBLE, 0x7ff0000000000001ULL);
3736 next();
3737 break;
3738 case TOK___INF__:
3739 vpush64(VT_DOUBLE, 0x7ff0000000000000ULL);
3740 next();
3741 break;
3743 default:
3744 tok_identifier:
3745 t = tok;
3746 next();
3747 if (t < TOK_UIDENT)
3748 expect("identifier");
3749 s = sym_find(t);
3750 if (!s) {
3751 if (tok != '(')
3752 tcc_error("'%s' undeclared", get_tok_str(t, NULL));
3753 /* for simple function calls, we tolerate undeclared
3754 external reference to int() function */
3755 if (tcc_state->warn_implicit_function_declaration)
3756 tcc_warning("implicit declaration of function '%s'",
3757 get_tok_str(t, NULL));
3758 s = external_global_sym(t, &func_old_type, 0);
3760 if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
3761 (VT_STATIC | VT_INLINE | VT_FUNC)) {
3762 /* if referencing an inline function, then we generate a
3763 symbol to it if not already done. It will have the
3764 effect to generate code for it at the end of the
3765 compilation unit. Inline function as always
3766 generated in the text section. */
3767 if (!s->c)
3768 put_extern_sym(s, text_section, 0, 0);
3769 r = VT_SYM | VT_CONST;
3770 } else {
3771 r = s->r;
3773 vset(&s->type, r, s->c);
3774 /* if forward reference, we must point to s */
3775 if (vtop->r & VT_SYM) {
3776 vtop->sym = s;
3777 vtop->c.ul = 0;
3779 break;
3782 /* post operations */
3783 while (1) {
3784 if (tok == TOK_INC || tok == TOK_DEC) {
3785 inc(1, tok);
3786 next();
3787 } else if (tok == '.' || tok == TOK_ARROW) {
3788 int qualifiers;
3789 /* field */
3790 if (tok == TOK_ARROW)
3791 indir();
3792 qualifiers = vtop->type.t & (VT_CONSTANT | VT_VOLATILE);
3793 test_lvalue();
3794 gaddrof();
3795 next();
3796 /* expect pointer on structure */
3797 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
3798 expect("struct or union");
3799 s = vtop->type.ref;
3800 /* find field */
3801 tok |= SYM_FIELD;
3802 while ((s = s->next) != NULL) {
3803 if (s->v == tok)
3804 break;
3806 if (!s)
3807 tcc_error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, NULL));
3808 /* add field offset to pointer */
3809 vtop->type = char_pointer_type; /* change type to 'char *' */
3810 vpushi(s->c);
3811 gen_op('+');
3812 /* change type to field type, and set to lvalue */
3813 vtop->type = s->type;
3814 vtop->type.t |= qualifiers;
3815 /* an array is never an lvalue */
3816 if (!(vtop->type.t & VT_ARRAY)) {
3817 vtop->r |= lvalue_type(vtop->type.t);
3818 #ifdef CONFIG_TCC_BCHECK
3819 /* if bound checking, the referenced pointer must be checked */
3820 if (tcc_state->do_bounds_check)
3821 vtop->r |= VT_MUSTBOUND;
3822 #endif
3824 next();
3825 } else if (tok == '[') {
3826 next();
3827 gexpr();
3828 gen_op('+');
3829 indir();
3830 skip(']');
3831 } else if (tok == '(') {
3832 SValue ret;
3833 Sym *sa;
3834 int nb_args;
3836 /* function call */
3837 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
3838 /* pointer test (no array accepted) */
3839 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
3840 vtop->type = *pointed_type(&vtop->type);
3841 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
3842 goto error_func;
3843 } else {
3844 error_func:
3845 expect("function pointer");
3847 } else {
3848 vtop->r &= ~VT_LVAL; /* no lvalue */
3850 /* get return type */
3851 s = vtop->type.ref;
3852 next();
3853 sa = s->next; /* first parameter */
3854 nb_args = 0;
3855 ret.r2 = VT_CONST;
3856 /* compute first implicit argument if a structure is returned */
3857 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
3858 /* get some space for the returned structure */
3859 size = type_size(&s->type, &align);
3860 loc = (loc - size) & -align;
3861 ret.type = s->type;
3862 ret.r = VT_LOCAL | VT_LVAL;
3863 /* pass it as 'int' to avoid structure arg passing
3864 problems */
3865 vseti(VT_LOCAL, loc);
3866 ret.c = vtop->c;
3867 nb_args++;
3868 } else {
3869 ret.type = s->type;
3870 /* return in register */
3871 if (is_float(ret.type.t)) {
3872 ret.r = reg_fret(ret.type.t);
3873 } else {
3874 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
3875 ret.r2 = REG_LRET;
3876 ret.r = REG_IRET;
3878 ret.c.i = 0;
3880 if (tok != ')') {
3881 for(;;) {
3882 expr_eq();
3883 gfunc_param_typed(s, sa);
3884 nb_args++;
3885 if (sa)
3886 sa = sa->next;
3887 if (tok == ')')
3888 break;
3889 skip(',');
3892 if (sa)
3893 tcc_error("too few arguments to function");
3894 skip(')');
3895 if (!nocode_wanted) {
3896 gfunc_call(nb_args);
3897 } else {
3898 vtop -= (nb_args + 1);
3900 /* return value */
3901 vsetc(&ret.type, ret.r, &ret.c);
3902 vtop->r2 = ret.r2;
3903 } else {
3904 break;
3909 ST_FUNC void expr_prod(void)
3911 int t;
3913 unary();
3914 while (tok == '*' || tok == '/' || tok == '%') {
3915 t = tok;
3916 next();
3917 unary();
3918 gen_op(t);
3922 ST_FUNC void expr_sum(void)
3924 int t;
3926 expr_prod();
3927 while (tok == '+' || tok == '-') {
3928 t = tok;
3929 next();
3930 expr_prod();
3931 gen_op(t);
3935 static void expr_shift(void)
3937 int t;
3939 expr_sum();
3940 while (tok == TOK_SHL || tok == TOK_SAR) {
3941 t = tok;
3942 next();
3943 expr_sum();
3944 gen_op(t);
3948 static void expr_cmp(void)
3950 int t;
3952 expr_shift();
3953 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
3954 tok == TOK_ULT || tok == TOK_UGE) {
3955 t = tok;
3956 next();
3957 expr_shift();
3958 gen_op(t);
3962 static void expr_cmpeq(void)
3964 int t;
3966 expr_cmp();
3967 while (tok == TOK_EQ || tok == TOK_NE) {
3968 t = tok;
3969 next();
3970 expr_cmp();
3971 gen_op(t);
3975 static void expr_and(void)
3977 expr_cmpeq();
3978 while (tok == '&') {
3979 next();
3980 expr_cmpeq();
3981 gen_op('&');
3985 static void expr_xor(void)
3987 expr_and();
3988 while (tok == '^') {
3989 next();
3990 expr_and();
3991 gen_op('^');
3995 static void expr_or(void)
3997 expr_xor();
3998 while (tok == '|') {
3999 next();
4000 expr_xor();
4001 gen_op('|');
4005 /* XXX: fix this mess */
4006 static void expr_land_const(void)
4008 expr_or();
4009 while (tok == TOK_LAND) {
4010 next();
4011 expr_or();
4012 gen_op(TOK_LAND);
4016 /* XXX: fix this mess */
4017 static void expr_lor_const(void)
4019 expr_land_const();
4020 while (tok == TOK_LOR) {
4021 next();
4022 expr_land_const();
4023 gen_op(TOK_LOR);
4027 /* only used if non constant */
4028 static void expr_land(void)
4030 int t;
4032 expr_or();
4033 if (tok == TOK_LAND) {
4034 t = 0;
4035 save_regs(1);
4036 for(;;) {
4037 t = gtst(1, t);
4038 if (tok != TOK_LAND) {
4039 vseti(VT_JMPI, t);
4040 break;
4042 next();
4043 expr_or();
4048 static void expr_lor(void)
4050 int t;
4052 expr_land();
4053 if (tok == TOK_LOR) {
4054 t = 0;
4055 save_regs(1);
4056 for(;;) {
4057 t = gtst(0, t);
4058 if (tok != TOK_LOR) {
4059 vseti(VT_JMP, t);
4060 break;
4062 next();
4063 expr_land();
4068 /* XXX: better constant handling */
4069 static void expr_cond(void)
4071 int tt, u, r1, r2, rc, t1, t2, bt1, bt2;
4072 SValue sv;
4073 CType type, type1, type2;
4075 if (const_wanted) {
4076 expr_lor_const();
4077 if (tok == '?') {
4078 CType boolean;
4079 int c;
4080 boolean.t = VT_BOOL;
4081 vdup();
4082 gen_cast(&boolean);
4083 c = vtop->c.i;
4084 vpop();
4085 next();
4086 if (tok != ':' || !gnu_ext) {
4087 vpop();
4088 gexpr();
4090 if (!c)
4091 vpop();
4092 skip(':');
4093 expr_cond();
4094 if (c)
4095 vpop();
4097 } else {
4098 expr_lor();
4099 if (tok == '?') {
4100 next();
4101 if (vtop != vstack) {
4102 /* needed to avoid having different registers saved in
4103 each branch */
4104 if (is_float(vtop->type.t)) {
4105 rc = RC_FLOAT;
4106 #ifdef TCC_TARGET_X86_64
4107 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
4108 rc = RC_ST0;
4110 #endif
4112 else
4113 rc = RC_INT;
4114 gv(rc);
4115 save_regs(1);
4117 if (tok == ':' && gnu_ext) {
4118 gv_dup();
4119 tt = gtst(1, 0);
4120 } else {
4121 tt = gtst(1, 0);
4122 gexpr();
4124 type1 = vtop->type;
4125 sv = *vtop; /* save value to handle it later */
4126 vtop--; /* no vpop so that FP stack is not flushed */
4127 skip(':');
4128 u = gjmp(0);
4129 gsym(tt);
4130 expr_cond();
4131 type2 = vtop->type;
4133 t1 = type1.t;
4134 bt1 = t1 & VT_BTYPE;
4135 t2 = type2.t;
4136 bt2 = t2 & VT_BTYPE;
4137 /* cast operands to correct type according to ISOC rules */
4138 if (is_float(bt1) || is_float(bt2)) {
4139 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
4140 type.t = VT_LDOUBLE;
4141 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
4142 type.t = VT_DOUBLE;
4143 } else {
4144 type.t = VT_FLOAT;
4146 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
4147 /* cast to biggest op */
4148 type.t = VT_LLONG;
4149 /* convert to unsigned if it does not fit in a long long */
4150 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
4151 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
4152 type.t |= VT_UNSIGNED;
4153 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
4154 /* If one is a null ptr constant the result type
4155 is the other. */
4156 if (is_null_pointer (vtop))
4157 type = type1;
4158 else if (is_null_pointer (&sv))
4159 type = type2;
4160 /* XXX: test pointer compatibility, C99 has more elaborate
4161 rules here. */
4162 else
4163 type = type1;
4164 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
4165 /* XXX: test function pointer compatibility */
4166 type = bt1 == VT_FUNC ? type1 : type2;
4167 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
4168 /* XXX: test structure compatibility */
4169 type = bt1 == VT_STRUCT ? type1 : type2;
4170 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
4171 /* NOTE: as an extension, we accept void on only one side */
4172 type.t = VT_VOID;
4173 } else {
4174 /* integer operations */
4175 type.t = VT_INT;
4176 /* convert to unsigned if it does not fit in an integer */
4177 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
4178 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
4179 type.t |= VT_UNSIGNED;
4182 /* now we convert second operand */
4183 gen_cast(&type);
4184 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4185 gaddrof();
4186 rc = RC_INT;
4187 if (is_float(type.t)) {
4188 rc = RC_FLOAT;
4189 #ifdef TCC_TARGET_X86_64
4190 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
4191 rc = RC_ST0;
4193 #endif
4194 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
4195 /* for long longs, we use fixed registers to avoid having
4196 to handle a complicated move */
4197 rc = RC_IRET;
4200 r2 = gv(rc);
4201 /* this is horrible, but we must also convert first
4202 operand */
4203 tt = gjmp(0);
4204 gsym(u);
4205 /* put again first value and cast it */
4206 *vtop = sv;
4207 gen_cast(&type);
4208 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4209 gaddrof();
4210 r1 = gv(rc);
4211 move_reg(r2, r1);
4212 vtop->r = r2;
4213 gsym(tt);
4218 static void expr_eq(void)
4220 int t;
4222 expr_cond();
4223 if (tok == '=' ||
4224 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
4225 tok == TOK_A_XOR || tok == TOK_A_OR ||
4226 tok == TOK_A_SHL || tok == TOK_A_SAR) {
4227 test_lvalue();
4228 t = tok;
4229 next();
4230 if (t == '=') {
4231 expr_eq();
4232 } else {
4233 vdup();
4234 expr_eq();
4235 gen_op(t & 0x7f);
4237 vstore();
4241 ST_FUNC void gexpr(void)
4243 while (1) {
4244 expr_eq();
4245 if (tok != ',')
4246 break;
4247 vpop();
4248 next();
4252 /* parse an expression and return its type without any side effect. */
4253 static void expr_type(CType *type)
4255 int saved_nocode_wanted;
4257 saved_nocode_wanted = nocode_wanted;
4258 nocode_wanted = 1;
4259 gexpr();
4260 *type = vtop->type;
4261 vpop();
4262 nocode_wanted = saved_nocode_wanted;
4265 /* parse a unary expression and return its type without any side
4266 effect. */
4267 static void unary_type(CType *type)
4269 int a;
4271 a = nocode_wanted;
4272 nocode_wanted = 1;
4273 unary();
4274 *type = vtop->type;
4275 vpop();
4276 nocode_wanted = a;
4279 /* parse a constant expression and return value in vtop. */
4280 static void expr_const1(void)
4282 int a;
4283 a = const_wanted;
4284 const_wanted = 1;
4285 expr_cond();
4286 const_wanted = a;
4289 /* parse an integer constant and return its value. */
4290 ST_FUNC int expr_const(void)
4292 int c;
4293 expr_const1();
4294 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
4295 expect("constant expression");
4296 c = vtop->c.i;
4297 vpop();
4298 return c;
4301 /* return the label token if current token is a label, otherwise
4302 return zero */
4303 static int is_label(void)
4305 int last_tok;
4307 /* fast test first */
4308 if (tok < TOK_UIDENT)
4309 return 0;
4310 /* no need to save tokc because tok is an identifier */
4311 last_tok = tok;
4312 next();
4313 if (tok == ':') {
4314 next();
4315 return last_tok;
4316 } else {
4317 unget_tok(last_tok);
4318 return 0;
4322 static void label_or_decl(int l)
4324 int last_tok;
4326 /* fast test first */
4327 if (tok >= TOK_UIDENT)
4329 /* no need to save tokc because tok is an identifier */
4330 last_tok = tok;
4331 next();
4332 if (tok == ':') {
4333 unget_tok(last_tok);
4334 return;
4336 unget_tok(last_tok);
4338 decl(l);
4341 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
4342 int case_reg, int is_expr)
4344 int a, b, c, d;
4345 Sym *s;
4347 /* generate line number info */
4348 if (tcc_state->do_debug &&
4349 (last_line_num != file->line_num || last_ind != ind)) {
4350 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
4351 last_ind = ind;
4352 last_line_num = file->line_num;
4355 if (is_expr) {
4356 /* default return value is (void) */
4357 vpushi(0);
4358 vtop->type.t = VT_VOID;
4361 if (tok == TOK_IF) {
4362 /* if test */
4363 next();
4364 skip('(');
4365 gexpr();
4366 skip(')');
4367 a = gtst(1, 0);
4368 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4369 c = tok;
4370 if (c == TOK_ELSE) {
4371 next();
4372 d = gjmp(0);
4373 gsym(a);
4374 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4375 gsym(d); /* patch else jmp */
4376 } else
4377 gsym(a);
4378 } else if (tok == TOK_WHILE) {
4379 next();
4380 d = ind;
4381 skip('(');
4382 gexpr();
4383 skip(')');
4384 a = gtst(1, 0);
4385 b = 0;
4386 block(&a, &b, case_sym, def_sym, case_reg, 0);
4387 gjmp_addr(d);
4388 gsym(a);
4389 gsym_addr(b, d);
4390 } else if (tok == '{') {
4391 Sym *llabel;
4393 next();
4394 /* record local declaration stack position */
4395 s = local_stack;
4396 llabel = local_label_stack;
4397 /* handle local labels declarations */
4398 if (tok == TOK_LABEL) {
4399 next();
4400 for(;;) {
4401 if (tok < TOK_UIDENT)
4402 expect("label identifier");
4403 label_push(&local_label_stack, tok, LABEL_DECLARED);
4404 next();
4405 if (tok == ',') {
4406 next();
4407 } else {
4408 skip(';');
4409 break;
4413 while (tok != '}') {
4414 label_or_decl(VT_LOCAL);
4415 if (tok != '}') {
4416 if (is_expr)
4417 vpop();
4418 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
4421 /* pop locally defined labels */
4422 label_pop(&local_label_stack, llabel);
4423 if(is_expr) {
4424 /* XXX: this solution makes only valgrind happy...
4425 triggered by gcc.c-torture/execute/20000917-1.c */
4426 Sym *p;
4427 switch(vtop->type.t & VT_BTYPE) {
4428 case VT_PTR:
4429 case VT_STRUCT:
4430 case VT_ENUM:
4431 case VT_FUNC:
4432 for(p=vtop->type.ref;p;p=p->prev)
4433 if(p->prev==s)
4434 tcc_error("unsupported expression type");
4437 /* pop locally defined symbols */
4438 sym_pop(&local_stack, s);
4439 next();
4440 } else if (tok == TOK_RETURN) {
4441 next();
4442 if (tok != ';') {
4443 gexpr();
4444 gen_assign_cast(&func_vt);
4445 if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
4446 CType type;
4447 /* if returning structure, must copy it to implicit
4448 first pointer arg location */
4449 #ifdef TCC_ARM_EABI
4450 int align, size;
4451 size = type_size(&func_vt,&align);
4452 if(size <= 4)
4454 if((vtop->r != (VT_LOCAL | VT_LVAL) || (vtop->c.i & 3))
4455 && (align & 3))
4457 int addr;
4458 loc = (loc - size) & -4;
4459 addr = loc;
4460 type = func_vt;
4461 vset(&type, VT_LOCAL | VT_LVAL, addr);
4462 vswap();
4463 vstore();
4464 vset(&int_type, VT_LOCAL | VT_LVAL, addr);
4466 vtop->type = int_type;
4467 gv(RC_IRET);
4468 } else {
4469 #endif
4470 type = func_vt;
4471 mk_pointer(&type);
4472 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
4473 indir();
4474 vswap();
4475 /* copy structure value to pointer */
4476 vstore();
4477 #ifdef TCC_ARM_EABI
4479 #endif
4480 } else if (is_float(func_vt.t)) {
4481 gv(rc_fret(func_vt.t));
4482 } else {
4483 gv(RC_IRET);
4485 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
4487 skip(';');
4488 rsym = gjmp(rsym); /* jmp */
4489 } else if (tok == TOK_BREAK) {
4490 /* compute jump */
4491 if (!bsym)
4492 tcc_error("cannot break");
4493 *bsym = gjmp(*bsym);
4494 next();
4495 skip(';');
4496 } else if (tok == TOK_CONTINUE) {
4497 /* compute jump */
4498 if (!csym)
4499 tcc_error("cannot continue");
4500 *csym = gjmp(*csym);
4501 next();
4502 skip(';');
4503 } else if (tok == TOK_FOR) {
4504 int e;
4505 next();
4506 skip('(');
4507 s = local_stack;
4508 if (tok != ';') {
4509 /* c99 for-loop init decl? */
4510 if (!decl0(VT_LOCAL, 1)) {
4511 /* no, regular for-loop init expr */
4512 gexpr();
4513 vpop();
4516 skip(';');
4517 d = ind;
4518 c = ind;
4519 a = 0;
4520 b = 0;
4521 if (tok != ';') {
4522 gexpr();
4523 a = gtst(1, 0);
4525 skip(';');
4526 if (tok != ')') {
4527 e = gjmp(0);
4528 c = ind;
4529 gexpr();
4530 vpop();
4531 gjmp_addr(d);
4532 gsym(e);
4534 skip(')');
4535 block(&a, &b, case_sym, def_sym, case_reg, 0);
4536 gjmp_addr(c);
4537 gsym(a);
4538 gsym_addr(b, c);
4539 sym_pop(&local_stack, s);
4540 } else
4541 if (tok == TOK_DO) {
4542 next();
4543 a = 0;
4544 b = 0;
4545 d = ind;
4546 block(&a, &b, case_sym, def_sym, case_reg, 0);
4547 skip(TOK_WHILE);
4548 skip('(');
4549 gsym(b);
4550 gexpr();
4551 c = gtst(0, 0);
4552 gsym_addr(c, d);
4553 skip(')');
4554 gsym(a);
4555 skip(';');
4556 } else
4557 if (tok == TOK_SWITCH) {
4558 next();
4559 skip('(');
4560 gexpr();
4561 /* XXX: other types than integer */
4562 case_reg = gv(RC_INT);
4563 vpop();
4564 skip(')');
4565 a = 0;
4566 b = gjmp(0); /* jump to first case */
4567 c = 0;
4568 block(&a, csym, &b, &c, case_reg, 0);
4569 /* if no default, jmp after switch */
4570 if (c == 0)
4571 c = ind;
4572 /* default label */
4573 gsym_addr(b, c);
4574 /* break label */
4575 gsym(a);
4576 } else
4577 if (tok == TOK_CASE) {
4578 int v1, v2;
4579 if (!case_sym)
4580 expect("switch");
4581 next();
4582 v1 = expr_const();
4583 v2 = v1;
4584 if (gnu_ext && tok == TOK_DOTS) {
4585 next();
4586 v2 = expr_const();
4587 if (v2 < v1)
4588 tcc_warning("empty case range");
4590 /* since a case is like a label, we must skip it with a jmp */
4591 b = gjmp(0);
4592 gsym(*case_sym);
4593 vseti(case_reg, 0);
4594 vpushi(v1);
4595 if (v1 == v2) {
4596 gen_op(TOK_EQ);
4597 *case_sym = gtst(1, 0);
4598 } else {
4599 gen_op(TOK_GE);
4600 *case_sym = gtst(1, 0);
4601 vseti(case_reg, 0);
4602 vpushi(v2);
4603 gen_op(TOK_LE);
4604 *case_sym = gtst(1, *case_sym);
4606 gsym(b);
4607 skip(':');
4608 is_expr = 0;
4609 goto block_after_label;
4610 } else
4611 if (tok == TOK_DEFAULT) {
4612 next();
4613 skip(':');
4614 if (!def_sym)
4615 expect("switch");
4616 if (*def_sym)
4617 tcc_error("too many 'default'");
4618 *def_sym = ind;
4619 is_expr = 0;
4620 goto block_after_label;
4621 } else
4622 if (tok == TOK_GOTO) {
4623 next();
4624 if (tok == '*' && gnu_ext) {
4625 /* computed goto */
4626 next();
4627 gexpr();
4628 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
4629 expect("pointer");
4630 ggoto();
4631 } else if (tok >= TOK_UIDENT) {
4632 s = label_find(tok);
4633 /* put forward definition if needed */
4634 if (!s) {
4635 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
4636 } else {
4637 if (s->r == LABEL_DECLARED)
4638 s->r = LABEL_FORWARD;
4640 /* label already defined */
4641 if (s->r & LABEL_FORWARD)
4642 s->jnext = gjmp(s->jnext);
4643 else
4644 gjmp_addr(s->jnext);
4645 next();
4646 } else {
4647 expect("label identifier");
4649 skip(';');
4650 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
4651 asm_instr();
4652 } else {
4653 b = is_label();
4654 if (b) {
4655 /* label case */
4656 s = label_find(b);
4657 if (s) {
4658 if (s->r == LABEL_DEFINED)
4659 tcc_error("duplicate label '%s'", get_tok_str(s->v, NULL));
4660 gsym(s->jnext);
4661 s->r = LABEL_DEFINED;
4662 } else {
4663 s = label_push(&global_label_stack, b, LABEL_DEFINED);
4665 s->jnext = ind;
4666 /* we accept this, but it is a mistake */
4667 block_after_label:
4668 if (tok == '}') {
4669 tcc_warning("deprecated use of label at end of compound statement");
4670 } else {
4671 if (is_expr)
4672 vpop();
4673 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
4675 } else {
4676 /* expression case */
4677 if (tok != ';') {
4678 if (is_expr) {
4679 vpop();
4680 gexpr();
4681 } else {
4682 gexpr();
4683 vpop();
4686 skip(';');
4691 /* t is the array or struct type. c is the array or struct
4692 address. cur_index/cur_field is the pointer to the current
4693 value. 'size_only' is true if only size info is needed (only used
4694 in arrays) */
4695 static void decl_designator(CType *type, Section *sec, unsigned long c,
4696 int *cur_index, Sym **cur_field,
4697 int size_only)
4699 Sym *s, *f;
4700 int notfirst, index, index_last, align, l, nb_elems, elem_size;
4701 CType type1;
4703 notfirst = 0;
4704 elem_size = 0;
4705 nb_elems = 1;
4706 if (gnu_ext && (l = is_label()) != 0)
4707 goto struct_field;
4708 while (tok == '[' || tok == '.') {
4709 if (tok == '[') {
4710 if (!(type->t & VT_ARRAY))
4711 expect("array type");
4712 s = type->ref;
4713 next();
4714 index = expr_const();
4715 if (index < 0 || (s->c >= 0 && index >= s->c))
4716 expect("invalid index");
4717 if (tok == TOK_DOTS && gnu_ext) {
4718 next();
4719 index_last = expr_const();
4720 if (index_last < 0 ||
4721 (s->c >= 0 && index_last >= s->c) ||
4722 index_last < index)
4723 expect("invalid index");
4724 } else {
4725 index_last = index;
4727 skip(']');
4728 if (!notfirst)
4729 *cur_index = index_last;
4730 type = pointed_type(type);
4731 elem_size = type_size(type, &align);
4732 c += index * elem_size;
4733 /* NOTE: we only support ranges for last designator */
4734 nb_elems = index_last - index + 1;
4735 if (nb_elems != 1) {
4736 notfirst = 1;
4737 break;
4739 } else {
4740 next();
4741 l = tok;
4742 next();
4743 struct_field:
4744 if ((type->t & VT_BTYPE) != VT_STRUCT)
4745 expect("struct/union type");
4746 s = type->ref;
4747 l |= SYM_FIELD;
4748 f = s->next;
4749 while (f) {
4750 if (f->v == l)
4751 break;
4752 f = f->next;
4754 if (!f)
4755 expect("field");
4756 if (!notfirst)
4757 *cur_field = f;
4758 /* XXX: fix this mess by using explicit storage field */
4759 type1 = f->type;
4760 type1.t |= (type->t & ~VT_TYPE);
4761 type = &type1;
4762 c += f->c;
4764 notfirst = 1;
4766 if (notfirst) {
4767 if (tok == '=') {
4768 next();
4769 } else {
4770 if (!gnu_ext)
4771 expect("=");
4773 } else {
4774 if (type->t & VT_ARRAY) {
4775 index = *cur_index;
4776 type = pointed_type(type);
4777 c += index * type_size(type, &align);
4778 } else {
4779 f = *cur_field;
4780 if (!f)
4781 tcc_error("too many field init");
4782 /* XXX: fix this mess by using explicit storage field */
4783 type1 = f->type;
4784 type1.t |= (type->t & ~VT_TYPE);
4785 type = &type1;
4786 c += f->c;
4789 decl_initializer(type, sec, c, 0, size_only);
4791 /* XXX: make it more general */
4792 if (!size_only && nb_elems > 1) {
4793 unsigned long c_end;
4794 uint8_t *src, *dst;
4795 int i;
4797 if (!sec)
4798 tcc_error("range init not supported yet for dynamic storage");
4799 c_end = c + nb_elems * elem_size;
4800 if (c_end > sec->data_allocated)
4801 section_realloc(sec, c_end);
4802 src = sec->data + c;
4803 dst = src;
4804 for(i = 1; i < nb_elems; i++) {
4805 dst += elem_size;
4806 memcpy(dst, src, elem_size);
4811 #define EXPR_VAL 0
4812 #define EXPR_CONST 1
4813 #define EXPR_ANY 2
4815 /* store a value or an expression directly in global data or in local array */
4816 static void init_putv(CType *type, Section *sec, unsigned long c,
4817 int v, int expr_type)
4819 int saved_global_expr, bt, bit_pos, bit_size;
4820 void *ptr;
4821 unsigned long long bit_mask;
4822 CType dtype;
4824 switch(expr_type) {
4825 case EXPR_VAL:
4826 vpushi(v);
4827 break;
4828 case EXPR_CONST:
4829 /* compound literals must be allocated globally in this case */
4830 saved_global_expr = global_expr;
4831 global_expr = 1;
4832 expr_const1();
4833 global_expr = saved_global_expr;
4834 /* NOTE: symbols are accepted */
4835 if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
4836 tcc_error("initializer element is not constant");
4837 break;
4838 case EXPR_ANY:
4839 expr_eq();
4840 break;
4843 dtype = *type;
4844 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
4846 if (sec) {
4847 /* XXX: not portable */
4848 /* XXX: generate error if incorrect relocation */
4849 gen_assign_cast(&dtype);
4850 bt = type->t & VT_BTYPE;
4851 /* we'll write at most 12 bytes */
4852 if (c + 12 > sec->data_allocated) {
4853 section_realloc(sec, c + 12);
4855 ptr = sec->data + c;
4856 /* XXX: make code faster ? */
4857 if (!(type->t & VT_BITFIELD)) {
4858 bit_pos = 0;
4859 bit_size = 32;
4860 bit_mask = -1LL;
4861 } else {
4862 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
4863 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
4864 bit_mask = (1LL << bit_size) - 1;
4866 if ((vtop->r & VT_SYM) &&
4867 (bt == VT_BYTE ||
4868 bt == VT_SHORT ||
4869 bt == VT_DOUBLE ||
4870 bt == VT_LDOUBLE ||
4871 bt == VT_LLONG ||
4872 (bt == VT_INT && bit_size != 32)))
4873 tcc_error("initializer element is not computable at load time");
4874 switch(bt) {
4875 case VT_BOOL:
4876 vtop->c.i = (vtop->c.i != 0);
4877 case VT_BYTE:
4878 *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
4879 break;
4880 case VT_SHORT:
4881 *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
4882 break;
4883 case VT_DOUBLE:
4884 *(double *)ptr = vtop->c.d;
4885 break;
4886 case VT_LDOUBLE:
4887 *(long double *)ptr = vtop->c.ld;
4888 break;
4889 case VT_LLONG:
4890 *(long long *)ptr |= (vtop->c.ll & bit_mask) << bit_pos;
4891 break;
4892 default:
4893 if (vtop->r & VT_SYM) {
4894 greloc(sec, vtop->sym, c, R_DATA_PTR);
4896 *(int *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
4897 break;
4899 vtop--;
4900 } else {
4901 vset(&dtype, VT_LOCAL|VT_LVAL, c);
4902 vswap();
4903 vstore();
4904 vpop();
4908 /* put zeros for variable based init */
4909 static void init_putz(CType *t, Section *sec, unsigned long c, int size)
4911 if (sec) {
4912 /* nothing to do because globals are already set to zero */
4913 } else {
4914 vpush_global_sym(&func_old_type, TOK_memset);
4915 vseti(VT_LOCAL, c);
4916 vpushi(0);
4917 vpushi(size);
4918 gfunc_call(3);
4922 /* 't' contains the type and storage info. 'c' is the offset of the
4923 object in section 'sec'. If 'sec' is NULL, it means stack based
4924 allocation. 'first' is true if array '{' must be read (multi
4925 dimension implicit array init handling). 'size_only' is true if
4926 size only evaluation is wanted (only for arrays). */
4927 static void decl_initializer(CType *type, Section *sec, unsigned long c,
4928 int first, int size_only)
4930 int index, array_length, n, no_oblock, nb, parlevel, parlevel1, i;
4931 int size1, align1, expr_type;
4932 Sym *s, *f;
4933 CType *t1;
4935 if (type->t & VT_VLA) {
4936 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
4937 int a;
4938 CValue retcval;
4940 vpush_global_sym(&func_old_type, TOK_alloca);
4941 vla_runtime_type_size(type, &a);
4942 gfunc_call(1);
4944 /* return value */
4945 retcval.i = 0;
4946 vsetc(type, REG_IRET, &retcval);
4947 vset(type, VT_LOCAL|VT_LVAL, c);
4948 vswap();
4949 vstore();
4950 vpop();
4951 #else
4952 tcc_error("variable length arrays unsupported for this target");
4953 #endif
4954 } else if (type->t & VT_ARRAY) {
4955 s = type->ref;
4956 n = s->c;
4957 array_length = 0;
4958 t1 = pointed_type(type);
4959 size1 = type_size(t1, &align1);
4961 no_oblock = 1;
4962 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
4963 tok == '{') {
4964 if (tok != '{')
4965 tcc_error("character array initializer must be a literal,"
4966 " optionally enclosed in braces");
4967 skip('{');
4968 no_oblock = 0;
4971 /* only parse strings here if correct type (otherwise: handle
4972 them as ((w)char *) expressions */
4973 if ((tok == TOK_LSTR &&
4974 #ifdef TCC_TARGET_PE
4975 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
4976 #else
4977 (t1->t & VT_BTYPE) == VT_INT
4978 #endif
4979 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
4980 while (tok == TOK_STR || tok == TOK_LSTR) {
4981 int cstr_len, ch;
4982 CString *cstr;
4984 cstr = tokc.cstr;
4985 /* compute maximum number of chars wanted */
4986 if (tok == TOK_STR)
4987 cstr_len = cstr->size;
4988 else
4989 cstr_len = cstr->size / sizeof(nwchar_t);
4990 cstr_len--;
4991 nb = cstr_len;
4992 if (n >= 0 && nb > (n - array_length))
4993 nb = n - array_length;
4994 if (!size_only) {
4995 if (cstr_len > nb)
4996 tcc_warning("initializer-string for array is too long");
4997 /* in order to go faster for common case (char
4998 string in global variable, we handle it
4999 specifically */
5000 if (sec && tok == TOK_STR && size1 == 1) {
5001 memcpy(sec->data + c + array_length, cstr->data, nb);
5002 } else {
5003 for(i=0;i<nb;i++) {
5004 if (tok == TOK_STR)
5005 ch = ((unsigned char *)cstr->data)[i];
5006 else
5007 ch = ((nwchar_t *)cstr->data)[i];
5008 init_putv(t1, sec, c + (array_length + i) * size1,
5009 ch, EXPR_VAL);
5013 array_length += nb;
5014 next();
5016 /* only add trailing zero if enough storage (no
5017 warning in this case since it is standard) */
5018 if (n < 0 || array_length < n) {
5019 if (!size_only) {
5020 init_putv(t1, sec, c + (array_length * size1), 0, EXPR_VAL);
5022 array_length++;
5024 } else {
5025 index = 0;
5026 while (tok != '}') {
5027 decl_designator(type, sec, c, &index, NULL, size_only);
5028 if (n >= 0 && index >= n)
5029 tcc_error("index too large");
5030 /* must put zero in holes (note that doing it that way
5031 ensures that it even works with designators) */
5032 if (!size_only && array_length < index) {
5033 init_putz(t1, sec, c + array_length * size1,
5034 (index - array_length) * size1);
5036 index++;
5037 if (index > array_length)
5038 array_length = index;
5039 /* special test for multi dimensional arrays (may not
5040 be strictly correct if designators are used at the
5041 same time) */
5042 if (index >= n && no_oblock)
5043 break;
5044 if (tok == '}')
5045 break;
5046 skip(',');
5049 if (!no_oblock)
5050 skip('}');
5051 /* put zeros at the end */
5052 if (!size_only && n >= 0 && array_length < n) {
5053 init_putz(t1, sec, c + array_length * size1,
5054 (n - array_length) * size1);
5056 /* patch type size if needed */
5057 if (n < 0)
5058 s->c = array_length;
5059 } else if ((type->t & VT_BTYPE) == VT_STRUCT &&
5060 (sec || !first || tok == '{')) {
5061 int par_count;
5063 /* NOTE: the previous test is a specific case for automatic
5064 struct/union init */
5065 /* XXX: union needs only one init */
5067 /* XXX: this test is incorrect for local initializers
5068 beginning with ( without {. It would be much more difficult
5069 to do it correctly (ideally, the expression parser should
5070 be used in all cases) */
5071 par_count = 0;
5072 if (tok == '(') {
5073 AttributeDef ad1;
5074 CType type1;
5075 next();
5076 while (tok == '(') {
5077 par_count++;
5078 next();
5080 if (!parse_btype(&type1, &ad1))
5081 expect("cast");
5082 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
5083 #if 0
5084 if (!is_assignable_types(type, &type1))
5085 tcc_error("invalid type for cast");
5086 #endif
5087 skip(')');
5089 no_oblock = 1;
5090 if (first || tok == '{') {
5091 skip('{');
5092 no_oblock = 0;
5094 s = type->ref;
5095 f = s->next;
5096 array_length = 0;
5097 index = 0;
5098 n = s->c;
5099 while (tok != '}') {
5100 decl_designator(type, sec, c, NULL, &f, size_only);
5101 index = f->c;
5102 if (!size_only && array_length < index) {
5103 init_putz(type, sec, c + array_length,
5104 index - array_length);
5106 index = index + type_size(&f->type, &align1);
5107 if (index > array_length)
5108 array_length = index;
5110 /* gr: skip fields from same union - ugly. */
5111 while (f->next) {
5112 ///printf("index: %2d %08x -- %2d %08x\n", f->c, f->type.t, f->next->c, f->next->type.t);
5113 /* test for same offset */
5114 if (f->next->c != f->c)
5115 break;
5116 /* if yes, test for bitfield shift */
5117 if ((f->type.t & VT_BITFIELD) && (f->next->type.t & VT_BITFIELD)) {
5118 int bit_pos_1 = (f->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5119 int bit_pos_2 = (f->next->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5120 //printf("bitfield %d %d\n", bit_pos_1, bit_pos_2);
5121 if (bit_pos_1 != bit_pos_2)
5122 break;
5124 f = f->next;
5127 f = f->next;
5128 if (no_oblock && f == NULL)
5129 break;
5130 if (tok == '}')
5131 break;
5132 skip(',');
5134 /* put zeros at the end */
5135 if (!size_only && array_length < n) {
5136 init_putz(type, sec, c + array_length,
5137 n - array_length);
5139 if (!no_oblock)
5140 skip('}');
5141 while (par_count) {
5142 skip(')');
5143 par_count--;
5145 } else if (tok == '{') {
5146 next();
5147 decl_initializer(type, sec, c, first, size_only);
5148 skip('}');
5149 } else if (size_only) {
5150 /* just skip expression */
5151 parlevel = parlevel1 = 0;
5152 while ((parlevel > 0 || parlevel1 > 0 ||
5153 (tok != '}' && tok != ',')) && tok != -1) {
5154 if (tok == '(')
5155 parlevel++;
5156 else if (tok == ')')
5157 parlevel--;
5158 else if (tok == '{')
5159 parlevel1++;
5160 else if (tok == '}')
5161 parlevel1--;
5162 next();
5164 } else {
5165 /* currently, we always use constant expression for globals
5166 (may change for scripting case) */
5167 expr_type = EXPR_CONST;
5168 if (!sec)
5169 expr_type = EXPR_ANY;
5170 init_putv(type, sec, c, 0, expr_type);
5174 /* parse an initializer for type 't' if 'has_init' is non zero, and
5175 allocate space in local or global data space ('r' is either
5176 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
5177 variable 'v' with an associated name represented by 'asm_label' of
5178 scope 'scope' is declared before initializers are parsed. If 'v' is
5179 zero, then a reference to the new object is put in the value stack.
5180 If 'has_init' is 2, a special parsing is done to handle string
5181 constants. */
5182 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
5183 int has_init, int v, char *asm_label,
5184 int scope)
5186 int size, align, addr, data_offset;
5187 int level;
5188 ParseState saved_parse_state = {0};
5189 TokenString init_str;
5190 Section *sec;
5191 Sym *flexible_array;
5193 flexible_array = NULL;
5194 if ((type->t & VT_BTYPE) == VT_STRUCT) {
5195 Sym *field;
5196 field = type->ref;
5197 while (field && field->next)
5198 field = field->next;
5199 if (field->type.t & VT_ARRAY && field->type.ref->c < 0)
5200 flexible_array = field;
5203 size = type_size(type, &align);
5204 /* If unknown size, we must evaluate it before
5205 evaluating initializers because
5206 initializers can generate global data too
5207 (e.g. string pointers or ISOC99 compound
5208 literals). It also simplifies local
5209 initializers handling */
5210 tok_str_new(&init_str);
5211 if (size < 0 || (flexible_array && has_init)) {
5212 if (!has_init)
5213 tcc_error("unknown type size");
5214 /* get all init string */
5215 if (has_init == 2) {
5216 /* only get strings */
5217 while (tok == TOK_STR || tok == TOK_LSTR) {
5218 tok_str_add_tok(&init_str);
5219 next();
5221 } else {
5222 level = 0;
5223 while (level > 0 || (tok != ',' && tok != ';')) {
5224 if (tok < 0)
5225 tcc_error("unexpected end of file in initializer");
5226 tok_str_add_tok(&init_str);
5227 if (tok == '{')
5228 level++;
5229 else if (tok == '}') {
5230 level--;
5231 if (level <= 0) {
5232 next();
5233 break;
5236 next();
5239 tok_str_add(&init_str, -1);
5240 tok_str_add(&init_str, 0);
5242 /* compute size */
5243 save_parse_state(&saved_parse_state);
5245 macro_ptr = init_str.str;
5246 next();
5247 decl_initializer(type, NULL, 0, 1, 1);
5248 /* prepare second initializer parsing */
5249 macro_ptr = init_str.str;
5250 next();
5252 /* if still unknown size, error */
5253 size = type_size(type, &align);
5254 if (size < 0)
5255 tcc_error("unknown type size");
5257 if (flexible_array)
5258 size += flexible_array->type.ref->c * pointed_size(&flexible_array->type);
5259 /* take into account specified alignment if bigger */
5260 if (ad->aligned) {
5261 if (ad->aligned > align)
5262 align = ad->aligned;
5263 } else if (ad->packed) {
5264 align = 1;
5266 if ((r & VT_VALMASK) == VT_LOCAL) {
5267 sec = NULL;
5268 #ifdef CONFIG_TCC_BCHECK
5269 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5270 loc--;
5272 #endif
5273 loc = (loc - size) & -align;
5274 addr = loc;
5275 #ifdef CONFIG_TCC_BCHECK
5276 /* handles bounds */
5277 /* XXX: currently, since we do only one pass, we cannot track
5278 '&' operators, so we add only arrays */
5279 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5280 unsigned long *bounds_ptr;
5281 /* add padding between regions */
5282 loc--;
5283 /* then add local bound info */
5284 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(unsigned long));
5285 bounds_ptr[0] = addr;
5286 bounds_ptr[1] = size;
5288 #endif
5289 if (v) {
5290 /* local variable */
5291 sym_push(v, type, r, addr);
5292 } else {
5293 /* push local reference */
5294 vset(type, r, addr);
5296 } else {
5297 Sym *sym;
5299 sym = NULL;
5300 if (v && scope == VT_CONST) {
5301 /* see if the symbol was already defined */
5302 sym = sym_find(v);
5303 if (sym) {
5304 if (!is_compatible_types(&sym->type, type))
5305 tcc_error("incompatible types for redefinition of '%s'",
5306 get_tok_str(v, NULL));
5307 if (sym->type.t & VT_EXTERN) {
5308 /* if the variable is extern, it was not allocated */
5309 sym->type.t &= ~VT_EXTERN;
5310 /* set array size if it was ommited in extern
5311 declaration */
5312 if ((sym->type.t & VT_ARRAY) &&
5313 sym->type.ref->c < 0 &&
5314 type->ref->c >= 0)
5315 sym->type.ref->c = type->ref->c;
5316 } else {
5317 /* we accept several definitions of the same
5318 global variable. this is tricky, because we
5319 must play with the SHN_COMMON type of the symbol */
5320 /* XXX: should check if the variable was already
5321 initialized. It is incorrect to initialized it
5322 twice */
5323 /* no init data, we won't add more to the symbol */
5324 if (!has_init)
5325 goto no_alloc;
5330 /* allocate symbol in corresponding section */
5331 sec = ad->section;
5332 if (!sec) {
5333 if (has_init)
5334 sec = data_section;
5335 else if (tcc_state->nocommon)
5336 sec = bss_section;
5338 if (sec) {
5339 data_offset = sec->data_offset;
5340 data_offset = (data_offset + align - 1) & -align;
5341 addr = data_offset;
5342 /* very important to increment global pointer at this time
5343 because initializers themselves can create new initializers */
5344 data_offset += size;
5345 #ifdef CONFIG_TCC_BCHECK
5346 /* add padding if bound check */
5347 if (tcc_state->do_bounds_check)
5348 data_offset++;
5349 #endif
5350 sec->data_offset = data_offset;
5351 /* allocate section space to put the data */
5352 if (sec->sh_type != SHT_NOBITS &&
5353 data_offset > sec->data_allocated)
5354 section_realloc(sec, data_offset);
5355 /* align section if needed */
5356 if (align > sec->sh_addralign)
5357 sec->sh_addralign = align;
5358 } else {
5359 addr = 0; /* avoid warning */
5362 if (v) {
5363 if (scope != VT_CONST || !sym) {
5364 sym = sym_push(v, type, r | VT_SYM, 0);
5365 sym->asm_label = asm_label;
5367 /* update symbol definition */
5368 if (sec) {
5369 put_extern_sym(sym, sec, addr, size);
5370 } else {
5371 ElfW(Sym) *esym;
5372 /* put a common area */
5373 put_extern_sym(sym, NULL, align, size);
5374 /* XXX: find a nicer way */
5375 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
5376 esym->st_shndx = SHN_COMMON;
5378 } else {
5379 CValue cval;
5381 /* push global reference */
5382 sym = get_sym_ref(type, sec, addr, size);
5383 cval.ul = 0;
5384 vsetc(type, VT_CONST | VT_SYM, &cval);
5385 vtop->sym = sym;
5387 /* patch symbol weakness */
5388 if (type->t & VT_WEAK)
5389 weaken_symbol(sym);
5390 #ifdef CONFIG_TCC_BCHECK
5391 /* handles bounds now because the symbol must be defined
5392 before for the relocation */
5393 if (tcc_state->do_bounds_check) {
5394 unsigned long *bounds_ptr;
5396 greloc(bounds_section, sym, bounds_section->data_offset, R_DATA_PTR);
5397 /* then add global bound info */
5398 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(long));
5399 bounds_ptr[0] = 0; /* relocated */
5400 bounds_ptr[1] = size;
5402 #endif
5404 if (has_init || (type->t & VT_VLA)) {
5405 decl_initializer(type, sec, addr, 1, 0);
5406 /* restore parse state if needed */
5407 if (init_str.str) {
5408 tok_str_free(init_str.str);
5409 restore_parse_state(&saved_parse_state);
5411 /* patch flexible array member size back to -1, */
5412 /* for possible subsequent similar declarations */
5413 if (flexible_array)
5414 flexible_array->type.ref->c = -1;
5416 no_alloc: ;
5419 static void put_func_debug(Sym *sym)
5421 char buf[512];
5423 /* stabs info */
5424 /* XXX: we put here a dummy type */
5425 snprintf(buf, sizeof(buf), "%s:%c1",
5426 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
5427 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
5428 cur_text_section, sym->c);
5429 /* //gr gdb wants a line at the function */
5430 put_stabn(N_SLINE, 0, file->line_num, 0);
5431 last_ind = 0;
5432 last_line_num = 0;
5435 /* parse an old style function declaration list */
5436 /* XXX: check multiple parameter */
5437 static void func_decl_list(Sym *func_sym)
5439 AttributeDef ad;
5440 int v;
5441 Sym *s;
5442 CType btype, type;
5444 /* parse each declaration */
5445 while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF &&
5446 tok != TOK_ASM1 && tok != TOK_ASM2 && tok != TOK_ASM3) {
5447 if (!parse_btype(&btype, &ad))
5448 expect("declaration list");
5449 if (((btype.t & VT_BTYPE) == VT_ENUM ||
5450 (btype.t & VT_BTYPE) == VT_STRUCT) &&
5451 tok == ';') {
5452 /* we accept no variable after */
5453 } else {
5454 for(;;) {
5455 type = btype;
5456 type_decl(&type, &ad, &v, TYPE_DIRECT);
5457 /* find parameter in function parameter list */
5458 s = func_sym->next;
5459 while (s != NULL) {
5460 if ((s->v & ~SYM_FIELD) == v)
5461 goto found;
5462 s = s->next;
5464 tcc_error("declaration for parameter '%s' but no such parameter",
5465 get_tok_str(v, NULL));
5466 found:
5467 /* check that no storage specifier except 'register' was given */
5468 if (type.t & VT_STORAGE)
5469 tcc_error("storage class specified for '%s'", get_tok_str(v, NULL));
5470 convert_parameter_type(&type);
5471 /* we can add the type (NOTE: it could be local to the function) */
5472 s->type = type;
5473 /* accept other parameters */
5474 if (tok == ',')
5475 next();
5476 else
5477 break;
5480 skip(';');
5484 /* parse a function defined by symbol 'sym' and generate its code in
5485 'cur_text_section' */
5486 static void gen_function(Sym *sym)
5488 int saved_nocode_wanted = nocode_wanted;
5489 nocode_wanted = 0;
5490 ind = cur_text_section->data_offset;
5491 /* NOTE: we patch the symbol size later */
5492 put_extern_sym(sym, cur_text_section, ind, 0);
5493 funcname = get_tok_str(sym->v, NULL);
5494 func_ind = ind;
5495 /* put debug symbol */
5496 if (tcc_state->do_debug)
5497 put_func_debug(sym);
5498 /* push a dummy symbol to enable local sym storage */
5499 sym_push2(&local_stack, SYM_FIELD, 0, 0);
5500 gfunc_prolog(&sym->type);
5501 rsym = 0;
5502 block(NULL, NULL, NULL, NULL, 0, 0);
5503 gsym(rsym);
5504 gfunc_epilog();
5505 cur_text_section->data_offset = ind;
5506 label_pop(&global_label_stack, NULL);
5507 sym_pop(&local_stack, NULL); /* reset local stack */
5508 /* end of function */
5509 /* patch symbol size */
5510 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
5511 ind - func_ind;
5512 /* patch symbol weakness (this definition overrules any prototype) */
5513 if (sym->type.t & VT_WEAK)
5514 weaken_symbol(sym);
5515 if (tcc_state->do_debug) {
5516 put_stabn(N_FUN, 0, 0, ind - func_ind);
5518 /* It's better to crash than to generate wrong code */
5519 cur_text_section = NULL;
5520 funcname = ""; /* for safety */
5521 func_vt.t = VT_VOID; /* for safety */
5522 ind = 0; /* for safety */
5523 nocode_wanted = saved_nocode_wanted;
5526 ST_FUNC void gen_inline_functions(void)
5528 Sym *sym;
5529 int *str, inline_generated, i;
5530 struct InlineFunc *fn;
5532 /* iterate while inline function are referenced */
5533 for(;;) {
5534 inline_generated = 0;
5535 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
5536 fn = tcc_state->inline_fns[i];
5537 sym = fn->sym;
5538 if (sym && sym->c) {
5539 /* the function was used: generate its code and
5540 convert it to a normal function */
5541 str = fn->token_str;
5542 fn->sym = NULL;
5543 if (file)
5544 strcpy(file->filename, fn->filename);
5545 sym->r = VT_SYM | VT_CONST;
5546 sym->type.t &= ~VT_INLINE;
5548 macro_ptr = str;
5549 next();
5550 cur_text_section = text_section;
5551 gen_function(sym);
5552 macro_ptr = NULL; /* fail safe */
5554 inline_generated = 1;
5557 if (!inline_generated)
5558 break;
5560 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
5561 fn = tcc_state->inline_fns[i];
5562 str = fn->token_str;
5563 tok_str_free(str);
5565 dynarray_reset(&tcc_state->inline_fns, &tcc_state->nb_inline_fns);
5568 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
5569 static int decl0(int l, int is_for_loop_init)
5571 int v, has_init, r;
5572 CType type, btype;
5573 Sym *sym;
5574 AttributeDef ad;
5576 while (1) {
5577 if (!parse_btype(&btype, &ad)) {
5578 if (is_for_loop_init)
5579 return 0;
5580 /* skip redundant ';' */
5581 /* XXX: find more elegant solution */
5582 if (tok == ';') {
5583 next();
5584 continue;
5586 if (l == VT_CONST &&
5587 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
5588 /* global asm block */
5589 asm_global_instr();
5590 continue;
5592 /* special test for old K&R protos without explicit int
5593 type. Only accepted when defining global data */
5594 if (l == VT_LOCAL || tok < TOK_DEFINE)
5595 break;
5596 btype.t = VT_INT;
5598 if (((btype.t & VT_BTYPE) == VT_ENUM ||
5599 (btype.t & VT_BTYPE) == VT_STRUCT) &&
5600 tok == ';') {
5601 /* we accept no variable after */
5602 next();
5603 continue;
5605 while (1) { /* iterate thru each declaration */
5606 char *asm_label; // associated asm label
5607 type = btype;
5608 type_decl(&type, &ad, &v, TYPE_DIRECT);
5609 #if 0
5611 char buf[500];
5612 type_to_str(buf, sizeof(buf), t, get_tok_str(v, NULL));
5613 printf("type = '%s'\n", buf);
5615 #endif
5616 if ((type.t & VT_BTYPE) == VT_FUNC) {
5617 if ((type.t & VT_STATIC) && (l == VT_LOCAL)) {
5618 tcc_error("function without file scope cannot be static");
5620 /* if old style function prototype, we accept a
5621 declaration list */
5622 sym = type.ref;
5623 if (sym->c == FUNC_OLD)
5624 func_decl_list(sym);
5627 asm_label = NULL;
5628 if (gnu_ext && (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
5629 CString astr;
5631 asm_label_instr(&astr);
5632 asm_label = tcc_strdup(astr.data);
5633 cstr_free(&astr);
5635 /* parse one last attribute list, after asm label */
5636 parse_attribute(&ad);
5639 if (ad.weak)
5640 type.t |= VT_WEAK;
5641 #ifdef TCC_TARGET_PE
5642 if (ad.func_import)
5643 type.t |= VT_IMPORT;
5644 if (ad.func_export)
5645 type.t |= VT_EXPORT;
5646 #endif
5647 if (tok == '{') {
5648 if (l == VT_LOCAL)
5649 tcc_error("cannot use local functions");
5650 if ((type.t & VT_BTYPE) != VT_FUNC)
5651 expect("function definition");
5653 /* reject abstract declarators in function definition */
5654 sym = type.ref;
5655 while ((sym = sym->next) != NULL)
5656 if (!(sym->v & ~SYM_FIELD))
5657 expect("identifier");
5659 /* XXX: cannot do better now: convert extern line to static inline */
5660 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
5661 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
5663 sym = sym_find(v);
5664 if (sym) {
5665 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
5666 goto func_error1;
5668 r = sym->type.ref->r;
5669 /* use func_call from prototype if not defined */
5670 if (FUNC_CALL(r) != FUNC_CDECL
5671 && FUNC_CALL(type.ref->r) == FUNC_CDECL)
5672 FUNC_CALL(type.ref->r) = FUNC_CALL(r);
5674 /* use export from prototype */
5675 if (FUNC_EXPORT(r))
5676 FUNC_EXPORT(type.ref->r) = 1;
5678 /* use static from prototype */
5679 if (sym->type.t & VT_STATIC)
5680 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
5682 if (!is_compatible_types(&sym->type, &type)) {
5683 func_error1:
5684 tcc_error("incompatible types for redefinition of '%s'",
5685 get_tok_str(v, NULL));
5687 /* if symbol is already defined, then put complete type */
5688 sym->type = type;
5689 } else {
5690 /* put function symbol */
5691 sym = global_identifier_push(v, type.t, 0);
5692 sym->type.ref = type.ref;
5695 /* static inline functions are just recorded as a kind
5696 of macro. Their code will be emitted at the end of
5697 the compilation unit only if they are used */
5698 if ((type.t & (VT_INLINE | VT_STATIC)) ==
5699 (VT_INLINE | VT_STATIC)) {
5700 TokenString func_str;
5701 int block_level;
5702 struct InlineFunc *fn;
5703 const char *filename;
5705 tok_str_new(&func_str);
5707 block_level = 0;
5708 for(;;) {
5709 int t;
5710 if (tok == TOK_EOF)
5711 tcc_error("unexpected end of file");
5712 tok_str_add_tok(&func_str);
5713 t = tok;
5714 next();
5715 if (t == '{') {
5716 block_level++;
5717 } else if (t == '}') {
5718 block_level--;
5719 if (block_level == 0)
5720 break;
5723 tok_str_add(&func_str, -1);
5724 tok_str_add(&func_str, 0);
5725 filename = file ? file->filename : "";
5726 fn = tcc_malloc(sizeof *fn + strlen(filename));
5727 strcpy(fn->filename, filename);
5728 fn->sym = sym;
5729 fn->token_str = func_str.str;
5730 dynarray_add((void ***)&tcc_state->inline_fns, &tcc_state->nb_inline_fns, fn);
5732 } else {
5733 /* compute text section */
5734 cur_text_section = ad.section;
5735 if (!cur_text_section)
5736 cur_text_section = text_section;
5737 sym->r = VT_SYM | VT_CONST;
5738 gen_function(sym);
5740 break;
5741 } else {
5742 if (btype.t & VT_TYPEDEF) {
5743 /* save typedefed type */
5744 /* XXX: test storage specifiers ? */
5745 sym = sym_push(v, &type, INT_ATTR(&ad), 0);
5746 sym->type.t |= VT_TYPEDEF;
5747 } else {
5748 r = 0;
5749 if ((type.t & VT_BTYPE) == VT_FUNC) {
5750 /* external function definition */
5751 /* specific case for func_call attribute */
5752 type.ref->r = INT_ATTR(&ad);
5753 } else if (!(type.t & VT_ARRAY)) {
5754 /* not lvalue if array */
5755 r |= lvalue_type(type.t);
5757 has_init = (tok == '=');
5758 if (has_init && (type.t & VT_VLA))
5759 tcc_error("Variable length array cannot be initialized");
5760 if ((btype.t & VT_EXTERN) || ((type.t & VT_BTYPE) == VT_FUNC) ||
5761 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
5762 !has_init && l == VT_CONST && type.ref->c < 0)) {
5763 /* external variable or function */
5764 /* NOTE: as GCC, uninitialized global static
5765 arrays of null size are considered as
5766 extern */
5767 sym = external_sym(v, &type, r, asm_label);
5769 if (type.t & VT_WEAK)
5770 weaken_symbol(sym);
5772 if (ad.alias_target) {
5773 Section tsec;
5774 Elf32_Sym *esym;
5775 Sym *alias_target;
5777 alias_target = sym_find(ad.alias_target);
5778 if (!alias_target || !alias_target->c)
5779 tcc_error("unsupported forward __alias__ attribute");
5780 esym = &((Elf32_Sym *)symtab_section->data)[alias_target->c];
5781 tsec.sh_num = esym->st_shndx;
5782 put_extern_sym2(sym, &tsec, esym->st_value, esym->st_size, 0);
5784 } else {
5785 type.t |= (btype.t & VT_STATIC); /* Retain "static". */
5786 if (type.t & VT_STATIC)
5787 r |= VT_CONST;
5788 else
5789 r |= l;
5790 if (has_init)
5791 next();
5792 decl_initializer_alloc(&type, &ad, r, has_init, v, asm_label, l);
5795 if (tok != ',') {
5796 if (is_for_loop_init)
5797 return 1;
5798 skip(';');
5799 break;
5801 next();
5803 ad.aligned = 0;
5806 return 0;
5809 ST_FUNC void decl(int l)
5811 decl0(l, 0);