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