Fix initializing members multiple times
[tinycc.git] / tccgen.c
blob5c749712f5def8af5c696a6497026e0f75371b8b
1 /*
2 * TCC - Tiny C Compiler
3 *
4 * Copyright (c) 2001-2004 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #include "tcc.h"
23 /********************************************************/
24 /* global variables */
26 /* loc : local variable index
27 ind : output code index
28 rsym: return symbol
29 anon_sym: anonymous symbol index
31 ST_DATA int rsym, anon_sym, ind, loc;
33 ST_DATA Sym *sym_free_first;
34 ST_DATA void **sym_pools;
35 ST_DATA int nb_sym_pools;
37 ST_DATA Sym *global_stack;
38 ST_DATA Sym *local_stack;
39 ST_DATA Sym *define_stack;
40 ST_DATA Sym *global_label_stack;
41 ST_DATA Sym *local_label_stack;
42 static int local_scope;
43 static int in_sizeof;
44 static int section_sym;
46 ST_DATA int vlas_in_scope; /* number of VLAs that are currently in scope */
47 ST_DATA int vla_sp_root_loc; /* vla_sp_loc for SP before any VLAs were pushed */
48 ST_DATA int vla_sp_loc; /* Pointer to variable holding location to store stack pointer on the stack when modifying stack pointer */
50 ST_DATA SValue __vstack[1+VSTACK_SIZE], *vtop, *pvtop;
52 ST_DATA int const_wanted; /* true if constant wanted */
53 ST_DATA int nocode_wanted; /* true if no code generation wanted for an expression */
54 ST_DATA int global_expr; /* true if compound literals must be allocated globally (used during initializers parsing */
55 ST_DATA CType func_vt; /* current function return type (used by return instruction) */
56 ST_DATA int func_var; /* true if current function is variadic (used by return instruction) */
57 ST_DATA int func_vc;
58 ST_DATA int last_line_num, last_ind, func_ind; /* debug last line number and pc */
59 ST_DATA const char *funcname;
61 ST_DATA CType char_pointer_type, func_old_type, int_type, size_type;
63 ST_DATA struct switch_t {
64 struct case_t {
65 int v1, v2, sym;
66 } **p; int n; /* list of case ranges */
67 int def_sym; /* default symbol */
68 } *cur_switch; /* current switch */
70 /* ------------------------------------------------------------------------- */
71 static void gen_cast(CType *type);
72 static inline CType *pointed_type(CType *type);
73 static int is_compatible_types(CType *type1, CType *type2);
74 static int parse_btype(CType *type, AttributeDef *ad);
75 static void type_decl(CType *type, AttributeDef *ad, int *v, int td);
76 static void parse_expr_type(CType *type);
77 static void decl_initializer(CType *type, Section *sec, unsigned long c, int first, int size_only);
78 static void block(int *bsym, int *csym, int is_expr);
79 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r, int has_init, int v, int scope);
80 static int decl0(int l, int is_for_loop_init);
81 static void expr_eq(void);
82 static void expr_lor_const(void);
83 static void unary_type(CType *type);
84 static void vla_runtime_type_size(CType *type, int *a);
85 static void vla_sp_restore(void);
86 static void vla_sp_restore_root(void);
87 static int is_compatible_parameter_types(CType *type1, CType *type2);
88 static void expr_type(CType *type);
89 ST_FUNC void vpush64(int ty, unsigned long long v);
90 ST_FUNC void vpush(CType *type);
91 ST_FUNC int gvtst(int inv, int t);
92 ST_FUNC int is_btype_size(int bt);
93 static void gen_inline_functions(TCCState *s);
95 ST_INLN int is_float(int t)
97 int bt;
98 bt = t & VT_BTYPE;
99 return bt == VT_LDOUBLE || bt == VT_DOUBLE || bt == VT_FLOAT || bt == VT_QFLOAT;
102 /* we use our own 'finite' function to avoid potential problems with
103 non standard math libs */
104 /* XXX: endianness dependent */
105 ST_FUNC int ieee_finite(double d)
107 int p[4];
108 memcpy(p, &d, sizeof(double));
109 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
112 ST_FUNC void test_lvalue(void)
114 if (!(vtop->r & VT_LVAL))
115 expect("lvalue");
118 ST_FUNC void check_vstack(void)
120 if (pvtop != vtop)
121 tcc_error("internal compiler error: vstack leak (%d)", vtop - pvtop);
124 /* ------------------------------------------------------------------------- */
125 /* vstack debugging aid */
127 #if 0
128 void pv (const char *lbl, int a, int b)
130 int i;
131 for (i = a; i < a + b; ++i) {
132 SValue *p = &vtop[-i];
133 printf("%s vtop[-%d] : type.t:%04x r:%04x r2:%04x c.i:%d\n",
134 lbl, i, p->type.t, p->r, p->r2, (int)p->c.i);
137 #endif
139 /* ------------------------------------------------------------------------- */
140 ST_FUNC void tccgen_start(TCCState *s1)
142 cur_text_section = NULL;
143 funcname = "";
144 anon_sym = SYM_FIRST_ANOM;
145 section_sym = 0;
146 nocode_wanted = 1;
148 /* define some often used types */
149 int_type.t = VT_INT;
150 char_pointer_type.t = VT_BYTE;
151 mk_pointer(&char_pointer_type);
152 #if PTR_SIZE == 4
153 size_type.t = VT_INT;
154 #else
155 size_type.t = VT_LLONG;
156 #endif
157 func_old_type.t = VT_FUNC;
158 func_old_type.ref = sym_push(SYM_FIELD, &int_type, FUNC_CDECL, FUNC_OLD);
160 if (s1->do_debug) {
161 char buf[512];
163 /* file info: full path + filename */
164 section_sym = put_elf_sym(symtab_section, 0, 0,
165 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
166 text_section->sh_num, NULL);
167 getcwd(buf, sizeof(buf));
168 #ifdef _WIN32
169 normalize_slashes(buf);
170 #endif
171 pstrcat(buf, sizeof(buf), "/");
172 put_stabs_r(buf, N_SO, 0, 0,
173 text_section->data_offset, text_section, section_sym);
174 put_stabs_r(file->filename, N_SO, 0, 0,
175 text_section->data_offset, text_section, section_sym);
177 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
178 symbols can be safely used */
179 put_elf_sym(symtab_section, 0, 0,
180 ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
181 SHN_ABS, file->filename);
183 #ifdef TCC_TARGET_ARM
184 arm_init(s1);
185 #endif
188 ST_FUNC void tccgen_end(TCCState *s1)
190 gen_inline_functions(s1);
191 check_vstack();
192 /* end of translation unit info */
193 if (s1->do_debug) {
194 put_stabs_r(NULL, N_SO, 0, 0,
195 text_section->data_offset, text_section, section_sym);
199 /* ------------------------------------------------------------------------- */
200 /* update sym->c so that it points to an external symbol in section
201 'section' with value 'value' */
203 ST_FUNC void put_extern_sym2(Sym *sym, Section *section,
204 addr_t value, unsigned long size,
205 int can_add_underscore)
207 int sym_type, sym_bind, sh_num, info, other;
208 ElfW(Sym) *esym;
209 const char *name;
210 char buf1[256];
212 #ifdef CONFIG_TCC_BCHECK
213 char buf[32];
214 #endif
216 if (section == NULL)
217 sh_num = SHN_UNDEF;
218 else if (section == SECTION_ABS)
219 sh_num = SHN_ABS;
220 else
221 sh_num = section->sh_num;
223 if ((sym->type.t & VT_BTYPE) == VT_FUNC) {
224 sym_type = STT_FUNC;
225 } else if ((sym->type.t & VT_BTYPE) == VT_VOID) {
226 sym_type = STT_NOTYPE;
227 } else {
228 sym_type = STT_OBJECT;
231 if (sym->type.t & VT_STATIC)
232 sym_bind = STB_LOCAL;
233 else {
234 if (sym->type.t & VT_WEAK)
235 sym_bind = STB_WEAK;
236 else
237 sym_bind = STB_GLOBAL;
240 if (!sym->c) {
241 name = get_tok_str(sym->v, NULL);
242 #ifdef CONFIG_TCC_BCHECK
243 if (tcc_state->do_bounds_check) {
244 /* XXX: avoid doing that for statics ? */
245 /* if bound checking is activated, we change some function
246 names by adding the "__bound" prefix */
247 switch(sym->v) {
248 #ifdef TCC_TARGET_PE
249 /* XXX: we rely only on malloc hooks */
250 case TOK_malloc:
251 case TOK_free:
252 case TOK_realloc:
253 case TOK_memalign:
254 case TOK_calloc:
255 #endif
256 case TOK_memcpy:
257 case TOK_memmove:
258 case TOK_memset:
259 case TOK_strlen:
260 case TOK_strcpy:
261 case TOK_alloca:
262 strcpy(buf, "__bound_");
263 strcat(buf, name);
264 name = buf;
265 break;
268 #endif
269 other = 0;
271 #ifdef TCC_TARGET_PE
272 if (sym->type.t & VT_EXPORT)
273 other |= ST_PE_EXPORT;
274 if (sym_type == STT_FUNC && sym->type.ref) {
275 Sym *ref = sym->type.ref;
276 if (ref->a.func_export)
277 other |= ST_PE_EXPORT;
278 if (ref->a.func_call == FUNC_STDCALL && can_add_underscore) {
279 sprintf(buf1, "_%s@%d", name, ref->a.func_args * PTR_SIZE);
280 name = buf1;
281 other |= ST_PE_STDCALL;
282 can_add_underscore = 0;
284 } else {
285 if (find_elf_sym(tcc_state->dynsymtab_section, name))
286 other |= ST_PE_IMPORT;
287 if (sym->type.t & VT_IMPORT)
288 other |= ST_PE_IMPORT;
290 #else
291 if (! (sym->type.t & VT_STATIC))
292 other = (sym->type.t & VT_VIS_MASK) >> VT_VIS_SHIFT;
293 #endif
294 if (tcc_state->leading_underscore && can_add_underscore) {
295 buf1[0] = '_';
296 pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
297 name = buf1;
299 if (sym->asm_label) {
300 name = get_tok_str(sym->asm_label, NULL);
302 info = ELFW(ST_INFO)(sym_bind, sym_type);
303 sym->c = set_elf_sym(symtab_section, value, size, info, other, sh_num, name);
304 } else {
305 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
306 esym->st_value = value;
307 esym->st_size = size;
308 esym->st_shndx = sh_num;
312 ST_FUNC void put_extern_sym(Sym *sym, Section *section,
313 addr_t value, unsigned long size)
315 put_extern_sym2(sym, section, value, size, 1);
318 /* add a new relocation entry to symbol 'sym' in section 's' */
319 ST_FUNC void greloca(Section *s, Sym *sym, unsigned long offset, int type,
320 addr_t addend)
322 int c = 0;
323 if (sym) {
324 if (0 == sym->c)
325 put_extern_sym(sym, NULL, 0, 0);
326 c = sym->c;
328 /* now we can add ELF relocation info */
329 put_elf_reloca(symtab_section, s, offset, type, c, addend);
332 ST_FUNC void greloc(Section *s, Sym *sym, unsigned long offset, int type)
334 greloca(s, sym, offset, type, 0);
337 /* ------------------------------------------------------------------------- */
338 /* symbol allocator */
339 static Sym *__sym_malloc(void)
341 Sym *sym_pool, *sym, *last_sym;
342 int i;
344 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
345 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
347 last_sym = sym_free_first;
348 sym = sym_pool;
349 for(i = 0; i < SYM_POOL_NB; i++) {
350 sym->next = last_sym;
351 last_sym = sym;
352 sym++;
354 sym_free_first = last_sym;
355 return last_sym;
358 static inline Sym *sym_malloc(void)
360 Sym *sym;
361 #ifndef SYM_DEBUG
362 sym = sym_free_first;
363 if (!sym)
364 sym = __sym_malloc();
365 sym_free_first = sym->next;
366 return sym;
367 #else
368 sym = tcc_malloc(sizeof(Sym));
369 return sym;
370 #endif
373 ST_INLN void sym_free(Sym *sym)
375 #ifndef SYM_DEBUG
376 sym->next = sym_free_first;
377 sym_free_first = sym;
378 #else
379 tcc_free(sym);
380 #endif
383 /* push, without hashing */
384 ST_FUNC Sym *sym_push2(Sym **ps, int v, int t, long c)
386 Sym *s;
388 s = sym_malloc();
389 s->scope = 0;
390 s->v = v;
391 s->type.t = t;
392 s->type.ref = NULL;
393 #ifdef _WIN64
394 s->d = NULL;
395 #endif
396 s->c = c;
397 s->next = NULL;
398 /* add in stack */
399 s->prev = *ps;
400 *ps = s;
401 return s;
404 /* find a symbol and return its associated structure. 's' is the top
405 of the symbol stack */
406 ST_FUNC Sym *sym_find2(Sym *s, int v)
408 while (s) {
409 if (s->v == v)
410 return s;
411 else if (s->v == -1)
412 return NULL;
413 s = s->prev;
415 return NULL;
418 /* structure lookup */
419 ST_INLN Sym *struct_find(int v)
421 v -= TOK_IDENT;
422 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
423 return NULL;
424 return table_ident[v]->sym_struct;
427 /* find an identifier */
428 ST_INLN Sym *sym_find(int v)
430 v -= TOK_IDENT;
431 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
432 return NULL;
433 return table_ident[v]->sym_identifier;
436 /* push a given symbol on the symbol stack */
437 ST_FUNC Sym *sym_push(int v, CType *type, int r, int c)
439 Sym *s, **ps;
440 TokenSym *ts;
442 if (local_stack)
443 ps = &local_stack;
444 else
445 ps = &global_stack;
446 s = sym_push2(ps, v, type->t, c);
447 s->type.ref = type->ref;
448 s->r = r;
449 /* don't record fields or anonymous symbols */
450 /* XXX: simplify */
451 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
452 /* record symbol in token array */
453 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
454 if (v & SYM_STRUCT)
455 ps = &ts->sym_struct;
456 else
457 ps = &ts->sym_identifier;
458 s->prev_tok = *ps;
459 *ps = s;
460 s->scope = local_scope;
461 if (s->prev_tok && s->prev_tok->scope == s->scope)
462 tcc_error("redeclaration of '%s'",
463 get_tok_str(v & ~SYM_STRUCT, NULL));
465 return s;
468 /* push a global identifier */
469 ST_FUNC Sym *global_identifier_push(int v, int t, int c)
471 Sym *s, **ps;
472 s = sym_push2(&global_stack, v, t, c);
473 /* don't record anonymous symbol */
474 if (v < SYM_FIRST_ANOM) {
475 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
476 /* modify the top most local identifier, so that
477 sym_identifier will point to 's' when popped */
478 while (*ps != NULL)
479 ps = &(*ps)->prev_tok;
480 s->prev_tok = NULL;
481 *ps = s;
483 return s;
486 /* pop symbols until top reaches 'b'. If KEEP is non-zero don't really
487 pop them yet from the list, but do remove them from the token array. */
488 ST_FUNC void sym_pop(Sym **ptop, Sym *b, int keep)
490 Sym *s, *ss, **ps;
491 TokenSym *ts;
492 int v;
494 s = *ptop;
495 while(s != b) {
496 ss = s->prev;
497 v = s->v;
498 /* remove symbol in token array */
499 /* XXX: simplify */
500 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
501 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
502 if (v & SYM_STRUCT)
503 ps = &ts->sym_struct;
504 else
505 ps = &ts->sym_identifier;
506 *ps = s->prev_tok;
508 if (!keep)
509 sym_free(s);
510 s = ss;
512 if (!keep)
513 *ptop = b;
516 static void weaken_symbol(Sym *sym)
518 sym->type.t |= VT_WEAK;
519 if (sym->c > 0) {
520 int esym_type;
521 ElfW(Sym) *esym;
523 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
524 esym_type = ELFW(ST_TYPE)(esym->st_info);
525 esym->st_info = ELFW(ST_INFO)(STB_WEAK, esym_type);
529 static void apply_visibility(Sym *sym, CType *type)
531 int vis = sym->type.t & VT_VIS_MASK;
532 int vis2 = type->t & VT_VIS_MASK;
533 if (vis == (STV_DEFAULT << VT_VIS_SHIFT))
534 vis = vis2;
535 else if (vis2 == (STV_DEFAULT << VT_VIS_SHIFT))
537 else
538 vis = (vis < vis2) ? vis : vis2;
539 sym->type.t &= ~VT_VIS_MASK;
540 sym->type.t |= vis;
542 if (sym->c > 0) {
543 ElfW(Sym) *esym;
545 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
546 vis >>= VT_VIS_SHIFT;
547 esym->st_other = (esym->st_other & ~ELFW(ST_VISIBILITY)(-1)) | vis;
551 /* ------------------------------------------------------------------------- */
553 ST_FUNC void swap(int *p, int *q)
555 int t;
556 t = *p;
557 *p = *q;
558 *q = t;
561 static void vsetc(CType *type, int r, CValue *vc)
563 int v;
565 if (vtop >= vstack + (VSTACK_SIZE - 1))
566 tcc_error("memory full (vstack)");
567 /* cannot let cpu flags if other instruction are generated. Also
568 avoid leaving VT_JMP anywhere except on the top of the stack
569 because it would complicate the code generator. */
570 if (vtop >= vstack) {
571 v = vtop->r & VT_VALMASK;
572 if (v == VT_CMP || (v & ~1) == VT_JMP)
573 gv(RC_INT);
575 vtop++;
576 vtop->type = *type;
577 vtop->r = r;
578 vtop->r2 = VT_CONST;
579 vtop->c = *vc;
580 vtop->sym = NULL;
583 /* push constant of type "type" with useless value */
584 ST_FUNC void vpush(CType *type)
586 CValue cval;
587 vsetc(type, VT_CONST, &cval);
590 /* push integer constant */
591 ST_FUNC void vpushi(int v)
593 CValue cval;
594 cval.i = v;
595 vsetc(&int_type, VT_CONST, &cval);
598 /* push a pointer sized constant */
599 static void vpushs(addr_t v)
601 CValue cval;
602 cval.i = v;
603 vsetc(&size_type, VT_CONST, &cval);
606 /* push arbitrary 64bit constant */
607 ST_FUNC void vpush64(int ty, unsigned long long v)
609 CValue cval;
610 CType ctype;
611 ctype.t = ty;
612 ctype.ref = NULL;
613 cval.i = v;
614 vsetc(&ctype, VT_CONST, &cval);
617 /* push long long constant */
618 static inline void vpushll(long long v)
620 vpush64(VT_LLONG, v);
623 /* push a symbol value of TYPE */
624 static inline void vpushsym(CType *type, Sym *sym)
626 CValue cval;
627 cval.i = 0;
628 vsetc(type, VT_CONST | VT_SYM, &cval);
629 vtop->sym = sym;
632 /* Return a static symbol pointing to a section */
633 ST_FUNC Sym *get_sym_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
635 int v;
636 Sym *sym;
638 v = anon_sym++;
639 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
640 sym->type.ref = type->ref;
641 sym->r = VT_CONST | VT_SYM;
642 put_extern_sym(sym, sec, offset, size);
643 return sym;
646 /* push a reference to a section offset by adding a dummy symbol */
647 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
649 vpushsym(type, get_sym_ref(type, sec, offset, size));
652 /* define a new external reference to a symbol 'v' of type 'u' */
653 ST_FUNC Sym *external_global_sym(int v, CType *type, int r)
655 Sym *s;
657 s = sym_find(v);
658 if (!s) {
659 /* push forward reference */
660 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
661 s->type.ref = type->ref;
662 s->r = r | VT_CONST | VT_SYM;
664 return s;
667 /* define a new external reference to a symbol 'v' */
668 static Sym *external_sym(int v, CType *type, int r)
670 Sym *s;
672 s = sym_find(v);
673 if (!s) {
674 /* push forward reference */
675 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
676 s->type.t |= VT_EXTERN;
677 } else if (s->type.ref == func_old_type.ref) {
678 s->type.ref = type->ref;
679 s->r = r | VT_CONST | VT_SYM;
680 s->type.t |= VT_EXTERN;
681 } else if (!is_compatible_types(&s->type, type)) {
682 tcc_error("incompatible types for redefinition of '%s'",
683 get_tok_str(v, NULL));
685 /* Merge some storage attributes. */
686 if (type->t & VT_WEAK)
687 weaken_symbol(s);
689 if (type->t & VT_VIS_MASK)
690 apply_visibility(s, type);
692 return s;
695 /* push a reference to global symbol v */
696 ST_FUNC void vpush_global_sym(CType *type, int v)
698 vpushsym(type, external_global_sym(v, type, 0));
701 ST_FUNC void vset(CType *type, int r, int v)
703 CValue cval;
705 cval.i = v;
706 vsetc(type, r, &cval);
709 static void vseti(int r, int v)
711 CType type;
712 type.t = VT_INT;
713 type.ref = 0;
714 vset(&type, r, v);
717 ST_FUNC void vswap(void)
719 SValue tmp;
720 /* cannot let cpu flags if other instruction are generated. Also
721 avoid leaving VT_JMP anywhere except on the top of the stack
722 because it would complicate the code generator. */
723 if (vtop >= vstack) {
724 int v = vtop->r & VT_VALMASK;
725 if (v == VT_CMP || (v & ~1) == VT_JMP)
726 gv(RC_INT);
728 tmp = vtop[0];
729 vtop[0] = vtop[-1];
730 vtop[-1] = tmp;
732 /* XXX: +2% overall speed possible with optimized memswap
734 * memswap(&vtop[0], &vtop[1], sizeof *vtop);
738 ST_FUNC void vpushv(SValue *v)
740 if (vtop >= vstack + (VSTACK_SIZE - 1))
741 tcc_error("memory full (vstack)");
742 vtop++;
743 *vtop = *v;
746 static void vdup(void)
748 vpushv(vtop);
751 /* save registers up to (vtop - n) stack entry */
752 ST_FUNC void save_regs(int n)
754 SValue *p, *p1;
755 for(p = vstack, p1 = vtop - n; p <= p1; p++)
756 save_reg(p->r);
759 /* save r to the memory stack, and mark it as being free */
760 ST_FUNC void save_reg(int r)
762 save_reg_upstack(r, 0);
765 /* save r to the memory stack, and mark it as being free,
766 if seen up to (vtop - n) stack entry */
767 ST_FUNC void save_reg_upstack(int r, int n)
769 int l, saved, size, align;
770 SValue *p, *p1, sv;
771 CType *type;
773 if ((r &= VT_VALMASK) >= VT_CONST)
774 return;
776 /* modify all stack values */
777 saved = 0;
778 l = 0;
779 for(p = vstack, p1 = vtop - n; p <= p1; p++) {
780 if ((p->r & VT_VALMASK) == r ||
781 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
782 /* must save value on stack if not already done */
783 if (!saved) {
784 /* NOTE: must reload 'r' because r might be equal to r2 */
785 r = p->r & VT_VALMASK;
786 /* store register in the stack */
787 type = &p->type;
788 if ((p->r & VT_LVAL) ||
789 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
790 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
791 type = &char_pointer_type;
792 #else
793 type = &int_type;
794 #endif
795 size = type_size(type, &align);
796 loc = (loc - size) & -align;
797 sv.type.t = type->t;
798 sv.r = VT_LOCAL | VT_LVAL;
799 sv.c.i = loc;
800 store(r, &sv);
801 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
802 /* x86 specific: need to pop fp register ST0 if saved */
803 if (r == TREG_ST0) {
804 o(0xd8dd); /* fstp %st(0) */
806 #endif
807 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
808 /* special long long case */
809 if ((type->t & VT_BTYPE) == VT_LLONG) {
810 sv.c.i += 4;
811 store(p->r2, &sv);
813 #endif
814 l = loc;
815 saved = 1;
817 /* mark that stack entry as being saved on the stack */
818 if (p->r & VT_LVAL) {
819 /* also clear the bounded flag because the
820 relocation address of the function was stored in
821 p->c.i */
822 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
823 } else {
824 p->r = lvalue_type(p->type.t) | VT_LOCAL;
826 p->r2 = VT_CONST;
827 p->c.i = l;
832 #ifdef TCC_TARGET_ARM
833 /* find a register of class 'rc2' with at most one reference on stack.
834 * If none, call get_reg(rc) */
835 ST_FUNC int get_reg_ex(int rc, int rc2)
837 int r;
838 SValue *p;
840 for(r=0;r<NB_REGS;r++) {
841 if (reg_classes[r] & rc2) {
842 int n;
843 n=0;
844 for(p = vstack; p <= vtop; p++) {
845 if ((p->r & VT_VALMASK) == r ||
846 (p->r2 & VT_VALMASK) == r)
847 n++;
849 if (n <= 1)
850 return r;
853 return get_reg(rc);
855 #endif
857 /* find a free register of class 'rc'. If none, save one register */
858 ST_FUNC int get_reg(int rc)
860 int r;
861 SValue *p;
863 /* find a free register */
864 for(r=0;r<NB_REGS;r++) {
865 if (reg_classes[r] & rc) {
866 for(p=vstack;p<=vtop;p++) {
867 if ((p->r & VT_VALMASK) == r ||
868 (p->r2 & VT_VALMASK) == r)
869 goto notfound;
871 return r;
873 notfound: ;
876 /* no register left : free the first one on the stack (VERY
877 IMPORTANT to start from the bottom to ensure that we don't
878 spill registers used in gen_opi()) */
879 for(p=vstack;p<=vtop;p++) {
880 /* look at second register (if long long) */
881 r = p->r2 & VT_VALMASK;
882 if (r < VT_CONST && (reg_classes[r] & rc))
883 goto save_found;
884 r = p->r & VT_VALMASK;
885 if (r < VT_CONST && (reg_classes[r] & rc)) {
886 save_found:
887 save_reg(r);
888 return r;
891 /* Should never comes here */
892 return -1;
895 /* move register 's' (of type 't') to 'r', and flush previous value of r to memory
896 if needed */
897 static void move_reg(int r, int s, int t)
899 SValue sv;
901 if (r != s) {
902 save_reg(r);
903 sv.type.t = t;
904 sv.type.ref = NULL;
905 sv.r = s;
906 sv.c.i = 0;
907 load(r, &sv);
911 /* get address of vtop (vtop MUST BE an lvalue) */
912 ST_FUNC void gaddrof(void)
914 if (vtop->r & VT_REF && !nocode_wanted)
915 gv(RC_INT);
916 vtop->r &= ~VT_LVAL;
917 /* tricky: if saved lvalue, then we can go back to lvalue */
918 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
919 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
924 #ifdef CONFIG_TCC_BCHECK
925 /* generate lvalue bound code */
926 static void gbound(void)
928 int lval_type;
929 CType type1;
931 vtop->r &= ~VT_MUSTBOUND;
932 /* if lvalue, then use checking code before dereferencing */
933 if (vtop->r & VT_LVAL) {
934 /* if not VT_BOUNDED value, then make one */
935 if (!(vtop->r & VT_BOUNDED)) {
936 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
937 /* must save type because we must set it to int to get pointer */
938 type1 = vtop->type;
939 vtop->type.t = VT_PTR;
940 gaddrof();
941 vpushi(0);
942 gen_bounded_ptr_add();
943 vtop->r |= lval_type;
944 vtop->type = type1;
946 /* then check for dereferencing */
947 gen_bounded_ptr_deref();
950 #endif
952 /* store vtop a register belonging to class 'rc'. lvalues are
953 converted to values. Cannot be used if cannot be converted to
954 register value (such as structures). */
955 ST_FUNC int gv(int rc)
957 int r, bit_pos, bit_size, size, align, i;
958 int rc2;
960 /* NOTE: get_reg can modify vstack[] */
961 if (vtop->type.t & VT_BITFIELD) {
962 CType type;
963 int bits = 32;
964 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
965 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
966 /* remove bit field info to avoid loops */
967 vtop->type.t &= ~VT_BITFIELD & ((1 << VT_STRUCT_SHIFT) - 1);
968 /* cast to int to propagate signedness in following ops */
969 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
970 type.t = VT_LLONG;
971 bits = 64;
972 } else
973 type.t = VT_INT;
974 if((vtop->type.t & VT_UNSIGNED) ||
975 (vtop->type.t & VT_BTYPE) == VT_BOOL)
976 type.t |= VT_UNSIGNED;
977 gen_cast(&type);
978 /* generate shifts */
979 vpushi(bits - (bit_pos + bit_size));
980 gen_op(TOK_SHL);
981 vpushi(bits - bit_size);
982 /* NOTE: transformed to SHR if unsigned */
983 gen_op(TOK_SAR);
984 r = gv(rc);
985 } else {
986 if (is_float(vtop->type.t) &&
987 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
988 Sym *sym;
989 int *ptr;
990 unsigned long offset;
991 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
992 CValue check;
993 #endif
995 /* XXX: unify with initializers handling ? */
996 /* CPUs usually cannot use float constants, so we store them
997 generically in data segment */
998 size = type_size(&vtop->type, &align);
999 offset = (data_section->data_offset + align - 1) & -align;
1000 data_section->data_offset = offset;
1001 /* XXX: not portable yet */
1002 #if defined(__i386__) || defined(__x86_64__)
1003 /* Zero pad x87 tenbyte long doubles */
1004 if (size == LDOUBLE_SIZE) {
1005 vtop->c.tab[2] &= 0xffff;
1006 #if LDOUBLE_SIZE == 16
1007 vtop->c.tab[3] = 0;
1008 #endif
1010 #endif
1011 ptr = section_ptr_add(data_section, size);
1012 size = size >> 2;
1013 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
1014 check.d = 1;
1015 if(check.tab[0])
1016 for(i=0;i<size;i++)
1017 ptr[i] = vtop->c.tab[size-1-i];
1018 else
1019 #endif
1020 for(i=0;i<size;i++)
1021 ptr[i] = vtop->c.tab[i];
1022 sym = get_sym_ref(&vtop->type, data_section, offset, size << 2);
1023 vtop->r |= VT_LVAL | VT_SYM;
1024 vtop->sym = sym;
1025 vtop->c.i = 0;
1027 #ifdef CONFIG_TCC_BCHECK
1028 if (vtop->r & VT_MUSTBOUND)
1029 gbound();
1030 #endif
1032 r = vtop->r & VT_VALMASK;
1033 rc2 = (rc & RC_FLOAT) ? RC_FLOAT : RC_INT;
1034 #ifndef TCC_TARGET_ARM64
1035 if (rc == RC_IRET)
1036 rc2 = RC_LRET;
1037 #ifdef TCC_TARGET_X86_64
1038 else if (rc == RC_FRET)
1039 rc2 = RC_QRET;
1040 #endif
1041 #endif
1043 /* need to reload if:
1044 - constant
1045 - lvalue (need to dereference pointer)
1046 - already a register, but not in the right class */
1047 if (r >= VT_CONST
1048 || (vtop->r & VT_LVAL)
1049 || !(reg_classes[r] & rc)
1050 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1051 || ((vtop->type.t & VT_BTYPE) == VT_QLONG && !(reg_classes[vtop->r2] & rc2))
1052 || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT && !(reg_classes[vtop->r2] & rc2))
1053 #else
1054 || ((vtop->type.t & VT_BTYPE) == VT_LLONG && !(reg_classes[vtop->r2] & rc2))
1055 #endif
1058 r = get_reg(rc);
1059 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1060 if (((vtop->type.t & VT_BTYPE) == VT_QLONG) || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT)) {
1061 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
1062 #else
1063 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
1064 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
1065 unsigned long long ll;
1066 #endif
1067 int r2, original_type;
1068 original_type = vtop->type.t;
1069 /* two register type load : expand to two words
1070 temporarily */
1071 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
1072 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
1073 /* load constant */
1074 ll = vtop->c.i;
1075 vtop->c.i = ll; /* first word */
1076 load(r, vtop);
1077 vtop->r = r; /* save register value */
1078 vpushi(ll >> 32); /* second word */
1079 } else
1080 #endif
1081 if (vtop->r & VT_LVAL) {
1082 /* We do not want to modifier the long long
1083 pointer here, so the safest (and less
1084 efficient) is to save all the other registers
1085 in the stack. XXX: totally inefficient. */
1086 #if 0
1087 save_regs(1);
1088 #else
1089 /* lvalue_save: save only if used further down the stack */
1090 save_reg_upstack(vtop->r, 1);
1091 #endif
1092 /* load from memory */
1093 vtop->type.t = load_type;
1094 load(r, vtop);
1095 vdup();
1096 vtop[-1].r = r; /* save register value */
1097 /* increment pointer to get second word */
1098 vtop->type.t = addr_type;
1099 gaddrof();
1100 vpushi(load_size);
1101 gen_op('+');
1102 vtop->r |= VT_LVAL;
1103 vtop->type.t = load_type;
1104 } else {
1105 /* move registers */
1106 load(r, vtop);
1107 vdup();
1108 vtop[-1].r = r; /* save register value */
1109 vtop->r = vtop[-1].r2;
1111 /* Allocate second register. Here we rely on the fact that
1112 get_reg() tries first to free r2 of an SValue. */
1113 r2 = get_reg(rc2);
1114 load(r2, vtop);
1115 vpop();
1116 /* write second register */
1117 vtop->r2 = r2;
1118 vtop->type.t = original_type;
1119 } else if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
1120 int t1, t;
1121 /* lvalue of scalar type : need to use lvalue type
1122 because of possible cast */
1123 t = vtop->type.t;
1124 t1 = t;
1125 /* compute memory access type */
1126 if (vtop->r & VT_REF)
1127 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1128 t = VT_PTR;
1129 #else
1130 t = VT_INT;
1131 #endif
1132 else if (vtop->r & VT_LVAL_BYTE)
1133 t = VT_BYTE;
1134 else if (vtop->r & VT_LVAL_SHORT)
1135 t = VT_SHORT;
1136 if (vtop->r & VT_LVAL_UNSIGNED)
1137 t |= VT_UNSIGNED;
1138 vtop->type.t = t;
1139 load(r, vtop);
1140 /* restore wanted type */
1141 vtop->type.t = t1;
1142 } else {
1143 /* one register type load */
1144 load(r, vtop);
1147 vtop->r = r;
1148 #ifdef TCC_TARGET_C67
1149 /* uses register pairs for doubles */
1150 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
1151 vtop->r2 = r+1;
1152 #endif
1154 return r;
1157 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
1158 ST_FUNC void gv2(int rc1, int rc2)
1160 int v;
1162 /* generate more generic register first. But VT_JMP or VT_CMP
1163 values must be generated first in all cases to avoid possible
1164 reload errors */
1165 v = vtop[0].r & VT_VALMASK;
1166 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
1167 vswap();
1168 gv(rc1);
1169 vswap();
1170 gv(rc2);
1171 /* test if reload is needed for first register */
1172 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
1173 vswap();
1174 gv(rc1);
1175 vswap();
1177 } else {
1178 gv(rc2);
1179 vswap();
1180 gv(rc1);
1181 vswap();
1182 /* test if reload is needed for first register */
1183 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
1184 gv(rc2);
1189 #ifndef TCC_TARGET_ARM64
1190 /* wrapper around RC_FRET to return a register by type */
1191 static int rc_fret(int t)
1193 #ifdef TCC_TARGET_X86_64
1194 if (t == VT_LDOUBLE) {
1195 return RC_ST0;
1197 #endif
1198 return RC_FRET;
1200 #endif
1202 /* wrapper around REG_FRET to return a register by type */
1203 static int reg_fret(int t)
1205 #ifdef TCC_TARGET_X86_64
1206 if (t == VT_LDOUBLE) {
1207 return TREG_ST0;
1209 #endif
1210 return REG_FRET;
1213 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
1214 /* expand 64bit on stack in two ints */
1215 static void lexpand(void)
1217 int u, v;
1218 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
1219 v = vtop->r & (VT_VALMASK | VT_LVAL);
1220 if (v == VT_CONST) {
1221 vdup();
1222 vtop[0].c.i >>= 32;
1223 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
1224 vdup();
1225 vtop[0].c.i += 4;
1226 } else {
1227 gv(RC_INT);
1228 vdup();
1229 vtop[0].r = vtop[-1].r2;
1230 vtop[0].r2 = vtop[-1].r2 = VT_CONST;
1232 vtop[0].type.t = vtop[-1].type.t = VT_INT | u;
1234 #endif
1236 #ifdef TCC_TARGET_ARM
1237 /* expand long long on stack */
1238 ST_FUNC void lexpand_nr(void)
1240 int u,v;
1242 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
1243 vdup();
1244 vtop->r2 = VT_CONST;
1245 vtop->type.t = VT_INT | u;
1246 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
1247 if (v == VT_CONST) {
1248 vtop[-1].c.i = vtop->c.i;
1249 vtop->c.i = vtop->c.i >> 32;
1250 vtop->r = VT_CONST;
1251 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
1252 vtop->c.i += 4;
1253 vtop->r = vtop[-1].r;
1254 } else if (v > VT_CONST) {
1255 vtop--;
1256 lexpand();
1257 } else
1258 vtop->r = vtop[-1].r2;
1259 vtop[-1].r2 = VT_CONST;
1260 vtop[-1].type.t = VT_INT | u;
1262 #endif
1264 #if !defined(TCC_TARGET_X86_64) && !defined(TCC_TARGET_ARM64)
1265 /* build a long long from two ints */
1266 static void lbuild(int t)
1268 gv2(RC_INT, RC_INT);
1269 vtop[-1].r2 = vtop[0].r;
1270 vtop[-1].type.t = t;
1271 vpop();
1273 #endif
1275 /* rotate n first stack elements to the bottom
1276 I1 ... In -> I2 ... In I1 [top is right]
1278 ST_FUNC void vrotb(int n)
1280 int i;
1281 SValue tmp;
1283 tmp = vtop[-n + 1];
1284 for(i=-n+1;i!=0;i++)
1285 vtop[i] = vtop[i+1];
1286 vtop[0] = tmp;
1289 /* rotate the n elements before entry e towards the top
1290 I1 ... In ... -> In I1 ... I(n-1) ... [top is right]
1292 ST_FUNC void vrote(SValue *e, int n)
1294 int i;
1295 SValue tmp;
1297 tmp = *e;
1298 for(i = 0;i < n - 1; i++)
1299 e[-i] = e[-i - 1];
1300 e[-n + 1] = tmp;
1303 /* rotate n first stack elements to the top
1304 I1 ... In -> In I1 ... I(n-1) [top is right]
1306 ST_FUNC void vrott(int n)
1308 vrote(vtop, n);
1311 /* pop stack value */
1312 ST_FUNC void vpop(void)
1314 int v;
1315 v = vtop->r & VT_VALMASK;
1316 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1317 /* for x86, we need to pop the FP stack */
1318 if (v == TREG_ST0 && !nocode_wanted) {
1319 o(0xd8dd); /* fstp %st(0) */
1320 } else
1321 #endif
1322 if (v == VT_JMP || v == VT_JMPI) {
1323 /* need to put correct jump if && or || without test */
1324 gsym(vtop->c.i);
1326 vtop--;
1329 /* convert stack entry to register and duplicate its value in another
1330 register */
1331 static void gv_dup(void)
1333 int rc, t, r, r1;
1334 SValue sv;
1336 t = vtop->type.t;
1337 #if !defined(TCC_TARGET_X86_64) && !defined(TCC_TARGET_ARM64)
1338 if ((t & VT_BTYPE) == VT_LLONG) {
1339 lexpand();
1340 gv_dup();
1341 vswap();
1342 vrotb(3);
1343 gv_dup();
1344 vrotb(4);
1345 /* stack: H L L1 H1 */
1346 lbuild(t);
1347 vrotb(3);
1348 vrotb(3);
1349 vswap();
1350 lbuild(t);
1351 vswap();
1352 } else
1353 #endif
1355 /* duplicate value */
1356 rc = RC_INT;
1357 sv.type.t = VT_INT;
1358 if (is_float(t)) {
1359 rc = RC_FLOAT;
1360 #ifdef TCC_TARGET_X86_64
1361 if ((t & VT_BTYPE) == VT_LDOUBLE) {
1362 rc = RC_ST0;
1364 #endif
1365 sv.type.t = t;
1367 r = gv(rc);
1368 r1 = get_reg(rc);
1369 sv.r = r;
1370 sv.c.i = 0;
1371 load(r1, &sv); /* move r to r1 */
1372 vdup();
1373 /* duplicates value */
1374 if (r != r1)
1375 vtop->r = r1;
1379 /* Generate value test
1381 * Generate a test for any value (jump, comparison and integers) */
1382 ST_FUNC int gvtst(int inv, int t)
1384 int v = vtop->r & VT_VALMASK;
1385 if (v != VT_CMP && v != VT_JMP && v != VT_JMPI) {
1386 vpushi(0);
1387 gen_op(TOK_NE);
1389 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1390 /* constant jmp optimization */
1391 if ((vtop->c.i != 0) != inv)
1392 t = gjmp(t);
1393 vtop--;
1394 return t;
1396 return gtst(inv, t);
1399 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
1400 /* generate CPU independent (unsigned) long long operations */
1401 static void gen_opl(int op)
1403 int t, a, b, op1, c, i;
1404 int func;
1405 unsigned short reg_iret = REG_IRET;
1406 unsigned short reg_lret = REG_LRET;
1407 SValue tmp;
1409 switch(op) {
1410 case '/':
1411 case TOK_PDIV:
1412 func = TOK___divdi3;
1413 goto gen_func;
1414 case TOK_UDIV:
1415 func = TOK___udivdi3;
1416 goto gen_func;
1417 case '%':
1418 func = TOK___moddi3;
1419 goto gen_mod_func;
1420 case TOK_UMOD:
1421 func = TOK___umoddi3;
1422 gen_mod_func:
1423 #ifdef TCC_ARM_EABI
1424 reg_iret = TREG_R2;
1425 reg_lret = TREG_R3;
1426 #endif
1427 gen_func:
1428 /* call generic long long function */
1429 vpush_global_sym(&func_old_type, func);
1430 vrott(3);
1431 gfunc_call(2);
1432 vpushi(0);
1433 vtop->r = reg_iret;
1434 vtop->r2 = reg_lret;
1435 break;
1436 case '^':
1437 case '&':
1438 case '|':
1439 case '*':
1440 case '+':
1441 case '-':
1442 //pv("gen_opl A",0,2);
1443 t = vtop->type.t;
1444 vswap();
1445 lexpand();
1446 vrotb(3);
1447 lexpand();
1448 /* stack: L1 H1 L2 H2 */
1449 tmp = vtop[0];
1450 vtop[0] = vtop[-3];
1451 vtop[-3] = tmp;
1452 tmp = vtop[-2];
1453 vtop[-2] = vtop[-3];
1454 vtop[-3] = tmp;
1455 vswap();
1456 /* stack: H1 H2 L1 L2 */
1457 //pv("gen_opl B",0,4);
1458 if (op == '*') {
1459 vpushv(vtop - 1);
1460 vpushv(vtop - 1);
1461 gen_op(TOK_UMULL);
1462 lexpand();
1463 /* stack: H1 H2 L1 L2 ML MH */
1464 for(i=0;i<4;i++)
1465 vrotb(6);
1466 /* stack: ML MH H1 H2 L1 L2 */
1467 tmp = vtop[0];
1468 vtop[0] = vtop[-2];
1469 vtop[-2] = tmp;
1470 /* stack: ML MH H1 L2 H2 L1 */
1471 gen_op('*');
1472 vrotb(3);
1473 vrotb(3);
1474 gen_op('*');
1475 /* stack: ML MH M1 M2 */
1476 gen_op('+');
1477 gen_op('+');
1478 } else if (op == '+' || op == '-') {
1479 /* XXX: add non carry method too (for MIPS or alpha) */
1480 if (op == '+')
1481 op1 = TOK_ADDC1;
1482 else
1483 op1 = TOK_SUBC1;
1484 gen_op(op1);
1485 /* stack: H1 H2 (L1 op L2) */
1486 vrotb(3);
1487 vrotb(3);
1488 gen_op(op1 + 1); /* TOK_xxxC2 */
1489 } else {
1490 gen_op(op);
1491 /* stack: H1 H2 (L1 op L2) */
1492 vrotb(3);
1493 vrotb(3);
1494 /* stack: (L1 op L2) H1 H2 */
1495 gen_op(op);
1496 /* stack: (L1 op L2) (H1 op H2) */
1498 /* stack: L H */
1499 lbuild(t);
1500 break;
1501 case TOK_SAR:
1502 case TOK_SHR:
1503 case TOK_SHL:
1504 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1505 t = vtop[-1].type.t;
1506 vswap();
1507 lexpand();
1508 vrotb(3);
1509 /* stack: L H shift */
1510 c = (int)vtop->c.i;
1511 /* constant: simpler */
1512 /* NOTE: all comments are for SHL. the other cases are
1513 done by swaping words */
1514 vpop();
1515 if (op != TOK_SHL)
1516 vswap();
1517 if (c >= 32) {
1518 /* stack: L H */
1519 vpop();
1520 if (c > 32) {
1521 vpushi(c - 32);
1522 gen_op(op);
1524 if (op != TOK_SAR) {
1525 vpushi(0);
1526 } else {
1527 gv_dup();
1528 vpushi(31);
1529 gen_op(TOK_SAR);
1531 vswap();
1532 } else {
1533 vswap();
1534 gv_dup();
1535 /* stack: H L L */
1536 vpushi(c);
1537 gen_op(op);
1538 vswap();
1539 vpushi(32 - c);
1540 if (op == TOK_SHL)
1541 gen_op(TOK_SHR);
1542 else
1543 gen_op(TOK_SHL);
1544 vrotb(3);
1545 /* stack: L L H */
1546 vpushi(c);
1547 if (op == TOK_SHL)
1548 gen_op(TOK_SHL);
1549 else
1550 gen_op(TOK_SHR);
1551 gen_op('|');
1553 if (op != TOK_SHL)
1554 vswap();
1555 lbuild(t);
1556 } else {
1557 /* XXX: should provide a faster fallback on x86 ? */
1558 switch(op) {
1559 case TOK_SAR:
1560 func = TOK___ashrdi3;
1561 goto gen_func;
1562 case TOK_SHR:
1563 func = TOK___lshrdi3;
1564 goto gen_func;
1565 case TOK_SHL:
1566 func = TOK___ashldi3;
1567 goto gen_func;
1570 break;
1571 default:
1572 /* compare operations */
1573 t = vtop->type.t;
1574 vswap();
1575 lexpand();
1576 vrotb(3);
1577 lexpand();
1578 /* stack: L1 H1 L2 H2 */
1579 tmp = vtop[-1];
1580 vtop[-1] = vtop[-2];
1581 vtop[-2] = tmp;
1582 /* stack: L1 L2 H1 H2 */
1583 /* compare high */
1584 op1 = op;
1585 /* when values are equal, we need to compare low words. since
1586 the jump is inverted, we invert the test too. */
1587 if (op1 == TOK_LT)
1588 op1 = TOK_LE;
1589 else if (op1 == TOK_GT)
1590 op1 = TOK_GE;
1591 else if (op1 == TOK_ULT)
1592 op1 = TOK_ULE;
1593 else if (op1 == TOK_UGT)
1594 op1 = TOK_UGE;
1595 a = 0;
1596 b = 0;
1597 gen_op(op1);
1598 if (op1 != TOK_NE) {
1599 a = gvtst(1, 0);
1601 if (op != TOK_EQ) {
1602 /* generate non equal test */
1603 /* XXX: NOT PORTABLE yet */
1604 if (a == 0) {
1605 b = gvtst(0, 0);
1606 } else {
1607 #if defined(TCC_TARGET_I386)
1608 b = psym(0x850f, 0);
1609 #elif defined(TCC_TARGET_ARM)
1610 b = ind;
1611 o(0x1A000000 | encbranch(ind, 0, 1));
1612 #elif defined(TCC_TARGET_C67) || defined(TCC_TARGET_ARM64)
1613 tcc_error("not implemented");
1614 #else
1615 #error not supported
1616 #endif
1619 /* compare low. Always unsigned */
1620 op1 = op;
1621 if (op1 == TOK_LT)
1622 op1 = TOK_ULT;
1623 else if (op1 == TOK_LE)
1624 op1 = TOK_ULE;
1625 else if (op1 == TOK_GT)
1626 op1 = TOK_UGT;
1627 else if (op1 == TOK_GE)
1628 op1 = TOK_UGE;
1629 gen_op(op1);
1630 a = gvtst(1, a);
1631 gsym(b);
1632 vseti(VT_JMPI, a);
1633 break;
1636 #endif
1638 static uint64_t gen_opic_sdiv(uint64_t a, uint64_t b)
1640 uint64_t x = (a >> 63 ? -a : a) / (b >> 63 ? -b : b);
1641 return (a ^ b) >> 63 ? -x : x;
1644 static int gen_opic_lt(uint64_t a, uint64_t b)
1646 return (a ^ (uint64_t)1 << 63) < (b ^ (uint64_t)1 << 63);
1649 /* handle integer constant optimizations and various machine
1650 independent opt */
1651 static void gen_opic(int op)
1653 SValue *v1 = vtop - 1;
1654 SValue *v2 = vtop;
1655 int t1 = v1->type.t & VT_BTYPE;
1656 int t2 = v2->type.t & VT_BTYPE;
1657 int c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1658 int c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1659 uint64_t l1 = c1 ? v1->c.i : 0;
1660 uint64_t l2 = c2 ? v2->c.i : 0;
1661 int shm = (t1 == VT_LLONG) ? 63 : 31;
1663 if (t1 != VT_LLONG && (PTR_SIZE != 8 || t1 != VT_PTR))
1664 l1 = ((uint32_t)l1 |
1665 (v1->type.t & VT_UNSIGNED ? 0 : -(l1 & 0x80000000)));
1666 if (t2 != VT_LLONG && (PTR_SIZE != 8 || t2 != VT_PTR))
1667 l2 = ((uint32_t)l2 |
1668 (v2->type.t & VT_UNSIGNED ? 0 : -(l2 & 0x80000000)));
1670 if (c1 && c2) {
1671 switch(op) {
1672 case '+': l1 += l2; break;
1673 case '-': l1 -= l2; break;
1674 case '&': l1 &= l2; break;
1675 case '^': l1 ^= l2; break;
1676 case '|': l1 |= l2; break;
1677 case '*': l1 *= l2; break;
1679 case TOK_PDIV:
1680 case '/':
1681 case '%':
1682 case TOK_UDIV:
1683 case TOK_UMOD:
1684 /* if division by zero, generate explicit division */
1685 if (l2 == 0) {
1686 if (const_wanted)
1687 tcc_error("division by zero in constant");
1688 goto general_case;
1690 switch(op) {
1691 default: l1 = gen_opic_sdiv(l1, l2); break;
1692 case '%': l1 = l1 - l2 * gen_opic_sdiv(l1, l2); break;
1693 case TOK_UDIV: l1 = l1 / l2; break;
1694 case TOK_UMOD: l1 = l1 % l2; break;
1696 break;
1697 case TOK_SHL: l1 <<= (l2 & shm); break;
1698 case TOK_SHR: l1 >>= (l2 & shm); break;
1699 case TOK_SAR:
1700 l1 = (l1 >> 63) ? ~(~l1 >> (l2 & shm)) : l1 >> (l2 & shm);
1701 break;
1702 /* tests */
1703 case TOK_ULT: l1 = l1 < l2; break;
1704 case TOK_UGE: l1 = l1 >= l2; break;
1705 case TOK_EQ: l1 = l1 == l2; break;
1706 case TOK_NE: l1 = l1 != l2; break;
1707 case TOK_ULE: l1 = l1 <= l2; break;
1708 case TOK_UGT: l1 = l1 > l2; break;
1709 case TOK_LT: l1 = gen_opic_lt(l1, l2); break;
1710 case TOK_GE: l1 = !gen_opic_lt(l1, l2); break;
1711 case TOK_LE: l1 = !gen_opic_lt(l2, l1); break;
1712 case TOK_GT: l1 = gen_opic_lt(l2, l1); break;
1713 /* logical */
1714 case TOK_LAND: l1 = l1 && l2; break;
1715 case TOK_LOR: l1 = l1 || l2; break;
1716 default:
1717 goto general_case;
1719 v1->c.i = l1;
1720 vtop--;
1721 } else {
1722 /* if commutative ops, put c2 as constant */
1723 if (c1 && (op == '+' || op == '&' || op == '^' ||
1724 op == '|' || op == '*')) {
1725 vswap();
1726 c2 = c1; //c = c1, c1 = c2, c2 = c;
1727 l2 = l1; //l = l1, l1 = l2, l2 = l;
1729 if (!const_wanted &&
1730 c1 && ((l1 == 0 &&
1731 (op == TOK_SHL || op == TOK_SHR || op == TOK_SAR)) ||
1732 (l1 == -1 && op == TOK_SAR))) {
1733 /* treat (0 << x), (0 >> x) and (-1 >> x) as constant */
1734 vtop--;
1735 } else if (!const_wanted &&
1736 c2 && ((l2 == 0 && (op == '&' || op == '*')) ||
1737 (l2 == -1 && op == '|') ||
1738 (l2 == 0xffffffff && t2 != VT_LLONG && op == '|') ||
1739 (l2 == 1 && (op == '%' || op == TOK_UMOD)))) {
1740 /* treat (x & 0), (x * 0), (x | -1) and (x % 1) as constant */
1741 if (l2 == 1)
1742 vtop->c.i = 0;
1743 vswap();
1744 vtop--;
1745 } else if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
1746 op == TOK_PDIV) &&
1747 l2 == 1) ||
1748 ((op == '+' || op == '-' || op == '|' || op == '^' ||
1749 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
1750 l2 == 0) ||
1751 (op == '&' &&
1752 l2 == -1))) {
1753 /* filter out NOP operations like x*1, x-0, x&-1... */
1754 vtop--;
1755 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
1756 /* try to use shifts instead of muls or divs */
1757 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
1758 int n = -1;
1759 while (l2) {
1760 l2 >>= 1;
1761 n++;
1763 vtop->c.i = n;
1764 if (op == '*')
1765 op = TOK_SHL;
1766 else if (op == TOK_PDIV)
1767 op = TOK_SAR;
1768 else
1769 op = TOK_SHR;
1771 goto general_case;
1772 } else if (c2 && (op == '+' || op == '-') &&
1773 (((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM))
1774 || (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
1775 /* symbol + constant case */
1776 if (op == '-')
1777 l2 = -l2;
1778 vtop--;
1779 vtop->c.i += l2;
1780 } else {
1781 general_case:
1782 if (!nocode_wanted) {
1783 /* call low level op generator */
1784 if (t1 == VT_LLONG || t2 == VT_LLONG ||
1785 (PTR_SIZE == 8 && (t1 == VT_PTR || t2 == VT_PTR)))
1786 gen_opl(op);
1787 else
1788 gen_opi(op);
1789 } else {
1790 vtop--;
1791 /* Ensure vtop isn't marked VT_CONST in case something
1792 up our callchain is interested in const-ness of the
1793 expression. Also make it a non-LVAL if it was,
1794 so that further code can't accidentally generate
1795 a deref (happen only for buggy uses of e.g.
1796 gv() under nocode_wanted). */
1797 vtop->r &= ~(VT_VALMASK | VT_LVAL);
1803 /* generate a floating point operation with constant propagation */
1804 static void gen_opif(int op)
1806 int c1, c2;
1807 SValue *v1, *v2;
1808 long double f1, f2;
1810 v1 = vtop - 1;
1811 v2 = vtop;
1812 /* currently, we cannot do computations with forward symbols */
1813 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1814 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1815 if (c1 && c2) {
1816 if (v1->type.t == VT_FLOAT) {
1817 f1 = v1->c.f;
1818 f2 = v2->c.f;
1819 } else if (v1->type.t == VT_DOUBLE) {
1820 f1 = v1->c.d;
1821 f2 = v2->c.d;
1822 } else {
1823 f1 = v1->c.ld;
1824 f2 = v2->c.ld;
1827 /* NOTE: we only do constant propagation if finite number (not
1828 NaN or infinity) (ANSI spec) */
1829 if (!ieee_finite(f1) || !ieee_finite(f2))
1830 goto general_case;
1832 switch(op) {
1833 case '+': f1 += f2; break;
1834 case '-': f1 -= f2; break;
1835 case '*': f1 *= f2; break;
1836 case '/':
1837 if (f2 == 0.0) {
1838 if (const_wanted)
1839 tcc_error("division by zero in constant");
1840 goto general_case;
1842 f1 /= f2;
1843 break;
1844 /* XXX: also handles tests ? */
1845 default:
1846 goto general_case;
1848 /* XXX: overflow test ? */
1849 if (v1->type.t == VT_FLOAT) {
1850 v1->c.f = f1;
1851 } else if (v1->type.t == VT_DOUBLE) {
1852 v1->c.d = f1;
1853 } else {
1854 v1->c.ld = f1;
1856 vtop--;
1857 } else {
1858 general_case:
1859 if (!nocode_wanted) {
1860 gen_opf(op);
1861 } else {
1862 vtop--;
1867 static int pointed_size(CType *type)
1869 int align;
1870 return type_size(pointed_type(type), &align);
1873 static void vla_runtime_pointed_size(CType *type)
1875 int align;
1876 vla_runtime_type_size(pointed_type(type), &align);
1879 static inline int is_null_pointer(SValue *p)
1881 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
1882 return 0;
1883 return ((p->type.t & VT_BTYPE) == VT_INT && (uint32_t)p->c.i == 0) ||
1884 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.i == 0) ||
1885 ((p->type.t & VT_BTYPE) == VT_PTR &&
1886 (PTR_SIZE == 4 ? (uint32_t)p->c.i == 0 : p->c.i == 0));
1889 static inline int is_integer_btype(int bt)
1891 return (bt == VT_BYTE || bt == VT_SHORT ||
1892 bt == VT_INT || bt == VT_LLONG);
1895 /* check types for comparison or subtraction of pointers */
1896 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
1898 CType *type1, *type2, tmp_type1, tmp_type2;
1899 int bt1, bt2;
1901 /* null pointers are accepted for all comparisons as gcc */
1902 if (is_null_pointer(p1) || is_null_pointer(p2))
1903 return;
1904 type1 = &p1->type;
1905 type2 = &p2->type;
1906 bt1 = type1->t & VT_BTYPE;
1907 bt2 = type2->t & VT_BTYPE;
1908 /* accept comparison between pointer and integer with a warning */
1909 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
1910 if (op != TOK_LOR && op != TOK_LAND )
1911 tcc_warning("comparison between pointer and integer");
1912 return;
1915 /* both must be pointers or implicit function pointers */
1916 if (bt1 == VT_PTR) {
1917 type1 = pointed_type(type1);
1918 } else if (bt1 != VT_FUNC)
1919 goto invalid_operands;
1921 if (bt2 == VT_PTR) {
1922 type2 = pointed_type(type2);
1923 } else if (bt2 != VT_FUNC) {
1924 invalid_operands:
1925 tcc_error("invalid operands to binary %s", get_tok_str(op, NULL));
1927 if ((type1->t & VT_BTYPE) == VT_VOID ||
1928 (type2->t & VT_BTYPE) == VT_VOID)
1929 return;
1930 tmp_type1 = *type1;
1931 tmp_type2 = *type2;
1932 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1933 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1934 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
1935 /* gcc-like error if '-' is used */
1936 if (op == '-')
1937 goto invalid_operands;
1938 else
1939 tcc_warning("comparison of distinct pointer types lacks a cast");
1943 /* generic gen_op: handles types problems */
1944 ST_FUNC void gen_op(int op)
1946 int u, t1, t2, bt1, bt2, t;
1947 CType type1;
1949 redo:
1950 t1 = vtop[-1].type.t;
1951 t2 = vtop[0].type.t;
1952 bt1 = t1 & VT_BTYPE;
1953 bt2 = t2 & VT_BTYPE;
1955 if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
1956 tcc_error("operation on a struct");
1957 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
1958 if (bt2 == VT_FUNC) {
1959 mk_pointer(&vtop->type);
1960 gaddrof();
1962 if (bt1 == VT_FUNC) {
1963 vswap();
1964 mk_pointer(&vtop->type);
1965 gaddrof();
1966 vswap();
1968 goto redo;
1969 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
1970 /* at least one operand is a pointer */
1971 /* relationnal op: must be both pointers */
1972 if (op >= TOK_ULT && op <= TOK_LOR) {
1973 check_comparison_pointer_types(vtop - 1, vtop, op);
1974 /* pointers are handled are unsigned */
1975 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1976 t = VT_LLONG | VT_UNSIGNED;
1977 #else
1978 t = VT_INT | VT_UNSIGNED;
1979 #endif
1980 goto std_op;
1982 /* if both pointers, then it must be the '-' op */
1983 if (bt1 == VT_PTR && bt2 == VT_PTR) {
1984 if (op != '-')
1985 tcc_error("cannot use pointers here");
1986 check_comparison_pointer_types(vtop - 1, vtop, op);
1987 /* XXX: check that types are compatible */
1988 if (vtop[-1].type.t & VT_VLA) {
1989 vla_runtime_pointed_size(&vtop[-1].type);
1990 } else {
1991 vpushi(pointed_size(&vtop[-1].type));
1993 vrott(3);
1994 gen_opic(op);
1995 /* set to integer type */
1996 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1997 vtop->type.t = VT_LLONG;
1998 #else
1999 vtop->type.t = VT_INT;
2000 #endif
2001 vswap();
2002 gen_op(TOK_PDIV);
2003 } else {
2004 /* exactly one pointer : must be '+' or '-'. */
2005 if (op != '-' && op != '+')
2006 tcc_error("cannot use pointers here");
2007 /* Put pointer as first operand */
2008 if (bt2 == VT_PTR) {
2009 vswap();
2010 swap(&t1, &t2);
2012 #if PTR_SIZE == 4
2013 if ((vtop[0].type.t & VT_BTYPE) == VT_LLONG)
2014 /* XXX: truncate here because gen_opl can't handle ptr + long long */
2015 gen_cast(&int_type);
2016 #endif
2017 type1 = vtop[-1].type;
2018 type1.t &= ~VT_ARRAY;
2019 if (vtop[-1].type.t & VT_VLA)
2020 vla_runtime_pointed_size(&vtop[-1].type);
2021 else {
2022 u = pointed_size(&vtop[-1].type);
2023 if (u < 0)
2024 tcc_error("unknown array element size");
2025 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2026 vpushll(u);
2027 #else
2028 /* XXX: cast to int ? (long long case) */
2029 vpushi(u);
2030 #endif
2032 gen_op('*');
2033 #if 0
2034 /* #ifdef CONFIG_TCC_BCHECK
2035 The main reason to removing this code:
2036 #include <stdio.h>
2037 int main ()
2039 int v[10];
2040 int i = 10;
2041 int j = 9;
2042 fprintf(stderr, "v+i-j = %p\n", v+i-j);
2043 fprintf(stderr, "v+(i-j) = %p\n", v+(i-j));
2045 When this code is on. then the output looks like
2046 v+i-j = 0xfffffffe
2047 v+(i-j) = 0xbff84000
2049 /* if evaluating constant expression, no code should be
2050 generated, so no bound check */
2051 if (tcc_state->do_bounds_check && !const_wanted) {
2052 /* if bounded pointers, we generate a special code to
2053 test bounds */
2054 if (op == '-') {
2055 vpushi(0);
2056 vswap();
2057 gen_op('-');
2059 gen_bounded_ptr_add();
2060 } else
2061 #endif
2063 gen_opic(op);
2065 /* put again type if gen_opic() swaped operands */
2066 vtop->type = type1;
2068 } else if (is_float(bt1) || is_float(bt2)) {
2069 /* compute bigger type and do implicit casts */
2070 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
2071 t = VT_LDOUBLE;
2072 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
2073 t = VT_DOUBLE;
2074 } else {
2075 t = VT_FLOAT;
2077 /* floats can only be used for a few operations */
2078 if (op != '+' && op != '-' && op != '*' && op != '/' &&
2079 (op < TOK_ULT || op > TOK_GT))
2080 tcc_error("invalid operands for binary operation");
2081 goto std_op;
2082 } else if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL) {
2083 t = bt1 == VT_LLONG ? VT_LLONG : VT_INT;
2084 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (t | VT_UNSIGNED))
2085 t |= VT_UNSIGNED;
2086 goto std_op;
2087 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
2088 /* cast to biggest op */
2089 t = VT_LLONG;
2090 /* convert to unsigned if it does not fit in a long long */
2091 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
2092 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
2093 t |= VT_UNSIGNED;
2094 goto std_op;
2095 } else {
2096 /* integer operations */
2097 t = VT_INT;
2098 /* convert to unsigned if it does not fit in an integer */
2099 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
2100 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
2101 t |= VT_UNSIGNED;
2102 std_op:
2103 /* XXX: currently, some unsigned operations are explicit, so
2104 we modify them here */
2105 if (t & VT_UNSIGNED) {
2106 if (op == TOK_SAR)
2107 op = TOK_SHR;
2108 else if (op == '/')
2109 op = TOK_UDIV;
2110 else if (op == '%')
2111 op = TOK_UMOD;
2112 else if (op == TOK_LT)
2113 op = TOK_ULT;
2114 else if (op == TOK_GT)
2115 op = TOK_UGT;
2116 else if (op == TOK_LE)
2117 op = TOK_ULE;
2118 else if (op == TOK_GE)
2119 op = TOK_UGE;
2121 vswap();
2122 type1.t = t;
2123 gen_cast(&type1);
2124 vswap();
2125 /* special case for shifts and long long: we keep the shift as
2126 an integer */
2127 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
2128 type1.t = VT_INT;
2129 gen_cast(&type1);
2130 if (is_float(t))
2131 gen_opif(op);
2132 else
2133 gen_opic(op);
2134 if (op >= TOK_ULT && op <= TOK_GT) {
2135 /* relationnal op: the result is an int */
2136 vtop->type.t = VT_INT;
2137 } else {
2138 vtop->type.t = t;
2141 // Make sure that we have converted to an rvalue:
2142 if (vtop->r & VT_LVAL && !nocode_wanted)
2143 gv(is_float(vtop->type.t & VT_BTYPE) ? RC_FLOAT : RC_INT);
2146 #ifndef TCC_TARGET_ARM
2147 /* generic itof for unsigned long long case */
2148 static void gen_cvt_itof1(int t)
2150 #ifdef TCC_TARGET_ARM64
2151 gen_cvt_itof(t);
2152 #else
2153 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
2154 (VT_LLONG | VT_UNSIGNED)) {
2156 if (t == VT_FLOAT)
2157 vpush_global_sym(&func_old_type, TOK___floatundisf);
2158 #if LDOUBLE_SIZE != 8
2159 else if (t == VT_LDOUBLE)
2160 vpush_global_sym(&func_old_type, TOK___floatundixf);
2161 #endif
2162 else
2163 vpush_global_sym(&func_old_type, TOK___floatundidf);
2164 vrott(2);
2165 gfunc_call(1);
2166 vpushi(0);
2167 vtop->r = reg_fret(t);
2168 } else {
2169 gen_cvt_itof(t);
2171 #endif
2173 #endif
2175 /* generic ftoi for unsigned long long case */
2176 static void gen_cvt_ftoi1(int t)
2178 #ifdef TCC_TARGET_ARM64
2179 gen_cvt_ftoi(t);
2180 #else
2181 int st;
2183 if (t == (VT_LLONG | VT_UNSIGNED)) {
2184 /* not handled natively */
2185 st = vtop->type.t & VT_BTYPE;
2186 if (st == VT_FLOAT)
2187 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
2188 #if LDOUBLE_SIZE != 8
2189 else if (st == VT_LDOUBLE)
2190 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
2191 #endif
2192 else
2193 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
2194 vrott(2);
2195 gfunc_call(1);
2196 vpushi(0);
2197 vtop->r = REG_IRET;
2198 vtop->r2 = REG_LRET;
2199 } else {
2200 gen_cvt_ftoi(t);
2202 #endif
2205 /* force char or short cast */
2206 static void force_charshort_cast(int t)
2208 int bits, dbt;
2209 dbt = t & VT_BTYPE;
2210 /* XXX: add optimization if lvalue : just change type and offset */
2211 if (dbt == VT_BYTE)
2212 bits = 8;
2213 else
2214 bits = 16;
2215 if (t & VT_UNSIGNED) {
2216 vpushi((1 << bits) - 1);
2217 gen_op('&');
2218 } else {
2219 if ((vtop->type.t & VT_BTYPE) == VT_LLONG)
2220 bits = 64 - bits;
2221 else
2222 bits = 32 - bits;
2223 vpushi(bits);
2224 gen_op(TOK_SHL);
2225 /* result must be signed or the SAR is converted to an SHL
2226 This was not the case when "t" was a signed short
2227 and the last value on the stack was an unsigned int */
2228 vtop->type.t &= ~VT_UNSIGNED;
2229 vpushi(bits);
2230 gen_op(TOK_SAR);
2234 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
2235 static void gen_cast(CType *type)
2237 int sbt, dbt, sf, df, c, p;
2239 /* special delayed cast for char/short */
2240 /* XXX: in some cases (multiple cascaded casts), it may still
2241 be incorrect */
2242 if (vtop->r & VT_MUSTCAST) {
2243 vtop->r &= ~VT_MUSTCAST;
2244 force_charshort_cast(vtop->type.t);
2247 /* bitfields first get cast to ints */
2248 if (vtop->type.t & VT_BITFIELD && !nocode_wanted) {
2249 gv(RC_INT);
2252 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
2253 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
2255 if (sbt != dbt) {
2256 sf = is_float(sbt);
2257 df = is_float(dbt);
2258 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
2259 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
2260 if (c) {
2261 /* constant case: we can do it now */
2262 /* XXX: in ISOC, cannot do it if error in convert */
2263 if (sbt == VT_FLOAT)
2264 vtop->c.ld = vtop->c.f;
2265 else if (sbt == VT_DOUBLE)
2266 vtop->c.ld = vtop->c.d;
2268 if (df) {
2269 if ((sbt & VT_BTYPE) == VT_LLONG) {
2270 if ((sbt & VT_UNSIGNED) || !(vtop->c.i >> 63))
2271 vtop->c.ld = vtop->c.i;
2272 else
2273 vtop->c.ld = -(long double)-vtop->c.i;
2274 } else if(!sf) {
2275 if ((sbt & VT_UNSIGNED) || !(vtop->c.i >> 31))
2276 vtop->c.ld = (uint32_t)vtop->c.i;
2277 else
2278 vtop->c.ld = -(long double)-(uint32_t)vtop->c.i;
2281 if (dbt == VT_FLOAT)
2282 vtop->c.f = (float)vtop->c.ld;
2283 else if (dbt == VT_DOUBLE)
2284 vtop->c.d = (double)vtop->c.ld;
2285 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
2286 vtop->c.i = vtop->c.ld;
2287 } else if (sf && dbt == VT_BOOL) {
2288 vtop->c.i = (vtop->c.ld != 0);
2289 } else {
2290 if(sf)
2291 vtop->c.i = vtop->c.ld;
2292 else if (sbt == (VT_LLONG|VT_UNSIGNED))
2294 else if (sbt & VT_UNSIGNED)
2295 vtop->c.i = (uint32_t)vtop->c.i;
2296 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2297 else if (sbt == VT_PTR)
2299 #endif
2300 else if (sbt != VT_LLONG)
2301 vtop->c.i = ((uint32_t)vtop->c.i |
2302 -(vtop->c.i & 0x80000000));
2304 if (dbt == (VT_LLONG|VT_UNSIGNED))
2306 else if (dbt == VT_BOOL)
2307 vtop->c.i = (vtop->c.i != 0);
2308 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2309 else if (dbt == VT_PTR)
2311 #endif
2312 else if (dbt != VT_LLONG) {
2313 uint32_t m = ((dbt & VT_BTYPE) == VT_BYTE ? 0xff :
2314 (dbt & VT_BTYPE) == VT_SHORT ? 0xffff :
2315 0xffffffff);
2316 vtop->c.i &= m;
2317 if (!(dbt & VT_UNSIGNED))
2318 vtop->c.i |= -(vtop->c.i & ((m >> 1) + 1));
2321 } else if (p && dbt == VT_BOOL) {
2322 vtop->r = VT_CONST;
2323 vtop->c.i = 1;
2324 } else if (!nocode_wanted) {
2325 /* non constant case: generate code */
2326 if (sf && df) {
2327 /* convert from fp to fp */
2328 gen_cvt_ftof(dbt);
2329 } else if (df) {
2330 /* convert int to fp */
2331 gen_cvt_itof1(dbt);
2332 } else if (sf) {
2333 /* convert fp to int */
2334 if (dbt == VT_BOOL) {
2335 vpushi(0);
2336 gen_op(TOK_NE);
2337 } else {
2338 /* we handle char/short/etc... with generic code */
2339 if (dbt != (VT_INT | VT_UNSIGNED) &&
2340 dbt != (VT_LLONG | VT_UNSIGNED) &&
2341 dbt != VT_LLONG)
2342 dbt = VT_INT;
2343 gen_cvt_ftoi1(dbt);
2344 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
2345 /* additional cast for char/short... */
2346 vtop->type.t = dbt;
2347 gen_cast(type);
2350 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
2351 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
2352 if ((sbt & VT_BTYPE) != VT_LLONG) {
2353 /* scalar to long long */
2354 /* machine independent conversion */
2355 gv(RC_INT);
2356 /* generate high word */
2357 if (sbt == (VT_INT | VT_UNSIGNED)) {
2358 vpushi(0);
2359 gv(RC_INT);
2360 } else {
2361 if (sbt == VT_PTR) {
2362 /* cast from pointer to int before we apply
2363 shift operation, which pointers don't support*/
2364 gen_cast(&int_type);
2366 gv_dup();
2367 vpushi(31);
2368 gen_op(TOK_SAR);
2370 /* patch second register */
2371 vtop[-1].r2 = vtop->r;
2372 vpop();
2374 #else
2375 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
2376 (dbt & VT_BTYPE) == VT_PTR ||
2377 (dbt & VT_BTYPE) == VT_FUNC) {
2378 if ((sbt & VT_BTYPE) != VT_LLONG &&
2379 (sbt & VT_BTYPE) != VT_PTR &&
2380 (sbt & VT_BTYPE) != VT_FUNC) {
2381 /* need to convert from 32bit to 64bit */
2382 gv(RC_INT);
2383 if (sbt != (VT_INT | VT_UNSIGNED)) {
2384 #if defined(TCC_TARGET_ARM64)
2385 gen_cvt_sxtw();
2386 #elif defined(TCC_TARGET_X86_64)
2387 int r = gv(RC_INT);
2388 /* x86_64 specific: movslq */
2389 o(0x6348);
2390 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
2391 #else
2392 #error
2393 #endif
2396 #endif
2397 } else if (dbt == VT_BOOL) {
2398 /* scalar to bool */
2399 vpushi(0);
2400 gen_op(TOK_NE);
2401 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
2402 (dbt & VT_BTYPE) == VT_SHORT) {
2403 if (sbt == VT_PTR) {
2404 vtop->type.t = VT_INT;
2405 tcc_warning("nonportable conversion from pointer to char/short");
2407 force_charshort_cast(dbt);
2408 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
2409 } else if ((dbt & VT_BTYPE) == VT_INT) {
2410 /* scalar to int */
2411 if ((sbt & VT_BTYPE) == VT_LLONG) {
2412 /* from long long: just take low order word */
2413 lexpand();
2414 vpop();
2416 /* if lvalue and single word type, nothing to do because
2417 the lvalue already contains the real type size (see
2418 VT_LVAL_xxx constants) */
2419 #endif
2422 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
2423 /* if we are casting between pointer types,
2424 we must update the VT_LVAL_xxx size */
2425 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
2426 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
2428 vtop->type = *type;
2431 /* return type size as known at compile time. Put alignment at 'a' */
2432 ST_FUNC int type_size(CType *type, int *a)
2434 Sym *s;
2435 int bt;
2437 bt = type->t & VT_BTYPE;
2438 if (bt == VT_STRUCT) {
2439 /* struct/union */
2440 s = type->ref;
2441 *a = s->r;
2442 return s->c;
2443 } else if (bt == VT_PTR) {
2444 if (type->t & VT_ARRAY) {
2445 int ts;
2447 s = type->ref;
2448 ts = type_size(&s->type, a);
2450 if (ts < 0 && s->c < 0)
2451 ts = -ts;
2453 return ts * s->c;
2454 } else {
2455 *a = PTR_SIZE;
2456 return PTR_SIZE;
2458 } else if (bt == VT_LDOUBLE) {
2459 *a = LDOUBLE_ALIGN;
2460 return LDOUBLE_SIZE;
2461 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
2462 #ifdef TCC_TARGET_I386
2463 #ifdef TCC_TARGET_PE
2464 *a = 8;
2465 #else
2466 *a = 4;
2467 #endif
2468 #elif defined(TCC_TARGET_ARM)
2469 #ifdef TCC_ARM_EABI
2470 *a = 8;
2471 #else
2472 *a = 4;
2473 #endif
2474 #else
2475 *a = 8;
2476 #endif
2477 return 8;
2478 } else if (bt == VT_INT || bt == VT_FLOAT) {
2479 *a = 4;
2480 return 4;
2481 } else if (bt == VT_SHORT) {
2482 *a = 2;
2483 return 2;
2484 } else if (bt == VT_QLONG || bt == VT_QFLOAT) {
2485 *a = 8;
2486 return 16;
2487 } else if (bt == VT_ENUM) {
2488 *a = 4;
2489 /* Enums might be incomplete, so don't just return '4' here. */
2490 return type->ref->c;
2491 } else {
2492 /* char, void, function, _Bool */
2493 *a = 1;
2494 return 1;
2498 /* push type size as known at runtime time on top of value stack. Put
2499 alignment at 'a' */
2500 ST_FUNC void vla_runtime_type_size(CType *type, int *a)
2502 if (type->t & VT_VLA) {
2503 type_size(&type->ref->type, a);
2504 vset(&int_type, VT_LOCAL|VT_LVAL, type->ref->c);
2505 } else {
2506 vpushi(type_size(type, a));
2510 static void vla_sp_restore(void) {
2511 if (vlas_in_scope) {
2512 gen_vla_sp_restore(vla_sp_loc);
2516 static void vla_sp_restore_root(void) {
2517 if (vlas_in_scope) {
2518 gen_vla_sp_restore(vla_sp_root_loc);
2522 /* return the pointed type of t */
2523 static inline CType *pointed_type(CType *type)
2525 return &type->ref->type;
2528 /* modify type so that its it is a pointer to type. */
2529 ST_FUNC void mk_pointer(CType *type)
2531 Sym *s;
2532 s = sym_push(SYM_FIELD, type, 0, -1);
2533 type->t = VT_PTR | (type->t & ~VT_TYPE);
2534 type->ref = s;
2537 /* compare function types. OLD functions match any new functions */
2538 static int is_compatible_func(CType *type1, CType *type2)
2540 Sym *s1, *s2;
2542 s1 = type1->ref;
2543 s2 = type2->ref;
2544 if (!is_compatible_types(&s1->type, &s2->type))
2545 return 0;
2546 /* check func_call */
2547 if (s1->a.func_call != s2->a.func_call)
2548 return 0;
2549 /* XXX: not complete */
2550 if (s1->c == FUNC_OLD || s2->c == FUNC_OLD)
2551 return 1;
2552 if (s1->c != s2->c)
2553 return 0;
2554 while (s1 != NULL) {
2555 if (s2 == NULL)
2556 return 0;
2557 if (!is_compatible_parameter_types(&s1->type, &s2->type))
2558 return 0;
2559 s1 = s1->next;
2560 s2 = s2->next;
2562 if (s2)
2563 return 0;
2564 return 1;
2567 /* return true if type1 and type2 are the same. If unqualified is
2568 true, qualifiers on the types are ignored.
2570 - enums are not checked as gcc __builtin_types_compatible_p ()
2572 static int compare_types(CType *type1, CType *type2, int unqualified)
2574 int bt1, t1, t2;
2576 t1 = type1->t & VT_TYPE;
2577 t2 = type2->t & VT_TYPE;
2578 if (unqualified) {
2579 /* strip qualifiers before comparing */
2580 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
2581 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
2583 /* Default Vs explicit signedness only matters for char */
2584 if ((t1 & VT_BTYPE) != VT_BYTE) {
2585 t1 &= ~VT_DEFSIGN;
2586 t2 &= ~VT_DEFSIGN;
2588 /* An enum is compatible with (unsigned) int. Ideally we would
2589 store the enums signedness in type->ref.a.<some_bit> and
2590 only accept unsigned enums with unsigned int and vice versa.
2591 But one of our callers (gen_assign_cast) always strips VT_UNSIGNED
2592 from pointer target types, so we can't add it here either. */
2593 if ((t1 & VT_BTYPE) == VT_ENUM) {
2594 t1 = VT_INT;
2595 if (type1->ref->a.unsigned_enum)
2596 t1 |= VT_UNSIGNED;
2598 if ((t2 & VT_BTYPE) == VT_ENUM) {
2599 t2 = VT_INT;
2600 if (type2->ref->a.unsigned_enum)
2601 t2 |= VT_UNSIGNED;
2603 /* XXX: bitfields ? */
2604 if (t1 != t2)
2605 return 0;
2606 /* test more complicated cases */
2607 bt1 = t1 & VT_BTYPE;
2608 if (bt1 == VT_PTR) {
2609 type1 = pointed_type(type1);
2610 type2 = pointed_type(type2);
2611 return is_compatible_types(type1, type2);
2612 } else if (bt1 == VT_STRUCT) {
2613 return (type1->ref == type2->ref);
2614 } else if (bt1 == VT_FUNC) {
2615 return is_compatible_func(type1, type2);
2616 } else {
2617 return 1;
2621 /* return true if type1 and type2 are exactly the same (including
2622 qualifiers).
2624 static int is_compatible_types(CType *type1, CType *type2)
2626 return compare_types(type1,type2,0);
2629 /* return true if type1 and type2 are the same (ignoring qualifiers).
2631 static int is_compatible_parameter_types(CType *type1, CType *type2)
2633 return compare_types(type1,type2,1);
2636 /* print a type. If 'varstr' is not NULL, then the variable is also
2637 printed in the type */
2638 /* XXX: union */
2639 /* XXX: add array and function pointers */
2640 static void type_to_str(char *buf, int buf_size,
2641 CType *type, const char *varstr)
2643 int bt, v, t;
2644 Sym *s, *sa;
2645 char buf1[256];
2646 const char *tstr;
2648 t = type->t & VT_TYPE;
2649 bt = t & VT_BTYPE;
2650 buf[0] = '\0';
2651 if (t & VT_CONSTANT)
2652 pstrcat(buf, buf_size, "const ");
2653 if (t & VT_VOLATILE)
2654 pstrcat(buf, buf_size, "volatile ");
2655 if ((t & (VT_DEFSIGN | VT_UNSIGNED)) == (VT_DEFSIGN | VT_UNSIGNED))
2656 pstrcat(buf, buf_size, "unsigned ");
2657 else if (t & VT_DEFSIGN)
2658 pstrcat(buf, buf_size, "signed ");
2659 switch(bt) {
2660 case VT_VOID:
2661 tstr = "void";
2662 goto add_tstr;
2663 case VT_BOOL:
2664 tstr = "_Bool";
2665 goto add_tstr;
2666 case VT_BYTE:
2667 tstr = "char";
2668 goto add_tstr;
2669 case VT_SHORT:
2670 tstr = "short";
2671 goto add_tstr;
2672 case VT_INT:
2673 tstr = "int";
2674 goto add_tstr;
2675 case VT_LONG:
2676 tstr = "long";
2677 goto add_tstr;
2678 case VT_LLONG:
2679 tstr = "long long";
2680 goto add_tstr;
2681 case VT_FLOAT:
2682 tstr = "float";
2683 goto add_tstr;
2684 case VT_DOUBLE:
2685 tstr = "double";
2686 goto add_tstr;
2687 case VT_LDOUBLE:
2688 tstr = "long double";
2689 add_tstr:
2690 pstrcat(buf, buf_size, tstr);
2691 break;
2692 case VT_ENUM:
2693 case VT_STRUCT:
2694 if (bt == VT_STRUCT)
2695 tstr = "struct ";
2696 else
2697 tstr = "enum ";
2698 pstrcat(buf, buf_size, tstr);
2699 v = type->ref->v & ~SYM_STRUCT;
2700 if (v >= SYM_FIRST_ANOM)
2701 pstrcat(buf, buf_size, "<anonymous>");
2702 else
2703 pstrcat(buf, buf_size, get_tok_str(v, NULL));
2704 break;
2705 case VT_FUNC:
2706 s = type->ref;
2707 type_to_str(buf, buf_size, &s->type, varstr);
2708 pstrcat(buf, buf_size, "(");
2709 sa = s->next;
2710 while (sa != NULL) {
2711 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
2712 pstrcat(buf, buf_size, buf1);
2713 sa = sa->next;
2714 if (sa)
2715 pstrcat(buf, buf_size, ", ");
2717 pstrcat(buf, buf_size, ")");
2718 goto no_var;
2719 case VT_PTR:
2720 s = type->ref;
2721 if (t & VT_ARRAY) {
2722 snprintf(buf1, sizeof(buf1), "%s[%ld]", varstr ? varstr : "", s->c);
2723 type_to_str(buf, buf_size, &s->type, buf1);
2724 goto no_var;
2726 pstrcpy(buf1, sizeof(buf1), "*");
2727 if (t & VT_CONSTANT)
2728 pstrcat(buf1, buf_size, "const ");
2729 if (t & VT_VOLATILE)
2730 pstrcat(buf1, buf_size, "volatile ");
2731 if (varstr)
2732 pstrcat(buf1, sizeof(buf1), varstr);
2733 type_to_str(buf, buf_size, &s->type, buf1);
2734 goto no_var;
2736 if (varstr) {
2737 pstrcat(buf, buf_size, " ");
2738 pstrcat(buf, buf_size, varstr);
2740 no_var: ;
2743 /* verify type compatibility to store vtop in 'dt' type, and generate
2744 casts if needed. */
2745 static void gen_assign_cast(CType *dt)
2747 CType *st, *type1, *type2, tmp_type1, tmp_type2;
2748 char buf1[256], buf2[256];
2749 int dbt, sbt;
2751 st = &vtop->type; /* source type */
2752 dbt = dt->t & VT_BTYPE;
2753 sbt = st->t & VT_BTYPE;
2754 if (sbt == VT_VOID || dbt == VT_VOID) {
2755 if (sbt == VT_VOID && dbt == VT_VOID)
2756 ; /*
2757 It is Ok if both are void
2758 A test program:
2759 void func1() {}
2760 void func2() {
2761 return func1();
2763 gcc accepts this program
2765 else
2766 tcc_error("cannot cast from/to void");
2768 if (dt->t & VT_CONSTANT)
2769 tcc_warning("assignment of read-only location");
2770 switch(dbt) {
2771 case VT_PTR:
2772 /* special cases for pointers */
2773 /* '0' can also be a pointer */
2774 if (is_null_pointer(vtop))
2775 goto type_ok;
2776 /* accept implicit pointer to integer cast with warning */
2777 if (is_integer_btype(sbt)) {
2778 tcc_warning("assignment makes pointer from integer without a cast");
2779 goto type_ok;
2781 type1 = pointed_type(dt);
2782 /* a function is implicitely a function pointer */
2783 if (sbt == VT_FUNC) {
2784 if ((type1->t & VT_BTYPE) != VT_VOID &&
2785 !is_compatible_types(pointed_type(dt), st))
2786 tcc_warning("assignment from incompatible pointer type");
2787 goto type_ok;
2789 if (sbt != VT_PTR)
2790 goto error;
2791 type2 = pointed_type(st);
2792 if ((type1->t & VT_BTYPE) == VT_VOID ||
2793 (type2->t & VT_BTYPE) == VT_VOID) {
2794 /* void * can match anything */
2795 } else {
2796 /* exact type match, except for qualifiers */
2797 tmp_type1 = *type1;
2798 tmp_type2 = *type2;
2799 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2800 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2801 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2802 /* Like GCC don't warn by default for merely changes
2803 in pointer target signedness. Do warn for different
2804 base types, though, in particular for unsigned enums
2805 and signed int targets. */
2806 if ((tmp_type1.t & (VT_DEFSIGN | VT_UNSIGNED)) !=
2807 (tmp_type2.t & (VT_DEFSIGN | VT_UNSIGNED)) &&
2808 (tmp_type1.t & VT_BTYPE) == (tmp_type2.t & VT_BTYPE))
2810 else
2811 tcc_warning("assignment from incompatible pointer type");
2814 /* check const and volatile */
2815 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
2816 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
2817 tcc_warning("assignment discards qualifiers from pointer target type");
2818 break;
2819 case VT_BYTE:
2820 case VT_SHORT:
2821 case VT_INT:
2822 case VT_LLONG:
2823 if (sbt == VT_PTR || sbt == VT_FUNC) {
2824 tcc_warning("assignment makes integer from pointer without a cast");
2825 } else if (sbt == VT_STRUCT) {
2826 goto case_VT_STRUCT;
2828 /* XXX: more tests */
2829 break;
2830 case VT_STRUCT:
2831 case_VT_STRUCT:
2832 tmp_type1 = *dt;
2833 tmp_type2 = *st;
2834 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2835 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2836 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2837 error:
2838 type_to_str(buf1, sizeof(buf1), st, NULL);
2839 type_to_str(buf2, sizeof(buf2), dt, NULL);
2840 tcc_error("cannot cast '%s' to '%s'", buf1, buf2);
2842 break;
2844 type_ok:
2845 gen_cast(dt);
2848 /* store vtop in lvalue pushed on stack */
2849 ST_FUNC void vstore(void)
2851 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
2853 ft = vtop[-1].type.t;
2854 sbt = vtop->type.t & VT_BTYPE;
2855 dbt = ft & VT_BTYPE;
2856 if ((((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
2857 (sbt == VT_INT && dbt == VT_SHORT))
2858 && !(vtop->type.t & VT_BITFIELD)) {
2859 /* optimize char/short casts */
2860 delayed_cast = VT_MUSTCAST;
2861 vtop->type.t = (ft & VT_TYPE & ~VT_BITFIELD &
2862 ((1 << VT_STRUCT_SHIFT) - 1));
2863 /* XXX: factorize */
2864 if (ft & VT_CONSTANT)
2865 tcc_warning("assignment of read-only location");
2866 } else {
2867 delayed_cast = 0;
2868 if (!(ft & VT_BITFIELD))
2869 gen_assign_cast(&vtop[-1].type);
2872 if (sbt == VT_STRUCT) {
2873 /* if structure, only generate pointer */
2874 /* structure assignment : generate memcpy */
2875 /* XXX: optimize if small size */
2876 if (!nocode_wanted) {
2877 size = type_size(&vtop->type, &align);
2879 /* destination */
2880 vswap();
2881 vtop->type.t = VT_PTR;
2882 gaddrof();
2884 /* address of memcpy() */
2885 #ifdef TCC_ARM_EABI
2886 if(!(align & 7))
2887 vpush_global_sym(&func_old_type, TOK_memcpy8);
2888 else if(!(align & 3))
2889 vpush_global_sym(&func_old_type, TOK_memcpy4);
2890 else
2891 #endif
2892 /* Use memmove, rather than memcpy, as dest and src may be same: */
2893 vpush_global_sym(&func_old_type, TOK_memmove);
2895 vswap();
2896 /* source */
2897 vpushv(vtop - 2);
2898 vtop->type.t = VT_PTR;
2899 gaddrof();
2900 /* type size */
2901 vpushi(size);
2902 gfunc_call(3);
2903 } else {
2904 vswap();
2905 vpop();
2907 /* leave source on stack */
2908 } else if (ft & VT_BITFIELD) {
2909 /* bitfield store handling */
2911 /* save lvalue as expression result (example: s.b = s.a = n;) */
2912 vdup(), vtop[-1] = vtop[-2];
2914 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
2915 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
2916 /* remove bit field info to avoid loops */
2917 vtop[-1].type.t = ft & ~VT_BITFIELD & ((1 << VT_STRUCT_SHIFT) - 1);
2919 if((ft & VT_BTYPE) == VT_BOOL) {
2920 gen_cast(&vtop[-1].type);
2921 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
2924 /* duplicate destination */
2925 vdup();
2926 vtop[-1] = vtop[-2];
2928 /* mask and shift source */
2929 if((ft & VT_BTYPE) != VT_BOOL) {
2930 if((ft & VT_BTYPE) == VT_LLONG) {
2931 vpushll((1ULL << bit_size) - 1ULL);
2932 } else {
2933 vpushi((1 << bit_size) - 1);
2935 gen_op('&');
2937 vpushi(bit_pos);
2938 gen_op(TOK_SHL);
2939 /* load destination, mask and or with source */
2940 vswap();
2941 if((ft & VT_BTYPE) == VT_LLONG) {
2942 vpushll(~(((1ULL << bit_size) - 1ULL) << bit_pos));
2943 } else {
2944 vpushi(~(((1 << bit_size) - 1) << bit_pos));
2946 gen_op('&');
2947 gen_op('|');
2948 /* store result */
2949 vstore();
2950 /* ... and discard */
2951 vpop();
2953 } else {
2954 if (!nocode_wanted) {
2955 #ifdef CONFIG_TCC_BCHECK
2956 /* bound check case */
2957 if (vtop[-1].r & VT_MUSTBOUND) {
2958 vswap();
2959 gbound();
2960 vswap();
2962 #endif
2963 rc = RC_INT;
2964 if (is_float(ft)) {
2965 rc = RC_FLOAT;
2966 #ifdef TCC_TARGET_X86_64
2967 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
2968 rc = RC_ST0;
2969 } else if ((ft & VT_BTYPE) == VT_QFLOAT) {
2970 rc = RC_FRET;
2972 #endif
2974 r = gv(rc); /* generate value */
2975 /* if lvalue was saved on stack, must read it */
2976 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
2977 SValue sv;
2978 t = get_reg(RC_INT);
2979 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2980 sv.type.t = VT_PTR;
2981 #else
2982 sv.type.t = VT_INT;
2983 #endif
2984 sv.r = VT_LOCAL | VT_LVAL;
2985 sv.c.i = vtop[-1].c.i;
2986 load(t, &sv);
2987 vtop[-1].r = t | VT_LVAL;
2989 /* two word case handling : store second register at word + 4 (or +8 for x86-64) */
2990 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2991 if (((ft & VT_BTYPE) == VT_QLONG) || ((ft & VT_BTYPE) == VT_QFLOAT)) {
2992 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
2993 #else
2994 if ((ft & VT_BTYPE) == VT_LLONG) {
2995 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
2996 #endif
2997 vtop[-1].type.t = load_type;
2998 store(r, vtop - 1);
2999 vswap();
3000 /* convert to int to increment easily */
3001 vtop->type.t = addr_type;
3002 gaddrof();
3003 vpushi(load_size);
3004 gen_op('+');
3005 vtop->r |= VT_LVAL;
3006 vswap();
3007 vtop[-1].type.t = load_type;
3008 /* XXX: it works because r2 is spilled last ! */
3009 store(vtop->r2, vtop - 1);
3010 } else {
3011 store(r, vtop - 1);
3014 vswap();
3015 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
3016 vtop->r |= delayed_cast;
3020 /* post defines POST/PRE add. c is the token ++ or -- */
3021 ST_FUNC void inc(int post, int c)
3023 test_lvalue();
3024 vdup(); /* save lvalue */
3025 if (post) {
3026 if (!nocode_wanted)
3027 gv_dup(); /* duplicate value */
3028 else
3029 vdup(); /* duplicate value */
3030 vrotb(3);
3031 vrotb(3);
3033 /* add constant */
3034 vpushi(c - TOK_MID);
3035 gen_op('+');
3036 vstore(); /* store value */
3037 if (post)
3038 vpop(); /* if post op, return saved value */
3041 ST_FUNC void parse_mult_str (CString *astr, const char *msg)
3043 /* read the string */
3044 if (tok != TOK_STR)
3045 expect(msg);
3046 cstr_new(astr);
3047 while (tok == TOK_STR) {
3048 /* XXX: add \0 handling too ? */
3049 cstr_cat(astr, tokc.str.data, -1);
3050 next();
3052 cstr_ccat(astr, '\0');
3055 /* Parse GNUC __attribute__ extension. Currently, the following
3056 extensions are recognized:
3057 - aligned(n) : set data/function alignment.
3058 - packed : force data alignment to 1
3059 - section(x) : generate data/code in this section.
3060 - unused : currently ignored, but may be used someday.
3061 - regparm(n) : pass function parameters in registers (i386 only)
3063 static void parse_attribute(AttributeDef *ad)
3065 int t, n;
3066 CString astr;
3068 while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
3069 next();
3070 skip('(');
3071 skip('(');
3072 while (tok != ')') {
3073 if (tok < TOK_IDENT)
3074 expect("attribute name");
3075 t = tok;
3076 next();
3077 switch(t) {
3078 case TOK_SECTION1:
3079 case TOK_SECTION2:
3080 skip('(');
3081 parse_mult_str(&astr, "section name");
3082 ad->section = find_section(tcc_state, (char *)astr.data);
3083 skip(')');
3084 cstr_free(&astr);
3085 break;
3086 case TOK_ALIAS1:
3087 case TOK_ALIAS2:
3088 skip('(');
3089 parse_mult_str(&astr, "alias(\"target\")");
3090 ad->alias_target = /* save string as token, for later */
3091 tok_alloc((char*)astr.data, astr.size-1)->tok;
3092 skip(')');
3093 cstr_free(&astr);
3094 break;
3095 case TOK_VISIBILITY1:
3096 case TOK_VISIBILITY2:
3097 skip('(');
3098 parse_mult_str(&astr,
3099 "visibility(\"default|hidden|internal|protected\")");
3100 if (!strcmp (astr.data, "default"))
3101 ad->a.visibility = STV_DEFAULT;
3102 else if (!strcmp (astr.data, "hidden"))
3103 ad->a.visibility = STV_HIDDEN;
3104 else if (!strcmp (astr.data, "internal"))
3105 ad->a.visibility = STV_INTERNAL;
3106 else if (!strcmp (astr.data, "protected"))
3107 ad->a.visibility = STV_PROTECTED;
3108 else
3109 expect("visibility(\"default|hidden|internal|protected\")");
3110 skip(')');
3111 cstr_free(&astr);
3112 break;
3113 case TOK_ALIGNED1:
3114 case TOK_ALIGNED2:
3115 if (tok == '(') {
3116 next();
3117 n = expr_const();
3118 if (n <= 0 || (n & (n - 1)) != 0)
3119 tcc_error("alignment must be a positive power of two");
3120 skip(')');
3121 } else {
3122 n = MAX_ALIGN;
3124 ad->a.aligned = n;
3125 break;
3126 case TOK_PACKED1:
3127 case TOK_PACKED2:
3128 ad->a.packed = 1;
3129 break;
3130 case TOK_WEAK1:
3131 case TOK_WEAK2:
3132 ad->a.weak = 1;
3133 break;
3134 case TOK_UNUSED1:
3135 case TOK_UNUSED2:
3136 /* currently, no need to handle it because tcc does not
3137 track unused objects */
3138 break;
3139 case TOK_NORETURN1:
3140 case TOK_NORETURN2:
3141 /* currently, no need to handle it because tcc does not
3142 track unused objects */
3143 break;
3144 case TOK_CDECL1:
3145 case TOK_CDECL2:
3146 case TOK_CDECL3:
3147 ad->a.func_call = FUNC_CDECL;
3148 break;
3149 case TOK_STDCALL1:
3150 case TOK_STDCALL2:
3151 case TOK_STDCALL3:
3152 ad->a.func_call = FUNC_STDCALL;
3153 break;
3154 #ifdef TCC_TARGET_I386
3155 case TOK_REGPARM1:
3156 case TOK_REGPARM2:
3157 skip('(');
3158 n = expr_const();
3159 if (n > 3)
3160 n = 3;
3161 else if (n < 0)
3162 n = 0;
3163 if (n > 0)
3164 ad->a.func_call = FUNC_FASTCALL1 + n - 1;
3165 skip(')');
3166 break;
3167 case TOK_FASTCALL1:
3168 case TOK_FASTCALL2:
3169 case TOK_FASTCALL3:
3170 ad->a.func_call = FUNC_FASTCALLW;
3171 break;
3172 #endif
3173 case TOK_MODE:
3174 skip('(');
3175 switch(tok) {
3176 case TOK_MODE_DI:
3177 ad->a.mode = VT_LLONG + 1;
3178 break;
3179 case TOK_MODE_QI:
3180 ad->a.mode = VT_BYTE + 1;
3181 break;
3182 case TOK_MODE_HI:
3183 ad->a.mode = VT_SHORT + 1;
3184 break;
3185 case TOK_MODE_SI:
3186 case TOK_MODE_word:
3187 ad->a.mode = VT_INT + 1;
3188 break;
3189 default:
3190 tcc_warning("__mode__(%s) not supported\n", get_tok_str(tok, NULL));
3191 break;
3193 next();
3194 skip(')');
3195 break;
3196 case TOK_DLLEXPORT:
3197 ad->a.func_export = 1;
3198 break;
3199 case TOK_DLLIMPORT:
3200 ad->a.func_import = 1;
3201 break;
3202 default:
3203 if (tcc_state->warn_unsupported)
3204 tcc_warning("'%s' attribute ignored", get_tok_str(t, NULL));
3205 /* skip parameters */
3206 if (tok == '(') {
3207 int parenthesis = 0;
3208 do {
3209 if (tok == '(')
3210 parenthesis++;
3211 else if (tok == ')')
3212 parenthesis--;
3213 next();
3214 } while (parenthesis && tok != -1);
3216 break;
3218 if (tok != ',')
3219 break;
3220 next();
3222 skip(')');
3223 skip(')');
3227 static Sym * find_field (CType *type, int v)
3229 Sym *s = type->ref;
3230 v |= SYM_FIELD;
3231 while ((s = s->next) != NULL) {
3232 if ((s->v & SYM_FIELD) && (s->v & ~SYM_FIELD) >= SYM_FIRST_ANOM) {
3233 Sym *ret = find_field (&s->type, v);
3234 if (ret)
3235 return ret;
3237 if (s->v == v)
3238 break;
3240 return s;
3243 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
3244 static void struct_decl(CType *type, AttributeDef *ad, int u)
3246 int a, v, size, align, maxalign, c, offset, flexible, extra_bytes;
3247 int bit_size, bit_pos, bsize, bt, lbit_pos, prevbt;
3248 Sym *s, *ss, *ass, **ps;
3249 AttributeDef ad1;
3250 CType type1, btype;
3252 a = tok; /* save decl type */
3253 next();
3254 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3255 parse_attribute(ad);
3256 if (tok != '{') {
3257 v = tok;
3258 next();
3259 /* struct already defined ? return it */
3260 if (v < TOK_IDENT)
3261 expect("struct/union/enum name");
3262 s = struct_find(v);
3263 if (s && (s->scope == local_scope || (tok != '{' && tok != ';'))) {
3264 if (s->type.t != a)
3265 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
3266 goto do_decl;
3268 } else {
3269 v = anon_sym++;
3271 /* Record the original enum/struct/union token. */
3272 type1.t = a;
3273 type1.ref = NULL;
3274 /* we put an undefined size for struct/union */
3275 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
3276 s->r = 0; /* default alignment is zero as gcc */
3277 /* put struct/union/enum name in type */
3278 do_decl:
3279 type->t = u;
3280 type->ref = s;
3282 if (tok == '{') {
3283 next();
3284 if (s->c != -1)
3285 tcc_error("struct/union/enum already defined");
3286 /* cannot be empty */
3287 c = 0;
3288 /* non empty enums are not allowed */
3289 if (a == TOK_ENUM) {
3290 int seen_neg = 0;
3291 for(;;) {
3292 v = tok;
3293 if (v < TOK_UIDENT)
3294 expect("identifier");
3295 ss = sym_find(v);
3296 if (ss && !local_stack)
3297 tcc_error("redefinition of enumerator '%s'",
3298 get_tok_str(v, NULL));
3299 next();
3300 if (tok == '=') {
3301 next();
3302 c = expr_const();
3304 if (c < 0)
3305 seen_neg = 1;
3306 /* enum symbols have static storage */
3307 ss = sym_push(v, &int_type, VT_CONST, c);
3308 ss->type.t |= VT_STATIC;
3309 if (tok != ',')
3310 break;
3311 next();
3312 c++;
3313 /* NOTE: we accept a trailing comma */
3314 if (tok == '}')
3315 break;
3317 if (!seen_neg)
3318 s->a.unsigned_enum = 1;
3319 s->c = type_size(&int_type, &align);
3320 skip('}');
3321 } else {
3322 maxalign = 1;
3323 ps = &s->next;
3324 prevbt = VT_INT;
3325 bit_pos = 0;
3326 offset = 0;
3327 flexible = 0;
3328 while (tok != '}') {
3329 if (!parse_btype(&btype, &ad1)) {
3330 skip(';');
3331 continue;
3333 while (1) {
3334 extra_bytes = 0;
3335 if (flexible)
3336 tcc_error("flexible array member '%s' not at the end of struct",
3337 get_tok_str(v, NULL));
3338 bit_size = -1;
3339 v = 0;
3340 type1 = btype;
3341 if (tok != ':') {
3342 type_decl(&type1, &ad1, &v, TYPE_DIRECT | TYPE_ABSTRACT);
3343 if (v == 0) {
3344 if ((type1.t & VT_BTYPE) != VT_STRUCT)
3345 expect("identifier");
3346 else {
3347 int v = btype.ref->v;
3348 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
3349 if (tcc_state->ms_extensions == 0)
3350 expect("identifier");
3354 if (type_size(&type1, &align) < 0) {
3355 if ((a == TOK_STRUCT) && (type1.t & VT_ARRAY) && c)
3356 flexible = 1;
3357 else
3358 tcc_error("field '%s' has incomplete type",
3359 get_tok_str(v, NULL));
3361 if ((type1.t & VT_BTYPE) == VT_FUNC ||
3362 (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
3363 tcc_error("invalid type for '%s'",
3364 get_tok_str(v, NULL));
3366 if (tok == ':') {
3367 next();
3368 bit_size = expr_const();
3369 /* XXX: handle v = 0 case for messages */
3370 if (bit_size < 0)
3371 tcc_error("negative width in bit-field '%s'",
3372 get_tok_str(v, NULL));
3373 if (v && bit_size == 0)
3374 tcc_error("zero width for bit-field '%s'",
3375 get_tok_str(v, NULL));
3377 size = type_size(&type1, &align);
3378 if (ad1.a.aligned) {
3379 if (align < ad1.a.aligned)
3380 align = ad1.a.aligned;
3381 } else if (ad1.a.packed || ad->a.packed) {
3382 align = 1;
3383 } else if (*tcc_state->pack_stack_ptr) {
3384 if (align > *tcc_state->pack_stack_ptr)
3385 align = *tcc_state->pack_stack_ptr;
3387 lbit_pos = 0;
3388 if (bit_size >= 0) {
3389 bt = type1.t & VT_BTYPE;
3390 if (bt != VT_INT &&
3391 bt != VT_BYTE &&
3392 bt != VT_SHORT &&
3393 bt != VT_BOOL &&
3394 bt != VT_ENUM &&
3395 bt != VT_LLONG)
3396 tcc_error("bitfields must have scalar type");
3397 bsize = size * 8;
3398 if (bit_size > bsize) {
3399 tcc_error("width of '%s' exceeds its type",
3400 get_tok_str(v, NULL));
3401 } else if (bit_size == bsize) {
3402 /* no need for bit fields */
3403 bit_pos = 0;
3404 } else if (bit_size == 0) {
3405 /* XXX: what to do if only padding in a
3406 structure ? */
3407 /* zero size: means to pad */
3408 bit_pos = 0;
3409 } else {
3410 /* if type change, union, or will overrun
3411 * allignment slot, start at a newly
3412 * alligned slot */
3413 if ((bit_pos + bit_size) > bsize ||
3414 bt != prevbt || a == TOK_UNION)
3415 bit_pos = 0;
3416 lbit_pos = bit_pos;
3417 /* XXX: handle LSB first */
3418 type1.t |= VT_BITFIELD |
3419 (bit_pos << VT_STRUCT_SHIFT) |
3420 (bit_size << (VT_STRUCT_SHIFT + 6));
3421 bit_pos += bit_size;
3422 /* without ms-bitfields, allocate the
3423 * minimum number of bytes necessary,
3424 * adding single bytes as needed */
3425 if (!tcc_state->ms_bitfields) {
3426 if (lbit_pos == 0)
3427 /* minimum bytes for new bitfield */
3428 size = (bit_size + 7) / 8;
3429 else {
3430 /* enough spare bits already allocated? */
3431 bit_size = (lbit_pos - 1) % 8 + 1 + bit_size;
3432 if (bit_size > 8) /* doesn't fit */
3433 extra_bytes = (bit_size - 1) / 8;
3437 prevbt = bt;
3438 } else {
3439 bit_pos = 0;
3441 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
3442 /* add new memory data only if starting bit
3443 field or adding bytes to existing bit field */
3444 if (extra_bytes) c += extra_bytes;
3445 else if (lbit_pos == 0) {
3446 if (a == TOK_STRUCT) {
3447 c = (c + align - 1) & -align;
3448 offset = c;
3449 if (size > 0)
3450 c += size;
3451 } else {
3452 offset = 0;
3453 if (size > c)
3454 c = size;
3456 if (align > maxalign)
3457 maxalign = align;
3459 #if 0
3460 printf("add field %s offset=%d",
3461 get_tok_str(v, NULL), offset);
3462 if (type1.t & VT_BITFIELD) {
3463 printf(" pos=%d size=%d",
3464 (type1.t >> VT_STRUCT_SHIFT) & 0x3f,
3465 (type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
3467 printf("\n");
3468 #endif
3470 if (v == 0 && (type1.t & VT_BTYPE) == VT_STRUCT) {
3471 /* An anonymous struct/union. Adjust member offsets
3472 to reflect the real offset of our containing struct.
3473 Also set the offset of this anon member inside
3474 the outer struct to be zero. Via this it
3475 works when accessing the field offset directly
3476 (from base object), as well as when recursing
3477 members in initializer handling. */
3478 int v2 = btype.ref->v;
3479 if (!(v2 & SYM_FIELD) &&
3480 (v2 & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
3481 Sym **pps;
3482 /* This happens only with MS extensions. The
3483 anon member has a named struct type, so it
3484 potentially is shared with other references.
3485 We need to unshare members so we can modify
3486 them. */
3487 ass = type1.ref;
3488 type1.ref = sym_push(anon_sym++ | SYM_FIELD,
3489 &type1.ref->type, 0,
3490 type1.ref->c);
3491 pps = &type1.ref->next;
3492 while ((ass = ass->next) != NULL) {
3493 *pps = sym_push(ass->v, &ass->type, 0, ass->c);
3494 pps = &((*pps)->next);
3496 *pps = NULL;
3498 ass = type1.ref;
3499 while ((ass = ass->next) != NULL)
3500 ass->c += offset;
3501 offset = 0;
3502 v = anon_sym++;
3504 if (v) {
3505 ss = sym_push(v | SYM_FIELD, &type1, 0, offset);
3506 *ps = ss;
3507 ps = &ss->next;
3509 if (tok == ';' || tok == TOK_EOF)
3510 break;
3511 skip(',');
3513 skip(';');
3515 skip('}');
3516 /* store size and alignment */
3517 s->c = (c + maxalign - 1) & -maxalign;
3518 s->r = maxalign;
3523 /* return 1 if basic type is a type size (short, long, long long) */
3524 ST_FUNC int is_btype_size(int bt)
3526 return bt == VT_SHORT || bt == VT_LONG || bt == VT_LLONG;
3529 /* Add type qualifiers to a type. If the type is an array then the qualifiers
3530 are added to the element type, copied because it could be a typedef. */
3531 static void parse_btype_qualify(CType *type, int qualifiers)
3533 while (type->t & VT_ARRAY) {
3534 type->ref = sym_push(SYM_FIELD, &type->ref->type, 0, type->ref->c);
3535 type = &type->ref->type;
3537 type->t |= qualifiers;
3540 /* return 0 if no type declaration. otherwise, return the basic type
3541 and skip it.
3543 static int parse_btype(CType *type, AttributeDef *ad)
3545 int t, u, bt_size, complete, type_found, typespec_found;
3546 Sym *s;
3547 CType type1;
3549 memset(ad, 0, sizeof(AttributeDef));
3550 complete = 0;
3551 type_found = 0;
3552 typespec_found = 0;
3553 t = 0;
3554 while(1) {
3555 switch(tok) {
3556 case TOK_EXTENSION:
3557 /* currently, we really ignore extension */
3558 next();
3559 continue;
3561 /* basic types */
3562 case TOK_CHAR:
3563 u = VT_BYTE;
3564 basic_type:
3565 next();
3566 basic_type1:
3567 if (complete)
3568 tcc_error("too many basic types");
3569 t |= u;
3570 bt_size = is_btype_size (u & VT_BTYPE);
3571 if (u == VT_INT || (!bt_size && !(t & VT_TYPEDEF)))
3572 complete = 1;
3573 typespec_found = 1;
3574 break;
3575 case TOK_VOID:
3576 u = VT_VOID;
3577 goto basic_type;
3578 case TOK_SHORT:
3579 u = VT_SHORT;
3580 goto basic_type;
3581 case TOK_INT:
3582 u = VT_INT;
3583 goto basic_type;
3584 case TOK_LONG:
3585 next();
3586 if ((t & VT_BTYPE) == VT_DOUBLE) {
3587 #ifndef TCC_TARGET_PE
3588 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3589 #endif
3590 } else if ((t & VT_BTYPE) == VT_LONG) {
3591 t = (t & ~VT_BTYPE) | VT_LLONG;
3592 } else {
3593 u = VT_LONG;
3594 goto basic_type1;
3596 break;
3597 #ifdef TCC_TARGET_ARM64
3598 case TOK_UINT128:
3599 /* GCC's __uint128_t appears in some Linux header files. Make it a
3600 synonym for long double to get the size and alignment right. */
3601 u = VT_LDOUBLE;
3602 goto basic_type;
3603 #endif
3604 case TOK_BOOL:
3605 u = VT_BOOL;
3606 goto basic_type;
3607 case TOK_FLOAT:
3608 u = VT_FLOAT;
3609 goto basic_type;
3610 case TOK_DOUBLE:
3611 next();
3612 if ((t & VT_BTYPE) == VT_LONG) {
3613 #ifdef TCC_TARGET_PE
3614 t = (t & ~VT_BTYPE) | VT_DOUBLE;
3615 #else
3616 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3617 #endif
3618 } else {
3619 u = VT_DOUBLE;
3620 goto basic_type1;
3622 break;
3623 case TOK_ENUM:
3624 struct_decl(&type1, ad, VT_ENUM);
3625 basic_type2:
3626 u = type1.t;
3627 type->ref = type1.ref;
3628 goto basic_type1;
3629 case TOK_STRUCT:
3630 case TOK_UNION:
3631 struct_decl(&type1, ad, VT_STRUCT);
3632 goto basic_type2;
3634 /* type modifiers */
3635 case TOK_CONST1:
3636 case TOK_CONST2:
3637 case TOK_CONST3:
3638 type->t = t;
3639 parse_btype_qualify(type, VT_CONSTANT);
3640 t = type->t;
3641 next();
3642 break;
3643 case TOK_VOLATILE1:
3644 case TOK_VOLATILE2:
3645 case TOK_VOLATILE3:
3646 type->t = t;
3647 parse_btype_qualify(type, VT_VOLATILE);
3648 t = type->t;
3649 next();
3650 break;
3651 case TOK_SIGNED1:
3652 case TOK_SIGNED2:
3653 case TOK_SIGNED3:
3654 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == (VT_DEFSIGN|VT_UNSIGNED))
3655 tcc_error("signed and unsigned modifier");
3656 typespec_found = 1;
3657 t |= VT_DEFSIGN;
3658 next();
3659 break;
3660 case TOK_REGISTER:
3661 case TOK_AUTO:
3662 case TOK_RESTRICT1:
3663 case TOK_RESTRICT2:
3664 case TOK_RESTRICT3:
3665 next();
3666 break;
3667 case TOK_UNSIGNED:
3668 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == VT_DEFSIGN)
3669 tcc_error("signed and unsigned modifier");
3670 t |= VT_DEFSIGN | VT_UNSIGNED;
3671 next();
3672 typespec_found = 1;
3673 break;
3675 /* storage */
3676 case TOK_EXTERN:
3677 t |= VT_EXTERN;
3678 next();
3679 break;
3680 case TOK_STATIC:
3681 t |= VT_STATIC;
3682 next();
3683 break;
3684 case TOK_TYPEDEF:
3685 t |= VT_TYPEDEF;
3686 next();
3687 break;
3688 case TOK_INLINE1:
3689 case TOK_INLINE2:
3690 case TOK_INLINE3:
3691 t |= VT_INLINE;
3692 next();
3693 break;
3695 /* GNUC attribute */
3696 case TOK_ATTRIBUTE1:
3697 case TOK_ATTRIBUTE2:
3698 parse_attribute(ad);
3699 if (ad->a.mode) {
3700 u = ad->a.mode -1;
3701 t = (t & ~VT_BTYPE) | u;
3703 break;
3704 /* GNUC typeof */
3705 case TOK_TYPEOF1:
3706 case TOK_TYPEOF2:
3707 case TOK_TYPEOF3:
3708 next();
3709 parse_expr_type(&type1);
3710 /* remove all storage modifiers except typedef */
3711 type1.t &= ~(VT_STORAGE&~VT_TYPEDEF);
3712 goto basic_type2;
3713 default:
3714 if (typespec_found)
3715 goto the_end;
3716 s = sym_find(tok);
3717 if (!s || !(s->type.t & VT_TYPEDEF))
3718 goto the_end;
3720 type->t = ((s->type.t & ~VT_TYPEDEF) |
3721 (t & ~(VT_CONSTANT | VT_VOLATILE)));
3722 type->ref = s->type.ref;
3723 if (t & (VT_CONSTANT | VT_VOLATILE))
3724 parse_btype_qualify(type, t & (VT_CONSTANT | VT_VOLATILE));
3725 t = type->t;
3727 if (s->r) {
3728 /* get attributes from typedef */
3729 if (0 == ad->a.aligned)
3730 ad->a.aligned = s->a.aligned;
3731 if (0 == ad->a.func_call)
3732 ad->a.func_call = s->a.func_call;
3733 ad->a.packed |= s->a.packed;
3735 next();
3736 typespec_found = 1;
3737 break;
3739 type_found = 1;
3741 the_end:
3742 if (tcc_state->char_is_unsigned) {
3743 if ((t & (VT_DEFSIGN|VT_BTYPE)) == VT_BYTE)
3744 t |= VT_UNSIGNED;
3747 /* long is never used as type */
3748 if ((t & VT_BTYPE) == VT_LONG)
3749 #if (!defined TCC_TARGET_X86_64 && !defined TCC_TARGET_ARM64) || \
3750 defined TCC_TARGET_PE
3751 t = (t & ~VT_BTYPE) | VT_INT;
3752 #else
3753 t = (t & ~VT_BTYPE) | VT_LLONG;
3754 #endif
3755 type->t = t;
3756 return type_found;
3759 /* convert a function parameter type (array to pointer and function to
3760 function pointer) */
3761 static inline void convert_parameter_type(CType *pt)
3763 /* remove const and volatile qualifiers (XXX: const could be used
3764 to indicate a const function parameter */
3765 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
3766 /* array must be transformed to pointer according to ANSI C */
3767 pt->t &= ~VT_ARRAY;
3768 if ((pt->t & VT_BTYPE) == VT_FUNC) {
3769 mk_pointer(pt);
3773 ST_FUNC void parse_asm_str(CString *astr)
3775 skip('(');
3776 parse_mult_str(astr, "string constant");
3779 /* Parse an asm label and return the token */
3780 static int asm_label_instr(void)
3782 int v;
3783 CString astr;
3785 next();
3786 parse_asm_str(&astr);
3787 skip(')');
3788 #ifdef ASM_DEBUG
3789 printf("asm_alias: \"%s\"\n", (char *)astr.data);
3790 #endif
3791 v = tok_alloc(astr.data, astr.size - 1)->tok;
3792 cstr_free(&astr);
3793 return v;
3796 static void post_type(CType *type, AttributeDef *ad, int storage)
3798 int n, l, t1, arg_size, align;
3799 Sym **plast, *s, *first;
3800 AttributeDef ad1;
3801 CType pt;
3803 if (tok == '(') {
3804 /* function declaration */
3805 next();
3806 l = 0;
3807 first = NULL;
3808 plast = &first;
3809 arg_size = 0;
3810 if (tok != ')') {
3811 for(;;) {
3812 /* read param name and compute offset */
3813 if (l != FUNC_OLD) {
3814 if (!parse_btype(&pt, &ad1)) {
3815 if (l) {
3816 tcc_error("invalid type");
3817 } else {
3818 l = FUNC_OLD;
3819 goto old_proto;
3822 l = FUNC_NEW;
3823 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
3824 break;
3825 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
3826 if ((pt.t & VT_BTYPE) == VT_VOID)
3827 tcc_error("parameter declared as void");
3828 arg_size += (type_size(&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
3829 } else {
3830 old_proto:
3831 n = tok;
3832 if (n < TOK_UIDENT)
3833 expect("identifier");
3834 pt.t = VT_INT;
3835 next();
3837 convert_parameter_type(&pt);
3838 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
3839 *plast = s;
3840 plast = &s->next;
3841 if (tok == ')')
3842 break;
3843 skip(',');
3844 if (l == FUNC_NEW && tok == TOK_DOTS) {
3845 l = FUNC_ELLIPSIS;
3846 next();
3847 break;
3851 /* if no parameters, then old type prototype */
3852 if (l == 0)
3853 l = FUNC_OLD;
3854 skip(')');
3855 /* NOTE: const is ignored in returned type as it has a special
3856 meaning in gcc / C++ */
3857 type->t &= ~VT_CONSTANT;
3858 /* some ancient pre-K&R C allows a function to return an array
3859 and the array brackets to be put after the arguments, such
3860 that "int c()[]" means something like "int[] c()" */
3861 if (tok == '[') {
3862 next();
3863 skip(']'); /* only handle simple "[]" */
3864 type->t |= VT_PTR;
3866 /* we push a anonymous symbol which will contain the function prototype */
3867 ad->a.func_args = arg_size;
3868 s = sym_push(SYM_FIELD, type, 0, l);
3869 s->a = ad->a;
3870 s->next = first;
3871 type->t = VT_FUNC;
3872 type->ref = s;
3873 } else if (tok == '[') {
3874 int saved_nocode_wanted = nocode_wanted;
3875 /* array definition */
3876 next();
3877 if (tok == TOK_RESTRICT1)
3878 next();
3879 n = -1;
3880 t1 = 0;
3881 if (tok != ']') {
3882 if (!local_stack || (storage & VT_STATIC))
3883 vpushi(expr_const());
3884 else {
3885 /* VLAs (which can only happen with local_stack && !VT_STATIC)
3886 length must always be evaluated, even under nocode_wanted,
3887 so that its size slot is initialized (e.g. under sizeof
3888 or typeof). */
3889 nocode_wanted = 0;
3890 gexpr();
3892 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3893 n = vtop->c.i;
3894 if (n < 0)
3895 tcc_error("invalid array size");
3896 } else {
3897 if (!is_integer_btype(vtop->type.t & VT_BTYPE))
3898 tcc_error("size of variable length array should be an integer");
3899 t1 = VT_VLA;
3902 skip(']');
3903 /* parse next post type */
3904 post_type(type, ad, storage);
3905 if (type->t == VT_FUNC)
3906 tcc_error("declaration of an array of functions");
3907 t1 |= type->t & VT_VLA;
3909 if (t1 & VT_VLA) {
3910 loc -= type_size(&int_type, &align);
3911 loc &= -align;
3912 n = loc;
3914 vla_runtime_type_size(type, &align);
3915 gen_op('*');
3916 vset(&int_type, VT_LOCAL|VT_LVAL, n);
3917 vswap();
3918 vstore();
3920 if (n != -1)
3921 vpop();
3922 nocode_wanted = saved_nocode_wanted;
3924 /* we push an anonymous symbol which will contain the array
3925 element type */
3926 s = sym_push(SYM_FIELD, type, 0, n);
3927 type->t = (t1 ? VT_VLA : VT_ARRAY) | VT_PTR;
3928 type->ref = s;
3932 /* Parse a type declaration (except basic type), and return the type
3933 in 'type'. 'td' is a bitmask indicating which kind of type decl is
3934 expected. 'type' should contain the basic type. 'ad' is the
3935 attribute definition of the basic type. It can be modified by
3936 type_decl().
3938 static void type_decl(CType *type, AttributeDef *ad, int *v, int td)
3940 Sym *s;
3941 CType type1, *type2;
3942 int qualifiers, storage;
3944 while (tok == '*') {
3945 qualifiers = 0;
3946 redo:
3947 next();
3948 switch(tok) {
3949 case TOK_CONST1:
3950 case TOK_CONST2:
3951 case TOK_CONST3:
3952 qualifiers |= VT_CONSTANT;
3953 goto redo;
3954 case TOK_VOLATILE1:
3955 case TOK_VOLATILE2:
3956 case TOK_VOLATILE3:
3957 qualifiers |= VT_VOLATILE;
3958 goto redo;
3959 case TOK_RESTRICT1:
3960 case TOK_RESTRICT2:
3961 case TOK_RESTRICT3:
3962 goto redo;
3963 /* XXX: clarify attribute handling */
3964 case TOK_ATTRIBUTE1:
3965 case TOK_ATTRIBUTE2:
3966 parse_attribute(ad);
3967 break;
3969 mk_pointer(type);
3970 type->t |= qualifiers;
3973 /* recursive type */
3974 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
3975 type1.t = 0; /* XXX: same as int */
3976 if (tok == '(') {
3977 next();
3978 /* XXX: this is not correct to modify 'ad' at this point, but
3979 the syntax is not clear */
3980 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3981 parse_attribute(ad);
3982 type_decl(&type1, ad, v, td);
3983 skip(')');
3984 } else {
3985 /* type identifier */
3986 if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
3987 *v = tok;
3988 next();
3989 } else {
3990 if (!(td & TYPE_ABSTRACT))
3991 expect("identifier");
3992 *v = 0;
3995 storage = type->t & VT_STORAGE;
3996 type->t &= ~VT_STORAGE;
3997 post_type(type, ad, storage);
3998 type->t |= storage;
3999 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
4000 parse_attribute(ad);
4002 if (!type1.t)
4003 return;
4004 /* append type at the end of type1 */
4005 type2 = &type1;
4006 for(;;) {
4007 s = type2->ref;
4008 type2 = &s->type;
4009 if (!type2->t) {
4010 *type2 = *type;
4011 break;
4014 *type = type1;
4017 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
4018 ST_FUNC int lvalue_type(int t)
4020 int bt, r;
4021 r = VT_LVAL;
4022 bt = t & VT_BTYPE;
4023 if (bt == VT_BYTE || bt == VT_BOOL)
4024 r |= VT_LVAL_BYTE;
4025 else if (bt == VT_SHORT)
4026 r |= VT_LVAL_SHORT;
4027 else
4028 return r;
4029 if (t & VT_UNSIGNED)
4030 r |= VT_LVAL_UNSIGNED;
4031 return r;
4034 /* indirection with full error checking and bound check */
4035 ST_FUNC void indir(void)
4037 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
4038 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
4039 return;
4040 expect("pointer");
4042 if ((vtop->r & VT_LVAL) && !nocode_wanted)
4043 gv(RC_INT);
4044 vtop->type = *pointed_type(&vtop->type);
4045 /* Arrays and functions are never lvalues */
4046 if (!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_VLA)
4047 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
4048 vtop->r |= lvalue_type(vtop->type.t);
4049 /* if bound checking, the referenced pointer must be checked */
4050 #ifdef CONFIG_TCC_BCHECK
4051 if (tcc_state->do_bounds_check)
4052 vtop->r |= VT_MUSTBOUND;
4053 #endif
4057 /* pass a parameter to a function and do type checking and casting */
4058 static void gfunc_param_typed(Sym *func, Sym *arg)
4060 int func_type;
4061 CType type;
4063 func_type = func->c;
4064 if (func_type == FUNC_OLD ||
4065 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
4066 /* default casting : only need to convert float to double */
4067 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
4068 type.t = VT_DOUBLE;
4069 gen_cast(&type);
4070 } else if (vtop->type.t & VT_BITFIELD) {
4071 type.t = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
4072 type.ref = vtop->type.ref;
4073 gen_cast(&type);
4075 } else if (arg == NULL) {
4076 tcc_error("too many arguments to function");
4077 } else {
4078 type = arg->type;
4079 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
4080 gen_assign_cast(&type);
4084 /* parse an expression of the form '(type)' or '(expr)' and return its
4085 type */
4086 static void parse_expr_type(CType *type)
4088 int n;
4089 AttributeDef ad;
4091 skip('(');
4092 if (parse_btype(type, &ad)) {
4093 type_decl(type, &ad, &n, TYPE_ABSTRACT);
4094 } else {
4095 expr_type(type);
4097 skip(')');
4100 static void parse_type(CType *type)
4102 AttributeDef ad;
4103 int n;
4105 if (!parse_btype(type, &ad)) {
4106 expect("type");
4108 type_decl(type, &ad, &n, TYPE_ABSTRACT);
4111 static void vpush_tokc(int t)
4113 CType type;
4114 type.t = t;
4115 type.ref = 0;
4116 vsetc(&type, VT_CONST, &tokc);
4119 ST_FUNC void unary(void)
4121 int n, t, align, size, r, sizeof_caller;
4122 CType type;
4123 Sym *s;
4124 AttributeDef ad;
4126 sizeof_caller = in_sizeof;
4127 in_sizeof = 0;
4128 /* XXX: GCC 2.95.3 does not generate a table although it should be
4129 better here */
4130 tok_next:
4131 switch(tok) {
4132 case TOK_EXTENSION:
4133 next();
4134 goto tok_next;
4135 case TOK_CINT:
4136 case TOK_CCHAR:
4137 case TOK_LCHAR:
4138 vpushi(tokc.i);
4139 next();
4140 break;
4141 case TOK_CUINT:
4142 vpush_tokc(VT_INT | VT_UNSIGNED);
4143 next();
4144 break;
4145 case TOK_CLLONG:
4146 vpush_tokc(VT_LLONG);
4147 next();
4148 break;
4149 case TOK_CULLONG:
4150 vpush_tokc(VT_LLONG | VT_UNSIGNED);
4151 next();
4152 break;
4153 case TOK_CFLOAT:
4154 vpush_tokc(VT_FLOAT);
4155 next();
4156 break;
4157 case TOK_CDOUBLE:
4158 vpush_tokc(VT_DOUBLE);
4159 next();
4160 break;
4161 case TOK_CLDOUBLE:
4162 vpush_tokc(VT_LDOUBLE);
4163 next();
4164 break;
4165 case TOK___FUNCTION__:
4166 if (!gnu_ext)
4167 goto tok_identifier;
4168 /* fall thru */
4169 case TOK___FUNC__:
4171 void *ptr;
4172 int len;
4173 /* special function name identifier */
4174 len = strlen(funcname) + 1;
4175 /* generate char[len] type */
4176 type.t = VT_BYTE;
4177 mk_pointer(&type);
4178 type.t |= VT_ARRAY;
4179 type.ref->c = len;
4180 vpush_ref(&type, data_section, data_section->data_offset, len);
4181 ptr = section_ptr_add(data_section, len);
4182 memcpy(ptr, funcname, len);
4183 next();
4185 break;
4186 case TOK_LSTR:
4187 #ifdef TCC_TARGET_PE
4188 t = VT_SHORT | VT_UNSIGNED;
4189 #else
4190 t = VT_INT;
4191 #endif
4192 goto str_init;
4193 case TOK_STR:
4194 /* string parsing */
4195 t = VT_BYTE;
4196 str_init:
4197 if (tcc_state->warn_write_strings)
4198 t |= VT_CONSTANT;
4199 type.t = t;
4200 mk_pointer(&type);
4201 type.t |= VT_ARRAY;
4202 memset(&ad, 0, sizeof(AttributeDef));
4203 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, 0);
4204 break;
4205 case '(':
4206 next();
4207 /* cast ? */
4208 if (parse_btype(&type, &ad)) {
4209 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
4210 skip(')');
4211 /* check ISOC99 compound literal */
4212 if (tok == '{') {
4213 /* data is allocated locally by default */
4214 if (global_expr)
4215 r = VT_CONST;
4216 else
4217 r = VT_LOCAL;
4218 /* all except arrays are lvalues */
4219 if (!(type.t & VT_ARRAY))
4220 r |= lvalue_type(type.t);
4221 memset(&ad, 0, sizeof(AttributeDef));
4222 decl_initializer_alloc(&type, &ad, r, 1, 0, 0);
4223 } else {
4224 if (sizeof_caller) {
4225 vpush(&type);
4226 return;
4228 unary();
4229 gen_cast(&type);
4231 } else if (tok == '{') {
4232 if (const_wanted)
4233 tcc_error("expected constant");
4234 /* save all registers */
4235 if (!nocode_wanted)
4236 save_regs(0);
4237 /* statement expression : we do not accept break/continue
4238 inside as GCC does */
4239 block(NULL, NULL, 1);
4240 skip(')');
4241 } else {
4242 gexpr();
4243 skip(')');
4245 break;
4246 case '*':
4247 next();
4248 unary();
4249 indir();
4250 break;
4251 case '&':
4252 next();
4253 unary();
4254 /* functions names must be treated as function pointers,
4255 except for unary '&' and sizeof. Since we consider that
4256 functions are not lvalues, we only have to handle it
4257 there and in function calls. */
4258 /* arrays can also be used although they are not lvalues */
4259 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
4260 !(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
4261 test_lvalue();
4262 mk_pointer(&vtop->type);
4263 gaddrof();
4264 break;
4265 case '!':
4266 next();
4267 unary();
4268 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4269 CType boolean;
4270 boolean.t = VT_BOOL;
4271 gen_cast(&boolean);
4272 vtop->c.i = !vtop->c.i;
4273 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
4274 vtop->c.i ^= 1;
4275 else {
4276 save_regs(1);
4277 vseti(VT_JMP, gvtst(1, 0));
4279 break;
4280 case '~':
4281 next();
4282 unary();
4283 vpushi(-1);
4284 gen_op('^');
4285 break;
4286 case '+':
4287 next();
4288 unary();
4289 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
4290 tcc_error("pointer not accepted for unary plus");
4291 /* In order to force cast, we add zero, except for floating point
4292 where we really need an noop (otherwise -0.0 will be transformed
4293 into +0.0). */
4294 if (!is_float(vtop->type.t)) {
4295 vpushi(0);
4296 gen_op('+');
4298 break;
4299 case TOK_SIZEOF:
4300 case TOK_ALIGNOF1:
4301 case TOK_ALIGNOF2:
4302 t = tok;
4303 next();
4304 in_sizeof++;
4305 unary_type(&type); // Perform a in_sizeof = 0;
4306 size = type_size(&type, &align);
4307 if (t == TOK_SIZEOF) {
4308 if (!(type.t & VT_VLA)) {
4309 if (size < 0)
4310 tcc_error("sizeof applied to an incomplete type");
4311 vpushs(size);
4312 } else {
4313 vla_runtime_type_size(&type, &align);
4315 } else {
4316 vpushs(align);
4318 vtop->type.t |= VT_UNSIGNED;
4319 break;
4321 case TOK_builtin_expect:
4323 /* __builtin_expect is a no-op for now */
4324 int saved_nocode_wanted;
4325 next();
4326 skip('(');
4327 expr_eq();
4328 skip(',');
4329 saved_nocode_wanted = nocode_wanted;
4330 nocode_wanted = 1;
4331 expr_lor_const();
4332 vpop();
4333 nocode_wanted = saved_nocode_wanted;
4334 skip(')');
4336 break;
4337 case TOK_builtin_types_compatible_p:
4339 CType type1, type2;
4340 next();
4341 skip('(');
4342 parse_type(&type1);
4343 skip(',');
4344 parse_type(&type2);
4345 skip(')');
4346 type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
4347 type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
4348 vpushi(is_compatible_types(&type1, &type2));
4350 break;
4351 case TOK_builtin_choose_expr:
4353 int saved_nocode_wanted, c;
4354 next();
4355 skip('(');
4356 c = expr_const();
4357 skip(',');
4358 if (!c) {
4359 saved_nocode_wanted = nocode_wanted;
4360 nocode_wanted = 1;
4362 expr_eq();
4363 if (!c) {
4364 vpop();
4365 nocode_wanted = saved_nocode_wanted;
4367 skip(',');
4368 if (c) {
4369 saved_nocode_wanted = nocode_wanted;
4370 nocode_wanted = 1;
4372 expr_eq();
4373 if (c) {
4374 vpop();
4375 nocode_wanted = saved_nocode_wanted;
4377 skip(')');
4379 break;
4380 case TOK_builtin_constant_p:
4382 int saved_nocode_wanted, res;
4383 next();
4384 skip('(');
4385 saved_nocode_wanted = nocode_wanted;
4386 nocode_wanted = 1;
4387 gexpr();
4388 res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
4389 vpop();
4390 nocode_wanted = saved_nocode_wanted;
4391 skip(')');
4392 vpushi(res);
4394 break;
4395 case TOK_builtin_frame_address:
4396 case TOK_builtin_return_address:
4398 int tok1 = tok;
4399 int level;
4400 CType type;
4401 next();
4402 skip('(');
4403 if (tok != TOK_CINT) {
4404 tcc_error("%s only takes positive integers",
4405 tok1 == TOK_builtin_return_address ?
4406 "__builtin_return_address" :
4407 "__builtin_frame_address");
4409 level = (uint32_t)tokc.i;
4410 next();
4411 skip(')');
4412 type.t = VT_VOID;
4413 mk_pointer(&type);
4414 vset(&type, VT_LOCAL, 0); /* local frame */
4415 while (level--) {
4416 mk_pointer(&vtop->type);
4417 indir(); /* -> parent frame */
4419 if (tok1 == TOK_builtin_return_address) {
4420 // assume return address is just above frame pointer on stack
4421 vpushi(PTR_SIZE);
4422 gen_op('+');
4423 mk_pointer(&vtop->type);
4424 indir();
4427 break;
4428 #ifdef TCC_TARGET_X86_64
4429 #ifdef TCC_TARGET_PE
4430 case TOK_builtin_va_start:
4432 next();
4433 skip('(');
4434 expr_eq();
4435 skip(',');
4436 expr_eq();
4437 skip(')');
4438 if ((vtop->r & VT_VALMASK) != VT_LOCAL)
4439 tcc_error("__builtin_va_start expects a local variable");
4440 vtop->r &= ~(VT_LVAL | VT_REF);
4441 vtop->type = char_pointer_type;
4442 vtop->c.i += 8;
4443 vstore();
4445 break;
4446 #else
4447 case TOK_builtin_va_arg_types:
4449 CType type;
4450 next();
4451 skip('(');
4452 parse_type(&type);
4453 skip(')');
4454 vpushi(classify_x86_64_va_arg(&type));
4456 break;
4457 #endif
4458 #endif
4460 #ifdef TCC_TARGET_ARM64
4461 case TOK___va_start: {
4462 if (nocode_wanted)
4463 tcc_error("statement in global scope");
4464 next();
4465 skip('(');
4466 expr_eq();
4467 skip(',');
4468 expr_eq();
4469 skip(')');
4470 //xx check types
4471 gen_va_start();
4472 vpushi(0);
4473 vtop->type.t = VT_VOID;
4474 break;
4476 case TOK___va_arg: {
4477 CType type;
4478 if (nocode_wanted)
4479 tcc_error("statement in global scope");
4480 next();
4481 skip('(');
4482 expr_eq();
4483 skip(',');
4484 parse_type(&type);
4485 skip(')');
4486 //xx check types
4487 gen_va_arg(&type);
4488 vtop->type = type;
4489 break;
4491 case TOK___arm64_clear_cache: {
4492 next();
4493 skip('(');
4494 expr_eq();
4495 skip(',');
4496 expr_eq();
4497 skip(')');
4498 gen_clear_cache();
4499 vpushi(0);
4500 vtop->type.t = VT_VOID;
4501 break;
4503 #endif
4504 /* pre operations */
4505 case TOK_INC:
4506 case TOK_DEC:
4507 t = tok;
4508 next();
4509 unary();
4510 inc(0, t);
4511 break;
4512 case '-':
4513 next();
4514 unary();
4515 t = vtop->type.t & VT_BTYPE;
4516 if (is_float(t)) {
4517 /* In IEEE negate(x) isn't subtract(0,x), but rather
4518 subtract(-0, x). */
4519 vpush(&vtop->type);
4520 if (t == VT_FLOAT)
4521 vtop->c.f = -0.0f;
4522 else if (t == VT_DOUBLE)
4523 vtop->c.d = -0.0;
4524 else
4525 vtop->c.ld = -0.0;
4526 } else
4527 vpushi(0);
4528 vswap();
4529 gen_op('-');
4530 break;
4531 case TOK_LAND:
4532 if (!gnu_ext)
4533 goto tok_identifier;
4534 next();
4535 /* allow to take the address of a label */
4536 if (tok < TOK_UIDENT)
4537 expect("label identifier");
4538 s = label_find(tok);
4539 if (!s) {
4540 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
4541 } else {
4542 if (s->r == LABEL_DECLARED)
4543 s->r = LABEL_FORWARD;
4545 if (!s->type.t) {
4546 s->type.t = VT_VOID;
4547 mk_pointer(&s->type);
4548 s->type.t |= VT_STATIC;
4550 vpushsym(&s->type, s);
4551 next();
4552 break;
4554 // special qnan , snan and infinity values
4555 case TOK___NAN__:
4556 vpush64(VT_DOUBLE, 0x7ff8000000000000ULL);
4557 next();
4558 break;
4559 case TOK___SNAN__:
4560 vpush64(VT_DOUBLE, 0x7ff0000000000001ULL);
4561 next();
4562 break;
4563 case TOK___INF__:
4564 vpush64(VT_DOUBLE, 0x7ff0000000000000ULL);
4565 next();
4566 break;
4568 default:
4569 tok_identifier:
4570 t = tok;
4571 next();
4572 if (t < TOK_UIDENT)
4573 expect("identifier");
4574 s = sym_find(t);
4575 if (!s) {
4576 const char *name = get_tok_str(t, NULL);
4577 if (tok != '(')
4578 tcc_error("'%s' undeclared", name);
4579 /* for simple function calls, we tolerate undeclared
4580 external reference to int() function */
4581 if (tcc_state->warn_implicit_function_declaration
4582 #ifdef TCC_TARGET_PE
4583 /* people must be warned about using undeclared WINAPI functions
4584 (which usually start with uppercase letter) */
4585 || (name[0] >= 'A' && name[0] <= 'Z')
4586 #endif
4588 tcc_warning("implicit declaration of function '%s'", name);
4589 s = external_global_sym(t, &func_old_type, 0);
4591 if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
4592 (VT_STATIC | VT_INLINE | VT_FUNC)) {
4593 /* if referencing an inline function, then we generate a
4594 symbol to it if not already done. It will have the
4595 effect to generate code for it at the end of the
4596 compilation unit. Inline function as always
4597 generated in the text section. */
4598 if (!s->c && !nocode_wanted)
4599 put_extern_sym(s, text_section, 0, 0);
4600 r = VT_SYM | VT_CONST;
4601 } else {
4602 r = s->r;
4603 /* A symbol that has a register is a local register variable,
4604 which starts out as VT_LOCAL value. */
4605 if ((r & VT_VALMASK) < VT_CONST)
4606 r = (r & ~VT_VALMASK) | VT_LOCAL;
4608 vset(&s->type, r, s->c);
4609 /* Point to s as backpointer (even without r&VT_SYM).
4610 Will be used by at least the x86 inline asm parser for
4611 regvars. */
4612 vtop->sym = s;
4613 if (vtop->r & VT_SYM) {
4614 vtop->c.i = 0;
4616 break;
4619 /* post operations */
4620 while (1) {
4621 if (tok == TOK_INC || tok == TOK_DEC) {
4622 inc(1, tok);
4623 next();
4624 } else if (tok == '.' || tok == TOK_ARROW || tok == TOK_CDOUBLE) {
4625 int qualifiers;
4626 /* field */
4627 if (tok == TOK_ARROW)
4628 indir();
4629 qualifiers = vtop->type.t & (VT_CONSTANT | VT_VOLATILE);
4630 test_lvalue();
4631 gaddrof();
4632 /* expect pointer on structure */
4633 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
4634 expect("struct or union");
4635 if (tok == TOK_CDOUBLE)
4636 expect("field name");
4637 next();
4638 if (tok == TOK_CINT || tok == TOK_CUINT)
4639 expect("field name");
4640 s = find_field(&vtop->type, tok);
4641 if (!s)
4642 tcc_error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, &tokc));
4643 /* add field offset to pointer */
4644 vtop->type = char_pointer_type; /* change type to 'char *' */
4645 vpushi(s->c);
4646 gen_op('+');
4647 /* change type to field type, and set to lvalue */
4648 vtop->type = s->type;
4649 vtop->type.t |= qualifiers;
4650 /* an array is never an lvalue */
4651 if (!(vtop->type.t & VT_ARRAY)) {
4652 vtop->r |= lvalue_type(vtop->type.t);
4653 #ifdef CONFIG_TCC_BCHECK
4654 /* if bound checking, the referenced pointer must be checked */
4655 if (tcc_state->do_bounds_check && (vtop->r & VT_VALMASK) != VT_LOCAL)
4656 vtop->r |= VT_MUSTBOUND;
4657 #endif
4659 next();
4660 } else if (tok == '[') {
4661 next();
4662 gexpr();
4663 gen_op('+');
4664 indir();
4665 skip(']');
4666 } else if (tok == '(') {
4667 SValue ret;
4668 Sym *sa;
4669 int nb_args, ret_nregs, ret_align, regsize, variadic;
4671 /* function call */
4672 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
4673 /* pointer test (no array accepted) */
4674 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
4675 vtop->type = *pointed_type(&vtop->type);
4676 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
4677 goto error_func;
4678 } else {
4679 error_func:
4680 expect("function pointer");
4682 } else {
4683 vtop->r &= ~VT_LVAL; /* no lvalue */
4685 /* get return type */
4686 s = vtop->type.ref;
4687 next();
4688 sa = s->next; /* first parameter */
4689 nb_args = 0;
4690 ret.r2 = VT_CONST;
4691 /* compute first implicit argument if a structure is returned */
4692 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
4693 variadic = (s->c == FUNC_ELLIPSIS);
4694 ret_nregs = gfunc_sret(&s->type, variadic, &ret.type,
4695 &ret_align, &regsize);
4696 if (!ret_nregs) {
4697 /* get some space for the returned structure */
4698 size = type_size(&s->type, &align);
4699 #ifdef TCC_TARGET_ARM64
4700 /* On arm64, a small struct is return in registers.
4701 It is much easier to write it to memory if we know
4702 that we are allowed to write some extra bytes, so
4703 round the allocated space up to a power of 2: */
4704 if (size < 16)
4705 while (size & (size - 1))
4706 size = (size | (size - 1)) + 1;
4707 #endif
4708 loc = (loc - size) & -align;
4709 ret.type = s->type;
4710 ret.r = VT_LOCAL | VT_LVAL;
4711 /* pass it as 'int' to avoid structure arg passing
4712 problems */
4713 vseti(VT_LOCAL, loc);
4714 ret.c = vtop->c;
4715 nb_args++;
4717 } else {
4718 ret_nregs = 1;
4719 ret.type = s->type;
4722 if (ret_nregs) {
4723 /* return in register */
4724 if (is_float(ret.type.t)) {
4725 ret.r = reg_fret(ret.type.t);
4726 #ifdef TCC_TARGET_X86_64
4727 if ((ret.type.t & VT_BTYPE) == VT_QFLOAT)
4728 ret.r2 = REG_QRET;
4729 #endif
4730 } else {
4731 #ifndef TCC_TARGET_ARM64
4732 #ifdef TCC_TARGET_X86_64
4733 if ((ret.type.t & VT_BTYPE) == VT_QLONG)
4734 #else
4735 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
4736 #endif
4737 ret.r2 = REG_LRET;
4738 #endif
4739 ret.r = REG_IRET;
4741 ret.c.i = 0;
4743 if (tok != ')') {
4744 for(;;) {
4745 expr_eq();
4746 gfunc_param_typed(s, sa);
4747 nb_args++;
4748 if (sa)
4749 sa = sa->next;
4750 if (tok == ')')
4751 break;
4752 skip(',');
4755 if (sa)
4756 tcc_error("too few arguments to function");
4757 skip(')');
4758 if (!nocode_wanted) {
4759 gfunc_call(nb_args);
4760 } else {
4761 vtop -= (nb_args + 1);
4764 /* return value */
4765 for (r = ret.r + ret_nregs + !ret_nregs; r-- > ret.r;) {
4766 vsetc(&ret.type, r, &ret.c);
4767 vtop->r2 = ret.r2; /* Loop only happens when r2 is VT_CONST */
4770 /* handle packed struct return */
4771 if (((s->type.t & VT_BTYPE) == VT_STRUCT) && ret_nregs) {
4772 int addr, offset;
4774 size = type_size(&s->type, &align);
4775 /* We're writing whole regs often, make sure there's enough
4776 space. Assume register size is power of 2. */
4777 if (regsize > align)
4778 align = regsize;
4779 loc = (loc - size) & -align;
4780 addr = loc;
4781 offset = 0;
4782 for (;;) {
4783 vset(&ret.type, VT_LOCAL | VT_LVAL, addr + offset);
4784 vswap();
4785 vstore();
4786 vtop--;
4787 if (--ret_nregs == 0)
4788 break;
4789 offset += regsize;
4791 vset(&s->type, VT_LOCAL | VT_LVAL, addr);
4793 } else {
4794 break;
4799 ST_FUNC void expr_prod(void)
4801 int t;
4803 unary();
4804 while (tok == '*' || tok == '/' || tok == '%') {
4805 t = tok;
4806 next();
4807 unary();
4808 gen_op(t);
4812 ST_FUNC void expr_sum(void)
4814 int t;
4816 expr_prod();
4817 while (tok == '+' || tok == '-') {
4818 t = tok;
4819 next();
4820 expr_prod();
4821 gen_op(t);
4825 static void expr_shift(void)
4827 int t;
4829 expr_sum();
4830 while (tok == TOK_SHL || tok == TOK_SAR) {
4831 t = tok;
4832 next();
4833 expr_sum();
4834 gen_op(t);
4838 static void expr_cmp(void)
4840 int t;
4842 expr_shift();
4843 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
4844 tok == TOK_ULT || tok == TOK_UGE) {
4845 t = tok;
4846 next();
4847 expr_shift();
4848 gen_op(t);
4852 static void expr_cmpeq(void)
4854 int t;
4856 expr_cmp();
4857 while (tok == TOK_EQ || tok == TOK_NE) {
4858 t = tok;
4859 next();
4860 expr_cmp();
4861 gen_op(t);
4865 static void expr_and(void)
4867 expr_cmpeq();
4868 while (tok == '&') {
4869 next();
4870 expr_cmpeq();
4871 gen_op('&');
4875 static void expr_xor(void)
4877 expr_and();
4878 while (tok == '^') {
4879 next();
4880 expr_and();
4881 gen_op('^');
4885 static void expr_or(void)
4887 expr_xor();
4888 while (tok == '|') {
4889 next();
4890 expr_xor();
4891 gen_op('|');
4895 /* XXX: fix this mess */
4896 static void expr_land_const(void)
4898 expr_or();
4899 while (tok == TOK_LAND) {
4900 next();
4901 expr_or();
4902 gen_op(TOK_LAND);
4905 static void expr_lor_const(void)
4907 expr_land_const();
4908 while (tok == TOK_LOR) {
4909 next();
4910 expr_land_const();
4911 gen_op(TOK_LOR);
4915 static void expr_land(void)
4917 expr_or();
4918 if (tok == TOK_LAND) {
4919 int t = 0;
4920 for(;;) {
4921 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4922 CType ctb;
4923 ctb.t = VT_BOOL;
4924 gen_cast(&ctb);
4925 if (vtop->c.i) {
4926 vpop();
4927 } else {
4928 int saved_nocode_wanted = nocode_wanted;
4929 nocode_wanted = 1;
4930 while (tok == TOK_LAND) {
4931 next();
4932 expr_or();
4933 vpop();
4935 if (t)
4936 gsym(t);
4937 nocode_wanted = saved_nocode_wanted;
4938 gen_cast(&int_type);
4939 break;
4941 } else {
4942 if (!t)
4943 save_regs(1);
4944 t = gvtst(1, t);
4946 if (tok != TOK_LAND) {
4947 if (t)
4948 vseti(VT_JMPI, t);
4949 else
4950 vpushi(1);
4951 break;
4953 next();
4954 expr_or();
4959 static void expr_lor(void)
4961 expr_land();
4962 if (tok == TOK_LOR) {
4963 int t = 0;
4964 for(;;) {
4965 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4966 CType ctb;
4967 ctb.t = VT_BOOL;
4968 gen_cast(&ctb);
4969 if (!vtop->c.i) {
4970 vpop();
4971 } else {
4972 int saved_nocode_wanted = nocode_wanted;
4973 nocode_wanted = 1;
4974 while (tok == TOK_LOR) {
4975 next();
4976 expr_land();
4977 vpop();
4979 if (t)
4980 gsym(t);
4981 nocode_wanted = saved_nocode_wanted;
4982 gen_cast(&int_type);
4983 break;
4985 } else {
4986 if (!t)
4987 save_regs(1);
4988 t = gvtst(0, t);
4990 if (tok != TOK_LOR) {
4991 if (t)
4992 vseti(VT_JMP, t);
4993 else
4994 vpushi(0);
4995 break;
4997 next();
4998 expr_land();
5003 /* Assuming vtop is a value used in a conditional context
5004 (i.e. compared with zero) return 0 if it's false, 1 if
5005 true and -1 if it can't be statically determined. */
5006 static int condition_3way(void)
5008 int c = -1;
5009 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST &&
5010 (!(vtop->r & VT_SYM) ||
5011 !(vtop->sym->type.t & VT_WEAK))) {
5012 CType boolean;
5013 boolean.t = VT_BOOL;
5014 vdup();
5015 gen_cast(&boolean);
5016 c = vtop->c.i;
5017 vpop();
5019 return c;
5022 static void expr_cond(void)
5024 int tt, u, r1, r2, rc, t1, t2, bt1, bt2, islv;
5025 int c;
5026 SValue sv;
5027 CType type, type1, type2;
5029 expr_lor();
5030 if (tok == '?') {
5031 next();
5032 c = condition_3way();
5033 if (c >= 0) {
5034 int saved_nocode_wanted = nocode_wanted;
5035 if (c) {
5036 if (tok != ':' || !gnu_ext) {
5037 vpop();
5038 gexpr();
5040 skip(':');
5041 nocode_wanted = 1;
5042 expr_cond();
5043 vpop();
5044 nocode_wanted = saved_nocode_wanted;
5045 } else {
5046 vpop();
5047 if (tok != ':' || !gnu_ext) {
5048 nocode_wanted = 1;
5049 gexpr();
5050 vpop();
5051 nocode_wanted = saved_nocode_wanted;
5053 skip(':');
5054 expr_cond();
5057 else {
5058 /* XXX This doesn't handle nocode_wanted correctly at all.
5059 It unconditionally calls gv/gvtst and friends. That's
5060 the case for many of the expr_ routines. Currently
5061 that should generate only useless code, but depending
5062 on other operand handling this might also generate
5063 pointer derefs for lvalue conversions whose result
5064 is useless, but nevertheless can lead to segfault.
5066 Somewhen we need to overhaul the whole nocode_wanted
5067 handling. */
5068 if (vtop != vstack) {
5069 /* needed to avoid having different registers saved in
5070 each branch */
5071 if (is_float(vtop->type.t)) {
5072 rc = RC_FLOAT;
5073 #ifdef TCC_TARGET_X86_64
5074 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
5075 rc = RC_ST0;
5077 #endif
5079 else
5080 rc = RC_INT;
5081 gv(rc);
5082 save_regs(1);
5084 if (tok == ':' && gnu_ext) {
5085 gv_dup();
5086 tt = gvtst(1, 0);
5087 } else {
5088 tt = gvtst(1, 0);
5089 gexpr();
5091 type1 = vtop->type;
5092 sv = *vtop; /* save value to handle it later */
5093 vtop--; /* no vpop so that FP stack is not flushed */
5094 skip(':');
5095 u = gjmp(0);
5096 gsym(tt);
5097 expr_cond();
5098 type2 = vtop->type;
5100 t1 = type1.t;
5101 bt1 = t1 & VT_BTYPE;
5102 t2 = type2.t;
5103 bt2 = t2 & VT_BTYPE;
5104 /* cast operands to correct type according to ISOC rules */
5105 if (is_float(bt1) || is_float(bt2)) {
5106 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
5107 type.t = VT_LDOUBLE;
5108 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
5109 type.t = VT_DOUBLE;
5110 } else {
5111 type.t = VT_FLOAT;
5113 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
5114 /* cast to biggest op */
5115 type.t = VT_LLONG;
5116 /* convert to unsigned if it does not fit in a long long */
5117 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
5118 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
5119 type.t |= VT_UNSIGNED;
5120 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
5121 /* If one is a null ptr constant the result type
5122 is the other. */
5123 if (is_null_pointer (vtop))
5124 type = type1;
5125 else if (is_null_pointer (&sv))
5126 type = type2;
5127 /* XXX: test pointer compatibility, C99 has more elaborate
5128 rules here. */
5129 else
5130 type = type1;
5131 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
5132 /* XXX: test function pointer compatibility */
5133 type = bt1 == VT_FUNC ? type1 : type2;
5134 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
5135 /* XXX: test structure compatibility */
5136 type = bt1 == VT_STRUCT ? type1 : type2;
5137 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
5138 /* NOTE: as an extension, we accept void on only one side */
5139 type.t = VT_VOID;
5140 } else {
5141 /* integer operations */
5142 type.t = VT_INT;
5143 /* convert to unsigned if it does not fit in an integer */
5144 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
5145 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
5146 type.t |= VT_UNSIGNED;
5148 /* keep structs lvalue by transforming `(expr ? a : b)` to `*(expr ? &a : &b)` so
5149 that `(expr ? a : b).mem` does not error with "lvalue expected" */
5150 islv = (vtop->r & VT_LVAL) && (sv.r & VT_LVAL) && VT_STRUCT == (type.t & VT_BTYPE);
5152 /* now we convert second operand */
5153 gen_cast(&type);
5154 if (islv) {
5155 mk_pointer(&vtop->type);
5156 gaddrof();
5158 else if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
5159 gaddrof();
5160 rc = RC_INT;
5161 if (is_float(type.t)) {
5162 rc = RC_FLOAT;
5163 #ifdef TCC_TARGET_X86_64
5164 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
5165 rc = RC_ST0;
5167 #endif
5168 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
5169 /* for long longs, we use fixed registers to avoid having
5170 to handle a complicated move */
5171 rc = RC_IRET;
5174 r2 = gv(rc);
5175 /* this is horrible, but we must also convert first
5176 operand */
5177 tt = gjmp(0);
5178 gsym(u);
5179 /* put again first value and cast it */
5180 *vtop = sv;
5181 gen_cast(&type);
5182 if (islv) {
5183 mk_pointer(&vtop->type);
5184 gaddrof();
5186 else if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
5187 gaddrof();
5188 r1 = gv(rc);
5189 move_reg(r2, r1, type.t);
5190 vtop->r = r2;
5191 gsym(tt);
5192 if (islv)
5193 indir();
5198 static void expr_eq(void)
5200 int t;
5202 expr_cond();
5203 if (tok == '=' ||
5204 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
5205 tok == TOK_A_XOR || tok == TOK_A_OR ||
5206 tok == TOK_A_SHL || tok == TOK_A_SAR) {
5207 test_lvalue();
5208 t = tok;
5209 next();
5210 if (t == '=') {
5211 expr_eq();
5212 } else {
5213 vdup();
5214 expr_eq();
5215 gen_op(t & 0x7f);
5217 vstore();
5221 ST_FUNC void gexpr(void)
5223 while (1) {
5224 expr_eq();
5225 if (tok != ',')
5226 break;
5227 vpop();
5228 next();
5232 /* parse an expression and return its type without any side effect. */
5233 static void expr_type(CType *type)
5235 int saved_nocode_wanted;
5237 saved_nocode_wanted = nocode_wanted;
5238 nocode_wanted = 1;
5239 gexpr();
5240 *type = vtop->type;
5241 vpop();
5242 nocode_wanted = saved_nocode_wanted;
5245 /* parse a unary expression and return its type without any side
5246 effect. */
5247 static void unary_type(CType *type)
5249 int a;
5251 a = nocode_wanted;
5252 nocode_wanted = 1;
5253 unary();
5254 *type = vtop->type;
5255 vpop();
5256 nocode_wanted = a;
5259 /* parse a constant expression and return value in vtop. */
5260 static void expr_const1(void)
5262 int a;
5263 a = const_wanted;
5264 const_wanted = 1;
5265 expr_cond();
5266 const_wanted = a;
5269 /* parse an integer constant and return its value. */
5270 ST_FUNC int expr_const(void)
5272 int c;
5273 expr_const1();
5274 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
5275 expect("constant expression");
5276 c = vtop->c.i;
5277 vpop();
5278 return c;
5281 /* return the label token if current token is a label, otherwise
5282 return zero */
5283 static int is_label(void)
5285 int last_tok;
5287 /* fast test first */
5288 if (tok < TOK_UIDENT)
5289 return 0;
5290 /* no need to save tokc because tok is an identifier */
5291 last_tok = tok;
5292 next();
5293 if (tok == ':') {
5294 next();
5295 return last_tok;
5296 } else {
5297 unget_tok(last_tok);
5298 return 0;
5302 static void label_or_decl(int l)
5304 int last_tok;
5306 /* fast test first */
5307 if (tok >= TOK_UIDENT)
5309 /* no need to save tokc because tok is an identifier */
5310 last_tok = tok;
5311 next();
5312 if (tok == ':') {
5313 unget_tok(last_tok);
5314 return;
5316 unget_tok(last_tok);
5318 decl(l);
5321 static int case_cmp(const void *pa, const void *pb)
5323 int a = (*(struct case_t**) pa)->v1;
5324 int b = (*(struct case_t**) pb)->v1;
5325 return a < b ? -1 : a > b;
5328 static int gcase(struct case_t **base, int len, int case_reg, int *bsym)
5330 struct case_t *p;
5331 int e;
5332 while (len > 4) {
5333 /* binary search */
5334 p = base[len/2];
5335 vseti(case_reg, 0);
5336 vdup();
5337 vpushi(p->v2);
5338 gen_op(TOK_LE);
5339 e = gtst(1, 0);
5340 case_reg = gv(RC_INT);
5341 vpop();
5342 vseti(case_reg, 0);
5343 vdup();
5344 vpushi(p->v1);
5345 gen_op(TOK_GE);
5346 gtst_addr(0, p->sym); /* v1 <= x <= v2 */
5347 case_reg = gv(RC_INT);
5348 vpop();
5349 /* x < v1 */
5350 case_reg = gcase(base, len/2, case_reg, bsym);
5351 if (cur_switch->def_sym)
5352 gjmp_addr(cur_switch->def_sym);
5353 else
5354 *bsym = gjmp(*bsym);
5355 /* x > v2 */
5356 gsym(e);
5357 e = len/2 + 1;
5358 base += e; len -= e;
5360 /* linear scan */
5361 while (len--) {
5362 p = *base++;
5363 vseti(case_reg, 0);
5364 vdup();
5365 vpushi(p->v2);
5366 if (p->v1 == p->v2) {
5367 gen_op(TOK_EQ);
5368 gtst_addr(0, p->sym);
5369 } else {
5370 gen_op(TOK_LE);
5371 e = gtst(1, 0);
5372 case_reg = gv(RC_INT);
5373 vpop();
5374 vseti(case_reg, 0);
5375 vdup();
5376 vpushi(p->v1);
5377 gen_op(TOK_GE);
5378 gtst_addr(0, p->sym);
5379 gsym(e);
5381 case_reg = gv(RC_INT);
5382 vpop();
5384 return case_reg;
5387 static void block(int *bsym, int *csym, int is_expr)
5389 int a, b, c, d, cond;
5390 Sym *s;
5392 /* generate line number info */
5393 if (tcc_state->do_debug &&
5394 (last_line_num != file->line_num || last_ind != ind)) {
5395 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
5396 last_ind = ind;
5397 last_line_num = file->line_num;
5400 if (is_expr) {
5401 /* default return value is (void) */
5402 vpushi(0);
5403 vtop->type.t = VT_VOID;
5406 if (tok == TOK_IF) {
5407 /* if test */
5408 int saved_nocode_wanted = nocode_wanted;
5409 next();
5410 skip('(');
5411 gexpr();
5412 skip(')');
5413 cond = condition_3way();
5414 if (cond == 0)
5415 nocode_wanted |= 2;
5416 a = gvtst(1, 0);
5417 block(bsym, csym, 0);
5418 if (cond != 1)
5419 nocode_wanted = saved_nocode_wanted;
5420 c = tok;
5421 if (c == TOK_ELSE) {
5422 next();
5423 if (cond == 1)
5424 nocode_wanted |= 2;
5425 d = gjmp(0);
5426 gsym(a);
5427 block(bsym, csym, 0);
5428 gsym(d); /* patch else jmp */
5429 if (cond != 0)
5430 nocode_wanted = saved_nocode_wanted;
5431 } else
5432 gsym(a);
5433 } else if (tok == TOK_WHILE) {
5434 int saved_nocode_wanted;
5435 nocode_wanted &= ~2;
5436 next();
5437 d = ind;
5438 vla_sp_restore();
5439 skip('(');
5440 gexpr();
5441 skip(')');
5442 a = gvtst(1, 0);
5443 b = 0;
5444 ++local_scope;
5445 saved_nocode_wanted = nocode_wanted;
5446 block(&a, &b, 0);
5447 nocode_wanted = saved_nocode_wanted;
5448 --local_scope;
5449 if(!nocode_wanted)
5450 gjmp_addr(d);
5451 gsym(a);
5452 gsym_addr(b, d);
5453 } else if (tok == '{') {
5454 Sym *llabel;
5455 int block_vla_sp_loc = vla_sp_loc, saved_vlas_in_scope = vlas_in_scope;
5457 next();
5458 /* record local declaration stack position */
5459 s = local_stack;
5460 llabel = local_label_stack;
5461 ++local_scope;
5463 /* handle local labels declarations */
5464 if (tok == TOK_LABEL) {
5465 next();
5466 for(;;) {
5467 if (tok < TOK_UIDENT)
5468 expect("label identifier");
5469 label_push(&local_label_stack, tok, LABEL_DECLARED);
5470 next();
5471 if (tok == ',') {
5472 next();
5473 } else {
5474 skip(';');
5475 break;
5479 while (tok != '}') {
5480 label_or_decl(VT_LOCAL);
5481 if (tok != '}') {
5482 if (is_expr)
5483 vpop();
5484 block(bsym, csym, is_expr);
5487 /* pop locally defined labels */
5488 label_pop(&local_label_stack, llabel);
5489 /* pop locally defined symbols */
5490 --local_scope;
5491 /* In the is_expr case (a statement expression is finished here),
5492 vtop might refer to symbols on the local_stack. Either via the
5493 type or via vtop->sym. We can't pop those nor any that in turn
5494 might be referred to. To make it easier we don't roll back
5495 any symbols in that case; some upper level call to block() will
5496 do that. We do have to remove such symbols from the lookup
5497 tables, though. sym_pop will do that. */
5498 sym_pop(&local_stack, s, is_expr);
5500 /* Pop VLA frames and restore stack pointer if required */
5501 if (vlas_in_scope > saved_vlas_in_scope) {
5502 vla_sp_loc = saved_vlas_in_scope ? block_vla_sp_loc : vla_sp_root_loc;
5503 vla_sp_restore();
5505 vlas_in_scope = saved_vlas_in_scope;
5507 next();
5508 } else if (tok == TOK_RETURN) {
5509 next();
5510 if (tok != ';') {
5511 gexpr();
5512 gen_assign_cast(&func_vt);
5513 #ifdef TCC_TARGET_ARM64
5514 // Perhaps it would be better to use this for all backends:
5515 greturn();
5516 #else
5517 if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
5518 CType type, ret_type;
5519 int ret_align, ret_nregs, regsize;
5520 ret_nregs = gfunc_sret(&func_vt, func_var, &ret_type,
5521 &ret_align, &regsize);
5522 if (0 == ret_nregs) {
5523 /* if returning structure, must copy it to implicit
5524 first pointer arg location */
5525 type = func_vt;
5526 mk_pointer(&type);
5527 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
5528 indir();
5529 vswap();
5530 /* copy structure value to pointer */
5531 vstore();
5532 } else {
5533 /* returning structure packed into registers */
5534 int r, size, addr, align;
5535 size = type_size(&func_vt,&align);
5536 if ((vtop->r != (VT_LOCAL | VT_LVAL) ||
5537 (vtop->c.i & (ret_align-1)))
5538 && (align & (ret_align-1))) {
5539 loc = (loc - size) & -ret_align;
5540 addr = loc;
5541 type = func_vt;
5542 vset(&type, VT_LOCAL | VT_LVAL, addr);
5543 vswap();
5544 vstore();
5545 vpop();
5546 vset(&ret_type, VT_LOCAL | VT_LVAL, addr);
5548 vtop->type = ret_type;
5549 if (is_float(ret_type.t))
5550 r = rc_fret(ret_type.t);
5551 else
5552 r = RC_IRET;
5554 if (ret_nregs == 1)
5555 gv(r);
5556 else {
5557 for (;;) {
5558 vdup();
5559 gv(r);
5560 vpop();
5561 if (--ret_nregs == 0)
5562 break;
5563 /* We assume that when a structure is returned in multiple
5564 registers, their classes are consecutive values of the
5565 suite s(n) = 2^n */
5566 r <<= 1;
5567 vtop->c.i += regsize;
5571 } else if (is_float(func_vt.t)) {
5572 gv(rc_fret(func_vt.t));
5573 } else {
5574 gv(RC_IRET);
5576 #endif
5577 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
5579 skip(';');
5580 /* jump unless last stmt in top-level block */
5581 if (tok != '}' || local_scope != 1)
5582 rsym = gjmp(rsym);
5583 nocode_wanted |= 2;
5584 } else if (tok == TOK_BREAK) {
5585 /* compute jump */
5586 if (!bsym)
5587 tcc_error("cannot break");
5588 *bsym = gjmp(*bsym);
5589 next();
5590 skip(';');
5591 nocode_wanted |= 2;
5592 } else if (tok == TOK_CONTINUE) {
5593 /* compute jump */
5594 if (!csym)
5595 tcc_error("cannot continue");
5596 vla_sp_restore_root();
5597 *csym = gjmp(*csym);
5598 next();
5599 skip(';');
5600 } else if (tok == TOK_FOR) {
5601 int e;
5602 int saved_nocode_wanted;
5603 nocode_wanted &= ~2;
5604 next();
5605 skip('(');
5606 s = local_stack;
5607 ++local_scope;
5608 if (tok != ';') {
5609 /* c99 for-loop init decl? */
5610 if (!decl0(VT_LOCAL, 1)) {
5611 /* no, regular for-loop init expr */
5612 gexpr();
5613 vpop();
5616 skip(';');
5617 d = ind;
5618 c = ind;
5619 vla_sp_restore();
5620 a = 0;
5621 b = 0;
5622 if (tok != ';') {
5623 gexpr();
5624 a = gvtst(1, 0);
5626 skip(';');
5627 if (tok != ')') {
5628 e = gjmp(0);
5629 c = ind;
5630 vla_sp_restore();
5631 gexpr();
5632 vpop();
5633 gjmp_addr(d);
5634 gsym(e);
5636 skip(')');
5637 saved_nocode_wanted = nocode_wanted;
5638 block(&a, &b, 0);
5639 nocode_wanted = saved_nocode_wanted;
5640 if(!nocode_wanted)
5641 gjmp_addr(c);
5642 gsym(a);
5643 gsym_addr(b, c);
5644 --local_scope;
5645 sym_pop(&local_stack, s, 0);
5647 } else
5648 if (tok == TOK_DO) {
5649 int saved_nocode_wanted;
5650 nocode_wanted &= ~2;
5651 next();
5652 a = 0;
5653 b = 0;
5654 d = ind;
5655 vla_sp_restore();
5656 saved_nocode_wanted = nocode_wanted;
5657 block(&a, &b, 0);
5658 nocode_wanted = saved_nocode_wanted;
5659 skip(TOK_WHILE);
5660 skip('(');
5661 gsym(b);
5662 gexpr();
5663 c = gvtst(0, 0);
5664 if (!nocode_wanted)
5665 gsym_addr(c, d);
5666 skip(')');
5667 gsym(a);
5668 skip(';');
5669 } else
5670 if (tok == TOK_SWITCH) {
5671 struct switch_t *saved, sw;
5672 int saved_nocode_wanted = nocode_wanted;
5673 next();
5674 skip('(');
5675 gexpr();
5676 /* XXX: other types than integer */
5677 c = gv(RC_INT);
5678 vpop();
5679 skip(')');
5680 a = 0;
5681 b = gjmp(0); /* jump to first case */
5682 sw.p = NULL; sw.n = 0; sw.def_sym = 0;
5683 saved = cur_switch;
5684 cur_switch = &sw;
5685 block(&a, csym, 0);
5686 nocode_wanted = saved_nocode_wanted;
5687 a = gjmp(a); /* add implicit break */
5688 /* case lookup */
5689 gsym(b);
5690 qsort(sw.p, sw.n, sizeof(void*), case_cmp);
5691 for (b = 1; b < sw.n; b++)
5692 if (sw.p[b - 1]->v2 >= sw.p[b]->v1)
5693 tcc_error("duplicate case value");
5694 gcase(sw.p, sw.n, c, &a);
5695 if (sw.def_sym)
5696 gjmp_addr(sw.def_sym);
5697 dynarray_reset(&sw.p, &sw.n);
5698 cur_switch = saved;
5699 /* break label */
5700 gsym(a);
5701 } else
5702 if (tok == TOK_CASE) {
5703 struct case_t *cr = tcc_malloc(sizeof(struct case_t));
5704 if (!cur_switch)
5705 expect("switch");
5706 nocode_wanted &= ~2;
5707 next();
5708 cr->v1 = cr->v2 = expr_const();
5709 if (gnu_ext && tok == TOK_DOTS) {
5710 next();
5711 cr->v2 = expr_const();
5712 if (cr->v2 < cr->v1)
5713 tcc_warning("empty case range");
5715 cr->sym = ind;
5716 dynarray_add((void***) &cur_switch->p, &cur_switch->n, cr);
5717 skip(':');
5718 is_expr = 0;
5719 goto block_after_label;
5720 } else
5721 if (tok == TOK_DEFAULT) {
5722 next();
5723 skip(':');
5724 if (!cur_switch)
5725 expect("switch");
5726 if (cur_switch->def_sym)
5727 tcc_error("too many 'default'");
5728 cur_switch->def_sym = ind;
5729 is_expr = 0;
5730 goto block_after_label;
5731 } else
5732 if (tok == TOK_GOTO) {
5733 next();
5734 if (tok == '*' && gnu_ext) {
5735 /* computed goto */
5736 next();
5737 gexpr();
5738 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
5739 expect("pointer");
5740 if (!nocode_wanted)
5741 ggoto();
5742 else
5743 vtop--;
5744 } else if (tok >= TOK_UIDENT) {
5745 s = label_find(tok);
5746 /* put forward definition if needed */
5747 if (!s) {
5748 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
5749 } else {
5750 if (s->r == LABEL_DECLARED)
5751 s->r = LABEL_FORWARD;
5753 vla_sp_restore_root();
5754 if (nocode_wanted)
5756 else if (s->r & LABEL_FORWARD)
5757 s->jnext = gjmp(s->jnext);
5758 else
5759 gjmp_addr(s->jnext);
5760 next();
5761 } else {
5762 expect("label identifier");
5764 skip(';');
5765 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
5766 asm_instr();
5767 } else {
5768 b = is_label();
5769 if (b) {
5770 /* label case */
5771 s = label_find(b);
5772 if (s) {
5773 if (s->r == LABEL_DEFINED)
5774 tcc_error("duplicate label '%s'", get_tok_str(s->v, NULL));
5775 gsym(s->jnext);
5776 s->r = LABEL_DEFINED;
5777 } else {
5778 s = label_push(&global_label_stack, b, LABEL_DEFINED);
5780 s->jnext = ind;
5781 vla_sp_restore();
5782 /* we accept this, but it is a mistake */
5783 block_after_label:
5784 nocode_wanted &= ~2;
5785 if (tok == '}') {
5786 tcc_warning("deprecated use of label at end of compound statement");
5787 } else {
5788 if (is_expr)
5789 vpop();
5790 block(bsym, csym, is_expr);
5792 } else {
5793 /* expression case */
5794 if (tok != ';') {
5795 if (is_expr) {
5796 vpop();
5797 gexpr();
5798 } else {
5799 gexpr();
5800 vpop();
5803 skip(';');
5808 #define EXPR_CONST 1
5809 #define EXPR_ANY 2
5811 static void parse_init_elem(int expr_type)
5813 int saved_global_expr;
5814 switch(expr_type) {
5815 case EXPR_CONST:
5816 /* compound literals must be allocated globally in this case */
5817 saved_global_expr = global_expr;
5818 global_expr = 1;
5819 expr_const1();
5820 global_expr = saved_global_expr;
5821 /* NOTE: symbols are accepted */
5822 if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
5823 tcc_error("initializer element is not constant");
5824 break;
5825 case EXPR_ANY:
5826 expr_eq();
5827 break;
5831 /* t is the array or struct type. c is the array or struct
5832 address. cur_field is the pointer to the current
5833 value, for arrays the 'c' member contains the current start
5834 index and the 'r' contains the end index (in case of range init).
5835 'size_only' is true if only size info is needed (only used
5836 in arrays) */
5837 static void decl_designator(CType *type, Section *sec, unsigned long c,
5838 Sym **cur_field, int size_only)
5840 Sym *s, *f;
5841 int notfirst, index, index_last, align, l, nb_elems, elem_size;
5842 CType type1;
5844 notfirst = 0;
5845 elem_size = 0;
5846 nb_elems = 1;
5847 if (gnu_ext && (l = is_label()) != 0)
5848 goto struct_field;
5849 while (tok == '[' || tok == '.') {
5850 if (tok == '[') {
5851 if (!(type->t & VT_ARRAY))
5852 expect("array type");
5853 s = type->ref;
5854 next();
5855 index = expr_const();
5856 if (index < 0 || (s->c >= 0 && index >= s->c))
5857 tcc_error("invalid index");
5858 if (tok == TOK_DOTS && gnu_ext) {
5859 next();
5860 index_last = expr_const();
5861 if (index_last < 0 ||
5862 (s->c >= 0 && index_last >= s->c) ||
5863 index_last < index)
5864 tcc_error("invalid index");
5865 } else {
5866 index_last = index;
5868 skip(']');
5869 if (!notfirst) {
5870 (*cur_field)->c = index;
5871 (*cur_field)->r = index_last;
5873 type = pointed_type(type);
5874 elem_size = type_size(type, &align);
5875 c += index * elem_size;
5876 /* NOTE: we only support ranges for last designator */
5877 nb_elems = index_last - index + 1;
5878 if (nb_elems != 1) {
5879 notfirst = 1;
5880 break;
5882 } else {
5883 next();
5884 l = tok;
5885 next();
5886 struct_field:
5887 if ((type->t & VT_BTYPE) != VT_STRUCT)
5888 expect("struct/union type");
5889 f = find_field(type, l);
5890 if (!f)
5891 expect("field");
5892 if (!notfirst)
5893 *cur_field = f;
5894 /* XXX: fix this mess by using explicit storage field */
5895 type1 = f->type;
5896 type1.t |= (type->t & ~VT_TYPE);
5897 type = &type1;
5898 c += f->c;
5900 notfirst = 1;
5902 if (notfirst) {
5903 if (tok == '=') {
5904 next();
5905 } else {
5906 if (!gnu_ext)
5907 expect("=");
5909 } else {
5910 if (type->t & VT_ARRAY) {
5911 index = (*cur_field)->c;
5912 if (type->ref->c >= 0 && index >= type->ref->c)
5913 tcc_error("index too large");
5914 type = pointed_type(type);
5915 c += index * type_size(type, &align);
5916 } else {
5917 f = *cur_field;
5918 if (!f)
5919 tcc_error("too many field init");
5920 /* XXX: fix this mess by using explicit storage field */
5921 type1 = f->type;
5922 type1.t |= (type->t & ~VT_TYPE);
5923 type = &type1;
5924 c += f->c;
5927 decl_initializer(type, sec, c, 0, size_only);
5929 /* XXX: make it more general */
5930 if (!size_only && nb_elems > 1) {
5931 unsigned long c_end;
5932 uint8_t *src, *dst;
5933 int i;
5935 if (!sec) {
5936 vset(type, VT_LOCAL|VT_LVAL, c);
5937 for (i = 1; i < nb_elems; i++) {
5938 vset(type, VT_LOCAL|VT_LVAL, c + elem_size * i);
5939 vswap();
5940 vstore();
5942 vpop();
5943 } else {
5944 c_end = c + nb_elems * elem_size;
5945 if (c_end > sec->data_allocated)
5946 section_realloc(sec, c_end);
5947 src = sec->data + c;
5948 dst = src;
5949 for(i = 1; i < nb_elems; i++) {
5950 dst += elem_size;
5951 memcpy(dst, src, elem_size);
5957 /* store a value or an expression directly in global data or in local array */
5958 static void init_putv(CType *type, Section *sec, unsigned long c)
5960 int bt, bit_pos, bit_size;
5961 void *ptr;
5962 unsigned long long bit_mask;
5963 CType dtype;
5965 dtype = *type;
5966 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
5968 if (sec) {
5969 int size, align;
5970 /* XXX: not portable */
5971 /* XXX: generate error if incorrect relocation */
5972 gen_assign_cast(&dtype);
5973 bt = type->t & VT_BTYPE;
5974 size = type_size(type, &align);
5975 if (c + size > sec->data_allocated) {
5976 section_realloc(sec, c + size);
5978 ptr = sec->data + c;
5979 /* XXX: make code faster ? */
5980 if (!(type->t & VT_BITFIELD)) {
5981 bit_pos = 0;
5982 bit_size = PTR_SIZE * 8;
5983 bit_mask = -1LL;
5984 } else {
5985 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5986 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
5987 bit_mask = (1LL << bit_size) - 1;
5989 if ((vtop->r & (VT_SYM|VT_CONST)) == (VT_SYM|VT_CONST) &&
5990 vtop->sym->v >= SYM_FIRST_ANOM &&
5991 /* XXX This rejects compount literals like
5992 '(void *){ptr}'. The problem is that '&sym' is
5993 represented the same way, which would be ruled out
5994 by the SYM_FIRST_ANOM check above, but also '"string"'
5995 in 'char *p = "string"' is represented the same
5996 with the type being VT_PTR and the symbol being an
5997 anonymous one. That is, there's no difference in vtop
5998 between '(void *){x}' and '&(void *){x}'. Ignore
5999 pointer typed entities here. Hopefully no real code
6000 will every use compound literals with scalar type. */
6001 (vtop->type.t & VT_BTYPE) != VT_PTR) {
6002 /* These come from compound literals, memcpy stuff over. */
6003 Section *ssec;
6004 ElfW(Sym) *esym;
6005 ElfW_Rel *rel;
6006 esym = &((ElfW(Sym) *)symtab_section->data)[vtop->sym->c];
6007 ssec = tcc_state->sections[esym->st_shndx];
6008 memmove (ptr, ssec->data + esym->st_value, size);
6009 if (ssec->reloc) {
6010 /* We need to copy over all memory contents, and that
6011 includes relocations. Use the fact that relocs are
6012 created it order, so look from the end of relocs
6013 until we hit one before the copied region. */
6014 int num_relocs = ssec->reloc->data_offset / sizeof(*rel);
6015 rel = (ElfW_Rel*)(ssec->reloc->data + ssec->reloc->data_offset);
6016 while (num_relocs--) {
6017 rel--;
6018 if (rel->r_offset >= esym->st_value + size)
6019 continue;
6020 if (rel->r_offset < esym->st_value)
6021 break;
6022 /* Note: if the same fields are initialized multiple
6023 times (possible with designators) then we possibly
6024 add multiple relocations for the same offset here.
6025 That would lead to wrong code, the last reloc needs
6026 to win. We clean this up later after the whole
6027 initializer is parsed. */
6028 put_elf_reloca(symtab_section, sec,
6029 c + rel->r_offset - esym->st_value,
6030 ELFW(R_TYPE)(rel->r_info),
6031 ELFW(R_SYM)(rel->r_info),
6032 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
6033 rel->r_addend
6034 #else
6036 #endif
6040 } else {
6041 if ((vtop->r & VT_SYM) &&
6042 (bt == VT_BYTE ||
6043 bt == VT_SHORT ||
6044 bt == VT_DOUBLE ||
6045 bt == VT_LDOUBLE ||
6046 #if PTR_SIZE == 8
6047 (bt == VT_LLONG && bit_size != 64) ||
6048 bt == VT_INT
6049 #else
6050 bt == VT_LLONG ||
6051 (bt == VT_INT && bit_size != 32)
6052 #endif
6054 tcc_error("initializer element is not computable at load time");
6055 switch(bt) {
6056 /* XXX: when cross-compiling we assume that each type has the
6057 same representation on host and target, which is likely to
6058 be wrong in the case of long double */
6059 case VT_BOOL:
6060 vtop->c.i = (vtop->c.i != 0);
6061 case VT_BYTE:
6062 *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
6063 break;
6064 case VT_SHORT:
6065 *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
6066 break;
6067 case VT_DOUBLE:
6068 *(double *)ptr = vtop->c.d;
6069 break;
6070 case VT_LDOUBLE:
6071 if (sizeof(long double) == LDOUBLE_SIZE)
6072 *(long double *)ptr = vtop->c.ld;
6073 else if (sizeof(double) == LDOUBLE_SIZE)
6074 *(double *)ptr = vtop->c.ld;
6075 else
6076 tcc_error("can't cross compile long double constants");
6077 break;
6078 #if PTR_SIZE != 8
6079 case VT_LLONG:
6080 *(long long *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
6081 break;
6082 #else
6083 case VT_LLONG:
6084 #endif
6085 case VT_PTR:
6087 addr_t val = (vtop->c.i & bit_mask) << bit_pos;
6088 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
6089 if (vtop->r & VT_SYM)
6090 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
6091 else
6092 *(addr_t *)ptr |= val;
6093 #else
6094 if (vtop->r & VT_SYM)
6095 greloc(sec, vtop->sym, c, R_DATA_PTR);
6096 *(addr_t *)ptr |= val;
6097 #endif
6098 break;
6100 default:
6102 int val = (vtop->c.i & bit_mask) << bit_pos;
6103 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
6104 if (vtop->r & VT_SYM)
6105 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
6106 else
6107 *(int *)ptr |= val;
6108 #else
6109 if (vtop->r & VT_SYM)
6110 greloc(sec, vtop->sym, c, R_DATA_PTR);
6111 *(int *)ptr |= val;
6112 #endif
6113 break;
6117 vtop--;
6118 } else {
6119 vset(&dtype, VT_LOCAL|VT_LVAL, c);
6120 vswap();
6121 vstore();
6122 vpop();
6126 /* put zeros for variable based init */
6127 static void init_putz(Section *sec, unsigned long c, int size)
6129 if (sec) {
6130 /* nothing to do because globals are already set to zero */
6131 } else {
6132 vpush_global_sym(&func_old_type, TOK_memset);
6133 vseti(VT_LOCAL, c);
6134 #ifdef TCC_TARGET_ARM
6135 vpushs(size);
6136 vpushi(0);
6137 #else
6138 vpushi(0);
6139 vpushs(size);
6140 #endif
6141 gfunc_call(3);
6145 /* 't' contains the type and storage info. 'c' is the offset of the
6146 object in section 'sec'. If 'sec' is NULL, it means stack based
6147 allocation. 'first' is true if array '{' must be read (multi
6148 dimension implicit array init handling). 'size_only' is true if
6149 size only evaluation is wanted (only for arrays). */
6150 static void decl_initializer(CType *type, Section *sec, unsigned long c,
6151 int first, int size_only)
6153 int index, array_length, n, no_oblock, nb, parlevel, parlevel1, i;
6154 int size1, align1;
6155 int have_elem;
6156 Sym *s, *f;
6157 Sym indexsym;
6158 CType *t1;
6160 /* If we currently are at an '}' or ',' we have read an initializer
6161 element in one of our callers, and not yet consumed it. */
6162 have_elem = tok == '}' || tok == ',';
6163 if (!have_elem && tok != '{' &&
6164 /* In case of strings we have special handling for arrays, so
6165 don't consume them as initializer value (which would commit them
6166 to some anonymous symbol). */
6167 tok != TOK_LSTR && tok != TOK_STR &&
6168 !size_only) {
6169 parse_init_elem(!sec ? EXPR_ANY : EXPR_CONST);
6170 have_elem = 1;
6173 if (have_elem &&
6174 !(type->t & VT_ARRAY) &&
6175 /* Use i_c_parameter_t, to strip toplevel qualifiers.
6176 The source type might have VT_CONSTANT set, which is
6177 of course assignable to non-const elements. */
6178 is_compatible_parameter_types(type, &vtop->type)) {
6179 init_putv(type, sec, c);
6180 } else if (type->t & VT_ARRAY) {
6181 s = type->ref;
6182 n = s->c;
6183 array_length = 0;
6184 t1 = pointed_type(type);
6185 size1 = type_size(t1, &align1);
6187 no_oblock = 1;
6188 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
6189 tok == '{') {
6190 if (tok != '{')
6191 tcc_error("character array initializer must be a literal,"
6192 " optionally enclosed in braces");
6193 skip('{');
6194 no_oblock = 0;
6197 /* only parse strings here if correct type (otherwise: handle
6198 them as ((w)char *) expressions */
6199 if ((tok == TOK_LSTR &&
6200 #ifdef TCC_TARGET_PE
6201 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
6202 #else
6203 (t1->t & VT_BTYPE) == VT_INT
6204 #endif
6205 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
6206 while (tok == TOK_STR || tok == TOK_LSTR) {
6207 int cstr_len, ch;
6209 /* compute maximum number of chars wanted */
6210 if (tok == TOK_STR)
6211 cstr_len = tokc.str.size;
6212 else
6213 cstr_len = tokc.str.size / sizeof(nwchar_t);
6214 cstr_len--;
6215 nb = cstr_len;
6216 if (n >= 0 && nb > (n - array_length))
6217 nb = n - array_length;
6218 if (!size_only) {
6219 if (cstr_len > nb)
6220 tcc_warning("initializer-string for array is too long");
6221 /* in order to go faster for common case (char
6222 string in global variable, we handle it
6223 specifically */
6224 if (sec && tok == TOK_STR && size1 == 1) {
6225 memcpy(sec->data + c + array_length, tokc.str.data, nb);
6226 } else {
6227 for(i=0;i<nb;i++) {
6228 if (tok == TOK_STR)
6229 ch = ((unsigned char *)tokc.str.data)[i];
6230 else
6231 ch = ((nwchar_t *)tokc.str.data)[i];
6232 vpushi(ch);
6233 init_putv(t1, sec, c + (array_length + i) * size1);
6237 array_length += nb;
6238 next();
6240 /* only add trailing zero if enough storage (no
6241 warning in this case since it is standard) */
6242 if (n < 0 || array_length < n) {
6243 if (!size_only) {
6244 vpushi(0);
6245 init_putv(t1, sec, c + (array_length * size1));
6247 array_length++;
6249 } else {
6250 indexsym.c = 0;
6251 indexsym.r = 0;
6252 f = &indexsym;
6254 do_init_list:
6255 while (tok != '}' || have_elem) {
6256 decl_designator(type, sec, c, &f, size_only);
6257 have_elem = 0;
6258 index = f->c;
6259 /* must put zero in holes (note that doing it that way
6260 ensures that it even works with designators) */
6261 if (!size_only && array_length < index) {
6262 init_putz(sec, c + array_length * size1,
6263 (index - array_length) * size1);
6265 if (type->t & VT_ARRAY) {
6266 index = indexsym.c = ++indexsym.r;
6267 } else {
6268 index = index + type_size(&f->type, &align1);
6269 if (s->type.t == TOK_UNION)
6270 f = NULL;
6271 else
6272 f = f->next;
6274 if (index > array_length)
6275 array_length = index;
6277 if (type->t & VT_ARRAY) {
6278 /* special test for multi dimensional arrays (may not
6279 be strictly correct if designators are used at the
6280 same time) */
6281 if (no_oblock && index >= n)
6282 break;
6283 } else {
6284 if (no_oblock && f == NULL)
6285 break;
6287 if (tok == '}')
6288 break;
6289 skip(',');
6292 /* put zeros at the end */
6293 if (!size_only && array_length < n) {
6294 init_putz(sec, c + array_length * size1,
6295 (n - array_length) * size1);
6297 if (!no_oblock)
6298 skip('}');
6299 /* patch type size if needed, which happens only for array types */
6300 if (n < 0)
6301 s->c = array_length;
6302 } else if ((type->t & VT_BTYPE) == VT_STRUCT) {
6303 size1 = 1;
6304 no_oblock = 1;
6305 if (first || tok == '{') {
6306 skip('{');
6307 no_oblock = 0;
6309 s = type->ref;
6310 f = s->next;
6311 array_length = 0;
6312 n = s->c;
6313 goto do_init_list;
6314 } else if (tok == '{') {
6315 next();
6316 decl_initializer(type, sec, c, first, size_only);
6317 skip('}');
6318 } else if (size_only) {
6319 /* If we supported only ISO C we wouldn't have to accept calling
6320 this on anything than an array size_only==1 (and even then
6321 only on the outermost level, so no recursion would be needed),
6322 because initializing a flex array member isn't supported.
6323 But GNU C supports it, so we need to recurse even into
6324 subfields of structs and arrays when size_only is set. */
6325 /* just skip expression */
6326 parlevel = parlevel1 = 0;
6327 while ((parlevel > 0 || parlevel1 > 0 ||
6328 (tok != '}' && tok != ',')) && tok != -1) {
6329 if (tok == '(')
6330 parlevel++;
6331 else if (tok == ')') {
6332 if (parlevel == 0 && parlevel1 == 0)
6333 break;
6334 parlevel--;
6336 else if (tok == '{')
6337 parlevel1++;
6338 else if (tok == '}') {
6339 if (parlevel == 0 && parlevel1 == 0)
6340 break;
6341 parlevel1--;
6343 next();
6345 } else {
6346 if (!have_elem) {
6347 /* This should happen only when we haven't parsed
6348 the init element above for fear of committing a
6349 string constant to memory too early. */
6350 if (tok != TOK_STR && tok != TOK_LSTR)
6351 expect("string constant");
6352 parse_init_elem(!sec ? EXPR_ANY : EXPR_CONST);
6354 init_putv(type, sec, c);
6358 /* parse an initializer for type 't' if 'has_init' is non zero, and
6359 allocate space in local or global data space ('r' is either
6360 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
6361 variable 'v' of scope 'scope' is declared before initializers
6362 are parsed. If 'v' is zero, then a reference to the new object
6363 is put in the value stack. If 'has_init' is 2, a special parsing
6364 is done to handle string constants. */
6365 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
6366 int has_init, int v, int scope)
6368 int size, align, addr, data_offset;
6369 int level;
6370 ParseState saved_parse_state = {0};
6371 TokenString *init_str = NULL;
6372 Section *sec;
6373 Sym *flexible_array;
6375 flexible_array = NULL;
6376 if ((type->t & VT_BTYPE) == VT_STRUCT) {
6377 Sym *field = type->ref->next;
6378 if (field) {
6379 while (field->next)
6380 field = field->next;
6381 if (field->type.t & VT_ARRAY && field->type.ref->c < 0)
6382 flexible_array = field;
6386 size = type_size(type, &align);
6387 /* If unknown size, we must evaluate it before
6388 evaluating initializers because
6389 initializers can generate global data too
6390 (e.g. string pointers or ISOC99 compound
6391 literals). It also simplifies local
6392 initializers handling */
6393 if (size < 0 || (flexible_array && has_init)) {
6394 if (!has_init)
6395 tcc_error("unknown type size");
6396 /* get all init string */
6397 init_str = tok_str_alloc();
6398 if (has_init == 2) {
6399 /* only get strings */
6400 while (tok == TOK_STR || tok == TOK_LSTR) {
6401 tok_str_add_tok(init_str);
6402 next();
6404 } else {
6405 level = 0;
6406 while (level > 0 || (tok != ',' && tok != ';')) {
6407 if (tok < 0)
6408 tcc_error("unexpected end of file in initializer");
6409 tok_str_add_tok(init_str);
6410 if (tok == '{')
6411 level++;
6412 else if (tok == '}') {
6413 level--;
6414 if (level <= 0) {
6415 next();
6416 break;
6419 next();
6422 tok_str_add(init_str, -1);
6423 tok_str_add(init_str, 0);
6425 /* compute size */
6426 save_parse_state(&saved_parse_state);
6428 begin_macro(init_str, 1);
6429 next();
6430 decl_initializer(type, NULL, 0, 1, 1);
6431 /* prepare second initializer parsing */
6432 macro_ptr = init_str->str;
6433 next();
6435 /* if still unknown size, error */
6436 size = type_size(type, &align);
6437 if (size < 0)
6438 tcc_error("unknown type size");
6440 /* If there's a flex member and it was used in the initializer
6441 adjust size. */
6442 if (flexible_array &&
6443 flexible_array->type.ref->c > 0)
6444 size += flexible_array->type.ref->c
6445 * pointed_size(&flexible_array->type);
6446 /* take into account specified alignment if bigger */
6447 if (ad->a.aligned) {
6448 if (ad->a.aligned > align)
6449 align = ad->a.aligned;
6450 } else if (ad->a.packed) {
6451 align = 1;
6453 if ((r & VT_VALMASK) == VT_LOCAL) {
6454 sec = NULL;
6455 #ifdef CONFIG_TCC_BCHECK
6456 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
6457 loc--;
6459 #endif
6460 loc = (loc - size) & -align;
6461 addr = loc;
6462 #ifdef CONFIG_TCC_BCHECK
6463 /* handles bounds */
6464 /* XXX: currently, since we do only one pass, we cannot track
6465 '&' operators, so we add only arrays */
6466 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
6467 addr_t *bounds_ptr;
6468 /* add padding between regions */
6469 loc--;
6470 /* then add local bound info */
6471 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(addr_t));
6472 bounds_ptr[0] = addr;
6473 bounds_ptr[1] = size;
6475 #endif
6476 if (v) {
6477 /* local variable */
6478 #ifdef CONFIG_TCC_ASM
6479 if (ad->asm_label) {
6480 int reg = asm_parse_regvar(ad->asm_label);
6481 if (reg >= 0)
6482 r = (r & ~VT_VALMASK) | reg;
6484 #endif
6485 sym_push(v, type, r, addr);
6486 } else {
6487 /* push local reference */
6488 vset(type, r, addr);
6490 } else {
6491 Sym *sym;
6493 sym = NULL;
6494 if (v && scope == VT_CONST) {
6495 /* see if the symbol was already defined */
6496 sym = sym_find(v);
6497 if (sym) {
6498 if (!is_compatible_types(&sym->type, type))
6499 tcc_error("incompatible types for redefinition of '%s'",
6500 get_tok_str(v, NULL));
6501 if (sym->type.t & VT_EXTERN) {
6502 /* if the variable is extern, it was not allocated */
6503 sym->type.t &= ~VT_EXTERN;
6504 /* set array size if it was omitted in extern
6505 declaration */
6506 if ((sym->type.t & VT_ARRAY) &&
6507 sym->type.ref->c < 0 &&
6508 type->ref->c >= 0)
6509 sym->type.ref->c = type->ref->c;
6510 } else {
6511 /* we accept several definitions of the same
6512 global variable. this is tricky, because we
6513 must play with the SHN_COMMON type of the symbol */
6514 /* XXX: should check if the variable was already
6515 initialized. It is incorrect to initialized it
6516 twice */
6517 /* no init data, we won't add more to the symbol */
6518 if (!has_init)
6519 goto no_alloc;
6524 /* allocate symbol in corresponding section */
6525 sec = ad->section;
6526 if (!sec) {
6527 if (has_init)
6528 sec = data_section;
6529 else if (tcc_state->nocommon)
6530 sec = bss_section;
6532 if (sec) {
6533 data_offset = sec->data_offset;
6534 data_offset = (data_offset + align - 1) & -align;
6535 addr = data_offset;
6536 /* very important to increment global pointer at this time
6537 because initializers themselves can create new initializers */
6538 data_offset += size;
6539 #ifdef CONFIG_TCC_BCHECK
6540 /* add padding if bound check */
6541 if (tcc_state->do_bounds_check)
6542 data_offset++;
6543 #endif
6544 sec->data_offset = data_offset;
6545 /* allocate section space to put the data */
6546 if (sec->sh_type != SHT_NOBITS &&
6547 data_offset > sec->data_allocated)
6548 section_realloc(sec, data_offset);
6549 /* align section if needed */
6550 if (align > sec->sh_addralign)
6551 sec->sh_addralign = align;
6552 } else {
6553 addr = 0; /* avoid warning */
6556 if (v) {
6557 if (scope != VT_CONST || !sym) {
6558 sym = sym_push(v, type, r | VT_SYM, 0);
6559 sym->asm_label = ad->asm_label;
6561 /* update symbol definition */
6562 if (sec) {
6563 put_extern_sym(sym, sec, addr, size);
6564 } else {
6565 ElfW(Sym) *esym;
6566 /* put a common area */
6567 put_extern_sym(sym, NULL, align, size);
6568 /* XXX: find a nicer way */
6569 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
6570 esym->st_shndx = SHN_COMMON;
6572 } else {
6573 /* push global reference */
6574 sym = get_sym_ref(type, sec, addr, size);
6575 vpushsym(type, sym);
6577 /* patch symbol weakness */
6578 if (type->t & VT_WEAK)
6579 weaken_symbol(sym);
6580 apply_visibility(sym, type);
6581 #ifdef CONFIG_TCC_BCHECK
6582 /* handles bounds now because the symbol must be defined
6583 before for the relocation */
6584 if (tcc_state->do_bounds_check) {
6585 addr_t *bounds_ptr;
6587 greloc(bounds_section, sym, bounds_section->data_offset, R_DATA_PTR);
6588 /* then add global bound info */
6589 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(addr_t));
6590 bounds_ptr[0] = 0; /* relocated */
6591 bounds_ptr[1] = size;
6593 #endif
6595 if (type->t & VT_VLA) {
6596 int a;
6598 /* save current stack pointer */
6599 if (vlas_in_scope == 0) {
6600 if (vla_sp_root_loc == -1)
6601 vla_sp_root_loc = (loc -= PTR_SIZE);
6602 gen_vla_sp_save(vla_sp_root_loc);
6605 vla_runtime_type_size(type, &a);
6606 gen_vla_alloc(type, a);
6607 gen_vla_sp_save(addr);
6608 vla_sp_loc = addr;
6609 vlas_in_scope++;
6610 } else if (has_init) {
6611 size_t oldreloc_offset = 0;
6612 if (sec && sec->reloc)
6613 oldreloc_offset = sec->reloc->data_offset;
6614 decl_initializer(type, sec, addr, 1, 0);
6615 if (sec && sec->reloc)
6616 squeeze_multi_relocs(sec, oldreloc_offset);
6617 /* patch flexible array member size back to -1, */
6618 /* for possible subsequent similar declarations */
6619 if (flexible_array)
6620 flexible_array->type.ref->c = -1;
6622 no_alloc: ;
6623 /* restore parse state if needed */
6624 if (init_str) {
6625 end_macro();
6626 restore_parse_state(&saved_parse_state);
6630 static void put_func_debug(Sym *sym)
6632 char buf[512];
6634 /* stabs info */
6635 /* XXX: we put here a dummy type */
6636 snprintf(buf, sizeof(buf), "%s:%c1",
6637 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
6638 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
6639 cur_text_section, sym->c);
6640 /* //gr gdb wants a line at the function */
6641 put_stabn(N_SLINE, 0, file->line_num, 0);
6642 last_ind = 0;
6643 last_line_num = 0;
6646 /* parse an old style function declaration list */
6647 /* XXX: check multiple parameter */
6648 static void func_decl_list(Sym *func_sym)
6650 AttributeDef ad;
6651 int v;
6652 Sym *s;
6653 CType btype, type;
6655 /* parse each declaration */
6656 while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF &&
6657 tok != TOK_ASM1 && tok != TOK_ASM2 && tok != TOK_ASM3) {
6658 if (!parse_btype(&btype, &ad))
6659 expect("declaration list");
6660 if (((btype.t & VT_BTYPE) == VT_ENUM ||
6661 (btype.t & VT_BTYPE) == VT_STRUCT) &&
6662 tok == ';') {
6663 /* we accept no variable after */
6664 } else {
6665 for(;;) {
6666 type = btype;
6667 type_decl(&type, &ad, &v, TYPE_DIRECT);
6668 /* find parameter in function parameter list */
6669 s = func_sym->next;
6670 while (s != NULL) {
6671 if ((s->v & ~SYM_FIELD) == v)
6672 goto found;
6673 s = s->next;
6675 tcc_error("declaration for parameter '%s' but no such parameter",
6676 get_tok_str(v, NULL));
6677 found:
6678 /* check that no storage specifier except 'register' was given */
6679 if (type.t & VT_STORAGE)
6680 tcc_error("storage class specified for '%s'", get_tok_str(v, NULL));
6681 convert_parameter_type(&type);
6682 /* we can add the type (NOTE: it could be local to the function) */
6683 s->type = type;
6684 /* accept other parameters */
6685 if (tok == ',')
6686 next();
6687 else
6688 break;
6691 skip(';');
6695 /* parse a function defined by symbol 'sym' and generate its code in
6696 'cur_text_section' */
6697 static void gen_function(Sym *sym)
6699 int saved_nocode_wanted = nocode_wanted;
6701 nocode_wanted = 0;
6702 ind = cur_text_section->data_offset;
6703 /* NOTE: we patch the symbol size later */
6704 put_extern_sym(sym, cur_text_section, ind, 0);
6705 funcname = get_tok_str(sym->v, NULL);
6706 func_ind = ind;
6707 /* Initialize VLA state */
6708 vla_sp_loc = -1;
6709 vla_sp_root_loc = -1;
6710 /* put debug symbol */
6711 if (tcc_state->do_debug)
6712 put_func_debug(sym);
6714 /* push a dummy symbol to enable local sym storage */
6715 sym_push2(&local_stack, SYM_FIELD, 0, 0);
6716 local_scope = 1; /* for function parameters */
6717 gfunc_prolog(&sym->type);
6718 local_scope = 0;
6720 rsym = 0;
6721 block(NULL, NULL, 0);
6722 gsym(rsym);
6723 gfunc_epilog();
6724 cur_text_section->data_offset = ind;
6725 label_pop(&global_label_stack, NULL);
6726 /* reset local stack */
6727 local_scope = 0;
6728 sym_pop(&local_stack, NULL, 0);
6729 /* end of function */
6730 /* patch symbol size */
6731 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
6732 ind - func_ind;
6733 /* patch symbol weakness (this definition overrules any prototype) */
6734 if (sym->type.t & VT_WEAK)
6735 weaken_symbol(sym);
6736 apply_visibility(sym, &sym->type);
6737 if (tcc_state->do_debug) {
6738 put_stabn(N_FUN, 0, 0, ind - func_ind);
6740 /* It's better to crash than to generate wrong code */
6741 cur_text_section = NULL;
6742 funcname = ""; /* for safety */
6743 func_vt.t = VT_VOID; /* for safety */
6744 func_var = 0; /* for safety */
6745 ind = 0; /* for safety */
6746 nocode_wanted = saved_nocode_wanted;
6747 check_vstack();
6750 static void gen_inline_functions(TCCState *s)
6752 Sym *sym;
6753 int inline_generated, i, ln;
6754 struct InlineFunc *fn;
6756 ln = file->line_num;
6757 /* iterate while inline function are referenced */
6758 for(;;) {
6759 inline_generated = 0;
6760 for (i = 0; i < s->nb_inline_fns; ++i) {
6761 fn = s->inline_fns[i];
6762 sym = fn->sym;
6763 if (sym && sym->c) {
6764 /* the function was used: generate its code and
6765 convert it to a normal function */
6766 fn->sym = NULL;
6767 if (file)
6768 pstrcpy(file->filename, sizeof file->filename, fn->filename);
6769 sym->r = VT_SYM | VT_CONST;
6770 sym->type.t &= ~VT_INLINE;
6772 begin_macro(fn->func_str, 1);
6773 next();
6774 cur_text_section = text_section;
6775 gen_function(sym);
6776 end_macro();
6778 inline_generated = 1;
6781 if (!inline_generated)
6782 break;
6784 file->line_num = ln;
6787 ST_FUNC void free_inline_functions(TCCState *s)
6789 int i;
6790 /* free tokens of unused inline functions */
6791 for (i = 0; i < s->nb_inline_fns; ++i) {
6792 struct InlineFunc *fn = s->inline_fns[i];
6793 if (fn->sym)
6794 tok_str_free(fn->func_str);
6796 dynarray_reset(&s->inline_fns, &s->nb_inline_fns);
6799 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
6800 static int decl0(int l, int is_for_loop_init)
6802 int v, has_init, r;
6803 CType type, btype;
6804 Sym *sym;
6805 AttributeDef ad;
6807 while (1) {
6808 if (!parse_btype(&btype, &ad)) {
6809 if (is_for_loop_init)
6810 return 0;
6811 /* skip redundant ';' */
6812 /* XXX: find more elegant solution */
6813 if (tok == ';') {
6814 next();
6815 continue;
6817 if (l == VT_CONST &&
6818 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
6819 /* global asm block */
6820 asm_global_instr();
6821 continue;
6823 /* special test for old K&R protos without explicit int
6824 type. Only accepted when defining global data */
6825 if (l == VT_LOCAL || tok < TOK_UIDENT)
6826 break;
6827 btype.t = VT_INT;
6829 if (((btype.t & VT_BTYPE) == VT_ENUM ||
6830 (btype.t & VT_BTYPE) == VT_STRUCT) &&
6831 tok == ';') {
6832 if ((btype.t & VT_BTYPE) == VT_STRUCT) {
6833 int v = btype.ref->v;
6834 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) >= SYM_FIRST_ANOM)
6835 tcc_warning("unnamed struct/union that defines no instances");
6837 next();
6838 continue;
6840 while (1) { /* iterate thru each declaration */
6841 type = btype;
6842 /* If the base type itself was an array type of unspecified
6843 size (like in 'typedef int arr[]; arr x = {1};') then
6844 we will overwrite the unknown size by the real one for
6845 this decl. We need to unshare the ref symbol holding
6846 that size. */
6847 if ((type.t & VT_ARRAY) && type.ref->c < 0) {
6848 type.ref = sym_push(SYM_FIELD, &type.ref->type, 0, type.ref->c);
6850 type_decl(&type, &ad, &v, TYPE_DIRECT);
6851 #if 0
6853 char buf[500];
6854 type_to_str(buf, sizeof(buf), t, get_tok_str(v, NULL));
6855 printf("type = '%s'\n", buf);
6857 #endif
6858 if ((type.t & VT_BTYPE) == VT_FUNC) {
6859 if ((type.t & VT_STATIC) && (l == VT_LOCAL)) {
6860 tcc_error("function without file scope cannot be static");
6862 /* if old style function prototype, we accept a
6863 declaration list */
6864 sym = type.ref;
6865 if (sym->c == FUNC_OLD)
6866 func_decl_list(sym);
6869 if (gnu_ext && (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
6870 ad.asm_label = asm_label_instr();
6871 /* parse one last attribute list, after asm label */
6872 parse_attribute(&ad);
6873 if (tok == '{')
6874 expect(";");
6877 if (ad.a.weak)
6878 type.t |= VT_WEAK;
6879 #ifdef TCC_TARGET_PE
6880 if (ad.a.func_import)
6881 type.t |= VT_IMPORT;
6882 if (ad.a.func_export)
6883 type.t |= VT_EXPORT;
6884 #endif
6885 type.t |= ad.a.visibility << VT_VIS_SHIFT;
6887 if (tok == '{') {
6888 if (l == VT_LOCAL)
6889 tcc_error("cannot use local functions");
6890 if ((type.t & VT_BTYPE) != VT_FUNC)
6891 expect("function definition");
6893 /* reject abstract declarators in function definition */
6894 sym = type.ref;
6895 while ((sym = sym->next) != NULL)
6896 if (!(sym->v & ~SYM_FIELD))
6897 expect("identifier");
6899 /* XXX: cannot do better now: convert extern line to static inline */
6900 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
6901 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
6903 sym = sym_find(v);
6904 if (sym) {
6905 Sym *ref;
6906 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
6907 goto func_error1;
6909 ref = sym->type.ref;
6910 if (0 == ref->a.func_proto)
6911 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
6913 /* use func_call from prototype if not defined */
6914 if (ref->a.func_call != FUNC_CDECL
6915 && type.ref->a.func_call == FUNC_CDECL)
6916 type.ref->a.func_call = ref->a.func_call;
6918 /* use export from prototype */
6919 if (ref->a.func_export)
6920 type.ref->a.func_export = 1;
6922 /* use static from prototype */
6923 if (sym->type.t & VT_STATIC)
6924 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
6926 /* If the definition has no visibility use the
6927 one from prototype. */
6928 if (! (type.t & VT_VIS_MASK))
6929 type.t |= sym->type.t & VT_VIS_MASK;
6931 if (!is_compatible_types(&sym->type, &type)) {
6932 func_error1:
6933 tcc_error("incompatible types for redefinition of '%s'",
6934 get_tok_str(v, NULL));
6936 type.ref->a.func_proto = 0;
6937 /* if symbol is already defined, then put complete type */
6938 sym->type = type;
6939 } else {
6940 /* put function symbol */
6941 sym = global_identifier_push(v, type.t, 0);
6942 sym->type.ref = type.ref;
6945 /* static inline functions are just recorded as a kind
6946 of macro. Their code will be emitted at the end of
6947 the compilation unit only if they are used */
6948 if ((type.t & (VT_INLINE | VT_STATIC)) ==
6949 (VT_INLINE | VT_STATIC)) {
6950 int block_level;
6951 struct InlineFunc *fn;
6952 const char *filename;
6954 filename = file ? file->filename : "";
6955 fn = tcc_malloc(sizeof *fn + strlen(filename));
6956 strcpy(fn->filename, filename);
6957 fn->sym = sym;
6958 fn->func_str = tok_str_alloc();
6960 block_level = 0;
6961 for(;;) {
6962 int t;
6963 if (tok == TOK_EOF)
6964 tcc_error("unexpected end of file");
6965 tok_str_add_tok(fn->func_str);
6966 t = tok;
6967 next();
6968 if (t == '{') {
6969 block_level++;
6970 } else if (t == '}') {
6971 block_level--;
6972 if (block_level == 0)
6973 break;
6976 tok_str_add(fn->func_str, -1);
6977 tok_str_add(fn->func_str, 0);
6978 dynarray_add((void ***)&tcc_state->inline_fns, &tcc_state->nb_inline_fns, fn);
6980 } else {
6981 /* compute text section */
6982 cur_text_section = ad.section;
6983 if (!cur_text_section)
6984 cur_text_section = text_section;
6985 sym->r = VT_SYM | VT_CONST;
6986 gen_function(sym);
6988 break;
6989 } else {
6990 if (btype.t & VT_TYPEDEF) {
6991 /* save typedefed type */
6992 /* XXX: test storage specifiers ? */
6993 sym = sym_find(v);
6994 if (sym && sym->scope == local_scope) {
6995 if (!is_compatible_types(&sym->type, &type)
6996 || !(sym->type.t & VT_TYPEDEF))
6997 tcc_error("incompatible redefinition of '%s'",
6998 get_tok_str(v, NULL));
6999 sym->type = type;
7000 } else {
7001 sym = sym_push(v, &type, 0, 0);
7003 sym->a = ad.a;
7004 sym->type.t |= VT_TYPEDEF;
7005 } else {
7006 r = 0;
7007 if ((type.t & VT_BTYPE) == VT_FUNC) {
7008 /* external function definition */
7009 /* specific case for func_call attribute */
7010 ad.a.func_proto = 1;
7011 type.ref->a = ad.a;
7012 } else if (!(type.t & VT_ARRAY)) {
7013 /* not lvalue if array */
7014 r |= lvalue_type(type.t);
7016 has_init = (tok == '=');
7017 if (has_init && (type.t & VT_VLA))
7018 tcc_error("variable length array cannot be initialized");
7019 if ((btype.t & VT_EXTERN) || ((type.t & VT_BTYPE) == VT_FUNC) ||
7020 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
7021 !has_init && l == VT_CONST && type.ref->c < 0)) {
7022 /* external variable or function */
7023 /* NOTE: as GCC, uninitialized global static
7024 arrays of null size are considered as
7025 extern */
7026 sym = external_sym(v, &type, r);
7027 sym->asm_label = ad.asm_label;
7029 if (ad.alias_target) {
7030 Section tsec;
7031 ElfW(Sym) *esym;
7032 Sym *alias_target;
7034 alias_target = sym_find(ad.alias_target);
7035 if (!alias_target || !alias_target->c)
7036 tcc_error("unsupported forward __alias__ attribute");
7037 esym = &((ElfW(Sym) *)symtab_section->data)[alias_target->c];
7038 tsec.sh_num = esym->st_shndx;
7039 put_extern_sym2(sym, &tsec, esym->st_value, esym->st_size, 0);
7041 } else {
7042 type.t |= (btype.t & VT_STATIC); /* Retain "static". */
7043 if (type.t & VT_STATIC)
7044 r |= VT_CONST;
7045 else
7046 r |= l;
7047 if (has_init)
7048 next();
7049 decl_initializer_alloc(&type, &ad, r, has_init, v, l);
7052 if (tok != ',') {
7053 if (is_for_loop_init)
7054 return 1;
7055 skip(';');
7056 break;
7058 next();
7060 ad.a.aligned = 0;
7063 return 0;
7066 ST_FUNC void decl(int l)
7068 decl0(l, 0);
7071 /* ------------------------------------------------------------------------- */