gen_putz () and struct_copy (), is to reduce the third-party call that
[tinycc.git] / tccgen.c
blobb8721b12b4989cb88e2631aa16b91862b78ee818
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, ex_rc;
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;
73 ST_DATA int pop_stack;
75 ST_DATA CType char_pointer_type, func_old_type, int_type, size_type;
77 /* ------------------------------------------------------------------------- */
78 static void gen_cast(CType *type);
79 static inline CType *pointed_type(CType *type);
80 static int is_compatible_types(CType *type1, CType *type2);
81 static int parse_btype(CType *type, AttributeDef *ad);
82 static void type_decl(CType *type, AttributeDef *ad, int *v, int td);
83 static void parse_expr_type(CType *type);
84 static void decl_initializer(CType *type, Section *sec, unsigned long c, int first, int size_only);
85 static void block(int *bsym, int *csym, int *case_sym, int *def_sym, int case_reg, int is_expr);
86 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r, int has_init, int v, char *asm_label, int scope);
87 static int decl0(int l, int is_for_loop_init);
88 static void expr_eq(void);
89 static void unary_type(CType *type);
90 static void vla_runtime_type_size(CType *type, int *a);
91 static void vla_sp_save(void);
92 static int is_compatible_parameter_types(CType *type1, CType *type2);
93 static void expr_type(CType *type);
94 ST_FUNC void vpush64(int ty, unsigned long long v);
95 ST_FUNC void vpush(CType *type);
96 ST_FUNC int gtst(int inv, int t);
97 ST_FUNC int is_btype_size(int bt);
99 ST_INLN int is_float(int t)
101 int bt;
102 bt = t & VT_BTYPE;
103 return bt == VT_LDOUBLE || bt == VT_DOUBLE || bt == VT_FLOAT || bt == VT_QFLOAT;
106 /* we use our own 'finite' function to avoid potential problems with
107 non standard math libs */
108 /* XXX: endianness dependent */
109 ST_FUNC int ieee_finite(double d)
111 int p[4];
112 memcpy(p, &d, sizeof(double));
113 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
116 ST_FUNC void test_lvalue(void)
118 if (!(vtop->r & VT_LVAL))
119 expect("lvalue");
122 /* ------------------------------------------------------------------------- */
123 /* symbol allocator */
124 static Sym *__sym_malloc(void)
126 Sym *sym_pool, *sym, *last_sym;
127 int i;
129 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
130 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
132 last_sym = sym_free_first;
133 sym = sym_pool;
134 for(i = 0; i < SYM_POOL_NB; i++) {
135 sym->next = last_sym;
136 last_sym = sym;
137 sym++;
139 sym_free_first = last_sym;
140 return last_sym;
143 static inline Sym *sym_malloc(void)
145 Sym *sym;
146 sym = sym_free_first;
147 if (!sym)
148 sym = __sym_malloc();
149 sym_free_first = sym->next;
150 return sym;
153 ST_INLN void sym_free(Sym *sym)
155 sym->next = sym_free_first;
156 tcc_free(sym->asm_label);
157 sym_free_first = sym;
160 /* push, without hashing */
161 ST_FUNC Sym *sym_push2(Sym **ps, int v, int t, long c)
163 Sym *s;
164 if (ps == &local_stack) {
165 for (s = *ps; s && s != scope_stack_bottom; s = s->prev)
166 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM && s->v == v)
167 tcc_error("incompatible types for redefinition of '%s'",
168 get_tok_str(v, NULL));
170 s = sym_malloc();
171 s->asm_label = NULL;
172 s->v = v;
173 s->type.t = t;
174 s->type.ref = NULL;
175 #ifdef _WIN64
176 s->d = NULL;
177 #endif
178 s->c = c;
179 s->next = NULL;
180 /* add in stack */
181 s->prev = *ps;
182 *ps = s;
183 return s;
186 /* find a symbol and return its associated structure. 's' is the top
187 of the symbol stack */
188 ST_FUNC Sym *sym_find2(Sym *s, int v)
190 while (s) {
191 if (s->v == v)
192 return s;
193 else if (s->v == -1)
194 return NULL;
195 s = s->prev;
197 return NULL;
200 /* structure lookup */
201 ST_INLN Sym *struct_find(int v)
203 v -= TOK_IDENT;
204 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
205 return NULL;
206 return table_ident[v]->sym_struct;
209 /* find an identifier */
210 ST_INLN Sym *sym_find(int v)
212 v -= TOK_IDENT;
213 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
214 return NULL;
215 return table_ident[v]->sym_identifier;
218 /* push a given symbol on the symbol stack */
219 ST_FUNC Sym *sym_push(int v, CType *type, int r, int c)
221 Sym *s, **ps;
222 TokenSym *ts;
224 if (local_stack)
225 ps = &local_stack;
226 else
227 ps = &global_stack;
228 s = sym_push2(ps, v, type->t, c);
229 s->type.ref = type->ref;
230 s->r = r;
231 /* don't record fields or anonymous symbols */
232 /* XXX: simplify */
233 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
234 /* record symbol in token array */
235 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
236 if (v & SYM_STRUCT)
237 ps = &ts->sym_struct;
238 else
239 ps = &ts->sym_identifier;
240 s->prev_tok = *ps;
241 *ps = s;
243 return s;
246 /* push a global identifier */
247 ST_FUNC Sym *global_identifier_push(int v, int t, int c)
249 Sym *s, **ps;
250 s = sym_push2(&global_stack, v, t, c);
251 /* don't record anonymous symbol */
252 if (v < SYM_FIRST_ANOM) {
253 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
254 /* modify the top most local identifier, so that
255 sym_identifier will point to 's' when popped */
256 while (*ps != NULL)
257 ps = &(*ps)->prev_tok;
258 s->prev_tok = NULL;
259 *ps = s;
261 return s;
264 /* pop symbols until top reaches 'b' */
265 ST_FUNC void sym_pop(Sym **ptop, Sym *b)
267 Sym *s, *ss, **ps;
268 TokenSym *ts;
269 int v;
271 s = *ptop;
272 while(s != b) {
273 ss = s->prev;
274 v = s->v;
275 /* remove symbol in token array */
276 /* XXX: simplify */
277 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
278 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
279 if (v & SYM_STRUCT)
280 ps = &ts->sym_struct;
281 else
282 ps = &ts->sym_identifier;
283 *ps = s->prev_tok;
285 sym_free(s);
286 s = ss;
288 *ptop = b;
291 static void weaken_symbol(Sym *sym)
293 sym->type.t |= VT_WEAK;
294 if (sym->c > 0) {
295 int esym_type;
296 ElfW(Sym) *esym;
298 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
299 esym_type = ELFW(ST_TYPE)(esym->st_info);
300 esym->st_info = ELFW(ST_INFO)(STB_WEAK, esym_type);
304 static void apply_visibility(Sym *sym, CType *type)
306 int vis = sym->type.t & VT_VIS_MASK;
307 int vis2 = type->t & VT_VIS_MASK;
308 if (vis == (STV_DEFAULT << VT_VIS_SHIFT))
309 vis = vis2;
310 else if (vis2 == (STV_DEFAULT << VT_VIS_SHIFT))
312 else
313 vis = (vis < vis2) ? vis : vis2;
314 sym->type.t &= ~VT_VIS_MASK;
315 sym->type.t |= vis;
317 if (sym->c > 0) {
318 ElfW(Sym) *esym;
320 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
321 vis >>= VT_VIS_SHIFT;
322 esym->st_other = (esym->st_other & ~ELFW(ST_VISIBILITY)(-1)) | vis;
326 /* ------------------------------------------------------------------------- */
328 ST_FUNC void swap(int *p, int *q)
330 int t;
331 t = *p;
332 *p = *q;
333 *q = t;
336 static void vsetc(CType *type, int r, CValue *vc)
338 int v;
340 if (vtop >= vstack + (VSTACK_SIZE - 1))
341 tcc_error("memory full (vstack)");
342 /* cannot let cpu flags if other instruction are generated. Also
343 avoid leaving VT_JMP anywhere except on the top of the stack
344 because it would complicate the code generator. */
345 if (vtop >= vstack) {
346 v = vtop->r & VT_VALMASK;
347 if (v == VT_CMP || (v & ~1) == VT_JMP)
348 gv(RC_INT);
350 vtop++;
351 vtop->type = *type;
352 vtop->r = r;
353 vtop->r2 = VT_CONST;
354 vtop->c = *vc;
357 /* push constant of type "type" with useless value */
358 ST_FUNC void vpush(CType *type)
360 CValue cval;
361 vsetc(type, VT_CONST, &cval);
364 /* push integer constant */
365 ST_FUNC void vpushi(int v)
367 CValue cval;
368 cval.i = v;
369 vsetc(&int_type, VT_CONST, &cval);
372 /* push a pointer sized constant */
373 static void vpushs(addr_t v)
375 CValue cval;
376 cval.ptr_offset = v;
377 vsetc(&size_type, VT_CONST, &cval);
380 /* push arbitrary 64bit constant */
381 ST_FUNC void vpush64(int ty, unsigned long long v)
383 CValue cval;
384 CType ctype;
385 ctype.t = ty;
386 ctype.ref = NULL;
387 cval.ull = v;
388 vsetc(&ctype, VT_CONST, &cval);
391 /* push long long constant */
392 static inline void vpushll(long long v)
394 vpush64(VT_LLONG, v);
397 /* push a symbol value of TYPE */
398 static inline void vpushsym(CType *type, Sym *sym)
400 CValue cval;
401 cval.ptr_offset = 0;
402 vsetc(type, VT_CONST | VT_SYM, &cval);
403 vtop->sym = sym;
406 /* Return a static symbol pointing to a section */
407 ST_FUNC Sym *get_sym_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
409 int v;
410 Sym *sym;
412 v = anon_sym++;
413 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
414 sym->type.ref = type->ref;
415 sym->r = VT_CONST | VT_SYM;
416 put_extern_sym(sym, sec, offset, size);
417 return sym;
420 /* push a reference to a section offset by adding a dummy symbol */
421 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
423 vpushsym(type, get_sym_ref(type, sec, offset, size));
426 /* define a new external reference to a symbol 'v' of type 'u' */
427 ST_FUNC Sym *external_global_sym(int v, CType *type, int r)
429 Sym *s;
431 s = sym_find(v);
432 if (!s) {
433 /* push forward reference */
434 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
435 s->type.ref = type->ref;
436 s->r = r | VT_CONST | VT_SYM;
438 return s;
441 /* define a new external reference to a symbol 'v' with alternate asm
442 name 'asm_label' of type 'u'. 'asm_label' is equal to NULL if there
443 is no alternate name (most cases) */
444 static Sym *external_sym(int v, CType *type, int r, char *asm_label)
446 Sym *s;
448 s = sym_find(v);
449 if (!s) {
450 /* push forward reference */
451 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
452 s->asm_label = asm_label;
453 s->type.t |= VT_EXTERN;
454 } else if (s->type.ref == func_old_type.ref) {
455 s->type.ref = type->ref;
456 s->r = r | VT_CONST | VT_SYM;
457 s->type.t |= VT_EXTERN;
458 } else if (!is_compatible_types(&s->type, type)) {
459 tcc_error("incompatible types for redefinition of '%s'",
460 get_tok_str(v, NULL));
462 /* Merge some storage attributes. */
463 if (type->t & VT_WEAK)
464 weaken_symbol(s);
466 if (type->t & VT_VIS_MASK)
467 apply_visibility(s, type);
469 return s;
472 /* push a reference to global symbol v */
473 ST_FUNC void vpush_global_sym(CType *type, int v)
475 vpushsym(type, external_global_sym(v, type, 0));
478 ST_FUNC void vset(CType *type, int r, int v)
480 CValue cval;
482 cval.i = v;
483 vsetc(type, r, &cval);
486 static void vseti(int r, int v)
488 CType type;
489 type.t = VT_INT;
490 type.ref = 0;
491 vset(&type, r, v);
494 ST_FUNC void vswap(void)
496 SValue tmp;
497 /* cannot let cpu flags if other instruction are generated. Also
498 avoid leaving VT_JMP anywhere except on the top of the stack
499 because it would complicate the code generator. */
500 if (vtop >= vstack) {
501 int v = vtop->r & VT_VALMASK;
502 if (v == VT_CMP || (v & ~1) == VT_JMP)
503 gv(RC_INT);
505 tmp = vtop[0];
506 vtop[0] = vtop[-1];
507 vtop[-1] = tmp;
509 /* XXX: +2% overall speed possible with optimized memswap
511 * memswap(&vtop[0], &vtop[1], sizeof *vtop);
515 ST_FUNC void vpushv(SValue *v)
517 if (vtop >= vstack + (VSTACK_SIZE - 1))
518 tcc_error("memory full (vstack)");
519 vtop++;
520 *vtop = *v;
523 ST_FUNC void vdup(void)
525 vpushv(vtop);
528 /* save r to the memory stack, and mark it as being free */
529 ST_FUNC void save_reg(int r)
531 int l, saved, size, align;
532 SValue *p, sv;
533 CType *type;
535 /* modify all stack values */
536 saved = 0;
537 l = 0;
538 for(p=vstack;p<=vtop;p++) {
539 if ((p->r & VT_VALMASK) == r ||
540 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
541 /* must save value on stack if not already done */
542 if (!saved) {
543 /* NOTE: must reload 'r' because r might be equal to r2 */
544 r = p->r & VT_VALMASK;
545 /* store register in the stack */
546 type = &p->type;
547 if ((p->r & VT_LVAL) ||
548 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
549 #ifdef TCC_TARGET_X86_64
550 type = &char_pointer_type;
551 #else
552 type = &int_type;
553 #endif
554 size = type_size(type, &align);
555 loc = (loc - size) & -align;
556 sv.type.t = type->t;
557 sv.r = VT_LOCAL | VT_LVAL;
558 sv.c.ul = loc;
559 store(r, &sv);
560 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
561 /* x86 specific: need to pop fp register ST0 if saved */
562 if (r == TREG_ST0) {
563 o(0xd8dd); /* fstp %st(0) */
565 #endif
566 #ifndef TCC_TARGET_X86_64
567 /* special long long case */
568 if ((type->t & VT_BTYPE) == VT_LLONG) {
569 sv.c.ul += 4;
570 store(p->r2, &sv);
572 #endif
573 l = loc;
574 saved = 1;
576 /* mark that stack entry as being saved on the stack */
577 if (p->r & VT_LVAL) {
578 /* also clear the bounded flag because the
579 relocation address of the function was stored in
580 p->c.ul */
581 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
582 } else {
583 p->r = lvalue_type(p->type.t) | VT_LOCAL;
585 p->r2 = VT_CONST;
586 p->c.ul = l;
591 #ifdef TCC_TARGET_ARM
592 /* find a register of class 'rc2' with at most one reference on stack.
593 * If none, call get_reg(rc) */
594 ST_FUNC int get_reg_ex(int rc, int rc2)
596 int r;
597 SValue *p;
599 for(r=0;r<NB_REGS;r++) {
600 if (reg_classes[r] & rc2) {
601 int n;
602 n=0;
603 for(p = vstack; p <= vtop; p++) {
604 if ((p->r & VT_VALMASK) == r ||
605 (p->r2 & VT_VALMASK) == r)
606 n++;
608 if (n <= 1)
609 return r;
612 return get_reg(rc);
614 #endif
616 /* find a free register of class 'rc'. If none, save one register */
617 ST_FUNC int get_reg(int rc)
619 int r;
620 SValue *p;
622 /* find a free register */
623 for(r=0;r<NB_REGS;r++) {
624 if (reg_classes[r] & rc) {
625 for(p=vstack;p<=vtop;p++) {
626 if ((p->r & VT_VALMASK) == r ||
627 (p->r2 & VT_VALMASK) == r)
628 goto notfound;
630 return r;
632 notfound: ;
635 /* no register left : free the first one on the stack (VERY
636 IMPORTANT to start from the bottom to ensure that we don't
637 spill registers used in gen_opi()) */
638 for(p=vstack;p<=vtop;p++) {
639 /* look at second register (if long long) */
640 r = p->r2 & VT_VALMASK;
641 if (r < VT_CONST && (reg_classes[r] & rc))
642 goto save_found;
643 r = p->r & VT_VALMASK;
644 if (r < VT_CONST && (reg_classes[r] & rc)) {
645 save_found:
646 save_reg(r);
647 return r;
650 /* Should never comes here */
651 return -1;
654 /* save registers up to (vtop - n) stack entry */
655 ST_FUNC void save_regs(int n)
657 int r;
658 SValue *p, *p1;
659 p1 = vtop - n;
660 for(p = vstack;p <= p1; p++) {
661 r = p->r & VT_VALMASK;
662 if (r < VT_CONST) {
663 save_reg(r);
668 /* move register 's' (of type 't') to 'r', and flush previous value of r to memory
669 if needed */
670 static void move_reg(int r, int s, int t)
672 SValue sv;
674 if (r != s) {
675 save_reg(r);
676 sv.type.t = t;
677 sv.type.ref = NULL;
678 sv.r = s;
679 sv.c.ul = 0;
680 load(r, &sv);
684 /* get address of vtop (vtop MUST BE an lvalue) */
685 ST_FUNC void gaddrof(void)
687 if (vtop->r & VT_REF)
688 gv(RC_INT);
689 vtop->r &= ~VT_LVAL;
690 /* tricky: if saved lvalue, then we can go back to lvalue */
691 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
692 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
697 #ifdef CONFIG_TCC_BCHECK
698 /* generate lvalue bound code */
699 static void gbound(void)
701 int lval_type;
702 CType type1;
704 vtop->r &= ~VT_MUSTBOUND;
705 /* if lvalue, then use checking code before dereferencing */
706 if (vtop->r & VT_LVAL) {
707 /* if not VT_BOUNDED value, then make one */
708 if (!(vtop->r & VT_BOUNDED)) {
709 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
710 /* must save type because we must set it to int to get pointer */
711 type1 = vtop->type;
712 vtop->type.t = VT_INT;
713 gaddrof();
714 vpushi(0);
715 gen_bounded_ptr_add();
716 vtop->r |= lval_type;
717 vtop->type = type1;
719 /* then check for dereferencing */
720 gen_bounded_ptr_deref();
723 #endif
725 /* store vtop a register belonging to class 'rc'. lvalues are
726 converted to values. Cannot be used if cannot be converted to
727 register value (such as structures). */
728 ST_FUNC int gv(int rc)
730 int r, bit_pos, bit_size, size, align, i, ft, sbt;
731 int rc2;
733 ft = vtop->type.t;
734 sbt = ft & VT_BTYPE;
735 /* NOTE: get_reg can modify vstack[] */
736 if (ft & VT_BITFIELD) {
737 CType type;
738 int bits;
739 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
740 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
741 /* remove bit field info to avoid loops */
742 ft = vtop->type.t &= ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
743 /* cast to int to propagate signedness in following ops */
744 if (sbt == VT_LLONG) {
745 type.t = VT_LLONG;
746 bits = 64;
747 } else{
748 type.t = VT_INT;
749 bits = 32;
751 if((ft & VT_UNSIGNED) || sbt == VT_BOOL)
752 type.t |= VT_UNSIGNED;
753 gen_cast(&type);
754 /* generate shifts */
755 vpushi(bits - (bit_pos + bit_size));
756 gen_op(TOK_SHL);
757 vpushi(bits - bit_size);
758 /* NOTE: transformed to SHR if unsigned */
759 gen_op(TOK_SAR);
760 r = gv(rc);
761 } else {
762 if (is_float(vtop->type.t) &&
763 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
764 Sym *sym;
765 int *ptr;
766 unsigned long offset;
767 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
768 CValue check;
769 #endif
771 /* XXX: unify with initializers handling ? */
772 /* CPUs usually cannot use float constants, so we store them
773 generically in data segment */
774 size = type_size(&vtop->type, &align);
775 offset = (data_section->data_offset + align - 1) & -align;
776 data_section->data_offset = offset;
777 /* XXX: not portable yet */
778 #if defined(__i386__) || defined(__x86_64__)
779 /* Zero pad x87 tenbyte long doubles */
780 if (size == LDOUBLE_SIZE) {
781 vtop->c.tab[2] &= 0xffff;
782 #if LDOUBLE_SIZE == 16
783 vtop->c.tab[3] = 0;
784 #endif
786 #endif
787 ptr = section_ptr_add(data_section, size);
788 size = size >> 2;
789 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
790 check.d = 1;
791 if(check.tab[0])
792 for(i=0;i<size;i++)
793 ptr[i] = vtop->c.tab[size-1-i];
794 else
795 #endif
796 for(i=0;i<size;i++)
797 ptr[i] = vtop->c.tab[i];
798 sym = get_sym_ref(&vtop->type, data_section, offset, size << 2);
799 vtop->r |= VT_LVAL | VT_SYM;
800 vtop->sym = sym;
801 vtop->c.ptr_offset = 0;
803 #ifdef CONFIG_TCC_BCHECK
804 if (vtop->r & VT_MUSTBOUND)
805 gbound();
806 #endif
808 r = vtop->r & VT_VALMASK;
809 if((rc & ~RC_MASK) && (rc != RC_ST0))
810 rc2 = ex_rc;
811 else
812 rc2 = (rc & RC_FLOAT) ? RC_FLOAT : RC_INT;
814 /* need to reload if:
815 - constant
816 - lvalue (need to dereference pointer)
817 - already a register, but not in the right class */
818 if (r >= VT_CONST || (vtop->r & VT_LVAL) || !(reg_classes[r] & rc)
819 #ifdef TCC_TARGET_X86_64
820 || (sbt == VT_QLONG && !(reg_classes[vtop->r2] & rc2))
821 || (sbt == VT_QFLOAT && !(reg_classes[vtop->r2] & rc2))
822 #else
823 || (sbt == VT_LLONG && !(reg_classes[vtop->r2] & rc2))
824 #endif
825 || vtop->c.i)
827 r = get_reg(rc);
828 #ifdef TCC_TARGET_X86_64
829 if ((sbt == VT_QLONG) || (sbt == VT_QFLOAT))
830 #else
831 if (sbt == VT_LLONG)
832 #endif
834 #ifdef TCC_TARGET_X86_64
835 int load_size = 8, load_type = (sbt == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
836 #else
837 int load_size = 4, load_type = VT_INT;
838 unsigned long long ll;
839 #endif
840 int r2;
841 /* two register type load : expand to two words
842 temporarily */
843 #ifndef TCC_TARGET_X86_64
844 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
845 /* load constant */
846 ll = vtop->c.ull;
847 vtop->c.ui = ll; /* first word */
848 load(r, vtop);
849 vtop->r = r; /* save register value */
850 vpushi(ll >> 32); /* second word */
851 } else
852 #endif
853 /* XXX: test to VT_CONST incorrect ? */
854 if (r >= VT_CONST || (vtop->r & VT_LVAL)) {
855 /* We do not want to modifier the long long
856 pointer here, so the safest (and less
857 efficient) is to save all the other registers
858 in the regs. use VT_TMP XXX: totally inefficient. */
859 /* load from memory */
860 vtop->type.t = load_type;
861 load(r, vtop);
862 vdup();
863 vtop[-1].r = r | VT_TMP; /* lock register value */
864 /* increment pointer to get second word */
865 vtop->type = char_pointer_type;
866 gaddrof();
867 vpushi(load_size);
868 gen_op('+');
869 vtop->r |= VT_LVAL;
870 vtop->type.t = load_type;
871 } else {
872 /* move registers */
873 load(r, vtop);
874 vdup();
875 vtop[-1].r = r | VT_TMP; /* lock register value */
876 vtop->r = vtop[-1].r2;
878 /* Allocate second register. Here we rely on the fact that
879 get_reg() tries first to free r2 of an SValue. */
880 r2 = get_reg(rc2);
881 load(r2, vtop);
882 vtop--;
883 /* write second register */
884 vtop->r2 = r2;
885 vtop->r &= ~VT_TMP;
886 vtop->type.t = ft;
887 } else if ((vtop->r & VT_LVAL) && !is_float(ft)) {
888 int t;
889 /* lvalue of scalar type : need to use lvalue type
890 because of possible cast */
891 t = ft;
892 /* compute memory access type */
893 if (vtop->r & VT_REF)
894 #ifdef TCC_TARGET_X86_64
895 t = VT_PTR;
896 #else
897 t = VT_INT;
898 #endif
899 else if (vtop->r & VT_LVAL_BYTE)
900 t = VT_BYTE;
901 else if (vtop->r & VT_LVAL_SHORT)
902 t = VT_SHORT;
903 if (vtop->r & VT_LVAL_UNSIGNED)
904 t |= VT_UNSIGNED;
905 vtop->type.t = t;
906 load(r, vtop);
907 /* restore wanted type */
908 vtop->type.t = ft;
909 } else {
910 /* one register type load */
911 load(r, vtop);
913 vtop->r = r;
914 vtop->c.ptr_offset = 0;
916 #ifdef TCC_TARGET_C67
917 /* uses register pairs for doubles */
918 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
919 vtop->r2 = r+1;
920 #endif
922 return r;
925 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
926 ST_FUNC void gv2(int rc1, int rc2)
928 /* generate more generic register first. But VT_JMP or VT_CMP
929 values must be generated first in all cases to avoid possible
930 reload errors */
931 if (rc1 <= rc2) {
932 vswap();
933 gv(rc1);
934 vswap();
935 gv(rc2);
936 /* test if reload is needed for first register */
937 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
938 vswap();
939 gv(rc1);
940 vswap();
942 } else {
943 gv(rc2);
944 vswap();
945 gv(rc1);
946 vswap();
947 /* test if reload is needed for first register */
948 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
949 gv(rc2);
954 /* wrapper around RC_FRET to return a register by type */
955 static int rc_fret(int t)
957 #ifdef TCC_TARGET_X86_64
958 if (t == VT_LDOUBLE) {
959 return RC_ST0;
961 #endif
962 ex_rc = RC_QRET;
963 return RC_FRET;
966 /* wrapper around REG_FRET to return a register by type */
967 static int reg_fret(int t)
969 #ifdef TCC_TARGET_X86_64
970 if (t == VT_LDOUBLE) {
971 return TREG_ST0;
973 #endif
974 return REG_FRET;
977 /* expand long long on stack in two int registers */
978 static void lexpand(void)
980 int u;
982 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
983 gv(RC_INT);
984 vdup();
985 vtop[0].r = vtop[-1].r2;
986 vtop[0].r2 = VT_CONST;
987 vtop[-1].r2 = VT_CONST;
988 vtop[0].type.t = VT_INT | u;
989 vtop[-1].type.t = VT_INT | u;
992 #ifdef TCC_TARGET_ARM
993 /* expand long long on stack */
994 ST_FUNC void lexpand_nr(void)
996 int u,v;
998 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
999 vdup();
1000 vtop->r2 = VT_CONST;
1001 vtop->type.t = VT_INT | u;
1002 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
1003 if (v == VT_CONST) {
1004 vtop[-1].c.ui = vtop->c.ull;
1005 vtop->c.ui = vtop->c.ull >> 32;
1006 vtop->r = VT_CONST;
1007 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
1008 vtop->c.ui += 4;
1009 vtop->r = vtop[-1].r;
1010 } else if (v > VT_CONST) {
1011 vtop--;
1012 lexpand();
1013 } else
1014 vtop->r = vtop[-1].r2;
1015 vtop[-1].r2 = VT_CONST;
1016 vtop[-1].type.t = VT_INT | u;
1018 #endif
1020 #ifndef TCC_TARGET_X86_64
1021 /* build a long long from two ints */
1022 static void lbuild(int t)
1024 gv2(RC_INT, RC_INT);
1025 vtop[-1].r2 = vtop[0].r;
1026 vtop[-1].type.t = t;
1027 vpop();
1029 #endif
1031 /* rotate n first stack elements to the bottom
1032 I1 ... In -> I2 ... In I1 [top is right]
1034 ST_FUNC void vrotb(int n)
1036 int i;
1037 SValue tmp;
1039 tmp = vtop[-n + 1];
1040 for(i=-n+1;i!=0;i++)
1041 vtop[i] = vtop[i+1];
1042 vtop[0] = tmp;
1045 /* rotate the n elements before entry e towards the top
1046 I1 ... In ... -> In I1 ... I(n-1) ... [top is right]
1048 ST_FUNC void vrote(SValue *e, int n)
1050 int i;
1051 SValue tmp;
1053 tmp = *e;
1054 for(i = 0;i < n - 1; i++)
1055 e[-i] = e[-i - 1];
1056 e[-n + 1] = tmp;
1059 /* rotate n first stack elements to the top
1060 I1 ... In -> In I1 ... I(n-1) [top is right]
1062 ST_FUNC void vrott(int n)
1064 vrote(vtop, n);
1067 /* pop stack value */
1068 ST_FUNC void vpop(void)
1070 int v;
1071 v = vtop->r & VT_VALMASK;
1072 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1073 /* for x86, we need to pop the FP stack */
1074 if (v == TREG_ST0 && !nocode_wanted) {
1075 o(0xd8dd); /* fstp %st(0) */
1076 } else
1077 #endif
1078 if (v == VT_JMP || v == VT_JMPI) {
1079 /* need to put correct jump if && or || without test */
1080 gsym(vtop->c.ul);
1082 vtop--;
1085 /* convert stack entry to register and duplicate its value in another
1086 register */
1087 static void gv_dup(void)
1089 int rc, t, r, r1;
1090 SValue sv;
1091 t = vtop->type.t;
1092 #ifndef TCC_TARGET_X86_64
1093 if ((t & VT_BTYPE) == VT_LLONG) {
1094 lexpand();
1095 gv_dup();
1096 vswap();
1097 vrotb(3);
1098 gv_dup();
1099 vrotb(4);
1100 /* stack: H L L1 H1 */
1101 lbuild(t);
1102 vrott(3);
1103 vswap();
1104 lbuild(t);
1105 vswap();
1106 } else
1107 #endif
1109 /* duplicate value */
1110 if (is_float(t)) {
1111 rc = RC_FLOAT;
1112 #ifdef TCC_TARGET_X86_64
1113 if ((t & VT_BTYPE) == VT_LDOUBLE) {
1114 rc = RC_ST0;
1116 #endif
1117 }else
1118 rc = RC_INT;
1119 sv.type.t = t;
1120 r = gv(rc);
1121 r1 = get_reg(rc);
1122 sv.r = r;
1123 sv.c.ul = 0;
1124 load(r1, &sv); /* move r to r1 */
1125 vdup();
1126 /* duplicates value */
1127 if (r != r1)
1128 vtop->r = r1;
1131 #ifndef TCC_TARGET_X86_64
1132 /* generate CPU independent (unsigned) long long operations */
1133 static void gen_opl(int op)
1135 int t, a, b, op1, c, i;
1136 int func;
1137 unsigned short reg_iret = REG_IRET;
1138 unsigned short reg_lret = REG_LRET;
1139 SValue tmp;
1141 switch(op) {
1142 case '/':
1143 case TOK_PDIV:
1144 func = TOK___divdi3;
1145 goto gen_func;
1146 case TOK_UDIV:
1147 func = TOK___udivdi3;
1148 goto gen_func;
1149 case '%':
1150 func = TOK___moddi3;
1151 goto gen_mod_func;
1152 case TOK_UMOD:
1153 func = TOK___umoddi3;
1154 gen_mod_func:
1155 #ifdef TCC_ARM_EABI
1156 reg_iret = TREG_R2;
1157 reg_lret = TREG_R3;
1158 #endif
1159 gen_func:
1160 /* call generic long long function */
1161 vpush_global_sym(&func_old_type, func);
1162 vrott(3);
1163 gfunc_call(2);
1164 vpushi(0);
1165 vtop->r = reg_iret;
1166 vtop->r2 = reg_lret;
1167 break;
1168 case '^':
1169 case '&':
1170 case '|':
1171 case '*':
1172 case '+':
1173 case '-':
1174 t = vtop->type.t;
1175 vswap();
1176 lexpand();
1177 vrotb(3);
1178 lexpand();
1179 /* stack: L1 H1 L2 H2 */
1180 tmp = vtop[0];
1181 vtop[0] = vtop[-3];
1182 vtop[-3] = tmp;
1183 tmp = vtop[-2];
1184 vtop[-2] = vtop[-3];
1185 vtop[-3] = tmp;
1186 vswap();
1187 /* stack: H1 H2 L1 L2 */
1188 if (op == '*') {
1189 vpushv(vtop - 1);
1190 vpushv(vtop - 1);
1191 gen_op(TOK_UMULL);
1192 lexpand();
1193 /* stack: H1 H2 L1 L2 ML MH */
1194 for(i=0;i<4;i++)
1195 vrotb(6);
1196 /* stack: ML MH H1 H2 L1 L2 */
1197 tmp = vtop[0];
1198 vtop[0] = vtop[-2];
1199 vtop[-2] = tmp;
1200 /* stack: ML MH H1 L2 H2 L1 */
1201 gen_op('*');
1202 vrotb(3);
1203 vrotb(3);
1204 gen_op('*');
1205 /* stack: ML MH M1 M2 */
1206 gen_op('+');
1207 gen_op('+');
1208 } else if (op == '+' || op == '-') {
1209 /* XXX: add non carry method too (for MIPS or alpha) */
1210 if (op == '+')
1211 op1 = TOK_ADDC1;
1212 else
1213 op1 = TOK_SUBC1;
1214 gen_op(op1);
1215 /* stack: H1 H2 (L1 op L2) */
1216 vrotb(3);
1217 vrotb(3);
1218 gen_op(op1 + 1); /* TOK_xxxC2 */
1219 } else {
1220 gen_op(op);
1221 /* stack: H1 H2 (L1 op L2) */
1222 vrotb(3);
1223 vrotb(3);
1224 /* stack: (L1 op L2) H1 H2 */
1225 gen_op(op);
1226 /* stack: (L1 op L2) (H1 op H2) */
1228 /* stack: L H */
1229 lbuild(t);
1230 break;
1231 case TOK_SAR:
1232 case TOK_SHR:
1233 case TOK_SHL:
1234 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1235 t = vtop[-1].type.t;
1236 vswap();
1237 lexpand();
1238 vrotb(3);
1239 /* stack: L H shift */
1240 c = (int)vtop->c.i;
1241 /* constant: simpler */
1242 /* NOTE: all comments are for SHL. the other cases are
1243 done by swaping words */
1244 vpop();
1245 if (op != TOK_SHL)
1246 vswap();
1247 if (c >= 32) {
1248 /* stack: L H */
1249 vpop();
1250 if (c > 32) {
1251 vpushi(c - 32);
1252 gen_op(op);
1254 if (op != TOK_SAR) {
1255 vpushi(0);
1256 } else {
1257 gv_dup();
1258 vpushi(31);
1259 gen_op(TOK_SAR);
1261 vswap();
1262 } else {
1263 vswap();
1264 gv_dup();
1265 /* stack: H L L */
1266 vpushi(c);
1267 gen_op(op);
1268 vswap();
1269 vpushi(32 - c);
1270 if (op == TOK_SHL)
1271 gen_op(TOK_SHR);
1272 else
1273 gen_op(TOK_SHL);
1274 vrotb(3);
1275 /* stack: L L H */
1276 vpushi(c);
1277 if (op == TOK_SHL)
1278 gen_op(TOK_SHL);
1279 else
1280 gen_op(TOK_SHR);
1281 gen_op('|');
1283 if (op != TOK_SHL)
1284 vswap();
1285 lbuild(t);
1286 } else {
1287 /* XXX: should provide a faster fallback on x86 ? */
1288 switch(op) {
1289 case TOK_SAR:
1290 func = TOK___ashrdi3;
1291 goto gen_func;
1292 case TOK_SHR:
1293 func = TOK___lshrdi3;
1294 goto gen_func;
1295 case TOK_SHL:
1296 func = TOK___ashldi3;
1297 goto gen_func;
1300 break;
1301 default:
1302 /* compare operations */
1303 t = vtop->type.t;
1304 vswap();
1305 lexpand();
1306 vrotb(3);
1307 lexpand();
1308 /* stack: L1 H1 L2 H2 */
1309 tmp = vtop[-1];
1310 vtop[-1] = vtop[-2];
1311 vtop[-2] = tmp;
1312 /* stack: L1 L2 H1 H2 */
1313 /* compare high */
1314 op1 = op;
1315 /* when values are equal, we need to compare low words. since
1316 the jump is inverted, we invert the test too. */
1317 if (op1 == TOK_LT)
1318 op1 = TOK_LE;
1319 else if (op1 == TOK_GT)
1320 op1 = TOK_GE;
1321 else if (op1 == TOK_ULT)
1322 op1 = TOK_ULE;
1323 else if (op1 == TOK_UGT)
1324 op1 = TOK_UGE;
1325 a = 0;
1326 b = 0;
1327 gen_op(op1);
1328 if (op1 != TOK_NE) {
1329 a = gtst(1, 0);
1331 if (op != TOK_EQ) {
1332 /* generate non equal test */
1333 /* XXX: NOT PORTABLE yet */
1334 if (a == 0) {
1335 b = gtst(0, 0);
1336 } else {
1337 #if defined(TCC_TARGET_I386)
1338 b = psym(0x850f, 0);
1339 #elif defined(TCC_TARGET_ARM)
1340 b = ind;
1341 o(0x1A000000 | encbranch(ind, 0, 1));
1342 #elif defined(TCC_TARGET_C67)
1343 tcc_error("not implemented");
1344 #else
1345 #error not supported
1346 #endif
1349 /* compare low. Always unsigned */
1350 op1 = op;
1351 if (op1 == TOK_LT)
1352 op1 = TOK_ULT;
1353 else if (op1 == TOK_LE)
1354 op1 = TOK_ULE;
1355 else if (op1 == TOK_GT)
1356 op1 = TOK_UGT;
1357 else if (op1 == TOK_GE)
1358 op1 = TOK_UGE;
1359 gen_op(op1);
1360 a = gtst(1, a);
1361 gsym(b);
1362 vseti(VT_JMPI, a);
1363 break;
1366 #endif
1368 /* handle integer constant optimizations and various machine
1369 independent opt */
1370 static void gen_opic(int op)
1372 int c1, c2, t1, t2, n;
1373 SValue *v1, *v2;
1374 long long l1, l2;
1375 typedef unsigned long long U;
1377 v1 = vtop - 1;
1378 v2 = vtop;
1379 t1 = v1->type.t & VT_BTYPE;
1380 t2 = v2->type.t & VT_BTYPE;
1382 if (t1 == VT_LLONG)
1383 l1 = v1->c.ll;
1384 else if (v1->type.t & VT_UNSIGNED)
1385 l1 = v1->c.ui;
1386 else
1387 l1 = v1->c.i;
1389 if (t2 == VT_LLONG)
1390 l2 = v2->c.ll;
1391 else if (v2->type.t & VT_UNSIGNED)
1392 l2 = v2->c.ui;
1393 else
1394 l2 = v2->c.i;
1396 /* currently, we cannot do computations with forward symbols */
1397 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1398 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1399 if (c1 && c2) {
1400 switch(op) {
1401 case '+': l1 += l2; break;
1402 case '-': l1 -= l2; break;
1403 case '&': l1 &= l2; break;
1404 case '^': l1 ^= l2; break;
1405 case '|': l1 |= l2; break;
1406 case '*': l1 *= l2; break;
1408 case TOK_PDIV:
1409 case '/':
1410 case '%':
1411 case TOK_UDIV:
1412 case TOK_UMOD:
1413 /* if division by zero, generate explicit division */
1414 if (l2 == 0) {
1415 if (const_wanted)
1416 tcc_error("division by zero in constant");
1417 goto general_case;
1419 switch(op) {
1420 default: l1 /= l2; break;
1421 case '%': l1 %= l2; break;
1422 case TOK_UDIV: l1 = (U)l1 / l2; break;
1423 case TOK_UMOD: l1 = (U)l1 % l2; break;
1425 break;
1426 case TOK_SHL: l1 <<= l2; break;
1427 case TOK_SHR: l1 = (U)l1 >> l2; break;
1428 case TOK_SAR: l1 >>= l2; break;
1429 /* tests */
1430 case TOK_ULT: l1 = (U)l1 < (U)l2; break;
1431 case TOK_UGE: l1 = (U)l1 >= (U)l2; break;
1432 case TOK_EQ: l1 = l1 == l2; break;
1433 case TOK_NE: l1 = l1 != l2; break;
1434 case TOK_ULE: l1 = (U)l1 <= (U)l2; break;
1435 case TOK_UGT: l1 = (U)l1 > (U)l2; break;
1436 case TOK_LT: l1 = l1 < l2; break;
1437 case TOK_GE: l1 = l1 >= l2; break;
1438 case TOK_LE: l1 = l1 <= l2; break;
1439 case TOK_GT: l1 = l1 > l2; break;
1440 /* logical */
1441 case TOK_LAND: l1 = l1 && l2; break;
1442 case TOK_LOR: l1 = l1 || l2; break;
1443 default:
1444 goto general_case;
1446 v1->c.ll = l1;
1447 vtop--;
1448 } else {
1449 /* if commutative ops, put c2 as constant */
1450 if (c1 && (op == '+' || op == '&' || op == '^' ||
1451 op == '|' || op == '*')) {
1452 vswap();
1453 c2 = c1; //c = c1, c1 = c2, c2 = c;
1454 l2 = l1; //l = l1, l1 = l2, l2 = l;
1456 /* Filter out NOP operations like x*1, x-0, x&-1... */
1457 if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
1458 op == TOK_PDIV) &&
1459 l2 == 1) ||
1460 ((op == '+' || op == '-' || op == '|' || op == '^' ||
1461 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
1462 l2 == 0) ||
1463 (op == '&' &&
1464 l2 == -1))) {
1465 /* nothing to do */
1466 vtop--;
1467 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
1468 /* try to use shifts instead of muls or divs */
1469 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
1470 n = -1;
1471 while (l2) {
1472 l2 >>= 1;
1473 n++;
1475 vtop->c.ll = n;
1476 if (op == '*')
1477 op = TOK_SHL;
1478 else if (op == TOK_PDIV)
1479 op = TOK_SAR;
1480 else
1481 op = TOK_SHR;
1483 goto general_case;
1484 } else if (c2 && (op == '+' || op == '-') &&
1485 (((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM))
1486 || (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
1487 /* symbol + constant case */
1488 if (op == '-')
1489 l2 = -l2;
1490 vtop--;
1491 vtop->c.ll += l2;
1492 } else {
1493 general_case:
1494 if (!nocode_wanted) {
1495 /* call low level op generator */
1496 if (t1 == VT_LLONG || t2 == VT_LLONG)
1497 gen_opl(op);
1498 else
1499 gen_opi(op);
1500 } else {
1501 vtop--;
1507 /* generate a floating point operation with constant propagation */
1508 static void gen_opif(int op)
1510 int c1, c2;
1511 SValue *v1, *v2;
1512 long double f1, f2;
1514 v1 = vtop - 1;
1515 v2 = vtop;
1516 /* currently, we cannot do computations with forward symbols */
1517 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1518 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1519 if (c1 && c2) {
1520 if (v1->type.t == VT_FLOAT) {
1521 f1 = v1->c.f;
1522 f2 = v2->c.f;
1523 } else if (v1->type.t == VT_DOUBLE) {
1524 f1 = v1->c.d;
1525 f2 = v2->c.d;
1526 } else {
1527 f1 = v1->c.ld;
1528 f2 = v2->c.ld;
1531 /* NOTE: we only do constant propagation if finite number (not
1532 NaN or infinity) (ANSI spec) */
1533 if (!ieee_finite(f1) || !ieee_finite(f2))
1534 goto general_case;
1536 switch(op) {
1537 case '+': f1 += f2; break;
1538 case '-': f1 -= f2; break;
1539 case '*': f1 *= f2; break;
1540 case '/':
1541 if (f2 == 0.0) {
1542 if (const_wanted)
1543 tcc_error("division by zero in constant");
1544 goto general_case;
1546 f1 /= f2;
1547 break;
1548 /* XXX: also handles tests ? */
1549 default:
1550 goto general_case;
1552 /* XXX: overflow test ? */
1553 if (v1->type.t == VT_FLOAT) {
1554 v1->c.f = f1;
1555 } else if (v1->type.t == VT_DOUBLE) {
1556 v1->c.d = f1;
1557 } else {
1558 v1->c.ld = f1;
1560 vtop--;
1561 } else {
1562 general_case:
1563 if (!nocode_wanted) {
1564 gen_opf(op);
1565 } else {
1566 vtop--;
1571 static int pointed_size(CType *type)
1573 int align;
1574 return type_size(pointed_type(type), &align);
1577 static void vla_runtime_pointed_size(CType *type)
1579 int align;
1580 vla_runtime_type_size(pointed_type(type), &align);
1583 static inline int is_null_pointer(SValue *p)
1585 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
1586 return 0;
1587 return ((p->type.t & VT_BTYPE) == VT_INT && p->c.i == 0) ||
1588 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.ll == 0) ||
1589 ((p->type.t & VT_BTYPE) == VT_PTR && p->c.ptr_offset == 0);
1592 static inline int is_integer_btype(int bt)
1594 return (bt == VT_BYTE || bt == VT_SHORT ||
1595 bt == VT_INT || bt == VT_LLONG);
1598 /* check types for comparison or subtraction of pointers */
1599 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
1601 CType *type1, *type2, tmp_type1, tmp_type2;
1602 int bt1, bt2;
1604 /* null pointers are accepted for all comparisons as gcc */
1605 if (is_null_pointer(p1) || is_null_pointer(p2))
1606 return;
1607 type1 = &p1->type;
1608 type2 = &p2->type;
1609 bt1 = type1->t & VT_BTYPE;
1610 bt2 = type2->t & VT_BTYPE;
1611 /* accept comparison between pointer and integer with a warning */
1612 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
1613 if (op != TOK_LOR && op != TOK_LAND )
1614 tcc_warning("comparison between pointer and integer");
1615 return;
1618 /* both must be pointers or implicit function pointers */
1619 if (bt1 == VT_PTR) {
1620 type1 = pointed_type(type1);
1621 } else if (bt1 != VT_FUNC)
1622 goto invalid_operands;
1624 if (bt2 == VT_PTR) {
1625 type2 = pointed_type(type2);
1626 } else if (bt2 != VT_FUNC) {
1627 invalid_operands:
1628 tcc_error("invalid operands to binary %s", get_tok_str(op, NULL));
1630 if ((type1->t & VT_BTYPE) == VT_VOID ||
1631 (type2->t & VT_BTYPE) == VT_VOID)
1632 return;
1633 tmp_type1 = *type1;
1634 tmp_type2 = *type2;
1635 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1636 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1637 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
1638 /* gcc-like error if '-' is used */
1639 if (op == '-')
1640 goto invalid_operands;
1641 else
1642 tcc_warning("comparison of distinct pointer types lacks a cast");
1646 /* generic gen_op: handles types problems */
1647 ST_FUNC void gen_op(int op)
1649 int u, t1, t2, bt1, bt2, t;
1650 CType type1;
1652 t1 = vtop[-1].type.t;
1653 t2 = vtop[0].type.t;
1654 bt1 = t1 & VT_BTYPE;
1655 bt2 = t2 & VT_BTYPE;
1657 if (bt1 == VT_PTR || bt2 == VT_PTR) {
1658 /* at least one operand is a pointer */
1659 /* relationnal op: must be both pointers */
1660 if (op >= TOK_ULT && op <= TOK_LOR) {
1661 check_comparison_pointer_types(vtop - 1, vtop, op);
1662 /* pointers are handled are unsigned */
1663 #ifdef TCC_TARGET_X86_64
1664 t = VT_LLONG | VT_UNSIGNED;
1665 #else
1666 t = VT_INT | VT_UNSIGNED;
1667 #endif
1668 goto std_op;
1670 /* if both pointers, then it must be the '-' op */
1671 if (bt1 == VT_PTR && bt2 == VT_PTR) {
1672 if (op != '-')
1673 tcc_error("cannot use pointers here");
1674 check_comparison_pointer_types(vtop - 1, vtop, op);
1675 /* XXX: check that types are compatible */
1676 if (vtop[-1].type.t & VT_VLA) {
1677 vla_runtime_pointed_size(&vtop[-1].type);
1678 } else {
1679 vpushi(pointed_size(&vtop[-1].type));
1681 vrott(3);
1682 gen_opic(op);
1683 /* set to integer type */
1684 #ifdef TCC_TARGET_X86_64
1685 vtop->type.t = VT_LLONG;
1686 #else
1687 vtop->type.t = VT_INT;
1688 #endif
1689 vswap();
1690 gen_op(TOK_PDIV);
1691 } else {
1692 /* exactly one pointer : must be '+' or '-'. */
1693 if (op != '-' && op != '+')
1694 tcc_error("cannot use pointers here");
1695 /* Put pointer as first operand */
1696 if (bt2 == VT_PTR) {
1697 vswap();
1698 swap(&t1, &t2);
1700 type1 = vtop[-1].type;
1701 type1.t &= ~VT_ARRAY;
1702 if (vtop[-1].type.t & VT_VLA)
1703 vla_runtime_pointed_size(&vtop[-1].type);
1704 else {
1705 u = pointed_size(&vtop[-1].type);
1706 if (u < 0)
1707 tcc_error("unknown array element size");
1708 #ifdef TCC_TARGET_X86_64
1709 vpushll(u);
1710 #else
1711 /* XXX: cast to int ? (long long case) */
1712 vpushi(u);
1713 #endif
1715 gen_op('*');
1716 #ifdef CONFIG_TCC_BCHECK
1717 /* if evaluating constant expression, no code should be
1718 generated, so no bound check */
1719 if (tcc_state->do_bounds_check && !const_wanted) {
1720 /* if bounded pointers, we generate a special code to
1721 test bounds */
1722 if (op == '-') {
1723 vpushi(0);
1724 vswap();
1725 gen_op('-');
1727 gen_bounded_ptr_add();
1728 } else
1729 #endif
1731 gen_opic(op);
1733 /* put again type if gen_opic() swaped operands */
1734 vtop->type = type1;
1736 } else if (is_float(bt1) || is_float(bt2)) {
1737 /* compute bigger type and do implicit casts */
1738 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
1739 t = VT_LDOUBLE;
1740 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
1741 t = VT_DOUBLE;
1742 } else {
1743 t = VT_FLOAT;
1745 /* floats can only be used for a few operations */
1746 if (op != '+' && op != '-' && op != '*' && op != '/' &&
1747 (op < TOK_ULT || op > TOK_GT))
1748 tcc_error("invalid operands for binary operation");
1749 goto std_op;
1750 } else if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL) {
1751 t = bt1 == VT_LLONG ? VT_LLONG : VT_INT;
1752 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (t | VT_UNSIGNED))
1753 t |= VT_UNSIGNED;
1754 goto std_op;
1755 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
1756 /* cast to biggest op */
1757 t = VT_LLONG;
1758 /* convert to unsigned if it does not fit in a long long */
1759 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
1760 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
1761 t |= VT_UNSIGNED;
1762 goto std_op;
1763 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
1764 tcc_error("comparison of struct");
1765 } else {
1766 /* integer operations */
1767 t = VT_INT;
1768 /* convert to unsigned if it does not fit in an integer */
1769 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
1770 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
1771 t |= VT_UNSIGNED;
1772 std_op:
1773 /* XXX: currently, some unsigned operations are explicit, so
1774 we modify them here */
1775 if (t & VT_UNSIGNED) {
1776 if (op == TOK_SAR)
1777 op = TOK_SHR;
1778 else if (op == '/')
1779 op = TOK_UDIV;
1780 else if (op == '%')
1781 op = TOK_UMOD;
1782 else if (op == TOK_LT)
1783 op = TOK_ULT;
1784 else if (op == TOK_GT)
1785 op = TOK_UGT;
1786 else if (op == TOK_LE)
1787 op = TOK_ULE;
1788 else if (op == TOK_GE)
1789 op = TOK_UGE;
1791 vswap();
1792 type1.t = t;
1793 gen_cast(&type1);
1794 vswap();
1795 /* special case for shifts and long long: we keep the shift as
1796 an integer */
1797 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
1798 type1.t = VT_INT;
1799 gen_cast(&type1);
1800 if (is_float(t))
1801 gen_opif(op);
1802 else
1803 gen_opic(op);
1804 if (op >= TOK_ULT && op <= TOK_GT) {
1805 /* relationnal op: the result is an int */
1806 vtop->type.t = VT_INT;
1807 } else {
1808 vtop->type.t = t;
1813 #ifndef TCC_TARGET_ARM
1814 /* generic itof for unsigned long long case */
1815 static void gen_cvt_itof1(int t)
1817 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
1818 (VT_LLONG | VT_UNSIGNED)) {
1820 if (t == VT_FLOAT)
1821 vpush_global_sym(&func_old_type, TOK___floatundisf);
1822 #if LDOUBLE_SIZE != 8
1823 else if (t == VT_LDOUBLE)
1824 vpush_global_sym(&func_old_type, TOK___floatundixf);
1825 #endif
1826 else
1827 vpush_global_sym(&func_old_type, TOK___floatundidf);
1828 vrott(2);
1829 gfunc_call(1);
1830 vpushi(0);
1831 vtop->r = reg_fret(t);
1832 } else {
1833 gen_cvt_itof(t);
1836 #endif
1838 /* generic ftoi for unsigned long long case */
1839 static void gen_cvt_ftoi1(int t)
1841 int st;
1843 if (t == (VT_LLONG | VT_UNSIGNED)) {
1844 /* not handled natively */
1845 st = vtop->type.t & VT_BTYPE;
1846 if (st == VT_FLOAT)
1847 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
1848 #if LDOUBLE_SIZE != 8
1849 else if (st == VT_LDOUBLE)
1850 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
1851 #endif
1852 else
1853 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
1854 vrott(2);
1855 gfunc_call(1);
1856 vpushi(0);
1857 vtop->r = REG_IRET;
1858 vtop->r2 = REG_LRET;
1859 } else {
1860 gen_cvt_ftoi(t);
1864 /* force char or short cast */
1865 static void force_charshort_cast(int t)
1867 int bits, dbt;
1868 dbt = t & VT_BTYPE;
1869 /* XXX: add optimization if lvalue : just change type and offset */
1870 if (dbt == VT_BYTE)
1871 bits = 8;
1872 else
1873 bits = 16;
1874 if (t & VT_UNSIGNED) {
1875 vpushi((1 << bits) - 1);
1876 gen_op('&');
1877 } else {
1878 bits = 32 - bits;
1879 vpushi(bits);
1880 gen_op(TOK_SHL);
1881 /* result must be signed or the SAR is converted to an SHL
1882 This was not the case when "t" was a signed short
1883 and the last value on the stack was an unsigned int */
1884 vtop->type.t &= ~VT_UNSIGNED;
1885 vpushi(bits);
1886 gen_op(TOK_SAR);
1890 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
1891 static void gen_cast(CType *type)
1893 int sbt, dbt, sf, df, c, p;
1895 /* special delayed cast for char/short */
1896 /* XXX: in some cases (multiple cascaded casts), it may still
1897 be incorrect */
1898 if (vtop->r & VT_MUSTCAST) {
1899 vtop->r &= ~VT_MUSTCAST;
1900 force_charshort_cast(vtop->type.t);
1903 /* bitfields first get cast to ints */
1904 if (vtop->type.t & VT_BITFIELD) {
1905 gv(RC_INT);
1908 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
1909 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
1911 if (sbt != dbt) {
1912 sf = is_float(sbt);
1913 df = is_float(dbt);
1914 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1915 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
1916 if (c) {
1917 /* constant case: we can do it now */
1918 /* XXX: in ISOC, cannot do it if error in convert */
1919 if (sbt == VT_FLOAT)
1920 vtop->c.ld = vtop->c.f;
1921 else if (sbt == VT_DOUBLE)
1922 vtop->c.ld = vtop->c.d;
1924 if (df) {
1925 if ((sbt & VT_BTYPE) == VT_LLONG) {
1926 if (sbt & VT_UNSIGNED)
1927 vtop->c.ld = vtop->c.ull;
1928 else
1929 vtop->c.ld = vtop->c.ll;
1930 } else if(!sf) {
1931 if (sbt & VT_UNSIGNED)
1932 vtop->c.ld = vtop->c.ui;
1933 else
1934 vtop->c.ld = vtop->c.i;
1937 if (dbt == VT_FLOAT)
1938 vtop->c.f = (float)vtop->c.ld;
1939 else if (dbt == VT_DOUBLE)
1940 vtop->c.d = (double)vtop->c.ld;
1941 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
1942 vtop->c.ull = (unsigned long long)vtop->c.ld;
1943 } else if (sf && dbt == VT_BOOL) {
1944 vtop->c.i = (vtop->c.ld != 0);
1945 } else {
1946 if(sf)
1947 vtop->c.ll = (long long)vtop->c.ld;
1948 else if (sbt == (VT_LLONG|VT_UNSIGNED))
1949 vtop->c.ll = vtop->c.ull;
1950 else if (sbt & VT_UNSIGNED)
1951 vtop->c.ll = vtop->c.ui;
1952 #ifdef TCC_TARGET_X86_64
1953 else if (sbt == VT_PTR)
1955 #endif
1956 else if (sbt != VT_LLONG)
1957 vtop->c.ll = vtop->c.i;
1959 if (dbt == (VT_LLONG|VT_UNSIGNED))
1960 vtop->c.ull = vtop->c.ll;
1961 else if (dbt == VT_BOOL)
1962 vtop->c.i = (vtop->c.ll != 0);
1963 #ifdef TCC_TARGET_X86_64
1964 else if (dbt == VT_PTR)
1966 #endif
1967 else if (dbt != VT_LLONG) {
1968 int s = 0;
1969 if ((dbt & VT_BTYPE) == VT_BYTE)
1970 s = 24;
1971 else if ((dbt & VT_BTYPE) == VT_SHORT)
1972 s = 16;
1973 if(dbt & VT_UNSIGNED)
1974 vtop->c.ui = ((unsigned int)vtop->c.ll << s) >> s;
1975 else
1976 vtop->c.i = ((int)vtop->c.ll << s) >> s;
1979 } else if (p && dbt == VT_BOOL) {
1980 vtop->r = VT_CONST;
1981 vtop->c.i = 1;
1982 } else if (!nocode_wanted) {
1983 /* non constant case: generate code */
1984 if (sf && df) {
1985 /* convert from fp to fp */
1986 gen_cvt_ftof(dbt);
1987 } else if (df) {
1988 /* convert int to fp */
1989 gen_cvt_itof1(dbt);
1990 } else if (sf) {
1991 /* convert fp to int */
1992 if (dbt == VT_BOOL) {
1993 vpushi(0);
1994 gen_op(TOK_NE);
1995 } else {
1996 /* we handle char/short/etc... with generic code */
1997 if (dbt != (VT_INT | VT_UNSIGNED) &&
1998 dbt != (VT_LLONG | VT_UNSIGNED) &&
1999 dbt != VT_LLONG)
2000 dbt = VT_INT;
2001 gen_cvt_ftoi1(dbt);
2002 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
2003 /* additional cast for char/short... */
2004 vtop->type.t = dbt;
2005 gen_cast(type);
2008 #ifndef TCC_TARGET_X86_64
2009 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
2010 if ((sbt & VT_BTYPE) != VT_LLONG) {
2011 /* scalar to long long */
2012 /* machine independent conversion */
2013 gv(RC_INT);
2014 /* generate high word */
2015 if (sbt == (VT_INT | VT_UNSIGNED)) {
2016 vpushi(0);
2017 gv(RC_INT);
2018 } else {
2019 if (sbt == VT_PTR) {
2020 /* cast from pointer to int before we apply
2021 shift operation, which pointers don't support*/
2022 gen_cast(&int_type);
2024 gv_dup();
2025 vpushi(31);
2026 gen_op(TOK_SAR);
2028 /* patch second register */
2029 vtop[-1].r2 = vtop->r;
2030 vpop();
2032 #else
2033 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
2034 (dbt & VT_BTYPE) == VT_PTR ||
2035 (dbt & VT_BTYPE) == VT_FUNC) {
2036 if ((sbt & VT_BTYPE) != VT_LLONG &&
2037 (sbt & VT_BTYPE) != VT_PTR &&
2038 (sbt & VT_BTYPE) != VT_FUNC) {
2039 /* need to convert from 32bit to 64bit */
2040 int r = gv(RC_INT);
2041 if (sbt != (VT_INT | VT_UNSIGNED)) {
2042 /* x86_64 specific: movslq */
2043 o(0x6348);
2044 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
2047 #endif
2048 } else if (dbt == VT_BOOL) {
2049 /* scalar to bool */
2050 vpushi(0);
2051 gen_op(TOK_NE);
2052 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
2053 (dbt & VT_BTYPE) == VT_SHORT) {
2054 if (sbt == VT_PTR) {
2055 vtop->type.t = VT_INT;
2056 tcc_warning("nonportable conversion from pointer to char/short");
2058 force_charshort_cast(dbt);
2059 } else if ((dbt & VT_BTYPE) == VT_INT) {
2060 /* scalar to int */
2061 if (sbt == VT_LLONG) {
2062 /* from long long: just take low order word */
2063 lexpand();
2064 vpop();
2066 /* if lvalue and single word type, nothing to do because
2067 the lvalue already contains the real type size (see
2068 VT_LVAL_xxx constants) */
2071 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
2072 /* if we are casting between pointer types,
2073 we must update the VT_LVAL_xxx size */
2074 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
2075 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
2077 vtop->type = *type;
2080 /* return type size as known at compile time. Put alignment at 'a' */
2081 ST_FUNC int type_size(CType *type, int *a)
2083 Sym *s;
2084 int bt;
2085 size_t size;
2087 bt = type->t & VT_BTYPE;
2088 if (bt == VT_STRUCT) {
2089 assert(!(type->t & VT_VLS));
2090 /* struct/union */
2091 s = type->ref;
2092 *a = s->r;
2093 size = s->c;
2094 } else if (bt == VT_PTR) {
2095 if (type->t & VT_ARRAY) {
2096 int ts;
2097 s = type->ref;
2098 ts = type_size(&s->type, a);
2099 if (ts < 0 && s->c < 0)
2100 ts = -ts;
2101 size = (size_t)ts * s->c;
2102 } else {
2103 *a = PTR_SIZE;
2104 size = PTR_SIZE;
2106 } else if (bt == VT_LDOUBLE) {
2107 *a = LDOUBLE_ALIGN;
2108 size = LDOUBLE_SIZE;
2109 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
2110 #ifdef TCC_TARGET_I386
2111 #ifdef TCC_TARGET_PE
2112 *a = 8;
2113 #else
2114 *a = 4;
2115 #endif
2116 #elif defined(TCC_TARGET_ARM)
2117 #ifdef TCC_ARM_EABI
2118 *a = 8;
2119 #else
2120 *a = 4;
2121 #endif
2122 #else
2123 *a = 8;
2124 #endif
2125 size = 8;
2126 } else if (bt == VT_INT || bt == VT_ENUM || bt == VT_FLOAT) {
2127 *a = 4;
2128 size = 4;
2129 } else if (bt == VT_SHORT) {
2130 *a = 2;
2131 size = 2;
2132 } else if (bt == VT_QLONG || bt == VT_QFLOAT) {
2133 *a = 8;
2134 size = 16;
2135 } else {
2136 /* char, void, function, _Bool */
2137 *a = 1;
2138 size = 1;
2140 assert(size == (int)size);
2141 return (int)size;
2144 /* push type size as known at runtime time on top of value stack. Put
2145 alignment at 'a' */
2146 ST_FUNC void vla_runtime_type_size(CType *type, int *a)
2148 if (type->t & VT_VLA) {
2149 vset(&int_type, VT_LOCAL|VT_LVAL, type->ref->c);
2150 } else {
2151 vpushi(type_size(type, a));
2155 static void vla_sp_save(void) {
2156 if (!(vla_flags & VLA_SP_LOC_SET)) {
2157 *vla_sp_loc = (loc -= PTR_SIZE);
2158 vla_flags |= VLA_SP_LOC_SET;
2160 if (!(vla_flags & VLA_SP_SAVED)) {
2161 gen_vla_sp_save(*vla_sp_loc);
2162 vla_flags |= VLA_SP_SAVED;
2166 /* return the pointed type of t */
2167 static inline CType *pointed_type(CType *type)
2169 return &type->ref->type;
2172 /* modify type so that its it is a pointer to type. */
2173 ST_FUNC void mk_pointer(CType *type)
2175 Sym *s;
2176 s = sym_push(SYM_FIELD, type, 0, -1);
2177 type->t = VT_PTR | (type->t & ~VT_TYPE);
2178 type->ref = s;
2181 /* compare function types. OLD functions match any new functions */
2182 static int is_compatible_func(CType *type1, CType *type2)
2184 Sym *s1, *s2;
2186 s1 = type1->ref;
2187 s2 = type2->ref;
2188 if (!is_compatible_types(&s1->type, &s2->type))
2189 return 0;
2190 /* check func_call */
2191 if (s1->a.func_call != s2->a.func_call)
2192 return 0;
2193 /* XXX: not complete */
2194 if (s1->c == FUNC_OLD || s2->c == FUNC_OLD)
2195 return 1;
2196 if (s1->c != s2->c)
2197 return 0;
2198 while (s1 != NULL) {
2199 if (s2 == NULL)
2200 return 0;
2201 if (!is_compatible_parameter_types(&s1->type, &s2->type))
2202 return 0;
2203 s1 = s1->next;
2204 s2 = s2->next;
2206 if (s2)
2207 return 0;
2208 return 1;
2211 /* return true if type1 and type2 are the same. If unqualified is
2212 true, qualifiers on the types are ignored.
2214 - enums are not checked as gcc __builtin_types_compatible_p ()
2216 static int compare_types(CType *type1, CType *type2, int unqualified)
2218 int bt1, t1, t2;
2220 t1 = type1->t & VT_TYPE;
2221 t2 = type2->t & VT_TYPE;
2222 if (unqualified) {
2223 /* strip qualifiers before comparing */
2224 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
2225 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
2227 /* Default Vs explicit signedness only matters for char */
2228 if ((t1 & VT_BTYPE) != VT_BYTE) {
2229 t1 &= ~VT_DEFSIGN;
2230 t2 &= ~VT_DEFSIGN;
2232 /* XXX: bitfields ? */
2233 if (t1 != t2)
2234 return 0;
2235 /* test more complicated cases */
2236 bt1 = t1 & VT_BTYPE;
2237 if (bt1 == VT_PTR) {
2238 type1 = pointed_type(type1);
2239 type2 = pointed_type(type2);
2240 return is_compatible_types(type1, type2);
2241 } else if (bt1 == VT_STRUCT) {
2242 return (type1->ref == type2->ref);
2243 } else if (bt1 == VT_FUNC) {
2244 return is_compatible_func(type1, type2);
2245 } else {
2246 return 1;
2250 /* return true if type1 and type2 are exactly the same (including
2251 qualifiers).
2253 static int is_compatible_types(CType *type1, CType *type2)
2255 return compare_types(type1,type2,0);
2258 /* return true if type1 and type2 are the same (ignoring qualifiers).
2260 static int is_compatible_parameter_types(CType *type1, CType *type2)
2262 return compare_types(type1,type2,1);
2265 /* print a type. If 'varstr' is not NULL, then the variable is also
2266 printed in the type */
2267 /* XXX: union */
2268 /* XXX: add array and function pointers */
2269 static void type_to_str(char *buf, int buf_size,
2270 CType *type, const char *varstr)
2272 int bt, v, t;
2273 Sym *s, *sa;
2274 char buf1[256];
2275 const char *tstr;
2277 t = type->t & VT_TYPE;
2278 bt = t & VT_BTYPE;
2279 buf[0] = '\0';
2280 if (t & VT_CONSTANT)
2281 pstrcat(buf, buf_size, "const ");
2282 if (t & VT_VOLATILE)
2283 pstrcat(buf, buf_size, "volatile ");
2284 if ((t & (VT_DEFSIGN | VT_UNSIGNED)) == (VT_DEFSIGN | VT_UNSIGNED))
2285 pstrcat(buf, buf_size, "unsigned ");
2286 else if (t & VT_DEFSIGN)
2287 pstrcat(buf, buf_size, "signed ");
2288 switch(bt) {
2289 case VT_VOID:
2290 tstr = "void";
2291 goto add_tstr;
2292 case VT_BOOL:
2293 tstr = "_Bool";
2294 goto add_tstr;
2295 case VT_BYTE:
2296 tstr = "char";
2297 goto add_tstr;
2298 case VT_SHORT:
2299 tstr = "short";
2300 goto add_tstr;
2301 case VT_INT:
2302 tstr = "int";
2303 goto add_tstr;
2304 case VT_LONG:
2305 tstr = "long";
2306 goto add_tstr;
2307 case VT_LLONG:
2308 tstr = "long long";
2309 goto add_tstr;
2310 case VT_FLOAT:
2311 tstr = "float";
2312 goto add_tstr;
2313 case VT_DOUBLE:
2314 tstr = "double";
2315 goto add_tstr;
2316 case VT_LDOUBLE:
2317 tstr = "long double";
2318 add_tstr:
2319 pstrcat(buf, buf_size, tstr);
2320 break;
2321 case VT_ENUM:
2322 case VT_STRUCT:
2323 if (bt == VT_STRUCT)
2324 tstr = "struct ";
2325 else
2326 tstr = "enum ";
2327 pstrcat(buf, buf_size, tstr);
2328 v = type->ref->v & ~SYM_STRUCT;
2329 if (v >= SYM_FIRST_ANOM)
2330 pstrcat(buf, buf_size, "<anonymous>");
2331 else
2332 pstrcat(buf, buf_size, get_tok_str(v, NULL));
2333 break;
2334 case VT_FUNC:
2335 s = type->ref;
2336 type_to_str(buf, buf_size, &s->type, varstr);
2337 pstrcat(buf, buf_size, "(");
2338 sa = s->next;
2339 while (sa != NULL) {
2340 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
2341 pstrcat(buf, buf_size, buf1);
2342 sa = sa->next;
2343 if (sa)
2344 pstrcat(buf, buf_size, ", ");
2346 pstrcat(buf, buf_size, ")");
2347 goto no_var;
2348 case VT_PTR:
2349 s = type->ref;
2350 pstrcpy(buf1, sizeof(buf1), "*");
2351 if (varstr)
2352 pstrcat(buf1, sizeof(buf1), varstr);
2353 type_to_str(buf, buf_size, &s->type, buf1);
2354 goto no_var;
2356 if (varstr) {
2357 pstrcat(buf, buf_size, " ");
2358 pstrcat(buf, buf_size, varstr);
2360 no_var: ;
2363 /* verify type compatibility to store vtop in 'dt' type, and generate
2364 casts if needed. */
2365 static void gen_assign_cast(CType *dt)
2367 CType *st, *type1, *type2, tmp_type1, tmp_type2;
2368 char buf1[256], buf2[256];
2369 int dbt, sbt;
2371 st = &vtop->type; /* source type */
2372 dbt = dt->t & VT_BTYPE;
2373 sbt = st->t & VT_BTYPE;
2374 if (sbt == VT_VOID || dbt == VT_VOID)
2375 tcc_error("cannot cast from/to void");
2376 if (dt->t & VT_CONSTANT)
2377 tcc_warning("assignment of read-only location");
2378 switch(dbt) {
2379 case VT_PTR:
2380 /* special cases for pointers */
2381 /* '0' can also be a pointer */
2382 if (is_null_pointer(vtop))
2383 goto type_ok;
2384 /* accept implicit pointer to integer cast with warning */
2385 if (is_integer_btype(sbt)) {
2386 tcc_warning("assignment makes pointer from integer without a cast");
2387 goto type_ok;
2389 type1 = pointed_type(dt);
2390 /* a function is implicitely a function pointer */
2391 if (sbt == VT_FUNC) {
2392 if ((type1->t & VT_BTYPE) != VT_VOID &&
2393 !is_compatible_types(pointed_type(dt), st))
2394 tcc_warning("assignment from incompatible pointer type");
2395 goto type_ok;
2397 if (sbt != VT_PTR)
2398 goto error;
2399 type2 = pointed_type(st);
2400 if ((type1->t & VT_BTYPE) == VT_VOID ||
2401 (type2->t & VT_BTYPE) == VT_VOID) {
2402 /* void * can match anything */
2403 } else {
2404 /* exact type match, except for unsigned */
2405 tmp_type1 = *type1;
2406 tmp_type2 = *type2;
2407 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT |
2408 VT_VOLATILE);
2409 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT |
2410 VT_VOLATILE);
2411 if (!is_compatible_types(&tmp_type1, &tmp_type2))
2412 tcc_warning("assignment from incompatible pointer type");
2414 /* check const and volatile */
2415 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
2416 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
2417 tcc_warning("assignment discards qualifiers from pointer target type");
2418 break;
2419 case VT_BYTE:
2420 case VT_SHORT:
2421 case VT_INT:
2422 case VT_LLONG:
2423 if (sbt == VT_PTR || sbt == VT_FUNC) {
2424 tcc_warning("assignment makes integer from pointer without a cast");
2426 /* XXX: more tests */
2427 break;
2428 case VT_STRUCT:
2429 tmp_type1 = *dt;
2430 tmp_type2 = *st;
2431 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2432 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2433 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2434 error:
2435 type_to_str(buf1, sizeof(buf1), st, NULL);
2436 type_to_str(buf2, sizeof(buf2), dt, NULL);
2437 tcc_error("cannot cast '%s' to '%s'", buf1, buf2);
2439 break;
2441 type_ok:
2442 gen_cast(dt);
2445 static void vstore_im(){
2446 int rc, ft, sbt, dbt, t, r;
2447 ft = vtop[-1].type.t;
2448 sbt = vtop->type.t & VT_BTYPE;
2449 dbt = ft & VT_BTYPE;
2450 if (is_float(ft)) {
2451 rc = RC_FLOAT;
2452 #ifdef TCC_TARGET_X86_64
2453 if (dbt == VT_LDOUBLE) {
2454 rc = RC_ST0;
2456 #endif
2457 }else
2458 rc = RC_INT;
2459 r = gv(rc); /* generate value */
2460 /* if lvalue was saved on stack, must read it */
2461 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
2462 SValue sv;
2463 t = get_reg(RC_INT);
2464 #ifdef TCC_TARGET_X86_64
2465 sv.type.t = VT_PTR;
2466 #else
2467 sv.type.t = VT_INT;
2468 #endif
2469 sv.r = VT_LOCAL | VT_LVAL;
2470 sv.c.ul = vtop[-1].c.ul;
2471 load(t, &sv);
2472 vtop[-1].r = t | VT_LVAL;
2473 vtop[-1].c.ul = 0;
2475 /* two word case handling : store second register at word + 4 */
2476 #ifdef TCC_TARGET_X86_64
2477 if ((dbt == VT_QLONG) || (dbt == VT_QFLOAT))
2478 #else
2479 if (dbt == VT_LLONG)
2480 #endif
2482 #ifdef TCC_TARGET_X86_64
2483 int load_size = 8, load_type = (sbt == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
2484 #else
2485 int load_size = 4, load_type = VT_INT;
2486 #endif
2487 vtop[-1].type.t = load_type;
2488 store(r, vtop - 1);
2489 vswap();
2490 /* convert to int to increment easily */
2491 vtop->type = char_pointer_type;
2492 gaddrof();
2493 vpushi(load_size);
2494 gen_op('+');
2495 vtop->r |= VT_LVAL;
2496 vswap();
2497 vtop[-1].type.t = load_type;
2498 /* XXX: it works because r2 is spilled last ! */
2499 store(vtop->r2, vtop - 1);
2500 vtop->type.t = ft;
2501 vtop[-1].type.t = ft;
2502 } else {
2503 store(r, vtop - 1);
2507 /* store vtop in lvalue pushed on stack */
2508 ST_FUNC void vstore(void)
2510 int sbt, dbt, ft, size, align, bit_size, bit_pos, delayed_cast;
2512 ft = vtop[-1].type.t;
2513 sbt = vtop->type.t & VT_BTYPE;
2514 dbt = ft & VT_BTYPE;
2515 if ((((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
2516 (sbt == VT_INT && dbt == VT_SHORT)) && !(vtop->type.t & VT_BITFIELD)) {
2517 /* optimize char/short casts */
2518 delayed_cast = VT_MUSTCAST;
2519 vtop->type.t = ft & (VT_TYPE & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT)));
2520 /* XXX: factorize */
2521 if (ft & VT_CONSTANT)
2522 tcc_warning("assignment of read-only location");
2523 } else {
2524 delayed_cast = 0;
2525 if (!(ft & VT_BITFIELD))
2526 gen_assign_cast(&vtop[-1].type);
2529 if (sbt == VT_STRUCT) {
2530 /* if structure, only generate pointer */
2531 /* structure assignment : generate memcpy */
2532 /* XXX: optimize if small size */
2533 if (!nocode_wanted) {
2534 SValue ret;
2535 int ret_nregs, ret_align;
2536 ret_nregs = gfunc_sret(&vtop->type, func_var, &ret.type, &ret_align);
2537 if(0){
2538 vswap();
2539 vpushv(vtop - 1);
2540 vtop[0].type = ret.type;
2541 vtop[-1].type = ret.type;
2542 vstore_im();
2543 vtop -=2;
2544 }else{
2545 size = type_size(&vtop->type, &align);
2546 #ifndef TCC_TARGET_X86_64
2547 /* destination */
2548 vswap();
2549 vtop->type.t = VT_PTR;
2550 gaddrof();
2552 /* address of memcpy() */
2553 # ifdef TCC_ARM_EABI
2554 if(!(align & 7))
2555 vpush_global_sym(&func_old_type, TOK_memcpy8);
2556 else if(!(align & 3))
2557 vpush_global_sym(&func_old_type, TOK_memcpy4);
2558 else
2559 # endif
2560 vpush_global_sym(&func_old_type, TOK_memcpy);
2562 vswap();
2563 /* source */
2564 vpushv(vtop - 2);
2565 vtop->type.t = VT_PTR;
2566 gaddrof();
2567 /* type size */
2568 vpushi(size);
2569 gfunc_call(3);
2570 #else
2571 /* destination */
2572 vswap();
2573 vtop->type.t = VT_PTR;
2574 gaddrof();
2575 /* source */
2576 vpushv(vtop - 1);
2577 vtop->type.t = VT_PTR;
2578 gaddrof();
2579 /* size */
2580 vpushi(size);
2581 struct_copy(&vtop[-2], &vtop[-1], &vtop[0]);
2582 vtop -=3;
2583 #endif
2585 } else {
2586 vswap();
2587 vpop();
2589 /* leave source on stack */
2590 } else if (ft & VT_BITFIELD) {
2591 /* bitfield store handling */
2592 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
2593 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
2594 /* remove bit field info to avoid loops */
2595 vtop[-1].type.t = ft & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
2596 /* duplicate source into other register */
2597 if(dbt == VT_BOOL) {
2598 gen_cast(&vtop[-1].type);
2599 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
2602 /* duplicate destination */
2603 vdup();
2604 vtop[-1] = vtop[-2];
2606 /* mask and shift source */
2607 if(dbt != VT_BOOL) {
2608 if(dbt == VT_LLONG) {
2609 vpushll((1ULL << bit_size) - 1ULL);
2610 } else {
2611 vpushi((1 << bit_size) - 1);
2613 gen_op('&');
2615 vpushi(bit_pos);
2616 gen_op(TOK_SHL);
2617 /* load destination, mask and or with source */
2618 vswap();
2619 if(dbt == VT_LLONG) {
2620 vpushll(~(((1ULL << bit_size) - 1ULL) << bit_pos));
2621 } else {
2622 vpushi(~(((1 << bit_size) - 1) << bit_pos));
2624 gen_op('&');
2625 gen_op('|');
2626 /* store result */
2627 vstore();
2628 } else {
2629 #ifdef CONFIG_TCC_BCHECK
2630 /* bound check case */
2631 if (vtop[-1].r & VT_MUSTBOUND) {
2632 vswap();
2633 gbound();
2634 vswap();
2636 #endif
2637 if (!nocode_wanted) {
2638 vstore_im();
2640 vswap();
2641 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
2642 vtop->r |= delayed_cast;
2646 /* post defines POST/PRE add. c is the token ++ or -- */
2647 ST_FUNC void inc(int post, int c)
2649 test_lvalue();
2650 vdup(); /* save lvalue */
2651 if (post) {
2652 gv_dup(); /* duplicate value */
2653 vrotb(3);
2654 vrotb(3);
2656 /* add constant */
2657 vpushi(c - TOK_MID);
2658 gen_op('+');
2659 vstore(); /* store value */
2660 if (post)
2661 vpop(); /* if post op, return saved value */
2664 /* Parse GNUC __attribute__ extension. Currently, the following
2665 extensions are recognized:
2666 - aligned(n) : set data/function alignment.
2667 - packed : force data alignment to 1
2668 - section(x) : generate data/code in this section.
2669 - unused : currently ignored, but may be used someday.
2670 - regparm(n) : pass function parameters in registers (i386 only)
2672 static void parse_attribute(AttributeDef *ad)
2674 int t, n;
2676 while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
2677 next();
2678 skip('(');
2679 skip('(');
2680 while (tok != ')') {
2681 if (tok < TOK_IDENT)
2682 expect("attribute name");
2683 t = tok;
2684 next();
2685 switch(t) {
2686 case TOK_SECTION1:
2687 case TOK_SECTION2:
2688 skip('(');
2689 if (tok != TOK_STR)
2690 expect("section name");
2691 ad->section = find_section(tcc_state, (char *)tokc.cstr->data);
2692 next();
2693 skip(')');
2694 break;
2695 case TOK_ALIAS1:
2696 case TOK_ALIAS2:
2697 skip('(');
2698 if (tok != TOK_STR)
2699 expect("alias(\"target\")");
2700 ad->alias_target = /* save string as token, for later */
2701 tok_alloc((char*)tokc.cstr->data, tokc.cstr->size-1)->tok;
2702 next();
2703 skip(')');
2704 break;
2705 case TOK_VISIBILITY1:
2706 case TOK_VISIBILITY2:
2707 skip('(');
2708 if (tok != TOK_STR)
2709 expect("visibility(\"default|hidden|internal|protected\")");
2710 if (!strcmp (tokc.cstr->data, "default"))
2711 ad->a.visibility = STV_DEFAULT;
2712 else if (!strcmp (tokc.cstr->data, "hidden"))
2713 ad->a.visibility = STV_HIDDEN;
2714 else if (!strcmp (tokc.cstr->data, "internal"))
2715 ad->a.visibility = STV_INTERNAL;
2716 else if (!strcmp (tokc.cstr->data, "protected"))
2717 ad->a.visibility = STV_PROTECTED;
2718 else
2719 expect("visibility(\"default|hidden|internal|protected\")");
2720 next();
2721 skip(')');
2722 break;
2723 case TOK_ALIGNED1:
2724 case TOK_ALIGNED2:
2725 if (tok == '(') {
2726 next();
2727 n = expr_const();
2728 if (n <= 0 || (n & (n - 1)) != 0)
2729 tcc_error("alignment must be a positive power of two");
2730 skip(')');
2731 } else {
2732 n = MAX_ALIGN;
2734 ad->a.aligned = n;
2735 break;
2736 case TOK_PACKED1:
2737 case TOK_PACKED2:
2738 ad->a.packed = 1;
2739 break;
2740 case TOK_WEAK1:
2741 case TOK_WEAK2:
2742 ad->a.weak = 1;
2743 break;
2744 case TOK_UNUSED1:
2745 case TOK_UNUSED2:
2746 /* currently, no need to handle it because tcc does not
2747 track unused objects */
2748 break;
2749 case TOK_NORETURN1:
2750 case TOK_NORETURN2:
2751 /* currently, no need to handle it because tcc does not
2752 track unused objects */
2753 break;
2754 case TOK_CDECL1:
2755 case TOK_CDECL2:
2756 case TOK_CDECL3:
2757 ad->a.func_call = FUNC_CDECL;
2758 break;
2759 case TOK_STDCALL1:
2760 case TOK_STDCALL2:
2761 case TOK_STDCALL3:
2762 ad->a.func_call = FUNC_STDCALL;
2763 break;
2764 #ifdef TCC_TARGET_I386
2765 case TOK_REGPARM1:
2766 case TOK_REGPARM2:
2767 skip('(');
2768 n = expr_const();
2769 if (n > 3)
2770 n = 3;
2771 else if (n < 0)
2772 n = 0;
2773 if (n > 0)
2774 ad->a.func_call = FUNC_FASTCALL1 + n - 1;
2775 skip(')');
2776 break;
2777 case TOK_FASTCALL1:
2778 case TOK_FASTCALL2:
2779 case TOK_FASTCALL3:
2780 ad->a.func_call = FUNC_FASTCALLW;
2781 break;
2782 #endif
2783 case TOK_MODE:
2784 skip('(');
2785 switch(tok) {
2786 case TOK_MODE_DI:
2787 ad->a.mode = VT_LLONG + 1;
2788 break;
2789 case TOK_MODE_HI:
2790 ad->a.mode = VT_SHORT + 1;
2791 break;
2792 case TOK_MODE_SI:
2793 ad->a.mode = VT_INT + 1;
2794 break;
2795 default:
2796 tcc_warning("__mode__(%s) not supported\n", get_tok_str(tok, NULL));
2797 break;
2799 next();
2800 skip(')');
2801 break;
2802 case TOK_DLLEXPORT:
2803 ad->a.func_export = 1;
2804 break;
2805 case TOK_DLLIMPORT:
2806 ad->a.func_import = 1;
2807 break;
2808 default:
2809 if (tcc_state->warn_unsupported)
2810 tcc_warning("'%s' attribute ignored", get_tok_str(t, NULL));
2811 /* skip parameters */
2812 if (tok == '(') {
2813 int parenthesis = 0;
2814 do {
2815 if (tok == '(')
2816 parenthesis++;
2817 else if (tok == ')')
2818 parenthesis--;
2819 next();
2820 } while (parenthesis && tok != -1);
2822 break;
2824 if (tok != ',')
2825 break;
2826 next();
2828 skip(')');
2829 skip(')');
2833 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
2834 static void struct_decl(CType *type, int u, int tdef)
2836 int a, v, size, align, maxalign, c, offset, flexible;
2837 int bit_size, bit_pos, bsize, bt, lbit_pos, prevbt;
2838 Sym *s, *ss, *ass, **ps;
2839 AttributeDef ad;
2840 CType type1, btype;
2842 a = tok; /* save decl type */
2843 next();
2844 if (tok != '{') {
2845 v = tok;
2846 next();
2847 /* struct already defined ? return it */
2848 if (v < TOK_IDENT)
2849 expect("struct/union/enum name");
2850 s = struct_find(v);
2851 if (s) {
2852 if (s->type.t != a)
2853 tcc_error("invalid type");
2854 goto do_decl;
2855 } else if (tok >= TOK_IDENT && !tdef)
2856 tcc_error("unknown struct/union/enum");
2857 } else {
2858 v = anon_sym++;
2860 type1.t = a;
2861 type1.ref = NULL;
2862 /* we put an undefined size for struct/union */
2863 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
2864 s->r = 0; /* default alignment is zero as gcc */
2865 /* put struct/union/enum name in type */
2866 do_decl:
2867 type->t = u;
2868 type->ref = s;
2870 if (tok == '{') {
2871 next();
2872 if (s->c != -1)
2873 tcc_error("struct/union/enum already defined");
2874 /* cannot be empty */
2875 c = 0;
2876 /* non empty enums are not allowed */
2877 if (a == TOK_ENUM) {
2878 for(;;) {
2879 v = tok;
2880 if (v < TOK_UIDENT)
2881 expect("identifier");
2882 ss = sym_find(v);
2883 if (ss && !local_stack)
2884 tcc_error("redefinition of enumerator '%s'",
2885 get_tok_str(v, NULL));
2886 next();
2887 if (tok == '=') {
2888 next();
2889 c = expr_const();
2891 /* enum symbols have static storage */
2892 ss = sym_push(v, &int_type, VT_CONST, c);
2893 ss->type.t |= VT_STATIC;
2894 if (tok != ',')
2895 break;
2896 next();
2897 c++;
2898 /* NOTE: we accept a trailing comma */
2899 if (tok == '}')
2900 break;
2902 s->c = type_size(&int_type, &align);
2903 skip('}');
2904 } else {
2905 maxalign = 1;
2906 ps = &s->next;
2907 prevbt = VT_INT;
2908 bit_pos = 0;
2909 offset = 0;
2910 flexible = 0;
2911 while (tok != '}') {
2912 parse_btype(&btype, &ad);
2913 while (1) {
2914 if (flexible)
2915 tcc_error("flexible array member '%s' not at the end of struct",
2916 get_tok_str(v, NULL));
2917 bit_size = -1;
2918 v = 0;
2919 type1 = btype;
2920 if (tok != ':') {
2921 type_decl(&type1, &ad, &v, TYPE_DIRECT | TYPE_ABSTRACT);
2922 if (v == 0 && (type1.t & VT_BTYPE) != VT_STRUCT)
2923 expect("identifier");
2924 if (type_size(&type1, &align) < 0) {
2925 if ((a == TOK_STRUCT) && (type1.t & VT_ARRAY) && c)
2926 flexible = 1;
2927 else
2928 tcc_error("field '%s' has incomplete type",
2929 get_tok_str(v, NULL));
2931 if ((type1.t & VT_BTYPE) == VT_FUNC ||
2932 (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
2933 tcc_error("invalid type for '%s'",
2934 get_tok_str(v, NULL));
2936 if (tok == ':') {
2937 next();
2938 bit_size = expr_const();
2939 /* XXX: handle v = 0 case for messages */
2940 if (bit_size < 0)
2941 tcc_error("negative width in bit-field '%s'",
2942 get_tok_str(v, NULL));
2943 if (v && bit_size == 0)
2944 tcc_error("zero width for bit-field '%s'",
2945 get_tok_str(v, NULL));
2947 size = type_size(&type1, &align);
2948 if (ad.a.aligned) {
2949 if (align < ad.a.aligned)
2950 align = ad.a.aligned;
2951 } else if (ad.a.packed) {
2952 align = 1;
2953 } else if (*tcc_state->pack_stack_ptr) {
2954 if (align > *tcc_state->pack_stack_ptr)
2955 align = *tcc_state->pack_stack_ptr;
2957 lbit_pos = 0;
2958 if (bit_size >= 0) {
2959 bt = type1.t & VT_BTYPE;
2960 if (bt != VT_INT &&
2961 bt != VT_BYTE &&
2962 bt != VT_SHORT &&
2963 bt != VT_BOOL &&
2964 bt != VT_ENUM &&
2965 bt != VT_LLONG)
2966 tcc_error("bitfields must have scalar type");
2967 bsize = size * 8;
2968 if (bit_size > bsize) {
2969 tcc_error("width of '%s' exceeds its type",
2970 get_tok_str(v, NULL));
2971 } else if (bit_size == bsize) {
2972 /* no need for bit fields */
2973 bit_pos = 0;
2974 } else if (bit_size == 0) {
2975 /* XXX: what to do if only padding in a
2976 structure ? */
2977 /* zero size: means to pad */
2978 bit_pos = 0;
2979 } else {
2980 /* we do not have enough room ?
2981 did the type change?
2982 is it a union? */
2983 if ((bit_pos + bit_size) > bsize ||
2984 bt != prevbt || a == TOK_UNION)
2985 bit_pos = 0;
2986 lbit_pos = bit_pos;
2987 /* XXX: handle LSB first */
2988 type1.t |= VT_BITFIELD |
2989 (bit_pos << VT_STRUCT_SHIFT) |
2990 (bit_size << (VT_STRUCT_SHIFT + 6));
2991 bit_pos += bit_size;
2993 prevbt = bt;
2994 } else {
2995 bit_pos = 0;
2997 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
2998 /* add new memory data only if starting
2999 bit field */
3000 if (lbit_pos == 0) {
3001 if (a == TOK_STRUCT) {
3002 c = (c + align - 1) & -align;
3003 offset = c;
3004 if (size > 0)
3005 c += size;
3006 } else {
3007 offset = 0;
3008 if (size > c)
3009 c = size;
3011 if (align > maxalign)
3012 maxalign = align;
3014 #if 0
3015 printf("add field %s offset=%d",
3016 get_tok_str(v, NULL), offset);
3017 if (type1.t & VT_BITFIELD) {
3018 printf(" pos=%d size=%d",
3019 (type1.t >> VT_STRUCT_SHIFT) & 0x3f,
3020 (type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
3022 printf("\n");
3023 #endif
3025 if (v == 0 && (type1.t & VT_BTYPE) == VT_STRUCT) {
3026 ass = type1.ref;
3027 while ((ass = ass->next) != NULL) {
3028 ss = sym_push(ass->v, &ass->type, 0, offset + ass->c);
3029 *ps = ss;
3030 ps = &ss->next;
3032 } else if (v) {
3033 ss = sym_push(v | SYM_FIELD, &type1, 0, offset);
3034 *ps = ss;
3035 ps = &ss->next;
3037 if (tok == ';' || tok == TOK_EOF)
3038 break;
3039 skip(',');
3041 skip(';');
3043 skip('}');
3044 /* store size and alignment */
3045 s->c = (c + maxalign - 1) & -maxalign;
3046 s->r = maxalign;
3051 /* return 1 if basic type is a type size (short, long, long long) */
3052 ST_FUNC int is_btype_size(int bt)
3054 return bt == VT_SHORT || bt == VT_LONG || bt == VT_LLONG;
3057 /* return 0 if no type declaration. otherwise, return the basic type
3058 and skip it.
3060 static int parse_btype(CType *type, AttributeDef *ad)
3062 int t, u, bt_size, complete, type_found, typespec_found;
3063 Sym *s;
3064 CType type1;
3066 memset(ad, 0, sizeof(AttributeDef));
3067 complete = 0;
3068 type_found = 0;
3069 typespec_found = 0;
3070 t = 0;
3071 while(1) {
3072 switch(tok) {
3073 case TOK_EXTENSION:
3074 /* currently, we really ignore extension */
3075 next();
3076 continue;
3078 /* basic types */
3079 case TOK_CHAR:
3080 u = VT_BYTE;
3081 basic_type:
3082 next();
3083 basic_type1:
3084 if (complete)
3085 tcc_error("too many basic types");
3086 t |= u;
3087 bt_size = is_btype_size (u & VT_BTYPE);
3088 if (u == VT_INT || (!bt_size && !(t & VT_TYPEDEF)))
3089 complete = 1;
3090 typespec_found = 1;
3091 break;
3092 case TOK_VOID:
3093 u = VT_VOID;
3094 goto basic_type;
3095 case TOK_SHORT:
3096 u = VT_SHORT;
3097 goto basic_type;
3098 case TOK_INT:
3099 u = VT_INT;
3100 goto basic_type;
3101 case TOK_LONG:
3102 next();
3103 if ((t & VT_BTYPE) == VT_DOUBLE) {
3104 #ifndef TCC_TARGET_PE
3105 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3106 #endif
3107 } else if ((t & VT_BTYPE) == VT_LONG) {
3108 t = (t & ~VT_BTYPE) | VT_LLONG;
3109 } else {
3110 u = VT_LONG;
3111 goto basic_type1;
3113 break;
3114 case TOK_BOOL:
3115 u = VT_BOOL;
3116 goto basic_type;
3117 case TOK_FLOAT:
3118 u = VT_FLOAT;
3119 goto basic_type;
3120 case TOK_DOUBLE:
3121 next();
3122 if ((t & VT_BTYPE) == VT_LONG) {
3123 #ifdef TCC_TARGET_PE
3124 t = (t & ~VT_BTYPE) | VT_DOUBLE;
3125 #else
3126 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3127 #endif
3128 } else {
3129 u = VT_DOUBLE;
3130 goto basic_type1;
3132 break;
3133 case TOK_ENUM:
3134 struct_decl(&type1, VT_ENUM, t & VT_TYPEDEF);
3135 basic_type2:
3136 u = type1.t;
3137 type->ref = type1.ref;
3138 goto basic_type1;
3139 case TOK_STRUCT:
3140 case TOK_UNION:
3141 struct_decl(&type1, VT_STRUCT, t & VT_TYPEDEF);
3142 goto basic_type2;
3144 /* type modifiers */
3145 case TOK_CONST1:
3146 case TOK_CONST2:
3147 case TOK_CONST3:
3148 t |= VT_CONSTANT;
3149 next();
3150 break;
3151 case TOK_VOLATILE1:
3152 case TOK_VOLATILE2:
3153 case TOK_VOLATILE3:
3154 t |= VT_VOLATILE;
3155 next();
3156 break;
3157 case TOK_SIGNED1:
3158 case TOK_SIGNED2:
3159 case TOK_SIGNED3:
3160 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == (VT_DEFSIGN|VT_UNSIGNED))
3161 tcc_error("signed and unsigned modifier");
3162 typespec_found = 1;
3163 t |= VT_DEFSIGN;
3164 next();
3165 break;
3166 case TOK_REGISTER:
3167 case TOK_AUTO:
3168 case TOK_RESTRICT1:
3169 case TOK_RESTRICT2:
3170 case TOK_RESTRICT3:
3171 next();
3172 break;
3173 case TOK_UNSIGNED:
3174 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == VT_DEFSIGN)
3175 tcc_error("signed and unsigned modifier");
3176 t |= VT_DEFSIGN | VT_UNSIGNED;
3177 next();
3178 typespec_found = 1;
3179 break;
3181 /* storage */
3182 case TOK_EXTERN:
3183 t |= VT_EXTERN;
3184 next();
3185 break;
3186 case TOK_STATIC:
3187 t |= VT_STATIC;
3188 next();
3189 break;
3190 case TOK_TYPEDEF:
3191 t |= VT_TYPEDEF;
3192 next();
3193 break;
3194 case TOK_INLINE1:
3195 case TOK_INLINE2:
3196 case TOK_INLINE3:
3197 t |= VT_INLINE;
3198 next();
3199 break;
3201 /* GNUC attribute */
3202 case TOK_ATTRIBUTE1:
3203 case TOK_ATTRIBUTE2:
3204 parse_attribute(ad);
3205 if (ad->a.mode) {
3206 u = ad->a.mode -1;
3207 t = (t & ~VT_BTYPE) | u;
3209 break;
3210 /* GNUC typeof */
3211 case TOK_TYPEOF1:
3212 case TOK_TYPEOF2:
3213 case TOK_TYPEOF3:
3214 next();
3215 parse_expr_type(&type1);
3216 /* remove all storage modifiers except typedef */
3217 type1.t &= ~(VT_STORAGE&~VT_TYPEDEF);
3218 goto basic_type2;
3219 default:
3220 if (typespec_found)
3221 goto the_end;
3222 s = sym_find(tok);
3223 if (!s || !(s->type.t & VT_TYPEDEF))
3224 goto the_end;
3225 t |= (s->type.t & ~VT_TYPEDEF);
3226 type->ref = s->type.ref;
3227 if (s->r) {
3228 /* get attributes from typedef */
3229 if (0 == ad->a.aligned)
3230 ad->a.aligned = s->a.aligned;
3231 if (0 == ad->a.func_call)
3232 ad->a.func_call = s->a.func_call;
3233 ad->a.packed |= s->a.packed;
3235 next();
3236 typespec_found = 1;
3237 break;
3239 type_found = 1;
3241 the_end:
3242 if (tcc_state->char_is_unsigned) {
3243 if ((t & (VT_DEFSIGN|VT_BTYPE)) == VT_BYTE)
3244 t |= VT_UNSIGNED;
3247 /* long is never used as type */
3248 if ((t & VT_BTYPE) == VT_LONG)
3249 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
3250 t = (t & ~VT_BTYPE) | VT_INT;
3251 #else
3252 t = (t & ~VT_BTYPE) | VT_LLONG;
3253 #endif
3254 type->t = t;
3255 return type_found;
3258 /* convert a function parameter type (array to pointer and function to
3259 function pointer) */
3260 static inline void convert_parameter_type(CType *pt)
3262 /* remove const and volatile qualifiers (XXX: const could be used
3263 to indicate a const function parameter */
3264 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
3265 /* array must be transformed to pointer according to ANSI C */
3266 pt->t &= ~VT_ARRAY;
3267 if ((pt->t & VT_BTYPE) == VT_FUNC) {
3268 mk_pointer(pt);
3272 ST_FUNC void parse_asm_str(CString *astr)
3274 skip('(');
3275 /* read the string */
3276 if (tok != TOK_STR)
3277 expect("string constant");
3278 cstr_new(astr);
3279 while (tok == TOK_STR) {
3280 /* XXX: add \0 handling too ? */
3281 cstr_cat(astr, tokc.cstr->data);
3282 next();
3284 cstr_ccat(astr, '\0');
3287 /* Parse an asm label and return the label
3288 * Don't forget to free the CString in the caller! */
3289 static void asm_label_instr(CString *astr)
3291 next();
3292 parse_asm_str(astr);
3293 skip(')');
3294 #ifdef ASM_DEBUG
3295 printf("asm_alias: \"%s\"\n", (char *)astr->data);
3296 #endif
3299 static void post_type(CType *type, AttributeDef *ad)
3301 int n, l, t1, arg_size, align;
3302 Sym **plast, *s, *first;
3303 AttributeDef ad1;
3304 CType pt;
3306 if (tok == '(') {
3307 /* function declaration */
3308 next();
3309 l = 0;
3310 first = NULL;
3311 plast = &first;
3312 arg_size = 0;
3313 if (tok != ')') {
3314 for(;;) {
3315 /* read param name and compute offset */
3316 if (l != FUNC_OLD) {
3317 if (!parse_btype(&pt, &ad1)) {
3318 if (l) {
3319 tcc_error("invalid type");
3320 } else {
3321 l = FUNC_OLD;
3322 goto old_proto;
3325 l = FUNC_NEW;
3326 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
3327 break;
3328 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
3329 if ((pt.t & VT_BTYPE) == VT_VOID)
3330 tcc_error("parameter declared as void");
3331 arg_size += (type_size(&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
3332 } else {
3333 old_proto:
3334 n = tok;
3335 if (n < TOK_UIDENT)
3336 expect("identifier");
3337 pt.t = VT_INT;
3338 next();
3340 convert_parameter_type(&pt);
3341 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
3342 *plast = s;
3343 plast = &s->next;
3344 if (tok == ')')
3345 break;
3346 skip(',');
3347 if (l == FUNC_NEW && tok == TOK_DOTS) {
3348 l = FUNC_ELLIPSIS;
3349 next();
3350 break;
3354 /* if no parameters, then old type prototype */
3355 if (l == 0)
3356 l = FUNC_OLD;
3357 skip(')');
3358 /* NOTE: const is ignored in returned type as it has a special
3359 meaning in gcc / C++ */
3360 type->t &= ~VT_CONSTANT;
3361 /* some ancient pre-K&R C allows a function to return an array
3362 and the array brackets to be put after the arguments, such
3363 that "int c()[]" means something like "int[] c()" */
3364 if (tok == '[') {
3365 next();
3366 skip(']'); /* only handle simple "[]" */
3367 type->t |= VT_PTR;
3369 /* we push a anonymous symbol which will contain the function prototype */
3370 ad->a.func_args = arg_size;
3371 s = sym_push(SYM_FIELD, type, 0, l);
3372 s->a = ad->a;
3373 s->next = first;
3374 type->t = VT_FUNC;
3375 type->ref = s;
3376 } else if (tok == '[') {
3377 /* array definition */
3378 next();
3379 if (tok == TOK_RESTRICT1)
3380 next();
3381 n = -1;
3382 t1 = 0;
3383 if (tok != ']') {
3384 if (!local_stack || nocode_wanted)
3385 vpushi(expr_const());
3386 else gexpr();
3387 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3388 n = vtop->c.i;
3389 if (n < 0)
3390 tcc_error("invalid array size");
3391 } else {
3392 if (!is_integer_btype(vtop->type.t & VT_BTYPE))
3393 tcc_error("size of variable length array should be an integer");
3394 t1 = VT_VLA;
3397 skip(']');
3398 /* parse next post type */
3399 post_type(type, ad);
3400 if (type->t == VT_FUNC)
3401 tcc_error("declaration of an array of functions");
3402 t1 |= type->t & VT_VLA;
3404 if (t1 & VT_VLA) {
3405 loc -= type_size(&int_type, &align);
3406 loc &= -align;
3407 n = loc;
3409 vla_runtime_type_size(type, &align);
3410 gen_op('*');
3411 vset(&int_type, VT_LOCAL|VT_LVAL, loc);
3412 vswap();
3413 vstore();
3415 if (n != -1)
3416 vpop();
3418 /* we push an anonymous symbol which will contain the array
3419 element type */
3420 s = sym_push(SYM_FIELD, type, 0, n);
3421 type->t = (t1 ? VT_VLA : VT_ARRAY) | VT_PTR;
3422 type->ref = s;
3426 /* Parse a type declaration (except basic type), and return the type
3427 in 'type'. 'td' is a bitmask indicating which kind of type decl is
3428 expected. 'type' should contain the basic type. 'ad' is the
3429 attribute definition of the basic type. It can be modified by
3430 type_decl().
3432 static void type_decl(CType *type, AttributeDef *ad, int *v, int td)
3434 Sym *s;
3435 CType type1, *type2;
3436 int qualifiers, storage;
3438 while (tok == '*') {
3439 qualifiers = 0;
3440 redo:
3441 next();
3442 switch(tok) {
3443 case TOK_CONST1:
3444 case TOK_CONST2:
3445 case TOK_CONST3:
3446 qualifiers |= VT_CONSTANT;
3447 goto redo;
3448 case TOK_VOLATILE1:
3449 case TOK_VOLATILE2:
3450 case TOK_VOLATILE3:
3451 qualifiers |= VT_VOLATILE;
3452 goto redo;
3453 case TOK_RESTRICT1:
3454 case TOK_RESTRICT2:
3455 case TOK_RESTRICT3:
3456 goto redo;
3458 mk_pointer(type);
3459 type->t |= qualifiers;
3462 /* XXX: clarify attribute handling */
3463 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3464 parse_attribute(ad);
3466 /* recursive type */
3467 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
3468 type1.t = 0; /* XXX: same as int */
3469 if (tok == '(') {
3470 next();
3471 /* XXX: this is not correct to modify 'ad' at this point, but
3472 the syntax is not clear */
3473 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3474 parse_attribute(ad);
3475 type_decl(&type1, ad, v, td);
3476 skip(')');
3477 } else {
3478 /* type identifier */
3479 if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
3480 *v = tok;
3481 next();
3482 } else {
3483 if (!(td & TYPE_ABSTRACT))
3484 expect("identifier");
3485 *v = 0;
3488 storage = type->t & VT_STORAGE;
3489 type->t &= ~VT_STORAGE;
3490 if (storage & VT_STATIC) {
3491 int saved_nocode_wanted = nocode_wanted;
3492 nocode_wanted = 1;
3493 post_type(type, ad);
3494 nocode_wanted = saved_nocode_wanted;
3495 } else
3496 post_type(type, ad);
3497 type->t |= storage;
3498 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3499 parse_attribute(ad);
3501 if (!type1.t)
3502 return;
3503 /* append type at the end of type1 */
3504 type2 = &type1;
3505 for(;;) {
3506 s = type2->ref;
3507 type2 = &s->type;
3508 if (!type2->t) {
3509 *type2 = *type;
3510 break;
3513 *type = type1;
3516 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
3517 ST_FUNC int lvalue_type(int t)
3519 int bt, r;
3520 r = VT_LVAL;
3521 bt = t & VT_BTYPE;
3522 if (bt == VT_BYTE || bt == VT_BOOL)
3523 r |= VT_LVAL_BYTE;
3524 else if (bt == VT_SHORT)
3525 r |= VT_LVAL_SHORT;
3526 else
3527 return r;
3528 if (t & VT_UNSIGNED)
3529 r |= VT_LVAL_UNSIGNED;
3530 return r;
3533 /* indirection with full error checking and bound check */
3534 ST_FUNC void indir(void)
3536 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
3537 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
3538 return;
3539 expect("pointer");
3541 if ((vtop->r & VT_LVAL) && !nocode_wanted)
3542 gv(RC_INT);
3543 vtop->type = *pointed_type(&vtop->type);
3544 /* Arrays and functions are never lvalues */
3545 if (!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_VLA)
3546 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
3547 vtop->r |= lvalue_type(vtop->type.t);
3548 /* if bound checking, the referenced pointer must be checked */
3549 #ifdef CONFIG_TCC_BCHECK
3550 if (tcc_state->do_bounds_check)
3551 vtop->r |= VT_MUSTBOUND;
3552 #endif
3556 /* pass a parameter to a function and do type checking and casting */
3557 static void gfunc_param_typed(Sym *func, Sym *arg)
3559 int func_type;
3560 CType type;
3562 func_type = func->c;
3563 if (func_type == FUNC_OLD ||
3564 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
3565 /* default casting : only need to convert float to double */
3566 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
3567 type.t = VT_DOUBLE;
3568 gen_cast(&type);
3569 } else if (vtop->type.t & VT_BITFIELD) {
3570 type.t = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
3571 gen_cast(&type);
3573 } else if (arg == NULL) {
3574 tcc_error("too many arguments to function");
3575 } else {
3576 type = arg->type;
3577 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
3578 gen_assign_cast(&type);
3582 /* parse an expression of the form '(type)' or '(expr)' and return its
3583 type */
3584 static void parse_expr_type(CType *type)
3586 int n;
3587 AttributeDef ad;
3589 skip('(');
3590 if (parse_btype(type, &ad)) {
3591 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3592 } else {
3593 expr_type(type);
3595 skip(')');
3598 static void parse_type(CType *type)
3600 AttributeDef ad;
3601 int n;
3603 if (!parse_btype(type, &ad)) {
3604 expect("type");
3606 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3609 static void vpush_tokc(int t)
3611 CType type;
3612 type.t = t;
3613 type.ref = 0;
3614 vsetc(&type, VT_CONST, &tokc);
3617 ST_FUNC void unary(void)
3619 int n, t, align, size, r, sizeof_caller;
3620 CType type;
3621 Sym *s;
3622 AttributeDef ad;
3623 static int in_sizeof = 0;
3625 sizeof_caller = in_sizeof;
3626 in_sizeof = 0;
3627 /* XXX: GCC 2.95.3 does not generate a table although it should be
3628 better here */
3629 tok_next:
3630 switch(tok) {
3631 case TOK_EXTENSION:
3632 next();
3633 goto tok_next;
3634 case TOK_CINT:
3635 case TOK_CCHAR:
3636 case TOK_LCHAR:
3637 vpushi(tokc.i);
3638 next();
3639 break;
3640 case TOK_CUINT:
3641 vpush_tokc(VT_INT | VT_UNSIGNED);
3642 next();
3643 break;
3644 case TOK_CLLONG:
3645 vpush_tokc(VT_LLONG);
3646 next();
3647 break;
3648 case TOK_CULLONG:
3649 vpush_tokc(VT_LLONG | VT_UNSIGNED);
3650 next();
3651 break;
3652 case TOK_CFLOAT:
3653 vpush_tokc(VT_FLOAT);
3654 next();
3655 break;
3656 case TOK_CDOUBLE:
3657 vpush_tokc(VT_DOUBLE);
3658 next();
3659 break;
3660 case TOK_CLDOUBLE:
3661 vpush_tokc(VT_LDOUBLE);
3662 next();
3663 break;
3664 case TOK___FUNCTION__:
3665 if (!gnu_ext)
3666 goto tok_identifier;
3667 /* fall thru */
3668 case TOK___FUNC__:
3670 void *ptr;
3671 int len;
3672 /* special function name identifier */
3673 len = strlen(funcname) + 1;
3674 /* generate char[len] type */
3675 type.t = VT_BYTE;
3676 mk_pointer(&type);
3677 type.t |= VT_ARRAY;
3678 type.ref->c = len;
3679 vpush_ref(&type, data_section, data_section->data_offset, len);
3680 ptr = section_ptr_add(data_section, len);
3681 memcpy(ptr, funcname, len);
3682 next();
3684 break;
3685 case TOK_LSTR:
3686 #ifdef TCC_TARGET_PE
3687 t = VT_SHORT | VT_UNSIGNED;
3688 #else
3689 t = VT_INT;
3690 #endif
3691 goto str_init;
3692 case TOK_STR:
3693 /* string parsing */
3694 t = VT_BYTE;
3695 str_init:
3696 if (tcc_state->warn_write_strings)
3697 t |= VT_CONSTANT;
3698 type.t = t;
3699 mk_pointer(&type);
3700 type.t |= VT_ARRAY;
3701 memset(&ad, 0, sizeof(AttributeDef));
3702 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, NULL, 0);
3703 break;
3704 case '(':
3705 next();
3706 /* cast ? */
3707 if (parse_btype(&type, &ad)) {
3708 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
3709 skip(')');
3710 /* check ISOC99 compound literal */
3711 if (tok == '{') {
3712 /* data is allocated locally by default */
3713 if (global_expr)
3714 r = VT_CONST;
3715 else
3716 r = VT_LOCAL;
3717 /* all except arrays are lvalues */
3718 if (!(type.t & VT_ARRAY))
3719 r |= lvalue_type(type.t);
3720 memset(&ad, 0, sizeof(AttributeDef));
3721 decl_initializer_alloc(&type, &ad, r, 1, 0, NULL, 0);
3722 } else {
3723 if (sizeof_caller) {
3724 vpush(&type);
3725 return;
3727 unary();
3728 gen_cast(&type);
3730 } else if (tok == '{') {
3731 /* save all registers */
3732 save_regs(0);
3733 /* statement expression : we do not accept break/continue
3734 inside as GCC does */
3735 block(NULL, NULL, NULL, NULL, 0, 1);
3736 skip(')');
3737 } else {
3738 gexpr();
3739 skip(')');
3741 break;
3742 case '*':
3743 next();
3744 unary();
3745 indir();
3746 break;
3747 case '&':
3748 next();
3749 unary();
3750 /* functions names must be treated as function pointers,
3751 except for unary '&' and sizeof. Since we consider that
3752 functions are not lvalues, we only have to handle it
3753 there and in function calls. */
3754 /* arrays can also be used although they are not lvalues */
3755 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
3756 !(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
3757 test_lvalue();
3758 mk_pointer(&vtop->type);
3759 gaddrof();
3760 break;
3761 case '!':
3762 next();
3763 unary();
3764 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3765 CType boolean;
3766 boolean.t = VT_BOOL;
3767 gen_cast(&boolean);
3768 vtop->c.i = !vtop->c.i;
3769 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
3770 vtop->c.i = vtop->c.i ^ 1;
3771 else {
3772 save_regs(1);
3773 vseti(VT_JMP, gtst(1, 0));
3775 break;
3776 case '~':
3777 next();
3778 unary();
3779 vpushi(-1);
3780 gen_op('^');
3781 break;
3782 case '+':
3783 next();
3784 unary();
3785 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
3786 tcc_error("pointer not accepted for unary plus");
3787 /* In order to force cast, we add zero, except for floating point
3788 where we really need an noop (otherwise -0.0 will be transformed
3789 into +0.0). */
3790 if (!is_float(vtop->type.t)) {
3791 vpushi(0);
3792 gen_op('+');
3794 break;
3795 case TOK_SIZEOF:
3796 case TOK_ALIGNOF1:
3797 case TOK_ALIGNOF2:
3798 t = tok;
3799 next();
3800 in_sizeof++;
3801 unary_type(&type); // Perform a in_sizeof = 0;
3802 size = type_size(&type, &align);
3803 if (t == TOK_SIZEOF) {
3804 if (!(type.t & VT_VLA)) {
3805 if (size < 0)
3806 tcc_error("sizeof applied to an incomplete type");
3807 vpushs(size);
3808 } else {
3809 vla_runtime_type_size(&type, &align);
3811 } else {
3812 vpushs(align);
3814 vtop->type.t |= VT_UNSIGNED;
3815 break;
3817 case TOK_builtin_types_compatible_p:
3819 CType type1, type2;
3820 next();
3821 skip('(');
3822 parse_type(&type1);
3823 skip(',');
3824 parse_type(&type2);
3825 skip(')');
3826 type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
3827 type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
3828 vpushi(is_compatible_types(&type1, &type2));
3830 break;
3831 case TOK_builtin_constant_p:
3833 int saved_nocode_wanted, res;
3834 next();
3835 skip('(');
3836 saved_nocode_wanted = nocode_wanted;
3837 nocode_wanted = 1;
3838 gexpr();
3839 res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
3840 vpop();
3841 nocode_wanted = saved_nocode_wanted;
3842 skip(')');
3843 vpushi(res);
3845 break;
3846 case TOK_builtin_frame_address:
3848 int level;
3849 CType type;
3850 next();
3851 skip('(');
3852 if (tok != TOK_CINT || tokc.i < 0) {
3853 tcc_error("__builtin_frame_address only takes positive integers");
3855 level = tokc.i;
3856 next();
3857 skip(')');
3858 type.t = VT_VOID;
3859 mk_pointer(&type);
3860 vset(&type, VT_LOCAL, 0); /* local frame */
3861 while (level--) {
3862 mk_pointer(&vtop->type);
3863 indir(); /* -> parent frame */
3866 break;
3867 #ifdef TCC_TARGET_X86_64
3868 #ifdef TCC_TARGET_PE
3869 case TOK_builtin_va_start:
3871 next();
3872 skip('(');
3873 expr_eq();
3874 skip(',');
3875 expr_eq();
3876 skip(')');
3877 if ((vtop->r & VT_VALMASK) != VT_LOCAL)
3878 tcc_error("__builtin_va_start expects a local variable");
3879 vtop->r &= ~(VT_LVAL | VT_REF);
3880 vtop->type = char_pointer_type;
3881 vstore();
3883 break;
3884 #else
3885 case TOK_builtin_va_arg_types:
3887 CType type;
3888 next();
3889 skip('(');
3890 parse_type(&type);
3891 skip(')');
3892 vpushi(classify_x86_64_va_arg(&type));
3894 break;
3895 #endif
3896 #endif
3897 case TOK_INC:
3898 case TOK_DEC:
3899 t = tok;
3900 next();
3901 unary();
3902 inc(0, t);
3903 break;
3904 case '-':
3905 next();
3906 unary();
3907 t = vtop->type.t & VT_BTYPE;
3908 if (is_float(t)) {
3909 /* In IEEE negate(x) isn't subtract(0,x), but rather
3910 subtract(-0, x). */
3911 vpush(&vtop->type);
3912 if (t == VT_FLOAT)
3913 vtop->c.f = -0.0f;
3914 else if (t == VT_DOUBLE)
3915 vtop->c.d = -0.0;
3916 else
3917 vtop->c.ld = -0.0;
3918 } else
3919 vpushi(0);
3920 vswap();
3921 gen_op('-');
3922 break;
3923 case TOK_LAND:
3924 if (!gnu_ext)
3925 goto tok_identifier;
3926 next();
3927 /* allow to take the address of a label */
3928 if (tok < TOK_UIDENT)
3929 expect("label identifier");
3930 s = label_find(tok);
3931 if (!s) {
3932 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
3933 } else {
3934 if (s->r == LABEL_DECLARED)
3935 s->r = LABEL_FORWARD;
3937 if (!s->type.t) {
3938 s->type.t = VT_VOID;
3939 mk_pointer(&s->type);
3940 s->type.t |= VT_STATIC;
3942 vpushsym(&s->type, s);
3943 next();
3944 break;
3946 // special qnan , snan and infinity values
3947 case TOK___NAN__:
3948 vpush64(VT_DOUBLE, 0x7ff8000000000000ULL);
3949 next();
3950 break;
3951 case TOK___SNAN__:
3952 vpush64(VT_DOUBLE, 0x7ff0000000000001ULL);
3953 next();
3954 break;
3955 case TOK___INF__:
3956 vpush64(VT_DOUBLE, 0x7ff0000000000000ULL);
3957 next();
3958 break;
3960 default:
3961 tok_identifier:
3962 t = tok;
3963 next();
3964 if (t < TOK_UIDENT)
3965 expect("identifier");
3966 s = sym_find(t);
3967 if (!s) {
3968 const char *name = get_tok_str(t, NULL);
3969 if (tok != '(')
3970 tcc_error("'%s' undeclared", name);
3971 /* for simple function calls, we tolerate undeclared
3972 external reference to int() function */
3973 if (tcc_state->warn_implicit_function_declaration
3974 #ifdef TCC_TARGET_PE
3975 /* people must be warned about using undeclared WINAPI functions
3976 (which usually start with uppercase letter) */
3977 || (name[0] >= 'A' && name[0] <= 'Z')
3978 #endif
3980 tcc_warning("implicit declaration of function '%s'", name);
3981 s = external_global_sym(t, &func_old_type, 0);
3983 if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
3984 (VT_STATIC | VT_INLINE | VT_FUNC)) {
3985 /* if referencing an inline function, then we generate a
3986 symbol to it if not already done. It will have the
3987 effect to generate code for it at the end of the
3988 compilation unit. Inline function as always
3989 generated in the text section. */
3990 if (!s->c)
3991 put_extern_sym(s, text_section, 0, 0);
3992 r = VT_SYM | VT_CONST;
3993 } else {
3994 r = s->r;
3996 vset(&s->type, r, s->c);
3997 /* if forward reference, we must point to s */
3998 if (vtop->r & VT_SYM) {
3999 vtop->sym = s;
4000 vtop->c.ptr_offset = 0;
4002 break;
4005 /* post operations */
4006 while (1) {
4007 if (tok == TOK_INC || tok == TOK_DEC) {
4008 inc(1, tok);
4009 next();
4010 } else if (tok == '.' || tok == TOK_ARROW) {
4011 int qualifiers;
4012 /* field */
4013 if (tok == TOK_ARROW)
4014 indir();
4015 qualifiers = vtop->type.t & (VT_CONSTANT | VT_VOLATILE);
4016 test_lvalue();
4017 gaddrof();
4018 next();
4019 /* expect pointer on structure */
4020 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
4021 expect("struct or union");
4022 s = vtop->type.ref;
4023 /* find field */
4024 tok |= SYM_FIELD;
4025 while ((s = s->next) != NULL) {
4026 if (s->v == tok)
4027 break;
4029 if (!s)
4030 tcc_error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, NULL));
4031 /* add field offset to pointer */
4032 vtop->type = char_pointer_type; /* change type to 'char *' */
4033 vpushi(s->c);
4034 gen_op('+');
4035 /* change type to field type, and set to lvalue */
4036 vtop->type = s->type;
4037 vtop->type.t |= qualifiers;
4038 /* an array is never an lvalue */
4039 if (!(vtop->type.t & VT_ARRAY)) {
4040 vtop->r |= lvalue_type(vtop->type.t);
4041 #ifdef CONFIG_TCC_BCHECK
4042 /* if bound checking, the referenced pointer must be checked */
4043 if (tcc_state->do_bounds_check)
4044 vtop->r |= VT_MUSTBOUND;
4045 #endif
4047 next();
4048 } else if (tok == '[') {
4049 next();
4050 gexpr();
4051 gen_op('+');
4052 indir();
4053 skip(']');
4054 } else if (tok == '(') {
4055 SValue ret;
4056 Sym *sa;
4057 int nb_args, ret_nregs, ret_align, variadic;
4059 /* function call */
4060 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
4061 /* pointer test (no array accepted) */
4062 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
4063 vtop->type = *pointed_type(&vtop->type);
4064 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
4065 goto error_func;
4066 } else {
4067 error_func:
4068 expect("function pointer");
4070 } else {
4071 vtop->r &= ~VT_LVAL; /* no lvalue */
4073 /* get return type */
4074 s = vtop->type.ref;
4075 next();
4076 sa = s->next; /* first parameter */
4077 nb_args = 0;
4078 ret.r2 = VT_CONST;
4079 /* compute first implicit argument if a structure is returned */
4080 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
4081 variadic = (s->c == FUNC_ELLIPSIS);
4082 ret_nregs = gfunc_sret(&s->type, variadic, &ret.type,
4083 &ret_align);
4084 if (!ret_nregs) {
4085 /* get some space for the returned structure */
4086 size = type_size(&s->type, &align);
4087 loc = (loc - size) & -align;
4088 ret.type = s->type;
4089 ret.r = VT_LOCAL | VT_LVAL;
4090 /* pass it as 'int' to avoid structure arg passing
4091 problems */
4092 vseti(VT_LOCAL, loc);
4093 ret.c = vtop->c;
4094 nb_args++;
4096 } else {
4097 ret_nregs = 1;
4098 ret.type = s->type;
4101 if (ret_nregs) {
4102 /* return in register */
4103 if (is_float(ret.type.t)) {
4104 ret.r = reg_fret(ret.type.t);
4105 #ifdef TCC_TARGET_X86_64
4106 if ((ret.type.t & VT_BTYPE) == VT_QFLOAT)
4107 ret.r2 = REG_QRET;
4108 #endif
4109 } else {
4110 #ifdef TCC_TARGET_X86_64
4111 if ((ret.type.t & VT_BTYPE) == VT_QLONG)
4112 #else
4113 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
4114 #endif
4115 ret.r2 = REG_LRET;
4116 ret.r = REG_IRET;
4118 ret.c.i = 0;
4120 if (tok != ')') {
4121 for(;;) {
4122 expr_eq();
4123 gfunc_param_typed(s, sa);
4124 nb_args++;
4125 if (sa)
4126 sa = sa->next;
4127 if (tok == ')')
4128 break;
4129 skip(',');
4132 if (sa)
4133 tcc_error("too few arguments to function");
4134 skip(')');
4135 if (!nocode_wanted) {
4136 gfunc_call(nb_args);
4137 } else {
4138 vtop -= (nb_args + 1);
4141 /* return value */
4142 for (r = ret.r + ret_nregs + !ret_nregs; r-- > ret.r;) {
4143 vsetc(&ret.type, r, &ret.c);
4144 vtop->r2 = ret.r2; /* Loop only happens when r2 is VT_CONST */
4147 /* handle packed struct return */
4148 if (((s->type.t & VT_BTYPE) == VT_STRUCT) && ret_nregs) {
4149 int addr, offset;
4151 size = type_size(&s->type, &align);
4152 loc = (loc - size) & -align;
4153 addr = loc;
4154 offset = 0;
4155 for (;;) {
4156 vset(&ret.type, VT_LOCAL | VT_LVAL, addr + offset);
4157 vswap();
4158 vstore();
4159 vtop--;
4160 if (--ret_nregs == 0)
4161 break;
4162 /* XXX: compatible with arm only: ret_align == register_size */
4163 offset += ret_align;
4165 vset(&s->type, VT_LOCAL | VT_LVAL, addr);
4167 } else {
4168 break;
4173 ST_FUNC void expr_prod(void)
4175 int t;
4177 unary();
4178 while (tok == '*' || tok == '/' || tok == '%') {
4179 t = tok;
4180 next();
4181 unary();
4182 gen_op(t);
4186 ST_FUNC void expr_sum(void)
4188 int t;
4190 expr_prod();
4191 while (tok == '+' || tok == '-') {
4192 t = tok;
4193 next();
4194 expr_prod();
4195 gen_op(t);
4199 static void expr_shift(void)
4201 int t;
4203 expr_sum();
4204 while (tok == TOK_SHL || tok == TOK_SAR) {
4205 t = tok;
4206 next();
4207 expr_sum();
4208 gen_op(t);
4212 static void expr_cmp(void)
4214 int t;
4216 expr_shift();
4217 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
4218 tok == TOK_ULT || tok == TOK_UGE) {
4219 t = tok;
4220 next();
4221 expr_shift();
4222 gen_op(t);
4226 static void expr_cmpeq(void)
4228 int t;
4230 expr_cmp();
4231 while (tok == TOK_EQ || tok == TOK_NE) {
4232 t = tok;
4233 next();
4234 expr_cmp();
4235 gen_op(t);
4239 static void expr_and(void)
4241 expr_cmpeq();
4242 while (tok == '&') {
4243 next();
4244 expr_cmpeq();
4245 gen_op('&');
4249 static void expr_xor(void)
4251 expr_and();
4252 while (tok == '^') {
4253 next();
4254 expr_and();
4255 gen_op('^');
4259 static void expr_or(void)
4261 expr_xor();
4262 while (tok == '|') {
4263 next();
4264 expr_xor();
4265 gen_op('|');
4269 /* XXX: fix this mess */
4270 static void expr_land_const(void)
4272 expr_or();
4273 while (tok == TOK_LAND) {
4274 next();
4275 expr_or();
4276 gen_op(TOK_LAND);
4280 /* XXX: fix this mess */
4281 static void expr_lor_const(void)
4283 expr_land_const();
4284 while (tok == TOK_LOR) {
4285 next();
4286 expr_land_const();
4287 gen_op(TOK_LOR);
4291 /* only used if non constant */
4292 static void expr_land(void)
4294 int t;
4296 expr_or();
4297 if (tok == TOK_LAND) {
4298 t = 0;
4299 save_regs(1);
4300 for(;;) {
4301 t = gtst(1, t);
4302 if (tok != TOK_LAND) {
4303 vseti(VT_JMPI, t);
4304 break;
4306 next();
4307 expr_or();
4312 static void expr_lor(void)
4314 int t;
4316 expr_land();
4317 if (tok == TOK_LOR) {
4318 t = 0;
4319 save_regs(1);
4320 for(;;) {
4321 t = gtst(0, t);
4322 if (tok != TOK_LOR) {
4323 vseti(VT_JMP, t);
4324 break;
4326 next();
4327 expr_land();
4332 /* XXX: better constant handling */
4333 static void expr_cond(void)
4335 int tt, u, r1, r2, rc, t1, t2, bt1, bt2;
4336 SValue sv;
4337 CType type, type1, type2;
4339 if (const_wanted) {
4340 expr_lor_const();
4341 if (tok == '?') {
4342 CType boolean;
4343 int c;
4344 boolean.t = VT_BOOL;
4345 vdup();
4346 gen_cast(&boolean);
4347 c = vtop->c.i;
4348 vpop();
4349 next();
4350 if (tok != ':' || !gnu_ext) {
4351 vpop();
4352 gexpr();
4354 if (!c)
4355 vpop();
4356 skip(':');
4357 expr_cond();
4358 if (c)
4359 vpop();
4361 } else {
4362 expr_lor();
4363 if (tok == '?') {
4364 next();
4365 if (vtop != vstack) {
4366 /* needed to avoid having different registers saved in
4367 each branch */
4368 if (is_float(vtop->type.t)) {
4369 rc = RC_FLOAT;
4370 #ifdef TCC_TARGET_X86_64
4371 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
4372 rc = RC_ST0;
4374 #endif
4376 else
4377 rc = RC_INT;
4378 gv(rc);
4379 save_regs(1);
4381 if (tok == ':' && gnu_ext) {
4382 gv_dup();
4383 tt = gtst(1, 0);
4384 } else {
4385 tt = gtst(1, 0);
4386 gexpr();
4388 type1 = vtop->type;
4389 sv = *vtop; /* save value to handle it later */
4390 vtop--; /* no vpop so that FP stack is not flushed */
4391 skip(':');
4392 u = gjmp(0);
4393 gsym(tt);
4394 expr_cond();
4395 type2 = vtop->type;
4397 t1 = type1.t;
4398 bt1 = t1 & VT_BTYPE;
4399 t2 = type2.t;
4400 bt2 = t2 & VT_BTYPE;
4401 /* cast operands to correct type according to ISOC rules */
4402 if (is_float(bt1) || is_float(bt2)) {
4403 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
4404 type.t = VT_LDOUBLE;
4405 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
4406 type.t = VT_DOUBLE;
4407 } else {
4408 type.t = VT_FLOAT;
4410 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
4411 /* cast to biggest op */
4412 type.t = VT_LLONG;
4413 /* convert to unsigned if it does not fit in a long long */
4414 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
4415 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
4416 type.t |= VT_UNSIGNED;
4417 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
4418 /* If one is a null ptr constant the result type
4419 is the other. */
4420 if (is_null_pointer (vtop))
4421 type = type1;
4422 else if (is_null_pointer (&sv))
4423 type = type2;
4424 /* XXX: test pointer compatibility, C99 has more elaborate
4425 rules here. */
4426 else
4427 type = type1;
4428 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
4429 /* XXX: test function pointer compatibility */
4430 type = bt1 == VT_FUNC ? type1 : type2;
4431 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
4432 /* XXX: test structure compatibility */
4433 type = bt1 == VT_STRUCT ? type1 : type2;
4434 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
4435 /* NOTE: as an extension, we accept void on only one side */
4436 type.t = VT_VOID;
4437 } else {
4438 /* integer operations */
4439 type.t = VT_INT;
4440 /* convert to unsigned if it does not fit in an integer */
4441 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
4442 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
4443 type.t |= VT_UNSIGNED;
4446 /* now we convert second operand */
4447 gen_cast(&type);
4448 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4449 gaddrof();
4450 rc = RC_INT;
4451 if (is_float(type.t)) {
4452 rc = RC_FLOAT;
4453 #ifdef TCC_TARGET_X86_64
4454 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
4455 rc = RC_ST0;
4457 #endif
4458 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
4459 /* for long longs, we use fixed registers to avoid having
4460 to handle a complicated move */
4461 rc = RC_IRET;
4464 r2 = gv(rc);
4465 /* this is horrible, but we must also convert first
4466 operand */
4467 tt = gjmp(0);
4468 gsym(u);
4469 /* put again first value and cast it */
4470 *vtop = sv;
4471 gen_cast(&type);
4472 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4473 gaddrof();
4474 r1 = gv(rc);
4475 move_reg(r2, r1, type.t);
4476 vtop->r = r2;
4477 gsym(tt);
4482 static void expr_eq(void)
4484 int t;
4486 expr_cond();
4487 if (tok == '=' ||
4488 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
4489 tok == TOK_A_XOR || tok == TOK_A_OR ||
4490 tok == TOK_A_SHL || tok == TOK_A_SAR) {
4491 test_lvalue();
4492 t = tok;
4493 next();
4494 if (t == '=') {
4495 expr_eq();
4496 } else {
4497 vdup();
4498 expr_eq();
4499 gen_op(t & 0x7f);
4501 vstore();
4505 ST_FUNC void gexpr(void)
4507 while (1) {
4508 expr_eq();
4509 if (tok != ',')
4510 break;
4511 vpop();
4512 next();
4516 /* parse an expression and return its type without any side effect. */
4517 static void expr_type(CType *type)
4519 int saved_nocode_wanted;
4521 saved_nocode_wanted = nocode_wanted;
4522 nocode_wanted = 1;
4523 gexpr();
4524 *type = vtop->type;
4525 vpop();
4526 nocode_wanted = saved_nocode_wanted;
4529 /* parse a unary expression and return its type without any side
4530 effect. */
4531 static void unary_type(CType *type)
4533 int a;
4535 a = nocode_wanted;
4536 nocode_wanted = 1;
4537 unary();
4538 *type = vtop->type;
4539 vpop();
4540 nocode_wanted = a;
4543 /* parse a constant expression and return value in vtop. */
4544 static void expr_const1(void)
4546 int a;
4547 a = const_wanted;
4548 const_wanted = 1;
4549 expr_cond();
4550 const_wanted = a;
4553 /* parse an integer constant and return its value. */
4554 ST_FUNC int expr_const(void)
4556 int c;
4557 expr_const1();
4558 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
4559 expect("constant expression");
4560 c = vtop->c.i;
4561 vpop();
4562 return c;
4565 /* return the label token if current token is a label, otherwise
4566 return zero */
4567 static int is_label(void)
4569 int last_tok;
4571 /* fast test first */
4572 if (tok < TOK_UIDENT)
4573 return 0;
4574 /* no need to save tokc because tok is an identifier */
4575 last_tok = tok;
4576 next();
4577 if (tok == ':') {
4578 next();
4579 return last_tok;
4580 } else {
4581 unget_tok(last_tok);
4582 return 0;
4586 static void label_or_decl(int l)
4588 int last_tok;
4590 /* fast test first */
4591 if (tok >= TOK_UIDENT)
4593 /* no need to save tokc because tok is an identifier */
4594 last_tok = tok;
4595 next();
4596 if (tok == ':') {
4597 unget_tok(last_tok);
4598 return;
4600 unget_tok(last_tok);
4602 decl(l);
4605 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
4606 int case_reg, int is_expr)
4608 int a, b, c, d;
4609 Sym *s, *frame_bottom;
4611 /* generate line number info */
4612 if (tcc_state->do_debug &&
4613 (last_line_num != file->line_num || last_ind != ind)) {
4614 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
4615 last_ind = ind;
4616 last_line_num = file->line_num;
4619 if (is_expr) {
4620 /* default return value is (void) */
4621 vpushi(0);
4622 vtop->type.t = VT_VOID;
4625 if (tok == TOK_IF) {
4626 /* if test */
4627 next();
4628 skip('(');
4629 gexpr();
4630 skip(')');
4631 a = gtst(1, 0);
4632 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4633 c = tok;
4634 if (c == TOK_ELSE) {
4635 next();
4636 d = gjmp(0);
4637 gsym(a);
4638 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4639 gsym(d); /* patch else jmp */
4640 } else
4641 gsym(a);
4642 } else if (tok == TOK_WHILE) {
4643 next();
4644 d = ind;
4645 skip('(');
4646 gexpr();
4647 skip(')');
4648 a = gtst(1, 0);
4649 b = 0;
4650 block(&a, &b, case_sym, def_sym, case_reg, 0);
4651 gjmp_addr(d);
4652 gsym(a);
4653 gsym_addr(b, d);
4654 } else if (tok == '{') {
4655 Sym *llabel;
4656 int block_vla_sp_loc, *saved_vla_sp_loc, saved_vla_flags;
4658 next();
4659 /* record local declaration stack position */
4660 s = local_stack;
4661 frame_bottom = sym_push2(&local_stack, SYM_FIELD, 0, 0);
4662 frame_bottom->next = scope_stack_bottom;
4663 scope_stack_bottom = frame_bottom;
4664 llabel = local_label_stack;
4666 /* save VLA state */
4667 block_vla_sp_loc = *(saved_vla_sp_loc = vla_sp_loc);
4668 if (saved_vla_sp_loc != &vla_sp_root_loc)
4669 vla_sp_loc = &block_vla_sp_loc;
4671 saved_vla_flags = vla_flags;
4672 vla_flags |= VLA_NEED_NEW_FRAME;
4674 /* handle local labels declarations */
4675 if (tok == TOK_LABEL) {
4676 next();
4677 for(;;) {
4678 if (tok < TOK_UIDENT)
4679 expect("label identifier");
4680 label_push(&local_label_stack, tok, LABEL_DECLARED);
4681 next();
4682 if (tok == ',') {
4683 next();
4684 } else {
4685 skip(';');
4686 break;
4690 while (tok != '}') {
4691 label_or_decl(VT_LOCAL);
4692 if (tok != '}') {
4693 if (is_expr)
4694 vpop();
4695 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
4698 /* pop locally defined labels */
4699 label_pop(&local_label_stack, llabel);
4700 if(is_expr) {
4701 /* XXX: this solution makes only valgrind happy...
4702 triggered by gcc.c-torture/execute/20000917-1.c */
4703 Sym *p;
4704 switch(vtop->type.t & VT_BTYPE) {
4705 case VT_PTR:
4706 case VT_STRUCT:
4707 case VT_ENUM:
4708 case VT_FUNC:
4709 for(p=vtop->type.ref;p;p=p->prev)
4710 if(p->prev==s)
4711 tcc_error("unsupported expression type");
4714 /* pop locally defined symbols */
4715 scope_stack_bottom = scope_stack_bottom->next;
4716 sym_pop(&local_stack, s);
4718 /* Pop VLA frames and restore stack pointer if required */
4719 if (saved_vla_sp_loc != &vla_sp_root_loc)
4720 *saved_vla_sp_loc = block_vla_sp_loc;
4721 if (vla_sp_loc != (saved_vla_sp_loc == &vla_sp_root_loc ? &vla_sp_root_loc : &block_vla_sp_loc)) {
4722 vla_sp_loc = saved_vla_sp_loc;
4723 gen_vla_sp_restore(*vla_sp_loc);
4725 vla_flags = (vla_flags & ~VLA_SCOPE_FLAGS) | (saved_vla_flags & VLA_SCOPE_FLAGS);
4727 next();
4728 } else if (tok == TOK_RETURN) {
4729 next();
4730 if (tok != ';') {
4731 gexpr();
4732 gen_assign_cast(&func_vt);
4733 if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
4734 CType type, ret_type;
4735 int ret_align, ret_nregs;
4736 ret_nregs = gfunc_sret(&func_vt, func_var, &ret_type,
4737 &ret_align);
4738 if (0 == ret_nregs) {
4739 /* if returning structure, must copy it to implicit
4740 first pointer arg location */
4741 type = func_vt;
4742 mk_pointer(&type);
4743 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
4744 indir();
4745 vswap();
4746 /* copy structure value to pointer */
4747 vstore();
4748 } else {
4749 /* returning structure packed into registers */
4750 int rc, size, addr, align;
4751 size = type_size(&func_vt,&align);
4752 if ((vtop->r != (VT_LOCAL | VT_LVAL) || (vtop->c.i & (ret_align-1)))
4753 && (align & (ret_align-1))) {
4754 loc = (loc - size) & -align;
4755 addr = loc;
4756 type = func_vt;
4757 vset(&type, VT_LOCAL | VT_LVAL, addr);
4758 vswap();
4759 vstore();
4760 vset(&ret_type, VT_LOCAL | VT_LVAL, addr);
4762 vtop->type = ret_type;
4763 if (is_float(ret_type.t))
4764 rc = rc_fret(ret_type.t);
4765 else{
4766 rc = RC_IRET;
4767 ex_rc = RC_LRET;
4770 for (;;) {
4771 gv(rc);
4772 if (--ret_nregs == 0)
4773 break;
4774 /* We assume that when a structure is returned in multiple
4775 registers, their classes are consecutive values of the
4776 suite s(n) = 2^n */
4777 rc <<= 1;
4778 /* XXX: compatible with arm only: ret_align == register_size */
4779 vtop->c.i += ret_align;
4780 vtop->r = VT_LOCAL | VT_LVAL;
4783 } else if (is_float(func_vt.t)) {
4784 gv(rc_fret(func_vt.t));
4785 } else {
4786 gv(RC_IRET);
4788 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
4790 skip(';');
4791 rsym = gjmp(rsym); /* jmp */
4792 } else if (tok == TOK_BREAK) {
4793 /* compute jump */
4794 if (!bsym)
4795 tcc_error("cannot break");
4796 *bsym = gjmp(*bsym);
4797 next();
4798 skip(';');
4799 } else if (tok == TOK_CONTINUE) {
4800 /* compute jump */
4801 if (!csym)
4802 tcc_error("cannot continue");
4803 *csym = gjmp(*csym);
4804 next();
4805 skip(';');
4806 } else if (tok == TOK_FOR) {
4807 int e;
4808 next();
4809 skip('(');
4810 s = local_stack;
4811 frame_bottom = sym_push2(&local_stack, SYM_FIELD, 0, 0);
4812 frame_bottom->next = scope_stack_bottom;
4813 scope_stack_bottom = frame_bottom;
4814 if (tok != ';') {
4815 /* c99 for-loop init decl? */
4816 if (!decl0(VT_LOCAL, 1)) {
4817 /* no, regular for-loop init expr */
4818 gexpr();
4819 vpop();
4822 skip(';');
4823 d = ind;
4824 c = ind;
4825 a = 0;
4826 b = 0;
4827 if (tok != ';') {
4828 gexpr();
4829 a = gtst(1, 0);
4831 skip(';');
4832 if (tok != ')') {
4833 e = gjmp(0);
4834 c = ind;
4835 gexpr();
4836 vpop();
4837 gjmp_addr(d);
4838 gsym(e);
4840 skip(')');
4841 block(&a, &b, case_sym, def_sym, case_reg, 0);
4842 gjmp_addr(c);
4843 gsym(a);
4844 gsym_addr(b, c);
4845 scope_stack_bottom = scope_stack_bottom->next;
4846 sym_pop(&local_stack, s);
4847 } else
4848 if (tok == TOK_DO) {
4849 next();
4850 a = 0;
4851 b = 0;
4852 d = ind;
4853 block(&a, &b, case_sym, def_sym, case_reg, 0);
4854 skip(TOK_WHILE);
4855 skip('(');
4856 gsym(b);
4857 gexpr();
4858 c = gtst(0, 0);
4859 gsym_addr(c, d);
4860 skip(')');
4861 gsym(a);
4862 skip(';');
4863 } else
4864 if (tok == TOK_SWITCH) {
4865 next();
4866 skip('(');
4867 gexpr();
4868 /* XXX: other types than integer */
4869 case_reg = gv(RC_INT);
4870 vpop();
4871 skip(')');
4872 a = 0;
4873 b = gjmp(0); /* jump to first case */
4874 c = 0;
4875 block(&a, csym, &b, &c, case_reg, 0);
4876 /* if no default, jmp after switch */
4877 if (c == 0)
4878 c = ind;
4879 /* default label */
4880 gsym_addr(b, c);
4881 /* break label */
4882 gsym(a);
4883 } else
4884 if (tok == TOK_CASE) {
4885 int v1, v2;
4886 if (!case_sym)
4887 expect("switch");
4888 next();
4889 v1 = expr_const();
4890 v2 = v1;
4891 if (gnu_ext && tok == TOK_DOTS) {
4892 next();
4893 v2 = expr_const();
4894 if (v2 < v1)
4895 tcc_warning("empty case range");
4897 /* since a case is like a label, we must skip it with a jmp */
4898 b = gjmp(0);
4899 gsym(*case_sym);
4900 vseti(case_reg, 0);
4901 vpushi(v1);
4902 if (v1 == v2) {
4903 gen_op(TOK_EQ);
4904 *case_sym = gtst(1, 0);
4905 } else {
4906 gen_op(TOK_GE);
4907 *case_sym = gtst(1, 0);
4908 vseti(case_reg, 0);
4909 vpushi(v2);
4910 gen_op(TOK_LE);
4911 *case_sym = gtst(1, *case_sym);
4913 gsym(b);
4914 skip(':');
4915 is_expr = 0;
4916 goto block_after_label;
4917 } else
4918 if (tok == TOK_DEFAULT) {
4919 next();
4920 skip(':');
4921 if (!def_sym)
4922 expect("switch");
4923 if (*def_sym)
4924 tcc_error("too many 'default'");
4925 *def_sym = ind;
4926 is_expr = 0;
4927 goto block_after_label;
4928 } else
4929 if (tok == TOK_GOTO) {
4930 next();
4931 if (tok == '*' && gnu_ext) {
4932 /* computed goto */
4933 next();
4934 gexpr();
4935 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
4936 expect("pointer");
4937 ggoto();
4938 } else if (tok >= TOK_UIDENT) {
4939 s = label_find(tok);
4940 /* put forward definition if needed */
4941 if (!s) {
4942 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
4943 } else {
4944 if (s->r == LABEL_DECLARED)
4945 s->r = LABEL_FORWARD;
4947 /* label already defined */
4948 if (vla_flags & VLA_IN_SCOPE) {
4949 /* If VLAs are in use, save the current stack pointer and
4950 reset the stack pointer to what it was at function entry
4951 (label will restore stack pointer in inner scopes) */
4952 vla_sp_save();
4953 gen_vla_sp_restore(vla_sp_root_loc);
4955 if (s->r & LABEL_FORWARD)
4956 s->jnext = gjmp(s->jnext);
4957 else
4958 gjmp_addr(s->jnext);
4959 next();
4960 } else {
4961 expect("label identifier");
4963 skip(';');
4964 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
4965 asm_instr();
4966 } else {
4967 b = is_label();
4968 if (b) {
4969 /* label case */
4970 if (vla_flags & VLA_IN_SCOPE) {
4971 /* save/restore stack pointer across label
4972 this is a no-op when combined with the load immediately
4973 after the label unless we arrive via goto */
4974 vla_sp_save();
4976 s = label_find(b);
4977 if (s) {
4978 if (s->r == LABEL_DEFINED)
4979 tcc_error("duplicate label '%s'", get_tok_str(s->v, NULL));
4980 gsym(s->jnext);
4981 s->r = LABEL_DEFINED;
4982 } else {
4983 s = label_push(&global_label_stack, b, LABEL_DEFINED);
4985 s->jnext = ind;
4986 if (vla_flags & VLA_IN_SCOPE) {
4987 gen_vla_sp_restore(*vla_sp_loc);
4988 vla_flags |= VLA_NEED_NEW_FRAME;
4990 /* we accept this, but it is a mistake */
4991 block_after_label:
4992 if (tok == '}') {
4993 tcc_warning("deprecated use of label at end of compound statement");
4994 } else {
4995 if (is_expr)
4996 vpop();
4997 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
4999 } else {
5000 /* expression case */
5001 if (tok != ';') {
5002 if (is_expr) {
5003 vpop();
5004 gexpr();
5005 } else {
5006 gexpr();
5007 vpop();
5010 skip(';');
5015 /* t is the array or struct type. c is the array or struct
5016 address. cur_index/cur_field is the pointer to the current
5017 value. 'size_only' is true if only size info is needed (only used
5018 in arrays) */
5019 static void decl_designator(CType *type, Section *sec, unsigned long c,
5020 int *cur_index, Sym **cur_field,
5021 int size_only)
5023 Sym *s, *f;
5024 int notfirst, index, index_last, align, l, nb_elems, elem_size;
5025 CType type1;
5027 notfirst = 0;
5028 elem_size = 0;
5029 nb_elems = 1;
5030 if (gnu_ext && (l = is_label()) != 0)
5031 goto struct_field;
5032 while (tok == '[' || tok == '.') {
5033 if (tok == '[') {
5034 if (!(type->t & VT_ARRAY))
5035 expect("array type");
5036 s = type->ref;
5037 next();
5038 index = expr_const();
5039 if (index < 0 || (s->c >= 0 && index >= s->c))
5040 expect("invalid index");
5041 if (tok == TOK_DOTS && gnu_ext) {
5042 next();
5043 index_last = expr_const();
5044 if (index_last < 0 ||
5045 (s->c >= 0 && index_last >= s->c) ||
5046 index_last < index)
5047 expect("invalid index");
5048 } else {
5049 index_last = index;
5051 skip(']');
5052 if (!notfirst)
5053 *cur_index = index_last;
5054 type = pointed_type(type);
5055 elem_size = type_size(type, &align);
5056 c += index * elem_size;
5057 /* NOTE: we only support ranges for last designator */
5058 nb_elems = index_last - index + 1;
5059 if (nb_elems != 1) {
5060 notfirst = 1;
5061 break;
5063 } else {
5064 next();
5065 l = tok;
5066 next();
5067 struct_field:
5068 if ((type->t & VT_BTYPE) != VT_STRUCT)
5069 expect("struct/union type");
5070 s = type->ref;
5071 l |= SYM_FIELD;
5072 f = s->next;
5073 while (f) {
5074 if (f->v == l)
5075 break;
5076 f = f->next;
5078 if (!f)
5079 expect("field");
5080 if (!notfirst)
5081 *cur_field = f;
5082 /* XXX: fix this mess by using explicit storage field */
5083 type1 = f->type;
5084 type1.t |= (type->t & ~VT_TYPE);
5085 type = &type1;
5086 c += f->c;
5088 notfirst = 1;
5090 if (notfirst) {
5091 if (tok == '=') {
5092 next();
5093 } else {
5094 if (!gnu_ext)
5095 expect("=");
5097 } else {
5098 if (type->t & VT_ARRAY) {
5099 index = *cur_index;
5100 type = pointed_type(type);
5101 c += index * type_size(type, &align);
5102 } else {
5103 f = *cur_field;
5104 if (!f)
5105 tcc_error("too many field init");
5106 /* XXX: fix this mess by using explicit storage field */
5107 type1 = f->type;
5108 type1.t |= (type->t & ~VT_TYPE);
5109 type = &type1;
5110 c += f->c;
5113 decl_initializer(type, sec, c, 0, size_only);
5115 /* XXX: make it more general */
5116 if (!size_only && nb_elems > 1) {
5117 unsigned long c_end;
5118 uint8_t *src, *dst;
5119 int i;
5121 if (!sec)
5122 tcc_error("range init not supported yet for dynamic storage");
5123 c_end = c + nb_elems * elem_size;
5124 if (c_end > sec->data_allocated)
5125 section_realloc(sec, c_end);
5126 src = sec->data + c;
5127 dst = src;
5128 for(i = 1; i < nb_elems; i++) {
5129 dst += elem_size;
5130 memcpy(dst, src, elem_size);
5135 #define EXPR_VAL 0
5136 #define EXPR_CONST 1
5137 #define EXPR_ANY 2
5139 /* store a value or an expression directly in global data or in local array */
5140 static void init_putv(CType *type, Section *sec, unsigned long c,
5141 int v, int expr_type)
5143 int saved_global_expr, bt, bit_pos, bit_size;
5144 void *ptr;
5145 unsigned long long bit_mask;
5146 CType dtype;
5148 switch(expr_type) {
5149 case EXPR_VAL:
5150 vpushi(v);
5151 break;
5152 case EXPR_CONST:
5153 /* compound literals must be allocated globally in this case */
5154 saved_global_expr = global_expr;
5155 global_expr = 1;
5156 expr_const1();
5157 global_expr = saved_global_expr;
5158 /* NOTE: symbols are accepted */
5159 if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
5160 tcc_error("initializer element is not constant");
5161 break;
5162 case EXPR_ANY:
5163 expr_eq();
5164 break;
5167 dtype = *type;
5168 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
5170 if (sec) {
5171 /* XXX: not portable */
5172 /* XXX: generate error if incorrect relocation */
5173 gen_assign_cast(&dtype);
5174 bt = type->t & VT_BTYPE;
5175 /* we'll write at most 12 bytes */
5176 if (c + 12 > sec->data_allocated) {
5177 section_realloc(sec, c + 12);
5179 ptr = sec->data + c;
5180 /* XXX: make code faster ? */
5181 if (!(type->t & VT_BITFIELD)) {
5182 bit_pos = 0;
5183 bit_size = 32;
5184 bit_mask = -1LL;
5185 } else {
5186 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5187 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
5188 bit_mask = (1LL << bit_size) - 1;
5190 if ((vtop->r & VT_SYM) &&
5191 (bt == VT_BYTE ||
5192 bt == VT_SHORT ||
5193 bt == VT_DOUBLE ||
5194 bt == VT_LDOUBLE ||
5195 bt == VT_LLONG ||
5196 (bt == VT_INT && bit_size != 32)))
5197 tcc_error("initializer element is not computable at load time");
5198 switch(bt) {
5199 case VT_BOOL:
5200 vtop->c.i = (vtop->c.i != 0);
5201 case VT_BYTE:
5202 *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5203 break;
5204 case VT_SHORT:
5205 *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5206 break;
5207 case VT_DOUBLE:
5208 *(double *)ptr = vtop->c.d;
5209 break;
5210 case VT_LDOUBLE:
5211 *(long double *)ptr = vtop->c.ld;
5212 break;
5213 case VT_LLONG:
5214 *(long long *)ptr |= (vtop->c.ll & bit_mask) << bit_pos;
5215 break;
5216 case VT_PTR:
5217 if (vtop->r & VT_SYM) {
5218 greloc(sec, vtop->sym, c, R_DATA_PTR);
5220 *(addr_t *)ptr |= (vtop->c.ptr_offset & bit_mask) << bit_pos;
5221 break;
5222 default:
5223 if (vtop->r & VT_SYM) {
5224 greloc(sec, vtop->sym, c, R_DATA_PTR);
5226 *(int *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5227 break;
5229 vtop--;
5230 } else {
5231 vset(&dtype, VT_LOCAL|VT_LVAL, c);
5232 vswap();
5233 vstore();
5234 vpop();
5238 /* put zeros for variable based init */
5239 static void init_putz(CType *t, Section *sec, unsigned long c, int size)
5241 if (sec) {
5242 /* nothing to do because globals are already set to zero */
5243 } else {
5244 #ifndef TCC_TARGET_X86_64
5245 vpush_global_sym(&func_old_type, TOK_memset);
5246 vseti(VT_LOCAL, c);
5247 #ifdef TCC_TARGET_ARM
5248 vpushs(size);
5249 vpushi(0);
5250 #else
5251 vpushi(0);
5252 vpushs(size);
5253 #endif
5254 gfunc_call(3);
5255 #else
5256 vseti(VT_LOCAL, c);
5257 gen_putz(vtop, size);
5258 vtop--;
5259 #endif
5263 /* 't' contains the type and storage info. 'c' is the offset of the
5264 object in section 'sec'. If 'sec' is NULL, it means stack based
5265 allocation. 'first' is true if array '{' must be read (multi
5266 dimension implicit array init handling). 'size_only' is true if
5267 size only evaluation is wanted (only for arrays). */
5268 static void decl_initializer(CType *type, Section *sec, unsigned long c,
5269 int first, int size_only)
5271 int index, array_length, n, no_oblock, nb, parlevel, parlevel1, i;
5272 int size1, align1, expr_type;
5273 Sym *s, *f;
5274 CType *t1;
5276 if (type->t & VT_VLA) {
5277 int a;
5279 /* save current stack pointer */
5280 if (vla_flags & VLA_NEED_NEW_FRAME) {
5281 vla_sp_save();
5282 vla_flags = VLA_IN_SCOPE;
5283 vla_sp_loc = &vla_sp_loc_tmp;
5286 vla_runtime_type_size(type, &a);
5287 gen_vla_alloc(type, a);
5288 vset(type, VT_LOCAL|VT_LVAL, c);
5289 vswap();
5290 vstore();
5291 vpop();
5292 } else if (type->t & VT_ARRAY) {
5293 s = type->ref;
5294 n = s->c;
5295 array_length = 0;
5296 t1 = pointed_type(type);
5297 size1 = type_size(t1, &align1);
5299 no_oblock = 1;
5300 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
5301 tok == '{') {
5302 if (tok != '{')
5303 tcc_error("character array initializer must be a literal,"
5304 " optionally enclosed in braces");
5305 skip('{');
5306 no_oblock = 0;
5309 /* only parse strings here if correct type (otherwise: handle
5310 them as ((w)char *) expressions */
5311 if ((tok == TOK_LSTR &&
5312 #ifdef TCC_TARGET_PE
5313 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
5314 #else
5315 (t1->t & VT_BTYPE) == VT_INT
5316 #endif
5317 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
5318 while (tok == TOK_STR || tok == TOK_LSTR) {
5319 int cstr_len, ch;
5320 CString *cstr;
5322 cstr = tokc.cstr;
5323 /* compute maximum number of chars wanted */
5324 if (tok == TOK_STR)
5325 cstr_len = cstr->size;
5326 else
5327 cstr_len = cstr->size / sizeof(nwchar_t);
5328 cstr_len--;
5329 nb = cstr_len;
5330 if (n >= 0 && nb > (n - array_length))
5331 nb = n - array_length;
5332 if (!size_only) {
5333 if (cstr_len > nb)
5334 tcc_warning("initializer-string for array is too long");
5335 /* in order to go faster for common case (char
5336 string in global variable, we handle it
5337 specifically */
5338 if (sec && tok == TOK_STR && size1 == 1) {
5339 memcpy(sec->data + c + array_length, cstr->data, nb);
5340 } else {
5341 for(i=0;i<nb;i++) {
5342 if (tok == TOK_STR)
5343 ch = ((unsigned char *)cstr->data)[i];
5344 else
5345 ch = ((nwchar_t *)cstr->data)[i];
5346 init_putv(t1, sec, c + (array_length + i) * size1,
5347 ch, EXPR_VAL);
5351 array_length += nb;
5352 next();
5354 /* only add trailing zero if enough storage (no
5355 warning in this case since it is standard) */
5356 if (n < 0 || array_length < n) {
5357 if (!size_only) {
5358 init_putv(t1, sec, c + (array_length * size1), 0, EXPR_VAL);
5360 array_length++;
5362 } else {
5363 index = 0;
5364 while (tok != '}') {
5365 decl_designator(type, sec, c, &index, NULL, size_only);
5366 if (n >= 0 && index >= n)
5367 tcc_error("index too large");
5368 /* must put zero in holes (note that doing it that way
5369 ensures that it even works with designators) */
5370 if (!size_only && array_length < index) {
5371 init_putz(t1, sec, c + array_length * size1,
5372 (index - array_length) * size1);
5374 index++;
5375 if (index > array_length)
5376 array_length = index;
5377 /* special test for multi dimensional arrays (may not
5378 be strictly correct if designators are used at the
5379 same time) */
5380 if (index >= n && no_oblock)
5381 break;
5382 if (tok == '}')
5383 break;
5384 skip(',');
5387 if (!no_oblock)
5388 skip('}');
5389 /* put zeros at the end */
5390 if (!size_only && n >= 0 && array_length < n) {
5391 init_putz(t1, sec, c + array_length * size1,
5392 (n - array_length) * size1);
5394 /* patch type size if needed */
5395 if (n < 0)
5396 s->c = array_length;
5397 } else if ((type->t & VT_BTYPE) == VT_STRUCT &&
5398 (sec || !first || tok == '{')) {
5399 int par_count;
5401 /* NOTE: the previous test is a specific case for automatic
5402 struct/union init */
5403 /* XXX: union needs only one init */
5405 /* XXX: this test is incorrect for local initializers
5406 beginning with ( without {. It would be much more difficult
5407 to do it correctly (ideally, the expression parser should
5408 be used in all cases) */
5409 par_count = 0;
5410 if (tok == '(') {
5411 AttributeDef ad1;
5412 CType type1;
5413 next();
5414 while (tok == '(') {
5415 par_count++;
5416 next();
5418 if (!parse_btype(&type1, &ad1))
5419 expect("cast");
5420 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
5421 #if 0
5422 if (!is_assignable_types(type, &type1))
5423 tcc_error("invalid type for cast");
5424 #endif
5425 skip(')');
5427 no_oblock = 1;
5428 if (first || tok == '{') {
5429 skip('{');
5430 no_oblock = 0;
5432 s = type->ref;
5433 f = s->next;
5434 array_length = 0;
5435 index = 0;
5436 n = s->c;
5437 while (tok != '}') {
5438 decl_designator(type, sec, c, NULL, &f, size_only);
5439 index = f->c;
5440 if (!size_only && array_length < index) {
5441 init_putz(type, sec, c + array_length,
5442 index - array_length);
5444 index = index + type_size(&f->type, &align1);
5445 if (index > array_length)
5446 array_length = index;
5448 /* gr: skip fields from same union - ugly. */
5449 while (f->next) {
5450 ///printf("index: %2d %08x -- %2d %08x\n", f->c, f->type.t, f->next->c, f->next->type.t);
5451 /* test for same offset */
5452 if (f->next->c != f->c)
5453 break;
5454 /* if yes, test for bitfield shift */
5455 if ((f->type.t & VT_BITFIELD) && (f->next->type.t & VT_BITFIELD)) {
5456 int bit_pos_1 = (f->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5457 int bit_pos_2 = (f->next->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5458 //printf("bitfield %d %d\n", bit_pos_1, bit_pos_2);
5459 if (bit_pos_1 != bit_pos_2)
5460 break;
5462 f = f->next;
5465 f = f->next;
5466 if (no_oblock && f == NULL)
5467 break;
5468 if (tok == '}')
5469 break;
5470 skip(',');
5472 /* put zeros at the end */
5473 if (!size_only && array_length < n) {
5474 init_putz(type, sec, c + array_length,
5475 n - array_length);
5477 if (!no_oblock)
5478 skip('}');
5479 while (par_count) {
5480 skip(')');
5481 par_count--;
5483 } else if (tok == '{') {
5484 next();
5485 decl_initializer(type, sec, c, first, size_only);
5486 skip('}');
5487 } else if (size_only) {
5488 /* just skip expression */
5489 parlevel = parlevel1 = 0;
5490 while ((parlevel > 0 || parlevel1 > 0 ||
5491 (tok != '}' && tok != ',')) && tok != -1) {
5492 if (tok == '(')
5493 parlevel++;
5494 else if (tok == ')')
5495 parlevel--;
5496 else if (tok == '{')
5497 parlevel1++;
5498 else if (tok == '}')
5499 parlevel1--;
5500 next();
5502 } else {
5503 /* currently, we always use constant expression for globals
5504 (may change for scripting case) */
5505 expr_type = EXPR_CONST;
5506 if (!sec)
5507 expr_type = EXPR_ANY;
5508 init_putv(type, sec, c, 0, expr_type);
5512 /* parse an initializer for type 't' if 'has_init' is non zero, and
5513 allocate space in local or global data space ('r' is either
5514 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
5515 variable 'v' with an associated name represented by 'asm_label' of
5516 scope 'scope' is declared before initializers are parsed. If 'v' is
5517 zero, then a reference to the new object is put in the value stack.
5518 If 'has_init' is 2, a special parsing is done to handle string
5519 constants. */
5520 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
5521 int has_init, int v, char *asm_label,
5522 int scope)
5524 int size, align, addr, data_offset;
5525 int level;
5526 ParseState saved_parse_state = {0};
5527 TokenString init_str;
5528 Section *sec;
5529 Sym *flexible_array;
5531 flexible_array = NULL;
5532 if ((type->t & VT_BTYPE) == VT_STRUCT) {
5533 Sym *field = type->ref->next;
5534 if (field) {
5535 while (field->next)
5536 field = field->next;
5537 if (field->type.t & VT_ARRAY && field->type.ref->c < 0)
5538 flexible_array = field;
5542 size = type_size(type, &align);
5543 /* If unknown size, we must evaluate it before
5544 evaluating initializers because
5545 initializers can generate global data too
5546 (e.g. string pointers or ISOC99 compound
5547 literals). It also simplifies local
5548 initializers handling */
5549 tok_str_new(&init_str);
5550 if (size < 0 || (flexible_array && has_init)) {
5551 if (!has_init)
5552 tcc_error("unknown type size");
5553 /* get all init string */
5554 if (has_init == 2) {
5555 /* only get strings */
5556 while (tok == TOK_STR || tok == TOK_LSTR) {
5557 tok_str_add_tok(&init_str);
5558 next();
5560 } else {
5561 level = 0;
5562 while (level > 0 || (tok != ',' && tok != ';')) {
5563 if (tok < 0)
5564 tcc_error("unexpected end of file in initializer");
5565 tok_str_add_tok(&init_str);
5566 if (tok == '{')
5567 level++;
5568 else if (tok == '}') {
5569 level--;
5570 if (level <= 0) {
5571 next();
5572 break;
5575 next();
5578 tok_str_add(&init_str, -1);
5579 tok_str_add(&init_str, 0);
5581 /* compute size */
5582 save_parse_state(&saved_parse_state);
5584 macro_ptr = init_str.str;
5585 next();
5586 decl_initializer(type, NULL, 0, 1, 1);
5587 /* prepare second initializer parsing */
5588 macro_ptr = init_str.str;
5589 next();
5591 /* if still unknown size, error */
5592 size = type_size(type, &align);
5593 if (size < 0)
5594 tcc_error("unknown type size");
5596 if (flexible_array)
5597 size += flexible_array->type.ref->c * pointed_size(&flexible_array->type);
5598 /* take into account specified alignment if bigger */
5599 if (ad->a.aligned) {
5600 if (ad->a.aligned > align)
5601 align = ad->a.aligned;
5602 } else if (ad->a.packed) {
5603 align = 1;
5605 if ((r & VT_VALMASK) == VT_LOCAL) {
5606 sec = NULL;
5607 #ifdef CONFIG_TCC_BCHECK
5608 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5609 loc--;
5611 #endif
5612 loc = (loc - size) & -align;
5613 addr = loc;
5614 #ifdef CONFIG_TCC_BCHECK
5615 /* handles bounds */
5616 /* XXX: currently, since we do only one pass, we cannot track
5617 '&' operators, so we add only arrays */
5618 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5619 unsigned long *bounds_ptr;
5620 /* add padding between regions */
5621 loc--;
5622 /* then add local bound info */
5623 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(unsigned long));
5624 bounds_ptr[0] = addr;
5625 bounds_ptr[1] = size;
5627 #endif
5628 if (v) {
5629 /* local variable */
5630 sym_push(v, type, r, addr);
5631 } else {
5632 /* push local reference */
5633 vset(type, r, addr);
5635 } else {
5636 Sym *sym;
5638 sym = NULL;
5639 if (v && scope == VT_CONST) {
5640 /* see if the symbol was already defined */
5641 sym = sym_find(v);
5642 if (sym) {
5643 if (!is_compatible_types(&sym->type, type))
5644 tcc_error("incompatible types for redefinition of '%s'",
5645 get_tok_str(v, NULL));
5646 if (sym->type.t & VT_EXTERN) {
5647 /* if the variable is extern, it was not allocated */
5648 sym->type.t &= ~VT_EXTERN;
5649 /* set array size if it was omitted in extern
5650 declaration */
5651 if ((sym->type.t & VT_ARRAY) &&
5652 sym->type.ref->c < 0 &&
5653 type->ref->c >= 0)
5654 sym->type.ref->c = type->ref->c;
5655 } else {
5656 /* we accept several definitions of the same
5657 global variable. this is tricky, because we
5658 must play with the SHN_COMMON type of the symbol */
5659 /* XXX: should check if the variable was already
5660 initialized. It is incorrect to initialized it
5661 twice */
5662 /* no init data, we won't add more to the symbol */
5663 if (!has_init)
5664 goto no_alloc;
5669 /* allocate symbol in corresponding section */
5670 sec = ad->section;
5671 if (!sec) {
5672 if (has_init)
5673 sec = data_section;
5674 else if (tcc_state->nocommon)
5675 sec = bss_section;
5677 if (sec) {
5678 data_offset = sec->data_offset;
5679 data_offset = (data_offset + align - 1) & -align;
5680 addr = data_offset;
5681 /* very important to increment global pointer at this time
5682 because initializers themselves can create new initializers */
5683 data_offset += size;
5684 #ifdef CONFIG_TCC_BCHECK
5685 /* add padding if bound check */
5686 if (tcc_state->do_bounds_check)
5687 data_offset++;
5688 #endif
5689 sec->data_offset = data_offset;
5690 /* allocate section space to put the data */
5691 if (sec->sh_type != SHT_NOBITS &&
5692 data_offset > sec->data_allocated)
5693 section_realloc(sec, data_offset);
5694 /* align section if needed */
5695 if (align > sec->sh_addralign)
5696 sec->sh_addralign = align;
5697 } else {
5698 addr = 0; /* avoid warning */
5701 if (v) {
5702 if (scope != VT_CONST || !sym) {
5703 sym = sym_push(v, type, r | VT_SYM, 0);
5704 sym->asm_label = asm_label;
5706 /* update symbol definition */
5707 if (sec) {
5708 put_extern_sym(sym, sec, addr, size);
5709 } else {
5710 ElfW(Sym) *esym;
5711 /* put a common area */
5712 put_extern_sym(sym, NULL, align, size);
5713 /* XXX: find a nicer way */
5714 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
5715 esym->st_shndx = SHN_COMMON;
5717 } else {
5718 /* push global reference */
5719 sym = get_sym_ref(type, sec, addr, size);
5720 vpushsym(type, sym);
5722 /* patch symbol weakness */
5723 if (type->t & VT_WEAK)
5724 weaken_symbol(sym);
5725 apply_visibility(sym, type);
5726 #ifdef CONFIG_TCC_BCHECK
5727 /* handles bounds now because the symbol must be defined
5728 before for the relocation */
5729 if (tcc_state->do_bounds_check) {
5730 unsigned long *bounds_ptr;
5732 greloc(bounds_section, sym, bounds_section->data_offset, R_DATA_PTR);
5733 /* then add global bound info */
5734 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(long));
5735 bounds_ptr[0] = 0; /* relocated */
5736 bounds_ptr[1] = size;
5738 #endif
5740 if (has_init || (type->t & VT_VLA)) {
5741 decl_initializer(type, sec, addr, 1, 0);
5742 /* restore parse state if needed */
5743 if (init_str.str) {
5744 tok_str_free(init_str.str);
5745 restore_parse_state(&saved_parse_state);
5747 /* patch flexible array member size back to -1, */
5748 /* for possible subsequent similar declarations */
5749 if (flexible_array)
5750 flexible_array->type.ref->c = -1;
5752 no_alloc: ;
5755 static void put_func_debug(Sym *sym)
5757 char buf[512];
5759 /* stabs info */
5760 /* XXX: we put here a dummy type */
5761 snprintf(buf, sizeof(buf), "%s:%c1",
5762 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
5763 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
5764 cur_text_section, sym->c);
5765 /* //gr gdb wants a line at the function */
5766 put_stabn(N_SLINE, 0, file->line_num, 0);
5767 last_ind = 0;
5768 last_line_num = 0;
5771 /* parse an old style function declaration list */
5772 /* XXX: check multiple parameter */
5773 static void func_decl_list(Sym *func_sym)
5775 AttributeDef ad;
5776 int v;
5777 Sym *s;
5778 CType btype, type;
5780 /* parse each declaration */
5781 while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF &&
5782 tok != TOK_ASM1 && tok != TOK_ASM2 && tok != TOK_ASM3) {
5783 if (!parse_btype(&btype, &ad))
5784 expect("declaration list");
5785 if (((btype.t & VT_BTYPE) == VT_ENUM ||
5786 (btype.t & VT_BTYPE) == VT_STRUCT) &&
5787 tok == ';') {
5788 /* we accept no variable after */
5789 } else {
5790 for(;;) {
5791 type = btype;
5792 type_decl(&type, &ad, &v, TYPE_DIRECT);
5793 /* find parameter in function parameter list */
5794 s = func_sym->next;
5795 while (s != NULL) {
5796 if ((s->v & ~SYM_FIELD) == v)
5797 goto found;
5798 s = s->next;
5800 tcc_error("declaration for parameter '%s' but no such parameter",
5801 get_tok_str(v, NULL));
5802 found:
5803 /* check that no storage specifier except 'register' was given */
5804 if (type.t & VT_STORAGE)
5805 tcc_error("storage class specified for '%s'", get_tok_str(v, NULL));
5806 convert_parameter_type(&type);
5807 /* we can add the type (NOTE: it could be local to the function) */
5808 s->type = type;
5809 /* accept other parameters */
5810 if (tok == ',')
5811 next();
5812 else
5813 break;
5816 skip(';');
5820 /* parse a function defined by symbol 'sym' and generate its code in
5821 'cur_text_section' */
5822 static void gen_function(Sym *sym)
5824 int saved_nocode_wanted = nocode_wanted;
5825 nocode_wanted = 0;
5826 ind = cur_text_section->data_offset;
5827 /* NOTE: we patch the symbol size later */
5828 put_extern_sym(sym, cur_text_section, ind, 0);
5829 funcname = get_tok_str(sym->v, NULL);
5830 func_ind = ind;
5831 /* Initialize VLA state */
5832 vla_sp_loc = &vla_sp_root_loc;
5833 vla_flags = VLA_NEED_NEW_FRAME;
5834 /* put debug symbol */
5835 if (tcc_state->do_debug)
5836 put_func_debug(sym);
5837 /* push a dummy symbol to enable local sym storage */
5838 sym_push2(&local_stack, SYM_FIELD, 0, 0);
5839 gfunc_prolog(&sym->type);
5840 #ifdef CONFIG_TCC_BCHECK
5841 if (tcc_state->do_bounds_check
5842 && !strcmp(get_tok_str(sym->v, NULL), "main")) {
5843 int i;
5845 sym = local_stack;
5846 for (i = 0, sym = local_stack; i < 2; i++, sym = sym->prev) {
5847 if (sym->v & SYM_FIELD || sym->prev->v & SYM_FIELD)
5848 break;
5849 vpush_global_sym(&func_old_type, TOK___bound_main_arg);
5850 vset(&sym->type, sym->r, sym->c);
5851 gfunc_call(1);
5854 #endif
5855 rsym = 0;
5856 block(NULL, NULL, NULL, NULL, 0, 0);
5857 gsym(rsym);
5858 gfunc_epilog();
5859 cur_text_section->data_offset = ind;
5860 label_pop(&global_label_stack, NULL);
5861 /* reset local stack */
5862 scope_stack_bottom = NULL;
5863 sym_pop(&local_stack, NULL);
5864 /* end of function */
5865 /* patch symbol size */
5866 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
5867 ind - func_ind;
5868 /* patch symbol weakness (this definition overrules any prototype) */
5869 if (sym->type.t & VT_WEAK)
5870 weaken_symbol(sym);
5871 apply_visibility(sym, &sym->type);
5872 if (tcc_state->do_debug) {
5873 put_stabn(N_FUN, 0, 0, ind - func_ind);
5875 /* It's better to crash than to generate wrong code */
5876 cur_text_section = NULL;
5877 funcname = ""; /* for safety */
5878 func_vt.t = VT_VOID; /* for safety */
5879 func_var = 0; /* for safety */
5880 ind = 0; /* for safety */
5881 nocode_wanted = saved_nocode_wanted;
5884 ST_FUNC void gen_inline_functions(void)
5886 Sym *sym;
5887 int *str, inline_generated, i;
5888 struct InlineFunc *fn;
5890 /* iterate while inline function are referenced */
5891 for(;;) {
5892 inline_generated = 0;
5893 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
5894 fn = tcc_state->inline_fns[i];
5895 sym = fn->sym;
5896 if (sym && sym->c) {
5897 /* the function was used: generate its code and
5898 convert it to a normal function */
5899 str = fn->token_str;
5900 fn->sym = NULL;
5901 if (file)
5902 pstrcpy(file->filename, sizeof file->filename, fn->filename);
5903 sym->r = VT_SYM | VT_CONST;
5904 sym->type.t &= ~VT_INLINE;
5906 macro_ptr = str;
5907 next();
5908 cur_text_section = text_section;
5909 gen_function(sym);
5910 macro_ptr = NULL; /* fail safe */
5912 inline_generated = 1;
5915 if (!inline_generated)
5916 break;
5918 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
5919 fn = tcc_state->inline_fns[i];
5920 str = fn->token_str;
5921 tok_str_free(str);
5923 dynarray_reset(&tcc_state->inline_fns, &tcc_state->nb_inline_fns);
5926 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
5927 static int decl0(int l, int is_for_loop_init)
5929 int v, has_init, r;
5930 CType type, btype;
5931 Sym *sym;
5932 AttributeDef ad;
5934 while (1) {
5935 if (!parse_btype(&btype, &ad)) {
5936 if (is_for_loop_init)
5937 return 0;
5938 /* skip redundant ';' */
5939 /* XXX: find more elegant solution */
5940 if (tok == ';') {
5941 next();
5942 continue;
5944 if (l == VT_CONST &&
5945 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
5946 /* global asm block */
5947 asm_global_instr();
5948 continue;
5950 /* special test for old K&R protos without explicit int
5951 type. Only accepted when defining global data */
5952 if (l == VT_LOCAL || tok < TOK_DEFINE)
5953 break;
5954 btype.t = VT_INT;
5956 if (((btype.t & VT_BTYPE) == VT_ENUM ||
5957 (btype.t & VT_BTYPE) == VT_STRUCT) &&
5958 tok == ';') {
5959 /* we accept no variable after */
5960 next();
5961 continue;
5963 while (1) { /* iterate thru each declaration */
5964 char *asm_label; // associated asm label
5965 type = btype;
5966 type_decl(&type, &ad, &v, TYPE_DIRECT);
5967 #if 0
5969 char buf[500];
5970 type_to_str(buf, sizeof(buf), t, get_tok_str(v, NULL));
5971 printf("type = '%s'\n", buf);
5973 #endif
5974 if ((type.t & VT_BTYPE) == VT_FUNC) {
5975 if ((type.t & VT_STATIC) && (l == VT_LOCAL)) {
5976 tcc_error("function without file scope cannot be static");
5978 /* if old style function prototype, we accept a
5979 declaration list */
5980 sym = type.ref;
5981 if (sym->c == FUNC_OLD)
5982 func_decl_list(sym);
5985 asm_label = NULL;
5986 if (gnu_ext && (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
5987 CString astr;
5989 asm_label_instr(&astr);
5990 asm_label = tcc_strdup(astr.data);
5991 cstr_free(&astr);
5993 /* parse one last attribute list, after asm label */
5994 parse_attribute(&ad);
5997 if (ad.a.weak)
5998 type.t |= VT_WEAK;
5999 #ifdef TCC_TARGET_PE
6000 if (ad.a.func_import)
6001 type.t |= VT_IMPORT;
6002 if (ad.a.func_export)
6003 type.t |= VT_EXPORT;
6004 #endif
6005 type.t |= ad.a.visibility << VT_VIS_SHIFT;
6007 if (tok == '{') {
6008 if (l == VT_LOCAL)
6009 tcc_error("cannot use local functions");
6010 if ((type.t & VT_BTYPE) != VT_FUNC)
6011 expect("function definition");
6013 /* reject abstract declarators in function definition */
6014 sym = type.ref;
6015 while ((sym = sym->next) != NULL)
6016 if (!(sym->v & ~SYM_FIELD))
6017 expect("identifier");
6019 /* XXX: cannot do better now: convert extern line to static inline */
6020 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
6021 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
6023 sym = sym_find(v);
6024 if (sym) {
6025 Sym *ref;
6026 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
6027 goto func_error1;
6029 ref = sym->type.ref;
6030 if (0 == ref->a.func_proto)
6031 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
6033 /* use func_call from prototype if not defined */
6034 if (ref->a.func_call != FUNC_CDECL
6035 && type.ref->a.func_call == FUNC_CDECL)
6036 type.ref->a.func_call = ref->a.func_call;
6038 /* use export from prototype */
6039 if (ref->a.func_export)
6040 type.ref->a.func_export = 1;
6042 /* use static from prototype */
6043 if (sym->type.t & VT_STATIC)
6044 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
6046 /* If the definition has no visibility use the
6047 one from prototype. */
6048 if (! (type.t & VT_VIS_MASK))
6049 type.t |= sym->type.t & VT_VIS_MASK;
6051 if (!is_compatible_types(&sym->type, &type)) {
6052 func_error1:
6053 tcc_error("incompatible types for redefinition of '%s'",
6054 get_tok_str(v, NULL));
6056 type.ref->a.func_proto = 0;
6057 /* if symbol is already defined, then put complete type */
6058 sym->type = type;
6059 } else {
6060 /* put function symbol */
6061 sym = global_identifier_push(v, type.t, 0);
6062 sym->type.ref = type.ref;
6065 /* static inline functions are just recorded as a kind
6066 of macro. Their code will be emitted at the end of
6067 the compilation unit only if they are used */
6068 if ((type.t & (VT_INLINE | VT_STATIC)) ==
6069 (VT_INLINE | VT_STATIC)) {
6070 TokenString func_str;
6071 int block_level;
6072 struct InlineFunc *fn;
6073 const char *filename;
6075 tok_str_new(&func_str);
6077 block_level = 0;
6078 for(;;) {
6079 int t;
6080 if (tok == TOK_EOF)
6081 tcc_error("unexpected end of file");
6082 tok_str_add_tok(&func_str);
6083 t = tok;
6084 next();
6085 if (t == '{') {
6086 block_level++;
6087 } else if (t == '}') {
6088 block_level--;
6089 if (block_level == 0)
6090 break;
6093 tok_str_add(&func_str, -1);
6094 tok_str_add(&func_str, 0);
6095 filename = file ? file->filename : "";
6096 fn = tcc_malloc(sizeof *fn + strlen(filename));
6097 strcpy(fn->filename, filename);
6098 fn->sym = sym;
6099 fn->token_str = func_str.str;
6100 dynarray_add((void ***)&tcc_state->inline_fns, &tcc_state->nb_inline_fns, fn);
6102 } else {
6103 /* compute text section */
6104 cur_text_section = ad.section;
6105 if (!cur_text_section)
6106 cur_text_section = text_section;
6107 sym->r = VT_SYM | VT_CONST;
6108 gen_function(sym);
6110 break;
6111 } else {
6112 if (btype.t & VT_TYPEDEF) {
6113 /* save typedefed type */
6114 /* XXX: test storage specifiers ? */
6115 sym = sym_push(v, &type, 0, 0);
6116 sym->a = ad.a;
6117 sym->type.t |= VT_TYPEDEF;
6118 } else {
6119 r = 0;
6120 if ((type.t & VT_BTYPE) == VT_FUNC) {
6121 /* external function definition */
6122 /* specific case for func_call attribute */
6123 ad.a.func_proto = 1;
6124 type.ref->a = ad.a;
6125 } else if (!(type.t & VT_ARRAY)) {
6126 /* not lvalue if array */
6127 r |= lvalue_type(type.t);
6129 has_init = (tok == '=');
6130 if (has_init && (type.t & VT_VLA))
6131 tcc_error("Variable length array cannot be initialized");
6132 if ((btype.t & VT_EXTERN) || ((type.t & VT_BTYPE) == VT_FUNC) ||
6133 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
6134 !has_init && l == VT_CONST && type.ref->c < 0)) {
6135 /* external variable or function */
6136 /* NOTE: as GCC, uninitialized global static
6137 arrays of null size are considered as
6138 extern */
6139 sym = external_sym(v, &type, r, asm_label);
6141 if (ad.alias_target) {
6142 Section tsec;
6143 Elf32_Sym *esym;
6144 Sym *alias_target;
6146 alias_target = sym_find(ad.alias_target);
6147 if (!alias_target || !alias_target->c)
6148 tcc_error("unsupported forward __alias__ attribute");
6149 esym = &((Elf32_Sym *)symtab_section->data)[alias_target->c];
6150 tsec.sh_num = esym->st_shndx;
6151 put_extern_sym2(sym, &tsec, esym->st_value, esym->st_size, 0);
6153 } else {
6154 type.t |= (btype.t & VT_STATIC); /* Retain "static". */
6155 if (type.t & VT_STATIC)
6156 r |= VT_CONST;
6157 else
6158 r |= l;
6159 if (has_init)
6160 next();
6161 decl_initializer_alloc(&type, &ad, r, has_init, v, asm_label, l);
6164 if (tok != ',') {
6165 if (is_for_loop_init)
6166 return 1;
6167 skip(';');
6168 break;
6170 next();
6172 ad.a.aligned = 0;
6175 return 0;
6178 ST_FUNC void decl(int l)
6180 decl0(l, 0);