Fix access-after-free with statement expressions
[tinycc.git] / tccgen.c
blobbe5a8cb55df412a75212cfe3f49f44c529d9ce10
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->asm_label = 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;
582 /* push constant of type "type" with useless value */
583 ST_FUNC void vpush(CType *type)
585 CValue cval;
586 vsetc(type, VT_CONST, &cval);
589 /* push integer constant */
590 ST_FUNC void vpushi(int v)
592 CValue cval;
593 cval.i = v;
594 vsetc(&int_type, VT_CONST, &cval);
597 /* push a pointer sized constant */
598 static void vpushs(addr_t v)
600 CValue cval;
601 cval.i = v;
602 vsetc(&size_type, VT_CONST, &cval);
605 /* push arbitrary 64bit constant */
606 ST_FUNC void vpush64(int ty, unsigned long long v)
608 CValue cval;
609 CType ctype;
610 ctype.t = ty;
611 ctype.ref = NULL;
612 cval.i = v;
613 vsetc(&ctype, VT_CONST, &cval);
616 /* push long long constant */
617 static inline void vpushll(long long v)
619 vpush64(VT_LLONG, v);
622 /* push a symbol value of TYPE */
623 static inline void vpushsym(CType *type, Sym *sym)
625 CValue cval;
626 cval.i = 0;
627 vsetc(type, VT_CONST | VT_SYM, &cval);
628 vtop->sym = sym;
631 /* Return a static symbol pointing to a section */
632 ST_FUNC Sym *get_sym_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
634 int v;
635 Sym *sym;
637 v = anon_sym++;
638 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
639 sym->type.ref = type->ref;
640 sym->r = VT_CONST | VT_SYM;
641 put_extern_sym(sym, sec, offset, size);
642 return sym;
645 /* push a reference to a section offset by adding a dummy symbol */
646 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
648 vpushsym(type, get_sym_ref(type, sec, offset, size));
651 /* define a new external reference to a symbol 'v' of type 'u' */
652 ST_FUNC Sym *external_global_sym(int v, CType *type, int r)
654 Sym *s;
656 s = sym_find(v);
657 if (!s) {
658 /* push forward reference */
659 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
660 s->type.ref = type->ref;
661 s->r = r | VT_CONST | VT_SYM;
663 return s;
666 /* define a new external reference to a symbol 'v' */
667 static Sym *external_sym(int v, CType *type, int r)
669 Sym *s;
671 s = sym_find(v);
672 if (!s) {
673 /* push forward reference */
674 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
675 s->type.t |= VT_EXTERN;
676 } else if (s->type.ref == func_old_type.ref) {
677 s->type.ref = type->ref;
678 s->r = r | VT_CONST | VT_SYM;
679 s->type.t |= VT_EXTERN;
680 } else if (!is_compatible_types(&s->type, type)) {
681 tcc_error("incompatible types for redefinition of '%s'",
682 get_tok_str(v, NULL));
684 /* Merge some storage attributes. */
685 if (type->t & VT_WEAK)
686 weaken_symbol(s);
688 if (type->t & VT_VIS_MASK)
689 apply_visibility(s, type);
691 return s;
694 /* push a reference to global symbol v */
695 ST_FUNC void vpush_global_sym(CType *type, int v)
697 vpushsym(type, external_global_sym(v, type, 0));
700 ST_FUNC void vset(CType *type, int r, int v)
702 CValue cval;
704 cval.i = v;
705 vsetc(type, r, &cval);
708 static void vseti(int r, int v)
710 CType type;
711 type.t = VT_INT;
712 type.ref = 0;
713 vset(&type, r, v);
716 ST_FUNC void vswap(void)
718 SValue tmp;
719 /* cannot let cpu flags if other instruction are generated. Also
720 avoid leaving VT_JMP anywhere except on the top of the stack
721 because it would complicate the code generator. */
722 if (vtop >= vstack) {
723 int v = vtop->r & VT_VALMASK;
724 if (v == VT_CMP || (v & ~1) == VT_JMP)
725 gv(RC_INT);
727 tmp = vtop[0];
728 vtop[0] = vtop[-1];
729 vtop[-1] = tmp;
731 /* XXX: +2% overall speed possible with optimized memswap
733 * memswap(&vtop[0], &vtop[1], sizeof *vtop);
737 ST_FUNC void vpushv(SValue *v)
739 if (vtop >= vstack + (VSTACK_SIZE - 1))
740 tcc_error("memory full (vstack)");
741 vtop++;
742 *vtop = *v;
745 static void vdup(void)
747 vpushv(vtop);
750 /* save registers up to (vtop - n) stack entry */
751 ST_FUNC void save_regs(int n)
753 SValue *p, *p1;
754 for(p = vstack, p1 = vtop - n; p <= p1; p++)
755 save_reg(p->r);
758 /* save r to the memory stack, and mark it as being free */
759 ST_FUNC void save_reg(int r)
761 save_reg_upstack(r, 0);
764 /* save r to the memory stack, and mark it as being free,
765 if seen up to (vtop - n) stack entry */
766 ST_FUNC void save_reg_upstack(int r, int n)
768 int l, saved, size, align;
769 SValue *p, *p1, sv;
770 CType *type;
772 if ((r &= VT_VALMASK) >= VT_CONST)
773 return;
775 /* modify all stack values */
776 saved = 0;
777 l = 0;
778 for(p = vstack, p1 = vtop - n; p <= p1; p++) {
779 if ((p->r & VT_VALMASK) == r ||
780 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
781 /* must save value on stack if not already done */
782 if (!saved) {
783 /* NOTE: must reload 'r' because r might be equal to r2 */
784 r = p->r & VT_VALMASK;
785 /* store register in the stack */
786 type = &p->type;
787 if ((p->r & VT_LVAL) ||
788 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
789 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
790 type = &char_pointer_type;
791 #else
792 type = &int_type;
793 #endif
794 size = type_size(type, &align);
795 loc = (loc - size) & -align;
796 sv.type.t = type->t;
797 sv.r = VT_LOCAL | VT_LVAL;
798 sv.c.i = loc;
799 store(r, &sv);
800 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
801 /* x86 specific: need to pop fp register ST0 if saved */
802 if (r == TREG_ST0) {
803 o(0xd8dd); /* fstp %st(0) */
805 #endif
806 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
807 /* special long long case */
808 if ((type->t & VT_BTYPE) == VT_LLONG) {
809 sv.c.i += 4;
810 store(p->r2, &sv);
812 #endif
813 l = loc;
814 saved = 1;
816 /* mark that stack entry as being saved on the stack */
817 if (p->r & VT_LVAL) {
818 /* also clear the bounded flag because the
819 relocation address of the function was stored in
820 p->c.i */
821 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
822 } else {
823 p->r = lvalue_type(p->type.t) | VT_LOCAL;
825 p->r2 = VT_CONST;
826 p->c.i = l;
831 #ifdef TCC_TARGET_ARM
832 /* find a register of class 'rc2' with at most one reference on stack.
833 * If none, call get_reg(rc) */
834 ST_FUNC int get_reg_ex(int rc, int rc2)
836 int r;
837 SValue *p;
839 for(r=0;r<NB_REGS;r++) {
840 if (reg_classes[r] & rc2) {
841 int n;
842 n=0;
843 for(p = vstack; p <= vtop; p++) {
844 if ((p->r & VT_VALMASK) == r ||
845 (p->r2 & VT_VALMASK) == r)
846 n++;
848 if (n <= 1)
849 return r;
852 return get_reg(rc);
854 #endif
856 /* find a free register of class 'rc'. If none, save one register */
857 ST_FUNC int get_reg(int rc)
859 int r;
860 SValue *p;
862 /* find a free register */
863 for(r=0;r<NB_REGS;r++) {
864 if (reg_classes[r] & rc) {
865 for(p=vstack;p<=vtop;p++) {
866 if ((p->r & VT_VALMASK) == r ||
867 (p->r2 & VT_VALMASK) == r)
868 goto notfound;
870 return r;
872 notfound: ;
875 /* no register left : free the first one on the stack (VERY
876 IMPORTANT to start from the bottom to ensure that we don't
877 spill registers used in gen_opi()) */
878 for(p=vstack;p<=vtop;p++) {
879 /* look at second register (if long long) */
880 r = p->r2 & VT_VALMASK;
881 if (r < VT_CONST && (reg_classes[r] & rc))
882 goto save_found;
883 r = p->r & VT_VALMASK;
884 if (r < VT_CONST && (reg_classes[r] & rc)) {
885 save_found:
886 save_reg(r);
887 return r;
890 /* Should never comes here */
891 return -1;
894 /* move register 's' (of type 't') to 'r', and flush previous value of r to memory
895 if needed */
896 static void move_reg(int r, int s, int t)
898 SValue sv;
900 if (r != s) {
901 save_reg(r);
902 sv.type.t = t;
903 sv.type.ref = NULL;
904 sv.r = s;
905 sv.c.i = 0;
906 load(r, &sv);
910 /* get address of vtop (vtop MUST BE an lvalue) */
911 ST_FUNC void gaddrof(void)
913 if (vtop->r & VT_REF && !nocode_wanted)
914 gv(RC_INT);
915 vtop->r &= ~VT_LVAL;
916 /* tricky: if saved lvalue, then we can go back to lvalue */
917 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
918 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
923 #ifdef CONFIG_TCC_BCHECK
924 /* generate lvalue bound code */
925 static void gbound(void)
927 int lval_type;
928 CType type1;
930 vtop->r &= ~VT_MUSTBOUND;
931 /* if lvalue, then use checking code before dereferencing */
932 if (vtop->r & VT_LVAL) {
933 /* if not VT_BOUNDED value, then make one */
934 if (!(vtop->r & VT_BOUNDED)) {
935 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
936 /* must save type because we must set it to int to get pointer */
937 type1 = vtop->type;
938 vtop->type.t = VT_PTR;
939 gaddrof();
940 vpushi(0);
941 gen_bounded_ptr_add();
942 vtop->r |= lval_type;
943 vtop->type = type1;
945 /* then check for dereferencing */
946 gen_bounded_ptr_deref();
949 #endif
951 /* store vtop a register belonging to class 'rc'. lvalues are
952 converted to values. Cannot be used if cannot be converted to
953 register value (such as structures). */
954 ST_FUNC int gv(int rc)
956 int r, bit_pos, bit_size, size, align, i;
957 int rc2;
959 /* NOTE: get_reg can modify vstack[] */
960 if (vtop->type.t & VT_BITFIELD) {
961 CType type;
962 int bits = 32;
963 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
964 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
965 /* remove bit field info to avoid loops */
966 vtop->type.t &= ~VT_BITFIELD & ((1 << VT_STRUCT_SHIFT) - 1);
967 /* cast to int to propagate signedness in following ops */
968 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
969 type.t = VT_LLONG;
970 bits = 64;
971 } else
972 type.t = VT_INT;
973 if((vtop->type.t & VT_UNSIGNED) ||
974 (vtop->type.t & VT_BTYPE) == VT_BOOL)
975 type.t |= VT_UNSIGNED;
976 gen_cast(&type);
977 /* generate shifts */
978 vpushi(bits - (bit_pos + bit_size));
979 gen_op(TOK_SHL);
980 vpushi(bits - bit_size);
981 /* NOTE: transformed to SHR if unsigned */
982 gen_op(TOK_SAR);
983 r = gv(rc);
984 } else {
985 if (is_float(vtop->type.t) &&
986 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
987 Sym *sym;
988 int *ptr;
989 unsigned long offset;
990 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
991 CValue check;
992 #endif
994 /* XXX: unify with initializers handling ? */
995 /* CPUs usually cannot use float constants, so we store them
996 generically in data segment */
997 size = type_size(&vtop->type, &align);
998 offset = (data_section->data_offset + align - 1) & -align;
999 data_section->data_offset = offset;
1000 /* XXX: not portable yet */
1001 #if defined(__i386__) || defined(__x86_64__)
1002 /* Zero pad x87 tenbyte long doubles */
1003 if (size == LDOUBLE_SIZE) {
1004 vtop->c.tab[2] &= 0xffff;
1005 #if LDOUBLE_SIZE == 16
1006 vtop->c.tab[3] = 0;
1007 #endif
1009 #endif
1010 ptr = section_ptr_add(data_section, size);
1011 size = size >> 2;
1012 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
1013 check.d = 1;
1014 if(check.tab[0])
1015 for(i=0;i<size;i++)
1016 ptr[i] = vtop->c.tab[size-1-i];
1017 else
1018 #endif
1019 for(i=0;i<size;i++)
1020 ptr[i] = vtop->c.tab[i];
1021 sym = get_sym_ref(&vtop->type, data_section, offset, size << 2);
1022 vtop->r |= VT_LVAL | VT_SYM;
1023 vtop->sym = sym;
1024 vtop->c.i = 0;
1026 #ifdef CONFIG_TCC_BCHECK
1027 if (vtop->r & VT_MUSTBOUND)
1028 gbound();
1029 #endif
1031 r = vtop->r & VT_VALMASK;
1032 rc2 = (rc & RC_FLOAT) ? RC_FLOAT : RC_INT;
1033 #ifndef TCC_TARGET_ARM64
1034 if (rc == RC_IRET)
1035 rc2 = RC_LRET;
1036 #ifdef TCC_TARGET_X86_64
1037 else if (rc == RC_FRET)
1038 rc2 = RC_QRET;
1039 #endif
1040 #endif
1042 /* need to reload if:
1043 - constant
1044 - lvalue (need to dereference pointer)
1045 - already a register, but not in the right class */
1046 if (r >= VT_CONST
1047 || (vtop->r & VT_LVAL)
1048 || !(reg_classes[r] & rc)
1049 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1050 || ((vtop->type.t & VT_BTYPE) == VT_QLONG && !(reg_classes[vtop->r2] & rc2))
1051 || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT && !(reg_classes[vtop->r2] & rc2))
1052 #else
1053 || ((vtop->type.t & VT_BTYPE) == VT_LLONG && !(reg_classes[vtop->r2] & rc2))
1054 #endif
1057 r = get_reg(rc);
1058 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1059 if (((vtop->type.t & VT_BTYPE) == VT_QLONG) || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT)) {
1060 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
1061 #else
1062 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
1063 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
1064 unsigned long long ll;
1065 #endif
1066 int r2, original_type;
1067 original_type = vtop->type.t;
1068 /* two register type load : expand to two words
1069 temporarily */
1070 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
1071 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
1072 /* load constant */
1073 ll = vtop->c.i;
1074 vtop->c.i = ll; /* first word */
1075 load(r, vtop);
1076 vtop->r = r; /* save register value */
1077 vpushi(ll >> 32); /* second word */
1078 } else
1079 #endif
1080 if (vtop->r & VT_LVAL) {
1081 /* We do not want to modifier the long long
1082 pointer here, so the safest (and less
1083 efficient) is to save all the other registers
1084 in the stack. XXX: totally inefficient. */
1085 #if 0
1086 save_regs(1);
1087 #else
1088 /* lvalue_save: save only if used further down the stack */
1089 save_reg_upstack(vtop->r, 1);
1090 #endif
1091 /* load from memory */
1092 vtop->type.t = load_type;
1093 load(r, vtop);
1094 vdup();
1095 vtop[-1].r = r; /* save register value */
1096 /* increment pointer to get second word */
1097 vtop->type.t = addr_type;
1098 gaddrof();
1099 vpushi(load_size);
1100 gen_op('+');
1101 vtop->r |= VT_LVAL;
1102 vtop->type.t = load_type;
1103 } else {
1104 /* move registers */
1105 load(r, vtop);
1106 vdup();
1107 vtop[-1].r = r; /* save register value */
1108 vtop->r = vtop[-1].r2;
1110 /* Allocate second register. Here we rely on the fact that
1111 get_reg() tries first to free r2 of an SValue. */
1112 r2 = get_reg(rc2);
1113 load(r2, vtop);
1114 vpop();
1115 /* write second register */
1116 vtop->r2 = r2;
1117 vtop->type.t = original_type;
1118 } else if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
1119 int t1, t;
1120 /* lvalue of scalar type : need to use lvalue type
1121 because of possible cast */
1122 t = vtop->type.t;
1123 t1 = t;
1124 /* compute memory access type */
1125 if (vtop->r & VT_REF)
1126 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1127 t = VT_PTR;
1128 #else
1129 t = VT_INT;
1130 #endif
1131 else if (vtop->r & VT_LVAL_BYTE)
1132 t = VT_BYTE;
1133 else if (vtop->r & VT_LVAL_SHORT)
1134 t = VT_SHORT;
1135 if (vtop->r & VT_LVAL_UNSIGNED)
1136 t |= VT_UNSIGNED;
1137 vtop->type.t = t;
1138 load(r, vtop);
1139 /* restore wanted type */
1140 vtop->type.t = t1;
1141 } else {
1142 /* one register type load */
1143 load(r, vtop);
1146 vtop->r = r;
1147 #ifdef TCC_TARGET_C67
1148 /* uses register pairs for doubles */
1149 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
1150 vtop->r2 = r+1;
1151 #endif
1153 return r;
1156 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
1157 ST_FUNC void gv2(int rc1, int rc2)
1159 int v;
1161 /* generate more generic register first. But VT_JMP or VT_CMP
1162 values must be generated first in all cases to avoid possible
1163 reload errors */
1164 v = vtop[0].r & VT_VALMASK;
1165 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
1166 vswap();
1167 gv(rc1);
1168 vswap();
1169 gv(rc2);
1170 /* test if reload is needed for first register */
1171 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
1172 vswap();
1173 gv(rc1);
1174 vswap();
1176 } else {
1177 gv(rc2);
1178 vswap();
1179 gv(rc1);
1180 vswap();
1181 /* test if reload is needed for first register */
1182 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
1183 gv(rc2);
1188 #ifndef TCC_TARGET_ARM64
1189 /* wrapper around RC_FRET to return a register by type */
1190 static int rc_fret(int t)
1192 #ifdef TCC_TARGET_X86_64
1193 if (t == VT_LDOUBLE) {
1194 return RC_ST0;
1196 #endif
1197 return RC_FRET;
1199 #endif
1201 /* wrapper around REG_FRET to return a register by type */
1202 static int reg_fret(int t)
1204 #ifdef TCC_TARGET_X86_64
1205 if (t == VT_LDOUBLE) {
1206 return TREG_ST0;
1208 #endif
1209 return REG_FRET;
1212 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
1213 /* expand 64bit on stack in two ints */
1214 static void lexpand(void)
1216 int u, v;
1217 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
1218 v = vtop->r & (VT_VALMASK | VT_LVAL);
1219 if (v == VT_CONST) {
1220 vdup();
1221 vtop[0].c.i >>= 32;
1222 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
1223 vdup();
1224 vtop[0].c.i += 4;
1225 } else {
1226 gv(RC_INT);
1227 vdup();
1228 vtop[0].r = vtop[-1].r2;
1229 vtop[0].r2 = vtop[-1].r2 = VT_CONST;
1231 vtop[0].type.t = vtop[-1].type.t = VT_INT | u;
1233 #endif
1235 #ifdef TCC_TARGET_ARM
1236 /* expand long long on stack */
1237 ST_FUNC void lexpand_nr(void)
1239 int u,v;
1241 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
1242 vdup();
1243 vtop->r2 = VT_CONST;
1244 vtop->type.t = VT_INT | u;
1245 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
1246 if (v == VT_CONST) {
1247 vtop[-1].c.i = vtop->c.i;
1248 vtop->c.i = vtop->c.i >> 32;
1249 vtop->r = VT_CONST;
1250 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
1251 vtop->c.i += 4;
1252 vtop->r = vtop[-1].r;
1253 } else if (v > VT_CONST) {
1254 vtop--;
1255 lexpand();
1256 } else
1257 vtop->r = vtop[-1].r2;
1258 vtop[-1].r2 = VT_CONST;
1259 vtop[-1].type.t = VT_INT | u;
1261 #endif
1263 #if !defined(TCC_TARGET_X86_64) && !defined(TCC_TARGET_ARM64)
1264 /* build a long long from two ints */
1265 static void lbuild(int t)
1267 gv2(RC_INT, RC_INT);
1268 vtop[-1].r2 = vtop[0].r;
1269 vtop[-1].type.t = t;
1270 vpop();
1272 #endif
1274 /* rotate n first stack elements to the bottom
1275 I1 ... In -> I2 ... In I1 [top is right]
1277 ST_FUNC void vrotb(int n)
1279 int i;
1280 SValue tmp;
1282 tmp = vtop[-n + 1];
1283 for(i=-n+1;i!=0;i++)
1284 vtop[i] = vtop[i+1];
1285 vtop[0] = tmp;
1288 /* rotate the n elements before entry e towards the top
1289 I1 ... In ... -> In I1 ... I(n-1) ... [top is right]
1291 ST_FUNC void vrote(SValue *e, int n)
1293 int i;
1294 SValue tmp;
1296 tmp = *e;
1297 for(i = 0;i < n - 1; i++)
1298 e[-i] = e[-i - 1];
1299 e[-n + 1] = tmp;
1302 /* rotate n first stack elements to the top
1303 I1 ... In -> In I1 ... I(n-1) [top is right]
1305 ST_FUNC void vrott(int n)
1307 vrote(vtop, n);
1310 /* pop stack value */
1311 ST_FUNC void vpop(void)
1313 int v;
1314 v = vtop->r & VT_VALMASK;
1315 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1316 /* for x86, we need to pop the FP stack */
1317 if (v == TREG_ST0 && !nocode_wanted) {
1318 o(0xd8dd); /* fstp %st(0) */
1319 } else
1320 #endif
1321 if (v == VT_JMP || v == VT_JMPI) {
1322 /* need to put correct jump if && or || without test */
1323 gsym(vtop->c.i);
1325 vtop--;
1328 /* convert stack entry to register and duplicate its value in another
1329 register */
1330 static void gv_dup(void)
1332 int rc, t, r, r1;
1333 SValue sv;
1335 t = vtop->type.t;
1336 #if !defined(TCC_TARGET_X86_64) && !defined(TCC_TARGET_ARM64)
1337 if ((t & VT_BTYPE) == VT_LLONG) {
1338 lexpand();
1339 gv_dup();
1340 vswap();
1341 vrotb(3);
1342 gv_dup();
1343 vrotb(4);
1344 /* stack: H L L1 H1 */
1345 lbuild(t);
1346 vrotb(3);
1347 vrotb(3);
1348 vswap();
1349 lbuild(t);
1350 vswap();
1351 } else
1352 #endif
1354 /* duplicate value */
1355 rc = RC_INT;
1356 sv.type.t = VT_INT;
1357 if (is_float(t)) {
1358 rc = RC_FLOAT;
1359 #ifdef TCC_TARGET_X86_64
1360 if ((t & VT_BTYPE) == VT_LDOUBLE) {
1361 rc = RC_ST0;
1363 #endif
1364 sv.type.t = t;
1366 r = gv(rc);
1367 r1 = get_reg(rc);
1368 sv.r = r;
1369 sv.c.i = 0;
1370 load(r1, &sv); /* move r to r1 */
1371 vdup();
1372 /* duplicates value */
1373 if (r != r1)
1374 vtop->r = r1;
1378 /* Generate value test
1380 * Generate a test for any value (jump, comparison and integers) */
1381 ST_FUNC int gvtst(int inv, int t)
1383 int v = vtop->r & VT_VALMASK;
1384 if (v != VT_CMP && v != VT_JMP && v != VT_JMPI) {
1385 vpushi(0);
1386 gen_op(TOK_NE);
1388 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1389 /* constant jmp optimization */
1390 if ((vtop->c.i != 0) != inv)
1391 t = gjmp(t);
1392 vtop--;
1393 return t;
1395 return gtst(inv, t);
1398 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
1399 /* generate CPU independent (unsigned) long long operations */
1400 static void gen_opl(int op)
1402 int t, a, b, op1, c, i;
1403 int func;
1404 unsigned short reg_iret = REG_IRET;
1405 unsigned short reg_lret = REG_LRET;
1406 SValue tmp;
1408 switch(op) {
1409 case '/':
1410 case TOK_PDIV:
1411 func = TOK___divdi3;
1412 goto gen_func;
1413 case TOK_UDIV:
1414 func = TOK___udivdi3;
1415 goto gen_func;
1416 case '%':
1417 func = TOK___moddi3;
1418 goto gen_mod_func;
1419 case TOK_UMOD:
1420 func = TOK___umoddi3;
1421 gen_mod_func:
1422 #ifdef TCC_ARM_EABI
1423 reg_iret = TREG_R2;
1424 reg_lret = TREG_R3;
1425 #endif
1426 gen_func:
1427 /* call generic long long function */
1428 vpush_global_sym(&func_old_type, func);
1429 vrott(3);
1430 gfunc_call(2);
1431 vpushi(0);
1432 vtop->r = reg_iret;
1433 vtop->r2 = reg_lret;
1434 break;
1435 case '^':
1436 case '&':
1437 case '|':
1438 case '*':
1439 case '+':
1440 case '-':
1441 //pv("gen_opl A",0,2);
1442 t = vtop->type.t;
1443 vswap();
1444 lexpand();
1445 vrotb(3);
1446 lexpand();
1447 /* stack: L1 H1 L2 H2 */
1448 tmp = vtop[0];
1449 vtop[0] = vtop[-3];
1450 vtop[-3] = tmp;
1451 tmp = vtop[-2];
1452 vtop[-2] = vtop[-3];
1453 vtop[-3] = tmp;
1454 vswap();
1455 /* stack: H1 H2 L1 L2 */
1456 //pv("gen_opl B",0,4);
1457 if (op == '*') {
1458 vpushv(vtop - 1);
1459 vpushv(vtop - 1);
1460 gen_op(TOK_UMULL);
1461 lexpand();
1462 /* stack: H1 H2 L1 L2 ML MH */
1463 for(i=0;i<4;i++)
1464 vrotb(6);
1465 /* stack: ML MH H1 H2 L1 L2 */
1466 tmp = vtop[0];
1467 vtop[0] = vtop[-2];
1468 vtop[-2] = tmp;
1469 /* stack: ML MH H1 L2 H2 L1 */
1470 gen_op('*');
1471 vrotb(3);
1472 vrotb(3);
1473 gen_op('*');
1474 /* stack: ML MH M1 M2 */
1475 gen_op('+');
1476 gen_op('+');
1477 } else if (op == '+' || op == '-') {
1478 /* XXX: add non carry method too (for MIPS or alpha) */
1479 if (op == '+')
1480 op1 = TOK_ADDC1;
1481 else
1482 op1 = TOK_SUBC1;
1483 gen_op(op1);
1484 /* stack: H1 H2 (L1 op L2) */
1485 vrotb(3);
1486 vrotb(3);
1487 gen_op(op1 + 1); /* TOK_xxxC2 */
1488 } else {
1489 gen_op(op);
1490 /* stack: H1 H2 (L1 op L2) */
1491 vrotb(3);
1492 vrotb(3);
1493 /* stack: (L1 op L2) H1 H2 */
1494 gen_op(op);
1495 /* stack: (L1 op L2) (H1 op H2) */
1497 /* stack: L H */
1498 lbuild(t);
1499 break;
1500 case TOK_SAR:
1501 case TOK_SHR:
1502 case TOK_SHL:
1503 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1504 t = vtop[-1].type.t;
1505 vswap();
1506 lexpand();
1507 vrotb(3);
1508 /* stack: L H shift */
1509 c = (int)vtop->c.i;
1510 /* constant: simpler */
1511 /* NOTE: all comments are for SHL. the other cases are
1512 done by swaping words */
1513 vpop();
1514 if (op != TOK_SHL)
1515 vswap();
1516 if (c >= 32) {
1517 /* stack: L H */
1518 vpop();
1519 if (c > 32) {
1520 vpushi(c - 32);
1521 gen_op(op);
1523 if (op != TOK_SAR) {
1524 vpushi(0);
1525 } else {
1526 gv_dup();
1527 vpushi(31);
1528 gen_op(TOK_SAR);
1530 vswap();
1531 } else {
1532 vswap();
1533 gv_dup();
1534 /* stack: H L L */
1535 vpushi(c);
1536 gen_op(op);
1537 vswap();
1538 vpushi(32 - c);
1539 if (op == TOK_SHL)
1540 gen_op(TOK_SHR);
1541 else
1542 gen_op(TOK_SHL);
1543 vrotb(3);
1544 /* stack: L L H */
1545 vpushi(c);
1546 if (op == TOK_SHL)
1547 gen_op(TOK_SHL);
1548 else
1549 gen_op(TOK_SHR);
1550 gen_op('|');
1552 if (op != TOK_SHL)
1553 vswap();
1554 lbuild(t);
1555 } else {
1556 /* XXX: should provide a faster fallback on x86 ? */
1557 switch(op) {
1558 case TOK_SAR:
1559 func = TOK___ashrdi3;
1560 goto gen_func;
1561 case TOK_SHR:
1562 func = TOK___lshrdi3;
1563 goto gen_func;
1564 case TOK_SHL:
1565 func = TOK___ashldi3;
1566 goto gen_func;
1569 break;
1570 default:
1571 /* compare operations */
1572 t = vtop->type.t;
1573 vswap();
1574 lexpand();
1575 vrotb(3);
1576 lexpand();
1577 /* stack: L1 H1 L2 H2 */
1578 tmp = vtop[-1];
1579 vtop[-1] = vtop[-2];
1580 vtop[-2] = tmp;
1581 /* stack: L1 L2 H1 H2 */
1582 /* compare high */
1583 op1 = op;
1584 /* when values are equal, we need to compare low words. since
1585 the jump is inverted, we invert the test too. */
1586 if (op1 == TOK_LT)
1587 op1 = TOK_LE;
1588 else if (op1 == TOK_GT)
1589 op1 = TOK_GE;
1590 else if (op1 == TOK_ULT)
1591 op1 = TOK_ULE;
1592 else if (op1 == TOK_UGT)
1593 op1 = TOK_UGE;
1594 a = 0;
1595 b = 0;
1596 gen_op(op1);
1597 if (op1 != TOK_NE) {
1598 a = gvtst(1, 0);
1600 if (op != TOK_EQ) {
1601 /* generate non equal test */
1602 /* XXX: NOT PORTABLE yet */
1603 if (a == 0) {
1604 b = gvtst(0, 0);
1605 } else {
1606 #if defined(TCC_TARGET_I386)
1607 b = psym(0x850f, 0);
1608 #elif defined(TCC_TARGET_ARM)
1609 b = ind;
1610 o(0x1A000000 | encbranch(ind, 0, 1));
1611 #elif defined(TCC_TARGET_C67) || defined(TCC_TARGET_ARM64)
1612 tcc_error("not implemented");
1613 #else
1614 #error not supported
1615 #endif
1618 /* compare low. Always unsigned */
1619 op1 = op;
1620 if (op1 == TOK_LT)
1621 op1 = TOK_ULT;
1622 else if (op1 == TOK_LE)
1623 op1 = TOK_ULE;
1624 else if (op1 == TOK_GT)
1625 op1 = TOK_UGT;
1626 else if (op1 == TOK_GE)
1627 op1 = TOK_UGE;
1628 gen_op(op1);
1629 a = gvtst(1, a);
1630 gsym(b);
1631 vseti(VT_JMPI, a);
1632 break;
1635 #endif
1637 static uint64_t gen_opic_sdiv(uint64_t a, uint64_t b)
1639 uint64_t x = (a >> 63 ? -a : a) / (b >> 63 ? -b : b);
1640 return (a ^ b) >> 63 ? -x : x;
1643 static int gen_opic_lt(uint64_t a, uint64_t b)
1645 return (a ^ (uint64_t)1 << 63) < (b ^ (uint64_t)1 << 63);
1648 /* handle integer constant optimizations and various machine
1649 independent opt */
1650 static void gen_opic(int op)
1652 SValue *v1 = vtop - 1;
1653 SValue *v2 = vtop;
1654 int t1 = v1->type.t & VT_BTYPE;
1655 int t2 = v2->type.t & VT_BTYPE;
1656 int c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1657 int c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1658 uint64_t l1 = c1 ? v1->c.i : 0;
1659 uint64_t l2 = c2 ? v2->c.i : 0;
1660 int shm = (t1 == VT_LLONG) ? 63 : 31;
1662 if (t1 != VT_LLONG)
1663 l1 = ((uint32_t)l1 |
1664 (v1->type.t & VT_UNSIGNED ? 0 : -(l1 & 0x80000000)));
1665 if (t2 != VT_LLONG)
1666 l2 = ((uint32_t)l2 |
1667 (v2->type.t & VT_UNSIGNED ? 0 : -(l2 & 0x80000000)));
1669 if (c1 && c2) {
1670 switch(op) {
1671 case '+': l1 += l2; break;
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;
1678 case TOK_PDIV:
1679 case '/':
1680 case '%':
1681 case TOK_UDIV:
1682 case TOK_UMOD:
1683 /* if division by zero, generate explicit division */
1684 if (l2 == 0) {
1685 if (const_wanted)
1686 tcc_error("division by zero in constant");
1687 goto general_case;
1689 switch(op) {
1690 default: l1 = gen_opic_sdiv(l1, l2); break;
1691 case '%': l1 = l1 - l2 * gen_opic_sdiv(l1, l2); break;
1692 case TOK_UDIV: l1 = l1 / l2; break;
1693 case TOK_UMOD: l1 = l1 % l2; break;
1695 break;
1696 case TOK_SHL: l1 <<= (l2 & shm); break;
1697 case TOK_SHR: l1 >>= (l2 & shm); break;
1698 case TOK_SAR:
1699 l1 = (l1 >> 63) ? ~(~l1 >> (l2 & shm)) : l1 >> (l2 & shm);
1700 break;
1701 /* tests */
1702 case TOK_ULT: l1 = l1 < l2; break;
1703 case TOK_UGE: l1 = l1 >= l2; break;
1704 case TOK_EQ: l1 = l1 == l2; break;
1705 case TOK_NE: l1 = l1 != l2; break;
1706 case TOK_ULE: l1 = l1 <= l2; break;
1707 case TOK_UGT: l1 = l1 > l2; break;
1708 case TOK_LT: l1 = gen_opic_lt(l1, l2); break;
1709 case TOK_GE: l1 = !gen_opic_lt(l1, l2); break;
1710 case TOK_LE: l1 = !gen_opic_lt(l2, l1); break;
1711 case TOK_GT: l1 = gen_opic_lt(l2, l1); break;
1712 /* logical */
1713 case TOK_LAND: l1 = l1 && l2; break;
1714 case TOK_LOR: l1 = l1 || l2; break;
1715 default:
1716 goto general_case;
1718 v1->c.i = l1;
1719 vtop--;
1720 } else {
1721 /* if commutative ops, put c2 as constant */
1722 if (c1 && (op == '+' || op == '&' || op == '^' ||
1723 op == '|' || op == '*')) {
1724 vswap();
1725 c2 = c1; //c = c1, c1 = c2, c2 = c;
1726 l2 = l1; //l = l1, l1 = l2, l2 = l;
1728 if (!const_wanted &&
1729 c1 && ((l1 == 0 &&
1730 (op == TOK_SHL || op == TOK_SHR || op == TOK_SAR)) ||
1731 (l1 == -1 && op == TOK_SAR))) {
1732 /* treat (0 << x), (0 >> x) and (-1 >> x) as constant */
1733 vtop--;
1734 } else if (!const_wanted &&
1735 c2 && ((l2 == 0 && (op == '&' || op == '*')) ||
1736 (l2 == -1 && op == '|') ||
1737 (l2 == 0xffffffff && t2 != VT_LLONG && op == '|') ||
1738 (l2 == 1 && (op == '%' || op == TOK_UMOD)))) {
1739 /* treat (x & 0), (x * 0), (x | -1) and (x % 1) as constant */
1740 if (l2 == 1)
1741 vtop->c.i = 0;
1742 vswap();
1743 vtop--;
1744 } else if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
1745 op == TOK_PDIV) &&
1746 l2 == 1) ||
1747 ((op == '+' || op == '-' || op == '|' || op == '^' ||
1748 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
1749 l2 == 0) ||
1750 (op == '&' &&
1751 l2 == -1))) {
1752 /* filter out NOP operations like x*1, x-0, x&-1... */
1753 vtop--;
1754 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
1755 /* try to use shifts instead of muls or divs */
1756 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
1757 int n = -1;
1758 while (l2) {
1759 l2 >>= 1;
1760 n++;
1762 vtop->c.i = n;
1763 if (op == '*')
1764 op = TOK_SHL;
1765 else if (op == TOK_PDIV)
1766 op = TOK_SAR;
1767 else
1768 op = TOK_SHR;
1770 goto general_case;
1771 } else if (c2 && (op == '+' || op == '-') &&
1772 (((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM))
1773 || (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
1774 /* symbol + constant case */
1775 if (op == '-')
1776 l2 = -l2;
1777 vtop--;
1778 vtop->c.i += l2;
1779 } else {
1780 general_case:
1781 if (!nocode_wanted) {
1782 /* call low level op generator */
1783 if (t1 == VT_LLONG || t2 == VT_LLONG ||
1784 (PTR_SIZE == 8 && (t1 == VT_PTR || t2 == VT_PTR)))
1785 gen_opl(op);
1786 else
1787 gen_opi(op);
1788 } else {
1789 vtop--;
1795 /* generate a floating point operation with constant propagation */
1796 static void gen_opif(int op)
1798 int c1, c2;
1799 SValue *v1, *v2;
1800 long double f1, f2;
1802 v1 = vtop - 1;
1803 v2 = vtop;
1804 /* currently, we cannot do computations with forward symbols */
1805 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1806 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1807 if (c1 && c2) {
1808 if (v1->type.t == VT_FLOAT) {
1809 f1 = v1->c.f;
1810 f2 = v2->c.f;
1811 } else if (v1->type.t == VT_DOUBLE) {
1812 f1 = v1->c.d;
1813 f2 = v2->c.d;
1814 } else {
1815 f1 = v1->c.ld;
1816 f2 = v2->c.ld;
1819 /* NOTE: we only do constant propagation if finite number (not
1820 NaN or infinity) (ANSI spec) */
1821 if (!ieee_finite(f1) || !ieee_finite(f2))
1822 goto general_case;
1824 switch(op) {
1825 case '+': f1 += f2; break;
1826 case '-': f1 -= f2; break;
1827 case '*': f1 *= f2; break;
1828 case '/':
1829 if (f2 == 0.0) {
1830 if (const_wanted)
1831 tcc_error("division by zero in constant");
1832 goto general_case;
1834 f1 /= f2;
1835 break;
1836 /* XXX: also handles tests ? */
1837 default:
1838 goto general_case;
1840 /* XXX: overflow test ? */
1841 if (v1->type.t == VT_FLOAT) {
1842 v1->c.f = f1;
1843 } else if (v1->type.t == VT_DOUBLE) {
1844 v1->c.d = f1;
1845 } else {
1846 v1->c.ld = f1;
1848 vtop--;
1849 } else {
1850 general_case:
1851 if (!nocode_wanted) {
1852 gen_opf(op);
1853 } else {
1854 vtop--;
1859 static int pointed_size(CType *type)
1861 int align;
1862 return type_size(pointed_type(type), &align);
1865 static void vla_runtime_pointed_size(CType *type)
1867 int align;
1868 vla_runtime_type_size(pointed_type(type), &align);
1871 static inline int is_null_pointer(SValue *p)
1873 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
1874 return 0;
1875 return ((p->type.t & VT_BTYPE) == VT_INT && (uint32_t)p->c.i == 0) ||
1876 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.i == 0) ||
1877 ((p->type.t & VT_BTYPE) == VT_PTR &&
1878 (PTR_SIZE == 4 ? (uint32_t)p->c.i == 0 : p->c.i == 0));
1881 static inline int is_integer_btype(int bt)
1883 return (bt == VT_BYTE || bt == VT_SHORT ||
1884 bt == VT_INT || bt == VT_LLONG);
1887 /* check types for comparison or subtraction of pointers */
1888 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
1890 CType *type1, *type2, tmp_type1, tmp_type2;
1891 int bt1, bt2;
1893 /* null pointers are accepted for all comparisons as gcc */
1894 if (is_null_pointer(p1) || is_null_pointer(p2))
1895 return;
1896 type1 = &p1->type;
1897 type2 = &p2->type;
1898 bt1 = type1->t & VT_BTYPE;
1899 bt2 = type2->t & VT_BTYPE;
1900 /* accept comparison between pointer and integer with a warning */
1901 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
1902 if (op != TOK_LOR && op != TOK_LAND )
1903 tcc_warning("comparison between pointer and integer");
1904 return;
1907 /* both must be pointers or implicit function pointers */
1908 if (bt1 == VT_PTR) {
1909 type1 = pointed_type(type1);
1910 } else if (bt1 != VT_FUNC)
1911 goto invalid_operands;
1913 if (bt2 == VT_PTR) {
1914 type2 = pointed_type(type2);
1915 } else if (bt2 != VT_FUNC) {
1916 invalid_operands:
1917 tcc_error("invalid operands to binary %s", get_tok_str(op, NULL));
1919 if ((type1->t & VT_BTYPE) == VT_VOID ||
1920 (type2->t & VT_BTYPE) == VT_VOID)
1921 return;
1922 tmp_type1 = *type1;
1923 tmp_type2 = *type2;
1924 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1925 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1926 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
1927 /* gcc-like error if '-' is used */
1928 if (op == '-')
1929 goto invalid_operands;
1930 else
1931 tcc_warning("comparison of distinct pointer types lacks a cast");
1935 /* generic gen_op: handles types problems */
1936 ST_FUNC void gen_op(int op)
1938 int u, t1, t2, bt1, bt2, t;
1939 CType type1;
1941 redo:
1942 t1 = vtop[-1].type.t;
1943 t2 = vtop[0].type.t;
1944 bt1 = t1 & VT_BTYPE;
1945 bt2 = t2 & VT_BTYPE;
1947 if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
1948 tcc_error("operation on a struct");
1949 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
1950 if (bt2 == VT_FUNC) {
1951 mk_pointer(&vtop->type);
1952 gaddrof();
1954 if (bt1 == VT_FUNC) {
1955 vswap();
1956 mk_pointer(&vtop->type);
1957 gaddrof();
1958 vswap();
1960 goto redo;
1961 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
1962 /* at least one operand is a pointer */
1963 /* relationnal op: must be both pointers */
1964 if (op >= TOK_ULT && op <= TOK_LOR) {
1965 check_comparison_pointer_types(vtop - 1, vtop, op);
1966 /* pointers are handled are unsigned */
1967 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1968 t = VT_LLONG | VT_UNSIGNED;
1969 #else
1970 t = VT_INT | VT_UNSIGNED;
1971 #endif
1972 goto std_op;
1974 /* if both pointers, then it must be the '-' op */
1975 if (bt1 == VT_PTR && bt2 == VT_PTR) {
1976 if (op != '-')
1977 tcc_error("cannot use pointers here");
1978 check_comparison_pointer_types(vtop - 1, vtop, op);
1979 /* XXX: check that types are compatible */
1980 if (vtop[-1].type.t & VT_VLA) {
1981 vla_runtime_pointed_size(&vtop[-1].type);
1982 } else {
1983 vpushi(pointed_size(&vtop[-1].type));
1985 vrott(3);
1986 gen_opic(op);
1987 /* set to integer type */
1988 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1989 vtop->type.t = VT_LLONG;
1990 #else
1991 vtop->type.t = VT_INT;
1992 #endif
1993 vswap();
1994 gen_op(TOK_PDIV);
1995 } else {
1996 /* exactly one pointer : must be '+' or '-'. */
1997 if (op != '-' && op != '+')
1998 tcc_error("cannot use pointers here");
1999 /* Put pointer as first operand */
2000 if (bt2 == VT_PTR) {
2001 vswap();
2002 swap(&t1, &t2);
2004 #if PTR_SIZE == 4
2005 if ((vtop[0].type.t & VT_BTYPE) == VT_LLONG)
2006 /* XXX: truncate here because gen_opl can't handle ptr + long long */
2007 gen_cast(&int_type);
2008 #endif
2009 type1 = vtop[-1].type;
2010 type1.t &= ~VT_ARRAY;
2011 if (vtop[-1].type.t & VT_VLA)
2012 vla_runtime_pointed_size(&vtop[-1].type);
2013 else {
2014 u = pointed_size(&vtop[-1].type);
2015 if (u < 0)
2016 tcc_error("unknown array element size");
2017 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2018 vpushll(u);
2019 #else
2020 /* XXX: cast to int ? (long long case) */
2021 vpushi(u);
2022 #endif
2024 gen_op('*');
2025 #if 0
2026 /* #ifdef CONFIG_TCC_BCHECK
2027 The main reason to removing this code:
2028 #include <stdio.h>
2029 int main ()
2031 int v[10];
2032 int i = 10;
2033 int j = 9;
2034 fprintf(stderr, "v+i-j = %p\n", v+i-j);
2035 fprintf(stderr, "v+(i-j) = %p\n", v+(i-j));
2037 When this code is on. then the output looks like
2038 v+i-j = 0xfffffffe
2039 v+(i-j) = 0xbff84000
2041 /* if evaluating constant expression, no code should be
2042 generated, so no bound check */
2043 if (tcc_state->do_bounds_check && !const_wanted) {
2044 /* if bounded pointers, we generate a special code to
2045 test bounds */
2046 if (op == '-') {
2047 vpushi(0);
2048 vswap();
2049 gen_op('-');
2051 gen_bounded_ptr_add();
2052 } else
2053 #endif
2055 gen_opic(op);
2057 /* put again type if gen_opic() swaped operands */
2058 vtop->type = type1;
2060 } else if (is_float(bt1) || is_float(bt2)) {
2061 /* compute bigger type and do implicit casts */
2062 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
2063 t = VT_LDOUBLE;
2064 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
2065 t = VT_DOUBLE;
2066 } else {
2067 t = VT_FLOAT;
2069 /* floats can only be used for a few operations */
2070 if (op != '+' && op != '-' && op != '*' && op != '/' &&
2071 (op < TOK_ULT || op > TOK_GT))
2072 tcc_error("invalid operands for binary operation");
2073 goto std_op;
2074 } else if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL) {
2075 t = bt1 == VT_LLONG ? VT_LLONG : VT_INT;
2076 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (t | VT_UNSIGNED))
2077 t |= VT_UNSIGNED;
2078 goto std_op;
2079 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
2080 /* cast to biggest op */
2081 t = VT_LLONG;
2082 /* convert to unsigned if it does not fit in a long long */
2083 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
2084 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
2085 t |= VT_UNSIGNED;
2086 goto std_op;
2087 } else {
2088 /* integer operations */
2089 t = VT_INT;
2090 /* convert to unsigned if it does not fit in an integer */
2091 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
2092 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
2093 t |= VT_UNSIGNED;
2094 std_op:
2095 /* XXX: currently, some unsigned operations are explicit, so
2096 we modify them here */
2097 if (t & VT_UNSIGNED) {
2098 if (op == TOK_SAR)
2099 op = TOK_SHR;
2100 else if (op == '/')
2101 op = TOK_UDIV;
2102 else if (op == '%')
2103 op = TOK_UMOD;
2104 else if (op == TOK_LT)
2105 op = TOK_ULT;
2106 else if (op == TOK_GT)
2107 op = TOK_UGT;
2108 else if (op == TOK_LE)
2109 op = TOK_ULE;
2110 else if (op == TOK_GE)
2111 op = TOK_UGE;
2113 vswap();
2114 type1.t = t;
2115 gen_cast(&type1);
2116 vswap();
2117 /* special case for shifts and long long: we keep the shift as
2118 an integer */
2119 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
2120 type1.t = VT_INT;
2121 gen_cast(&type1);
2122 if (is_float(t))
2123 gen_opif(op);
2124 else
2125 gen_opic(op);
2126 if (op >= TOK_ULT && op <= TOK_GT) {
2127 /* relationnal op: the result is an int */
2128 vtop->type.t = VT_INT;
2129 } else {
2130 vtop->type.t = t;
2133 // Make sure that we have converted to an rvalue:
2134 if (vtop->r & VT_LVAL && !nocode_wanted)
2135 gv(is_float(vtop->type.t & VT_BTYPE) ? RC_FLOAT : RC_INT);
2138 #ifndef TCC_TARGET_ARM
2139 /* generic itof for unsigned long long case */
2140 static void gen_cvt_itof1(int t)
2142 #ifdef TCC_TARGET_ARM64
2143 gen_cvt_itof(t);
2144 #else
2145 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
2146 (VT_LLONG | VT_UNSIGNED)) {
2148 if (t == VT_FLOAT)
2149 vpush_global_sym(&func_old_type, TOK___floatundisf);
2150 #if LDOUBLE_SIZE != 8
2151 else if (t == VT_LDOUBLE)
2152 vpush_global_sym(&func_old_type, TOK___floatundixf);
2153 #endif
2154 else
2155 vpush_global_sym(&func_old_type, TOK___floatundidf);
2156 vrott(2);
2157 gfunc_call(1);
2158 vpushi(0);
2159 vtop->r = reg_fret(t);
2160 } else {
2161 gen_cvt_itof(t);
2163 #endif
2165 #endif
2167 /* generic ftoi for unsigned long long case */
2168 static void gen_cvt_ftoi1(int t)
2170 #ifdef TCC_TARGET_ARM64
2171 gen_cvt_ftoi(t);
2172 #else
2173 int st;
2175 if (t == (VT_LLONG | VT_UNSIGNED)) {
2176 /* not handled natively */
2177 st = vtop->type.t & VT_BTYPE;
2178 if (st == VT_FLOAT)
2179 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
2180 #if LDOUBLE_SIZE != 8
2181 else if (st == VT_LDOUBLE)
2182 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
2183 #endif
2184 else
2185 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
2186 vrott(2);
2187 gfunc_call(1);
2188 vpushi(0);
2189 vtop->r = REG_IRET;
2190 vtop->r2 = REG_LRET;
2191 } else {
2192 gen_cvt_ftoi(t);
2194 #endif
2197 /* force char or short cast */
2198 static void force_charshort_cast(int t)
2200 int bits, dbt;
2201 dbt = t & VT_BTYPE;
2202 /* XXX: add optimization if lvalue : just change type and offset */
2203 if (dbt == VT_BYTE)
2204 bits = 8;
2205 else
2206 bits = 16;
2207 if (t & VT_UNSIGNED) {
2208 vpushi((1 << bits) - 1);
2209 gen_op('&');
2210 } else {
2211 if ((vtop->type.t & VT_BTYPE) == VT_LLONG)
2212 bits = 64 - bits;
2213 else
2214 bits = 32 - bits;
2215 vpushi(bits);
2216 gen_op(TOK_SHL);
2217 /* result must be signed or the SAR is converted to an SHL
2218 This was not the case when "t" was a signed short
2219 and the last value on the stack was an unsigned int */
2220 vtop->type.t &= ~VT_UNSIGNED;
2221 vpushi(bits);
2222 gen_op(TOK_SAR);
2226 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
2227 static void gen_cast(CType *type)
2229 int sbt, dbt, sf, df, c, p;
2231 /* special delayed cast for char/short */
2232 /* XXX: in some cases (multiple cascaded casts), it may still
2233 be incorrect */
2234 if (vtop->r & VT_MUSTCAST) {
2235 vtop->r &= ~VT_MUSTCAST;
2236 force_charshort_cast(vtop->type.t);
2239 /* bitfields first get cast to ints */
2240 if (vtop->type.t & VT_BITFIELD && !nocode_wanted) {
2241 gv(RC_INT);
2244 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
2245 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
2247 if (sbt != dbt) {
2248 sf = is_float(sbt);
2249 df = is_float(dbt);
2250 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
2251 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
2252 if (c) {
2253 /* constant case: we can do it now */
2254 /* XXX: in ISOC, cannot do it if error in convert */
2255 if (sbt == VT_FLOAT)
2256 vtop->c.ld = vtop->c.f;
2257 else if (sbt == VT_DOUBLE)
2258 vtop->c.ld = vtop->c.d;
2260 if (df) {
2261 if ((sbt & VT_BTYPE) == VT_LLONG) {
2262 if ((sbt & VT_UNSIGNED) || !(vtop->c.i >> 63))
2263 vtop->c.ld = vtop->c.i;
2264 else
2265 vtop->c.ld = -(long double)-vtop->c.i;
2266 } else if(!sf) {
2267 if ((sbt & VT_UNSIGNED) || !(vtop->c.i >> 31))
2268 vtop->c.ld = (uint32_t)vtop->c.i;
2269 else
2270 vtop->c.ld = -(long double)-(uint32_t)vtop->c.i;
2273 if (dbt == VT_FLOAT)
2274 vtop->c.f = (float)vtop->c.ld;
2275 else if (dbt == VT_DOUBLE)
2276 vtop->c.d = (double)vtop->c.ld;
2277 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
2278 vtop->c.i = vtop->c.ld;
2279 } else if (sf && dbt == VT_BOOL) {
2280 vtop->c.i = (vtop->c.ld != 0);
2281 } else {
2282 if(sf)
2283 vtop->c.i = vtop->c.ld;
2284 else if (sbt == (VT_LLONG|VT_UNSIGNED))
2286 else if (sbt & VT_UNSIGNED)
2287 vtop->c.i = (uint32_t)vtop->c.i;
2288 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2289 else if (sbt == VT_PTR)
2291 #endif
2292 else if (sbt != VT_LLONG)
2293 vtop->c.i = ((uint32_t)vtop->c.i |
2294 -(vtop->c.i & 0x80000000));
2296 if (dbt == (VT_LLONG|VT_UNSIGNED))
2298 else if (dbt == VT_BOOL)
2299 vtop->c.i = (vtop->c.i != 0);
2300 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2301 else if (dbt == VT_PTR)
2303 #endif
2304 else if (dbt != VT_LLONG) {
2305 uint32_t m = ((dbt & VT_BTYPE) == VT_BYTE ? 0xff :
2306 (dbt & VT_BTYPE) == VT_SHORT ? 0xffff :
2307 0xffffffff);
2308 vtop->c.i &= m;
2309 if (!(dbt & VT_UNSIGNED))
2310 vtop->c.i |= -(vtop->c.i & ((m >> 1) + 1));
2313 } else if (p && dbt == VT_BOOL) {
2314 vtop->r = VT_CONST;
2315 vtop->c.i = 1;
2316 } else if (!nocode_wanted) {
2317 /* non constant case: generate code */
2318 if (sf && df) {
2319 /* convert from fp to fp */
2320 gen_cvt_ftof(dbt);
2321 } else if (df) {
2322 /* convert int to fp */
2323 gen_cvt_itof1(dbt);
2324 } else if (sf) {
2325 /* convert fp to int */
2326 if (dbt == VT_BOOL) {
2327 vpushi(0);
2328 gen_op(TOK_NE);
2329 } else {
2330 /* we handle char/short/etc... with generic code */
2331 if (dbt != (VT_INT | VT_UNSIGNED) &&
2332 dbt != (VT_LLONG | VT_UNSIGNED) &&
2333 dbt != VT_LLONG)
2334 dbt = VT_INT;
2335 gen_cvt_ftoi1(dbt);
2336 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
2337 /* additional cast for char/short... */
2338 vtop->type.t = dbt;
2339 gen_cast(type);
2342 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
2343 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
2344 if ((sbt & VT_BTYPE) != VT_LLONG) {
2345 /* scalar to long long */
2346 /* machine independent conversion */
2347 gv(RC_INT);
2348 /* generate high word */
2349 if (sbt == (VT_INT | VT_UNSIGNED)) {
2350 vpushi(0);
2351 gv(RC_INT);
2352 } else {
2353 if (sbt == VT_PTR) {
2354 /* cast from pointer to int before we apply
2355 shift operation, which pointers don't support*/
2356 gen_cast(&int_type);
2358 gv_dup();
2359 vpushi(31);
2360 gen_op(TOK_SAR);
2362 /* patch second register */
2363 vtop[-1].r2 = vtop->r;
2364 vpop();
2366 #else
2367 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
2368 (dbt & VT_BTYPE) == VT_PTR ||
2369 (dbt & VT_BTYPE) == VT_FUNC) {
2370 if ((sbt & VT_BTYPE) != VT_LLONG &&
2371 (sbt & VT_BTYPE) != VT_PTR &&
2372 (sbt & VT_BTYPE) != VT_FUNC) {
2373 /* need to convert from 32bit to 64bit */
2374 gv(RC_INT);
2375 if (sbt != (VT_INT | VT_UNSIGNED)) {
2376 #if defined(TCC_TARGET_ARM64)
2377 gen_cvt_sxtw();
2378 #elif defined(TCC_TARGET_X86_64)
2379 int r = gv(RC_INT);
2380 /* x86_64 specific: movslq */
2381 o(0x6348);
2382 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
2383 #else
2384 #error
2385 #endif
2388 #endif
2389 } else if (dbt == VT_BOOL) {
2390 /* scalar to bool */
2391 vpushi(0);
2392 gen_op(TOK_NE);
2393 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
2394 (dbt & VT_BTYPE) == VT_SHORT) {
2395 if (sbt == VT_PTR) {
2396 vtop->type.t = VT_INT;
2397 tcc_warning("nonportable conversion from pointer to char/short");
2399 force_charshort_cast(dbt);
2400 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
2401 } else if ((dbt & VT_BTYPE) == VT_INT) {
2402 /* scalar to int */
2403 if ((sbt & VT_BTYPE) == VT_LLONG) {
2404 /* from long long: just take low order word */
2405 lexpand();
2406 vpop();
2408 /* if lvalue and single word type, nothing to do because
2409 the lvalue already contains the real type size (see
2410 VT_LVAL_xxx constants) */
2411 #endif
2414 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
2415 /* if we are casting between pointer types,
2416 we must update the VT_LVAL_xxx size */
2417 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
2418 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
2420 vtop->type = *type;
2423 /* return type size as known at compile time. Put alignment at 'a' */
2424 ST_FUNC int type_size(CType *type, int *a)
2426 Sym *s;
2427 int bt;
2429 bt = type->t & VT_BTYPE;
2430 if (bt == VT_STRUCT) {
2431 /* struct/union */
2432 s = type->ref;
2433 *a = s->r;
2434 return s->c;
2435 } else if (bt == VT_PTR) {
2436 if (type->t & VT_ARRAY) {
2437 int ts;
2439 s = type->ref;
2440 ts = type_size(&s->type, a);
2442 if (ts < 0 && s->c < 0)
2443 ts = -ts;
2445 return ts * s->c;
2446 } else {
2447 *a = PTR_SIZE;
2448 return PTR_SIZE;
2450 } else if (bt == VT_LDOUBLE) {
2451 *a = LDOUBLE_ALIGN;
2452 return LDOUBLE_SIZE;
2453 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
2454 #ifdef TCC_TARGET_I386
2455 #ifdef TCC_TARGET_PE
2456 *a = 8;
2457 #else
2458 *a = 4;
2459 #endif
2460 #elif defined(TCC_TARGET_ARM)
2461 #ifdef TCC_ARM_EABI
2462 *a = 8;
2463 #else
2464 *a = 4;
2465 #endif
2466 #else
2467 *a = 8;
2468 #endif
2469 return 8;
2470 } else if (bt == VT_INT || bt == VT_FLOAT) {
2471 *a = 4;
2472 return 4;
2473 } else if (bt == VT_SHORT) {
2474 *a = 2;
2475 return 2;
2476 } else if (bt == VT_QLONG || bt == VT_QFLOAT) {
2477 *a = 8;
2478 return 16;
2479 } else if (bt == VT_ENUM) {
2480 *a = 4;
2481 /* Enums might be incomplete, so don't just return '4' here. */
2482 return type->ref->c;
2483 } else {
2484 /* char, void, function, _Bool */
2485 *a = 1;
2486 return 1;
2490 /* push type size as known at runtime time on top of value stack. Put
2491 alignment at 'a' */
2492 ST_FUNC void vla_runtime_type_size(CType *type, int *a)
2494 if (type->t & VT_VLA) {
2495 type_size(&type->ref->type, a);
2496 vset(&int_type, VT_LOCAL|VT_LVAL, type->ref->c);
2497 } else {
2498 vpushi(type_size(type, a));
2502 static void vla_sp_restore(void) {
2503 if (vlas_in_scope) {
2504 gen_vla_sp_restore(vla_sp_loc);
2508 static void vla_sp_restore_root(void) {
2509 if (vlas_in_scope) {
2510 gen_vla_sp_restore(vla_sp_root_loc);
2514 /* return the pointed type of t */
2515 static inline CType *pointed_type(CType *type)
2517 return &type->ref->type;
2520 /* modify type so that its it is a pointer to type. */
2521 ST_FUNC void mk_pointer(CType *type)
2523 Sym *s;
2524 s = sym_push(SYM_FIELD, type, 0, -1);
2525 type->t = VT_PTR | (type->t & ~VT_TYPE);
2526 type->ref = s;
2529 /* compare function types. OLD functions match any new functions */
2530 static int is_compatible_func(CType *type1, CType *type2)
2532 Sym *s1, *s2;
2534 s1 = type1->ref;
2535 s2 = type2->ref;
2536 if (!is_compatible_types(&s1->type, &s2->type))
2537 return 0;
2538 /* check func_call */
2539 if (s1->a.func_call != s2->a.func_call)
2540 return 0;
2541 /* XXX: not complete */
2542 if (s1->c == FUNC_OLD || s2->c == FUNC_OLD)
2543 return 1;
2544 if (s1->c != s2->c)
2545 return 0;
2546 while (s1 != NULL) {
2547 if (s2 == NULL)
2548 return 0;
2549 if (!is_compatible_parameter_types(&s1->type, &s2->type))
2550 return 0;
2551 s1 = s1->next;
2552 s2 = s2->next;
2554 if (s2)
2555 return 0;
2556 return 1;
2559 /* return true if type1 and type2 are the same. If unqualified is
2560 true, qualifiers on the types are ignored.
2562 - enums are not checked as gcc __builtin_types_compatible_p ()
2564 static int compare_types(CType *type1, CType *type2, int unqualified)
2566 int bt1, t1, t2;
2568 t1 = type1->t & VT_TYPE;
2569 t2 = type2->t & VT_TYPE;
2570 if (unqualified) {
2571 /* strip qualifiers before comparing */
2572 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
2573 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
2575 /* Default Vs explicit signedness only matters for char */
2576 if ((t1 & VT_BTYPE) != VT_BYTE) {
2577 t1 &= ~VT_DEFSIGN;
2578 t2 &= ~VT_DEFSIGN;
2580 /* An enum is compatible with (unsigned) int. Ideally we would
2581 store the enums signedness in type->ref.a.<some_bit> and
2582 only accept unsigned enums with unsigned int and vice versa.
2583 But one of our callers (gen_assign_cast) always strips VT_UNSIGNED
2584 from pointer target types, so we can't add it here either. */
2585 if ((t1 & VT_BTYPE) == VT_ENUM) {
2586 t1 = VT_INT;
2587 if (type1->ref->a.unsigned_enum)
2588 t1 |= VT_UNSIGNED;
2590 if ((t2 & VT_BTYPE) == VT_ENUM) {
2591 t2 = VT_INT;
2592 if (type2->ref->a.unsigned_enum)
2593 t2 |= VT_UNSIGNED;
2595 /* XXX: bitfields ? */
2596 if (t1 != t2)
2597 return 0;
2598 /* test more complicated cases */
2599 bt1 = t1 & VT_BTYPE;
2600 if (bt1 == VT_PTR) {
2601 type1 = pointed_type(type1);
2602 type2 = pointed_type(type2);
2603 return is_compatible_types(type1, type2);
2604 } else if (bt1 == VT_STRUCT) {
2605 return (type1->ref == type2->ref);
2606 } else if (bt1 == VT_FUNC) {
2607 return is_compatible_func(type1, type2);
2608 } else {
2609 return 1;
2613 /* return true if type1 and type2 are exactly the same (including
2614 qualifiers).
2616 static int is_compatible_types(CType *type1, CType *type2)
2618 return compare_types(type1,type2,0);
2621 /* return true if type1 and type2 are the same (ignoring qualifiers).
2623 static int is_compatible_parameter_types(CType *type1, CType *type2)
2625 return compare_types(type1,type2,1);
2628 /* print a type. If 'varstr' is not NULL, then the variable is also
2629 printed in the type */
2630 /* XXX: union */
2631 /* XXX: add array and function pointers */
2632 static void type_to_str(char *buf, int buf_size,
2633 CType *type, const char *varstr)
2635 int bt, v, t;
2636 Sym *s, *sa;
2637 char buf1[256];
2638 const char *tstr;
2640 t = type->t & VT_TYPE;
2641 bt = t & VT_BTYPE;
2642 buf[0] = '\0';
2643 if (t & VT_CONSTANT)
2644 pstrcat(buf, buf_size, "const ");
2645 if (t & VT_VOLATILE)
2646 pstrcat(buf, buf_size, "volatile ");
2647 if ((t & (VT_DEFSIGN | VT_UNSIGNED)) == (VT_DEFSIGN | VT_UNSIGNED))
2648 pstrcat(buf, buf_size, "unsigned ");
2649 else if (t & VT_DEFSIGN)
2650 pstrcat(buf, buf_size, "signed ");
2651 switch(bt) {
2652 case VT_VOID:
2653 tstr = "void";
2654 goto add_tstr;
2655 case VT_BOOL:
2656 tstr = "_Bool";
2657 goto add_tstr;
2658 case VT_BYTE:
2659 tstr = "char";
2660 goto add_tstr;
2661 case VT_SHORT:
2662 tstr = "short";
2663 goto add_tstr;
2664 case VT_INT:
2665 tstr = "int";
2666 goto add_tstr;
2667 case VT_LONG:
2668 tstr = "long";
2669 goto add_tstr;
2670 case VT_LLONG:
2671 tstr = "long long";
2672 goto add_tstr;
2673 case VT_FLOAT:
2674 tstr = "float";
2675 goto add_tstr;
2676 case VT_DOUBLE:
2677 tstr = "double";
2678 goto add_tstr;
2679 case VT_LDOUBLE:
2680 tstr = "long double";
2681 add_tstr:
2682 pstrcat(buf, buf_size, tstr);
2683 break;
2684 case VT_ENUM:
2685 case VT_STRUCT:
2686 if (bt == VT_STRUCT)
2687 tstr = "struct ";
2688 else
2689 tstr = "enum ";
2690 pstrcat(buf, buf_size, tstr);
2691 v = type->ref->v & ~SYM_STRUCT;
2692 if (v >= SYM_FIRST_ANOM)
2693 pstrcat(buf, buf_size, "<anonymous>");
2694 else
2695 pstrcat(buf, buf_size, get_tok_str(v, NULL));
2696 break;
2697 case VT_FUNC:
2698 s = type->ref;
2699 type_to_str(buf, buf_size, &s->type, varstr);
2700 pstrcat(buf, buf_size, "(");
2701 sa = s->next;
2702 while (sa != NULL) {
2703 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
2704 pstrcat(buf, buf_size, buf1);
2705 sa = sa->next;
2706 if (sa)
2707 pstrcat(buf, buf_size, ", ");
2709 pstrcat(buf, buf_size, ")");
2710 goto no_var;
2711 case VT_PTR:
2712 s = type->ref;
2713 if (t & VT_ARRAY) {
2714 snprintf(buf1, sizeof(buf1), "%s[%ld]", varstr ? varstr : "", s->c);
2715 type_to_str(buf, buf_size, &s->type, buf1);
2716 goto no_var;
2718 pstrcpy(buf1, sizeof(buf1), "*");
2719 if (t & VT_CONSTANT)
2720 pstrcat(buf1, buf_size, "const ");
2721 if (t & VT_VOLATILE)
2722 pstrcat(buf1, buf_size, "volatile ");
2723 if (varstr)
2724 pstrcat(buf1, sizeof(buf1), varstr);
2725 type_to_str(buf, buf_size, &s->type, buf1);
2726 goto no_var;
2728 if (varstr) {
2729 pstrcat(buf, buf_size, " ");
2730 pstrcat(buf, buf_size, varstr);
2732 no_var: ;
2735 /* verify type compatibility to store vtop in 'dt' type, and generate
2736 casts if needed. */
2737 static void gen_assign_cast(CType *dt)
2739 CType *st, *type1, *type2, tmp_type1, tmp_type2;
2740 char buf1[256], buf2[256];
2741 int dbt, sbt;
2743 st = &vtop->type; /* source type */
2744 dbt = dt->t & VT_BTYPE;
2745 sbt = st->t & VT_BTYPE;
2746 if (sbt == VT_VOID || dbt == VT_VOID) {
2747 if (sbt == VT_VOID && dbt == VT_VOID)
2748 ; /*
2749 It is Ok if both are void
2750 A test program:
2751 void func1() {}
2752 void func2() {
2753 return func1();
2755 gcc accepts this program
2757 else
2758 tcc_error("cannot cast from/to void");
2760 if (dt->t & VT_CONSTANT)
2761 tcc_warning("assignment of read-only location");
2762 switch(dbt) {
2763 case VT_PTR:
2764 /* special cases for pointers */
2765 /* '0' can also be a pointer */
2766 if (is_null_pointer(vtop))
2767 goto type_ok;
2768 /* accept implicit pointer to integer cast with warning */
2769 if (is_integer_btype(sbt)) {
2770 tcc_warning("assignment makes pointer from integer without a cast");
2771 goto type_ok;
2773 type1 = pointed_type(dt);
2774 /* a function is implicitely a function pointer */
2775 if (sbt == VT_FUNC) {
2776 if ((type1->t & VT_BTYPE) != VT_VOID &&
2777 !is_compatible_types(pointed_type(dt), st))
2778 tcc_warning("assignment from incompatible pointer type");
2779 goto type_ok;
2781 if (sbt != VT_PTR)
2782 goto error;
2783 type2 = pointed_type(st);
2784 if ((type1->t & VT_BTYPE) == VT_VOID ||
2785 (type2->t & VT_BTYPE) == VT_VOID) {
2786 /* void * can match anything */
2787 } else {
2788 /* exact type match, except for qualifiers */
2789 tmp_type1 = *type1;
2790 tmp_type2 = *type2;
2791 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2792 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2793 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2794 /* Like GCC don't warn by default for merely changes
2795 in pointer target signedness. Do warn for different
2796 base types, though, in particular for unsigned enums
2797 and signed int targets. */
2798 if ((tmp_type1.t & (VT_DEFSIGN | VT_UNSIGNED)) !=
2799 (tmp_type2.t & (VT_DEFSIGN | VT_UNSIGNED)) &&
2800 (tmp_type1.t & VT_BTYPE) == (tmp_type2.t & VT_BTYPE))
2802 else
2803 tcc_warning("assignment from incompatible pointer type");
2806 /* check const and volatile */
2807 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
2808 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
2809 tcc_warning("assignment discards qualifiers from pointer target type");
2810 break;
2811 case VT_BYTE:
2812 case VT_SHORT:
2813 case VT_INT:
2814 case VT_LLONG:
2815 if (sbt == VT_PTR || sbt == VT_FUNC) {
2816 tcc_warning("assignment makes integer from pointer without a cast");
2817 } else if (sbt == VT_STRUCT) {
2818 goto case_VT_STRUCT;
2820 /* XXX: more tests */
2821 break;
2822 case VT_STRUCT:
2823 case_VT_STRUCT:
2824 tmp_type1 = *dt;
2825 tmp_type2 = *st;
2826 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2827 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2828 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2829 error:
2830 type_to_str(buf1, sizeof(buf1), st, NULL);
2831 type_to_str(buf2, sizeof(buf2), dt, NULL);
2832 tcc_error("cannot cast '%s' to '%s'", buf1, buf2);
2834 break;
2836 type_ok:
2837 gen_cast(dt);
2840 /* store vtop in lvalue pushed on stack */
2841 ST_FUNC void vstore(void)
2843 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
2845 ft = vtop[-1].type.t;
2846 sbt = vtop->type.t & VT_BTYPE;
2847 dbt = ft & VT_BTYPE;
2848 if ((((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
2849 (sbt == VT_INT && dbt == VT_SHORT))
2850 && !(vtop->type.t & VT_BITFIELD)) {
2851 /* optimize char/short casts */
2852 delayed_cast = VT_MUSTCAST;
2853 vtop->type.t = (ft & VT_TYPE & ~VT_BITFIELD &
2854 ((1 << VT_STRUCT_SHIFT) - 1));
2855 /* XXX: factorize */
2856 if (ft & VT_CONSTANT)
2857 tcc_warning("assignment of read-only location");
2858 } else {
2859 delayed_cast = 0;
2860 if (!(ft & VT_BITFIELD))
2861 gen_assign_cast(&vtop[-1].type);
2864 if (sbt == VT_STRUCT) {
2865 /* if structure, only generate pointer */
2866 /* structure assignment : generate memcpy */
2867 /* XXX: optimize if small size */
2868 if (!nocode_wanted) {
2869 size = type_size(&vtop->type, &align);
2871 /* destination */
2872 vswap();
2873 vtop->type.t = VT_PTR;
2874 gaddrof();
2876 /* address of memcpy() */
2877 #ifdef TCC_ARM_EABI
2878 if(!(align & 7))
2879 vpush_global_sym(&func_old_type, TOK_memcpy8);
2880 else if(!(align & 3))
2881 vpush_global_sym(&func_old_type, TOK_memcpy4);
2882 else
2883 #endif
2884 /* Use memmove, rather than memcpy, as dest and src may be same: */
2885 vpush_global_sym(&func_old_type, TOK_memmove);
2887 vswap();
2888 /* source */
2889 vpushv(vtop - 2);
2890 vtop->type.t = VT_PTR;
2891 gaddrof();
2892 /* type size */
2893 vpushi(size);
2894 gfunc_call(3);
2895 } else {
2896 vswap();
2897 vpop();
2899 /* leave source on stack */
2900 } else if (ft & VT_BITFIELD) {
2901 /* bitfield store handling */
2903 /* save lvalue as expression result (example: s.b = s.a = n;) */
2904 vdup(), vtop[-1] = vtop[-2];
2906 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
2907 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
2908 /* remove bit field info to avoid loops */
2909 vtop[-1].type.t = ft & ~VT_BITFIELD & ((1 << VT_STRUCT_SHIFT) - 1);
2911 if((ft & VT_BTYPE) == VT_BOOL) {
2912 gen_cast(&vtop[-1].type);
2913 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
2916 /* duplicate destination */
2917 vdup();
2918 vtop[-1] = vtop[-2];
2920 /* mask and shift source */
2921 if((ft & VT_BTYPE) != VT_BOOL) {
2922 if((ft & VT_BTYPE) == VT_LLONG) {
2923 vpushll((1ULL << bit_size) - 1ULL);
2924 } else {
2925 vpushi((1 << bit_size) - 1);
2927 gen_op('&');
2929 vpushi(bit_pos);
2930 gen_op(TOK_SHL);
2931 /* load destination, mask and or with source */
2932 vswap();
2933 if((ft & VT_BTYPE) == VT_LLONG) {
2934 vpushll(~(((1ULL << bit_size) - 1ULL) << bit_pos));
2935 } else {
2936 vpushi(~(((1 << bit_size) - 1) << bit_pos));
2938 gen_op('&');
2939 gen_op('|');
2940 /* store result */
2941 vstore();
2942 /* ... and discard */
2943 vpop();
2945 } else {
2946 if (!nocode_wanted) {
2947 #ifdef CONFIG_TCC_BCHECK
2948 /* bound check case */
2949 if (vtop[-1].r & VT_MUSTBOUND) {
2950 vswap();
2951 gbound();
2952 vswap();
2954 #endif
2955 rc = RC_INT;
2956 if (is_float(ft)) {
2957 rc = RC_FLOAT;
2958 #ifdef TCC_TARGET_X86_64
2959 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
2960 rc = RC_ST0;
2961 } else if ((ft & VT_BTYPE) == VT_QFLOAT) {
2962 rc = RC_FRET;
2964 #endif
2966 r = gv(rc); /* generate value */
2967 /* if lvalue was saved on stack, must read it */
2968 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
2969 SValue sv;
2970 t = get_reg(RC_INT);
2971 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2972 sv.type.t = VT_PTR;
2973 #else
2974 sv.type.t = VT_INT;
2975 #endif
2976 sv.r = VT_LOCAL | VT_LVAL;
2977 sv.c.i = vtop[-1].c.i;
2978 load(t, &sv);
2979 vtop[-1].r = t | VT_LVAL;
2981 /* two word case handling : store second register at word + 4 (or +8 for x86-64) */
2982 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2983 if (((ft & VT_BTYPE) == VT_QLONG) || ((ft & VT_BTYPE) == VT_QFLOAT)) {
2984 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
2985 #else
2986 if ((ft & VT_BTYPE) == VT_LLONG) {
2987 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
2988 #endif
2989 vtop[-1].type.t = load_type;
2990 store(r, vtop - 1);
2991 vswap();
2992 /* convert to int to increment easily */
2993 vtop->type.t = addr_type;
2994 gaddrof();
2995 vpushi(load_size);
2996 gen_op('+');
2997 vtop->r |= VT_LVAL;
2998 vswap();
2999 vtop[-1].type.t = load_type;
3000 /* XXX: it works because r2 is spilled last ! */
3001 store(vtop->r2, vtop - 1);
3002 } else {
3003 store(r, vtop - 1);
3006 vswap();
3007 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
3008 vtop->r |= delayed_cast;
3012 /* post defines POST/PRE add. c is the token ++ or -- */
3013 ST_FUNC void inc(int post, int c)
3015 test_lvalue();
3016 vdup(); /* save lvalue */
3017 if (post) {
3018 if (!nocode_wanted)
3019 gv_dup(); /* duplicate value */
3020 else
3021 vdup(); /* duplicate value */
3022 vrotb(3);
3023 vrotb(3);
3025 /* add constant */
3026 vpushi(c - TOK_MID);
3027 gen_op('+');
3028 vstore(); /* store value */
3029 if (post)
3030 vpop(); /* if post op, return saved value */
3033 ST_FUNC void parse_mult_str (CString *astr, const char *msg)
3035 /* read the string */
3036 if (tok != TOK_STR)
3037 expect(msg);
3038 cstr_new(astr);
3039 while (tok == TOK_STR) {
3040 /* XXX: add \0 handling too ? */
3041 cstr_cat(astr, tokc.str.data, -1);
3042 next();
3044 cstr_ccat(astr, '\0');
3047 /* Parse GNUC __attribute__ extension. Currently, the following
3048 extensions are recognized:
3049 - aligned(n) : set data/function alignment.
3050 - packed : force data alignment to 1
3051 - section(x) : generate data/code in this section.
3052 - unused : currently ignored, but may be used someday.
3053 - regparm(n) : pass function parameters in registers (i386 only)
3055 static void parse_attribute(AttributeDef *ad)
3057 int t, n;
3058 CString astr;
3060 while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
3061 next();
3062 skip('(');
3063 skip('(');
3064 while (tok != ')') {
3065 if (tok < TOK_IDENT)
3066 expect("attribute name");
3067 t = tok;
3068 next();
3069 switch(t) {
3070 case TOK_SECTION1:
3071 case TOK_SECTION2:
3072 skip('(');
3073 parse_mult_str(&astr, "section name");
3074 ad->section = find_section(tcc_state, (char *)astr.data);
3075 skip(')');
3076 cstr_free(&astr);
3077 break;
3078 case TOK_ALIAS1:
3079 case TOK_ALIAS2:
3080 skip('(');
3081 parse_mult_str(&astr, "alias(\"target\")");
3082 ad->alias_target = /* save string as token, for later */
3083 tok_alloc((char*)astr.data, astr.size-1)->tok;
3084 skip(')');
3085 cstr_free(&astr);
3086 break;
3087 case TOK_VISIBILITY1:
3088 case TOK_VISIBILITY2:
3089 skip('(');
3090 parse_mult_str(&astr,
3091 "visibility(\"default|hidden|internal|protected\")");
3092 if (!strcmp (astr.data, "default"))
3093 ad->a.visibility = STV_DEFAULT;
3094 else if (!strcmp (astr.data, "hidden"))
3095 ad->a.visibility = STV_HIDDEN;
3096 else if (!strcmp (astr.data, "internal"))
3097 ad->a.visibility = STV_INTERNAL;
3098 else if (!strcmp (astr.data, "protected"))
3099 ad->a.visibility = STV_PROTECTED;
3100 else
3101 expect("visibility(\"default|hidden|internal|protected\")");
3102 skip(')');
3103 cstr_free(&astr);
3104 break;
3105 case TOK_ALIGNED1:
3106 case TOK_ALIGNED2:
3107 if (tok == '(') {
3108 next();
3109 n = expr_const();
3110 if (n <= 0 || (n & (n - 1)) != 0)
3111 tcc_error("alignment must be a positive power of two");
3112 skip(')');
3113 } else {
3114 n = MAX_ALIGN;
3116 ad->a.aligned = n;
3117 break;
3118 case TOK_PACKED1:
3119 case TOK_PACKED2:
3120 ad->a.packed = 1;
3121 break;
3122 case TOK_WEAK1:
3123 case TOK_WEAK2:
3124 ad->a.weak = 1;
3125 break;
3126 case TOK_UNUSED1:
3127 case TOK_UNUSED2:
3128 /* currently, no need to handle it because tcc does not
3129 track unused objects */
3130 break;
3131 case TOK_NORETURN1:
3132 case TOK_NORETURN2:
3133 /* currently, no need to handle it because tcc does not
3134 track unused objects */
3135 break;
3136 case TOK_CDECL1:
3137 case TOK_CDECL2:
3138 case TOK_CDECL3:
3139 ad->a.func_call = FUNC_CDECL;
3140 break;
3141 case TOK_STDCALL1:
3142 case TOK_STDCALL2:
3143 case TOK_STDCALL3:
3144 ad->a.func_call = FUNC_STDCALL;
3145 break;
3146 #ifdef TCC_TARGET_I386
3147 case TOK_REGPARM1:
3148 case TOK_REGPARM2:
3149 skip('(');
3150 n = expr_const();
3151 if (n > 3)
3152 n = 3;
3153 else if (n < 0)
3154 n = 0;
3155 if (n > 0)
3156 ad->a.func_call = FUNC_FASTCALL1 + n - 1;
3157 skip(')');
3158 break;
3159 case TOK_FASTCALL1:
3160 case TOK_FASTCALL2:
3161 case TOK_FASTCALL3:
3162 ad->a.func_call = FUNC_FASTCALLW;
3163 break;
3164 #endif
3165 case TOK_MODE:
3166 skip('(');
3167 switch(tok) {
3168 case TOK_MODE_DI:
3169 ad->a.mode = VT_LLONG + 1;
3170 break;
3171 case TOK_MODE_QI:
3172 ad->a.mode = VT_BYTE + 1;
3173 break;
3174 case TOK_MODE_HI:
3175 ad->a.mode = VT_SHORT + 1;
3176 break;
3177 case TOK_MODE_SI:
3178 case TOK_MODE_word:
3179 ad->a.mode = VT_INT + 1;
3180 break;
3181 default:
3182 tcc_warning("__mode__(%s) not supported\n", get_tok_str(tok, NULL));
3183 break;
3185 next();
3186 skip(')');
3187 break;
3188 case TOK_DLLEXPORT:
3189 ad->a.func_export = 1;
3190 break;
3191 case TOK_DLLIMPORT:
3192 ad->a.func_import = 1;
3193 break;
3194 default:
3195 if (tcc_state->warn_unsupported)
3196 tcc_warning("'%s' attribute ignored", get_tok_str(t, NULL));
3197 /* skip parameters */
3198 if (tok == '(') {
3199 int parenthesis = 0;
3200 do {
3201 if (tok == '(')
3202 parenthesis++;
3203 else if (tok == ')')
3204 parenthesis--;
3205 next();
3206 } while (parenthesis && tok != -1);
3208 break;
3210 if (tok != ',')
3211 break;
3212 next();
3214 skip(')');
3215 skip(')');
3219 static Sym * find_field (CType *type, int v)
3221 Sym *s = type->ref;
3222 v |= SYM_FIELD;
3223 while ((s = s->next) != NULL) {
3224 if ((s->v & SYM_FIELD) && (s->v & ~SYM_FIELD) >= SYM_FIRST_ANOM) {
3225 Sym *ret = find_field (&s->type, v);
3226 if (ret)
3227 return ret;
3229 if (s->v == v)
3230 break;
3232 return s;
3235 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
3236 static void struct_decl(CType *type, AttributeDef *ad, int u)
3238 int a, v, size, align, maxalign, c, offset, flexible, extra_bytes;
3239 int bit_size, bit_pos, bsize, bt, lbit_pos, prevbt;
3240 Sym *s, *ss, *ass, **ps;
3241 AttributeDef ad1;
3242 CType type1, btype;
3244 a = tok; /* save decl type */
3245 next();
3246 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3247 parse_attribute(ad);
3248 if (tok != '{') {
3249 v = tok;
3250 next();
3251 /* struct already defined ? return it */
3252 if (v < TOK_IDENT)
3253 expect("struct/union/enum name");
3254 s = struct_find(v);
3255 if (s && (s->scope == local_scope || (tok != '{' && tok != ';'))) {
3256 if (s->type.t != a)
3257 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
3258 goto do_decl;
3260 } else {
3261 v = anon_sym++;
3263 /* Record the original enum/struct/union token. */
3264 type1.t = a;
3265 type1.ref = NULL;
3266 /* we put an undefined size for struct/union */
3267 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
3268 s->r = 0; /* default alignment is zero as gcc */
3269 /* put struct/union/enum name in type */
3270 do_decl:
3271 type->t = u;
3272 type->ref = s;
3274 if (tok == '{') {
3275 next();
3276 if (s->c != -1)
3277 tcc_error("struct/union/enum already defined");
3278 /* cannot be empty */
3279 c = 0;
3280 /* non empty enums are not allowed */
3281 if (a == TOK_ENUM) {
3282 int seen_neg = 0;
3283 for(;;) {
3284 v = tok;
3285 if (v < TOK_UIDENT)
3286 expect("identifier");
3287 ss = sym_find(v);
3288 if (ss && !local_stack)
3289 tcc_error("redefinition of enumerator '%s'",
3290 get_tok_str(v, NULL));
3291 next();
3292 if (tok == '=') {
3293 next();
3294 c = expr_const();
3296 if (c < 0)
3297 seen_neg = 1;
3298 /* enum symbols have static storage */
3299 ss = sym_push(v, &int_type, VT_CONST, c);
3300 ss->type.t |= VT_STATIC;
3301 if (tok != ',')
3302 break;
3303 next();
3304 c++;
3305 /* NOTE: we accept a trailing comma */
3306 if (tok == '}')
3307 break;
3309 if (!seen_neg)
3310 s->a.unsigned_enum = 1;
3311 s->c = type_size(&int_type, &align);
3312 skip('}');
3313 } else {
3314 maxalign = 1;
3315 ps = &s->next;
3316 prevbt = VT_INT;
3317 bit_pos = 0;
3318 offset = 0;
3319 flexible = 0;
3320 while (tok != '}') {
3321 if (!parse_btype(&btype, &ad1)) {
3322 skip(';');
3323 continue;
3325 while (1) {
3326 extra_bytes = 0;
3327 if (flexible)
3328 tcc_error("flexible array member '%s' not at the end of struct",
3329 get_tok_str(v, NULL));
3330 bit_size = -1;
3331 v = 0;
3332 type1 = btype;
3333 if (tok != ':') {
3334 type_decl(&type1, &ad1, &v, TYPE_DIRECT | TYPE_ABSTRACT);
3335 if (v == 0) {
3336 if ((type1.t & VT_BTYPE) != VT_STRUCT)
3337 expect("identifier");
3338 else {
3339 int v = btype.ref->v;
3340 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
3341 if (tcc_state->ms_extensions == 0)
3342 expect("identifier");
3346 if (type_size(&type1, &align) < 0) {
3347 if ((a == TOK_STRUCT) && (type1.t & VT_ARRAY) && c)
3348 flexible = 1;
3349 else
3350 tcc_error("field '%s' has incomplete type",
3351 get_tok_str(v, NULL));
3353 if ((type1.t & VT_BTYPE) == VT_FUNC ||
3354 (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
3355 tcc_error("invalid type for '%s'",
3356 get_tok_str(v, NULL));
3358 if (tok == ':') {
3359 next();
3360 bit_size = expr_const();
3361 /* XXX: handle v = 0 case for messages */
3362 if (bit_size < 0)
3363 tcc_error("negative width in bit-field '%s'",
3364 get_tok_str(v, NULL));
3365 if (v && bit_size == 0)
3366 tcc_error("zero width for bit-field '%s'",
3367 get_tok_str(v, NULL));
3369 size = type_size(&type1, &align);
3370 if (ad1.a.aligned) {
3371 if (align < ad1.a.aligned)
3372 align = ad1.a.aligned;
3373 } else if (ad1.a.packed || ad->a.packed) {
3374 align = 1;
3375 } else if (*tcc_state->pack_stack_ptr) {
3376 if (align > *tcc_state->pack_stack_ptr)
3377 align = *tcc_state->pack_stack_ptr;
3379 lbit_pos = 0;
3380 if (bit_size >= 0) {
3381 bt = type1.t & VT_BTYPE;
3382 if (bt != VT_INT &&
3383 bt != VT_BYTE &&
3384 bt != VT_SHORT &&
3385 bt != VT_BOOL &&
3386 bt != VT_ENUM &&
3387 bt != VT_LLONG)
3388 tcc_error("bitfields must have scalar type");
3389 bsize = size * 8;
3390 if (bit_size > bsize) {
3391 tcc_error("width of '%s' exceeds its type",
3392 get_tok_str(v, NULL));
3393 } else if (bit_size == bsize) {
3394 /* no need for bit fields */
3395 bit_pos = 0;
3396 } else if (bit_size == 0) {
3397 /* XXX: what to do if only padding in a
3398 structure ? */
3399 /* zero size: means to pad */
3400 bit_pos = 0;
3401 } else {
3402 /* if type change, union, or will overrun
3403 * allignment slot, start at a newly
3404 * alligned slot */
3405 if ((bit_pos + bit_size) > bsize ||
3406 bt != prevbt || a == TOK_UNION)
3407 bit_pos = 0;
3408 lbit_pos = bit_pos;
3409 /* XXX: handle LSB first */
3410 type1.t |= VT_BITFIELD |
3411 (bit_pos << VT_STRUCT_SHIFT) |
3412 (bit_size << (VT_STRUCT_SHIFT + 6));
3413 bit_pos += bit_size;
3414 /* without ms-bitfields, allocate the
3415 * minimum number of bytes necessary,
3416 * adding single bytes as needed */
3417 if (!tcc_state->ms_bitfields) {
3418 if (lbit_pos == 0)
3419 /* minimum bytes for new bitfield */
3420 size = (bit_size + 7) / 8;
3421 else {
3422 /* enough spare bits already allocated? */
3423 bit_size = (lbit_pos - 1) % 8 + 1 + bit_size;
3424 if (bit_size > 8) /* doesn't fit */
3425 extra_bytes = (bit_size - 1) / 8;
3429 prevbt = bt;
3430 } else {
3431 bit_pos = 0;
3433 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
3434 /* add new memory data only if starting bit
3435 field or adding bytes to existing bit field */
3436 if (extra_bytes) c += extra_bytes;
3437 else if (lbit_pos == 0) {
3438 if (a == TOK_STRUCT) {
3439 c = (c + align - 1) & -align;
3440 offset = c;
3441 if (size > 0)
3442 c += size;
3443 } else {
3444 offset = 0;
3445 if (size > c)
3446 c = size;
3448 if (align > maxalign)
3449 maxalign = align;
3451 #if 0
3452 printf("add field %s offset=%d",
3453 get_tok_str(v, NULL), offset);
3454 if (type1.t & VT_BITFIELD) {
3455 printf(" pos=%d size=%d",
3456 (type1.t >> VT_STRUCT_SHIFT) & 0x3f,
3457 (type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
3459 printf("\n");
3460 #endif
3462 if (v == 0 && (type1.t & VT_BTYPE) == VT_STRUCT) {
3463 /* An anonymous struct/union. Adjust member offsets
3464 to reflect the real offset of our containing struct.
3465 Also set the offset of this anon member inside
3466 the outer struct to be zero. Via this it
3467 works when accessing the field offset directly
3468 (from base object), as well as when recursing
3469 members in initializer handling. */
3470 int v2 = btype.ref->v;
3471 if (!(v2 & SYM_FIELD) &&
3472 (v2 & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
3473 Sym **pps;
3474 /* This happens only with MS extensions. The
3475 anon member has a named struct type, so it
3476 potentially is shared with other references.
3477 We need to unshare members so we can modify
3478 them. */
3479 ass = type1.ref;
3480 type1.ref = sym_push(anon_sym++ | SYM_FIELD,
3481 &type1.ref->type, 0,
3482 type1.ref->c);
3483 pps = &type1.ref->next;
3484 while ((ass = ass->next) != NULL) {
3485 *pps = sym_push(ass->v, &ass->type, 0, ass->c);
3486 pps = &((*pps)->next);
3488 *pps = NULL;
3490 ass = type1.ref;
3491 while ((ass = ass->next) != NULL)
3492 ass->c += offset;
3493 offset = 0;
3494 v = anon_sym++;
3496 if (v) {
3497 ss = sym_push(v | SYM_FIELD, &type1, 0, offset);
3498 *ps = ss;
3499 ps = &ss->next;
3501 if (tok == ';' || tok == TOK_EOF)
3502 break;
3503 skip(',');
3505 skip(';');
3507 skip('}');
3508 /* store size and alignment */
3509 s->c = (c + maxalign - 1) & -maxalign;
3510 s->r = maxalign;
3515 /* return 1 if basic type is a type size (short, long, long long) */
3516 ST_FUNC int is_btype_size(int bt)
3518 return bt == VT_SHORT || bt == VT_LONG || bt == VT_LLONG;
3521 /* Add type qualifiers to a type. If the type is an array then the qualifiers
3522 are added to the element type, copied because it could be a typedef. */
3523 static void parse_btype_qualify(CType *type, int qualifiers)
3525 while (type->t & VT_ARRAY) {
3526 type->ref = sym_push(SYM_FIELD, &type->ref->type, 0, type->ref->c);
3527 type = &type->ref->type;
3529 type->t |= qualifiers;
3532 /* return 0 if no type declaration. otherwise, return the basic type
3533 and skip it.
3535 static int parse_btype(CType *type, AttributeDef *ad)
3537 int t, u, bt_size, complete, type_found, typespec_found;
3538 Sym *s;
3539 CType type1;
3541 memset(ad, 0, sizeof(AttributeDef));
3542 complete = 0;
3543 type_found = 0;
3544 typespec_found = 0;
3545 t = 0;
3546 while(1) {
3547 switch(tok) {
3548 case TOK_EXTENSION:
3549 /* currently, we really ignore extension */
3550 next();
3551 continue;
3553 /* basic types */
3554 case TOK_CHAR:
3555 u = VT_BYTE;
3556 basic_type:
3557 next();
3558 basic_type1:
3559 if (complete)
3560 tcc_error("too many basic types");
3561 t |= u;
3562 bt_size = is_btype_size (u & VT_BTYPE);
3563 if (u == VT_INT || (!bt_size && !(t & VT_TYPEDEF)))
3564 complete = 1;
3565 typespec_found = 1;
3566 break;
3567 case TOK_VOID:
3568 u = VT_VOID;
3569 goto basic_type;
3570 case TOK_SHORT:
3571 u = VT_SHORT;
3572 goto basic_type;
3573 case TOK_INT:
3574 u = VT_INT;
3575 goto basic_type;
3576 case TOK_LONG:
3577 next();
3578 if ((t & VT_BTYPE) == VT_DOUBLE) {
3579 #ifndef TCC_TARGET_PE
3580 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3581 #endif
3582 } else if ((t & VT_BTYPE) == VT_LONG) {
3583 t = (t & ~VT_BTYPE) | VT_LLONG;
3584 } else {
3585 u = VT_LONG;
3586 goto basic_type1;
3588 break;
3589 #ifdef TCC_TARGET_ARM64
3590 case TOK_UINT128:
3591 /* GCC's __uint128_t appears in some Linux header files. Make it a
3592 synonym for long double to get the size and alignment right. */
3593 u = VT_LDOUBLE;
3594 goto basic_type;
3595 #endif
3596 case TOK_BOOL:
3597 u = VT_BOOL;
3598 goto basic_type;
3599 case TOK_FLOAT:
3600 u = VT_FLOAT;
3601 goto basic_type;
3602 case TOK_DOUBLE:
3603 next();
3604 if ((t & VT_BTYPE) == VT_LONG) {
3605 #ifdef TCC_TARGET_PE
3606 t = (t & ~VT_BTYPE) | VT_DOUBLE;
3607 #else
3608 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3609 #endif
3610 } else {
3611 u = VT_DOUBLE;
3612 goto basic_type1;
3614 break;
3615 case TOK_ENUM:
3616 struct_decl(&type1, ad, VT_ENUM);
3617 basic_type2:
3618 u = type1.t;
3619 type->ref = type1.ref;
3620 goto basic_type1;
3621 case TOK_STRUCT:
3622 case TOK_UNION:
3623 struct_decl(&type1, ad, VT_STRUCT);
3624 goto basic_type2;
3626 /* type modifiers */
3627 case TOK_CONST1:
3628 case TOK_CONST2:
3629 case TOK_CONST3:
3630 type->t = t;
3631 parse_btype_qualify(type, VT_CONSTANT);
3632 t = type->t;
3633 next();
3634 break;
3635 case TOK_VOLATILE1:
3636 case TOK_VOLATILE2:
3637 case TOK_VOLATILE3:
3638 type->t = t;
3639 parse_btype_qualify(type, VT_VOLATILE);
3640 t = type->t;
3641 next();
3642 break;
3643 case TOK_SIGNED1:
3644 case TOK_SIGNED2:
3645 case TOK_SIGNED3:
3646 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == (VT_DEFSIGN|VT_UNSIGNED))
3647 tcc_error("signed and unsigned modifier");
3648 typespec_found = 1;
3649 t |= VT_DEFSIGN;
3650 next();
3651 break;
3652 case TOK_REGISTER:
3653 case TOK_AUTO:
3654 case TOK_RESTRICT1:
3655 case TOK_RESTRICT2:
3656 case TOK_RESTRICT3:
3657 next();
3658 break;
3659 case TOK_UNSIGNED:
3660 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == VT_DEFSIGN)
3661 tcc_error("signed and unsigned modifier");
3662 t |= VT_DEFSIGN | VT_UNSIGNED;
3663 next();
3664 typespec_found = 1;
3665 break;
3667 /* storage */
3668 case TOK_EXTERN:
3669 t |= VT_EXTERN;
3670 next();
3671 break;
3672 case TOK_STATIC:
3673 t |= VT_STATIC;
3674 next();
3675 break;
3676 case TOK_TYPEDEF:
3677 t |= VT_TYPEDEF;
3678 next();
3679 break;
3680 case TOK_INLINE1:
3681 case TOK_INLINE2:
3682 case TOK_INLINE3:
3683 t |= VT_INLINE;
3684 next();
3685 break;
3687 /* GNUC attribute */
3688 case TOK_ATTRIBUTE1:
3689 case TOK_ATTRIBUTE2:
3690 parse_attribute(ad);
3691 if (ad->a.mode) {
3692 u = ad->a.mode -1;
3693 t = (t & ~VT_BTYPE) | u;
3695 break;
3696 /* GNUC typeof */
3697 case TOK_TYPEOF1:
3698 case TOK_TYPEOF2:
3699 case TOK_TYPEOF3:
3700 next();
3701 parse_expr_type(&type1);
3702 /* remove all storage modifiers except typedef */
3703 type1.t &= ~(VT_STORAGE&~VT_TYPEDEF);
3704 goto basic_type2;
3705 default:
3706 if (typespec_found)
3707 goto the_end;
3708 s = sym_find(tok);
3709 if (!s || !(s->type.t & VT_TYPEDEF))
3710 goto the_end;
3712 type->t = ((s->type.t & ~VT_TYPEDEF) |
3713 (t & ~(VT_CONSTANT | VT_VOLATILE)));
3714 type->ref = s->type.ref;
3715 if (t & (VT_CONSTANT | VT_VOLATILE))
3716 parse_btype_qualify(type, t & (VT_CONSTANT | VT_VOLATILE));
3717 t = type->t;
3719 if (s->r) {
3720 /* get attributes from typedef */
3721 if (0 == ad->a.aligned)
3722 ad->a.aligned = s->a.aligned;
3723 if (0 == ad->a.func_call)
3724 ad->a.func_call = s->a.func_call;
3725 ad->a.packed |= s->a.packed;
3727 next();
3728 typespec_found = 1;
3729 break;
3731 type_found = 1;
3733 the_end:
3734 if (tcc_state->char_is_unsigned) {
3735 if ((t & (VT_DEFSIGN|VT_BTYPE)) == VT_BYTE)
3736 t |= VT_UNSIGNED;
3739 /* long is never used as type */
3740 if ((t & VT_BTYPE) == VT_LONG)
3741 #if (!defined TCC_TARGET_X86_64 && !defined TCC_TARGET_ARM64) || \
3742 defined TCC_TARGET_PE
3743 t = (t & ~VT_BTYPE) | VT_INT;
3744 #else
3745 t = (t & ~VT_BTYPE) | VT_LLONG;
3746 #endif
3747 type->t = t;
3748 return type_found;
3751 /* convert a function parameter type (array to pointer and function to
3752 function pointer) */
3753 static inline void convert_parameter_type(CType *pt)
3755 /* remove const and volatile qualifiers (XXX: const could be used
3756 to indicate a const function parameter */
3757 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
3758 /* array must be transformed to pointer according to ANSI C */
3759 pt->t &= ~VT_ARRAY;
3760 if ((pt->t & VT_BTYPE) == VT_FUNC) {
3761 mk_pointer(pt);
3765 ST_FUNC void parse_asm_str(CString *astr)
3767 skip('(');
3768 parse_mult_str(astr, "string constant");
3771 /* Parse an asm label and return the token */
3772 static int asm_label_instr(void)
3774 int v;
3775 CString astr;
3777 next();
3778 parse_asm_str(&astr);
3779 skip(')');
3780 #ifdef ASM_DEBUG
3781 printf("asm_alias: \"%s\"\n", (char *)astr.data);
3782 #endif
3783 v = tok_alloc(astr.data, astr.size - 1)->tok;
3784 cstr_free(&astr);
3785 return v;
3788 static void post_type(CType *type, AttributeDef *ad)
3790 int n, l, t1, arg_size, align;
3791 Sym **plast, *s, *first;
3792 AttributeDef ad1;
3793 CType pt;
3795 if (tok == '(') {
3796 /* function declaration */
3797 next();
3798 l = 0;
3799 first = NULL;
3800 plast = &first;
3801 arg_size = 0;
3802 if (tok != ')') {
3803 for(;;) {
3804 /* read param name and compute offset */
3805 if (l != FUNC_OLD) {
3806 if (!parse_btype(&pt, &ad1)) {
3807 if (l) {
3808 tcc_error("invalid type");
3809 } else {
3810 l = FUNC_OLD;
3811 goto old_proto;
3814 l = FUNC_NEW;
3815 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
3816 break;
3817 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
3818 if ((pt.t & VT_BTYPE) == VT_VOID)
3819 tcc_error("parameter declared as void");
3820 arg_size += (type_size(&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
3821 } else {
3822 old_proto:
3823 n = tok;
3824 if (n < TOK_UIDENT)
3825 expect("identifier");
3826 pt.t = VT_INT;
3827 next();
3829 convert_parameter_type(&pt);
3830 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
3831 *plast = s;
3832 plast = &s->next;
3833 if (tok == ')')
3834 break;
3835 skip(',');
3836 if (l == FUNC_NEW && tok == TOK_DOTS) {
3837 l = FUNC_ELLIPSIS;
3838 next();
3839 break;
3843 /* if no parameters, then old type prototype */
3844 if (l == 0)
3845 l = FUNC_OLD;
3846 skip(')');
3847 /* NOTE: const is ignored in returned type as it has a special
3848 meaning in gcc / C++ */
3849 type->t &= ~VT_CONSTANT;
3850 /* some ancient pre-K&R C allows a function to return an array
3851 and the array brackets to be put after the arguments, such
3852 that "int c()[]" means something like "int[] c()" */
3853 if (tok == '[') {
3854 next();
3855 skip(']'); /* only handle simple "[]" */
3856 type->t |= VT_PTR;
3858 /* we push a anonymous symbol which will contain the function prototype */
3859 ad->a.func_args = arg_size;
3860 s = sym_push(SYM_FIELD, type, 0, l);
3861 s->a = ad->a;
3862 s->next = first;
3863 type->t = VT_FUNC;
3864 type->ref = s;
3865 } else if (tok == '[') {
3866 /* array definition */
3867 next();
3868 if (tok == TOK_RESTRICT1)
3869 next();
3870 n = -1;
3871 t1 = 0;
3872 if (tok != ']') {
3873 if (!local_stack || nocode_wanted)
3874 vpushi(expr_const());
3875 else gexpr();
3876 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3877 n = vtop->c.i;
3878 if (n < 0)
3879 tcc_error("invalid array size");
3880 } else {
3881 if (!is_integer_btype(vtop->type.t & VT_BTYPE))
3882 tcc_error("size of variable length array should be an integer");
3883 t1 = VT_VLA;
3886 skip(']');
3887 /* parse next post type */
3888 post_type(type, ad);
3889 if (type->t == VT_FUNC)
3890 tcc_error("declaration of an array of functions");
3891 t1 |= type->t & VT_VLA;
3893 if (t1 & VT_VLA) {
3894 loc -= type_size(&int_type, &align);
3895 loc &= -align;
3896 n = loc;
3898 vla_runtime_type_size(type, &align);
3899 gen_op('*');
3900 vset(&int_type, VT_LOCAL|VT_LVAL, n);
3901 vswap();
3902 vstore();
3904 if (n != -1)
3905 vpop();
3907 /* we push an anonymous symbol which will contain the array
3908 element type */
3909 s = sym_push(SYM_FIELD, type, 0, n);
3910 type->t = (t1 ? VT_VLA : VT_ARRAY) | VT_PTR;
3911 type->ref = s;
3915 /* Parse a type declaration (except basic type), and return the type
3916 in 'type'. 'td' is a bitmask indicating which kind of type decl is
3917 expected. 'type' should contain the basic type. 'ad' is the
3918 attribute definition of the basic type. It can be modified by
3919 type_decl().
3921 static void type_decl(CType *type, AttributeDef *ad, int *v, int td)
3923 Sym *s;
3924 CType type1, *type2;
3925 int qualifiers, storage;
3927 while (tok == '*') {
3928 qualifiers = 0;
3929 redo:
3930 next();
3931 switch(tok) {
3932 case TOK_CONST1:
3933 case TOK_CONST2:
3934 case TOK_CONST3:
3935 qualifiers |= VT_CONSTANT;
3936 goto redo;
3937 case TOK_VOLATILE1:
3938 case TOK_VOLATILE2:
3939 case TOK_VOLATILE3:
3940 qualifiers |= VT_VOLATILE;
3941 goto redo;
3942 case TOK_RESTRICT1:
3943 case TOK_RESTRICT2:
3944 case TOK_RESTRICT3:
3945 goto redo;
3946 /* XXX: clarify attribute handling */
3947 case TOK_ATTRIBUTE1:
3948 case TOK_ATTRIBUTE2:
3949 parse_attribute(ad);
3950 break;
3952 mk_pointer(type);
3953 type->t |= qualifiers;
3956 /* recursive type */
3957 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
3958 type1.t = 0; /* XXX: same as int */
3959 if (tok == '(') {
3960 next();
3961 /* XXX: this is not correct to modify 'ad' at this point, but
3962 the syntax is not clear */
3963 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3964 parse_attribute(ad);
3965 type_decl(&type1, ad, v, td);
3966 skip(')');
3967 } else {
3968 /* type identifier */
3969 if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
3970 *v = tok;
3971 next();
3972 } else {
3973 if (!(td & TYPE_ABSTRACT))
3974 expect("identifier");
3975 *v = 0;
3978 storage = type->t & VT_STORAGE;
3979 type->t &= ~VT_STORAGE;
3980 if (storage & VT_STATIC) {
3981 int saved_nocode_wanted = nocode_wanted;
3982 nocode_wanted = 1;
3983 post_type(type, ad);
3984 nocode_wanted = saved_nocode_wanted;
3985 } else
3986 post_type(type, ad);
3987 type->t |= storage;
3988 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3989 parse_attribute(ad);
3991 if (!type1.t)
3992 return;
3993 /* append type at the end of type1 */
3994 type2 = &type1;
3995 for(;;) {
3996 s = type2->ref;
3997 type2 = &s->type;
3998 if (!type2->t) {
3999 *type2 = *type;
4000 break;
4003 *type = type1;
4006 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
4007 ST_FUNC int lvalue_type(int t)
4009 int bt, r;
4010 r = VT_LVAL;
4011 bt = t & VT_BTYPE;
4012 if (bt == VT_BYTE || bt == VT_BOOL)
4013 r |= VT_LVAL_BYTE;
4014 else if (bt == VT_SHORT)
4015 r |= VT_LVAL_SHORT;
4016 else
4017 return r;
4018 if (t & VT_UNSIGNED)
4019 r |= VT_LVAL_UNSIGNED;
4020 return r;
4023 /* indirection with full error checking and bound check */
4024 ST_FUNC void indir(void)
4026 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
4027 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
4028 return;
4029 expect("pointer");
4031 if ((vtop->r & VT_LVAL) && !nocode_wanted)
4032 gv(RC_INT);
4033 vtop->type = *pointed_type(&vtop->type);
4034 /* Arrays and functions are never lvalues */
4035 if (!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_VLA)
4036 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
4037 vtop->r |= lvalue_type(vtop->type.t);
4038 /* if bound checking, the referenced pointer must be checked */
4039 #ifdef CONFIG_TCC_BCHECK
4040 if (tcc_state->do_bounds_check)
4041 vtop->r |= VT_MUSTBOUND;
4042 #endif
4046 /* pass a parameter to a function and do type checking and casting */
4047 static void gfunc_param_typed(Sym *func, Sym *arg)
4049 int func_type;
4050 CType type;
4052 func_type = func->c;
4053 if (func_type == FUNC_OLD ||
4054 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
4055 /* default casting : only need to convert float to double */
4056 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
4057 type.t = VT_DOUBLE;
4058 gen_cast(&type);
4059 } else if (vtop->type.t & VT_BITFIELD) {
4060 type.t = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
4061 gen_cast(&type);
4063 } else if (arg == NULL) {
4064 tcc_error("too many arguments to function");
4065 } else {
4066 type = arg->type;
4067 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
4068 gen_assign_cast(&type);
4072 /* parse an expression of the form '(type)' or '(expr)' and return its
4073 type */
4074 static void parse_expr_type(CType *type)
4076 int n;
4077 AttributeDef ad;
4079 skip('(');
4080 if (parse_btype(type, &ad)) {
4081 type_decl(type, &ad, &n, TYPE_ABSTRACT);
4082 } else {
4083 expr_type(type);
4085 skip(')');
4088 static void parse_type(CType *type)
4090 AttributeDef ad;
4091 int n;
4093 if (!parse_btype(type, &ad)) {
4094 expect("type");
4096 type_decl(type, &ad, &n, TYPE_ABSTRACT);
4099 static void vpush_tokc(int t)
4101 CType type;
4102 type.t = t;
4103 type.ref = 0;
4104 vsetc(&type, VT_CONST, &tokc);
4107 ST_FUNC void unary(void)
4109 int n, t, align, size, r, sizeof_caller;
4110 CType type;
4111 Sym *s;
4112 AttributeDef ad;
4114 sizeof_caller = in_sizeof;
4115 in_sizeof = 0;
4116 /* XXX: GCC 2.95.3 does not generate a table although it should be
4117 better here */
4118 tok_next:
4119 switch(tok) {
4120 case TOK_EXTENSION:
4121 next();
4122 goto tok_next;
4123 case TOK_CINT:
4124 case TOK_CCHAR:
4125 case TOK_LCHAR:
4126 vpushi(tokc.i);
4127 next();
4128 break;
4129 case TOK_CUINT:
4130 vpush_tokc(VT_INT | VT_UNSIGNED);
4131 next();
4132 break;
4133 case TOK_CLLONG:
4134 vpush_tokc(VT_LLONG);
4135 next();
4136 break;
4137 case TOK_CULLONG:
4138 vpush_tokc(VT_LLONG | VT_UNSIGNED);
4139 next();
4140 break;
4141 case TOK_CFLOAT:
4142 vpush_tokc(VT_FLOAT);
4143 next();
4144 break;
4145 case TOK_CDOUBLE:
4146 vpush_tokc(VT_DOUBLE);
4147 next();
4148 break;
4149 case TOK_CLDOUBLE:
4150 vpush_tokc(VT_LDOUBLE);
4151 next();
4152 break;
4153 case TOK___FUNCTION__:
4154 if (!gnu_ext)
4155 goto tok_identifier;
4156 /* fall thru */
4157 case TOK___FUNC__:
4159 void *ptr;
4160 int len;
4161 /* special function name identifier */
4162 len = strlen(funcname) + 1;
4163 /* generate char[len] type */
4164 type.t = VT_BYTE;
4165 mk_pointer(&type);
4166 type.t |= VT_ARRAY;
4167 type.ref->c = len;
4168 vpush_ref(&type, data_section, data_section->data_offset, len);
4169 ptr = section_ptr_add(data_section, len);
4170 memcpy(ptr, funcname, len);
4171 next();
4173 break;
4174 case TOK_LSTR:
4175 #ifdef TCC_TARGET_PE
4176 t = VT_SHORT | VT_UNSIGNED;
4177 #else
4178 t = VT_INT;
4179 #endif
4180 goto str_init;
4181 case TOK_STR:
4182 /* string parsing */
4183 t = VT_BYTE;
4184 str_init:
4185 if (tcc_state->warn_write_strings)
4186 t |= VT_CONSTANT;
4187 type.t = t;
4188 mk_pointer(&type);
4189 type.t |= VT_ARRAY;
4190 memset(&ad, 0, sizeof(AttributeDef));
4191 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, 0);
4192 break;
4193 case '(':
4194 next();
4195 /* cast ? */
4196 if (parse_btype(&type, &ad)) {
4197 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
4198 skip(')');
4199 /* check ISOC99 compound literal */
4200 if (tok == '{') {
4201 /* data is allocated locally by default */
4202 if (global_expr)
4203 r = VT_CONST;
4204 else
4205 r = VT_LOCAL;
4206 /* all except arrays are lvalues */
4207 if (!(type.t & VT_ARRAY))
4208 r |= lvalue_type(type.t);
4209 memset(&ad, 0, sizeof(AttributeDef));
4210 decl_initializer_alloc(&type, &ad, r, 1, 0, 0);
4211 } else {
4212 if (sizeof_caller) {
4213 vpush(&type);
4214 return;
4216 unary();
4217 gen_cast(&type);
4219 } else if (tok == '{') {
4220 if (const_wanted)
4221 tcc_error("expected constant");
4222 /* save all registers */
4223 if (!nocode_wanted)
4224 save_regs(0);
4225 /* statement expression : we do not accept break/continue
4226 inside as GCC does */
4227 block(NULL, NULL, 1);
4228 skip(')');
4229 } else {
4230 gexpr();
4231 skip(')');
4233 break;
4234 case '*':
4235 next();
4236 unary();
4237 indir();
4238 break;
4239 case '&':
4240 next();
4241 unary();
4242 /* functions names must be treated as function pointers,
4243 except for unary '&' and sizeof. Since we consider that
4244 functions are not lvalues, we only have to handle it
4245 there and in function calls. */
4246 /* arrays can also be used although they are not lvalues */
4247 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
4248 !(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
4249 test_lvalue();
4250 mk_pointer(&vtop->type);
4251 gaddrof();
4252 break;
4253 case '!':
4254 next();
4255 unary();
4256 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4257 CType boolean;
4258 boolean.t = VT_BOOL;
4259 gen_cast(&boolean);
4260 vtop->c.i = !vtop->c.i;
4261 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
4262 vtop->c.i ^= 1;
4263 else {
4264 save_regs(1);
4265 vseti(VT_JMP, gvtst(1, 0));
4267 break;
4268 case '~':
4269 next();
4270 unary();
4271 vpushi(-1);
4272 gen_op('^');
4273 break;
4274 case '+':
4275 next();
4276 unary();
4277 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
4278 tcc_error("pointer not accepted for unary plus");
4279 /* In order to force cast, we add zero, except for floating point
4280 where we really need an noop (otherwise -0.0 will be transformed
4281 into +0.0). */
4282 if (!is_float(vtop->type.t)) {
4283 vpushi(0);
4284 gen_op('+');
4286 break;
4287 case TOK_SIZEOF:
4288 case TOK_ALIGNOF1:
4289 case TOK_ALIGNOF2:
4290 t = tok;
4291 next();
4292 in_sizeof++;
4293 unary_type(&type); // Perform a in_sizeof = 0;
4294 size = type_size(&type, &align);
4295 if (t == TOK_SIZEOF) {
4296 if (!(type.t & VT_VLA)) {
4297 if (size < 0)
4298 tcc_error("sizeof applied to an incomplete type");
4299 vpushs(size);
4300 } else {
4301 vla_runtime_type_size(&type, &align);
4303 } else {
4304 vpushs(align);
4306 vtop->type.t |= VT_UNSIGNED;
4307 break;
4309 case TOK_builtin_expect:
4311 /* __builtin_expect is a no-op for now */
4312 int saved_nocode_wanted;
4313 next();
4314 skip('(');
4315 expr_eq();
4316 skip(',');
4317 saved_nocode_wanted = nocode_wanted;
4318 nocode_wanted = 1;
4319 expr_lor_const();
4320 vpop();
4321 nocode_wanted = saved_nocode_wanted;
4322 skip(')');
4324 break;
4325 case TOK_builtin_types_compatible_p:
4327 CType type1, type2;
4328 next();
4329 skip('(');
4330 parse_type(&type1);
4331 skip(',');
4332 parse_type(&type2);
4333 skip(')');
4334 type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
4335 type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
4336 vpushi(is_compatible_types(&type1, &type2));
4338 break;
4339 case TOK_builtin_choose_expr:
4341 int saved_nocode_wanted, c;
4342 next();
4343 skip('(');
4344 c = expr_const();
4345 skip(',');
4346 if (!c) {
4347 saved_nocode_wanted = nocode_wanted;
4348 nocode_wanted = 1;
4350 expr_eq();
4351 if (!c) {
4352 vpop();
4353 nocode_wanted = saved_nocode_wanted;
4355 skip(',');
4356 if (c) {
4357 saved_nocode_wanted = nocode_wanted;
4358 nocode_wanted = 1;
4360 expr_eq();
4361 if (c) {
4362 vpop();
4363 nocode_wanted = saved_nocode_wanted;
4365 skip(')');
4367 break;
4368 case TOK_builtin_constant_p:
4370 int saved_nocode_wanted, res;
4371 next();
4372 skip('(');
4373 saved_nocode_wanted = nocode_wanted;
4374 nocode_wanted = 1;
4375 gexpr();
4376 res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
4377 vpop();
4378 nocode_wanted = saved_nocode_wanted;
4379 skip(')');
4380 vpushi(res);
4382 break;
4383 case TOK_builtin_frame_address:
4384 case TOK_builtin_return_address:
4386 int tok1 = tok;
4387 int level;
4388 CType type;
4389 next();
4390 skip('(');
4391 if (tok != TOK_CINT) {
4392 tcc_error("%s only takes positive integers",
4393 tok1 == TOK_builtin_return_address ?
4394 "__builtin_return_address" :
4395 "__builtin_frame_address");
4397 level = (uint32_t)tokc.i;
4398 next();
4399 skip(')');
4400 type.t = VT_VOID;
4401 mk_pointer(&type);
4402 vset(&type, VT_LOCAL, 0); /* local frame */
4403 while (level--) {
4404 mk_pointer(&vtop->type);
4405 indir(); /* -> parent frame */
4407 if (tok1 == TOK_builtin_return_address) {
4408 // assume return address is just above frame pointer on stack
4409 vpushi(PTR_SIZE);
4410 gen_op('+');
4411 mk_pointer(&vtop->type);
4412 indir();
4415 break;
4416 #ifdef TCC_TARGET_X86_64
4417 #ifdef TCC_TARGET_PE
4418 case TOK_builtin_va_start:
4420 next();
4421 skip('(');
4422 expr_eq();
4423 skip(',');
4424 expr_eq();
4425 skip(')');
4426 if ((vtop->r & VT_VALMASK) != VT_LOCAL)
4427 tcc_error("__builtin_va_start expects a local variable");
4428 vtop->r &= ~(VT_LVAL | VT_REF);
4429 vtop->type = char_pointer_type;
4430 vtop->c.i += 8;
4431 vstore();
4433 break;
4434 #else
4435 case TOK_builtin_va_arg_types:
4437 CType type;
4438 next();
4439 skip('(');
4440 parse_type(&type);
4441 skip(')');
4442 vpushi(classify_x86_64_va_arg(&type));
4444 break;
4445 #endif
4446 #endif
4448 #ifdef TCC_TARGET_ARM64
4449 case TOK___va_start: {
4450 if (nocode_wanted)
4451 tcc_error("statement in global scope");
4452 next();
4453 skip('(');
4454 expr_eq();
4455 skip(',');
4456 expr_eq();
4457 skip(')');
4458 //xx check types
4459 gen_va_start();
4460 vpushi(0);
4461 vtop->type.t = VT_VOID;
4462 break;
4464 case TOK___va_arg: {
4465 CType type;
4466 if (nocode_wanted)
4467 tcc_error("statement in global scope");
4468 next();
4469 skip('(');
4470 expr_eq();
4471 skip(',');
4472 parse_type(&type);
4473 skip(')');
4474 //xx check types
4475 gen_va_arg(&type);
4476 vtop->type = type;
4477 break;
4479 case TOK___arm64_clear_cache: {
4480 next();
4481 skip('(');
4482 expr_eq();
4483 skip(',');
4484 expr_eq();
4485 skip(')');
4486 gen_clear_cache();
4487 vpushi(0);
4488 vtop->type.t = VT_VOID;
4489 break;
4491 #endif
4492 /* pre operations */
4493 case TOK_INC:
4494 case TOK_DEC:
4495 t = tok;
4496 next();
4497 unary();
4498 inc(0, t);
4499 break;
4500 case '-':
4501 next();
4502 unary();
4503 t = vtop->type.t & VT_BTYPE;
4504 if (is_float(t)) {
4505 /* In IEEE negate(x) isn't subtract(0,x), but rather
4506 subtract(-0, x). */
4507 vpush(&vtop->type);
4508 if (t == VT_FLOAT)
4509 vtop->c.f = -0.0f;
4510 else if (t == VT_DOUBLE)
4511 vtop->c.d = -0.0;
4512 else
4513 vtop->c.ld = -0.0;
4514 } else
4515 vpushi(0);
4516 vswap();
4517 gen_op('-');
4518 break;
4519 case TOK_LAND:
4520 if (!gnu_ext)
4521 goto tok_identifier;
4522 next();
4523 /* allow to take the address of a label */
4524 if (tok < TOK_UIDENT)
4525 expect("label identifier");
4526 s = label_find(tok);
4527 if (!s) {
4528 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
4529 } else {
4530 if (s->r == LABEL_DECLARED)
4531 s->r = LABEL_FORWARD;
4533 if (!s->type.t) {
4534 s->type.t = VT_VOID;
4535 mk_pointer(&s->type);
4536 s->type.t |= VT_STATIC;
4538 vpushsym(&s->type, s);
4539 next();
4540 break;
4542 // special qnan , snan and infinity values
4543 case TOK___NAN__:
4544 vpush64(VT_DOUBLE, 0x7ff8000000000000ULL);
4545 next();
4546 break;
4547 case TOK___SNAN__:
4548 vpush64(VT_DOUBLE, 0x7ff0000000000001ULL);
4549 next();
4550 break;
4551 case TOK___INF__:
4552 vpush64(VT_DOUBLE, 0x7ff0000000000000ULL);
4553 next();
4554 break;
4556 default:
4557 tok_identifier:
4558 t = tok;
4559 next();
4560 if (t < TOK_UIDENT)
4561 expect("identifier");
4562 s = sym_find(t);
4563 if (!s) {
4564 const char *name = get_tok_str(t, NULL);
4565 if (tok != '(')
4566 tcc_error("'%s' undeclared", name);
4567 /* for simple function calls, we tolerate undeclared
4568 external reference to int() function */
4569 if (tcc_state->warn_implicit_function_declaration
4570 #ifdef TCC_TARGET_PE
4571 /* people must be warned about using undeclared WINAPI functions
4572 (which usually start with uppercase letter) */
4573 || (name[0] >= 'A' && name[0] <= 'Z')
4574 #endif
4576 tcc_warning("implicit declaration of function '%s'", name);
4577 s = external_global_sym(t, &func_old_type, 0);
4579 if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
4580 (VT_STATIC | VT_INLINE | VT_FUNC)) {
4581 /* if referencing an inline function, then we generate a
4582 symbol to it if not already done. It will have the
4583 effect to generate code for it at the end of the
4584 compilation unit. Inline function as always
4585 generated in the text section. */
4586 if (!s->c)
4587 put_extern_sym(s, text_section, 0, 0);
4588 r = VT_SYM | VT_CONST;
4589 } else {
4590 r = s->r;
4592 vset(&s->type, r, s->c);
4593 /* if forward reference, we must point to s */
4594 if (vtop->r & VT_SYM) {
4595 vtop->sym = s;
4596 vtop->c.i = 0;
4598 break;
4601 /* post operations */
4602 while (1) {
4603 if (tok == TOK_INC || tok == TOK_DEC) {
4604 inc(1, tok);
4605 next();
4606 } else if (tok == '.' || tok == TOK_ARROW || tok == TOK_CDOUBLE) {
4607 int qualifiers;
4608 /* field */
4609 if (tok == TOK_ARROW)
4610 indir();
4611 qualifiers = vtop->type.t & (VT_CONSTANT | VT_VOLATILE);
4612 test_lvalue();
4613 gaddrof();
4614 /* expect pointer on structure */
4615 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
4616 expect("struct or union");
4617 if (tok == TOK_CDOUBLE)
4618 expect("field name");
4619 next();
4620 if (tok == TOK_CINT || tok == TOK_CUINT)
4621 expect("field name");
4622 s = find_field(&vtop->type, tok);
4623 if (!s)
4624 tcc_error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, &tokc));
4625 /* add field offset to pointer */
4626 vtop->type = char_pointer_type; /* change type to 'char *' */
4627 vpushi(s->c);
4628 gen_op('+');
4629 /* change type to field type, and set to lvalue */
4630 vtop->type = s->type;
4631 vtop->type.t |= qualifiers;
4632 /* an array is never an lvalue */
4633 if (!(vtop->type.t & VT_ARRAY)) {
4634 vtop->r |= lvalue_type(vtop->type.t);
4635 #ifdef CONFIG_TCC_BCHECK
4636 /* if bound checking, the referenced pointer must be checked */
4637 if (tcc_state->do_bounds_check && (vtop->r & VT_VALMASK) != VT_LOCAL)
4638 vtop->r |= VT_MUSTBOUND;
4639 #endif
4641 next();
4642 } else if (tok == '[') {
4643 next();
4644 gexpr();
4645 gen_op('+');
4646 indir();
4647 skip(']');
4648 } else if (tok == '(') {
4649 SValue ret;
4650 Sym *sa;
4651 int nb_args, ret_nregs, ret_align, regsize, variadic;
4653 /* function call */
4654 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
4655 /* pointer test (no array accepted) */
4656 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
4657 vtop->type = *pointed_type(&vtop->type);
4658 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
4659 goto error_func;
4660 } else {
4661 error_func:
4662 expect("function pointer");
4664 } else {
4665 vtop->r &= ~VT_LVAL; /* no lvalue */
4667 /* get return type */
4668 s = vtop->type.ref;
4669 next();
4670 sa = s->next; /* first parameter */
4671 nb_args = 0;
4672 ret.r2 = VT_CONST;
4673 /* compute first implicit argument if a structure is returned */
4674 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
4675 variadic = (s->c == FUNC_ELLIPSIS);
4676 ret_nregs = gfunc_sret(&s->type, variadic, &ret.type,
4677 &ret_align, &regsize);
4678 if (!ret_nregs) {
4679 /* get some space for the returned structure */
4680 size = type_size(&s->type, &align);
4681 #ifdef TCC_TARGET_ARM64
4682 /* On arm64, a small struct is return in registers.
4683 It is much easier to write it to memory if we know
4684 that we are allowed to write some extra bytes, so
4685 round the allocated space up to a power of 2: */
4686 if (size < 16)
4687 while (size & (size - 1))
4688 size = (size | (size - 1)) + 1;
4689 #endif
4690 loc = (loc - size) & -align;
4691 ret.type = s->type;
4692 ret.r = VT_LOCAL | VT_LVAL;
4693 /* pass it as 'int' to avoid structure arg passing
4694 problems */
4695 vseti(VT_LOCAL, loc);
4696 ret.c = vtop->c;
4697 nb_args++;
4699 } else {
4700 ret_nregs = 1;
4701 ret.type = s->type;
4704 if (ret_nregs) {
4705 /* return in register */
4706 if (is_float(ret.type.t)) {
4707 ret.r = reg_fret(ret.type.t);
4708 #ifdef TCC_TARGET_X86_64
4709 if ((ret.type.t & VT_BTYPE) == VT_QFLOAT)
4710 ret.r2 = REG_QRET;
4711 #endif
4712 } else {
4713 #ifndef TCC_TARGET_ARM64
4714 #ifdef TCC_TARGET_X86_64
4715 if ((ret.type.t & VT_BTYPE) == VT_QLONG)
4716 #else
4717 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
4718 #endif
4719 ret.r2 = REG_LRET;
4720 #endif
4721 ret.r = REG_IRET;
4723 ret.c.i = 0;
4725 if (tok != ')') {
4726 for(;;) {
4727 expr_eq();
4728 gfunc_param_typed(s, sa);
4729 nb_args++;
4730 if (sa)
4731 sa = sa->next;
4732 if (tok == ')')
4733 break;
4734 skip(',');
4737 if (sa)
4738 tcc_error("too few arguments to function");
4739 skip(')');
4740 if (!nocode_wanted) {
4741 gfunc_call(nb_args);
4742 } else {
4743 vtop -= (nb_args + 1);
4746 /* return value */
4747 for (r = ret.r + ret_nregs + !ret_nregs; r-- > ret.r;) {
4748 vsetc(&ret.type, r, &ret.c);
4749 vtop->r2 = ret.r2; /* Loop only happens when r2 is VT_CONST */
4752 /* handle packed struct return */
4753 if (((s->type.t & VT_BTYPE) == VT_STRUCT) && ret_nregs) {
4754 int addr, offset;
4756 size = type_size(&s->type, &align);
4757 /* We're writing whole regs often, make sure there's enough
4758 space. Assume register size is power of 2. */
4759 if (regsize > align)
4760 align = regsize;
4761 loc = (loc - size) & -align;
4762 addr = loc;
4763 offset = 0;
4764 for (;;) {
4765 vset(&ret.type, VT_LOCAL | VT_LVAL, addr + offset);
4766 vswap();
4767 vstore();
4768 vtop--;
4769 if (--ret_nregs == 0)
4770 break;
4771 offset += regsize;
4773 vset(&s->type, VT_LOCAL | VT_LVAL, addr);
4775 } else {
4776 break;
4781 ST_FUNC void expr_prod(void)
4783 int t;
4785 unary();
4786 while (tok == '*' || tok == '/' || tok == '%') {
4787 t = tok;
4788 next();
4789 unary();
4790 gen_op(t);
4794 ST_FUNC void expr_sum(void)
4796 int t;
4798 expr_prod();
4799 while (tok == '+' || tok == '-') {
4800 t = tok;
4801 next();
4802 expr_prod();
4803 gen_op(t);
4807 static void expr_shift(void)
4809 int t;
4811 expr_sum();
4812 while (tok == TOK_SHL || tok == TOK_SAR) {
4813 t = tok;
4814 next();
4815 expr_sum();
4816 gen_op(t);
4820 static void expr_cmp(void)
4822 int t;
4824 expr_shift();
4825 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
4826 tok == TOK_ULT || tok == TOK_UGE) {
4827 t = tok;
4828 next();
4829 expr_shift();
4830 gen_op(t);
4834 static void expr_cmpeq(void)
4836 int t;
4838 expr_cmp();
4839 while (tok == TOK_EQ || tok == TOK_NE) {
4840 t = tok;
4841 next();
4842 expr_cmp();
4843 gen_op(t);
4847 static void expr_and(void)
4849 expr_cmpeq();
4850 while (tok == '&') {
4851 next();
4852 expr_cmpeq();
4853 gen_op('&');
4857 static void expr_xor(void)
4859 expr_and();
4860 while (tok == '^') {
4861 next();
4862 expr_and();
4863 gen_op('^');
4867 static void expr_or(void)
4869 expr_xor();
4870 while (tok == '|') {
4871 next();
4872 expr_xor();
4873 gen_op('|');
4877 /* XXX: fix this mess */
4878 static void expr_land_const(void)
4880 expr_or();
4881 while (tok == TOK_LAND) {
4882 next();
4883 expr_or();
4884 gen_op(TOK_LAND);
4887 static void expr_lor_const(void)
4889 expr_land_const();
4890 while (tok == TOK_LOR) {
4891 next();
4892 expr_land_const();
4893 gen_op(TOK_LOR);
4897 static void expr_land(void)
4899 expr_or();
4900 if (tok == TOK_LAND) {
4901 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4902 CType ctb, cti;
4903 ctb.t = VT_BOOL;
4904 cti.t = VT_INT;
4905 next();
4906 gen_cast(&ctb);
4907 if (vtop->c.i) {
4908 vpop();
4909 expr_land();
4910 gen_cast(&ctb);
4911 } else {
4912 int saved_nocode_wanted = nocode_wanted;
4913 nocode_wanted = 1;
4914 expr_land();
4915 vpop();
4916 nocode_wanted = saved_nocode_wanted;
4918 gen_cast(&cti);
4919 } else {
4920 int t = 0;
4921 save_regs(1);
4922 for(;;) {
4923 t = gvtst(1, t);
4924 if (tok != TOK_LAND) {
4925 vseti(VT_JMPI, t);
4926 break;
4928 next();
4929 expr_or();
4935 static void expr_lor(void)
4937 expr_land();
4938 if (tok == TOK_LOR) {
4939 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4940 CType ctb, cti;
4941 ctb.t = VT_BOOL;
4942 cti.t = VT_INT;
4943 next();
4944 gen_cast(&ctb);
4945 if (vtop->c.i) {
4946 int saved_nocode_wanted = nocode_wanted;
4947 nocode_wanted = 1;
4948 expr_lor();
4949 vpop();
4950 nocode_wanted = saved_nocode_wanted;
4951 } else {
4952 vpop();
4953 expr_lor();
4954 gen_cast(&ctb);
4956 gen_cast(&cti);
4957 } else {
4958 int t = 0;
4959 save_regs(1);
4960 for(;;) {
4961 t = gvtst(0, t);
4962 if (tok != TOK_LOR) {
4963 vseti(VT_JMP, t);
4964 break;
4966 next();
4967 expr_land();
4973 static void expr_cond(void)
4975 int tt, u, r1, r2, rc, t1, t2, bt1, bt2, islv;
4976 SValue sv;
4977 CType type, type1, type2;
4979 expr_lor();
4980 if (tok == '?') {
4981 next();
4982 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4983 int saved_nocode_wanted = nocode_wanted;
4984 CType boolean;
4985 int c;
4986 boolean.t = VT_BOOL;
4987 vdup();
4988 gen_cast(&boolean);
4989 c = vtop->c.i;
4990 vpop();
4991 if (c) {
4992 if (tok != ':' || !gnu_ext) {
4993 vpop();
4994 gexpr();
4996 skip(':');
4997 nocode_wanted = 1;
4998 expr_cond();
4999 vpop();
5000 nocode_wanted = saved_nocode_wanted;
5001 } else {
5002 vpop();
5003 if (tok != ':' || !gnu_ext) {
5004 nocode_wanted = 1;
5005 gexpr();
5006 vpop();
5007 nocode_wanted = saved_nocode_wanted;
5009 skip(':');
5010 expr_cond();
5013 else {
5014 if (vtop != vstack) {
5015 /* needed to avoid having different registers saved in
5016 each branch */
5017 if (is_float(vtop->type.t)) {
5018 rc = RC_FLOAT;
5019 #ifdef TCC_TARGET_X86_64
5020 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
5021 rc = RC_ST0;
5023 #endif
5025 else
5026 rc = RC_INT;
5027 gv(rc);
5028 save_regs(1);
5030 if (tok == ':' && gnu_ext) {
5031 gv_dup();
5032 tt = gvtst(1, 0);
5033 } else {
5034 tt = gvtst(1, 0);
5035 gexpr();
5037 type1 = vtop->type;
5038 sv = *vtop; /* save value to handle it later */
5039 vtop--; /* no vpop so that FP stack is not flushed */
5040 skip(':');
5041 u = gjmp(0);
5042 gsym(tt);
5043 expr_cond();
5044 type2 = vtop->type;
5046 t1 = type1.t;
5047 bt1 = t1 & VT_BTYPE;
5048 t2 = type2.t;
5049 bt2 = t2 & VT_BTYPE;
5050 /* cast operands to correct type according to ISOC rules */
5051 if (is_float(bt1) || is_float(bt2)) {
5052 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
5053 type.t = VT_LDOUBLE;
5054 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
5055 type.t = VT_DOUBLE;
5056 } else {
5057 type.t = VT_FLOAT;
5059 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
5060 /* cast to biggest op */
5061 type.t = VT_LLONG;
5062 /* convert to unsigned if it does not fit in a long long */
5063 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
5064 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
5065 type.t |= VT_UNSIGNED;
5066 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
5067 /* If one is a null ptr constant the result type
5068 is the other. */
5069 if (is_null_pointer (vtop))
5070 type = type1;
5071 else if (is_null_pointer (&sv))
5072 type = type2;
5073 /* XXX: test pointer compatibility, C99 has more elaborate
5074 rules here. */
5075 else
5076 type = type1;
5077 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
5078 /* XXX: test function pointer compatibility */
5079 type = bt1 == VT_FUNC ? type1 : type2;
5080 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
5081 /* XXX: test structure compatibility */
5082 type = bt1 == VT_STRUCT ? type1 : type2;
5083 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
5084 /* NOTE: as an extension, we accept void on only one side */
5085 type.t = VT_VOID;
5086 } else {
5087 /* integer operations */
5088 type.t = VT_INT;
5089 /* convert to unsigned if it does not fit in an integer */
5090 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
5091 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
5092 type.t |= VT_UNSIGNED;
5094 /* keep structs lvalue by transforming `(expr ? a : b)` to `*(expr ? &a : &b)` so
5095 that `(expr ? a : b).mem` does not error with "lvalue expected" */
5096 islv = (vtop->r & VT_LVAL) && (sv.r & VT_LVAL) && VT_STRUCT == (type.t & VT_BTYPE);
5098 /* now we convert second operand */
5099 gen_cast(&type);
5100 if (islv) {
5101 mk_pointer(&vtop->type);
5102 gaddrof();
5104 else if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
5105 gaddrof();
5106 rc = RC_INT;
5107 if (is_float(type.t)) {
5108 rc = RC_FLOAT;
5109 #ifdef TCC_TARGET_X86_64
5110 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
5111 rc = RC_ST0;
5113 #endif
5114 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
5115 /* for long longs, we use fixed registers to avoid having
5116 to handle a complicated move */
5117 rc = RC_IRET;
5120 r2 = gv(rc);
5121 /* this is horrible, but we must also convert first
5122 operand */
5123 tt = gjmp(0);
5124 gsym(u);
5125 /* put again first value and cast it */
5126 *vtop = sv;
5127 gen_cast(&type);
5128 if (islv) {
5129 mk_pointer(&vtop->type);
5130 gaddrof();
5132 else if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
5133 gaddrof();
5134 r1 = gv(rc);
5135 move_reg(r2, r1, type.t);
5136 vtop->r = r2;
5137 gsym(tt);
5138 if (islv)
5139 indir();
5144 static void expr_eq(void)
5146 int t;
5148 expr_cond();
5149 if (tok == '=' ||
5150 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
5151 tok == TOK_A_XOR || tok == TOK_A_OR ||
5152 tok == TOK_A_SHL || tok == TOK_A_SAR) {
5153 test_lvalue();
5154 t = tok;
5155 next();
5156 if (t == '=') {
5157 expr_eq();
5158 } else {
5159 vdup();
5160 expr_eq();
5161 gen_op(t & 0x7f);
5163 vstore();
5167 ST_FUNC void gexpr(void)
5169 while (1) {
5170 expr_eq();
5171 if (tok != ',')
5172 break;
5173 vpop();
5174 next();
5178 /* parse an expression and return its type without any side effect. */
5179 static void expr_type(CType *type)
5181 int saved_nocode_wanted;
5183 saved_nocode_wanted = nocode_wanted;
5184 nocode_wanted = 1;
5185 gexpr();
5186 *type = vtop->type;
5187 vpop();
5188 nocode_wanted = saved_nocode_wanted;
5191 /* parse a unary expression and return its type without any side
5192 effect. */
5193 static void unary_type(CType *type)
5195 int a;
5197 a = nocode_wanted;
5198 nocode_wanted = 1;
5199 unary();
5200 *type = vtop->type;
5201 vpop();
5202 nocode_wanted = a;
5205 /* parse a constant expression and return value in vtop. */
5206 static void expr_const1(void)
5208 int a;
5209 a = const_wanted;
5210 const_wanted = 1;
5211 expr_cond();
5212 const_wanted = a;
5215 /* parse an integer constant and return its value. */
5216 ST_FUNC int expr_const(void)
5218 int c;
5219 expr_const1();
5220 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
5221 expect("constant expression");
5222 c = vtop->c.i;
5223 vpop();
5224 return c;
5227 /* return the label token if current token is a label, otherwise
5228 return zero */
5229 static int is_label(void)
5231 int last_tok;
5233 /* fast test first */
5234 if (tok < TOK_UIDENT)
5235 return 0;
5236 /* no need to save tokc because tok is an identifier */
5237 last_tok = tok;
5238 next();
5239 if (tok == ':') {
5240 next();
5241 return last_tok;
5242 } else {
5243 unget_tok(last_tok);
5244 return 0;
5248 static void label_or_decl(int l)
5250 int last_tok;
5252 /* fast test first */
5253 if (tok >= TOK_UIDENT)
5255 /* no need to save tokc because tok is an identifier */
5256 last_tok = tok;
5257 next();
5258 if (tok == ':') {
5259 unget_tok(last_tok);
5260 return;
5262 unget_tok(last_tok);
5264 decl(l);
5267 static int case_cmp(const void *pa, const void *pb)
5269 int a = (*(struct case_t**) pa)->v1;
5270 int b = (*(struct case_t**) pb)->v1;
5271 return a < b ? -1 : a > b;
5274 static int gcase(struct case_t **base, int len, int case_reg, int *bsym)
5276 struct case_t *p;
5277 int e;
5278 while (len > 4) {
5279 /* binary search */
5280 p = base[len/2];
5281 vseti(case_reg, 0);
5282 vdup();
5283 vpushi(p->v2);
5284 gen_op(TOK_LE);
5285 e = gtst(1, 0);
5286 case_reg = gv(RC_INT);
5287 vpop();
5288 vseti(case_reg, 0);
5289 vdup();
5290 vpushi(p->v1);
5291 gen_op(TOK_GE);
5292 gtst_addr(0, p->sym); /* v1 <= x <= v2 */
5293 case_reg = gv(RC_INT);
5294 vpop();
5295 /* x < v1 */
5296 case_reg = gcase(base, len/2, case_reg, bsym);
5297 if (cur_switch->def_sym)
5298 gjmp_addr(cur_switch->def_sym);
5299 else
5300 *bsym = gjmp(*bsym);
5301 /* x > v2 */
5302 gsym(e);
5303 e = len/2 + 1;
5304 base += e; len -= e;
5306 /* linear scan */
5307 while (len--) {
5308 p = *base++;
5309 vseti(case_reg, 0);
5310 vdup();
5311 vpushi(p->v2);
5312 if (p->v1 == p->v2) {
5313 gen_op(TOK_EQ);
5314 gtst_addr(0, p->sym);
5315 } else {
5316 gen_op(TOK_LE);
5317 e = gtst(1, 0);
5318 case_reg = gv(RC_INT);
5319 vpop();
5320 vseti(case_reg, 0);
5321 vdup();
5322 vpushi(p->v1);
5323 gen_op(TOK_GE);
5324 gtst_addr(0, p->sym);
5325 gsym(e);
5327 case_reg = gv(RC_INT);
5328 vpop();
5330 return case_reg;
5333 static void block(int *bsym, int *csym, int is_expr)
5335 int a, b, c, d;
5336 Sym *s;
5338 /* generate line number info */
5339 if (tcc_state->do_debug &&
5340 (last_line_num != file->line_num || last_ind != ind)) {
5341 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
5342 last_ind = ind;
5343 last_line_num = file->line_num;
5346 if (is_expr) {
5347 /* default return value is (void) */
5348 vpushi(0);
5349 vtop->type.t = VT_VOID;
5352 if (tok == TOK_IF) {
5353 /* if test */
5354 next();
5355 skip('(');
5356 gexpr();
5357 skip(')');
5358 a = gvtst(1, 0);
5359 block(bsym, csym, 0);
5360 c = tok;
5361 if (c == TOK_ELSE) {
5362 next();
5363 d = gjmp(0);
5364 gsym(a);
5365 block(bsym, csym, 0);
5366 gsym(d); /* patch else jmp */
5367 } else
5368 gsym(a);
5369 } else if (tok == TOK_WHILE) {
5370 next();
5371 d = ind;
5372 vla_sp_restore();
5373 skip('(');
5374 gexpr();
5375 skip(')');
5376 a = gvtst(1, 0);
5377 b = 0;
5378 ++local_scope;
5379 block(&a, &b, 0);
5380 --local_scope;
5381 if(!nocode_wanted)
5382 gjmp_addr(d);
5383 gsym(a);
5384 gsym_addr(b, d);
5385 } else if (tok == '{') {
5386 Sym *llabel;
5387 int block_vla_sp_loc = vla_sp_loc, saved_vlas_in_scope = vlas_in_scope;
5389 next();
5390 /* record local declaration stack position */
5391 s = local_stack;
5392 llabel = local_label_stack;
5393 ++local_scope;
5395 /* handle local labels declarations */
5396 if (tok == TOK_LABEL) {
5397 next();
5398 for(;;) {
5399 if (tok < TOK_UIDENT)
5400 expect("label identifier");
5401 label_push(&local_label_stack, tok, LABEL_DECLARED);
5402 next();
5403 if (tok == ',') {
5404 next();
5405 } else {
5406 skip(';');
5407 break;
5411 while (tok != '}') {
5412 label_or_decl(VT_LOCAL);
5413 if (tok != '}') {
5414 if (is_expr)
5415 vpop();
5416 block(bsym, csym, is_expr);
5419 /* pop locally defined labels */
5420 label_pop(&local_label_stack, llabel);
5421 /* pop locally defined symbols */
5422 --local_scope;
5423 /* In the is_expr case (a statement expression is finished here),
5424 vtop might refer to symbols on the local_stack. Either via the
5425 type or via vtop->sym. We can't pop those nor any that in turn
5426 might be referred to. To make it easier we don't roll back
5427 any symbols in that case; some upper level call to block() will
5428 do that. We do have to remove such symbols from the lookup
5429 tables, though. sym_pop will do that. */
5430 sym_pop(&local_stack, s, is_expr);
5432 /* Pop VLA frames and restore stack pointer if required */
5433 if (vlas_in_scope > saved_vlas_in_scope) {
5434 vla_sp_loc = saved_vlas_in_scope ? block_vla_sp_loc : vla_sp_root_loc;
5435 vla_sp_restore();
5437 vlas_in_scope = saved_vlas_in_scope;
5439 next();
5440 } else if (tok == TOK_RETURN) {
5441 next();
5442 if (tok != ';') {
5443 gexpr();
5444 gen_assign_cast(&func_vt);
5445 #ifdef TCC_TARGET_ARM64
5446 // Perhaps it would be better to use this for all backends:
5447 greturn();
5448 #else
5449 if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
5450 CType type, ret_type;
5451 int ret_align, ret_nregs, regsize;
5452 ret_nregs = gfunc_sret(&func_vt, func_var, &ret_type,
5453 &ret_align, &regsize);
5454 if (0 == ret_nregs) {
5455 /* if returning structure, must copy it to implicit
5456 first pointer arg location */
5457 type = func_vt;
5458 mk_pointer(&type);
5459 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
5460 indir();
5461 vswap();
5462 /* copy structure value to pointer */
5463 vstore();
5464 } else {
5465 /* returning structure packed into registers */
5466 int r, size, addr, align;
5467 size = type_size(&func_vt,&align);
5468 if ((vtop->r != (VT_LOCAL | VT_LVAL) ||
5469 (vtop->c.i & (ret_align-1)))
5470 && (align & (ret_align-1))) {
5471 loc = (loc - size) & -ret_align;
5472 addr = loc;
5473 type = func_vt;
5474 vset(&type, VT_LOCAL | VT_LVAL, addr);
5475 vswap();
5476 vstore();
5477 vpop();
5478 vset(&ret_type, VT_LOCAL | VT_LVAL, addr);
5480 vtop->type = ret_type;
5481 if (is_float(ret_type.t))
5482 r = rc_fret(ret_type.t);
5483 else
5484 r = RC_IRET;
5486 if (ret_nregs == 1)
5487 gv(r);
5488 else {
5489 for (;;) {
5490 vdup();
5491 gv(r);
5492 vpop();
5493 if (--ret_nregs == 0)
5494 break;
5495 /* We assume that when a structure is returned in multiple
5496 registers, their classes are consecutive values of the
5497 suite s(n) = 2^n */
5498 r <<= 1;
5499 vtop->c.i += regsize;
5503 } else if (is_float(func_vt.t)) {
5504 gv(rc_fret(func_vt.t));
5505 } else {
5506 gv(RC_IRET);
5508 #endif
5509 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
5511 skip(';');
5512 /* jump unless last stmt in top-level block */
5513 if (tok != '}' || local_scope != 1)
5514 rsym = gjmp(rsym);
5515 } else if (tok == TOK_BREAK) {
5516 /* compute jump */
5517 if (!bsym)
5518 tcc_error("cannot break");
5519 *bsym = gjmp(*bsym);
5520 next();
5521 skip(';');
5522 } else if (tok == TOK_CONTINUE) {
5523 /* compute jump */
5524 if (!csym)
5525 tcc_error("cannot continue");
5526 vla_sp_restore_root();
5527 *csym = gjmp(*csym);
5528 next();
5529 skip(';');
5530 } else if (tok == TOK_FOR) {
5531 int e;
5532 next();
5533 skip('(');
5534 s = local_stack;
5535 ++local_scope;
5536 if (tok != ';') {
5537 /* c99 for-loop init decl? */
5538 if (!decl0(VT_LOCAL, 1)) {
5539 /* no, regular for-loop init expr */
5540 gexpr();
5541 vpop();
5544 skip(';');
5545 d = ind;
5546 c = ind;
5547 vla_sp_restore();
5548 a = 0;
5549 b = 0;
5550 if (tok != ';') {
5551 gexpr();
5552 a = gvtst(1, 0);
5554 skip(';');
5555 if (tok != ')') {
5556 e = gjmp(0);
5557 c = ind;
5558 vla_sp_restore();
5559 gexpr();
5560 vpop();
5561 gjmp_addr(d);
5562 gsym(e);
5564 skip(')');
5565 block(&a, &b, 0);
5566 if(!nocode_wanted)
5567 gjmp_addr(c);
5568 gsym(a);
5569 gsym_addr(b, c);
5570 --local_scope;
5571 sym_pop(&local_stack, s, 0);
5573 } else
5574 if (tok == TOK_DO) {
5575 next();
5576 a = 0;
5577 b = 0;
5578 d = ind;
5579 vla_sp_restore();
5580 block(&a, &b, 0);
5581 skip(TOK_WHILE);
5582 skip('(');
5583 gsym(b);
5584 gexpr();
5585 c = gvtst(0, 0);
5586 gsym_addr(c, d);
5587 skip(')');
5588 gsym(a);
5589 skip(';');
5590 } else
5591 if (tok == TOK_SWITCH) {
5592 struct switch_t *saved, sw;
5593 next();
5594 skip('(');
5595 gexpr();
5596 /* XXX: other types than integer */
5597 c = gv(RC_INT);
5598 vpop();
5599 skip(')');
5600 a = 0;
5601 b = gjmp(0); /* jump to first case */
5602 sw.p = NULL; sw.n = 0; sw.def_sym = 0;
5603 saved = cur_switch;
5604 cur_switch = &sw;
5605 block(&a, csym, 0);
5606 a = gjmp(a); /* add implicit break */
5607 /* case lookup */
5608 gsym(b);
5609 qsort(sw.p, sw.n, sizeof(void*), case_cmp);
5610 for (b = 1; b < sw.n; b++)
5611 if (sw.p[b - 1]->v2 >= sw.p[b]->v1)
5612 tcc_error("duplicate case value");
5613 gcase(sw.p, sw.n, c, &a);
5614 if (sw.def_sym)
5615 gjmp_addr(sw.def_sym);
5616 dynarray_reset(&sw.p, &sw.n);
5617 cur_switch = saved;
5618 /* break label */
5619 gsym(a);
5620 } else
5621 if (tok == TOK_CASE) {
5622 struct case_t *cr = tcc_malloc(sizeof(struct case_t));
5623 if (!cur_switch)
5624 expect("switch");
5625 next();
5626 cr->v1 = cr->v2 = expr_const();
5627 if (gnu_ext && tok == TOK_DOTS) {
5628 next();
5629 cr->v2 = expr_const();
5630 if (cr->v2 < cr->v1)
5631 tcc_warning("empty case range");
5633 cr->sym = ind;
5634 dynarray_add((void***) &cur_switch->p, &cur_switch->n, cr);
5635 skip(':');
5636 is_expr = 0;
5637 goto block_after_label;
5638 } else
5639 if (tok == TOK_DEFAULT) {
5640 next();
5641 skip(':');
5642 if (!cur_switch)
5643 expect("switch");
5644 if (cur_switch->def_sym)
5645 tcc_error("too many 'default'");
5646 cur_switch->def_sym = ind;
5647 is_expr = 0;
5648 goto block_after_label;
5649 } else
5650 if (tok == TOK_GOTO) {
5651 next();
5652 if (tok == '*' && gnu_ext) {
5653 /* computed goto */
5654 next();
5655 gexpr();
5656 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
5657 expect("pointer");
5658 ggoto();
5659 } else if (tok >= TOK_UIDENT) {
5660 s = label_find(tok);
5661 /* put forward definition if needed */
5662 if (!s) {
5663 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
5664 } else {
5665 if (s->r == LABEL_DECLARED)
5666 s->r = LABEL_FORWARD;
5668 vla_sp_restore_root();
5669 if (s->r & LABEL_FORWARD)
5670 s->jnext = gjmp(s->jnext);
5671 else
5672 gjmp_addr(s->jnext);
5673 next();
5674 } else {
5675 expect("label identifier");
5677 skip(';');
5678 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
5679 asm_instr();
5680 } else {
5681 b = is_label();
5682 if (b) {
5683 /* label case */
5684 s = label_find(b);
5685 if (s) {
5686 if (s->r == LABEL_DEFINED)
5687 tcc_error("duplicate label '%s'", get_tok_str(s->v, NULL));
5688 gsym(s->jnext);
5689 s->r = LABEL_DEFINED;
5690 } else {
5691 s = label_push(&global_label_stack, b, LABEL_DEFINED);
5693 s->jnext = ind;
5694 vla_sp_restore();
5695 /* we accept this, but it is a mistake */
5696 block_after_label:
5697 if (tok == '}') {
5698 tcc_warning("deprecated use of label at end of compound statement");
5699 } else {
5700 if (is_expr)
5701 vpop();
5702 block(bsym, csym, is_expr);
5704 } else {
5705 /* expression case */
5706 if (tok != ';') {
5707 if (is_expr) {
5708 vpop();
5709 gexpr();
5710 } else {
5711 gexpr();
5712 vpop();
5715 skip(';');
5720 #define EXPR_CONST 1
5721 #define EXPR_ANY 2
5723 static void parse_init_elem(int expr_type)
5725 int saved_global_expr;
5726 switch(expr_type) {
5727 case EXPR_CONST:
5728 /* compound literals must be allocated globally in this case */
5729 saved_global_expr = global_expr;
5730 global_expr = 1;
5731 expr_const1();
5732 global_expr = saved_global_expr;
5733 /* NOTE: symbols are accepted */
5734 if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
5735 tcc_error("initializer element is not constant");
5736 break;
5737 case EXPR_ANY:
5738 expr_eq();
5739 break;
5743 /* t is the array or struct type. c is the array or struct
5744 address. cur_field is the pointer to the current
5745 value, for arrays the 'c' member contains the current start
5746 index and the 'r' contains the end index (in case of range init).
5747 'size_only' is true if only size info is needed (only used
5748 in arrays) */
5749 static void decl_designator(CType *type, Section *sec, unsigned long c,
5750 Sym **cur_field, int size_only)
5752 Sym *s, *f;
5753 int notfirst, index, index_last, align, l, nb_elems, elem_size;
5754 CType type1;
5756 notfirst = 0;
5757 elem_size = 0;
5758 nb_elems = 1;
5759 if (gnu_ext && (l = is_label()) != 0)
5760 goto struct_field;
5761 while (tok == '[' || tok == '.') {
5762 if (tok == '[') {
5763 if (!(type->t & VT_ARRAY))
5764 expect("array type");
5765 s = type->ref;
5766 next();
5767 index = expr_const();
5768 if (index < 0 || (s->c >= 0 && index >= s->c))
5769 tcc_error("invalid index");
5770 if (tok == TOK_DOTS && gnu_ext) {
5771 next();
5772 index_last = expr_const();
5773 if (index_last < 0 ||
5774 (s->c >= 0 && index_last >= s->c) ||
5775 index_last < index)
5776 tcc_error("invalid index");
5777 } else {
5778 index_last = index;
5780 skip(']');
5781 if (!notfirst) {
5782 (*cur_field)->c = index;
5783 (*cur_field)->r = index_last;
5785 type = pointed_type(type);
5786 elem_size = type_size(type, &align);
5787 c += index * elem_size;
5788 /* NOTE: we only support ranges for last designator */
5789 nb_elems = index_last - index + 1;
5790 if (nb_elems != 1) {
5791 notfirst = 1;
5792 break;
5794 } else {
5795 next();
5796 l = tok;
5797 next();
5798 struct_field:
5799 if ((type->t & VT_BTYPE) != VT_STRUCT)
5800 expect("struct/union type");
5801 f = find_field(type, l);
5802 if (!f)
5803 expect("field");
5804 if (!notfirst)
5805 *cur_field = f;
5806 /* XXX: fix this mess by using explicit storage field */
5807 type1 = f->type;
5808 type1.t |= (type->t & ~VT_TYPE);
5809 type = &type1;
5810 c += f->c;
5812 notfirst = 1;
5814 if (notfirst) {
5815 if (tok == '=') {
5816 next();
5817 } else {
5818 if (!gnu_ext)
5819 expect("=");
5821 } else {
5822 if (type->t & VT_ARRAY) {
5823 index = (*cur_field)->c;
5824 if (type->ref->c >= 0 && index >= type->ref->c)
5825 tcc_error("index too large");
5826 type = pointed_type(type);
5827 c += index * type_size(type, &align);
5828 } else {
5829 f = *cur_field;
5830 if (!f)
5831 tcc_error("too many field init");
5832 /* XXX: fix this mess by using explicit storage field */
5833 type1 = f->type;
5834 type1.t |= (type->t & ~VT_TYPE);
5835 type = &type1;
5836 c += f->c;
5839 decl_initializer(type, sec, c, 0, size_only);
5841 /* XXX: make it more general */
5842 if (!size_only && nb_elems > 1) {
5843 unsigned long c_end;
5844 uint8_t *src, *dst;
5845 int i;
5847 if (!sec) {
5848 vset(type, VT_LOCAL|VT_LVAL, c);
5849 for (i = 1; i < nb_elems; i++) {
5850 vset(type, VT_LOCAL|VT_LVAL, c + elem_size * i);
5851 vswap();
5852 vstore();
5854 vpop();
5855 } else {
5856 c_end = c + nb_elems * elem_size;
5857 if (c_end > sec->data_allocated)
5858 section_realloc(sec, c_end);
5859 src = sec->data + c;
5860 dst = src;
5861 for(i = 1; i < nb_elems; i++) {
5862 dst += elem_size;
5863 memcpy(dst, src, elem_size);
5869 /* store a value or an expression directly in global data or in local array */
5870 static void init_putv(CType *type, Section *sec, unsigned long c)
5872 int bt, bit_pos, bit_size;
5873 void *ptr;
5874 unsigned long long bit_mask;
5875 CType dtype;
5877 dtype = *type;
5878 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
5880 if (sec) {
5881 int size, align;
5882 /* XXX: not portable */
5883 /* XXX: generate error if incorrect relocation */
5884 gen_assign_cast(&dtype);
5885 bt = type->t & VT_BTYPE;
5886 size = type_size(type, &align);
5887 if (c + size > sec->data_allocated) {
5888 section_realloc(sec, c + size);
5890 ptr = sec->data + c;
5891 /* XXX: make code faster ? */
5892 if (!(type->t & VT_BITFIELD)) {
5893 bit_pos = 0;
5894 bit_size = PTR_SIZE * 8;
5895 bit_mask = -1LL;
5896 } else {
5897 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5898 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
5899 bit_mask = (1LL << bit_size) - 1;
5901 if ((vtop->r & (VT_SYM|VT_CONST)) == (VT_SYM|VT_CONST) &&
5902 vtop->sym->v >= SYM_FIRST_ANOM &&
5903 /* XXX This rejects compount literals like
5904 '(void *){ptr}'. The problem is that '&sym' is
5905 represented the same way, which would be ruled out
5906 by the SYM_FIRST_ANOM check above, but also '"string"'
5907 in 'char *p = "string"' is represented the same
5908 with the type being VT_PTR and the symbol being an
5909 anonymous one. That is, there's no difference in vtop
5910 between '(void *){x}' and '&(void *){x}'. Ignore
5911 pointer typed entities here. Hopefully no real code
5912 will every use compound literals with scalar type. */
5913 (vtop->type.t & VT_BTYPE) != VT_PTR) {
5914 /* These come from compound literals, memcpy stuff over. */
5915 Section *ssec;
5916 ElfW(Sym) *esym;
5917 esym = &((ElfW(Sym) *)symtab_section->data)[vtop->sym->c];
5918 ssec = tcc_state->sections[esym->st_shndx];
5919 memmove (ptr, ssec->data + esym->st_value, size);
5920 } else {
5921 if ((vtop->r & VT_SYM) &&
5922 (bt == VT_BYTE ||
5923 bt == VT_SHORT ||
5924 bt == VT_DOUBLE ||
5925 bt == VT_LDOUBLE ||
5926 #if PTR_SIZE == 8
5927 (bt == VT_LLONG && bit_size != 64) ||
5928 bt == VT_INT
5929 #else
5930 bt == VT_LLONG ||
5931 (bt == VT_INT && bit_size != 32)
5932 #endif
5934 tcc_error("initializer element is not computable at load time");
5935 switch(bt) {
5936 /* XXX: when cross-compiling we assume that each type has the
5937 same representation on host and target, which is likely to
5938 be wrong in the case of long double */
5939 case VT_BOOL:
5940 vtop->c.i = (vtop->c.i != 0);
5941 case VT_BYTE:
5942 *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5943 break;
5944 case VT_SHORT:
5945 *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5946 break;
5947 case VT_DOUBLE:
5948 *(double *)ptr = vtop->c.d;
5949 break;
5950 case VT_LDOUBLE:
5951 if (sizeof(long double) == LDOUBLE_SIZE)
5952 *(long double *)ptr = vtop->c.ld;
5953 else if (sizeof(double) == LDOUBLE_SIZE)
5954 *(double *)ptr = vtop->c.ld;
5955 else
5956 tcc_error("can't cross compile long double constants");
5957 break;
5958 #if PTR_SIZE != 8
5959 case VT_LLONG:
5960 *(long long *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5961 break;
5962 #else
5963 case VT_LLONG:
5964 #endif
5965 case VT_PTR:
5967 addr_t val = (vtop->c.i & bit_mask) << bit_pos;
5968 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
5969 if (vtop->r & VT_SYM)
5970 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
5971 else
5972 *(addr_t *)ptr |= val;
5973 #else
5974 if (vtop->r & VT_SYM)
5975 greloc(sec, vtop->sym, c, R_DATA_PTR);
5976 *(addr_t *)ptr |= val;
5977 #endif
5978 break;
5980 default:
5982 int val = (vtop->c.i & bit_mask) << bit_pos;
5983 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
5984 if (vtop->r & VT_SYM)
5985 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
5986 else
5987 *(int *)ptr |= val;
5988 #else
5989 if (vtop->r & VT_SYM)
5990 greloc(sec, vtop->sym, c, R_DATA_PTR);
5991 *(int *)ptr |= val;
5992 #endif
5993 break;
5997 vtop--;
5998 } else {
5999 vset(&dtype, VT_LOCAL|VT_LVAL, c);
6000 vswap();
6001 vstore();
6002 vpop();
6006 /* put zeros for variable based init */
6007 static void init_putz(Section *sec, unsigned long c, int size)
6009 if (sec) {
6010 /* nothing to do because globals are already set to zero */
6011 } else {
6012 vpush_global_sym(&func_old_type, TOK_memset);
6013 vseti(VT_LOCAL, c);
6014 #ifdef TCC_TARGET_ARM
6015 vpushs(size);
6016 vpushi(0);
6017 #else
6018 vpushi(0);
6019 vpushs(size);
6020 #endif
6021 gfunc_call(3);
6025 /* 't' contains the type and storage info. 'c' is the offset of the
6026 object in section 'sec'. If 'sec' is NULL, it means stack based
6027 allocation. 'first' is true if array '{' must be read (multi
6028 dimension implicit array init handling). 'size_only' is true if
6029 size only evaluation is wanted (only for arrays). */
6030 static void decl_initializer(CType *type, Section *sec, unsigned long c,
6031 int first, int size_only)
6033 int index, array_length, n, no_oblock, nb, parlevel, parlevel1, i;
6034 int size1, align1;
6035 int have_elem;
6036 Sym *s, *f;
6037 Sym indexsym;
6038 CType *t1;
6040 /* If we currently are at an '}' or ',' we have read an initializer
6041 element in one of our callers, and not yet consumed it. */
6042 have_elem = tok == '}' || tok == ',';
6043 if (!have_elem && tok != '{' &&
6044 /* In case of strings we have special handling for arrays, so
6045 don't consume them as initializer value (which would commit them
6046 to some anonymous symbol). */
6047 tok != TOK_LSTR && tok != TOK_STR &&
6048 !size_only) {
6049 parse_init_elem(!sec ? EXPR_ANY : EXPR_CONST);
6050 have_elem = 1;
6053 if (have_elem &&
6054 !(type->t & VT_ARRAY) &&
6055 /* Use i_c_parameter_t, to strip toplevel qualifiers.
6056 The source type might have VT_CONSTANT set, which is
6057 of course assignable to non-const elements. */
6058 is_compatible_parameter_types(type, &vtop->type)) {
6059 init_putv(type, sec, c);
6060 } else if (type->t & VT_ARRAY) {
6061 s = type->ref;
6062 n = s->c;
6063 array_length = 0;
6064 t1 = pointed_type(type);
6065 size1 = type_size(t1, &align1);
6067 no_oblock = 1;
6068 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
6069 tok == '{') {
6070 if (tok != '{')
6071 tcc_error("character array initializer must be a literal,"
6072 " optionally enclosed in braces");
6073 skip('{');
6074 no_oblock = 0;
6077 /* only parse strings here if correct type (otherwise: handle
6078 them as ((w)char *) expressions */
6079 if ((tok == TOK_LSTR &&
6080 #ifdef TCC_TARGET_PE
6081 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
6082 #else
6083 (t1->t & VT_BTYPE) == VT_INT
6084 #endif
6085 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
6086 while (tok == TOK_STR || tok == TOK_LSTR) {
6087 int cstr_len, ch;
6089 /* compute maximum number of chars wanted */
6090 if (tok == TOK_STR)
6091 cstr_len = tokc.str.size;
6092 else
6093 cstr_len = tokc.str.size / sizeof(nwchar_t);
6094 cstr_len--;
6095 nb = cstr_len;
6096 if (n >= 0 && nb > (n - array_length))
6097 nb = n - array_length;
6098 if (!size_only) {
6099 if (cstr_len > nb)
6100 tcc_warning("initializer-string for array is too long");
6101 /* in order to go faster for common case (char
6102 string in global variable, we handle it
6103 specifically */
6104 if (sec && tok == TOK_STR && size1 == 1) {
6105 memcpy(sec->data + c + array_length, tokc.str.data, nb);
6106 } else {
6107 for(i=0;i<nb;i++) {
6108 if (tok == TOK_STR)
6109 ch = ((unsigned char *)tokc.str.data)[i];
6110 else
6111 ch = ((nwchar_t *)tokc.str.data)[i];
6112 vpushi(ch);
6113 init_putv(t1, sec, c + (array_length + i) * size1);
6117 array_length += nb;
6118 next();
6120 /* only add trailing zero if enough storage (no
6121 warning in this case since it is standard) */
6122 if (n < 0 || array_length < n) {
6123 if (!size_only) {
6124 vpushi(0);
6125 init_putv(t1, sec, c + (array_length * size1));
6127 array_length++;
6129 } else {
6130 indexsym.c = 0;
6131 indexsym.r = 0;
6132 f = &indexsym;
6134 do_init_list:
6135 while (tok != '}' || have_elem) {
6136 decl_designator(type, sec, c, &f, size_only);
6137 have_elem = 0;
6138 index = f->c;
6139 /* must put zero in holes (note that doing it that way
6140 ensures that it even works with designators) */
6141 if (!size_only && array_length < index) {
6142 init_putz(sec, c + array_length * size1,
6143 (index - array_length) * size1);
6145 if (type->t & VT_ARRAY) {
6146 index = indexsym.c = ++indexsym.r;
6147 } else {
6148 index = index + type_size(&f->type, &align1);
6149 if (s->type.t == TOK_UNION)
6150 f = NULL;
6151 else
6152 f = f->next;
6154 if (index > array_length)
6155 array_length = index;
6157 if (type->t & VT_ARRAY) {
6158 /* special test for multi dimensional arrays (may not
6159 be strictly correct if designators are used at the
6160 same time) */
6161 if (no_oblock && index >= n)
6162 break;
6163 } else {
6164 if (no_oblock && f == NULL)
6165 break;
6167 if (tok == '}')
6168 break;
6169 skip(',');
6172 /* put zeros at the end */
6173 if (!size_only && array_length < n) {
6174 init_putz(sec, c + array_length * size1,
6175 (n - array_length) * size1);
6177 if (!no_oblock)
6178 skip('}');
6179 /* patch type size if needed, which happens only for array types */
6180 if (n < 0)
6181 s->c = array_length;
6182 } else if ((type->t & VT_BTYPE) == VT_STRUCT) {
6183 size1 = 1;
6184 no_oblock = 1;
6185 if (first || tok == '{') {
6186 skip('{');
6187 no_oblock = 0;
6189 s = type->ref;
6190 f = s->next;
6191 array_length = 0;
6192 n = s->c;
6193 goto do_init_list;
6194 } else if (tok == '{') {
6195 next();
6196 decl_initializer(type, sec, c, first, size_only);
6197 skip('}');
6198 } else if (size_only) {
6199 /* If we supported only ISO C we wouldn't have to accept calling
6200 this on anything than an array size_only==1 (and even then
6201 only on the outermost level, so no recursion would be needed),
6202 because initializing a flex array member isn't supported.
6203 But GNU C supports it, so we need to recurse even into
6204 subfields of structs and arrays when size_only is set. */
6205 /* just skip expression */
6206 parlevel = parlevel1 = 0;
6207 while ((parlevel > 0 || parlevel1 > 0 ||
6208 (tok != '}' && tok != ',')) && tok != -1) {
6209 if (tok == '(')
6210 parlevel++;
6211 else if (tok == ')') {
6212 if (parlevel == 0 && parlevel1 == 0)
6213 break;
6214 parlevel--;
6216 else if (tok == '{')
6217 parlevel1++;
6218 else if (tok == '}') {
6219 if (parlevel == 0 && parlevel1 == 0)
6220 break;
6221 parlevel1--;
6223 next();
6225 } else {
6226 if (!have_elem) {
6227 /* This should happen only when we haven't parsed
6228 the init element above for fear of committing a
6229 string constant to memory too early. */
6230 if (tok != TOK_STR && tok != TOK_LSTR)
6231 expect("string constant");
6232 parse_init_elem(!sec ? EXPR_ANY : EXPR_CONST);
6234 init_putv(type, sec, c);
6238 /* parse an initializer for type 't' if 'has_init' is non zero, and
6239 allocate space in local or global data space ('r' is either
6240 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
6241 variable 'v' of scope 'scope' is declared before initializers
6242 are parsed. If 'v' is zero, then a reference to the new object
6243 is put in the value stack. If 'has_init' is 2, a special parsing
6244 is done to handle string constants. */
6245 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
6246 int has_init, int v, int scope)
6248 int size, align, addr, data_offset;
6249 int level;
6250 ParseState saved_parse_state = {0};
6251 TokenString *init_str = NULL;
6252 Section *sec;
6253 Sym *flexible_array;
6255 flexible_array = NULL;
6256 if ((type->t & VT_BTYPE) == VT_STRUCT) {
6257 Sym *field = type->ref->next;
6258 if (field) {
6259 while (field->next)
6260 field = field->next;
6261 if (field->type.t & VT_ARRAY && field->type.ref->c < 0)
6262 flexible_array = field;
6266 size = type_size(type, &align);
6267 /* If unknown size, we must evaluate it before
6268 evaluating initializers because
6269 initializers can generate global data too
6270 (e.g. string pointers or ISOC99 compound
6271 literals). It also simplifies local
6272 initializers handling */
6273 if (size < 0 || (flexible_array && has_init)) {
6274 if (!has_init)
6275 tcc_error("unknown type size");
6276 /* get all init string */
6277 init_str = tok_str_alloc();
6278 if (has_init == 2) {
6279 /* only get strings */
6280 while (tok == TOK_STR || tok == TOK_LSTR) {
6281 tok_str_add_tok(init_str);
6282 next();
6284 } else {
6285 level = 0;
6286 while (level > 0 || (tok != ',' && tok != ';')) {
6287 if (tok < 0)
6288 tcc_error("unexpected end of file in initializer");
6289 tok_str_add_tok(init_str);
6290 if (tok == '{')
6291 level++;
6292 else if (tok == '}') {
6293 level--;
6294 if (level <= 0) {
6295 next();
6296 break;
6299 next();
6302 tok_str_add(init_str, -1);
6303 tok_str_add(init_str, 0);
6305 /* compute size */
6306 save_parse_state(&saved_parse_state);
6308 begin_macro(init_str, 1);
6309 next();
6310 decl_initializer(type, NULL, 0, 1, 1);
6311 /* prepare second initializer parsing */
6312 macro_ptr = init_str->str;
6313 next();
6315 /* if still unknown size, error */
6316 size = type_size(type, &align);
6317 if (size < 0)
6318 tcc_error("unknown type size");
6320 /* If there's a flex member and it was used in the initializer
6321 adjust size. */
6322 if (flexible_array &&
6323 flexible_array->type.ref->c > 0)
6324 size += flexible_array->type.ref->c
6325 * pointed_size(&flexible_array->type);
6326 /* take into account specified alignment if bigger */
6327 if (ad->a.aligned) {
6328 if (ad->a.aligned > align)
6329 align = ad->a.aligned;
6330 } else if (ad->a.packed) {
6331 align = 1;
6333 if ((r & VT_VALMASK) == VT_LOCAL) {
6334 sec = NULL;
6335 #ifdef CONFIG_TCC_BCHECK
6336 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
6337 loc--;
6339 #endif
6340 loc = (loc - size) & -align;
6341 addr = loc;
6342 #ifdef CONFIG_TCC_BCHECK
6343 /* handles bounds */
6344 /* XXX: currently, since we do only one pass, we cannot track
6345 '&' operators, so we add only arrays */
6346 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
6347 addr_t *bounds_ptr;
6348 /* add padding between regions */
6349 loc--;
6350 /* then add local bound info */
6351 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(addr_t));
6352 bounds_ptr[0] = addr;
6353 bounds_ptr[1] = size;
6355 #endif
6356 if (v) {
6357 /* local variable */
6358 sym_push(v, type, r, addr);
6359 } else {
6360 /* push local reference */
6361 vset(type, r, addr);
6363 } else {
6364 Sym *sym;
6366 sym = NULL;
6367 if (v && scope == VT_CONST) {
6368 /* see if the symbol was already defined */
6369 sym = sym_find(v);
6370 if (sym) {
6371 if (!is_compatible_types(&sym->type, type))
6372 tcc_error("incompatible types for redefinition of '%s'",
6373 get_tok_str(v, NULL));
6374 if (sym->type.t & VT_EXTERN) {
6375 /* if the variable is extern, it was not allocated */
6376 sym->type.t &= ~VT_EXTERN;
6377 /* set array size if it was omitted in extern
6378 declaration */
6379 if ((sym->type.t & VT_ARRAY) &&
6380 sym->type.ref->c < 0 &&
6381 type->ref->c >= 0)
6382 sym->type.ref->c = type->ref->c;
6383 } else {
6384 /* we accept several definitions of the same
6385 global variable. this is tricky, because we
6386 must play with the SHN_COMMON type of the symbol */
6387 /* XXX: should check if the variable was already
6388 initialized. It is incorrect to initialized it
6389 twice */
6390 /* no init data, we won't add more to the symbol */
6391 if (!has_init)
6392 goto no_alloc;
6397 /* allocate symbol in corresponding section */
6398 sec = ad->section;
6399 if (!sec) {
6400 if (has_init)
6401 sec = data_section;
6402 else if (tcc_state->nocommon)
6403 sec = bss_section;
6405 if (sec) {
6406 data_offset = sec->data_offset;
6407 data_offset = (data_offset + align - 1) & -align;
6408 addr = data_offset;
6409 /* very important to increment global pointer at this time
6410 because initializers themselves can create new initializers */
6411 data_offset += size;
6412 #ifdef CONFIG_TCC_BCHECK
6413 /* add padding if bound check */
6414 if (tcc_state->do_bounds_check)
6415 data_offset++;
6416 #endif
6417 sec->data_offset = data_offset;
6418 /* allocate section space to put the data */
6419 if (sec->sh_type != SHT_NOBITS &&
6420 data_offset > sec->data_allocated)
6421 section_realloc(sec, data_offset);
6422 /* align section if needed */
6423 if (align > sec->sh_addralign)
6424 sec->sh_addralign = align;
6425 } else {
6426 addr = 0; /* avoid warning */
6429 if (v) {
6430 if (scope != VT_CONST || !sym) {
6431 sym = sym_push(v, type, r | VT_SYM, 0);
6432 sym->asm_label = ad->asm_label;
6434 /* update symbol definition */
6435 if (sec) {
6436 put_extern_sym(sym, sec, addr, size);
6437 } else {
6438 ElfW(Sym) *esym;
6439 /* put a common area */
6440 put_extern_sym(sym, NULL, align, size);
6441 /* XXX: find a nicer way */
6442 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
6443 esym->st_shndx = SHN_COMMON;
6445 } else {
6446 /* push global reference */
6447 sym = get_sym_ref(type, sec, addr, size);
6448 vpushsym(type, sym);
6450 /* patch symbol weakness */
6451 if (type->t & VT_WEAK)
6452 weaken_symbol(sym);
6453 apply_visibility(sym, type);
6454 #ifdef CONFIG_TCC_BCHECK
6455 /* handles bounds now because the symbol must be defined
6456 before for the relocation */
6457 if (tcc_state->do_bounds_check) {
6458 addr_t *bounds_ptr;
6460 greloc(bounds_section, sym, bounds_section->data_offset, R_DATA_PTR);
6461 /* then add global bound info */
6462 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(addr_t));
6463 bounds_ptr[0] = 0; /* relocated */
6464 bounds_ptr[1] = size;
6466 #endif
6468 if (type->t & VT_VLA) {
6469 int a;
6471 /* save current stack pointer */
6472 if (vlas_in_scope == 0) {
6473 if (vla_sp_root_loc == -1)
6474 vla_sp_root_loc = (loc -= PTR_SIZE);
6475 gen_vla_sp_save(vla_sp_root_loc);
6478 vla_runtime_type_size(type, &a);
6479 gen_vla_alloc(type, a);
6480 gen_vla_sp_save(addr);
6481 vla_sp_loc = addr;
6482 vlas_in_scope++;
6483 } else if (has_init) {
6484 decl_initializer(type, sec, addr, 1, 0);
6485 /* patch flexible array member size back to -1, */
6486 /* for possible subsequent similar declarations */
6487 if (flexible_array)
6488 flexible_array->type.ref->c = -1;
6490 no_alloc: ;
6491 /* restore parse state if needed */
6492 if (init_str) {
6493 end_macro();
6494 restore_parse_state(&saved_parse_state);
6498 static void put_func_debug(Sym *sym)
6500 char buf[512];
6502 /* stabs info */
6503 /* XXX: we put here a dummy type */
6504 snprintf(buf, sizeof(buf), "%s:%c1",
6505 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
6506 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
6507 cur_text_section, sym->c);
6508 /* //gr gdb wants a line at the function */
6509 put_stabn(N_SLINE, 0, file->line_num, 0);
6510 last_ind = 0;
6511 last_line_num = 0;
6514 /* parse an old style function declaration list */
6515 /* XXX: check multiple parameter */
6516 static void func_decl_list(Sym *func_sym)
6518 AttributeDef ad;
6519 int v;
6520 Sym *s;
6521 CType btype, type;
6523 /* parse each declaration */
6524 while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF &&
6525 tok != TOK_ASM1 && tok != TOK_ASM2 && tok != TOK_ASM3) {
6526 if (!parse_btype(&btype, &ad))
6527 expect("declaration list");
6528 if (((btype.t & VT_BTYPE) == VT_ENUM ||
6529 (btype.t & VT_BTYPE) == VT_STRUCT) &&
6530 tok == ';') {
6531 /* we accept no variable after */
6532 } else {
6533 for(;;) {
6534 type = btype;
6535 type_decl(&type, &ad, &v, TYPE_DIRECT);
6536 /* find parameter in function parameter list */
6537 s = func_sym->next;
6538 while (s != NULL) {
6539 if ((s->v & ~SYM_FIELD) == v)
6540 goto found;
6541 s = s->next;
6543 tcc_error("declaration for parameter '%s' but no such parameter",
6544 get_tok_str(v, NULL));
6545 found:
6546 /* check that no storage specifier except 'register' was given */
6547 if (type.t & VT_STORAGE)
6548 tcc_error("storage class specified for '%s'", get_tok_str(v, NULL));
6549 convert_parameter_type(&type);
6550 /* we can add the type (NOTE: it could be local to the function) */
6551 s->type = type;
6552 /* accept other parameters */
6553 if (tok == ',')
6554 next();
6555 else
6556 break;
6559 skip(';');
6563 /* parse a function defined by symbol 'sym' and generate its code in
6564 'cur_text_section' */
6565 static void gen_function(Sym *sym)
6567 int saved_nocode_wanted = nocode_wanted;
6569 nocode_wanted = 0;
6570 ind = cur_text_section->data_offset;
6571 /* NOTE: we patch the symbol size later */
6572 put_extern_sym(sym, cur_text_section, ind, 0);
6573 funcname = get_tok_str(sym->v, NULL);
6574 func_ind = ind;
6575 /* Initialize VLA state */
6576 vla_sp_loc = -1;
6577 vla_sp_root_loc = -1;
6578 /* put debug symbol */
6579 if (tcc_state->do_debug)
6580 put_func_debug(sym);
6582 /* push a dummy symbol to enable local sym storage */
6583 sym_push2(&local_stack, SYM_FIELD, 0, 0);
6584 local_scope = 1; /* for function parameters */
6585 gfunc_prolog(&sym->type);
6586 local_scope = 0;
6588 rsym = 0;
6589 block(NULL, NULL, 0);
6590 gsym(rsym);
6591 gfunc_epilog();
6592 cur_text_section->data_offset = ind;
6593 label_pop(&global_label_stack, NULL);
6594 /* reset local stack */
6595 local_scope = 0;
6596 sym_pop(&local_stack, NULL, 0);
6597 /* end of function */
6598 /* patch symbol size */
6599 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
6600 ind - func_ind;
6601 /* patch symbol weakness (this definition overrules any prototype) */
6602 if (sym->type.t & VT_WEAK)
6603 weaken_symbol(sym);
6604 apply_visibility(sym, &sym->type);
6605 if (tcc_state->do_debug) {
6606 put_stabn(N_FUN, 0, 0, ind - func_ind);
6608 /* It's better to crash than to generate wrong code */
6609 cur_text_section = NULL;
6610 funcname = ""; /* for safety */
6611 func_vt.t = VT_VOID; /* for safety */
6612 func_var = 0; /* for safety */
6613 ind = 0; /* for safety */
6614 nocode_wanted = saved_nocode_wanted;
6615 check_vstack();
6618 static void gen_inline_functions(TCCState *s)
6620 Sym *sym;
6621 int inline_generated, i, ln;
6622 struct InlineFunc *fn;
6624 ln = file->line_num;
6625 /* iterate while inline function are referenced */
6626 for(;;) {
6627 inline_generated = 0;
6628 for (i = 0; i < s->nb_inline_fns; ++i) {
6629 fn = s->inline_fns[i];
6630 sym = fn->sym;
6631 if (sym && sym->c) {
6632 /* the function was used: generate its code and
6633 convert it to a normal function */
6634 fn->sym = NULL;
6635 if (file)
6636 pstrcpy(file->filename, sizeof file->filename, fn->filename);
6637 sym->r = VT_SYM | VT_CONST;
6638 sym->type.t &= ~VT_INLINE;
6640 begin_macro(fn->func_str, 1);
6641 next();
6642 cur_text_section = text_section;
6643 gen_function(sym);
6644 end_macro();
6646 inline_generated = 1;
6649 if (!inline_generated)
6650 break;
6652 file->line_num = ln;
6655 ST_FUNC void free_inline_functions(TCCState *s)
6657 int i;
6658 /* free tokens of unused inline functions */
6659 for (i = 0; i < s->nb_inline_fns; ++i) {
6660 struct InlineFunc *fn = s->inline_fns[i];
6661 if (fn->sym)
6662 tok_str_free(fn->func_str);
6664 dynarray_reset(&s->inline_fns, &s->nb_inline_fns);
6667 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
6668 static int decl0(int l, int is_for_loop_init)
6670 int v, has_init, r;
6671 CType type, btype;
6672 Sym *sym;
6673 AttributeDef ad;
6675 while (1) {
6676 if (!parse_btype(&btype, &ad)) {
6677 if (is_for_loop_init)
6678 return 0;
6679 /* skip redundant ';' */
6680 /* XXX: find more elegant solution */
6681 if (tok == ';') {
6682 next();
6683 continue;
6685 if (l == VT_CONST &&
6686 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
6687 /* global asm block */
6688 asm_global_instr();
6689 continue;
6691 /* special test for old K&R protos without explicit int
6692 type. Only accepted when defining global data */
6693 if (l == VT_LOCAL || tok < TOK_UIDENT)
6694 break;
6695 btype.t = VT_INT;
6697 if (((btype.t & VT_BTYPE) == VT_ENUM ||
6698 (btype.t & VT_BTYPE) == VT_STRUCT) &&
6699 tok == ';') {
6700 if ((btype.t & VT_BTYPE) == VT_STRUCT) {
6701 int v = btype.ref->v;
6702 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) >= SYM_FIRST_ANOM)
6703 tcc_warning("unnamed struct/union that defines no instances");
6705 next();
6706 continue;
6708 while (1) { /* iterate thru each declaration */
6709 type = btype;
6710 /* If the base type itself was an array type of unspecified
6711 size (like in 'typedef int arr[]; arr x = {1};') then
6712 we will overwrite the unknown size by the real one for
6713 this decl. We need to unshare the ref symbol holding
6714 that size. */
6715 if ((type.t & VT_ARRAY) && type.ref->c < 0) {
6716 type.ref = sym_push(SYM_FIELD, &type.ref->type, 0, type.ref->c);
6718 type_decl(&type, &ad, &v, TYPE_DIRECT);
6719 #if 0
6721 char buf[500];
6722 type_to_str(buf, sizeof(buf), t, get_tok_str(v, NULL));
6723 printf("type = '%s'\n", buf);
6725 #endif
6726 if ((type.t & VT_BTYPE) == VT_FUNC) {
6727 if ((type.t & VT_STATIC) && (l == VT_LOCAL)) {
6728 tcc_error("function without file scope cannot be static");
6730 /* if old style function prototype, we accept a
6731 declaration list */
6732 sym = type.ref;
6733 if (sym->c == FUNC_OLD)
6734 func_decl_list(sym);
6737 if (gnu_ext && (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
6738 ad.asm_label = asm_label_instr();
6739 /* parse one last attribute list, after asm label */
6740 parse_attribute(&ad);
6741 if (tok == '{')
6742 expect(";");
6745 if (ad.a.weak)
6746 type.t |= VT_WEAK;
6747 #ifdef TCC_TARGET_PE
6748 if (ad.a.func_import)
6749 type.t |= VT_IMPORT;
6750 if (ad.a.func_export)
6751 type.t |= VT_EXPORT;
6752 #endif
6753 type.t |= ad.a.visibility << VT_VIS_SHIFT;
6755 if (tok == '{') {
6756 if (l == VT_LOCAL)
6757 tcc_error("cannot use local functions");
6758 if ((type.t & VT_BTYPE) != VT_FUNC)
6759 expect("function definition");
6761 /* reject abstract declarators in function definition */
6762 sym = type.ref;
6763 while ((sym = sym->next) != NULL)
6764 if (!(sym->v & ~SYM_FIELD))
6765 expect("identifier");
6767 /* XXX: cannot do better now: convert extern line to static inline */
6768 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
6769 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
6771 sym = sym_find(v);
6772 if (sym) {
6773 Sym *ref;
6774 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
6775 goto func_error1;
6777 ref = sym->type.ref;
6778 if (0 == ref->a.func_proto)
6779 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
6781 /* use func_call from prototype if not defined */
6782 if (ref->a.func_call != FUNC_CDECL
6783 && type.ref->a.func_call == FUNC_CDECL)
6784 type.ref->a.func_call = ref->a.func_call;
6786 /* use export from prototype */
6787 if (ref->a.func_export)
6788 type.ref->a.func_export = 1;
6790 /* use static from prototype */
6791 if (sym->type.t & VT_STATIC)
6792 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
6794 /* If the definition has no visibility use the
6795 one from prototype. */
6796 if (! (type.t & VT_VIS_MASK))
6797 type.t |= sym->type.t & VT_VIS_MASK;
6799 if (!is_compatible_types(&sym->type, &type)) {
6800 func_error1:
6801 tcc_error("incompatible types for redefinition of '%s'",
6802 get_tok_str(v, NULL));
6804 type.ref->a.func_proto = 0;
6805 /* if symbol is already defined, then put complete type */
6806 sym->type = type;
6807 } else {
6808 /* put function symbol */
6809 sym = global_identifier_push(v, type.t, 0);
6810 sym->type.ref = type.ref;
6813 /* static inline functions are just recorded as a kind
6814 of macro. Their code will be emitted at the end of
6815 the compilation unit only if they are used */
6816 if ((type.t & (VT_INLINE | VT_STATIC)) ==
6817 (VT_INLINE | VT_STATIC)) {
6818 int block_level;
6819 struct InlineFunc *fn;
6820 const char *filename;
6822 filename = file ? file->filename : "";
6823 fn = tcc_malloc(sizeof *fn + strlen(filename));
6824 strcpy(fn->filename, filename);
6825 fn->sym = sym;
6826 fn->func_str = tok_str_alloc();
6828 block_level = 0;
6829 for(;;) {
6830 int t;
6831 if (tok == TOK_EOF)
6832 tcc_error("unexpected end of file");
6833 tok_str_add_tok(fn->func_str);
6834 t = tok;
6835 next();
6836 if (t == '{') {
6837 block_level++;
6838 } else if (t == '}') {
6839 block_level--;
6840 if (block_level == 0)
6841 break;
6844 tok_str_add(fn->func_str, -1);
6845 tok_str_add(fn->func_str, 0);
6846 dynarray_add((void ***)&tcc_state->inline_fns, &tcc_state->nb_inline_fns, fn);
6848 } else {
6849 /* compute text section */
6850 cur_text_section = ad.section;
6851 if (!cur_text_section)
6852 cur_text_section = text_section;
6853 sym->r = VT_SYM | VT_CONST;
6854 gen_function(sym);
6856 break;
6857 } else {
6858 if (btype.t & VT_TYPEDEF) {
6859 /* save typedefed type */
6860 /* XXX: test storage specifiers ? */
6861 sym = sym_find(v);
6862 if (sym && sym->scope == local_scope) {
6863 if (!is_compatible_types(&sym->type, &type)
6864 || !(sym->type.t & VT_TYPEDEF))
6865 tcc_error("incompatible redefinition of '%s'",
6866 get_tok_str(v, NULL));
6867 sym->type = type;
6868 } else {
6869 sym = sym_push(v, &type, 0, 0);
6871 sym->a = ad.a;
6872 sym->type.t |= VT_TYPEDEF;
6873 } else {
6874 r = 0;
6875 if ((type.t & VT_BTYPE) == VT_FUNC) {
6876 /* external function definition */
6877 /* specific case for func_call attribute */
6878 ad.a.func_proto = 1;
6879 type.ref->a = ad.a;
6880 } else if (!(type.t & VT_ARRAY)) {
6881 /* not lvalue if array */
6882 r |= lvalue_type(type.t);
6884 has_init = (tok == '=');
6885 if (has_init && (type.t & VT_VLA))
6886 tcc_error("variable length array cannot be initialized");
6887 if ((btype.t & VT_EXTERN) || ((type.t & VT_BTYPE) == VT_FUNC) ||
6888 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
6889 !has_init && l == VT_CONST && type.ref->c < 0)) {
6890 /* external variable or function */
6891 /* NOTE: as GCC, uninitialized global static
6892 arrays of null size are considered as
6893 extern */
6894 sym = external_sym(v, &type, r);
6895 sym->asm_label = ad.asm_label;
6897 if (ad.alias_target) {
6898 Section tsec;
6899 Elf32_Sym *esym;
6900 Sym *alias_target;
6902 alias_target = sym_find(ad.alias_target);
6903 if (!alias_target || !alias_target->c)
6904 tcc_error("unsupported forward __alias__ attribute");
6905 esym = &((Elf32_Sym *)symtab_section->data)[alias_target->c];
6906 tsec.sh_num = esym->st_shndx;
6907 put_extern_sym2(sym, &tsec, esym->st_value, esym->st_size, 0);
6909 } else {
6910 type.t |= (btype.t & VT_STATIC); /* Retain "static". */
6911 if (type.t & VT_STATIC)
6912 r |= VT_CONST;
6913 else
6914 r |= l;
6915 if (has_init)
6916 next();
6917 decl_initializer_alloc(&type, &ad, r, has_init, v, l);
6920 if (tok != ',') {
6921 if (is_for_loop_init)
6922 return 1;
6923 skip(';');
6924 break;
6926 next();
6928 ad.a.aligned = 0;
6931 return 0;
6934 ST_FUNC void decl(int l)
6936 decl0(l, 0);
6939 /* ------------------------------------------------------------------------- */