libtcc1: Don't use stdlib functions
[tinycc.git] / tccgen.c
blob2cc57bd4783d268284eb4b75d9f03cb926bd639c
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 l2 += vtop[-1].c.i;
1779 /* The backends can't always deal with addends to symbols
1780 larger than +-1<<31. Don't construct such. */
1781 if ((int)l2 != l2)
1782 goto general_case;
1783 vtop--;
1784 vtop->c.i = l2;
1785 } else {
1786 general_case:
1787 if (!nocode_wanted) {
1788 /* call low level op generator */
1789 if (t1 == VT_LLONG || t2 == VT_LLONG ||
1790 (PTR_SIZE == 8 && (t1 == VT_PTR || t2 == VT_PTR)))
1791 gen_opl(op);
1792 else
1793 gen_opi(op);
1794 } else {
1795 vtop--;
1796 /* Ensure vtop isn't marked VT_CONST in case something
1797 up our callchain is interested in const-ness of the
1798 expression. Also make it a non-LVAL if it was,
1799 so that further code can't accidentally generate
1800 a deref (happen only for buggy uses of e.g.
1801 gv() under nocode_wanted). */
1802 vtop->r &= ~(VT_VALMASK | VT_LVAL);
1808 /* generate a floating point operation with constant propagation */
1809 static void gen_opif(int op)
1811 int c1, c2;
1812 SValue *v1, *v2;
1813 long double f1, f2;
1815 v1 = vtop - 1;
1816 v2 = vtop;
1817 /* currently, we cannot do computations with forward symbols */
1818 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1819 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1820 if (c1 && c2) {
1821 if (v1->type.t == VT_FLOAT) {
1822 f1 = v1->c.f;
1823 f2 = v2->c.f;
1824 } else if (v1->type.t == VT_DOUBLE) {
1825 f1 = v1->c.d;
1826 f2 = v2->c.d;
1827 } else {
1828 f1 = v1->c.ld;
1829 f2 = v2->c.ld;
1832 /* NOTE: we only do constant propagation if finite number (not
1833 NaN or infinity) (ANSI spec) */
1834 if (!ieee_finite(f1) || !ieee_finite(f2))
1835 goto general_case;
1837 switch(op) {
1838 case '+': f1 += f2; break;
1839 case '-': f1 -= f2; break;
1840 case '*': f1 *= f2; break;
1841 case '/':
1842 if (f2 == 0.0) {
1843 if (const_wanted)
1844 tcc_error("division by zero in constant");
1845 goto general_case;
1847 f1 /= f2;
1848 break;
1849 /* XXX: also handles tests ? */
1850 default:
1851 goto general_case;
1853 /* XXX: overflow test ? */
1854 if (v1->type.t == VT_FLOAT) {
1855 v1->c.f = f1;
1856 } else if (v1->type.t == VT_DOUBLE) {
1857 v1->c.d = f1;
1858 } else {
1859 v1->c.ld = f1;
1861 vtop--;
1862 } else {
1863 general_case:
1864 if (!nocode_wanted) {
1865 gen_opf(op);
1866 } else {
1867 vtop--;
1872 static int pointed_size(CType *type)
1874 int align;
1875 return type_size(pointed_type(type), &align);
1878 static void vla_runtime_pointed_size(CType *type)
1880 int align;
1881 vla_runtime_type_size(pointed_type(type), &align);
1884 static inline int is_null_pointer(SValue *p)
1886 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
1887 return 0;
1888 return ((p->type.t & VT_BTYPE) == VT_INT && (uint32_t)p->c.i == 0) ||
1889 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.i == 0) ||
1890 ((p->type.t & VT_BTYPE) == VT_PTR &&
1891 (PTR_SIZE == 4 ? (uint32_t)p->c.i == 0 : p->c.i == 0));
1894 static inline int is_integer_btype(int bt)
1896 return (bt == VT_BYTE || bt == VT_SHORT ||
1897 bt == VT_INT || bt == VT_LLONG);
1900 /* check types for comparison or subtraction of pointers */
1901 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
1903 CType *type1, *type2, tmp_type1, tmp_type2;
1904 int bt1, bt2;
1906 /* null pointers are accepted for all comparisons as gcc */
1907 if (is_null_pointer(p1) || is_null_pointer(p2))
1908 return;
1909 type1 = &p1->type;
1910 type2 = &p2->type;
1911 bt1 = type1->t & VT_BTYPE;
1912 bt2 = type2->t & VT_BTYPE;
1913 /* accept comparison between pointer and integer with a warning */
1914 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
1915 if (op != TOK_LOR && op != TOK_LAND )
1916 tcc_warning("comparison between pointer and integer");
1917 return;
1920 /* both must be pointers or implicit function pointers */
1921 if (bt1 == VT_PTR) {
1922 type1 = pointed_type(type1);
1923 } else if (bt1 != VT_FUNC)
1924 goto invalid_operands;
1926 if (bt2 == VT_PTR) {
1927 type2 = pointed_type(type2);
1928 } else if (bt2 != VT_FUNC) {
1929 invalid_operands:
1930 tcc_error("invalid operands to binary %s", get_tok_str(op, NULL));
1932 if ((type1->t & VT_BTYPE) == VT_VOID ||
1933 (type2->t & VT_BTYPE) == VT_VOID)
1934 return;
1935 tmp_type1 = *type1;
1936 tmp_type2 = *type2;
1937 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1938 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1939 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
1940 /* gcc-like error if '-' is used */
1941 if (op == '-')
1942 goto invalid_operands;
1943 else
1944 tcc_warning("comparison of distinct pointer types lacks a cast");
1948 /* generic gen_op: handles types problems */
1949 ST_FUNC void gen_op(int op)
1951 int u, t1, t2, bt1, bt2, t;
1952 CType type1;
1954 redo:
1955 t1 = vtop[-1].type.t;
1956 t2 = vtop[0].type.t;
1957 bt1 = t1 & VT_BTYPE;
1958 bt2 = t2 & VT_BTYPE;
1960 if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
1961 tcc_error("operation on a struct");
1962 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
1963 if (bt2 == VT_FUNC) {
1964 mk_pointer(&vtop->type);
1965 gaddrof();
1967 if (bt1 == VT_FUNC) {
1968 vswap();
1969 mk_pointer(&vtop->type);
1970 gaddrof();
1971 vswap();
1973 goto redo;
1974 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
1975 /* at least one operand is a pointer */
1976 /* relationnal op: must be both pointers */
1977 if (op >= TOK_ULT && op <= TOK_LOR) {
1978 check_comparison_pointer_types(vtop - 1, vtop, op);
1979 /* pointers are handled are unsigned */
1980 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1981 t = VT_LLONG | VT_UNSIGNED;
1982 #else
1983 t = VT_INT | VT_UNSIGNED;
1984 #endif
1985 goto std_op;
1987 /* if both pointers, then it must be the '-' op */
1988 if (bt1 == VT_PTR && bt2 == VT_PTR) {
1989 if (op != '-')
1990 tcc_error("cannot use pointers here");
1991 check_comparison_pointer_types(vtop - 1, vtop, op);
1992 /* XXX: check that types are compatible */
1993 if (vtop[-1].type.t & VT_VLA) {
1994 vla_runtime_pointed_size(&vtop[-1].type);
1995 } else {
1996 vpushi(pointed_size(&vtop[-1].type));
1998 vrott(3);
1999 gen_opic(op);
2000 /* set to integer type */
2001 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2002 vtop->type.t = VT_LLONG;
2003 #else
2004 vtop->type.t = VT_INT;
2005 #endif
2006 vswap();
2007 gen_op(TOK_PDIV);
2008 } else {
2009 /* exactly one pointer : must be '+' or '-'. */
2010 if (op != '-' && op != '+')
2011 tcc_error("cannot use pointers here");
2012 /* Put pointer as first operand */
2013 if (bt2 == VT_PTR) {
2014 vswap();
2015 swap(&t1, &t2);
2017 #if PTR_SIZE == 4
2018 if ((vtop[0].type.t & VT_BTYPE) == VT_LLONG)
2019 /* XXX: truncate here because gen_opl can't handle ptr + long long */
2020 gen_cast(&int_type);
2021 #endif
2022 type1 = vtop[-1].type;
2023 type1.t &= ~VT_ARRAY;
2024 if (vtop[-1].type.t & VT_VLA)
2025 vla_runtime_pointed_size(&vtop[-1].type);
2026 else {
2027 u = pointed_size(&vtop[-1].type);
2028 if (u < 0)
2029 tcc_error("unknown array element size");
2030 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2031 vpushll(u);
2032 #else
2033 /* XXX: cast to int ? (long long case) */
2034 vpushi(u);
2035 #endif
2037 gen_op('*');
2038 #if 0
2039 /* #ifdef CONFIG_TCC_BCHECK
2040 The main reason to removing this code:
2041 #include <stdio.h>
2042 int main ()
2044 int v[10];
2045 int i = 10;
2046 int j = 9;
2047 fprintf(stderr, "v+i-j = %p\n", v+i-j);
2048 fprintf(stderr, "v+(i-j) = %p\n", v+(i-j));
2050 When this code is on. then the output looks like
2051 v+i-j = 0xfffffffe
2052 v+(i-j) = 0xbff84000
2054 /* if evaluating constant expression, no code should be
2055 generated, so no bound check */
2056 if (tcc_state->do_bounds_check && !const_wanted) {
2057 /* if bounded pointers, we generate a special code to
2058 test bounds */
2059 if (op == '-') {
2060 vpushi(0);
2061 vswap();
2062 gen_op('-');
2064 gen_bounded_ptr_add();
2065 } else
2066 #endif
2068 gen_opic(op);
2070 /* put again type if gen_opic() swaped operands */
2071 vtop->type = type1;
2073 } else if (is_float(bt1) || is_float(bt2)) {
2074 /* compute bigger type and do implicit casts */
2075 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
2076 t = VT_LDOUBLE;
2077 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
2078 t = VT_DOUBLE;
2079 } else {
2080 t = VT_FLOAT;
2082 /* floats can only be used for a few operations */
2083 if (op != '+' && op != '-' && op != '*' && op != '/' &&
2084 (op < TOK_ULT || op > TOK_GT))
2085 tcc_error("invalid operands for binary operation");
2086 goto std_op;
2087 } else if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL) {
2088 t = bt1 == VT_LLONG ? VT_LLONG : VT_INT;
2089 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (t | VT_UNSIGNED))
2090 t |= VT_UNSIGNED;
2091 goto std_op;
2092 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
2093 /* cast to biggest op */
2094 t = VT_LLONG;
2095 /* convert to unsigned if it does not fit in a long long */
2096 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
2097 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
2098 t |= VT_UNSIGNED;
2099 goto std_op;
2100 } else {
2101 /* integer operations */
2102 t = VT_INT;
2103 /* convert to unsigned if it does not fit in an integer */
2104 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
2105 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
2106 t |= VT_UNSIGNED;
2107 std_op:
2108 /* XXX: currently, some unsigned operations are explicit, so
2109 we modify them here */
2110 if (t & VT_UNSIGNED) {
2111 if (op == TOK_SAR)
2112 op = TOK_SHR;
2113 else if (op == '/')
2114 op = TOK_UDIV;
2115 else if (op == '%')
2116 op = TOK_UMOD;
2117 else if (op == TOK_LT)
2118 op = TOK_ULT;
2119 else if (op == TOK_GT)
2120 op = TOK_UGT;
2121 else if (op == TOK_LE)
2122 op = TOK_ULE;
2123 else if (op == TOK_GE)
2124 op = TOK_UGE;
2126 vswap();
2127 type1.t = t;
2128 gen_cast(&type1);
2129 vswap();
2130 /* special case for shifts and long long: we keep the shift as
2131 an integer */
2132 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
2133 type1.t = VT_INT;
2134 gen_cast(&type1);
2135 if (is_float(t))
2136 gen_opif(op);
2137 else
2138 gen_opic(op);
2139 if (op >= TOK_ULT && op <= TOK_GT) {
2140 /* relationnal op: the result is an int */
2141 vtop->type.t = VT_INT;
2142 } else {
2143 vtop->type.t = t;
2146 // Make sure that we have converted to an rvalue:
2147 if (vtop->r & VT_LVAL && !nocode_wanted)
2148 gv(is_float(vtop->type.t & VT_BTYPE) ? RC_FLOAT : RC_INT);
2151 #ifndef TCC_TARGET_ARM
2152 /* generic itof for unsigned long long case */
2153 static void gen_cvt_itof1(int t)
2155 #ifdef TCC_TARGET_ARM64
2156 gen_cvt_itof(t);
2157 #else
2158 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
2159 (VT_LLONG | VT_UNSIGNED)) {
2161 if (t == VT_FLOAT)
2162 vpush_global_sym(&func_old_type, TOK___floatundisf);
2163 #if LDOUBLE_SIZE != 8
2164 else if (t == VT_LDOUBLE)
2165 vpush_global_sym(&func_old_type, TOK___floatundixf);
2166 #endif
2167 else
2168 vpush_global_sym(&func_old_type, TOK___floatundidf);
2169 vrott(2);
2170 gfunc_call(1);
2171 vpushi(0);
2172 vtop->r = reg_fret(t);
2173 } else {
2174 gen_cvt_itof(t);
2176 #endif
2178 #endif
2180 /* generic ftoi for unsigned long long case */
2181 static void gen_cvt_ftoi1(int t)
2183 #ifdef TCC_TARGET_ARM64
2184 gen_cvt_ftoi(t);
2185 #else
2186 int st;
2188 if (t == (VT_LLONG | VT_UNSIGNED)) {
2189 /* not handled natively */
2190 st = vtop->type.t & VT_BTYPE;
2191 if (st == VT_FLOAT)
2192 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
2193 #if LDOUBLE_SIZE != 8
2194 else if (st == VT_LDOUBLE)
2195 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
2196 #endif
2197 else
2198 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
2199 vrott(2);
2200 gfunc_call(1);
2201 vpushi(0);
2202 vtop->r = REG_IRET;
2203 vtop->r2 = REG_LRET;
2204 } else {
2205 gen_cvt_ftoi(t);
2207 #endif
2210 /* force char or short cast */
2211 static void force_charshort_cast(int t)
2213 int bits, dbt;
2214 dbt = t & VT_BTYPE;
2215 /* XXX: add optimization if lvalue : just change type and offset */
2216 if (dbt == VT_BYTE)
2217 bits = 8;
2218 else
2219 bits = 16;
2220 if (t & VT_UNSIGNED) {
2221 vpushi((1 << bits) - 1);
2222 gen_op('&');
2223 } else {
2224 if ((vtop->type.t & VT_BTYPE) == VT_LLONG)
2225 bits = 64 - bits;
2226 else
2227 bits = 32 - bits;
2228 vpushi(bits);
2229 gen_op(TOK_SHL);
2230 /* result must be signed or the SAR is converted to an SHL
2231 This was not the case when "t" was a signed short
2232 and the last value on the stack was an unsigned int */
2233 vtop->type.t &= ~VT_UNSIGNED;
2234 vpushi(bits);
2235 gen_op(TOK_SAR);
2239 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
2240 static void gen_cast(CType *type)
2242 int sbt, dbt, sf, df, c, p;
2244 /* special delayed cast for char/short */
2245 /* XXX: in some cases (multiple cascaded casts), it may still
2246 be incorrect */
2247 if (vtop->r & VT_MUSTCAST) {
2248 vtop->r &= ~VT_MUSTCAST;
2249 force_charshort_cast(vtop->type.t);
2252 /* bitfields first get cast to ints */
2253 if (vtop->type.t & VT_BITFIELD && !nocode_wanted) {
2254 gv(RC_INT);
2257 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
2258 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
2260 if (sbt != dbt) {
2261 sf = is_float(sbt);
2262 df = is_float(dbt);
2263 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
2264 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
2265 if (c) {
2266 /* constant case: we can do it now */
2267 /* XXX: in ISOC, cannot do it if error in convert */
2268 if (sbt == VT_FLOAT)
2269 vtop->c.ld = vtop->c.f;
2270 else if (sbt == VT_DOUBLE)
2271 vtop->c.ld = vtop->c.d;
2273 if (df) {
2274 if ((sbt & VT_BTYPE) == VT_LLONG) {
2275 if ((sbt & VT_UNSIGNED) || !(vtop->c.i >> 63))
2276 vtop->c.ld = vtop->c.i;
2277 else
2278 vtop->c.ld = -(long double)-vtop->c.i;
2279 } else if(!sf) {
2280 if ((sbt & VT_UNSIGNED) || !(vtop->c.i >> 31))
2281 vtop->c.ld = (uint32_t)vtop->c.i;
2282 else
2283 vtop->c.ld = -(long double)-(uint32_t)vtop->c.i;
2286 if (dbt == VT_FLOAT)
2287 vtop->c.f = (float)vtop->c.ld;
2288 else if (dbt == VT_DOUBLE)
2289 vtop->c.d = (double)vtop->c.ld;
2290 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
2291 vtop->c.i = vtop->c.ld;
2292 } else if (sf && dbt == VT_BOOL) {
2293 vtop->c.i = (vtop->c.ld != 0);
2294 } else {
2295 if(sf)
2296 vtop->c.i = vtop->c.ld;
2297 else if (sbt == (VT_LLONG|VT_UNSIGNED))
2299 else if (sbt & VT_UNSIGNED)
2300 vtop->c.i = (uint32_t)vtop->c.i;
2301 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2302 else if (sbt == VT_PTR)
2304 #endif
2305 else if (sbt != VT_LLONG)
2306 vtop->c.i = ((uint32_t)vtop->c.i |
2307 -(vtop->c.i & 0x80000000));
2309 if (dbt == (VT_LLONG|VT_UNSIGNED))
2311 else if (dbt == VT_BOOL)
2312 vtop->c.i = (vtop->c.i != 0);
2313 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2314 else if (dbt == VT_PTR)
2316 #endif
2317 else if (dbt != VT_LLONG) {
2318 uint32_t m = ((dbt & VT_BTYPE) == VT_BYTE ? 0xff :
2319 (dbt & VT_BTYPE) == VT_SHORT ? 0xffff :
2320 0xffffffff);
2321 vtop->c.i &= m;
2322 if (!(dbt & VT_UNSIGNED))
2323 vtop->c.i |= -(vtop->c.i & ((m >> 1) + 1));
2326 } else if (p && dbt == VT_BOOL) {
2327 vtop->r = VT_CONST;
2328 vtop->c.i = 1;
2329 } else if (!nocode_wanted) {
2330 /* non constant case: generate code */
2331 if (sf && df) {
2332 /* convert from fp to fp */
2333 gen_cvt_ftof(dbt);
2334 } else if (df) {
2335 /* convert int to fp */
2336 gen_cvt_itof1(dbt);
2337 } else if (sf) {
2338 /* convert fp to int */
2339 if (dbt == VT_BOOL) {
2340 vpushi(0);
2341 gen_op(TOK_NE);
2342 } else {
2343 /* we handle char/short/etc... with generic code */
2344 if (dbt != (VT_INT | VT_UNSIGNED) &&
2345 dbt != (VT_LLONG | VT_UNSIGNED) &&
2346 dbt != VT_LLONG)
2347 dbt = VT_INT;
2348 gen_cvt_ftoi1(dbt);
2349 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
2350 /* additional cast for char/short... */
2351 vtop->type.t = dbt;
2352 gen_cast(type);
2355 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
2356 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
2357 if ((sbt & VT_BTYPE) != VT_LLONG) {
2358 /* scalar to long long */
2359 /* machine independent conversion */
2360 gv(RC_INT);
2361 /* generate high word */
2362 if (sbt == (VT_INT | VT_UNSIGNED)) {
2363 vpushi(0);
2364 gv(RC_INT);
2365 } else {
2366 if (sbt == VT_PTR) {
2367 /* cast from pointer to int before we apply
2368 shift operation, which pointers don't support*/
2369 gen_cast(&int_type);
2371 gv_dup();
2372 vpushi(31);
2373 gen_op(TOK_SAR);
2375 /* patch second register */
2376 vtop[-1].r2 = vtop->r;
2377 vpop();
2379 #else
2380 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
2381 (dbt & VT_BTYPE) == VT_PTR ||
2382 (dbt & VT_BTYPE) == VT_FUNC) {
2383 if ((sbt & VT_BTYPE) != VT_LLONG &&
2384 (sbt & VT_BTYPE) != VT_PTR &&
2385 (sbt & VT_BTYPE) != VT_FUNC) {
2386 /* need to convert from 32bit to 64bit */
2387 gv(RC_INT);
2388 if (sbt != (VT_INT | VT_UNSIGNED)) {
2389 #if defined(TCC_TARGET_ARM64)
2390 gen_cvt_sxtw();
2391 #elif defined(TCC_TARGET_X86_64)
2392 int r = gv(RC_INT);
2393 /* x86_64 specific: movslq */
2394 o(0x6348);
2395 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
2396 #else
2397 #error
2398 #endif
2401 #endif
2402 } else if (dbt == VT_BOOL) {
2403 /* scalar to bool */
2404 vpushi(0);
2405 gen_op(TOK_NE);
2406 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
2407 (dbt & VT_BTYPE) == VT_SHORT) {
2408 if (sbt == VT_PTR) {
2409 vtop->type.t = VT_INT;
2410 tcc_warning("nonportable conversion from pointer to char/short");
2412 force_charshort_cast(dbt);
2413 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
2414 } else if ((dbt & VT_BTYPE) == VT_INT) {
2415 /* scalar to int */
2416 if ((sbt & VT_BTYPE) == VT_LLONG) {
2417 /* from long long: just take low order word */
2418 lexpand();
2419 vpop();
2421 /* if lvalue and single word type, nothing to do because
2422 the lvalue already contains the real type size (see
2423 VT_LVAL_xxx constants) */
2424 #endif
2427 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
2428 /* if we are casting between pointer types,
2429 we must update the VT_LVAL_xxx size */
2430 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
2431 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
2433 vtop->type = *type;
2436 /* return type size as known at compile time. Put alignment at 'a' */
2437 ST_FUNC int type_size(CType *type, int *a)
2439 Sym *s;
2440 int bt;
2442 bt = type->t & VT_BTYPE;
2443 if (bt == VT_STRUCT) {
2444 /* struct/union */
2445 s = type->ref;
2446 *a = s->r;
2447 return s->c;
2448 } else if (bt == VT_PTR) {
2449 if (type->t & VT_ARRAY) {
2450 int ts;
2452 s = type->ref;
2453 ts = type_size(&s->type, a);
2455 if (ts < 0 && s->c < 0)
2456 ts = -ts;
2458 return ts * s->c;
2459 } else {
2460 *a = PTR_SIZE;
2461 return PTR_SIZE;
2463 } else if (bt == VT_LDOUBLE) {
2464 *a = LDOUBLE_ALIGN;
2465 return LDOUBLE_SIZE;
2466 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
2467 #ifdef TCC_TARGET_I386
2468 #ifdef TCC_TARGET_PE
2469 *a = 8;
2470 #else
2471 *a = 4;
2472 #endif
2473 #elif defined(TCC_TARGET_ARM)
2474 #ifdef TCC_ARM_EABI
2475 *a = 8;
2476 #else
2477 *a = 4;
2478 #endif
2479 #else
2480 *a = 8;
2481 #endif
2482 return 8;
2483 } else if (bt == VT_INT || bt == VT_FLOAT) {
2484 *a = 4;
2485 return 4;
2486 } else if (bt == VT_SHORT) {
2487 *a = 2;
2488 return 2;
2489 } else if (bt == VT_QLONG || bt == VT_QFLOAT) {
2490 *a = 8;
2491 return 16;
2492 } else if (bt == VT_ENUM) {
2493 *a = 4;
2494 /* Enums might be incomplete, so don't just return '4' here. */
2495 return type->ref->c;
2496 } else {
2497 /* char, void, function, _Bool */
2498 *a = 1;
2499 return 1;
2503 /* push type size as known at runtime time on top of value stack. Put
2504 alignment at 'a' */
2505 ST_FUNC void vla_runtime_type_size(CType *type, int *a)
2507 if (type->t & VT_VLA) {
2508 type_size(&type->ref->type, a);
2509 vset(&int_type, VT_LOCAL|VT_LVAL, type->ref->c);
2510 } else {
2511 vpushi(type_size(type, a));
2515 static void vla_sp_restore(void) {
2516 if (vlas_in_scope) {
2517 gen_vla_sp_restore(vla_sp_loc);
2521 static void vla_sp_restore_root(void) {
2522 if (vlas_in_scope) {
2523 gen_vla_sp_restore(vla_sp_root_loc);
2527 /* return the pointed type of t */
2528 static inline CType *pointed_type(CType *type)
2530 return &type->ref->type;
2533 /* modify type so that its it is a pointer to type. */
2534 ST_FUNC void mk_pointer(CType *type)
2536 Sym *s;
2537 s = sym_push(SYM_FIELD, type, 0, -1);
2538 type->t = VT_PTR | (type->t & ~VT_TYPE);
2539 type->ref = s;
2542 /* compare function types. OLD functions match any new functions */
2543 static int is_compatible_func(CType *type1, CType *type2)
2545 Sym *s1, *s2;
2547 s1 = type1->ref;
2548 s2 = type2->ref;
2549 if (!is_compatible_types(&s1->type, &s2->type))
2550 return 0;
2551 /* check func_call */
2552 if (s1->a.func_call != s2->a.func_call)
2553 return 0;
2554 /* XXX: not complete */
2555 if (s1->c == FUNC_OLD || s2->c == FUNC_OLD)
2556 return 1;
2557 if (s1->c != s2->c)
2558 return 0;
2559 while (s1 != NULL) {
2560 if (s2 == NULL)
2561 return 0;
2562 if (!is_compatible_parameter_types(&s1->type, &s2->type))
2563 return 0;
2564 s1 = s1->next;
2565 s2 = s2->next;
2567 if (s2)
2568 return 0;
2569 return 1;
2572 /* return true if type1 and type2 are the same. If unqualified is
2573 true, qualifiers on the types are ignored.
2575 - enums are not checked as gcc __builtin_types_compatible_p ()
2577 static int compare_types(CType *type1, CType *type2, int unqualified)
2579 int bt1, t1, t2;
2581 t1 = type1->t & VT_TYPE;
2582 t2 = type2->t & VT_TYPE;
2583 if (unqualified) {
2584 /* strip qualifiers before comparing */
2585 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
2586 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
2588 /* Default Vs explicit signedness only matters for char */
2589 if ((t1 & VT_BTYPE) != VT_BYTE) {
2590 t1 &= ~VT_DEFSIGN;
2591 t2 &= ~VT_DEFSIGN;
2593 /* An enum is compatible with (unsigned) int. Ideally we would
2594 store the enums signedness in type->ref.a.<some_bit> and
2595 only accept unsigned enums with unsigned int and vice versa.
2596 But one of our callers (gen_assign_cast) always strips VT_UNSIGNED
2597 from pointer target types, so we can't add it here either. */
2598 if ((t1 & VT_BTYPE) == VT_ENUM) {
2599 t1 = VT_INT;
2600 if (type1->ref->a.unsigned_enum)
2601 t1 |= VT_UNSIGNED;
2603 if ((t2 & VT_BTYPE) == VT_ENUM) {
2604 t2 = VT_INT;
2605 if (type2->ref->a.unsigned_enum)
2606 t2 |= VT_UNSIGNED;
2608 /* XXX: bitfields ? */
2609 if (t1 != t2)
2610 return 0;
2611 /* test more complicated cases */
2612 bt1 = t1 & VT_BTYPE;
2613 if (bt1 == VT_PTR) {
2614 type1 = pointed_type(type1);
2615 type2 = pointed_type(type2);
2616 return is_compatible_types(type1, type2);
2617 } else if (bt1 == VT_STRUCT) {
2618 return (type1->ref == type2->ref);
2619 } else if (bt1 == VT_FUNC) {
2620 return is_compatible_func(type1, type2);
2621 } else {
2622 return 1;
2626 /* return true if type1 and type2 are exactly the same (including
2627 qualifiers).
2629 static int is_compatible_types(CType *type1, CType *type2)
2631 return compare_types(type1,type2,0);
2634 /* return true if type1 and type2 are the same (ignoring qualifiers).
2636 static int is_compatible_parameter_types(CType *type1, CType *type2)
2638 return compare_types(type1,type2,1);
2641 /* print a type. If 'varstr' is not NULL, then the variable is also
2642 printed in the type */
2643 /* XXX: union */
2644 /* XXX: add array and function pointers */
2645 static void type_to_str(char *buf, int buf_size,
2646 CType *type, const char *varstr)
2648 int bt, v, t;
2649 Sym *s, *sa;
2650 char buf1[256];
2651 const char *tstr;
2653 t = type->t & VT_TYPE;
2654 bt = t & VT_BTYPE;
2655 buf[0] = '\0';
2656 if (t & VT_CONSTANT)
2657 pstrcat(buf, buf_size, "const ");
2658 if (t & VT_VOLATILE)
2659 pstrcat(buf, buf_size, "volatile ");
2660 if ((t & (VT_DEFSIGN | VT_UNSIGNED)) == (VT_DEFSIGN | VT_UNSIGNED))
2661 pstrcat(buf, buf_size, "unsigned ");
2662 else if (t & VT_DEFSIGN)
2663 pstrcat(buf, buf_size, "signed ");
2664 switch(bt) {
2665 case VT_VOID:
2666 tstr = "void";
2667 goto add_tstr;
2668 case VT_BOOL:
2669 tstr = "_Bool";
2670 goto add_tstr;
2671 case VT_BYTE:
2672 tstr = "char";
2673 goto add_tstr;
2674 case VT_SHORT:
2675 tstr = "short";
2676 goto add_tstr;
2677 case VT_INT:
2678 tstr = "int";
2679 goto add_tstr;
2680 case VT_LONG:
2681 tstr = "long";
2682 goto add_tstr;
2683 case VT_LLONG:
2684 tstr = "long long";
2685 goto add_tstr;
2686 case VT_FLOAT:
2687 tstr = "float";
2688 goto add_tstr;
2689 case VT_DOUBLE:
2690 tstr = "double";
2691 goto add_tstr;
2692 case VT_LDOUBLE:
2693 tstr = "long double";
2694 add_tstr:
2695 pstrcat(buf, buf_size, tstr);
2696 break;
2697 case VT_ENUM:
2698 case VT_STRUCT:
2699 if (bt == VT_STRUCT)
2700 tstr = "struct ";
2701 else
2702 tstr = "enum ";
2703 pstrcat(buf, buf_size, tstr);
2704 v = type->ref->v & ~SYM_STRUCT;
2705 if (v >= SYM_FIRST_ANOM)
2706 pstrcat(buf, buf_size, "<anonymous>");
2707 else
2708 pstrcat(buf, buf_size, get_tok_str(v, NULL));
2709 break;
2710 case VT_FUNC:
2711 s = type->ref;
2712 type_to_str(buf, buf_size, &s->type, varstr);
2713 pstrcat(buf, buf_size, "(");
2714 sa = s->next;
2715 while (sa != NULL) {
2716 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
2717 pstrcat(buf, buf_size, buf1);
2718 sa = sa->next;
2719 if (sa)
2720 pstrcat(buf, buf_size, ", ");
2722 pstrcat(buf, buf_size, ")");
2723 goto no_var;
2724 case VT_PTR:
2725 s = type->ref;
2726 if (t & VT_ARRAY) {
2727 snprintf(buf1, sizeof(buf1), "%s[%ld]", varstr ? varstr : "", s->c);
2728 type_to_str(buf, buf_size, &s->type, buf1);
2729 goto no_var;
2731 pstrcpy(buf1, sizeof(buf1), "*");
2732 if (t & VT_CONSTANT)
2733 pstrcat(buf1, buf_size, "const ");
2734 if (t & VT_VOLATILE)
2735 pstrcat(buf1, buf_size, "volatile ");
2736 if (varstr)
2737 pstrcat(buf1, sizeof(buf1), varstr);
2738 type_to_str(buf, buf_size, &s->type, buf1);
2739 goto no_var;
2741 if (varstr) {
2742 pstrcat(buf, buf_size, " ");
2743 pstrcat(buf, buf_size, varstr);
2745 no_var: ;
2748 /* verify type compatibility to store vtop in 'dt' type, and generate
2749 casts if needed. */
2750 static void gen_assign_cast(CType *dt)
2752 CType *st, *type1, *type2, tmp_type1, tmp_type2;
2753 char buf1[256], buf2[256];
2754 int dbt, sbt;
2756 st = &vtop->type; /* source type */
2757 dbt = dt->t & VT_BTYPE;
2758 sbt = st->t & VT_BTYPE;
2759 if (sbt == VT_VOID || dbt == VT_VOID) {
2760 if (sbt == VT_VOID && dbt == VT_VOID)
2761 ; /*
2762 It is Ok if both are void
2763 A test program:
2764 void func1() {}
2765 void func2() {
2766 return func1();
2768 gcc accepts this program
2770 else
2771 tcc_error("cannot cast from/to void");
2773 if (dt->t & VT_CONSTANT)
2774 tcc_warning("assignment of read-only location");
2775 switch(dbt) {
2776 case VT_PTR:
2777 /* special cases for pointers */
2778 /* '0' can also be a pointer */
2779 if (is_null_pointer(vtop))
2780 goto type_ok;
2781 /* accept implicit pointer to integer cast with warning */
2782 if (is_integer_btype(sbt)) {
2783 tcc_warning("assignment makes pointer from integer without a cast");
2784 goto type_ok;
2786 type1 = pointed_type(dt);
2787 /* a function is implicitely a function pointer */
2788 if (sbt == VT_FUNC) {
2789 if ((type1->t & VT_BTYPE) != VT_VOID &&
2790 !is_compatible_types(pointed_type(dt), st))
2791 tcc_warning("assignment from incompatible pointer type");
2792 goto type_ok;
2794 if (sbt != VT_PTR)
2795 goto error;
2796 type2 = pointed_type(st);
2797 if ((type1->t & VT_BTYPE) == VT_VOID ||
2798 (type2->t & VT_BTYPE) == VT_VOID) {
2799 /* void * can match anything */
2800 } else {
2801 /* exact type match, except for qualifiers */
2802 tmp_type1 = *type1;
2803 tmp_type2 = *type2;
2804 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2805 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2806 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2807 /* Like GCC don't warn by default for merely changes
2808 in pointer target signedness. Do warn for different
2809 base types, though, in particular for unsigned enums
2810 and signed int targets. */
2811 if ((tmp_type1.t & (VT_DEFSIGN | VT_UNSIGNED)) !=
2812 (tmp_type2.t & (VT_DEFSIGN | VT_UNSIGNED)) &&
2813 (tmp_type1.t & VT_BTYPE) == (tmp_type2.t & VT_BTYPE))
2815 else
2816 tcc_warning("assignment from incompatible pointer type");
2819 /* check const and volatile */
2820 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
2821 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
2822 tcc_warning("assignment discards qualifiers from pointer target type");
2823 break;
2824 case VT_BYTE:
2825 case VT_SHORT:
2826 case VT_INT:
2827 case VT_LLONG:
2828 if (sbt == VT_PTR || sbt == VT_FUNC) {
2829 tcc_warning("assignment makes integer from pointer without a cast");
2830 } else if (sbt == VT_STRUCT) {
2831 goto case_VT_STRUCT;
2833 /* XXX: more tests */
2834 break;
2835 case VT_STRUCT:
2836 case_VT_STRUCT:
2837 tmp_type1 = *dt;
2838 tmp_type2 = *st;
2839 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2840 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2841 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2842 error:
2843 type_to_str(buf1, sizeof(buf1), st, NULL);
2844 type_to_str(buf2, sizeof(buf2), dt, NULL);
2845 tcc_error("cannot cast '%s' to '%s'", buf1, buf2);
2847 break;
2849 type_ok:
2850 gen_cast(dt);
2853 /* store vtop in lvalue pushed on stack */
2854 ST_FUNC void vstore(void)
2856 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
2858 ft = vtop[-1].type.t;
2859 sbt = vtop->type.t & VT_BTYPE;
2860 dbt = ft & VT_BTYPE;
2861 if ((((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
2862 (sbt == VT_INT && dbt == VT_SHORT))
2863 && !(vtop->type.t & VT_BITFIELD)) {
2864 /* optimize char/short casts */
2865 delayed_cast = VT_MUSTCAST;
2866 vtop->type.t = (ft & VT_TYPE & ~VT_BITFIELD &
2867 ((1 << VT_STRUCT_SHIFT) - 1));
2868 /* XXX: factorize */
2869 if (ft & VT_CONSTANT)
2870 tcc_warning("assignment of read-only location");
2871 } else {
2872 delayed_cast = 0;
2873 if (!(ft & VT_BITFIELD))
2874 gen_assign_cast(&vtop[-1].type);
2877 if (sbt == VT_STRUCT) {
2878 /* if structure, only generate pointer */
2879 /* structure assignment : generate memcpy */
2880 /* XXX: optimize if small size */
2881 if (!nocode_wanted) {
2882 size = type_size(&vtop->type, &align);
2884 /* destination */
2885 vswap();
2886 vtop->type.t = VT_PTR;
2887 gaddrof();
2889 /* address of memcpy() */
2890 #ifdef TCC_ARM_EABI
2891 if(!(align & 7))
2892 vpush_global_sym(&func_old_type, TOK_memcpy8);
2893 else if(!(align & 3))
2894 vpush_global_sym(&func_old_type, TOK_memcpy4);
2895 else
2896 #endif
2897 /* Use memmove, rather than memcpy, as dest and src may be same: */
2898 vpush_global_sym(&func_old_type, TOK_memmove);
2900 vswap();
2901 /* source */
2902 vpushv(vtop - 2);
2903 vtop->type.t = VT_PTR;
2904 gaddrof();
2905 /* type size */
2906 vpushi(size);
2907 gfunc_call(3);
2908 } else {
2909 vswap();
2910 vpop();
2912 /* leave source on stack */
2913 } else if (ft & VT_BITFIELD) {
2914 /* bitfield store handling */
2916 /* save lvalue as expression result (example: s.b = s.a = n;) */
2917 vdup(), vtop[-1] = vtop[-2];
2919 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
2920 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
2921 /* remove bit field info to avoid loops */
2922 vtop[-1].type.t = ft & ~VT_BITFIELD & ((1 << VT_STRUCT_SHIFT) - 1);
2924 if((ft & VT_BTYPE) == VT_BOOL) {
2925 gen_cast(&vtop[-1].type);
2926 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
2929 /* duplicate destination */
2930 vdup();
2931 vtop[-1] = vtop[-2];
2933 /* mask and shift source */
2934 if((ft & VT_BTYPE) != VT_BOOL) {
2935 if((ft & VT_BTYPE) == VT_LLONG) {
2936 vpushll((1ULL << bit_size) - 1ULL);
2937 } else {
2938 vpushi((1 << bit_size) - 1);
2940 gen_op('&');
2942 vpushi(bit_pos);
2943 gen_op(TOK_SHL);
2944 /* load destination, mask and or with source */
2945 vswap();
2946 if((ft & VT_BTYPE) == VT_LLONG) {
2947 vpushll(~(((1ULL << bit_size) - 1ULL) << bit_pos));
2948 } else {
2949 vpushi(~(((1 << bit_size) - 1) << bit_pos));
2951 gen_op('&');
2952 gen_op('|');
2953 /* store result */
2954 vstore();
2955 /* ... and discard */
2956 vpop();
2958 } else {
2959 if (!nocode_wanted) {
2960 #ifdef CONFIG_TCC_BCHECK
2961 /* bound check case */
2962 if (vtop[-1].r & VT_MUSTBOUND) {
2963 vswap();
2964 gbound();
2965 vswap();
2967 #endif
2968 rc = RC_INT;
2969 if (is_float(ft)) {
2970 rc = RC_FLOAT;
2971 #ifdef TCC_TARGET_X86_64
2972 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
2973 rc = RC_ST0;
2974 } else if ((ft & VT_BTYPE) == VT_QFLOAT) {
2975 rc = RC_FRET;
2977 #endif
2979 r = gv(rc); /* generate value */
2980 /* if lvalue was saved on stack, must read it */
2981 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
2982 SValue sv;
2983 t = get_reg(RC_INT);
2984 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2985 sv.type.t = VT_PTR;
2986 #else
2987 sv.type.t = VT_INT;
2988 #endif
2989 sv.r = VT_LOCAL | VT_LVAL;
2990 sv.c.i = vtop[-1].c.i;
2991 load(t, &sv);
2992 vtop[-1].r = t | VT_LVAL;
2994 /* two word case handling : store second register at word + 4 (or +8 for x86-64) */
2995 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2996 if (((ft & VT_BTYPE) == VT_QLONG) || ((ft & VT_BTYPE) == VT_QFLOAT)) {
2997 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
2998 #else
2999 if ((ft & VT_BTYPE) == VT_LLONG) {
3000 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
3001 #endif
3002 vtop[-1].type.t = load_type;
3003 store(r, vtop - 1);
3004 vswap();
3005 /* convert to int to increment easily */
3006 vtop->type.t = addr_type;
3007 gaddrof();
3008 vpushi(load_size);
3009 gen_op('+');
3010 vtop->r |= VT_LVAL;
3011 vswap();
3012 vtop[-1].type.t = load_type;
3013 /* XXX: it works because r2 is spilled last ! */
3014 store(vtop->r2, vtop - 1);
3015 } else {
3016 store(r, vtop - 1);
3019 vswap();
3020 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
3021 vtop->r |= delayed_cast;
3025 /* post defines POST/PRE add. c is the token ++ or -- */
3026 ST_FUNC void inc(int post, int c)
3028 test_lvalue();
3029 vdup(); /* save lvalue */
3030 if (post) {
3031 if (!nocode_wanted)
3032 gv_dup(); /* duplicate value */
3033 else
3034 vdup(); /* duplicate value */
3035 vrotb(3);
3036 vrotb(3);
3038 /* add constant */
3039 vpushi(c - TOK_MID);
3040 gen_op('+');
3041 vstore(); /* store value */
3042 if (post)
3043 vpop(); /* if post op, return saved value */
3046 ST_FUNC void parse_mult_str (CString *astr, const char *msg)
3048 /* read the string */
3049 if (tok != TOK_STR)
3050 expect(msg);
3051 cstr_new(astr);
3052 while (tok == TOK_STR) {
3053 /* XXX: add \0 handling too ? */
3054 cstr_cat(astr, tokc.str.data, -1);
3055 next();
3057 cstr_ccat(astr, '\0');
3060 /* Parse GNUC __attribute__ extension. Currently, the following
3061 extensions are recognized:
3062 - aligned(n) : set data/function alignment.
3063 - packed : force data alignment to 1
3064 - section(x) : generate data/code in this section.
3065 - unused : currently ignored, but may be used someday.
3066 - regparm(n) : pass function parameters in registers (i386 only)
3068 static void parse_attribute(AttributeDef *ad)
3070 int t, n;
3071 CString astr;
3073 while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
3074 next();
3075 skip('(');
3076 skip('(');
3077 while (tok != ')') {
3078 if (tok < TOK_IDENT)
3079 expect("attribute name");
3080 t = tok;
3081 next();
3082 switch(t) {
3083 case TOK_SECTION1:
3084 case TOK_SECTION2:
3085 skip('(');
3086 parse_mult_str(&astr, "section name");
3087 ad->section = find_section(tcc_state, (char *)astr.data);
3088 skip(')');
3089 cstr_free(&astr);
3090 break;
3091 case TOK_ALIAS1:
3092 case TOK_ALIAS2:
3093 skip('(');
3094 parse_mult_str(&astr, "alias(\"target\")");
3095 ad->alias_target = /* save string as token, for later */
3096 tok_alloc((char*)astr.data, astr.size-1)->tok;
3097 skip(')');
3098 cstr_free(&astr);
3099 break;
3100 case TOK_VISIBILITY1:
3101 case TOK_VISIBILITY2:
3102 skip('(');
3103 parse_mult_str(&astr,
3104 "visibility(\"default|hidden|internal|protected\")");
3105 if (!strcmp (astr.data, "default"))
3106 ad->a.visibility = STV_DEFAULT;
3107 else if (!strcmp (astr.data, "hidden"))
3108 ad->a.visibility = STV_HIDDEN;
3109 else if (!strcmp (astr.data, "internal"))
3110 ad->a.visibility = STV_INTERNAL;
3111 else if (!strcmp (astr.data, "protected"))
3112 ad->a.visibility = STV_PROTECTED;
3113 else
3114 expect("visibility(\"default|hidden|internal|protected\")");
3115 skip(')');
3116 cstr_free(&astr);
3117 break;
3118 case TOK_ALIGNED1:
3119 case TOK_ALIGNED2:
3120 if (tok == '(') {
3121 next();
3122 n = expr_const();
3123 if (n <= 0 || (n & (n - 1)) != 0)
3124 tcc_error("alignment must be a positive power of two");
3125 skip(')');
3126 } else {
3127 n = MAX_ALIGN;
3129 ad->a.aligned = n;
3130 break;
3131 case TOK_PACKED1:
3132 case TOK_PACKED2:
3133 ad->a.packed = 1;
3134 break;
3135 case TOK_WEAK1:
3136 case TOK_WEAK2:
3137 ad->a.weak = 1;
3138 break;
3139 case TOK_UNUSED1:
3140 case TOK_UNUSED2:
3141 /* currently, no need to handle it because tcc does not
3142 track unused objects */
3143 break;
3144 case TOK_NORETURN1:
3145 case TOK_NORETURN2:
3146 /* currently, no need to handle it because tcc does not
3147 track unused objects */
3148 break;
3149 case TOK_CDECL1:
3150 case TOK_CDECL2:
3151 case TOK_CDECL3:
3152 ad->a.func_call = FUNC_CDECL;
3153 break;
3154 case TOK_STDCALL1:
3155 case TOK_STDCALL2:
3156 case TOK_STDCALL3:
3157 ad->a.func_call = FUNC_STDCALL;
3158 break;
3159 #ifdef TCC_TARGET_I386
3160 case TOK_REGPARM1:
3161 case TOK_REGPARM2:
3162 skip('(');
3163 n = expr_const();
3164 if (n > 3)
3165 n = 3;
3166 else if (n < 0)
3167 n = 0;
3168 if (n > 0)
3169 ad->a.func_call = FUNC_FASTCALL1 + n - 1;
3170 skip(')');
3171 break;
3172 case TOK_FASTCALL1:
3173 case TOK_FASTCALL2:
3174 case TOK_FASTCALL3:
3175 ad->a.func_call = FUNC_FASTCALLW;
3176 break;
3177 #endif
3178 case TOK_MODE:
3179 skip('(');
3180 switch(tok) {
3181 case TOK_MODE_DI:
3182 ad->a.mode = VT_LLONG + 1;
3183 break;
3184 case TOK_MODE_QI:
3185 ad->a.mode = VT_BYTE + 1;
3186 break;
3187 case TOK_MODE_HI:
3188 ad->a.mode = VT_SHORT + 1;
3189 break;
3190 case TOK_MODE_SI:
3191 case TOK_MODE_word:
3192 ad->a.mode = VT_INT + 1;
3193 break;
3194 default:
3195 tcc_warning("__mode__(%s) not supported\n", get_tok_str(tok, NULL));
3196 break;
3198 next();
3199 skip(')');
3200 break;
3201 case TOK_DLLEXPORT:
3202 ad->a.func_export = 1;
3203 break;
3204 case TOK_DLLIMPORT:
3205 ad->a.func_import = 1;
3206 break;
3207 default:
3208 if (tcc_state->warn_unsupported)
3209 tcc_warning("'%s' attribute ignored", get_tok_str(t, NULL));
3210 /* skip parameters */
3211 if (tok == '(') {
3212 int parenthesis = 0;
3213 do {
3214 if (tok == '(')
3215 parenthesis++;
3216 else if (tok == ')')
3217 parenthesis--;
3218 next();
3219 } while (parenthesis && tok != -1);
3221 break;
3223 if (tok != ',')
3224 break;
3225 next();
3227 skip(')');
3228 skip(')');
3232 static Sym * find_field (CType *type, int v)
3234 Sym *s = type->ref;
3235 v |= SYM_FIELD;
3236 while ((s = s->next) != NULL) {
3237 if ((s->v & SYM_FIELD) && (s->v & ~SYM_FIELD) >= SYM_FIRST_ANOM) {
3238 Sym *ret = find_field (&s->type, v);
3239 if (ret)
3240 return ret;
3242 if (s->v == v)
3243 break;
3245 return s;
3248 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
3249 static void struct_decl(CType *type, AttributeDef *ad, int u)
3251 int a, v, size, align, maxalign, c, offset, flexible, extra_bytes;
3252 int bit_size, bit_pos, bsize, bt, lbit_pos, prevbt;
3253 Sym *s, *ss, *ass, **ps;
3254 AttributeDef ad1;
3255 CType type1, btype;
3257 a = tok; /* save decl type */
3258 next();
3259 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3260 parse_attribute(ad);
3261 if (tok != '{') {
3262 v = tok;
3263 next();
3264 /* struct already defined ? return it */
3265 if (v < TOK_IDENT)
3266 expect("struct/union/enum name");
3267 s = struct_find(v);
3268 if (s && (s->scope == local_scope || (tok != '{' && tok != ';'))) {
3269 if (s->type.t != a)
3270 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
3271 goto do_decl;
3273 } else {
3274 v = anon_sym++;
3276 /* Record the original enum/struct/union token. */
3277 type1.t = a;
3278 type1.ref = NULL;
3279 /* we put an undefined size for struct/union */
3280 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
3281 s->r = 0; /* default alignment is zero as gcc */
3282 /* put struct/union/enum name in type */
3283 do_decl:
3284 type->t = u;
3285 type->ref = s;
3287 if (tok == '{') {
3288 next();
3289 if (s->c != -1)
3290 tcc_error("struct/union/enum already defined");
3291 /* cannot be empty */
3292 c = 0;
3293 /* non empty enums are not allowed */
3294 if (a == TOK_ENUM) {
3295 int seen_neg = 0;
3296 for(;;) {
3297 v = tok;
3298 if (v < TOK_UIDENT)
3299 expect("identifier");
3300 ss = sym_find(v);
3301 if (ss && !local_stack)
3302 tcc_error("redefinition of enumerator '%s'",
3303 get_tok_str(v, NULL));
3304 next();
3305 if (tok == '=') {
3306 next();
3307 c = expr_const();
3309 if (c < 0)
3310 seen_neg = 1;
3311 /* enum symbols have static storage */
3312 ss = sym_push(v, &int_type, VT_CONST, c);
3313 ss->type.t |= VT_STATIC;
3314 if (tok != ',')
3315 break;
3316 next();
3317 c++;
3318 /* NOTE: we accept a trailing comma */
3319 if (tok == '}')
3320 break;
3322 if (!seen_neg)
3323 s->a.unsigned_enum = 1;
3324 s->c = type_size(&int_type, &align);
3325 skip('}');
3326 } else {
3327 maxalign = 1;
3328 ps = &s->next;
3329 prevbt = VT_INT;
3330 bit_pos = 0;
3331 offset = 0;
3332 flexible = 0;
3333 while (tok != '}') {
3334 if (!parse_btype(&btype, &ad1)) {
3335 skip(';');
3336 continue;
3338 while (1) {
3339 extra_bytes = 0;
3340 if (flexible)
3341 tcc_error("flexible array member '%s' not at the end of struct",
3342 get_tok_str(v, NULL));
3343 bit_size = -1;
3344 v = 0;
3345 type1 = btype;
3346 if (tok != ':') {
3347 type_decl(&type1, &ad1, &v, TYPE_DIRECT | TYPE_ABSTRACT);
3348 if (v == 0) {
3349 if ((type1.t & VT_BTYPE) != VT_STRUCT)
3350 expect("identifier");
3351 else {
3352 int v = btype.ref->v;
3353 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
3354 if (tcc_state->ms_extensions == 0)
3355 expect("identifier");
3359 if (type_size(&type1, &align) < 0) {
3360 if ((a == TOK_STRUCT) && (type1.t & VT_ARRAY) && c)
3361 flexible = 1;
3362 else
3363 tcc_error("field '%s' has incomplete type",
3364 get_tok_str(v, NULL));
3366 if ((type1.t & VT_BTYPE) == VT_FUNC ||
3367 (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
3368 tcc_error("invalid type for '%s'",
3369 get_tok_str(v, NULL));
3371 if (tok == ':') {
3372 next();
3373 bit_size = expr_const();
3374 /* XXX: handle v = 0 case for messages */
3375 if (bit_size < 0)
3376 tcc_error("negative width in bit-field '%s'",
3377 get_tok_str(v, NULL));
3378 if (v && bit_size == 0)
3379 tcc_error("zero width for bit-field '%s'",
3380 get_tok_str(v, NULL));
3382 size = type_size(&type1, &align);
3383 if (ad1.a.aligned) {
3384 if (align < ad1.a.aligned)
3385 align = ad1.a.aligned;
3386 } else if (ad1.a.packed || ad->a.packed) {
3387 align = 1;
3388 } else if (*tcc_state->pack_stack_ptr) {
3389 if (align > *tcc_state->pack_stack_ptr)
3390 align = *tcc_state->pack_stack_ptr;
3392 lbit_pos = 0;
3393 if (bit_size >= 0) {
3394 bt = type1.t & VT_BTYPE;
3395 if (bt != VT_INT &&
3396 bt != VT_BYTE &&
3397 bt != VT_SHORT &&
3398 bt != VT_BOOL &&
3399 bt != VT_ENUM &&
3400 bt != VT_LLONG)
3401 tcc_error("bitfields must have scalar type");
3402 bsize = size * 8;
3403 if (bit_size > bsize) {
3404 tcc_error("width of '%s' exceeds its type",
3405 get_tok_str(v, NULL));
3406 } else if (bit_size == bsize) {
3407 /* no need for bit fields */
3408 bit_pos = 0;
3409 } else if (bit_size == 0) {
3410 /* XXX: what to do if only padding in a
3411 structure ? */
3412 /* zero size: means to pad */
3413 bit_pos = 0;
3414 } else {
3415 /* if type change, union, or will overrun
3416 * allignment slot, start at a newly
3417 * alligned slot */
3418 if ((bit_pos + bit_size) > bsize ||
3419 bt != prevbt || a == TOK_UNION)
3420 bit_pos = 0;
3421 lbit_pos = bit_pos;
3422 /* XXX: handle LSB first */
3423 type1.t |= VT_BITFIELD |
3424 (bit_pos << VT_STRUCT_SHIFT) |
3425 (bit_size << (VT_STRUCT_SHIFT + 6));
3426 bit_pos += bit_size;
3427 /* without ms-bitfields, allocate the
3428 * minimum number of bytes necessary,
3429 * adding single bytes as needed */
3430 if (!tcc_state->ms_bitfields) {
3431 if (lbit_pos == 0)
3432 /* minimum bytes for new bitfield */
3433 size = (bit_size + 7) / 8;
3434 else {
3435 /* enough spare bits already allocated? */
3436 bit_size = (lbit_pos - 1) % 8 + 1 + bit_size;
3437 if (bit_size > 8) /* doesn't fit */
3438 extra_bytes = (bit_size - 1) / 8;
3442 prevbt = bt;
3443 } else {
3444 bit_pos = 0;
3446 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
3447 /* add new memory data only if starting bit
3448 field or adding bytes to existing bit field */
3449 if (extra_bytes) c += extra_bytes;
3450 else if (lbit_pos == 0) {
3451 if (a == TOK_STRUCT) {
3452 c = (c + align - 1) & -align;
3453 offset = c;
3454 if (size > 0)
3455 c += size;
3456 } else {
3457 offset = 0;
3458 if (size > c)
3459 c = size;
3461 if (align > maxalign)
3462 maxalign = align;
3464 #if 0
3465 printf("add field %s offset=%d",
3466 get_tok_str(v, NULL), offset);
3467 if (type1.t & VT_BITFIELD) {
3468 printf(" pos=%d size=%d",
3469 (type1.t >> VT_STRUCT_SHIFT) & 0x3f,
3470 (type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
3472 printf("\n");
3473 #endif
3475 if (v == 0 && (type1.t & VT_BTYPE) == VT_STRUCT) {
3476 /* An anonymous struct/union. Adjust member offsets
3477 to reflect the real offset of our containing struct.
3478 Also set the offset of this anon member inside
3479 the outer struct to be zero. Via this it
3480 works when accessing the field offset directly
3481 (from base object), as well as when recursing
3482 members in initializer handling. */
3483 int v2 = btype.ref->v;
3484 if (!(v2 & SYM_FIELD) &&
3485 (v2 & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
3486 Sym **pps;
3487 /* This happens only with MS extensions. The
3488 anon member has a named struct type, so it
3489 potentially is shared with other references.
3490 We need to unshare members so we can modify
3491 them. */
3492 ass = type1.ref;
3493 type1.ref = sym_push(anon_sym++ | SYM_FIELD,
3494 &type1.ref->type, 0,
3495 type1.ref->c);
3496 pps = &type1.ref->next;
3497 while ((ass = ass->next) != NULL) {
3498 *pps = sym_push(ass->v, &ass->type, 0, ass->c);
3499 pps = &((*pps)->next);
3501 *pps = NULL;
3503 ass = type1.ref;
3504 while ((ass = ass->next) != NULL)
3505 ass->c += offset;
3506 offset = 0;
3507 v = anon_sym++;
3509 if (v) {
3510 ss = sym_push(v | SYM_FIELD, &type1, 0, offset);
3511 *ps = ss;
3512 ps = &ss->next;
3514 if (tok == ';' || tok == TOK_EOF)
3515 break;
3516 skip(',');
3518 skip(';');
3520 skip('}');
3521 /* store size and alignment */
3522 s->c = (c + maxalign - 1) & -maxalign;
3523 s->r = maxalign;
3528 /* return 1 if basic type is a type size (short, long, long long) */
3529 ST_FUNC int is_btype_size(int bt)
3531 return bt == VT_SHORT || bt == VT_LONG || bt == VT_LLONG;
3534 /* Add type qualifiers to a type. If the type is an array then the qualifiers
3535 are added to the element type, copied because it could be a typedef. */
3536 static void parse_btype_qualify(CType *type, int qualifiers)
3538 while (type->t & VT_ARRAY) {
3539 type->ref = sym_push(SYM_FIELD, &type->ref->type, 0, type->ref->c);
3540 type = &type->ref->type;
3542 type->t |= qualifiers;
3545 /* return 0 if no type declaration. otherwise, return the basic type
3546 and skip it.
3548 static int parse_btype(CType *type, AttributeDef *ad)
3550 int t, u, bt_size, complete, type_found, typespec_found;
3551 Sym *s;
3552 CType type1;
3554 memset(ad, 0, sizeof(AttributeDef));
3555 complete = 0;
3556 type_found = 0;
3557 typespec_found = 0;
3558 t = 0;
3559 while(1) {
3560 switch(tok) {
3561 case TOK_EXTENSION:
3562 /* currently, we really ignore extension */
3563 next();
3564 continue;
3566 /* basic types */
3567 case TOK_CHAR:
3568 u = VT_BYTE;
3569 basic_type:
3570 next();
3571 basic_type1:
3572 if (complete)
3573 tcc_error("too many basic types");
3574 t |= u;
3575 bt_size = is_btype_size (u & VT_BTYPE);
3576 if (u == VT_INT || (!bt_size && !(t & VT_TYPEDEF)))
3577 complete = 1;
3578 typespec_found = 1;
3579 break;
3580 case TOK_VOID:
3581 u = VT_VOID;
3582 goto basic_type;
3583 case TOK_SHORT:
3584 u = VT_SHORT;
3585 goto basic_type;
3586 case TOK_INT:
3587 u = VT_INT;
3588 goto basic_type;
3589 case TOK_LONG:
3590 next();
3591 if ((t & VT_BTYPE) == VT_DOUBLE) {
3592 #ifndef TCC_TARGET_PE
3593 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3594 #endif
3595 } else if ((t & VT_BTYPE) == VT_LONG) {
3596 t = (t & ~VT_BTYPE) | VT_LLONG;
3597 } else {
3598 u = VT_LONG;
3599 goto basic_type1;
3601 break;
3602 #ifdef TCC_TARGET_ARM64
3603 case TOK_UINT128:
3604 /* GCC's __uint128_t appears in some Linux header files. Make it a
3605 synonym for long double to get the size and alignment right. */
3606 u = VT_LDOUBLE;
3607 goto basic_type;
3608 #endif
3609 case TOK_BOOL:
3610 u = VT_BOOL;
3611 goto basic_type;
3612 case TOK_FLOAT:
3613 u = VT_FLOAT;
3614 goto basic_type;
3615 case TOK_DOUBLE:
3616 next();
3617 if ((t & VT_BTYPE) == VT_LONG) {
3618 #ifdef TCC_TARGET_PE
3619 t = (t & ~VT_BTYPE) | VT_DOUBLE;
3620 #else
3621 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3622 #endif
3623 } else {
3624 u = VT_DOUBLE;
3625 goto basic_type1;
3627 break;
3628 case TOK_ENUM:
3629 struct_decl(&type1, ad, VT_ENUM);
3630 basic_type2:
3631 u = type1.t;
3632 type->ref = type1.ref;
3633 goto basic_type1;
3634 case TOK_STRUCT:
3635 case TOK_UNION:
3636 struct_decl(&type1, ad, VT_STRUCT);
3637 goto basic_type2;
3639 /* type modifiers */
3640 case TOK_CONST1:
3641 case TOK_CONST2:
3642 case TOK_CONST3:
3643 type->t = t;
3644 parse_btype_qualify(type, VT_CONSTANT);
3645 t = type->t;
3646 next();
3647 break;
3648 case TOK_VOLATILE1:
3649 case TOK_VOLATILE2:
3650 case TOK_VOLATILE3:
3651 type->t = t;
3652 parse_btype_qualify(type, VT_VOLATILE);
3653 t = type->t;
3654 next();
3655 break;
3656 case TOK_SIGNED1:
3657 case TOK_SIGNED2:
3658 case TOK_SIGNED3:
3659 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == (VT_DEFSIGN|VT_UNSIGNED))
3660 tcc_error("signed and unsigned modifier");
3661 typespec_found = 1;
3662 t |= VT_DEFSIGN;
3663 next();
3664 break;
3665 case TOK_REGISTER:
3666 case TOK_AUTO:
3667 case TOK_RESTRICT1:
3668 case TOK_RESTRICT2:
3669 case TOK_RESTRICT3:
3670 next();
3671 break;
3672 case TOK_UNSIGNED:
3673 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == VT_DEFSIGN)
3674 tcc_error("signed and unsigned modifier");
3675 t |= VT_DEFSIGN | VT_UNSIGNED;
3676 next();
3677 typespec_found = 1;
3678 break;
3680 /* storage */
3681 case TOK_EXTERN:
3682 t |= VT_EXTERN;
3683 next();
3684 break;
3685 case TOK_STATIC:
3686 t |= VT_STATIC;
3687 next();
3688 break;
3689 case TOK_TYPEDEF:
3690 t |= VT_TYPEDEF;
3691 next();
3692 break;
3693 case TOK_INLINE1:
3694 case TOK_INLINE2:
3695 case TOK_INLINE3:
3696 t |= VT_INLINE;
3697 next();
3698 break;
3700 /* GNUC attribute */
3701 case TOK_ATTRIBUTE1:
3702 case TOK_ATTRIBUTE2:
3703 parse_attribute(ad);
3704 if (ad->a.mode) {
3705 u = ad->a.mode -1;
3706 t = (t & ~VT_BTYPE) | u;
3708 break;
3709 /* GNUC typeof */
3710 case TOK_TYPEOF1:
3711 case TOK_TYPEOF2:
3712 case TOK_TYPEOF3:
3713 next();
3714 parse_expr_type(&type1);
3715 /* remove all storage modifiers except typedef */
3716 type1.t &= ~(VT_STORAGE&~VT_TYPEDEF);
3717 goto basic_type2;
3718 default:
3719 if (typespec_found)
3720 goto the_end;
3721 s = sym_find(tok);
3722 if (!s || !(s->type.t & VT_TYPEDEF))
3723 goto the_end;
3725 type->t = ((s->type.t & ~VT_TYPEDEF) |
3726 (t & ~(VT_CONSTANT | VT_VOLATILE)));
3727 type->ref = s->type.ref;
3728 if (t & (VT_CONSTANT | VT_VOLATILE))
3729 parse_btype_qualify(type, t & (VT_CONSTANT | VT_VOLATILE));
3730 t = type->t;
3732 if (s->r) {
3733 /* get attributes from typedef */
3734 if (0 == ad->a.aligned)
3735 ad->a.aligned = s->a.aligned;
3736 if (0 == ad->a.func_call)
3737 ad->a.func_call = s->a.func_call;
3738 ad->a.packed |= s->a.packed;
3740 next();
3741 typespec_found = 1;
3742 break;
3744 type_found = 1;
3746 the_end:
3747 if (tcc_state->char_is_unsigned) {
3748 if ((t & (VT_DEFSIGN|VT_BTYPE)) == VT_BYTE)
3749 t |= VT_UNSIGNED;
3752 /* long is never used as type */
3753 if ((t & VT_BTYPE) == VT_LONG)
3754 #if (!defined TCC_TARGET_X86_64 && !defined TCC_TARGET_ARM64) || \
3755 defined TCC_TARGET_PE
3756 t = (t & ~VT_BTYPE) | VT_INT;
3757 #else
3758 t = (t & ~VT_BTYPE) | VT_LLONG;
3759 #endif
3760 type->t = t;
3761 return type_found;
3764 /* convert a function parameter type (array to pointer and function to
3765 function pointer) */
3766 static inline void convert_parameter_type(CType *pt)
3768 /* remove const and volatile qualifiers (XXX: const could be used
3769 to indicate a const function parameter */
3770 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
3771 /* array must be transformed to pointer according to ANSI C */
3772 pt->t &= ~VT_ARRAY;
3773 if ((pt->t & VT_BTYPE) == VT_FUNC) {
3774 mk_pointer(pt);
3778 ST_FUNC void parse_asm_str(CString *astr)
3780 skip('(');
3781 parse_mult_str(astr, "string constant");
3784 /* Parse an asm label and return the token */
3785 static int asm_label_instr(void)
3787 int v;
3788 CString astr;
3790 next();
3791 parse_asm_str(&astr);
3792 skip(')');
3793 #ifdef ASM_DEBUG
3794 printf("asm_alias: \"%s\"\n", (char *)astr.data);
3795 #endif
3796 v = tok_alloc(astr.data, astr.size - 1)->tok;
3797 cstr_free(&astr);
3798 return v;
3801 static void post_type(CType *type, AttributeDef *ad, int storage)
3803 int n, l, t1, arg_size, align;
3804 Sym **plast, *s, *first;
3805 AttributeDef ad1;
3806 CType pt;
3808 if (tok == '(') {
3809 /* function declaration */
3810 next();
3811 l = 0;
3812 first = NULL;
3813 plast = &first;
3814 arg_size = 0;
3815 if (tok != ')') {
3816 for(;;) {
3817 /* read param name and compute offset */
3818 if (l != FUNC_OLD) {
3819 if (!parse_btype(&pt, &ad1)) {
3820 if (l) {
3821 tcc_error("invalid type");
3822 } else {
3823 l = FUNC_OLD;
3824 goto old_proto;
3827 l = FUNC_NEW;
3828 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
3829 break;
3830 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
3831 if ((pt.t & VT_BTYPE) == VT_VOID)
3832 tcc_error("parameter declared as void");
3833 arg_size += (type_size(&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
3834 } else {
3835 old_proto:
3836 n = tok;
3837 if (n < TOK_UIDENT)
3838 expect("identifier");
3839 pt.t = VT_INT;
3840 next();
3842 convert_parameter_type(&pt);
3843 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
3844 *plast = s;
3845 plast = &s->next;
3846 if (tok == ')')
3847 break;
3848 skip(',');
3849 if (l == FUNC_NEW && tok == TOK_DOTS) {
3850 l = FUNC_ELLIPSIS;
3851 next();
3852 break;
3856 /* if no parameters, then old type prototype */
3857 if (l == 0)
3858 l = FUNC_OLD;
3859 skip(')');
3860 /* NOTE: const is ignored in returned type as it has a special
3861 meaning in gcc / C++ */
3862 type->t &= ~VT_CONSTANT;
3863 /* some ancient pre-K&R C allows a function to return an array
3864 and the array brackets to be put after the arguments, such
3865 that "int c()[]" means something like "int[] c()" */
3866 if (tok == '[') {
3867 next();
3868 skip(']'); /* only handle simple "[]" */
3869 type->t |= VT_PTR;
3871 /* we push a anonymous symbol which will contain the function prototype */
3872 ad->a.func_args = arg_size;
3873 s = sym_push(SYM_FIELD, type, 0, l);
3874 s->a = ad->a;
3875 s->next = first;
3876 type->t = VT_FUNC;
3877 type->ref = s;
3878 } else if (tok == '[') {
3879 int saved_nocode_wanted = nocode_wanted;
3880 /* array definition */
3881 next();
3882 if (tok == TOK_RESTRICT1)
3883 next();
3884 n = -1;
3885 t1 = 0;
3886 if (tok != ']') {
3887 if (!local_stack || (storage & VT_STATIC))
3888 vpushi(expr_const());
3889 else {
3890 /* VLAs (which can only happen with local_stack && !VT_STATIC)
3891 length must always be evaluated, even under nocode_wanted,
3892 so that its size slot is initialized (e.g. under sizeof
3893 or typeof). */
3894 nocode_wanted = 0;
3895 gexpr();
3897 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3898 n = vtop->c.i;
3899 if (n < 0)
3900 tcc_error("invalid array size");
3901 } else {
3902 if (!is_integer_btype(vtop->type.t & VT_BTYPE))
3903 tcc_error("size of variable length array should be an integer");
3904 t1 = VT_VLA;
3907 skip(']');
3908 /* parse next post type */
3909 post_type(type, ad, storage);
3910 if (type->t == VT_FUNC)
3911 tcc_error("declaration of an array of functions");
3912 t1 |= type->t & VT_VLA;
3914 if (t1 & VT_VLA) {
3915 loc -= type_size(&int_type, &align);
3916 loc &= -align;
3917 n = loc;
3919 vla_runtime_type_size(type, &align);
3920 gen_op('*');
3921 vset(&int_type, VT_LOCAL|VT_LVAL, n);
3922 vswap();
3923 vstore();
3925 if (n != -1)
3926 vpop();
3927 nocode_wanted = saved_nocode_wanted;
3929 /* we push an anonymous symbol which will contain the array
3930 element type */
3931 s = sym_push(SYM_FIELD, type, 0, n);
3932 type->t = (t1 ? VT_VLA : VT_ARRAY) | VT_PTR;
3933 type->ref = s;
3937 /* Parse a type declaration (except basic type), and return the type
3938 in 'type'. 'td' is a bitmask indicating which kind of type decl is
3939 expected. 'type' should contain the basic type. 'ad' is the
3940 attribute definition of the basic type. It can be modified by
3941 type_decl().
3943 static void type_decl(CType *type, AttributeDef *ad, int *v, int td)
3945 Sym *s;
3946 CType type1, *type2;
3947 int qualifiers, storage;
3949 while (tok == '*') {
3950 qualifiers = 0;
3951 redo:
3952 next();
3953 switch(tok) {
3954 case TOK_CONST1:
3955 case TOK_CONST2:
3956 case TOK_CONST3:
3957 qualifiers |= VT_CONSTANT;
3958 goto redo;
3959 case TOK_VOLATILE1:
3960 case TOK_VOLATILE2:
3961 case TOK_VOLATILE3:
3962 qualifiers |= VT_VOLATILE;
3963 goto redo;
3964 case TOK_RESTRICT1:
3965 case TOK_RESTRICT2:
3966 case TOK_RESTRICT3:
3967 goto redo;
3968 /* XXX: clarify attribute handling */
3969 case TOK_ATTRIBUTE1:
3970 case TOK_ATTRIBUTE2:
3971 parse_attribute(ad);
3972 break;
3974 mk_pointer(type);
3975 type->t |= qualifiers;
3978 /* recursive type */
3979 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
3980 type1.t = 0; /* XXX: same as int */
3981 if (tok == '(') {
3982 next();
3983 /* XXX: this is not correct to modify 'ad' at this point, but
3984 the syntax is not clear */
3985 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3986 parse_attribute(ad);
3987 type_decl(&type1, ad, v, td);
3988 skip(')');
3989 } else {
3990 /* type identifier */
3991 if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
3992 *v = tok;
3993 next();
3994 } else {
3995 if (!(td & TYPE_ABSTRACT))
3996 expect("identifier");
3997 *v = 0;
4000 storage = type->t & VT_STORAGE;
4001 type->t &= ~VT_STORAGE;
4002 post_type(type, ad, storage);
4003 type->t |= storage;
4004 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
4005 parse_attribute(ad);
4007 if (!type1.t)
4008 return;
4009 /* append type at the end of type1 */
4010 type2 = &type1;
4011 for(;;) {
4012 s = type2->ref;
4013 type2 = &s->type;
4014 if (!type2->t) {
4015 *type2 = *type;
4016 break;
4019 *type = type1;
4022 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
4023 ST_FUNC int lvalue_type(int t)
4025 int bt, r;
4026 r = VT_LVAL;
4027 bt = t & VT_BTYPE;
4028 if (bt == VT_BYTE || bt == VT_BOOL)
4029 r |= VT_LVAL_BYTE;
4030 else if (bt == VT_SHORT)
4031 r |= VT_LVAL_SHORT;
4032 else
4033 return r;
4034 if (t & VT_UNSIGNED)
4035 r |= VT_LVAL_UNSIGNED;
4036 return r;
4039 /* indirection with full error checking and bound check */
4040 ST_FUNC void indir(void)
4042 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
4043 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
4044 return;
4045 expect("pointer");
4047 if ((vtop->r & VT_LVAL) && !nocode_wanted)
4048 gv(RC_INT);
4049 vtop->type = *pointed_type(&vtop->type);
4050 /* Arrays and functions are never lvalues */
4051 if (!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_VLA)
4052 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
4053 vtop->r |= lvalue_type(vtop->type.t);
4054 /* if bound checking, the referenced pointer must be checked */
4055 #ifdef CONFIG_TCC_BCHECK
4056 if (tcc_state->do_bounds_check)
4057 vtop->r |= VT_MUSTBOUND;
4058 #endif
4062 /* pass a parameter to a function and do type checking and casting */
4063 static void gfunc_param_typed(Sym *func, Sym *arg)
4065 int func_type;
4066 CType type;
4068 func_type = func->c;
4069 if (func_type == FUNC_OLD ||
4070 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
4071 /* default casting : only need to convert float to double */
4072 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
4073 type.t = VT_DOUBLE;
4074 gen_cast(&type);
4075 } else if (vtop->type.t & VT_BITFIELD) {
4076 type.t = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
4077 type.ref = vtop->type.ref;
4078 gen_cast(&type);
4080 } else if (arg == NULL) {
4081 tcc_error("too many arguments to function");
4082 } else {
4083 type = arg->type;
4084 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
4085 gen_assign_cast(&type);
4089 /* parse an expression of the form '(type)' or '(expr)' and return its
4090 type */
4091 static void parse_expr_type(CType *type)
4093 int n;
4094 AttributeDef ad;
4096 skip('(');
4097 if (parse_btype(type, &ad)) {
4098 type_decl(type, &ad, &n, TYPE_ABSTRACT);
4099 } else {
4100 expr_type(type);
4102 skip(')');
4105 static void parse_type(CType *type)
4107 AttributeDef ad;
4108 int n;
4110 if (!parse_btype(type, &ad)) {
4111 expect("type");
4113 type_decl(type, &ad, &n, TYPE_ABSTRACT);
4116 static void vpush_tokc(int t)
4118 CType type;
4119 type.t = t;
4120 type.ref = 0;
4121 vsetc(&type, VT_CONST, &tokc);
4124 ST_FUNC void unary(void)
4126 int n, t, align, size, r, sizeof_caller;
4127 CType type;
4128 Sym *s;
4129 AttributeDef ad;
4131 sizeof_caller = in_sizeof;
4132 in_sizeof = 0;
4133 /* XXX: GCC 2.95.3 does not generate a table although it should be
4134 better here */
4135 tok_next:
4136 switch(tok) {
4137 case TOK_EXTENSION:
4138 next();
4139 goto tok_next;
4140 case TOK_CINT:
4141 case TOK_CCHAR:
4142 case TOK_LCHAR:
4143 vpushi(tokc.i);
4144 next();
4145 break;
4146 case TOK_CUINT:
4147 vpush_tokc(VT_INT | VT_UNSIGNED);
4148 next();
4149 break;
4150 case TOK_CLLONG:
4151 vpush_tokc(VT_LLONG);
4152 next();
4153 break;
4154 case TOK_CULLONG:
4155 vpush_tokc(VT_LLONG | VT_UNSIGNED);
4156 next();
4157 break;
4158 case TOK_CFLOAT:
4159 vpush_tokc(VT_FLOAT);
4160 next();
4161 break;
4162 case TOK_CDOUBLE:
4163 vpush_tokc(VT_DOUBLE);
4164 next();
4165 break;
4166 case TOK_CLDOUBLE:
4167 vpush_tokc(VT_LDOUBLE);
4168 next();
4169 break;
4170 case TOK___FUNCTION__:
4171 if (!gnu_ext)
4172 goto tok_identifier;
4173 /* fall thru */
4174 case TOK___FUNC__:
4176 void *ptr;
4177 int len;
4178 /* special function name identifier */
4179 len = strlen(funcname) + 1;
4180 /* generate char[len] type */
4181 type.t = VT_BYTE;
4182 mk_pointer(&type);
4183 type.t |= VT_ARRAY;
4184 type.ref->c = len;
4185 vpush_ref(&type, data_section, data_section->data_offset, len);
4186 ptr = section_ptr_add(data_section, len);
4187 memcpy(ptr, funcname, len);
4188 next();
4190 break;
4191 case TOK_LSTR:
4192 #ifdef TCC_TARGET_PE
4193 t = VT_SHORT | VT_UNSIGNED;
4194 #else
4195 t = VT_INT;
4196 #endif
4197 goto str_init;
4198 case TOK_STR:
4199 /* string parsing */
4200 t = VT_BYTE;
4201 str_init:
4202 if (tcc_state->warn_write_strings)
4203 t |= VT_CONSTANT;
4204 type.t = t;
4205 mk_pointer(&type);
4206 type.t |= VT_ARRAY;
4207 memset(&ad, 0, sizeof(AttributeDef));
4208 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, 0);
4209 break;
4210 case '(':
4211 next();
4212 /* cast ? */
4213 if (parse_btype(&type, &ad)) {
4214 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
4215 skip(')');
4216 /* check ISOC99 compound literal */
4217 if (tok == '{') {
4218 /* data is allocated locally by default */
4219 if (global_expr)
4220 r = VT_CONST;
4221 else
4222 r = VT_LOCAL;
4223 /* all except arrays are lvalues */
4224 if (!(type.t & VT_ARRAY))
4225 r |= lvalue_type(type.t);
4226 memset(&ad, 0, sizeof(AttributeDef));
4227 decl_initializer_alloc(&type, &ad, r, 1, 0, 0);
4228 } else {
4229 if (sizeof_caller) {
4230 vpush(&type);
4231 return;
4233 unary();
4234 gen_cast(&type);
4236 } else if (tok == '{') {
4237 if (const_wanted)
4238 tcc_error("expected constant");
4239 /* save all registers */
4240 if (!nocode_wanted)
4241 save_regs(0);
4242 /* statement expression : we do not accept break/continue
4243 inside as GCC does */
4244 block(NULL, NULL, 1);
4245 skip(')');
4246 } else {
4247 gexpr();
4248 skip(')');
4250 break;
4251 case '*':
4252 next();
4253 unary();
4254 indir();
4255 break;
4256 case '&':
4257 next();
4258 unary();
4259 /* functions names must be treated as function pointers,
4260 except for unary '&' and sizeof. Since we consider that
4261 functions are not lvalues, we only have to handle it
4262 there and in function calls. */
4263 /* arrays can also be used although they are not lvalues */
4264 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
4265 !(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
4266 test_lvalue();
4267 mk_pointer(&vtop->type);
4268 gaddrof();
4269 break;
4270 case '!':
4271 next();
4272 unary();
4273 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4274 CType boolean;
4275 boolean.t = VT_BOOL;
4276 gen_cast(&boolean);
4277 vtop->c.i = !vtop->c.i;
4278 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
4279 vtop->c.i ^= 1;
4280 else {
4281 save_regs(1);
4282 vseti(VT_JMP, gvtst(1, 0));
4284 break;
4285 case '~':
4286 next();
4287 unary();
4288 vpushi(-1);
4289 gen_op('^');
4290 break;
4291 case '+':
4292 next();
4293 unary();
4294 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
4295 tcc_error("pointer not accepted for unary plus");
4296 /* In order to force cast, we add zero, except for floating point
4297 where we really need an noop (otherwise -0.0 will be transformed
4298 into +0.0). */
4299 if (!is_float(vtop->type.t)) {
4300 vpushi(0);
4301 gen_op('+');
4303 break;
4304 case TOK_SIZEOF:
4305 case TOK_ALIGNOF1:
4306 case TOK_ALIGNOF2:
4307 t = tok;
4308 next();
4309 in_sizeof++;
4310 unary_type(&type); // Perform a in_sizeof = 0;
4311 size = type_size(&type, &align);
4312 if (t == TOK_SIZEOF) {
4313 if (!(type.t & VT_VLA)) {
4314 if (size < 0)
4315 tcc_error("sizeof applied to an incomplete type");
4316 vpushs(size);
4317 } else {
4318 vla_runtime_type_size(&type, &align);
4320 } else {
4321 vpushs(align);
4323 vtop->type.t |= VT_UNSIGNED;
4324 break;
4326 case TOK_builtin_expect:
4328 /* __builtin_expect is a no-op for now */
4329 int saved_nocode_wanted;
4330 next();
4331 skip('(');
4332 expr_eq();
4333 skip(',');
4334 saved_nocode_wanted = nocode_wanted;
4335 nocode_wanted = 1;
4336 expr_lor_const();
4337 vpop();
4338 nocode_wanted = saved_nocode_wanted;
4339 skip(')');
4341 break;
4342 case TOK_builtin_types_compatible_p:
4344 CType type1, type2;
4345 next();
4346 skip('(');
4347 parse_type(&type1);
4348 skip(',');
4349 parse_type(&type2);
4350 skip(')');
4351 type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
4352 type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
4353 vpushi(is_compatible_types(&type1, &type2));
4355 break;
4356 case TOK_builtin_choose_expr:
4358 int saved_nocode_wanted, c;
4359 next();
4360 skip('(');
4361 c = expr_const();
4362 skip(',');
4363 if (!c) {
4364 saved_nocode_wanted = nocode_wanted;
4365 nocode_wanted = 1;
4367 expr_eq();
4368 if (!c) {
4369 vpop();
4370 nocode_wanted = saved_nocode_wanted;
4372 skip(',');
4373 if (c) {
4374 saved_nocode_wanted = nocode_wanted;
4375 nocode_wanted = 1;
4377 expr_eq();
4378 if (c) {
4379 vpop();
4380 nocode_wanted = saved_nocode_wanted;
4382 skip(')');
4384 break;
4385 case TOK_builtin_constant_p:
4387 int saved_nocode_wanted, res;
4388 next();
4389 skip('(');
4390 saved_nocode_wanted = nocode_wanted;
4391 nocode_wanted = 1;
4392 gexpr();
4393 res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
4394 vpop();
4395 nocode_wanted = saved_nocode_wanted;
4396 skip(')');
4397 vpushi(res);
4399 break;
4400 case TOK_builtin_frame_address:
4401 case TOK_builtin_return_address:
4403 int tok1 = tok;
4404 int level;
4405 CType type;
4406 next();
4407 skip('(');
4408 if (tok != TOK_CINT) {
4409 tcc_error("%s only takes positive integers",
4410 tok1 == TOK_builtin_return_address ?
4411 "__builtin_return_address" :
4412 "__builtin_frame_address");
4414 level = (uint32_t)tokc.i;
4415 next();
4416 skip(')');
4417 type.t = VT_VOID;
4418 mk_pointer(&type);
4419 vset(&type, VT_LOCAL, 0); /* local frame */
4420 while (level--) {
4421 mk_pointer(&vtop->type);
4422 indir(); /* -> parent frame */
4424 if (tok1 == TOK_builtin_return_address) {
4425 // assume return address is just above frame pointer on stack
4426 vpushi(PTR_SIZE);
4427 gen_op('+');
4428 mk_pointer(&vtop->type);
4429 indir();
4432 break;
4433 #ifdef TCC_TARGET_X86_64
4434 #ifdef TCC_TARGET_PE
4435 case TOK_builtin_va_start:
4437 next();
4438 skip('(');
4439 expr_eq();
4440 skip(',');
4441 expr_eq();
4442 skip(')');
4443 if ((vtop->r & VT_VALMASK) != VT_LOCAL)
4444 tcc_error("__builtin_va_start expects a local variable");
4445 vtop->r &= ~(VT_LVAL | VT_REF);
4446 vtop->type = char_pointer_type;
4447 vtop->c.i += 8;
4448 vstore();
4450 break;
4451 #else
4452 case TOK_builtin_va_arg_types:
4454 CType type;
4455 next();
4456 skip('(');
4457 parse_type(&type);
4458 skip(')');
4459 vpushi(classify_x86_64_va_arg(&type));
4461 break;
4462 #endif
4463 #endif
4465 #ifdef TCC_TARGET_ARM64
4466 case TOK___va_start: {
4467 if (nocode_wanted)
4468 tcc_error("statement in global scope");
4469 next();
4470 skip('(');
4471 expr_eq();
4472 skip(',');
4473 expr_eq();
4474 skip(')');
4475 //xx check types
4476 gen_va_start();
4477 vpushi(0);
4478 vtop->type.t = VT_VOID;
4479 break;
4481 case TOK___va_arg: {
4482 CType type;
4483 if (nocode_wanted)
4484 tcc_error("statement in global scope");
4485 next();
4486 skip('(');
4487 expr_eq();
4488 skip(',');
4489 parse_type(&type);
4490 skip(')');
4491 //xx check types
4492 gen_va_arg(&type);
4493 vtop->type = type;
4494 break;
4496 case TOK___arm64_clear_cache: {
4497 next();
4498 skip('(');
4499 expr_eq();
4500 skip(',');
4501 expr_eq();
4502 skip(')');
4503 gen_clear_cache();
4504 vpushi(0);
4505 vtop->type.t = VT_VOID;
4506 break;
4508 #endif
4509 /* pre operations */
4510 case TOK_INC:
4511 case TOK_DEC:
4512 t = tok;
4513 next();
4514 unary();
4515 inc(0, t);
4516 break;
4517 case '-':
4518 next();
4519 unary();
4520 t = vtop->type.t & VT_BTYPE;
4521 if (is_float(t)) {
4522 /* In IEEE negate(x) isn't subtract(0,x), but rather
4523 subtract(-0, x). */
4524 vpush(&vtop->type);
4525 if (t == VT_FLOAT)
4526 vtop->c.f = -0.0f;
4527 else if (t == VT_DOUBLE)
4528 vtop->c.d = -0.0;
4529 else
4530 vtop->c.ld = -0.0;
4531 } else
4532 vpushi(0);
4533 vswap();
4534 gen_op('-');
4535 break;
4536 case TOK_LAND:
4537 if (!gnu_ext)
4538 goto tok_identifier;
4539 next();
4540 /* allow to take the address of a label */
4541 if (tok < TOK_UIDENT)
4542 expect("label identifier");
4543 s = label_find(tok);
4544 if (!s) {
4545 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
4546 } else {
4547 if (s->r == LABEL_DECLARED)
4548 s->r = LABEL_FORWARD;
4550 if (!s->type.t) {
4551 s->type.t = VT_VOID;
4552 mk_pointer(&s->type);
4553 s->type.t |= VT_STATIC;
4555 vpushsym(&s->type, s);
4556 next();
4557 break;
4559 // special qnan , snan and infinity values
4560 case TOK___NAN__:
4561 vpush64(VT_DOUBLE, 0x7ff8000000000000ULL);
4562 next();
4563 break;
4564 case TOK___SNAN__:
4565 vpush64(VT_DOUBLE, 0x7ff0000000000001ULL);
4566 next();
4567 break;
4568 case TOK___INF__:
4569 vpush64(VT_DOUBLE, 0x7ff0000000000000ULL);
4570 next();
4571 break;
4573 default:
4574 tok_identifier:
4575 t = tok;
4576 next();
4577 if (t < TOK_UIDENT)
4578 expect("identifier");
4579 s = sym_find(t);
4580 if (!s) {
4581 const char *name = get_tok_str(t, NULL);
4582 if (tok != '(')
4583 tcc_error("'%s' undeclared", name);
4584 /* for simple function calls, we tolerate undeclared
4585 external reference to int() function */
4586 if (tcc_state->warn_implicit_function_declaration
4587 #ifdef TCC_TARGET_PE
4588 /* people must be warned about using undeclared WINAPI functions
4589 (which usually start with uppercase letter) */
4590 || (name[0] >= 'A' && name[0] <= 'Z')
4591 #endif
4593 tcc_warning("implicit declaration of function '%s'", name);
4594 s = external_global_sym(t, &func_old_type, 0);
4596 if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
4597 (VT_STATIC | VT_INLINE | VT_FUNC)) {
4598 /* if referencing an inline function, then we generate a
4599 symbol to it if not already done. It will have the
4600 effect to generate code for it at the end of the
4601 compilation unit. Inline function as always
4602 generated in the text section. */
4603 if (!s->c && !nocode_wanted)
4604 put_extern_sym(s, text_section, 0, 0);
4605 r = VT_SYM | VT_CONST;
4606 } else {
4607 r = s->r;
4608 /* A symbol that has a register is a local register variable,
4609 which starts out as VT_LOCAL value. */
4610 if ((r & VT_VALMASK) < VT_CONST)
4611 r = (r & ~VT_VALMASK) | VT_LOCAL;
4613 vset(&s->type, r, s->c);
4614 /* Point to s as backpointer (even without r&VT_SYM).
4615 Will be used by at least the x86 inline asm parser for
4616 regvars. */
4617 vtop->sym = s;
4618 if (vtop->r & VT_SYM) {
4619 vtop->c.i = 0;
4621 break;
4624 /* post operations */
4625 while (1) {
4626 if (tok == TOK_INC || tok == TOK_DEC) {
4627 inc(1, tok);
4628 next();
4629 } else if (tok == '.' || tok == TOK_ARROW || tok == TOK_CDOUBLE) {
4630 int qualifiers;
4631 /* field */
4632 if (tok == TOK_ARROW)
4633 indir();
4634 qualifiers = vtop->type.t & (VT_CONSTANT | VT_VOLATILE);
4635 test_lvalue();
4636 gaddrof();
4637 /* expect pointer on structure */
4638 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
4639 expect("struct or union");
4640 if (tok == TOK_CDOUBLE)
4641 expect("field name");
4642 next();
4643 if (tok == TOK_CINT || tok == TOK_CUINT)
4644 expect("field name");
4645 s = find_field(&vtop->type, tok);
4646 if (!s)
4647 tcc_error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, &tokc));
4648 /* add field offset to pointer */
4649 vtop->type = char_pointer_type; /* change type to 'char *' */
4650 vpushi(s->c);
4651 gen_op('+');
4652 /* change type to field type, and set to lvalue */
4653 vtop->type = s->type;
4654 vtop->type.t |= qualifiers;
4655 /* an array is never an lvalue */
4656 if (!(vtop->type.t & VT_ARRAY)) {
4657 vtop->r |= lvalue_type(vtop->type.t);
4658 #ifdef CONFIG_TCC_BCHECK
4659 /* if bound checking, the referenced pointer must be checked */
4660 if (tcc_state->do_bounds_check && (vtop->r & VT_VALMASK) != VT_LOCAL)
4661 vtop->r |= VT_MUSTBOUND;
4662 #endif
4664 next();
4665 } else if (tok == '[') {
4666 next();
4667 gexpr();
4668 gen_op('+');
4669 indir();
4670 skip(']');
4671 } else if (tok == '(') {
4672 SValue ret;
4673 Sym *sa;
4674 int nb_args, ret_nregs, ret_align, regsize, variadic;
4676 /* function call */
4677 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
4678 /* pointer test (no array accepted) */
4679 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
4680 vtop->type = *pointed_type(&vtop->type);
4681 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
4682 goto error_func;
4683 } else {
4684 error_func:
4685 expect("function pointer");
4687 } else {
4688 vtop->r &= ~VT_LVAL; /* no lvalue */
4690 /* get return type */
4691 s = vtop->type.ref;
4692 next();
4693 sa = s->next; /* first parameter */
4694 nb_args = 0;
4695 ret.r2 = VT_CONST;
4696 /* compute first implicit argument if a structure is returned */
4697 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
4698 variadic = (s->c == FUNC_ELLIPSIS);
4699 ret_nregs = gfunc_sret(&s->type, variadic, &ret.type,
4700 &ret_align, &regsize);
4701 if (!ret_nregs) {
4702 /* get some space for the returned structure */
4703 size = type_size(&s->type, &align);
4704 #ifdef TCC_TARGET_ARM64
4705 /* On arm64, a small struct is return in registers.
4706 It is much easier to write it to memory if we know
4707 that we are allowed to write some extra bytes, so
4708 round the allocated space up to a power of 2: */
4709 if (size < 16)
4710 while (size & (size - 1))
4711 size = (size | (size - 1)) + 1;
4712 #endif
4713 loc = (loc - size) & -align;
4714 ret.type = s->type;
4715 ret.r = VT_LOCAL | VT_LVAL;
4716 /* pass it as 'int' to avoid structure arg passing
4717 problems */
4718 vseti(VT_LOCAL, loc);
4719 ret.c = vtop->c;
4720 nb_args++;
4722 } else {
4723 ret_nregs = 1;
4724 ret.type = s->type;
4727 if (ret_nregs) {
4728 /* return in register */
4729 if (is_float(ret.type.t)) {
4730 ret.r = reg_fret(ret.type.t);
4731 #ifdef TCC_TARGET_X86_64
4732 if ((ret.type.t & VT_BTYPE) == VT_QFLOAT)
4733 ret.r2 = REG_QRET;
4734 #endif
4735 } else {
4736 #ifndef TCC_TARGET_ARM64
4737 #ifdef TCC_TARGET_X86_64
4738 if ((ret.type.t & VT_BTYPE) == VT_QLONG)
4739 #else
4740 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
4741 #endif
4742 ret.r2 = REG_LRET;
4743 #endif
4744 ret.r = REG_IRET;
4746 ret.c.i = 0;
4748 if (tok != ')') {
4749 for(;;) {
4750 expr_eq();
4751 gfunc_param_typed(s, sa);
4752 nb_args++;
4753 if (sa)
4754 sa = sa->next;
4755 if (tok == ')')
4756 break;
4757 skip(',');
4760 if (sa)
4761 tcc_error("too few arguments to function");
4762 skip(')');
4763 if (!nocode_wanted) {
4764 gfunc_call(nb_args);
4765 } else {
4766 vtop -= (nb_args + 1);
4769 /* return value */
4770 for (r = ret.r + ret_nregs + !ret_nregs; r-- > ret.r;) {
4771 vsetc(&ret.type, r, &ret.c);
4772 vtop->r2 = ret.r2; /* Loop only happens when r2 is VT_CONST */
4775 /* handle packed struct return */
4776 if (((s->type.t & VT_BTYPE) == VT_STRUCT) && ret_nregs) {
4777 int addr, offset;
4779 size = type_size(&s->type, &align);
4780 /* We're writing whole regs often, make sure there's enough
4781 space. Assume register size is power of 2. */
4782 if (regsize > align)
4783 align = regsize;
4784 loc = (loc - size) & -align;
4785 addr = loc;
4786 offset = 0;
4787 for (;;) {
4788 vset(&ret.type, VT_LOCAL | VT_LVAL, addr + offset);
4789 vswap();
4790 vstore();
4791 vtop--;
4792 if (--ret_nregs == 0)
4793 break;
4794 offset += regsize;
4796 vset(&s->type, VT_LOCAL | VT_LVAL, addr);
4798 } else {
4799 break;
4804 ST_FUNC void expr_prod(void)
4806 int t;
4808 unary();
4809 while (tok == '*' || tok == '/' || tok == '%') {
4810 t = tok;
4811 next();
4812 unary();
4813 gen_op(t);
4817 ST_FUNC void expr_sum(void)
4819 int t;
4821 expr_prod();
4822 while (tok == '+' || tok == '-') {
4823 t = tok;
4824 next();
4825 expr_prod();
4826 gen_op(t);
4830 static void expr_shift(void)
4832 int t;
4834 expr_sum();
4835 while (tok == TOK_SHL || tok == TOK_SAR) {
4836 t = tok;
4837 next();
4838 expr_sum();
4839 gen_op(t);
4843 static void expr_cmp(void)
4845 int t;
4847 expr_shift();
4848 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
4849 tok == TOK_ULT || tok == TOK_UGE) {
4850 t = tok;
4851 next();
4852 expr_shift();
4853 gen_op(t);
4857 static void expr_cmpeq(void)
4859 int t;
4861 expr_cmp();
4862 while (tok == TOK_EQ || tok == TOK_NE) {
4863 t = tok;
4864 next();
4865 expr_cmp();
4866 gen_op(t);
4870 static void expr_and(void)
4872 expr_cmpeq();
4873 while (tok == '&') {
4874 next();
4875 expr_cmpeq();
4876 gen_op('&');
4880 static void expr_xor(void)
4882 expr_and();
4883 while (tok == '^') {
4884 next();
4885 expr_and();
4886 gen_op('^');
4890 static void expr_or(void)
4892 expr_xor();
4893 while (tok == '|') {
4894 next();
4895 expr_xor();
4896 gen_op('|');
4900 /* XXX: fix this mess */
4901 static void expr_land_const(void)
4903 expr_or();
4904 while (tok == TOK_LAND) {
4905 next();
4906 expr_or();
4907 gen_op(TOK_LAND);
4910 static void expr_lor_const(void)
4912 expr_land_const();
4913 while (tok == TOK_LOR) {
4914 next();
4915 expr_land_const();
4916 gen_op(TOK_LOR);
4920 static void expr_land(void)
4922 expr_or();
4923 if (tok == TOK_LAND) {
4924 int t = 0;
4925 for(;;) {
4926 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4927 CType ctb;
4928 ctb.t = VT_BOOL;
4929 gen_cast(&ctb);
4930 if (vtop->c.i) {
4931 vpop();
4932 } else {
4933 int saved_nocode_wanted = nocode_wanted;
4934 nocode_wanted = 1;
4935 while (tok == TOK_LAND) {
4936 next();
4937 expr_or();
4938 vpop();
4940 if (t)
4941 gsym(t);
4942 nocode_wanted = saved_nocode_wanted;
4943 gen_cast(&int_type);
4944 break;
4946 } else {
4947 if (!t)
4948 save_regs(1);
4949 t = gvtst(1, t);
4951 if (tok != TOK_LAND) {
4952 if (t)
4953 vseti(VT_JMPI, t);
4954 else
4955 vpushi(1);
4956 break;
4958 next();
4959 expr_or();
4964 static void expr_lor(void)
4966 expr_land();
4967 if (tok == TOK_LOR) {
4968 int t = 0;
4969 for(;;) {
4970 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4971 CType ctb;
4972 ctb.t = VT_BOOL;
4973 gen_cast(&ctb);
4974 if (!vtop->c.i) {
4975 vpop();
4976 } else {
4977 int saved_nocode_wanted = nocode_wanted;
4978 nocode_wanted = 1;
4979 while (tok == TOK_LOR) {
4980 next();
4981 expr_land();
4982 vpop();
4984 if (t)
4985 gsym(t);
4986 nocode_wanted = saved_nocode_wanted;
4987 gen_cast(&int_type);
4988 break;
4990 } else {
4991 if (!t)
4992 save_regs(1);
4993 t = gvtst(0, t);
4995 if (tok != TOK_LOR) {
4996 if (t)
4997 vseti(VT_JMP, t);
4998 else
4999 vpushi(0);
5000 break;
5002 next();
5003 expr_land();
5008 /* Assuming vtop is a value used in a conditional context
5009 (i.e. compared with zero) return 0 if it's false, 1 if
5010 true and -1 if it can't be statically determined. */
5011 static int condition_3way(void)
5013 int c = -1;
5014 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST &&
5015 (!(vtop->r & VT_SYM) ||
5016 !(vtop->sym->type.t & VT_WEAK))) {
5017 CType boolean;
5018 boolean.t = VT_BOOL;
5019 vdup();
5020 gen_cast(&boolean);
5021 c = vtop->c.i;
5022 vpop();
5024 return c;
5027 static void expr_cond(void)
5029 int tt, u, r1, r2, rc, t1, t2, bt1, bt2, islv;
5030 int c;
5031 SValue sv;
5032 CType type, type1, type2;
5034 expr_lor();
5035 if (tok == '?') {
5036 next();
5037 c = condition_3way();
5038 if (c >= 0) {
5039 int saved_nocode_wanted = nocode_wanted;
5040 if (c) {
5041 if (tok != ':' || !gnu_ext) {
5042 vpop();
5043 gexpr();
5045 skip(':');
5046 nocode_wanted = 1;
5047 expr_cond();
5048 vpop();
5049 nocode_wanted = saved_nocode_wanted;
5050 } else {
5051 vpop();
5052 if (tok != ':' || !gnu_ext) {
5053 nocode_wanted = 1;
5054 gexpr();
5055 vpop();
5056 nocode_wanted = saved_nocode_wanted;
5058 skip(':');
5059 expr_cond();
5062 else {
5063 /* XXX This doesn't handle nocode_wanted correctly at all.
5064 It unconditionally calls gv/gvtst and friends. That's
5065 the case for many of the expr_ routines. Currently
5066 that should generate only useless code, but depending
5067 on other operand handling this might also generate
5068 pointer derefs for lvalue conversions whose result
5069 is useless, but nevertheless can lead to segfault.
5071 Somewhen we need to overhaul the whole nocode_wanted
5072 handling. */
5073 if (vtop != vstack) {
5074 /* needed to avoid having different registers saved in
5075 each branch */
5076 if (is_float(vtop->type.t)) {
5077 rc = RC_FLOAT;
5078 #ifdef TCC_TARGET_X86_64
5079 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
5080 rc = RC_ST0;
5082 #endif
5084 else
5085 rc = RC_INT;
5086 gv(rc);
5087 save_regs(1);
5089 if (tok == ':' && gnu_ext) {
5090 gv_dup();
5091 tt = gvtst(1, 0);
5092 } else {
5093 tt = gvtst(1, 0);
5094 gexpr();
5096 type1 = vtop->type;
5097 sv = *vtop; /* save value to handle it later */
5098 vtop--; /* no vpop so that FP stack is not flushed */
5099 skip(':');
5100 u = gjmp(0);
5101 gsym(tt);
5102 expr_cond();
5103 type2 = vtop->type;
5105 t1 = type1.t;
5106 bt1 = t1 & VT_BTYPE;
5107 t2 = type2.t;
5108 bt2 = t2 & VT_BTYPE;
5109 /* cast operands to correct type according to ISOC rules */
5110 if (is_float(bt1) || is_float(bt2)) {
5111 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
5112 type.t = VT_LDOUBLE;
5113 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
5114 type.t = VT_DOUBLE;
5115 } else {
5116 type.t = VT_FLOAT;
5118 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
5119 /* cast to biggest op */
5120 type.t = VT_LLONG;
5121 /* convert to unsigned if it does not fit in a long long */
5122 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
5123 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
5124 type.t |= VT_UNSIGNED;
5125 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
5126 /* If one is a null ptr constant the result type
5127 is the other. */
5128 if (is_null_pointer (vtop))
5129 type = type1;
5130 else if (is_null_pointer (&sv))
5131 type = type2;
5132 /* XXX: test pointer compatibility, C99 has more elaborate
5133 rules here. */
5134 else
5135 type = type1;
5136 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
5137 /* XXX: test function pointer compatibility */
5138 type = bt1 == VT_FUNC ? type1 : type2;
5139 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
5140 /* XXX: test structure compatibility */
5141 type = bt1 == VT_STRUCT ? type1 : type2;
5142 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
5143 /* NOTE: as an extension, we accept void on only one side */
5144 type.t = VT_VOID;
5145 } else {
5146 /* integer operations */
5147 type.t = VT_INT;
5148 /* convert to unsigned if it does not fit in an integer */
5149 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
5150 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
5151 type.t |= VT_UNSIGNED;
5153 /* keep structs lvalue by transforming `(expr ? a : b)` to `*(expr ? &a : &b)` so
5154 that `(expr ? a : b).mem` does not error with "lvalue expected" */
5155 islv = (vtop->r & VT_LVAL) && (sv.r & VT_LVAL) && VT_STRUCT == (type.t & VT_BTYPE);
5157 /* now we convert second operand */
5158 gen_cast(&type);
5159 if (islv) {
5160 mk_pointer(&vtop->type);
5161 gaddrof();
5163 else if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
5164 gaddrof();
5165 rc = RC_INT;
5166 if (is_float(type.t)) {
5167 rc = RC_FLOAT;
5168 #ifdef TCC_TARGET_X86_64
5169 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
5170 rc = RC_ST0;
5172 #endif
5173 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
5174 /* for long longs, we use fixed registers to avoid having
5175 to handle a complicated move */
5176 rc = RC_IRET;
5179 r2 = gv(rc);
5180 /* this is horrible, but we must also convert first
5181 operand */
5182 tt = gjmp(0);
5183 gsym(u);
5184 /* put again first value and cast it */
5185 *vtop = sv;
5186 gen_cast(&type);
5187 if (islv) {
5188 mk_pointer(&vtop->type);
5189 gaddrof();
5191 else if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
5192 gaddrof();
5193 r1 = gv(rc);
5194 move_reg(r2, r1, type.t);
5195 vtop->r = r2;
5196 gsym(tt);
5197 if (islv)
5198 indir();
5203 static void expr_eq(void)
5205 int t;
5207 expr_cond();
5208 if (tok == '=' ||
5209 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
5210 tok == TOK_A_XOR || tok == TOK_A_OR ||
5211 tok == TOK_A_SHL || tok == TOK_A_SAR) {
5212 test_lvalue();
5213 t = tok;
5214 next();
5215 if (t == '=') {
5216 expr_eq();
5217 } else {
5218 vdup();
5219 expr_eq();
5220 gen_op(t & 0x7f);
5222 vstore();
5226 ST_FUNC void gexpr(void)
5228 while (1) {
5229 expr_eq();
5230 if (tok != ',')
5231 break;
5232 vpop();
5233 next();
5237 /* parse an expression and return its type without any side effect. */
5238 static void expr_type(CType *type)
5240 int saved_nocode_wanted;
5242 saved_nocode_wanted = nocode_wanted;
5243 nocode_wanted = 1;
5244 gexpr();
5245 *type = vtop->type;
5246 vpop();
5247 nocode_wanted = saved_nocode_wanted;
5250 /* parse a unary expression and return its type without any side
5251 effect. */
5252 static void unary_type(CType *type)
5254 int a;
5256 a = nocode_wanted;
5257 nocode_wanted = 1;
5258 unary();
5259 *type = vtop->type;
5260 vpop();
5261 nocode_wanted = a;
5264 /* parse a constant expression and return value in vtop. */
5265 static void expr_const1(void)
5267 int a;
5268 a = const_wanted;
5269 const_wanted = 1;
5270 expr_cond();
5271 const_wanted = a;
5274 /* parse an integer constant and return its value. */
5275 ST_FUNC int expr_const(void)
5277 int c;
5278 expr_const1();
5279 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
5280 expect("constant expression");
5281 c = vtop->c.i;
5282 vpop();
5283 return c;
5286 /* return the label token if current token is a label, otherwise
5287 return zero */
5288 static int is_label(void)
5290 int last_tok;
5292 /* fast test first */
5293 if (tok < TOK_UIDENT)
5294 return 0;
5295 /* no need to save tokc because tok is an identifier */
5296 last_tok = tok;
5297 next();
5298 if (tok == ':') {
5299 next();
5300 return last_tok;
5301 } else {
5302 unget_tok(last_tok);
5303 return 0;
5307 static void label_or_decl(int l)
5309 int last_tok;
5311 /* fast test first */
5312 if (tok >= TOK_UIDENT)
5314 /* no need to save tokc because tok is an identifier */
5315 last_tok = tok;
5316 next();
5317 if (tok == ':') {
5318 unget_tok(last_tok);
5319 return;
5321 unget_tok(last_tok);
5323 decl(l);
5326 static int case_cmp(const void *pa, const void *pb)
5328 int a = (*(struct case_t**) pa)->v1;
5329 int b = (*(struct case_t**) pb)->v1;
5330 return a < b ? -1 : a > b;
5333 static int gcase(struct case_t **base, int len, int case_reg, int *bsym)
5335 struct case_t *p;
5336 int e;
5337 while (len > 4) {
5338 /* binary search */
5339 p = base[len/2];
5340 vseti(case_reg, 0);
5341 vdup();
5342 vpushi(p->v2);
5343 gen_op(TOK_LE);
5344 e = gtst(1, 0);
5345 case_reg = gv(RC_INT);
5346 vpop();
5347 vseti(case_reg, 0);
5348 vdup();
5349 vpushi(p->v1);
5350 gen_op(TOK_GE);
5351 gtst_addr(0, p->sym); /* v1 <= x <= v2 */
5352 case_reg = gv(RC_INT);
5353 vpop();
5354 /* x < v1 */
5355 case_reg = gcase(base, len/2, case_reg, bsym);
5356 if (cur_switch->def_sym)
5357 gjmp_addr(cur_switch->def_sym);
5358 else
5359 *bsym = gjmp(*bsym);
5360 /* x > v2 */
5361 gsym(e);
5362 e = len/2 + 1;
5363 base += e; len -= e;
5365 /* linear scan */
5366 while (len--) {
5367 p = *base++;
5368 vseti(case_reg, 0);
5369 vdup();
5370 vpushi(p->v2);
5371 if (p->v1 == p->v2) {
5372 gen_op(TOK_EQ);
5373 gtst_addr(0, p->sym);
5374 } else {
5375 gen_op(TOK_LE);
5376 e = gtst(1, 0);
5377 case_reg = gv(RC_INT);
5378 vpop();
5379 vseti(case_reg, 0);
5380 vdup();
5381 vpushi(p->v1);
5382 gen_op(TOK_GE);
5383 gtst_addr(0, p->sym);
5384 gsym(e);
5386 case_reg = gv(RC_INT);
5387 vpop();
5389 return case_reg;
5392 static void block(int *bsym, int *csym, int is_expr)
5394 int a, b, c, d, cond;
5395 Sym *s;
5397 /* generate line number info */
5398 if (tcc_state->do_debug &&
5399 (last_line_num != file->line_num || last_ind != ind)) {
5400 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
5401 last_ind = ind;
5402 last_line_num = file->line_num;
5405 if (is_expr) {
5406 /* default return value is (void) */
5407 vpushi(0);
5408 vtop->type.t = VT_VOID;
5411 if (tok == TOK_IF) {
5412 /* if test */
5413 int saved_nocode_wanted = nocode_wanted;
5414 next();
5415 skip('(');
5416 gexpr();
5417 skip(')');
5418 cond = condition_3way();
5419 if (cond == 0)
5420 nocode_wanted |= 2;
5421 a = gvtst(1, 0);
5422 block(bsym, csym, 0);
5423 if (cond != 1)
5424 nocode_wanted = saved_nocode_wanted;
5425 c = tok;
5426 if (c == TOK_ELSE) {
5427 next();
5428 if (cond == 1)
5429 nocode_wanted |= 2;
5430 d = gjmp(0);
5431 gsym(a);
5432 block(bsym, csym, 0);
5433 gsym(d); /* patch else jmp */
5434 if (cond != 0)
5435 nocode_wanted = saved_nocode_wanted;
5436 } else
5437 gsym(a);
5438 } else if (tok == TOK_WHILE) {
5439 int saved_nocode_wanted;
5440 nocode_wanted &= ~2;
5441 next();
5442 d = ind;
5443 vla_sp_restore();
5444 skip('(');
5445 gexpr();
5446 skip(')');
5447 a = gvtst(1, 0);
5448 b = 0;
5449 ++local_scope;
5450 saved_nocode_wanted = nocode_wanted;
5451 block(&a, &b, 0);
5452 nocode_wanted = saved_nocode_wanted;
5453 --local_scope;
5454 if(!nocode_wanted)
5455 gjmp_addr(d);
5456 gsym(a);
5457 gsym_addr(b, d);
5458 } else if (tok == '{') {
5459 Sym *llabel;
5460 int block_vla_sp_loc = vla_sp_loc, saved_vlas_in_scope = vlas_in_scope;
5462 next();
5463 /* record local declaration stack position */
5464 s = local_stack;
5465 llabel = local_label_stack;
5466 ++local_scope;
5468 /* handle local labels declarations */
5469 if (tok == TOK_LABEL) {
5470 next();
5471 for(;;) {
5472 if (tok < TOK_UIDENT)
5473 expect("label identifier");
5474 label_push(&local_label_stack, tok, LABEL_DECLARED);
5475 next();
5476 if (tok == ',') {
5477 next();
5478 } else {
5479 skip(';');
5480 break;
5484 while (tok != '}') {
5485 label_or_decl(VT_LOCAL);
5486 if (tok != '}') {
5487 if (is_expr)
5488 vpop();
5489 block(bsym, csym, is_expr);
5492 /* pop locally defined labels */
5493 label_pop(&local_label_stack, llabel);
5494 /* pop locally defined symbols */
5495 --local_scope;
5496 /* In the is_expr case (a statement expression is finished here),
5497 vtop might refer to symbols on the local_stack. Either via the
5498 type or via vtop->sym. We can't pop those nor any that in turn
5499 might be referred to. To make it easier we don't roll back
5500 any symbols in that case; some upper level call to block() will
5501 do that. We do have to remove such symbols from the lookup
5502 tables, though. sym_pop will do that. */
5503 sym_pop(&local_stack, s, is_expr);
5505 /* Pop VLA frames and restore stack pointer if required */
5506 if (vlas_in_scope > saved_vlas_in_scope) {
5507 vla_sp_loc = saved_vlas_in_scope ? block_vla_sp_loc : vla_sp_root_loc;
5508 vla_sp_restore();
5510 vlas_in_scope = saved_vlas_in_scope;
5512 next();
5513 } else if (tok == TOK_RETURN) {
5514 next();
5515 if (tok != ';') {
5516 gexpr();
5517 gen_assign_cast(&func_vt);
5518 #ifdef TCC_TARGET_ARM64
5519 // Perhaps it would be better to use this for all backends:
5520 greturn();
5521 #else
5522 if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
5523 CType type, ret_type;
5524 int ret_align, ret_nregs, regsize;
5525 ret_nregs = gfunc_sret(&func_vt, func_var, &ret_type,
5526 &ret_align, &regsize);
5527 if (0 == ret_nregs) {
5528 /* if returning structure, must copy it to implicit
5529 first pointer arg location */
5530 type = func_vt;
5531 mk_pointer(&type);
5532 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
5533 indir();
5534 vswap();
5535 /* copy structure value to pointer */
5536 vstore();
5537 } else {
5538 /* returning structure packed into registers */
5539 int r, size, addr, align;
5540 size = type_size(&func_vt,&align);
5541 if ((vtop->r != (VT_LOCAL | VT_LVAL) ||
5542 (vtop->c.i & (ret_align-1)))
5543 && (align & (ret_align-1))) {
5544 loc = (loc - size) & -ret_align;
5545 addr = loc;
5546 type = func_vt;
5547 vset(&type, VT_LOCAL | VT_LVAL, addr);
5548 vswap();
5549 vstore();
5550 vpop();
5551 vset(&ret_type, VT_LOCAL | VT_LVAL, addr);
5553 vtop->type = ret_type;
5554 if (is_float(ret_type.t))
5555 r = rc_fret(ret_type.t);
5556 else
5557 r = RC_IRET;
5559 if (ret_nregs == 1)
5560 gv(r);
5561 else {
5562 for (;;) {
5563 vdup();
5564 gv(r);
5565 vpop();
5566 if (--ret_nregs == 0)
5567 break;
5568 /* We assume that when a structure is returned in multiple
5569 registers, their classes are consecutive values of the
5570 suite s(n) = 2^n */
5571 r <<= 1;
5572 vtop->c.i += regsize;
5576 } else if (is_float(func_vt.t)) {
5577 gv(rc_fret(func_vt.t));
5578 } else {
5579 gv(RC_IRET);
5581 #endif
5582 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
5584 skip(';');
5585 /* jump unless last stmt in top-level block */
5586 if (tok != '}' || local_scope != 1)
5587 rsym = gjmp(rsym);
5588 nocode_wanted |= 2;
5589 } else if (tok == TOK_BREAK) {
5590 /* compute jump */
5591 if (!bsym)
5592 tcc_error("cannot break");
5593 *bsym = gjmp(*bsym);
5594 next();
5595 skip(';');
5596 nocode_wanted |= 2;
5597 } else if (tok == TOK_CONTINUE) {
5598 /* compute jump */
5599 if (!csym)
5600 tcc_error("cannot continue");
5601 vla_sp_restore_root();
5602 *csym = gjmp(*csym);
5603 next();
5604 skip(';');
5605 } else if (tok == TOK_FOR) {
5606 int e;
5607 int saved_nocode_wanted;
5608 nocode_wanted &= ~2;
5609 next();
5610 skip('(');
5611 s = local_stack;
5612 ++local_scope;
5613 if (tok != ';') {
5614 /* c99 for-loop init decl? */
5615 if (!decl0(VT_LOCAL, 1)) {
5616 /* no, regular for-loop init expr */
5617 gexpr();
5618 vpop();
5621 skip(';');
5622 d = ind;
5623 c = ind;
5624 vla_sp_restore();
5625 a = 0;
5626 b = 0;
5627 if (tok != ';') {
5628 gexpr();
5629 a = gvtst(1, 0);
5631 skip(';');
5632 if (tok != ')') {
5633 e = gjmp(0);
5634 c = ind;
5635 vla_sp_restore();
5636 gexpr();
5637 vpop();
5638 gjmp_addr(d);
5639 gsym(e);
5641 skip(')');
5642 saved_nocode_wanted = nocode_wanted;
5643 block(&a, &b, 0);
5644 nocode_wanted = saved_nocode_wanted;
5645 if(!nocode_wanted)
5646 gjmp_addr(c);
5647 gsym(a);
5648 gsym_addr(b, c);
5649 --local_scope;
5650 sym_pop(&local_stack, s, 0);
5652 } else
5653 if (tok == TOK_DO) {
5654 int saved_nocode_wanted;
5655 nocode_wanted &= ~2;
5656 next();
5657 a = 0;
5658 b = 0;
5659 d = ind;
5660 vla_sp_restore();
5661 saved_nocode_wanted = nocode_wanted;
5662 block(&a, &b, 0);
5663 nocode_wanted = saved_nocode_wanted;
5664 skip(TOK_WHILE);
5665 skip('(');
5666 gsym(b);
5667 gexpr();
5668 c = gvtst(0, 0);
5669 if (!nocode_wanted)
5670 gsym_addr(c, d);
5671 skip(')');
5672 gsym(a);
5673 skip(';');
5674 } else
5675 if (tok == TOK_SWITCH) {
5676 struct switch_t *saved, sw;
5677 int saved_nocode_wanted = nocode_wanted;
5678 next();
5679 skip('(');
5680 gexpr();
5681 /* XXX: other types than integer */
5682 c = gv(RC_INT);
5683 vpop();
5684 skip(')');
5685 a = 0;
5686 b = gjmp(0); /* jump to first case */
5687 sw.p = NULL; sw.n = 0; sw.def_sym = 0;
5688 saved = cur_switch;
5689 cur_switch = &sw;
5690 block(&a, csym, 0);
5691 nocode_wanted = saved_nocode_wanted;
5692 a = gjmp(a); /* add implicit break */
5693 /* case lookup */
5694 gsym(b);
5695 if (!nocode_wanted) {
5696 qsort(sw.p, sw.n, sizeof(void*), case_cmp);
5697 for (b = 1; b < sw.n; b++)
5698 if (sw.p[b - 1]->v2 >= sw.p[b]->v1)
5699 tcc_error("duplicate case value");
5700 gcase(sw.p, sw.n, c, &a);
5701 if (sw.def_sym)
5702 gjmp_addr(sw.def_sym);
5704 dynarray_reset(&sw.p, &sw.n);
5705 cur_switch = saved;
5706 /* break label */
5707 gsym(a);
5708 } else
5709 if (tok == TOK_CASE) {
5710 struct case_t *cr = tcc_malloc(sizeof(struct case_t));
5711 if (!cur_switch)
5712 expect("switch");
5713 nocode_wanted &= ~2;
5714 next();
5715 cr->v1 = cr->v2 = expr_const();
5716 if (gnu_ext && tok == TOK_DOTS) {
5717 next();
5718 cr->v2 = expr_const();
5719 if (cr->v2 < cr->v1)
5720 tcc_warning("empty case range");
5722 cr->sym = ind;
5723 dynarray_add((void***) &cur_switch->p, &cur_switch->n, cr);
5724 skip(':');
5725 is_expr = 0;
5726 goto block_after_label;
5727 } else
5728 if (tok == TOK_DEFAULT) {
5729 next();
5730 skip(':');
5731 if (!cur_switch)
5732 expect("switch");
5733 if (cur_switch->def_sym)
5734 tcc_error("too many 'default'");
5735 cur_switch->def_sym = ind;
5736 is_expr = 0;
5737 goto block_after_label;
5738 } else
5739 if (tok == TOK_GOTO) {
5740 next();
5741 if (tok == '*' && gnu_ext) {
5742 /* computed goto */
5743 next();
5744 gexpr();
5745 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
5746 expect("pointer");
5747 if (!nocode_wanted)
5748 ggoto();
5749 else
5750 vtop--;
5751 } else if (tok >= TOK_UIDENT) {
5752 s = label_find(tok);
5753 /* put forward definition if needed */
5754 if (!s) {
5755 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
5756 } else {
5757 if (s->r == LABEL_DECLARED)
5758 s->r = LABEL_FORWARD;
5760 vla_sp_restore_root();
5761 if (nocode_wanted)
5763 else if (s->r & LABEL_FORWARD)
5764 s->jnext = gjmp(s->jnext);
5765 else
5766 gjmp_addr(s->jnext);
5767 next();
5768 } else {
5769 expect("label identifier");
5771 skip(';');
5772 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
5773 asm_instr();
5774 } else {
5775 b = is_label();
5776 if (b) {
5777 /* label case */
5778 s = label_find(b);
5779 if (s) {
5780 if (s->r == LABEL_DEFINED)
5781 tcc_error("duplicate label '%s'", get_tok_str(s->v, NULL));
5782 gsym(s->jnext);
5783 s->r = LABEL_DEFINED;
5784 } else {
5785 s = label_push(&global_label_stack, b, LABEL_DEFINED);
5787 s->jnext = ind;
5788 vla_sp_restore();
5789 /* we accept this, but it is a mistake */
5790 block_after_label:
5791 nocode_wanted &= ~2;
5792 if (tok == '}') {
5793 tcc_warning("deprecated use of label at end of compound statement");
5794 } else {
5795 if (is_expr)
5796 vpop();
5797 block(bsym, csym, is_expr);
5799 } else {
5800 /* expression case */
5801 if (tok != ';') {
5802 if (is_expr) {
5803 vpop();
5804 gexpr();
5805 } else {
5806 gexpr();
5807 vpop();
5810 skip(';');
5815 #define EXPR_CONST 1
5816 #define EXPR_ANY 2
5818 static void parse_init_elem(int expr_type)
5820 int saved_global_expr;
5821 switch(expr_type) {
5822 case EXPR_CONST:
5823 /* compound literals must be allocated globally in this case */
5824 saved_global_expr = global_expr;
5825 global_expr = 1;
5826 expr_const1();
5827 global_expr = saved_global_expr;
5828 /* NOTE: symbols are accepted */
5829 if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
5830 tcc_error("initializer element is not constant");
5831 break;
5832 case EXPR_ANY:
5833 expr_eq();
5834 break;
5838 /* t is the array or struct type. c is the array or struct
5839 address. cur_field is the pointer to the current
5840 value, for arrays the 'c' member contains the current start
5841 index and the 'r' contains the end index (in case of range init).
5842 'size_only' is true if only size info is needed (only used
5843 in arrays) */
5844 static void decl_designator(CType *type, Section *sec, unsigned long c,
5845 Sym **cur_field, int size_only)
5847 Sym *s, *f;
5848 int notfirst, index, index_last, align, l, nb_elems, elem_size;
5849 CType type1;
5851 notfirst = 0;
5852 elem_size = 0;
5853 nb_elems = 1;
5854 if (gnu_ext && (l = is_label()) != 0)
5855 goto struct_field;
5856 while (tok == '[' || tok == '.') {
5857 if (tok == '[') {
5858 if (!(type->t & VT_ARRAY))
5859 expect("array type");
5860 s = type->ref;
5861 next();
5862 index = expr_const();
5863 if (index < 0 || (s->c >= 0 && index >= s->c))
5864 tcc_error("invalid index");
5865 if (tok == TOK_DOTS && gnu_ext) {
5866 next();
5867 index_last = expr_const();
5868 if (index_last < 0 ||
5869 (s->c >= 0 && index_last >= s->c) ||
5870 index_last < index)
5871 tcc_error("invalid index");
5872 } else {
5873 index_last = index;
5875 skip(']');
5876 if (!notfirst) {
5877 (*cur_field)->c = index;
5878 (*cur_field)->r = index_last;
5880 type = pointed_type(type);
5881 elem_size = type_size(type, &align);
5882 c += index * elem_size;
5883 /* NOTE: we only support ranges for last designator */
5884 nb_elems = index_last - index + 1;
5885 if (nb_elems != 1) {
5886 notfirst = 1;
5887 break;
5889 } else {
5890 next();
5891 l = tok;
5892 next();
5893 struct_field:
5894 if ((type->t & VT_BTYPE) != VT_STRUCT)
5895 expect("struct/union type");
5896 f = find_field(type, l);
5897 if (!f)
5898 expect("field");
5899 if (!notfirst)
5900 *cur_field = f;
5901 /* XXX: fix this mess by using explicit storage field */
5902 type1 = f->type;
5903 type1.t |= (type->t & ~VT_TYPE);
5904 type = &type1;
5905 c += f->c;
5907 notfirst = 1;
5909 if (notfirst) {
5910 if (tok == '=') {
5911 next();
5912 } else {
5913 if (!gnu_ext)
5914 expect("=");
5916 } else {
5917 if (type->t & VT_ARRAY) {
5918 index = (*cur_field)->c;
5919 if (type->ref->c >= 0 && index >= type->ref->c)
5920 tcc_error("index too large");
5921 type = pointed_type(type);
5922 c += index * type_size(type, &align);
5923 } else {
5924 f = *cur_field;
5925 if (!f)
5926 tcc_error("too many field init");
5927 /* XXX: fix this mess by using explicit storage field */
5928 type1 = f->type;
5929 type1.t |= (type->t & ~VT_TYPE);
5930 type = &type1;
5931 c += f->c;
5934 decl_initializer(type, sec, c, 0, size_only);
5936 /* XXX: make it more general */
5937 if (!size_only && nb_elems > 1) {
5938 unsigned long c_end;
5939 uint8_t *src, *dst;
5940 int i;
5942 if (!sec) {
5943 vset(type, VT_LOCAL|VT_LVAL, c);
5944 for (i = 1; i < nb_elems; i++) {
5945 vset(type, VT_LOCAL|VT_LVAL, c + elem_size * i);
5946 vswap();
5947 vstore();
5949 vpop();
5950 } else {
5951 c_end = c + nb_elems * elem_size;
5952 if (c_end > sec->data_allocated)
5953 section_realloc(sec, c_end);
5954 src = sec->data + c;
5955 dst = src;
5956 for(i = 1; i < nb_elems; i++) {
5957 dst += elem_size;
5958 memcpy(dst, src, elem_size);
5964 /* store a value or an expression directly in global data or in local array */
5965 static void init_putv(CType *type, Section *sec, unsigned long c)
5967 int bt, bit_pos, bit_size;
5968 void *ptr;
5969 unsigned long long bit_mask;
5970 CType dtype;
5972 dtype = *type;
5973 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
5975 if (sec) {
5976 int size, align;
5977 /* XXX: not portable */
5978 /* XXX: generate error if incorrect relocation */
5979 gen_assign_cast(&dtype);
5980 bt = type->t & VT_BTYPE;
5981 size = type_size(type, &align);
5982 if (c + size > sec->data_allocated) {
5983 section_realloc(sec, c + size);
5985 ptr = sec->data + c;
5986 /* XXX: make code faster ? */
5987 if (!(type->t & VT_BITFIELD)) {
5988 bit_pos = 0;
5989 bit_size = PTR_SIZE * 8;
5990 bit_mask = -1LL;
5991 } else {
5992 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5993 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
5994 bit_mask = (1LL << bit_size) - 1;
5996 if ((vtop->r & (VT_SYM|VT_CONST)) == (VT_SYM|VT_CONST) &&
5997 vtop->sym->v >= SYM_FIRST_ANOM &&
5998 /* XXX This rejects compount literals like
5999 '(void *){ptr}'. The problem is that '&sym' is
6000 represented the same way, which would be ruled out
6001 by the SYM_FIRST_ANOM check above, but also '"string"'
6002 in 'char *p = "string"' is represented the same
6003 with the type being VT_PTR and the symbol being an
6004 anonymous one. That is, there's no difference in vtop
6005 between '(void *){x}' and '&(void *){x}'. Ignore
6006 pointer typed entities here. Hopefully no real code
6007 will every use compound literals with scalar type. */
6008 (vtop->type.t & VT_BTYPE) != VT_PTR) {
6009 /* These come from compound literals, memcpy stuff over. */
6010 Section *ssec;
6011 ElfW(Sym) *esym;
6012 ElfW_Rel *rel;
6013 esym = &((ElfW(Sym) *)symtab_section->data)[vtop->sym->c];
6014 ssec = tcc_state->sections[esym->st_shndx];
6015 memmove (ptr, ssec->data + esym->st_value, size);
6016 if (ssec->reloc) {
6017 /* We need to copy over all memory contents, and that
6018 includes relocations. Use the fact that relocs are
6019 created it order, so look from the end of relocs
6020 until we hit one before the copied region. */
6021 int num_relocs = ssec->reloc->data_offset / sizeof(*rel);
6022 rel = (ElfW_Rel*)(ssec->reloc->data + ssec->reloc->data_offset);
6023 while (num_relocs--) {
6024 rel--;
6025 if (rel->r_offset >= esym->st_value + size)
6026 continue;
6027 if (rel->r_offset < esym->st_value)
6028 break;
6029 /* Note: if the same fields are initialized multiple
6030 times (possible with designators) then we possibly
6031 add multiple relocations for the same offset here.
6032 That would lead to wrong code, the last reloc needs
6033 to win. We clean this up later after the whole
6034 initializer is parsed. */
6035 put_elf_reloca(symtab_section, sec,
6036 c + rel->r_offset - esym->st_value,
6037 ELFW(R_TYPE)(rel->r_info),
6038 ELFW(R_SYM)(rel->r_info),
6039 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
6040 rel->r_addend
6041 #else
6043 #endif
6047 } else {
6048 if ((vtop->r & VT_SYM) &&
6049 (bt == VT_BYTE ||
6050 bt == VT_SHORT ||
6051 bt == VT_DOUBLE ||
6052 bt == VT_LDOUBLE ||
6053 #if PTR_SIZE == 8
6054 (bt == VT_LLONG && bit_size != 64) ||
6055 bt == VT_INT
6056 #else
6057 bt == VT_LLONG ||
6058 (bt == VT_INT && bit_size != 32)
6059 #endif
6061 tcc_error("initializer element is not computable at load time");
6062 switch(bt) {
6063 /* XXX: when cross-compiling we assume that each type has the
6064 same representation on host and target, which is likely to
6065 be wrong in the case of long double */
6066 case VT_BOOL:
6067 vtop->c.i = (vtop->c.i != 0);
6068 case VT_BYTE:
6069 *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
6070 break;
6071 case VT_SHORT:
6072 *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
6073 break;
6074 case VT_DOUBLE:
6075 *(double *)ptr = vtop->c.d;
6076 break;
6077 case VT_LDOUBLE:
6078 if (sizeof(long double) == LDOUBLE_SIZE)
6079 *(long double *)ptr = vtop->c.ld;
6080 else if (sizeof(double) == LDOUBLE_SIZE)
6081 *(double *)ptr = vtop->c.ld;
6082 else
6083 tcc_error("can't cross compile long double constants");
6084 break;
6085 #if PTR_SIZE != 8
6086 case VT_LLONG:
6087 *(long long *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
6088 break;
6089 #else
6090 case VT_LLONG:
6091 #endif
6092 case VT_PTR:
6094 addr_t val = (vtop->c.i & bit_mask) << bit_pos;
6095 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
6096 if (vtop->r & VT_SYM)
6097 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
6098 else
6099 *(addr_t *)ptr |= val;
6100 #else
6101 if (vtop->r & VT_SYM)
6102 greloc(sec, vtop->sym, c, R_DATA_PTR);
6103 *(addr_t *)ptr |= val;
6104 #endif
6105 break;
6107 default:
6109 int val = (vtop->c.i & bit_mask) << bit_pos;
6110 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
6111 if (vtop->r & VT_SYM)
6112 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
6113 else
6114 *(int *)ptr |= val;
6115 #else
6116 if (vtop->r & VT_SYM)
6117 greloc(sec, vtop->sym, c, R_DATA_PTR);
6118 *(int *)ptr |= val;
6119 #endif
6120 break;
6124 vtop--;
6125 } else {
6126 vset(&dtype, VT_LOCAL|VT_LVAL, c);
6127 vswap();
6128 vstore();
6129 vpop();
6133 /* put zeros for variable based init */
6134 static void init_putz(Section *sec, unsigned long c, int size)
6136 if (sec) {
6137 /* nothing to do because globals are already set to zero */
6138 } else {
6139 vpush_global_sym(&func_old_type, TOK_memset);
6140 vseti(VT_LOCAL, c);
6141 #ifdef TCC_TARGET_ARM
6142 vpushs(size);
6143 vpushi(0);
6144 #else
6145 vpushi(0);
6146 vpushs(size);
6147 #endif
6148 gfunc_call(3);
6152 /* 't' contains the type and storage info. 'c' is the offset of the
6153 object in section 'sec'. If 'sec' is NULL, it means stack based
6154 allocation. 'first' is true if array '{' must be read (multi
6155 dimension implicit array init handling). 'size_only' is true if
6156 size only evaluation is wanted (only for arrays). */
6157 static void decl_initializer(CType *type, Section *sec, unsigned long c,
6158 int first, int size_only)
6160 int index, array_length, n, no_oblock, nb, parlevel, parlevel1, i;
6161 int size1, align1;
6162 int have_elem;
6163 Sym *s, *f;
6164 Sym indexsym;
6165 CType *t1;
6167 /* If we currently are at an '}' or ',' we have read an initializer
6168 element in one of our callers, and not yet consumed it. */
6169 have_elem = tok == '}' || tok == ',';
6170 if (!have_elem && tok != '{' &&
6171 /* In case of strings we have special handling for arrays, so
6172 don't consume them as initializer value (which would commit them
6173 to some anonymous symbol). */
6174 tok != TOK_LSTR && tok != TOK_STR &&
6175 !size_only) {
6176 parse_init_elem(!sec ? EXPR_ANY : EXPR_CONST);
6177 have_elem = 1;
6180 if (have_elem &&
6181 !(type->t & VT_ARRAY) &&
6182 /* Use i_c_parameter_t, to strip toplevel qualifiers.
6183 The source type might have VT_CONSTANT set, which is
6184 of course assignable to non-const elements. */
6185 is_compatible_parameter_types(type, &vtop->type)) {
6186 init_putv(type, sec, c);
6187 } else if (type->t & VT_ARRAY) {
6188 s = type->ref;
6189 n = s->c;
6190 array_length = 0;
6191 t1 = pointed_type(type);
6192 size1 = type_size(t1, &align1);
6194 no_oblock = 1;
6195 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
6196 tok == '{') {
6197 if (tok != '{')
6198 tcc_error("character array initializer must be a literal,"
6199 " optionally enclosed in braces");
6200 skip('{');
6201 no_oblock = 0;
6204 /* only parse strings here if correct type (otherwise: handle
6205 them as ((w)char *) expressions */
6206 if ((tok == TOK_LSTR &&
6207 #ifdef TCC_TARGET_PE
6208 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
6209 #else
6210 (t1->t & VT_BTYPE) == VT_INT
6211 #endif
6212 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
6213 while (tok == TOK_STR || tok == TOK_LSTR) {
6214 int cstr_len, ch;
6216 /* compute maximum number of chars wanted */
6217 if (tok == TOK_STR)
6218 cstr_len = tokc.str.size;
6219 else
6220 cstr_len = tokc.str.size / sizeof(nwchar_t);
6221 cstr_len--;
6222 nb = cstr_len;
6223 if (n >= 0 && nb > (n - array_length))
6224 nb = n - array_length;
6225 if (!size_only) {
6226 if (cstr_len > nb)
6227 tcc_warning("initializer-string for array is too long");
6228 /* in order to go faster for common case (char
6229 string in global variable, we handle it
6230 specifically */
6231 if (sec && tok == TOK_STR && size1 == 1) {
6232 memcpy(sec->data + c + array_length, tokc.str.data, nb);
6233 } else {
6234 for(i=0;i<nb;i++) {
6235 if (tok == TOK_STR)
6236 ch = ((unsigned char *)tokc.str.data)[i];
6237 else
6238 ch = ((nwchar_t *)tokc.str.data)[i];
6239 vpushi(ch);
6240 init_putv(t1, sec, c + (array_length + i) * size1);
6244 array_length += nb;
6245 next();
6247 /* only add trailing zero if enough storage (no
6248 warning in this case since it is standard) */
6249 if (n < 0 || array_length < n) {
6250 if (!size_only) {
6251 vpushi(0);
6252 init_putv(t1, sec, c + (array_length * size1));
6254 array_length++;
6256 } else {
6257 indexsym.c = 0;
6258 indexsym.r = 0;
6259 f = &indexsym;
6261 do_init_list:
6262 while (tok != '}' || have_elem) {
6263 decl_designator(type, sec, c, &f, size_only);
6264 have_elem = 0;
6265 index = f->c;
6266 /* must put zero in holes (note that doing it that way
6267 ensures that it even works with designators) */
6268 if (!size_only && array_length < index) {
6269 init_putz(sec, c + array_length * size1,
6270 (index - array_length) * size1);
6272 if (type->t & VT_ARRAY) {
6273 index = indexsym.c = ++indexsym.r;
6274 } else {
6275 index = index + type_size(&f->type, &align1);
6276 if (s->type.t == TOK_UNION)
6277 f = NULL;
6278 else
6279 f = f->next;
6281 if (index > array_length)
6282 array_length = index;
6284 if (type->t & VT_ARRAY) {
6285 /* special test for multi dimensional arrays (may not
6286 be strictly correct if designators are used at the
6287 same time) */
6288 if (no_oblock && index >= n)
6289 break;
6290 } else {
6291 if (no_oblock && f == NULL)
6292 break;
6294 if (tok == '}')
6295 break;
6296 skip(',');
6299 /* put zeros at the end */
6300 if (!size_only && array_length < n) {
6301 init_putz(sec, c + array_length * size1,
6302 (n - array_length) * size1);
6304 if (!no_oblock)
6305 skip('}');
6306 /* patch type size if needed, which happens only for array types */
6307 if (n < 0)
6308 s->c = array_length;
6309 } else if ((type->t & VT_BTYPE) == VT_STRUCT) {
6310 size1 = 1;
6311 no_oblock = 1;
6312 if (first || tok == '{') {
6313 skip('{');
6314 no_oblock = 0;
6316 s = type->ref;
6317 f = s->next;
6318 array_length = 0;
6319 n = s->c;
6320 goto do_init_list;
6321 } else if (tok == '{') {
6322 next();
6323 decl_initializer(type, sec, c, first, size_only);
6324 skip('}');
6325 } else if (size_only) {
6326 /* If we supported only ISO C we wouldn't have to accept calling
6327 this on anything than an array size_only==1 (and even then
6328 only on the outermost level, so no recursion would be needed),
6329 because initializing a flex array member isn't supported.
6330 But GNU C supports it, so we need to recurse even into
6331 subfields of structs and arrays when size_only is set. */
6332 /* just skip expression */
6333 parlevel = parlevel1 = 0;
6334 while ((parlevel > 0 || parlevel1 > 0 ||
6335 (tok != '}' && tok != ',')) && tok != -1) {
6336 if (tok == '(')
6337 parlevel++;
6338 else if (tok == ')') {
6339 if (parlevel == 0 && parlevel1 == 0)
6340 break;
6341 parlevel--;
6343 else if (tok == '{')
6344 parlevel1++;
6345 else if (tok == '}') {
6346 if (parlevel == 0 && parlevel1 == 0)
6347 break;
6348 parlevel1--;
6350 next();
6352 } else {
6353 if (!have_elem) {
6354 /* This should happen only when we haven't parsed
6355 the init element above for fear of committing a
6356 string constant to memory too early. */
6357 if (tok != TOK_STR && tok != TOK_LSTR)
6358 expect("string constant");
6359 parse_init_elem(!sec ? EXPR_ANY : EXPR_CONST);
6361 init_putv(type, sec, c);
6365 /* parse an initializer for type 't' if 'has_init' is non zero, and
6366 allocate space in local or global data space ('r' is either
6367 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
6368 variable 'v' of scope 'scope' is declared before initializers
6369 are parsed. If 'v' is zero, then a reference to the new object
6370 is put in the value stack. If 'has_init' is 2, a special parsing
6371 is done to handle string constants. */
6372 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
6373 int has_init, int v, int scope)
6375 int size, align, addr, data_offset;
6376 int level;
6377 ParseState saved_parse_state = {0};
6378 TokenString *init_str = NULL;
6379 Section *sec;
6380 Sym *flexible_array;
6382 flexible_array = NULL;
6383 if ((type->t & VT_BTYPE) == VT_STRUCT) {
6384 Sym *field = type->ref->next;
6385 if (field) {
6386 while (field->next)
6387 field = field->next;
6388 if (field->type.t & VT_ARRAY && field->type.ref->c < 0)
6389 flexible_array = field;
6393 size = type_size(type, &align);
6394 /* If unknown size, we must evaluate it before
6395 evaluating initializers because
6396 initializers can generate global data too
6397 (e.g. string pointers or ISOC99 compound
6398 literals). It also simplifies local
6399 initializers handling */
6400 if (size < 0 || (flexible_array && has_init)) {
6401 if (!has_init)
6402 tcc_error("unknown type size");
6403 /* get all init string */
6404 init_str = tok_str_alloc();
6405 if (has_init == 2) {
6406 /* only get strings */
6407 while (tok == TOK_STR || tok == TOK_LSTR) {
6408 tok_str_add_tok(init_str);
6409 next();
6411 } else {
6412 level = 0;
6413 while (level > 0 || (tok != ',' && tok != ';')) {
6414 if (tok < 0)
6415 tcc_error("unexpected end of file in initializer");
6416 tok_str_add_tok(init_str);
6417 if (tok == '{')
6418 level++;
6419 else if (tok == '}') {
6420 level--;
6421 if (level <= 0) {
6422 next();
6423 break;
6426 next();
6429 tok_str_add(init_str, -1);
6430 tok_str_add(init_str, 0);
6432 /* compute size */
6433 save_parse_state(&saved_parse_state);
6435 begin_macro(init_str, 1);
6436 next();
6437 decl_initializer(type, NULL, 0, 1, 1);
6438 /* prepare second initializer parsing */
6439 macro_ptr = init_str->str;
6440 next();
6442 /* if still unknown size, error */
6443 size = type_size(type, &align);
6444 if (size < 0)
6445 tcc_error("unknown type size");
6447 /* If there's a flex member and it was used in the initializer
6448 adjust size. */
6449 if (flexible_array &&
6450 flexible_array->type.ref->c > 0)
6451 size += flexible_array->type.ref->c
6452 * pointed_size(&flexible_array->type);
6453 /* take into account specified alignment if bigger */
6454 if (ad->a.aligned) {
6455 if (ad->a.aligned > align)
6456 align = ad->a.aligned;
6457 } else if (ad->a.packed) {
6458 align = 1;
6460 if ((r & VT_VALMASK) == VT_LOCAL) {
6461 sec = NULL;
6462 #ifdef CONFIG_TCC_BCHECK
6463 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
6464 loc--;
6466 #endif
6467 loc = (loc - size) & -align;
6468 addr = loc;
6469 #ifdef CONFIG_TCC_BCHECK
6470 /* handles bounds */
6471 /* XXX: currently, since we do only one pass, we cannot track
6472 '&' operators, so we add only arrays */
6473 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
6474 addr_t *bounds_ptr;
6475 /* add padding between regions */
6476 loc--;
6477 /* then add local bound info */
6478 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(addr_t));
6479 bounds_ptr[0] = addr;
6480 bounds_ptr[1] = size;
6482 #endif
6483 if (v) {
6484 /* local variable */
6485 #ifdef CONFIG_TCC_ASM
6486 if (ad->asm_label) {
6487 int reg = asm_parse_regvar(ad->asm_label);
6488 if (reg >= 0)
6489 r = (r & ~VT_VALMASK) | reg;
6491 #endif
6492 sym_push(v, type, r, addr);
6493 } else {
6494 /* push local reference */
6495 vset(type, r, addr);
6497 } else {
6498 Sym *sym;
6500 sym = NULL;
6501 if (v && scope == VT_CONST) {
6502 /* see if the symbol was already defined */
6503 sym = sym_find(v);
6504 if (sym) {
6505 if (!is_compatible_types(&sym->type, type))
6506 tcc_error("incompatible types for redefinition of '%s'",
6507 get_tok_str(v, NULL));
6508 if (sym->type.t & VT_EXTERN) {
6509 /* if the variable is extern, it was not allocated */
6510 sym->type.t &= ~VT_EXTERN;
6511 /* set array size if it was omitted in extern
6512 declaration */
6513 if ((sym->type.t & VT_ARRAY) &&
6514 sym->type.ref->c < 0 &&
6515 type->ref->c >= 0)
6516 sym->type.ref->c = type->ref->c;
6517 } else {
6518 /* we accept several definitions of the same
6519 global variable. this is tricky, because we
6520 must play with the SHN_COMMON type of the symbol */
6521 /* XXX: should check if the variable was already
6522 initialized. It is incorrect to initialized it
6523 twice */
6524 /* no init data, we won't add more to the symbol */
6525 if (!has_init)
6526 goto no_alloc;
6531 /* allocate symbol in corresponding section */
6532 sec = ad->section;
6533 if (!sec) {
6534 if (has_init)
6535 sec = data_section;
6536 else if (tcc_state->nocommon)
6537 sec = bss_section;
6539 if (sec) {
6540 data_offset = sec->data_offset;
6541 data_offset = (data_offset + align - 1) & -align;
6542 addr = data_offset;
6543 /* very important to increment global pointer at this time
6544 because initializers themselves can create new initializers */
6545 data_offset += size;
6546 #ifdef CONFIG_TCC_BCHECK
6547 /* add padding if bound check */
6548 if (tcc_state->do_bounds_check)
6549 data_offset++;
6550 #endif
6551 sec->data_offset = data_offset;
6552 /* allocate section space to put the data */
6553 if (sec->sh_type != SHT_NOBITS &&
6554 data_offset > sec->data_allocated)
6555 section_realloc(sec, data_offset);
6556 /* align section if needed */
6557 if (align > sec->sh_addralign)
6558 sec->sh_addralign = align;
6559 } else {
6560 addr = 0; /* avoid warning */
6563 if (v) {
6564 if (scope != VT_CONST || !sym) {
6565 sym = sym_push(v, type, r | VT_SYM, 0);
6566 sym->asm_label = ad->asm_label;
6568 /* update symbol definition */
6569 if (sec) {
6570 put_extern_sym(sym, sec, addr, size);
6571 } else {
6572 ElfW(Sym) *esym;
6573 /* put a common area */
6574 put_extern_sym(sym, NULL, align, size);
6575 /* XXX: find a nicer way */
6576 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
6577 esym->st_shndx = SHN_COMMON;
6579 } else {
6580 /* push global reference */
6581 sym = get_sym_ref(type, sec, addr, size);
6582 vpushsym(type, sym);
6584 /* patch symbol weakness */
6585 if (type->t & VT_WEAK)
6586 weaken_symbol(sym);
6587 apply_visibility(sym, type);
6588 #ifdef CONFIG_TCC_BCHECK
6589 /* handles bounds now because the symbol must be defined
6590 before for the relocation */
6591 if (tcc_state->do_bounds_check) {
6592 addr_t *bounds_ptr;
6594 greloc(bounds_section, sym, bounds_section->data_offset, R_DATA_PTR);
6595 /* then add global bound info */
6596 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(addr_t));
6597 bounds_ptr[0] = 0; /* relocated */
6598 bounds_ptr[1] = size;
6600 #endif
6602 if (type->t & VT_VLA) {
6603 int a;
6605 /* save current stack pointer */
6606 if (vlas_in_scope == 0) {
6607 if (vla_sp_root_loc == -1)
6608 vla_sp_root_loc = (loc -= PTR_SIZE);
6609 gen_vla_sp_save(vla_sp_root_loc);
6612 vla_runtime_type_size(type, &a);
6613 gen_vla_alloc(type, a);
6614 gen_vla_sp_save(addr);
6615 vla_sp_loc = addr;
6616 vlas_in_scope++;
6617 } else if (has_init) {
6618 size_t oldreloc_offset = 0;
6619 if (sec && sec->reloc)
6620 oldreloc_offset = sec->reloc->data_offset;
6621 decl_initializer(type, sec, addr, 1, 0);
6622 if (sec && sec->reloc)
6623 squeeze_multi_relocs(sec, oldreloc_offset);
6624 /* patch flexible array member size back to -1, */
6625 /* for possible subsequent similar declarations */
6626 if (flexible_array)
6627 flexible_array->type.ref->c = -1;
6629 no_alloc: ;
6630 /* restore parse state if needed */
6631 if (init_str) {
6632 end_macro();
6633 restore_parse_state(&saved_parse_state);
6637 static void put_func_debug(Sym *sym)
6639 char buf[512];
6641 /* stabs info */
6642 /* XXX: we put here a dummy type */
6643 snprintf(buf, sizeof(buf), "%s:%c1",
6644 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
6645 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
6646 cur_text_section, sym->c);
6647 /* //gr gdb wants a line at the function */
6648 put_stabn(N_SLINE, 0, file->line_num, 0);
6649 last_ind = 0;
6650 last_line_num = 0;
6653 /* parse an old style function declaration list */
6654 /* XXX: check multiple parameter */
6655 static void func_decl_list(Sym *func_sym)
6657 AttributeDef ad;
6658 int v;
6659 Sym *s;
6660 CType btype, type;
6662 /* parse each declaration */
6663 while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF &&
6664 tok != TOK_ASM1 && tok != TOK_ASM2 && tok != TOK_ASM3) {
6665 if (!parse_btype(&btype, &ad))
6666 expect("declaration list");
6667 if (((btype.t & VT_BTYPE) == VT_ENUM ||
6668 (btype.t & VT_BTYPE) == VT_STRUCT) &&
6669 tok == ';') {
6670 /* we accept no variable after */
6671 } else {
6672 for(;;) {
6673 type = btype;
6674 type_decl(&type, &ad, &v, TYPE_DIRECT);
6675 /* find parameter in function parameter list */
6676 s = func_sym->next;
6677 while (s != NULL) {
6678 if ((s->v & ~SYM_FIELD) == v)
6679 goto found;
6680 s = s->next;
6682 tcc_error("declaration for parameter '%s' but no such parameter",
6683 get_tok_str(v, NULL));
6684 found:
6685 /* check that no storage specifier except 'register' was given */
6686 if (type.t & VT_STORAGE)
6687 tcc_error("storage class specified for '%s'", get_tok_str(v, NULL));
6688 convert_parameter_type(&type);
6689 /* we can add the type (NOTE: it could be local to the function) */
6690 s->type = type;
6691 /* accept other parameters */
6692 if (tok == ',')
6693 next();
6694 else
6695 break;
6698 skip(';');
6702 /* parse a function defined by symbol 'sym' and generate its code in
6703 'cur_text_section' */
6704 static void gen_function(Sym *sym)
6706 int saved_nocode_wanted = nocode_wanted;
6708 nocode_wanted = 0;
6709 ind = cur_text_section->data_offset;
6710 /* NOTE: we patch the symbol size later */
6711 put_extern_sym(sym, cur_text_section, ind, 0);
6712 funcname = get_tok_str(sym->v, NULL);
6713 func_ind = ind;
6714 /* Initialize VLA state */
6715 vla_sp_loc = -1;
6716 vla_sp_root_loc = -1;
6717 /* put debug symbol */
6718 if (tcc_state->do_debug)
6719 put_func_debug(sym);
6721 /* push a dummy symbol to enable local sym storage */
6722 sym_push2(&local_stack, SYM_FIELD, 0, 0);
6723 local_scope = 1; /* for function parameters */
6724 gfunc_prolog(&sym->type);
6725 local_scope = 0;
6727 rsym = 0;
6728 block(NULL, NULL, 0);
6729 gsym(rsym);
6730 gfunc_epilog();
6731 cur_text_section->data_offset = ind;
6732 label_pop(&global_label_stack, NULL);
6733 /* reset local stack */
6734 local_scope = 0;
6735 sym_pop(&local_stack, NULL, 0);
6736 /* end of function */
6737 /* patch symbol size */
6738 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
6739 ind - func_ind;
6740 /* patch symbol weakness (this definition overrules any prototype) */
6741 if (sym->type.t & VT_WEAK)
6742 weaken_symbol(sym);
6743 apply_visibility(sym, &sym->type);
6744 if (tcc_state->do_debug) {
6745 put_stabn(N_FUN, 0, 0, ind - func_ind);
6747 /* It's better to crash than to generate wrong code */
6748 cur_text_section = NULL;
6749 funcname = ""; /* for safety */
6750 func_vt.t = VT_VOID; /* for safety */
6751 func_var = 0; /* for safety */
6752 ind = 0; /* for safety */
6753 nocode_wanted = saved_nocode_wanted;
6754 check_vstack();
6757 static void gen_inline_functions(TCCState *s)
6759 Sym *sym;
6760 int inline_generated, i, ln;
6761 struct InlineFunc *fn;
6763 ln = file->line_num;
6764 /* iterate while inline function are referenced */
6765 for(;;) {
6766 inline_generated = 0;
6767 for (i = 0; i < s->nb_inline_fns; ++i) {
6768 fn = s->inline_fns[i];
6769 sym = fn->sym;
6770 if (sym && sym->c) {
6771 /* the function was used: generate its code and
6772 convert it to a normal function */
6773 fn->sym = NULL;
6774 if (file)
6775 pstrcpy(file->filename, sizeof file->filename, fn->filename);
6776 sym->r = VT_SYM | VT_CONST;
6777 sym->type.t &= ~VT_INLINE;
6779 begin_macro(fn->func_str, 1);
6780 next();
6781 cur_text_section = text_section;
6782 gen_function(sym);
6783 end_macro();
6785 inline_generated = 1;
6788 if (!inline_generated)
6789 break;
6791 file->line_num = ln;
6794 ST_FUNC void free_inline_functions(TCCState *s)
6796 int i;
6797 /* free tokens of unused inline functions */
6798 for (i = 0; i < s->nb_inline_fns; ++i) {
6799 struct InlineFunc *fn = s->inline_fns[i];
6800 if (fn->sym)
6801 tok_str_free(fn->func_str);
6803 dynarray_reset(&s->inline_fns, &s->nb_inline_fns);
6806 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
6807 static int decl0(int l, int is_for_loop_init)
6809 int v, has_init, r;
6810 CType type, btype;
6811 Sym *sym;
6812 AttributeDef ad;
6814 while (1) {
6815 if (!parse_btype(&btype, &ad)) {
6816 if (is_for_loop_init)
6817 return 0;
6818 /* skip redundant ';' */
6819 /* XXX: find more elegant solution */
6820 if (tok == ';') {
6821 next();
6822 continue;
6824 if (l == VT_CONST &&
6825 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
6826 /* global asm block */
6827 asm_global_instr();
6828 continue;
6830 /* special test for old K&R protos without explicit int
6831 type. Only accepted when defining global data */
6832 if (l == VT_LOCAL || tok < TOK_UIDENT)
6833 break;
6834 btype.t = VT_INT;
6836 if (((btype.t & VT_BTYPE) == VT_ENUM ||
6837 (btype.t & VT_BTYPE) == VT_STRUCT) &&
6838 tok == ';') {
6839 if ((btype.t & VT_BTYPE) == VT_STRUCT) {
6840 int v = btype.ref->v;
6841 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) >= SYM_FIRST_ANOM)
6842 tcc_warning("unnamed struct/union that defines no instances");
6844 next();
6845 continue;
6847 while (1) { /* iterate thru each declaration */
6848 type = btype;
6849 /* If the base type itself was an array type of unspecified
6850 size (like in 'typedef int arr[]; arr x = {1};') then
6851 we will overwrite the unknown size by the real one for
6852 this decl. We need to unshare the ref symbol holding
6853 that size. */
6854 if ((type.t & VT_ARRAY) && type.ref->c < 0) {
6855 type.ref = sym_push(SYM_FIELD, &type.ref->type, 0, type.ref->c);
6857 type_decl(&type, &ad, &v, TYPE_DIRECT);
6858 #if 0
6860 char buf[500];
6861 type_to_str(buf, sizeof(buf), t, get_tok_str(v, NULL));
6862 printf("type = '%s'\n", buf);
6864 #endif
6865 if ((type.t & VT_BTYPE) == VT_FUNC) {
6866 if ((type.t & VT_STATIC) && (l == VT_LOCAL)) {
6867 tcc_error("function without file scope cannot be static");
6869 /* if old style function prototype, we accept a
6870 declaration list */
6871 sym = type.ref;
6872 if (sym->c == FUNC_OLD)
6873 func_decl_list(sym);
6876 if (gnu_ext && (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
6877 ad.asm_label = asm_label_instr();
6878 /* parse one last attribute list, after asm label */
6879 parse_attribute(&ad);
6880 if (tok == '{')
6881 expect(";");
6884 if (ad.a.weak)
6885 type.t |= VT_WEAK;
6886 #ifdef TCC_TARGET_PE
6887 if (ad.a.func_import)
6888 type.t |= VT_IMPORT;
6889 if (ad.a.func_export)
6890 type.t |= VT_EXPORT;
6891 #endif
6892 type.t |= ad.a.visibility << VT_VIS_SHIFT;
6894 if (tok == '{') {
6895 if (l == VT_LOCAL)
6896 tcc_error("cannot use local functions");
6897 if ((type.t & VT_BTYPE) != VT_FUNC)
6898 expect("function definition");
6900 /* reject abstract declarators in function definition */
6901 sym = type.ref;
6902 while ((sym = sym->next) != NULL)
6903 if (!(sym->v & ~SYM_FIELD))
6904 expect("identifier");
6906 /* XXX: cannot do better now: convert extern line to static inline */
6907 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
6908 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
6910 sym = sym_find(v);
6911 if (sym) {
6912 Sym *ref;
6913 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
6914 goto func_error1;
6916 ref = sym->type.ref;
6917 if (0 == ref->a.func_proto)
6918 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
6920 /* use func_call from prototype if not defined */
6921 if (ref->a.func_call != FUNC_CDECL
6922 && type.ref->a.func_call == FUNC_CDECL)
6923 type.ref->a.func_call = ref->a.func_call;
6925 /* use export from prototype */
6926 if (ref->a.func_export)
6927 type.ref->a.func_export = 1;
6929 /* use static from prototype */
6930 if (sym->type.t & VT_STATIC)
6931 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
6933 /* If the definition has no visibility use the
6934 one from prototype. */
6935 if (! (type.t & VT_VIS_MASK))
6936 type.t |= sym->type.t & VT_VIS_MASK;
6938 if (!is_compatible_types(&sym->type, &type)) {
6939 func_error1:
6940 tcc_error("incompatible types for redefinition of '%s'",
6941 get_tok_str(v, NULL));
6943 type.ref->a.func_proto = 0;
6944 /* if symbol is already defined, then put complete type */
6945 sym->type = type;
6946 } else {
6947 /* put function symbol */
6948 sym = global_identifier_push(v, type.t, 0);
6949 sym->type.ref = type.ref;
6952 /* static inline functions are just recorded as a kind
6953 of macro. Their code will be emitted at the end of
6954 the compilation unit only if they are used */
6955 if ((type.t & (VT_INLINE | VT_STATIC)) ==
6956 (VT_INLINE | VT_STATIC)) {
6957 int block_level;
6958 struct InlineFunc *fn;
6959 const char *filename;
6961 filename = file ? file->filename : "";
6962 fn = tcc_malloc(sizeof *fn + strlen(filename));
6963 strcpy(fn->filename, filename);
6964 fn->sym = sym;
6965 fn->func_str = tok_str_alloc();
6967 block_level = 0;
6968 for(;;) {
6969 int t;
6970 if (tok == TOK_EOF)
6971 tcc_error("unexpected end of file");
6972 tok_str_add_tok(fn->func_str);
6973 t = tok;
6974 next();
6975 if (t == '{') {
6976 block_level++;
6977 } else if (t == '}') {
6978 block_level--;
6979 if (block_level == 0)
6980 break;
6983 tok_str_add(fn->func_str, -1);
6984 tok_str_add(fn->func_str, 0);
6985 dynarray_add((void ***)&tcc_state->inline_fns, &tcc_state->nb_inline_fns, fn);
6987 } else {
6988 /* compute text section */
6989 cur_text_section = ad.section;
6990 if (!cur_text_section)
6991 cur_text_section = text_section;
6992 sym->r = VT_SYM | VT_CONST;
6993 gen_function(sym);
6995 break;
6996 } else {
6997 if (btype.t & VT_TYPEDEF) {
6998 /* save typedefed type */
6999 /* XXX: test storage specifiers ? */
7000 sym = sym_find(v);
7001 if (sym && sym->scope == local_scope) {
7002 if (!is_compatible_types(&sym->type, &type)
7003 || !(sym->type.t & VT_TYPEDEF))
7004 tcc_error("incompatible redefinition of '%s'",
7005 get_tok_str(v, NULL));
7006 sym->type = type;
7007 } else {
7008 sym = sym_push(v, &type, 0, 0);
7010 sym->a = ad.a;
7011 sym->type.t |= VT_TYPEDEF;
7012 } else {
7013 r = 0;
7014 if ((type.t & VT_BTYPE) == VT_FUNC) {
7015 /* external function definition */
7016 /* specific case for func_call attribute */
7017 ad.a.func_proto = 1;
7018 type.ref->a = ad.a;
7019 } else if (!(type.t & VT_ARRAY)) {
7020 /* not lvalue if array */
7021 r |= lvalue_type(type.t);
7023 has_init = (tok == '=');
7024 if (has_init && (type.t & VT_VLA))
7025 tcc_error("variable length array cannot be initialized");
7026 if ((btype.t & VT_EXTERN) || ((type.t & VT_BTYPE) == VT_FUNC) ||
7027 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
7028 !has_init && l == VT_CONST && type.ref->c < 0)) {
7029 /* external variable or function */
7030 /* NOTE: as GCC, uninitialized global static
7031 arrays of null size are considered as
7032 extern */
7033 sym = external_sym(v, &type, r);
7034 sym->asm_label = ad.asm_label;
7036 if (ad.alias_target) {
7037 Section tsec;
7038 ElfW(Sym) *esym;
7039 Sym *alias_target;
7041 alias_target = sym_find(ad.alias_target);
7042 if (!alias_target || !alias_target->c)
7043 tcc_error("unsupported forward __alias__ attribute");
7044 esym = &((ElfW(Sym) *)symtab_section->data)[alias_target->c];
7045 tsec.sh_num = esym->st_shndx;
7046 put_extern_sym2(sym, &tsec, esym->st_value, esym->st_size, 0);
7048 } else {
7049 type.t |= (btype.t & VT_STATIC); /* Retain "static". */
7050 if (type.t & VT_STATIC)
7051 r |= VT_CONST;
7052 else
7053 r |= l;
7054 if (has_init)
7055 next();
7056 decl_initializer_alloc(&type, &ad, r, has_init, v, l);
7059 if (tok != ',') {
7060 if (is_for_loop_init)
7061 return 1;
7062 skip(';');
7063 break;
7065 next();
7067 ad.a.aligned = 0;
7070 return 0;
7073 ST_FUNC void decl(int l)
7075 decl0(l, 0);
7078 /* ------------------------------------------------------------------------- */