fix push_macro, asked Tom to help me testfix push_macro
[tinycc.git] / tccgen.c
blob1f871415ca466110194642cc75c25b6da506bee7
1 /*
2 * TCC - Tiny C Compiler
3 *
4 * Copyright (c) 2001-2004 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #include "tcc.h"
23 /********************************************************/
24 /* global variables */
26 /* loc : local variable index
27 ind : output code index
28 rsym: return symbol
29 anon_sym: anonymous symbol index
31 ST_DATA int rsym, anon_sym, ind, loc;
33 ST_DATA Section *text_section, *data_section, *bss_section; /* predefined sections */
34 ST_DATA Section *cur_text_section; /* current section where function code is generated */
35 #ifdef CONFIG_TCC_ASM
36 ST_DATA Section *last_text_section; /* to handle .previous asm directive */
37 #endif
38 #ifdef CONFIG_TCC_BCHECK
39 /* bound check related sections */
40 ST_DATA Section *bounds_section; /* contains global data bound description */
41 ST_DATA Section *lbounds_section; /* contains local data bound description */
42 #endif
43 /* symbol sections */
44 ST_DATA Section *symtab_section, *strtab_section;
45 /* debug sections */
46 ST_DATA Section *stab_section, *stabstr_section;
47 ST_DATA Sym *sym_free_first;
48 ST_DATA void **sym_pools;
49 ST_DATA int nb_sym_pools;
51 ST_DATA Sym *global_stack;
52 ST_DATA Sym *local_stack;
53 ST_DATA Sym *scope_stack_bottom;
54 ST_DATA Sym *define_stack;
55 ST_DATA Sym *global_label_stack;
56 ST_DATA Sym *local_label_stack;
58 ST_DATA int vla_sp_loc_tmp; /* vla_sp_loc is set to this when the value won't be needed later */
59 ST_DATA int vla_sp_root_loc; /* vla_sp_loc for SP before any VLAs were pushed */
60 ST_DATA int *vla_sp_loc; /* Pointer to variable holding location to store stack pointer on the stack when modifying stack pointer */
61 ST_DATA int vla_flags; /* VLA_* flags */
63 ST_DATA SValue __vstack[1+VSTACK_SIZE], *vtop;
65 ST_DATA int const_wanted; /* true if constant wanted */
66 ST_DATA int nocode_wanted; /* true if no code generation wanted for an expression */
67 ST_DATA int global_expr; /* true if compound literals must be allocated globally (used during initializers parsing */
68 ST_DATA CType func_vt; /* current function return type (used by return instruction) */
69 ST_DATA int func_var; /* true if current function is variadic (used by return instruction) */
70 ST_DATA int func_vc;
71 ST_DATA int last_line_num, last_ind, func_ind; /* debug last line number and pc */
72 ST_DATA char *funcname;
74 ST_DATA CType char_pointer_type, func_old_type, int_type, size_type;
76 /* ------------------------------------------------------------------------- */
77 static void gen_cast(CType *type);
78 static inline CType *pointed_type(CType *type);
79 static int is_compatible_types(CType *type1, CType *type2);
80 static int parse_btype(CType *type, AttributeDef *ad);
81 static void type_decl(CType *type, AttributeDef *ad, int *v, int td);
82 static void parse_expr_type(CType *type);
83 static void decl_initializer(CType *type, Section *sec, unsigned long c, int first, int size_only);
84 static void block(int *bsym, int *csym, int *case_sym, int *def_sym, int case_reg, int is_expr);
85 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r, int has_init, int v, char *asm_label, int scope);
86 static int decl0(int l, int is_for_loop_init);
87 static void expr_eq(void);
88 static void unary_type(CType *type);
89 static void vla_runtime_type_size(CType *type, int *a);
90 static void vla_sp_save(void);
91 static int is_compatible_parameter_types(CType *type1, CType *type2);
92 static void expr_type(CType *type);
93 static int is_force;
95 ST_FUNC void vpush64(int ty, unsigned long long v);
96 ST_FUNC void vpush(CType *type);
97 ST_FUNC int gvtst(int inv, int t);
98 ST_FUNC int is_btype_size(int bt);
100 ST_INLN int is_float(int t)
102 int bt;
103 bt = t & VT_BTYPE;
104 return bt == VT_LDOUBLE || bt == VT_DOUBLE || bt == VT_FLOAT || bt == VT_QFLOAT;
107 /* we use our own 'finite' function to avoid potential problems with
108 non standard math libs */
109 /* XXX: endianness dependent */
110 ST_FUNC int ieee_finite(double d)
112 int p[4];
113 memcpy(p, &d, sizeof(double));
114 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
117 ST_FUNC void test_lvalue(void)
119 if (!(vtop->r & VT_LVAL))
120 expect("lvalue");
123 /* ------------------------------------------------------------------------- */
124 /* symbol allocator */
125 static Sym *__sym_malloc(void)
127 Sym *sym_pool, *sym, *last_sym;
128 int i;
130 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
131 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
133 last_sym = sym_free_first;
134 sym = sym_pool;
135 for(i = 0; i < SYM_POOL_NB; i++) {
136 sym->next = last_sym;
137 last_sym = sym;
138 sym++;
140 sym_free_first = last_sym;
141 return last_sym;
144 static inline Sym *sym_malloc(void)
146 Sym *sym;
147 sym = sym_free_first;
148 if (!sym)
149 sym = __sym_malloc();
150 sym_free_first = sym->next;
151 return sym;
154 ST_INLN void sym_free(Sym *sym)
156 sym->next = sym_free_first;
157 tcc_free(sym->asm_label);
158 sym_free_first = sym;
161 /* push, without hashing */
162 ST_FUNC Sym *sym_push2(Sym **ps, int v, int t, long c)
164 Sym *s;
165 if (ps == &local_stack) {
166 for (s = *ps; s && s != scope_stack_bottom; s = s->prev)
167 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM && s->v == v)
168 tcc_error("incompatible types for redefinition of '%s'",
169 get_tok_str(v, NULL));
171 s = sym_malloc();
172 s->asm_label = NULL;
173 s->v = v;
174 s->type.t = t;
175 s->type.ref = NULL;
176 #ifdef _WIN64
177 s->d = NULL;
178 #endif
179 s->c = c;
180 s->next = NULL;
181 /* add in stack */
182 s->prev = *ps;
183 *ps = s;
184 return s;
187 /* find a symbol and return its associated structure. 's' is the top
188 of the symbol stack */
189 ST_FUNC Sym *sym_find2(Sym *s, int v)
191 while (s) {
192 if (s->v == v)
193 return s;
194 else if (s->v == -1)
195 return NULL;
196 s = s->prev;
198 return NULL;
201 /* structure lookup */
202 ST_INLN Sym *struct_find(int v)
204 v -= TOK_IDENT;
205 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
206 return NULL;
207 return table_ident[v]->sym_struct;
210 /* find an identifier */
211 ST_INLN Sym *sym_find(int v)
213 v -= TOK_IDENT;
214 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
215 return NULL;
216 return table_ident[v]->sym_identifier;
219 /* push a given symbol on the symbol stack */
220 ST_FUNC Sym *sym_push(int v, CType *type, int r, int c)
222 Sym *s, **ps;
223 TokenSym *ts;
225 if (local_stack)
226 ps = &local_stack;
227 else
228 ps = &global_stack;
229 s = sym_push2(ps, v, type->t, c);
230 s->type.ref = type->ref;
231 s->r = r;
232 /* don't record fields or anonymous symbols */
233 /* XXX: simplify */
234 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
235 /* record symbol in token array */
236 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
237 if (v & SYM_STRUCT)
238 ps = &ts->sym_struct;
239 else
240 ps = &ts->sym_identifier;
241 s->prev_tok = *ps;
242 *ps = s;
244 return s;
247 /* push a global identifier */
248 ST_FUNC Sym *global_identifier_push(int v, int t, int c)
250 Sym *s, **ps;
251 s = sym_push2(&global_stack, v, t, c);
252 /* don't record anonymous symbol */
253 if (v < SYM_FIRST_ANOM) {
254 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
255 /* modify the top most local identifier, so that
256 sym_identifier will point to 's' when popped */
257 while (*ps != NULL)
258 ps = &(*ps)->prev_tok;
259 s->prev_tok = NULL;
260 *ps = s;
262 return s;
265 /* pop symbols until top reaches 'b' */
266 ST_FUNC void sym_pop(Sym **ptop, Sym *b)
268 Sym *s, *ss, **ps;
269 TokenSym *ts;
270 int v;
272 s = *ptop;
273 while(s != b) {
274 ss = s->prev;
275 v = s->v;
276 /* remove symbol in token array */
277 /* XXX: simplify */
278 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
279 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
280 if (v & SYM_STRUCT)
281 ps = &ts->sym_struct;
282 else
283 ps = &ts->sym_identifier;
284 *ps = s->prev_tok;
286 sym_free(s);
287 s = ss;
289 *ptop = b;
292 static void weaken_symbol(Sym *sym)
294 sym->type.t |= VT_WEAK;
295 if (sym->c > 0) {
296 int esym_type;
297 ElfW(Sym) *esym;
299 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
300 esym_type = ELFW(ST_TYPE)(esym->st_info);
301 esym->st_info = ELFW(ST_INFO)(STB_WEAK, esym_type);
305 static void apply_visibility(Sym *sym, CType *type)
307 int vis = sym->type.t & VT_VIS_MASK;
308 int vis2 = type->t & VT_VIS_MASK;
309 if (vis == (STV_DEFAULT << VT_VIS_SHIFT))
310 vis = vis2;
311 else if (vis2 == (STV_DEFAULT << VT_VIS_SHIFT))
313 else
314 vis = (vis < vis2) ? vis : vis2;
315 sym->type.t &= ~VT_VIS_MASK;
316 sym->type.t |= vis;
318 if (sym->c > 0) {
319 ElfW(Sym) *esym;
321 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
322 vis >>= VT_VIS_SHIFT;
323 esym->st_other = (esym->st_other & ~ELFW(ST_VISIBILITY)(-1)) | vis;
327 /* ------------------------------------------------------------------------- */
329 ST_FUNC void swap(int *p, int *q)
331 int t;
332 t = *p;
333 *p = *q;
334 *q = t;
337 static void vsetc(CType *type, int r, CValue *vc)
339 int v;
341 if (vtop >= vstack + (VSTACK_SIZE - 1))
342 tcc_error("memory full (vstack)");
343 /* cannot let cpu flags if other instruction are generated. Also
344 avoid leaving VT_JMP anywhere except on the top of the stack
345 because it would complicate the code generator. */
346 if (vtop >= vstack) {
347 v = vtop->r & VT_VALMASK;
348 if (v == VT_CMP || (v & ~1) == VT_JMP)
349 gv(RC_INT);
351 vtop++;
352 vtop->type = *type;
353 vtop->r = r;
354 vtop->r2 = VT_CONST;
355 vtop->c = *vc;
358 /* push constant of type "type" with useless value */
359 ST_FUNC void vpush(CType *type)
361 CValue cval;
362 vsetc(type, VT_CONST, &cval);
365 /* push integer constant */
366 ST_FUNC void vpushi(int v)
368 CValue cval;
369 cval.i = v;
370 vsetc(&int_type, VT_CONST, &cval);
373 /* push a pointer sized constant */
374 static void vpushs(addr_t v)
376 CValue cval;
377 cval.ptr_offset = v;
378 vsetc(&size_type, VT_CONST, &cval);
381 /* push arbitrary 64bit constant */
382 ST_FUNC void vpush64(int ty, unsigned long long v)
384 CValue cval;
385 CType ctype;
386 ctype.t = ty;
387 ctype.ref = NULL;
388 cval.ull = v;
389 vsetc(&ctype, VT_CONST, &cval);
392 /* push long long constant */
393 static inline void vpushll(long long v)
395 vpush64(VT_LLONG, v);
398 /* push a symbol value of TYPE */
399 static inline void vpushsym(CType *type, Sym *sym)
401 CValue cval;
402 cval.ptr_offset = 0;
403 vsetc(type, VT_CONST | VT_SYM, &cval);
404 vtop->sym = sym;
407 /* Return a static symbol pointing to a section */
408 ST_FUNC Sym *get_sym_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
410 int v;
411 Sym *sym;
413 v = anon_sym++;
414 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
415 sym->type.ref = type->ref;
416 sym->r = VT_CONST | VT_SYM;
417 put_extern_sym(sym, sec, offset, size);
418 return sym;
421 /* push a reference to a section offset by adding a dummy symbol */
422 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
424 vpushsym(type, get_sym_ref(type, sec, offset, size));
427 /* define a new external reference to a symbol 'v' of type 'u' */
428 ST_FUNC Sym *external_global_sym(int v, CType *type, int r)
430 Sym *s;
432 s = sym_find(v);
433 if (!s) {
434 /* push forward reference */
435 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
436 s->type.ref = type->ref;
437 s->r = r | VT_CONST | VT_SYM;
439 return s;
442 /* define a new external reference to a symbol 'v' with alternate asm
443 name 'asm_label' of type 'u'. 'asm_label' is equal to NULL if there
444 is no alternate name (most cases) */
445 static Sym *external_sym(int v, CType *type, int r, char *asm_label)
447 Sym *s;
449 s = sym_find(v);
450 if (!s) {
451 /* push forward reference */
452 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
453 s->asm_label = asm_label;
454 s->type.t |= VT_EXTERN;
455 } else if (s->type.ref == func_old_type.ref) {
456 s->type.ref = type->ref;
457 s->r = r | VT_CONST | VT_SYM;
458 s->type.t |= VT_EXTERN;
459 } else if (!is_compatible_types(&s->type, type)) {
460 tcc_error("incompatible types for redefinition of '%s'",
461 get_tok_str(v, NULL));
463 /* Merge some storage attributes. */
464 if (type->t & VT_WEAK)
465 weaken_symbol(s);
467 if (type->t & VT_VIS_MASK)
468 apply_visibility(s, type);
470 return s;
473 /* push a reference to global symbol v */
474 ST_FUNC void vpush_global_sym(CType *type, int v)
476 vpushsym(type, external_global_sym(v, type, 0));
479 ST_FUNC void vset(CType *type, int r, int v)
481 CValue cval;
483 cval.i = v;
484 vsetc(type, r, &cval);
487 static void vseti(int r, int v)
489 CType type;
490 type.t = VT_INT;
491 type.ref = 0;
492 vset(&type, r, v);
495 ST_FUNC void vswap(void)
497 SValue tmp;
498 /* cannot let cpu flags if other instruction are generated. Also
499 avoid leaving VT_JMP anywhere except on the top of the stack
500 because it would complicate the code generator. */
501 if (vtop >= vstack) {
502 int v = vtop->r & VT_VALMASK;
503 if (v == VT_CMP || (v & ~1) == VT_JMP)
504 gv(RC_INT);
506 tmp = vtop[0];
507 vtop[0] = vtop[-1];
508 vtop[-1] = tmp;
510 /* XXX: +2% overall speed possible with optimized memswap
512 * memswap(&vtop[0], &vtop[1], sizeof *vtop);
516 ST_FUNC void vpushv(SValue *v)
518 if (vtop >= vstack + (VSTACK_SIZE - 1))
519 tcc_error("memory full (vstack)");
520 vtop++;
521 *vtop = *v;
524 static void vdup(void)
526 vpushv(vtop);
529 /* save r to the memory stack, and mark it as being free */
530 ST_FUNC void save_reg(int r)
532 int l, saved, size, align;
533 SValue *p, sv;
534 CType *type;
536 /* modify all stack values */
537 saved = 0;
538 l = 0;
539 for(p=vstack;p<=vtop;p++) {
540 if ((p->r & VT_VALMASK) == r ||
541 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
542 /* must save value on stack if not already done */
543 if (!saved) {
544 /* NOTE: must reload 'r' because r might be equal to r2 */
545 r = p->r & VT_VALMASK;
546 /* store register in the stack */
547 type = &p->type;
548 if ((p->r & VT_LVAL) ||
549 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
550 #ifdef TCC_TARGET_X86_64
551 type = &char_pointer_type;
552 #else
553 type = &int_type;
554 #endif
555 size = type_size(type, &align);
556 loc = (loc - size) & -align;
557 sv.type.t = type->t;
558 sv.r = VT_LOCAL | VT_LVAL;
559 sv.c.ul = loc;
560 store(r, &sv);
561 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
562 /* x86 specific: need to pop fp register ST0 if saved */
563 if (r == TREG_ST0) {
564 o(0xd8dd); /* fstp %st(0) */
566 #endif
567 #ifndef TCC_TARGET_X86_64
568 /* special long long case */
569 if ((type->t & VT_BTYPE) == VT_LLONG) {
570 sv.c.ul += 4;
571 store(p->r2, &sv);
573 #endif
574 l = loc;
575 saved = 1;
577 /* mark that stack entry as being saved on the stack */
578 if (p->r & VT_LVAL) {
579 /* also clear the bounded flag because the
580 relocation address of the function was stored in
581 p->c.ul */
582 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
583 } else {
584 p->r = lvalue_type(p->type.t) | VT_LOCAL;
586 p->r2 = VT_CONST;
587 p->c.ul = l;
592 #ifdef TCC_TARGET_ARM
593 /* find a register of class 'rc2' with at most one reference on stack.
594 * If none, call get_reg(rc) */
595 ST_FUNC int get_reg_ex(int rc, int rc2)
597 int r;
598 SValue *p;
600 for(r=0;r<NB_REGS;r++) {
601 if (reg_classes[r] & rc2) {
602 int n;
603 n=0;
604 for(p = vstack; p <= vtop; p++) {
605 if ((p->r & VT_VALMASK) == r ||
606 (p->r2 & VT_VALMASK) == r)
607 n++;
609 if (n <= 1)
610 return r;
613 return get_reg(rc);
615 #endif
617 /* find a free register of class 'rc'. If none, save one register */
618 ST_FUNC int get_reg(int rc)
620 int r;
621 SValue *p;
623 /* find a free register */
624 for(r=0;r<NB_REGS;r++) {
625 if (reg_classes[r] & rc) {
626 for(p=vstack;p<=vtop;p++) {
627 if ((p->r & VT_VALMASK) == r ||
628 (p->r2 & VT_VALMASK) == r)
629 goto notfound;
631 return r;
633 notfound: ;
636 /* no register left : free the first one on the stack (VERY
637 IMPORTANT to start from the bottom to ensure that we don't
638 spill registers used in gen_opi()) */
639 for(p=vstack;p<=vtop;p++) {
640 /* look at second register (if long long) */
641 r = p->r2 & VT_VALMASK;
642 if (r < VT_CONST && (reg_classes[r] & rc))
643 goto save_found;
644 r = p->r & VT_VALMASK;
645 if (r < VT_CONST && (reg_classes[r] & rc)) {
646 save_found:
647 save_reg(r);
648 return r;
651 /* Should never comes here */
652 return -1;
655 /* save registers up to (vtop - n) stack entry */
656 ST_FUNC void save_regs(int n)
658 int r;
659 SValue *p, *p1;
660 p1 = vtop - n;
661 for(p = vstack;p <= p1; p++) {
662 r = p->r & VT_VALMASK;
663 if (r < VT_CONST) {
664 save_reg(r);
669 /* move register 's' (of type 't') to 'r', and flush previous value of r to memory
670 if needed */
671 static void move_reg(int r, int s, int t)
673 SValue sv;
675 if (r != s) {
676 save_reg(r);
677 sv.type.t = t;
678 sv.type.ref = NULL;
679 sv.r = s;
680 sv.c.ul = 0;
681 load(r, &sv);
685 /* get address of vtop (vtop MUST BE an lvalue) */
686 static void gaddrof(void)
688 if (vtop->r & VT_REF)
689 gv(RC_INT);
690 vtop->r &= ~VT_LVAL;
691 /* tricky: if saved lvalue, then we can go back to lvalue */
692 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
693 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
698 #ifdef CONFIG_TCC_BCHECK
699 /* generate lvalue bound code */
700 static void gbound(void)
702 int lval_type;
703 CType type1;
705 vtop->r &= ~VT_MUSTBOUND;
706 /* if lvalue, then use checking code before dereferencing */
707 if (vtop->r & VT_LVAL) {
708 /* if not VT_BOUNDED value, then make one */
709 if (!(vtop->r & VT_BOUNDED)) {
710 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
711 /* must save type because we must set it to int to get pointer */
712 type1 = vtop->type;
713 vtop->type.t = VT_INT;
714 gaddrof();
715 vpushi(0);
716 gen_bounded_ptr_add();
717 vtop->r |= lval_type;
718 vtop->type = type1;
720 /* then check for dereferencing */
721 gen_bounded_ptr_deref();
724 #endif
726 /* store vtop a register belonging to class 'rc'. lvalues are
727 converted to values. Cannot be used if cannot be converted to
728 register value (such as structures). */
729 ST_FUNC int gv(int rc)
731 int r, bit_pos, bit_size, size, align, i;
732 int rc2;
734 /* NOTE: get_reg can modify vstack[] */
735 if (vtop->type.t & VT_BITFIELD) {
736 CType type;
737 int bits = 32;
738 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
739 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
740 /* remove bit field info to avoid loops */
741 vtop->type.t &= ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
742 /* cast to int to propagate signedness in following ops */
743 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
744 type.t = VT_LLONG;
745 bits = 64;
746 } else
747 type.t = VT_INT;
748 if((vtop->type.t & VT_UNSIGNED) ||
749 (vtop->type.t & VT_BTYPE) == VT_BOOL)
750 type.t |= VT_UNSIGNED;
751 gen_cast(&type);
752 /* generate shifts */
753 vpushi(bits - (bit_pos + bit_size));
754 gen_op(TOK_SHL);
755 vpushi(bits - bit_size);
756 /* NOTE: transformed to SHR if unsigned */
757 gen_op(TOK_SAR);
758 r = gv(rc);
759 } else {
760 if (is_float(vtop->type.t) &&
761 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
762 Sym *sym;
763 int *ptr;
764 unsigned long offset;
765 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
766 CValue check;
767 #endif
769 /* XXX: unify with initializers handling ? */
770 /* CPUs usually cannot use float constants, so we store them
771 generically in data segment */
772 size = type_size(&vtop->type, &align);
773 offset = (data_section->data_offset + align - 1) & -align;
774 data_section->data_offset = offset;
775 /* XXX: not portable yet */
776 #if defined(__i386__) || defined(__x86_64__)
777 /* Zero pad x87 tenbyte long doubles */
778 if (size == LDOUBLE_SIZE) {
779 vtop->c.tab[2] &= 0xffff;
780 #if LDOUBLE_SIZE == 16
781 vtop->c.tab[3] = 0;
782 #endif
784 #endif
785 ptr = section_ptr_add(data_section, size);
786 size = size >> 2;
787 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
788 check.d = 1;
789 if(check.tab[0])
790 for(i=0;i<size;i++)
791 ptr[i] = vtop->c.tab[size-1-i];
792 else
793 #endif
794 for(i=0;i<size;i++)
795 ptr[i] = vtop->c.tab[i];
796 sym = get_sym_ref(&vtop->type, data_section, offset, size << 2);
797 vtop->r |= VT_LVAL | VT_SYM;
798 vtop->sym = sym;
799 vtop->c.ptr_offset = 0;
801 #ifdef CONFIG_TCC_BCHECK
802 if (vtop->r & VT_MUSTBOUND)
803 gbound();
804 #endif
806 r = vtop->r & VT_VALMASK;
807 rc2 = (rc & RC_FLOAT) ? RC_FLOAT : RC_INT;
808 if (rc == RC_IRET)
809 rc2 = RC_LRET;
810 #ifdef TCC_TARGET_X86_64
811 else if (rc == RC_FRET)
812 rc2 = RC_QRET;
813 #endif
815 /* need to reload if:
816 - constant
817 - lvalue (need to dereference pointer)
818 - already a register, but not in the right class */
819 if (r >= VT_CONST
820 || (vtop->r & VT_LVAL)
821 || !(reg_classes[r] & rc)
822 #ifdef TCC_TARGET_X86_64
823 || ((vtop->type.t & VT_BTYPE) == VT_QLONG && !(reg_classes[vtop->r2] & rc2))
824 || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT && !(reg_classes[vtop->r2] & rc2))
825 #else
826 || ((vtop->type.t & VT_BTYPE) == VT_LLONG && !(reg_classes[vtop->r2] & rc2))
827 #endif
830 r = get_reg(rc);
831 #ifdef TCC_TARGET_X86_64
832 if (((vtop->type.t & VT_BTYPE) == VT_QLONG) || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT)) {
833 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
834 #else
835 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
836 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
837 unsigned long long ll;
838 #endif
839 int r2, original_type;
840 original_type = vtop->type.t;
841 /* two register type load : expand to two words
842 temporarily */
843 #ifndef TCC_TARGET_X86_64
844 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
845 /* load constant */
846 ll = vtop->c.ull;
847 vtop->c.ui = ll; /* first word */
848 load(r, vtop);
849 vtop->r = r; /* save register value */
850 vpushi(ll >> 32); /* second word */
851 } else
852 #endif
853 if (r >= VT_CONST || /* XXX: test to VT_CONST incorrect ? */
854 (vtop->r & VT_LVAL)) {
855 /* We do not want to modifier the long long
856 pointer here, so the safest (and less
857 efficient) is to save all the other registers
858 in the stack. XXX: totally inefficient. */
859 save_regs(1);
860 /* load from memory */
861 vtop->type.t = load_type;
862 load(r, vtop);
863 vdup();
864 vtop[-1].r = r; /* save register value */
865 /* increment pointer to get second word */
866 vtop->type.t = addr_type;
867 gaddrof();
868 vpushi(load_size);
869 gen_op('+');
870 vtop->r |= VT_LVAL;
871 vtop->type.t = load_type;
872 } else {
873 /* move registers */
874 load(r, vtop);
875 vdup();
876 vtop[-1].r = r; /* save register value */
877 vtop->r = vtop[-1].r2;
879 /* Allocate second register. Here we rely on the fact that
880 get_reg() tries first to free r2 of an SValue. */
881 r2 = get_reg(rc2);
882 load(r2, vtop);
883 vpop();
884 /* write second register */
885 vtop->r2 = r2;
886 vtop->type.t = original_type;
887 } else if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
888 int t1, t;
889 /* lvalue of scalar type : need to use lvalue type
890 because of possible cast */
891 t = vtop->type.t;
892 t1 = t;
893 /* compute memory access type */
894 if (vtop->r & VT_REF)
895 #ifdef TCC_TARGET_X86_64
896 t = VT_PTR;
897 #else
898 t = VT_INT;
899 #endif
900 else if (vtop->r & VT_LVAL_BYTE)
901 t = VT_BYTE;
902 else if (vtop->r & VT_LVAL_SHORT)
903 t = VT_SHORT;
904 if (vtop->r & VT_LVAL_UNSIGNED)
905 t |= VT_UNSIGNED;
906 vtop->type.t = t;
907 load(r, vtop);
908 /* restore wanted type */
909 vtop->type.t = t1;
910 } else {
911 /* one register type load */
912 load(r, vtop);
915 vtop->r = r;
916 #ifdef TCC_TARGET_C67
917 /* uses register pairs for doubles */
918 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
919 vtop->r2 = r+1;
920 #endif
922 return r;
925 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
926 ST_FUNC void gv2(int rc1, int rc2)
928 int v;
930 /* generate more generic register first. But VT_JMP or VT_CMP
931 values must be generated first in all cases to avoid possible
932 reload errors */
933 v = vtop[0].r & VT_VALMASK;
934 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
935 vswap();
936 gv(rc1);
937 vswap();
938 gv(rc2);
939 /* test if reload is needed for first register */
940 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
941 vswap();
942 gv(rc1);
943 vswap();
945 } else {
946 gv(rc2);
947 vswap();
948 gv(rc1);
949 vswap();
950 /* test if reload is needed for first register */
951 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
952 gv(rc2);
957 /* wrapper around RC_FRET to return a register by type */
958 static int rc_fret(int t)
960 #ifdef TCC_TARGET_X86_64
961 if (t == VT_LDOUBLE) {
962 return RC_ST0;
964 #endif
965 return RC_FRET;
968 /* wrapper around REG_FRET to return a register by type */
969 static int reg_fret(int t)
971 #ifdef TCC_TARGET_X86_64
972 if (t == VT_LDOUBLE) {
973 return TREG_ST0;
975 #endif
976 return REG_FRET;
979 /* expand long long on stack in two int registers */
980 static void lexpand(void)
982 int u;
984 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
985 gv(RC_INT);
986 vdup();
987 vtop[0].r = vtop[-1].r2;
988 vtop[0].r2 = VT_CONST;
989 vtop[-1].r2 = VT_CONST;
990 vtop[0].type.t = VT_INT | u;
991 vtop[-1].type.t = VT_INT | u;
994 #ifdef TCC_TARGET_ARM
995 /* expand long long on stack */
996 ST_FUNC void lexpand_nr(void)
998 int u,v;
1000 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
1001 vdup();
1002 vtop->r2 = VT_CONST;
1003 vtop->type.t = VT_INT | u;
1004 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
1005 if (v == VT_CONST) {
1006 vtop[-1].c.ui = vtop->c.ull;
1007 vtop->c.ui = vtop->c.ull >> 32;
1008 vtop->r = VT_CONST;
1009 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
1010 vtop->c.ui += 4;
1011 vtop->r = vtop[-1].r;
1012 } else if (v > VT_CONST) {
1013 vtop--;
1014 lexpand();
1015 } else
1016 vtop->r = vtop[-1].r2;
1017 vtop[-1].r2 = VT_CONST;
1018 vtop[-1].type.t = VT_INT | u;
1020 #endif
1022 /* build a long long from two ints */
1023 static void lbuild(int t)
1025 gv2(RC_INT, RC_INT);
1026 vtop[-1].r2 = vtop[0].r;
1027 vtop[-1].type.t = t;
1028 vpop();
1031 /* rotate n first stack elements to the bottom
1032 I1 ... In -> I2 ... In I1 [top is right]
1034 ST_FUNC void vrotb(int n)
1036 int i;
1037 SValue tmp;
1039 tmp = vtop[-n + 1];
1040 for(i=-n+1;i!=0;i++)
1041 vtop[i] = vtop[i+1];
1042 vtop[0] = tmp;
1045 /* rotate the n elements before entry e towards the top
1046 I1 ... In ... -> In I1 ... I(n-1) ... [top is right]
1048 ST_FUNC void vrote(SValue *e, int n)
1050 int i;
1051 SValue tmp;
1053 tmp = *e;
1054 for(i = 0;i < n - 1; i++)
1055 e[-i] = e[-i - 1];
1056 e[-n + 1] = tmp;
1059 /* rotate n first stack elements to the top
1060 I1 ... In -> In I1 ... I(n-1) [top is right]
1062 ST_FUNC void vrott(int n)
1064 vrote(vtop, n);
1067 /* pop stack value */
1068 ST_FUNC void vpop(void)
1070 int v;
1071 v = vtop->r & VT_VALMASK;
1072 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1073 /* for x86, we need to pop the FP stack */
1074 if (v == TREG_ST0 && !nocode_wanted) {
1075 o(0xd8dd); /* fstp %st(0) */
1076 } else
1077 #endif
1078 if (v == VT_JMP || v == VT_JMPI) {
1079 /* need to put correct jump if && or || without test */
1080 gsym(vtop->c.ul);
1082 vtop--;
1085 /* convert stack entry to register and duplicate its value in another
1086 register */
1087 static void gv_dup(void)
1089 int rc, t, r, r1;
1090 SValue sv;
1092 t = vtop->type.t;
1093 if ((t & VT_BTYPE) == VT_LLONG) {
1094 lexpand();
1095 gv_dup();
1096 vswap();
1097 vrotb(3);
1098 gv_dup();
1099 vrotb(4);
1100 /* stack: H L L1 H1 */
1101 lbuild(t);
1102 vrotb(3);
1103 vrotb(3);
1104 vswap();
1105 lbuild(t);
1106 vswap();
1107 } else {
1108 /* duplicate value */
1109 rc = RC_INT;
1110 sv.type.t = VT_INT;
1111 if (is_float(t)) {
1112 rc = RC_FLOAT;
1113 #ifdef TCC_TARGET_X86_64
1114 if ((t & VT_BTYPE) == VT_LDOUBLE) {
1115 rc = RC_ST0;
1117 #endif
1118 sv.type.t = t;
1120 r = gv(rc);
1121 r1 = get_reg(rc);
1122 sv.r = r;
1123 sv.c.ul = 0;
1124 load(r1, &sv); /* move r to r1 */
1125 vdup();
1126 /* duplicates value */
1127 if (r != r1)
1128 vtop->r = r1;
1132 /* Generate value test
1134 * Generate a test for any value (jump, comparison and integers) */
1135 ST_FUNC int gvtst(int inv, int t)
1137 int v = vtop->r & VT_VALMASK;
1138 if (v != VT_CMP && v != VT_JMP && v != VT_JMPI) {
1139 vpushi(0);
1140 gen_op(TOK_NE);
1142 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1143 /* constant jmp optimization */
1144 if ((vtop->c.i != 0) != inv)
1145 t = gjmp(t);
1146 vtop--;
1147 return t;
1149 return gtst(inv, t);
1152 #ifndef TCC_TARGET_X86_64
1153 /* generate CPU independent (unsigned) long long operations */
1154 static void gen_opl(int op)
1156 int t, a, b, op1, c, i;
1157 int func;
1158 unsigned short reg_iret = REG_IRET;
1159 unsigned short reg_lret = REG_LRET;
1160 SValue tmp;
1162 switch(op) {
1163 case '/':
1164 case TOK_PDIV:
1165 func = TOK___divdi3;
1166 goto gen_func;
1167 case TOK_UDIV:
1168 func = TOK___udivdi3;
1169 goto gen_func;
1170 case '%':
1171 func = TOK___moddi3;
1172 goto gen_mod_func;
1173 case TOK_UMOD:
1174 func = TOK___umoddi3;
1175 gen_mod_func:
1176 #ifdef TCC_ARM_EABI
1177 reg_iret = TREG_R2;
1178 reg_lret = TREG_R3;
1179 #endif
1180 gen_func:
1181 /* call generic long long function */
1182 vpush_global_sym(&func_old_type, func);
1183 vrott(3);
1184 gfunc_call(2);
1185 vpushi(0);
1186 vtop->r = reg_iret;
1187 vtop->r2 = reg_lret;
1188 break;
1189 case '^':
1190 case '&':
1191 case '|':
1192 case '*':
1193 case '+':
1194 case '-':
1195 t = vtop->type.t;
1196 vswap();
1197 lexpand();
1198 vrotb(3);
1199 lexpand();
1200 /* stack: L1 H1 L2 H2 */
1201 tmp = vtop[0];
1202 vtop[0] = vtop[-3];
1203 vtop[-3] = tmp;
1204 tmp = vtop[-2];
1205 vtop[-2] = vtop[-3];
1206 vtop[-3] = tmp;
1207 vswap();
1208 /* stack: H1 H2 L1 L2 */
1209 if (op == '*') {
1210 vpushv(vtop - 1);
1211 vpushv(vtop - 1);
1212 gen_op(TOK_UMULL);
1213 lexpand();
1214 /* stack: H1 H2 L1 L2 ML MH */
1215 for(i=0;i<4;i++)
1216 vrotb(6);
1217 /* stack: ML MH H1 H2 L1 L2 */
1218 tmp = vtop[0];
1219 vtop[0] = vtop[-2];
1220 vtop[-2] = tmp;
1221 /* stack: ML MH H1 L2 H2 L1 */
1222 gen_op('*');
1223 vrotb(3);
1224 vrotb(3);
1225 gen_op('*');
1226 /* stack: ML MH M1 M2 */
1227 gen_op('+');
1228 gen_op('+');
1229 } else if (op == '+' || op == '-') {
1230 /* XXX: add non carry method too (for MIPS or alpha) */
1231 if (op == '+')
1232 op1 = TOK_ADDC1;
1233 else
1234 op1 = TOK_SUBC1;
1235 gen_op(op1);
1236 /* stack: H1 H2 (L1 op L2) */
1237 vrotb(3);
1238 vrotb(3);
1239 gen_op(op1 + 1); /* TOK_xxxC2 */
1240 } else {
1241 gen_op(op);
1242 /* stack: H1 H2 (L1 op L2) */
1243 vrotb(3);
1244 vrotb(3);
1245 /* stack: (L1 op L2) H1 H2 */
1246 gen_op(op);
1247 /* stack: (L1 op L2) (H1 op H2) */
1249 /* stack: L H */
1250 lbuild(t);
1251 break;
1252 case TOK_SAR:
1253 case TOK_SHR:
1254 case TOK_SHL:
1255 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1256 t = vtop[-1].type.t;
1257 vswap();
1258 lexpand();
1259 vrotb(3);
1260 /* stack: L H shift */
1261 c = (int)vtop->c.i;
1262 /* constant: simpler */
1263 /* NOTE: all comments are for SHL. the other cases are
1264 done by swaping words */
1265 vpop();
1266 if (op != TOK_SHL)
1267 vswap();
1268 if (c >= 32) {
1269 /* stack: L H */
1270 vpop();
1271 if (c > 32) {
1272 vpushi(c - 32);
1273 gen_op(op);
1275 if (op != TOK_SAR) {
1276 vpushi(0);
1277 } else {
1278 gv_dup();
1279 vpushi(31);
1280 gen_op(TOK_SAR);
1282 vswap();
1283 } else {
1284 vswap();
1285 gv_dup();
1286 /* stack: H L L */
1287 vpushi(c);
1288 gen_op(op);
1289 vswap();
1290 vpushi(32 - c);
1291 if (op == TOK_SHL)
1292 gen_op(TOK_SHR);
1293 else
1294 gen_op(TOK_SHL);
1295 vrotb(3);
1296 /* stack: L L H */
1297 vpushi(c);
1298 if (op == TOK_SHL)
1299 gen_op(TOK_SHL);
1300 else
1301 gen_op(TOK_SHR);
1302 gen_op('|');
1304 if (op != TOK_SHL)
1305 vswap();
1306 lbuild(t);
1307 } else {
1308 /* XXX: should provide a faster fallback on x86 ? */
1309 switch(op) {
1310 case TOK_SAR:
1311 func = TOK___ashrdi3;
1312 goto gen_func;
1313 case TOK_SHR:
1314 func = TOK___lshrdi3;
1315 goto gen_func;
1316 case TOK_SHL:
1317 func = TOK___ashldi3;
1318 goto gen_func;
1321 break;
1322 default:
1323 /* compare operations */
1324 t = vtop->type.t;
1325 vswap();
1326 lexpand();
1327 vrotb(3);
1328 lexpand();
1329 /* stack: L1 H1 L2 H2 */
1330 tmp = vtop[-1];
1331 vtop[-1] = vtop[-2];
1332 vtop[-2] = tmp;
1333 /* stack: L1 L2 H1 H2 */
1334 /* compare high */
1335 op1 = op;
1336 /* when values are equal, we need to compare low words. since
1337 the jump is inverted, we invert the test too. */
1338 if (op1 == TOK_LT)
1339 op1 = TOK_LE;
1340 else if (op1 == TOK_GT)
1341 op1 = TOK_GE;
1342 else if (op1 == TOK_ULT)
1343 op1 = TOK_ULE;
1344 else if (op1 == TOK_UGT)
1345 op1 = TOK_UGE;
1346 a = 0;
1347 b = 0;
1348 gen_op(op1);
1349 if (op1 != TOK_NE) {
1350 a = gvtst(1, 0);
1352 if (op != TOK_EQ) {
1353 /* generate non equal test */
1354 /* XXX: NOT PORTABLE yet */
1355 if (a == 0) {
1356 b = gvtst(0, 0);
1357 } else {
1358 #if defined(TCC_TARGET_I386)
1359 b = psym(0x850f, 0);
1360 #elif defined(TCC_TARGET_ARM)
1361 b = ind;
1362 o(0x1A000000 | encbranch(ind, 0, 1));
1363 #elif defined(TCC_TARGET_C67)
1364 tcc_error("not implemented");
1365 #else
1366 #error not supported
1367 #endif
1370 /* compare low. Always unsigned */
1371 op1 = op;
1372 if (op1 == TOK_LT)
1373 op1 = TOK_ULT;
1374 else if (op1 == TOK_LE)
1375 op1 = TOK_ULE;
1376 else if (op1 == TOK_GT)
1377 op1 = TOK_UGT;
1378 else if (op1 == TOK_GE)
1379 op1 = TOK_UGE;
1380 gen_op(op1);
1381 a = gvtst(1, a);
1382 gsym(b);
1383 vseti(VT_JMPI, a);
1384 break;
1387 #endif
1389 /* handle integer constant optimizations and various machine
1390 independent opt */
1391 static void gen_opic(int op)
1393 int c1, c2, t1, t2, n;
1394 SValue *v1, *v2;
1395 long long l1, l2;
1396 typedef unsigned long long U;
1398 v1 = vtop - 1;
1399 v2 = vtop;
1400 t1 = v1->type.t & VT_BTYPE;
1401 t2 = v2->type.t & VT_BTYPE;
1403 if (t1 == VT_LLONG)
1404 l1 = v1->c.ll;
1405 else if (v1->type.t & VT_UNSIGNED)
1406 l1 = v1->c.ui;
1407 else
1408 l1 = v1->c.i;
1410 if (t2 == VT_LLONG)
1411 l2 = v2->c.ll;
1412 else if (v2->type.t & VT_UNSIGNED)
1413 l2 = v2->c.ui;
1414 else
1415 l2 = v2->c.i;
1417 /* currently, we cannot do computations with forward symbols */
1418 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1419 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1420 if (c1 && c2) {
1421 switch(op) {
1422 case '+': l1 += l2; break;
1423 case '-': l1 -= l2; break;
1424 case '&': l1 &= l2; break;
1425 case '^': l1 ^= l2; break;
1426 case '|': l1 |= l2; break;
1427 case '*': l1 *= l2; break;
1429 case TOK_PDIV:
1430 case '/':
1431 case '%':
1432 case TOK_UDIV:
1433 case TOK_UMOD:
1434 /* if division by zero, generate explicit division */
1435 if (l2 == 0) {
1436 if (const_wanted)
1437 tcc_error("division by zero in constant");
1438 goto general_case;
1440 switch(op) {
1441 default: l1 /= l2; break;
1442 case '%': l1 %= l2; break;
1443 case TOK_UDIV: l1 = (U)l1 / l2; break;
1444 case TOK_UMOD: l1 = (U)l1 % l2; break;
1446 break;
1447 case TOK_SHL: l1 <<= l2; break;
1448 case TOK_SHR: l1 = (U)l1 >> l2; break;
1449 case TOK_SAR: l1 >>= l2; break;
1450 /* tests */
1451 case TOK_ULT: l1 = (U)l1 < (U)l2; break;
1452 case TOK_UGE: l1 = (U)l1 >= (U)l2; break;
1453 case TOK_EQ: l1 = l1 == l2; break;
1454 case TOK_NE: l1 = l1 != l2; break;
1455 case TOK_ULE: l1 = (U)l1 <= (U)l2; break;
1456 case TOK_UGT: l1 = (U)l1 > (U)l2; break;
1457 case TOK_LT: l1 = l1 < l2; break;
1458 case TOK_GE: l1 = l1 >= l2; break;
1459 case TOK_LE: l1 = l1 <= l2; break;
1460 case TOK_GT: l1 = l1 > l2; break;
1461 /* logical */
1462 case TOK_LAND: l1 = l1 && l2; break;
1463 case TOK_LOR: l1 = l1 || l2; break;
1464 default:
1465 goto general_case;
1467 v1->c.ll = l1;
1468 vtop--;
1469 } else {
1470 /* if commutative ops, put c2 as constant */
1471 if (c1 && (op == '+' || op == '&' || op == '^' ||
1472 op == '|' || op == '*')) {
1473 vswap();
1474 c2 = c1; //c = c1, c1 = c2, c2 = c;
1475 l2 = l1; //l = l1, l1 = l2, l2 = l;
1477 /* Filter out NOP operations like x*1, x-0, x&-1... */
1478 if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
1479 op == TOK_PDIV) &&
1480 l2 == 1) ||
1481 ((op == '+' || op == '-' || op == '|' || op == '^' ||
1482 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
1483 l2 == 0) ||
1484 (op == '&' &&
1485 l2 == -1))) {
1486 /* nothing to do */
1487 vtop--;
1488 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
1489 /* try to use shifts instead of muls or divs */
1490 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
1491 n = -1;
1492 while (l2) {
1493 l2 >>= 1;
1494 n++;
1496 vtop->c.ll = n;
1497 if (op == '*')
1498 op = TOK_SHL;
1499 else if (op == TOK_PDIV)
1500 op = TOK_SAR;
1501 else
1502 op = TOK_SHR;
1504 goto general_case;
1505 } else if (c2 && (op == '+' || op == '-') &&
1506 (((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM))
1507 || (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
1508 /* symbol + constant case */
1509 if (op == '-')
1510 l2 = -l2;
1511 vtop--;
1512 vtop->c.ll += l2;
1513 } else {
1514 general_case:
1515 if (!nocode_wanted) {
1516 /* call low level op generator */
1517 if (t1 == VT_LLONG || t2 == VT_LLONG)
1518 gen_opl(op);
1519 else
1520 gen_opi(op);
1521 } else {
1522 vtop--;
1528 /* generate a floating point operation with constant propagation */
1529 static void gen_opif(int op)
1531 int c1, c2;
1532 SValue *v1, *v2;
1533 long double f1, f2;
1535 v1 = vtop - 1;
1536 v2 = vtop;
1537 /* currently, we cannot do computations with forward symbols */
1538 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1539 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1540 if (c1 && c2) {
1541 if (v1->type.t == VT_FLOAT) {
1542 f1 = v1->c.f;
1543 f2 = v2->c.f;
1544 } else if (v1->type.t == VT_DOUBLE) {
1545 f1 = v1->c.d;
1546 f2 = v2->c.d;
1547 } else {
1548 f1 = v1->c.ld;
1549 f2 = v2->c.ld;
1552 /* NOTE: we only do constant propagation if finite number (not
1553 NaN or infinity) (ANSI spec) */
1554 if (!ieee_finite(f1) || !ieee_finite(f2))
1555 goto general_case;
1557 switch(op) {
1558 case '+': f1 += f2; break;
1559 case '-': f1 -= f2; break;
1560 case '*': f1 *= f2; break;
1561 case '/':
1562 if (f2 == 0.0) {
1563 if (const_wanted)
1564 tcc_error("division by zero in constant");
1565 goto general_case;
1567 f1 /= f2;
1568 break;
1569 /* XXX: also handles tests ? */
1570 default:
1571 goto general_case;
1573 /* XXX: overflow test ? */
1574 if (v1->type.t == VT_FLOAT) {
1575 v1->c.f = f1;
1576 } else if (v1->type.t == VT_DOUBLE) {
1577 v1->c.d = f1;
1578 } else {
1579 v1->c.ld = f1;
1581 vtop--;
1582 } else {
1583 general_case:
1584 if (!nocode_wanted) {
1585 gen_opf(op);
1586 } else {
1587 vtop--;
1592 static int pointed_size(CType *type)
1594 int align;
1595 return type_size(pointed_type(type), &align);
1598 static void vla_runtime_pointed_size(CType *type)
1600 int align;
1601 vla_runtime_type_size(pointed_type(type), &align);
1604 static inline int is_null_pointer(SValue *p)
1606 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
1607 return 0;
1608 return ((p->type.t & VT_BTYPE) == VT_INT && p->c.i == 0) ||
1609 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.ll == 0) ||
1610 ((p->type.t & VT_BTYPE) == VT_PTR && p->c.ptr_offset == 0);
1613 static inline int is_integer_btype(int bt)
1615 return (bt == VT_BYTE || bt == VT_SHORT ||
1616 bt == VT_INT || bt == VT_LLONG);
1619 /* check types for comparison or subtraction of pointers */
1620 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
1622 CType *type1, *type2, tmp_type1, tmp_type2;
1623 int bt1, bt2;
1625 /* null pointers are accepted for all comparisons as gcc */
1626 if (is_null_pointer(p1) || is_null_pointer(p2))
1627 return;
1628 type1 = &p1->type;
1629 type2 = &p2->type;
1630 bt1 = type1->t & VT_BTYPE;
1631 bt2 = type2->t & VT_BTYPE;
1632 /* accept comparison between pointer and integer with a warning */
1633 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
1634 if (op != TOK_LOR && op != TOK_LAND )
1635 tcc_warning("comparison between pointer and integer");
1636 return;
1639 /* both must be pointers or implicit function pointers */
1640 if (bt1 == VT_PTR) {
1641 type1 = pointed_type(type1);
1642 } else if (bt1 != VT_FUNC)
1643 goto invalid_operands;
1645 if (bt2 == VT_PTR) {
1646 type2 = pointed_type(type2);
1647 } else if (bt2 != VT_FUNC) {
1648 invalid_operands:
1649 tcc_error("invalid operands to binary %s", get_tok_str(op, NULL));
1651 if ((type1->t & VT_BTYPE) == VT_VOID ||
1652 (type2->t & VT_BTYPE) == VT_VOID)
1653 return;
1654 tmp_type1 = *type1;
1655 tmp_type2 = *type2;
1656 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1657 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1658 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
1659 /* gcc-like error if '-' is used */
1660 if (op == '-')
1661 goto invalid_operands;
1662 else
1663 tcc_warning("comparison of distinct pointer types lacks a cast");
1667 /* generic gen_op: handles types problems */
1668 ST_FUNC void gen_op(int op)
1670 int u, t1, t2, bt1, bt2, t;
1671 CType type1;
1673 t1 = vtop[-1].type.t;
1674 t2 = vtop[0].type.t;
1675 bt1 = t1 & VT_BTYPE;
1676 bt2 = t2 & VT_BTYPE;
1678 if (bt1 == VT_PTR || bt2 == VT_PTR) {
1679 /* at least one operand is a pointer */
1680 /* relationnal op: must be both pointers */
1681 if (op >= TOK_ULT && op <= TOK_LOR) {
1682 check_comparison_pointer_types(vtop - 1, vtop, op);
1683 /* pointers are handled are unsigned */
1684 #ifdef TCC_TARGET_X86_64
1685 t = VT_LLONG | VT_UNSIGNED;
1686 #else
1687 t = VT_INT | VT_UNSIGNED;
1688 #endif
1689 goto std_op;
1691 /* if both pointers, then it must be the '-' op */
1692 if (bt1 == VT_PTR && bt2 == VT_PTR) {
1693 if (op != '-')
1694 tcc_error("cannot use pointers here");
1695 check_comparison_pointer_types(vtop - 1, vtop, op);
1696 /* XXX: check that types are compatible */
1697 if (vtop[-1].type.t & VT_VLA) {
1698 vla_runtime_pointed_size(&vtop[-1].type);
1699 } else {
1700 vpushi(pointed_size(&vtop[-1].type));
1702 vrott(3);
1703 gen_opic(op);
1704 /* set to integer type */
1705 #ifdef TCC_TARGET_X86_64
1706 vtop->type.t = VT_LLONG;
1707 #else
1708 vtop->type.t = VT_INT;
1709 #endif
1710 vswap();
1711 gen_op(TOK_PDIV);
1712 } else {
1713 /* exactly one pointer : must be '+' or '-'. */
1714 if (op != '-' && op != '+')
1715 tcc_error("cannot use pointers here");
1716 /* Put pointer as first operand */
1717 if (bt2 == VT_PTR) {
1718 vswap();
1719 swap(&t1, &t2);
1721 type1 = vtop[-1].type;
1722 type1.t &= ~VT_ARRAY;
1723 if (vtop[-1].type.t & VT_VLA)
1724 vla_runtime_pointed_size(&vtop[-1].type);
1725 else {
1726 u = pointed_size(&vtop[-1].type);
1727 if (u < 0)
1728 tcc_error("unknown array element size");
1729 #ifdef TCC_TARGET_X86_64
1730 vpushll(u);
1731 #else
1732 /* XXX: cast to int ? (long long case) */
1733 vpushi(u);
1734 #endif
1736 gen_op('*');
1737 #ifdef CONFIG_TCC_BCHECK
1738 /* if evaluating constant expression, no code should be
1739 generated, so no bound check */
1740 if (tcc_state->do_bounds_check && !const_wanted) {
1741 /* if bounded pointers, we generate a special code to
1742 test bounds */
1743 if (op == '-') {
1744 vpushi(0);
1745 vswap();
1746 gen_op('-');
1748 gen_bounded_ptr_add();
1749 } else
1750 #endif
1752 gen_opic(op);
1754 /* put again type if gen_opic() swaped operands */
1755 vtop->type = type1;
1757 } else if (is_float(bt1) || is_float(bt2)) {
1758 /* compute bigger type and do implicit casts */
1759 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
1760 t = VT_LDOUBLE;
1761 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
1762 t = VT_DOUBLE;
1763 } else {
1764 t = VT_FLOAT;
1766 /* floats can only be used for a few operations */
1767 if (op != '+' && op != '-' && op != '*' && op != '/' &&
1768 (op < TOK_ULT || op > TOK_GT))
1769 tcc_error("invalid operands for binary operation");
1770 goto std_op;
1771 } else if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL) {
1772 t = bt1 == VT_LLONG ? VT_LLONG : VT_INT;
1773 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (t | VT_UNSIGNED))
1774 t |= VT_UNSIGNED;
1775 goto std_op;
1776 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
1777 /* cast to biggest op */
1778 t = VT_LLONG;
1779 /* convert to unsigned if it does not fit in a long long */
1780 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
1781 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
1782 t |= VT_UNSIGNED;
1783 goto std_op;
1784 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
1785 tcc_error("comparison of struct");
1786 } else {
1787 /* integer operations */
1788 t = VT_INT;
1789 /* convert to unsigned if it does not fit in an integer */
1790 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
1791 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
1792 t |= VT_UNSIGNED;
1793 std_op:
1794 /* XXX: currently, some unsigned operations are explicit, so
1795 we modify them here */
1796 if (t & VT_UNSIGNED) {
1797 if (op == TOK_SAR)
1798 op = TOK_SHR;
1799 else if (op == '/')
1800 op = TOK_UDIV;
1801 else if (op == '%')
1802 op = TOK_UMOD;
1803 else if (op == TOK_LT)
1804 op = TOK_ULT;
1805 else if (op == TOK_GT)
1806 op = TOK_UGT;
1807 else if (op == TOK_LE)
1808 op = TOK_ULE;
1809 else if (op == TOK_GE)
1810 op = TOK_UGE;
1812 vswap();
1813 type1.t = t;
1814 gen_cast(&type1);
1815 vswap();
1816 /* special case for shifts and long long: we keep the shift as
1817 an integer */
1818 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
1819 type1.t = VT_INT;
1820 gen_cast(&type1);
1821 if (is_float(t))
1822 gen_opif(op);
1823 else
1824 gen_opic(op);
1825 if (op >= TOK_ULT && op <= TOK_GT) {
1826 /* relationnal op: the result is an int */
1827 vtop->type.t = VT_INT;
1828 } else {
1829 vtop->type.t = t;
1834 #ifndef TCC_TARGET_ARM
1835 /* generic itof for unsigned long long case */
1836 static void gen_cvt_itof1(int t)
1838 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
1839 (VT_LLONG | VT_UNSIGNED)) {
1841 if (t == VT_FLOAT)
1842 vpush_global_sym(&func_old_type, TOK___floatundisf);
1843 #if LDOUBLE_SIZE != 8
1844 else if (t == VT_LDOUBLE)
1845 vpush_global_sym(&func_old_type, TOK___floatundixf);
1846 #endif
1847 else
1848 vpush_global_sym(&func_old_type, TOK___floatundidf);
1849 vrott(2);
1850 gfunc_call(1);
1851 vpushi(0);
1852 vtop->r = reg_fret(t);
1853 } else {
1854 gen_cvt_itof(t);
1857 #endif
1859 /* generic ftoi for unsigned long long case */
1860 static void gen_cvt_ftoi1(int t)
1862 int st;
1864 if (t == (VT_LLONG | VT_UNSIGNED)) {
1865 /* not handled natively */
1866 st = vtop->type.t & VT_BTYPE;
1867 if (st == VT_FLOAT)
1868 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
1869 #if LDOUBLE_SIZE != 8
1870 else if (st == VT_LDOUBLE)
1871 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
1872 #endif
1873 else
1874 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
1875 vrott(2);
1876 gfunc_call(1);
1877 vpushi(0);
1878 vtop->r = REG_IRET;
1879 vtop->r2 = REG_LRET;
1880 } else {
1881 gen_cvt_ftoi(t);
1885 /* force char or short cast */
1886 static void force_charshort_cast(int t)
1888 int bits, dbt;
1889 dbt = t & VT_BTYPE;
1890 /* XXX: add optimization if lvalue : just change type and offset */
1891 if (dbt == VT_BYTE)
1892 bits = 8;
1893 else
1894 bits = 16;
1895 if (t & VT_UNSIGNED) {
1896 vpushi((1 << bits) - 1);
1897 gen_op('&');
1898 } else {
1899 bits = 32 - bits;
1900 vpushi(bits);
1901 gen_op(TOK_SHL);
1902 /* result must be signed or the SAR is converted to an SHL
1903 This was not the case when "t" was a signed short
1904 and the last value on the stack was an unsigned int */
1905 vtop->type.t &= ~VT_UNSIGNED;
1906 vpushi(bits);
1907 gen_op(TOK_SAR);
1911 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
1912 static void gen_cast(CType *type)
1914 int sbt, dbt, sf, df, c, p;
1916 /* special delayed cast for char/short */
1917 /* XXX: in some cases (multiple cascaded casts), it may still
1918 be incorrect */
1919 if (vtop->r & VT_MUSTCAST) {
1920 vtop->r &= ~VT_MUSTCAST;
1921 force_charshort_cast(vtop->type.t);
1924 /* bitfields first get cast to ints */
1925 if (vtop->type.t & VT_BITFIELD) {
1926 gv(RC_INT);
1929 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
1930 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
1932 if (sbt != dbt) {
1933 sf = is_float(sbt);
1934 df = is_float(dbt);
1935 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1936 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
1937 if (c) {
1938 /* constant case: we can do it now */
1939 /* XXX: in ISOC, cannot do it if error in convert */
1940 if (sbt == VT_FLOAT)
1941 vtop->c.ld = vtop->c.f;
1942 else if (sbt == VT_DOUBLE)
1943 vtop->c.ld = vtop->c.d;
1945 if (df) {
1946 if ((sbt & VT_BTYPE) == VT_LLONG) {
1947 if (sbt & VT_UNSIGNED)
1948 vtop->c.ld = vtop->c.ull;
1949 else
1950 vtop->c.ld = vtop->c.ll;
1951 } else if(!sf) {
1952 if (sbt & VT_UNSIGNED)
1953 vtop->c.ld = vtop->c.ui;
1954 else
1955 vtop->c.ld = vtop->c.i;
1958 if (dbt == VT_FLOAT)
1959 vtop->c.f = (float)vtop->c.ld;
1960 else if (dbt == VT_DOUBLE)
1961 vtop->c.d = (double)vtop->c.ld;
1962 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
1963 vtop->c.ull = (unsigned long long)vtop->c.ld;
1964 } else if (sf && dbt == VT_BOOL) {
1965 vtop->c.i = (vtop->c.ld != 0);
1966 } else {
1967 if(sf)
1968 vtop->c.ll = (long long)vtop->c.ld;
1969 else if (sbt == (VT_LLONG|VT_UNSIGNED))
1970 vtop->c.ll = vtop->c.ull;
1971 else if (sbt & VT_UNSIGNED)
1972 vtop->c.ll = vtop->c.ui;
1973 #ifdef TCC_TARGET_X86_64
1974 else if (sbt == VT_PTR)
1976 #endif
1977 else if (sbt != VT_LLONG)
1978 vtop->c.ll = vtop->c.i;
1980 if (dbt == (VT_LLONG|VT_UNSIGNED))
1981 vtop->c.ull = vtop->c.ll;
1982 else if (dbt == VT_BOOL)
1983 vtop->c.i = (vtop->c.ll != 0);
1984 #ifdef TCC_TARGET_X86_64
1985 else if (dbt == VT_PTR)
1987 #endif
1988 else if (dbt != VT_LLONG) {
1989 int s, dt, warr = 0;
1990 long long ll;
1991 dt = dbt & VT_BTYPE;
1992 ll = vtop->c.ll;
1993 if (dt == VT_BYTE){
1994 if((ll != (unsigned char)ll) && (ll != (char)ll))
1995 warr = 1;
1996 s = 24;
1997 }else if (dt == VT_SHORT){
1998 if((ll != (unsigned short)ll) && (ll != (short)ll))
1999 warr = 1;
2000 s = 16;
2001 }else{
2002 if((ll != (unsigned int)ll) && (ll != (int)ll))
2003 warr = 1;
2004 s = 0;
2006 if(warr && !is_force){
2007 if(dt == VT_ENUM){
2008 tcc_warning("large integer implicitly truncated to unsigned type");
2009 dbt = VT_UNSIGNED;
2010 }else
2011 tcc_warning("overflow in implicit constant conversion");
2013 if(dbt & VT_UNSIGNED)
2014 vtop->c.ui = ((unsigned int)vtop->c.ll << s) >> s;
2015 else
2016 vtop->c.i = ((int)vtop->c.ll << s) >> s;
2019 } else if (p && dbt == VT_BOOL) {
2020 vtop->r = VT_CONST;
2021 vtop->c.i = 1;
2022 } else if (!nocode_wanted) {
2023 /* non constant case: generate code */
2024 if (sf && df) {
2025 /* convert from fp to fp */
2026 gen_cvt_ftof(dbt);
2027 } else if (df) {
2028 /* convert int to fp */
2029 gen_cvt_itof1(dbt);
2030 } else if (sf) {
2031 /* convert fp to int */
2032 if (dbt == VT_BOOL) {
2033 vpushi(0);
2034 gen_op(TOK_NE);
2035 } else {
2036 /* we handle char/short/etc... with generic code */
2037 if (dbt != (VT_INT | VT_UNSIGNED) &&
2038 dbt != (VT_LLONG | VT_UNSIGNED) &&
2039 dbt != VT_LLONG)
2040 dbt = VT_INT;
2041 gen_cvt_ftoi1(dbt);
2042 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
2043 /* additional cast for char/short... */
2044 vtop->type.t = dbt;
2045 gen_cast(type);
2048 #ifndef TCC_TARGET_X86_64
2049 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
2050 if ((sbt & VT_BTYPE) != VT_LLONG) {
2051 /* scalar to long long */
2052 /* machine independent conversion */
2053 gv(RC_INT);
2054 /* generate high word */
2055 if (sbt == (VT_INT | VT_UNSIGNED)) {
2056 vpushi(0);
2057 gv(RC_INT);
2058 } else {
2059 if (sbt == VT_PTR) {
2060 /* cast from pointer to int before we apply
2061 shift operation, which pointers don't support*/
2062 gen_cast(&int_type);
2064 gv_dup();
2065 vpushi(31);
2066 gen_op(TOK_SAR);
2068 /* patch second register */
2069 vtop[-1].r2 = vtop->r;
2070 vpop();
2072 #else
2073 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
2074 (dbt & VT_BTYPE) == VT_PTR ||
2075 (dbt & VT_BTYPE) == VT_FUNC) {
2076 if ((sbt & VT_BTYPE) != VT_LLONG &&
2077 (sbt & VT_BTYPE) != VT_PTR &&
2078 (sbt & VT_BTYPE) != VT_FUNC) {
2079 /* need to convert from 32bit to 64bit */
2080 int r = gv(RC_INT);
2081 if (sbt != (VT_INT | VT_UNSIGNED)) {
2082 /* x86_64 specific: movslq */
2083 o(0x6348);
2084 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
2087 #endif
2088 } else if (dbt == VT_BOOL) {
2089 /* scalar to bool */
2090 vpushi(0);
2091 gen_op(TOK_NE);
2092 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
2093 (dbt & VT_BTYPE) == VT_SHORT) {
2094 if (sbt == VT_PTR) {
2095 vtop->type.t = VT_INT;
2096 tcc_warning("nonportable conversion from pointer to char/short");
2098 force_charshort_cast(dbt);
2099 } else if ((dbt & VT_BTYPE) == VT_INT) {
2100 /* scalar to int */
2101 if (sbt == VT_LLONG) {
2102 /* from long long: just take low order word */
2103 lexpand();
2104 vpop();
2106 /* if lvalue and single word type, nothing to do because
2107 the lvalue already contains the real type size (see
2108 VT_LVAL_xxx constants) */
2111 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
2112 /* if we are casting between pointer types,
2113 we must update the VT_LVAL_xxx size */
2114 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
2115 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
2117 vtop->type = *type;
2120 /* return type size as known at compile time. Put alignment at 'a' */
2121 ST_FUNC int type_size(CType *type, int *a)
2123 Sym *s;
2124 int bt;
2126 bt = type->t & VT_BTYPE;
2127 if (bt == VT_STRUCT) {
2128 /* struct/union */
2129 s = type->ref;
2130 *a = s->r;
2131 return s->c;
2132 } else if (bt == VT_PTR) {
2133 if (type->t & VT_ARRAY) {
2134 int ts;
2136 s = type->ref;
2137 ts = type_size(&s->type, a);
2139 if (ts < 0 && s->c < 0)
2140 ts = -ts;
2142 return ts * s->c;
2143 } else {
2144 *a = PTR_SIZE;
2145 return PTR_SIZE;
2147 } else if (bt == VT_LDOUBLE) {
2148 *a = LDOUBLE_ALIGN;
2149 return LDOUBLE_SIZE;
2150 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
2151 #ifdef TCC_TARGET_I386
2152 #ifdef TCC_TARGET_PE
2153 *a = 8;
2154 #else
2155 *a = 4;
2156 #endif
2157 #elif defined(TCC_TARGET_ARM)
2158 #ifdef TCC_ARM_EABI
2159 *a = 8;
2160 #else
2161 *a = 4;
2162 #endif
2163 #else
2164 *a = 8;
2165 #endif
2166 return 8;
2167 } else if (bt == VT_INT || bt == VT_ENUM || bt == VT_FLOAT) {
2168 *a = 4;
2169 return 4;
2170 } else if (bt == VT_SHORT) {
2171 *a = 2;
2172 return 2;
2173 } else if (bt == VT_QLONG || bt == VT_QFLOAT) {
2174 *a = 8;
2175 return 16;
2176 } else {
2177 /* char, void, function, _Bool */
2178 *a = 1;
2179 return 1;
2183 /* push type size as known at runtime time on top of value stack. Put
2184 alignment at 'a' */
2185 ST_FUNC void vla_runtime_type_size(CType *type, int *a)
2187 if (type->t & VT_VLA) {
2188 vset(&int_type, VT_LOCAL|VT_LVAL, type->ref->c);
2189 } else {
2190 vpushi(type_size(type, a));
2194 static void vla_sp_save(void) {
2195 if (!(vla_flags & VLA_SP_LOC_SET)) {
2196 *vla_sp_loc = (loc -= PTR_SIZE);
2197 vla_flags |= VLA_SP_LOC_SET;
2199 if (!(vla_flags & VLA_SP_SAVED)) {
2200 gen_vla_sp_save(*vla_sp_loc);
2201 vla_flags |= VLA_SP_SAVED;
2205 /* return the pointed type of t */
2206 static inline CType *pointed_type(CType *type)
2208 return &type->ref->type;
2211 /* modify type so that its it is a pointer to type. */
2212 ST_FUNC void mk_pointer(CType *type)
2214 Sym *s;
2215 s = sym_push(SYM_FIELD, type, 0, -1);
2216 type->t = VT_PTR | (type->t & ~VT_TYPE);
2217 type->ref = s;
2220 /* compare function types. OLD functions match any new functions */
2221 static int is_compatible_func(CType *type1, CType *type2)
2223 Sym *s1, *s2;
2225 s1 = type1->ref;
2226 s2 = type2->ref;
2227 if (!is_compatible_types(&s1->type, &s2->type))
2228 return 0;
2229 /* check func_call */
2230 if (s1->a.func_call != s2->a.func_call)
2231 return 0;
2232 /* XXX: not complete */
2233 if (s1->c == FUNC_OLD || s2->c == FUNC_OLD)
2234 return 1;
2235 if (s1->c != s2->c)
2236 return 0;
2237 while (s1 != NULL) {
2238 if (s2 == NULL)
2239 return 0;
2240 if (!is_compatible_parameter_types(&s1->type, &s2->type))
2241 return 0;
2242 s1 = s1->next;
2243 s2 = s2->next;
2245 if (s2)
2246 return 0;
2247 return 1;
2250 /* return true if type1 and type2 are the same. If unqualified is
2251 true, qualifiers on the types are ignored.
2253 - enums are not checked as gcc __builtin_types_compatible_p ()
2255 static int compare_types(CType *type1, CType *type2, int unqualified)
2257 int bt1, t1, t2;
2259 t1 = type1->t & VT_TYPE;
2260 t2 = type2->t & VT_TYPE;
2261 if (unqualified) {
2262 /* strip qualifiers before comparing */
2263 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
2264 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
2266 /* Default Vs explicit signedness only matters for char */
2267 if ((t1 & VT_BTYPE) != VT_BYTE) {
2268 t1 &= ~VT_DEFSIGN;
2269 t2 &= ~VT_DEFSIGN;
2271 /* XXX: bitfields ? */
2272 if (t1 != t2)
2273 return 0;
2274 /* test more complicated cases */
2275 bt1 = t1 & VT_BTYPE;
2276 if (bt1 == VT_PTR) {
2277 type1 = pointed_type(type1);
2278 type2 = pointed_type(type2);
2279 return is_compatible_types(type1, type2);
2280 } else if (bt1 == VT_STRUCT) {
2281 return (type1->ref == type2->ref);
2282 } else if (bt1 == VT_FUNC) {
2283 return is_compatible_func(type1, type2);
2284 } else {
2285 return 1;
2289 /* return true if type1 and type2 are exactly the same (including
2290 qualifiers).
2292 static int is_compatible_types(CType *type1, CType *type2)
2294 return compare_types(type1,type2,0);
2297 /* return true if type1 and type2 are the same (ignoring qualifiers).
2299 static int is_compatible_parameter_types(CType *type1, CType *type2)
2301 return compare_types(type1,type2,1);
2304 /* print a type. If 'varstr' is not NULL, then the variable is also
2305 printed in the type */
2306 /* XXX: union */
2307 /* XXX: add array and function pointers */
2308 static void type_to_str(char *buf, int buf_size,
2309 CType *type, const char *varstr)
2311 int bt, v, t;
2312 Sym *s, *sa;
2313 char buf1[256];
2314 const char *tstr;
2316 t = type->t & VT_TYPE;
2317 bt = t & VT_BTYPE;
2318 buf[0] = '\0';
2319 if (t & VT_CONSTANT)
2320 pstrcat(buf, buf_size, "const ");
2321 if (t & VT_VOLATILE)
2322 pstrcat(buf, buf_size, "volatile ");
2323 if ((t & (VT_DEFSIGN | VT_UNSIGNED)) == (VT_DEFSIGN | VT_UNSIGNED))
2324 pstrcat(buf, buf_size, "unsigned ");
2325 else if (t & VT_DEFSIGN)
2326 pstrcat(buf, buf_size, "signed ");
2327 switch(bt) {
2328 case VT_VOID:
2329 tstr = "void";
2330 goto add_tstr;
2331 case VT_BOOL:
2332 tstr = "_Bool";
2333 goto add_tstr;
2334 case VT_BYTE:
2335 tstr = "char";
2336 goto add_tstr;
2337 case VT_SHORT:
2338 tstr = "short";
2339 goto add_tstr;
2340 case VT_INT:
2341 tstr = "int";
2342 goto add_tstr;
2343 case VT_LONG:
2344 tstr = "long";
2345 goto add_tstr;
2346 case VT_LLONG:
2347 tstr = "long long";
2348 goto add_tstr;
2349 case VT_FLOAT:
2350 tstr = "float";
2351 goto add_tstr;
2352 case VT_DOUBLE:
2353 tstr = "double";
2354 goto add_tstr;
2355 case VT_LDOUBLE:
2356 tstr = "long double";
2357 add_tstr:
2358 pstrcat(buf, buf_size, tstr);
2359 break;
2360 case VT_ENUM:
2361 case VT_STRUCT:
2362 if (bt == VT_STRUCT)
2363 tstr = "struct ";
2364 else
2365 tstr = "enum ";
2366 pstrcat(buf, buf_size, tstr);
2367 v = type->ref->v & ~SYM_STRUCT;
2368 if (v >= SYM_FIRST_ANOM)
2369 pstrcat(buf, buf_size, "<anonymous>");
2370 else
2371 pstrcat(buf, buf_size, get_tok_str(v, NULL));
2372 break;
2373 case VT_FUNC:
2374 s = type->ref;
2375 type_to_str(buf, buf_size, &s->type, varstr);
2376 pstrcat(buf, buf_size, "(");
2377 sa = s->next;
2378 while (sa != NULL) {
2379 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
2380 pstrcat(buf, buf_size, buf1);
2381 sa = sa->next;
2382 if (sa)
2383 pstrcat(buf, buf_size, ", ");
2385 pstrcat(buf, buf_size, ")");
2386 goto no_var;
2387 case VT_PTR:
2388 s = type->ref;
2389 pstrcpy(buf1, sizeof(buf1), "*");
2390 if (varstr)
2391 pstrcat(buf1, sizeof(buf1), varstr);
2392 type_to_str(buf, buf_size, &s->type, buf1);
2393 goto no_var;
2395 if (varstr) {
2396 pstrcat(buf, buf_size, " ");
2397 pstrcat(buf, buf_size, varstr);
2399 no_var: ;
2402 /* verify type compatibility to store vtop in 'dt' type, and generate
2403 casts if needed. */
2404 static void gen_assign_cast(CType *dt)
2406 CType *st, *type1, *type2, tmp_type1, tmp_type2;
2407 char buf1[256], buf2[256];
2408 int dbt, sbt;
2410 st = &vtop->type; /* source type */
2411 dbt = dt->t & VT_BTYPE;
2412 sbt = st->t & VT_BTYPE;
2413 if (sbt == VT_VOID || dbt == VT_VOID)
2414 tcc_error("cannot cast from/to void");
2415 if (dt->t & VT_CONSTANT)
2416 tcc_warning("assignment of read-only location");
2417 switch(dbt) {
2418 case VT_PTR:
2419 /* special cases for pointers */
2420 /* '0' can also be a pointer */
2421 if (is_null_pointer(vtop))
2422 goto type_ok;
2423 /* accept implicit pointer to integer cast with warning */
2424 if (is_integer_btype(sbt)) {
2425 tcc_warning("assignment makes pointer from integer without a cast");
2426 goto type_ok;
2428 type1 = pointed_type(dt);
2429 /* a function is implicitely a function pointer */
2430 if (sbt == VT_FUNC) {
2431 if ((type1->t & VT_BTYPE) != VT_VOID &&
2432 !is_compatible_types(pointed_type(dt), st))
2433 tcc_warning("assignment from incompatible pointer type");
2434 goto type_ok;
2436 if (sbt != VT_PTR)
2437 goto error;
2438 type2 = pointed_type(st);
2439 if ((type1->t & VT_BTYPE) == VT_VOID ||
2440 (type2->t & VT_BTYPE) == VT_VOID) {
2441 /* void * can match anything */
2442 } else {
2443 /* exact type match, except for unsigned */
2444 tmp_type1 = *type1;
2445 tmp_type2 = *type2;
2446 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT |
2447 VT_VOLATILE);
2448 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT |
2449 VT_VOLATILE);
2450 if (!is_compatible_types(&tmp_type1, &tmp_type2))
2451 tcc_warning("assignment from incompatible pointer type");
2453 /* check const and volatile */
2454 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
2455 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
2456 tcc_warning("assignment discards qualifiers from pointer target type");
2457 break;
2458 case VT_BYTE:
2459 case VT_SHORT:
2460 case VT_INT:
2461 case VT_LLONG:
2462 if (sbt == VT_PTR || sbt == VT_FUNC) {
2463 tcc_warning("assignment makes integer from pointer without a cast");
2465 if (sbt == VT_STRUCT)
2466 goto error;
2467 /* XXX: more tests */
2468 break;
2469 case VT_STRUCT:
2470 tmp_type1 = *dt;
2471 tmp_type2 = *st;
2472 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2473 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2474 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2475 error:
2476 type_to_str(buf1, sizeof(buf1), st, NULL);
2477 type_to_str(buf2, sizeof(buf2), dt, NULL);
2478 tcc_error("cannot cast '%s' to '%s'", buf1, buf2);
2480 break;
2482 type_ok:
2483 gen_cast(dt);
2486 /* store vtop in lvalue pushed on stack */
2487 ST_FUNC void vstore(void)
2489 int sbt, dbt, ft, cc, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
2491 ft = vtop[-1].type.t;
2492 sbt = vtop->type.t & VT_BTYPE;
2493 dbt = ft & VT_BTYPE;
2494 cc = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
2495 if ((((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
2496 (sbt == VT_INT && dbt == VT_SHORT))
2497 && !(vtop->type.t & VT_BITFIELD) && !cc) {
2498 /* optimize char/short casts */
2499 delayed_cast = VT_MUSTCAST;
2500 vtop->type.t = ft & (VT_TYPE & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT)));
2501 /* XXX: factorize */
2502 if (ft & VT_CONSTANT)
2503 tcc_warning("assignment of read-only location");
2504 } else {
2505 delayed_cast = 0;
2506 if (!(ft & VT_BITFIELD))
2507 gen_assign_cast(&vtop[-1].type);
2510 if (sbt == VT_STRUCT) {
2511 /* if structure, only generate pointer */
2512 /* structure assignment : generate memcpy */
2513 /* XXX: optimize if small size */
2514 if (!nocode_wanted) {
2515 size = type_size(&vtop->type, &align);
2517 /* destination */
2518 vswap();
2519 vtop->type.t = VT_PTR;
2520 gaddrof();
2522 /* address of memcpy() */
2523 #ifdef TCC_ARM_EABI
2524 if(!(align & 7))
2525 vpush_global_sym(&func_old_type, TOK_memcpy8);
2526 else if(!(align & 3))
2527 vpush_global_sym(&func_old_type, TOK_memcpy4);
2528 else
2529 #endif
2530 vpush_global_sym(&func_old_type, TOK_memcpy);
2532 vswap();
2533 /* source */
2534 vpushv(vtop - 2);
2535 vtop->type.t = VT_PTR;
2536 gaddrof();
2537 /* type size */
2538 vpushi(size);
2539 gfunc_call(3);
2540 } else {
2541 vswap();
2542 vpop();
2544 /* leave source on stack */
2545 } else if (ft & VT_BITFIELD) {
2546 /* bitfield store handling */
2547 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
2548 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
2549 /* remove bit field info to avoid loops */
2550 vtop[-1].type.t = ft & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
2552 /* duplicate source into other register */
2553 gv_dup();
2554 vswap();
2555 vrott(3);
2557 if((ft & VT_BTYPE) == VT_BOOL) {
2558 gen_cast(&vtop[-1].type);
2559 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
2562 /* duplicate destination */
2563 vdup();
2564 vtop[-1] = vtop[-2];
2566 /* mask and shift source */
2567 if((ft & VT_BTYPE) != VT_BOOL) {
2568 if((ft & VT_BTYPE) == VT_LLONG) {
2569 vpushll((1ULL << bit_size) - 1ULL);
2570 } else {
2571 vpushi((1 << bit_size) - 1);
2573 gen_op('&');
2575 vpushi(bit_pos);
2576 gen_op(TOK_SHL);
2577 /* load destination, mask and or with source */
2578 vswap();
2579 if((ft & VT_BTYPE) == VT_LLONG) {
2580 vpushll(~(((1ULL << bit_size) - 1ULL) << bit_pos));
2581 } else {
2582 vpushi(~(((1 << bit_size) - 1) << bit_pos));
2584 gen_op('&');
2585 gen_op('|');
2586 /* store result */
2587 vstore();
2589 /* pop off shifted source from "duplicate source..." above */
2590 vpop();
2592 } else {
2593 #ifdef CONFIG_TCC_BCHECK
2594 /* bound check case */
2595 if (vtop[-1].r & VT_MUSTBOUND) {
2596 vswap();
2597 gbound();
2598 vswap();
2600 #endif
2601 if (!nocode_wanted) {
2602 rc = RC_INT;
2603 if (is_float(ft)) {
2604 rc = RC_FLOAT;
2605 #ifdef TCC_TARGET_X86_64
2606 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
2607 rc = RC_ST0;
2608 } else if ((ft & VT_BTYPE) == VT_QFLOAT) {
2609 rc = RC_FRET;
2611 #endif
2613 r = gv(rc); /* generate value */
2614 /* if lvalue was saved on stack, must read it */
2615 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
2616 SValue sv;
2617 t = get_reg(RC_INT);
2618 #ifdef TCC_TARGET_X86_64
2619 sv.type.t = VT_PTR;
2620 #else
2621 sv.type.t = VT_INT;
2622 #endif
2623 sv.r = VT_LOCAL | VT_LVAL;
2624 sv.c.ul = vtop[-1].c.ul;
2625 load(t, &sv);
2626 vtop[-1].r = t | VT_LVAL;
2628 /* two word case handling : store second register at word + 4 (or +8 for x86-64) */
2629 #ifdef TCC_TARGET_X86_64
2630 if (((ft & VT_BTYPE) == VT_QLONG) || ((ft & VT_BTYPE) == VT_QFLOAT)) {
2631 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
2632 #else
2633 if ((ft & VT_BTYPE) == VT_LLONG) {
2634 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
2635 #endif
2636 vtop[-1].type.t = load_type;
2637 store(r, vtop - 1);
2638 vswap();
2639 /* convert to int to increment easily */
2640 vtop->type.t = addr_type;
2641 gaddrof();
2642 vpushi(load_size);
2643 gen_op('+');
2644 vtop->r |= VT_LVAL;
2645 vswap();
2646 vtop[-1].type.t = load_type;
2647 /* XXX: it works because r2 is spilled last ! */
2648 store(vtop->r2, vtop - 1);
2649 } else {
2650 store(r, vtop - 1);
2653 vswap();
2654 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
2655 vtop->r |= delayed_cast;
2659 /* post defines POST/PRE add. c is the token ++ or -- */
2660 ST_FUNC void inc(int post, int c)
2662 test_lvalue();
2663 vdup(); /* save lvalue */
2664 if (post) {
2665 gv_dup(); /* duplicate value */
2666 vrotb(3);
2667 vrotb(3);
2669 /* add constant */
2670 vpushi(c - TOK_MID);
2671 gen_op('+');
2672 vstore(); /* store value */
2673 if (post)
2674 vpop(); /* if post op, return saved value */
2677 /* Parse GNUC __attribute__ extension. Currently, the following
2678 extensions are recognized:
2679 - aligned(n) : set data/function alignment.
2680 - packed : force data alignment to 1
2681 - section(x) : generate data/code in this section.
2682 - unused : currently ignored, but may be used someday.
2683 - regparm(n) : pass function parameters in registers (i386 only)
2685 static void parse_attribute(AttributeDef *ad)
2687 int t, n;
2689 while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
2690 next();
2691 skip('(');
2692 skip('(');
2693 while (tok != ')') {
2694 if (tok < TOK_IDENT)
2695 expect("attribute name");
2696 t = tok;
2697 next();
2698 switch(t) {
2699 case TOK_SECTION1:
2700 case TOK_SECTION2:
2701 skip('(');
2702 if (tok != TOK_STR)
2703 expect("section name");
2704 ad->section = find_section(tcc_state, (char *)tokc.cstr->data);
2705 next();
2706 skip(')');
2707 break;
2708 case TOK_ALIAS1:
2709 case TOK_ALIAS2:
2710 skip('(');
2711 if (tok != TOK_STR)
2712 expect("alias(\"target\")");
2713 ad->alias_target = /* save string as token, for later */
2714 tok_alloc((char*)tokc.cstr->data, tokc.cstr->size-1)->tok;
2715 next();
2716 skip(')');
2717 break;
2718 case TOK_VISIBILITY1:
2719 case TOK_VISIBILITY2:
2720 skip('(');
2721 if (tok != TOK_STR)
2722 expect("visibility(\"default|hidden|internal|protected\")");
2723 if (!strcmp (tokc.cstr->data, "default"))
2724 ad->a.visibility = STV_DEFAULT;
2725 else if (!strcmp (tokc.cstr->data, "hidden"))
2726 ad->a.visibility = STV_HIDDEN;
2727 else if (!strcmp (tokc.cstr->data, "internal"))
2728 ad->a.visibility = STV_INTERNAL;
2729 else if (!strcmp (tokc.cstr->data, "protected"))
2730 ad->a.visibility = STV_PROTECTED;
2731 else
2732 expect("visibility(\"default|hidden|internal|protected\")");
2733 next();
2734 skip(')');
2735 break;
2736 case TOK_ALIGNED1:
2737 case TOK_ALIGNED2:
2738 if (tok == '(') {
2739 next();
2740 n = expr_const();
2741 if (n <= 0 || (n & (n - 1)) != 0)
2742 tcc_error("alignment must be a positive power of two");
2743 skip(')');
2744 } else {
2745 n = MAX_ALIGN;
2747 ad->a.aligned = n;
2748 break;
2749 case TOK_PACKED1:
2750 case TOK_PACKED2:
2751 ad->a.packed = 1;
2752 break;
2753 case TOK_WEAK1:
2754 case TOK_WEAK2:
2755 ad->a.weak = 1;
2756 break;
2757 case TOK_UNUSED1:
2758 case TOK_UNUSED2:
2759 /* currently, no need to handle it because tcc does not
2760 track unused objects */
2761 break;
2762 case TOK_NORETURN1:
2763 case TOK_NORETURN2:
2764 /* currently, no need to handle it because tcc does not
2765 track unused objects */
2766 break;
2767 case TOK_CDECL1:
2768 case TOK_CDECL2:
2769 case TOK_CDECL3:
2770 ad->a.func_call = FUNC_CDECL;
2771 break;
2772 case TOK_STDCALL1:
2773 case TOK_STDCALL2:
2774 case TOK_STDCALL3:
2775 ad->a.func_call = FUNC_STDCALL;
2776 break;
2777 #ifdef TCC_TARGET_I386
2778 case TOK_REGPARM1:
2779 case TOK_REGPARM2:
2780 skip('(');
2781 n = expr_const();
2782 if (n > 3)
2783 n = 3;
2784 else if (n < 0)
2785 n = 0;
2786 if (n > 0)
2787 ad->a.func_call = FUNC_FASTCALL1 + n - 1;
2788 skip(')');
2789 break;
2790 case TOK_FASTCALL1:
2791 case TOK_FASTCALL2:
2792 case TOK_FASTCALL3:
2793 ad->a.func_call = FUNC_FASTCALLW;
2794 break;
2795 #endif
2796 case TOK_MODE:
2797 skip('(');
2798 switch(tok) {
2799 case TOK_MODE_DI:
2800 ad->a.mode = VT_LLONG + 1;
2801 break;
2802 case TOK_MODE_HI:
2803 ad->a.mode = VT_SHORT + 1;
2804 break;
2805 case TOK_MODE_SI:
2806 ad->a.mode = VT_INT + 1;
2807 break;
2808 default:
2809 tcc_warning("__mode__(%s) not supported\n", get_tok_str(tok, NULL));
2810 break;
2812 next();
2813 skip(')');
2814 break;
2815 case TOK_DLLEXPORT:
2816 ad->a.func_export = 1;
2817 break;
2818 case TOK_DLLIMPORT:
2819 ad->a.func_import = 1;
2820 break;
2821 default:
2822 if (tcc_state->warn_unsupported)
2823 tcc_warning("'%s' attribute ignored", get_tok_str(t, NULL));
2824 /* skip parameters */
2825 if (tok == '(') {
2826 int parenthesis = 0;
2827 do {
2828 if (tok == '(')
2829 parenthesis++;
2830 else if (tok == ')')
2831 parenthesis--;
2832 next();
2833 } while (parenthesis && tok != -1);
2835 break;
2837 if (tok != ',')
2838 break;
2839 next();
2841 skip(')');
2842 skip(')');
2846 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
2847 static void struct_decl(CType *type, int u, int tdef)
2849 int a, v, size, align, maxalign, c, offset, flexible;
2850 int bit_size, bit_pos, bsize, bt, lbit_pos, prevbt;
2851 Sym *s, *ss, *ass, **ps;
2852 AttributeDef ad;
2853 CType type1, btype;
2855 a = tok; /* save decl type */
2856 next();
2857 if (tok != '{') {
2858 v = tok;
2859 next();
2860 /* struct already defined ? return it */
2861 if (v < TOK_IDENT)
2862 expect("struct/union/enum name");
2863 s = struct_find(v);
2864 if (s) {
2865 if (s->type.t != a)
2866 tcc_error("invalid type: '%s'", get_tok_str(v, NULL));
2867 goto do_decl;
2868 } else if (tok >= TOK_IDENT && !tdef)
2869 tcc_error("unknown struct/union/enum");
2870 } else {
2871 v = anon_sym++;
2873 type1.t = a;
2874 type1.ref = NULL;
2875 /* we put an undefined size for struct/union */
2876 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
2877 s->r = 0; /* default alignment is zero as gcc */
2878 /* put struct/union/enum name in type */
2879 do_decl:
2880 type->t = u;
2881 type->ref = s;
2883 if (tok == '{') {
2884 next();
2885 if (s->c != -1)
2886 tcc_error("struct/union/enum already defined");
2887 /* cannot be empty */
2888 c = 0;
2889 /* non empty enums are not allowed */
2890 if (a == TOK_ENUM) {
2891 for(;;) {
2892 v = tok;
2893 if (v < TOK_UIDENT)
2894 expect("identifier");
2895 ss = sym_find(v);
2896 if (ss && !local_stack)
2897 tcc_error("redefinition of enumerator '%s'",
2898 get_tok_str(v, NULL));
2899 next();
2900 if (tok == '=') {
2901 next();
2902 c = expr_const();
2904 /* enum symbols have static storage */
2905 ss = sym_push(v, &int_type, VT_CONST, c);
2906 ss->type.t |= VT_STATIC;
2907 if (tok != ',')
2908 break;
2909 next();
2910 c++;
2911 /* NOTE: we accept a trailing comma */
2912 if (tok == '}')
2913 break;
2915 s->c = type_size(&int_type, &align);
2916 skip('}');
2917 } else {
2918 maxalign = 1;
2919 ps = &s->next;
2920 prevbt = VT_INT;
2921 bit_pos = 0;
2922 offset = 0;
2923 flexible = 0;
2924 while (tok != '}') {
2925 parse_btype(&btype, &ad);
2926 while (1) {
2927 if (flexible)
2928 tcc_error("flexible array member '%s' not at the end of struct",
2929 get_tok_str(v, NULL));
2930 bit_size = -1;
2931 v = 0;
2932 type1 = btype;
2933 if (tok != ':') {
2934 type_decl(&type1, &ad, &v, TYPE_DIRECT | TYPE_ABSTRACT);
2935 if (v == 0 && (type1.t & VT_BTYPE) != VT_STRUCT)
2936 expect("identifier");
2937 if (type_size(&type1, &align) < 0) {
2938 if ((a == TOK_STRUCT) && (type1.t & VT_ARRAY))
2939 flexible = 1;
2940 else
2941 tcc_error("field '%s' has incomplete type",
2942 get_tok_str(v, NULL));
2944 if ((type1.t & VT_BTYPE) == VT_FUNC ||
2945 (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
2946 tcc_error("invalid type for '%s'",
2947 get_tok_str(v, NULL));
2949 if (tok == ':') {
2950 next();
2951 bit_size = expr_const();
2952 /* XXX: handle v = 0 case for messages */
2953 if (bit_size < 0)
2954 tcc_error("negative width in bit-field '%s'",
2955 get_tok_str(v, NULL));
2956 if (v && bit_size == 0)
2957 tcc_error("zero width for bit-field '%s'",
2958 get_tok_str(v, NULL));
2960 size = type_size(&type1, &align);
2961 if (ad.a.aligned) {
2962 if (align < ad.a.aligned)
2963 align = ad.a.aligned;
2964 } else if (ad.a.packed) {
2965 align = 1;
2966 } else if (*tcc_state->pack_stack_ptr) {
2967 if (align > *tcc_state->pack_stack_ptr)
2968 align = *tcc_state->pack_stack_ptr;
2970 lbit_pos = 0;
2971 if (bit_size >= 0) {
2972 bt = type1.t & VT_BTYPE;
2973 if (bt != VT_INT &&
2974 bt != VT_BYTE &&
2975 bt != VT_SHORT &&
2976 bt != VT_BOOL &&
2977 bt != VT_ENUM &&
2978 bt != VT_LLONG)
2979 tcc_error("bitfields must have scalar type");
2980 bsize = size * 8;
2981 if (bit_size > bsize) {
2982 tcc_error("width of '%s' exceeds its type",
2983 get_tok_str(v, NULL));
2984 } else if (bit_size == bsize) {
2985 /* no need for bit fields */
2986 bit_pos = 0;
2987 } else if (bit_size == 0) {
2988 /* XXX: what to do if only padding in a
2989 structure ? */
2990 /* zero size: means to pad */
2991 bit_pos = 0;
2992 } else {
2993 /* we do not have enough room ?
2994 did the type change?
2995 is it a union? */
2996 if ((bit_pos + bit_size) > bsize ||
2997 bt != prevbt || a == TOK_UNION)
2998 bit_pos = 0;
2999 lbit_pos = bit_pos;
3000 /* XXX: handle LSB first */
3001 type1.t |= VT_BITFIELD |
3002 (bit_pos << VT_STRUCT_SHIFT) |
3003 (bit_size << (VT_STRUCT_SHIFT + 6));
3004 bit_pos += bit_size;
3006 prevbt = bt;
3007 } else {
3008 bit_pos = 0;
3010 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
3011 /* add new memory data only if starting
3012 bit field */
3013 if (lbit_pos == 0) {
3014 if (a == TOK_STRUCT) {
3015 c = (c + align - 1) & -align;
3016 offset = c;
3017 if (size > 0)
3018 c += size;
3019 } else {
3020 offset = 0;
3021 if (size > c)
3022 c = size;
3024 if (align > maxalign)
3025 maxalign = align;
3027 #if 0
3028 printf("add field %s offset=%d",
3029 get_tok_str(v, NULL), offset);
3030 if (type1.t & VT_BITFIELD) {
3031 printf(" pos=%d size=%d",
3032 (type1.t >> VT_STRUCT_SHIFT) & 0x3f,
3033 (type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
3035 printf("\n");
3036 #endif
3038 if (v == 0 && (type1.t & VT_BTYPE) == VT_STRUCT) {
3039 ass = type1.ref;
3040 while ((ass = ass->next) != NULL) {
3041 ss = sym_push(ass->v, &ass->type, 0, offset + ass->c);
3042 *ps = ss;
3043 ps = &ss->next;
3045 } else if (v) {
3046 ss = sym_push(v | SYM_FIELD, &type1, 0, offset);
3047 *ps = ss;
3048 ps = &ss->next;
3050 if (tok == ';' || tok == TOK_EOF)
3051 break;
3052 skip(',');
3054 skip(';');
3056 skip('}');
3057 if (!c && flexible)
3058 tcc_error("flexible array member '%s' in otherwise empty struct", get_tok_str(v, NULL));
3059 /* store size and alignment */
3060 s->c = (c + maxalign - 1) & -maxalign;
3061 s->r = maxalign;
3066 /* return 1 if basic type is a type size (short, long, long long) */
3067 ST_FUNC int is_btype_size(int bt)
3069 return bt == VT_SHORT || bt == VT_LONG || bt == VT_LLONG;
3072 /* return 0 if no type declaration. otherwise, return the basic type
3073 and skip it.
3075 static int parse_btype(CType *type, AttributeDef *ad)
3077 int t, u, bt_size, complete, type_found, typespec_found;
3078 Sym *s;
3079 CType type1;
3081 memset(ad, 0, sizeof(AttributeDef));
3082 complete = 0;
3083 type_found = 0;
3084 typespec_found = 0;
3085 t = 0;
3086 while(1) {
3087 switch(tok) {
3088 case TOK_EXTENSION:
3089 /* currently, we really ignore extension */
3090 next();
3091 continue;
3093 /* basic types */
3094 case TOK_CHAR:
3095 u = VT_BYTE;
3096 basic_type:
3097 next();
3098 basic_type1:
3099 if (complete)
3100 tcc_error("too many basic types");
3101 t |= u;
3102 bt_size = is_btype_size (u & VT_BTYPE);
3103 if (u == VT_INT || (!bt_size && !(t & VT_TYPEDEF)))
3104 complete = 1;
3105 typespec_found = 1;
3106 break;
3107 case TOK_VOID:
3108 u = VT_VOID;
3109 goto basic_type;
3110 case TOK_SHORT:
3111 u = VT_SHORT;
3112 goto basic_type;
3113 case TOK_INT:
3114 u = VT_INT;
3115 goto basic_type;
3116 case TOK_LONG:
3117 next();
3118 if ((t & VT_BTYPE) == VT_DOUBLE) {
3119 #ifndef TCC_TARGET_PE
3120 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3121 #endif
3122 } else if ((t & VT_BTYPE) == VT_LONG) {
3123 t = (t & ~VT_BTYPE) | VT_LLONG;
3124 } else {
3125 u = VT_LONG;
3126 goto basic_type1;
3128 break;
3129 case TOK_BOOL:
3130 u = VT_BOOL;
3131 goto basic_type;
3132 case TOK_FLOAT:
3133 u = VT_FLOAT;
3134 goto basic_type;
3135 case TOK_DOUBLE:
3136 next();
3137 if ((t & VT_BTYPE) == VT_LONG) {
3138 #ifdef TCC_TARGET_PE
3139 t = (t & ~VT_BTYPE) | VT_DOUBLE;
3140 #else
3141 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3142 #endif
3143 } else {
3144 u = VT_DOUBLE;
3145 goto basic_type1;
3147 break;
3148 case TOK_ENUM:
3149 struct_decl(&type1, VT_ENUM, t & VT_TYPEDEF);
3150 basic_type2:
3151 u = type1.t;
3152 type->ref = type1.ref;
3153 goto basic_type1;
3154 case TOK_STRUCT:
3155 case TOK_UNION:
3156 struct_decl(&type1, VT_STRUCT, t & VT_TYPEDEF);
3157 goto basic_type2;
3159 /* type modifiers */
3160 case TOK_CONST1:
3161 case TOK_CONST2:
3162 case TOK_CONST3:
3163 t |= VT_CONSTANT;
3164 next();
3165 break;
3166 case TOK_VOLATILE1:
3167 case TOK_VOLATILE2:
3168 case TOK_VOLATILE3:
3169 t |= VT_VOLATILE;
3170 next();
3171 break;
3172 case TOK_SIGNED1:
3173 case TOK_SIGNED2:
3174 case TOK_SIGNED3:
3175 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == (VT_DEFSIGN|VT_UNSIGNED))
3176 tcc_error("signed and unsigned modifier");
3177 typespec_found = 1;
3178 t |= VT_DEFSIGN;
3179 next();
3180 break;
3181 case TOK_REGISTER:
3182 case TOK_AUTO:
3183 case TOK_RESTRICT1:
3184 case TOK_RESTRICT2:
3185 case TOK_RESTRICT3:
3186 next();
3187 break;
3188 case TOK_UNSIGNED:
3189 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == VT_DEFSIGN)
3190 tcc_error("signed and unsigned modifier");
3191 t |= VT_DEFSIGN | VT_UNSIGNED;
3192 next();
3193 typespec_found = 1;
3194 break;
3196 /* storage */
3197 case TOK_EXTERN:
3198 t |= VT_EXTERN;
3199 next();
3200 break;
3201 case TOK_STATIC:
3202 t |= VT_STATIC;
3203 next();
3204 break;
3205 case TOK_TYPEDEF:
3206 t |= VT_TYPEDEF;
3207 next();
3208 break;
3209 case TOK_INLINE1:
3210 case TOK_INLINE2:
3211 case TOK_INLINE3:
3212 t |= VT_INLINE;
3213 next();
3214 break;
3216 /* GNUC attribute */
3217 case TOK_ATTRIBUTE1:
3218 case TOK_ATTRIBUTE2:
3219 parse_attribute(ad);
3220 if (ad->a.mode) {
3221 u = ad->a.mode -1;
3222 t = (t & ~VT_BTYPE) | u;
3224 break;
3225 /* GNUC typeof */
3226 case TOK_TYPEOF1:
3227 case TOK_TYPEOF2:
3228 case TOK_TYPEOF3:
3229 next();
3230 parse_expr_type(&type1);
3231 /* remove all storage modifiers except typedef */
3232 type1.t &= ~(VT_STORAGE&~VT_TYPEDEF);
3233 goto basic_type2;
3234 default:
3235 if (typespec_found)
3236 goto the_end;
3237 s = sym_find(tok);
3238 if (!s || !(s->type.t & VT_TYPEDEF))
3239 goto the_end;
3240 t |= (s->type.t & ~VT_TYPEDEF);
3241 type->ref = s->type.ref;
3242 if (s->r) {
3243 /* get attributes from typedef */
3244 if (0 == ad->a.aligned)
3245 ad->a.aligned = s->a.aligned;
3246 if (0 == ad->a.func_call)
3247 ad->a.func_call = s->a.func_call;
3248 ad->a.packed |= s->a.packed;
3250 next();
3251 typespec_found = 1;
3252 break;
3254 type_found = 1;
3256 the_end:
3257 if (tcc_state->char_is_unsigned) {
3258 if ((t & (VT_DEFSIGN|VT_BTYPE)) == VT_BYTE)
3259 t |= VT_UNSIGNED;
3262 /* long is never used as type */
3263 if ((t & VT_BTYPE) == VT_LONG)
3264 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
3265 t = (t & ~VT_BTYPE) | VT_INT;
3266 #else
3267 t = (t & ~VT_BTYPE) | VT_LLONG;
3268 #endif
3269 type->t = t;
3270 return type_found;
3273 /* convert a function parameter type (array to pointer and function to
3274 function pointer) */
3275 static inline void convert_parameter_type(CType *pt)
3277 /* remove const and volatile qualifiers (XXX: const could be used
3278 to indicate a const function parameter */
3279 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
3280 /* array must be transformed to pointer according to ANSI C */
3281 pt->t &= ~VT_ARRAY;
3282 if ((pt->t & VT_BTYPE) == VT_FUNC) {
3283 mk_pointer(pt);
3287 ST_FUNC void parse_asm_str(CString *astr)
3289 skip('(');
3290 /* read the string */
3291 if (tok != TOK_STR)
3292 expect("string constant");
3293 cstr_new(astr);
3294 while (tok == TOK_STR) {
3295 /* XXX: add \0 handling too ? */
3296 cstr_cat(astr, tokc.cstr->data);
3297 next();
3299 cstr_ccat(astr, '\0');
3302 /* Parse an asm label and return the label
3303 * Don't forget to free the CString in the caller! */
3304 static void asm_label_instr(CString *astr)
3306 next();
3307 parse_asm_str(astr);
3308 skip(')');
3309 #ifdef ASM_DEBUG
3310 printf("asm_alias: \"%s\"\n", (char *)astr->data);
3311 #endif
3314 static void post_type(CType *type, AttributeDef *ad)
3316 int n, l, t1, arg_size, align;
3317 Sym **plast, *s, *first;
3318 AttributeDef ad1;
3319 CType pt;
3321 if (tok == '(') {
3322 /* function declaration */
3323 next();
3324 l = 0;
3325 first = NULL;
3326 plast = &first;
3327 arg_size = 0;
3328 if (tok != ')') {
3329 for(;;) {
3330 /* read param name and compute offset */
3331 if (l != FUNC_OLD) {
3332 if (!parse_btype(&pt, &ad1)) {
3333 if (l) {
3334 tcc_error("invalid type");
3335 } else {
3336 l = FUNC_OLD;
3337 goto old_proto;
3340 l = FUNC_NEW;
3341 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
3342 break;
3343 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
3344 if ((pt.t & VT_BTYPE) == VT_VOID)
3345 tcc_error("parameter declared as void");
3346 arg_size += (type_size(&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
3347 } else {
3348 old_proto:
3349 n = tok;
3350 if (n < TOK_UIDENT)
3351 expect("identifier");
3352 pt.t = VT_INT;
3353 next();
3355 convert_parameter_type(&pt);
3356 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
3357 *plast = s;
3358 plast = &s->next;
3359 if (tok == ')')
3360 break;
3361 skip(',');
3362 if (l == FUNC_NEW && tok == TOK_DOTS) {
3363 l = FUNC_ELLIPSIS;
3364 next();
3365 break;
3369 /* if no parameters, then old type prototype */
3370 if (l == 0)
3371 l = FUNC_OLD;
3372 skip(')');
3373 /* NOTE: const is ignored in returned type as it has a special
3374 meaning in gcc / C++ */
3375 type->t &= ~VT_CONSTANT;
3376 /* some ancient pre-K&R C allows a function to return an array
3377 and the array brackets to be put after the arguments, such
3378 that "int c()[]" means something like "int[] c()" */
3379 if (tok == '[') {
3380 next();
3381 skip(']'); /* only handle simple "[]" */
3382 type->t |= VT_PTR;
3384 /* we push a anonymous symbol which will contain the function prototype */
3385 ad->a.func_args = arg_size;
3386 s = sym_push(SYM_FIELD, type, 0, l);
3387 s->a = ad->a;
3388 s->next = first;
3389 type->t = VT_FUNC;
3390 type->ref = s;
3391 } else if (tok == '[') {
3392 /* array definition */
3393 next();
3394 if (tok == TOK_RESTRICT1)
3395 next();
3396 n = -1;
3397 t1 = 0;
3398 if (tok != ']') {
3399 if (!local_stack || nocode_wanted)
3400 vpushi(expr_const());
3401 else gexpr();
3402 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3403 n = vtop->c.i;
3404 if (n < 0)
3405 tcc_error("invalid array size");
3406 } else {
3407 if (!is_integer_btype(vtop->type.t & VT_BTYPE))
3408 tcc_error("size of variable length array should be an integer");
3409 t1 = VT_VLA;
3412 skip(']');
3413 /* parse next post type */
3414 post_type(type, ad);
3415 if (type->t == VT_FUNC)
3416 tcc_error("declaration of an array of functions");
3417 t1 |= type->t & VT_VLA;
3419 if (t1 & VT_VLA) {
3420 loc -= type_size(&int_type, &align);
3421 loc &= -align;
3422 n = loc;
3424 vla_runtime_type_size(type, &align);
3425 gen_op('*');
3426 vset(&int_type, VT_LOCAL|VT_LVAL, loc);
3427 vswap();
3428 vstore();
3430 if (n != -1)
3431 vpop();
3433 /* we push an anonymous symbol which will contain the array
3434 element type */
3435 s = sym_push(SYM_FIELD, type, 0, n);
3436 type->t = (t1 ? VT_VLA : VT_ARRAY) | VT_PTR;
3437 type->ref = s;
3441 /* Parse a type declaration (except basic type), and return the type
3442 in 'type'. 'td' is a bitmask indicating which kind of type decl is
3443 expected. 'type' should contain the basic type. 'ad' is the
3444 attribute definition of the basic type. It can be modified by
3445 type_decl().
3447 static void type_decl(CType *type, AttributeDef *ad, int *v, int td)
3449 Sym *s;
3450 CType type1, *type2;
3451 int qualifiers, storage;
3453 while (tok == '*') {
3454 qualifiers = 0;
3455 redo:
3456 next();
3457 switch(tok) {
3458 case TOK_CONST1:
3459 case TOK_CONST2:
3460 case TOK_CONST3:
3461 qualifiers |= VT_CONSTANT;
3462 goto redo;
3463 case TOK_VOLATILE1:
3464 case TOK_VOLATILE2:
3465 case TOK_VOLATILE3:
3466 qualifiers |= VT_VOLATILE;
3467 goto redo;
3468 case TOK_RESTRICT1:
3469 case TOK_RESTRICT2:
3470 case TOK_RESTRICT3:
3471 goto redo;
3473 mk_pointer(type);
3474 type->t |= qualifiers;
3477 /* XXX: clarify attribute handling */
3478 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3479 parse_attribute(ad);
3481 /* recursive type */
3482 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
3483 type1.t = 0; /* XXX: same as int */
3484 if (tok == '(') {
3485 next();
3486 /* XXX: this is not correct to modify 'ad' at this point, but
3487 the syntax is not clear */
3488 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3489 parse_attribute(ad);
3490 type_decl(&type1, ad, v, td);
3491 skip(')');
3492 } else {
3493 /* type identifier */
3494 if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
3495 *v = tok;
3496 next();
3497 } else {
3498 if (!(td & TYPE_ABSTRACT))
3499 expect("identifier");
3500 *v = 0;
3503 storage = type->t & VT_STORAGE;
3504 type->t &= ~VT_STORAGE;
3505 if (storage & VT_STATIC) {
3506 int saved_nocode_wanted = nocode_wanted;
3507 nocode_wanted = 1;
3508 post_type(type, ad);
3509 nocode_wanted = saved_nocode_wanted;
3510 } else
3511 post_type(type, ad);
3512 type->t |= storage;
3513 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3514 parse_attribute(ad);
3516 if (!type1.t)
3517 return;
3518 /* append type at the end of type1 */
3519 type2 = &type1;
3520 for(;;) {
3521 s = type2->ref;
3522 type2 = &s->type;
3523 if (!type2->t) {
3524 *type2 = *type;
3525 break;
3528 *type = type1;
3531 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
3532 ST_FUNC int lvalue_type(int t)
3534 int bt, r;
3535 r = VT_LVAL;
3536 bt = t & VT_BTYPE;
3537 if (bt == VT_BYTE || bt == VT_BOOL)
3538 r |= VT_LVAL_BYTE;
3539 else if (bt == VT_SHORT)
3540 r |= VT_LVAL_SHORT;
3541 else
3542 return r;
3543 if (t & VT_UNSIGNED)
3544 r |= VT_LVAL_UNSIGNED;
3545 return r;
3548 /* indirection with full error checking and bound check */
3549 ST_FUNC void indir(void)
3551 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
3552 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
3553 return;
3554 expect("pointer");
3556 if ((vtop->r & VT_LVAL) && !nocode_wanted)
3557 gv(RC_INT);
3558 vtop->type = *pointed_type(&vtop->type);
3559 /* Arrays and functions are never lvalues */
3560 if (!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_VLA)
3561 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
3562 vtop->r |= lvalue_type(vtop->type.t);
3563 /* if bound checking, the referenced pointer must be checked */
3564 #ifdef CONFIG_TCC_BCHECK
3565 if (tcc_state->do_bounds_check)
3566 vtop->r |= VT_MUSTBOUND;
3567 #endif
3571 /* pass a parameter to a function and do type checking and casting */
3572 static void gfunc_param_typed(Sym *func, Sym *arg)
3574 int func_type;
3575 CType type;
3577 func_type = func->c;
3578 if (func_type == FUNC_OLD ||
3579 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
3580 /* default casting : only need to convert float to double */
3581 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
3582 type.t = VT_DOUBLE;
3583 gen_cast(&type);
3584 } else if (vtop->type.t & VT_BITFIELD) {
3585 type.t = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
3586 gen_cast(&type);
3588 } else if (arg == NULL) {
3589 tcc_error("too many arguments to function");
3590 } else {
3591 type = arg->type;
3592 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
3593 gen_assign_cast(&type);
3597 /* parse an expression of the form '(type)' or '(expr)' and return its
3598 type */
3599 static void parse_expr_type(CType *type)
3601 int n;
3602 AttributeDef ad;
3604 skip('(');
3605 if (parse_btype(type, &ad)) {
3606 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3607 } else {
3608 expr_type(type);
3610 skip(')');
3613 static void parse_type(CType *type)
3615 AttributeDef ad;
3616 int n;
3618 if (!parse_btype(type, &ad)) {
3619 expect("type");
3621 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3624 static void vpush_tokc(int t)
3626 CType type;
3627 type.t = t;
3628 type.ref = 0;
3629 vsetc(&type, VT_CONST, &tokc);
3632 ST_FUNC void unary(void)
3634 int n, t, align, size, r, sizeof_caller;
3635 CType type;
3636 Sym *s;
3637 AttributeDef ad;
3638 static int in_sizeof = 0;
3640 sizeof_caller = in_sizeof;
3641 in_sizeof = 0;
3642 /* XXX: GCC 2.95.3 does not generate a table although it should be
3643 better here */
3644 tok_next:
3645 switch(tok) {
3646 case TOK_EXTENSION:
3647 next();
3648 goto tok_next;
3649 case TOK_CINT:
3650 case TOK_CCHAR:
3651 case TOK_LCHAR:
3652 vpushi(tokc.i);
3653 next();
3654 break;
3655 case TOK_CUINT:
3656 vpush_tokc(VT_INT | VT_UNSIGNED);
3657 next();
3658 break;
3659 case TOK_CLLONG:
3660 vpush_tokc(VT_LLONG);
3661 next();
3662 break;
3663 case TOK_CULLONG:
3664 vpush_tokc(VT_LLONG | VT_UNSIGNED);
3665 next();
3666 break;
3667 case TOK_CFLOAT:
3668 vpush_tokc(VT_FLOAT);
3669 next();
3670 break;
3671 case TOK_CDOUBLE:
3672 vpush_tokc(VT_DOUBLE);
3673 next();
3674 break;
3675 case TOK_CLDOUBLE:
3676 vpush_tokc(VT_LDOUBLE);
3677 next();
3678 break;
3679 case TOK___FUNCTION__:
3680 if (!gnu_ext)
3681 goto tok_identifier;
3682 /* fall thru */
3683 case TOK___FUNC__:
3685 void *ptr;
3686 int len;
3687 /* special function name identifier */
3688 len = strlen(funcname) + 1;
3689 /* generate char[len] type */
3690 type.t = VT_BYTE;
3691 mk_pointer(&type);
3692 type.t |= VT_ARRAY;
3693 type.ref->c = len;
3694 vpush_ref(&type, data_section, data_section->data_offset, len);
3695 ptr = section_ptr_add(data_section, len);
3696 memcpy(ptr, funcname, len);
3697 next();
3699 break;
3700 case TOK_LSTR:
3701 #ifdef TCC_TARGET_PE
3702 t = VT_SHORT | VT_UNSIGNED;
3703 #else
3704 t = VT_INT;
3705 #endif
3706 goto str_init;
3707 case TOK_STR:
3708 /* string parsing */
3709 t = VT_BYTE;
3710 str_init:
3711 if (tcc_state->warn_write_strings)
3712 t |= VT_CONSTANT;
3713 type.t = t;
3714 mk_pointer(&type);
3715 type.t |= VT_ARRAY;
3716 memset(&ad, 0, sizeof(AttributeDef));
3717 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, NULL, 0);
3718 break;
3719 case '(':
3720 next();
3721 /* cast ? */
3722 if (parse_btype(&type, &ad)) {
3723 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
3724 skip(')');
3725 /* check ISOC99 compound literal */
3726 if (tok == '{') {
3727 /* data is allocated locally by default */
3728 if (global_expr)
3729 r = VT_CONST;
3730 else
3731 r = VT_LOCAL;
3732 /* all except arrays are lvalues */
3733 if (!(type.t & VT_ARRAY))
3734 r |= lvalue_type(type.t);
3735 memset(&ad, 0, sizeof(AttributeDef));
3736 decl_initializer_alloc(&type, &ad, r, 1, 0, NULL, 0);
3737 } else {
3738 if (sizeof_caller) {
3739 vpush(&type);
3740 return;
3742 unary();
3743 is_force = 1;
3744 gen_cast(&type);
3745 is_force = 0;
3747 } else if (tok == '{') {
3748 /* save all registers */
3749 save_regs(0);
3750 /* statement expression : we do not accept break/continue
3751 inside as GCC does */
3752 block(NULL, NULL, NULL, NULL, 0, 1);
3753 skip(')');
3754 } else {
3755 gexpr();
3756 skip(')');
3758 break;
3759 case '*':
3760 next();
3761 unary();
3762 indir();
3763 break;
3764 case '&':
3765 next();
3766 unary();
3767 /* functions names must be treated as function pointers,
3768 except for unary '&' and sizeof. Since we consider that
3769 functions are not lvalues, we only have to handle it
3770 there and in function calls. */
3771 /* arrays can also be used although they are not lvalues */
3772 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
3773 !(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
3774 test_lvalue();
3775 mk_pointer(&vtop->type);
3776 gaddrof();
3777 break;
3778 case '!':
3779 next();
3780 unary();
3781 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3782 CType boolean;
3783 boolean.t = VT_BOOL;
3784 gen_cast(&boolean);
3785 vtop->c.i = !vtop->c.i;
3786 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
3787 vtop->c.i = vtop->c.i ^ 1;
3788 else {
3789 save_regs(1);
3790 vseti(VT_JMP, gvtst(1, 0));
3792 break;
3793 case '~':
3794 next();
3795 unary();
3796 vpushi(-1);
3797 gen_op('^');
3798 break;
3799 case '+':
3800 next();
3801 unary();
3802 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
3803 tcc_error("pointer not accepted for unary plus");
3804 /* In order to force cast, we add zero, except for floating point
3805 where we really need an noop (otherwise -0.0 will be transformed
3806 into +0.0). */
3807 if (!is_float(vtop->type.t)) {
3808 vpushi(0);
3809 gen_op('+');
3811 break;
3812 case TOK_SIZEOF:
3813 case TOK_ALIGNOF1:
3814 case TOK_ALIGNOF2:
3815 t = tok;
3816 next();
3817 in_sizeof++;
3818 unary_type(&type); // Perform a in_sizeof = 0;
3819 size = type_size(&type, &align);
3820 if (t == TOK_SIZEOF) {
3821 if (!(type.t & VT_VLA)) {
3822 if (size < 0)
3823 tcc_error("sizeof applied to an incomplete type");
3824 if(type.t & VT_BITFIELD)
3825 tcc_error("'%s' applied to a bit-field", get_tok_str(t, NULL));
3826 vpushs(size);
3827 } else {
3828 vla_runtime_type_size(&type, &align);
3830 } else {
3831 vpushs(align);
3833 vtop->type.t |= VT_UNSIGNED;
3834 break;
3836 case TOK_builtin_types_compatible_p:
3838 CType type1, type2;
3839 next();
3840 skip('(');
3841 parse_type(&type1);
3842 skip(',');
3843 parse_type(&type2);
3844 skip(')');
3845 type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
3846 type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
3847 vpushi(is_compatible_types(&type1, &type2));
3849 break;
3850 case TOK_builtin_constant_p:
3852 int saved_nocode_wanted, res;
3853 next();
3854 skip('(');
3855 saved_nocode_wanted = nocode_wanted;
3856 nocode_wanted = 1;
3857 gexpr();
3858 res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
3859 vpop();
3860 nocode_wanted = saved_nocode_wanted;
3861 skip(')');
3862 vpushi(res);
3864 break;
3865 case TOK_builtin_frame_address:
3867 int level;
3868 CType type;
3869 next();
3870 skip('(');
3871 if (tok != TOK_CINT || tokc.i < 0) {
3872 tcc_error("__builtin_frame_address only takes positive integers");
3874 level = tokc.i;
3875 next();
3876 skip(')');
3877 type.t = VT_VOID;
3878 mk_pointer(&type);
3879 vset(&type, VT_LOCAL, 0); /* local frame */
3880 while (level--) {
3881 mk_pointer(&vtop->type);
3882 indir(); /* -> parent frame */
3885 break;
3886 #ifdef TCC_TARGET_X86_64
3887 #ifdef TCC_TARGET_PE
3888 case TOK_builtin_va_start:
3890 next();
3891 skip('(');
3892 expr_eq();
3893 skip(',');
3894 expr_eq();
3895 skip(')');
3896 if ((vtop->r & VT_VALMASK) != VT_LOCAL)
3897 tcc_error("__builtin_va_start expects a local variable");
3898 vtop->r &= ~(VT_LVAL | VT_REF);
3899 vtop->type = char_pointer_type;
3900 vstore();
3902 break;
3903 #else
3904 case TOK_builtin_va_arg_types:
3906 CType type;
3907 next();
3908 skip('(');
3909 parse_type(&type);
3910 skip(')');
3911 vpushi(classify_x86_64_va_arg(&type));
3913 break;
3914 #endif
3915 #endif
3916 case TOK_INC:
3917 case TOK_DEC:
3918 t = tok;
3919 next();
3920 unary();
3921 inc(0, t);
3922 break;
3923 case '-':
3924 next();
3925 unary();
3926 t = vtop->type.t & VT_BTYPE;
3927 if (is_float(t)) {
3928 /* In IEEE negate(x) isn't subtract(0,x), but rather
3929 subtract(-0, x). */
3930 vpush(&vtop->type);
3931 if (t == VT_FLOAT)
3932 vtop->c.f = -0.0f;
3933 else if (t == VT_DOUBLE)
3934 vtop->c.d = -0.0;
3935 else
3936 vtop->c.ld = -0.0;
3937 } else
3938 vpushi(0);
3939 vswap();
3940 gen_op('-');
3941 break;
3942 case TOK_LAND:
3943 if (!gnu_ext)
3944 goto tok_identifier;
3945 next();
3946 /* allow to take the address of a label */
3947 if (tok < TOK_UIDENT)
3948 expect("label identifier");
3949 s = label_find(tok);
3950 if (!s) {
3951 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
3952 } else {
3953 if (s->r == LABEL_DECLARED)
3954 s->r = LABEL_FORWARD;
3956 if (!s->type.t) {
3957 s->type.t = VT_VOID;
3958 mk_pointer(&s->type);
3959 s->type.t |= VT_STATIC;
3961 vpushsym(&s->type, s);
3962 next();
3963 break;
3965 // special qnan , snan and infinity values
3966 case TOK___NAN__:
3967 vpush64(VT_DOUBLE, 0x7ff8000000000000ULL);
3968 next();
3969 break;
3970 case TOK___SNAN__:
3971 vpush64(VT_DOUBLE, 0x7ff0000000000001ULL);
3972 next();
3973 break;
3974 case TOK___INF__:
3975 vpush64(VT_DOUBLE, 0x7ff0000000000000ULL);
3976 next();
3977 break;
3979 default:
3980 tok_identifier:
3981 t = tok;
3982 next();
3983 if (t < TOK_UIDENT)
3984 expect("identifier");
3985 s = sym_find(t);
3986 if (!s) {
3987 const char *name = get_tok_str(t, NULL);
3988 if (tok != '(')
3989 tcc_error("'%s' undeclared", name);
3990 /* for simple function calls, we tolerate undeclared
3991 external reference to int() function */
3992 if (tcc_state->warn_implicit_function_declaration
3993 #ifdef TCC_TARGET_PE
3994 /* people must be warned about using undeclared WINAPI functions
3995 (which usually start with uppercase letter) */
3996 || (name[0] >= 'A' && name[0] <= 'Z')
3997 #endif
3999 tcc_warning("implicit declaration of function '%s'", name);
4000 s = external_global_sym(t, &func_old_type, 0);
4002 if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
4003 (VT_STATIC | VT_INLINE | VT_FUNC)) {
4004 /* if referencing an inline function, then we generate a
4005 symbol to it if not already done. It will have the
4006 effect to generate code for it at the end of the
4007 compilation unit. Inline function as always
4008 generated in the text section. */
4009 if (!s->c)
4010 put_extern_sym(s, text_section, 0, 0);
4011 r = VT_SYM | VT_CONST;
4012 } else {
4013 r = s->r;
4015 vset(&s->type, r, s->c);
4016 /* if forward reference, we must point to s */
4017 if (vtop->r & VT_SYM) {
4018 vtop->sym = s;
4019 vtop->c.ptr_offset = 0;
4021 break;
4024 /* post operations */
4025 while (1) {
4026 if (tok == TOK_INC || tok == TOK_DEC) {
4027 inc(1, tok);
4028 next();
4029 } else if (tok == '.' || tok == TOK_ARROW) {
4030 int qualifiers;
4031 /* field */
4032 if (tok == TOK_ARROW)
4033 indir();
4034 qualifiers = vtop->type.t & (VT_CONSTANT | VT_VOLATILE);
4035 test_lvalue();
4036 gaddrof();
4037 next();
4038 /* expect pointer on structure */
4039 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
4040 expect("struct or union");
4041 s = vtop->type.ref;
4042 /* find field */
4043 tok |= SYM_FIELD;
4044 while ((s = s->next) != NULL) {
4045 if (s->v == tok)
4046 break;
4048 if (!s)
4049 tcc_error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, NULL));
4050 /* add field offset to pointer */
4051 vtop->type = char_pointer_type; /* change type to 'char *' */
4052 vpushi(s->c);
4053 gen_op('+');
4054 /* change type to field type, and set to lvalue */
4055 vtop->type = s->type;
4056 vtop->type.t |= qualifiers;
4057 /* an array is never an lvalue */
4058 if (!(vtop->type.t & VT_ARRAY)) {
4059 vtop->r |= lvalue_type(vtop->type.t);
4060 #ifdef CONFIG_TCC_BCHECK
4061 /* if bound checking, the referenced pointer must be checked */
4062 if (tcc_state->do_bounds_check)
4063 vtop->r |= VT_MUSTBOUND;
4064 #endif
4066 next();
4067 } else if (tok == '[') {
4068 next();
4069 gexpr();
4070 gen_op('+');
4071 indir();
4072 skip(']');
4073 } else if (tok == '(') {
4074 SValue ret;
4075 Sym *sa;
4076 int nb_args, ret_nregs, ret_align, variadic;
4078 /* function call */
4079 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
4080 /* pointer test (no array accepted) */
4081 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
4082 vtop->type = *pointed_type(&vtop->type);
4083 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
4084 goto error_func;
4085 } else {
4086 error_func:
4087 expect("function pointer");
4089 } else {
4090 vtop->r &= ~VT_LVAL; /* no lvalue */
4092 /* get return type */
4093 s = vtop->type.ref;
4094 next();
4095 sa = s->next; /* first parameter */
4096 nb_args = 0;
4097 ret.r2 = VT_CONST;
4098 /* compute first implicit argument if a structure is returned */
4099 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
4100 variadic = (s->c == FUNC_ELLIPSIS);
4101 ret_nregs = gfunc_sret(&s->type, variadic, &ret.type,
4102 &ret_align);
4103 if (!ret_nregs) {
4104 /* get some space for the returned structure */
4105 size = type_size(&s->type, &align);
4106 loc = (loc - size) & -align;
4107 ret.type = s->type;
4108 ret.r = VT_LOCAL | VT_LVAL;
4109 /* pass it as 'int' to avoid structure arg passing
4110 problems */
4111 vseti(VT_LOCAL, loc);
4112 ret.c = vtop->c;
4113 nb_args++;
4115 } else {
4116 ret_nregs = 1;
4117 ret.type = s->type;
4120 if (ret_nregs) {
4121 /* return in register */
4122 if (is_float(ret.type.t)) {
4123 ret.r = reg_fret(ret.type.t);
4124 #ifdef TCC_TARGET_X86_64
4125 if ((ret.type.t & VT_BTYPE) == VT_QFLOAT)
4126 ret.r2 = REG_QRET;
4127 #endif
4128 } else {
4129 #ifdef TCC_TARGET_X86_64
4130 if ((ret.type.t & VT_BTYPE) == VT_QLONG)
4131 #else
4132 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
4133 #endif
4134 ret.r2 = REG_LRET;
4135 ret.r = REG_IRET;
4137 ret.c.i = 0;
4139 if (tok != ')') {
4140 for(;;) {
4141 expr_eq();
4142 gfunc_param_typed(s, sa);
4143 nb_args++;
4144 if (sa)
4145 sa = sa->next;
4146 if (tok == ')')
4147 break;
4148 skip(',');
4151 if (sa)
4152 tcc_error("too few arguments to function");
4153 skip(')');
4154 if (!nocode_wanted) {
4155 gfunc_call(nb_args);
4156 } else {
4157 vtop -= (nb_args + 1);
4160 /* return value */
4161 for (r = ret.r + ret_nregs + !ret_nregs; r-- > ret.r;) {
4162 vsetc(&ret.type, r, &ret.c);
4163 vtop->r2 = ret.r2; /* Loop only happens when r2 is VT_CONST */
4166 /* handle packed struct return */
4167 if (((s->type.t & VT_BTYPE) == VT_STRUCT) && ret_nregs) {
4168 int addr, offset;
4170 size = type_size(&s->type, &align);
4171 loc = (loc - size) & -align;
4172 addr = loc;
4173 offset = 0;
4174 for (;;) {
4175 vset(&ret.type, VT_LOCAL | VT_LVAL, addr + offset);
4176 vswap();
4177 vstore();
4178 vtop--;
4179 if (--ret_nregs == 0)
4180 break;
4181 /* XXX: compatible with arm only: ret_align == register_size */
4182 offset += ret_align;
4184 vset(&s->type, VT_LOCAL | VT_LVAL, addr);
4186 } else {
4187 break;
4192 ST_FUNC void expr_prod(void)
4194 int t;
4196 unary();
4197 while (tok == '*' || tok == '/' || tok == '%') {
4198 t = tok;
4199 next();
4200 unary();
4201 gen_op(t);
4205 ST_FUNC void expr_sum(void)
4207 int t;
4209 expr_prod();
4210 while (tok == '+' || tok == '-') {
4211 t = tok;
4212 next();
4213 expr_prod();
4214 gen_op(t);
4218 static void expr_shift(void)
4220 int t;
4222 expr_sum();
4223 while (tok == TOK_SHL || tok == TOK_SAR) {
4224 t = tok;
4225 next();
4226 expr_sum();
4227 gen_op(t);
4231 static void expr_cmp(void)
4233 int t;
4235 expr_shift();
4236 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
4237 tok == TOK_ULT || tok == TOK_UGE) {
4238 t = tok;
4239 next();
4240 expr_shift();
4241 gen_op(t);
4245 static void expr_cmpeq(void)
4247 int t;
4249 expr_cmp();
4250 while (tok == TOK_EQ || tok == TOK_NE) {
4251 t = tok;
4252 next();
4253 expr_cmp();
4254 gen_op(t);
4258 static void expr_and(void)
4260 expr_cmpeq();
4261 while (tok == '&') {
4262 next();
4263 expr_cmpeq();
4264 gen_op('&');
4268 static void expr_xor(void)
4270 expr_and();
4271 while (tok == '^') {
4272 next();
4273 expr_and();
4274 gen_op('^');
4278 static void expr_or(void)
4280 expr_xor();
4281 while (tok == '|') {
4282 next();
4283 expr_xor();
4284 gen_op('|');
4288 /* XXX: fix this mess */
4289 static void expr_land_const(void)
4291 expr_or();
4292 while (tok == TOK_LAND) {
4293 next();
4294 expr_or();
4295 gen_op(TOK_LAND);
4299 /* XXX: fix this mess */
4300 static void expr_lor_const(void)
4302 expr_land_const();
4303 while (tok == TOK_LOR) {
4304 next();
4305 expr_land_const();
4306 gen_op(TOK_LOR);
4310 /* only used if non constant */
4311 static void expr_land(void)
4313 int t;
4315 expr_or();
4316 if (tok == TOK_LAND) {
4317 t = 0;
4318 save_regs(1);
4319 for(;;) {
4320 t = gvtst(1, t);
4321 if (tok != TOK_LAND) {
4322 vseti(VT_JMPI, t);
4323 break;
4325 next();
4326 expr_or();
4331 static void expr_lor(void)
4333 int t;
4335 expr_land();
4336 if (tok == TOK_LOR) {
4337 t = 0;
4338 save_regs(1);
4339 for(;;) {
4340 t = gvtst(0, t);
4341 if (tok != TOK_LOR) {
4342 vseti(VT_JMP, t);
4343 break;
4345 next();
4346 expr_land();
4351 /* XXX: better constant handling */
4352 static void expr_cond(void)
4354 int tt, u, r1, r2, rc, t1, t2, bt1, bt2;
4355 SValue sv;
4356 CType type, type1, type2;
4358 if (const_wanted) {
4359 expr_lor_const();
4360 if (tok == '?') {
4361 CType boolean;
4362 int c;
4363 boolean.t = VT_BOOL;
4364 vdup();
4365 gen_cast(&boolean);
4366 c = vtop->c.i;
4367 vpop();
4368 next();
4369 if (tok != ':' || !gnu_ext) {
4370 vpop();
4371 gexpr();
4373 if (!c)
4374 vpop();
4375 skip(':');
4376 expr_cond();
4377 if (c)
4378 vpop();
4380 } else {
4381 expr_lor();
4382 if (tok == '?') {
4383 next();
4384 if (vtop != vstack) {
4385 /* needed to avoid having different registers saved in
4386 each branch */
4387 if (is_float(vtop->type.t)) {
4388 rc = RC_FLOAT;
4389 #ifdef TCC_TARGET_X86_64
4390 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
4391 rc = RC_ST0;
4393 #endif
4395 else
4396 rc = RC_INT;
4397 gv(rc);
4398 save_regs(1);
4400 if (tok == ':' && gnu_ext) {
4401 gv_dup();
4402 tt = gvtst(1, 0);
4403 } else {
4404 tt = gvtst(1, 0);
4405 gexpr();
4407 type1 = vtop->type;
4408 sv = *vtop; /* save value to handle it later */
4409 vtop--; /* no vpop so that FP stack is not flushed */
4410 skip(':');
4411 u = gjmp(0);
4412 gsym(tt);
4413 expr_cond();
4414 type2 = vtop->type;
4416 t1 = type1.t;
4417 bt1 = t1 & VT_BTYPE;
4418 t2 = type2.t;
4419 bt2 = t2 & VT_BTYPE;
4420 /* cast operands to correct type according to ISOC rules */
4421 if (is_float(bt1) || is_float(bt2)) {
4422 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
4423 type.t = VT_LDOUBLE;
4424 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
4425 type.t = VT_DOUBLE;
4426 } else {
4427 type.t = VT_FLOAT;
4429 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
4430 /* cast to biggest op */
4431 type.t = VT_LLONG;
4432 /* convert to unsigned if it does not fit in a long long */
4433 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
4434 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
4435 type.t |= VT_UNSIGNED;
4436 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
4437 /* If one is a null ptr constant the result type
4438 is the other. */
4439 if (is_null_pointer (vtop))
4440 type = type1;
4441 else if (is_null_pointer (&sv))
4442 type = type2;
4443 /* XXX: test pointer compatibility, C99 has more elaborate
4444 rules here. */
4445 else
4446 type = type1;
4447 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
4448 /* XXX: test function pointer compatibility */
4449 type = bt1 == VT_FUNC ? type1 : type2;
4450 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
4451 /* XXX: test structure compatibility */
4452 type = bt1 == VT_STRUCT ? type1 : type2;
4453 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
4454 /* NOTE: as an extension, we accept void on only one side */
4455 type.t = VT_VOID;
4456 } else {
4457 /* integer operations */
4458 type.t = VT_INT;
4459 /* convert to unsigned if it does not fit in an integer */
4460 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
4461 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
4462 type.t |= VT_UNSIGNED;
4465 /* now we convert second operand */
4466 gen_cast(&type);
4467 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4468 gaddrof();
4469 rc = RC_INT;
4470 if (is_float(type.t)) {
4471 rc = RC_FLOAT;
4472 #ifdef TCC_TARGET_X86_64
4473 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
4474 rc = RC_ST0;
4476 #endif
4477 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
4478 /* for long longs, we use fixed registers to avoid having
4479 to handle a complicated move */
4480 rc = RC_IRET;
4483 r2 = gv(rc);
4484 /* this is horrible, but we must also convert first
4485 operand */
4486 tt = gjmp(0);
4487 gsym(u);
4488 /* put again first value and cast it */
4489 *vtop = sv;
4490 gen_cast(&type);
4491 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4492 gaddrof();
4493 r1 = gv(rc);
4494 move_reg(r2, r1, type.t);
4495 vtop->r = r2;
4496 gsym(tt);
4501 static void expr_eq(void)
4503 int t;
4505 expr_cond();
4506 if (tok == '=' ||
4507 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
4508 tok == TOK_A_XOR || tok == TOK_A_OR ||
4509 tok == TOK_A_SHL || tok == TOK_A_SAR) {
4510 test_lvalue();
4511 t = tok;
4512 next();
4513 if (t == '=') {
4514 expr_eq();
4515 } else {
4516 vdup();
4517 expr_eq();
4518 gen_op(t & 0x7f);
4520 vstore();
4524 ST_FUNC void gexpr(void)
4526 while (1) {
4527 expr_eq();
4528 if (tok != ',')
4529 break;
4530 vpop();
4531 next();
4535 /* parse an expression and return its type without any side effect. */
4536 static void expr_type(CType *type)
4538 int saved_nocode_wanted;
4540 saved_nocode_wanted = nocode_wanted;
4541 nocode_wanted = 1;
4542 gexpr();
4543 *type = vtop->type;
4544 vpop();
4545 nocode_wanted = saved_nocode_wanted;
4548 /* parse a unary expression and return its type without any side
4549 effect. */
4550 static void unary_type(CType *type)
4552 int a;
4554 a = nocode_wanted;
4555 nocode_wanted = 1;
4556 unary();
4557 *type = vtop->type;
4558 vpop();
4559 nocode_wanted = a;
4562 /* parse a constant expression and return value in vtop. */
4563 static void expr_const1(void)
4565 int a;
4566 a = const_wanted;
4567 const_wanted = 1;
4568 expr_cond();
4569 const_wanted = a;
4572 /* parse an integer constant and return its value. */
4573 ST_FUNC int expr_const(void)
4575 int c;
4576 expr_const1();
4577 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
4578 expect("constant expression");
4579 c = vtop->c.i;
4580 vpop();
4581 return c;
4584 /* return the label token if current token is a label, otherwise
4585 return zero */
4586 static int is_label(void)
4588 int last_tok;
4590 /* fast test first */
4591 if (tok < TOK_UIDENT)
4592 return 0;
4593 /* no need to save tokc because tok is an identifier */
4594 last_tok = tok;
4595 next();
4596 if (tok == ':') {
4597 next();
4598 return last_tok;
4599 } else {
4600 unget_tok(last_tok);
4601 return 0;
4605 static void label_or_decl(int l)
4607 int last_tok;
4609 /* fast test first */
4610 if (tok >= TOK_UIDENT)
4612 /* no need to save tokc because tok is an identifier */
4613 last_tok = tok;
4614 next();
4615 if (tok == ':') {
4616 unget_tok(last_tok);
4617 return;
4619 unget_tok(last_tok);
4621 decl(l);
4624 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
4625 int case_reg, int is_expr)
4627 int a, b, c, d;
4628 Sym *s, *frame_bottom;
4630 /* generate line number info */
4631 if (tcc_state->do_debug &&
4632 (last_line_num != file->line_num || last_ind != ind)) {
4633 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
4634 last_ind = ind;
4635 last_line_num = file->line_num;
4638 if (is_expr) {
4639 /* default return value is (void) */
4640 vpushi(0);
4641 vtop->type.t = VT_VOID;
4644 if (tok == TOK_IF) {
4645 /* if test */
4646 next();
4647 skip('(');
4648 gexpr();
4649 skip(')');
4650 a = gvtst(1, 0);
4651 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4652 c = tok;
4653 if (c == TOK_ELSE) {
4654 next();
4655 d = gjmp(0);
4656 gsym(a);
4657 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4658 gsym(d); /* patch else jmp */
4659 } else
4660 gsym(a);
4661 } else if (tok == TOK_WHILE) {
4662 next();
4663 d = ind;
4664 skip('(');
4665 gexpr();
4666 skip(')');
4667 a = gvtst(1, 0);
4668 b = 0;
4669 block(&a, &b, case_sym, def_sym, case_reg, 0);
4670 gjmp_addr(d);
4671 gsym(a);
4672 gsym_addr(b, d);
4673 } else if (tok == '{') {
4674 Sym *llabel;
4675 int block_vla_sp_loc, *saved_vla_sp_loc, saved_vla_flags;
4677 next();
4678 /* record local declaration stack position */
4679 s = local_stack;
4680 frame_bottom = sym_push2(&local_stack, SYM_FIELD, 0, 0);
4681 frame_bottom->next = scope_stack_bottom;
4682 scope_stack_bottom = frame_bottom;
4683 llabel = local_label_stack;
4685 /* save VLA state */
4686 block_vla_sp_loc = *(saved_vla_sp_loc = vla_sp_loc);
4687 if (saved_vla_sp_loc != &vla_sp_root_loc)
4688 vla_sp_loc = &block_vla_sp_loc;
4690 saved_vla_flags = vla_flags;
4691 vla_flags |= VLA_NEED_NEW_FRAME;
4693 /* handle local labels declarations */
4694 if (tok == TOK_LABEL) {
4695 next();
4696 for(;;) {
4697 if (tok < TOK_UIDENT)
4698 expect("label identifier");
4699 label_push(&local_label_stack, tok, LABEL_DECLARED);
4700 next();
4701 if (tok == ',') {
4702 next();
4703 } else {
4704 skip(';');
4705 break;
4709 while (tok != '}') {
4710 label_or_decl(VT_LOCAL);
4711 if (tok != '}') {
4712 if (is_expr)
4713 vpop();
4714 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
4717 /* pop locally defined labels */
4718 label_pop(&local_label_stack, llabel);
4719 if(is_expr) {
4720 /* XXX: this solution makes only valgrind happy...
4721 triggered by gcc.c-torture/execute/20000917-1.c */
4722 Sym *p;
4723 switch(vtop->type.t & VT_BTYPE) {
4724 case VT_PTR:
4725 case VT_STRUCT:
4726 case VT_ENUM:
4727 case VT_FUNC:
4728 for(p=vtop->type.ref;p;p=p->prev)
4729 if(p->prev==s)
4730 tcc_error("unsupported expression type");
4733 /* pop locally defined symbols */
4734 scope_stack_bottom = scope_stack_bottom->next;
4735 sym_pop(&local_stack, s);
4737 /* Pop VLA frames and restore stack pointer if required */
4738 if (saved_vla_sp_loc != &vla_sp_root_loc)
4739 *saved_vla_sp_loc = block_vla_sp_loc;
4740 if (vla_sp_loc != (saved_vla_sp_loc == &vla_sp_root_loc ? &vla_sp_root_loc : &block_vla_sp_loc)) {
4741 vla_sp_loc = saved_vla_sp_loc;
4742 gen_vla_sp_restore(*vla_sp_loc);
4744 vla_flags = (vla_flags & ~VLA_SCOPE_FLAGS) | (saved_vla_flags & VLA_SCOPE_FLAGS);
4746 next();
4747 } else if (tok == TOK_RETURN) {
4748 next();
4749 if (tok != ';') {
4750 gexpr();
4751 gen_assign_cast(&func_vt);
4752 if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
4753 CType type, ret_type;
4754 int ret_align, ret_nregs;
4755 ret_nregs = gfunc_sret(&func_vt, func_var, &ret_type,
4756 &ret_align);
4757 if (0 == ret_nregs) {
4758 /* if returning structure, must copy it to implicit
4759 first pointer arg location */
4760 type = func_vt;
4761 mk_pointer(&type);
4762 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
4763 indir();
4764 vswap();
4765 /* copy structure value to pointer */
4766 vstore();
4767 } else {
4768 /* returning structure packed into registers */
4769 int r, size, addr, align;
4770 size = type_size(&func_vt,&align);
4771 if ((vtop->r != (VT_LOCAL | VT_LVAL) || (vtop->c.i & (ret_align-1)))
4772 && (align & (ret_align-1))) {
4773 loc = (loc - size) & -align;
4774 addr = loc;
4775 type = func_vt;
4776 vset(&type, VT_LOCAL | VT_LVAL, addr);
4777 vswap();
4778 vstore();
4779 vset(&ret_type, VT_LOCAL | VT_LVAL, addr);
4781 vtop->type = ret_type;
4782 if (is_float(ret_type.t))
4783 r = rc_fret(ret_type.t);
4784 else
4785 r = RC_IRET;
4787 for (;;) {
4788 gv(r);
4789 if (--ret_nregs == 0)
4790 break;
4791 /* We assume that when a structure is returned in multiple
4792 registers, their classes are consecutive values of the
4793 suite s(n) = 2^n */
4794 r <<= 1;
4795 /* XXX: compatible with arm only: ret_align == register_size */
4796 vtop->c.i += ret_align;
4797 vtop->r = VT_LOCAL | VT_LVAL;
4800 } else if (is_float(func_vt.t)) {
4801 gv(rc_fret(func_vt.t));
4802 } else {
4803 gv(RC_IRET);
4805 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
4807 skip(';');
4808 rsym = gjmp(rsym); /* jmp */
4809 } else if (tok == TOK_BREAK) {
4810 /* compute jump */
4811 if (!bsym)
4812 tcc_error("cannot break");
4813 *bsym = gjmp(*bsym);
4814 next();
4815 skip(';');
4816 } else if (tok == TOK_CONTINUE) {
4817 /* compute jump */
4818 if (!csym)
4819 tcc_error("cannot continue");
4820 *csym = gjmp(*csym);
4821 next();
4822 skip(';');
4823 } else if (tok == TOK_FOR) {
4824 int e;
4825 next();
4826 skip('(');
4827 s = local_stack;
4828 frame_bottom = sym_push2(&local_stack, SYM_FIELD, 0, 0);
4829 frame_bottom->next = scope_stack_bottom;
4830 scope_stack_bottom = frame_bottom;
4831 if (tok != ';') {
4832 /* c99 for-loop init decl? */
4833 if (!decl0(VT_LOCAL, 1)) {
4834 /* no, regular for-loop init expr */
4835 gexpr();
4836 vpop();
4839 skip(';');
4840 d = ind;
4841 c = ind;
4842 a = 0;
4843 b = 0;
4844 if (tok != ';') {
4845 gexpr();
4846 a = gvtst(1, 0);
4848 skip(';');
4849 if (tok != ')') {
4850 e = gjmp(0);
4851 c = ind;
4852 gexpr();
4853 vpop();
4854 gjmp_addr(d);
4855 gsym(e);
4857 skip(')');
4858 block(&a, &b, case_sym, def_sym, case_reg, 0);
4859 gjmp_addr(c);
4860 gsym(a);
4861 gsym_addr(b, c);
4862 scope_stack_bottom = scope_stack_bottom->next;
4863 sym_pop(&local_stack, s);
4864 } else
4865 if (tok == TOK_DO) {
4866 next();
4867 a = 0;
4868 b = 0;
4869 d = ind;
4870 block(&a, &b, case_sym, def_sym, case_reg, 0);
4871 skip(TOK_WHILE);
4872 skip('(');
4873 gsym(b);
4874 gexpr();
4875 c = gvtst(0, 0);
4876 gsym_addr(c, d);
4877 skip(')');
4878 gsym(a);
4879 skip(';');
4880 } else
4881 if (tok == TOK_SWITCH) {
4882 next();
4883 skip('(');
4884 gexpr();
4885 /* XXX: other types than integer */
4886 case_reg = gv(RC_INT);
4887 vpop();
4888 skip(')');
4889 a = 0;
4890 b = gjmp(0); /* jump to first case */
4891 c = 0;
4892 block(&a, csym, &b, &c, case_reg, 0);
4893 /* if no default, jmp after switch */
4894 if (c == 0)
4895 c = ind;
4896 /* default label */
4897 gsym_addr(b, c);
4898 /* break label */
4899 gsym(a);
4900 } else
4901 if (tok == TOK_CASE) {
4902 int v1, v2;
4903 if (!case_sym)
4904 expect("switch");
4905 next();
4906 v1 = expr_const();
4907 v2 = v1;
4908 if (gnu_ext && tok == TOK_DOTS) {
4909 next();
4910 v2 = expr_const();
4911 if (v2 < v1)
4912 tcc_warning("empty case range");
4914 /* since a case is like a label, we must skip it with a jmp */
4915 b = gjmp(0);
4916 gsym(*case_sym);
4917 vseti(case_reg, 0);
4918 vpushi(v1);
4919 if (v1 == v2) {
4920 gen_op(TOK_EQ);
4921 *case_sym = gtst(1, 0);
4922 } else {
4923 gen_op(TOK_GE);
4924 *case_sym = gtst(1, 0);
4925 vseti(case_reg, 0);
4926 vpushi(v2);
4927 gen_op(TOK_LE);
4928 *case_sym = gtst(1, *case_sym);
4930 gsym(b);
4931 skip(':');
4932 is_expr = 0;
4933 goto block_after_label;
4934 } else
4935 if (tok == TOK_DEFAULT) {
4936 next();
4937 skip(':');
4938 if (!def_sym)
4939 expect("switch");
4940 if (*def_sym)
4941 tcc_error("too many 'default'");
4942 *def_sym = ind;
4943 is_expr = 0;
4944 goto block_after_label;
4945 } else
4946 if (tok == TOK_GOTO) {
4947 next();
4948 if (tok == '*' && gnu_ext) {
4949 /* computed goto */
4950 next();
4951 gexpr();
4952 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
4953 expect("pointer");
4954 ggoto();
4955 } else if (tok >= TOK_UIDENT) {
4956 s = label_find(tok);
4957 /* put forward definition if needed */
4958 if (!s) {
4959 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
4960 } else {
4961 if (s->r == LABEL_DECLARED)
4962 s->r = LABEL_FORWARD;
4964 /* label already defined */
4965 if (vla_flags & VLA_IN_SCOPE) {
4966 /* If VLAs are in use, save the current stack pointer and
4967 reset the stack pointer to what it was at function entry
4968 (label will restore stack pointer in inner scopes) */
4969 vla_sp_save();
4970 gen_vla_sp_restore(vla_sp_root_loc);
4972 if (s->r & LABEL_FORWARD)
4973 s->jnext = gjmp(s->jnext);
4974 else
4975 gjmp_addr(s->jnext);
4976 next();
4977 } else {
4978 expect("label identifier");
4980 skip(';');
4981 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
4982 asm_instr();
4983 } else {
4984 b = is_label();
4985 if (b) {
4986 /* label case */
4987 if (vla_flags & VLA_IN_SCOPE) {
4988 /* save/restore stack pointer across label
4989 this is a no-op when combined with the load immediately
4990 after the label unless we arrive via goto */
4991 vla_sp_save();
4993 s = label_find(b);
4994 if (s) {
4995 if (s->r == LABEL_DEFINED)
4996 tcc_error("duplicate label '%s'", get_tok_str(s->v, NULL));
4997 gsym(s->jnext);
4998 s->r = LABEL_DEFINED;
4999 } else {
5000 s = label_push(&global_label_stack, b, LABEL_DEFINED);
5002 s->jnext = ind;
5003 if (vla_flags & VLA_IN_SCOPE) {
5004 gen_vla_sp_restore(*vla_sp_loc);
5005 vla_flags |= VLA_NEED_NEW_FRAME;
5007 /* we accept this, but it is a mistake */
5008 block_after_label:
5009 if (tok == '}') {
5010 tcc_warning("deprecated use of label at end of compound statement");
5011 } else {
5012 if (is_expr)
5013 vpop();
5014 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
5016 } else {
5017 /* expression case */
5018 if (tok != ';') {
5019 if (is_expr) {
5020 vpop();
5021 gexpr();
5022 } else {
5023 gexpr();
5024 vpop();
5027 skip(';');
5032 /* t is the array or struct type. c is the array or struct
5033 address. cur_index/cur_field is the pointer to the current
5034 value. 'size_only' is true if only size info is needed (only used
5035 in arrays) */
5036 static void decl_designator(CType *type, Section *sec, unsigned long c,
5037 int *cur_index, Sym **cur_field,
5038 int size_only)
5040 Sym *s, *f;
5041 int notfirst, index, index_last, align, l, nb_elems, elem_size;
5042 CType type1;
5044 notfirst = 0;
5045 elem_size = 0;
5046 nb_elems = 1;
5047 if (gnu_ext && (l = is_label()) != 0)
5048 goto struct_field;
5049 while (tok == '[' || tok == '.') {
5050 if (tok == '[') {
5051 if (!(type->t & VT_ARRAY))
5052 expect("array type");
5053 s = type->ref;
5054 next();
5055 index = expr_const();
5056 if (index < 0 || (s->c >= 0 && index >= s->c))
5057 expect("invalid index");
5058 if (tok == TOK_DOTS && gnu_ext) {
5059 next();
5060 index_last = expr_const();
5061 if (index_last < 0 ||
5062 (s->c >= 0 && index_last >= s->c) ||
5063 index_last < index)
5064 expect("invalid index");
5065 } else {
5066 index_last = index;
5068 skip(']');
5069 if (!notfirst)
5070 *cur_index = index_last;
5071 type = pointed_type(type);
5072 elem_size = type_size(type, &align);
5073 c += index * elem_size;
5074 /* NOTE: we only support ranges for last designator */
5075 nb_elems = index_last - index + 1;
5076 if (nb_elems != 1) {
5077 notfirst = 1;
5078 break;
5080 } else {
5081 next();
5082 l = tok;
5083 next();
5084 struct_field:
5085 if ((type->t & VT_BTYPE) != VT_STRUCT)
5086 expect("struct/union type");
5087 s = type->ref;
5088 l |= SYM_FIELD;
5089 f = s->next;
5090 while (f) {
5091 if (f->v == l)
5092 break;
5093 f = f->next;
5095 if (!f)
5096 expect("field");
5097 if (!notfirst)
5098 *cur_field = f;
5099 /* XXX: fix this mess by using explicit storage field */
5100 type1 = f->type;
5101 type1.t |= (type->t & ~VT_TYPE);
5102 type = &type1;
5103 c += f->c;
5105 notfirst = 1;
5107 if (notfirst) {
5108 if (tok == '=') {
5109 next();
5110 } else {
5111 if (!gnu_ext)
5112 expect("=");
5114 } else {
5115 if (type->t & VT_ARRAY) {
5116 index = *cur_index;
5117 type = pointed_type(type);
5118 c += index * type_size(type, &align);
5119 } else {
5120 f = *cur_field;
5121 if (!f)
5122 tcc_error("too many field init");
5123 /* XXX: fix this mess by using explicit storage field */
5124 type1 = f->type;
5125 type1.t |= (type->t & ~VT_TYPE);
5126 type = &type1;
5127 c += f->c;
5130 decl_initializer(type, sec, c, 0, size_only);
5132 /* XXX: make it more general */
5133 if (!size_only && nb_elems > 1) {
5134 unsigned long c_end;
5135 uint8_t *src, *dst;
5136 int i;
5138 if (!sec)
5139 tcc_error("range init not supported yet for dynamic storage");
5140 c_end = c + nb_elems * elem_size;
5141 if (c_end > sec->data_allocated)
5142 section_realloc(sec, c_end);
5143 src = sec->data + c;
5144 dst = src;
5145 for(i = 1; i < nb_elems; i++) {
5146 dst += elem_size;
5147 memcpy(dst, src, elem_size);
5152 #define EXPR_VAL 0
5153 #define EXPR_CONST 1
5154 #define EXPR_ANY 2
5156 /* store a value or an expression directly in global data or in local array */
5157 static void init_putv(CType *type, Section *sec, unsigned long c,
5158 int v, int expr_type)
5160 int saved_global_expr, bt, bit_pos, bit_size;
5161 void *ptr;
5162 unsigned long long bit_mask;
5163 CType dtype;
5165 switch(expr_type) {
5166 case EXPR_VAL:
5167 vpushi(v);
5168 break;
5169 case EXPR_CONST:
5170 /* compound literals must be allocated globally in this case */
5171 saved_global_expr = global_expr;
5172 global_expr = 1;
5173 expr_const1();
5174 global_expr = saved_global_expr;
5175 /* NOTE: symbols are accepted */
5176 if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
5177 tcc_error("initializer element is not constant");
5178 break;
5179 case EXPR_ANY:
5180 expr_eq();
5181 break;
5184 dtype = *type;
5185 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
5187 if (sec) {
5188 /* XXX: not portable */
5189 /* XXX: generate error if incorrect relocation */
5190 gen_assign_cast(&dtype);
5191 bt = type->t & VT_BTYPE;
5192 /* we'll write at most 12 bytes */
5193 if (c + 12 > sec->data_allocated) {
5194 section_realloc(sec, c + 12);
5196 ptr = sec->data + c;
5197 /* XXX: make code faster ? */
5198 if (!(type->t & VT_BITFIELD)) {
5199 bit_pos = 0;
5200 bit_size = 32;
5201 bit_mask = -1LL;
5202 } else {
5203 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5204 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
5205 bit_mask = (1LL << bit_size) - 1;
5207 if ((vtop->r & VT_SYM) &&
5208 (bt == VT_BYTE ||
5209 bt == VT_SHORT ||
5210 bt == VT_DOUBLE ||
5211 bt == VT_LDOUBLE ||
5212 bt == VT_LLONG ||
5213 (bt == VT_INT && bit_size != 32)))
5214 tcc_error("initializer element is not computable at load time");
5215 switch(bt) {
5216 case VT_BOOL:
5217 vtop->c.i = (vtop->c.i != 0);
5218 case VT_BYTE:
5219 *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5220 break;
5221 case VT_SHORT:
5222 *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5223 break;
5224 case VT_DOUBLE:
5225 *(double *)ptr = vtop->c.d;
5226 break;
5227 case VT_LDOUBLE:
5228 *(long double *)ptr = vtop->c.ld;
5229 break;
5230 case VT_LLONG:
5231 *(long long *)ptr |= (vtop->c.ll & bit_mask) << bit_pos;
5232 break;
5233 case VT_PTR:
5234 if (vtop->r & VT_SYM) {
5235 greloc(sec, vtop->sym, c, R_DATA_PTR);
5237 *(addr_t *)ptr |= (vtop->c.ptr_offset & bit_mask) << bit_pos;
5238 break;
5239 default:
5240 if (vtop->r & VT_SYM) {
5241 greloc(sec, vtop->sym, c, R_DATA_PTR);
5243 *(int *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5244 break;
5246 vtop--;
5247 } else {
5248 vset(&dtype, VT_LOCAL|VT_LVAL, c);
5249 vswap();
5250 vstore();
5251 vpop();
5255 /* put zeros for variable based init */
5256 static void init_putz(CType *t, Section *sec, unsigned long c, int size)
5258 if (sec) {
5259 /* nothing to do because globals are already set to zero */
5260 } else {
5261 vpush_global_sym(&func_old_type, TOK_memset);
5262 vseti(VT_LOCAL, c);
5263 #ifdef TCC_TARGET_ARM
5264 vpushs(size);
5265 vpushi(0);
5266 #else
5267 vpushi(0);
5268 vpushs(size);
5269 #endif
5270 gfunc_call(3);
5274 /* 't' contains the type and storage info. 'c' is the offset of the
5275 object in section 'sec'. If 'sec' is NULL, it means stack based
5276 allocation. 'first' is true if array '{' must be read (multi
5277 dimension implicit array init handling). 'size_only' is true if
5278 size only evaluation is wanted (only for arrays). */
5279 static void decl_initializer(CType *type, Section *sec, unsigned long c,
5280 int first, int size_only)
5282 int index, array_length, n, no_oblock, nb, parlevel, parlevel1, i;
5283 int size1, align1, expr_type;
5284 Sym *s, *f;
5285 CType *t1;
5287 if (type->t & VT_VLA) {
5288 int a;
5290 /* save current stack pointer */
5291 if (vla_flags & VLA_NEED_NEW_FRAME) {
5292 vla_sp_save();
5293 vla_flags = VLA_IN_SCOPE;
5294 vla_sp_loc = &vla_sp_loc_tmp;
5297 vla_runtime_type_size(type, &a);
5298 gen_vla_alloc(type, a);
5299 vset(type, VT_LOCAL|VT_LVAL, c);
5300 vswap();
5301 vstore();
5302 vpop();
5303 } else if (type->t & VT_ARRAY) {
5304 s = type->ref;
5305 n = s->c;
5306 array_length = 0;
5307 t1 = pointed_type(type);
5308 size1 = type_size(t1, &align1);
5310 no_oblock = 1;
5311 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
5312 tok == '{') {
5313 if (tok != '{')
5314 tcc_error("character array initializer must be a literal,"
5315 " optionally enclosed in braces");
5316 skip('{');
5317 no_oblock = 0;
5320 /* only parse strings here if correct type (otherwise: handle
5321 them as ((w)char *) expressions */
5322 if ((tok == TOK_LSTR &&
5323 #ifdef TCC_TARGET_PE
5324 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
5325 #else
5326 (t1->t & VT_BTYPE) == VT_INT
5327 #endif
5328 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
5329 while (tok == TOK_STR || tok == TOK_LSTR) {
5330 int cstr_len, ch;
5331 CString *cstr;
5333 cstr = tokc.cstr;
5334 /* compute maximum number of chars wanted */
5335 if (tok == TOK_STR)
5336 cstr_len = cstr->size;
5337 else
5338 cstr_len = cstr->size / sizeof(nwchar_t);
5339 cstr_len--;
5340 nb = cstr_len;
5341 if (n >= 0 && nb > (n - array_length))
5342 nb = n - array_length;
5343 if (!size_only) {
5344 if (cstr_len > nb)
5345 tcc_warning("initializer-string for array is too long");
5346 /* in order to go faster for common case (char
5347 string in global variable, we handle it
5348 specifically */
5349 if (sec && tok == TOK_STR && size1 == 1) {
5350 memcpy(sec->data + c + array_length, cstr->data, nb);
5351 } else {
5352 for(i=0;i<nb;i++) {
5353 if (tok == TOK_STR)
5354 ch = ((unsigned char *)cstr->data)[i];
5355 else
5356 ch = ((nwchar_t *)cstr->data)[i];
5357 init_putv(t1, sec, c + (array_length + i) * size1,
5358 ch, EXPR_VAL);
5362 array_length += nb;
5363 next();
5365 /* only add trailing zero if enough storage (no
5366 warning in this case since it is standard) */
5367 if (n < 0 || array_length < n) {
5368 if (!size_only) {
5369 init_putv(t1, sec, c + (array_length * size1), 0, EXPR_VAL);
5371 array_length++;
5373 } else {
5374 index = 0;
5375 while (tok != '}') {
5376 decl_designator(type, sec, c, &index, NULL, size_only);
5377 if (n >= 0 && index >= n)
5378 tcc_error("index too large");
5379 /* must put zero in holes (note that doing it that way
5380 ensures that it even works with designators) */
5381 if (!size_only && array_length < index) {
5382 init_putz(t1, sec, c + array_length * size1,
5383 (index - array_length) * size1);
5385 index++;
5386 if (index > array_length)
5387 array_length = index;
5388 /* special test for multi dimensional arrays (may not
5389 be strictly correct if designators are used at the
5390 same time) */
5391 if (index >= n && no_oblock)
5392 break;
5393 if (tok == '}')
5394 break;
5395 skip(',');
5398 if (!no_oblock)
5399 skip('}');
5400 /* put zeros at the end */
5401 if (!size_only && n >= 0 && array_length < n) {
5402 init_putz(t1, sec, c + array_length * size1,
5403 (n - array_length) * size1);
5405 /* patch type size if needed */
5406 if (n < 0)
5407 s->c = array_length;
5408 } else if ((type->t & VT_BTYPE) == VT_STRUCT &&
5409 (sec || !first || tok == '{')) {
5410 int par_count;
5412 /* NOTE: the previous test is a specific case for automatic
5413 struct/union init */
5414 /* XXX: union needs only one init */
5416 /* XXX: this test is incorrect for local initializers
5417 beginning with ( without {. It would be much more difficult
5418 to do it correctly (ideally, the expression parser should
5419 be used in all cases) */
5420 par_count = 0;
5421 if (tok == '(') {
5422 AttributeDef ad1;
5423 CType type1;
5424 next();
5425 while (tok == '(') {
5426 par_count++;
5427 next();
5429 if (!parse_btype(&type1, &ad1))
5430 expect("cast");
5431 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
5432 #if 0
5433 if (!is_assignable_types(type, &type1))
5434 tcc_error("invalid type for cast");
5435 #endif
5436 skip(')');
5438 no_oblock = 1;
5439 if (first || tok == '{') {
5440 skip('{');
5441 no_oblock = 0;
5443 s = type->ref;
5444 f = s->next;
5445 array_length = 0;
5446 index = 0;
5447 n = s->c;
5448 while (tok != '}') {
5449 decl_designator(type, sec, c, NULL, &f, size_only);
5450 index = f->c;
5451 if (!size_only && array_length < index) {
5452 init_putz(type, sec, c + array_length,
5453 index - array_length);
5455 index = index + type_size(&f->type, &align1);
5456 if (index > array_length)
5457 array_length = index;
5459 /* gr: skip fields from same union - ugly. */
5460 while (f->next) {
5461 ///printf("index: %2d %08x -- %2d %08x\n", f->c, f->type.t, f->next->c, f->next->type.t);
5462 /* test for same offset */
5463 if (f->next->c != f->c)
5464 break;
5465 /* if yes, test for bitfield shift */
5466 if ((f->type.t & VT_BITFIELD) && (f->next->type.t & VT_BITFIELD)) {
5467 int bit_pos_1 = (f->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5468 int bit_pos_2 = (f->next->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5469 //printf("bitfield %d %d\n", bit_pos_1, bit_pos_2);
5470 if (bit_pos_1 != bit_pos_2)
5471 break;
5473 f = f->next;
5476 f = f->next;
5477 if (no_oblock && f == NULL)
5478 break;
5479 if (tok == '}')
5480 break;
5481 skip(',');
5483 /* put zeros at the end */
5484 if (!size_only && array_length < n) {
5485 init_putz(type, sec, c + array_length,
5486 n - array_length);
5488 if (!no_oblock)
5489 skip('}');
5490 while (par_count) {
5491 skip(')');
5492 par_count--;
5494 } else if (tok == '{') {
5495 next();
5496 decl_initializer(type, sec, c, first, size_only);
5497 skip('}');
5498 } else if (size_only) {
5499 /* just skip expression */
5500 parlevel = parlevel1 = 0;
5501 while ((parlevel > 0 || parlevel1 > 0 ||
5502 (tok != '}' && tok != ',')) && tok != -1) {
5503 if (tok == '(')
5504 parlevel++;
5505 else if (tok == ')')
5506 parlevel--;
5507 else if (tok == '{')
5508 parlevel1++;
5509 else if (tok == '}')
5510 parlevel1--;
5511 next();
5513 } else {
5514 /* currently, we always use constant expression for globals
5515 (may change for scripting case) */
5516 expr_type = EXPR_CONST;
5517 if (!sec)
5518 expr_type = EXPR_ANY;
5519 init_putv(type, sec, c, 0, expr_type);
5523 /* parse an initializer for type 't' if 'has_init' is non zero, and
5524 allocate space in local or global data space ('r' is either
5525 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
5526 variable 'v' with an associated name represented by 'asm_label' of
5527 scope 'scope' is declared before initializers are parsed. If 'v' is
5528 zero, then a reference to the new object is put in the value stack.
5529 If 'has_init' is 2, a special parsing is done to handle string
5530 constants. */
5531 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
5532 int has_init, int v, char *asm_label,
5533 int scope)
5535 int size, align, addr, data_offset;
5536 int level;
5537 ParseState saved_parse_state = {0};
5538 TokenString init_str;
5539 Section *sec;
5540 Sym *flexible_array;
5542 flexible_array = NULL;
5543 if ((type->t & VT_BTYPE) == VT_STRUCT) {
5544 Sym *field = type->ref->next;
5545 if (field) {
5546 while (field->next)
5547 field = field->next;
5548 if (field->type.t & VT_ARRAY && field->type.ref->c < 0)
5549 flexible_array = field;
5553 size = type_size(type, &align);
5554 /* If unknown size, we must evaluate it before
5555 evaluating initializers because
5556 initializers can generate global data too
5557 (e.g. string pointers or ISOC99 compound
5558 literals). It also simplifies local
5559 initializers handling */
5560 tok_str_new(&init_str);
5561 if (size < 0 || (flexible_array && has_init)) {
5562 if (!has_init)
5563 tcc_error("unknown type size");
5564 /* get all init string */
5565 if (has_init == 2) {
5566 /* only get strings */
5567 while (tok == TOK_STR || tok == TOK_LSTR) {
5568 tok_str_add_tok(&init_str);
5569 next();
5571 } else {
5572 level = 0;
5573 while (level > 0 || (tok != ',' && tok != ';')) {
5574 if (tok < 0)
5575 tcc_error("unexpected end of file in initializer");
5576 tok_str_add_tok(&init_str);
5577 if (tok == '{')
5578 level++;
5579 else if (tok == '}') {
5580 level--;
5581 if (level <= 0) {
5582 next();
5583 break;
5586 next();
5589 tok_str_add(&init_str, -1);
5590 tok_str_add(&init_str, 0);
5592 /* compute size */
5593 save_parse_state(&saved_parse_state);
5595 macro_ptr = init_str.str;
5596 next();
5597 decl_initializer(type, NULL, 0, 1, 1);
5598 /* prepare second initializer parsing */
5599 macro_ptr = init_str.str;
5600 next();
5602 /* if still unknown size, error */
5603 size = type_size(type, &align);
5604 if (size < 0)
5605 tcc_error("unknown type size");
5607 if (flexible_array)
5608 size += flexible_array->type.ref->c * pointed_size(&flexible_array->type);
5609 /* take into account specified alignment if bigger */
5610 if (ad->a.aligned) {
5611 if (ad->a.aligned > align)
5612 align = ad->a.aligned;
5613 } else if (ad->a.packed) {
5614 align = 1;
5616 if ((r & VT_VALMASK) == VT_LOCAL) {
5617 sec = NULL;
5618 #ifdef CONFIG_TCC_BCHECK
5619 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5620 loc--;
5622 #endif
5623 loc = (loc - size) & -align;
5624 addr = loc;
5625 #ifdef CONFIG_TCC_BCHECK
5626 /* handles bounds */
5627 /* XXX: currently, since we do only one pass, we cannot track
5628 '&' operators, so we add only arrays */
5629 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5630 unsigned long *bounds_ptr;
5631 /* add padding between regions */
5632 loc--;
5633 /* then add local bound info */
5634 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(unsigned long));
5635 bounds_ptr[0] = addr;
5636 bounds_ptr[1] = size;
5638 #endif
5639 if (v) {
5640 /* local variable */
5641 sym_push(v, type, r, addr);
5642 } else {
5643 /* push local reference */
5644 vset(type, r, addr);
5646 } else {
5647 Sym *sym;
5649 sym = NULL;
5650 if (v && scope == VT_CONST) {
5651 /* see if the symbol was already defined */
5652 sym = sym_find(v);
5653 if (sym) {
5654 if (!is_compatible_types(&sym->type, type))
5655 tcc_error("incompatible types for redefinition of '%s'",
5656 get_tok_str(v, NULL));
5657 if (sym->type.t & VT_EXTERN) {
5658 /* if the variable is extern, it was not allocated */
5659 sym->type.t &= ~VT_EXTERN;
5660 /* set array size if it was omitted in extern
5661 declaration */
5662 if ((sym->type.t & VT_ARRAY) &&
5663 sym->type.ref->c < 0 &&
5664 type->ref->c >= 0)
5665 sym->type.ref->c = type->ref->c;
5666 } else {
5667 /* we accept several definitions of the same
5668 global variable. this is tricky, because we
5669 must play with the SHN_COMMON type of the symbol */
5670 /* XXX: should check if the variable was already
5671 initialized. It is incorrect to initialized it
5672 twice */
5673 /* no init data, we won't add more to the symbol */
5674 if (!has_init)
5675 goto no_alloc;
5680 /* allocate symbol in corresponding section */
5681 sec = ad->section;
5682 if (!sec) {
5683 if (has_init)
5684 sec = data_section;
5685 else if (tcc_state->nocommon)
5686 sec = bss_section;
5688 if (sec) {
5689 data_offset = sec->data_offset;
5690 data_offset = (data_offset + align - 1) & -align;
5691 addr = data_offset;
5692 /* very important to increment global pointer at this time
5693 because initializers themselves can create new initializers */
5694 data_offset += size;
5695 #ifdef CONFIG_TCC_BCHECK
5696 /* add padding if bound check */
5697 if (tcc_state->do_bounds_check)
5698 data_offset++;
5699 #endif
5700 sec->data_offset = data_offset;
5701 /* allocate section space to put the data */
5702 if (sec->sh_type != SHT_NOBITS &&
5703 data_offset > sec->data_allocated)
5704 section_realloc(sec, data_offset);
5705 /* align section if needed */
5706 if (align > sec->sh_addralign)
5707 sec->sh_addralign = align;
5708 } else {
5709 addr = 0; /* avoid warning */
5712 if (v) {
5713 if (scope != VT_CONST || !sym) {
5714 sym = sym_push(v, type, r | VT_SYM, 0);
5715 sym->asm_label = asm_label;
5717 /* update symbol definition */
5718 if (sec) {
5719 put_extern_sym(sym, sec, addr, size);
5720 } else {
5721 ElfW(Sym) *esym;
5722 /* put a common area */
5723 put_extern_sym(sym, NULL, align, size);
5724 /* XXX: find a nicer way */
5725 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
5726 esym->st_shndx = SHN_COMMON;
5728 } else {
5729 /* push global reference */
5730 sym = get_sym_ref(type, sec, addr, size);
5731 vpushsym(type, sym);
5733 /* patch symbol weakness */
5734 if (type->t & VT_WEAK)
5735 weaken_symbol(sym);
5736 apply_visibility(sym, type);
5737 #ifdef CONFIG_TCC_BCHECK
5738 /* handles bounds now because the symbol must be defined
5739 before for the relocation */
5740 if (tcc_state->do_bounds_check) {
5741 unsigned long *bounds_ptr;
5743 greloc(bounds_section, sym, bounds_section->data_offset, R_DATA_PTR);
5744 /* then add global bound info */
5745 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(long));
5746 bounds_ptr[0] = 0; /* relocated */
5747 bounds_ptr[1] = size;
5749 #endif
5751 if (has_init || (type->t & VT_VLA)) {
5752 decl_initializer(type, sec, addr, 1, 0);
5753 /* restore parse state if needed */
5754 if (init_str.str) {
5755 tok_str_free(init_str.str);
5756 restore_parse_state(&saved_parse_state);
5758 /* patch flexible array member size back to -1, */
5759 /* for possible subsequent similar declarations */
5760 if (flexible_array)
5761 flexible_array->type.ref->c = -1;
5763 no_alloc: ;
5766 static void put_func_debug(Sym *sym)
5768 char buf[512];
5770 /* stabs info */
5771 /* XXX: we put here a dummy type */
5772 snprintf(buf, sizeof(buf), "%s:%c1",
5773 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
5774 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
5775 cur_text_section, sym->c);
5776 /* //gr gdb wants a line at the function */
5777 put_stabn(N_SLINE, 0, file->line_num, 0);
5778 last_ind = 0;
5779 last_line_num = 0;
5782 /* parse an old style function declaration list */
5783 /* XXX: check multiple parameter */
5784 static void func_decl_list(Sym *func_sym)
5786 AttributeDef ad;
5787 int v;
5788 Sym *s;
5789 CType btype, type;
5791 /* parse each declaration */
5792 while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF &&
5793 tok != TOK_ASM1 && tok != TOK_ASM2 && tok != TOK_ASM3) {
5794 if (!parse_btype(&btype, &ad))
5795 expect("declaration list");
5796 if (((btype.t & VT_BTYPE) == VT_ENUM ||
5797 (btype.t & VT_BTYPE) == VT_STRUCT) &&
5798 tok == ';') {
5799 /* we accept no variable after */
5800 } else {
5801 for(;;) {
5802 type = btype;
5803 type_decl(&type, &ad, &v, TYPE_DIRECT);
5804 /* find parameter in function parameter list */
5805 s = func_sym->next;
5806 while (s != NULL) {
5807 if ((s->v & ~SYM_FIELD) == v)
5808 goto found;
5809 s = s->next;
5811 tcc_error("declaration for parameter '%s' but no such parameter",
5812 get_tok_str(v, NULL));
5813 found:
5814 /* check that no storage specifier except 'register' was given */
5815 if (type.t & VT_STORAGE)
5816 tcc_error("storage class specified for '%s'", get_tok_str(v, NULL));
5817 convert_parameter_type(&type);
5818 /* we can add the type (NOTE: it could be local to the function) */
5819 s->type = type;
5820 /* accept other parameters */
5821 if (tok == ',')
5822 next();
5823 else
5824 break;
5827 skip(';');
5831 /* parse a function defined by symbol 'sym' and generate its code in
5832 'cur_text_section' */
5833 static void gen_function(Sym *sym)
5835 int saved_nocode_wanted = nocode_wanted;
5836 nocode_wanted = 0;
5837 ind = cur_text_section->data_offset;
5838 /* NOTE: we patch the symbol size later */
5839 put_extern_sym(sym, cur_text_section, ind, 0);
5840 funcname = get_tok_str(sym->v, NULL);
5841 func_ind = ind;
5842 /* Initialize VLA state */
5843 vla_sp_loc = &vla_sp_root_loc;
5844 vla_flags = VLA_NEED_NEW_FRAME;
5845 /* put debug symbol */
5846 if (tcc_state->do_debug)
5847 put_func_debug(sym);
5848 /* push a dummy symbol to enable local sym storage */
5849 sym_push2(&local_stack, SYM_FIELD, 0, 0);
5850 gfunc_prolog(&sym->type);
5851 #ifdef CONFIG_TCC_BCHECK
5852 if (tcc_state->do_bounds_check
5853 && !strcmp(get_tok_str(sym->v, NULL), "main")) {
5854 int i;
5856 sym = local_stack;
5857 for (i = 0, sym = local_stack; i < 2; i++, sym = sym->prev) {
5858 if (sym->v & SYM_FIELD || sym->prev->v & SYM_FIELD)
5859 break;
5860 vpush_global_sym(&func_old_type, TOK___bound_main_arg);
5861 vset(&sym->type, sym->r, sym->c);
5862 gfunc_call(1);
5865 #endif
5866 rsym = 0;
5867 block(NULL, NULL, NULL, NULL, 0, 0);
5868 gsym(rsym);
5869 gfunc_epilog();
5870 cur_text_section->data_offset = ind;
5871 label_pop(&global_label_stack, NULL);
5872 /* reset local stack */
5873 scope_stack_bottom = NULL;
5874 sym_pop(&local_stack, NULL);
5875 /* end of function */
5876 /* patch symbol size */
5877 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
5878 ind - func_ind;
5879 /* patch symbol weakness (this definition overrules any prototype) */
5880 if (sym->type.t & VT_WEAK)
5881 weaken_symbol(sym);
5882 apply_visibility(sym, &sym->type);
5883 if (tcc_state->do_debug) {
5884 put_stabn(N_FUN, 0, 0, ind - func_ind);
5886 /* It's better to crash than to generate wrong code */
5887 cur_text_section = NULL;
5888 funcname = ""; /* for safety */
5889 func_vt.t = VT_VOID; /* for safety */
5890 func_var = 0; /* for safety */
5891 ind = 0; /* for safety */
5892 nocode_wanted = saved_nocode_wanted;
5895 ST_FUNC void gen_inline_functions(void)
5897 Sym *sym;
5898 int *str, inline_generated, i;
5899 struct InlineFunc *fn;
5901 /* iterate while inline function are referenced */
5902 for(;;) {
5903 inline_generated = 0;
5904 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
5905 fn = tcc_state->inline_fns[i];
5906 sym = fn->sym;
5907 if (sym && sym->c) {
5908 /* the function was used: generate its code and
5909 convert it to a normal function */
5910 str = fn->token_str;
5911 fn->sym = NULL;
5912 if (file)
5913 pstrcpy(file->filename, sizeof file->filename, fn->filename);
5914 sym->r = VT_SYM | VT_CONST;
5915 sym->type.t &= ~VT_INLINE;
5917 macro_ptr = str;
5918 next();
5919 cur_text_section = text_section;
5920 gen_function(sym);
5921 macro_ptr = NULL; /* fail safe */
5923 inline_generated = 1;
5926 if (!inline_generated)
5927 break;
5929 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
5930 fn = tcc_state->inline_fns[i];
5931 str = fn->token_str;
5932 tok_str_free(str);
5934 dynarray_reset(&tcc_state->inline_fns, &tcc_state->nb_inline_fns);
5937 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
5938 static int decl0(int l, int is_for_loop_init)
5940 int v, has_init, r;
5941 CType type, btype;
5942 Sym *sym;
5943 AttributeDef ad;
5945 while (1) {
5946 if (!parse_btype(&btype, &ad)) {
5947 if (is_for_loop_init)
5948 return 0;
5949 /* skip redundant ';' */
5950 /* XXX: find more elegant solution */
5951 if (tok == ';') {
5952 next();
5953 continue;
5955 if (l == VT_CONST &&
5956 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
5957 /* global asm block */
5958 asm_global_instr();
5959 continue;
5961 /* special test for old K&R protos without explicit int
5962 type. Only accepted when defining global data */
5963 if (l == VT_LOCAL || tok < TOK_DEFINE)
5964 break;
5965 btype.t = VT_INT;
5967 if (((btype.t & VT_BTYPE) == VT_ENUM ||
5968 (btype.t & VT_BTYPE) == VT_STRUCT) &&
5969 tok == ';') {
5970 /* we accept no variable after */
5971 next();
5972 continue;
5974 while (1) { /* iterate thru each declaration */
5975 char *asm_label; // associated asm label
5976 type = btype;
5977 type_decl(&type, &ad, &v, TYPE_DIRECT);
5978 #if 0
5980 char buf[500];
5981 type_to_str(buf, sizeof(buf), t, get_tok_str(v, NULL));
5982 printf("type = '%s'\n", buf);
5984 #endif
5985 if ((type.t & VT_BTYPE) == VT_FUNC) {
5986 if ((type.t & VT_STATIC) && (l == VT_LOCAL)) {
5987 tcc_error("function without file scope cannot be static");
5989 /* if old style function prototype, we accept a
5990 declaration list */
5991 sym = type.ref;
5992 if (sym->c == FUNC_OLD)
5993 func_decl_list(sym);
5996 asm_label = NULL;
5997 if (gnu_ext && (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
5998 CString astr;
6000 asm_label_instr(&astr);
6001 asm_label = tcc_strdup(astr.data);
6002 cstr_free(&astr);
6004 /* parse one last attribute list, after asm label */
6005 parse_attribute(&ad);
6008 if (ad.a.weak)
6009 type.t |= VT_WEAK;
6010 #ifdef TCC_TARGET_PE
6011 if (ad.a.func_import)
6012 type.t |= VT_IMPORT;
6013 if (ad.a.func_export)
6014 type.t |= VT_EXPORT;
6015 #endif
6016 type.t |= ad.a.visibility << VT_VIS_SHIFT;
6018 if (tok == '{') {
6019 if (l == VT_LOCAL)
6020 tcc_error("cannot use local functions");
6021 if ((type.t & VT_BTYPE) != VT_FUNC)
6022 expect("function definition");
6024 /* reject abstract declarators in function definition */
6025 sym = type.ref;
6026 while ((sym = sym->next) != NULL)
6027 if (!(sym->v & ~SYM_FIELD))
6028 expect("identifier");
6030 /* XXX: cannot do better now: convert extern line to static inline */
6031 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
6032 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
6034 sym = sym_find(v);
6035 if (sym) {
6036 Sym *ref;
6037 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
6038 goto func_error1;
6040 ref = sym->type.ref;
6041 if (0 == ref->a.func_proto)
6042 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
6044 /* use func_call from prototype if not defined */
6045 if (ref->a.func_call != FUNC_CDECL
6046 && type.ref->a.func_call == FUNC_CDECL)
6047 type.ref->a.func_call = ref->a.func_call;
6049 /* use export from prototype */
6050 if (ref->a.func_export)
6051 type.ref->a.func_export = 1;
6053 /* use static from prototype */
6054 if (sym->type.t & VT_STATIC)
6055 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
6057 /* If the definition has no visibility use the
6058 one from prototype. */
6059 if (! (type.t & VT_VIS_MASK))
6060 type.t |= sym->type.t & VT_VIS_MASK;
6062 if (!is_compatible_types(&sym->type, &type)) {
6063 func_error1:
6064 tcc_error("incompatible types for redefinition of '%s'",
6065 get_tok_str(v, NULL));
6067 type.ref->a.func_proto = 0;
6068 /* if symbol is already defined, then put complete type */
6069 sym->type = type;
6070 } else {
6071 /* put function symbol */
6072 sym = global_identifier_push(v, type.t, 0);
6073 sym->type.ref = type.ref;
6076 /* static inline functions are just recorded as a kind
6077 of macro. Their code will be emitted at the end of
6078 the compilation unit only if they are used */
6079 if ((type.t & (VT_INLINE | VT_STATIC)) ==
6080 (VT_INLINE | VT_STATIC)) {
6081 TokenString func_str;
6082 int block_level;
6083 struct InlineFunc *fn;
6084 const char *filename;
6086 tok_str_new(&func_str);
6088 block_level = 0;
6089 for(;;) {
6090 int t;
6091 if (tok == TOK_EOF)
6092 tcc_error("unexpected end of file");
6093 tok_str_add_tok(&func_str);
6094 t = tok;
6095 next();
6096 if (t == '{') {
6097 block_level++;
6098 } else if (t == '}') {
6099 block_level--;
6100 if (block_level == 0)
6101 break;
6104 tok_str_add(&func_str, -1);
6105 tok_str_add(&func_str, 0);
6106 filename = file ? file->filename : "";
6107 fn = tcc_malloc(sizeof *fn + strlen(filename));
6108 strcpy(fn->filename, filename);
6109 fn->sym = sym;
6110 fn->token_str = func_str.str;
6111 dynarray_add((void ***)&tcc_state->inline_fns, &tcc_state->nb_inline_fns, fn);
6113 } else {
6114 /* compute text section */
6115 cur_text_section = ad.section;
6116 if (!cur_text_section)
6117 cur_text_section = text_section;
6118 sym->r = VT_SYM | VT_CONST;
6119 gen_function(sym);
6121 break;
6122 } else {
6123 if (btype.t & VT_TYPEDEF) {
6124 /* save typedefed type */
6125 /* XXX: test storage specifiers ? */
6126 sym = sym_push(v, &type, 0, 0);
6127 sym->a = ad.a;
6128 sym->type.t |= VT_TYPEDEF;
6129 } else {
6130 r = 0;
6131 if ((type.t & VT_BTYPE) == VT_FUNC) {
6132 /* external function definition */
6133 /* specific case for func_call attribute */
6134 ad.a.func_proto = 1;
6135 type.ref->a = ad.a;
6136 } else if (!(type.t & VT_ARRAY)) {
6137 /* not lvalue if array */
6138 r |= lvalue_type(type.t);
6140 has_init = (tok == '=');
6141 if (has_init && (type.t & VT_VLA))
6142 tcc_error("Variable length array cannot be initialized");
6143 if ((btype.t & VT_EXTERN) || ((type.t & VT_BTYPE) == VT_FUNC) ||
6144 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
6145 !has_init && l == VT_CONST && type.ref->c < 0)) {
6146 /* external variable or function */
6147 /* NOTE: as GCC, uninitialized global static
6148 arrays of null size are considered as
6149 extern */
6150 sym = external_sym(v, &type, r, asm_label);
6152 if (ad.alias_target) {
6153 Section tsec;
6154 Elf32_Sym *esym;
6155 Sym *alias_target;
6157 alias_target = sym_find(ad.alias_target);
6158 if (!alias_target || !alias_target->c)
6159 tcc_error("unsupported forward __alias__ attribute");
6160 esym = &((Elf32_Sym *)symtab_section->data)[alias_target->c];
6161 tsec.sh_num = esym->st_shndx;
6162 put_extern_sym2(sym, &tsec, esym->st_value, esym->st_size, 0);
6164 } else {
6165 type.t |= (btype.t & VT_STATIC); /* Retain "static". */
6166 if (type.t & VT_STATIC)
6167 r |= VT_CONST;
6168 else
6169 r |= l;
6170 if (has_init)
6171 next();
6172 decl_initializer_alloc(&type, &ad, r, has_init, v, asm_label, l);
6175 if (tok != ',') {
6176 if (is_for_loop_init)
6177 return 1;
6178 skip(';');
6179 break;
6181 next();
6183 ad.a.aligned = 0;
6186 return 0;
6189 ST_FUNC void decl(int l)
6191 decl0(l, 0);