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