small change to previous whitespace-only commit
[tinycc/miki.git] / tccgen.c
blob805d50181eb49212aed29ddc77a6b5493af6058b
1 /*
2 * TCC - Tiny C Compiler
3 *
4 * Copyright (c) 2001-2004 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #include "tcc.h"
23 /********************************************************/
24 /* global variables */
26 /* loc : local variable index
27 ind : output code index
28 rsym: return symbol
29 anon_sym: anonymous symbol index
31 ST_DATA int rsym, anon_sym, ind, loc;
33 ST_DATA Section *text_section, *data_section, *bss_section; /* predefined sections */
34 ST_DATA Section *cur_text_section; /* current section where function code is generated */
35 #ifdef CONFIG_TCC_ASM
36 ST_DATA Section *last_text_section; /* to handle .previous asm directive */
37 #endif
38 #ifdef CONFIG_TCC_BCHECK
39 /* bound check related sections */
40 ST_DATA Section *bounds_section; /* contains global data bound description */
41 ST_DATA Section *lbounds_section; /* contains local data bound description */
42 #endif
43 /* symbol sections */
44 ST_DATA Section *symtab_section, *strtab_section;
45 /* debug sections */
46 ST_DATA Section *stab_section, *stabstr_section;
47 ST_DATA Sym *sym_free_first;
48 ST_DATA void **sym_pools;
49 ST_DATA int nb_sym_pools;
51 ST_DATA Sym *global_stack;
52 ST_DATA Sym *local_stack;
53 ST_DATA Sym *define_stack;
54 ST_DATA Sym *global_label_stack;
55 ST_DATA Sym *local_label_stack;
57 ST_DATA SValue vstack[VSTACK_SIZE], *vtop;
59 ST_DATA int const_wanted; /* true if constant wanted */
60 ST_DATA int nocode_wanted; /* true if no code generation wanted for an expression */
61 ST_DATA int global_expr; /* true if compound literals must be allocated globally (used during initializers parsing */
62 ST_DATA CType func_vt; /* current function return type (used by return instruction) */
63 ST_DATA int func_vc;
64 ST_DATA int last_line_num, last_ind, func_ind; /* debug last line number and pc */
65 ST_DATA char *funcname;
67 ST_DATA CType char_pointer_type, func_old_type, int_type;
69 /* ------------------------------------------------------------------------- */
70 static void gen_cast(CType *type);
71 static inline CType *pointed_type(CType *type);
72 static int is_compatible_types(CType *type1, CType *type2);
73 static int parse_btype(CType *type, AttributeDef *ad);
74 static void type_decl(CType *type, AttributeDef *ad, int *v, int td);
75 static void parse_expr_type(CType *type);
76 static void decl_initializer(CType *type, Section *sec, unsigned long c, int first, int size_only);
77 static void block(int *bsym, int *csym, int *case_sym, int *def_sym, int case_reg, int is_expr);
78 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r, int has_init, int v, char *asm_label, int scope);
79 static void expr_eq(void);
80 static void unary_type(CType *type);
81 static int is_compatible_parameter_types(CType *type1, CType *type2);
82 static void expr_type(CType *type);
84 ST_INLN int is_float(int t)
86 int bt;
87 bt = t & VT_BTYPE;
88 return bt == VT_LDOUBLE || bt == VT_DOUBLE || bt == VT_FLOAT;
91 ST_FUNC void test_lvalue(void)
93 if (!(vtop->r & VT_LVAL))
94 expect("lvalue");
97 /* ------------------------------------------------------------------------- */
98 /* symbol allocator */
99 static Sym *__sym_malloc(void)
101 Sym *sym_pool, *sym, *last_sym;
102 int i;
104 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
105 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
107 last_sym = sym_free_first;
108 sym = sym_pool;
109 for(i = 0; i < SYM_POOL_NB; i++) {
110 sym->next = last_sym;
111 last_sym = sym;
112 sym++;
114 sym_free_first = last_sym;
115 return last_sym;
118 static inline Sym *sym_malloc(void)
120 Sym *sym;
121 sym = sym_free_first;
122 if (!sym)
123 sym = __sym_malloc();
124 sym_free_first = sym->next;
125 return sym;
128 ST_INLN void sym_free(Sym *sym)
130 sym->next = sym_free_first;
131 tcc_free(sym->asm_label);
132 sym_free_first = sym;
135 /* push, without hashing */
136 ST_FUNC Sym *sym_push2(Sym **ps, int v, int t, long c)
138 Sym *s;
139 s = sym_malloc();
140 s->asm_label = NULL;
141 s->v = v;
142 s->type.t = t;
143 s->type.ref = NULL;
144 #ifdef _WIN64
145 s->d = NULL;
146 #endif
147 s->c = c;
148 s->next = NULL;
149 /* add in stack */
150 s->prev = *ps;
151 *ps = s;
152 return s;
155 /* find a symbol and return its associated structure. 's' is the top
156 of the symbol stack */
157 ST_FUNC Sym *sym_find2(Sym *s, int v)
159 while (s) {
160 if (s->v == v)
161 return s;
162 s = s->prev;
164 return NULL;
167 /* structure lookup */
168 ST_INLN Sym *struct_find(int v)
170 v -= TOK_IDENT;
171 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
172 return NULL;
173 return table_ident[v]->sym_struct;
176 /* find an identifier */
177 ST_INLN Sym *sym_find(int v)
179 v -= TOK_IDENT;
180 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
181 return NULL;
182 return table_ident[v]->sym_identifier;
185 /* push a given symbol on the symbol stack */
186 ST_FUNC Sym *sym_push(int v, CType *type, int r, int c)
188 Sym *s, **ps;
189 TokenSym *ts;
191 if (local_stack)
192 ps = &local_stack;
193 else
194 ps = &global_stack;
195 s = sym_push2(ps, v, type->t, c);
196 s->type.ref = type->ref;
197 s->r = r;
198 /* don't record fields or anonymous symbols */
199 /* XXX: simplify */
200 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
201 /* record symbol in token array */
202 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
203 if (v & SYM_STRUCT)
204 ps = &ts->sym_struct;
205 else
206 ps = &ts->sym_identifier;
207 s->prev_tok = *ps;
208 *ps = s;
210 return s;
213 /* push a global identifier */
214 ST_FUNC Sym *global_identifier_push(int v, int t, int c)
216 Sym *s, **ps;
217 s = sym_push2(&global_stack, v, t, c);
218 /* don't record anonymous symbol */
219 if (v < SYM_FIRST_ANOM) {
220 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
221 /* modify the top most local identifier, so that
222 sym_identifier will point to 's' when popped */
223 while (*ps != NULL)
224 ps = &(*ps)->prev_tok;
225 s->prev_tok = NULL;
226 *ps = s;
228 return s;
231 /* pop symbols until top reaches 'b' */
232 ST_FUNC void sym_pop(Sym **ptop, Sym *b)
234 Sym *s, *ss, **ps;
235 TokenSym *ts;
236 int v;
238 s = *ptop;
239 while(s != b) {
240 ss = s->prev;
241 v = s->v;
242 /* remove symbol in token array */
243 /* XXX: simplify */
244 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
245 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
246 if (v & SYM_STRUCT)
247 ps = &ts->sym_struct;
248 else
249 ps = &ts->sym_identifier;
250 *ps = s->prev_tok;
252 sym_free(s);
253 s = ss;
255 *ptop = b;
258 static void weaken_symbol(Sym *sym)
260 sym->type.t |= VT_WEAK;
261 if (sym->c > 0) {
262 int esym_type;
263 ElfW(Sym) *esym;
265 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
266 esym_type = ELFW(ST_TYPE)(esym->st_info);
267 esym->st_info = ELFW(ST_INFO)(STB_WEAK, esym_type);
271 /* ------------------------------------------------------------------------- */
273 ST_FUNC void swap(int *p, int *q)
275 int t;
276 t = *p;
277 *p = *q;
278 *q = t;
281 static void vsetc(CType *type, int r, CValue *vc)
283 int v;
285 if (vtop >= vstack + (VSTACK_SIZE - 1))
286 error("memory full");
287 /* cannot let cpu flags if other instruction are generated. Also
288 avoid leaving VT_JMP anywhere except on the top of the stack
289 because it would complicate the code generator. */
290 if (vtop >= vstack) {
291 v = vtop->r & VT_VALMASK;
292 if (v == VT_CMP || (v & ~1) == VT_JMP)
293 gv(RC_INT);
295 vtop++;
296 vtop->type = *type;
297 vtop->r = r;
298 vtop->r2 = VT_CONST;
299 vtop->c = *vc;
302 /* push constant of type "type" with useless value */
303 void vpush(CType *type)
305 CValue cval;
306 vsetc(type, VT_CONST, &cval);
309 /* push integer constant */
310 ST_FUNC void vpushi(int v)
312 CValue cval;
313 cval.i = v;
314 vsetc(&int_type, VT_CONST, &cval);
317 /* push long long constant */
318 static void vpushll(long long v)
320 CValue cval;
321 CType ctype;
322 ctype.t = VT_LLONG;
323 ctype.ref = 0;
324 cval.ull = v;
325 vsetc(&ctype, VT_CONST, &cval);
328 /* push arbitrary 64bit constant */
329 void vpush64(int ty, unsigned long long v)
331 CValue cval;
332 CType ctype;
333 ctype.t = ty;
334 cval.ull = v;
335 vsetc(&ctype, VT_CONST, &cval);
338 /* Return a static symbol pointing to a section */
339 ST_FUNC Sym *get_sym_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
341 int v;
342 Sym *sym;
344 v = anon_sym++;
345 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
346 sym->type.ref = type->ref;
347 sym->r = VT_CONST | VT_SYM;
348 put_extern_sym(sym, sec, offset, size);
349 return sym;
352 /* push a reference to a section offset by adding a dummy symbol */
353 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
355 CValue cval;
357 cval.ul = 0;
358 vsetc(type, VT_CONST | VT_SYM, &cval);
359 vtop->sym = get_sym_ref(type, sec, offset, size);
362 /* define a new external reference to a symbol 'v' of type 'u' */
363 ST_FUNC Sym *external_global_sym(int v, CType *type, int r)
365 Sym *s;
367 s = sym_find(v);
368 if (!s) {
369 /* push forward reference */
370 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
371 s->type.ref = type->ref;
372 s->r = r | VT_CONST | VT_SYM;
374 return s;
377 /* define a new external reference to a symbol 'v' with alternate asm
378 name 'asm_label' of type 'u'. 'asm_label' is equal to NULL if there
379 is no alternate name (most cases) */
380 static Sym *external_sym(int v, CType *type, int r, char *asm_label)
382 Sym *s;
384 s = sym_find(v);
385 if (!s) {
386 /* push forward reference */
387 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
388 s->asm_label = asm_label;
389 s->type.t |= VT_EXTERN;
390 } else if (s->type.ref == func_old_type.ref) {
391 s->type.ref = type->ref;
392 s->r = r | VT_CONST | VT_SYM;
393 s->type.t |= VT_EXTERN;
394 } else if (!is_compatible_types(&s->type, type)) {
395 error("incompatible types for redefinition of '%s'",
396 get_tok_str(v, NULL));
398 return s;
401 /* push a reference to global symbol v */
402 ST_FUNC void vpush_global_sym(CType *type, int v)
404 Sym *sym;
405 CValue cval;
407 sym = external_global_sym(v, type, 0);
408 cval.ul = 0;
409 vsetc(type, VT_CONST | VT_SYM, &cval);
410 vtop->sym = sym;
413 ST_FUNC void vset(CType *type, int r, int v)
415 CValue cval;
417 cval.i = v;
418 vsetc(type, r, &cval);
421 static void vseti(int r, int v)
423 CType type;
424 type.t = VT_INT;
425 type.ref = 0;
426 vset(&type, r, v);
429 ST_FUNC void vswap(void)
431 SValue tmp;
433 tmp = vtop[0];
434 vtop[0] = vtop[-1];
435 vtop[-1] = tmp;
438 ST_FUNC void vpushv(SValue *v)
440 if (vtop >= vstack + (VSTACK_SIZE - 1))
441 error("memory full");
442 vtop++;
443 *vtop = *v;
446 static void vdup(void)
448 vpushv(vtop);
451 /* save r to the memory stack, and mark it as being free */
452 ST_FUNC void save_reg(int r)
454 int l, saved, size, align;
455 SValue *p, sv;
456 CType *type;
458 /* modify all stack values */
459 saved = 0;
460 l = 0;
461 for(p=vstack;p<=vtop;p++) {
462 if ((p->r & VT_VALMASK) == r ||
463 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
464 /* must save value on stack if not already done */
465 if (!saved) {
466 /* NOTE: must reload 'r' because r might be equal to r2 */
467 r = p->r & VT_VALMASK;
468 /* store register in the stack */
469 type = &p->type;
470 if ((p->r & VT_LVAL) ||
471 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
472 #ifdef TCC_TARGET_X86_64
473 type = &char_pointer_type;
474 #else
475 type = &int_type;
476 #endif
477 size = type_size(type, &align);
478 loc = (loc - size) & -align;
479 sv.type.t = type->t;
480 sv.r = VT_LOCAL | VT_LVAL;
481 sv.c.ul = loc;
482 store(r, &sv);
483 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
484 /* x86 specific: need to pop fp register ST0 if saved */
485 if (r == TREG_ST0) {
486 o(0xd8dd); /* fstp %st(0) */
488 #endif
489 #ifndef TCC_TARGET_X86_64
490 /* special long long case */
491 if ((type->t & VT_BTYPE) == VT_LLONG) {
492 sv.c.ul += 4;
493 store(p->r2, &sv);
495 #endif
496 l = loc;
497 saved = 1;
499 /* mark that stack entry as being saved on the stack */
500 if (p->r & VT_LVAL) {
501 /* also clear the bounded flag because the
502 relocation address of the function was stored in
503 p->c.ul */
504 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
505 } else {
506 p->r = lvalue_type(p->type.t) | VT_LOCAL;
508 p->r2 = VT_CONST;
509 p->c.ul = l;
514 #ifdef TCC_TARGET_ARM
515 /* find a register of class 'rc2' with at most one reference on stack.
516 * If none, call get_reg(rc) */
517 ST_FUNC int get_reg_ex(int rc, int rc2)
519 int r;
520 SValue *p;
522 for(r=0;r<NB_REGS;r++) {
523 if (reg_classes[r] & rc2) {
524 int n;
525 n=0;
526 for(p = vstack; p <= vtop; p++) {
527 if ((p->r & VT_VALMASK) == r ||
528 (p->r2 & VT_VALMASK) == r)
529 n++;
531 if (n <= 1)
532 return r;
535 return get_reg(rc);
537 #endif
539 /* find a free register of class 'rc'. If none, save one register */
540 ST_FUNC int get_reg(int rc)
542 int r;
543 SValue *p;
545 /* find a free register */
546 for(r=0;r<NB_REGS;r++) {
547 if (reg_classes[r] & rc) {
548 for(p=vstack;p<=vtop;p++) {
549 if ((p->r & VT_VALMASK) == r ||
550 (p->r2 & VT_VALMASK) == r)
551 goto notfound;
553 return r;
555 notfound: ;
558 /* no register left : free the first one on the stack (VERY
559 IMPORTANT to start from the bottom to ensure that we don't
560 spill registers used in gen_opi()) */
561 for(p=vstack;p<=vtop;p++) {
562 r = p->r & VT_VALMASK;
563 if (r < VT_CONST && (reg_classes[r] & rc))
564 goto save_found;
565 /* also look at second register (if long long) */
566 r = p->r2 & VT_VALMASK;
567 if (r < VT_CONST && (reg_classes[r] & rc)) {
568 save_found:
569 save_reg(r);
570 return r;
573 /* Should never comes here */
574 return -1;
577 /* save registers up to (vtop - n) stack entry */
578 ST_FUNC void save_regs(int n)
580 int r;
581 SValue *p, *p1;
582 p1 = vtop - n;
583 for(p = vstack;p <= p1; p++) {
584 r = p->r & VT_VALMASK;
585 if (r < VT_CONST) {
586 save_reg(r);
591 /* move register 's' to 'r', and flush previous value of r to memory
592 if needed */
593 static void move_reg(int r, int s)
595 SValue sv;
597 if (r != s) {
598 save_reg(r);
599 sv.type.t = VT_INT;
600 sv.r = s;
601 sv.c.ul = 0;
602 load(r, &sv);
606 /* get address of vtop (vtop MUST BE an lvalue) */
607 static void gaddrof(void)
609 vtop->r &= ~VT_LVAL;
610 /* tricky: if saved lvalue, then we can go back to lvalue */
611 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
612 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
615 #ifdef CONFIG_TCC_BCHECK
616 /* generate lvalue bound code */
617 static void gbound(void)
619 int lval_type;
620 CType type1;
622 vtop->r &= ~VT_MUSTBOUND;
623 /* if lvalue, then use checking code before dereferencing */
624 if (vtop->r & VT_LVAL) {
625 /* if not VT_BOUNDED value, then make one */
626 if (!(vtop->r & VT_BOUNDED)) {
627 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
628 /* must save type because we must set it to int to get pointer */
629 type1 = vtop->type;
630 vtop->type.t = VT_INT;
631 gaddrof();
632 vpushi(0);
633 gen_bounded_ptr_add();
634 vtop->r |= lval_type;
635 vtop->type = type1;
637 /* then check for dereferencing */
638 gen_bounded_ptr_deref();
641 #endif
643 /* store vtop a register belonging to class 'rc'. lvalues are
644 converted to values. Cannot be used if cannot be converted to
645 register value (such as structures). */
646 ST_FUNC int gv(int rc)
648 int r, rc2, bit_pos, bit_size, size, align, i;
650 /* NOTE: get_reg can modify vstack[] */
651 if (vtop->type.t & VT_BITFIELD) {
652 CType type;
653 int bits = 32;
654 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
655 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
656 /* remove bit field info to avoid loops */
657 vtop->type.t &= ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
658 /* cast to int to propagate signedness in following ops */
659 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
660 type.t = VT_LLONG;
661 bits = 64;
662 } else
663 type.t = VT_INT;
664 if((vtop->type.t & VT_UNSIGNED) ||
665 (vtop->type.t & VT_BTYPE) == VT_BOOL)
666 type.t |= VT_UNSIGNED;
667 gen_cast(&type);
668 /* generate shifts */
669 vpushi(bits - (bit_pos + bit_size));
670 gen_op(TOK_SHL);
671 vpushi(bits - bit_size);
672 /* NOTE: transformed to SHR if unsigned */
673 gen_op(TOK_SAR);
674 r = gv(rc);
675 } else {
676 if (is_float(vtop->type.t) &&
677 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
678 Sym *sym;
679 int *ptr;
680 unsigned long offset;
681 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
682 CValue check;
683 #endif
685 /* XXX: unify with initializers handling ? */
686 /* CPUs usually cannot use float constants, so we store them
687 generically in data segment */
688 size = type_size(&vtop->type, &align);
689 offset = (data_section->data_offset + align - 1) & -align;
690 data_section->data_offset = offset;
691 /* XXX: not portable yet */
692 #if defined(__i386__) || defined(__x86_64__)
693 /* Zero pad x87 tenbyte long doubles */
694 if (size == LDOUBLE_SIZE)
695 vtop->c.tab[2] &= 0xffff;
696 #endif
697 ptr = section_ptr_add(data_section, size);
698 size = size >> 2;
699 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
700 check.d = 1;
701 if(check.tab[0])
702 for(i=0;i<size;i++)
703 ptr[i] = vtop->c.tab[size-1-i];
704 else
705 #endif
706 for(i=0;i<size;i++)
707 ptr[i] = vtop->c.tab[i];
708 sym = get_sym_ref(&vtop->type, data_section, offset, size << 2);
709 vtop->r |= VT_LVAL | VT_SYM;
710 vtop->sym = sym;
711 vtop->c.ul = 0;
713 #ifdef CONFIG_TCC_BCHECK
714 if (vtop->r & VT_MUSTBOUND)
715 gbound();
716 #endif
718 r = vtop->r & VT_VALMASK;
719 rc2 = RC_INT;
720 if (rc == RC_IRET)
721 rc2 = RC_LRET;
722 /* need to reload if:
723 - constant
724 - lvalue (need to dereference pointer)
725 - already a register, but not in the right class */
726 if (r >= VT_CONST
727 || (vtop->r & VT_LVAL)
728 || !(reg_classes[r] & rc)
729 #ifndef TCC_TARGET_X86_64
730 || ((vtop->type.t & VT_BTYPE) == VT_LLONG && !(reg_classes[vtop->r2] & rc2))
731 #endif
734 r = get_reg(rc);
735 #ifndef TCC_TARGET_X86_64
736 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
737 int r2;
738 unsigned long long ll;
739 /* two register type load : expand to two words
740 temporarily */
741 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
742 /* load constant */
743 ll = vtop->c.ull;
744 vtop->c.ui = ll; /* first word */
745 load(r, vtop);
746 vtop->r = r; /* save register value */
747 vpushi(ll >> 32); /* second word */
748 } else if (r >= VT_CONST || /* XXX: test to VT_CONST incorrect ? */
749 (vtop->r & VT_LVAL)) {
750 /* We do not want to modifier the long long
751 pointer here, so the safest (and less
752 efficient) is to save all the other registers
753 in the stack. XXX: totally inefficient. */
754 save_regs(1);
755 /* load from memory */
756 load(r, vtop);
757 vdup();
758 vtop[-1].r = r; /* save register value */
759 /* increment pointer to get second word */
760 vtop->type.t = VT_INT;
761 gaddrof();
762 vpushi(4);
763 gen_op('+');
764 vtop->r |= VT_LVAL;
765 } else {
766 /* move registers */
767 load(r, vtop);
768 vdup();
769 vtop[-1].r = r; /* save register value */
770 vtop->r = vtop[-1].r2;
772 /* allocate second register */
773 r2 = get_reg(rc2);
774 load(r2, vtop);
775 vpop();
776 /* write second register */
777 vtop->r2 = r2;
778 } else
779 #endif
780 if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
781 int t1, t;
782 /* lvalue of scalar type : need to use lvalue type
783 because of possible cast */
784 t = vtop->type.t;
785 t1 = t;
786 /* compute memory access type */
787 if (vtop->r & VT_LVAL_BYTE)
788 t = VT_BYTE;
789 else if (vtop->r & VT_LVAL_SHORT)
790 t = VT_SHORT;
791 if (vtop->r & VT_LVAL_UNSIGNED)
792 t |= VT_UNSIGNED;
793 vtop->type.t = t;
794 load(r, vtop);
795 /* restore wanted type */
796 vtop->type.t = t1;
797 } else {
798 /* one register type load */
799 load(r, vtop);
802 vtop->r = r;
803 #ifdef TCC_TARGET_C67
804 /* uses register pairs for doubles */
805 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
806 vtop->r2 = r+1;
807 #endif
809 return r;
812 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
813 ST_FUNC void gv2(int rc1, int rc2)
815 int v;
817 /* generate more generic register first. But VT_JMP or VT_CMP
818 values must be generated first in all cases to avoid possible
819 reload errors */
820 v = vtop[0].r & VT_VALMASK;
821 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
822 vswap();
823 gv(rc1);
824 vswap();
825 gv(rc2);
826 /* test if reload is needed for first register */
827 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
828 vswap();
829 gv(rc1);
830 vswap();
832 } else {
833 gv(rc2);
834 vswap();
835 gv(rc1);
836 vswap();
837 /* test if reload is needed for first register */
838 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
839 gv(rc2);
844 /* wrapper around RC_FRET to return a register by type */
845 static int rc_fret(int t)
847 #ifdef TCC_TARGET_X86_64
848 if (t == VT_LDOUBLE) {
849 return RC_ST0;
851 #endif
852 return RC_FRET;
855 /* wrapper around REG_FRET to return a register by type */
856 static int reg_fret(int t)
858 #ifdef TCC_TARGET_X86_64
859 if (t == VT_LDOUBLE) {
860 return TREG_ST0;
862 #endif
863 return REG_FRET;
866 /* expand long long on stack in two int registers */
867 static void lexpand(void)
869 int u;
871 u = vtop->type.t & VT_UNSIGNED;
872 gv(RC_INT);
873 vdup();
874 vtop[0].r = vtop[-1].r2;
875 vtop[0].r2 = VT_CONST;
876 vtop[-1].r2 = VT_CONST;
877 vtop[0].type.t = VT_INT | u;
878 vtop[-1].type.t = VT_INT | u;
881 #ifdef TCC_TARGET_ARM
882 /* expand long long on stack */
883 ST_FUNC void lexpand_nr(void)
885 int u,v;
887 u = vtop->type.t & VT_UNSIGNED;
888 vdup();
889 vtop->r2 = VT_CONST;
890 vtop->type.t = VT_INT | u;
891 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
892 if (v == VT_CONST) {
893 vtop[-1].c.ui = vtop->c.ull;
894 vtop->c.ui = vtop->c.ull >> 32;
895 vtop->r = VT_CONST;
896 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
897 vtop->c.ui += 4;
898 vtop->r = vtop[-1].r;
899 } else if (v > VT_CONST) {
900 vtop--;
901 lexpand();
902 } else
903 vtop->r = vtop[-1].r2;
904 vtop[-1].r2 = VT_CONST;
905 vtop[-1].type.t = VT_INT | u;
907 #endif
909 /* build a long long from two ints */
910 static void lbuild(int t)
912 gv2(RC_INT, RC_INT);
913 vtop[-1].r2 = vtop[0].r;
914 vtop[-1].type.t = t;
915 vpop();
918 /* rotate n first stack elements to the bottom
919 I1 ... In -> I2 ... In I1 [top is right]
921 static void vrotb(int n)
923 int i;
924 SValue tmp;
926 tmp = vtop[-n + 1];
927 for(i=-n+1;i!=0;i++)
928 vtop[i] = vtop[i+1];
929 vtop[0] = tmp;
932 /* rotate n first stack elements to the top
933 I1 ... In -> In I1 ... I(n-1) [top is right]
935 ST_FUNC void vrott(int n)
937 int i;
938 SValue tmp;
940 tmp = vtop[0];
941 for(i = 0;i < n - 1; i++)
942 vtop[-i] = vtop[-i - 1];
943 vtop[-n + 1] = tmp;
946 #ifdef TCC_TARGET_ARM
947 /* like vrott but in other direction
948 In ... I1 -> I(n-1) ... I1 In [top is right]
950 ST_FUNC void vnrott(int n)
952 int i;
953 SValue tmp;
955 tmp = vtop[-n + 1];
956 for(i = n - 1; i > 0; i--)
957 vtop[-i] = vtop[-i + 1];
958 vtop[0] = tmp;
960 #endif
962 /* pop stack value */
963 ST_FUNC void vpop(void)
965 int v;
966 v = vtop->r & VT_VALMASK;
967 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
968 /* for x86, we need to pop the FP stack */
969 if (v == TREG_ST0 && !nocode_wanted) {
970 o(0xd8dd); /* fstp %st(0) */
971 } else
972 #endif
973 if (v == VT_JMP || v == VT_JMPI) {
974 /* need to put correct jump if && or || without test */
975 gsym(vtop->c.ul);
977 vtop--;
980 /* convert stack entry to register and duplicate its value in another
981 register */
982 static void gv_dup(void)
984 int rc, t, r, r1;
985 SValue sv;
987 t = vtop->type.t;
988 if ((t & VT_BTYPE) == VT_LLONG) {
989 lexpand();
990 gv_dup();
991 vswap();
992 vrotb(3);
993 gv_dup();
994 vrotb(4);
995 /* stack: H L L1 H1 */
996 lbuild(t);
997 vrotb(3);
998 vrotb(3);
999 vswap();
1000 lbuild(t);
1001 vswap();
1002 } else {
1003 /* duplicate value */
1004 rc = RC_INT;
1005 sv.type.t = VT_INT;
1006 if (is_float(t)) {
1007 rc = RC_FLOAT;
1008 #ifdef TCC_TARGET_X86_64
1009 if ((t & VT_BTYPE) == VT_LDOUBLE) {
1010 rc = RC_ST0;
1012 #endif
1013 sv.type.t = t;
1015 r = gv(rc);
1016 r1 = get_reg(rc);
1017 sv.r = r;
1018 sv.c.ul = 0;
1019 load(r1, &sv); /* move r to r1 */
1020 vdup();
1021 /* duplicates value */
1022 if (r != r1)
1023 vtop->r = r1;
1027 #ifndef TCC_TARGET_X86_64
1028 /* generate CPU independent (unsigned) long long operations */
1029 static void gen_opl(int op)
1031 int t, a, b, op1, c, i;
1032 int func;
1033 unsigned short reg_iret = REG_IRET;
1034 unsigned short reg_lret = REG_LRET;
1035 SValue tmp;
1037 switch(op) {
1038 case '/':
1039 case TOK_PDIV:
1040 func = TOK___divdi3;
1041 goto gen_func;
1042 case TOK_UDIV:
1043 func = TOK___udivdi3;
1044 goto gen_func;
1045 case '%':
1046 func = TOK___moddi3;
1047 goto gen_mod_func;
1048 case TOK_UMOD:
1049 func = TOK___umoddi3;
1050 gen_mod_func:
1051 #ifdef TCC_ARM_EABI
1052 reg_iret = TREG_R2;
1053 reg_lret = TREG_R3;
1054 #endif
1055 gen_func:
1056 /* call generic long long function */
1057 vpush_global_sym(&func_old_type, func);
1058 vrott(3);
1059 gfunc_call(2);
1060 vpushi(0);
1061 vtop->r = reg_iret;
1062 vtop->r2 = reg_lret;
1063 break;
1064 case '^':
1065 case '&':
1066 case '|':
1067 case '*':
1068 case '+':
1069 case '-':
1070 t = vtop->type.t;
1071 vswap();
1072 lexpand();
1073 vrotb(3);
1074 lexpand();
1075 /* stack: L1 H1 L2 H2 */
1076 tmp = vtop[0];
1077 vtop[0] = vtop[-3];
1078 vtop[-3] = tmp;
1079 tmp = vtop[-2];
1080 vtop[-2] = vtop[-3];
1081 vtop[-3] = tmp;
1082 vswap();
1083 /* stack: H1 H2 L1 L2 */
1084 if (op == '*') {
1085 vpushv(vtop - 1);
1086 vpushv(vtop - 1);
1087 gen_op(TOK_UMULL);
1088 lexpand();
1089 /* stack: H1 H2 L1 L2 ML MH */
1090 for(i=0;i<4;i++)
1091 vrotb(6);
1092 /* stack: ML MH H1 H2 L1 L2 */
1093 tmp = vtop[0];
1094 vtop[0] = vtop[-2];
1095 vtop[-2] = tmp;
1096 /* stack: ML MH H1 L2 H2 L1 */
1097 gen_op('*');
1098 vrotb(3);
1099 vrotb(3);
1100 gen_op('*');
1101 /* stack: ML MH M1 M2 */
1102 gen_op('+');
1103 gen_op('+');
1104 } else if (op == '+' || op == '-') {
1105 /* XXX: add non carry method too (for MIPS or alpha) */
1106 if (op == '+')
1107 op1 = TOK_ADDC1;
1108 else
1109 op1 = TOK_SUBC1;
1110 gen_op(op1);
1111 /* stack: H1 H2 (L1 op L2) */
1112 vrotb(3);
1113 vrotb(3);
1114 gen_op(op1 + 1); /* TOK_xxxC2 */
1115 } else {
1116 gen_op(op);
1117 /* stack: H1 H2 (L1 op L2) */
1118 vrotb(3);
1119 vrotb(3);
1120 /* stack: (L1 op L2) H1 H2 */
1121 gen_op(op);
1122 /* stack: (L1 op L2) (H1 op H2) */
1124 /* stack: L H */
1125 lbuild(t);
1126 break;
1127 case TOK_SAR:
1128 case TOK_SHR:
1129 case TOK_SHL:
1130 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1131 t = vtop[-1].type.t;
1132 vswap();
1133 lexpand();
1134 vrotb(3);
1135 /* stack: L H shift */
1136 c = (int)vtop->c.i;
1137 /* constant: simpler */
1138 /* NOTE: all comments are for SHL. the other cases are
1139 done by swaping words */
1140 vpop();
1141 if (op != TOK_SHL)
1142 vswap();
1143 if (c >= 32) {
1144 /* stack: L H */
1145 vpop();
1146 if (c > 32) {
1147 vpushi(c - 32);
1148 gen_op(op);
1150 if (op != TOK_SAR) {
1151 vpushi(0);
1152 } else {
1153 gv_dup();
1154 vpushi(31);
1155 gen_op(TOK_SAR);
1157 vswap();
1158 } else {
1159 vswap();
1160 gv_dup();
1161 /* stack: H L L */
1162 vpushi(c);
1163 gen_op(op);
1164 vswap();
1165 vpushi(32 - c);
1166 if (op == TOK_SHL)
1167 gen_op(TOK_SHR);
1168 else
1169 gen_op(TOK_SHL);
1170 vrotb(3);
1171 /* stack: L L H */
1172 vpushi(c);
1173 if (op == TOK_SHL)
1174 gen_op(TOK_SHL);
1175 else
1176 gen_op(TOK_SHR);
1177 gen_op('|');
1179 if (op != TOK_SHL)
1180 vswap();
1181 lbuild(t);
1182 } else {
1183 /* XXX: should provide a faster fallback on x86 ? */
1184 switch(op) {
1185 case TOK_SAR:
1186 func = TOK___ashrdi3;
1187 goto gen_func;
1188 case TOK_SHR:
1189 func = TOK___lshrdi3;
1190 goto gen_func;
1191 case TOK_SHL:
1192 func = TOK___ashldi3;
1193 goto gen_func;
1196 break;
1197 default:
1198 /* compare operations */
1199 t = vtop->type.t;
1200 vswap();
1201 lexpand();
1202 vrotb(3);
1203 lexpand();
1204 /* stack: L1 H1 L2 H2 */
1205 tmp = vtop[-1];
1206 vtop[-1] = vtop[-2];
1207 vtop[-2] = tmp;
1208 /* stack: L1 L2 H1 H2 */
1209 /* compare high */
1210 op1 = op;
1211 /* when values are equal, we need to compare low words. since
1212 the jump is inverted, we invert the test too. */
1213 if (op1 == TOK_LT)
1214 op1 = TOK_LE;
1215 else if (op1 == TOK_GT)
1216 op1 = TOK_GE;
1217 else if (op1 == TOK_ULT)
1218 op1 = TOK_ULE;
1219 else if (op1 == TOK_UGT)
1220 op1 = TOK_UGE;
1221 a = 0;
1222 b = 0;
1223 gen_op(op1);
1224 if (op1 != TOK_NE) {
1225 a = gtst(1, 0);
1227 if (op != TOK_EQ) {
1228 /* generate non equal test */
1229 /* XXX: NOT PORTABLE yet */
1230 if (a == 0) {
1231 b = gtst(0, 0);
1232 } else {
1233 #if defined(TCC_TARGET_I386)
1234 b = psym(0x850f, 0);
1235 #elif defined(TCC_TARGET_ARM)
1236 b = ind;
1237 o(0x1A000000 | encbranch(ind, 0, 1));
1238 #elif defined(TCC_TARGET_C67)
1239 error("not implemented");
1240 #else
1241 #error not supported
1242 #endif
1245 /* compare low. Always unsigned */
1246 op1 = op;
1247 if (op1 == TOK_LT)
1248 op1 = TOK_ULT;
1249 else if (op1 == TOK_LE)
1250 op1 = TOK_ULE;
1251 else if (op1 == TOK_GT)
1252 op1 = TOK_UGT;
1253 else if (op1 == TOK_GE)
1254 op1 = TOK_UGE;
1255 gen_op(op1);
1256 a = gtst(1, a);
1257 gsym(b);
1258 vseti(VT_JMPI, a);
1259 break;
1262 #endif
1264 /* handle integer constant optimizations and various machine
1265 independent opt */
1266 static void gen_opic(int op)
1268 int c1, c2, t1, t2, n;
1269 SValue *v1, *v2;
1270 long long l1, l2;
1271 typedef unsigned long long U;
1273 v1 = vtop - 1;
1274 v2 = vtop;
1275 t1 = v1->type.t & VT_BTYPE;
1276 t2 = v2->type.t & VT_BTYPE;
1278 if (t1 == VT_LLONG)
1279 l1 = v1->c.ll;
1280 else if (v1->type.t & VT_UNSIGNED)
1281 l1 = v1->c.ui;
1282 else
1283 l1 = v1->c.i;
1285 if (t2 == VT_LLONG)
1286 l2 = v2->c.ll;
1287 else if (v2->type.t & VT_UNSIGNED)
1288 l2 = v2->c.ui;
1289 else
1290 l2 = v2->c.i;
1292 /* currently, we cannot do computations with forward symbols */
1293 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1294 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1295 if (c1 && c2) {
1296 switch(op) {
1297 case '+': l1 += l2; break;
1298 case '-': l1 -= l2; break;
1299 case '&': l1 &= l2; break;
1300 case '^': l1 ^= l2; break;
1301 case '|': l1 |= l2; break;
1302 case '*': l1 *= l2; break;
1304 case TOK_PDIV:
1305 case '/':
1306 case '%':
1307 case TOK_UDIV:
1308 case TOK_UMOD:
1309 /* if division by zero, generate explicit division */
1310 if (l2 == 0) {
1311 if (const_wanted)
1312 error("division by zero in constant");
1313 goto general_case;
1315 switch(op) {
1316 default: l1 /= l2; break;
1317 case '%': l1 %= l2; break;
1318 case TOK_UDIV: l1 = (U)l1 / l2; break;
1319 case TOK_UMOD: l1 = (U)l1 % l2; break;
1321 break;
1322 case TOK_SHL: l1 <<= l2; break;
1323 case TOK_SHR: l1 = (U)l1 >> l2; break;
1324 case TOK_SAR: l1 >>= l2; break;
1325 /* tests */
1326 case TOK_ULT: l1 = (U)l1 < (U)l2; break;
1327 case TOK_UGE: l1 = (U)l1 >= (U)l2; break;
1328 case TOK_EQ: l1 = l1 == l2; break;
1329 case TOK_NE: l1 = l1 != l2; break;
1330 case TOK_ULE: l1 = (U)l1 <= (U)l2; break;
1331 case TOK_UGT: l1 = (U)l1 > (U)l2; break;
1332 case TOK_LT: l1 = l1 < l2; break;
1333 case TOK_GE: l1 = l1 >= l2; break;
1334 case TOK_LE: l1 = l1 <= l2; break;
1335 case TOK_GT: l1 = l1 > l2; break;
1336 /* logical */
1337 case TOK_LAND: l1 = l1 && l2; break;
1338 case TOK_LOR: l1 = l1 || l2; break;
1339 default:
1340 goto general_case;
1342 v1->c.ll = l1;
1343 vtop--;
1344 } else {
1345 /* if commutative ops, put c2 as constant */
1346 if (c1 && (op == '+' || op == '&' || op == '^' ||
1347 op == '|' || op == '*')) {
1348 vswap();
1349 c2 = c1; //c = c1, c1 = c2, c2 = c;
1350 l2 = l1; //l = l1, l1 = l2, l2 = l;
1352 /* Filter out NOP operations like x*1, x-0, x&-1... */
1353 if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
1354 op == TOK_PDIV) &&
1355 l2 == 1) ||
1356 ((op == '+' || op == '-' || op == '|' || op == '^' ||
1357 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
1358 l2 == 0) ||
1359 (op == '&' &&
1360 l2 == -1))) {
1361 /* nothing to do */
1362 vtop--;
1363 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
1364 /* try to use shifts instead of muls or divs */
1365 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
1366 n = -1;
1367 while (l2) {
1368 l2 >>= 1;
1369 n++;
1371 vtop->c.ll = n;
1372 if (op == '*')
1373 op = TOK_SHL;
1374 else if (op == TOK_PDIV)
1375 op = TOK_SAR;
1376 else
1377 op = TOK_SHR;
1379 goto general_case;
1380 } else if (c2 && (op == '+' || op == '-') &&
1381 (((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM))
1382 || (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
1383 /* symbol + constant case */
1384 if (op == '-')
1385 l2 = -l2;
1386 vtop--;
1387 vtop->c.ll += l2;
1388 } else {
1389 general_case:
1390 if (!nocode_wanted) {
1391 /* call low level op generator */
1392 if (t1 == VT_LLONG || t2 == VT_LLONG)
1393 gen_opl(op);
1394 else
1395 gen_opi(op);
1396 } else {
1397 vtop--;
1403 /* generate a floating point operation with constant propagation */
1404 static void gen_opif(int op)
1406 int c1, c2;
1407 SValue *v1, *v2;
1408 long double f1, f2;
1410 v1 = vtop - 1;
1411 v2 = vtop;
1412 /* currently, we cannot do computations with forward symbols */
1413 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1414 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1415 if (c1 && c2) {
1416 if (v1->type.t == VT_FLOAT) {
1417 f1 = v1->c.f;
1418 f2 = v2->c.f;
1419 } else if (v1->type.t == VT_DOUBLE) {
1420 f1 = v1->c.d;
1421 f2 = v2->c.d;
1422 } else {
1423 f1 = v1->c.ld;
1424 f2 = v2->c.ld;
1427 /* NOTE: we only do constant propagation if finite number (not
1428 NaN or infinity) (ANSI spec) */
1429 if (!ieee_finite(f1) || !ieee_finite(f2))
1430 goto general_case;
1432 switch(op) {
1433 case '+': f1 += f2; break;
1434 case '-': f1 -= f2; break;
1435 case '*': f1 *= f2; break;
1436 case '/':
1437 if (f2 == 0.0) {
1438 if (const_wanted)
1439 error("division by zero in constant");
1440 goto general_case;
1442 f1 /= f2;
1443 break;
1444 /* XXX: also handles tests ? */
1445 default:
1446 goto general_case;
1448 /* XXX: overflow test ? */
1449 if (v1->type.t == VT_FLOAT) {
1450 v1->c.f = f1;
1451 } else if (v1->type.t == VT_DOUBLE) {
1452 v1->c.d = f1;
1453 } else {
1454 v1->c.ld = f1;
1456 vtop--;
1457 } else {
1458 general_case:
1459 if (!nocode_wanted) {
1460 gen_opf(op);
1461 } else {
1462 vtop--;
1467 static int pointed_size(CType *type)
1469 int align;
1470 return type_size(pointed_type(type), &align);
1473 static inline int is_null_pointer(SValue *p)
1475 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
1476 return 0;
1477 return ((p->type.t & VT_BTYPE) == VT_INT && p->c.i == 0) ||
1478 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.ll == 0);
1481 static inline int is_integer_btype(int bt)
1483 return (bt == VT_BYTE || bt == VT_SHORT ||
1484 bt == VT_INT || bt == VT_LLONG);
1487 /* check types for comparison or substraction of pointers */
1488 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
1490 CType *type1, *type2, tmp_type1, tmp_type2;
1491 int bt1, bt2;
1493 /* null pointers are accepted for all comparisons as gcc */
1494 if (is_null_pointer(p1) || is_null_pointer(p2))
1495 return;
1496 type1 = &p1->type;
1497 type2 = &p2->type;
1498 bt1 = type1->t & VT_BTYPE;
1499 bt2 = type2->t & VT_BTYPE;
1500 /* accept comparison between pointer and integer with a warning */
1501 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
1502 if (op != TOK_LOR && op != TOK_LAND )
1503 warning("comparison between pointer and integer");
1504 return;
1507 /* both must be pointers or implicit function pointers */
1508 if (bt1 == VT_PTR) {
1509 type1 = pointed_type(type1);
1510 } else if (bt1 != VT_FUNC)
1511 goto invalid_operands;
1513 if (bt2 == VT_PTR) {
1514 type2 = pointed_type(type2);
1515 } else if (bt2 != VT_FUNC) {
1516 invalid_operands:
1517 error("invalid operands to binary %s", get_tok_str(op, NULL));
1519 if ((type1->t & VT_BTYPE) == VT_VOID ||
1520 (type2->t & VT_BTYPE) == VT_VOID)
1521 return;
1522 tmp_type1 = *type1;
1523 tmp_type2 = *type2;
1524 tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1525 tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1526 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
1527 /* gcc-like error if '-' is used */
1528 if (op == '-')
1529 goto invalid_operands;
1530 else
1531 warning("comparison of distinct pointer types lacks a cast");
1535 /* generic gen_op: handles types problems */
1536 ST_FUNC void gen_op(int op)
1538 int u, t1, t2, bt1, bt2, t;
1539 CType type1;
1541 t1 = vtop[-1].type.t;
1542 t2 = vtop[0].type.t;
1543 bt1 = t1 & VT_BTYPE;
1544 bt2 = t2 & VT_BTYPE;
1546 if (bt1 == VT_PTR || bt2 == VT_PTR) {
1547 /* at least one operand is a pointer */
1548 /* relationnal op: must be both pointers */
1549 if (op >= TOK_ULT && op <= TOK_LOR) {
1550 check_comparison_pointer_types(vtop - 1, vtop, op);
1551 /* pointers are handled are unsigned */
1552 #ifdef TCC_TARGET_X86_64
1553 t = VT_LLONG | VT_UNSIGNED;
1554 #else
1555 t = VT_INT | VT_UNSIGNED;
1556 #endif
1557 goto std_op;
1559 /* if both pointers, then it must be the '-' op */
1560 if (bt1 == VT_PTR && bt2 == VT_PTR) {
1561 if (op != '-')
1562 error("cannot use pointers here");
1563 check_comparison_pointer_types(vtop - 1, vtop, op);
1564 /* XXX: check that types are compatible */
1565 u = pointed_size(&vtop[-1].type);
1566 gen_opic(op);
1567 /* set to integer type */
1568 #ifdef TCC_TARGET_X86_64
1569 vtop->type.t = VT_LLONG;
1570 #else
1571 vtop->type.t = VT_INT;
1572 #endif
1573 vpushi(u);
1574 gen_op(TOK_PDIV);
1575 } else {
1576 /* exactly one pointer : must be '+' or '-'. */
1577 if (op != '-' && op != '+')
1578 error("cannot use pointers here");
1579 /* Put pointer as first operand */
1580 if (bt2 == VT_PTR) {
1581 vswap();
1582 swap(&t1, &t2);
1584 type1 = vtop[-1].type;
1585 type1.t &= ~VT_ARRAY;
1586 u = pointed_size(&vtop[-1].type);
1587 if (u < 0)
1588 error("unknown array element size");
1589 #ifdef TCC_TARGET_X86_64
1590 vpushll(u);
1591 #else
1592 /* XXX: cast to int ? (long long case) */
1593 vpushi(u);
1594 #endif
1595 gen_op('*');
1596 #ifdef CONFIG_TCC_BCHECK
1597 /* if evaluating constant expression, no code should be
1598 generated, so no bound check */
1599 if (tcc_state->do_bounds_check && !const_wanted) {
1600 /* if bounded pointers, we generate a special code to
1601 test bounds */
1602 if (op == '-') {
1603 vpushi(0);
1604 vswap();
1605 gen_op('-');
1607 gen_bounded_ptr_add();
1608 } else
1609 #endif
1611 gen_opic(op);
1613 /* put again type if gen_opic() swaped operands */
1614 vtop->type = type1;
1616 } else if (is_float(bt1) || is_float(bt2)) {
1617 /* compute bigger type and do implicit casts */
1618 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
1619 t = VT_LDOUBLE;
1620 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
1621 t = VT_DOUBLE;
1622 } else {
1623 t = VT_FLOAT;
1625 /* floats can only be used for a few operations */
1626 if (op != '+' && op != '-' && op != '*' && op != '/' &&
1627 (op < TOK_ULT || op > TOK_GT))
1628 error("invalid operands for binary operation");
1629 goto std_op;
1630 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
1631 /* cast to biggest op */
1632 t = VT_LLONG;
1633 /* convert to unsigned if it does not fit in a long long */
1634 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
1635 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
1636 t |= VT_UNSIGNED;
1637 goto std_op;
1638 } else {
1639 /* integer operations */
1640 t = VT_INT;
1641 /* convert to unsigned if it does not fit in an integer */
1642 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
1643 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
1644 t |= VT_UNSIGNED;
1645 std_op:
1646 /* XXX: currently, some unsigned operations are explicit, so
1647 we modify them here */
1648 if (t & VT_UNSIGNED) {
1649 if (op == TOK_SAR)
1650 op = TOK_SHR;
1651 else if (op == '/')
1652 op = TOK_UDIV;
1653 else if (op == '%')
1654 op = TOK_UMOD;
1655 else if (op == TOK_LT)
1656 op = TOK_ULT;
1657 else if (op == TOK_GT)
1658 op = TOK_UGT;
1659 else if (op == TOK_LE)
1660 op = TOK_ULE;
1661 else if (op == TOK_GE)
1662 op = TOK_UGE;
1664 vswap();
1665 type1.t = t;
1666 gen_cast(&type1);
1667 vswap();
1668 /* special case for shifts and long long: we keep the shift as
1669 an integer */
1670 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
1671 type1.t = VT_INT;
1672 gen_cast(&type1);
1673 if (is_float(t))
1674 gen_opif(op);
1675 else
1676 gen_opic(op);
1677 if (op >= TOK_ULT && op <= TOK_GT) {
1678 /* relationnal op: the result is an int */
1679 vtop->type.t = VT_INT;
1680 } else {
1681 vtop->type.t = t;
1686 #ifndef TCC_TARGET_ARM
1687 /* generic itof for unsigned long long case */
1688 static void gen_cvt_itof1(int t)
1690 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
1691 (VT_LLONG | VT_UNSIGNED)) {
1693 if (t == VT_FLOAT)
1694 vpush_global_sym(&func_old_type, TOK___floatundisf);
1695 #if LDOUBLE_SIZE != 8
1696 else if (t == VT_LDOUBLE)
1697 vpush_global_sym(&func_old_type, TOK___floatundixf);
1698 #endif
1699 else
1700 vpush_global_sym(&func_old_type, TOK___floatundidf);
1701 vrott(2);
1702 gfunc_call(1);
1703 vpushi(0);
1704 vtop->r = reg_fret(t);
1705 } else {
1706 gen_cvt_itof(t);
1709 #endif
1711 /* generic ftoi for unsigned long long case */
1712 static void gen_cvt_ftoi1(int t)
1714 int st;
1716 if (t == (VT_LLONG | VT_UNSIGNED)) {
1717 /* not handled natively */
1718 st = vtop->type.t & VT_BTYPE;
1719 if (st == VT_FLOAT)
1720 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
1721 #if LDOUBLE_SIZE != 8
1722 else if (st == VT_LDOUBLE)
1723 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
1724 #endif
1725 else
1726 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
1727 vrott(2);
1728 gfunc_call(1);
1729 vpushi(0);
1730 vtop->r = REG_IRET;
1731 vtop->r2 = REG_LRET;
1732 } else {
1733 gen_cvt_ftoi(t);
1737 /* force char or short cast */
1738 static void force_charshort_cast(int t)
1740 int bits, dbt;
1741 dbt = t & VT_BTYPE;
1742 /* XXX: add optimization if lvalue : just change type and offset */
1743 if (dbt == VT_BYTE)
1744 bits = 8;
1745 else
1746 bits = 16;
1747 if (t & VT_UNSIGNED) {
1748 vpushi((1 << bits) - 1);
1749 gen_op('&');
1750 } else {
1751 bits = 32 - bits;
1752 vpushi(bits);
1753 gen_op(TOK_SHL);
1754 /* result must be signed or the SAR is converted to an SHL
1755 This was not the case when "t" was a signed short
1756 and the last value on the stack was an unsigned int */
1757 vtop->type.t &= ~VT_UNSIGNED;
1758 vpushi(bits);
1759 gen_op(TOK_SAR);
1763 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
1764 static void gen_cast(CType *type)
1766 int sbt, dbt, sf, df, c, p;
1768 /* special delayed cast for char/short */
1769 /* XXX: in some cases (multiple cascaded casts), it may still
1770 be incorrect */
1771 if (vtop->r & VT_MUSTCAST) {
1772 vtop->r &= ~VT_MUSTCAST;
1773 force_charshort_cast(vtop->type.t);
1776 /* bitfields first get cast to ints */
1777 if (vtop->type.t & VT_BITFIELD) {
1778 gv(RC_INT);
1781 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
1782 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
1784 if (sbt != dbt) {
1785 sf = is_float(sbt);
1786 df = is_float(dbt);
1787 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1788 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
1789 if (c) {
1790 /* constant case: we can do it now */
1791 /* XXX: in ISOC, cannot do it if error in convert */
1792 if (sbt == VT_FLOAT)
1793 vtop->c.ld = vtop->c.f;
1794 else if (sbt == VT_DOUBLE)
1795 vtop->c.ld = vtop->c.d;
1797 if (df) {
1798 if ((sbt & VT_BTYPE) == VT_LLONG) {
1799 if (sbt & VT_UNSIGNED)
1800 vtop->c.ld = vtop->c.ull;
1801 else
1802 vtop->c.ld = vtop->c.ll;
1803 } else if(!sf) {
1804 if (sbt & VT_UNSIGNED)
1805 vtop->c.ld = vtop->c.ui;
1806 else
1807 vtop->c.ld = vtop->c.i;
1810 if (dbt == VT_FLOAT)
1811 vtop->c.f = (float)vtop->c.ld;
1812 else if (dbt == VT_DOUBLE)
1813 vtop->c.d = (double)vtop->c.ld;
1814 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
1815 vtop->c.ull = (unsigned long long)vtop->c.ld;
1816 } else if (sf && dbt == VT_BOOL) {
1817 vtop->c.i = (vtop->c.ld != 0);
1818 } else {
1819 if(sf)
1820 vtop->c.ll = (long long)vtop->c.ld;
1821 else if (sbt == (VT_LLONG|VT_UNSIGNED))
1822 vtop->c.ll = vtop->c.ull;
1823 else if (sbt & VT_UNSIGNED)
1824 vtop->c.ll = vtop->c.ui;
1825 #ifdef TCC_TARGET_X86_64
1826 else if (sbt == VT_PTR)
1828 #endif
1829 else if (sbt != VT_LLONG)
1830 vtop->c.ll = vtop->c.i;
1832 if (dbt == (VT_LLONG|VT_UNSIGNED))
1833 vtop->c.ull = vtop->c.ll;
1834 else if (dbt == VT_BOOL)
1835 vtop->c.i = (vtop->c.ll != 0);
1836 else if (dbt != VT_LLONG) {
1837 int s = 0;
1838 if ((dbt & VT_BTYPE) == VT_BYTE)
1839 s = 24;
1840 else if ((dbt & VT_BTYPE) == VT_SHORT)
1841 s = 16;
1843 if(dbt & VT_UNSIGNED)
1844 vtop->c.ui = ((unsigned int)vtop->c.ll << s) >> s;
1845 else
1846 vtop->c.i = ((int)vtop->c.ll << s) >> s;
1849 } else if (p && dbt == VT_BOOL) {
1850 vtop->r = VT_CONST;
1851 vtop->c.i = 1;
1852 } else if (!nocode_wanted) {
1853 /* non constant case: generate code */
1854 if (sf && df) {
1855 /* convert from fp to fp */
1856 gen_cvt_ftof(dbt);
1857 } else if (df) {
1858 /* convert int to fp */
1859 gen_cvt_itof1(dbt);
1860 } else if (sf) {
1861 /* convert fp to int */
1862 if (dbt == VT_BOOL) {
1863 vpushi(0);
1864 gen_op(TOK_NE);
1865 } else {
1866 /* we handle char/short/etc... with generic code */
1867 if (dbt != (VT_INT | VT_UNSIGNED) &&
1868 dbt != (VT_LLONG | VT_UNSIGNED) &&
1869 dbt != VT_LLONG)
1870 dbt = VT_INT;
1871 gen_cvt_ftoi1(dbt);
1872 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
1873 /* additional cast for char/short... */
1874 vtop->type.t = dbt;
1875 gen_cast(type);
1878 #ifndef TCC_TARGET_X86_64
1879 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
1880 if ((sbt & VT_BTYPE) != VT_LLONG) {
1881 /* scalar to long long */
1882 /* machine independent conversion */
1883 gv(RC_INT);
1884 /* generate high word */
1885 if (sbt == (VT_INT | VT_UNSIGNED)) {
1886 vpushi(0);
1887 gv(RC_INT);
1888 } else {
1889 if (sbt == VT_PTR) {
1890 /* cast from pointer to int before we apply
1891 shift operation, which pointers don't support*/
1892 gen_cast(&int_type);
1894 gv_dup();
1895 vpushi(31);
1896 gen_op(TOK_SAR);
1898 /* patch second register */
1899 vtop[-1].r2 = vtop->r;
1900 vpop();
1902 #else
1903 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
1904 (dbt & VT_BTYPE) == VT_PTR ||
1905 (dbt & VT_BTYPE) == VT_FUNC) {
1906 if ((sbt & VT_BTYPE) != VT_LLONG &&
1907 (sbt & VT_BTYPE) != VT_PTR &&
1908 (sbt & VT_BTYPE) != VT_FUNC) {
1909 /* need to convert from 32bit to 64bit */
1910 int r = gv(RC_INT);
1911 if (sbt != (VT_INT | VT_UNSIGNED)) {
1912 /* x86_64 specific: movslq */
1913 o(0x6348);
1914 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
1917 #endif
1918 } else if (dbt == VT_BOOL) {
1919 /* scalar to bool */
1920 vpushi(0);
1921 gen_op(TOK_NE);
1922 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
1923 (dbt & VT_BTYPE) == VT_SHORT) {
1924 if (sbt == VT_PTR) {
1925 vtop->type.t = VT_INT;
1926 warning("nonportable conversion from pointer to char/short");
1928 force_charshort_cast(dbt);
1929 } else if ((dbt & VT_BTYPE) == VT_INT) {
1930 /* scalar to int */
1931 if (sbt == VT_LLONG) {
1932 /* from long long: just take low order word */
1933 lexpand();
1934 vpop();
1936 /* if lvalue and single word type, nothing to do because
1937 the lvalue already contains the real type size (see
1938 VT_LVAL_xxx constants) */
1941 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
1942 /* if we are casting between pointer types,
1943 we must update the VT_LVAL_xxx size */
1944 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
1945 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
1947 vtop->type = *type;
1950 /* return type size. Put alignment at 'a' */
1951 ST_FUNC int type_size(CType *type, int *a)
1953 Sym *s;
1954 int bt;
1956 bt = type->t & VT_BTYPE;
1957 if (bt == VT_STRUCT) {
1958 /* struct/union */
1959 s = type->ref;
1960 *a = s->r & 0xffffff;
1961 return s->c;
1962 } else if (bt == VT_PTR) {
1963 if (type->t & VT_ARRAY) {
1964 int ts;
1966 s = type->ref;
1967 ts = type_size(&s->type, a);
1969 if (ts < 0 && s->c < 0)
1970 ts = -ts;
1972 return ts * s->c;
1973 } else {
1974 *a = PTR_SIZE;
1975 return PTR_SIZE;
1977 } else if (bt == VT_LDOUBLE) {
1978 *a = LDOUBLE_ALIGN;
1979 return LDOUBLE_SIZE;
1980 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
1981 #ifdef TCC_TARGET_I386
1982 #ifdef TCC_TARGET_PE
1983 *a = 8;
1984 #else
1985 *a = 4;
1986 #endif
1987 #elif defined(TCC_TARGET_ARM)
1988 #ifdef TCC_ARM_EABI
1989 *a = 8;
1990 #else
1991 *a = 4;
1992 #endif
1993 #else
1994 *a = 8;
1995 #endif
1996 return 8;
1997 } else if (bt == VT_INT || bt == VT_ENUM || bt == VT_FLOAT) {
1998 *a = 4;
1999 return 4;
2000 } else if (bt == VT_SHORT) {
2001 *a = 2;
2002 return 2;
2003 } else {
2004 /* char, void, function, _Bool */
2005 *a = 1;
2006 return 1;
2010 /* return the pointed type of t */
2011 static inline CType *pointed_type(CType *type)
2013 return &type->ref->type;
2016 /* modify type so that its it is a pointer to type. */
2017 ST_FUNC void mk_pointer(CType *type)
2019 Sym *s;
2020 s = sym_push(SYM_FIELD, type, 0, -1);
2021 type->t = VT_PTR | (type->t & ~VT_TYPE);
2022 type->ref = s;
2025 /* compare function types. OLD functions match any new functions */
2026 static int is_compatible_func(CType *type1, CType *type2)
2028 Sym *s1, *s2;
2030 s1 = type1->ref;
2031 s2 = type2->ref;
2032 if (!is_compatible_types(&s1->type, &s2->type))
2033 return 0;
2034 /* check func_call */
2035 if (FUNC_CALL(s1->r) != FUNC_CALL(s2->r))
2036 return 0;
2037 /* XXX: not complete */
2038 if (s1->c == FUNC_OLD || s2->c == FUNC_OLD)
2039 return 1;
2040 if (s1->c != s2->c)
2041 return 0;
2042 while (s1 != NULL) {
2043 if (s2 == NULL)
2044 return 0;
2045 if (!is_compatible_parameter_types(&s1->type, &s2->type))
2046 return 0;
2047 s1 = s1->next;
2048 s2 = s2->next;
2050 if (s2)
2051 return 0;
2052 return 1;
2055 /* return true if type1 and type2 are the same. If unqualified is
2056 true, qualifiers on the types are ignored.
2058 - enums are not checked as gcc __builtin_types_compatible_p ()
2060 static int compare_types(CType *type1, CType *type2, int unqualified)
2062 int bt1, t1, t2;
2064 t1 = type1->t & VT_TYPE;
2065 t2 = type2->t & VT_TYPE;
2066 if (unqualified) {
2067 /* strip qualifiers before comparing */
2068 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
2069 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
2071 /* XXX: bitfields ? */
2072 if (t1 != t2)
2073 return 0;
2074 /* test more complicated cases */
2075 bt1 = t1 & VT_BTYPE;
2076 if (bt1 == VT_PTR) {
2077 type1 = pointed_type(type1);
2078 type2 = pointed_type(type2);
2079 return is_compatible_types(type1, type2);
2080 } else if (bt1 == VT_STRUCT) {
2081 return (type1->ref == type2->ref);
2082 } else if (bt1 == VT_FUNC) {
2083 return is_compatible_func(type1, type2);
2084 } else {
2085 return 1;
2089 /* return true if type1 and type2 are exactly the same (including
2090 qualifiers).
2092 static int is_compatible_types(CType *type1, CType *type2)
2094 return compare_types(type1,type2,0);
2097 /* return true if type1 and type2 are the same (ignoring qualifiers).
2099 static int is_compatible_parameter_types(CType *type1, CType *type2)
2101 return compare_types(type1,type2,1);
2104 /* print a type. If 'varstr' is not NULL, then the variable is also
2105 printed in the type */
2106 /* XXX: union */
2107 /* XXX: add array and function pointers */
2108 static void type_to_str(char *buf, int buf_size,
2109 CType *type, const char *varstr)
2111 int bt, v, t;
2112 Sym *s, *sa;
2113 char buf1[256];
2114 const char *tstr;
2116 t = type->t & VT_TYPE;
2117 bt = t & VT_BTYPE;
2118 buf[0] = '\0';
2119 if (t & VT_CONSTANT)
2120 pstrcat(buf, buf_size, "const ");
2121 if (t & VT_VOLATILE)
2122 pstrcat(buf, buf_size, "volatile ");
2123 if (t & VT_UNSIGNED)
2124 pstrcat(buf, buf_size, "unsigned ");
2125 switch(bt) {
2126 case VT_VOID:
2127 tstr = "void";
2128 goto add_tstr;
2129 case VT_BOOL:
2130 tstr = "_Bool";
2131 goto add_tstr;
2132 case VT_BYTE:
2133 tstr = "char";
2134 goto add_tstr;
2135 case VT_SHORT:
2136 tstr = "short";
2137 goto add_tstr;
2138 case VT_INT:
2139 tstr = "int";
2140 goto add_tstr;
2141 case VT_LONG:
2142 tstr = "long";
2143 goto add_tstr;
2144 case VT_LLONG:
2145 tstr = "long long";
2146 goto add_tstr;
2147 case VT_FLOAT:
2148 tstr = "float";
2149 goto add_tstr;
2150 case VT_DOUBLE:
2151 tstr = "double";
2152 goto add_tstr;
2153 case VT_LDOUBLE:
2154 tstr = "long double";
2155 add_tstr:
2156 pstrcat(buf, buf_size, tstr);
2157 break;
2158 case VT_ENUM:
2159 case VT_STRUCT:
2160 if (bt == VT_STRUCT)
2161 tstr = "struct ";
2162 else
2163 tstr = "enum ";
2164 pstrcat(buf, buf_size, tstr);
2165 v = type->ref->v & ~SYM_STRUCT;
2166 if (v >= SYM_FIRST_ANOM)
2167 pstrcat(buf, buf_size, "<anonymous>");
2168 else
2169 pstrcat(buf, buf_size, get_tok_str(v, NULL));
2170 break;
2171 case VT_FUNC:
2172 s = type->ref;
2173 type_to_str(buf, buf_size, &s->type, varstr);
2174 pstrcat(buf, buf_size, "(");
2175 sa = s->next;
2176 while (sa != NULL) {
2177 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
2178 pstrcat(buf, buf_size, buf1);
2179 sa = sa->next;
2180 if (sa)
2181 pstrcat(buf, buf_size, ", ");
2183 pstrcat(buf, buf_size, ")");
2184 goto no_var;
2185 case VT_PTR:
2186 s = type->ref;
2187 pstrcpy(buf1, sizeof(buf1), "*");
2188 if (varstr)
2189 pstrcat(buf1, sizeof(buf1), varstr);
2190 type_to_str(buf, buf_size, &s->type, buf1);
2191 goto no_var;
2193 if (varstr) {
2194 pstrcat(buf, buf_size, " ");
2195 pstrcat(buf, buf_size, varstr);
2197 no_var: ;
2200 /* verify type compatibility to store vtop in 'dt' type, and generate
2201 casts if needed. */
2202 static void gen_assign_cast(CType *dt)
2204 CType *st, *type1, *type2, tmp_type1, tmp_type2;
2205 char buf1[256], buf2[256];
2206 int dbt, sbt;
2208 st = &vtop->type; /* source type */
2209 dbt = dt->t & VT_BTYPE;
2210 sbt = st->t & VT_BTYPE;
2211 if (dt->t & VT_CONSTANT)
2212 warning("assignment of read-only location");
2213 switch(dbt) {
2214 case VT_PTR:
2215 /* special cases for pointers */
2216 /* '0' can also be a pointer */
2217 if (is_null_pointer(vtop))
2218 goto type_ok;
2219 /* accept implicit pointer to integer cast with warning */
2220 if (is_integer_btype(sbt)) {
2221 warning("assignment makes pointer from integer without a cast");
2222 goto type_ok;
2224 type1 = pointed_type(dt);
2225 /* a function is implicitely a function pointer */
2226 if (sbt == VT_FUNC) {
2227 if ((type1->t & VT_BTYPE) != VT_VOID &&
2228 !is_compatible_types(pointed_type(dt), st))
2229 warning("assignment from incompatible pointer type");
2230 goto type_ok;
2232 if (sbt != VT_PTR)
2233 goto error;
2234 type2 = pointed_type(st);
2235 if ((type1->t & VT_BTYPE) == VT_VOID ||
2236 (type2->t & VT_BTYPE) == VT_VOID) {
2237 /* void * can match anything */
2238 } else {
2239 /* exact type match, except for unsigned */
2240 tmp_type1 = *type1;
2241 tmp_type2 = *type2;
2242 tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
2243 tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
2244 if (!is_compatible_types(&tmp_type1, &tmp_type2))
2245 warning("assignment from incompatible pointer type");
2247 /* check const and volatile */
2248 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
2249 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
2250 warning("assignment discards qualifiers from pointer target type");
2251 break;
2252 case VT_BYTE:
2253 case VT_SHORT:
2254 case VT_INT:
2255 case VT_LLONG:
2256 if (sbt == VT_PTR || sbt == VT_FUNC) {
2257 warning("assignment makes integer from pointer without a cast");
2259 /* XXX: more tests */
2260 break;
2261 case VT_STRUCT:
2262 tmp_type1 = *dt;
2263 tmp_type2 = *st;
2264 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2265 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2266 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2267 error:
2268 type_to_str(buf1, sizeof(buf1), st, NULL);
2269 type_to_str(buf2, sizeof(buf2), dt, NULL);
2270 error("cannot cast '%s' to '%s'", buf1, buf2);
2272 break;
2274 type_ok:
2275 gen_cast(dt);
2278 /* store vtop in lvalue pushed on stack */
2279 ST_FUNC void vstore(void)
2281 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
2283 ft = vtop[-1].type.t;
2284 sbt = vtop->type.t & VT_BTYPE;
2285 dbt = ft & VT_BTYPE;
2286 if (((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
2287 (sbt == VT_INT && dbt == VT_SHORT)) {
2288 /* optimize char/short casts */
2289 delayed_cast = VT_MUSTCAST;
2290 vtop->type.t = ft & (VT_TYPE & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT)));
2291 /* XXX: factorize */
2292 if (ft & VT_CONSTANT)
2293 warning("assignment of read-only location");
2294 } else {
2295 delayed_cast = 0;
2296 if (!(ft & VT_BITFIELD))
2297 gen_assign_cast(&vtop[-1].type);
2300 if (sbt == VT_STRUCT) {
2301 /* if structure, only generate pointer */
2302 /* structure assignment : generate memcpy */
2303 /* XXX: optimize if small size */
2304 if (!nocode_wanted) {
2305 size = type_size(&vtop->type, &align);
2307 /* destination */
2308 vswap();
2309 vtop->type.t = VT_PTR;
2310 gaddrof();
2312 /* address of memcpy() */
2313 #ifdef TCC_ARM_EABI
2314 if(!(align & 7))
2315 vpush_global_sym(&func_old_type, TOK_memcpy8);
2316 else if(!(align & 3))
2317 vpush_global_sym(&func_old_type, TOK_memcpy4);
2318 else
2319 #endif
2320 vpush_global_sym(&func_old_type, TOK_memcpy);
2322 vswap();
2323 /* source */
2324 vpushv(vtop - 2);
2325 vtop->type.t = VT_PTR;
2326 gaddrof();
2327 /* type size */
2328 vpushi(size);
2329 gfunc_call(3);
2330 } else {
2331 vswap();
2332 vpop();
2334 /* leave source on stack */
2335 } else if (ft & VT_BITFIELD) {
2336 /* bitfield store handling */
2337 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
2338 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
2339 /* remove bit field info to avoid loops */
2340 vtop[-1].type.t = ft & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
2342 /* duplicate source into other register */
2343 gv_dup();
2344 vswap();
2345 vrott(3);
2347 if((ft & VT_BTYPE) == VT_BOOL) {
2348 gen_cast(&vtop[-1].type);
2349 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
2352 /* duplicate destination */
2353 vdup();
2354 vtop[-1] = vtop[-2];
2356 /* mask and shift source */
2357 if((ft & VT_BTYPE) != VT_BOOL) {
2358 if((ft & VT_BTYPE) == VT_LLONG) {
2359 vpushll((1ULL << bit_size) - 1ULL);
2360 } else {
2361 vpushi((1 << bit_size) - 1);
2363 gen_op('&');
2365 vpushi(bit_pos);
2366 gen_op(TOK_SHL);
2367 /* load destination, mask and or with source */
2368 vswap();
2369 if((ft & VT_BTYPE) == VT_LLONG) {
2370 vpushll(~(((1ULL << bit_size) - 1ULL) << bit_pos));
2371 } else {
2372 vpushi(~(((1 << bit_size) - 1) << bit_pos));
2374 gen_op('&');
2375 gen_op('|');
2376 /* store result */
2377 vstore();
2379 /* pop off shifted source from "duplicate source..." above */
2380 vpop();
2382 } else {
2383 #ifdef CONFIG_TCC_BCHECK
2384 /* bound check case */
2385 if (vtop[-1].r & VT_MUSTBOUND) {
2386 vswap();
2387 gbound();
2388 vswap();
2390 #endif
2391 if (!nocode_wanted) {
2392 rc = RC_INT;
2393 if (is_float(ft)) {
2394 rc = RC_FLOAT;
2395 #ifdef TCC_TARGET_X86_64
2396 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
2397 rc = RC_ST0;
2399 #endif
2401 r = gv(rc); /* generate value */
2402 /* if lvalue was saved on stack, must read it */
2403 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
2404 SValue sv;
2405 t = get_reg(RC_INT);
2406 #ifdef TCC_TARGET_X86_64
2407 sv.type.t = VT_PTR;
2408 #else
2409 sv.type.t = VT_INT;
2410 #endif
2411 sv.r = VT_LOCAL | VT_LVAL;
2412 sv.c.ul = vtop[-1].c.ul;
2413 load(t, &sv);
2414 vtop[-1].r = t | VT_LVAL;
2416 store(r, vtop - 1);
2417 #ifndef TCC_TARGET_X86_64
2418 /* two word case handling : store second register at word + 4 */
2419 if ((ft & VT_BTYPE) == VT_LLONG) {
2420 vswap();
2421 /* convert to int to increment easily */
2422 vtop->type.t = VT_INT;
2423 gaddrof();
2424 vpushi(4);
2425 gen_op('+');
2426 vtop->r |= VT_LVAL;
2427 vswap();
2428 /* XXX: it works because r2 is spilled last ! */
2429 store(vtop->r2, vtop - 1);
2431 #endif
2433 vswap();
2434 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
2435 vtop->r |= delayed_cast;
2439 /* post defines POST/PRE add. c is the token ++ or -- */
2440 ST_FUNC void inc(int post, int c)
2442 test_lvalue();
2443 vdup(); /* save lvalue */
2444 if (post) {
2445 gv_dup(); /* duplicate value */
2446 vrotb(3);
2447 vrotb(3);
2449 /* add constant */
2450 vpushi(c - TOK_MID);
2451 gen_op('+');
2452 vstore(); /* store value */
2453 if (post)
2454 vpop(); /* if post op, return saved value */
2457 /* Parse GNUC __attribute__ extension. Currently, the following
2458 extensions are recognized:
2459 - aligned(n) : set data/function alignment.
2460 - packed : force data alignment to 1
2461 - section(x) : generate data/code in this section.
2462 - unused : currently ignored, but may be used someday.
2463 - regparm(n) : pass function parameters in registers (i386 only)
2465 static void parse_attribute(AttributeDef *ad)
2467 int t, n;
2469 while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
2470 next();
2471 skip('(');
2472 skip('(');
2473 while (tok != ')') {
2474 if (tok < TOK_IDENT)
2475 expect("attribute name");
2476 t = tok;
2477 next();
2478 switch(t) {
2479 case TOK_SECTION1:
2480 case TOK_SECTION2:
2481 skip('(');
2482 if (tok != TOK_STR)
2483 expect("section name");
2484 ad->section = find_section(tcc_state, (char *)tokc.cstr->data);
2485 next();
2486 skip(')');
2487 break;
2488 case TOK_ALIAS1:
2489 case TOK_ALIAS2:
2490 skip('(');
2491 if (tok != TOK_STR)
2492 expect("alias(\"target\")");
2493 ad->alias_target = /* save string as token, for later */
2494 tok_alloc((char*)tokc.cstr->data, tokc.cstr->size-1)->tok;
2495 next();
2496 skip(')');
2497 break;
2498 case TOK_ALIGNED1:
2499 case TOK_ALIGNED2:
2500 if (tok == '(') {
2501 next();
2502 n = expr_const();
2503 if (n <= 0 || (n & (n - 1)) != 0)
2504 error("alignment must be a positive power of two");
2505 skip(')');
2506 } else {
2507 n = MAX_ALIGN;
2509 ad->aligned = n;
2510 break;
2511 case TOK_PACKED1:
2512 case TOK_PACKED2:
2513 ad->packed = 1;
2514 break;
2515 case TOK_WEAK1:
2516 case TOK_WEAK2:
2517 ad->weak = 1;
2518 break;
2519 case TOK_UNUSED1:
2520 case TOK_UNUSED2:
2521 /* currently, no need to handle it because tcc does not
2522 track unused objects */
2523 break;
2524 case TOK_NORETURN1:
2525 case TOK_NORETURN2:
2526 /* currently, no need to handle it because tcc does not
2527 track unused objects */
2528 break;
2529 case TOK_CDECL1:
2530 case TOK_CDECL2:
2531 case TOK_CDECL3:
2532 ad->func_call = FUNC_CDECL;
2533 break;
2534 case TOK_STDCALL1:
2535 case TOK_STDCALL2:
2536 case TOK_STDCALL3:
2537 ad->func_call = FUNC_STDCALL;
2538 break;
2539 #ifdef TCC_TARGET_I386
2540 case TOK_REGPARM1:
2541 case TOK_REGPARM2:
2542 skip('(');
2543 n = expr_const();
2544 if (n > 3)
2545 n = 3;
2546 else if (n < 0)
2547 n = 0;
2548 if (n > 0)
2549 ad->func_call = FUNC_FASTCALL1 + n - 1;
2550 skip(')');
2551 break;
2552 case TOK_FASTCALL1:
2553 case TOK_FASTCALL2:
2554 case TOK_FASTCALL3:
2555 ad->func_call = FUNC_FASTCALLW;
2556 break;
2557 #endif
2558 case TOK_MODE:
2559 skip('(');
2560 switch(tok) {
2561 case TOK_MODE_DI:
2562 ad->mode = VT_LLONG + 1;
2563 break;
2564 case TOK_MODE_HI:
2565 ad->mode = VT_SHORT + 1;
2566 break;
2567 case TOK_MODE_SI:
2568 ad->mode = VT_INT + 1;
2569 break;
2570 default:
2571 warning("__mode__(%s) not supported\n", get_tok_str(tok, NULL));
2572 break;
2574 next();
2575 skip(')');
2576 break;
2577 case TOK_DLLEXPORT:
2578 ad->func_export = 1;
2579 break;
2580 case TOK_DLLIMPORT:
2581 ad->func_import = 1;
2582 break;
2583 default:
2584 if (tcc_state->warn_unsupported)
2585 warning("'%s' attribute ignored", get_tok_str(t, NULL));
2586 /* skip parameters */
2587 if (tok == '(') {
2588 int parenthesis = 0;
2589 do {
2590 if (tok == '(')
2591 parenthesis++;
2592 else if (tok == ')')
2593 parenthesis--;
2594 next();
2595 } while (parenthesis && tok != -1);
2597 break;
2599 if (tok != ',')
2600 break;
2601 next();
2603 skip(')');
2604 skip(')');
2608 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
2609 static void struct_decl(CType *type, int u)
2611 int a, v, size, align, maxalign, c, offset;
2612 int bit_size, bit_pos, bsize, bt, lbit_pos, prevbt, resize;
2613 Sym *s, *ss, *ass, **ps;
2614 AttributeDef ad;
2615 CType type1, btype;
2617 a = tok; /* save decl type */
2618 next();
2619 if (tok != '{') {
2620 v = tok;
2621 next();
2622 /* struct already defined ? return it */
2623 if (v < TOK_IDENT)
2624 expect("struct/union/enum name");
2625 s = struct_find(v);
2626 if (s) {
2627 if (s->type.t != a)
2628 error("invalid type");
2629 goto do_decl;
2631 } else {
2632 v = anon_sym++;
2634 type1.t = a;
2635 /* we put an undefined size for struct/union */
2636 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
2637 s->r = 0; /* default alignment is zero as gcc */
2638 /* put struct/union/enum name in type */
2639 do_decl:
2640 type->t = u;
2641 type->ref = s;
2643 if (tok == '{') {
2644 next();
2645 if (s->c != -1)
2646 error("struct/union/enum already defined");
2647 /* cannot be empty */
2648 c = 0;
2649 /* non empty enums are not allowed */
2650 if (a == TOK_ENUM) {
2651 for(;;) {
2652 v = tok;
2653 if (v < TOK_UIDENT)
2654 expect("identifier");
2655 next();
2656 if (tok == '=') {
2657 next();
2658 c = expr_const();
2660 /* enum symbols have static storage */
2661 ss = sym_push(v, &int_type, VT_CONST, c);
2662 ss->type.t |= VT_STATIC;
2663 if (tok != ',')
2664 break;
2665 next();
2666 c++;
2667 /* NOTE: we accept a trailing comma */
2668 if (tok == '}')
2669 break;
2671 skip('}');
2672 } else {
2673 resize = 0;
2674 maxalign = 1;
2675 ps = &s->next;
2676 prevbt = VT_INT;
2677 bit_pos = 0;
2678 offset = 0;
2679 while (tok != '}') {
2680 parse_btype(&btype, &ad);
2681 while (1) {
2682 bit_size = -1;
2683 v = 0;
2684 type1 = btype;
2685 if (tok != ':') {
2686 type_decl(&type1, &ad, &v, TYPE_DIRECT | TYPE_ABSTRACT);
2687 if (v == 0 && (type1.t & VT_BTYPE) != VT_STRUCT)
2688 expect("identifier");
2689 if ((type1.t & VT_BTYPE) == VT_FUNC ||
2690 (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
2691 error("invalid type for '%s'",
2692 get_tok_str(v, NULL));
2694 if (tok == ':') {
2695 next();
2696 bit_size = expr_const();
2697 /* XXX: handle v = 0 case for messages */
2698 if (bit_size < 0)
2699 error("negative width in bit-field '%s'",
2700 get_tok_str(v, NULL));
2701 if (v && bit_size == 0)
2702 error("zero width for bit-field '%s'",
2703 get_tok_str(v, NULL));
2705 size = type_size(&type1, &align);
2706 if (ad.aligned) {
2707 if (align < ad.aligned)
2708 align = ad.aligned;
2709 } else if (ad.packed) {
2710 align = 1;
2711 } else if (*tcc_state->pack_stack_ptr) {
2712 if (align > *tcc_state->pack_stack_ptr)
2713 align = *tcc_state->pack_stack_ptr;
2715 lbit_pos = 0;
2716 if (bit_size >= 0) {
2717 bt = type1.t & VT_BTYPE;
2718 if (bt != VT_INT &&
2719 bt != VT_BYTE &&
2720 bt != VT_SHORT &&
2721 bt != VT_BOOL &&
2722 bt != VT_ENUM &&
2723 bt != VT_LLONG)
2724 error("bitfields must have scalar type");
2725 bsize = size * 8;
2726 if (bit_size > bsize) {
2727 error("width of '%s' exceeds its type",
2728 get_tok_str(v, NULL));
2729 } else if (bit_size == bsize) {
2730 /* no need for bit fields */
2731 bit_pos = 0;
2732 } else if (bit_size == 0) {
2733 /* XXX: what to do if only padding in a
2734 structure ? */
2735 /* zero size: means to pad */
2736 bit_pos = 0;
2737 } else {
2738 /* we do not have enough room ?
2739 did the type change?
2740 is it a union? */
2741 if ((bit_pos + bit_size) > bsize ||
2742 bt != prevbt || a == TOK_UNION)
2743 bit_pos = 0;
2744 lbit_pos = bit_pos;
2745 /* XXX: handle LSB first */
2746 type1.t |= VT_BITFIELD |
2747 (bit_pos << VT_STRUCT_SHIFT) |
2748 (bit_size << (VT_STRUCT_SHIFT + 6));
2749 bit_pos += bit_size;
2751 prevbt = bt;
2752 } else {
2753 bit_pos = 0;
2755 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
2756 /* add new memory data only if starting
2757 bit field */
2758 if (lbit_pos == 0) {
2759 if (a == TOK_STRUCT) {
2760 c = (c + align - 1) & -align;
2761 offset = c;
2762 if (size > 0)
2763 c += size;
2764 if (size < 0)
2765 resize = 1;
2766 } else {
2767 offset = 0;
2768 if (size > c)
2769 c = size;
2771 if (align > maxalign)
2772 maxalign = align;
2774 #if 0
2775 printf("add field %s offset=%d",
2776 get_tok_str(v, NULL), offset);
2777 if (type1.t & VT_BITFIELD) {
2778 printf(" pos=%d size=%d",
2779 (type1.t >> VT_STRUCT_SHIFT) & 0x3f,
2780 (type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
2782 printf("\n");
2783 #endif
2785 if (v == 0 && (type1.t & VT_BTYPE) == VT_STRUCT) {
2786 ass = type1.ref;
2787 while ((ass = ass->next) != NULL) {
2788 ss = sym_push(ass->v, &ass->type, 0, offset + ass->c);
2789 *ps = ss;
2790 ps = &ss->next;
2792 } else if (v) {
2793 ss = sym_push(v | SYM_FIELD, &type1, 0, offset);
2794 *ps = ss;
2795 ps = &ss->next;
2797 if (tok == ';' || tok == TOK_EOF)
2798 break;
2799 skip(',');
2801 skip(';');
2803 skip('}');
2804 /* store size and alignment */
2805 s->c = (c + maxalign - 1) & -maxalign;
2806 s->r = maxalign | (resize ? (1 << 31) : 0);
2811 /* return 0 if no type declaration. otherwise, return the basic type
2812 and skip it.
2814 static int parse_btype(CType *type, AttributeDef *ad)
2816 int t, u, type_found, typespec_found, typedef_found;
2817 Sym *s;
2818 CType type1;
2820 memset(ad, 0, sizeof(AttributeDef));
2821 type_found = 0;
2822 typespec_found = 0;
2823 typedef_found = 0;
2824 t = 0;
2825 while(1) {
2826 switch(tok) {
2827 case TOK_EXTENSION:
2828 /* currently, we really ignore extension */
2829 next();
2830 continue;
2832 /* basic types */
2833 case TOK_CHAR:
2834 u = VT_BYTE;
2835 basic_type:
2836 next();
2837 basic_type1:
2838 if ((t & VT_BTYPE) != 0)
2839 error("too many basic types");
2840 t |= u;
2841 typespec_found = 1;
2842 break;
2843 case TOK_VOID:
2844 u = VT_VOID;
2845 goto basic_type;
2846 case TOK_SHORT:
2847 u = VT_SHORT;
2848 goto basic_type;
2849 case TOK_INT:
2850 next();
2851 typespec_found = 1;
2852 break;
2853 case TOK_LONG:
2854 next();
2855 if ((t & VT_BTYPE) == VT_DOUBLE) {
2856 #ifndef TCC_TARGET_PE
2857 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
2858 #endif
2859 } else if ((t & VT_BTYPE) == VT_LONG) {
2860 t = (t & ~VT_BTYPE) | VT_LLONG;
2861 } else {
2862 u = VT_LONG;
2863 goto basic_type1;
2865 break;
2866 case TOK_BOOL:
2867 u = VT_BOOL;
2868 goto basic_type;
2869 case TOK_FLOAT:
2870 u = VT_FLOAT;
2871 goto basic_type;
2872 case TOK_DOUBLE:
2873 next();
2874 if ((t & VT_BTYPE) == VT_LONG) {
2875 #ifdef TCC_TARGET_PE
2876 t = (t & ~VT_BTYPE) | VT_DOUBLE;
2877 #else
2878 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
2879 #endif
2880 } else {
2881 u = VT_DOUBLE;
2882 goto basic_type1;
2884 break;
2885 case TOK_ENUM:
2886 struct_decl(&type1, VT_ENUM);
2887 basic_type2:
2888 u = type1.t;
2889 type->ref = type1.ref;
2890 goto basic_type1;
2891 case TOK_STRUCT:
2892 case TOK_UNION:
2893 struct_decl(&type1, VT_STRUCT);
2894 goto basic_type2;
2896 /* type modifiers */
2897 case TOK_CONST1:
2898 case TOK_CONST2:
2899 case TOK_CONST3:
2900 t |= VT_CONSTANT;
2901 next();
2902 break;
2903 case TOK_VOLATILE1:
2904 case TOK_VOLATILE2:
2905 case TOK_VOLATILE3:
2906 t |= VT_VOLATILE;
2907 next();
2908 break;
2909 case TOK_SIGNED1:
2910 case TOK_SIGNED2:
2911 case TOK_SIGNED3:
2912 typespec_found = 1;
2913 t |= VT_SIGNED;
2914 next();
2915 break;
2916 case TOK_REGISTER:
2917 case TOK_AUTO:
2918 case TOK_RESTRICT1:
2919 case TOK_RESTRICT2:
2920 case TOK_RESTRICT3:
2921 next();
2922 break;
2923 case TOK_UNSIGNED:
2924 t |= VT_UNSIGNED;
2925 next();
2926 typespec_found = 1;
2927 break;
2929 /* storage */
2930 case TOK_EXTERN:
2931 t |= VT_EXTERN;
2932 next();
2933 break;
2934 case TOK_STATIC:
2935 t |= VT_STATIC;
2936 next();
2937 break;
2938 case TOK_TYPEDEF:
2939 t |= VT_TYPEDEF;
2940 next();
2941 break;
2942 case TOK_INLINE1:
2943 case TOK_INLINE2:
2944 case TOK_INLINE3:
2945 t |= VT_INLINE;
2946 next();
2947 break;
2949 /* GNUC attribute */
2950 case TOK_ATTRIBUTE1:
2951 case TOK_ATTRIBUTE2:
2952 parse_attribute(ad);
2953 if (ad->mode) {
2954 u = ad->mode -1;
2955 t = (t & ~VT_BTYPE) | u;
2957 break;
2958 /* GNUC typeof */
2959 case TOK_TYPEOF1:
2960 case TOK_TYPEOF2:
2961 case TOK_TYPEOF3:
2962 next();
2963 parse_expr_type(&type1);
2964 /* remove all storage modifiers except typedef */
2965 type1.t &= ~(VT_STORAGE&~VT_TYPEDEF);
2966 goto basic_type2;
2967 default:
2968 if (typespec_found || typedef_found)
2969 goto the_end;
2970 s = sym_find(tok);
2971 if (!s || !(s->type.t & VT_TYPEDEF))
2972 goto the_end;
2973 typedef_found = 1;
2974 t |= (s->type.t & ~VT_TYPEDEF);
2975 type->ref = s->type.ref;
2976 if (s->r) {
2977 /* get attributes from typedef */
2978 if (0 == ad->aligned)
2979 ad->aligned = FUNC_ALIGN(s->r);
2980 if (0 == ad->func_call)
2981 ad->func_call = FUNC_CALL(s->r);
2982 ad->packed |= FUNC_PACKED(s->r);
2984 next();
2985 typespec_found = 1;
2986 break;
2988 type_found = 1;
2990 the_end:
2991 if ((t & (VT_SIGNED|VT_UNSIGNED)) == (VT_SIGNED|VT_UNSIGNED))
2992 error("signed and unsigned modifier");
2993 if (tcc_state->char_is_unsigned) {
2994 if ((t & (VT_SIGNED|VT_UNSIGNED|VT_BTYPE)) == VT_BYTE)
2995 t |= VT_UNSIGNED;
2997 t &= ~VT_SIGNED;
2999 /* long is never used as type */
3000 if ((t & VT_BTYPE) == VT_LONG)
3001 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
3002 t = (t & ~VT_BTYPE) | VT_INT;
3003 #else
3004 t = (t & ~VT_BTYPE) | VT_LLONG;
3005 #endif
3006 type->t = t;
3007 return type_found;
3010 /* convert a function parameter type (array to pointer and function to
3011 function pointer) */
3012 static inline void convert_parameter_type(CType *pt)
3014 /* remove const and volatile qualifiers (XXX: const could be used
3015 to indicate a const function parameter */
3016 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
3017 /* array must be transformed to pointer according to ANSI C */
3018 pt->t &= ~VT_ARRAY;
3019 if ((pt->t & VT_BTYPE) == VT_FUNC) {
3020 mk_pointer(pt);
3024 ST_FUNC void parse_asm_str(CString *astr)
3026 skip('(');
3027 /* read the string */
3028 if (tok != TOK_STR)
3029 expect("string constant");
3030 cstr_new(astr);
3031 while (tok == TOK_STR) {
3032 /* XXX: add \0 handling too ? */
3033 cstr_cat(astr, tokc.cstr->data);
3034 next();
3036 cstr_ccat(astr, '\0');
3039 /* Parse an asm label and return the label
3040 * Don't forget to free the CString in the caller! */
3041 static void asm_label_instr(CString *astr)
3043 next();
3044 parse_asm_str(astr);
3045 skip(')');
3046 #ifdef ASM_DEBUG
3047 printf("asm_alias: \"%s\"\n", (char *)astr->data);
3048 #endif
3051 static void post_type_array(CType *type, AttributeDef *ad);
3053 static void post_type_args(CType *type, AttributeDef *ad)
3055 int n, l, t1, arg_size, align;
3056 Sym **plast, *s, *first;
3057 AttributeDef ad1;
3058 CType pt;
3060 /* function declaration */
3061 skip('(');
3062 l = 0;
3063 first = NULL;
3064 plast = &first;
3065 arg_size = 0;
3066 if (tok != ')') {
3067 for(;;) {
3068 /* read param name and compute offset */
3069 if (l != FUNC_OLD) {
3070 if (!parse_btype(&pt, &ad1)) {
3071 if (l) {
3072 error("invalid type");
3073 } else {
3074 l = FUNC_OLD;
3075 goto old_proto;
3078 l = FUNC_NEW;
3079 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
3080 break;
3081 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
3082 if ((pt.t & VT_BTYPE) == VT_VOID)
3083 error("parameter declared as void");
3084 arg_size += (type_size(&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
3085 } else {
3086 old_proto:
3087 n = tok;
3088 if (n < TOK_UIDENT)
3089 expect("identifier");
3090 pt.t = VT_INT;
3091 next();
3093 convert_parameter_type(&pt);
3094 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
3095 *plast = s;
3096 plast = &s->next;
3097 if (tok == ')')
3098 break;
3099 skip(',');
3100 if (l == FUNC_NEW && tok == TOK_DOTS) {
3101 l = FUNC_ELLIPSIS;
3102 next();
3103 break;
3107 /* if no parameters, then old type prototype */
3108 if (l == 0)
3109 l = FUNC_OLD;
3110 skip(')');
3111 t1 = type->t & VT_STORAGE;
3112 /* NOTE: const is ignored in returned type as it has a special
3113 meaning in gcc / C++ */
3114 type->t &= ~(VT_STORAGE | VT_CONSTANT);
3115 /* some ancient pre-K&R C allows a function to return an array
3116 and the array brackets to be put after the arguments, such
3117 that "int c()[]" means the same as "int[] c()" */
3118 if (tok == '[')
3119 post_type_array(type, ad);
3120 /* we push a anonymous symbol which will contain the function prototype */
3121 ad->func_args = arg_size;
3122 s = sym_push(SYM_FIELD, type, INT_ATTR(ad), l);
3123 s->next = first;
3124 type->t = t1 | VT_FUNC;
3125 type->ref = s;
3128 static void post_type_array(CType *type, AttributeDef *ad)
3130 int n, t1;
3131 Sym *s;
3133 /* array definition */
3134 skip('[');
3135 if (tok == TOK_RESTRICT1)
3136 next();
3137 n = -1;
3138 if (tok != ']') {
3139 n = expr_const();
3140 if (n < 0)
3141 error("invalid array size");
3143 skip(']');
3144 /* parse next post type */
3145 t1 = type->t & VT_STORAGE;
3146 type->t &= ~VT_STORAGE;
3147 if (tok == '[')
3148 post_type_array(type, ad);
3150 /* we push a anonymous symbol which will contain the array
3151 element type */
3152 s = sym_push(SYM_FIELD, type, 0, n);
3153 if (n < 0)
3154 ARRAY_RESIZE(s->r) = 1;
3155 type->t = t1 | VT_ARRAY | VT_PTR;
3156 type->ref = s;
3159 /* Parse a type declaration (except basic type), and return the type
3160 in 'type'. 'td' is a bitmask indicating which kind of type decl is
3161 expected. 'type' should contain the basic type. 'ad' is the
3162 attribute definition of the basic type. It can be modified by
3163 type_decl().
3165 static void type_decl(CType *type, AttributeDef *ad, int *v, int td)
3167 Sym *s;
3168 CType type1, *type2;
3169 int qualifiers;
3171 while (tok == '*') {
3172 qualifiers = 0;
3173 redo:
3174 next();
3175 switch(tok) {
3176 case TOK_CONST1:
3177 case TOK_CONST2:
3178 case TOK_CONST3:
3179 qualifiers |= VT_CONSTANT;
3180 goto redo;
3181 case TOK_VOLATILE1:
3182 case TOK_VOLATILE2:
3183 case TOK_VOLATILE3:
3184 qualifiers |= VT_VOLATILE;
3185 goto redo;
3186 case TOK_RESTRICT1:
3187 case TOK_RESTRICT2:
3188 case TOK_RESTRICT3:
3189 goto redo;
3191 mk_pointer(type);
3192 type->t |= qualifiers;
3195 /* XXX: clarify attribute handling */
3196 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3197 parse_attribute(ad);
3199 /* recursive type */
3200 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
3201 type1.t = 0; /* XXX: same as int */
3202 if (tok == '(') {
3203 next();
3204 /* XXX: this is not correct to modify 'ad' at this point, but
3205 the syntax is not clear */
3206 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3207 parse_attribute(ad);
3208 type_decl(&type1, ad, v, td);
3209 skip(')');
3210 } else {
3211 /* type identifier */
3212 if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
3213 *v = tok;
3214 next();
3215 } else {
3216 if (!(td & TYPE_ABSTRACT))
3217 expect("identifier");
3218 *v = 0;
3221 if (tok == '(')
3222 post_type_args(type, ad);
3223 else if (tok == '[')
3224 post_type_array(type, ad);
3225 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3226 parse_attribute(ad);
3228 if (!type1.t)
3229 return;
3230 /* append type at the end of type1 */
3231 type2 = &type1;
3232 for(;;) {
3233 s = type2->ref;
3234 type2 = &s->type;
3235 if (!type2->t) {
3236 *type2 = *type;
3237 break;
3240 *type = type1;
3243 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
3244 ST_FUNC int lvalue_type(int t)
3246 int bt, r;
3247 r = VT_LVAL;
3248 bt = t & VT_BTYPE;
3249 if (bt == VT_BYTE || bt == VT_BOOL)
3250 r |= VT_LVAL_BYTE;
3251 else if (bt == VT_SHORT)
3252 r |= VT_LVAL_SHORT;
3253 else
3254 return r;
3255 if (t & VT_UNSIGNED)
3256 r |= VT_LVAL_UNSIGNED;
3257 return r;
3260 /* indirection with full error checking and bound check */
3261 ST_FUNC void indir(void)
3263 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
3264 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
3265 return;
3266 expect("pointer");
3268 if ((vtop->r & VT_LVAL) && !nocode_wanted)
3269 gv(RC_INT);
3270 vtop->type = *pointed_type(&vtop->type);
3271 /* Arrays and functions are never lvalues */
3272 if (!(vtop->type.t & VT_ARRAY)
3273 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
3274 vtop->r |= lvalue_type(vtop->type.t);
3275 /* if bound checking, the referenced pointer must be checked */
3276 #ifdef CONFIG_TCC_BCHECK
3277 if (tcc_state->do_bounds_check)
3278 vtop->r |= VT_MUSTBOUND;
3279 #endif
3283 /* pass a parameter to a function and do type checking and casting */
3284 static void gfunc_param_typed(Sym *func, Sym *arg)
3286 int func_type;
3287 CType type;
3289 func_type = func->c;
3290 if (func_type == FUNC_OLD ||
3291 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
3292 /* default casting : only need to convert float to double */
3293 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
3294 type.t = VT_DOUBLE;
3295 gen_cast(&type);
3297 } else if (arg == NULL) {
3298 error("too many arguments to function");
3299 } else {
3300 type = arg->type;
3301 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
3302 gen_assign_cast(&type);
3306 /* parse an expression of the form '(type)' or '(expr)' and return its
3307 type */
3308 static void parse_expr_type(CType *type)
3310 int n;
3311 AttributeDef ad;
3313 skip('(');
3314 if (parse_btype(type, &ad)) {
3315 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3316 } else {
3317 expr_type(type);
3319 skip(')');
3322 static void parse_type(CType *type)
3324 AttributeDef ad;
3325 int n;
3327 if (!parse_btype(type, &ad)) {
3328 expect("type");
3330 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3333 static void vpush_tokc(int t)
3335 CType type;
3336 type.t = t;
3337 type.ref = 0;
3338 vsetc(&type, VT_CONST, &tokc);
3341 ST_FUNC void unary(void)
3343 int n, t, align, size, r, sizeof_caller;
3344 CType type;
3345 Sym *s;
3346 AttributeDef ad;
3347 static int in_sizeof = 0;
3349 sizeof_caller = in_sizeof;
3350 in_sizeof = 0;
3351 /* XXX: GCC 2.95.3 does not generate a table although it should be
3352 better here */
3353 tok_next:
3354 switch(tok) {
3355 case TOK_EXTENSION:
3356 next();
3357 goto tok_next;
3358 case TOK_CINT:
3359 case TOK_CCHAR:
3360 case TOK_LCHAR:
3361 vpushi(tokc.i);
3362 next();
3363 break;
3364 case TOK_CUINT:
3365 vpush_tokc(VT_INT | VT_UNSIGNED);
3366 next();
3367 break;
3368 case TOK_CLLONG:
3369 vpush_tokc(VT_LLONG);
3370 next();
3371 break;
3372 case TOK_CULLONG:
3373 vpush_tokc(VT_LLONG | VT_UNSIGNED);
3374 next();
3375 break;
3376 case TOK_CFLOAT:
3377 vpush_tokc(VT_FLOAT);
3378 next();
3379 break;
3380 case TOK_CDOUBLE:
3381 vpush_tokc(VT_DOUBLE);
3382 next();
3383 break;
3384 case TOK_CLDOUBLE:
3385 vpush_tokc(VT_LDOUBLE);
3386 next();
3387 break;
3388 case TOK___FUNCTION__:
3389 if (!gnu_ext)
3390 goto tok_identifier;
3391 /* fall thru */
3392 case TOK___FUNC__:
3394 void *ptr;
3395 int len;
3396 /* special function name identifier */
3397 len = strlen(funcname) + 1;
3398 /* generate char[len] type */
3399 type.t = VT_BYTE;
3400 mk_pointer(&type);
3401 type.t |= VT_ARRAY;
3402 type.ref->c = len;
3403 vpush_ref(&type, data_section, data_section->data_offset, len);
3404 ptr = section_ptr_add(data_section, len);
3405 memcpy(ptr, funcname, len);
3406 next();
3408 break;
3409 case TOK_LSTR:
3410 #ifdef TCC_TARGET_PE
3411 t = VT_SHORT | VT_UNSIGNED;
3412 #else
3413 t = VT_INT;
3414 #endif
3415 goto str_init;
3416 case TOK_STR:
3417 /* string parsing */
3418 t = VT_BYTE;
3419 str_init:
3420 if (tcc_state->warn_write_strings)
3421 t |= VT_CONSTANT;
3422 type.t = t;
3423 mk_pointer(&type);
3424 type.t |= VT_ARRAY;
3425 memset(&ad, 0, sizeof(AttributeDef));
3426 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, NULL, 0);
3427 break;
3428 case '(':
3429 next();
3430 /* cast ? */
3431 if (parse_btype(&type, &ad)) {
3432 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
3433 skip(')');
3434 /* check ISOC99 compound literal */
3435 if (tok == '{') {
3436 /* data is allocated locally by default */
3437 if (global_expr)
3438 r = VT_CONST;
3439 else
3440 r = VT_LOCAL;
3441 /* all except arrays are lvalues */
3442 if (!(type.t & VT_ARRAY))
3443 r |= lvalue_type(type.t);
3444 memset(&ad, 0, sizeof(AttributeDef));
3445 decl_initializer_alloc(&type, &ad, r, 1, 0, NULL, 0);
3446 } else {
3447 if (sizeof_caller) {
3448 vpush(&type);
3449 return;
3451 unary();
3452 gen_cast(&type);
3454 } else if (tok == '{') {
3455 /* save all registers */
3456 save_regs(0);
3457 /* statement expression : we do not accept break/continue
3458 inside as GCC does */
3459 block(NULL, NULL, NULL, NULL, 0, 1);
3460 skip(')');
3461 } else {
3462 gexpr();
3463 skip(')');
3465 break;
3466 case '*':
3467 next();
3468 unary();
3469 indir();
3470 break;
3471 case '&':
3472 next();
3473 unary();
3474 /* functions names must be treated as function pointers,
3475 except for unary '&' and sizeof. Since we consider that
3476 functions are not lvalues, we only have to handle it
3477 there and in function calls. */
3478 /* arrays can also be used although they are not lvalues */
3479 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
3480 !(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
3481 test_lvalue();
3482 mk_pointer(&vtop->type);
3483 gaddrof();
3484 break;
3485 case '!':
3486 next();
3487 unary();
3488 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3489 CType boolean;
3490 boolean.t = VT_BOOL;
3491 gen_cast(&boolean);
3492 vtop->c.i = !vtop->c.i;
3493 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
3494 vtop->c.i = vtop->c.i ^ 1;
3495 else {
3496 save_regs(1);
3497 vseti(VT_JMP, gtst(1, 0));
3499 break;
3500 case '~':
3501 next();
3502 unary();
3503 vpushi(-1);
3504 gen_op('^');
3505 break;
3506 case '+':
3507 next();
3508 /* in order to force cast, we add zero */
3509 unary();
3510 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
3511 error("pointer not accepted for unary plus");
3512 vpushi(0);
3513 gen_op('+');
3514 break;
3515 case TOK_SIZEOF:
3516 case TOK_ALIGNOF1:
3517 case TOK_ALIGNOF2:
3518 t = tok;
3519 next();
3520 in_sizeof++;
3521 unary_type(&type); // Perform a in_sizeof = 0;
3522 size = type_size(&type, &align);
3523 if (t == TOK_SIZEOF) {
3524 if (size < 0)
3525 error("sizeof applied to an incomplete type");
3526 vpushi(size);
3527 } else {
3528 vpushi(align);
3530 vtop->type.t |= VT_UNSIGNED;
3531 break;
3533 case TOK_builtin_types_compatible_p:
3535 CType type1, type2;
3536 next();
3537 skip('(');
3538 parse_type(&type1);
3539 skip(',');
3540 parse_type(&type2);
3541 skip(')');
3542 type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
3543 type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
3544 vpushi(is_compatible_types(&type1, &type2));
3546 break;
3547 case TOK_builtin_constant_p:
3549 int saved_nocode_wanted, res;
3550 next();
3551 skip('(');
3552 saved_nocode_wanted = nocode_wanted;
3553 nocode_wanted = 1;
3554 gexpr();
3555 res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
3556 vpop();
3557 nocode_wanted = saved_nocode_wanted;
3558 skip(')');
3559 vpushi(res);
3561 break;
3562 case TOK_builtin_frame_address:
3564 CType type;
3565 next();
3566 skip('(');
3567 if (tok != TOK_CINT) {
3568 error("__builtin_frame_address only takes integers");
3570 if (tokc.i != 0) {
3571 error("TCC only supports __builtin_frame_address(0)");
3573 next();
3574 skip(')');
3575 type.t = VT_VOID;
3576 mk_pointer(&type);
3577 vset(&type, VT_LOCAL, 0);
3579 break;
3580 #ifdef TCC_TARGET_X86_64
3581 case TOK_builtin_va_arg_types:
3583 /* This definition must be synced with stdarg.h */
3584 enum __va_arg_type {
3585 __va_gen_reg, __va_float_reg, __va_stack
3587 CType type;
3588 int bt;
3589 next();
3590 skip('(');
3591 parse_type(&type);
3592 skip(')');
3593 bt = type.t & VT_BTYPE;
3594 if (bt == VT_STRUCT || bt == VT_LDOUBLE) {
3595 vpushi(__va_stack);
3596 } else if (bt == VT_FLOAT || bt == VT_DOUBLE) {
3597 vpushi(__va_float_reg);
3598 } else {
3599 vpushi(__va_gen_reg);
3602 break;
3603 #endif
3604 case TOK_INC:
3605 case TOK_DEC:
3606 t = tok;
3607 next();
3608 unary();
3609 inc(0, t);
3610 break;
3611 case '-':
3612 next();
3613 vpushi(0);
3614 unary();
3615 gen_op('-');
3616 break;
3617 case TOK_LAND:
3618 if (!gnu_ext)
3619 goto tok_identifier;
3620 next();
3621 /* allow to take the address of a label */
3622 if (tok < TOK_UIDENT)
3623 expect("label identifier");
3624 s = label_find(tok);
3625 if (!s) {
3626 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
3627 } else {
3628 if (s->r == LABEL_DECLARED)
3629 s->r = LABEL_FORWARD;
3631 if (!s->type.t) {
3632 s->type.t = VT_VOID;
3633 mk_pointer(&s->type);
3634 s->type.t |= VT_STATIC;
3636 vset(&s->type, VT_CONST | VT_SYM, 0);
3637 vtop->sym = s;
3638 next();
3639 break;
3641 // special qnan , snan and infinity values
3642 case TOK___NAN__:
3643 vpush64(VT_DOUBLE, 0x7ff8000000000000ULL);
3644 next();
3645 break;
3646 case TOK___SNAN__:
3647 vpush64(VT_DOUBLE, 0x7ff0000000000001ULL);
3648 next();
3649 break;
3650 case TOK___INF__:
3651 vpush64(VT_DOUBLE, 0x7ff0000000000000ULL);
3652 next();
3653 break;
3655 default:
3656 tok_identifier:
3657 t = tok;
3658 next();
3659 if (t < TOK_UIDENT)
3660 expect("identifier");
3661 s = sym_find(t);
3662 if (!s) {
3663 if (tok != '(')
3664 error("'%s' undeclared", get_tok_str(t, NULL));
3665 /* for simple function calls, we tolerate undeclared
3666 external reference to int() function */
3667 if (tcc_state->warn_implicit_function_declaration)
3668 warning("implicit declaration of function '%s'",
3669 get_tok_str(t, NULL));
3670 s = external_global_sym(t, &func_old_type, 0);
3672 if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
3673 (VT_STATIC | VT_INLINE | VT_FUNC)) {
3674 /* if referencing an inline function, then we generate a
3675 symbol to it if not already done. It will have the
3676 effect to generate code for it at the end of the
3677 compilation unit. Inline function as always
3678 generated in the text section. */
3679 if (!s->c)
3680 put_extern_sym(s, text_section, 0, 0);
3681 r = VT_SYM | VT_CONST;
3682 } else {
3683 r = s->r;
3685 vset(&s->type, r, s->c);
3686 /* if forward reference, we must point to s */
3687 if (vtop->r & VT_SYM) {
3688 vtop->sym = s;
3689 vtop->c.ul = 0;
3691 break;
3694 /* post operations */
3695 while (1) {
3696 if (tok == TOK_INC || tok == TOK_DEC) {
3697 inc(1, tok);
3698 next();
3699 } else if (tok == '.' || tok == TOK_ARROW) {
3700 int qualifiers;
3701 /* field */
3702 if (tok == TOK_ARROW)
3703 indir();
3704 qualifiers = vtop->type.t & (VT_CONSTANT | VT_VOLATILE);
3705 test_lvalue();
3706 gaddrof();
3707 next();
3708 /* expect pointer on structure */
3709 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
3710 expect("struct or union");
3711 s = vtop->type.ref;
3712 /* find field */
3713 tok |= SYM_FIELD;
3714 while ((s = s->next) != NULL) {
3715 if (s->v == tok)
3716 break;
3718 if (!s)
3719 error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, NULL));
3720 /* add field offset to pointer */
3721 vtop->type = char_pointer_type; /* change type to 'char *' */
3722 vpushi(s->c);
3723 gen_op('+');
3724 /* change type to field type, and set to lvalue */
3725 vtop->type = s->type;
3726 vtop->type.t |= qualifiers;
3727 /* an array is never an lvalue */
3728 if (!(vtop->type.t & VT_ARRAY)) {
3729 vtop->r |= lvalue_type(vtop->type.t);
3730 #ifdef CONFIG_TCC_BCHECK
3731 /* if bound checking, the referenced pointer must be checked */
3732 if (tcc_state->do_bounds_check)
3733 vtop->r |= VT_MUSTBOUND;
3734 #endif
3736 next();
3737 } else if (tok == '[') {
3738 next();
3739 gexpr();
3740 gen_op('+');
3741 indir();
3742 skip(']');
3743 } else if (tok == '(') {
3744 SValue ret;
3745 Sym *sa;
3746 int nb_args;
3748 /* function call */
3749 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
3750 /* pointer test (no array accepted) */
3751 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
3752 vtop->type = *pointed_type(&vtop->type);
3753 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
3754 goto error_func;
3755 } else {
3756 error_func:
3757 expect("function pointer");
3759 } else {
3760 vtop->r &= ~VT_LVAL; /* no lvalue */
3762 /* get return type */
3763 s = vtop->type.ref;
3764 next();
3765 sa = s->next; /* first parameter */
3766 nb_args = 0;
3767 ret.r2 = VT_CONST;
3768 /* compute first implicit argument if a structure is returned */
3769 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
3770 /* get some space for the returned structure */
3771 size = type_size(&s->type, &align);
3772 loc = (loc - size) & -align;
3773 ret.type = s->type;
3774 ret.r = VT_LOCAL | VT_LVAL;
3775 /* pass it as 'int' to avoid structure arg passing
3776 problems */
3777 vseti(VT_LOCAL, loc);
3778 ret.c = vtop->c;
3779 nb_args++;
3780 } else {
3781 ret.type = s->type;
3782 /* return in register */
3783 if (is_float(ret.type.t)) {
3784 ret.r = reg_fret(ret.type.t);
3785 } else {
3786 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
3787 ret.r2 = REG_LRET;
3788 ret.r = REG_IRET;
3790 ret.c.i = 0;
3792 if (tok != ')') {
3793 for(;;) {
3794 expr_eq();
3795 gfunc_param_typed(s, sa);
3796 nb_args++;
3797 if (sa)
3798 sa = sa->next;
3799 if (tok == ')')
3800 break;
3801 skip(',');
3804 if (sa)
3805 error("too few arguments to function");
3806 skip(')');
3807 if (!nocode_wanted) {
3808 gfunc_call(nb_args);
3809 } else {
3810 vtop -= (nb_args + 1);
3812 /* return value */
3813 vsetc(&ret.type, ret.r, &ret.c);
3814 vtop->r2 = ret.r2;
3815 } else {
3816 break;
3821 ST_FUNC void expr_prod(void)
3823 int t;
3825 unary();
3826 while (tok == '*' || tok == '/' || tok == '%') {
3827 t = tok;
3828 next();
3829 unary();
3830 gen_op(t);
3834 ST_FUNC void expr_sum(void)
3836 int t;
3838 expr_prod();
3839 while (tok == '+' || tok == '-') {
3840 t = tok;
3841 next();
3842 expr_prod();
3843 gen_op(t);
3847 static void expr_shift(void)
3849 int t;
3851 expr_sum();
3852 while (tok == TOK_SHL || tok == TOK_SAR) {
3853 t = tok;
3854 next();
3855 expr_sum();
3856 gen_op(t);
3860 static void expr_cmp(void)
3862 int t;
3864 expr_shift();
3865 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
3866 tok == TOK_ULT || tok == TOK_UGE) {
3867 t = tok;
3868 next();
3869 expr_shift();
3870 gen_op(t);
3874 static void expr_cmpeq(void)
3876 int t;
3878 expr_cmp();
3879 while (tok == TOK_EQ || tok == TOK_NE) {
3880 t = tok;
3881 next();
3882 expr_cmp();
3883 gen_op(t);
3887 static void expr_and(void)
3889 expr_cmpeq();
3890 while (tok == '&') {
3891 next();
3892 expr_cmpeq();
3893 gen_op('&');
3897 static void expr_xor(void)
3899 expr_and();
3900 while (tok == '^') {
3901 next();
3902 expr_and();
3903 gen_op('^');
3907 static void expr_or(void)
3909 expr_xor();
3910 while (tok == '|') {
3911 next();
3912 expr_xor();
3913 gen_op('|');
3917 /* XXX: fix this mess */
3918 static void expr_land_const(void)
3920 expr_or();
3921 while (tok == TOK_LAND) {
3922 next();
3923 expr_or();
3924 gen_op(TOK_LAND);
3928 /* XXX: fix this mess */
3929 static void expr_lor_const(void)
3931 expr_land_const();
3932 while (tok == TOK_LOR) {
3933 next();
3934 expr_land_const();
3935 gen_op(TOK_LOR);
3939 /* only used if non constant */
3940 static void expr_land(void)
3942 int t;
3944 expr_or();
3945 if (tok == TOK_LAND) {
3946 t = 0;
3947 save_regs(1);
3948 for(;;) {
3949 t = gtst(1, t);
3950 if (tok != TOK_LAND) {
3951 vseti(VT_JMPI, t);
3952 break;
3954 next();
3955 expr_or();
3960 static void expr_lor(void)
3962 int t;
3964 expr_land();
3965 if (tok == TOK_LOR) {
3966 t = 0;
3967 save_regs(1);
3968 for(;;) {
3969 t = gtst(0, t);
3970 if (tok != TOK_LOR) {
3971 vseti(VT_JMP, t);
3972 break;
3974 next();
3975 expr_land();
3980 /* XXX: better constant handling */
3981 static void expr_cond(void)
3983 int tt, u, r1, r2, rc, t1, t2, bt1, bt2;
3984 SValue sv;
3985 CType type, type1, type2;
3987 if (const_wanted) {
3988 expr_lor_const();
3989 if (tok == '?') {
3990 CType boolean;
3991 int c;
3992 boolean.t = VT_BOOL;
3993 vdup();
3994 gen_cast(&boolean);
3995 c = vtop->c.i;
3996 vpop();
3997 next();
3998 if (tok != ':' || !gnu_ext) {
3999 vpop();
4000 gexpr();
4002 if (!c)
4003 vpop();
4004 skip(':');
4005 expr_cond();
4006 if (c)
4007 vpop();
4009 } else {
4010 expr_lor();
4011 if (tok == '?') {
4012 next();
4013 if (vtop != vstack) {
4014 /* needed to avoid having different registers saved in
4015 each branch */
4016 if (is_float(vtop->type.t)) {
4017 rc = RC_FLOAT;
4018 #ifdef TCC_TARGET_X86_64
4019 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
4020 rc = RC_ST0;
4022 #endif
4024 else
4025 rc = RC_INT;
4026 gv(rc);
4027 save_regs(1);
4029 if (tok == ':' && gnu_ext) {
4030 gv_dup();
4031 tt = gtst(1, 0);
4032 } else {
4033 tt = gtst(1, 0);
4034 gexpr();
4036 type1 = vtop->type;
4037 sv = *vtop; /* save value to handle it later */
4038 vtop--; /* no vpop so that FP stack is not flushed */
4039 skip(':');
4040 u = gjmp(0);
4041 gsym(tt);
4042 expr_cond();
4043 type2 = vtop->type;
4045 t1 = type1.t;
4046 bt1 = t1 & VT_BTYPE;
4047 t2 = type2.t;
4048 bt2 = t2 & VT_BTYPE;
4049 /* cast operands to correct type according to ISOC rules */
4050 if (is_float(bt1) || is_float(bt2)) {
4051 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
4052 type.t = VT_LDOUBLE;
4053 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
4054 type.t = VT_DOUBLE;
4055 } else {
4056 type.t = VT_FLOAT;
4058 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
4059 /* cast to biggest op */
4060 type.t = VT_LLONG;
4061 /* convert to unsigned if it does not fit in a long long */
4062 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
4063 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
4064 type.t |= VT_UNSIGNED;
4065 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
4066 /* XXX: test pointer compatibility */
4067 type = type1;
4068 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
4069 /* XXX: test function pointer compatibility */
4070 type = type1;
4071 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
4072 /* XXX: test structure compatibility */
4073 type = type1;
4074 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
4075 /* NOTE: as an extension, we accept void on only one side */
4076 type.t = VT_VOID;
4077 } else {
4078 /* integer operations */
4079 type.t = VT_INT;
4080 /* convert to unsigned if it does not fit in an integer */
4081 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
4082 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
4083 type.t |= VT_UNSIGNED;
4086 /* now we convert second operand */
4087 gen_cast(&type);
4088 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4089 gaddrof();
4090 rc = RC_INT;
4091 if (is_float(type.t)) {
4092 rc = RC_FLOAT;
4093 #ifdef TCC_TARGET_X86_64
4094 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
4095 rc = RC_ST0;
4097 #endif
4098 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
4099 /* for long longs, we use fixed registers to avoid having
4100 to handle a complicated move */
4101 rc = RC_IRET;
4104 r2 = gv(rc);
4105 /* this is horrible, but we must also convert first
4106 operand */
4107 tt = gjmp(0);
4108 gsym(u);
4109 /* put again first value and cast it */
4110 *vtop = sv;
4111 gen_cast(&type);
4112 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4113 gaddrof();
4114 r1 = gv(rc);
4115 move_reg(r2, r1);
4116 vtop->r = r2;
4117 gsym(tt);
4122 static void expr_eq(void)
4124 int t;
4126 expr_cond();
4127 if (tok == '=' ||
4128 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
4129 tok == TOK_A_XOR || tok == TOK_A_OR ||
4130 tok == TOK_A_SHL || tok == TOK_A_SAR) {
4131 test_lvalue();
4132 t = tok;
4133 next();
4134 if (t == '=') {
4135 expr_eq();
4136 } else {
4137 vdup();
4138 expr_eq();
4139 gen_op(t & 0x7f);
4141 vstore();
4145 ST_FUNC void gexpr(void)
4147 while (1) {
4148 expr_eq();
4149 if (tok != ',')
4150 break;
4151 vpop();
4152 next();
4156 /* parse an expression and return its type without any side effect. */
4157 static void expr_type(CType *type)
4159 int saved_nocode_wanted;
4161 saved_nocode_wanted = nocode_wanted;
4162 nocode_wanted = 1;
4163 gexpr();
4164 *type = vtop->type;
4165 vpop();
4166 nocode_wanted = saved_nocode_wanted;
4169 /* parse a unary expression and return its type without any side
4170 effect. */
4171 static void unary_type(CType *type)
4173 int a;
4175 a = nocode_wanted;
4176 nocode_wanted = 1;
4177 unary();
4178 *type = vtop->type;
4179 vpop();
4180 nocode_wanted = a;
4183 /* parse a constant expression and return value in vtop. */
4184 static void expr_const1(void)
4186 int a;
4187 a = const_wanted;
4188 const_wanted = 1;
4189 expr_cond();
4190 const_wanted = a;
4193 /* parse an integer constant and return its value. */
4194 ST_FUNC int expr_const(void)
4196 int c;
4197 expr_const1();
4198 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
4199 expect("constant expression");
4200 c = vtop->c.i;
4201 vpop();
4202 return c;
4205 /* return the label token if current token is a label, otherwise
4206 return zero */
4207 static int is_label(void)
4209 int last_tok;
4211 /* fast test first */
4212 if (tok < TOK_UIDENT)
4213 return 0;
4214 /* no need to save tokc because tok is an identifier */
4215 last_tok = tok;
4216 next();
4217 if (tok == ':') {
4218 next();
4219 return last_tok;
4220 } else {
4221 unget_tok(last_tok);
4222 return 0;
4226 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
4227 int case_reg, int is_expr)
4229 int a, b, c, d;
4230 Sym *s;
4232 /* generate line number info */
4233 if (tcc_state->do_debug &&
4234 (last_line_num != file->line_num || last_ind != ind)) {
4235 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
4236 last_ind = ind;
4237 last_line_num = file->line_num;
4240 if (is_expr) {
4241 /* default return value is (void) */
4242 vpushi(0);
4243 vtop->type.t = VT_VOID;
4246 if (tok == TOK_IF) {
4247 /* if test */
4248 next();
4249 skip('(');
4250 gexpr();
4251 skip(')');
4252 a = gtst(1, 0);
4253 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4254 c = tok;
4255 if (c == TOK_ELSE) {
4256 next();
4257 d = gjmp(0);
4258 gsym(a);
4259 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4260 gsym(d); /* patch else jmp */
4261 } else
4262 gsym(a);
4263 } else if (tok == TOK_WHILE) {
4264 next();
4265 d = ind;
4266 skip('(');
4267 gexpr();
4268 skip(')');
4269 a = gtst(1, 0);
4270 b = 0;
4271 block(&a, &b, case_sym, def_sym, case_reg, 0);
4272 gjmp_addr(d);
4273 gsym(a);
4274 gsym_addr(b, d);
4275 } else if (tok == '{') {
4276 Sym *llabel;
4278 next();
4279 /* record local declaration stack position */
4280 s = local_stack;
4281 llabel = local_label_stack;
4282 /* handle local labels declarations */
4283 if (tok == TOK_LABEL) {
4284 next();
4285 for(;;) {
4286 if (tok < TOK_UIDENT)
4287 expect("label identifier");
4288 label_push(&local_label_stack, tok, LABEL_DECLARED);
4289 next();
4290 if (tok == ',') {
4291 next();
4292 } else {
4293 skip(';');
4294 break;
4298 while (tok != '}') {
4299 decl(VT_LOCAL);
4300 if (tok != '}') {
4301 if (is_expr)
4302 vpop();
4303 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
4306 /* pop locally defined labels */
4307 label_pop(&local_label_stack, llabel);
4308 /* pop locally defined symbols */
4309 if(is_expr) {
4310 /* XXX: this solution makes only valgrind happy...
4311 triggered by gcc.c-torture/execute/20000917-1.c */
4312 Sym *p;
4313 switch(vtop->type.t & VT_BTYPE) {
4314 case VT_PTR:
4315 case VT_STRUCT:
4316 case VT_ENUM:
4317 case VT_FUNC:
4318 for(p=vtop->type.ref;p;p=p->prev)
4319 if(p->prev==s)
4320 error("unsupported expression type");
4323 sym_pop(&local_stack, s);
4324 next();
4325 } else if (tok == TOK_RETURN) {
4326 next();
4327 if (tok != ';') {
4328 gexpr();
4329 gen_assign_cast(&func_vt);
4330 if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
4331 CType type;
4332 /* if returning structure, must copy it to implicit
4333 first pointer arg location */
4334 #ifdef TCC_ARM_EABI
4335 int align, size;
4336 size = type_size(&func_vt,&align);
4337 if(size <= 4)
4339 if((vtop->r != (VT_LOCAL | VT_LVAL) || (vtop->c.i & 3))
4340 && (align & 3))
4342 int addr;
4343 loc = (loc - size) & -4;
4344 addr = loc;
4345 type = func_vt;
4346 vset(&type, VT_LOCAL | VT_LVAL, addr);
4347 vswap();
4348 vstore();
4349 vset(&int_type, VT_LOCAL | VT_LVAL, addr);
4351 vtop->type = int_type;
4352 gv(RC_IRET);
4353 } else {
4354 #endif
4355 type = func_vt;
4356 mk_pointer(&type);
4357 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
4358 indir();
4359 vswap();
4360 /* copy structure value to pointer */
4361 vstore();
4362 #ifdef TCC_ARM_EABI
4364 #endif
4365 } else if (is_float(func_vt.t)) {
4366 gv(rc_fret(func_vt.t));
4367 } else {
4368 gv(RC_IRET);
4370 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
4372 skip(';');
4373 rsym = gjmp(rsym); /* jmp */
4374 } else if (tok == TOK_BREAK) {
4375 /* compute jump */
4376 if (!bsym)
4377 error("cannot break");
4378 *bsym = gjmp(*bsym);
4379 next();
4380 skip(';');
4381 } else if (tok == TOK_CONTINUE) {
4382 /* compute jump */
4383 if (!csym)
4384 error("cannot continue");
4385 *csym = gjmp(*csym);
4386 next();
4387 skip(';');
4388 } else if (tok == TOK_FOR) {
4389 int e;
4390 next();
4391 skip('(');
4392 if (tok != ';') {
4393 for_loop_init();
4395 skip(';');
4396 d = ind;
4397 c = ind;
4398 a = 0;
4399 b = 0;
4400 if (tok != ';') {
4401 gexpr();
4402 a = gtst(1, 0);
4404 skip(';');
4405 if (tok != ')') {
4406 e = gjmp(0);
4407 c = ind;
4408 gexpr();
4409 vpop();
4410 gjmp_addr(d);
4411 gsym(e);
4413 skip(')');
4414 block(&a, &b, case_sym, def_sym, case_reg, 0);
4415 gjmp_addr(c);
4416 gsym(a);
4417 gsym_addr(b, c);
4418 } else
4419 if (tok == TOK_DO) {
4420 next();
4421 a = 0;
4422 b = 0;
4423 d = ind;
4424 block(&a, &b, case_sym, def_sym, case_reg, 0);
4425 skip(TOK_WHILE);
4426 skip('(');
4427 gsym(b);
4428 gexpr();
4429 c = gtst(0, 0);
4430 gsym_addr(c, d);
4431 skip(')');
4432 gsym(a);
4433 skip(';');
4434 } else
4435 if (tok == TOK_SWITCH) {
4436 next();
4437 skip('(');
4438 gexpr();
4439 /* XXX: other types than integer */
4440 case_reg = gv(RC_INT);
4441 vpop();
4442 skip(')');
4443 a = 0;
4444 b = gjmp(0); /* jump to first case */
4445 c = 0;
4446 block(&a, csym, &b, &c, case_reg, 0);
4447 /* if no default, jmp after switch */
4448 if (c == 0)
4449 c = ind;
4450 /* default label */
4451 gsym_addr(b, c);
4452 /* break label */
4453 gsym(a);
4454 } else
4455 if (tok == TOK_CASE) {
4456 int v1, v2;
4457 if (!case_sym)
4458 expect("switch");
4459 next();
4460 v1 = expr_const();
4461 v2 = v1;
4462 if (gnu_ext && tok == TOK_DOTS) {
4463 next();
4464 v2 = expr_const();
4465 if (v2 < v1)
4466 warning("empty case range");
4468 /* since a case is like a label, we must skip it with a jmp */
4469 b = gjmp(0);
4470 gsym(*case_sym);
4471 vseti(case_reg, 0);
4472 vpushi(v1);
4473 if (v1 == v2) {
4474 gen_op(TOK_EQ);
4475 *case_sym = gtst(1, 0);
4476 } else {
4477 gen_op(TOK_GE);
4478 *case_sym = gtst(1, 0);
4479 vseti(case_reg, 0);
4480 vpushi(v2);
4481 gen_op(TOK_LE);
4482 *case_sym = gtst(1, *case_sym);
4484 gsym(b);
4485 skip(':');
4486 is_expr = 0;
4487 goto block_after_label;
4488 } else
4489 if (tok == TOK_DEFAULT) {
4490 next();
4491 skip(':');
4492 if (!def_sym)
4493 expect("switch");
4494 if (*def_sym)
4495 error("too many 'default'");
4496 *def_sym = ind;
4497 is_expr = 0;
4498 goto block_after_label;
4499 } else
4500 if (tok == TOK_GOTO) {
4501 next();
4502 if (tok == '*' && gnu_ext) {
4503 /* computed goto */
4504 next();
4505 gexpr();
4506 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
4507 expect("pointer");
4508 ggoto();
4509 } else if (tok >= TOK_UIDENT) {
4510 s = label_find(tok);
4511 /* put forward definition if needed */
4512 if (!s) {
4513 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
4514 } else {
4515 if (s->r == LABEL_DECLARED)
4516 s->r = LABEL_FORWARD;
4518 /* label already defined */
4519 if (s->r & LABEL_FORWARD)
4520 s->jnext = gjmp(s->jnext);
4521 else
4522 gjmp_addr(s->jnext);
4523 next();
4524 } else {
4525 expect("label identifier");
4527 skip(';');
4528 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
4529 asm_instr();
4530 } else {
4531 b = is_label();
4532 if (b) {
4533 /* label case */
4534 s = label_find(b);
4535 if (s) {
4536 if (s->r == LABEL_DEFINED)
4537 error("duplicate label '%s'", get_tok_str(s->v, NULL));
4538 gsym(s->jnext);
4539 s->r = LABEL_DEFINED;
4540 } else {
4541 s = label_push(&global_label_stack, b, LABEL_DEFINED);
4543 s->jnext = ind;
4544 /* we accept this, but it is a mistake */
4545 block_after_label:
4546 if (tok == '}') {
4547 warning("deprecated use of label at end of compound statement");
4548 } else {
4549 if (is_expr)
4550 vpop();
4551 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
4553 } else {
4554 /* expression case */
4555 if (tok != ';') {
4556 if (is_expr) {
4557 vpop();
4558 gexpr();
4559 } else {
4560 gexpr();
4561 vpop();
4564 skip(';');
4569 /* t is the array or struct type. c is the array or struct
4570 address. cur_index/cur_field is the pointer to the current
4571 value. 'size_only' is true if only size info is needed (only used
4572 in arrays) */
4573 static void decl_designator(CType *type, Section *sec, unsigned long c,
4574 int *cur_index, Sym **cur_field,
4575 int size_only)
4577 Sym *s, *f;
4578 int notfirst, index, index_last, align, l, nb_elems, elem_size;
4579 CType type1;
4581 notfirst = 0;
4582 elem_size = 0;
4583 nb_elems = 1;
4584 if (gnu_ext && (l = is_label()) != 0)
4585 goto struct_field;
4586 while (tok == '[' || tok == '.') {
4587 if (tok == '[') {
4588 if (!(type->t & VT_ARRAY))
4589 expect("array type");
4590 s = type->ref;
4591 next();
4592 index = expr_const();
4593 if (index < 0 || (s->c >= 0 && index >= s->c))
4594 expect("invalid index");
4595 if (tok == TOK_DOTS && gnu_ext) {
4596 next();
4597 index_last = expr_const();
4598 if (index_last < 0 ||
4599 (s->c >= 0 && index_last >= s->c) ||
4600 index_last < index)
4601 expect("invalid index");
4602 } else {
4603 index_last = index;
4605 skip(']');
4606 if (!notfirst)
4607 *cur_index = index_last;
4608 type = pointed_type(type);
4609 elem_size = type_size(type, &align);
4610 c += index * elem_size;
4611 /* NOTE: we only support ranges for last designator */
4612 nb_elems = index_last - index + 1;
4613 if (nb_elems != 1) {
4614 notfirst = 1;
4615 break;
4617 } else {
4618 next();
4619 l = tok;
4620 next();
4621 struct_field:
4622 if ((type->t & VT_BTYPE) != VT_STRUCT)
4623 expect("struct/union type");
4624 s = type->ref;
4625 l |= SYM_FIELD;
4626 f = s->next;
4627 while (f) {
4628 if (f->v == l)
4629 break;
4630 f = f->next;
4632 if (!f)
4633 expect("field");
4634 if (!notfirst)
4635 *cur_field = f;
4636 /* XXX: fix this mess by using explicit storage field */
4637 type1 = f->type;
4638 type1.t |= (type->t & ~VT_TYPE);
4639 type = &type1;
4640 c += f->c;
4642 notfirst = 1;
4644 if (notfirst) {
4645 if (tok == '=') {
4646 next();
4647 } else {
4648 if (!gnu_ext)
4649 expect("=");
4651 } else {
4652 if (type->t & VT_ARRAY) {
4653 index = *cur_index;
4654 type = pointed_type(type);
4655 c += index * type_size(type, &align);
4656 } else {
4657 f = *cur_field;
4658 if (!f)
4659 error("too many field init");
4660 /* XXX: fix this mess by using explicit storage field */
4661 type1 = f->type;
4662 type1.t |= (type->t & ~VT_TYPE);
4663 type = &type1;
4664 c += f->c;
4667 decl_initializer(type, sec, c, 0, size_only);
4669 /* XXX: make it more general */
4670 if (!size_only && nb_elems > 1) {
4671 unsigned long c_end;
4672 uint8_t *src, *dst;
4673 int i;
4675 if (!sec)
4676 error("range init not supported yet for dynamic storage");
4677 c_end = c + nb_elems * elem_size;
4678 if (c_end > sec->data_allocated)
4679 section_realloc(sec, c_end);
4680 src = sec->data + c;
4681 dst = src;
4682 for(i = 1; i < nb_elems; i++) {
4683 dst += elem_size;
4684 memcpy(dst, src, elem_size);
4689 #define EXPR_VAL 0
4690 #define EXPR_CONST 1
4691 #define EXPR_ANY 2
4693 /* store a value or an expression directly in global data or in local array */
4694 static void init_putv(CType *type, Section *sec, unsigned long c,
4695 int v, int expr_type)
4697 int saved_global_expr, bt, bit_pos, bit_size;
4698 void *ptr;
4699 unsigned long long bit_mask;
4700 CType dtype;
4702 switch(expr_type) {
4703 case EXPR_VAL:
4704 vpushi(v);
4705 break;
4706 case EXPR_CONST:
4707 /* compound literals must be allocated globally in this case */
4708 saved_global_expr = global_expr;
4709 global_expr = 1;
4710 expr_const1();
4711 global_expr = saved_global_expr;
4712 /* NOTE: symbols are accepted */
4713 if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
4714 error("initializer element is not constant");
4715 break;
4716 case EXPR_ANY:
4717 expr_eq();
4718 break;
4721 dtype = *type;
4722 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
4724 if (sec) {
4725 /* XXX: not portable */
4726 /* XXX: generate error if incorrect relocation */
4727 gen_assign_cast(&dtype);
4728 bt = type->t & VT_BTYPE;
4729 /* we'll write at most 12 bytes */
4730 if (c + 12 > sec->data_allocated) {
4731 section_realloc(sec, c + 12);
4733 ptr = sec->data + c;
4734 /* XXX: make code faster ? */
4735 if (!(type->t & VT_BITFIELD)) {
4736 bit_pos = 0;
4737 bit_size = 32;
4738 bit_mask = -1LL;
4739 } else {
4740 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
4741 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
4742 bit_mask = (1LL << bit_size) - 1;
4744 if ((vtop->r & VT_SYM) &&
4745 (bt == VT_BYTE ||
4746 bt == VT_SHORT ||
4747 bt == VT_DOUBLE ||
4748 bt == VT_LDOUBLE ||
4749 bt == VT_LLONG ||
4750 (bt == VT_INT && bit_size != 32)))
4751 error("initializer element is not computable at load time");
4752 switch(bt) {
4753 case VT_BOOL:
4754 vtop->c.i = (vtop->c.i != 0);
4755 case VT_BYTE:
4756 *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
4757 break;
4758 case VT_SHORT:
4759 *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
4760 break;
4761 case VT_DOUBLE:
4762 *(double *)ptr = vtop->c.d;
4763 break;
4764 case VT_LDOUBLE:
4765 *(long double *)ptr = vtop->c.ld;
4766 break;
4767 case VT_LLONG:
4768 *(long long *)ptr |= (vtop->c.ll & bit_mask) << bit_pos;
4769 break;
4770 default:
4771 if (vtop->r & VT_SYM) {
4772 greloc(sec, vtop->sym, c, R_DATA_PTR);
4774 *(int *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
4775 break;
4777 vtop--;
4778 } else {
4779 vset(&dtype, VT_LOCAL|VT_LVAL, c);
4780 vswap();
4781 vstore();
4782 vpop();
4786 /* put zeros for variable based init */
4787 static void init_putz(CType *t, Section *sec, unsigned long c, int size)
4789 if (sec) {
4790 /* nothing to do because globals are already set to zero */
4791 } else {
4792 vpush_global_sym(&func_old_type, TOK_memset);
4793 vseti(VT_LOCAL, c);
4794 vpushi(0);
4795 vpushi(size);
4796 gfunc_call(3);
4800 /* 't' contains the type and storage info. 'c' is the offset of the
4801 object in section 'sec'. If 'sec' is NULL, it means stack based
4802 allocation. 'first' is true if array '{' must be read (multi
4803 dimension implicit array init handling). 'size_only' is true if
4804 size only evaluation is wanted (only for arrays). */
4805 static void decl_initializer(CType *type, Section *sec, unsigned long c,
4806 int first, int size_only)
4808 int index, array_length, n, no_oblock, nb, parlevel, parlevel1, i;
4809 int size1, align1, expr_type;
4810 Sym *s, *f;
4811 CType *t1;
4813 if (type->t & VT_ARRAY) {
4814 s = type->ref;
4815 n = s->c;
4816 array_length = 0;
4817 t1 = pointed_type(type);
4818 size1 = type_size(t1, &align1);
4820 no_oblock = 1;
4821 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
4822 tok == '{') {
4823 if (tok != '{')
4824 error("character array initializer must be a literal,"
4825 " optionally enclosed in braces");
4826 skip('{');
4827 no_oblock = 0;
4830 /* only parse strings here if correct type (otherwise: handle
4831 them as ((w)char *) expressions */
4832 if ((tok == TOK_LSTR &&
4833 #ifdef TCC_TARGET_PE
4834 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
4835 #else
4836 (t1->t & VT_BTYPE) == VT_INT
4837 #endif
4838 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
4839 while (tok == TOK_STR || tok == TOK_LSTR) {
4840 int cstr_len, ch;
4841 CString *cstr;
4843 cstr = tokc.cstr;
4844 /* compute maximum number of chars wanted */
4845 if (tok == TOK_STR)
4846 cstr_len = cstr->size;
4847 else
4848 cstr_len = cstr->size / sizeof(nwchar_t);
4849 cstr_len--;
4850 nb = cstr_len;
4851 if (n >= 0 && nb > (n - array_length))
4852 nb = n - array_length;
4853 if (!size_only) {
4854 if (cstr_len > nb)
4855 warning("initializer-string for array is too long");
4856 /* in order to go faster for common case (char
4857 string in global variable, we handle it
4858 specifically */
4859 if (sec && tok == TOK_STR && size1 == 1) {
4860 memcpy(sec->data + c + array_length, cstr->data, nb);
4861 } else {
4862 for(i=0;i<nb;i++) {
4863 if (tok == TOK_STR)
4864 ch = ((unsigned char *)cstr->data)[i];
4865 else
4866 ch = ((nwchar_t *)cstr->data)[i];
4867 init_putv(t1, sec, c + (array_length + i) * size1,
4868 ch, EXPR_VAL);
4872 array_length += nb;
4873 next();
4875 /* only add trailing zero if enough storage (no
4876 warning in this case since it is standard) */
4877 if (n < 0 || array_length < n) {
4878 if (!size_only) {
4879 init_putv(t1, sec, c + (array_length * size1), 0, EXPR_VAL);
4881 array_length++;
4883 } else {
4884 index = 0;
4885 if (ARRAY_RESIZE(s->r))
4886 n = -1;
4887 while (tok != '}') {
4888 decl_designator(type, sec, c, &index, NULL, size_only);
4889 if (n >= 0 && index >= n)
4890 error("index too large");
4891 /* must put zero in holes (note that doing it that way
4892 ensures that it even works with designators) */
4893 if (!size_only && array_length < index) {
4894 init_putz(t1, sec, c + array_length * size1,
4895 (index - array_length) * size1);
4897 index++;
4898 if (index > array_length)
4899 array_length = index;
4900 /* special test for multi dimensional arrays (may not
4901 be strictly correct if designators are used at the
4902 same time) */
4903 if (index >= n && no_oblock)
4904 break;
4905 if (tok == '}')
4906 break;
4907 skip(',');
4910 if (!no_oblock)
4911 skip('}');
4912 /* put zeros at the end */
4913 if (!size_only && n >= 0 && array_length < n) {
4914 init_putz(t1, sec, c + array_length * size1,
4915 (n - array_length) * size1);
4917 /* patch type size if needed */
4918 if (n < 0)
4919 s->c = array_length;
4920 } else if ((type->t & VT_BTYPE) == VT_STRUCT &&
4921 (sec || !first || tok == '{')) {
4922 int par_count;
4924 /* NOTE: the previous test is a specific case for automatic
4925 struct/union init */
4926 /* XXX: union needs only one init */
4928 /* XXX: this test is incorrect for local initializers
4929 beginning with ( without {. It would be much more difficult
4930 to do it correctly (ideally, the expression parser should
4931 be used in all cases) */
4932 par_count = 0;
4933 if (tok == '(') {
4934 AttributeDef ad1;
4935 CType type1;
4936 next();
4937 while (tok == '(') {
4938 par_count++;
4939 next();
4941 if (!parse_btype(&type1, &ad1))
4942 expect("cast");
4943 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
4944 #if 0
4945 if (!is_assignable_types(type, &type1))
4946 error("invalid type for cast");
4947 #endif
4948 skip(')');
4950 no_oblock = 1;
4951 if (first || tok == '{') {
4952 skip('{');
4953 no_oblock = 0;
4955 s = type->ref;
4956 f = s->next;
4957 array_length = 0;
4958 index = 0;
4959 n = s->c;
4960 if (s->r & (1<<31))
4961 n = -1;
4962 while (tok != '}') {
4963 decl_designator(type, sec, c, NULL, &f, size_only);
4964 index = f->c;
4965 if (!size_only && array_length < index) {
4966 init_putz(type, sec, c + array_length,
4967 index - array_length);
4969 index = index + type_size(&f->type, &align1);
4970 if (index > array_length)
4971 array_length = index;
4973 /* gr: skip fields from same union - ugly. */
4974 while (f->next) {
4975 ///printf("index: %2d %08x -- %2d %08x\n", f->c, f->type.t, f->next->c, f->next->type.t);
4976 /* test for same offset */
4977 if (f->next->c != f->c)
4978 break;
4979 /* if yes, test for bitfield shift */
4980 if ((f->type.t & VT_BITFIELD) && (f->next->type.t & VT_BITFIELD)) {
4981 int bit_pos_1 = (f->type.t >> VT_STRUCT_SHIFT) & 0x3f;
4982 int bit_pos_2 = (f->next->type.t >> VT_STRUCT_SHIFT) & 0x3f;
4983 //printf("bitfield %d %d\n", bit_pos_1, bit_pos_2);
4984 if (bit_pos_1 != bit_pos_2)
4985 break;
4987 f = f->next;
4990 f = f->next;
4991 if (no_oblock && f == NULL)
4992 break;
4993 if (tok == '}')
4994 break;
4995 skip(',');
4997 /* put zeros at the end */
4998 if (!size_only && n >= 0 && array_length < n) {
4999 init_putz(type, sec, c + array_length,
5000 n - array_length);
5002 if (!no_oblock)
5003 skip('}');
5004 while (par_count) {
5005 skip(')');
5006 par_count--;
5008 if (n < 0)
5009 s->c = array_length;
5010 } else if (tok == '{') {
5011 next();
5012 decl_initializer(type, sec, c, first, size_only);
5013 skip('}');
5014 } else if (size_only) {
5015 /* just skip expression */
5016 parlevel = parlevel1 = 0;
5017 while ((parlevel > 0 || parlevel1 > 0 ||
5018 (tok != '}' && tok != ',')) && tok != -1) {
5019 if (tok == '(')
5020 parlevel++;
5021 else if (tok == ')')
5022 parlevel--;
5023 else if (tok == '{')
5024 parlevel1++;
5025 else if (tok == '}')
5026 parlevel1--;
5027 next();
5029 } else {
5030 /* currently, we always use constant expression for globals
5031 (may change for scripting case) */
5032 expr_type = EXPR_CONST;
5033 if (!sec)
5034 expr_type = EXPR_ANY;
5035 init_putv(type, sec, c, 0, expr_type);
5039 /* parse an initializer for type 't' if 'has_init' is non zero, and
5040 allocate space in local or global data space ('r' is either
5041 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
5042 variable 'v' with an associated name represented by 'asm_label' of
5043 scope 'scope' is declared before initializers are parsed. If 'v' is
5044 zero, then a reference to the new object is put in the value stack.
5045 If 'has_init' is 2, a special parsing is done to handle string
5046 constants. */
5047 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
5048 int has_init, int v, char *asm_label,
5049 int scope)
5051 int size, align, addr, data_offset;
5052 int level;
5053 ParseState saved_parse_state = {0};
5054 TokenString init_str;
5055 Section *sec;
5057 /* resize the struct */
5058 if ((type->t & VT_BTYPE) == VT_STRUCT && (type->ref->r & (1<<31)) != 0)
5059 type->ref->c = -1;
5060 size = type_size(type, &align);
5061 /* If unknown size, we must evaluate it before
5062 evaluating initializers because
5063 initializers can generate global data too
5064 (e.g. string pointers or ISOC99 compound
5065 literals). It also simplifies local
5066 initializers handling */
5067 tok_str_new(&init_str);
5068 if (size < 0) {
5069 if (!has_init)
5070 error("unknown type size");
5071 /* get all init string */
5072 if (has_init == 2) {
5073 /* only get strings */
5074 while (tok == TOK_STR || tok == TOK_LSTR) {
5075 tok_str_add_tok(&init_str);
5076 next();
5078 } else {
5079 level = 0;
5080 while (level > 0 || (tok != ',' && tok != ';')) {
5081 if (tok < 0)
5082 error("unexpected end of file in initializer");
5083 tok_str_add_tok(&init_str);
5084 if (tok == '{')
5085 level++;
5086 else if (tok == '}') {
5087 level--;
5088 if (level <= 0) {
5089 next();
5090 break;
5093 next();
5096 tok_str_add(&init_str, -1);
5097 tok_str_add(&init_str, 0);
5099 /* compute size */
5100 save_parse_state(&saved_parse_state);
5102 macro_ptr = init_str.str;
5103 next();
5104 decl_initializer(type, NULL, 0, 1, 1);
5105 /* prepare second initializer parsing */
5106 macro_ptr = init_str.str;
5107 next();
5109 /* if still unknown size, error */
5110 size = type_size(type, &align);
5111 if (size < 0)
5112 error("unknown type size");
5114 /* take into account specified alignment if bigger */
5115 if (ad->aligned) {
5116 if (ad->aligned > align)
5117 align = ad->aligned;
5118 } else if (ad->packed) {
5119 align = 1;
5121 if ((r & VT_VALMASK) == VT_LOCAL) {
5122 sec = NULL;
5123 #ifdef CONFIG_TCC_BCHECK
5124 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY))
5125 loc--;
5126 #endif
5127 loc = (loc - size) & -align;
5128 addr = loc;
5129 #ifdef CONFIG_TCC_BCHECK
5130 /* handles bounds */
5131 /* XXX: currently, since we do only one pass, we cannot track
5132 '&' operators, so we add only arrays */
5133 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5134 unsigned long *bounds_ptr;
5135 /* add padding between regions */
5136 loc--;
5137 /* then add local bound info */
5138 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(unsigned long));
5139 bounds_ptr[0] = addr;
5140 bounds_ptr[1] = size;
5142 #endif
5143 if (v) {
5144 /* local variable */
5145 sym_push(v, type, r, addr);
5146 } else {
5147 /* push local reference */
5148 vset(type, r, addr);
5150 } else {
5151 Sym *sym;
5153 sym = NULL;
5154 if (v && scope == VT_CONST) {
5155 /* see if the symbol was already defined */
5156 sym = sym_find(v);
5157 if (sym) {
5158 if (!is_compatible_types(&sym->type, type))
5159 error("incompatible types for redefinition of '%s'",
5160 get_tok_str(v, NULL));
5161 if (sym->type.t & VT_EXTERN) {
5162 /* if the variable is extern, it was not allocated */
5163 sym->type.t &= ~VT_EXTERN;
5164 /* set array size if it was ommited in extern
5165 declaration */
5166 if ((sym->type.t & VT_ARRAY) &&
5167 sym->type.ref->c < 0 &&
5168 type->ref->c >= 0)
5169 sym->type.ref->c = type->ref->c;
5170 } else {
5171 /* we accept several definitions of the same
5172 global variable. this is tricky, because we
5173 must play with the SHN_COMMON type of the symbol */
5174 /* XXX: should check if the variable was already
5175 initialized. It is incorrect to initialized it
5176 twice */
5177 /* no init data, we won't add more to the symbol */
5178 if (!has_init)
5179 goto no_alloc;
5184 /* allocate symbol in corresponding section */
5185 sec = ad->section;
5186 if (!sec) {
5187 if (has_init)
5188 sec = data_section;
5189 else if (tcc_state->nocommon)
5190 sec = bss_section;
5192 if (sec) {
5193 data_offset = sec->data_offset;
5194 data_offset = (data_offset + align - 1) & -align;
5195 addr = data_offset;
5196 /* very important to increment global pointer at this time
5197 because initializers themselves can create new initializers */
5198 data_offset += size;
5199 #ifdef CONFIG_TCC_BCHECK
5200 /* add padding if bound check */
5201 if (tcc_state->do_bounds_check)
5202 data_offset++;
5203 #endif
5204 sec->data_offset = data_offset;
5205 /* allocate section space to put the data */
5206 if (sec->sh_type != SHT_NOBITS &&
5207 data_offset > sec->data_allocated)
5208 section_realloc(sec, data_offset);
5209 /* align section if needed */
5210 if (align > sec->sh_addralign)
5211 sec->sh_addralign = align;
5212 } else {
5213 addr = 0; /* avoid warning */
5216 if (v) {
5217 if (scope != VT_CONST || !sym) {
5218 sym = sym_push(v, type, r | VT_SYM, 0);
5219 sym->asm_label = asm_label;
5221 /* update symbol definition */
5222 if (sec) {
5223 put_extern_sym(sym, sec, addr, size);
5224 } else {
5225 ElfW(Sym) *esym;
5226 /* put a common area */
5227 put_extern_sym(sym, NULL, align, size);
5228 /* XXX: find a nicer way */
5229 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
5230 esym->st_shndx = SHN_COMMON;
5232 } else {
5233 CValue cval;
5235 /* push global reference */
5236 sym = get_sym_ref(type, sec, addr, size);
5237 cval.ul = 0;
5238 vsetc(type, VT_CONST | VT_SYM, &cval);
5239 vtop->sym = sym;
5241 /* patch symbol weakness */
5242 if (type->t & VT_WEAK)
5243 weaken_symbol(sym);
5244 #ifdef CONFIG_TCC_BCHECK
5245 /* handles bounds now because the symbol must be defined
5246 before for the relocation */
5247 if (tcc_state->do_bounds_check) {
5248 unsigned long *bounds_ptr;
5250 greloc(bounds_section, sym, bounds_section->data_offset, R_DATA_PTR);
5251 /* then add global bound info */
5252 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(long));
5253 bounds_ptr[0] = 0; /* relocated */
5254 bounds_ptr[1] = size;
5256 #endif
5258 if (has_init) {
5259 decl_initializer(type, sec, addr, 1, 0);
5260 /* restore parse state if needed */
5261 if (init_str.str) {
5262 tok_str_free(init_str.str);
5263 restore_parse_state(&saved_parse_state);
5266 no_alloc: ;
5269 static void put_func_debug(Sym *sym)
5271 char buf[512];
5273 /* stabs info */
5274 /* XXX: we put here a dummy type */
5275 snprintf(buf, sizeof(buf), "%s:%c1",
5276 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
5277 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
5278 cur_text_section, sym->c);
5279 /* //gr gdb wants a line at the function */
5280 put_stabn(N_SLINE, 0, file->line_num, 0);
5281 last_ind = 0;
5282 last_line_num = 0;
5285 /* parse an old style function declaration list */
5286 /* XXX: check multiple parameter */
5287 static void func_decl_list(Sym *func_sym)
5289 AttributeDef ad;
5290 int v;
5291 Sym *s;
5292 CType btype, type;
5294 /* parse each declaration */
5295 while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF &&
5296 tok != TOK_ASM1 && tok != TOK_ASM2 && tok != TOK_ASM3) {
5297 if (!parse_btype(&btype, &ad))
5298 expect("declaration list");
5299 if (((btype.t & VT_BTYPE) == VT_ENUM ||
5300 (btype.t & VT_BTYPE) == VT_STRUCT) &&
5301 tok == ';') {
5302 /* we accept no variable after */
5303 } else {
5304 for(;;) {
5305 type = btype;
5306 type_decl(&type, &ad, &v, TYPE_DIRECT);
5307 /* find parameter in function parameter list */
5308 s = func_sym->next;
5309 while (s != NULL) {
5310 if ((s->v & ~SYM_FIELD) == v)
5311 goto found;
5312 s = s->next;
5314 error("declaration for parameter '%s' but no such parameter",
5315 get_tok_str(v, NULL));
5316 found:
5317 /* check that no storage specifier except 'register' was given */
5318 if (type.t & VT_STORAGE)
5319 error("storage class specified for '%s'", get_tok_str(v, NULL));
5320 convert_parameter_type(&type);
5321 /* we can add the type (NOTE: it could be local to the function) */
5322 s->type = type;
5323 /* accept other parameters */
5324 if (tok == ',')
5325 next();
5326 else
5327 break;
5330 skip(';');
5334 /* parse a function defined by symbol 'sym' and generate its code in
5335 'cur_text_section' */
5336 static void gen_function(Sym *sym)
5338 int saved_nocode_wanted = nocode_wanted;
5339 nocode_wanted = 0;
5340 ind = cur_text_section->data_offset;
5341 /* NOTE: we patch the symbol size later */
5342 put_extern_sym(sym, cur_text_section, ind, 0);
5343 funcname = get_tok_str(sym->v, NULL);
5344 func_ind = ind;
5345 /* put debug symbol */
5346 if (tcc_state->do_debug)
5347 put_func_debug(sym);
5348 /* push a dummy symbol to enable local sym storage */
5349 sym_push2(&local_stack, SYM_FIELD, 0, 0);
5350 gfunc_prolog(&sym->type);
5351 rsym = 0;
5352 block(NULL, NULL, NULL, NULL, 0, 0);
5353 gsym(rsym);
5354 gfunc_epilog();
5355 cur_text_section->data_offset = ind;
5356 label_pop(&global_label_stack, NULL);
5357 sym_pop(&local_stack, NULL); /* reset local stack */
5358 /* end of function */
5359 /* patch symbol size */
5360 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
5361 ind - func_ind;
5362 /* patch symbol weakness (this definition overrules any prototype) */
5363 if (sym->type.t & VT_WEAK)
5364 weaken_symbol(sym);
5365 if (tcc_state->do_debug) {
5366 put_stabn(N_FUN, 0, 0, ind - func_ind);
5368 /* It's better to crash than to generate wrong code */
5369 cur_text_section = NULL;
5370 funcname = ""; /* for safety */
5371 func_vt.t = VT_VOID; /* for safety */
5372 ind = 0; /* for safety */
5373 nocode_wanted = saved_nocode_wanted;
5376 ST_FUNC void gen_inline_functions(void)
5378 Sym *sym;
5379 int *str, inline_generated, i;
5380 struct InlineFunc *fn;
5382 /* iterate while inline function are referenced */
5383 for(;;) {
5384 inline_generated = 0;
5385 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
5386 fn = tcc_state->inline_fns[i];
5387 sym = fn->sym;
5388 if (sym && sym->c) {
5389 /* the function was used: generate its code and
5390 convert it to a normal function */
5391 str = fn->token_str;
5392 fn->sym = NULL;
5393 if (file)
5394 strcpy(file->filename, fn->filename);
5395 sym->r = VT_SYM | VT_CONST;
5396 sym->type.t &= ~VT_INLINE;
5398 macro_ptr = str;
5399 next();
5400 cur_text_section = text_section;
5401 gen_function(sym);
5402 macro_ptr = NULL; /* fail safe */
5404 inline_generated = 1;
5407 if (!inline_generated)
5408 break;
5410 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
5411 fn = tcc_state->inline_fns[i];
5412 str = fn->token_str;
5413 tok_str_free(str);
5415 dynarray_reset(&tcc_state->inline_fns, &tcc_state->nb_inline_fns);
5418 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
5419 static void decl0(int l, int is_for_loop_init)
5421 int v, has_init, r;
5422 CType type, btype;
5423 Sym *sym;
5424 AttributeDef ad;
5426 while (1) {
5427 if (!parse_btype(&btype, &ad)) {
5428 if (is_for_loop_init) {
5429 gexpr();
5430 vpop();
5431 return;
5433 /* skip redundant ';' */
5434 /* XXX: find more elegant solution */
5435 if (tok == ';') {
5436 next();
5437 continue;
5439 if (l == VT_CONST &&
5440 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
5441 /* global asm block */
5442 asm_global_instr();
5443 continue;
5445 /* special test for old K&R protos without explicit int
5446 type. Only accepted when defining global data */
5447 if (l == VT_LOCAL || tok < TOK_DEFINE)
5448 break;
5449 btype.t = VT_INT;
5451 if (((btype.t & VT_BTYPE) == VT_ENUM ||
5452 (btype.t & VT_BTYPE) == VT_STRUCT) &&
5453 tok == ';') {
5454 /* we accept no variable after */
5455 next();
5456 continue;
5458 while (1) { /* iterate thru each declaration */
5459 char *asm_label; // associated asm label
5460 type = btype;
5461 type_decl(&type, &ad, &v, TYPE_DIRECT);
5462 #if 0
5464 char buf[500];
5465 type_to_str(buf, sizeof(buf), t, get_tok_str(v, NULL));
5466 printf("type = '%s'\n", buf);
5468 #endif
5469 if ((type.t & VT_BTYPE) == VT_FUNC) {
5470 if ((type.t & VT_STATIC) && (l == VT_LOCAL)) {
5471 error("function without file scope cannot be static");
5473 /* if old style function prototype, we accept a
5474 declaration list */
5475 sym = type.ref;
5476 if (sym->c == FUNC_OLD)
5477 func_decl_list(sym);
5480 asm_label = NULL;
5481 if (gnu_ext && (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
5482 CString astr;
5484 asm_label_instr(&astr);
5485 asm_label = tcc_strdup(astr.data);
5486 cstr_free(&astr);
5488 /* parse one last attribute list, after asm label */
5489 parse_attribute(&ad);
5492 if (ad.weak)
5493 type.t |= VT_WEAK;
5494 #ifdef TCC_TARGET_PE
5495 if (ad.func_import)
5496 type.t |= VT_IMPORT;
5497 if (ad.func_export)
5498 type.t |= VT_EXPORT;
5499 #endif
5500 if (tok == '{') {
5501 if (l == VT_LOCAL)
5502 error("cannot use local functions");
5503 if ((type.t & VT_BTYPE) != VT_FUNC)
5504 expect("function definition");
5506 /* reject abstract declarators in function definition */
5507 sym = type.ref;
5508 while ((sym = sym->next) != NULL)
5509 if (!(sym->v & ~SYM_FIELD))
5510 expect("identifier");
5512 /* XXX: cannot do better now: convert extern line to static inline */
5513 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
5514 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
5516 sym = sym_find(v);
5517 if (sym) {
5518 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
5519 goto func_error1;
5521 r = sym->type.ref->r;
5522 /* use func_call from prototype if not defined */
5523 if (FUNC_CALL(r) != FUNC_CDECL
5524 && FUNC_CALL(type.ref->r) == FUNC_CDECL)
5525 FUNC_CALL(type.ref->r) = FUNC_CALL(r);
5527 /* use export from prototype */
5528 if (FUNC_EXPORT(r))
5529 FUNC_EXPORT(type.ref->r) = 1;
5531 /* use static from prototype */
5532 if (sym->type.t & VT_STATIC)
5533 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
5535 if (!is_compatible_types(&sym->type, &type)) {
5536 func_error1:
5537 error("incompatible types for redefinition of '%s'",
5538 get_tok_str(v, NULL));
5540 /* if symbol is already defined, then put complete type */
5541 sym->type = type;
5542 } else {
5543 /* put function symbol */
5544 sym = global_identifier_push(v, type.t, 0);
5545 sym->type.ref = type.ref;
5548 /* static inline functions are just recorded as a kind
5549 of macro. Their code will be emitted at the end of
5550 the compilation unit only if they are used */
5551 if ((type.t & (VT_INLINE | VT_STATIC)) ==
5552 (VT_INLINE | VT_STATIC)) {
5553 TokenString func_str;
5554 int block_level;
5555 struct InlineFunc *fn;
5556 const char *filename;
5558 tok_str_new(&func_str);
5560 block_level = 0;
5561 for(;;) {
5562 int t;
5563 if (tok == TOK_EOF)
5564 error("unexpected end of file");
5565 tok_str_add_tok(&func_str);
5566 t = tok;
5567 next();
5568 if (t == '{') {
5569 block_level++;
5570 } else if (t == '}') {
5571 block_level--;
5572 if (block_level == 0)
5573 break;
5576 tok_str_add(&func_str, -1);
5577 tok_str_add(&func_str, 0);
5578 filename = file ? file->filename : "";
5579 fn = tcc_malloc(sizeof *fn + strlen(filename));
5580 strcpy(fn->filename, filename);
5581 fn->sym = sym;
5582 fn->token_str = func_str.str;
5583 dynarray_add((void ***)&tcc_state->inline_fns, &tcc_state->nb_inline_fns, fn);
5585 } else {
5586 /* compute text section */
5587 cur_text_section = ad.section;
5588 if (!cur_text_section)
5589 cur_text_section = text_section;
5590 sym->r = VT_SYM | VT_CONST;
5591 gen_function(sym);
5593 break;
5594 } else {
5595 if (btype.t & VT_TYPEDEF) {
5596 /* save typedefed type */
5597 /* XXX: test storage specifiers ? */
5598 sym = sym_push(v, &type, INT_ATTR(&ad), 0);
5599 sym->type.t |= VT_TYPEDEF;
5600 } else {
5601 r = 0;
5602 if ((type.t & VT_BTYPE) == VT_FUNC) {
5603 /* external function definition */
5604 /* specific case for func_call attribute */
5605 type.ref->r = INT_ATTR(&ad);
5606 } else if (!(type.t & VT_ARRAY)) {
5607 /* not lvalue if array */
5608 r |= lvalue_type(type.t);
5610 has_init = (tok == '=');
5611 if ((btype.t & VT_EXTERN) || ((type.t & VT_BTYPE) == VT_FUNC) ||
5612 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
5613 !has_init && l == VT_CONST && type.ref->c < 0)) {
5614 /* external variable or function */
5615 /* NOTE: as GCC, uninitialized global static
5616 arrays of null size are considered as
5617 extern */
5618 sym = external_sym(v, &type, r, asm_label);
5620 if (type.t & VT_WEAK)
5621 weaken_symbol(sym);
5623 if (ad.alias_target) {
5624 Section tsec;
5625 Elf32_Sym *esym;
5626 Sym *alias_target;
5628 alias_target = sym_find(ad.alias_target);
5629 if (!alias_target || !alias_target->c)
5630 error("unsupported forward __alias__ attribute");
5631 esym = &((Elf32_Sym *)symtab_section->data)[alias_target->c];
5632 tsec.sh_num = esym->st_shndx;
5633 put_extern_sym2(sym, &tsec, esym->st_value, esym->st_size, 0);
5635 } else {
5636 type.t |= (btype.t & VT_STATIC); /* Retain "static". */
5637 if (type.t & VT_STATIC)
5638 r |= VT_CONST;
5639 else
5640 r |= l;
5641 if (has_init)
5642 next();
5643 decl_initializer_alloc(&type, &ad, r, has_init, v, asm_label, l);
5646 if (tok != ',') {
5647 if (is_for_loop_init)
5648 return;
5649 skip(';');
5650 break;
5652 next();
5658 ST_FUNC void for_loop_init(void)
5660 decl0(VT_LOCAL, 1);
5663 ST_FUNC void decl(int l)
5665 decl0(l, 0);