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