revert vstore()
[tinycc.git] / tccgen.c
blob387b9863c467376ad71ad9aa26300f011fd67f27
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_putz;
94 static int is_force;
96 ST_FUNC void vpush64(int ty, unsigned long long v);
97 ST_FUNC void vpush(CType *type);
98 ST_FUNC int gvtst(int inv, int t);
99 ST_FUNC int is_btype_size(int bt);
101 ST_INLN int is_float(int t)
103 int bt;
104 bt = t & VT_BTYPE;
105 return bt == VT_LDOUBLE || bt == VT_DOUBLE || bt == VT_FLOAT || bt == VT_QFLOAT;
108 /* we use our own 'finite' function to avoid potential problems with
109 non standard math libs */
110 /* XXX: endianness dependent */
111 ST_FUNC int ieee_finite(double d)
113 int p[4];
114 memcpy(p, &d, sizeof(double));
115 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
118 ST_FUNC void test_lvalue(void)
120 if (!(vtop->r & VT_LVAL))
121 expect("lvalue");
124 /* ------------------------------------------------------------------------- */
125 /* symbol allocator */
126 static Sym *__sym_malloc(void)
128 Sym *sym_pool, *sym, *last_sym;
129 int i;
131 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
132 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
134 last_sym = sym_free_first;
135 sym = sym_pool;
136 for(i = 0; i < SYM_POOL_NB; i++) {
137 sym->next = last_sym;
138 last_sym = sym;
139 sym++;
141 sym_free_first = last_sym;
142 return last_sym;
145 static inline Sym *sym_malloc(void)
147 Sym *sym;
148 sym = sym_free_first;
149 if (!sym)
150 sym = __sym_malloc();
151 sym_free_first = sym->next;
152 return sym;
155 ST_INLN void sym_free(Sym *sym)
157 sym->next = sym_free_first;
158 tcc_free(sym->asm_label);
159 sym_free_first = sym;
162 /* push, without hashing */
163 ST_FUNC Sym *sym_push2(Sym **ps, int v, int t, long c)
165 Sym *s;
166 if (ps == &local_stack) {
167 for (s = *ps; s && s != scope_stack_bottom; s = s->prev)
168 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM && s->v == v)
169 tcc_error("incompatible types for redefinition of '%s'",
170 get_tok_str(v, NULL));
172 s = sym_malloc();
173 s->asm_label = NULL;
174 s->v = v;
175 s->type.t = t;
176 s->type.ref = NULL;
177 #ifdef _WIN64
178 s->d = NULL;
179 #endif
180 s->c = c;
181 s->next = NULL;
182 /* add in stack */
183 s->prev = *ps;
184 *ps = s;
185 return s;
188 /* find a symbol and return its associated structure. 's' is the top
189 of the symbol stack */
190 ST_FUNC Sym *sym_find2(Sym *s, int v)
192 while (s) {
193 if (s->v == v)
194 return s;
195 else if (s->v == -1)
196 return NULL;
197 s = s->prev;
199 return NULL;
202 /* structure lookup */
203 ST_INLN Sym *struct_find(int v)
205 v -= TOK_IDENT;
206 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
207 return NULL;
208 return table_ident[v]->sym_struct;
211 /* find an identifier */
212 ST_INLN Sym *sym_find(int v)
214 v -= TOK_IDENT;
215 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
216 return NULL;
217 return table_ident[v]->sym_identifier;
220 /* push a given symbol on the symbol stack */
221 ST_FUNC Sym *sym_push(int v, CType *type, int r, int c)
223 Sym *s, **ps;
224 TokenSym *ts;
226 if (local_stack)
227 ps = &local_stack;
228 else
229 ps = &global_stack;
230 s = sym_push2(ps, v, type->t, c);
231 s->type.ref = type->ref;
232 s->r = r;
233 /* don't record fields or anonymous symbols */
234 /* XXX: simplify */
235 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
236 /* record symbol in token array */
237 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
238 if (v & SYM_STRUCT)
239 ps = &ts->sym_struct;
240 else
241 ps = &ts->sym_identifier;
242 s->prev_tok = *ps;
243 *ps = s;
245 return s;
248 /* push a global identifier */
249 ST_FUNC Sym *global_identifier_push(int v, int t, int c)
251 Sym *s, **ps;
252 s = sym_push2(&global_stack, v, t, c);
253 /* don't record anonymous symbol */
254 if (v < SYM_FIRST_ANOM) {
255 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
256 /* modify the top most local identifier, so that
257 sym_identifier will point to 's' when popped */
258 while (*ps != NULL)
259 ps = &(*ps)->prev_tok;
260 s->prev_tok = NULL;
261 *ps = s;
263 return s;
266 /* pop symbols until top reaches 'b' */
267 ST_FUNC void sym_pop(Sym **ptop, Sym *b)
269 Sym *s, *ss, **ps;
270 TokenSym *ts;
271 int v;
273 s = *ptop;
274 while(s != b) {
275 ss = s->prev;
276 v = s->v;
277 /* remove symbol in token array */
278 /* XXX: simplify */
279 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
280 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
281 if (v & SYM_STRUCT)
282 ps = &ts->sym_struct;
283 else
284 ps = &ts->sym_identifier;
285 *ps = s->prev_tok;
287 sym_free(s);
288 s = ss;
290 *ptop = b;
293 static void weaken_symbol(Sym *sym)
295 sym->type.t |= VT_WEAK;
296 if (sym->c > 0) {
297 int esym_type;
298 ElfW(Sym) *esym;
300 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
301 esym_type = ELFW(ST_TYPE)(esym->st_info);
302 esym->st_info = ELFW(ST_INFO)(STB_WEAK, esym_type);
306 static void apply_visibility(Sym *sym, CType *type)
308 int vis = sym->type.t & VT_VIS_MASK;
309 int vis2 = type->t & VT_VIS_MASK;
310 if (vis == (STV_DEFAULT << VT_VIS_SHIFT))
311 vis = vis2;
312 else if (vis2 == (STV_DEFAULT << VT_VIS_SHIFT))
314 else
315 vis = (vis < vis2) ? vis : vis2;
316 sym->type.t &= ~VT_VIS_MASK;
317 sym->type.t |= vis;
319 if (sym->c > 0) {
320 ElfW(Sym) *esym;
322 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
323 vis >>= VT_VIS_SHIFT;
324 esym->st_other = (esym->st_other & ~ELFW(ST_VISIBILITY)(-1)) | vis;
328 /* ------------------------------------------------------------------------- */
330 ST_FUNC void swap(int *p, int *q)
332 int t;
333 t = *p;
334 *p = *q;
335 *q = t;
338 static void vsetc(CType *type, int r, CValue *vc)
340 int v;
342 if (vtop >= vstack + (VSTACK_SIZE - 1))
343 tcc_error("memory full (vstack)");
344 /* cannot let cpu flags if other instruction are generated. Also
345 avoid leaving VT_JMP anywhere except on the top of the stack
346 because it would complicate the code generator. */
347 if (vtop >= vstack) {
348 v = vtop->r & VT_VALMASK;
349 if (v == VT_CMP || (v & ~1) == VT_JMP)
350 gv(RC_INT);
352 vtop++;
353 vtop->type = *type;
354 vtop->r = r;
355 vtop->r2 = VT_CONST;
356 vtop->c = *vc;
359 /* push constant of type "type" with useless value */
360 ST_FUNC void vpush(CType *type)
362 CValue cval;
363 vsetc(type, VT_CONST, &cval);
366 /* push integer constant */
367 ST_FUNC void vpushi(int v)
369 CValue cval;
370 cval.i = v;
371 vsetc(&int_type, VT_CONST, &cval);
374 /* push a pointer sized constant */
375 static void vpushs(addr_t v)
377 CValue cval;
378 cval.ptr_offset = v;
379 vsetc(&size_type, VT_CONST, &cval);
382 /* push arbitrary 64bit constant */
383 ST_FUNC void vpush64(int ty, unsigned long long v)
385 CValue cval;
386 CType ctype;
387 ctype.t = ty;
388 ctype.ref = NULL;
389 cval.ull = v;
390 vsetc(&ctype, VT_CONST, &cval);
393 /* push long long constant */
394 static inline void vpushll(long long v)
396 vpush64(VT_LLONG, v);
399 /* push a symbol value of TYPE */
400 static inline void vpushsym(CType *type, Sym *sym)
402 CValue cval;
403 cval.ptr_offset = 0;
404 vsetc(type, VT_CONST | VT_SYM, &cval);
405 vtop->sym = sym;
408 /* Return a static symbol pointing to a section */
409 ST_FUNC Sym *get_sym_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
411 int v;
412 Sym *sym;
414 v = anon_sym++;
415 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
416 sym->type.ref = type->ref;
417 sym->r = VT_CONST | VT_SYM;
418 put_extern_sym(sym, sec, offset, size);
419 return sym;
422 /* push a reference to a section offset by adding a dummy symbol */
423 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
425 vpushsym(type, get_sym_ref(type, sec, offset, size));
428 /* define a new external reference to a symbol 'v' of type 'u' */
429 ST_FUNC Sym *external_global_sym(int v, CType *type, int r)
431 Sym *s;
433 s = sym_find(v);
434 if (!s) {
435 /* push forward reference */
436 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
437 s->type.ref = type->ref;
438 s->r = r | VT_CONST | VT_SYM;
440 return s;
443 /* define a new external reference to a symbol 'v' with alternate asm
444 name 'asm_label' of type 'u'. 'asm_label' is equal to NULL if there
445 is no alternate name (most cases) */
446 static Sym *external_sym(int v, CType *type, int r, char *asm_label)
448 Sym *s;
450 s = sym_find(v);
451 if (!s) {
452 /* push forward reference */
453 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
454 s->asm_label = asm_label;
455 s->type.t |= VT_EXTERN;
456 } else if (s->type.ref == func_old_type.ref) {
457 s->type.ref = type->ref;
458 s->r = r | VT_CONST | VT_SYM;
459 s->type.t |= VT_EXTERN;
460 } else if (!is_compatible_types(&s->type, type)) {
461 tcc_error("incompatible types for redefinition of '%s'",
462 get_tok_str(v, NULL));
464 /* Merge some storage attributes. */
465 if (type->t & VT_WEAK)
466 weaken_symbol(s);
468 if (type->t & VT_VIS_MASK)
469 apply_visibility(s, type);
471 return s;
474 /* push a reference to global symbol v */
475 ST_FUNC void vpush_global_sym(CType *type, int v)
477 vpushsym(type, external_global_sym(v, type, 0));
480 ST_FUNC void vset(CType *type, int r, int v)
482 CValue cval;
484 cval.i = v;
485 vsetc(type, r, &cval);
488 static void vseti(int r, int v)
490 CType type;
491 type.t = VT_INT;
492 type.ref = 0;
493 vset(&type, r, v);
496 ST_FUNC void vswap(void)
498 SValue tmp;
499 /* cannot let cpu flags if other instruction are generated. Also
500 avoid leaving VT_JMP anywhere except on the top of the stack
501 because it would complicate the code generator. */
502 if (vtop >= vstack) {
503 int v = vtop->r & VT_VALMASK;
504 if (v == VT_CMP || (v & ~1) == VT_JMP)
505 gv(RC_INT);
507 tmp = vtop[0];
508 vtop[0] = vtop[-1];
509 vtop[-1] = tmp;
511 /* XXX: +2% overall speed possible with optimized memswap
513 * memswap(&vtop[0], &vtop[1], sizeof *vtop);
517 ST_FUNC void vpushv(SValue *v)
519 if (vtop >= vstack + (VSTACK_SIZE - 1))
520 tcc_error("memory full (vstack)");
521 vtop++;
522 *vtop = *v;
525 static void vdup(void)
527 vpushv(vtop);
530 /* save r to the memory stack, and mark it as being free */
531 ST_FUNC void save_reg(int r)
533 int l, saved, size, align;
534 SValue *p, sv;
535 CType *type;
537 /* modify all stack values */
538 saved = 0;
539 l = 0;
540 for(p=vstack;p<=vtop;p++) {
541 if ((p->r & VT_VALMASK) == r ||
542 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
543 /* must save value on stack if not already done */
544 if (!saved) {
545 /* NOTE: must reload 'r' because r might be equal to r2 */
546 r = p->r & VT_VALMASK;
547 /* store register in the stack */
548 type = &p->type;
549 if ((p->r & VT_LVAL) ||
550 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
551 #ifdef TCC_TARGET_X86_64
552 type = &char_pointer_type;
553 #else
554 type = &int_type;
555 #endif
556 size = type_size(type, &align);
557 loc = (loc - size) & -align;
558 sv.type.t = type->t;
559 sv.r = VT_LOCAL | VT_LVAL;
560 sv.c.ul = loc;
561 store(r, &sv);
562 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
563 /* x86 specific: need to pop fp register ST0 if saved */
564 if (r == TREG_ST0) {
565 o(0xd8dd); /* fstp %st(0) */
567 #endif
568 #ifndef TCC_TARGET_X86_64
569 /* special long long case */
570 if ((type->t & VT_BTYPE) == VT_LLONG) {
571 sv.c.ul += 4;
572 store(p->r2, &sv);
574 #endif
575 l = loc;
576 saved = 1;
578 /* mark that stack entry as being saved on the stack */
579 if (p->r & VT_LVAL) {
580 /* also clear the bounded flag because the
581 relocation address of the function was stored in
582 p->c.ul */
583 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
584 } else {
585 p->r = lvalue_type(p->type.t) | VT_LOCAL;
587 p->r2 = VT_CONST;
588 p->c.ul = l;
593 #ifdef TCC_TARGET_ARM
594 /* find a register of class 'rc2' with at most one reference on stack.
595 * If none, call get_reg(rc) */
596 ST_FUNC int get_reg_ex(int rc, int rc2)
598 int r;
599 SValue *p;
601 for(r=0;r<NB_REGS;r++) {
602 if (reg_classes[r] & rc2) {
603 int n;
604 n=0;
605 for(p = vstack; p <= vtop; p++) {
606 if ((p->r & VT_VALMASK) == r ||
607 (p->r2 & VT_VALMASK) == r)
608 n++;
610 if (n <= 1)
611 return r;
614 return get_reg(rc);
616 #endif
618 /* find a free register of class 'rc'. If none, save one register */
619 ST_FUNC int get_reg(int rc)
621 int r;
622 SValue *p;
624 /* find a free register */
625 for(r=0;r<NB_REGS;r++) {
626 if (reg_classes[r] & rc) {
627 for(p=vstack;p<=vtop;p++) {
628 if ((p->r & VT_VALMASK) == r ||
629 (p->r2 & VT_VALMASK) == r)
630 goto notfound;
632 return r;
634 notfound: ;
637 /* no register left : free the first one on the stack (VERY
638 IMPORTANT to start from the bottom to ensure that we don't
639 spill registers used in gen_opi()) */
640 for(p=vstack;p<=vtop;p++) {
641 /* look at second register (if long long) */
642 r = p->r2 & VT_VALMASK;
643 if (r < VT_CONST && (reg_classes[r] & rc))
644 goto save_found;
645 r = p->r & VT_VALMASK;
646 if (r < VT_CONST && (reg_classes[r] & rc)) {
647 save_found:
648 save_reg(r);
649 return r;
652 /* Should never comes here */
653 return -1;
656 /* save registers up to (vtop - n) stack entry */
657 ST_FUNC void save_regs(int n)
659 int r;
660 SValue *p, *p1;
661 p1 = vtop - n;
662 for(p = vstack;p <= p1; p++) {
663 r = p->r & VT_VALMASK;
664 if (r < VT_CONST) {
665 save_reg(r);
670 /* move register 's' (of type 't') to 'r', and flush previous value of r to memory
671 if needed */
672 static void move_reg(int r, int s, int t)
674 SValue sv;
676 if (r != s) {
677 save_reg(r);
678 sv.type.t = t;
679 sv.type.ref = NULL;
680 sv.r = s;
681 sv.c.ul = 0;
682 load(r, &sv);
686 /* get address of vtop (vtop MUST BE an lvalue) */
687 static void gaddrof(void)
689 if (vtop->r & VT_REF)
690 gv(RC_INT);
691 vtop->r &= ~VT_LVAL;
692 /* tricky: if saved lvalue, then we can go back to lvalue */
693 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
694 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
699 #ifdef CONFIG_TCC_BCHECK
700 /* generate lvalue bound code */
701 static void gbound(void)
703 int lval_type;
704 CType type1;
706 vtop->r &= ~VT_MUSTBOUND;
707 /* if lvalue, then use checking code before dereferencing */
708 if (vtop->r & VT_LVAL) {
709 /* if not VT_BOUNDED value, then make one */
710 if (!(vtop->r & VT_BOUNDED)) {
711 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
712 /* must save type because we must set it to int to get pointer */
713 type1 = vtop->type;
714 vtop->type.t = VT_INT;
715 gaddrof();
716 vpushi(0);
717 gen_bounded_ptr_add();
718 vtop->r |= lval_type;
719 vtop->type = type1;
721 /* then check for dereferencing */
722 gen_bounded_ptr_deref();
725 #endif
727 /* store vtop a register belonging to class 'rc'. lvalues are
728 converted to values. Cannot be used if cannot be converted to
729 register value (such as structures). */
730 ST_FUNC int gv(int rc)
732 int r, bit_pos, bit_size, size, align, i;
733 int rc2;
735 /* NOTE: get_reg can modify vstack[] */
736 if (vtop->type.t & VT_BITFIELD) {
737 CType type;
738 int bits = 32;
739 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
740 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
741 /* remove bit field info to avoid loops */
742 vtop->type.t &= ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
743 /* cast to int to propagate signedness in following ops */
744 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
745 type.t = VT_LLONG;
746 bits = 64;
747 } else
748 type.t = VT_INT;
749 if((vtop->type.t & VT_UNSIGNED) ||
750 (vtop->type.t & VT_BTYPE) == VT_BOOL)
751 type.t |= VT_UNSIGNED;
752 gen_cast(&type);
753 /* generate shifts */
754 vpushi(bits - (bit_pos + bit_size));
755 gen_op(TOK_SHL);
756 vpushi(bits - bit_size);
757 /* NOTE: transformed to SHR if unsigned */
758 gen_op(TOK_SAR);
759 r = gv(rc);
760 } else {
761 if (is_float(vtop->type.t) &&
762 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
763 Sym *sym;
764 int *ptr;
765 unsigned long offset;
766 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
767 CValue check;
768 #endif
770 /* XXX: unify with initializers handling ? */
771 /* CPUs usually cannot use float constants, so we store them
772 generically in data segment */
773 size = type_size(&vtop->type, &align);
774 offset = (data_section->data_offset + align - 1) & -align;
775 data_section->data_offset = offset;
776 /* XXX: not portable yet */
777 #if defined(__i386__) || defined(__x86_64__)
778 /* Zero pad x87 tenbyte long doubles */
779 if (size == LDOUBLE_SIZE) {
780 vtop->c.tab[2] &= 0xffff;
781 #if LDOUBLE_SIZE == 16
782 vtop->c.tab[3] = 0;
783 #endif
785 #endif
786 ptr = section_ptr_add(data_section, size);
787 size = size >> 2;
788 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
789 check.d = 1;
790 if(check.tab[0])
791 for(i=0;i<size;i++)
792 ptr[i] = vtop->c.tab[size-1-i];
793 else
794 #endif
795 for(i=0;i<size;i++)
796 ptr[i] = vtop->c.tab[i];
797 sym = get_sym_ref(&vtop->type, data_section, offset, size << 2);
798 vtop->r |= VT_LVAL | VT_SYM;
799 vtop->sym = sym;
800 vtop->c.ptr_offset = 0;
802 #ifdef CONFIG_TCC_BCHECK
803 if (vtop->r & VT_MUSTBOUND)
804 gbound();
805 #endif
807 r = vtop->r & VT_VALMASK;
808 rc2 = (rc & RC_FLOAT) ? RC_FLOAT : RC_INT;
809 if (rc == RC_IRET)
810 rc2 = RC_LRET;
811 #ifdef TCC_TARGET_X86_64
812 else if (rc == RC_FRET)
813 rc2 = RC_QRET;
814 #endif
816 /* need to reload if:
817 - constant
818 - lvalue (need to dereference pointer)
819 - already a register, but not in the right class */
820 if (r >= VT_CONST
821 || (vtop->r & VT_LVAL)
822 || !(reg_classes[r] & rc)
823 #ifdef TCC_TARGET_X86_64
824 || ((vtop->type.t & VT_BTYPE) == VT_QLONG && !(reg_classes[vtop->r2] & rc2))
825 || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT && !(reg_classes[vtop->r2] & rc2))
826 #else
827 || ((vtop->type.t & VT_BTYPE) == VT_LLONG && !(reg_classes[vtop->r2] & rc2))
828 #endif
831 r = get_reg(rc);
832 #ifdef TCC_TARGET_X86_64
833 if (((vtop->type.t & VT_BTYPE) == VT_QLONG) || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT)) {
834 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
835 #else
836 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
837 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
838 unsigned long long ll;
839 #endif
840 int r2, original_type;
841 original_type = vtop->type.t;
842 /* two register type load : expand to two words
843 temporarily */
844 #ifndef TCC_TARGET_X86_64
845 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
846 /* load constant */
847 ll = vtop->c.ull;
848 vtop->c.ui = ll; /* first word */
849 load(r, vtop);
850 vtop->r = r; /* save register value */
851 vpushi(ll >> 32); /* second word */
852 } else
853 #endif
854 if (r >= VT_CONST || /* XXX: test to VT_CONST incorrect ? */
855 (vtop->r & VT_LVAL)) {
856 /* We do not want to modifier the long long
857 pointer here, so the safest (and less
858 efficient) is to save all the other registers
859 in the stack. XXX: totally inefficient. */
860 save_regs(1);
861 /* load from memory */
862 vtop->type.t = load_type;
863 load(r, vtop);
864 vdup();
865 vtop[-1].r = r; /* save register value */
866 /* increment pointer to get second word */
867 vtop->type.t = addr_type;
868 gaddrof();
869 vpushi(load_size);
870 gen_op('+');
871 vtop->r |= VT_LVAL;
872 vtop->type.t = load_type;
873 } else {
874 /* move registers */
875 load(r, vtop);
876 vdup();
877 vtop[-1].r = r; /* save register value */
878 vtop->r = vtop[-1].r2;
880 /* Allocate second register. Here we rely on the fact that
881 get_reg() tries first to free r2 of an SValue. */
882 r2 = get_reg(rc2);
883 load(r2, vtop);
884 vpop();
885 /* write second register */
886 vtop->r2 = r2;
887 vtop->type.t = original_type;
888 } else if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
889 int t1, t;
890 /* lvalue of scalar type : need to use lvalue type
891 because of possible cast */
892 t = vtop->type.t;
893 t1 = t;
894 /* compute memory access type */
895 if (vtop->r & VT_REF)
896 #ifdef TCC_TARGET_X86_64
897 t = VT_PTR;
898 #else
899 t = VT_INT;
900 #endif
901 else if (vtop->r & VT_LVAL_BYTE)
902 t = VT_BYTE;
903 else if (vtop->r & VT_LVAL_SHORT)
904 t = VT_SHORT;
905 if (vtop->r & VT_LVAL_UNSIGNED)
906 t |= VT_UNSIGNED;
907 vtop->type.t = t;
908 load(r, vtop);
909 /* restore wanted type */
910 vtop->type.t = t1;
911 } else {
912 /* one register type load */
913 load(r, vtop);
916 vtop->r = r;
917 #ifdef TCC_TARGET_C67
918 /* uses register pairs for doubles */
919 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
920 vtop->r2 = r+1;
921 #endif
923 return r;
926 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
927 ST_FUNC void gv2(int rc1, int rc2)
929 int v;
931 /* generate more generic register first. But VT_JMP or VT_CMP
932 values must be generated first in all cases to avoid possible
933 reload errors */
934 v = vtop[0].r & VT_VALMASK;
935 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
936 vswap();
937 gv(rc1);
938 vswap();
939 gv(rc2);
940 /* test if reload is needed for first register */
941 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
942 vswap();
943 gv(rc1);
944 vswap();
946 } else {
947 gv(rc2);
948 vswap();
949 gv(rc1);
950 vswap();
951 /* test if reload is needed for first register */
952 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
953 gv(rc2);
958 /* wrapper around RC_FRET to return a register by type */
959 static int rc_fret(int t)
961 #ifdef TCC_TARGET_X86_64
962 if (t == VT_LDOUBLE) {
963 return RC_ST0;
965 #endif
966 return RC_FRET;
969 /* wrapper around REG_FRET to return a register by type */
970 static int reg_fret(int t)
972 #ifdef TCC_TARGET_X86_64
973 if (t == VT_LDOUBLE) {
974 return TREG_ST0;
976 #endif
977 return REG_FRET;
980 /* expand long long on stack in two int registers */
981 static void lexpand(void)
983 int u;
985 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
986 gv(RC_INT);
987 vdup();
988 vtop[0].r = vtop[-1].r2;
989 vtop[0].r2 = VT_CONST;
990 vtop[-1].r2 = VT_CONST;
991 vtop[0].type.t = VT_INT | u;
992 vtop[-1].type.t = VT_INT | u;
995 #ifdef TCC_TARGET_ARM
996 /* expand long long on stack */
997 ST_FUNC void lexpand_nr(void)
999 int u,v;
1001 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
1002 vdup();
1003 vtop->r2 = VT_CONST;
1004 vtop->type.t = VT_INT | u;
1005 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
1006 if (v == VT_CONST) {
1007 vtop[-1].c.ui = vtop->c.ull;
1008 vtop->c.ui = vtop->c.ull >> 32;
1009 vtop->r = VT_CONST;
1010 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
1011 vtop->c.ui += 4;
1012 vtop->r = vtop[-1].r;
1013 } else if (v > VT_CONST) {
1014 vtop--;
1015 lexpand();
1016 } else
1017 vtop->r = vtop[-1].r2;
1018 vtop[-1].r2 = VT_CONST;
1019 vtop[-1].type.t = VT_INT | u;
1021 #endif
1023 #ifndef TCC_TARGET_X86_64
1024 /* build a long long from two ints */
1025 static void lbuild(int t)
1027 gv2(RC_INT, RC_INT);
1028 vtop[-1].r2 = vtop[0].r;
1029 vtop[-1].type.t = t;
1030 vpop();
1032 #endif
1034 /* rotate n first stack elements to the bottom
1035 I1 ... In -> I2 ... In I1 [top is right]
1037 ST_FUNC void vrotb(int n)
1039 int i;
1040 SValue tmp;
1042 tmp = vtop[-n + 1];
1043 for(i=-n+1;i!=0;i++)
1044 vtop[i] = vtop[i+1];
1045 vtop[0] = tmp;
1048 /* rotate the n elements before entry e towards the top
1049 I1 ... In ... -> In I1 ... I(n-1) ... [top is right]
1051 ST_FUNC void vrote(SValue *e, int n)
1053 int i;
1054 SValue tmp;
1056 tmp = *e;
1057 for(i = 0;i < n - 1; i++)
1058 e[-i] = e[-i - 1];
1059 e[-n + 1] = tmp;
1062 /* rotate n first stack elements to the top
1063 I1 ... In -> In I1 ... I(n-1) [top is right]
1065 ST_FUNC void vrott(int n)
1067 vrote(vtop, n);
1070 /* pop stack value */
1071 ST_FUNC void vpop(void)
1073 int v;
1074 v = vtop->r & VT_VALMASK;
1075 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1076 /* for x86, we need to pop the FP stack */
1077 if (v == TREG_ST0 && !nocode_wanted) {
1078 o(0xd8dd); /* fstp %st(0) */
1079 } else
1080 #endif
1081 if (v == VT_JMP || v == VT_JMPI) {
1082 /* need to put correct jump if && or || without test */
1083 gsym(vtop->c.ul);
1085 vtop--;
1088 /* convert stack entry to register and duplicate its value in another
1089 register */
1090 static void gv_dup(void)
1092 int rc, t, r, r1;
1093 SValue sv;
1094 t = vtop->type.t;
1095 #ifndef TCC_TARGET_X86_64
1096 if ((t & VT_BTYPE) == VT_LLONG) {
1097 lexpand();
1098 gv_dup();
1099 vswap();
1100 vrotb(3);
1101 gv_dup();
1102 vrotb(4);
1103 /* stack: H L L1 H1 */
1104 lbuild(t);
1105 vrott(3);
1106 vswap();
1107 lbuild(t);
1108 vswap();
1109 } else
1110 #endif
1112 /* duplicate value */
1113 if (is_float(t)) {
1114 rc = RC_FLOAT;
1115 #ifdef TCC_TARGET_X86_64
1116 if ((t & VT_BTYPE) == VT_LDOUBLE) {
1117 rc = RC_ST0;
1119 #endif
1120 }else
1121 rc = RC_INT;
1122 sv.type.t = t;
1123 r = gv(rc);
1124 r1 = get_reg(rc);
1125 sv.r = r;
1126 sv.c.ul = 0;
1127 load(r1, &sv); /* move r to r1 */
1128 vdup();
1129 /* duplicates value */
1130 if (r != r1)
1131 vtop->r = r1;
1135 /* Generate value test
1137 * Generate a test for any value (jump, comparison and integers) */
1138 ST_FUNC int gvtst(int inv, int t)
1140 int v = vtop->r & VT_VALMASK;
1141 if (v != VT_CMP && v != VT_JMP && v != VT_JMPI) {
1142 vpushi(0);
1143 gen_op(TOK_NE);
1145 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1146 /* constant jmp optimization */
1147 if ((vtop->c.i != 0) != inv)
1148 t = gjmp(t);
1149 vtop--;
1150 return t;
1152 return gtst(inv, t);
1155 #ifndef TCC_TARGET_X86_64
1156 /* generate CPU independent (unsigned) long long operations */
1157 static void gen_opl(int op)
1159 int t, a, b, op1, c, i;
1160 int func;
1161 unsigned short reg_iret = REG_IRET;
1162 unsigned short reg_lret = REG_LRET;
1163 SValue tmp;
1165 switch(op) {
1166 case '/':
1167 case TOK_PDIV:
1168 func = TOK___divdi3;
1169 goto gen_func;
1170 case TOK_UDIV:
1171 func = TOK___udivdi3;
1172 goto gen_func;
1173 case '%':
1174 func = TOK___moddi3;
1175 goto gen_mod_func;
1176 case TOK_UMOD:
1177 func = TOK___umoddi3;
1178 gen_mod_func:
1179 #ifdef TCC_ARM_EABI
1180 reg_iret = TREG_R2;
1181 reg_lret = TREG_R3;
1182 #endif
1183 gen_func:
1184 /* call generic long long function */
1185 vpush_global_sym(&func_old_type, func);
1186 vrott(3);
1187 gfunc_call(2);
1188 vpushi(0);
1189 vtop->r = reg_iret;
1190 vtop->r2 = reg_lret;
1191 break;
1192 case '^':
1193 case '&':
1194 case '|':
1195 case '*':
1196 case '+':
1197 case '-':
1198 t = vtop->type.t;
1199 vswap();
1200 lexpand();
1201 vrotb(3);
1202 lexpand();
1203 /* stack: L1 H1 L2 H2 */
1204 tmp = vtop[0];
1205 vtop[0] = vtop[-3];
1206 vtop[-3] = tmp;
1207 tmp = vtop[-2];
1208 vtop[-2] = vtop[-3];
1209 vtop[-3] = tmp;
1210 vswap();
1211 /* stack: H1 H2 L1 L2 */
1212 if (op == '*') {
1213 vpushv(vtop - 1);
1214 vpushv(vtop - 1);
1215 gen_op(TOK_UMULL);
1216 lexpand();
1217 /* stack: H1 H2 L1 L2 ML MH */
1218 for(i=0;i<4;i++)
1219 vrotb(6);
1220 /* stack: ML MH H1 H2 L1 L2 */
1221 tmp = vtop[0];
1222 vtop[0] = vtop[-2];
1223 vtop[-2] = tmp;
1224 /* stack: ML MH H1 L2 H2 L1 */
1225 gen_op('*');
1226 vrotb(3);
1227 vrotb(3);
1228 gen_op('*');
1229 /* stack: ML MH M1 M2 */
1230 gen_op('+');
1231 gen_op('+');
1232 } else if (op == '+' || op == '-') {
1233 /* XXX: add non carry method too (for MIPS or alpha) */
1234 if (op == '+')
1235 op1 = TOK_ADDC1;
1236 else
1237 op1 = TOK_SUBC1;
1238 gen_op(op1);
1239 /* stack: H1 H2 (L1 op L2) */
1240 vrotb(3);
1241 vrotb(3);
1242 gen_op(op1 + 1); /* TOK_xxxC2 */
1243 } else {
1244 gen_op(op);
1245 /* stack: H1 H2 (L1 op L2) */
1246 vrotb(3);
1247 vrotb(3);
1248 /* stack: (L1 op L2) H1 H2 */
1249 gen_op(op);
1250 /* stack: (L1 op L2) (H1 op H2) */
1252 /* stack: L H */
1253 lbuild(t);
1254 break;
1255 case TOK_SAR:
1256 case TOK_SHR:
1257 case TOK_SHL:
1258 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1259 t = vtop[-1].type.t;
1260 vswap();
1261 lexpand();
1262 vrotb(3);
1263 /* stack: L H shift */
1264 c = (int)vtop->c.i;
1265 /* constant: simpler */
1266 /* NOTE: all comments are for SHL. the other cases are
1267 done by swaping words */
1268 vpop();
1269 if (op != TOK_SHL)
1270 vswap();
1271 if (c >= 32) {
1272 /* stack: L H */
1273 vpop();
1274 if (c > 32) {
1275 vpushi(c - 32);
1276 gen_op(op);
1278 if (op != TOK_SAR) {
1279 vpushi(0);
1280 } else {
1281 gv_dup();
1282 vpushi(31);
1283 gen_op(TOK_SAR);
1285 vswap();
1286 } else {
1287 vswap();
1288 gv_dup();
1289 /* stack: H L L */
1290 vpushi(c);
1291 gen_op(op);
1292 vswap();
1293 vpushi(32 - c);
1294 if (op == TOK_SHL)
1295 gen_op(TOK_SHR);
1296 else
1297 gen_op(TOK_SHL);
1298 vrotb(3);
1299 /* stack: L L H */
1300 vpushi(c);
1301 if (op == TOK_SHL)
1302 gen_op(TOK_SHL);
1303 else
1304 gen_op(TOK_SHR);
1305 gen_op('|');
1307 if (op != TOK_SHL)
1308 vswap();
1309 lbuild(t);
1310 } else {
1311 /* XXX: should provide a faster fallback on x86 ? */
1312 switch(op) {
1313 case TOK_SAR:
1314 func = TOK___ashrdi3;
1315 goto gen_func;
1316 case TOK_SHR:
1317 func = TOK___lshrdi3;
1318 goto gen_func;
1319 case TOK_SHL:
1320 func = TOK___ashldi3;
1321 goto gen_func;
1324 break;
1325 default:
1326 /* compare operations */
1327 t = vtop->type.t;
1328 vswap();
1329 lexpand();
1330 vrotb(3);
1331 lexpand();
1332 /* stack: L1 H1 L2 H2 */
1333 tmp = vtop[-1];
1334 vtop[-1] = vtop[-2];
1335 vtop[-2] = tmp;
1336 /* stack: L1 L2 H1 H2 */
1337 /* compare high */
1338 op1 = op;
1339 /* when values are equal, we need to compare low words. since
1340 the jump is inverted, we invert the test too. */
1341 if (op1 == TOK_LT)
1342 op1 = TOK_LE;
1343 else if (op1 == TOK_GT)
1344 op1 = TOK_GE;
1345 else if (op1 == TOK_ULT)
1346 op1 = TOK_ULE;
1347 else if (op1 == TOK_UGT)
1348 op1 = TOK_UGE;
1349 a = 0;
1350 b = 0;
1351 gen_op(op1);
1352 if (op1 != TOK_NE) {
1353 a = gvtst(1, 0);
1355 if (op != TOK_EQ) {
1356 /* generate non equal test */
1357 /* XXX: NOT PORTABLE yet */
1358 if (a == 0) {
1359 b = gvtst(0, 0);
1360 } else {
1361 #if defined(TCC_TARGET_I386)
1362 b = psym(0x850f, 0);
1363 #elif defined(TCC_TARGET_ARM)
1364 b = ind;
1365 o(0x1A000000 | encbranch(ind, 0, 1));
1366 #elif defined(TCC_TARGET_C67)
1367 tcc_error("not implemented");
1368 #else
1369 #error not supported
1370 #endif
1373 /* compare low. Always unsigned */
1374 op1 = op;
1375 if (op1 == TOK_LT)
1376 op1 = TOK_ULT;
1377 else if (op1 == TOK_LE)
1378 op1 = TOK_ULE;
1379 else if (op1 == TOK_GT)
1380 op1 = TOK_UGT;
1381 else if (op1 == TOK_GE)
1382 op1 = TOK_UGE;
1383 gen_op(op1);
1384 a = gvtst(1, a);
1385 gsym(b);
1386 vseti(VT_JMPI, a);
1387 break;
1390 #endif
1392 /* handle integer constant optimizations and various machine
1393 independent opt */
1394 static void gen_opic(int op)
1396 int c1, c2, t1, t2, n;
1397 SValue *v1, *v2;
1398 long long l1, l2;
1399 typedef unsigned long long U;
1401 v1 = vtop - 1;
1402 v2 = vtop;
1403 t1 = v1->type.t & VT_BTYPE;
1404 t2 = v2->type.t & VT_BTYPE;
1406 if (t1 == VT_LLONG)
1407 l1 = v1->c.ll;
1408 else if (v1->type.t & VT_UNSIGNED)
1409 l1 = v1->c.ui;
1410 else
1411 l1 = v1->c.i;
1413 if (t2 == VT_LLONG)
1414 l2 = v2->c.ll;
1415 else if (v2->type.t & VT_UNSIGNED)
1416 l2 = v2->c.ui;
1417 else
1418 l2 = v2->c.i;
1420 /* currently, we cannot do computations with forward symbols */
1421 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1422 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1423 if (c1 && c2) {
1424 switch(op) {
1425 case '+': l1 += l2; break;
1426 case '-': l1 -= l2; break;
1427 case '&': l1 &= l2; break;
1428 case '^': l1 ^= l2; break;
1429 case '|': l1 |= l2; break;
1430 case '*': l1 *= l2; break;
1432 case TOK_PDIV:
1433 case '/':
1434 case '%':
1435 case TOK_UDIV:
1436 case TOK_UMOD:
1437 /* if division by zero, generate explicit division */
1438 if (l2 == 0) {
1439 if (const_wanted)
1440 tcc_error("division by zero in constant");
1441 goto general_case;
1443 switch(op) {
1444 default: l1 /= l2; break;
1445 case '%': l1 %= l2; break;
1446 case TOK_UDIV: l1 = (U)l1 / l2; break;
1447 case TOK_UMOD: l1 = (U)l1 % l2; break;
1449 break;
1450 case TOK_SHL: l1 <<= l2; break;
1451 case TOK_SHR: l1 = (U)l1 >> l2; break;
1452 case TOK_SAR: l1 >>= l2; break;
1453 /* tests */
1454 case TOK_ULT: l1 = (U)l1 < (U)l2; break;
1455 case TOK_UGE: l1 = (U)l1 >= (U)l2; break;
1456 case TOK_EQ: l1 = l1 == l2; break;
1457 case TOK_NE: l1 = l1 != l2; break;
1458 case TOK_ULE: l1 = (U)l1 <= (U)l2; break;
1459 case TOK_UGT: l1 = (U)l1 > (U)l2; break;
1460 case TOK_LT: l1 = l1 < l2; break;
1461 case TOK_GE: l1 = l1 >= l2; break;
1462 case TOK_LE: l1 = l1 <= l2; break;
1463 case TOK_GT: l1 = l1 > l2; break;
1464 /* logical */
1465 case TOK_LAND: l1 = l1 && l2; break;
1466 case TOK_LOR: l1 = l1 || l2; break;
1467 default:
1468 goto general_case;
1470 v1->c.ll = l1;
1471 vtop--;
1472 } else {
1473 /* if commutative ops, put c2 as constant */
1474 if (c1 && (op == '+' || op == '&' || op == '^' ||
1475 op == '|' || op == '*')) {
1476 vswap();
1477 c2 = c1; //c = c1, c1 = c2, c2 = c;
1478 l2 = l1; //l = l1, l1 = l2, l2 = l;
1480 /* Filter out NOP operations like x*1, x-0, x&-1... */
1481 if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
1482 op == TOK_PDIV) &&
1483 l2 == 1) ||
1484 ((op == '+' || op == '-' || op == '|' || op == '^' ||
1485 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
1486 l2 == 0) ||
1487 (op == '&' &&
1488 l2 == -1))) {
1489 /* nothing to do */
1490 vtop--;
1491 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
1492 /* try to use shifts instead of muls or divs */
1493 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
1494 n = -1;
1495 while (l2) {
1496 l2 >>= 1;
1497 n++;
1499 vtop->c.ll = n;
1500 if (op == '*')
1501 op = TOK_SHL;
1502 else if (op == TOK_PDIV)
1503 op = TOK_SAR;
1504 else
1505 op = TOK_SHR;
1507 goto general_case;
1508 } else if (c2 && (op == '+' || op == '-') &&
1509 (((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM))
1510 || (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
1511 /* symbol + constant case */
1512 if (op == '-')
1513 l2 = -l2;
1514 vtop--;
1515 vtop->c.ll += l2;
1516 } else {
1517 general_case:
1518 if (!nocode_wanted) {
1519 /* call low level op generator */
1520 if (t1 == VT_LLONG || t2 == VT_LLONG)
1521 gen_opl(op);
1522 else
1523 gen_opi(op);
1524 } else {
1525 vtop--;
1531 /* generate a floating point operation with constant propagation */
1532 static void gen_opif(int op)
1534 int c1, c2;
1535 SValue *v1, *v2;
1536 long double f1, f2;
1538 v1 = vtop - 1;
1539 v2 = vtop;
1540 /* currently, we cannot do computations with forward symbols */
1541 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1542 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1543 if (c1 && c2) {
1544 if (v1->type.t == VT_FLOAT) {
1545 f1 = v1->c.f;
1546 f2 = v2->c.f;
1547 } else if (v1->type.t == VT_DOUBLE) {
1548 f1 = v1->c.d;
1549 f2 = v2->c.d;
1550 } else {
1551 f1 = v1->c.ld;
1552 f2 = v2->c.ld;
1555 /* NOTE: we only do constant propagation if finite number (not
1556 NaN or infinity) (ANSI spec) */
1557 if (!ieee_finite(f1) || !ieee_finite(f2))
1558 goto general_case;
1560 switch(op) {
1561 case '+': f1 += f2; break;
1562 case '-': f1 -= f2; break;
1563 case '*': f1 *= f2; break;
1564 case '/':
1565 if (f2 == 0.0) {
1566 if (const_wanted)
1567 tcc_error("division by zero in constant");
1568 goto general_case;
1570 f1 /= f2;
1571 break;
1572 /* XXX: also handles tests ? */
1573 default:
1574 goto general_case;
1576 /* XXX: overflow test ? */
1577 if (v1->type.t == VT_FLOAT) {
1578 v1->c.f = f1;
1579 } else if (v1->type.t == VT_DOUBLE) {
1580 v1->c.d = f1;
1581 } else {
1582 v1->c.ld = f1;
1584 vtop--;
1585 } else {
1586 general_case:
1587 if (!nocode_wanted) {
1588 gen_opf(op);
1589 } else {
1590 vtop--;
1595 static int pointed_size(CType *type)
1597 int align;
1598 return type_size(pointed_type(type), &align);
1601 static void vla_runtime_pointed_size(CType *type)
1603 int align;
1604 vla_runtime_type_size(pointed_type(type), &align);
1607 static inline int is_null_pointer(SValue *p)
1609 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
1610 return 0;
1611 return ((p->type.t & VT_BTYPE) == VT_INT && p->c.i == 0) ||
1612 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.ll == 0) ||
1613 ((p->type.t & VT_BTYPE) == VT_PTR && p->c.ptr_offset == 0);
1616 static inline int is_integer_btype(int bt)
1618 return (bt == VT_BYTE || bt == VT_SHORT ||
1619 bt == VT_INT || bt == VT_LLONG);
1622 /* check types for comparison or subtraction of pointers */
1623 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
1625 CType *type1, *type2, tmp_type1, tmp_type2;
1626 int bt1, bt2;
1628 /* null pointers are accepted for all comparisons as gcc */
1629 if (is_null_pointer(p1) || is_null_pointer(p2))
1630 return;
1631 type1 = &p1->type;
1632 type2 = &p2->type;
1633 bt1 = type1->t & VT_BTYPE;
1634 bt2 = type2->t & VT_BTYPE;
1635 /* accept comparison between pointer and integer with a warning */
1636 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
1637 if (op != TOK_LOR && op != TOK_LAND )
1638 tcc_warning("comparison between pointer and integer");
1639 return;
1642 /* both must be pointers or implicit function pointers */
1643 if (bt1 == VT_PTR) {
1644 type1 = pointed_type(type1);
1645 } else if (bt1 != VT_FUNC)
1646 goto invalid_operands;
1648 if (bt2 == VT_PTR) {
1649 type2 = pointed_type(type2);
1650 } else if (bt2 != VT_FUNC) {
1651 invalid_operands:
1652 tcc_error("invalid operands to binary %s", get_tok_str(op, NULL));
1654 if ((type1->t & VT_BTYPE) == VT_VOID ||
1655 (type2->t & VT_BTYPE) == VT_VOID)
1656 return;
1657 tmp_type1 = *type1;
1658 tmp_type2 = *type2;
1659 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1660 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1661 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
1662 /* gcc-like error if '-' is used */
1663 if (op == '-')
1664 goto invalid_operands;
1665 else
1666 tcc_warning("comparison of distinct pointer types lacks a cast");
1670 /* generic gen_op: handles types problems */
1671 ST_FUNC void gen_op(int op)
1673 int u, t1, t2, bt1, bt2, t;
1674 CType type1;
1676 t1 = vtop[-1].type.t;
1677 t2 = vtop[0].type.t;
1678 bt1 = t1 & VT_BTYPE;
1679 bt2 = t2 & VT_BTYPE;
1681 if (bt1 == VT_PTR || bt2 == VT_PTR) {
1682 /* at least one operand is a pointer */
1683 /* relationnal op: must be both pointers */
1684 if (op >= TOK_ULT && op <= TOK_LOR) {
1685 check_comparison_pointer_types(vtop - 1, vtop, op);
1686 /* pointers are handled are unsigned */
1687 #ifdef TCC_TARGET_X86_64
1688 t = VT_LLONG | VT_UNSIGNED;
1689 #else
1690 t = VT_INT | VT_UNSIGNED;
1691 #endif
1692 goto std_op;
1694 /* if both pointers, then it must be the '-' op */
1695 if (bt1 == VT_PTR && bt2 == VT_PTR) {
1696 if (op != '-')
1697 tcc_error("cannot use pointers here");
1698 check_comparison_pointer_types(vtop - 1, vtop, op);
1699 /* XXX: check that types are compatible */
1700 if (vtop[-1].type.t & VT_VLA) {
1701 vla_runtime_pointed_size(&vtop[-1].type);
1702 } else {
1703 vpushi(pointed_size(&vtop[-1].type));
1705 vrott(3);
1706 gen_opic(op);
1707 /* set to integer type */
1708 #ifdef TCC_TARGET_X86_64
1709 vtop->type.t = VT_LLONG;
1710 #else
1711 vtop->type.t = VT_INT;
1712 #endif
1713 vswap();
1714 gen_op(TOK_PDIV);
1715 } else {
1716 /* exactly one pointer : must be '+' or '-'. */
1717 if (op != '-' && op != '+')
1718 tcc_error("cannot use pointers here");
1719 /* Put pointer as first operand */
1720 if (bt2 == VT_PTR) {
1721 vswap();
1722 swap(&t1, &t2);
1724 type1 = vtop[-1].type;
1725 type1.t &= ~VT_ARRAY;
1726 if (vtop[-1].type.t & VT_VLA)
1727 vla_runtime_pointed_size(&vtop[-1].type);
1728 else {
1729 u = pointed_size(&vtop[-1].type);
1730 if (u < 0)
1731 tcc_error("unknown array element size");
1732 #ifdef TCC_TARGET_X86_64
1733 vpushll(u);
1734 #else
1735 /* XXX: cast to int ? (long long case) */
1736 vpushi(u);
1737 #endif
1739 gen_op('*');
1740 #ifdef CONFIG_TCC_BCHECK
1741 /* if evaluating constant expression, no code should be
1742 generated, so no bound check */
1743 if (tcc_state->do_bounds_check && !const_wanted) {
1744 /* if bounded pointers, we generate a special code to
1745 test bounds */
1746 if (op == '-') {
1747 vpushi(0);
1748 vswap();
1749 gen_op('-');
1751 gen_bounded_ptr_add();
1752 } else
1753 #endif
1755 gen_opic(op);
1757 /* put again type if gen_opic() swaped operands */
1758 vtop->type = type1;
1760 } else if (is_float(bt1) || is_float(bt2)) {
1761 /* compute bigger type and do implicit casts */
1762 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
1763 t = VT_LDOUBLE;
1764 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
1765 t = VT_DOUBLE;
1766 } else {
1767 t = VT_FLOAT;
1769 /* floats can only be used for a few operations */
1770 if (op != '+' && op != '-' && op != '*' && op != '/' &&
1771 (op < TOK_ULT || op > TOK_GT))
1772 tcc_error("invalid operands for binary operation");
1773 goto std_op;
1774 } else if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL) {
1775 t = bt1 == VT_LLONG ? VT_LLONG : VT_INT;
1776 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (t | VT_UNSIGNED))
1777 t |= VT_UNSIGNED;
1778 goto std_op;
1779 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
1780 /* cast to biggest op */
1781 t = VT_LLONG;
1782 /* convert to unsigned if it does not fit in a long long */
1783 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
1784 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
1785 t |= VT_UNSIGNED;
1786 goto std_op;
1787 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
1788 tcc_error("comparison of struct");
1789 } else {
1790 /* integer operations */
1791 t = VT_INT;
1792 /* convert to unsigned if it does not fit in an integer */
1793 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
1794 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
1795 t |= VT_UNSIGNED;
1796 std_op:
1797 /* XXX: currently, some unsigned operations are explicit, so
1798 we modify them here */
1799 if (t & VT_UNSIGNED) {
1800 if (op == TOK_SAR)
1801 op = TOK_SHR;
1802 else if (op == '/')
1803 op = TOK_UDIV;
1804 else if (op == '%')
1805 op = TOK_UMOD;
1806 else if (op == TOK_LT)
1807 op = TOK_ULT;
1808 else if (op == TOK_GT)
1809 op = TOK_UGT;
1810 else if (op == TOK_LE)
1811 op = TOK_ULE;
1812 else if (op == TOK_GE)
1813 op = TOK_UGE;
1815 vswap();
1816 type1.t = t;
1817 gen_cast(&type1);
1818 vswap();
1819 /* special case for shifts and long long: we keep the shift as
1820 an integer */
1821 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
1822 type1.t = VT_INT;
1823 gen_cast(&type1);
1824 if (is_float(t))
1825 gen_opif(op);
1826 else
1827 gen_opic(op);
1828 if (op >= TOK_ULT && op <= TOK_GT) {
1829 /* relationnal op: the result is an int */
1830 vtop->type.t = VT_INT;
1831 } else {
1832 vtop->type.t = t;
1837 #ifndef TCC_TARGET_ARM
1838 /* generic itof for unsigned long long case */
1839 static void gen_cvt_itof1(int t)
1841 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
1842 (VT_LLONG | VT_UNSIGNED)) {
1844 if (t == VT_FLOAT)
1845 vpush_global_sym(&func_old_type, TOK___floatundisf);
1846 #if LDOUBLE_SIZE != 8
1847 else if (t == VT_LDOUBLE)
1848 vpush_global_sym(&func_old_type, TOK___floatundixf);
1849 #endif
1850 else
1851 vpush_global_sym(&func_old_type, TOK___floatundidf);
1852 vrott(2);
1853 gfunc_call(1);
1854 vpushi(0);
1855 vtop->r = reg_fret(t);
1856 } else {
1857 gen_cvt_itof(t);
1860 #endif
1862 /* generic ftoi for unsigned long long case */
1863 static void gen_cvt_ftoi1(int t)
1865 int st;
1867 if (t == (VT_LLONG | VT_UNSIGNED)) {
1868 /* not handled natively */
1869 st = vtop->type.t & VT_BTYPE;
1870 if (st == VT_FLOAT)
1871 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
1872 #if LDOUBLE_SIZE != 8
1873 else if (st == VT_LDOUBLE)
1874 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
1875 #endif
1876 else
1877 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
1878 vrott(2);
1879 gfunc_call(1);
1880 vpushi(0);
1881 vtop->r = REG_IRET;
1882 vtop->r2 = REG_LRET;
1883 } else {
1884 gen_cvt_ftoi(t);
1888 /* force char or short cast */
1889 static void force_charshort_cast(int t)
1891 int bits, dbt;
1892 dbt = t & VT_BTYPE;
1893 /* XXX: add optimization if lvalue : just change type and offset */
1894 if (dbt == VT_BYTE)
1895 bits = 8;
1896 else
1897 bits = 16;
1898 if (t & VT_UNSIGNED) {
1899 vpushi((1 << bits) - 1);
1900 gen_op('&');
1901 } else {
1902 bits = 32 - bits;
1903 vpushi(bits);
1904 gen_op(TOK_SHL);
1905 /* result must be signed or the SAR is converted to an SHL
1906 This was not the case when "t" was a signed short
1907 and the last value on the stack was an unsigned int */
1908 vtop->type.t &= ~VT_UNSIGNED;
1909 vpushi(bits);
1910 gen_op(TOK_SAR);
1914 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
1915 static void gen_cast(CType *type)
1917 int sbt, dbt, sf, df, c, p;
1919 /* special delayed cast for char/short */
1920 /* XXX: in some cases (multiple cascaded casts), it may still
1921 be incorrect */
1922 if (vtop->r & VT_MUSTCAST) {
1923 vtop->r &= ~VT_MUSTCAST;
1924 force_charshort_cast(vtop->type.t);
1927 /* bitfields first get cast to ints */
1928 if (vtop->type.t & VT_BITFIELD) {
1929 gv(RC_INT);
1932 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
1933 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
1935 if (sbt != dbt) {
1936 sf = is_float(sbt);
1937 df = is_float(dbt);
1938 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1939 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
1940 if (c) {
1941 /* constant case: we can do it now */
1942 /* XXX: in ISOC, cannot do it if error in convert */
1943 if (sbt == VT_FLOAT)
1944 vtop->c.ld = vtop->c.f;
1945 else if (sbt == VT_DOUBLE)
1946 vtop->c.ld = vtop->c.d;
1948 if (df) {
1949 if ((sbt & VT_BTYPE) == VT_LLONG) {
1950 if (sbt & VT_UNSIGNED)
1951 vtop->c.ld = vtop->c.ull;
1952 else
1953 vtop->c.ld = vtop->c.ll;
1954 } else if(!sf) {
1955 if (sbt & VT_UNSIGNED)
1956 vtop->c.ld = vtop->c.ui;
1957 else
1958 vtop->c.ld = vtop->c.i;
1961 if (dbt == VT_FLOAT)
1962 vtop->c.f = (float)vtop->c.ld;
1963 else if (dbt == VT_DOUBLE)
1964 vtop->c.d = (double)vtop->c.ld;
1965 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
1966 vtop->c.ull = (unsigned long long)vtop->c.ld;
1967 } else if (sf && dbt == VT_BOOL) {
1968 vtop->c.i = (vtop->c.ld != 0);
1969 } else {
1970 if(sf)
1971 vtop->c.ll = (long long)vtop->c.ld;
1972 else if (sbt == (VT_LLONG|VT_UNSIGNED))
1973 vtop->c.ll = vtop->c.ull;
1974 else if (sbt & VT_UNSIGNED)
1975 vtop->c.ll = vtop->c.ui;
1976 #ifdef TCC_TARGET_X86_64
1977 else if (sbt == VT_PTR)
1979 #endif
1980 else if (sbt != VT_LLONG)
1981 vtop->c.ll = vtop->c.i;
1983 if (dbt == (VT_LLONG|VT_UNSIGNED))
1984 vtop->c.ull = vtop->c.ll;
1985 else if (dbt == VT_BOOL)
1986 vtop->c.i = (vtop->c.ll != 0);
1987 #ifdef TCC_TARGET_X86_64
1988 else if (dbt == VT_PTR)
1990 #endif
1991 else if (dbt != VT_LLONG) {
1992 int s, dt, warr = 0;
1993 long long ll;
1994 dt = dbt & VT_BTYPE;
1995 ll = vtop->c.ll;
1996 if (dt == VT_BYTE){
1997 if((ll != (unsigned char)ll) && (ll != (char)ll))
1998 warr = 1;
1999 s = 24;
2000 }else if (dt == VT_SHORT){
2001 if((ll != (unsigned short)ll) && (ll != (short)ll))
2002 warr = 1;
2003 s = 16;
2004 }else{
2005 if((ll != (unsigned int)ll) && (ll != (int)ll))
2006 warr = 1;
2007 s = 0;
2009 if(warr && !is_force){
2010 if(dt == VT_ENUM){
2011 tcc_warning("large integer implicitly truncated to unsigned type");
2012 dbt = VT_UNSIGNED;
2013 }else
2014 tcc_warning("overflow in implicit constant conversion");
2016 if(dbt & VT_UNSIGNED)
2017 vtop->c.ui = ((unsigned int)vtop->c.ll << s) >> s;
2018 else
2019 vtop->c.i = ((int)vtop->c.ll << s) >> s;
2022 } else if (p && dbt == VT_BOOL) {
2023 vtop->r = VT_CONST;
2024 vtop->c.i = 1;
2025 } else if (!nocode_wanted) {
2026 /* non constant case: generate code */
2027 if (sf && df) {
2028 /* convert from fp to fp */
2029 gen_cvt_ftof(dbt);
2030 } else if (df) {
2031 /* convert int to fp */
2032 gen_cvt_itof1(dbt);
2033 } else if (sf) {
2034 /* convert fp to int */
2035 if (dbt == VT_BOOL) {
2036 vpushi(0);
2037 gen_op(TOK_NE);
2038 } else {
2039 /* we handle char/short/etc... with generic code */
2040 if (dbt != (VT_INT | VT_UNSIGNED) &&
2041 dbt != (VT_LLONG | VT_UNSIGNED) &&
2042 dbt != VT_LLONG)
2043 dbt = VT_INT;
2044 gen_cvt_ftoi1(dbt);
2045 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
2046 /* additional cast for char/short... */
2047 vtop->type.t = dbt;
2048 gen_cast(type);
2051 #ifndef TCC_TARGET_X86_64
2052 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
2053 if ((sbt & VT_BTYPE) != VT_LLONG) {
2054 /* scalar to long long */
2055 /* machine independent conversion */
2056 gv(RC_INT);
2057 /* generate high word */
2058 if (sbt == (VT_INT | VT_UNSIGNED)) {
2059 vpushi(0);
2060 gv(RC_INT);
2061 } else {
2062 if (sbt == VT_PTR) {
2063 /* cast from pointer to int before we apply
2064 shift operation, which pointers don't support*/
2065 gen_cast(&int_type);
2067 gv_dup();
2068 vpushi(31);
2069 gen_op(TOK_SAR);
2071 /* patch second register */
2072 vtop[-1].r2 = vtop->r;
2073 vpop();
2075 #else
2076 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
2077 (dbt & VT_BTYPE) == VT_PTR ||
2078 (dbt & VT_BTYPE) == VT_FUNC) {
2079 if ((sbt & VT_BTYPE) != VT_LLONG &&
2080 (sbt & VT_BTYPE) != VT_PTR &&
2081 (sbt & VT_BTYPE) != VT_FUNC) {
2082 /* need to convert from 32bit to 64bit */
2083 int r = gv(RC_INT);
2084 if (sbt != (VT_INT | VT_UNSIGNED)) {
2085 /* x86_64 specific: movslq */
2086 o(0x6348);
2087 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
2090 #endif
2091 } else if (dbt == VT_BOOL) {
2092 /* scalar to bool */
2093 vpushi(0);
2094 gen_op(TOK_NE);
2095 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
2096 (dbt & VT_BTYPE) == VT_SHORT) {
2097 if (sbt == VT_PTR) {
2098 vtop->type.t = VT_INT;
2099 tcc_warning("nonportable conversion from pointer to char/short");
2101 force_charshort_cast(dbt);
2102 } else if ((dbt & VT_BTYPE) == VT_INT) {
2103 /* scalar to int */
2104 if (sbt == VT_LLONG) {
2105 /* from long long: just take low order word */
2106 lexpand();
2107 vpop();
2109 /* if lvalue and single word type, nothing to do because
2110 the lvalue already contains the real type size (see
2111 VT_LVAL_xxx constants) */
2114 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
2115 /* if we are casting between pointer types,
2116 we must update the VT_LVAL_xxx size */
2117 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
2118 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
2120 vtop->type = *type;
2123 /* return type size as known at compile time. Put alignment at 'a' */
2124 ST_FUNC int type_size(CType *type, int *a)
2126 Sym *s;
2127 int bt;
2129 bt = type->t & VT_BTYPE;
2130 if (bt == VT_STRUCT) {
2131 /* struct/union */
2132 s = type->ref;
2133 *a = s->r;
2134 return s->c;
2135 } else if (bt == VT_PTR) {
2136 if (type->t & VT_ARRAY) {
2137 int ts;
2139 s = type->ref;
2140 ts = type_size(&s->type, a);
2142 if (ts < 0 && s->c < 0)
2143 ts = -ts;
2145 return ts * s->c;
2146 } else {
2147 *a = PTR_SIZE;
2148 return PTR_SIZE;
2150 } else if (bt == VT_LDOUBLE) {
2151 *a = LDOUBLE_ALIGN;
2152 return LDOUBLE_SIZE;
2153 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
2154 #ifdef TCC_TARGET_I386
2155 #ifdef TCC_TARGET_PE
2156 *a = 8;
2157 #else
2158 *a = 4;
2159 #endif
2160 #elif defined(TCC_TARGET_ARM)
2161 #ifdef TCC_ARM_EABI
2162 *a = 8;
2163 #else
2164 *a = 4;
2165 #endif
2166 #else
2167 *a = 8;
2168 #endif
2169 return 8;
2170 } else if (bt == VT_INT || bt == VT_ENUM || bt == VT_FLOAT) {
2171 *a = 4;
2172 return 4;
2173 } else if (bt == VT_SHORT) {
2174 *a = 2;
2175 return 2;
2176 } else if (bt == VT_QLONG || bt == VT_QFLOAT) {
2177 *a = 8;
2178 return 16;
2179 } else {
2180 /* char, void, function, _Bool */
2181 *a = 1;
2182 return 1;
2186 /* push type size as known at runtime time on top of value stack. Put
2187 alignment at 'a' */
2188 ST_FUNC void vla_runtime_type_size(CType *type, int *a)
2190 if (type->t & VT_VLA) {
2191 vset(&int_type, VT_LOCAL|VT_LVAL, type->ref->c);
2192 } else {
2193 vpushi(type_size(type, a));
2197 static void vla_sp_save(void) {
2198 if (!(vla_flags & VLA_SP_LOC_SET)) {
2199 *vla_sp_loc = (loc -= PTR_SIZE);
2200 vla_flags |= VLA_SP_LOC_SET;
2202 if (!(vla_flags & VLA_SP_SAVED)) {
2203 gen_vla_sp_save(*vla_sp_loc);
2204 vla_flags |= VLA_SP_SAVED;
2208 /* return the pointed type of t */
2209 static inline CType *pointed_type(CType *type)
2211 return &type->ref->type;
2214 /* modify type so that its it is a pointer to type. */
2215 ST_FUNC void mk_pointer(CType *type)
2217 Sym *s;
2218 s = sym_push(SYM_FIELD, type, 0, -1);
2219 type->t = VT_PTR | (type->t & ~VT_TYPE);
2220 type->ref = s;
2223 /* compare function types. OLD functions match any new functions */
2224 static int is_compatible_func(CType *type1, CType *type2)
2226 Sym *s1, *s2;
2228 s1 = type1->ref;
2229 s2 = type2->ref;
2230 if (!is_compatible_types(&s1->type, &s2->type))
2231 return 0;
2232 /* check func_call */
2233 if (s1->a.func_call != s2->a.func_call)
2234 return 0;
2235 /* XXX: not complete */
2236 if (s1->c == FUNC_OLD || s2->c == FUNC_OLD)
2237 return 1;
2238 if (s1->c != s2->c)
2239 return 0;
2240 while (s1 != NULL) {
2241 if (s2 == NULL)
2242 return 0;
2243 if (!is_compatible_parameter_types(&s1->type, &s2->type))
2244 return 0;
2245 s1 = s1->next;
2246 s2 = s2->next;
2248 if (s2)
2249 return 0;
2250 return 1;
2253 /* return true if type1 and type2 are the same. If unqualified is
2254 true, qualifiers on the types are ignored.
2256 - enums are not checked as gcc __builtin_types_compatible_p ()
2258 static int compare_types(CType *type1, CType *type2, int unqualified)
2260 int bt1, t1, t2;
2262 t1 = type1->t & VT_TYPE;
2263 t2 = type2->t & VT_TYPE;
2264 if (unqualified) {
2265 /* strip qualifiers before comparing */
2266 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
2267 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
2269 /* Default Vs explicit signedness only matters for char */
2270 if ((t1 & VT_BTYPE) != VT_BYTE) {
2271 t1 &= ~VT_DEFSIGN;
2272 t2 &= ~VT_DEFSIGN;
2274 /* XXX: bitfields ? */
2275 if (t1 != t2)
2276 return 0;
2277 /* test more complicated cases */
2278 bt1 = t1 & VT_BTYPE;
2279 if (bt1 == VT_PTR) {
2280 type1 = pointed_type(type1);
2281 type2 = pointed_type(type2);
2282 return is_compatible_types(type1, type2);
2283 } else if (bt1 == VT_STRUCT) {
2284 return (type1->ref == type2->ref);
2285 } else if (bt1 == VT_FUNC) {
2286 return is_compatible_func(type1, type2);
2287 } else {
2288 return 1;
2292 /* return true if type1 and type2 are exactly the same (including
2293 qualifiers).
2295 static int is_compatible_types(CType *type1, CType *type2)
2297 return compare_types(type1,type2,0);
2300 /* return true if type1 and type2 are the same (ignoring qualifiers).
2302 static int is_compatible_parameter_types(CType *type1, CType *type2)
2304 return compare_types(type1,type2,1);
2307 /* print a type. If 'varstr' is not NULL, then the variable is also
2308 printed in the type */
2309 /* XXX: union */
2310 /* XXX: add array and function pointers */
2311 static void type_to_str(char *buf, int buf_size,
2312 CType *type, const char *varstr)
2314 int bt, v, t;
2315 Sym *s, *sa;
2316 char buf1[256];
2317 const char *tstr;
2319 t = type->t & VT_TYPE;
2320 bt = t & VT_BTYPE;
2321 buf[0] = '\0';
2322 if (t & VT_CONSTANT)
2323 pstrcat(buf, buf_size, "const ");
2324 if (t & VT_VOLATILE)
2325 pstrcat(buf, buf_size, "volatile ");
2326 if ((t & (VT_DEFSIGN | VT_UNSIGNED)) == (VT_DEFSIGN | VT_UNSIGNED))
2327 pstrcat(buf, buf_size, "unsigned ");
2328 else if (t & VT_DEFSIGN)
2329 pstrcat(buf, buf_size, "signed ");
2330 switch(bt) {
2331 case VT_VOID:
2332 tstr = "void";
2333 goto add_tstr;
2334 case VT_BOOL:
2335 tstr = "_Bool";
2336 goto add_tstr;
2337 case VT_BYTE:
2338 tstr = "char";
2339 goto add_tstr;
2340 case VT_SHORT:
2341 tstr = "short";
2342 goto add_tstr;
2343 case VT_INT:
2344 tstr = "int";
2345 goto add_tstr;
2346 case VT_LONG:
2347 tstr = "long";
2348 goto add_tstr;
2349 case VT_LLONG:
2350 tstr = "long long";
2351 goto add_tstr;
2352 case VT_FLOAT:
2353 tstr = "float";
2354 goto add_tstr;
2355 case VT_DOUBLE:
2356 tstr = "double";
2357 goto add_tstr;
2358 case VT_LDOUBLE:
2359 tstr = "long double";
2360 add_tstr:
2361 pstrcat(buf, buf_size, tstr);
2362 break;
2363 case VT_ENUM:
2364 case VT_STRUCT:
2365 if (bt == VT_STRUCT)
2366 tstr = "struct ";
2367 else
2368 tstr = "enum ";
2369 pstrcat(buf, buf_size, tstr);
2370 v = type->ref->v & ~SYM_STRUCT;
2371 if (v >= SYM_FIRST_ANOM)
2372 pstrcat(buf, buf_size, "<anonymous>");
2373 else
2374 pstrcat(buf, buf_size, get_tok_str(v, NULL));
2375 break;
2376 case VT_FUNC:
2377 s = type->ref;
2378 type_to_str(buf, buf_size, &s->type, varstr);
2379 pstrcat(buf, buf_size, "(");
2380 sa = s->next;
2381 while (sa != NULL) {
2382 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
2383 pstrcat(buf, buf_size, buf1);
2384 sa = sa->next;
2385 if (sa)
2386 pstrcat(buf, buf_size, ", ");
2388 pstrcat(buf, buf_size, ")");
2389 goto no_var;
2390 case VT_PTR:
2391 s = type->ref;
2392 pstrcpy(buf1, sizeof(buf1), "*");
2393 if (varstr)
2394 pstrcat(buf1, sizeof(buf1), varstr);
2395 type_to_str(buf, buf_size, &s->type, buf1);
2396 goto no_var;
2398 if (varstr) {
2399 pstrcat(buf, buf_size, " ");
2400 pstrcat(buf, buf_size, varstr);
2402 no_var: ;
2405 /* verify type compatibility to store vtop in 'dt' type, and generate
2406 casts if needed. */
2407 static void gen_assign_cast(CType *dt)
2409 CType *st, *type1, *type2, tmp_type1, tmp_type2;
2410 char buf1[256], buf2[256];
2411 int dbt, sbt;
2413 st = &vtop->type; /* source type */
2414 dbt = dt->t & VT_BTYPE;
2415 sbt = st->t & VT_BTYPE;
2416 if (sbt == VT_VOID || dbt == VT_VOID)
2417 tcc_error("cannot cast from/to void");
2418 if (dt->t & VT_CONSTANT)
2419 tcc_warning("assignment of read-only location");
2420 switch(dbt) {
2421 case VT_PTR:
2422 /* special cases for pointers */
2423 /* '0' can also be a pointer */
2424 if (is_null_pointer(vtop))
2425 goto type_ok;
2426 /* accept implicit pointer to integer cast with warning */
2427 if (is_integer_btype(sbt)) {
2428 tcc_warning("assignment makes pointer from integer without a cast");
2429 goto type_ok;
2431 type1 = pointed_type(dt);
2432 /* a function is implicitely a function pointer */
2433 if (sbt == VT_FUNC) {
2434 if ((type1->t & VT_BTYPE) != VT_VOID &&
2435 !is_compatible_types(pointed_type(dt), st))
2436 tcc_warning("assignment from incompatible pointer type");
2437 goto type_ok;
2439 if (sbt != VT_PTR)
2440 goto error;
2441 type2 = pointed_type(st);
2442 if ((type1->t & VT_BTYPE) == VT_VOID ||
2443 (type2->t & VT_BTYPE) == VT_VOID) {
2444 /* void * can match anything */
2445 } else {
2446 /* exact type match, except for unsigned */
2447 tmp_type1 = *type1;
2448 tmp_type2 = *type2;
2449 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT |
2450 VT_VOLATILE);
2451 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT |
2452 VT_VOLATILE);
2453 if (!is_compatible_types(&tmp_type1, &tmp_type2))
2454 tcc_warning("assignment from incompatible pointer type");
2456 /* check const and volatile */
2457 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
2458 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
2459 tcc_warning("assignment discards qualifiers from pointer target type");
2460 break;
2461 case VT_BYTE:
2462 case VT_SHORT:
2463 case VT_INT:
2464 case VT_LLONG:
2465 if (sbt == VT_PTR || sbt == VT_FUNC) {
2466 tcc_warning("assignment makes integer from pointer without a cast");
2468 if (sbt == VT_STRUCT)
2469 goto error;
2470 /* XXX: more tests */
2471 break;
2472 case VT_STRUCT:
2473 tmp_type1 = *dt;
2474 tmp_type2 = *st;
2475 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2476 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2477 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2478 error:
2479 type_to_str(buf1, sizeof(buf1), st, NULL);
2480 type_to_str(buf2, sizeof(buf2), dt, NULL);
2481 tcc_error("cannot cast '%s' to '%s'", buf1, buf2);
2483 break;
2485 type_ok:
2486 gen_cast(dt);
2489 /* store vtop in lvalue pushed on stack */
2490 ST_FUNC void vstore(void)
2492 int sbt, dbt, ft, cc, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
2494 ft = vtop[-1].type.t;
2495 sbt = vtop->type.t & VT_BTYPE;
2496 dbt = ft & VT_BTYPE;
2497 cc = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
2498 if ((((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
2499 (sbt == VT_INT && dbt == VT_SHORT))
2500 && !(vtop->type.t & VT_BITFIELD) && !cc) {
2501 /* optimize char/short casts */
2502 delayed_cast = VT_MUSTCAST;
2503 vtop->type.t = ft & (VT_TYPE & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT)));
2504 /* XXX: factorize */
2505 if (ft & VT_CONSTANT)
2506 tcc_warning("assignment of read-only location");
2507 } else {
2508 delayed_cast = 0;
2509 if (!(ft & VT_BITFIELD))
2510 gen_assign_cast(&vtop[-1].type);
2513 if (sbt == VT_STRUCT) {
2514 /* if structure, only generate pointer */
2515 /* structure assignment : generate memcpy */
2516 /* XXX: optimize if small size */
2517 if (!nocode_wanted) {
2518 size = type_size(&vtop->type, &align);
2520 /* destination */
2521 vswap();
2522 vtop->type.t = VT_PTR;
2523 gaddrof();
2525 /* address of memcpy() */
2526 #ifdef TCC_ARM_EABI
2527 if(!(align & 7))
2528 vpush_global_sym(&func_old_type, TOK_memcpy8);
2529 else if(!(align & 3))
2530 vpush_global_sym(&func_old_type, TOK_memcpy4);
2531 else
2532 #endif
2533 vpush_global_sym(&func_old_type, TOK_memcpy);
2535 vswap();
2536 /* source */
2537 vpushv(vtop - 2);
2538 vtop->type.t = VT_PTR;
2539 gaddrof();
2540 /* type size */
2541 vpushi(size);
2542 gfunc_call(3);
2543 } else {
2544 vswap();
2545 vpop();
2547 /* leave source on stack */
2548 } else if (ft & VT_BITFIELD) {
2549 /* bitfield store handling */
2550 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
2551 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
2552 /* remove bit field info to avoid loops */
2553 vtop[-1].type.t = ft & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
2555 /* duplicate source into other register */
2556 gv_dup();
2557 vswap();
2558 vrott(3);
2560 if((ft & VT_BTYPE) == VT_BOOL) {
2561 gen_cast(&vtop[-1].type);
2562 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
2565 /* duplicate destination */
2566 vdup();
2567 vtop[-1] = vtop[-2];
2569 /* mask and shift source */
2570 if((ft & VT_BTYPE) != VT_BOOL) {
2571 if((ft & VT_BTYPE) == VT_LLONG) {
2572 vpushll((1ULL << bit_size) - 1ULL);
2573 } else {
2574 vpushi((1 << bit_size) - 1);
2576 gen_op('&');
2578 vpushi(bit_pos);
2579 gen_op(TOK_SHL);
2580 /* load destination, mask and or with source */
2581 vswap();
2582 if((ft & VT_BTYPE) == VT_LLONG) {
2583 vpushll(~(((1ULL << bit_size) - 1ULL) << bit_pos));
2584 } else {
2585 vpushi(~(((1 << bit_size) - 1) << bit_pos));
2587 gen_op('&');
2588 gen_op('|');
2589 /* store result */
2590 vstore();
2592 /* pop off shifted source from "duplicate source..." above */
2593 vpop();
2594 } else {
2595 #ifdef CONFIG_TCC_BCHECK
2596 /* bound check case */
2597 if (vtop[-1].r & VT_MUSTBOUND) {
2598 vswap();
2599 gbound();
2600 vswap();
2602 #endif
2603 if (!nocode_wanted) {
2604 rc = RC_INT;
2605 if (is_float(ft)) {
2606 rc = RC_FLOAT;
2607 #ifdef TCC_TARGET_X86_64
2608 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
2609 rc = RC_ST0;
2610 } else if ((ft & VT_BTYPE) == VT_QFLOAT) {
2611 rc = RC_FRET;
2613 #endif
2615 r = gv(rc); /* generate value */
2616 /* if lvalue was saved on stack, must read it */
2617 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
2618 SValue sv;
2619 t = get_reg(RC_INT);
2620 #ifdef TCC_TARGET_X86_64
2621 sv.type.t = VT_PTR;
2622 #else
2623 sv.type.t = VT_INT;
2624 #endif
2625 sv.r = VT_LOCAL | VT_LVAL;
2626 sv.c.ul = vtop[-1].c.ul;
2627 load(t, &sv);
2628 vtop[-1].r = t | VT_LVAL;
2630 /* two word case handling : store second register at word + 4 (or +8 for x86-64) */
2631 #ifdef TCC_TARGET_X86_64
2632 if (((ft & VT_BTYPE) == VT_QLONG) || ((ft & VT_BTYPE) == VT_QFLOAT)) {
2633 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
2634 #else
2635 if ((ft & VT_BTYPE) == VT_LLONG) {
2636 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
2637 #endif
2638 vtop[-1].type.t = load_type;
2639 store(r, vtop - 1);
2640 vswap();
2641 /* convert to int to increment easily */
2642 vtop->type.t = addr_type;
2643 gaddrof();
2644 vpushi(load_size);
2645 gen_op('+');
2646 vtop->r |= VT_LVAL;
2647 vswap();
2648 vtop[-1].type.t = load_type;
2649 /* XXX: it works because r2 is spilled last ! */
2650 store(vtop->r2, vtop - 1);
2651 } else {
2652 store(r, vtop - 1);
2655 vswap();
2656 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
2657 vtop->r |= delayed_cast;
2661 /* post defines POST/PRE add. c is the token ++ or -- */
2662 ST_FUNC void inc(int post, int c)
2664 test_lvalue();
2665 vdup(); /* save lvalue */
2666 if (post) {
2667 gv_dup(); /* duplicate value */
2668 vrotb(3);
2669 vrotb(3);
2671 /* add constant */
2672 vpushi(c - TOK_MID);
2673 gen_op('+');
2674 vstore(); /* store value */
2675 if (post)
2676 vpop(); /* if post op, return saved value */
2679 /* Parse GNUC __attribute__ extension. Currently, the following
2680 extensions are recognized:
2681 - aligned(n) : set data/function alignment.
2682 - packed : force data alignment to 1
2683 - section(x) : generate data/code in this section.
2684 - unused : currently ignored, but may be used someday.
2685 - regparm(n) : pass function parameters in registers (i386 only)
2687 static void parse_attribute(AttributeDef *ad)
2689 int t, n;
2691 while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
2692 next();
2693 skip('(');
2694 skip('(');
2695 while (tok != ')') {
2696 if (tok < TOK_IDENT)
2697 expect("attribute name");
2698 t = tok;
2699 next();
2700 switch(t) {
2701 case TOK_SECTION1:
2702 case TOK_SECTION2:
2703 skip('(');
2704 if (tok != TOK_STR)
2705 expect("section name");
2706 ad->section = find_section(tcc_state, (char *)tokc.cstr->data);
2707 next();
2708 skip(')');
2709 break;
2710 case TOK_ALIAS1:
2711 case TOK_ALIAS2:
2712 skip('(');
2713 if (tok != TOK_STR)
2714 expect("alias(\"target\")");
2715 ad->alias_target = /* save string as token, for later */
2716 tok_alloc((char*)tokc.cstr->data, tokc.cstr->size-1)->tok;
2717 next();
2718 skip(')');
2719 break;
2720 case TOK_VISIBILITY1:
2721 case TOK_VISIBILITY2:
2722 skip('(');
2723 if (tok != TOK_STR)
2724 expect("visibility(\"default|hidden|internal|protected\")");
2725 if (!strcmp (tokc.cstr->data, "default"))
2726 ad->a.visibility = STV_DEFAULT;
2727 else if (!strcmp (tokc.cstr->data, "hidden"))
2728 ad->a.visibility = STV_HIDDEN;
2729 else if (!strcmp (tokc.cstr->data, "internal"))
2730 ad->a.visibility = STV_INTERNAL;
2731 else if (!strcmp (tokc.cstr->data, "protected"))
2732 ad->a.visibility = STV_PROTECTED;
2733 else
2734 expect("visibility(\"default|hidden|internal|protected\")");
2735 next();
2736 skip(')');
2737 break;
2738 case TOK_ALIGNED1:
2739 case TOK_ALIGNED2:
2740 if (tok == '(') {
2741 next();
2742 n = expr_const();
2743 if (n <= 0 || (n & (n - 1)) != 0)
2744 tcc_error("alignment must be a positive power of two");
2745 skip(')');
2746 } else {
2747 n = MAX_ALIGN;
2749 ad->a.aligned = n;
2750 break;
2751 case TOK_PACKED1:
2752 case TOK_PACKED2:
2753 ad->a.packed = 1;
2754 break;
2755 case TOK_WEAK1:
2756 case TOK_WEAK2:
2757 ad->a.weak = 1;
2758 break;
2759 case TOK_UNUSED1:
2760 case TOK_UNUSED2:
2761 /* currently, no need to handle it because tcc does not
2762 track unused objects */
2763 break;
2764 case TOK_NORETURN1:
2765 case TOK_NORETURN2:
2766 /* currently, no need to handle it because tcc does not
2767 track unused objects */
2768 break;
2769 case TOK_CDECL1:
2770 case TOK_CDECL2:
2771 case TOK_CDECL3:
2772 ad->a.func_call = FUNC_CDECL;
2773 break;
2774 case TOK_STDCALL1:
2775 case TOK_STDCALL2:
2776 case TOK_STDCALL3:
2777 ad->a.func_call = FUNC_STDCALL;
2778 break;
2779 #ifdef TCC_TARGET_I386
2780 case TOK_REGPARM1:
2781 case TOK_REGPARM2:
2782 skip('(');
2783 n = expr_const();
2784 if (n > 3)
2785 n = 3;
2786 else if (n < 0)
2787 n = 0;
2788 if (n > 0)
2789 ad->a.func_call = FUNC_FASTCALL1 + n - 1;
2790 skip(')');
2791 break;
2792 case TOK_FASTCALL1:
2793 case TOK_FASTCALL2:
2794 case TOK_FASTCALL3:
2795 ad->a.func_call = FUNC_FASTCALLW;
2796 break;
2797 #endif
2798 case TOK_MODE:
2799 skip('(');
2800 switch(tok) {
2801 case TOK_MODE_DI:
2802 ad->a.mode = VT_LLONG + 1;
2803 break;
2804 case TOK_MODE_HI:
2805 ad->a.mode = VT_SHORT + 1;
2806 break;
2807 case TOK_MODE_SI:
2808 ad->a.mode = VT_INT + 1;
2809 break;
2810 default:
2811 tcc_warning("__mode__(%s) not supported\n", get_tok_str(tok, NULL));
2812 break;
2814 next();
2815 skip(')');
2816 break;
2817 case TOK_DLLEXPORT:
2818 ad->a.func_export = 1;
2819 break;
2820 case TOK_DLLIMPORT:
2821 ad->a.func_import = 1;
2822 break;
2823 default:
2824 if (tcc_state->warn_unsupported)
2825 tcc_warning("'%s' attribute ignored", get_tok_str(t, NULL));
2826 /* skip parameters */
2827 if (tok == '(') {
2828 int parenthesis = 0;
2829 do {
2830 if (tok == '(')
2831 parenthesis++;
2832 else if (tok == ')')
2833 parenthesis--;
2834 next();
2835 } while (parenthesis && tok != -1);
2837 break;
2839 if (tok != ',')
2840 break;
2841 next();
2843 skip(')');
2844 skip(')');
2848 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
2849 static void struct_decl(CType *type, int u, int tdef)
2851 int a, v, size, align, maxalign, c, offset, flexible;
2852 int bit_size, bit_pos, bsize, bt, lbit_pos, prevbt;
2853 Sym *s, *ss, *ass, **ps;
2854 AttributeDef ad;
2855 CType type1, btype;
2857 a = tok; /* save decl type */
2858 next();
2859 if (tok != '{') {
2860 v = tok;
2861 next();
2862 /* struct already defined ? return it */
2863 if (v < TOK_IDENT)
2864 expect("struct/union/enum name");
2865 s = struct_find(v);
2866 if (s) {
2867 if (s->type.t != a)
2868 tcc_error("invalid type: '%s'", get_tok_str(v, NULL));
2869 goto do_decl;
2870 } else if (tok >= TOK_IDENT && !tdef)
2871 tcc_error("unknown struct/union/enum");
2872 } else {
2873 v = anon_sym++;
2875 type1.t = a;
2876 type1.ref = NULL;
2877 /* we put an undefined size for struct/union */
2878 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
2879 s->r = 0; /* default alignment is zero as gcc */
2880 /* put struct/union/enum name in type */
2881 do_decl:
2882 type->t = u;
2883 type->ref = s;
2885 if (tok == '{') {
2886 next();
2887 if (s->c != -1)
2888 tcc_error("struct/union/enum already defined");
2889 /* cannot be empty */
2890 c = 0;
2891 /* non empty enums are not allowed */
2892 if (a == TOK_ENUM) {
2893 for(;;) {
2894 v = tok;
2895 if (v < TOK_UIDENT)
2896 expect("identifier");
2897 ss = sym_find(v);
2898 if (ss && !local_stack)
2899 tcc_error("redefinition of enumerator '%s'",
2900 get_tok_str(v, NULL));
2901 next();
2902 if (tok == '=') {
2903 next();
2904 c = expr_const();
2906 /* enum symbols have static storage */
2907 ss = sym_push(v, &int_type, VT_CONST, c);
2908 ss->type.t |= VT_STATIC;
2909 if (tok != ',')
2910 break;
2911 next();
2912 c++;
2913 /* NOTE: we accept a trailing comma */
2914 if (tok == '}')
2915 break;
2917 s->c = type_size(&int_type, &align);
2918 skip('}');
2919 } else {
2920 maxalign = 1;
2921 ps = &s->next;
2922 prevbt = VT_INT;
2923 bit_pos = 0;
2924 offset = 0;
2925 flexible = 0;
2926 while (tok != '}') {
2927 parse_btype(&btype, &ad);
2928 while (1) {
2929 if (flexible)
2930 tcc_error("flexible array member '%s' not at the end of struct",
2931 get_tok_str(v, NULL));
2932 bit_size = -1;
2933 v = 0;
2934 type1 = btype;
2935 if (tok != ':') {
2936 type_decl(&type1, &ad, &v, TYPE_DIRECT | TYPE_ABSTRACT);
2937 if (v == 0 && (type1.t & VT_BTYPE) != VT_STRUCT)
2938 expect("identifier");
2939 if (type_size(&type1, &align) < 0) {
2940 if ((a == TOK_STRUCT) && (type1.t & VT_ARRAY))
2941 flexible = 1;
2942 else
2943 tcc_error("field '%s' has incomplete type",
2944 get_tok_str(v, NULL));
2946 if ((type1.t & VT_BTYPE) == VT_FUNC ||
2947 (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
2948 tcc_error("invalid type for '%s'",
2949 get_tok_str(v, NULL));
2951 if (tok == ':') {
2952 next();
2953 bit_size = expr_const();
2954 /* XXX: handle v = 0 case for messages */
2955 if (bit_size < 0)
2956 tcc_error("negative width in bit-field '%s'",
2957 get_tok_str(v, NULL));
2958 if (v && bit_size == 0)
2959 tcc_error("zero width for bit-field '%s'",
2960 get_tok_str(v, NULL));
2962 size = type_size(&type1, &align);
2963 if (ad.a.aligned) {
2964 if (align < ad.a.aligned)
2965 align = ad.a.aligned;
2966 } else if (ad.a.packed) {
2967 align = 1;
2968 } else if (*tcc_state->pack_stack_ptr) {
2969 if (align > *tcc_state->pack_stack_ptr)
2970 align = *tcc_state->pack_stack_ptr;
2972 lbit_pos = 0;
2973 if (bit_size >= 0) {
2974 bt = type1.t & VT_BTYPE;
2975 if (bt != VT_INT &&
2976 bt != VT_BYTE &&
2977 bt != VT_SHORT &&
2978 bt != VT_BOOL &&
2979 bt != VT_ENUM &&
2980 bt != VT_LLONG)
2981 tcc_error("bitfields must have scalar type");
2982 bsize = size * 8;
2983 if (bit_size > bsize) {
2984 tcc_error("width of '%s' exceeds its type",
2985 get_tok_str(v, NULL));
2986 } else if (bit_size == bsize) {
2987 /* no need for bit fields */
2988 bit_pos = 0;
2989 } else if (bit_size == 0) {
2990 /* XXX: what to do if only padding in a
2991 structure ? */
2992 /* zero size: means to pad */
2993 bit_pos = 0;
2994 } else {
2995 /* we do not have enough room ?
2996 did the type change?
2997 is it a union? */
2998 if ((bit_pos + bit_size) > bsize ||
2999 bt != prevbt || a == TOK_UNION)
3000 bit_pos = 0;
3001 lbit_pos = bit_pos;
3002 /* XXX: handle LSB first */
3003 type1.t |= VT_BITFIELD |
3004 (bit_pos << VT_STRUCT_SHIFT) |
3005 (bit_size << (VT_STRUCT_SHIFT + 6));
3006 bit_pos += bit_size;
3008 prevbt = bt;
3009 } else {
3010 bit_pos = 0;
3012 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
3013 /* add new memory data only if starting
3014 bit field */
3015 if (lbit_pos == 0) {
3016 if (a == TOK_STRUCT) {
3017 c = (c + align - 1) & -align;
3018 offset = c;
3019 if (size > 0)
3020 c += size;
3021 } else {
3022 offset = 0;
3023 if (size > c)
3024 c = size;
3026 if (align > maxalign)
3027 maxalign = align;
3029 #if 0
3030 printf("add field %s offset=%d",
3031 get_tok_str(v, NULL), offset);
3032 if (type1.t & VT_BITFIELD) {
3033 printf(" pos=%d size=%d",
3034 (type1.t >> VT_STRUCT_SHIFT) & 0x3f,
3035 (type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
3037 printf("\n");
3038 #endif
3040 if (v == 0 && (type1.t & VT_BTYPE) == VT_STRUCT) {
3041 ass = type1.ref;
3042 while ((ass = ass->next) != NULL) {
3043 ss = sym_push(ass->v, &ass->type, 0, offset + ass->c);
3044 *ps = ss;
3045 ps = &ss->next;
3047 } else if (v) {
3048 ss = sym_push(v | SYM_FIELD, &type1, 0, offset);
3049 *ps = ss;
3050 ps = &ss->next;
3052 if (tok == ';' || tok == TOK_EOF)
3053 break;
3054 skip(',');
3056 skip(';');
3058 skip('}');
3059 if (!c && flexible)
3060 tcc_error("flexible array member '%s' in otherwise empty struct", get_tok_str(v, NULL));
3061 /* store size and alignment */
3062 s->c = (c + maxalign - 1) & -maxalign;
3063 s->r = maxalign;
3068 /* return 1 if basic type is a type size (short, long, long long) */
3069 ST_FUNC int is_btype_size(int bt)
3071 return bt == VT_SHORT || bt == VT_LONG || bt == VT_LLONG;
3074 /* return 0 if no type declaration. otherwise, return the basic type
3075 and skip it.
3077 static int parse_btype(CType *type, AttributeDef *ad)
3079 int t, u, bt_size, complete, type_found, typespec_found;
3080 Sym *s;
3081 CType type1;
3083 memset(ad, 0, sizeof(AttributeDef));
3084 complete = 0;
3085 type_found = 0;
3086 typespec_found = 0;
3087 t = 0;
3088 while(1) {
3089 switch(tok) {
3090 case TOK_EXTENSION:
3091 /* currently, we really ignore extension */
3092 next();
3093 continue;
3095 /* basic types */
3096 case TOK_CHAR:
3097 u = VT_BYTE;
3098 basic_type:
3099 next();
3100 basic_type1:
3101 if (complete)
3102 tcc_error("too many basic types");
3103 t |= u;
3104 bt_size = is_btype_size (u & VT_BTYPE);
3105 if (u == VT_INT || (!bt_size && !(t & VT_TYPEDEF)))
3106 complete = 1;
3107 typespec_found = 1;
3108 break;
3109 case TOK_VOID:
3110 u = VT_VOID;
3111 goto basic_type;
3112 case TOK_SHORT:
3113 u = VT_SHORT;
3114 goto basic_type;
3115 case TOK_INT:
3116 u = VT_INT;
3117 goto basic_type;
3118 case TOK_LONG:
3119 next();
3120 if ((t & VT_BTYPE) == VT_DOUBLE) {
3121 #ifndef TCC_TARGET_PE
3122 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3123 #endif
3124 } else if ((t & VT_BTYPE) == VT_LONG) {
3125 t = (t & ~VT_BTYPE) | VT_LLONG;
3126 } else {
3127 u = VT_LONG;
3128 goto basic_type1;
3130 break;
3131 case TOK_BOOL:
3132 u = VT_BOOL;
3133 goto basic_type;
3134 case TOK_FLOAT:
3135 u = VT_FLOAT;
3136 goto basic_type;
3137 case TOK_DOUBLE:
3138 next();
3139 if ((t & VT_BTYPE) == VT_LONG) {
3140 #ifdef TCC_TARGET_PE
3141 t = (t & ~VT_BTYPE) | VT_DOUBLE;
3142 #else
3143 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3144 #endif
3145 } else {
3146 u = VT_DOUBLE;
3147 goto basic_type1;
3149 break;
3150 case TOK_ENUM:
3151 struct_decl(&type1, VT_ENUM, t & VT_TYPEDEF);
3152 basic_type2:
3153 u = type1.t;
3154 type->ref = type1.ref;
3155 goto basic_type1;
3156 case TOK_STRUCT:
3157 case TOK_UNION:
3158 struct_decl(&type1, VT_STRUCT, t & VT_TYPEDEF);
3159 goto basic_type2;
3161 /* type modifiers */
3162 case TOK_CONST1:
3163 case TOK_CONST2:
3164 case TOK_CONST3:
3165 t |= VT_CONSTANT;
3166 next();
3167 break;
3168 case TOK_VOLATILE1:
3169 case TOK_VOLATILE2:
3170 case TOK_VOLATILE3:
3171 t |= VT_VOLATILE;
3172 next();
3173 break;
3174 case TOK_SIGNED1:
3175 case TOK_SIGNED2:
3176 case TOK_SIGNED3:
3177 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == (VT_DEFSIGN|VT_UNSIGNED))
3178 tcc_error("signed and unsigned modifier");
3179 typespec_found = 1;
3180 t |= VT_DEFSIGN;
3181 next();
3182 break;
3183 case TOK_REGISTER:
3184 case TOK_AUTO:
3185 case TOK_RESTRICT1:
3186 case TOK_RESTRICT2:
3187 case TOK_RESTRICT3:
3188 next();
3189 break;
3190 case TOK_UNSIGNED:
3191 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == VT_DEFSIGN)
3192 tcc_error("signed and unsigned modifier");
3193 t |= VT_DEFSIGN | VT_UNSIGNED;
3194 next();
3195 typespec_found = 1;
3196 break;
3198 /* storage */
3199 case TOK_EXTERN:
3200 t |= VT_EXTERN;
3201 next();
3202 break;
3203 case TOK_STATIC:
3204 t |= VT_STATIC;
3205 next();
3206 break;
3207 case TOK_TYPEDEF:
3208 t |= VT_TYPEDEF;
3209 next();
3210 break;
3211 case TOK_INLINE1:
3212 case TOK_INLINE2:
3213 case TOK_INLINE3:
3214 t |= VT_INLINE;
3215 next();
3216 break;
3218 /* GNUC attribute */
3219 case TOK_ATTRIBUTE1:
3220 case TOK_ATTRIBUTE2:
3221 parse_attribute(ad);
3222 if (ad->a.mode) {
3223 u = ad->a.mode -1;
3224 t = (t & ~VT_BTYPE) | u;
3226 break;
3227 /* GNUC typeof */
3228 case TOK_TYPEOF1:
3229 case TOK_TYPEOF2:
3230 case TOK_TYPEOF3:
3231 next();
3232 parse_expr_type(&type1);
3233 /* remove all storage modifiers except typedef */
3234 type1.t &= ~(VT_STORAGE&~VT_TYPEDEF);
3235 goto basic_type2;
3236 default:
3237 if (typespec_found)
3238 goto the_end;
3239 s = sym_find(tok);
3240 if (!s || !(s->type.t & VT_TYPEDEF))
3241 goto the_end;
3242 t |= (s->type.t & ~VT_TYPEDEF);
3243 type->ref = s->type.ref;
3244 if (s->r) {
3245 /* get attributes from typedef */
3246 if (0 == ad->a.aligned)
3247 ad->a.aligned = s->a.aligned;
3248 if (0 == ad->a.func_call)
3249 ad->a.func_call = s->a.func_call;
3250 ad->a.packed |= s->a.packed;
3252 next();
3253 typespec_found = 1;
3254 break;
3256 type_found = 1;
3258 the_end:
3259 if (tcc_state->char_is_unsigned) {
3260 if ((t & (VT_DEFSIGN|VT_BTYPE)) == VT_BYTE)
3261 t |= VT_UNSIGNED;
3264 /* long is never used as type */
3265 if ((t & VT_BTYPE) == VT_LONG)
3266 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
3267 t = (t & ~VT_BTYPE) | VT_INT;
3268 #else
3269 t = (t & ~VT_BTYPE) | VT_LLONG;
3270 #endif
3271 type->t = t;
3272 return type_found;
3275 /* convert a function parameter type (array to pointer and function to
3276 function pointer) */
3277 static inline void convert_parameter_type(CType *pt)
3279 /* remove const and volatile qualifiers (XXX: const could be used
3280 to indicate a const function parameter */
3281 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
3282 /* array must be transformed to pointer according to ANSI C */
3283 pt->t &= ~VT_ARRAY;
3284 if ((pt->t & VT_BTYPE) == VT_FUNC) {
3285 mk_pointer(pt);
3289 ST_FUNC void parse_asm_str(CString *astr)
3291 skip('(');
3292 /* read the string */
3293 if (tok != TOK_STR)
3294 expect("string constant");
3295 cstr_new(astr);
3296 while (tok == TOK_STR) {
3297 /* XXX: add \0 handling too ? */
3298 cstr_cat(astr, tokc.cstr->data);
3299 next();
3301 cstr_ccat(astr, '\0');
3304 /* Parse an asm label and return the label
3305 * Don't forget to free the CString in the caller! */
3306 static void asm_label_instr(CString *astr)
3308 next();
3309 parse_asm_str(astr);
3310 skip(')');
3311 #ifdef ASM_DEBUG
3312 printf("asm_alias: \"%s\"\n", (char *)astr->data);
3313 #endif
3316 static void post_type(CType *type, AttributeDef *ad)
3318 int n, l, t1, arg_size, align;
3319 Sym **plast, *s, *first;
3320 AttributeDef ad1;
3321 CType pt;
3323 if (tok == '(') {
3324 /* function declaration */
3325 next();
3326 l = 0;
3327 first = NULL;
3328 plast = &first;
3329 arg_size = 0;
3330 if (tok != ')') {
3331 for(;;) {
3332 /* read param name and compute offset */
3333 if (l != FUNC_OLD) {
3334 if (!parse_btype(&pt, &ad1)) {
3335 if (l) {
3336 tcc_error("invalid type");
3337 } else {
3338 l = FUNC_OLD;
3339 goto old_proto;
3342 l = FUNC_NEW;
3343 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
3344 break;
3345 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
3346 if ((pt.t & VT_BTYPE) == VT_VOID)
3347 tcc_error("parameter declared as void");
3348 arg_size += (type_size(&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
3349 } else {
3350 old_proto:
3351 n = tok;
3352 if (n < TOK_UIDENT)
3353 expect("identifier");
3354 pt.t = VT_INT;
3355 next();
3357 convert_parameter_type(&pt);
3358 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
3359 *plast = s;
3360 plast = &s->next;
3361 if (tok == ')')
3362 break;
3363 skip(',');
3364 if (l == FUNC_NEW && tok == TOK_DOTS) {
3365 l = FUNC_ELLIPSIS;
3366 next();
3367 break;
3371 /* if no parameters, then old type prototype */
3372 if (l == 0)
3373 l = FUNC_OLD;
3374 skip(')');
3375 /* NOTE: const is ignored in returned type as it has a special
3376 meaning in gcc / C++ */
3377 type->t &= ~VT_CONSTANT;
3378 /* some ancient pre-K&R C allows a function to return an array
3379 and the array brackets to be put after the arguments, such
3380 that "int c()[]" means something like "int[] c()" */
3381 if (tok == '[') {
3382 next();
3383 skip(']'); /* only handle simple "[]" */
3384 type->t |= VT_PTR;
3386 /* we push a anonymous symbol which will contain the function prototype */
3387 ad->a.func_args = arg_size;
3388 s = sym_push(SYM_FIELD, type, 0, l);
3389 s->a = ad->a;
3390 s->next = first;
3391 type->t = VT_FUNC;
3392 type->ref = s;
3393 } else if (tok == '[') {
3394 /* array definition */
3395 next();
3396 if (tok == TOK_RESTRICT1)
3397 next();
3398 n = -1;
3399 t1 = 0;
3400 if (tok != ']') {
3401 if (!local_stack || nocode_wanted)
3402 vpushi(expr_const());
3403 else gexpr();
3404 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3405 n = vtop->c.i;
3406 if (n < 0)
3407 tcc_error("invalid array size");
3408 } else {
3409 if (!is_integer_btype(vtop->type.t & VT_BTYPE))
3410 tcc_error("size of variable length array should be an integer");
3411 t1 = VT_VLA;
3414 skip(']');
3415 /* parse next post type */
3416 post_type(type, ad);
3417 if (type->t == VT_FUNC)
3418 tcc_error("declaration of an array of functions");
3419 t1 |= type->t & VT_VLA;
3421 if (t1 & VT_VLA) {
3422 loc -= type_size(&int_type, &align);
3423 loc &= -align;
3424 n = loc;
3426 vla_runtime_type_size(type, &align);
3427 gen_op('*');
3428 vset(&int_type, VT_LOCAL|VT_LVAL, loc);
3429 vswap();
3430 vstore();
3432 if (n != -1)
3433 vpop();
3435 /* we push an anonymous symbol which will contain the array
3436 element type */
3437 s = sym_push(SYM_FIELD, type, 0, n);
3438 type->t = (t1 ? VT_VLA : VT_ARRAY) | VT_PTR;
3439 type->ref = s;
3443 /* Parse a type declaration (except basic type), and return the type
3444 in 'type'. 'td' is a bitmask indicating which kind of type decl is
3445 expected. 'type' should contain the basic type. 'ad' is the
3446 attribute definition of the basic type. It can be modified by
3447 type_decl().
3449 static void type_decl(CType *type, AttributeDef *ad, int *v, int td)
3451 Sym *s;
3452 CType type1, *type2;
3453 int qualifiers, storage;
3455 while (tok == '*') {
3456 qualifiers = 0;
3457 redo:
3458 next();
3459 switch(tok) {
3460 case TOK_CONST1:
3461 case TOK_CONST2:
3462 case TOK_CONST3:
3463 qualifiers |= VT_CONSTANT;
3464 goto redo;
3465 case TOK_VOLATILE1:
3466 case TOK_VOLATILE2:
3467 case TOK_VOLATILE3:
3468 qualifiers |= VT_VOLATILE;
3469 goto redo;
3470 case TOK_RESTRICT1:
3471 case TOK_RESTRICT2:
3472 case TOK_RESTRICT3:
3473 goto redo;
3475 mk_pointer(type);
3476 type->t |= qualifiers;
3479 /* XXX: clarify attribute handling */
3480 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3481 parse_attribute(ad);
3483 /* recursive type */
3484 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
3485 type1.t = 0; /* XXX: same as int */
3486 if (tok == '(') {
3487 next();
3488 /* XXX: this is not correct to modify 'ad' at this point, but
3489 the syntax is not clear */
3490 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3491 parse_attribute(ad);
3492 type_decl(&type1, ad, v, td);
3493 skip(')');
3494 } else {
3495 /* type identifier */
3496 if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
3497 *v = tok;
3498 next();
3499 } else {
3500 if (!(td & TYPE_ABSTRACT))
3501 expect("identifier");
3502 *v = 0;
3505 storage = type->t & VT_STORAGE;
3506 type->t &= ~VT_STORAGE;
3507 if (storage & VT_STATIC) {
3508 int saved_nocode_wanted = nocode_wanted;
3509 nocode_wanted = 1;
3510 post_type(type, ad);
3511 nocode_wanted = saved_nocode_wanted;
3512 } else
3513 post_type(type, ad);
3514 type->t |= storage;
3515 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3516 parse_attribute(ad);
3518 if (!type1.t)
3519 return;
3520 /* append type at the end of type1 */
3521 type2 = &type1;
3522 for(;;) {
3523 s = type2->ref;
3524 type2 = &s->type;
3525 if (!type2->t) {
3526 *type2 = *type;
3527 break;
3530 *type = type1;
3533 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
3534 ST_FUNC int lvalue_type(int t)
3536 int bt, r;
3537 r = VT_LVAL;
3538 bt = t & VT_BTYPE;
3539 if (bt == VT_BYTE || bt == VT_BOOL)
3540 r |= VT_LVAL_BYTE;
3541 else if (bt == VT_SHORT)
3542 r |= VT_LVAL_SHORT;
3543 else
3544 return r;
3545 if (t & VT_UNSIGNED)
3546 r |= VT_LVAL_UNSIGNED;
3547 return r;
3550 /* indirection with full error checking and bound check */
3551 ST_FUNC void indir(void)
3553 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
3554 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
3555 return;
3556 expect("pointer");
3558 if ((vtop->r & VT_LVAL) && !nocode_wanted)
3559 gv(RC_INT);
3560 vtop->type = *pointed_type(&vtop->type);
3561 /* Arrays and functions are never lvalues */
3562 if (!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_VLA)
3563 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
3564 vtop->r |= lvalue_type(vtop->type.t);
3565 /* if bound checking, the referenced pointer must be checked */
3566 #ifdef CONFIG_TCC_BCHECK
3567 if (tcc_state->do_bounds_check)
3568 vtop->r |= VT_MUSTBOUND;
3569 #endif
3573 /* pass a parameter to a function and do type checking and casting */
3574 static void gfunc_param_typed(Sym *func, Sym *arg)
3576 int func_type;
3577 CType type;
3579 func_type = func->c;
3580 if (func_type == FUNC_OLD ||
3581 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
3582 /* default casting : only need to convert float to double */
3583 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
3584 type.t = VT_DOUBLE;
3585 gen_cast(&type);
3586 } else if (vtop->type.t & VT_BITFIELD) {
3587 type.t = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
3588 gen_cast(&type);
3590 } else if (arg == NULL) {
3591 tcc_error("too many arguments to function");
3592 } else {
3593 type = arg->type;
3594 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
3595 gen_assign_cast(&type);
3599 /* parse an expression of the form '(type)' or '(expr)' and return its
3600 type */
3601 static void parse_expr_type(CType *type)
3603 int n;
3604 AttributeDef ad;
3606 skip('(');
3607 if (parse_btype(type, &ad)) {
3608 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3609 } else {
3610 expr_type(type);
3612 skip(')');
3615 static void parse_type(CType *type)
3617 AttributeDef ad;
3618 int n;
3620 if (!parse_btype(type, &ad)) {
3621 expect("type");
3623 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3626 static void vpush_tokc(int t)
3628 CType type;
3629 type.t = t;
3630 type.ref = 0;
3631 vsetc(&type, VT_CONST, &tokc);
3634 ST_FUNC void unary(void)
3636 int n, t, align, size, r, sizeof_caller;
3637 CType type;
3638 Sym *s;
3639 AttributeDef ad;
3640 static int in_sizeof = 0;
3642 sizeof_caller = in_sizeof;
3643 in_sizeof = 0;
3644 /* XXX: GCC 2.95.3 does not generate a table although it should be
3645 better here */
3646 tok_next:
3647 switch(tok) {
3648 case TOK_EXTENSION:
3649 next();
3650 goto tok_next;
3651 case TOK_CINT:
3652 case TOK_CCHAR:
3653 case TOK_LCHAR:
3654 vpushi(tokc.i);
3655 next();
3656 break;
3657 case TOK_CUINT:
3658 vpush_tokc(VT_INT | VT_UNSIGNED);
3659 next();
3660 break;
3661 case TOK_CLLONG:
3662 vpush_tokc(VT_LLONG);
3663 next();
3664 break;
3665 case TOK_CULLONG:
3666 vpush_tokc(VT_LLONG | VT_UNSIGNED);
3667 next();
3668 break;
3669 case TOK_CFLOAT:
3670 vpush_tokc(VT_FLOAT);
3671 next();
3672 break;
3673 case TOK_CDOUBLE:
3674 vpush_tokc(VT_DOUBLE);
3675 next();
3676 break;
3677 case TOK_CLDOUBLE:
3678 vpush_tokc(VT_LDOUBLE);
3679 next();
3680 break;
3681 case TOK___FUNCTION__:
3682 if (!gnu_ext)
3683 goto tok_identifier;
3684 /* fall thru */
3685 case TOK___FUNC__:
3687 void *ptr;
3688 int len;
3689 /* special function name identifier */
3690 len = strlen(funcname) + 1;
3691 /* generate char[len] type */
3692 type.t = VT_BYTE;
3693 mk_pointer(&type);
3694 type.t |= VT_ARRAY;
3695 type.ref->c = len;
3696 vpush_ref(&type, data_section, data_section->data_offset, len);
3697 ptr = section_ptr_add(data_section, len);
3698 memcpy(ptr, funcname, len);
3699 next();
3701 break;
3702 case TOK_LSTR:
3703 #ifdef TCC_TARGET_PE
3704 t = VT_SHORT | VT_UNSIGNED;
3705 #else
3706 t = VT_INT;
3707 #endif
3708 goto str_init;
3709 case TOK_STR:
3710 /* string parsing */
3711 t = VT_BYTE;
3712 str_init:
3713 if (tcc_state->warn_write_strings)
3714 t |= VT_CONSTANT;
3715 type.t = t;
3716 mk_pointer(&type);
3717 type.t |= VT_ARRAY;
3718 memset(&ad, 0, sizeof(AttributeDef));
3719 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, NULL, 0);
3720 break;
3721 case '(':
3722 next();
3723 /* cast ? */
3724 if (parse_btype(&type, &ad)) {
3725 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
3726 skip(')');
3727 /* check ISOC99 compound literal */
3728 if (tok == '{') {
3729 /* data is allocated locally by default */
3730 if (global_expr)
3731 r = VT_CONST;
3732 else
3733 r = VT_LOCAL;
3734 /* all except arrays are lvalues */
3735 if (!(type.t & VT_ARRAY))
3736 r |= lvalue_type(type.t);
3737 memset(&ad, 0, sizeof(AttributeDef));
3738 decl_initializer_alloc(&type, &ad, r, 1, 0, NULL, 0);
3739 } else {
3740 if (sizeof_caller) {
3741 vpush(&type);
3742 return;
3744 unary();
3745 is_force = 1;
3746 gen_cast(&type);
3747 is_force = 0;
3749 } else if (tok == '{') {
3750 /* save all registers */
3751 save_regs(0);
3752 /* statement expression : we do not accept break/continue
3753 inside as GCC does */
3754 block(NULL, NULL, NULL, NULL, 0, 1);
3755 skip(')');
3756 } else {
3757 gexpr();
3758 skip(')');
3760 break;
3761 case '*':
3762 next();
3763 unary();
3764 indir();
3765 break;
3766 case '&':
3767 next();
3768 unary();
3769 /* functions names must be treated as function pointers,
3770 except for unary '&' and sizeof. Since we consider that
3771 functions are not lvalues, we only have to handle it
3772 there and in function calls. */
3773 /* arrays can also be used although they are not lvalues */
3774 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
3775 !(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
3776 test_lvalue();
3777 mk_pointer(&vtop->type);
3778 gaddrof();
3779 break;
3780 case '!':
3781 next();
3782 unary();
3783 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3784 CType boolean;
3785 boolean.t = VT_BOOL;
3786 gen_cast(&boolean);
3787 vtop->c.i = !vtop->c.i;
3788 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
3789 vtop->c.i = vtop->c.i ^ 1;
3790 else {
3791 save_regs(1);
3792 vseti(VT_JMP, gvtst(1, 0));
3794 break;
3795 case '~':
3796 next();
3797 unary();
3798 vpushi(-1);
3799 gen_op('^');
3800 break;
3801 case '+':
3802 next();
3803 unary();
3804 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
3805 tcc_error("pointer not accepted for unary plus");
3806 /* In order to force cast, we add zero, except for floating point
3807 where we really need an noop (otherwise -0.0 will be transformed
3808 into +0.0). */
3809 if (!is_float(vtop->type.t)) {
3810 vpushi(0);
3811 gen_op('+');
3813 break;
3814 case TOK_SIZEOF:
3815 case TOK_ALIGNOF1:
3816 case TOK_ALIGNOF2:
3817 t = tok;
3818 next();
3819 in_sizeof++;
3820 unary_type(&type); // Perform a in_sizeof = 0;
3821 size = type_size(&type, &align);
3822 if (t == TOK_SIZEOF) {
3823 if (!(type.t & VT_VLA)) {
3824 if (size < 0)
3825 tcc_error("sizeof applied to an incomplete type");
3826 if(type.t & VT_BITFIELD)
3827 tcc_error("'%s' applied to a bit-field", get_tok_str(t, NULL));
3828 vpushs(size);
3829 } else {
3830 vla_runtime_type_size(&type, &align);
3832 } else {
3833 vpushs(align);
3835 vtop->type.t |= VT_UNSIGNED;
3836 break;
3838 case TOK_builtin_types_compatible_p:
3840 CType type1, type2;
3841 next();
3842 skip('(');
3843 parse_type(&type1);
3844 skip(',');
3845 parse_type(&type2);
3846 skip(')');
3847 type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
3848 type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
3849 vpushi(is_compatible_types(&type1, &type2));
3851 break;
3852 case TOK_builtin_constant_p:
3854 int saved_nocode_wanted, res;
3855 next();
3856 skip('(');
3857 saved_nocode_wanted = nocode_wanted;
3858 nocode_wanted = 1;
3859 gexpr();
3860 res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
3861 vpop();
3862 nocode_wanted = saved_nocode_wanted;
3863 skip(')');
3864 vpushi(res);
3866 break;
3867 case TOK_builtin_frame_address:
3869 int level;
3870 CType type;
3871 next();
3872 skip('(');
3873 if (tok != TOK_CINT || tokc.i < 0) {
3874 tcc_error("__builtin_frame_address only takes positive integers");
3876 level = tokc.i;
3877 next();
3878 skip(')');
3879 type.t = VT_VOID;
3880 mk_pointer(&type);
3881 vset(&type, VT_LOCAL, 0); /* local frame */
3882 while (level--) {
3883 mk_pointer(&vtop->type);
3884 indir(); /* -> parent frame */
3887 break;
3888 #ifdef TCC_TARGET_X86_64
3889 #ifdef TCC_TARGET_PE
3890 case TOK_builtin_va_start:
3892 next();
3893 skip('(');
3894 expr_eq();
3895 skip(',');
3896 expr_eq();
3897 skip(')');
3898 if ((vtop->r & VT_VALMASK) != VT_LOCAL)
3899 tcc_error("__builtin_va_start expects a local variable");
3900 vtop->r &= ~(VT_LVAL | VT_REF);
3901 vtop->type = char_pointer_type;
3902 vstore();
3904 break;
3905 #else
3906 case TOK_builtin_va_arg_types:
3908 CType type;
3909 next();
3910 skip('(');
3911 parse_type(&type);
3912 skip(')');
3913 vpushi(classify_x86_64_va_arg(&type));
3915 break;
3916 #endif
3917 #endif
3918 case TOK_INC:
3919 case TOK_DEC:
3920 t = tok;
3921 next();
3922 unary();
3923 inc(0, t);
3924 break;
3925 case '-':
3926 next();
3927 unary();
3928 t = vtop->type.t & VT_BTYPE;
3929 if (is_float(t)) {
3930 /* In IEEE negate(x) isn't subtract(0,x), but rather
3931 subtract(-0, x). */
3932 vpush(&vtop->type);
3933 if (t == VT_FLOAT)
3934 vtop->c.f = -0.0f;
3935 else if (t == VT_DOUBLE)
3936 vtop->c.d = -0.0;
3937 else
3938 vtop->c.ld = -0.0;
3939 } else
3940 vpushi(0);
3941 vswap();
3942 gen_op('-');
3943 break;
3944 case TOK_LAND:
3945 if (!gnu_ext)
3946 goto tok_identifier;
3947 next();
3948 /* allow to take the address of a label */
3949 if (tok < TOK_UIDENT)
3950 expect("label identifier");
3951 s = label_find(tok);
3952 if (!s) {
3953 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
3954 } else {
3955 if (s->r == LABEL_DECLARED)
3956 s->r = LABEL_FORWARD;
3958 if (!s->type.t) {
3959 s->type.t = VT_VOID;
3960 mk_pointer(&s->type);
3961 s->type.t |= VT_STATIC;
3963 vpushsym(&s->type, s);
3964 next();
3965 break;
3967 // special qnan , snan and infinity values
3968 case TOK___NAN__:
3969 vpush64(VT_DOUBLE, 0x7ff8000000000000ULL);
3970 next();
3971 break;
3972 case TOK___SNAN__:
3973 vpush64(VT_DOUBLE, 0x7ff0000000000001ULL);
3974 next();
3975 break;
3976 case TOK___INF__:
3977 vpush64(VT_DOUBLE, 0x7ff0000000000000ULL);
3978 next();
3979 break;
3981 default:
3982 tok_identifier:
3983 t = tok;
3984 next();
3985 if (t < TOK_UIDENT)
3986 expect("identifier");
3987 s = sym_find(t);
3988 if (!s) {
3989 const char *name = get_tok_str(t, NULL);
3990 if (tok != '(')
3991 tcc_error("'%s' undeclared", name);
3992 /* for simple function calls, we tolerate undeclared
3993 external reference to int() function */
3994 if (tcc_state->warn_implicit_function_declaration
3995 #ifdef TCC_TARGET_PE
3996 /* people must be warned about using undeclared WINAPI functions
3997 (which usually start with uppercase letter) */
3998 || (name[0] >= 'A' && name[0] <= 'Z')
3999 #endif
4001 tcc_warning("implicit declaration of function '%s'", name);
4002 s = external_sym(t, &func_old_type, 0, NULL);
4004 if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
4005 (VT_STATIC | VT_INLINE | VT_FUNC)) {
4006 /* if referencing an inline function, then we generate a
4007 symbol to it if not already done. It will have the
4008 effect to generate code for it at the end of the
4009 compilation unit. Inline function as always
4010 generated in the text section. */
4011 if (!s->c)
4012 put_extern_sym(s, text_section, 0, 0);
4013 r = VT_SYM | VT_CONST;
4014 } else {
4015 r = s->r;
4017 vset(&s->type, r, s->c);
4018 /* if forward reference, we must point to s */
4019 if (vtop->r & VT_SYM) {
4020 vtop->sym = s;
4021 vtop->c.ptr_offset = 0;
4023 break;
4026 /* post operations */
4027 while (1) {
4028 if (tok == TOK_INC || tok == TOK_DEC) {
4029 inc(1, tok);
4030 next();
4031 } else if (tok == '.' || tok == TOK_ARROW) {
4032 int qualifiers;
4033 /* field */
4034 if (tok == TOK_ARROW)
4035 indir();
4036 qualifiers = vtop->type.t & (VT_CONSTANT | VT_VOLATILE);
4037 test_lvalue();
4038 gaddrof();
4039 next();
4040 /* expect pointer on structure */
4041 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
4042 expect("struct or union");
4043 s = vtop->type.ref;
4044 /* find field */
4045 tok |= SYM_FIELD;
4046 while ((s = s->next) != NULL) {
4047 if (s->v == tok)
4048 break;
4050 if (!s)
4051 tcc_error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, NULL));
4052 /* add field offset to pointer */
4053 vtop->type = char_pointer_type; /* change type to 'char *' */
4054 vpushi(s->c);
4055 gen_op('+');
4056 /* change type to field type, and set to lvalue */
4057 vtop->type = s->type;
4058 vtop->type.t |= qualifiers;
4059 /* an array is never an lvalue */
4060 if (!(vtop->type.t & VT_ARRAY)) {
4061 vtop->r |= lvalue_type(vtop->type.t);
4062 #ifdef CONFIG_TCC_BCHECK
4063 /* if bound checking, the referenced pointer must be checked */
4064 if (tcc_state->do_bounds_check)
4065 vtop->r |= VT_MUSTBOUND;
4066 #endif
4068 next();
4069 } else if (tok == '[') {
4070 next();
4071 gexpr();
4072 gen_op('+');
4073 indir();
4074 skip(']');
4075 } else if (tok == '(') {
4076 SValue ret;
4077 Sym *sa;
4078 int nb_args, ret_nregs, ret_align, variadic;
4080 /* function call */
4081 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
4082 /* pointer test (no array accepted) */
4083 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
4084 vtop->type = *pointed_type(&vtop->type);
4085 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
4086 goto error_func;
4087 } else {
4088 error_func:
4089 expect("function pointer");
4091 } else {
4092 vtop->r &= ~VT_LVAL; /* no lvalue */
4094 /* get return type */
4095 s = vtop->type.ref;
4096 next();
4097 sa = s->next; /* first parameter */
4098 nb_args = 0;
4099 ret.r2 = VT_CONST;
4100 /* compute first implicit argument if a structure is returned */
4101 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
4102 variadic = (s->c == FUNC_ELLIPSIS);
4103 ret_nregs = gfunc_sret(&s->type, variadic, &ret.type,
4104 &ret_align);
4105 if (!ret_nregs) {
4106 /* get some space for the returned structure */
4107 size = type_size(&s->type, &align);
4108 loc = (loc - size) & -align;
4109 ret.type = s->type;
4110 ret.r = VT_LOCAL | VT_LVAL;
4111 /* pass it as 'int' to avoid structure arg passing
4112 problems */
4113 vseti(VT_LOCAL, loc);
4114 ret.c = vtop->c;
4115 nb_args++;
4117 } else {
4118 ret_nregs = 1;
4119 ret.type = s->type;
4122 if (ret_nregs) {
4123 /* return in register */
4124 if (is_float(ret.type.t)) {
4125 ret.r = reg_fret(ret.type.t);
4126 #ifdef TCC_TARGET_X86_64
4127 if ((ret.type.t & VT_BTYPE) == VT_QFLOAT)
4128 ret.r2 = REG_QRET;
4129 #endif
4130 } else {
4131 #ifdef TCC_TARGET_X86_64
4132 if ((ret.type.t & VT_BTYPE) == VT_QLONG)
4133 #else
4134 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
4135 #endif
4136 ret.r2 = REG_LRET;
4137 ret.r = REG_IRET;
4139 ret.c.i = 0;
4141 if (tok != ')') {
4142 for(;;) {
4143 expr_eq();
4144 gfunc_param_typed(s, sa);
4145 nb_args++;
4146 if (sa)
4147 sa = sa->next;
4148 if (tok == ')')
4149 break;
4150 skip(',');
4153 if (sa)
4154 tcc_error("too few arguments to function");
4155 skip(')');
4156 if (!nocode_wanted) {
4157 gfunc_call(nb_args);
4158 } else {
4159 vtop -= (nb_args + 1);
4162 /* return value */
4163 for (r = ret.r + ret_nregs + !ret_nregs; r-- > ret.r;) {
4164 vsetc(&ret.type, r, &ret.c);
4165 vtop->r2 = ret.r2; /* Loop only happens when r2 is VT_CONST */
4168 /* handle packed struct return */
4169 if (((s->type.t & VT_BTYPE) == VT_STRUCT) && ret_nregs) {
4170 int addr, offset;
4172 size = type_size(&s->type, &align);
4173 loc = (loc - size) & -align;
4174 addr = loc;
4175 offset = 0;
4176 for (;;) {
4177 vset(&ret.type, VT_LOCAL | VT_LVAL, addr + offset);
4178 vswap();
4179 vstore();
4180 vtop--;
4181 if (--ret_nregs == 0)
4182 break;
4183 /* XXX: compatible with arm only: ret_align == register_size */
4184 offset += ret_align;
4186 vset(&s->type, VT_LOCAL | VT_LVAL, addr);
4188 } else {
4189 break;
4194 ST_FUNC void expr_prod(void)
4196 int t;
4198 unary();
4199 while (tok == '*' || tok == '/' || tok == '%') {
4200 t = tok;
4201 next();
4202 unary();
4203 gen_op(t);
4207 ST_FUNC void expr_sum(void)
4209 int t;
4211 expr_prod();
4212 while (tok == '+' || tok == '-') {
4213 t = tok;
4214 next();
4215 expr_prod();
4216 gen_op(t);
4220 static void expr_shift(void)
4222 int t;
4224 expr_sum();
4225 while (tok == TOK_SHL || tok == TOK_SAR) {
4226 t = tok;
4227 next();
4228 expr_sum();
4229 gen_op(t);
4233 static void expr_cmp(void)
4235 int t;
4237 expr_shift();
4238 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
4239 tok == TOK_ULT || tok == TOK_UGE) {
4240 t = tok;
4241 next();
4242 expr_shift();
4243 gen_op(t);
4247 static void expr_cmpeq(void)
4249 int t;
4251 expr_cmp();
4252 while (tok == TOK_EQ || tok == TOK_NE) {
4253 t = tok;
4254 next();
4255 expr_cmp();
4256 gen_op(t);
4260 static void expr_and(void)
4262 expr_cmpeq();
4263 while (tok == '&') {
4264 next();
4265 expr_cmpeq();
4266 gen_op('&');
4270 static void expr_xor(void)
4272 expr_and();
4273 while (tok == '^') {
4274 next();
4275 expr_and();
4276 gen_op('^');
4280 static void expr_or(void)
4282 expr_xor();
4283 while (tok == '|') {
4284 next();
4285 expr_xor();
4286 gen_op('|');
4290 /* XXX: fix this mess */
4291 static void expr_land_const(void)
4293 expr_or();
4294 while (tok == TOK_LAND) {
4295 next();
4296 expr_or();
4297 gen_op(TOK_LAND);
4301 /* XXX: fix this mess */
4302 static void expr_lor_const(void)
4304 expr_land_const();
4305 while (tok == TOK_LOR) {
4306 next();
4307 expr_land_const();
4308 gen_op(TOK_LOR);
4312 /* only used if non constant */
4313 static void expr_land(void)
4315 int t;
4317 expr_or();
4318 if (tok == TOK_LAND) {
4319 t = 0;
4320 save_regs(1);
4321 for(;;) {
4322 t = gvtst(1, t);
4323 if (tok != TOK_LAND) {
4324 vseti(VT_JMPI, t);
4325 break;
4327 next();
4328 expr_or();
4333 static void expr_lor(void)
4335 int t;
4337 expr_land();
4338 if (tok == TOK_LOR) {
4339 t = 0;
4340 save_regs(1);
4341 for(;;) {
4342 t = gvtst(0, t);
4343 if (tok != TOK_LOR) {
4344 vseti(VT_JMP, t);
4345 break;
4347 next();
4348 expr_land();
4353 /* XXX: better constant handling */
4354 static void expr_cond(void)
4356 int tt, u, r1, r2, rc, t1, t2, bt1, bt2;
4357 SValue sv;
4358 CType type, type1, type2;
4360 if (const_wanted) {
4361 expr_lor_const();
4362 if (tok == '?') {
4363 CType boolean;
4364 int c;
4365 boolean.t = VT_BOOL;
4366 vdup();
4367 gen_cast(&boolean);
4368 c = vtop->c.i;
4369 vpop();
4370 next();
4371 if (tok != ':' || !gnu_ext) {
4372 vpop();
4373 gexpr();
4375 if (!c)
4376 vpop();
4377 skip(':');
4378 expr_cond();
4379 if (c)
4380 vpop();
4382 } else {
4383 expr_lor();
4384 if (tok == '?') {
4385 next();
4386 if (vtop != vstack) {
4387 /* needed to avoid having different registers saved in
4388 each branch */
4389 if (is_float(vtop->type.t)) {
4390 rc = RC_FLOAT;
4391 #ifdef TCC_TARGET_X86_64
4392 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
4393 rc = RC_ST0;
4395 #endif
4397 else
4398 rc = RC_INT;
4399 gv(rc);
4400 save_regs(1);
4402 if (tok == ':' && gnu_ext) {
4403 gv_dup();
4404 tt = gvtst(1, 0);
4405 } else {
4406 tt = gvtst(1, 0);
4407 gexpr();
4409 type1 = vtop->type;
4410 sv = *vtop; /* save value to handle it later */
4411 vtop--; /* no vpop so that FP stack is not flushed */
4412 skip(':');
4413 u = gjmp(0);
4414 gsym(tt);
4415 expr_cond();
4416 type2 = vtop->type;
4418 t1 = type1.t;
4419 bt1 = t1 & VT_BTYPE;
4420 t2 = type2.t;
4421 bt2 = t2 & VT_BTYPE;
4422 /* cast operands to correct type according to ISOC rules */
4423 if (is_float(bt1) || is_float(bt2)) {
4424 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
4425 type.t = VT_LDOUBLE;
4426 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
4427 type.t = VT_DOUBLE;
4428 } else {
4429 type.t = VT_FLOAT;
4431 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
4432 /* cast to biggest op */
4433 type.t = VT_LLONG;
4434 /* convert to unsigned if it does not fit in a long long */
4435 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
4436 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
4437 type.t |= VT_UNSIGNED;
4438 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
4439 /* If one is a null ptr constant the result type
4440 is the other. */
4441 if (is_null_pointer (vtop))
4442 type = type1;
4443 else if (is_null_pointer (&sv))
4444 type = type2;
4445 /* XXX: test pointer compatibility, C99 has more elaborate
4446 rules here. */
4447 else
4448 type = type1;
4449 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
4450 /* XXX: test function pointer compatibility */
4451 type = bt1 == VT_FUNC ? type1 : type2;
4452 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
4453 /* XXX: test structure compatibility */
4454 type = bt1 == VT_STRUCT ? type1 : type2;
4455 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
4456 /* NOTE: as an extension, we accept void on only one side */
4457 type.t = VT_VOID;
4458 } else {
4459 /* integer operations */
4460 type.t = VT_INT;
4461 /* convert to unsigned if it does not fit in an integer */
4462 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
4463 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
4464 type.t |= VT_UNSIGNED;
4467 /* now we convert second operand */
4468 gen_cast(&type);
4469 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4470 gaddrof();
4471 rc = RC_INT;
4472 if (is_float(type.t)) {
4473 rc = RC_FLOAT;
4474 #ifdef TCC_TARGET_X86_64
4475 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
4476 rc = RC_ST0;
4478 #endif
4479 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
4480 /* for long longs, we use fixed registers to avoid having
4481 to handle a complicated move */
4482 rc = RC_IRET;
4485 r2 = gv(rc);
4486 /* this is horrible, but we must also convert first
4487 operand */
4488 tt = gjmp(0);
4489 gsym(u);
4490 /* put again first value and cast it */
4491 *vtop = sv;
4492 gen_cast(&type);
4493 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4494 gaddrof();
4495 r1 = gv(rc);
4496 move_reg(r2, r1, type.t);
4497 vtop->r = r2;
4498 gsym(tt);
4503 static void expr_eq(void)
4505 int t;
4507 expr_cond();
4508 if (tok == '=' ||
4509 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
4510 tok == TOK_A_XOR || tok == TOK_A_OR ||
4511 tok == TOK_A_SHL || tok == TOK_A_SAR) {
4512 test_lvalue();
4513 t = tok;
4514 next();
4515 if (t == '=') {
4516 expr_eq();
4517 } else {
4518 vdup();
4519 expr_eq();
4520 gen_op(t & 0x7f);
4522 vstore();
4526 ST_FUNC void gexpr(void)
4528 while (1) {
4529 expr_eq();
4530 if (tok != ',')
4531 break;
4532 vpop();
4533 next();
4537 /* parse an expression and return its type without any side effect. */
4538 static void expr_type(CType *type)
4540 int saved_nocode_wanted;
4542 saved_nocode_wanted = nocode_wanted;
4543 nocode_wanted = 1;
4544 gexpr();
4545 *type = vtop->type;
4546 vpop();
4547 nocode_wanted = saved_nocode_wanted;
4550 /* parse a unary expression and return its type without any side
4551 effect. */
4552 static void unary_type(CType *type)
4554 int a;
4556 a = nocode_wanted;
4557 nocode_wanted = 1;
4558 unary();
4559 *type = vtop->type;
4560 vpop();
4561 nocode_wanted = a;
4564 /* parse a constant expression and return value in vtop. */
4565 static void expr_const1(void)
4567 int a;
4568 a = const_wanted;
4569 const_wanted = 1;
4570 expr_cond();
4571 const_wanted = a;
4574 /* parse an integer constant and return its value. */
4575 ST_FUNC int expr_const(void)
4577 int c;
4578 expr_const1();
4579 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
4580 expect("constant expression");
4581 c = vtop->c.i;
4582 vpop();
4583 return c;
4586 /* return the label token if current token is a label, otherwise
4587 return zero */
4588 static int is_label(void)
4590 int last_tok;
4592 /* fast test first */
4593 if (tok < TOK_UIDENT)
4594 return 0;
4595 /* no need to save tokc because tok is an identifier */
4596 last_tok = tok;
4597 next();
4598 if (tok == ':') {
4599 next();
4600 return last_tok;
4601 } else {
4602 unget_tok(last_tok);
4603 return 0;
4607 static void label_or_decl(int l)
4609 int last_tok;
4611 /* fast test first */
4612 if (tok >= TOK_UIDENT)
4614 /* no need to save tokc because tok is an identifier */
4615 last_tok = tok;
4616 next();
4617 if (tok == ':') {
4618 unget_tok(last_tok);
4619 return;
4621 unget_tok(last_tok);
4623 decl(l);
4626 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
4627 int case_reg, int is_expr)
4629 int a, b, c, d;
4630 Sym *s, *frame_bottom;
4632 /* generate line number info */
4633 if (tcc_state->do_debug &&
4634 (last_line_num != file->line_num || last_ind != ind)) {
4635 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
4636 last_ind = ind;
4637 last_line_num = file->line_num;
4640 if (is_expr) {
4641 /* default return value is (void) */
4642 vpushi(0);
4643 vtop->type.t = VT_VOID;
4646 if (tok == TOK_IF) {
4647 /* if test */
4648 next();
4649 skip('(');
4650 gexpr();
4651 skip(')');
4652 a = gvtst(1, 0);
4653 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4654 c = tok;
4655 if (c == TOK_ELSE) {
4656 next();
4657 d = gjmp(0);
4658 gsym(a);
4659 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4660 gsym(d); /* patch else jmp */
4661 } else
4662 gsym(a);
4663 } else if (tok == TOK_WHILE) {
4664 next();
4665 d = ind;
4666 skip('(');
4667 gexpr();
4668 skip(')');
4669 a = gvtst(1, 0);
4670 b = 0;
4671 block(&a, &b, case_sym, def_sym, case_reg, 0);
4672 gjmp_addr(d);
4673 gsym(a);
4674 gsym_addr(b, d);
4675 } else if (tok == '{') {
4676 Sym *llabel;
4677 int block_vla_sp_loc, *saved_vla_sp_loc, saved_vla_flags;
4679 next();
4680 /* record local declaration stack position */
4681 s = local_stack;
4682 frame_bottom = sym_push2(&local_stack, SYM_FIELD, 0, 0);
4683 frame_bottom->next = scope_stack_bottom;
4684 scope_stack_bottom = frame_bottom;
4685 llabel = local_label_stack;
4687 /* save VLA state */
4688 block_vla_sp_loc = *(saved_vla_sp_loc = vla_sp_loc);
4689 if (saved_vla_sp_loc != &vla_sp_root_loc)
4690 vla_sp_loc = &block_vla_sp_loc;
4692 saved_vla_flags = vla_flags;
4693 vla_flags |= VLA_NEED_NEW_FRAME;
4695 /* handle local labels declarations */
4696 if (tok == TOK_LABEL) {
4697 next();
4698 for(;;) {
4699 if (tok < TOK_UIDENT)
4700 expect("label identifier");
4701 label_push(&local_label_stack, tok, LABEL_DECLARED);
4702 next();
4703 if (tok == ',') {
4704 next();
4705 } else {
4706 skip(';');
4707 break;
4711 while (tok != '}') {
4712 label_or_decl(VT_LOCAL);
4713 if (tok != '}') {
4714 if (is_expr)
4715 vpop();
4716 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
4719 /* pop locally defined labels */
4720 label_pop(&local_label_stack, llabel);
4721 if(is_expr) {
4722 /* XXX: this solution makes only valgrind happy...
4723 triggered by gcc.c-torture/execute/20000917-1.c */
4724 Sym *p;
4725 switch(vtop->type.t & VT_BTYPE) {
4726 case VT_PTR:
4727 case VT_STRUCT:
4728 case VT_ENUM:
4729 case VT_FUNC:
4730 for(p=vtop->type.ref;p;p=p->prev)
4731 if(p->prev==s)
4732 tcc_error("unsupported expression type");
4735 /* pop locally defined symbols */
4736 scope_stack_bottom = scope_stack_bottom->next;
4737 sym_pop(&local_stack, s);
4739 /* Pop VLA frames and restore stack pointer if required */
4740 if (saved_vla_sp_loc != &vla_sp_root_loc)
4741 *saved_vla_sp_loc = block_vla_sp_loc;
4742 if (vla_sp_loc != (saved_vla_sp_loc == &vla_sp_root_loc ? &vla_sp_root_loc : &block_vla_sp_loc)) {
4743 vla_sp_loc = saved_vla_sp_loc;
4744 gen_vla_sp_restore(*vla_sp_loc);
4746 vla_flags = (vla_flags & ~VLA_SCOPE_FLAGS) | (saved_vla_flags & VLA_SCOPE_FLAGS);
4748 next();
4749 } else if (tok == TOK_RETURN) {
4750 next();
4751 if (tok != ';') {
4752 gexpr();
4753 gen_assign_cast(&func_vt);
4754 if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
4755 CType type, ret_type;
4756 int ret_align, ret_nregs;
4757 ret_nregs = gfunc_sret(&func_vt, func_var, &ret_type,
4758 &ret_align);
4759 if (0 == ret_nregs) {
4760 /* if returning structure, must copy it to implicit
4761 first pointer arg location */
4762 type = func_vt;
4763 mk_pointer(&type);
4764 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
4765 indir();
4766 vswap();
4767 /* copy structure value to pointer */
4768 vstore();
4769 } else {
4770 /* returning structure packed into registers */
4771 int r, size, addr, align;
4772 size = type_size(&func_vt,&align);
4773 if ((vtop->r != (VT_LOCAL | VT_LVAL) || (vtop->c.i & (ret_align-1)))
4774 && (align & (ret_align-1))) {
4775 loc = (loc - size) & -align;
4776 addr = loc;
4777 type = func_vt;
4778 vset(&type, VT_LOCAL | VT_LVAL, addr);
4779 vswap();
4780 vstore();
4781 vset(&ret_type, VT_LOCAL | VT_LVAL, addr);
4783 vtop->type = ret_type;
4784 if (is_float(ret_type.t))
4785 r = rc_fret(ret_type.t);
4786 else
4787 r = RC_IRET;
4789 for (;;) {
4790 gv(r);
4791 if (--ret_nregs == 0)
4792 break;
4793 /* We assume that when a structure is returned in multiple
4794 registers, their classes are consecutive values of the
4795 suite s(n) = 2^n */
4796 r <<= 1;
4797 /* XXX: compatible with arm only: ret_align == register_size */
4798 vtop->c.i += ret_align;
4799 vtop->r = VT_LOCAL | VT_LVAL;
4802 } else if (is_float(func_vt.t)) {
4803 gv(rc_fret(func_vt.t));
4804 } else {
4805 gv(RC_IRET);
4807 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
4809 skip(';');
4810 rsym = gjmp(rsym); /* jmp */
4811 } else if (tok == TOK_BREAK) {
4812 /* compute jump */
4813 if (!bsym)
4814 tcc_error("cannot break");
4815 *bsym = gjmp(*bsym);
4816 next();
4817 skip(';');
4818 } else if (tok == TOK_CONTINUE) {
4819 /* compute jump */
4820 if (!csym)
4821 tcc_error("cannot continue");
4822 *csym = gjmp(*csym);
4823 next();
4824 skip(';');
4825 } else if (tok == TOK_FOR) {
4826 int e;
4827 next();
4828 skip('(');
4829 s = local_stack;
4830 frame_bottom = sym_push2(&local_stack, SYM_FIELD, 0, 0);
4831 frame_bottom->next = scope_stack_bottom;
4832 scope_stack_bottom = frame_bottom;
4833 if (tok != ';') {
4834 /* c99 for-loop init decl? */
4835 if (!decl0(VT_LOCAL, 1)) {
4836 /* no, regular for-loop init expr */
4837 gexpr();
4838 vpop();
4841 skip(';');
4842 d = ind;
4843 c = ind;
4844 a = 0;
4845 b = 0;
4846 if (tok != ';') {
4847 gexpr();
4848 a = gvtst(1, 0);
4850 skip(';');
4851 if (tok != ')') {
4852 e = gjmp(0);
4853 c = ind;
4854 gexpr();
4855 vpop();
4856 gjmp_addr(d);
4857 gsym(e);
4859 skip(')');
4860 block(&a, &b, case_sym, def_sym, case_reg, 0);
4861 gjmp_addr(c);
4862 gsym(a);
4863 gsym_addr(b, c);
4864 scope_stack_bottom = scope_stack_bottom->next;
4865 sym_pop(&local_stack, s);
4866 } else
4867 if (tok == TOK_DO) {
4868 next();
4869 a = 0;
4870 b = 0;
4871 d = ind;
4872 block(&a, &b, case_sym, def_sym, case_reg, 0);
4873 skip(TOK_WHILE);
4874 skip('(');
4875 gsym(b);
4876 gexpr();
4877 c = gvtst(0, 0);
4878 gsym_addr(c, d);
4879 skip(')');
4880 gsym(a);
4881 skip(';');
4882 } else
4883 if (tok == TOK_SWITCH) {
4884 next();
4885 skip('(');
4886 gexpr();
4887 /* XXX: other types than integer */
4888 case_reg = gv(RC_INT);
4889 vpop();
4890 skip(')');
4891 a = 0;
4892 b = gjmp(0); /* jump to first case */
4893 c = 0;
4894 block(&a, csym, &b, &c, case_reg, 0);
4895 /* if no default, jmp after switch */
4896 if (c == 0)
4897 c = ind;
4898 /* default label */
4899 gsym_addr(b, c);
4900 /* break label */
4901 gsym(a);
4902 } else
4903 if (tok == TOK_CASE) {
4904 int v1, v2;
4905 if (!case_sym)
4906 expect("switch");
4907 next();
4908 v1 = expr_const();
4909 v2 = v1;
4910 if (gnu_ext && tok == TOK_DOTS) {
4911 next();
4912 v2 = expr_const();
4913 if (v2 < v1)
4914 tcc_warning("empty case range");
4916 /* since a case is like a label, we must skip it with a jmp */
4917 b = gjmp(0);
4918 gsym(*case_sym);
4919 vseti(case_reg, 0);
4920 vpushi(v1);
4921 if (v1 == v2) {
4922 gen_op(TOK_EQ);
4923 *case_sym = gtst(1, 0);
4924 } else {
4925 gen_op(TOK_GE);
4926 *case_sym = gtst(1, 0);
4927 vseti(case_reg, 0);
4928 vpushi(v2);
4929 gen_op(TOK_LE);
4930 *case_sym = gtst(1, *case_sym);
4932 gsym(b);
4933 skip(':');
4934 is_expr = 0;
4935 goto block_after_label;
4936 } else
4937 if (tok == TOK_DEFAULT) {
4938 next();
4939 skip(':');
4940 if (!def_sym)
4941 expect("switch");
4942 if (*def_sym)
4943 tcc_error("too many 'default'");
4944 *def_sym = ind;
4945 is_expr = 0;
4946 goto block_after_label;
4947 } else
4948 if (tok == TOK_GOTO) {
4949 next();
4950 if (tok == '*' && gnu_ext) {
4951 /* computed goto */
4952 next();
4953 gexpr();
4954 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
4955 expect("pointer");
4956 ggoto();
4957 } else if (tok >= TOK_UIDENT) {
4958 s = label_find(tok);
4959 /* put forward definition if needed */
4960 if (!s) {
4961 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
4962 } else {
4963 if (s->r == LABEL_DECLARED)
4964 s->r = LABEL_FORWARD;
4966 /* label already defined */
4967 if (vla_flags & VLA_IN_SCOPE) {
4968 /* If VLAs are in use, save the current stack pointer and
4969 reset the stack pointer to what it was at function entry
4970 (label will restore stack pointer in inner scopes) */
4971 vla_sp_save();
4972 gen_vla_sp_restore(vla_sp_root_loc);
4974 if (s->r & LABEL_FORWARD)
4975 s->jnext = gjmp(s->jnext);
4976 else
4977 gjmp_addr(s->jnext);
4978 next();
4979 } else {
4980 expect("label identifier");
4982 skip(';');
4983 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
4984 asm_instr();
4985 } else {
4986 b = is_label();
4987 if (b) {
4988 /* label case */
4989 if (vla_flags & VLA_IN_SCOPE) {
4990 /* save/restore stack pointer across label
4991 this is a no-op when combined with the load immediately
4992 after the label unless we arrive via goto */
4993 vla_sp_save();
4995 s = label_find(b);
4996 if (s) {
4997 if (s->r == LABEL_DEFINED)
4998 tcc_error("duplicate label '%s'", get_tok_str(s->v, NULL));
4999 gsym(s->jnext);
5000 s->r = LABEL_DEFINED;
5001 } else {
5002 s = label_push(&global_label_stack, b, LABEL_DEFINED);
5004 s->jnext = ind;
5005 if (vla_flags & VLA_IN_SCOPE) {
5006 gen_vla_sp_restore(*vla_sp_loc);
5007 vla_flags |= VLA_NEED_NEW_FRAME;
5009 /* we accept this, but it is a mistake */
5010 block_after_label:
5011 if (tok == '}') {
5012 tcc_warning("deprecated use of label at end of compound statement");
5013 } else {
5014 if (is_expr)
5015 vpop();
5016 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
5018 } else {
5019 /* expression case */
5020 if (tok != ';') {
5021 if (is_expr) {
5022 vpop();
5023 gexpr();
5024 } else {
5025 gexpr();
5026 vpop();
5029 skip(';');
5034 /* t is the array or struct type. c is the array or struct
5035 address. cur_index/cur_field is the pointer to the current
5036 value. 'size_only' is true if only size info is needed (only used
5037 in arrays) */
5038 static void decl_designator(CType *type, Section *sec, unsigned long c,
5039 int *cur_index, Sym **cur_field,
5040 int size_only)
5042 Sym *s, *f;
5043 int notfirst, index, index_last, align, l, nb_elems, elem_size;
5044 CType type1;
5046 notfirst = 0;
5047 elem_size = 0;
5048 nb_elems = 1;
5049 if (gnu_ext && (l = is_label()) != 0)
5050 goto struct_field;
5051 s = type->ref;
5052 while (tok == '[' || tok == '.') {
5053 if (tok == '[') {
5054 if (!(type->t & VT_ARRAY))
5055 expect("array type");
5056 next();
5057 index = expr_const();
5058 if (index < 0 || (s->c >= 0 && index >= s->c))
5059 expect("invalid index");
5060 if (tok == TOK_DOTS && gnu_ext) {
5061 next();
5062 index_last = expr_const();
5063 if (index_last < 0 ||
5064 (s->c >= 0 && index_last >= s->c) ||
5065 index_last < index)
5066 expect("invalid index");
5067 } else {
5068 index_last = index;
5070 skip(']');
5071 if (!notfirst)
5072 *cur_index = index_last;
5073 type = pointed_type(type);
5074 elem_size = type_size(type, &align);
5075 c += index * elem_size;
5076 /* NOTE: we only support ranges for last designator */
5077 nb_elems = index_last - index + 1;
5078 if (nb_elems != 1) {
5079 notfirst = 1;
5080 break;
5082 } else {
5083 next();
5084 l = tok;
5085 next();
5086 struct_field:
5087 if ((type->t & VT_BTYPE) != VT_STRUCT)
5088 expect("struct/union type");
5089 l |= SYM_FIELD;
5090 f = s->next;
5091 while (f) {
5092 if (f->v == l)
5093 break;
5094 f = f->next;
5096 if (!f)
5097 expect("field");
5098 if (!notfirst)
5099 *cur_field = f;
5100 /* XXX: fix this mess by using explicit storage field */
5101 type1 = f->type;
5102 type1.t |= (type->t & ~VT_TYPE);
5103 type = &type1;
5104 c += f->c;
5106 notfirst = 1;
5108 if (notfirst) {
5109 if (tok == '=') {
5110 next();
5111 } else {
5112 if (!gnu_ext)
5113 expect("=");
5115 } else {
5116 if (type->t & VT_ARRAY) {
5117 index = *cur_index;
5118 if (s->c >= 0 && index >= s->c){
5119 if(!size_only)
5120 tcc_warning("excess elements in array initializer");
5121 type = NULL;
5122 size_only = 1;
5123 }else{
5124 type = pointed_type(type);
5125 c += index * type_size(type, &align);
5127 } else {
5128 f = *cur_field;
5129 if (f){
5130 /* XXX: fix this mess by using explicit storage field */
5131 type1 = f->type;
5132 type1.t |= (type->t & ~VT_TYPE);
5133 type = &type1;
5134 c += f->c;
5135 }else{
5136 if(!size_only)
5137 tcc_warning("excess elements in %s initializer",
5138 get_tok_str(s->type.t, NULL));
5139 type = NULL;
5140 size_only = 1;
5144 decl_initializer(type, sec, c, 0, size_only);
5146 /* XXX: make it more general */
5147 if (!size_only && nb_elems > 1) {
5148 unsigned long c_end;
5149 uint8_t *src, *dst;
5150 int i;
5152 if (!sec)
5153 tcc_error("range init not supported yet for dynamic storage");
5154 c_end = c + nb_elems * elem_size;
5155 if (c_end > sec->data_allocated)
5156 section_realloc(sec, c_end);
5157 src = sec->data + c;
5158 dst = src;
5159 for(i = 1; i < nb_elems; i++) {
5160 dst += elem_size;
5161 memcpy(dst, src, elem_size);
5166 #define EXPR_VAL 0
5167 #define EXPR_CONST 1
5168 #define EXPR_ANY 2
5170 /* store a value or an expression directly in global data or in local array */
5171 static void init_putv(CType *type, Section *sec, unsigned long c,
5172 int v, int expr_type)
5174 int saved_global_expr, bt, bit_pos, bit_size;
5175 void *ptr;
5176 unsigned long long bit_mask;
5177 CType dtype;
5179 switch(expr_type) {
5180 case EXPR_VAL:
5181 vpushi(v);
5182 break;
5183 case EXPR_CONST:
5184 /* compound literals must be allocated globally in this case */
5185 saved_global_expr = global_expr;
5186 global_expr = 1;
5187 expr_const1();
5188 global_expr = saved_global_expr;
5189 /* NOTE: symbols are accepted */
5190 if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
5191 tcc_error("initializer element is not constant");
5192 break;
5193 case EXPR_ANY:
5194 expr_eq();
5195 break;
5198 dtype = *type;
5199 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
5201 if (sec) {
5202 /* XXX: not portable */
5203 /* XXX: generate error if incorrect relocation */
5204 gen_assign_cast(&dtype);
5205 bt = type->t & VT_BTYPE;
5206 /* we'll write at most 12 bytes */
5207 if (c + 12 > sec->data_allocated) {
5208 section_realloc(sec, c + 12);
5210 ptr = sec->data + c;
5211 /* XXX: make code faster ? */
5212 if (!(type->t & VT_BITFIELD)) {
5213 bit_pos = 0;
5214 bit_size = 32;
5215 bit_mask = -1LL;
5216 } else {
5217 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5218 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
5219 bit_mask = (1LL << bit_size) - 1;
5221 if ((vtop->r & VT_SYM) &&
5222 (bt == VT_BYTE ||
5223 bt == VT_SHORT ||
5224 bt == VT_DOUBLE ||
5225 bt == VT_LDOUBLE ||
5226 bt == VT_LLONG ||
5227 (bt == VT_INT && bit_size != 32)))
5228 tcc_error("initializer element is not computable at load time");
5229 switch(bt) {
5230 case VT_BOOL:
5231 vtop->c.i = (vtop->c.i != 0);
5232 case VT_BYTE:
5233 *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5234 break;
5235 case VT_SHORT:
5236 *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5237 break;
5238 case VT_DOUBLE:
5239 *(double *)ptr = vtop->c.d;
5240 break;
5241 case VT_LDOUBLE:
5242 *(long double *)ptr = vtop->c.ld;
5243 break;
5244 case VT_LLONG:
5245 *(long long *)ptr |= (vtop->c.ll & bit_mask) << bit_pos;
5246 break;
5247 case VT_PTR:
5248 if (vtop->r & VT_SYM) {
5249 greloc(sec, vtop->sym, c, R_DATA_PTR);
5251 *(addr_t *)ptr |= (vtop->c.ptr_offset & bit_mask) << bit_pos;
5252 break;
5253 default:
5254 if (vtop->r & VT_SYM) {
5255 greloc(sec, vtop->sym, c, R_DATA_PTR);
5257 *(int *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5258 break;
5260 vtop--;
5261 } else {
5262 vset(&dtype, VT_LOCAL|VT_LVAL, c);
5263 vswap();
5264 vstore();
5265 vpop();
5269 /* put zeros for variable based init */
5270 static void init_putz(CType *t, Section *sec, unsigned long c, int size)
5272 if (sec) {
5273 /* nothing to do because globals are already set to zero */
5274 } else {
5275 vpush_global_sym(&func_old_type, TOK_memset);
5276 vseti(VT_LOCAL, c);
5277 #ifdef TCC_TARGET_ARM
5278 vpushs(size);
5279 vpushi(0);
5280 #else
5281 vpushi(0);
5282 vpushs(size);
5283 #endif
5284 gfunc_call(3);
5288 /* 't' contains the type and storage info. 'c' is the offset of the
5289 object in section 'sec'. If 'sec' is NULL, it means stack based
5290 allocation. 'first' is true if array '{' must be read (multi
5291 dimension implicit array init handling). 'size_only' is true if
5292 size only evaluation is wanted (only for arrays). */
5293 static void decl_initializer(CType *type, Section *sec, unsigned long c,
5294 int first, int size_only)
5296 int index, array_length, n, no_oblock, nb, parlevel, parlevel1, i;
5297 int size1, align1, expr_type;
5298 Sym *s, *f;
5299 CType *t1;
5301 if(!type)
5302 goto Ignore;
5303 if (type->t & VT_VLA) {
5304 int a;
5306 /* save current stack pointer */
5307 if (vla_flags & VLA_NEED_NEW_FRAME) {
5308 vla_sp_save();
5309 vla_flags = VLA_IN_SCOPE;
5310 vla_sp_loc = &vla_sp_loc_tmp;
5313 vla_runtime_type_size(type, &a);
5314 gen_vla_alloc(type, a);
5315 vset(type, VT_LOCAL|VT_LVAL, c);
5316 vswap();
5317 vstore();
5318 vpop();
5319 } else if (type->t & VT_ARRAY) {
5320 s = type->ref;
5321 n = s->c;
5322 array_length = 0;
5323 t1 = pointed_type(type);
5324 size1 = type_size(t1, &align1);
5326 no_oblock = 1;
5327 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
5328 tok == '{') {
5329 if (tok != '{')
5330 tcc_error("character array initializer must be a literal,"
5331 " optionally enclosed in braces");
5332 skip('{');
5333 no_oblock = 0;
5336 /* only parse strings here if correct type (otherwise: handle
5337 them as ((w)char *) expressions */
5338 if ((tok == TOK_LSTR &&
5339 #ifdef TCC_TARGET_PE
5340 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
5341 #else
5342 (t1->t & VT_BTYPE) == VT_INT
5343 #endif
5344 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
5345 while (tok == TOK_STR || tok == TOK_LSTR) {
5346 int cstr_len, ch;
5347 CString *cstr;
5349 cstr = tokc.cstr;
5350 /* compute maximum number of chars wanted */
5351 if (tok == TOK_STR)
5352 cstr_len = cstr->size;
5353 else
5354 cstr_len = cstr->size / sizeof(nwchar_t);
5355 cstr_len--;
5356 nb = cstr_len;
5357 if (n >= 0 && nb > (n - array_length))
5358 nb = n - array_length;
5359 if (!size_only) {
5360 if (cstr_len > nb)
5361 tcc_warning("initializer-string for array is too long");
5362 /* in order to go faster for common case (char
5363 string in global variable, we handle it
5364 specifically */
5365 if (sec && tok == TOK_STR && size1 == 1) {
5366 memcpy(sec->data + c + array_length, cstr->data, nb);
5367 } else {
5368 for(i=0;i<nb;i++) {
5369 if (tok == TOK_STR)
5370 ch = ((unsigned char *)cstr->data)[i];
5371 else
5372 ch = ((nwchar_t *)cstr->data)[i];
5373 init_putv(t1, sec, c + (array_length + i) * size1,
5374 ch, EXPR_VAL);
5378 array_length += nb;
5379 next();
5381 /* only add trailing zero if enough storage (no
5382 warning in this case since it is standard) */
5383 if (n < 0 || array_length < n) {
5384 if (!size_only) {
5385 init_putv(t1, sec, c + (array_length * size1), 0, EXPR_VAL);
5387 array_length++;
5389 } else {
5390 index = 0;
5391 while (tok != '}') {
5392 decl_designator(type, sec, c, &index, NULL, size_only);
5393 /* must put zero in holes (note that doing it that way
5394 ensures that it even works with designators) */
5395 if (!is_putz && array_length < index)
5396 is_putz = 1;
5397 index++;
5398 if (index > array_length)
5399 array_length = index;
5400 /* special test for multi dimensional arrays (may not
5401 be strictly correct if designators are used at the
5402 same time) */
5403 if (index >= n && no_oblock)
5404 break;
5405 if (tok == '}')
5406 break;
5407 skip(',');
5410 if (!no_oblock)
5411 skip('}');
5412 /* put zeros at the end */
5413 if (!is_putz && n >= 0 && array_length < n)
5414 is_putz = 1;
5415 /* patch type size if needed */
5416 if (n < 0)
5417 s->c = array_length;
5418 } else if ((type->t & VT_BTYPE) == VT_STRUCT &&
5419 (sec || !first || tok == '{')) {
5420 int par_count;
5422 /* NOTE: the previous test is a specific case for automatic
5423 struct/union init */
5424 /* XXX: union needs only one init */
5426 /* XXX: this test is incorrect for local initializers
5427 beginning with ( without {. It would be much more difficult
5428 to do it correctly (ideally, the expression parser should
5429 be used in all cases) */
5430 par_count = 0;
5431 if (tok == '(') {
5432 AttributeDef ad1;
5433 CType type1;
5434 next();
5435 while (tok == '(') {
5436 par_count++;
5437 next();
5439 if (!parse_btype(&type1, &ad1))
5440 expect("cast");
5441 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
5442 #if 0
5443 if (!is_assignable_types(type, &type1))
5444 tcc_error("invalid type for cast");
5445 #endif
5446 skip(')');
5448 no_oblock = 1;
5449 if (first || tok == '{') {
5450 skip('{');
5451 no_oblock = 0;
5453 s = type->ref;
5454 f = s->next;
5455 array_length = 0;
5456 index = 0;
5457 n = s->c;
5458 while (tok != '}') {
5459 decl_designator(type, sec, c, NULL, &f, size_only);
5460 if(f){
5461 index = f->c;
5462 if (!is_putz && array_length < index)
5463 is_putz = 1;
5464 index = index + type_size(&f->type, &align1);
5465 if (index > array_length)
5466 array_length = index;
5468 /* gr: skip fields from same union - ugly. */
5469 while (f->next) {
5470 ///printf("index: %2d %08x -- %2d %08x\n", f->c, f->type.t, f->next->c, f->next->type.t);
5471 /* test for same offset */
5472 if (f->next->c != f->c)
5473 break;
5474 /* if yes, test for bitfield shift */
5475 if ((f->type.t & VT_BITFIELD) && (f->next->type.t & VT_BITFIELD)) {
5476 int bit_pos_1 = (f->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5477 int bit_pos_2 = (f->next->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5478 //printf("bitfield %d %d\n", bit_pos_1, bit_pos_2);
5479 if (bit_pos_1 != bit_pos_2)
5480 break;
5482 f = f->next;
5485 f = f->next;
5486 if (no_oblock && f == NULL)
5487 break;
5489 if (tok == '}')
5490 break;
5491 skip(',');
5493 if (!no_oblock)
5494 skip('}');
5495 /* put zeros at the end */
5496 if (!is_putz && array_length < n)
5497 is_putz = 1;
5498 while (par_count) {
5499 skip(')');
5500 par_count--;
5502 } else if (tok == '{') {
5503 next();
5504 decl_initializer(type, sec, c, first, size_only);
5505 skip('}');
5506 } else if (size_only) {
5507 Ignore:
5508 /* just skip expression */
5509 parlevel = parlevel1 = 0;
5510 while ((parlevel > 0 || parlevel1 > 0 ||
5511 (tok != '}' && tok != ',')) && tok != -1) {
5512 if (tok == '(')
5513 parlevel++;
5514 else if (tok == ')')
5515 parlevel--;
5516 else if (tok == '{')
5517 parlevel1++;
5518 else if (tok == '}')
5519 parlevel1--;
5520 next();
5522 } else {
5523 /* currently, we always use constant expression for globals
5524 (may change for scripting case) */
5525 expr_type = EXPR_CONST;
5526 if (!sec)
5527 expr_type = EXPR_ANY;
5528 init_putv(type, sec, c, 0, expr_type);
5532 /* parse an initializer for type 't' if 'has_init' is non zero, and
5533 allocate space in local or global data space ('r' is either
5534 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
5535 variable 'v' with an associated name represented by 'asm_label' of
5536 scope 'scope' is declared before initializers are parsed. If 'v' is
5537 zero, then a reference to the new object is put in the value stack.
5538 If 'has_init' is 2, a special parsing is done to handle string
5539 constants. */
5540 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
5541 int has_init, int v, char *asm_label,
5542 int scope)
5544 int size, align, addr, data_offset;
5545 int level;
5546 ParseState saved_parse_state = {0};
5547 TokenString init_str;
5548 Section *sec;
5549 Sym *flexible_array;
5551 flexible_array = NULL;
5552 is_putz = 0;
5553 if ((type->t & VT_BTYPE) == VT_STRUCT) {
5554 Sym *field = type->ref->next;
5555 if (field) {
5556 while (field->next)
5557 field = field->next;
5558 if (field->type.t & VT_ARRAY && field->type.ref->c < 0)
5559 flexible_array = field;
5563 size = type_size(type, &align);
5564 /* If unknown size, we must evaluate it before
5565 evaluating initializers because
5566 initializers can generate global data too
5567 (e.g. string pointers or ISOC99 compound
5568 literals). It also simplifies local
5569 initializers handling */
5570 tok_str_new(&init_str);
5571 if (size < 0 || ((((type->t & VT_BTYPE) == VT_STRUCT) || (type->t & VT_ARRAY)) &&
5572 has_init && (tok < TOK_IDENT))){
5573 if (!has_init)
5574 tcc_error("unknown type size");
5575 /* get all init string */
5576 if (has_init == 2) {
5577 /* only get strings */
5578 while (tok == TOK_STR || tok == TOK_LSTR) {
5579 tok_str_add_tok(&init_str);
5580 next();
5582 } else {
5583 level = 0;
5584 while (level > 0 || (tok != ',' && tok != ';')) {
5585 if (tok < 0)
5586 tcc_error("unexpected end of file in initializer");
5587 tok_str_add_tok(&init_str);
5588 if (tok == '{')
5589 level++;
5590 else if (tok == '}') {
5591 level--;
5592 if (level <= 0) {
5593 next();
5594 break;
5597 next();
5600 tok_str_add(&init_str, -1);
5601 tok_str_add(&init_str, 0);
5603 /* compute size */
5604 save_parse_state(&saved_parse_state);
5606 macro_ptr = init_str.str;
5607 next();
5608 decl_initializer(type, NULL, 0, 1, 1);
5609 /* prepare second initializer parsing */
5610 macro_ptr = init_str.str;
5611 next();
5613 /* if still unknown size, error */
5614 size = type_size(type, &align);
5615 if (size < 0)
5616 tcc_error("unknown type size");
5618 if (flexible_array)
5619 size += flexible_array->type.ref->c * pointed_size(&flexible_array->type);
5620 /* take into account specified alignment if bigger */
5621 if (ad->a.aligned) {
5622 if (ad->a.aligned > align)
5623 align = ad->a.aligned;
5624 } else if (ad->a.packed) {
5625 align = 1;
5627 if ((r & VT_VALMASK) == VT_LOCAL) {
5628 sec = NULL;
5629 #ifdef CONFIG_TCC_BCHECK
5630 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5631 loc--;
5633 #endif
5634 loc = (loc - size) & -align;
5635 addr = loc;
5636 #ifdef CONFIG_TCC_BCHECK
5637 /* handles bounds */
5638 /* XXX: currently, since we do only one pass, we cannot track
5639 '&' operators, so we add only arrays */
5640 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5641 unsigned long *bounds_ptr;
5642 /* add padding between regions */
5643 loc--;
5644 /* then add local bound info */
5645 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(unsigned long));
5646 bounds_ptr[0] = addr;
5647 bounds_ptr[1] = size;
5649 #endif
5650 if (v) {
5651 /* local variable */
5652 sym_push(v, type, r, addr);
5653 } else {
5654 /* push local reference */
5655 vset(type, r, addr);
5657 } else {
5658 Sym *sym;
5660 sym = NULL;
5661 if (v && scope == VT_CONST) {
5662 /* see if the symbol was already defined */
5663 sym = sym_find(v);
5664 if (sym) {
5665 if (!is_compatible_types(&sym->type, type))
5666 tcc_error("incompatible types for redefinition of '%s'",
5667 get_tok_str(v, NULL));
5668 if (sym->type.t & VT_EXTERN) {
5669 /* if the variable is extern, it was not allocated */
5670 sym->type.t &= ~VT_EXTERN;
5671 /* set array size if it was omitted in extern
5672 declaration */
5673 if ((sym->type.t & VT_ARRAY) &&
5674 sym->type.ref->c < 0 &&
5675 type->ref->c >= 0)
5676 sym->type.ref->c = type->ref->c;
5677 } else {
5678 /* we accept several definitions of the same
5679 global variable. this is tricky, because we
5680 must play with the SHN_COMMON type of the symbol */
5681 /* XXX: should check if the variable was already
5682 initialized. It is incorrect to initialized it
5683 twice */
5684 /* no init data, we won't add more to the symbol */
5685 if (!has_init)
5686 goto no_alloc;
5691 /* allocate symbol in corresponding section */
5692 sec = ad->section;
5693 if (!sec) {
5694 if (has_init)
5695 sec = data_section;
5696 else if (tcc_state->nocommon)
5697 sec = bss_section;
5699 if (sec) {
5700 data_offset = sec->data_offset;
5701 data_offset = (data_offset + align - 1) & -align;
5702 addr = data_offset;
5703 /* very important to increment global pointer at this time
5704 because initializers themselves can create new initializers */
5705 data_offset += size;
5706 #ifdef CONFIG_TCC_BCHECK
5707 /* add padding if bound check */
5708 if (tcc_state->do_bounds_check)
5709 data_offset++;
5710 #endif
5711 sec->data_offset = data_offset;
5712 /* allocate section space to put the data */
5713 if (sec->sh_type != SHT_NOBITS &&
5714 data_offset > sec->data_allocated)
5715 section_realloc(sec, data_offset);
5716 /* align section if needed */
5717 if (align > sec->sh_addralign)
5718 sec->sh_addralign = align;
5719 } else {
5720 addr = 0; /* avoid warning */
5723 if (v) {
5724 if (scope != VT_CONST || !sym) {
5725 sym = sym_push(v, type, r | VT_SYM, 0);
5726 sym->asm_label = asm_label;
5728 /* update symbol definition */
5729 if (sec) {
5730 put_extern_sym(sym, sec, addr, size);
5731 } else {
5732 ElfW(Sym) *esym;
5733 /* put a common area */
5734 put_extern_sym(sym, NULL, align, size);
5735 /* XXX: find a nicer way */
5736 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
5737 esym->st_shndx = SHN_COMMON;
5739 } else {
5740 /* push global reference */
5741 sym = get_sym_ref(type, sec, addr, size);
5742 vpushsym(type, sym);
5744 /* patch symbol weakness */
5745 if (type->t & VT_WEAK)
5746 weaken_symbol(sym);
5747 apply_visibility(sym, type);
5748 #ifdef CONFIG_TCC_BCHECK
5749 /* handles bounds now because the symbol must be defined
5750 before for the relocation */
5751 if (tcc_state->do_bounds_check) {
5752 unsigned long *bounds_ptr;
5754 greloc(bounds_section, sym, bounds_section->data_offset, R_DATA_PTR);
5755 /* then add global bound info */
5756 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(long));
5757 bounds_ptr[0] = 0; /* relocated */
5758 bounds_ptr[1] = size;
5760 #endif
5762 if (has_init || (type->t & VT_VLA)) {
5763 if(is_putz)
5764 init_putz(type, sec, addr, size);
5765 decl_initializer(type, sec, addr, 1, 0);
5766 /* restore parse state if needed */
5767 if (init_str.str) {
5768 tok_str_free(init_str.str);
5769 restore_parse_state(&saved_parse_state);
5771 /* patch flexible array member size back to -1, */
5772 /* for possible subsequent similar declarations */
5773 if (flexible_array)
5774 flexible_array->type.ref->c = -1;
5776 no_alloc: ;
5779 static void put_func_debug(Sym *sym)
5781 char buf[512];
5783 /* stabs info */
5784 /* XXX: we put here a dummy type */
5785 snprintf(buf, sizeof(buf), "%s:%c1",
5786 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
5787 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
5788 cur_text_section, sym->c);
5789 /* //gr gdb wants a line at the function */
5790 put_stabn(N_SLINE, 0, file->line_num, 0);
5791 last_ind = 0;
5792 last_line_num = 0;
5795 /* parse an old style function declaration list */
5796 /* XXX: check multiple parameter */
5797 static void func_decl_list(Sym *func_sym)
5799 AttributeDef ad;
5800 int v;
5801 Sym *s;
5802 CType btype, type;
5804 /* parse each declaration */
5805 while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF &&
5806 tok != TOK_ASM1 && tok != TOK_ASM2 && tok != TOK_ASM3) {
5807 if (!parse_btype(&btype, &ad))
5808 expect("declaration list");
5809 if (((btype.t & VT_BTYPE) == VT_ENUM ||
5810 (btype.t & VT_BTYPE) == VT_STRUCT) &&
5811 tok == ';') {
5812 /* we accept no variable after */
5813 } else {
5814 for(;;) {
5815 type = btype;
5816 type_decl(&type, &ad, &v, TYPE_DIRECT);
5817 /* find parameter in function parameter list */
5818 s = func_sym->next;
5819 while (s != NULL) {
5820 if ((s->v & ~SYM_FIELD) == v)
5821 goto found;
5822 s = s->next;
5824 tcc_error("declaration for parameter '%s' but no such parameter",
5825 get_tok_str(v, NULL));
5826 found:
5827 /* check that no storage specifier except 'register' was given */
5828 if (type.t & VT_STORAGE)
5829 tcc_error("storage class specified for '%s'", get_tok_str(v, NULL));
5830 convert_parameter_type(&type);
5831 /* we can add the type (NOTE: it could be local to the function) */
5832 s->type = type;
5833 /* accept other parameters */
5834 if (tok == ',')
5835 next();
5836 else
5837 break;
5840 skip(';');
5844 /* parse a function defined by symbol 'sym' and generate its code in
5845 'cur_text_section' */
5846 static void gen_function(Sym *sym)
5848 int saved_nocode_wanted = nocode_wanted;
5849 nocode_wanted = 0;
5850 ind = cur_text_section->data_offset;
5851 /* NOTE: we patch the symbol size later */
5852 put_extern_sym(sym, cur_text_section, ind, 0);
5853 funcname = get_tok_str(sym->v, NULL);
5854 func_ind = ind;
5855 /* Initialize VLA state */
5856 vla_sp_loc = &vla_sp_root_loc;
5857 vla_flags = VLA_NEED_NEW_FRAME;
5858 /* put debug symbol */
5859 if (tcc_state->do_debug)
5860 put_func_debug(sym);
5861 /* push a dummy symbol to enable local sym storage */
5862 sym_push2(&local_stack, SYM_FIELD, 0, 0);
5863 gfunc_prolog(&sym->type);
5864 #ifdef CONFIG_TCC_BCHECK
5865 if (tcc_state->do_bounds_check
5866 && !strcmp(get_tok_str(sym->v, NULL), "main")) {
5867 int i;
5869 sym = local_stack;
5870 for (i = 0, sym = local_stack; i < 2; i++, sym = sym->prev) {
5871 if (sym->v & SYM_FIELD || sym->prev->v & SYM_FIELD)
5872 break;
5873 vpush_global_sym(&func_old_type, TOK___bound_main_arg);
5874 vset(&sym->type, sym->r, sym->c);
5875 gfunc_call(1);
5878 #endif
5879 rsym = 0;
5880 block(NULL, NULL, NULL, NULL, 0, 0);
5881 gsym(rsym);
5882 gfunc_epilog();
5883 cur_text_section->data_offset = ind;
5884 label_pop(&global_label_stack, NULL);
5885 /* reset local stack */
5886 scope_stack_bottom = NULL;
5887 sym_pop(&local_stack, NULL);
5888 /* end of function */
5889 /* patch symbol size */
5890 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
5891 ind - func_ind;
5892 /* patch symbol weakness (this definition overrules any prototype) */
5893 if (sym->type.t & VT_WEAK)
5894 weaken_symbol(sym);
5895 apply_visibility(sym, &sym->type);
5896 if (tcc_state->do_debug) {
5897 put_stabn(N_FUN, 0, 0, ind - func_ind);
5899 /* It's better to crash than to generate wrong code */
5900 cur_text_section = NULL;
5901 funcname = ""; /* for safety */
5902 func_vt.t = VT_VOID; /* for safety */
5903 func_var = 0; /* for safety */
5904 ind = 0; /* for safety */
5905 nocode_wanted = saved_nocode_wanted;
5908 ST_FUNC void gen_inline_functions(void)
5910 Sym *sym;
5911 int *str, inline_generated, i;
5912 struct InlineFunc *fn;
5914 /* iterate while inline function are referenced */
5915 for(;;) {
5916 inline_generated = 0;
5917 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
5918 fn = tcc_state->inline_fns[i];
5919 sym = fn->sym;
5920 if (sym && sym->c) {
5921 /* the function was used: generate its code and
5922 convert it to a normal function */
5923 str = fn->token_str;
5924 fn->sym = NULL;
5925 if (file)
5926 pstrcpy(file->filename, sizeof file->filename, fn->filename);
5927 sym->r = VT_SYM | VT_CONST;
5928 sym->type.t &= ~VT_INLINE;
5930 macro_ptr = str;
5931 next();
5932 cur_text_section = text_section;
5933 gen_function(sym);
5934 macro_ptr = NULL; /* fail safe */
5936 inline_generated = 1;
5939 if (!inline_generated)
5940 break;
5942 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
5943 fn = tcc_state->inline_fns[i];
5944 str = fn->token_str;
5945 tok_str_free(str);
5947 dynarray_reset(&tcc_state->inline_fns, &tcc_state->nb_inline_fns);
5950 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
5951 static int decl0(int l, int is_for_loop_init)
5953 int v, has_init, r;
5954 CType type, btype;
5955 Sym *sym;
5956 AttributeDef ad;
5958 while (1) {
5959 if (!parse_btype(&btype, &ad)) {
5960 if (is_for_loop_init)
5961 return 0;
5962 /* skip redundant ';' */
5963 /* XXX: find more elegant solution */
5964 if (tok == ';') {
5965 next();
5966 continue;
5968 if (l == VT_CONST &&
5969 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
5970 /* global asm block */
5971 asm_global_instr();
5972 continue;
5974 /* special test for old K&R protos without explicit int
5975 type. Only accepted when defining global data */
5976 if (l == VT_LOCAL || tok < TOK_DEFINE)
5977 break;
5978 btype.t = VT_INT;
5980 if (((btype.t & VT_BTYPE) == VT_ENUM ||
5981 (btype.t & VT_BTYPE) == VT_STRUCT) &&
5982 tok == ';') {
5983 /* we accept no variable after */
5984 next();
5985 continue;
5987 while (1) { /* iterate thru each declaration */
5988 char *asm_label; // associated asm label
5989 type = btype;
5990 type_decl(&type, &ad, &v, TYPE_DIRECT);
5991 #if 0
5993 char buf[500];
5994 type_to_str(buf, sizeof(buf), t, get_tok_str(v, NULL));
5995 printf("type = '%s'\n", buf);
5997 #endif
5998 if ((type.t & VT_BTYPE) == VT_FUNC) {
5999 if ((type.t & VT_STATIC) && (l == VT_LOCAL)) {
6000 tcc_error("function without file scope cannot be static");
6002 /* if old style function prototype, we accept a
6003 declaration list */
6004 sym = type.ref;
6005 if (sym->c == FUNC_OLD)
6006 func_decl_list(sym);
6009 asm_label = NULL;
6010 if (gnu_ext && (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
6011 CString astr;
6013 asm_label_instr(&astr);
6014 asm_label = tcc_strdup(astr.data);
6015 cstr_free(&astr);
6017 /* parse one last attribute list, after asm label */
6018 parse_attribute(&ad);
6021 if (ad.a.weak)
6022 type.t |= VT_WEAK;
6023 #ifdef TCC_TARGET_PE
6024 if (ad.a.func_import)
6025 type.t |= VT_IMPORT;
6026 if (ad.a.func_export)
6027 type.t |= VT_EXPORT;
6028 #endif
6029 type.t |= ad.a.visibility << VT_VIS_SHIFT;
6031 if (tok == '{') {
6032 if (l == VT_LOCAL)
6033 tcc_error("cannot use local functions");
6034 if ((type.t & VT_BTYPE) != VT_FUNC)
6035 expect("function definition");
6037 /* reject abstract declarators in function definition */
6038 sym = type.ref;
6039 while ((sym = sym->next) != NULL)
6040 if (!(sym->v & ~SYM_FIELD))
6041 expect("identifier");
6043 /* XXX: cannot do better now: convert extern line to static inline */
6044 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
6045 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
6047 sym = sym_find(v);
6048 if (sym) {
6049 Sym *ref;
6050 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
6051 goto func_error1;
6053 ref = sym->type.ref;
6054 if (0 == ref->a.func_proto)
6055 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
6057 /* use func_call from prototype if not defined */
6058 if (ref->a.func_call != FUNC_CDECL
6059 && type.ref->a.func_call == FUNC_CDECL)
6060 type.ref->a.func_call = ref->a.func_call;
6062 /* use export from prototype */
6063 if (ref->a.func_export)
6064 type.ref->a.func_export = 1;
6066 /* use static from prototype */
6067 if (sym->type.t & VT_STATIC)
6068 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
6070 /* If the definition has no visibility use the
6071 one from prototype. */
6072 if (! (type.t & VT_VIS_MASK))
6073 type.t |= sym->type.t & VT_VIS_MASK;
6075 if (!is_compatible_types(&sym->type, &type)) {
6076 func_error1:
6077 tcc_error("incompatible types for redefinition of '%s'",
6078 get_tok_str(v, NULL));
6080 type.ref->a.func_proto = 0;
6081 /* if symbol is already defined, then put complete type */
6082 sym->type = type;
6083 } else {
6084 /* put function symbol */
6085 sym = global_identifier_push(v, type.t, 0);
6086 sym->type.ref = type.ref;
6089 /* static inline functions are just recorded as a kind
6090 of macro. Their code will be emitted at the end of
6091 the compilation unit only if they are used */
6092 if ((type.t & (VT_INLINE | VT_STATIC)) ==
6093 (VT_INLINE | VT_STATIC)) {
6094 TokenString func_str;
6095 int block_level;
6096 struct InlineFunc *fn;
6097 const char *filename;
6099 tok_str_new(&func_str);
6101 block_level = 0;
6102 for(;;) {
6103 int t;
6104 if (tok == TOK_EOF)
6105 tcc_error("unexpected end of file");
6106 tok_str_add_tok(&func_str);
6107 t = tok;
6108 next();
6109 if (t == '{') {
6110 block_level++;
6111 } else if (t == '}') {
6112 block_level--;
6113 if (block_level == 0)
6114 break;
6117 tok_str_add(&func_str, -1);
6118 tok_str_add(&func_str, 0);
6119 filename = file ? file->filename : "";
6120 fn = tcc_malloc(sizeof *fn + strlen(filename));
6121 strcpy(fn->filename, filename);
6122 fn->sym = sym;
6123 fn->token_str = func_str.str;
6124 dynarray_add((void ***)&tcc_state->inline_fns, &tcc_state->nb_inline_fns, fn);
6126 } else {
6127 /* compute text section */
6128 cur_text_section = ad.section;
6129 if (!cur_text_section)
6130 cur_text_section = text_section;
6131 sym->r = VT_SYM | VT_CONST;
6132 gen_function(sym);
6134 break;
6135 } else {
6136 if (btype.t & VT_TYPEDEF) {
6137 /* save typedefed type */
6138 /* XXX: test storage specifiers ? */
6139 sym = sym_push(v, &type, 0, 0);
6140 sym->a = ad.a;
6141 sym->type.t |= VT_TYPEDEF;
6142 } else {
6143 r = 0;
6144 if ((type.t & VT_BTYPE) == VT_FUNC) {
6145 /* external function definition */
6146 /* specific case for func_call attribute */
6147 ad.a.func_proto = 1;
6148 type.ref->a = ad.a;
6149 } else if (!(type.t & VT_ARRAY)) {
6150 /* not lvalue if array */
6151 r |= lvalue_type(type.t);
6153 has_init = (tok == '=');
6154 if (has_init && (type.t & VT_VLA))
6155 tcc_error("Variable length array cannot be initialized");
6156 if ((btype.t & VT_EXTERN) || ((type.t & VT_BTYPE) == VT_FUNC) ||
6157 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
6158 !has_init && l == VT_CONST && type.ref->c < 0)) {
6159 /* external variable or function */
6160 /* NOTE: as GCC, uninitialized global static
6161 arrays of null size are considered as
6162 extern */
6163 sym = external_sym(v, &type, r, asm_label);
6165 if (ad.alias_target) {
6166 Section tsec;
6167 Elf32_Sym *esym;
6168 Sym *alias_target;
6170 alias_target = sym_find(ad.alias_target);
6171 if (!alias_target || !alias_target->c)
6172 tcc_error("unsupported forward __alias__ attribute");
6173 esym = &((Elf32_Sym *)symtab_section->data)[alias_target->c];
6174 tsec.sh_num = esym->st_shndx;
6175 put_extern_sym2(sym, &tsec, esym->st_value, esym->st_size, 0);
6177 } else {
6178 type.t |= (btype.t & VT_STATIC); /* Retain "static". */
6179 if (type.t & VT_STATIC)
6180 r |= VT_CONST;
6181 else
6182 r |= l;
6183 if (has_init)
6184 next();
6185 decl_initializer_alloc(&type, &ad, r, has_init, v, asm_label, l);
6188 if (tok != ',') {
6189 if (is_for_loop_init)
6190 return 1;
6191 skip(';');
6192 break;
6194 next();
6196 ad.a.aligned = 0;
6199 return 0;
6202 ST_FUNC void decl(int l)
6204 decl0(l, 0);